Editor/TraceTools.cs

MCP toolset exposing physics traces to an editor AI tool: ray, sphere cast, box cast, batched rays and a ground-height grid sampler. Filters by tags, an ignored object hierarchy and trigger handling, and returns hit position, normal, distance, object, tags and surface.

using System;
using System.Collections.Generic;
using System.Linq;
using Editor.Mcp;
using Sandbox;
using static LevelTools.McpHelpers;

namespace LevelTools;

/// <summary>Whether a trace hits trigger colliders.</summary>
public enum TriggerMode
{
    /// <summary>Pass through triggers - the default.</summary>
    Ignore,
    /// <summary>Hit triggers as well as solids.</summary>
    Include,
    /// <summary>Hit triggers and nothing else.</summary>
    Only,
}

/// <summary>One ray for trace_multi_ray.</summary>
public class RaySpec
{
    /// <summary>Ray start as 'x,y,z'.</summary>
    public Vector3 From { get; set; }

    /// <summary>Ray end as 'x,y,z'.</summary>
    public Vector3 To { get; set; }
}

[McpToolset( "trace", "Physics traces with filters - rays, sphere and box casts, ray batches and height grids for placement" )]
public static class TraceTools
{
    const int MaxRays = 256;
    const int MaxGridPoints = 1024;

    /// <summary>
    /// Trace a ray through the open scene's physics and report the first thing it hits, with tag,
    /// object and trigger filters. Works in the editor without play mode. On a miss only Hit and
    /// Position (the ray's end) are returned.
    /// </summary>
    /// <param name="from">Ray start as 'x,y,z'.</param>
    /// <param name="to">Ray end as 'x,y,z'.</param>
    /// <param name="withAnyTags">Only hit objects carrying at least one of these tags.</param>
    /// <param name="withoutTags">Never hit objects carrying any of these tags.</param>
    /// <param name="ignoreId">Game object id whose whole hierarchy the trace passes through, e.g. the object being placed.</param>
    /// <param name="triggers">Ignore (default), Include or Only trigger colliders.</param>
    [McpTool.ReadOnly( "trace_ray" )]
    public static object Ray( Vector3 from, Vector3 to, string[] withAnyTags = null, string[] withoutTags = null,
        string ignoreId = "", TriggerMode triggers = TriggerMode.Ignore )
    {
        RequireVector( "from", from );
        RequireVector( "to", to );

        var t = Filtered( ReadScene().Trace.Ray( from, to ), withAnyTags, withoutTags, ignoreId, triggers );
        return Result( t.Run(), from );
    }

    /// <summary>
    /// Sweep a sphere from one point to another and report the first thing it touches - checks whether
    /// something of that size fits along a path. Position is the sphere's centre where it stopped.
    /// Filters as trace_ray.
    /// </summary>
    /// <param name="from">Sweep start (sphere centre) as 'x,y,z'.</param>
    /// <param name="to">Sweep end as 'x,y,z'.</param>
    /// <param name="radius">Sphere radius in units, above 0.</param>
    /// <param name="withAnyTags">Only hit objects carrying at least one of these tags.</param>
    /// <param name="withoutTags">Never hit objects carrying any of these tags.</param>
    /// <param name="ignoreId">Game object id whose whole hierarchy the trace passes through.</param>
    /// <param name="triggers">Ignore (default), Include or Only trigger colliders.</param>
    [McpTool.ReadOnly( "trace_sphere_cast" )]
    public static object SphereCast( Vector3 from, Vector3 to, float radius, string[] withAnyTags = null, string[] withoutTags = null,
        string ignoreId = "", TriggerMode triggers = TriggerMode.Ignore )
    {
        RequireVector( "from", from );
        RequireVector( "to", to );
        RequireFinite( "radius", radius );
        if ( radius <= 0 ) throw new Exception( "radius must be above 0 - use trace_ray for a zero-width trace" );

        var t = Filtered( ReadScene().Trace.Sphere( radius, from, to ), withAnyTags, withoutTags, ignoreId, triggers );
        return Result( t.Run(), from );
    }

    /// <summary>
    /// Sweep a box from one point to another and report the first thing it touches - checks whether a
    /// footprint fits before placing something. Position is the box's centre where it stopped. Filters
    /// as trace_ray.
    /// </summary>
    /// <param name="from">Sweep start (box centre) as 'x,y,z'.</param>
    /// <param name="to">Sweep end as 'x,y,z'.</param>
    /// <param name="size">Full box size, corner to corner, as 'x,y,z'; each above 0.</param>
    /// <param name="rotation">Box rotation as 'pitch,yaw,roll'. Default axis-aligned.</param>
    /// <param name="withAnyTags">Only hit objects carrying at least one of these tags.</param>
    /// <param name="withoutTags">Never hit objects carrying any of these tags.</param>
    /// <param name="ignoreId">Game object id whose whole hierarchy the trace passes through.</param>
    /// <param name="triggers">Ignore (default), Include or Only trigger colliders.</param>
    [McpTool.ReadOnly( "trace_box_cast" )]
    public static object BoxCast( Vector3 from, Vector3 to, Vector3 size, Angles? rotation = null, string[] withAnyTags = null,
        string[] withoutTags = null, string ignoreId = "", TriggerMode triggers = TriggerMode.Ignore )
    {
        RequireVector( "from", from );
        RequireVector( "to", to );
        RequirePositive( "size", size );

        var t = ReadScene().Trace.Ray( from, to ).Size( size );
        if ( rotation is { } r )
        {
            RequireFinite( "rotation", r.pitch, r.yaw, r.roll );
            t = t.Rotated( r.ToRotation() );
        }

        return Result( Filtered( t, withAnyTags, withoutTags, ignoreId, triggers ).Run(), from );
    }

    /// <summary>
    /// Trace up to 256 rays with the same filters in one call; Results keep the input order. Each result
    /// is shaped as trace_ray's.
    /// </summary>
    /// <param name="rays">The rays, each an object with From and To as 'x,y,z'.</param>
    /// <param name="withAnyTags">Only hit objects carrying at least one of these tags.</param>
    /// <param name="withoutTags">Never hit objects carrying any of these tags.</param>
    /// <param name="ignoreId">Game object id whose whole hierarchy every ray passes through.</param>
    /// <param name="triggers">Ignore (default), Include or Only trigger colliders.</param>
    [McpTool.ReadOnly( "trace_multi_ray" )]
    public static object MultiRay( RaySpec[] rays, string[] withAnyTags = null, string[] withoutTags = null,
        string ignoreId = "", TriggerMode triggers = TriggerMode.Ignore )
    {
        if ( rays is null || rays.Length == 0 || rays.Length > MaxRays )
            throw new Exception( $"Give between 1 and {MaxRays} rays - split a larger batch into several calls" );

        var scene = ReadScene();
        var results = new List<object>( rays.Length );

        for ( var i = 0; i < rays.Length; i++ )
        {
            if ( rays[i] is null ) throw new Exception( $"Ray {i} is empty - each ray needs From and To" );
            RequireVector( $"rays[{i}].From", rays[i].From );
            RequireVector( $"rays[{i}].To", rays[i].To );

            var t = Filtered( scene.Trace.Ray( rays[i].From, rays[i].To ), withAnyTags, withoutTags, ignoreId, triggers );
            results.Add( Result( t.Run(), rays[i].From ) );
        }

        return new { Count = results.Count, Results = results };
    }

    /// <summary>
    /// Sample ground height on an evenly spaced grid by tracing straight down - for finding flat spots
    /// to place things or reading the shape of the ground. Grid points run edge to edge across size.
    /// Heights and Slopes are row-major (rows along y, columns along x); null marks a miss. Slope is the
    /// angle in degrees between the surface normal and straight up. Filters as trace_ray.
    /// </summary>
    /// <param name="center">Grid centre as 'x,y,z'; rays run from z + height down to z - height.</param>
    /// <param name="size">Grid extent as 'x,y' in units; each above 0.</param>
    /// <param name="columns">Points along x, 2 to 64.</param>
    /// <param name="rows">Points along y, 2 to 64. columns times rows is at most 1024.</param>
    /// <param name="height">How far above and below center.z each ray reaches, above 0.</param>
    /// <param name="withAnyTags">Only hit objects carrying at least one of these tags.</param>
    /// <param name="withoutTags">Never hit objects carrying any of these tags.</param>
    /// <param name="ignoreId">Game object id whose whole hierarchy the rays pass through.</param>
    /// <param name="triggers">Ignore (default), Include or Only trigger colliders.</param>
    [McpTool.ReadOnly( "trace_sample_grid" )]
    public static object SampleGrid( Vector3 center, Vector2 size, int columns = 16, int rows = 16, float height = 10000f,
        string[] withAnyTags = null, string[] withoutTags = null, string ignoreId = "", TriggerMode triggers = TriggerMode.Ignore )
    {
        RequireVector( "center", center );
        RequireFinite( "size", size.x, size.y );
        RequireFinite( "height", height );
        if ( size.x <= 0 || size.y <= 0 ) throw new Exception( "Both size components must be above 0" );
        if ( height <= 0 ) throw new Exception( "height must be above 0" );
        if ( columns < 2 || columns > 64 || rows < 2 || rows > 64 )
            throw new Exception( "columns and rows must each be 2 to 64" );
        if ( columns * rows > MaxGridPoints )
            throw new Exception( $"columns times rows is {columns * rows}, over the {MaxGridPoints} limit - lower one, or sample in tiles" );

        var scene = ReadScene();
        var heights = new float?[columns * rows];
        var slopes = new float?[columns * rows];
        var corner = new Vector3( center.x - size.x / 2, center.y - size.y / 2, center.z );

        for ( var row = 0; row < rows; row++ )
        {
            for ( var col = 0; col < columns; col++ )
            {
                var x = corner.x + size.x * col / (columns - 1);
                var y = corner.y + size.y * row / (rows - 1);
                var from = new Vector3( x, y, center.z + height );
                var to = new Vector3( x, y, center.z - height );

                var r = Filtered( scene.Trace.Ray( from, to ), withAnyTags, withoutTags, ignoreId, triggers ).Run();
                if ( !r.Hit ) continue;

                heights[row * columns + col] = r.EndPosition.z;
                slopes[row * columns + col] = Vector3.GetAngle( r.Normal, Vector3.Up );
            }
        }

        var hits = heights.Where( h => h.HasValue ).Select( h => h.Value ).ToList();

        return new
        {
            Columns = columns,
            Rows = rows,
            Misses = heights.Length - hits.Count,
            MinZ = hits.Count > 0 ? hits.Min() : (float?)null,
            MaxZ = hits.Count > 0 ? hits.Max() : (float?)null,
            Heights = heights,
            Slopes = slopes,
        };
    }

    static SceneTrace Filtered( SceneTrace t, string[] withAnyTags, string[] withoutTags, string ignoreId, TriggerMode triggers )
    {
        if ( withAnyTags is { Length: > 0 } ) t = t.WithAnyTags( withAnyTags );
        if ( withoutTags is { Length: > 0 } ) t = t.WithoutTags( withoutTags );
        if ( !string.IsNullOrWhiteSpace( ignoreId ) ) t = t.IgnoreGameObjectHierarchy( FindByGuid( ignoreId ) );

        return triggers switch
        {
            TriggerMode.Include => t.HitTriggers(),
            TriggerMode.Only => t.HitTriggersOnly(),
            _ => t,
        };
    }

    static object Result( SceneTraceResult r, Vector3 from )
    {
        if ( !r.Hit ) return new { Hit = false, Position = r.EndPosition };

        return new
        {
            Hit = true,
            Position = r.EndPosition,
            r.Normal,
            Distance = from.Distance( r.EndPosition ),
            GameObjectId = r.GameObject?.Id,
            Name = r.GameObject?.Name,
            Tags = r.GameObject?.Tags.TryGetAll( true ).ToArray(),
            Surface = r.Surface?.ResourceName,
            r.StartedSolid,
        };
    }

    static void RequireVector( string name, Vector3 v ) => RequireFinite( name, v.x, v.y, v.z );
}