Skip to content

Commit

Permalink
add configuration synchronization (#28)
Browse files Browse the repository at this point in the history
Release-as: 1.4.4
  • Loading branch information
Hypick122 committed Mar 4, 2024
1 parent 18516b1 commit 12a50d4
Show file tree
Hide file tree
Showing 5 changed files with 122 additions and 22 deletions.
3 changes: 3 additions & 0 deletions BetterShotgun/BetterShotgun.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@
<Reference Include="Unity.InputSystem">
<HintPath>..\Lib\Unity.InputSystem.dll</HintPath>
</Reference>
<Reference Include="Unity.Collections">
<HintPath>..\Lib\Unity.Collections.dll</HintPath>
</Reference>
</ItemGroup>

<!-- https://github.com/EvaisaDev/UnityNetcodePatcher#usage-as-a-post-build-event -->
Expand Down
32 changes: 16 additions & 16 deletions BetterShotgun/Patches/ShotgunItemPatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ internal class ShotgunItemPatch
[HarmonyPrefix]
public static void Update(ShotgunItem __instance)
{
if (Plugin.Config.MisfireOff && !__instance.safetyOn)
if (Config.Instance.MisfireOff && !__instance.safetyOn)
{
__instance.hasHitGroundWithSafetyOff = true;
__instance.misfireTimer = float.MaxValue;
Expand All @@ -31,7 +31,7 @@ public static void Update(ShotgunItem __instance)
[HarmonyPrefix]
public static void ItemActivate(ShotgunItem __instance)
{
if (Plugin.Config.InfiniteAmmo)
if (Config.Instance.InfiniteAmmo)
__instance.shellsLoaded = int.MaxValue;
}

Expand Down Expand Up @@ -59,19 +59,19 @@ public static void SetSafetyControlTip(ShotgunItem __instance)
[HarmonyPostfix]
public static void UpdateControlTipsForItem(ShotgunItem __instance)
{
if (Plugin.Config.ShowAmmoCount)
if (Config.Default.ShowAmmoCount)
__instance.SetSafetyControlTip();
}

private static string GetCustomTooltip(ShotgunItem item)
{
var newToolTips = Plugin.Config.AmmoCheckAnimation ? "Reload / Check" : "Reload";
var newToolTips = Config.Default.AmmoCheckAnimation ? "Reload / Check" : "Reload";

if (!Plugin.Config.ShowAmmoCount)
if (!Config.Default.ShowAmmoCount)
return $"{newToolTips}: [{Plugin.InputActionsInstance.ReloadKey.GetBindingDisplayString()}]";

var maxAmmo = Plugin.Config.ReloadNoLimit ? "" : "2";
var ammoInfo = Plugin.Config.InfiniteAmmo ? "" : $"{item.shellsLoaded}/{maxAmmo}";
var maxAmmo = Config.Instance.ReloadNoLimit ? "" : "2";
var ammoInfo = Config.Instance.InfiniteAmmo ? "" : $"{item.shellsLoaded}/{maxAmmo}";

return $"{newToolTips} ({ammoInfo}): [{Plugin.InputActionsInstance.ReloadKey.GetBindingDisplayString()}]";
}
Expand Down Expand Up @@ -114,7 +114,7 @@ public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstructio
var found = false;
foreach (var instruction in instructions)
{
if (Plugin.Config.DisableFriendlyFire && !found && instruction.ToString().Contains("playerHeldBy"))
if (Config.Instance.DisableFriendlyFire && !found && instruction.ToString().Contains("playerHeldBy"))
{
found = true;
yield return new CodeInstruction(OpCodes.Ldarg_0);
Expand All @@ -138,10 +138,10 @@ private static bool CheckFriendly(ShotgunItem __instance)
[HarmonyPrefix]
public static bool ItemInteractLeftRight(ShotgunItem __instance, bool right)
{
if (Plugin.Config.ReloadKeybind.ToLower() != "e" && right)
if (Config.Default.ReloadKeybind.ToLower() != "e" && right)
return false;

if (Plugin.Config.ReloadNoLimit && right && !__instance.isReloading)
if (Config.Instance.ReloadNoLimit && right && !__instance.isReloading)
{
__instance.StartReloadGun();
return false;
Expand All @@ -154,8 +154,8 @@ public static bool ItemInteractLeftRight(ShotgunItem __instance, bool right)
[HarmonyPrefix]
public static bool StartReloadGun(ShotgunItem __instance)
{
if ((Plugin.Config.AmmoCheckAnimation && !__instance.ReloadedGun()) || (Plugin.Config.AmmoCheckAnimation &&
!Plugin.Config.ReloadNoLimit && !Plugin.Config.InfiniteAmmo && __instance.shellsLoaded >= 2))
if ((Config.Default.AmmoCheckAnimation && !__instance.ReloadedGun()) || (Config.Default.AmmoCheckAnimation &&
!Config.Instance.ReloadNoLimit && !Config.Instance.InfiniteAmmo && __instance.shellsLoaded >= 2))
{
if (__instance.gunCoroutine != null)
__instance.StopCoroutine(__instance.gunCoroutine);
Expand All @@ -164,7 +164,7 @@ public static bool StartReloadGun(ShotgunItem __instance)
return false;
}

if (Plugin.Config.InfiniteAmmo && __instance.ReloadedGun())
if (Config.Instance.InfiniteAmmo && __instance.ReloadedGun())
return false;

return __instance.IsOwner;
Expand Down Expand Up @@ -194,7 +194,7 @@ private static IEnumerator CheckAmmoAnimation(ShotgunItem __instance)

private static IEnumerator ReloadGunAnimationCustom(ShotgunItem __instance)
{
if (!Plugin.Config.SkipReloadAnimation)
if (!Config.Instance.SkipReloadAnimation)
{
__instance.isReloading = true;
if (__instance.shellsLoaded <= 0)
Expand Down Expand Up @@ -227,7 +227,7 @@ private static IEnumerator ReloadGunAnimationCustom(ShotgunItem __instance)
__instance.playerHeldBy.DestroyItemInSlotAndSync(__instance.ammoSlotToUse);
__instance.ammoSlotToUse = -1;

if (Plugin.Config.ReloadNoLimit)
if (Config.Instance.ReloadNoLimit)
__instance.shellsLoaded++;
else
__instance.shellsLoaded = Mathf.Clamp(__instance.shellsLoaded + 1, 0, 2);
Expand Down Expand Up @@ -255,7 +255,7 @@ private static IEnumerator ReloadGunAnimationCustom(ShotgunItem __instance)
__instance.playerHeldBy.DestroyItemInSlotAndSync(__instance.ammoSlotToUse);
__instance.ammoSlotToUse = -1;

if (Plugin.Config.ReloadNoLimit)
if (Config.Instance.ReloadNoLimit)
__instance.shellsLoaded++;
else
__instance.shellsLoaded = Mathf.Clamp(__instance.shellsLoaded + 1, 0, 2);
Expand Down
29 changes: 29 additions & 0 deletions BetterShotgun/Patches/SyncConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using GameNetcodeStuff;
using HarmonyLib;

namespace Hypick.Patches;

[HarmonyPatch]
public class SyncConfig
{
[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
[HarmonyPostfix]
public static void InitializeLocalPlayer() {
if (Config.IsHost) {
Config.MessageManager.RegisterNamedMessageHandler("BetterShotgun_OnRequestConfigSync", Config.OnRequestSync);
Config.Synced = true;

return;
}

Config.Synced = false;
Config.MessageManager.RegisterNamedMessageHandler("BetterShotgun_OnReceiveConfigSync", Config.OnReceiveSync);
Config.RequestSync();
}

[HarmonyPostfix]
[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
public static void PlayerLeave() {
Config.RevertSync();
}
}
14 changes: 8 additions & 6 deletions BetterShotgun/Plugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class Plugin : BaseUnityPlugin

public static ManualLogSource Log => Instance.Logger;

public new static PluginConfig Config;
public new static Config Config;

Check failure on line 24 in BetterShotgun/Plugin.cs

View workflow job for this annotation

GitHub Actions / Build

The type or namespace name 'Config' could not be found (are you missing a using directive or an assembly reference?)

Check failure on line 24 in BetterShotgun/Plugin.cs

View workflow job for this annotation

GitHub Actions / Build

The type or namespace name 'Config' could not be found (are you missing a using directive or an assembly reference?)

private readonly Harmony _harmony = new(MyPluginInfo.PLUGIN_GUID);

Expand All @@ -42,7 +42,7 @@ public class Plugin : BaseUnityPlugin

private void Awake()
{
Config = new PluginConfig(base.Config);
Config = new Config(base.Config);

SceneManager.sceneLoaded += OnSceneLoaded;

Expand Down Expand Up @@ -102,10 +102,12 @@ private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
"ReservedWeaponSlot detected, the name of the cartridges changes from \"Shell\" to \"Ammo\"");
}

RegisterItem(Shotgun, "Shotgun", Config.ShotgunMaxDiscount, Config.ShotgunMinValue,
Config.ShotgunMaxValue, Config.ShotgunWeight, Config.ShotgunPrice, Config.ShotgunRarity);
RegisterItem(ShotgunShell, ammoName, Config.ShellMaxDiscount, Config.ShellMinValue, Config.ShellMaxValue, 0,
Config.ShellPrice, Config.ShellRarity);
RegisterItem(Shotgun, "Shotgun", Config.Instance.ShotgunMaxDiscount, Config.Instance.ShotgunMinValue,
Config.Instance.ShotgunMaxValue, Config.Instance.ShotgunWeight, Config.Instance.ShotgunPrice,
Config.Instance.ShotgunRarity);
RegisterItem(ShotgunShell, ammoName, Config.Instance.ShellMaxDiscount, Config.Instance.ShellMinValue,
Config.Instance.ShellMaxValue, 0,
Config.Instance.ShellPrice, Config.Instance.ShellRarity);
}
}

Expand Down
66 changes: 66 additions & 0 deletions BetterShotgun/SyncedInstance.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Unity.Netcode;

namespace Hypick;

[Serializable]
public class SyncedInstance<T> {
internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager;
internal static bool IsClient => NetworkManager.Singleton.IsClient;
internal static bool IsHost => NetworkManager.Singleton.IsHost;

[NonSerialized]
protected static int IntSize = 4;

public static T Default { get; private set; }
public static T Instance { get; private set; }

public static bool Synced { get; internal set; }

protected void InitInstance(T instance) {
Default = instance;
Instance = instance;

// Makes sure the size of an integer is correct for the current system.
// We use 4 by default as that's the size of an int on 32 and 64 bit systems.
IntSize = sizeof(int);
}

internal static void SyncInstance(byte[] data) {
Instance = DeserializeFromBytes(data);
Synced = true;
}

internal static void RevertSync() {
Instance = Default;
Synced = false;
}

public static byte[] SerializeToBytes(T val) {
BinaryFormatter bf = new();
using MemoryStream stream = new();

try {
bf.Serialize(stream, val);
return stream.ToArray();
}
catch (Exception e) {
Plugin.Log.LogError($"Error serializing instance: {e}");
return null;
}
}

public static T DeserializeFromBytes(byte[] data) {
BinaryFormatter bf = new();
using MemoryStream stream = new(data);

try {
return (T) bf.Deserialize(stream);
} catch (Exception e) {
Plugin.Log.LogError($"Error deserializing instance: {e}");
return default;
}
}
}

0 comments on commit 12a50d4

Please sign in to comment.