-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathModEntry.cs
533 lines (476 loc) · 18.6 KB
/
ModEntry.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
using HarmonyLib;
using Microsoft.Xna.Framework;
using Nanoray.Shrike;
using Nanoray.Shrike.Harmony;
using Shockah.CommonModCode.GMCM;
using Shockah.Kokoro;
using Shockah.Kokoro.GMCM;
using Shockah.Kokoro.Stardew;
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewValley;
using StardewValley.Objects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using SObject = StardewValley.Object;
namespace Shockah.InAHeartbeat;
public sealed class ModEntry : BaseMod<ModConfig>
{
private const string EmeraldID = "(O)60";
private const string AquamarineID = "(O)62";
private const string RubyID = "(O)64";
private const string AmethystID = "(O)66";
private const string TopazID = "(O)68";
private const string JadeID = "(O)70";
private const string DiamondID = "(O)72";
private const string PrismaticShardID = "(O)74";
private const string PearlID = "(O)797";
private static ModEntry Instance = null!;
public override void OnEntry(IModHelper helper)
{
Instance = this;
helper.Events.GameLoop.GameLaunched += OnGameLaunched;
}
private void OnGameLaunched(object? sender, GameLaunchedEventArgs e)
{
var api = Helper.ModRegistry.GetApi<ISpaceCoreApi>("spacechase0.SpaceCore");
if (api is null)
{
Monitor.Log("SpaceCore is not installed. The mod will not work.", LogLevel.Error);
return;
}
SetupConfig();
api.AdvancedInteractionStarted += OnAdvancedInteractionStarted;
Harmony harmony = new(ModManifest.UniqueID);
harmony.TryPatch(
monitor: Monitor,
original: () => AccessTools.Method(typeof(NPC), nameof(NPC.tryToReceiveActiveObject)),
transpiler: new HarmonyMethod(GetType(), nameof(NPC_tryToReceiveActiveObject_Transpiler))
);
harmony.TryPatch(
monitor: Monitor,
original: () => AccessTools.Method(typeof(NPC), "engagementResponse"),
prefix: new HarmonyMethod(GetType(), nameof(NPC_engagementResponse_Prefix))
);
harmony.TryPatch(
monitor: Monitor,
original: () => AccessTools.Method(typeof(NPC), nameof(NPC.checkAction)),
transpiler: new HarmonyMethod(GetType(), nameof(NPC_checkAction_Transpiler))
);
}
private void OnAdvancedInteractionStarted(object? sender, Action<string, Action> e)
{
if (sender is not NPC npc)
return;
if (npc.Name == "Caroline")
{
if (Config.IsBouquetCraftable && HasFriendshipWithAnyone(Game1.player, Config.DateFriendshipRequired.GetMin(), DatingState.Datable))
{
string translationKey = GetBestPossibleBouquetQuality(Game1.player) switch
{
SObject.bestQuality => "action.arrangeABouquet.iridium",
SObject.highQuality => "action.arrangeABouquet.gold",
SObject.medQuality => "action.arrangeABouquet.silver",
_ => "action.arrangeABouquet.regular"
};
e(Helper.Translation.Get(translationKey), () => OnArrangeABouquetAction(npc));
}
if (Config.IsPendantCraftable && HasFriendshipWithAnyone(Game1.player, Config.MarryFriendshipRequired.GetMin(), DatingState.Dating))
{
string translationKey = GetBestPossiblePendantQuality(Game1.player) switch
{
SObject.bestQuality => "action.craftAPendant.iridium",
SObject.highQuality => "action.craftAPendant.gold",
SObject.medQuality => "action.craftAPendant.silver",
_ => "action.craftAPendant.regular"
};
e(Helper.Translation.Get(translationKey), () => OnCraftAPendantAction(npc));
}
}
}
private void OnArrangeABouquetAction(NPC npc)
{
var player = Game1.player;
if (GetBestPossibleBouquetQuality(player) is not { } bestPossibleQuality)
{
npc.CurrentDialogue.Push(new Dialogue(npc, ".", Helper.Translation.Get("action.arrangeABouquet.notEnoughFlowers")));
Game1.drawDialogue(npc);
return;
}
// this should always succeed
_ = ConsumeBouquetCraftingRequirements(player, bestPossibleQuality);
player.addItemByMenuIfNecessary(ItemRegistry.Create("(O)458", quality: bestPossibleQuality));
npc.CurrentDialogue.Push(new Dialogue(npc, ".", Helper.Translation.Get("action.arrangeABouquet.success")));
Game1.drawDialogue(npc);
}
private void OnCraftAPendantAction(NPC npc)
{
var player = Game1.player;
if (GetBestPossiblePendantQuality(player) is not { } bestPossibleQuality)
{
npc.CurrentDialogue.Push(new Dialogue(npc, ".", Helper.Translation.Get("action.craftAPendant.notEnoughMaterials")));
Game1.drawDialogue(npc);
return;
}
// this should always succeed
_ = ConsumePendantCraftingRequirements(player, bestPossibleQuality);
player.addItemByMenuIfNecessary(ItemRegistry.Create("(O)460", quality: bestPossibleQuality));
npc.CurrentDialogue.Push(new Dialogue(npc, ".", Helper.Translation.Get("action.craftAPendant.success")));
Game1.drawDialogue(npc);
}
private void SetupConfig()
{
var api = Helper.ModRegistry.GetApi<IGenericModConfigMenuApi>("spacechase0.GenericModConfigMenu");
if (api is null)
return;
GMCMI18nHelper helper = new(api, ModManifest, Helper.Translation);
api.Register(
ModManifest,
reset: () => Config = new ModConfig(),
save: () =>
{
WriteConfig();
LogConfig();
}
);
helper.AddSectionTitle("config.bouquet.section");
helper.AddBoolOption("config.craftable", () => Config.IsBouquetCraftable);
helper.AddNumberOption("config.bouquet.flowersRequired", () => Config.BouquetFlowersRequired, min: 0, max: 20, interval: 1);
helper.AddNumberOption("config.bouquet.flowerTypesRequired", () => Config.BouquetFlowerTypesRequired, min: 0, max: 20, interval: 1);
api.AddNumberOption(
ModManifest,
getValue: () => Config.DateFriendshipRequired.Regular,
setValue: value => Config.DateFriendshipRequired.Regular = value,
name: () => Helper.Translation.Get("config.friendshipRequired.regular.name"),
tooltip: () => Helper.Translation.Get("config.friendshipRequired.tooltip"),
min: 0, max: 2500, interval: 50
);
api.AddNumberOption(
ModManifest,
getValue: () => Config.DateFriendshipRequired.Silver,
setValue: value => Config.DateFriendshipRequired.Silver = value,
name: () => Helper.Translation.Get("config.friendshipRequired.silver.name"),
tooltip: () => Helper.Translation.Get("config.friendshipRequired.tooltip"),
min: 0, max: 2500, interval: 50
);
api.AddNumberOption(
ModManifest,
getValue: () => Config.DateFriendshipRequired.Gold,
setValue: value => Config.DateFriendshipRequired.Gold = value,
name: () => Helper.Translation.Get("config.friendshipRequired.gold.name"),
tooltip: () => Helper.Translation.Get("config.friendshipRequired.tooltip"),
min: 0, max: 2500, interval: 50
);
api.AddNumberOption(
ModManifest,
getValue: () => Config.DateFriendshipRequired.Iridium,
setValue: value => Config.DateFriendshipRequired.Iridium = value,
name: () => Helper.Translation.Get("config.friendshipRequired.iridium.name"),
tooltip: () => Helper.Translation.Get("config.friendshipRequired.tooltip"),
min: 0, max: 2500, interval: 50
);
helper.AddSectionTitle("config.pendant.section");
helper.AddBoolOption("config.craftable", () => Config.IsPendantCraftable);
api.AddNumberOption(
ModManifest,
getValue: () => Config.PendantGemsRequired.Regular,
setValue: value => Config.PendantGemsRequired.Regular = value,
name: () => Helper.Translation.Get("config.pendant.gemsRequired.regular.name"),
min: 0, max: 8, interval: 1
);
api.AddNumberOption(
ModManifest,
getValue: () => Config.PendantGemsRequired.Silver,
setValue: value => Config.PendantGemsRequired.Silver = value,
name: () => Helper.Translation.Get("config.pendant.gemsRequired.silver.name"),
min: 0, max: 8, interval: 1
);
api.AddNumberOption(
ModManifest,
getValue: () => Config.PendantGemsRequired.Gold,
setValue: value => Config.PendantGemsRequired.Gold = value,
name: () => Helper.Translation.Get("config.pendant.gemsRequired.gold.name"),
min: 0, max: 8, interval: 1
);
api.AddNumberOption(
ModManifest,
getValue: () => Config.PendantGemsRequired.Iridium,
setValue: value => Config.PendantGemsRequired.Iridium = value,
name: () => Helper.Translation.Get("config.pendant.gemsRequired.iridium.name"),
min: 0, max: 8, interval: 1
);
api.AddNumberOption(
ModManifest,
getValue: () => Config.MarryFriendshipRequired.Regular,
setValue: value => Config.MarryFriendshipRequired.Regular = value,
name: () => Helper.Translation.Get("config.friendshipRequired.regular.name"),
tooltip: () => Helper.Translation.Get("config.friendshipRequired.tooltip"),
min: 0, max: 2500, interval: 50
);
api.AddNumberOption(
ModManifest,
getValue: () => Config.MarryFriendshipRequired.Silver,
setValue: value => Config.MarryFriendshipRequired.Silver = value,
name: () => Helper.Translation.Get("config.friendshipRequired.silver.name"),
tooltip: () => Helper.Translation.Get("config.friendshipRequired.tooltip"),
min: 0, max: 2500, interval: 50
);
api.AddNumberOption(
ModManifest,
getValue: () => Config.MarryFriendshipRequired.Gold,
setValue: value => Config.MarryFriendshipRequired.Gold = value,
name: () => Helper.Translation.Get("config.friendshipRequired.gold.name"),
tooltip: () => Helper.Translation.Get("config.friendshipRequired.tooltip"),
min: 0, max: 2500, interval: 50
);
api.AddNumberOption(
ModManifest,
getValue: () => Config.MarryFriendshipRequired.Iridium,
setValue: value => Config.MarryFriendshipRequired.Iridium = value,
name: () => Helper.Translation.Get("config.friendshipRequired.iridium.name"),
tooltip: () => Helper.Translation.Get("config.friendshipRequired.tooltip"),
min: 0, max: 2500, interval: 50
);
}
private static bool HasFriendshipWithAnyone(Farmer player, int friendshipLevel, DatingState minimumDatingState)
{
foreach (NPC npc in Utility.getAllCharacters())
if (player.getFriendshipLevelForNPC(npc.Name) >= friendshipLevel && (int)player.GetDatingState(npc) >= (int)minimumDatingState)
return true;
return false;
}
private static FlowerDescriptor? GetFlowerDescriptor(SObject item)
{
if (item.Category != SObject.flowersCategory)
return null;
if (item is ColoredObject colored)
return new(item.QualifiedItemId, colored.color.Value);
else
return new(item.QualifiedItemId, Color.White);
}
private static IEnumerable<(SObject Item, FlowerDescriptor FlowerDescriptor)> GetAllHeldFlowers(Farmer player)
{
foreach (var item in player.Items)
{
if (item is not SObject @object)
continue;
var descriptor = GetFlowerDescriptor(@object);
if (descriptor is null)
continue;
yield return (Item: @object, FlowerDescriptor: descriptor.Value);
}
}
private static IEnumerable<SObject> GetAllHeldGems(Farmer player)
{
foreach (var item in player.Items)
{
if (item is not SObject @object)
continue;
if (@object.bigCraftable.Value)
continue;
if (item.QualifiedItemId is EmeraldID or AquamarineID or RubyID or AmethystID or TopazID or JadeID or DiamondID or PrismaticShardID)
yield return @object;
}
}
private int? GetBestPossibleBouquetQuality(Farmer player)
{
if (HasBouquetCraftingRequirements(player, SObject.bestQuality))
return SObject.bestQuality;
else if (HasBouquetCraftingRequirements(player, SObject.highQuality))
return SObject.highQuality;
else if (HasBouquetCraftingRequirements(player, SObject.medQuality))
return SObject.medQuality;
else if (HasBouquetCraftingRequirements(player, SObject.lowQuality))
return SObject.lowQuality;
else
return null;
}
private int? GetBestPossiblePendantQuality(Farmer player)
{
if (!player.Items.Any(item => item is SObject @object && [email protected] && @object.QualifiedItemId == PearlID))
return null;
var types = GetAllHeldGems(player).Select(gem => gem.QualifiedItemId).ToHashSet();
if (types.Count >= Config.PendantGemsRequired.Iridium)
return SObject.bestQuality;
else if (types.Count >= Config.PendantGemsRequired.Gold)
return SObject.highQuality;
else if (types.Count >= Config.PendantGemsRequired.Silver)
return SObject.medQuality;
else if (types.Count >= Config.PendantGemsRequired.Regular)
return SObject.lowQuality;
else
return null;
}
private bool HasBouquetCraftingRequirements(Farmer player, int minimumItemQuality)
{
HashSet<FlowerDescriptor> uniqueFlowerTypes = [];
int flowersLeft = Config.BouquetFlowersRequired;
foreach (var flower in GetAllHeldFlowers(player))
{
if (flower.Item.Quality < minimumItemQuality)
continue;
uniqueFlowerTypes.Add(flower.FlowerDescriptor);
flowersLeft -= flower.Item.Stack;
if (flowersLeft <= 0 && uniqueFlowerTypes.Count >= Config.BouquetFlowerTypesRequired)
return true;
}
return false;
}
private bool ConsumeBouquetCraftingRequirements(Farmer player, int itemQuality)
{
var itemsLeft = GetAllHeldFlowers(player)
.Where(e => e.Item.Quality >= itemQuality)
.OrderBy(e => e.Item.Quality)
.ThenBy(e => e.Item.salePrice())
.Select(e => (Item: e.Item, FlowerDescriptor: e.FlowerDescriptor, Amount: e.Item.Stack))
.ToList();
List<Item> itemsToConsume = [];
HashSet<FlowerDescriptor> uniqueFlowerTypes = [];
int flowersLeft = Config.BouquetFlowersRequired;
void ActuallyConsume()
{
foreach (var item in itemsToConsume)
player.ConsumeItem(item);
}
while (true)
{
if (itemsLeft.Count == 0)
return false;
for (int i = 0; i < itemsLeft.Count; i++)
{
var entry = itemsLeft[i];
if (uniqueFlowerTypes.Count < Config.BouquetFlowerTypesRequired && uniqueFlowerTypes.Contains(entry.FlowerDescriptor))
continue;
uniqueFlowerTypes.Add(entry.FlowerDescriptor);
flowersLeft--;
itemsToConsume.Add(entry.Item.getOne());
if (entry.Amount <= 1)
itemsLeft.RemoveAt(i--);
else
itemsLeft[i] = (Item: entry.Item, FlowerDescriptor: entry.FlowerDescriptor, Amount: entry.Amount - 1);
if (flowersLeft <= 0 && uniqueFlowerTypes.Count >= Config.BouquetFlowerTypesRequired)
{
ActuallyConsume();
return true;
}
}
if (uniqueFlowerTypes.Count < Config.BouquetFlowerTypesRequired)
return false;
}
}
private bool ConsumePendantCraftingRequirements(Farmer player, int itemQuality)
{
int gemsRequired = Config.PendantGemsRequired.GetForQuality(itemQuality);
var gems = GetAllHeldGems(player).OrderBy(gem => gem.salePrice());
HashSet<string> uniqueGemTypes = [];
foreach (var gem in gems)
{
if (uniqueGemTypes.Contains(gem.QualifiedItemId))
continue;
uniqueGemTypes.Add(gem.QualifiedItemId);
if (uniqueGemTypes.Count >= gemsRequired)
break;
}
if (uniqueGemTypes.Count < gemsRequired)
return false;
if (!player.ConsumeItem(ItemRegistry.Create(PearlID), exactQuality: false))
return false;
foreach (var gemType in uniqueGemTypes)
player.ConsumeItem(ItemRegistry.Create(gemType), exactQuality: false);
return true;
}
private static IEnumerable<CodeInstruction> NPC_tryToReceiveActiveObject_Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase originalMethod)
{
try
{
return new SequenceBlockMatcher<CodeInstruction>(instructions)
.Find(
ILMatches.Call("get_Points"),
ILMatches.LdcI4(1000).Anchor(out Guid requirementAnchor),
ILMatches.AnyBranch
)
.Anchors().PointerMatcher(requirementAnchor)
.Replace(
new CodeInstruction(OpCodes.Ldarg_1),
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(ModEntry), nameof(GetDateFriendshipRequirement))),
new CodeInstruction(OpCodes.Ldc_I4_2),
new CodeInstruction(OpCodes.Div)
)
.Find(
ILMatches.Call("get_Points"),
ILMatches.LdcI4(2000).Anchor(out requirementAnchor),
ILMatches.AnyBranch
)
.Anchors().PointerMatcher(requirementAnchor)
.Replace(
new CodeInstruction(OpCodes.Ldarg_1),
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(ModEntry), nameof(GetDateFriendshipRequirement)))
)
.Find(
ILMatches.Call("get_Points"),
ILMatches.LdcI4(2500).Anchor(out requirementAnchor),
ILMatches.AnyBranch
)
.Anchors().PointerMatcher(requirementAnchor)
.Replace(
new CodeInstruction(OpCodes.Ldarg_1),
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(ModEntry), nameof(GetMarryFriendshipRequirement)))
)
.AllElements();
}
catch (Exception ex)
{
Instance.Monitor.Log($"Could not patch method {originalMethod} - {Instance.ModManifest.Name} probably won't work.\nReason: {ex}", LogLevel.Error);
return instructions;
}
}
private static void NPC_engagementResponse_Prefix(NPC __instance, Farmer who, bool asRoommate)
=> SetMarriedFriendshipRequirement(__instance, asRoommate ? Instance.Config.MarryFriendshipRequired.Regular : GetMarryFriendshipRequirement(who));
private static IEnumerable<CodeInstruction> NPC_checkAction_Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase originalMethod)
{
try
{
return new SequenceBlockMatcher<CodeInstruction>(instructions)
.Find(
ILMatches.Ldarg(1),
ILMatches.Ldarg(0),
ILMatches.Call("get_Name"),
ILMatches.Call("getFriendshipHeartLevelForNPC"),
ILMatches.LdcI4(9),
ILMatches.Ble.GetBranchTarget(out var kissDenyBranchLabel)
)
.Replace(
new CodeInstruction(OpCodes.Ldarg_1),
new CodeInstruction(OpCodes.Ldarg_0),
new CodeInstruction(OpCodes.Call, AccessTools.PropertyGetter(typeof(NPC), nameof(NPC.Name))),
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Farmer), nameof(Farmer.getFriendshipLevelForNPC))),
new CodeInstruction(OpCodes.Ldarg_0),
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(ModEntry), nameof(GetMarriedFriendshipRequirement))),
new CodeInstruction(OpCodes.Blt, kissDenyBranchLabel.Value)
)
.AllElements();
}
catch (Exception ex)
{
Instance.Monitor.Log($"Could not patch method {originalMethod} - {Instance.ModManifest.Name} probably won't work.\nReason: {ex}", LogLevel.Error);
return instructions;
}
}
public static int GetDateFriendshipRequirement(Farmer player)
=> Instance.Config.DateFriendshipRequired.GetForQuality(player.ActiveObject.Quality);
public static int GetMarryFriendshipRequirement(Farmer player)
=> Instance.Config.MarryFriendshipRequired.GetForQuality(player.ActiveObject.Quality);
public static int GetMarriedFriendshipRequirement(NPC npc)
{
int marriedFriendshipRequirement = Instance.Config.MarryFriendshipRequired.Regular;
if (npc.modData.TryGetValue($"{Instance.ModManifest.UniqueID}/MarriedFriendshipRequirement", out var marriedFriendshipRequirementString))
if (int.TryParse(marriedFriendshipRequirementString, out var parsedMarriedFriendshipRequirement))
marriedFriendshipRequirement = parsedMarriedFriendshipRequirement;
return marriedFriendshipRequirement;
}
public static void SetMarriedFriendshipRequirement(NPC npc, int value)
=> npc.modData[$"{Instance.ModManifest.UniqueID}/MarriedFriendshipRequirement"] = $"{value}";
}