fauna: SpringRigData, the VRMC_springBone rig parsed from a GLB skin (whale-rig-s1)
Skin joints no spring names are body bones; unknown collider shapes, spring joints whose parent is not their predecessor or a body bone, cycles, and non-unit scales are refused by name. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a515899b14
commit
793470c330
3 changed files with 310 additions and 0 deletions
8
Assets/Scripts/Fauna Display.meta
Normal file
8
Assets/Scripts/Fauna Display.meta
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 7f592f693bf509d4990685519d0cc371
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
300
Assets/Scripts/Fauna Display/SpringRigData.cs
Normal file
300
Assets/Scripts/Fauna Display/SpringRigData.cs
Normal file
|
|
@ -0,0 +1,300 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Unity.Mathematics;
|
||||
|
||||
namespace Aetheria.FaunaDisplay
|
||||
{
|
||||
// One spring joint's VRMC_springBone parameters. They drive the segment that ends at the NEXT joint of the chain.
|
||||
public readonly struct SpringJointParams
|
||||
{
|
||||
public readonly float HitRadius, Stiffness, GravityPower, DragForce;
|
||||
public readonly float3 GravityDir;
|
||||
public SpringJointParams(float hitRadius, float stiffness, float gravityPower, float3 gravityDir, float dragForce)
|
||||
{ HitRadius = hitRadius; Stiffness = stiffness; GravityPower = gravityPower; GravityDir = gravityDir; DragForce = dragForce; }
|
||||
}
|
||||
|
||||
// A VRMC_springBone collider bound to a body bone: sphere (Tail unused) or capsule from Offset to Tail, in the bone's frame.
|
||||
public readonly struct SpringCollider
|
||||
{
|
||||
public readonly int Bone;
|
||||
public readonly bool Capsule;
|
||||
public readonly float3 Offset, Tail;
|
||||
public readonly float Radius;
|
||||
public SpringCollider(int bone, bool capsule, float3 offset, float3 tail, float radius)
|
||||
{ Bone = bone; Capsule = capsule; Offset = offset; Tail = tail; Radius = radius; }
|
||||
}
|
||||
|
||||
// The parsed rig: a glTF skin plus VRMC_springBone 1.0 (the seam with the Blender builder). Bone index = skin joint
|
||||
// index, so the mesh's BLENDINDICES address the skin matrices directly. Skin joints no spring names are body bones.
|
||||
// Immutable after FromGlbJson; presentation only (nothing in ServerShared reads it).
|
||||
public sealed class SpringRigData
|
||||
{
|
||||
public int BoneCount => _parent.Length;
|
||||
public int BodyCount { get; private set; }
|
||||
public int ChainCount => _chainStart.Length;
|
||||
public int SpringJointCount => _chainBone.Length;
|
||||
public float MaxChainLength { get; private set; }
|
||||
|
||||
public IReadOnlyList<int> Parent => _parent; // bone parent in the skin, -1 for a root
|
||||
public IReadOnlyList<float3> RestPosition => _restPos; // local to the parent (roots: composed over non-skin ancestors)
|
||||
public IReadOnlyList<quaternion> RestRotation => _restRot;
|
||||
public IReadOnlyList<float4x4> BindPose => _bind; // inverseBindMatrices
|
||||
public IReadOnlyList<bool> IsBody => _isBody;
|
||||
public IReadOnlyList<int> SpineIndex => _spine; // position along the swimming spine, -1 off it
|
||||
public IReadOnlyList<SpringCollider> Colliders => _colliders;
|
||||
public string ChainName(int c) => _chainName[c];
|
||||
public IReadOnlyList<int> ChainBones(int c) => new ArraySegment<int>(_chainBone, _chainStart[c], _chainLen[c]);
|
||||
public SpringJointParams ChainJoint(int c, int k) => _chainParam[_chainStart[c] + k];
|
||||
public IReadOnlyList<int> ChainColliders(int c) => new ArraySegment<int>(_chainCol, _chainColStart[c], _chainColLen[c]);
|
||||
|
||||
// Flattened layout the jobs copy: chain c owns [ChainStart[c], +ChainLen[c]) of ChainBone/ChainParam.
|
||||
internal int[] _parent, _order, _spine, _chainStart, _chainLen, _chainBone, _chainColStart, _chainColLen, _chainCol;
|
||||
internal float3[] _restPos;
|
||||
internal quaternion[] _restRot;
|
||||
internal float4x4[] _bind;
|
||||
internal bool[] _isBody;
|
||||
internal SpringJointParams[] _chainParam;
|
||||
internal SpringCollider[] _colliders;
|
||||
string[] _chainName;
|
||||
|
||||
SpringRigData() { }
|
||||
|
||||
// A GLB container: header, JSON chunk, optional BIN chunk.
|
||||
public static SpringRigData FromGlb(byte[] glb, int skin = 0)
|
||||
{
|
||||
if (glb.Length < 20 || BitConverter.ToUInt32(glb, 0) != 0x46546C67) throw new InvalidDataException("Not a GLB (magic).");
|
||||
int at = 12;
|
||||
JObject json = null;
|
||||
byte[] bin = null;
|
||||
while (at + 8 <= glb.Length)
|
||||
{
|
||||
int length = (int)BitConverter.ToUInt32(glb, at);
|
||||
uint type = BitConverter.ToUInt32(glb, at + 4);
|
||||
if (type == 0x4E4F534A) json = JObject.Parse(Encoding.UTF8.GetString(glb, at + 8, length));
|
||||
else if (type == 0x004E4942 && bin == null) { bin = new byte[length]; Buffer.BlockCopy(glb, at + 8, bin, 0, length); }
|
||||
at += 8 + length;
|
||||
}
|
||||
return FromGlbJson(json ?? throw new InvalidDataException("GLB has no JSON chunk."), bin, skin);
|
||||
}
|
||||
|
||||
// json is the GLB JSON chunk, bin the BIN chunk (the inverseBindMatrices live there).
|
||||
public static SpringRigData FromGlbJson(JObject json, byte[] bin, int skinIndex = 0)
|
||||
{
|
||||
var nodes = json["nodes"] as JArray ?? throw new InvalidDataException("glTF has no nodes.");
|
||||
var skins = json["skins"] as JArray;
|
||||
var skin = skins != null && skinIndex >= 0 && skinIndex < skins.Count ? skins[skinIndex] as JObject : null;
|
||||
if (skin == null) throw new InvalidDataException($"glTF has no skin {skinIndex}.");
|
||||
var joints = (skin["joints"] as JArray)?.Select(j => (int)j).ToArray() ?? throw new InvalidDataException("Skin has no joints.");
|
||||
int n = nodes.Count, b = joints.Length;
|
||||
|
||||
// Node parents from children; a node with two parents or a loop is refused by name.
|
||||
var nodeParent = Enumerable.Repeat(-1, n).ToArray();
|
||||
for (int i = 0; i < n; i++)
|
||||
foreach (var child in (nodes[i]["children"] as JArray) ?? new JArray())
|
||||
{
|
||||
int c = (int)child;
|
||||
if (c < 0 || c >= n) throw new InvalidDataException($"Node {i} names child {c} outside the node list.");
|
||||
if (nodeParent[c] >= 0) throw new InvalidDataException($"Node {c} has two parents ({nodeParent[c]} and {i}).");
|
||||
nodeParent[c] = i;
|
||||
}
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int hops = 0;
|
||||
for (int p = nodeParent[i]; p >= 0; p = nodeParent[p])
|
||||
if (++hops > n) throw new InvalidDataException($"Cycle in the node tree through node {i}.");
|
||||
}
|
||||
|
||||
var boneOfNode = Enumerable.Repeat(-1, n).ToArray();
|
||||
for (int i = 0; i < b; i++)
|
||||
{
|
||||
if (joints[i] < 0 || joints[i] >= n) throw new InvalidDataException($"Skin joint {i} names node {joints[i]} outside the node list.");
|
||||
if (boneOfNode[joints[i]] >= 0) throw new InvalidDataException($"Node {joints[i]} appears twice in the skin.");
|
||||
boneOfNode[joints[i]] = i;
|
||||
}
|
||||
|
||||
var d = new SpringRigData { _isBody = Enumerable.Repeat(true, b).ToArray() };
|
||||
d._parent = new int[b];
|
||||
d._restPos = new float3[b];
|
||||
d._restRot = new quaternion[b];
|
||||
for (int i = 0; i < b; i++)
|
||||
{
|
||||
// Rest pose of a bone is its node's TRS; a bone whose parent node is outside the skin composes that ancestry in.
|
||||
var (pos, rot) = LocalRest(nodes, joints[i]);
|
||||
int pn = nodeParent[joints[i]];
|
||||
var outside = new List<int>();
|
||||
while (pn >= 0 && boneOfNode[pn] < 0) { outside.Add(pn); pn = nodeParent[pn]; }
|
||||
d._parent[i] = pn >= 0 ? boneOfNode[pn] : -1;
|
||||
foreach (var o in outside)
|
||||
{
|
||||
var (op, or) = LocalRest(nodes, o);
|
||||
pos = op + math.mul(or, pos);
|
||||
rot = math.mul(or, rot);
|
||||
}
|
||||
d._restPos[i] = pos;
|
||||
d._restRot[i] = rot;
|
||||
}
|
||||
|
||||
// Colliders, groups, springs.
|
||||
var ext = json["extensions"]?["VRMC_springBone"] as JObject;
|
||||
var colliders = new List<SpringCollider>();
|
||||
var colliderJson = (ext?["colliders"] as JArray) ?? new JArray();
|
||||
for (int ci = 0; ci < colliderJson.Count; ci++)
|
||||
{
|
||||
var c = colliderJson[ci];
|
||||
int node = (int)c["node"];
|
||||
if (node < 0 || node >= n || boneOfNode[node] < 0) throw new InvalidDataException($"Collider {ci} sits on node {node}, which is not a skin joint.");
|
||||
var shape = c["shape"] as JObject ?? throw new InvalidDataException($"Collider {ci} has no shape.");
|
||||
var props = shape.Properties().ToArray();
|
||||
if (props.Length != 1 || (props[0].Name != "sphere" && props[0].Name != "capsule"))
|
||||
throw new InvalidDataException($"Collider {ci}: unknown shape '{string.Join(",", props.Select(p => p.Name))}' (sphere or capsule).");
|
||||
var s = props[0].Value;
|
||||
bool capsule = props[0].Name == "capsule";
|
||||
var offset = Vec3(s["offset"], default);
|
||||
colliders.Add(new SpringCollider(boneOfNode[node], capsule, offset, capsule ? Vec3(s["tail"], default) : offset, (float)(s["radius"] ?? 0f)));
|
||||
}
|
||||
d._colliders = colliders.ToArray();
|
||||
var groups = ((ext?["colliderGroups"] as JArray) ?? new JArray()).Select(g => ((g["colliders"] as JArray) ?? new JArray()).Select(x => (int)x).ToArray()).ToArray();
|
||||
|
||||
var springs = ((ext?["springs"] as JArray) ?? new JArray()).Cast<JObject>().ToArray();
|
||||
var springBones = new List<int[]>();
|
||||
for (int si = 0; si < springs.Length; si++)
|
||||
{
|
||||
var name = (string)springs[si]["name"] ?? $"spring{si}";
|
||||
var bones = ((springs[si]["joints"] as JArray) ?? new JArray()).Select(j =>
|
||||
{
|
||||
int node = (int)j["node"];
|
||||
if (node < 0 || node >= n || boneOfNode[node] < 0) throw new InvalidDataException($"Spring '{name}' names node {node}, which is not a skin joint.");
|
||||
return boneOfNode[node];
|
||||
}).ToArray();
|
||||
if (bones.Length < 2) throw new InvalidDataException($"Spring '{name}' needs at least two joints.");
|
||||
foreach (var bone in bones)
|
||||
{
|
||||
if (!d._isBody[bone]) throw new InvalidDataException($"Spring '{name}': node {joints[bone]} is named twice by springs.");
|
||||
d._isBody[bone] = false;
|
||||
}
|
||||
springBones.Add(bones);
|
||||
}
|
||||
for (int si = 0; si < springBones.Count; si++)
|
||||
{
|
||||
var bones = springBones[si];
|
||||
var name = (string)springs[si]["name"] ?? $"spring{si}";
|
||||
for (int k = 0; k < bones.Length; k++)
|
||||
{
|
||||
int parent = d._parent[bones[k]];
|
||||
if (k == 0 && (parent < 0 || !d._isBody[parent]))
|
||||
throw new InvalidDataException($"Spring '{name}': first joint (node {joints[bones[0]]}) must hang from a body bone.");
|
||||
if (k > 0 && parent != bones[k - 1])
|
||||
throw new InvalidDataException($"Spring '{name}': joint {k} (node {joints[bones[k]]}) has parent {(parent < 0 ? "none" : "node " + joints[parent])}, not its predecessor node {joints[bones[k - 1]]}.");
|
||||
}
|
||||
}
|
||||
|
||||
var chainBone = new List<int>(); var chainParam = new List<SpringJointParams>(); var chainCol = new List<int>();
|
||||
var starts = new List<int>(); var lens = new List<int>(); var cstarts = new List<int>(); var clens = new List<int>(); var names = new List<string>();
|
||||
float longest = 0;
|
||||
for (int si = 0; si < springBones.Count; si++)
|
||||
{
|
||||
var bones = springBones[si];
|
||||
var sp = springs[si];
|
||||
starts.Add(chainBone.Count); lens.Add(bones.Length); names.Add((string)sp["name"] ?? $"spring{si}");
|
||||
var js = (JArray)sp["joints"];
|
||||
float length = 0;
|
||||
for (int k = 0; k < bones.Length; k++)
|
||||
{
|
||||
chainBone.Add(bones[k]);
|
||||
var j = js[k];
|
||||
chainParam.Add(new SpringJointParams((float)(j["hitRadius"] ?? 0f), (float)(j["stiffness"] ?? 1f), (float)(j["gravityPower"] ?? 0f),
|
||||
Vec3(j["gravityDir"], new float3(0, -1, 0)), (float)(j["dragForce"] ?? 0.5f)));
|
||||
if (k > 0) length += math.length(d._restPos[bones[k]]);
|
||||
}
|
||||
longest = math.max(longest, length);
|
||||
cstarts.Add(chainCol.Count);
|
||||
var set = new SortedSet<int>();
|
||||
foreach (var g in (sp["colliderGroups"] as JArray) ?? new JArray())
|
||||
{
|
||||
int gi = (int)g;
|
||||
if (gi < 0 || gi >= groups.Length) throw new InvalidDataException($"Spring '{names[names.Count - 1]}' names collider group {gi}, which does not exist.");
|
||||
foreach (var c in groups[gi])
|
||||
{
|
||||
if (c < 0 || c >= d._colliders.Length) throw new InvalidDataException($"Collider group {gi} names collider {c}, which does not exist.");
|
||||
set.Add(c);
|
||||
}
|
||||
}
|
||||
chainCol.AddRange(set); clens.Add(set.Count);
|
||||
}
|
||||
d._chainBone = chainBone.ToArray(); d._chainParam = chainParam.ToArray(); d._chainCol = chainCol.ToArray();
|
||||
d._chainStart = starts.ToArray(); d._chainLen = lens.ToArray(); d._chainColStart = cstarts.ToArray(); d._chainColLen = clens.ToArray();
|
||||
d._chainName = names.ToArray();
|
||||
d.MaxChainLength = longest;
|
||||
d.BodyCount = d._isBody.Count(x => x);
|
||||
|
||||
// Parents before children.
|
||||
var children = new List<int>[b];
|
||||
for (int i = 0; i < b; i++) children[i] = new List<int>();
|
||||
var roots = new List<int>();
|
||||
for (int i = 0; i < b; i++) (d._parent[i] < 0 ? roots : children[d._parent[i]]).Add(i);
|
||||
var order = new List<int>(roots);
|
||||
for (int i = 0; i < order.Count; i++) order.AddRange(children[order[i]]);
|
||||
d._order = order.ToArray();
|
||||
|
||||
// Spine: from the first body root, the body child with the most body descendants at each step; the swim wave runs down it.
|
||||
var weight = new int[b];
|
||||
for (int i = d._order.Length - 1; i >= 0; i--)
|
||||
{
|
||||
int bone = d._order[i];
|
||||
if (!d._isBody[bone]) continue;
|
||||
weight[bone] += 1;
|
||||
if (d._parent[bone] >= 0) weight[d._parent[bone]] += weight[bone];
|
||||
}
|
||||
d._spine = Enumerable.Repeat(-1, b).ToArray();
|
||||
int cur = roots.Where(r => d._isBody[r]).DefaultIfEmpty(-1).First(), depth = 0;
|
||||
while (cur >= 0)
|
||||
{
|
||||
d._spine[cur] = depth++;
|
||||
cur = children[cur].Where(c => d._isBody[c]).OrderByDescending(c => weight[c]).DefaultIfEmpty(-1).First();
|
||||
}
|
||||
|
||||
d._bind = ReadBindPoses(json, skin, bin, b);
|
||||
return d;
|
||||
}
|
||||
|
||||
static float3 Vec3(JToken t, float3 fallback) => t is JArray a && a.Count == 3 ? new float3((float)a[0], (float)a[1], (float)a[2]) : fallback;
|
||||
|
||||
static (float3, quaternion) LocalRest(JArray nodes, int node)
|
||||
{
|
||||
var nd = nodes[node];
|
||||
if (nd["matrix"] != null) throw new InvalidDataException($"Node {node} uses a matrix; the rig takes translation, rotation and unit scale.");
|
||||
if (nd["scale"] is JArray s && (math.abs((float)s[0] - 1) > 1e-4f || math.abs((float)s[1] - 1) > 1e-4f || math.abs((float)s[2] - 1) > 1e-4f))
|
||||
throw new InvalidDataException($"Node {node} has a non-unit scale; bake it before export.");
|
||||
float3 t = Vec3(nd["translation"], default);
|
||||
var r = nd["rotation"] as JArray;
|
||||
return (t, r != null && r.Count == 4 ? math.normalize(new quaternion((float)r[0], (float)r[1], (float)r[2], (float)r[3])) : quaternion.identity);
|
||||
}
|
||||
|
||||
static float4x4[] ReadBindPoses(JObject json, JObject skin, byte[] bin, int count)
|
||||
{
|
||||
var result = Enumerable.Repeat(float4x4.identity, count).ToArray();
|
||||
if (skin["inverseBindMatrices"] == null) return result;
|
||||
var acc = (json["accessors"] as JArray)?[(int)skin["inverseBindMatrices"]] ?? throw new InvalidDataException("inverseBindMatrices names a missing accessor.");
|
||||
var view = (json["bufferViews"] as JArray)?[(int)acc["bufferView"]] ?? throw new InvalidDataException("inverseBindMatrices accessor has no bufferView.");
|
||||
if ((int)acc["componentType"] != 5126 || (string)acc["type"] != "MAT4" || (int)acc["count"] < count)
|
||||
throw new InvalidDataException("inverseBindMatrices must be float MAT4, one per joint.");
|
||||
int at = (int)(view["byteOffset"] ?? 0) + (int)(acc["byteOffset"] ?? 0);
|
||||
if (bin == null || at + count * 64 > bin.Length) throw new InvalidDataException("inverseBindMatrices run past the BIN chunk.");
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var f = new float[16];
|
||||
Buffer.BlockCopy(bin, at + i * 64, f, 0, 64);
|
||||
result[i] = new float4x4(f[0], f[4], f[8], f[12], f[1], f[5], f[9], f[13], f[2], f[6], f[10], f[14], f[3], f[7], f[11], f[15]); // glTF is column-major
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Fauna Display/SpringRigData.cs.meta
Normal file
2
Assets/Scripts/Fauna Display/SpringRigData.cs.meta
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
fileFormatVersion: 2
|
||||
guid: f6469766221cfcc439a676418613514c
|
||||
Loading…
Reference in a new issue