/
AutoItemPlacer.cs
353 lines (332 loc) · 17.3 KB
/
AutoItemPlacer.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
using Barotrauma.Extensions;
using Barotrauma.Items.Components;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Barotrauma
{
static class AutoItemPlacer
{
public static bool OutputDebugInfo = false;
public static void SpawnItems(Identifier? startItemSet = null)
{
if (GameMain.NetworkMember != null && !GameMain.NetworkMember.IsServer) { return; }
//player has more than one sub = we must have given the start items already
bool startItemsGiven = GameMain.GameSession?.OwnedSubmarines != null && GameMain.GameSession.OwnedSubmarines.Count > 1;
if (!startItemsGiven)
{
for (int i = 0; i < Submarine.MainSubs.Length; i++)
{
var sub = Submarine.MainSubs[i];
if (sub == null || sub.Info.InitialSuppliesSpawned || sub.Info.IsManuallyOutfitted || !sub.Info.IsPlayer) { continue; }
//1st pass: items defined in the start item set, only spawned in the main sub (not drones/shuttles or other linked subs)
SpawnStartItems(sub, startItemSet);
//2nd pass: items defined using preferred containers, spawned in the main sub and all the linked subs (drones, shuttles etc)
var subs = sub.GetConnectedSubs().Where(s => s.TeamID == sub.TeamID);
CreateAndPlace(subs);
subs.ForEach(s => s.Info.InitialSuppliesSpawned = true);
sub.CheckFuel();
}
}
//spawn items in wrecks, beacon stations and pirate subs
foreach (var sub in Submarine.Loaded)
{
if (sub.Info.Type is SubmarineType.Player or SubmarineType.Outpost or SubmarineType.OutpostModule) { continue; }
if (sub.Info.InitialSuppliesSpawned) { continue; }
CreateAndPlace(sub.ToEnumerable());
sub.Info.InitialSuppliesSpawned = true;
}
if (Level.Loaded?.StartOutpost != null && Level.Loaded.Type == LevelData.LevelType.Outpost)
{
var sub = Level.Loaded.StartOutpost;
if (!sub.Info.InitialSuppliesSpawned)
{
Rand.SetSyncedSeed(ToolBox.StringToInt(sub.Info.Name));
CreateAndPlace(sub.ToEnumerable());
sub.Info.InitialSuppliesSpawned = true;
}
}
}
/// <summary>
/// Spawns loot in the specified container.
/// </summary>
/// <param name="skipItemProbability">Probability for an individual loot item to be skipped. I.e. a value of 1.0 means nothing spawns, 0.5 means there's about 50% of the normal amount of loot.</param>
public static void RegenerateLoot(Submarine sub, ItemContainer regeneratedContainer, float skipItemProbability = 0.0f)
{
CreateAndPlace(sub.ToEnumerable(), regeneratedContainer: regeneratedContainer, skipItemProbability);
}
public static Identifier DefaultStartItemSet = new Identifier("normal");
/// <summary>
/// Spawns the items defined in the start item set in the specified sub.
/// </summary>
private static void SpawnStartItems(Submarine sub, Identifier? startItemSet)
{
Identifier setIdentifier = startItemSet ?? DefaultStartItemSet;
if (!StartItemSet.Sets.TryGet(setIdentifier, out StartItemSet itemSet))
{
DebugConsole.AddWarning($"Couldn't find a start item set matching the identifier \"{setIdentifier}\"!");
if (!StartItemSet.Sets.TryGet(DefaultStartItemSet, out StartItemSet defaultSet))
{
DebugConsole.ThrowError($"Couldn't find the default start item set \"{DefaultStartItemSet}\"!");
return;
}
itemSet = defaultSet;
}
WayPoint wp = WayPoint.GetRandom(SpawnType.Cargo, null, sub);
ISpatialEntity initialSpawnPos;
if (wp?.CurrentHull == null)
{
var spawnHull = Hull.HullList.Where(h => h.Submarine == sub && !h.IsWetRoom).GetRandomUnsynced();
if (spawnHull == null)
{
DebugConsole.AddWarning($"Failed to spawn start items in the sub. No cargo waypoint or dry hulls found to spawn the items in.");
return;
}
initialSpawnPos = spawnHull;
}
else
{
initialSpawnPos = wp;
}
var newItems = new List<Item>();
foreach (var startItem in itemSet.Items)
{
if (!ItemPrefab.Prefabs.TryGet(startItem.Item, out ItemPrefab itemPrefab))
{
DebugConsole.AddWarning($"Cannot find a start item with with the identifier \"{startItem.Item}\"");
continue;
}
if (startItem.MultiPlayerOnly && GameMain.GameSession?.GameMode is { IsSinglePlayer: true }) { continue; }
for (int i = 0; i < startItem.Amount; i++)
{
var item = new Item(itemPrefab, initialSpawnPos.Position, sub, callOnItemLoaded: false);
// Is this necessary?
foreach (WifiComponent wifiComponent in item.GetComponents<WifiComponent>())
{
wifiComponent.TeamID = sub.TeamID;
}
newItems.Add(item);
}
}
var cargoContainers = new List<ItemContainer>();
foreach (var item in newItems)
{
#if SERVER
Entity.Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(item));
#endif
foreach (ItemComponent ic in item.Components)
{
ic.OnItemLoaded();
}
var container = sub.FindContainerFor(item, onlyPrimary: true);
if (container == null)
{
var cargoContainer = CargoManager.GetOrCreateCargoContainerFor(item.Prefab, initialSpawnPos, ref cargoContainers);
container = cargoContainer?.Item;
}
container?.OwnInventory.TryPutItem(item, user: null);
}
}
private static void CreateAndPlace(IEnumerable<Submarine> subs, ItemContainer regeneratedContainer = null, float skipItemProbability = 0.0f)
{
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
{
DebugConsole.ThrowError("Clients are not allowed to use AutoItemPlacer.\n" + Environment.StackTrace.CleanupStackTrace());
return;
}
List<Item> itemsToSpawn = new List<Item>(100);
int itemCountApprox = MapEntityPrefab.List.Count() / 3;
var containers = new List<ItemContainer>(70 + 30 * subs.Count());
var prefabsItemsCanSpawnIn = new List<ItemPrefab>(itemCountApprox / 3);
var singlePrefabs = new List<ItemPrefab>(itemCountApprox);
var removals = new List<ItemPrefab>();
// generate loot only for a specific container if defined
if (regeneratedContainer != null)
{
containers.Add(regeneratedContainer);
}
else
{
foreach (Item item in Item.ItemList)
{
if (!subs.Contains(item.Submarine)) { continue; }
if (item.GetRootInventoryOwner() is Character) { continue; }
if (item.NonInteractable) { continue; }
containers.AddRange(item.GetComponents<ItemContainer>());
}
containers.Shuffle(Rand.RandSync.ServerAndClient);
}
var itemPrefabs = ItemPrefab.Prefabs.OrderBy(p => p.UintIdentifier);
foreach (ItemPrefab ip in itemPrefabs)
{
if (ip.PreferredContainers.None()) { continue; }
if (ip.ConfigElement.Elements().Any(e => string.Equals(e.Name.ToString(), typeof(ItemContainer).Name.ToString(), StringComparison.OrdinalIgnoreCase)) && itemPrefabs.Any(ip2 => CanSpawnIn(ip2, ip)))
{
prefabsItemsCanSpawnIn.Add(ip);
}
else
{
singlePrefabs.Add(ip);
}
}
bool CanSpawnIn(ItemPrefab item, ItemPrefab container)
{
foreach (var preferredContainer in item.PreferredContainers)
{
if (ItemPrefab.IsContainerPreferred(preferredContainer.Primary, container.Identifier.ToEnumerable().Union(container.Tags))) { return true; }
}
return false;
}
var validContainers = new Dictionary<ItemContainer, PreferredContainer>();
prefabsItemsCanSpawnIn.Shuffle(Rand.RandSync.ServerAndClient);
// Spawn items that other items can spawn in first so we can fill them up with items if needed (oxygen tanks inside the spawned diving masks, etc)
for (int i = 0; i < prefabsItemsCanSpawnIn.Count; i++)
{
var itemPrefab = prefabsItemsCanSpawnIn[i];
if (itemPrefab == null) { continue; }
SpawnItems(itemPrefab);
}
// Spawn items that nothing can spawn in last
singlePrefabs.Shuffle(Rand.RandSync.ServerAndClient);
singlePrefabs.ForEach(i => SpawnItems(i));
if (OutputDebugInfo)
{
var subNames = subs.Select(s => s.Info.Name).ToList();
DebugConsole.NewMessage($"Automatically placed items in { string.Join(", ", subNames) }:");
foreach (string itemName in itemsToSpawn.Select(it => it.Name).Distinct())
{
DebugConsole.NewMessage(" - " + itemName + " x" + itemsToSpawn.Count(it => it.Name == itemName));
}
}
if (GameMain.GameSession?.Level != null &&
GameMain.GameSession.Level.Type == LevelData.LevelType.Outpost &&
GameMain.GameSession.StartLocation?.TakenItems != null)
{
foreach (Location.TakenItem takenItem in GameMain.GameSession.StartLocation.TakenItems)
{
var matchingItem = itemsToSpawn.Find(it => takenItem.Matches(it));
if (matchingItem == null) { continue; }
if (OutputDebugInfo)
{
DebugConsole.NewMessage($"Removing the stolen item: {matchingItem.Prefab.Identifier} ({matchingItem.ID})");
}
var containedItems = itemsToSpawn.FindAll(it => it.ParentInventory?.Owner == matchingItem);
matchingItem.Remove();
itemsToSpawn.Remove(matchingItem);
foreach (Item containedItem in containedItems)
{
containedItem.Remove();
itemsToSpawn.Remove(containedItem);
}
}
}
foreach (Item item in itemsToSpawn)
{
#if SERVER
Entity.Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(item));
#endif
foreach (ItemComponent ic in item.Components)
{
ic.OnItemLoaded();
}
}
void SpawnItems(ItemPrefab itemPrefab, float skipItemProbability = 0.0f)
{
if (Rand.Range(0.0f, 1.0f, Rand.RandSync.ServerAndClient) < skipItemProbability) { return; }
if (itemPrefab == null)
{
string errorMsg = "Error in AutoItemPlacer.SpawnItems - itemPrefab was null.\n" + Environment.StackTrace.CleanupStackTrace();
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("AutoItemPlacer.SpawnItems:ItemNull", GameAnalyticsManager.ErrorSeverity.Error, errorMsg);
return;
}
bool isCampaign = GameMain.GameSession?.GameMode is CampaignMode;
float levelDifficulty = Level.Loaded?.Difficulty ?? 0.0f;
foreach (PreferredContainer preferredContainer in itemPrefab.PreferredContainers)
{
if (preferredContainer.CampaignOnly && !isCampaign) { continue; }
if (preferredContainer.NotCampaign && isCampaign) { continue; }
if (levelDifficulty < preferredContainer.MinLevelDifficulty || levelDifficulty > preferredContainer.MaxLevelDifficulty) { continue; }
if (preferredContainer.SpawnProbability <= 0.0f || preferredContainer.MaxAmount <= 0 && preferredContainer.Amount <= 0) { continue; }
validContainers = GetValidContainers(preferredContainer, containers, validContainers, primary: true);
if (validContainers.None())
{
validContainers = GetValidContainers(preferredContainer, containers, validContainers, primary: false);
}
foreach (var validContainer in validContainers)
{
var newItems = CreateItems(itemPrefab, containers, validContainer);
if (newItems.Any())
{
itemsToSpawn.AddRange(newItems);
}
}
}
}
}
private static Dictionary<ItemContainer, PreferredContainer> GetValidContainers(PreferredContainer preferredContainer, IEnumerable<ItemContainer> allContainers, Dictionary<ItemContainer, PreferredContainer> validContainers, bool primary)
{
validContainers.Clear();
foreach (ItemContainer container in allContainers)
{
if (!container.AutoFill) { continue; }
if (primary)
{
if (!ItemPrefab.IsContainerPreferred(preferredContainer.Primary, container)) { continue; }
}
else
{
if (!ItemPrefab.IsContainerPreferred(preferredContainer.Secondary, container)) { continue; }
}
if (!validContainers.ContainsKey(container))
{
validContainers.Add(container, preferredContainer);
}
}
return validContainers;
}
private static List<Item> CreateItems(ItemPrefab itemPrefab, List<ItemContainer> containers, KeyValuePair<ItemContainer, PreferredContainer> validContainer)
{
List<Item> newItems = new List<Item>();
if (Rand.Value(Rand.RandSync.ServerAndClient) > validContainer.Value.SpawnProbability) { return newItems; }
// Don't add dangerously reactive materials in thalamus wrecks
if (validContainer.Key.Item.Submarine.WreckAI != null && itemPrefab.Tags.Contains("explodesinwater"))
{
return newItems;
}
int amount = validContainer.Value.Amount;
if (amount == 0)
{
amount = Rand.Range(validContainer.Value.MinAmount, validContainer.Value.MaxAmount + 1, Rand.RandSync.ServerAndClient);
}
for (int i = 0; i < amount; i++)
{
if (validContainer.Key.Inventory.IsFull(takeStacksIntoAccount: true))
{
containers.Remove(validContainer.Key);
break;
}
var existingItem = validContainer.Key.Inventory.AllItems.FirstOrDefault(it => it.Prefab == itemPrefab);
int quality = existingItem?.Quality ?? Quality.GetSpawnedItemQuality(validContainer.Key.Item.Submarine, Level.Loaded, Rand.RandSync.ServerAndClient);
if (!validContainer.Key.Inventory.CanBePut(itemPrefab, quality: quality)) { break; }
var item = new Item(itemPrefab, validContainer.Key.Item.Position, validContainer.Key.Item.Submarine, callOnItemLoaded: false)
{
SpawnedInCurrentOutpost = validContainer.Key.Item.SpawnedInCurrentOutpost,
AllowStealing = validContainer.Key.Item.AllowStealing || validContainer.Key.Item.Prefab.AllowStealingContainedItems,
Quality = quality,
OriginalModuleIndex = validContainer.Key.Item.OriginalModuleIndex,
OriginalContainerIndex =
Item.ItemList.Where(it => it.Submarine == validContainer.Key.Item.Submarine && it.OriginalModuleIndex == validContainer.Key.Item.OriginalModuleIndex).ToList().IndexOf(validContainer.Key.Item)
};
foreach (WifiComponent wifiComponent in item.GetComponents<WifiComponent>())
{
wifiComponent.TeamID = validContainer.Key.Item.Submarine.TeamID;
}
newItems.Add(item);
validContainer.Key.Inventory.TryPutItem(item, null, createNetworkEvent: false);
containers.AddRange(item.GetComponents<ItemContainer>());
}
return newItems;
}
}
}