Merge pull request 'feature/gltf-pipeline-v2' (#18) from feature/gltf-pipeline-v2 into develop

Reviewed-on: #18
This commit was merged in pull request #18.
This commit is contained in:
2026-04-17 02:07:43 +00:00
18 changed files with 1381 additions and 183 deletions

View File

@@ -96,16 +96,17 @@ PlayerArmature ← armature root object (never keyframe this)
**Never animate:** `PlayerArmature` — it's the armature root object, not a bone. **Never animate:** `PlayerArmature` — it's the armature root object, not a bone.
**Everything else follows this rule:** **Everything else follows this rule:**
- Your item **always** controls bones in its declared regions. - **Standard animations** (`Idle`, `Struggle`, `Walk`): your item controls ONLY bones in its declared regions. Keyframes on other bones are ignored.
- Your item **can also** animate free bones (not owned by any other equipped item). - **`Full` animations** (`FullIdle`, `FullStruggle`, `FullWalk`): your item also controls free bones (body, legs — not owned by another item). See [Full-Body Animations](#full-body-animations-naming-convention).
- **Head is protected by default**: vanilla head tracking is preserved unless your item owns a head region (HEAD, EYES, EARS, MOUTH). In `Full` animations, head stays protected. Use `FullHead` prefix (e.g., `FullHeadStruggle`) to explicitly opt into head animation as a free bone.
- Your item **cannot** override bones owned by another equipped item. - Your item **cannot** override bones owned by another equipped item.
| Bone | Who Controls It | | Bone | Who Controls It |
|------|----------------| |------|----------------|
| `body` / `torso` | Context layer by default. Your item if it owns TORSO or WAIST, or if `body` is free. | | `body` / `torso` | Context layer by default. Your item if it owns TORSO or WAIST. Also available as a free bone in `Full` animations. |
| `head` | Vanilla head tracking by default. Your item if it owns HEAD, EYES, EARS, or MOUTH. | | `head` | **Vanilla head tracking by default.** Your item if it owns HEAD, EYES, EARS, or MOUTH. Available as a free bone ONLY in `FullHead` animations (e.g., `FullHeadStruggle`). |
| Arms (`*UpperArm`, `*LowerArm`) | Vanilla by default. Your item if it owns ARMS or HANDS. | | Arms (`*UpperArm`, `*LowerArm`) | Vanilla by default. Your item if it owns ARMS or HANDS. Also available as free bones in `Full` animations. |
| Legs (`*UpperLeg`, `*LowerLeg`) | Context layer by default. Your item if it owns LEGS or FEET. | | Legs (`*UpperLeg`, `*LowerLeg`) | Context layer by default. Your item if it owns LEGS or FEET. Also available as free bones in `Full` animations. |
**Note:** `torso` and `body` both map to the same internal part. Prefer animating `body` — using `torso` produces the same result but is less intuitive. **Note:** `torso` and `body` both map to the same internal part. Prefer animating `body` — using `torso` produces the same result but is less intuitive.
@@ -160,7 +161,7 @@ Three regions are **global** — they encompass sub-regions:
Use the **TiedUp! Blender Template** (provided with the mod). It contains: Use the **TiedUp! Blender Template** (provided with the mod). It contains:
- The correct `PlayerArmature` skeleton with all 11 bones - The correct `PlayerArmature` skeleton with all 11 bones
- A reference player mesh (Steve + Alex) for scale — toggle visibility as needed - A reference player mesh (Slime model) for scale — toggle visibility as needed
- Pre-named Action slots - Pre-named Action slots
### Guidelines ### Guidelines
@@ -183,7 +184,8 @@ Weight paint your mesh to the skeleton bones it should follow.
### Rules ### Rules
- **Only paint to the 11 standard bones.** Any other bones in your Blender file will be ignored by the mod. - **Paint to the 11 standard bones** for parts that should follow the player's body.
- **You can also use custom bones** for decorative elements like chains, ribbons, pendants, or twist bones. Custom bones follow their parent in the bone hierarchy (rest pose) — they won't animate independently, but they move with the body part they're attached to. This is useful for better weight painting and mesh deformation.
- **Paint to the bones of your regions.** Handcuffs (ARMS region) should be weighted to `rightUpperArm`, `rightLowerArm`, `leftUpperArm`, `leftLowerArm`. - **Paint to the bones of your regions.** Handcuffs (ARMS region) should be weighted to `rightUpperArm`, `rightLowerArm`, `leftUpperArm`, `leftLowerArm`.
- **You can paint to bones outside your regions** for smooth deformation. For example, handcuffs might have small weights on `body` near the shoulder area for smoother bending. This is fine — the weight painting is about mesh deformation, not animation control. - **You can paint to bones outside your regions** for smooth deformation. For example, handcuffs might have small weights on `body` near the shoulder area for smoother bending. This is fine — the weight painting is about mesh deformation, not animation control.
- **Normalize your weights.** Each vertex's total weights across all bones must sum to 1.0. Blender does this by default. - **Normalize your weights.** Each vertex's total weights across all bones must sum to 1.0. Blender does this by default.
@@ -193,6 +195,7 @@ Weight paint your mesh to the skeleton bones it should follow.
- For rigid items (metal cuffs), use hard weights — each vertex fully assigned to one bone. - For rigid items (metal cuffs), use hard weights — each vertex fully assigned to one bone.
- For flexible items (rope, leather), blend weights between adjacent bones for smooth bending. - For flexible items (rope, leather), blend weights between adjacent bones for smooth bending.
- The chain between handcuffs? Weight it 50/50 to both arms, or use a separate mesh element weighted to `body`. - The chain between handcuffs? Weight it 50/50 to both arms, or use a separate mesh element weighted to `body`.
- Custom bones are great for chains, dangling locks, or decorative straps — add a bone parented to a standard bone, weight your mesh to it, and it'll follow the parent's movement automatically.
--- ---
@@ -258,9 +261,6 @@ Declare default colors per channel in your item JSON:
"tintable_1": "#FF0000", "tintable_1": "#FF0000",
"tintable_2": "#C0C0C0" "tintable_2": "#C0C0C0"
}, },
"animation_bones": {
"idle": []
},
"pose_priority": 10, "pose_priority": 10,
"escape_difficulty": 3 "escape_difficulty": 3
} }
@@ -309,19 +309,19 @@ The `PlayerArmature|` prefix is Blender's convention for armature-scoped actions
| Gag (MOUTH) | *(none)* | No pose change — mesh only | | Gag (MOUTH) | *(none)* | No pose change — mesh only |
| Straitjacket (ARMS+TORSO) | Arms + body (+ legs if free) | Arms crossed, slight forward lean, optional waddle | | Straitjacket (ARMS+TORSO) | Arms + body (+ legs if free) | Arms crossed, slight forward lean, optional waddle |
**Why only your bones?** The mod's 2-layer system activates your keyframes for bones in your declared regions. But there's a nuance: **free bones** (bones not owned by any equipped item) can also be animated by your item. **Why only your bones?** In standard animations (`Idle`, `Struggle`), the mod only uses keyframes for bones in your declared regions. Keyframes on other bones are ignored — safe to leave them in your GLB.
For example: if a player wears only a straitjacket (ARMS+TORSO), the legs are "free" — no item claims them. If your straitjacket's GLB has leg keyframes (e.g., a waddle walk), the mod will use them. But if the player also wears ankle cuffs (LEGS), those leg keyframes are ignored — the ankle cuffs take over. To animate free bones (body, legs not owned by another item), use the `Full` prefix — see [Full-Body Animations](#full-body-animations-naming-convention). For example, a straitjacket's `FullWalk` can animate legs for a waddle, but only if no ankle cuffs are equipped.
**The rule:** Your item always controls its own bones. It can also animate free bones if your GLB has keyframes for them. It can never override another item's bones. **The rule:** Standard animations = owned bones only. `Full` animations = owned + free bones. `FullHead` animations = owned + free + head. Your item can never override another item's bones.
### Idle is a Single-Frame Pose ### Animation Frames
`Idle` should be a **static pose** — one keyframe at frame 0. The mod loops it as a held position. **Frame 0 is the base pose** — the minimum every animation must have. The mod always has a valid pose to display from frame 0.
``` **Multi-frame animations** (loops, transitions) are supported by the GLB parser — all frames are parsed and stored. However, **multi-frame playback is not yet implemented** in the item animation converter (`GltfPoseConverter`). Currently only frame 0 is read at runtime. Multi-frame playback is a high-priority feature — see `docs/TODO.md`.
Frame 0: Pose all owned bones → done.
``` **What this means for artists now:** Design your animations with full multi-frame loops (struggle thrashing, walk cycles, breathing idles). Put the most representative pose at frame 0. When multi-frame playback ships, your animations will work immediately without re-exporting.
### Optional Animations ### Optional Animations
@@ -329,13 +329,13 @@ Beyond `Idle`, you can provide animations for specific contexts. All are optiona
| Animation Name | Context | Notes | | Animation Name | Context | Notes |
|----------------|---------|-------| |----------------|---------|-------|
| `Idle` | Standing still | **Required.** Single-frame pose. | | `Idle` | Standing still | **Required.** Single-frame or looped. Frame 0 = base pose. |
| `Struggle` | Player is struggling | Multi-frame loop. 20-40 frames recommended. | | `Struggle` | Player is struggling | Multi-frame loop recommended. 20-40 frames. |
| `Walk` | Player is walking | Multi-frame loop synced to walk speed. | | `Walk` | Player is walking | Multi-frame loop synced to walk speed. |
| `Sneak` | Player is sneaking | Single-frame or short loop. | | `Sneak` | Player is sneaking | Single-frame or short loop. |
| `SitIdle` | Sitting (chair, minecart) | Single-frame pose. | | `SitIdle` | Sitting (chair, minecart) | Single-frame or looped. |
| `SitStruggle` | Sitting + struggling | Multi-frame loop. | | `SitStruggle` | Sitting + struggling | Multi-frame loop. |
| `KneelIdle` | Kneeling | Single-frame pose. | | `KneelIdle` | Kneeling | Single-frame or looped. |
| `KneelStruggle` | Kneeling + struggling | Multi-frame loop. | | `KneelStruggle` | Kneeling + struggling | Multi-frame loop. |
| `Crawl` | Crawling (dog pose) | Multi-frame loop. | | `Crawl` | Crawling (dog pose) | Multi-frame loop. |
@@ -350,21 +350,27 @@ If an animation doesn't exist in your GLB, the mod looks for alternatives. At ea
``` ```
SIT + STRUGGLE: SIT + STRUGGLE:
FullSitStruggle → SitStruggle → FullStruggle → Struggle FullHeadSitStruggle → FullSitStruggle → SitStruggle
→ FullSit → Sit → FullStruggle → Struggle → FullIdle → Idle → FullHeadStruggle → FullStruggle → Struggle
→ FullHeadSit → FullSit → Sit
→ FullHeadIdle → FullIdle → Idle
KNEEL + STRUGGLE: KNEEL + STRUGGLE:
FullKneelStruggle → KneelStruggle → FullStruggle → Struggle FullHeadKneelStruggle → FullKneelStruggle → KneelStruggle
→ FullKneel → Kneel → FullStruggle → Struggle → FullIdle → Idle → FullHeadStruggle → FullStruggle → Struggle
→ FullHeadKneel → FullKneel → Kneel
→ FullHeadIdle → FullIdle → Idle
SIT + IDLE: FullSitIdle → SitIdle → FullSit → Sit → FullIdle → Idle SIT + IDLE: FullHeadSitIdle → FullSitIdle → SitIdle → ... → FullHeadIdle → FullIdle → Idle
KNEEL + IDLE: FullKneelIdle → KneelIdle → FullKneel → Kneel → FullIdle → Idle KNEEL + IDLE: FullHeadKneelIdle → FullKneelIdle → KneelIdle → ... → FullHeadIdle → FullIdle → Idle
SNEAK: FullSneak → Sneak → FullIdle → Idle SNEAK: FullHeadSneak → FullSneak → Sneak → FullHeadIdle → FullIdle → Idle
WALK: FullWalk → Walk → FullIdle → Idle WALK: FullHeadWalk → FullWalk → Walk → FullHeadIdle → FullIdle → Idle
STAND STRUGGLE: FullStruggle → Struggle → FullIdle → Idle STAND STRUGGLE: FullHeadStruggle → FullStruggle → Struggle → FullHeadIdle → FullIdle → Idle
STAND IDLE: FullIdle → Idle STAND IDLE: FullHeadIdle → FullIdle → Idle
``` ```
At each step, `FullHead` is tried first (full body + head), then `Full` (full body, head preserved), then standard (owned bones only).
In practice, most items only need `Idle`. Add `FullWalk` or `FullStruggle` when your item changes how the whole body moves. In practice, most items only need `Idle`. Add `FullWalk` or `FullStruggle` when your item changes how the whole body moves.
**Practical impact:** If you only provide `Idle`, your item works in every context. The player will hold the Idle pose while sitting, kneeling, sneaking, etc. It won't look perfect, but it will work. Add more animations over time to polish the experience. **Practical impact:** If you only provide `Idle`, your item works in every context. The player will hold the Idle pose while sitting, kneeling, sneaking, etc. It won't look perfect, but it will work. Add more animations over time to polish the experience.
@@ -394,18 +400,19 @@ Some items affect the entire body — not just their declared regions. A straitj
**Convention:** Prefix the animation name with `Full`. **Convention:** Prefix the animation name with `Full`.
| Standard Name | Full-Body Name | What Changes | | Standard Name | Full-Body Name | Full + Head | What Changes |
|--------------|---------------|-------------| |--------------|---------------|-------------|-------------|
| `Idle` | `FullIdle` | Owned bones + body lean, leg stance | | `Idle` | `FullIdle` | `FullHeadIdle` | Owned bones + body lean, leg stance (+ head if Head variant) |
| `Walk` | `FullWalk` | Owned bones + leg waddle, body sway | | `Walk` | `FullWalk` | `FullHeadWalk` | Owned bones + leg waddle, body sway (+ head if Head variant) |
| `Struggle` | `FullStruggle` | Owned bones + full-body thrashing | | `Struggle` | `FullStruggle` | `FullHeadStruggle` | Owned bones + full-body thrashing (+ head if Head variant) |
| `Sneak` | `FullSneak` | Owned bones + custom sneak posture | | `Sneak` | `FullSneak` | `FullHeadSneak` | Owned bones + custom sneak posture (+ head if Head variant) |
**In Blender:** **In Blender:**
``` ```
PlayerArmature|Idle ← region-only: just arms for handcuffs PlayerArmature|Idle ← region-only: just arms for handcuffs
PlayerArmature|FullWalk ← full-body: arms + legs waddle + body bob PlayerArmature|FullWalk ← full-body: arms + legs waddle + body bob
PlayerArmature|FullStruggle ← full-body: everything moves PlayerArmature|FullStruggle ← full-body: body + legs thrash (head free)
PlayerArmature|FullHeadStruggle ← full-body + head: everything moves including head
``` ```
**How the mod resolves this:** **How the mod resolves this:**
@@ -423,7 +430,9 @@ PlayerArmature|FullStruggle ← full-body: everything moves
| `Sneak` | Default sneak lean is fine | Your item changes how sneaking looks | | `Sneak` | Default sneak lean is fine | Your item changes how sneaking looks |
**Key points:** **Key points:**
- `Full` animations include keyframes for ALL bones you want to control (owned + free). - **Standard animations** (`Idle`, `Struggle`, `Walk`) only animate your item's **owned bones** (from `regions`). Any keyframes on other bones are ignored. This is safe — you can keyframe everything in Blender without worrying about side effects.
- **`Full` animations** (`FullIdle`, `FullStruggle`, `FullWalk`) additionally enable **free bones** (body, legs — bones not owned by any other equipped item). This is how you create waddle walks, full-body struggles, etc.
- **Head is protected by default.** In `Full` animations, the `head` bone is NOT enabled as a free bone — vanilla head tracking (mouse look) is preserved. To animate the head in a Full animation, add `Head` to the animation name: `FullHeadStruggle`, `FullHeadIdle`, etc. Items that own a head region (HEAD, EYES, EARS, MOUTH) always control head regardless of naming.
- Free bones in `Full` animations are only used when no other item owns them. - Free bones in `Full` animations are only used when no other item owns them.
- You can provide BOTH: `Idle` (region-only) and `FullWalk` (full-body). The mod picks the right one per context. - You can provide BOTH: `Idle` (region-only) and `FullWalk` (full-body). The mod picks the right one per context.
- `FullIdle` is rarely needed — most items only need a full-body version for movement animations. - `FullIdle` is rarely needed — most items only need a full-body version for movement animations.
@@ -630,7 +639,8 @@ In your JSON definition, separate the mesh from the animations:
- [ ] Actions are named `PlayerArmature|Idle`, `PlayerArmature|Struggle`, etc. - [ ] Actions are named `PlayerArmature|Idle`, `PlayerArmature|Struggle`, etc.
- [ ] Mesh is weight-painted to skeleton bones only - [ ] Mesh is weight-painted to skeleton bones only
- [ ] Weights are normalized - [ ] Weights are normalized
- [ ] No orphan bones (extra bones not in the standard 11 are ignored but add file size) - [ ] Custom bones (if any) are parented to a standard bone in the hierarchy
- [ ] Your item mesh is named `Item` in Blender (recommended — ensures the mod picks the correct mesh if your file has multiple objects)
- [ ] Materials/textures are applied (the GLB bakes them in) - [ ] Materials/textures are applied (the GLB bakes them in)
- [ ] Scale is correct (1 Blender unit = 1 Minecraft block = 16 pixels) - [ ] Scale is correct (1 Blender unit = 1 Minecraft block = 16 pixels)
@@ -648,9 +658,6 @@ Every item needs a JSON file that declares its gameplay properties. The mod scan
"display_name": "Rope Gag", "display_name": "Rope Gag",
"model": "mycreator:models/gltf/rope_gag.glb", "model": "mycreator:models/gltf/rope_gag.glb",
"regions": ["MOUTH"], "regions": ["MOUTH"],
"animation_bones": {
"idle": []
},
"pose_priority": 10, "pose_priority": 10,
"escape_difficulty": 2, "escape_difficulty": 2,
"lockable": false "lockable": false
@@ -759,18 +766,19 @@ The `movement_style` changes how the player physically moves — slower speed, d
| `supports_color` | bool | No | Whether this item has tintable zones. Default: `false` | | `supports_color` | bool | No | Whether this item has tintable zones. Default: `false` |
| `tint_channels` | object | No | Default colors per tintable zone: `{"tintable_1": "#FF0000"}` | | `tint_channels` | object | No | Default colors per tintable zone: `{"tintable_1": "#FF0000"}` |
| `icon` | string | No | Inventory sprite model (see [Inventory Icons](#inventory-icons) below) | | `icon` | string | No | Inventory sprite model (see [Inventory Icons](#inventory-icons) below) |
| `animations` | string/object | No | `"auto"` (default) or explicit name mapping |
| `movement_style` | string | No | Movement restriction: `"waddle"`, `"shuffle"`, `"hop"`, or `"crawl"` | | `movement_style` | string | No | Movement restriction: `"waddle"`, `"shuffle"`, `"hop"`, or `"crawl"` |
| `movement_modifier` | object | No | Override speed/jump for the movement style (requires `movement_style`) | | `movement_modifier` | object | No | Override speed/jump for the movement style (requires `movement_style`) |
| `creator` | string | No | Author/creator name, shown in the item tooltip | | `creator` | string | No | Author/creator name, shown in the item tooltip |
| `animation_bones` | object | Yes | Per-animation bone whitelist (see below) | | `animation_bones` | object | No | Per-animation bone whitelist (see below). If omitted, all owned bones are enabled for all animations. |
| `components` | object | No | Gameplay behavior components (see [Components](#components-gameplay-behaviors) below) | | `components` | object | No | Gameplay behavior components (see [Components](#components-gameplay-behaviors) below) |
### animation_bones (required) ### animation_bones (optional)
Declares which bones each named animation is allowed to control for this item. This enables fine-grained per-animation bone filtering: an item might own `body` via its regions but only want the "idle" animation to affect the arms. Fine-grained control over which bones each animation is allowed to affect. Most items don't need this — if omitted, all owned bones (from your `regions`) are enabled for all animations automatically.
**Format:** A JSON object where each key is an animation name (matching the GLB animation names) and each value is an array of bone names. **When to use it:** When your item owns bones via its regions but you only want specific animations to affect specific bones. For example, an item owning ARMS + TORSO might only want the "idle" pose to affect the arms, and only the "struggle" animation to also move the body.
**Format:** A JSON object where each key is an animation name and each value is an array of bone names.
**Valid bone names:** `head`, `body`, `rightArm`, `leftArm`, `rightLeg`, `leftLeg` **Valid bone names:** `head`, `body`, `rightArm`, `leftArm`, `rightLeg`, `leftLeg`
@@ -784,7 +792,7 @@ Declares which bones each named animation is allowed to control for this item. T
At runtime, the effective bones for a given animation clip are computed as the **intersection** of `animation_bones[clipName]` and the item's owned parts (from region conflict resolution). If the clip name is not listed in `animation_bones`, the item falls back to using all its owned parts. At runtime, the effective bones for a given animation clip are computed as the **intersection** of `animation_bones[clipName]` and the item's owned parts (from region conflict resolution). If the clip name is not listed in `animation_bones`, the item falls back to using all its owned parts.
This field is **required**. Items without `animation_bones` will be rejected by the parser. **If omitted entirely:** All owned bones are enabled for all animations. This is the correct default for most items — you only need `animation_bones` for advanced per-animation filtering.
### Components (Gameplay Behaviors) ### Components (Gameplay Behaviors)
@@ -823,9 +831,6 @@ Items without the `"components"` field work normally — components are entirely
"display_name": "GPS Shock Collar", "display_name": "GPS Shock Collar",
"model": "mycreator:models/gltf/gps_shock_collar.glb", "model": "mycreator:models/gltf/gps_shock_collar.glb",
"regions": ["NECK"], "regions": ["NECK"],
"animation_bones": {
"idle": []
},
"pose_priority": 10, "pose_priority": 10,
"escape_difficulty": 5, "escape_difficulty": 5,
"components": { "components": {
@@ -1014,14 +1019,36 @@ Use your own namespace (e.g., `mycreator`) to avoid conflicts with the base mod
--- ---
## Validation & Debugging
The mod includes built-in tools to help you catch issues with your GLB files.
### `/tiedup validate` Command
Run `/tiedup validate` in-game (client-side command) to see a diagnostic report for all loaded GLBs:
- **RED** errors — item won't work (missing GLB, invalid file, no skin)
- **YELLOW** warnings — item works but something looks wrong (bone typo, multiple meshes, no Idle animation)
- **GRAY** info — informational (custom bones detected, vertex count)
Filter by item: `/tiedup validate tiedup:leather_armbinder`
The validation runs automatically on every resource reload (F3+T). Check your game log for a summary line: `[GltfValidation] Validated N GLBs: X passed, Y with warnings, Z with errors`.
### Mesh Naming Convention
If your GLB contains multiple meshes, name your item mesh `Item` in Blender. The mod prioritizes a mesh named `Item` over other meshes. If no `Item` mesh is found, the last non-`Player` mesh is used (backward compatible, but may pick the wrong one in multi-mesh files).
---
## Common Mistakes ## Common Mistakes
### Skeleton Issues ### Skeleton Issues
| Mistake | Symptom | Fix | | Mistake | Symptom | Fix |
|---------|---------|-----| |---------|---------|-----|
| Bone name typo (`RightUpperArm` instead of `rightUpperArm`) | Mesh doesn't follow that bone | Names are **camelCase**, not PascalCase. Check exact spelling. | | Bone name typo (`RightUpperArm` instead of `rightUpperArm`) | WARN in log with suggestion: "did you mean 'rightUpperArm'?" — bone treated as custom | Names are **camelCase**, not PascalCase. Check exact spelling. Run `/tiedup validate` to see warnings. |
| Extra bones in the armature | No visible issue (ignored), larger file | Delete non-standard bones before export | | Extra bones in the armature | Custom bones follow their parent in rest pose | Intentional custom bones are fine (chains, decorations). Unintentional ones add file size — delete them. |
| Missing `PlayerArmature` root | Mesh renders at wrong position | Rename your armature root to `PlayerArmature` | | Missing `PlayerArmature` root | Mesh renders at wrong position | Rename your armature root to `PlayerArmature` |
| Animating `body` bone without TORSO region | Body keyframes used only if `body` is free (no other item owns it) | Declare TORSO/WAIST region if you always want to control body, or use `Full` animations for free-bone effects | | Animating `body` bone without TORSO region | Body keyframes used only if `body` is free (no other item owns it) | Declare TORSO/WAIST region if you always want to control body, or use `Full` animations for free-bone effects |
@@ -1029,11 +1056,11 @@ Use your own namespace (e.g., `mycreator`) to avoid conflicts with the base mod
| Mistake | Symptom | Fix | | Mistake | Symptom | Fix |
|---------|---------|-----| |---------|---------|-----|
| Action not prefixed with `PlayerArmature\|` | Animation not found, falls back to first clip | Rename: `Idle``PlayerArmature\|Idle` | | Action not prefixed with `PlayerArmature\|` | Animation not found, falls back to first clip | Rename: `Idle``PlayerArmature\|Idle`. Note: the mod strips any `ArmatureName\|` prefix, so custom armature names also work. |
| Wrong case (`idle` instead of `Idle`) | Animation not found | Use exact PascalCase: `Idle`, `SitIdle`, `KneelStruggle` | | Wrong case (`idle` instead of `Idle`) | Animation not found | Use exact PascalCase: `Idle`, `SitIdle`, `KneelStruggle` |
| Variant gap (`.1`, `.2`, `.4` — missing `.3`) | Only .1 and .2 are used | Number sequentially with no gaps | | Variant gap (`.1`, `.2`, `.4` — missing `.3`) | Only .1 and .2 are used | Number sequentially with no gaps |
| Animating bones outside your regions | Keyframes silently ignored | Only animate bones in your declared regions | | Animating bones outside your regions | Keyframes silently ignored | Only animate bones in your declared regions |
| Multi-frame Idle | Works but wastes resources | Idle should be a single keyframe at frame 0 | | Multi-frame animations play as static pose | Multi-frame playback not yet implemented — only frame 0 is used | Design full animations now (they'll work when playback ships). Ensure frame 0 is a good base pose. |
### Weight Painting Issues ### Weight Painting Issues
@@ -1041,7 +1068,7 @@ Use your own namespace (e.g., `mycreator`) to avoid conflicts with the base mod
|---------|---------|-----| |---------|---------|-----|
| Vertices not weighted to any bone | Part of mesh stays frozen in space | Weight paint everything to at least one bone | | Vertices not weighted to any bone | Part of mesh stays frozen in space | Weight paint everything to at least one bone |
| Weights not normalized | Mesh stretches or compresses oddly | Blender > Weights > Normalize All | | Weights not normalized | Mesh stretches or compresses oddly | Blender > Weights > Normalize All |
| Weighted to a non-standard bone | That part of mesh stays frozen | Only weight to the 11 standard bones | | Weighted to a non-standard bone | Mesh follows parent bone in rest pose | This is OK if intentional (custom bones). If not, re-weight to a standard bone. |
### JSON Issues ### JSON Issues
@@ -1073,9 +1100,6 @@ A collar sits on the neck. It doesn't change the player's pose.
"display_name": "Leather Collar", "display_name": "Leather Collar",
"model": "mycreator:models/gltf/leather_collar.glb", "model": "mycreator:models/gltf/leather_collar.glb",
"regions": ["NECK"], "regions": ["NECK"],
"animation_bones": {
"idle": []
},
"pose_priority": 5, "pose_priority": 5,
"escape_difficulty": 3, "escape_difficulty": 3,
"lockable": true "lockable": true
@@ -1548,11 +1572,16 @@ NEVER DO:
GOOD TO KNOW: GOOD TO KNOW:
→ Only Idle is required. Everything else has fallbacks. → Only Idle is required. Everything else has fallbacks.
→ animation_bones is optional. Omit it and all owned bones work for all animations.
→ Templates let you skip animation entirely. → Templates let you skip animation entirely.
Free bones (not owned by any item) CAN be animated by your GLB. Custom bones are supported — add chain/ribbon/twist bones parented to standard bones.
→ Free bones (body, legs) can be animated using Full-prefixed animations (FullWalk, FullStruggle).
→ Head is protected — use FullHead prefix (FullHeadStruggle) to also animate the head.
→ Bones owned by another equipped item are always ignored. → Bones owned by another equipped item are always ignored.
→ The mod handles sitting, sneaking, walking — you don't have to. → The mod handles sitting, sneaking, walking — you don't have to.
→ Context GLBs in tiedup_contexts/ replace default postures. → Context GLBs in tiedup_contexts/ replace default postures.
→ Name your item mesh "Item" in Blender for explicit selection in multi-mesh files.
→ Run /tiedup validate in-game to check your GLBs for issues.
→ Slim model is optional. Steve mesh works on Alex (minor clipping). → Slim model is optional. Steve mesh works on Alex (minor clipping).
→ Textures bake into the GLB. No separate file needed. → Textures bake into the GLB. No separate file needed.
``` ```

View File

@@ -72,34 +72,43 @@ public final class GlbAnimationResolver {
String prefix = context.getGlbContextPrefix(); // "Sit", "Kneel", "Sneak", "Walk", "" String prefix = context.getGlbContextPrefix(); // "Sit", "Kneel", "Sneak", "Walk", ""
String variant = context.getGlbVariant(); // "Idle" or "Struggle" String variant = context.getGlbVariant(); // "Idle" or "Struggle"
// 1. Exact match: "FullSitIdle" then "SitIdle" (with variants) // 1. Exact match: "FullHeadSitIdle" then "FullSitIdle" then "SitIdle" (with variants)
// FullHead variants opt-in to head animation (see GltfPoseConverter.enableSelectiveParts)
String exact = prefix + variant; String exact = prefix + variant;
if (!exact.isEmpty()) { if (!exact.isEmpty()) {
String picked = pickWithVariants(data, "Full" + exact); String picked = pickWithVariants(data, "FullHead" + exact);
if (picked != null) return picked;
picked = pickWithVariants(data, "Full" + exact);
if (picked != null) return picked; if (picked != null) return picked;
picked = pickWithVariants(data, exact); picked = pickWithVariants(data, exact);
if (picked != null) return picked; if (picked != null) return picked;
} }
// 2. For struggles: try "FullStruggle" then "Struggle" (with variants) // 2. For struggles: try "FullHeadStruggle" then "FullStruggle" then "Struggle" (with variants)
if (context.isStruggling()) { if (context.isStruggling()) {
String picked = pickWithVariants(data, "FullStruggle"); String picked = pickWithVariants(data, "FullHeadStruggle");
if (picked != null) return picked;
picked = pickWithVariants(data, "FullStruggle");
if (picked != null) return picked; if (picked != null) return picked;
picked = pickWithVariants(data, "Struggle"); picked = pickWithVariants(data, "Struggle");
if (picked != null) return picked; if (picked != null) return picked;
} }
// 3. Context-only: "FullSit" then "Sit" (with variants) // 3. Context-only: "FullHead{prefix}" then "Full{prefix}" then "{prefix}" (with variants)
if (!prefix.isEmpty()) { if (!prefix.isEmpty()) {
String picked = pickWithVariants(data, "Full" + prefix); String picked = pickWithVariants(data, "FullHead" + prefix);
if (picked != null) return picked;
picked = pickWithVariants(data, "Full" + prefix);
if (picked != null) return picked; if (picked != null) return picked;
picked = pickWithVariants(data, prefix); picked = pickWithVariants(data, prefix);
if (picked != null) return picked; if (picked != null) return picked;
} }
// 4. Variant-only: "FullIdle" then "Idle" (with variants) // 4. Variant-only: "FullHeadIdle" then "FullIdle" then "Idle" (with variants)
{ {
String picked = pickWithVariants(data, "Full" + variant); String picked = pickWithVariants(data, "FullHead" + variant);
if (picked != null) return picked;
picked = pickWithVariants(data, "Full" + variant);
if (picked != null) return picked; if (picked != null) return picked;
picked = pickWithVariants(data, variant); picked = pickWithVariants(data, variant);
if (picked != null) return picked; if (picked != null) return picked;

View File

@@ -103,29 +103,37 @@ public final class GlbParser {
JsonObject skin = skins.get(0).getAsJsonObject(); JsonObject skin = skins.get(0).getAsJsonObject();
JsonArray skinJoints = skin.getAsJsonArray("joints"); JsonArray skinJoints = skin.getAsJsonArray("joints");
// Filter skin joints to only include known deforming bones // Accept all skin joints (no filtering — custom bones are supported)
List<Integer> filteredJointNodes = new ArrayList<>(); List<Integer> allJointNodes = new ArrayList<>();
int[] skinJointRemap = new int[skinJoints.size()]; // old skin index -> new filtered index
java.util.Arrays.fill(skinJointRemap, -1);
for (int j = 0; j < skinJoints.size(); j++) { for (int j = 0; j < skinJoints.size(); j++) {
int nodeIdx = skinJoints.get(j).getAsInt(); int nodeIdx = skinJoints.get(j).getAsInt();
JsonObject node = nodes.get(nodeIdx).getAsJsonObject(); JsonObject node = nodes.get(nodeIdx).getAsJsonObject();
String name = node.has("name") String name = node.has("name")
? node.get("name").getAsString() ? node.get("name").getAsString()
: "joint_" + j; : "joint_" + j;
if (GltfBoneMapper.isKnownBone(name)) { // Strip armature prefix (e.g., "MyRig|body" -> "body")
skinJointRemap[j] = filteredJointNodes.size(); if (name.contains("|")) {
filteredJointNodes.add(nodeIdx); name = name.substring(name.lastIndexOf('|') + 1);
} else {
LOGGER.debug(
"[GltfPipeline] Skipping non-deforming bone: '{}' (node {})",
name,
nodeIdx
);
} }
// Log info for non-MC bones
if (!GltfBoneMapper.isKnownBone(name)) {
String suggestion = GltfBoneMapper.suggestBoneName(name);
if (suggestion != null) {
LOGGER.warn(
"[GltfPipeline] Unknown bone '{}' in {} — did you mean '{}'? (treated as custom bone)",
name, debugName, suggestion
);
} else {
LOGGER.info(
"[GltfPipeline] Custom bone '{}' in {} (will follow parent hierarchy in rest pose)",
name, debugName
);
}
}
allJointNodes.add(nodeIdx);
} }
int jointCount = filteredJointNodes.size(); int jointCount = allJointNodes.size();
String[] jointNames = new String[jointCount]; String[] jointNames = new String[jointCount];
int[] parentJointIndices = new int[jointCount]; int[] parentJointIndices = new int[jointCount];
Quaternionf[] restRotations = new Quaternionf[jointCount]; Quaternionf[] restRotations = new Quaternionf[jointCount];
@@ -135,19 +143,23 @@ public final class GlbParser {
int[] nodeToJoint = new int[nodes.size()]; int[] nodeToJoint = new int[nodes.size()];
java.util.Arrays.fill(nodeToJoint, -1); java.util.Arrays.fill(nodeToJoint, -1);
for (int j = 0; j < jointCount; j++) { for (int j = 0; j < jointCount; j++) {
int nodeIdx = filteredJointNodes.get(j); int nodeIdx = allJointNodes.get(j);
nodeToJoint[nodeIdx] = j; nodeToJoint[nodeIdx] = j;
} }
// Read joint names, rest pose, and build parent mapping // Read joint names, rest pose, and build parent mapping
java.util.Arrays.fill(parentJointIndices, -1); java.util.Arrays.fill(parentJointIndices, -1);
for (int j = 0; j < jointCount; j++) { for (int j = 0; j < jointCount; j++) {
int nodeIdx = filteredJointNodes.get(j); int nodeIdx = allJointNodes.get(j);
JsonObject node = nodes.get(nodeIdx).getAsJsonObject(); JsonObject node = nodes.get(nodeIdx).getAsJsonObject();
jointNames[j] = node.has("name") String rawName = node.has("name")
? node.get("name").getAsString() ? node.get("name").getAsString()
: "joint_" + j; : "joint_" + j;
// Strip armature prefix consistently
jointNames[j] = rawName.contains("|")
? rawName.substring(rawName.lastIndexOf('|') + 1)
: rawName;
// Rest rotation // Rest rotation
if (node.has("rotation")) { if (node.has("rotation")) {
@@ -192,7 +204,6 @@ public final class GlbParser {
} }
// -- Inverse Bind Matrices -- // -- Inverse Bind Matrices --
// IBM accessor is indexed by original skin joint order, so we pick the filtered entries
Matrix4f[] inverseBindMatrices = new Matrix4f[jointCount]; Matrix4f[] inverseBindMatrices = new Matrix4f[jointCount];
if (skin.has("inverseBindMatrices")) { if (skin.has("inverseBindMatrices")) {
int ibmAccessor = skin.get("inverseBindMatrices").getAsInt(); int ibmAccessor = skin.get("inverseBindMatrices").getAsInt();
@@ -202,12 +213,9 @@ public final class GlbParser {
binData, binData,
ibmAccessor ibmAccessor
); );
for (int origJ = 0; origJ < skinJoints.size(); origJ++) { for (int j = 0; j < jointCount; j++) {
int newJ = skinJointRemap[origJ]; inverseBindMatrices[j] = new Matrix4f();
if (newJ >= 0) { inverseBindMatrices[j].set(ibmData, j * 16);
inverseBindMatrices[newJ] = new Matrix4f();
inverseBindMatrices[newJ].set(ibmData, origJ * 16);
}
} }
} else { } else {
for (int j = 0; j < jointCount; j++) { for (int j = 0; j < jointCount; j++) {
@@ -215,20 +223,36 @@ public final class GlbParser {
} }
} }
// -- Find mesh (ignore "Player" mesh, take LAST non-Player) -- // -- Find mesh by convention, then fallback --
// WORKAROUND: Takes the LAST non-Player mesh because modelers may leave prototype meshes // Priority: 1) mesh named "Item", 2) last non-Player mesh
// in the .glb. Revert to first non-Player mesh once modeler workflow is standardized.
int targetMeshIdx = -1; int targetMeshIdx = -1;
String selectedMeshName = null;
int nonPlayerCount = 0;
if (meshes != null) { if (meshes != null) {
for (int mi = 0; mi < meshes.size(); mi++) { for (int mi = 0; mi < meshes.size(); mi++) {
JsonObject mesh = meshes.get(mi).getAsJsonObject(); JsonObject mesh = meshes.get(mi).getAsJsonObject();
String meshName = mesh.has("name") String meshName = mesh.has("name")
? mesh.get("name").getAsString() ? mesh.get("name").getAsString()
: ""; : "";
if ("Item".equals(meshName)) {
targetMeshIdx = mi;
selectedMeshName = meshName;
break; // Convention match — use it
}
if (!"Player".equals(meshName)) { if (!"Player".equals(meshName)) {
targetMeshIdx = mi; targetMeshIdx = mi;
selectedMeshName = meshName;
nonPlayerCount++;
} }
} }
if (nonPlayerCount > 1 && !"Item".equals(selectedMeshName)) {
LOGGER.warn(
"[GltfPipeline] {} non-Player meshes found in {} — using '{}'. "
+ "Name your mesh 'Item' for explicit selection.",
nonPlayerCount, debugName,
selectedMeshName != null ? selectedMeshName : "(unnamed)"
);
}
} }
// -- Parse root material names (for tint channel detection) -- // -- Parse root material names (for tint channel detection) --
@@ -320,15 +344,10 @@ public final class GlbParser {
binData, binData,
attributes.get("JOINTS_0").getAsInt() attributes.get("JOINTS_0").getAsInt()
); );
// Remap vertex joint indices from original skin order to filtered order // No remap needed — all joints are kept, indices match directly.
// Guard against out-of-range joint indices.
for (int i = 0; i < primJoints.length; i++) { for (int i = 0; i < primJoints.length; i++) {
int origIdx = primJoints[i]; if (primJoints[i] < 0 || primJoints[i] >= jointCount) {
if (origIdx >= 0 && origIdx < skinJointRemap.length) {
primJoints[i] =
skinJointRemap[origIdx] >= 0
? skinJointRemap[origIdx]
: 0;
} else {
primJoints[i] = 0; primJoints[i] = 0;
} }
} }

View File

@@ -7,6 +7,7 @@ import com.tiedup.remake.client.animation.context.GlbAnimationResolver;
import com.tiedup.remake.client.animation.context.RegionBoneMapper; import com.tiedup.remake.client.animation.context.RegionBoneMapper;
import dev.kosmx.playerAnim.core.data.KeyframeAnimation; import dev.kosmx.playerAnim.core.data.KeyframeAnimation;
import java.util.HashSet; import java.util.HashSet;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@@ -126,11 +127,13 @@ public final class GltfAnimationApplier {
String enabledKey = canonicalPartsKey(ownership.enabledParts()); String enabledKey = canonicalPartsKey(ownership.enabledParts());
String partsKey = ownedKey + ";" + enabledKey; String partsKey = ownedKey + ";" + enabledKey;
// Build composite state key to avoid redundant updates // Build composite state key to detect context changes.
// NOTE: This key does NOT include the variant name — that is resolved fresh
// each time the context changes, enabling random variant selection.
String stateKey = animSource + "|" + context.name() + "|" + partsKey; String stateKey = animSource + "|" + context.name() + "|" + partsKey;
String currentKey = activeStateKeys.get(entity.getUUID()); String currentKey = activeStateKeys.get(entity.getUUID());
if (stateKey.equals(currentKey)) { if (stateKey.equals(currentKey)) {
return true; // Already active, no-op return true; // Same context, same parts — no need to re-resolve
} }
// === Layer 1: Context animation (base body posture) === // === Layer 1: Context animation (base body posture) ===
@@ -153,26 +156,36 @@ public final class GltfAnimationApplier {
return false; return false;
} }
KeyframeAnimation itemAnim = itemAnimCache.get(itemCacheKey); // Resolve animation data first (needed for variant resolution)
GltfData animData = GlbAnimationResolver.resolveAnimationData(
modelLoc,
animationSource
);
if (animData == null) {
LOGGER.warn(
"[GltfPipeline] Failed to load animation GLB: {}",
animSource
);
failedLoadKeys.add(itemCacheKey);
activeStateKeys.put(entity.getUUID(), stateKey);
return false;
}
// Resolve which named animation to use (with fallback chain + variant selection).
// This must happen BEFORE the cache lookup because variant selection is random —
// we want a fresh random pick each time the context changes, not a permanently
// cached first pick.
String glbAnimName = GlbAnimationResolver.resolve(
animData,
context
);
// Include the resolved animation name in the cache key so different variants
// (Struggle.1 vs Struggle.2) get separate cache entries.
String variantCacheKey = itemCacheKey + "#" + (glbAnimName != null ? glbAnimName : "default");
KeyframeAnimation itemAnim = itemAnimCache.get(variantCacheKey);
if (itemAnim == null) { if (itemAnim == null) {
GltfData animData = GlbAnimationResolver.resolveAnimationData(
modelLoc,
animationSource
);
if (animData == null) {
LOGGER.warn(
"[GltfPipeline] Failed to load animation GLB: {}",
animSource
);
failedLoadKeys.add(itemCacheKey);
activeStateKeys.put(entity.getUUID(), stateKey);
return false;
}
// Resolve which named animation to use (with fallback chain + variant selection)
String glbAnimName = GlbAnimationResolver.resolve(
animData,
context
);
// Pass both owned parts and enabled parts (owned + free) for selective enabling // Pass both owned parts and enabled parts (owned + free) for selective enabling
itemAnim = GltfPoseConverter.convertSelective( itemAnim = GltfPoseConverter.convertSelective(
animData, animData,
@@ -180,7 +193,7 @@ public final class GltfAnimationApplier {
ownership.thisParts(), ownership.thisParts(),
ownership.enabledParts() ownership.enabledParts()
); );
itemAnimCache.put(itemCacheKey, itemAnim); itemAnimCache.put(variantCacheKey, itemAnim);
} }
BondageAnimationManager.playDirect(entity, itemAnim); BondageAnimationManager.playDirect(entity, itemAnim);
@@ -239,7 +252,40 @@ public final class GltfAnimationApplier {
} }
// === Layer 2: Composite item animation === // === Layer 2: Composite item animation ===
String compositeCacheKey = "multi#" + stateKey; // Pre-resolve animation data and variant names for all items BEFORE cache lookup.
// This ensures random variant selection happens fresh on each context change,
// and each variant combination gets its own cache entry.
record ResolvedItem(
GltfData animData,
String glbAnimName,
RegionBoneMapper.V2ItemAnimInfo info
) {}
List<ResolvedItem> resolvedItems = new ArrayList<>();
StringBuilder variantKeyBuilder = new StringBuilder("multi#").append(stateKey);
for (RegionBoneMapper.V2ItemAnimInfo item : items) {
ResourceLocation animSource =
item.animSource() != null ? item.animSource() : item.modelLoc();
GltfData animData = GlbAnimationResolver.resolveAnimationData(
item.modelLoc(), item.animSource()
);
if (animData == null) {
LOGGER.warn(
"[GltfPipeline] Failed to load GLB for multi-item: {}",
animSource
);
continue;
}
String glbAnimName = GlbAnimationResolver.resolve(animData, context);
resolvedItems.add(new ResolvedItem(animData, glbAnimName, item));
variantKeyBuilder.append('#')
.append(glbAnimName != null ? glbAnimName : "default");
}
String compositeCacheKey = variantKeyBuilder.toString();
if (failedLoadKeys.contains(compositeCacheKey)) { if (failedLoadKeys.contains(compositeCacheKey)) {
activeStateKeys.put(entity.getUUID(), stateKey); activeStateKeys.put(entity.getUUID(), stateKey);
@@ -261,29 +307,13 @@ public final class GltfAnimationApplier {
boolean anyLoaded = false; boolean anyLoaded = false;
for (int i = 0; i < items.size(); i++) { for (ResolvedItem resolved : resolvedItems) {
RegionBoneMapper.V2ItemAnimInfo item = items.get(i); RegionBoneMapper.V2ItemAnimInfo item = resolved.info();
GltfData animData = resolved.animData();
String glbAnimName = resolved.glbAnimName();
ResourceLocation animSource = ResourceLocation animSource =
item.animSource() != null item.animSource() != null ? item.animSource() : item.modelLoc();
? item.animSource()
: item.modelLoc();
GltfData animData = GlbAnimationResolver.resolveAnimationData(
item.modelLoc(),
item.animSource()
);
if (animData == null) {
LOGGER.warn(
"[GltfPipeline] Failed to load GLB for multi-item: {}",
animSource
);
continue;
}
String glbAnimName = GlbAnimationResolver.resolve(
animData,
context
);
GltfData.AnimationClip rawClip; GltfData.AnimationClip rawClip;
if (glbAnimName != null) { if (glbAnimName != null) {
rawClip = animData.getRawAnimation(glbAnimName); rawClip = animData.getRawAnimation(glbAnimName);
@@ -298,9 +328,7 @@ public final class GltfAnimationApplier {
// if the item declares per-animation bone filtering. // if the item declares per-animation bone filtering.
Set<String> effectiveParts = item.ownedParts(); Set<String> effectiveParts = item.ownedParts();
if (glbAnimName != null && !item.animationBones().isEmpty()) { if (glbAnimName != null && !item.animationBones().isEmpty()) {
Set<String> override = item Set<String> override = item.animationBones().get(glbAnimName);
.animationBones()
.get(glbAnimName);
if (override != null) { if (override != null) {
Set<String> filtered = new HashSet<>(override); Set<String> filtered = new HashSet<>(override);
filtered.retainAll(item.ownedParts()); filtered.retainAll(item.ownedParts());
@@ -311,19 +339,13 @@ public final class GltfAnimationApplier {
} }
GltfPoseConverter.addBonesToBuilder( GltfPoseConverter.addBonesToBuilder(
builder, builder, animData, rawClip, effectiveParts
animData,
rawClip,
effectiveParts
); );
anyLoaded = true; anyLoaded = true;
LOGGER.debug( LOGGER.debug(
"[GltfPipeline] Multi-item: {} -> owned={}, effective={}, anim={}", "[GltfPipeline] Multi-item: {} -> owned={}, effective={}, anim={}",
animSource, animSource, item.ownedParts(), effectiveParts, glbAnimName
item.ownedParts(),
effectiveParts,
glbAnimName
); );
} }

View File

@@ -7,6 +7,7 @@ import net.minecraft.client.model.HumanoidModel;
import net.minecraft.client.model.geom.ModelPart; import net.minecraft.client.model.geom.ModelPart;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import org.jetbrains.annotations.Nullable;
/** /**
* Maps glTF bone names to Minecraft HumanoidModel parts. * Maps glTF bone names to Minecraft HumanoidModel parts.
@@ -110,4 +111,25 @@ public final class GltfBoneMapper {
public static boolean isKnownBone(String boneName) { public static boolean isKnownBone(String boneName) {
return BONE_TO_PART.containsKey(boneName); return BONE_TO_PART.containsKey(boneName);
} }
/**
* Get all known bone names for validation/suggestion purposes.
*/
public static Set<String> knownBoneNames() {
return BONE_TO_PART.keySet();
}
/**
* Suggest a known bone name for a case-insensitive match.
* Returns null if no case-insensitive match is found.
*/
@Nullable
public static String suggestBoneName(String unknownBone) {
for (String known : BONE_TO_PART.keySet()) {
if (known.equalsIgnoreCase(unknownBone)) {
return known;
}
}
return null;
}
} }

View File

@@ -96,6 +96,7 @@ public final class GltfClientSetup {
ProfilerFiller profiler ProfilerFiller profiler
) { ) {
GltfCache.clearCache(); GltfCache.clearCache();
GltfSkinCache.clearAll();
GltfAnimationApplier.invalidateCache(); GltfAnimationApplier.invalidateCache();
GltfMeshRenderer.clearRenderTypeCache(); GltfMeshRenderer.clearRenderTypeCache();
// Reload context GLB animations from resource packs FIRST, // Reload context GLB animations from resource packs FIRST,
@@ -117,7 +118,43 @@ public final class GltfClientSetup {
LOGGER.info( LOGGER.info(
"[GltfPipeline] Data-driven item reload listener registered" "[GltfPipeline] Data-driven item reload listener registered"
); );
// GLB structural validation (runs after item definitions are loaded)
event.registerReloadListener(new com.tiedup.remake.client.gltf.diagnostic.GlbValidationReloadListener());
LOGGER.info("[GltfPipeline] GLB validation reload listener registered");
} }
} }
/**
* FORGE bus event subscribers for entity lifecycle cleanup.
* Removes skin cache entries when entities leave the level, preventing memory leaks.
*/
@Mod.EventBusSubscriber(
modid = "tiedup",
bus = Mod.EventBusSubscriber.Bus.FORGE,
value = Dist.CLIENT
)
public static class ForgeBusEvents {
@SubscribeEvent
public static void onEntityLeaveLevel(
net.minecraftforge.event.entity.EntityLeaveLevelEvent event
) {
if (event.getLevel().isClientSide()) {
GltfSkinCache.removeEntity(event.getEntity().getId());
}
}
@SubscribeEvent
public static void onRegisterClientCommands(
net.minecraftforge.client.event.RegisterClientCommandsEvent event
) {
com.tiedup.remake.commands.ValidateGlbCommand.register(
event.getDispatcher()
);
LOGGER.info(
"[GltfPipeline] Client command /tiedup validate registered"
);
}
}
} }

View File

@@ -225,6 +225,101 @@ public final class GltfMeshRenderer extends RenderStateShard {
} }
} }
/**
* Two-pass skinned renderer with cache support.
*
* <p><b>Pass 1</b> (skippable): if {@code cachedPositions} is null, skin every
* unique vertex into flat {@code float[]} arrays (positions and normals).
* If cached arrays are provided, Pass 1 is skipped entirely.</p>
*
* <p><b>Pass 2</b> (always): iterate the index buffer, read skinned data from
* the arrays, and emit to the {@link VertexConsumer}.</p>
*
* @param data parsed glTF data
* @param jointMatrices computed joint matrices from skinning engine
* @param poseStack current pose stack
* @param buffer multi-buffer source
* @param packedLight packed light value
* @param packedOverlay packed overlay value
* @param renderType the RenderType to use for rendering
* @param cachedPositions previously cached skinned positions, or null to compute fresh
* @param cachedNormals previously cached skinned normals, or null to compute fresh
* @return {@code new float[][] { positions, normals }} for the caller to cache
*/
public static float[][] renderSkinnedWithCache(
GltfData data,
Matrix4f[] jointMatrices,
PoseStack poseStack,
MultiBufferSource buffer,
int packedLight,
int packedOverlay,
RenderType renderType,
float[] cachedPositions,
float[] cachedNormals
) {
int vertexCount = data.vertexCount();
float[] positions;
float[] normals;
// -- Pass 1: Skin all unique vertices (skipped when cache hit) --
if (cachedPositions != null && cachedNormals != null) {
positions = cachedPositions;
normals = cachedNormals;
} else {
positions = new float[vertexCount * 3];
normals = new float[vertexCount * 3];
float[] outPos = new float[3];
float[] outNormal = new float[3];
Vector4f tmpPos = new Vector4f();
Vector4f tmpNorm = new Vector4f();
for (int v = 0; v < vertexCount; v++) {
GltfSkinningEngine.skinVertex(
data, v, jointMatrices, outPos, outNormal, tmpPos, tmpNorm
);
positions[v * 3] = outPos[0];
positions[v * 3 + 1] = outPos[1];
positions[v * 3 + 2] = outPos[2];
normals[v * 3] = outNormal[0];
normals[v * 3 + 1] = outNormal[1];
normals[v * 3 + 2] = outNormal[2];
}
}
// -- Pass 2: Emit vertices from arrays to VertexConsumer --
Matrix4f pose = poseStack.last().pose();
Matrix3f normalMat = poseStack.last().normal();
VertexConsumer vc = buffer.getBuffer(renderType);
int[] indices = data.indices();
float[] texCoords = data.texCoords();
for (int idx : indices) {
float px = positions[idx * 3];
float py = positions[idx * 3 + 1];
float pz = positions[idx * 3 + 2];
float nx = normals[idx * 3];
float ny = normals[idx * 3 + 1];
float nz = normals[idx * 3 + 2];
float u = texCoords[idx * 2];
float v = texCoords[idx * 2 + 1];
vc
.vertex(pose, px, py, pz)
.color(255, 255, 255, 255)
.uv(u, 1.0f - v)
.overlayCoords(packedOverlay)
.uv2(packedLight)
.normal(normalMat, nx, ny, nz)
.endVertex();
}
return new float[][] { positions, normals };
}
/** /**
* Render a skinned glTF mesh with per-primitive tint colors. * Render a skinned glTF mesh with per-primitive tint colors.
* *

View File

@@ -208,12 +208,14 @@ public final class GltfPoseConverter {
} }
} }
// Selective: enable owned parts always, free parts only if they have keyframes // Selective: enable owned parts always, free parts only for "Full" animations
// that explicitly opt into full-body control.
enableSelectiveParts( enableSelectiveParts(
builder, builder,
ownedParts, ownedParts,
enabledParts, enabledParts,
partsWithKeyframes partsWithKeyframes,
animName
); );
KeyframeAnimation anim = builder.build(); KeyframeAnimation anim = builder.build();
@@ -554,22 +556,42 @@ public final class GltfPoseConverter {
* *
* <ul> * <ul>
* <li>Owned parts: always enabled (the item controls these bones)</li> * <li>Owned parts: always enabled (the item controls these bones)</li>
* <li>Free parts WITH keyframes: enabled (the GLB has animation data for them)</li> * <li>Free parts WITH keyframes AND "Full" animation: enabled (explicit opt-in to full-body)</li>
* <li>Free parts WITHOUT keyframes: disabled (no data to animate, pass through to context)</li> * <li>Free parts without "Full" prefix: disabled (prevents accidental bone hijacking)</li>
* <li>Other items' parts: disabled (pass through to their own layer)</li> * <li>Other items' parts: disabled (pass through to their own layer)</li>
* </ul> * </ul>
* *
* <p>The "Full" prefix convention (FullIdle, FullStruggle, FullWalk) is the artist's
* explicit declaration that this animation is designed to control the entire body,
* not just the item's owned regions. Without this prefix, free bones are never enabled,
* even if the GLB contains keyframes for them. This prevents accidental bone hijacking
* when an artist keyframes all bones in Blender by default.</p>
*
* @param builder the animation builder with keyframes already added * @param builder the animation builder with keyframes already added
* @param ownedParts parts the item explicitly owns (always enabled) * @param ownedParts parts the item explicitly owns (always enabled)
* @param enabledParts parts the item may animate (owned + free) * @param enabledParts parts the item may animate (owned + free)
* @param partsWithKeyframes parts that received actual animation data from the GLB * @param partsWithKeyframes parts that received actual animation data from the GLB
* @param animName resolved animation name (checked for "Full" prefix)
*/ */
private static void enableSelectiveParts( private static void enableSelectiveParts(
KeyframeAnimation.AnimationBuilder builder, KeyframeAnimation.AnimationBuilder builder,
Set<String> ownedParts, Set<String> ownedParts,
Set<String> enabledParts, Set<String> enabledParts,
Set<String> partsWithKeyframes Set<String> partsWithKeyframes,
String animName
) { ) {
// Free bones are only enabled for "Full" animations (FullIdle, FullStruggle, etc.)
// The "gltf_" prefix is added by convertClipSelective, so check for "gltf_Full"
boolean isFullBodyAnimation = animName != null &&
animName.startsWith("gltf_Full");
// Head is protected by default — only enabled as a free bone when the animation
// name contains "Head" (e.g., FullHeadStruggle, FullHeadIdle).
// This lets artists opt-in per animation without affecting the item's regions.
// FullHead prefix (e.g., FullHeadStruggle) opts into head as a free bone.
// Use startsWith to avoid false positives (e.g., FullOverhead, FullAhead).
boolean allowFreeHead = isFullBodyAnimation &&
animName.startsWith("gltf_FullHead");
String[] allParts = { String[] allParts = {
"head", "head",
"body", "body",
@@ -588,13 +610,20 @@ public final class GltfPoseConverter {
// Always enable owned parts — the item controls these bones // Always enable owned parts — the item controls these bones
part.fullyEnablePart(false); part.fullyEnablePart(false);
} else if ( } else if (
isFullBodyAnimation &&
enabledParts.contains(partName) && enabledParts.contains(partName) &&
partsWithKeyframes.contains(partName) partsWithKeyframes.contains(partName) &&
(!"head".equals(partName) || allowFreeHead)
) { ) {
// Free part WITH keyframes: enable so the GLB animation drives it // Full-body animation: free part WITH keyframes enable.
// The "Full" prefix is the artist's explicit opt-in to animate
// bones outside their declared regions.
// Head is protected by default (preserves vanilla head tracking).
// Use "Head" in the animation name (e.g., FullHeadStruggle) to
// explicitly opt-in to head control for that animation.
part.fullyEnablePart(false); part.fullyEnablePart(false);
} else { } else {
// Other item's part, or free part without keyframes: disable. // Non-Full animation, other item's part, or free part without keyframes.
// Disabled parts pass through to the lower-priority context layer. // Disabled parts pass through to the lower-priority context layer.
part.setEnabled(false); part.setEnabled(false);
} }

View File

@@ -0,0 +1,121 @@
package com.tiedup.remake.client.gltf;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
/**
* Skinning result cache that avoids re-skinning when a player's pose hasn't changed.
*
* <p>Uses a dirty-flag approach: each cache entry stores the raw int bits of
* every float input (joint euler angles) that drove the last skinning pass.
* On the next frame, if all bits match exactly, the cached skinned positions
* and normals are reused (skipping the expensive LBS loop).
*
* <p>Bit comparison via {@link Float#floatToRawIntBits(float)} avoids epsilon
* drift: a pose is "unchanged" only when the inputs are identical down to the
* bit (idle, AFK, paused animation frame).
*/
@OnlyIn(Dist.CLIENT)
public final class GltfSkinCache {
private record CacheKey(int entityId, ResourceLocation modelLoc) {}
private static final class Entry {
int[] lastInputBits;
float[] skinnedPositions;
float[] skinnedNormals;
}
private static final Map<CacheKey, Entry> cache = new HashMap<>();
private GltfSkinCache() {}
/**
* Check whether the pose inputs are bit-identical to the last cached skinning pass.
*
* @param entityId the entity's numeric ID
* @param modelLoc the model ResourceLocation (distinguishes multiple items on one entity)
* @param currentInputs flat array of float inputs that drove joint matrix computation
* @return true if every input bit matches the cached entry (safe to reuse cached data)
*/
public static boolean isPoseUnchanged(
int entityId,
ResourceLocation modelLoc,
float[] currentInputs
) {
CacheKey key = new CacheKey(entityId, modelLoc);
Entry entry = cache.get(key);
if (entry == null || entry.lastInputBits == null) return false;
if (entry.lastInputBits.length != currentInputs.length) return false;
for (int i = 0; i < currentInputs.length; i++) {
if (
entry.lastInputBits[i]
!= Float.floatToRawIntBits(currentInputs[i])
) {
return false;
}
}
return true;
}
/**
* Store a skinning result in the cache, replacing any previous entry for the same key.
*
* @param entityId the entity's numeric ID
* @param modelLoc the model ResourceLocation
* @param poseInputs the float inputs that produced these results (will be bit-snapshotted)
* @param positions skinned vertex positions (will be cloned)
* @param normals skinned vertex normals (will be cloned)
*/
public static void store(
int entityId,
ResourceLocation modelLoc,
float[] poseInputs,
float[] positions,
float[] normals
) {
CacheKey key = new CacheKey(entityId, modelLoc);
Entry entry = cache.computeIfAbsent(key, k -> new Entry());
entry.lastInputBits = new int[poseInputs.length];
for (int i = 0; i < poseInputs.length; i++) {
entry.lastInputBits[i] = Float.floatToRawIntBits(poseInputs[i]);
}
entry.skinnedPositions = positions.clone();
entry.skinnedNormals = normals.clone();
}
/**
* Retrieve cached skinned positions, or null if no cache entry exists.
*/
public static float[] getCachedPositions(
int entityId,
ResourceLocation modelLoc
) {
Entry entry = cache.get(new CacheKey(entityId, modelLoc));
return entry != null ? entry.skinnedPositions : null;
}
/**
* Retrieve cached skinned normals, or null if no cache entry exists.
*/
public static float[] getCachedNormals(
int entityId,
ResourceLocation modelLoc
) {
Entry entry = cache.get(new CacheKey(entityId, modelLoc));
return entry != null ? entry.skinnedNormals : null;
}
/** Clear the entire cache (called on resource reload). */
public static void clearAll() {
cache.clear();
}
/** Remove all cache entries for a specific entity (called on entity leave). */
public static void removeEntity(int entityId) {
cache.entrySet().removeIf(e -> e.getKey().entityId == entityId);
}
}

View File

@@ -0,0 +1,20 @@
package com.tiedup.remake.client.gltf.diagnostic;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.jetbrains.annotations.Nullable;
/**
* A single diagnostic finding from GLB validation.
*/
@OnlyIn(Dist.CLIENT)
public record GlbDiagnostic(
ResourceLocation source,
@Nullable ResourceLocation itemDef,
Severity severity,
String code,
String message
) {
public enum Severity { ERROR, WARNING, INFO }
}

View File

@@ -0,0 +1,49 @@
package com.tiedup.remake.client.gltf.diagnostic;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
/**
* Static client-side registry of GLB validation results.
* Populated during resource reload, queried by /tiedup validate command.
*/
@OnlyIn(Dist.CLIENT)
public final class GlbDiagnosticRegistry {
private static final Map<ResourceLocation, GlbValidationResult> results =
new LinkedHashMap<>();
private GlbDiagnosticRegistry() {}
public static void clear() {
results.clear();
}
public static void addResult(GlbValidationResult result) {
results.put(result.source(), result);
}
public static Collection<GlbValidationResult> getAll() {
return Collections.unmodifiableCollection(results.values());
}
public static List<GlbValidationResult> getErrors() {
return results.values().stream()
.filter(r -> !r.passed())
.toList();
}
public static GlbValidationResult get(ResourceLocation source) {
return results.get(source);
}
public static int size() {
return results.size();
}
}

View File

@@ -0,0 +1,156 @@
package com.tiedup.remake.client.gltf.diagnostic;
import com.tiedup.remake.v2.bondage.datadriven.DataDrivenItemDefinition;
import com.tiedup.remake.v2.bondage.datadriven.DataDrivenItemRegistry;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.toasts.SystemToast;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.SimplePreparableReloadListener;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Reload listener that validates all data-driven item GLB models on resource
* reload (F3+T or startup).
*
* <p>Must be registered AFTER {@link com.tiedup.remake.v2.bondage.datadriven.DataDrivenItemReloadListener}
* so that the item registry is populated before validation runs.</p>
*
* <p>On each reload:
* <ol>
* <li>Clears the {@link GlbDiagnosticRegistry}</li>
* <li>Iterates all {@link DataDrivenItemDefinition}s</li>
* <li>For each definition with a model location, attempts to open the GLB
* resource and runs {@link GlbValidator#validate} on it</li>
* <li>Records results into the diagnostic registry and logs a summary</li>
* </ol>
*/
@OnlyIn(Dist.CLIENT)
public class GlbValidationReloadListener
extends SimplePreparableReloadListener<Void>
{
private static final Logger LOGGER = LogManager.getLogger("GltfValidation");
@Override
protected Void prepare(
ResourceManager resourceManager,
ProfilerFiller profiler
) {
return null;
}
@Override
protected void apply(
Void nothing,
ResourceManager resourceManager,
ProfilerFiller profiler
) {
GlbDiagnosticRegistry.clear();
Collection<DataDrivenItemDefinition> definitions =
DataDrivenItemRegistry.getAll();
if (definitions.isEmpty()) {
LOGGER.warn(
"[GltfValidation] No data-driven item definitions found — skipping GLB validation"
);
return;
}
int passed = 0;
int withWarnings = 0;
int withErrors = 0;
for (DataDrivenItemDefinition def : definitions) {
ResourceLocation modelLoc = def.modelLocation();
if (modelLoc == null) {
continue;
}
Optional<Resource> resourceOpt =
resourceManager.getResource(modelLoc);
if (resourceOpt.isEmpty()) {
// GLB file not found in any resource pack
GlbValidationResult missingResult = GlbValidationResult.of(
modelLoc,
List.of(new GlbDiagnostic(
modelLoc,
def.id(),
GlbDiagnostic.Severity.ERROR,
"MISSING_GLB",
"GLB file not found: " + modelLoc
+ " (referenced by item " + def.id() + ")"
))
);
GlbDiagnosticRegistry.addResult(missingResult);
withErrors++;
continue;
}
try (InputStream stream = resourceOpt.get().open()) {
GlbValidationResult result =
GlbValidator.validate(stream, modelLoc);
GlbDiagnosticRegistry.addResult(result);
if (!result.passed()) {
withErrors++;
} else if (hasWarnings(result)) {
withWarnings++;
} else {
passed++;
}
} catch (Exception e) {
GlbValidationResult errorResult = GlbValidationResult.of(
modelLoc,
List.of(new GlbDiagnostic(
modelLoc,
def.id(),
GlbDiagnostic.Severity.ERROR,
"GLB_READ_ERROR",
"Failed to read GLB file: " + e.getMessage()
))
);
GlbDiagnosticRegistry.addResult(errorResult);
withErrors++;
}
}
int total = passed + withWarnings + withErrors;
LOGGER.info(
"[GltfValidation] Validated {} GLBs: {} passed, {} with warnings, {} with errors",
total, passed, withWarnings, withErrors
);
// Show toast notification for errors so artists don't have to check logs
if (withErrors > 0) {
int errorCount = withErrors;
Minecraft.getInstance().tell(() ->
Minecraft.getInstance().getToasts().addToast(
SystemToast.multiline(
Minecraft.getInstance(),
SystemToast.SystemToastIds.PACK_LOAD_FAILURE,
Component.literal("TiedUp! GLB Validation"),
Component.literal(errorCount + " model(s) have errors. Run /tiedup validate")
)
)
);
}
}
private static boolean hasWarnings(GlbValidationResult result) {
return result.diagnostics().stream()
.anyMatch(d -> d.severity() == GlbDiagnostic.Severity.WARNING);
}
}

View File

@@ -0,0 +1,26 @@
package com.tiedup.remake.client.gltf.diagnostic;
import java.util.List;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
/**
* Validation result for a single GLB file.
*/
@OnlyIn(Dist.CLIENT)
public record GlbValidationResult(
ResourceLocation source,
List<GlbDiagnostic> diagnostics,
boolean passed
) {
/** Create a result, computing passed from diagnostics. */
public static GlbValidationResult of(
ResourceLocation source,
List<GlbDiagnostic> diagnostics
) {
boolean passed = diagnostics.stream()
.noneMatch(d -> d.severity() == GlbDiagnostic.Severity.ERROR);
return new GlbValidationResult(source, List.copyOf(diagnostics), passed);
}
}

View File

@@ -0,0 +1,407 @@
package com.tiedup.remake.client.gltf.diagnostic;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tiedup.remake.client.gltf.GltfBoneMapper;
import com.tiedup.remake.client.gltf.diagnostic.GlbDiagnostic.Severity;
import com.tiedup.remake.v2.bondage.datadriven.DataDrivenItemDefinition;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
/**
* Lightweight structural validator for GLB files.
*
* <p>Reads only the 12-byte header and the JSON chunk (first chunk) — never
* touches the binary mesh data. Produces a list of {@link GlbDiagnostic}
* findings that can range from hard errors (invalid header, missing skin) to
* informational notes (custom bone names).</p>
*
* <p>All methods are static; the class cannot be instantiated.</p>
*/
@OnlyIn(Dist.CLIENT)
public final class GlbValidator {
private static final int GLB_MAGIC = 0x46546C67; // "glTF"
private static final int GLB_VERSION = 2;
private static final int CHUNK_JSON = 0x4E4F534A; // "JSON"
private GlbValidator() {}
/**
* Validate a GLB file by reading its header and JSON chunk.
*
* @param input the raw GLB byte stream (will be fully consumed)
* @param source resource location of the GLB file (used in diagnostics)
* @return a validation result containing all findings
*/
public static GlbValidationResult validate(
InputStream input,
ResourceLocation source
) {
List<GlbDiagnostic> diagnostics = new ArrayList<>();
JsonObject root;
try {
root = readJsonChunk(input, source, diagnostics);
} catch (Exception e) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.ERROR, "INVALID_GLB_HEADER",
"Failed to read GLB header or JSON chunk: " + e.getMessage()
));
return GlbValidationResult.of(source, diagnostics);
}
// If readJsonChunk added an ERROR, root will be null
if (root == null) {
return GlbValidationResult.of(source, diagnostics);
}
validateSkins(root, source, diagnostics);
validateMeshes(root, source, diagnostics);
validateAnimations(root, source, diagnostics);
return GlbValidationResult.of(source, diagnostics);
}
/**
* Cross-reference a validation result against an item definition.
* Stub for future checks (e.g. region/bone coverage, animation name
* matching against definition-declared poses).
*
* @param result the prior structural validation result
* @param def the item definition to cross-reference
* @return additional diagnostics (currently empty)
*/
public static List<GlbDiagnostic> validateAgainstDefinition(
GlbValidationResult result,
DataDrivenItemDefinition def
) {
return Collections.emptyList();
}
// ------------------------------------------------------------------ //
// Header + JSON chunk extraction //
// ------------------------------------------------------------------ //
/** Maximum GLB file size the validator will accept (50 MB). */
private static final long MAX_GLB_SIZE = 50L * 1024 * 1024;
/**
* Parse the GLB header and extract the JSON chunk root object.
* Returns null and adds ERROR diagnostics on failure.
*/
private static JsonObject readJsonChunk(
InputStream input,
ResourceLocation source,
List<GlbDiagnostic> diagnostics
) throws Exception {
// Read the 12-byte header first to check totalLength before
// committing to readAllBytes (OOM guard for malformed GLBs).
byte[] header = input.readNBytes(12);
if (header.length < 12) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.ERROR, "INVALID_GLB_HEADER",
"File too small to contain a GLB header (" + header.length + " bytes)"
));
return null;
}
ByteBuffer headerBuf = ByteBuffer.wrap(header).order(ByteOrder.LITTLE_ENDIAN);
// -- Header (12 bytes) --
int magic = headerBuf.getInt();
if (magic != GLB_MAGIC) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.ERROR, "INVALID_GLB_HEADER",
String.format("Bad magic number: 0x%08X (expected 0x%08X)", magic, GLB_MAGIC)
));
return null;
}
int version = headerBuf.getInt();
if (version != GLB_VERSION) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.ERROR, "INVALID_GLB_HEADER",
"Unsupported GLB version " + version + " (expected " + GLB_VERSION + ")"
));
return null;
}
int totalLength = headerBuf.getInt();
// OOM guard: reject files that declare a size exceeding the cap.
// totalLength is a signed int, so treat negative values as > 2 GB.
if (totalLength < 0 || Integer.toUnsignedLong(totalLength) > MAX_GLB_SIZE) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.ERROR, "GLB_TOO_LARGE",
"GLB declares totalLength=" + Integer.toUnsignedLong(totalLength)
+ " bytes which exceeds the " + (MAX_GLB_SIZE / (1024 * 1024))
+ " MB safety cap — aborting validation"
));
return null;
}
// Now read the remainder (totalLength includes the 12-byte header)
int remaining = totalLength - 12;
if (remaining < 0) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.ERROR, "INVALID_GLB_HEADER",
"GLB totalLength (" + totalLength + ") is smaller than the header itself"
));
return null;
}
byte[] restBytes = input.readNBytes(remaining);
ByteBuffer buf = ByteBuffer.wrap(restBytes).order(ByteOrder.LITTLE_ENDIAN);
// -- First chunk must be JSON --
if (buf.remaining() < 8) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.ERROR, "INVALID_GLB_HEADER",
"File truncated: no chunk header after GLB header"
));
return null;
}
int jsonChunkLength = buf.getInt();
int jsonChunkType = buf.getInt();
if (jsonChunkType != CHUNK_JSON) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.ERROR, "INVALID_GLB_HEADER",
String.format(
"First chunk is not JSON: type 0x%08X (expected 0x%08X)",
jsonChunkType, CHUNK_JSON
)
));
return null;
}
if (buf.remaining() < jsonChunkLength) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.ERROR, "INVALID_GLB_HEADER",
"File truncated: JSON chunk declares " + jsonChunkLength
+ " bytes but only " + buf.remaining() + " remain"
));
return null;
}
byte[] jsonBytes = new byte[jsonChunkLength];
buf.get(jsonBytes);
String jsonStr = new String(jsonBytes, StandardCharsets.UTF_8);
return JsonParser.parseString(jsonStr).getAsJsonObject();
}
// ------------------------------------------------------------------ //
// Skin / bone validation //
// ------------------------------------------------------------------ //
private static void validateSkins(
JsonObject root,
ResourceLocation source,
List<GlbDiagnostic> diagnostics
) {
if (!root.has("skins")) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.ERROR, "NO_SKINS",
"GLB has no 'skins' array — skinned mesh rendering requires at least one skin"
));
return;
}
JsonArray skins = root.getAsJsonArray("skins");
if (skins.size() == 0) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.ERROR, "NO_SKINS",
"GLB 'skins' array is empty — skinned mesh rendering requires at least one skin"
));
return;
}
// Validate bones in the first skin
JsonObject skin = skins.get(0).getAsJsonObject();
if (!skin.has("joints")) {
return;
}
JsonArray joints = skin.getAsJsonArray("joints");
JsonArray nodes = root.has("nodes") ? root.getAsJsonArray("nodes") : null;
if (nodes == null) {
return;
}
for (int j = 0; j < joints.size(); j++) {
int nodeIdx = joints.get(j).getAsInt();
if (nodeIdx < 0 || nodeIdx >= nodes.size()) {
continue;
}
JsonObject node = nodes.get(nodeIdx).getAsJsonObject();
if (!node.has("name")) {
continue;
}
String rawName = node.get("name").getAsString();
// Strip armature prefix (e.g. "MyRig|body" -> "body")
String boneName = rawName.contains("|")
? rawName.substring(rawName.lastIndexOf('|') + 1)
: rawName;
if (GltfBoneMapper.isKnownBone(boneName)) {
// OK — known bone, no diagnostic needed
continue;
}
String suggestion = GltfBoneMapper.suggestBoneName(boneName);
if (suggestion != null) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.WARNING, "BONE_TYPO_SUGGESTION",
"Bone '" + boneName + "' is not recognized — did you mean '"
+ suggestion + "'?"
));
} else {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.INFO, "UNKNOWN_BONE",
"Bone '" + boneName + "' is not a standard MC bone (treated as custom bone)"
));
}
}
}
// ------------------------------------------------------------------ //
// Mesh validation //
// ------------------------------------------------------------------ //
private static void validateMeshes(
JsonObject root,
ResourceLocation source,
List<GlbDiagnostic> diagnostics
) {
if (!root.has("meshes")) {
return;
}
JsonArray meshes = root.getAsJsonArray("meshes");
// Count non-Player meshes
int nonPlayerCount = 0;
for (int mi = 0; mi < meshes.size(); mi++) {
JsonObject mesh = meshes.get(mi).getAsJsonObject();
String meshName = mesh.has("name")
? mesh.get("name").getAsString()
: "";
if (!"Player".equals(meshName)) {
nonPlayerCount++;
}
}
if (nonPlayerCount > 1) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.WARNING, "MULTI_MESH_AMBIGUITY",
nonPlayerCount + " non-Player meshes found — name your item mesh 'Item' "
+ "for explicit selection"
));
}
// Check WEIGHTS_0 on the mesh that GlbParser would actually select:
// 1) mesh named "Item", 2) last non-Player mesh.
JsonObject targetMesh = null;
String targetMeshName = null;
for (int mi = 0; mi < meshes.size(); mi++) {
JsonObject mesh = meshes.get(mi).getAsJsonObject();
String meshName = mesh.has("name")
? mesh.get("name").getAsString()
: "";
if ("Item".equals(meshName)) {
targetMesh = mesh;
targetMeshName = meshName;
break; // Convention match — same as GlbParser
}
if (!"Player".equals(meshName)) {
targetMesh = mesh;
targetMeshName = meshName;
}
}
if (targetMesh != null && targetMesh.has("primitives")) {
JsonArray primitives = targetMesh.getAsJsonArray("primitives");
if (primitives.size() > 0) {
JsonObject firstPrimitive = primitives.get(0).getAsJsonObject();
if (firstPrimitive.has("attributes")) {
JsonObject attributes = firstPrimitive.getAsJsonObject("attributes");
if (!attributes.has("WEIGHTS_0")) {
String meshLabel = targetMeshName != null
? "'" + targetMeshName + "'"
: "(unnamed)";
diagnostics.add(new GlbDiagnostic(
source, null, Severity.WARNING, "NO_WEIGHTS",
"Selected mesh " + meshLabel
+ " first primitive has no WEIGHTS_0 attribute "
+ "— skinning will not work correctly"
));
}
}
}
}
}
// ------------------------------------------------------------------ //
// Animation validation //
// ------------------------------------------------------------------ //
private static void validateAnimations(
JsonObject root,
ResourceLocation source,
List<GlbDiagnostic> diagnostics
) {
if (!root.has("animations")) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.WARNING, "NO_IDLE_ANIMATION",
"GLB has no 'animations' array — no Idle animation found"
));
return;
}
JsonArray animations = root.getAsJsonArray("animations");
if (animations.size() == 0) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.WARNING, "NO_IDLE_ANIMATION",
"GLB 'animations' array is empty — no Idle animation found"
));
return;
}
boolean hasIdle = false;
for (int ai = 0; ai < animations.size(); ai++) {
JsonObject anim = animations.get(ai).getAsJsonObject();
if (!anim.has("name")) {
continue;
}
String animName = anim.get("name").getAsString();
// Strip armature prefix (e.g. "Armature|Idle" -> "Idle")
if (animName.contains("|")) {
animName = animName.substring(animName.lastIndexOf('|') + 1);
}
if ("Idle".equals(animName)) {
hasIdle = true;
break;
}
}
if (!hasIdle) {
diagnostics.add(new GlbDiagnostic(
source, null, Severity.WARNING, "NO_IDLE_ANIMATION",
"No animation named 'Idle' found — the default rest pose may not display correctly"
));
}
}
}

View File

@@ -0,0 +1,133 @@
package com.tiedup.remake.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.tiedup.remake.client.gltf.diagnostic.GlbDiagnostic;
import com.tiedup.remake.client.gltf.diagnostic.GlbDiagnosticRegistry;
import com.tiedup.remake.client.gltf.diagnostic.GlbValidationResult;
import net.minecraft.ChatFormatting;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
/**
* Client-only command: /tiedup validate [item_id]
*
* Displays GLB validation diagnostics in chat.
* Registered via {@link net.minecraftforge.client.event.RegisterClientCommandsEvent}
* on the FORGE bus (never on the server).
*/
@OnlyIn(Dist.CLIENT)
public final class ValidateGlbCommand {
private ValidateGlbCommand() {}
public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
dispatcher.register(
Commands.literal("tiedup")
.then(Commands.literal("validate")
.executes(ctx -> validateAll(ctx.getSource()))
.then(Commands.argument("item_id", StringArgumentType.string())
.executes(ctx -> validateOne(
ctx.getSource(),
StringArgumentType.getString(ctx, "item_id")
))
)
)
);
}
private static int validateAll(CommandSourceStack source) {
var all = GlbDiagnosticRegistry.getAll();
if (all.isEmpty()) {
source.sendSuccess(
() -> Component.literal(
"[TiedUp] No GLB validation results. "
+ "Try reloading resources (F3+T)."
).withStyle(ChatFormatting.YELLOW),
false
);
return 0;
}
int totalDiags = 0;
for (GlbValidationResult result : all) {
if (result.diagnostics().isEmpty()) continue;
source.sendSuccess(
() -> Component.literal("--- " + result.source() + " ---")
.withStyle(
result.passed()
? ChatFormatting.GREEN
: ChatFormatting.RED
),
false
);
for (GlbDiagnostic d : result.diagnostics()) {
source.sendSuccess(() -> formatDiagnostic(d), false);
totalDiags++;
}
}
int count = totalDiags;
source.sendSuccess(
() -> Component.literal(
"[TiedUp] " + count + " diagnostic(s) across "
+ GlbDiagnosticRegistry.size() + " GLBs"
).withStyle(ChatFormatting.GRAY),
false
);
return 1;
}
private static int validateOne(CommandSourceStack source, String itemId) {
ResourceLocation loc = ResourceLocation.tryParse(itemId);
if (loc == null) {
source.sendFailure(
Component.literal("Invalid resource location: " + itemId)
);
return 0;
}
for (GlbValidationResult result : GlbDiagnosticRegistry.getAll()) {
boolean match = result.source().equals(loc);
if (!match) {
match = result.diagnostics().stream()
.anyMatch(d -> loc.equals(d.itemDef()));
}
if (match) {
source.sendSuccess(
() -> Component.literal("--- " + result.source() + " ---")
.withStyle(
result.passed()
? ChatFormatting.GREEN
: ChatFormatting.RED
),
false
);
for (GlbDiagnostic d : result.diagnostics()) {
source.sendSuccess(() -> formatDiagnostic(d), false);
}
return 1;
}
}
source.sendFailure(
Component.literal("No validation results for: " + itemId)
);
return 0;
}
private static Component formatDiagnostic(GlbDiagnostic d) {
ChatFormatting color = switch (d.severity()) {
case ERROR -> ChatFormatting.RED;
case WARNING -> ChatFormatting.YELLOW;
case INFO -> ChatFormatting.GRAY;
};
return Component.literal(
" [" + d.severity() + "] " + d.code() + ": " + d.message()
).withStyle(color);
}
}

View File

@@ -103,7 +103,8 @@ public record DataDrivenItemDefinition(
* is not present in this map (or null), the item falls back to its full * is not present in this map (or null), the item falls back to its full
* {@code ownedParts}.</p> * {@code ownedParts}.</p>
* *
* <p>This field is required in the JSON definition. Never null, never empty.</p> * <p>Optional in JSON. When absent, defaults to empty map (= all owned bones
* enabled for all animations, no filtering).</p>
*/ */
Map<String, Set<String>> animationBones, Map<String, Set<String>> animationBones,
@@ -111,9 +112,10 @@ public record DataDrivenItemDefinition(
Map<ComponentType, JsonObject> componentConfigs Map<ComponentType, JsonObject> componentConfigs
) { ) {
/** Compact constructor: default null componentConfigs to empty immutable map. */ /** Compact constructor: default null maps to empty immutable maps. */
public DataDrivenItemDefinition { public DataDrivenItemDefinition {
if (componentConfigs == null) componentConfigs = Map.of(); if (componentConfigs == null) componentConfigs = Map.of();
if (animationBones == null) animationBones = Map.of();
} }
/** Check whether this definition declares a given component type. */ /** Check whether this definition declares a given component type. */

View File

@@ -261,17 +261,27 @@ public final class DataDrivenItemParser {
// Optional: creator (author name for tooltip) // Optional: creator (author name for tooltip)
String creator = getStringOrNull(root, "creator"); String creator = getStringOrNull(root, "creator");
// Required: animation_bones (per-animation bone whitelist) // Optional: animation_bones (per-animation bone whitelist)
Map<String, Set<String>> animationBones = parseAnimationBones( // When absent, all owned bones are enabled for all animations.
root, Map<String, Set<String>> animationBones;
fileId if (!root.has("animation_bones")) {
); // Not an error — absent means "permissive" (all owned bones, all animations)
if (animationBones == null) { animationBones = null;
LOGGER.error( LOGGER.debug(
"[DataDrivenItems] Skipping {}: missing or invalid 'animation_bones'", "[DataDrivenItems] {}: animation_bones not declared — all owned bones enabled for all animations",
fileId fileId
); );
return null; // null is fine — the record constructor defaults it to Map.of()
} else {
animationBones = parseAnimationBones(root, fileId);
if (animationBones == null) {
// Field was present but malformed — parseAnimationBones already logged details
LOGGER.error(
"[DataDrivenItems] Skipping {}: 'animation_bones' is present but invalid",
fileId
);
return null;
}
} }
// Optional: components (per-component JSON configs) // Optional: components (per-component JSON configs)

View File

@@ -1216,6 +1216,10 @@ public final class FurnitureGlbParser {
String name = node.has("name") String name = node.has("name")
? node.get("name").getAsString() ? node.get("name").getAsString()
: "joint_" + j; : "joint_" + j;
// Strip armature prefix (e.g., "MyRig|body" -> "body")
if (name.contains("|")) {
name = name.substring(name.lastIndexOf('|') + 1);
}
if (GltfBoneMapper.isKnownBone(name)) { if (GltfBoneMapper.isKnownBone(name)) {
skinJointRemap[j] = filteredJointNodes.size(); skinJointRemap[j] = filteredJointNodes.size();
filteredJointNodes.add(nodeIdx); filteredJointNodes.add(nodeIdx);
@@ -1257,9 +1261,13 @@ public final class FurnitureGlbParser {
int nodeIdx = filteredJointNodes.get(j); int nodeIdx = filteredJointNodes.get(j);
JsonObject node = nodes.get(nodeIdx).getAsJsonObject(); JsonObject node = nodes.get(nodeIdx).getAsJsonObject();
jointNames[j] = node.has("name") String rawBoneName = node.has("name")
? node.get("name").getAsString() ? node.get("name").getAsString()
: "joint_" + j; : "joint_" + j;
// Strip armature prefix consistently
jointNames[j] = rawBoneName.contains("|")
? rawBoneName.substring(rawBoneName.lastIndexOf('|') + 1)
: rawBoneName;
if (node.has("rotation")) { if (node.has("rotation")) {
JsonArray r = node.getAsJsonArray("rotation"); JsonArray r = node.getAsJsonArray("rotation");
@@ -1432,6 +1440,10 @@ public final class FurnitureGlbParser {
String name = node.has("name") String name = node.has("name")
? node.get("name").getAsString() ? node.get("name").getAsString()
: "joint_" + j; : "joint_" + j;
// Strip armature prefix (e.g., "MyRig|body" -> "body")
if (name.contains("|")) {
name = name.substring(name.lastIndexOf('|') + 1);
}
if (GltfBoneMapper.isKnownBone(name)) { if (GltfBoneMapper.isKnownBone(name)) {
filteredJointNodes.add(nodeIdx); filteredJointNodes.add(nodeIdx);
} }