Editor MCP toolset that sculpts terrain heightmaps: fractal noise fill, hydraulic erosion, landform stamps, plus ClutterComponent regeneration and clearing.
using System;
using System.Collections.Generic;
using System.Linq;
using Editor;
using Editor.Mcp;
using Sandbox;
using Sandbox.Clutter;
using static LevelTools.McpHelpers;
using static LevelTools.TerrainEdit;
namespace LevelTools;
[McpToolset( "terrain" )]
public static class TerrainSculptTools
{
public enum NoiseType { Perlin, Ridged, Billow }
public enum NoiseMode { Set, Add, Multiply }
public enum StampShape { Hill, Crater, Mesa, Ridge, Valley, Plateau }
public enum StampMode { Add, Subtract, Set }
/// <summary>
/// Fill the whole heightmap with fractal Perlin noise. Set replaces heights with noise times
/// amplitude, Add adds that on top, Multiply scales existing heights by the 0 to 1 noise value.
/// Ridged makes sharp crests, Billow rounded bumps. The same seed and settings give the same result.
/// The user can undo this. Returns the new height range; follow with terrain_erode for realism.
/// </summary>
/// <param name="type">Noise shape.</param>
/// <param name="scale">Noise frequency per heightmap texel. Smaller gives broader features.</param>
/// <param name="amplitude">Height of the noise in units. Default 30% of the terrain's maximum height.</param>
/// <param name="octaves">Detail layers, 1 to 12.</param>
/// <param name="persistence">How much each octave's amplitude shrinks, 0 to 1.</param>
/// <param name="lacunarity">How much each octave's frequency grows.</param>
/// <param name="seed">Random seed.</param>
/// <param name="mode">How noise combines with the existing heights.</param>
/// <param name="offsetX">Noise offset in texels along X, to move the pattern.</param>
/// <param name="offsetY">Noise offset in texels along Y.</param>
/// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
[McpTool( "terrain_noise" )]
public static object Noise( NoiseType type = NoiseType.Perlin, float scale = 0.01f, float? amplitude = null, [Sandbox.Range( 1, 12 )] int octaves = 4,
float persistence = 0.5f, float lacunarity = 2f, int seed = 42, NoiseMode mode = NoiseMode.Set, float offsetX = 0f, float offsetY = 0f, string id = "" )
{
var (terrain, session) = ForEdit( id );
var map = terrain.Storage.HeightMap;
var res = terrain.Storage.Resolution;
var amp = amplitude ?? terrain.Storage.TerrainHeight * 0.3f;
RequireFinite( "scale, amplitude, persistence, lacunarity and offsets", scale, amp, persistence, lacunarity, offsetX, offsetY );
var perm = Permutation( seed );
CommitHeights( session, terrain, "Terrain Noise", Whole( terrain ), () =>
{
for ( var y = 0; y < res; y++ )
{
for ( var x = 0; x < res; x++ )
{
var n = Fbm( (x + offsetX) * scale, (y + offsetY) * scale, octaves, persistence, lacunarity, perm );
if ( type == NoiseType.Ridged ) n = 1f - MathF.Abs( n * 2f - 1f );
else if ( type == NoiseType.Billow ) n = MathF.Abs( n * 2f - 1f );
var i = y * res + x;
var current = HeightOf( terrain, map[i] );
map[i] = RawOf( terrain, mode switch
{
NoiseMode.Add => current + n * amp,
NoiseMode.Multiply => current * n,
_ => n * amp
} );
}
}
} );
return new { Id = terrain.GameObject.Id, Type = type.ToString(), Mode = mode.ToString(), LowestHeight = HeightOf( terrain, map.Min() ), HighestHeight = HeightOf( terrain, map.Max() ) };
}
/// <summary>
/// Hydraulic erosion over the whole heightmap: simulated water droplets carve channels and deposit
/// sediment downhill (Hans Theobald Beyer's particle method). Runs on the editor thread - 50000
/// droplets on a 512 terrain takes about a second. The user can undo this.
/// </summary>
/// <param name="iterations">Number of droplets, up to 1000000.</param>
/// <param name="erosionRate">How fast droplets pick up sediment, 0 to 1.</param>
/// <param name="depositionRate">How fast they drop excess sediment, 0 to 1.</param>
/// <param name="evaporationRate">Water lost per step, 0 to 1.</param>
/// <param name="gravity">Downhill acceleration.</param>
/// <param name="inertia">How much a droplet keeps its direction, 0 to 1.</param>
/// <param name="capacity">Sediment a droplet can carry, relative to its speed, water and slope.</param>
/// <param name="minCapacity">Least sediment capacity, so droplets on flat ground still erode.</param>
/// <param name="lifetime">Most steps a droplet lives.</param>
/// <param name="erosionRadius">Radius in texels that each erosion step spreads over.</param>
/// <param name="seed">Random seed for droplet starting points.</param>
/// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
[McpTool( "terrain_erode" )]
public static object Erode( [Sandbox.Range( 1, 1000000 )] int iterations = 50000, float erosionRate = 0.3f, float depositionRate = 0.3f,
float evaporationRate = 0.01f, float gravity = 4f, float inertia = 0.05f, float capacity = 4f, float minCapacity = 0.01f,
[Sandbox.Range( 1, 200 )] int lifetime = 30, [Sandbox.Range( 1, 16 )] int erosionRadius = 3, int seed = 42, string id = "" )
{
RequireFinite( "the erosion rates, gravity, inertia and capacities", erosionRate, depositionRate, evaporationRate, gravity, inertia, capacity, minCapacity );
var (terrain, session) = ForEdit( id );
var res = terrain.Storage.Resolution;
var map = terrain.Storage.HeightMap;
CommitHeights( session, terrain, "Terrain Erode", Whole( terrain ), () =>
{
// Normalised floats, so small per-step changes aren't lost to 16-bit rounding
var h = map.Select( x => x / (float)ushort.MaxValue ).ToArray();
var brush = ErosionBrush( erosionRadius );
var rng = new Random( seed );
for ( var drop = 0; drop < iterations; drop++ )
{
float px = rng.NextSingle() * (res - 2) + 1, py = rng.NextSingle() * (res - 2) + 1;
float dx = 0, dy = 0, speed = 1, water = 1, sediment = 0;
for ( var life = 0; life < lifetime; life++ )
{
int nx = (int)px, ny = (int)py;
if ( nx < 1 || nx >= res - 1 || ny < 1 || ny >= res - 1 ) break;
float cx = px - nx, cy = py - ny;
var i = ny * res + nx;
float nw = h[i], ne = h[i + 1], sw = h[i + res], se = h[i + res + 1];
var gx = (ne - nw) * (1 - cy) + (se - sw) * cy;
var gy = (sw - nw) * (1 - cx) + (se - ne) * cx;
var height = nw * (1 - cx) * (1 - cy) + ne * cx * (1 - cy) + sw * (1 - cx) * cy + se * cx * cy;
dx = dx * inertia - gx * (1 - inertia);
dy = dy * inertia - gy * (1 - inertia);
var len = MathF.Sqrt( dx * dx + dy * dy );
if ( len > 0 ) { dx /= len; dy /= len; }
else { dx = rng.NextSingle() * 2 - 1; dy = rng.NextSingle() * 2 - 1; }
float npx = px + dx, npy = py + dy;
if ( npx < 1 || npx >= res - 1 || npy < 1 || npy >= res - 1 ) break;
var dh = Bilinear( h, res, npx, npy ) - height;
var cap = Math.Max( -dh * speed * water * capacity, minCapacity );
if ( sediment > cap || dh > 0 )
{
var deposit = dh > 0 ? Math.Min( dh, sediment ) : (sediment - cap) * depositionRate;
sediment -= deposit;
h[i] += deposit * (1 - cx) * (1 - cy);
h[i + 1] += deposit * cx * (1 - cy);
h[i + res] += deposit * (1 - cx) * cy;
h[i + res + 1] += deposit * cx * cy;
}
else
{
var erode = Math.Min( (cap - sediment) * erosionRate, -dh );
foreach ( var (bx, by, w) in brush )
{
int ex = nx + bx, ey = ny + by;
if ( ex < 0 || ex >= res || ey < 0 || ey >= res ) continue;
h[ey * res + ex] = Math.Max( 0, h[ey * res + ex] - erode * w );
}
sediment += erode;
}
speed = MathF.Sqrt( Math.Max( 0, speed * speed + dh * gravity ) );
water *= 1 - evaporationRate;
px = npx; py = npy;
if ( water < 0.001f ) break;
}
}
for ( var i = 0; i < map.Length; i++ )
map[i] = (ushort)MathF.Round( Math.Clamp( h[i], 0f, 1f ) * ushort.MaxValue );
} );
return new { Id = terrain.GameObject.Id, Droplets = iterations, LowestHeight = HeightOf( terrain, map.Min() ), HighestHeight = HeightOf( terrain, map.Max() ) };
}
/// <summary>
/// Press a landform into the heightmap: a Gaussian Hill, a Crater with a rim, a flat-topped Mesa or
/// Plateau, or a Ridge or Valley line turned by angle. Crater, Ridge and Valley fade to zero over
/// the outer fifth of the radius, so no shape ends in a wall at its edge. Add raises by the shape, Subtract lowers by it,
/// Set replaces heights with it. The user can undo this. Check with terrain_get_height_region.
/// </summary>
/// <param name="position">Centre of the stamp as 'x,y,z'.</param>
/// <param name="shape">Landform to stamp.</param>
/// <param name="mode">How the shape combines with existing heights.</param>
/// <param name="height">Peak height of the shape in units.</param>
/// <param name="radius">Stamp radius in units.</param>
/// <param name="angle">Direction of a Ridge or Valley in degrees: 0 runs it along X, 90 along Y.</param>
/// <param name="id">Terrain game object id. Empty means the scene's only terrain.</param>
[McpTool( "terrain_stamp" )]
public static object Stamp( Vector3 position, StampShape shape = StampShape.Hill, StampMode mode = StampMode.Add, float height = 20f,
float radius = 50f, float angle = 0f, string id = "" )
{
RequireFinite( "height and angle", height, angle );
var (terrain, session) = ForEdit( id );
var map = terrain.Storage.HeightMap;
var brush = BrushAt( terrain, position, radius );
var r = (float)brush.Radius;
var sigma = r / 3f;
float cos = MathF.Cos( angle.DegreeToRadian() ), sin = MathF.Sin( angle.DegreeToRadian() );
var changed = 0;
CommitHeights( session, terrain, $"Terrain Stamp {shape}", brush.Region, () => changed = brush.ForEach( ( i, dx, dy, t ) =>
{
var dist = t * r;
var across = -dx * sin + dy * cos;
// These shapes are still well above zero at the radius, so they fade out over its outer fifth instead of ending in a wall
var edgeFade = SmoothStep( Math.Clamp( (1f - t) / 0.2f, 0f, 1f ) );
var profile = shape switch
{
StampShape.Crater => (-Gauss( dist, sigma ) + 0.6f * Gauss( dist - r * 0.8f, r * 0.15f )) * edgeFade,
StampShape.Mesa => SmoothStep( t < 0.7f ? 1f : 1f - (t - 0.7f) / 0.3f ),
StampShape.Ridge => Gauss( across, sigma * MathF.Sqrt( 0.3f ) ) * edgeFade,
StampShape.Valley => -Gauss( across, sigma * MathF.Sqrt( 0.3f ) ) * edgeFade,
StampShape.Plateau => t < 0.6f ? 1f : Math.Max( 0f, 1f - (t - 0.6f) / 0.4f ),
_ => Gauss( dist, sigma )
};
var current = HeightOf( terrain, map[i] );
map[i] = RawOf( terrain, mode switch
{
StampMode.Set => height * profile,
StampMode.Subtract => current - height * MathF.Abs( profile ),
_ => current + height * profile
} );
} ) );
return new { Id = terrain.GameObject.Id, Shape = shape.ToString(), Mode = mode.ToString(), TexelsChanged = changed };
}
/// <summary>
/// Regenerate the objects a ClutterComponent scatters. Volume mode rebuilds everything inside its
/// Bounds; Infinite mode rebuilds the streamed tiles overlapping the box, or every tile when no box is
/// given, and they stream back in around the camera. Either fills in over the next frames. Set the
/// component's Clutter definition, Seed or Mode with set_component first. Not undoable - generation
/// finishes after the call returns; the same seed scatters the same objects again.
/// </summary>
/// <param name="id">Id of the game object with the ClutterComponent.</param>
/// <param name="boundsMin">Infinite mode only: box minimum corner as 'x,y,z'. Give with boundsMax.</param>
/// <param name="boundsMax">Infinite mode only: box maximum corner as 'x,y,z'. Give with boundsMin.</param>
[McpTool( "terrain_regenerate_clutter" )]
public static string RegenerateClutter( string id, Vector3? boundsMin = null, Vector3? boundsMax = null )
{
var clutter = FindClutter( id );
var name = clutter.GameObject.Name;
if ( clutter.Clutter is null )
throw new Exception( $"'{name}' has no clutter definition - set its Clutter property to a .clutter asset with set_component" );
if ( (boundsMin is null) != (boundsMax is null) )
throw new Exception( "Give both boundsMin and boundsMax, or neither" );
if ( !clutter.Infinite )
{
if ( boundsMin is not null )
throw new Exception( $"'{name}' is in Volume mode, which always regenerates its whole Bounds - change Bounds with set_component, or call without a box" );
clutter.Generate();
SessionOf( clutter.GameObject ).HasUnsavedChanges = true;
return $"Regenerating the clutter inside '{name}''s bounds - it fills in over the next frames";
}
if ( boundsMin is { } min && boundsMax is { } max )
{
clutter.InvalidateTilesInBounds( new BBox( min, max ) );
return $"Regenerating '{name}''s clutter tiles overlapping {min} to {max}";
}
clutter.ClearInfinite();
return $"Cleared every clutter tile of '{name}' - they stream back in around the camera";
}
/// <summary>
/// Remove every object a ClutterComponent has scattered. In Infinite mode the tiles stream straight
/// back around the camera, so to keep it empty disable the component instead. Not undoable -
/// terrain_regenerate_clutter with the same seed scatters the same objects again.
/// </summary>
/// <param name="id">Id of the game object with the ClutterComponent.</param>
[McpTool( "terrain_clear_clutter" )]
public static string ClearClutter( string id )
{
var clutter = FindClutter( id );
clutter.Clear();
SessionOf( clutter.GameObject ).HasUnsavedChanges = true;
return $"Cleared the clutter of '{clutter.GameObject.Name}'";
}
static ClutterComponent FindClutter( string id )
{
var go = FindByGuid( id );
return go.Components.Get<ClutterComponent>( FindMode.EverythingInSelf )
?? throw new Exception( $"'{go.Name}' has no ClutterComponent - find_game_objects can search by component type" );
}
static float Gauss( float x, float sigma ) => MathF.Exp( -x * x / (2 * sigma * sigma) );
static float SmoothStep( float x ) => x * x * (3 - 2 * x);
static float Bilinear( float[] h, int res, float x, float y )
{
int ix = (int)x, iy = (int)y;
float fx = x - ix, fy = y - iy;
var i = iy * res + ix;
return h[i] * (1 - fx) * (1 - fy) + h[i + 1] * fx * (1 - fy) + h[i + res] * (1 - fx) * fy + h[i + res + 1] * fx * fy;
}
static List<(int X, int Y, float Weight)> ErosionBrush( int radius )
{
var brush = new List<(int, int, float)>();
for ( var y = -radius; y <= radius; y++ )
{
for ( var x = -radius; x <= radius; x++ )
{
var d = MathF.Sqrt( x * x + y * y );
if ( d <= radius ) brush.Add( (x, y, 1f - d / radius) );
}
}
var total = brush.Sum( b => b.Item3 );
return brush.Select( b => (b.Item1, b.Item2, b.Item3 / total) ).ToList();
}
static int[] Permutation( int seed )
{
var p = Enumerable.Range( 0, 256 ).ToArray();
var rng = new Random( seed );
for ( var i = 255; i > 0; i-- )
{
var j = rng.Next( i + 1 );
(p[i], p[j]) = (p[j], p[i]);
}
return p.Concat( p ).ToArray();
}
// Classic improved Perlin noise, remapped to 0..1
static float Perlin( float x, float y, int[] perm )
{
int xi = (int)MathF.Floor( x ) & 255, yi = (int)MathF.Floor( y ) & 255;
float xf = x - MathF.Floor( x ), yf = y - MathF.Floor( y );
float u = xf * xf * xf * (xf * (xf * 6 - 15) + 10), v = yf * yf * yf * (yf * (yf * 6 - 15) + 10);
int aa = perm[perm[xi] + yi], ab = perm[perm[xi] + yi + 1], ba = perm[perm[xi + 1] + yi], bb = perm[perm[xi + 1] + yi + 1];
static float Grad( int hash, float fx, float fy ) => (hash & 3) switch
{
0 => fx + fy,
1 => -fx + fy,
2 => fx - fy,
_ => -fx - fy
};
var x1 = Grad( aa, xf, yf ) + u * (Grad( ba, xf - 1, yf ) - Grad( aa, xf, yf ));
var x2 = Grad( ab, xf, yf - 1 ) + u * (Grad( bb, xf - 1, yf - 1 ) - Grad( ab, xf, yf - 1 ));
return (x1 + v * (x2 - x1) + 1) / 2;
}
static float Fbm( float x, float y, int octaves, float persistence, float lacunarity, int[] perm )
{
float total = 0, amplitude = 1, frequency = 1, max = 0;
for ( var i = 0; i < octaves; i++ )
{
total += Perlin( x * frequency, y * frequency, perm ) * amplitude;
max += amplitude;
amplitude *= persistence;
frequency *= lacunarity;
}
return total / max;
}
}