Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

11.7 KB
Raw Blame
#nullable enable
using System;
using System.Collections.Generic;
using Statecraft.Game.Map.Collection;
using Statecraft.Game.Map.Kits;
using UnityEngine;
using UnityEngine.Rendering;

namespace Statecraft.Game.Map.Units
{
    /// <summary>The close-zoom detail of the tokens' Collection figures (issue #665, #663's rule: "full detail and the idle
    /// clip only at close zoom"). Each camera picks with the town models' switch and its hysteresis (TownModelLayer.CloseAt:
    /// close below CloseEnterM, far again beyond CloseExitM). Up close, each figure whose model has an idle clip
    /// (CollectionCatalog.Animated) shows its skinned near model, playing the clip, under the same holder as its far model, so
    /// the camera's yaw (#644) and the far model's height and feet carry over; far off, the far mesh draws and the clip stops.
    /// The near prefabs are asked for only once a camera first comes close, through the same stream, after the first frame.
    /// It fails open: until a near prefab arrives, and for good when it is missing or damaged, the far model stays. C05, the
    /// pioneer veteran, has no idle clip (walk and run only), so he keeps his still far model close up (owner, 18 October
    /// 2026, #665: "Keep its still model"); the switch turns his code-driven idle (UnitFigureIdle, #2374) on and off with the
    /// zoom instead, and asks for no near model. One per unit layer or showcase; nothing is allocated while the zoom band holds.</summary>
    [ExecuteAlways]
    public sealed class UnitFigureDetail : MonoBehaviour
    {
        /// <summary>The name of the near model's object, beside the far model under the figure's holder.</summary>
        public const string NearName = "Near";

        sealed class Figure
        {
            public Transform Holder = null!, Far = null!;
            public string Id = "";
            public Renderer[] FarRenderers = Array.Empty<Renderer>(), NearRenderers = Array.Empty<Renderer>();
            public Animator[] Animators = Array.Empty<Animator>();
            /// <summary>A figure that idles in code on its far model (C05): it has no near model to ask for.</summary>
            public UnitFigureIdle? Idle;
        }

        readonly List<Figure> figures = new List<Figure>();
        readonly HashSet<string> nearAsked = new HashSet<string>(StringComparer.Ordinal);
        /// <summary>Each camera's last choice (by instance id), for the hysteresis.</summary>
        readonly Dictionary<int, bool> closeFor = new Dictionary<int, bool>();
        static readonly Predicate<Figure> Gone = f => f.Holder == null;
        static bool logged;

        /// <summary>True when the last camera to render was close (the near models show where they have arrived).</summary>
        public bool LastClose { get; private set; }

        /// <summary>The switch of the unit layer or showcase that <paramref name="piece"/> stands in (the root that owns its
        /// runtime assets, so it goes with the layer), made on first use.</summary>
        internal static UnitFigureDetail Of(Transform piece) => Existing(piece) ?? RootOf(piece).AddComponent<UnitFigureDetail>();

        /// <summary>The switch <paramref name="piece"/> stands in, if one exists; never made. Teardown uses this: a token the
        /// unit layer has detached for destruction is its own root, and Unity refuses a component on an object being destroyed.
        /// A figure left registered in its layer's switch is pruned once its holder is destroyed (<see cref="Gone"/>).</summary>
        internal static UnitFigureDetail? Existing(Transform piece) =>
            RootOf(piece).TryGetComponent<UnitFigureDetail>(out var detail) ? detail : null;

        static GameObject RootOf(Transform piece)
        {
            var assets = piece.GetComponentInParent<MapRuntimeAssets>(true);
            return assets != null ? assets.gameObject : piece.root.gameObject;
        }

        /// <summary>A figure whose far model <paramref name="holder"/> now holds (its first child), with an idle clip, or with
        /// a code-driven idle on the far model itself (UnitFigureIdle).</summary>
        internal void Add(Transform holder, string id)
        {
            var far = holder.GetChild(0);
            var f = new Figure { Holder = holder, Far = far, Id = id, FarRenderers = far.GetComponentsInChildren<Renderer>(true), Idle = far.GetComponent<UnitFigureIdle>() };
            figures.Add(f);
            if (LastClose && f.Idle == null) { Ask(f); Attach(f); }
            Show(f);
        }

        void OnEnable() => RenderPipelineManager.beginCameraRendering += Choose;
        void OnDisable() => RenderPipelineManager.beginCameraRendering -= Choose;

        internal void Choose(ScriptableRenderContext context, Camera camera)
        {
            if (camera.cameraType == CameraType.Preview || camera.cameraType == CameraType.Reflection) return;
            int id = camera.GetInstanceID();
            bool close = TownModelLayer.CloseAt(TownModelLayer.ViewDistance(camera), closeFor.TryGetValue(id, out var was) ? was : (bool?)null);
            closeFor[id] = close;
            if (close == LastClose) return;
            LastClose = close;
            figures.RemoveAll(Gone);
            foreach (var f in figures) { if (close && f.Idle == null) { Ask(f); Attach(f); } Show(f); }
        }

        internal CollectionResidencyMetrics.Category ResidencySnapshot()
        {
            var ids = new HashSet<string>(StringComparer.Ordinal); int refs = 0;
            foreach (var f in figures)
            {
                if (f.Holder == null) continue; ids.Add(f.Id);
                refs += Array.FindAll(f.FarRenderers, r => r != null).Length + Array.FindAll(f.NearRenderers, r => r != null).Length;
                refs += Array.FindAll(f.Animators, a => a != null).Length;
            }
            return CollectionResidencyMetrics.Row("units", 0, 0, ids, 0, 0, 0, refs, 0, 0);
        }
        void Ask(Figure figure)
        {
            var owner = figure.Holder != null && figure.Holder.parent != null ? figure.Holder.parent.GetComponent<UnitFigureResidency>() : null;
            if (owner != null) { owner.RequestNear(); return; }
            if (nearAsked.Add(figure.Id)) UnitFigures.RequestNear(figure.Id, () => Arrived(figure.Id));
        }
        internal void OwnedArrived(string id) => Arrived(id);
        internal void Remove(Transform holder)
        {
            figures.RemoveAll(f => f.Holder == null || f.Holder == holder);
            nearAsked.RemoveWhere(id => !figures.Exists(f => f.Id == id));
        }

        /// <summary>Stops using and destroys only a holder's camera-gated near clone. The independently owned far model
        /// remains registered and visible while the near source lease completes its deferred retirement.</summary>
        internal static IReadOnlyList<UnityEngine.Object> RetireNear(Transform piece)
        {
            var holder = piece.Find(UnitFigures.ModelName);
            if (holder == null) return Array.Empty<UnityEngine.Object>();
            var figure = Existing(piece)?.figures.Find(f => f.Holder == holder);
            var near = holder.Find(NearName);
            if (figure != null)
            {
                foreach (var renderer in figure.FarRenderers) if (renderer != null) renderer.forceRenderingOff = false;
                foreach (var renderer in figure.NearRenderers) if (renderer != null) renderer.forceRenderingOff = true;
                foreach (var animator in figure.Animators) if (animator != null) animator.enabled = false;
                figure.NearRenderers = Array.Empty<Renderer>();
                figure.Animators = Array.Empty<Animator>();
            }
            if (near == null) return Array.Empty<UnityEngine.Object>();
            var original = near.gameObject;
            if (Application.isPlaying) { near.SetParent(null); Destroy(original); } else DestroyImmediate(original);
            UnitFigures.GeometryChanged();
            return new UnityEngine.Object[] { original };
        }

        void Arrived(string id)
        {
            if (this == null) return;   // the layer was rebuilt meanwhile
            figures.RemoveAll(Gone);
            foreach (var f in figures)
                if (f.Id == id) { Attach(f); Show(f); }
        }

        /// <summary>Puts the near model beside the far one, once it has arrived: as tall as the far model, centred over its
        /// feet, casting shadows as it does, with the probes off as on the far model.</summary>
        void Attach(Figure f)
        {
            if (f.NearRenderers.Length > 0 || f.Holder == null || f.Idle != null) return;
            var prefab = UnitFigures.Near(f.Id);
            if (prefab == null) return;
            var near = Instantiate(prefab, f.Holder, false).transform;   // the prefab's own root rotation (the FBX axis turn) kept
            near.name = NearName;
            OriginalModelPose.Sample(near.gameObject); // measure the same frame-zero pose before close idle starts
            if (UnitFigures.BoxIn(f.Holder, f.Far) is Bounds far && UnitFigures.BoxIn(f.Holder, near) is Bounds box && box.size.y > 1e-6f)
            {
                near.localScale *= far.size.y / box.size.y;
                if (UnitFigures.BoxIn(f.Holder, near) is Bounds fit)
                    near.localPosition += new Vector3(far.center.x - fit.center.x, far.min.y - fit.min.y, far.center.z - fit.center.z);
            }
            var like = f.FarRenderers.Length > 0 ? f.FarRenderers[0] : null;
            f.NearRenderers = near.GetComponentsInChildren<Renderer>(true);
            foreach (var r in f.NearRenderers)
            {
                if (like != null) { r.shadowCastingMode = like.shadowCastingMode; r.receiveShadows = like.receiveShadows; }
                r.lightProbeUsage = LightProbeUsage.Off; r.reflectionProbeUsage = ReflectionProbeUsage.Off;
            }
            f.Animators = near.GetComponentsInChildren<Animator>(true);
            if (f.Holder.parent != null)
            {
                UnitFigureWeapon.Refresh(f.Holder.parent);   // the near model holds the figure's weapon too (#2083)
                UnitFigurePointFire.Refresh(f.Holder.parent);   // and takes a held point-fire aim (#2084)
            }
            UnitFigures.GeometryChanged();
            if (!logged && Application.isPlaying) { logged = true; Debug.Log("UNITS figures: the skinned near figures streamed in (close zoom)"); }
        }

        /// <summary>Reads again the renderers of the figure <paramref name="holder"/> holds (a weapon joined its far or near
        /// model, UnitFigureWeapon), and shows it as the zoom asks.</summary>
        internal void Rescan(Transform holder)
        {
            var f = figures.Find(x => x.Holder == holder);
            if (f == null) return;
            if (f.Far != null) f.FarRenderers = f.Far.GetComponentsInChildren<Renderer>(true);
            var near = holder.Find(NearName);
            if (near != null && f.NearRenderers.Length > 0) f.NearRenderers = near.GetComponentsInChildren<Renderer>(true);
            Show(f);
        }

        void Show(Figure f)
        {
            bool near = LastClose && f.NearRenderers.Length > 0;
            foreach (var r in f.FarRenderers) if (r != null) r.forceRenderingOff = near;
            foreach (var r in f.NearRenderers) if (r != null) r.forceRenderingOff = !near;
            foreach (var a in f.Animators) if (a != null) a.enabled = near;
            if (f.Idle != null) f.Idle.enabled = LastClose;   // C05's code-driven idle runs close up, on his far model (#2374)
            // A figure that turns near mid-move or mid-attack takes up its token's walk or fire at once (#1866).
            var motion = near && f.Holder != null ? f.Holder.GetComponentInParent<UnitTokenMotion>() : null;
            if (motion != null && (motion.Moving || motion.Attacking)) motion.RefreshPose();
        }
    }
}