Editor/MeshFaceTools.cs

Editor MCP toolset exposing mesh face editing tools: extrude, remove, add, clip, thicken, quad slice, flip and scale. Each tool calls the polygon mesh API inside the editor's undo transaction and returns face indices and mesh counts.

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

namespace LevelTools;

[McpToolset( "mesh" )]
public static class MeshFaceTools
{
    /// <summary>
    /// Extrude faces: move them out and join them to where they were with new side faces. By default
    /// they move along their average normal by distance; offset moves them by an exact local vector
    /// instead. The user can undo this. Returns the moved and the new side faces' indices.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="faces">Face indices from mesh_get_info.</param>
    /// <param name="distance">How far to move the faces along their average normal. Negative pushes them in.</param>
    /// <param name="offset">Exact offset as 'x,y,z' in the object's local space. Overrides distance.</param>
    [McpTool( "mesh_extrude_faces" )]
    public static object ExtrudeFaces( string id, int[] faces, float distance = 50f, Vector3? offset = null )
    {
        var (component, session) = ForEdit( id );
        var handles = Faces( component.Mesh, faces );

        RequireFinite( "distance", distance );
        if ( offset is { } o )
            RequireFinite( "offset", o.x, o.y, o.z );

        var move = offset ?? AverageNormal( component.Mesh, handles ) * distance;
        if ( move.IsNearlyZero() )
            throw new Exception( "That extrusion moves the faces nowhere - give a non-zero distance, or an offset when the faces' normals cancel out" );

        var (moved, sides) = Edit( session, component, "Extrude Faces", mesh =>
        {
            mesh.ExtrudeFaces( handles, out var newFaces, out var connecting, move );
            return (newFaces, connecting);
        } );

        return new { Id = component.GameObject.Id, Offset = move, Faces = Indices( moved ), SideFaces = Indices( sides ), Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Delete faces, leaving a hole with open edges. Vertices no face uses any more go too. The user can
    /// undo this. Indices of other faces can change - call mesh_get_info again before the next edit.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="faces">Face indices from mesh_get_info.</param>
    [McpTool( "mesh_remove_faces" )]
    public static object RemoveFaces( string id, int[] faces )
    {
        var (component, session) = ForEdit( id );
        var handles = Faces( component.Mesh, faces );

        Edit( session, component, "Remove Faces", mesh =>
        {
            mesh.RemoveFaces( handles );
            return 0;
        } );

        return new { Id = component.GameObject.Id, Removed = handles.Length, Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Add a face through existing vertices, e.g. to fill a hole left by mesh_remove_faces. List the
    /// vertices counter-clockwise as seen from the side the face should face. The user can undo this.
    /// Returns the new face's index.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="vertices">Three or more vertex indices from mesh_get_info, in winding order.</param>
    /// <param name="material">Material asset path for the face. Empty uses the material of a face it borders, or leaves it with none if it borders no face.</param>
    [McpTool( "mesh_add_face" )]
    public static object AddFace( string id, int[] vertices, string material = "" )
    {
        var (component, session) = ForEdit( id );
        var handles = Vertices( component.Mesh, vertices );

        if ( handles.Length < vertices.Length )
            throw new Exception( "A vertex appears twice - list each corner of the face once" );

        if ( handles.Length < 3 )
            throw new Exception( "A face needs at least three vertices" );

        var mat = string.IsNullOrWhiteSpace( material ) ? null : LoadMaterial( material );

        var face = Edit( session, component, "Add Face", mesh =>
        {
            var added = mesh.AddFace( handles );
            if ( !added.IsValid ) return added;

            // The engine leaves a new face with no material; a filled hole should match the faces around it
            var paint = mat ?? (mesh.GetFacesConnectedToFace( added, out var around ) ? around.Select( mesh.GetFaceMaterial ).FirstOrDefault( m => m is not null ) : null);
            if ( paint is not null ) mesh.AssignMaterialToFaces( [added], paint );

            // AddFace leaves the texture axes zero, so every corner would share one UV; the engine's hole fill aligns too
            mesh.TextureAlignToGrid( mesh.Transform, added );
            return added;
        }, added => added.IsValid );

        if ( !face.IsValid )
            throw new Exception( "Those vertices can't make a face - each edge can only border one face per side, so try the opposite winding or vertices around an open hole (Open edges in mesh_get_info)" );

        return new { Id = component.GameObject.Id, Face = face.Index, Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Cut faces along a plane in the object's local space, splitting every face it crosses. Faces on the
    /// side the normal points away from are removed unless keepBoth is set, and the cut can be capped to
    /// close the mesh. The user can undo this. Returns the cap faces' indices.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="point">A point on the plane as 'x,y,z', local space.</param>
    /// <param name="normal">The plane's normal as 'x,y,z'. Faces in front of it are kept.</param>
    /// <param name="faces">Face indices to cut. Empty cuts the whole mesh.</param>
    /// <param name="keepBoth">Split faces along the plane but remove nothing.</param>
    /// <param name="cap">Close the cut with new faces where possible.</param>
    [McpTool( "mesh_clip_faces" )]
    public static object ClipFaces( string id, Vector3 point, Vector3 normal, int[] faces = null, bool keepBoth = false, bool cap = true )
    {
        var (component, session) = ForEdit( id );
        var handles = FacesOrAll( component.Mesh, faces );

        RequireFinite( "point and normal", point.x, point.y, point.z, normal.x, normal.y, normal.z );
        if ( normal.IsNearlyZero() )
            throw new Exception( "The plane normal can't be zero" );

        var capFaces = new List<FaceHandle>();
        var newEdges = new List<HalfEdgeHandle>();
        Edit( session, component, "Clip Faces", mesh =>
        {
            mesh.ClipFacesByPlaneAndCap( handles, new Plane( point, normal.Normal ), !keepBoth, cap, newEdges, capFaces );
            return 0;
        } );

        return new { Id = component.GameObject.Id, NewEdges = newEdges.Count, CapFaces = Indices( capFaces ), Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Give faces thickness: copies them amount units back along their normals and joins the copy to the
    /// original with side faces - a plane becomes a slab. Every edge on the outline of the faces must be
    /// open, as on a plane or around a hole. The user can undo this. Returns the thickened faces' indices,
    /// which are the ones given.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="faces">Face indices from mesh_get_info.</param>
    /// <param name="amount">Thickness in units. Negative thickens toward the front.</param>
    [McpTool( "mesh_thicken_faces" )]
    public static object ThickenFaces( string id, int[] faces, float amount )
    {
        var (component, session) = ForEdit( id );
        var handles = Faces( component.Mesh, faces );

        RequireFinite( "amount", amount );
        if ( amount == 0 )
            throw new Exception( "Give a non-zero amount" );

        // The engine skips any face island with a closed edge on its outline, and refuses when that leaves none
        component.Mesh.FindBoundaryEdgesConnectedToFaces( handles, out var boundary );
        var closed = boundary.Where( e => !component.Mesh.IsEdgeOpen( e ) ).Select( e => FullEdge( component.Mesh, e ).Index ).FirstOrDefault( -1 );
        if ( boundary.Count == 0 || closed >= 0 )
            throw new Exception( $"Only faces whose outline is all open edges can be thickened, like a plane or a shell with a hole - {(closed >= 0 ? $"edge {closed} borders another face" : "those faces have no outline")}; mesh_get_info marks open edges" );

        var (ok, added) = Edit( session, component, "Thicken Faces", mesh =>
        {
            var thickened = mesh.ThickenFaces( handles, amount, out var outFaces );
            mesh.ComputeFaceTextureCoordinatesFromParameters();
            return (thickened, outFaces);
        }, r => r.Item1 );
        if ( !ok )
            throw Refused( "thicken those faces" );

        return new { Id = component.GameObject.Id, Faces = Indices( added ), Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Slice faces into a grid of cutsX by cutsY extra cuts, measured along each face's own corners. Works
    /// best on four-cornered faces. The user can undo this. Returns the resulting faces' indices.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="faces">Face indices from mesh_get_info.</param>
    /// <param name="cutsX">Cuts across the first direction, 0 to 64.</param>
    /// <param name="cutsY">Cuts across the second direction, 0 to 64.</param>
    [McpTool( "mesh_quad_slice_faces" )]
    public static object QuadSliceFaces( string id, int[] faces, [Sandbox.Range( 0, 64 )] int cutsX = 1, [Sandbox.Range( 0, 64 )] int cutsY = 1 )
    {
        var (component, session) = ForEdit( id );
        var handles = Faces( component.Mesh, faces );

        if ( cutsX + cutsY == 0 )
            throw new Exception( "Give at least one cut" );

        var added = new List<FaceHandle>();
        Edit( session, component, "Quad Slice Faces", mesh =>
        {
            // 60 degrees is the corner angle the editor's slice uses to find a face's four corners
            mesh.QuadSliceFaces( handles, cutsX, cutsY, 60f, added );

            // The slice leaves the new faces' UVs unset; the editor's slice recomputes them the same way
            mesh.ComputeFaceTextureCoordinatesFromParameters();
            return 0;
        } );

        return new { Id = component.GameObject.Id, Faces = Indices( added ), Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Turn every face of the mesh inside out, reversing its normals - for a mesh that renders inside out
    /// or that should be seen from inside, like a room. The user can undo this.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    [McpTool( "mesh_flip_faces" )]
    public static object FlipFaces( string id )
    {
        var (component, session) = ForEdit( id );

        Edit( session, component, "Flip Faces", mesh =>
        {
            mesh.FlipAllFaces();
            return 0;
        } );

        return new { Id = component.GameObject.Id, Mesh = Counts( component.Mesh ) };
    }

    /// <summary>
    /// Scale the mesh's vertices about the object's origin, changing its geometry rather than the
    /// object's transform (set_game_object does that). The user can undo this. Returns the new local bounds.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="scale">Scale factor per axis as 'x,y,z', e.g. '2,2,1'. A negative factor mirrors the mesh; its faces are flipped to keep facing outward.</param>
    [McpTool( "mesh_scale_mesh" )]
    public static object ScaleMesh( string id, Vector3 scale )
    {
        var (component, session) = ForEdit( id );

        RequireFinite( "scale", scale.x, scale.y, scale.z );
        if ( scale.x == 0 || scale.y == 0 || scale.z == 0 )
            throw new Exception( "A zero scale would flatten the mesh - give every axis a non-zero factor" );

        Edit( session, component, "Scale Mesh", mesh =>
        {
            mesh.Scale( scale );

            // The texture stretches with the mesh, as the editor's scale bake does
            mesh.ComputeFaceTextureParametersFromCoordinates();

            // An odd number of negative axes mirrors the mesh and reverses its winding, as the editor's mirror tool corrects for
            if ( (scale.x < 0) ^ (scale.y < 0) ^ (scale.z < 0) )
                mesh.FlipAllFaces();

            return 0;
        } );

        var bounds = component.Mesh.CalculateBounds();
        return new { Id = component.GameObject.Id, Bounds = new { bounds.Mins, bounds.Maxs } };
    }

    static Vector3 AverageNormal( PolygonMesh mesh, FaceHandle[] faces )
    {
        var sum = Vector3.Zero;
        foreach ( var face in faces )
        {
            mesh.ComputeFaceNormal( face, out var normal );
            sum += normal;
        }

        return sum.Normal;
    }
}