Files
systemrevivalserver/Game/Dungeon/DungeonGeneratorVNext.cs
T
2026-02-08 22:21:03 -05:00

457 lines
15 KiB
C#

using DataServer.Data;
using Microsoft.Extensions.Logging;
namespace GameServer.Dungeon;
/// <summary>
/// Dungeon Generator VNext (first-pass implementation):
/// - BSP room partitioning for macro structure
/// - Random-walk corridor carving (2-4 tile width)
/// - Tier-scaled size/room count and multi-boss support for tier 6+
/// </summary>
public class DungeonGeneratorVNext
{
private readonly int _seed;
private readonly int _tier;
private readonly Random _rng;
private readonly ILogger<DungeonGeneratorVNext>? _logger;
public DungeonGeneratorVNext(GameDbContext db, int seed, int tier = 1, ILogger<DungeonGeneratorVNext>? logger = null)
{
_seed = seed;
_tier = Math.Max(1, tier);
_rng = new Random(seed);
_logger = logger;
}
private readonly record struct PartitionRect(int X, int Y, int Width, int Height)
{
public int CenterX => X + Width / 2;
public int CenterY => Y + Height / 2;
}
public Task<DungeonLayoutV2> GenerateAsync()
{
int size = 72 + (_tier * 8);
if (_tier >= 6) size += (_tier - 5) * 12;
int mapWidth = Math.Clamp(size, 64, 220);
int mapHeight = Math.Clamp(size, 64, 220);
int targetRooms = 10 + (_tier * 2);
if (_tier >= 6) targetRooms += _tier;
targetRooms = Math.Clamp(targetRooms, 12, 80);
var layout = new DungeonLayoutV2(mapWidth, mapHeight)
{
Seed = _seed,
Tier = _tier,
TileSize = 32
};
for (int x = 0; x < mapWidth; x++)
{
for (int y = 0; y < mapHeight; y++)
{
layout.Tiles[x, y] = 0;
layout.Walkable![x, y] = false;
}
}
var rooms = GenerateRooms(mapWidth, mapHeight, targetRooms);
if (rooms.Count < 2)
{
rooms = GenerateFallbackRooms(mapWidth, mapHeight);
}
foreach (var room in rooms)
{
CarveRoom(layout, room);
}
ConnectRoomsWithRandomWalk(layout, rooms);
AddLoopConnections(layout, rooms, Math.Max(2, rooms.Count / 4));
AssignRoomTypes(rooms);
GenerateSpawnsAndChests(layout, rooms);
BuildSimpleTileDetails(layout);
layout.Rooms = rooms;
var entrance = rooms.FirstOrDefault(r => r.Type == DungeonRoomType.Entrance) ?? rooms[0];
layout.SpawnPoint = new DungeonPoint(entrance.CenterX, entrance.CenterY);
layout.PlayerSpawnX = entrance.CenterX;
layout.PlayerSpawnY = entrance.CenterY;
layout.TotalMobs = layout.MobSpawns.Count;
layout.TotalChests = layout.ChestSpawns.Count;
_logger?.LogInformation(
"VNext generated seed {Seed}, tier {Tier}: {Width}x{Height}, rooms={RoomCount}, mobs={MobCount}, chests={ChestCount}",
_seed, _tier, mapWidth, mapHeight, rooms.Count, layout.TotalMobs, layout.TotalChests);
return Task.FromResult(layout);
}
private List<DungeonRoom> GenerateRooms(int mapWidth, int mapHeight, int targetRooms)
{
var leaves = new List<PartitionRect> { new(2, 2, mapWidth - 4, mapHeight - 4) };
int minLeafSize = 16;
int splitGuard = 0;
while (leaves.Count < targetRooms * 2 && splitGuard++ < 4000)
{
int index = _rng.Next(leaves.Count);
var leaf = leaves[index];
bool splitVertical = leaf.Width > leaf.Height;
if (_rng.NextDouble() < 0.35) splitVertical = !splitVertical;
if (splitVertical)
{
if (leaf.Width < minLeafSize * 2) continue;
int splitX = _rng.Next(leaf.X + minLeafSize, leaf.X + leaf.Width - minLeafSize);
var left = new PartitionRect(leaf.X, leaf.Y, splitX - leaf.X, leaf.Height);
var right = new PartitionRect(splitX, leaf.Y, leaf.X + leaf.Width - splitX, leaf.Height);
leaves[index] = left;
leaves.Add(right);
}
else
{
if (leaf.Height < minLeafSize * 2) continue;
int splitY = _rng.Next(leaf.Y + minLeafSize, leaf.Y + leaf.Height - minLeafSize);
var top = new PartitionRect(leaf.X, leaf.Y, leaf.Width, splitY - leaf.Y);
var bottom = new PartitionRect(leaf.X, splitY, leaf.Width, leaf.Y + leaf.Height - splitY);
leaves[index] = top;
leaves.Add(bottom);
}
}
var rooms = new List<DungeonRoom>();
int minRoom = 8;
int maxRoom = 20;
foreach (var leaf in leaves.OrderBy(_ => _rng.Next()))
{
if (rooms.Count >= targetRooms) break;
int margin = 2;
int maxW = Math.Max(minRoom, leaf.Width - margin * 2);
int maxH = Math.Max(minRoom, leaf.Height - margin * 2);
if (maxW < minRoom || maxH < minRoom) continue;
int width = _rng.Next(minRoom, Math.Min(maxRoom, maxW) + 1);
int height = _rng.Next(minRoom, Math.Min(maxRoom, maxH) + 1);
int x = _rng.Next(leaf.X + 1, leaf.X + leaf.Width - width);
int y = _rng.Next(leaf.Y + 1, leaf.Y + leaf.Height - height);
var room = new DungeonRoom(x, y, width, height);
if (rooms.Any(r => room.Intersects(r, 1))) continue;
rooms.Add(room);
}
return rooms
.OrderBy(r => r.X + r.Y)
.ToList();
}
private List<DungeonRoom> GenerateFallbackRooms(int mapWidth, int mapHeight)
{
var rooms = new List<DungeonRoom>();
int count = Math.Max(6, Math.Min(12, 4 + _tier));
int attempts = 0;
while (rooms.Count < count && attempts++ < count * 30)
{
int width = _rng.Next(8, 16);
int height = _rng.Next(8, 16);
int x = _rng.Next(2, mapWidth - width - 2);
int y = _rng.Next(2, mapHeight - height - 2);
var room = new DungeonRoom(x, y, width, height);
if (rooms.Any(r => room.Intersects(r, 2))) continue;
rooms.Add(room);
}
return rooms.OrderBy(r => r.X + r.Y).ToList();
}
private void CarveRoom(DungeonLayoutV2 layout, DungeonRoom room)
{
for (int x = room.X; x < room.X + room.Width; x++)
{
for (int y = room.Y; y < room.Y + room.Height; y++)
{
SetFloor(layout, x, y);
}
}
}
private void ConnectRoomsWithRandomWalk(DungeonLayoutV2 layout, List<DungeonRoom> rooms)
{
if (rooms.Count < 2) return;
var connected = new List<DungeonRoom> { rooms[0] };
var unconnected = new HashSet<DungeonRoom>(rooms.Skip(1));
while (unconnected.Count > 0)
{
DungeonRoom? bestFrom = null;
DungeonRoom? bestTo = null;
float bestDist = float.MaxValue;
foreach (var from in connected)
{
foreach (var to in unconnected)
{
float dist = Distance(from.CenterX, from.CenterY, to.CenterX, to.CenterY);
if (dist < bestDist)
{
bestDist = dist;
bestFrom = from;
bestTo = to;
}
}
}
if (bestFrom == null || bestTo == null) break;
int width = _rng.Next(2, 5);
CarveRandomWalkCorridor(layout, bestFrom.CenterX, bestFrom.CenterY, bestTo.CenterX, bestTo.CenterY, width);
connected.Add(bestTo);
unconnected.Remove(bestTo);
}
}
private void AddLoopConnections(DungeonLayoutV2 layout, List<DungeonRoom> rooms, int loopCount)
{
if (rooms.Count < 3) return;
for (int i = 0; i < loopCount; i++)
{
var a = rooms[_rng.Next(rooms.Count)];
var b = rooms[_rng.Next(rooms.Count)];
if (ReferenceEquals(a, b)) continue;
int width = _rng.Next(2, 5);
CarveRandomWalkCorridor(layout, a.CenterX, a.CenterY, b.CenterX, b.CenterY, width);
}
}
private void CarveRandomWalkCorridor(DungeonLayoutV2 layout, int startX, int startY, int endX, int endY, int width)
{
int x = startX;
int y = startY;
int guard = layout.Width * layout.Height * 2;
while ((x != endX || y != endY) && guard-- > 0)
{
CarveBrush(layout, x, y, width);
int dx = Math.Sign(endX - x);
int dy = Math.Sign(endY - y);
int stepX = 0;
int stepY = 0;
if (_rng.NextDouble() < 0.7)
{
if (Math.Abs(endX - x) >= Math.Abs(endY - y))
stepX = dx;
else
stepY = dy;
}
else
{
int roll = _rng.Next(4);
if (roll == 0) stepX = 1;
if (roll == 1) stepX = -1;
if (roll == 2) stepY = 1;
if (roll == 3) stepY = -1;
}
if (stepX == 0 && stepY == 0)
{
if (dx != 0) stepX = dx;
else if (dy != 0) stepY = dy;
}
x = Math.Clamp(x + stepX, 1, layout.Width - 2);
y = Math.Clamp(y + stepY, 1, layout.Height - 2);
}
CarveBrush(layout, endX, endY, width);
}
private void CarveBrush(DungeonLayoutV2 layout, int cx, int cy, int width)
{
int half = width / 2;
for (int x = cx - half; x <= cx + half; x++)
{
for (int y = cy - half; y <= cy + half; y++)
{
SetFloor(layout, x, y);
}
}
}
private void SetFloor(DungeonLayoutV2 layout, int x, int y)
{
if (x < 1 || y < 1 || x >= layout.Width - 1 || y >= layout.Height - 1) return;
layout.Tiles[x, y] = 1;
layout.Walkable![x, y] = true;
}
private void AssignRoomTypes(List<DungeonRoom> rooms)
{
if (rooms.Count == 0) return;
int entranceIndex = rooms
.Select((r, i) => (idx: i, score: r.X + r.Y))
.OrderBy(p => p.score)
.Select(p => p.idx)
.First();
rooms[entranceIndex].Type = DungeonRoomType.Entrance;
int bossCount = _tier >= 6 ? Math.Min(1 + (_tier / 4), 3) : 1;
var candidates = rooms
.Select((r, i) => (room: r, idx: i))
.Where(p => p.idx != entranceIndex)
.OrderByDescending(p => Distance(rooms[entranceIndex].CenterX, rooms[entranceIndex].CenterY, p.room.CenterX, p.room.CenterY))
.ToList();
if (candidates.Count == 0)
{
rooms[entranceIndex].Type = DungeonRoomType.Boss;
return;
}
foreach (var room in rooms.Where(r => r.Type != DungeonRoomType.Entrance))
{
room.Type = DungeonRoomType.Combat;
}
for (int i = 0; i < Math.Min(bossCount, candidates.Count); i++)
{
candidates[i].room.Type = DungeonRoomType.Boss;
}
int treasureCount = Math.Max(1, rooms.Count / 8);
var treasureCandidates = rooms
.Where(r => r.Type == DungeonRoomType.Combat)
.OrderBy(_ => _rng.Next())
.Take(treasureCount);
foreach (var room in treasureCandidates)
{
room.Type = DungeonRoomType.Treasure;
}
}
private void GenerateSpawnsAndChests(DungeonLayoutV2 layout, List<DungeonRoom> rooms)
{
layout.MobSpawns.Clear();
layout.ChestSpawns.Clear();
int mobId = 1;
int chestId = 1;
for (int i = 0; i < rooms.Count; i++)
{
var room = rooms[i];
if (room.Type == DungeonRoomType.Entrance) continue;
int mobCount = room.Type switch
{
DungeonRoomType.Boss => 1,
DungeonRoomType.Treasure => _rng.Next(1, 3),
_ => _rng.Next(2, 5 + Math.Max(0, _tier / 2))
};
for (int m = 0; m < mobCount; m++)
{
var pos = RandomPointInRoom(room);
layout.MobSpawns.Add(new DungeonMobSpawn
{
Id = mobId++,
X = pos.x,
Y = pos.y,
MobType = room.Type == DungeonRoomType.Boss ? DungeonMobSpawnType.Boss : DungeonMobSpawnType.Normal,
RoomIndex = i
});
}
int chestCount = room.Type switch
{
DungeonRoomType.Boss => 1,
DungeonRoomType.Treasure => _rng.Next(1, 3),
_ => _rng.NextDouble() < 0.25 ? 1 : 0
};
for (int c = 0; c < chestCount; c++)
{
var pos = RandomPointInRoom(room);
layout.ChestSpawns.Add(new DungeonChestSpawn
{
Id = chestId++,
X = pos.x,
Y = pos.y,
ChestType = room.Type == DungeonRoomType.Boss ? DungeonChestType.Boss : DungeonChestType.Normal,
RoomIndex = i
});
}
}
if (!layout.MobSpawns.Any(m => m.MobType == DungeonMobSpawnType.Boss) && rooms.Count > 0)
{
int fallbackRoomIndex = rooms.FindIndex(r => r.Type != DungeonRoomType.Entrance);
if (fallbackRoomIndex < 0) fallbackRoomIndex = 0;
var pos = RandomPointInRoom(rooms[fallbackRoomIndex]);
layout.MobSpawns.Add(new DungeonMobSpawn
{
Id = mobId,
X = pos.x,
Y = pos.y,
MobType = DungeonMobSpawnType.Boss,
RoomIndex = fallbackRoomIndex
});
rooms[fallbackRoomIndex].Type = DungeonRoomType.Boss;
}
}
private (int x, int y) RandomPointInRoom(DungeonRoom room)
{
int x = _rng.Next(room.X + 1, room.X + room.Width - 1);
int y = _rng.Next(room.Y + 1, room.Y + room.Height - 1);
return (x, y);
}
private void BuildSimpleTileDetails(DungeonLayoutV2 layout)
{
layout.TileDetails.Clear();
for (int y = 0; y < layout.Height; y++)
{
for (int x = 0; x < layout.Width; x++)
{
if (!layout.Walkable![x, y]) continue;
layout.TileDetails.Add(new PlacedTile
{
X = x,
Y = y,
TileDefinitionId = 0,
SheetId = 0,
FrameIndex = 0,
Layer = 0,
Rotation = 0,
FlipX = false,
FlipY = false
});
}
}
}
private static float Distance(int x1, int y1, int x2, int y2)
{
int dx = x2 - x1;
int dy = y2 - y1;
return MathF.Sqrt(dx * dx + dy * dy);
}
}