Editor/CourseWallBuilderTool.Sync.cs

This file contains the CourseWallBuilderTool, an editor component that synchronizes the game scene's geometry with a wall structure graph. It creates, modifies, and destroys game objects representing posts and wall segments (rails) to match the state defined in the graph.

using Sandbox;
using Editor;
using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// Scene sync: makes the scene match a wall graph in one undo step. Doomed objects go, every post
/// without an object gets one, every touched post is stood and turned again, every rail without
/// pieces is built. The piece layouts here (where a corner stands for its rails, how edge pieces
/// tile a rail, how the Holekit rail stands) are the same functions the preview draws its ghosts
/// with, so what is shown is what is placed.
/// </summary>
public sealed partial class CourseWallBuilderTool
{
	const string KitWallModelPath = "models/kit/wall_100.vmdl";
	const string KitPostModelPath = "models/kit/post_10.vmdl";
	const string NuWallEdgePrefab = "prefabs/nuwall/edge.prefab";
	const string NuWallCornerPrefab = "prefabs/nuwall/edge_corner.prefab";
	const string NuWallEdgeModelPath = "models/kit/nuwall/edge.vmdl";
	const string NuWallCornerModelPath = "models/kit/nuwall/edge_corner.vmdl";

	/// <summary>NuWall: a tile's centre to its edge, the model y the edge piece's rail is built around.</summary>
	const float NuWallEdgeDistance = KitShape.Tile / 2f;

	/// <summary>NuWall: where the corner model's post stands, from the pivot, when the model is not loaded.</summary>
	static readonly Vector3 NuWallCornerPost = new( -NuWallEdgeDistance, NuWallEdgeDistance, 0f );

	/// <summary>NuWall: the corner post's footprint radius (18 for the 36 wide model).</summary>
	float NuWallCornerRadius => NuWallCornerModel is { } model ? MathF.Max( model.Bounds.Size.x, model.Bounds.Size.y ) * 0.5f : 18f;

	/// <summary>NuWall: how far short of a post's centre a rail stops: 8 inside the log's radius, so the rail end is buried in the post with no gap at any angle, while rails meeting at the post never run through each other at its centre.</summary>
	float NuWallRailInset => MathF.Max( 0f, NuWallCornerRadius - 8f );

	/// <summary>The Holekit post's footprint.</summary>
	const float PostSize = KitShape.WallThickness;

	Model _kitWall, _kitPost, _nuWallEdge, _nuWallCorner;
	Model KitWallModel => _kitWall ??= WallPieces.LoadModel( KitWallModelPath );
	Model KitPostModel => _kitPost ??= WallPieces.LoadModel( KitPostModelPath );
	Model NuWallEdgeModel => _nuWallEdge ??= WallPieces.LoadModel( NuWallEdgeModelPath );
	Model NuWallCornerModel => _nuWallCorner ??= WallPieces.LoadModel( NuWallCornerModelPath );

	/// <summary>The group whose walls get the invariant check at the start of the next frame: objects destroyed by an action are gone only then.</summary>
	GameObject _checkGroup;

	/// <summary>
	/// Syncs the scene to the graph as one undo step named for the action: destroys the doomed
	/// objects, stands a post for every post node without one (in the current style), re-stands and
	/// re-turns every touched post whose stance changes, builds every rail without pieces. An action
	/// that changes nothing (a rail over an existing one) makes no undo step. Returns false when there
	/// was nothing to do or no session. With golf_wall_debug on, the scene is read back and checked
	/// next frame.
	/// </summary>
	bool Apply( WallGraph graph, string name )
	{
		var session = SceneEditorSession.Active;
		if ( session is null ) return false;
		var parent = ParentFor( graph.Group );
		var doomed = graph.Doomed.Where( go => go.IsValid() ).ToList();
		var moves = new List<(WallPost post, Transform to)>();
		foreach ( var post in graph.Touched )
		{
			if ( !post.Object.IsValid() || doomed.Contains( post.Object ) ) continue;
			var to = PostTransform( post.Object, post.Point, graph.RailInfo( post ) );
			if ( Differs( post.Object.WorldTransform, to ) ) moves.Add( (post, to) );
		}
		var builds = graph.Posts.Any( p => !p.Object.IsValid() ) || graph.Rails.Any( r => r.Pieces.Count == 0 );
		if ( doomed.Count == 0 && moves.Count == 0 && !builds ) return false;

		using ( session.Scene.Push() )
		using ( session.UndoScope( name ).WithGameObjectCreations().WithGameObjectDestructions( doomed ).WithGameObjectChanges( moves.Select( m => m.post.Object ).ToList(), GameObjectUndoFlags.All ).Push() )
		{
			foreach ( var go in doomed ) go.Destroy();
			foreach ( var (post, to) in moves ) post.Object.WorldTransform = to;
			foreach ( var post in graph.Posts.Where( p => !p.Object.IsValid() ) ) post.Object = CreatePost( parent, graph, post );
			foreach ( var rail in graph.Rails.Where( r => r.Pieces.Count == 0 ) ) rail.Pieces.AddRange( CreateRail( parent, rail ) );
			graph.Group.GetComponent<GolfHoleCollision>()?.MarkDirty();
		}
		graph.Doomed.Clear();
		graph.Touched.Clear();
		if ( DebugLog ) _checkGroup = graph.Group;
		return true;
	}

	/// <summary>True when two stances are not the same place and heading (within a hundredth of a unit and a hair of a degree).</summary>
	static bool Differs( Transform a, Transform b )
		=> a.Position.Distance( b.Position ) > 0.01f || Vector3.Dot( a.Rotation.Forward, b.Rotation.Forward ) < 0.9999999f || Vector3.Dot( a.Rotation.Up, b.Rotation.Up ) < 0.9999999f;

	/// <summary>A post object of the current style at a graph post: a NuWall corner turned to the rails there, or the kit post in concrete.</summary>
	GameObject CreatePost( GameObject parent, WallGraph graph, WallPost post )
	{
		if ( Style == WallStyle.NuWall )
		{
			var transform = NuWallCornerTransform( post.Point, graph.RailInfo( post ) );
			var corner = GameObject.Clone( NuWallCornerPrefab, transform, parent, true, "Post" );
			if ( corner is null ) { Log.Warning( $"Course Wall Builder: {NuWallCornerPrefab} is missing" ); return null; }
			corner.WorldTransform = transform;   // Clone takes the transform as local to the parent; the stance is a world one
			return corner;
		}
		var model = KitPostModel;
		if ( model is null )
		{
			Log.Warning( $"Course Wall Builder: {KitPostModelPath} is missing" );
			return null;
		}
		return WallPieces.CreateModelObject( parent, "Post", model, post.Point - WallPieces.StandOffset( model.Bounds ), Rotation.Identity, Vector3.One, WallPieces.LoadConcrete() );
	}

	/// <summary>The pieces of a rail in its style between its posts.</summary>
	List<GameObject> CreateRail( GameObject parent, WallRail rail )
	{
		var made = new List<GameObject>();
		if ( rail.Length < 1f ) return made;
		if ( rail.Style == WallStyle.NuWall )
		{
			foreach ( var transform in NuWallEdgeTransforms( rail.A.Point, rail.B.Point, RailHand( rail ) ) )
			{
				var go = GameObject.Clone( NuWallEdgePrefab, transform, parent, true, "Wall" );
				if ( go is null ) { Log.Warning( $"Course Wall Builder: {NuWallEdgePrefab} is missing" ); break; }
				go.WorldTransform = transform;   // Clone takes the transform as local to the parent; the stance is a world one
				go.LocalScale = transform.Scale;
				made.Add( go );
			}
			return made;
		}

		var wall = KitWallModel;
		if ( wall is null ) { Log.Warning( $"Course Wall Builder: {KitWallModelPath} is missing" ); return made; }
		var material = WallPieces.LoadConcrete();
		var from = rail.A.Point;
		var to = rail.B.Point;
		if ( Fit == WallFit.Stretch )
		{
			if ( WallPieces.PlaceModelWall( parent, wall, from, to, null, material ) is { } piece ) made.Add( piece );
			return made;
		}
		// Repeat: whole copies of the model along the run, the last one covering the rest.
		var run = to - from;
		var modelLength = MathF.Max( 1f, wall.Bounds.Size.x );
		var direction = run.Normal;
		var copies = (int)MathF.Floor( run.Length / modelLength );
		for ( var i = 0; i < copies; i++ )
			if ( WallPieces.PlaceModelWall( parent, wall, from + direction * (i * modelLength), from + direction * ((i + 1) * modelLength), null, material ) is { } piece ) made.Add( piece );
		if ( run.Length - copies * modelLength > 1f && WallPieces.PlaceModelWall( parent, wall, from + direction * (copies * modelLength), to, null, material ) is { } last ) made.Add( last );
		return made;
	}

	/// <summary>The hand a NuWall rail is laid with: its inside's side, or the camera rule when it has none.</summary>
	bool RailHand( WallRail rail ) => rail.Hand ?? CameraHand( rail.A.Point, rail.B.Point, ViewPosition() );

	/// <summary>The inside of a NuWall rail as a world direction from its hand.</summary>
	static Vector3 InsideFor( Vector3 from, Vector3 to, bool left )
	{
		var flat = (to - from).WithZ( 0f );
		if ( flat.Length < 0.01f ) return Vector3.Zero;
		var l = Rotation.LookAt( flat.Normal, Vector3.Up ).Left;
		return left ? l : -l;
	}

	/// <summary>The camera rule: the inside is the side of a rail further from where the camera is (or was at the run's first click). True when that is the left of from to to.</summary>
	static bool CameraHand( Vector3 from, Vector3 to, Vector3 camera )
	{
		var flat = (to - from).WithZ( 0f );
		if ( flat.Length < 1f ) return true;
		var left = Rotation.LookAt( flat.Normal, Vector3.Up ).Left;
		var mid = (from + to) * 0.5f;
		return (mid + left * NuWallEdgeDistance).Distance( camera ) > (mid - left * NuWallEdgeDistance).Distance( camera );
	}

	/// <summary>
	/// Where the view is: the gizmo's ray origin inside a gizmo frame, else the scene camera, else the
	/// origin. The gizmo state exists only while the editor draws a frame, so anything that runs the
	/// tool from outside (a script, a test) must not touch it directly.
	/// </summary>
	Vector3 ViewPosition()
	{
		try { return Gizmo.CurrentRay.Position; }
		catch ( Exception ) { }
		try { if ( Camera.IsValid() ) return Camera.WorldPosition; } catch ( Exception ) { }
		return Vector3.Zero;
	}

	// ---------------------------------------------------------------- piece layouts

	/// <summary>Where a post object stands for a foot point: a NuWall corner turned to the rails given, any other post by its foot, upright and keeping its yaw.</summary>
	Transform PostTransform( GameObject post, Vector3 point, IEnumerable<(Vector3 away, Vector3? inside)> rails )
	{
		if ( IsNuWallCorner( post ) ) return NuWallCornerTransform( point, rails );
		var yaw = Rotation.FromYaw( post.WorldRotation.Yaw() );
		if ( post.GetComponent<KitShape>() is null && post.GetComponent<ModelRenderer>() is { Model: { } model } )
			return new Transform( point - yaw * WallPieces.StandOffset( model.Bounds ), yaw );
		return new Transform( point, yaw );
	}

	/// <summary>
	/// Where a NuWall corner stands for a post point and the rails meeting there: its post (100 back
	/// and 100 left of the pivot) on the point, and the piece turned so its pivot lies on the inside
	/// of the corner, along the bisector of the rails' insides. One rail: its inside. Rails without an
	/// inside (Holekit): the bisector of the rails' directions. None: the pivot towards -y. So the
	/// piece's yaw follows the actual angle between the rails, 90 degrees or not.
	/// </summary>
	Transform NuWallCornerTransform( Vector3 point, IEnumerable<(Vector3 away, Vector3? inside)> rails )
	{
		var postLocal = NuWallCornerModel is { } model ? WallPieces.StandOffset( model.Bounds ) : NuWallCornerPost;
		var insides = Vector3.Zero;
		var aways = Vector3.Zero;
		var count = 0;
		foreach ( var (away, inside) in rails )
		{
			if ( inside is { } i && i.WithZ( 0f ).Length > 0.01f ) insides += i.WithZ( 0f ).Normal;
			if ( away.WithZ( 0f ).Length > 0.01f ) aways += away.WithZ( 0f ).Normal;
			count++;
		}
		var toPivot = insides.Length > 0.01f ? insides.Normal
			: count >= 2 && aways.Length > 0.01f ? aways.Normal
			: count == 1 && aways.Length > 0.01f ? Vector3.Cross( aways.Normal, Vector3.Up ).Normal
			: new Vector3( 1f, -1f, 0f ).Normal;

		// The pivot sits at post - postLocal in model space, i.e. along (100, -100): -45 degrees. Turn that onto toPivot.
		var pivotOffset = -postLocal;
		var modelAngle = MathF.Atan2( pivotOffset.y, pivotOffset.x );
		var yaw = MathF.Atan2( toPivot.y, toPivot.x ) - modelAngle;
		var rotation = Rotation.FromYaw( yaw * 180f / MathF.PI );
		return new Transform( point - rotation * postLocal, rotation );
	}

	/// <summary>
	/// The edge pieces of a NuWall rail between two post points as pivot transforms. The rail stops a
	/// rail inset short of each post so rails meeting at a post never run into each other; the corner
	/// covers the join. The shortened run is divided into as many equal pieces as fit nearest to the
	/// 200 piece length (at least one), each scaled along its length to its share, so there is no
	/// sliver and every join is flush. Each pivot sits 100 to the inside of the run, so the model's y
	/// 100 line (its rail, 95..115) lies on the run and the rail's slope faces the inside. The model's
	/// +Y is the run's left, so the run is laid with the inside on its right and reversed when the
	/// inside is on the left. Pitched along a slope, roll level.
	/// </summary>
	IEnumerable<Transform> NuWallEdgeTransforms( Vector3 from, Vector3 to, bool insideLeft )
	{
		if ( (to - from).WithZ( 0f ).Length < 1f ) yield break;
		if ( insideLeft ) (from, to) = (to, from);

		// Stop inside the posts' logs; a run too short for that keeps a one-unit stub in the middle.
		var inset = NuWallRailInset;
		var whole = to - from;
		if ( whole.Length > 2f * inset + 1f )
		{
			from += whole.Normal * inset;
			to -= whole.Normal * inset;
		}
		else
		{
			var mid = (from + to) * 0.5f;
			from = mid - whole.Normal * 0.5f;
			to = mid + whole.Normal * 0.5f;
		}

		var run = to - from;
		var length = run.Length;
		var direction = run.Normal;
		var rotation = Rotation.LookAt( direction, Vector3.Up );
		var toPivot = -rotation.Left * NuWallEdgeDistance;

		var pieces = Math.Max( 1, (int)MathF.Round( length / KitShape.Tile ) );
		var pieceLength = length / pieces;
		var scale = new Vector3( pieceLength / KitShape.Tile, 1f, 1f );
		for ( var i = 0; i < pieces; i++ )
		{
			var transform = new Transform( from + direction * ((i + 0.5f) * pieceLength) + toPivot, rotation );
			yield return MathF.Abs( scale.x - 1f ) > 0.001f ? transform.WithScale( scale ) : transform;
		}
	}

	/// <summary>Where the Holekit rail model stands scaled over a run: the ghost of the Kit Model Wall the click makes (which is rebuilt at the run's length rather than scaled, and sheared on a slope where this ghost is pitched).</summary>
	static Transform HolekitRailTransform( Model wall, Vector3 from, Vector3 to )
	{
		var run = to - from;
		var rotation = Rotation.LookAt( run.Normal, Vector3.Up );
		var bounds = wall.Bounds;
		var scale = new Vector3( run.Length / MathF.Max( 1f, bounds.Size.x ), 1f, 1f );
		var onLine = new Vector3( bounds.Center.x, bounds.Center.y, bounds.Mins.z );
		return new Transform( from + run * 0.5f - rotation * (onLine * scale), rotation ).WithScale( scale );
	}

	// ---------------------------------------------------------------- invariants

	/// <summary>
	/// Reads a group's walls back from the scene and lists everything wrong with them: the graph's
	/// own rules (one post per place, no duplicate, zero-length, crossing or overlapping rails, no
	/// rail through a post, every rail end on a post, every corner turned to its rails) and the run
	/// state (every post of the open run stands, each step joined to the one before). Empty when all
	/// is well.
	/// </summary>
	List<string> Invariants( GameObject group )
	{
		var graph = ReadGraph( group );
		var problems = graph.Violations( post => IsNuWallCorner( post.Object ) ? NuWallCornerTransform( post.Point, graph.RailInfo( post ) ) : null );
		if ( _run is not null && _run.GroupName == group.Name )
		{
			if ( _run.Scene != Scene ) problems.Add( "run state: the run belongs to another scene" );
			if ( _run.Points.Count == 0 ) problems.Add( "run state: a run with no post" );
			for ( var i = 0; i < _run.Points.Count; i++ )
			{
				var post = graph.PostAt( _run.Points[i] );
				if ( post is null ) { problems.Add( $"run state: no post stands at the run's step {i} ({_run.Points[i]})" ); continue; }
				if ( i > 0 && !graph.HasRailToward( post, _run.Points[i - 1] ) ) problems.Add( $"run state: step {i} ({_run.Points[i]}) has no rail back to step {i - 1}" );
			}
		}
		if ( _run is null && FlipInside ) problems.Add( "run state: Flip inside is on with no run open" );
		return problems;
	}

	/// <summary>golf_wall_debug: the invariant check of a group, one warning per problem, or one line that all is well.</summary>
	void LogInvariants( GameObject group )
	{
		var problems = Invariants( group );
		if ( problems.Count == 0 )
		{
			var graph = ReadGraph( group );
			Log.Info( $"golf_wall_debug: invariants ok ({graph.Posts.Count} posts, {graph.Rails.Count} rails{(_run is null ? "" : $", run of {_run.Points.Count}")})" );
			return;
		}
		foreach ( var problem in problems ) Log.Warning( $"golf_wall_debug: invariant broken: {problem}" );
	}
}