Skip to content

Commit

Permalink
[v2.3.2] Compatibility with TerminalFormatter's modified store, among…
Browse files Browse the repository at this point in the history
… other things.

- Added `TerminalFormatter` as a soft dependency.
	- _I think?_
- Sales for rotating items should now display with `TerminalFormatter` installed.
	- Added transpiler for `Store.GetNodeText()` to display discounted prices and amounts in the store page whenever an item is on sale.
	- Temporary fix until proper compatibility can be made.
- `relativeScroll` now unpatches itself if `TerminalFormatter` is installed, since it already includes it.
- Patching is done upon loading the main menu for the first time.
  • Loading branch information
pacoito123 committed Aug 4, 2024
1 parent 7fed1f6 commit 8c1b01d
Show file tree
Hide file tree
Showing 8 changed files with 138 additions and 8 deletions.
13 changes: 12 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
### [2.3.2]

Compatibility with TerminalFormatter's modified store, among other things.
- Added [TerminalFormatter](https://thunderstore.io/c/lethal-company/p/mrov/TerminalFormatter) as a soft dependency.
- _I think?_
- Sales for rotating items should now display with [TerminalFormatter](https://thunderstore.io/c/lethal-company/p/mrov/TerminalFormatter) installed.
- Added transpiler for `Store.GetNodeText()` to display discounted prices and amounts in the store page whenever an item is on sale.
- Temporary fix until proper compatibility can be made.
- `relativeScroll` now unpatches itself if [TerminalFormatter](https://thunderstore.io/c/lethal-company/p/mrov/TerminalFormatter) is installed, since it already includes it.
- Patching is done upon loading into the main menu for the first time.

### [2.3.1]

Compatibility patch for Lategame Upgrades (and likely some moon-routing mods).
Compatibility patch for Lategame Upgrades (and likely other moon-routing price adjustment mods).
- Fixed compatibility with [Lategame Upgrades](https://thunderstore.io/c/lethal-company/p/malco/Lategame_Upgrades)' `Efficient Engines` upgrade.
- `Terminal.LoadNewNodeIfAffordable()` transpiler no longer removes instructions or touches `Terminal.totalCostOfItems` when routing to a moon.
- Changed priority of `Terminal.LoadNewNodeIfAffordable()` to `High` (600), so it's applied earlier.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using HarmonyLib;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using TerminalFormatter.Nodes;
using static StoreRotationConfig.Patches.TerminalItemSalesPatches;

namespace StoreRotationConfig.Compatibility
{
/// <summary>
/// Class handling compatibility with 'TerminalFormatter'.
/// </summary>
[HarmonyPatch]
internal static class TerminalFormatterCompatibility
{
/// <summary>
/// Whether 'TerminalFormatter' is present in the BepInEx Chainloader or not.
/// </summary>
public static bool Enabled
{
get
{
_enabled ??= BepInEx.Bootstrap.Chainloader.PluginInfos.ContainsKey("TerminalFormatter");

return (bool)_enabled;
}
}
private static bool? _enabled;

/// <summary>
/// Whether patches for 'TerminalFormatter' compatibility have already been applied or not.
/// </summary>
public static bool Patched { get; internal set; } = false;

/// <summary>
/// Replaces parameter with delegate call to display item discounts and their modified prices.
/// </summary>
/// ... (TerminalFormatter.Nodes.Store:286)
/// consoleTable.AddRow(new object[]
/// {
/// text7,
/// string.Format("${0}",
/// // terminalNode2.itemCost),
/// -> call(terminalNode2)),
/// ""
/// });
/// <param name="instructions">Iterator with original IL instructions.</param>
/// <returns>Iterator with modified IL instructions.</returns>
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
[HarmonyPatch(typeof(Store), nameof(Store.GetNodeText))]
[HarmonyTranspiler]
private static IEnumerable<CodeInstruction> GetNodeTextTranspiler(IEnumerable<CodeInstruction> instructions)
{
return new CodeMatcher(instructions).MatchForward(false,
new CodeMatch(OpCodes.Ldstr, "[DECORATIONS]"))
.MatchForward(false,
new(OpCodes.Ldfld, AccessTools.Field(typeof(TerminalNode), nameof(TerminalNode.itemCost))),
new(OpCodes.Box, operand: typeof(int)))
.SetInstructionAndAdvance(Transpilers.EmitDelegate((TerminalNode item) =>
{
// Return full cost if 'salesChance' is disabled OR the 'RotationSales' dictionary doesn't contain a discount for the item about to be displayed.
if (Plugin.Settings.SALE_CHANCE == 0 || (RotationSales != null && !RotationSales.ContainsKey(item)))
{
return $"{item.itemCost}";
}

Plugin.StaticLogger.LogDebug($"Appending {RotationSales[item]} to {item.creatureName}...");

// Obtain discounted item price.
int discountedPrice = item.itemCost - (int)(item.itemCost * (RotationSales[item] / 100f));

// Return string containing the discounted price and discount amount to display in the store page.
return $"{discountedPrice} ({RotationSales[item]}% OFF!)";
}))
.SetOperandAndAdvance(typeof(string))
.InstructionEnumeration();
}
}
}
20 changes: 20 additions & 0 deletions StoreRotationConfig/Patches/SyncShipUnlockablesPatches.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using GameNetcodeStuff;
using HarmonyLib;
using StoreRotationConfig.Compatibility;
using Unity.Netcode;

namespace StoreRotationConfig.Patches
Expand Down Expand Up @@ -46,6 +48,24 @@ private static void MenuManagerStartPre()
// Plugin.Settings.ConfigSynced = false;
UnlockablesSynced = false;
// ...

// Handle 'TerminalFormatter' compatibility here since I can't seem to get it to load before my mod, despite the soft dependency.
if (TerminalFormatterCompatibility.Enabled && !TerminalFormatterCompatibility.Patched)
{
Plugin.StaticLogger.LogInfo($"Patching 'TerminalFormatter'...");

// Patch 'TerminalFormatter.Nodes.Store.GetNodeText' to display discounts assigned to the rotating store.
Plugin.Harmony.PatchAll(typeof(TerminalFormatterCompatibility));

// Unpatch 'relativeScroll' tweak (already present in 'TerminalFormatter').
Plugin.Harmony.Unpatch(AccessTools.Method(typeof(PlayerControllerB), "ScrollMouse_performed"),
HarmonyPatchType.Transpiler, Plugin.GUID);

// Toggle patched status to avoid running more than once (every menu reload).
TerminalFormatterCompatibility.Patched = true;

Plugin.StaticLogger.LogInfo($"'TerminalFormatter' patched!");
}
}
}
}
2 changes: 1 addition & 1 deletion StoreRotationConfig/Patches/TerminalItemSalesPatches.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ private static IEnumerable<CodeInstruction> TextPostProcessTranspiler(IEnumerabl
TerminalNode item = storeRotation[index];

// Return if 'salesChance' is disabled OR the 'RotationSales' dictionary doesn't contain a discount for the item about to be displayed.
if (Plugin.Settings.SALE_CHANCE == 0 || RotationSales == null || !RotationSales.ContainsKey(item))
if (Plugin.Settings.SALE_CHANCE == 0 || (RotationSales != null && !RotationSales.ContainsKey(item)))
{
return;
}
Expand Down
2 changes: 1 addition & 1 deletion StoreRotationConfig/Patches/UnlockShipObjectPatches.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace StoreRotationConfig.Patches
/// Patches for removing purchased items from both current and future store rotations.
/// </summary>
[HarmonyPatch(typeof(StartOfRound))]
internal class UnlockShipObjectPatch
internal class UnlockShipObjectPatches
{
[HarmonyPatch("UnlockShipObject", typeof(int))]
[HarmonyPrefix]
Expand Down
22 changes: 19 additions & 3 deletions StoreRotationConfig/Plugin.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using StoreRotationConfig.Patches;
using System;
using System.Reflection;

namespace StoreRotationConfig
{
Expand All @@ -11,11 +11,17 @@ namespace StoreRotationConfig
/// </summary>
[BepInPlugin(GUID, PLUGIN_NAME, VERSION)]
[BepInDependency("com.sigurd.csync", "5.0.1")]
[BepInDependency("TerminalFormatter", BepInDependency.DependencyFlags.SoftDependency)]
public class Plugin : BaseUnityPlugin
{
internal const string GUID = "pacoito.StoreRotationConfig", PLUGIN_NAME = "StoreRotationConfig", VERSION = "2.3.1";
internal const string GUID = "pacoito.StoreRotationConfig", PLUGIN_NAME = "StoreRotationConfig", VERSION = "2.3.2";
internal static ManualLogSource StaticLogger { get; private set; }

/// <summary>
/// Harmony instance for patching.
/// </summary>
internal static Harmony Harmony { get; private set; }

/// <summary>
/// Plugin configuration instance.
/// </summary>
Expand Down Expand Up @@ -47,8 +53,18 @@ private void Awake()

try
{
// Initialize 'Config' and 'Harmony' instances.
Settings = new(Config);
_ = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), $"{GUID}");
Harmony = new(GUID);
//

// Apply all patches, except for compatibility ones.
Harmony.PatchAll(typeof(RotateShipDecorSelectionPatch));
Harmony.PatchAll(typeof(SyncShipUnlockablesPatch));
Harmony.PatchAll(typeof(TerminalItemSalesPatches));
Harmony.PatchAll(typeof(TerminalScrollMousePatch));
Harmony.PatchAll(typeof(UnlockShipObjectPatches));
// ...

StaticLogger.LogInfo($"{PLUGIN_NAME} loaded!");
}
Expand Down
6 changes: 5 additions & 1 deletion StoreRotationConfig/StoreRotationConfig.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<AssemblyName>StoreRotationConfig</AssemblyName>
<Description>Configure the number of items in each store rotation, show them all, remove purchases, sort them, and/or enable sales for them.</Description>
<Version>2.3.1</Version>
<Version>2.3.2</Version>
</PropertyGroup>

<!-- Project properties. -->
Expand Down Expand Up @@ -46,6 +46,10 @@
<Reference Include="Unity.Netcode.Runtime">
<HintPath>managed\Unity.Netcode.Runtime.dll</HintPath>
</Reference>
<!-- Compatibility with other mods. -->
<Reference Include="TerminalFormatter">
<HintPath>managed\TerminalFormatter.dll</HintPath>
</Reference>
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework.TrimEnd(`0123456789`))' == 'net'">
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "StoreRotationConfig",
"version_number": "2.3.1",
"version_number": "2.3.2",
"website_url": "https://github.com/pacoito123/LC_StoreRotationConfig",
"description": "Configure the number of items in each store rotation, show them all, remove purchases, sort them, and/or enable sales for them. Also includes a fix for the terminal scrolling too far and skipping lines.",
"dependencies": [
Expand Down

0 comments on commit 8c1b01d

Please sign in to comment.