Sump/Grafts/GraftSocket.cs

Static helper that resolves where a graft attaches to the player lizard, returning a world position and rotation for a named bone plus offset. Uses a SkinnedModelRenderer's bone transforms when the rigged model has that bone, caching bind-pose rotations per Model, and falls back to a hardcoded table of points on the old primitive body.

using System;
using System.Collections.Generic;

/// <summary>
/// Where on the lizard a graft sits. A socket is a bone name plus an offset in the lizard's own
/// frame (+X ahead, +Y left, +Z up, inches). On the rigged model the socket follows that bone:
/// any <see cref="SkinnedModelRenderer"/> under the player whose model has a bone of that name.
/// On the old body made of primitives (no such renderer, or no such bone) it falls back to a
/// fixed point on the body object, from the table below. Grafts only ever ask
/// <see cref="Resolve"/>, so they cannot tell which body they are on.
/// </summary>
public static class GraftSocket
{
	/// <summary>
	/// On the rigged model, turn the graft with its bone (a tail graft swings with the tail). Off,
	/// it takes only the bone's position and keeps the lizard's own facing. Switch it off if grafts
	/// sit at odd angles on the rig: the turning relies on the model's bind pose being read right.
	/// </summary>
	public static bool FollowBoneRotation { get; set; } = true;

	/// <summary>Seconds between looks for a rigged model under the player (it can turn up late, or be swapped).</summary>
	const float SearchEvery = 1f;

	// The old placeholder body, in its own frame with the feet at the origin: about 56 inches
	// tall at the head, hips at (-2,0,25), head at (22,0,51), tail root at (-7,0,25).
	static readonly Dictionary<string, Vector3> FallbackPoints = BuildFallback();

	static Dictionary<string, Vector3> BuildFallback()
	{
		var t = new Dictionary<string, Vector3>
		{
			["pelvis"] = new( -2f, 0f, 25f ),
			["spine_0"] = new( 2f, 0f, 29f ),
			["spine_1"] = new( 7f, 0f, 34f ),
			["spine_2"] = new( 12f, 0f, 40f ),
			["neck_0"] = new( 16f, 0f, 45f ),
			["neck_1"] = new( 19f, 0f, 48f ),
			["head"] = new( 22f, 0f, 51f ),
			["jaw"] = new( 25f, 0f, 47f ),
		};

		// The tail runs back and down from its root to just above the floor.
		for ( int i = 0; i < 8; i++ )
			t["tail_" + i] = new Vector3( -7f - i * 6f, 0f, MathF.Max( 25f - i * 3f, 4f ) );

		// Limbs, left side; the right side is the mirror image.
		var left = new (string Name, Vector3 At)[]
		{
			("clavicle", new( 12f, 5f, 40f )),
			("arm_upper", new( 13f, 8f, 38f )),
			("arm_lower", new( 15f, 10f, 30f )),
			("hand", new( 17f, 10f, 22f )),
			("leg_upper", new( -2f, 6f, 24f )),
			("leg_lower", new( -1f, 8f, 14f )),
			("foot", new( 0f, 8f, 2f )),
		};
		foreach ( var (name, at) in left )
		{
			t[name + "_l"] = at;
			t[name + "_r"] = new Vector3( at.x, -at.y, at.z );
		}
		return t;
	}

	/// <summary>The fixed point used for a bone on the old body (the hips, for a name nobody knows).</summary>
	public static Vector3 FallbackPoint( string bone ) =>
		bone is not null && FallbackPoints.TryGetValue( bone, out var at ) ? at : FallbackPoints["pelvis"];

	// What was found under the player at the last look.
	static ReptileController _player;
	static readonly List<SkinnedModelRenderer> _renderers = new();
	static float _nextSearch;

	// Per model: each bone's rotation in the model's own space in the bind pose (null = no such bone).
	static readonly Dictionary<Model, Dictionary<string, Rotation?>> _binds = new();

	/// <summary>
	/// The world position and rotation of a socket right now. The rotation is the lizard's own
	/// frame as carried by that bone, so parts are always built facing +X with +Z up. Size scales
	/// the offset (the lizard shrunk to a toy). True when a real bone was followed, false on the fallback.
	/// </summary>
	public static bool Resolve( ReptileController player, string bone, Vector3 offset, float size, out Vector3 position, out Rotation rotation )
	{
		position = Vector3.Zero;
		rotation = Rotation.Identity;
		if ( !player.IsValid() ) return false;

		try
		{
			if ( TryBone( player, bone, out var at, out var carried ) )
			{
				position = at + carried * (offset * size);
				rotation = carried;
				return true;
			}
		}
		catch ( Exception e )
		{
			// Whatever went wrong with the rig, the fallback always works.
			Log.Warning( $"GraftSocket: bone '{bone}' could not be followed: {e.Message}" );
			_renderers.Clear();
			_nextSearch = RealTime.Now + 5f;
		}

		var basis = player.Body.IsValid() ? player.Body : player.GameObject;
		rotation = basis.WorldRotation;
		position = basis.WorldPosition + rotation * ((FallbackPoint( bone ) + offset) * size);
		return false;
	}

	static bool TryBone( ReptileController player, string bone, out Vector3 position, out Rotation carried )
	{
		position = Vector3.Zero;
		carried = Rotation.Identity;
		if ( string.IsNullOrEmpty( bone ) ) return false;

		if ( _player != player || RealTime.Now >= _nextSearch )
		{
			_player = player;
			_nextSearch = RealTime.Now + SearchEvery;
			_renderers.Clear();
			foreach ( var found in player.Components.GetAll<SkinnedModelRenderer>( FindMode.EverythingInSelfAndDescendants ) )
				_renderers.Add( found );
		}

		foreach ( var renderer in _renderers )
		{
			if ( !renderer.IsValid() || !renderer.Active || renderer.Model is null ) continue;
			var bind = BindRotation( renderer.Model, bone );
			if ( bind is null ) continue;
			if ( !renderer.TryGetBoneTransform( bone, out var world ) ) continue;

			position = world.Position;
			carried = FollowBoneRotation ? world.Rotation * bind.Value.Inverse : renderer.WorldRotation;
			return true;
		}
		return false;
	}

	/// <summary>A bone's bind-pose rotation in model space, worked out once per model by walking up its parents.</summary>
	static Rotation? BindRotation( Model model, string bone )
	{
		if ( !_binds.TryGetValue( model, out var _bind ) )
		{
			if ( _binds.Count > 8 ) _binds.Clear();
			_binds[model] = _bind = new Dictionary<string, Rotation?>();
		}
		if ( _bind.TryGetValue( bone, out var known ) ) return known;

		Rotation? result = null;
		var bones = model.Bones;
		if ( bones is not null && bones.HasBone( bone ) )
		{
			var rotation = Rotation.Identity;
			var at = bones.GetBone( bone );
			for ( int i = 0; at is not null && i < 64; i++ )
			{
				rotation = at.LocalTransform.Rotation * rotation;
				at = at.Parent;
			}
			result = rotation;
		}
		_bind[bone] = result;
		return result;
	}
}