A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(rig2d): a 2D character can be rigged with no other program, with IK and bone constraints
yhh9b902d2b2f68
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 812be0a19..9f5e7e656 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Added+- **A 2D character can be rigged in the editor, with no other program.** Right-click an image to create an `.esrig`, then cut it into parts, drag out bones, cover the parts with a mesh, bind by distance and paint weights with add, remove and smooth brushes, and push vertices into named deforms, all on one canvas that can try poses without changing the rig. Saving writes an `.esmesh` and an `.esprefab` beside it, so a built game carries no authoring data. Bones are ordinary entities, so clips, the Animator's blends, layers and masks all reach them, and a deform is a `MeshMorph` weight clips can key.+- **2D bones can reach for things and follow each other.** `IK2D` on the last bone of a limb bends it to a target after the animation has played, exactly for two bones and iteratively for more, with a weight clips can key. `BoneConstraint2D` limits a joint's rotation, which a chain through it keeps to, or copies another entity's rotation or position, or looks at it. Both follow a character mirrored by a negative scale. `esengine/rig2d` also makes all of this from code.- **A tile layer can be dug, blown up and rebuilt while the game runs.** `createDestructibleTilemap` in `esengine/tilemap` gives a layer tiles with hardness that wear down over several blows, circular explosions with falloff that walls can shelter from, and placing and filling, with one list of what changed for drops and effects. The neighbouring autotiles re-resolve, `createNavGrid` or `syncNavGrid` keeps a navigation grid in step one cell at a time, and `toJSON` and `load` save only the cells that differ from the map it started as, refusing a damaged save whole. On a streamed world, `publishChunk` lays a player's changes over what the generator made, so a chunk let go and made again comes back as it was left.- **Solid tile ground can have colliders only where it is exposed.** `TilemapRuntime.setCollisionOutline` generates plain boxes for tiles with an open side, so solid ground costs no bodies and a tunnel below a surface leaves the surface's colliders alone. A destructible layer turns it on; `collisionOutline: false` keeps merged ground.@@ -26,6 +28,8 @@ published separately; it ships inside the editor.### Fixed+- **A skinned mesh is not culled for where its entity stands.** A skinned mesh is placed by its joints, and was culled by its entity's box in the bind pose, so a body an animation carried away from its root vanished when that box left the view, in 2D and 3D alike. It is now culled around its joints.+- **A texture stays on a scene that rescans as it is placed.** Two project rescans in a row started two loads of one texture, and the second to finish could release the one the scene was drawing with. The entity then drew white and stayed white, since the load counted as started and nothing asked again. An asset now loads one at a time and loads again afterwards when it was asked for meanwhile.- **A tile's custom properties in an `.estileset` reach the game.** `getTileProperty` answered nothing on a layer painted from an `.estileset`; only Tiled maps carried them. Replacing a tileset blanks the properties of the old one.## [0.100.0] - 2026-11-08diff --git a/desktop b/desktopindex 055304409..1b8d53fa6 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 0553044093da756df8c06b732ed9184b746bf5c3+Subproject commit 1b8d53fa641997ec9b8af6eac93400a3ca4838b8diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjsindex 7a7010e26..bcdf301f1 100644--- a/docs/astro/astro.config.mjs+++ b/docs/astro/astro.config.mjs@@ -241,6 +241,7 @@ export default defineConfig({{ label: 'Overview', translations: { 'zh-CN': '总览' }, slug: 'animation/overview' },{ label: 'Timeline', translations: { 'zh-CN': '时间轴' }, slug: 'animation/timeline' },{ label: 'Spring bones', translations: { 'zh-CN': '弹簧骨骼' }, slug: 'animation/spring-bones' },+ { label: '2D Rigs', translations: { 'zh-CN': '2D 骨骼' }, slug: 'animation/rig-2d' },{ label: 'Spine Animation', translations: { 'zh-CN': 'Spine 动画' }, slug: 'animation/spine' },{ label: 'DragonBones Animation', translations: { 'zh-CN': 'DragonBones 动画' }, slug: 'animation/dragonbones' },],diff --git a/docs/astro/src/content/docs/animation/rig-2d.mdx b/docs/astro/src/content/docs/animation/rig-2d.mdxnew file mode 100644index 000000000..f4892505e--- /dev/null+++ b/docs/astro/src/content/docs/animation/rig-2d.mdx@@ -0,0 +1,95 @@+---+title: 2D Rigs+description: Make a skeletal 2D character inside the editor — parts, bones, painted weights and mesh deforms — then animate it with clips, blend it with the Animator, and bend it with IK and constraints.+---++import { Aside } from '@astrojs/starlight/components';++A 2D rig bends one image the way a skeleton bends a body. You make it in the editor from any PNG, with no separate animation program and no third-party format.+[Spine](/docs/animation/spine/) and [DragonBones](/docs/animation/dragonbones/) keep working beside it; use whichever a character was made in.++## How it fits together++- **`.esrig`** is what you edit: the parts cut from an image, the bones under them, and what each vertex follows.+- Saving writes **`.esmesh`** and **`.esprefab`** beside it. Scenes use those, so a built game carries no authoring data.+- **Bones are entities.** Each is an ordinary entity with a Transform, so clips, the Animator, masks and code reach them like anything else.++## Make a character++Right-click an image in the Content Browser and choose **Create 2D Rig**. Then work through the modes along the top, which are in the order a character is made:++| Mode | What you do |+|---|---|+| **Parts** | **Split by Transparency** cuts a sheet of limbs into parts. Drag them into a character. The list on the right sets which draws on top. |+| **Bones** | With **New**, drag a bone out. Start on another bone's end and it carries on from it. With **Select**, drag an end to aim a bone and the rest to move it. |+| **Mesh** | Every part starts covered by a grid. Smaller cells bend more smoothly and cost more. Drag a vertex to adjust it. |+| **Weights** | **By Distance** binds what is nearest, then paint what that got wrong: pick a bone on the right and drag. `Shift` inverts, `Ctrl` smooths, `[` and `]` change the radius. **Whole Part to Selected Bone** is for a piece that does not bend. |+| **Deforms** | **New Shape**, then drag to push vertices: a breath, a smile, a bulge. |++**Try Pose** turns bones to see how the weights hold up. It changes nothing in the rig, and **Bind Pose** puts it back. **Place in Scene** saves and instantiates the prefab. Saving again updates every instance, keeping what a scene added to one.++<Aside type="note">+ This version has no adding or deleting single vertices, and a character draws from one image. Generating a part's mesh again clears that part's weights and deforms, and asks first.+</Aside>++## Animate it++Select the character and key its bones in the [Sequencer](/docs/animation/timeline/) like any other entity. A bone is named by its path under the root, such as `hips/spine/arm`. A deform is a weight on the `MeshMorph` component, which keys the same way.++Blending is the [Animator](/docs/animation/overview/)'s job, as for any other character: 1D and 2D blends, layers, masks and transitions all work on bones.++## IK++Add **`IK2D`** to the last bone of a limb and point `target` at an entity. The end of that bone reaches for it, after the animation has played, so a hand can hold what it holds whichever clip is running.++| Field | Meaning |+|---|---|+| `target` | The entity to reach for. |+| `chainLength` | How many bones bend, counting this one. Two solve exactly and keep their bend; more take an iterative solve. |+| `bend` | With two bones, the way the middle joint bends: `1` counter-clockwise or `-1`. |+| `weight` | How far from the animated pose towards the solve. Clips can key it. |+| `matchTargetRotation` | Also turn this bone to the target's rotation, for a foot flat on a slope. |++## Constraints++Add **`BoneConstraint2D`** to a bone. Constraints run after IK, from the trunk out:++| `kind` | What it does |+|---|---|+| **Limit Rotation** | Keeps the local rotation between `min` and `max`. An IK chain through the bone keeps to them too. |+| **Copy Rotation** | Takes `source`'s world rotation, plus `offset`. |+| **Copy Position** | Stands on `source`'s world position. |+| **Look At** | Points the bone's +x at `source`, plus `offset`. |++IK and constraints run in play mode. Both follow a character mirrored by a negative scale on its root.++## In code++Rigs are plain data, so a game or a tool can make one:++```typescript+import {+ autoWeightPart, bakeRig, coverRigPart, createRig, rigImageFromRGBA, spawnRig, IK2D,+} from 'esengine/rig2d';++const image = rigImageFromRGBA(width, height, rgba);+const rig = createRig('hero.png', width, height);+rig.bones.push(+ { name: 'upper', parent: -1, x: 0, y: 0, rotation: 0, length: 50 },+ { name: 'lower', parent: 0, x: 50, y: 0, rotation: 0, length: 50 },+);+const rect = { x: 0, y: 0, w: width, h: height };+const part = { name: 'arm', rect, x: 0, y: height / 2, ...coverRigPart(image, rect), weights: [] };+rig.parts.push(part);+autoWeightPart(rig, part);++const mesh = assets.createMesh(bakeRig(rig));+const { bones } = spawnRig(world, rig, { mesh, texture });+world.insert(bones[1], IK2D, { target, chainLength: 2, bend: 1, weight: 1, matchTargetRotation: false, enabled: true });+```++## Limits++- A rig is one mesh, drawn in one draw call, up to 256 bones. A vertex follows at most 4.+- Parts of one rig draw in the order you set. Against the rest of the scene, a rig sorts by `MeshRenderer.layer` and then by z, as a mesh does.+- A selected rig's outline shows its bind pose, not its current pose.diff --git a/docs/astro/src/content/docs/zh-cn/animation/rig-2d.mdx b/docs/astro/src/content/docs/zh-cn/animation/rig-2d.mdxnew file mode 100644index 000000000..cedf95668--- /dev/null+++ b/docs/astro/src/content/docs/zh-cn/animation/rig-2d.mdx@@ -0,0 +1,95 @@+---+title: 2D 骨骼+description: 在编辑器里直接做骨骼 2D 角色——部件、骨骼、权重绘制和网格变形——再用片段做动画、用 Animator 混合、用 IK 和约束控制姿势。+---++import { Aside } from '@astrojs/starlight/components';++2D 骨骼让一张图像身体一样弯折。任何 PNG 都可以在编辑器里直接做,不需要另外的动画软件,也不依赖第三方格式。+[Spine](/docs/zh-cn/animation/spine/) 和 [DragonBones](/docs/zh-cn/animation/dragonbones/) 照常可用;角色是用哪个做的,就继续用哪个。++## 整体结构++- **`.esrig`** 是你编辑的文件:从图上切出的部件、部件下面的骨骼、每个顶点跟随哪些骨骼。+- 保存时在旁边写出 **`.esmesh`** 和 **`.esprefab`**。场景只用这两个,所以打包后的游戏不带编辑数据。+- **骨骼就是实体。** 每根骨骼都是带 Transform 的普通实体,片段、Animator、遮罩和代码都能像控制其他实体一样控制它。++## 做一个角色++在内容浏览器里右键一张图,选 **创建 2D 骨骼**。然后沿顶部的模式依次操作,顺序就是做角色的顺序:++| 模式 | 做什么 |+|---|---|+| **部件** | **按透明区域切分** 把一张肢体拼图切成部件,再拖动摆成角色。右侧列表决定谁画在上面。 |+| **骨骼** | 选 **新建** 后拖出一根骨骼;从另一根骨骼的末端开始,就接在它后面。选 **选择** 时,拖末端调方向,拖其余位置移动。 |+| **网格** | 每个部件一开始就盖着一层网格。格子越小弯折越顺,代价也越大。拖动顶点可以微调。 |+| **权重** | **按距离** 先绑定最近的骨骼,再刷它弄错的地方:在右侧选一根骨骼后拖动。`Shift` 反向,`Ctrl` 平滑,`[` 和 `]` 调半径。**整个部件跟选中骨骼** 用于不弯的部件。 |+| **变形** | **新建形状**,然后拖动把顶点推过去:呼吸、微笑、鼓起。 |++**试摆** 可以转动骨骼,看权重是否合适。它不改骨骼文件,回到 **绑定姿势** 就复原。**放入场景** 会保存并实例化 prefab。再次保存时所有实例都会更新,实例上后加的内容会保留。++<Aside type="note">+ 这一版不支持单独增删顶点,一个角色只能用一张图。重新生成部件网格会清掉这个部件的权重和变形,操作前会提醒。+</Aside>++## 做动画++选中角色,在[时间线](/docs/zh-cn/animation/timeline/)里像其他实体一样给骨骼打关键帧。骨骼按它在根下面的路径命名,比如 `hips/spine/arm`。变形是 `MeshMorph` 组件上的权重,打关键帧的方式相同。++混合由 [Animator](/docs/zh-cn/animation/overview/) 负责,和其他角色一样:1D、2D 混合、分层、遮罩和过渡都对骨骼有效。++## IK++给肢体的最后一根骨骼加 **`IK2D`**,把 `target` 指向一个实体。这根骨骼的末端会在动画播放之后去够它,所以不管播哪个片段,手都能握住要握的东西。++| 字段 | 含义 |+|---|---|+| `target` | 要够到的实体。 |+| `chainLength` | 弯折几根骨骼,包括这一根。两根时精确求解并保持弯折方向;更多时迭代求解。 |+| `bend` | 两根骨骼时中间关节的弯折方向:`1` 逆时针,`-1` 顺时针。 |+| `weight` | 从动画姿势向解算结果靠拢的比例。可以打关键帧。 |+| `matchTargetRotation` | 让这根骨骼同时转到目标的旋转,比如脚贴合斜坡。 |++## 约束++给骨骼加 **`BoneConstraint2D`**。约束在 IK 之后运行,从躯干向外:++| `kind` | 作用 |+|---|---|+| **Limit Rotation** | 把局部旋转限制在 `min` 和 `max` 之间。穿过这根骨骼的 IK 链也会遵守。 |+| **Copy Rotation** | 取 `source` 的世界旋转,再加 `offset`。 |+| **Copy Position** | 站到 `source` 的世界位置上。 |+| **Look At** | 让骨骼的 +x 指向 `source`,再加 `offset`。 |++IK 和约束在播放模式下运行。根节点用负缩放镜像的角色同样适用。++## 用代码++骨骼是普通数据,游戏或工具都可以自己生成:++```typescript+import {+ autoWeightPart, bakeRig, coverRigPart, createRig, rigImageFromRGBA, spawnRig, IK2D,+} from 'esengine/rig2d';++const image = rigImageFromRGBA(width, height, rgba);+const rig = createRig('hero.png', width, height);+rig.bones.push(+ { name: 'upper', parent: -1, x: 0, y: 0, rotation: 0, length: 50 },+ { name: 'lower', parent: 0, x: 50, y: 0, rotation: 0, length: 50 },+);+const rect = { x: 0, y: 0, w: width, h: height };+const part = { name: 'arm', rect, x: 0, y: height / 2, ...coverRigPart(image, rect), weights: [] };+rig.parts.push(part);+autoWeightPart(rig, part);++const mesh = assets.createMesh(bakeRig(rig));+const { bones } = spawnRig(world, rig, { mesh, texture });+world.insert(bones[1], IK2D, { target, chainLength: 2, bend: 1, weight: 1, matchTargetRotation: false, enabled: true });+```++## 限制++- 一个骨骼角色是一个网格、一次绘制,最多 256 根骨骼。一个顶点最多跟随 4 根。+- 同一角色的部件按你设定的顺序绘制。和场景其他内容之间,按 `MeshRenderer.layer` 再按 z 排序,和普通网格一样。+- 选中角色时的外框显示的是绑定姿势,不是当前姿势。diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 3ff7150ac..62cbf9099 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 176,- "experimental": 2875,+ "experimental": 2918,"deprecated": 3},- "total": 3166,+ "total": 3209,"subsystems": [{"id": "mobile-controls",@@ -393,6 +393,19 @@"SplineCurve"]},+ {+ "id": "rig2d",+ "title": "2D rigs",+ "titleZh": "2D 骨骼",+ "tier": "experimental",+ "why": "baking, weights and the solvers are checked against the real engine, but no shipped example carries a rig yet, and its editor is new.",+ "whyZh": "烘焙、权重和解算都对真实引擎做了检查,但还没有示例真正用上骨骼角色,编辑器也是新的。",+ "entry": [+ "createRig",+ "bakeRig",+ "IK2D"+ ]+ },{"id": "imported-scene","title": "Imported scene runtime",diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex eef8f919e..9bc56b03c 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -178,6 +178,9 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {RagdollJoint: { category: 'physics', summary: 'What the author says of one bone of a ragdoll: no body of its own, or limits (and a one-way bend) of its own.', doc: 'gameplay/physics-3d', anchor: 'ragdoll', anchorZh: '布娃娃' },FirstPersonController: { category: 'physics', summary: 'Looks, walks, jumps and crouches in a CharacterController3D from the keyboard, the pointer and the touch screen, through a camera on a child.', doc: 'gameplay/physics-3d', anchor: 'first-person', anchorZh: '第一人称' },FirstPersonViewModel: { category: 'physics', summary: 'On the player\'s camera: draws what is held with a second camera over the world\'s, with its own field of view and near plane, so it does not go through walls.', doc: 'gameplay/physics-3d', anchor: 'a-view-model', anchorZh: '视图模型' },+ Bone2D: { category: 'animation', summary: 'A bone of a 2D rig: an entity whose Transform is its joint, reaching a length along its own +x.', doc: 'animation/rig-2d' },+ IK2D: { category: 'animation', summary: 'Bends the last bones of a limb after the animation has played, so the end of this bone reaches a target.', doc: 'animation/rig-2d' },+ BoneConstraint2D: { category: 'animation', summary: 'Limits a bone's rotation, or makes it copy another entity's rotation or position, or look at it.', doc: 'animation/rig-2d' },PathFollower: { category: 'graphics', summary: 'Moves its entity along the Spline of another at a steady speed, once, round or back and forth, turning to face along it if asked.', doc: null },TerrainBand2D: { category: 'graphics', summary: 'A 2D ground drawn along the Spline of the same entity: a filled body, a lip along the surface with an optional image, and an optional chain collider.', doc: null },SwingTwistJoint3D: { category: 'physics', summary: 'A ball joint with independent twist limits, an elliptical swing cone and optional angular velocity motors.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 06af68079..8d5ce5b98 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -417,6 +417,74 @@"lift"]},+ {+ "name": "Bone2D",+ "source": "ts",+ "fields": [+ {+ "key": "length",+ "type": "number",+ "default": "0",+ "doc": "How far the bone reaches along its +x. An IK chain ending here reaches for the target with this end.",+ "range": "≥ 0"+ }+ ],+ "animatable": [+ "length"+ ]+ },+ {+ "name": "BoneConstraint2D",+ "source": "ts",+ "fields": [+ {+ "key": "kind",+ "type": "enum",+ "default": "Limit Rotation",+ "values": [+ "Limit Rotation",+ "Copy Rotation",+ "Copy Position",+ "Look At"+ ]+ },+ {+ "key": "source",+ "type": "Entity",+ "default": "none",+ "doc": "The entity copied or looked at. Limit Rotation reads none."+ },+ {+ "key": "min",+ "type": "number",+ "default": "-45"+ },+ {+ "key": "max",+ "type": "number",+ "default": "45"+ },+ {+ "key": "offset",+ "type": "number",+ "default": "0"+ },+ {+ "key": "weight",+ "type": "number",+ "default": "1",+ "range": "0–1, step 0.01"+ },+ {+ "key": "enabled",+ "type": "boolean",+ "default": "true"+ }+ ],+ "animatable": [+ "weight"+ ]+ },{"name": "BoxCollider2D","source": "cpp",@@ -2813,6 +2881,53 @@"cooldown"]},+ {+ "name": "IK2D",+ "source": "ts",+ "fields": [+ {+ "key": "target",+ "type": "Entity",+ "default": "none",+ "doc": "The entity the end of this bone reaches for."+ },+ {+ "key": "chainLength",+ "type": "number",+ "default": "2",+ "doc": "How many bones bend, counting this one. Two bones solve exactly and keep their bend; more take an iterative solve.",+ "range": "1–32, step 1"+ },+ {+ "key": "bend",+ "type": "number",+ "default": "1",+ "doc": "Two bones: the way the middle joint bends, 1 counter-clockwise or -1.",+ "range": "-1–1, step 2"+ },+ {+ "key": "weight",+ "type": "number",+ "default": "1",+ "doc": "How far from the animated pose towards the solve.",+ "range": "0–1, step 0.01"+ },+ {+ "key": "matchTargetRotation",+ "type": "boolean",+ "default": "false",+ "doc": "Also turn this bone to the target's rotation."+ },+ {+ "key": "enabled",+ "type": "boolean",+ "default": "true"+ }+ ],+ "animatable": [+ "weight"+ ]+ },{"name": "Impostor","source": "cpp",diff --git a/pipeline/src/bundle/engineSubpaths.ts b/pipeline/src/bundle/engineSubpaths.tsindex 7004d9264..96073b4a9 100644--- a/pipeline/src/bundle/engineSubpaths.ts+++ b/pipeline/src/bundle/engineSubpaths.ts@@ -21,6 +21,7 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {'esengine/worldgen': 'worldgen/index.js','esengine/water': 'water/index.js','esengine/spline': 'spline/index.js',+ 'esengine/rig2d': 'rig2d/index.js','esengine/imported-scene': 'imported-scene/index.js','esengine/character-shaders': 'character-shaders/index.js','esengine/logic': 'logic/index.js',diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.tsindex 1904f664c..fe2ed0a26 100644--- a/pipeline/src/project/targetSupport.ts+++ b/pipeline/src/project/targetSupport.ts@@ -27,7 +27,7 @@ import { NATIVE_PLATFORMS, type ExportPlatform } from './platforms';/** An engine subsystem a build target may lack. */export type Subsystem =- | 'text' | 'tilemap' | 'terrain' | 'foliage' | 'worldgen' | 'water' | 'spline' | 'importedScene' | 'characterShaders' | 'timeline' | 'fxBasic' | 'fxAtmosphere' | 'fxLighting' | 'particles' | 'postprocess' | 'physics' | 'physics3d'+ | 'text' | 'tilemap' | 'terrain' | 'foliage' | 'worldgen' | 'water' | 'spline' | 'rig2d' | 'importedScene' | 'characterShaders' | 'timeline' | 'fxBasic' | 'fxAtmosphere' | 'fxLighting' | 'particles' | 'postprocess' | 'physics' | 'physics3d'| 'spine' | 'dragonbones' | 'video' | 'ai' | 'logic' | 'replication' | 'gameplay';/**@@ -49,6 +49,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>worldgen: ['WorldGen', 'WorldZone'],water: ['WaterBody', 'WaterZone', 'Floating'],spline: ['Spline', 'PathFollower', 'TerrainBand2D'],+ rig2d: ['Bone2D', 'IK2D', 'BoneConstraint2D'],importedScene: ['NodeVisibility', 'ParticleModelUnits'],// Hair, Skin and Eye are shaders, not components: a character's materials are what name them (see SHADER_SUBSYSTEM).characterShaders: [],@@ -116,6 +117,7 @@ export const SUBSYSTEM_LABEL: Readonly<Record<Subsystem, string>> = {worldgen: 'Generated worlds (biomes, zones, placement)',water: 'Water',spline: 'Splines',+ rig2d: '2D rig constraints',importedScene: 'Imported scene (node visibility, particle units)',characterShaders: 'Character shaders (hair, skin, eye)',particles: 'Particles',@@ -151,6 +153,7 @@ export const SUBSYSTEM_INSTALL: Readonly<Record<Subsystem, string>> = {worldgen: 'esengine/worldgen',water: 'esengine/water',spline: 'esengine/spline',+ rig2d: 'esengine/rig2d',importedScene: 'esengine/imported-scene',characterShaders: 'esengine/character-shaders',physics: 'esengine/physics',diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 0c8857b75..abaf42c1c 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 2060 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 2067 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1834,11 +1834,42 @@ Kinematic = 1Static = 0```+## Bone2D — const @experimental+```+ComponentDef<Bone2DData>+```++## Bone2DData — interface @experimental+```+length: number+```+## BoneClass — type @experimental```'spine' | 'neck' | 'head' | 'shoulder' | 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot' | 'toe' | 'other'```+## BoneConstraint2D — const @experimental+```+ComponentDef<BoneConstraint2DData>+```++## BoneConstraint2DData — interface @experimental+```+enabled: boolean+kind: number+max: number+min: number+offset: number+source: number+weight: number+```++## BoneConstraintKind — const @experimental+```+{ readonly LimitRotation: 0; readonly CopyRotation: 1; readonly CopyPosition: 2; readonly LookAt: 3; }+```+## BoxCollider2D — const @experimental```BuiltinComponentDef<BoxCollider2DData>@@ -5100,6 +5131,21 @@ static new (options: HttpBackendOptions): HttpBackendstatic prototype: HttpBackend```+## IK2D — const @experimental+```+ComponentDef<IK2DData>+```++## IK2DData — interface @experimental+```+bend: number+chainLength: number+enabled: boolean+matchTargetRotation: boolean+target: number+weight: number+```+## IMPOSTOR_BAKE_LAYER — const @experimental```31diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 482adbdb7..a1739fe03 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 169 beta · 2079 experimental · 3 deprecated+Symbols: 115 public · 169 beta · 2086 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1834,11 +1834,42 @@ Kinematic = 1Static = 0```+## Bone2D — const @experimental+```+ComponentDef<Bone2DData>+```++## Bone2DData — interface @experimental+```+length: number+```+## BoneClass — type @experimental```'spine' | 'neck' | 'head' | 'shoulder' | 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot' | 'toe' | 'other'```+## BoneConstraint2D — const @experimental+```+ComponentDef<BoneConstraint2DData>+```++## BoneConstraint2DData — interface @experimental+```+enabled: boolean+kind: number+max: number+min: number+offset: number+source: number+weight: number+```++## BoneConstraintKind — const @experimental+```+{ readonly LimitRotation: 0; readonly CopyRotation: 1; readonly CopyPosition: 2; readonly LookAt: 3; }+```+## BoxCollider2D — const @experimental```BuiltinComponentDef<BoxCollider2DData>@@ -5108,6 +5139,21 @@ static new (options: HttpBackendOptions): HttpBackendstatic prototype: HttpBackend```+## IK2D — const @experimental+```+ComponentDef<IK2DData>+```++## IK2DData — interface @experimental+```+bend: number+chainLength: number+enabled: boolean+matchTargetRotation: boolean+target: number+weight: number+```+## IMPOSTOR_BAKE_LAYER — const @experimental```31diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex c4f408c56..b40b81c89 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 166 beta · 2059 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2066 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1829,11 +1829,42 @@ Kinematic = 1Static = 0```+## Bone2D — const @experimental+```+ComponentDef<Bone2DData>+```++## Bone2DData — interface @experimental+```+length: number+```+## BoneClass — type @experimental```'spine' | 'neck' | 'head' | 'shoulder' | 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot' | 'toe' | 'other'```+## BoneConstraint2D — const @experimental+```+ComponentDef<BoneConstraint2DData>+```++## BoneConstraint2DData — interface @experimental+```+enabled: boolean+kind: number+max: number+min: number+offset: number+source: number+weight: number+```++## BoneConstraintKind — const @experimental+```+{ readonly LimitRotation: 0; readonly CopyRotation: 1; readonly CopyPosition: 2; readonly LookAt: 3; }+```+## BoxCollider2D — const @experimental```BuiltinComponentDef<BoxCollider2DData>@@ -5095,6 +5126,21 @@ static new (options: HttpBackendOptions): HttpBackendstatic prototype: HttpBackend```+## IK2D — const @experimental+```+ComponentDef<IK2DData>+```++## IK2DData — interface @experimental+```+bend: number+chainLength: number+enabled: boolean+matchTargetRotation: boolean+target: number+weight: number+```+## IMPOSTOR_BAKE_LAYER — const @experimental```31diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 5921c509e..8ada46239 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 2081 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 2088 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1829,11 +1829,42 @@ Kinematic = 1Static = 0```+## Bone2D — const @experimental+```+ComponentDef<Bone2DData>+```++## Bone2DData — interface @experimental+```+length: number+```+## BoneClass — type @experimental```'spine' | 'neck' | 'head' | 'shoulder' | 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot' | 'toe' | 'other'```+## BoneConstraint2D — const @experimental+```+ComponentDef<BoneConstraint2DData>+```++## BoneConstraint2DData — interface @experimental+```+enabled: boolean+kind: number+max: number+min: number+offset: number+source: number+weight: number+```++## BoneConstraintKind — const @experimental+```+{ readonly LimitRotation: 0; readonly CopyRotation: 1; readonly CopyPosition: 2; readonly LookAt: 3; }+```+## BoxCollider2D — const @experimental```BuiltinComponentDef<BoxCollider2DData>@@ -5095,6 +5126,21 @@ static new (options: HttpBackendOptions): HttpBackendstatic prototype: HttpBackend```+## IK2D — const @experimental+```+ComponentDef<IK2DData>+```++## IK2DData — interface @experimental+```+bend: number+chainLength: number+enabled: boolean+matchTargetRotation: boolean+target: number+weight: number+```+## IMPOSTOR_BAKE_LAYER — const @experimental```31diff --git a/sdk/etc/rig2d.api.md b/sdk/etc/rig2d.api.mdnew file mode 100644index 000000000..e472a41a1--- /dev/null+++ b/sdk/etc/rig2d.api.md@@ -0,0 +1,271 @@+# API surface — esengine/rig2d++<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->+Symbols: 0 public · 0 beta · 43 experimental · 0 deprecated++## Bone2D — const @experimental+```+ComponentDef<Bone2DData>+```++## Bone2DData — interface @experimental+```+length: number+```++## BoneConstraint2D — const @experimental+```+ComponentDef<BoneConstraint2DData>+```++## BoneConstraint2DData — interface @experimental+```+enabled: boolean+kind: number+max: number+min: number+offset: number+source: number+weight: number+```++## BoneConstraintKind — const @experimental+```+{ readonly LimitRotation: 0; readonly CopyRotation: 1; readonly CopyPosition: 2; readonly LookAt: 3; }+```++## ChainBone — interface @experimental+```+max: number | undefined+min: number | undefined+rotation: number+x: number+y: number+```++## ChainSolveOptions — interface @experimental+```+bend: number | undefined+iterations: number | undefined+tipLength: number+tolerance: number | undefined+```++## IK2D — const @experimental+```+ComponentDef<IK2DData>+```++## IK2DData — interface @experimental+```+bend: number+chainLength: number+enabled: boolean+matchTargetRotation: boolean+target: number+weight: number+```++## RIG_MAX_INFLUENCES — const @experimental+```+4+```++## RIG_SOURCE_EXT — const @experimental+```+".esrig"+```++## RIG_SOURCE_VERSION — const @experimental+```+1+```++## Rig2DPlugin — class @experimental+```+activeWhen: (ComponentDef<BoneConstraint2DData> | ComponentDef<IK2DData>)[]+build: (app: App) => void+name: string+static new (): Rig2DPlugin+static prototype: Rig2DPlugin+```++## RigBone — interface @experimental+```+length: number+name: string+parent: number+rotation: number+x: number+y: number+```++## RigBoneWorld — interface @experimental+```+rotation: number+x: number+y: number+```++## RigDeform — interface @experimental+```+name: string+offsets: Record<string, number[]>+```++## RigImage — interface @experimental+```+alpha: (x: number, y: number) => number+height: number+width: number+```++## RigPart — interface @experimental+```+name: string+rect: { x: number; y: number; w: number; h: number; }+triangles: number[]+vertices: number[]+weights: number[][]+x: number+y: number+```++## RigSource — interface @experimental+```+bones: RigBone[]+deforms: RigDeform[]+parts: RigPart[]+texture: string+textureHeight: number+textureWidth: number+unitsPerPixel: number+version: number+```++## RigWeightDab — interface @experimental+```+bone: number+mode: "add" | "remove" | "smooth"+radius: number+strength: number+x: number+y: number+```++## SpawnedRig — interface @experimental+```+bones: number[]+root: number+```++## autoWeightPart — function @experimental+```+(rig: RigSource, part: RigPart, opts?: { bones?: readonly number[]; falloff?: number; }): void+```++## bakeRig — function @experimental+```+(rig: RigSource): MeshData+```++## bindPartToBone — function @experimental+```+(part: RigPart, bone: number): void+```++## chainTip — function @experimental+```+(chain: readonly ChainBone[], tipLength: number): { x: number; y: number; }+```++## checkRig — function @experimental+```+(rig: RigSource): string[]+```++## clampAngle — function @experimental+```+(angle: number, min?: number, max?: number): number+```++## coverRigPart — function @experimental+```+(image: RigImage, rect: RigPart["rect"], opts?: { cell?: number; threshold?: number; }): { vertices: number[]; triangles: number[]; }+```++## createRig — function @experimental+```+(texture: string, textureWidth: number, textureHeight: number, unitsPerPixel?: number): RigSource+```++## findRigParts — function @experimental+```+(image: RigImage, opts?: { threshold?: number; minArea?: number; }): { x: number; y: number; w: number; h: number; }[]+```++## paintPartWeights — function @experimental+```+(rig: RigSource, part: RigPart, dab: RigWeightDab): number+```++## parseRig — function @experimental+```+(text: string): RigSource+```++## partWeightsOf — function @experimental+```+(part: RigPart, bone: number): Float32Array+```++## pushRigDeform — function @experimental+```+(rig: RigSource, deformIndex: number, x: number, y: number, radius: number, dx: number, dy: number): number+```++## removeRigBone — function @experimental+```+(rig: RigSource, index: number): void+```++## rigBoneWorlds — function @experimental+```+(bones: readonly RigBone[], rotations?: ArrayLike<number>): RigBoneWorld[]+```++## rigImageFromRGBA — function @experimental+```+(width: number, height: number, rgba: ArrayLike<number>): RigImage+```++## rigPrefab — function @experimental+```+(rig: RigSource, name: string, mesh: string, texture: string): { version: string; name: string; rootEntityId: string; entities: Record<string, unknown>[]; }+```++## rigVertex — function @experimental+```+(rig: RigSource, part: RigPart, vertex: number): { x: number; y: number; }+```++## serializeRig — function @experimental+```+(rig: RigSource): string+```++## skinRigPart — function @experimental+```+(rig: RigSource, partIndex: number, posed: readonly RigBoneWorld[], deformWeights?: ArrayLike<number>): Float32Array+```++## solveChain2D — function @experimental+```+(chain: ChainBone[], targetX: number, targetY: number, opts: ChainSolveOptions): void+```++## spawnRig — function @experimental+```+(world: World, rig: RigSource, opts: { mesh: number; texture: number; layer?: number; x?: number; y?: number; z?: number; }): SpawnedRig+```+diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 0c63b2fd6..f055aab67 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 164 beta · 2072 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 2079 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1829,11 +1829,42 @@ Kinematic = 1Static = 0```+## Bone2D — const @experimental+```+ComponentDef<Bone2DData>+```++## Bone2DData — interface @experimental+```+length: number+```+## BoneClass — type @experimental```'spine' | 'neck' | 'head' | 'shoulder' | 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot' | 'toe' | 'other'```+## BoneConstraint2D — const @experimental+```+ComponentDef<BoneConstraint2DData>+```++## BoneConstraint2DData — interface @experimental+```+enabled: boolean+kind: number+max: number+min: number+offset: number+source: number+weight: number+```++## BoneConstraintKind — const @experimental+```+{ readonly LimitRotation: 0; readonly CopyRotation: 1; readonly CopyPosition: 2; readonly LookAt: 3; }+```+## BoxCollider2D — const @experimental```BuiltinComponentDef<BoxCollider2DData>@@ -5095,6 +5126,21 @@ static new (options: HttpBackendOptions): HttpBackendstatic prototype: HttpBackend```+## IK2D — const @experimental+```+ComponentDef<IK2DData>+```++## IK2DData — interface @experimental+```+bend: number+chainLength: number+enabled: boolean+matchTargetRotation: boolean+target: number+weight: number+```+## IMPOSTOR_BAKE_LAYER — const @experimental```31diff --git a/sdk/package.json b/sdk/package.jsonindex 9e7ef9fc5..7b86fe758 100644--- a/sdk/package.json+++ b/sdk/package.json@@ -26,6 +26,7 @@"./dist/worldgen/index.js","./dist/water/index.js","./dist/spline/index.js",+ "./dist/rig2d/index.js","./dist/imported-scene/index.js","./dist/character-shaders/index.js","./dist/logic/index.js",@@ -120,6 +121,10 @@"import": "./dist/spline/index.js","types": "./dist/spline/index.d.ts"},+ "./rig2d": {+ "import": "./dist/rig2d/index.js",+ "types": "./dist/rig2d/index.d.ts"+ },"./imported-scene": {"import": "./dist/imported-scene/index.js","types": "./dist/imported-scene/index.d.ts"diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.jsindex 0d6296e1b..ba4fcfd6d 100644--- a/sdk/rolldown.config.js+++ b/sdk/rolldown.config.js@@ -112,6 +112,7 @@ export default defineConfig(['worldgen/index': 'src/worldgen/index.ts','water/index': 'src/water/index.ts','spline/index': 'src/spline/index.ts',+ 'rig2d/index': 'src/rig2d/index.ts','imported-scene/index': 'src/imported-scene/index.ts','character-shaders/index': 'src/character/index.ts','logic/index': 'src/logic/index.ts',diff --git a/sdk/rollup.config.js b/sdk/rollup.config.jsindex b2555ad84..b08117eb9 100644--- a/sdk/rollup.config.js+++ b/sdk/rollup.config.js@@ -34,6 +34,7 @@ export default ['worldgen/index': 'src/worldgen/index.ts','water/index': 'src/water/index.ts','spline/index': 'src/spline/index.ts',+ 'rig2d/index': 'src/rig2d/index.ts','imported-scene/index': 'src/imported-scene/index.ts','character-shaders/index': 'src/character/index.ts','logic/index': 'src/logic/index.ts',diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex e37bd0639..32a5a272d 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -836,6 +836,7 @@ export { WorldPlan, type Placement, type Group, type Rejection } from './worldgeexport { Zones, type ZoneDef, type ZoneShape } from './worldgen/zones';export { PlacementDiffs, type PlacementChange, type PlacementDiffsData } from './worldgen/diffs';// Splines and water are optional modules too (`esengine/spline`, `esengine/water`).+export { Bone2D, IK2D, BoneConstraint2D, BoneConstraintKind, type Bone2DData, type IK2DData, type BoneConstraint2DData } from './rig2d/rig2dPlugin';export { Bakes, BakesRes, bakesOf, finish, type WorkJob, type BakeProgress } from './runtime/bakes';export { CollisionGeometry, CollisionGeometryRes, collisionGeometryOf, type CollisionPiece } from './runtime/collisionGeometry';export { Spline, SplinePlugin, splinePlugin, PathFollower, PathMode, PathOrient, pathPlace, type SplineData, type PathFollowerData } from './spline/splinePlugin';diff --git a/sdk/src/platform/nativeModuleRegistry.ts b/sdk/src/platform/nativeModuleRegistry.tsindex 031163ece..2bea57788 100644--- a/sdk/src/platform/nativeModuleRegistry.ts+++ b/sdk/src/platform/nativeModuleRegistry.ts@@ -33,6 +33,7 @@ import * as FoliageModule from '../foliage';import * as WorldGenModule from '../worldgen';import * as WaterModule from '../water';import * as SplineModule from '../spline';+import * as Rig2DModule from '../rig2d';import * as ImportedSceneModule from '../imported-scene';import * as CharacterShadersModule from '../character';import * as ScriptGraphModule from '../logic';@@ -64,6 +65,7 @@ export const NATIVE_MODULE_NAMESPACES: Readonly<Record<string, unknown>> = {'esengine/worldgen': WorldGenModule,'esengine/water': WaterModule,'esengine/spline': SplineModule,+ 'esengine/rig2d': Rig2DModule,'esengine/imported-scene': ImportedSceneModule,'esengine/character-shaders': CharacterShadersModule,'esengine/logic': ScriptGraphModule,diff --git a/sdk/src/rig2d/index.ts b/sdk/src/rig2d/index.tsnew file mode 100644index 000000000..9cf7e9743--- /dev/null+++ b/sdk/src/rig2d/index.ts@@ -0,0 +1,22 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+export {+ RIG_SOURCE_VERSION, RIG_SOURCE_EXT, RIG_MAX_INFLUENCES, createRig, checkRig, parseRig, serializeRig, rigBoneWorlds, removeRigBone,+ type RigSource, type RigBone, type RigPart, type RigDeform, type RigBoneWorld,+} from './rigSource';+export {+ rigImageFromRGBA, findRigParts, coverRigPart, rigVertex, autoWeightPart, bindPartToBone, paintPartWeights, partWeightsOf, pushRigDeform,+ type RigImage, type RigWeightDab,+} from './rigMesh';+export { bakeRig, skinRigPart } from './rigBake';+export { solveChain2D, chainTip, clampAngle, type ChainBone, type ChainSolveOptions } from './solve2d';+export {+ Bone2D, IK2D, BoneConstraint2D, BoneConstraintKind, Rig2DPlugin,+ type Bone2DData, type IK2DData, type BoneConstraint2DData,+} from './rig2dPlugin';+export { spawnRig, rigPrefab, type SpawnedRig } from './spawnRig';++// Importing this subpath INSTALLS the constraints — see tilemap/index.ts.+import { registerRig2DSupport } from './rig2dSupport';++registerRig2DSupport();diff --git a/sdk/src/rig2d/rig2dPlugin.ts b/sdk/src/rig2d/rig2dPlugin.tsnew file mode 100644index 000000000..fd2b00c90--- /dev/null+++ b/sdk/src/rig2d/rig2dPlugin.ts@@ -0,0 +1,264 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file rig2dPlugin.ts+ * @brief Bones as entities, and what bends them after the animation has spoken: IK chains and bone constraints.+ *+ * @details Runs after the animator, the timeline and physics, on the pose they stated, so a foot lands where the ground is whichever+ * clip is playing. Worlds are walked from the local fields rather than read from `Transform.worldPosition`: those are+ * composed for the frame's draw and are last frame's here, and each chain has to see what the one before it just did.+ *+ * A solve starts from the ANIMATED pose. Something a bone holds that this system did not write is the animation's and+ * becomes the base; what it did write is not, or `weight` would creep towards 1 on a bone no clip touches.+ */+import type { App, Plugin } from '../app/app';+import { defineComponent, Parent, Transform } from '../ecs/component';+import { playModeOnly } from '../ecs/env';+import { Schedule, defineSystem } from '../ecs/system';+import type { Entity } from '../types';+import type { World } from '../ecs/world';+import { clampAngle, solveChain2D, type ChainBone } from './solve2d';++const DEG = Math.PI / 180;++/** A bone: an entity whose Transform is its joint, reaching `length` along its own +x. @experimental */+export interface Bone2DData { length: number }+/** @experimental */+export const Bone2D = defineComponent<Bone2DData>('Bone2D', { length: 0 }, {+ fields: { length: { min: 0, tooltip: 'How far the bone reaches along its +x. An IK chain ending here reaches for the target with this end.' } },+});++/** @experimental */+export interface IK2DData {+ /** What the end of this bone reaches for. */+ target: Entity;+ /** Bones bent, this one and those above it. */+ chainLength: number;+ /** Two bones: which way the middle joint bends, 1 counter-clockwise or -1. */+ bend: number;+ /** 0 leaves the animation alone, 1 reaches the target. */+ weight: number;+ /** Also turn this bone to the target's rotation: a foot flat on a slope, a hand holding what it holds. */+ matchTargetRotation: boolean;+ enabled: boolean;+}+/** @experimental */+export const IK2D = defineComponent<IK2DData>('IK2D', {+ target: 0 as Entity, chainLength: 2, bend: 1, weight: 1, matchTargetRotation: false, enabled: true,+}, {+ entityFields: ['target'],+ animatableFields: ['weight'],+ fields: {+ target: { tooltip: 'The entity the end of this bone reaches for.' },+ chainLength: { min: 1, max: 32, step: 1, tooltip: 'How many bones bend, counting this one. Two bones solve exactly and keep their bend; more take an iterative solve.' },+ bend: { min: -1, max: 1, step: 2, tooltip: 'Two bones: the way the middle joint bends, 1 counter-clockwise or -1.' },+ weight: { min: 0, max: 1, step: 0.01, tooltip: 'How far from the animated pose towards the solve.' },+ matchTargetRotation: { tooltip: "Also turn this bone to the target's rotation." },+ },+});++/** What a {@link BoneConstraint2D} does. @experimental */+export const BoneConstraintKind = {+ /** Keep the bone's local rotation between `min` and `max`. An IK chain through this bone keeps to them too. */+ LimitRotation: 0,+ /** Take `source`'s world rotation, plus `offset`. */+ CopyRotation: 1,+ /** Stand on `source`'s world position. */+ CopyPosition: 2,+ /** Point +x at `source`, plus `offset`. */+ LookAt: 3,+} as const;++/** @experimental */+export interface BoneConstraint2DData {+ kind: number;+ source: Entity;+ /** LimitRotation: degrees of local rotation. */+ min: number;+ max: number;+ /** CopyRotation and LookAt: degrees added on top. */+ offset: number;+ weight: number;+ enabled: boolean;+}+/** @experimental */+export const BoneConstraint2D = defineComponent<BoneConstraint2DData>('BoneConstraint2D', {+ kind: BoneConstraintKind.LimitRotation, source: 0 as Entity, min: -45, max: 45, offset: 0, weight: 1, enabled: true,+}, {+ entityFields: ['source'],+ animatableFields: ['weight'],+ fields: {+ kind: { enum: [+ { label: 'Limit Rotation', value: BoneConstraintKind.LimitRotation },+ { label: 'Copy Rotation', value: BoneConstraintKind.CopyRotation },+ { label: 'Copy Position', value: BoneConstraintKind.CopyPosition },+ { label: 'Look At', value: BoneConstraintKind.LookAt },+ ] },+ source: { tooltip: 'The entity copied or looked at. Limit Rotation reads none.' },+ min: { unit: '°', shownWhen: { field: 'kind', values: [BoneConstraintKind.LimitRotation] } },+ max: { unit: '°', shownWhen: { field: 'kind', values: [BoneConstraintKind.LimitRotation] } },+ offset: { unit: '°', shownWhen: { field: 'kind', values: [BoneConstraintKind.CopyRotation, BoneConstraintKind.LookAt] } },+ weight: { min: 0, max: 1, step: 0.01 },+ },+});++/** A placement in the world: `point = (x, y) + R(angle) * S * local`. */+interface Place { x: number; y: number; angle: number; sx: number; sy: number }+const NOWHERE: Place = { x: 0, y: 0, angle: 0, sx: 1, sy: 1 };++/** What a bone held that the animation stated, and what was written over it. */+interface Base { angle: number; wroteAngle: number | null; x: number; y: number; wroteX: number | null; wroteY: number | null; frame: number }++const zAngle = (q: { w: number; z: number }): number => 2 * Math.atan2(q.z, q.w);+const close = (a: number | null, b: number): boolean => a !== null && Math.abs(a - b) < 1e-5;+const wrap = (a: number): number => Math.atan2(Math.sin(a), Math.cos(a));++/** One frame of solving. @internal */+export class Rig2DSolver {+ private readonly bases_ = new Map<Entity, Base>();+ private readonly places_ = new Map<Entity, Place>();+ private frame_ = 0;++ constructor(private readonly world: World) {}++ forget(entity: Entity): void { this.bases_.delete(entity); }++ private parentOf_(entity: Entity): Entity | null {+ const parent = this.world.tryGet(entity, Parent) as { entity: Entity } | null;+ return parent && this.world.valid(parent.entity) && this.world.has(parent.entity, Transform) ? parent.entity : null;+ }++ private placeOf_(entity: Entity | null): Place {+ if (entity === null) return NOWHERE;+ const known = this.places_.get(entity);+ if (known) return known;+ const up = this.placeOf_(this.parentOf_(entity));+ const t = this.world.get(entity, Transform);+ const c = Math.cos(up.angle), s = Math.sin(up.angle), lx = t.position.x * up.sx, ly = t.position.y * up.sy;+ const mirrored = up.sx * up.sy < 0;+ const place: Place = {+ x: up.x + c * lx - s * ly, y: up.y + s * lx + c * ly,+ angle: up.angle + (mirrored ? -1 : 1) * zAngle(t.rotation), sx: up.sx * t.scale.x, sy: up.sy * t.scale.y,+ };+ this.places_.set(entity, place);+ return place;+ }++ private baseOf_(entity: Entity): Base {+ const t = this.world.get(entity, Transform), angle = zAngle(t.rotation);+ let base = this.bases_.get(entity);+ if (!base) {+ base = { angle, wroteAngle: null, x: t.position.x, y: t.position.y, wroteX: null, wroteY: null, frame: this.frame_ };+ this.bases_.set(entity, base);+ return base;+ }+ if (base.frame !== this.frame_) {+ base.frame = this.frame_;+ if (!close(base.wroteAngle, angle)) { base.angle = angle; base.wroteAngle = null; }+ if (!close(base.wroteX, t.position.x) || !close(base.wroteY, t.position.y)) { base.x = t.position.x; base.y = t.position.y; base.wroteX = null; base.wroteY = null; }+ }+ return base;+ }++ private writeAngle_(entity: Entity, base: Base, angle: number): void {+ base.wroteAngle = angle;+ const half = angle / 2;+ this.world.update(entity, Transform, (t) => { t.rotation = { w: Math.cos(half), x: 0, y: 0, z: Math.sin(half) }; });+ this.places_.clear();+ }++ private toLocal_(parent: Place, x: number, y: number): { x: number; y: number } {+ const c = Math.cos(parent.angle), s = Math.sin(parent.angle), dx = x - parent.x, dy = y - parent.y;+ return { x: (c * dx + s * dy) / (parent.sx || 1), y: (-s * dx + c * dy) / (parent.sy || 1) };+ }++ private limitOf_(entity: Entity): { min?: number; max?: number } {+ const limit = this.world.tryGet(entity, BoneConstraint2D);+ if (!limit || !limit.enabled || limit.kind !== BoneConstraintKind.LimitRotation) return {};+ return { min: limit.min * DEG, max: limit.max * DEG };+ }++ private solveIK_(tip: Entity): void {+ const ik = this.world.get(tip, IK2D);+ if (!ik.enabled || !(ik.weight > 0) || !this.world.valid(ik.target) || !this.world.has(ik.target, Transform)) return;+ const bones: Entity[] = [tip];+ for (let at = this.parentOf_(tip); at !== null && bones.length < ik.chainLength; at = this.parentOf_(at)) bones.unshift(at);+ const above = this.placeOf_(this.parentOf_(bones[0]!));+ const target = this.placeOf_(ik.target);+ const local = this.toLocal_(above, target.x, target.y);+ const chain: ChainBone[] = bones.map((bone) => {+ const t = this.world.get(bone, Transform);+ const place: ChainBone = { x: t.position.x, y: t.position.y, rotation: this.baseOf_(bone).angle };+ return { ...place, ...this.limitOf_(bone) };+ });+ const tipBone = this.world.tryGet(tip, Bone2D);+ solveChain2D(chain, local.x, local.y, { tipLength: tipBone ? tipBone.length : 0, bend: ik.bend === 0 ? undefined : ik.bend });+ bones.forEach((bone, i) => {+ const base = this.baseOf_(bone);+ this.writeAngle_(bone, base, base.angle + wrap(chain[i]!.rotation - base.angle) * Math.min(1, ik.weight));+ });+ if (ik.matchTargetRotation) {+ const above2 = this.placeOf_(this.parentOf_(tip)), base = this.baseOf_(tip);+ const sign = above2.sx * above2.sy < 0 ? -1 : 1;+ const held = this.world.get(tip, Transform);+ const current = zAngle(held.rotation);+ this.writeAngle_(tip, base, current + wrap(sign * (target.angle - above2.angle) - current) * Math.min(1, ik.weight));+ }+ }++ private applyConstraint_(bone: Entity): void {+ const c = this.world.get(bone, BoneConstraint2D);+ if (!c.enabled || !(c.weight > 0)) return;+ const base = this.baseOf_(bone), weight = Math.min(1, c.weight);+ const held = zAngle(this.world.get(bone, Transform).rotation);+ if (c.kind === BoneConstraintKind.LimitRotation) {+ const limited = clampAngle(held, c.min * DEG, c.max * DEG);+ if (limited !== held) this.writeAngle_(bone, base, held + (limited - held) * weight);+ return;+ }+ if (!this.world.valid(c.source) || !this.world.has(c.source, Transform)) return;+ const source = this.placeOf_(c.source), up = this.placeOf_(this.parentOf_(bone));+ const sign = up.sx * up.sy < 0 ? -1 : 1;+ if (c.kind === BoneConstraintKind.CopyPosition) {+ const local = this.toLocal_(up, source.x, source.y);+ const x = base.x + (local.x - base.x) * weight, y = base.y + (local.y - base.y) * weight;+ base.wroteX = x; base.wroteY = y;+ this.world.update(bone, Transform, (t) => { t.position.x = x; t.position.y = y; });+ this.places_.clear();+ return;+ }+ const own = this.placeOf_(bone);+ const world = c.kind === BoneConstraintKind.CopyRotation ? source.angle : Math.atan2(source.y - own.y, source.x - own.x);+ const wanted = sign * (world + c.offset * DEG - up.angle);+ this.writeAngle_(bone, base, held + wrap(wanted - held) * weight);+ }++ private depthOf_(entity: Entity): number {+ let depth = 0;+ for (let at = this.parentOf_(entity); at !== null; at = this.parentOf_(at)) depth++;+ return depth;+ }++ /** Chains first, from the trunk out, so a limb reaches from where its body now is; constraints have the last word, the same way. */+ step(): void {+ this.frame_++;+ this.places_.clear();+ const byDepth = (list: readonly Entity[]) => list.map(e => [this.depthOf_(e), e] as const).sort((a, b) => a[0] - b[0] || a[1] - b[1]).map(p => p[1]);+ for (const tip of byDepth(this.world.getEntitiesWithComponents([IK2D, Transform]))) this.solveIK_(tip);+ for (const bone of byDepth(this.world.getEntitiesWithComponents([BoneConstraint2D, Transform]))) this.applyConstraint_(bone);+ }+}++/** Runs {@link IK2D} and {@link BoneConstraint2D} on a running game. @experimental */+export class Rig2DPlugin implements Plugin {+ name = 'rig2d';+ readonly activeWhen = [IK2D, BoneConstraint2D];++ build(app: App): void {+ const solver = new Rig2DSolver(app.world);+ app.world.onDespawn((entity: Entity) => solver.forget(entity));+ app.addSystemToSchedule(Schedule.PostUpdate, defineSystem([], () => solver.step(), { name: 'Rig2DSystem' }), {+ runAfter: ['PhysicsInterpolateSystem'], runIf: playModeOnly,+ });+ }+}diff --git a/sdk/src/rig2d/rig2dSupport.ts b/sdk/src/rig2d/rig2dSupport.tsnew file mode 100644index 000000000..831640eb5--- /dev/null+++ b/sdk/src/rig2d/rig2dSupport.ts@@ -0,0 +1,13 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file rig2dSupport.ts — what a build that ships 2D rig constraints tells the core.+ *+ * A call, not a file's side effect — see tilemap/tilemapSupport.ts.+ */+import { addEntryPlugin } from '../runtime/entryPlugins';+import { Rig2DPlugin } from './rig2dPlugin';++export function registerRig2DSupport(): void {+ addEntryPlugin('rig2d', () => new Rig2DPlugin());+}diff --git a/sdk/src/rig2d/rigBake.ts b/sdk/src/rig2d/rigBake.tsnew file mode 100644index 000000000..9da83ecc1--- /dev/null+++ b/sdk/src/rig2d/rigBake.ts@@ -0,0 +1,132 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file rigBake.ts+ * @brief What a scene draws of a rig: its `.esmesh`, and the skin that same geometry takes in a preview.+ *+ * @details One mesh, the parts laid down in draw order: a blended mesh draws in index order, so that order IS how a limb goes behind+ * the body, and the whole character is one draw. Joint i of the mesh is bone i of the rig, so what binds it is the order of the bones.+ */+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../asset/meshFormat';+import { rigVertex } from './rigMesh';+import { checkRig, rigBoneWorlds, type RigBoneWorld, type RigSource } from './rigSource';++/** Turns a rig into mesh data, refusing one {@link checkRig} refuses or that has no bones to follow. @experimental */+export function bakeRig(rig: RigSource): MeshData {+ const problems = checkRig(rig);+ if (rig.bones.length === 0) problems.push('it has no bones');+ for (const part of rig.parts) {+ if (part.weights.some(w => w.length === 0)) problems.push(`part "${part.name}" has vertices that follow no bone`);+ }+ if (problems.length > 0) throw new Error(`this rig cannot be baked: ${problems.join('; ')}`);++ const { channels, vertexStride } = packChannels([+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.Joints, components: 4, type: MeshChannelType.UInt16 },+ { semantic: MeshChannel.Weights, components: 4, type: MeshChannelType.Float32 },+ ]);+ const offsetOf = (semantic: number): number => channels.find(c => c.semantic === semantic)!.offset;+ const positionAt = offsetOf(MeshChannel.Position), uvAt = offsetOf(MeshChannel.TexCoord0);+ const jointsAt = offsetOf(MeshChannel.Joints), weightsAt = offsetOf(MeshChannel.Weights);++ const vertexCount = rig.parts.reduce((total, p) => total + p.vertices.length / 2, 0);+ const bytes = new Uint8Array(vertexCount * vertexStride), view = new DataView(bytes.buffer);+ const indices: number[] = [], partBase = new Map<string, number>();+ const min: [number, number, number] = [Infinity, Infinity, 0], max: [number, number, number] = [-Infinity, -Infinity, 0];+ let base = 0;+ for (const part of rig.parts) {+ partBase.set(part.name, base);+ for (let v = 0; v < part.vertices.length / 2; v++) {+ const at = (base + v) * vertexStride, p = rigVertex(rig, part, v), w = part.weights[v]!;+ view.setFloat32(at + positionAt, p.x, true);+ view.setFloat32(at + positionAt + 4, p.y, true);+ view.setFloat32(at + uvAt, (part.rect.x + part.vertices[v * 2]!) / rig.textureWidth, true);+ // A texture's v runs up the image: row 0 of the file is v = 1.+ view.setFloat32(at + uvAt + 4, 1 - (part.rect.y + part.vertices[v * 2 + 1]!) / rig.textureHeight, true);+ let sum = 0;+ for (let i = 1; i < w.length; i += 2) sum += w[i]!;+ for (let i = 0; i < w.length; i += 2) {+ view.setUint16(at + jointsAt + i, w[i]!, true);+ view.setFloat32(at + weightsAt + i * 2, sum > 0 ? w[i + 1]! / sum : 0, true);+ }+ min[0] = Math.min(min[0], p.x); min[1] = Math.min(min[1], p.y);+ max[0] = Math.max(max[0], p.x); max[1] = Math.max(max[1], p.y);+ }+ for (const t of part.triangles) indices.push(base + t);+ base += part.vertices.length / 2;+ }++ const inverseBindMatrices = new Float32Array(rig.bones.length * 16);+ rigBoneWorlds(rig.bones).forEach((w, i) => {+ const c = Math.cos(w.rotation), s = Math.sin(w.rotation);+ inverseBindMatrices.set([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, -(c * w.x + s * w.y), s * w.x - c * w.y, 0, 1], i * 16);+ });++ const mesh: MeshData = {+ channels, vertexStride, vertexCount, vertices: bytes, indices: new Uint32Array(indices),+ aabbMin: vertexCount > 0 ? min : [0, 0, 0], aabbMax: vertexCount > 0 ? max : [0, 0, 0], inverseBindMatrices,+ };+ if (rig.deforms.length > 0) {+ const deltas = new Float32Array(rig.deforms.length * vertexCount * 3);+ rig.deforms.forEach((deform, target) => {+ for (const [name, offsets] of Object.entries(deform.offsets)) {+ const start = partBase.get(name)!;+ for (let i = 0; i < offsets.length; i += 3) {+ const at = (target * vertexCount + start + offsets[i]!) * 3;+ deltas[at] = offsets[i + 1]!;+ deltas[at + 1] = offsets[i + 2]!;+ }+ }+ });+ mesh.morph = { names: rig.deforms.map(d => d.name), hasNormals: false, deltas };+ // A shape can reach past the rest pose, and the box is what the mesh is culled by. All of them at once is the most it can be.+ let reach = 0;+ rig.deforms.forEach((_, target) => {+ let most = 0;+ for (let v = 0; v < vertexCount; v++) {+ const at = (target * vertexCount + v) * 3;+ most = Math.max(most, Math.abs(deltas[at]!), Math.abs(deltas[at + 1]!));+ }+ reach += most;+ });+ mesh.aabbMin = [mesh.aabbMin[0] - reach, mesh.aabbMin[1] - reach, 0];+ mesh.aabbMax = [mesh.aabbMax[0] + reach, mesh.aabbMax[1] + reach, 0];+ }+ return mesh;+}++/**+ * Where every vertex of one part lands, flat `[x, y, ...]` in rig space, by the same sum the shader does: deform first, then skin.+ * What an authoring view draws, so what it shows is what the game will.+ * @experimental+ */+export function skinRigPart(rig: RigSource, partIndex: number, posed: readonly RigBoneWorld[], deformWeights?: ArrayLike<number>): Float32Array {+ const part = rig.parts[partIndex]!, bind = rigBoneWorlds(rig.bones), count = part.vertices.length / 2;+ const offset = new Float32Array(count * 2);+ rig.deforms.forEach((deform, d) => {+ const weight = deformWeights?.[d] ?? 0, offsets = deform.offsets[part.name];+ if (!weight || !offsets) return;+ for (let i = 0; i < offsets.length; i += 3) {+ offset[offsets[i]! * 2]! += offsets[i + 1]! * weight;+ offset[offsets[i]! * 2 + 1]! += offsets[i + 2]! * weight;+ }+ });+ const out = new Float32Array(count * 2);+ for (let v = 0; v < count; v++) {+ const at = rigVertex(rig, part, v), w = part.weights[v]!;+ const px = at.x + offset[v * 2]!, py = at.y + offset[v * 2 + 1]!;+ if (w.length === 0) { out[v * 2] = px; out[v * 2 + 1] = py; continue; }+ let x = 0, y = 0, sum = 0;+ for (let i = 0; i < w.length; i += 2) {+ const from = bind[w[i]!]!, to = posed[w[i]!]!, weight = w[i + 1]!;+ const dx = px - from.x, dy = py - from.y, turn = to.rotation - from.rotation, c = Math.cos(turn), s = Math.sin(turn);+ x += (to.x + c * dx - s * dy) * weight;+ y += (to.y + s * dx + c * dy) * weight;+ sum += weight;+ }+ out[v * 2] = sum > 0 ? x / sum : px;+ out[v * 2 + 1] = sum > 0 ? y / sum : py;+ }+ return out;+}diff --git a/sdk/src/rig2d/rigMesh.ts b/sdk/src/rig2d/rigMesh.tsnew file mode 100644index 000000000..d58d87eef--- /dev/null+++ b/sdk/src/rig2d/rigMesh.ts@@ -0,0 +1,224 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file rigMesh.ts+ * @brief From an image to a mesh that bends: cutting it into parts, covering a part, deciding what each vertex follows.+ *+ * @details A part is covered by a grid of cells, keeping those with something drawn in them. An outline hugging the picture saves+ * triangles but bends badly: long thin triangles fold where a limb turns, and the even cells are what make a bend smooth.+ * The empty corners of a kept cell are transparent, so the grid's stairs are never seen.+ */+import { RIG_MAX_INFLUENCES, rigBoneWorlds, type RigPart, type RigSource } from './rigSource';++/** Image coverage: `alpha(x, y)` in 0..255 for a pixel from the top left. @experimental */+export interface RigImage {+ width: number;+ height: number;+ alpha(x: number, y: number): number;+}++/** A rig image over RGBA bytes, row by row from the top. @experimental */+export function rigImageFromRGBA(width: number, height: number, rgba: ArrayLike<number>): RigImage {+ return { width, height, alpha: (x, y) => rgba[(y * width + x) * 4 + 3] ?? 0 };+}++/**+ * The separate pictures in an image, each what is joined by drawn pixels, largest first. What a sheet of a character's limbs is+ * cut into. Specks under `minArea` pixels are left out.+ * @experimental+ */+export function findRigParts(image: RigImage, opts: { threshold?: number; minArea?: number } = {}): { x: number; y: number; w: number; h: number }[] {+ const threshold = opts.threshold ?? 8, minArea = opts.minArea ?? 16, { width, height } = image;+ const seen = new Uint8Array(width * height), found: { rect: { x: number; y: number; w: number; h: number }; area: number }[] = [];+ const stack: number[] = [];+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {+ const start = y * width + x;+ if (seen[start] || image.alpha(x, y) < threshold) continue;+ seen[start] = 1;+ stack.push(start);+ let minX = x, maxX = x, minY = y, maxY = y, area = 0;+ while (stack.length > 0) {+ const at = stack.pop()!, px = at % width, py = (at - px) / width;+ area++;+ if (px < minX) minX = px; if (px > maxX) maxX = px;+ if (py < minY) minY = py; if (py > maxY) maxY = py;+ for (const [nx, ny] of [[px - 1, py], [px + 1, py], [px, py - 1], [px, py + 1]] as const) {+ if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;+ const next = ny * width + nx;+ if (seen[next] || image.alpha(nx, ny) < threshold) continue;+ seen[next] = 1;+ stack.push(next);+ }+ }+ if (area >= minArea) found.push({ rect: { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 }, area });+ }+ return found.sort((a, b) => b.area - a.area).map(f => f.rect);+}++/** Covers `rect` with square cells of `cell` pixels, wherever something is drawn. Vertices come back in pixels from the rect's corner. @experimental */+export function coverRigPart(image: RigImage, rect: RigPart['rect'], opts: { cell?: number; threshold?: number } = {}): { vertices: number[]; triangles: number[] } {+ const cell = Math.max(2, Math.round(opts.cell ?? 16)), threshold = opts.threshold ?? 8;+ const cols = Math.max(1, Math.ceil(rect.w / cell)), rows = Math.max(1, Math.ceil(rect.h / cell));+ const index = new Map<number, number>(), vertices: number[] = [], triangles: number[] = [];+ const corner = (cx: number, cy: number): number => {+ const key = cy * (cols + 1) + cx;+ let at = index.get(key);+ if (at === undefined) {+ at = vertices.length / 2;+ index.set(key, at);+ vertices.push(Math.min(cx * cell, rect.w), Math.min(cy * cell, rect.h));+ }+ return at;+ };+ const drawn = (cx: number, cy: number): boolean => {+ const x1 = Math.min(rect.x + (cx + 1) * cell, rect.x + rect.w), y1 = Math.min(rect.y + (cy + 1) * cell, rect.y + rect.h);+ for (let y = rect.y + cy * cell; y < y1; y++) for (let x = rect.x + cx * cell; x < x1; x++) {+ if (x >= 0 && y >= 0 && x < image.width && y < image.height && image.alpha(x, y) >= threshold) return true;+ }+ return false;+ };+ for (let cy = 0; cy < rows; cy++) for (let cx = 0; cx < cols; cx++) {+ if (!drawn(cx, cy)) continue;+ const a = corner(cx, cy), b = corner(cx + 1, cy), c = corner(cx + 1, cy + 1), d = corner(cx, cy + 1);+ // The diagonal alternates, or a bend across the grid leans all one way. Wound counter-clockwise as seen with y up.+ if ((cx + cy) % 2 === 0) triangles.push(a, d, b, b, d, c);+ else triangles.push(a, d, c, a, c, b);+ }+ return { vertices, triangles };+}++/** Where a part's vertex sits in rig space. @experimental */+export function rigVertex(rig: RigSource, part: RigPart, vertex: number): { x: number; y: number } {+ return { x: part.x + part.vertices[vertex * 2]! * rig.unitsPerPixel, y: part.y - part.vertices[vertex * 2 + 1]! * rig.unitsPerPixel };+}++function distanceToSegment(px: number, py: number, ax: number, ay: number, bx: number, by: number): number {+ const dx = bx - ax, dy = by - ay, lengthSq = dx * dx + dy * dy;+ const t = lengthSq === 0 ? 0 : Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / lengthSq));+ return Math.hypot(px - (ax + t * dx), py - (ay + t * dy));+}++function normalized(pairs: [number, number][]): number[] {+ const kept = pairs.filter(p => p[1] > 0).sort((a, b) => b[1] - a[1]).slice(0, RIG_MAX_INFLUENCES);+ const sum = kept.reduce((total, p) => total + p[1], 0);+ return sum > 0 ? kept.flatMap(([bone, weight]) => [bone, weight / sum]) : [];+}++/**+ * Binds a part's vertices by how near each is to each bone. A good start and not the end: nearness cannot tell an arm from the+ * torso it hangs beside, which is what `bones` (only these may be followed) and painting are for. `falloff` is how sharply a bone's reach ends.+ * @experimental+ */+export function autoWeightPart(rig: RigSource, part: RigPart, opts: { bones?: readonly number[]; falloff?: number } = {}): void {+ const worlds = rigBoneWorlds(rig.bones), falloff = opts.falloff ?? 4;+ const candidates = opts.bones ?? rig.bones.map((_, i) => i);+ const ends = candidates.map((i) => {+ const w = worlds[i]!, length = rig.bones[i]!.length;+ return { bone: i, ax: w.x, ay: w.y, bx: w.x + Math.cos(w.rotation) * length, by: w.y + Math.sin(w.rotation) * length };+ });+ part.weights = [];+ for (let v = 0; v < part.vertices.length / 2; v++) {+ const at = rigVertex(rig, part, v);+ part.weights.push(normalized(ends.map(e => [+ e.bone, Math.pow(1 / (distanceToSegment(at.x, at.y, e.ax, e.ay, e.bx, e.by) + 1), falloff),+ ])));+ }+}++/** Every vertex of a part follows one bone, for a piece that does not bend: a helmet, a sword. @experimental */+export function bindPartToBone(part: RigPart, bone: number): void {+ part.weights = Array.from({ length: part.vertices.length / 2 }, () => [bone, 1]);+}++/** One dab of a weight brush. `add` and `remove` move `bone`'s share, `smooth` evens every bone with the vertices joined to each. @experimental */+export interface RigWeightDab {+ x: number;+ y: number;+ /** World units. */+ radius: number;+ bone: number;+ /** How far the centre of the brush goes, 0..1. */+ strength: number;+ mode: 'add' | 'remove' | 'smooth';+}++/** Applies a dab to a part, returning how many vertices changed. The weights still sum to 1 after it, which is why the others give way. @experimental */+export function paintPartWeights(rig: RigSource, part: RigPart, dab: RigWeightDab): number {+ const count = part.vertices.length / 2;+ let neighbours: Set<number>[] | null = null;+ if (dab.mode === 'smooth') {+ neighbours = Array.from({ length: count }, () => new Set<number>());+ for (let t = 0; t < part.triangles.length; t += 3) {+ const a = part.triangles[t]!, b = part.triangles[t + 1]!, c = part.triangles[t + 2]!;+ neighbours[a]!.add(b).add(c); neighbours[b]!.add(a).add(c); neighbours[c]!.add(a).add(b);+ }+ }+ const before = neighbours ? part.weights.map(w => w.slice()) : part.weights;+ let changed = 0;+ for (let v = 0; v < count; v++) {+ const at = rigVertex(rig, part, v), d = Math.hypot(at.x - dab.x, at.y - dab.y);+ if (d >= dab.radius) continue;+ const reach = (1 - d / dab.radius) ** 2 * dab.strength;+ const shares = new Map<number, number>();+ const w = before[v]!;+ for (let i = 0; i < w.length; i += 2) shares.set(w[i]!, w[i + 1]!);+ if (dab.mode === 'smooth') {+ const around = new Map<number, number>();+ const list = [...neighbours![v]!];+ for (const n of list) {+ const other = before[n]!;+ for (let i = 0; i < other.length; i += 2) around.set(other[i]!, (around.get(other[i]!) ?? 0) + other[i + 1]! / Math.max(list.length, 1));+ }+ for (const bone of new Set([...shares.keys(), ...around.keys()])) {+ const own = shares.get(bone) ?? 0;+ shares.set(bone, own + ((around.get(bone) ?? 0) - own) * reach);+ }+ } else {+ const own = shares.get(dab.bone) ?? 0;+ const next = dab.mode === 'add' ? own + (1 - own) * reach : own * (1 - reach);+ if (next === own) continue;+ const rest = 1 - own, left = 1 - next;+ for (const [bone, share] of shares) if (bone !== dab.bone) shares.set(bone, rest > 0 ? share * (left / rest) : 0);+ shares.set(dab.bone, next);+ }+ const result = normalized([...shares]);+ // A vertex stripped of everything would collapse onto the origin, so the last of it stays where it was.+ if (result.length === 0) continue;+ part.weights[v] = result;+ changed++;+ }+ return changed;+}++/** Pushes the vertices of every part around (x, y), by (dx, dy) at the centre and nothing at `radius`, into one deform. Returns how many moved. @experimental */+export function pushRigDeform(rig: RigSource, deformIndex: number, x: number, y: number, radius: number, dx: number, dy: number): number {+ const deform = rig.deforms[deformIndex];+ if (!deform) return 0;+ let moved = 0;+ for (const part of rig.parts) {+ const held = new Map<number, [number, number]>();+ const flat = deform.offsets[part.name] ?? [];+ for (let i = 0; i < flat.length; i += 3) held.set(flat[i]!, [flat[i + 1]!, flat[i + 2]!]);+ let touched = false;+ for (let v = 0; v < part.vertices.length / 2; v++) {+ const at = rigVertex(rig, part, v), [ox, oy] = held.get(v) ?? [0, 0];+ const d = Math.hypot(at.x + ox - x, at.y + oy - y);+ if (d >= radius) continue;+ const reach = (1 - d / radius) ** 2;+ held.set(v, [ox + dx * reach, oy + dy * reach]);+ touched = true;+ moved++;+ }+ if (touched) deform.offsets[part.name] = [...held].sort((a, b) => a[0] - b[0]).flatMap(([v, [ox, oy]]) => [v, ox, oy]);+ }+ return moved;+}++/** How much `bone` moves each vertex of a part, 0..1: what a weight view colours. @experimental */+export function partWeightsOf(part: RigPart, bone: number): Float32Array {+ const out = new Float32Array(part.vertices.length / 2);+ part.weights.forEach((w, v) => {+ for (let i = 0; i < w.length; i += 2) if (w[i] === bone) out[v] = w[i + 1]!;+ });+ return out;+}diff --git a/sdk/src/rig2d/rigSource.ts b/sdk/src/rig2d/rigSource.tsnew file mode 100644index 000000000..bdd897799--- /dev/null+++ b/sdk/src/rig2d/rigSource.ts@@ -0,0 +1,181 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file rigSource.ts+ * @brief `.esrig`: a 2D character as it is authored. Parts cut from an image, the bones under them, what each vertex follows.+ *+ * @details The file a person edits; the `.esmesh` baked from it is what a scene draws, so a built game carries no rig code unless+ * it uses constraints. Bones in a scene are ordinary entities, which is what lets clips, the animator and masks reach them.+ * Rig space is world units, y up. Part vertices stay in image pixels, y down, so a part keeps its shape when it is moved.+ * A parent always comes before its children in `bones`: every walk over them relies on it.+ */++export const RIG_SOURCE_VERSION = 1;+export const RIG_SOURCE_EXT = '.esrig';+/** A vertex follows at most this many bones: what the mesh format's joint channel holds. */+export const RIG_MAX_INFLUENCES = 4;++/** @experimental */+export interface RigBone {+ name: string;+ /** Index of the parent bone, -1 for a root. */+ parent: number;+ /** Where it starts in its parent's space (rig space for a root). */+ x: number;+ y: number;+ /** Radians, counter-clockwise, in its parent's space. */+ rotation: number;+ /** How far it reaches along its own +x. Draws the bone, aims an IK chain, and shapes automatic weights. */+ length: number;+}++/** @experimental */+export interface RigPart {+ name: string;+ /** The piece of the image, in pixels from its top left. */+ rect: { x: number; y: number; w: number; h: number };+ /** Where the rect's top left sits in rig space. */+ x: number;+ y: number;+ /** Flat `[x, y, ...]`, in pixels from the rect's top left, y down. */+ vertices: number[];+ /** Flat vertex indices, three a triangle. */+ triangles: number[];+ /** Per vertex, flat `[bone, weight, ...]`, at most {@link RIG_MAX_INFLUENCES} pairs summing to 1. Empty until it is bound, which only a bake refuses. */+ weights: number[][];+}++/** A shape the mesh can blend towards. `offsets` is by part name, flat `[vertex, dx, dy, ...]` in rig units, y up. @experimental */+export interface RigDeform {+ name: string;+ offsets: Record<string, number[]>;+}++/** @experimental */+export interface RigSource {+ version: number;+ /** The image the parts are cut from. */+ texture: string;+ textureWidth: number;+ textureHeight: number;+ /** World units one image pixel covers. */+ unitsPerPixel: number;+ bones: RigBone[];+ /** In draw order, first at the back: they are one mesh, drawn in index order. */+ parts: RigPart[];+ deforms: RigDeform[];+}++/** @experimental */+export function createRig(texture: string, textureWidth: number, textureHeight: number, unitsPerPixel = 1): RigSource {+ return { version: RIG_SOURCE_VERSION, texture, textureWidth, textureHeight, unitsPerPixel, bones: [], parts: [], deforms: [] };+}++const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);+const flat = (v: unknown): v is number[] => Array.isArray(v) && v.every(finite);++/** Every way a rig is not a rig, as sentences. A rig still being made passes: no bones, and vertices that follow nothing yet. @experimental */+export function checkRig(rig: RigSource): string[] {+ const out: string[] = [];+ if (rig?.version !== RIG_SOURCE_VERSION) return [`version ${String(rig?.version)} is not one this engine reads (${RIG_SOURCE_VERSION})`];+ if (typeof rig.texture !== 'string') out.push('texture is not a path');+ if (!(rig.textureWidth > 0) || !(rig.textureHeight > 0)) out.push('the image size is missing');+ if (!(rig.unitsPerPixel > 0)) out.push('unitsPerPixel must be above 0');+ if (!Array.isArray(rig.bones) || !Array.isArray(rig.parts) || !Array.isArray(rig.deforms)) return [...out, 'bones, parts and deforms must be lists'];+ const boneNames = new Set<string>();+ rig.bones.forEach((b, i) => {+ if (typeof b?.name !== 'string' || b.name === '') out.push(`bone ${i} has no name`);+ else if (boneNames.has(b.name)) out.push(`two bones are called "${b.name}": a clip names a bone by its path, so the second could not be reached`);+ else boneNames.add(b.name);+ if (!Number.isInteger(b?.parent) || b.parent < -1 || b.parent >= i) out.push(`bone "${b?.name}" must name a parent earlier in the list`);+ if (![b?.x, b?.y, b?.rotation, b?.length].every(finite) || b.length < 0) out.push(`bone "${b?.name}" has a bad position, rotation or length`);+ });+ const partNames = new Set<string>();+ rig.parts.forEach((p) => {+ const label = `part "${p?.name}"`;+ if (typeof p?.name !== 'string' || p.name === '' || partNames.has(p.name)) out.push(`${label} needs a name of its own`);+ else partNames.add(p.name);+ if (![p?.rect?.x, p?.rect?.y, p?.rect?.w, p?.rect?.h, p?.x, p?.y].every(finite)) { out.push(`${label} has a bad rect or position`); return; }+ if (!flat(p.vertices) || p.vertices.length % 2 !== 0) { out.push(`${label} has bad vertices`); return; }+ const count = p.vertices.length / 2;+ if (!flat(p.triangles) || p.triangles.length % 3 !== 0 || p.triangles.some(t => !Number.isInteger(t) || t < 0 || t >= count)) out.push(`${label} has bad triangles`);+ if (!Array.isArray(p.weights) || p.weights.length !== count) { out.push(`${label} needs one weight list per vertex`); return; }+ p.weights.forEach((w, v) => {+ if (!flat(w) || w.length % 2 !== 0 || w.length > RIG_MAX_INFLUENCES * 2) { out.push(`${label} vertex ${v} has bad weights`); return; }+ for (let i = 0; i < w.length; i += 2) {+ if (!Number.isInteger(w[i]) || w[i]! < 0 || w[i]! >= rig.bones.length) { out.push(`${label} vertex ${v} follows a bone that is not there`); return; }+ }+ });+ });+ rig.deforms.forEach((d) => {+ if (typeof d?.name !== 'string' || d.name === '') out.push('a deform has no name');+ for (const [part, offsets] of Object.entries(d?.offsets ?? {})) {+ const owner = rig.parts.find(p => p.name === part);+ if (!owner) { out.push(`deform "${d.name}" moves a part that is not there: "${part}"`); continue; }+ if (!flat(offsets) || offsets.length % 3 !== 0) { out.push(`deform "${d.name}" has bad offsets for "${part}"`); continue; }+ for (let i = 0; i < offsets.length; i += 3) {+ if (!Number.isInteger(offsets[i]) || offsets[i]! < 0 || offsets[i]! >= owner.vertices.length / 2) { out.push(`deform "${d.name}" moves a vertex "${part}" does not have`); break; }+ }+ }+ });+ return out;+}++/** Reads a `.esrig`, refusing a damaged one: a silently repaired rig is a character that moves wrong later. @experimental */+export function parseRig(text: string): RigSource {+ const rig = JSON.parse(text) as RigSource;+ const problems = checkRig(rig);+ if (problems.length > 0) throw new Error(`this .esrig cannot be used: ${problems.join('; ')}`);+ return rig;+}++/** @experimental */+export function serializeRig(rig: RigSource): string {+ return `${JSON.stringify(rig, (_key, value) => (typeof value === 'number' && !Number.isInteger(value) ? Number(value.toFixed(5)) : value), 2)}\n`;+}++/** A bone's place in rig space. @experimental */+export interface RigBoneWorld { x: number; y: number; rotation: number }++/** Every bone in rig space. `rotations` poses them, by bone index, in place of their bind rotations. @experimental */+export function rigBoneWorlds(bones: readonly RigBone[], rotations?: ArrayLike<number>): RigBoneWorld[] {+ const out: RigBoneWorld[] = [];+ bones.forEach((b, i) => {+ const local = rotations?.[i] ?? b.rotation;+ const parent = out[b.parent];+ if (!parent) { out.push({ x: b.x, y: b.y, rotation: local }); return; }+ const c = Math.cos(parent.rotation), s = Math.sin(parent.rotation);+ out.push({ x: parent.x + c * b.x - s * b.y, y: parent.y + s * b.x + c * b.y, rotation: parent.rotation + local });+ });+ return out;+}++/** Takes a bone out, giving its children to its parent where they stand, and its vertices to its parent or nearest survivor. @experimental */+export function removeRigBone(rig: RigSource, index: number): void {+ const worlds = rigBoneWorlds(rig.bones), gone = rig.bones[index];+ if (!gone) return;+ const heir = gone.parent >= 0 ? gone.parent : -1;+ const heirWorld = heir >= 0 ? worlds[heir]! : { x: 0, y: 0, rotation: 0 };+ rig.bones.forEach((b, i) => {+ if (b.parent !== index) return;+ const w = worlds[i]!, c = Math.cos(heirWorld.rotation), s = Math.sin(heirWorld.rotation);+ const dx = w.x - heirWorld.x, dy = w.y - heirWorld.y;+ b.x = c * dx + s * dy; b.y = -s * dx + c * dy;+ b.rotation = w.rotation - heirWorld.rotation; b.parent = heir;+ });+ rig.bones.splice(index, 1);+ for (const b of rig.bones) if (b.parent > index) b.parent--;+ const shift = (bone: number): number => (bone > index ? bone - 1 : bone);+ const fallback = heir >= 0 ? heir : 0;+ for (const part of rig.parts) {+ part.weights = part.weights.map((w) => {+ const merged = new Map<number, number>();+ for (let i = 0; i < w.length; i += 2) {+ const bone = w[i] === index ? fallback : shift(w[i]!);+ merged.set(bone, (merged.get(bone) ?? 0) + w[i + 1]!);+ }+ return [...merged].flat();+ });+ if (rig.bones.length === 0) part.weights = part.weights.map(() => []);+ }+}diff --git a/sdk/src/rig2d/solve2d.ts b/sdk/src/rig2d/solve2d.tsnew file mode 100644index 000000000..eb2f4733d--- /dev/null+++ b/sdk/src/rig2d/solve2d.ts@@ -0,0 +1,106 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file solve2d.ts+ * @brief Bending a chain of bones towards a point, in one plane. Pure, so the runtime and an authoring view move a limb the same way.+ *+ * @details Two bones have an exact answer, which is also the only one that keeps a knee bending the way it was told. Longer chains+ * take cyclic coordinate descent: it respects a joint's limits directly, where a position-based solver would have to project them back afterwards.+ */++/** One bone of a chain. `x, y` is where it starts in its parent's space and `rotation` its turn there. @experimental */+export interface ChainBone {+ x: number;+ y: number;+ rotation: number;+ /** Radians the local rotation must stay between. */+ min?: number;+ max?: number;+}++/** @experimental */+export interface ChainSolveOptions {+ /** How far past the last bone's origin the point being aimed is, along its +x. */+ tipLength: number;+ /** Two bones only: which way the middle joint bends, +1 counter-clockwise. Defaults to the way it already bends. */+ bend?: number;+ iterations?: number;+ /** Close enough, in the chain's units. */+ tolerance?: number;+}++const wrap = (a: number): number => Math.atan2(Math.sin(a), Math.cos(a));++/** A rotation within a joint's limits, measured the short way round from the middle of them so a limit can cross ±180°. @experimental */+export function clampAngle(angle: number, min?: number, max?: number): number {+ if (min === undefined || max === undefined) return angle;+ const middle = (min + max) / 2, half = (max - min) / 2, off = wrap(angle - middle);+ return middle + Math.max(-half, Math.min(half, off));+}++/** Where the chain's tip ends up, in the space the first bone's `x, y` are in. @experimental */+export function chainTip(chain: readonly ChainBone[], tipLength: number): { x: number; y: number } {+ let x = 0, y = 0, angle = 0;+ chain.forEach((bone, i) => {+ const c = Math.cos(angle), s = Math.sin(angle);+ x += c * bone.x - s * bone.y;+ y += s * bone.x + c * bone.y;+ angle += bone.rotation;+ if (i === chain.length - 1) { x += Math.cos(angle) * tipLength; y += Math.sin(angle) * tipLength; }+ });+ return { x, y };+}++function solveTwoBones(chain: ChainBone[], targetX: number, targetY: number, opts: ChainSolveOptions): void {+ const upper = chain[0]!, lower = chain[1]!;+ const a = Math.hypot(lower.x, lower.y), b = opts.tipLength;+ const lean = Math.atan2(lower.y, lower.x);+ const dx = targetX - upper.x, dy = targetY - upper.y;+ const reach = Math.hypot(dx, dy);+ if (reach === 0) return;+ // Past its reach the limb straightens towards the point; closer than it can fold, it folds fully.+ const d = Math.max(Math.abs(a - b), Math.min(a + b, reach));+ const sign = opts.bend ?? (wrap(lower.rotation - lean) >= 0 ? 1 : -1);+ const cosElbow = Math.max(-1, Math.min(1, (d * d - a * a - b * b) / (2 * a * b)));+ const elbow = Math.acos(cosElbow) * sign;+ const shoulder = Math.atan2(dy, dx) - Math.atan2(b * Math.sin(elbow), a + b * Math.cos(elbow));+ upper.rotation = clampAngle(shoulder - lean, upper.min, upper.max);+ lower.rotation = clampAngle(elbow + lean, lower.min, lower.max);+}++function solveCCD(chain: ChainBone[], targetX: number, targetY: number, opts: ChainSolveOptions): void {+ const iterations = opts.iterations ?? 12, tolerance = opts.tolerance ?? 0.01;+ for (let pass = 0; pass < iterations; pass++) {+ for (let i = chain.length - 1; i >= 0; i--) {+ let x = 0, y = 0, angle = 0;+ for (let j = 0; j <= i; j++) {+ const c = Math.cos(angle), s = Math.sin(angle);+ x += c * chain[j]!.x - s * chain[j]!.y;+ y += s * chain[j]!.x + c * chain[j]!.y;+ if (j < i) angle += chain[j]!.rotation;+ }+ const tip = chainTip(chain, opts.tipLength);+ const turn = wrap(Math.atan2(targetY - y, targetX - x) - Math.atan2(tip.y - y, tip.x - x));+ chain[i]!.rotation = clampAngle(chain[i]!.rotation + turn, chain[i]!.min, chain[i]!.max);+ }+ const tip = chainTip(chain, opts.tipLength);+ if (Math.hypot(tip.x - targetX, tip.y - targetY) <= tolerance) return;+ }+}++/**+ * Turns the chain's bones in place so its tip reaches `target`, in the space the first bone's `x, y` are in. A point out of reach+ * leaves the chain stretched towards it.+ * @experimental+ */+export function solveChain2D(chain: ChainBone[], targetX: number, targetY: number, opts: ChainSolveOptions): void {+ if (chain.length === 0) return;+ if (chain.length === 1) {+ const bone = chain[0]!;+ bone.rotation = clampAngle(Math.atan2(targetY - bone.y, targetX - bone.x), bone.min, bone.max);+ } else if (chain.length === 2 && opts.tipLength > 0 && (chain[1]!.x !== 0 || chain[1]!.y !== 0)) {+ solveTwoBones(chain, targetX, targetY, opts);+ // A limit can leave the exact answer short of a point the limb could still reach another way.+ if (chain.some(b => b.min !== undefined)) solveCCD(chain, targetX, targetY, opts);+ } else solveCCD(chain, targetX, targetY, opts);+}diff --git a/sdk/src/rig2d/spawnRig.ts b/sdk/src/rig2d/spawnRig.tsnew file mode 100644index 000000000..d00a119b9--- /dev/null+++ b/sdk/src/rig2d/spawnRig.ts@@ -0,0 +1,71 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file spawnRig.ts+ * @brief A rig's bones and skin as entities in a running world, for characters a game makes in code. The editor writes the same shape into a scene.+ */+import { getComponent, MeshRenderer, Transform } from '../ecs/component';+import { PREFAB_FORMAT_VERSION } from '../prefab/migrate';+import type { World } from '../ecs/world';+import type { Entity } from '../types';+import { Bone2D } from './rig2dPlugin';+import type { RigSource } from './rigSource';++/** @experimental */+export interface SpawnedRig {+ /** Carries the MeshRenderer, the MeshSkin and, when the rig has deforms, the MeshMorph. */+ root: Entity;+ /** By bone index, which is the order the mesh's joints are in. */+ bones: Entity[];+}++/** `mesh` is the rig baked and loaded; `texture` is its image. Each bone is named as in the rig, so a clip reaches it by path. @experimental */+export function spawnRig(world: World, rig: RigSource, opts: { mesh: number; texture: number; layer?: number; x?: number; y?: number; z?: number }): SpawnedRig {+ const root = world.spawn('Rig');+ world.insert(root, Transform, { position: { x: opts.x ?? 0, y: opts.y ?? 0, z: opts.z ?? 0 } });+ const bones: Entity[] = [];+ rig.bones.forEach((bone, i) => {+ const entity = world.spawn(bone.name), half = bone.rotation / 2;+ world.insert(entity, Transform, {+ position: { x: bone.x, y: bone.y, z: 0 },+ rotation: { w: Math.cos(half), x: 0, y: 0, z: Math.sin(half) },+ });+ world.insert(entity, Bone2D, { length: bone.length });+ world.setParent(entity, bone.parent >= 0 ? bones[bone.parent]! : root);+ bones[i] = entity;+ });+ world.insert(root, MeshRenderer, { mesh: opts.mesh, texture: opts.texture, layer: opts.layer ?? 0, opaque: false, enabled: true });+ world.insert(root, getComponent('MeshSkin')!, { joints: bones });+ if (rig.deforms.length > 0) world.insert(root, getComponent('MeshMorph')!, { weights: rig.deforms.map(() => 0) });+ return { root, bones };+}++/**+ * A rig as a prefab, which is how it reaches a scene: saving again changes every instance, and what a scene adds to one (an IK2D, a clip) stays.+ * `mesh` and `texture` are asset refs. Same shape as {@link spawnRig}.+ * @experimental+ */+export function rigPrefab(rig: RigSource, name: string, mesh: string, texture: string): { version: string; name: string; rootEntityId: string; entities: Record<string, unknown>[] } {+ const idOf = (i: number): string => `b${i}`;+ const children = (parent: number): string[] => rig.bones.flatMap((b, i) => (b.parent === parent ? [idOf(i)] : []));+ const entities: Record<string, unknown>[] = [{+ prefabEntityId: 'root', name, parent: null, children: children(-1), visible: true,+ components: [+ { type: 'Transform', data: {} },+ { type: 'MeshRenderer', data: { mesh, texture, opaque: false } },+ { type: 'MeshSkin', data: { joints: rig.bones.map((_, i) => idOf(i)) } },+ ...(rig.deforms.length > 0 ? [{ type: 'MeshMorph', data: { weights: rig.deforms.map(() => 0) } }] : []),+ ],+ }];+ rig.bones.forEach((bone, i) => {+ const half = bone.rotation / 2;+ entities.push({+ prefabEntityId: idOf(i), name: bone.name, parent: bone.parent >= 0 ? idOf(bone.parent) : 'root', children: children(i), visible: true,+ components: [+ { type: 'Transform', data: { position: { x: bone.x, y: bone.y, z: 0 }, rotation: { w: Math.cos(half), x: 0, y: 0, z: Math.sin(half) } } },+ { type: 'Bone2D', data: { length: bone.length } },+ ],+ });+ });+ return { version: PREFAB_FORMAT_VERSION, name, rootEntityId: 'root', entities };+}diff --git a/sdk/src/runtime/optionalPlugins.ts b/sdk/src/runtime/optionalPlugins.tsindex 005d0df61..37cf8e5ed 100644--- a/sdk/src/runtime/optionalPlugins.ts+++ b/sdk/src/runtime/optionalPlugins.ts@@ -29,6 +29,7 @@ import { registerFoliageSupport } from '../foliage/foliageSupport';import { registerWorldGenSupport } from '../worldgen/worldgenSupport';import { registerWaterSupport } from '../water/waterSupport';import { registerSplineSupport } from '../spline/splineSupport';+import { registerRig2DSupport } from '../rig2d/rig2dSupport';import { registerImportedSceneSupport } from '../imported-scene/importedSceneSupport';import { registerCharacterShaders } from '../character/characterSupport';import { registerScriptGraphSupport } from '../logic/logicSupport';@@ -52,6 +53,7 @@ export function installOptionalPlugins(): void {registerWorldGenSupport();registerWaterSupport();registerSplineSupport();+ registerRig2DSupport();registerImportedSceneSupport();registerCharacterShaders();registerScriptGraphSupport();diff --git a/sdk/tests/rig2d-wasm.test.ts b/sdk/tests/rig2d-wasm.test.tsnew file mode 100644index 000000000..edd509d94--- /dev/null+++ b/sdk/tests/rig2d-wasm.test.ts@@ -0,0 +1,297 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, beforeAll, describe, expect, it } from 'vitest';+import { App } from '../src/app/app';+import { Parent, Transform, ensureBuiltinComponentsRegistered, getComponent } from '../src/ecs/component';+import { setEditorMode, setPlayMode } from '../src/ecs/env';+import { Bone2D, BoneConstraint2D, BoneConstraintKind, IK2D, Rig2DPlugin, createRig, spawnRig } from '../src/rig2d/index';+import { Rig2DSolver } from '../src/rig2d/rig2dPlugin';+import { Animator, AnimatorControllerAPI, type AnimatorData } from '../src/animation';+import { createTimelineMotionDriver, TIMELINE_MOTION } from '../src/timeline';+import { TimelineAPI } from '../src/timeline/TimelineControl';+import { InterpType, TrackType, WrapMode, type TimelineAsset } from '../src/timeline/TimelineTypes';+import type { Entity } from '../src/types';+import type { ESEngineModule } from '../src/wasm';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';++let core: ESEngineModule;+const apps: App[] = [];+afterEach(() => { for (const app of apps.splice(0)) app.quit(); });++function scene() {+ core.setActiveContext(null);+ const app = App.new(); apps.push(app); app.connectCpp(new core.Registry(), core, { ownedRegistry: true });+ setPlayMode(true);+ app.addPlugin(new Rig2DPlugin());+ const world = app.world;+ const spawn = (x: number, y: number, parent?: Entity, length?: number): Entity => {+ const e = world.spawn(); world.insert(e, Transform, { position: { x, y, z: 0 } });+ if (parent !== undefined) world.setParent(e, parent);+ if (length !== undefined) world.insert(e, Bone2D, { length });+ return e;+ };+ const angleOf = (e: Entity) => { const q = world.get(e, Transform).rotation; return 2 * Math.atan2(q.z, q.w); };+ /** Where the end of `tip` is, by what the engine itself composes. */+ const worldOf = (e: Entity) => { world.ensureTransformsComposed(); return world.get(e, Transform).worldPosition; };+ const tipOf = (tip: Entity, length: number) => {+ world.ensureTransformsComposed();+ const held = world.get(tip, Transform), a = 2 * Math.atan2(held.worldRotation.z, held.worldRotation.w);+ return { x: held.worldPosition.x + Math.cos(a) * length * held.worldScale.x, y: held.worldPosition.y + Math.sin(a) * length * held.worldScale.x };+ };+ const step = (n = 1) => app.stepFrames(n, 1 / 60);+ return { app, world, spawn, angleOf, worldOf, tipOf, step };+}++describe.skipIf(!HAS_WASM)('2D rig on a running world', () => {+ beforeAll(async () => { ensureBuiltinComponentsRegistered(); core = await loadWasmModule(); });++ it.each([+ ['at the origin', { x: 0, y: 0 }, { x: 1, y: 1 }, 0],+ ['carried somewhere', { x: 300, y: -40 }, { x: 1, y: 1 }, 0],+ ['under a turned parent', { x: 30, y: 10 }, { x: 1, y: 1 }, 0.8],+ ['under a scaled parent', { x: 0, y: 0 }, { x: 2, y: 2 }, 0],+ ['mirrored by a parent', { x: 50, y: 0 }, { x: -1, y: 1 }, 0],+ ])('puts the end of the chain on the target, by the engine\'s own transforms, %s', async (_name, at, scale, turn) => {+ const { world, spawn, tipOf, worldOf, step } = scene();+ const root = spawn(at.x, at.y);+ world.update(root, Transform, (t) => { t.scale = { x: scale.x, y: scale.y, z: 1 }; t.rotation = { w: Math.cos(turn / 2), x: 0, y: 0, z: Math.sin(turn / 2) }; });+ const upper = spawn(0, 0, root, 50), lower = spawn(50, 0, upper, 40);+ const target = spawn(at.x + 30 * scale.x, at.y + 50 * scale.y);+ world.insert(lower, IK2D, { target, chainLength: 2, bend: 1, weight: 1, matchTargetRotation: false, enabled: true });+ await step();+ const tip = tipOf(lower, 40), want = worldOf(target);+ expect(tip.x).toBeCloseTo(want.x, 1); expect(tip.y).toBeCloseTo(want.y, 1);+ });++ it('reaches under a body that is turned inside a mirrored parent', async () => {+ const { world, spawn, worldOf, step } = scene();+ const root = spawn(50, 0);+ world.update(root, Transform, (t) => { t.scale = { x: -1, y: 1, z: 1 }; });+ const torso = spawn(0, 20, root);+ world.update(torso, Transform, (t) => { t.rotation = { w: Math.cos(0.3), x: 0, y: 0, z: Math.sin(0.3) }; });+ const upper = spawn(10, 0, torso, 50), lower = spawn(50, 0, upper, 40), target = spawn(-10, 70);+ world.insert(lower, IK2D, { target, chainLength: 2, bend: 1, weight: 1, matchTargetRotation: false, enabled: true });+ await step();+ const want = worldOf(target);+ world.ensureTransformsComposed();+ const held = world.get(lower, Transform), a = 2 * Math.atan2(held.worldRotation.z, held.worldRotation.w);+ const tip = { x: held.worldPosition.x + Math.cos(a) * 40 * held.worldScale.x, y: held.worldPosition.y + Math.sin(a) * 40 * held.worldScale.x };+ expect(tip.x).toBeCloseTo(want.x, 1); expect(tip.y).toBeCloseTo(want.y, 1);+ });++ it('sees what a chain just moved, even where it looked before the chain moved it', async () => {+ const { world, spawn, worldOf, step } = scene();+ const root = spawn(0, 0);+ // The first chain reads `carried`, on a bone the second chain then turns; the constraint reads it after.+ const arm = spawn(0, 0, root, 30);+ const other = spawn(100, 0), wrist = spawn(0, 0, other, 40), hand = spawn(40, 0, wrist, 40), carried = spawn(30, 0, hand);+ const follower = spawn(-200, -200);+ world.insert(arm, IK2D, { target: carried, chainLength: 1, bend: 1, weight: 1, matchTargetRotation: false, enabled: true });+ const handTarget = spawn(100, 80);+ world.insert(hand, IK2D, { target: handTarget, chainLength: 2, bend: 1, weight: 1, matchTargetRotation: false, enabled: true });+ world.insert(follower, BoneConstraint2D, { kind: BoneConstraintKind.CopyPosition, source: carried, min: 0, max: 0, offset: 0, weight: 1, enabled: true });+ await step();+ const want = worldOf(carried), got = worldOf(follower);+ expect(got.x).toBeCloseTo(want.x, 1); expect(got.y).toBeCloseTo(want.y, 1);+ });++ it('keeps a chain of three within a limit, and still reaches', async () => {+ const { world, spawn, angleOf, tipOf, step } = scene();+ const root = spawn(0, 0), a = spawn(0, 0, root, 30), b = spawn(30, 0, a, 30), c = spawn(30, 0, b, 30), target = spawn(40, 50);+ world.insert(a, BoneConstraint2D, { kind: BoneConstraintKind.LimitRotation, source: 0 as Entity, min: -10, max: 10, offset: 0, weight: 1, enabled: true });+ world.insert(c, IK2D, { target, chainLength: 3, bend: 1, weight: 1, matchTargetRotation: false, enabled: true });+ await step();+ expect(Math.abs(angleOf(a))).toBeLessThanOrEqual(10 * Math.PI / 180 + 1e-5);+ const tip = tipOf(c, 30);+ expect(Math.hypot(tip.x - 40, tip.y - 50)).toBeLessThan(0.5);+ });++ it('follows a target that moves', async () => {+ const { world, spawn, tipOf, step } = scene();+ const root = spawn(0, 0), upper = spawn(0, 0, root, 50), lower = spawn(50, 0, upper, 50), target = spawn(60, 20);+ world.insert(lower, IK2D, { target, chainLength: 2, bend: 1, weight: 1, matchTargetRotation: false, enabled: true });+ await step();+ world.update(target, Transform, (t) => { t.position.x = -30; t.position.y = 70; });+ await step();+ const tip = tipOf(lower, 50);+ expect(tip.x).toBeCloseTo(-30, 1); expect(tip.y).toBeCloseTo(70, 1);+ });++ it('blends with what the animation said, and does not creep on a bone no clip moves', async () => {+ const { world, spawn, angleOf, step } = scene();+ const root = spawn(0, 0), upper = spawn(0, 0, root, 50), lower = spawn(50, 0, upper, 50), target = spawn(0, 80);+ world.insert(lower, IK2D, { target, chainLength: 2, bend: 1, weight: 0.5, matchTargetRotation: false, enabled: true });+ await step();+ const once = angleOf(upper);+ expect(Math.abs(once)).toBeGreaterThan(0.1);+ await step(30);+ expect(angleOf(upper)).toBeCloseTo(once, 4);+ });++ it('takes a new animated pose as its base', async () => {+ const { world, spawn, angleOf, step } = scene();+ const root = spawn(0, 0), upper = spawn(0, 0, root, 50), lower = spawn(50, 0, upper, 50), target = spawn(0, 80);+ world.insert(lower, IK2D, { target, chainLength: 2, bend: 1, weight: 0, matchTargetRotation: false, enabled: true });+ await step();+ world.update(upper, Transform, (t) => { t.rotation = { w: Math.cos(0.25), x: 0, y: 0, z: Math.sin(0.25) }; });+ await step();+ expect(angleOf(upper)).toBeCloseTo(0.5, 4);+ world.update(lower, IK2D, (ik) => { ik.weight = 1e-6; });+ await step();+ expect(angleOf(upper)).toBeCloseTo(0.5, 3);+ });++ it('does nothing without a target, disabled, or stopped', async () => {+ const { world, spawn, angleOf, step } = scene();+ const root = spawn(0, 0), upper = spawn(0, 0, root, 50), lower = spawn(50, 0, upper, 50);+ world.insert(lower, IK2D, { target: 0 as Entity, chainLength: 2, bend: 1, weight: 1, matchTargetRotation: false, enabled: true });+ await step();+ expect(angleOf(upper)).toBe(0);+ const target = spawn(0, 80);+ world.update(lower, IK2D, (ik) => { ik.target = target; ik.enabled = false; });+ await step();+ expect(angleOf(upper)).toBe(0);+ setEditorMode(true); setPlayMode(false);+ world.update(lower, IK2D, (ik) => { ik.enabled = true; });+ await step();+ expect(angleOf(upper)).toBe(0);+ setEditorMode(false); setPlayMode(true);+ });++ it('matches the target\'s rotation when asked', async () => {+ const { world, spawn, step } = scene();+ const root = spawn(0, 0), upper = spawn(0, 0, root, 50), lower = spawn(50, 0, upper, 50), target = spawn(60, 20);+ world.update(target, Transform, (t) => { t.rotation = { w: Math.cos(0.4), x: 0, y: 0, z: Math.sin(0.4) }; });+ world.insert(lower, IK2D, { target, chainLength: 2, bend: 1, weight: 1, matchTargetRotation: true, enabled: true });+ await step();+ world.ensureTransformsComposed();+ const q = world.get(lower, Transform).worldRotation;+ expect(2 * Math.atan2(q.z, q.w)).toBeCloseTo(0.8, 3);+ });++ it('limits a joint, by itself and inside a chain', async () => {+ const { world, spawn, angleOf, step } = scene();+ const root = spawn(0, 0), upper = spawn(0, 0, root, 50), lower = spawn(50, 0, upper, 50), target = spawn(-30, 60);+ world.insert(upper, BoneConstraint2D, { kind: BoneConstraintKind.LimitRotation, source: 0 as Entity, min: -10, max: 10, offset: 0, weight: 1, enabled: true });+ world.insert(lower, IK2D, { target, chainLength: 2, bend: 1, weight: 1, matchTargetRotation: false, enabled: true });+ await step();+ expect(Math.abs(angleOf(upper))).toBeLessThanOrEqual(10 * Math.PI / 180 + 1e-5);+ const alone = spawn(0, 0, root, 10);+ world.update(alone, Transform, (t) => { t.rotation = { w: Math.cos(1), x: 0, y: 0, z: Math.sin(1) }; });+ world.insert(alone, BoneConstraint2D, { kind: BoneConstraintKind.LimitRotation, source: 0 as Entity, min: -30, max: 30, offset: 0, weight: 1, enabled: true });+ await step();+ expect(angleOf(alone)).toBeCloseTo(30 * Math.PI / 180, 4);+ });++ it('copies rotation and position, and looks at, whatever turns the parent', async () => {+ const { world, spawn, worldOf, step } = scene();+ const parent = spawn(10, 0);+ world.update(parent, Transform, (t) => { t.rotation = { w: Math.cos(0.3), x: 0, y: 0, z: Math.sin(0.3) }; });+ const source = spawn(100, 50);+ world.update(source, Transform, (t) => { t.rotation = { w: Math.cos(0.5), x: 0, y: 0, z: Math.sin(0.5) }; });+ const copier = spawn(5, 0, parent), mover = spawn(5, 0, parent), looker = spawn(0, 0, parent);+ const row = { min: 0, max: 0, weight: 1, enabled: true };+ world.insert(copier, BoneConstraint2D, { ...row, kind: BoneConstraintKind.CopyRotation, source, offset: 90 });+ world.insert(mover, BoneConstraint2D, { ...row, kind: BoneConstraintKind.CopyPosition, source, offset: 0 });+ world.insert(looker, BoneConstraint2D, { ...row, kind: BoneConstraintKind.LookAt, source, offset: 0 });+ await step();+ world.ensureTransformsComposed();+ const worldAngle = (e: Entity) => { const q = world.get(e, Transform).worldRotation; return 2 * Math.atan2(q.z, q.w); };+ expect(worldAngle(copier)).toBeCloseTo(1 + Math.PI / 2, 3);+ expect(worldOf(mover).x).toBeCloseTo(100, 2); expect(worldOf(mover).y).toBeCloseTo(50, 2);+ expect(worldAngle(looker)).toBeCloseTo(Math.atan2(50, 90), 3);+ });++ it('bends a limb from where its body was just put by another chain', async () => {+ const { world, spawn, tipOf, step } = scene();+ const root = spawn(0, 0), spine = spawn(0, 0, root, 100), arm = spawn(100, 0, spine, 30), hand = spawn(30, 0, arm, 30);+ const bodyTarget = spawn(0, 100), handTarget = spawn(30, 110);+ world.insert(spine, IK2D, { target: bodyTarget, chainLength: 1, bend: 1, weight: 1, matchTargetRotation: false, enabled: true });+ world.insert(hand, IK2D, { target: handTarget, chainLength: 2, bend: 1, weight: 1, matchTargetRotation: false, enabled: true });+ await step();+ const tip = tipOf(hand, 30);+ expect(tip.x).toBeCloseTo(30, 1); expect(tip.y).toBeCloseTo(110, 1);+ });++ describe('under the animator', () => {+ const turn = (bone: string, angle: number): TimelineAsset => {+ const key = (value: number) => [{ time: 0, value, inTangent: 0, outTangent: 0, interpolation: InterpType.Linear }];+ return {+ version: '1.2', type: 'timeline', duration: 1, wrapMode: WrapMode.Loop,+ tracks: [{+ type: TrackType.Property, component: 'Transform', childPath: bone, name: bone,+ channels: [+ { property: 'rotation.w', keyframes: key(Math.cos(angle / 2)) }, { property: 'rotation.x', keyframes: key(0) },+ { property: 'rotation.y', keyframes: key(0) }, { property: 'rotation.z', keyframes: key(Math.sin(angle / 2)) },+ ],+ }],+ } as TimelineAsset;+ };+ function character() {+ const { world, angleOf, tipOf, spawn } = scene();+ const rig = createRig('x.png', 10, 10);+ rig.bones.push(+ { name: 'upper', parent: -1, x: 0, y: 0, rotation: 0, length: 50 },+ { name: 'lower', parent: 0, x: 50, y: 0, rotation: 0, length: 50 },+ { name: 'tail', parent: -1, x: 0, y: 0, rotation: 0, length: 10 },+ );+ const made = spawnRig(world, rig, { mesh: 0, texture: 0 });+ const timeline = new TimelineAPI();+ timeline.registerAsset('still', turn('upper/lower', 0));+ timeline.registerAsset('bent', turn('upper/lower', 1));+ timeline.registerAsset('wag', turn('tail', 0.6));+ const animator = new AnimatorControllerAPI();+ animator.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(timeline));+ animator.registerController('hero', {+ parameters: [{ name: 'speed', type: 'float', default: 0 }], initialState: 'Move',+ states: [{ name: 'Move', transitions: [], motion: {+ kind: 'blend1d', parameter: 'speed',+ thresholds: [{ value: 0, motion: { kind: TIMELINE_MOTION, clip: 'still' } }, { value: 1, motion: { kind: TIMELINE_MOTION, clip: 'bent' } }],+ } }],+ });+ world.insert(made.root, Animator, { controller: 'hero', currentState: '', enabled: true } as AnimatorData);+ return { world, made, animator, angleOf, tipOf, spawn };+ }++ it('blends two clips on a bone, by a parameter', () => {+ const { world, made, animator, angleOf } = character();+ for (const [speed, want] of [[0, 0], [0.5, 0.5], [1, 1]] as const) {+ animator.setFloat(made.root, 'speed', speed);+ animator.update(world, 0.016);+ expect(angleOf(made.bones[1]!)).toBeCloseTo(want, 2);+ }+ });++ it('lets a chain reach from the blended pose, and a bone no chain holds keep playing', () => {+ const { world, made, animator, angleOf, tipOf, spawn } = character();+ const solver = new Rig2DSolver(world), target = spawn(40, 40);+ world.insert(made.bones[1]!, IK2D, { target, chainLength: 2, bend: 1, weight: 1, matchTargetRotation: false, enabled: true });+ for (let frame = 0; frame < 3; frame++) {+ animator.setFloat(made.root, 'speed', 0.5);+ animator.update(world, 0.016);+ solver.step();+ const tip = tipOf(made.bones[1]!, 50);+ expect(tip.x).toBeCloseTo(40, 1); expect(tip.y).toBeCloseTo(40, 1);+ }+ expect(angleOf(made.bones[2]!)).toBe(0);+ // With the chain let go, the bone is back on what the clip said.+ world.update(made.bones[1]!, IK2D, (ik) => { ik.weight = 0; });+ animator.update(world, 0.016);+ solver.step();+ expect(angleOf(made.bones[1]!)).toBeCloseTo(0.5, 2);+ });+ });++ it('spawns a rig the way a clip finds it', () => {+ const { world } = scene();+ const rig = createRig('x.png', 10, 10);+ rig.bones.push({ name: 'a', parent: -1, x: 1, y: 2, rotation: 0.5, length: 3 }, { name: 'b', parent: 0, x: 3, y: 0, rotation: 0, length: 3 });+ rig.deforms.push({ name: 'd', offsets: {} });+ const made = spawnRig(world, rig, { mesh: 0, texture: 0 });+ expect(made.bones).toHaveLength(2);+ expect(world.get(made.bones[1]!, Parent).entity).toBe(made.bones[0]);+ expect(world.get(made.bones[0]!, Bone2D).length).toBe(3);+ expect(world.get(made.root, getComponent('MeshSkin')!).joints).toEqual(made.bones);+ expect(world.get(made.root, getComponent('MeshMorph')!).weights).toEqual([0]);+ });+});diff --git a/sdk/tests/rig2d.test.ts b/sdk/tests/rig2d.test.tsnew file mode 100644index 000000000..bc66c278b--- /dev/null+++ b/sdk/tests/rig2d.test.ts@@ -0,0 +1,319 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { decodeMesh, encodeMesh, MeshChannel } from '../src/asset/meshFormat';+import {+ autoWeightPart, bakeRig, bindPartToBone, chainTip, checkRig, clampAngle, coverRigPart, createRig, findRigParts, paintPartWeights, parseRig,+ partWeightsOf, pushRigDeform, removeRigBone, rigBoneWorlds, rigImageFromRGBA, rigVertex, serializeRig, skinRigPart, solveChain2D,+ type ChainBone, type RigPart, type RigSource,+} from '../src/rig2d/index';++const solidImage = (w: number, h: number, drawn: (x: number, y: number) => boolean) => ({ width: w, height: h, alpha: (x: number, y: number) => (drawn(x, y) ? 255 : 0) });++/** A 100x20 limb along +x from the origin, two bones meeting at its middle. */+function limb(): RigSource {+ const rig = createRig('limb.png', 100, 20);+ rig.bones.push({ name: 'upper', parent: -1, x: 0, y: 0, rotation: 0, length: 50 }, { name: 'lower', parent: 0, x: 50, y: 0, rotation: 0, length: 50 });+ const rect = { x: 0, y: 0, w: 100, h: 20 };+ const part: RigPart = { name: 'limb', rect, x: 0, y: 10, ...coverRigPart(solidImage(100, 20, () => true), rect, { cell: 10 }), weights: [] };+ rig.parts.push(part);+ autoWeightPart(rig, part);+ return rig;+}++function vertexOf(mesh: ReturnType<typeof bakeRig>, v: number) {+ const view = new DataView(mesh.vertices.buffer, mesh.vertices.byteOffset);+ const at = (s: number) => v * mesh.vertexStride + mesh.channels.find(c => c.semantic === s)!.offset;+ return {+ x: view.getFloat32(at(MeshChannel.Position), true), y: view.getFloat32(at(MeshChannel.Position) + 4, true),+ u: view.getFloat32(at(MeshChannel.TexCoord0), true), v: view.getFloat32(at(MeshChannel.TexCoord0) + 4, true),+ j0: view.getUint16(at(MeshChannel.Joints), true), w0: view.getFloat32(at(MeshChannel.Weights), true),+ };+}++describe('rig source', () => {+ it('round-trips through its file', () => {+ const rig = limb();+ expect(parseRig(serializeRig(rig)).bones).toEqual(rig.bones);+ expect(parseRig(serializeRig(rig)).parts[0]!.triangles).toEqual(rig.parts[0]!.triangles);+ });++ it.each([+ ['another version', (r: any) => { r.version = 99; }, /version/],+ ['a child before its parent', (r: any) => { r.bones[0].parent = 1; }, /earlier/],+ ['two bones of one name', (r: any) => { r.bones[1].name = 'upper'; }, /two bones/],+ ['a triangle past the vertices', (r: any) => { r.parts[0].triangles[0] = 99999; }, /triangles/],+ ['a vertex with no weight list', (r: any) => { r.parts[0].weights.pop(); }, /weight list/],+ ['a weight on a missing bone', (r: any) => { r.parts[0].weights[0] = [7, 1]; }, /not there/],+ ['more influences than the mesh holds', (r: any) => { r.parts[0].weights[0] = [0, .2, 0, .2, 0, .2, 0, .2, 0, .2]; }, /bad weights/],+ ['a deform of a missing part', (r: any) => { r.deforms.push({ name: 'd', offsets: { nope: [0, 1, 1] } }); }, /not there/],+ ['a deform of a missing vertex', (r: any) => { r.deforms.push({ name: 'd', offsets: { limb: [99999, 1, 1] } }); }, /does not have/],+ ])('refuses %s', (_name, spoil, message) => {+ const rig = limb();+ spoil(rig);+ expect(checkRig(rig).join(' ')).toMatch(message);+ expect(() => parseRig(JSON.stringify(rig))).toThrow(message);+ });++ it('gives a removed bone\'s children and vertices to its parent, leaving the children where they stood', () => {+ const rig = createRig('x.png', 10, 10);+ rig.bones.push(+ { name: 'a', parent: -1, x: 10, y: 0, rotation: Math.PI / 2, length: 10 },+ { name: 'b', parent: 0, x: 10, y: 0, rotation: 0.5, length: 10 },+ { name: 'c', parent: 1, x: 10, y: 0, rotation: 0.25, length: 10 },+ );+ rig.parts.push({ name: 'p', rect: { x: 0, y: 0, w: 1, h: 1 }, x: 0, y: 0, vertices: [0, 0], triangles: [], weights: [[1, 0.5, 2, 0.5]] });+ const before = rigBoneWorlds(rig.bones)[2]!;+ removeRigBone(rig, 1);+ expect(rig.bones.map(b => b.name)).toEqual(['a', 'c']);+ const after = rigBoneWorlds(rig.bones)[1]!;+ expect(after.x).toBeCloseTo(before.x); expect(after.y).toBeCloseTo(before.y); expect(after.rotation).toBeCloseTo(before.rotation);+ expect(rig.parts[0]!.weights[0]).toEqual([0, 0.5, 1, 0.5]);+ expect(checkRig(rig)).toEqual([]);+ });+});++describe('from an image', () => {+ it('finds each separate picture, leaving specks out', () => {+ const image = solidImage(40, 20, (x, y) => (x < 10 && y < 10) || (x >= 20 && x < 35 && y >= 5 && y < 15) || (x === 39 && y === 19));+ expect(findRigParts(image)).toEqual([{ x: 20, y: 5, w: 15, h: 10 }, { x: 0, y: 0, w: 10, h: 10 }]);+ });++ it('reads alpha out of RGBA rows', () => {+ const rgba = new Uint8Array(2 * 2 * 4); rgba[(1 * 2 + 1) * 4 + 3] = 200;+ const image = rigImageFromRGBA(2, 2, rgba);+ expect(image.alpha(1, 1)).toBe(200); expect(image.alpha(0, 0)).toBe(0);+ });++ it('covers what is drawn and nothing else, sharing corners', () => {+ const image = solidImage(30, 10, x => x < 10 || x >= 20);+ const { vertices, triangles } = coverRigPart(image, { x: 0, y: 0, w: 30, h: 10 }, { cell: 10 });+ expect(triangles.length).toBe(2 * 2 * 3);+ expect(vertices.length / 2).toBe(8);+ for (let v = 0; v < vertices.length; v += 2) expect(vertices[v]! <= 10 || vertices[v]! >= 20).toBe(true);+ });++ it('stays inside a rect that is not a whole number of cells', () => {+ const { vertices } = coverRigPart(solidImage(25, 13, () => true), { x: 0, y: 0, w: 25, h: 13 }, { cell: 10 });+ expect(Math.max(...vertices.filter((_, i) => i % 2 === 0))).toBe(25);+ expect(Math.max(...vertices.filter((_, i) => i % 2 === 1))).toBe(13);+ });++ it('winds its triangles the way the mesh pipeline culls, counter-clockwise with y up', () => {+ const rig = limb(), part = rig.parts[0]!;+ for (let t = 0; t < part.triangles.length; t += 3) {+ const [a, b, c] = [0, 1, 2].map(i => rigVertex(rig, part, part.triangles[t + i]!)) as [{ x: number; y: number }, { x: number; y: number }, { x: number; y: number }];+ expect((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)).toBeGreaterThan(0);+ }+ });+});++describe('weights', () => {+ it('follows the nearer bone, and sums to one', () => {+ const rig = limb(), part = rig.parts[0]!;+ part.weights.forEach((w, v) => {+ let sum = 0;+ for (let i = 1; i < w.length; i += 2) sum += w[i]!;+ expect(sum).toBeCloseTo(1);+ const at = rigVertex(rig, part, v), share = partWeightsOf(part, 0)[v]!;+ if (at.x < 30) expect(share).toBeGreaterThan(0.9);+ if (at.x > 70) expect(share).toBeLessThan(0.1);+ });+ });++ it('binds only to the bones it is allowed', () => {+ const rig = limb(), part = rig.parts[0]!;+ autoWeightPart(rig, part, { bones: [1] });+ expect(part.weights.every(w => w.length === 2 && w[0] === 1 && w[1] === 1)).toBe(true);+ bindPartToBone(part, 0);+ expect(part.weights.every(w => w[0] === 0 && w[1] === 1)).toBe(true);+ });++ const sums = (part: RigPart) => part.weights.map(w => w.reduce((t, x, i) => (i % 2 ? t + x : t), 0));++ it('paints a bone in within the brush, the others giving way', () => {+ const rig = limb(), part = rig.parts[0]!;+ bindPartToBone(part, 0);+ const changed = paintPartWeights(rig, part, { x: 80, y: 0, radius: 15, bone: 1, strength: 1, mode: 'add' });+ expect(changed).toBeGreaterThan(0);+ const share = partWeightsOf(part, 1);+ part.weights.forEach((_, v) => {+ const at = rigVertex(rig, part, v), d = Math.hypot(at.x - 80, at.y);+ if (d >= 15) expect(share[v]).toBe(0); else expect(share[v]).toBeGreaterThan(0);+ if (d === 0) expect(share[v]).toBeCloseTo(1);+ });+ for (const s of sums(part)) expect(s).toBeCloseTo(1);+ expect(checkRig(rig)).toEqual([]);+ });++ it('removes a bone without ever leaving a vertex that follows nothing', () => {+ const rig = limb(), part = rig.parts[0]!;+ bindPartToBone(part, 0);+ paintPartWeights(rig, part, { x: 50, y: 0, radius: 500, bone: 0, strength: 1, mode: 'remove' });+ expect(part.weights.every(w => w.length >= 2)).toBe(true);+ for (const s of sums(part)) expect(s).toBeCloseTo(1);+ });++ it('smooths a hard edge, keeping the sum', () => {+ const rig = limb(), part = rig.parts[0]!;+ part.weights = part.weights.map((_, v) => [rigVertex(rig, part, v).x < 50 ? 0 : 1, 1]);+ const near = part.weights.findIndex((_, v) => rigVertex(rig, part, v).x === 50);+ expect(partWeightsOf(part, 0)[near]).toBe(0);+ paintPartWeights(rig, part, { x: 50, y: 0, radius: 40, bone: 0, strength: 1, mode: 'smooth' });+ const share = partWeightsOf(part, 0)[near]!;+ expect(share).toBeGreaterThan(0.2); expect(share).toBeLessThan(0.8);+ for (const s of sums(part)) expect(s).toBeCloseTo(1);+ });+});++describe('baking', () => {+ it('refuses what could not move', () => {+ const none = createRig('x.png', 10, 10);+ expect(() => bakeRig(none)).toThrow(/no bones/);+ const rig = limb();+ rig.parts[0]!.weights[0] = [];+ expect(() => bakeRig(rig)).toThrow();+ });++ it('survives the mesh file with its skin and shapes', () => {+ const rig = limb();+ rig.deforms.push({ name: 'bulge', offsets: { limb: [0, 3, 4] } });+ const mesh = decodeMesh(encodeMesh(bakeRig(rig)));+ expect(mesh.vertexCount).toBe(rig.parts[0]!.vertices.length / 2);+ expect(mesh.inverseBindMatrices!.length).toBe(32);+ expect(mesh.morph!.names).toEqual(['bulge']);+ expect([...mesh.morph!.deltas.slice(0, 3)]).toEqual([3, 4, 0]);+ });++ it('turns image pixels into rig space and into UVs with row 0 at the top', () => {+ const rig = createRig('x.png', 200, 100, 0.5);+ rig.bones.push({ name: 'b', parent: -1, x: 0, y: 0, rotation: 0, length: 0 });+ const part: RigPart = { name: 'p', rect: { x: 50, y: 20, w: 10, h: 10 }, x: 7, y: 9, vertices: [10, 10], triangles: [], weights: [[0, 1]] };+ rig.parts.push(part);+ const v = vertexOf(bakeRig(rig), 0);+ expect(v.x).toBeCloseTo(7 + 5); expect(v.y).toBeCloseTo(9 - 5);+ expect(v.u).toBeCloseTo(60 / 200); expect(v.v).toBeCloseTo(1 - 30 / 100);+ });++ it('lays parts down in draw order', () => {+ const rig = limb();+ rig.parts.push({ ...rig.parts[0]!, name: 'front' });+ const mesh = bakeRig(rig), count = rig.parts[0]!.vertices.length / 2;+ const last = mesh.indices.slice(mesh.indices.length / 2);+ expect(Math.min(...last)).toBe(count);+ });++ it('holds the bind pose: joint world times inverse bind is identity', () => {+ const rig = limb();+ rig.bones[1]!.rotation = 0.7;+ const mesh = bakeRig(rig), worlds = rigBoneWorlds(rig.bones);+ worlds.forEach((w, i) => {+ const m = mesh.inverseBindMatrices!.slice(i * 16, i * 16 + 16);+ // Applying the inverse to the joint's own origin lands on zero, and to a point one along its +x on (1, 0).+ const apply = (x: number, y: number) => ({ x: m[0]! * x + m[4]! * y + m[12]!, y: m[1]! * x + m[5]! * y + m[13]! });+ expect(apply(w.x, w.y).x).toBeCloseTo(0); expect(apply(w.x, w.y).y).toBeCloseTo(0);+ const along = apply(w.x + Math.cos(w.rotation), w.y + Math.sin(w.rotation));+ expect(along.x).toBeCloseTo(1); expect(along.y).toBeCloseTo(0);+ });+ });+});++describe('skinning a preview', () => {+ it('leaves the bind pose where it is', () => {+ const rig = limb(), out = skinRigPart(rig, 0, rigBoneWorlds(rig.bones));+ for (let v = 0; v < out.length / 2; v++) {+ const at = rigVertex(rig, rig.parts[0]!, v);+ expect(out[v * 2]).toBeCloseTo(at.x); expect(out[v * 2 + 1]).toBeCloseTo(at.y);+ }+ });++ it('carries a vertex with its bone, and deforms before it bends', () => {+ const rig = limb(), part = rig.parts[0]!;+ bindPartToBone(part, 1);+ rig.deforms.push({ name: 'up', offsets: { limb: [0, 0, 10] } });+ const posed = rigBoneWorlds(rig.bones, [0, Math.PI / 2]);+ const out = skinRigPart(rig, 0, posed, [1]);+ const v0 = rigVertex(rig, part, 0);+ // Offset up 10 in bind space, then a quarter turn about (50, 0): (x, y) -> (50 - y, x - 50).+ expect(out[0]).toBeCloseTo(50 - (v0.y + 10)); expect(out[1]).toBeCloseTo(v0.x - 50);+ });+});++describe('pushing a deform', () => {+ it('moves what is under the brush, adds up, and bakes', () => {+ const rig = limb();+ rig.deforms.push({ name: 'bulge', offsets: {} });+ expect(pushRigDeform(rig, 0, 500, 500, 10, 1, 1)).toBe(0);+ expect(pushRigDeform(rig, 0, 50, 0, 25, 0, 8)).toBeGreaterThan(0);+ const offsets = rig.deforms[0]!.offsets.limb!;+ const centre = rig.parts[0]!.vertices.findIndex((_, i) => i % 2 === 0 && rig.parts[0]!.vertices[i] === 50 && rig.parts[0]!.vertices[i + 1] === 10) / 2;+ const at = offsets.findIndex((_, i) => i % 3 === 0 && offsets[i] === centre);+ expect(offsets[at + 2]).toBeCloseTo(8);+ expect(checkRig(rig)).toEqual([]);+ pushRigDeform(rig, 0, 50, 8, 25, 0, 4);+ expect(rig.deforms[0]!.offsets.limb![at + 2]).toBeCloseTo(12);+ expect(bakeRig(rig).morph!.names).toEqual(['bulge']);+ });+});++describe('chain solving', () => {+ const arm = (): ChainBone[] => [{ x: 0, y: 0, rotation: 0 }, { x: 50, y: 0, rotation: 0.2 }];++ it('reaches exactly with two bones, either way it bends', () => {+ for (const bend of [1, -1]) {+ const chain = arm();+ solveChain2D(chain, 40, 60, { tipLength: 50, bend });+ const tip = chainTip(chain, 50);+ expect(tip.x).toBeCloseTo(40); expect(tip.y).toBeCloseTo(60);+ expect(Math.sign(Math.sin(chain[1]!.rotation))).toBe(bend);+ }+ });++ it('reaches with a middle joint that does not lie along the bone above it', () => {+ const chain: ChainBone[] = [{ x: 5, y: 7, rotation: 0 }, { x: 40, y: 30, rotation: 0.3 }];+ solveChain2D(chain, 30, 60, { tipLength: 50, bend: 1 });+ const tip = chainTip(chain, 50);+ expect(tip.x).toBeCloseTo(30); expect(tip.y).toBeCloseTo(60);+ });++ it('finds another way when a limit stops the exact answer of two bones', () => {+ const chain: ChainBone[] = [{ x: 0, y: 0, rotation: 0, min: -0.2, max: 0.2 }, { x: 50, y: 0, rotation: 0.2 }];+ solveChain2D(chain, 60, 45, { tipLength: 50, bend: 1 });+ const tip = chainTip(chain, 50);+ expect(Math.hypot(tip.x - 60, tip.y - 45)).toBeLessThan(0.5);+ expect(Math.abs(chain[0]!.rotation)).toBeLessThanOrEqual(0.2 + 1e-9);+ });++ it('straightens at what it cannot reach, and does not break at what it cannot fold to', () => {+ const far = arm();+ solveChain2D(far, 500, 0, { tipLength: 50 });+ expect(chainTip(far, 50).x).toBeCloseTo(100);+ const close = arm();+ solveChain2D(close, 0, 0, { tipLength: 50 });+ expect(close.every(b => Number.isFinite(b.rotation))).toBe(true);+ const shortTip = arm();+ solveChain2D(shortTip, 3, 4, { tipLength: 20 });+ const tip = chainTip(shortTip, 20);+ expect(Math.hypot(tip.x, tip.y)).toBeCloseTo(30);+ });++ it('reaches with a long chain', () => {+ const chain: ChainBone[] = Array.from({ length: 6 }, (_, i) => ({ x: i === 0 ? 0 : 20, y: 0, rotation: 0.1 }));+ solveChain2D(chain, 40, 70, { tipLength: 20 });+ const tip = chainTip(chain, 20);+ expect(Math.hypot(tip.x - 40, tip.y - 70)).toBeLessThan(0.5);+ });++ it('keeps a long chain within its joints\' limits', () => {+ const chain: ChainBone[] = Array.from({ length: 4 }, (_, i) => ({ x: i === 0 ? 0 : 20, y: 0, rotation: 0, min: -0.3, max: 0.3 }));+ solveChain2D(chain, -40, 10, { tipLength: 20 });+ for (const b of chain) expect(Math.abs(b.rotation)).toBeLessThanOrEqual(0.3 + 1e-9);+ });++ it('clamps across the wrap, the short way round', () => {+ expect(clampAngle(3.1, 2.8, 3.4)).toBeCloseTo(3.1);+ expect(clampAngle(-3.1, 2.8, 3.4)).toBeCloseTo(-3.1 + Math.PI * 2);+ expect(clampAngle(0, -1, 1)).toBe(0);+ expect(clampAngle(5, undefined, undefined)).toBe(5);+ });+});diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjsindex 6b9ca28c8..7ebe5c7c8 100644--- a/tools/apiSubsystems.mjs+++ b/tools/apiSubsystems.mjs@@ -335,6 +335,16 @@ export const SUBSYSTEMS = [whyZh: '曲线和按距离度量已经有检查,但目前只有河流会沿着它走,编辑器里也还没有绘制它的工具',entry: ['Spline', 'SplineCurve'],},+ {+ id: 'rig2d',+ title: '2D rigs',+ titleZh: '2D 骨骼',+ source: ['rig2d'],+ tier: 'experimental',+ why: 'baking, weights and the solvers are checked against the real engine, but no shipped example carries a rig yet, and its editor is new.',+ whyZh: '烘焙、权重和解算都对真实引擎做了检查,但还没有示例真正用上骨骼角色,编辑器也是新的。',+ entry: ['createRig', 'bakeRig', 'IK2D'],+ },{id: 'imported-scene',title: 'Imported scene runtime',diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.jsindex a6e614d66..40e82bd69 100644--- a/tools/assetMetaTable.js+++ b/tools/assetMetaTable.js@@ -91,6 +91,9 @@ export const EXT_TO_TYPE = Object.freeze({// `.esmesh`, and that is what a scene references. Typed for the same reason// `.esmatgraph` is, and apart from `model` because nothing imports it.'.esmodel': 'modeling',+ // A 2D character as it is authored. Never shipped, for the same reason: saving one bakes+ // the sibling `.esmesh`, and a scene references that.+ '.esrig': 'rig','.esanim': 'animclip','.esanimclip': 'animclip','.estimeline': 'animation',diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjsindex 238571dfe..60f6922d4 100644--- a/tools/check-corpus-authoring.mjs+++ b/tools/check-corpus-authoring.mjs@@ -142,6 +142,9 @@ const DISPOSITION = {PathFollower: ['owed', 'no example moves a thing along a spline yet; a platform or a cart on a track is the first to'],Ragdoll: ['owed', 'no example carries a skinned character that is knocked down yet; the first one with a rigged enemy goes into one'],RagdollJoint: ['owed', 'arrives with the first example that has a Ragdoll, which is the only place a bone needs a say of its own'],+ Bone2D: ['owed', 'no example carries a 2D rig yet; the first character built in the rig editor is the place for it'],+ IK2D: ['owed', 'arrives with the first example that has a Bone2D, which is the only place a chain has bones to bend'],+ BoneConstraint2D: ['owed', 'arrives with the first example that has a Bone2D, for the same reason'],TerrainBand2D: ['owed', 'no example draws a 2D ground from a spline yet; the first side-scroller built on one carries it'],Impostor: ['owed', 'no example has far objects small enough to stand a picture in for yet; an open 3D world with distant props is the first to'],Billboard: ['owed', 'no example draws a card that faces the camera yet; a 3D scene with signs or far trees on cards is the first to'],diff --git a/tools/lib/sdkProgram.mjs b/tools/lib/sdkProgram.mjsindex b183a5560..b515f88da 100644--- a/tools/lib/sdkProgram.mjs+++ b/tools/lib/sdkProgram.mjs@@ -68,6 +68,7 @@ export const ENTRIES = {'worldgen': 'src/worldgen/index.ts','water': 'src/water/index.ts','spline': 'src/spline/index.ts',+ 'rig2d': 'src/rig2d/index.ts','imported-scene': 'src/imported-scene/index.ts','character-shaders': 'src/character/index.ts','logic': 'src/logic/index.ts',diff --git a/tools/nativeScriptModules.js b/tools/nativeScriptModules.jsindex 0f4cff491..20509534c 100644--- a/tools/nativeScriptModules.js+++ b/tools/nativeScriptModules.js@@ -74,6 +74,7 @@ export const MODULES = {'esengine/worldgen': { disposition: 'native-subpath' },'esengine/water': { disposition: 'native-subpath' },'esengine/spline': { disposition: 'native-subpath' },+ 'esengine/rig2d': { disposition: 'native-subpath' },'esengine/imported-scene': { disposition: 'native-subpath' },'esengine/character-shaders': { disposition: 'native-subpath' },'esengine/logic': { disposition: 'native-subpath' },diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 74104c93e..a12dcd420 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4216,4 +4216,12 @@ export const NOTED = {{"note": "A row of tiles being edited uploads a piece of itself."},"feat(tilemap): a tile layer can be dug, blown up and rebuilt while the game runs":{"note": "A tile layer can be dug, blown up and rebuilt while the game runs."},+ "fix(render): a skinned mesh is culled around its joints, not where its entity stands":+ {"note": "A skinned mesh is not culled for where its entity stands."},+ "feat(rig2d): a 2D character can be rigged with no other program, with IK and bone constraints":+ {"note": "A 2D character can be rigged in the editor, with no other program."},+ "fix(assets): one hot load at a time per asset, so two rescans cannot lose a texture":+ {"note": "A texture stays on a scene that rescans as it is placed."},+ "feat(rig): the 2D rig editor, from an image to a character in the scene":+ {"note": "A 2D character can be rigged in the editor, with no other program."},};