The file defines the WallGraph data structure, its components (WallPost, WallRail), and the logic to normalize the wall geometry. It manages walls as a graph of connected points and segments and enforces various geometric invariants like merging close posts or splitting crossing rails.
using Sandbox;
using Editor;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The wall graph: the Course Wall Builder's model of one group's walls as posts at points and
/// rails between pairs of posts. It is read back from the scene objects (<see cref="ReadGraph"/>)
/// at the start of every frame and every action, changed through a handful of operations, and
/// synced back to the scene in one undo step (<see cref="Apply"/>). The graph never touches the
/// scene itself: it records the objects it has doomed and the posts it has touched. A clone of the
/// graph given the same operation is the preview.
///
/// Every operation leaves the graph normalised: one post per location, no rail without length, no
/// rail running through a post without ending on it, no two rails crossing (a post is added where
/// they do and both are split), no two rails between the same posts. Collinear overlaps fall out of
/// those rules: a rail's end post lying on another rail splits it, and the duplicate that leaves is
/// dropped. So a click on a rail splits it, a rail through a post is split at it, a rail across a
/// rail makes a four-way post, a rail along a rail adds only what is missing, and a post moved onto
/// another merges into it.
/// </summary>
public sealed partial class CourseWallBuilderTool
{
/// <summary>Two points closer than this (units) are the same place: one post per location, a rail end meets its post, a post on a rail's line splits it.</summary>
const float JoinDistance = 5f;
/// <summary>A post more than this above or below a rail's line, or two rails further apart in height where they would cross, are on different levels and do not meet.</summary>
const float LevelTolerance = 30f;
/// <summary>A post of the graph: its foot point and the scene object standing there (null until the graph is applied).</summary>
sealed class WallPost
{
public Vector3 Point;
public GameObject Object;
/// <summary>Set by <see cref="WallGraph.MovePost"/>: when two posts merge, the moved one gives way.</summary>
public bool Moved;
public override string ToString() => $"post at {Point}";
}
/// <summary>A rail of the graph: the two posts it joins, its style, its inside (NuWall: the world direction from the rail towards its tile) and the scene pieces built for it (empty until applied or when it is to be rebuilt).</summary>
sealed class WallRail
{
public WallPost A, B;
public WallStyle Style;
public Vector3? Inside;
public readonly List<GameObject> Pieces = new();
public bool Ends( WallPost post ) => A == post || B == post;
public WallPost Other( WallPost post ) => A == post ? B : A;
public Vector3 Flat => (B.Point - A.Point).WithZ( 0f );
public float Length => Flat.Length;
/// <summary>The left of the rail's direction from A to B, in the ground plane.</summary>
public Vector3 Left => Length < 0.01f ? Vector3.Left : Rotation.LookAt( Flat.Normal, Vector3.Up ).Left;
/// <summary>The inside as a hand: true when it lies on the left of A to B; null for no inside or one square to the rail.</summary>
public bool? Hand
{
get
{
if ( Inside is not { } inside || inside.WithZ( 0f ).Length < 0.01f ) return null;
var dot = Vector3.Dot( Left, inside.WithZ( 0f ).Normal );
return MathF.Abs( dot ) < 0.2f ? null : dot > 0f;
}
}
public override string ToString() => $"rail {A.Point} - {B.Point} ({Style}, {Pieces.Count} pieces)";
}
sealed class WallGraph
{
/// <summary>The group the walls belong to: a hole group, or the scene itself for pieces at the root.</summary>
public readonly GameObject Group;
public readonly List<WallPost> Posts = new();
public readonly List<WallRail> Rails = new();
/// <summary>Scene objects the operations have made redundant: destroyed when the graph is applied.</summary>
public readonly HashSet<GameObject> Doomed = new();
/// <summary>Posts whose point or rails changed: re-stood and re-turned when the graph is applied, and recorded in the undo step.</summary>
public readonly HashSet<WallPost> Touched = new();
public WallGraph( GameObject group ) { Group = group; }
// ---------------------------------------------------------------- queries
public WallPost PostAt( Vector3 point ) => Posts.Where( p => p.Point.Distance( point ) <= JoinDistance ).OrderBy( p => p.Point.Distance( point ) ).FirstOrDefault();
public WallPost PostOf( GameObject go ) => go.IsValid() ? Posts.FirstOrDefault( p => p.Object == go ) : null;
public IEnumerable<WallRail> RailsAt( WallPost post ) => Rails.Where( r => r.Ends( post ) );
public WallRail RailOf( GameObject piece ) => Rails.FirstOrDefault( r => r.Pieces.Contains( piece ) );
/// <summary>What a corner at a post needs: for each rail there, the direction away along it and its inside.</summary>
public IEnumerable<(Vector3 away, Vector3? inside)> RailInfo( WallPost post ) => RailsAt( post ).Select( r => (r.Other( post ).Point - post.Point, r.Inside) );
/// <summary>True when a rail leaves the post towards a point and reaches at least that far (the way a run's steps are joined, through any posts added on the way).</summary>
public bool HasRailToward( WallPost post, Vector3 point )
{
var to = (point - post.Point).WithZ( 0f );
if ( to.Length < 1f ) return false;
foreach ( var rail in RailsAt( post ) )
{
var along = (rail.Other( post ).Point - post.Point).WithZ( 0f );
if ( along.Length < 1f ) continue;
if ( Vector3.Dot( along.Normal, to.Normal ) >= 0.999f && along.Length <= to.Length + JoinDistance ) return true;
}
return false;
}
// ---------------------------------------------------------------- operations
/// <summary>The post at a point: the one already there, or a new one (which splits any rail it stands on).</summary>
public WallPost AddPost( Vector3 point )
{
if ( PostAt( point ) is { } existing ) return existing;
var post = new WallPost { Point = point };
Posts.Add( post );
Touched.Add( post );
Normalise();
return post;
}
/// <summary>A rail between two posts; what it crosses is split, what it runs along is kept, a duplicate adds nothing.</summary>
public void AddRail( WallPost a, WallPost b, WallStyle style, Vector3? inside )
{
if ( a == b || !Posts.Contains( a ) || !Posts.Contains( b ) ) return;
Rails.Add( new WallRail { A = a, B = b, Style = style, Inside = inside } );
Touched.Add( a );
Touched.Add( b );
Normalise();
}
/// <summary>Takes a rail out; its posts stay (the Delete action drops the ones left without rails).</summary>
public void RemoveRail( WallRail rail )
{
if ( !Rails.Remove( rail ) ) return;
Doom( rail );
Touched.Add( rail.A );
Touched.Add( rail.B );
}
/// <summary>Takes a post out with every rail ending at it.</summary>
public void RemovePost( WallPost post )
{
foreach ( var rail in RailsAt( post ).ToList() ) RemoveRail( rail );
if ( !Posts.Remove( post ) ) return;
if ( post.Object.IsValid() ) Doomed.Add( post.Object );
Touched.Remove( post );
}
/// <summary>Moves a post: its rails are rebuilt to the new point, each keeping its inside on the same hand; a post it lands on takes it over (merge).</summary>
public void MovePost( WallPost post, Vector3 point )
{
if ( !Posts.Contains( post ) ) return;
var hands = RailsAt( post ).Select( r => (rail: r, hand: r.Hand) ).ToList();
post.Point = point;
post.Moved = true;
Touched.Add( post );
foreach ( var (rail, hand) in hands )
{
Rebuild( rail );
if ( hand is { } h ) rail.Inside = rail.Left * (h ? 1f : -1f);
}
Normalise();
}
/// <summary>A rail to be built again from its posts: its pieces are doomed.</summary>
public void Rebuild( WallRail rail )
{
Doom( rail );
Touched.Add( rail.A );
Touched.Add( rail.B );
}
/// <summary>A rail in another style, rebuilt.</summary>
public void Restyle( WallRail rail, WallStyle style, Vector3? inside )
{
rail.Style = style;
rail.Inside = inside;
Rebuild( rail );
}
/// <summary>A copy to try an operation on: the preview, or a what-if. Shares the scene objects, starts with nothing doomed or touched.</summary>
public WallGraph Clone()
{
var copy = new WallGraph( Group );
var map = new Dictionary<WallPost, WallPost>();
foreach ( var post in Posts )
{
var c = new WallPost { Point = post.Point, Object = post.Object, Moved = post.Moved };
map[post] = c;
copy.Posts.Add( c );
}
foreach ( var rail in Rails )
{
var c = new WallRail { A = map[rail.A], B = map[rail.B], Style = rail.Style, Inside = rail.Inside };
c.Pieces.AddRange( rail.Pieces );
copy.Rails.Add( c );
}
return copy;
}
void Doom( WallRail rail )
{
foreach ( var go in rail.Pieces ) if ( go.IsValid() ) Doomed.Add( go );
rail.Pieces.Clear();
}
// ---------------------------------------------------------------- normalisation
/// <summary>Applies the rules until none changes anything: merge posts at one place, drop rails without length, split rails at the posts on them, split crossing rails at a new post, drop duplicate rails.</summary>
void Normalise()
{
for ( var guard = 0; guard < 256; guard++ )
{
if ( MergeClosePosts() || DropDegenerateRails() || SplitThroughPosts() || SplitCrossings() || DropDuplicateRails() ) continue;
return;
}
Log.Warning( "Course Wall Builder: the wall graph did not settle" );
}
bool MergeClosePosts()
{
for ( var i = 0; i < Posts.Count; i++ )
for ( var j = i + 1; j < Posts.Count; j++ )
{
if ( Posts[i].Point.Distance( Posts[j].Point ) > JoinDistance ) continue;
var survivor = Score( Posts[i] ) >= Score( Posts[j] ) ? Posts[i] : Posts[j];
Merge( survivor == Posts[i] ? Posts[j] : Posts[i], survivor );
return true;
}
return false;
}
/// <summary>Which of two posts at one place stays: a standing post over a new one, an unmoved post over the moved one.</summary>
static int Score( WallPost post ) => (post.Object.IsValid() ? 2 : 0) + (post.Moved ? 0 : 1);
void Merge( WallPost loser, WallPost survivor )
{
foreach ( var rail in RailsAt( loser ).ToList() )
{
Rebuild( rail );
if ( rail.A == loser ) rail.A = survivor;
if ( rail.B == loser ) rail.B = survivor;
}
Posts.Remove( loser );
if ( loser.Object.IsValid() ) Doomed.Add( loser.Object );
Touched.Remove( loser );
Touched.Add( survivor );
}
bool DropDegenerateRails()
{
var rail = Rails.FirstOrDefault( r => r.A == r.B || r.Length <= JoinDistance );
if ( rail is null ) return false;
RemoveRail( rail );
return true;
}
bool SplitThroughPosts()
{
foreach ( var rail in Rails )
foreach ( var post in Posts )
{
if ( rail.Ends( post ) || !Interior( rail, post.Point, out _ ) ) continue;
Split( rail, post );
return true;
}
return false;
}
bool SplitCrossings()
{
for ( var i = 0; i < Rails.Count; i++ )
for ( var j = i + 1; j < Rails.Count; j++ )
{
if ( CrossingOf( Rails[i], Rails[j] ) is not { } point ) continue;
var post = new WallPost { Point = point };
Posts.Add( post );
Touched.Add( post );
var a = Rails[i];
var b = Rails[j];
Split( a, post );
Split( b, post );
return true;
}
return false;
}
bool DropDuplicateRails()
{
for ( var i = 0; i < Rails.Count; i++ )
for ( var j = i + 1; j < Rails.Count; j++ )
{
var a = Rails[i];
var b = Rails[j];
if ( !(a.Ends( b.A ) && a.Ends( b.B )) ) continue;
// The standing rail stays; a new rail over it adds nothing.
RemoveRail( b.Pieces.Count == 0 || a.Pieces.Count > 0 ? b : a );
return true;
}
return false;
}
/// <summary>Replaces a rail by its two halves meeting at a post on it, both in the rail's style and inside.</summary>
void Split( WallRail rail, WallPost at )
{
if ( !Rails.Remove( rail ) ) return;
Doom( rail );
Rails.Add( new WallRail { A = rail.A, B = at, Style = rail.Style, Inside = rail.Inside } );
Rails.Add( new WallRail { A = at, B = rail.B, Style = rail.Style, Inside = rail.Inside } );
Touched.Add( rail.A );
Touched.Add( rail.B );
Touched.Add( at );
}
// ---------------------------------------------------------------- geometry
/// <summary>True when a point lies on a rail's line between its ends (more than the join distance from both, within it of the line, on the rail's level); along is the distance from A.</summary>
public static bool Interior( WallRail rail, Vector3 point, out float along )
{
along = 0f;
var e = rail.Flat;
var length = e.Length;
if ( length < 1f ) return false;
var ap = (point - rail.A.Point).WithZ( 0f );
along = Vector3.Dot( ap, e ) / length;
if ( along <= JoinDistance || along >= length - JoinDistance ) return false;
var t = along / length;
if ( (ap - e * t).Length > JoinDistance ) return false;
var z = rail.A.Point.z + (rail.B.Point.z - rail.A.Point.z) * t;
return MathF.Abs( point.z - z ) <= LevelTolerance;
}
/// <summary>Where two rails properly cross (not parallel, the meeting point inside both by more than the join distance, on the same level), on the first rail's line; null when they do not.</summary>
public static Vector3? CrossingOf( WallRail a, WallRail b )
{
var d1 = a.Flat;
var d2 = b.Flat;
var l1 = d1.Length;
var l2 = d2.Length;
if ( l1 < 1f || l2 < 1f ) return null;
var denom = d1.x * d2.y - d1.y * d2.x;
if ( MathF.Abs( denom ) < 0.02f * l1 * l2 ) return null; // parallel
var ap = (b.A.Point - a.A.Point).WithZ( 0f );
var s = (ap.x * d2.y - ap.y * d2.x) / denom; // 0..1 along a
var u = (ap.x * d1.y - ap.y * d1.x) / denom; // 0..1 along b
if ( s * l1 <= JoinDistance || s * l1 >= l1 - JoinDistance ) return null;
if ( u * l2 <= JoinDistance || u * l2 >= l2 - JoinDistance ) return null;
var onA = a.A.Point + (a.B.Point - a.A.Point) * s;
var onB = b.A.Point + (b.B.Point - b.A.Point) * u;
if ( MathF.Abs( onA.z - onB.z ) > LevelTolerance ) return null;
return onA;
}
/// <summary>True when two rails lie along one line and share more than the join distance of it.</summary>
public static bool Overlap( WallRail a, WallRail b )
{
var d1 = a.Flat;
var d2 = b.Flat;
if ( d1.Length < 1f || d2.Length < 1f ) return false;
var dir = d1.Normal;
if ( MathF.Abs( dir.x * d2.Normal.y - dir.y * d2.Normal.x ) > 0.02f ) return false; // not parallel
var ap = (b.A.Point - a.A.Point).WithZ( 0f );
if ( (ap - dir * Vector3.Dot( ap, dir )).Length > JoinDistance ) return false; // beside, not on the line
var p = Vector3.Dot( ap, dir );
var q = Vector3.Dot( (b.B.Point - a.A.Point).WithZ( 0f ), dir );
var lo = MathF.Max( 0f, MathF.Min( p, q ) );
var hi = MathF.Min( d1.Length, MathF.Max( p, q ) );
return hi - lo > JoinDistance;
}
// ---------------------------------------------------------------- invariants
/// <summary>
/// Everything that is wrong with the graph as it stands, one line each: posts at one place,
/// rails without length, duplicate rails, a rail through a post, crossing rails, overlapping
/// collinear rails, a rail end with no post standing there, a corner not turned to its rails
/// (expectedCorner gives where a post's object should stand, or null for a post that is not a
/// corner). Empty when all is well.
/// </summary>
public List<string> Violations( Func<WallPost, Transform?> expectedCorner )
{
var problems = new List<string>();
for ( var i = 0; i < Posts.Count; i++ )
for ( var j = i + 1; j < Posts.Count; j++ )
if ( Posts[i].Point.Distance( Posts[j].Point ) <= JoinDistance ) problems.Add( $"two posts at one place: {Posts[i].Point} and {Posts[j].Point}" );
foreach ( var rail in Rails )
{
if ( rail.A == rail.B || rail.Length <= JoinDistance ) problems.Add( $"rail without length at {rail.A.Point}" );
if ( !rail.A.Object.IsValid() ) problems.Add( $"rail end with no post at {rail.A.Point}" );
if ( !rail.B.Object.IsValid() ) problems.Add( $"rail end with no post at {rail.B.Point}" );
foreach ( var post in Posts )
if ( !rail.Ends( post ) && Interior( rail, post.Point, out _ ) ) problems.Add( $"{rail} runs through the post at {post.Point}" );
}
for ( var i = 0; i < Rails.Count; i++ )
for ( var j = i + 1; j < Rails.Count; j++ )
{
var a = Rails[i];
var b = Rails[j];
if ( a.Ends( b.A ) && a.Ends( b.B ) ) problems.Add( $"duplicate rails {a.A.Point} - {a.B.Point}" );
else if ( CrossingOf( a, b ) is { } point ) problems.Add( $"{a} crosses {b} at {point}" );
else if ( Overlap( a, b ) ) problems.Add( $"{a} overlaps {b}" );
}
foreach ( var post in Posts )
{
if ( !post.Object.IsValid() || expectedCorner( post ) is not { } expected ) continue;
var actual = post.Object.WorldTransform;
var yawOff = MathF.Abs( (actual.Rotation.Yaw() - expected.Rotation.Yaw() + 540f) % 360f - 180f );
if ( actual.Position.Distance( expected.Position ) > 0.5f || yawOff > 0.5f ) problems.Add( $"corner at {post.Point} is not turned to its rails (off by {actual.Position.Distance( expected.Position ):0.#} units, {yawOff:0.#} degrees)" );
}
return problems;
}
}
// ---------------------------------------------------------------- reading the scene
/// <summary>A course-wall post: named Post and not one of the bounds pieces (those carry the bounds tag and belong to Add bounds).</summary>
static bool IsPost( GameObject go ) => go.IsValid() && go.Name == "Post" && !go.Tags.Has( GolfHoleEdgeWalls.Tag );
/// <summary>A course-wall rail piece: named Wall and not one of the bounds pieces.</summary>
static bool IsRailPiece( GameObject go ) => go.IsValid() && go.Name == "Wall" && !go.Tags.Has( GolfHoleEdgeWalls.Tag );
bool IsNuWallEdge( GameObject go ) => NuWallEdgeModel is { } edge && go.GetComponent<ModelRenderer>()?.Model?.ResourcePath == edge.ResourcePath;
bool IsNuWallCorner( GameObject go ) => go.IsValid() && NuWallCornerModel is { } corner && go.GetComponent<ModelRenderer>()?.Model?.ResourcePath == corner.ResourcePath;
/// <summary>The foot of a post object: the point it was placed on.</summary>
static Vector3 PostPoint( GameObject post )
=> post.GetComponent<KitShape>() is null && post.GetComponent<ModelRenderer>() is { Model: { } model }
? post.WorldTransform.PointToWorld( WallPieces.StandOffset( model.Bounds ) )
: post.WorldPosition;
/// <summary>One end of a NuWall edge piece's rail line (100 along x from the pivot, at y 100), in world space; sign picks the end.</summary>
static Vector3 RailEndOf( GameObject piece, float sign ) => piece.WorldTransform.PointToWorld( new Vector3( sign * NuWallEdgeDistance, NuWallEdgeDistance, 0f ) );
/// <summary>The piece (a Post or Wall object) the hit object is or sits under, or null.</summary>
static GameObject PieceUnder( GameObject hit )
{
for ( var go = hit; go.IsValid() && go is not Sandbox.Scene; go = go.Parent )
if ( IsPost( go ) || IsRailPiece( go ) ) return go;
return null;
}
/// <summary>The group a piece belongs to: its hole group, or the scene when it sits at the root.</summary>
GameObject GroupOf( GameObject piece ) => piece.Parent.IsValid() ? piece.Parent : Scene;
/// <summary>The group as the placement functions want it: null for the scene root.</summary>
static GameObject ParentFor( GameObject group ) => group is Sandbox.Scene ? null : group;
/// <summary>
/// The graph of a group's walls as the scene has them. Posts are the Post objects by their feet.
/// A rail is a chain of Wall pieces that share ends along one line with no post at the shared
/// end: one Kit Model Wall (or several, Repeat fit) for Holekit, the edge pieces for NuWall, whose
/// rail line stops a rail inset short of each post. Each chain end goes to the post it runs to;
/// a rail end with no post there gets a post node without an object (the invariant check reports
/// it, and applying any change stands a post there). A post being dragged is read at the point
/// it started from, so the rails still end where they were built.
/// </summary>
WallGraph ReadGraph( GameObject group, (GameObject post, Vector3 at)? override_ = null )
{
var graph = new WallGraph( group );
foreach ( var go in group.Children )
{
if ( !IsPost( go ) ) continue;
var point = override_ is { } o && o.post == go ? o.at : PostPoint( go );
graph.Posts.Add( new WallPost { Point = point, Object = go } );
}
// Every rail piece as a line with its ends, style and inside.
var pieces = new List<(GameObject go, Vector3 e0, Vector3 e1, WallStyle style, Vector3? inside)>();
foreach ( var go in group.Children )
{
if ( !IsRailPiece( go ) ) continue;
if ( go.GetComponent<KitModelWall>() is { } kit )
pieces.Add( (go, go.WorldPosition, go.WorldPosition + go.WorldRotation.Forward * kit.Length + Vector3.Up * kit.Rise, WallStyle.Holekit, null) );
else if ( IsNuWallEdge( go ) )
pieces.Add( (go, RailEndOf( go, -1f ), RailEndOf( go, 1f ), WallStyle.NuWall, (-go.WorldRotation.Left).WithZ( 0f ).Normal) );
}
float Reach( WallStyle style ) => style == WallStyle.NuWall ? NuWallCornerRadius + JoinDistance : PostSize;
float Extend( WallStyle style ) => style == WallStyle.NuWall ? NuWallRailInset : 0f;
bool PostNear( Vector3 point, float reach ) => graph.Posts.Any( p => p.Point.Distance( point ) <= reach );
// A chain end goes to the post within reach that the rail runs to; none there: a post node at the rail's end.
WallPost EndPost( Vector3 end, Vector3 away, WallStyle style )
{
var target = end + away.Normal * Extend( style );
var post = graph.Posts.Where( p => p.Point.Distance( end ) <= Reach( style ) ).OrderBy( p => p.Point.Distance( target ) ).FirstOrDefault();
if ( post is not null ) return post;
post = new WallPost { Point = target };
graph.Posts.Add( post );
return post;
}
var used = new bool[pieces.Count];
for ( var i = 0; i < pieces.Count; i++ )
{
if ( used[i] ) continue;
used[i] = true;
var (go, a, b, style, inside) = pieces[i];
var chain = new List<GameObject> { go };
var direction = (b - a).WithZ( 0f ).Normal;
var reach = Reach( style );
var grew = true;
while ( grew )
{
grew = false;
for ( var j = 0; j < pieces.Count && !grew; j++ )
{
if ( used[j] || pieces[j].style != style ) continue;
var d = (pieces[j].e1 - pieces[j].e0).WithZ( 0f ).Normal;
if ( MathF.Abs( Vector3.Dot( d, direction ) ) < 0.999f ) continue;
foreach ( var (end, other) in new[] { (pieces[j].e0, pieces[j].e1), (pieces[j].e1, pieces[j].e0) } )
{
if ( end.Distance( a ) <= JoinDistance && !PostNear( a, reach ) ) a = other;
else if ( end.Distance( b ) <= JoinDistance && !PostNear( b, reach ) ) b = other;
else continue;
used[j] = true;
chain.Add( pieces[j].go );
grew = true;
break;
}
}
}
var rail = new WallRail { A = EndPost( a, a - b, style ), B = EndPost( b, b - a, style ), Style = style, Inside = inside };
rail.Pieces.AddRange( chain );
graph.Rails.Add( rail );
}
return graph;
}
}