Rampage/Humans/RampagePopulace.Build.cs

Population builder for the Rampage game, part of the RampagePopulace partial class. Scatters townsfolk and named district locals along the street map, groups them into cells, bakes each cell's crowd into one merged mesh per palette colour, and sets up the fat guy cameo. Also owns the runtime side of the cell system: waking a cell into pooled stand-in GameObjects with hats and props, sending them home, trimming distant hats and props, and computing baked colours from roles.

using System;
using System.Collections.Generic;
using System.Linq;

// Making the town's people: who stands where, the baked far crowd, the blocks that wake and
// sleep, and the pool of stand-ins.
public sealed partial class RampagePopulace
{
	enum Level : byte
	{
		/// <summary>A spare slot: nobody.</summary>
		Free,
		/// <summary>At home in a sleeping block: part of its baked mesh.</summary>
		Asleep,
		/// <summary>A cheap moving stand-in.</summary>
		StandIn,
		/// <summary>A real physics body.</summary>
		Real,
		/// <summary>A stand-in thrown through the air the cheap way, or lying dazed where it landed.</summary>
		Tossed,
	}

	struct Agent
	{
		public Vector3 Position;        // the feet
		public Vector3 Velocity, Home;
		public Vector3 Lane;            // the pull back toward the street, worked out now and then
		public Vector3 Cover;           // where it hides, if it has found somewhere
		public Vector2 Slot;            // its place in a formation: forward and left of the middle
		public float Yaw, Phase, Pace, Panic;
		public float HitAt;             // when it was last hit
		public float Timer;             // tossed: when it must be down by; dazed: when it gets up
		public int Cell;                // its home block, or below zero for somebody sent by the authorities
		public int AwakeSlot;           // where it is in the awake list
		public int Squad;               // its formation, or below zero
		public byte Role, Colour, Chain, Bounces, Hits;
		public Level Level;
		public bool Brave;              // goes for the lizard
		public bool Cowed;              // has been hit, and has lost all interest in heroics
		public bool Shielded;           // still has its riot shield
		public bool Stray;              // awake with no awake block to belong to
		public bool Dazed, Stranded, HasCover, Crouched;
		public StandIn StandIn;
		public RealBody Body;
		public PersonTarget Target;
	}

	/// <summary>The cheap moving version of a person: a block, a head, a hat and a prop.</summary>
	sealed class StandIn
	{
		public GameObject Go, Hat, Prop, Stars;
		public ModelRenderer Body, Head, HatRenderer, PropRenderer;
		/// <summary>Far enough off that its hat and prop are not drawn.</summary>
		public bool Trimmed;
	}

	sealed class Cell
	{
		public int Index;
		public Vector3 Centre;
		public float Radius;
		public List<int> Agents = new();
		public List<GameObject> Chunks = new();
		public bool Awake;
		public LumpTarget Lump;
	}

	sealed class MeshBuffer
	{
		public List<Vertex> Vertices = new();
		public List<int> Indices = new();
		public Vector3 Mins = new( float.MaxValue ), Maxs = new( float.MinValue );
	}

	// What the far crowd is baked in: the town's shirts, then the uniforms.
	static readonly Color[] Palette =
	{
		new( 0.85f, 0.22f, 0.2f ), new( 0.95f, 0.75f, 0.15f ), new( 0.2f, 0.6f, 0.85f ), new( 0.3f, 0.75f, 0.35f ), new( 0.55f, 0.35f, 0.8f ),
		new( 0.92f, 0.92f, 0.9f ), new( 0.08f, 0.08f, 0.12f ), new( 0.32f, 0.38f, 0.22f ), new( 0.45f, 0.45f, 0.48f ),
	};
	const int TownShirts = 5;
	static readonly Color[] Skins = { new( 0.93f, 0.76f, 0.62f ), new( 0.72f, 0.5f, 0.36f ), new( 0.45f, 0.3f, 0.22f ) };

	Agent[] _agents = Array.Empty<Agent>();
	readonly Stack<int> _free = new();
	readonly List<Cell> _cells = new();
	readonly List<int> _awake = new();
	readonly Stack<StandIn> _pool = new();

	// Generated meshes and models have to be held on to, or they are collected.
	readonly List<Mesh> _meshes = new();
	readonly List<Model> _models = new();
	Model _bodyModel, _headModel;
	Material _material;

	/// <summary>
	/// Everything that makes the town's people, as a list of small steps (each "yield" ends one).
	/// The frame takes as many as fit in <see cref="BuildBudgetMs"/>.
	/// </summary>
	IEnumerator<bool> BuildSteps()
	{
		_root = new GameObject( GameObject, true, "Populace" );
		_root.Flags |= GameObjectFlags.NotSaved;
		_root.WorldTransform = new Transform( Vector3.Zero );   // the baked crowd is in world space
		_material = Model.Load( "models/dev/box.vmdl" ).Materials.FirstOrDefault();

		// The one-person models the stand-ins share.
		var body = new MeshBuffer();
		AddBody( body, Vector3.Zero, 0f, 1f );
		_bodyModel = MakeModel( body );
		var head = new MeshBuffer();
		AddHead( head, Vector3.Zero, 0f, 1f );
		_headModel = MakeModel( head );
		yield return true;

		PopulaceMap.BuildStreetGrid();
		var streets = PopulaceMap.Streets();

		float side = PopulaceMap.HalfSize * 2f / 1000f;
		int wanted = Math.Clamp( (int)(Density * side * side), MinPopulation, MaxPopulation );
		int cast = 0;
		foreach ( var district in HumanRoles.Districts ) cast += district.Count;

		_agents = new Agent[wanted + cast + MaxResponders + 40];
		_gridNext = new int[_agents.Length];
		int made = 0;

		// Ordinary townsfolk, scattered along the streets.
		var player = Rampage.Player;
		var keepClear = player.IsValid() ? player.WorldPosition : PopulaceMap.Centre;
		for ( int n = 0; n < wanted && streets.Count > 0; n++ )
		{
			if ( !StreetSpot( streets, out var at ) ) continue;
			if ( FlatDistance( at, keepClear ) < 260f ) continue;      // nobody standing on the lizard as it arrives

			var role = HumanRoles.Townsperson();
			AddAgent( made++, role, at, Game.Random.Float( 0f, MathF.PI * 2f ) );
			if ( (n & 255) == 255 ) yield return true;
		}
		yield return true;

		// The people from the misfits' pasts, round their landmarks.
		for ( int d = 0; d < HumanRoles.Districts.Length; d++ )
		{
			var district = HumanRoles.Districts[d];
			if ( !PopulaceMap.FindLandmark( district.Words, d, out var landmark ) ) continue;

			// On the street outside it, if there is one near: the landmark itself may be a building.
			var middle = landmark;
			if ( PopulaceMap.NearestStreet( landmark, out var street ) < 900f ) middle = street;

			for ( int n = 0; n < district.Count; n++ )
			{
				var at = middle;
				for ( int tries = 0; tries < 6; tries++ )
				{
					float angle = Game.Random.Float( 0f, MathF.PI * 2f );
					float reach = district.Radius * MathF.Sqrt( Game.Random.Float( 0.03f, 1f ) );
					at = PopulaceMap.Contain( middle + new Vector3( MathF.Cos( angle ), MathF.Sin( angle ), 0f ) * reach );
					if ( PopulaceMap.CanWalk( at ) ) break;
				}
				var toLandmark = landmark - at;
				float yaw = MathF.Atan2( -toLandmark.y, -toLandmark.x ) + Game.Random.Float( -0.6f, 0.6f );     // backs to their place, looking out
				AddAgent( made++, district.Locals[n % district.Locals.Length], at, yaw );
			}
		}

		Townsfolk = made;
		for ( int i = _agents.Length - 1; i >= made; i-- ) _free.Push( i );

		SortIntoCells( made );
		yield return true;

		// The far crowd, a block at a time.
		foreach ( var cell in _cells )
		{
			BakeCell( cell );
			yield return true;
		}

		if ( SpawnFatGuy ) PlaceFatGuy( streets, keepClear );
		yield return true;

		// Stand-ins for the first blocks to wake, made now and put away.
		int spare = Math.Min( PrewarmStandIns, MaxAwake );
		for ( int n = 0; n < spare; n++ )
		{
			var s = NewStandIn();
			s.Go.Enabled = false;
			_pool.Push( s );
			if ( (n & 3) == 3 ) yield return true;
		}
	}

	/// <summary>Somewhere on a street: a street point, or part way to another one near it, and a little to one side.</summary>
	bool StreetSpot( IReadOnlyList<Vector3> streets, out Vector3 at )
	{
		for ( int tries = 0; tries < 3; tries++ )
		{
			var a = streets[Game.Random.Next( streets.Count )];

			// Streets given only as a few points still get people between them.
			var b = a;
			float nearest = 2000f * 2000f;
			for ( int k = 0; k < 5; k++ )
			{
				var other = streets[Game.Random.Next( streets.Count )];
				float d = (other - a).WithZ( 0f ).LengthSquared;
				if ( d > 1f && d < nearest ) { nearest = d; b = other; }
			}

			at = Vector3.Lerp( a, b, Game.Random.Float( 0f, 1f ) )
				+ new Vector3( Game.Random.Float( -StreetSpread, StreetSpread ), Game.Random.Float( -StreetSpread, StreetSpread ), 0f );
			if ( PopulaceMap.CanWalk( at ) ) return true;
		}
		at = default;
		return false;
	}

	void AddAgent( int i, HumanRole role, Vector3 at, float yaw )
	{
		at.z = PopulaceMap.GroundAt( at );
		_agents[i] = new Agent
		{
			Position = at,
			Home = at,
			Yaw = yaw,
			Phase = Game.Random.Float( 0f, 20f ),
			Pace = Game.Random.Float( 0.8f, 1.2f ),
			Role = (byte)HumanRoles.IndexOf( role ),
			Colour = (byte)BakeColour( role ),
			Level = Level.Asleep,
			Squad = -1,
			Cell = -1,
			AwakeSlot = -1,
			Brave = role.Manner == HumanManner.Brave || (role.Manner == HumanManner.Stroller && Game.Random.Float( 0f, 1f ) < BraveChance),
			Shielded = role.Shield,
		};
	}

	/// <summary>The colour somebody shows up in from afar: the nearest of the baked palette to what they wear.</summary>
	static int BakeColour( HumanRole role )
	{
		var wears = role.Coat ?? role.Shirt;
		if ( wears is not { } tint ) return Game.Random.Next( TownShirts );

		int best = 0;
		float bestGap = float.MaxValue;
		for ( int c = 0; c < Palette.Length; c++ )
		{
			float gap = MathF.Abs( Palette[c].r - tint.r ) + MathF.Abs( Palette[c].g - tint.g ) + MathF.Abs( Palette[c].b - tint.b );
			if ( gap < bestGap ) { bestGap = gap; best = c; }
		}
		return best;
	}

	/// <summary>What a stand-in or a real body wears on top: the coat, else the shirt, else its colour from the town's shirts.</summary>
	static Color TopTint( in Agent a, HumanRole role ) => role.Coat ?? role.Shirt ?? Palette[a.Colour % Palette.Length];

	void SortIntoCells( int count )
	{
		var cells = new Dictionary<(int, int), Cell>();
		for ( int i = 0; i < count; i++ )
		{
			var at = _agents[i].Home;
			var key = ((int)MathF.Floor( at.x / CellSize ), (int)MathF.Floor( at.y / CellSize ));
			if ( !cells.TryGetValue( key, out var cell ) )
			{
				cell = new Cell { Index = _cells.Count };
				cells[key] = cell;
				_cells.Add( cell );
			}
			_agents[i].Cell = cell.Index;
			cell.Agents.Add( i );
		}

		foreach ( var cell in _cells )
		{
			var sum = Vector3.Zero;
			foreach ( int i in cell.Agents ) sum += _agents[i].Home;
			cell.Centre = sum / cell.Agents.Count;
			foreach ( int i in cell.Agents ) cell.Radius = MathF.Max( cell.Radius, FlatDistance( _agents[i].Home, cell.Centre ) );
			cell.Radius += 40f;
			cell.Lump = new LumpTarget( this, cell );
			Rampage.Register( cell.Lump, false );
		}
	}

	/// <summary>The far crowd: one block's people as one mesh per colour, shown while the block sleeps.</summary>
	void BakeCell( Cell cell )
	{
		var bodies = new MeshBuffer[Palette.Length];
		var heads = new MeshBuffer();
		foreach ( int i in cell.Agents )
		{
			ref var a = ref _agents[i];
			float size = HumanRoles.All[a.Role].Scale;
			AddBody( bodies[a.Colour] ??= new MeshBuffer(), a.Home, a.Yaw, size );
			AddHead( heads, a.Home, a.Yaw, size );
		}

		bool first = true;
		for ( int c = 0; c < Palette.Length; c++ )
		{
			if ( bodies[c] is null ) continue;
			var chunk = new GameObject( _root, true, "Far Crowd" );
			chunk.Flags |= GameObjectFlags.NotSaved;
			ChunkPart( chunk, bodies[c], Palette[c] );
			if ( first ) ChunkPart( chunk, heads, Skins[cell.Index % Skins.Length] );
			first = false;
			cell.Chunks.Add( chunk );
		}
	}

	void ChunkPart( GameObject go, MeshBuffer buffer, Color tint )
	{
		var renderer = go.Components.Create<ModelRenderer>();
		renderer.Model = MakeModel( buffer );
		renderer.Tint = tint;
		renderer.RenderType = ModelRenderer.ShadowRenderType.Off;
	}

	Model MakeModel( MeshBuffer buffer )
	{
		var mesh = new Mesh( _material );
		mesh.CreateVertexBuffer( buffer.Vertices.Count, buffer.Vertices );
		mesh.CreateIndexBuffer( buffer.Indices.Count, buffer.Indices );
		mesh.Bounds = new BBox( buffer.Mins, buffer.Maxs );
		var model = Model.Builder.AddMesh( mesh ).Create();
		_meshes.Add( mesh );
		_models.Add( model );
		return model;
	}

	// A person from far away: a block for the body and a block for the head (the stadium's own).
	static void AddBody( MeshBuffer m, Vector3 feet, float yaw, float size ) => AddBox( m, feet, yaw, 6f * size, 11f * size, 0f, 54f * size, false );
	static void AddHead( MeshBuffer m, Vector3 feet, float yaw, float size ) => AddBox( m, feet, yaw, 7f * size, 7f * size, 55f * size, 69f * size, true );

	/// <summary>A box standing on <paramref name="feet"/>, turned about the vertical. Both windings, so it shows whichever way the engine culls.</summary>
	static void AddBox( MeshBuffer m, Vector3 feet, float yaw, float hx, float hy, float z0, float z1, bool bottom )
	{
		float cos = MathF.Cos( yaw ), sin = MathF.Sin( yaw );
		Vector3 P( float x, float y, float z ) => feet + new Vector3( x * cos - y * sin, x * sin + y * cos, z );
		Vector3 N( float x, float y ) => new( x * cos - y * sin, x * sin + y * cos, 0f );

		Quad( m, P( hx, -hy, z0 ), P( hx, hy, z0 ), P( hx, hy, z1 ), P( hx, -hy, z1 ), N( 1f, 0f ) );
		Quad( m, P( -hx, hy, z0 ), P( -hx, -hy, z0 ), P( -hx, -hy, z1 ), P( -hx, hy, z1 ), N( -1f, 0f ) );
		Quad( m, P( hx, hy, z0 ), P( -hx, hy, z0 ), P( -hx, hy, z1 ), P( hx, hy, z1 ), N( 0f, 1f ) );
		Quad( m, P( -hx, -hy, z0 ), P( hx, -hy, z0 ), P( hx, -hy, z1 ), P( -hx, -hy, z1 ), N( 0f, -1f ) );
		Quad( m, P( -hx, -hy, z1 ), P( hx, -hy, z1 ), P( hx, hy, z1 ), P( -hx, hy, z1 ), Vector3.Up );
		if ( bottom ) Quad( m, P( -hx, hy, z0 ), P( hx, hy, z0 ), P( hx, -hy, z0 ), P( -hx, -hy, z0 ), Vector3.Down );
	}

	static void Quad( MeshBuffer m, Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector3 normal )
	{
		int i = m.Vertices.Count;
		var tangent = MathF.Abs( normal.z ) > 0.5f ? Vector3.Forward : Vector3.Up;
		m.Vertices.Add( new Vertex( a, normal, tangent, new Vector4( 0f, 0f, 0f, 0f ) ) );
		m.Vertices.Add( new Vertex( b, normal, tangent, new Vector4( 1f, 0f, 0f, 0f ) ) );
		m.Vertices.Add( new Vertex( c, normal, tangent, new Vector4( 1f, 1f, 0f, 0f ) ) );
		m.Vertices.Add( new Vertex( d, normal, tangent, new Vector4( 0f, 1f, 0f, 0f ) ) );

		m.Indices.Add( i ); m.Indices.Add( i + 1 ); m.Indices.Add( i + 2 );
		m.Indices.Add( i ); m.Indices.Add( i + 2 ); m.Indices.Add( i + 3 );
		m.Indices.Add( i ); m.Indices.Add( i + 2 ); m.Indices.Add( i + 1 );
		m.Indices.Add( i ); m.Indices.Add( i + 3 ); m.Indices.Add( i + 2 );

		m.Mins = Vector3.Min( m.Mins, Vector3.Min( Vector3.Min( a, b ), Vector3.Min( c, d ) ) );
		m.Maxs = Vector3.Max( m.Maxs, Vector3.Max( Vector3.Max( a, b ), Vector3.Max( c, d ) ) );
	}

	void PlaceFatGuy( IReadOnlyList<Vector3> streets, Vector3 keepClear )
	{
		// Somewhere in town: a street a good walk from where the lizard comes up.
		var at = PopulaceMap.Contain( keepClear + new Vector3( 1800f, 900f, 0f ) );
		for ( int tries = 0; tries < 40 && streets.Count > 0; tries++ )
		{
			var spot = streets[Game.Random.Next( streets.Count )];
			float distance = FlatDistance( spot, keepClear );
			if ( distance < 1400f || distance > 3200f || !PopulaceMap.CanWalk( spot ) ) continue;
			at = spot;
			break;
		}
		at.z = PopulaceMap.GroundAt( at );

		var go = new GameObject( _root, true, "The Fat Guy" );
		go.Flags |= GameObjectFlags.NotSaved;
		go.WorldPosition = at;
		go.WorldRotation = Rotation.FromYaw( Game.Random.Float( 0f, 360f ) );

		var fat = go.Components.Create<FatGuy>();
		fat.CameoOnly = true;
		fat.CameoWobble = true;
		TheFatGuy = go.Components.Create<RampageFatGuy>();
	}

	// ---- Blocks waking and sleeping ------------------------------------------------------------------

	void WakeAndSleepCells( Vector3 lizard )
	{
		float wake = WakeRadius, sleep = SleepRadius;
		int wakes = RampageGame.Current is { Phase: RampagePhase.Intro } ? 4 : 1;     // behind the intro's black, faster
		foreach ( var cell in _cells )
		{
			float distance = MathF.Max( FlatDistance( cell.Centre, lizard ) - cell.Radius, 0f );
			if ( !cell.Awake )
			{
				// One block a look, so a street of them never wakes in the same frame.
				if ( wakes > 0 && distance < wake && _awake.Count + cell.Agents.Count <= MaxAwake ) { WakeCell( cell ); wakes--; }
			}
			else if ( distance > sleep ) SleepCell( cell, lizard );
		}
	}

	/// <summary>The block's baked crowd is hidden and each of its people becomes a stand-in.</summary>
	void WakeCell( Cell cell )
	{
		if ( cell.Awake ) return;
		cell.Awake = true;
		foreach ( var chunk in cell.Chunks ) if ( chunk.IsValid() ) chunk.Enabled = false;
		Rampage.Unregister( cell.Lump );

		foreach ( int i in cell.Agents )
		{
			ref var a = ref _agents[i];
			a.Stray = false;
			if ( a.Level != Level.Asleep ) continue;    // still out and about from last time
			WakeAgent( i );
		}
	}

	/// <summary>One sleeping person becomes a stand-in where it stands, and something the weapon can hit.</summary>
	void WakeAgent( int i )
	{
		ref var a = ref _agents[i];
		a.Level = Level.StandIn;
		a.StandIn = TakeStandIn( in a );
		a.AwakeSlot = _awake.Count;
		_awake.Add( i );

		if ( HumanRoles.All[a.Role].Manner == HumanManner.Child ) return;   // the child is never a target
		a.Target ??= new PersonTarget( this, i );
		Rampage.Register( a.Target );
	}

	/// <summary>
	/// The lizard has gone: everybody of this block goes home, calm, dusted off and worth points
	/// again, and the baked crowd is shown. Anybody still near the lizard, in the air or a real
	/// body is left out as a stray and goes home later.
	/// </summary>
	void SleepCell( Cell cell, Vector3 lizard )
	{
		cell.Awake = false;
		float near = WakeRadius * 0.8f;
		foreach ( int i in cell.Agents )
		{
			ref var a = ref _agents[i];
			if ( a.Level == Level.Asleep ) continue;
			if ( a.Level != Level.StandIn || FlatDistance( a.Position, lizard ) < near ) { a.Stray = true; continue; }
			SendHome( i );
		}
		foreach ( var chunk in cell.Chunks ) if ( chunk.IsValid() ) chunk.Enabled = true;
		Rampage.Register( cell.Lump, false );
	}

	/// <summary>A stand-in goes home: back into its sleeping block (or, for one of the authorities, off duty).</summary>
	void SendHome( int i )
	{
		ref var a = ref _agents[i];
		if ( a.Target is not null ) Rampage.Unregister( a.Target );
		ReturnStandIn( ref a );
		RemoveAwake( i );

		a.Velocity = Vector3.Zero;
		a.Panic = 0f;
		a.Hits = 0;
		a.Chain = 0;
		a.Cowed = a.Dazed = a.Stranded = a.HasCover = a.Crouched = a.Stray = false;
		a.Squad = -1;

		if ( a.Cell < 0 )
		{
			// One of the authorities: the slot is free for the next wave.
			a.Level = Level.Free;
			a.Target = null;
			_free.Push( i );
			Responders = Math.Max( Responders - 1, 0 );
			return;
		}

		var role = HumanRoles.All[a.Role];
		a.Position = a.Home;
		a.Shielded = role.Shield;
		a.Level = Level.Asleep;

		// Its block woke again while it was away: straight back out as a stand-in at home.
		if ( _cells[a.Cell].Awake ) WakeAgent( i );
	}

	void RemoveAwake( int i )
	{
		ref var a = ref _agents[i];
		int slot = a.AwakeSlot;
		if ( slot < 0 || slot >= _awake.Count || _awake[slot] != i ) return;

		int last = _awake[^1];
		_awake[slot] = last;
		_agents[last].AwakeSlot = slot;
		_awake.RemoveAt( _awake.Count - 1 );
		a.AwakeSlot = -1;
	}

	// ---- The pool of stand-ins ---------------------------------------------------------------------

	StandIn TakeStandIn( in Agent a )
	{
		StandIn s = null;
		while ( _pool.Count > 0 && s is null )
		{
			s = _pool.Pop();
			if ( !s.Go.IsValid() ) s = null;
		}

		if ( s is null ) s = NewStandIn();
		else s.Go.Enabled = true;
		s.Trimmed = false;

		// Dressed as whoever it is standing in for.
		var role = HumanRoles.All[a.Role];
		s.Body.Tint = TopTint( in a, role );
		s.Go.WorldScale = role.Scale * (role.Burly || role.Guard ? 1.1f : 1f);
		s.Go.WorldPosition = a.Position;
		s.Go.WorldRotation = Rotation.FromYaw( a.Yaw * 180f / MathF.PI );

		s.Hat.Enabled = role.Hat.HasValue;
		if ( role.Hat is { } hat )
			PopulaceFx.Shape( s.Hat, s.HatRenderer, new Vector3( 0f, 0f, 71f ), role.WideHat ? new Vector3( 28f, 28f, 3f ) : new Vector3( 15f, 15f, 5f ), hat, false );

		bool prop = role.Prop is not null && (!role.Shield || a.Shielded);
		s.Prop.Enabled = prop;
		if ( prop ) PopulaceFx.Shape( s.Prop, s.PropRenderer, role.Prop.Position, role.Prop.Size, role.Prop.Tint, role.Prop.Ball );
		return s;
	}

	/// <summary>A new stand-in: the two models everybody shares, and a hat and a prop to be dressed later. No shadows.</summary>
	StandIn NewStandIn()
	{
		var s = new StandIn();
		s.Go = new GameObject( _root, true, "Stand-in" );
		s.Go.Flags |= GameObjectFlags.NotSaved;
		s.Body = s.Go.Components.Create<ModelRenderer>();
		s.Body.Model = _bodyModel;
		s.Body.RenderType = ModelRenderer.ShadowRenderType.Off;
		s.Head = s.Go.Components.Create<ModelRenderer>();
		s.Head.Model = _headModel;
		s.Head.Tint = Skins[Game.Random.Next( Skins.Length )];
		s.Head.RenderType = ModelRenderer.ShadowRenderType.Off;

		s.Hat = PopulaceFx.Block( s.Go, "Hat", Vector3.Zero, Vector3.One, Color.White );
		s.HatRenderer = s.Hat.Components.Get<ModelRenderer>();
		s.Prop = PopulaceFx.Block( s.Go, "Prop", Vector3.Zero, Vector3.One, Color.White );
		s.PropRenderer = s.Prop.Components.Get<ModelRenderer>();
		return s;
	}

	/// <summary>
	/// Far off, a hat and a phone are a pixel each and a draw each: they are switched off, and
	/// come back when the lizard is near again.
	/// </summary>
	void Trim( ref Agent a, HumanRole role, bool trimmed )
	{
		var s = a.StandIn;
		if ( s is null || s.Trimmed == trimmed ) return;
		s.Trimmed = trimmed;
		if ( s.Hat.IsValid() ) s.Hat.Enabled = !trimmed && role.Hat.HasValue;
		if ( s.Prop.IsValid() ) s.Prop.Enabled = !trimmed && role.Prop is not null && (!role.Shield || a.Shielded);
	}

	void ReturnStandIn( ref Agent a )
	{
		var s = a.StandIn;
		a.StandIn = null;
		if ( s is null ) return;
		if ( s.Stars is not null ) { PopulaceFx.ReturnStars( s.Stars ); s.Stars = null; }
		if ( !s.Go.IsValid() ) return;
		s.Go.Enabled = false;
		_pool.Push( s );
	}
}