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): static batching draws marked meshes that share a material as one mesh
yhh255c694f40e9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ac163d650..abe60fafa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **Static batching.** Static meshes that share a material can be drawn as one. Add `StaticBatch` to a mesh that will not move, and the meshes that share its material, texture, colour and layer are merged while the game runs into one mesh per area, so a level built from many different props costs a few draws instead of one per distinct mesh. The renderer already drew copies of the same mesh as one instanced draw; this is for different meshes. The marked entities stay as authored — scripts find them, colliders collide, the editor picks them — and only their drawing moves to the merged mesh. A mesh is left out, and the reason recorded, when it is skinned, morphing, a level-of-detail group, blended, moving (a dynamic body or a character), lit by a bake or a probe volume, or alone in its group. Merging copies each part's vertices, so it spends memory to save draws; `StaticBatching` reports each merged mesh's size and what drawing its parts cost before.- **Camera shots and nested sequences on the timeline.** Timelines have camera and sequence tracks. A camera track is a row of shots: each bar is the camera that is the view for its span, bars that touch cut, and a bar dragged over the previous one blends across the overlap with its own curve. A sequence track plays another timeline in a window of this one, on its own clock, with a speed, a loop, and a node to bind to so one sequence can play on different characters. A timeline cannot play itself, directly or through another, and nesting stops at four levels. The Sequencer shows both as bars above the object tracks, with the shot or clip in Details, and the viewport's camera preview follows the shot while you scrub. Which shot and which nested frame show is a function of time alone, so scrubbing, jumping and playing backwards agree.### Changeddiff --git a/fixtures/scenes/static-batch-off.esscene b/fixtures/scenes/static-batch-off.esscenenew file mode 100644index 000000000..f467c13c0--- /dev/null+++ b/fixtures/scenes/static-batch-off.esscene@@ -0,0 +1,834 @@+{+ "version": 4,+ "name": "static-batch-off",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 800,+ "y": 800,+ "z": 300+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 150,+ "isActive": true,+ "priority": 0+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "cube1",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 680,+ "y": 890,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 2,+ "name": "cube2",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 680,+ "y": 830,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 3,+ "name": "cube3",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 680,+ "y": 770,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 4,+ "name": "cube4",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 680,+ "y": 710,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 5,+ "name": "sphere1",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 740,+ "y": 890,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:sphere",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 6,+ "name": "sphere2",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 740,+ "y": 830,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:sphere",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 7,+ "name": "sphere3",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 740,+ "y": 770,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:sphere",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 8,+ "name": "sphere4",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 740,+ "y": 710,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:sphere",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 9,+ "name": "capsule1",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 800,+ "y": 890,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:capsule",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 10,+ "name": "capsule2",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 800,+ "y": 830,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:capsule",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 11,+ "name": "capsule3",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 800,+ "y": 770,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:capsule",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 12,+ "name": "capsule4",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 800,+ "y": 710,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:capsule",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 13,+ "name": "cylinder1",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 860,+ "y": 890,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cylinder",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 14,+ "name": "cylinder2",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 860,+ "y": 830,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cylinder",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 15,+ "name": "cylinder3",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 860,+ "y": 770,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cylinder",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 16,+ "name": "cylinder4",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 860,+ "y": 710,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cylinder",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 17,+ "name": "cone1",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 920,+ "y": 890,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cone",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 18,+ "name": "cone2",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 920,+ "y": 830,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cone",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 19,+ "name": "cone3",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 920,+ "y": 770,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cone",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 20,+ "name": "cone4",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 920,+ "y": 710,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cone",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/fixtures/scenes/static-batch-on.esscene b/fixtures/scenes/static-batch-on.esscenenew file mode 100644index 000000000..f31f38bb1--- /dev/null+++ b/fixtures/scenes/static-batch-on.esscene@@ -0,0 +1,954 @@+{+ "version": 4,+ "name": "static-batch-on",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 800,+ "y": 800,+ "z": 300+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 150,+ "isActive": true,+ "priority": 0+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "cube1",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 680,+ "y": 890,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 2,+ "name": "cube2",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 680,+ "y": 830,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 3,+ "name": "cube3",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 680,+ "y": 770,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 4,+ "name": "cube4",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 680,+ "y": 710,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 5,+ "name": "sphere1",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 740,+ "y": 890,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:sphere",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 6,+ "name": "sphere2",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 740,+ "y": 830,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:sphere",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 7,+ "name": "sphere3",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 740,+ "y": 770,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:sphere",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 8,+ "name": "sphere4",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 740,+ "y": 710,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:sphere",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 9,+ "name": "capsule1",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 800,+ "y": 890,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:capsule",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 10,+ "name": "capsule2",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 800,+ "y": 830,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:capsule",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 11,+ "name": "capsule3",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 800,+ "y": 770,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:capsule",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 12,+ "name": "capsule4",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 800,+ "y": 710,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:capsule",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 13,+ "name": "cylinder1",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 860,+ "y": 890,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cylinder",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 14,+ "name": "cylinder2",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 860,+ "y": 830,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cylinder",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 15,+ "name": "cylinder3",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 860,+ "y": 770,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cylinder",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 16,+ "name": "cylinder4",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 860,+ "y": 710,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cylinder",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 17,+ "name": "cone1",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 920,+ "y": 890,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cone",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 18,+ "name": "cone2",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 920,+ "y": 830,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cone",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 19,+ "name": "cone3",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 920,+ "y": 770,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cone",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ },+ {+ "id": 20,+ "name": "cone4",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 920,+ "y": 710,+ "z": 0+ },+ "scale": {+ "x": 0.35,+ "y": 0.35,+ "z": 0.35+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cone",+ "color": {+ "r": 1,+ "g": 0,+ "b": 0,+ "a": 1+ },+ "lit": false,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ },+ {+ "type": "StaticBatch",+ "data": {+ "group": ""+ }+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 43a46520c..60fb0d70d 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 · 152 beta · 1636 experimental · 3 deprecated+Symbols: 115 public · 152 beta · 1649 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1007,6 +1007,7 @@ baseUrl: string | undefinedcatalog: CatalogcheckForUpdate: (options: CheckForUpdateOptions) => Promise<UpdatePlan>cleanDiskCache: (budgetBytes: number, execute?: boolean) => Promise<CacheCleanupResult>+createMesh: (data: MeshData) => numberdiskCacheReport: (rescan?: boolean) => Promise<ContentCacheReport>fetchBinary: (ref: string) => Promise<ArrayBuffer>fetchJson: <T = unknown>(ref: string) => Promise<T>@@ -1045,12 +1046,14 @@ pathForHandle: (kind: string, handle: number) => string | nullpathForRenderedTexture: (renderId: number) => string | nullpreload: (refs: ReadonlyArray<string>, onProgress?: (loaded: number, total: number) => void, options?: { readonly maxConcurrent?: number; }) => Promise<{ failed: MissingAsset[]; }>preloadSceneAssets: (sceneData: SceneData, onProgress?: (loaded: number, total: number) => void, options?: { readonly maxConcurrent?: number; readonly skipSpine?: boolean; }) => Promise<SceneAssetResult>+readMeshData: (handle: number) => Promise<MeshData | null>recoverFromDeviceLoss: () => Promise<boolean>register: <T>(loader: AssetLoader<T>) => voidreleaseAll: () => voidreleaseAnimClip: (ref: string) => voidreleaseAssets: (byType: ReadonlyMap<string, ReadonlySet<string>>) => voidreleaseAudio: (ref: string) => void+releaseBuiltMesh: (handle: number) => voidreleaseFont: (ref: string) => voidreleaseGroup: (groupName: string) => voidreleaseMaterial: (handle: number) => void@@ -7551,6 +7554,11 @@ readonly SpineVersion[]"/"```+## STATIC_BATCH_DEFAULTS — const @experimental+```+StaticBatchLimits+```+## SafeArea — const @experimental```ComponentDef<SafeAreaData>@@ -8800,6 +8808,92 @@ reason: stringsite: "variant" | "nested" | "instance"```+## StaticBatch — const @experimental+```+ComponentDef<StaticBatchData>+```++## StaticBatchData — interface @experimental+```+group: string+```++## StaticBatchGroup — interface @experimental+```+bytes: number+drawsBefore: number+entity: number+parts: number[]+triangles: number+vertices: number+```++## StaticBatchLimits — interface @experimental+```+cellSize: number+maxVertices: number+```++## StaticBatchPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): StaticBatchPlugin+static prototype: StaticBatchPlugin+```++## StaticBatchRefusal — type @experimental+```+| 'no-mesh'+ /** Posed by a skeleton: one draw can only be in one pose. */+ | 'skinned'+ /** Carries blend shapes: one draw can only be in one shape. */+ | 'morph'+ /** Chooses among levels of detail at run time, which a merged mesh cannot. */+ | 'lod'+ /** Lit by a bake: its atlas patch belongs to the object, not to the batch. */+ | 'baked'+ /** Blended: its result depends on order, and merging is the loss of order. */+ | 'blended'+ /** Moves (a dynamic body or a character): a static batch bakes where it stands. */+ | 'moves'+ /** Switched off, so there is nothing to draw. */+ | 'disabled'+ /** Vertex layout the merge cannot transform (positions or normals not float). */+ | 'layout'+ /** The only member of its group: merging it would cost memory and save nothing. */+ | 'alone'+```++## StaticBatchReport — interface @experimental+```+groups: StaticBatchGroup[]+refused: Map<number, StaticBatchRefusal>+```++## StaticBatching — class @experimental+```+@internal busy_: boolean+@internal dirty_: boolean+@internal groups_: StaticBatchGroupState[]+@internal pending_: number+@internal refused_: Map<number, StaticBatchRefusal>+@internal seen_: Set<number>+@internal stable_: number+limits: StaticBatchLimits+pending: number+rebuild: () => void+report: () => StaticBatchReport+static new (): StaticBatching+static prototype: StaticBatching+```++## StaticBatchingRes — const @experimental+```+ResourceDef<StaticBatching>+```+## Stats — const @experimental```ResourceDef<FrameStats>@@ -12823,6 +12917,11 @@ Logger(text: string, opts: MeasureTextOptions): TextMetrics```+## mergeMeshes — function @experimental+```+(parts: readonly BatchPart[]): MeshData+```+## meshRendererPlugin — const @experimental```MeshRendererPlugin@@ -13068,6 +13167,11 @@ ParticlePlugin(lines: Vec3[][], position: Vec3, rotation: Quat): Vec3[][]```+## planStaticBatches — function @experimental+```+(candidates: readonly StaticBatchCandidate[], limits?: StaticBatchLimits): StaticBatchPlan+```+## planarReflectionStatus — function @experimental```(app: App, entity: Entity, view?: Entity): PlanarReflectionStatus@@ -13973,6 +14077,11 @@ MotionDriver<AnimatorClipMotion>(config: DebugChannelConfig): void```+## staticBatchPlugin — const @experimental+```+Plugin+```+## statsPlugin — const @experimental```StatsPlugindiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 81fa8e944..892ff34aa 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 · 157 beta · 1655 experimental · 3 deprecated+Symbols: 115 public · 157 beta · 1668 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1007,6 +1007,7 @@ baseUrl: string | undefinedcatalog: CatalogcheckForUpdate: (options: CheckForUpdateOptions) => Promise<UpdatePlan>cleanDiskCache: (budgetBytes: number, execute?: boolean) => Promise<CacheCleanupResult>+createMesh: (data: MeshData) => numberdiskCacheReport: (rescan?: boolean) => Promise<ContentCacheReport>fetchBinary: (ref: string) => Promise<ArrayBuffer>fetchJson: <T = unknown>(ref: string) => Promise<T>@@ -1045,12 +1046,14 @@ pathForHandle: (kind: string, handle: number) => string | nullpathForRenderedTexture: (renderId: number) => string | nullpreload: (refs: ReadonlyArray<string>, onProgress?: (loaded: number, total: number) => void, options?: { readonly maxConcurrent?: number; }) => Promise<{ failed: MissingAsset[]; }>preloadSceneAssets: (sceneData: SceneData, onProgress?: (loaded: number, total: number) => void, options?: { readonly maxConcurrent?: number; readonly skipSpine?: boolean; }) => Promise<SceneAssetResult>+readMeshData: (handle: number) => Promise<MeshData | null>recoverFromDeviceLoss: () => Promise<boolean>register: <T>(loader: AssetLoader<T>) => voidreleaseAll: () => voidreleaseAnimClip: (ref: string) => voidreleaseAssets: (byType: ReadonlyMap<string, ReadonlySet<string>>) => voidreleaseAudio: (ref: string) => void+releaseBuiltMesh: (handle: number) => voidreleaseFont: (ref: string) => voidreleaseGroup: (groupName: string) => voidreleaseMaterial: (handle: number) => void@@ -7764,6 +7767,11 @@ readonly SpineVersion[]"/"```+## STATIC_BATCH_DEFAULTS — const @experimental+```+StaticBatchLimits+```+## SafeArea — const @experimental```ComponentDef<SafeAreaData>@@ -9013,6 +9021,92 @@ reason: stringsite: "variant" | "nested" | "instance"```+## StaticBatch — const @experimental+```+ComponentDef<StaticBatchData>+```++## StaticBatchData — interface @experimental+```+group: string+```++## StaticBatchGroup — interface @experimental+```+bytes: number+drawsBefore: number+entity: number+parts: number[]+triangles: number+vertices: number+```++## StaticBatchLimits — interface @experimental+```+cellSize: number+maxVertices: number+```++## StaticBatchPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): StaticBatchPlugin+static prototype: StaticBatchPlugin+```++## StaticBatchRefusal — type @experimental+```+| 'no-mesh'+ /** Posed by a skeleton: one draw can only be in one pose. */+ | 'skinned'+ /** Carries blend shapes: one draw can only be in one shape. */+ | 'morph'+ /** Chooses among levels of detail at run time, which a merged mesh cannot. */+ | 'lod'+ /** Lit by a bake: its atlas patch belongs to the object, not to the batch. */+ | 'baked'+ /** Blended: its result depends on order, and merging is the loss of order. */+ | 'blended'+ /** Moves (a dynamic body or a character): a static batch bakes where it stands. */+ | 'moves'+ /** Switched off, so there is nothing to draw. */+ | 'disabled'+ /** Vertex layout the merge cannot transform (positions or normals not float). */+ | 'layout'+ /** The only member of its group: merging it would cost memory and save nothing. */+ | 'alone'+```++## StaticBatchReport — interface @experimental+```+groups: StaticBatchGroup[]+refused: Map<number, StaticBatchRefusal>+```++## StaticBatching — class @experimental+```+@internal busy_: boolean+@internal dirty_: boolean+@internal groups_: StaticBatchGroupState[]+@internal pending_: number+@internal refused_: Map<number, StaticBatchRefusal>+@internal seen_: Set<number>+@internal stable_: number+limits: StaticBatchLimits+pending: number+rebuild: () => void+report: () => StaticBatchReport+static new (): StaticBatching+static prototype: StaticBatching+```++## StaticBatchingRes — const @experimental+```+ResourceDef<StaticBatching>+```+## Stats — const @experimental```ResourceDef<FrameStats>@@ -13086,6 +13180,11 @@ Logger(text: string, opts: MeasureTextOptions): TextMetrics```+## mergeMeshes — function @experimental+```+(parts: readonly BatchPart[]): MeshData+```+## meshRendererPlugin — const @experimental```MeshRendererPlugin@@ -13331,6 +13430,11 @@ ParticlePlugin(lines: Vec3[][], position: Vec3, rotation: Quat): Vec3[][]```+## planStaticBatches — function @experimental+```+(candidates: readonly StaticBatchCandidate[], limits?: StaticBatchLimits): StaticBatchPlan+```+## planarReflectionStatus — function @experimental```(app: App, entity: Entity, view?: Entity): PlanarReflectionStatus@@ -14236,6 +14340,11 @@ MotionDriver<AnimatorClipMotion>(config: DebugChannelConfig): void```+## staticBatchPlugin — const @experimental+```+Plugin+```+## statsPlugin — const @experimental```StatsPlugindiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 04f0a969b..878495e5d 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 · 154 beta · 1635 experimental · 3 deprecated+Symbols: 115 public · 154 beta · 1648 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1002,6 +1002,7 @@ baseUrl: string | undefinedcatalog: CatalogcheckForUpdate: (options: CheckForUpdateOptions) => Promise<UpdatePlan>cleanDiskCache: (budgetBytes: number, execute?: boolean) => Promise<CacheCleanupResult>+createMesh: (data: MeshData) => numberdiskCacheReport: (rescan?: boolean) => Promise<ContentCacheReport>fetchBinary: (ref: string) => Promise<ArrayBuffer>fetchJson: <T = unknown>(ref: string) => Promise<T>@@ -1040,12 +1041,14 @@ pathForHandle: (kind: string, handle: number) => string | nullpathForRenderedTexture: (renderId: number) => string | nullpreload: (refs: ReadonlyArray<string>, onProgress?: (loaded: number, total: number) => void, options?: { readonly maxConcurrent?: number; }) => Promise<{ failed: MissingAsset[]; }>preloadSceneAssets: (sceneData: SceneData, onProgress?: (loaded: number, total: number) => void, options?: { readonly maxConcurrent?: number; readonly skipSpine?: boolean; }) => Promise<SceneAssetResult>+readMeshData: (handle: number) => Promise<MeshData | null>recoverFromDeviceLoss: () => Promise<boolean>register: <T>(loader: AssetLoader<T>) => voidreleaseAll: () => voidreleaseAnimClip: (ref: string) => voidreleaseAssets: (byType: ReadonlyMap<string, ReadonlySet<string>>) => voidreleaseAudio: (ref: string) => void+releaseBuiltMesh: (handle: number) => voidreleaseFont: (ref: string) => voidreleaseGroup: (groupName: string) => voidreleaseMaterial: (handle: number) => void@@ -7546,6 +7549,11 @@ readonly SpineVersion[]"/"```+## STATIC_BATCH_DEFAULTS — const @experimental+```+StaticBatchLimits+```+## SafeArea — const @experimental```ComponentDef<SafeAreaData>@@ -8795,6 +8803,92 @@ reason: stringsite: "variant" | "nested" | "instance"```+## StaticBatch — const @experimental+```+ComponentDef<StaticBatchData>+```++## StaticBatchData — interface @experimental+```+group: string+```++## StaticBatchGroup — interface @experimental+```+bytes: number+drawsBefore: number+entity: number+parts: number[]+triangles: number+vertices: number+```++## StaticBatchLimits — interface @experimental+```+cellSize: number+maxVertices: number+```++## StaticBatchPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): StaticBatchPlugin+static prototype: StaticBatchPlugin+```++## StaticBatchRefusal — type @experimental+```+| 'no-mesh'+ /** Posed by a skeleton: one draw can only be in one pose. */+ | 'skinned'+ /** Carries blend shapes: one draw can only be in one shape. */+ | 'morph'+ /** Chooses among levels of detail at run time, which a merged mesh cannot. */+ | 'lod'+ /** Lit by a bake: its atlas patch belongs to the object, not to the batch. */+ | 'baked'+ /** Blended: its result depends on order, and merging is the loss of order. */+ | 'blended'+ /** Moves (a dynamic body or a character): a static batch bakes where it stands. */+ | 'moves'+ /** Switched off, so there is nothing to draw. */+ | 'disabled'+ /** Vertex layout the merge cannot transform (positions or normals not float). */+ | 'layout'+ /** The only member of its group: merging it would cost memory and save nothing. */+ | 'alone'+```++## StaticBatchReport — interface @experimental+```+groups: StaticBatchGroup[]+refused: Map<number, StaticBatchRefusal>+```++## StaticBatching — class @experimental+```+@internal busy_: boolean+@internal dirty_: boolean+@internal groups_: StaticBatchGroupState[]+@internal pending_: number+@internal refused_: Map<number, StaticBatchRefusal>+@internal seen_: Set<number>+@internal stable_: number+limits: StaticBatchLimits+pending: number+rebuild: () => void+report: () => StaticBatchReport+static new (): StaticBatching+static prototype: StaticBatching+```++## StaticBatchingRes — const @experimental+```+ResourceDef<StaticBatching>+```+## Stats — const @experimental```ResourceDef<FrameStats>@@ -12823,6 +12917,11 @@ Logger(text: string, opts: MeasureTextOptions): TextMetrics```+## mergeMeshes — function @experimental+```+(parts: readonly BatchPart[]): MeshData+```+## meshRendererPlugin — const @experimental```MeshRendererPlugin@@ -13073,6 +13172,11 @@ ParticlePlugin(lines: Vec3[][], position: Vec3, rotation: Quat): Vec3[][]```+## planStaticBatches — function @experimental+```+(candidates: readonly StaticBatchCandidate[], limits?: StaticBatchLimits): StaticBatchPlan+```+## planarReflectionStatus — function @experimental```(app: App, entity: Entity, view?: Entity): PlanarReflectionStatus@@ -13978,6 +14082,11 @@ MotionDriver<AnimatorClipMotion>(config: DebugChannelConfig): void```+## staticBatchPlugin — const @experimental+```+Plugin+```+## statsPlugin — const @experimental```StatsPlugindiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex a1a6fa9cb..d503001b6 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 · 152 beta · 1657 experimental · 3 deprecated+Symbols: 115 public · 152 beta · 1670 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1002,6 +1002,7 @@ baseUrl: string | undefinedcatalog: CatalogcheckForUpdate: (options: CheckForUpdateOptions) => Promise<UpdatePlan>cleanDiskCache: (budgetBytes: number, execute?: boolean) => Promise<CacheCleanupResult>+createMesh: (data: MeshData) => numberdiskCacheReport: (rescan?: boolean) => Promise<ContentCacheReport>fetchBinary: (ref: string) => Promise<ArrayBuffer>fetchJson: <T = unknown>(ref: string) => Promise<T>@@ -1040,12 +1041,14 @@ pathForHandle: (kind: string, handle: number) => string | nullpathForRenderedTexture: (renderId: number) => string | nullpreload: (refs: ReadonlyArray<string>, onProgress?: (loaded: number, total: number) => void, options?: { readonly maxConcurrent?: number; }) => Promise<{ failed: MissingAsset[]; }>preloadSceneAssets: (sceneData: SceneData, onProgress?: (loaded: number, total: number) => void, options?: { readonly maxConcurrent?: number; readonly skipSpine?: boolean; }) => Promise<SceneAssetResult>+readMeshData: (handle: number) => Promise<MeshData | null>recoverFromDeviceLoss: () => Promise<boolean>register: <T>(loader: AssetLoader<T>) => voidreleaseAll: () => voidreleaseAnimClip: (ref: string) => voidreleaseAssets: (byType: ReadonlyMap<string, ReadonlySet<string>>) => voidreleaseAudio: (ref: string) => void+releaseBuiltMesh: (handle: number) => voidreleaseFont: (ref: string) => voidreleaseGroup: (groupName: string) => voidreleaseMaterial: (handle: number) => void@@ -7839,6 +7842,11 @@ readonly SpineVersion[]"/"```+## STATIC_BATCH_DEFAULTS — const @experimental+```+StaticBatchLimits+```+## SafeArea — const @experimental```ComponentDef<SafeAreaData>@@ -9088,6 +9096,92 @@ reason: stringsite: "variant" | "nested" | "instance"```+## StaticBatch — const @experimental+```+ComponentDef<StaticBatchData>+```++## StaticBatchData — interface @experimental+```+group: string+```++## StaticBatchGroup — interface @experimental+```+bytes: number+drawsBefore: number+entity: number+parts: number[]+triangles: number+vertices: number+```++## StaticBatchLimits — interface @experimental+```+cellSize: number+maxVertices: number+```++## StaticBatchPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): StaticBatchPlugin+static prototype: StaticBatchPlugin+```++## StaticBatchRefusal — type @experimental+```+| 'no-mesh'+ /** Posed by a skeleton: one draw can only be in one pose. */+ | 'skinned'+ /** Carries blend shapes: one draw can only be in one shape. */+ | 'morph'+ /** Chooses among levels of detail at run time, which a merged mesh cannot. */+ | 'lod'+ /** Lit by a bake: its atlas patch belongs to the object, not to the batch. */+ | 'baked'+ /** Blended: its result depends on order, and merging is the loss of order. */+ | 'blended'+ /** Moves (a dynamic body or a character): a static batch bakes where it stands. */+ | 'moves'+ /** Switched off, so there is nothing to draw. */+ | 'disabled'+ /** Vertex layout the merge cannot transform (positions or normals not float). */+ | 'layout'+ /** The only member of its group: merging it would cost memory and save nothing. */+ | 'alone'+```++## StaticBatchReport — interface @experimental+```+groups: StaticBatchGroup[]+refused: Map<number, StaticBatchRefusal>+```++## StaticBatching — class @experimental+```+@internal busy_: boolean+@internal dirty_: boolean+@internal groups_: StaticBatchGroupState[]+@internal pending_: number+@internal refused_: Map<number, StaticBatchRefusal>+@internal seen_: Set<number>+@internal stable_: number+limits: StaticBatchLimits+pending: number+rebuild: () => void+report: () => StaticBatchReport+static new (): StaticBatching+static prototype: StaticBatching+```++## StaticBatchingRes — const @experimental+```+ResourceDef<StaticBatching>+```+## Stats — const @experimental```ResourceDef<FrameStats>@@ -13132,6 +13226,11 @@ Logger(text: string, opts: MeasureTextOptions): TextMetrics```+## mergeMeshes — function @experimental+```+(parts: readonly BatchPart[]): MeshData+```+## meshRendererPlugin — const @experimental```MeshRendererPlugin@@ -13377,6 +13476,11 @@ ParticlePlugin(lines: Vec3[][], position: Vec3, rotation: Quat): Vec3[][]```+## planStaticBatches — function @experimental+```+(candidates: readonly StaticBatchCandidate[], limits?: StaticBatchLimits): StaticBatchPlan+```+## planarReflectionStatus — function @experimental```(app: App, entity: Entity, view?: Entity): PlanarReflectionStatus@@ -14282,6 +14386,11 @@ MotionDriver<AnimatorClipMotion>(config: DebugChannelConfig): void```+## staticBatchPlugin — const @experimental+```+Plugin+```+## statsPlugin — const @experimental```StatsPlugindiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 30ffa3f7f..72d5efe5b 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 · 152 beta · 1648 experimental · 3 deprecated+Symbols: 115 public · 152 beta · 1661 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1002,6 +1002,7 @@ baseUrl: string | undefinedcatalog: CatalogcheckForUpdate: (options: CheckForUpdateOptions) => Promise<UpdatePlan>cleanDiskCache: (budgetBytes: number, execute?: boolean) => Promise<CacheCleanupResult>+createMesh: (data: MeshData) => numberdiskCacheReport: (rescan?: boolean) => Promise<ContentCacheReport>fetchBinary: (ref: string) => Promise<ArrayBuffer>fetchJson: <T = unknown>(ref: string) => Promise<T>@@ -1040,12 +1041,14 @@ pathForHandle: (kind: string, handle: number) => string | nullpathForRenderedTexture: (renderId: number) => string | nullpreload: (refs: ReadonlyArray<string>, onProgress?: (loaded: number, total: number) => void, options?: { readonly maxConcurrent?: number; }) => Promise<{ failed: MissingAsset[]; }>preloadSceneAssets: (sceneData: SceneData, onProgress?: (loaded: number, total: number) => void, options?: { readonly maxConcurrent?: number; readonly skipSpine?: boolean; }) => Promise<SceneAssetResult>+readMeshData: (handle: number) => Promise<MeshData | null>recoverFromDeviceLoss: () => Promise<boolean>register: <T>(loader: AssetLoader<T>) => voidreleaseAll: () => voidreleaseAnimClip: (ref: string) => voidreleaseAssets: (byType: ReadonlyMap<string, ReadonlySet<string>>) => voidreleaseAudio: (ref: string) => void+releaseBuiltMesh: (handle: number) => voidreleaseFont: (ref: string) => voidreleaseGroup: (groupName: string) => voidreleaseMaterial: (handle: number) => void@@ -7553,6 +7556,11 @@ readonly SpineVersion[]"/"```+## STATIC_BATCH_DEFAULTS — const @experimental+```+StaticBatchLimits+```+## SafeArea — const @experimental```ComponentDef<SafeAreaData>@@ -8802,6 +8810,92 @@ reason: stringsite: "variant" | "nested" | "instance"```+## StaticBatch — const @experimental+```+ComponentDef<StaticBatchData>+```++## StaticBatchData — interface @experimental+```+group: string+```++## StaticBatchGroup — interface @experimental+```+bytes: number+drawsBefore: number+entity: number+parts: number[]+triangles: number+vertices: number+```++## StaticBatchLimits — interface @experimental+```+cellSize: number+maxVertices: number+```++## StaticBatchPlugin — class @experimental+```+build: (app: App) => void+cleanup: (app?: App) => void+name: string+static new (): StaticBatchPlugin+static prototype: StaticBatchPlugin+```++## StaticBatchRefusal — type @experimental+```+| 'no-mesh'+ /** Posed by a skeleton: one draw can only be in one pose. */+ | 'skinned'+ /** Carries blend shapes: one draw can only be in one shape. */+ | 'morph'+ /** Chooses among levels of detail at run time, which a merged mesh cannot. */+ | 'lod'+ /** Lit by a bake: its atlas patch belongs to the object, not to the batch. */+ | 'baked'+ /** Blended: its result depends on order, and merging is the loss of order. */+ | 'blended'+ /** Moves (a dynamic body or a character): a static batch bakes where it stands. */+ | 'moves'+ /** Switched off, so there is nothing to draw. */+ | 'disabled'+ /** Vertex layout the merge cannot transform (positions or normals not float). */+ | 'layout'+ /** The only member of its group: merging it would cost memory and save nothing. */+ | 'alone'+```++## StaticBatchReport — interface @experimental+```+groups: StaticBatchGroup[]+refused: Map<number, StaticBatchRefusal>+```++## StaticBatching — class @experimental+```+@internal busy_: boolean+@internal dirty_: boolean+@internal groups_: StaticBatchGroupState[]+@internal pending_: number+@internal refused_: Map<number, StaticBatchRefusal>+@internal seen_: Set<number>+@internal stable_: number+limits: StaticBatchLimits+pending: number+rebuild: () => void+report: () => StaticBatchReport+static new (): StaticBatching+static prototype: StaticBatching+```++## StaticBatchingRes — const @experimental+```+ResourceDef<StaticBatching>+```+## Stats — const @experimental```ResourceDef<FrameStats>@@ -12859,6 +12953,11 @@ Logger(text: string, opts: MeasureTextOptions): TextMetrics```+## mergeMeshes — function @experimental+```+(parts: readonly BatchPart[]): MeshData+```+## meshRendererPlugin — const @experimental```MeshRendererPlugin@@ -13104,6 +13203,11 @@ ParticlePlugin(lines: Vec3[][], position: Vec3, rotation: Quat): Vec3[][]```+## planStaticBatches — function @experimental+```+(candidates: readonly StaticBatchCandidate[], limits?: StaticBatchLimits): StaticBatchPlan+```+## planarReflectionStatus — function @experimental```(app: App, entity: Entity, view?: Entity): PlanarReflectionStatus@@ -14009,6 +14113,11 @@ MotionDriver<AnimatorClipMotion>(config: DebugChannelConfig): void```+## staticBatchPlugin — const @experimental+```+Plugin+```+## statsPlugin — const @experimental```StatsPlugindiff --git a/sdk/src/app/pluginSets.ts b/sdk/src/app/pluginSets.tsindex 356f2edc3..a77ef8668 100644--- a/sdk/src/app/pluginSets.ts+++ b/sdk/src/app/pluginSets.ts@@ -27,6 +27,7 @@ import { videoPlugin } from '../video';import { particlePlugin } from '../particle';import { trailPlugin } from '../trail';import { meshRendererPlugin } from '../render/meshRenderer';+import { staticBatchPlugin } from '../render/staticBatchPlugin';import { postProcessPlugin } from '../postprocess';import { timelinePlugin } from '../timeline';import { timerPlugin } from '../ecs/timer';@@ -56,7 +57,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, meshRendererPlugin,+ animationPlugin, videoPlugin, particlePlugin, trailPlugin, meshRendererPlugin, staticBatchPlugin,postProcessPlugin, timelinePlugin,];@@ -67,7 +68,7 @@ export const presentationBasePlugins = (): Plugin[] => [*/export const PLUGIN_BUILD_ORDER: readonly string[] = ['Diagnostics', 'timer', 'velocity', 'lifecycle', 'animation', 'audio', 'video',- 'particle', 'trail', 'meshRenderer', 'tilemap', 'postProcess', 'timeline',+ 'particle', 'trail', 'meshRenderer', 'staticBatch', 'tilemap', 'postProcess', 'timeline','gameplay','perception', 'fsm', 'bt', 'scriptGraph', 'nav', 'eventBinding', 'replication','services',@@ -93,7 +94,7 @@ export function inBuildOrder(plugins: readonly Plugin[]): Plugin[] {export const webBasePlugins = (): Plugin[] => [diagnosticsPlugin,timerPlugin, velocityPlugin, lifecyclePlugin, animationPlugin, audioPlugin, videoPlugin,- particlePlugin, trailPlugin, meshRendererPlugin, postProcessPlugin, timelinePlugin,+ particlePlugin, trailPlugin, meshRendererPlugin, staticBatchPlugin, postProcessPlugin, timelinePlugin,eventBindingPlugin,servicesPlugin,];diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 2054ff08a..ad3412cfa 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -36,6 +36,7 @@ import { MaterialAssetLoader } from './loaders/MaterialAssetLoader';import { MaterialShaderAssetLoader } from './loaders/MaterialShaderAssetLoader';import { isBuiltinAssetRef } from './documentRef';import { MeshAssetLoader, type MeshResult } from './loaders/MeshAssetLoader';+import type { MeshData } from './meshFormat';import { nativeEngineApi, type EngineApi } from '../ecs/bridge/engineApi';import { isBuiltinMeshRef } from './builtinMeshes';import { EnvironmentAssetLoader } from './loaders/EnvironmentAssetLoader';@@ -477,6 +478,12 @@ export class Assets {* live World handle use it to name the asset (see {@link pathForHandle}). */private handleToPath_ = new Map<string, string>();+ /**+ * Geometry built at run time rather than loaded (a static batch), by handle. It has no file to be replayed+ * from, so the data itself is kept: a device loss puts it back from here.+ */+ private builtMeshes_ = new Map<number, MeshData>();+private constructor(options: AssetsOptions) {this.backend = options.backend && packedBackend(options.backend, () => this.manifestModel_);this.catalog = options.catalog ?? Catalog.empty();@@ -616,6 +623,12 @@ export class Assets {let restored = 0;for (const handle of this.meshesAwaitingRematerialization()) {+ const built = this.builtMeshes_.get(handle);+ if (built) {+ if (loader.uploadData(built, handle) !== 0) restored++;+ else log.error('assets', `Device recovery: the engine refused built geometry ${handle}`);+ continue;+ }const path = this.pathForHandle('mesh', handle);if (!path) {log.error('assets', `Device recovery: mesh ${handle} is declared replayable and`@@ -651,6 +664,35 @@ export class Assets {return whole;}+ /** The decoded geometry behind a mesh handle this realm loaded, or null when nothing here can name it. */+ async readMeshData(handle: number): Promise<MeshData | null> {+ const loader = this.getLoader<MeshResult>('mesh');+ const path = this.pathForHandle('mesh', handle);+ if (!(loader instanceof MeshAssetLoader) || !path) return null;+ try {+ return await loader.readSource(path, this.getLoadContext_());+ } catch (e) {+ log.warn('assets', `Reading the geometry of ${path} failed`, e);+ return null;+ }+ }++ /** Uploads geometry built at run time. Returns its handle, or 0 when the engine refused it. */+ createMesh(data: MeshData): number {+ const loader = this.getLoader<MeshResult>('mesh');+ if (!(loader instanceof MeshAssetLoader)) return 0;+ const handle = loader.uploadData(data);+ if (handle !== 0) this.builtMeshes_.set(handle, data);+ return handle;+ }++ /** Gives back geometry {@link createMesh} made. */+ releaseBuiltMesh(handle: number): void {+ if (!this.builtMeshes_.delete(handle)) return;+ const loader = this.getLoader<MeshResult>('mesh');+ if (loader instanceof MeshAssetLoader) loader.releaseData(handle);+ }+private async loadTextureVariant_(ref: string, flip: boolean): Promise<TextureResult> {return (await this.acquireTextureVariant_(ref, flip)).result;}@@ -2441,6 +2483,9 @@ export class Assets {},], dispose => dispose());} finally {+ const meshLoader = this.getLoader<MeshResult>('mesh');+ if (meshLoader instanceof MeshAssetLoader) for (const handle of this.builtMeshes_.keys()) meshLoader.releaseData(handle);+ this.builtMeshes_.clear();this.handleToPath_.clear();this.releasing_ = false;}diff --git a/sdk/src/asset/loaders/MeshAssetLoader.ts b/sdk/src/asset/loaders/MeshAssetLoader.tsindex 9ba78cffa..e3be1b433 100644--- a/sdk/src/asset/loaders/MeshAssetLoader.ts+++ b/sdk/src/asset/loaders/MeshAssetLoader.ts@@ -53,6 +53,16 @@ export class MeshAssetLoader implements AssetLoader<MeshResult> {return this.upload_(await this.decode_(path, ctx), handle) !== 0;}+ /** The decoded source behind a mesh path — what a tool that rebuilds geometry (a static batch) starts from. */+ readSource(path: string, ctx: LoadContext): Promise<MeshData> {+ return this.decode_(path, ctx);+ }++ /** Uploads geometry that has no file under it; `target` 0 mints a handle, otherwise the existing one is re-realized. */+ uploadData(mesh: MeshData, target = 0): number {+ return this.upload_(mesh, target);+ }+private async decode_(path: string, ctx: LoadContext): Promise<MeshData> {const builtin = isBuiltinMeshRef(path) ? builtinMeshTemplate(path) : undefined;return builtin@@ -120,6 +130,11 @@ export class MeshAssetLoader implements AssetLoader<MeshResult> {});}+ /** Gives back a handle {@link uploadData} minted. */+ releaseData(handle: number): void {+ this.core_()?.mesh_release?.(handle);+ }+unload(asset: MeshResult): void {releaseMeshCollision(asset.handle);this.core_()?.mesh_release?.(asset.handle);diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 76274ee84..abbc156c8 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -775,6 +775,14 @@ export {MeshRendererPlugin,meshRendererPlugin,} from './render/meshRenderer';+export {+ StaticBatch, StaticBatching, StaticBatchingRes, StaticBatchPlugin, staticBatchPlugin,+ type StaticBatchData,+} from './render/staticBatchPlugin';+export {+ mergeMeshes, planStaticBatches, STATIC_BATCH_DEFAULTS,+ type StaticBatchGroup, type StaticBatchLimits, type StaticBatchRefusal, type StaticBatchReport,+} from './render/staticBatch';// =============================================================================// Tilemapdiff --git a/sdk/src/render/staticBatch.ts b/sdk/src/render/staticBatch.tsnew file mode 100644index 000000000..fa0a09a79--- /dev/null+++ b/sdk/src/render/staticBatch.ts@@ -0,0 +1,317 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file staticBatch.ts+ * @brief Many static meshes that share a material, folded into a few larger ones.+ *+ * @details The renderer already draws the SAME geometry many times as one instanced+ * draw. What it cannot do is draw DIFFERENT geometry as one: each mesh is its+ * own buffer range, so a level assembled from fifty distinct props pays fifty+ * draws per material. A static batch is the answer a tool can give — bake each+ * part's world transform into its vertices, concatenate, and draw the result once.+ *+ * Three jobs, kept apart so each can be tested without a GPU:+ * - {@link mergeMeshes} the geometry: transforms and concatenates decoded meshes;+ * - {@link planStaticBatches} the grouping: who may share a draw, in which cells;+ * - the plugin (staticBatchPlugin.ts) the world: reads entities, uploads, hides.+ *+ * What it costs is memory, not correctness: the merged mesh holds a copy of every+ * part's vertices, and a part that stood for a hundred instances is now a hundred+ * copies. {@link StaticBatchGroup} reports both numbers so the trade is visible.+ */+import { MeshChannel, MeshChannelType, type MeshChannelDesc, type MeshData } from '../asset/meshFormat';++/** Why a mesh was left out of every batch. Each one is a rule the merge relies on. */+export type StaticBatchRefusal =+ /** No geometry behind the handle yet (still loading, or a mesh that failed). */+ | 'no-mesh'+ /** Posed by a skeleton: one draw can only be in one pose. */+ | 'skinned'+ /** Carries blend shapes: one draw can only be in one shape. */+ | 'morph'+ /** Chooses among levels of detail at run time, which a merged mesh cannot. */+ | 'lod'+ /** Lit by a bake: its atlas patch belongs to the object, not to the batch. */+ | 'baked'+ /** Blended: its result depends on order, and merging is the loss of order. */+ | 'blended'+ /** Moves (a dynamic body or a character): a static batch bakes where it stands. */+ | 'moves'+ /** Switched off, so there is nothing to draw. */+ | 'disabled'+ /** Vertex layout the merge cannot transform (positions or normals not float). */+ | 'layout'+ /** The only member of its group: merging it would cost memory and save nothing. */+ | 'alone';++/** What decides whether two meshes may share a draw — every field is state a draw owns. */+export interface StaticBatchState {+ material: number;+ texture: number;+ normalMap: number;+ color: { r: number; g: number; b: number; a: number };+ layer: number;+ cullBackfaces: boolean;+ lit: boolean;+ parallax: { x: number; y: number };+ /** The author's own grouping (`StaticBatch.group`), so two rooms can be kept apart. */+ group: string;+}++/** Whether a vertex layout is one the merge knows how to transform. */+export function channelSignature(channels: readonly MeshChannelDesc[], stride: number): string {+ return `${stride}:${channels.map((c) => `${c.semantic}.${c.components}.${c.type}@${c.offset}`).join(',')}`;+}++/** Null when the layout can be merged; otherwise the refusal to report. */+export function layoutRefusal(mesh: MeshData): StaticBatchRefusal | null {+ if (mesh.inverseBindMatrices || mesh.channels.some((c) => c.semantic === MeshChannel.Joints || c.semantic === MeshChannel.Weights)) {+ return 'skinned';+ }+ if (mesh.morph) return 'morph';+ const need = (semantic: number, components: number): boolean => {+ const c = mesh.channels.find((x) => x.semantic === semantic);+ return !c || (c.type === MeshChannelType.Float32 && c.components >= components);+ };+ // A channel that is present has to be float to be transformed in place; absent is fine (flat).+ return need(MeshChannel.Position, 3) && need(MeshChannel.Normal, 3) && need(MeshChannel.Tangent, 4)+ && mesh.channels.some((c) => c.semantic === MeshChannel.Position) ? null : 'layout';+}++/** A column-major 4x4 from a TRS, as the engine resolved the entity's world transform. */+export function worldMatrix(p: { x: number; y: number; z: number }, q: { x: number; y: number; z: number; w: number },+ s: { x: number; y: number; z: number }): Float64Array {+ const { x, y, z, w } = q;+ return Float64Array.of(+ (1 - 2 * (y * y + z * z)) * s.x, (2 * (x * y + z * w)) * s.x, (2 * (x * z - y * w)) * s.x, 0,+ (2 * (x * y - z * w)) * s.y, (1 - 2 * (x * x + z * z)) * s.y, (2 * (y * z + x * w)) * s.y, 0,+ (2 * (x * z + y * w)) * s.z, (2 * (y * z - x * w)) * s.z, (1 - 2 * (x * x + y * y)) * s.z, 0,+ p.x, p.y, p.z, 1,+ );+}++/** One mesh and where it stands. */+export interface BatchPart {+ mesh: MeshData;+ /** Column-major world matrix. */+ world: ArrayLike<number>;+}++/** The inverse transpose of the upper 3x3, which is what carries a normal through a non-uniform scale. */+function normalMatrix(m: ArrayLike<number>): Float64Array {+ const a = m[0]!, b = m[1]!, c = m[2]!, d = m[4]!, e = m[5]!, f = m[6]!, g = m[8]!, h = m[9]!, i = m[10]!;+ // The cofactor matrix is det * inverse-transpose; the sign of det is kept, the scale is normalised away.+ return Float64Array.of(+ e * i - f * h, f * g - d * i, d * h - e * g,+ c * h - b * i, a * i - c * g, b * g - a * h,+ b * f - c * e, c * d - a * f, a * e - b * d,+ );+}++const determinant3 = (m: ArrayLike<number>): number =>+ m[0]! * (m[5]! * m[10]! - m[6]! * m[9]!) - m[4]! * (m[1]! * m[10]! - m[2]! * m[9]!) + m[8]! * (m[1]! * m[6]! - m[2]! * m[5]!);++/**+ * Concatenates `parts` into one mesh in world space.+ *+ * Every part must carry the same vertex layout (the planner groups by it); positions and+ * tangents go through the world matrix, normals through its inverse transpose. A mirrored part+ * (negative determinant) has its winding reversed and its tangent handedness flipped, so it+ * still faces the way it did.+ */+export function mergeMeshes(parts: readonly BatchPart[]): MeshData {+ if (parts.length === 0) throw new Error('mergeMeshes needs at least one part');+ const first = parts[0]!.mesh;+ const signature = channelSignature(first.channels, first.vertexStride);+ const stride = first.vertexStride;+ let vertexCount = 0;+ let indexCount = 0;+ for (const p of parts) {+ if (channelSignature(p.mesh.channels, p.mesh.vertexStride) !== signature) {+ throw new Error('mergeMeshes: parts carry different vertex layouts');+ }+ vertexCount += p.mesh.vertexCount;+ indexCount += p.mesh.indices.length;+ }++ const position = first.channels.find((c) => c.semantic === MeshChannel.Position)!;+ const normal = first.channels.find((c) => c.semantic === MeshChannel.Normal);+ const tangent = first.channels.find((c) => c.semantic === MeshChannel.Tangent);++ const vertices = new Uint8Array(vertexCount * stride);+ const indices = new Uint32Array(indexCount);+ const min: [number, number, number] = [Infinity, Infinity, Infinity];+ const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];+ let vBase = 0;+ let iBase = 0;++ for (const { mesh, world } of parts) {+ const out = new Uint8Array(vertices.buffer, vBase * stride, mesh.vertexCount * stride);+ out.set(mesh.vertices.subarray(0, mesh.vertexCount * stride));+ // A view over a copy that starts at a vertex boundary: strides are multiples of 4.+ const dv = new DataView(vertices.buffer, vBase * stride, mesh.vertexCount * stride);+ const nm = normalMatrix(world);+ const flip = determinant3(world) < 0;++ for (let v = 0; v < mesh.vertexCount; v++) {+ const at = v * stride;+ const px = dv.getFloat32(at + position.offset, true);+ const py = dv.getFloat32(at + position.offset + 4, true);+ const pz = dv.getFloat32(at + position.offset + 8, true);+ const wx = world[0]! * px + world[4]! * py + world[8]! * pz + world[12]!;+ const wy = world[1]! * px + world[5]! * py + world[9]! * pz + world[13]!;+ const wz = world[2]! * px + world[6]! * py + world[10]! * pz + world[14]!;+ dv.setFloat32(at + position.offset, wx, true);+ dv.setFloat32(at + position.offset + 4, wy, true);+ dv.setFloat32(at + position.offset + 8, wz, true);+ if (wx < min[0]) min[0] = wx; if (wx > max[0]) max[0] = wx;+ if (wy < min[1]) min[1] = wy; if (wy > max[1]) max[1] = wy;+ if (wz < min[2]) min[2] = wz; if (wz > max[2]) max[2] = wz;++ if (normal) {+ const nx = dv.getFloat32(at + normal.offset, true);+ const ny = dv.getFloat32(at + normal.offset + 4, true);+ const nz = dv.getFloat32(at + normal.offset + 8, true);+ // nm holds the cofactors of the matrix read row-wise from the column-major input, so+ // the product with it is taken transposed: n' = N^T * n.+ let rx = nm[0]! * nx + nm[3]! * ny + nm[6]! * nz;+ let ry = nm[1]! * nx + nm[4]! * ny + nm[7]! * nz;+ let rz = nm[2]! * nx + nm[5]! * ny + nm[8]! * nz;+ const len = Math.hypot(rx, ry, rz) || 1;+ // The cofactor of a mirrored matrix points the other way; the surface it belongs to has flipped winding.+ const sign = flip ? -1 : 1;+ rx = (rx / len) * sign; ry = (ry / len) * sign; rz = (rz / len) * sign;+ dv.setFloat32(at + normal.offset, rx, true);+ dv.setFloat32(at + normal.offset + 4, ry, true);+ dv.setFloat32(at + normal.offset + 8, rz, true);+ }+ if (tangent) {+ const tx = dv.getFloat32(at + tangent.offset, true);+ const ty = dv.getFloat32(at + tangent.offset + 4, true);+ const tz = dv.getFloat32(at + tangent.offset + 8, true);+ let rx = world[0]! * tx + world[4]! * ty + world[8]! * tz;+ let ry = world[1]! * tx + world[5]! * ty + world[9]! * tz;+ let rz = world[2]! * tx + world[6]! * ty + world[10]! * tz;+ const len = Math.hypot(rx, ry, rz) || 1;+ rx /= len; ry /= len; rz /= len;+ dv.setFloat32(at + tangent.offset, rx, true);+ dv.setFloat32(at + tangent.offset + 4, ry, true);+ dv.setFloat32(at + tangent.offset + 8, rz, true);+ if (flip) dv.setFloat32(at + tangent.offset + 12, -dv.getFloat32(at + tangent.offset + 12, true), true);+ }+ }++ const src = mesh.indices;+ if (flip) {+ for (let t = 0; t + 2 < src.length; t += 3) {+ indices[iBase + t] = src[t]! + vBase;+ indices[iBase + t + 1] = src[t + 2]! + vBase;+ indices[iBase + t + 2] = src[t + 1]! + vBase;+ }+ } else {+ for (let t = 0; t < src.length; t++) indices[iBase + t] = src[t]! + vBase;+ }+ vBase += mesh.vertexCount;+ iBase += src.length;+ }++ return {+ channels: first.channels.map((c) => ({ ...c })),+ vertexStride: stride,+ vertexCount,+ vertices,+ indices,+ aabbMin: min,+ aabbMax: max,+ };+}++/** What the planner knows about one entity, without holding its geometry. */+export interface StaticBatchCandidate {+ entity: number;+ /** `staticBatchKey(...)` of its draw state plus its vertex layout. */+ key: string;+ /** Where its mesh stands, for the cell it falls in. */+ center: readonly [number, number, number];+ vertices: number;+}++export interface StaticBatchPlan {+ /** Entities to merge together, one list per resulting mesh. */+ batches: { key: string; entities: number[]; vertices: number }[];+ /** Entities left out because they would have been alone in their group. */+ alone: number[];+}++export interface StaticBatchLimits {+ /** Side of the world cell a batch is confined to: bigger merges more and culls worse. */+ cellSize: number;+ /** Most vertices one merged mesh may hold. */+ maxVertices: number;+}++export const STATIC_BATCH_DEFAULTS: StaticBatchLimits = { cellSize: 1600, maxVertices: 262144 };++/** The draw state two meshes must share to be one draw, as a string. */+export function staticBatchKey(state: StaticBatchState, layout: string): string {+ const c = state.color;+ return [state.material, state.texture, state.normalMap, c.r, c.g, c.b, c.a, state.layer,+ state.cullBackfaces ? 1 : 0, state.lit ? 1 : 0, state.parallax.x, state.parallax.y, state.group, layout].join('|');+}++/**+ * Groups candidates by draw state, confines each group to world cells, and splits a cell at the+ * vertex limit. Order inside a batch follows entity id, so the same scene always merges the same way.+ */+export function planStaticBatches(candidates: readonly StaticBatchCandidate[],+ limits: StaticBatchLimits = STATIC_BATCH_DEFAULTS): StaticBatchPlan {+ const cells = new Map<string, StaticBatchCandidate[]>();+ const size = Math.max(1, limits.cellSize);+ for (const c of candidates) {+ const cell = `${c.key}#${Math.floor(c.center[0] / size)},${Math.floor(c.center[1] / size)},${Math.floor(c.center[2] / size)}`;+ const list = cells.get(cell);+ if (list) list.push(c); else cells.set(cell, [c]);+ }+ const plan: StaticBatchPlan = { batches: [], alone: [] };+ for (const list of cells.values()) {+ list.sort((a, b) => a.entity - b.entity);+ let current: StaticBatchCandidate[] = [];+ let vertices = 0;+ const flush = (): void => {+ if (current.length === 0) return;+ if (current.length === 1) plan.alone.push(current[0]!.entity);+ else plan.batches.push({ key: current[0]!.key, entities: current.map((c) => c.entity), vertices });+ current = [];+ vertices = 0;+ };+ for (const c of list) {+ if (current.length > 0 && vertices + c.vertices > limits.maxVertices) flush();+ current.push(c);+ vertices += c.vertices;+ }+ flush();+ }+ plan.batches.sort((a, b) => a.entities[0]! - b.entities[0]!);+ plan.alone.sort((a, b) => a - b);+ return plan;+}++/** One merged mesh, as the report states it. */+export interface StaticBatchGroup {+ /** The entity that now draws the merged mesh. */+ entity: number;+ /** The meshes folded into it. */+ parts: number[];+ vertices: number;+ triangles: number;+ /** Bytes of vertex and index data the merged mesh holds (the copy the merge costs). */+ bytes: number;+ /** What drawing the parts took: one per distinct mesh range, plus the instancing the renderer already did. */+ drawsBefore: number;+}++/** What the last pass did and left out, for a profiler or an editor panel. */+export interface StaticBatchReport {+ groups: StaticBatchGroup[];+ refused: Map<number, StaticBatchRefusal>;+}diff --git a/sdk/src/render/staticBatchPlugin.ts b/sdk/src/render/staticBatchPlugin.tsnew file mode 100644index 000000000..1ed0d4a59--- /dev/null+++ b/sdk/src/render/staticBatchPlugin.ts@@ -0,0 +1,336 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file staticBatchPlugin.ts+ * @brief Folds the meshes an author marked `StaticBatch` into a few larger ones, while the game runs.+ *+ * @details Run time, not export time, so the editor's Play, a web build, a mini game and a native+ * app all draw the same thing. The marked entities stay exactly as authored — scripts can+ * still find them, colliders still collide, the editor still picks them — and only their+ * MeshRenderer is switched off; one entity per merged group draws them instead.+ *+ * The contract is the usual one for static batching: a marked mesh does not move after the+ * pass has seen it. Destroying one is supported (its group is rebuilt without it); moving+ * one is not, and nothing here can notice.+ *+ * A pass waits until entities stop arriving: a scene spawns over several frames, and merging+ * what has arrived so far would leave a batch per frame instead of a batch per room.+ */+import type { App, Plugin } from '../app/app';+import { defineSystem, Schedule } from '../ecs/system';+import { defineResource } from '../ecs/resource';+import {+ defineComponent, getComponent, MeshRenderer, Transform, SceneOwner,+ type ComponentDef, type MeshRendererData, type TransformData,+} from '../ecs/component';+import { RigidBody3D, CharacterController3D } from '../physics3d/Physics3DComponents';+import { BodyType } from '../wasm/wasm.generated';+import { playModeOnly } from '../ecs/env';+import { Assets } from '../asset/AssetPlugin';+import { MeshChannel, type MeshData } from '../asset/meshFormat';+import { log } from '../util/logger';+import type { Entity } from '../types';+import {+ STATIC_BATCH_DEFAULTS, channelSignature, layoutRefusal, mergeMeshes, planStaticBatches, staticBatchKey, worldMatrix,+ type BatchPart, type StaticBatchCandidate, type StaticBatchGroup, type StaticBatchLimits, type StaticBatchRefusal,+ type StaticBatchReport,+} from './staticBatch';++/** The fields of the `StaticBatch` component. @experimental */+export interface StaticBatchData {+ /** Meshes batch only with others of the same group, so two rooms can be kept apart. */+ group: string;+}++/**+ * Marks a mesh as one that will not move, so it may be drawn together with others that share its material.+ * Presence is the opt-in.+ *+ * @experimental+ */+export const StaticBatch: ComponentDef<StaticBatchData> = defineComponent<StaticBatchData>('StaticBatch', {+ group: '',+}, {+ fields: {+ group: { tooltip: 'Meshes batch only with others of the same group. Empty is the default group.' },+ },+});++/** Run-time access to the batcher: what it did, and how to ask it to do it again. */+export class StaticBatching {+ limits: StaticBatchLimits = { ...STATIC_BATCH_DEFAULTS };+ /** @internal */ readonly groups_: StaticBatchGroupState[] = [];+ /** @internal */ readonly refused_ = new Map<number, StaticBatchRefusal>();+ /** @internal */ readonly seen_ = new Set<number>();+ /** @internal */ pending_ = 0;+ /** @internal */ stable_ = 0;+ /** @internal */ busy_ = false;+ /** @internal */ dirty_ = true;++ /** What the last passes merged and left out. */+ report(): StaticBatchReport {+ return { groups: this.groups_.map((g) => g.report), refused: new Map(this.refused_) };+ }++ /** Marked entities the pass has not decided on yet (their mesh is still loading). */+ get pending(): number {+ return this.pending_;+ }++ /** Forget every decision and merge again from the scene as it stands. */+ rebuild(): void {+ this.dirty_ = true;+ this.stable_ = 0;+ }+}++/** The resource the plugin installs. @experimental */+export const StaticBatchingRes = defineResource<StaticBatching>(new StaticBatching(), 'StaticBatching');++interface StaticBatchGroupState {+ entity: Entity;+ handle: number;+ parts: Entity[];+ report: StaticBatchGroup;+}++/** Frames with nothing new to merge before a pass starts. */+const SETTLE_FRAMES = 2;+/** Frames between checks for a part that has gone away. */+const SWEEP_FRAMES = 30;++const drawsOf = (meshes: readonly MeshData[]): number => new Set(meshes).size;++export class StaticBatchPlugin implements Plugin {+ name = 'staticBatch';++ build(app: App): void {+ const state = new StaticBatching();+ app.insertResource(StaticBatchingRes, state);+ const world = app.world;+ let frame = 0;++ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {+ frame++;+ if (state.busy_ || !app.hasResource(Assets)) return;+ const assets = app.getResource(Assets);++ if (state.dirty_) {+ this.discardAll(app, state);+ state.dirty_ = false;+ }+ const fresh = this.freshEntities(app, state);+ if (fresh.length > 0) {+ state.stable_ = 0;+ state.pending_ = fresh.length;+ return;+ }+ state.pending_ = 0;+ const undecided = this.undecided(app, state);+ if (undecided.length > 0) {+ state.stable_++;+ if (state.stable_ < SETTLE_FRAMES) return;+ state.busy_ = true;+ void this.pass(app, state, assets, undecided)+ .catch((e) => log.error('staticBatch', 'a static batch pass failed', e))+ .finally(() => { state.busy_ = false; });+ return;+ }+ if (frame % SWEEP_FRAMES === 0) this.sweep(app, state, assets);+ }, { name: 'StaticBatchSystem' }), { runIf: playModeOnly });+ }++ cleanup(app?: App): void {+ if (app?.hasResource(StaticBatchingRes)) this.discardAll(app, app.getResource(StaticBatchingRes));+ }++ /** Marked entities whose mesh handle has not arrived: the pass cannot decide on them yet. */+ private freshEntities(app: App, state: StaticBatching): Entity[] {+ const world = app.world;+ const out: Entity[] = [];+ for (const e of world.getEntitiesWithComponents([StaticBatch, MeshRenderer, Transform])) {+ if (state.seen_.has(e)) continue;+ const mr = world.get(e, MeshRenderer) as MeshRendererData;+ if (mr.enabled && mr.mesh === 0) out.push(e);+ }+ return out;+ }++ /** 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));+ }++ private refuse(state: StaticBatching, entity: Entity, why: StaticBatchRefusal): void {+ state.refused_.set(entity, why);+ state.seen_.add(entity);+ }++ private async pass(app: App, state: StaticBatching, assets: ReturnType<App['getResource']> & any, entities: Entity[]): Promise<void> {+ const world = app.world;+ const lodDef = getComponent('LODGroup');+ const skinDef = getComponent('MeshSkin');+ const probeDef = getComponent('LightProbeVolume');+ const bakedDef = getComponent('BakedLighting');+ const probed = !!probeDef && world.getEntitiesWithComponents([probeDef]).length > 0;+ const baked = !!bakedDef && world.getEntitiesWithComponents([bakedDef])+ .some((e) => (world.get(e, bakedDef) as { bakedFrom?: string }).bakedFrom);++ const meshes = new Map<number, MeshData | null>();+ const candidates: StaticBatchCandidate[] = [];+ const info = new Map<number, { mr: MeshRendererData; mesh: MeshData; world: BatchPart['world']; scene: string }>();++ for (const e of entities) {+ if (!world.valid(e)) continue;+ const mr = world.get(e, MeshRenderer) as MeshRendererData;+ const sb = world.get(e, StaticBatch) as StaticBatchData;+ if (!mr.enabled) { this.refuse(state, e, 'disabled'); continue; }+ if (!mr.opaque) { this.refuse(state, e, 'blended'); continue; }+ if (lodDef && world.has(e, lodDef)) { this.refuse(state, e, 'lod'); continue; }+ if (skinDef && world.has(e, skinDef)) { this.refuse(state, e, 'skinned'); continue; }+ if (world.has(e, CharacterController3D)+ || (world.has(e, RigidBody3D) && (world.get(e, RigidBody3D) as { bodyType: number }).bodyType !== BodyType.Static)) {+ this.refuse(state, e, 'moves');+ continue;+ }+ if (probed) { this.refuse(state, e, 'baked'); continue; }++ if (!meshes.has(mr.mesh)) meshes.set(mr.mesh, await assets.readMeshData(mr.mesh));+ const mesh = meshes.get(mr.mesh) ?? null;+ if (!mesh) { this.refuse(state, e, 'no-mesh'); continue; }+ if (baked && mesh.channels.some((c) => c.semantic === MeshChannel.TexCoord1)) { this.refuse(state, e, 'baked'); continue; }+ const layout = layoutRefusal(mesh);+ if (layout) { this.refuse(state, e, layout); continue; }+ if (!world.valid(e)) continue;++ const t = world.get(e, Transform) as TransformData;+ const matrix = worldMatrix(t.worldPosition, t.worldRotation, t.worldScale);+ const scene = world.has(e, SceneOwner) ? (world.get(e, SceneOwner) as { scene: string }).scene : '';+ 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] = [+ matrix[0]! * cx + matrix[4]! * cy + matrix[8]! * cz + matrix[12]!,+ matrix[1]! * cx + matrix[5]! * cy + matrix[9]! * cz + matrix[13]!,+ matrix[2]! * cx + matrix[6]! * cy + matrix[10]! * cz + matrix[14]!,+ ];+ const 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: `${sb.group}@${scene}`,+ }, channelSignature(mesh.channels, mesh.vertexStride));+ candidates.push({ entity: e, key, center, vertices: mesh.vertexCount });+ info.set(e, { mr, mesh, world: matrix, scene });+ }++ const plan = planStaticBatches(candidates, state.limits);+ for (const e of plan.alone) this.refuse(state, e as Entity, 'alone');++ for (const batch of plan.batches) {+ const members = batch.entities.filter((e) => world.valid(e as Entity)) as Entity[];+ if (members.length < 2) { for (const e of members) this.refuse(state, e, 'alone'); continue; }+ const parts: BatchPart[] = members.map((e) => ({ mesh: info.get(e)!.mesh, world: info.get(e)!.world }));+ const merged = mergeMeshes(parts);+ const handle = assets.createMesh(merged);+ if (handle === 0) {+ log.warn('staticBatch', `the engine refused a merged mesh of ${members.length} parts (${merged.vertexCount} vertices)`);+ for (const e of members) this.refuse(state, e, 'layout');+ continue;+ }+ const head = info.get(members[0]!)!;+ const holder = world.spawn(`StaticBatch ${state.groups_.length + 1}`);+ world.insert(holder, Transform, {});+ world.insert(holder, MeshRenderer, { ...head.mr, mesh: handle, enabled: true });+ if (head.scene) world.insert(holder, SceneOwner, { scene: head.scene });+ for (const e of members) {+ const mr = world.get(e, MeshRenderer) as MeshRendererData;+ world.insert(e, MeshRenderer, { ...mr, enabled: false });+ state.seen_.add(e);+ }+ state.groups_.push({+ entity: holder, handle, parts: members,+ report: {+ entity: holder, parts: members, vertices: merged.vertexCount, triangles: merged.indices.length / 3,+ bytes: merged.vertices.byteLength + merged.indices.byteLength,+ drawsBefore: drawsOf(members.map((e) => info.get(e)!.mesh)),+ },+ });+ }+ }++ /** Rebuild any group that lost a part (its scene unloaded, or the entity was destroyed). */+ private sweep(app: App, state: StaticBatching, assets: any): void {+ const world = app.world;+ for (let i = state.groups_.length - 1; i >= 0; i--) {+ const g = state.groups_[i]!;+ const alive = g.parts.filter((e) => world.valid(e));+ if (!world.valid(g.entity)) {+ assets.releaseBuiltMesh(g.handle);+ for (const e of alive) this.restore(world, e);+ state.groups_.splice(i, 1);+ continue;+ }+ if (alive.length === g.parts.length) continue;+ // A part went away: draw the rest from a smaller merge, or one by one when only one is left.+ state.busy_ = true;+ void this.shrink(app, state, assets, g, alive).finally(() => { state.busy_ = false; });+ return;+ }+ }++ private restore(world: App['world'], entity: Entity): void {+ const mr = world.tryGet(entity, MeshRenderer) as MeshRendererData | null;+ if (mr) world.insert(entity, MeshRenderer, { ...mr, enabled: true });+ }++ private async shrink(app: App, state: StaticBatching, assets: any, g: StaticBatchGroupState, alive: Entity[]): Promise<void> {+ const world = app.world;+ const index = state.groups_.indexOf(g);+ if (index < 0) return;+ if (alive.length < 2) {+ for (const e of alive) this.restore(world, e);+ if (world.valid(g.entity)) world.despawn(g.entity);+ assets.releaseBuiltMesh(g.handle);+ state.groups_.splice(index, 1);+ return;+ }+ const meshes = new Map<number, MeshData | null>();+ const parts: BatchPart[] = [];+ for (const e of alive) {+ const handle = (world.get(e, MeshRenderer) as MeshRendererData).mesh;+ if (!meshes.has(handle)) meshes.set(handle, await assets.readMeshData(handle));+ const mesh = meshes.get(handle);+ if (!mesh || !world.valid(e)) continue;+ const t = world.get(e, Transform) as TransformData;+ parts.push({ mesh, world: worldMatrix(t.worldPosition, t.worldRotation, t.worldScale) });+ }+ if (parts.length !== alive.length || !world.valid(g.entity)) return;+ const merged = mergeMeshes(parts);+ const handle = assets.createMesh(merged);+ if (handle === 0) return;+ const holder = world.get(g.entity, MeshRenderer) as MeshRendererData;+ world.insert(g.entity, MeshRenderer, { ...holder, mesh: handle });+ assets.releaseBuiltMesh(g.handle);+ g.handle = handle;+ g.parts = alive;+ g.report = {+ ...g.report, parts: alive, vertices: merged.vertexCount, triangles: merged.indices.length / 3,+ bytes: merged.vertices.byteLength + merged.indices.byteLength,+ drawsBefore: drawsOf(parts.map((p) => p.mesh)),+ };+ }++ /** Undo everything: parts draw themselves again, merged meshes are released. */+ private discardAll(app: App, state: StaticBatching): void {+ const world = app.world;+ const assets = app.hasResource(Assets) ? app.getResource(Assets) : null;+ for (const g of state.groups_) {+ for (const e of g.parts) if (world.valid(e)) this.restore(world, e);+ if (world.valid(g.entity)) world.despawn(g.entity);+ assets?.releaseBuiltMesh(g.handle);+ }+ state.groups_.length = 0;+ state.refused_.clear();+ state.seen_.clear();+ }+}++export const staticBatchPlugin: Plugin = new StaticBatchPlugin();diff --git a/sdk/tests/static-batch.test.ts b/sdk/tests/static-batch.test.tsnew file mode 100644index 000000000..11f99b0bb--- /dev/null+++ b/sdk/tests/static-batch.test.ts@@ -0,0 +1,127 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../src/asset/meshFormat';+import {+ mergeMeshes, planStaticBatches, worldMatrix, layoutRefusal, staticBatchKey, channelSignature, STATIC_BATCH_DEFAULTS,+} from '../src/render/staticBatch';++const F = MeshChannelType.Float32;+const { channels, vertexStride } = packChannels([+ { semantic: MeshChannel.Position, components: 3, type: F },+ { semantic: MeshChannel.Normal, components: 3, type: F },+ { semantic: MeshChannel.TexCoord0, components: 2, type: F },+]);++/** A single triangle in the XY plane facing +Z. */+function triangle(): MeshData {+ const vertices = new Uint8Array(3 * vertexStride);+ const dv = new DataView(vertices.buffer);+ const corners = [[0, 0, 0], [1, 0, 0], [0, 1, 0]];+ corners.forEach((p, i) => {+ const at = i * vertexStride;+ p.forEach((v, k) => dv.setFloat32(at + channels[0]!.offset + k * 4, v, true));+ [0, 0, 1].forEach((v, k) => dv.setFloat32(at + channels[1]!.offset + k * 4, v, true));+ [i === 1 ? 1 : 0, i === 2 ? 1 : 0].forEach((v, k) => dv.setFloat32(at + channels[2]!.offset + k * 4, v, true));+ });+ return { channels, vertexStride, vertexCount: 3, vertices, indices: Uint32Array.of(0, 1, 2), aabbMin: [0, 0, 0], aabbMax: [1, 1, 0] };+}++const IDENT_Q = { x: 0, y: 0, z: 0, w: 1 };+const read = (m: MeshData, vertex: number, channel: number, k: number): number =>+ new DataView(m.vertices.buffer, m.vertices.byteOffset).getFloat32(vertex * m.vertexStride + m.channels[channel]!.offset + k * 4, true);++describe('mergeMeshes', () => {+ it('concatenates parts in world space and offsets their indices', () => {+ const a = { mesh: triangle(), world: worldMatrix({ x: 10, y: 0, z: 0 }, IDENT_Q, { x: 1, y: 1, z: 1 }) };+ const b = { mesh: triangle(), world: worldMatrix({ x: 0, y: 5, z: 0 }, IDENT_Q, { x: 2, y: 2, z: 2 }) };+ const merged = mergeMeshes([a, b]);+ expect(merged.vertexCount).toBe(6);+ expect(Array.from(merged.indices)).toEqual([0, 1, 2, 3, 4, 5]);+ expect([read(merged, 1, 0, 0), read(merged, 1, 0, 1)]).toEqual([11, 0]);+ expect([read(merged, 4, 0, 0), read(merged, 4, 0, 1)]).toEqual([2, 5]);+ expect(merged.aabbMin).toEqual([0, 0, 0]);+ expect(merged.aabbMax).toEqual([11, 7, 0]);+ });++ it('keeps UVs and leaves the source untouched', () => {+ const source = triangle();+ const before = Uint8Array.from(source.vertices);+ const merged = mergeMeshes([{ mesh: source, world: worldMatrix({ x: 3, y: 3, z: 3 }, IDENT_Q, { x: 1, y: 1, z: 1 }) }]);+ expect(read(merged, 1, 2, 0)).toBe(1);+ expect(Array.from(source.vertices)).toEqual(Array.from(before));+ });++ it('rotates normals with the part and unscales them under a non-uniform scale', () => {+ // 90 degrees about X: +Z becomes -Y.+ const s = Math.SQRT1_2;+ const rotated = mergeMeshes([{ mesh: triangle(), world: worldMatrix({ x: 0, y: 0, z: 0 }, { x: s, y: 0, z: 0, w: s }, { x: 1, y: 1, z: 1 }) }]);+ expect(read(rotated, 0, 1, 1)).toBeCloseTo(-1, 5);+ expect(read(rotated, 0, 1, 2)).toBeCloseTo(0, 5);+ // Stretching X must not tilt a +Z normal.+ const stretched = mergeMeshes([{ mesh: triangle(), world: worldMatrix({ x: 0, y: 0, z: 0 }, IDENT_Q, { x: 8, y: 1, z: 1 }) }]);+ expect(read(stretched, 0, 1, 2)).toBeCloseTo(1, 5);+ expect(read(stretched, 0, 1, 0)).toBeCloseTo(0, 5);+ });++ it('a mirrored part keeps facing the way it did: winding reverses, the normal stays outward', () => {+ const merged = mergeMeshes([{ mesh: triangle(), world: worldMatrix({ x: 0, y: 0, z: 0 }, IDENT_Q, { x: -1, y: 1, z: 1 }) }]);+ expect(Array.from(merged.indices)).toEqual([0, 2, 1]);+ // Mirroring X leaves a +Z normal pointing +Z.+ expect(read(merged, 0, 1, 2)).toBeCloseTo(1, 5);+ });++ it('refuses parts with different layouts rather than guessing', () => {+ const other = packChannels([{ semantic: MeshChannel.Position, components: 3, type: F }]);+ const flat: MeshData = {+ channels: other.channels, vertexStride: other.vertexStride, vertexCount: 1,+ vertices: new Uint8Array(other.vertexStride), indices: Uint32Array.of(0), aabbMin: [0, 0, 0], aabbMax: [0, 0, 0],+ };+ const w = worldMatrix({ x: 0, y: 0, z: 0 }, IDENT_Q, { x: 1, y: 1, z: 1 });+ expect(() => mergeMeshes([{ mesh: triangle(), world: w }, { mesh: flat, world: w }])).toThrow(/different vertex layouts/);+ });+});++describe('layoutRefusal', () => {+ it('accepts a plain float layout and names why it refuses the rest', () => {+ expect(layoutRefusal(triangle())).toBeNull();+ expect(layoutRefusal({ ...triangle(), inverseBindMatrices: new Float32Array(16) })).toBe('skinned');+ expect(layoutRefusal({ ...triangle(), morph: { names: ['a'], hasNormals: false, deltas: new Float32Array(9) } })).toBe('morph');+ const packed = packChannels([+ { semantic: MeshChannel.Position, components: 3, type: F },+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.UNorm8 },+ ]);+ expect(layoutRefusal({ ...triangle(), channels: packed.channels, vertexStride: packed.vertexStride })).toBe('layout');+ });+});++describe('planStaticBatches', () => {+ const state = { material: 1, texture: 2, normalMap: 0, color: { r: 1, g: 1, b: 1, a: 1 }, layer: 0, cullBackfaces: true, lit: true, parallax: { x: 0, y: 0 }, group: '' };+ const layout = channelSignature(channels, vertexStride);+ const key = (over: Partial<typeof state> = {}) => staticBatchKey({ ...state, ...over }, layout);+ const at = (entity: number, x: number, k = key(), vertices = 100) => ({ entity, key: k, center: [x, 0, 0] as const, vertices });++ it('merges what shares a draw state and sits in one cell, and leaves a lone mesh alone', () => {+ const plan = planStaticBatches([at(1, 0), at(2, 100), at(3, 200), at(4, 100, key({ material: 9 }))]);+ expect(plan.batches.map((b) => b.entities)).toEqual([[1, 2, 3]]);+ expect(plan.alone).toEqual([4]);+ });++ it('keeps cells apart so culling still works, and caps a batch at the vertex limit', () => {+ const cell = STATIC_BATCH_DEFAULTS.cellSize;+ const far = planStaticBatches([at(1, 0), at(2, 10), at(3, cell * 3), at(4, cell * 3 + 10)]);+ expect(far.batches.map((b) => b.entities)).toEqual([[1, 2], [3, 4]]);+ const capped = planStaticBatches([at(1, 0, key(), 60), at(2, 1, key(), 60), at(3, 2, key(), 60), at(4, 3, key(), 60)], { cellSize: 1000, maxVertices: 130 });+ expect(capped.batches.map((b) => b.entities)).toEqual([[1, 2], [3, 4]]);+ });++ it('is deterministic whatever order candidates arrive in', () => {+ const list = [at(5, 0), at(2, 1), at(9, 2), at(1, 3)];+ expect(planStaticBatches([...list].reverse())).toEqual(planStaticBatches(list));+ });++ it('the author\'s group keeps otherwise identical meshes in separate batches', () => {+ const plan = planStaticBatches([at(1, 0, key({ group: 'a' })), at(2, 1, key({ group: 'a' })), at(3, 2, key({ group: 'b' })), at(4, 3, key({ group: 'b' }))]);+ expect(plan.batches.map((b) => b.entities)).toEqual([[1, 2], [3, 4]]);+ });+});diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjsindex a2fe81a57..f747b3b4c 100644--- a/tools/goldenProjects.mjs+++ b/tools/goldenProjects.mjs@@ -92,6 +92,7 @@ export const CENSUS_FLOOR = '0.60.0';* that does not exist, and release notes are a different act. Theirs is ungated.*/export const SHIPPED = {+ "Static batching.": { notCertifiable: "Static batching is covered by the static-batch SDK tests and the static-batch-on / static-batch-off render scenes (draw calls and pixels); no golden project marks a mesh StaticBatch." },"Camera shots and nested sequences on the timeline.": { notCertifiable: "Camera and sequence tracks are covered by the timeline-sequences, timeline-drive and camera-director SDK tests and the editor timeline-clips tests; no golden project plays a timeline with a camera or sequence track." },"Dynamic planar reflections.": { notCertifiable: "Planar reflection is covered by the planar-reflection and planar-reflection-off render-scene pixel gates, tools/tests/planar-reflection.e2e.mjs, test_planar_reflection and the planar-reflection editor authoring check; no golden project carries a reflecting surface." },"SUD OpenPaaS development export.": { notCertifiable: "The OpenPaaS export is covered by the pipeline export and package tests, the native SUD runtime end-to-end check and the packer verification; no golden project is packaged for OpenPaaS." },diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 754b5a0c4..2e1fc7d2d 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2449,6 +2449,8 @@ export const NOTED = {{"note":"Device quality profiles can be previewed in the editor."},"fix(editor): opening a timeline opens the Sequencer":{"note":"Opening a timeline opens the Sequencer."},+ "feat(render): static batching draws marked meshes that share a material as one mesh":+ {"note":"Static meshes that share a material can be drawn as one."},"feat(timeline): camera and sequence tracks play shots and nested timelines":{"note":"Timelines have camera and sequence tracks."},"feat(editor): the Sequencer edits camera shots and sequence clips":diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex 52a29efc2..283791e10 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -280,6 +280,11 @@ export const SCENES = [// What the frame COST: nine cubes inside the ortho view and six a thousand units out,// same mesh and same material, so render.culled is the only place the six can show.// batch.draws holds the nine to ONE instanced call; render.triangles counts 9 x 12.+ // Five different primitives, four of each, one shared draw state. The renderer instances each shape, so the+ // frame costs one draw per DISTINCT mesh — five. The same scene with `StaticBatch` on the meshes folds all+ // twenty into one merged mesh, and the picture must not move: the same twenty points are the claim.+ { id: "static-batch-off", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/static-batch-off.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "12", ESTELLA_VERIFY_DRAW_CALLS: "5", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.1,\"y\":0.2,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.1,\"y\":0.4,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.1,\"y\":0.6,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.1,\"y\":0.8,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.3,\"y\":0.2,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.3,\"y\":0.4,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.3,\"y\":0.6,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.3,\"y\":0.8,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.5,\"y\":0.2,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.5,\"y\":0.4,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.5,\"y\":0.6,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.5,\"y\":0.8,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.7,\"y\":0.2,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.7,\"y\":0.4,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.7,\"y\":0.6,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.7,\"y\":0.8,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.9,\"y\":0.2,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.9,\"y\":0.4,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.9,\"y\":0.6,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.9,\"y\":0.8,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.5,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20}]" } },+ { id: "static-batch-on", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/static-batch-on.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "12", ESTELLA_VERIFY_DRAW_CALLS: "1", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.1,\"y\":0.2,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.1,\"y\":0.4,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.1,\"y\":0.6,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.1,\"y\":0.8,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.3,\"y\":0.2,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.3,\"y\":0.4,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.3,\"y\":0.6,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.3,\"y\":0.8,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.5,\"y\":0.2,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.5,\"y\":0.4,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.5,\"y\":0.6,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.5,\"y\":0.8,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.7,\"y\":0.2,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.7,\"y\":0.4,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.7,\"y\":0.6,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.7,\"y\":0.8,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.9,\"y\":0.2,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.9,\"y\":0.4,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.9,\"y\":0.6,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.9,\"y\":0.8,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.5,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20}]" } },{ id: "mesh-cost", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-cost.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_COUNTERS: "{\"render.meshes\":9,\"render.culled\":6,\"render.triangles\":108,\"batch.draws\":1}", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.1667,\"y\":0.1667,\"rgb\":[255,0,0],\"tol\":20},{\"x\":0.5,\"y\":0.5,\"rgb\":[255,0,255],\"tol\":20},{\"x\":0.8333,\"y\":0.8333,\"rgb\":[0,255,0],\"tol\":20},{\"x\":0.3,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":10}]" } },// A CEILING, not an exact value: at scale the question is whether submission stays O(1)// in the count, and render.sprites stays exact so a frame that dropped content cannot pass