Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(render): a mesh is drawn in the shape its weights ask for

esengine4c3b8ed9283b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 31e198b33..924d04a21 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,19 @@ published separately; it ships inside the editor.
### Added
+- **A model brings the shapes it can be blended towards.** A glTF morph target
+ was reported at the door and dropped; now the `.esmesh` carries one delta per
+ vertex per target beside the vertices it moves, and the prefab an import writes
+ gives the entity a `MeshMorph` whose weights say what shape it is in. The
+ deltas deform on the GPU, before the pose — a face can be posed by bones and
+ shaped by its expressions at once — and the material path deforms with the
+ engine's own, so a mesh drawn by a custom shader moves the same way.
+
+ The weights are a **budget on what is live**, not on what a mesh carries: the
+ eight heaviest are blended and the rest read as zero, which is what an
+ untouched weight already means. Three pixel gates hold it — the same quad, the
+ same two points, and the weight the only thing that differs.
+
- **A controller is a stack of machines, not one.** One state machine can say a
character is running or that it is waving, never both. A `.esanimator` now
carries layers over its base one — each a machine with its own clock, its own
diff --git a/desktop b/desktop
index 5c47aeb09..aaa7189a2 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 5c47aeb09bf3f2e1050008e0c296656affc13494
+Subproject commit aaa7189a2f8ce6682961935d90d4e3b8e481d5fb
diff --git a/docs/astro/src/content/docs/assets/models.mdx b/docs/astro/src/content/docs/assets/models.mdx
index f488172a8..2ae9b0f65 100644
--- a/docs/astro/src/content/docs/assets/models.mdx
+++ b/docs/astro/src/content/docs/assets/models.mdx
@@ -170,6 +170,23 @@ joints.
| 64 joints per mesh | The pose is a uniform block, which is 4KB at that size — inside what a WebGL2 block is guaranteed. A mesh wanting more draws undeformed. |
| Joint count must match the bind pose | A mesh whose `MeshSkin` names a different number of joints draws undeformed rather than with vertices resolved against the wrong matrices. |
+## Morph targets
+
+A model that carries shapes to blend towards — blend shapes, in most DCC tools — brings
+them with it: the `.esmesh` holds one delta per vertex per target beside the vertices, and
+the prefab gives the entity a `MeshMorph` whose `weights` say how far it is blended towards
+each. Entry *i* is target *i*, in the order the file lists them; the names the source
+carries are kept with the geometry, so a weight addresses a shape by position.
+
+A weight of 0 leaves the mesh as authored and 1 is the target in full. Neither is a bound:
+glTF states none, and pushing past 1 or below 0 is a shape an author may want.
+
+| Limit | Why |
+|---|---|
+| 8 shapes blended at once | A budget on what is LIVE, not on what a mesh carries — a face holds a handful of expressions open while its mesh has a hundred. The heaviest weights are taken; the rest read as zero, which is what an untouched weight already means. |
+| Normals deform only where the geometry has them | A mesh with no `NORMAL` channel is shaded off a constant normal, which no delta can bend. |
+| Tangents are not carried | The tangent frame is derived per pixel, from the surface as deformed. |
+
## FBX
FBX is read by [ufbx](https://github.com/ufbx/ufbx), built into the editor — no Autodesk
@@ -214,7 +231,7 @@ when it runs.
| Not imported | Why |
|---|---|
-| Morph targets / blend shapes, `weights` animation channels | Blending between shapes needs the targets themselves, which are not carried. |
+| `weights` animation channels | The shapes themselves are imported (see [Morph targets](#morph-targets)); a clip that drives them is not carried yet. |
| A second UV set (`TEXCOORD_1`), `KHR_texture_transform`, an FBX uv transform | UVs are used as authored. |
| Non-triangle primitives (`mode` ≠ 4) | The renderer draws triangle lists. |
| `normalTexture.scale` | The map is applied at full strength. |
diff --git a/docs/astro/src/content/docs/zh-cn/assets/models.mdx b/docs/astro/src/content/docs/zh-cn/assets/models.mdx
index 227f4bb77..c5937c5dc 100644
--- a/docs/astro/src/content/docs/zh-cn/assets/models.mdx
+++ b/docs/astro/src/content/docs/zh-cn/assets/models.mdx
@@ -156,6 +156,22 @@ mesh 就会变形。
| 每个 mesh 最多 64 根骨骼 | 姿态走 uniform 块,64 根是 4KB —— 在 WebGL2 对一个块的保证范围内。超过的 mesh 按不变形绘制。 |
| 骨骼数必须与绑定姿态一致 | `MeshSkin` 列出的骨骼数对不上时按不变形绘制,而不是让顶点去解析错误的矩阵。 |
+## Morph target
+
+模型带着可混合的形状进来(在多数 DCC 里叫 blend shape):`.esmesh` 在顶点旁边存下每个
+target 对每个顶点的 delta,prefab 给实体挂一个 `MeshMorph`,它的 `weights` 说明当前朝
+每个形状混合了多少。第 *i* 项对应第 *i* 个 target,顺序就是文件列出的顺序;名字跟着几何
+走,所以权重是按位置寻址形状的。
+
+权重 0 是作者创作时的形状,1 是完整的 target。两者都不是上界:glTF 没有规定边界,超过 1
+或低于 0 都是作者可能想要的形状。
+
+| 限制 | 为什么 |
+|---|---|
+| 同时最多混合 8 个形状 | 限制的是**活跃**数量,不是 mesh 能携带的数量——一张脸同时张开的表情就那么几个,而它的 mesh 可以有上百个形状。取权重最大的那些,其余按 0 读,这和作者没动过的权重是同一件事。 |
+| 只有几何自带法线时法线才变形 | 没有 `NORMAL` 通道的 mesh 按一个常量法线着色,任何 delta 都弯不动它。 |
+| 不带切线 | 切线基是逐像素从变形后的表面推出来的。 |
+
## FBX
FBX 由编译进编辑器的 [ufbx](https://github.com/ufbx/ufbx) 读取——不需要 Autodesk FBX
@@ -193,7 +209,7 @@ Physical、Blender 的 Principled 最终都落到[材质](#材质)那一节列
| 不导入 | 为什么 |
|---|---|
-| morph target / blend shape、`weights` 动画通道 | 在多个形状之间混合需要那些 target 本身,而它们没有被带过来。 |
+| `weights` 动画通道 | 形状本身会被导入(见 [Morph target](#morph-target));驱动它们的剪辑还没有被带过来。 |
| 第二套 UV(`TEXCOORD_1`)、`KHR_texture_transform`、FBX 的 uv transform | UV 按作者写的原样使用。 |
| 非三角形 primitive(`mode` ≠ 4) | 渲染器画的是三角形列表。 |
| `normalTexture.scale` | 法线贴图按全强度应用。 |
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index e924743e1..6181605a1 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -74,6 +74,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
PostProcessVolume: { category: 'graphics', summary: 'A stack of full-screen effects (bloom, vignette, colour grading) applied after the scene is drawn.', doc: 'graphics/post-processing', anchor: 'using-a-postprocessvolume', anchorZh: '使用-postprocessvolume' },
MeshRenderer: { category: 'graphics', summary: 'Geometry drawn as an entity — your own vertices or an imported mesh, with a material and a sorting layer.', doc: 'graphics/drawing', anchor: 'custom-meshes-meshrenderer', anchorZh: '自定义网格meshrenderer' },
MeshSkin: { category: 'graphics', summary: 'The joint entities that deform a MeshRenderer — an imported skin, in the order its bind matrices are in.', doc: 'assets/models', anchor: 'skinning', anchorZh: '蒙皮' },
+ MeshMorph: { category: 'graphics', summary: 'How far a MeshRenderer is blended towards each of the shapes its mesh carries — one weight per morph target.', doc: 'assets/models', anchor: 'morph-targets', anchorZh: 'morph-target' },
StreamedWorld: { category: 'world', summary: 'Declares the scene a streamed world and how big the cook cuts its cells.', doc: 'world/streaming', anchor: 'declaring-a-streamed-world', anchorZh: '声明一个流送世界' },
WorldPersistent: { category: 'world', summary: 'Keeps an entity\'s whole subtree out of the partition — it belongs to the persistent world.', doc: 'world/streaming', anchor: 'declaring-a-streamed-world', anchorZh: '声明一个流送世界' },
WorldStreamingSource: { category: 'world', summary: 'Asks for the places near it to exist; several sources are unioned.', doc: 'world/streaming', anchor: 'asking-for-places-streaming-sources', anchorZh: '请求地方存在流送源' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 15ebb3cc3..44b407e31 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -2159,6 +2159,21 @@
}
]
},
+ {
+ "name": "MeshMorph",
+ "source": "cpp",
+ "fields": [
+ {
+ "key": "weights",
+ "type": "array",
+ "default": "empty",
+ "doc": "Weight per morph target of the mesh, in the order the mesh carries them."
+ }
+ ],
+ "animatable": [
+ "weights"
+ ]
+ },
{
"name": "MeshRenderer",
"source": "cpp",
diff --git a/examples/effects-gallery/assets/materials/dissolve.esshader b/examples/effects-gallery/assets/materials/dissolve.esshader
index 8308b3ee5..dcd71898a 100644
--- a/examples/effects-gallery/assets/materials/dissolve.esshader
+++ b/examples/effects-gallery/assets/materials/dissolve.esshader
@@ -40,7 +40,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 0a687499da49fe50
-// assembled-hash: 568d4738969a1eda
+// assembled-hash: 5f362db3e16c1904
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -115,7 +115,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 0a687499da49fe50
-// assembled-hash: 568d4738969a1eda
+// assembled-hash: 5f362db3e16c1904
struct MaterialConstants {
u_progress: f32,
u_edgeColor: vec4<f32>,
diff --git a/examples/effects-gallery/assets/materials/hit-flash.esshader b/examples/effects-gallery/assets/materials/hit-flash.esshader
index d706fedfb..364fa24d8 100644
--- a/examples/effects-gallery/assets/materials/hit-flash.esshader
+++ b/examples/effects-gallery/assets/materials/hit-flash.esshader
@@ -25,7 +25,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 674537b45fb865fb
-// assembled-hash: 99d7f7ea2ccf332b
+// assembled-hash: 103f9553169cf122
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -98,7 +98,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 674537b45fb865fb
-// assembled-hash: 99d7f7ea2ccf332b
+// assembled-hash: 103f9553169cf122
struct MaterialConstants {
u_flash: f32,
u_flashColor: vec4<f32>,
diff --git a/examples/effects-gallery/assets/materials/outline.esshader b/examples/effects-gallery/assets/materials/outline.esshader
index d6b8d3006..2ed13916d 100644
--- a/examples/effects-gallery/assets/materials/outline.esshader
+++ b/examples/effects-gallery/assets/materials/outline.esshader
@@ -34,7 +34,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 7ed4f4686c6bfd8d
-// assembled-hash: ef95e088165b545d
+// assembled-hash: 34782906d87fa387
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -107,7 +107,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 7ed4f4686c6bfd8d
-// assembled-hash: ef95e088165b545d
+// assembled-hash: 34782906d87fa387
struct MaterialConstants {
u_outlineColor: vec4<f32>,
u_outlineWidth: f32,
diff --git a/examples/effects-gallery/assets/materials/pixelate.esshader b/examples/effects-gallery/assets/materials/pixelate.esshader
index b76830727..1b2e2a7fc 100644
--- a/examples/effects-gallery/assets/materials/pixelate.esshader
+++ b/examples/effects-gallery/assets/materials/pixelate.esshader
@@ -23,7 +23,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 0c2fb4b31599ec7a
-// assembled-hash: d93ca8d8cf534600
+// assembled-hash: 5961907023c47348
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -95,7 +95,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 0c2fb4b31599ec7a
-// assembled-hash: d93ca8d8cf534600
+// assembled-hash: 5961907023c47348
struct MaterialConstants {
u_pixels: f32,
}
diff --git a/examples/effects-gallery/assets/materials/uv-scroll.esshader b/examples/effects-gallery/assets/materials/uv-scroll.esshader
index 3edfee4be..35e220042 100644
--- a/examples/effects-gallery/assets/materials/uv-scroll.esshader
+++ b/examples/effects-gallery/assets/materials/uv-scroll.esshader
@@ -24,7 +24,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 301c5b2b73d966f3
-// assembled-hash: 4e56eee430ca22da
+// assembled-hash: db913a6ef915eecf
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -96,7 +96,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 301c5b2b73d966f3
-// assembled-hash: 4e56eee430ca22da
+// assembled-hash: db913a6ef915eecf
struct TimeConstants {
u_time: vec4<f32>,
u_viewport: vec4<f32>,
diff --git a/examples/model-import/assets/models/robot.esprefab b/examples/model-import/assets/models/robot.esprefab
index abd14a8f7..22dee6f78 100644
--- a/examples/model-import/assets/models/robot.esprefab
+++ b/examples/model-import/assets/models/robot.esprefab
@@ -100,6 +100,14 @@
"cullBackfaces": true,
"enabled": true
}
+ },
+ {
+ "type": "MeshMorph",
+ "data": {
+ "weights": [
+ 0.6
+ ]
+ }
}
]
}
diff --git a/examples/model-import/assets/models/robot.gltf b/examples/model-import/assets/models/robot.gltf
index 87eaea3ce..9415624a3 100644
--- a/examples/model-import/assets/models/robot.gltf
+++ b/examples/model-import/assets/models/robot.gltf
@@ -5,8 +5,8 @@
},
"buffers": [
{
- "byteLength": 312,
- "uri": "data:application/octet-stream;base64,AADwwgAAcEIAAAAAAADwQgAAcEIAAAAAAADwwgAAcMIAAAAAAADwQgAAcMIAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AACAPwAAgD8AAAIAAQABAAIAAwAAAHDCAACgQQAAAAAAAHBCAACgQQAAAAAAAHDCAACgwQAAAAAAAHBCAACgwQAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAIA/AACAPwAAAgABAAEAAgADAAAAAAAAAIA+AAAAAAAA3EIAAAAAAAAAAAAAIEMAAAAA"
+ "byteLength": 360,
+ "uri": "data:application/octet-stream;base64,AADwwgAAcEIAAAAAAADwQgAAcEIAAAAAAADwwgAAcMIAAAAAAADwQgAAcMIAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AACAPwAAgD8AAAIAAQABAAIAAwAAAHDCAACgQQAAAAAAAHBCAACgQQAAAAAAAHDCAACgwQAAAAAAAHBCAACgwQAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAIA/AACAPwAAAgABAAEAAgADAAAAAAAAAIA+AAAAAAAA3EIAAAAAAAAAAAAAIEMAAAAAAAAAAAAAAAAAAAAAAABwwgAAwEAAAAAAAAAAAAAAAAAAAAAAAABwwgAAwMAAAAAA"
}
],
"bufferViews": [
@@ -59,6 +59,11 @@
"buffer": 0,
"byteOffset": 288,
"byteLength": 24
+ },
+ {
+ "buffer": 0,
+ "byteOffset": 312,
+ "byteLength": 48
}
],
"accessors": [
@@ -147,6 +152,22 @@
"componentType": 5126,
"count": 2,
"type": "VEC3"
+ },
+ {
+ "bufferView": 10,
+ "componentType": 5126,
+ "count": 4,
+ "type": "VEC3",
+ "min": [
+ -60.0,
+ -6.0,
+ 0.0
+ ],
+ "max": [
+ 0.0,
+ 6.0,
+ 0.0
+ ]
}
],
"images": [
@@ -231,9 +252,19 @@
},
"indices": 7,
"material": 1,
- "mode": 4
+ "mode": 4,
+ "targets": [
+ {
+ "POSITION": 10
+ }
+ ]
}
- ]
+ ],
+ "extras": {
+ "targetNames": [
+ "Furl"
+ ]
+ }
}
],
"nodes": [
@@ -265,6 +296,9 @@
0.9,
0.9,
1
+ ],
+ "weights": [
+ 0.6
]
}
],
diff --git a/examples/model-import/assets/models/robot_0_0.esmesh b/examples/model-import/assets/models/robot_0_0.esmesh
index b53b1646d..69a07dbb7 100644
Binary files a/examples/model-import/assets/models/robot_0_0.esmesh and b/examples/model-import/assets/models/robot_0_0.esmesh differ
diff --git a/examples/model-import/assets/models/robot_1_0.esmesh b/examples/model-import/assets/models/robot_1_0.esmesh
index 50ef1b866..df34a8596 100644
Binary files a/examples/model-import/assets/models/robot_1_0.esmesh and b/examples/model-import/assets/models/robot_1_0.esmesh differ
diff --git a/examples/model-import/assets/models/robot_m1.esmaterial b/examples/model-import/assets/models/robot_m1.esmaterial
index 342bbb363..b6cc4e1dc 100644
--- a/examples/model-import/assets/models/robot_m1.esmaterial
+++ b/examples/model-import/assets/models/robot_m1.esmaterial
@@ -7,13 +7,13 @@
"depthWrite": true,
"cull": 1,
"properties": {
+ "u_metallic": 0,
+ "u_roughness": 1,
"u_emissive": {
"r": 0.9,
"g": 0.25,
"b": 0.1,
"a": 1
- },
- "u_metallic": 0,
- "u_roughness": 1
+ }
}
}
diff --git a/fixtures/scenes/depth-layers/opaque.esshader b/fixtures/scenes/depth-layers/opaque.esshader
index ee2bc7537..02464e51c 100644
--- a/fixtures/scenes/depth-layers/opaque.esshader
+++ b/fixtures/scenes/depth-layers/opaque.esshader
@@ -24,7 +24,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 930787555114ce9c
-// assembled-hash: 70cacfe42f3b2a27
+// assembled-hash: 15f28579e4dc8167
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -90,7 +90,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 930787555114ce9c
-// assembled-hash: 70cacfe42f3b2a27
+// assembled-hash: 15f28579e4dc8167
struct FrameConstants {
u_projection: mat4x4<f32>,
u_camera: vec4<f32>,
diff --git a/fixtures/scenes/mat-builtin-lit/lit.esshader b/fixtures/scenes/mat-builtin-lit/lit.esshader
index 8f31d60f9..2d05de1e8 100644
--- a/fixtures/scenes/mat-builtin-lit/lit.esshader
+++ b/fixtures/scenes/mat-builtin-lit/lit.esshader
@@ -27,7 +27,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 5330079245724fa2
-// assembled-hash: a3fdbc8ad17bed89
+// assembled-hash: b31eee5b749c21d9
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -108,7 +108,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 5330079245724fa2
-// assembled-hash: a3fdbc8ad17bed89
+// assembled-hash: b31eee5b749c21d9
struct FrameConstants {
u_projection: mat4x4<f32>,
u_camera: vec4<f32>,
diff --git a/fixtures/scenes/mat-dissolve/dissolve.esshader b/fixtures/scenes/mat-dissolve/dissolve.esshader
index 8308b3ee5..dcd71898a 100644
--- a/fixtures/scenes/mat-dissolve/dissolve.esshader
+++ b/fixtures/scenes/mat-dissolve/dissolve.esshader
@@ -40,7 +40,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 0a687499da49fe50
-// assembled-hash: 568d4738969a1eda
+// assembled-hash: 5f362db3e16c1904
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -115,7 +115,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 0a687499da49fe50
-// assembled-hash: 568d4738969a1eda
+// assembled-hash: 5f362db3e16c1904
struct MaterialConstants {
u_progress: f32,
u_edgeColor: vec4<f32>,
diff --git a/fixtures/scenes/mesh-morph-mat.esscene b/fixtures/scenes/mesh-morph-mat.esscene
new file mode 100644
index 000000000..818ed572e
--- /dev/null
+++ b/fixtures/scenes/mesh-morph-mat.esscene
@@ -0,0 +1,75 @@
+{
+ "version": 4,
+ "name": "MeshMorphMaterial",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 10
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 100,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Quad",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "scenes/morph-quad.esmesh",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "enabled": true,
+ "material": "/scenes/mesh-skin-mat/skinmat.esmaterial"
+ }
+ },
+ {
+ "type": "MeshMorph",
+ "data": {
+ "weights": [
+ 1
+ ]
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/fixtures/scenes/mesh-morph-off.esscene b/fixtures/scenes/mesh-morph-off.esscene
new file mode 100644
index 000000000..d60223a85
--- /dev/null
+++ b/fixtures/scenes/mesh-morph-off.esscene
@@ -0,0 +1,74 @@
+{
+ "version": 4,
+ "name": "MeshMorphOff",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 10
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 100,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Quad",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "scenes/morph-quad.esmesh",
+ "color": {
+ "r": 0,
+ "g": 1,
+ "b": 0,
+ "a": 1
+ },
+ "enabled": true
+ }
+ },
+ {
+ "type": "MeshMorph",
+ "data": {
+ "weights": [
+ 0
+ ]
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/fixtures/scenes/mesh-morph-on.esscene b/fixtures/scenes/mesh-morph-on.esscene
new file mode 100644
index 000000000..fd299982c
--- /dev/null
+++ b/fixtures/scenes/mesh-morph-on.esscene
@@ -0,0 +1,74 @@
+{
+ "version": 4,
+ "name": "MeshMorphOn",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 10
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 100,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Quad",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "scenes/morph-quad.esmesh",
+ "color": {
+ "r": 0,
+ "g": 1,
+ "b": 0,
+ "a": 1
+ },
+ "enabled": true
+ }
+ },
+ {
+ "type": "MeshMorph",
+ "data": {
+ "weights": [
+ 1
+ ]
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/fixtures/scenes/morph-quad.esmesh b/fixtures/scenes/morph-quad.esmesh
new file mode 100644
index 000000000..852923905
Binary files /dev/null and b/fixtures/scenes/morph-quad.esmesh differ
diff --git a/pipeline/src/assets/gltfImport.ts b/pipeline/src/assets/gltfImport.ts
index f9936f405..8c02e1b05 100644
--- a/pipeline/src/assets/gltfImport.ts
+++ b/pipeline/src/assets/gltfImport.ts
@@ -12,7 +12,7 @@
*/
/// <reference path="./draco3dgltf.d.ts" />
import { MESH_MAX_BONES, MeshChannel, MeshChannelType, packChannels,
- type MeshMorphData } from 'esengine';
+ type MeshMorphTargets } from 'esengine';
import { MeshoptDecoder } from 'meshoptimizer/decoder';
import {
ANIMATED_PATHS, alignQuaternionSigns, animationProductName, disambiguateNodes,
@@ -684,7 +684,7 @@ type GltfPrimitive = GltfMesh['primitives'][number];
*/
function morphTargets(src: GltfBytes, mesh: GltfMesh, prim: GltfPrimitive,
vertexCount: number, hasNormals: boolean,
- label: string, warnings: string[]): MeshMorphData | undefined {
+ label: string, warnings: string[]): MeshMorphTargets | undefined {
const targets = prim.targets ?? [];
if (!targets.length) return undefined;
if (targets.some(t => t.TANGENT !== undefined)) {
@@ -871,6 +871,15 @@ export async function importGltfMeshes(
}
}
+ // The weights a mesh's shapes start at. On the NODE where one states them,
+ // since one mesh may be drawn twice in different shapes — and the first such
+ // node wins, the same way the skin above does.
+ const meshWeights = new Map<number, number[]>();
+ for (const node of json.nodes ?? []) {
+ if (node.mesh === undefined || !node.weights) continue;
+ if (!meshWeights.has(node.mesh)) meshWeights.set(node.mesh, node.weights);
+ }
+
// ~800KB of decoder, loaded only for a file that carries Draco — the same
// lazy dynamic import the cook uses for its KTX2 encoder, and the reason the
// import is async in the first place.
@@ -1070,6 +1079,10 @@ export async function importGltfMeshes(
triangleCount: indices.length / 3,
...(prim.material !== undefined ? { material: materialFor(prim.material) } : {}),
...(skinned ? { skinJoints: skin!.joints } : {}),
+ // The node's own weights override the mesh's: one mesh may be
+ // instanced into several nodes, each holding a different shape.
+ ...(morph ? { morphWeights: meshWeights.get(meshIndex) ?? mesh.weights ?? [] }
+ : {}),
});
} catch (err) {
warnings.push(`${label}: ${err instanceof Error ? err.message : String(err)}`);
diff --git a/pipeline/src/assets/modelImport.ts b/pipeline/src/assets/modelImport.ts
index f0a302c47..cde346ed8 100644
--- a/pipeline/src/assets/modelImport.ts
+++ b/pipeline/src/assets/modelImport.ts
@@ -29,6 +29,8 @@ export interface ImportedMesh {
/** Source node indices of the joints its `Joints` channel indexes, in order.
* Absent for geometry nothing skins. */
skinJoints?: number[];
+ /** The weight each morph target starts at, where the source states them. */
+ morphWeights?: number[];
}
/** Where a material's image comes from: a product this import writes, or a file already on disk. */
@@ -442,6 +444,20 @@ function skinComponent(mesh: ImportedMesh): ComponentData[] {
return [{ type: 'MeshSkin', data: { joints: mesh.skinJoints.map(i => `n${i}`) } }];
}
+/**
+ * The shape this mesh starts in. Written whenever it HAS shapes, even at rest:
+ * the component is what a clip and the inspector address, and a mesh whose
+ * weights arrive only once something moves them is one an author cannot open.
+ */
+function morphComponent(mesh: ImportedMesh): ComponentData[] {
+ const targets = mesh.data.morph?.names.length ?? 0;
+ if (targets === 0) return [];
+ const authored = mesh.morphWeights ?? [];
+ return [{ type: 'MeshMorph', data: {
+ weights: Array.from({ length: targets }, (_, i) => authored[i] ?? 0),
+ } }];
+}
+
/** Only what differs from a Transform's defaults, so a diff shows the placement. */
function transformComponent(trs?: Trs, scale?: number): ComponentData {
const s = trs?.scale ?? [1, 1, 1];
@@ -479,7 +495,8 @@ export function assembleModelPrefab(name: string, meshes: ImportedMesh[],
// One primitive rides the node itself; several cannot, since a MeshRenderer
// draws one mesh — they become its children, at its own origin.
const own = drawn.length === 1 && drawn[0]
- ? [meshComponent(drawn[0], name, refs), ...skinComponent(drawn[0])] : [];
+ ? [meshComponent(drawn[0], name, refs), ...skinComponent(drawn[0]),
+ ...morphComponent(drawn[0])] : [];
const self = entity(id, node.name, parent,
[transformComponent(node, rootScale), ...own]);
entities.push(self);
@@ -489,7 +506,7 @@ export function assembleModelPrefab(name: string, meshes: ImportedMesh[],
self.children.push(childId);
entities.push(entity(childId, mesh.name, id,
[transformComponent(), meshComponent(mesh, name, refs),
- ...skinComponent(mesh)]));
+ ...skinComponent(mesh), ...morphComponent(mesh)]));
});
}
for (const child of node.children) self.children.push(emitNode(child, id));
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 43330e086..2fcf7adc9 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5,7 +5,7 @@ Symbols: 114 public · 94 beta · 1720 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"422d8d4f497e4e40"
+"7aee1689088373e3"
```
## ANCHOR_AXES — const @experimental
@@ -5095,13 +5095,13 @@ aabbMin: [number, number, number]
channels: MeshChannelDesc[]
indices: Uint32Array<ArrayBufferLike>
inverseBindMatrices: Float32Array<ArrayBufferLike> | undefined
-morph: MeshMorphData | undefined
+morph: MeshMorphTargets | undefined
vertexCount: number
vertexStride: number
vertices: Uint8Array<ArrayBufferLike>
```
-## MeshMorphData — interface @experimental
+## MeshMorphTargets — interface @experimental
```
deltas: Float32Array<ArrayBufferLike>
hasNormals: boolean
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 1690633cb..08c5a75b9 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5,7 +5,7 @@ Symbols: 114 public · 99 beta · 1739 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"422d8d4f497e4e40"
+"7aee1689088373e3"
```
## ANCHOR_AXES — const @experimental
@@ -5108,13 +5108,13 @@ aabbMin: [number, number, number]
channels: MeshChannelDesc[]
indices: Uint32Array<ArrayBufferLike>
inverseBindMatrices: Float32Array<ArrayBufferLike> | undefined
-morph: MeshMorphData | undefined
+morph: MeshMorphTargets | undefined
vertexCount: number
vertexStride: number
vertices: Uint8Array<ArrayBufferLike>
```
-## MeshMorphData — interface @experimental
+## MeshMorphTargets — interface @experimental
```
deltas: Float32Array<ArrayBufferLike>
hasNormals: boolean
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 477698b31..2a1bbfb0a 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -5090,13 +5090,13 @@ aabbMin: [number, number, number]
channels: MeshChannelDesc[]
indices: Uint32Array<ArrayBufferLike>
inverseBindMatrices: Float32Array<ArrayBufferLike> | undefined
-morph: MeshMorphData | undefined
+morph: MeshMorphTargets | undefined
vertexCount: number
vertexStride: number
vertices: Uint8Array<ArrayBufferLike>
```
-## MeshMorphData — interface @experimental
+## MeshMorphTargets — interface @experimental
```
deltas: Float32Array<ArrayBufferLike>
hasNormals: boolean
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 78679b76a..16405dd09 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -5090,13 +5090,13 @@ aabbMin: [number, number, number]
channels: MeshChannelDesc[]
indices: Uint32Array<ArrayBufferLike>
inverseBindMatrices: Float32Array<ArrayBufferLike> | undefined
-morph: MeshMorphData | undefined
+morph: MeshMorphTargets | undefined
vertexCount: number
vertexStride: number
vertices: Uint8Array<ArrayBufferLike>
```
-## MeshMorphData — interface @experimental
+## MeshMorphTargets — interface @experimental
```
deltas: Float32Array<ArrayBufferLike>
hasNormals: boolean
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 7832d9101..20c90a6bc 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -31,6 +31,7 @@ addInteractable: (entity: Entity, component: Interactable) => void
addLODGroup: (entity: Entity, component: LODGroup) => void
addLight: (entity: Entity, component: Light) => void
addMeshCollider3D: (entity: Entity, component: MeshCollider3D) => void
+addMeshMorph: (entity: Entity, component: MeshMorph) => void
addMeshRenderer: (entity: Entity, component: MeshRenderer) => void
addMeshSkin: (entity: Entity, component: MeshSkin) => void
addParent: (entity: Entity, component: Parent) => void
@@ -77,6 +78,7 @@ getInteractable: (entity: Entity) => Interactable
getLODGroup: (entity: Entity) => LODGroup
getLight: (entity: Entity) => Light
getMeshCollider3D: (entity: Entity) => MeshCollider3D
+getMeshMorph: (entity: Entity) => MeshMorph
getMeshRenderer: (entity: Entity) => MeshRenderer
getMeshSkin: (entity: Entity) => MeshSkin
getParent: (entity: Entity) => Parent
@@ -119,6 +121,7 @@ hasInteractable: (entity: Entity) => boolean
hasLODGroup: (entity: Entity) => boolean
hasLight: (entity: Entity) => boolean
hasMeshCollider3D: (entity: Entity) => boolean
+hasMeshMorph: (entity: Entity) => boolean
hasMeshRenderer: (entity: Entity) => boolean
hasMeshSkin: (entity: Entity) => boolean
hasParent: (entity: Entity) => boolean
@@ -162,6 +165,7 @@ removeInteractable: (entity: Entity) => void
removeLODGroup: (entity: Entity) => void
removeLight: (entity: Entity) => void
removeMeshCollider3D: (entity: Entity) => void
+removeMeshMorph: (entity: Entity) => void
removeMeshRenderer: (entity: Entity) => void
removeMeshSkin: (entity: Entity) => void
removeParent: (entity: Entity) => void
@@ -320,9 +324,9 @@ meshRenderer_makeAllResident: ((registry: CppRegistry) => number) | undefined
meshRenderer_setGeometry: ((registry: CppRegistry, entity: number, posUvPtr: number, vertexCount: number, colorsPtr: number, indicesPtr: number, indexCount: number) => void) | undefined
meshRenderer_setMaterialAll: ((registry: CppRegistry, materialId: number) => number) | undefined
meshRenderer_setMeshAll: ((registry: CppRegistry, meshHandle: number) => number) | undefined
-mesh_createFromChannels: ((channelsPtr: number, channelCount: number, vertexStride: number, vertexPtr: number, vertexBytes: number, indexPtr: number, indexCount: number, minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number, bindPtr: number, bindFloats: number) => number) | undefined
+mesh_createFromChannels: ((channelsPtr: number, channelCount: number, vertexStride: number, vertexPtr: number, vertexBytes: number, indexPtr: number, indexCount: number, minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number, bindPtr: number, bindFloats: number, morphPtr: number, morphFloats: number, morphTargets: number, morphNormals: number) => number) | undefined
mesh_release: ((meshHandle: number) => void) | undefined
-mesh_rematerializeFromChannels: ((targetHandle: number, channelsPtr: number, channelCount: number, vertexStride: number, vertexPtr: number, vertexBytes: number, indexPtr: number, indexCount: number, minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number, bindPtr: number, bindFloats: number) => number) | undefined
+mesh_rematerializeFromChannels: ((targetHandle: number, channelsPtr: number, channelCount: number, vertexStride: number, vertexPtr: number, vertexBytes: number, indexPtr: number, indexCount: number, minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number, bindPtr: number, bindFloats: number, morphPtr: number, morphFloats: number, morphTargets: number, morphNormals: number) => number) | undefined
notifyDeviceLost: ((reason: number, message: string) => void) | undefined
particle_getAliveCount: ((entity: number) => number) | undefined
particle_play: ((registry: CppRegistry, entity: number) => void) | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 39ebf36dc..e6cbc695d 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -5097,13 +5097,13 @@ aabbMin: [number, number, number]
channels: MeshChannelDesc[]
indices: Uint32Array<ArrayBufferLike>
inverseBindMatrices: Float32Array<ArrayBufferLike> | undefined
-morph: MeshMorphData | undefined
+morph: MeshMorphTargets | undefined
vertexCount: number
vertexStride: number
vertices: Uint8Array<ArrayBufferLike>
```
-## MeshMorphData — interface @experimental
+## MeshMorphTargets — interface @experimental
```
deltas: Float32Array<ArrayBufferLike>
hasNormals: boolean
diff --git a/sdk/src/asset/loaders/MeshAssetLoader.ts b/sdk/src/asset/loaders/MeshAssetLoader.ts
index 654aec1e2..9ba78cffa 100644
--- a/sdk/src/asset/loaders/MeshAssetLoader.ts
+++ b/sdk/src/asset/loaders/MeshAssetLoader.ts
@@ -80,6 +80,11 @@ export class MeshAssetLoader implements AssetLoader<MeshResult> {
// guess what a vertex is bound to.
const bind = mesh.inverseBindMatrices;
const bindPtr = bind ? alloc(bind.byteLength) : 0;
+ // The shapes go over for the same reason: a delta is addressed by a
+ // vertex index, so the engine holding one without the other could
+ // only guess which vertex a shape moves.
+ const morph = mesh.morph;
+ const morphPtr = morph ? alloc(morph.deltas.byteLength) : 0;
m!.HEAPU8.set(table, tablePtr);
m!.HEAPU8.set(mesh.vertices, vertexPtr);
m!.HEAPU8.set(new Uint8Array(mesh.indices.buffer, mesh.indices.byteOffset,
@@ -88,6 +93,14 @@ export class MeshAssetLoader implements AssetLoader<MeshResult> {
m!.HEAPU8.set(new Uint8Array(bind.buffer, bind.byteOffset, bind.byteLength),
bindPtr);
}
+ if (morph) {
+ m!.HEAPU8.set(new Uint8Array(morph.deltas.buffer, morph.deltas.byteOffset,
+ morph.deltas.byteLength), morphPtr);
+ }
+ const shapes: [number, number, number, number] = [
+ morphPtr, morph?.deltas.length ?? 0, morph?.names.length ?? 0,
+ morph?.hasNormals ? 1 : 0,
+ ];
return mint
? m!.mesh_createFromChannels!(
tablePtr, mesh.channels.length, mesh.vertexStride,
@@ -95,7 +108,7 @@ export class MeshAssetLoader implements AssetLoader<MeshResult> {
indexPtr, mesh.indices.length,
mesh.aabbMin[0], mesh.aabbMin[1], mesh.aabbMin[2],
mesh.aabbMax[0], mesh.aabbMax[1], mesh.aabbMax[2],
- bindPtr, bind?.length ?? 0)
+ bindPtr, bind?.length ?? 0, ...shapes)
: m!.mesh_rematerializeFromChannels!(
target,
tablePtr, mesh.channels.length, mesh.vertexStride,
@@ -103,7 +116,7 @@ export class MeshAssetLoader implements AssetLoader<MeshResult> {
indexPtr, mesh.indices.length,
mesh.aabbMin[0], mesh.aabbMin[1], mesh.aabbMin[2],
mesh.aabbMax[0], mesh.aabbMax[1], mesh.aabbMax[2],
- bindPtr, bind?.length ?? 0);
+ bindPtr, bind?.length ?? 0, ...shapes);
});
}
diff --git a/sdk/src/asset/meshFormat.ts b/sdk/src/asset/meshFormat.ts
index 733a18a6a..756d527ca 100644
--- a/sdk/src/asset/meshFormat.ts
+++ b/sdk/src/asset/meshFormat.ts
@@ -79,7 +79,7 @@ export interface MeshChannelDesc {
* carries. Deltas rather than whole positions because a target usually moves a
* fraction of the mesh, and what is stored is then zero wherever it says nothing.
*/
-export interface MeshMorphData {
+export interface MeshMorphTargets {
/** One name per target, in the order weights address them. */
names: string[];
/** Whether each target carries a normal delta behind its position delta.
@@ -117,7 +117,7 @@ export interface MeshData {
* vertex per target, so a file carrying the two apart could not say which
* vertex a delta moves.
*/
- morph?: MeshMorphData;
+ morph?: MeshMorphTargets;
}
/** Bytes one component of a channel type occupies. */
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 9769229ef..14807b4be 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -130,7 +130,7 @@ export { setTextureBudget, getResourceStats, trimTextureCache, type ResourceStat
*/
export {
MeshChannel, MeshChannelType, MESH_MAX_BONES, packChannels, encodeMesh, decodeMesh,
- encodeChannelTable, type MeshChannelDesc, type MeshData, type MeshMorphData,
+ encodeChannelTable, type MeshChannelDesc, type MeshData, type MeshMorphTargets,
} from './asset/meshFormat';
export type { MeshResult } from './asset/loaders/MeshAssetLoader';
/**
diff --git a/sdk/src/ecs/bridge/BuiltinBridge.ts b/sdk/src/ecs/bridge/BuiltinBridge.ts
index 298571ea8..e28edaa16 100644
--- a/sdk/src/ecs/bridge/BuiltinBridge.ts
+++ b/sdk/src/ecs/bridge/BuiltinBridge.ts
@@ -70,9 +70,12 @@ export function convertForWasm(
return obj;
}
-/** An embind std::vector<Entity>, which its owner has to free. */
+/** An embind std::vector, which its owner has to free. */
interface WasmVector { push_back(v: number): void; delete(): void }
+/** The read side of one: what a component's list field comes back as. */
+interface WasmVectorRead { size(): number; get(i: number): number; delete(): void }
+
/**
* Replace a LIST of entities with the vector embind expects, returning the ones
* created so the caller can free them — an embind vector is a heap object.
@@ -96,6 +99,58 @@ export function materializeEntityVectors(
return made;
}
+/**
+ * Replace a list of NUMBERS with the vector embind expects, returning the ones
+ * created so the caller can free them. The same boundary
+ * {@link materializeEntityVectors} crosses, for values rather than references.
+ */
+export function materializeNumberVectors(
+ obj: Record<string, unknown>, fields: readonly string[],
+ module: { VectorFloat?: new () => WasmVector } | null,
+): WasmVector[] {
+ const made: WasmVector[] = [];
+ if (!module?.VectorFloat) return made;
+ for (const key of fields) {
+ const val = obj[key];
+ if (!Array.isArray(val)) continue;
+ const vec = new module.VectorFloat();
+ for (const n of val) vec.push_back(Number(n));
+ obj[key] = vec;
+ made.push(vec);
+ }
+ return made;
+}
+
+/**
+ * Snapshot a component's list fields back into JS arrays, freeing the embind
+ * vectors they came back as.
+ *
+ * Read here and not left to the caller: an embind vector is a heap object that
+ * leaks unless freed, and an array is what everything above this already speaks.
+ */
+/**
+ * Which of a builtin's fields hold a list of numbers. Read off the generated
+ * metadata rather than carried on the component definition: that definition is
+ * a public type, and how a field crosses THIS boundary is not part of it.
+ */
+function numberListFieldsOf(cppName: string): readonly string[] {
+ return (COMPONENT_META[cppName]?.numberListFields ?? []) as readonly string[];
+}
+
+export function snapshotNumberVectors(
+ obj: Record<string, unknown>, fields: readonly string[],
+): Record<string, unknown> {
+ for (const key of fields) {
+ const vec = obj[key] as WasmVectorRead | undefined;
+ if (!vec || typeof vec.size !== 'function') continue;
+ const out: number[] = [];
+ for (let i = 0; i < vec.size(); i++) out.push(vec.get(i));
+ obj[key] = out;
+ vec.delete();
+ }
+ return obj;
+}
+
// =============================================================================
// Pointer-based Field Access
// =============================================================================
@@ -776,6 +831,9 @@ export class BuiltinBridge {
const vectors = materializeEntityVectors(
payload, component.entityFields ?? [],
this.module_ as unknown as { VectorEntity?: new () => WasmVector } | null);
+ vectors.push(...materializeNumberVectors(
+ payload, numberListFieldsOf(component._cppName),
+ this.module_ as unknown as { VectorFloat?: new () => WasmVector } | null));
try {
methods.add(entity, payload);
} finally {
@@ -802,7 +860,8 @@ export class BuiltinBridge {
try {
const raw = this.getBuiltinMethods(component._cppName).get(entity);
return convertFromWasm(
- raw as Record<string, unknown>,
+ snapshotNumberVectors(raw as Record<string, unknown>,
+ numberListFieldsOf(component._cppName)),
component.colorKeys,
) as T;
} catch (e) {
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index 3a994f3e7..179f624b6 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -75,9 +75,9 @@ export interface NativeEngineApi {
meshRenderer_setGeometry?(registry: unknown, entity: number, posUvPtr: number, vertexCount: number, colorsPtr: number, indicesPtr: number, indexCount: number): void;
meshRenderer_setMaterialAll?(registry: unknown, materialId: number): number;
meshRenderer_setMeshAll?(registry: unknown, meshHandle: number): number;
- mesh_createFromChannels?(channelsPtr: number, channelCount: number, vertexStride: number, vertexPtr: number, vertexBytes: number, indexPtr: number, indexCount: number, minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number, bindPtr: number, bindFloats: number): number;
+ mesh_createFromChannels?(channelsPtr: number, channelCount: number, vertexStride: number, vertexPtr: number, vertexBytes: number, indexPtr: number, indexCount: number, minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number, bindPtr: number, bindFloats: number, morphPtr: number, morphFloats: number, morphTargets: number, morphNormals: number): number;
mesh_release?(meshHandle: number): void;
- mesh_rematerializeFromChannels?(targetHandle: number, channelsPtr: number, channelCount: number, vertexStride: number, vertexPtr: number, vertexBytes: number, indexPtr: number, indexCount: number, minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number, bindPtr: number, bindFloats: number): number;
+ mesh_rematerializeFromChannels?(targetHandle: number, channelsPtr: number, channelCount: number, vertexStride: number, vertexPtr: number, vertexBytes: number, indexPtr: number, indexCount: number, minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number, bindPtr: number, bindFloats: number, morphPtr: number, morphFloats: number, morphTargets: number, morphNormals: number): number;
particle_getAliveCount?(entity: number): number;
particle_play?(registry: unknown, entity: number): void;
particle_reset?(registry: unknown, entity: number): void;
diff --git a/sdk/src/ecs/bridge/nativeRegistry.ts b/sdk/src/ecs/bridge/nativeRegistry.ts
index e39da7c74..3724d0c8c 100644
--- a/sdk/src/ecs/bridge/nativeRegistry.ts
+++ b/sdk/src/ecs/bridge/nativeRegistry.ts
@@ -144,6 +144,32 @@ export function createNativeRegistry(
hostCall(scope, REGISTRY_BINDINGS.setMeshSkinJoints, [e, [...(data.joints ?? [])]]);
};
+ // The rest of the components a variable-length field keeps out of the buffer
+ // loop below. Driven by the metadata rather than named one at a time: their
+ // accessors are GENERATED, so a new number list needs no edit here.
+ for (const [cppName, meta] of Object.entries(COMPONENT_META)) {
+ const fields = (meta?.numberListFields ?? []) as readonly string[];
+ if (!fields.length || PTR_ACCESSORS[cppName]) continue;
+ reg[`has${cppName}`] = (e: Entity): boolean =>
+ !!hostCallOpt(scope, `es_${cppName}_has`, [e]);
+ reg[`remove${cppName}`] = (e: Entity): void => {
+ hostCallOpt(scope, `es_${cppName}_remove`, [e]);
+ };
+ reg[`get${cppName}`] = (e: Entity): Record<string, unknown> => {
+ const out: Record<string, unknown> = {};
+ for (const f of fields) {
+ out[f] = hostCallOpt(scope, `es_${cppName}_${f}_get`, [e]) ?? [];
+ }
+ return out;
+ };
+ reg[`add${cppName}`] = (e: Entity, data: Record<string, unknown>): void => {
+ for (const f of fields) {
+ hostCallOpt(scope, `es_${cppName}_${f}_set`,
+ [e, [...((data[f] as Iterable<number>) ?? [])]]);
+ }
+ };
+ }
+
reg.delete = (): void => {};
// The scene queries the wasm module answers as module-level functions. There is
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 1a23a1614..e779b92ab 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -15,7 +15,7 @@ import type { AlignContent, AlignItems, AlignSelf, BodyType, CanvasScaleMode, Cl
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '422d8d4f497e4e40';
+export const ABI_LAYOUT_HASH = '7aee1689088373e3';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -75,6 +75,13 @@ export interface ComponentMetaEntry {
* and keep the hand-written pair the registry wires them by.
*/
listFields?: string[];
+ /**
+ * List fields whose elements are NUMBERS, which the web boundary
+ * marshals as a registered embind vector rather than a JS array.
+ * Apart from `entityFields`: that list also re-aims references when
+ * a prefab is instantiated, and a weight is a value, not a reference.
+ */
+ numberListFields?: string[];
colorFields: string[];
animatableFields: string[];
/**
@@ -518,6 +525,20 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
layer: { min: 0, max: 15, advanced: true },
},
},
+ MeshMorph: {
+ defaults: {
+ weights: [],
+ },
+ assetFields: [],
+ entityFields: [],
+ listFields: ['weights'],
+ numberListFields: ['weights'],
+ colorFields: [],
+ animatableFields: ['weights'],
+ fields: {
+ weights: { tooltip: "Weight per morph target of the mesh, in the order the mesh carries them." },
+ },
+ },
MeshRenderer: {
defaults: {
texture: 0,
@@ -1377,6 +1398,10 @@ export interface MeshCollider3DData {
enabled: boolean;
}
+export interface MeshMorphData {
+ weights: number[];
+}
+
export interface MeshRendererData {
texture: number;
normalMap: number;
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 148a63d1b..5b5021f85 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -264,7 +264,9 @@ export interface ESEngineModule {
indexPtr: number, indexCount: number,
minX: number, minY: number, minZ: number,
maxX: number, maxY: number, maxZ: number,
- bindPtr: number, bindFloats: number): number;
+ bindPtr: number, bindFloats: number,
+ morphPtr: number, morphFloats: number,
+ morphTargets: number, morphNormals: number): number;
/**
* Put replayed geometry behind an EXISTING mesh handle after a device loss.
* Returns the handle it was given, or 0 if the engine refused — never a new
@@ -278,7 +280,9 @@ export interface ESEngineModule {
indexPtr: number, indexCount: number,
minX: number, minY: number, minZ: number,
maxX: number, maxY: number, maxZ: number,
- bindPtr: number, bindFloats: number): number;
+ bindPtr: number, bindFloats: number,
+ morphPtr: number, morphFloats: number,
+ morphTargets: number, morphNormals: number): number;
/**
* The renderer's program-readiness epoch. Advanced whenever programs that
* WERE ready go cold, so a readiness record carrying an older one is naming
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index be5c33bdb..395001fa3 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -21,6 +21,14 @@ export interface VectorEntity {
delete(): void;
}
+export interface VectorFloat {
+ size(): number;
+ get(index: number): number;
+ push_back(value: number): void;
+ set(index: number, value: number): boolean;
+ delete(): void;
+}
+
// Enums
export enum AlignContent {
@@ -571,6 +579,10 @@ export interface MeshCollider3D {
enabled: boolean;
}
+export interface MeshMorph {
+ weights: VectorFloat;
+}
+
export interface MeshRenderer {
texture: number;
normalMap: number;
@@ -960,6 +972,10 @@ export interface Registry {
getMeshCollider3D(entity: Entity): MeshCollider3D;
addMeshCollider3D(entity: Entity, component: MeshCollider3D): void;
removeMeshCollider3D(entity: Entity): void;
+ hasMeshMorph(entity: Entity): boolean;
+ getMeshMorph(entity: Entity): MeshMorph;
+ addMeshMorph(entity: Entity, component: MeshMorph): void;
+ removeMeshMorph(entity: Entity): void;
hasMeshRenderer(entity: Entity): boolean;
getMeshRenderer(entity: Entity): MeshRenderer;
addMeshRenderer(entity: Entity, component: MeshRenderer): void;
@@ -1088,6 +1104,7 @@ export interface ESEngineModule {
LODGroup: new () => LODGroup;
Light: new () => Light;
MeshCollider3D: new () => MeshCollider3D;
+ MeshMorph: new () => MeshMorph;
MeshRenderer: new () => MeshRenderer;
MeshSkin: new () => MeshSkin;
Parent: new () => Parent;
diff --git a/src/esengine/aot/AotComponents.generated.cpp b/src/esengine/aot/AotComponents.generated.cpp
index fc91c4d1a..4424b8a9b 100644
--- a/src/esengine/aot/AotComponents.generated.cpp
+++ b/src/esengine/aot/AotComponents.generated.cpp
@@ -152,6 +152,11 @@ ComponentAt engineComponentAt(ecs::Registry& registry, const char* name) {
return registry.tryGet<esengine::ecs::MeshCollider3D>(Entity::fromRaw(raw));
};
}
+ if (std::strcmp(name, "MeshMorph") == 0) {
+ return [&registry](std::uint32_t raw) -> void* {
+ return registry.tryGet<esengine::ecs::MeshMorph>(Entity::fromRaw(raw));
+ };
+ }
if (std::strcmp(name, "MeshRenderer") == 0) {
return [&registry](std::uint32_t raw) -> void* {
return registry.tryGet<esengine::ecs::MeshRenderer>(Entity::fromRaw(raw));
@@ -366,6 +371,11 @@ CandidatesOf engineComponentCandidates(ecs::Registry& registry, const char* name
return denseAsIds(registry.entitiesWith<esengine::ecs::MeshCollider3D>());
};
}
+ if (std::strcmp(name, "MeshMorph") == 0) {
+ return [&registry]() -> Candidates {
+ return denseAsIds(registry.entitiesWith<esengine::ecs::MeshMorph>());
+ };
+ }
if (std::strcmp(name, "MeshRenderer") == 0) {
return [&registry]() -> Candidates {
return denseAsIds(registry.entitiesWith<esengine::ecs::MeshRenderer>());
@@ -508,6 +518,7 @@ bool isEngineComponent(const char* name) {
if (std::strcmp(name, "LODGroup") == 0) return true;
if (std::strcmp(name, "Light") == 0) return true;
if (std::strcmp(name, "MeshCollider3D") == 0) return true;
+ if (std::strcmp(name, "MeshMorph") == 0) return true;
if (std::strcmp(name, "MeshRenderer") == 0) return true;
if (std::strcmp(name, "MeshSkin") == 0) return true;
if (std::strcmp(name, "Parent") == 0) return true;
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index dc264485f..783742787 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash aa777eab55be0aa1
+ * @schema_hash 568d2025de148a47
*/
-#define ES_EDITOR_API_SCHEMA_HASH "aa777eab55be0aa1"
+#define ES_EDITOR_API_SCHEMA_HASH "568d2025de148a47"
#include <emscripten/bind.h>
#include <string>
@@ -82,6 +82,7 @@ std::vector<std::string> editor_getComponentNames() {
"LODGroup",
"Light",
"MeshCollider3D",
+ "MeshMorph",
"MeshRenderer",
"MeshSkin",
"Parent",
@@ -355,6 +356,9 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"layer","type":"int","group":"MeshCollider3D"},
{"key":"enabled","type":"bool","group":"MeshCollider3D"}
])JSON";
+ } else if (name == "MeshMorph") {
+ return R"JSON([
+ ])JSON";
} else if (name == "MeshRenderer") {
return R"JSON([
{"key":"texture","type":"asset","group":"MeshRenderer"},
@@ -806,6 +810,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "MeshCollider3D") {
if (!reg.has<esengine::ecs::MeshCollider3D>(entity)) reg.emplace<esengine::ecs::MeshCollider3D>(entity);
return true;
+ } else if (name == "MeshMorph") {
+ if (!reg.has<esengine::ecs::MeshMorph>(entity)) reg.emplace<esengine::ecs::MeshMorph>(entity);
+ return true;
} else if (name == "MeshRenderer") {
if (!reg.has<esengine::ecs::MeshRenderer>(entity)) reg.emplace<esengine::ecs::MeshRenderer>(entity);
return true;
@@ -924,6 +931,8 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
if (reg.has<esengine::ecs::Light>(entity)) { reg.remove<esengine::ecs::Light>(entity); return true; }
} else if (name == "MeshCollider3D") {
if (reg.has<esengine::ecs::MeshCollider3D>(entity)) { reg.remove<esengine::ecs::MeshCollider3D>(entity); return true; }
+ } else if (name == "MeshMorph") {
+ if (reg.has<esengine::ecs::MeshMorph>(entity)) { reg.remove<esengine::ecs::MeshMorph>(entity); return true; }
} else if (name == "MeshRenderer") {
if (reg.has<esengine::ecs::MeshRenderer>(entity)) { reg.remove<esengine::ecs::MeshRenderer>(entity); return true; }
} else if (name == "MeshSkin") {
@@ -997,6 +1006,7 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (name == "LODGroup") return reg.has<esengine::ecs::LODGroup>(entity);
if (name == "Light") return reg.has<esengine::ecs::Light>(entity);
if (name == "MeshCollider3D") return reg.has<esengine::ecs::MeshCollider3D>(entity);
+ if (name == "MeshMorph") return reg.has<esengine::ecs::MeshMorph>(entity);
if (name == "MeshRenderer") return reg.has<esengine::ecs::MeshRenderer>(entity);
if (name == "MeshSkin") return reg.has<esengine::ecs::MeshSkin>(entity);
if (name == "Parent") return reg.has<esengine::ecs::Parent>(entity);
@@ -1048,6 +1058,7 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (reg.has<esengine::ecs::LODGroup>(entity)) result.push_back("LODGroup");
if (reg.has<esengine::ecs::Light>(entity)) result.push_back("Light");
if (reg.has<esengine::ecs::MeshCollider3D>(entity)) result.push_back("MeshCollider3D");
+ if (reg.has<esengine::ecs::MeshMorph>(entity)) result.push_back("MeshMorph");
if (reg.has<esengine::ecs::MeshRenderer>(entity)) result.push_back("MeshRenderer");
if (reg.has<esengine::ecs::MeshSkin>(entity)) result.push_back("MeshSkin");
if (reg.has<esengine::ecs::Parent>(entity)) result.push_back("Parent");
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 919bf8aa1..e552d9bad 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -253,6 +253,7 @@ struct MeshUpload {
u32 indexCount = 0;
const f32* bind = nullptr;
u32 bindFloats = 0;
+ MeshMorphSource morph;
glm::vec3 localMin{0.0f};
glm::vec3 localMax{0.0f};
@@ -274,7 +275,9 @@ bool marshalMeshChannels(MeshUpload& out, const char* who,
uintptr_t indexPtr, u32 indexCount,
f32 minX, f32 minY, f32 minZ,
f32 maxX, f32 maxY, f32 maxZ,
- uintptr_t bindPtr, u32 bindFloats) {
+ uintptr_t bindPtr, u32 bindFloats,
+ uintptr_t morphPtr, u32 morphFloats,
+ u32 morphTargets, u32 morphNormals) {
if (channelCount == 0 || channelCount > MAX_VERTEX_ATTRIBUTES) return false;
if (vertexStride == 0 || vertexBytes == 0 || indexCount == 0) return false;
if (indexCount % 3 != 0) {
@@ -321,6 +324,13 @@ bool marshalMeshChannels(MeshUpload& out, const char* who,
// it; a mesh with joints and no matrices is drawn static rather than wrong.
out.bind = bindFloats > 0 ? boundarySpan<f32>(bindPtr, bindFloats, who) : nullptr;
out.bindFloats = bindFloats;
+ // The shapes ride with the vertices for the reason the bind pose does: a
+ // delta is addressed BY a vertex index, so the two are one statement.
+ if (morphTargets > 0 && morphFloats > 0) {
+ if (const f32* deltas = boundarySpan<f32>(morphPtr, morphFloats, who)) {
+ out.morph = {ConstSpan<f32>(deltas, morphFloats), morphTargets, morphNormals != 0};
+ }
+ }
out.channelCount = channelCount;
out.vertexStride = vertexStride;
out.verts = verts;
@@ -342,18 +352,21 @@ u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexS
uintptr_t indexPtr, u32 indexCount,
f32 minX, f32 minY, f32 minZ,
f32 maxX, f32 maxY, f32 maxZ,
- uintptr_t bindPtr, u32 bindFloats) {
+ uintptr_t bindPtr, u32 bindFloats,
+ uintptr_t morphPtr, u32 morphFloats,
+ u32 morphTargets, u32 morphNormals) {
auto* rm = ctx().tryGet<resource::ResourceManager>();
MeshUpload up;
if (!rm || !marshalMeshChannels(up, "mesh_createFromChannels",
channelsPtr, channelCount, vertexStride,
vertexPtr, vertexBytes, indexPtr, indexCount,
- minX, minY, minZ, maxX, maxY, maxZ, bindPtr, bindFloats)) {
+ minX, minY, minZ, maxX, maxY, maxZ, bindPtr, bindFloats,
+ morphPtr, morphFloats, morphTargets, morphNormals)) {
return 0;
}
auto handle = rm->createMesh(up.vertexSpan(), up.indexSpan(), up.channelSpan(), up.vertexStride,
up.localMin, up.localMax,
- MeshRecovery::SourceReplayable, up.bindSpan());
+ MeshRecovery::SourceReplayable, up.bindSpan(), up.morph);
return handle.id();
}
@@ -366,19 +379,23 @@ u32 mesh_rematerializeFromChannels(u32 targetHandle,
uintptr_t indexPtr, u32 indexCount,
f32 minX, f32 minY, f32 minZ,
f32 maxX, f32 maxY, f32 maxZ,
- uintptr_t bindPtr, u32 bindFloats) {
+ uintptr_t bindPtr, u32 bindFloats,
+ uintptr_t morphPtr, u32 morphFloats,
+ u32 morphTargets, u32 morphNormals) {
auto* rm = ctx().tryGet<resource::ResourceManager>();
MeshUpload up;
if (!rm || targetHandle == 0
|| !marshalMeshChannels(up, "mesh_rematerializeFromChannels",
channelsPtr, channelCount, vertexStride,
vertexPtr, vertexBytes, indexPtr, indexCount,
- minX, minY, minZ, maxX, maxY, maxZ, bindPtr, bindFloats)) {
+ minX, minY, minZ, maxX, maxY, maxZ, bindPtr, bindFloats,
+ morphPtr, morphFloats, morphTargets, morphNormals)) {
return 0;
}
return rm->rematerializeMesh(resource::MeshHandle(targetHandle),
up.vertexSpan(), up.indexSpan(), up.channelSpan(),
- up.vertexStride, up.localMin, up.localMax, up.bindSpan())
+ up.vertexStride, up.localMin, up.localMax, up.bindSpan(),
+ up.morph)
? targetHandle : 0;
}
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index 1125e163d..fc50fa4f4 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -76,7 +76,9 @@ u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexS
uintptr_t indexPtr, u32 indexCount,
f32 minX, f32 minY, f32 minZ,
f32 maxX, f32 maxY, f32 maxZ,
- uintptr_t bindPtr, u32 bindFloats);
+ uintptr_t bindPtr, u32 bindFloats,
+ uintptr_t morphPtr, u32 morphFloats,
+ u32 morphTargets, u32 morphNormals);
/** @brief Releases a mesh and the buffers it owns. */
/** @brief Puts replayed geometry behind an EXISTING mesh handle after a device
* loss. Returns @p targetHandle on success, 0 on failure — never a new
@@ -87,7 +89,9 @@ u32 mesh_rematerializeFromChannels(u32 targetHandle,
uintptr_t indexPtr, u32 indexCount,
f32 minX, f32 minY, f32 minZ,
f32 maxX, f32 maxY, f32 maxZ,
- uintptr_t bindPtr, u32 bindFloats);
+ uintptr_t bindPtr, u32 bindFloats,
+ uintptr_t morphPtr, u32 morphFloats,
+ u32 morphTargets, u32 morphNormals);
void mesh_release(u32 meshHandle);
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index f44e45d02..c32bc3e1a 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -1451,6 +1451,8 @@ UIVisualJS uivisualToJS(const esengine::ecs::UIVisual& c) {
EMSCRIPTEN_BINDINGS(esengine_components) {
register_vector<u32>("VectorEntity");
+ register_vector<f32>("VectorFloat");
+
value_object<BitmapTextJS>("BitmapText")
.field("text", &BitmapTextJS::text)
.field("color", &BitmapTextJS::color)
@@ -1640,6 +1642,9 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("layer", &MeshCollider3DJS::layer)
.field("enabled", &MeshCollider3DJS::enabled);
+ value_object<esengine::ecs::MeshMorph>("MeshMorph")
+ .field("weights", &esengine::ecs::MeshMorph::weights);
+
value_object<MeshRendererJS>("MeshRenderer")
.field("texture", &MeshRendererJS::texture)
.field("normalMap", &MeshRendererJS::normalMap)
@@ -2352,6 +2357,27 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::MeshCollider3D>(entity);
}))
+ // MeshMorph
+ .function("hasMeshMorph", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::MeshMorph>(static_cast<Entity>(e));
+ }))
+ .function("getMeshMorph", optional_override([](Registry& r, u32 e) -> esengine::ecs::MeshMorph& {
+ auto entity = static_cast<Entity>(e);
+ static esengine::ecs::MeshMorph s_dummy{};
+ if (!r.valid(entity) || !r.has<esengine::ecs::MeshMorph>(entity)) return s_dummy;
+ return r.get<esengine::ecs::MeshMorph>(entity);
+ }), allow_raw_pointers())
+ .function("addMeshMorph", optional_override([](Registry& r, u32 e, const esengine::ecs::MeshMorph& c) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ r.emplaceOrReplace<esengine::ecs::MeshMorph>(entity, c);
+ }))
+ .function("removeMeshMorph", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::MeshMorph>(entity)) return;
+ r.remove<esengine::ecs::MeshMorph>(entity);
+ }))
+
// MeshRenderer
.function("hasMeshRenderer", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::MeshRenderer>(static_cast<Entity>(e));
@@ -2930,6 +2956,7 @@ emscripten::val esengineGetBuiltinComponentNames() {
arr.set(i++, val(std::string("LODGroup")));
arr.set(i++, val(std::string("Light")));
arr.set(i++, val(std::string("MeshCollider3D")));
+ arr.set(i++, val(std::string("MeshMorph")));
arr.set(i++, val(std::string("MeshRenderer")));
arr.set(i++, val(std::string("MeshSkin")));
arr.set(i++, val(std::string("Parent")));
@@ -3352,7 +3379,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "422d8d4f497e4e40";
+static const char* kEsAbiLayoutHash = "7aee1689088373e3";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/data/shaders/mesh.esshader b/src/esengine/data/shaders/mesh.esshader
index 00912955e..1f1d61536 100644
--- a/src/esengine/data/shaders/mesh.esshader
+++ b/src/esengine/data/shaders/mesh.esshader
@@ -75,6 +75,38 @@ layout(std140) uniform SkinConstants {
};
#endif
+// The shapes this draw is blended towards. Declared unconditionally and NOT as a
+// feature: whether a draw has any is a number in the block, and making it a
+// program instead would double this shader's variants and every material's with
+// them — for a branch whose condition is the same at every vertex of a draw.
+layout(std140) uniform MorphConstants {
+ // x = live shapes, y = vertices, z = texels per vertex, w = texture width.
+ vec4 u_morphInfo;
+ vec4 u_morphShape[8];
+};
+// The deltas: one texel per (target, vertex), and a second behind it where the
+// targets bend normals. A texture because they are megabytes, and a uniform
+// block is not.
+uniform highp sampler2D u_morphDeltas;
+
+vec3 morphDelta(float index) {
+ float width = u_morphInfo.w;
+ return texelFetch(u_morphDeltas, ivec2(int(mod(index, width)), int(index / width)), 0).xyz;
+}
+
+// Before the pose, never after: a target was authored against the mesh at rest,
+// so the offset it states is a local one.
+void applyMorph(inout vec3 position, inout vec3 normal) {
+ int live = int(u_morphInfo.x);
+ float perVertex = u_morphInfo.z;
+ for (int i = 0; i < 8; i++) {
+ if (i >= live) break;
+ float at = (u_morphShape[i].x * u_morphInfo.y + float(gl_VertexID)) * perVertex;
+ position += u_morphShape[i].y * morphDelta(at);
+ if (perVertex > 1.5) normal += u_morphShape[i].y * morphDelta(at + 1.0);
+ }
+}
+
out vec2 v_texCoord;
out vec4 v_color;
#ifdef LIT
@@ -94,6 +126,13 @@ out highp vec4 v_shadowClip;
#endif
void main() {
+ vec3 local = a_position;
+#ifdef MESH_NORMALS
+ vec3 localNormal = a_normal;
+#else
+ vec3 localNormal = vec3(0.0, 0.0, 1.0);
+#endif
+ applyMorph(local, localNormal);
#ifdef SKINNED
// The four bones this vertex is bound to, blended by their weights. The
// result is world-space, so no model matrix follows it.
@@ -101,10 +140,10 @@ void main() {
+ a_weights.y * u_bones[a_joints.y]
+ a_weights.z * u_bones[a_joints.z]
+ a_weights.w * u_bones[a_joints.w];
- vec4 world = skin * vec4(a_position, 1.0);
+ vec4 world = skin * vec4(local, 1.0);
#else
mat4 model = mat4(a_model0, a_model1, a_model2, a_model3);
- vec4 world = model * vec4(a_position, 1.0);
+ vec4 world = model * vec4(local, 1.0);
#endif
gl_Position = u_projection * world;
v_texCoord = a_texCoord;
@@ -114,9 +153,9 @@ void main() {
#endif
#ifdef LIT
#if defined(MESH_NORMALS) && defined(SKINNED)
- v_worldNormal = mat3(skin) * a_normal;
+ v_worldNormal = mat3(skin) * localNormal;
#elif defined(MESH_NORMALS)
- v_worldNormal = mat3(a_nrm0, a_nrm1, a_nrm2) * a_normal;
+ v_worldNormal = mat3(a_nrm0, a_nrm1, a_nrm2) * localNormal;
#else
// A surface with no normal channel faces the viewer, exactly as a sprite does.
v_worldNormal = vec3(0.0, 0.0, 1.0);
@@ -179,6 +218,19 @@ struct SkinConstants { bones : array<mat4x4f, 64> };
@group(0) @binding(5) var<uniform> skin : SkinConstants;
#endif
+// The GLSL twin's MorphConstants, and for the same reason unconditional. The
+// texture is declared HERE, in the vertex stage, which is what tells the backend
+// that unit 4 has to be visible to it — group-1 textures are fragment-only
+// otherwise (see SkinConstants.hpp, which chose a block over a texture for it).
+struct MorphConstants { info : vec4f, shape : array<vec4f, 8> };
+@group(0) @binding(6) var<uniform> morph : MorphConstants;
+@group(1) @binding(4) var t4 : texture_2d<f32>;
+
+fn morphDelta(index : f32) -> vec3f {
+ let width = morph.info.w;
+ return textureLoad(t4, vec2i(i32(index % width), i32(index / width)), 0).xyz;
+}
+
struct VSIn {
@location(0) a_position : vec3f,
@location(1) a_color : vec4f,
@@ -196,6 +248,8 @@ struct VSIn {
@location(11) a_model3 : vec4f,
#endif
@location(12) a_instTint : vec4f,
+ // What the GLSL twin reads as gl_VertexID: a morph delta is addressed by it.
+ @builtin(vertex_index) vertexIndex : u32,
#ifdef MESH_NORMALS
#ifndef SKINNED
@location(13) a_nrm0 : vec3f,
@@ -219,6 +273,23 @@ struct VSOut {
};
@vertex fn vs_main(v : VSIn) -> VSOut {
+ var local = v.a_position;
+#ifdef MESH_NORMALS
+ var localNormal = v.a_normal;
+#else
+ var localNormal = vec3f(0.0, 0.0, 1.0);
+#endif
+ // Before the pose, never after: a target was authored against the mesh at
+ // rest, so the offset it states is a local one.
+ let live = i32(morph.info.x);
+ for (var i = 0; i < 8; i = i + 1) {
+ if (i >= live) { break; }
+ let at = (morph.shape[i].x * morph.info.y + f32(v.vertexIndex)) * morph.info.z;
+ local = local + morph.shape[i].y * morphDelta(at);
+ if (morph.info.z > 1.5) {
+ localNormal = localNormal + morph.shape[i].y * morphDelta(at + 1.0);
+ }
+ }
#ifdef SKINNED
// The four bones this vertex is bound to, blended by their weights. The
// result is world-space, so no model matrix follows it.
@@ -226,10 +297,10 @@ struct VSOut {
+ v.a_weights.y * skin.bones[v.a_joints.y]
+ v.a_weights.z * skin.bones[v.a_joints.z]
+ v.a_weights.w * skin.bones[v.a_joints.w];
- let world = pose * vec4f(v.a_position, 1.0);
+ let world = pose * vec4f(local, 1.0);
#else
let model = mat4x4f(v.a_model0, v.a_model1, v.a_model2, v.a_model3);
- let world = model * vec4f(v.a_position, 1.0);
+ let world = model * vec4f(local, 1.0);
#endif
var out : VSOut;
@@ -242,9 +313,9 @@ struct VSOut {
#ifdef LIT
#ifdef MESH_NORMALS
#ifdef SKINNED
- out.v_worldNormal = mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * v.a_normal;
+ out.v_worldNormal = mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * localNormal;
#else
- out.v_worldNormal = mat3x3f(v.a_nrm0, v.a_nrm1, v.a_nrm2) * v.a_normal;
+ out.v_worldNormal = mat3x3f(v.a_nrm0, v.a_nrm1, v.a_nrm2) * localNormal;
#endif
#else
// A surface with no normal channel faces the viewer, exactly as a sprite does.
diff --git a/src/esengine/ecs/components/MeshRenderer.hpp b/src/esengine/ecs/components/MeshRenderer.hpp
index 2b70f8697..3b9888854 100644
--- a/src/esengine/ecs/components/MeshRenderer.hpp
+++ b/src/esengine/ecs/components/MeshRenderer.hpp
@@ -141,4 +141,27 @@ struct MeshSkin {
MeshSkin() = default;
};
+// =============================================================================
+// MeshMorph Component
+// =============================================================================
+
+/**
+ * @brief What SHAPE a @ref MeshRenderer is in: how far it is blended towards each
+ * of the shapes its mesh carries.
+ *
+ * @details The third of the trio, for the reason the second exists: MeshRenderer
+ * says what is drawn and MeshSkin what moves it. Entry i weights target
+ * i — positional, because a name lives with the geometry.
+ */
+ES_COMPONENT()
+struct MeshMorph {
+ /** @brief Weight per target, 0 leaving the mesh as authored. Not clamped: a
+ * negative weight and one past 1 are both shapes an author may want,
+ * and glTF states neither bound. */
+ ES_PROPERTY(animatable, tooltip="Weight per morph target of the mesh, in the order the mesh carries them.")
+ std::vector<f32> weights;
+
+ MeshMorph() = default;
+};
+
} // namespace esengine::ecs
diff --git a/src/esengine/renderer/draw/BatchBuilder.cpp b/src/esengine/renderer/draw/BatchBuilder.cpp
index 0324ab9e2..9767959fb 100644
--- a/src/esengine/renderer/draw/BatchBuilder.cpp
+++ b/src/esengine/renderer/draw/BatchBuilder.cpp
@@ -109,6 +109,7 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,
cmd.vertex_layout = key.vertexLayout;
cmd.skin_offset = key.skinOffset;
cmd.skin_count = key.skinCount;
+ cmd.morph_index = key.morphIndex;
cmd.shader_id = key.shaderId;
cmd.blend_mode = key.blend;
cmd.layout_id = key.layoutId;
@@ -140,6 +141,13 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,
cmd.texture_ids[3] = key.envTextureId;
cmd.texture_count = 4;
}
+ // The mesh's own deltas, one slot further still. Read in the VERTEX stage,
+ // unlike the three above — the only sampler here that is.
+ if (key.morphTextureId != 0 && cmd.texture_count >= 1 && key.layoutId != LayoutId::Batch) {
+ for (u8 slot = cmd.texture_count; slot < 4; ++slot) cmd.texture_ids[slot] = key.textureId;
+ cmd.texture_ids[4] = key.morphTextureId;
+ cmd.texture_count = 5;
+ }
cmd.entity = key.entity;
cmd.type = key.type;
cmd.layer = layer;
diff --git a/src/esengine/renderer/draw/BatchBuilder.hpp b/src/esengine/renderer/draw/BatchBuilder.hpp
index ece9ed9f3..e00a7378e 100644
--- a/src/esengine/renderer/draw/BatchBuilder.hpp
+++ b/src/esengine/renderer/draw/BatchBuilder.hpp
@@ -135,6 +135,11 @@ struct BatchDrawKey {
// like the buffers above: what deforms a draw is the draw's, not the batch's.
u32 skinOffset = 0;
u32 skinCount = 0;
+
+ // The shapes this draw is blended towards: the block in the frame's pool
+ // (1-based, 0 = none) and the mesh's own delta texture behind it.
+ u32 morphIndex = 0;
+ u32 morphTextureId = 0;
};
/**
diff --git a/src/esengine/renderer/draw/DrawCommand.hpp b/src/esengine/renderer/draw/DrawCommand.hpp
index eb1dfe80d..802214c88 100644
--- a/src/esengine/renderer/draw/DrawCommand.hpp
+++ b/src/esengine/renderer/draw/DrawCommand.hpp
@@ -146,6 +146,10 @@ struct DrawCommand {
u32 skin_offset = 0;
u32 skin_count = 0;
+ // A morphed draw's shapes: 1 + where its block sits in the frame's pool, so
+ // 0 means the geometry is in the shape it was authored in.
+ u32 morph_index = 0;
+
bool hasPersistentGeometry() const { return vertex_buffer != BufferHandle::Invalid; }
// Vertices owned by this command (from vertex_byte_offset). Needed so the merge pass
@@ -320,6 +324,8 @@ struct DrawCommand {
if (!hasPersistentGeometry() || !next.hasPersistentGeometry()) return false;
if (instance_stride == 0 || instance_stride != next.instance_stride) return false;
if (skin_count != 0 || next.skin_count != 0) return false;
+ // Same reason: one draw can only be in one shape.
+ if (morph_index != 0 || next.morph_index != 0) return false;
// BOTH, not just this one: an opaque head asked about a draw whose
// result depends on when it happens would otherwise swallow it and
// paint it with the head's own state.
diff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cpp
index a35abf386..00e58a919 100644
--- a/src/esengine/renderer/draw/DrawList.cpp
+++ b/src/esengine/renderer/draw/DrawList.cpp
@@ -45,6 +45,7 @@ void DrawList::clear() {
commands_.clear();
sort_entries_.clear();
skin_matrices_.clear();
+ morph_shapes_.clear();
merged_draw_calls_ = 0;
depth_required_ = false;
}
@@ -55,6 +56,11 @@ u32 DrawList::addSkinMatrices(const glm::mat4* matrices, u32 count) {
return at;
}
+u32 DrawList::addMorphShapes(const MorphConstants& shapes) {
+ morph_shapes_.push_back(shapes);
+ return static_cast<u32>(morph_shapes_.size());
+}
+
void DrawList::push(const DrawCommand& cmd) {
// Accumulated where commands ENTER, not scanned where the answer is wanted:
// push is the one funnel every render path goes through, so a path added
@@ -173,9 +179,11 @@ void DrawList::finalize(TransientBufferPool& pool) {
void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
MaterialStore& materials, u32 white_texture_id,
- FrameCapture* capture, BufferHandle skin_ubo) {
+ FrameCapture* capture, BufferHandle skin_ubo, BufferHandle morph_ubo) {
PipelineDesc lastDesc{};
PipelineHandle lastHandle = PipelineHandle::Invalid;
+ /// Whether the block still holds a morphed draw's shapes — see the upload below.
+ bool morph_live = false;
for (u32 i = 0; i < merged_draw_calls_; ++i) {
const auto& cmd = commands_[i];
@@ -224,6 +232,21 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
cmd.skin_count * sizeof(glm::mat4));
}
+ // The shapes, the same way. Cleared on the way OUT of a morphed draw
+ // rather than written before every other one: a mesh with none would
+ // otherwise be deformed by whatever the last morphed draw left behind.
+ if (morph_ubo != BufferHandle::Invalid) {
+ if (cmd.morph_index > 0) {
+ device.updateBuffer(morph_ubo, 0, &morph_shapes_[cmd.morph_index - 1],
+ sizeof(MorphConstants));
+ morph_live = true;
+ } else if (morph_live) {
+ const MorphConstants none{};
+ device.updateBuffer(morph_ubo, 0, &none, sizeof(MorphConstants));
+ morph_live = false;
+ }
+ }
+
// Dynamic per-draw state (sorted+merged draws already group these coarsely).
if (cmd.state_flags & CMD_STATE_SCISSOR) {
device.setScissorTest(true);
diff --git a/src/esengine/renderer/draw/DrawList.hpp b/src/esengine/renderer/draw/DrawList.hpp
index 2290a86ff..368ad5814 100644
--- a/src/esengine/renderer/draw/DrawList.hpp
+++ b/src/esengine/renderer/draw/DrawList.hpp
@@ -7,6 +7,7 @@
#include "../rhi/GfxDevice.hpp"
#include "../rhi/TransientBufferPool.hpp"
#include "../frame/FrameCapture.hpp"
+#include "../store/MorphConstants.hpp"
#include "../../math/Math.hpp"
#include <algorithm>
@@ -49,13 +50,18 @@ public:
void execute(GfxDevice& device, TransientBufferPool& buffers,
MaterialStore& materials, u32 white_texture_id = 0,
FrameCapture* capture = nullptr,
- BufferHandle skin_ubo = BufferHandle::Invalid);
+ BufferHandle skin_ubo = BufferHandle::Invalid,
+ BufferHandle morph_ubo = BufferHandle::Invalid);
/** Append one draw's bone matrices; returns where they start. Frame-scoped,
* like the vertex pool: a command references an offset, not a copy. */
u32 addSkinMatrices(const glm::mat4* matrices, u32 count);
const glm::mat4* skinMatrices() const { return skin_matrices_.data(); }
+ /** Append one draw's shapes; returns 1 + where they sit, so that 0 stays
+ * available for "this draw is in the shape it was authored in". */
+ u32 addMorphShapes(const MorphConstants& shapes);
+
u32 commandCount() const { return static_cast<u32>(commands_.size()); }
u32 mergedDrawCallCount() const { return merged_draw_calls_; }
@@ -175,6 +181,7 @@ private:
std::vector<DrawCommand> commands_;
/// Every skinned draw's bone matrices for this frame, indexed by skin_offset.
std::vector<glm::mat4> skin_matrices_;
+ std::vector<MorphConstants> morph_shapes_;
std::vector<SortEntry> sort_entries_;
std::vector<DrawCommand> sorted_scratch_; // reused across frames to avoid a
// per-frame heap alloc in finalize()
diff --git a/src/esengine/renderer/frame/RenderContext.cpp b/src/esengine/renderer/frame/RenderContext.cpp
index c92685f5c..8024d7e9b 100644
--- a/src/esengine/renderer/frame/RenderContext.cpp
+++ b/src/esengine/renderer/frame/RenderContext.cpp
@@ -16,6 +16,7 @@
#include "./FrameConstants.hpp"
#include "../draw/DrawParams.hpp"
#include "../store/SkinConstants.hpp"
+#include "../store/MorphConstants.hpp"
#include "../../core/Log.hpp"
#include <cmath>
@@ -152,6 +153,15 @@ void RenderContext::initFrameUbo() {
bones.data());
device_.setUniformBuffer(SKIN_CONSTANTS_BINDING, skinUbo_);
+ // The shapes one draw is blended towards. Bound once like the pose above,
+ // but read by EVERY mesh draw: a mesh with no shapes finds a zeroed block,
+ // which is the same statement as having none. See MorphConstants.hpp.
+ const std::vector<u8> shapes(sizeof(MorphConstants), 0);
+ morphUbo_ = device_.createBuffer(
+ {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(MorphConstants)), /*dynamic=*/true},
+ shapes.data());
+ device_.setUniformBuffer(MORPH_CONSTANTS_BINDING, morphUbo_);
+
ES_LOG_DEBUG("FrameConstants UBO created (handle: {})", static_cast<u32>(frameUbo_));
}
diff --git a/src/esengine/renderer/frame/RenderContext.hpp b/src/esengine/renderer/frame/RenderContext.hpp
index 528da1288..0e114be1d 100644
--- a/src/esengine/renderer/frame/RenderContext.hpp
+++ b/src/esengine/renderer/frame/RenderContext.hpp
@@ -211,10 +211,14 @@ private:
BufferHandle drawParamsFallback_ = BufferHandle::Invalid;
/// One skinned draw's bone matrices, rewritten immediately before that draw.
BufferHandle skinUbo_ = BufferHandle::Invalid;
+ /// One morphed draw's shape weights, on the same terms.
+ BufferHandle morphUbo_ = BufferHandle::Invalid;
public:
/** @brief The per-draw bone-matrix block a skinned draw writes into. */
BufferHandle skinUbo() const { return skinUbo_; }
+ /** @brief The per-draw shape-weight block a morphed draw writes into. */
+ BufferHandle morphUbo() const { return morphUbo_; }
private:
f32 lastElapsed_ = 0.0f;
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index 37ca35fd1..96242d387 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -288,7 +288,7 @@ void RenderFrame::drawScene() {
{
ES_PROFILE_SCOPE("render.submit");
draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
- &frame_capture_, context_.skinUbo());
+ &frame_capture_, context_.skinUbo(), context_.morphUbo());
}
// Handed over to whatever the graph runs next. Blend/depth/colour-mask come
@@ -677,7 +677,7 @@ void RenderFrame::replayToDrawCall(i32 stopAtDrawCall) {
context_.updateCameraConstants(view_projection_);
context_.lights().uploadAndBind();
draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
- &frame_capture_, context_.skinUbo());
+ &frame_capture_, context_.skinUbo(), context_.morphUbo());
// Leave scissor disabled for whatever renders next; invalidate so the next
// setPipeline re-applies its full state (stencil included).
@@ -750,7 +750,7 @@ void RenderFrame::renderSurface(ecs::Registry& registry, const glm::mat4& viewPr
context_.updateCameraConstants(viewProjection);
context_.lights().uploadAndBind();
draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
- &frame_capture_, context_.skinUbo());
+ &frame_capture_, context_.skinUbo(), context_.morphUbo());
frame_capture_.endCapture();
rt->unbind();
@@ -1711,7 +1711,8 @@ void RenderFrame::executeShadowPass(ecs::Registry& registry) {
// nothing — the whole pass came back empty for exactly this.
context_.lights().uploadAndBind();
list.execute(device_, shadow_pool_, context_.materials(),
- context_.getWhiteTextureId(), nullptr, context_.skinUbo());
+ context_.getWhiteTextureId(), nullptr, context_.skinUbo(),
+ context_.morphUbo());
++shadowTiles;
shadowDraws += list.mergedDrawCallCount();
}
diff --git a/src/esengine/renderer/frame/RenderFrameOverlay.cpp b/src/esengine/renderer/frame/RenderFrameOverlay.cpp
index 32b60f499..203175650 100644
--- a/src/esengine/renderer/frame/RenderFrameOverlay.cpp
+++ b/src/esengine/renderer/frame/RenderFrameOverlay.cpp
@@ -80,7 +80,7 @@ void RenderFrame::drawScreenOverlay() {
{
ES_PROFILE_SCOPE("render.overlay.submit");
draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
- &frame_capture_, context_.skinUbo());
+ &frame_capture_, context_.skinUbo(), context_.morphUbo());
}
device_.invalidatePipelineCache();
device_.setScissorTest(false);
diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cpp
index f0780d0d4..14df26e9a 100644
--- a/src/esengine/renderer/plugins/MeshPlugin.cpp
+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp
@@ -3,6 +3,7 @@
#include "MeshPlugin.hpp"
#include "../draw/BatchBuilder.hpp"
#include "../store/MaterialStore.hpp"
+#include "../store/MorphConstants.hpp"
#include "../frame/RenderFrame.hpp"
#include "../frame/RenderContext.hpp"
#include "../rhi/Texture.hpp"
@@ -20,6 +21,7 @@
#include <glm/gtc/matrix_access.hpp>
#include <algorithm>
+#include <cmath>
#include <string>
#include <vector>
@@ -120,6 +122,51 @@ u32 skinPose(ecs::Registry& registry, Entity entity, const Mesh& mesh,
return count;
}
+/**
+ * @brief The shapes this entity is in, as the block one draw is deformed by.
+ *
+ * @details Only the heaviest MESH_MAX_ACTIVE_MORPHS are taken, and a weight left
+ * out reads as zero — which is what a weight an author never moved
+ * already means. Zero weights are dropped first, so the budget is spent
+ * on shapes that are saying something.
+ *
+ * @return False when the entity is in the shape the mesh was authored in.
+ */
+bool morphShapes(ecs::Registry& registry, Entity entity, const Mesh& mesh,
+ MorphConstants& out) {
+ if (!mesh.isMorphable()) return false;
+ const auto* morph = registry.tryGet<ecs::MeshMorph>(entity);
+ if (!morph) return false;
+
+ // Weight i addresses target i, so a list longer than the mesh names shapes
+ // it does not have — those entries are not read rather than shifting the rest.
+ const u32 count = std::min(static_cast<u32>(morph->weights.size()), mesh.morphTargetCount);
+ u32 live = 0;
+ for (u32 t = 0; t < count; ++t) {
+ const f32 weight = morph->weights[t];
+ if (weight == 0.0f) continue;
+ if (live < MESH_MAX_ACTIVE_MORPHS) {
+ out.shape[live++] = glm::vec4(static_cast<f32>(t), weight, 0.0f, 0.0f);
+ continue;
+ }
+ // Full: the smallest of what is held loses its place, and only to
+ // something heavier — so what survives is the heaviest set, whatever
+ // order the weights arrived in.
+ u32 lightest = 0;
+ for (u32 i = 1; i < MESH_MAX_ACTIVE_MORPHS; ++i) {
+ if (std::abs(out.shape[i].y) < std::abs(out.shape[lightest].y)) lightest = i;
+ }
+ if (std::abs(weight) > std::abs(out.shape[lightest].y)) {
+ out.shape[lightest] = glm::vec4(static_cast<f32>(t), weight, 0.0f, 0.0f);
+ }
+ }
+ if (live == 0) return false;
+ out.info = glm::vec4(static_cast<f32>(live), static_cast<f32>(mesh.vertexCount),
+ mesh.morphHasNormals ? 2.0f : 1.0f,
+ static_cast<f32>(MORPH_TEXTURE_WIDTH));
+ return true;
+}
+
/**
* @brief The levels a group can actually be drawn at, in the order they take over.
*
@@ -609,6 +656,14 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
u32 instOffset = buffers.allocVertices(LayoutId::MeshInstance, stride);
auto* dst = buffers.vertexData(LayoutId::MeshInstance) + instOffset;
u32 tintRGBA = packColor(mesh.color);
+ // The shapes, whether or not bones move it: the two deform the
+ // same vertices, and a morph target is what the mesh is BEFORE a
+ // pose is applied to it.
+ MorphConstants shapes{};
+ if (morphShapes(registry, entity, *resident, shapes)) {
+ key.morphIndex = draw_list.addMorphShapes(shapes);
+ key.morphTextureId = static_cast<u32>(resident->morphTexture);
+ }
if (skinned) {
std::memcpy(dst, &tintRGBA, 4);
key.skinOffset = draw_list.addSkinMatrices(pose_scratch_.data(), poseSize);
diff --git a/src/esengine/renderer/rhi/GfxEnums.hpp b/src/esengine/renderer/rhi/GfxEnums.hpp
index fd2c49c85..3fed2d64c 100644
--- a/src/esengine/renderer/rhi/GfxEnums.hpp
+++ b/src/esengine/renderer/rhi/GfxEnums.hpp
@@ -106,6 +106,17 @@ static constexpr u32 MESH_INSTANCE_STRIDE_SKINNED = 4;
/// Bone matrices one skinned draw may carry. 64 mat4 is 4KB, inside the 16KB a
/// WebGL2 uniform block is guaranteed; a mesh wanting more is drawn static.
static constexpr u32 MESH_MAX_BONES = 64;
+/// Morph targets one draw may be blended by AT ONCE — a budget on what is LIVE,
+/// since a face holds a handful of expressions open while its mesh carries a
+/// hundred. The heaviest weights are taken; the rest read as zero.
+static constexpr u32 MESH_MAX_ACTIVE_MORPHS = 8;
+/// Texels per row of a mesh's delta texture. 2048 is the smallest MAX_TEXTURE_SIZE
+/// WebGL2 guarantees, so a square of them is the most any device here must hold.
+static constexpr u32 MORPH_TEXTURE_WIDTH = 2048;
+/// Deltas one mesh may carry: targets * vertices * (2 with normals, else 1).
+/// Beyond it the geometry draws unmorphed — a texture the device refuses is a
+/// mesh that does not draw at all.
+static constexpr u32 MORPH_MAX_TEXELS = MORPH_TEXTURE_WIDTH * MORPH_TEXTURE_WIDTH;
/// The attributes that record occupies (4 matrix rows + the tint).
static constexpr u32 MESH_INSTANCE_ATTRIBUTES = 5;
/// Where those attributes start. FIXED, not "after the mesh's channels": a mesh
diff --git a/src/esengine/renderer/rhi/Shader.cpp b/src/esengine/renderer/rhi/Shader.cpp
index 78268330d..d94a24dd9 100644
--- a/src/esengine/renderer/rhi/Shader.cpp
+++ b/src/esengine/renderer/rhi/Shader.cpp
@@ -20,6 +20,7 @@
#include "../store/MaterialConstants.hpp"
#include "../store/SkinConstants.hpp"
#include "../store/LightConstants.hpp"
+#include "../store/MorphConstants.hpp"
#include "../../core/Log.hpp"
#include <cstring>
@@ -252,6 +253,13 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSr
device_->uniformBlockBinding(program_, skinBlock, SKIN_CONSTANTS_BINDING);
}
+ // And the per-draw shape weights, which every mesh vertex stage declares —
+ // whether a draw HAS shapes is a number in the block, not a variant.
+ u32 morphBlock = device_->getUniformBlockIndex(program_, MORPH_CONSTANTS_BLOCK);
+ if (morphBlock != GFX_INVALID_UNIFORM_BLOCK) {
+ device_->uniformBlockBinding(program_, morphBlock, MORPH_CONSTANTS_BINDING);
+ }
+
// Same for the per-draw params block (rewriteLooseUniforms generates it for
// shaders whose loose uniforms were lifted); commitParams binds the UBO.
u32 drawParamsBlock = device_->getUniformBlockIndex(program_, DRAW_PARAMS_BLOCK);
@@ -263,7 +271,8 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSr
// blocks above are: the header reaches every Lit shader, so a compile site that
// forgot the unit would sample slot 0 silently. GLSL ES 300 has no layout(binding).
if (hasUniform(SHADOW_MAP_SAMPLER) || hasUniform(ENV_MAP_SAMPLER)
- || hasUniform(SHADOW_2D_SAMPLER) || hasUniform(SHAPE_2D_SAMPLER)) {
+ || hasUniform(SHADOW_2D_SAMPLER) || hasUniform(SHAPE_2D_SAMPLER)
+ || hasUniform(MORPH_DELTA_SAMPLER)) {
bind();
if (hasUniform(SHADOW_MAP_SAMPLER)) {
setUniform(SHADOW_MAP_SAMPLER, static_cast<i32>(SHADOW_MAP_TEXTURE_UNIT));
@@ -277,6 +286,10 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSr
if (hasUniform(SHAPE_2D_SAMPLER)) {
setUniform(SHAPE_2D_SAMPLER, static_cast<i32>(SHAPE_2D_TEXTURE_UNIT));
}
+ // The one sampler here read by the VERTEX stage.
+ if (hasUniform(MORPH_DELTA_SAMPLER)) {
+ setUniform(MORPH_DELTA_SAMPLER, static_cast<i32>(MORPH_DELTA_TEXTURE_UNIT));
+ }
unbind();
}
diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
index 7f777d843..7fb52d8c6 100644
--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
@@ -426,6 +426,38 @@ layout(std140) uniform SkinConstants {
};
#endif
+
+
+
+
+layout(std140) uniform MorphConstants {
+
+ vec4 u_morphInfo;
+ vec4 u_morphShape[8];
+};
+
+
+
+uniform highp sampler2D u_morphDeltas;
+
+vec3 morphDelta(float index) {
+ float width = u_morphInfo.w;
+ return texelFetch(u_morphDeltas, ivec2(int(mod(index, width)), int(index / width)), 0).xyz;
+}
+
+
+
+void applyMorph(inout vec3 position, inout vec3 normal) {
+ int live = int(u_morphInfo.x);
+ float perVertex = u_morphInfo.z;
+ for (int i = 0; i < 8; i++) {
+ if (i >= live) break;
+ float at = (u_morphShape[i].x * u_morphInfo.y + float(gl_VertexID)) * perVertex;
+ position += u_morphShape[i].y * morphDelta(at);
+ if (perVertex > 1.5) normal += u_morphShape[i].y * morphDelta(at + 1.0);
+ }
+}
+
out vec2 v_texCoord;
out vec4 v_color;
#ifdef LIT
@@ -445,6 +477,13 @@ out highp vec4 v_shadowClip;
#endif
void main() {
+ vec3 local = a_position;
+#ifdef MESH_NORMALS
+ vec3 localNormal = a_normal;
+#else
+ vec3 localNormal = vec3(0.0, 0.0, 1.0);
+#endif
+ applyMorph(local, localNormal);
#ifdef SKINNED
@@ -452,10 +491,10 @@ void main() {
+ a_weights.y * u_bones[a_joints.y]
+ a_weights.z * u_bones[a_joints.z]
+ a_weights.w * u_bones[a_joints.w];
- vec4 world = skin * vec4(a_position, 1.0);
+ vec4 world = skin * vec4(local, 1.0);
#else
mat4 model = mat4(a_model0, a_model1, a_model2, a_model3);
- vec4 world = model * vec4(a_position, 1.0);
+ vec4 world = model * vec4(local, 1.0);
#endif
gl_Position = u_projection * world;
v_texCoord = a_texCoord;
@@ -465,9 +504,9 @@ void main() {
#endif
#ifdef LIT
#if defined(MESH_NORMALS) && defined(SKINNED)
- v_worldNormal = mat3(skin) * a_normal;
+ v_worldNormal = mat3(skin) * localNormal;
#elif defined(MESH_NORMALS)
- v_worldNormal = mat3(a_nrm0, a_nrm1, a_nrm2) * a_normal;
+ v_worldNormal = mat3(a_nrm0, a_nrm1, a_nrm2) * localNormal;
#else
v_worldNormal = vec3(0.0, 0.0, 1.0);
@@ -530,6 +569,19 @@ struct SkinConstants { bones : array<mat4x4f, 64> };
@group(0) @binding(5) var<uniform> skin : SkinConstants;
#endif
+
+
+
+
+struct MorphConstants { info : vec4f, shape : array<vec4f, 8> };
+@group(0) @binding(6) var<uniform> morph : MorphConstants;
+@group(1) @binding(4) var t4 : texture_2d<f32>;
+
+fn morphDelta(index : f32) -> vec3f {
+ let width = morph.info.w;
+ return textureLoad(t4, vec2i(i32(index % width), i32(index / width)), 0).xyz;
+}
+
struct VSIn {
@location(0) a_position : vec3f,
@location(1) a_color : vec4f,
@@ -547,6 +599,8 @@ struct VSIn {
@location(11) a_model3 : vec4f,
#endif
@location(12) a_instTint : vec4f,
+
+ @builtin(vertex_index) vertexIndex : u32,
#ifdef MESH_NORMALS
#ifndef SKINNED
@location(13) a_nrm0 : vec3f,
@@ -570,6 +624,23 @@ struct VSOut {
};
@vertex fn vs_main(v : VSIn) -> VSOut {
+ var local = v.a_position;
+#ifdef MESH_NORMALS
+ var localNormal = v.a_normal;
+#else
+ var localNormal = vec3f(0.0, 0.0, 1.0);
+#endif
+
+
+ let live = i32(morph.info.x);
+ for (var i = 0; i < 8; i = i + 1) {
+ if (i >= live) { break; }
+ let at = (morph.shape[i].x * morph.info.y + f32(v.vertexIndex)) * morph.info.z;
+ local = local + morph.shape[i].y * morphDelta(at);
+ if (morph.info.z > 1.5) {
+ localNormal = localNormal + morph.shape[i].y * morphDelta(at + 1.0);
+ }
+ }
#ifdef SKINNED
@@ -577,10 +648,10 @@ struct VSOut {
+ v.a_weights.y * skin.bones[v.a_joints.y]
+ v.a_weights.z * skin.bones[v.a_joints.z]
+ v.a_weights.w * skin.bones[v.a_joints.w];
- let world = pose * vec4f(v.a_position, 1.0);
+ let world = pose * vec4f(local, 1.0);
#else
let model = mat4x4f(v.a_model0, v.a_model1, v.a_model2, v.a_model3);
- let world = model * vec4f(v.a_position, 1.0);
+ let world = model * vec4f(local, 1.0);
#endif
var out : VSOut;
@@ -593,9 +664,9 @@ struct VSOut {
#ifdef LIT
#ifdef MESH_NORMALS
#ifdef SKINNED
- out.v_worldNormal = mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * v.a_normal;
+ out.v_worldNormal = mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * localNormal;
#else
- out.v_worldNormal = mat3x3f(v.a_nrm0, v.a_nrm1, v.a_nrm2) * v.a_normal;
+ out.v_worldNormal = mat3x3f(v.a_nrm0, v.a_nrm1, v.a_nrm2) * localNormal;
#endif
#else
diff --git a/src/esengine/renderer/store/MorphConstants.hpp b/src/esengine/renderer/store/MorphConstants.hpp
new file mode 100644
index 000000000..6771b5c10
--- /dev/null
+++ b/src/esengine/renderer/store/MorphConstants.hpp
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file MorphConstants.hpp
+ * @brief The shapes one draw is blended towards: which targets, and how far.
+ *
+ * @details Per DRAW and rewritten immediately before it, exactly as
+ * @ref SkinConstants is — the same reason serves both: only one draw's
+ * deformation is ever in flight.
+ *
+ * The DELTAS are not here. They are per vertex per target, which is
+ * megabytes and no uniform block, so they live in a texture the mesh
+ * owns and this block says where in it to look. What a block can carry
+ * is the part that changes every frame: the weights.
+ */
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../rhi/GfxEnums.hpp"
+#include "../../math/Math.hpp"
+
+namespace esengine {
+
+/** @brief Indexed UBO binding point for the per-draw MorphConstants block. */
+inline constexpr u32 MORPH_CONSTANTS_BINDING = 6;
+
+/** @brief GLSL block name; must match the shader's declaration + Shader::compile lookup. */
+inline constexpr const char* MORPH_CONSTANTS_BLOCK = "MorphConstants";
+
+/** @brief The sampler the deltas arrive through, and the unit it is pinned to. */
+inline constexpr const char* MORPH_DELTA_SAMPLER = "u_morphDeltas";
+inline constexpr u32 MORPH_DELTA_TEXTURE_UNIT = 4;
+
+/** @brief std140 mirror of the block. */
+struct MorphConstants {
+ /// x = live shapes below, y = vertices, z = texels one vertex occupies (2
+ /// where the targets bend normals), w = the texture's width. Floats: a
+ /// std140 int vector is the member the two backends align differently.
+ glm::vec4 info{0.0f};
+ /// x = which target, y = how far towards it. Only the first `info.x` are read.
+ glm::vec4 shape[MESH_MAX_ACTIVE_MORPHS];
+};
+
+static_assert(sizeof(MorphConstants) == 16 + MESH_MAX_ACTIVE_MORPHS * 16,
+ "MorphConstants must be a tight array of vec4 to match std140");
+
+} // namespace esengine
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index 2ea509ca3..41d104b47 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -1086,6 +1086,10 @@ ShaderHandle WebGPUDevice::createProgram(const GfxShaderSource& source,
scanWGSLBindingMask(source.fragmentSrc, 1);
rec.group1DepthMask = scanWGSLDepthTextureMask(source.vertexSrc, 1) |
scanWGSLDepthTextureMask(source.fragmentSrc, 1);
+ // What the VERTEX stage declares, on its own: a sampled texture is visible
+ // to the fragment stage alone unless the layout says otherwise, and reading
+ // one it was not given is a pipeline WebGPU rejects with nothing named.
+ rec.group1VertexMask = scanWGSLBindingMask(source.vertexSrc, 1);
if (!rec.vertex || !rec.fragment) {
if (rec.vertex) wgpuShaderModuleRelease(rec.vertex);
if (rec.fragment) wgpuShaderModuleRelease(rec.fragment);
@@ -1209,7 +1213,8 @@ WGPURenderPipeline WebGPUDevice::ensurePipeline(u32 id) {
// unbound bindings are legal (dummy backfill) and group compatibility
// holds by identity.
pd.layout = pipelineLayoutFor(progIt->second.group0Mask, progIt->second.group1Mask,
- progIt->second.group1DepthMask);
+ progIt->second.group1DepthMask,
+ progIt->second.group1VertexMask);
pd.vertex.module = progIt->second.vertex;
pd.vertex.entryPoint = sv("vs_main");
pd.vertex.bufferCount = slotCount;
@@ -1427,12 +1432,14 @@ void WebGPUDevice::drawInternalClear(bool color, bool depth, bool stencil,
bind_group_dirty_ = true;
}
-WGPUBindGroupLayout WebGPUDevice::groupLayoutFor(u32 group, u32 mask, u32 depthMask) {
+WGPUBindGroupLayout WebGPUDevice::groupLayoutFor(u32 group, u32 mask, u32 depthMask,
+ u32 vertexMask) {
// depthMask is part of the key: the same bindings sampled as depth are a
// DIFFERENT layout, and sharing one entry would bind a float texture under a
- // depth declaration.
+ // depth declaration. vertexMask likewise — visibility is part of an entry.
const u64 key = (static_cast<u64>(group) << 32) | mask
- ^ (static_cast<u64>(depthMask) << 48);
+ ^ (static_cast<u64>(depthMask) << 48)
+ ^ (static_cast<u64>(vertexMask) << 16);
auto cached = group_layouts_.find(key);
if (cached != group_layouts_.end()) return cached->second;
if (!device_) return nullptr;
@@ -1452,16 +1459,22 @@ WGPUBindGroupLayout WebGPUDevice::groupLayoutFor(u32 group, u32 mask, u32 depthM
}
} else {
// Texture units through the unit→binding convention. Fragment-only
- // visibility: the engine samples in fragment stages exclusively.
+ // visibility unless the vertex stage declared the binding itself: a
+ // stage sees only what its entry admits.
static_assert(kTextureSlots == kGroup1TextureUnits,
"device texture slots mirror the group-1 convention");
for (u32 unit = 0; unit < kTextureSlots; ++unit) {
const u32 tb = textureBindingForUnit(unit);
const u32 sb = samplerBindingForUnit(unit);
+ const auto stages = [&](u32 binding) {
+ return (vertexMask & (1u << binding))
+ ? (WGPUShaderStage_Vertex | WGPUShaderStage_Fragment)
+ : WGPUShaderStage_Fragment;
+ };
if (mask & (1u << tb)) {
WGPUBindGroupLayoutEntry e{};
e.binding = tb;
- e.visibility = WGPUShaderStage_Fragment;
+ e.visibility = stages(tb);
e.texture.sampleType = (depthMask & (1u << tb))
? WGPUTextureSampleType_Depth
: WGPUTextureSampleType_Float;
@@ -1471,7 +1484,7 @@ WGPUBindGroupLayout WebGPUDevice::groupLayoutFor(u32 group, u32 mask, u32 depthM
if (mask & (1u << sb)) {
WGPUBindGroupLayoutEntry e{};
e.binding = sb;
- e.visibility = WGPUShaderStage_Fragment;
+ e.visibility = stages(sb);
e.sampler.type = WGPUSamplerBindingType_Filtering;
entries[count++] = e;
}
@@ -1487,11 +1500,12 @@ WGPUBindGroupLayout WebGPUDevice::groupLayoutFor(u32 group, u32 mask, u32 depthM
}
WGPUPipelineLayout WebGPUDevice::pipelineLayoutFor(u32 group0Mask, u32 group1Mask,
- u32 group1DepthMask) {
- // The depth mask changes the group-1 layout under this pipeline, so it has
- // to reach the key here too — see groupLayoutFor.
+ u32 group1DepthMask, u32 group1VertexMask) {
+ // The depth and visibility masks change the group-1 layout under this
+ // pipeline, so they have to reach the key here too — see groupLayoutFor.
const u64 key = ((static_cast<u64>(group1Mask) << 32) | group0Mask)
- ^ (static_cast<u64>(group1DepthMask) << 16);
+ ^ (static_cast<u64>(group1DepthMask) << 16)
+ ^ (static_cast<u64>(group1VertexMask) << 8);
auto cached = pipeline_layouts_.find(key);
if (cached != pipeline_layouts_.end()) return cached->second;
if (!device_) return nullptr;
@@ -1501,7 +1515,9 @@ WGPUPipelineLayout WebGPUDevice::pipelineLayoutFor(u32 group0Mask, u32 group1Mas
WGPUBindGroupLayout bgls[2];
u32 count = 0;
if (group0Mask != 0 || group1Mask != 0) bgls[count++] = groupLayoutFor(0, group0Mask);
- if (group1Mask != 0) bgls[count++] = groupLayoutFor(1, group1Mask, group1DepthMask);
+ if (group1Mask != 0) {
+ bgls[count++] = groupLayoutFor(1, group1Mask, group1DepthMask, group1VertexMask);
+ }
WGPUPipelineLayoutDescriptor pld{};
pld.bindGroupLayoutCount = count;
@@ -1654,7 +1670,8 @@ void WebGPUDevice::flushBindGroup() {
}
WGPUBindGroupDescriptor tgd{};
- tgd.layout = groupLayoutFor(1, prog->group1Mask, prog->group1DepthMask);
+ tgd.layout = groupLayoutFor(1, prog->group1Mask, prog->group1DepthMask,
+ prog->group1VertexMask);
tgd.entryCount = texCount;
tgd.entries = texEntries;
u64 tids[kTextureSlots * 2];
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index 337000dbc..0da515ca5 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -365,6 +365,10 @@ private:
* so an unused declaration is as legal as in GLSL. */
u32 group0Mask = 0;
u32 group1Mask = 0;
+ /// Which of group1Mask's bindings the VERTEX stage declares. A texture is
+ /// fragment-visible by default here; one the vertex stage names has to say
+ /// so, and the layout it produces is a different layout.
+ u32 group1VertexMask = 0;
/// Which of group1Mask's bindings are `texture_depth_2d`.
u32 group1DepthMask = 0;
};
@@ -401,11 +405,13 @@ private:
* are texture_2d/sampler pairs per the WebGPUMappings unit→binding
* convention (engine units 0..7 at 0..7/8..15, material units 8..15
* at 16..23/24..31). */
- WGPUBindGroupLayout groupLayoutFor(u32 group, u32 mask, u32 depthMask = 0);
+ WGPUBindGroupLayout groupLayoutFor(u32 group, u32 mask, u32 depthMask = 0,
+ u32 vertexMask = 0);
/** @brief Returns the cached explicit pipeline layout for a program's masks.
* A program with group-1 bindings but an empty group 0 still gets a
* (zero-entry) group-0 layout, so group indices stay positional. */
- WGPUPipelineLayout pipelineLayoutFor(u32 group0Mask, u32 group1Mask, u32 group1DepthMask = 0);
+ WGPUPipelineLayout pipelineLayoutFor(u32 group0Mask, u32 group1Mask, u32 group1DepthMask = 0,
+ u32 group1VertexMask = 0);
/** @brief Lazily creates the dummy backfill resources: a zeroed uniform
* buffer and a 1x1 white texture, standing in for declared-but-
* unbound bindings (GL reads an unbound block/unit without
diff --git a/src/esengine/resource/Mesh.hpp b/src/esengine/resource/Mesh.hpp
index 6dc20aad2..44a3c0b02 100644
--- a/src/esengine/resource/Mesh.hpp
+++ b/src/esengine/resource/Mesh.hpp
@@ -28,6 +28,19 @@ enum class MeshRecovery : u8 {
HostOnly, ///< Built in this process from bytes kept nowhere else.
};
+/**
+ * @brief The shapes handed to a realization: the deltas, and how to read them.
+ *
+ * @details One record because the three are unreadable apart — the array is flat,
+ * and the count and the flag are what say where target i begins.
+ */
+struct MeshMorphSource {
+ /// `targetCount * vertexCount * (hasNormals ? 6 : 3)` floats.
+ ConstSpan<f32> deltas;
+ u32 targetCount = 0;
+ bool hasNormals = false;
+};
+
/**
* @brief Buffers, the layout that describes them, and the bounds culling reads.
*
@@ -76,6 +89,20 @@ public:
bool isSkinned() const { return !inverseBind.empty(); }
+ /** The shapes this geometry can be blended towards, as a texture of deltas:
+ * one texel per (target, vertex), and a second behind it where the targets
+ * bend normals. Realized with the buffers above and lost with them. */
+ TextureHandle morphTexture = TextureHandle::Invalid;
+ u32 morphTargetCount = 0;
+ bool morphHasNormals = false;
+ /** Vertices the deltas are indexed by — the stride from one target to the
+ * next inside the texture, and the reason it is kept beside them. */
+ u32 vertexCount = 0;
+
+ bool isMorphable() const {
+ return morphTargetCount > 0 && morphTexture != TextureHandle::Invalid;
+ }
+
/** Whether a live GPU realization stands behind this identity. False from a
* device loss until the rematerialization that replaces it, which is what
* stops the draw path consuming buffers that died with their device. */
@@ -85,6 +112,7 @@ public:
&& layout != VertexLayoutHandle::Invalid;
}
+
bool isDrawable() const { return hasRealization() && indexCount > 0; }
};
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index 8390aba01..0ead4c1ff 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -20,6 +20,9 @@
#include "../renderer/rhi/Texture.hpp"
#include "../renderer/rhi/Buffer.hpp"
+#include <cstring>
+#include <vector>
+
namespace esengine::resource {
void ResourceManager::init(GfxDevice& device) {
@@ -488,10 +491,37 @@ void ResourceManager::releaseVertexBuffer(VertexBufferHandle handle) {
// Mesh Resources
// =============================================================================
+namespace {
+
+/**
+ * IEEE binary32 to binary16. A morph delta is a small offset, so the end that
+ * matters is the subnormal one — hence the explicit path rather than a cast.
+ * A value too large for half saturates to infinity, which is what a delta that
+ * big would look like on screen either way.
+ */
+u16 packHalf(f32 value) {
+ u32 bits = 0;
+ std::memcpy(&bits, &value, sizeof(bits));
+ const u32 sign = (bits >> 16) & 0x8000u;
+ const i32 exponent = static_cast<i32>((bits >> 23) & 0xFFu) - 127 + 15;
+ const u32 mantissa = bits & 0x7FFFFFu;
+ if (exponent >= 31) return static_cast<u16>(sign | 0x7C00u);
+ if (exponent <= 0) {
+ if (exponent < -10) return static_cast<u16>(sign);
+ const u32 shift = static_cast<u32>(14 - exponent);
+ const u32 subnormal = (mantissa | 0x800000u) >> shift;
+ return static_cast<u16>(sign | (subnormal + ((mantissa >> (shift - 1)) & 1u)));
+ }
+ const u32 half = sign | (static_cast<u32>(exponent) << 10) | (mantissa >> 13);
+ return static_cast<u16>(half + ((mantissa & 0x1FFFu) > 0x1000u ? 1u : 0u));
+}
+
+} // namespace
+
bool ResourceManager::realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,
ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
const glm::vec3& localMin, const glm::vec3& localMax,
- ConstSpan<f32> inverseBind) {
+ ConstSpan<f32> inverseBind, const MeshMorphSource& morph) {
if (!device_ || vertexBytes.empty() || indices.empty() || channels.empty()) return false;
// The mesh describes its own vertices; the per-object transform is the
@@ -584,16 +614,87 @@ bool ResourceManager::realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSp
mesh.inverseBind.resize(joints);
std::memcpy(mesh.inverseBind.data(), inverseBind.data(), joints * sizeof(glm::mat4));
}
+ mesh.vertexCount = vertexStride > 0 ? static_cast<u32>(vertexBytes.size()) / vertexStride : 0;
+
+ // The shapes, last: geometry that draws is worth having even when the deltas
+ // behind it are refused, and the refusal leaves a mesh in its authored shape
+ // rather than no mesh at all.
+ const esengine::TextureHandle previousMorph = mesh.morphTexture;
+ mesh.morphTexture = esengine::TextureHandle::Invalid;
+ mesh.morphTargetCount = 0;
+ mesh.morphHasNormals = false;
+ if (morph.targetCount > 0 && !morph.deltas.empty()) {
+ mesh.morphTexture = createMorphTexture(morph, mesh.vertexCount);
+ if (mesh.morphTexture != esengine::TextureHandle::Invalid) {
+ mesh.morphTargetCount = morph.targetCount;
+ mesh.morphHasNormals = morph.hasNormals;
+ }
+ }
+ if (previousMorph != esengine::TextureHandle::Invalid) device_->deleteTexture(previousMorph);
return true;
}
+/**
+ * @brief One mesh's deltas as a texture the vertex stage reads.
+ *
+ * @details A row per MORPH_TEXTURE_WIDTH texels rather than per target: a target
+ * of ten thousand vertices would ask for a texture wider than any
+ * device guarantees. Half precision because a delta is an offset off a
+ * coordinate the vertex already carries at full precision.
+ */
+esengine::TextureHandle ResourceManager::createMorphTexture(const MeshMorphSource& morph,
+ u32 vertexCount) {
+ if (!device_ || vertexCount == 0) return esengine::TextureHandle::Invalid;
+ const u32 perVertex = morph.hasNormals ? 2u : 1u;
+ const u32 components = morph.hasNormals ? 6u : 3u;
+ const u64 texels = static_cast<u64>(morph.targetCount) * vertexCount * perVertex;
+ if (morph.deltas.size() < static_cast<u64>(morph.targetCount) * vertexCount * components) {
+ ES_LOG_WARN("mesh morph: {} deltas describe fewer than {} targets over {} vertices;"
+ " drawing the authored shape",
+ morph.deltas.size(), morph.targetCount, vertexCount);
+ return esengine::TextureHandle::Invalid;
+ }
+ if (texels > MORPH_MAX_TEXELS) {
+ ES_LOG_WARN("mesh morph: {} targets over {} vertices needs {} texels and the largest"
+ " texture here holds {}; drawing the authored shape",
+ morph.targetCount, vertexCount, texels, MORPH_MAX_TEXELS);
+ return esengine::TextureHandle::Invalid;
+ }
+
+ const u32 height = static_cast<u32>((texels + MORPH_TEXTURE_WIDTH - 1) / MORPH_TEXTURE_WIDTH);
+ std::vector<u16> pixels(static_cast<usize>(MORPH_TEXTURE_WIDTH) * height * 4, 0);
+ for (u32 t = 0; t < morph.targetCount; ++t) {
+ for (u32 v = 0; v < vertexCount; ++v) {
+ const usize src = (static_cast<usize>(t) * vertexCount + v) * components;
+ const usize dst = (static_cast<usize>(t) * vertexCount + v) * perVertex * 4;
+ for (u32 c = 0; c < 3; ++c) pixels[dst + c] = packHalf(morph.deltas[src + c]);
+ if (!morph.hasNormals) continue;
+ for (u32 c = 0; c < 3; ++c) pixels[dst + 4 + c] = packHalf(morph.deltas[src + 3 + c]);
+ }
+ }
+
+ TextureDesc desc;
+ desc.width = MORPH_TEXTURE_WIDTH;
+ desc.height = height;
+ desc.format = GfxPixelFormat::RGBA16F;
+ // Fetched by texel index, never filtered: a value between two deltas belongs
+ // to no vertex, and asking for one is how a half-texel offset gets invented.
+ desc.minFilter = TextureFilter::Nearest;
+ desc.magFilter = TextureFilter::Nearest;
+ desc.wrapS = TextureWrap::ClampToEdge;
+ desc.wrapT = TextureWrap::ClampToEdge;
+ desc.mipmaps = false;
+ return device_->createTexture(desc, pixels.data());
+}
+
MeshHandle ResourceManager::createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,
ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
const glm::vec3& localMin, const glm::vec3& localMax,
- MeshRecovery recovery, ConstSpan<f32> inverseBind) {
+ MeshRecovery recovery, ConstSpan<f32> inverseBind,
+ const MeshMorphSource& morph) {
auto mesh = makeUnique<Mesh>();
if (!realizeMesh(*mesh, vertexBytes, indices, channels, vertexStride,
- localMin, localMax, inverseBind)) {
+ localMin, localMax, inverseBind, morph)) {
return MeshHandle();
}
mesh->recovery = recovery;
@@ -604,7 +705,7 @@ bool ResourceManager::rematerializeMesh(MeshHandle target, ConstSpan<u8> vertexB
ConstSpan<u32> indices,
ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
const glm::vec3& localMin, const glm::vec3& localMax,
- ConstSpan<f32> inverseBind) {
+ ConstSpan<f32> inverseBind, const MeshMorphSource& morph) {
Mesh* mesh = meshes_.get(target);
if (!mesh) {
ES_LOG_ERROR("rematerializeMesh: handle {} names no live mesh", target.id());
@@ -618,7 +719,7 @@ bool ResourceManager::rematerializeMesh(MeshHandle target, ConstSpan<u8> vertexB
return false;
}
if (!realizeMesh(*mesh, vertexBytes, indices, channels, vertexStride,
- localMin, localMax, inverseBind)) {
+ localMin, localMax, inverseBind, morph)) {
ES_LOG_ERROR("rematerializeMesh: mesh {} could not be rebuilt; it stays owed",
target.id());
return false;
@@ -656,6 +757,10 @@ u32 ResourceManager::invalidateGpuMeshes() {
mesh.vertexBuffer = BufferHandle::Invalid;
mesh.indexBuffer = BufferHandle::Invalid;
mesh.layout = VertexLayoutHandle::Invalid;
+ // Forgotten for the same reason, and the COUNT with it: a mesh that still
+ // claimed targets would be drawn morphed against a texture that is gone.
+ mesh.morphTexture = esengine::TextureHandle::Invalid;
+ mesh.morphTargetCount = 0;
if (mesh.recovery == MeshRecovery::SourceReplayable) {
awaitingRematerialization_.push_back(handle);
@@ -687,6 +792,10 @@ void ResourceManager::releaseMesh(MeshHandle handle) {
// createVertexLayout caches by description and other meshes share the result.
releaseVertexBuffer(mesh->vertices);
releaseIndexBuffer(mesh->indices);
+ // The delta texture IS the mesh's own — nothing shares it, unlike the layout.
+ if (mesh->morphTexture != esengine::TextureHandle::Invalid && device_) {
+ device_->deleteTexture(mesh->morphTexture);
+ }
meshes_.release(handle.id());
// A released mesh cannot be owed: the identity the debt named is gone, and a
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index c40ab2322..dccb41086 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -466,7 +466,8 @@ public:
MeshHandle createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,
ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
const glm::vec3& localMin, const glm::vec3& localMax,
- MeshRecovery recovery, ConstSpan<f32> inverseBind = {});
+ MeshRecovery recovery, ConstSpan<f32> inverseBind = {},
+ const MeshMorphSource& morph = {});
/**
* @brief Puts new geometry behind an EXISTING mesh handle.
@@ -480,7 +481,7 @@ public:
bool rematerializeMesh(MeshHandle target, ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,
ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
const glm::vec3& localMin, const glm::vec3& localMax,
- ConstSpan<f32> inverseBind = {});
+ ConstSpan<f32> inverseBind = {}, const MeshMorphSource& morph = {});
/** @brief The mesh a handle names, or null. */
Mesh* getMesh(MeshHandle handle);
@@ -700,7 +701,10 @@ private:
bool realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,
ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
const glm::vec3& localMin, const glm::vec3& localMax,
- ConstSpan<f32> inverseBind);
+ ConstSpan<f32> inverseBind, const MeshMorphSource& morph);
+ /** The deltas as a texture the vertex stage fetches from, or an invalid
+ * handle where they do not fit one — see realizeMesh for what that means. */
+ esengine::TextureHandle createMorphTexture(const MeshMorphSource& morph, u32 vertexCount);
std::vector<MeshHandle> awaitingRematerialization_;
u32 meshes_lost_non_recoverable_ = 0;
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index 5e56fbaae..553c1e10b 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -130,6 +130,17 @@ std::string canonicalVertexStageWGSL(bool lit) {
"struct SkinConstants { bones : array<mat4x4f, 64> };\n"
"@group(0) @binding(5) var<uniform> skin : SkinConstants;\n"
"#endif\n"
+ "#ifdef MESH\n"
+ // The GLSL twin's morph block. Declaring the texture in the VERTEX stage
+ // is what earns it vertex visibility in the bind-group layout.
+ "struct MorphConstants { info : vec4f, shape : array<vec4f, 8> };\n"
+ "@group(0) @binding(6) var<uniform> morph : MorphConstants;\n"
+ "@group(1) @binding(4) var t4 : texture_2d<f32>;\n"
+ "fn morphDelta(index : f32) -> vec3f {\n"
+ " let width = morph.info.w;\n"
+ " return textureLoad(t4, vec2i(i32(index % width), i32(index / width)), 0).xyz;\n"
+ "}\n"
+ "#endif\n"
"\n"
"struct VSIn {\n"
// A particle's quad corner is the vertex; where that corner lands is on the
@@ -169,10 +180,32 @@ std::string canonicalVertexStageWGSL(bool lit) {
"#endif\n"
"#endif\n"
"#endif\n"
+ "#ifdef MESH\n"
+ // What the GLSL twin reads as gl_VertexID.
+ " @builtin(vertex_index) vertexIndex : u32,\n"
+ "#endif\n"
"};\n"
"\n"
"@vertex fn vs_main(v : VSIn) -> VSOut {\n"
" var out : VSOut;\n"
+ "#ifdef MESH\n"
+ " var local = v.a_position;\n"
+ "#ifdef MESH_NORMALS\n"
+ " var localNormal = v.a_normal;\n"
+ "#else\n"
+ " var localNormal = vec3f(0.0, 0.0, 1.0);\n"
+ "#endif\n"
+ // Before the pose: a target was authored against the mesh at rest.
+ " let live = i32(morph.info.x);\n"
+ " for (var i = 0; i < 8; i = i + 1) {\n"
+ " if (i >= live) { break; }\n"
+ " let at = (morph.shape[i].x * morph.info.y + f32(v.vertexIndex)) * morph.info.z;\n"
+ " local = local + morph.shape[i].y * morphDelta(at);\n"
+ " if (morph.info.z > 1.5) {\n"
+ " localNormal = localNormal + morph.shape[i].y * morphDelta(at + 1.0);\n"
+ " }\n"
+ " }\n"
+ "#endif\n"
// A particle faces the viewer wherever it is seen from; head-on and
// orthographic the axes come out (1,0,0) and (0,1,0), the flat quad a 2D
// scene has always drawn.
@@ -197,10 +230,10 @@ std::string canonicalVertexStageWGSL(bool lit) {
" + v.a_weights.y * skin.bones[v.a_joints.y]\n"
" + v.a_weights.z * skin.bones[v.a_joints.z]\n"
" + v.a_weights.w * skin.bones[v.a_joints.w];\n"
- " let world = pose * vec4f(v.a_position, 1.0);\n"
+ " let world = pose * vec4f(local, 1.0);\n"
" out.v_color = v.a_color * v.a_instTint;\n"
"#elif defined(MESH)\n"
- " let world = mat4x4f(v.a_model0, v.a_model1, v.a_model2, v.a_model3) * vec4f(v.a_position, 1.0);\n"
+ " let world = mat4x4f(v.a_model0, v.a_model1, v.a_model2, v.a_model3) * vec4f(local, 1.0);\n"
" out.v_color = v.a_color * v.a_instTint;\n"
"#else\n"
" let world = vec4f(v.a_position, 1.0);\n"
@@ -215,9 +248,9 @@ std::string canonicalVertexStageWGSL(bool lit) {
"#endif\n"
"#ifdef MESH_NORMALS\n"
"#ifdef SKINNED\n"
- " out.v_worldNormal = mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * v.a_normal;\n"
+ " out.v_worldNormal = mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * localNormal;\n"
"#else\n"
- " out.v_worldNormal = mat3x3f(v.a_nrm0, v.a_nrm1, v.a_nrm2) * v.a_normal;\n"
+ " out.v_worldNormal = mat3x3f(v.a_nrm0, v.a_nrm1, v.a_nrm2) * localNormal;\n"
"#endif\n"
" out.v_worldXYZ = world.xyz;\n"
"#endif\n";
@@ -322,6 +355,30 @@ std::string canonicalVertexStage(bool lit) {
"#endif\n"
"#endif\n"
"#endif\n"
+ "#ifdef MESH\n"
+ // The shapes a resident mesh is blended towards. See mesh.esshader, whose
+ // vertex stage says the same thing to the same blocks: a material's mesh
+ // variant deforms the same geometry, so it must deform it the same way.
+ "layout(std140) uniform MorphConstants {\n"
+ " vec4 u_morphInfo;\n"
+ " vec4 u_morphShape[8];\n"
+ "};\n"
+ "uniform highp sampler2D u_morphDeltas;\n"
+ "vec3 morphDelta(float index) {\n"
+ " float width = u_morphInfo.w;\n"
+ " return texelFetch(u_morphDeltas, ivec2(int(mod(index, width)), int(index / width)), 0).xyz;\n"
+ "}\n"
+ "void applyMorph(inout vec3 position, inout vec3 normal) {\n"
+ " int live = int(u_morphInfo.x);\n"
+ " float perVertex = u_morphInfo.z;\n"
+ " for (int i = 0; i < 8; i++) {\n"
+ " if (i >= live) break;\n"
+ " float at = (u_morphShape[i].x * u_morphInfo.y + float(gl_VertexID)) * perVertex;\n"
+ " position += u_morphShape[i].y * morphDelta(at);\n"
+ " if (perVertex > 1.5) normal += u_morphShape[i].y * morphDelta(at + 1.0);\n"
+ " }\n"
+ "}\n"
+ "#endif\n"
"\n"
"out vec4 v_color;\n"
"out vec2 v_texCoord;\n"
@@ -335,6 +392,16 @@ std::string canonicalVertexStage(bool lit) {
src +=
"\n"
"void main() {\n"
+ "#ifdef MESH\n"
+ " vec3 local = a_position;\n"
+ "#ifdef MESH_NORMALS\n"
+ " vec3 localNormal = a_normal;\n"
+ "#else\n"
+ " vec3 localNormal = vec3(0.0, 0.0, 1.0);\n"
+ "#endif\n"
+ // Before the pose: a target was authored against the mesh at rest.
+ " applyMorph(local, localNormal);\n"
+ "#endif\n"
// A particle faces the viewer wherever it is seen from; head-on and
// orthographic the axes come out (1,0,0) and (0,1,0), the flat quad a 2D
// scene has always drawn.
@@ -358,10 +425,10 @@ std::string canonicalVertexStage(bool lit) {
" + a_weights.y * u_bones[a_joints.y]\n"
" + a_weights.z * u_bones[a_joints.z]\n"
" + a_weights.w * u_bones[a_joints.w];\n"
- " vec4 world = skin * vec4(a_position, 1.0);\n"
+ " vec4 world = skin * vec4(local, 1.0);\n"
" v_color = a_color * a_instTint;\n"
"#elif defined(MESH)\n"
- " vec4 world = mat4(a_model0, a_model1, a_model2, a_model3) * vec4(a_position, 1.0);\n"
+ " vec4 world = mat4(a_model0, a_model1, a_model2, a_model3) * vec4(local, 1.0);\n"
" v_color = a_color * a_instTint;\n"
"#else\n"
" vec4 world = vec4(a_position, 1.0);\n"
@@ -376,9 +443,9 @@ std::string canonicalVertexStage(bool lit) {
"#endif\n"
"#ifdef MESH_NORMALS\n"
"#ifdef SKINNED\n"
- " v_worldNormal = mat3(skin) * a_normal;\n"
+ " v_worldNormal = mat3(skin) * localNormal;\n"
"#else\n"
- " v_worldNormal = mat3(a_nrm0, a_nrm1, a_nrm2) * a_normal;\n"
+ " v_worldNormal = mat3(a_nrm0, a_nrm1, a_nrm2) * localNormal;\n"
"#endif\n"
" v_worldXYZ = world.xyz;\n"
"#endif\n";
diff --git a/tests/renderer/test_shader_device.cpp b/tests/renderer/test_shader_device.cpp
index abaec4d0a..fa7529c32 100644
--- a/tests/renderer/test_shader_device.cpp
+++ b/tests/renderer/test_shader_device.cpp
@@ -7,6 +7,7 @@
#include "MockGfxDevice.hpp"
#include "esengine/renderer/rhi/Shader.hpp"
#include "esengine/renderer/store/LightConstants.hpp"
+#include "esengine/renderer/store/MorphConstants.hpp"
#include <cstdio>
@@ -31,15 +32,15 @@ int main() {
CHECK(d.getActiveUniformsCalls == 1, "reflection routes through device.getActiveUniforms");
// compile() pins the engine-injected samplers to their units, so the counts
- // the rest of this block asserts start from what that seeding left behind.
- // Four: the shadow map, the environment's reflection, and the two 2D masks.
- CHECK(d.setUniform1iCalls == 4
- && d.lastUniform1iVal == static_cast<i32>(SHAPE_2D_TEXTURE_UNIT),
+ // below start from what that seeding left behind. Five: the shadow map,
+ // the reflection, the two 2D masks, and the morph deltas.
+ CHECK(d.setUniform1iCalls == 5
+ && d.lastUniform1iVal == static_cast<i32>(MORPH_DELTA_TEXTURE_UNIT),
"compile pins the injected samplers to their texture units");
CHECK(d.useProgramCalls == 2, "seeding them binds and unbinds the program once");
shader->setUniform("u_tex", 3);
- CHECK(d.setUniform1iCalls == 5, "setUniform(name,int) routes through device.setUniform1i");
+ CHECK(d.setUniform1iCalls == 6, "setUniform(name,int) routes through device.setUniform1i");
CHECK(d.lastUniform1iVal == 3, "uniform value forwarded");
shader->setUniform("u_color", glm::vec4(1, 0, 0, 1));
diff --git a/tools/check-native-components.mjs b/tools/check-native-components.mjs
index eebaf8974..48916b94b 100644
--- a/tools/check-native-components.mjs
+++ b/tools/check-native-components.mjs
@@ -39,12 +39,29 @@ const byHand = new Set(
[...regSrc.matchAll(/reg\.add([A-Z][A-Za-z0-9_]*)\s*=/g)].map((m) => m[1]),
);
-const stranded = components.filter((c) => !withAccessor.has(c) && !byHand.has(c));
+// The third route: a component whose only fields are number lists has no POD
+// layout either, and the registry presents it from the metadata naming them.
+// Whether that loop is THERE is read here — deleting it must strand them.
+const hasMetadataLoop = /numberListFields[\s\S]{0,2000}?reg\[`add\$\{cppName\}`\]/.test(regSrc);
+/** A component's own slice of the metadata: from its name to the next one's. */
+const entries = [...meta.matchAll(/^ {4}([A-Z][A-Za-z0-9_]*):\s*\{/gm)];
+const byMetadata = new Set(
+ hasMetadataLoop
+ ? entries
+ .filter(([, ], i) => /\n\s+numberListFields:/.test(
+ meta.slice(entries[i].index, entries[i + 1]?.index ?? meta.length)))
+ .map((m) => m[1])
+ : [],
+);
+
+const stranded = components.filter(
+ (c) => !withAccessor.has(c) && !byHand.has(c) && !byMetadata.has(c));
if (stranded.length) {
console.error('check-native-components: no route to the registry on a device for '
+ `${stranded.length} component(s):`);
for (const c of stranded) {
- console.error(` ${c} — no ptr accessor and no reg.add${c} in nativeRegistry.ts`);
+ console.error(` ${c} — no ptr accessor, no reg.add${c} in nativeRegistry.ts, and no`
+ + ' number-list fields the metadata loop there would present it by');
}
console.error('\nGive it a POD layout, or present it by hand the way MeshSkin and the '
+ 'hierarchy components are.');
@@ -53,4 +70,5 @@ if (stranded.length) {
console.log(`check-native-components: ${components.length} builtin(s) reach the registry on a `
+ `device — ${withAccessor.size} by ptr accessor, ${byHand.size} presented by hand `
- + `(${[...byHand].sort().join(', ')}).`);
+ + `(${[...byHand].sort().join(', ')}), ${byMetadata.size} from their number-list metadata`
+ + `${byMetadata.size ? ` (${[...byMetadata].sort().join(', ')})` : ''}.`);
diff --git a/tools/eht/generators/metadata.py b/tools/eht/generators/metadata.py
index 28067aa2b..a7dbc3d89 100644
--- a/tools/eht/generators/metadata.py
+++ b/tools/eht/generators/metadata.py
@@ -61,6 +61,15 @@ class MetadataGenerator:
return {'skeletonField': skel_field, 'atlasField': atlas_field, 'runtime': runtime}
return None
+ def _is_number_list(self, prop) -> bool:
+ """A list of numbers the boundary marshals as a registered embind vector.
+
+ Apart from `entityFields` because that list also re-aims entity references
+ when a prefab is instantiated; these are values, and a reference is not.
+ """
+ t = self.types.clean_type(prop.cpp_type)
+ return t in self.types.VECTOR_TYPES and 'entity_ref' not in prop.annotations
+
def _get_entity_fields(self, comp: Component) -> List[str]:
return [p.name for p in comp.properties if 'entity_ref' in p.annotations]
@@ -268,6 +277,8 @@ class MetadataGenerator:
# `std::vector<Entity>` (Children.entities), which must stay an array.
if self.types.is_entity_vector(t):
return 'Entity[]'
+ if t in self.types.VECTOR_TYPES:
+ return f'{self.types.CPP_TO_TS[self.types.VECTOR_TYPES[t][0]]}[]'
if self.types.is_struct_vector(t):
return f'{self.types.vector_elem_ts(t)}[]'
if self.types.is_handle(t):
@@ -431,6 +442,13 @@ class MetadataGenerator:
' * and keep the hand-written pair the registry wires them by.',
' */',
' listFields?: string[];',
+ ' /**',
+ ' * List fields whose elements are NUMBERS, which the web boundary',
+ ' * marshals as a registered embind vector rather than a JS array.',
+ ' * Apart from `entityFields`: that list also re-aims references when',
+ ' * a prefab is instantiated, and a weight is a value, not a reference.',
+ ' */',
+ ' numberListFields?: string[];',
' colorFields: string[];',
' animatableFields: string[];',
' /**',
@@ -508,10 +526,15 @@ class MetadataGenerator:
lines.append(' entityFields: [],')
list_fields = [p.name for p in comp.properties
- if self.types.is_struct_vector(p.cpp_type)]
+ if self.types.is_struct_vector(p.cpp_type)
+ or self._is_number_list(p)]
if list_fields:
parts = ', '.join(f"'{f}'" for f in list_fields)
lines.append(f' listFields: [{parts}],')
+ number_lists = [p.name for p in comp.properties if self._is_number_list(p)]
+ if number_lists:
+ parts = ', '.join(f"'{f}'" for f in number_lists)
+ lines.append(f' numberListFields: [{parts}],')
if color_fields:
parts = ', '.join(f"'{f}'" for f in color_fields)
diff --git a/tools/eht/generators/native_bindings.py b/tools/eht/generators/native_bindings.py
index 1e7086db5..04408a110 100644
--- a/tools/eht/generators/native_bindings.py
+++ b/tools/eht/generators/native_bindings.py
@@ -71,6 +71,11 @@ class NativeBindingsGenerator:
out = []
for prop in comp.properties:
t = self.types.clean_type(prop.cpp_type)
+ # A list of plain numbers crosses as a list of numbers: no members to
+ # walk, which is what the empty list below means downstream.
+ if t in self.types.VECTOR_TYPES and 'entity_ref' not in prop.annotations:
+ out.append((prop, []))
+ continue
if not self.types.is_struct_vector(t):
continue
elem = self.types.vector_elem(t)
@@ -89,12 +94,15 @@ class NativeBindingsGenerator:
f' const auto* c = esn_reg().tryGet<{full}>(esn_entity(ctx, argv[0]));',
' if (!c) return arr;',
' uint32_t i = 0;',
- f' for (const auto& v : c->{prop.name}) {{',
- ' JSValue o = JS_NewObject(ctx);']
- for m in members:
- out.append(f' JS_SetPropertyStr(ctx, o, "{m}", JS_NewFloat64(ctx, v.{m}));')
- out += [' JS_SetPropertyUint32(ctx, arr, i++, o);',
- ' }',
+ f' for (const auto& v : c->{prop.name}) {{']
+ if members:
+ out.append(' JSValue o = JS_NewObject(ctx);')
+ for m in members:
+ out.append(f' JS_SetPropertyStr(ctx, o, "{m}", JS_NewFloat64(ctx, v.{m}));')
+ out.append(' JS_SetPropertyUint32(ctx, arr, i++, o);')
+ else:
+ out.append(' JS_SetPropertyUint32(ctx, arr, i++, JS_NewFloat64(ctx, v));')
+ out += [' }',
' return arr;',
'}',
f'static JSValue {set_name}(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{',
@@ -110,10 +118,13 @@ class NativeBindingsGenerator:
' JSValue e = JS_GetPropertyUint32(ctx, argv[1], i);',
f' decltype(c.{prop.name})::value_type v{{}};',
' double n = 0;']
- for m in members:
- out += [f' {{ JSValue f = JS_GetPropertyStr(ctx, e, "{m}");',
- f' if (JS_ToFloat64(ctx, &n, f) == 0) v.{m} = static_cast<decltype(v.{m})>(n);',
- ' JS_FreeValue(ctx, f); }']
+ if members:
+ for m in members:
+ out += [f' {{ JSValue f = JS_GetPropertyStr(ctx, e, "{m}");',
+ f' if (JS_ToFloat64(ctx, &n, f) == 0) v.{m} = static_cast<decltype(v.{m})>(n);',
+ ' JS_FreeValue(ctx, f); }']
+ else:
+ out += [' if (JS_ToFloat64(ctx, &n, e) == 0) v = static_cast<decltype(v)>(n);']
out += [f' c.{prop.name}.push_back(v);',
' JS_FreeValue(ctx, e);',
' }',
diff --git a/tools/eht/generators/typescript.py b/tools/eht/generators/typescript.py
index 88bd305e3..b94041192 100644
--- a/tools/eht/generators/typescript.py
+++ b/tools/eht/generators/typescript.py
@@ -37,19 +37,20 @@ class TypeScriptGenerator:
for name, members in self.types.CUSTOM_STRUCTS.items():
fields = ' '.join(f'{m}: {self.types.member_ts_type(cpp)};' for m, cpp in members)
lines.append(f'export interface {name} {{ {fields} }}')
- lines.extend([
- 'export type Mat4 = number[];',
- '',
- '// Emscripten Vector Types',
- 'export interface VectorEntity {',
- ' size(): number;',
- ' get(index: number): number;',
- ' push_back(value: number): void;',
- ' set(index: number, value: number): boolean;',
- ' delete(): void;',
- '}',
- '',
- ])
+ lines.extend(['export type Mat4 = number[];', '', '// Emscripten Vector Types'])
+ # One interface per registered vector, driven by the same registry embind
+ # reads: a second list here would be one that could disagree with it.
+ for js_name in dict.fromkeys(n for _, n, _ in self.types.VECTOR_TYPES.values()):
+ lines.extend([
+ f'export interface {js_name} {{',
+ ' size(): number;',
+ ' get(index: number): number;',
+ ' push_back(value: number): void;',
+ ' set(index: number, value: number): boolean;',
+ ' delete(): void;',
+ '}',
+ '',
+ ])
return lines
def _gen_enums(self) -> List[str]:
diff --git a/tools/eht/type_system.py b/tools/eht/type_system.py
index 2a57d5353..87ac45172 100644
--- a/tools/eht/type_system.py
+++ b/tools/eht/type_system.py
@@ -34,7 +34,13 @@ class TypeSystem:
SKIP_TYPES = {'glm::mat4', 'std::function'}
- VECTOR_TYPES = {'std::vector<Entity>': ('u32', 'VectorEntity', 'VectorEntity')}
+ # `std::vector<T>` fields the boundary marshals: element C++ type, the embind
+ # vector registered for it, and the TS interface that names it. Adding one is
+ # an entry here — every generator below reads the registry.
+ VECTOR_TYPES = {
+ 'std::vector<Entity>': ('u32', 'VectorEntity', 'VectorEntity'),
+ 'std::vector<f32>': ('f32', 'VectorFloat', 'VectorFloat'),
+ }
CPP_TO_TS = {
'bool': 'boolean',
diff --git a/tools/gen-shader-twins.mjs b/tools/gen-shader-twins.mjs
index b09fd1fdb..f80a12279 100644
--- a/tools/gen-shader-twins.mjs
+++ b/tools/gen-shader-twins.mjs
@@ -66,6 +66,8 @@ const ENGINE_SAMPLERS = [
{ name: 'u_envMap', unit: 3 },
{ name: 'u_shadow2D', unit: 7 },
{ name: 'u_lightShape2D', unit: 6 },
+ // The one the VERTEX stage reads, pinned in MorphConstants.hpp.
+ { name: 'u_morphDeltas', unit: 4 },
];
// Group-1 unit map — mirrors WebGPUMappings textureBindingForUnit/samplerBindingForUnit.
diff --git a/tools/make-morph-fixture.mjs b/tools/make-morph-fixture.mjs
new file mode 100644
index 000000000..78422c2e3
--- /dev/null
+++ b/tools/make-morph-fixture.mjs
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * Regenerate the morph-target fixture: one quad, and one shape that moves the
+ * WHOLE of it a hundred units right. That much on purpose — a target that
+ * nudges a vertex passes whether or not the deltas reached the GPU.
+ *
+ * node tools/make-morph-fixture.mjs
+ */
+import { writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { encodeMesh, packChannels, MeshChannel, MeshChannelType } from '../sdk/dist/index.node.js';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const OUT = path.join(ROOT, 'fixtures', 'scenes', 'morph-quad.esmesh');
+
+/** Centred on (-50, 0) so the authored shape sits in the frame's left half. */
+const POSITIONS = [
+ [-70, -20, 0], [-30, -20, 0], [-30, 20, 0], [-70, 20, 0],
+];
+const UVS = [[0, 0], [1, 0], [1, 1], [0, 1]];
+const SHIFT = 100;
+
+const { channels, vertexStride } = packChannels([
+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },
+]);
+
+const vertices = new Uint8Array(POSITIONS.length * vertexStride);
+const view = new DataView(vertices.buffer);
+POSITIONS.forEach((p, i) => {
+ const at = i * vertexStride;
+ for (let c = 0; c < 3; c++) view.setFloat32(at + channels[0].offset + c * 4, p[c], true);
+ view.setFloat32(at + channels[1].offset, UVS[i][0], true);
+ view.setFloat32(at + channels[1].offset + 4, UVS[i][1], true);
+ for (let c = 0; c < 4; c++) view.setUint8(at + channels[2].offset + c, 255);
+});
+
+const deltas = new Float32Array(POSITIONS.length * 3);
+for (let i = 0; i < POSITIONS.length; i++) deltas[i * 3] = SHIFT;
+
+writeFileSync(OUT, encodeMesh({
+ channels, vertexStride, vertexCount: POSITIONS.length, vertices,
+ indices: Uint32Array.from([0, 1, 2, 0, 2, 3]),
+ aabbMin: [-70, -20, 0], aabbMax: [-30, 20, 0],
+ morph: { names: ['Shift'], hasNormals: false, deltas },
+}));
+console.log(`wrote ${path.relative(ROOT, OUT)}`);
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index 3045d909d..e9077ccde 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -106,6 +106,15 @@ export const SCENES = [
// and there was no skinned one, so a skinned mesh fell back to the engine's
// shader and ignored what it was made of (sabotage: the probes come back white).
{ id: "mesh-skin-material", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-skin-mat.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.35,\"y\":0.6,\"rgb\":[0,0,255],\"tol\":30},{\"x\":0.75,\"y\":0.35,\"rgb\":[0,0,255],\"tol\":30},{\"x\":0.75,\"y\":0.60,\"rgb\":[0,0,0],\"tol\":20}]" } },
+ // The two halves of one claim: the SAME mesh, the same two points, and the
+ // weight is the only thing that differs. A quad in its authored place proves
+ // nothing alone — a morph that never reached the GPU passes the first.
+ { id: "mesh-morph-rest", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-morph-off.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.25,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":30},{\"x\":0.75,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20}]" } },
+ { id: "mesh-morph-shaped", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-morph-on.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.75,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":30},{\"x\":0.25,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20}]" } },
+ // A material shader writes no vertex stage, so it takes the engine's — a
+ // DIFFERENT copy of the deform. Through the other source, the same shape: the
+ // two must move the quad alike or one of them is not deforming at all.
+ { id: "mesh-morph-material", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-morph-mat.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.75,\"y\":0.5,\"rgb\":[0,0,255],\"tol\":30},{\"x\":0.25,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20}]" } },
// A mesh casting on a mesh: a floor 200 units below a blocker, sun leaning 0.5 in
// x, so the shadow lands 100 along +x and x 75..175 is floor the light cannot see.
// The blocker itself stays lit — shadowing one's own caster is the classic bug.