-
Notifications
You must be signed in to change notification settings - Fork 394
/
Map.cs
1746 lines (1542 loc) · 77.5 KB
/
Map.cs
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Barotrauma.Extensions;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Voronoi2;
namespace Barotrauma
{
partial class Map
{
public bool AllowDebugTeleport;
private readonly MapGenerationParams generationParams;
private Location furthestDiscoveredLocation;
public int Width { get; private set; }
public int Height { get; private set; }
public Action<Location, LocationConnection> OnLocationSelected;
public Action<LocationConnection, IEnumerable<Mission>> OnMissionsSelected;
public readonly struct LocationChangeInfo
{
public readonly Location PrevLocation;
public readonly Location NewLocation;
public LocationChangeInfo(Location prevLocation, Location newLocation)
{
PrevLocation = prevLocation;
NewLocation = newLocation;
}
}
/// <summary>
/// From -> To
/// </summary>
public readonly NamedEvent<LocationChangeInfo> OnLocationChanged = new NamedEvent<LocationChangeInfo>();
private List<Location> endLocations = new List<Location>();
public IReadOnlyList<Location> EndLocations { get { return endLocations; } }
public Location StartLocation { get; private set; }
public Location CurrentLocation { get; private set; }
public int CurrentLocationIndex
{
get { return Locations.IndexOf(CurrentLocation); }
}
public Location SelectedLocation { get; private set; }
public int SelectedLocationIndex
{
get { return Locations.IndexOf(SelectedLocation); }
}
public IEnumerable<int> GetSelectedMissionIndices()
{
return SelectedConnection == null ? Enumerable.Empty<int>() : CurrentLocation.GetSelectedMissionIndices();
}
public LocationConnection SelectedConnection { get; private set; }
public string Seed { get; private set; }
public List<Location> Locations { get; private set; }
private readonly List<Location> locationsDiscovered = new List<Location>();
private readonly List<Location> locationsVisited = new List<Location>();
public List<LocationConnection> Connections { get; private set; }
public Radiation Radiation;
private bool trackedLocationDiscoveryAndVisitOrder = true;
public Map(CampaignSettings settings)
{
generationParams = MapGenerationParams.Instance;
Width = generationParams.Width;
Height = generationParams.Height;
Locations = new List<Location>();
Connections = new List<LocationConnection>();
if (generationParams.RadiationParams != null)
{
Radiation = new Radiation(this, generationParams.RadiationParams)
{
Enabled = settings.RadiationEnabled
};
}
}
/// <summary>
/// Load a previously saved campaign map from XML
/// </summary>
private Map(CampaignMode campaign, XElement element) : this(campaign.Settings)
{
Seed = element.GetAttributeString("seed", "a");
Rand.SetSyncedSeed(ToolBox.StringToInt(Seed));
Width = element.GetAttributeInt("width", Width);
Height = element.GetAttributeInt("height", Height);
bool lairsFound = false;
foreach (var subElement in element.Elements())
{
switch (subElement.Name.ToString().ToLowerInvariant())
{
case "location":
int i = subElement.GetAttributeInt("i", 0);
while (Locations.Count <= i)
{
Locations.Add(null);
}
lairsFound |= subElement.GetAttributeString("type", "").Equals("lair", StringComparison.OrdinalIgnoreCase);
Locations[i] = new Location(campaign, subElement);
break;
case "radiation":
Radiation = new Radiation(this, generationParams.RadiationParams, subElement)
{
Enabled = campaign.Settings.RadiationEnabled
};
break;
}
}
List<XElement> connectionElements = new List<XElement>();
foreach (var subElement in element.Elements())
{
switch (subElement.Name.ToString().ToLowerInvariant())
{
case "connection":
Point locationIndices = subElement.GetAttributePoint("locations", new Point(0, 1));
if (locationIndices.X == locationIndices.Y) { continue; }
var connection = new LocationConnection(Locations[locationIndices.X], Locations[locationIndices.Y])
{
Passed = subElement.GetAttributeBool("passed", false),
Locked = subElement.GetAttributeBool("locked", false),
Difficulty = subElement.GetAttributeFloat("difficulty", 0.0f)
};
Locations[locationIndices.X].Connections.Add(connection);
Locations[locationIndices.Y].Connections.Add(connection);
string biomeId = subElement.GetAttributeString("biome", "");
connection.Biome =
Biome.Prefabs.FirstOrDefault(b => b.Identifier == biomeId) ??
Biome.Prefabs.FirstOrDefault(b => !b.OldIdentifier.IsEmpty && b.OldIdentifier == biomeId) ??
Biome.Prefabs.First();
connection.Difficulty = MathHelper.Clamp(connection.Difficulty, connection.Biome.MinDifficulty, connection.Biome.AdjustedMaxDifficulty);
connection.LevelData = new LevelData(subElement.Element("Level"), connection.Difficulty);
Connections.Add(connection);
connectionElements.Add(subElement);
break;
}
}
//backwards compatibility: location biomes weren't saved (or used for anything) previously,
//assign them if they haven't been assigned
Random rand = new MTRandom(ToolBox.StringToInt(Seed));
if (Locations.First().Biome == null)
{
AssignBiomes(rand);
}
int startLocationindex = element.GetAttributeInt("startlocation", -1);
if (startLocationindex >= 0 && startLocationindex < Locations.Count)
{
StartLocation = Locations[startLocationindex];
}
else
{
DebugConsole.AddWarning($"Error while loading the map. Start location index out of bounds (index: {startLocationindex}, location count: {Locations.Count}).");
foreach (Location location in Locations)
{
if (!location.Type.HasOutpost) { continue; }
if (StartLocation == null || location.MapPosition.X < StartLocation.MapPosition.X)
{
StartLocation = location;
}
}
}
if (element.GetAttribute("endlocation") != null)
{
//backwards compatibility
int endLocationIndex = element.GetAttributeInt("endlocation", -1);
if (endLocationIndex >= 0 && endLocationIndex < Locations.Count)
{
endLocations.Add(Locations[endLocationIndex]);
}
else
{
DebugConsole.AddWarning($"Error while loading the map. End location index out of bounds (index: {endLocationIndex}, location count: {Locations.Count}).");
}
}
else
{
int[] endLocationindices = element.GetAttributeIntArray("endlocations", Array.Empty<int>());
foreach (int endLocationIndex in endLocationindices)
{
if (endLocationIndex >= 0 && endLocationIndex < Locations.Count)
{
endLocations.Add(Locations[endLocationIndex]);
}
else
{
DebugConsole.AddWarning($"Error while loading the map. End location index out of bounds (index: {endLocationIndex}, location count: {Locations.Count}).");
}
}
}
if (!endLocations.Any())
{
DebugConsole.AddWarning($"Error while loading the map. No end location(s) found. Choosing the rightmost location as the end location...");
Location endLocation = null;
foreach (Location location in Locations)
{
if (endLocation == null || location.MapPosition.X > endLocation.MapPosition.X)
{
endLocation = location;
}
}
endLocations.Add(endLocation);
}
System.Diagnostics.Debug.Assert(endLocations.First().Biome != null, "End location biome was null.");
System.Diagnostics.Debug.Assert(endLocations.First().Biome.IsEndBiome, "The biome of the end location isn't the end biome.");
//backwards compatibility (or support for loading maps created with mods that modify the end biome setup):
//if there's too few end locations, create more
int missingOutpostCount = endLocations.First().Biome.EndBiomeLocationCount - endLocations.Count;
Location firstEndLocation = EndLocations[0];
for (int i = 0; i < missingOutpostCount; i++)
{
Vector2 mapPos = new Vector2(
MathHelper.Lerp(firstEndLocation.MapPosition.X, Width, MathHelper.Lerp(0.2f, 0.8f, i / (float)missingOutpostCount)),
Height * MathHelper.Lerp(0.2f, 1.0f, (float)rand.NextDouble()));
var newEndLocation = new Location(mapPos, generationParams.DifficultyZones, rand, forceLocationType: firstEndLocation.Type, existingLocations: Locations)
{
Biome = endLocations.First().Biome
};
newEndLocation.LevelData = new LevelData(newEndLocation, this, difficulty: 100.0f);
Locations.Add(newEndLocation);
endLocations.Add(newEndLocation);
}
//backwards compatibility: if the map contained the now-removed lairs and has no hunting grounds, create some hunting grounds
if (lairsFound && !Connections.Any(c => c.LevelData.HasHuntingGrounds))
{
for (int i = 0; i < Connections.Count; i++)
{
Connections[i].LevelData.HasHuntingGrounds = Rand.Range(0.0f, 1.0f) < Connections[i].Difficulty / 100.0f * LevelData.MaxHuntingGroundsProbability;
connectionElements[i].SetAttributeValue("hashuntinggrounds", true);
}
}
foreach (var endLocation in EndLocations)
{
if (endLocation.Type?.ForceLocationName is { IsEmpty: false })
{
endLocation.ForceName(endLocation.Type.ForceLocationName);
}
}
AssignEndLocationLevelData();
//backwards compatibility: if locations go out of bounds (map saved with different generation parameters before width/height were included in the xml)
float maxX = Locations.Select(l => l.MapPosition.X).Max();
if (maxX > Width) { Width = (int)(maxX + 10); }
float maxY = Locations.Select(l => l.MapPosition.Y).Max();
if (maxY > Height) { Height = (int)(maxY + 10); }
InitProjectSpecific();
}
/// <summary>
/// Generate a new campaign map from the seed
/// </summary>
public Map(CampaignMode campaign, string seed) : this(campaign.Settings)
{
Seed = seed;
Rand.SetSyncedSeed(ToolBox.StringToInt(Seed));
Generate(campaign);
if (Locations.Count == 0)
{
throw new Exception($"Generating a campaign map failed (no locations created). Width: {Width}, height: {Height}");
}
FindStartLocation(l => l.Type.Identifier == "outpost");
//if no outpost was found (using a mod that replaces the outpost location type?), find any type of outpost
if (CurrentLocation == null)
{
FindStartLocation(l => l.Type.HasOutpost && l.Type.OutpostTeam == CharacterTeamType.FriendlyNPC);
}
void FindStartLocation(Func<Location, bool> predicate)
{
foreach (Location location in Locations)
{
if (!predicate(location)) { continue; }
if (CurrentLocation == null || location.MapPosition.X < CurrentLocation.MapPosition.X)
{
CurrentLocation = StartLocation = furthestDiscoveredLocation = location;
}
}
}
StartLocation.SecondaryFaction = null;
var startOutpostFaction = campaign?.Factions.FirstOrDefault(f => f.Prefab.StartOutpost);
if (startOutpostFaction != null)
{
StartLocation.Faction = startOutpostFaction;
}
foreach (var connection in StartLocation.Connections)
{
//force locations adjacent to the start location to have an outpost
//non-inhabited locations seem to be confusing to new players, particularly
//on the first round/mission when they still don't know how transitions between levels work
var otherLocation = connection.OtherLocation(StartLocation);
if (!otherLocation.HasOutpost())
{
if (LocationType.Prefabs.TryGet("outpost".ToIdentifier(), out LocationType outpostLocationType))
{
otherLocation.ChangeType(campaign, outpostLocationType);
}
}
if (otherLocation.HasOutpost() &&
otherLocation.Type.OutpostTeam == CharacterTeamType.FriendlyNPC &&
otherLocation.Type.Faction.IsEmpty)
{
otherLocation.Faction = startOutpostFaction;
}
}
System.Diagnostics.Debug.Assert(StartLocation != null, "Start location not assigned after level generation.");
int loops = campaign.CampaignMetadata.GetInt("campaign.endings".ToIdentifier(), 0);
if (loops == 0 && (campaign.Settings.WorldHostility == WorldHostilityOption.Low || campaign.Settings.WorldHostility == WorldHostilityOption.Medium))
{
if (StartLocation != null)
{
StartLocation.LevelData = new LevelData(StartLocation, this, 0);
}
//ensure all paths from the starting location have 0 difficulty to make the 1st campaign round very easy
foreach (var locationConnection in StartLocation.Connections)
{
if (locationConnection.Difficulty > 0.0f)
{
locationConnection.Difficulty = 0.0f;
locationConnection.LevelData = new LevelData(locationConnection);
}
}
}
if (campaign.IsSinglePlayer && campaign.Settings.TutorialEnabled && LocationType.Prefabs.TryGet("tutorialoutpost", out var tutorialOutpost))
{
CurrentLocation.ChangeType(campaign, tutorialOutpost);
}
Discover(CurrentLocation);
Visit(CurrentLocation);
CurrentLocation.CreateStores();
foreach (var location in Locations)
{
location.UnlockInitialMissions();
}
InitProjectSpecific();
}
partial void InitProjectSpecific();
#region Generation
private void Generate(CampaignMode campaign)
{
Connections.Clear();
Locations.Clear();
List<Vector2> voronoiSites = new List<Vector2>();
for (float x = 10.0f; x < Width - 10.0f; x += generationParams.VoronoiSiteInterval.X)
{
for (float y = 10.0f; y < Height - 10.0f; y += generationParams.VoronoiSiteInterval.Y)
{
voronoiSites.Add(new Vector2(
x + generationParams.VoronoiSiteVariance.X * Rand.Range(-0.5f, 0.5f, Rand.RandSync.ServerAndClient),
y + generationParams.VoronoiSiteVariance.Y * Rand.Range(-0.5f, 0.5f, Rand.RandSync.ServerAndClient)));
}
}
Voronoi voronoi = new Voronoi(0.5f);
List<GraphEdge> edges = voronoi.MakeVoronoiGraph(voronoiSites, Width, Height);
Vector2 margin = new Vector2(
Math.Min(10, Width * 0.1f),
Math.Min(10, Height * 0.2f));
float startX = margin.X, endX = Width - margin.X;
float startY = margin.Y, endY = Height - margin.Y;
if (!edges.Any())
{
throw new Exception($"Generating a campaign map failed (no edges in the voronoi graph). Width: {Width}, height: {Height}, margin: {margin}");
}
voronoiSites.Clear();
Dictionary<int, List<Location>> locationsPerZone = new Dictionary<int, List<Location>>();
bool possibleStartOutpostCreated = false;
foreach (GraphEdge edge in edges)
{
if (edge.Point1 == edge.Point2) { continue; }
if (edge.Point1.X < margin.X || edge.Point1.X > Width - margin.X || edge.Point1.Y < startY || edge.Point1.Y > endY)
{
continue;
}
if (edge.Point2.X < margin.X || edge.Point2.X > Width - margin.X || edge.Point2.Y < startY || edge.Point2.Y > endY)
{
continue;
}
Location[] newLocations = new Location[2];
newLocations[0] = Locations.Find(l => l.MapPosition == edge.Point1 || l.MapPosition == edge.Point2);
newLocations[1] = Locations.Find(l => l != newLocations[0] && (l.MapPosition == edge.Point1 || l.MapPosition == edge.Point2));
for (int i = 0; i < 2; i++)
{
if (newLocations[i] != null) { continue; }
Vector2[] points = new Vector2[] { edge.Point1, edge.Point2 };
int positionIndex = Rand.Int(1, Rand.RandSync.ServerAndClient);
Vector2 position = points[positionIndex];
if (newLocations[1 - i] != null && newLocations[1 - i].MapPosition == position) { position = points[1 - positionIndex]; }
int zone = GetZoneIndex(position.X);
if (!locationsPerZone.ContainsKey(zone))
{
locationsPerZone[zone] = new List<Location>();
}
LocationType forceLocationType = null;
if (!possibleStartOutpostCreated)
{
float zoneWidth = Width / generationParams.DifficultyZones;
float threshold = zoneWidth * 0.1f;
if (position.X < threshold)
{
LocationType.Prefabs.TryGet("outpost", out forceLocationType);
possibleStartOutpostCreated = true;
}
}
if (forceLocationType == null)
{
foreach (LocationType locationType in LocationType.Prefabs.OrderBy(lt => lt.Identifier))
{
if (locationType.MinCountPerZone.TryGetValue(zone, out int minCount) && locationsPerZone[zone].Count(l => l.Type == locationType) < minCount)
{
forceLocationType = locationType;
break;
}
}
}
newLocations[i] = Location.CreateRandom(position, zone, Rand.GetRNG(Rand.RandSync.ServerAndClient),
requireOutpost: false, forceLocationType: forceLocationType, existingLocations: Locations);
locationsPerZone[zone].Add(newLocations[i]);
Locations.Add(newLocations[i]);
}
var newConnection = new LocationConnection(newLocations[0], newLocations[1]);
Connections.Add(newConnection);
}
//remove connections that are too short
float minConnectionDistanceSqr = generationParams.MinConnectionDistance * generationParams.MinConnectionDistance;
for (int i = Connections.Count - 1; i >= 0; i--)
{
LocationConnection connection = Connections[i];
if (Vector2.DistanceSquared(connection.Locations[0].MapPosition, connection.Locations[1].MapPosition) > minConnectionDistanceSqr)
{
continue;
}
//locations.Remove(connection.Locations[0]);
Connections.Remove(connection);
foreach (LocationConnection connection2 in Connections)
{
if (connection2.Locations[0] == connection.Locations[0]) { connection2.Locations[0] = connection.Locations[1]; }
if (connection2.Locations[1] == connection.Locations[0]) { connection2.Locations[1] = connection.Locations[1]; }
}
}
foreach (LocationConnection connection in Connections)
{
connection.Locations[0].Connections.Add(connection);
connection.Locations[1].Connections.Add(connection);
}
//remove locations that are too close to each other
float minLocationDistanceSqr = generationParams.MinLocationDistance * generationParams.MinLocationDistance;
for (int i = Locations.Count - 1; i >= 0; i--)
{
for (int j = Locations.Count - 1; j > i; j--)
{
float dist = Vector2.DistanceSquared(Locations[i].MapPosition, Locations[j].MapPosition);
if (dist > minLocationDistanceSqr)
{
continue;
}
//move connections from Locations[j] to Locations[i]
foreach (LocationConnection connection in Locations[j].Connections)
{
if (connection.Locations[0] == Locations[j])
{
connection.Locations[0] = Locations[i];
}
else
{
connection.Locations[1] = Locations[i];
}
if (connection.Locations[0] != connection.Locations[1])
{
Locations[i].Connections.Add(connection);
}
else
{
Connections.Remove(connection);
}
}
Locations[i].Connections.RemoveAll(c => c.OtherLocation(Locations[i]) == Locations[j]);
Locations.RemoveAt(j);
}
}
//make sure the connections are in the same order on the locations and the Connections list
//otherwise their order will change when loading the game (as they're added to the locations in the same order they're loaded)
foreach (var location in Locations)
{
location.Connections.Sort((c1, c2) => Connections.IndexOf(c1).CompareTo(Connections.IndexOf(c2)));
}
for (int i = Connections.Count - 1; i >= 0; i--)
{
i = Math.Min(i, Connections.Count - 1);
LocationConnection connection = Connections[i];
for (int n = Math.Min(i - 1, Connections.Count - 1); n >= 0; n--)
{
if (connection.Locations.Contains(Connections[n].Locations[0])
&& connection.Locations.Contains(Connections[n].Locations[1]))
{
Connections.RemoveAt(n);
}
}
}
List<LocationConnection>[] connectionsBetweenZones = new List<LocationConnection>[generationParams.DifficultyZones];
for (int i = 0; i < generationParams.DifficultyZones; i++)
{
connectionsBetweenZones[i] = new List<LocationConnection>();
}
var shuffledConnections = Connections.ToList();
shuffledConnections.Shuffle(Rand.RandSync.ServerAndClient);
foreach (var connection in shuffledConnections)
{
int zone1 = GetZoneIndex(connection.Locations[0].MapPosition.X);
int zone2 = GetZoneIndex(connection.Locations[1].MapPosition.X);
if (zone1 == zone2) { continue; }
if (zone1 > zone2)
{
(zone1, zone2) = (zone2, zone1);
}
if (generationParams.GateCount[zone1] == 0) { continue; }
if (!connectionsBetweenZones[zone1].Any())
{
connectionsBetweenZones[zone1].Add(connection);
}
else if (generationParams.GateCount[zone1] == 1)
{
//if there's only one connection, place it at the center of the map
if (Math.Abs(connection.CenterPos.Y - Height / 2) < Math.Abs(connectionsBetweenZones[zone1].First().CenterPos.Y - Height / 2))
{
connectionsBetweenZones[zone1].Clear();
connectionsBetweenZones[zone1].Add(connection);
}
}
else if (connectionsBetweenZones[zone1].Count() < generationParams.GateCount[zone1] &&
connectionsBetweenZones[zone1].None(c => c.Locations.Contains(connection.Locations[0]) || c.Locations.Contains(connection.Locations[1])))
{
connectionsBetweenZones[zone1].Add(connection);
}
}
var gateFactions = campaign.Factions.Where(f => f.Prefab.ControlledOutpostPercentage > 0).OrderBy(f => f.Prefab.Identifier).ToList();
for (int i = Connections.Count - 1; i >= 0; i--)
{
int zone1 = GetZoneIndex(Connections[i].Locations[0].MapPosition.X);
int zone2 = GetZoneIndex(Connections[i].Locations[1].MapPosition.X);
if (zone1 == zone2) { continue; }
if (zone1 == generationParams.DifficultyZones || zone2 == generationParams.DifficultyZones) { continue; }
int leftZone = Math.Min(zone1, zone2);
if (generationParams.GateCount[leftZone] == 0) { continue; }
if (!connectionsBetweenZones[leftZone].Contains(Connections[i]))
{
Connections.RemoveAt(i);
}
else
{
var leftMostLocation =
Connections[i].Locations[0].MapPosition.X < Connections[i].Locations[1].MapPosition.X ?
Connections[i].Locations[0] :
Connections[i].Locations[1];
if (!AllowAsBiomeGate(leftMostLocation.Type))
{
leftMostLocation.ChangeType(
campaign,
LocationType.Prefabs.OrderBy(lt => lt.Identifier).First(lt => AllowAsBiomeGate(lt)),
createStores: false);
}
static bool AllowAsBiomeGate(LocationType lt)
{
//checking for "abandoned" is not strictly necessary here because it's now configured to not be allowed as a biome gate
//but might be better to keep it for backwards compatibility (previously we relied only on that check)
return lt.HasOutpost && lt.Identifier != "abandoned" && lt.AllowAsBiomeGate;
}
leftMostLocation.IsGateBetweenBiomes = true;
Connections[i].Locked = true;
if (leftMostLocation.Type.HasOutpost && campaign != null && gateFactions.Any())
{
leftMostLocation.Faction = gateFactions[connectionsBetweenZones[leftZone].IndexOf(Connections[i]) % gateFactions.Count];
}
}
}
foreach (Location location in Locations)
{
for (int i = location.Connections.Count - 1; i >= 0; i--)
{
if (!Connections.Contains(location.Connections[i]))
{
location.Connections.RemoveAt(i);
}
}
}
//make sure the location at the right side of the gate between biomes isn't a dead-end
//those may sometimes generate if all the connections of the right-side location lead to the previous biome
//(i.e. a situation where the adjacent locations happen to be at the left side of the border of the biomes, see see Regalis11/Barotrauma#10047)
for (int i = 0; i < Connections.Count; i++)
{
var connection = Connections[i];
if (!connection.Locked) { continue; }
var rightMostLocation =
connection.Locations[0].MapPosition.X > connection.Locations[1].MapPosition.X ?
connection.Locations[0] :
connection.Locations[1];
//if there's only one connection (= the connection between biomes), create a new connection to the closest location to the right
if (rightMostLocation.Connections.Count == 1)
{
Location closestLocation = null;
float closestDist = float.PositiveInfinity;
foreach (Location otherLocation in Locations)
{
if (otherLocation == rightMostLocation || otherLocation.MapPosition.X < rightMostLocation.MapPosition.X) { continue; }
float dist = Vector2.DistanceSquared(rightMostLocation.MapPosition, otherLocation.MapPosition);
if (dist < closestDist || closestLocation == null)
{
closestLocation = otherLocation;
closestDist = dist;
}
}
var newConnection = new LocationConnection(rightMostLocation, closestLocation);
rightMostLocation.Connections.Add(newConnection);
closestLocation.Connections.Add(newConnection);
Connections.Add(newConnection);
GenerateLocationConnectionVisuals(newConnection);
}
}
//remove orphans
Locations.RemoveAll(l => !Connections.Any(c => c.Locations.Contains(l)));
AssignBiomes(new MTRandom(ToolBox.StringToInt(Seed)));
foreach (LocationConnection connection in Connections)
{
if (connection.Locations.Any(l => l.IsGateBetweenBiomes))
{
connection.Difficulty = Math.Min(connection.Locations.Min(l => l.Biome.ActualMaxDifficulty), connection.Biome.AdjustedMaxDifficulty);
}
else
{
connection.Difficulty = CalculateDifficulty(connection.CenterPos.X, connection.Biome);
}
}
foreach (Location location in Locations)
{
location.LevelData = new LevelData(location, this, CalculateDifficulty(location.MapPosition.X, location.Biome));
location.TryAssignFactionBasedOnLocationType(campaign);
if (location.Type.HasOutpost && campaign != null && location.Type.OutpostTeam == CharacterTeamType.FriendlyNPC)
{
if (location.Type.Faction.IsEmpty)
{
//no faction defined in the location type, assign a random one
location.Faction ??= campaign.GetRandomFaction(Rand.RandSync.ServerAndClient);
}
if (location.Type.SecondaryFaction.IsEmpty)
{
//no secondary faction defined in the location type, assign a random one
location.SecondaryFaction ??= campaign.GetRandomSecondaryFaction(Rand.RandSync.ServerAndClient);
}
}
location.CreateStores(force: true);
}
foreach (LocationConnection connection in Connections)
{
connection.LevelData = new LevelData(connection);
}
CreateEndLocation(campaign);
float CalculateDifficulty(float mapPosition, Biome biome)
{
float settingsFactor = campaign.Settings.LevelDifficultyMultiplier;
float minDifficulty = 0;
float maxDifficulty = 100;
float difficulty = mapPosition / Width * 100;
System.Diagnostics.Debug.Assert(biome != null);
if (biome != null)
{
minDifficulty = biome.MinDifficulty;
maxDifficulty = biome.AdjustedMaxDifficulty;
float diff = 1 - settingsFactor;
difficulty *= 1 - (1f / biome.AllowedZones.Max() * diff);
}
return MathHelper.Clamp(difficulty, minDifficulty, maxDifficulty);
}
}
partial void GenerateAllLocationConnectionVisuals();
partial void GenerateLocationConnectionVisuals(LocationConnection connection);
private int GetZoneIndex(float xPos)
{
float zoneWidth = Width / generationParams.DifficultyZones;
return MathHelper.Clamp((int)Math.Floor(xPos / zoneWidth) + 1, 1, generationParams.DifficultyZones);
}
public Biome GetBiome(Vector2 mapPos)
{
return GetBiome(mapPos.X);
}
public Biome GetBiome(float xPos)
{
float zoneWidth = Width / generationParams.DifficultyZones;
int zoneIndex = (int)Math.Floor(xPos / zoneWidth) + 1;
zoneIndex = Math.Clamp(zoneIndex, 1, generationParams.DifficultyZones - 1);
return Biome.Prefabs.FirstOrDefault(b => b.AllowedZones.Contains(zoneIndex));
}
private void AssignBiomes(Random rand)
{
var biomes = Biome.Prefabs;
float zoneWidth = Width / generationParams.DifficultyZones;
List<Biome> allowedBiomes = new List<Biome>(10);
for (int i = 0; i < generationParams.DifficultyZones; i++)
{
allowedBiomes.Clear();
allowedBiomes.AddRange(biomes.Where(b => b.AllowedZones.Contains(generationParams.DifficultyZones - i)));
float zoneX = zoneWidth * (generationParams.DifficultyZones - i);
foreach (Location location in Locations)
{
if (location.MapPosition.X < zoneX)
{
location.Biome = allowedBiomes[rand.Next() % allowedBiomes.Count];
}
}
}
foreach (LocationConnection connection in Connections)
{
if (connection.Biome != null) { continue; }
connection.Biome = connection.Locations[0].MapPosition.X > connection.Locations[1].MapPosition.X ? connection.Locations[0].Biome : connection.Locations[1].Biome;
}
System.Diagnostics.Debug.Assert(Locations.All(l => l.Biome != null));
System.Diagnostics.Debug.Assert(Connections.All(c => c.Biome != null));
}
private Location GetPreviousToEndLocation()
{
Location previousToEndLocation = null;
foreach (Location location in Locations)
{
if (!location.Biome.IsEndBiome && (previousToEndLocation == null || location.MapPosition.X > previousToEndLocation.MapPosition.X))
{
previousToEndLocation = location;
}
}
return previousToEndLocation;
}
private void ForceLocationTypeToNone(CampaignMode campaign, Location location)
{
if (LocationType.Prefabs.TryGet("none", out LocationType locationType))
{
location.ChangeType(campaign, locationType, createStores: false);
}
location.DisallowLocationTypeChanges = true;
}
private void CreateEndLocation(CampaignMode campaign)
{
float zoneWidth = Width / generationParams.DifficultyZones;
Vector2 endPos = new Vector2(Width - zoneWidth * 0.7f, Height / 2);
float closestDist = float.MaxValue;
var endLocation = Locations.First();
foreach (Location location in Locations)
{
float dist = Vector2.DistanceSquared(endPos, location.MapPosition);
if (location.Biome.IsEndBiome && dist < closestDist)
{
endLocation = location;
closestDist = dist;
}
}
var previousToEndLocation = GetPreviousToEndLocation();
if (endLocation == null || previousToEndLocation == null) { return; }
endLocations = new List<Location>() { endLocation };
if (endLocation.Biome.EndBiomeLocationCount > 1)
{
FindConnectedEndLocations(endLocation);
void FindConnectedEndLocations(Location currLocation)
{
if (endLocations.Count >= endLocation.Biome.EndBiomeLocationCount) { return; }
foreach (var connection in currLocation.Connections)
{
if (connection.Biome != endLocation.Biome) { continue; }
var otherLocation = connection.OtherLocation(currLocation);
if (otherLocation != null && !endLocations.Contains(otherLocation))
{
if (endLocations.Count >= endLocation.Biome.EndBiomeLocationCount) { return; }
endLocations.Add(otherLocation);
FindConnectedEndLocations(otherLocation);
}
}
}
}
ForceLocationTypeToNone(campaign, previousToEndLocation);
//remove all locations from the end biome except the end location
for (int i = Locations.Count - 1; i >= 0; i--)
{
if (Locations[i].Biome.IsEndBiome)
{
for (int j = Locations[i].Connections.Count - 1; j >= 0; j--)
{
if (j >= Locations[i].Connections.Count) { continue; }
var connection = Locations[i].Connections[j];
var otherLocation = connection.OtherLocation(Locations[i]);
Locations[i].Connections.RemoveAt(j);
otherLocation?.Connections.Remove(connection);
Connections.Remove(connection);
}
if (!endLocations.Contains(Locations[i]))
{
Locations.RemoveAt(i);
}
}
}
//removed all connections from the second-to-last location, need to reconnect it
if (previousToEndLocation.Connections.None())
{
Location connectTo = Locations.First();
foreach (Location location in Locations)
{
if (!location.Biome.IsEndBiome && location != previousToEndLocation && location.MapPosition.X > connectTo.MapPosition.X)
{
connectTo = location;
}
}
var newConnection = new LocationConnection(previousToEndLocation, connectTo)
{
Biome = endLocation.Biome,
Difficulty = 100.0f
};
newConnection.LevelData = new LevelData(newConnection);
Connections.Add(newConnection);
previousToEndLocation.Connections.Add(newConnection);
connectTo.Connections.Add(newConnection);
}
var endConnection = new LocationConnection(previousToEndLocation, endLocation)
{
Biome = endLocation.Biome,
Difficulty = 100.0f
};
endConnection.LevelData = new LevelData(endConnection);
Connections.Add(endConnection);
previousToEndLocation.Connections.Add(endConnection);
endLocation.Connections.Add(endConnection);
AssignEndLocationLevelData();
}
private void AssignEndLocationLevelData()
{
for (int i = 0; i < endLocations.Count; i++)
{
endLocations[i].LevelData.ReassignGenerationParams(Seed);
var outpostParams = OutpostGenerationParams.OutpostParams.FirstOrDefault(p => p.ForceToEndLocationIndex == i);
if (outpostParams != null)
{
endLocations[i].LevelData.ForceOutpostGenerationParams = outpostParams;
}
}
}
private void ExpandBiomes(List<LocationConnection> seeds)
{
List<LocationConnection> nextSeeds = new List<LocationConnection>();
foreach (LocationConnection connection in seeds)
{
foreach (Location location in connection.Locations)
{
foreach (LocationConnection otherConnection in location.Connections)
{
if (otherConnection == connection) continue;
if (otherConnection.Biome != null) continue; //already assigned
otherConnection.Biome = connection.Biome;
nextSeeds.Add(otherConnection);
}
}
}
if (nextSeeds.Count > 0)
{
ExpandBiomes(nextSeeds);
}
}
#endregion Generation
public void MoveToNextLocation()
{
if (SelectedLocation == null && Level.Loaded?.EndLocation != null)
{
//force the location at the end of the level to be selected, even if it's been deselect on the map
//(e.g. due to returning to an empty location the beginning of the level during the round)
SelectLocation(Level.Loaded.EndLocation);
}
if (SelectedConnection == null)
{
if (!endLocations.Contains(CurrentLocation))
{
DebugConsole.ThrowError("Could not move to the next location (no connection selected).\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
}
if (SelectedLocation == null)
{
if (endLocations.Contains(CurrentLocation))
{
int currentEndLocationIndex = endLocations.IndexOf(CurrentLocation);
if (currentEndLocationIndex < endLocations.Count - 1)
{
//more end locations to go, progress to the next one
SelectedLocation = endLocations[currentEndLocationIndex + 1];