Editor/TerrainTools.cs

Editor MCP toolset named "terrain" that gives an AI tool access to s&box heightmap terrain. Creates Terrain objects with embedded TerrainStorage, reads info/heights/height regions, sculpts with set/raise/lower/flatten/smooth brushes and falloff, imports and exports heightmaps as .r16/.raw/.png or images through project files, all inside the editor's undo scopes.

File Access
using System;
using System.IO;
using System.Linq;
using Editor;
using Editor.Mcp;
using Sandbox;
using static LevelTools.McpHelpers;
using static LevelTools.TerrainEdit;

namespace LevelTools;

[McpToolset( "terrain", "Heightmap terrain - create terrains, read and sculpt heights, generate noise, erosion and stamps, import and export heightmaps, manage and paint terrain materials and holes, and regenerate clutter" )]
public static class TerrainTools
{
    public enum HeightMode { Set, Raise, Lower, Flatten, Smooth }

    public enum Falloff { Linear, Smooth, None }

    /// <summary>
    /// Create a game object with a flat Terrain whose data is embedded in the scene, as adding a Terrain
    /// in the editor does. Size and maximum height can be changed later with set_component (TerrainSize,
    /// TerrainHeight). The user can undo this. Returns the new object's id - shape it with
    /// terrain_set_height, terrain_noise or terrain_stamp, and give it materials with terrain_add_material.
    /// </summary>
    /// <param name="name">Name for the new object.</param>
    /// <param name="position">World position of the terrain's corner as 'x,y,z'. The terrain extends along +X and +Y from it.</param>
    /// <param name="size">Width and length in units.</param>
    /// <param name="height">Maximum height in units. Heights are stored as fractions of it.</param>
    /// <param name="resolution">Heightmap texels per side: 256, 512, 1024, 2048, 4096 or 8192.</param>
    [McpTool( "terrain_create" )]
    public static object Create( string name = "Terrain", Vector3? position = null, float size = 1024f, float height = 512f, int resolution = 512 )
    {
        if ( resolution < 256 || resolution > 8192 || !System.Numerics.BitOperations.IsPow2( resolution ) )
            throw new Exception( $"Resolution {resolution} isn't one the terrain editor offers - use 256, 512, 1024, 2048, 4096 or 8192" );

        var p = position ?? Vector3.Zero;
        RequireFinite( "position, size and height", p.x, p.y, p.z, size, height );
        if ( size <= 0 || height <= 0 )
            throw new Exception( "Size and height must both be above zero" );

        var session = ActiveSession();

        using var sceneScope = session.Scene.Push();
        using var undoScope = session.UndoScope( "Create Terrain" ).WithGameObjectCreations().Push();

        var go = session.Scene.CreateObject();
        go.Name = name;
        go.WorldPosition = p;

        var storage = new TerrainStorage { TerrainSize = size, TerrainHeight = height };
        storage.SetResolution( resolution );

        // Without this a storage made in code saves as a null reference and the terrain is empty on reload - the inspector does the same
        storage.EmbeddedResource = new Sandbox.Resources.EmbeddedResource { ResourceCompiler = "embed" };

        var terrain = go.Components.Create<Terrain>( false );
        terrain.Storage = storage;
        terrain.Enabled = true;

        return new { Id = go.Id, ComponentId = terrain.Id, Name = go.Name, Position = go.WorldPosition, Size = size, Height = height, Resolution = resolution };
    }

    /// <summary>
    /// A terrain's size, maximum height, resolution, clipmap settings, the range of heights it holds, and
    /// its materials with the index each one paints with.
    /// </summary>
    /// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
    [McpTool.ReadOnly( "terrain_get_info" )]
    public static object GetInfo( string id = "" )
    {
        var terrain = ForRead( id );
        var storage = terrain.Storage;
        var heights = storage.HeightMap;

        return new
        {
            Id = terrain.GameObject.Id,
            ComponentId = terrain.Id,
            Name = terrain.GameObject.Name,
            Enabled = terrain.Active,
            Position = terrain.WorldPosition,
            Size = storage.TerrainSize,
            MaxHeight = storage.TerrainHeight,
            storage.Resolution,
            Storage = storage.EmbeddedResource is not null ? "embedded in the scene" : storage.ResourcePath,
            terrain.ClipMapLodLevels,
            terrain.SubdivisionFactor,
            LowestHeight = MathF.Round( HeightOf( terrain, heights.Min() ), 2 ),
            HighestHeight = MathF.Round( HeightOf( terrain, heights.Max() ), 2 ),
            Materials = storage.Materials.Select( ( m, i ) => new { Index = i, Name = m?.ResourceName, Path = m?.ResourcePath } ).ToArray()
        };
    }

    /// <summary>
    /// The terrain height at a world position, from the heightmap texel under it. Height is above the
    /// terrain's own base; SurfaceZ is the world Z of the surface there.
    /// </summary>
    /// <param name="position">World position as 'x,y,z'. Only x and y matter.</param>
    /// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
    [McpTool.ReadOnly( "terrain_get_height" )]
    public static object GetHeight( Vector3 position, string id = "" )
    {
        var terrain = ForRead( id );
        var texel = RequireTexel( terrain, position );
        var height = HeightOf( terrain, terrain.Storage.HeightMap[texel.y * terrain.Storage.Resolution + texel.x] );

        var local = terrain.WorldTransform.PointToLocal( position );
        var surface = terrain.WorldTransform.PointToWorld( new Vector3( local.x, local.y, height ) );

        return new { Id = terrain.GameObject.Id, Height = MathF.Round( height, 3 ), SurfaceZ = MathF.Round( surface.z, 3 ), Texel = texel, MaxHeight = terrain.Storage.TerrainHeight };
    }

    /// <summary>
    /// Sample a square grid of terrain heights centred on a position, with the lowest, highest and average.
    /// Heights[row][column]: rows run from -Y to +Y, columns from -X to +X. Samples off the terrain are null.
    /// </summary>
    /// <param name="position">Centre of the square as 'x,y,z'.</param>
    /// <param name="regionSize">Side length of the square in units.</param>
    /// <param name="samples">Samples per side, 2 to 64.</param>
    /// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
    [McpTool.ReadOnly( "terrain_get_height_region" )]
    public static object GetHeightRegion( Vector3 position, float regionSize = 100f, [Sandbox.Range( 2, 64 )] int samples = 10, string id = "" )
    {
        var terrain = ForRead( id );
        var step = regionSize / (samples - 1);
        var start = position - new Vector3( regionSize / 2, regionSize / 2, 0 );

        var heights = new float?[samples][];
        for ( var row = 0; row < samples; row++ )
        {
            heights[row] = new float?[samples];
            for ( var column = 0; column < samples; column++ )
            {
                if ( TexelAt( terrain, start + new Vector3( column * step, row * step, 0 ) ) is { } t )
                    heights[row][column] = MathF.Round( HeightOf( terrain, terrain.Storage.HeightMap[t.y * terrain.Storage.Resolution + t.x] ), 2 );
            }
        }

        var found = heights.SelectMany( x => x ).Where( x => x.HasValue ).Select( x => x.Value ).ToArray();
        if ( found.Length == 0 )
            throw new Exception( $"No sample of that square falls on the terrain '{terrain.GameObject.Name}' - terrain_get_info shows its position and size" );

        return new { Id = terrain.GameObject.Id, Lowest = found.Min(), Highest = found.Max(), Average = MathF.Round( found.Average(), 2 ), Heights = heights };
    }

    /// <summary>
    /// Sculpt a circle of the heightmap. Set moves heights toward height, Raise and Lower add or subtract
    /// it, Flatten moves them toward the height under the centre and Smooth toward their neighbours'
    /// average. Strength and falloff scale the change toward the rim. The user can undo this. Check the
    /// result with terrain_get_height.
    /// </summary>
    /// <param name="position">Brush centre as 'x,y,z'.</param>
    /// <param name="mode">How heights change.</param>
    /// <param name="height">Target height above the terrain base for Set; the amount for Raise and Lower. Unused by Flatten and Smooth.</param>
    /// <param name="radius">Brush radius in units.</param>
    /// <param name="strength">0 to 1, how far each texel moves toward its target at the centre.</param>
    /// <param name="falloff">How strength fades to the rim.</param>
    /// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
    [McpTool( "terrain_set_height" )]
    public static object SetHeight( Vector3 position, HeightMode mode = HeightMode.Set, float height = 0f, float radius = 50f,
        [Sandbox.Range( 0, 1 )] float strength = 1f, Falloff falloff = Falloff.Linear, string id = "" )
    {
        RequireFinite( "height and strength", height, strength );
        var (terrain, session) = ForEdit( id );
        var map = terrain.Storage.HeightMap;
        var res = terrain.Storage.Resolution;
        var brush = BrushAt( terrain, position, radius );

        var centreHeight = 0f;
        if ( mode == HeightMode.Flatten )
        {
            var centre = RequireTexel( terrain, position );
            centreHeight = HeightOf( terrain, map[centre.y * res + centre.x] );
        }

        // Smooth reads the untouched heights, so the result doesn't depend on the order texels are visited
        var source = mode == HeightMode.Smooth ? (ushort[])map.Clone() : map;

        var changed = 0;
        CommitHeights( session, terrain, $"Terrain {mode}", brush.Region, () => changed = brush.ForEach( ( i, _, _, t ) =>
        {
            var weight = strength * falloff switch
            {
                Falloff.Smooth => 1f - t * t * (3f - 2f * t),
                Falloff.None => 1f,
                _ => 1f - t
            };

            var current = HeightOf( terrain, map[i] );
            var target = mode switch
            {
                HeightMode.Raise => current + height * weight,
                HeightMode.Lower => current - height * weight,
                HeightMode.Flatten => current + (centreHeight - current) * weight,
                HeightMode.Smooth => current + (HeightOf( terrain, Average( source, res, i, 6 ) ) - current) * weight,
                _ => current + (height - current) * weight
            };

            map[i] = RawOf( terrain, target );
        } ) );

        return new { Id = terrain.GameObject.Id, Mode = mode.ToString(), TexelsChanged = changed };
    }

    /// <summary>
    /// Replace the whole heightmap from a file in the project. A .r16 or .raw file is read as 16-bit
    /// little-endian heights, as the editor's own Import Heightmap reads it. A .r8 file is read as 8-bit
    /// heights scaled to the full height range - the editor's importer keeps the raw byte instead, so the
    /// same .r8 gives a terrain 257 times taller here. Raw files must be square and match the terrain's
    /// resolution. Any other file is read as an image, resized to the resolution, with brightness as
    /// height. The user can undo this.
    /// </summary>
    /// <param name="path">File path relative to the project folder, e.g. 'heightmaps/island.png'.</param>
    /// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
    [McpTool( "terrain_import_heightmap" )]
    public static object ImportHeightmap( string path, string id = "" )
    {
        var (terrain, session) = ForEdit( id );
        var file = ProjectPath( path );

        if ( !File.Exists( file ) )
            throw new Exception( $"No file at '{path}' in the project" );

        var res = terrain.Storage.Resolution;
        var heights = Path.GetExtension( file ).ToLowerInvariant() switch
        {
            ".r16" or ".raw" => ReadRaw( file, res, 2 ),
            ".r8" => ReadRaw( file, res, 1 ),
            _ => ReadImage( file, res )
        };

        CommitHeights( session, terrain, "Import Heightmap", Whole( terrain ), () => heights.CopyTo( terrain.Storage.HeightMap, 0 ) );

        return new { Id = terrain.GameObject.Id, Imported = path, Resolution = res, LowestHeight = HeightOf( terrain, heights.Min() ), HighestHeight = HeightOf( terrain, heights.Max() ) };
    }

    /// <summary>
    /// Write the heightmap to a file in the project, replacing any file already there - this cannot be
    /// undone. A .r16 or .raw path writes exact 16-bit little-endian heights that terrain_import_heightmap
    /// and the editor's Import Heightmap read back; a .png path writes an 8-bit grayscale image, which
    /// loses precision. Other extensions are refused. Changes no scene state.
    /// </summary>
    /// <param name="path">File path relative to the project folder ending in .r16, .raw or .png, e.g. 'heightmaps/island.r16'.</param>
    /// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
    [McpTool( "terrain_export_heightmap" )]
    public static object ExportHeightmap( string path, string id = "" )
    {
        var terrain = ForRead( id );
        var file = ProjectPath( path );
        var heights = terrain.Storage.HeightMap;
        var res = terrain.Storage.Resolution;
        var extension = Path.GetExtension( file ).ToLowerInvariant();

        // The write replaces the file outright, so only paths that are heightmaps by name may be overwritten
        if ( extension is not (".r16" or ".raw" or ".png") )
            throw new Exception( $"'{path}' isn't a heightmap path - end it in .r16 or .raw for exact 16-bit heights, or .png for an 8-bit image" );

        byte[] bytes;

        if ( extension is ".r16" or ".raw" )
        {
            bytes = new byte[heights.Length * 2];
            Buffer.BlockCopy( heights, 0, bytes, 0, bytes.Length );
        }
        else
        {
            using var bitmap = new Bitmap( res, res );
            bitmap.SetPixels( heights.Select( h => new Color( h / (float)ushort.MaxValue, h / (float)ushort.MaxValue, h / (float)ushort.MaxValue ) ).ToArray() );
            bytes = bitmap.ToPng();
        }

        var replaced = File.Exists( file );
        Directory.CreateDirectory( Path.GetDirectoryName( file ) );
        File.WriteAllBytes( file, bytes );

        return new { Id = terrain.GameObject.Id, Written = file, Replaced = replaced, Bytes = bytes.Length, Resolution = res, Format = extension is ".r16" or ".raw" ? "r16" : "png8" };
    }

    static ushort Average( ushort[] map, int res, int index, int kernel )
    {
        int cx = index % res, cy = index / res, sum = 0, count = 0;

        for ( var y = Math.Max( 0, cy - kernel ); y <= Math.Min( res - 1, cy + kernel ); y++ )
        {
            for ( var x = Math.Max( 0, cx - kernel ); x <= Math.Min( res - 1, cx + kernel ); x++ )
            {
                sum += map[y * res + x];
                count++;
            }
        }

        return (ushort)((sum + count / 2) / count);
    }

    static ushort[] ReadRaw( string file, int res, int bytesPerTexel )
    {
        var bytes = File.ReadAllBytes( file );

        if ( bytes.Length != res * res * bytesPerTexel )
            throw new Exception( $"That file holds {bytes.Length} bytes, but a {res}x{res} terrain needs {res * res * bytesPerTexel} at {bytesPerTexel * 8} bits - export or resample it at the terrain's resolution" );

        var heights = new ushort[res * res];

        if ( bytesPerTexel == 2 )
            Buffer.BlockCopy( bytes, 0, heights, 0, bytes.Length );
        else
            for ( var i = 0; i < heights.Length; i++ ) heights[i] = (ushort)(bytes[i] * 257);

        return heights;
    }

    static ushort[] ReadImage( string file, int res )
    {
        using var loaded = Bitmap.CreateFromBytes( File.ReadAllBytes( file ) );

        if ( loaded is null || !loaded.IsValid )
            throw new Exception( $"'{Path.GetFileName( file )}' isn't an image the engine can read - use PNG, TGA or JPG, or a .r16 raw heightmap" );

        using var sized = loaded.Width == res && loaded.Height == res ? null : loaded.Resize( res, res );

        return (sized ?? loaded).GetPixels()
            .Select( p => (ushort)(Math.Clamp( p.r * 0.299f + p.g * 0.587f + p.b * 0.114f, 0f, 1f ) * ushort.MaxValue) )
            .ToArray();
    }
}