-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMilitiaBehavior.cs
469 lines (420 loc) · 21.1 KB
/
MilitiaBehavior.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
using System;
using System.Collections.Generic;
using System.Linq;
using Helpers;
using TaleWorlds.CampaignSystem;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Party.PartyComponents;
using TaleWorlds.CampaignSystem.Roster;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.LinQuick;
using TaleWorlds.TwoDimension;
using static BanditMilitias.Helper;
using static BanditMilitias.Globals;
// ReSharper disable InconsistentNaming
namespace BanditMilitias
{
public class MilitiaBehavior : CampaignBehaviorBase
{
private const double SmallChance = 0.0005;
internal const float Increment = 5;
private const float EffectRadius = 100;
private const int AdjustRadius = 50;
private const int settlementFindRange = 200;
public override void RegisterEvents()
{
CampaignEvents.VillageBeingRaided.AddNonSerializedListener(this, v =>
{
if (Globals.Settings.ShowRaids
&& v.Owner?.LeaderHero == Hero.MainHero
&& v.Settlement.Party?.MapEvent is not null
&& v.Settlement.Party.MapEvent.PartiesOnSide(BattleSideEnum.Attacker)
.AnyQ(m => m.Party.IsMobile && m.Party.MobileParty.IsBM()))
{
InformationManager.DisplayMessage(
new InformationMessage($"{v.Name} is being raided by {v.Settlement.Party.MapEvent.PartiesOnSide(BattleSideEnum.Attacker).First().Party.Name}!"));
}
});
CampaignEvents.RaidCompletedEvent.AddNonSerializedListener(this, (_, m) =>
{
if (Globals.Settings.ShowRaids
&& m.PartiesOnSide(BattleSideEnum.Attacker)
.AnyQ(mep => mep.Party.IsMobile && mep.Party.MobileParty.IsBM()))
{
InformationManager.DisplayMessage(
new InformationMessage($"{m.MapEventSettlement?.Name} raided! " +
$"{m.PartiesOnSide(BattleSideEnum.Attacker).First().Party.Name} is fat with loot near {SettlementHelper.FindNearestTown().Name}!"));
}
});
CampaignEvents.TickPartialHourlyAiEvent.AddNonSerializedListener(this, TickPartialHourlyAiEvent);
CampaignEvents.DailyTickPartyEvent.AddNonSerializedListener(this, DailyTickPartyEvent);
CampaignEvents.HourlyTickEvent.AddNonSerializedListener(this, SpawnBM);
CampaignEvents.MobilePartyDestroyed.AddNonSerializedListener(this, MobilePartyDestroyed);
CampaignEvents.DailyTickEvent.AddNonSerializedListener(this, DailyTick);
}
private void DailyTick()
{
if (Globals.Settings.Debug)
{
var bandits = MobileParty.AllBanditParties.WhereQ(p => !p.IsBM());
Log.Debug?.Log($"Total regular bandit parties, Day {CampaignTime.Now.GetDayOfYear}, {bandits.Count()}");
foreach (var hero in Hero.AllAliveHeroes.WhereQ(h => h.PartyBelongedTo.IsBM()))
{
if (hero.BattleEquipment[5].IsEmpty)
{
Log.Debug?.Log($"Naked hero {hero.PartyBelongedTo.Name}");
}
}
}
}
private static void MobilePartyDestroyed(MobileParty mobileParty, PartyBase destroyer)
{
// Avoidance-bomb all BMs in the area
int AvoidanceIncrease() => Rng.Next(15, 35);
if (!mobileParty.IsBM() || destroyer?.LeaderHero is null)
return;
destroyer.MobileParty.GetBM()?.Avoidance.Remove(mobileParty.LeaderHero);
foreach (var BM in GetCachedBMs().WhereQ(bm =>
bm.MobileParty.Position2D.Distance(mobileParty.Position2D) < EffectRadius))
{
if (BM.Avoidance.TryGetValue(destroyer.LeaderHero, out _))
BM.Avoidance[destroyer.LeaderHero] += AvoidanceIncrease();
else
BM.Avoidance.Add(destroyer.LeaderHero, AvoidanceIncrease());
}
}
private static void TickPartialHourlyAiEvent(MobileParty mobileParty)
{
if (mobileParty.PartyComponent is not (BanditPartyComponent or ModBanditMilitiaPartyComponent))
return;
if (mobileParty.MemberRoster.TotalManCount < Globals.Settings.MergeableSize)
return;
if (mobileParty.IsUsedByAQuest())
return;
// they will evacuate hideouts and not chase caravans
if (mobileParty.PartyComponent is BanditPartyComponent)
{
if ((mobileParty.CurrentSettlement is not null
&& mobileParty.AiBehaviorMapEntity is Settlement { IsHideout: true })
|| mobileParty.AiBehaviorMapEntity is MobileParty { IsCaravan: true })
return;
}
if (mobileParty.MapEvent is not null)
return;
// near any Hideouts?
if (mobileParty.IsBM()
&& Settlement.FindSettlementsAroundPosition(mobileParty.Position2D, MinDistanceFromHideout, s => s.IsHideout).Any())
{
BMThink(mobileParty);
return;
}
// BM changed too recently?
if (mobileParty.IsBM()
&& CampaignTime.Now < mobileParty.GetBM().LastMergedOrSplitDate + CampaignTime.Hours(Globals.Settings.CooldownHours))
{
BMThink(mobileParty);
return;
}
var nearbyBandits = MobileParty.FindPartiesAroundPosition(mobileParty.Position2D, FindRadius).WhereQ(m =>
m.IsBandit
&& m.MapEvent is null
&& m.MemberRoster.TotalManCount > Globals.Settings.MergeableSize
&& m.MemberRoster.TotalManCount + mobileParty.MemberRoster.TotalManCount >= Globals.Settings.MinPartySize
&& IsAvailableBanditParty(m)).ToListQ();
nearbyBandits.Remove(mobileParty);
if (!nearbyBandits.Any())
{
BMThink(mobileParty);
return;
}
MobileParty mergeTarget = default;
foreach (var target in nearbyBandits.OrderByQ(m => m.Position2D.Distance(mobileParty.Position2D)))
{
var militiaTotalCount = mobileParty.MemberRoster.TotalManCount + target.MemberRoster.TotalManCount;
if (militiaTotalCount < Globals.Settings.MinPartySize || militiaTotalCount > CalculatedMaxPartySize)
continue;
if (target.IsBM())
{
CampaignTime? targetLastChangeDate = target.GetBM().LastMergedOrSplitDate;
if (CampaignTime.Now < targetLastChangeDate + CampaignTime.Hours(Globals.Settings.CooldownHours))
continue;
}
if (NumMountedTroops(mobileParty.MemberRoster) + NumMountedTroops(target.MemberRoster) > militiaTotalCount / 2)
continue;
mergeTarget = target;
break;
}
if (mergeTarget is null)
{
BMThink(mobileParty);
return;
}
if (Campaign.Current.Models.MapDistanceModel.GetDistance(mergeTarget, mobileParty) > MergeDistance
&& mobileParty.TargetParty != mergeTarget)
{
//Log.Debug?.Log($"{new string('>', 100mobileParty.SetMoveEscortParty(mergeTarget);)} MOVING {mobileParty.StringId,20} {mergeTarget.StringId,20}");
mobileParty.SetMoveEscortParty(mergeTarget);
mergeTarget.SetMoveEscortParty(mobileParty);
return;
}
//Log.Debug?.Log($"{new string('=', 100)} MERGING {mobileParty.StringId,20} {mergeTarget.StringId,20}");
// create a new party merged from the two
var rosters = MergeRosters(mobileParty, mergeTarget);
var clan = mobileParty.ActualClan ?? mergeTarget.ActualClan ?? Clan.BanditFactions.GetRandomElementInefficiently();
var bm = MobileParty.CreateParty("Bandit_Militia", new ModBanditMilitiaPartyComponent(clan), m => m.ActualClan = clan);
InitMilitia(bm, rosters, mobileParty.Position2D);
// each BM gets the average of Avoidance values
var calculatedAvoidance = new Dictionary<Hero, float>();
void CalcAverageAvoidance(ModBanditMilitiaPartyComponent BM)
{
foreach (var entry in BM.Avoidance)
if (!calculatedAvoidance.TryGetValue(entry.Key, out _))
calculatedAvoidance.Add(entry.Key, entry.Value);
else
{
calculatedAvoidance[entry.Key] += entry.Value;
calculatedAvoidance[entry.Key] /= 2;
}
}
if (mobileParty.PartyComponent is ModBanditMilitiaPartyComponent BM1)
CalcAverageAvoidance(BM1);
if (mergeTarget.PartyComponent is ModBanditMilitiaPartyComponent BM2)
CalcAverageAvoidance(BM2);
bm.GetBM().Avoidance = calculatedAvoidance;
// teleport new militias near the player
if (Globals.Settings.TestingMode)
{
// in case a prisoner
var party = Hero.MainHero.PartyBelongedTo ?? Hero.MainHero.PartyBelongedToAsPrisoner.MobileParty;
bm.Position2D = party.Position2D;
}
bm.Party.Visuals.SetMapIconAsDirty();
try
{
// can throw if Clan is null (doesn't happen in 3.9 apparently)
Trash(mobileParty);
Trash(mergeTarget);
}
catch (Exception ex)
{
Log.Debug?.Log(ex);
}
DoPowerCalculations();
}
internal static void BMThink(MobileParty mobileParty)
{
Settlement target;
switch (mobileParty.Ai.AiState)
{
case AIState.Undefined:
case AIState.PatrollingAroundLocation when mobileParty.DefaultBehavior is AiBehavior.Hold or AiBehavior.None:
if (mobileParty.TargetSettlement is null)
{
target = Settlement.All.WhereQ(s => s.Position2D.Distance(mobileParty.Position2D) < settlementFindRange).GetRandomElementInefficiently();
mobileParty.SetMovePatrolAroundSettlement(target);
}
break;
case AIState.PatrollingAroundLocation:
// PILLAGE!
if (Globals.Settings.AllowPillaging
&& mobileParty.LeaderHero is not null
&& mobileParty.Party.TotalStrength > MilitiaPartyAveragePower
&& Rng.NextDouble() < SmallChance
&& GetCachedBMs().CountQ(m => m.MobileParty.ShortTermBehavior is AiBehavior.RaidSettlement) < RaidCap)
{
target = SettlementHelper.FindNearestVillage(s =>
{
// JetBrains Rider suggested this insanity
if (s.Village is { VillageState: Village.VillageStates.BeingRaided or Village.VillageStates.Looted }
|| s.Owner is null
|| s.GetValue() <= 0)
{
return false;
}
return true;
}, mobileParty);
var BM = mobileParty.GetBM();
if (BM is null)
return;
if (BM.Avoidance.ContainsKey(target.Owner)
&& Rng.NextDouble() * 100 <= BM.Avoidance[target.Owner])
{
Log.Debug?.Log($"||| {mobileParty.Name} avoided pillaging {target}");
break;
}
if (target.OwnerClan == Hero.MainHero.Clan)
InformationManager.DisplayMessage(new InformationMessage($"{mobileParty.Name} is raiding your village {target.Name} near {target.Town?.Name}!"));
//Log.Debug?.Log($"{new string('=', 100)} {target.Village.VillageState}");
mobileParty.SetMoveRaidSettlement(target);
}
break;
}
}
private static void DailyTickPartyEvent(MobileParty mobileParty)
{
if (mobileParty.IsBM())
{
if ((int)CampaignTime.Now.ToWeeks % CampaignTime.DaysInWeek == 0
&& Globals.Settings.AllowPillaging)
{
AdjustAvoidance(mobileParty);
}
TryGrowing(mobileParty);
if (Rng.NextDouble() <= Globals.Settings.TrainingChance)
{
TrainMilitia(mobileParty);
}
TrySplitParty(mobileParty);
}
}
private static void AdjustAvoidance(MobileParty mobileParty)
{
foreach (var BM in GetCachedBMs(true)
.WhereQ(bm => bm.Leader is not null
&& bm.MobileParty.Position2D.Distance(mobileParty.Position2D) < AdjustRadius))
{
foreach (var kvp in BM.Avoidance)
{
if (BM.Avoidance.ContainsKey(kvp.Key))
{
if (kvp.Value > BM.Avoidance[kvp.Key])
{
BM.Avoidance[kvp.Key] -= Increment;
}
else if (kvp.Value < BM.Avoidance[kvp.Key])
{
BM.Avoidance[kvp.Key] += Increment;
}
}
}
}
}
private static void TryGrowing(MobileParty mobileParty)
{
if (Globals.Settings.GrowthPercent > 0
&& MilitiaPowerPercent <= Globals.Settings.GlobalPowerPercent
&& mobileParty.ShortTermBehavior != AiBehavior.FleeToPoint
&& mobileParty.MapEvent is null
&& IsAvailableBanditParty(mobileParty)
&& Rng.NextDouble() <= Globals.Settings.GrowthChance / 100f)
{
var eligibleToGrow = mobileParty.MemberRoster.GetTroopRoster().WhereQ(rosterElement =>
rosterElement.Character.Tier < Globals.Settings.MaxTrainingTier
&& !rosterElement.Character.IsHero
&& mobileParty.ShortTermBehavior != AiBehavior.FleeToPoint
&& !mobileParty.IsVisible
&& !rosterElement.Character.Name.ToString().StartsWith("Glorious"))
.ToListQ();
if (eligibleToGrow.Any())
{
var growthAmount = mobileParty.MemberRoster.TotalManCount * Globals.Settings.GrowthPercent / 100f;
// bump up growth to reach GlobalPowerPercent (synthetic but it helps warm up militia population)
// thanks Erythion!
var boost = CalculatedGlobalPowerLimit / GlobalMilitiaPower;
growthAmount += Globals.Settings.GlobalPowerPercent / 100f * boost;
growthAmount = Mathf.Clamp(growthAmount, 1, 50);
//Log.Debug?.Log($"+++ Growing {mobileParty.Name}, total: {mobileParty.MemberRoster.TotalManCount}");
for (var i = 0; i < growthAmount && mobileParty.MemberRoster.TotalManCount + 1 < CalculatedMaxPartySize; i++)
{
var troop = eligibleToGrow.GetRandomElement().Character;
if (GlobalMilitiaPower + troop.GetPower() < CalculatedGlobalPowerLimit)
{
mobileParty.MemberRoster.AddToCounts(troop, 1);
}
}
AdjustCavalryCount(mobileParty.MemberRoster);
//var troopString = $"{mobileParty.Party.NumberOfAllMembers} troop" + (mobileParty.Party.NumberOfAllMembers > 1 ? "s" : "");
//var strengthString = $"{Math.Round(mobileParty.Party.TotalStrength)} strength";
//Log.Debug?.Log($"{$"Grown to",-70} | {troopString,10} | {strengthString,12} |");
DoPowerCalculations();
// Log.Debug?.Log($"Grown to: {mobileParty.MemberRoster.TotalManCount}");
}
}
}
private static void SpawnBM()
{
if (!Globals.Settings.MilitiaSpawn)
return;
try
{
var settlement = Settlement.All.WhereQ(s => !s.IsVisible && s.GetTrackDistanceToMainAgent() > 100).GetRandomElementInefficiently()
?? Settlement.All.WhereQ(s => s.GetTrackDistanceToMainAgent() > 200).GetRandomElementInefficiently(); // for cheats that make all IsVisible
for (var i = 0;
MilitiaPowerPercent + 1 <= Globals.Settings.GlobalPowerPercent
&& i < (Globals.Settings.GlobalPowerPercent - MilitiaPowerPercent) / 24f;
i++)
{
if (Rng.Next(0, 101) > Globals.Settings.SpawnChance)
continue;
Clan clan;
// ROT
if (settlement.OwnerClan == Wights)
clan = Clan.BanditFactions.Except(new[] { Wights }).GetRandomElementInefficiently();
else
clan = settlement.OwnerClan;
var min = Convert.ToInt32(Globals.Settings.MinPartySize);
var max = Convert.ToInt32(CalculatedMaxPartySize);
// if the MinPartySize is cranked it will throw ArgumentOutOfRangeException
if (max < min)
max = min;
var roster = TroopRoster.CreateDummyTroopRoster();
var size = Convert.ToInt32(Rng.Next(min, max + 1) / 2f);
var foot = Rng.Next(40, 61);
var range = Rng.Next(20, Rng.Next(35, 100 - foot) + 1);
var horse = 100 - foot - range;
// DRM has no cavalry
if (Globals.BasicCavalry.Count == 0)
{
foot += horse % 2 == 0
? horse / 2
: horse / 2 + 1;
range += horse / 2;
horse = 0;
}
var formation = new List<int>
{
foot, range, horse
};
for (var index = 0; index < formation.Count; index++)
{
for (var c = 0; c < formation[index] * size / 100f; c++)
switch (index)
{
case 0:
roster.AddToCounts(Globals.BasicInfantry.GetRandomElement(), 1);
break;
case 1:
roster.AddToCounts(Globals.BasicRanged.GetRandomElement(), 1);
break;
case 2:
roster.AddToCounts(Globals.BasicCavalry.GetRandomElement(), 1);
break;
}
}
var bm = MobileParty.CreateParty("Bandit_Militia", new ModBanditMilitiaPartyComponent(clan), m => m.ActualClan = clan);
InitMilitia(bm, new[] { roster, TroopRoster.CreateDummyTroopRoster() }, settlement.GatePosition);
DoPowerCalculations();
// teleport new militias near the player
if (Globals.Settings.TestingMode)
{
// in case a prisoner
var party = Hero.MainHero.PartyBelongedTo ?? Hero.MainHero.PartyBelongedToAsPrisoner.MobileParty;
bm.Position2D = party.Position2D;
}
}
}
catch (Exception ex)
{
InformationManager.DisplayMessage(new InformationMessage("Problem spawning BM, please open a bug report with the log.txt file (Debug setting must be on)."));
InformationManager.DisplayMessage(new InformationMessage($"{ex.Message}"));
Log.Debug?.Log(ex);
}
}
public override void SyncData(IDataStore dataStore)
{
dataStore.SyncData("Heroes", ref Heroes);
}
}
}