sion: 3072m Sion map loader, Ymir heightfield+trimesh physics, LOD1/LOD2 renderer, and tests

This commit is contained in:
Meta Vens 2026-12-05 01:18:46 +01:00
commit 1864acecb7
14 changed files with 2242 additions and 183 deletions

View file

@ -227,7 +227,7 @@ public partial class ArenaRenderer : Node3D
Multimesh = _vfxBeamMm,
MaterialOverride = _vfxMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 220f, 1800f)),
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};
@ -247,7 +247,7 @@ public partial class ArenaRenderer : Node3D
Multimesh = _vfxSphereMm,
MaterialOverride = _vfxMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 220f, 1800f)),
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};
@ -267,7 +267,7 @@ public partial class ArenaRenderer : Node3D
Multimesh = _vfxRingMm,
MaterialOverride = _vfxMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 220f, 1800f)),
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};
@ -287,7 +287,7 @@ public partial class ArenaRenderer : Node3D
Multimesh = _dropDiscMm,
MaterialOverride = _vfxMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 180f, 1800f)),
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};
@ -307,7 +307,7 @@ public partial class ArenaRenderer : Node3D
Multimesh = _dropPillarMm,
MaterialOverride = _imperialBeaconMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 180f, 1800f)),
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};
@ -460,7 +460,7 @@ public partial class ArenaRenderer : Node3D
_safeRingImm.SurfaceBegin(Mesh.PrimitiveType.Triangles);
const int segments = 160;
const float halfThick = 1.1f;
float halfThick = terrain.MapSize > 2000f ? 2.2f : 1.1f;
float rInner = MathF.Max(2f, safeRadius - halfThick);
float rOuter = safeRadius + halfThick;
@ -832,7 +832,7 @@ public partial class ArenaRenderer : Node3D
if (!_dropVisuals.TryGetValue(d.Id, out var entry))
{
TerrainField.WorldToTile(d.X, d.Z, out int tx, out int tz);
state.Terrain.MapWorldToTile(d.X, d.Z, out int tx, out int tz);
float baseY = state.Terrain.SampleHeight(d.X, d.Z);
if (d.Module is { } mod)
{

View file

@ -41,6 +41,8 @@ public partial class Hud : CanvasLayer
private Label _controlsHint = null!;
private RadarWidget _radar = null!;
private Label _radarTitle = null!;
private Label _mapAttribLabel = null!;
private CrosshairOverlay _crosshair = null!;
private InventoryGridControl _schematic = null!;
private Label _hoverLabel = null!;
@ -169,14 +171,21 @@ public partial class Hud : CanvasLayer
{
float agl = MathF.Max(0f, player.Y - player.Grid.Spec.HalfHeight - state.Terrain.SampleHeight(player.X, player.Z));
_statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALT {agl:F1}m | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}";
_controlsHint.Text = "WASD Fly | Space/C Climb/Descend | Mouse Aim | LMB Fire | E Bolt/Swap | Tab Garage";
_controlsHint.Text = "WASD Fly | Space/C Alt | Mouse Aim | LMB Fire | E Bolt/Swap | Tab Garage | M Map";
}
else
{
_statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}";
_controlsHint.Text = "WASD Drive | Mouse Aim | LMB Fire | E Bolt/Swap | Tab Garage | Wheel Zoom";
_controlsHint.Text = "WASD Drive | Mouse Aim | LMB Fire | E Bolt/Swap | Tab Garage | M Map | Wheel Zoom";
}
_radarTitle.Text = state.MapKind == ArenaMapKind.Sion
? "SION 3KM • RADAR"
: "DESERT RING • RADAR";
_mapAttribLabel.Text = state.MapKind == ArenaMapKind.Sion
? "Data: swisstopo | [M] Switch Map"
: "[M] Switch to Sion 3 km";
float distCenter = MathF.Sqrt(player.X * player.X + player.Z * player.Z);
float outside = distCenter - state.Spectators.SafeRadius;
int cleared = state.Spectators.CountClearedFor(player.Id);
@ -346,16 +355,21 @@ public partial class Hud : CanvasLayer
vbox.AddThemeConstantOverride("separation", 4);
panel.AddChild(vbox);
var title = new Label { Text = "GALLERY & ARENA RADAR", HorizontalAlignment = HorizontalAlignment.Center };
title.AddThemeColorOverride("font_color", OrangeCol);
title.AddThemeFontSizeOverride("font_size", 12);
vbox.AddChild(title);
_radarTitle = new Label { Text = "SION 3KM • RADAR", HorizontalAlignment = HorizontalAlignment.Center };
_radarTitle.AddThemeColorOverride("font_color", OrangeCol);
_radarTitle.AddThemeFontSizeOverride("font_size", 12);
vbox.AddChild(_radarTitle);
_radar = new RadarWidget
{
CustomMinimumSize = new Vector2(214f, 214f)
};
vbox.AddChild(_radar);
_mapAttribLabel = new Label { Text = "Data: swisstopo | [M] Switch Map", HorizontalAlignment = HorizontalAlignment.Center };
_mapAttribLabel.AddThemeColorOverride("font_color", TextMuted);
_mapAttribLabel.AddThemeFontSizeOverride("font_size", 10);
vbox.AddChild(_mapAttribLabel);
}
private void BuildBottomLeftSchematic()
@ -1023,7 +1037,8 @@ public partial class Hud : CanvasLayer
Vector2 center = Size * 0.5f;
float radius = MathF.Min(Size.X, Size.Y) * 0.47f;
float maxBlipRadius = MathF.Max(4f, radius - 3f);
float scale = radius / MatchState.ArenaHalfExtent;
float arenaHalf = MathF.Max(1f, _state?.Terrain.MapHalfExtent ?? MatchState.ArenaHalfExtent);
float scale = radius / arenaHalf;
DrawCircle(center, radius, BgInner);
DrawArc(center, radius, 0f, MathF.Tau, 48, BorderCol, 1.5f);

View file

@ -14,14 +14,19 @@ namespace RustToDust.Client;
public partial class Main : Node3D
{
private TerrainRenderer _terrain = null!;
private SionMapRenderer _sionMap = null!;
private ArenaRenderer _arena = null!;
private Camera3D _camera = null!;
private Hud _hud = null!;
private DirectionalLight3D _sun = null!;
private ProceduralSkyMaterial _skyMat = null!;
private Godot.Environment _env = null!;
private ArenaSession? _session;
private ArenaMapKind _mapKind = ArenaMapKind.Sion;
private PlayerInput? _scriptedInput;
private float _cameraYaw;
private float _cameraPitch = Mathf.DegToRad(12f);
private float _cameraPitch = Mathf.DegToRad(5f);
private float _cameraZoom = 1.0f;
private Vector3 _cameraSmoothedAnchor = Vector3.Zero;
private float _elapsedSeconds;
@ -53,8 +58,11 @@ public partial class Main : Node3D
public ArenaSession Session => _session ?? throw new InvalidOperationException($"No active ArenaSession ({Failure ?? "uninitialized"})");
public TerrainRenderer Terrain => _terrain;
public SionMapRenderer SionMap => _sionMap;
public ArenaRenderer Arena => _arena;
public Hud Hud => _hud;
public ArenaMapKind MapKind => _mapKind;
public ArenaMapKind? InitialMapKindOverride { get; set; }
public string? Failure { get; private set; }
public int Seed => _seed;
public float CameraYaw => _cameraYaw;
@ -66,6 +74,9 @@ public partial class Main : Node3D
_terrain = new TerrainRenderer { Name = "Terrain" };
AddChild(_terrain);
_sionMap = new SionMapRenderer { Name = "SionMap" };
AddChild(_sionMap);
_arena = new ArenaRenderer { Name = "Arena" };
AddChild(_arena);
@ -74,20 +85,32 @@ public partial class Main : Node3D
Name = "ShoulderCamera",
Current = true,
Fov = 58f,
Far = 1800f
Far = 4200f
};
AddChild(_camera);
_hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw) { Name = "Hud" };
AddChild(_hud);
if (InitialMapKindOverride.HasValue)
{
_mapKind = InitialMapKindOverride.Value;
}
else
{
string? envMap = System.Environment.GetEnvironmentVariable("RTD_MAP");
_mapKind = string.Equals(envMap, "desert", StringComparison.OrdinalIgnoreCase)
? ArenaMapKind.Desert
: ArenaMapKind.Sion;
}
if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"), out int perfFrames) && perfFrames > 0)
{
_perfTargetFrames = perfFrames;
ArenaSession.PerfEnabled = true;
}
Reset(_seed);
Reset(_seed, _mapKind);
if (_perfTargetFrames > 0 && System.Environment.GetEnvironmentVariable("RTD_PERF_COMBAT") == "1" && _session is not null)
{
SetupPerfCombatScenario(_session);
@ -149,26 +172,49 @@ public partial class Main : Node3D
_session = null;
}
public void Reset(int seed)
public void Reset(int seed, ArenaMapKind? mapKind = null)
{
_seed = seed;
if (mapKind.HasValue)
{
_mapKind = mapKind.Value;
}
_session?.Dispose();
_session = null;
Failure = null;
try
{
_session = new ArenaSession(seed);
_session = new ArenaSession(seed, _mapKind);
var p = _session.State.Player;
_cameraYaw = p.Yaw;
_cameraPitch = Mathf.DegToRad(12f);
_cameraPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(5f) : Mathf.DegToRad(12f);
_cameraZoom = 1.0f;
_cameraSmoothedAnchor = ComputeTargetAnchor(p);
_camera.Far = _mapKind == ArenaMapKind.Sion ? 4200f : 1800f;
ApplyEnvironmentForMap(_mapKind);
if (_mapKind == ArenaMapKind.Sion)
{
_terrain.Visible = false;
_sionMap.Visible = true;
_sionMap.EnsureBuilt(_session.State.SionMap!, _session.State.Terrain);
_arena.Sync(_session, _elapsedSeconds, 0f);
UpdateCamera(1f);
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_sionMap.Visible = false;
_terrain.Visible = true;
_terrain.InvalidateAll();
_terrain.Sync(_session.State.Terrain);
_arena.Sync(_session, _elapsedSeconds, 0f);
UpdateCamera(1f);
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
_terrain.InvalidateAll();
_terrain.Sync(_session.State.Terrain);
_arena.Sync(_session, _elapsedSeconds, 0f);
UpdateCamera(1f);
_hud.Sync(_session);
if (DisplayServer.GetName() != "headless" && !_hud.GarageExpanded && _perfTargetFrames == 0)
@ -214,7 +260,10 @@ public partial class Main : Node3D
}
break;
case Key.R:
Reset(_seed + 1);
Reset(_seed + 1, _mapKind);
break;
case Key.M:
Reset(_seed, _mapKind == ArenaMapKind.Sion ? ArenaMapKind.Desert : ArenaMapKind.Sion);
break;
case Key.Escape:
if (_hud.GarageExpanded)
@ -292,7 +341,10 @@ public partial class Main : Node3D
{
double toMs = 1000.0 / Stopwatch.Frequency;
long tt0 = Stopwatch.GetTimestamp();
_terrain.Sync(_session.State.Terrain);
if (_mapKind == ArenaMapKind.Desert)
{
_terrain.Sync(_session.State.Terrain);
}
long tt1 = Stopwatch.GetTimestamp();
_arena.Sync(_session, _elapsedSeconds, (float)delta);
long ta1 = Stopwatch.GetTimestamp();
@ -301,7 +353,14 @@ public partial class Main : Node3D
long tc0 = Stopwatch.GetTimestamp();
UpdateCamera((float)delta);
_terrain.UpdateTileLod(_camera.GlobalPosition);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
long th0 = Stopwatch.GetTimestamp();
_hud.Sync(_session);
long th1 = Stopwatch.GetTimestamp();
@ -340,10 +399,20 @@ public partial class Main : Node3D
}
else
{
_terrain.Sync(_session.State.Terrain);
if (_mapKind == ArenaMapKind.Desert)
{
_terrain.Sync(_session.State.Terrain);
}
_arena.Sync(_session, _elapsedSeconds, (float)delta);
UpdateCamera((float)delta);
_terrain.UpdateTileLod(_camera.GlobalPosition);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
_hud.Sync(_session);
}
}
@ -395,6 +464,10 @@ public partial class Main : Node3D
GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count:F2}");
GD.Print($"StepBreakdownMs/tick: ring={ArenaSession.PerfRingMs / _perfPhysicsTicks:F2} ai={ArenaSession.PerfAiMs / _perfPhysicsTicks:F2} drive={ArenaSession.PerfDriveMs / _perfPhysicsTicks:F2} world={ArenaSession.PerfWorldMs / _perfPhysicsTicks:F2} sync={ArenaSession.PerfBodySyncMs / _perfPhysicsTicks:F2} detect={ArenaSession.PerfDetectMs / _perfPhysicsTicks:F2} weapons={ArenaSession.PerfWeaponsMs / _perfPhysicsTicks:F2}");
GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} tracers={_session?.State.Tracers.Count ?? 0}");
if (_mapKind == ArenaMapKind.Sion)
{
GD.Print($"SionMap: chunks={_sionMap.TerrainChunkCount} tiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}");
}
foreach (var kv in _arena.AssetCache.Vehicles)
{
int tris = 0;
@ -617,7 +690,7 @@ public partial class Main : Node3D
private void SetupLightingAndSky()
{
var sun = new DirectionalLight3D
_sun = new DirectionalLight3D
{
Name = "DesertSun",
LightColor = new Color(1.0f, 0.92f, 0.78f),
@ -627,19 +700,19 @@ public partial class Main : Node3D
DirectionalShadowMaxDistance = 88f,
RotationDegrees = new Vector3(-48f, 32f, 0f)
};
AddChild(sun);
AddChild(_sun);
var skyMat = new ProceduralSkyMaterial
_skyMat = new ProceduralSkyMaterial
{
SkyTopColor = new Color(0.24f, 0.34f, 0.44f),
SkyHorizonColor = new Color(0.76f, 0.56f, 0.37f),
GroundBottomColor = new Color(0.32f, 0.22f, 0.14f),
GroundHorizonColor = new Color(0.70f, 0.50f, 0.33f)
};
var env = new Godot.Environment
_env = new Godot.Environment
{
BackgroundMode = Godot.Environment.BGMode.Sky,
Sky = new Sky { SkyMaterial = skyMat },
Sky = new Sky { SkyMaterial = _skyMat },
AmbientLightSource = Godot.Environment.AmbientSource.Sky,
AmbientLightEnergy = 0.55f,
FogEnabled = true,
@ -649,6 +722,46 @@ public partial class Main : Node3D
FogDepthBegin = 380f,
FogDepthEnd = 1100f
};
AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = env });
AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = _env });
}
private void ApplyEnvironmentForMap(ArenaMapKind mapKind)
{
if (mapKind == ArenaMapKind.Sion)
{
_sun.LightColor = new Color(1.0f, 0.95f, 0.87f);
_sun.LightEnergy = 1.25f;
_sun.DirectionalShadowMaxDistance = 160f;
_sun.RotationDegrees = new Vector3(-42f, 28f, 0f);
_skyMat.SkyTopColor = new Color(0.18f, 0.36f, 0.62f);
_skyMat.SkyHorizonColor = new Color(0.68f, 0.79f, 0.89f);
_skyMat.GroundBottomColor = new Color(0.24f, 0.26f, 0.22f);
_skyMat.GroundHorizonColor = new Color(0.58f, 0.67f, 0.74f);
_env.AmbientLightEnergy = 0.42f;
_env.FogLightColor = new Color(0.70f, 0.79f, 0.88f);
_env.FogDensity = 0.42f;
_env.FogDepthBegin = 850f;
_env.FogDepthEnd = 3000f;
}
else
{
_sun.LightColor = new Color(1.0f, 0.92f, 0.78f);
_sun.LightEnergy = 1.45f;
_sun.DirectionalShadowMaxDistance = 88f;
_sun.RotationDegrees = new Vector3(-48f, 32f, 0f);
_skyMat.SkyTopColor = new Color(0.24f, 0.34f, 0.44f);
_skyMat.SkyHorizonColor = new Color(0.76f, 0.56f, 0.37f);
_skyMat.GroundBottomColor = new Color(0.32f, 0.22f, 0.14f);
_skyMat.GroundHorizonColor = new Color(0.70f, 0.50f, 0.33f);
_env.AmbientLightEnergy = 0.55f;
_env.FogLightColor = new Color(0.76f, 0.57f, 0.39f);
_env.FogDensity = 0.72f;
_env.FogDepthBegin = 380f;
_env.FogDepthEnd = 1100f;
}
}
}

View file

@ -92,7 +92,7 @@ public partial class PomDecalPool : Node3D
Multimesh = _multiMesh,
MaterialOverride = _material,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 180f, 1800f)),
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};

502
client/SionMapRenderer.cs Normal file
View file

@ -0,0 +1,502 @@
using System;
using System.Collections.Generic;
using System.IO;
using Godot;
using RustToDust.Core;
namespace RustToDust.Client;
/// <summary>
/// Renders the 3072m x 3072m Sion, Switzerland arena:
/// - 6x6 (512m) seam-free chunked terrain ArrayMeshes from heightmap.f32 textured with terrain_surface.png + micro-grain shader.
/// - 36 spatial building tiles swapping cleanly between LOD1 (&lt;= 650m), LOD2 (650m..2200m), and culled (&gt; 2200m),
/// with shadow casting restricted to &lt;= 450m and shared PBR materials across all tiles.
/// </summary>
public partial class SionMapRenderer : Node3D
{
public const float Lod1DistanceM = 650f;
public const float CullDistanceM = 2200f;
public const float ShadowDistanceM = 450f;
private const int ChunkGridVerts = 65; // 64 quads per 512m chunk (8m spacing)
private sealed class BuildingTileEntry
{
public int Tx;
public int Tz;
public float CenterX;
public float CenterZ;
public required ArrayMesh Lod1Mesh;
public required ArrayMesh Lod2Mesh;
public required MeshInstance3D Instance;
}
private readonly List<MeshInstance3D> _terrainChunks = new(36);
private readonly List<BuildingTileEntry> _buildingTiles = new(36);
private readonly Dictionary<string, StandardMaterial3D> _sharedBuildingMaterials = new(StringComparer.Ordinal);
private string? _builtForDir;
private ShaderMaterial? _terrainMat;
private ImageTexture? _surfaceTex;
public bool IsBuilt { get; private set; }
public int TerrainChunkCount => _terrainChunks.Count;
public int BuildingTileCount => _buildingTiles.Count;
public int ActiveLod1TileCount { get; private set; }
public int ActiveLod2TileCount { get; private set; }
public int CulledTileCount { get; private set; }
public void EnsureBuilt(SionMapData sion, TerrainField terrain)
{
if (IsBuilt && string.Equals(_builtForDir, sion.DirectoryPath, StringComparison.OrdinalIgnoreCase))
{
return;
}
ClearBuilt();
_builtForDir = sion.DirectoryPath;
BuildTerrainMaterial(sion);
BuildTerrainChunks(sion, terrain);
BuildBuildingTiles(sion);
IsBuilt = true;
}
public void UpdateLod(Vector3 camPos)
{
if (!IsBuilt)
{
return;
}
const float lod1Sq = Lod1DistanceM * Lod1DistanceM;
const float cullSq = CullDistanceM * CullDistanceM;
const float shadowSq = ShadowDistanceM * ShadowDistanceM;
int lod1Count = 0;
int lod2Count = 0;
int culledCount = 0;
for (int i = 0; i < _buildingTiles.Count; i++)
{
var t = _buildingTiles[i];
float dx = t.CenterX - camPos.X;
float dz = t.CenterZ - camPos.Z;
float d2 = dx * dx + dz * dz;
if (d2 > cullSq)
{
if (t.Instance.Visible)
{
t.Instance.Visible = false;
}
culledCount++;
continue;
}
if (!t.Instance.Visible)
{
t.Instance.Visible = true;
}
ArrayMesh desired = d2 <= lod1Sq ? t.Lod1Mesh : t.Lod2Mesh;
if (!ReferenceEquals(t.Instance.Mesh, desired))
{
t.Instance.Mesh = desired;
}
if (d2 <= lod1Sq) lod1Count++;
else lod2Count++;
var desiredShadow = d2 <= shadowSq
? GeometryInstance3D.ShadowCastingSetting.On
: GeometryInstance3D.ShadowCastingSetting.Off;
if (t.Instance.CastShadow != desiredShadow)
{
t.Instance.CastShadow = desiredShadow;
}
}
ActiveLod1TileCount = lod1Count;
ActiveLod2TileCount = lod2Count;
CulledTileCount = culledCount;
}
private void BuildTerrainMaterial(SionMapData sion)
{
string surfPath = Path.Combine(sion.DirectoryPath, sion.Metadata.SurfaceTexture);
if (!File.Exists(surfPath))
{
throw new FileNotFoundException($"Missing Sion terrain surface texture: {surfPath}", surfPath);
}
var img = Image.LoadFromFile(surfPath);
if (img is null || img.IsEmpty())
{
throw new InvalidOperationException($"Failed to decode Sion terrain surface texture: {surfPath}");
}
img.GenerateMipmaps();
_surfaceTex = ImageTexture.CreateFromImage(img);
var shader = new Shader
{
Code = """
shader_type spatial;
render_mode cull_back, depth_draw_opaque;
uniform sampler2D surface_tex : source_color, filter_linear_mipmap, repeat_disable;
varying vec3 v_world_pos;
varying vec3 v_world_normal;
float hash21(vec2 p) {
p = fract(p * vec2(123.34, 456.21));
p += dot(p, p + 45.32);
return fract(p.x * p.y);
}
float value_noise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
float a = hash21(i);
float b = hash21(i + vec2(1.0, 0.0));
float c = hash21(i + vec2(0.0, 1.0));
float d = hash21(i + vec2(1.0, 1.0));
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}
void vertex() {
v_world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
v_world_normal = normalize((MODEL_MATRIX * vec4(NORMAL, 0.0)).xyz);
}
void fragment() {
vec3 base_col = texture(surface_tex, UV).rgb;
// Multi-scale crisp world-space micro-grain for up-close ground readability
float dist = length((INV_VIEW_MATRIX * vec4(0.0, 0.0, 0.0, 1.0)).xyz - v_world_pos);
float near_fade = clamp(1.0 - smoothstep(140.0, 520.0, dist), 0.12, 1.0);
float macro = (value_noise(v_world_pos.xz * 0.28) - 0.5) * 0.07;
float micro = (value_noise(v_world_pos.xz * 2.4) - 0.5) * 0.06;
float grit = (hash21(floor(v_world_pos.xz * 12.0)) - 0.5) * 0.035;
float slope = 1.0 - clamp(v_world_normal.y, 0.0, 1.0);
float strata = (value_noise(vec2(v_world_pos.x * 0.15 + v_world_pos.z * 0.15, v_world_pos.y * 0.9)) - 0.5) * 0.10 * smoothstep(0.10, 0.35, slope);
vec3 col = clamp(base_col + vec3(macro + (micro + grit) * near_fade + strata), vec3(0.0), vec3(1.0));
ALBEDO = col;
ROUGHNESS = mix(0.88, 0.96, slope);
METALLIC = 0.03;
}
"""
};
_terrainMat = new ShaderMaterial { Shader = shader };
_terrainMat.SetShaderParameter("surface_tex", _surfaceTex);
}
private void BuildTerrainChunks(SionMapData sion, TerrainField terrain)
{
int grid = sion.Metadata.TileGrid;
float sizeM = sion.Metadata.SizeMeters;
float tileSize = sion.Metadata.TileSizeMeters;
float half = sizeM * 0.5f;
int n = ChunkGridVerts;
float step = tileSize / (n - 1);
// Precompute shared index buffer for every 65x65 chunk (Godot ArrayMesh cull_back uses CW front-facing winding)
int quadCount = (n - 1) * (n - 1);
var indices = new int[quadCount * 6];
int ii = 0;
for (int gz = 0; gz < n - 1; gz++)
{
for (int gx = 0; gx < n - 1; gx++)
{
int i00 = gz * n + gx;
int i10 = i00 + 1;
int i01 = i00 + n;
int i11 = i01 + 1;
indices[ii++] = i00;
indices[ii++] = i10;
indices[ii++] = i01;
indices[ii++] = i10;
indices[ii++] = i11;
indices[ii++] = i01;
}
}
int vertCount = n * n;
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
float x0 = -half + tx * tileSize;
float z0 = -half + tz * tileSize;
float cx = x0 + tileSize * 0.5f;
float cz = z0 + tileSize * 0.5f;
var verts = new Vector3[vertCount];
var normals = new Vector3[vertCount];
var uvs = new Vector2[vertCount];
for (int gz = 0; gz < n; gz++)
{
float wz = z0 + gz * step;
float lx = 0f;
float lz = wz - cz;
float v = (wz + half) / sizeM;
for (int gx = 0; gx < n; gx++)
{
float wx = x0 + gx * step;
lx = wx - cx;
float h = terrain.SampleHeight(wx, wz);
var (nx, ny, nz) = terrain.SampleNormal(wx, wz);
int idx = gz * n + gx;
verts[idx] = new Vector3(lx, h, lz);
normals[idx] = new Vector3(nx, ny, nz);
uvs[idx] = new Vector2((wx + half) / sizeM, v);
}
}
var arrays = new Godot.Collections.Array();
arrays.Resize((int)Mesh.ArrayType.Max);
arrays[(int)Mesh.ArrayType.Vertex] = verts;
arrays[(int)Mesh.ArrayType.Normal] = normals;
arrays[(int)Mesh.ArrayType.TexUV] = uvs;
arrays[(int)Mesh.ArrayType.Index] = indices;
var mesh = new ArrayMesh();
mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays);
var chunkNode = new MeshInstance3D
{
Name = $"SionTerrain_{tx}_{tz}",
Mesh = mesh,
MaterialOverride = _terrainMat,
Position = new Vector3(cx, 0f, cz),
CastShadow = GeometryInstance3D.ShadowCastingSetting.On
};
AddChild(chunkNode);
_terrainChunks.Add(chunkNode);
}
}
}
private void BuildBuildingTiles(SionMapData sion)
{
var tiles = sion.Metadata.Tiles;
for (int i = 0; i < tiles.Count; i++)
{
var tm = tiles[i];
string lod1Path = Path.Combine(sion.DirectoryPath, tm.Lod1RelativePath.Replace('/', Path.DirectorySeparatorChar));
string lod2Path = Path.Combine(sion.DirectoryPath, tm.Lod2RelativePath.Replace('/', Path.DirectorySeparatorChar));
ArrayMesh lod1Mesh = LoadMergedTileGlb(lod1Path);
ArrayMesh lod2Mesh = LoadMergedTileGlb(lod2Path);
var mi = new MeshInstance3D
{
Name = $"SionBuildings_{tm.Tx}_{tm.Tz}",
Mesh = lod2Mesh,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
};
AddChild(mi);
_buildingTiles.Add(new BuildingTileEntry
{
Tx = tm.Tx,
Tz = tm.Tz,
CenterX = tm.Center.X,
CenterZ = tm.Center.Z,
Lod1Mesh = lod1Mesh,
Lod2Mesh = lod2Mesh,
Instance = mi
});
}
}
private ArrayMesh LoadMergedTileGlb(string glbPath)
{
if (!File.Exists(glbPath))
{
throw new FileNotFoundException($"Missing Sion building GLB: {glbPath}", glbPath);
}
var doc = new GltfDocument();
var state = new GltfState();
Error err = doc.AppendFromFile(glbPath, state);
if (err != Error.Ok)
{
throw new InvalidOperationException($"GltfDocument failed to load '{glbPath}': {err}");
}
Node? root = doc.GenerateScene(state);
if (root is null)
{
throw new InvalidOperationException($"GltfDocument generated null scene for '{glbPath}'.");
}
try
{
var byMat = new Dictionary<string, (StandardMaterial3D Mat, List<Vector3> Pos, List<Vector3> Norm, List<int> Idx)>(StringComparer.Ordinal);
CollectMeshesRecursive(root, Transform3D.Identity, byMat);
var outMesh = new ArrayMesh();
foreach (var kv in byMat)
{
var entry = kv.Value;
if (entry.Pos.Count == 0 || entry.Idx.Count == 0)
{
continue;
}
var arrays = new Godot.Collections.Array();
arrays.Resize((int)Mesh.ArrayType.Max);
arrays[(int)Mesh.ArrayType.Vertex] = entry.Pos.ToArray();
arrays[(int)Mesh.ArrayType.Normal] = entry.Norm.ToArray();
arrays[(int)Mesh.ArrayType.Index] = entry.Idx.ToArray();
int surfIdx = outMesh.GetSurfaceCount();
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays);
outMesh.SurfaceSetMaterial(surfIdx, entry.Mat);
}
return outMesh;
}
finally
{
root.Free();
}
}
private void CollectMeshesRecursive(
Node node,
Transform3D parentXf,
Dictionary<string, (StandardMaterial3D Mat, List<Vector3> Pos, List<Vector3> Norm, List<int> Idx)> byMat)
{
Transform3D xf = node is Node3D n3 ? parentXf * n3.Transform : parentXf;
if (node is MeshInstance3D mi && mi.Mesh is not null)
{
Basis normalBasis = xf.Basis.Inverse().Transposed();
int surfCount = mi.Mesh.GetSurfaceCount();
for (int s = 0; s < surfCount; s++)
{
var arr = mi.Mesh.SurfaceGetArrays(s);
if (arr.Count <= (int)Mesh.ArrayType.Vertex)
{
continue;
}
Vector3[] posArr = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
if (posArr.Length == 0)
{
continue;
}
Vector3[]? normArr = arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array
? arr[(int)Mesh.ArrayType.Normal].AsVector3Array()
: null;
int[]? idxArr = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array
? arr[(int)Mesh.ArrayType.Index].AsInt32Array()
: null;
Material? srcMat = mi.Mesh.SurfaceGetMaterial(s);
(string matKey, StandardMaterial3D sharedMat) = GetOrShareBuildingMaterial(srcMat);
if (!byMat.TryGetValue(matKey, out var bucket))
{
bucket = (sharedMat, new List<Vector3>(posArr.Length), new List<Vector3>(posArr.Length), new List<int>(idxArr?.Length ?? posArr.Length));
byMat[matKey] = bucket;
}
int baseVert = bucket.Pos.Count;
for (int v = 0; v < posArr.Length; v++)
{
bucket.Pos.Add(xf * posArr[v]);
Vector3 n = normArr is not null && v < normArr.Length
? (normalBasis * normArr[v]).Normalized()
: Vector3.Up;
bucket.Norm.Add(n);
}
if (idxArr is not null && idxArr.Length > 0)
{
for (int k = 0; k < idxArr.Length; k++)
{
bucket.Idx.Add(baseVert + idxArr[k]);
}
}
else
{
for (int k = 0; k < posArr.Length; k++)
{
bucket.Idx.Add(baseVert + k);
}
}
}
}
for (int i = 0; i < node.GetChildCount(); i++)
{
CollectMeshesRecursive(node.GetChild(i), xf, byMat);
}
}
private (string Key, StandardMaterial3D Mat) GetOrShareBuildingMaterial(Material? srcMat)
{
if (srcMat is StandardMaterial3D std)
{
Color c = std.AlbedoColor;
string key = $"{std.ResourceName}|{c.R:F3},{c.G:F3},{c.B:F3},{c.A:F3}|{std.Roughness:F2}|{std.Metallic:F2}";
if (!_sharedBuildingMaterials.TryGetValue(key, out var cached))
{
cached = new StandardMaterial3D
{
AlbedoColor = c,
Roughness = std.Roughness,
Metallic = std.Metallic,
CullMode = BaseMaterial3D.CullModeEnum.Back
};
_sharedBuildingMaterials[key] = cached;
}
return (key, cached);
}
const string defaultKey = "__default_building";
if (!_sharedBuildingMaterials.TryGetValue(defaultKey, out var defMat))
{
defMat = new StandardMaterial3D
{
AlbedoColor = new Color(0.55f, 0.52f, 0.48f),
Roughness = 0.88f,
Metallic = 0.04f
};
_sharedBuildingMaterials[defaultKey] = defMat;
}
return (defaultKey, defMat);
}
private void ClearBuilt()
{
for (int i = 0; i < _terrainChunks.Count; i++)
{
_terrainChunks[i].QueueFree();
}
_terrainChunks.Clear();
for (int i = 0; i < _buildingTiles.Count; i++)
{
_buildingTiles[i].Instance.QueueFree();
}
_buildingTiles.Clear();
_sharedBuildingMaterials.Clear();
_terrainMat = null;
_surfaceTex = null;
_builtForDir = null;
IsBuilt = false;
ActiveLod1TileCount = 0;
ActiveLod2TileCount = 0;
CulledTileCount = 0;
}
}

View file

@ -13,7 +13,7 @@ namespace RustToDust.Client.Tests;
/// </summary>
public partial class Smoke : Node
{
private const double WatchdogSeconds = 60.0;
private const double WatchdogSeconds = 90.0;
private readonly List<string> _failures = new();
private Main _main = null!;
@ -35,6 +35,7 @@ public partial class Smoke : Node
try
{
_main = GD.Load<PackedScene>("res://Main.tscn").Instantiate<Main>();
_main.InitialMapKindOverride = ArenaMapKind.Desert;
AddChild(_main);
if (_main.Failure is { } failure)
@ -270,6 +271,7 @@ public partial class Smoke : Node
await VerifyCut3bVehiclesAndMechanismsAsync();
await MaybeCapturePreviewAsync(isHeadless);
await VerifyMaxLoadPaladinGarageAsync();
await VerifySionMapAsync();
}
private async Task VerifyHudAndShadersAsync(bool isHeadless)
@ -1404,6 +1406,70 @@ public partial class Smoke : Node
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}
private async Task VerifySionMapAsync()
{
_main.Reset(42, ArenaMapKind.Sion);
Check(_main.Failure is null, $"Sion Reset failed: {_main.Failure}");
if (_main.Failure is not null)
{
return;
}
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var sionState = _main.Session.State;
Check(_main.MapKind == ArenaMapKind.Sion && sionState.MapKind == ArenaMapKind.Sion, "Expected Sion map kind after Reset");
Check(_main.SionMap.Visible && !_main.Terrain.Visible, "Expected SionMapRenderer visible and Desert TerrainRenderer hidden");
Check(_main.SionMap.IsBuilt, "Expected SionMapRenderer.IsBuilt == true");
Check(_main.SionMap.TerrainChunkCount == 36, $"Expected 36 Sion terrain chunks, got {_main.SionMap.TerrainChunkCount}");
Check(_main.SionMap.BuildingTileCount == 36, $"Expected 36 Sion building tiles, got {_main.SionMap.BuildingTileCount}");
Check(_main.SionMap.ActiveLod1TileCount > 0, $"Expected > 0 LOD1 tiles near Sion spawn, got {_main.SionMap.ActiveLod1TileCount}");
Check(_main.SionMap.ActiveLod2TileCount > 0, $"Expected > 0 LOD2 tiles in Sion valley, got {_main.SionMap.ActiveLod2TileCount}");
var cam = _main.GetViewport().GetCamera3D();
Check(cam is not null && cam.Far >= 3600f, $"Expected Camera3D.Far >= 3600m on Sion, got {cam?.Far ?? 0f}");
var sionMap = sionState.SionMap!;
foreach (var c in sionState.Contenders)
{
Check(!sionMap.IsInsideAnyBuildingXz(c.X, c.Z, 0f), $"Contender {c.Id} spawned inside building at ({c.X:F1}, {c.Z:F1})");
}
foreach (var d in sionState.GroundDrops)
{
Check(!sionMap.IsInsideAnyBuildingXz(d.X, d.Z, 0f), $"GroundDrop {d.Id} spawned inside building at ({d.X:F1}, {d.Z:F1})");
}
Vector2 vpSize = GetViewport().GetVisibleRect().Size;
Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Sion HUD panels overlapped or clipped at {vpSize}");
var player = sionState.Player;
float startX = player.X;
float startZ = player.Z;
_main.SetScriptedInput(new PlayerInput(
Throttle: 1f,
Steer: 0f,
AimWorldX: startX + MathF.Sin(player.Yaw) * 50f,
AimWorldZ: startZ + MathF.Cos(player.Yaw) * 50f,
Fire: false,
InteractPickup: false,
Brake: false));
for (int i = 0; i < 30; i++)
{
await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame);
Check(float.IsFinite(player.X) && float.IsFinite(player.Y) && float.IsFinite(player.Z),
$"Sion player pose non-finite at frame {i}");
float gh = sionState.Terrain.SampleHeight(player.X, player.Z);
Check(player.Y - player.Grid.Spec.HalfHeight >= gh - 0.8f,
$"Sion player fell below terrain at frame {i}: bottom={player.Y - player.Grid.Spec.HalfHeight:F2}m < ground={gh:F2}m");
}
_main.SetScriptedInput(null);
float disp = MathF.Sqrt((player.X - startX) * (player.X - startX) + (player.Z - startZ) * (player.Z - startZ));
Check(disp > 1.5f, $"Expected player displacement > 1.5m on Sion after 30 frames, got {disp:F2}m");
GD.Print($"SMOKE INFO: Sion verified (chunks={_main.SionMap.TerrainChunkCount}, tiles={_main.SionMap.BuildingTileCount}, lod1={_main.SionMap.ActiveLod1TileCount}, lod2={_main.SionMap.ActiveLod2TileCount}, disp={disp:F2}m)");
}
private static int CountPremulViolations(Image img, float tolerance)
{
int count = 0;