leviathan.intents.json drops brokkr_mesh_polish.delight; rig.ps1 reran and the committed .springrig is its export, sha256 F9C9C720998464ABCA72567B02F606DA6D94ECCCE36791C87ED3C6E4D18D8BBA (6.6 MB: the source JPEG is kept, not a re-encoded 22 MB PNG). The tendrils stay supple. The pinned base colour hash becomes 975E8E8458CCBA274F94B777745265291530F26F4E42EFA9F3FFDD85D3BF28C4, the same with Direct3D11 and with -nographics. Run, VerifyGlbCases, ImportNoGfx and VerifyGlb on the asset pass; the rest-pose reading is still 6.02e-7 against the 7.8e-5 tolerance. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1543 lines
99 KiB
C#
1543 lines
99 KiB
C#
/* 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.Diagnostics;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Security.Cryptography;
|
|
using Aetheria.FaunaDisplay;
|
|
using Newtonsoft.Json.Linq;
|
|
using Unity.Mathematics;
|
|
using UnityEditor;
|
|
using UnityEngine;
|
|
using UnityEngine.Rendering;
|
|
using Debug = UnityEngine.Debug;
|
|
|
|
namespace Aetheria.EditorTools
|
|
{
|
|
/// <summary>
|
|
/// Batchmode verify for the whale rig (campaign aetheria-fauna, cut whale-rig-s1): a synthetic rig built in code as a glTF
|
|
/// skin plus VRMC_springBone, run through SpringRig.Present, checked against CPU re-derivations. Opens no scene.
|
|
/// Needs a graphics device (the skin check renders): run WITHOUT -nographics, and without -quit (Run exits itself, 0 or 1).
|
|
/// Unity -batchmode -projectPath <repo> -executeMethod Aetheria.EditorTools.SpringRigVerify.Run -logFile <path>
|
|
/// VerifyGlb runs the rig contract's own parse (SpringRigData.FromGlb) and the glTFast skin comparison on the GLB at
|
|
/// SPRINGRIG_GLB (same flags, method VerifyGlb); it adds no rule of its own. .springrig files are GLBs. It is a thin wrapper
|
|
/// over GlbFile, the file run (a missing path, a refusal or a failed comparison is exit 1, a pass 0) that VerifyGlbCases also runs.
|
|
/// VerifyGlbCases pins GlbFile's verdicts and exit codes on edited Synth GLBs, the committed asset, a text file and a missing path (same flags).
|
|
/// CaptureAsset renders the imported .springrig at SPRINGRIG_ASSET (an Assets path) swimming under one directional light to PNG frames in
|
|
/// SPRINGRIG_CAPTURE_OUT (an absolute path; same flags, method CaptureAsset). Optional: SPRINGRIG_FRAMES (300), SPRINGRIG_FOCUS (x,y,z in
|
|
/// the whale's object space, the camera's target), SPRINGRIG_DISTANCE (1.15), SPRINGRIG_SIDE=-1 (the camera on the -X side), SPRINGRIG_PLANE=1 (a floor
|
|
/// under the whale, to see its shadow).
|
|
/// </summary>
|
|
public static class SpringRigVerify
|
|
{
|
|
const string Tag = "[SpringRigVerify]";
|
|
const double Dt = 1.0 / 60;
|
|
|
|
// Cost bound (lodur:ruling:deterministic-bound-margin): median ms per frame of three Present calls, three whales of 770
|
|
// spring joints, Starfire (Ryzen 3 3100, GTX 1070), editor batchmode, 2 substeps a frame, drawn-pose collision rounds and the
|
|
// Burst bounds job included, other agents' load on the machine. Paired interleaved rounds of 60 frames, shipped against Burst
|
|
// off: shipped worst 0.881 (runs 0.728, 0.881), least mutant 10.13 (runs 10.13, 10.28), separation 11; bound sqrt(0.881 x 10.13) = 2.99. The managed
|
|
// bounds loop it replaced cost about 0.9 ms of the 1.5 ms this read before (Soul).
|
|
const double CostBoundMs = 2.99;
|
|
|
|
static readonly List<GameObject> Scrap = new List<GameObject>();
|
|
static readonly SwimSettings NoSwim = new SwimSettings { PeriodSeconds = 1, Axis = new float3(1, 0, 0) };
|
|
|
|
public static void Run()
|
|
{
|
|
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null)
|
|
{
|
|
Debug.LogError($"{Tag} FAIL: no graphics device in this session; rerun batchmode without -nographics.");
|
|
EditorApplication.Exit(1);
|
|
return;
|
|
}
|
|
var checks = new (string name, Func<string> body)[]
|
|
{
|
|
("vrmc-parse", VrmcParse), ("rest-holds", RestHolds), ("length-holds", LengthHolds), ("collider-pushes-out", ColliderPushesOut),
|
|
("fixed-substeps", FixedSubsteps), ("pause-freezes", PauseFreezes), ("swim-closed-form", SwimClosedForm),
|
|
("freeze-and-reset", FreezeAndReset), ("skin-matches-cpu", SkinMatchesCpu), ("cost-bound", CostBound),
|
|
("lengths-hold-at-any-rate", LengthsHoldAtAnyRate), ("steady-motion-is-smooth", SteadyMotionIsSmooth), ("skin-matches-fk", SkinMatchesFk),
|
|
("capsule-is-finite", CapsuleIsFinite), ("gravity-sags", GravitySags), ("reset-honours-scale", ResetHonoursScale),
|
|
("bounds-follow-the-swim", BoundsFollowTheSwim), ("lod-hysteresis", LodHysteresis), ("inertia-carries", InertiaCarries),
|
|
("reentry-is-continuous", ReentryIsContinuous), ("root-jump-resets", RootJumpResets), ("shadow-is-skinned", ShadowIsSkinned),
|
|
("normals-are-skinned", NormalsAreSkinned),
|
|
};
|
|
int failed = 0;
|
|
foreach (var (name, body) in checks)
|
|
{
|
|
string verdict;
|
|
try { verdict = body(); }
|
|
catch (Exception e) { verdict = "exception: " + e; }
|
|
finally { foreach (var go in Scrap) if (go != null) UnityEngine.Object.DestroyImmediate(go); Scrap.Clear(); }
|
|
if (verdict == null) Debug.Log($"{Tag} PASS {name}");
|
|
else { Debug.LogError($"{Tag} FAIL {name}: {verdict}"); failed++; }
|
|
}
|
|
Handedness(verdict =>
|
|
{
|
|
foreach (var go in Scrap) if (go != null) UnityEngine.Object.DestroyImmediate(go);
|
|
Scrap.Clear();
|
|
if (verdict == null) Debug.Log($"{Tag} PASS handedness");
|
|
else { Debug.LogError($"{Tag} FAIL handedness: {verdict}"); failed++; }
|
|
ImporterBuilds(built =>
|
|
{
|
|
foreach (var go in Scrap) if (go != null) UnityEngine.Object.DestroyImmediate(go);
|
|
Scrap.Clear();
|
|
if (built == null) Debug.Log($"{Tag} PASS importer-builds");
|
|
else { Debug.LogError($"{Tag} FAIL importer-builds: {built}"); failed++; }
|
|
Debug.Log(failed == 0 ? $"{Tag} PASS all" : $"{Tag} FAIL {failed} check(s)");
|
|
EditorApplication.Exit(failed == 0 ? 0 : 1);
|
|
});
|
|
});
|
|
}
|
|
|
|
// ---------------------------------------------------------------- the checks (null is a pass)
|
|
|
|
static string VrmcParse()
|
|
{
|
|
const string fixture = @"{
|
|
""nodes"": [
|
|
{""name"":""body"",""translation"":[0,0,0],""children"":[1,2]},
|
|
{""name"":""fin"",""translation"":[1,0,0]},
|
|
{""name"":""t0"",""translation"":[0,-1,0],""children"":[3]},
|
|
{""name"":""t1"",""translation"":[0,-0.5,0],""children"":[4]},
|
|
{""name"":""t2"",""translation"":[0,-0.25,0]},{""name"":""loose""}],
|
|
""skins"": [{""joints"":[0,1,2,3,4]}],
|
|
""extensions"": {""VRMC_springBone"": {""specVersion"":""1.0"",
|
|
""colliders"": [
|
|
{""node"":0,""shape"":{""sphere"":{""offset"":[0,0,0.1],""radius"":0.4}}},
|
|
{""node"":1,""shape"":{""capsule"":{""offset"":[0,0,0],""radius"":0.1,""tail"":[0.5,0,0]}}}],
|
|
""colliderGroups"": [{""name"":""body"",""colliders"":[0,1]}],
|
|
""springs"": [{""name"":""tendril"",""colliderGroups"":[0],""joints"":[
|
|
{""node"":2,""hitRadius"":0.05,""stiffness"":2,""gravityPower"":0.5,""gravityDir"":[0,-1,0],""dragForce"":0.3},
|
|
{""node"":3,""hitRadius"":0.06,""stiffness"":3,""gravityPower"":0.25,""gravityDir"":[0.6,-0.8,0],""dragForce"":0.2},
|
|
{""node"":4,""hitRadius"":0.07}]}]}}}";
|
|
var d = SpringRigData.FromGlbJson(JObject.Parse(fixture), null);
|
|
if (d.BoneCount != 5 || d.BodyCount != 2 || d.ChainCount != 1 || d.SpringJointCount != 3) return $"counts {d.BoneCount}/{d.BodyCount}/{d.ChainCount}/{d.SpringJointCount}";
|
|
if (!d.Parent.SequenceEqual(new[] { -1, 0, 0, 2, 3 })) return "parents " + string.Join(",", d.Parent);
|
|
if (!d.IsBody.SequenceEqual(new[] { true, true, false, false, false })) return "body flags";
|
|
if (!d.ChainBones(0).SequenceEqual(new[] { 2, 3, 4 }) || d.ChainName(0) != "tendril") return "chain bones";
|
|
var j1 = d.ChainJoint(0, 1);
|
|
if (j1.HitRadius != 0.06f || j1.Stiffness != 3f || j1.GravityPower != 0.25f || j1.DragForce != 0.2f || !j1.GravityDir.Equals(new float3(-0.6f, -0.8f, 0))) return "joint 1 parameters (gravity direction is mirrored in x like every glTF vector)";
|
|
var j2 = d.ChainJoint(0, 2);
|
|
if (j2.Stiffness != 1f || j2.DragForce != 0.5f || j2.GravityPower != 0f) return "joint 2 defaults";
|
|
if (d.Colliders.Count != 2 || d.Colliders[0].Capsule || d.Colliders[0].Bone != 0 || d.Colliders[0].Radius != 0.4f || !d.Colliders[0].Offset.Equals(new float3(0, 0, 0.1f))) return "sphere collider";
|
|
if (!d.Colliders[1].Capsule || d.Colliders[1].Bone != 1 || !d.Colliders[1].Tail.Equals(new float3(-0.5f, 0, 0))) return "capsule collider (glTF x 0.5 is Unity x -0.5)";
|
|
if (!d.ChainColliders(0).SequenceEqual(new[] { 0, 1 })) return "collider group";
|
|
if (!d.RestPosition[3].Equals(new float3(0, -0.5f, 0)) || d.SpineIndex[0] != 0 || d.SpineIndex[1] != 1 || d.SpineIndex[2] != -1) return "rest or spine";
|
|
|
|
string Refused(Func<string, string> mutate, string expect)
|
|
{
|
|
try { SpringRigData.FromGlbJson(JObject.Parse(mutate(fixture)), null); return $"'{expect}' mutant parsed"; }
|
|
catch (InvalidDataException e) { return e.Message.Contains(expect) ? null : $"'{expect}' mutant refused with: {e.Message}"; }
|
|
}
|
|
return Refused(f => f.Replace("\"sphere\"", "\"cone\""), "unknown shape 'cone'")
|
|
?? Refused(f => f.Replace("{\"name\":\"fin\",\"translation\":[1,0,0]}", "{\"name\":\"fin\",\"matrix\":[1,0,0,0,0,1,0,0,0,0,1,0,1,0,0,1]}"), "uses a matrix")
|
|
?? Refused(f => f.Replace("{\"name\":\"fin\",\"translation\":[1,0,0]}", "{\"name\":\"fin\",\"scale\":[2,1,1]}"), "non-unit scale")
|
|
?? Refused(f => f.Replace("{\"node\":1,\"shape\"", "{\"node\":5,\"shape\""), "Collider 1 sits on node 5, which is not a skin joint")
|
|
?? Refused(f => f.Replace("{\"node\":4,\"hitRadius\":0.07}", "{\"node\":3,\"hitRadius\":0.07}"), "named twice")
|
|
?? Refused(f => f.Replace("{\"node\":0,\"shape\"", "{\"node\":3,\"shape\""), "a spring joint; colliders ride body bones")
|
|
?? Refused(f => f.Replace("{\"name\":\"t1\",\"translation\":[0,-0.5,0]", "{\"name\":\"t1\",\"translation\":[0,0,0]"), "sits on its predecessor")
|
|
?? Refused(f => f.Replace("{\"node\":3,\"hitRadius\":0.06", "{\"node\":4,\"hitRadius\":0.06").Replace("{\"node\":4,\"hitRadius\":0.07}", "{\"node\":3,\"hitRadius\":0.07}"), "not its predecessor")
|
|
?? Refused(f => f.Replace("\"children\":[1,2]", "\"children\":[1]").Replace("\"children\":[3]", "\"children\":[3]").Replace("\"children\":[4]", "\"children\":[4,2]"), "Cycle in the node tree");
|
|
}
|
|
|
|
// Stiffness is a rate, so the rest pull settles at any value; a fixed-size nudge along the axis (VRM's) limit-cycles at 60.
|
|
static string RestHolds() => RestCase(20) ?? RestCase(60);
|
|
|
|
static string RestCase(float stiffness)
|
|
{
|
|
var s = new Synth { Gravity = 0, Stiffness = stiffness };
|
|
var w = Whale(s, out var data);
|
|
w.Swim.AmplitudeDegrees = 0;
|
|
double t = 0, moved = 0;
|
|
for (; t < 2; t += Dt) // jostle the tendrils
|
|
{
|
|
w.Present(t, new Vector3(Mathf.Sin((float)t * 6) * 0.8f, 0, 0), Quaternion.identity, 1);
|
|
moved = math.max(moved, Displacement(w, data, t, default, quaternion.identity));
|
|
}
|
|
if (moved < 0.05) return $"the jostle moved the tendrils only {moved} (vacuous)";
|
|
for (int i = 0; i < 600; i++, t += Dt) w.Present(t, Vector3.zero, Quaternion.identity, 1);
|
|
double worst = Displacement(w, data, t - Dt, default, quaternion.identity) / (s.Joints - 1) / math.length(s.Seg);
|
|
return worst <= 1e-4 ? null : $"stiffness {stiffness}: after 600 frames the worst spring joint is {worst} chain lengths from rest";
|
|
}
|
|
|
|
static string LengthHolds()
|
|
{
|
|
var s = new Synth { Gravity = 0.3f, Stiffness = 3 };
|
|
var w = Whale(s, out var data);
|
|
w.Swim.AmplitudeDegrees = 20;
|
|
double worst = 0;
|
|
for (int i = 0; i < 600; i++)
|
|
{
|
|
double t = i * Dt;
|
|
w.Present(t, new Vector3(Mathf.Sin((float)t * 3) * 2, 0, (float)t * 8), Quaternion.Euler(0, Mathf.Sin((float)t * 2) * 30, 0), 1.5f);
|
|
for (int c = 0; c < data.ChainCount; c++)
|
|
{
|
|
var bones = data.ChainBones(c);
|
|
for (int k = 1; k < bones.Count; k++)
|
|
{
|
|
double rest = math.length(data.RestPosition[bones[k]]) * 1.5, len = math.distance(w.BonePosition(bones[k]), w.BonePosition(bones[k - 1]));
|
|
worst = math.max(worst, math.abs(len - rest) / rest);
|
|
}
|
|
}
|
|
}
|
|
return worst <= 1e-3 ? null : $"worst relative segment error {worst}";
|
|
}
|
|
|
|
// The drawn pose is pushed out of the colliders and length-held twice, which leaves a residual of 0.13% of radius + hit
|
|
// radius at every stiffness from 2 to 60 and 0.18% under a scaled, rotated root (run7; the solver step alone left 0.8% at 2
|
|
// up to 3.9% at 60, Soul). Bound per lodur:ruling:deterministic-bound-margin: shipped worst 0.18%, least claimed mutant
|
|
// (push-out removed) 100%, bound sqrt(0.0018 x 1.0) = 4%, separation 22 and 25. Mutants that ignore the whale's scale or
|
|
// its bone's rotation read 47% and 100%. Stiffness 60 claims the VRM nudge (a fixed-size pull along the rest axis, which a rate
|
|
// pull is not): it reads 4.6% there against shipped 0.13%, so that case's bound is sqrt(0.0013 x 0.046) = 0.9%, separation 5 and 7.
|
|
static string ColliderPushesOut() =>
|
|
ColliderCase(8, 0.04, 1, Quaternion.identity, Vector3.zero)
|
|
?? ColliderCase(2, 0.04, 1, Quaternion.identity, Vector3.zero)
|
|
?? ColliderCase(20, 0.04, 1, Quaternion.identity, Vector3.zero)
|
|
?? ColliderCase(60, 0.009, 1, Quaternion.identity, Vector3.zero)
|
|
// A scaled, rotated whale: a collider that ignores the whale's scale or its bone's rotation is far from the tendril.
|
|
?? ColliderCase(8, 0.04, 2.2f, Quaternion.Euler(25, 70, 15), new Vector3(4, -3, 9));
|
|
|
|
static string ColliderCase(float stiffness, double bound, float scale, Quaternion rootRot, Vector3 rootPos)
|
|
{
|
|
var s = new Synth { Gravity = 0, Stiffness = stiffness };
|
|
var hostA = s.Host(0); var hostB = s.Host(1);
|
|
s.Colliders = new JArray
|
|
{
|
|
Collider(hostA, "sphere", s.JointRest(0, 3), null, 0.12f),
|
|
Collider(hostB, "capsule", s.JointRest(1, 3) + new float3(-0.2f, 0, 0), s.JointRest(1, 3) + new float3(0.2f, 0, 0), 0.12f),
|
|
};
|
|
var w = Whale(s, out var data);
|
|
w.Swim.AmplitudeDegrees = 0;
|
|
w.Present(0, rootPos, rootRot, scale);
|
|
double worst = 0; // deepest penetration as a fraction of radius + hit radius
|
|
for (int i = 1; i < 240; i++)
|
|
{
|
|
w.Present(i * Dt, rootPos, rootRot, scale);
|
|
foreach (var col in data.Colliders)
|
|
for (int c = 0; c < data.ChainCount; c++)
|
|
{
|
|
var bones = data.ChainBones(c);
|
|
for (int k = 1; k < bones.Count; k++)
|
|
{
|
|
float3 origin = w.BonePosition(col.Bone), a = origin + math.mul(w.BoneRotation(col.Bone), col.Offset * scale), b = origin + math.mul(w.BoneRotation(col.Bone), col.Tail * scale);
|
|
float3 seg = b - a, p = w.BonePosition(bones[k]);
|
|
float3 near = col.Capsule ? a + seg * math.saturate(math.dot(p - a, seg) / math.max(math.lengthsq(seg), 1e-12f)) : a;
|
|
float reach = (col.Radius + data.ChainJoint(c, k - 1).HitRadius) * scale;
|
|
worst = math.max(worst, (reach - math.distance(p, near)) / reach);
|
|
}
|
|
}
|
|
}
|
|
Debug.Log($"{Tag} collider residual: stiffness {stiffness}, scale {scale}: {worst:P2} of reach");
|
|
return worst <= bound ? null : $"stiffness {stiffness}, scale {scale}: a joint ends a frame {worst:P1} of its reach inside a collider (bound {bound:P0})";
|
|
}
|
|
|
|
static string FixedSubsteps()
|
|
{
|
|
long Run(int fps, int seconds)
|
|
{
|
|
var w = Whale(new Synth(), out _);
|
|
for (int i = 0; i <= fps * seconds; i++) w.Present(i / (double)fps, Vector3.zero, Quaternion.identity, 1);
|
|
return w.SubstepsRun;
|
|
}
|
|
long a = Run(30, 3), b = Run(144, 3);
|
|
if (a != 360 || b != 360) return $"3 s ran {a} substeps at 30 fps and {b} at 144 fps; floor(3 x 120) = 360";
|
|
// Below 30 fps a frame owes more than the 4 it may run: the tendrils run slow (the clamp), they do not spiral.
|
|
long slow = Run(24, 3);
|
|
if (slow != 4 * 24 * 3) return $"3 s at 24 fps ran {slow} substeps, not the clamped {4 * 24 * 3}";
|
|
var hitch = Whale(new Synth(), out _);
|
|
hitch.Present(0, Vector3.zero, Quaternion.identity, 1);
|
|
hitch.Present(0.5, Vector3.zero, Quaternion.identity, 1);
|
|
return hitch.SubstepsRun == 4 ? null : $"a half-second hitch ran {hitch.SubstepsRun} substeps, not 4";
|
|
}
|
|
|
|
static string PauseFreezes()
|
|
{
|
|
var w = Whale(new Synth { Gravity = 0.3f }, out _);
|
|
double t = 0;
|
|
for (int i = 0; i < 90; i++, t += Dt) w.Present(t, new Vector3(Mathf.Sin((float)t * 4), 0, (float)t * 5), Quaternion.Euler(0, (float)t * 20, 0), 1);
|
|
t -= Dt;
|
|
var pose = new Vector3(Mathf.Sin((float)t * 4), 0, (float)t * 5);
|
|
w.Present(t, pose, Quaternion.Euler(0, (float)t * 20, 0), 1);
|
|
var first = w.Skin.ToArray();
|
|
for (int i = 0; i < 10; i++)
|
|
{
|
|
w.Present(t, pose, Quaternion.Euler(0, (float)t * 20, 0), 1);
|
|
var now = w.Skin.ToArray();
|
|
for (int j = 0; j < now.Length; j++)
|
|
if (!BitEqual(first[j], now[j])) return $"bone {j} changed on held frame {i + 1}";
|
|
}
|
|
return null;
|
|
}
|
|
|
|
static string SwimClosedForm()
|
|
{
|
|
var one = Whale(new Synth(), out var data);
|
|
var many = Whale(new Synth(), out _);
|
|
one.Present(5.0, Vector3.zero, Quaternion.identity, 1);
|
|
for (int i = 0; i <= 100; i++) many.Present(5.0 * i / 100, Vector3.zero, Quaternion.identity, 1);
|
|
var a = one.Skin.ToArray(); var b = many.Skin.ToArray();
|
|
bool moves = false;
|
|
for (int i = 0; i < data.BoneCount; i++)
|
|
{
|
|
if (!data.IsBody[i]) continue;
|
|
if (!BitEqual(a[i], b[i])) return $"body bone {i} differs between 1 and 100 frames";
|
|
moves |= !BitEqual(a[i], float4x4.identity);
|
|
}
|
|
return moves ? null : "the swim moved nothing (vacuous)";
|
|
}
|
|
|
|
static string FreezeAndReset()
|
|
{
|
|
var cam = new GameObject("lodCam").AddComponent<Camera>();
|
|
Scrap.Add(cam.gameObject);
|
|
cam.fieldOfView = 60;
|
|
var s = new Synth { Gravity = 0, Stiffness = 4 };
|
|
var w = Whale(s, out var data);
|
|
w.LodCamera = cam;
|
|
w.Swim.AmplitudeDegrees = 0;
|
|
cam.transform.position = new Vector3(0, 0, -50);
|
|
double t = 0;
|
|
for (; t < 3; t += Dt) w.Present(t, new Vector3(Mathf.Sin((float)t * 5), 0, 0), Quaternion.identity, 1);
|
|
if (w.Level != SpringLod.Full) return "near whale is not Full";
|
|
// Far: frozen. Tendrils at rest on the swimming body, no solver job.
|
|
// Leaving Full the tendrils ease to rest instead of snapping: the first frozen frame moves a tip, relative to its chain root, a
|
|
// small part of the chain (a snap is about half of it).
|
|
var chain = data.ChainBones(0);
|
|
float3 Rel() => w.BonePosition(chain[chain.Count - 1]) - w.BonePosition(chain[0]);
|
|
var relBefore = Rel();
|
|
cam.transform.position = new Vector3(0, 0, -300);
|
|
w.Present(t, new Vector3(Mathf.Sin((float)t * 5), 0, 0), Quaternion.identity, 1);
|
|
double snap = math.distance(Rel(), relBefore) / ((s.Joints - 1) * math.length(s.Seg));
|
|
if (snap > 0.15) return $"the first frozen frame moved a tip {snap:P0} of its chain (a snap, not an ease)";
|
|
t += Dt;
|
|
w.Swim.AmplitudeDegrees = 15;
|
|
for (int i = 0, eased = (int)math.ceil(w.BlendSeconds / Dt) + 2; i < eased; i++, t += Dt) w.Present(t, new Vector3(Mathf.Sin((float)t * 5), 0, 0), Quaternion.identity, 1); // the ease ends at BlendSeconds
|
|
int jobs = w.SolveJobsScheduled;
|
|
double rest = 0;
|
|
for (int i = 0; i < 10; i++, t += Dt)
|
|
{
|
|
var pos = new Vector3(Mathf.Sin((float)t * 5), 0, 0);
|
|
if (w.Present(t, pos, Quaternion.identity, 1) != SpringLod.Frozen) return "far whale is not Frozen";
|
|
Fk(data, t, w.Swim, pos, quaternion.identity, 1, out var fp, out _);
|
|
for (int b = 0; b < data.BoneCount; b++) rest = math.max(rest, math.distance(fp[b], w.BonePosition(b)));
|
|
}
|
|
if (w.SolveJobsScheduled != jobs) return "a solver job ran while frozen";
|
|
if (rest > 1e-4) return $"frozen tendrils are {rest} from rest on the swimming body";
|
|
// Unfreeze with the body still: the stale perturbed state must not show.
|
|
w.Swim.AmplitudeDegrees = 0;
|
|
var held = new Vector3(Mathf.Sin((float)(t - Dt) * 5), 0, 0);
|
|
w.Present(t, held, Quaternion.identity, 1); // still frozen, at the amplitude-0 pose
|
|
var before = Positions(w, data);
|
|
cam.transform.position = new Vector3(0, 0, -50);
|
|
t += Dt;
|
|
if (w.Present(t, held, Quaternion.identity, 1) != SpringLod.Full) return "near whale did not return to Full";
|
|
double joint = Max(before, Positions(w, data), data, springs: true);
|
|
if (joint > 1e-4) return $"unfreeze: first frame moved a spring joint {joint}, body moved 0";
|
|
// A root jump longer than the longest chain, in one frame.
|
|
for (int i = 0; i < 60; i++) { t += Dt; w.Present(t, held + new Vector3(Mathf.Sin(i * 0.5f) * 0.5f, 0, 0), Quaternion.identity, 1); }
|
|
before = Positions(w, data);
|
|
int resets = w.Resets;
|
|
t += Dt;
|
|
var jumped = held + new Vector3(0, 0, 50);
|
|
w.Present(t, jumped, Quaternion.identity, 1);
|
|
if (w.Resets != resets + 1) return "a root jump did not reset";
|
|
var after = Positions(w, data);
|
|
// The joints come to rest on the jumped body (so they moved no more than the body plus the pre-jump lag), not stretched behind it.
|
|
double lag = Displacement(w, data, t, jumped, quaternion.identity);
|
|
return lag <= 1e-3 ? null : $"root jump: a spring joint is {lag} from rest on the body in the first frame";
|
|
}
|
|
|
|
static string SkinMatchesCpu()
|
|
{
|
|
var s = new Synth { Spine = 3, Chains = 2, Joints = 3, Gravity = 0.2f, Stiffness = 4 };
|
|
var go = new GameObject("skinTest");
|
|
Scrap.Add(go);
|
|
var rig = go.AddComponent<SpringRig>();
|
|
var data = SpringRigData.FromGlbJson(s.Build(out var bin), bin);
|
|
var (verts, tris) = BoneTriangles(data);
|
|
var mesh = MakeMesh(verts, tris);
|
|
Scrap.Add(go);
|
|
go.AddComponent<MeshFilter>().sharedMesh = mesh;
|
|
var mr = go.AddComponent<MeshRenderer>();
|
|
mr.sharedMaterial = SkinMaterial(0);
|
|
rig.Renderer = mr;
|
|
rig.Swim.AmplitudeDegrees = 25;
|
|
rig.Initialize(data, mesh.bounds);
|
|
double t = 0;
|
|
for (int i = 0; i < 90; i++, t += Dt) rig.Present(t, new Vector3(0, 0, (float)t * 2), Quaternion.Euler(0, 20, 0), 1.3f);
|
|
|
|
var localToWorld = go.transform.localToWorldMatrix;
|
|
var world = new Vector3[verts.Count];
|
|
var skin = rig.Skin;
|
|
for (int v = 0; v < verts.Count; v++)
|
|
{
|
|
float3 p = 0;
|
|
var vert = verts[v];
|
|
p += vert.w.x * math.mul(skin[(int)vert.b0], new float4(vert.p, 1)).xyz + vert.w.y * math.mul(skin[(int)vert.b1], new float4(vert.p, 1)).xyz;
|
|
world[v] = localToWorld.MultiplyPoint3x4(p);
|
|
}
|
|
const int size = 256;
|
|
var bounds = new Bounds(world[0], Vector3.zero);
|
|
foreach (var p in world) bounds.Encapsulate(p);
|
|
var cam = new GameObject("skinCam").AddComponent<Camera>();
|
|
Scrap.Add(cam.gameObject);
|
|
cam.orthographic = true;
|
|
cam.orthographicSize = Mathf.Max(bounds.extents.y, bounds.extents.z) * 1.15f;
|
|
cam.transform.SetPositionAndRotation(bounds.center + new Vector3(10, 0, 0), Quaternion.LookRotation(Vector3.left));
|
|
cam.clearFlags = CameraClearFlags.SolidColor;
|
|
cam.backgroundColor = Color.black;
|
|
cam.nearClipPlane = 0.1f; cam.farClipPlane = 50;
|
|
var rt = new RenderTexture(size, size, 24, RenderTextureFormat.ARGB32);
|
|
cam.targetTexture = rt;
|
|
RenderSettings.ambientMode = AmbientMode.Flat;
|
|
RenderSettings.ambientLight = Color.white;
|
|
cam.Render();
|
|
var read = new Texture2D(size, size, TextureFormat.RGBA32, false);
|
|
RenderTexture.active = rt;
|
|
read.ReadPixels(new Rect(0, 0, size, size), 0, 0);
|
|
read.Apply();
|
|
RenderTexture.active = null;
|
|
var gpu = read.GetPixels32().Select(c => c.r > 8 || c.g > 8 || c.b > 8).ToArray();
|
|
var cpu = new bool[size * size];
|
|
for (int i = 0; i < tris.Count; i += 3)
|
|
{
|
|
var a = (Vector2)cam.WorldToScreenPoint(world[tris[i]]); var b = (Vector2)cam.WorldToScreenPoint(world[tris[i + 1]]); var c = (Vector2)cam.WorldToScreenPoint(world[tris[i + 2]]);
|
|
for (int y = 0; y < size; y++)
|
|
for (int x = 0; x < size; x++)
|
|
{
|
|
var p = new Vector2(x + 0.5f, y + 0.5f);
|
|
float d1 = Edge(p, a, b), d2 = Edge(p, b, c), d3 = Edge(p, c, a);
|
|
if ((d1 >= 0 && d2 >= 0 && d3 >= 0) || (d1 <= 0 && d2 <= 0 && d3 <= 0)) cpu[y * size + x] = true;
|
|
}
|
|
}
|
|
UnityEngine.Object.DestroyImmediate(rt);
|
|
int lit = cpu.Count(x => x);
|
|
if (lit < 400) return $"only {lit} px covered (vacuous)";
|
|
int stray = 0;
|
|
for (int y = 0; y < size; y++)
|
|
for (int x = 0; x < size; x++)
|
|
{
|
|
if (gpu[y * size + x] && !Near(cpu, x, y, size)) stray++;
|
|
if (cpu[y * size + x] && !Near(gpu, x, y, size)) stray++;
|
|
}
|
|
return stray == 0 ? null : $"{stray} px differ by more than 1 px between the shader and the CPU skin ({lit} px covered)";
|
|
}
|
|
|
|
static string CostBound()
|
|
{
|
|
var s = new Synth { Spine = 12, Chains = 110, Joints = 7 };
|
|
var whales = Enumerable.Range(0, 3).Select(i => Whale(s, out var unused)).ToArray();
|
|
var debugger = Unity.Jobs.LowLevel.Unsafe.JobsUtility.JobDebuggerEnabled;
|
|
Unity.Jobs.LowLevel.Unsafe.JobsUtility.JobDebuggerEnabled = false;
|
|
// Paired interleaved readings: rounds of 60 frames (10 warm-up), Burst on then off, five rounds; shipped worst and least mutant.
|
|
double Block(int round)
|
|
{
|
|
var ms = new List<double>();
|
|
for (int f = 0; f < 70; f++)
|
|
{
|
|
double t = (round * 70 + f) * Dt;
|
|
long start = Stopwatch.GetTimestamp();
|
|
for (int i = 0; i < whales.Length; i++)
|
|
whales[i].Present(t, new Vector3(i * 30 + Mathf.Sin((float)t * 3), 0, (float)t * 6), Quaternion.Euler(0, (float)t * 10, 0), 4);
|
|
if (f >= 10) ms.Add((Stopwatch.GetTimestamp() - start) * 1000.0 / Stopwatch.Frequency);
|
|
}
|
|
ms.Sort();
|
|
return ms[ms.Count / 2];
|
|
}
|
|
double shipped = 0, mutant = double.MaxValue;
|
|
try
|
|
{
|
|
for (int round = 0; round < 5; round++)
|
|
{
|
|
Unity.Burst.BurstCompiler.Options.EnableBurstCompilation = true;
|
|
shipped = math.max(shipped, Block(round * 2));
|
|
Unity.Burst.BurstCompiler.Options.EnableBurstCompilation = false;
|
|
mutant = math.min(mutant, Block(round * 2 + 1));
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
Unity.Burst.BurstCompiler.Options.EnableBurstCompilation = true;
|
|
Unity.Jobs.LowLevel.Unsafe.JobsUtility.JobDebuggerEnabled = debugger;
|
|
}
|
|
// The write-back alone: one GraphicsBuffer.SetData of a whale's skin matrices.
|
|
var upload = new Unity.Collections.NativeArray<float4x4>(whales[0].Data.BoneCount, Unity.Collections.Allocator.Temp);
|
|
var uploads = new List<double>();
|
|
for (int i = 0; i < 300; i++)
|
|
{
|
|
long start = Stopwatch.GetTimestamp();
|
|
whales[0].SkinBuffer.SetData(upload);
|
|
uploads.Add((Stopwatch.GetTimestamp() - start) * 1000.0 / Stopwatch.Frequency);
|
|
}
|
|
upload.Dispose();
|
|
uploads.Sort();
|
|
Debug.Log($"{Tag} cost-bound: 3 whales x 770 joints, median ms per frame, paired rounds: shipped worst {shipped:F3}, Burst-off least {mutant:F3}, ratio {mutant / shipped:F2}; bound {CostBoundMs}; skin upload alone {uploads[uploads.Count / 2]:F4} ms per whale");
|
|
if (shipped * 1.2 > CostBoundMs) return $"shipped {shipped:F3} ms is not 1.2x under the bound {CostBoundMs}";
|
|
if (mutant < CostBoundMs * 1.2) return $"the Burst-off mutant {mutant:F3} ms is not 1.2x over the bound {CostBoundMs}";
|
|
return null;
|
|
}
|
|
|
|
|
|
// ---------------------------------------------------------------- checks added after Soul's pass
|
|
|
|
// The drawn pose holds segment length on every rendered frame at any refresh rate, including frames that owe no substep
|
|
// (144 fps runs one frame in six of them) and uneven frame times.
|
|
static string LengthsHoldAtAnyRate()
|
|
{
|
|
var rng = new System.Random(7);
|
|
foreach (var (name, next) in new (string, Func<double>)[] { ("144 fps", () => 1.0 / 144), ("165 fps", () => 1.0 / 165), ("240 fps", () => 1.0 / 240),
|
|
("uneven", () => 1.0 / (45 + rng.Next(0, 200))) })
|
|
{
|
|
var s = new Synth { Gravity = 0.3f, Stiffness = 3 };
|
|
var w = Whale(s, out var data);
|
|
w.Swim.AmplitudeDegrees = 20;
|
|
double t = 0, worst = 0;
|
|
long zero = 0;
|
|
for (int i = 0; i < 700; i++, t += next())
|
|
{
|
|
long before = w.SubstepsRun;
|
|
w.Present(t, new Vector3(Mathf.Sin((float)t * 3) * 2, 0, (float)t * 8), Quaternion.Euler(0, Mathf.Sin((float)t * 2) * 30, 0), 1.5f);
|
|
if (i > 0 && w.SubstepsRun == before) zero++;
|
|
for (int c = 0; c < data.ChainCount; c++)
|
|
{
|
|
var bones = data.ChainBones(c);
|
|
for (int k = 1; k < bones.Count; k++)
|
|
{
|
|
double rest = math.length(data.RestPosition[bones[k]]) * 1.5, len = math.distance(w.BonePosition(bones[k]), w.BonePosition(bones[k - 1]));
|
|
worst = math.max(worst, math.abs(len - rest) / rest);
|
|
}
|
|
}
|
|
}
|
|
if (zero < 20) return $"{name}: only {zero} frames owed no substep (vacuous)";
|
|
if (worst > 1e-3) return $"{name}: worst relative segment error {worst} over {zero} no-substep frames";
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// A tendril on a body moving steadily trails it by a constant offset; the offset must not beat with the frame rate. At 144 fps
|
|
// an un-interpolated pose holds the tail for the frames that owe no step. Bound per lodur:ruling:deterministic-bound-margin:
|
|
// shipped worst 1.0e-5 (runs 0.76e-5, 1.0e-5; float32 positions near z = 36), least mutant 1.3e-4 (pose not interpolated: the
|
|
// fraction forced to 0), bound sqrt(1.0e-5 x 1.3e-4) = 3.6e-5, separation 3.6 on each side.
|
|
const double BeatBound = 3.6e-5;
|
|
static string SteadyMotionIsSmooth()
|
|
{
|
|
var s = new Synth { Gravity = 0, Stiffness = 3, Drag = 0.5f };
|
|
var w = Whale(s, out var data);
|
|
w.Swim.AmplitudeDegrees = 0;
|
|
double t = 0, lo = double.MaxValue, hi = double.MinValue;
|
|
int tip = data.ChainBones(0)[data.ChainBones(0).Count - 1];
|
|
for (int i = 0; i < 144 * 6; i++, t += 1.0 / 144)
|
|
{
|
|
var pos = new Vector3(0, 0, (float)t * 6f);
|
|
w.Present(t, pos, Quaternion.identity, 1);
|
|
if (i >= 144 * 4) { double lag = pos.z - w.BonePosition(tip).z; lo = math.min(lo, lag); hi = math.max(hi, lag); }
|
|
}
|
|
Debug.Log($"{Tag} steady-motion: tip lag spread {hi - lo:F5} u at 6 u/s, 144 fps");
|
|
return hi - lo <= BeatBound ? null : $"the tip's lag behind a steadily moving body beats by {hi - lo} u (bound {BeatBound})";
|
|
}
|
|
|
|
// Inertia: a tendril dragged behind a body that stops swings forward past rest (velocity carried, light drag); a pull alone only
|
|
// creeps back. Without the velocity term the overshoot is nil.
|
|
static string InertiaCarries()
|
|
{
|
|
var s = new Synth { Chains = 2, Gravity = 0, Stiffness = 1.5f, Drag = 0.05f, Colliders = new JArray() };
|
|
var w = Whale(s, out var data);
|
|
w.Swim.AmplitudeDegrees = 0;
|
|
var chain = data.ChainBones(0);
|
|
int tip = chain[chain.Count - 1];
|
|
double t = 0, overshoot = double.MinValue;
|
|
for (int i = 0; i < 60; i++, t += Dt) w.Present(t, new Vector3(0, 0, i * 4f / 60), Quaternion.identity, 1);
|
|
var stop = new Vector3(0, 0, 59 * 4f / 60);
|
|
Fk(data, 0, NoSwim, stop, quaternion.identity, 1, out var rest, out _);
|
|
for (int i = 0; i < 180; i++, t += Dt)
|
|
{
|
|
w.Present(t, stop, Quaternion.identity, 1);
|
|
overshoot = math.max(overshoot, w.BonePosition(tip).z - rest[tip].z);
|
|
}
|
|
Debug.Log($"{Tag} inertia: tip overshoot past rest along the motion {overshoot:F5} u");
|
|
return overshoot >= InertiaBound ? null : $"after the body stops the tip overshoots rest by {overshoot} u, expected at least {InertiaBound}";
|
|
}
|
|
// Shipped overshoot 1.15 u, no-inertia mutant -0.03 u (it only creeps back): the bound sits between, at 0.5.
|
|
const double InertiaBound = 0.5;
|
|
|
|
// The skin matrices are the product they claim to be, checked against forward kinematics that shares no code with the jobs,
|
|
// on a rig with rotated rest bones, exact inverse bind matrices, a swimming body and a scaled, rotated root.
|
|
static string SkinMatchesFk()
|
|
{
|
|
var s = new Synth { Spine = 4, Chains = 3, Joints = 4, Rot = true, Colliders = new JArray() };
|
|
var w = Whale(s, out var data);
|
|
w.Swim = new SwimSettings { AmplitudeDegrees = 20, PeriodSeconds = 2, PhasePerBone = 0.15f, Axis = new float3(0.3f, 1, 0.5f) };
|
|
var pos = new Vector3(3, -2, 5); var rot = Quaternion.Euler(25, 70, 15); const float scale = 2.5f; const double t = 1.3;
|
|
w.Present(t, pos, rot, scale); // the first frame: tendrils reset to rest on the posed body
|
|
Fk(data, t, w.Swim, pos, rot, scale, out var fp, out var fr);
|
|
var inverse = math.inverse(float4x4.TRS(pos, rot, new float3(scale)));
|
|
double worst = 0;
|
|
for (int i = 0; i < data.BoneCount; i++)
|
|
{
|
|
var expect = math.mul(inverse, math.mul(float4x4.TRS(fp[i], fr[i], new float3(scale)), data.BindPose[i]));
|
|
var got = w.Skin[i];
|
|
worst = math.max(worst, math.max(math.cmax(math.abs(expect.c0 - got.c0)), math.max(math.cmax(math.abs(expect.c1 - got.c1)), math.max(math.cmax(math.abs(expect.c2 - got.c2)), math.cmax(math.abs(expect.c3 - got.c3))))));
|
|
}
|
|
if (worst > 1e-3) return $"skin matrices are {worst} from rootInverse x boneWorld x bindPose";
|
|
// Exact inverse bind matrices: the unswum, unmoved rig at rest has the identity for every skin matrix.
|
|
var rest = Whale(s, out _);
|
|
rest.Swim.AmplitudeDegrees = 0;
|
|
rest.Present(0, pos, rot, scale);
|
|
for (int i = 0; i < data.BoneCount; i++)
|
|
if (math.cmax(math.abs(rest.Skin[i].c0 - float4x4.identity.c0)) + math.cmax(math.abs(rest.Skin[i].c3 - float4x4.identity.c3)) > 1e-3) return $"bone {i} at rest is not the identity";
|
|
return null;
|
|
}
|
|
|
|
// A capsule ends where its tail ends: a joint on the axis line beyond the tail is left alone (an infinite line would push it).
|
|
static string CapsuleIsFinite()
|
|
{
|
|
var s = new Synth { Chains = 2, Gravity = 0, Stiffness = 8 };
|
|
var host = s.Host(1);
|
|
s.Colliders = new JArray { Collider(host, "capsule", s.JointRest(1, 3) + new float3(-0.35f, 0, 0), s.JointRest(1, 3) + new float3(-0.12f, 0, 0), 0.05f) };
|
|
var w = Whale(s, out var data);
|
|
w.Swim.AmplitudeDegrees = 0;
|
|
for (int i = 0; i < 240; i++) w.Present(i * Dt, Vector3.zero, Quaternion.identity, 1);
|
|
double moved = Displacement(w, data, 0, default, quaternion.identity);
|
|
return moved <= 1e-3 ? null : $"a joint beyond the capsule's tail moved {moved}";
|
|
}
|
|
|
|
// Gravity moves the tendrils along the world direction, whatever the whale's orientation.
|
|
static string GravitySags()
|
|
{
|
|
var s = new Synth { Chains = 4, Gravity = 3, Stiffness = 6, GravityDir = new float3(0, 0, 1), Colliders = new JArray() };
|
|
var w = Whale(s, out var data);
|
|
w.Swim.AmplitudeDegrees = 0;
|
|
var rot = Quaternion.Euler(0, 90, 0);
|
|
for (int i = 0; i < 300; i++) w.Present(i * Dt, Vector3.zero, rot, 1);
|
|
Fk(data, 0, w.Swim, default, rot, 1, out var rest, out _);
|
|
double sag = 0; int n = 0;
|
|
for (int b = 0; b < data.BoneCount; b++)
|
|
if (!data.IsBody[b]) { sag += w.BonePosition(b).z - rest[b].z; n++; }
|
|
sag /= n;
|
|
return sag >= 0.05 ? null : $"mean sag along the world gravity direction is {sag}, expected at least 0.05";
|
|
}
|
|
|
|
// The root-jump threshold is a chain length in world units: a whale scaled 4x moving 3 u a frame is not jumping.
|
|
static string ResetHonoursScale()
|
|
{
|
|
var w = Whale(new Synth(), out _);
|
|
for (int i = 0; i < 60; i++) w.Present(i * Dt, new Vector3(3 * i, 0, 0), Quaternion.identity, 4);
|
|
var jumped = Whale(new Synth(), out _);
|
|
for (int i = 0; i < 60; i++) jumped.Present(i * Dt, new Vector3(i == 30 ? 500 : 0, 0, 0), Quaternion.identity, 4);
|
|
if (w.Resets != 1) return $"steady motion at scale 4 reset {w.Resets} times, not once";
|
|
return jumped.Resets == 3 ? null : $"a jump of 500 u at scale 4 reset {jumped.Resets - 1} extra times, expected 2 (out and back)";
|
|
}
|
|
|
|
// Bounds follow the pose: every skinned vertex stays inside the renderer's bounds at a swim amplitude that moves the body, at a
|
|
// scale above 1 (a bounds job that ignores scale is too large, which still holds every vertex) and below it (too small).
|
|
static string BoundsFollowTheSwim() => BoundsCase(1.5f) ?? BoundsCase(0.6f);
|
|
|
|
static string BoundsCase(float scale)
|
|
{
|
|
var s = new Synth { Gravity = 0.5f, Stiffness = 2, Colliders = new JArray() };
|
|
var go = new GameObject("boundsTest");
|
|
Scrap.Add(go);
|
|
var rig = go.AddComponent<SpringRig>();
|
|
var data = SpringRigData.FromGlbJson(s.Build(out var bin), bin);
|
|
var (verts, tris) = BoneTriangles(data);
|
|
var mesh = MakeMesh(verts, tris);
|
|
go.AddComponent<MeshFilter>().sharedMesh = mesh;
|
|
rig.Renderer = go.AddComponent<MeshRenderer>();
|
|
rig.Swim = new SwimSettings { AmplitudeDegrees = 25, PeriodSeconds = 2, PhasePerBone = 0.15f, Axis = new float3(1, 0, 0) };
|
|
rig.Initialize(data, mesh.bounds);
|
|
double worst = 0; Bounds first = default, last = default;
|
|
for (int f = 0; f < 300; f++)
|
|
{
|
|
rig.Present(f * Dt, new Vector3(0, 0, f * 0.05f), Quaternion.Euler(0, f * 0.5f, 0), scale);
|
|
var b = rig.Renderer.localBounds;
|
|
if (f == 0) first = b; last = b;
|
|
for (int v = 0; v < verts.Count; v++)
|
|
{
|
|
float4 p = new float4(verts[v].p, 1);
|
|
float3 skinned = verts[v].w.x * math.mul(rig.Skin[(int)verts[v].b0], p).xyz + verts[v].w.y * math.mul(rig.Skin[(int)verts[v].b1], p).xyz;
|
|
float3 outside = math.max(math.abs(skinned - (float3)b.center) - (float3)b.extents, 0f);
|
|
worst = math.max(worst, math.cmax(outside));
|
|
}
|
|
}
|
|
if (worst > 1e-3) return $"at scale {scale} a skinned vertex lies {worst} outside the bounds";
|
|
return first.size != last.size ? null : $"at scale {scale} the bounds never changed (vacuous)";
|
|
}
|
|
|
|
// Returning to Full part way through the ease continues from the pose last drawn: the returning frame moves a tip, relative to its
|
|
// chain root, a small part of the chain; a reset to rest moves it by nearly all of the distance the tip had left (Soul read 96% of
|
|
// the chain after 3 frames out with the old quarter-second ease). Readings with the 0.75 s ease, the largest over the two cases
|
|
// (3 and 8 frames out): shipped 0.172; the reset-to-rest mutant least 0.970 (0.970 and 1.207). The bound is
|
|
// lodur:ruling:deterministic-bound-margin's geometric mean sqrt(0.172 x 0.970) = 0.41, a separation of 2.4 on each side.
|
|
const double ReentryBound = 0.41;
|
|
|
|
static string ReentryIsContinuous()
|
|
{
|
|
// The ease default reads as settling, not as a flare (finding ease-moves-fast: 0.5 to 1 s).
|
|
var defaults = new GameObject("easeDefault");
|
|
Scrap.Add(defaults);
|
|
float blend = defaults.AddComponent<SpringRig>().BlendSeconds;
|
|
if (blend < 0.5f || blend > 1f) return $"BlendSeconds defaults to {blend}, not in 0.5 to 1";
|
|
var shortOut = ReentryCase(3);
|
|
var longOut = ReentryCase(8); // both run, so both readings are logged
|
|
return shortOut ?? longOut;
|
|
}
|
|
|
|
static string ReentryCase(int framesOut)
|
|
{
|
|
var cam = new GameObject("lodCam").AddComponent<Camera>();
|
|
Scrap.Add(cam.gameObject);
|
|
cam.fieldOfView = 60;
|
|
var s = new Synth { Gravity = 0, Stiffness = 4 };
|
|
var w = Whale(s, out var data);
|
|
w.LodCamera = cam;
|
|
w.Swim.AmplitudeDegrees = 0;
|
|
var chains = Enumerable.Range(0, data.ChainCount).Select(c => data.ChainBones(c)).ToArray();
|
|
float3[] Rel() => chains.Select(b => w.BonePosition(b[b.Count - 1]) - w.BonePosition(b[0])).ToArray();
|
|
double chainLength = (s.Joints - 1) * math.length(s.Seg);
|
|
cam.transform.position = new Vector3(0, 0, -50);
|
|
double t = 0;
|
|
Vector3 At() => new Vector3(Mathf.Sin((float)t * 5) * 3.2f, 0, 0);
|
|
for (; t < 3; t += Dt) w.Present(t, At(), Quaternion.identity, 1);
|
|
if (w.Level != SpringLod.Full) return "near whale is not Full";
|
|
cam.transform.position = new Vector3(0, 0, -300);
|
|
for (int i = 0; i < framesOut; i++, t += Dt) w.Present(t, At(), Quaternion.identity, 1);
|
|
if (w.Level != SpringLod.Frozen) return "far whale is not Frozen";
|
|
var drawn = Rel();
|
|
cam.transform.position = new Vector3(0, 0, -50);
|
|
if (w.Present(t, At(), Quaternion.identity, 1) != SpringLod.Full) return "near whale did not return to Full";
|
|
var back = Rel();
|
|
double moved = 0;
|
|
for (int c = 0; c < drawn.Length; c++) moved = math.max(moved, math.distance(back[c], drawn[c]) / chainLength);
|
|
Debug.Log($"{Tag} reentry after {framesOut} frames out: the returning frame moved a tip {moved:P1} of its chain (bound {ReentryBound:P1})");
|
|
return moved <= ReentryBound ? null : $"returning after {framesOut} frames out moved a tip {moved:P0} of its chain in one frame (a reset to rest, not a continuation)";
|
|
}
|
|
|
|
// A root jump while the ease is part way still resets to rest: the returning frame's tips lie on the body's rest pose, not on the
|
|
// stale drawn pose far away. Readings (largest distance of a spring joint from its rest place, in units; the chain is 1.2 long):
|
|
// shipped 8.4e-8, a solver seeded from the stale drawn pose 1.79; bound sqrt(8.4e-8 x 1.79) = 3.9e-4..
|
|
const double JumpBound = 3.9e-4;
|
|
|
|
static string RootJumpResets()
|
|
{
|
|
var cam = new GameObject("lodCam").AddComponent<Camera>();
|
|
Scrap.Add(cam.gameObject);
|
|
cam.fieldOfView = 60;
|
|
var w = Whale(new Synth { Gravity = 0, Stiffness = 4 }, out var data);
|
|
w.LodCamera = cam;
|
|
w.Swim.AmplitudeDegrees = 0;
|
|
double t = 0;
|
|
Vector3 at = Vector3.zero;
|
|
void Frame(float back) { cam.transform.position = at + new Vector3(0, 0, -back); w.Present(t, at, Quaternion.identity, 1); t += Dt; }
|
|
for (; t < 3;) { at = new Vector3(Mathf.Sin((float)t * 5) * 3.2f, 0, 0); Frame(50); }
|
|
for (int i = 0; i < 3; i++) Frame(300);
|
|
at = new Vector3(500, 0, 0);
|
|
Frame(50);
|
|
double off = Displacement(w, data, t - Dt, at, quaternion.identity);
|
|
Debug.Log($"{Tag} root jump during the ease: a spring joint {off:F4} u from rest on the returning frame (bound {JumpBound})");
|
|
return off <= JumpBound ? null : $"after a root jump a spring joint is {off} from rest: the solver was seeded from the stale pose";
|
|
}
|
|
|
|
// The shadow caster skins like the body: a ShadowsOnly leviathan swimming at 40 degrees under a light pointing straight down casts, on
|
|
// a floor seen from above, the silhouette of its skinned triangles, not of its rest triangles. Intersection over union against the CPU
|
|
// projection of the skinned triangles. Readings: shipped 0.877; a caster that compiles the empty stub 0.330 (and 0.879 to the rest
|
|
// triangles). The bound is lodur:ruling:deterministic-bound-margin's geometric mean sqrt(0.877 x 0.330) = 0.538, separation 1.63 each side.
|
|
const double ShadowBound = 0.538;
|
|
|
|
static string ShadowIsSkinned()
|
|
{
|
|
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(AssetPath);
|
|
if (prefab == null) return $"{AssetPath} imported no main object";
|
|
var (shadows, distance, resolution) = (QualitySettings.shadows, QualitySettings.shadowDistance, QualitySettings.shadowResolution);
|
|
var (ambientMode, ambient) = (RenderSettings.ambientMode, RenderSettings.ambientLight);
|
|
try
|
|
{
|
|
var go = UnityEngine.Object.Instantiate(prefab);
|
|
Scrap.Add(go);
|
|
var rig = go.GetComponent<SpringRig>();
|
|
rig.Initialize();
|
|
rig.Swim.AmplitudeDegrees = 40;
|
|
go.GetComponent<MeshRenderer>().shadowCastingMode = ShadowCastingMode.ShadowsOnly;
|
|
QualitySettings.shadows = ShadowQuality.All; QualitySettings.shadowDistance = 20; QualitySettings.shadowResolution = UnityEngine.ShadowResolution.VeryHigh;
|
|
var light = new GameObject("sun").AddComponent<Light>();
|
|
Scrap.Add(light.gameObject);
|
|
light.type = LightType.Directional; light.intensity = 1.2f; light.shadows = LightShadows.Hard; light.shadowBias = 0.005f; light.shadowNormalBias = 0f;
|
|
light.transform.rotation = Quaternion.Euler(90, 0, 0);
|
|
RenderSettings.ambientMode = AmbientMode.Flat; RenderSettings.ambientLight = new Color(0.1f, 0.1f, 0.1f);
|
|
double t = 0;
|
|
for (int f = 0; f < 150; f++, t += Dt) rig.Present(t, new Vector3(0, 0.5f, 0), Quaternion.identity, 1);
|
|
var floor = GameObject.CreatePrimitive(PrimitiveType.Plane);
|
|
Scrap.Add(floor);
|
|
floor.transform.position = new Vector3(0, -0.6f, 0); floor.transform.localScale = new Vector3(0.3f, 1, 0.3f);
|
|
floor.GetComponent<Renderer>().sharedMaterial = new Material(Shader.Find("Standard")) { color = Color.white };
|
|
var cam = new GameObject("shadowCam").AddComponent<Camera>();
|
|
Scrap.Add(cam.gameObject);
|
|
cam.orthographic = true; cam.orthographicSize = 0.6f; cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = Color.black;
|
|
cam.transform.position = new Vector3(0, 3, 0); cam.transform.rotation = Quaternion.Euler(90, 0, 0);
|
|
cam.nearClipPlane = 0.1f; cam.farClipPlane = 10;
|
|
const int size = 512;
|
|
var rt = new RenderTexture(size, size, 24, RenderTextureFormat.ARGB32);
|
|
cam.targetTexture = rt;
|
|
cam.Render();
|
|
var read = new Texture2D(size, size, TextureFormat.RGBA32, false);
|
|
RenderTexture.active = rt;
|
|
read.ReadPixels(new Rect(0, 0, size, size), 0, 0);
|
|
RenderTexture.active = null;
|
|
var px = read.GetPixels32();
|
|
int lo = 255, hi = 0;
|
|
foreach (var p in px) { lo = Math.Min(lo, p.r); hi = Math.Max(hi, p.r); }
|
|
if (hi - lo < 40) return $"no shadow on the floor (floor values {lo} to {hi})";
|
|
int threshold = (lo + hi) / 2;
|
|
var gpu = px.Select(p => p.r < threshold).ToArray();
|
|
var mesh = go.GetComponent<MeshFilter>().sharedMesh;
|
|
var verts = mesh.vertices; var weights = mesh.boneWeights;
|
|
var l2w = go.transform.localToWorldMatrix;
|
|
var skinned = new Vector2[verts.Length];
|
|
for (int v = 0; v < verts.Length; v++)
|
|
{
|
|
var p4 = new float4(verts[v], 1); var w = weights[v];
|
|
float3 s = w.weight0 * math.mul(rig.Skin[w.boneIndex0], p4).xyz + w.weight1 * math.mul(rig.Skin[w.boneIndex1], p4).xyz
|
|
+ w.weight2 * math.mul(rig.Skin[w.boneIndex2], p4).xyz + w.weight3 * math.mul(rig.Skin[w.boneIndex3], p4).xyz;
|
|
skinned[v] = (Vector2)cam.WorldToScreenPoint(l2w.MultiplyPoint3x4(s));
|
|
}
|
|
double iou = Iou(gpu, Raster(skinned, mesh.triangles, size));
|
|
UnityEngine.Object.DestroyImmediate(rt);
|
|
Debug.Log($"{Tag} shadow: intersection over union with the skinned triangles' projection {iou:F3} (bound {ShadowBound})");
|
|
return iou >= ShadowBound ? null : $"the shadow matches the skinned silhouette only {iou:F3} (bound {ShadowBound}): the shadow caster is not skinning";
|
|
}
|
|
finally { QualitySettings.shadows = shadows; QualitySettings.shadowDistance = distance; QualitySettings.shadowResolution = resolution; RenderSettings.ambientMode = ambientMode; RenderSettings.ambientLight = ambient; }
|
|
}
|
|
|
|
static bool[] Raster(Vector2[] v, int[] tris, int size)
|
|
{
|
|
var m = new bool[size * size];
|
|
for (int i = 0; i < tris.Length; i += 3)
|
|
{
|
|
var a = v[tris[i]]; var b = v[tris[i + 1]]; var c = v[tris[i + 2]];
|
|
int x0 = Mathf.Max(0, Mathf.FloorToInt(Mathf.Min(a.x, Mathf.Min(b.x, c.x)))), x1 = Mathf.Min(size - 1, Mathf.CeilToInt(Mathf.Max(a.x, Mathf.Max(b.x, c.x))));
|
|
int y0 = Mathf.Max(0, Mathf.FloorToInt(Mathf.Min(a.y, Mathf.Min(b.y, c.y)))), y1 = Mathf.Min(size - 1, Mathf.CeilToInt(Mathf.Max(a.y, Mathf.Max(b.y, c.y))));
|
|
for (int y = y0; y <= y1; y++)
|
|
for (int x = x0; x <= x1; x++)
|
|
{
|
|
var p = new Vector2(x + 0.5f, y + 0.5f);
|
|
float d1 = Edge(p, a, b), d2 = Edge(p, b, c), d3 = Edge(p, c, a);
|
|
if ((d1 >= 0 && d2 >= 0 && d3 >= 0) || (d1 <= 0 && d2 <= 0 && d3 <= 0)) m[y * size + x] = true;
|
|
}
|
|
}
|
|
return m;
|
|
}
|
|
|
|
static double Iou(bool[] a, bool[] b)
|
|
{
|
|
int both = 0, either = 0;
|
|
for (int k = 0; k < a.Length; k++) { if (a[k] && b[k]) both++; if (a[k] || b[k]) either++; }
|
|
return either == 0 ? 0 : (double)both / either;
|
|
}
|
|
|
|
// The normals are skinned with the positions: a whale lit by one directional light pointing straight down (black ambient) whose body is
|
|
// bent about Z turns its triangles' normals (X at rest, so lit by nothing) up toward the light, and reflects light; a shader that skins
|
|
// positions only keeps the normals at X and reflects none. The light the camera sees from the bent whale. Readings: shipped 41253, normals not skinned 13667 (rest 12545); the bound is
|
|
// lodur:ruling:deterministic-bound-margin's geometric mean sqrt(41253 x 13667) = 23744, a separation of 1.74 on each side.
|
|
const double NormalsBound = 23700;
|
|
|
|
static string NormalsAreSkinned()
|
|
{
|
|
var (ambientMode, ambient) = (RenderSettings.ambientMode, RenderSettings.ambientLight);
|
|
try
|
|
{
|
|
var light = new GameObject("normalsSun").AddComponent<Light>();
|
|
Scrap.Add(light.gameObject);
|
|
light.type = LightType.Directional; light.intensity = 1; light.shadows = LightShadows.None;
|
|
light.transform.rotation = Quaternion.Euler(90, 0, 0);
|
|
RenderSettings.ambientMode = AmbientMode.Flat; RenderSettings.ambientLight = Color.black;
|
|
double Seen(float amplitude)
|
|
{
|
|
var s = new Synth { Spine = 2, Chains = 1, Joints = 2, Gravity = 0, Stiffness = 4 };
|
|
var go = new GameObject("normalsTest");
|
|
Scrap.Add(go);
|
|
var rig = go.AddComponent<SpringRig>();
|
|
var data = SpringRigData.FromGlbJson(s.Build(out var bin), bin);
|
|
var (verts, tris) = BoneTriangles(data);
|
|
var mesh = MakeMesh(verts, tris);
|
|
go.AddComponent<MeshFilter>().sharedMesh = mesh;
|
|
var mr = go.AddComponent<MeshRenderer>();
|
|
mr.sharedMaterial = SkinMaterial(0);
|
|
rig.Renderer = mr;
|
|
rig.Swim = new SwimSettings { AmplitudeDegrees = amplitude, PeriodSeconds = 4, PhasePerBone = 0, Axis = new float3(0, 0, 1) };
|
|
rig.Initialize(data, mesh.bounds);
|
|
rig.Present(1.0, Vector3.zero, Quaternion.identity, 1); // a quarter period: the swim at its peak
|
|
var cam = new GameObject("normalsCam").AddComponent<Camera>();
|
|
Scrap.Add(cam.gameObject);
|
|
cam.orthographic = true; cam.orthographicSize = 1.5f;
|
|
cam.transform.SetPositionAndRotation(new Vector3(10, 0, 0.5f), Quaternion.LookRotation(Vector3.left));
|
|
cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = Color.black;
|
|
cam.nearClipPlane = 0.1f; cam.farClipPlane = 50;
|
|
var rt = new RenderTexture(128, 128, 24, RenderTextureFormat.ARGB32);
|
|
cam.targetTexture = rt;
|
|
cam.Render();
|
|
var read = new Texture2D(128, 128, TextureFormat.RGBA32, false);
|
|
RenderTexture.active = rt;
|
|
read.ReadPixels(new Rect(0, 0, 128, 128), 0, 0);
|
|
RenderTexture.active = null;
|
|
UnityEngine.Object.DestroyImmediate(rt);
|
|
double total = 0;
|
|
foreach (var p in read.GetPixels32()) total += p.r + p.g + p.b;
|
|
return total;
|
|
}
|
|
double rest = Seen(0), bent = Seen(40);
|
|
Debug.Log($"{Tag} normals: light seen at rest {rest}, bent 40 degrees {bent} (bound {NormalsBound})");
|
|
return bent >= NormalsBound ? null : $"a whale bent 40 degrees reflects {bent} (at rest {rest}): its normals did not turn with it";
|
|
}
|
|
finally { RenderSettings.ambientMode = ambientMode; RenderSettings.ambientLight = ambient; }
|
|
}
|
|
|
|
// Hovering at the Full threshold must not flip the level every frame.
|
|
static string LodHysteresis()
|
|
{
|
|
var cam = new GameObject("lodCam").AddComponent<Camera>();
|
|
Scrap.Add(cam.gameObject);
|
|
cam.fieldOfView = 60;
|
|
var w = Whale(new Synth(), out _);
|
|
w.LodCamera = cam;
|
|
float threshold = 8.485f / (2f * Mathf.Tan(30 * Mathf.Deg2Rad) * w.FullAbove); // the Whale bounds' diameter over the visible height
|
|
int flips = 0; var level = SpringLod.Hidden;
|
|
for (int i = 0; i < 120; i++)
|
|
{
|
|
cam.transform.position = new Vector3(0, 0, -threshold * (i % 2 == 0 ? 0.99f : 1.01f));
|
|
var now = w.Present(i * Dt, Vector3.zero, Quaternion.identity, 1);
|
|
if (i > 0 && now != level) flips++;
|
|
level = now;
|
|
}
|
|
if (flips > 1) return $"hovering at the threshold flipped the level {flips} times in 120 frames";
|
|
cam.transform.position = new Vector3(0, 0, -threshold * 1.4f);
|
|
return w.Present(121 * Dt, Vector3.zero, Quaternion.identity, 1) == SpringLod.Full ? "a whale 40% farther than the threshold is still Full (vacuous)" : null;
|
|
}
|
|
|
|
// The rig and a glTFast-imported mesh share one space. glTFast mirrors x on everything it imports; SpringRigData is the one
|
|
// owner of the same mirror for the rig. A real GLB (rotated rest bones, swim about an oblique axis) is imported by glTFast
|
|
// and parsed by SpringRigData; the bind poses and rest bone poses must agree, and the vertices Unity skins from the bone poses
|
|
// the rig computed must land where the rig's own skin matrices put them.
|
|
static void Handedness(Action<string> done)
|
|
{
|
|
var glb = new Synth { Spine = 4, Chains = 3, Joints = 4, Rot = true, Stiffness = 5, Gravity = 0.2f, Colliders = new JArray() }.Glb();
|
|
ImportAndCompare(glb, SpringRigData.FromGlb(glb), done);
|
|
}
|
|
|
|
// The rig contract's own parse of a GLB file, then the same glTFast comparison. SpringRigData.FromGlb owns every refusal; the exit
|
|
// code is GlbFile's, the one function VerifyGlbCases also runs: this method only checks the device, logs and exits with it.
|
|
public static void VerifyGlb()
|
|
{
|
|
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null)
|
|
{
|
|
Debug.LogError($"{Tag} FAIL: no graphics device in this session; rerun batchmode without -nographics.");
|
|
EditorApplication.Exit(1);
|
|
return;
|
|
}
|
|
GlbFile(Environment.GetEnvironmentVariable("SPRINGRIG_GLB"), (code, verdict) =>
|
|
{
|
|
if (code == 0) Debug.Log($"{Tag} PASS glb");
|
|
else Debug.LogError($"{Tag} FAIL glb: {verdict}");
|
|
EditorApplication.Exit(code);
|
|
});
|
|
}
|
|
|
|
// The file run: a missing or unreadable path is 1, a refusal or a failed comparison is 1, a pass is 0. done gets the exit code
|
|
// and the verdict (null on a pass). Any file (.glb, .springrig) is a GLB container.
|
|
static void GlbFile(string path, Action<int, string> done, Disturbance? disturb = null)
|
|
{
|
|
if (string.IsNullOrEmpty(path) || !File.Exists(path)) { done(1, $"set SPRINGRIG_GLB to a readable GLB path (got '{path}')"); return; }
|
|
byte[] glb;
|
|
try { glb = File.ReadAllBytes(path); }
|
|
catch (Exception e) { done(1, e.Message); return; }
|
|
CheckGlb(glb, verdict => done(verdict == null ? 0 : 1, verdict), disturb);
|
|
}
|
|
|
|
// FromGlb, then the glTFast comparison: null is a pass, else the owner's refusal or the comparison's verdict.
|
|
static void CheckGlb(byte[] glb, Action<string> done, Disturbance? disturb = null)
|
|
{
|
|
SpringRigData data;
|
|
try { data = SpringRigData.FromGlb(glb); }
|
|
catch (Exception e) { done(e.Message); return; }
|
|
Debug.Log($"{Tag} glb: bones {data.BoneCount}, bodies {data.BodyCount}, chains {data.ChainCount}, spring joints {data.SpringJointCount}, max chain length {data.MaxChainLength}, colliders {data.Colliders.Count}");
|
|
ImportAndCompare(glb, data, verdict =>
|
|
{
|
|
foreach (var go in Scrap) if (go != null) UnityEngine.Object.DestroyImmediate(go);
|
|
Scrap.Clear();
|
|
done(verdict);
|
|
}, disturb);
|
|
}
|
|
|
|
// VerifyGlb's own pins: each GLB is a Synth rig edited one way; the verdict must be the expected one (null a pass, else a
|
|
// substring of the refusal). Kills a VerifyGlb that exits 0 after FAIL, reads a failed import as PASS, compares the wrong
|
|
// GLB, swallows the comparison's exception, drops the vacuity guard or widens the tolerance.
|
|
// ... -executeMethod Aetheria.EditorTools.SpringRigVerify.VerifyGlbCases
|
|
public static void VerifyGlbCases()
|
|
{
|
|
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null)
|
|
{
|
|
Debug.LogError($"{Tag} FAIL: no graphics device in this session; rerun batchmode without -nographics.");
|
|
EditorApplication.Exit(1);
|
|
return;
|
|
}
|
|
Synth Base() => new Synth { Spine = 4, Chains = 3, Joints = 4, Rot = true };
|
|
var cases = new (string name, Synth rig, string expect, Disturbance? disturb)[]
|
|
{
|
|
("accepts-synth", Base(), null, null),
|
|
("refuses-by-owner", new Synth { Spine = 4, Chains = 3, Joints = 4, Rot = true, Edit = j => j["nodes"][1]["scale"] = new JArray(2, 1, 1) }, "non-unit scale", null),
|
|
("refuses-unknown-required-extension", new Synth { Spine = 4, Chains = 3, Joints = 4, Rot = true, Edit = j => j["extensionsRequired"] = new JArray("KHR_not_a_real_extension") }, "glTFast did not import", null),
|
|
("refuses-joint-past-bones", new Synth { Spine = 4, Chains = 3, Joints = 4, Rot = true, BadJoint = true }, "exception", null),
|
|
("refuses-skin-off-by-a-known-amount", new Synth { Spine = 4, Chains = 3, Joints = 4, Rot = true }, "Unity skins a vertex 0.02", new Disturbance(Phase.Posed, smr => smr.bones[1].position += new Vector3(0.02f, 0, 0))),
|
|
("refuses-bind-pose-off-by-a-known-amount", Base(), "bind poses differ", new Disturbance(Phase.Imported, smr =>
|
|
{
|
|
var bind = smr.sharedMesh.bindposes;
|
|
bind[1] = Matrix4x4.Translate(new Vector3(0.01f, 0, 0)) * bind[1];
|
|
smr.sharedMesh.bindposes = bind;
|
|
})),
|
|
("refuses-rest-node-off-by-a-known-amount", Base(), "rest bone poses differ", new Disturbance(Phase.Imported, smr => smr.bones[1].position += new Vector3(0.01f, 0, 0))),
|
|
("refuses-vacuous-mesh", new Synth { Spine = 4, Chains = 3, Joints = 4, Rot = true, Tiny = true }, "vacuous", null),
|
|
};
|
|
int failed = 0, at = 0;
|
|
// The file run itself, by path: the committed asset passes with its head at +Z, a text file named .springrig and a missing path are exit 1.
|
|
var text = Path.Combine(Path.GetTempPath(), "springrig-not-a-glb.springrig");
|
|
File.WriteAllText(text, "this is not a GLB");
|
|
var files = new (string name, string path, int code)[]
|
|
{
|
|
("accepts-the-committed-leviathan", AssetFile, 0), ("refuses-a-text-file", text, 1), ("refuses-a-missing-path", Path.Combine(Path.GetTempPath(), "springrig-missing.springrig"), 1),
|
|
};
|
|
int fileAt = 0;
|
|
void Next()
|
|
{
|
|
if (fileAt < files.Length)
|
|
{
|
|
var (fileName, path, code) = files[fileAt++];
|
|
GlbFile(path, (got, verdict) =>
|
|
{
|
|
string head = got == 0 && code == 0 ? HeadForward(path) : null;
|
|
if (got == code && head == null) Debug.Log($"{Tag} PASS glb file {fileName}: exit {got}");
|
|
else { Debug.LogError($"{Tag} FAIL glb file {fileName}: expected exit {code}, got {got} ({verdict ?? head})"); failed++; }
|
|
foreach (var go in Scrap) if (go != null) UnityEngine.Object.DestroyImmediate(go);
|
|
Scrap.Clear();
|
|
Next();
|
|
});
|
|
return;
|
|
}
|
|
if (at == cases.Length)
|
|
{
|
|
File.Delete(text);
|
|
Debug.Log(failed == 0 ? $"{Tag} PASS all glb cases" : $"{Tag} FAIL {failed} glb case(s)");
|
|
EditorApplication.Exit(failed == 0 ? 0 : 1);
|
|
return;
|
|
}
|
|
var (name, rig, expect, disturb) = cases[at++];
|
|
CheckGlb(rig.Glb(), verdict =>
|
|
{
|
|
bool ok = expect == null ? verdict == null : verdict != null && verdict.Contains(expect);
|
|
if (ok) Debug.Log($"{Tag} PASS glb case {name}: {verdict ?? "accepted"}");
|
|
else { Debug.LogError($"{Tag} FAIL glb case {name}: expected {expect ?? "accept"}, got {verdict ?? "accept"}"); failed++; }
|
|
Next();
|
|
}, disturb);
|
|
}
|
|
Next();
|
|
}
|
|
|
|
// The committed leviathan, by the path the importer and the checks share.
|
|
const string AssetPath = "Assets/Content/Fauna/Leviathan/leviathan.springrig";
|
|
static string AssetFile => Path.GetFullPath(AssetPath);
|
|
|
|
// The importer's product for the committed leviathan: a main object with SpringRig (Rig set; Awake initializes it), the mesh in
|
|
// SpringSkin's streams with as many vertices as glTFast makes of the same file, a BC7 base colour with mips on the material, and an
|
|
// Addressables entry (the folder entry Assets/Content covers it).
|
|
static void ImporterBuilds(Action<string> done)
|
|
{
|
|
var main = AssetDatabase.LoadAssetAtPath<GameObject>(AssetPath);
|
|
if (main == null) { done($"{AssetPath} imported no main object (see the import errors above)"); return; }
|
|
var spring = main.GetComponent<SpringRig>();
|
|
if (spring == null || spring.Rig == null) { done("the main object has no SpringRig with a Rig"); return; }
|
|
var mesh = AssetDatabase.LoadAssetAtPath<Mesh>(AssetPath);
|
|
if (mesh == null || main.GetComponent<MeshFilter>().sharedMesh != mesh) { done("the main object's mesh is not the asset's mesh"); return; }
|
|
if (mesh.GetVertexAttributeFormat(VertexAttribute.BlendWeight) != VertexAttributeFormat.Float32 || mesh.GetVertexAttributeDimension(VertexAttribute.BlendWeight) != 4
|
|
|| mesh.GetVertexAttributeFormat(VertexAttribute.BlendIndices) != VertexAttributeFormat.UInt32 || mesh.GetVertexAttributeDimension(VertexAttribute.BlendIndices) != 4)
|
|
{ done("the mesh does not carry BlendWeight Float32x4 and BlendIndices UInt32x4"); return; }
|
|
var texture = main.GetComponent<MeshRenderer>().sharedMaterial.GetTexture("_MainTex") as Texture2D;
|
|
if (texture != null && !texture.isDataSRGB) { done("the base colour is linear, not sRGB"); return; }
|
|
var hash = AlbedoHash();
|
|
if (hash != null) { done(hash); return; }
|
|
if (texture == null || texture.format != TextureFormat.BC7 || texture.mipmapCount < 2) { done($"the base colour is {(texture == null ? "missing" : texture.format + " with " + texture.mipmapCount + " mips")}, not BC7 with mips"); return; }
|
|
var entry = UnityEditor.AddressableAssets.AddressableAssetSettingsDefaultObject.Settings.FindAssetEntry(AssetDatabase.AssetPathToGUID(AssetPath), true);
|
|
if (entry == null) { done("Addressables has no entry for the asset (Assets/Content is the folder entry)"); return; }
|
|
var clone = UnityEngine.Object.Instantiate(main);
|
|
Scrap.Add(clone);
|
|
typeof(SpringRig).GetMethod("Awake", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Invoke(clone.GetComponent<SpringRig>(), null);
|
|
if (clone.GetComponent<SpringRig>().Data == null) { done("Awake did not initialize the rig from Rig"); return; }
|
|
Import(File.ReadAllBytes(AssetFile), (root, why) =>
|
|
{
|
|
var smr = root.GetComponentInChildren<SkinnedMeshRenderer>();
|
|
done(why ?? (smr == null ? "glTFast made no skinned mesh" : smr.sharedMesh.vertexCount == mesh.vertexCount ? null : $"the imported mesh has {mesh.vertexCount} vertices, glTFast's has {smr.sharedMesh.vertexCount}"));
|
|
});
|
|
}
|
|
|
|
// The imported base colour is a function of the file's bytes alone: the SHA-256 of its raw BC7 data with mips is the same in a session
|
|
// with a graphics device and in a -nographics one (SpringRigVerify.ImportNoGfx forces a reimport there and runs the same check).
|
|
const string AlbedoRawSha = "975E8E8458CCBA274F94B777745265291530F26F4E42EFA9F3FFDD85D3BF28C4";
|
|
|
|
static string AlbedoHash()
|
|
{
|
|
var main = AssetDatabase.LoadAssetAtPath<GameObject>(AssetPath);
|
|
var texture = main == null ? null : main.GetComponent<MeshRenderer>().sharedMaterial.GetTexture("_MainTex") as Texture2D;
|
|
if (texture == null) return "the asset has no base colour";
|
|
using var sha = SHA256.Create();
|
|
string got = BitConverter.ToString(sha.ComputeHash(texture.GetRawTextureData<byte>().ToArray())).Replace("-", "");
|
|
Debug.Log($"{Tag} albedo raw SHA-256 {got} ({SystemInfo.graphicsDeviceType})");
|
|
return got == AlbedoRawSha ? null : $"the base colour's raw SHA-256 is {got}, not {AlbedoRawSha}";
|
|
}
|
|
|
|
// Batch method for a -nographics session: reimport the committed asset with no device and check what comes out.
|
|
public static void ImportNoGfx()
|
|
{
|
|
string verdict;
|
|
try
|
|
{
|
|
if (SystemInfo.graphicsDeviceType != GraphicsDeviceType.Null) verdict = "this session has a graphics device; run it with -nographics";
|
|
else
|
|
{
|
|
AssetDatabase.ImportAsset(AssetPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport);
|
|
verdict = AssetDatabase.LoadAssetAtPath<GameObject>(AssetPath) == null ? "the reimport made no main object" : AlbedoHash();
|
|
}
|
|
}
|
|
catch (Exception e) { verdict = "exception: " + e; }
|
|
if (verdict == null) Debug.Log($"{Tag} PASS import without a device");
|
|
else Debug.LogError($"{Tag} FAIL import without a device: {verdict}");
|
|
EditorApplication.Exit(verdict == null ? 0 : 1);
|
|
}
|
|
|
|
// The head is at +Z: the spine's root bone sits, at rest, past the centre of the imported mesh's bounds along Z, which is where SpringRig's
|
|
// heading (its rotation) points the whale. A recipe whose head lands at -Z fails here.
|
|
static string HeadForward(string path)
|
|
{
|
|
var data = SpringRigData.FromGlb(File.ReadAllBytes(path));
|
|
var mesh = AssetDatabase.LoadAssetAtPath<Mesh>(AssetPath);
|
|
if (mesh == null) return $"{AssetPath} imported no mesh";
|
|
int root = Enumerable.Range(0, data.BoneCount).First(i => data.Parent[i] < 0);
|
|
Fk(data, 0, NoSwim, default, quaternion.identity, 1, out var rest, out _);
|
|
return rest[root].z > mesh.bounds.center.z ? null : $"the spine root sits at z {rest[root].z}, not past the mesh's centre {mesh.bounds.center.z}: the whale faces -Z";
|
|
}
|
|
|
|
// A Disturbance moves what glTFast imported at a named point of the comparison: only VerifyGlbCases passes one, to give a check a
|
|
// known error. Imported: before the bind and rest poses are compared (a bind pose or a rest node moved). Posed: after the rig
|
|
// posed the bones and before Unity bakes the skin (a bone moved).
|
|
enum Phase { Imported, Posed }
|
|
readonly struct Disturbance
|
|
{
|
|
public readonly Phase When;
|
|
public readonly Action<SkinnedMeshRenderer> Act;
|
|
public Disturbance(Phase when, Action<SkinnedMeshRenderer> act) { When = when; Act = act; }
|
|
}
|
|
|
|
// Tolerances of the glTFast comparison (lodur:ruling:deterministic-bound-margin): the geometric mean of the shipped worst reading and
|
|
// the reading of the case that moves one bone by 0.01 (bind 1.0e-2, rest 1.0e-2). Shipped, over the Synth cases and the committed
|
|
// leviathan: rest bone poses 6.0e-7 (separation 129 and 128), bind poses exactly 0, so the rest reading, the same float noise, stands
|
|
// in for it (the mean of 0 is 0).
|
|
const double BindTolerance = 7.8e-5, PoseTolerance = 7.8e-5;
|
|
|
|
// disturb moves the imported skeleton: only VerifyGlbCases passes one.
|
|
// glTFast imports and instantiates the GLB into a scratch root, driven by the editor's update loop (it resumes on the main thread, so
|
|
// it is not waited on). done gets the root and null, or the root and why there is no scene.
|
|
static void Import(byte[] glb, Action<GameObject, string> done)
|
|
{
|
|
var root = new GameObject("imported");
|
|
Scrap.Add(root);
|
|
var gltf = new GLTFast.GltfImport(deferAgent: new GLTFast.UninterruptedDeferAgent());
|
|
var load = gltf.LoadGltfBinary(glb, new Uri("file:///spring-rig.glb"));
|
|
System.Threading.Tasks.Task<bool> instantiate = null;
|
|
var clock = Stopwatch.StartNew();
|
|
EditorApplication.CallbackFunction poll = null;
|
|
poll = () =>
|
|
{
|
|
if (instantiate == null && load.IsCompleted) instantiate = load.Result ? gltf.InstantiateMainSceneAsync(root.transform) : null;
|
|
bool failed = (load.IsCompleted && !load.Result) || clock.Elapsed.TotalSeconds > 120;
|
|
if (!failed && (instantiate == null || !instantiate.IsCompleted)) return;
|
|
EditorApplication.update -= poll;
|
|
done(root, failed ? "glTFast did not import the GLB" : instantiate.Result ? null : "glTFast did not instantiate the scene");
|
|
};
|
|
EditorApplication.update += poll;
|
|
}
|
|
|
|
static void ImportAndCompare(byte[] glb, SpringRigData data, Action<string> done, Disturbance? disturb = null) =>
|
|
Import(glb, (root, why) =>
|
|
{
|
|
string verdict;
|
|
try { verdict = why ?? HandednessCompare(data, root, disturb); }
|
|
catch (Exception e) { verdict = "exception: " + e; }
|
|
done(verdict);
|
|
});
|
|
|
|
static string HandednessCompare(SpringRigData data, GameObject root, Disturbance? disturb)
|
|
{
|
|
var smr = root.GetComponentInChildren<SkinnedMeshRenderer>();
|
|
if (smr == null || smr.bones.Length != data.BoneCount) return "glTFast made no skinned mesh with the rig's bones";
|
|
if (disturb is { When: Phase.Imported } early) early.Act(smr);
|
|
var mesh = smr.sharedMesh;
|
|
double bind = 0, pose = 0;
|
|
Fk(data, 0, new SwimSettings { AmplitudeDegrees = 0, PeriodSeconds = 1, Axis = new float3(1, 0, 0) }, default, quaternion.identity, 1, out var rp, out var rr);
|
|
for (int i = 0; i < data.BoneCount; i++)
|
|
{
|
|
var a = (float4x4)mesh.bindposes[i]; var b = data.BindPose[i];
|
|
bind = math.max(bind, math.max(math.cmax(math.abs(a.c0 - b.c0)), math.max(math.cmax(math.abs(a.c1 - b.c1)), math.max(math.cmax(math.abs(a.c2 - b.c2)), math.cmax(math.abs(a.c3 - b.c3))))));
|
|
pose = math.max(pose, math.distance(smr.bones[i].position, (Vector3)rp[i]) + Quaternion.Angle(smr.bones[i].rotation, (Quaternion)rr[i]) * 0.01);
|
|
}
|
|
Debug.Log($"{Tag} glb readings: bind poses differ by {bind:E2} (tolerance {BindTolerance:E1}), rest bone poses by {pose:E2} (tolerance {PoseTolerance:E1})");
|
|
if (bind > BindTolerance) return $"glTFast's bind poses differ from the rig's by {bind}";
|
|
if (pose > PoseTolerance) return $"glTFast's rest bone poses differ from the rig's by {pose}";
|
|
|
|
var holder = new GameObject("rig");
|
|
Scrap.Add(holder);
|
|
var rig = holder.AddComponent<SpringRig>();
|
|
rig.Renderer = holder.AddComponent<MeshRenderer>();
|
|
rig.Swim = new SwimSettings { AmplitudeDegrees = 22, PeriodSeconds = 2, PhasePerBone = 0.15f, Axis = new float3(0.3f, 1, 0.5f) };
|
|
rig.Initialize(data, mesh.bounds);
|
|
for (int f = 0; f < 90; f++) rig.Present(f * Dt, Vector3.zero, Quaternion.identity, 1);
|
|
for (int i = 0; i < data.BoneCount; i++) smr.bones[i].SetPositionAndRotation((Vector3)rig.BonePosition(i), (Quaternion)rig.BoneRotation(i));
|
|
if (disturb is { When: Phase.Posed } late) late.Act(smr);
|
|
var baked = new Mesh();
|
|
smr.BakeMesh(baked, true);
|
|
var bakedVerts = baked.vertices; var vertices = mesh.vertices; var weights = mesh.boneWeights;
|
|
double worst = 0, spread = 0;
|
|
for (int v = 0; v < vertices.Length; v++)
|
|
{
|
|
var p = new float4(vertices[v], 1);
|
|
var w = weights[v];
|
|
float3 mine = w.weight0 * math.mul(rig.Skin[w.boneIndex0], p).xyz + w.weight1 * math.mul(rig.Skin[w.boneIndex1], p).xyz
|
|
+ w.weight2 * math.mul(rig.Skin[w.boneIndex2], p).xyz + w.weight3 * math.mul(rig.Skin[w.boneIndex3], p).xyz;
|
|
var unity = smr.transform.TransformPoint(bakedVerts[v]);
|
|
worst = math.max(worst, math.distance(mine, unity));
|
|
spread = math.max(spread, math.distance(mine, vertices[v]));
|
|
}
|
|
if (spread < 0.1) return $"the posed mesh moved only {spread} from rest (vacuous)";
|
|
return worst <= 1e-3 ? null : $"Unity skins a vertex {worst} from where the rig's skin matrices put it";
|
|
}
|
|
|
|
// ---------------------------------------------------------------- capture
|
|
|
|
// The look check: the imported asset (the main object a .springrig imports to, through AssetDatabase) swims along its +Z with a slow
|
|
// yaw under one directional light with shadows and flat ambient, and every frame is a PNG. The camera follows the whale's position and
|
|
// looks at SPRINGRIG_FOCUS in its object space, so a close framing follows the part it names.
|
|
public static void CaptureAsset()
|
|
{
|
|
Action restoreQuality = null;
|
|
try
|
|
{
|
|
var asset = Environment.GetEnvironmentVariable("SPRINGRIG_ASSET") ?? throw new InvalidOperationException("Set SPRINGRIG_ASSET to an Assets path.");
|
|
var dir = Environment.GetEnvironmentVariable("SPRINGRIG_CAPTURE_OUT") ?? throw new InvalidOperationException("Set SPRINGRIG_CAPTURE_OUT.");
|
|
if (!Path.IsPathRooted(dir)) throw new InvalidOperationException($"SPRINGRIG_CAPTURE_OUT must be absolute (got '{dir}').");
|
|
int frames = int.TryParse(Environment.GetEnvironmentVariable("SPRINGRIG_FRAMES"), out var n) ? n : 300;
|
|
float distance = float.TryParse(Environment.GetEnvironmentVariable("SPRINGRIG_DISTANCE"), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var d) ? d : 1.15f;
|
|
bool plane = Environment.GetEnvironmentVariable("SPRINGRIG_PLANE") == "1";
|
|
float side = Environment.GetEnvironmentVariable("SPRINGRIG_SIDE") == "-1" ? -1f : 1f;
|
|
Directory.CreateDirectory(dir);
|
|
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(asset) ?? throw new InvalidOperationException($"No imported asset at {asset}.");
|
|
var go = UnityEngine.Object.Instantiate(prefab);
|
|
var rig = go.GetComponent<SpringRig>() ?? throw new InvalidOperationException($"{asset} has no SpringRig.");
|
|
rig.Initialize();
|
|
var focus = rig.Renderer.localBounds.center;
|
|
var spec = Environment.GetEnvironmentVariable("SPRINGRIG_FOCUS");
|
|
if (!string.IsNullOrEmpty(spec))
|
|
{
|
|
var p = spec.Split(',').Select(s => float.Parse(s, System.Globalization.CultureInfo.InvariantCulture)).ToArray();
|
|
focus = new Vector3(p[0], p[1], p[2]);
|
|
}
|
|
// Quality settings persist into ProjectSettings when the editor exits: put them back when the capture ends.
|
|
var (quality, distanceBefore, resolution) = (QualitySettings.shadows, QualitySettings.shadowDistance, QualitySettings.shadowResolution);
|
|
restoreQuality = () => { QualitySettings.shadows = quality; QualitySettings.shadowDistance = distanceBefore; QualitySettings.shadowResolution = resolution; };
|
|
QualitySettings.shadows = ShadowQuality.All;
|
|
QualitySettings.shadowDistance = 20;
|
|
QualitySettings.shadowResolution = UnityEngine.ShadowResolution.VeryHigh;
|
|
var light = new GameObject("sun").AddComponent<Light>();
|
|
light.type = LightType.Directional; light.intensity = 1.9f; light.shadows = LightShadows.Soft;
|
|
light.transform.rotation = Quaternion.Euler(45, -35, 0);
|
|
RenderSettings.ambientMode = AmbientMode.Flat; RenderSettings.ambientLight = new Color(0.70f, 0.74f, 0.85f);
|
|
GameObject floor = null;
|
|
if (plane)
|
|
{
|
|
floor = GameObject.CreatePrimitive(PrimitiveType.Plane);
|
|
floor.GetComponent<Renderer>().sharedMaterial = new Material(Shader.Find("Standard")) { color = new Color(0.55f, 0.55f, 0.6f) };
|
|
floor.transform.localScale = Vector3.one * 0.5f;
|
|
}
|
|
var cam = new GameObject("cam").AddComponent<Camera>();
|
|
cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = new Color(0.03f, 0.04f, 0.09f);
|
|
cam.fieldOfView = 40; cam.nearClipPlane = 0.02f; cam.farClipPlane = 100;
|
|
var rt = new RenderTexture(1280, 720, 24, RenderTextureFormat.ARGB32) { antiAliasing = 4 };
|
|
cam.targetTexture = rt;
|
|
var read = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false);
|
|
Vector3 pos = Vector3.zero;
|
|
for (int f = 0; f < frames; f++)
|
|
{
|
|
double t = f * Dt;
|
|
// Swim forward along +z, yawing slowly and drifting sideways a little, so the tendrils trail across the body.
|
|
var rot = Quaternion.AngleAxis(Mathf.Cos((float)t * 0.9f) * 22f, Vector3.up);
|
|
pos += rot * Vector3.forward * (0.55f / 60f) + Vector3.right * (Mathf.Sin((float)t * 1.3f) * 0.004f);
|
|
rig.Present(t, pos, rot, 1);
|
|
var target = pos + rot * focus;
|
|
if (floor != null) floor.transform.position = new Vector3(pos.x, pos.y - 0.45f, pos.z);
|
|
cam.transform.position = target + Vector3.right * (side * distance) + Vector3.up * (0.2f * distance) - Vector3.forward * (0.1f * distance);
|
|
cam.transform.LookAt(target, Vector3.up);
|
|
cam.Render();
|
|
RenderTexture.active = rt;
|
|
read.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
|
|
RenderTexture.active = null;
|
|
File.WriteAllBytes(Path.Combine(dir, $"frame_{f:D4}.png"), read.EncodeToPNG());
|
|
}
|
|
Debug.Log($"{Tag} captured {frames} frames of {asset} to {dir}; steps {rig.SubstepsRun} resets {rig.Resets} level {rig.Level}");
|
|
restoreQuality?.Invoke();
|
|
EditorApplication.Exit(0);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Debug.LogError($"{Tag} capture FAIL: {e}");
|
|
restoreQuality?.Invoke();
|
|
EditorApplication.Exit(1);
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------- the synthetic rig
|
|
|
|
// A glTF skin built in code, in glTF (right-handed) space: a spine along +z (body bones) and Chains tendrils of Joints
|
|
// joints hanging from it in a ring, one VRMC_springBone spring each. Rest rotations are identity unless Rot, which gives
|
|
// every node a fixed non-trivial rotation (inverse bind matrices are always the exact inverse of the rest world).
|
|
sealed class Synth
|
|
{
|
|
public int Spine = 4, Chains = 8, Joints = 5;
|
|
public float Stiffness = 8, Drag = 0.4f, Gravity = 0, Hit = 0.02f, Ring = 0.4f;
|
|
public Vector3 Seg = new Vector3(0, -0.1f, -0.3f);
|
|
public float3 GravityDir = new float3(0, -1, 0);
|
|
public bool Rot;
|
|
public Action<JObject> Edit; // Glb(): edits the glTF JSON last (cases of VerifyGlbCases)
|
|
public bool BadJoint, Tiny; // Glb(): a joint index past the bones; the whole mesh a speck at the root bone
|
|
public JArray Colliders; // null: a sphere on every spine bone but the root
|
|
|
|
public float3[] World; // rest world position and rotation per node, glTF space, set by Build
|
|
public quaternion[] WorldRot;
|
|
public int[] ParentOf;
|
|
|
|
public int Host(int chain) => 1 + chain % Math.Max(1, Spine - 1);
|
|
float Theta(int chain) => ((chain * 0.618f) % 1f - 0.5f) * 2.4f;
|
|
public float3 JointRest(int chain, int k) => new float3(Ring * Mathf.Sin(Theta(chain)), -Ring * Mathf.Cos(Theta(chain)), 0) + (float3)Seg * k;
|
|
quaternion NodeRot(int node) => Rot ? quaternion.AxisAngle(math.normalize(new float3(1 + node % 3, 2 - node % 2, 1 + node % 5)), 0.25f + 0.1f * (node % 7)) : quaternion.identity;
|
|
|
|
public JObject Build(out byte[] bin)
|
|
{
|
|
int n = Spine + Chains * Joints;
|
|
var nodes = new JArray(); var pos = new float3[n]; var rot = new quaternion[n]; ParentOf = new int[n];
|
|
void Node(int i, string name, int parent, float3 local)
|
|
{
|
|
var q = NodeRot(i);
|
|
var node = new JObject { ["name"] = name, ["translation"] = Arr(local), ["children"] = new JArray() };
|
|
if (Rot) node["rotation"] = new JArray(q.value.x, q.value.y, q.value.z, q.value.w);
|
|
nodes.Add(node);
|
|
ParentOf[i] = parent;
|
|
pos[i] = parent < 0 ? local : pos[parent] + math.mul(rot[parent], local);
|
|
rot[i] = parent < 0 ? q : math.mul(rot[parent], q);
|
|
if (parent >= 0) ((JArray)nodes[parent]["children"]).Add(i);
|
|
}
|
|
for (int i = 0; i < Spine; i++) Node(i, "spine" + i, i - 1, i == 0 ? default : new float3(0, 0, 1));
|
|
var springs = new JArray();
|
|
for (int c = 0; c < Chains; c++)
|
|
{
|
|
var joints = new JArray();
|
|
for (int k = 0; k < Joints; k++)
|
|
{
|
|
int node = Spine + c * Joints + k;
|
|
Node(node, $"t{c}_{k}", k == 0 ? Host(c) : node - 1, k == 0 ? JointRest(c, 0) : (float3)Seg);
|
|
joints.Add(new JObject { ["node"] = node, ["hitRadius"] = Hit, ["stiffness"] = Stiffness, ["gravityPower"] = Gravity, ["gravityDir"] = Arr(GravityDir), ["dragForce"] = Drag });
|
|
}
|
|
springs.Add(new JObject { ["name"] = "tendril" + c, ["joints"] = joints, ["colliderGroups"] = new JArray(0) });
|
|
}
|
|
World = pos; WorldRot = rot;
|
|
var colliders = Colliders ?? new JArray(Enumerable.Range(1, Spine - 1).Select(i => Collider(i, "sphere", default, null, Ring * 0.8f)));
|
|
var bytes = new byte[n * 64];
|
|
for (int i = 0; i < n; i++)
|
|
{
|
|
var m = math.inverse(float4x4.TRS(pos[i], rot[i], new float3(1))); // glTF stores column-major
|
|
var f = new[] { m.c0.x, m.c0.y, m.c0.z, m.c0.w, m.c1.x, m.c1.y, m.c1.z, m.c1.w, m.c2.x, m.c2.y, m.c2.z, m.c2.w, m.c3.x, m.c3.y, m.c3.z, m.c3.w };
|
|
Buffer.BlockCopy(f, 0, bytes, i * 64, 64);
|
|
}
|
|
bin = bytes;
|
|
return new JObject
|
|
{
|
|
["asset"] = new JObject { ["version"] = "2.0" },
|
|
["nodes"] = nodes,
|
|
["skins"] = new JArray(new JObject { ["joints"] = new JArray(Enumerable.Range(0, n)), ["inverseBindMatrices"] = 0 }),
|
|
["accessors"] = new JArray(new JObject { ["bufferView"] = 0, ["componentType"] = 5126, ["count"] = n, ["type"] = "MAT4" }),
|
|
["bufferViews"] = new JArray(new JObject { ["buffer"] = 0, ["byteOffset"] = 0, ["byteLength"] = n * 64 }),
|
|
["extensions"] = new JObject
|
|
{
|
|
["VRMC_springBone"] = new JObject
|
|
{
|
|
["specVersion"] = "1.0", ["colliders"] = colliders, ["springs"] = springs,
|
|
["colliderGroups"] = new JArray(new JObject { ["name"] = "body", ["colliders"] = new JArray(Enumerable.Range(0, colliders.Count)) }),
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
// A real GLB: the rig plus one skinned mesh node (a triangle around every bone, weights 0.6 the bone and 0.4 its parent).
|
|
public byte[] Glb()
|
|
{
|
|
var json = Build(out var ibm);
|
|
int n = World.Length, v = 3 * n;
|
|
if (n > 255) throw new InvalidOperationException("Glb joints are bytes.");
|
|
var positions = new List<float>(); var normals = new List<float>(); var joints = new List<byte>(); var weights = new List<float>();
|
|
for (int i = 0; i < n; i++)
|
|
foreach (var o in new[] { new float3(0, 0.12f, 0), new float3(0, -0.12f, 0), new float3(0, 0, 0.3f) })
|
|
{
|
|
var p = Tiny ? World[0] + o * 0.01f : World[i] + math.mul(WorldRot[i], o);
|
|
positions.AddRange(new[] { p.x, p.y, p.z }); normals.AddRange(new[] { 1f, 0, 0 });
|
|
if (Tiny) { joints.AddRange(new byte[4]); weights.AddRange(new[] { 1f, 0, 0, 0 }); }
|
|
else { joints.AddRange(new[] { (byte)(BadJoint && i == 0 ? 200 : i), (byte)(ParentOf[i] >= 0 ? ParentOf[i] : i), (byte)0, (byte)0 }); weights.AddRange(new[] { 0.6f, 0.4f, 0, 0 }); }
|
|
}
|
|
var chunks = new[] { ibm, Bytes(positions), Bytes(normals), joints.ToArray(), Bytes(weights), Bytes(Enumerable.Range(0, v).ToArray()) };
|
|
var views = (JArray)json["bufferViews"]; var accessors = (JArray)json["accessors"];
|
|
int at = 0;
|
|
for (int i = 0; i < chunks.Length; i++)
|
|
{
|
|
if (i > 0) views.Add(new JObject { ["buffer"] = 0, ["byteOffset"] = at, ["byteLength"] = chunks[i].Length });
|
|
at += chunks[i].Length;
|
|
}
|
|
JObject Acc(int view, int type, string kind) => new JObject { ["bufferView"] = view, ["componentType"] = type, ["count"] = v, ["type"] = kind };
|
|
accessors.Add(Acc(1, 5126, "VEC3")); accessors.Add(Acc(2, 5126, "VEC3")); accessors.Add(Acc(3, 5121, "VEC4"));
|
|
accessors.Add(Acc(4, 5126, "VEC4")); accessors.Add(Acc(5, 5125, "SCALAR"));
|
|
accessors[1]["min"] = new JArray(Enumerable.Range(0, 3).Select(a => positions.Where((_, i) => i % 3 == a).Min() - 1));
|
|
accessors[1]["max"] = new JArray(Enumerable.Range(0, 3).Select(a => positions.Where((_, i) => i % 3 == a).Max() + 1));
|
|
json["buffers"] = new JArray(new JObject { ["byteLength"] = at });
|
|
json["meshes"] = new JArray(new JObject { ["primitives"] = new JArray(new JObject
|
|
{
|
|
["attributes"] = new JObject { ["POSITION"] = 1, ["NORMAL"] = 2, ["JOINTS_0"] = 3, ["WEIGHTS_0"] = 4 }, ["indices"] = 5,
|
|
}) });
|
|
((JArray)json["nodes"]).Add(new JObject { ["name"] = "mesh", ["mesh"] = 0, ["skin"] = 0 });
|
|
json["scenes"] = new JArray(new JObject { ["nodes"] = new JArray(0, n) });
|
|
json["scene"] = 0;
|
|
Edit?.Invoke(json);
|
|
var jsonBytes = Pad(System.Text.Encoding.UTF8.GetBytes(json.ToString(Newtonsoft.Json.Formatting.None)), 32);
|
|
var bin = Pad(chunks.SelectMany(c => c).ToArray(), 0);
|
|
var glb = new List<byte>();
|
|
glb.AddRange(BitConverter.GetBytes(0x46546C67u)); glb.AddRange(BitConverter.GetBytes(2u));
|
|
glb.AddRange(BitConverter.GetBytes((uint)(12 + 8 + jsonBytes.Length + 8 + bin.Length)));
|
|
glb.AddRange(BitConverter.GetBytes((uint)jsonBytes.Length)); glb.AddRange(BitConverter.GetBytes(0x4E4F534Au)); glb.AddRange(jsonBytes);
|
|
glb.AddRange(BitConverter.GetBytes((uint)bin.Length)); glb.AddRange(BitConverter.GetBytes(0x004E4942u)); glb.AddRange(bin);
|
|
return glb.ToArray();
|
|
}
|
|
|
|
static byte[] Bytes(List<float> f) { var b = new byte[f.Count * 4]; Buffer.BlockCopy(f.ToArray(), 0, b, 0, b.Length); return b; }
|
|
static byte[] Bytes(int[] f) { var b = new byte[f.Length * 4]; Buffer.BlockCopy(f, 0, b, 0, b.Length); return b; }
|
|
static byte[] Pad(byte[] b, byte fill) { var r = new byte[(b.Length + 3) / 4 * 4]; for (int i = 0; i < r.Length; i++) r[i] = i < b.Length ? b[i] : fill; return r; }
|
|
}
|
|
|
|
static JArray Arr(float3 v) => new JArray(v.x, v.y, v.z);
|
|
|
|
static JObject Collider(int node, string shape, float3 offset, float3? tail, float radius)
|
|
{
|
|
var body = new JObject { ["offset"] = Arr(offset), ["radius"] = radius };
|
|
if (tail.HasValue) body["tail"] = Arr(tail.Value);
|
|
return new JObject { ["node"] = node, ["shape"] = new JObject { [shape] = body } };
|
|
}
|
|
|
|
static SpringRig Whale(Synth s, out SpringRigData data)
|
|
{
|
|
var go = new GameObject("whale");
|
|
Scrap.Add(go);
|
|
var rig = go.AddComponent<SpringRig>();
|
|
rig.Renderer = go.AddComponent<MeshRenderer>();
|
|
data = SpringRigData.FromGlbJson(s.Build(out var bin), bin);
|
|
rig.Initialize(data, new Bounds(Vector3.zero, new Vector3(2, 2, 8)));
|
|
return rig;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- CPU references and helpers
|
|
|
|
// Forward kinematics of the swimming body with every spring joint at rest, independent of the jobs.
|
|
static void Fk(SpringRigData d, double t, SwimSettings swim, float3 rootPos, quaternion rootRot, float scale, out float3[] pos, out quaternion[] rot)
|
|
{
|
|
pos = new float3[d.BoneCount]; rot = new quaternion[d.BoneCount];
|
|
for (int i = 0; i < d.BoneCount; i++)
|
|
{
|
|
int p = d.Parent[i];
|
|
var local = d.SpineIndex[i] >= 0 ? math.mul(d.RestRotation[i], SwimPose.Rotation(t, d.SpineIndex[i], swim)) : d.RestRotation[i];
|
|
pos[i] = (p < 0 ? rootPos : pos[p]) + math.mul(p < 0 ? rootRot : rot[p], d.RestPosition[i] * scale);
|
|
rot[i] = math.mul(p < 0 ? rootRot : rot[p], local);
|
|
}
|
|
}
|
|
|
|
// Largest distance of a spring joint from its rest place on the body at the whale's pose.
|
|
static double Displacement(SpringRig w, SpringRigData d, double t, float3 rootPos, quaternion rootRot)
|
|
{
|
|
Fk(d, t, w.Swim, rootPos, rootRot, 1, out var rest, out _);
|
|
double worst = 0;
|
|
for (int i = 0; i < d.BoneCount; i++) if (!d.IsBody[i]) worst = math.max(worst, math.distance(rest[i], w.BonePosition(i)));
|
|
return worst;
|
|
}
|
|
|
|
static float3[] Positions(SpringRig w, SpringRigData d) => Enumerable.Range(0, d.BoneCount).Select(i => w.BonePosition(i)).ToArray();
|
|
|
|
static double Max(float3[] a, float3[] b, SpringRigData d, bool springs)
|
|
{
|
|
double worst = 0;
|
|
for (int i = 0; i < a.Length; i++) if (d.IsBody[i] != springs) worst = math.max(worst, math.distance(a[i], b[i]));
|
|
return worst;
|
|
}
|
|
|
|
static bool BitEqual(float4x4 a, float4x4 b) =>
|
|
a.c0.Equals(b.c0) && a.c1.Equals(b.c1) && a.c2.Equals(b.c2) && a.c3.Equals(b.c3);
|
|
|
|
static float Edge(Vector2 p, Vector2 a, Vector2 b) => (p.x - a.x) * (b.y - a.y) - (p.y - a.y) * (b.x - a.x);
|
|
|
|
static bool Near(bool[] mask, int x, int y, int size)
|
|
{
|
|
for (int dy = -1; dy <= 1; dy++)
|
|
for (int dx = -1; dx <= 1; dx++)
|
|
{
|
|
int px = x + dx, py = y + dy;
|
|
if (px >= 0 && py >= 0 && px < size && py < size && mask[py * size + px]) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- meshes and materials
|
|
|
|
struct Vertex { public Vector3 p, n; public Vector2 uv; public Vector4 w; public uint b0, b1, b2, b3; }
|
|
|
|
static Mesh MakeMesh(List<Vertex> verts, List<int> tris) =>
|
|
SpringRigImporter.Pack(verts.Select(v => v.p).ToArray(), verts.Select(v => v.n).ToArray(), verts.Select(v => v.uv).ToArray(), verts.Select(v => v.w).ToArray(),
|
|
verts.SelectMany(v => new[] { v.b0, v.b1, v.b2, v.b3 }).ToArray(), tris.ToArray());
|
|
|
|
static Material SkinMaterial(float cull)
|
|
{
|
|
var tex = new Texture2D(2, 1, TextureFormat.RGBA32, false) { filterMode = FilterMode.Point };
|
|
tex.SetPixels(new[] { new Color(0.45f, 0.62f, 0.82f), new Color(0.95f, 0.72f, 0.45f) });
|
|
tex.Apply();
|
|
var m = new Material(Shader.Find("Aetheria/FaunaSkinned"));
|
|
m.SetTexture("_MainTex", tex);
|
|
m.SetFloat("_Cull", cull);
|
|
return m;
|
|
}
|
|
|
|
// One triangle around every bone at its rest place, weights 0.6 the bone and 0.4 its parent.
|
|
static (List<Vertex>, List<int>) BoneTriangles(SpringRigData data)
|
|
{
|
|
Fk(data, 0, NoSwim, default, quaternion.identity, 1, out var rest, out var restRot);
|
|
var verts = new List<Vertex>(); var tris = new List<int>();
|
|
for (int i = 0; i < data.BoneCount; i++)
|
|
{
|
|
int other = data.Parent[i] >= 0 ? data.Parent[i] : i;
|
|
foreach (var o in new[] { new float3(0, 0.12f, 0), new float3(0, -0.12f, 0), new float3(0, 0, 0.3f) })
|
|
{
|
|
tris.Add(verts.Count);
|
|
verts.Add(new Vertex { p = rest[i] + math.mul(restRot[i], o), n = Vector3.right, uv = new Vector2(0.5f, 0.5f), w = new Vector4(0.6f, 0.4f, 0, 0), b0 = (uint)i, b1 = (uint)other });
|
|
}
|
|
}
|
|
return (verts, tris);
|
|
}
|
|
}
|
|
}
|