-
Notifications
You must be signed in to change notification settings - Fork 0
/
Patches.cs
625 lines (520 loc) · 22.5 KB
/
Patches.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
using System.Reflection.Emit;
using System.Text.Json;
using System.Text.RegularExpressions;
using HarmonyLib;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Netcode;
using StardewValley;
using StardewValley.Extensions;
using StardewValley.TerrainFeatures;
using Object = StardewValley.Object;
using Vector2 = Microsoft.Xna.Framework.Vector2;
namespace CustomMoss;
public class helper
{
public static Dictionary<string, string> DecodeModData(string content)
{
Dictionary<string, string>? desContent = JsonSerializer.Deserialize<Dictionary<string, string>>(content);
return desContent ?? new Dictionary<string, string>();
}
public static NetString EncodeModData(Dictionary<string, string> content)
{
string output = JsonSerializer.Serialize(content);
return new NetString(output);
}
public static List<string> ParseAsList(string content)
{
return Regex.Split(content, ", +").ToList();
}
}
/////////////////
//// TREES ////
/////////////////
[HarmonyPatch(typeof(Tree), nameof(Tree.dayUpdate))]
public class Tree_dayUpdate_Patches
{
private static ModConfig Config = ModEntry.Config;
public static void Postfix(Tree __instance)
{
string treeUID = "aceynk.CustomMoss/Tree";
Random rnd = Random.Shared;
Dictionary<string, Dictionary<string, string>> mossData = Game1.content.Load<Dictionary<string, Dictionary<string, string>>>(treeUID);
if (!__instance.modData.ContainsKey(treeUID))
{
__instance.modData[treeUID] = JsonSerializer.Serialize(new Dictionary<string, string>
{
{"current_moss", "null"}
});
}
Dictionary<string, string> modDict = helper.DecodeModData(__instance.modData[treeUID]);
/*
* modDict looks like:
*
* {
* "current_moss": <moss id>
* }
*/
// checks //
if (modDict.Keys.Count == 0)
{
modDict["current_moss"] = "null";
}
if (__instance.hasMoss.Value)
{
if (!Config.VanillaMossOverrides)
{
__instance.hasMoss.Value = modDict["current_moss"] == "null";
}
else
{
modDict["current_moss"] = "null";
}
}
if (modDict["current_moss"] != "null" && mossData[modDict["current_moss"]].ContainsKey("GrowConditions") &&
!GameStateQuery.CheckConditions(mossData[modDict["current_moss"]]["GrowConditions"], Game1.currentLocation,
Game1.player))
{
modDict["current_moss"] = "null";
}
if (modDict["current_moss"] != "null" && mossData[modDict["current_moss"]].ContainsKey("ValidTrees") &&
!helper.ParseAsList(mossData[modDict["current_moss"]]["ValidTrees"]).Contains(__instance.treeType.Value))
{
modDict["current_moss"] = "null";
}
// process moss data //
foreach (string mossId in mossData.Keys)
{
if (modDict["current_moss"] != "null") break;
if (mossData[mossId].ContainsKey("GrowConditions") &&
!GameStateQuery.CheckConditions(mossData[mossId]["GrowConditions"]))
{
continue;
}
if (mossData[mossId].ContainsKey("ValidTrees") && !helper
.ParseAsList(mossData[mossId]["ValidTrees"])
.Contains(__instance.treeType.Value))
{
continue;
}
if (rnd.NextBool(float.Parse(mossData[mossId]["Chance"])))
{
modDict["current_moss"] = mossId;
if (!Config.VanillaMossOverrides)
{
__instance.hasMoss.Value = false;
}
}
}
__instance.modData[treeUID] = helper.EncodeModData(modDict);
}
}
[HarmonyPatch(typeof(Tree), nameof(Tree.performToolAction))]
public class Tree_performToolAction_Patches
{
public static void Prefix(Tool t, int explosion, Vector2 tileLocation, Tree __instance)
{
string treeUID = "aceynk.CustomMoss/Tree";
if (!__instance.modData.ContainsKey(treeUID))
{
__instance.modData[treeUID] = JsonSerializer.Serialize(new Dictionary<string, string>
{
{"current_moss", "null"}
});
}
Dictionary<string, string> modDict = helper.DecodeModData(__instance.modData[treeUID]);
Dictionary<string, Dictionary<string, string>> mossData = Game1.content.Load<Dictionary<string, Dictionary<string, string>>>("aceynk.CustomMoss/Tree");
Random rnd = Random.Shared;
if (__instance.growthStage.Value >= 5)
{
if (!mossData.ContainsKey(modDict["current_moss"]))
{
modDict["current_moss"] = "null";
}
if (modDict["current_moss"] != "null")
{
string mossId = modDict["current_moss"];
int amountBonus = 0;
if (ModEntry.ScytheAPI != null
&& ModEntry.ScytheAPI.HasGathererEnchantment(t)
&& Random.Shared.NextBool())
{
amountBonus = 1;
}
Item outItem = ItemRegistry.Create(
mossId,
amount: rnd.Next(
int.Parse(mossData[mossId]["MinAmount"]),
int.Parse(mossData[mossId]["MaxAmount"]) + 1
) + amountBonus
);
// modified from decompiled game
if (t is not null && t.getLastFarmerToUse() is not null)
{
t.getLastFarmerToUse().gainExperience(Farmer.foragingSkill, outItem.Stack * int.Parse(mossData[mossId]["Experience"]));
}
// modified from decompiled game vv
GameLocation location = __instance.Location ?? Game1.currentLocation;
Vector2 itemDebrisVector = new Vector2(tileLocation.X, tileLocation.Y - 1f) * 64f;
Game1.createMultipleItemDebris(outItem, itemDebrisVector, -1, location,
Game1.player.StandingPixel.Y - 32);
modDict["current_moss"] = "null";
// modified from decompiled game vvvv
Game1.stats.Increment("mossHarvested");
__instance.shake(tileLocation, doEvenIfStillShaking: true);
__instance.growthStage.Value = 9;
Game1.playSound("moss_cut");
__instance.modData[treeUID] = helper.EncodeModData(modDict);
}
}
}
}
[HarmonyPatch(typeof(Tree), nameof(Tree.draw))]
public class Tree_draw_Patches
{
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
CodeMatcher cMatcher = new CodeMatcher(instructions);
cMatcher.MatchEndForward(
new CodeMatch(OpCodes.Add),
new CodeMatch(OpCodes.Ldc_R4, 10000f),
new CodeMatch(OpCodes.Div),
new CodeMatch(OpCodes.Ldloc_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(Vector2), nameof(Vector2.X))),
new CodeMatch(OpCodes.Ldc_R4, 1000000f),
new CodeMatch(OpCodes.Div),
new CodeMatch(OpCodes.Sub)
)
.ThrowIfNotMatch("Couldn't find transpiler start position for Tree.draw. (main)")
.Advance(1)
.RemoveInstruction()
.Insert(
new CodeInstruction(OpCodes.Ldarg_0),
new CodeInstruction(OpCodes.Call,
AccessTools.Method(typeof(TranspilerSupplementary), nameof(TranspilerSupplementary.TreeDraw)))
);
cMatcher.MatchEndForward(
new CodeMatch(OpCodes.Ldc_I4_1),
new CodeMatch(OpCodes.Ldloc_2),
new CodeMatch(OpCodes.Ldc_R4, 10000f),
new CodeMatch(OpCodes.Div)
)
.ThrowIfNotMatch("Couldn't find transpiler start position for Tree.draw. (trunk #1)")
.Advance(1)
.RemoveInstruction()
.Insert(
new CodeInstruction(OpCodes.Ldarg_0),
new CodeInstruction(OpCodes.Call,
AccessTools.Method(typeof(TranspilerSupplementary), nameof(TranspilerSupplementary.TreeDraw)))
);
return cMatcher.InstructionEnumeration();
}
}
public class TranspilerSupplementary
{
public static void TreeDraw(SpriteBatch spriteBatch, Texture2D textureValue, Vector2 position,
Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects,
float layerDepth, Tree curInstance)
{
string treeUID = "aceynk.CustomMoss/Tree";
if (curInstance.modData.ContainsKey(treeUID))
{
Dictionary<string, string> modDict = helper.DecodeModData(curInstance.modData[treeUID]);
Dictionary<string, Dictionary<string, string>> mossData =
Game1.content.Load<Dictionary<string, Dictionary<string, string>>>(treeUID);
void dealWithRectangle()
{
if (sourceRectangle is not null)
{
Rectangle tempRect = (Rectangle)sourceRectangle;
if (Game1.currentSeason != "winter")
{
tempRect.X += 96;
}
sourceRectangle = tempRect;
}
}
void evalTreeTexture(string textureKey)
{
if (mossData[modDict["current_moss"]].ContainsKey(textureKey))
{
try
{
textureValue = Game1.content.Load<Texture2D>(mossData[modDict["current_moss"]][textureKey]);
}
catch
{
ModEntry._log.Log($"Failed to load the {textureKey} asset. Defaulting to vanilla sprites if possible.");
dealWithRectangle();
}
}
else
{
dealWithRectangle();
}
}
if (!mossData.ContainsKey(modDict["current_moss"]))
{
modDict["current_moss"] = "null";
}
if (modDict["current_moss"] != "null")
{
switch (curInstance.treeType.Value)
{
case Tree.bushyTree: // Oak
evalTreeTexture("TextureOak");
break;
case Tree.leafyTree: // Maple
evalTreeTexture("TextureMaple");
break;
case Tree.pineTree: // Pine
evalTreeTexture("TexturePine");
break;
case Tree.greenRainTreeBushy: // Green Rain Type 1
evalTreeTexture("Texture1");
break;
case Tree.greenRainTreeLeafy: // Green Rain Type 2
evalTreeTexture("Texture2");
break;
default:
if (mossData[modDict["custom_moss"]].ContainsKey("Texture" + curInstance.treeType.Value))
{
evalTreeTexture("Texture" + curInstance.treeType.Value);
}
else dealWithRectangle();
break;
}
}
}
spriteBatch.Draw(textureValue, position, sourceRectangle, color, rotation, origin, scale, effects,
layerDepth);
}
public static bool MushroomLog_hasMoss(Tree t)
{
string treeUID = "aceynk.CustomMoss/Tree";
if (t.modData.ContainsKey(treeUID))
{
Dictionary<string, string> modDict = helper.DecodeModData(t.modData[treeUID]);
return modDict["current_moss"] != "null";
}
return t.hasMoss.Value;
}
}
//////////////////
//// STONES ////
//////////////////
[HarmonyPatch(typeof(Object), nameof(Object.DayUpdate))]
public class Object_dayUpdate_Patches
{
public static void Postfix(Object __instance)
{
string stoneUID = "aceynk.CustomMoss/Stone";
Random rnd = Random.Shared;
Dictionary<string, Dictionary<string, string>> mossData =
Game1.content.Load<Dictionary<string, Dictionary<string, string>>>(stoneUID);
if (!__instance.modData.ContainsKey(stoneUID))
{
__instance.modData[stoneUID] = JsonSerializer.Serialize(new Dictionary<string, string>
{
{"current_moss", "null"}
});
}
Dictionary<string, string> modDict = helper.DecodeModData(__instance.modData[stoneUID]);
if (__instance.QualifiedItemId == "(O)343" || __instance.QualifiedItemId == "(O)450")
{
if (modDict["current_moss"] != "null")
{
if (mossData[modDict["current_moss"]].ContainsKey("GrowConditions") &&
!GameStateQuery.CheckConditions(mossData[modDict["current_moss"]]["GrowConditions"]))
{
modDict["current_moss"] = "null";
}
}
foreach (string mossId in mossData.Keys)
{
if (modDict["current_moss"] != "null") break;
if (mossData[mossId].ContainsKey("GrowConditions") && !helper
.ParseAsList(mossData[mossId]["GrowConditions"]).Contains(Game1.currentSeason))
{
continue;
}
if (rnd.NextBool(float.Parse(mossData[mossId]["Chance"])))
{
modDict["current_moss"] = mossId;
}
}
}
__instance.modData[stoneUID] = helper.EncodeModData(modDict);
}
}
[HarmonyPatch(typeof(Object), nameof(Object.performToolAction))]
public class Object_performToolAction_Patches
{
public static void Prefix(Tool t, Object __instance)
{
string stoneUID = "aceynk.CustomMoss/Stone";
if (!__instance.modData.ContainsKey(stoneUID))
{
__instance.modData[stoneUID] = JsonSerializer.Serialize(new Dictionary<string, string>
{
{"current_moss", "null"}
});
}
Dictionary<string, string> modDict = helper.DecodeModData(__instance.modData[stoneUID]);
Dictionary<string, Dictionary<string, string>> mossData = Game1.content.Load<Dictionary<string, Dictionary<string, string>>>(stoneUID);
Random rnd = Random.Shared;
if (!mossData.ContainsKey(modDict["current_moss"]))
{
modDict["current_moss"] = "null";
}
if (modDict["current_moss"] != "null")
{
string mossId = modDict["current_moss"];
int amountBonus = 0;
if (ModEntry.ScytheAPI != null
&& ModEntry.ScytheAPI.HasGathererEnchantment(t)
&& Random.Shared.NextBool())
{
amountBonus = 1;
}
Item outItem = ItemRegistry.Create(
mossId,
amount: rnd.Next(
int.Parse(mossData[mossId]["MinAmount"]),
int.Parse(mossData[mossId]["MaxAmount"]) + 1
) + amountBonus
);
// modified from decompiled game
if (t is not null && t.getLastFarmerToUse() is not null)
{
t.getLastFarmerToUse().gainExperience(Farmer.foragingSkill, outItem.Stack * int.Parse(mossData[mossId]["Experience"]));
}
// modified from decompiled game vv
GameLocation location = __instance.Location ?? Game1.currentLocation;
Vector2 itemDebrisVector = new Vector2(__instance.TileLocation.X, __instance.TileLocation.Y - 1f) * 64f;
Game1.createMultipleItemDebris(outItem, itemDebrisVector, -1, location,
Game1.player.StandingPixel.Y - 32);
modDict["current_moss"] = "null";
// modified from decompiled game vvvv
Game1.stats.Increment("mossHarvested");
Game1.playSound("moss_cut");
__instance.modData[stoneUID] = helper.EncodeModData(modDict);
}
}
}
[HarmonyPatch(typeof(Object), nameof(Object.performRemoveAction))]
public class Object_performRemoveAction_Patches
{
public static void Prefix(Object __instance)
{
string stoneUID = "aceynk.CustomMoss/Stone";
if (!__instance.modData.ContainsKey(stoneUID))
{
__instance.modData[stoneUID] = JsonSerializer.Serialize(new Dictionary<string, string>
{
{"current_moss", "null"}
});
}
Dictionary<string, string> modDict = helper.DecodeModData(__instance.modData[stoneUID]);
Dictionary<string, Dictionary<string, string>> mossData = Game1.content.Load<Dictionary<string, Dictionary<string, string>>>(stoneUID);
Random rnd = Random.Shared;
if (!mossData.ContainsKey(modDict["current_moss"]))
{
modDict["current_moss"] = "null";
}
if (modDict["current_moss"] != "null")
{
string mossId = modDict["current_moss"];
int amountBonus = 0;
if (ModEntry.ScytheAPI != null
&& ModEntry.ScytheAPI.HasGathererEnchantment(Game1.player.CurrentTool)
&& Random.Shared.NextBool())
{
amountBonus = 1;
}
Item outItem = ItemRegistry.Create(
mossId,
amount: rnd.Next(
int.Parse(mossData[mossId]["MinAmount"]),
int.Parse(mossData[mossId]["MaxAmount"]) + 1
) + amountBonus
);
Game1.player.gainExperience(Farmer.foragingSkill, outItem.Stack * int.Parse(mossData[mossId]["Experience"]));
// modified from decompiled game vv
GameLocation location = __instance.Location ?? Game1.currentLocation;
Vector2 itemDebrisVector = new Vector2(__instance.TileLocation.X, __instance.TileLocation.Y - 1f) * 64f;
Game1.createMultipleItemDebris(outItem, itemDebrisVector, -1, location,
Game1.player.StandingPixel.Y - 32);
modDict["current_moss"] = "null";
// modified from decompiled game vvvv
Game1.stats.Increment("mossHarvested");
Game1.playSound("moss_cut");
__instance.modData[stoneUID] = helper.EncodeModData(modDict);
}
}
}
[HarmonyPatch(typeof(Object), nameof(Object.draw), new[] {typeof(SpriteBatch), typeof(int), typeof(int), typeof(float)})]
public class Object_draw_Patches
{
public static void Postfix(SpriteBatch spriteBatch, int x, int y, float alpha, Object __instance)
{
string stoneUID = "aceynk.CustomMoss/Stone";
if (!__instance.modData.ContainsKey(stoneUID)) return;
Dictionary<string, string> modDict = helper.DecodeModData(__instance.modData[stoneUID]);
Dictionary<string, Dictionary<string, string>> mossData =
Game1.content.Load<Dictionary<string, Dictionary<string, string>>>(stoneUID);
if (!mossData.ContainsKey(modDict["current_moss"]))
{
modDict["current_moss"] = "null";
}
if (modDict["current_moss"] == "null" || !mossData[modDict["current_moss"]].ContainsKey("Texture")) return;
Texture2D texture = Game1.content.Load<Texture2D>(mossData[modDict["current_moss"]]["Texture"]);
Vector2 position = Game1.GlobalToLocal(Game1.viewport, new Vector2(x * 64 + 32, y * 64 + 51 + 5));
float depth = (__instance.isPassable() ? __instance.boundingBox.Top : __instance.boundingBox.Bottom) / 10000f;
Rectangle sourceRect;
switch (__instance.QualifiedItemId)
{
case "(O)343":
if (!mossData[modDict["current_moss"]].ContainsKey("SpriteIndex343")) break;
sourceRect = Game1.getSourceRectForStandardTileSheet(texture,
int.Parse(mossData[modDict["current_moss"]]["SpriteIndex343"]), 16, 16);
spriteBatch.Draw(texture, position, sourceRect, Color.White, 0f, new Vector2(8f, 14f), 4f,
__instance.flipped ? SpriteEffects.FlipHorizontally : SpriteEffects.None,
depth);
break;
case "(O)450":
if (!mossData[modDict["current_moss"]].ContainsKey("SpriteIndex450")) break;
sourceRect = Game1.getSourceRectForStandardTileSheet(texture,
int.Parse(mossData[modDict["current_moss"]]["SpriteIndex450"]), 16, 16);
spriteBatch.Draw(texture, position, sourceRect, Color.White, 0f, new Vector2(8f, 14f), 4f,
__instance.flipped ? SpriteEffects.FlipHorizontally : SpriteEffects.None,
depth);
break;
}
}
}
///////////////////////
//// MUSHROOM LOGS ////
///////////////////////
[HarmonyPatch(typeof(Object), nameof(Object.OutputMushroomLog))]
public class Object_OutputMushroomLog
{
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
CodeMatcher cMatcher = new(instructions);
cMatcher.MatchEndForward(
new CodeMatch(OpCodes.Ldstr, "(O)422"),
new CodeMatch(OpCodes.Stloc_S, 12),
new CodeMatch(OpCodes.Ldloc_2),
new CodeMatch(OpCodes.Ldloc_S, 12),
new CodeMatch(OpCodes.Callvirt, AccessTools.Method(typeof(List<string>), nameof(List<string>.Add)))
)
.ThrowIfNotMatch("Couldn't find transpiler start position for Object.OutputMushroomLog patch.")
.Advance(2)
.RemoveInstructions(2)
.Insert(
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(TranspilerSupplementary), nameof(TranspilerSupplementary.MushroomLog_hasMoss)))
);
return cMatcher.InstructionEnumeration();
}
}