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 skinned model deforms

esengine678f616ab9eb
diff --git a/desktop/public/scenes/mesh-skin.esscene b/desktop/public/scenes/mesh-skin.esscene
new file mode 100644
index 000000000..8b50ea987
--- /dev/null
+++ b/desktop/public/scenes/mesh-skin.esscene
@@ -0,0 +1,62 @@
+{
+ "version": 1,
+ "name": "MeshSkin",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "components": [
+ {
+ "type": "Transform",
+ "data": { "position": { "x": 60, "y": 20, "z": 10 } }
+ },
+ {
+ "type": "Camera",
+ "data": { "projectionType": 1, "orthoSize": 100, "isActive": true, "priority": 0 }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 1,
+ "name": "Bone0",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } }
+ ],
+ "visible": true
+ },
+ {
+ "id": 2,
+ "name": "Bone1",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 60, "y": 60, "z": 0 } } }
+ ],
+ "visible": true
+ },
+ {
+ "id": 3,
+ "name": "Body",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },
+ {
+ "type": "Mesh2D",
+ "data": {
+ "mesh": "scenes/skinned-arm.esmesh",
+ "color": { "r": 0, "g": 1, "b": 0, "a": 1 },
+ "enabled": true
+ }
+ },
+ { "type": "MeshSkin", "data": { "joints": [1, 2] } }
+ ],
+ "visible": true
+ }
+ ]
+}
diff --git a/desktop/public/scenes/skinned-arm.esmesh b/desktop/public/scenes/skinned-arm.esmesh
new file mode 100644
index 000000000..31f790bdf
Binary files /dev/null and b/desktop/public/scenes/skinned-arm.esmesh differ
diff --git a/desktop/public/scenes/skinned-arm.esmesh.meta b/desktop/public/scenes/skinned-arm.esmesh.meta
new file mode 100644
index 000000000..7c03ea3eb
--- /dev/null
+++ b/desktop/public/scenes/skinned-arm.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "8fe8b390-505a-45d6-901e-21785b321820",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/desktop/public/scenes/skinned-arm.esprefab b/desktop/public/scenes/skinned-arm.esprefab
new file mode 100644
index 000000000..82d7856e9
--- /dev/null
+++ b/desktop/public/scenes/skinned-arm.esprefab
@@ -0,0 +1,85 @@
+{
+ "version": "2",
+ "name": "skinned-arm",
+ "rootEntityId": "n0",
+ "entities": [
+ {
+ "prefabEntityId": "n0",
+ "name": "Rig",
+ "parent": null,
+ "children": [
+ "n1",
+ "n2",
+ "n3"
+ ],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ }
+ ]
+ },
+ {
+ "prefabEntityId": "n1",
+ "name": "Bone0",
+ "parent": "n0",
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ }
+ ]
+ },
+ {
+ "prefabEntityId": "n2",
+ "name": "Bone1",
+ "parent": "n0",
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 60,
+ "y": 0,
+ "z": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "prefabEntityId": "n3",
+ "name": "Body",
+ "parent": "n0",
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "Mesh2D",
+ "data": {
+ "mesh": "scenes/skinned-arm.esmesh",
+ "enabled": true
+ }
+ },
+ {
+ "type": "MeshSkin",
+ "data": {
+ "joints": [
+ "n1",
+ "n2"
+ ]
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/desktop/public/scenes/skinned-arm.esprefab.meta b/desktop/public/scenes/skinned-arm.esprefab.meta
new file mode 100644
index 000000000..d731833b0
--- /dev/null
+++ b/desktop/public/scenes/skinned-arm.esprefab.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "dbe01388-b8ff-4a85-bf8f-3f6e3fbe1cba",
+ "version": "2.0",
+ "type": "prefab",
+ "importer": {}
+}
diff --git a/desktop/public/scenes/skinned-arm.gltf b/desktop/public/scenes/skinned-arm.gltf
new file mode 100644
index 000000000..7a0404762
--- /dev/null
+++ b/desktop/public/scenes/skinned-arm.gltf
@@ -0,0 +1,140 @@
+{
+ "asset": {
+ "version": "2.0",
+ "generator": "estella test fixture"
+ },
+ "buffers": [
+ {
+ "byteLength": 370,
+ "uri": "data:application/octet-stream;base64,AAAAAAAAoMEAAAAAAAAAAAAAoEEAAAAAAABwQgAAoMEAAAAAAABwQgAAoEEAAAAAAADwQgAAoMEAAAAAAADwQgAAoEEAAAAAAAACAAEAAQACAAMAAgAEAAMAAwAEAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAAAAAAIA/AACAPwAAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAAAAAAAAgD8AAAAAAABwwgAAAAAAAAAAAACAPw=="
+ }
+ ],
+ "bufferViews": [
+ {
+ "buffer": 0,
+ "byteOffset": 0,
+ "byteLength": 72
+ },
+ {
+ "buffer": 0,
+ "byteOffset": 72,
+ "byteLength": 24
+ },
+ {
+ "buffer": 0,
+ "byteOffset": 98,
+ "byteLength": 48
+ },
+ {
+ "buffer": 0,
+ "byteOffset": 146,
+ "byteLength": 96
+ },
+ {
+ "buffer": 0,
+ "byteOffset": 242,
+ "byteLength": 128
+ }
+ ],
+ "accessors": [
+ {
+ "bufferView": 0,
+ "componentType": 5126,
+ "count": 6,
+ "type": "VEC3",
+ "min": [
+ 0,
+ -20,
+ 0
+ ],
+ "max": [
+ 120,
+ 20,
+ 0
+ ]
+ },
+ {
+ "bufferView": 1,
+ "componentType": 5123,
+ "count": 12,
+ "type": "SCALAR"
+ },
+ {
+ "bufferView": 2,
+ "componentType": 5123,
+ "count": 6,
+ "type": "VEC4"
+ },
+ {
+ "bufferView": 3,
+ "componentType": 5126,
+ "count": 6,
+ "type": "VEC4"
+ },
+ {
+ "bufferView": 4,
+ "componentType": 5126,
+ "count": 2,
+ "type": "MAT4"
+ }
+ ],
+ "meshes": [
+ {
+ "name": "Arm",
+ "primitives": [
+ {
+ "attributes": {
+ "POSITION": 0,
+ "JOINTS_0": 2,
+ "WEIGHTS_0": 3
+ },
+ "indices": 1,
+ "mode": 4
+ }
+ ]
+ }
+ ],
+ "nodes": [
+ {
+ "name": "Rig",
+ "children": [
+ 1,
+ 2,
+ 3
+ ]
+ },
+ {
+ "name": "Bone0"
+ },
+ {
+ "name": "Bone1",
+ "translation": [
+ 60,
+ 0,
+ 0
+ ]
+ },
+ {
+ "name": "Body",
+ "mesh": 0,
+ "skin": 0
+ }
+ ],
+ "scenes": [
+ {
+ "nodes": [
+ 0
+ ]
+ }
+ ],
+ "scene": 0,
+ "skins": [
+ {
+ "joints": [
+ 1,
+ 2
+ ],
+ "inverseBindMatrices": 4
+ }
+ ]
+}
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index e4a8b5025..a851d7ed7 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -270,7 +270,7 @@ mesh2d_setMaterialAll: ((registry: CppRegistry, materialId: number) => number) |
mesh2d_setMesh: ((registry: CppRegistry, entity: number, meshHandle: number) => void) | undefined
mesh2d_setMeshAll: ((registry: CppRegistry, meshHandle: number) => number) | undefined
mesh_create: ((posUvPtr: number, vertexCount: number, colorsPtr: number, indicesPtr: number, indexCount: 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) => 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_release: ((meshHandle: number) => void) | undefined
notifyDeviceLost: ((reason: number, message: string) => void) | undefined
particle_getAliveCount: ((entity: number) => number) | undefined
diff --git a/sdk/src/asset/loaders/MeshAssetLoader.ts b/sdk/src/asset/loaders/MeshAssetLoader.ts
index be83bdd34..ee0b5ca34 100644
--- a/sdk/src/asset/loaders/MeshAssetLoader.ts
+++ b/sdk/src/asset/loaders/MeshAssetLoader.ts
@@ -37,16 +37,25 @@ export class MeshAssetLoader implements AssetLoader<MeshResult> {
const tablePtr = alloc(table.byteLength);
const vertexPtr = alloc(mesh.vertices.byteLength);
const indexPtr = alloc(mesh.indices.byteLength);
+ // The bind pose goes over with the geometry: the Joints channel
+ // indexes it, so an engine holding one without the other could only
+ // guess what a vertex is bound to.
+ const bind = mesh.inverseBindMatrices;
+ const bindPtr = bind ? alloc(bind.byteLength) : 0;
m.HEAPU8.set(table, tablePtr);
m.HEAPU8.set(mesh.vertices, vertexPtr);
m.HEAPU8.set(new Uint8Array(mesh.indices.buffer, mesh.indices.byteOffset,
mesh.indices.byteLength), indexPtr);
+ if (bind) {
+ m.HEAPU8.set(new Uint8Array(bind.buffer, bind.byteOffset, bind.byteLength), bindPtr);
+ }
return m.mesh_createFromChannels!(
tablePtr, mesh.channels.length, mesh.vertexStride,
vertexPtr, mesh.vertices.byteLength,
indexPtr, mesh.indices.length,
mesh.aabbMin[0], mesh.aabbMin[1], mesh.aabbMin[2],
- mesh.aabbMax[0], mesh.aabbMax[1], mesh.aabbMax[2]);
+ mesh.aabbMax[0], mesh.aabbMax[1], mesh.aabbMax[2],
+ bindPtr, bind?.length ?? 0);
});
if (!handle) throw new Error(`the engine rejected the geometry in ${path}`);
diff --git a/sdk/src/ecs/bridge/BuiltinBridge.ts b/sdk/src/ecs/bridge/BuiltinBridge.ts
index e1e2693c0..52c66865e 100644
--- a/sdk/src/ecs/bridge/BuiltinBridge.ts
+++ b/sdk/src/ecs/bridge/BuiltinBridge.ts
@@ -69,6 +69,32 @@ export function convertForWasm(
return obj;
}
+/** An embind std::vector<Entity>, which its owner has to free. */
+interface WasmVector { push_back(v: number): void; 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.
+ * The boundary the colours above cross: a JS array is what a document stores,
+ * `std::vector<Entity>` is what the component holds.
+ */
+export function materializeEntityVectors(
+ obj: Record<string, unknown>, entityFields: readonly string[],
+ module: { VectorEntity?: new () => WasmVector } | null,
+): WasmVector[] {
+ const made: WasmVector[] = [];
+ if (!module?.VectorEntity) return made;
+ for (const key of entityFields) {
+ const val = obj[key];
+ if (!Array.isArray(val)) continue;
+ const vec = new module.VectorEntity();
+ for (const e of val) vec.push_back(Number(e) >>> 0);
+ obj[key] = vec;
+ made.push(vec);
+ }
+ return made;
+}
+
// =============================================================================
// Pointer-based Field Access
// =============================================================================
@@ -575,7 +601,15 @@ export class BuiltinBridge {
try {
const methods = this.getBuiltinMethods(component._cppName);
isNew = !methods.has(entity);
- methods.add(entity, convertForWasm(merged as Record<string, unknown>, component.colorKeys));
+ const payload = convertForWasm(merged as Record<string, unknown>, component.colorKeys);
+ const vectors = materializeEntityVectors(
+ payload, component.entityFields ?? [],
+ this.module_ as unknown as { VectorEntity?: new () => WasmVector } | null);
+ try {
+ methods.add(entity, payload);
+ } finally {
+ for (const v of vectors) v.delete();
+ }
} catch (e) {
handleWasmError(e, `insertBuiltin(${component._name}, entity=${entity})`);
}
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index 924069fae..28ac7d1b2 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -72,7 +72,7 @@ export interface NativeEngineApi {
mesh2d_setMesh?(registry: unknown, entity: number, meshHandle: number): void;
mesh2d_setMeshAll?(registry: unknown, meshHandle: number): number;
mesh_create?(posUvPtr: number, vertexCount: number, colorsPtr: number, indicesPtr: number, indexCount: 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): 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_release?(meshHandle: number): void;
particle_getAliveCount?(entity: number): number;
particle_play?(registry: unknown, entity: number): void;
diff --git a/sdk/src/scene/scene.ts b/sdk/src/scene/scene.ts
index 6ffeca50e..7ad6c2c74 100644
--- a/sdk/src/scene/scene.ts
+++ b/sdk/src/scene/scene.ts
@@ -163,19 +163,25 @@ export function remapEntityFields(compData: SceneComponentData, entityMap: Map<n
const comp = getComponent(compData.type);
if (!comp || comp.entityFields.length === 0) return;
const data = compData.data as Record<string, unknown>;
- for (const field of comp.entityFields) {
- const editorId = data[field];
- if (typeof editorId === 'number' && editorId !== INVALID_ENTITY) {
- const runtimeId = entityMap.get(editorId);
- if (runtimeId === undefined) {
- log.warn(
- 'scene',
- `Entity reference not found: ${compData.type}.${field} ` +
- `references entity ${editorId} which does not exist`,
- );
- }
- data[field] = runtimeId !== undefined ? runtimeId : INVALID_ENTITY;
+ const remap = (editorId: unknown): unknown => {
+ if (typeof editorId !== 'number' || editorId === INVALID_ENTITY) return editorId;
+ const runtimeId = entityMap.get(editorId);
+ if (runtimeId === undefined) {
+ log.warn(
+ 'scene',
+ `Entity reference not found: ${compData.type}.${field} ` +
+ `references entity ${editorId} which does not exist`,
+ );
}
+ return runtimeId !== undefined ? runtimeId : INVALID_ENTITY;
+ };
+ // A field can name ONE entity or a list of them (a skin's joints). A list
+ // that skipped this kept the document's own ids, which name other entities
+ // at runtime — the reference silently resolves to the wrong thing.
+ let field = '';
+ for (field of comp.entityFields) {
+ const value = data[field];
+ data[field] = Array.isArray(value) ? value.map(remap) : remap(value);
}
}
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 2a064af9e..ecb7c075c 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -242,7 +242,8 @@ export interface ESEngineModule {
vertexPtr: number, vertexBytes: number,
indexPtr: number, indexCount: number,
minX: number, minY: number, minZ: number,
- maxX: number, maxY: number, maxZ: number): number;
+ maxX: number, maxY: number, maxZ: number,
+ bindPtr: number, bindFloats: number): number;
/** Release a mesh and the buffers it owns. */
mesh_release?(meshHandle: number): void;
/** Point a Mesh2D at a resident mesh; 0 returns it to its inline payload. */
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 40fd8a7c3..19298a34a 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -262,7 +262,8 @@ u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexS
uintptr_t vertexPtr, u32 vertexBytes,
uintptr_t indexPtr, u32 indexCount,
f32 minX, f32 minY, f32 minZ,
- f32 maxX, f32 maxY, f32 maxZ) {
+ f32 maxX, f32 maxY, f32 maxZ,
+ uintptr_t bindPtr, u32 bindFloats) {
auto* rm = ctx().tryGet<resource::ResourceManager>();
if (!rm || channelCount == 0 || vertexStride == 0 || vertexBytes == 0 || indexCount == 0) return 0;
if (indexCount % 3 != 0) {
@@ -310,10 +311,15 @@ u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexS
};
}
+ // The bind pose rides beside the vertices because the Joints channel indexes
+ // it; a mesh with joints and no matrices is drawn static rather than wrong.
+ const f32* bind = bindFloats > 0
+ ? boundarySpan<f32>(bindPtr, bindFloats, "mesh_createFromChannels.inverseBind") : nullptr;
auto handle = rm->createMesh(ConstSpan<u8>(verts, vertexBytes),
ConstSpan<u32>(indices, indexCount),
ConstSpan<GfxVertexAttribute>(channels, channelCount), vertexStride,
- glm::vec3(minX, minY, minZ), glm::vec3(maxX, maxY, maxZ));
+ glm::vec3(minX, minY, minZ), glm::vec3(maxX, maxY, maxZ),
+ bind ? ConstSpan<f32>(bind, bindFloats) : ConstSpan<f32>());
return handle.id();
}
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index 566ac7902..d237ae1b0 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -74,7 +74,8 @@ u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexS
uintptr_t vertexPtr, u32 vertexBytes,
uintptr_t indexPtr, u32 indexCount,
f32 minX, f32 minY, f32 minZ,
- f32 maxX, f32 maxY, f32 maxZ);
+ f32 maxX, f32 maxY, f32 maxZ,
+ uintptr_t bindPtr, u32 bindFloats);
/** @brief Releases a mesh and the buffers it owns. */
void mesh_release(u32 meshHandle);
/** @brief Uploads geometry that stays on the GPU; returns its handle, 0 on failure. */
diff --git a/src/esengine/data/shaders/mesh.esshader b/src/esengine/data/shaders/mesh.esshader
index adbeb0ad3..99d56fccf 100644
--- a/src/esengine/data/shaders/mesh.esshader
+++ b/src/esengine/data/shaders/mesh.esshader
@@ -17,6 +17,11 @@
// (off a constant normal, which is what a 2D surface has).
#pragma feature LIT
+// Geometry deformed by joints. Its own transform is NOT read: a skinned mesh's
+// node placement is ignored (glTF requires it) because the bones are already
+// world-space, so the per-object record carries only a tint.
+#pragma feature SKINNED
+
// A normal map on top of those normals. Its tangent frame comes from the shared
// perturbNormal (screen-space derivatives), so the geometry needs no tangent
// channel — which is why this rides LIT rather than a vertex attribute.
@@ -34,15 +39,21 @@ layout(location = 2) in vec2 a_texCoord;
#ifdef MESH_NORMALS
layout(location = 3) in vec3 a_normal;
#endif
+#ifdef SKINNED
+layout(location = 5) in uvec4 a_joints;
+layout(location = 6) in vec4 a_weights;
+#endif
// 8.. and not 3..: a channel's semantic IS its location, so adding normals to a
// mesh must not move the per-object record (see MESH_INSTANCE_FIRST_LOCATION).
+#ifndef SKINNED
layout(location = 8) in vec4 a_model0;
layout(location = 9) in vec4 a_model1;
layout(location = 10) in vec4 a_model2;
layout(location = 11) in vec4 a_model3;
+#endif
layout(location = 12) in vec4 a_instTint;
-#ifdef MESH_NORMALS
+#if defined(MESH_NORMALS) && !defined(SKINNED)
// The normal matrix (inverse transpose of the model's 3x3), per object: under a
// non-uniform scale the model matrix skews a normal, and inverting one per
// vertex is the alternative.
@@ -55,6 +66,13 @@ layout(std140) uniform FrameConstants {
mat4 u_projection;
};
+#ifdef SKINNED
+// This draw's pose, rewritten immediately before it (SkinConstants, binding 5).
+layout(std140) uniform SkinConstants {
+ mat4 u_bones[64];
+};
+#endif
+
out vec2 v_texCoord;
out vec4 v_color;
#ifdef LIT
@@ -65,13 +83,25 @@ out highp vec3 v_worldPos;
#endif
void main() {
+#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.
+ mat4 skin = a_weights.x * u_bones[a_joints.x]
+ + 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);
+#else
mat4 model = mat4(a_model0, a_model1, a_model2, a_model3);
vec4 world = model * vec4(a_position, 1.0);
+#endif
gl_Position = u_projection * world;
v_texCoord = a_texCoord;
v_color = a_color * a_instTint;
#ifdef LIT
-#ifdef MESH_NORMALS
+#if defined(MESH_NORMALS) && defined(SKINNED)
+ v_worldNormal = mat3(skin) * a_normal;
+#elif defined(MESH_NORMALS)
v_worldNormal = mat3(a_nrm0, a_nrm1, a_nrm2) * a_normal;
#else
// A surface with no normal channel faces the viewer, exactly as a sprite does.
@@ -117,6 +147,11 @@ void main() {
struct FrameConstants { projection : mat4x4f };
@group(0) @binding(0) var<uniform> frame : FrameConstants;
+#ifdef SKINNED
+struct SkinConstants { bones : array<mat4x4f, 64> };
+@group(0) @binding(5) var<uniform> skin : SkinConstants;
+#endif
+
struct VSIn {
@location(0) a_position : vec3f,
@location(1) a_color : vec4f,
@@ -124,16 +159,23 @@ struct VSIn {
#ifdef MESH_NORMALS
@location(3) a_normal : vec3f,
#endif
+#ifdef SKINNED
+ @location(5) a_joints : vec4u,
+ @location(6) a_weights : vec4f,
+#else
@location(8) a_model0 : vec4f,
@location(9) a_model1 : vec4f,
@location(10) a_model2 : vec4f,
@location(11) a_model3 : vec4f,
+#endif
@location(12) a_instTint : vec4f,
#ifdef MESH_NORMALS
+#ifndef SKINNED
@location(13) a_nrm0 : vec3f,
@location(14) a_nrm1 : vec3f,
@location(15) a_nrm2 : vec3f,
#endif
+#endif
};
struct VSOut {
@builtin(position) pos : vec4f,
@@ -146,8 +188,18 @@ struct VSOut {
};
@vertex fn vs_main(v : VSIn) -> VSOut {
+#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.
+ let pose = v.a_weights.x * skin.bones[v.a_joints.x]
+ + 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);
+#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);
+#endif
var out : VSOut;
out.pos = frame.projection * world;
@@ -155,7 +207,11 @@ struct VSOut {
out.v_color = v.a_color * v.a_instTint;
#ifdef LIT
#ifdef MESH_NORMALS
+#ifdef SKINNED
+ out.v_worldNormal = mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * v.a_normal;
+#else
out.v_worldNormal = mat3x3f(v.a_nrm0, v.a_nrm1, v.a_nrm2) * v.a_normal;
+#endif
#else
// A surface with no normal channel faces the viewer, exactly as a sprite does.
out.v_worldNormal = vec3f(0.0, 0.0, 1.0);
diff --git a/src/esengine/renderer/draw/BatchBuilder.cpp b/src/esengine/renderer/draw/BatchBuilder.cpp
index d1cc93302..f51aa88bf 100644
--- a/src/esengine/renderer/draw/BatchBuilder.cpp
+++ b/src/esengine/renderer/draw/BatchBuilder.cpp
@@ -89,6 +89,8 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,
cmd.vertex_buffer = key.vertexBuffer;
cmd.index_buffer = key.indexBuffer;
cmd.vertex_layout = key.vertexLayout;
+ cmd.skin_offset = key.skinOffset;
+ cmd.skin_count = key.skinCount;
cmd.shader_id = key.shaderId;
cmd.blend_mode = key.blend;
cmd.layout_id = key.layoutId;
diff --git a/src/esengine/renderer/draw/BatchBuilder.hpp b/src/esengine/renderer/draw/BatchBuilder.hpp
index 2b55b0baa..525a3ddf5 100644
--- a/src/esengine/renderer/draw/BatchBuilder.hpp
+++ b/src/esengine/renderer/draw/BatchBuilder.hpp
@@ -113,6 +113,11 @@ struct BatchDrawKey {
BufferHandle vertexBuffer = BufferHandle::Invalid;
BufferHandle indexBuffer = BufferHandle::Invalid;
VertexLayoutHandle vertexLayout = VertexLayoutHandle::Invalid;
+
+ // A skinned draw's pose, already in the frame's matrix pool. Passed through
+ // like the buffers above: what deforms a draw is the draw's, not the batch's.
+ u32 skinOffset = 0;
+ u32 skinCount = 0;
};
/**
diff --git a/src/esengine/renderer/draw/DrawCommand.hpp b/src/esengine/renderer/draw/DrawCommand.hpp
index 3654a9be5..f7058d242 100644
--- a/src/esengine/renderer/draw/DrawCommand.hpp
+++ b/src/esengine/renderer/draw/DrawCommand.hpp
@@ -116,6 +116,11 @@ struct DrawCommand {
BufferHandle index_buffer = BufferHandle::Invalid;
VertexLayoutHandle vertex_layout = VertexLayoutHandle::Invalid;
+ // A skinned draw's pose: where its bone matrices start in the frame's pool
+ // and how many there are. Zero count = the geometry is not deformed.
+ u32 skin_offset = 0;
+ u32 skin_count = 0;
+
bool hasPersistentGeometry() const { return vertex_buffer != BufferHandle::Invalid; }
// Vertices owned by this command (from vertex_byte_offset). Needed so the merge pass
diff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cpp
index 5285c5216..90be3ec2a 100644
--- a/src/esengine/renderer/draw/DrawList.cpp
+++ b/src/esengine/renderer/draw/DrawList.cpp
@@ -24,9 +24,16 @@ void rewriteTexIndex(TransientBufferPool& pool, const DrawCommand& cmd, i32 slot
void DrawList::clear() {
commands_.clear();
sort_entries_.clear();
+ skin_matrices_.clear();
merged_draw_calls_ = 0;
}
+u32 DrawList::addSkinMatrices(const glm::mat4* matrices, u32 count) {
+ const u32 at = static_cast<u32>(skin_matrices_.size());
+ skin_matrices_.insert(skin_matrices_.end(), matrices, matrices + count);
+ return at;
+}
+
void DrawList::push(const DrawCommand& cmd) {
commands_.push_back(cmd);
}
@@ -121,7 +128,7 @@ void DrawList::finalize(TransientBufferPool& pool) {
void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
MaterialStore& materials, u32 white_texture_id,
- FrameCapture* capture) {
+ FrameCapture* capture, BufferHandle skin_ubo) {
PipelineDesc lastDesc{};
PipelineHandle lastHandle = PipelineHandle::Invalid;
@@ -166,6 +173,14 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
materials.bindForDraw(cmd.material_id);
}
+ // The pose, for a draw that has one. Written immediately before the draw
+ // that reads it: one draw's bones are in flight at a time, which is what
+ // lets a single block serve every skinned mesh in the frame.
+ if (cmd.skin_count > 0 && skin_ubo != BufferHandle::Invalid) {
+ device.updateBuffer(skin_ubo, 0, skin_matrices_.data() + cmd.skin_offset,
+ cmd.skin_count * sizeof(glm::mat4));
+ }
+
// 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 37bd8414b..eda812ed5 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 "../../math/Math.hpp"
#include <vector>
@@ -34,7 +35,13 @@ public:
// (filling with the draw's own tex re-pointed all 8 units on every tex change).
void execute(GfxDevice& device, TransientBufferPool& buffers,
MaterialStore& materials, u32 white_texture_id = 0,
- FrameCapture* capture = nullptr);
+ FrameCapture* capture = nullptr,
+ BufferHandle skin_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(); }
u32 commandCount() const { return static_cast<u32>(commands_.size()); }
u32 mergedDrawCallCount() const { return merged_draw_calls_; }
@@ -99,6 +106,8 @@ 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<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 0bc3a3db7..a45f4f750 100644
--- a/src/esengine/renderer/frame/RenderContext.cpp
+++ b/src/esengine/renderer/frame/RenderContext.cpp
@@ -15,6 +15,7 @@
#include "../rhi/GfxDevice.hpp"
#include "./FrameConstants.hpp"
#include "../draw/DrawParams.hpp"
+#include "../store/SkinConstants.hpp"
#include "../../core/Log.hpp"
#include <vector>
@@ -142,6 +143,14 @@ void RenderContext::initFrameUbo() {
{GfxBufferUsage::Uniform, DRAW_PARAMS_FALLBACK_SIZE, /*dynamic=*/false}, zeros.data());
device_.setUniformBuffer(DRAW_PARAMS_BINDING, drawParamsFallback_);
+ // A skinned draw's pose. Bound once and rewritten per draw: only one draw's
+ // bones are ever in flight, and a mesh with none never reads the block.
+ const std::vector<u8> bones(sizeof(SkinConstants), 0);
+ skinUbo_ = device_.createBuffer(
+ {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(SkinConstants)), /*dynamic=*/true},
+ bones.data());
+ device_.setUniformBuffer(SKIN_CONSTANTS_BINDING, skinUbo_);
+
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 7b10e2308..fba3c255b 100644
--- a/src/esengine/renderer/frame/RenderContext.hpp
+++ b/src/esengine/renderer/frame/RenderContext.hpp
@@ -193,6 +193,14 @@ private:
BufferHandle frameUbo_ = BufferHandle::Invalid;
BufferHandle timeUbo_ = BufferHandle::Invalid;
BufferHandle drawParamsFallback_ = BufferHandle::Invalid;
+ /// One skinned draw's bone matrices, rewritten immediately before that draw.
+ BufferHandle skinUbo_ = BufferHandle::Invalid;
+
+public:
+ /** @brief The per-draw bone-matrix block a skinned draw writes into. */
+ BufferHandle skinUbo() const { return skinUbo_; }
+
+private:
f32 lastElapsed_ = 0.0f;
MaterialStore materials_;
LightStore lights_;
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index a8147ecbd..555af1a2d 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -336,7 +336,8 @@ void RenderFrame::flush() {
{
ES_PROFILE_SCOPE("render.submit");
gpu_timer_.begin(device_);
- draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(), &frame_capture_);
+ draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
+ &frame_capture_, context_.skinUbo());
gpu_timer_.end(device_);
}
FrameProfiler::get().gpuScope("submit", gpu_timer_.lastMs());
@@ -453,7 +454,8 @@ void RenderFrame::replayToDrawCall(i32 stopAtDrawCall) {
context_.updateFrameConstants(view_projection_);
context_.lights().uploadAndBind();
- draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(), &frame_capture_);
+ draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
+ &frame_capture_, context_.skinUbo());
// Leave scissor disabled for whatever renders next; invalidate so the next
// setPipeline re-applies its full state (stencil included).
@@ -508,7 +510,8 @@ void RenderFrame::renderToTarget(ecs::Registry& registry, const glm::mat4& viewP
pool_.upload();
context_.updateFrameConstants(viewProjection);
context_.lights().uploadAndBind();
- draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(), &frame_capture_);
+ draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
+ &frame_capture_, context_.skinUbo());
frame_capture_.endCapture();
rt->unbind();
diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cpp
index 54b221e2b..5b59cb501 100644
--- a/src/esengine/renderer/plugins/MeshPlugin.cpp
+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp
@@ -35,8 +35,40 @@ u32 mulColor(u32 a, u32 b) {
}
/// Which program a draw needs: what the GEOMETRY carries and what the DRAW asked
/// for are separate questions, so they are separate bits.
-u32 meshVariant(bool normals, bool lit, bool normalMapped) {
- return (normals ? 1u : 0u) | (lit ? 2u : 0u) | (normalMapped ? 4u : 0u);
+/**
+ * This entity's pose: joint world placement times the mesh's own bind matrix,
+ * one per joint. Returns 0 — draw it static — when the two disagree about how
+ * many joints there are, since an index resolved against the wrong matrix moves
+ * the vertex somewhere arbitrary.
+ */
+u32 skinPose(ecs::Registry& registry, Entity entity, const Mesh& mesh,
+ std::vector<glm::mat4>& out) {
+ if (!mesh.isSkinned()) return 0;
+ const auto* skin = registry.tryGet<ecs::MeshSkin>(entity);
+ if (!skin || skin->joints.size() != mesh.inverseBind.size()) return 0;
+ const u32 count = static_cast<u32>(std::min<usize>(skin->joints.size(), MESH_MAX_BONES));
+
+ out.resize(count);
+ for (u32 i = 0; i < count; ++i) {
+ auto* joint = registry.tryGet<ecs::Transform>(skin->joints[i]);
+ // A joint that is not there leaves the bind pose, which is the mesh as
+ // authored rather than a vertex collapsed onto the origin.
+ if (!joint) { out[i] = glm::mat4(1.0f); continue; }
+ // Built from the decomposed world fields, the same three every other
+ // draw is placed by — the cached matrix is the transform system's own
+ // and is not guaranteed current for an entity nothing parents.
+ joint->ensureDecomposed();
+ const glm::mat4 world = glm::translate(glm::mat4(1.0f), joint->worldPosition)
+ * glm::mat4_cast(joint->worldRotation)
+ * glm::scale(glm::mat4(1.0f), joint->worldScale);
+ out[i] = world * mesh.inverseBind[i];
+ }
+ return count;
+}
+
+u32 meshVariant(bool normals, bool lit, bool normalMapped, bool skinned) {
+ return (normals ? 1u : 0u) | (lit ? 2u : 0u) | (normalMapped ? 4u : 0u)
+ | (skinned ? 8u : 0u);
}
} // namespace
@@ -54,7 +86,7 @@ void MeshPlugin::init(RenderFrameContext& ctx) {
mesh_programs_.fill(0);
// The base variant now, so a broken shader is a boot-time failure rather than
// one that waits for the first mesh; the rest compile when a draw asks.
- meshProgram(ctx, false, false, false);
+ meshProgram(ctx, false, false, false, false);
}
/**
@@ -64,8 +96,9 @@ void MeshPlugin::init(RenderFrameContext& ctx) {
* geometry's own channels pick half of it; the draw's `lit` picks the other half,
* and unlit geometry carrying normals still has to declare them.
*/
-u32 MeshPlugin::meshProgram(RenderFrameContext& ctx, bool normals, bool lit, bool normalMapped) {
- const u32 variant = meshVariant(normals, lit, normalMapped);
+u32 MeshPlugin::meshProgram(RenderFrameContext& ctx, bool normals, bool lit, bool normalMapped,
+ bool skinned) {
+ const u32 variant = meshVariant(normals, lit, normalMapped, skinned);
if (mesh_compiled_[variant]) return mesh_programs_[variant];
mesh_compiled_[variant] = true;
@@ -73,6 +106,7 @@ u32 MeshPlugin::meshProgram(RenderFrameContext& ctx, bool normals, bool lit, boo
if (normals) features.emplace_back("MESH_NORMALS");
if (lit) features.emplace_back("LIT");
if (normalMapped) features.emplace_back("NORMAL_MAP");
+ if (skinned) features.emplace_back("SKINNED");
// Authored as mesh.esshader, WGSL twin included. Its vertex stage is the one
// that reads a model matrix, which is what lets the vertices stay local.
@@ -197,21 +231,33 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
// vertices are local-space and untouched, so the CPU loop below — which
// exists to bake world space into every vertex — is skipped entirely.
if (resident && mesh_programs_[0] != 0) {
+ // The pose, when this entity says what moves it. The bones are
+ // world-space, so the entity's own transform is not read — which is
+ // what glTF requires of a skinned mesh.
+ const u32 poseSize = skinPose(registry, entity, *resident, pose_scratch_);
+ const bool skinned = poseSize > 0;
+
// `lit` is the draw's own word and is honoured either way: geometry
// with normals can be drawn unlit, and geometry without them takes
// light off the constant normal a 2D surface has.
const u32 residentShader =
- meshProgram(ctx, resident->hasNormals, mesh.lit, normalTextureId != 0);
+ meshProgram(ctx, resident->hasNormals, mesh.lit, normalTextureId != 0, skinned);
if (resident->isDrawable() && residentShader != 0) {
- const u32 stride = resident->hasNormals
- ? MESH_INSTANCE_STRIDE_LIT : MESH_INSTANCE_STRIDE;
+ const u32 stride = skinned ? MESH_INSTANCE_STRIDE_SKINNED
+ : resident->hasNormals ? MESH_INSTANCE_STRIDE_LIT
+ : MESH_INSTANCE_STRIDE;
u32 instOffset = buffers.allocVertices(LayoutId::MeshInstance, stride);
auto* dst = buffers.vertexData(LayoutId::MeshInstance) + instOffset;
+ u32 tintRGBA = packColor(mesh.color);
+ if (skinned) {
+ std::memcpy(dst, &tintRGBA, 4);
+ key.skinOffset = draw_list.addSkinMatrices(pose_scratch_.data(), poseSize);
+ key.skinCount = poseSize;
+ } else {
glm::mat4 model = glm::translate(glm::mat4(1.0f), position)
* glm::mat4_cast(rotation)
* glm::scale(glm::mat4(1.0f), scale);
std::memcpy(dst, &model[0][0], 64);
- u32 tintRGBA = packColor(mesh.color);
std::memcpy(dst + 64, &tintRGBA, 4);
if (resident->hasNormals) {
// Written per object rather than derived per vertex: this is
@@ -221,12 +267,13 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
std::memcpy(dst + 68 + row * 12, &nrm[row][0], 12);
}
}
+ }
// A material's default program is built for the BATCH vertex
// source and would draw this at its local origin, so ask for the
// one compiled for THIS source; a failed variant falls back.
u32 materialProgram = 0;
- if (key.materialId != 0 && ctx.materials) {
+ if (key.materialId != 0 && ctx.materials && !skinned) {
materialProgram = ctx.materials->meshProgram(key.materialId, ctx.resources,
resident->hasNormals);
if (materialProgram == 0) {
diff --git a/src/esengine/renderer/plugins/MeshPlugin.hpp b/src/esengine/renderer/plugins/MeshPlugin.hpp
index 11f33cf3a..d1dd514d3 100644
--- a/src/esengine/renderer/plugins/MeshPlugin.hpp
+++ b/src/esengine/renderer/plugins/MeshPlugin.hpp
@@ -28,13 +28,16 @@ private:
/// Resident-geometry programs, indexed by {has normals, lit, normal-mapped}:
/// what the geometry carries and what the draw asked for are separate
/// questions. Compiled on first use — a scene draws one or two of the five.
- std::array<u32, 8> mesh_programs_{};
- std::array<bool, 8> mesh_compiled_{};
+ std::array<u32, 16> mesh_programs_{};
+ std::array<bool, 16> mesh_compiled_{};
/// The shader RESOURCES behind those ids, kept because init() runs again
/// after a device rebuild: with no handle to release, each rebuild left a
/// dead shader in the pool and one more program the host never freed.
- std::array<resource::ShaderHandle, 8> mesh_shaders_{};
- u32 meshProgram(RenderFrameContext& ctx, bool normals, bool lit, bool normalMapped);
+ std::array<resource::ShaderHandle, 16> mesh_shaders_{};
+ /// One entity's bone matrices while they are being built; reused per draw.
+ std::vector<glm::mat4> pose_scratch_;
+ u32 meshProgram(RenderFrameContext& ctx, bool normals, bool lit, bool normalMapped,
+ bool skinned);
bool warned_material_ = false; ///< A material on resident geometry is said once.
};
diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cpp
index a2ea84dbe..9350eb54e 100644
--- a/src/esengine/renderer/rhi/GLDevice.cpp
+++ b/src/esengine/renderer/rhi/GLDevice.cpp
@@ -170,6 +170,12 @@ struct GLPixelFormatInfo {
GLenum type;
};
+/** Whether a data type carries integers a shader reads as integers. */
+bool isIntegerAttribute(GfxDataType type) {
+ return type == GfxDataType::UnsignedByte || type == GfxDataType::UnsignedShort
+ || type == GfxDataType::UnsignedInt || type == GfxDataType::Int;
+}
+
GLPixelFormatInfo toGLPixelFormat(GfxPixelFormat fmt) {
switch (fmt) {
case GfxPixelFormat::RGB8: return { GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE };
@@ -875,12 +881,21 @@ void GLDevice::prepareVertexState() {
const GfxVertexAttribute& attr = rec.desc.attributes[a];
if (attr.bufferSlot != slot) continue;
glEnableVertexAttribArray(attr.location);
- glVertexAttribPointer(
- attr.location, attr.components, toGLDataType(attr.type),
- attr.normalized ? GL_TRUE : GL_FALSE,
- static_cast<GLsizei>(rec.desc.strides[slot]),
- reinterpret_cast<const void*>(
- static_cast<uintptr_t>(pending_vbo_offset_[slot] + attr.offset)));
+ const void* at = reinterpret_cast<const void*>(
+ static_cast<uintptr_t>(pending_vbo_offset_[slot] + attr.offset));
+ // An un-normalized integer attribute reaches the shader AS an
+ // integer, through a different entry point: the float one converts,
+ // and a converted joint index is not an index.
+ if (!attr.normalized && isIntegerAttribute(attr.type)) {
+ glVertexAttribIPointer(
+ attr.location, attr.components, toGLDataType(attr.type),
+ static_cast<GLsizei>(rec.desc.strides[slot]), at);
+ } else {
+ glVertexAttribPointer(
+ attr.location, attr.components, toGLDataType(attr.type),
+ attr.normalized ? GL_TRUE : GL_FALSE,
+ static_cast<GLsizei>(rec.desc.strides[slot]), at);
+ }
glVertexAttribDivisor(attr.location, rec.desc.instanceStep[slot] ? 1 : 0);
}
rec.bakedVbo[slot] = pending_vbo_[slot];
diff --git a/src/esengine/renderer/rhi/GfxEnums.hpp b/src/esengine/renderer/rhi/GfxEnums.hpp
index 6b4d6c707..6ff1649ad 100644
--- a/src/esengine/renderer/rhi/GfxEnums.hpp
+++ b/src/esengine/renderer/rhi/GfxEnums.hpp
@@ -95,6 +95,13 @@ static constexpr u32 MESH_INSTANCE_STRIDE = 68;
/// Carried per object because a non-uniform scale makes the model matrix the
/// wrong transform for a normal, and inverting one per vertex is the alternative.
static constexpr u32 MESH_INSTANCE_STRIDE_LIT = 104;
+/// A SKINNED object's record: the tint, and nothing else. No model matrix — a
+/// skinned mesh's own transform is ignored (glTF says so) because its joints are
+/// already placed in the world — and the pose itself is a uniform block.
+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;
/// 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
@@ -114,6 +121,8 @@ enum class MeshChannel : u8 {
TexCoord0 = 2,
Normal = 3,
Tangent = 4,
+ Joints = 5,
+ Weights = 6,
};
// =============================================================================
diff --git a/src/esengine/renderer/rhi/Shader.cpp b/src/esengine/renderer/rhi/Shader.cpp
index 172b74305..b893390f4 100644
--- a/src/esengine/renderer/rhi/Shader.cpp
+++ b/src/esengine/renderer/rhi/Shader.cpp
@@ -18,6 +18,7 @@
#include "./GfxDevice.hpp"
#include "../frame/FrameConstants.hpp"
#include "../store/MaterialConstants.hpp"
+#include "../store/SkinConstants.hpp"
#include "../store/LightConstants.hpp"
#include "../../core/Log.hpp"
@@ -245,6 +246,12 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSr
device_->uniformBlockBinding(program_, timeBlock, TIME_CONSTANTS_BINDING);
}
+ // Same for a skinned mesh's pose, which DrawList rewrites per draw.
+ u32 skinBlock = device_->getUniformBlockIndex(program_, SKIN_CONSTANTS_BLOCK);
+ if (skinBlock != GFX_INVALID_UNIFORM_BLOCK) {
+ device_->uniformBlockBinding(program_, skinBlock, SKIN_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);
diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
index 942fe008b..98e6da132 100644
--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
@@ -290,6 +290,11 @@ inline constexpr const char* MESH = R"esshader(#pragma shader "Mesh"
// (off a constant normal, which is what a 2D surface has).
#pragma feature LIT
+// Geometry deformed by joints. Its own transform is NOT read: a skinned mesh's
+// node placement is ignored (glTF requires it) because the bones are already
+// world-space, so the per-object record carries only a tint.
+#pragma feature SKINNED
+
// A normal map on top of those normals. Its tangent frame comes from the shared
// perturbNormal (screen-space derivatives), so the geometry needs no tangent
// channel — which is why this rides LIT rather than a vertex attribute.
@@ -307,15 +312,21 @@ layout(location = 2) in vec2 a_texCoord;
#ifdef MESH_NORMALS
layout(location = 3) in vec3 a_normal;
#endif
+#ifdef SKINNED
+layout(location = 5) in uvec4 a_joints;
+layout(location = 6) in vec4 a_weights;
+#endif
// 8.. and not 3..: a channel's semantic IS its location, so adding normals to a
// mesh must not move the per-object record (see MESH_INSTANCE_FIRST_LOCATION).
+#ifndef SKINNED
layout(location = 8) in vec4 a_model0;
layout(location = 9) in vec4 a_model1;
layout(location = 10) in vec4 a_model2;
layout(location = 11) in vec4 a_model3;
+#endif
layout(location = 12) in vec4 a_instTint;
-#ifdef MESH_NORMALS
+#if defined(MESH_NORMALS) && !defined(SKINNED)
// The normal matrix (inverse transpose of the model's 3x3), per object: under a
// non-uniform scale the model matrix skews a normal, and inverting one per
// vertex is the alternative.
@@ -328,6 +339,13 @@ layout(std140) uniform FrameConstants {
mat4 u_projection;
};
+#ifdef SKINNED
+// This draw's pose, rewritten immediately before it (SkinConstants, binding 5).
+layout(std140) uniform SkinConstants {
+ mat4 u_bones[64];
+};
+#endif
+
out vec2 v_texCoord;
out vec4 v_color;
#ifdef LIT
@@ -338,13 +356,25 @@ out highp vec3 v_worldPos;
#endif
void main() {
+#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.
+ mat4 skin = a_weights.x * u_bones[a_joints.x]
+ + 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);
+#else
mat4 model = mat4(a_model0, a_model1, a_model2, a_model3);
vec4 world = model * vec4(a_position, 1.0);
+#endif
gl_Position = u_projection * world;
v_texCoord = a_texCoord;
v_color = a_color * a_instTint;
#ifdef LIT
-#ifdef MESH_NORMALS
+#if defined(MESH_NORMALS) && defined(SKINNED)
+ v_worldNormal = mat3(skin) * a_normal;
+#elif defined(MESH_NORMALS)
v_worldNormal = mat3(a_nrm0, a_nrm1, a_nrm2) * a_normal;
#else
// A surface with no normal channel faces the viewer, exactly as a sprite does.
@@ -390,6 +420,11 @@ void main() {
struct FrameConstants { projection : mat4x4f };
@group(0) @binding(0) var<uniform> frame : FrameConstants;
+#ifdef SKINNED
+struct SkinConstants { bones : array<mat4x4f, 64> };
+@group(0) @binding(5) var<uniform> skin : SkinConstants;
+#endif
+
struct VSIn {
@location(0) a_position : vec3f,
@location(1) a_color : vec4f,
@@ -397,16 +432,23 @@ struct VSIn {
#ifdef MESH_NORMALS
@location(3) a_normal : vec3f,
#endif
+#ifdef SKINNED
+ @location(5) a_joints : vec4u,
+ @location(6) a_weights : vec4f,
+#else
@location(8) a_model0 : vec4f,
@location(9) a_model1 : vec4f,
@location(10) a_model2 : vec4f,
@location(11) a_model3 : vec4f,
+#endif
@location(12) a_instTint : vec4f,
#ifdef MESH_NORMALS
+#ifndef SKINNED
@location(13) a_nrm0 : vec3f,
@location(14) a_nrm1 : vec3f,
@location(15) a_nrm2 : vec3f,
#endif
+#endif
};
struct VSOut {
@builtin(position) pos : vec4f,
@@ -419,8 +461,18 @@ struct VSOut {
};
@vertex fn vs_main(v : VSIn) -> VSOut {
+#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.
+ let pose = v.a_weights.x * skin.bones[v.a_joints.x]
+ + 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);
+#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);
+#endif
var out : VSOut;
out.pos = frame.projection * world;
@@ -428,7 +480,11 @@ struct VSOut {
out.v_color = v.a_color * v.a_instTint;
#ifdef LIT
#ifdef MESH_NORMALS
+#ifdef SKINNED
+ out.v_worldNormal = mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * v.a_normal;
+#else
out.v_worldNormal = mat3x3f(v.a_nrm0, v.a_nrm1, v.a_nrm2) * v.a_normal;
+#endif
#else
// A surface with no normal channel faces the viewer, exactly as a sprite does.
out.v_worldNormal = vec3f(0.0, 0.0, 1.0);
diff --git a/src/esengine/renderer/store/SkinConstants.hpp b/src/esengine/renderer/store/SkinConstants.hpp
new file mode 100644
index 000000000..a549eb3bf
--- /dev/null
+++ b/src/esengine/renderer/store/SkinConstants.hpp
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file SkinConstants.hpp
+ * @brief The pose one skinned draw is deformed by: a bone matrix per joint.
+ *
+ * @details Per DRAW, unlike the frame's lights and the material's parameters, so
+ * it is uploaded and bound immediately before the draw that reads it —
+ * the same shape the engine's other blocks have, at the next binding
+ * point. A uniform block rather than a texture because a bind group's
+ * textures are visible to the fragment stage alone on WebGPU, while its
+ * buffers are already visible to both.
+ *
+ * Each matrix is `jointWorld * inverseBind`: world space, because a
+ * skinned mesh's own transform is ignored (glTF requires it) — the
+ * joints are already placed, so the vertices they move are too.
+ */
+#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 SkinConstants block. */
+inline constexpr u32 SKIN_CONSTANTS_BINDING = 5;
+
+/** @brief GLSL block name; must match the shader's declaration + Shader::compile lookup. */
+inline constexpr const char* SKIN_CONSTANTS_BLOCK = "SkinConstants";
+
+/** @brief std140 mirror of the block. One mat4 per joint, MESH_MAX_BONES of them. */
+struct SkinConstants {
+ glm::mat4 bones[MESH_MAX_BONES];
+};
+
+static_assert(sizeof(SkinConstants) == MESH_MAX_BONES * 64,
+ "SkinConstants must be a tight array of mat4 to match std140");
+
+} // namespace esengine
diff --git a/src/esengine/resource/Mesh.hpp b/src/esengine/resource/Mesh.hpp
index 6eac54b7b..3952c9eb6 100644
--- a/src/esengine/resource/Mesh.hpp
+++ b/src/esengine/resource/Mesh.hpp
@@ -11,6 +11,8 @@
#include "../renderer/rhi/GfxEnums.hpp"
#include "./Handle.hpp"
+#include <vector>
+
namespace esengine {
/**
@@ -40,6 +42,12 @@ public:
glm::vec3 localMin{0.0f, 0.0f, 0.0f};
glm::vec3 localMax{0.0f, 0.0f, 0.0f};
+ /** The bind pose, one per joint the Joints channel indexes. Empty for
+ * geometry nothing skins; its size is what a skinned draw allocates. */
+ std::vector<glm::mat4> inverseBind;
+
+ bool isSkinned() const { return !inverseBind.empty(); }
+
bool isDrawable() const {
return vertexBuffer != BufferHandle::Invalid
&& indexBuffer != BufferHandle::Invalid
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index eb91698ee..af3085ec3 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -477,7 +477,8 @@ void ResourceManager::releaseVertexBuffer(VertexBufferHandle handle) {
MeshHandle ResourceManager::createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,
ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
- const glm::vec3& localMin, const glm::vec3& localMax) {
+ const glm::vec3& localMin, const glm::vec3& localMax,
+ ConstSpan<f32> inverseBind) {
if (!device_ || vertexBytes.empty() || indices.empty() || channels.empty()) return MeshHandle();
// The mesh describes its own vertices; the per-object transform is the
@@ -493,23 +494,30 @@ MeshHandle ResourceManager::createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32>
layout.attributes[i].bufferSlot = 0;
}
bool hasNormals = false;
+ bool skinned = false;
for (const GfxVertexAttribute& c : channels) {
if (c.location == static_cast<u32>(MeshChannel::Normal)) hasNormals = true;
+ if (c.location == static_cast<u32>(MeshChannel::Joints)) skinned = true;
}
+ skinned = skinned && !inverseBind.empty();
layout.strides[0] = vertexStride;
- layout.strides[1] = hasNormals ? MESH_INSTANCE_STRIDE_LIT : MESH_INSTANCE_STRIDE;
+ layout.strides[1] = skinned ? MESH_INSTANCE_STRIDE_SKINNED
+ : hasNormals ? MESH_INSTANCE_STRIDE_LIT : MESH_INSTANCE_STRIDE;
layout.instanceStep[1] = true;
u32 next = static_cast<u32>(channels.size());
- for (u32 row = 0; row < 4; ++row) {
- layout.attributes[next++] = {MESH_INSTANCE_FIRST_LOCATION + row, 4, GfxDataType::Float,
- false, row * 16u, 1};
+ // Only where the shader will read them: a layout may not declare an attribute
+ // its shader does not consume, which WebGPU rejects. A skinned record thus
+ // carries neither model nor normal matrix — its bones are world-space.
+ if (!skinned) {
+ for (u32 row = 0; row < 4; ++row) {
+ layout.attributes[next++] = {MESH_INSTANCE_FIRST_LOCATION + row, 4, GfxDataType::Float,
+ false, row * 16u, 1};
+ }
}
layout.attributes[next++] = {MESH_INSTANCE_FIRST_LOCATION + 4, 4, GfxDataType::UnsignedByte,
- true, 64, 1};
- // Only where the shader will read them: a layout may not declare an attribute
- // its pipeline's shader does not consume, which WebGPU rejects outright.
- if (hasNormals) {
+ true, skinned ? 0u : 64u, 1};
+ if (hasNormals && !skinned) {
for (u32 row = 0; row < 3; ++row) {
layout.attributes[next++] = {MESH_INSTANCE_FIRST_LOCATION + 5 + row, 3,
GfxDataType::Float, false, 68 + row * 12u, 1};
@@ -535,6 +543,11 @@ MeshHandle ResourceManager::createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32>
mesh->hasNormals = hasNormals;
mesh->localMin = localMin;
mesh->localMax = localMax;
+ if (skinned) {
+ const usize joints = inverseBind.size() / 16;
+ mesh->inverseBind.resize(joints);
+ std::memcpy(mesh->inverseBind.data(), inverseBind.data(), joints * sizeof(glm::mat4));
+ }
return meshes_.add(std::move(mesh));
}
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index 6c4c3db01..669adad45 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -460,7 +460,8 @@ public:
*/
MeshHandle createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32> indices,
ConstSpan<GfxVertexAttribute> channels, u32 vertexStride,
- const glm::vec3& localMin, const glm::vec3& localMax);
+ const glm::vec3& localMin, const glm::vec3& localMax,
+ ConstSpan<f32> inverseBind = {});
/** @brief The mesh a handle names, or null. */
Mesh* getMesh(MeshHandle handle);
diff --git a/tools/check-component-fields.mjs b/tools/check-component-fields.mjs
index 570e59a7b..cf21ddd0d 100644
--- a/tools/check-component-fields.mjs
+++ b/tools/check-component-fields.mjs
@@ -40,8 +40,6 @@ const DECLARED_GAPS = {
+ ' own built-in shader and never consult the table',
'SpineAnimation.material': 'see ParticleEmitter.material',
'DragonBonesAnimation.material': 'see ParticleEmitter.material',
- 'MeshSkin.joints': 'the import writes the joint list, and the renderer does not yet'
- + ' build a bone matrix from it (REARCH_3D D1)',
};
const components = JSON.parse(
diff --git a/tools/check-shader-conditionals.mjs b/tools/check-shader-conditionals.mjs
new file mode 100644
index 000000000..ca95172b5
--- /dev/null
+++ b/tools/check-shader-conditionals.mjs
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file check-shader-conditionals.mjs — a WGSL twin uses conditionals the
+ * engine can actually resolve.
+ *
+ * A GLSL stage is preprocessed by the DRIVER, which has a full C preprocessor.
+ * A WGSL twin is expanded by the engine (ShaderParser::preprocessWGSL), which
+ * understands `#ifdef`, `#ifndef`, `#elif defined(X)`, `#else` and `#endif` —
+ * and nothing else. A `#if defined(A) && !defined(B)` there is not an error: the
+ * line is emitted verbatim into the WGSL, which then fails to compile, and what
+ * reaches anyone is an invalid pipeline with no mention of a shader.
+ *
+ * The two halves of a file therefore do NOT have the same powers, which is the
+ * kind of asymmetry nothing else would state.
+ */
+import { readFileSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+const files = execFileSync('git', ['ls-files', '*.esshader'], { cwd: ROOT, encoding: 'utf8' })
+ .split('\n').filter(Boolean);
+
+const problems = [];
+let wgslBlocks = 0;
+for (const file of files) {
+ const text = readFileSync(path.join(ROOT, file), 'utf8');
+ // Every `#pragma <stage> wgsl` block up to its `#pragma end`.
+ const blocks = [...text.matchAll(/^#pragma\s+\w+\s+wgsl\s*$([\s\S]*?)^#pragma\s+end\s*$/gm)];
+ wgslBlocks += blocks.length;
+ for (const block of blocks) {
+ const before = text.slice(0, block.index).split('\n').length;
+ block[1].split('\n').forEach((line, i) => {
+ const lead = line.trim();
+ if (!lead.startsWith('#if')) return;
+ if (/^#if(def|ndef)\b/.test(lead)) return;
+ problems.push(`${file}:${before + i + 1} ${lead}`);
+ });
+ }
+}
+
+if (problems.length) {
+ console.error('check-shader-conditionals: a WGSL block uses a conditional the engine'
+ + " does not resolve — it reaches the compiler verbatim.\n");
+ for (const p of problems) console.error(` ${p}`);
+ console.error('\nUse nested #ifdef / #ifndef, or #elif defined(X).');
+ process.exit(1);
+}
+
+console.log(`check-shader-conditionals: ${wgslBlocks} WGSL block(s) across ${files.length}`
+ + ' shader(s) — every conditional is one the engine expands.');
diff --git a/tools/gates.mjs b/tools/gates.mjs
index 9c426108f..503b9ac8a 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -74,6 +74,7 @@ export const GATES = [
{ id: 'capabilities', run: 'node tools/check-capabilities.mjs' },
{ id: 'inspector-door', run: 'node tools/check-inspector-door.mjs' },
{ id: 'component-fields', run: 'node tools/check-component-fields.mjs' },
+ { id: 'shader-conditionals', run: 'node tools/check-shader-conditionals.mjs' },
{ id: 'import-settings', run: 'node tools/check-import-settings.mjs' },
{ id: 'dirty-source', run: 'node tools/check-dirty-source.mjs' },
{ id: 'path-sandbox', run: 'node tools/check-path-sandbox.mjs' },
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index e4e4fc8be..fd2604e0e 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -44,6 +44,10 @@ export const SCENES = [
// cell here, so the whole grid steps right by one and the left column empties.
// It rides the per-frame origin, not the cached chunk vertices.
{ id: "tilemap-origin", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SET_FIELD: "{\"entity\":1,\"component\":\"TilemapLayer\",\"key\":\"originOffset\",\"value\":[16,0]}", ESTELLA_VERIFY_SCENE: "/scenes/tilemap-flip.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/tilemap-flip.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.60,\"y\":0.36,\"rgb\":[255,0,0]},{\"x\":0.80,\"y\":0.36,\"rgb\":[0,255,0]},{\"x\":0.60,\"y\":0.58,\"rgb\":[0,0,255]},{\"x\":0.40,\"y\":0.36,\"rgb\":[0,0,0],\"tol\":20}]" } },
+ // A two-bone arm. Bone 1 binds at x=60 and the scene puts it 60 higher, so
+ // the half bound to it rises by exactly that and the half bound to bone 0 does
+ // not: the elbow is where the geometry says, not where a whole-mesh move puts it.
+ { id: "mesh-skin", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-skin.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.35,\"y\":0.6,\"rgb\":[0,255,0],\"tol\":30},{\"x\":0.75,\"y\":0.35,\"rgb\":[0,255,0],\"tol\":30},{\"x\":0.75,\"y\":0.60,\"rgb\":[0,0,0],\"tol\":20}]" } },
// A glTF animation, through the shipped importer. The scene puts the quad at
// x=150 and the clip runs -120 to 120 over a second, so 30 fixed steps is its
// midpoint: the model is at the origin and where the SCENE put it is empty.