Skip to content

Commit

Permalink
- Move to HarmonyX
Browse files Browse the repository at this point in the history
- Replace Traverse, AccessTools usage
  • Loading branch information
IceRaptor committed Apr 16, 2023
1 parent c4ddabe commit 81bdce2
Show file tree
Hide file tree
Showing 11 changed files with 100 additions and 116 deletions.
4 changes: 2 additions & 2 deletions LootMagnet/LootMagnet/LootMagnet.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@
<AssemblyTitle>LootMagnet</AssemblyTitle>
<Product>LootMagnet</Product>
<Copyright>Copyright © 2021</Copyright>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
<FileVersion>2.0.0.0</FileVersion>
<AssemblyVersion>8.0.0</AssemblyVersion>
<FileVersion>8.0.0</FileVersion>
<LangVersion>11</LangVersion>
</PropertyGroup>

Expand Down
6 changes: 3 additions & 3 deletions LootMagnet/LootMagnet/MissionResultsStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,6 @@ public void OnInventoryButton()
ammoText.SetText("AMMO");
inventoryWidget.tabAmmoToggleObj.OnClicked = new UnityEvent();
inventoryWidget.tabAmmoToggleObj.OnClicked.AddListener(new UnityAction(this.OnFilterButtonClicked));
inventoryUIInited = false;
RectTransform buttonRT = inventoryWidget.tabAmmoToggleObj.transform as RectTransform;
RectTransform parentRT = inventoryWidget.tabAmmoToggleObj.transform.parent as RectTransform;
Vector3 tabsPos = parentRT.localPosition;
Expand Down Expand Up @@ -534,8 +533,9 @@ public static void Postfix(AAR_SalvageScreen __instance)
[HarmonyPatch(MethodType.Normal)]
public static class AAR_CalculateAndAddAvailableSalvage
{
public static void Postfix(AAR_SalvageScreen __instance, List<ListElementController_BASE_NotListView> ___AllSalvageControllers)
public static void Postfix(AAR_SalvageScreen __instance)
{
List<ListElementController_BASE_NotListView> allSalvageControllers = __instance.AllSalvageControllers;
try
{
SalavageStorageWidget storageWidget = __instance.GetComponent<SalavageStorageWidget>();
Expand All @@ -547,7 +547,7 @@ public static void Postfix(AAR_SalvageScreen __instance, List<ListElementControl
if (storageWidget != null)
{
__instance.Sim.GetAllInventoryMechDefs(); //to make CustomSalvageRecalculate things
foreach (var salvageElement in ___AllSalvageControllers)
foreach (var salvageElement in allSalvageControllers)
{
var chassisElement = salvageElement as ListElementController_SalvageMechPart_NotListView;
if (chassisElement == null) { continue; }
Expand Down
38 changes: 15 additions & 23 deletions LootMagnet/LootMagnet/Patches/Patches.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,9 @@
namespace LootMagnet
{

[HarmonyPatch]
[HarmonyPatch(typeof(Contract), "GenerateSalvage")]
public static class Contract_GenerateSalvage
{

// Private method can't be patched by annotations, so use MethodInfo
public static MethodInfo TargetMethod()
{
return AccessTools.Method(typeof(Contract), "GenerateSalvage");
}

public static void Prefix(ref bool __runOriginal, Contract __instance)
{
if (!__runOriginal) return;
Expand Down Expand Up @@ -69,17 +62,17 @@ public static void Prefix(ref bool __runOriginal, Contract __instance, MissionRe
[HarmonyPatch(new Type[] { typeof(InventoryItemElement_NotListView) })]
public static class ListElementController_SalvageMechPart_RefreshInfoOnWidget
{
public static void Postfix(ListElementController_SalvageMechPart_NotListView __instance, InventoryItemElement_NotListView theWidget, MechDef ___mechDef, SalvageDef ___salvageDef)
public static void Postfix(ListElementController_SalvageMechPart_NotListView __instance, InventoryItemElement_NotListView theWidget)
{
Mod.Log.Debug?.Write($"LEC_SMP_NLV:RIOW - entered");
if (___salvageDef != null && ___salvageDef.RewardID != null && ___salvageDef.RewardID.Contains("_qty"))
if (__instance.salvageDef != null && __instance.salvageDef.RewardID != null && __instance.salvageDef.RewardID.Contains("_qty"))
{
int qtyIdx = ___salvageDef.RewardID.IndexOf("_qty");
string countS = ___salvageDef.RewardID.Substring(qtyIdx + 4);
int qtyIdx = __instance.salvageDef.RewardID.IndexOf("_qty");
string countS = __instance.salvageDef.RewardID.Substring(qtyIdx + 4);
int count = int.Parse(countS);
Mod.Log.Debug?.Write($"LEC_SMP_NLV:RIOW - found quantity {count}, changing mechdef");

DescriptionDef currentDesc = ___mechDef.Chassis.Description;
DescriptionDef currentDesc = __instance.mechDef.Chassis.Description;
string displayName = !String.IsNullOrEmpty(currentDesc.UIName) ? currentDesc.UIName : currentDesc.Name;
string newUIName = $"{displayName} <lowercase>[QTY:{count}]</lowercase>";

Expand Down Expand Up @@ -131,14 +124,14 @@ public static void Prefix(ref bool __runOriginal, Contract __instance, ref Salva
public static class AAR_SalvageScreen_CalculateAndAddAvailableSalvage
{

public static void Prefix(ref bool __runOriginal, AAR_SalvageScreen __instance, Contract ___contract, ref int ___totalSalvageMadeAvailable)
public static void Prefix(ref bool __runOriginal, AAR_SalvageScreen __instance)
{
if (!__runOriginal) return;

Mod.Log.Debug?.Write("AAR_SS:CAAAS entered.");

// Calculate potential salvage, which will be rolled up at this point (including mechs!)
ModState.PotentialSalvage = ___contract.GetPotentialSalvage();
ModState.PotentialSalvage = __instance.contract.GetPotentialSalvage();

// Sort by price, since other functions depend on it
ModState.PotentialSalvage.Sort(new Helper.SalvageDefByCostDescendingComparer());
Expand All @@ -157,12 +150,12 @@ public static void Prefix(ref bool __runOriginal, AAR_SalvageScreen __instance,
Helper.CalculateCompensation(ModState.PotentialSalvage);
}

___totalSalvageMadeAvailable = ModState.PotentialSalvage.Count - ModState.HeldbackParts.Count;
__instance.totalSalvageMadeAvailable = ModState.PotentialSalvage.Count - ModState.HeldbackParts.Count;
Mod.Log.Debug?.Write($"Setting totalSalvageMadeAvailable = potentialSalvage: {ModState.PotentialSalvage.Count} - heldbackParts: {ModState.HeldbackParts.Count}");

if (ModState.HeldbackParts.Count > 0)
{
UIHelper.ShowHoldbackDialog(___contract, __instance);
UIHelper.ShowHoldbackDialog(__instance.contract, __instance);
}
else
{
Expand All @@ -180,9 +173,8 @@ public static void Prefix(ref bool __runOriginal, AAR_SalvageScreen __instance,
public class AAR_SalvageChosen_ConvertToFinalState
{

public static void Postfix(AAR_SalvageChosen __instance, LocalizableText ___howManyReceivedText, AAR_SalvageScreen ___parent, SimGameState ___simState, Contract ___contract)
public static void Postfix(AAR_SalvageChosen __instance)
{

// Skip if the UI element isn't visible
if (!__instance.Visible)
{
Expand All @@ -202,12 +194,12 @@ public static void Postfix(AAR_SalvageChosen __instance, LocalizableText ___howM

// Update text with Quick Sell instructions
string localText = new Text(Mod.Config.LocalizedText[ModConfig.LT_QUICK_SELL], new object[] { }).ToString();
___howManyReceivedText.SetText(string.Concat(___howManyReceivedText.text, localText));
__instance.howManyReceivedText.SetText(string.Concat(__instance.howManyReceivedText.text, localText));

// Set the Mod state we'll rely upon
ModState.AAR_SalvageScreen = ___parent;
ModState.Contract = ___contract;
ModState.SimGameState = ___simState;
ModState.AAR_SalvageScreen = __instance.parent;
ModState.Contract = __instance.contract;
ModState.SimGameState = __instance.simState;

// Painful, full-context searches here
ModState.HBSPopupRoot =
Expand Down
18 changes: 4 additions & 14 deletions LootMagnet/LootMagnet/Utils/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -448,12 +448,7 @@ public static int MRBCfgIdx()
// Replica of HBS code used once holdback has been decided
public static void CalculateAndAddAvailableSalvage(AAR_SalvageScreen salvageScreen, List<SalvageDef> potentialSalvage)
{

Traverse salvageScreenT = Traverse.Create(salvageScreen);
Mod.Log.Debug?.Write("CAAAS - created base traverse.");

Traverse salvageSelectT = salvageScreenT.Field("salvageSelection");
AAR_SalvageSelection salvageSelection = salvageSelectT.GetValue<AAR_SalvageSelection>();
AAR_SalvageSelection salvageSelection = salvageScreen.salvageSelection;
Mod.Log.Debug?.Write("CAAAS - found salvage selection.");

foreach (SalvageDef item in potentialSalvage)
Expand All @@ -462,21 +457,16 @@ public static void CalculateAndAddAvailableSalvage(AAR_SalvageScreen salvageScre
}
Mod.Log.Debug?.Write("CAAAS - added all salvage entries.");

Traverse allSalvageContT = salvageScreenT.Field("AllSalvageControllers");
List<ListElementController_BASE_NotListView> allSalvageControllers =
allSalvageContT.GetValue<List<ListElementController_BASE_NotListView>>();
List <ListElementController_BASE_NotListView> allSalvageControllers = salvageScreen.AllSalvageControllers;
Mod.Log.Debug?.Write("CAAAS - found salvage controllers");

Traverse totalSalvageT = salvageScreenT.Field("totalSalvageMadeAvailable");
totalSalvageT.SetValue(allSalvageControllers.Count);
salvageScreen.totalSalvageMadeAvailable = allSalvageControllers.Count;
Mod.Log.Debug?.Write("CAAAS - updated salvageController count");

salvageSelection.ApplySalvageSorting();

// Update the contract potential salvage
Contract contract = salvageScreenT.Field("contract").GetValue<Contract>();
Traverse finalPotentialSalvageT = Traverse.Create(contract).Field("finalPotentialSalvage");
List<SalvageDef> finalPotentialSalvage = finalPotentialSalvageT.GetValue<List<SalvageDef>>();
List<SalvageDef> finalPotentialSalvage = salvageScreen.contract.finalPotentialSalvage;

finalPotentialSalvage.Clear();
finalPotentialSalvage.AddRange(potentialSalvage);
Expand Down
2 changes: 1 addition & 1 deletion LootMagnet/LootMagnet/Utils/UIHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public static void ShowHoldbackDialog(Contract contract, AAR_SalvageScreen salva
.AddButton(localButtonDispute, disputeAction, true, null)
.Render();

TextMeshProUGUI contentText = (TextMeshProUGUI)Traverse.Create(gp).Field("_contentText").GetValue();
TextMeshProUGUI contentText = gp._contentText;
contentText.alignment = TextAlignmentOptions.Left;
}

Expand Down
2 changes: 2 additions & 0 deletions LootMagnet/LootMagnetTests/GlobalUsing.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
global using BattleTech;
global using HarmonyLib;
35 changes: 22 additions & 13 deletions LootMagnet/LootMagnetTests/LootMagnetTests.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using System;
using LootMagnet;
using LootMagnet;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace LootMagnetTests {
namespace LootMagnetTests
{

[TestClass]
public class GetOutcomeTests {
public class GetOutcomeTests
{


[ClassInitialize]
Expand All @@ -16,7 +18,8 @@ public static void ClassInitialize(TestContext testContext)
}

[TestMethod]
public void TestOutcomes() {
public void TestOutcomes()
{

Dispute dispute = new Dispute(100000, "TEST");

Expand All @@ -30,17 +33,19 @@ public void TestOutcomes() {
}

[TestMethod]
public void TestAverageOutcome30() {
public void TestAverageOutcome30()
{

Dispute dispute = new Dispute(100000, "TEST");

dispute.SuccessChance = 30;
int successCount = 0;
int failCount = 0;
int totalCount = 100000;
for (int i = 0; i < totalCount; i++) {
if (dispute.GetOutcome() == Dispute.Outcome.SUCCESS) { successCount++; }
else { failCount++; }
for (int i = 0; i < totalCount; i++)
{
if (dispute.GetOutcome() == Dispute.Outcome.SUCCESS) { successCount++; }
else { failCount++; }
}
Console.WriteLine($"totalCount: {totalCount} successCount: {successCount} failCount: {failCount}");
float expectedSuccessRate = dispute.SuccessChance / 100f;
Expand All @@ -54,15 +59,17 @@ public void TestAverageOutcome30() {
}

[TestMethod]
public void TestAverageOutcome50() {
public void TestAverageOutcome50()
{

Dispute dispute = new Dispute(100000, "TEST");

dispute.SuccessChance = 50;
int successCount = 0;
int failCount = 0;
int totalCount = 100000;
for (int i = 0; i < totalCount; i++) {
for (int i = 0; i < totalCount; i++)
{
if (dispute.GetOutcome() == Dispute.Outcome.SUCCESS) { successCount++; } else { failCount++; }
}
Console.WriteLine($"totalCount: {totalCount} successCount: {successCount} failCount: {failCount}");
Expand All @@ -77,15 +84,17 @@ public void TestAverageOutcome50() {
}

[TestMethod]
public void TestAverageOutcome75() {
public void TestAverageOutcome75()
{

Dispute dispute = new Dispute(100000, "TEST");

dispute.SuccessChance = 75;
int successCount = 0;
int failCount = 0;
int totalCount = 100000;
for (int i = 0; i < totalCount; i++) {
for (int i = 0; i < totalCount; i++)
{
if (dispute.GetOutcome() == Dispute.Outcome.SUCCESS) { successCount++; } else { failCount++; }
}
Console.WriteLine($"totalCount: {totalCount} successCount: {successCount} failCount: {failCount}");
Expand Down
93 changes: 49 additions & 44 deletions LootMagnet/LootMagnetTests/LootMagnetTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,56 @@

<Target Name="ValidateBattleTechGameDir" Condition="'$(BattleTechGameDir)' == '' Or !Exists('$(BattleTechGameDir)')">
<Error Text="BattleTechGameDir variable not set properly" />
</Target>

<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net472</TargetFramework>
<AssemblySearchPaths>
$(ReferencePath);
{HintPathFromItem};
$(BattleTechGameDir)\BattleTech_Data\Managed
</AssemblySearchPaths>
<DisableImplicitFrameworkReferences>true</DisableImplicitFrameworkReferences>
<DebugType>none</DebugType>
<DebugSymbols>false</DebugSymbols>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>

<AssemblyTitle>LootMagnetTests</AssemblyTitle>
<Product>LootMagnetTests</Product>
<Copyright>Copyright © 2021</Copyright>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
<FileVersion>2.0.0.0</FileVersion>
</PropertyGroup>

<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets"
</Target>

<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net472</TargetFramework>
<AssemblySearchPaths>
$(ReferencePath);
{HintPathFromItem};
$(BattleTechGameDir)\BattleTech_Data\Managed
</AssemblySearchPaths>
<DisableImplicitFrameworkReferences>true</DisableImplicitFrameworkReferences>
<DebugType>none</DebugType>
<DebugSymbols>false</DebugSymbols>

<AssemblyTitle>LootMagnet</AssemblyTitle>
<Product>LootMagnet</Product>
<Copyright>Copyright © 2021</Copyright>
<AssemblyVersion>8.0.0</AssemblyVersion>
<FileVersion>8.0.0</FileVersion>
<LangVersion>11</LangVersion>
</PropertyGroup>

<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets"
Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="MSTest.TestAdapter" Version="1.4.0" />
<PackageReference Include="MSTest.TestFramework" Version="1.4.0" />
</ItemGroup>

<ItemGroup>
<Reference Include="0Harmony">
<Private>True</Private>
</Reference>
<Reference Include="Assembly-CSharp">
<Private>True</Private>
</Reference>
<Reference Include="System">
<Private>False</Private>
</Reference>
<Reference Include="System.Core">
<Private>False</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="MSTest.TestAdapter" Version="3.0.2" />
<PackageReference Include="MSTest.TestFramework" Version="3.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
</ItemGroup>

<ItemGroup>
<!-- Assets need to be private / included for testing purposes. Do not ship them-->
<PackageReference Include="HarmonyX" Version="2.10.1">
</PackageReference>

<Reference Include="Assembly-CSharp">
</Reference>
<Reference Include="System">
<Private>False</Private>
</Reference>
<Reference Include="System.Core">
<Private>False</Private>
</Reference>

<Reference Include="IRBTModUtils">
<HintPath>$(DeployedModPath)\..\IRBTModUtils\IRBTModUtils.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.CoreModule">
</Reference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\LootMagnet\LootMagnet.csproj" />
Expand Down
9 changes: 1 addition & 8 deletions LootMagnet/LootMagnetTests/MRBLevelTests.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
using BattleTech;
using Harmony;
using LootMagnet;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace LootMagnetTests
{
Expand Down
Loading

0 comments on commit 81bdce2

Please sign in to comment.