summaryrefslogtreecommitdiff
path: root/DungeonSystem/scripts/DungeonGenerator.cs
blob: 3a44dc4a64b778bbe086b998951e540ee89e6cc2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
using Godot;
using Godot.Collections;
using System.Collections.Generic;

namespace DungeonSystem;

public partial class DungeonGenerator : Node2D
{
    [Export] public PackedScene StartRoomScene { get; set; } = null!;
    [Export] public Array<PackedScene> CombatRoomScenes { get; set; } = new();
    [Export] public PackedScene ShopRoomScene { get; set; } = null!;
    [Export] public PackedScene TreasureRoomScene { get; set; } = null!;
    [Export] public PackedScene BossRoomScene { get; set; } = null!;
    [Export] public PackedScene DoorScene { get; set; } = null!;
    [Export] public PackedScene? EnemyScene { get; set; } = GD.Load<PackedScene>("res://enemy.tscn");

    [Export] public int TargetRoomCount { get; set; } = 10;
    [Export] public int MaxAttempts { get; set; } = 100;
    [Export] public int CorridorLengthTiles { get; set; } = 6;
    [Export] public int CorridorWidthTiles { get; set; } = 3;
    [Export] public int CorridorTileSourceId { get; set; } = 0;
    [Export] public Vector2I CorridorFloorAtlasCoords { get; set; } = new Vector2I(1, 6);
    [Export] public Vector2I CorridorWallAtlasCoords { get; set; } = new Vector2I(1, 0);
    [Export] public int MinEnemiesPerCombatRoom { get; set; } = 2;
    [Export] public int MaxEnemiesPerCombatRoom { get; set; } = 4;
    [Export] public float EnemySpawnPadding { get; set; } = 24.0f;
    [Export] public float EnemySpawnMinDistance { get; set; } = 24.0f;
    [Export] public float RoomEntryInnerMargin { get; set; } = 10.0f;

    private readonly Array<Room> _placedRooms = new();
    private readonly Array<Marker2D> _openDoors = new();
    private readonly List<CorridorConnection> _corridorConnections = new();
    private readonly System.Collections.Generic.Dictionary<Room, List<Door>> _roomDoors = new();

    private TileMapLayer? _corridorTileMap;
    private float _corridorTileSize = 16.0f;
    private RoomEncounterManager? _encounterManager;

    private readonly struct CorridorConnection
    {
        public readonly Vector2 From;
        public readonly Vector2 To;
        public readonly Vector2 Direction;

        public CorridorConnection(Vector2 from, Vector2 to, Vector2 direction)
        {
            From = from;
            To = to;
            Direction = direction;
        }
    }

    public override void _Ready()
    {
        GenerateDungeon();
    }

    public void GenerateDungeon()
    {
        _placedRooms.Clear();
        _openDoors.Clear();
        _corridorConnections.Clear();
        _roomDoors.Clear();

        // 1. Instantiate Start Room
        if (StartRoomScene.Instantiate() is not Room startRoom) return;

        AddChild(startRoom);
        startRoom.GlobalPosition = Vector2.Zero;
        _SetupCorridorTileMap(startRoom);

        _placedRooms.Add(startRoom);
        _openDoors.AddRange(startRoom.GetOpenDoors());

        // 2. Main Generation Loop
        int attempts = 0;
        while (_openDoors.Count > 0 && _placedRooms.Count < TargetRoomCount && attempts < MaxAttempts)
        {
            attempts++;
            Marker2D targetDoor = _openDoors[(int)(GD.Randi() % (uint)_openDoors.Count)];
            _TryAttachRoom(targetDoor);
        }

        _BuildCorridors();

        // 3. Post-Process Doors
        SpawnDoorsAndSealUnconnected();

        // 4. Setup encounter manager
        _ConfigureEncounterManager();
    }

    private bool _TryAttachRoom(Marker2D targetDoor)
    {
        if (CombatRoomScenes.Count == 0) return false;

        PackedScene candidateScene = CombatRoomScenes[(int)(GD.Randi() % (uint)CombatRoomScenes.Count)];
        if (candidateScene.Instantiate() is not Room candidate) return false;

        AddChild(candidate);

        Vector2 targetDirection = _GetDoorDirection(targetDoor);
        if (targetDirection == Vector2.Zero)
        {
            RemoveChild(candidate);
            candidate.QueueFree();
            return false;
        }

        Array<Marker2D> candidateDoors = candidate.GetOpenDoors();
        List<Marker2D> compatibleEntryDoors = new();
        foreach (Marker2D candidateDoor in candidateDoors)
        {
            Vector2 candidateDirection = _GetDoorDirection(candidateDoor);
            if (_AreOppositeDirections(targetDirection, candidateDirection))
            {
                compatibleEntryDoors.Add(candidateDoor);
            }
        }

        if (compatibleEntryDoors.Count == 0)
        {
            RemoveChild(candidate);
            candidate.QueueFree();
            return false;
        }

        Marker2D entryDoor = compatibleEntryDoors[(int)(GD.Randi() % (uint)compatibleEntryDoors.Count)];

        float corridorGap = Mathf.Max(1, CorridorLengthTiles) * _corridorTileSize;
        Vector2 desiredEntryPosition = targetDoor.GlobalPosition + targetDirection * corridorGap;

        Room? sourceRoom = targetDoor.GetParent()?.GetParent() as Room;

        // Align candidate entry door with a corridor gap from the target door.
        Vector2 offset = desiredEntryPosition - entryDoor.GlobalPosition;
        candidate.GlobalPosition += offset;

        bool roomOverlap = CheckOverlap(candidate);
        bool corridorOverlap = CheckCorridorOverlap(targetDoor.GlobalPosition, entryDoor.GlobalPosition, targetDirection, sourceRoom);

        if (roomOverlap || corridorOverlap)
        {
            RemoveChild(candidate);
            candidate.QueueFree();
            return false;
        }

        _placedRooms.Add(candidate);

        targetDoor.SetMeta("connected", true);
        entryDoor.SetMeta("connected", true);

        _openDoors.Remove(targetDoor);
        _openDoors.AddRange(candidate.GetOpenDoors());
        _corridorConnections.Add(new CorridorConnection(targetDoor.GlobalPosition, entryDoor.GlobalPosition, targetDirection));

        return true;
    }

    private bool CheckOverlap(Room candidate)
    {
        Rect2 candidateRect = candidate.GetRoomRect().Grow(-2.0f);

        foreach (Room room in _placedRooms)
        {
            if (candidateRect.Intersects(room.GetRoomRect().Grow(-2.0f)))
            {
                return true;
            }
        }

        return false;
    }

    private bool CheckCorridorOverlap(Vector2 fromDoor, Vector2 toDoor, Vector2 axisDirection, Room? sourceRoom)
    {
        int walkWidthTiles = Mathf.Max(1, CorridorWidthTiles);
        int halfWalkTiles = walkWidthTiles / 2;
        int halfTotalTiles = halfWalkTiles + 1;

        Vector2 start = fromDoor + axisDirection * (_corridorTileSize * 0.5f);
        Vector2 end = toDoor - axisDirection * (_corridorTileSize<