Editor/MeshSurfaceTools.cs

Editor-side MCP toolset that exposes mesh surface editing to an AI client: assign materials to faces, change per-face texture projection axes/offset/scale, and paint vertex colours and blend weights. All edits run through the mesh edit session so they are undoable.

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

namespace LevelTools;

[McpToolset( "mesh" )]
public static class MeshSurfaceTools
{
    /// <summary>
    /// Paint faces with a material, recomputing their texture coordinates as the editor's material tool
    /// does. The user can undo this.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="material">Material asset path, from asset_search type:vmat.</param>
    /// <param name="faces">Face indices from mesh_get_info. Empty paints every face.</param>
    [McpTool( "mesh_set_face_material" )]
    public static object SetFaceMaterial( string id, string material, int[] faces = null )
    {
        var (component, session) = ForEdit( id );
        var handles = FacesOrAll( component.Mesh, faces );
        var mat = LoadMaterial( material );

        Edit( session, component, "Apply Material", mesh =>
        {
            mesh.AssignMaterialToFaces( handles, mat );
            return 0;
        } );

        return new { Id = component.GameObject.Id, Material = mat.ResourcePath, Faces = handles.Length };
    }

    /// <summary>
    /// Change how a texture is projected onto faces: the U and V axes it runs along (world space), its
    /// offset in texels and its scale in units per texel. Only the arguments you give change; each face
    /// keeps the rest of its own. The user can undo this. Returns each face's resulting parameters.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="faces">Face indices from mesh_get_info. Empty changes every face.</param>
    /// <param name="uAxis">Direction the texture's U runs as 'x,y,z', e.g. '1,0,0'.</param>
    /// <param name="vAxis">Direction the texture's V runs as 'x,y,z', e.g. '0,-1,0'.</param>
    /// <param name="offset">Texture offset as 'u,v' in texels.</param>
    /// <param name="scale">Texture scale as 'u,v'. The editor's default is 0.25,0.25.</param>
    [McpTool( "mesh_set_texture_params" )]
    public static object SetTextureParams( string id, int[] faces = null, Vector3? uAxis = null, Vector3? vAxis = null, Vector2? offset = null, Vector2? scale = null )
    {
        var (component, session) = ForEdit( id );
        var handles = FacesOrAll( component.Mesh, faces );

        if ( uAxis is null && vAxis is null && offset is null && scale is null )
            throw new Exception( "Give at least one of uAxis, vAxis, offset or scale" );

        Vector3 ua = uAxis ?? default, va = vAxis ?? default;
        Vector2 of = offset ?? default, sc = scale ?? default;
        RequireFinite( "uAxis, vAxis, offset and scale", ua.x, ua.y, ua.z, va.x, va.y, va.z, of.x, of.y, sc.x, sc.y );
        if ( uAxis is { } u && u.IsNearlyZero() || vAxis is { } v && v.IsNearlyZero() || scale is { } s && (s.x == 0 || s.y == 0) )
            throw new Exception( "Axes and scale can't be zero" );

        Edit( session, component, "Set Texture Parameters", mesh =>
        {
            foreach ( var face in handles )
            {
                mesh.GetFaceTextureParameters( face, out var axisU, out var axisV, out var faceScale );

                // The engine keeps the offset in each axis' w component
                var newU = new Vector4( uAxis ?? (Vector3)axisU, offset?.x ?? axisU.w );
                var newV = new Vector4( vAxis ?? (Vector3)axisV, offset?.y ?? axisV.w );
                mesh.SetFaceTextureParameters( face, newU, newV, scale ?? faceScale );
            }

            return 0;
        } );

        return new
        {
            Id = component.GameObject.Id,
            Faces = handles.Select( face =>
            {
                component.Mesh.GetFaceTextureParameters( face, out var axisU, out var axisV, out var faceScale );
                return new { face.Index, UAxis = (Vector3)axisU, VAxis = (Vector3)axisV, Offset = new Vector2( axisU.w, axisV.w ), Scale = faceScale };
            } ).ToArray()
        };
    }

    /// <summary>
    /// Set the vertex colour of vertices, on every face corner that uses them. It shows only with a material
    /// whose shader uses vertex colour. The user can undo this.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="vertices">Vertex indices from mesh_get_info.</param>
    /// <param name="color">Colour as 'r,g,b,a' (0-1 floats), '#rrggbb' or a name like 'red'.</param>
    [McpTool( "mesh_set_vertex_color" )]
    public static object SetVertexColor( string id, int[] vertices, string color )
    {
        var value = Color.Parse( color ) ?? throw new Exception( $"'{color}' isn't a colour - give 'r,g,b,a' as 0-1 floats, '#rrggbb' or a name" );
        return Paint( id, vertices, "Set Vertex Color", ( mesh, corner ) => mesh.SetVertexColor( corner, value ) );
    }

    /// <summary>
    /// Set the blend weights of vertices, on every face corner that uses them - what the editor's vertex
    /// paint tool writes in Blend mode for materials that blend several layers. The user can undo this.
    /// </summary>
    /// <param name="id">Game object id of the mesh.</param>
    /// <param name="vertices">Vertex indices from mesh_get_info.</param>
    /// <param name="blend">Weights as 'r,g,b,a', each 0 to 1.</param>
    [McpTool( "mesh_set_vertex_blend" )]
    public static object SetVertexBlend( string id, int[] vertices, Vector4 blend )
    {
        RequireFinite( "blend", blend.x, blend.y, blend.z, blend.w );
        if ( new[] { blend.x, blend.y, blend.z, blend.w }.Any( x => x < 0 || x > 1 ) )
            throw new Exception( "Each blend weight must be 0 to 1" );

        return Paint( id, vertices, "Set Vertex Blend", ( mesh, corner ) => mesh.SetVertexBlend( corner, new Color( blend.x, blend.y, blend.z, blend.w ) ) );
    }

    static object Paint( string id, int[] vertices, string undoName, Action<PolygonMesh, HalfEdgeHandle> paint )
    {
        var (component, session) = ForEdit( id );
        var handles = Vertices( component.Mesh, vertices );

        // Colour and blend live on face corners (half-edges), not vertices, so paint every corner a vertex has.
        // The engine's list also holds the face-less half-edges of open boundaries, and is null for a lone vertex.
        var mesh = component.Mesh;
        var corners = handles.Select( v => mesh.GetFaceVerticesConnectedToVertex( v, out var all )
            ? all.Where( c => mesh.GetHalfEdgeFace( c ).IsValid ).ToArray()
            : [] ).ToArray();

        if ( Array.FindIndex( corners, c => c.Length == 0 ) is var lone and >= 0 )
            throw new Exception( $"Vertex {handles[lone].Index} is on no face, so it has no corners to paint" );

        Edit( session, component, undoName, m =>
        {
            foreach ( var corner in corners.SelectMany( c => c ) )
                paint( m, corner );

            return 0;
        } );

        return new { Id = component.GameObject.Id, Vertices = handles.Length, Corners = corners.Sum( c => c.Length ) };
    }
}