diff --git a/assets/maps/sion/heightmap.f32 b/assets/maps/sion/heightmap.f32 deleted file mode 100644 index 7b83982..0000000 Binary files a/assets/maps/sion/heightmap.f32 and /dev/null differ diff --git a/assets/maps/sion/heightmap_05m.u16z b/assets/maps/sion/heightmap_05m.u16z new file mode 100644 index 0000000..3c2dd63 Binary files /dev/null and b/assets/maps/sion/heightmap_05m.u16z differ diff --git a/assets/maps/sion/metadata.json b/assets/maps/sion/metadata.json index f2f22af..ac7c1c7 100644 --- a/assets/maps/sion/metadata.json +++ b/assets/maps/sion/metadata.json @@ -2,7 +2,7 @@ "name": "Sion, Valais, Switzerland", "attribution": "Federal Office of Topography swisstopo", "sources": [ - "ch.swisstopo.swissalti3d (2m DTM, Open Government Data)", + "ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)", "ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)" ], "stacItems": [ @@ -27,24 +27,33 @@ "swissbuildings3d_3_0_2020_1306-21", "swissbuildings3d_3_0_2020_1306-23" ], + "demAssetHash": "a0dae3310058004e43a071290b3972ae4e0919e0958be5ec56320ea1a204c5de", "crs": "EPSG:2056", "originE": 2592614.0, "originN": 1118514.0, "centerE": 2594150.0, "centerN": 1120050.0, "baseElevationM": 483.41, - "minY": -5.863, - "maxY": 304.92, - "reliefM": 310.783, + "minY": -5.885, + "maxY": 304.957, + "reliefM": 310.841, "sizeMeters": 3072.0, - "tileGrid": 6, - "tileSizeMeters": 512.0, - "gridRes": 1025, - "cellSizeMeters": 3.0, - "heightmapFormat": "float32_le_row_major", + "tileGrid": 16, + "tileSizeMeters": 192.0, + "buildingTileGrid": 6, + "buildingTileSizeMeters": 512.0, + "gridRes": 6145, + "cellSizeMeters": 0.5, + "heightmapFile": "heightmap_05m.u16z", + "heightmapFormat": "rdhm_v2_u16_zigzag_zlib", + "heightmapMinY": -5.884674072265625, + "heightmapScale": 0.004743136931210756, "surfaceTexture": "terrain_surface.png", - "surfaceTextureSize": 2048, + "surfaceTextureSize": 4096, "surfaceTextureFormat": "png_rgb_north_to_south_west_to_east", + "surfaceMaskTexture": "terrain_surface_mask.png", + "surfaceMaskTextureSize": 2048, + "surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water", "collisionFormat": { "magic": "RCOL", "version": 1, diff --git a/assets/maps/sion/terrain_surface.png b/assets/maps/sion/terrain_surface.png index e240d47..88ec3f2 100644 Binary files a/assets/maps/sion/terrain_surface.png and b/assets/maps/sion/terrain_surface.png differ diff --git a/assets/maps/sion/terrain_surface_mask.png b/assets/maps/sion/terrain_surface_mask.png new file mode 100644 index 0000000..eeac085 Binary files /dev/null and b/assets/maps/sion/terrain_surface_mask.png differ diff --git a/client/Main.cs b/client/Main.cs index bb1432f..52496cb 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -508,22 +508,27 @@ public partial class Main : Node3D private void EnsureMenuSionBackdrop() { _menuSionData ??= SionMapLoader.Load(); - _menuSionTerrain ??= TerrainField.LoadHeightmap( + _menuSionTerrain ??= TerrainField.LoadSharedHeightmap( _menuSionData.Metadata.SizeMeters, _menuSionData.Metadata.GridRes, - _menuSionData.Heights, + _menuSionData.Metadata.TileGrid, + _menuSionData.BaseDem, + _menuSionData.BaseDemMinY, + _menuSionData.BaseDemScale, _menuSionData.Metadata.MinY, _menuSionData.Metadata.MaxY, 42UL); - _terrain.Visible = false; + _terrain.Visible = true; + _terrain.Sync(_menuSionTerrain, _menuSionData); _sionMap.Visible = true; _arena.Visible = false; _dropReticleMesh.Visible = false; _camera.Far = 4200f; _atmosphere.ApplyMap(ArenaMapKind.Sion); - _sionMap.EnsureBuilt(_menuSionData, _menuSionTerrain); + _sionMap.EnsureBuilt(_menuSionData); UpdateLobbyOrMenuOrbitCamera(ArenaMapKind.Sion, _menuSionTerrain); + _terrain.UpdateTileLod(_camera.GlobalPosition); _sionMap.UpdateLod(_camera.GlobalPosition); } @@ -870,11 +875,14 @@ public partial class Main : Node3D bool inLobby = _screenMode == ClientScreenMode.Lobby || state.Phase == MatchPhase.Lobby; + _terrain.Visible = true; + _terrain.InvalidateAll(); + _terrain.Sync(state.Terrain, state.SionMap); + if (_mapKind == ArenaMapKind.Sion && state.SionMap is not null) { - _terrain.Visible = false; _sionMap.Visible = true; - _sionMap.EnsureBuilt(state.SionMap, state.Terrain); + _sionMap.EnsureBuilt(state.SionMap); if (!inLobby) { _arena.Sync(_session, _elapsedSeconds, 0f, 1f); @@ -884,14 +892,12 @@ public partial class Main : Node3D { UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain); } + _terrain.UpdateTileLod(_camera.GlobalPosition); _sionMap.UpdateLod(_camera.GlobalPosition); } else { _sionMap.Visible = false; - _terrain.Visible = true; - _terrain.InvalidateAll(); - _terrain.Sync(state.Terrain); if (!inLobby) { _arena.Sync(_session, _elapsedSeconds, 0f, 1f); @@ -1334,19 +1340,13 @@ public partial class Main : Node3D { _frameEvents.Clear(); _session.DrainSimEvents(_frameEvents); - if (_mapKind == ArenaMapKind.Desert) - { - _terrain.Sync(_session.ViewState.Terrain); - } + _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap); UpdateLobbyOrMenuOrbitCamera(_mapKind, _session.ViewState.Terrain); + _terrain.UpdateTileLod(_camera.GlobalPosition); if (_mapKind == ArenaMapKind.Sion) { _sionMap.UpdateLod(_camera.GlobalPosition); } - else - { - _terrain.UpdateTileLod(_camera.GlobalPosition); - } _lobbyScreen.Sync(_session); return; } @@ -1361,10 +1361,7 @@ public partial class Main : Node3D } double toMs = 1000.0 / Stopwatch.Frequency; long tt0 = Stopwatch.GetTimestamp(); - if (_mapKind == ArenaMapKind.Desert) - { - _terrain.Sync(_session.ViewState.Terrain); - } + _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap); long tt1 = Stopwatch.GetTimestamp(); _arena.Sync(_session, _elapsedSeconds, (float)delta, alpha); DrainAndFanSimEvents((float)delta, alpha); @@ -1375,14 +1372,11 @@ public partial class Main : Node3D long tc0 = Stopwatch.GetTimestamp(); UpdateCamera((float)delta, alpha); _audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha); + _terrain.UpdateTileLod(_camera.GlobalPosition); if (_mapKind == ArenaMapKind.Sion) { _sionMap.UpdateLod(_camera.GlobalPosition); } - else - { - _terrain.UpdateTileLod(_camera.GlobalPosition); - } long th0 = Stopwatch.GetTimestamp(); var localP = _session.LocalContender; float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f; @@ -1424,22 +1418,16 @@ public partial class Main : Node3D } else { - if (_mapKind == ArenaMapKind.Desert) - { - _terrain.Sync(_session.ViewState.Terrain); - } + _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap); _arena.Sync(_session, _elapsedSeconds, (float)delta, alpha); DrainAndFanSimEvents((float)delta, alpha); UpdateCamera((float)delta, alpha); _audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha); + _terrain.UpdateTileLod(_camera.GlobalPosition); if (_mapKind == ArenaMapKind.Sion) { _sionMap.UpdateLod(_camera.GlobalPosition); } - else - { - _terrain.UpdateTileLod(_camera.GlobalPosition); - } var localP = _session.LocalContender; float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f; _hud.ConsumeEvents(_frameEvents, _session.LocalContenderId, coreRatio, localP.MaxThermalRatio); @@ -1513,7 +1501,7 @@ public partial class Main : Node3D internal Color SampleCurrentMapGroundTint(float worldX, float worldZ) => _mapKind == ArenaMapKind.Sion - ? _sionMap.SampleGroundTint(worldX, worldZ) + ? _terrain.SampleGroundTint(worldX, worldZ) : DesertDustTint; private System.Numerics.Vector3? ResolveLiveWalkerFootWorld(bool isContender, int id, int legIndex) @@ -1601,7 +1589,7 @@ public partial class Main : Node3D } if (_mapKind == ArenaMapKind.Sion) { - GD.Print($"SionMap: chunks={_sionMap.TerrainChunkCount} tiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}"); + GD.Print($"SionMap: terrainTiles={_terrain.BakedTileCount} gpuScarSlots={_terrain.ActiveGpuScarSlots} bldgTiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}"); } foreach (var kv in _arena.AssetCache.Vehicles) { @@ -2076,7 +2064,7 @@ public partial class Main : Node3D var pt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z); float distFromOrigin = origin.DistanceTo(pt); - if (hit.StableId < ContenderStableIdBase) + if (ArenaSession.IsStaticWorldStableId(hit.StableId)) { if (distFromOrigin < hitDist) { diff --git a/client/SionMapRenderer.cs b/client/SionMapRenderer.cs index 135ae4e..40f26ef 100644 --- a/client/SionMapRenderer.cs +++ b/client/SionMapRenderer.cs @@ -7,17 +7,15 @@ using RustToDust.Core; namespace RustToDust.Client; /// -/// 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 (<= 650m), LOD2 (650m..2200m), and culled (> 2200m), -/// with shadow casting restricted to <= 450m and shared PBR materials across all tiles. +/// Renders Sion, Switzerland legacy building tiles (swapping cleanly between LOD1 <= 520m, LOD2 520..2200m, +/// and culled > 2200m). Terrain rendering is unified in . +/// (This class is scheduled for deletion in Cut 13c when WorldCityRenderer lands.) /// public partial class SionMapRenderer : Node3D { public const float Lod1DistanceM = 520f; public const float CullDistanceM = 2200f; public const float ShadowDistanceM = 360f; - private const int ChunkGridVerts = 129; // 128 quads per 512m chunk (4m spacing) private sealed class BuildingTileEntry { @@ -30,26 +28,17 @@ public partial class SionMapRenderer : Node3D public required MeshInstance3D Instance; } - private const int GroundTintGridSize = 128; - private static readonly Color NeutralAlpineDustTint = new(0.56f, 0.53f, 0.46f, 1.0f); - - private readonly List _terrainChunks = new(36); private readonly List _buildingTiles = new(36); private readonly Dictionary _sharedBuildingMaterials = new(StringComparer.Ordinal); private string? _builtForDir; - private ShaderMaterial? _terrainMat; - private ImageTexture? _surfaceTex; - private Color[]? _groundTintGrid; - private float _groundTintSizeM; 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) + public void EnsureBuilt(SionMapData sion) { if (IsBuilt && string.Equals(_builtForDir, sion.DirectoryPath, StringComparison.OrdinalIgnoreCase)) { @@ -58,9 +47,6 @@ public partial class SionMapRenderer : Node3D ClearBuilt(); _builtForDir = sion.DirectoryPath; - - BuildTerrainMaterial(sion); - BuildTerrainChunks(sion, terrain); BuildBuildingTiles(sion); IsBuilt = true; } @@ -124,186 +110,6 @@ public partial class SionMapRenderer : Node3D 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}"); - } - - // Downsample CPU copy once for zero-readback terrain-tinted dust & impact plumes - var tintImg = (Image)img.Duplicate(); - tintImg.Resize(GroundTintGridSize, GroundTintGridSize, Image.Interpolation.Bilinear); - var grid = new Color[GroundTintGridSize * GroundTintGridSize]; - for (int y = 0; y < GroundTintGridSize; y++) - { - for (int x = 0; x < GroundTintGridSize; x++) - { - Color c = tintImg.GetPixel(x, y); - grid[y * GroundTintGridSize + x] = new Color( - Math.Clamp(c.R + 0.11f, 0.20f, 0.90f), - Math.Clamp(c.G + 0.11f, 0.20f, 0.88f), - Math.Clamp(c.B + 0.10f, 0.18f, 0.84f), - 1.0f); - } - } - _groundTintGrid = grid; - _groundTintSizeM = sion.Metadata.SizeMeters; - - 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; - - // 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, 480.0, dist), 0.12, 1.0); - float macro = (value_noise(v_world_pos.xz * 0.28) - 0.5) * 0.07; - float grit = (hash21(floor(v_world_pos.xz * 8.0)) - 0.5) * 0.045; - - float slope = 1.0 - clamp(v_world_normal.y, 0.0, 1.0); - vec3 col = clamp(base_col * (1.0 + macro * 1.4 + grit * 1.6 * near_fade), vec3(0.0), vec3(1.0)); - ALBEDO = col; - ROUGHNESS = mix(0.88, 0.96, slope); - METALLIC = 0.02; - } - """ - }; - - _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 terrain 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; @@ -498,47 +304,8 @@ public partial class SionMapRenderer : Node3D return (defaultKey, defMat); } - public Color SampleGroundTint(float worldX, float worldZ) - { - Color[]? grid = _groundTintGrid; - float sizeM = _groundTintSizeM; - if (grid is null || sizeM <= 1f || !float.IsFinite(worldX) || !float.IsFinite(worldZ)) - { - return NeutralAlpineDustTint; - } - - float half = sizeM * 0.5f; - float u = (worldX + half) / sizeM; - float v = (worldZ + half) / sizeM; - if (u < 0f || u > 1f || v < 0f || v > 1f) - { - return NeutralAlpineDustTint; - } - - float fx = u * (GroundTintGridSize - 1); - float fy = v * (GroundTintGridSize - 1); - int x0 = Math.Clamp((int)MathF.Floor(fx), 0, GroundTintGridSize - 1); - int y0 = Math.Clamp((int)MathF.Floor(fy), 0, GroundTintGridSize - 1); - int x1 = Math.Min(x0 + 1, GroundTintGridSize - 1); - int y1 = Math.Min(y0 + 1, GroundTintGridSize - 1); - float tx = fx - x0; - float ty = fy - y0; - - Color c00 = grid[y0 * GroundTintGridSize + x0]; - Color c10 = grid[y0 * GroundTintGridSize + x1]; - Color c01 = grid[y1 * GroundTintGridSize + x0]; - Color c11 = grid[y1 * GroundTintGridSize + x1]; - return c00.Lerp(c10, tx).Lerp(c01.Lerp(c11, tx), ty); - } - 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(); @@ -546,10 +313,6 @@ public partial class SionMapRenderer : Node3D _buildingTiles.Clear(); _sharedBuildingMaterials.Clear(); - _terrainMat = null; - _surfaceTex = null; - _groundTintGrid = null; - _groundTintSizeM = 0f; _builtForDir = null; IsBuilt = false; ActiveLod1TileCount = 0; diff --git a/client/TerrainRenderer.cs b/client/TerrainRenderer.cs index 92e4a7a..21e59a1 100644 --- a/client/TerrainRenderer.cs +++ b/client/TerrainRenderer.cs @@ -1,164 +1,265 @@ using System; using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; using Godot; using RustToDust.Core; namespace RustToDust.Client; /// -/// Top-down orthographic SubViewport brush-to-tile PBR + displacement terrain baker. -/// Maintains an 8x8 grid of 192m x 192m terrain tiles covering [-768, +768] in X and Z. -/// Only tiles whose changed are re-baked. +/// Unified Layer-0 + live GPU brush compute terrain renderer for both Desert (8x8) and Sion (16x16). +/// Replaces permanent SubViewports and CanvasItem brush shaders with one compute shader +/// (terrain_tile_bake.glsl) writing sparse 388x388 delta slots +/// in an LRU pool (max 96 active scarred tiles; untouched tiles bind a 1x1 neutral fallback), +/// rendered via 3 exact-ratio shared PlaneMeshes (192/48/12) with zero T-junction edge morphing. /// public partial class TerrainRenderer : Node3D { - private const int ViewportSize = 256; - private const float InnerTexelSpan = 253.0f; // texel 1 center (1.5) .. texel 254 center (254.5) - private const float GutterCenterOffset = 1.5f; - private const float PixelsPerMeter = InnerTexelSpan / TerrainField.TileSize; - private const float HeightSpan = TerrainField.MaxWorldHeight - TerrainField.MinWorldHeight; - private const float BaseHeightNorm = (0f - TerrainField.MinWorldHeight) / HeightSpan; + public const int DeltaTexSize = 388; + public const float InnerTexelSpan = 384.0f; + public const float GutterStartIndex = 2.0f; + public const float GutterCenterOffset = 2.5f; + public const int MaxGpuScarTiles = 96; + public const int MaxDirtyRebakesPerSync = 4; + private const int BrushStrideBytes = 48; + private const int PushConstantBytes = 48; + private const int MaxSsboBrushes = 8192; + private const int GroundTintGridSize = 128; - private static readonly Color HeightClearColor = new(BaseHeightNorm, 0.88f, 0.0f, 1.0f); - private static readonly Color AlbedoClearColor = new(0.69f, 0.50f, 0.31f, 1.0f); - private static readonly Vector2[] BrushUv = + private static readonly Color DesertAlbedoClear = new(0.69f, 0.50f, 0.31f, 1.0f); + private static readonly Color NeutralAlpineDustTint = new(0.56f, 0.53f, 0.46f, 1.0f); + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct GpuBrush { - new(0f, 0f), - new(1f, 0f), - new(1f, 1f), - new(0f, 1f) - }; - private static readonly Vector2[] UnitQuadPoly = + public Vector4 PosRot; + public Vector4 RadDelta; + public Vector4 MatColor; + } + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct TileBakePush { - new(-1f, -1f), - new(1f, -1f), - new(1f, 1f), - new(-1f, 1f) - }; - private static readonly Vector2[] ClearQuadPoly = - { - new(0f, 0f), - new(ViewportSize, 0f), - new(ViewportSize, ViewportSize), - new(0f, ViewportSize) - }; + public Vector4 TileOriginAndSpan; + public Vector4 BaseColorAndGutter; + public uint BrushStart; + public uint BrushCount; + public uint TexSize; + public uint IsSion; + } private sealed class TileNode { - public SubViewport HeightViewport = null!; - public Node2D HeightCanvas = null!; - public readonly List HeightQuads = new(64); - public SubViewport AlbedoViewport = null!; - public Node2D AlbedoCanvas = null!; - public readonly List AlbedoQuads = new(48); + public int Tx; + public int Tz; + public float OriginX; + public float OriginZ; public MeshInstance3D SurfaceMesh = null!; - public int BakedVersion = -1; + public ShaderMaterial SurfaceMat = null!; + public int BakedStructuralVersion = -1; + public int BakedVisualVersion = -1; + public int LruSlotIndex = -1; + public float TileQuads = 192f; } - private readonly TileNode[,] _tiles = new TileNode[TerrainField.TileGridCount, TerrainField.TileGridCount]; + private sealed class LruSlot + { + public int SlotIndex; + public Rid DeltaHeightRid; + public Rid DeltaAlbedoRid; + public Rid UniformSetRid; + public Texture2Drd DeltaHeightTex = null!; + public Texture2Drd DeltaAlbedoTex = null!; + public int AssignedTileIndex = -1; + public ulong LastUsedSeq; + public bool IsRdAllocated; + } + + private sealed class PendingBakeJob + { + public int SlotIndex; + public float TileOriginX; + public float TileOriginZ; + public float TileSize; + public bool IsSion; + public GpuBrush[] Brushes = Array.Empty(); + } + + private TileNode[,]? _tiles; + private int _gridCount; + private float _tileSize = TerrainField.TileSize; + private float _mapSize = TerrainField.ArenaSize; + + private readonly LruSlot[] _lruPool = new LruSlot[MaxGpuScarTiles]; + private ulong _lruClock; + private PlaneMesh _nearPlaneMesh = null!; + private PlaneMesh _midPlaneMesh = null!; private PlaneMesh _farPlaneMesh = null!; - private ImageTexture _white1x1 = null!; - private Shader _clearShader = null!; - private Shader _brushAddShader = null!; - private Shader _brushSubShader = null!; - private Shader _brushAlbedoShader = null!; private Shader _surfaceShader = null!; - private ShaderMaterial _heightClearMat = null!; - private ShaderMaterial _albedoClearMat = null!; - private readonly Dictionary<(Shader Shader, int Kind, float HeightDelta), ShaderMaterial> _heightBrushMatCache = new(); - private readonly Dictionary<(int Kind, float R, float G, float B, float HeightDelta), ShaderMaterial> _albedoBrushMatCache = new(); - private const int MaxDirtyRebakesPerSync = 2; + + private ImageTexture _neutralDeltaHeightTex = null!; + private ImageTexture _neutralDeltaAlbedoTex = null!; + private ImageTexture _zeroDem1x1Tex = null!; + private ImageTexture _whiteSurface1x1Tex = null!; + private ImageTexture _zeroMask1x1Tex = null!; + + private Texture2Drd? _sionDemTexRd; + private Rid _sionDemRid; + private byte[]? _pendingSionDemUpload; + private int _pendingSionDemRes; + private ImageTexture? _sionSurfaceTex; + private ImageTexture? _sionMaskTex; + private Color[]? _groundTintGrid; + private float _groundTintSizeM; + private string? _loadedSionDir; + private float _sionDemMinY; + private float _sionDemScaleSpan; + private TerrainField? _lastTerrain; + private SionMapData? _lastSionMap; private int _rebakeCursor; + // Render-thread compute state + private readonly object _jobLock = new(); + private readonly List _pendingJobs = new(); + private readonly byte[] _ssboStagingBytes = new byte[MaxSsboBrushes * BrushStrideBytes]; + private readonly byte[] _pushBytes = new byte[PushConstantBytes]; + private volatile bool _hasQueuedRdFlush; + private bool _rdInitialized; + private bool _rdFailed; + private Rid _bakeShaderRid; + private Rid _bakePipeRid; + private Rid _brushSsboRid; + + // Synchronous test readback state (main thread calls ForceSync + readback via CallOnRenderThread) + private Rid _readbackTargetRid; + private byte[]? _readbackResult; + public int BakedTileCount { get; private set; } public int DirtyRebakes { get; private set; } + public int ActiveGpuScarSlots + { + get + { + int count = 0; + for (int i = 0; i < _lruPool.Length; i++) + { + if (_lruPool[i] is not null && _lruPool[i].AssignedTileIndex >= 0) + { + count++; + } + } + return count; + } + } public static double PerfBakeTileMs; public static int PerfBakeTileCalls; public override void _Ready() { - var whiteImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); - whiteImg.SetPixel(0, 0, Colors.White); - _white1x1 = ImageTexture.CreateFromImage(whiteImg); + var neutralHImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah); + neutralHImg.SetPixel(0, 0, new Color(0f, 0.88f, 0f, 0f)); + _neutralDeltaHeightTex = ImageTexture.CreateFromImage(neutralHImg); - _nearPlaneMesh = new PlaneMesh + var neutralAImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + neutralAImg.SetPixel(0, 0, new Color(DesertAlbedoClear.R, DesertAlbedoClear.G, DesertAlbedoClear.B, 1.0f)); + _neutralDeltaAlbedoTex = ImageTexture.CreateFromImage(neutralAImg); + + var zeroDemImg = Image.CreateEmpty(1, 1, false, Image.Format.Rh); + zeroDemImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 1f)); + _zeroDem1x1Tex = ImageTexture.CreateFromImage(zeroDemImg); + + var surf1x1Img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + surf1x1Img.SetPixel(0, 0, Colors.White); + _whiteSurface1x1Tex = ImageTexture.CreateFromImage(surf1x1Img); + + var mask1x1Img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + mask1x1Img.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f)); + _zeroMask1x1Tex = ImageTexture.CreateFromImage(mask1x1Img); + + _surfaceShader = GD.Load("res://terrain_surface.gdshader") + ?? throw new InvalidOperationException("Failed to load res://terrain_surface.gdshader"); + + for (int i = 0; i < MaxGpuScarTiles; i++) { - Size = new Vector2(TerrainField.TileSize, TerrainField.TileSize), - SubdivideWidth = 64, - SubdivideDepth = 64 - }; - _farPlaneMesh = new PlaneMesh + _lruPool[i] = new LruSlot + { + SlotIndex = i, + DeltaHeightTex = new Texture2Drd(), + DeltaAlbedoTex = new Texture2Drd() + }; + } + } + + public override void _ExitTree() + { + base._ExitTree(); + if (RenderingServer.GetRenderingDevice() is not null) { - Size = new Vector2(TerrainField.TileSize, TerrainField.TileSize), - SubdivideWidth = 16, - SubdivideDepth = 16 - }; - - _clearShader = new Shader - { - Code = """ - shader_type canvas_item; - render_mode blend_disabled; - uniform vec4 clear_vec = vec4(0.0, 0.0, 0.0, 1.0); - void fragment() { - COLOR = clear_vec; - } - """ - }; - _brushAddShader = GD.Load("res://terrain_brush.gdshader"); - _brushSubShader = GD.Load("res://terrain_brush_sub.gdshader"); - _brushAlbedoShader = GD.Load("res://terrain_brush_albedo.gdshader"); - _surfaceShader = GD.Load("res://terrain_surface.gdshader"); - - _heightClearMat = new ShaderMaterial { Shader = _clearShader }; - _heightClearMat.SetShaderParameter("clear_vec", new Vector4(HeightClearColor.R, HeightClearColor.G, HeightClearColor.B, HeightClearColor.A)); - _albedoClearMat = new ShaderMaterial { Shader = _clearShader }; - _albedoClearMat.SetShaderParameter("clear_vec", new Vector4(AlbedoClearColor.R, AlbedoClearColor.G, AlbedoClearColor.B, AlbedoClearColor.A)); - - BuildTileGrid(); + RenderingServer.CallOnRenderThread(Callable.From(DisposeRdResourcesOnRenderThread)); + RenderingServer.ForceSync(); + } } public void InvalidateAll() { - for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + if (_tiles is not null) { - for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + for (int tz = 0; tz < _gridCount; tz++) { - _tiles[tx, tz].BakedVersion = -1; + for (int tx = 0; tx < _gridCount; tx++) + { + var t = _tiles[tx, tz]; + if (t is null) continue; + t.BakedStructuralVersion = -1; + t.BakedVisualVersion = -1; + ReleaseTileSlot(t); + } } } BakedTileCount = 0; DirtyRebakes = 0; + _rebakeCursor = 0; _lastTerrain = null; } - public void Sync(TerrainField terrain) + public void Sync(TerrainField terrain, SionMapData? sionMap = null) { - if (!ReferenceEquals(_lastTerrain, terrain)) + bool mapChanged = !ReferenceEquals(_lastTerrain, terrain) || !ReferenceEquals(_lastSionMap, sionMap); + if (mapChanged) { + EnsureGridAllocated(terrain, sionMap); InvalidateAll(); _lastTerrain = terrain; + _lastSionMap = sionMap; } - const int totalTiles = TerrainField.TileGridCount * TerrainField.TileGridCount; - - // 1. Always bake uninitialized tiles and structural/crater dirty tiles immediately - ulong structuralMask = terrain.StructuralDirtyTileMask; - for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + if (_tiles is null) { - for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + return; + } + + int grid = terrain.TileGridCount; + int totalTiles = grid * grid; + bool isSion = sionMap is not null; + + // 1. Structural dirty tiles and uninitialized tiles bake immediately (never throttled) + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) { var tile = _tiles[tx, tz]; - int version = terrain.TileVersions[tx, tz]; - bool isUninitialized = tile.BakedVersion < 0 && tile.BakedVersion != version; - ulong bit = 1UL << (tz * TerrainField.TileGridCount + tx); - bool isStructuralDirty = (structuralMask & bit) != 0UL && tile.BakedVersion != version; - if (isUninitialized || isStructuralDirty) + int structVer = terrain.StructuralTileVersions[tx, tz]; + int visVer = terrain.VisualTileVersions[tx, tz]; + bool isUninit = tile.BakedVisualVersion < 0; + bool isStructDirty = tile.BakedStructuralVersion != structVer; + + if (isUninit || isStructDirty) { - BakeTile(tx, tz, tile, terrain); - if (isUninitialized) + EnqueueTileBake(tx, tz, tile, terrain, isSion); + if (isUninit) { BakedTileCount++; } @@ -166,67 +267,109 @@ public partial class TerrainRenderer : Node3D { DirtyRebakes++; } - tile.BakedVersion = version; - terrain.ClearStructuralDirtyTile(tx, tz); + tile.BakedStructuralVersion = structVer; + tile.BakedVisualVersion = visVer; } } } - // 2. Budget remaining passive dynamic tile rebakes (tracks/scorch) to <= 2 per Sync in round-robin order + // 2. Remaining passive visual dirty tiles (Tracks / Scorch) throttled to <= MaxDirtyRebakesPerSync (4) int rebakedThisSync = 0; - bool anyRemainingDirty = false; int startCursor = _rebakeCursor; for (int step = 0; step < totalTiles; step++) { int idx = (startCursor + step) % totalTiles; - int tx = idx % TerrainField.TileGridCount; - int tz = idx / TerrainField.TileGridCount; + int tx = idx % grid; + int tz = idx / grid; var tile = _tiles[tx, tz]; - int version = terrain.TileVersions[tx, tz]; - if (tile.BakedVersion != version) + int visVer = terrain.VisualTileVersions[tx, tz]; + if (tile.BakedVisualVersion != visVer) { if (rebakedThisSync < MaxDirtyRebakesPerSync) { - BakeTile(tx, tz, tile, terrain); + EnqueueTileBake(tx, tz, tile, terrain, isSion); DirtyRebakes++; - tile.BakedVersion = version; + tile.BakedStructuralVersion = terrain.StructuralTileVersions[tx, tz]; + tile.BakedVisualVersion = visVer; rebakedThisSync++; _rebakeCursor = (idx + 1) % totalTiles; } else { - anyRemainingDirty = true; + break; } } } - if (!anyRemainingDirty) + DispatchPendingJobsIfNeeded(); + } + + public int CountPendingDirtyVisualTiles(TerrainField terrain) + { + if (_tiles is null || !ReferenceEquals(_lastTerrain, terrain)) { - terrain.ClearDirtyMask(); + return 0; } + int count = 0; + int grid = terrain.TileGridCount; + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + if (_tiles[tx, tz].BakedVisualVersion != terrain.VisualTileVersions[tx, tz]) + { + count++; + } + } + } + return count; } public void UpdateTileLod(Vector3 camPos) { - const float nearRadiusSq = 240f * 240f; - const float shadowRadiusSq = 340f * 340f; - for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + if (_tiles is null) { - for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + return; + } + + const float nearRadiusSq = 220f * 220f; + const float midRadiusSq = 780f * 780f; + const float shadowRadiusSq = 360f * 360f; + float halfTile = _tileSize * 0.5f; + + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) { var tile = _tiles[tx, tz]; - if (tile?.SurfaceMesh is null) - { - continue; - } - Vector3 pos = tile.SurfaceMesh.Position; - float dx = pos.X - camPos.X; - float dz = pos.Z - camPos.Z; + float cx = tile.OriginX + halfTile; + float cz = tile.OriginZ + halfTile; + float dx = cx - camPos.X; + float dz = cz - camPos.Z; float d2 = dx * dx + dz * dz; - PlaneMesh desired = d2 <= nearRadiusSq ? _nearPlaneMesh : _farPlaneMesh; - if (!ReferenceEquals(tile.SurfaceMesh.Mesh, desired)) + + PlaneMesh desiredMesh; + float quads; + if (d2 <= nearRadiusSq) { - tile.SurfaceMesh.Mesh = desired; + desiredMesh = _nearPlaneMesh; + quads = 192f; + } + else if (d2 <= midRadiusSq) + { + desiredMesh = _midPlaneMesh; + quads = 48f; + } + else + { + desiredMesh = _farPlaneMesh; + quads = 12f; + } + + tile.TileQuads = quads; + if (!ReferenceEquals(tile.SurfaceMesh.Mesh, desiredMesh)) + { + tile.SurfaceMesh.Mesh = desiredMesh; } var desiredShadow = d2 <= shadowRadiusSq ? GeometryInstance3D.ShadowCastingSetting.On @@ -237,199 +380,384 @@ public partial class TerrainRenderer : Node3D } } } + + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) + { + var tile = _tiles[tx, tz]; + float qSelf = tile.TileQuads; + float qLeft = tx > 0 ? _tiles[tx - 1, tz].TileQuads : qSelf; + float qRight = tx < _gridCount - 1 ? _tiles[tx + 1, tz].TileQuads : qSelf; + float qTop = tz > 0 ? _tiles[tx, tz - 1].TileQuads : qSelf; + float qBottom = tz < _gridCount - 1 ? _tiles[tx, tz + 1].TileQuads : qSelf; + + tile.SurfaceMat.SetShaderParameter("tile_quads", qSelf); + tile.SurfaceMat.SetShaderParameter("neighbor_quads", new Vector4(qLeft, qRight, qTop, qBottom)); + } + } + } + + public Color SampleGroundTint(float worldX, float worldZ) + { + Color[]? grid = _groundTintGrid; + float sizeM = _groundTintSizeM; + if (grid is null || sizeM <= 1f || !float.IsFinite(worldX) || !float.IsFinite(worldZ)) + { + return NeutralAlpineDustTint; + } + + float half = sizeM * 0.5f; + float u = (worldX + half) / sizeM; + float v = (worldZ + half) / sizeM; + if (u < 0f || u > 1f || v < 0f || v > 1f) + { + return NeutralAlpineDustTint; + } + + float fx = u * (GroundTintGridSize - 1); + float fy = v * (GroundTintGridSize - 1); + int x0 = Math.Clamp((int)MathF.Floor(fx), 0, GroundTintGridSize - 1); + int y0 = Math.Clamp((int)MathF.Floor(fy), 0, GroundTintGridSize - 1); + int x1 = Math.Min(x0 + 1, GroundTintGridSize - 1); + int y1 = Math.Min(y0 + 1, GroundTintGridSize - 1); + float tx = fx - x0; + float ty = fy - y0; + + Color c00 = grid[y0 * GroundTintGridSize + x0]; + Color c10 = grid[y0 * GroundTintGridSize + x1]; + Color c01 = grid[y1 * GroundTintGridSize + x0]; + Color c11 = grid[y1 * GroundTintGridSize + x1]; + return c00.Lerp(c10, tx).Lerp(c01.Lerp(c11, tx), ty); } public bool TryGetHeightImageFormat(out Image.Format format) { format = Image.Format.Max; - var img = _tiles[0, 0]?.HeightViewport?.GetTexture()?.GetImage(); - if (img is null || img.IsEmpty()) + if (RenderingServer.GetRenderingDevice() is null || _rdFailed) { return false; } - format = img.GetFormat(); + format = Image.Format.Rgbah; return true; } public bool TrySampleBakedHeight(float wx, float wz, out float bakedHeight) { bakedHeight = 0f; - float cx = Math.Clamp(wx, -TerrainField.HalfExtent, TerrainField.HalfExtent); - float cz = Math.Clamp(wz, -TerrainField.HalfExtent, TerrainField.HalfExtent); - TerrainField.WorldToTile(cx, cz, out int tx, out int tz); - - var tile = _tiles[tx, tz]; - var tex = tile?.HeightViewport?.GetTexture(); - var img = tex?.GetImage(); - if (img is null || img.IsEmpty() || img.GetWidth() < ViewportSize || img.GetHeight() < ViewportSize) + if (_lastTerrain is not { } terrain || _tiles is null) + { + return false; + } + if (RenderingServer.GetRenderingDevice() is null || _rdFailed) { return false; } - float tileMinX = -TerrainField.HalfExtent + tx * TerrainField.TileSize; - float tileMinZ = -TerrainField.HalfExtent + tz * TerrainField.TileSize; - float px = GutterCenterOffset + (cx - tileMinX) * PixelsPerMeter; - float py = GutterCenterOffset + (cz - tileMinZ) * PixelsPerMeter; + if (_hasQueuedRdFlush) + { + RenderingServer.ForceSync(); + } + + float half = terrain.MapHalfExtent; + float cx = Math.Clamp(wx, -half, half); + float cz = Math.Clamp(wz, -half, half); + terrain.MapWorldToTile(cx, cz, out int tx, out int tz); + + var tile = _tiles[tx, tz]; + float baseH = terrain.SampleBaseHeight(cx, cz); + + if (tile.LruSlotIndex < 0) + { + bakedHeight = Math.Clamp(baseH, terrain.MapMinHeight, terrain.MapMaxHeight); + return true; + } + + var slot = _lruPool[tile.LruSlotIndex]; + if (!slot.IsRdAllocated || !slot.DeltaHeightRid.IsValid) + { + return false; + } + + _readbackTargetRid = slot.DeltaHeightRid; + _readbackResult = null; + RenderingServer.CallOnRenderThread(Callable.From(ReadbackTextureOnRenderThread)); + RenderingServer.ForceSync(); + + byte[]? raw = _readbackResult; + if (raw is null || raw.Length < DeltaTexSize * DeltaTexSize * 8) + { + return false; + } + + float pixelsPerMeter = InnerTexelSpan / _tileSize; + float px = GutterCenterOffset + (cx - tile.OriginX) * pixelsPerMeter; + float py = GutterCenterOffset + (cz - tile.OriginZ) * pixelsPerMeter; + float fx = Math.Clamp(px - 0.5f, 0f, DeltaTexSize - 1.0001f); + float fy = Math.Clamp(py - 0.5f, 0f, DeltaTexSize - 1.0001f); - float fx = Math.Clamp(px - 0.5f, 0f, ViewportSize - 1.0001f); - float fy = Math.Clamp(py - 0.5f, 0f, ViewportSize - 1.0001f); int x0 = (int)MathF.Floor(fx); int y0 = (int)MathF.Floor(fy); - int x1 = Math.Min(x0 + 1, ViewportSize - 1); - int y1 = Math.Min(y0 + 1, ViewportSize - 1); + int x1 = Math.Min(x0 + 1, DeltaTexSize - 1); + int y1 = Math.Min(y0 + 1, DeltaTexSize - 1); float txFrac = fx - x0; float tyFrac = fy - y0; - var c00 = img.GetPixel(x0, y0); - if (c00.A < 0.5f) + float ReadHalfR(int x, int y) { - return false; + int byteOff = (y * DeltaTexSize + x) * 8; + return (float)BitConverter.ToHalf(raw, byteOff); } - var c10 = img.GetPixel(x1, y0); - var c01 = img.GetPixel(x0, y1); - var c11 = img.GetPixel(x1, y1); + float h00 = ReadHalfR(x0, y0); + float h10 = ReadHalfR(x1, y0); + float h01 = ReadHalfR(x0, y1); + float h11 = ReadHalfR(x1, y1); - float r = (c00.R * (1f - txFrac) + c10.R * txFrac) * (1f - tyFrac) + - (c01.R * (1f - txFrac) + c11.R * txFrac) * tyFrac; - bakedHeight = TerrainField.MinWorldHeight + Math.Clamp(r, 0f, 1f) * HeightSpan; + float deltaH = (h00 * (1f - txFrac) + h10 * txFrac) * (1f - tyFrac) + + (h01 * (1f - txFrac) + h11 * txFrac) * tyFrac; + + bakedHeight = Math.Clamp(baseH + deltaH, terrain.MapMinHeight, terrain.MapMaxHeight); return true; } - private void BuildTileGrid() + private void EnsureGridAllocated(TerrainField terrain, SionMapData? sionMap) { - for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + bool needsRebuild = _tiles is null || + _gridCount != terrain.TileGridCount || + MathF.Abs(_tileSize - terrain.MapTileSize) > 0.01f; + + if (sionMap is not null) { - for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + EnsureSionLayer0Resources(sionMap); + } + + if (needsRebuild) + { + if (_tiles is not null) { - var tile = new TileNode(); - - tile.HeightViewport = CreateOrthoViewport($"Tile_{tx}_{tz}_Height", useHdr: true, out var heightCanvas); - tile.HeightCanvas = heightCanvas; - heightCanvas.AddChild(CreateClearQuad(_heightClearMat, _white1x1)); - AddChild(tile.HeightViewport); - - tile.AlbedoViewport = CreateOrthoViewport($"Tile_{tx}_{tz}_Albedo", useHdr: false, out var albedoCanvas); - tile.AlbedoCanvas = albedoCanvas; - albedoCanvas.AddChild(CreateClearQuad(_albedoClearMat, _white1x1)); - AddChild(tile.AlbedoViewport); - - var mat = new ShaderMaterial { Shader = _surfaceShader }; - mat.SetShaderParameter("height_tex", tile.HeightViewport.GetTexture()); - mat.SetShaderParameter("albedo_tex", tile.AlbedoViewport.GetTexture()); - mat.SetShaderParameter("height_min", TerrainField.MinWorldHeight); - mat.SetShaderParameter("height_max", TerrainField.MaxWorldHeight); - mat.SetShaderParameter("tile_size", TerrainField.TileSize); - mat.SetShaderParameter("inner_span", InnerTexelSpan); - mat.SetShaderParameter("tex_size", (float)ViewportSize); - mat.SetShaderParameter("gutter_offset", GutterCenterOffset); - - float centerX = -TerrainField.HalfExtent + (tx + 0.5f) * TerrainField.TileSize; - float centerZ = -TerrainField.HalfExtent + (tz + 0.5f) * TerrainField.TileSize; - - tile.SurfaceMesh = new MeshInstance3D + for (int tz = 0; tz < _gridCount; tz++) { - Name = $"Tile_{tx}_{tz}_Mesh", - Mesh = _nearPlaneMesh, - MaterialOverride = mat, - Position = new Vector3(centerX, 0f, centerZ), - CustomAabb = new Aabb( - new Vector3(-TerrainField.TileSize * 0.5f, TerrainField.MinWorldHeight - 2f, -TerrainField.TileSize * 0.5f), - new Vector3(TerrainField.TileSize, HeightSpan + 4f, TerrainField.TileSize)) - }; - AddChild(tile.SurfaceMesh); + for (int tx = 0; tx < _gridCount; tx++) + { + var old = _tiles[tx, tz]; + if (old?.SurfaceMesh is not null && IsInstanceValid(old.SurfaceMesh)) + { + old.SurfaceMesh.QueueFree(); + } + } + } + } - _tiles[tx, tz] = tile; + _gridCount = terrain.TileGridCount; + _tileSize = terrain.MapTileSize; + _mapSize = terrain.MapSize; + + _nearPlaneMesh = new PlaneMesh + { + Size = new Vector2(_tileSize, _tileSize), + SubdivideWidth = 191, + SubdivideDepth = 191 + }; + _midPlaneMesh = new PlaneMesh + { + Size = new Vector2(_tileSize, _tileSize), + SubdivideWidth = 47, + SubdivideDepth = 47 + }; + _farPlaneMesh = new PlaneMesh + { + Size = new Vector2(_tileSize, _tileSize), + SubdivideWidth = 11, + SubdivideDepth = 11 + }; + + _tiles = new TileNode[_gridCount, _gridCount]; + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) + { + float originX = -terrain.MapHalfExtent + tx * _tileSize; + float originZ = -terrain.MapHalfExtent + tz * _tileSize; + var mat = new ShaderMaterial { Shader = _surfaceShader }; + var mi = new MeshInstance3D + { + Name = $"Tile_{tx}_{tz}_Mesh", + Mesh = _nearPlaneMesh, + MaterialOverride = mat, + Position = new Vector3(originX + _tileSize * 0.5f, 0f, originZ + _tileSize * 0.5f) + }; + AddChild(mi); + + _tiles[tx, tz] = new TileNode + { + Tx = tx, + Tz = tz, + OriginX = originX, + OriginZ = originZ, + SurfaceMesh = mi, + SurfaceMat = mat + }; + } + } + } + + bool isSion = sionMap is not null; + float minY = terrain.MapMinHeight; + float maxY = terrain.MapMaxHeight; + float span = MathF.Max(1f, maxY - minY); + + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) + { + var tile = _tiles![tx, tz]; + var mat = tile.SurfaceMat; + mat.SetShaderParameter("base_dem_tex", isSion && _sionDemTexRd is not null ? _sionDemTexRd : _zeroDem1x1Tex); + mat.SetShaderParameter("base_surface_tex", isSion && _sionSurfaceTex is not null ? _sionSurfaceTex : _whiteSurface1x1Tex); + mat.SetShaderParameter("base_mask_tex", isSion && _sionMaskTex is not null ? _sionMaskTex : _zeroMask1x1Tex); + mat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex); + mat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex); + mat.SetShaderParameter("dem_min_y", isSion ? _sionDemMinY : 0f); + mat.SetShaderParameter("dem_scale_span", isSion ? _sionDemScaleSpan : 0f); + mat.SetShaderParameter("dem_grid_res", isSion ? (float)sionMap!.Metadata.GridRes : 1f); + mat.SetShaderParameter("height_min", minY); + mat.SetShaderParameter("height_max", maxY); + mat.SetShaderParameter("map_size", _mapSize); + mat.SetShaderParameter("tile_origin_x", tile.OriginX); + mat.SetShaderParameter("tile_origin_z", tile.OriginZ); + mat.SetShaderParameter("tile_size", _tileSize); + mat.SetShaderParameter("inner_span", InnerTexelSpan); + mat.SetShaderParameter("tex_size", (float)DeltaTexSize); + mat.SetShaderParameter("gutter_center", GutterCenterOffset); + mat.SetShaderParameter("is_sion", isSion ? 1f : 0f); + + tile.SurfaceMesh.CustomAabb = new Aabb( + new Vector3(-_tileSize * 0.5f, minY - 2f, -_tileSize * 0.5f), + new Vector3(_tileSize, span + 4f, _tileSize)); } } } - private static SubViewport CreateOrthoViewport(string name, bool useHdr, out Node2D canvas) + private void EnsureSionLayer0Resources(SionMapData sionMap) { - var vp = new SubViewport + if (string.Equals(_loadedSionDir, sionMap.DirectoryPath, StringComparison.OrdinalIgnoreCase)) { - Name = name, - Size = new Vector2I(ViewportSize, ViewportSize), - Disable3D = true, - UseHdr2D = useHdr, - TransparentBg = false, - Snap2DTransformsToPixel = false, - Snap2DVerticesToPixel = false, - RenderTargetClearMode = SubViewport.ClearMode.Always, - RenderTargetUpdateMode = SubViewport.UpdateMode.Disabled - }; + return; + } + _loadedSionDir = sionMap.DirectoryPath; + _sionDemMinY = sionMap.BaseDemMinY; + _sionDemScaleSpan = 65535.0f * sionMap.BaseDemScale; - var cam = new Camera2D + string surfPath = Path.Combine(sionMap.DirectoryPath, sionMap.Metadata.SurfaceTexture); + if (!File.Exists(surfPath)) { - AnchorMode = Camera2D.AnchorModeEnum.FixedTopLeft, - Position = Vector2.Zero, - Enabled = true, - PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, - ProcessCallback = Camera2D.Camera2DProcessCallback.Physics - }; - vp.AddChild(cam); + throw new FileNotFoundException($"Missing Sion terrain surface texture: {surfPath}", surfPath); + } + var surfImg = Image.LoadFromFile(surfPath) + ?? throw new InvalidOperationException($"Failed to decode Sion terrain surface texture: {surfPath}"); - canvas = new Node2D { Name = "Canvas" }; - vp.AddChild(canvas); - return vp; + var tintImg = (Image)surfImg.Duplicate(); + tintImg.Resize(GroundTintGridSize, GroundTintGridSize, Image.Interpolation.Bilinear); + var grid = new Color[GroundTintGridSize * GroundTintGridSize]; + for (int y = 0; y < GroundTintGridSize; y++) + { + for (int x = 0; x < GroundTintGridSize; x++) + { + Color c = tintImg.GetPixel(x, y); + grid[y * GroundTintGridSize + x] = new Color( + Math.Clamp(c.R + 0.11f, 0.20f, 0.90f), + Math.Clamp(c.G + 0.11f, 0.20f, 0.88f), + Math.Clamp(c.B + 0.10f, 0.18f, 0.84f), + 1.0f); + } + } + _groundTintGrid = grid; + _groundTintSizeM = sionMap.Metadata.SizeMeters; + + surfImg.GenerateMipmaps(); + _sionSurfaceTex = ImageTexture.CreateFromImage(surfImg); + + string maskName = string.IsNullOrWhiteSpace(sionMap.Metadata.SurfaceMaskTexture) + ? "terrain_surface_mask.png" + : sionMap.Metadata.SurfaceMaskTexture; + string maskPath = Path.Combine(sionMap.DirectoryPath, maskName); + if (File.Exists(maskPath)) + { + var maskImg = Image.LoadFromFile(maskPath); + if (maskImg is not null && !maskImg.IsEmpty()) + { + maskImg.GenerateMipmaps(); + _sionMaskTex = ImageTexture.CreateFromImage(maskImg); + } + } + + if (RenderingServer.GetRenderingDevice() is not null) + { + _sionDemTexRd ??= new Texture2Drd(); + byte[] demBytes = new byte[sionMap.BaseDem.Length * 2]; + Buffer.BlockCopy(sionMap.BaseDem, 0, demBytes, 0, demBytes.Length); + _pendingSionDemUpload = demBytes; + _pendingSionDemRes = sionMap.Metadata.GridRes; + RenderingServer.CallOnRenderThread(Callable.From(UploadSionDemOnRenderThread)); + } } - private void BakeTile(int tx, int tz, TileNode tile, TerrainField terrain) + private void EnqueueTileBake(int tx, int tz, TileNode tile, TerrainField terrain, bool isSion) { long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; - float tileMinX = -TerrainField.HalfExtent + tx * TerrainField.TileSize; - float tileMinZ = -TerrainField.HalfExtent + tz * TerrainField.TileSize; IReadOnlyList indices = terrain.GetTileBrushIndices(tx, tz); - var brushes = terrain.Brushes; - - int hCount = 0; - int aCount = 0; - - for (int i = 0; i < indices.Count; i++) + if (indices.Count == 0 && isSion) { - var b = brushes[indices[i]]; - if (b.RadiusX <= 0.05f || b.RadiusZ <= 0.05f) - { - continue; - } - - float px = GutterCenterOffset + (b.X - tileMinX) * PixelsPerMeter; - float py = GutterCenterOffset + (b.Z - tileMinZ) * PixelsPerMeter; - float rxPx = b.RadiusX * PixelsPerMeter; - float rzPx = b.RadiusZ * PixelsPerMeter; - int kindInt = (int)b.Kind; - - // 1. Height+Material brush pass(es) - if (b.Kind == TerrainBrushKind.Crater) - { - // Crater uses subtractive pit + additive ejecta rim/scorch - SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushSubShader, kindInt, b.HeightDelta), _white1x1); - SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushAddShader, kindInt, b.HeightDelta), _white1x1); - } - else if (b.Kind == TerrainBrushKind.Track) - { - SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushSubShader, kindInt, b.HeightDelta), _white1x1); - SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushAddShader, kindInt, b.HeightDelta), _white1x1); - } - else if (b.Kind == TerrainBrushKind.Road || b.HeightDelta < 0f) - { - SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushSubShader, kindInt, b.HeightDelta), _white1x1); - } - else - { - SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushAddShader, kindInt, b.HeightDelta), _white1x1); - } - - // 2. Albedo brush pass - SetQuad(tile.AlbedoCanvas, tile.AlbedoQuads, ref aCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateAlbedoBrushMat(kindInt, b.AlbedoR, b.AlbedoG, b.AlbedoB, b.HeightDelta), _white1x1); + // Untouched Sion tile: release LRU slot and bind shared 1x1 neutral delta texture + ReleaseTileSlot(tile); + tile.SurfaceMat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex); + tile.SurfaceMat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex); + return; } - HideUnusedQuads(tile.HeightQuads, hCount); - HideUnusedQuads(tile.AlbedoQuads, aCount); + int tileIdx = tz * _gridCount + tx; + LruSlot slot = AcquireLruSlot(tileIdx, tile); + tile.SurfaceMat.SetShaderParameter("delta_height_tex", slot.DeltaHeightTex); + tile.SurfaceMat.SetShaderParameter("delta_albedo_tex", slot.DeltaAlbedoTex); + + if (RenderingServer.GetRenderingDevice() is not null && !_rdFailed) + { + var brushes = terrain.Brushes; + var gpuList = new List(indices.Count); + for (int i = 0; i < indices.Count; i++) + { + var b = brushes[indices[i]]; + if (b.RadiusX <= 0.05f || b.RadiusZ <= 0.05f) + { + continue; + } + float invRx = 1f / MathF.Max(0.1f, b.RadiusX); + float invRz = 1f / MathF.Max(0.1f, b.RadiusZ); + float maxR = MathF.Max(0.1f, MathF.Max(b.RadiusX, b.RadiusZ)); + gpuList.Add(new GpuBrush + { + PosRot = new Vector4(b.X, b.Z, MathF.Cos(b.RotationRad), MathF.Sin(b.RotationRad)), + RadDelta = new Vector4(invRx, invRz, b.HeightDelta, maxR * maxR), + MatColor = new Vector4(b.AlbedoR, b.AlbedoG, b.AlbedoB, (float)(int)b.Kind) + }); + } + + lock (_jobLock) + { + _pendingJobs.Add(new PendingBakeJob + { + SlotIndex = slot.SlotIndex, + TileOriginX = tile.OriginX, + TileOriginZ = tile.OriginZ, + TileSize = _tileSize, + IsSion = isSion, + Brushes = gpuList.ToArray() + }); + } + } - tile.HeightViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; - tile.AlbedoViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; if (t0 != 0) { PerfBakeTileMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; @@ -437,94 +765,393 @@ public partial class TerrainRenderer : Node3D } } - private ShaderMaterial GetOrCreateHeightBrushMat(Shader shader, int kindInt, float heightDelta) + private LruSlot AcquireLruSlot(int tileIdx, TileNode tile) { - var key = (shader, kindInt, heightDelta); - if (!_heightBrushMatCache.TryGetValue(key, out var mat)) + _lruClock++; + if (tile.LruSlotIndex >= 0) { - mat = new ShaderMaterial { Shader = shader }; - mat.SetShaderParameter("brush_kind", kindInt); - mat.SetShaderParameter("height_delta", heightDelta); - mat.SetShaderParameter("height_span", HeightSpan); - _heightBrushMatCache[key] = mat; + var cur = _lruPool[tile.LruSlotIndex]; + if (cur.AssignedTileIndex == tileIdx) + { + cur.LastUsedSeq = _lruClock; + return cur; + } } - return mat; + + int bestIdx = -1; + ulong bestAge = ulong.MaxValue; + for (int i = 0; i < MaxGpuScarTiles; i++) + { + if (_lruPool[i].AssignedTileIndex < 0) + { + bestIdx = i; + break; + } + if (_lruPool[i].LastUsedSeq < bestAge) + { + bestAge = _lruPool[i].LastUsedSeq; + bestIdx = i; + } + } + + var chosen = _lruPool[bestIdx]; + if (chosen.AssignedTileIndex >= 0 && _tiles is not null) + { + int prevTileIdx = chosen.AssignedTileIndex; + int prevTx = prevTileIdx % _gridCount; + int prevTz = prevTileIdx / _gridCount; + if ((uint)prevTx < (uint)_gridCount && (uint)prevTz < (uint)_gridCount) + { + var evicted = _tiles[prevTx, prevTz]; + if (evicted.LruSlotIndex == bestIdx) + { + evicted.LruSlotIndex = -1; + evicted.BakedVisualVersion = -1; + evicted.BakedStructuralVersion = -1; + evicted.SurfaceMat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex); + evicted.SurfaceMat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex); + } + } + } + + chosen.AssignedTileIndex = tileIdx; + chosen.LastUsedSeq = _lruClock; + tile.LruSlotIndex = bestIdx; + return chosen; } - private ShaderMaterial GetOrCreateAlbedoBrushMat(int kindInt, float r, float g, float b, float heightDelta) + private void ReleaseTileSlot(TileNode tile) { - var key = (kindInt, r, g, b, heightDelta); - if (!_albedoBrushMatCache.TryGetValue(key, out var mat)) + if (tile.LruSlotIndex >= 0) { - mat = new ShaderMaterial { Shader = _brushAlbedoShader }; - mat.SetShaderParameter("brush_kind", kindInt); - mat.SetShaderParameter("brush_albedo", new Vector3(r, g, b)); - mat.SetShaderParameter("height_delta", heightDelta); - _albedoBrushMatCache[key] = mat; + var slot = _lruPool[tile.LruSlotIndex]; + if (slot.AssignedTileIndex == tile.Tz * _gridCount + tile.Tx) + { + slot.AssignedTileIndex = -1; + } + tile.LruSlotIndex = -1; } - return mat; } - private static Polygon2D CreateClearQuad(ShaderMaterial mat, ImageTexture whiteTex) + private void DispatchPendingJobsIfNeeded() { - return new Polygon2D + if (RenderingServer.GetRenderingDevice() is null || _rdFailed) { - Polygon = ClearQuadPoly, - UV = BrushUv, - Texture = whiteTex, - Material = mat + lock (_jobLock) + { + _pendingJobs.Clear(); + } + return; + } + + bool any; + lock (_jobLock) + { + any = _pendingJobs.Count > 0; + } + if (any) + { + _hasQueuedRdFlush = true; + RenderingServer.CallOnRenderThread(Callable.From(FlushPendingGpuBakesOnRenderThread)); + } + } + + private void UploadSionDemOnRenderThread() + { + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + byte[]? demBytes = _pendingSionDemUpload; + int res = _pendingSionDemRes; + _pendingSionDemUpload = null; + if (rd is null || demBytes is null || res <= 1) + { + return; + } + + if (_sionDemRid.IsValid) + { + if (_sionDemTexRd is not null) + { + _sionDemTexRd.TextureRdRid = new Rid(); + } + rd.FreeRid(_sionDemRid); + _sionDemRid = new Rid(); + } + + var fmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R16Unorm, + Width = (uint)res, + Height = (uint)res, + Depth = 1, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.CanUpdateBit }; + var dataArr = new Godot.Collections.Array { demBytes }; + _sionDemRid = rd.TextureCreate(fmt, new RDTextureView(), dataArr); + if (_sionDemTexRd is not null && _sionDemRid.IsValid) + { + _sionDemTexRd.TextureRdRid = _sionDemRid; + } } - private static void SetQuad( - Node2D canvas, - List pool, - ref int index, - float px, float py, - float rxPx, float rzPx, - float rotationRad, - ShaderMaterial mat, - ImageTexture whiteTex) + private bool EnsureComputePipelineOnRenderThread(RenderingDevice rd) { - Polygon2D quad; - if (index < pool.Count) + if (_rdInitialized) { - quad = pool[index]; - quad.Position = new Vector2(px, py); - quad.Rotation = rotationRad; - quad.Scale = new Vector2(rxPx, rzPx); - quad.Material = mat; - if (!quad.Visible) - { - quad.Visible = true; - } + return true; } - else + if (_rdFailed) { - quad = new Polygon2D + return false; + } + + string source = Godot.FileAccess.GetFileAsString("res://terrain_tile_bake.glsl"); + if (string.IsNullOrWhiteSpace(source)) + { + GD.PrintErr("TerrainRenderer: missing compute shader res://terrain_tile_bake.glsl"); + _rdFailed = true; + return false; + } + + using var rdSrc = new RDShaderSource + { + Language = RenderingDevice.ShaderLanguage.Glsl, + SourceCompute = source + }; + using RDShaderSpirV spirv = rd.ShaderCompileSpirVFromSource(rdSrc, allowCache: true); + if (!string.IsNullOrEmpty(spirv.CompileErrorCompute)) + { + GD.PrintErr($"TerrainRenderer: SPIR-V compile error in terrain_tile_bake.glsl: {spirv.CompileErrorCompute}"); + _rdFailed = true; + return false; + } + + _bakeShaderRid = rd.ShaderCreateFromSpirV(spirv, "terrain_tile_bake"); + _bakePipeRid = rd.ComputePipelineCreate(_bakeShaderRid); + if (!_bakeShaderRid.IsValid || !_bakePipeRid.IsValid) + { + GD.PrintErr("TerrainRenderer: failed to create compute pipeline"); + _rdFailed = true; + return false; + } + + _brushSsboRid = rd.StorageBufferCreate(MaxSsboBrushes * BrushStrideBytes, new byte[MaxSsboBrushes * BrushStrideBytes]); + _rdInitialized = true; + return true; + } + + private void EnsureSlotRdAllocatedOnRenderThread(RenderingDevice rd, LruSlot slot) + { + if (slot.IsRdAllocated) + { + return; + } + + var hFmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat, + Width = DeltaTexSize, + Height = DeltaTexSize, + Depth = 1, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | + RenderingDevice.TextureUsageBits.StorageBit | + RenderingDevice.TextureUsageBits.CanCopyFromBit + }; + slot.DeltaHeightRid = rd.TextureCreate(hFmt, new RDTextureView()); + + var aFmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R8G8B8A8Unorm, + Width = DeltaTexSize, + Height = DeltaTexSize, + Depth = 1, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit + }; + slot.DeltaAlbedoRid = rd.TextureCreate(aFmt, new RDTextureView()); + + var uniforms = new Godot.Collections.Array + { + new RDUniform { - Position = new Vector2(px, py), - Rotation = rotationRad, - Scale = new Vector2(rxPx, rzPx), - Polygon = UnitQuadPoly, - UV = BrushUv, - Texture = whiteTex, - Material = mat + UniformType = RenderingDevice.UniformType.Image, + Binding = 0, + _Ids = new Godot.Collections.Array { slot.DeltaHeightRid } + }, + new RDUniform + { + UniformType = RenderingDevice.UniformType.Image, + Binding = 1, + _Ids = new Godot.Collections.Array { slot.DeltaAlbedoRid } + }, + new RDUniform + { + UniformType = RenderingDevice.UniformType.StorageBuffer, + Binding = 2, + _Ids = new Godot.Collections.Array { _brushSsboRid } + } + }; + slot.UniformSetRid = rd.UniformSetCreate(uniforms, _bakeShaderRid, 0); + slot.DeltaHeightTex.TextureRdRid = slot.DeltaHeightRid; + slot.DeltaAlbedoTex.TextureRdRid = slot.DeltaAlbedoRid; + slot.IsRdAllocated = true; + } + + private void FlushPendingGpuBakesOnRenderThread() + { + PendingBakeJob[] jobs; + lock (_jobLock) + { + if (_pendingJobs.Count == 0) + { + _hasQueuedRdFlush = false; + return; + } + jobs = _pendingJobs.ToArray(); + _pendingJobs.Clear(); + } + + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null || !EnsureComputePipelineOnRenderThread(rd)) + { + _hasQueuedRdFlush = false; + return; + } + + long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; + + int totalBrushes = 0; + var brushStarts = new uint[jobs.Length]; + for (int j = 0; j < jobs.Length; j++) + { + int count = jobs[j].Brushes.Length; + if (totalBrushes + count > MaxSsboBrushes) + { + count = Math.Max(0, MaxSsboBrushes - totalBrushes); + } + brushStarts[j] = (uint)totalBrushes; + for (int b = 0; b < count; b++) + { + int byteOff = (totalBrushes + b) * BrushStrideBytes; + MemoryMarshal.Write(_ssboStagingBytes.AsSpan(byteOff, BrushStrideBytes), in jobs[j].Brushes[b]); + } + totalBrushes += count; + } + + if (totalBrushes > 0) + { + rd.BufferUpdate(_brushSsboRid, 0, (uint)(totalBrushes * BrushStrideBytes), _ssboStagingBytes); + } + + for (int j = 0; j < jobs.Length; j++) + { + EnsureSlotRdAllocatedOnRenderThread(rd, _lruPool[jobs[j].SlotIndex]); + } + + uint groups = (uint)((DeltaTexSize + 7) / 8); + long cl = rd.ComputeListBegin(); + rd.ComputeListBindComputePipeline(cl, _bakePipeRid); + for (int j = 0; j < jobs.Length; j++) + { + var job = jobs[j]; + var slot = _lruPool[job.SlotIndex]; + uint bCount = (uint)Math.Min(job.Brushes.Length, MaxSsboBrushes - (int)brushStarts[j]); + var push = new TileBakePush + { + TileOriginAndSpan = new Vector4(job.TileOriginX, job.TileOriginZ, job.TileSize, InnerTexelSpan), + BaseColorAndGutter = job.IsSion + ? new Vector4(0f, 0f, 0f, GutterStartIndex) + : new Vector4(DesertAlbedoClear.R, DesertAlbedoClear.G, DesertAlbedoClear.B, GutterStartIndex), + BrushStart = brushStarts[j], + BrushCount = bCount, + TexSize = DeltaTexSize, + IsSion = job.IsSion ? 1u : 0u }; - pool.Add(quad); - canvas.AddChild(quad); + MemoryMarshal.Write(_pushBytes, in push); + rd.ComputeListBindUniformSet(cl, slot.UniformSetRid, 0); + rd.ComputeListSetPushConstant(cl, _pushBytes, PushConstantBytes); + rd.ComputeListDispatch(cl, groups, groups, 1); + } + rd.ComputeListEnd(); + _hasQueuedRdFlush = false; + + if (t0 != 0) + { + PerfBakeTileMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; } - index++; } - private static void HideUnusedQuads(List pool, int usedCount) + private void ReadbackTextureOnRenderThread() { - for (int i = usedCount; i < pool.Count; i++) + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null || !_readbackTargetRid.IsValid) { - if (pool[i].Visible) - { - pool[i].Visible = false; - } + _readbackResult = null; + return; } + _readbackResult = rd.TextureGetData(_readbackTargetRid, 0); + } + + private void DisposeRdResourcesOnRenderThread() + { + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null) + { + return; + } + + for (int i = 0; i < _lruPool.Length; i++) + { + var slot = _lruPool[i]; + if (slot is null || !slot.IsRdAllocated) + { + continue; + } + slot.DeltaHeightTex.TextureRdRid = new Rid(); + slot.DeltaAlbedoTex.TextureRdRid = new Rid(); + if (slot.UniformSetRid.IsValid) rd.FreeRid(slot.UniformSetRid); + if (slot.DeltaHeightRid.IsValid) rd.FreeRid(slot.DeltaHeightRid); + if (slot.DeltaAlbedoRid.IsValid) rd.FreeRid(slot.DeltaAlbedoRid); + slot.UniformSetRid = new Rid(); + slot.DeltaHeightRid = new Rid(); + slot.DeltaAlbedoRid = new Rid(); + slot.IsRdAllocated = false; + } + + if (_sionDemTexRd is not null) + { + _sionDemTexRd.TextureRdRid = new Rid(); + } + if (_sionDemRid.IsValid) + { + rd.FreeRid(_sionDemRid); + _sionDemRid = new Rid(); + } + if (_brushSsboRid.IsValid) + { + rd.FreeRid(_brushSsboRid); + _brushSsboRid = new Rid(); + } + if (_bakePipeRid.IsValid) + { + rd.FreeRid(_bakePipeRid); + _bakePipeRid = new Rid(); + } + if (_bakeShaderRid.IsValid) + { + rd.FreeRid(_bakeShaderRid); + _bakeShaderRid = new Rid(); + } + _rdInitialized = false; } } diff --git a/client/terrain_brush.gdshader b/client/terrain_brush.gdshader deleted file mode 100644 index ccbe36f..0000000 --- a/client/terrain_brush.gdshader +++ /dev/null @@ -1,67 +0,0 @@ -shader_type canvas_item; -render_mode blend_add; - -// Encodes positive height deltas into R ([-18m, +52m] => span 70m), -// roughness delta into G, scorch/track wear into B, and ALWAYS A = 1.0 -// (required for TransparentBg=false UseHdr2D=true blend equations in forward_plus). -uniform int brush_kind = 0; -uniform float height_delta = 0.0; -uniform float height_span = 70.0; - -void fragment() { - vec2 uv_local = UV * 2.0 - 1.0; - float u = uv_local.x; - float v = uv_local.y; - float r2 = u * u + v * v; - if (r2 >= 1.0) { - discard; - } - - float pos_dh = 0.0; - float pos_dg = 0.0; - float d_scorch = 0.0; - - if (brush_kind == 0) { - // DuneRidge (positive) - float env = 1.0 - r2; - env *= env; - float ridge = max(0.0, 1.0 - u * u); - float asym = 1.0 + 0.32 * u; - pos_dh = max(0.0, height_delta) * env * (0.35 + 0.65 * ridge) * asym; - pos_dg = 0.02 * env; - } else if (brush_kind == 1) { - // Mesa - float r = sqrt(r2); - float t = clamp((1.0 - r) / 0.45, 0.0, 1.0); - float plateau = t * t * (3.0 - 2.0 * t); - pos_dh = max(0.0, height_delta) * plateau; - } else if (brush_kind == 2) { - // SalvagePad (positive part) - float env = 1.0 - r2; - env *= env; - pos_dh = max(0.0, height_delta) * env; - pos_dg = 0.03 * env; - } else if (brush_kind == 4) { - // Crater ejecta rim + slag/scorch - float r = sqrt(r2); - float depth = abs(height_delta); - float rim_t = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0)); - pos_dh = 0.32 * depth * rim_t * rim_t; - pos_dg = 0.04 * (1.0 - r); - d_scorch = 0.78 * clamp(1.0 - r * 0.9, 0.0, 1.0); - } else if (brush_kind == 5) { - // Track wear - float env = 1.0 - r2; - env *= env; - d_scorch = 0.32 * env; - } else if (brush_kind == 6) { - // Scorch - float r = sqrt(r2); - float mask = clamp(1.0 - r, 0.0, 1.0); - mask = mask * mask; - pos_dg = 0.02 * mask; - d_scorch = 0.85 * mask; - } - - COLOR = vec4(pos_dh / height_span, pos_dg, d_scorch, 1.0); -} diff --git a/client/terrain_brush_albedo.gdshader b/client/terrain_brush_albedo.gdshader deleted file mode 100644 index 3b1cdf8..0000000 --- a/client/terrain_brush_albedo.gdshader +++ /dev/null @@ -1,73 +0,0 @@ -shader_type canvas_item; -render_mode blend_mix; - -uniform int brush_kind = 0; -uniform vec3 brush_albedo = vec3(0.72, 0.53, 0.33); -uniform float height_delta = 0.0; - -void fragment() { - vec2 uv_local = UV * 2.0 - 1.0; - float u = uv_local.x; - float v = uv_local.y; - float r2 = u * u + v * v; - if (r2 >= 1.0) { - discard; - } - - vec3 col = brush_albedo; - float alpha = 0.0; - - if (brush_kind == 0) { - // DuneRidge: windward sunlit crest vs dry wash - float env = 1.0 - r2; - env *= env; - float ridge = max(0.0, 1.0 - u * u); - col = mix(brush_albedo * 0.90, brush_albedo * 1.12, ridge); - alpha = env * 0.72; - } else if (brush_kind == 1) { - // Mesa: rust-basalt plateau + stratified skirt - float r = sqrt(r2); - float t = clamp((1.0 - r) / 0.45, 0.0, 1.0); - float plateau = t * t * (3.0 - 2.0 * t); - float cliff_band = clamp(1.0 - abs(r - 0.74) * 5.0, 0.0, 1.0); - col = mix(brush_albedo, brush_albedo * 0.68, cliff_band); - alpha = clamp(plateau + cliff_band * 0.5, 0.0, 0.94); - } else if (brush_kind == 2) { - // SalvagePad: compacted gravel & weathered concrete slab - float env = 1.0 - r2; - env *= env; - float border = smoothstep(0.75, 0.92, sqrt(r2)); - col = mix(brush_albedo, vec3(0.32, 0.28, 0.24), border * 0.45); - alpha = clamp(env * 1.15, 0.0, 0.88); - } else if (brush_kind == 3) { - // Road: twin packed dirt ruts running longitudinally along u (cross-track offset abs(v)) - float env = 1.0 - r2; - env *= env; - float rut = smoothstep(0.15, 0.45, abs(v)) * (1.0 - smoothstep(0.60, 0.92, abs(v))); - col = mix(brush_albedo, brush_albedo * 0.76, rut); - alpha = env * (0.45 + 0.35 * rut); - } else if (brush_kind == 4) { - // Crater: charred pit center + bright rust ejecta rim - float r = sqrt(r2); - float pit = clamp(1.0 - r / 0.62, 0.0, 1.0); - float rim = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0)); - vec3 ejecta = vec3(0.62, 0.38, 0.22); - col = mix(ejecta, brush_albedo, clamp(pit * 1.3, 0.0, 1.0)); - alpha = clamp(max(pit * 0.94, rim * rim * 0.72), 0.0, 0.95); - } else if (brush_kind == 5) { - // Track: twin tire ruts along local X - float env = 1.0 - r2; - env *= env; - float treads = smoothstep(0.18, 0.45, abs(v)) * (1.0 - smoothstep(0.62, 0.92, abs(v))); - col = brush_albedo; - alpha = env * treads * 0.62; - } else if (brush_kind == 6) { - // Scorch - float r = sqrt(r2); - float mask = clamp(1.0 - r, 0.0, 1.0); - col = brush_albedo; - alpha = mask * mask * 0.88; - } - - COLOR = vec4(col, alpha); -} diff --git a/client/terrain_brush_sub.gdshader b/client/terrain_brush_sub.gdshader deleted file mode 100644 index 660e195..0000000 --- a/client/terrain_brush_sub.gdshader +++ /dev/null @@ -1,41 +0,0 @@ -shader_type canvas_item; -render_mode blend_sub; - -// Encodes negative height deltas (crater pits, dry washes, road ruts, tire ruts) into R. -uniform int brush_kind = 0; -uniform float height_delta = 0.0; -uniform float height_span = 70.0; - -void fragment() { - vec2 uv_local = UV * 2.0 - 1.0; - float u = uv_local.x; - float v = uv_local.y; - float r2 = u * u + v * v; - if (r2 >= 1.0) { - discard; - } - - float neg_dh = 0.0; - float neg_dg = 0.0; - if (brush_kind == 0) { - // Dry wash (negative DuneRidge) - float env = 1.0 - r2; - env *= env; - float ridge = max(0.0, 1.0 - u * u); - float asym = 1.0 + 0.32 * u; - neg_dh = max(0.0, -height_delta) * env * (0.35 + 0.65 * ridge) * asym; - } else if (brush_kind == 2 || brush_kind == 3 || brush_kind == 5) { - // SalvagePad (<0), Road, Track rut - float env = 1.0 - r2; - env *= env; - neg_dh = max(0.0, -height_delta) * env; - } else if (brush_kind == 4) { - // Crater pit - float r = sqrt(r2); - float depth = abs(height_delta); - float pit_t = clamp(1.0 - r / 0.62, 0.0, 1.0); - neg_dh = depth * pit_t * pit_t * (3.0 - 2.0 * pit_t); - } - - COLOR = vec4(neg_dh / height_span, neg_dg, 0.0, 1.0); -} diff --git a/client/terrain_surface.gdshader b/client/terrain_surface.gdshader index 706c6db..0818af1 100644 --- a/client/terrain_surface.gdshader +++ b/client/terrain_surface.gdshader @@ -1,18 +1,29 @@ shader_type spatial; render_mode cull_back, depth_draw_opaque; -uniform sampler2D height_tex : filter_linear, repeat_disable; -uniform sampler2D albedo_tex : source_color, filter_linear, repeat_disable; +uniform sampler2D base_dem_tex : filter_linear, repeat_disable; +uniform sampler2D base_surface_tex : source_color, filter_linear_mipmap, repeat_disable; +uniform sampler2D base_mask_tex : filter_linear_mipmap, repeat_disable; +uniform sampler2D delta_height_tex : filter_linear, repeat_disable; +uniform sampler2D delta_albedo_tex : source_color, filter_linear, repeat_disable; + +uniform float dem_min_y = 0.0; +uniform float dem_scale_span = 0.0; +uniform float dem_grid_res = 6145.0; uniform float height_min = -18.0; uniform float height_max = 52.0; +uniform float map_size = 1536.0; +uniform float tile_origin_x = 0.0; +uniform float tile_origin_z = 0.0; uniform float tile_size = 192.0; -uniform float inner_span = 253.0; -uniform float tex_size = 256.0; -uniform float gutter_offset = 1.5; +uniform float inner_span = 384.0; +uniform float tex_size = 388.0; +uniform float gutter_center = 2.5; +uniform float is_sion = 0.0; +uniform float tile_quads = 192.0; +uniform vec4 neighbor_quads = vec4(192.0, 192.0, 192.0, 192.0); // (-X, +X, -Z, +Z) -float decode_height(float h_norm) { - return mix(height_min, height_max, clamp(h_norm, 0.0, 1.0)); -} +varying vec3 v_world_pos; float hash21(vec2 p) { p = fract(p * vec2(123.34, 456.21)); @@ -20,37 +31,117 @@ float hash21(vec2 p) { 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); +} + vec2 to_baked_uv(vec2 mesh_uv) { - return (mesh_uv * inner_span + gutter_offset) / tex_size; + return (mesh_uv * inner_span + gutter_center) / tex_size; +} + +float sample_total_height(vec2 mesh_uv) { + vec2 world_xz = vec2(tile_origin_x, tile_origin_z) + mesh_uv * tile_size; + float base_h = 0.0; + if (is_sion > 0.5) { + float max_idx = dem_grid_res - 1.0; + vec2 dem_uv = ((world_xz + map_size * 0.5) / map_size * max_idx + 0.5) / dem_grid_res; + base_h = dem_min_y + textureLod(base_dem_tex, dem_uv, 0.0).r * dem_scale_span; + } + float delta_h = textureLod(delta_height_tex, to_baked_uv(mesh_uv), 0.0).r; + return clamp(base_h + delta_h, height_min, height_max); +} + +float sample_edge_snapped_height(vec2 uv) { + // Zero T-junction cracks: if an adjacent tile is coarser, snap edge vertex height + // onto the exact linear segment connecting the neighbor's coarse edge vertices. + if (uv.x < 0.0005 && neighbor_quads.x < tile_quads - 0.5) { + float nq = neighbor_quads.x; + float t = uv.y * nq; + float i0 = floor(t); + float u0 = i0 / nq; + float u1 = min(1.0, (i0 + 1.0) / nq); + return mix(sample_total_height(vec2(0.0, u0)), sample_total_height(vec2(0.0, u1)), t - i0); + } + if (uv.x > 0.9995 && neighbor_quads.y < tile_quads - 0.5) { + float nq = neighbor_quads.y; + float t = uv.y * nq; + float i0 = floor(t); + float u0 = i0 / nq; + float u1 = min(1.0, (i0 + 1.0) / nq); + return mix(sample_total_height(vec2(1.0, u0)), sample_total_height(vec2(1.0, u1)), t - i0); + } + if (uv.y < 0.0005 && neighbor_quads.z < tile_quads - 0.5) { + float nq = neighbor_quads.z; + float t = uv.x * nq; + float i0 = floor(t); + float u0 = i0 / nq; + float u1 = min(1.0, (i0 + 1.0) / nq); + return mix(sample_total_height(vec2(u0, 0.0)), sample_total_height(vec2(u1, 0.0)), t - i0); + } + if (uv.y > 0.9995 && neighbor_quads.w < tile_quads - 0.5) { + float nq = neighbor_quads.w; + float t = uv.x * nq; + float i0 = floor(t); + float u0 = i0 / nq; + float u1 = min(1.0, (i0 + 1.0) / nq); + return mix(sample_total_height(vec2(u0, 1.0)), sample_total_height(vec2(u1, 1.0)), t - i0); + } + return sample_total_height(uv); } void vertex() { - float h_norm = textureLod(height_tex, to_baked_uv(UV), 0.0).r; - VERTEX.y += decode_height(h_norm); + float h = sample_edge_snapped_height(UV); + VERTEX.y += h; + v_world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz; } void fragment() { - vec2 uv_baked = to_baked_uv(UV); - float texel_step = 1.0 / tex_size; - float world_step = tile_size / inner_span; + float world_step = tile_size / inner_span; // 0.5m + float uv_step = world_step / tile_size; - float hL = decode_height(texture(height_tex, uv_baked - vec2(texel_step, 0.0)).r); - float hR = decode_height(texture(height_tex, uv_baked + vec2(texel_step, 0.0)).r); - float hD = decode_height(texture(height_tex, uv_baked - vec2(0.0, texel_step)).r); - float hU = decode_height(texture(height_tex, uv_baked + vec2(0.0, texel_step)).r); + float hL = sample_total_height(UV - vec2(uv_step, 0.0)); + float hR = sample_total_height(UV + vec2(uv_step, 0.0)); + float hD = sample_total_height(UV - vec2(0.0, uv_step)); + float hU = sample_total_height(UV + vec2(0.0, uv_step)); vec3 world_normal = normalize(vec3(hL - hR, 2.0 * world_step, hD - hU)); NORMAL = normalize((VIEW_MATRIX * vec4(world_normal, 0.0)).xyz); - vec4 mat = texture(height_tex, uv_baked); - vec3 alb = texture(albedo_tex, uv_baked).rgb; - - // Subtle desert sand grain so dunes read crisply under sunlight (multiplicative in linear HDR) - float grain = (hash21(floor(UV * 768.0)) - 0.5) * 0.045; + vec2 uv_baked = to_baked_uv(UV); + vec4 mat = texture(delta_height_tex, uv_baked); + vec3 delta_alb = texture(delta_albedo_tex, uv_baked).rgb; float scorch = clamp(mat.b, 0.0, 1.0); - alb = clamp(alb * (1.0 + grain * 1.4), 0.0, 1.0) * (1.0 - 0.30 * scorch); + + vec3 alb; + float rough = clamp(mat.g, 0.35, 1.0); + if (is_sion > 0.5) { + vec2 world_uv = (v_world_pos.xz + map_size * 0.5) / map_size; + vec3 base_col = texture(base_surface_tex, world_uv).rgb; + vec4 cls = texture(base_mask_tex, world_uv); + alb = mix(base_col, delta_alb, clamp(mat.a, 0.0, 1.0)); + + 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, 480.0, dist), 0.12, 1.0); + float macro = (value_noise(v_world_pos.xz * 0.28) - 0.5) * 0.07; + float grit = (hash21(floor(v_world_pos.xz * 8.0)) - 0.5) * 0.045; + alb = clamp(alb * (1.0 + macro * 1.4 + grit * 1.6 * near_fade), 0.0, 1.0) * (1.0 - 0.32 * scorch); + + float base_rough = cls.r * 0.94 + cls.g * 0.90 + cls.b * 0.80 + cls.a * 0.26; + float cls_sum = max(0.001, cls.r + cls.g + cls.b + cls.a); + rough = mix(clamp(base_rough / cls_sum, 0.26, 0.96), rough, clamp(mat.a, 0.0, 1.0)); + } else { + float grain = (hash21(floor(UV * 768.0)) - 0.5) * 0.045; + alb = clamp(delta_alb * (1.0 + grain * 1.4), 0.0, 1.0) * (1.0 - 0.30 * scorch); + } ALBEDO = alb; - ROUGHNESS = clamp(mat.g, 0.35, 1.0); + ROUGHNESS = rough; METALLIC = 0.02; } diff --git a/client/terrain_tile_bake.glsl b/client/terrain_tile_bake.glsl new file mode 100644 index 0000000..96b0c42 --- /dev/null +++ b/client/terrain_tile_bake.glsl @@ -0,0 +1,176 @@ +#version 450 + +layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in; + +struct GpuBrush { + vec4 posRot; // x, z, cosR, sinR + vec4 radDelta; // invRx, invRz, heightDelta, maxRadiusSq + vec4 matColor; // albedoR, albedoG, albedoB, float(kind) +}; + +layout(set = 0, binding = 0, rgba16f) uniform writeonly image2D u_delta_height; +layout(set = 0, binding = 1, rgba8) uniform writeonly image2D u_delta_albedo; + +layout(set = 0, binding = 2, std430) readonly buffer BrushBuffer { + GpuBrush brushes[]; +} u_brushes; + +layout(push_constant, std430) uniform TileBakeParams { + vec4 tileOriginAndSpan; // x=tileMinX, y=tileMinZ, z=tileSize(192), w=innerSpan(384) + vec4 baseColorAndGutter; // rgb=clearAlbedo, w=gutterStart(2.0) + uvec4 counts; // x=brushStart, y=brushCount, z=texSize(388), w=isSion +} u_params; + +void main() { + ivec2 gid = ivec2(gl_GlobalInvocationID.xy); + int texSize = int(u_params.counts.z); + if (gid.x >= texSize || gid.y >= texSize) { + return; + } + + float tileMinX = u_params.tileOriginAndSpan.x; + float tileMinZ = u_params.tileOriginAndSpan.y; + float tileSize = u_params.tileOriginAndSpan.z; + float innerSpan = u_params.tileOriginAndSpan.w; + float gutterStart = u_params.baseColorAndGutter.w; + + float stepM = tileSize / innerSpan; + float wx = tileMinX + (float(gid.x) - gutterStart) * stepM; + float wz = tileMinZ + (float(gid.y) - gutterStart) * stepM; + + bool isSion = u_params.counts.w != 0u; + uint brushStart = u_params.counts.x; + uint brushEnd = brushStart + u_params.counts.y; + + float totalDh = 0.0; + float totalDg = 0.0; + float totalScorch = 0.0; + vec3 albedoAcc = u_params.baseColorAndGutter.rgb; + float deltaBlendAcc = isSion ? 0.0 : 1.0; + + for (uint i = brushStart; i < brushEnd; i++) { + GpuBrush b = u_brushes.brushes[i]; + float dx = wx - b.posRot.x; + float dz = wz - b.posRot.y; + if (dx * dx + dz * dz >= b.radDelta.w) { + continue; + } + + float cosR = b.posRot.z; + float sinR = b.posRot.w; + float lx = dx * cosR + dz * sinR; + float lz = -dx * sinR + dz * cosR; + + float u = lx * b.radDelta.x; + float v = lz * b.radDelta.y; + float r2 = u * u + v * v; + if (r2 >= 1.0) { + continue; + } + + int kind = int(b.matColor.w + 0.5); + float heightDelta = b.radDelta.z; + vec3 bCol = b.matColor.rgb; + float dh = 0.0; + float dg = 0.0; + float dScorch = 0.0; + vec3 col = bCol; + float alpha = 0.0; + + if (kind == 0) { + // DuneRidge + float env = 1.0 - r2; + env *= env; + float ridge = max(0.0, 1.0 - u * u); + float asym = 1.0 + 0.32 * u; + dh = heightDelta * env * (0.35 + 0.65 * ridge) * asym; + if (heightDelta > 0.0) { + dg = 0.02 * env; + } + col = mix(bCol * 0.90, bCol * 1.12, ridge); + alpha = env * 0.72; + } else if (kind == 1) { + // Mesa + float r = sqrt(r2); + float t = clamp((1.0 - r) / 0.45, 0.0, 1.0); + float plateau = t * t * (3.0 - 2.0 * t); + dh = heightDelta * plateau; + float cliffBand = clamp(1.0 - abs(r - 0.74) * 5.0, 0.0, 1.0); + col = mix(bCol, bCol * 0.68, cliffBand); + alpha = clamp(plateau + cliffBand * 0.5, 0.0, 0.94); + } else if (kind == 2) { + // SalvagePad + float env = 1.0 - r2; + env *= env; + dh = heightDelta * env; + if (heightDelta > 0.0) { + dg = 0.03 * env; + } + float border = smoothstep(0.75, 0.92, sqrt(r2)); + col = mix(bCol, vec3(0.32, 0.28, 0.24), border * 0.45); + alpha = clamp(env * 1.15, 0.0, 0.88); + } else if (kind == 3) { + // Road + float env = 1.0 - r2; + env *= env; + dh = heightDelta * env; + float rut = smoothstep(0.15, 0.45, abs(v)) * (1.0 - smoothstep(0.60, 0.92, abs(v))); + col = mix(bCol, bCol * 0.76, rut); + alpha = env * (0.45 + 0.35 * rut); + } else if (kind == 4) { + // Crater + float r = sqrt(r2); + float depth = abs(heightDelta); + float pitT = clamp(1.0 - r / 0.62, 0.0, 1.0); + float pit = -depth * pitT * pitT * (3.0 - 2.0 * pitT); + float rimT = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0)); + float rim = 0.32 * depth * rimT * rimT; + dh = pit + rim; + dg = 0.04 * (1.0 - r); + dScorch = 0.78 * clamp(1.0 - r * 0.9, 0.0, 1.0); + vec3 ejecta = isSion ? vec3(0.34, 0.31, 0.27) : vec3(0.62, 0.38, 0.22); + col = mix(ejecta, bCol, clamp(pitT * 1.3, 0.0, 1.0)); + alpha = clamp(max(pitT * 0.94, rimT * rimT * 0.72), 0.0, 0.95); + } else if (kind == 5) { + // Track + float env = 1.0 - r2; + env *= env; + dh = heightDelta * env; + dScorch = 0.32 * env; + float treads = smoothstep(0.18, 0.45, abs(v)) * (1.0 - smoothstep(0.62, 0.92, abs(v))); + col = bCol; + alpha = env * treads * 0.62; + } else if (kind == 6) { + // Scorch + float r = sqrt(r2); + float mask = clamp(1.0 - r, 0.0, 1.0); + float mask2 = mask * mask; + dg = 0.02 * mask2; + dScorch = 0.85 * mask2; + col = bCol; + alpha = mask2 * 0.88; + } else if (kind == 7) { + // Rubble + float env = 1.0 - r2; + env *= env; + float mound = 0.72 + 0.28 * cos(u * 3.14159265 * 2.5); + dh = heightDelta * env * mound; + dg = 0.08 * env; + dScorch = 0.35 * env; + float chunk = fract(sin(dot(floor(vec2(wx, wz) * 1.5), vec2(12.9898, 78.233))) * 43758.5453); + col = mix(bCol * 0.80, bCol * 1.15, chunk); + alpha = clamp(env * 1.2, 0.0, 0.96); + } + + totalDh += dh; + totalDg += dg; + totalScorch += dScorch; + albedoAcc = mix(albedoAcc, col, alpha); + deltaBlendAcc = max(deltaBlendAcc, alpha); + } + + float roughness = clamp(0.88 + totalDg, 0.35, 1.0); + float scorch = clamp(totalScorch, 0.0, 1.0); + imageStore(u_delta_height, gid, vec4(totalDh, roughness, scorch, clamp(deltaBlendAcc, 0.0, 1.0))); + imageStore(u_delta_albedo, gid, vec4(clamp(albedoAcc, 0.0, 1.0), 1.0)); +} diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index 5247dc6..a196952 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -203,11 +203,11 @@ public partial class Smoke : Node } } - // Regression check (Finding 4): 4-tile boundary crater at (0, 0) bakes all 4 tiles on Sync#1 (<= 0.20m error on all 4 quadrants) - // and passive Track throttling preserves DirtyTileMask until all tiles are baked without skipping via _rebakeCursor. + // Regression check: 4-tile boundary crater at (0, 0) bakes all 4 tiles on Sync#1 (<= 0.20m error on all 4 quadrants) + // and passive Track throttling (MaxDirtyRebakesPerSync=4) preserves pending visual versions until all tiles are baked without skipping via _rebakeCursor. { // Flush any lingering track rebakes first so baseline is clean - for (int flush = 0; flush < 32 && _main.Session.ViewState.Terrain.DirtyTileMask != 0UL; flush++) + for (int flush = 0; flush < 32 && _main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) > 0; flush++) { _main.Terrain.Sync(_main.Session.ViewState.Terrain); } @@ -229,8 +229,8 @@ public partial class Smoke : Node _main.Terrain.Sync(_main.Session.ViewState.Terrain); // Sync#1 Check(_main.Terrain.DirtyRebakes == rebakes4Before + 4, $"Expected 4-tile boundary crater at (0,0) to bake all 4 tiles on Sync#1, got {_main.Terrain.DirtyRebakes - rebakes4Before}"); - Check(_main.Session.ViewState.Terrain.StructuralDirtyTileMask == 0UL, - "Expected StructuralDirtyTileMask == 0 after Sync#1 on 4-tile boundary crater"); + Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 0, + "Expected 0 pending dirty tiles after Sync#1 on 4-tile boundary crater"); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); @@ -252,21 +252,23 @@ public partial class Smoke : Node } } - // Stamp 3 passive tracks in adjacent tiles so _rebakeCursor must advance across Sync#1 and Sync#2 without skipping + // Stamp 5 passive tracks in distinct tiles so _rebakeCursor advances across Sync#1 (4) and Sync#2 (1) without skipping int rebakesTrackBefore = _main.Terrain.DirtyRebakes; _main.Session.ViewState.Terrain.StampTrack(-480f, -480f, 0f, 2f, 3f); _main.Session.ViewState.Terrain.StampTrack(-288f, -480f, 0f, 2f, 3f); _main.Session.ViewState.Terrain.StampTrack(-96f, -480f, 0f, 2f, 3f); + _main.Session.ViewState.Terrain.StampTrack(96f, -480f, 0f, 2f, 3f); + _main.Session.ViewState.Terrain.StampTrack(288f, -480f, 0f, 2f, 3f); _main.Terrain.Sync(_main.Session.ViewState.Terrain); - Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 2, - $"Expected Sync#1 to throttle 3 passive tracks to 2 rebakes, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); - Check(_main.Session.ViewState.Terrain.DirtyTileMask != 0UL, - "Expected DirtyTileMask to stay non-zero while 1 passive track tile remains dirty"); + Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 4, + $"Expected Sync#1 to throttle 5 passive tracks to 4 rebakes, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); + Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 1, + "Expected 1 pending dirty track tile remaining after Sync#1"); _main.Terrain.Sync(_main.Session.ViewState.Terrain); - Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 3, - $"Expected Sync#2 to bake remaining 3rd passive track tile without _rebakeCursor skip, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); - Check(_main.Session.ViewState.Terrain.DirtyTileMask == 0UL, - "Expected DirtyTileMask == 0 after all passive track tiles baked"); + Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 5, + $"Expected Sync#2 to bake remaining 5th passive track tile without _rebakeCursor skip, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); + Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 0, + "Expected 0 pending dirty tiles after all passive track tiles baked"); } _main.SetPhysicsProcess(true); @@ -1864,9 +1866,10 @@ public partial class Smoke : Node var sionState = _main.Session.ViewState; 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.Terrain.Visible && _main.SionMap.Visible, "Expected unified TerrainRenderer and SionMapRenderer buildings visible on Sion"); + Check(_main.Terrain.BakedTileCount == 256, $"Expected 256 unified Sion terrain tiles (16x16), got {_main.Terrain.BakedTileCount}"); + Check(_main.Terrain.ActiveGpuScarSlots == 0, $"Expected 0 active GPU scar slots on clean Sion start, got {_main.Terrain.ActiveGpuScarSlots}"); 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}"); @@ -1913,14 +1916,31 @@ public partial class Smoke : Node 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"); - Color inBoundsTint = _main.SionMap.SampleGroundTint(player.X, player.Z); - Color outBoundsTint = _main.SionMap.SampleGroundTint(9999f, 9999f); + Color inBoundsTint = _main.Terrain.SampleGroundTint(player.X, player.Z); + Color outBoundsTint = _main.Terrain.SampleGroundTint(9999f, 9999f); Check(float.IsFinite(inBoundsTint.R) && float.IsFinite(inBoundsTint.G) && float.IsFinite(inBoundsTint.B) && inBoundsTint.R > 0.1f, $"Expected valid Sion SampleGroundTint at player pos, got {inBoundsTint}"); Check(MathF.Abs(outBoundsTint.R - 0.56f) < 0.01f && MathF.Abs(outBoundsTint.G - 0.53f) < 0.01f, $"Expected neutral alpine fallback tint outside Sion bounds, got {outBoundsTint}"); - 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, tint=({inBoundsTint.R:F2},{inBoundsTint.G:F2},{inBoundsTint.B:F2}))"); + // Verify live crater brush on Sion allocates sparse GPU scar slot & depresses GPU height + float sionCpuPre = sionState.Terrain.SampleHeight(player.X, player.Z); + sionState.Terrain.StampCrater(player.X, player.Z, radius: 5.0f, depth: 1.5f); + _main.Terrain.Sync(sionState.Terrain, sionState.SionMap); + Check(_main.Terrain.ActiveGpuScarSlots >= 1, $"Expected >= 1 active GPU scar slot on Sion after crater, got {_main.Terrain.ActiveGpuScarSlots}"); + if (DisplayServer.GetName() != "headless") + { + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + Check(_main.Terrain.TrySampleBakedHeight(player.X, player.Z, out float sionGpuPost), + "Expected TrySampleBakedHeight to succeed on Sion crater tile"); + float sionCpuPost = sionState.Terrain.SampleHeight(player.X, player.Z); + Check(MathF.Abs(sionGpuPost - sionCpuPost) <= 0.25f, + $"Expected Sion GPU crater height ({sionGpuPost:F3}m) to match CPU ({sionCpuPost:F3}m) within 0.25m"); + Check(sionGpuPost < sionCpuPre - 0.8f, + $"Expected Sion GPU crater height ({sionGpuPost:F3}m) to depress below pre-crater ({sionCpuPre:F3}m)"); + } + + GD.Print($"SMOKE INFO: Sion verified (terrainTiles={_main.Terrain.BakedTileCount}, gpuScarSlots={_main.Terrain.ActiveGpuScarSlots}, bldgTiles={_main.SionMap.BuildingTileCount}, lod1={_main.SionMap.ActiveLod1TileCount}, lod2={_main.SionMap.ActiveLod2TileCount}, disp={disp:F2}m, tint=({inBoundsTint.R:F2},{inBoundsTint.G:F2},{inBoundsTint.B:F2}))"); } private async Task VerifyOrbitalDropSequenceAsync() diff --git a/src/RustToDust.Core/ArenaScarLedger.cs b/src/RustToDust.Core/ArenaScarLedger.cs new file mode 100644 index 0000000..fb5841c --- /dev/null +++ b/src/RustToDust.Core/ArenaScarLedger.cs @@ -0,0 +1,378 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; + +namespace RustToDust.Core +{ + [MessagePackObject] + public sealed class TerrainScarEntry + { + [Key(0)] public byte Kind { get; set; } + [Key(1)] public float X { get; set; } + [Key(2)] public float Z { get; set; } + [Key(3)] public float Radius { get; set; } + [Key(4)] public float Depth { get; set; } + [Key(5)] public float Yaw { get; set; } + [Key(6)] public uint Rgb8 { get; set; } + [Key(7), CultElementId] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class BuildingScarEntry + { + [Key(0)] public ushort BldgId { get; set; } + [Key(1)] public ulong CollapsedMask { get; set; } + [Key(2)] public ulong DamagedMask { get; set; } + [Key(3), CultElementId(nameof(BldgId))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class TreeScarEntry + { + [Key(0)] public ushort TreeId { get; set; } + [Key(1)] public byte State { get; set; } + [Key(2), CultElementId(nameof(TreeId))] public string ElementId { get; set; } = string.Empty; + } + + [CultDocument("rtd.arena_scar_ledger", "1"), MessagePackObject] + public sealed class ArenaScarLedgerSnapshot + { + [CultName, Key(0)] public string AssetFingerprint { get; set; } = string.Empty; + [Key(1)] public List Terrain { get; set; } = new(); + [Key(2)] public List Buildings { get; set; } = new(); + [Key(3)] public List Trees { get; set; } = new(); + [Key(4)] public uint LedgerRevision { get; set; } + } + + public sealed class ArenaScarLedger + { + public const int MaxPersistentTerrainScars = 4096; + public const float CraterCoalesceRadiusMeters = 0.75f; + + private readonly List _terrain = new(); + private readonly Dictionary _buildings = new(); + private readonly Dictionary _trees = new(); + + public ArenaScarLedger(string assetFingerprint = "") + { + AssetFingerprint = assetFingerprint; + } + + public string AssetFingerprint { get; set; } + public uint LedgerRevision { get; private set; } + public bool IsDirty { get; set; } + public IReadOnlyList Terrain => _terrain; + public IReadOnlyDictionary Buildings => _buildings; + public IReadOnlyDictionary Trees => _trees; + + public void RecordTerrainStamp(TerrainStampEvent stamp) => + RecordTerrainStamp(stamp.Kind, stamp.X, stamp.Z, stamp.Radius, stamp.Depth, stamp.Yaw); + + public void RecordTerrainStamp(byte kind, float x, float z, float radius, float depth, float yaw, uint rgb8 = 0) + { + var stampKind = (TerrainStampKind)kind; + if (stampKind == TerrainStampKind.Track) + { + return; + } + + float coalesceSq = CraterCoalesceRadiusMeters * CraterCoalesceRadiusMeters; + if (stampKind == TerrainStampKind.Crater || stampKind == TerrainStampKind.Scorch) + { + for (int i = _terrain.Count - 1; i >= 0; i--) + { + var existing = _terrain[i]; + if (existing.Kind != kind) + { + continue; + } + float dx = existing.X - x; + float dz = existing.Z - z; + if (dx * dx + dz * dz < coalesceSq) + { + existing.Radius = MathF.Max(existing.Radius, radius); + existing.Depth = MathF.Max(existing.Depth, depth); + LedgerRevision++; + IsDirty = true; + return; + } + } + } + + if (_terrain.Count >= MaxPersistentTerrainScars) + { + int evictIdx = -1; + for (int i = 0; i < _terrain.Count; i++) + { + if (_terrain[i].Kind == (byte)TerrainStampKind.Scorch) + { + evictIdx = i; + break; + } + } + _terrain.RemoveAt(evictIdx >= 0 ? evictIdx : 0); + } + + _terrain.Add(new TerrainScarEntry + { + Kind = kind, + X = x, + Z = z, + Radius = radius, + Depth = depth, + Yaw = yaw, + Rgb8 = rgb8 + }); + LedgerRevision++; + IsDirty = true; + } + + public void Clear() + { + _terrain.Clear(); + _buildings.Clear(); + _trees.Clear(); + LedgerRevision++; + IsDirty = true; + } + + public ArenaScarLedgerSnapshot ToSnapshot() + { + var snap = new ArenaScarLedgerSnapshot + { + AssetFingerprint = AssetFingerprint, + LedgerRevision = LedgerRevision, + Terrain = new List(_terrain.Count), + Buildings = new List(_buildings.Count), + Trees = new List(_trees.Count) + }; + for (int i = 0; i < _terrain.Count; i++) + { + var t = _terrain[i]; + snap.Terrain.Add(new TerrainScarEntry + { + Kind = t.Kind, + X = t.X, + Z = t.Z, + Radius = t.Radius, + Depth = t.Depth, + Yaw = t.Yaw, + Rgb8 = t.Rgb8 + }); + } + foreach (var b in _buildings.Values) + { + snap.Buildings.Add(new BuildingScarEntry + { + BldgId = b.BldgId, + CollapsedMask = b.CollapsedMask, + DamagedMask = b.DamagedMask + }); + } + foreach (var tr in _trees.Values) + { + snap.Trees.Add(new TreeScarEntry + { + TreeId = tr.TreeId, + State = tr.State + }); + } + return snap; + } + + public void LoadFromSnapshot(ArenaScarLedgerSnapshot snapshot) + { + _terrain.Clear(); + _buildings.Clear(); + _trees.Clear(); + + if (!string.IsNullOrEmpty(AssetFingerprint) && + !string.Equals(snapshot.AssetFingerprint, AssetFingerprint, StringComparison.Ordinal)) + { + return; + } + + for (int i = 0; i < snapshot.Terrain.Count && i < MaxPersistentTerrainScars; i++) + { + var t = snapshot.Terrain[i]; + _terrain.Add(new TerrainScarEntry + { + Kind = t.Kind, + X = t.X, + Z = t.Z, + Radius = t.Radius, + Depth = t.Depth, + Yaw = t.Yaw, + Rgb8 = t.Rgb8 + }); + } + for (int i = 0; i < snapshot.Buildings.Count; i++) + { + var b = snapshot.Buildings[i]; + _buildings[b.BldgId] = new BuildingScarEntry + { + BldgId = b.BldgId, + CollapsedMask = b.CollapsedMask, + DamagedMask = b.DamagedMask + }; + } + for (int i = 0; i < snapshot.Trees.Count; i++) + { + var tr = snapshot.Trees[i]; + _trees[tr.TreeId] = new TreeScarEntry + { + TreeId = tr.TreeId, + State = tr.State + }; + } + LedgerRevision = snapshot.LedgerRevision; + IsDirty = false; + } + + public void ApplyToTerrain(TerrainField terrain) + { + for (int i = 0; i < _terrain.Count; i++) + { + var t = _terrain[i]; + switch ((TerrainStampKind)t.Kind) + { + case TerrainStampKind.Crater: + terrain.StampCrater(t.X, t.Z, t.Radius, t.Depth); + break; + case TerrainStampKind.Scorch: + terrain.StampScorch(t.X, t.Z, t.Radius); + break; + case TerrainStampKind.Rubble: + terrain.StampRubble(t.X, t.Z, t.Radius, t.Depth, t.Yaw); + break; + } + } + } + + public static byte[] CompressSnapshot(ArenaScarLedgerSnapshot snapshot) + { + byte[] raw = MessagePackSerializer.Serialize(snapshot); + using var ms = new MemoryStream(); + using (var zlib = new ZLibStream(ms, CompressionLevel.Optimal, leaveOpen: true)) + { + zlib.Write(raw, 0, raw.Length); + } + return ms.ToArray(); + } + + public static ArenaScarLedgerSnapshot DecompressSnapshot(byte[] compressed) + { + using var src = new MemoryStream(compressed); + using var zlib = new ZLibStream(src, CompressionMode.Decompress); + using var dst = new MemoryStream(); + zlib.CopyTo(dst); + return MessagePackSerializer.Deserialize(dst.ToArray()); + } + } + + public static class ArenaScarLedgerStore + { + public static CultDocumentRegistry Registry { get; } = + CultDocumentRegistry.ForTypes(new[] { typeof(ArenaScarLedgerSnapshot) }); + + public static CultRecordKey LedgerKey(string profile = "default") => new("scars:" + profile); + + public static string GetDefaultPath(ArenaMapKind mapKind, string profile = "default") + { + string baseDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + if (string.IsNullOrWhiteSpace(baseDir)) + { + baseDir = AppContext.BaseDirectory; + } + string mapTag = mapKind == ArenaMapKind.Sion ? "sion" : "desert"; + string safeProfile = string.IsNullOrWhiteSpace(profile) ? "default" : profile.Trim(); + return Path.Combine(baseDir, "RustToDust", "scars", $"{mapTag}_scars_{safeProfile}.cultcache"); + } + + public static CultCache Open(string path, bool writable = false) + { + var options = new CultCacheOpenOptions + { + Registry = Registry, + ReadOnly = !writable, + FlushOnDispose = false, + StoreFlushOnDispose = false, + UseDirectoryStore = false + }; + return CultCacheMessagePack.Create(path, options); + } + + public static ArenaScarLedgerSnapshot Load(string path, string expectedAssetFingerprint) + { + if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) + { + return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint }; + } + + try + { + using var cache = Open(path, writable: false); + var records = cache.GetAll().ToArray(); + if (records.Length == 0) + { + return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint }; + } + + var snap = records[0]; + if (!string.IsNullOrEmpty(expectedAssetFingerprint) && + !string.Equals(snap.AssetFingerprint, expectedAssetFingerprint, StringComparison.Ordinal)) + { + return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint }; + } + return snap; + } + catch + { + return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint }; + } + } + + public static void Save(string path, ArenaScarLedgerSnapshot snapshot, string profile = "default") + { + if (snapshot is null) throw new ArgumentNullException(nameof(snapshot)); + if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Path cannot be empty.", nameof(path)); + + string fullPath = Path.GetFullPath(path); + string dir = Path.GetDirectoryName(fullPath) ?? "."; + Directory.CreateDirectory(dir); + + string workspace = fullPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; + string tempFile = Path.Combine(workspace, "scars.cultcache"); + try + { + Directory.CreateDirectory(workspace); + using (var cache = Open(tempFile, writable: true)) + { + cache.UpsertAsync(typeof(ArenaScarLedgerSnapshot), snapshot, LedgerKey(profile)).GetAwaiter().GetResult(); + cache.FlushAsync().GetAwaiter().GetResult(); + } + + if (File.Exists(fullPath)) + { + File.Replace(tempFile, fullPath, null); + } + else + { + File.Move(tempFile, fullPath); + } + } + finally + { + if (Directory.Exists(workspace)) + { + Directory.Delete(workspace, recursive: true); + } + } + } + } +} diff --git a/src/RustToDust.Core/MatchState.cs b/src/RustToDust.Core/MatchState.cs index af9e4ae..1b1ef5e 100644 --- a/src/RustToDust.Core/MatchState.cs +++ b/src/RustToDust.Core/MatchState.cs @@ -352,7 +352,8 @@ namespace RustToDust.Core ArenaMapKind mapKind = ArenaMapKind.Desert, bool skipInitialDrop = false, bool startInLobby = false, - byte squadSize = 1) + byte squadSize = 1, + ArenaScarLedgerSnapshot? initialScars = null) { Seed = seed; MapKind = mapKind; @@ -367,13 +368,21 @@ namespace RustToDust.Core if (mapKind == ArenaMapKind.Sion) { SionMap = SionMapLoader.Load(); - Terrain = TerrainField.LoadHeightmap( + Terrain = TerrainField.LoadSharedHeightmap( SionMap.Metadata.SizeMeters, SionMap.Metadata.GridRes, - SionMap.Heights, + SionMap.Metadata.TileGrid, + SionMap.BaseDem, + SionMap.BaseDemMinY, + SionMap.BaseDemScale, SionMap.Metadata.MinY, SionMap.Metadata.MaxY, (ulong)seed); + ScarLedger = new ArenaScarLedger(SionMap.AssetFingerprint); + if (initialScars is not null) + { + ApplyPersistentScars(initialScars); + } Spectators = new SpectatorRing( seed + 101, SpectatorRing.DefaultSpectatorCount, @@ -396,6 +405,11 @@ namespace RustToDust.Core Spectators = new SpectatorRing(seed + 101); var rawCover = BuildCoverBoxes(); Terrain = TerrainField.Generate((ulong)seed, rawCover); + ScarLedger = new ArenaScarLedger($"desert:{seed}"); + if (initialScars is not null) + { + ApplyPersistentScars(initialScars); + } ArenaCoverBoxes = SeatBoxesOnTerrain(rawCover, Terrain); ArenaBoundaryBoxes = BuildBoundaryBoxes(ArenaHalfExtent, -48f, 72f); SpawnContenders(); @@ -531,7 +545,46 @@ namespace RustToDust.Core public int? WinnerContenderId { get; set; } public TerrainField Terrain { get; } + public ArenaScarLedger ScarLedger { get; } public List Contenders { get; } = new(); + + public void ApplyPersistentScars(ArenaScarLedgerSnapshot snapshot) + { + ScarLedger.LoadFromSnapshot(snapshot); + ScarLedger.ApplyToTerrain(Terrain); + } + + public void ApplyTerrainStamp(TerrainStampEvent stamp, bool recordInLedger = true) + { + switch ((TerrainStampKind)stamp.Kind) + { + case TerrainStampKind.Crater: + Terrain.StampCrater(stamp.X, stamp.Z, stamp.Radius, stamp.Depth); + break; + case TerrainStampKind.Scorch: + Terrain.StampScorch(stamp.X, stamp.Z, stamp.Radius); + break; + case TerrainStampKind.Track: + Terrain.StampTrack(stamp.X, stamp.Z, stamp.Yaw, stamp.Radius, stamp.Length); + return; + case TerrainStampKind.Rubble: + Terrain.StampRubble(stamp.X, stamp.Z, stamp.Radius, stamp.Depth, stamp.Yaw); + break; + } + if (recordInLedger) + { + ScarLedger.RecordTerrainStamp(stamp); + } + } + + public void RepairArenaScars() + { + Terrain.ClearDynamicScars(); + ScarLedger.Clear(); + } + + public bool IsSolidBuildingAtXz(float x, float z, float padding = 0f) => + SionMap is not null && SionMap.IsInsideAnyBuildingXz(x, z, padding); public SpectatorRing Spectators { get; } public List GroundDrops { get; } = new(); public List Tracers { get; } = new(); diff --git a/src/RustToDust.Core/OrbitalDropSystem.cs b/src/RustToDust.Core/OrbitalDropSystem.cs index 9852b1d..33f56cd 100644 --- a/src/RustToDust.Core/OrbitalDropSystem.cs +++ b/src/RustToDust.Core/OrbitalDropSystem.cs @@ -1475,8 +1475,21 @@ namespace RustToDust.Core { if (emitEvents && !touchSample.IsBuildingRoof) { - _state.Terrain.StampCrater(pod.X, pod.Z, pod.PodKind == OrbitalPodKind.Contender ? 3.4f : 2.1f, 0.32f); - _state.Terrain.StampScorch(pod.X, pod.Z, pod.PodKind == OrbitalPodKind.Contender ? 4.2f : 2.6f); + _state.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = pod.X, + Z = pod.Z, + Radius = pod.PodKind == OrbitalPodKind.Contender ? 3.4f : 2.1f, + Depth = 0.32f + }); + _state.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Scorch, + X = pod.X, + Z = pod.Z, + Radius = pod.PodKind == OrbitalPodKind.Contender ? 4.2f : 2.6f + }); } // Re-sample ground height after crater stamp diff --git a/src/RustToDust.Core/SimEvents.cs b/src/RustToDust.Core/SimEvents.cs index 19d7231..ef9fe75 100644 --- a/src/RustToDust.Core/SimEvents.cs +++ b/src/RustToDust.Core/SimEvents.cs @@ -8,7 +8,8 @@ namespace RustToDust.Core { Crater = 0, Scorch = 1, - Track = 2 + Track = 2, + Rubble = 3 } public enum SlotControlReason : byte @@ -34,6 +35,7 @@ namespace RustToDust.Core [Union(12, typeof(DropPodEvent))] [Union(13, typeof(OrdnanceNodeEvent))] [Union(14, typeof(MatchStartedEvent))] + [Union(17, typeof(ArenaRepairEvent))] public interface ISimEvent { } @@ -323,6 +325,7 @@ namespace RustToDust.Core [Key(15)] public LobbySnapshotDto? Lobby { get; set; } [Key(16)] public byte SquadSize { get; set; } = 1; [Key(17)] public byte[]? ContenderSquadIds { get; set; } + [Key(18)] public byte[]? PersistentScars { get; set; } } [MessagePackObject] @@ -381,6 +384,7 @@ namespace RustToDust.Core [Union(12, typeof(LobbySnapshotMsg))] [Union(13, typeof(ClientKeepaliveMsg))] [Union(14, typeof(LobbySquadCmdMsg))] + [Union(15, typeof(RepairArenaCmdMsg))] public interface ISchemaWireMessage { } @@ -499,6 +503,18 @@ namespace RustToDust.Core [Key(1)] public LobbySnapshotDto Snapshot { get; set; } = new(); } + [MessagePackObject] + public sealed class ArenaRepairEvent : ISimEvent + { + [Key(0)] public uint LedgerRevision { get; set; } + } + + [MessagePackObject] + public sealed class RepairArenaCmdMsg : ISchemaWireMessage + { + [Key(0)] public uint ReqSeq { get; set; } + } + [MessagePackObject] public sealed class ClientKeepaliveMsg : ISchemaWireMessage { diff --git a/src/RustToDust.Core/SionMapLoader.cs b/src/RustToDust.Core/SionMapLoader.cs index df3c5d9..6b01875 100644 --- a/src/RustToDust.Core/SionMapLoader.cs +++ b/src/RustToDust.Core/SionMapLoader.cs @@ -2,6 +2,7 @@ using System; using System.Buffers.Binary; using System.Collections.Generic; using System.IO; +using System.IO.Compression; using System.Numerics; using System.Text.Json; @@ -29,7 +30,14 @@ namespace RustToDust.Core float MinY, float MaxY, string SurfaceTexture, - IReadOnlyList Tiles); + IReadOnlyList Tiles, + string DemAssetHash = "", + string HeightmapFile = "heightmap_05m.u16z", + float HeightmapMinY = 0f, + float HeightmapScale = 1f, + string SurfaceMaskTexture = "terrain_surface_mask.png", + int BuildingTileGrid = 6, + float BuildingTileSizeMeters = 512f); public readonly record struct SionBuildingAabb( string Id, @@ -76,7 +84,7 @@ namespace RustToDust.Core { private const int SpatialGridRes = 64; - private readonly float[] _heights; + private readonly ushort[] _baseDem; private readonly SionBuildingAabb[] _buildings; private readonly List[] _cellBuildings; private readonly float[] _cellMinGroundY; @@ -87,13 +95,20 @@ namespace RustToDust.Core internal SionMapData( string directoryPath, SionMetadata metadata, - float[] heights, + ushort[] baseDem, + float baseDemMinY, + float baseDemScale, SionBuildingAabb[] buildings, SionCollisionMesh[] collisionMeshes) { DirectoryPath = directoryPath; Metadata = metadata; - _heights = heights; + _baseDem = baseDem; + BaseDemMinY = baseDemMinY; + BaseDemScale = baseDemScale; + AssetFingerprint = !string.IsNullOrWhiteSpace(metadata.DemAssetHash) + ? $"sion:{metadata.DemAssetHash}" + : $"sion:{metadata.GridRes}:{metadata.CellSizeMeters:F3}"; _buildings = buildings; CollisionMeshes = collisionMeshes; @@ -131,7 +146,11 @@ namespace RustToDust.Core public string DirectoryPath { get; } public SionMetadata Metadata { get; } - public ReadOnlySpan Heights => _heights; + public ushort[] BaseDem => _baseDem; + public float BaseDemMinY { get; } + public float BaseDemScale { get; } + public string AssetFingerprint { get; } + public float SampleBaseDemAtIndex(int index) => BaseDemMinY + _baseDem[index] * BaseDemScale; public IReadOnlyList Buildings => _buildings; public IReadOnlyList CollisionMeshes { get; } @@ -324,12 +343,12 @@ namespace RustToDust.Core AssetPathResolver.LocateSubdirectory( Path.Combine("maps", "sion"), IsValidSionDirectory, - "containing metadata.json and heightmap.f32"); + "containing metadata.json and heightmap_05m.u16z"); private static bool IsValidSionDirectory(string dir) => Directory.Exists(dir) && File.Exists(Path.Combine(dir, "metadata.json")) && - File.Exists(Path.Combine(dir, "heightmap.f32")) && + File.Exists(Path.Combine(dir, "heightmap_05m.u16z")) && File.Exists(Path.Combine(dir, "buildings_manifest.json")); public static SionMapData Load(string? sionDirectory = null) @@ -344,7 +363,12 @@ namespace RustToDust.Core } var meta = LoadMetadata(Path.Combine(root, "metadata.json")); - float[] heights = LoadHeightmap(Path.Combine(root, "heightmap.f32"), meta.GridRes); + string hmFile = string.IsNullOrWhiteSpace(meta.HeightmapFile) ? "heightmap_05m.u16z" : meta.HeightmapFile; + ushort[] baseDem = LoadHeightmapU16z( + Path.Combine(root, hmFile), + meta.GridRes, + out float demMinY, + out float demScale); SionBuildingAabb[] buildings = LoadBuildingsManifest(Path.Combine(root, "buildings_manifest.json")); var colMeshes = new SionCollisionMesh[meta.Tiles.Count]; for (int i = 0; i < meta.Tiles.Count; i++) @@ -354,7 +378,7 @@ namespace RustToDust.Core colMeshes[i] = LoadRcolFile(colPath, t.Tx, t.Tz); } - var data = new SionMapData(root, meta, heights, buildings, colMeshes); + var data = new SionMapData(root, meta, baseDem, demMinY, demScale, buildings, colMeshes); lock (CacheLock) { Cache[root] = data; @@ -395,29 +419,82 @@ namespace RustToDust.Core MinY: r.GetProperty("minY").GetSingle(), MaxY: r.GetProperty("maxY").GetSingle(), SurfaceTexture: r.GetProperty("surfaceTexture").GetString() ?? "terrain_surface.png", - Tiles: tiles); + Tiles: tiles, + DemAssetHash: r.TryGetProperty("demAssetHash", out var dh) ? (dh.GetString() ?? "") : "", + HeightmapFile: r.TryGetProperty("heightmapFile", out var hf) ? (hf.GetString() ?? "heightmap_05m.u16z") : "heightmap_05m.u16z", + HeightmapMinY: r.TryGetProperty("heightmapMinY", out var hmin) ? hmin.GetSingle() : 0f, + HeightmapScale: r.TryGetProperty("heightmapScale", out var hsc) ? hsc.GetSingle() : 1f, + SurfaceMaskTexture: r.TryGetProperty("surfaceMaskTexture", out var sm) ? (sm.GetString() ?? "terrain_surface_mask.png") : "terrain_surface_mask.png", + BuildingTileGrid: r.TryGetProperty("buildingTileGrid", out var btg) ? btg.GetInt32() : 6, + BuildingTileSizeMeters: r.TryGetProperty("buildingTileSizeMeters", out var bts) ? bts.GetSingle() : 512f); } - private static float[] LoadHeightmap(string path, int gridRes) + private static ushort[] LoadHeightmapU16z(string path, int expectedGridRes, out float minY, out float scale) { - byte[] raw = File.ReadAllBytes(path); - int expectedCount = gridRes * gridRes; - if (raw.Length != expectedCount * 4) + byte[] fileBytes = File.ReadAllBytes(path); + if (fileBytes.Length < 24) { - throw new InvalidDataException( - $"Expected heightmap.f32 byte length {expectedCount * 4} ({gridRes}x{gridRes}), got {raw.Length}."); + throw new InvalidDataException($"Heightmap file '{path}' too small ({fileBytes.Length} bytes)."); } - var heights = new float[expectedCount]; - ReadOnlySpan span = raw; - for (int i = 0; i < expectedCount; i++) + ReadOnlySpan hdr = fileBytes.AsSpan(0, 24); + if (hdr[0] != (byte)'R' || hdr[1] != (byte)'D' || hdr[2] != (byte)'H' || hdr[3] != (byte)'M') { - float v = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(i * 4, 4)); - if (!float.IsFinite(v)) + throw new InvalidDataException($"Invalid RDHM magic in '{path}'."); + } + + uint version = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4)); + if (version != 2) + { + throw new InvalidDataException($"Unsupported RDHM version {version} in '{path}'."); + } + + int gridRes = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(8, 4))); + if (gridRes != expectedGridRes) + { + throw new InvalidDataException($"RDHM gridRes mismatch in '{path}': header={gridRes}, metadata={expectedGridRes}."); + } + + minY = BinaryPrimitives.ReadSingleLittleEndian(hdr.Slice(12, 4)); + scale = BinaryPrimitives.ReadSingleLittleEndian(hdr.Slice(16, 4)); + int rawByteCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(20, 4))); + int expectedSamples = gridRes * gridRes; + if (rawByteCount != expectedSamples * 2) + { + throw new InvalidDataException($"RDHM rawByteCount mismatch in '{path}': {rawByteCount} != {expectedSamples * 2}."); + } + + byte[] raw = new byte[rawByteCount]; + using (var ms = new MemoryStream(fileBytes, 24, fileBytes.Length - 24, writable: false)) + using (var zlib = new ZLibStream(ms, CompressionMode.Decompress)) + { + int totalRead = 0; + while (totalRead < rawByteCount) { - throw new InvalidDataException($"Non-finite heightmap value at index {i}: {v}"); + int read = zlib.Read(raw, totalRead, rawByteCount - totalRead); + if (read <= 0) + { + throw new InvalidDataException($"Unexpected EOF decompressing RDHM payload in '{path}' at {totalRead}/{rawByteCount}."); + } + totalRead += read; + } + } + + var heights = new ushort[expectedSamples]; + ReadOnlySpan span = raw; + for (int r = 0; r < gridRes; r++) + { + int rowStart = r * gridRes; + ushort pred = r > 0 ? heights[(r - 1) * gridRes] : (ushort)0; + for (int c = 0; c < gridRes; c++) + { + int idx = rowStart + c; + ushort zz = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(idx * 2, 2)); + short d = unchecked((short)((zz >> 1) ^ -(zz & 1))); + ushort val = unchecked((ushort)(pred + d)); + heights[idx] = val; + pred = val; } - heights[i] = v; } return heights; } diff --git a/src/RustToDust.Core/TerrainField.cs b/src/RustToDust.Core/TerrainField.cs index faa3738..9087c16 100644 --- a/src/RustToDust.Core/TerrainField.cs +++ b/src/RustToDust.Core/TerrainField.cs @@ -11,7 +11,8 @@ namespace RustToDust.Core Road, Crater, Track, - Scorch + Scorch, + Rubble } public readonly record struct TerrainBrush( @@ -34,8 +35,8 @@ namespace RustToDust.Core { public const float ArenaSize = 1536f; public const float HalfExtent = 768f; - public const int TileGridCount = 8; - public const float TileSize = ArenaSize / TileGridCount; // 192m + public const int DesertTileGridCount = 8; + public const float TileSize = ArenaSize / DesertTileGridCount; // 192m private const int AccelGridCount = 64; private const int AccelCellCount = AccelGridCount * AccelGridCount; public const float MinWorldHeight = -18f; @@ -64,21 +65,33 @@ namespace RustToDust.Core private readonly List _brushes = new(); private readonly List _brushPrecomps = new(); - private readonly List[,] _tileBrushIndices = new List[TileGridCount, TileGridCount]; + private readonly List[,] _tileBrushIndices; private readonly List[] _cellBrushIndices = new List[AccelCellCount]; private readonly float[] _cellMaxHeight = new float[AccelCellCount]; private readonly float[] _cellBaseMaxHeight = new float[AccelCellCount]; private readonly Queue _dynamicDecalSlots = new(); private float[]? _heightmap; + private ushort[]? _sharedU16Heights; + private float _baseMinY; + private float _baseScale; + private readonly float[]?[,] _scarredTileHeights; private int _nextBrushId = 1; - public TerrainField(ulong seed) + public TerrainField(ulong seed, int tileGridCount = DesertTileGridCount) { - Seed = seed; - TileVersions = new int[TileGridCount, TileGridCount]; - for (int tz = 0; tz < TileGridCount; tz++) + if (tileGridCount <= 0) { - for (int tx = 0; tx < TileGridCount; tx++) + throw new ArgumentOutOfRangeException(nameof(tileGridCount)); + } + Seed = seed; + TileGridCount = tileGridCount; + StructuralTileVersions = new int[tileGridCount, tileGridCount]; + VisualTileVersions = new int[tileGridCount, tileGridCount]; + _tileBrushIndices = new List[tileGridCount, tileGridCount]; + _scarredTileHeights = new float[tileGridCount, tileGridCount][]; + for (int tz = 0; tz < tileGridCount; tz++) + { + for (int tx = 0; tx < tileGridCount; tx++) { _tileBrushIndices[tx, tz] = new List(32); } @@ -90,6 +103,7 @@ namespace RustToDust.Core } public ulong Seed { get; } + public int TileGridCount { get; } public bool IsHeightmapMode { get; private set; } public float MapSize { get; private set; } = ArenaSize; public float MapHalfExtent { get; private set; } = HalfExtent; @@ -98,11 +112,15 @@ namespace RustToDust.Core public float MapMaxHeight { get; private set; } = MaxWorldHeight; public int HeightmapRes { get; private set; } public float HeightmapCellSize { get; private set; } + public int PhysicsTileResolution => IsHeightmapMode ? ((HeightmapRes - 1) / TileGridCount + 1) : 0; + public ushort[]? SharedU16Heights => _sharedU16Heights; + public float BaseMinY => _baseMinY; + public float BaseScale => _baseScale; private float AccelCellSize => MapSize / AccelGridCount; public IReadOnlyList Brushes => _brushes; - public int[,] TileVersions { get; } - public ulong DirtyTileMask { get; private set; } - public ulong StructuralDirtyTileMask { get; private set; } + public int[,] StructuralTileVersions { get; } + public int[,] VisualTileVersions { get; } + public int[,] TileVersions => VisualTileVersions; public static TerrainField LoadHeightmap( float sizeMeters, @@ -125,12 +143,13 @@ namespace RustToDust.Core throw new ArgumentException($"Expected {gridRes * gridRes} height samples, got {heights.Length}.", nameof(heights)); } - var field = new TerrainField(seed) + int tileGridCount = Math.Max(1, (int)MathF.Round(sizeMeters / TileSize)); + var field = new TerrainField(seed, tileGridCount) { IsHeightmapMode = true, MapSize = sizeMeters, MapHalfExtent = sizeMeters * 0.5f, - MapTileSize = sizeMeters / TileGridCount, + MapTileSize = sizeMeters / tileGridCount, MapMinHeight = minY - 8f, MapMaxHeight = maxY + 4f, HeightmapRes = gridRes, @@ -138,9 +157,58 @@ namespace RustToDust.Core _heightmap = heights.ToArray() }; - float half = field.MapHalfExtent; - float cellSize = field.AccelCellSize; - float invDemStep = 1f / field.HeightmapCellSize; + field.InitializeAccelGridFromHeightmap(gridRes); + return field; + } + + public static TerrainField LoadSharedHeightmap( + float sizeMeters, + int gridRes, + int tileGridCount, + ushort[] sharedU16Heights, + float baseMinY, + float baseScale, + float worldMinY, + float worldMaxY, + ulong seed = 0UL) + { + if (sizeMeters <= 0f || !float.IsFinite(sizeMeters)) + { + throw new ArgumentOutOfRangeException(nameof(sizeMeters)); + } + if (gridRes < 2) + { + throw new ArgumentOutOfRangeException(nameof(gridRes)); + } + if (sharedU16Heights is null || sharedU16Heights.Length != gridRes * gridRes) + { + throw new ArgumentException($"Expected {gridRes * gridRes} u16 height samples, got {sharedU16Heights?.Length ?? 0}.", nameof(sharedU16Heights)); + } + + var field = new TerrainField(seed, tileGridCount) + { + IsHeightmapMode = true, + MapSize = sizeMeters, + MapHalfExtent = sizeMeters * 0.5f, + MapTileSize = sizeMeters / tileGridCount, + MapMinHeight = worldMinY - 8f, + MapMaxHeight = worldMaxY + 4f, + HeightmapRes = gridRes, + HeightmapCellSize = sizeMeters / (gridRes - 1), + _sharedU16Heights = sharedU16Heights, + _baseMinY = baseMinY, + _baseScale = baseScale + }; + + field.InitializeAccelGridFromHeightmap(gridRes); + return field; + } + + private void InitializeAccelGridFromHeightmap(int gridRes) + { + float half = MapHalfExtent; + float cellSize = AccelCellSize; + float invDemStep = 1f / HeightmapCellSize; for (int cz = 0; cz < AccelGridCount; cz++) { @@ -162,7 +230,9 @@ namespace RustToDust.Core int row = iz * gridRes; for (int ix = ix0; ix <= ix1; ix++) { - float h = field._heightmap[row + ix]; + float h = _sharedU16Heights is not null + ? _baseMinY + _sharedU16Heights[row + ix] * _baseScale + : _heightmap![row + ix]; if (h > cellMax) { cellMax = h; @@ -172,8 +242,8 @@ namespace RustToDust.Core int cellIdx = cz * AccelGridCount + cx; float boundedMax = float.IsNegativeInfinity(cellMax) ? 0f : cellMax + 0.05f; - field._cellBaseMaxHeight[cellIdx] = boundedMax; - field._cellMaxHeight[cellIdx] = boundedMax; + _cellBaseMaxHeight[cellIdx] = boundedMax; + _cellMaxHeight[cellIdx] = boundedMax; } } @@ -181,23 +251,12 @@ namespace RustToDust.Core { for (int tx = 0; tx < TileGridCount; tx++) { - field.TileVersions[tx, tz] = 1; - field.DirtyTileMask |= 1UL << (tz * TileGridCount + tx); + StructuralTileVersions[tx, tz] = 1; + VisualTileVersions[tx, tz] = 1; } } - - return field; } - public void ClearDirtyMask() - { - DirtyTileMask = 0UL; - StructuralDirtyTileMask = 0UL; - } - - public void ClearStructuralDirtyTile(int tx, int tz) => - StructuralDirtyTileMask &= ~(1UL << (tz * TileGridCount + tx)); - public IReadOnlyList GetTileBrushIndices(int tx, int tz) => _tileBrushIndices[tx, tz]; public static TerrainField Generate(ulong seed, IReadOnlyList coverBoxes) @@ -400,12 +459,12 @@ namespace RustToDust.Core } // Bump all initial tile versions to 1 so clients detect initial bake needed - for (int tz = 0; tz < TileGridCount; tz++) + for (int tz = 0; tz < field.TileGridCount; tz++) { - for (int tx = 0; tx < TileGridCount; tx++) + for (int tx = 0; tx < field.TileGridCount; tx++) { - field.TileVersions[tx, tz] = 1; - field.DirtyTileMask |= 1UL << (tz * TileGridCount + tx); + field.StructuralTileVersions[tx, tz] = 1; + field.VisualTileVersions[tx, tz] = 1; } } @@ -433,6 +492,27 @@ namespace RustToDust.Core Dynamic: true)); } + public void StampRubble(float x, float z, float radius, float heightDelta, float yaw = 0f) + { + float clampedR = Math.Clamp(radius, 1.5f, 18f); + float clampedH = Math.Clamp(MathF.Abs(heightDelta), 0.15f, 2.5f); + AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Rubble, + X: x, + Z: z, + RotationRad: yaw, + RadiusX: clampedR, + RadiusZ: clampedR, + HeightDelta: clampedH, + Roughness: 0.97f, + Metallic: 0.05f, + AlbedoR: 0.42f, + AlbedoG: 0.39f, + AlbedoB: 0.35f, + Dynamic: true)); + } + public void StampTrack(float x, float z, float yaw, float width, float length) { SetDynamicDecal(new TerrainBrush( @@ -472,13 +552,30 @@ namespace RustToDust.Core Dynamic: true)); } - public float SampleHeight(float x, float z) + public float SampleBaseHeight(float x, float z) { float half = MapHalfExtent; float cx = Math.Clamp(x, -half, half); float cz = Math.Clamp(z, -half, half); - float h = 0f; + if (_sharedU16Heights is not null) + { + int res = HeightmapRes; + float fx = Math.Clamp((cx + half) / HeightmapCellSize, 0f, res - 1f); + float fz = Math.Clamp((cz + half) / HeightmapCellSize, 0f, res - 1f); + int ix = Math.Clamp((int)fx, 0, res - 2); + int iz = Math.Clamp((int)fz, 0, res - 2); + float tx = Math.Clamp(fx - ix, 0f, 1f); + float tz = Math.Clamp(fz - iz, 0f, 1f); + int row0 = iz * res; + int row1 = row0 + res; + float h00 = _baseMinY + _sharedU16Heights[row0 + ix] * _baseScale; + float h10 = _baseMinY + _sharedU16Heights[row0 + ix + 1] * _baseScale; + float h01 = _baseMinY + _sharedU16Heights[row1 + ix] * _baseScale; + float h11 = _baseMinY + _sharedU16Heights[row1 + ix + 1] * _baseScale; + return (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz; + } + if (_heightmap is not null) { int res = HeightmapRes; @@ -494,9 +591,20 @@ namespace RustToDust.Core float h10 = _heightmap[row0 + ix + 1]; float h01 = _heightmap[row1 + ix]; float h11 = _heightmap[row1 + ix + 1]; - h = (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz; + return (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz; } + return 0f; + } + + public float SampleHeight(float x, float z) + { + float half = MapHalfExtent; + float cx = Math.Clamp(x, -half, half); + float cz = Math.Clamp(z, -half, half); + + float h = SampleBaseHeight(cx, cz); + WorldToAccelCell(cx, cz, out int acx, out int acz); var indices = _cellBrushIndices[acz * AccelGridCount + acx]; for (int i = 0; i < indices.Count; i++) @@ -509,6 +617,165 @@ namespace RustToDust.Core return Math.Clamp(h, MapMinHeight, MapMaxHeight); } + public void ExtractTilePhysicsHeights(int tx, int tz, Span dst, out float minY, out float maxY) + { + if ((uint)tx >= (uint)TileGridCount || (uint)tz >= (uint)TileGridCount) + { + throw new ArgumentOutOfRangeException(nameof(tx)); + } + if (!IsHeightmapMode) + { + throw new InvalidOperationException("ExtractTilePhysicsHeights requires heightmap mode."); + } + + int samplesPerTile = (HeightmapRes - 1) / TileGridCount; + int side = samplesPerTile + 1; + int count = side * side; + if (dst.Length < count) + { + throw new ArgumentException($"Destination span too small: need {count}, got {dst.Length}.", nameof(dst)); + } + + int gx0 = tx * samplesPerTile; + int gz0 = tz * samplesPerTile; + var tileBrushes = _tileBrushIndices[tx, tz]; + bool hasStructuralBrushes = false; + for (int i = 0; i < tileBrushes.Count; i++) + { + var k = _brushes[tileBrushes[i]].Kind; + if (k != TerrainBrushKind.Track && k != TerrainBrushKind.Scorch) + { + hasStructuralBrushes = true; + break; + } + } + + float minVal = float.PositiveInfinity; + float maxVal = float.NegativeInfinity; + float half = MapHalfExtent; + float step = HeightmapCellSize; + int res = HeightmapRes; + + for (int lz = 0; lz < side; lz++) + { + int gz = gz0 + lz; + int globalRow = gz * res + gx0; + int localRow = lz * side; + float wz = -half + gz * step; + + for (int lx = 0; lx < side; lx++) + { + float h = _sharedU16Heights is not null + ? _baseMinY + _sharedU16Heights[globalRow + lx] * _baseScale + : _heightmap![globalRow + lx]; + + if (hasStructuralBrushes) + { + float wx = -half + (gx0 + lx) * step; + for (int bi = 0; bi < tileBrushes.Count; bi++) + { + int bIdx = tileBrushes[bi]; + var b = _brushes[bIdx]; + if (b.Kind == TerrainBrushKind.Track || b.Kind == TerrainBrushKind.Scorch) + { + continue; + } + h += EvaluateBrushHeightFast(in b, _brushPrecomps[bIdx], wx, wz); + } + } + + float clamped = Math.Clamp(h, MapMinHeight, MapMaxHeight); + dst[localRow + lx] = clamped; + if (clamped < minVal) minVal = clamped; + if (clamped > maxVal) maxVal = clamped; + } + } + + if (hasStructuralBrushes) + { + var cached = _scarredTileHeights[tx, tz]; + if (cached is null || cached.Length != count) + { + cached = new float[count]; + _scarredTileHeights[tx, tz] = cached; + } + dst.Slice(0, count).CopyTo(cached); + } + else + { + _scarredTileHeights[tx, tz] = null; + } + + minY = float.IsPositiveInfinity(minVal) ? 0f : minVal; + maxY = float.IsNegativeInfinity(maxVal) ? 0f : maxVal; + } + + public void ClearDynamicScars() + { + if (_brushes.Count == 0) + { + return; + } + + bool anyDynamic = false; + var staticBrushes = new List(_brushes.Count); + for (int i = 0; i < _brushes.Count; i++) + { + if (_brushes[i].Dynamic) + { + anyDynamic = true; + GetBrushTileBounds(_brushes[i], out int minTx, out int maxTx, out int minTz, out int maxTz); + bool isStructural = _brushes[i].Kind != TerrainBrushKind.Track && _brushes[i].Kind != TerrainBrushKind.Scorch; + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + VisualTileVersions[tx, tz]++; + if (isStructural) + { + StructuralTileVersions[tx, tz]++; + } + _scarredTileHeights[tx, tz] = null; + } + } + } + else + { + staticBrushes.Add(_brushes[i]); + } + } + + if (!anyDynamic) + { + return; + } + + _brushes.Clear(); + _brushPrecomps.Clear(); + _dynamicDecalSlots.Clear(); + for (int tz = 0; tz < TileGridCount; tz++) + { + for (int tx = 0; tx < TileGridCount; tx++) + { + _tileBrushIndices[tx, tz].Clear(); + } + } + for (int c = 0; c < AccelCellCount; c++) + { + _cellBrushIndices[c].Clear(); + _cellMaxHeight[c] = _cellBaseMaxHeight[c]; + } + + for (int i = 0; i < staticBrushes.Count; i++) + { + int idx = _brushes.Count; + var b = staticBrushes[i]; + _brushes.Add(b); + _brushPrecomps.Add(BrushPrecomp.From(in b)); + RegisterBrushInTiles(idx, in b, incrementTileVersion: false); + } + } + public (float Nx, float Ny, float Nz) SampleNormal(float x, float z) { const float eps = 0.5f; @@ -723,6 +990,13 @@ namespace RustToDust.Core float rim = (0.32f * depth) * rimT * rimT; return pit + rim; } + case TerrainBrushKind.Rubble: + { + float env = 1f - r2; + env *= env; + float mound = 0.72f + 0.28f * MathF.Cos(u * MathF.PI * 2.5f); + return b.HeightDelta * env * mound; + } default: return 0f; } @@ -854,6 +1128,12 @@ namespace RustToDust.Core case TerrainBrushKind.Crater: cellMaxPositiveHeight = 0.33f * MathF.Abs(b.HeightDelta); break; + case TerrainBrushKind.Rubble: + { + float env = 1f - minR2; + cellMaxPositiveHeight = MathF.Max(0f, b.HeightDelta) * env * env; + break; + } default: cellMaxPositiveHeight = 0f; break; @@ -889,12 +1169,11 @@ namespace RustToDust.Core _tileBrushIndices[tx, tz].Add(index); if (incrementTileVersion) { - TileVersions[tx, tz]++; - ulong bit = 1UL << (tz * TileGridCount + tx); - DirtyTileMask |= bit; + VisualTileVersions[tx, tz]++; if (isStructural) { - StructuralDirtyTileMask |= bit; + StructuralTileVersions[tx, tz]++; + _scarredTileHeights[tx, tz] = null; } } } @@ -928,12 +1207,11 @@ namespace RustToDust.Core for (int tx = minTx; tx <= maxTx; tx++) { _tileBrushIndices[tx, tz].Remove(index); - TileVersions[tx, tz]++; - ulong bit = 1UL << (tz * TileGridCount + tx); - DirtyTileMask |= bit; + VisualTileVersions[tx, tz]++; if (isStructural) { - StructuralDirtyTileMask |= bit; + StructuralTileVersions[tx, tz]++; + _scarredTileHeights[tx, tz] = null; } } } @@ -997,8 +1275,8 @@ namespace RustToDust.Core { float nx = (x + HalfExtent) / TileSize; float nz = (z + HalfExtent) / TileSize; - tx = Math.Clamp((int)MathF.Floor(nx), 0, TileGridCount - 1); - tz = Math.Clamp((int)MathF.Floor(nz), 0, TileGridCount - 1); + tx = Math.Clamp((int)MathF.Floor(nx), 0, DesertTileGridCount - 1); + tz = Math.Clamp((int)MathF.Floor(nz), 0, DesertTileGridCount - 1); } private static bool IsBrushClearOfCover(in TerrainBrush candidate, IReadOnlyList coverBoxes) diff --git a/src/RustToDust.Net/ListenHostArenaSession.cs b/src/RustToDust.Net/ListenHostArenaSession.cs index 0b55556..1c34649 100644 --- a/src/RustToDust.Net/ListenHostArenaSession.cs +++ b/src/RustToDust.Net/ListenHostArenaSession.cs @@ -114,7 +114,7 @@ namespace RustToDust.Net public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation) { - var hit = _host.Session.World.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z)); + var hit = _host.Session.CastWorldRayClosest(origin, translation); return new ClientRayHit( hit.Hit, hit.StableId, diff --git a/src/RustToDust.Net/RemoteArenaSession.cs b/src/RustToDust.Net/RemoteArenaSession.cs index 6d8b5e9..d8dd6ad 100644 --- a/src/RustToDust.Net/RemoteArenaSession.cs +++ b/src/RustToDust.Net/RemoteArenaSession.cs @@ -52,10 +52,13 @@ namespace RustToDust.Net private MatchState _viewState; private Box3DSoaWorld? _predWorld; + private readonly Box3DPhysicsTileSync _predTileSync = new(); private Box3DSoaBodyHandle? _predBody; private WalkerState? _predWalker; private string _predChassisId = string.Empty; + public Box3DPhysicsTileSync PredTileSync => _predTileSync; + private Vector3 _predErrorPos; private Quaternion _predErrorRot = Quaternion.Identity; private bool _pendingChassisSwapSnap; @@ -518,7 +521,7 @@ namespace RustToDust.Net var staticHit = _predWorld.CastRayClosest( (origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z)); - if (staticHit.Hit && staticHit.StableId < ArenaSession.ContenderStableIdBase) + if (staticHit.Hit && ArenaSession.IsStaticWorldStableId(staticHit.StableId)) { bestFrac = staticHit.Fraction; best = new ClientRayHit( @@ -854,6 +857,12 @@ namespace RustToDust.Net _timeSinceLastPhysicsPodStep = 0f; _physicsPodSteppingActive = false; + if (dto.PersistentScars is { Length: > 0 }) + { + var snap = ArenaScarLedger.DecompressSnapshot(dto.PersistentScars); + _viewState.ApplyPersistentScars(snap); + } + for (int i = 0; i < dto.TerrainStamps.Count; i++) { ApplyTerrainStamp(dto.TerrainStamps[i]); @@ -948,12 +957,17 @@ namespace RustToDust.Net { _predWorld?.Dispose(); _predWorld = new Box3DSoaWorld(capacity: 256, gravityX: 0f, gravityY: -20f, gravityZ: 0f); - ArenaSession.BuildStaticArena(_predWorld, _viewState); + _predTileSync.Reset(); + ArenaSession.BuildStaticArena(_predWorld, _viewState, _predTileSync, warmAllActors: false); + var local = LocalContender; + if (_viewState.Terrain.IsHeightmapMode) + { + _predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1); + } _predBody = null; _predWalker = null; _predChassisId = string.Empty; - var local = LocalContender; var q = NormalizeQuat(new Quaternion(local.CurrRotX, local.CurrRotY, local.CurrRotZ, local.CurrRotW)); SpawnLocalPredictionBody(new Vector3(local.X, local.Y, local.Z), q, Vector3.Zero, Vector3.Zero); } @@ -1184,6 +1198,10 @@ namespace RustToDust.Net ArenaSession.FixedDt, injectEngineHeat: false, world: _predWorld); + if (_viewState.Terrain.IsHeightmapMode) + { + _predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1); + } _predWorld.Step(ArenaSession.FixedDt, subSteps); ArenaSession.SyncContenderPoseFromLane(local, _predWorld.View, _predBody.Value.Lane, _predWalker); } @@ -1273,6 +1291,10 @@ namespace RustToDust.Net local.VelY = pkt.LocalVel.Y; local.VelZ = pkt.LocalVel.Z; local.TargetHoverAltAgl = pkt.LocalTargetHoverAltAgl; + if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode) + { + _predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1); + } SpawnLocalPredictionBody(pkt.LocalPos, pkt.LocalRot, pkt.LocalVel, pkt.LocalAngVel); if (local.Lifecycle == ContenderLifecycle.Deploying && @@ -1631,6 +1653,13 @@ namespace RustToDust.Net case TerrainStampEvent stamp: ApplyTerrainStamp(stamp); break; + case ArenaRepairEvent: + _viewState.RepairArenaScars(); + if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode) + { + _predTileSync.SyncWindow(_predWorld, _viewState.Terrain, LocalContender.X, LocalContender.Z, halfTileRadius: 1); + } + break; case DropSpawnedEvent ds: _viewState.ApplyReplicatedDropSpawned( ds.DropId, ds.X, ds.Z, @@ -1792,17 +1821,10 @@ namespace RustToDust.Net private void ApplyTerrainStamp(TerrainStampEvent stamp) { - switch ((TerrainStampKind)stamp.Kind) + _viewState.ApplyTerrainStamp(stamp, recordInLedger: true); + if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode) { - case TerrainStampKind.Crater: - _viewState.Terrain.StampCrater(stamp.X, stamp.Z, stamp.Radius, stamp.Depth); - break; - case TerrainStampKind.Scorch: - _viewState.Terrain.StampScorch(stamp.X, stamp.Z, stamp.Radius); - break; - case TerrainStampKind.Track: - _viewState.Terrain.StampTrack(stamp.X, stamp.Z, stamp.Yaw, stamp.Radius, stamp.Length); - break; + _predTileSync.SyncWindow(_predWorld, _viewState.Terrain, LocalContender.X, LocalContender.Z, halfTileRadius: 1); } } diff --git a/src/RustToDust.Net/ServerMatchHost.cs b/src/RustToDust.Net/ServerMatchHost.cs index 49c1c77..4979a82 100644 --- a/src/RustToDust.Net/ServerMatchHost.cs +++ b/src/RustToDust.Net/ServerMatchHost.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Net; using System.Net.Sockets; using System.Numerics; @@ -32,6 +33,8 @@ namespace RustToDust.Net public readonly HashSet SentDropIds = new(); public readonly HashSet SentPodIds = new(); public readonly HashSet SentOrdnanceIds = new(); + public readonly HashSet SentTerrainStampIndices = new(); + public readonly int[,] SentTileVersions = new int[16, 16]; } private struct EntityPvsTracker @@ -51,6 +54,9 @@ namespace RustToDust.Net private readonly List _stepEvents = new(); private readonly List _hostPendingEvents = new(); private readonly List _terrainStampHistory = new(); + private readonly List[,] _tileStampHistory = new List[16, 16]; + private readonly string? _scarFilePath; + private readonly bool _persistScars; private readonly int _maxHumans; private readonly double _autoRestartSec; private readonly bool _allowClientReset; @@ -72,6 +78,7 @@ namespace RustToDust.Net private uint _nextPeerId = 1; private float _roundCompletedElapsed; private int _lastBroadcastCountdownSec = -1; + private uint _lastScarSaveTick; private bool _disposed; public ServerMatchHost( @@ -87,7 +94,10 @@ namespace RustToDust.Net string serverName = "Rust to Dust", int minHumansToStart = 1, bool restartToLobby = false, - byte squadSize = 1) + byte squadSize = 1, + string? scarFilePath = null, + bool persistScars = false, + bool repairScarsOnStart = false) { _maxHumans = Math.Clamp(maxHumans, 1, MatchState.ContenderCount); _autoRestartSec = autoRestartSec; @@ -97,6 +107,17 @@ namespace RustToDust.Net _minHumansToStart = Math.Clamp(minHumansToStart, 1, _maxHumans); _restartToLobby = restartToLobby; _squadSize = (byte)Math.Clamp((int)squadSize, 1, 4); + _persistScars = persistScars; + _scarFilePath = persistScars + ? (string.IsNullOrWhiteSpace(scarFilePath) ? ArenaScarLedgerStore.GetDefaultPath(mapKind) : scarFilePath) + : null; + for (int tz = 0; tz < 16; tz++) + { + for (int tx = 0; tx < 16; tx++) + { + _tileStampHistory[tx, tz] = new List(4); + } + } _socket = new Socket(bindAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp) { @@ -117,7 +138,25 @@ namespace RustToDust.Net }); _server.PeerDisconnected += OnTransportPeerDisconnected; - _session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize); + ArenaScarLedgerSnapshot? initialScars = null; + if (_persistScars && _scarFilePath is not null) + { + if (repairScarsOnStart) + { + var emptySnap = new ArenaScarLedgerSnapshot + { + AssetFingerprint = mapKind == ArenaMapKind.Sion ? SionMapLoader.Load().AssetFingerprint : $"desert:{seed}" + }; + ArenaScarLedgerStore.Save(_scarFilePath, emptySnap); + } + else + { + string fp = mapKind == ArenaMapKind.Sion ? SionMapLoader.Load().AssetFingerprint : $"desert:{seed}"; + initialScars = ArenaScarLedgerStore.Load(_scarFilePath, fp); + } + } + + _session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize, initialScars: initialScars); if (hostContenderId.HasValue) { _session.SetHumanSlot(hostContenderId.Value, true, "Host"); @@ -170,19 +209,33 @@ namespace RustToDust.Net public void ResetMatch(int seed, ArenaMapKind mapKind) => ResetMatch(seed, mapKind, startInLobby: false); - public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby) + public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby) => + ResetMatch(seed, mapKind, startInLobby, repairScars: false); + + public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby, bool repairScars) { if (_hostContenderId.HasValue && _hostContenderId.Value >= 0 && _hostContenderId.Value < _session.State.Contenders.Count) { _hostCallsign = _session.State.Contenders[_hostContenderId.Value].Name; } + ArenaScarLedgerSnapshot? preservedScars = null; + if (mapKind == _session.State.MapKind) + { + if (repairScars) + { + _session.State.RepairArenaScars(); + } + preservedScars = _session.State.ScarLedger.ToSnapshot(); + } + FlushScarLedgerIfDirty(); _session.Dispose(); - _session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize); + _session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize, initialScars: preservedScars); _matchGeneration++; _simTick = 0; _roundCompletedElapsed = 0f; _lastBroadcastCountdownSec = -1; _terrainStampHistory.Clear(); + ClearTileStampHistory(); _stepEvents.Clear(); _hostPendingEvents.Clear(); _reconnectTokens.Clear(); @@ -588,12 +641,19 @@ namespace RustToDust.Net { if (_stepEvents[i] is TerrainStampEvent ts) { + int stampIdx = _terrainStampHistory.Count; _terrainStampHistory.Add(ts); + _session.State.Terrain.MapWorldToTile(ts.X, ts.Z, out int tx, out int tz); + _tileStampHistory[tx, tz].Add(stampIdx); } } FlushEventsAndPvsEnter(); BroadcastSnapshots(); + if (_persistScars && (_simTick - _lastScarSaveTick) >= 1800) + { + FlushScarLedgerIfDirty(); + } try { _server.PollResends(); @@ -700,6 +760,16 @@ namespace RustToDust.Net } } break; + case RepairArenaCmdMsg: + if (_peersByEndpoint.TryGetValue(epKey, out var repPeer) && repPeer.Active && ReferenceEquals(repPeer.TransportPeer, transportPeer)) + { + repPeer.LastHeardUtcMs = nowUtcMs; + if (_allowClientReset || (_hostContenderId.HasValue && _hostContenderId.Value == repPeer.AssignedContenderId)) + { + RepairArenaScars(); + } + } + break; case InteractCmdMsg interactCmd: if (_peersByEndpoint.TryGetValue(epKey, out var intPeer) && intPeer.Active && ReferenceEquals(intPeer.TransportPeer, transportPeer)) { @@ -996,6 +1066,20 @@ namespace RustToDust.Net } peer.SentPodIds.Clear(); peer.SentOrdnanceIds.Clear(); + peer.SentTerrainStampIndices.Clear(); + Array.Clear(peer.SentTileVersions); + for (int i = 0; i < _terrainStampHistory.Count; i++) + { + peer.SentTerrainStampIndices.Add(i); + } + var terrain = _session.State.Terrain; + for (int tz = 0; tz < terrain.TileGridCount; tz++) + { + for (int tx = 0; tx < terrain.TileGridCount; tx++) + { + peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz]; + } + } var activePods = _session.State.OrbitalDrop.ActivePods; for (int i = 0; i < activePods.Count; i++) { @@ -1187,11 +1271,9 @@ namespace RustToDust.Net : new DropPickedUpEvent { DropId = dp.DropId, ContenderId = -1 }); } break; - case TerrainStampEvent stamp: - if (_session.IsPointInPeerPvs(obsId, stamp.X, _session.State.Terrain.SampleHeight(stamp.X, stamp.Z) + 0.5f, stamp.Z)) - { - filtered.Add(stamp); - } + case TerrainStampEvent: + // Delivered via 576m local geometry bubble sync below so distant live fire is never leaked + // while _predWorld stays 1:1 physics-synchronized before the player enters tile range. break; case OverheatAlertEvent oh: if (oh.ContenderId == obsId) @@ -1306,6 +1388,8 @@ namespace RustToDust.Net } } + SyncPeerLocalGeometryBubble(peer, obsId, filtered); + if (enteredPvsMask != 0) { var activePods = _session.State.OrbitalDrop.ActivePods; @@ -1753,13 +1837,10 @@ namespace RustToDust.Net }); } - for (int i = 0; i < _terrainStampHistory.Count; i++) + var scarSnap = _session.State.ScarLedger.ToSnapshot(); + if (scarSnap.Terrain.Count > 0 || scarSnap.Buildings.Count > 0 || scarSnap.Trees.Count > 0) { - var ts = _terrainStampHistory[i]; - if (_session.IsPointInPeerPvs(forContenderId, ts.X, _session.State.Terrain.SampleHeight(ts.X, ts.Z) + 0.5f, ts.Z)) - { - dto.TerrainStamps.Add(ts); - } + dto.PersistentScars = ArenaScarLedger.CompressSnapshot(scarSnap); } for (int i = 0; i < _session.State.Contenders.Count; i++) @@ -1865,10 +1946,124 @@ namespace RustToDust.Net } } + public void RepairArenaScars() + { + _session.RepairArenaScars(); + _terrainStampHistory.Clear(); + ClearTileStampHistory(); + FlushScarLedgerIfDirty(); + + uint rev = _session.State.ScarLedger.LedgerRevision; + var repairEv = new ArenaRepairEvent { LedgerRevision = rev }; + if (_hostContenderId.HasValue) + { + _hostPendingEvents.Add(repairEv); + } + + foreach (var peer in _peersByEndpoint.Values) + { + if (!peer.Active) continue; + peer.SentTerrainStampIndices.Clear(); + Array.Clear(peer.SentTileVersions); + SendSchemaToPeer(peer, new SimEventBatchMsg + { + BatchSeq = _eventBatchSeq++, + SimTick = _simTick, + SimTime = _session.State.Time, + MatchGeneration = _matchGeneration, + Events = new List { repairEv } + }); + } + } + + private void SyncPeerLocalGeometryBubble(ConnectedPeer peer, int obsId, List filtered) + { + if (_terrainStampHistory.Count == 0 || obsId < 0 || obsId >= _session.State.Contenders.Count) + { + return; + } + var obs = _session.State.Contenders[obsId]; + var terrain = _session.State.Terrain; + terrain.MapWorldToTile(obs.X, obs.Z, out int cx, out int cz); + int grid = terrain.TileGridCount; + int minTx = Math.Max(0, cx - 4); + int maxTx = Math.Min(grid - 1, cx + 4); + int minTz = Math.Max(0, cz - 4); + int maxTz = Math.Min(grid - 1, cz + 4); + const float bubbleRadiusSq = 576f * 576f; + + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + var list = _tileStampHistory[tx, tz]; + if (list.Count == 0) + { + peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz]; + continue; + } + + bool allSent = true; + for (int i = 0; i < list.Count; i++) + { + int stampIdx = list[i]; + if (peer.SentTerrainStampIndices.Contains(stampIdx)) + { + continue; + } + var ts = _terrainStampHistory[stampIdx]; + float dx = obs.X - ts.X; + float dz = obs.Z - ts.Z; + if (dx * dx + dz * dz <= bubbleRadiusSq) + { + peer.SentTerrainStampIndices.Add(stampIdx); + filtered.Add(ts); + } + else + { + allSent = false; + } + } + + if (allSent) + { + peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz]; + } + } + } + } + + private void ClearTileStampHistory() + { + for (int tz = 0; tz < 16; tz++) + { + for (int tx = 0; tx < 16; tx++) + { + _tileStampHistory[tx, tz].Clear(); + } + } + } + + private void FlushScarLedgerIfDirty() + { + if (!_persistScars || string.IsNullOrWhiteSpace(_scarFilePath)) + { + return; + } + if (!_session.State.ScarLedger.IsDirty && File.Exists(_scarFilePath)) + { + return; + } + ArenaScarLedgerStore.Save(_scarFilePath, _session.State.ScarLedger.ToSnapshot()); + _session.State.ScarLedger.IsDirty = false; + _lastScarSaveTick = _simTick; + } + public void Dispose() { if (_disposed) return; _disposed = true; + FlushScarLedgerIfDirty(); _server.PeerDisconnected -= OnTransportPeerDisconnected; _server.Dispose(); _socket.Dispose(); diff --git a/src/RustToDust.Server/Program.cs b/src/RustToDust.Server/Program.cs index 5d0dba9..5f7ae2b 100644 --- a/src/RustToDust.Server/Program.cs +++ b/src/RustToDust.Server/Program.cs @@ -28,6 +28,9 @@ namespace RustToDust.Server int minHumansToStart = TryParseInt(Environment.GetEnvironmentVariable("RTD_MIN_HUMANS"), 1); bool restartToLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_RESTART_TO_LOBBY"), false); int squadSize = Math.Clamp(TryParseInt(Environment.GetEnvironmentVariable("RTD_SQUAD_SIZE"), 3), 1, 4); + string? scarFilePath = Environment.GetEnvironmentVariable("RTD_SCAR_FILE"); + bool persistScars = TryParseBool(Environment.GetEnvironmentVariable("RTD_PERSIST_SCARS"), true); + bool repairScars = false; for (int i = 0; i < args.Length; i++) { @@ -61,6 +64,10 @@ namespace RustToDust.Server else if (a == "--restart-to-lobby") restartToLobby = true; else if (a == "--squad-size" && i + 1 < args.Length) squadSize = Math.Clamp(TryParseInt(args[++i], squadSize), 1, 4); else if (a.StartsWith("--squad-size=", StringComparison.Ordinal)) squadSize = Math.Clamp(TryParseInt(a.Substring("--squad-size=".Length), squadSize), 1, 4); + else if (a == "--scar-file" && i + 1 < args.Length) scarFilePath = args[++i]; + else if (a.StartsWith("--scar-file=", StringComparison.Ordinal)) scarFilePath = a.Substring("--scar-file=".Length); + else if (a == "--no-persist-scars") persistScars = false; + else if (a == "--repair-scars") repairScars = true; } if (!IPAddress.TryParse(bindStr, out var bindIp)) @@ -99,7 +106,10 @@ namespace RustToDust.Server serverName: serverName, minHumansToStart: minHumansToStart, restartToLobby: restartToLobby, - squadSize: (byte)squadSize); + squadSize: (byte)squadSize, + scarFilePath: scarFilePath, + persistScars: persistScars, + repairScarsOnStart: repairScars); host.LogMessage += msg => Console.WriteLine(msg); static DirectoryHeartbeatSnapshot BuildSnapshot(ServerMatchHost h, string hostAddr) => diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs index 902e343..8c74293 100644 --- a/src/RustToDust.Ymir/ArenaSession.cs +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -11,7 +11,7 @@ namespace RustToDust.Ymir { public const float FixedDt = 1f / 60f; public const int SubStepCount = 4; - public const int WorldBodyCapacity = 384; + public const int WorldBodyCapacity = 1024; private const ulong GroundStableId = 1; private const ulong StaticBoxStableIdBase = 10; @@ -20,6 +20,7 @@ namespace RustToDust.Ymir private const ulong SpectatorStableIdBase = 3000; private readonly Box3DSoaWorld _world; + private readonly Box3DPhysicsTileSync _tileSync = new(); private readonly Dictionary _contenderBodies = new(); private readonly Dictionary _spectatorBodies = new(); private readonly Dictionary _contenderWalkers = new(); @@ -35,9 +36,9 @@ namespace RustToDust.Ymir private long _forwardedPodEventId; private bool _disposed; - public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false, bool startInLobby = false, byte squadSize = 1) + public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false, bool startInLobby = false, byte squadSize = 1, ArenaScarLedgerSnapshot? initialScars = null) { - State = new MatchState(seed, mapKind, skipInitialDrop, startInLobby, squadSize); + State = new MatchState(seed, mapKind, skipInitialDrop, startInLobby, squadSize, initialScars); Ordnance = new OrdnanceRuntime(this); _spectatorPvs = new bool[MatchState.ContenderCount, State.Spectators.Spectators.Count]; _forwardedPodEventId = State.PodEvents.Count > 0 ? State.PodEvents[^1].EventId : 0; @@ -73,7 +74,7 @@ namespace RustToDust.Ymir gravityY: -20f, gravityZ: 0f); - BuildStaticArena(_world, State); + BuildStaticArena(_world, State, _tileSync, warmAllActors: true); SpawnContenderBodies(); SpawnSpectatorBodies(); UpdateObserverDetectionMemories(); @@ -91,8 +92,33 @@ namespace RustToDust.Ymir public MatchState State { get; } public OrdnanceRuntime Ordnance { get; } public Box3DSoaWorld World => _world; + public Box3DPhysicsTileSync TileSync => _tileSync; public bool EnableNetworkPvs { get; set; } = true; + public void RepairArenaScars() + { + State.RepairArenaScars(); + _tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: Box3DPhysicsTileSync.MaxTiles); + } + + public static bool IsStaticWorldStableId(ulong stableId) => + stableId < ContenderStableIdBase || stableId >= Box3DPhysicsTileSync.HeightfieldTileStableIdBase; + + public static bool IsStaticBuildingOrCoverStableId(ulong stableId) => + (stableId >= StaticMeshStableIdBase && stableId < ContenderStableIdBase) || + (stableId >= Box3DPhysicsTileSync.BuildingTileStableIdBase && stableId < Box3DPhysicsTileSync.TreeTileStableIdBase); + + public Box3DSoaRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation) + { + float len = translation.Length(); + if (len > 1e-4f && State.Terrain.IsHeightmapMode) + { + Vector3 dir = translation / len; + _tileSync.EnsureTilesAlongRay(_world, State.Terrain, origin.X, origin.Z, dir.X, dir.Z, len); + } + return _world.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z)); + } + public void SetHumanSlot(int contenderId, bool isHuman, string? callsign = null) { if (contenderId < 0 || contenderId >= State.Contenders.Count) @@ -322,6 +348,10 @@ namespace RustToDust.Ymir _contenderBodies.Remove(contenderId); } _contenderWalkers.Remove(contenderId); + if (State.Terrain.IsHeightmapMode) + { + _tileSync.EnsureTileRegion(_world, State.Terrain, x, z, halfTileRadius: 1); + } if (c.IsGroundedActive) { SpawnContenderBody(c); @@ -508,6 +538,7 @@ namespace RustToDust.Ymir if (State.SionMap is { } sionMap && sionMap.IntersectsAnyBuildingAabb(ax, ay, az, dir.X, dir.Y, dir.Z, dist)) { + _tileSync.EnsureTilesAlongRay(_world, State.Terrain, ax, az, dir.X, dir.Z, dist); Vector3 castOrigin = new(ax, ay, az); float remaining = dist; for (int hop = 0; hop < 4 && remaining > 0.25f; hop++) @@ -519,7 +550,7 @@ namespace RustToDust.Ymir { break; } - if (hit.StableId < ContenderStableIdBase) + if (IsStaticWorldStableId(hit.StableId)) { return false; } @@ -659,6 +690,7 @@ namespace RustToDust.Ymir MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight); State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown); + EnsureActivePhysicsTilesAndFlush(); ApplyPhysicsDrives(); _world.Step(FixedDt, subSteps); SyncBodiesFromWorld(); @@ -679,6 +711,7 @@ namespace RustToDust.Ymir MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight); State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown); long t2 = Stopwatch.GetTimestamp(); + EnsureActivePhysicsTilesAndFlush(); ApplyPhysicsDrives(); long t3 = Stopwatch.GetTimestamp(); _world.Step(FixedDt, subSteps); @@ -734,23 +767,28 @@ namespace RustToDust.Ymir return true; } - public static void BuildStaticArena(Box3DSoaWorld world, MatchState state) + public static void BuildStaticArena(Box3DSoaWorld world, MatchState state, Box3DPhysicsTileSync? tileSync = null, bool warmAllActors = true) { if (state.MapKind == ArenaMapKind.Sion && state.SionMap is { } sion) { - var meta = sion.Metadata; - float half = state.Terrain.MapHalfExtent; - world.AddStaticHeightField( - GroundStableId, - (-half, 0f, -half), - sion.Heights, - meta.GridRes, - meta.GridRes, - (meta.CellSizeMeters, 1.0f, meta.CellSizeMeters), - meta.MinY - 2f, - meta.MaxY + 2f, - friction: 0.15f, - restitution: 0.0f); + if (tileSync is not null && warmAllActors && state.Terrain.IsHeightmapMode) + { + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + tileSync.EnsureTileRegion(world, state.Terrain, c.X, c.Z, halfTileRadius: 1); + } + for (int i = 0; i < state.Spectators.Spectators.Count; i++) + { + var s = state.Spectators.Spectators[i]; + tileSync.EnsureTileRegion(world, state.Terrain, s.X, s.Z, halfTileRadius: 1); + } + for (int i = 0; i < state.OrbitalDrop.ActivePods.Count; i++) + { + var pod = state.OrbitalDrop.ActivePods[i]; + tileSync.EnsureTileRegion(world, state.Terrain, pod.X, pod.Z, halfTileRadius: 0); + } + } ulong boxId = StaticBoxStableIdBase; for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++) @@ -886,8 +924,44 @@ namespace RustToDust.Ymir } } - public DropSurfaceSample QueryDropSurface(float x, float z, float footRadius, float referenceMaxY) => - QueryDropSurface(State, _world, x, z, footRadius, referenceMaxY); + private void EnsureActivePhysicsTilesAndFlush() + { + if (!State.Terrain.IsHeightmapMode) + { + return; + } + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (c.Alive) + { + _tileSync.EnsureTileRegion(_world, State.Terrain, c.X, c.Z, halfTileRadius: 1); + } + } + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (s.Alive) + { + _tileSync.EnsureTileRegion(_world, State.Terrain, s.X, s.Z, halfTileRadius: 1); + } + } + for (int i = 0; i < State.OrbitalDrop.ActivePods.Count; i++) + { + var pod = State.OrbitalDrop.ActivePods[i]; + _tileSync.EnsureTileRegion(_world, State.Terrain, pod.X, pod.Z, halfTileRadius: 0); + } + _tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: 4); + } + + public DropSurfaceSample QueryDropSurface(float x, float z, float footRadius, float referenceMaxY) + { + if (State.Terrain.IsHeightmapMode) + { + _tileSync.EnsureTileRegion(_world, State.Terrain, x, z, halfTileRadius: 0); + } + return QueryDropSurface(State, _world, x, z, footRadius, referenceMaxY); + } public static DropSurfaceSample QueryDropSurface( MatchState state, @@ -2996,11 +3070,13 @@ namespace RustToDust.Ymir State.SpawnModuleDrop(victim.X + (i - 1) * 0.9f, victim.Z + 1.2f, victim.Grid.Mounted[i].Spec); } - State.Terrain.StampCrater(victim.X, victim.Z, radius: 5.2f, depth: 1.3f); - State.Terrain.StampScorch(victim.X, victim.Z, radius: 6.2f); + var craterEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = victim.X, Z = victim.Z, Radius = 5.2f, Depth = 1.3f }; + var scorchEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = victim.X, Z = victim.Z, Radius = 6.2f }; + State.ApplyTerrainStamp(craterEv, recordInLedger: true); + State.ApplyTerrainStamp(scorchEv, recordInLedger: true); State.OrbitalDrop.OnContenderEliminated(victim); - _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = victim.X, Z = victim.Z, Radius = 5.2f, Depth = 1.3f }); - _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = victim.X, Z = victim.Z, Radius = 6.2f }); + _stepEvents.Add(craterEv); + _stepEvents.Add(scorchEv); _stepEvents.Add(new ContenderEliminatedEvent { VictimId = victim.Id, @@ -3032,10 +3108,12 @@ namespace RustToDust.Ymir State.SpawnModuleDrop(spec.X + (i - 0.5f) * 1.1f, spec.Z, drops[i]); } - State.Terrain.StampCrater(spec.X, spec.Z, radius: 4.5f, depth: 1.1f); - State.Terrain.StampScorch(spec.X, spec.Z, radius: 5.4f); - _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = spec.X, Z = spec.Z, Radius = 4.5f, Depth = 1.1f }); - _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = spec.X, Z = spec.Z, Radius = 5.4f }); + var specCraterEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = spec.X, Z = spec.Z, Radius = 4.5f, Depth = 1.1f }; + var specScorchEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = spec.X, Z = spec.Z, Radius = 5.4f }; + State.ApplyTerrainStamp(specCraterEv, recordInLedger: true); + State.ApplyTerrainStamp(specScorchEv, recordInLedger: true); + _stepEvents.Add(specCraterEv); + _stepEvents.Add(specScorchEv); _stepEvents.Add(new SpectatorDestroyedEvent { SpectatorId = spec.Id, @@ -3299,26 +3377,36 @@ namespace RustToDust.Ymir { if (craterRadius > 0f && craterDepth > 0f) { - State.Terrain.StampCrater(x, z, radius: craterRadius, depth: craterDepth); - _stepEvents.Add(new TerrainStampEvent + var ev = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = x, Z = z, Radius = craterRadius, Depth = craterDepth - }); + }; + State.ApplyTerrainStamp(ev, recordInLedger: true); + _stepEvents.Add(ev); } if (scorchRadius > 0f) { - State.Terrain.StampScorch(x, z, radius: scorchRadius); - _stepEvents.Add(new TerrainStampEvent + var ev = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = x, Z = z, Radius = scorchRadius - }); + }; + State.ApplyTerrainStamp(ev, recordInLedger: true); + _stepEvents.Add(ev); + } + } + + void IOrdnanceTargetSink.EnsurePhysicsTilesAlongRay(Vector3 origin, Vector3 dir, float distance) + { + if (State.Terrain.IsHeightmapMode) + { + _tileSync.EnsureTilesAlongRay(_world, State.Terrain, origin.X, origin.Z, dir.X, dir.Z, distance); } } diff --git a/src/RustToDust.Ymir/Box3DPhysicsTileSync.cs b/src/RustToDust.Ymir/Box3DPhysicsTileSync.cs new file mode 100644 index 0000000..59ee434 --- /dev/null +++ b/src/RustToDust.Ymir/Box3DPhysicsTileSync.cs @@ -0,0 +1,283 @@ +using System; +using RustToDust.Core; +using Ymir.Box3D; + +namespace RustToDust.Ymir +{ + public sealed class Box3DPhysicsTileSync + { + public const ulong HeightfieldTileStableIdBase = 10_000; + public const ulong BuildingTileStableIdBase = 11_000; + public const ulong TreeTileStableIdBase = 12_000; + public const int MaxTiles = 256; + + private readonly Box3DSoaBodyHandle[] _residentHandles = new Box3DSoaBodyHandle[MaxTiles]; + private readonly bool[] _residentFlags = new bool[MaxTiles]; + private readonly int[] _syncedStructuralVersions = new int[MaxTiles]; + private float[]? _scratchHeights; + + public int ResidentTileCount { get; private set; } + + public bool TryGetResidentHandle(int tx, int tz, int tileGridCount, out Box3DSoaBodyHandle handle) + { + if ((uint)tx < (uint)tileGridCount && (uint)tz < (uint)tileGridCount) + { + int idx = tz * tileGridCount + tx; + if (_residentFlags[idx]) + { + handle = _residentHandles[idx]; + return true; + } + } + handle = default; + return false; + } + + public void Reset() + { + Array.Clear(_residentHandles); + Array.Clear(_residentFlags); + Array.Clear(_syncedStructuralVersions); + ResidentTileCount = 0; + } + + public bool EnsureTileResident(Box3DSoaWorld world, TerrainField terrain, int tx, int tz) + { + if (!terrain.IsHeightmapMode) + { + return false; + } + + int grid = terrain.TileGridCount; + if ((uint)tx >= (uint)grid || (uint)tz >= (uint)grid) + { + return false; + } + + int idx = tz * grid + tx; + int curVer = terrain.StructuralTileVersions[tx, tz]; + if (_residentFlags[idx] && _syncedStructuralVersions[idx] == curVer) + { + return false; + } + + int samplesPerTile = (terrain.HeightmapRes - 1) / grid; + int side = samplesPerTile + 1; + int sampleCount = side * side; + if (_scratchHeights is null || _scratchHeights.Length < sampleCount) + { + _scratchHeights = new float[sampleCount]; + } + + terrain.ExtractTilePhysicsHeights(tx, tz, _scratchHeights, out float minY, out float maxY); + + if (_residentFlags[idx]) + { + world.RemoveBody(_residentHandles[idx]); + ResidentTileCount--; + _residentFlags[idx] = false; + } + + float originX = -terrain.MapHalfExtent + tx * terrain.MapTileSize; + float originZ = -terrain.MapHalfExtent + tz * terrain.MapTileSize; + ulong stableId = HeightfieldTileStableIdBase + (ulong)idx; + var handle = world.AddStaticHeightField( + stableId, + (originX, 0f, originZ), + _scratchHeights.AsSpan(0, sampleCount), + side, + side, + (terrain.HeightmapCellSize, 1.0f, terrain.HeightmapCellSize), + minY - 2f, + maxY + 2f, + friction: 0.15f, + restitution: 0.0f); + + _residentHandles[idx] = handle; + _residentFlags[idx] = true; + _syncedStructuralVersions[idx] = curVer; + ResidentTileCount++; + return true; + } + + public void EnsureTileRegion(Box3DSoaWorld world, TerrainField terrain, float worldX, float worldZ, int halfTileRadius) + { + if (!terrain.IsHeightmapMode) + { + return; + } + + terrain.MapWorldToTile(worldX, worldZ, out int cx, out int cz); + int grid = terrain.TileGridCount; + int minTx = Math.Max(0, cx - halfTileRadius); + int maxTx = Math.Min(grid - 1, cx + halfTileRadius); + int minTz = Math.Max(0, cz - halfTileRadius); + int maxTz = Math.Min(grid - 1, cz + halfTileRadius); + + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + EnsureTileResident(world, terrain, tx, tz); + } + } + } + + public void EnsureTilesAlongRay( + Box3DSoaWorld world, + TerrainField terrain, + float ox, float oz, + float dx, float dz, + float maxDistance) + { + if (!terrain.IsHeightmapMode || maxDistance <= 0f) + { + return; + } + + float half = terrain.MapHalfExtent; + float tileSize = terrain.MapTileSize; + int grid = terrain.TileGridCount; + + float tMin = 0f; + float tMax = maxDistance; + if (!SlabClip(ox, dx, -half, half, ref tMin, ref tMax)) return; + if (!SlabClip(oz, dz, -half, half, ref tMin, ref tMax)) return; + + float sx = ox + dx * tMin; + float sz = oz + dz * tMin; + terrain.MapWorldToTile(sx, sz, out int tx, out int tz); + + float ex = ox + dx * tMax; + float ez = oz + dz * tMax; + terrain.MapWorldToTile(ex, ez, out int endTx, out int endTz); + + int stepX = dx > 1e-6f ? 1 : (dx < -1e-6f ? -1 : 0); + int stepZ = dz > 1e-6f ? 1 : (dz < -1e-6f ? -1 : 0); + float tDeltaX = stepX != 0 ? tileSize / MathF.Abs(dx) : float.PositiveInfinity; + float tDeltaZ = stepZ != 0 ? tileSize / MathF.Abs(dz) : float.PositiveInfinity; + + float nextBoundaryX = -half + (tx + (stepX > 0 ? 1 : 0)) * tileSize; + float nextBoundaryZ = -half + (tz + (stepZ > 0 ? 1 : 0)) * tileSize; + float tMaxX = stepX != 0 ? tMin + MathF.Max(0f, (nextBoundaryX - sx) / dx) : float.PositiveInfinity; + float tMaxZ = stepZ != 0 ? tMin + MathF.Max(0f, (nextBoundaryZ - sz) / dz) : float.PositiveInfinity; + + int maxSteps = grid * 2 + 4; + for (int iter = 0; iter < maxSteps; iter++) + { + EnsureTileResident(world, terrain, tx, tz); + if (tx == endTx && tz == endTz) + { + break; + } + + float curT; + if (tMaxX <= tMaxZ) + { + curT = tMaxX; + tMaxX += tDeltaX; + tx += stepX; + } + else + { + curT = tMaxZ; + tMaxZ += tDeltaZ; + tz += stepZ; + } + + if ((uint)tx >= (uint)grid || (uint)tz >= (uint)grid || curT > tMax) + { + break; + } + } + } + + public int FlushDirtyHeightfields(Box3DSoaWorld world, TerrainField terrain, int maxTilesPerTick = 4) + { + if (!terrain.IsHeightmapMode || maxTilesPerTick <= 0) + { + return 0; + } + + int grid = terrain.TileGridCount; + int rebuilt = 0; + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + int idx = tz * grid + tx; + if (!_residentFlags[idx]) + { + continue; + } + if (terrain.StructuralTileVersions[tx, tz] != _syncedStructuralVersions[idx]) + { + if (EnsureTileResident(world, terrain, tx, tz)) + { + rebuilt++; + if (rebuilt >= maxTilesPerTick) + { + return rebuilt; + } + } + } + } + } + return rebuilt; + } + + public void SyncWindow(Box3DSoaWorld world, TerrainField terrain, float centerX, float centerZ, int halfTileRadius = 1) + { + if (!terrain.IsHeightmapMode) + { + return; + } + + terrain.MapWorldToTile(centerX, centerZ, out int cx, out int cz); + int grid = terrain.TileGridCount; + int minTx = Math.Max(0, cx - halfTileRadius); + int maxTx = Math.Min(grid - 1, cx + halfTileRadius); + int minTz = Math.Max(0, cz - halfTileRadius); + int maxTz = Math.Min(grid - 1, cz + halfTileRadius); + + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + int idx = tz * grid + tx; + if (_residentFlags[idx] && (tx < minTx || tx > maxTx || tz < minTz || tz > maxTz)) + { + world.RemoveBody(_residentHandles[idx]); + _residentHandles[idx] = default; + _residentFlags[idx] = false; + _syncedStructuralVersions[idx] = 0; + ResidentTileCount--; + } + } + } + + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + EnsureTileResident(world, terrain, tx, tz); + } + } + } + + private static bool SlabClip(float o, float d, float minB, float maxB, ref float tMin, ref float tMax) + { + if (MathF.Abs(d) < 1e-6f) + { + return o >= minB && o <= maxB; + } + float invD = 1f / d; + float t1 = (minB - o) * invD; + float t2 = (maxB - o) * invD; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + return tMax >= tMin; + } + } +} diff --git a/src/RustToDust.Ymir/LocalArenaSession.cs b/src/RustToDust.Ymir/LocalArenaSession.cs index 1539b65..7bebd18 100644 --- a/src/RustToDust.Ymir/LocalArenaSession.cs +++ b/src/RustToDust.Ymir/LocalArenaSession.cs @@ -126,7 +126,7 @@ namespace RustToDust.Ymir public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation) { - var hit = Inner.World.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z)); + var hit = Inner.CastWorldRayClosest(origin, translation); return new ClientRayHit( hit.Hit, hit.StableId, diff --git a/src/RustToDust.Ymir/OrdnanceRuntime.cs b/src/RustToDust.Ymir/OrdnanceRuntime.cs index 9d0d124..7f5acdf 100644 --- a/src/RustToDust.Ymir/OrdnanceRuntime.cs +++ b/src/RustToDust.Ymir/OrdnanceRuntime.cs @@ -103,6 +103,7 @@ namespace RustToDust.Ymir bool isSpectatorShooter, int shooterEntityId); void StampTerrainImpact(float x, float z, float craterRadius, float craterDepth, float scorchRadius); + void EnsurePhysicsTilesAlongRay(Vector3 origin, Vector3 dir, float distance); } public struct LiveOrdnanceInstance @@ -763,6 +764,7 @@ namespace RustToDust.Ymir for (int hop = 0; hop < 4 && remaining > 1e-4f; hop++) { + _sink.EnsurePhysicsTilesAlongRay(castOrigin, dir, remaining); var rayHit = _sink.World.CastRayClosest( (castOrigin.X, castOrigin.Y, castOrigin.Z), (dir.X * remaining, dir.Y * remaining, dir.Z * remaining)); @@ -1290,6 +1292,7 @@ namespace RustToDust.Ymir for (int hop = 0; hop < 6 && remainingRange > 0.2f; hop++) { + _sink.EnsurePhysicsTilesAlongRay(castOrigin, dir, remainingRange); var rayHit = _sink.World.CastRayClosest( (castOrigin.X, castOrigin.Y, castOrigin.Z), (dir.X * remainingRange, dir.Y * remainingRange, dir.Z * remainingRange)); diff --git a/src/RustToDust.Ymir/WalkerLocomotion.cs b/src/RustToDust.Ymir/WalkerLocomotion.cs index 71b1d13..1a37040 100644 --- a/src/RustToDust.Ymir/WalkerLocomotion.cs +++ b/src/RustToDust.Ymir/WalkerLocomotion.cs @@ -477,10 +477,10 @@ namespace RustToDust.Ymir float rrX = x + right.X * w - fwd.X * l, rrZ = z + right.Z * w - fwd.Z * l; float hCenter = terrain.SampleHeight(x, z); - if (terrain.SampleNormal(flX, flZ).Ny < 0.72f || - terrain.SampleNormal(frX, frZ).Ny < 0.72f || - terrain.SampleNormal(rlX, rlZ).Ny < 0.72f || - terrain.SampleNormal(rrX, rrZ).Ny < 0.72f) + if (terrain.SampleNormal(flX, flZ).Ny < 0.58f || + terrain.SampleNormal(frX, frZ).Ny < 0.58f || + terrain.SampleNormal(rlX, rlZ).Ny < 0.58f || + terrain.SampleNormal(rrX, rrZ).Ny < 0.58f) { planeCenterY = hCenter; return centerNormal.Y >= 0.78f ? centerNormal : Vector3.UnitY; @@ -1007,6 +1007,27 @@ namespace RustToDust.Ymir } } } + else if (n == 4 && view.Size2[lane] > 2.4f && terrainNormal.Y >= 0.78f) + { + float fz = view.Size2[lane] * 0.98f; + float fw = view.Size0[lane] * 0.95f; + for (int ci = -1; ci <= 1; ci++) + { + float sx = fw * ci; + float cx = comPos.X + right.X * sx + fwd.X * fz; + float cz = comPos.Z + right.Z * sx + fwd.Z * fz; + if (WalkerState.SampleTerrainNormal(terrain, cx, cz).Y >= 0.58f) + { + float ch = terrain.SampleHeight(cx, cz); + Vector3 cornerRel = right * sx + fwd * fz - up * view.Size1[lane]; + float neededGroundY = (ch + 0.22f * scale - cornerRel.Y) - rideHeight; + if (neededGroundY > effectiveGroundY) + { + effectiveGroundY = MathF.Min(comGroundY + 1.15f * scale, neededGroundY); + } + } + } + } } float targetY = effectiveGroundY + rideHeight; if (!activeMove && !ws.IsAirborne) diff --git a/tests/RustToDust.Tests/CultNetMultiplayerTests.cs b/tests/RustToDust.Tests/CultNetMultiplayerTests.cs index 7a862dc..0c361c1 100644 --- a/tests/RustToDust.Tests/CultNetMultiplayerTests.cs +++ b/tests/RustToDust.Tests/CultNetMultiplayerTests.cs @@ -797,6 +797,87 @@ namespace RustToDust.Tests "Client must receive Exemplar walker snapshot even under dense 12 quad-walker contention"); } + [Fact] + public void Cut13a_OutOfPvsHistoricalCratersSyncViaPersistentScars_AndLiveCratersEnterWithin576mBubble() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + const float histX = 700f; + const float histZ = 700f; + float baseHistH = host.Session.State.Terrain.SampleHeight(histX, histZ); + + // 1. Historical out-of-PVS crater stamped before Client A joins + ((IOrdnanceTargetSink)host.Session).StampTerrainImpact(histX, histZ, craterRadius: 6f, craterDepth: 2.0f, scorchRadius: 7f); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + host.StepOnce(nowMs += 16); + float scarredHistH = host.Session.State.Terrain.SampleHeight(histX, histZ); + Assert.True(scarredHistH < baseHistH - 1.2f); + + using var clientA = new RemoteArenaSession(ep, "Scout"); + Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000)); + + // Out-of-PVS historical crater must be present immediately via PersistentScars + Assert.Equal(scarredHistH, clientA.ViewState.Terrain.SampleHeight(histX, histZ), precision: 3); + Assert.InRange(clientA.PredTileSync.ResidentTileCount, 1, 9); + + // 2. Live crater stamped far outside 576m bubble (-700, 100 vs open-sky ~700, 100 = ~1400m apart) + int slotA = clientA.LocalContenderId; + var sion = host.Session.State.SionMap!; + float liveX = 700f, liveZ = 100f; + for (float x = 640f; x <= 760f; x += 8f) + { + if (!sion.IsInsideAnyBuildingXz(x, liveZ, padding: 10f)) + { + liveX = x; + break; + } + } + float baseLiveH = host.Session.State.Terrain.SampleHeight(liveX, liveZ); + + host.Session.SetContenderPose(slotA, -700f, liveZ, 0f); + host.StepOnce(nowMs += 16); + ((IOrdnanceTargetSink)host.Session).StampTerrainImpact(liveX, liveZ, craterRadius: 6f, craterDepth: 2.0f, scorchRadius: 7f); + for (int t = 0; t < 10; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + clientA.PumpNetwork(); + Thread.Sleep(1); + } + float hostLiveH = host.Session.State.Terrain.SampleHeight(liveX, liveZ); + Assert.True(hostLiveH < baseLiveH - 1.2f); + Assert.Equal(baseLiveH, clientA.ViewState.Terrain.SampleHeight(liveX, liveZ), precision: 3); + + // 3. Client A enters 576m local geometry bubble (liveX - 450m -> dist = 450m <= 576m) + host.Session.SetContenderPose(slotA, liveX - 450f, liveZ, 0f); + Assert.True(PumpUntil( + host, + new[] { clientA }, + () => MathF.Abs(clientA.ViewState.Terrain.SampleHeight(liveX, liveZ) - hostLiveH) < 0.05f, + ref nowMs, + 3000), + "Client must receive live TerrainStampEvent upon entering 576m bubble before reaching _predWorld 3x3 window"); + + // 4. Client A steps into (liveX, liveZ) tile -> _predWorld 3x3 window matches server Box3D crater depth 1:1 + host.Session.SetContenderPose(slotA, liveX - 20f, liveZ, 0f); + for (int t = 0; t < 10; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + clientA.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + Assert.InRange(clientA.PredTileSync.ResidentTileCount, 1, 9); + float rayStartY = sion.Metadata.MaxY + 25f; + float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f); + var hostHit = host.Session.CastWorldRayClosest(new Vector3(liveX, rayStartY, liveZ), new Vector3(0f, raySpanY, 0f)); + var predHit = clientA.CastWorldRayClosest(new Vector3(liveX, rayStartY, liveZ), new Vector3(0f, raySpanY, 0f)); + Assert.True(hostHit.Hit && predHit.Hit); + Assert.True(MathF.Abs(hostHit.Point.Y - predHit.Point.Y) < 0.05f, + $"Expected _predWorld crater impact Y ({predHit.Point.Y:F3}m) to match server ({hostHit.Point.Y:F3}m)"); + } + private static byte[] EncodeRudpLatestDatagram(byte[] frameBytes, uint sequence) => CultNetRudpPacketCodec.Encode(new CultNetRudpPacket { diff --git a/tests/RustToDust.Tests/SionMapTests.cs b/tests/RustToDust.Tests/SionMapTests.cs index 3b4736f..e77a191 100644 --- a/tests/RustToDust.Tests/SionMapTests.cs +++ b/tests/RustToDust.Tests/SionMapTests.cs @@ -1,6 +1,9 @@ using System; +using System.IO; +using System.Net; using System.Numerics; using RustToDust.Core; +using RustToDust.Net; using RustToDust.Ymir; using Xunit; using Ymir.Box3D; @@ -16,20 +19,24 @@ namespace RustToDust.Tests var meta = sion.Metadata; Assert.Equal(3072f, meta.SizeMeters); - Assert.Equal(6, meta.TileGrid); - Assert.Equal(512f, meta.TileSizeMeters); - Assert.Equal(1025, meta.GridRes); - Assert.Equal(3.0f, meta.CellSizeMeters); + Assert.Equal(16, meta.TileGrid); + Assert.Equal(192f, meta.TileSizeMeters); + Assert.Equal(6145, meta.GridRes); + Assert.Equal(0.5f, meta.CellSizeMeters); + Assert.Equal("heightmap_05m.u16z", meta.HeightmapFile); + Assert.False(string.IsNullOrWhiteSpace(meta.DemAssetHash)); Assert.Contains("swisstopo", meta.Attribution, StringComparison.OrdinalIgnoreCase); - Assert.Equal(1025 * 1025, sion.Heights.Length); + Assert.Equal(6145 * 6145, sion.BaseDem.Length); Assert.Equal(2319, sion.Buildings.Count); Assert.Equal(36, sion.CollisionMeshes.Count); - var terrain = TerrainField.LoadHeightmap( - meta.SizeMeters, meta.GridRes, sion.Heights, meta.MinY, meta.MaxY); + var terrain = TerrainField.LoadSharedHeightmap( + meta.SizeMeters, meta.GridRes, meta.TileGrid, + sion.BaseDem, sion.BaseDemMinY, sion.BaseDemScale, + meta.MinY, meta.MaxY); - // Verify Basilique de Valere and valley buildings align cleanly with heightmap.f32 (0.00m coordinate drift) + // Verify Basilique de Valere and valley buildings align cleanly with heightmap_05m.u16z (0.00m coordinate drift) bool foundValere = false; int flatAlignChecked = 0; int closeAlignCount = 0; @@ -82,16 +89,19 @@ namespace RustToDust.Tests { var sion = SionMapLoader.Load(); var meta = sion.Metadata; - var terrain = TerrainField.LoadHeightmap( - meta.SizeMeters, meta.GridRes, sion.Heights, meta.MinY, meta.MaxY); + var terrain = TerrainField.LoadSharedHeightmap( + meta.SizeMeters, meta.GridRes, meta.TileGrid, + sion.BaseDem, sion.BaseDemMinY, sion.BaseDemScale, + meta.MinY, meta.MaxY); Assert.True(terrain.IsHeightmapMode); Assert.Equal(3072f, terrain.MapSize); Assert.Equal(1536f, terrain.MapHalfExtent); + Assert.Equal(16, terrain.TileGridCount); // Grid vertex exactness at (-1536, -1536) and (0, 0) - Assert.Equal(sion.Heights[0], terrain.SampleHeight(-1536f, -1536f), precision: 4); - Assert.Equal(sion.Heights[512 * 1025 + 512], terrain.SampleHeight(0f, 0f), precision: 4); + Assert.Equal(sion.SampleBaseDemAtIndex(0), terrain.SampleHeight(-1536f, -1536f), precision: 4); + Assert.Equal(sion.SampleBaseDemAtIndex(3072 * 6145 + 3072), terrain.SampleHeight(0f, 0f), precision: 4); // Plaza spawn area is flat; Valere hill rises > 100m var (_, plazaNy, _) = terrain.SampleNormal(-60f, 360f); @@ -126,7 +136,7 @@ namespace RustToDust.Tests Assert.Empty(state.ArenaCoverBoxes); Assert.Equal(MatchState.SionInitialSafeRadius, state.Spectators.SafeRadius); - // Verify StaticHeightField (1) + StaticMesh (36) exist in Ymir + // Verify lazy tiled StaticHeightField (192m tiles) + StaticMesh (36) exist in Ymir int hfCount = 0; int meshCount = 0; var view = session.World.View; @@ -136,7 +146,8 @@ namespace RustToDust.Tests if (kind == Box3DSoaKind.StaticHeightField) hfCount++; else if (kind == Box3DSoaKind.StaticMesh) meshCount++; } - Assert.Equal(1, hfCount); + Assert.InRange(hfCount, 1, 255); + Assert.Equal(hfCount, session.TileSync.ResidentTileCount); Assert.Equal(36, meshCount); // Verify zero contenders, spectators, or drops spawned inside any building @@ -225,5 +236,147 @@ namespace RustToDust.Tests float pDisp = MathF.Sqrt((player.X - pStartX) * (player.X - pStartX) + (player.Z - pStartZ) * (player.Z - pStartZ)); Assert.True(pDisp > 5f, $"Expected player displacement > 5m on Sion after 180 ticks, got {pDisp:F2}m"); } + + [Fact] + public void SionBox3DTile_CraterRebuildsLocalTileOnlyAndLeavesNeighborsIntact() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true); + var terrain = session.State.Terrain; + + // Tile (7, 7) spans [-192, 0) x [-192, 0); neighbor tile (8, 7) spans [0, 192) x [-192, 0). + // Pick an open-sky coordinate strictly inside tile (7, 7) away from any building footprint. + var sion = session.State.SionMap!; + float cx = -96f, cz = -96f; + bool foundSpot = false; + for (float z = -176f; z <= -16f && !foundSpot; z += 8f) + { + for (float x = -176f; x <= -16f; x += 8f) + { + if (!sion.IsInsideAnyBuildingXz(x, z, padding: 10f)) + { + cx = x; + cz = z; + foundSpot = true; + break; + } + } + } + Assert.True(foundSpot, "Expected open-sky spot inside Sion tile (7, 7)"); + + session.TileSync.EnsureTileRegion(session.World, terrain, cx, cz, halfTileRadius: 1); + + Assert.True(session.TileSync.TryGetResidentHandle(7, 7, terrain.TileGridCount, out var handleTargetBefore)); + Assert.True(session.TileSync.TryGetResidentHandle(8, 7, terrain.TileGridCount, out var handleNeighborBefore)); + + float rayStartY = sion.Metadata.MaxY + 25f; + float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f); + var hitBefore = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f)); + Assert.True(hitBefore.Hit); + Assert.Equal(Box3DPhysicsTileSync.HeightfieldTileStableIdBase + (ulong)(7 * 16 + 7), hitBefore.StableId); + + // Stamp crater strictly inside tile (7, 7) + session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = cx, + Z = cz, + Radius = 6f, + Depth = 2.0f + }); + int rebuilt = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 4); + Assert.Equal(1, rebuilt); + + Assert.True(session.TileSync.TryGetResidentHandle(7, 7, terrain.TileGridCount, out var handleTargetAfter)); + Assert.True(session.TileSync.TryGetResidentHandle(8, 7, terrain.TileGridCount, out var handleNeighborAfter)); + + Assert.NotEqual(handleTargetBefore, handleTargetAfter); + Assert.Equal(handleNeighborBefore, handleNeighborAfter); + + var hitAfter = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f)); + Assert.True(hitAfter.Hit); + Assert.True(hitAfter.Point.Y < hitBefore.Point.Y - 1.2f, + $"Expected Box3D raycast impact height to drop in crater (before={hitBefore.Point.Y:F3}, after={hitAfter.Point.Y:F3})"); + } + + [Fact] + public void ArenaScarLedgerStore_PersistsCratersAndRubbleAcrossResetAndRepairsToLayer0() + { + string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-scar-test-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + string scarPath = Path.Combine(tempDir, "sion_scars_test.cultcache"); + + try + { + const float craterX = -120f; + const float craterZ = 180f; + const float rubbleX = 140f; + const float rubbleZ = 180f; + float baseCraterH; + float baseRubbleH; + float scarredCraterH; + float scarredRubbleH; + + using (var host1 = new ServerMatchHost( + IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, + autoRestartSec: 0, scarFilePath: scarPath, persistScars: true)) + { + var state1 = host1.Session.State; + baseCraterH = state1.Terrain.SampleHeight(craterX, craterZ); + baseRubbleH = state1.Terrain.SampleHeight(rubbleX, rubbleZ); + + state1.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = craterX, + Z = craterZ, + Radius = 5.5f, + Depth = 1.8f + }); + state1.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Rubble, + X = rubbleX, + Z = rubbleZ, + Radius = 6.0f, + Depth = 1.2f, + Yaw = 0.4f + }); + + scarredCraterH = state1.Terrain.SampleHeight(craterX, craterZ); + scarredRubbleH = state1.Terrain.SampleHeight(rubbleX, rubbleZ); + Assert.True(scarredCraterH < baseCraterH - 1.2f); + Assert.True(scarredRubbleH > baseRubbleH + 0.6f); + + // ResetMatch preserves scars in RAM & flushes to CultCache + host1.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false); + Assert.Equal(scarredCraterH, host1.Session.State.Terrain.SampleHeight(craterX, craterZ), precision: 3); + Assert.Equal(scarredRubbleH, host1.Session.State.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3); + } + + Assert.True(File.Exists(scarPath), "Expected CultCache scar file on disk after host dispose"); + + using (var host2 = new ServerMatchHost( + IPAddress.Loopback, 0, seed: 44, ArenaMapKind.Sion, + autoRestartSec: 0, scarFilePath: scarPath, persistScars: true)) + { + var state2 = host2.Session.State; + Assert.Equal(scarredCraterH, state2.Terrain.SampleHeight(craterX, craterZ), precision: 3); + Assert.Equal(scarredRubbleH, state2.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3); + + // RepairArenaScars zeroes back to Layer 0 + host2.RepairArenaScars(); + Assert.Equal(baseCraterH, state2.Terrain.SampleHeight(craterX, craterZ), precision: 3); + Assert.Equal(baseRubbleH, state2.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3); + Assert.Empty(state2.ScarLedger.Terrain); + } + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, recursive: true); + } + } + } } } diff --git a/tests/RustToDust.Tests/TerrainTests.cs b/tests/RustToDust.Tests/TerrainTests.cs index 4ba9ea8..1e17818 100644 --- a/tests/RustToDust.Tests/TerrainTests.cs +++ b/tests/RustToDust.Tests/TerrainTests.cs @@ -13,7 +13,7 @@ namespace RustToDust.Tests public void Generate_ProducesDeterministicNonFlatReliefWithinBounds() { Assert.Equal(1536f, TerrainField.ArenaSize); - Assert.Equal(8, TerrainField.TileGridCount); + Assert.Equal(8, TerrainField.DesertTileGridCount); Assert.Equal(192f, TerrainField.TileSize); Assert.Equal(-18f, TerrainField.MinWorldHeight); Assert.Equal(52f, TerrainField.MaxWorldHeight); @@ -56,7 +56,6 @@ namespace RustToDust.Tests public void StampCrater_LowersCenterRaisesRimAndDirtyOnlyOverlappingTiles() { var terrain = TerrainField.Generate(42UL, Array.Empty()); - terrain.ClearDirtyMask(); // Tile (3, 3) spans X in [-192, 0), Z in [-192, 0). // Point (-96, -96) with radius 6m is strictly inside tile (3, 3) and nowhere else. @@ -79,15 +78,15 @@ namespace RustToDust.Tests $"Expected crater ejecta rim to rise >0.2m (before {beforeRim:F2}, after {afterRim:F2})"); // Only tile (3, 3) should have incremented from version 1 to 2 - for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + for (int tz = 0; tz < terrain.TileGridCount; tz++) { - for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + for (int tx = 0; tx < terrain.TileGridCount; tx++) { int expected = (tx == 3 && tz == 3) ? 2 : 1; - Assert.Equal(expected, terrain.TileVersions[tx, tz]); + Assert.Equal(expected, terrain.StructuralTileVersions[tx, tz]); + Assert.Equal(expected, terrain.VisualTileVersions[tx, tz]); } } - Assert.Equal(1UL << (3 * TerrainField.TileGridCount + 3), terrain.DirtyTileMask); } [Fact] diff --git a/tools/build_release.ps1 b/tools/build_release.ps1 index f12c601..b840c8d 100644 --- a/tools/build_release.ps1 +++ b/tools/build_release.ps1 @@ -328,7 +328,7 @@ $vCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "vehicles") -Des $gCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "gear") -DestDir (Join-Path $stagedAssetsDir "gear") -IncludeExtensions @(".glb") $dCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "decals") -DestDir (Join-Path $stagedAssetsDir "decals") -IncludeExtensions @(".png") $aCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "audio") -DestDir (Join-Path $stagedAssetsDir "audio") -IncludeExtensions @(".wav", ".md") -$mCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "maps\sion") -DestDir (Join-Path $stagedAssetsDir "maps\sion") -IncludeExtensions @(".json", ".f32", ".png", ".bin", ".glb") +$mCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "maps\sion") -DestDir (Join-Path $stagedAssetsDir "maps\sion") -IncludeExtensions @(".json", ".u16z", ".png", ".bin", ".glb") Write-Host "Staged runtime assets: vehicles=$vCount gear=$gCount decals=$dCount audio=$aCount sion=$mCount" # Step 4: Create ZIP and SHA256SUMS.txt diff --git a/tools/maps/sion/bake_sion.py b/tools/maps/sion/bake_sion.py index ab735fa..ed67b58 100644 --- a/tools/maps/sion/bake_sion.py +++ b/tools/maps/sion/bake_sion.py @@ -27,6 +27,7 @@ import struct import urllib.parse import urllib.request import zipfile +import zlib from collections import Counter, defaultdict from pathlib import Path @@ -54,12 +55,15 @@ import tifffile # --------------------------------------------------------------------------- ARENA_SIZE_M = 3072.0 HALF_EXTENT_M = 1536.0 -GRID_RES = 1025 -CELL_SIZE_M = ARENA_SIZE_M / (GRID_RES - 1) # 3.0m exact -TILE_GRID = 6 -TILE_SIZE_M = ARENA_SIZE_M / TILE_GRID # 512.0m exact +GRID_RES = 6145 +CELL_SIZE_M = ARENA_SIZE_M / (GRID_RES - 1) # 0.5m exact +TILE_GRID = 16 +TILE_SIZE_M = ARENA_SIZE_M / TILE_GRID # 192.0m exact +BUILDING_TILE_GRID = 6 +BUILDING_TILE_SIZE_M = ARENA_SIZE_M / BUILDING_TILE_GRID # 512.0m legacy until Cut 13b -SURFACE_TEX_RES = 2048 +SURFACE_TEX_RES = 4096 +SURFACE_MASK_RES = 2048 # Centered around Valere & Tourbillon twin citadels to frame: # - Valere & Tourbillon fortress hills @@ -77,8 +81,8 @@ WMS_BASE_URL = "https://wms.geo.admin.ch/" SKIRT_DEPTH_M = 4.0 MAX_LOD1_TRIS = 275_000 MAX_TILES_GLB_BYTES = 28_000_000 -MAX_SURFACE_PNG_BYTES = 3_000_000 -MAX_TOTAL_ASSETS_BYTES = 40_000_000 +MAX_SURFACE_PNG_BYTES = 14_000_000 +MAX_TOTAL_ASSETS_BYTES = 85_000_000 # --------------------------------------------------------------------------- @@ -266,7 +270,7 @@ def acquire_swisstopo_data( if (ek, nk) not in needed_tiles: continue for asset_name, asset in item.get("assets", {}).items(): - if "_2_2056_5728.tif" in asset_name: + if "_0.5_2056_5728.tif" in asset_name: prev = best_alti.get((ek, nk)) if prev is None or yr > prev[0]: best_alti[(ek, nk)] = (yr, item["id"], asset_name, asset["href"]) @@ -320,7 +324,7 @@ def acquire_swisstopo_data( def sample_mosaic_grid( mosaic: np.ndarray, e_origin: float, n_top: float, center_e: float, center_n: float, res: int ) -> np.ndarray: - pixel_m = 2.0 + pixel_m = 0.5 step_m = ARENA_SIZE_M / (res - 1) xs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m zs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m @@ -337,7 +341,7 @@ def build_heightmap( ) -> tuple[np.ndarray, np.ndarray, float, float, float]: ekms = sorted({k[0] for k in tif_paths}) nkms = sorted({k[1] for k in tif_paths}, reverse=True) # north-to-south rows - tile_px = 500 + tile_px = 2000 mosaic = np.zeros((len(nkms) * tile_px, len(ekms) * tile_px), dtype=np.float32) for ni, nk in enumerate(nkms): @@ -351,8 +355,8 @@ def build_heightmap( n_top = (nkms[0] + 1) * 1000.0 # Grid coordinates in RustToDust: - # row iz (0..1024): Z = -1536 + iz * 3.0 (North -> South), N = center_n - Z - # col ix (0..1024): X = -1536 + ix * 3.0 (West -> East), E = center_e + X + # row iz (0..6144): Z = -1536 + iz * 0.5 (North -> South), N = center_n - Z + # col ix (0..6144): X = -1536 + ix * 0.5 (West -> East), E = center_e + X hm_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, GRID_RES) surf_dem_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, SURFACE_TEX_RES) @@ -362,6 +366,37 @@ def build_heightmap( return hm_rel, surf_dem_asl, base_elev, float(hm_rel.min()), float(hm_rel.max()) +def export_heightmap_u16z(hm: np.ndarray, out_path: Path) -> tuple[float, float, str]: + """ + Export 0.5m quantized heightmap as heightmap_05m.u16z: + Header (24 bytes LE): + magic="RDHM", uint32 version=2, uint32 gridRes=6145, + float32 minY, float32 scale, uint32 rawByteCount + Payload: + zlib-compressed row-wise zig-zag int16 spatial prediction residuals of uint16[gridRes*gridRes]. + """ + min_y = float(np.float32(hm.min())) + max_y = float(np.float32(hm.max())) + scale = float(np.float32(max(1e-6, (max_y - min_y) / 65535.0))) + q = np.clip(np.round((hm.astype(np.float64) - min_y) / scale), 0, 65535).astype(np.uint16) + + pred = np.empty_like(q) + pred[0, 0] = 0 + pred[1:, 0] = q[:-1, 0] + pred[:, 1:] = q[:, :-1] + + diff = (q.astype(np.int32) - pred.astype(np.int32)).astype(np.int16) + d32 = diff.astype(np.int32) + zz = (((d32 << 1) ^ (d32 >> 15)) & 0xFFFF).astype(np.uint16) + raw_bytes = np.ascontiguousarray(zz, dtype=" dict[str, np.ndarray]: @@ -386,9 +421,18 @@ def acquire_wms_masks( print(f" [WMS fetch] {layer} -> {dest.name}") req = urllib.request.Request(url, headers={"User-Agent": "RustToDust-SionBaker/1.0"}) tmp = dest.with_suffix(".png.part") - with urllib.request.urlopen(req, timeout=45) as resp: - tmp.write_bytes(resp.read()) - tmp.replace(dest) + try: + with urllib.request.urlopen(req, timeout=45) as resp: + tmp.write_bytes(resp.read()) + tmp.replace(dest) + except Exception: + if res > 2048: + fallback = acquire_wms_masks(cache_dir, e0, n0, e1, n1, 2048) + return { + k: zoom(v, (res / v.shape[0], res / v.shape[1], 1), order=1) + for k, v in fallback.items() + } + raise out[key] = imagecodecs.png_decode(dest.read_bytes()) return out @@ -452,13 +496,10 @@ def build_terrain_surface_texture( fp_res_tris: list[np.ndarray], fp_ind_tris: list[np.ndarray], fp_fort_tris: list[np.ndarray], -) -> bytes: +) -> tuple[bytes, bytes]: """ - Synthesize 2048x2048 RGB surface albedo PNG (< 3 MB) combining: - - Grey alpine limestone cliffs (steep Valere / Tourbillon / hillside slopes) - - Valley meadows, terraced vineyards & alpine forest slopes - - Old Town stone plazas, industrial yards, rail ballast & road/bridge network - - Rhone river & canal glacial teal-blue water tint + Synthesize 4096x4096 RGB surface albedo PNG and 2048x2048 RGBA8 surface class mask PNG + (R=rock_cliff, G=grass_vineyard, B=asphalt_gravel, A=water_channel). """ res = dem_asl.shape[0] px_m = ARENA_SIZE_M / (res - 1) # 1.5m/px @@ -572,6 +613,7 @@ def build_terrain_surface_texture( water_col = np.array([0.13, 0.27, 0.34], dtype=np.float32) + (fbm[..., None] - 0.5) * 0.03 rgb = rgb * (1.0 - water_soft[..., None] * 0.96) + water_col * (water_soft[..., None] * 0.96) + road_total = np.zeros((res, res), dtype=np.float32) # 6. Roads, highway A9 & bridges (drawn after water so bridges span the Rhone!) if wms_masks and "roads" in wms_masks: r_rgba = wms_masks["roads"] @@ -586,11 +628,28 @@ def build_terrain_surface_texture( highway_col = np.array([0.25, 0.25, 0.26], dtype=np.float32) rgb = rgb * (1.0 - minor_soft[..., None] * 0.72) + street_col * (minor_soft[..., None] * 0.72) rgb = rgb * (1.0 - major_soft[..., None] * 0.88) + highway_col * (major_soft[..., None] * 0.88) + road_total = np.clip(np.maximum(minor_soft, major_soft), 0.0, 1.0) # Darken slightly under exact building footprints for subtle ambient grounding bldg_under = (mask_res | mask_ind | mask_fort) & (normal_y > 0.75) rgb[bldg_under] *= 0.88 + # Build 2048x2048 RGBA8 surface class mask: + # R = rock_cliff, G = grass_vineyard, B = asphalt_gravel, A = water_channel + water_ch = gaussian_filter(water_mask.astype(np.float32), sigma=1.0) if np.any(water_mask) else np.zeros((res, res), dtype=np.float32) + rail_ch = gaussian_filter(binary_dilation(wms_masks["rail"][..., 3] > 50, iterations=4).astype(np.float32), sigma=1.2) if (wms_masks and "rail" in wms_masks) else np.zeros((res, res), dtype=np.float32) + asphalt_gravel = np.clip(np.maximum(road_total, np.maximum(rail_ch, np.maximum(res_soft, np.maximum(ind_soft, fort_soft)))), 0.0, 1.0) + rock_cliff = np.clip(cliff_t, 0.0, 1.0) + grass_vineyard = np.clip((1.0 - rock_cliff) * (1.0 - water_ch) * (1.0 - asphalt_gravel * 0.85), 0.0, 1.0) + mask_full = np.stack([rock_cliff, grass_vineyard, asphalt_gravel, np.clip(water_ch, 0.0, 1.0)], axis=-1) + step = max(1, res // SURFACE_MASK_RES) + if step > 1: + mask_ds = mask_full.reshape(SURFACE_MASK_RES, step, SURFACE_MASK_RES, step, 4).mean(axis=(1, 3)) + else: + mask_ds = mask_full + mask_u8 = np.clip(np.round(mask_ds * 255.0), 0, 255).astype(np.uint8) + mask_png_bytes = imagecodecs.png_encode(mask_u8, level=9) + rgb_u8 = np.clip(np.round(rgb * 255.0), 0, 255).astype(np.uint8) png_bytes = imagecodecs.png_encode(rgb_u8, level=9) if len(png_bytes) >= MAX_SURFACE_PNG_BYTES: @@ -600,7 +659,7 @@ def build_terrain_surface_texture( if len(png_bytes) >= MAX_SURFACE_PNG_BYTES: rgb_u8 = (rgb_u8 & 0xFC) png_bytes = imagecodecs.png_encode(rgb_u8, level=9) - return png_bytes + return png_bytes, mask_png_bytes def sample_heightmap(hm: np.ndarray, x: np.ndarray | float, z: np.ndarray | float) -> np.ndarray | float: @@ -1715,6 +1774,7 @@ def main() -> None: parser.add_argument("--cache-dir", default=os.path.join(os.environ.get("TEMP", "/tmp"), "sion-cache")) parser.add_argument("--center-e", type=float, default=DEFAULT_CENTER_E) parser.add_argument("--center-n", type=float, default=DEFAULT_CENTER_N) + parser.add_argument("--terrain-only", action="store_true", help="Re-bake 0.5m DEM, surface, mask & metadata.json while preserving existing tiles/ & buildings_manifest.json") args = parser.parse_args() repo_root = Path(args.repo_root).resolve() @@ -1725,21 +1785,23 @@ def main() -> None: cache_dir = Path(args.cache_dir) cache_dir.mkdir(parents=True, exist_ok=True) - # Cut obsolete single-monolith GLBs & any stale tile files before baking - for obsolete in ("sion_lod2.glb", "sion_lod1.glb"): + # Cut obsolete single-monolith GLBs & legacy float32 heightmap + for obsolete in ("sion_lod2.glb", "sion_lod1.glb", "heightmap.f32"): obs_path = out_dir / obsolete if obs_path.exists(): obs_path.unlink() - print(f"[Sion Baker] Removed obsolete monolith {obs_path.name}") - for stale in tiles_dir.iterdir(): - if stale.is_file(): - stale.unlink() + print(f"[Sion Baker] Removed obsolete {obs_path.name}") + if not args.terrain_only: + for stale in tiles_dir.iterdir(): + if stale.is_file(): + stale.unlink() cE, cN = args.center_e, args.center_n e0, n0, e1, n1 = cE - HALF_EXTENT_M, cN - HALF_EXTENT_M, cE + HALF_EXTENT_M, cN + HALF_EXTENT_M print( - f"[Sion Baker] Arena {ARENA_SIZE_M:.0f}m x {ARENA_SIZE_M:.0f}m ({TILE_GRID}x{TILE_GRID} tiles of {TILE_SIZE_M:.0f}m) " + f"[Sion Baker] Arena {ARENA_SIZE_M:.0f}m x {ARENA_SIZE_M:.0f}m (terrain {TILE_GRID}x{TILE_GRID} @ {TILE_SIZE_M:.0f}m, " + f"bldg {BUILDING_TILE_GRID}x{BUILDING_TILE_GRID} @ {BUILDING_TILE_SIZE_M:.0f}m) " f"EPSG:2056 center=({cE:.1f}, {cN:.1f}) bbox=[{e0:.1f}..{e1:.1f}, {n0:.1f}..{n1:.1f}]" ) tif_paths, gdb_paths, stac_ids = acquire_swisstopo_data(cache_dir, e0, n0, e1, n1) @@ -1750,15 +1812,105 @@ def main() -> None: except Exception as exc: print(f" [WMS warning] Falling back to DEM-only river/road synthesis ({exc})") - print(f"[Sion Baker] Stitching & resampling swissALTI3D to {GRID_RES}x{GRID_RES} float32...") + print(f"[Sion Baker] Stitching & resampling swissALTI3D 0.5m to {GRID_RES}x{GRID_RES}...") hm, surf_dem_asl, base_elev, min_y, max_y = build_heightmap(tif_paths, cE, cN) - hm_path = out_dir / "heightmap.f32" - hm.astype("= MAX_TOTAL_ASSETS_BYTES: + raise RuntimeError(f"Total asset budget exceeded: {total_assets_bytes} bytes >= {MAX_TOTAL_ASSETS_BYTES}") + return + # Read semantic layers across intersecting GDB tiles print("[Sion Baker] Reading swissBUILDINGS3D 3.0 layers (Building_solid, Wall, Roof, Floor)...") reader = OgrReader() @@ -1877,8 +2029,8 @@ def main() -> None: bmax = all_rtd_pts.max(axis=0) box_center = (bmin + bmax) * 0.5 - tx = max(0, min(TILE_GRID - 1, int(math.floor((float(box_center[0]) + HALF_EXTENT_M) / TILE_SIZE_M)))) - tz = max(0, min(TILE_GRID - 1, int(math.floor((float(box_center[2]) + HALF_EXTENT_M) / TILE_SIZE_M)))) + tx = max(0, min(BUILDING_TILE_GRID - 1, int(math.floor((float(box_center[0]) + HALF_EXTENT_M) / BUILDING_TILE_SIZE_M)))) + tz = max(0, min(BUILDING_TILE_GRID - 1, int(math.floor((float(box_center[2]) + HALF_EXTENT_M) / BUILDING_TILE_SIZE_M)))) tkey = (tx, tz) tile_bldg_counts[tkey] += 1 @@ -1942,16 +2094,19 @@ def main() -> None: } ) - # Bake 2048x2048 terrain_surface.png albedo - print(f"[Sion Baker] Synthesizing {SURFACE_TEX_RES}x{SURFACE_TEX_RES} terrain_surface.png...") - surf_png = build_terrain_surface_texture( + # Bake 4096x4096 terrain_surface.png albedo + 2048x2048 terrain_surface_mask.png + print(f"[Sion Baker] Synthesizing {SURFACE_TEX_RES}x{SURFACE_TEX_RES} terrain_surface.png + {SURFACE_MASK_RES}x{SURFACE_MASK_RES} terrain_surface_mask.png...") + surf_png, mask_png = build_terrain_surface_texture( surf_dem_asl, base_elev, wms_masks, fp_res_tris, fp_ind_tris, fp_fort_tris ) surf_path = out_dir / "terrain_surface.png" surf_path.write_bytes(surf_png) + mask_path = out_dir / "terrain_surface_mask.png" + mask_path.write_bytes(mask_png) print(f" terrain_surface.png: {len(surf_png):,} bytes ({len(surf_png)/1e6:.2f} MB)") + print(f" terrain_surface_mask.png: {len(mask_png):,} bytes ({len(mask_png)/1e6:.2f} MB)") if len(surf_png) >= MAX_SURFACE_PNG_BYTES: - raise RuntimeError(f"terrain_surface.png exceeded 3 MB budget: {len(surf_png)} bytes") + raise RuntimeError(f"terrain_surface.png exceeded budget: {len(surf_png)} bytes") # Export per-tile LOD2 GLBs & RCOL v1 collision bins non_empty_tiles = sorted(tile_bldg_counts.keys()) @@ -1971,8 +2126,8 @@ def main() -> None: total_lod2_bytes += l2_bytes total_col_tris += c_tris total_col_bytes += c_bytes - tile_cx = -HALF_EXTENT_M + (tx + 0.5) * TILE_SIZE_M - tile_cz = -HALF_EXTENT_M + (tz + 0.5) * TILE_SIZE_M + tile_cx = -HALF_EXTENT_M + (tx + 0.5) * BUILDING_TILE_SIZE_M + tile_cz = -HALF_EXTENT_M + (tz + 0.5) * BUILDING_TILE_SIZE_M tile_stats[tkey] = { "tx": tx, "tz": tz, @@ -2035,8 +2190,8 @@ def main() -> None: "coordinateSystem": "rusttodust_arena_gltf", "attribution": "Federal Office of Topography swisstopo", "sizeMeters": ARENA_SIZE_M, - "tileGrid": TILE_GRID, - "tileSizeMeters": TILE_SIZE_M, + "tileGrid": BUILDING_TILE_GRID, + "tileSizeMeters": BUILDING_TILE_SIZE_M, "count": len(manifest_entries), "classes": dict(class_counts.most_common()), "buildings": manifest_entries, @@ -2048,10 +2203,11 @@ def main() -> None: "name": "Sion, Valais, Switzerland", "attribution": "Federal Office of Topography swisstopo", "sources": [ - "ch.swisstopo.swissalti3d (2m DTM, Open Government Data)", + "ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)", "ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)", ], "stacItems": stac_ids, + "demAssetHash": dem_hash, "crs": "EPSG:2056", "originE": e0, "originN": n0, @@ -2064,12 +2220,20 @@ def main() -> None: "sizeMeters": ARENA_SIZE_M, "tileGrid": TILE_GRID, "tileSizeMeters": TILE_SIZE_M, + "buildingTileGrid": BUILDING_TILE_GRID, + "buildingTileSizeMeters": BUILDING_TILE_SIZE_M, "gridRes": GRID_RES, "cellSizeMeters": CELL_SIZE_M, - "heightmapFormat": "float32_le_row_major", + "heightmapFile": "heightmap_05m.u16z", + "heightmapFormat": "rdhm_v2_u16_zigzag_zlib", + "heightmapMinY": hm_min_y, + "heightmapScale": hm_scale, "surfaceTexture": "terrain_surface.png", "surfaceTextureSize": SURFACE_TEX_RES, "surfaceTextureFormat": "png_rgb_north_to_south_west_to_east", + "surfaceMaskTexture": "terrain_surface_mask.png", + "surfaceMaskTextureSize": SURFACE_MASK_RES, + "surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water", "collisionFormat": { "magic": "RCOL", "version": 1,