Editor/CourseWallBuilderTool.cs

The Course Wall Builder editor tool constructs rail fences between posts in the scene view. It supports Holekit and NuWall styles, manages a piece-by-piece build run, and handles complex geometry snapping and piece placement logic.

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

/// <summary>
/// Course Wall Builder: a Scene view tool that draws the low rails shaping the putting lane, between
/// posts, like Golf With Your Friends' Easy Wall Builder. Click a surface to drop a post; every
/// further click drops the next post and fills a rail between the two, any angle, any length. The
/// run's own first post is a snap target once the run has three posts: clicking it lays the last
/// rail back to it and ends the run. Any other existing post can be joined. Right-click and Esc end
/// the run. A click on any existing post, with no run open, selects it; a click on the selected post
/// starts a run there (a NuWall run inherits the inside of the rail at that post). Pieces go under
/// the selected Hole group (or the scene root), each click with its own undo step.
///
/// The tool is built in layers, one partial file each. Input (this file): keys, the run, hover,
/// click, and the frame. Snap: one pass from the raw hit to the point a click uses. Graph: the walls
/// as posts and rails with the operations on them (add a post, add a rail, split a rail, merge
/// posts, move, remove), always normalised, so a rail across a rail is split at a new post, a post on
/// a rail splits it, a rail along a rail adds only what is missing, a post moved onto another merges
/// into it. Sync: the scene made to match the graph in one undo step, and the piece layouts. Edit:
/// the selection, the move gizmo, Delete and the style swap. Preview: the ghost of the pending click
/// from a clone of the graph through the same operations and layouts.
///
/// Two styles. Holekit: the kit's wall_100 rail between the posts (a Kit Model Wall, rebuilt at the
/// run's length and sheared on a slope so both ends stand vertical) and post_10 posts, in the kit
/// concrete. NuWall: the nuwall set's edge and edge_corner prefabs, placed by that set's own
/// convention: a piece's pivot sits at the centre of the tile the run borders and its rail (the
/// model's y 95..115) lands on the tile edge, so one edge piece covers 200 of run and an edge_corner
/// stands at every post, turned to the rails that meet there. The rail's slope faces the pivot: the
/// run's inside. The inside is the side further from the camera at the run's first click, kept on
/// the same hand round corners and through the loop close; Flip inside (the checkbox, or F) swaps it
/// for the current run.
///
/// The tall perimeter around a hole (hedges, trench walls) is not this tool's: the Add bounds button
/// on Golf Hole Collision builds that ring from the tile boundary.
/// </summary>
[EditorTool( "coursewall" )]
[Title( "Course Wall Builder" )]
[Icon( "fence" )]
public sealed partial class CourseWallBuilderTool : EditorTool
{
	/// <summary>The rail set the tool draws.</summary>
	public enum WallStyle
	{
		/// <summary>The hole kit's rail: wall_100 between the posts, post_10 posts, kit concrete.</summary>
		Holekit,

		/// <summary>The NuWall set: one edge piece per 200 of run and an edge_corner at every post, pivots on the bordering tile's centre.</summary>
		NuWall,
	}

	/// <summary>How a Holekit rail fills the run between two posts. NuWall always lays tile-sized pieces.</summary>
	public enum WallFit
	{
		/// <summary>One copy of the rail, rebuilt at the run's length.</summary>
		Stretch,

		/// <summary>Whole copies of the rail along the run; the last one covers the rest.</summary>
		Repeat,
	}

	/// <summary>Which rail set the tool draws.</summary>
	[Property, Title( "Style" )]
	public WallStyle Style { get; set; } = WallStyle.Holekit;

	/// <summary>How a Holekit rail fills the run between two posts.</summary>
	[Property, Title( "Fit (Holekit)" )]
	public WallFit Fit { get; set; } = WallFit.Stretch;

	/// <summary>NuWall: swaps the inside (the rail's slope side) of the current run. F does the same. Cleared when the run ends.</summary>
	[Property, Title( "Flip inside" )]
	public bool FlipInside { get; set; }

	/// <summary>golf_wall_debug: the invariant check after every action, the drag start, and a snap line while the cursor is near an edge midpoint or an axis 100 point.</summary>
	[Property, Title( "golf_wall_debug" )]
	public bool DebugLog { get; set; }

	/// <summary>
	/// An open run: the scene and group it is in, the points of its posts in click order, the inside
	/// hand locked by its first rail, the camera at its first click, and the insides of the rails at
	/// the post it was started from (for a run branching an existing NuWall wall).
	/// </summary>
	sealed class Run
	{
		public Sandbox.Scene Scene;

		/// <summary>The group by name: an undo that brings destroyed pieces back re-creates the group object, so a reference would go stale while the walls stand.</summary>
		public string GroupName;
		public readonly List<Vector3> Points = new();
		public bool? Hand;
		public Vector3 Camera;
		public readonly List<Vector3> Inherited = new();
		public Vector3 First => Points[0];
		public Vector3 Last => Points[^1];
	}

	/// <summary>The open run, or null. Set only by a click; cleared in <see cref="ResetRun"/>.</summary>
	Run _run;

	/// <summary>True while a run is open with a post to continue from.</summary>
	bool Continuing => _run is not null && _run.Points.Count > 0;

	Editor.Label _status, _snapStatus;
	WallStyle _lastStyle;
	bool _deleteWasDown, _escWasDown;

	/// <summary>
	/// The sidebar widget, which owns the tool's F shortcut on the scene view. A shortcut on a tool
	/// widget targeting the scene view is tried before the editor's own F (gameObject.frame), the
	/// way the mesh tools bind their F; the key is consumed when the tool acts on it and passed on
	/// to the editor when it does not. Polling the key would not stop the frame.
	/// </summary>
	sealed class Sidebar : ToolSidebarWidget
	{
		readonly CourseWallBuilderTool _tool;
		public Sidebar( CourseWallBuilderTool tool ) { _tool = tool; }

		[Shortcut( "coursewall.flip", "F", typeof( SceneViewWidget ) )]
		void Flip()
		{
			if ( !_tool.OnFlipKey() ) EditorShortcuts.PassShortcut = true;
		}
	}

	public override Widget CreateToolSidebar()
	{
		var sidebar = new Sidebar( this );
		sidebar.AddTitle( "Course Wall Builder", "fence" );
		sidebar.MinimumWidth = 320;

		var style = sidebar.AddGroup( "Style" );
		var so = this.GetSerialized();
		style.Add( Editor.ControlSheet.CreateRow( so.GetProperty( nameof( Style ) ) ) );
		style.Add( Editor.ControlSheet.CreateRow( so.GetProperty( nameof( Fit ) ) ) );
		style.Add( Editor.ControlSheet.CreateRow( so.GetProperty( nameof( FlipInside ) ) ) );
		style.Add( Editor.ControlSheet.CreateRow( so.GetProperty( nameof( DebugLog ) ) ) );
		style.Add( new Editor.Label( "Holekit: the kit rail and posts in concrete.\nNuWall: one edge per 200 of run, a corner at every post. The rail's slope faces the run's inside: the side away from the camera at the run's first click, kept on the same hand round corners. Flip inside or F swaps it for the current run.\nThe tall perimeter is Add bounds on Golf Hole Collision, not this tool." ) );

		var how = sidebar.AddGroup( "How to use" );
		how.Add( new Editor.Label( "Click a surface: a post.\nNext click: a post and a rail between.\nClick the run's first post: the last rail closes the loop and the run ends.\nClick another existing post: the rail joins it.\nEsc or right-click: end the run (placed pieces stay).\n\nWalls keep themselves tidy: a post set on a rail splits it, a rail across a rail gets a post where they cross, a rail along a rail adds only the missing part, a rail over an existing one adds nothing, and one post stands per place.\n\nSnapping, one pass per frame from the raw hit: the nearest point target first (posts, tile corners, edge midpoints, tile centres, 100 points on a locked axis), then the nearest line (tile edges, grid lines, the first-post alignment), then the direction alone (soft 45, 22.5 and right-angle steps), each within 30 units. Shift: hard snap to the nearest 100 grid point and 22.5 degree direction; posts, corners, midpoints and centres within 30 still win. Ctrl: only the loop close. Every snap draws in blue; the Snap line below names it.\nF: flip the inside of the current run (NuWall).\n\nEditing, with no run open:\nClick a post: select it. Click the selected post again: a new run starts there (branches its wall; NuWall keeps its inside).\nA selected or hovered post shows move arrows (X and Y; Z on a ramp): drag one to move the post with the usual snapping; it keeps to the floor unless Z is used; its rails are rebuilt on release. Release it on another post and the two merge.\nDelete: remove what is under the cursor (a rail whole, a post with its rails; a post left without rails goes too), else the selection.\nClick a rail: select it for the style swap or a flip (Shift-click adds or removes).\nChange Style with rails selected: they are rebuilt in the new style between the same posts.\nF: flip rail. With a rail selected and no run open, its slope swaps to the other side and the corners at both ends turn to match.\nCtrl+Z / Ctrl+Y: undo and redo any step." ) );

		var where = sidebar.AddGroup( "Pieces go under" );
		_status = new Editor.Label( ParentName() );
		where.Add( _status );

		var snap = sidebar.AddGroup( "Snap" );
		_snapStatus = new Editor.Label( "Snap: none" );
		snap.Add( _snapStatus );

		return sidebar;
	}

	public override void OnEnabled()
	{
		_lastStyle = Style;
		// The editor's own click-select and box-select would take the mouse press before the tool sees it.
		AllowGameObjectSelection = false;
		ResetRun();
	}

	public override void OnDisabled()
	{
		ResetRun();
		_deleteWasDown = _escWasDown = false;
		_selection.Clear();
		_gizmoPost = null;
		if ( _drag is { } drag && drag.Object.IsValid() ) drag.Object.WorldTransform = drag.Original;
		_drag = null;
	}

	// ---------------------------------------------------------------- the frame

	public override void OnUpdate()
	{
		if ( _status.IsValid() ) _status.Text = ParentName();

		// A drag holds the group it started in; otherwise the pieces go under the selected hole group,
		// else the open run's group (an undo can re-create the hole object and lose the selection), else the scene root.
		var group = _drag?.Group ?? FindParent() ?? RunGroup() ?? Scene;
		var parent = ParentFor( group );
		var graph = ReadGraph( group, _drag is { } d ? (d.Object, d.From) : null );
		ValidateRun( graph );
		if ( _checkGroup.IsValid() ) { LogInvariants( _checkGroup ); _checkGroup = null; }
		HandleKeys( graph );
		DrawSelection();

		// No scene-wide hitbox: the move gizmo's arrows are hitboxes themselves and must be what the cursor finds. Object picking is off while the tool is active.
		var trace = Scene.Trace.Ray( Gizmo.CurrentRay, 100000 ).UseRenderMeshes( true ).Run();
		_hovered = trace.Hit ? PieceUnder( trace.GameObject ) : null;
		var hovered = Continuing ? null : _hovered;

		// The gizmo owns the frame while one of its arrows is hovered or dragged: no snapping, no placing.
		if ( !Continuing && GizmoPost( hovered, trace ) is { } gizmoPost && UpdateMoveGizmo( graph, parent, gizmoPost ) )
		{
			SetSnapStatus( _drag is null ? "move gizmo" : "moving post" );
			return;
		}
		if ( !trace.Hit )
		{
			SetSnapStatus( "no surface" );
			return;
		}
		if ( hovered.IsValid() && !_selection.Contains( hovered ) ) DrawPieceOutline( hovered, false );

		var snap = Resolve( graph, parent, trace.HitPosition, Gizmo.IsShiftPressed, Gizmo.IsCtrlPressed );
		SetSnapStatus( snap.Kind.ToString() );
		DrawPreview( graph, snap );

		if ( Gizmo.WasLeftMousePressed ) HandleClick( graph, snap, hovered );
	}

	/// <summary>Keys, once per press: Esc and right-click end the run, Delete removes what is under the cursor or selected, a Style change rebuilds the selected rails. F is the sidebar's shortcut (<see cref="OnFlipKey"/>).</summary>
	void HandleKeys( WallGraph graph )
	{
		var escDown = Editor.Application.IsKeyDown( KeyCode.Escape );
		if ( escDown && !_escWasDown ) ResetRun();
		_escWasDown = escDown;
		if ( Gizmo.WasRightMousePressed ) ResetRun();

		var deleteDown = Editor.Application.IsKeyDown( KeyCode.Delete );
		if ( deleteDown && !_deleteWasDown ) DeleteHoveredOrSelection( graph );
		_deleteWasDown = deleteDown;

		if ( Style != _lastStyle )
		{
			_lastStyle = Style;
			SwapSelectedStyle( graph );
		}
	}

	/// <summary>
	/// The F key, from the sidebar's shortcut: with a run open, flips the run's inside; with no run
	/// open and a rail selected (and no drag going), flips that rail. True when it did one of those,
	/// so the key is consumed; false leaves the key to the editor.
	/// </summary>
	bool OnFlipKey()
	{
		if ( _run is not null ) { FlipInside = !FlipInside; return true; }
		if ( _drag is not null || !_selection.Any( IsRailPiece ) ) return false;
		FlipSelectedRails( ReadGraph( FindParent() ?? Scene ) );
		return true;
	}

	/// <summary>
	/// The click. On a piece with no run open: a rail is selected (for the style swap), a post is
	/// selected, and a click on the one selected post starts a run there. Otherwise the snap decides:
	/// the loop close, a join to an existing post (a rail while the run is open, the run's start when
	/// not), or a post at the point with the rail from the last post.
	/// </summary>
	void HandleClick( WallGraph graph, SnapResult snap, GameObject hovered )
	{
		if ( hovered.IsValid() )
		{
			if ( IsPost( hovered ) && !Gizmo.IsShiftPressed && _selection.Count == 1 && _selection[0] == hovered && graph.PostOf( hovered ) is { } selected )
				StartRunFromPost( graph, selected );
			else
				Select( graph, hovered, Gizmo.IsShiftPressed );
			return;
		}
		if ( snap.Kind == SnapKind.LoopClose )
		{
			CloseLoop( graph );
			return;
		}
		if ( snap.Kind == SnapKind.Post && graph.PostAt( snap.Point ) is { } existing )
		{
			if ( Continuing ) PlaceStep( graph, existing.Point );
			else StartRunFromPost( graph, existing );
			return;
		}
		PlaceStep( graph, snap.Point );
	}

	void SetSnapStatus( string text )
	{
		if ( _snapStatus.IsValid() ) _snapStatus.Text = $"Snap: {text}   |   build {GetType().Assembly.GetName().Version}";
	}

	/// <summary>The selected Hole group (the selection or one of its parents), else null for the scene root.</summary>
	GameObject FindParent()
	{
		foreach ( var selected in Selection.OfType<GameObject>() )
			for ( var go = selected; go.IsValid(); go = go.Parent )
				if ( go.GetComponent<GolfHoleCollision>() is not null || go.Name.StartsWith( "Hole ", StringComparison.OrdinalIgnoreCase ) ) return go;
		return null;
	}

	/// <summary>The open run's group by its name: the scene root, or the hole group so named; null for no run or none found.</summary>
	GameObject RunGroup()
	{
		if ( _run is null ) return null;
		if ( Scene.Name == _run.GroupName ) return Scene;
		return Scene.GetAllObjects( true ).FirstOrDefault( go => go.Name == _run.GroupName && (go.GetComponent<GolfHoleCollision>() is not null || go.Name.StartsWith( "Hole ", StringComparison.OrdinalIgnoreCase )) );
	}

	string ParentName()
	{
		var parent = FindParent() ?? RunGroup();
		return parent.IsValid() && parent is not Sandbox.Scene ? parent.Name : "the scene root (select a Hole group to build into it)";
	}

	// ---------------------------------------------------------------- the run

	/// <summary>The one place the run state is cleared. After it, only a click starts a run.</summary>
	void ResetRun()
	{
		_run = null;
		FlipInside = false;
	}

	/// <summary>A run begins in the group with the camera where it is now.</summary>
	void BeginRun( WallGraph graph )
	{
		ResetRun();
		_run = new Run { Scene = Scene, GroupName = graph.Group.Name, Camera = ViewPosition() };
	}

	/// <summary>
	/// Keeps the run honest every frame against the graph as it stands. Each click of the run is one
	/// undo step, so when the last step's post or rail is gone (Ctrl+Z, Delete, a move) that step
	/// drops off and the run stands at the step before, exactly as it did then; when every step is
	/// gone, or the scene or group changed, the run is over.
	/// </summary>
	void ValidateRun( WallGraph graph )
	{
		if ( _run is null ) return;
		if ( _run.Scene != Scene || _run.GroupName != graph.Group.Name ) { ResetRun(); return; }
		while ( _run.Points.Count > 0 && !StepStands( graph, _run.Points.Count - 1 ) ) _run.Points.RemoveAt( _run.Points.Count - 1 );
		if ( _run.Points.Count == 0 ) { ResetRun(); return; }
		if ( _run.Points.Count == 1 ) _run.Hand = null;   // no rail left: the hand is decided again by the next one
	}

	/// <summary>True when the run's step still stands: a post at its point and, past the first step, a rail from it back towards the step before.</summary>
	bool StepStands( WallGraph graph, int index )
	{
		var post = graph.PostAt( _run.Points[index] );
		if ( post is null ) return false;
		return index == 0 || graph.HasRailToward( post, _run.Points[index - 1] );
	}

	/// <summary>Starts a run at an existing post (extending or branching its wall), with no second post there; the NuWall rails at the post hand over their insides.</summary>
	void StartRunFromPost( WallGraph graph, WallPost post )
	{
		BeginRun( graph );
		_run.Inherited.AddRange( InsidesAt( graph, post ) );
		_run.Points.Add( post.Point );
	}

	/// <summary>The insides of the NuWall rails at a post, as world directions from the rail towards its tile.</summary>
	static IEnumerable<Vector3> InsidesAt( WallGraph graph, WallPost post )
		=> graph.RailsAt( post ).Where( r => r.Inside is { } i && i.WithZ( 0f ).Length > 0.01f ).Select( r => r.Inside.Value.WithZ( 0f ).Normal );

	/// <summary>
	/// The hand of the pending rail, before Flip inside: the run's locked hand; else, for a run started
	/// from a NuWall post, the side its inherited inside lies on (when the rail is not square to it);
	/// else the camera rule at the run's first click. True for the left of from to to.
	/// </summary>
	bool RunHand( Vector3 from, Vector3 to )
	{
		if ( _run.Hand is { } locked ) return locked;
		var flat = (to - from).WithZ( 0f );
		if ( flat.Length >= 1f )
		{
			var left = Rotation.LookAt( flat.Normal, Vector3.Up ).Left;
			foreach ( var inside in _run.Inherited )
			{
				var dot = Vector3.Dot( left, inside );
				if ( MathF.Abs( dot ) >= 0.2f ) return dot > 0f;
			}
		}
		return CameraHand( from, to, _run.Camera );
	}

	/// <summary>The inside of the pending rail as a world direction (Flip inside applied); null for a Holekit rail, which has none.</summary>
	Vector3? RailInside( Vector3 from, Vector3 to ) => Style == WallStyle.NuWall ? InsideFor( from, to, RunHand( from, to ) != FlipInside ) : null;

	/// <summary>
	/// One click of the run as one undo step: the post at the point (the existing one when a post
	/// stands there) and, while the run is open, the rail from the last post to it; the graph splits
	/// and merges whatever that touches. A click on the post the run stands at adds nothing.
	/// </summary>
	void PlaceStep( WallGraph graph, Vector3 point )
	{
		var from = Continuing ? graph.PostAt( _run.Last ) : null;
		if ( from is null ) BeginRun( graph );
		var post = graph.AddPost( point );
		if ( from == post ) return;
		if ( from is not null )
		{
			var inside = RailInside( from.Point, post.Point );
			if ( _run.Hand is null ) _run.Hand = RunHand( from.Point, post.Point );
			graph.AddRail( from, post, Style, inside );
		}
		_run.Points.Add( post.Point );
		Apply( graph, from is null ? "Course wall post" : "Course wall rail" );
	}

	/// <summary>The loop close as one undo step: the last rail back to the first post, and the run is over.</summary>
	void CloseLoop( WallGraph graph )
	{
		var first = graph.PostAt( _run.First );
		var last = graph.PostAt( _run.Last );
		if ( first is null || last is null || first == last ) { ResetRun(); return; }
		graph.AddRail( last, first, Style, RailInside( last.Point, first.Point ) );
		ResetRun();
		Apply( graph, "Course wall loop" );
	}

	// ---------------------------------------------------------------- hotload

	/// <summary>
	/// The tool manager makes a new tool instance only when the tool's name changes, so after a code
	/// hotload the toolbar keeps running the old instance with the old code (the engine's own tools
	/// never meet this: they live in the engine and are not hotloaded). Every frame the generation of
	/// this code that the editor's type library registers checks the running instance: when it is a
	/// Course Wall Builder of another (older) type, it steps the manager to the object tool and, once
	/// that has happened, back to this tool, which gives a fresh instance of the registered type and a
	/// fresh sidebar. Older generations of this code, whose hooks the editor still calls, stay quiet.
	/// </summary>
	static bool _recreating;
	static int _recreateAttempts;

	/// <summary>True when this generation of the code is the one the editor's type library registers under the tool's name.</summary>
	static bool IsRegisteredGeneration
	{
		get
		{
			var registered = EditorTypeLibrary.GetTypesWithAttribute<EditorToolAttribute>().FirstOrDefault( x => x.Type.IsNamed( nameof( CourseWallBuilderTool ) ) ).Type?.TargetType;
			return registered == typeof( CourseWallBuilderTool );
		}
	}

	[EditorEvent.Hotload]
	static void OnHotload()
	{
		_recreateAttempts = 0;
		_recreating = false;
	}

	[EditorEvent.Frame]
	static void KeepInstanceCurrent()
	{
		if ( !IsRegisteredGeneration ) return;
		var current = SceneViewWidget.Current?.Tools?.CurrentTool;
		if ( _recreating )
		{
			// Step two: the manager has switched to the object tool; come back as a fresh instance of this type.
			if ( current is null || current.GetType().Name != "ObjectEditorTool" ) return;
			_recreating = false;
			EditorToolManager.SetTool( nameof( CourseWallBuilderTool ) );
			return;
		}
		if ( current is null || current.GetType() == typeof( CourseWallBuilderTool ) ) return;
		if ( current.GetType().Name != nameof( CourseWallBuilderTool ) ) return;   // another tool is active
		if ( EditorToolManager.CurrentModeName != nameof( CourseWallBuilderTool ) ) return;
		if ( _recreateAttempts++ >= 3 ) return;
		Log.Info( $"Course Wall Builder: the running instance is from an older build, re-creating the tool (attempt {_recreateAttempts})" );
		EditorToolManager.SetTool( "ObjectEditorTool" );
		_recreating = true;
	}
}