Rampage/World/TownKit.cs
using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>The town's paintbox. Kept below full white so the daylight does not blow anything out.</summary>
public static class Tone
{
	public static readonly Color Asphalt = new( 0.2f, 0.2f, 0.22f );
	public static readonly Color Pavement = new( 0.56f, 0.55f, 0.52f );
	public static readonly Color Grass = new( 0.3f, 0.5f, 0.22f );
	public static readonly Color Concrete = new( 0.48f, 0.48f, 0.46f );
	public static readonly Color Dirt = new( 0.42f, 0.32f, 0.2f );
	public static readonly Color Line = new( 0.8f, 0.8f, 0.74f );
	public static readonly Color Glass = new( 0.35f, 0.55f, 0.7f );
	public static readonly Color Dark = new( 0.08f, 0.08f, 0.09f );
	public static readonly Color Metal = new( 0.45f, 0.47f, 0.5f );
	public static readonly Color Wood = new( 0.42f, 0.28f, 0.16f );
	public static readonly Color Leaf = new( 0.2f, 0.45f, 0.16f );
	public static readonly Color White = new( 0.82f, 0.82f, 0.8f );
	public static readonly Color Red = new( 0.75f, 0.14f, 0.12f );
	public static readonly Color Blue = new( 0.15f, 0.3f, 0.7f );
	public static readonly Color Yellow = new( 0.9f, 0.72f, 0.12f );
	public static readonly Color Green = new( 0.15f, 0.4f, 0.2f );
	public static readonly Color Orange = new( 0.9f, 0.45f, 0.1f );
	public static readonly Color Brick = new( 0.6f, 0.3f, 0.22f );
	public static readonly Color Stone = new( 0.62f, 0.6f, 0.55f );
	public static readonly Color Sand = new( 0.74f, 0.62f, 0.45f );
	public static readonly Color Water = new( 0.25f, 0.5f, 0.9f );
	public static readonly Color Dust = new( 0.75f, 0.72f, 0.66f );
	public static readonly Color Army = new( 0.3f, 0.36f, 0.2f );
	public static readonly Color Corn = new( 0.8f, 0.7f, 0.2f );
	public static readonly Color Hay = new( 0.78f, 0.66f, 0.3f );
	public static readonly Color Pink = new( 0.9f, 0.45f, 0.6f );
	public static readonly Color Slate = new( 0.3f, 0.32f, 0.36f );
	public static readonly Color Fire = new( 1f, 0.55f, 0.1f );
	public static readonly Color Smoke = new( 0.16f, 0.15f, 0.15f );

	/// <summary>House paint.</summary>
	public static readonly Color[] Pastels =
	{
		new( 0.8f, 0.74f, 0.6f ), new( 0.62f, 0.72f, 0.78f ), new( 0.78f, 0.62f, 0.56f ), new( 0.66f, 0.76f, 0.62f ),
		new( 0.8f, 0.78f, 0.7f ), new( 0.72f, 0.64f, 0.76f ),
	};

	/// <summary>Roof tiles.</summary>
	public static readonly Color[] Roofs = { new( 0.5f, 0.2f, 0.16f ), new( 0.3f, 0.3f, 0.33f ), new( 0.38f, 0.26f, 0.18f ) };

	/// <summary>Car paint.</summary>
	public static readonly Color[] Cars =
	{
		new( 0.7f, 0.12f, 0.1f ), new( 0.14f, 0.3f, 0.62f ), new( 0.75f, 0.75f, 0.72f ), new( 0.14f, 0.14f, 0.16f ),
		new( 0.2f, 0.45f, 0.3f ), new( 0.8f, 0.6f, 0.15f ), new( 0.45f, 0.47f, 0.5f ), new( 0.5f, 0.3f, 0.55f ),
	};

	/// <summary>A colour as a small number, to group boxes of one colour into one mesh.</summary>
	public static int Key( Color c )
		=> ((int)(Math.Clamp( c.r, 0f, 1f ) * 63f) << 12) | ((int)(Math.Clamp( c.g, 0f, 1f ) * 63f) << 6) | (int)(Math.Clamp( c.b, 0f, 1f ) * 63f);

	public static Color Shade( Color c, float by ) => new( c.r * by, c.g * by, c.b * by );
}

/// <summary>Triangles of one colour, gathered before they become a mesh. Every face is added in both
/// windings, so it shows whichever way the engine culls.</summary>
public sealed class TownMesh
{
	public readonly List<Vertex> Vertices = new();
	public readonly List<int> Indices = new();
	public Vector3 Mins = new( float.MaxValue ), Maxs = new( float.MinValue );
	public Color Tint = Color.White;

	public bool Empty => Vertices.Count == 0;

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

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

		Grow( a ); Grow( b ); Grow( c ); Grow( d );
	}

	public void Tri( Vector3 a, Vector3 b, Vector3 c, Vector3 normal )
	{
		int i = Vertices.Count;
		Vertices.Add( new Vertex( a, normal, Vector3.Up, new Vector4( 0f, 0f, 0f, 0f ) ) );
		Vertices.Add( new Vertex( b, normal, Vector3.Up, new Vector4( 1f, 0f, 0f, 0f ) ) );
		Vertices.Add( new Vertex( c, normal, Vector3.Up, new Vector4( 0.5f, 1f, 0f, 0f ) ) );
		Indices.Add( i ); Indices.Add( i + 1 ); Indices.Add( i + 2 );
		Indices.Add( i ); Indices.Add( i + 2 ); Indices.Add( i + 1 );
		Grow( a ); Grow( b ); Grow( c );
	}

	void Grow( Vector3 p )
	{
		Mins = Vector3.Min( Mins, p );
		Maxs = Vector3.Max( Maxs, p );
	}

	/// <summary>A box by its centre and full size, turned any way.</summary>
	public void Box( Vector3 centre, Vector3 size, Rotation turn )
	{
		var h = size * 0.5f;
		Vector3 P( float x, float y, float z ) => centre + turn * new Vector3( x * h.x, y * h.y, z * h.z );
		Vector3 fwd = turn * Vector3.Forward, left = turn * Vector3.Left, up = turn * Vector3.Up;

		Quad( P( 1, -1, -1 ), P( 1, 1, -1 ), P( 1, 1, 1 ), P( 1, -1, 1 ), fwd );
		Quad( P( -1, 1, -1 ), P( -1, -1, -1 ), P( -1, -1, 1 ), P( -1, 1, 1 ), -fwd );
		Quad( P( 1, 1, -1 ), P( -1, 1, -1 ), P( -1, 1, 1 ), P( 1, 1, 1 ), left );
		Quad( P( -1, -1, -1 ), P( 1, -1, -1 ), P( 1, -1, 1 ), P( -1, -1, 1 ), -left );
		Quad( P( -1, -1, 1 ), P( 1, -1, 1 ), P( 1, 1, 1 ), P( -1, 1, 1 ), up );
		Quad( P( -1, 1, -1 ), P( 1, 1, -1 ), P( 1, -1, -1 ), P( -1, -1, -1 ), -up );
	}

	public void Box( Vector3 centre, Vector3 size ) => Box( centre, size, Rotation.Identity );

	/// <summary>A flat piece of ground between two corners, facing up.</summary>
	public void Flat( float x0, float y0, float x1, float y1, float z )
		=> Quad( new Vector3( x0, y0, z ), new Vector3( x1, y0, z ), new Vector3( x1, y1, z ), new Vector3( x0, y1, z ), Vector3.Up );

	/// <summary>A pitched roof: a prism standing on a rectangle, its ridge along X or along Y.</summary>
	public void Gable( Vector3 baseCentre, float sizeX, float sizeY, float rise, bool ridgeAlongX )
	{
		float hu = (ridgeAlongX ? sizeX : sizeY) * 0.5f, hv = (ridgeAlongX ? sizeY : sizeX) * 0.5f;
		Vector3 P( float u, float v, float z ) => baseCentre + (ridgeAlongX ? new Vector3( u, v, z ) : new Vector3( v, u, z ));
		Vector3 N( float u, float v, float z ) => (ridgeAlongX ? new Vector3( u, v, z ) : new Vector3( v, u, z )).Normal;

		Vector3 r0 = P( -hu, 0f, rise ), r1 = P( hu, 0f, rise );
		Quad( P( -hu, -hv, 0f ), P( hu, -hv, 0f ), r1, r0, N( 0f, -rise, hv ) );
		Quad( P( hu, hv, 0f ), P( -hu, hv, 0f ), r0, r1, N( 0f, rise, hv ) );
		Tri( P( -hu, -hv, 0f ), P( -hu, hv, 0f ), r0, N( -1f, 0f, 0f ) );
		Tri( P( hu, hv, 0f ), P( hu, -hv, 0f ), r1, N( 1f, 0f, 0f ) );
		Quad( P( -hu, -hv, 0f ), P( hu, -hv, 0f ), P( hu, hv, 0f ), P( -hu, hv, 0f ), Vector3.Down );
	}
}

/// <summary>
/// The few things every part of the town is made from: a plain cube, a ball, the one material,
/// and the generated meshes (held on to here, or they would be collected and stop drawing).
/// </summary>
public sealed class TownKit
{
	/// <summary>The cube model is this big, centred on its origin (the same as the dev box).</summary>
	public const float BoxSize = 50f;
	/// <summary>The ball model has this radius.</summary>
	public const float BallRadius = 32f;

	public Model Cube { get; private set; }
	public Model Ball { get; private set; }
	public Material Paint { get; private set; }

	readonly List<Mesh> _meshes = new();
	readonly List<Model> _models = new();

	public TownKit()
	{
		var devBox = Model.Load( "models/dev/box.vmdl" );
		Ball = Model.Load( "models/dev/sphere.vmdl" );
		Paint = Material.Load( "materials/default/white.vmat" ) ?? devBox.Materials.FirstOrDefault();

		var cube = new TownMesh();
		cube.Box( Vector3.Zero, new Vector3( BoxSize, BoxSize, BoxSize ) );
		Cube = Make( cube ) ?? devBox;
	}

	/// <summary>Turns gathered triangles into a model. Null if there are none.</summary>
	public Model Make( TownMesh buffer )
	{
		if ( buffer is null || buffer.Empty ) return null;
		var mesh = new Mesh( Paint );
		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;
	}

	/// <summary>An empty unsaved object under a parent, at a local position.</summary>
	public GameObject Empty( GameObject parent, string name, Vector3 local = default )
	{
		var go = new GameObject( parent, true, name );
		go.Flags |= GameObjectFlags.NotSaved;
		go.LocalPosition = local;
		return go;
	}

	public ModelRenderer Draw( GameObject go, Model model, Color tint, bool shadows = true )
	{
		var renderer = go.Components.Create<ModelRenderer>();
		renderer.Model = model;
		renderer.Tint = tint;
		if ( !shadows ) renderer.RenderType = ModelRenderer.ShadowRenderType.Off;
		return renderer;
	}

	/// <summary>One tinted box as a child object: local centre, full size. Drawn only, no collision.</summary>
	public GameObject Block( GameObject parent, string name, Vector3 centre, Vector3 size, Color colour, bool shadows = true )
	{
		var go = Empty( parent, name, centre );
		go.LocalScale = size / BoxSize;
		Draw( go, Cube, colour, shadows );
		return go;
	}

	/// <summary>One tinted ball as a child object, stretched to the given full size on each axis.</summary>
	public GameObject Blob( GameObject parent, string name, Vector3 centre, Vector3 size, Color colour )
	{
		var go = Empty( parent, name, centre );
		go.LocalScale = size / (BallRadius * 2f);
		Draw( go, Ball, colour, false );
		return go;
	}

	// ---- Sound ---------------------------------------------------------------------------------

	static readonly Dictionary<string, float> _lastPlayed = new();

	/// <summary>
	/// Plays sounds/rampage/&lt;name&gt;.sound at a spot. Fails quietly if the sound is not there,
	/// and never plays the same sound twice within <paramref name="gap"/> seconds.
	/// </summary>
	public static void Play( string name, Vector3 at, float gap = 0.08f )
	{
		float now = RealTime.Now;
		if ( _lastPlayed.TryGetValue( name, out float last ) && now - last < gap && now >= last ) return;
		_lastPlayed[name] = now;
		Rampage.PlaySound( name, at );
	}

	/// <summary>The rotation that tips something standing upright over toward a level direction, about its base.</summary>
	public static Rotation Tip( Vector3 toward, float radians )
	{
		var side = Vector3.Cross( Vector3.Up, toward );
		if ( side.LengthSquared < 0.0001f ) return Rotation.Identity;
		side = side.Normal;
		var up = Vector3.Up * MathF.Cos( radians ) + toward * MathF.Sin( radians );
		return Rotation.LookAt( side, up ) * Rotation.LookAt( side, Vector3.Up ).Inverse;
	}
}