LizardRig.cs

Component that drives the lizard's rigged model. It picks and crossfades animations from ReptileController and LizardAttack state, then adds a simulated layer each prerender: tail chain physics, hanging chain simulation for the dangly bones, foot planting with two-bone IK, hand IK, spine lean and shudder, and a ModelPhysics ragdoll on a wipeout. Weapon mode simulates the dong as a free thrown chain that drags on the ground, can be snagged, and reports hit points and velocities.

File Access
using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// Drives the new, properly rigged lizard model (models/lizard/lizard.vmdl, built in Blender by
/// tools/blender/make_lizard.py). It is the visual only: <see cref="ReptileController"/> still
/// does the moving, and this reads it to choose an animation and then adds a layer of live
/// simulation on top of the animated pose every frame:
///
///  - the tail is a simulated chain that lags, whips and settles with the body's motion;
///  - the spine leans into acceleration and shudders from impacts;
///  - the feet are planted on the surface underneath with two-bone IK, and a hand is taken to
///    the grip point while reaching;
///  - on a wipeout the whole body goes to a physics ragdoll (joints and shapes from the model).
///
/// The simulated layer runs in small even steps, so it behaves the same at any frame rate.
/// This is the default lizard (<see cref="ReptileController.UseNewModel"/>); the original body
/// built from simple shapes (<see cref="ReptileBody"/>) is kept only as a fallback.
/// </summary>
[Title( "Lizard Rig" ), Category( "Player" ), Icon( "accessibility_new" )]
public sealed class LizardRig : Component
{
	public const string ModelPath = "models/lizard/lizard.vmdl";
	public const string PrefabPath = "prefabs/lizard_rig.prefab";

	/// <summary>Size of the model next to the old body.</summary>
	[Property] public float Scale { get; set; } = 1.15f;

	/// <summary>The model was exported facing +Y; this turns it to face the way the lizard does.</summary>
	[Property] public float ModelYaw { get; set; } = -90f;

	/// <summary>The lizard's own orientation (the model object itself is turned by <see cref="ModelYaw"/>).</summary>
	Rotation Frame => GameObject.Parent.IsValid() ? GameObject.Parent.WorldRotation : WorldRotation;

	/// <summary>Turn the whole simulated layer off, leaving only the baked animations.</summary>
	[Property, Group( "Simulation" )] public bool Procedural { get; set; } = true;
	[Property, Group( "Simulation" )] public bool FootIk { get; set; } = true;
	[Property, Group( "Simulation" )] public bool HandIk { get; set; } = true;
	[Property, Group( "Simulation" )] public bool TailPhysics { get; set; } = true;
	[Property, Group( "Simulation" )] public bool RagdollOnWipeout { get; set; } = true;

	/// <summary>
	/// The comedy bits at the groin (bones dangle_0..2 and sack_0). On: they are there, and swing
	/// and bounce with running, jumping and landings. Off: they are shrunk away to nothing.
	/// </summary>
	[Property, Group( "Simulation" )] public bool Dangly { get; set; } = true;

	// ---- Tail: a heavy chain. Each joint is a weight on a spring to where the animation has it.
	// Heavier = slower to follow and longer to settle. Less damping = more overshoot and wag.

	/// <summary>Weight of the tail. Heavier lags further behind the body and takes longer to come to rest.</summary>
	[Property, Group( "Tail Weight" )] public float TailMass { get; set; } = 2.4f;

	/// <summary>How hard the tail is held to its animated pose at the root (firm) and at the tip (floppy).</summary>
	[Property, Group( "Tail Weight" )] public float TailRootStiffness { get; set; } = 260f;
	[Property, Group( "Tail Weight" )] public float TailTipStiffness { get; set; } = 40f;

	/// <summary>Furthest each tail joint may swing from its animated direction, in degrees: tight at the root, loose at the tip.</summary>
	[Property, Group( "Tail Weight" ), Range( 0f, 120f )] public float TailRootSwingLimit { get; set; } = 14f;
	[Property, Group( "Tail Weight" ), Range( 0f, 120f )] public float TailTipSwingLimit { get; set; } = 58f;

	/// <summary>How quickly its swing dies away. Low values overshoot and wag; high values just follow.</summary>
	[Property, Group( "Tail Weight" )] public float TailDamping { get; set; } = 5.5f;

	/// <summary>How much it sags under its own weight, in inches per second squared.</summary>
	[Property, Group( "Tail Weight" )] public float TailGravity { get; set; } = 160f;

	/// <summary>How hard the body's own starts, stops and turns throw it the other way (1 is real inertia).</summary>
	[Property, Group( "Tail Weight" )] public float TailInertia { get; set; } = 1.1f;

	/// <summary>Extra throw toward the tip, so quick changes of direction crack it like a whip.</summary>
	[Property, Group( "Tail Weight" )] public float TailWhip { get; set; } = 1.6f;


	// ---- The dong (dangle_0..2): a short heavy chain hanging under gravity.

	[Property, Group( "Dong Weight" )] public float DongMass { get; set; } = 3f;
	/// <summary>How hard it is held to its rest pose at the root and at the tip. Low: it hangs and swings freely.</summary>
	[Property, Group( "Dong Weight" )] public float DongRootStiffness { get; set; } = 110f;
	[Property, Group( "Dong Weight" )] public float DongTipStiffness { get; set; } = 30f;

	/// <summary>Furthest each joint may swing from its rest direction, in degrees: root and tip.</summary>
	[Property, Group( "Dong Weight" ), Range( 0f, 120f )] public float DongRootSwingLimit { get; set; } = 28f;
	[Property, Group( "Dong Weight" ), Range( 0f, 120f )] public float DongTipSwingLimit { get; set; } = 70f;
	/// <summary>How quickly its swing dies away. Low values flop about for longer.</summary>
	[Property, Group( "Dong Weight" )] public float DongDamping { get; set; } = 3.2f;
	[Property, Group( "Dong Weight" )] public float DongGravity { get; set; } = 520f;
	/// <summary>How hard running, jumping, landing and turning throw it about.</summary>
	[Property, Group( "Dong Weight" )] public float DongInertia { get; set; } = 1.5f;
	/// <summary>Extra throw toward the tip: the flick at the end of a swing.</summary>
	[Property, Group( "Dong Weight" )] public float DongWhip { get; set; } = 1.2f;

	// ---- The sack (sack_0): one weight on a spring, swinging and bouncing on its own.

	[Property, Group( "Sack Weight" )] public float SackMass { get; set; } = 3.6f;
	[Property, Group( "Sack Weight" )] public float SackStiffness { get; set; } = 110f;
	/// <summary>How quickly its bounce dies away. Low values keep bouncing.</summary>
	[Property, Group( "Sack Weight" )] public float SackDamping { get; set; } = 2.6f;
	[Property, Group( "Sack Weight" )] public float SackGravity { get; set; } = 480f;
	/// <summary>How hard landings and stops bounce it.</summary>
	[Property, Group( "Sack Weight" )] public float SackInertia { get; set; } = 1.8f;

	/// <summary>Furthest the sack may swing from hanging straight, in degrees.</summary>
	[Property, Group( "Sack Weight" ), Range( 0f, 120f )] public float SackSwingLimit { get; set; } = 38f;

	// ---- Limits shared by the tail, the dong and the sack

	/// <summary>
	/// Twist allowed about each joint's own length, in degrees, on top of what the animation has.
	/// </summary>
	[Property, Group( "Chain Limits" ), Range( 0f, 90f )] public float TwistLimit { get; set; } = 12f;

	/// <summary>Furthest any joint may drift from where the skeleton has it, as a multiple of its bone length (the root gets about a third of this).</summary>
	[Property, Group( "Chain Limits" )] public float MaxOffset { get; set; } = 1.1f;

	/// <summary>How far the chains are kept clear of the hips and legs, in inches (0 lets them pass through).</summary>
	[Property, Group( "Chain Limits" )] public float BodyClearance { get; set; } = 4.2f;

	// ---- Weapon mode (the Rampage): the same dong and sack, grown and thrown about as a club.
	// Set by DongWeapon. With WeaponMode off, none of this is used and the rig is as it always was.

	/// <summary>On: the dong is a long free chain that is driven, drags on the ground and can be read for hits.</summary>
	public bool WeaponMode { get; set; }

	/// <summary>Length of the dong as a multiple of its natural length (its girth grows with it).</summary>
	public float DongScale { get; set; } = 1f;

	/// <summary>Size of the sack as a multiple of its natural size.</summary>
	public float SackScale { get; set; } = 1f;

	/// <summary>Extra inches of "chain" the sack is let out on (its neck stretches).</summary>
	public float SackChain { get; set; }

	/// <summary>The way the dong is being thrown (world direction), and how hard it is pulled to lie along it (0: left to hang).</summary>
	public Vector3 DongDrive { get; set; }
	public float DongDriveStrength { get; set; }

	/// <summary>The same for the sack.</summary>
	public Vector3 SackDrive { get; set; }
	public float SackDriveStrength { get; set; }

	/// <summary>Extra bend of the spine in degrees (pitch forward, yaw left, roll), for winding up and following through.</summary>
	public Angles BodyThrow { get; set; }

	/// <summary>Extra turn of the whole model about its up axis, in degrees (the sweep's spin).</summary>
	public float SpinYaw { get; set; }

	/// <summary>Moves the whole model off its spot, in the body's own space (a hop).</summary>
	public Vector3 BodyOffset { get; set; }

	/// <summary>Called when the dong (or the sack) comes down on the ground: where, and how fast it was falling.</summary>
	public Action<Vector3, float> DongLanded { get; set; }
	public Action<Vector3, float> SackLanded { get; set; }

	// ---- Weapon mode at giant size (set by DongWeapon; the defaults change nothing) ----

	/// <summary>Multiplies <see cref="WeaponGravity"/> for both weapons. A very long chain under ordinary gravity swings slowly, which is what enormous weight looks like; this trims it.</summary>
	public float WeaponGravityScale { get; set; } = 1f;

	/// <summary>
	/// Extra weight on the far end of the dong (a car hooked on the tip): 0 none, 1 about as much
	/// again. The loaded end answers the throw more slowly, so it lags further and carries on longer.
	/// </summary>
	public float DongTipLoad { get; set; }

	/// <summary>How many steps a second the weapon's chain is worked out in. A big, hard-thrown chain needs small steps to stay stable when frames are long.</summary>
	[Property, Group( "Weapon Chain" )] public float WeaponStepsPerSecond { get; set; } = 180f;

	/// <summary>True while one point of the dong is caught on something (see <see cref="SnagDong"/>).</summary>
	public bool DongSnagged => _snagPoint > 0;
	/// <summary>How far the caught chain is being stretched: 1 is slack or just taut, above that it is being pulled out of shape.</summary>
	public float DongSnagStretch { get; private set; } = 1f;

	/// <summary>
	/// Catches the dong on something: the chain point nearest <paramref name="point"/> (an index
	/// into <see cref="DongPoints"/>) is held at a place in the world, and the rest wraps on round
	/// it under its own momentum, until <see cref="FreeDong"/>.
	/// </summary>
	public void SnagDong( int point, Vector3 at )
	{
		if ( !WeaponMode || !_weaponPrimed || _wNow.Length < 3 ) return;
		_snagPoint = Math.Clamp( point, 1, _wNow.Length - 2 );
		_snagAt = at;
		DongSnagStretch = 1f;
	}

	public void FreeDong()
	{
		_snagPoint = 0;
		DongSnagStretch = 1f;
	}

	/// <summary>
	/// A knock to the dong itself (it has bounced over rubble, or come off a wall): this change of
	/// velocity is given to every point from <paramref name="fromAlong"/> (0 root, 1 tip) outward,
	/// growing toward the tip.
	/// </summary>
	public void DongImpulse( Vector3 velocity, float fromAlong = 0f )
	{
		int count = _wSpeed.Length;
		if ( !WeaponMode || !_weaponPrimed || count < 2 ) return;
		for ( int k = 1; k < count; k++ )
		{
			float along = (float)k / (count - 1);
			if ( along < fromAlong ) continue;
			_wSpeed[k] += velocity * (fromAlong < 1f ? (along - fromAlong) / (1f - fromAlong) * 0.7f + 0.3f : 1f);
		}
	}

	/// <summary>The same for the sack.</summary>
	public void SackImpulse( Vector3 velocity )
	{
		if ( WeaponMode && _sackPrimed ) _sackSpeed += velocity;
	}

	int _snagPoint;
	Vector3 _snagAt;

	[Property, Group( "Weapon Chain" )] public float WeaponGravity { get; set; } = 950f;
	/// <summary>How quickly the weapon's own swing dies away in the air.</summary>
	[Property, Group( "Weapon Chain" )] public float WeaponDamping { get; set; } = 0.7f;
	/// <summary>How hard it resists folding (0 is a rope, high is a pole).</summary>
	[Property, Group( "Weapon Chain" )] public float WeaponStiffness { get; set; } = 110f;
	/// <summary>Damping of the throw, as a share of critical. Low values overshoot and follow through.</summary>
	[Property, Group( "Weapon Chain" ), Range( 0f, 1.5f )] public float WeaponDriveDamping { get; set; } = 0.28f;
	/// <summary>Share of the throw that reaches the tip (the root gets all of it), so the tip lags and then cracks.</summary>
	[Property, Group( "Weapon Chain" ), Range( 0.05f, 1f )] public float WeaponTipLag { get; set; } = 0.5f;
	/// <summary>How fat the far end is next to the root: above 1 it is a club with a thin handle.</summary>
	[Property, Group( "Weapon Chain" ), Range( 0.5f, 4f )] public float WeaponTaper { get; set; } = 1.8f;
	/// <summary>Share of its falling speed it bounces back up with off the ground.</summary>
	[Property, Group( "Weapon Chain" ), Range( 0f, 0.9f )] public float WeaponBounce { get; set; } = 0.38f;
	/// <summary>How quickly dragging along the ground slows it.</summary>
	[Property, Group( "Weapon Chain" )] public float WeaponGroundDrag { get; set; } = 2.2f;
	/// <summary>Look for the ground under each point with a trace. Off: the ground is flat at the lizard's feet.</summary>
	[Property, Group( "Weapon Chain" )] public bool WeaponGroundTrace { get; set; } = true;

	// ---- Body motion

	/// <summary>Degrees the body leans per 1000 inches per second squared of acceleration.</summary>
	[Property, Group( "Body Motion" )] public float LeanPerAcceleration { get; set; } = 9f;

	/// <summary>Degrees it banks into a turn at full sprint while turning hard.</summary>
	[Property, Group( "Body Motion" )] public float TurnBank { get; set; } = 16f;

	/// <summary>Degrees it pitches forward at full sprint.</summary>
	[Property, Group( "Body Motion" )] public float SpeedLean { get; set; } = 11f;

	/// <summary>How springy the lean is, and how quickly it settles.</summary>
	[Property, Group( "Body Motion" )] public float LeanSpring { get; set; } = 60f;
	[Property, Group( "Body Motion" )] public float LeanDamping { get; set; } = 9f;

	/// <summary>Inches the hips rise and fall with each step at a run, and sway from side to side.</summary>
	[Property, Group( "Body Motion" )] public float StepBob { get; set; } = 1.6f;
	[Property, Group( "Body Motion" )] public float StepSway { get; set; } = 1.1f;

	/// <summary>Seconds one animation takes to melt into the next.</summary>
	[Property, Group( "Animation" )] public float BlendSeconds { get; set; } = 0.22f;

	/// <summary>How quickly the speed that picks and paces the walk and run follows the real speed.</summary>
	[Property, Group( "Animation" )] public float SpeedSmoothing { get; set; } = 8f;

	/// <summary>A foot lower than this (inches above the ground in the animation) counts as planted and is held where it lands.</summary>
	[Property, Group( "Foot Planting" )] public float PlantHeight { get; set; } = 1.8f;

	/// <summary>A planted foot lets go once the leg would have to stretch this far to keep it there.</summary>
	[Property, Group( "Foot Planting" )] public float PlantStretch { get; set; } = 9f;

	/// <summary>How firmly a planted foot is held (0 not at all, 1 nailed down).</summary>
	[Property, Group( "Foot Planting" ), Range( 0f, 1f )] public float PlantStrength { get; set; } = 0.85f;

	/// <summary>How far above and below the animated foot the ground is looked for.</summary>
	[Property, Group( "Simulation" )] public float FootProbe { get; set; } = 16f;

	/// <summary>Speeds the walk and run clips were animated at, in inches per second at Scale 1.</summary>
	[Property, Group( "Animation" )] public float WalkSpeed { get; set; } = 150f;
	[Property, Group( "Animation" )] public float RunSpeed { get; set; } = 520f;

	/// <summary>Above this speed it runs instead of walking.</summary>
	[Property, Group( "Animation" )] public float RunAbove { get; set; } = 380f;

	public SkinnedModelRenderer Renderer { get; private set; }

	/// <summary>The animation playing now.</summary>
	public string Current { get; private set; } = "";

	ReptileController _controller;
	LizardAttack _attack;
	CaveSculptor _sculptor;
	StadiumGame _stadium;
	ModelPhysics _ragdoll;
	float _ragdollBroke, _ragdollSince;
	float _blendFor;         // seconds for the blend in progress; 0 uses BlendSeconds
	float _held;             // 0 free .. 1 hands all over him, eased

	/// <summary>A knockdown ragdoll never lasts longer than this.</summary>
	[Property, Group( "Simulation" )] public float MaxRagdollSeconds { get; set; } = 1.6f;

	/// <summary>Seconds to blend from the ragdoll heap back up into the animation.</summary>
	[Property, Group( "Simulation" )] public float GetUpSeconds { get; set; } = 0.55f;

	// ---- Stance: how tall he stands and how much room there is between the legs. All in model
	// inches (multiplied by Scale), so it holds at any size, the giant included.

	/// <summary>How far the hips are raised above where the animation has them.</summary>
	[Property, Group( "Stance" )] public float HipLift { get; set; } = 3f;

	/// <summary>Length of the thigh and shin against the model's own (1 = as built).</summary>
	[Property, Group( "Stance" ), Range( 1f, 1.3f )] public float LegLength { get; set; } = 1.1f;

	/// <summary>How far each hip joint is moved outward, opening the gap between the thighs.</summary>
	[Property, Group( "Stance" )] public float HipSpread { get; set; } = 0.6f;

	/// <summary>How far each foot is set outward of where the animation puts it.</summary>
	[Property, Group( "Stance" )] public float StanceWiden { get; set; } = 1.2f;

	/// <summary>Where the dong hangs from, moved from the model's own anchor: forward, left, up.</summary>
	[Property, Group( "Stance" )] public Vector3 DongAnchor { get; set; } = new Vector3( 0.5f, 0f, -0.6f );

	/// <summary>Where the sack hangs from, moved from the model's own anchor: forward, left, up.</summary>
	[Property, Group( "Stance" )] public Vector3 SackAnchor { get; set; } = new Vector3( 0f, 0f, -0.5f );

	/// <summary>The hanging chains and the tail are kept this far above the ground he stands on.</summary>
	[Property, Group( "Chain Limits" )] public float GroundClearance { get; set; } = 1.5f;

	/// <summary>How far the stance has raised the body right now, in the world. The camera follows it.</summary>
	public float StandLift => HipLift * Scale * _stand;

	float _stand = 1f;       // 0 in the clips that are not stood upright (pinned, climbing), eased

	/// <summary>How hard he writhes and bucks while hands are on him, in degrees at the spine.</summary>
	[Property, Group( "Body Motion" )] public float WritheDegrees { get; set; } = 13f;

	// The skeleton, read once from the model.
	int _boneCount;
	int[] _parent = Array.Empty<int>();
	Transform[] _world = Array.Empty<Transform>();
	readonly Dictionary<string, int> _bone = new();
	int[] _tail = Array.Empty<int>();
	Chain _tailChain = new();

	// Blending from one animation into the next: the pose the old one left off in, relative to the model.
	Transform[] _lastPose = Array.Empty<Transform>(), _blendFrom = Array.Empty<Transform>();
	float _blend = 1f;
	bool _blendStart;
	float _animSpeed, _lastYaw;
	bool _running, _moving;

	// Planted feet.
	readonly Vector3[] _plantAt = new Vector3[2];
	readonly bool[] _planted = new bool[2];

	/// <summary>What one simulated chain weighs and how it is sprung.</summary>
	struct Weight
	{
		public float Mass, RootStiffness, TipStiffness, Damping, Gravity, Inertia, Whip, RootSwing, TipSwing;
	}
	Model _readModel;

	// Tail simulation: one particle at the head of each tail bone after the first, and one at the tip.
	Vector3[] _tailNow = Array.Empty<Vector3>(), _tailBefore = Array.Empty<Vector3>();

	// The dangly bits: the same kind of chain as the tail, one for the appendage and one for the sack.
	sealed class Chain
	{
		public int[] Bones = Array.Empty<int>();
		public Vector3[] Now = Array.Empty<Vector3>(), Before = Array.Empty<Vector3>();
		public bool Primed;

		// Where the skeleton had the chain last frame, and the length of the last step taken, so
		// the simulation can run in small even steps whatever the frame rate.
		public Vector3[] Target = Array.Empty<Vector3>();
		public Vector3 Root;
		public float Step;
	}
	readonly List<Chain> _dangly = new();
	Vector3 _bodyAcceleration;

	// Body dynamics.
	Vector3 _lastVelocity, _lean, _leanVelocity, _shudder, _shudderVelocity;
	Vector3 _pendingChange;   // change of speed not yet fed to the springs (see Lean)
	float _reachBlend;

	// The pose crossfade only starts from a pose that was really captured, and recently.
	bool _poseValid;
	float _poseTime;

	// Foot planting: the correction each ankle had last frame, and what is left of any jump in
	// it, which is bled away so a foot never snaps.
	readonly Vector3[] _footLast = new Vector3[2];
	readonly Vector3[] _footShift = new Vector3[2];

	// The clips this model really has; a missing one falls back to idle instead of being asked for.
	readonly HashSet<string> _sequences = new( StringComparer.OrdinalIgnoreCase );
	bool _sequencesRead;

	/// <summary>
	/// Puts the new model on a player: clones the rig prefab (or builds the same thing in code if
	/// the prefab is missing) under the old body's object, and hides the old body.
	/// </summary>
	public static LizardRig Attach( ReptileController controller )
	{
		if ( !controller.IsValid() ) return null;
		var holder = controller.Body.IsValid() ? controller.Body : controller.GameObject;

		var existing = holder.Components.Get<LizardRig>( FindMode.EverythingInSelfAndDescendants );
		if ( existing.IsValid() ) return existing;

		GameObject go = null;
		var prefab = GameObject.GetPrefab( PrefabPath );
		if ( prefab.IsValid() ) go = prefab.Clone( new Transform(), holder, true, "Lizard Rig" );
		if ( !go.IsValid() ) go = new GameObject( holder, true, "Lizard Rig" );

		go.Flags |= GameObjectFlags.NotSaved;
		go.SetParent( holder, false );
		go.LocalPosition = Vector3.Zero;
		var rig = go.Components.GetOrCreate<LizardRig>();
		var old = holder.Components.Get<ReptileBody>( FindMode.EverythingInSelfAndDescendants );
		if ( old.IsValid() ) old.Hidden = true;
		return rig;
	}

	protected override void OnStart()
	{
		_controller = Components.Get<ReptileController>( FindMode.EverythingInSelfAndAncestors );
		if ( _controller.IsValid() )
		{
			_attack = _controller.Components.Get<LizardAttack>();
			_sculptor = _controller.Components.Get<CaveSculptor>();
		}
		_stadium = StadiumGame.Get( Scene );

		Renderer = Components.GetOrCreate<SkinnedModelRenderer>();
		if ( Renderer.Model is null || Renderer.Model.IsError || Renderer.Model.BoneCount == 0 )
			Renderer.Model = Model.Load( ModelPath );
		Renderer.UseAnimGraph = false;
		LocalScale = Scale;
		ReadSkeleton();
	}

	void ReadSkeleton()
	{
		var model = Renderer?.Model;
		_readModel = model;
		_bone.Clear();
		_boneCount = model?.BoneCount ?? 0;
		_parent = new int[_boneCount];
		_world = new Transform[_boneCount];
		if ( model is null ) return;

		foreach ( var bone in model.Bones.AllBones )
		{
			if ( bone.Index < 0 || bone.Index >= _boneCount ) continue;
			_parent[bone.Index] = bone.Parent?.Index ?? -1;
			_bone[bone.Name] = bone.Index;
		}

		var tail = new List<int>();
		for ( int i = 0; i < 16 && _bone.TryGetValue( "tail_" + i, out int index ); i++ ) tail.Add( index );
		_tail = tail.ToArray();
		_tailNow = new Vector3[_tail.Length];
		_tailBefore = new Vector3[_tail.Length];
		_tailChain = new Chain { Bones = _tail, Now = new Vector3[_tail.Length], Before = new Vector3[_tail.Length] };
		_lastPose = new Transform[_boneCount];
		_blendFrom = new Transform[_boneCount];
		_blend = 1f;
		_poseValid = false;
		_planted[0] = _planted[1] = false;
		_footShift[0] = _footShift[1] = Vector3.Zero;

		_sequences.Clear();
		_sequencesRead = false;

		_dangly.Clear();
		AddChain( "dangle_0", "dangle_1", "dangle_2" );
		AddChain( "sack_0" );
	}

	void AddChain( params string[] names )
	{
		var bones = names.Select( Bone ).Where( i => i >= 0 ).ToArray();
		if ( bones.Length == 0 ) return;
		_dangly.Add( new Chain { Bones = bones, Now = new Vector3[bones.Length], Before = new Vector3[bones.Length] } );
	}

	int Bone( string name ) => _bone.TryGetValue( name, out int index ) ? index : -1;

	/// <summary>World position of a named bone, for things that want to hold on to the lizard.</summary>
	public bool TryBonePosition( string name, out Vector3 position )
	{
		position = default;
		int index = Bone( name );
		if ( index < 0 || !Renderer.IsValid() || Renderer.SceneModel is null ) return false;
		position = Renderer.SceneModel.GetBoneWorldTransform( index ).Position;
		return true;
	}

	/// <summary>Where the end of one of the old body's limbs is on this model ("arm_l", "leg_r", "tail"...).</summary>
	public bool TryLimbTip( string part, out Vector3 position ) => TryBonePosition( part switch
	{
		"arm_l" => "hand_l",
		"arm_r" => "hand_r",
		"leg_l" => "foot_l",
		"leg_r" => "foot_r",
		"tail" => "tail_5",
		_ => "head",
	}, out position );

	/// <summary>A knock: the tail whips and the spine shudders away from it.</summary>
	public void Impulse( Vector3 velocity )
	{
		_shudderVelocity += velocity * 0.02f;
		Knock( _tailChain, velocity * 0.4f );
		foreach ( var chain in _dangly ) Knock( chain, velocity * 0.6f );
	}

	/// <summary>Gives a chain a change of speed, more toward the tip, whatever step it is being simulated at.</summary>
	static void Knock( Chain chain, Vector3 speed )
	{
		// The chain's speed is held as the gap between where it is and where it was a step ago.
		float step = chain.Step > 0.00001f ? chain.Step : 1f / 120f;
		int count = Math.Min( chain.Now.Length, chain.Before.Length );
		for ( int i = 0; i < count; i++ )
			chain.Before[i] -= speed * (step * (i + 1));
	}

	// ---- Which animation -----------------------------------------------------------------------

	protected override void OnUpdate()
	{
		if ( !Renderer.IsValid() ) return;
		if ( Renderer.Model != _readModel ) ReadSkeleton();
		if ( MathF.Abs( LocalScale.x - Scale ) > 0.001f ) LocalScale = Scale;
		if ( !(_ragdoll.IsValid() && _ragdoll.Enabled) ) LocalRotation = Rotation.FromYaw( ModelYaw + (WeaponMode ? SpinYaw : 0f) );

		// A hop (weapon mode only); put back exactly once when it ends.
		var offset = WeaponMode ? BodyOffset : Vector3.Zero;
		if ( offset != _offsetApplied && !(_ragdoll.IsValid() && _ragdoll.Enabled) ) { LocalPosition = offset; _offsetApplied = offset; }

		UpdateRagdoll();
		if ( _ragdoll.IsValid() && _ragdoll.Enabled ) return;

		// Nothing to animate while the body is hidden (a memory is being relived in another
		// shape), the model failed to load, or it has no skeleton.
		if ( !Renderer.Enabled || Renderer.SceneModel is null || _boneCount == 0 ) { Current = ""; _poseValid = false; return; }

		string name = "idle";
		bool loop = true;
		float rate = 1f;
		float scrub = -1f;   // 0..1 to hold the clip at a point instead of letting it run

		bool has = _controller.IsValid();
		// The speed that picks and paces the clips follows the real speed smoothly, so a stumble or
		// a single slow frame does not flick the animation, and the switches have some give in them.
		float realSpeed = has ? _controller.Velocity.Length : 0f;
		_animSpeed += (realSpeed - _animSpeed) * MathF.Min( Time.Delta * SpeedSmoothing, 1f );
		float speed = _animSpeed;
		_running = speed > (_running ? RunAbove * 0.85f : RunAbove);
		_moving = speed > (_moving ? 14f : 28f);
		_stadium ??= StadiumGame.Get( Scene );

		if ( _stadium.IsValid() && _stadium.Phase == StadiumPhase.Shapeshift )
		{
			name = "shapeshift"; loop = false;
			scrub = Math.Clamp( _stadium.ShiftProgress, 0f, 1f );
		}
		else if ( has && (_controller.IsPinned || _controller.Leash.HasValue) )
		{
			name = "struggle"; rate = 1.2f;
		}
		else if ( _attack.IsValid() && _attack.Phase > 0f )
		{
			name = "bite"; loop = false;
			scrub = Math.Clamp( _attack.Phase, 0f, 1f );
		}
		else if ( has && _controller.IsLatching )
		{
			// The reach, then the pull: the controller's own latch drives the clip position.
			bool pulling = _controller.LegTuck > 0.02f;
			name = pulling ? "climb_pull" : "climb_reach"; loop = false;
			scrub = Math.Clamp( pulling ? _controller.LegTuck : _controller.ReachAmount, 0f, 1f );
		}
		else if ( has && _controller.IsReaching )
		{
			name = "climb_reach"; loop = false;
			scrub = Math.Clamp( _controller.ReachAmount, 0f, 1f );
		}
		else if ( Sculpting( true ) ) name = "dig";
		else if ( Sculpting( false ) ) name = "raise";
		else if ( _running ) { name = "run"; rate = speed / MathF.Max( RunSpeed * Scale, 1f ); }
		else if ( _moving ) { name = "walk"; rate = speed / MathF.Max( WalkSpeed * Scale, 1f ); }

		// A clip this model does not have is never asked for (asking fails inside the engine,
		// every frame): it stands in idle, or keeps what it has.
		// (Only trusted when the list has "idle" in it, which shows it uses the names we do.)
		var sequence = Renderer.Sequence;
		if ( sequence is null ) return;
		if ( !_sequencesRead )
		{
			_sequencesRead = true;
			var names = sequence.SequenceNames;
			if ( names is not null )
				foreach ( var sequenceName in names )
					if ( !string.IsNullOrEmpty( sequenceName ) ) _sequences.Add( sequenceName );
		}
		if ( _sequences.Contains( "idle" ) && !_sequences.Contains( name ) )
		{
			name = "idle"; loop = true; rate = 1f; scrub = -1f;
		}
		if ( Current != name )
		{
			// Walk and run hand over mid-stride: the new clip starts at the same point in the step.
			bool gait = (Current == "walk" || Current == "run") && (name == "walk" || name == "run");
			float phase = gait ? sequence.TimeNormalized : 0f;

			Current = name;
			sequence.Blending = true;
			sequence.Name = name;
			sequence.Looping = loop;
			if ( scrub < 0f )
			{
				if ( gait ) sequence.TimeNormalized = phase;
				else sequence.Time = 0f;
			}
			_blendStart = true;   // and the pose melts across (see Crossfade)
		}
		if ( scrub >= 0f )
		{
			sequence.PlaybackRate = 0f;
			sequence.TimeNormalized = scrub;
		}
		else sequence.PlaybackRate = Math.Clamp( rate, 0.3f, 2.5f );
	}

	bool Sculpting( bool dig )
	{
		if ( !_sculptor.IsValid() || !_sculptor.Enabled || !_controller.IsValid() || _controller.InputLocked ) return false;
		string action = dig ? _sculptor.DigAction : _sculptor.RaiseAction;
		return !string.IsNullOrEmpty( action ) && Input.Down( action );
	}

	// ---- Ragdoll -------------------------------------------------------------------------------

	void UpdateRagdoll()
	{
		bool want = RagdollOnWipeout && _stadium.IsValid() && _stadium.Charge.IsValid() && _stadium.Charge.WipedOut;
		bool on = _ragdoll.IsValid() && _ragdoll.Enabled;

		// A ragdoll is for a knockdown, and only for a moment. With hands on him he stays on his
		// feet and fights (see Writhe), and nothing may leave him lying limp for longer than this.
		if ( HandsOnHim() > 0 ) want = false;
		if ( on && Time.Now - _ragdollSince > MaxRagdollSeconds ) { want = false; _ragdollBroke = Time.Now + 1f; }

		// The lizard itself stays put while its body is a ragdoll, so the two do not pull apart.
		if ( _controller.IsValid() ) _controller.SetSpeedFactor( "ragdoll", on ? 0f : 1f );

		// Safety: if any part has come away from the hips (a joint has given up), stop at once
		// rather than draw a stretched body.
		if ( on && want )
		{
			Vector3? hips = null;
			foreach ( var body in _ragdoll.Bodies )
			{
				if ( !body.Component.IsValid() ) continue;
				hips ??= body.Component.WorldPosition;
				if ( (body.Component.WorldPosition - hips.Value).Length > 95f * Scale ) { want = false; _ragdollBroke = Time.Now + 3f; break; }
			}
		}
		if ( Time.Now < _ragdollBroke ) want = false;
		if ( want == on ) return;

		if ( want )
		{
			if ( !Renderer.Model.IsValid() || Renderer.Model.Physics is null || Renderer.Model.Physics.Parts.Count == 0 ) return;
			if ( !_ragdoll.IsValid() )
			{
				_ragdoll = Components.Create<ModelPhysics>( false );
				_ragdoll.Model = Renderer.Model;
				_ragdoll.Renderer = Renderer;
			}
			_ragdoll.Enabled = true;
			_ragdollSince = Time.Now;

			// It goes down carrying the speed it had.
			var velocity = _controller.IsValid() ? _controller.Velocity : Vector3.Zero;
			foreach ( var body in _ragdoll.Bodies )
				if ( body.Component.IsValid() ) body.Component.Velocity = velocity * 0.6f + Vector3.Random * 60f;
		}
		else
		{
			EndRagdoll();
		}
	}

	/// <summary>
	/// Stands the model back up out of the ragdoll. The physics component is removed outright, not
	/// just switched off: left in place it kept hold of the bones, and the lizard stayed lying where
	/// it fell, limp, for as long as anything else was going on (being grabbed, most visibly). The
	/// pose it was lying in is kept for a moment so the animation blends up out of it.
	/// </summary>
	void EndRagdoll()
	{
		bool wasDown = _ragdoll.IsValid() && _ragdoll.Enabled;
		var scene = Renderer.IsValid() ? Renderer.SceneModel : null;

		// Where every bone is lying now, before anything is put back.
		bool captured = false;
		if ( wasDown && scene is not null && _boneCount > 0 && _world.Length == _boneCount && _blendFrom.Length == _boneCount && _lastPose.Length == _boneCount )
		{
			for ( int i = 0; i < _boneCount; i++ ) _world[i] = scene.GetBoneWorldTransform( i );
			captured = true;
		}

		if ( _ragdoll.IsValid() ) _ragdoll.Destroy();
		_ragdoll = null;

		// Anything the ragdoll hung on the model to carry its bones goes with it.
		for ( int i = GameObject.Children.Count - 1; i >= 0; i-- )
		{
			var child = GameObject.Children[i];
			if ( !child.IsValid() ) continue;
			if ( child.Flags.Contains( GameObjectFlags.Bone ) || child.Flags.Contains( GameObjectFlags.PhysicsBone ) ) child.Destroy();
		}
		if ( Renderer.IsValid() )
		{
			Renderer.CreateBoneObjects = false;
			Renderer.UseAnimGraph = false;
		}
		scene?.ClearBoneOverrides();

		LocalPosition = Vector3.Zero;
		LocalRotation = Rotation.FromYaw( ModelYaw );
		Current = "";                       // the animation is chosen and started again next update
		_tailChain.Primed = false;
		foreach ( var chain in _dangly ) chain.Primed = false;
		_planted[0] = _planted[1] = false;
		_footShift[0] = _footShift[1] = Vector3.Zero;

		if ( captured )
		{
			// Blend from the heap to the animated pose, slowly enough to read as getting up.
			var model = WorldTransform;
			for ( int i = 0; i < _boneCount; i++ ) { _blendFrom[i] = model.ToLocal( _world[i] ); _lastPose[i] = _blendFrom[i]; }
			_blend = 0f;
			_blendFor = GetUpSeconds;
			_poseValid = true;
			_poseTime = Time.Now;
		}
		else _poseValid = false;
	}

	/// <summary>How many pairs of hands the crowd has on him right now (the stadium, or whoever is running a crowd).</summary>
	int HandsOnHim()
	{
		if ( _stadium.IsValid() ) return _stadium.Grabbers;
		var host = CrowdHosts.Fallback;
		return host.IsValid() ? host.Grabbers : 0;
	}

	/// <summary>
	/// Switched off (the old body chosen, a memory relived in another shape, the scene ending):
	/// the lizard must not be left frozen by a ragdoll that is no longer being watched.
	/// </summary>
	protected override void OnDisabled()
	{
		if ( _ragdoll.IsValid() && _ragdoll.Enabled ) EndRagdoll();
		if ( _controller.IsValid() ) _controller.SetSpeedFactor( "ragdoll", 1f );
		Current = "";
		_poseValid = false;
	}

	// ---- The simulated layer, on top of the animated pose --------------------------------------

	protected override void OnPreRender()
	{
		if ( !Procedural || !Renderer.IsValid() || _boneCount == 0 ) return;
		if ( _ragdoll.IsValid() && _ragdoll.Enabled ) return;
		var scene = Renderer.SceneModel;
		if ( scene is null ) return;

		// A hotload (or a model swap) can leave the working arrays the wrong size.
		if ( _lastPose.Length != _boneCount || _blendFrom.Length != _boneCount || _world.Length != _boneCount || _tailChain.Now.Length != _tail.Length )
		{
			ReadSkeleton();
			if ( _boneCount == 0 ) return;
		}

		for ( int i = 0; i < _boneCount; i++ ) _world[i] = scene.GetBoneWorldTransform( i );

		float dt = MathF.Min( Time.Delta, 1f / 20f );
		if ( dt <= 0f ) return;

		Crossfade( dt );
		Lean( dt );
		Stand( dt );
		if ( WeaponMode ) Throw();
		Stride();
		FindKeepOut();
		if ( TailPhysics ) Simulate( _tailChain, TailWeight, dt, 0.9f );
		Dangle( dt );
		if ( HandIk ) Hands( dt );
		if ( FootIk ) Feet( dt );

		for ( int i = 0; i < _boneCount; i++ ) scene.SetBoneWorldTransform( i, _world[i] );
	}

	/// <summary>Turns a bone, and everything hanging off it, about the bone's own joint.</summary>
	void Turn( int bone, Rotation by )
	{
		if ( bone < 0 ) return;
		var pivot = _world[bone].Position;
		_world[bone].Rotation = by * _world[bone].Rotation;
		for ( int i = bone + 1; i < _boneCount; i++ )
		{
			if ( !Under( i, bone ) ) continue;
			_world[i].Position = pivot + by * (_world[i].Position - pivot);
			_world[i].Rotation = by * _world[i].Rotation;
		}
	}

	/// <summary>Moves a bone, and everything hanging off it.</summary>
	void Shift( int bone, Vector3 by )
	{
		if ( bone < 0 ) return;
		_world[bone].Position += by;
		for ( int i = bone + 1; i < _boneCount; i++ )
			if ( Under( i, bone ) ) _world[i].Position += by;
	}

	bool Under( int bone, int ancestor )
	{
		for ( int p = _parent[bone], guard = 0; p >= 0 && guard < 64; p = _parent[p], guard++ )
			if ( p == ancestor ) return true;
		return false;
	}

	/// <summary>The body leans into its acceleration and shudders after a knock, as damped springs.</summary>
	void Lean( float dt )
	{
		var velocity = _controller.IsValid() ? _controller.Velocity : Vector3.Zero;
		var change = velocity - _lastVelocity;
		_lastVelocity = velocity;

		// The lizard moves in fixed ticks, so its speed changes in steps: on one frame in two or
		// three at a high frame rate, every frame at a low one. Taken raw, the same shove would be
		// a bigger spike the faster the game runs. So the change is fed in over a twentieth of a
		// second instead: the same total push at any frame rate.
		float feed = 1f - MathF.Exp( -dt * 20f );
		_pendingChange += change;
		var fed = _pendingChange * feed;
		_pendingChange -= fed;
		var acceleration = (fed / dt).ClampLength( 6000f );
		_bodyAcceleration = acceleration;

		// A sudden change of speed is an impact: the tail and spine take it.
		float jolt = change.Length;
		if ( jolt > 180f ) Impulse( -change / jolt * MathF.Min( jolt, 400f ) );

		// How fast the body is swinging round, for banking and for flinging the tail.
		float yaw = Frame.Angles().yaw;
		float yawRate = Math.Clamp( Angles.NormalizeAngle( yaw - _lastYaw ) / dt, -720f, 720f );
		_lastYaw = yaw;
		float sprint = _controller.IsValid() ? MathF.Max( _controller.SprintSpeed, 1f ) : 620f;
		float pace = Math.Clamp( velocity.Length / sprint, 0f, 1.3f );

		// Spring toward a lean made of three things, in the body's own frame: back or forward with
		// acceleration, forward with speed, and banked into the turn.
		var local = Frame.Inverse * acceleration;
		var want = new Vector3( local.x, local.y, 0f ) * (LeanPerAcceleration / 1000f);
		want = want.ClampLength( 22f );
		want.x -= SpeedLean * pace * 2f;                                   // forward into the run
		want.y += TurnBank * 2f * pace * Math.Clamp( yawRate / 220f, -1f, 1f );   // into the turn
		// Both springs in small even steps, so they settle the same at any frame rate.
		int steps = Math.Clamp( (int)MathF.Ceiling( dt * 120f - 0.001f ), 1, 6 );
		float h = dt / steps;
		for ( int step = 0; step < steps; step++ )
		{
			_leanVelocity += ((want - _lean) * LeanSpring - _leanVelocity * LeanDamping) * h;
			_lean += _leanVelocity * h;

			_shudderVelocity += (-_shudder * 260f - _shudderVelocity * 9f) * h;
			_shudder += _shudderVelocity * h;
		}
		_lean = _lean.ClampLength( 60f );
		_shudder = _shudder.ClampLength( 30f );

		// Pitch back when speeding up, roll into a turn; shared out up the spine.
		var total = _lean + new Vector3( _shudder.x, _shudder.y, 0f );

		// Hands on him: he stays upright and fights it. The spine bucks and rolls, the shoulders
		// and neck twist against each other, harder with every extra pair of hands.
		int hands = HandsOnHim();
		_held += ((hands > 0 ? MathF.Min( 0.55f + 0.2f * hands, 1.2f ) : 0f) - _held) * MathF.Min( dt * 6f, 1f );
		if ( _held > 0.01f )
		{
			float t = Time.Now;
			float w = WritheDegrees * _held;
			total += new Vector3( MathF.Sin( t * 13f ) * 0.7f + MathF.Sin( t * 5.3f ) * 0.45f, MathF.Sin( t * 9.1f + 1.3f ), 0f ) * w;
			Turn( Bone( "spine_1" ), Rotation.FromAxis( Frame.Up, MathF.Sin( t * 8.2f ) * w ) );
			Turn( Bone( "neck_0" ), Rotation.FromAxis( Frame.Up, MathF.Sin( t * 11.4f + 2f ) * w * 1.3f ) );
		}

		if ( total.Length < 0.05f ) return;
		var by = Frame * Rotation.From( -total.x * 0.5f, 0f, total.y * 0.5f ) * Frame.Inverse;
		Turn( Bone( "spine_0" ), by );
		Turn( Bone( "spine_2" ), by );
	}

	Weight TailWeight => new Weight { Mass = TailMass, RootStiffness = TailRootStiffness, TipStiffness = TailTipStiffness, Damping = TailDamping, Gravity = TailGravity, Inertia = TailInertia, Whip = TailWhip, RootSwing = TailRootSwingLimit, TipSwing = TailTipSwingLimit };
	Weight DongWeight => new Weight { Mass = DongMass, RootStiffness = DongRootStiffness, TipStiffness = DongTipStiffness, Damping = DongDamping, Gravity = DongGravity, Inertia = DongInertia, Whip = DongWhip, RootSwing = DongRootSwingLimit, TipSwing = DongTipSwingLimit };
	Weight SackWeight => new Weight { Mass = SackMass, RootStiffness = SackStiffness, TipStiffness = SackStiffness, Damping = SackDamping, Gravity = SackGravity, Inertia = SackInertia, Whip = 0f, RootSwing = SackSwingLimit, TipSwing = SackSwingLimit };

	// The hips and legs, as balls the chains may not enter. Filled once a frame.
	readonly List<(Vector3 Centre, float Radius)> _keepOut = new();

	void FindKeepOut()
	{
		_keepOut.Clear();
		if ( BodyClearance <= 0f ) return;
		float r = BodyClearance * Scale;
		int pelvis = Bone( "pelvis" );
		if ( pelvis >= 0 ) _keepOut.Add( (_world[pelvis].Position, r * 1.5f) );
		int belly = Bone( "spine_0" );
		if ( belly >= 0 && !WeaponMode ) _keepOut.Add( (_world[belly].Position, r) );   // the weapon is free to swing up
		for ( int side = 0; side < 2; side++ )
		{
			string suffix = side == 0 ? "_l" : "_r";
			int upper = Bone( "leg_upper" + suffix ), lower = Bone( "leg_lower" + suffix ), foot = Bone( "foot" + suffix );
			if ( upper < 0 || lower < 0 ) continue;
			var hip = _world[upper].Position;
			var knee = _world[lower].Position;
			_keepOut.Add( (hip, r * 1.15f) );
			_keepOut.Add( (Vector3.Lerp( hip, knee, 0.5f ), r) );
			_keepOut.Add( (knee, r * 0.85f) );
			if ( foot >= 0 ) _keepOut.Add( (Vector3.Lerp( knee, _world[foot].Position, 0.5f ), r * 0.7f) );
		}
	}

	/// <summary>Pushes a point out of the hips and legs.</summary>
	Vector3 KeepOut( Vector3 point )
	{
		foreach ( var (centre, radius) in _keepOut )
		{
			var away = point - centre;
			float distance = away.Length;
			if ( distance >= radius ) continue;
			point = distance > 0.001f ? centre + away / distance * radius : centre + Frame.Backward * radius;
		}
		return point;
	}

	/// <summary>Holds a direction within a cone of so many degrees about another.</summary>
	static Vector3 WithinCone( Vector3 direction, Vector3 axis, float degrees )
	{
		float cos = Math.Clamp( Vector3.Dot( direction, axis ), -1f, 1f );
		float angle = MathF.Acos( cos ) * (180f / MathF.PI);
		if ( angle <= degrees ) return direction;

		var hinge = Vector3.Cross( axis, direction );
		if ( hinge.Length < 0.0001f ) return axis;
		return (Rotation.FromAxis( hinge.Normal, degrees ) * axis).Normal;
	}

	/// <summary>
	/// Melts the pose of the animation that just ended into the one that just began, so nothing
	/// snaps. The old pose is held as it was left and faded out over <see cref="BlendSeconds"/>.
	/// </summary>
	void Crossfade( float dt )
	{
		var model = WorldTransform;

		// The pose to blend from has to be one this model was really drawn in a moment ago. Just
		// made, just re-read, or back from being hidden or a ragdoll, there is none: cut, don't blend.
		if ( _poseValid && Time.Now - _poseTime > 0.25f ) _poseValid = false;

		if ( _blendStart )
		{
			_blendStart = false;
			if ( !_poseValid ) _blend = 1f;
			else
			{
				if ( _blend >= 1f ) Array.Copy( _lastPose, _blendFrom, _boneCount );
				else
				{
					// Already mid-blend: carry on from what is on screen now.
					float was = Ease( _blend );
					for ( int i = 0; i < _boneCount; i++ ) _blendFrom[i] = Mix( _blendFrom[i], _lastPose[i], was );
				}
				_blend = 0f;
			}
		}
		else if ( !_poseValid ) _blend = 1f;   // a blend in progress has lost what it was coming from

		// Remember this frame's animated pose, relative to the model, before anything is added.
		for ( int i = 0; i < _boneCount; i++ ) _lastPose[i] = model.ToLocal( _world[i] );
		_poseValid = true;
		_poseTime = Time.Now;

		if ( _blend >= 1f ) { _blendFor = 0f; return; }
		_blend = MathF.Min( _blend + dt / MathF.Max( _blendFor > 0f ? _blendFor : BlendSeconds, 0.01f ), 1f );
		float t = Ease( _blend );
		for ( int i = 0; i < _boneCount; i++ ) _world[i] = model.ToWorld( Mix( _blendFrom[i], _lastPose[i], t ) );
	}

	static float Ease( float t ) => t * t * (3f - 2f * t);

	static Transform Mix( Transform a, Transform b, float t ) =>
		new Transform( Vector3.Lerp( a.Position, b.Position, t ), Rotation.Slerp( a.Rotation, b.Rotation, t ), b.Scale );

	/// <summary>
	/// Stands him taller than the clips were made: the hips go up, the thighs and shins are
	/// lengthened and set a little wider, and each leg is solved again so the foot stays exactly
	/// where the animation had it, flat on the ground. The dong and the sack are hung a little
	/// lower and further forward, clear of the thighs. Everything after this (the stride, the
	/// chains, the foot planting) works from the taller pose.
	/// </summary>
	void Stand( float dt )
	{
		bool upright = Current != "struggle" && Current != "shapeshift" && Current != "climb_reach";
		_stand += ((upright ? 1f : 0f) - _stand) * MathF.Min( dt * 8f, 1f );

		int pelvis = Bone( "pelvis" );
		if ( pelvis < 0 ) return;
		var up = Frame.Up;
		var left = Frame.Left;
		float amount = Math.Clamp( _stand, 0f, 1f );

		// The chains' anchors, first, so they ride with the hips.
		if ( Dangly )
		{
			var forward = Frame.Forward;
			var dong = DongAnchor * Scale;
			var sack = SackAnchor * Scale;
			Shift( Bone( "dangle_0" ), forward * dong.x + left * dong.y + up * dong.z );
			Shift( Bone( "sack_0" ), forward * sack.x + left * sack.y + up * sack.z );
		}

		if ( amount < 0.001f ) return;
		float lift = HipLift * Scale * amount;
		float longer = (Math.Clamp( LegLength, 1f, 1.3f ) - 1f) * amount;
		if ( lift < 0.001f && longer < 0.0001f && HipSpread <= 0f && StanceWiden <= 0f ) return;

		// Where the animation has the feet: they stay there.
		Span<Vector3> ankle = stackalloc Vector3[2];
		Span<Rotation> footTurn = stackalloc Rotation[2];
		Span<int> upper = stackalloc int[2], lower = stackalloc int[2], foot = stackalloc int[2];
		for ( int side = 0; side < 2; side++ )
		{
			string suffix = side == 0 ? "_l" : "_r";
			upper[side] = Bone( "leg_upper" + suffix ); lower[side] = Bone( "leg_lower" + suffix ); foot[side] = Bone( "foot" + suffix );
			if ( foot[side] < 0 ) continue;
			ankle[side] = _world[foot[side]].Position;
			footTurn[side] = _world[foot[side]].Rotation;
		}

		Shift( pelvis, up * lift );

		for ( int side = 0; side < 2; side++ )
		{
			if ( upper[side] < 0 || lower[side] < 0 || foot[side] < 0 ) continue;
			var outward = side == 0 ? left : -left;

			// Hips a little further apart, thigh and shin a little longer.
			Shift( upper[side], outward * (HipSpread * Scale * amount) );
			var hip = _world[upper[side]].Position;
			Shift( lower[side], (_world[lower[side]].Position - hip) * longer );
			var knee = _world[lower[side]].Position;
			Shift( foot[side], (_world[foot[side]].Position - knee) * longer );

			// The foot back where it was (a touch wider), within what the leg can reach.
			var target = ankle[side] + outward * (StanceWiden * Scale * amount);
			float leg = (knee - hip).Length + (_world[foot[side]].Position - knee).Length;
			var reach = target - hip;
			float distance = reach.Length;
			if ( leg > 0.02f && distance > 0.001f )
			{
				float held = Math.Clamp( distance, leg * 0.35f, leg * 0.985f );
				if ( held != distance ) target = hip + reach / distance * held;
			}
			SolveLimb( upper[side], lower[side], foot[side], target );

			// And lying the way the animation had it, not tipped by the new knee angle.
			Turn( foot[side], footTurn[side] * _world[foot[side]].Rotation.Inverse );
		}
	}

	/// <summary>Keeps a point of a hanging chain off the ground he is standing on.</summary>
	Vector3 AboveGround( Vector3 point )
	{
		if ( GroundClearance <= 0f || !_controller.IsValid() || !_controller.Attached ) return point;
		var up = Frame.Up;
		float height = Vector3.Dot( point - WorldPosition, up );
		float least = GroundClearance * Scale;
		return height < least ? point + up * (least - height) : point;
	}

	/// <summary>Weight shift: the hips rise and fall twice a stride and sway once, more the faster it goes.</summary>
	void Stride()
	{
		if ( Current != "walk" && Current != "run" ) return;
		int pelvis = Bone( "pelvis" );
		if ( pelvis < 0 ) return;

		float sprint = _controller.IsValid() ? MathF.Max( _controller.SprintSpeed, 1f ) : 620f;
		float pace = Math.Clamp( _animSpeed / sprint, 0f, 1f );
		float phase = Renderer.Sequence.TimeNormalized * MathF.PI * 2f;
		var up = Frame.Up;
		var side = Frame.Left;
		Shift( pelvis, up * (MathF.Sin( phase * 2f ) * StepBob * Scale * pace) + side * (MathF.Sin( phase ) * StepSway * Scale * (0.4f + 0.6f * pace)) );
	}

	/// <summary>
	/// One hanging chain with real weight. Every joint is a mass on a spring to where the skeleton
	/// has it. It is thrown the opposite way to each change in the body's motion (inertia), pulled
	/// down by gravity, keeps its momentum, and loses it only slowly, so it lags, overshoots when
	/// the body stops or turns, and flops to rest. Joints are held at bone length from the one
	/// above, and the bones are then pointed along the result.
	/// </summary>
	void Simulate( Chain chain, Weight weight, float dt, float tipLength )
	{
		int count = chain.Bones.Length;
		if ( count == 0 ) return;

		// Where the skeleton puts the far end of each bone: the next joint, or for the last bone
		// a bone-length further on.
		Span<Vector3> target = stackalloc Vector3[count];
		var root = _world[chain.Bones[0]].Position;
		for ( int i = 0; i < count; i++ )
		{
			if ( i + 1 < count ) { target[i] = _world[chain.Bones[i + 1]].Position; continue; }
			var along = i > 0
				? (_world[chain.Bones[i]].Position - _world[chain.Bones[i - 1]].Position) * tipLength
				: -Frame.Up * (3f * Scale);   // a single bone hangs straight down the body
			target[i] = _world[chain.Bones[i]].Position + along;
		}

		if ( chain.Now.Length != count || chain.Before.Length != count )
		{
			chain.Now = new Vector3[count];
			chain.Before = new Vector3[count];
			chain.Primed = false;
		}
		if ( chain.Target.Length != count ) { chain.Target = new Vector3[count]; chain.Primed = false; }

		if ( !chain.Primed || (chain.Now[0] - target[0]).Length > 200f )
		{
			for ( int i = 0; i < count; i++ ) chain.Now[i] = chain.Before[i] = chain.Target[i] = target[i];
			chain.Root = root;
			chain.Step = 0f;
			chain.Primed = true;
		}

		// Small even steps, so the springs and the damping behave the same at 30 frames a second
		// as at 144: a long frame is cut into several steps, with the skeleton's own motion spread
		// across them, and the carried speed is corrected for any change in step length.
		int steps = Math.Clamp( (int)MathF.Ceiling( dt * 120f - 0.001f ), 1, 6 );
		float h = dt / steps;
		Span<Vector3> aim = stackalloc Vector3[count];
		float mass = MathF.Max( weight.Mass, 0.05f );

		for ( int step = 0; step < steps; step++ )
		{
			float through = (step + 1f) / steps;
			var rootNow = Vector3.Lerp( chain.Root, root, through );
			for ( int i = 0; i < count; i++ ) aim[i] = Vector3.Lerp( chain.Target[i], target[i], through );
			float carry = chain.Step > 0.00001f ? Math.Clamp( h / chain.Step, 0.25f, 4f ) : 1f;
			chain.Step = h;

			for ( int i = 0; i < count; i++ )
			{
				float along = count > 1 ? (float)i / (count - 1) : 1f;   // 0 at the root, 1 at the tip

				// Spring and damping, both weaker for a heavier chain and toward the tip.
				float stiffness = weight.RootStiffness + (weight.TipStiffness - weight.RootStiffness) * along;
				float loose = weight.RootStiffness > 0.01f ? Math.Clamp( stiffness / weight.RootStiffness, 0.05f, 1f ) : 1f;
				float spring = MathF.Min( stiffness / mass, 1.5f / (h * h) );   // never stiffer than a step can hold
				float keep = MathF.Exp( -MathF.Max( weight.Damping, 0f ) * (0.6f + 0.4f * loose) / mass * h );

				var pull = (aim[i] - chain.Now[i]) * spring
					+ Vector3.Down * weight.Gravity
					- _bodyAcceleration * (weight.Inertia * (1f + weight.Whip * along));

				var next = chain.Now[i] + (chain.Now[i] - chain.Before[i]) * (carry * keep) + pull * (h * h);
				chain.Before[i] = chain.Now[i];

				// Held at bone length from the joint above.
				var anchor = i == 0 ? rootNow : chain.Now[i - 1];
				var restAnchor = i == 0 ? rootNow : aim[i - 1];
				float length = (aim[i] - restAnchor).Length;

				// Never further from where the skeleton has it than this.
				var drift = next - aim[i];
				float furthest = length * MathF.Max( MaxOffset, 0f ) * (0.35f + 0.65f * along);
				if ( drift.Length > furthest ) next = aim[i] + drift.Normal * furthest;

				// Not through the hips, the legs or the belly, and not into the ground.
				next = AboveGround( KeepOut( next ) );

				// The swing limit of this joint: a cone about its rest direction, tight at the root
				// and loose at the tip. Hitting the limit stops it (no bouncing on through the body).
				var span = next - anchor;
				var restSpan = aim[i] - restAnchor;
				if ( span.Length > 0.001f && restSpan.Length > 0.001f )
				{
					float limit = weight.RootSwing + (weight.TipSwing - weight.RootSwing) * along;
					var held = WithinCone( span.Normal, restSpan.Normal, limit );
					bool stopped = Vector3.Dot( held, span.Normal ) < 0.9999f;
					next = anchor + held * length;
					// Most of its speed is lost on the stop (the same share each second, however many steps that is).
					if ( stopped ) chain.Before[i] = Vector3.Lerp( chain.Before[i], next, 1f - MathF.Exp( -75f * h ) );
				}
				else next = aim[i];

				// A bad number must not live on in the chain: start it again from the skeleton.
				if ( float.IsNaN( next.x ) || float.IsNaN( next.y ) || float.IsNaN( next.z ) ) { next = aim[i]; chain.Before[i] = next; }
				chain.Now[i] = next;
			}
		}

		for ( int i = 0; i < count; i++ ) chain.Target[i] = target[i];
		chain.Root = root;

		// Point each bone down the simulated chain. The shortest turn from the rest direction to
		// the simulated one carries no twist of its own; a small extra twist follows the sideways
		// swing (capped by TwistLimit) so a hard flick rolls the chain a little instead of looking rigid.
		for ( int i = 0; i < count; i++ )
		{
			int bone = chain.Bones[i];
			var head = _world[bone].Position;
			var rest = (target[i] - (i == 0 ? root : target[i - 1])).Normal;
			var simulated = (chain.Now[i] - head).Normal;
			if ( rest.Length < 0.5f || simulated.Length < 0.5f ) continue;
			Turn( bone, Rotation.FromToRotation( rest, simulated ) );

			if ( TwistLimit > 0f )
			{
				float sideways = Vector3.Dot( simulated - rest, Frame.Left );
				float twist = Math.Clamp( sideways * 40f, -TwistLimit, TwistLimit );
				if ( MathF.Abs( twist ) > 0.05f ) Turn( bone, Rotation.FromAxis( simulated, twist ) );
			}
		}
	}

	/// <summary>
	/// The dong and the sack. On: each is its own weighted chain, so they swing and bounce
	/// separately. Off: the bones are shrunk to nothing and the mesh goes with them.
	/// </summary>
	void Dangle( float dt )
	{
		foreach ( var chain in _dangly )
		{
			if ( !Dangly )
			{
				foreach ( int bone in chain.Bones ) _world[bone] = _world[bone].WithScale( 0.001f );
				chain.Primed = false;
				continue;
			}
			if ( WeaponMode )
			{
				if ( chain.Bones.Length > 1 ) SimulateDong( chain, dt ); else SimulateSack( chain, dt );
				chain.Primed = false;   // the ordinary chain starts afresh when the weapon is put away
				continue;
			}
			Simulate( chain, chain.Bones.Length > 1 ? DongWeight : SackWeight, dt, 1f );
		}
		if ( !WeaponMode || !Dangly ) { _weaponPrimed = false; _sackPrimed = false; }
	}

	// ---- Weapon mode ---------------------------------------------------------------------------

	/// <summary>Points simulated along each dong bone.</summary>
	const int WeaponSub = 2;

	Vector3 _offsetApplied;
	Vector3[] _wNow = Array.Empty<Vector3>(), _wStart = Array.Empty<Vector3>(), _wSpeed = Array.Empty<Vector3>(), _wVelocity = Array.Empty<Vector3>();
	float[] _wGround = Array.Empty<float>(), _wSegment = Array.Empty<float>(), _wRadius = Array.Empty<float>();
	bool _weaponPrimed, _sackPrimed;
	float _dongRest, _dongLength, _flatGround = float.MinValue;
	Vector3 _sackNow, _sackSpeed, _sackVelocity;

	/// <summary>The dong from root to tip, in the world (empty outside weapon mode).</summary>
	public IReadOnlyList<Vector3> DongPoints => WeaponMode && _weaponPrimed ? _wNow : Array.Empty<Vector3>();
	/// <summary>How fast each of <see cref="DongPoints"/> really moved this frame.</summary>
	public IReadOnlyList<Vector3> DongVelocities => WeaponMode && _weaponPrimed ? _wVelocity : Array.Empty<Vector3>();
	public Vector3 DongRoot => WeaponMode && _weaponPrimed ? _wNow[0] : WorldPosition;
	public Vector3 DongTip => WeaponMode && _weaponPrimed ? _wNow[^1] : WorldPosition;
	public Vector3 DongTipVelocity => WeaponMode && _weaponPrimed ? _wVelocity[^1] : Vector3.Zero;
	public Vector3 SackPoint => WeaponMode && _sackPrimed ? _sackNow : WorldPosition;
	public Vector3 SackVelocity => WeaponMode && _sackPrimed ? _sackVelocity : Vector3.Zero;

	/// <summary>Natural length of the dong in the world, in inches, and its length now.</summary>
	public float DongRestLength => _dongRest > 0.01f ? _dongRest : 6.9f * Scale;
	public float DongLength => _dongLength > 0.01f ? _dongLength : DongRestLength * DongScale;

	/// <summary>How thick the dong is at one of <see cref="DongPoints"/>, as a radius in inches.</summary>
	public float DongRadiusAt( int point ) => point >= 0 && point < _wRadius.Length ? _wRadius[point] : 1.3f * Scale * DongScale;
	public float SackRadius => 2.3f * Scale * MathF.Max( SackScale, 0.05f );

	/// <summary>The spine bends with the throw.</summary>
	void Throw()
	{
		var a = BodyThrow;
		if ( MathF.Abs( a.pitch ) + MathF.Abs( a.yaw ) + MathF.Abs( a.roll ) < 0.05f ) return;
		var by = Frame * Rotation.From( a.pitch * 0.5f, a.yaw * 0.5f, a.roll * 0.5f ) * Frame.Inverse;
		Turn( Bone( "spine_0" ), by );
		Turn( Bone( "spine_2" ), by );
	}

	/// <summary>What the weapon's ground rays ignore. Made once: a ray is cast for every point of the chain every frame.</summary>
	static readonly string[] WeaponPassesThrough = { "debris", "crowd" };

	/// <summary>Height of the ground under a point (very low if there is none within reach).</summary>
	float GroundUnder( Vector3 point, float lift )
	{
		bool has = _controller.IsValid();
		if ( has && _controller.FloorHeight is not null ) return _controller.FloorHeight( point );
		if ( WeaponGroundTrace )
		{
			var trace = Scene.Trace.Ray( point + Vector3.Up * lift, point - Vector3.Up * lift )
				.IgnoreGameObjectHierarchy( has ? _controller.GameObject : GameObject ).WithoutTags( WeaponPassesThrough ).Run();
			if ( !trace.Hit ) return float.MinValue;
			if ( !trace.StartedSolid ) return trace.HitPosition.z;
		}
		return _flatGround;
	}

	void FindFlatGround()
	{
		if ( !_controller.IsValid() ) { if ( _flatGround == float.MinValue ) _flatGround = WorldPosition.z; return; }
		if ( _flatGround == float.MinValue || (_controller.Attached && _controller.Up.z > 0.7f) ) _flatGround = _controller.WorldPosition.z;
	}

	/// <summary>
	/// The dong as a weapon: a free chain of weights from the hips, a few to each bone. Nothing
	/// holds it to the skeleton's pose: it hangs, drags and bounces on the ground, and is thrown
	/// by pulling it toward lying along <see cref="DongDrive"/>, the root hardest and the tip least,
	/// so the tip lags behind the throw and then whips through and past it. The bones are then
	/// stretched along the result, thin at the root and fat at the end.
	/// </summary>
	void SimulateDong( Chain chain, float dt )
	{
		int bones = chain.Bones.Length;
		int count = bones * WeaponSub + 1;
		if ( _wNow.Length != count )
		{
			_wNow = new Vector3[count]; _wStart = new Vector3[count]; _wSpeed = new Vector3[count]; _wVelocity = new Vector3[count];
			_wGround = new float[count]; _wSegment = new float[count]; _wRadius = new float[count];
			_weaponPrimed = false;
		}

		// The skeleton's own idea of the chain: where it starts, which way each bone lies, how long.
		Span<Vector3> restDirection = stackalloc Vector3[bones];
		Span<float> restLength = stackalloc float[bones];
		Span<float> boneScale = stackalloc float[bones];
		var root = _world[chain.Bones[0]].Position;
		float rest = 0f, shares = 0f;
		for ( int i = 0; i < bones; i++ )
		{
			var head = _world[chain.Bones[i]].Position;
			Vector3 span;
			if ( i + 1 < bones ) span = _world[chain.Bones[i + 1]].Position - head;
			else if ( i > 0 ) span = head - _world[chain.Bones[i - 1]].Position;
			else span = -Frame.Up * (3f * Scale);
			restLength[i] = MathF.Max( span.Length, 0.01f );
			restDirection[i] = span.Length > 0.001f ? span.Normal : -Frame.Up;
			rest += restLength[i];

			// A bone can only be scaled evenly, so longer is also fatter. Sharing the length out
			// unevenly makes it a club: a thin handle at the hips and the bulk at the far end.
			boneScale[i] = 1f + (WeaponTaper - 1f) * (bones > 1 ? (float)i / (bones - 1) : 0f);
			shares += restLength[i] * boneScale[i];
		}
		_dongRest = rest;

		float grow = MathF.Max( DongScale, 0.05f ) * rest / MathF.Max( shares, 0.01f );
		for ( int i = 0; i < bones; i++ ) boneScale[i] *= grow;

		float length = 0f;
		_wRadius[0] = 1.3f * Scale * boneScale[0];
		for ( int k = 1; k < count; k++ )
		{
			int bone = (k - 1) / WeaponSub;
			_wSegment[k] = restLength[bone] * boneScale[bone] / WeaponSub;
			_wRadius[k] = 1.3f * Scale * boneScale[bone];
			length += _wSegment[k];
		}
		_dongLength = length;

		FindFlatGround();
		if ( !_weaponPrimed || (_wNow[0] - root).Length > 300f + length )
		{
			_wNow[0] = root;
			for ( int k = 1; k < count; k++ ) _wNow[k] = _wNow[k - 1] + restDirection[(k - 1) / WeaponSub] * _wSegment[k];
			for ( int k = 0; k < count; k++ ) { _wSpeed[k] = Vector3.Zero; _wVelocity[k] = Vector3.Zero; }
			_weaponPrimed = true;
		}

		// The ground under each point, found once a frame.
		for ( int k = 0; k < count; k++ )
		{
			_wStart[k] = _wNow[k];
			if ( k > 0 ) _wGround[k] = GroundUnder( _wNow[k], MathF.Max( 24f, _wRadius[k] * 2f ) + _wVelocity[k].Length * dt );
		}

		bool driven = DongDriveStrength > 0.01f && DongDrive.Length > 0.01f;
		var drive = driven ? DongDrive.Normal : Vector3.Zero;
		float driveDamping = 2f * WeaponDriveDamping * MathF.Sqrt( MathF.Max( DongDriveStrength, 0f ) );
		var rootFrom = _wNow[0];
		var rootVelocity = (root - rootFrom) / dt;
		float landedSpeed = 0f;
		var landedAt = Vector3.Zero;

		// Small steps, so a hard throw stays stable at any frame rate (more of them the longer the frame).
		int steps = Math.Clamp( (int)MathF.Ceiling( dt * MathF.Max( WeaponStepsPerSecond, 60f ) ), 1, 12 );
		float h = dt / steps;
		var gravity = Vector3.Down * (WeaponGravity * MathF.Max( WeaponGravityScale, 0f ));
		int snag = _snagPoint > 0 && _snagPoint < count ? _snagPoint : 0;
		for ( int step = 0; step < steps; step++ )
		{
			_wNow[0] = Vector3.Lerp( rootFrom, root, (step + 1f) / steps );
			float arc = 0f;
			for ( int k = 1; k < count; k++ )
			{
				arc += _wSegment[k];
				float along = (float)k / (count - 1);
				var now = _wNow[k];
				var velocity = _wSpeed[k];

				// Caught on something: this point stays where it is held, and the rest hangs and wraps from it.
				if ( k == snag )
				{
					_wSpeed[k] = Vector3.Zero;
					_wNow[k] = _snagAt;
					continue;
				}

				var pull = gravity - velocity * WeaponDamping;
				if ( driven )
				{
					float share = 1f + (WeaponTipLag - 1f) * along;
					// A load on the end is slower to answer the throw.
					if ( DongTipLoad > 0f ) share /= 1f + DongTipLoad * along * along;
					pull += ((_wNow[0] + drive * arc - now) * DongDriveStrength - (velocity - rootVelocity) * driveDamping) * share;
				}
				if ( k >= 2 && WeaponStiffness > 0f )
				{
					// Resists folding: pulled toward carrying straight on from the two points above.
					var line = _wNow[k - 1] - _wNow[k - 2];
					if ( line.Length > 0.001f ) pull += (_wNow[k - 1] + line.Normal * _wSegment[k] - now) * WeaponStiffness;
				}

				velocity += pull * h;
				var next = now + velocity * h;

				// Held at its length from the point above, and out of the hips and legs.
				var span = next - _wNow[k - 1];
				next = _wNow[k - 1] + (span.Length > 0.001f ? span.Normal : Vector3.Down) * _wSegment[k];
				next = KeepOut( next );
				velocity = (next - now) / h;

				// The ground: it lands with a slap, bounces a little and drags.
				float floor = _wGround[k] + _wRadius[k] * 0.8f;
				if ( next.z < floor )
				{
					float falling = -velocity.z;
					next = next.WithZ( floor );
					float drag = MathF.Max( 1f - WeaponGroundDrag * h, 0f );
					velocity = new Vector3( velocity.x * drag, velocity.y * drag, falling > 70f ? falling * WeaponBounce : 0f );
					if ( falling > landedSpeed ) { landedSpeed = falling; landedAt = next.WithZ( _wGround[k] ); }
				}

				_wSpeed[k] = velocity.ClampLength( 30000f );
				_wNow[k] = next;
			}
		}

		for ( int k = 0; k < count; k++ ) _wVelocity[k] = (_wNow[k] - _wStart[k]) / dt;
		if ( landedSpeed > 0f ) DongLanded?.Invoke( landedAt, landedSpeed );

		// How hard a caught chain is being pulled: the straight run from the hips to the catch, against the chain there is to cover it.
		if ( snag > 0 )
		{
			float slack = 0f;
			for ( int k = 1; k <= snag; k++ ) slack += _wSegment[k];
			DongSnagStretch = (_wNow[snag] - _wNow[0]).Length / MathF.Max( slack, 0.01f );
		}
		else DongSnagStretch = 1f;

		// Lay each bone from its first point to its last, scaled to fit.
		for ( int i = 0; i < bones; i++ )
		{
			int bone = chain.Bones[i];
			var from = _wNow[i * WeaponSub];
			var chord = _wNow[(i + 1) * WeaponSub] - from;
			var rotation = _world[bone].Rotation;
			if ( chord.Length > 0.001f ) rotation = Rotation.FromToRotation( restDirection[i], chord.Normal ) * rotation;
			float fit = Math.Clamp( chord.Length / (restLength[i] * boneScale[i]), 0.6f, 1.3f );
			_world[bone] = new Transform( from, rotation, _world[bone].Scale * (boneScale[i] * fit) );
		}
	}

	/// <summary>
	/// The sack as a weapon: one weight on a short line from the hips, let out by <see cref="SackChain"/>,
	/// thrown the same way as the dong and bouncing off the ground.
	/// </summary>
	void SimulateSack( Chain chain, float dt )
	{
		int bone = chain.Bones[0];
		var anchor = _world[bone].Position;
		var restDirection = -Frame.Up;
		float size = MathF.Max( SackScale, 0.05f );
		float body = 3f * Scale * size;
		float length = body + MathF.Max( SackChain, 0f );
		float radius = SackRadius;

		FindFlatGround();
		if ( !_sackPrimed || (_sackNow - anchor).Length > 300f + length )
		{
			_sackNow = anchor + restDirection * length;
			_sackSpeed = Vector3.Zero;
			_sackVelocity = Vector3.Zero;
			_sackPrimed = true;
		}

		var start = _sackNow;
		float ground = GroundUnder( _sackNow, MathF.Max( 24f, radius * 2f ) + _sackVelocity.Length * dt );
		bool driven = SackDriveStrength > 0.01f && SackDrive.Length > 0.01f;
		var drive = driven ? SackDrive.Normal : Vector3.Zero;
		float driveDamping = 2f * WeaponDriveDamping * MathF.Sqrt( MathF.Max( SackDriveStrength, 0f ) );
		float landedSpeed = 0f;

		int steps = Math.Clamp( (int)MathF.Ceiling( dt * MathF.Max( WeaponStepsPerSecond, 60f ) ), 1, 12 );
		float h = dt / steps;
		for ( int step = 0; step < steps; step++ )
		{
			var velocity = _sackSpeed;
			var pull = Vector3.Down * (WeaponGravity * MathF.Max( WeaponGravityScale, 0f )) - velocity * WeaponDamping;
			if ( driven ) pull += (anchor + drive * length - _sackNow) * SackDriveStrength - velocity * driveDamping;
			velocity += pull * h;
			var next = _sackNow + velocity * h;

			var span = next - anchor;
			next = anchor + (span.Length > 0.001f ? span.Normal : Vector3.Down) * length;
			next = KeepOut( next );
			velocity = (next - _sackNow) / h;

			float floor = ground + radius * 0.8f;
			if ( next.z < floor )
			{
				float falling = -velocity.z;
				next = next.WithZ( floor );
				float drag = MathF.Max( 1f - WeaponGroundDrag * h, 0f );
				// It is the bouncy one.
				velocity = new Vector3( velocity.x * drag, velocity.y * drag, falling > 70f ? falling * MathF.Min( WeaponBounce * 1.6f, 0.9f ) : 0f );
				landedSpeed = MathF.Max( landedSpeed, falling );
			}

			_sackSpeed = velocity.ClampLength( 30000f );
			_sackNow = next;
		}

		_sackVelocity = (_sackNow - start) / dt;
		if ( landedSpeed > 0f ) SackLanded?.Invoke( _sackNow.WithZ( ground ), landedSpeed );

		// The bone hangs from the end of its line and points along it; the skin still tied to the
		// hips stretches into the line.
		var along = _sackNow - anchor;
		var direction = along.Length > 0.001f ? along.Normal : restDirection;
		var rotation = Rotation.FromToRotation( restDirection, direction ) * _world[bone].Rotation;
		_world[bone] = new Transform( anchor + direction * MathF.Max( along.Length - body, 0f ), rotation, _world[bone].Scale * size );
	}

	/// <summary>While reaching for a grip, the right hand really goes to it.</summary>
	void Hands( float dt )
	{
		bool reaching = _controller.IsValid() && (_controller.IsReaching || _controller.IsLatching) && _controller.ReachAmount > 0.01f;
		_reachBlend += ((reaching ? _controller.ReachAmount : 0f) - _reachBlend) * MathF.Min( dt * 18f, 1f );
		if ( _reachBlend < 0.02f ) return;

		int hand = Bone( "hand_r" );
		if ( hand < 0 ) return;
		var target = Vector3.Lerp( _world[hand].Position, _controller.GripPoint, Math.Clamp( _reachBlend, 0f, 1f ) );
		SolveLimb( Bone( "arm_upper_r" ), Bone( "arm_lower_r" ), hand, target );
	}

	/// <summary>
	/// Each foot is put on whatever is really under it: found with a trace along the body's up
	/// axis, then the leg is solved to reach it and the foot laid along the surface.
	/// </summary>
	void Feet( float dt )
	{
		// Off the ground, mid-latch or mid-hop the feet go with the body: the correction is let
		// go of at once (the clip changes there anyway), and planting starts afresh on landing.
		bool grounded = _controller.IsValid() && _controller.Attached && !_controller.IsLatching
			&& !(WeaponMode && BodyOffset.Length > 0.5f);
		if ( !grounded )
		{
			_planted[0] = _planted[1] = false;
			_footShift[0] = _footShift[1] = Vector3.Zero;
			_footLast[0] = _footLast[1] = Vector3.Zero;
			return;
		}

		var up = Frame.Up;
		float probe = FootProbe * Scale;
		float ease = 1f - MathF.Exp( -dt * 20f );

		for ( int side = 0; side < 2; side++ )
		{
			string suffix = side == 0 ? "_l" : "_r";
			int upper = Bone( "leg_upper" + suffix ), lower = Bone( "leg_lower" + suffix ), foot = Bone( "foot" + suffix ), toe = Bone( "toe" + suffix );
			if ( upper < 0 || lower < 0 || foot < 0 || toe < 0 ) continue;

			// The animation's idea of how high this foot is off the body's ground plane.
			var toePosition = _world[toe].Position;
			float lifted = Vector3.Dot( toePosition - WorldPosition, up );

			var trace = Scene.Trace.Ray( toePosition + up * probe, toePosition - up * probe )
				.IgnoreGameObjectHierarchy( _controller.GameObject ).WithoutTags( "debris", "crowd" ).Run();

			// How far the ankle should be moved from where the clip has it. Nothing underfoot, or
			// ground too far away to be this foot's: no correction (eased out, never dropped).
			var shift = Vector3.Zero;
			bool found = trace.Hit && !trace.StartedSolid;
			if ( found )
			{
				// Keep the clip's own lift (a foot in mid-stride stays in the air) on top of the real ground.
				var wanted = trace.HitPosition + up * MathF.Max( lifted, 0f );

				// Planting: a foot that is down stays where it came down while the body moves over
				// it, instead of sliding with the clip. It lets go when the clip lifts it, or when
				// holding it would pull the leg too far; the ease below turns the release into a
				// quick step, not a snap.
				bool down = lifted < PlantHeight * Scale && _moving;
				if ( down )
				{
					if ( !_planted[side] || (_plantAt[side] - wanted).Length > PlantStretch * Scale )
					{
						_planted[side] = true;
						_plantAt[side] = wanted;
					}
					wanted = Vector3.Lerp( wanted, _plantAt[side], Math.Clamp( PlantStrength, 0f, 1f ) );
				}
				else _planted[side] = false;

				shift = wanted - toePosition;
				if ( shift.Length > probe + PlantStretch * Scale ) { shift = Vector3.Zero; found = false; _planted[side] = false; }
			}
			else _planted[side] = false;

			// A planted foot follows its spot exactly. But when the correction jumps (the ground
			// appears or vanishes under it, a plant lets go, a new one begins) the jump is taken
			// up and bled away over a few frames, so the foot steps across instead of popping.
			var jump = shift - _footLast[side];
			float allowed = 1.5f * Scale + (_controller.Velocity.Length + 60f) * dt * 1.5f;
			if ( jump.Length > allowed ) _footShift[side] -= jump;
			_footLast[side] = shift;
			_footShift[side] -= _footShift[side] * ease;
			_footShift[side] = _footShift[side].ClampLength( probe + PlantStretch * Scale );
			var applied = shift + _footShift[side];
			if ( applied.LengthSquared < 0.0004f ) continue;

			// The leg can only be so long and fold so far: the ankle is kept where the two bones
			// can reach it with the knee still bent a little, so it is never stretched straight
			// (the pop) or folded flat.
			var hip = _world[upper].Position;
			var ankle = _world[foot].Position + applied;
			float leg = (_world[lower].Position - hip).Length + (_world[foot].Position - _world[lower].Position).Length;
			var reach = ankle - hip;
			float distance = reach.Length;
			if ( leg > 0.02f && distance > 0.001f )
			{
				float held = Math.Clamp( distance, leg * 0.35f, leg * 0.985f );
				if ( held != distance ) ankle = hip + reach / distance * held;
			}

			SolveLimb( upper, lower, foot, ankle );

			// Planted feet lie along the surface.
			if ( found && lifted < 2f * Scale )
				Turn( foot, Rotation.FromToRotation( up, trace.Normal ) );
		}
	}

	/// <summary>Two-bone IK: turns the root and the middle joint so the end reaches the target, keeping the bend's plane.</summary>
	void SolveLimb( int root, int mid, int end, Vector3 target )
	{
		if ( root < 0 || mid < 0 || end < 0 ) return;
		var a = _world[root].Position;
		var b = _world[mid].Position;
		var c = _world[end].Position;

		float upper = (b - a).Length, lower = (c - b).Length;
		if ( upper < 0.01f || lower < 0.01f ) return;
		float reach = Math.Clamp( (target - a).Length, 0.01f, upper + lower - 0.01f );

		static float Angle( Vector3 x, Vector3 y ) => MathF.Acos( Math.Clamp( Vector3.Dot( x.Normal, y.Normal ), -1f, 1f ) );
		const float Degrees = 180f / MathF.PI;

		float rootNow = Angle( c - a, b - a );
		float midNow = Angle( a - b, c - b );
		float rootWant = MathF.Acos( Math.Clamp( (lower * lower - upper * upper - reach * reach) / (-2f * upper * reach), -1f, 1f ) );
		float midWant = MathF.Acos( Math.Clamp( (reach * reach - upper * upper - lower * lower) / (-2f * upper * lower), -1f, 1f ) );

		// The plane the limb bends in; if it is dead straight, bend it forward.
		var axis = Vector3.Cross( c - a, b - a );
		if ( axis.Length < 0.001f ) axis = Vector3.Cross( c - a, Frame.Forward );
		if ( axis.Length < 0.001f ) return;
		axis = axis.Normal;

		Turn( root, Rotation.FromAxis( axis, (rootWant - rootNow) * Degrees ) );
		Turn( mid, Rotation.FromAxis( axis, (midWant - midNow) * Degrees ) );

		// Then swing the whole limb so the end lies on the line to the target.
		var endNow = _world[end].Position - a;
		var toTarget = target - a;
		if ( endNow.Length > 0.01f && toTarget.Length > 0.01f )
			Turn( root, Rotation.FromToRotation( endNow.Normal, toTarget.Normal ) );
	}
}