From 7b03b4139a8f7d8987fa4576965e055aaa2eb7e5 Mon Sep 17 00:00:00 2001 From: dingo Date: Sun, 8 Feb 2026 22:01:19 -0500 Subject: [PATCH] new builder --- DungeonBuildSystemReview.md | 142 ++++++++++++++ DungeonBuilderVNextPlan.md | 249 ++++++++++++++++++++++++ Game/Dungeon/DungeonHandler.Dungeons.cs | 36 +++- Game/Dungeon/DungeonHandler.cs | 16 +- Game/Dungeon/DungeonHandlerAdmin.cs | 9 +- Game/Dungeon/DungeonInstance.cs | 56 ++++++ 6 files changed, 495 insertions(+), 13 deletions(-) create mode 100644 DungeonBuildSystemReview.md create mode 100644 DungeonBuilderVNextPlan.md diff --git a/DungeonBuildSystemReview.md b/DungeonBuildSystemReview.md new file mode 100644 index 0000000..2968133 --- /dev/null +++ b/DungeonBuildSystemReview.md @@ -0,0 +1,142 @@ +# Dungeon Build System Review (Admin/DungeonBuilder) + +## Goal +Document the current dungeon build/generation system, explain why it works today, and define a practical plan to make it more reliable and easier to operate from `/admin/dungeonbuilder`. + +## Current Architecture + +### Runtime generation entry points +- Active dungeon creation uses fallback chain: +1. `Game/Dungeon/DungeonHandler.Dungeons.cs` tries `DungeonGeneratorV3` first. +2. If V3 produces no tiles or throws, it falls back to `DungeonGeneratorV2`. +3. If V2 fails, it falls back to `DungeonGenerator` (V1). +- `DungeonHandler` has a duplicated create/join flow in `Game/Dungeon/DungeonHandler.cs` with the same fallback behavior. + +### Layout models +- `DungeonLayout` (`Game/Dungeon/DungeonLayout.cs`): + - Core grid + walkability + spawn lists. + - Supports RLE serialization for transport. +- `DungeonLayoutV2` (`Game/Dungeon/DungeonLayoutV2.cs`): + - Adds `TileDetails`, `TileMapSheets`, and placed objects for visual rendering. + - Keeps compatibility with `DungeonLayout`. + +### Generator versions +- V1: `Game/Dungeon/DungeonGenerator.cs` + - Pure procedural rooms + L-corridors. + - No DungeonBuilder template pipeline. +- V2: `Game/Dungeon/DungeonGeneratorV2.cs` + - Uses legacy `RoomTemplate` + tile definitions + socket/tag logic. + - Includes strict socket support and tag-driven fallback (`Game/Dungeon/TagDrivenTiles.cs`). +- V3: `Game/Dungeon/DungeonGeneratorV3.cs` + - Uses DungeonBuilder entities (`BuilderRoomTemplate`, `TileTemplate`, `ObjectTemplate`, `DungeonPalette`, buckets/rules). + - Pipeline: +1. Load palette and template sets. +2. Load tile definitions/sheets and bucket rules. +3. Place rooms (template stamp or procedural fallback). +4. Connect rooms (MST-like nearest linking + L corridors). +5. Fill floor tiles. +6. Place wall tiles. +7. Place objects. +8. Build spawn points. + +### Admin DungeonBuilder data model +- Main entities are defined in: + - `Data/entities/DungeonBuilder.cs` + - `Data/entities/TileMap.cs` + - `Data/entities/TileBuckets.cs` +- Editing pages: + - Rooms: `Services/Admin/Pages/DungeonBuilder/Rooms.cshtml.cs`, `RoomEdit.cshtml.cs` + - Tiles: `Services/Admin/Pages/DungeonBuilder/Tiles.cshtml.cs`, `TileEdit.cshtml.cs` + - Palettes: `Services/Admin/Pages/DungeonBuilder/PaletteEdit.cshtml.cs` + - Buckets: `Services/Admin/Pages/DungeonBuilder/Buckets/Edit.cshtml.cs` + - Stamps: `Services/Admin/Pages/DungeonBuilder/Stamps/Edit.cshtml.cs` + +## Why the system works today + +### 1) Defensive fallback chain prevents total outage +- Even if V3 content is misconfigured, dungeon creation still succeeds via V2/V1 fallback. + +### 2) Deterministic seed-based generation +- All generators initialize `Random` with seed, so reproducing map behavior is possible when using the same pipeline and data. + +### 3) Separation between logic grid and render tiles +- `Walkable` + tile ids drive simulation; `TileDetails` + `TileMapSheets` drive rendering. +- This supports live gameplay without requiring renderer-specific assumptions in sim code. + +### 4) Content-first generation in V3 +- V3 consumes palette and template assets from admin-managed DB content, enabling non-code content iteration. + +## Main issues (current gaps) + +### A) Generator fragmentation and duplicate orchestration +- V1/V2/V3 coexist with overlapping responsibilities. +- Dungeon creation logic is duplicated in both `DungeonHandler.Dungeons.cs` and `DungeonHandler.cs`. +- This increases drift risk and makes fixes easy to miss. + +### B) Restore path drops V2/V3 visual fidelity +- `RestoreDungeonFromPersistenceAsync` rebuilds with V1 (`DungeonGenerator.Generate(...)`) in `Game/Dungeon/DungeonHandler.Dungeons.cs`. +- Result: restored dungeons do not preserve V2/V3 visual layout/object output. + +### C) Test tool does not test real runtime generator +- `/admin/dungeonbuilder/testgen` (`TestGen.cshtml.cs`) uses an internal simplified generator, not V3. +- This makes admin preview results diverge from real dungeon runtime behavior. + +### D) Heavy silent-failure behavior in V3 parsing +- Multiple broad `catch { }` paths in `DungeonGeneratorV3` suppress parse/content errors. +- Invalid JSON or bad references degrade quality silently instead of failing fast with diagnostics. + +### E) Runtime DB access inside stamp/object loops +- `DungeonGeneratorV3` calls DB lookups inside generation loops (example: object template lookup during room stamping). +- This increases generation latency and variability under load. + +### F) Live tile edit broadcasting can become expensive +- Tile updates in `DungeonHandler` can fall back to full tile payload broadcast when diff data is missing. +- `HasPendingTileUpdates` and `_changedTiles` coordination is workable but fragile under concurrent edits. + +### G) Inconsistent template lineage +- V2 relies on `RoomTemplate` while V3 uses `BuilderRoomTemplate`. +- Admin UX is centered on Builder entities, but runtime still keeps legacy paths active. + +## Viable solution to improve system + +## Direction +Keep V3 as the primary pipeline and make admin tools validate against the same runtime code path. +Retain V2/V1 only as controlled feature-flagged emergency fallback, not normal operation. + +## Phase 1: Stabilize and align tooling +1. Make `/admin/dungeonbuilder/testgen` call `DungeonGeneratorV3.GenerateAsync` directly. +2. Add a structured generation report object (rooms placed, fallbacks used, parse errors, missing refs, timing). +3. Surface this report in the TestGen UI and store last N reports for troubleshooting. + +## Phase 2: Add content validation/compile step +1. Add “Validate Palette” action in admin: + - checks JSON parse for room/tile/object blobs, + - verifies referenced IDs exist and are enabled, + - checks connection points and spawn points are in-bounds, + - checks sockets/buckets consistency. +2. Add “Compile Palette Snapshot”: + - pre-resolve template references into normalized DTOs, + - cache by palette id + updated timestamp. +3. Generator consumes compiled snapshot (single load) instead of many ad-hoc DB lookups. + +## Phase 3: Runtime consistency and persistence +1. Persist enough V2/V3 layout data to restore exact walkability + visual state (or persisted layout seed+palette+version with deterministic replay). +2. Remove V1 restore path for dungeons created with V2/V3. +3. Keep one generator orchestration path in `DungeonHandler` (single method used by both partial files). + +## Phase 4: Live editing robustness +1. Replace boolean `HasPendingTileUpdates` with monotonic change version. +2. Store tile delta batches (position/layer/op/version) per dungeon for replay-safe client sync. +3. Keep “full snapshot” path only for explicit resync, not as implicit fallback. + +## Concrete acceptance criteria +1. TestGen output matches runtime generation for same `seed/tier/palette`. +2. Invalid Builder content produces actionable validation errors before runtime. +3. Restored dungeons preserve V3 visual/walkability integrity. +4. Generation no longer does N+1 DB fetches in stamp/object loops. +5. Tile edit sync remains differential under normal operation. + +## Recommended immediate next steps +1. Implement TestGen -> V3 integration first (highest ROI for admin trust). +2. Add validation endpoint + UI report next (prevents silent bad content). +3. Refactor dungeon creation into one shared internal method in `DungeonHandler`. diff --git a/DungeonBuilderVNextPlan.md b/DungeonBuilderVNextPlan.md new file mode 100644 index 0000000..c78ef0f --- /dev/null +++ b/DungeonBuilderVNextPlan.md @@ -0,0 +1,249 @@ +# Dungeon Builder VNext (New System Spec) + +## Core Rules (Authoritative) +1. Floor tiles may touch only floor tiles that share at least one floor bucket. +2. A floor tile may belong to multiple buckets. +3. Floor tiles must not touch floor tiles with no shared bucket on any cardinal side. +4. Corridors must be 2-4 tiles wide. +5. Wall placement follows the same bucket compatibility principle (shared wall bucket required where applicable). +6. Wall tile selection uses neighbor analysis (8 directions) to choose the correct visual tile. +7. Wall tile selection must support multiple tilesets while preserving correct topology. +8. Room templates are sampled from the selected palette, but each room slot may choose template stamp or procedural fallback. +9. The same room template must not be used more than once per dungeon tier run. +10. Every dungeon must contain at least one boss. +11. Tier 6+ dungeons increase in scale and may contain multiple bosses. +12. Dungeon clear/closure requires all bosses to be defeated. +13. Add runtime flag `BossesRespawnOnReload` (default `false` for now). + +## High-Level Generation Strategy +Use a hybrid pipeline: +1. BSP for macro structure (region partition + room candidate space). +2. Random Walk for organic connectivity and variation. +3. Corridor carving with width 2-4. +4. Floor painting via bucket-constrained compatibility. +5. Wall synthesis via 8-neighbor bitmask + bucket-specific lookup tables. + +## Data Model (VNext) + +### Floor tile definition +- `TileId` +- `SheetId` +- `FrameIndex` +- `FloorBuckets: HashSet` +- `Weight` +- `Tags` + +### Wall tile definition +- `TileId` +- `SheetId` +- `FrameIndex` +- `WallBuckets: HashSet` +- `MaskKey` (8-neighbor mask family key) +- `Weight` +- `Tags` + +### Bucket adjacency policy +- `BucketId` +- `AllowedTouchBuckets: HashSet` +- Applies to floor-floor and wall-wall adjacency checks. + +### Static wall lookup +- `Dictionary>>` +- Keyed by: + - `bucketId` + - `mask` from 8-neighbor occupancy (`0=empty/wall`, `1=floor`) + +### Room template sampling state +- `UsedRoomTemplateIds: HashSet` per generated dungeon instance (or per tier-run context). +- `RoomTemplateSamplingMode`: + - `TemplateOrProcedural` (try template first, allow procedural fallback by chance/rules). +- `NoDuplicateRoomTemplatePerTier: bool = true`. + +### Boss runtime state +- `TotalBossCount` +- `BossesDefeatedCount` +- `BossesRespawnOnReload: bool = false` +- `RequireAllBossesForDungeonClear: bool = true` + +## Topology Encoding for Walls + +### Neighbor mask convention +- 8 bits in fixed order: +1. N +2. NE +3. E +4. SE +5. S +6. SW +7. W +8. NW +- Bit value: + - `1` if neighbor cell is floor. + - `0` if neighbor cell is empty or wall. + +### Result +- Every wall candidate cell computes one mask. +- Mask + bucket selects correct wall tile variant. +- This decouples wall correctness from art pack and enables multi-tileset support. + +## Generation Pipeline (Detailed) + +### Stage 1: BSP partition +1. Split map recursively into partitions with min/max room constraints. +2. Create one room candidate per leaf. +3. Select room rectangles with padding constraints. +4. For each room slot, sample palette room templates with uniqueness guard: + - skip templates in `UsedRoomTemplateIds`, + - optionally choose procedural room even when template is available. + +### Stage 2: Random Walk connectivity overlay +1. Start from entrance room center. +2. Random walk toward unconnected room anchors, biasing to nearest disconnected clusters. +3. Carve walk paths with variable width 2-4. +4. Merge with BSP corridors for a mixed structured/organic shape. + +### Stage 3: Floor bucket assignment +1. Assign each room/corridor a target floor bucket set (theme + biome + substyle). +2. For each floor cell, pick a floor tile whose bucket set intersects: + - region target buckets + - all already-placed cardinal neighbor floor buckets. +3. If no candidate exists: + - attempt fallback via bucket adjacency policy, + - else backtrack local neighborhood and retry. + +### Stage 4: Wall candidate extraction +1. Any non-floor cell adjacent to floor (8-neighbor or cardinal, configurable) is a wall candidate. +2. Determine candidate wall bucket from nearby floor region/theme metadata. + +### Stage 5: Wall tile selection +1. Compute 8-neighbor floor mask for each wall candidate. +2. Query static lookup: `wallSet[bucket][mask]`. +3. Weighted-random choose tile from that set. +4. Validate adjacency (optional strict mode): ensure wall-wall bucket compatibility. +5. Place tile. + +### Stage 6: Validation pass +1. Floor adjacency audit: + - Every cardinal floor-floor edge must share at least one allowed bucket relation. +2. Wall adjacency audit: + - Wall neighbors satisfy wall bucket rules. +3. Connectivity audit: + - Entrance can reach boss/exit. +4. Repair pass if violations detected. + +### Stage 7: Boss allocation and clear rules +1. Compute boss count by tier: + - Tier 1-5: minimum `1`. + - Tier 6+: `>=1`, with multi-boss allowed by tier scaling config. +2. Ensure at least one valid boss room/spawn exists. +3. Mark dungeon clear condition as: + - `BossesDefeatedCount >= TotalBossCount`. +4. On reload/restore: + - if `BossesRespawnOnReload == false`, defeated bosses stay defeated. + - if `true`, bosses respawn by configured behavior. + +## Determinism +- All random operations must use one seeded RNG stream with sub-streams per stage: + - `rngRooms`, `rngWalk`, `rngFloors`, `rngWalls`, `rngProps`. +- Same seed + same content snapshot must produce identical layout. +- Room template uniqueness decisions must also be seed-deterministic. + +## Performance Targets +- No DB reads in inner placement loops. +- Preload content into immutable runtime caches: + - floor bucket index + - wall mask lookup + - bucket adjacency map +- Target: <=100ms generation for standard dungeon sizes on warm cache. + +## Admin Authoring Requirements + +### New builder UX primitives +1. Bucket editor: + - create floor/wall buckets, + - define allowed-touch matrix. +2. Floor tile editor: + - assign tile to one or more floor buckets. +3. Wall tile editor: + - assign tile to one or more wall buckets, + - assign supported masks. +4. Mask visualizer: + - click neighbors to toggle bits and preview selected wall tiles. + +### Validation in UI +- Real-time warnings: + - floor tile with no buckets, + - wall tile with no masks, + - bucket with empty compatibility map. + +## Suggested C# Runtime Shapes + +```csharp +public readonly record struct BucketId(int Value); + +public sealed class FloorTileDef { + public int TileId { get; init; } + public int SheetId { get; init; } + public int FrameIndex { get; init; } + public HashSet Buckets { get; init; } = new(); + public int Weight { get; init; } = 100; +} + +public sealed class WallTileDef { + public int TileId { get; init; } + public int SheetId { get; init; } + public int FrameIndex { get; init; } + public HashSet Buckets { get; init; } = new(); + public byte Mask { get; init; } + public int Weight { get; init; } = 100; +} + +public sealed class BucketAdjacency { + public Dictionary> AllowedTouches { get; init; } = new(); +} + +public sealed class WallMaskLibrary { + public Dictionary>> ByBucketMask { get; init; } = new(); +} + +public sealed class DungeonRunRules { + public bool NoDuplicateRoomTemplatePerTier { get; init; } = true; + public bool RequireAllBossesForDungeonClear { get; init; } = true; + public bool BossesRespawnOnReload { get; init; } = false; +} + +public sealed class DungeonBossState { + public int TotalBossCount { get; set; } + public int BossesDefeatedCount { get; set; } + public bool IsClearConditionMet => BossesDefeatedCount >= TotalBossCount; +} +``` + +## Rollout Plan +1. Build standalone `DungeonGeneratorVNext` behind feature flag. +2. Add offline test harness: + - run N seeds, + - report invalid adjacency/connectivity cases. +3. Integrate admin TestGen to run VNext side-by-side with current generator. +4. Switch runtime creation to VNext when validation metrics pass. +5. Keep old generators as emergency fallback for one release window. + +## Implementation Status +- [x] Runtime boss clear state now supports multi-boss semantics (`TotalBossCount`, `BossesDefeatedCount`, clear when all defeated). +- [x] Runtime empty-dungeon cleanup/persistence now uses all-bosses-defeated condition instead of first-boss-killed condition. +- [x] Added runtime flag `BossesRespawnOnReload` (default `false`) and wired respawn behavior to preserve defeated bosses when `false`. +- [x] Admin-spawned bosses now increment runtime boss target count. +- [ ] Persist `BossesRespawnOnReload` as authored dungeon metadata. +- [ ] Replace current generators with full `DungeonGeneratorVNext` (BSP + Random Walk + bucket-constrained floors/walls). +- [ ] Add VNext offline validation harness and side-by-side `/admin/dungeonbuilder/testgen` integration. + +## Acceptance Criteria +1. No invalid floor-floor bucket adjacency in validation output. +2. Corridor width always in `[2,4]`. +3. Wall masks resolve to valid tile in >=99.9% placements (rest repaired/fallbacked). +4. Deterministic output for fixed seed/content snapshot. +5. Admin can author new tilesets without changing placement logic code. +6. No duplicate room template IDs appear in a generated dungeon for the same tier-run. +7. Every generated dungeon has at least one boss. +8. Tier 6+ can generate multi-boss layouts and dungeon only clears after all are defeated. +9. Boss reload behavior is controlled by `BossesRespawnOnReload` and defaults to `false`. diff --git a/Game/Dungeon/DungeonHandler.Dungeons.cs b/Game/Dungeon/DungeonHandler.Dungeons.cs index d3921ff..05ea8ea 100644 --- a/Game/Dungeon/DungeonHandler.Dungeons.cs +++ b/Game/Dungeon/DungeonHandler.Dungeons.cs @@ -62,7 +62,7 @@ public sealed partial class DungeonHandler // Get active dungeons in player's bracket var availableDungeons = _dungeons.Values .Where(d => d.Simulation.Phase == DungeonPhase.Active && - !d.BossKilled) + !d.AllBossesDefeated) .Select(d => new { id = d.Id.ToString(), @@ -75,6 +75,8 @@ public sealed partial class DungeonHandler playerCount = d.Simulation.Players.Count, maxPlayers = 20, isJoinWindowOpen = d.IsJoinWindowOpen, + totalBosses = d.TotalBossCount, + defeatedBosses = d.BossesDefeatedCount, createdAt = d.CreatedAt, secondsRemaining = d.IsJoinWindowOpen ? (int)(d.JoinWindowEnd - DateTime.UtcNow).TotalSeconds : 0 }) @@ -220,6 +222,7 @@ public sealed partial class DungeonHandler CreatorName = session.Character.Name, LayoutV2 = layoutV2 // Store V2 layout for visual tile data }; + instance.InitializeBossState(simulation.Mobs.Values.Count(m => m.Type == MobType.Boss)); _dungeons[dungeonId] = instance; _log.LogInformation("Player {Name} (Level {Level}) created dungeon {Id} (tier {Tier}, bracket {Min}-{Max})", @@ -268,7 +271,7 @@ public sealed partial class DungeonHandler } // Check if boss killed - if (instance.BossKilled) + if (instance.AllBossesDefeated) { await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "dungeon_cleared" }, ct); return; @@ -540,6 +543,7 @@ public sealed partial class DungeonHandler IsPersisted = false, LastPlayerActivity = DateTime.UtcNow }; + instance.InitializeBossState(simulation.Mobs.Values.Count(m => m.Type == MobType.Boss), persisted.BossKilled); _log.LogInformation("Restored dungeon {Id} from persistence with fresh mobs", persisted.Id); return instance; @@ -557,6 +561,15 @@ public sealed partial class DungeonHandler /// private void RespawnAllMobs(DungeonInstance instance) { + var defeatedBossMobIds = !instance.BossesRespawnOnReload + ? instance.GetDefeatedBossMobIdsSnapshot() + : new HashSet(); + + if (instance.BossesRespawnOnReload) + { + instance.ResetBossProgress(); + } + // Check if any existing mobs have carried player loot - don't respawn those var mobsWithLoot = instance.Simulation.Mobs.Values .Where(m => m.HasCarriedLoot) @@ -587,6 +600,15 @@ public sealed partial class DungeonHandler else { // Use the fresh mob + if (!instance.BossesRespawnOnReload && + mob.Value.Type == MobType.Boss && + defeatedBossMobIds.Contains(mob.Key)) + { + mob.Value.IsAlive = false; + mob.Value.Health = 0; + mob.Value.State = MobState.Dead; + } + instance.Simulation.Mobs.TryAdd(mob.Key, mob.Value); } } @@ -612,8 +634,8 @@ public sealed partial class DungeonHandler } } - _log.LogDebug("Respawned {MobCount} mobs in dungeon {Id} (preserved {PreservedCount} with loot)", - instance.Simulation.Mobs.Count, instance.Id, mobsWithLoot.Count); + _log.LogDebug("Respawned {MobCount} mobs in dungeon {Id} (preserved {PreservedCount} with loot, bossesRespawn={BossesRespawn})", + instance.Simulation.Mobs.Count, instance.Id, mobsWithLoot.Count, instance.BossesRespawnOnReload); } /// @@ -621,7 +643,7 @@ public sealed partial class DungeonHandler /// private async Task PersistDungeonAsync(DungeonInstance instance, CancellationToken ct) { - if (instance.IsPersisted || instance.BossKilled) return; + if (instance.IsPersisted || instance.AllBossesDefeated) return; try { @@ -653,7 +675,7 @@ public sealed partial class DungeonHandler // Update existing record existing.LastActivity = instance.LastPlayerActivity; existing.PersistedAt = DateTime.UtcNow; - existing.BossKilled = instance.BossKilled; + existing.BossKilled = instance.AllBossesDefeated; existing.MobStateJson = System.Text.Json.JsonSerializer.Serialize(mobStates); existing.ChestStateJson = System.Text.Json.JsonSerializer.Serialize(chestStates); } @@ -672,7 +694,7 @@ public sealed partial class DungeonHandler CreatedAt = instance.CreatedAt, LastActivity = instance.LastPlayerActivity, PersistedAt = DateTime.UtcNow, - BossKilled = instance.BossKilled, + BossKilled = instance.AllBossesDefeated, MobStateJson = System.Text.Json.JsonSerializer.Serialize(mobStates), ChestStateJson = System.Text.Json.JsonSerializer.Serialize(chestStates) }; diff --git a/Game/Dungeon/DungeonHandler.cs b/Game/Dungeon/DungeonHandler.cs index b852d75..69d1ba3 100644 --- a/Game/Dungeon/DungeonHandler.cs +++ b/Game/Dungeon/DungeonHandler.cs @@ -611,6 +611,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler if (dungeon.Tier == tier && dungeon.LevelBracketMin == bracketMin && // Must match bracket dungeon.Simulation.Phase == DungeonPhase.Active && + !dungeon.AllBossesDefeated && dungeon.Simulation.Players.Count < maxPlayersPerDungeon && dungeon.IsJoinWindowOpen) // Use join window instead of hardcoded time { @@ -695,6 +696,7 @@ public sealed partial class DungeonHandler : IClientMessageHandler CreatorName = session.Character.Name, LayoutV2 = layoutV2 // Store V2 layout for visual tile data }; + instance.InitializeBossState(simulation.Mobs.Values.Count(m => m.Type == MobType.Boss)); _dungeons[dungeonId] = instance; @@ -1414,8 +1416,14 @@ public sealed partial class DungeonHandler : IClientMessageHandler { if (killedMob.Type == MobType.Boss) { - instance.BossKilled = true; - _log.LogInformation("Boss killed in dungeon {Id}! Dungeon is now cleared.", dungeonId); + if (instance.RegisterBossDefeat(death.EntityId)) + { + _log.LogInformation( + "Boss defeated in dungeon {Id}: {Defeated}/{Total} bosses cleared.", + dungeonId, + instance.BossesDefeatedCount, + instance.TotalBossCount); + } } } } @@ -1564,14 +1572,14 @@ public sealed partial class DungeonHandler : IClientMessageHandler { var emptyTime = DateTime.UtcNow - instance.LastPlayerActivity; - if (!instance.BossKilled && !instance.IsPersisted && emptyTime.TotalMinutes >= 5) + if (!instance.AllBossesDefeated && !instance.IsPersisted && emptyTime.TotalMinutes >= 5) { _ = PersistDungeonAsync(instance, CancellationToken.None); _dungeons.TryRemove(dungeonId, out _); _ = TrackDungeonDestroyedAsync(dungeonId); _log.LogInformation("Dungeon {Id} persisted after 10 minutes empty", dungeonId); } - else if (instance.BossKilled && emptyTime.TotalMinutes >= 5) + else if (instance.AllBossesDefeated && emptyTime.TotalMinutes >= 5) { _dungeons.TryRemove(dungeonId, out _); _ = TrackDungeonDestroyedAsync(dungeonId); diff --git a/Game/Dungeon/DungeonHandlerAdmin.cs b/Game/Dungeon/DungeonHandlerAdmin.cs index 190c8aa..2dfb84c 100644 --- a/Game/Dungeon/DungeonHandlerAdmin.cs +++ b/Game/Dungeon/DungeonHandlerAdmin.cs @@ -1,5 +1,6 @@ using System.Collections.Concurrent; using DataServer.Data.Entities; +using DataServer.Data.Enums; namespace GameServer.Dungeon; @@ -68,7 +69,7 @@ public partial class DungeonHandler if (dungeon.IsPersisted) return (false, "Dungeon already archived."); - if (dungeon.BossKilled) + if (dungeon.AllBossesDefeated) return (false, "Boss was killed; dungeon is marked for cleanup, not archive."); await PersistDungeonAsync(dungeon, ct); @@ -93,7 +94,7 @@ public partial class DungeonHandler TotalPlayers = dungeons.Sum(d => d.Simulation.Players.Count), TotalMobsAlive = dungeons.Sum(d => d.Simulation.Mobs.Values.Count(m => m.IsAlive)), CompletedCount = dungeons.Count(d => d.Simulation.Phase == DungeonPhase.Cleared), - BossesKilled = dungeons.Count(d => d.BossKilled) + BossesKilled = dungeons.Count(d => d.AllBossesDefeated) }; } @@ -168,6 +169,10 @@ public partial class DungeonHandler dungeon.Simulation.InitializeMobAbilities(mob, mobDef, stats); dungeon.Simulation.Mobs[newMobId] = mob; + if (mob.Type == MobType.Boss) + { + dungeon.RegisterBossSpawn(newMobId); + } return mob; } diff --git a/Game/Dungeon/DungeonInstance.cs b/Game/Dungeon/DungeonInstance.cs index 08cd4d2..2c68ecd 100644 --- a/Game/Dungeon/DungeonInstance.cs +++ b/Game/Dungeon/DungeonInstance.cs @@ -30,9 +30,13 @@ public class DungeonInstance public DateTime LastPlayerActivity { get; set; } = DateTime.UtcNow; public bool IsPersisted { get; set; } = false; public bool BossKilled { get; set; } = false; + public int TotalBossCount { get; set; } = 1; + public int BossesDefeatedCount { get; set; } = 0; + public bool BossesRespawnOnReload { get; set; } = false; // Admin editing public bool HasPendingTileUpdates { get; set; } = false; + private HashSet _defeatedBossMobIds { get; } = new(); /// /// Check if a player level is within the bracket range @@ -58,4 +62,56 @@ public class DungeonInstance /// Get the bracket number (1, 2, 3, etc.) /// public int BracketNumber => (LevelBracketMin - 1) / 10 + 1; + + public bool AllBossesDefeated => TotalBossCount > 0 && BossesDefeatedCount >= TotalBossCount; + + public void InitializeBossState(int totalBossCount, bool allBossesDefeated = false) + { + TotalBossCount = Math.Max(1, totalBossCount); + BossesDefeatedCount = allBossesDefeated ? TotalBossCount : 0; + _defeatedBossMobIds.Clear(); + BossKilled = AllBossesDefeated; + } + + public void RegisterBossSpawn(int mobId) + { + if (_defeatedBossMobIds.Contains(mobId)) + return; + + TotalBossCount = Math.Max(1, TotalBossCount + 1); + BossKilled = AllBossesDefeated; + } + + public bool RegisterBossDefeat(int mobId) + { + if (_defeatedBossMobIds.Contains(mobId)) + return false; + + _defeatedBossMobIds.Add(mobId); + BossesDefeatedCount = Math.Min(TotalBossCount, BossesDefeatedCount + 1); + BossKilled = AllBossesDefeated; + return true; + } + + public HashSet GetDefeatedBossMobIdsSnapshot() + { + return new HashSet(_defeatedBossMobIds); + } + + public void SetDefeatedBossMobIds(IEnumerable mobIds) + { + _defeatedBossMobIds.Clear(); + foreach (var mobId in mobIds) + _defeatedBossMobIds.Add(mobId); + + BossesDefeatedCount = Math.Min(TotalBossCount, _defeatedBossMobIds.Count); + BossKilled = AllBossesDefeated; + } + + public void ResetBossProgress() + { + BossesDefeatedCount = 0; + _defeatedBossMobIds.Clear(); + BossKilled = false; + } }