Findings of cut-whale-rig-s1.s3 (ease-reentry-pops, ease-moves-fast, bounds-scale-one-sided). - Present keeps a copy of the bone positions it drew and seeds the solver from it when the level returns to Full while the ease is part way (_restWeight < 1); a first Initialize, a fully eased return and a root jump still reset to rest. - BlendSeconds 0.25 -> 0.75. - SpringRig gets a serialized TextAsset Rig: Awake (and an Initialize() for editor code, where Awake does not run) builds the rig from it and the object's mesh. - reentry-is-continuous: leave Full for 3 and for 8 frames and return; the returning frame's tip motion beyond rigid is under 0.41 of the chain. Margin rule: shipped worst 0.172, reset-to-rest mutant 0.970 (3 frames) and 1.207 (8), geometric mean 0.41. - bounds-follow-the-swim runs at scale 1.5 and 0.6; a BoundsJob that ignores scale puts a vertex 1.24 outside at 0.6. - freeze-and-reset derives its ease frame count from BlendSeconds. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
221 lines
12 KiB
C#
221 lines
12 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 Unity.Collections;
|
|
using Unity.Jobs;
|
|
using Unity.Mathematics;
|
|
using UnityEngine;
|
|
|
|
namespace Aetheria.FaunaDisplay
|
|
{
|
|
public enum SpringLod { Full, Frozen, Hidden }
|
|
|
|
// One whale's skeleton, presentation only (rulings whale-rig-spring-bone-tendrils, presenter-phase-from-zone-time,
|
|
// fauna-in-sim-ruled): it owns every bone pose and skin matrix, body and tendril, of the frame it draws. The caller
|
|
// hands in the drawn time (DrawAhead.Time) and the whale's root pose; nothing else enters, and only the skin buffer
|
|
// and the renderer's bounds leave. No GameObject per joint and no Unity skinning or animation components: a shader reads the
|
|
// skin matrices (SpringSkin.cginc) from the mesh's BLENDINDICES and BLENDWEIGHTS.
|
|
public sealed class SpringRig : MonoBehaviour
|
|
{
|
|
// The solver's fixed substep, in drawn seconds, and the most substeps one frame runs. The two cannot both hold below
|
|
// MaxSubsteps x SubstepRate = 30 frames a second: there a frame owes more than 4 and the tendrils run slow (24 fps: at
|
|
// 80% of drawn time), which is the clamp's purpose (a hitch or a slow machine must not spiral). At 30 fps and above
|
|
// the count over any span is floor(span x 120) up to rounding at a boundary, which the interpolated pose hides.
|
|
public const int SubstepRate = 120;
|
|
public const int MaxSubsteps = 4;
|
|
|
|
[Tooltip("The rig's GLB (a .springrig the importer wraps). Awake initializes from it when set; callers that Initialize by hand leave it null.")]
|
|
public TextAsset Rig;
|
|
public MeshRenderer Renderer;
|
|
public SwimSettings Swim = SwimSettings.Default;
|
|
[Tooltip("Projected height of the whale as a fraction of the viewport at or above which the tendrils are solved.")]
|
|
public float FullAbove = 0.06f;
|
|
[Tooltip("Below FullAbove and at or above this the tendrils hold their rest pose on the swimming body; below it the caller hides them.")]
|
|
public float FrozenAbove = 0.015f;
|
|
[Tooltip("A level is left only once the projected height is this fraction below the threshold that entered it.")]
|
|
[Range(0f, 0.5f)] public float Hysteresis = 0.15f;
|
|
[Tooltip("Drawn seconds over which the tendrils ease to rest when the level leaves Full: 0.5 to 1 reads as settling, a quarter second as a flare.")]
|
|
public float BlendSeconds = 0.75f;
|
|
public Camera LodCamera;
|
|
|
|
public SpringRigData Data { get; private set; }
|
|
public SpringLod Level { get; private set; }
|
|
public GraphicsBuffer SkinBuffer { get; private set; }
|
|
public NativeArray<float4x4>.ReadOnly Skin => _skin.AsReadOnly();
|
|
public long SubstepsRun { get; private set; }
|
|
public int SolveJobsScheduled { get; private set; }
|
|
public int Resets { get; private set; }
|
|
public float3 BonePosition(int bone) => _bonePos[bone];
|
|
public quaternion BoneRotation(int bone) => _boneRot[bone];
|
|
|
|
NativeArray<int> _order, _parent, _spine, _chainStart, _chainLen, _chainBone, _chainColStart, _chainColLen, _chainCol;
|
|
NativeArray<float3> _restPos, _bonePos, _simPos, _simPrev, _drawn;
|
|
NativeArray<quaternion> _restRot, _boneRot;
|
|
NativeArray<float4x4> _bind, _skin;
|
|
NativeArray<SpringJointParams> _param;
|
|
NativeArray<SpringCollider> _colliders;
|
|
bool _started, _wasFull;
|
|
long _lastIndex;
|
|
float3 _lastPosition;
|
|
float _pad;
|
|
float _lodDiameter, _restWeight = 1f, _lastFrac;
|
|
double _lastTime;
|
|
bool _everFull;
|
|
NativeArray<float3> _minMax;
|
|
|
|
readonly System.Collections.Generic.List<IDisposable> _owned = new System.Collections.Generic.List<IDisposable>();
|
|
|
|
NativeArray<T> Own<T>(T[] source) where T : unmanaged { var a = new NativeArray<T>(source, Allocator.Persistent); _owned.Add(a); return a; }
|
|
NativeArray<T> Own<T>(int length) where T : unmanaged { var a = new NativeArray<T>(length, Allocator.Persistent); _owned.Add(a); return a; }
|
|
|
|
public void Initialize(SpringRigData data, Bounds meshBounds)
|
|
{
|
|
Release();
|
|
Data = data;
|
|
_order = Own(data._order);
|
|
_parent = Own(data._parent);
|
|
_spine = Own(data._spine);
|
|
_chainStart = Own(data._chainStart);
|
|
_chainLen = Own(data._chainLen);
|
|
_chainBone = Own(data._chainBone);
|
|
_chainColStart = Own(data._chainColStart);
|
|
_chainColLen = Own(data._chainColLen);
|
|
_chainCol = Own(data._chainCol);
|
|
_restPos = Own(data._restPos);
|
|
_restRot = Own(data._restRot);
|
|
_bind = Own(data._bind);
|
|
_param = Own(data._chainParam);
|
|
_colliders = Own(data._colliders);
|
|
int n = data.BoneCount;
|
|
_bonePos = Own<float3>(n);
|
|
_simPos = Own<float3>(n);
|
|
_simPrev = Own<float3>(n);
|
|
_drawn = Own<float3>(n);
|
|
_boneRot = Own<quaternion>(n);
|
|
_skin = Own<float4x4>(n);
|
|
_minMax = Own<float3>(2);
|
|
SkinBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, n, 64);
|
|
var block = new MaterialPropertyBlock();
|
|
block.SetBuffer("_SpringBones", SkinBuffer);
|
|
Renderer.SetPropertyBlock(block);
|
|
// The mesh reaches past its bones by the rest mesh's margin; each frame's bounds are the bones' reach plus that margin.
|
|
var restPos = new float3[n]; var restRot = new quaternion[n];
|
|
float3 lo = new float3(float.MaxValue), hi = new float3(float.MinValue);
|
|
foreach (int i in data._order)
|
|
{
|
|
int p = data._parent[i];
|
|
restPos[i] = (p < 0 ? default : restPos[p]) + math.mul(p < 0 ? quaternion.identity : restRot[p], data._restPos[i]);
|
|
restRot[i] = math.mul(p < 0 ? quaternion.identity : restRot[p], data._restRot[i]);
|
|
lo = math.min(lo, restPos[i]); hi = math.max(hi, restPos[i]);
|
|
}
|
|
_lodDiameter = meshBounds.extents.magnitude * 2f;
|
|
Renderer.localBounds = meshBounds;
|
|
// One radius all round (the mesh turns with its bones): the rest mesh's largest margin past its bones, per axis, as a length.
|
|
_pad = math.length(math.max(math.max(lo - (float3)meshBounds.min, (float3)meshBounds.max - hi), 0f));
|
|
_started = false;
|
|
_everFull = false;
|
|
_restWeight = 1f;
|
|
}
|
|
|
|
// The one entry: swim pose, solver substeps, skin write, upload, bounds. drawnTime is DrawAhead.Time.
|
|
public SpringLod Present(double drawnTime, Vector3 position, Quaternion rotation, float scale)
|
|
{
|
|
if (Data == null) throw new InvalidOperationException("SpringRig.Present before Initialize.");
|
|
Level = Classify(position, scale);
|
|
bool full = Level == SpringLod.Full;
|
|
|
|
// Substeps owed: the fixed 1/120 s boundaries crossed since the last frame, by absolute drawn time so the
|
|
// count over any span is the same at any frame rate. Not full: keep the index current so an unfreeze owes nothing.
|
|
long index = (long)math.floor(drawnTime * SubstepRate);
|
|
int steps = _started && full ? (int)math.clamp(index - _lastIndex, 0, MaxSubsteps) : 0;
|
|
_lastIndex = index;
|
|
float frac = (float)(drawnTime * SubstepRate - index);
|
|
|
|
// Leaving Full the tendrils ease to rest over BlendSeconds of drawn time (no snap); the solver still draws, with no steps.
|
|
double dt = _started ? math.max(drawnTime - _lastTime, 0) : 0;
|
|
_lastTime = drawnTime;
|
|
bool midEase = _everFull && _restWeight < 1f; // a return to Full from here starts from the pose last drawn, not from rest
|
|
if (full) { _restWeight = 0f; _everFull = true; _lastFrac = frac; }
|
|
else if (_everFull) _restWeight = (float)math.min(1.0, _restWeight + dt / math.max(BlendSeconds, 1e-4f));
|
|
bool easing = !full && _everFull && _restWeight < 1f;
|
|
|
|
bool jumped = math.distance(_lastPosition, position) > Data.MaxChainLength * scale;
|
|
bool reset = !_started || (full && !_wasFull) || jumped;
|
|
bool seedDrawn = reset && _started && !jumped && full && !_wasFull && midEase;
|
|
_started = true;
|
|
_wasFull = full;
|
|
_lastPosition = position;
|
|
if (reset && full) Resets++;
|
|
|
|
var pos = (float3)position;
|
|
var rot = (quaternion)rotation;
|
|
var pose = new PoseJob
|
|
{
|
|
order = _order, parent = _parent, spine = _spine, restPos = _restPos, restRot = _restRot,
|
|
swim = Swim, time = drawnTime, rootPos = pos, rootRot = rot, scale = scale, bonePos = _bonePos, boneRot = _boneRot,
|
|
}.Schedule();
|
|
if (full || easing)
|
|
{
|
|
SolveJobsScheduled++;
|
|
SubstepsRun += steps;
|
|
pose = new SpringSolveJob
|
|
{
|
|
chainStart = _chainStart, chainLen = _chainLen, chainBone = _chainBone, chainColStart = _chainColStart, chainColLen = _chainColLen,
|
|
chainCol = _chainCol, restPos = _restPos, restRot = _restRot, param = _param, colliders = _colliders,
|
|
bonePos = _bonePos, boneRot = _boneRot, simPos = _simPos, simPrev = _simPrev,
|
|
drawn = _drawn, seedDrawn = seedDrawn,
|
|
substeps = steps, step = 1f / SubstepRate, scale = scale, frac = full ? frac : _lastFrac, blend = full ? 0f : _restWeight, reset = reset,
|
|
}.Schedule(Data.ChainCount, 4, pose);
|
|
}
|
|
var skinned = new SkinJob
|
|
{
|
|
bonePos = _bonePos, boneRot = _boneRot, bind = _bind, rootInverse = math.inverse(float4x4.TRS(pos, rot, new float3(scale))), scale = scale, skin = _skin,
|
|
}.Schedule(Data.BoneCount, 64, pose);
|
|
new BoundsJob { bonePos = _bonePos, rootPos = pos, rootRot = rot, scale = scale, minMax = _minMax }.Schedule(skinned).Complete();
|
|
SkinBuffer.SetData(_skin);
|
|
_drawn.CopyFrom(_bonePos);
|
|
|
|
var t = Renderer.transform;
|
|
t.SetPositionAndRotation(position, rotation);
|
|
t.localScale = new Vector3(scale, scale, scale);
|
|
|
|
// Bounds follow the pose: every bone in object space, plus the rest mesh's margin around the bones.
|
|
float3 min = _minMax[0] - _pad, max = _minMax[1] + _pad;
|
|
Renderer.localBounds = new Bounds((min + max) * 0.5f, max - min);
|
|
return Level;
|
|
}
|
|
|
|
// Projected height of the whale's bounds as a fraction of the viewport.
|
|
SpringLod Classify(Vector3 position, float scale)
|
|
{
|
|
var cam = LodCamera;
|
|
if (cam == null) return SpringLod.Full;
|
|
float diameter = _lodDiameter * scale;
|
|
float visible = cam.orthographic ? cam.orthographicSize * 2f : 2f * Vector3.Distance(cam.transform.position, position) * Mathf.Tan(cam.fieldOfView * 0.5f * Mathf.Deg2Rad);
|
|
float height = diameter / Mathf.Max(visible, 1e-6f), stay = 1f - Hysteresis;
|
|
if (height >= FullAbove * (Level == SpringLod.Full ? stay : 1f)) return SpringLod.Full;
|
|
return height >= FrozenAbove * (Level != SpringLod.Hidden ? stay : 1f) ? SpringLod.Frozen : SpringLod.Hidden;
|
|
}
|
|
|
|
void Release()
|
|
{
|
|
foreach (var a in _owned) a.Dispose();
|
|
_owned.Clear();
|
|
SkinBuffer?.Release();
|
|
SkinBuffer = null;
|
|
}
|
|
|
|
// From the serialized Rig and this object's mesh. Awake calls it in play; an editor tool that instantiates the asset outside play
|
|
// (Awake does not run there) calls it itself.
|
|
public void Initialize() => Initialize(SpringRigData.FromGlb(Rig.bytes), GetComponent<MeshFilter>().sharedMesh.bounds);
|
|
|
|
void Awake()
|
|
{
|
|
if (Rig != null && Data == null) Initialize();
|
|
}
|
|
|
|
void OnDestroy() => Release();
|
|
}
|
|
}
|