using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("MuckDio")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Adds Risk of Rain 2's Dio's Best Friend (consumable extra life) to Muck as an Orange powerup.")]
[assembly: AssemblyFileVersion("0.1.1.0")]
[assembly: AssemblyInformationalVersion("0.1.1+879fc7ac66fec639f2f84b4b7a65d5c61c9ed734")]
[assembly: AssemblyProduct("Dio's Best Friend")]
[assembly: AssemblyTitle("MuckDio")]
[assembly: InternalsVisibleTo("MuckDio.Tests")]
[assembly: AssemblyVersion("0.1.1.0")]
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[Embedded]
internal sealed class IsReadOnlyAttribute : Attribute
{
}
}
namespace MuckDio
{
[HarmonyPatch(typeof(PlayerStatus), "HandleDamage", new Type[]
{
typeof(int),
typeof(int),
typeof(bool),
typeof(int)
})]
internal static class DamageGatePatch
{
[HarmonyPrefix]
private static bool Prefix()
{
try
{
bool isKillCommand = DioState.KillCommandFrame == Time.frameCount;
return DioRules.AllowDamage(DioState.Window.IsActive(Time.time), isKillCommand, DioPlugin.Cfg.KillCommandBypassesDio.Value);
}
catch
{
return true;
}
}
}
[HarmonyPatch(typeof(PlayerStatus), "PlayerDied", new Type[]
{
typeof(int),
typeof(int)
})]
internal static class DeathPatch
{
[HarmonyPrefix]
[HarmonyPriority(200)]
private static bool Prefix(PlayerStatus __instance)
{
try
{
DeathOutcome deathOutcome = DioRules.Decide(DioPowerup.LocalStacks(), __instance.hp, DioState.KillCommandFrame == Time.frameCount, DioPlugin.Cfg.KillCommandBypassesDio.Value);
if (deathOutcome != DeathOutcome.Revive)
{
if (DioPlugin.Cfg.VerboseLogging.Value)
{
DioPlugin.Log.LogInfo((object)$"Dio left this death alone: {deathOutcome}.");
}
return true;
}
return !DioRevive.Apply(__instance);
}
catch (Exception arg)
{
DioPlugin.Log.LogError((object)$"Dio death patch failed; vanilla death will run. {arg}");
return true;
}
}
}
internal sealed class DioConfig
{
public readonly ConfigEntry<float> InvulnerabilitySeconds;
public readonly ConfigEntry<float> ReviveHealthFraction;
public readonly ConfigEntry<bool> RefillHungerAndStamina;
public readonly ConfigEntry<bool> KillCommandBypassesDio;
public readonly ConfigEntry<bool> AnnounceInChat;
public readonly ConfigEntry<bool> ShowReviveEffect;
public readonly ConfigEntry<KeyboardShortcut> GiveDioKey;
public readonly ConfigEntry<bool> VerboseLogging;
public DioConfig(ConfigFile cfg)
{
//IL_0030: Unknown result type (might be due to invalid IL or missing references)
//IL_003a: Expected O, but got Unknown
//IL_0069: Unknown result type (might be due to invalid IL or missing references)
//IL_0073: Expected O, but got Unknown
//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
InvulnerabilitySeconds = cfg.Bind<float>("Dios Best Friend", "InvulnerabilitySeconds", 3f, new ConfigDescription("Seconds of invulnerability after this item revives you (0-30). Values below 0.1 still protect you for 0.1 seconds, so a second hit in the same frame cannot spend another stack. Only affects your own revives.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 30f), Array.Empty<object>()));
ReviveHealthFraction = cfg.Bind<float>("Dios Best Friend", "ReviveHealthFraction", 1f, new ConfigDescription("Fraction of max health and shield restored on revive (0-1). 0 restores 1 health. Only affects your own revives.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
RefillHungerAndStamina = cfg.Bind<bool>("Dios Best Friend", "RefillHungerAndStamina", true, "Restore hunger and stamina to max on revive. Only affects your own revives.");
KillCommandBypassesDio = cfg.Bind<bool>("Dios Best Friend", "KillCommandBypassesDio", true, "If true, /kill is a real death and does not consume this item, including during the invulnerability window. Only affects your own revives.");
AnnounceInChat = cfg.Bind<bool>("Dios Best Friend", "AnnounceInChat", true, "Send a chat line when this item revives you. Only affects your own revives.");
ShowReviveEffect = cfg.Bind<bool>("Visuals", "ShowReviveEffect", true, "Play a gold particle burst on revive. The burst is local. Only affects your own revives.");
GiveDioKey = cfg.Bind<KeyboardShortcut>("Debug", "GiveDioKey", KeyboardShortcut.Empty, "Press in-game to give yourself one stack. Solo testing only. The host's copy of your powerups is not updated. Empty disables it. Only affects your own revives.");
VerboseLogging = cfg.Bind<bool>("Debug", "VerboseLogging", false, "Log death decisions that do not revive, and the full powerup id table. Only affects your own revives.");
InvulnerabilitySeconds.SettingChanged += delegate
{
RefreshDescription();
};
ReviveHealthFraction.SettingChanged += delegate
{
RefreshDescription();
};
}
private static void RefreshDescription()
{
if ((Object)(object)DioPowerup.Definition != (Object)null)
{
DioPowerup.Definition.description = DioRules.Description(DioPlugin.Cfg.InvulnerabilitySeconds.Value, DioPlugin.Cfg.ReviveHealthFraction.Value);
}
}
}
[BepInPlugin("evan.muck.diosbestfriend", "Dio's Best Friend", "0.1.1")]
public class DioPlugin : BaseUnityPlugin
{
public const string Guid = "evan.muck.diosbestfriend";
public const string Name = "Dio's Best Friend";
public const string Version = "0.1.1";
internal static ManualLogSource Log;
internal static DioConfig Cfg;
private void Awake()
{
//IL_0047: Unknown result type (might be due to invalid IL or missing references)
//IL_004d: Expected O, but got Unknown
Log = ((BaseUnityPlugin)this).Logger;
Cfg = new DioConfig(((BaseUnityPlugin)this).Config);
try
{
DioPowerup.Create();
}
catch (Exception arg)
{
Log.LogError((object)string.Format("{0} disabled: creating the powerup failed. {1}", "Dio's Best Friend", arg));
return;
}
Harmony harmony = new Harmony("evan.muck.diosbestfriend");
if (!TryPatch(harmony, typeof(DeathPatch)))
{
Log.LogError((object)"Dio's Best Friend disabled: death patch failed. The powerup will not drop.");
return;
}
if (!TryPatch(harmony, typeof(DamageGatePatch)))
{
Log.LogError((object)"Dio's Best Friend disabled: damage gate patch failed. The powerup will not drop.");
return;
}
if (!TryPatch(harmony, typeof(RegisterDioPatch)))
{
Log.LogError((object)"Dio's Best Friend disabled: registration patch failed. The powerup will not drop.");
return;
}
if (!TryPatch(harmony, typeof(KillCommandPatch)))
{
Log.LogWarning((object)"Dio's Best Friend: the /kill patch failed, so /kill will consume a Dio.");
}
DioRunner.Ensure();
Log.LogInfo((object)"Dio's Best Friend 0.1.1 loaded. Every player needs this mod and the same set of powerup mods.");
Log.LogInfo((object)("Config: invulnerability " + Cfg.InvulnerabilitySeconds.Value.ToString("0.##", CultureInfo.InvariantCulture) + "s, health " + Cfg.ReviveHealthFraction.Value.ToString("0.##", CultureInfo.InvariantCulture) + ", refill hunger and stamina " + Cfg.RefillHungerAndStamina.Value + ", kill bypass " + Cfg.KillCommandBypassesDio.Value + ", chat " + Cfg.AnnounceInChat.Value + ", effect " + Cfg.ShowReviveEffect.Value + "."));
}
private static bool TryPatch(Harmony harmony, Type patchClass)
{
try
{
harmony.CreateClassProcessor(patchClass).Patch();
return true;
}
catch (Exception arg)
{
Log.LogError((object)string.Format("{0} failed to patch {1}: {2}", "Dio's Best Friend", patchClass.Name, arg));
return false;
}
}
}
internal static class DioPowerup
{
public const string PowerupName = "Dio's Best Friend";
private static FieldRef<PowerupInventory, int[]> _counts;
private static bool _countsFailed;
public static Powerup Definition { get; private set; }
public static int Id { get; internal set; } = -1;
public static void Create()
{
//IL_0046: Unknown result type (might be due to invalid IL or missing references)
Powerup obj = ScriptableObject.CreateInstance<Powerup>();
obj.name = "Dio's Best Friend";
((Object)obj).name = "Dio's Best Friend";
obj.description = DioRules.Description(DioPlugin.Cfg.InvulnerabilitySeconds.Value, DioPlugin.Cfg.ReviveHealthFraction.Value);
obj.tier = (PowerTier)2;
obj.sprite = LoadIcon();
((Object)obj).hideFlags = (HideFlags)32;
Definition = obj;
}
internal static int[] Counts()
{
PowerupInventory instance = PowerupInventory.Instance;
if ((Object)(object)instance == (Object)null || _countsFailed)
{
return null;
}
if (_counts == null)
{
try
{
_counts = AccessTools.FieldRefAccess<PowerupInventory, int[]>("powerups");
}
catch (Exception arg)
{
_countsFailed = true;
DioPlugin.Log.LogError((object)$"Dio cannot read powerup stacks (PowerupInventory.powerups): {arg}");
return null;
}
}
return _counts.Invoke(instance);
}
public static int LocalStacks()
{
int[] array = Counts();
if (array == null || Id < 0 || Id >= array.Length)
{
return 0;
}
return array[Id];
}
public static void GiveOneLocal()
{
int[] array = Counts();
if (array == null || Id < 0 || Id >= array.Length)
{
DioPlugin.Log.LogWarning((object)"Can't give Dio's Best Friend: not in a game yet, or the powerup isn't registered.");
return;
}
if ((Object)(object)PowerupUI.Instance == (Object)null || (Object)(object)PlayerStatus.Instance == (Object)null)
{
DioPlugin.Log.LogWarning((object)"Can't give Dio's Best Friend: the powerup bar or the player status is not ready.");
return;
}
array[Id]++;
PowerupUI.Instance.AddPowerup(Id);
PlayerStatus.Instance.UpdateStats();
DioPlugin.Log.LogInfo((object)$"Debug: Dio's Best Friend stacks now {array[Id]} (local only; the host's copy of your powerups is not updated).");
}
private static Sprite LoadIcon()
{
//IL_0039: Unknown result type (might be due to invalid IL or missing references)
//IL_003f: Expected O, but got Unknown
//IL_0084: Unknown result type (might be due to invalid IL or missing references)
//IL_0093: Unknown result type (might be due to invalid IL or missing references)
try
{
using Stream stream = typeof(DioPowerup).Assembly.GetManifestResourceStream("MuckDio.icon.png");
if (stream == null)
{
throw new FileNotFoundException("embedded icon.png missing");
}
using MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
if (!ImageConversion.LoadImage(val, memoryStream.ToArray()))
{
throw new InvalidDataException("icon.png failed to decode");
}
((Object)val).name = "DioIcon";
((Object)val).hideFlags = (HideFlags)32;
Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
((Object)obj).name = "DioIcon";
((Object)obj).hideFlags = (HideFlags)32;
return obj;
}
catch (Exception arg)
{
DioPlugin.Log.LogError((object)$"Failed to load Dio's Best Friend icon: {arg}");
return null;
}
}
}
[HarmonyPatch(typeof(ItemManager), "InitAllPowerups", new Type[] { })]
internal static class RegisterDioPatch
{
[HarmonyPostfix]
[HarmonyPriority(600)]
[HarmonyAfter(new string[] { "evan.muck.ukulele", "evan.muck.atgmissile", "evan.muck.crowbar", "evan.muck.stickybomb", "evan.muck.tritipdagger", "evan.muck.willothewisp", "evan.muck.devildeal", "evan.muck.shapedglass" })]
private static void Postfix(ItemManager __instance)
{
try
{
Powerup definition = DioPowerup.Definition;
if ((Object)(object)definition == (Object)null)
{
return;
}
Dictionary<int, Powerup> allPowerups = __instance.allPowerups;
Dictionary<string, int> stringToPowerupId = __instance.stringToPowerupId;
PickupArt.Apply(definition, __instance.powerupsOrange);
int value;
bool flag = stringToPowerupId.TryGetValue("Dio's Best Friend", out value);
Powerup value2;
bool existingIsOurs = flag && allPowerups.TryGetValue(value, out value2) && (Object)(object)value2 == (Object)(object)definition;
PowerupClaim powerupClaim = PowerupClaim.Resolve(flag, existingIsOurs, value, allPowerups.Keys, allPowerups.Count);
if (powerupClaim.Result != ClaimResult.Claimed)
{
DioPlugin.Log.LogError((object)$"Dio not registered: {powerupClaim.Result}");
DioPowerup.Id = -1;
return;
}
if (!flag)
{
allPowerups.Add(powerupClaim.Id, definition);
stringToPowerupId.Add("Dio's Best Friend", powerupClaim.Id);
}
definition.id = powerupClaim.Id;
if (__instance.powerupsOrange == null)
{
__instance.powerupsOrange = (Powerup[])(object)new Powerup[0];
}
if (!__instance.powerupsOrange.Contains(definition))
{
__instance.powerupsOrange = CollectionExtensions.AddToArray<Powerup>(__instance.powerupsOrange, definition);
}
DioPowerup.Id = powerupClaim.Id;
DioPlugin.Log.LogInfo((object)$"Registered Dio's Best Friend as Orange powerup id {powerupClaim.Id} ({allPowerups.Count} total, {__instance.powerupsOrange.Length} in the Orange pool).");
if (DioPlugin.Cfg.VerboseLogging.Value)
{
DioPlugin.Log.LogInfo((object)("Powerup ids: " + string.Join(", ", from kv in allPowerups
orderby kv.Key
select $"{kv.Key}={kv.Value.name}")));
}
DioPlugin.Log.LogInfo((object)("Custom powerups: " + string.Join(", ", from kv in allPowerups
where kv.Key >= 25
orderby kv.Key
select $"{kv.Key}={kv.Value.name}")));
}
catch (Exception arg)
{
DioPowerup.Id = -1;
DioPlugin.Log.LogError((object)$"Dio registration failed: {arg}");
}
}
}
internal static class DioRevive
{
public static bool Apply(PlayerStatus ps)
{
//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
int[] array;
Vitals vitals;
try
{
int num = DioPowerup.LocalStacks();
array = DioPowerup.Counts();
if (array == null || DioPowerup.Id < 0 || DioPowerup.Id >= array.Length || num <= 0)
{
return false;
}
vitals = ReviveVitals.Compute(ps.maxHp, ps.maxShield, ps.maxStamina, ps.maxHunger, ps.hunger, DioPlugin.Cfg.ReviveHealthFraction.Value, DioPlugin.Cfg.RefillHungerAndStamina.Value, ps.stamina);
ps.hp = vitals.Hp;
ps.shield = vitals.Shield;
ps.stamina = vitals.Stamina;
ps.hunger = vitals.Hunger;
array[DioPowerup.Id] = DioRules.StacksAfterRevive(num);
DioState.Window.Start(Time.time, DioPlugin.Cfg.InvulnerabilitySeconds.Value);
}
catch (Exception arg)
{
DioPlugin.Log.LogError((object)$"Dio revive failed before it finished; vanilla death will run. {arg}");
return false;
}
try
{
PowerupBar.SetCount(DioPowerup.Id, array[DioPowerup.Id]);
}
catch (Exception arg2)
{
DioPlugin.Log.LogWarning((object)$"Dio revived, but the powerup icon did not update: {arg2}");
}
try
{
ClientSend.PlayerHp(ps.HpAndShield(), ps.MaxHpAndShield());
}
catch (Exception arg3)
{
DioPlugin.Log.LogWarning((object)$"Dio revived, but the health update was not sent: {arg3}");
}
try
{
if (DioPlugin.Cfg.AnnounceInChat.Value && (Object)(object)ChatBox.Instance != (Object)null)
{
ChatBox.Instance.SendMessage("<color=orange>(Dio's Best Friend)<color=white> brought me back!");
}
}
catch (Exception arg4)
{
DioPlugin.Log.LogWarning((object)$"Dio revived, but the chat line failed: {arg4}");
}
try
{
if (DioPlugin.Cfg.ShowReviveEffect.Value && (Object)(object)PlayerMovement.Instance != (Object)null)
{
ReviveEffect.Play(((Component)PlayerMovement.Instance).transform.position + Vector3.up);
}
}
catch (Exception arg5)
{
DioPlugin.Log.LogWarning((object)$"Dio revived, but the particle burst failed: {arg5}");
}
DioPlugin.Log.LogInfo((object)$"Dio's Best Friend consumed: revived at {vitals.Hp:0}/{ps.maxHp} hp, {array[DioPowerup.Id]} left, invulnerable {DioPlugin.Cfg.InvulnerabilitySeconds.Value:0.##}s.");
return true;
}
}
internal enum DeathOutcome
{
VanillaDeath,
Revive,
AlreadySaved
}
internal static class DioRules
{
public static DeathOutcome Decide(int stacks, float hpAtEntry, bool isKillCommand, bool killCommandBypassesDio)
{
if (hpAtEntry > 0f)
{
return DeathOutcome.AlreadySaved;
}
if (isKillCommand && killCommandBypassesDio)
{
return DeathOutcome.VanillaDeath;
}
if (stacks <= 0)
{
return DeathOutcome.VanillaDeath;
}
return DeathOutcome.Revive;
}
public static int StacksAfterRevive(int stacks)
{
return Math.Max(0, stacks - 1);
}
public static bool AllowDamage(bool windowActive, bool isKillCommand, bool killCommandBypassesDio)
{
if (isKillCommand && killCommandBypassesDio)
{
return true;
}
return !windowActive;
}
public static string Description(float invulnSeconds, float healthFraction)
{
float num = ReviveVitals.Clamp01NaN1(healthFraction);
int num2 = (int)Math.Round(num * 100f, MidpointRounding.AwayFromZero);
string text = ((num <= 0f) ? "1 health" : $"{num2}% health");
float num3 = InvulnWindow.EffectiveSeconds(invulnSeconds);
if (float.IsNaN(num3))
{
num3 = 0.1f;
}
string text2 = num3.ToString("0.##", CultureInfo.InvariantCulture);
string text3 = ((num3 == 1f) ? "second" : "seconds");
return "Upon death, this item will be consumed and you will return to life with " + text + " and " + text2 + " " + text3 + " of invulnerability.";
}
}
internal sealed class DioRunner : MonoBehaviour
{
private static DioRunner _instance;
private static bool _sceneHooked;
public static void Ensure()
{
//IL_0044: Unknown result type (might be due to invalid IL or missing references)
//IL_0049: Unknown result type (might be due to invalid IL or missing references)
//IL_0051: Unknown result type (might be due to invalid IL or missing references)
//IL_0057: Expected O, but got Unknown
if (!_sceneHooked)
{
SceneManager.activeSceneChanged += delegate
{
DioState.Window.Reset();
};
_sceneHooked = true;
}
if (!((Object)(object)_instance != (Object)null))
{
GameObject val = new GameObject("MuckDio")
{
hideFlags = (HideFlags)61
};
Object.DontDestroyOnLoad((Object)val);
_instance = val.AddComponent<DioRunner>();
}
}
private void Update()
{
//IL_000a: Unknown result type (might be due to invalid IL or missing references)
//IL_000f: Unknown result type (might be due to invalid IL or missing references)
KeyboardShortcut value = DioPlugin.Cfg.GiveDioKey.Value;
if (((KeyboardShortcut)(ref value)).IsDown())
{
DioPowerup.GiveOneLocal();
}
if (DioState.Window.ConsumeEnded(Time.time) && (Object)(object)PlayerStatus.Instance != (Object)null)
{
try
{
ClientSend.PlayerHp(PlayerStatus.Instance.HpAndShield(), PlayerStatus.Instance.MaxHpAndShield());
}
catch (Exception arg)
{
DioPlugin.Log.LogWarning((object)$"Dio failed to resend health when invulnerability ended: {arg}");
}
}
}
}
internal static class DioState
{
internal static readonly InvulnWindow Window = new InvulnWindow();
internal static int KillCommandFrame = -1;
}
internal sealed class InvulnWindow
{
internal const float MinimumSeconds = 0.1f;
private bool _pendingEnd;
public float Until { get; private set; }
public static float EffectiveSeconds(float configured)
{
if (float.IsNaN(configured))
{
return float.NaN;
}
return Math.Max(configured, 0.1f);
}
public void Start(float now, float duration)
{
float num = EffectiveSeconds(duration);
if (!float.IsNaN(num))
{
Until = Math.Max(Until, now + num);
_pendingEnd = true;
}
}
public bool IsActive(float now)
{
return now < Until;
}
public bool ConsumeEnded(float now)
{
if (_pendingEnd && now >= Until)
{
_pendingEnd = false;
return true;
}
return false;
}
public void Reset()
{
Until = 0f;
_pendingEnd = false;
}
}
internal static class KillCommand
{
public static bool IsKill(string message)
{
if (string.IsNullOrEmpty(message))
{
return false;
}
string text = message.Split(new char[1] { ' ' })[0];
if (text.Length >= 1)
{
return text.Substring(1) == "kill";
}
return false;
}
}
[HarmonyPatch(typeof(ChatBox), "ChatCommand", new Type[] { typeof(string) })]
internal static class KillCommandPatch
{
[HarmonyPrefix]
private static void Prefix(string __0)
{
try
{
if (KillCommand.IsKill(__0))
{
DioState.KillCommandFrame = Time.frameCount;
}
}
catch
{
}
}
}
internal static class PickupArt
{
public const string ObjResource = "MuckDio.pickup.obj";
public const string JsonResource = "MuckDio.pickup.json";
public static void Apply(Powerup powerup, Powerup[] pool)
{
if ((Object)(object)powerup == (Object)null || (Object)(object)powerup.mesh != (Object)null)
{
return;
}
Powerup val = Donor(pool, powerup);
try
{
PickupMesh data = PickupMesh.From(PickupModel.Parse(Read("MuckDio.pickup.obj"), Read("MuckDio.pickup.json")));
Material val2 = (((Object)(object)val != (Object)null) ? val.material : null);
if ((Object)(object)val2 == (Object)null)
{
val2 = FallbackShader();
}
bool vertexColors = (Object)(object)val2 == (Object)null || !val2.HasProperty("_MainTex");
powerup.mesh = ToMesh(data, powerup.name, vertexColors);
powerup.material = ToMaterial(data, val2, powerup.name);
}
catch (Exception ex)
{
DioPlugin.Log.LogWarning((object)("Dio's Best Friend pickup model was not applied (" + ex.Message + ")."));
if ((Object)(object)val != (Object)null && (Object)(object)val.mesh != (Object)null)
{
powerup.mesh = val.mesh;
powerup.material = val.material;
}
else
{
DioPlugin.Log.LogWarning((object)"No Orange powerup to borrow a pickup model from; dropped Dio's Best Friend will be invisible.");
}
}
}
private static Powerup Donor(Powerup[] pool, Powerup self)
{
if (pool == null)
{
return null;
}
Powerup val = null;
foreach (Powerup val2 in pool)
{
if (!((Object)(object)val2 == (Object)null) && val2 != self)
{
if ((Object)(object)val2.material != (Object)null)
{
return val2;
}
if ((Object)(object)val == (Object)null && (Object)(object)val2.mesh != (Object)null)
{
val = val2;
}
}
}
return val;
}
private static string Read(string name)
{
using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name);
if (stream == null)
{
throw new FileNotFoundException(name);
}
using StreamReader streamReader = new StreamReader(stream);
return streamReader.ReadToEnd();
}
private static Mesh ToMesh(PickupMesh data, string itemName, bool vertexColors)
{
//IL_0000: Unknown result type (might be due to invalid IL or missing references)
//IL_0005: Unknown result type (might be due to invalid IL or missing references)
//IL_0016: Unknown result type (might be due to invalid IL or missing references)
//IL_001f: Expected O, but got Unknown
//IL_0097: Unknown result type (might be due to invalid IL or missing references)
//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
//IL_0127: Unknown result type (might be due to invalid IL or missing references)
//IL_0100: Unknown result type (might be due to invalid IL or missing references)
Mesh val = new Mesh
{
name = itemName + " pickup",
hideFlags = (HideFlags)32
};
List<Vector3> list = new List<Vector3>(data.Positions.Length);
List<Vector3> list2 = new List<Vector3>(data.Normals.Length);
List<Vector2> list3 = new List<Vector2>(data.U.Length);
List<Color> list4 = new List<Color>(data.Positions.Length);
for (int i = 0; i < data.Positions.Length; i++)
{
list.Add(new Vector3(data.Positions[i].X, data.Positions[i].Y, data.Positions[i].Z));
list2.Add(new Vector3(data.Normals[i].X, data.Normals[i].Y, data.Normals[i].Z));
list3.Add(new Vector2(data.U[i], 0.5f));
list4.Add((Color)(vertexColors ? new Color(data.R[i], data.G[i], data.B[i], 1f) : Color.white));
}
val.SetVertices(list);
val.SetNormals(list2);
val.SetUVs(0, list3);
val.SetColors(list4);
val.SetTriangles(data.Triangles, 0);
val.RecalculateBounds();
return val;
}
private static Material FallbackShader()
{
//IL_002b: Unknown result type (might be due to invalid IL or missing references)
//IL_0031: Expected O, but got Unknown
Shader val = Shader.Find("Standard");
if ((Object)(object)val == (Object)null)
{
val = Shader.Find("Diffuse");
}
if (!((Object)(object)val != (Object)null))
{
return null;
}
return new Material(val);
}
private static Material ToMaterial(PickupMesh data, Material source, string itemName)
{
//IL_0075: Unknown result type (might be due to invalid IL or missing references)
//IL_007a: Unknown result type (might be due to invalid IL or missing references)
//IL_008b: Unknown result type (might be due to invalid IL or missing references)
//IL_0092: Unknown result type (might be due to invalid IL or missing references)
//IL_0099: Unknown result type (might be due to invalid IL or missing references)
//IL_00a2: Expected O, but got Unknown
//IL_0026: Unknown result type (might be due to invalid IL or missing references)
//IL_002b: Unknown result type (might be due to invalid IL or missing references)
//IL_003c: Unknown result type (might be due to invalid IL or missing references)
//IL_0054: Unknown result type (might be due to invalid IL or missing references)
//IL_005e: Unknown result type (might be due to invalid IL or missing references)
//IL_0067: Expected O, but got Unknown
//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
//IL_010c: Unknown result type (might be due to invalid IL or missing references)
//IL_0115: Expected O, but got Unknown
//IL_011d: Unknown result type (might be due to invalid IL or missing references)
//IL_0128: Unknown result type (might be due to invalid IL or missing references)
//IL_0140: Unknown result type (might be due to invalid IL or missing references)
if ((Object)(object)source == (Object)null)
{
return null;
}
if (!source.HasProperty("_MainTex"))
{
MaterialSpec materialSpec = data.Palette[0];
return new Material(source)
{
name = itemName + " pickup",
color = new Color(materialSpec.R, materialSpec.G, materialSpec.B, 1f),
hideFlags = (HideFlags)32
};
}
Texture2D val = new Texture2D(data.Palette.Count, 1, (TextureFormat)4, false)
{
name = itemName + " palette",
filterMode = (FilterMode)0,
wrapMode = (TextureWrapMode)1,
hideFlags = (HideFlags)32
};
for (int i = 0; i < data.Palette.Count; i++)
{
MaterialSpec materialSpec2 = data.Palette[i];
val.SetPixel(i, 0, new Color(materialSpec2.R, materialSpec2.G, materialSpec2.B, 1f));
}
val.Apply(false, true);
Material val2 = new Material(source)
{
name = itemName + " pickup",
hideFlags = (HideFlags)32
};
val2.mainTexture = (Texture)(object)val;
val2.mainTextureScale = Vector2.one;
val2.mainTextureOffset = Vector2.zero;
if (val2.HasProperty("_Color"))
{
val2.color = Color.white;
}
return val2;
}
}
internal readonly struct Vec3
{
public readonly float X;
public readonly float Y;
public readonly float Z;
public Vec3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public static Vec3 operator -(Vec3 a, Vec3 b)
{
return new Vec3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
}
}
internal readonly struct MaterialSpec
{
public readonly float R;
public readonly float G;
public readonly float B;
public readonly float Emission;
public MaterialSpec(float r, float g, float b, float emission)
{
R = r;
G = g;
B = b;
Emission = emission;
}
}
internal sealed class SubMesh
{
public readonly string Material;
public readonly int[] Triangles;
public SubMesh(string material, int[] triangles)
{
Material = material;
Triangles = triangles;
}
}
internal sealed class PickupModel
{
private sealed class ObjObject
{
public readonly List<Vec3> Positions = new List<Vec3>();
public readonly List<Vec3> Normals = new List<Vec3>();
public readonly List<string> MaterialOrder = new List<string>();
public readonly Dictionary<string, List<int>> Triangles = new Dictionary<string, List<int>>();
}
public readonly string Name;
public readonly Vec3[] Positions;
public readonly Vec3[] Normals;
public readonly IReadOnlyList<SubMesh> SubMeshes;
public readonly IReadOnlyDictionary<string, MaterialSpec> Materials;
public int TriangleCount => Positions.Length / 3;
public PickupModel(string name, Vec3[] positions, Vec3[] normals, IReadOnlyList<SubMesh> subMeshes, IReadOnlyDictionary<string, MaterialSpec> materials)
{
Name = name;
Positions = positions;
Normals = normals;
SubMeshes = subMeshes;
Materials = materials;
}
public static PickupModel Parse(string objText, string json)
{
if (!(JsonReader.Parse(json) is Dictionary<string, object> obj))
{
throw new FormatException("pickup json: top level is not an object.");
}
string text = Str(obj, "name");
Dictionary<string, MaterialSpec> dictionary = ReadMaterials(Obj(obj, "materials"));
Dictionary<string, ObjObject> dictionary2 = ReadObj(objText, text);
if (dictionary2.Count != 1)
{
throw new FormatException($"{text}: a pickup OBJ needs exactly one object, it has {dictionary2.Count}.");
}
ObjObject objObject = null;
foreach (ObjObject value in dictionary2.Values)
{
objObject = value;
}
List<SubMesh> list = new List<SubMesh>();
foreach (string item in objObject.MaterialOrder)
{
if (!dictionary.ContainsKey(item))
{
throw new FormatException(text + ": uses undefined material '" + item + "'.");
}
list.Add(new SubMesh(item, objObject.Triangles[item].ToArray()));
}
PickupModel pickupModel = new PickupModel(text, objObject.Positions.ToArray(), objObject.Normals.ToArray(), list, dictionary);
int num = (int)Num(obj, "tris");
if (pickupModel.TriangleCount != num)
{
throw new FormatException($"{text}: OBJ has {pickupModel.TriangleCount} triangles, the json says {num}.");
}
return pickupModel;
}
private static Dictionary<string, ObjObject> ReadObj(string text, string name)
{
if (text == null)
{
throw new FormatException(name + ": OBJ text is null.");
}
List<Vec3> list = new List<Vec3>();
List<Vec3> list2 = new List<Vec3>();
Dictionary<string, ObjObject> dictionary = new Dictionary<string, ObjObject>();
ObjObject objObject = null;
string text2 = null;
string[] array = text.Split(new char[1] { '\n' });
for (int i = 0; i < array.Length; i++)
{
string[] array2 = array[i].Trim().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
if (array2.Length == 0)
{
continue;
}
switch (array2[0])
{
case "v":
{
Vec3 vec2 = ReadVec(array2, name, i);
list.Add(new Vec3(0f - vec2.X, vec2.Y, vec2.Z));
break;
}
case "vn":
{
Vec3 vec = ReadVec(array2, name, i);
list2.Add(new Vec3(0f - vec.X, vec.Y, vec.Z));
break;
}
case "o":
{
string text3 = string.Join(" ", array2, 1, array2.Length - 1);
if (dictionary.ContainsKey(text3))
{
throw new FormatException(name + ": OBJ object " + text3 + " appears twice.");
}
objObject = new ObjObject();
dictionary.Add(text3, objObject);
text2 = null;
break;
}
case "usemtl":
text2 = ((array2.Length > 1) ? array2[1] : null);
break;
case "f":
if (objObject == null || text2 == null)
{
throw new FormatException($"{name}: OBJ line {i + 1} has a face outside an object or material.");
}
if (array2.Length != 4)
{
throw new FormatException($"{name}: OBJ line {i + 1} is not a triangle.");
}
AddTriangle(objObject, text2, list, list2, array2, name, i);
break;
}
}
return dictionary;
}
private static void AddTriangle(ObjObject obj, string material, List<Vec3> vertices, List<Vec3> normals, string[] tokens, string name, int line)
{
if (!obj.Triangles.TryGetValue(material, out var value))
{
value = new List<int>();
obj.Triangles.Add(material, value);
obj.MaterialOrder.Add(material);
}
int[] array = new int[3] { 1, 3, 2 };
foreach (int num in array)
{
string[] array2 = tokens[num].Split(new char[1] { '/' });
Vec3 item = vertices[Index(array2[0], vertices.Count, name, line)];
if (array2.Length < 3 || array2[2].Length == 0)
{
throw new FormatException($"{name}: OBJ line {line + 1} has a corner without a normal.");
}
value.Add(obj.Positions.Count);
obj.Positions.Add(item);
obj.Normals.Add(normals[Index(array2[2], normals.Count, name, line)]);
}
}
private static int Index(string raw, int count, string name, int line)
{
if (!int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || result == 0)
{
throw new FormatException($"{name}: OBJ line {line + 1} has a bad index '{raw}'.");
}
int num = ((result > 0) ? (result - 1) : (count + result));
if (num < 0 || num >= count)
{
throw new FormatException($"{name}: OBJ line {line + 1} index {raw} is out of range.");
}
return num;
}
private static Vec3 ReadVec(string[] tokens, string name, int line)
{
if (tokens.Length < 4)
{
throw new FormatException($"{name}: OBJ line {line + 1} needs three numbers.");
}
return new Vec3(Float(tokens[1], name, line), Float(tokens[2], name, line), Float(tokens[3], name, line));
}
private static float Float(string raw, string name, int line)
{
if (!float.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
{
throw new FormatException($"{name}: OBJ line {line + 1} has a bad number '{raw}'.");
}
return result;
}
private static Dictionary<string, MaterialSpec> ReadMaterials(Dictionary<string, object> raw)
{
Dictionary<string, MaterialSpec> dictionary = new Dictionary<string, MaterialSpec>();
foreach (KeyValuePair<string, object> item in raw)
{
if (!(item.Value is Dictionary<string, object> obj))
{
throw new FormatException("pickup json: material " + item.Key + " is not an object.");
}
Vec3 vec = ReadVec3(obj, "rgb");
dictionary.Add(item.Key, new MaterialSpec(vec.X, vec.Y, vec.Z, (float)Num(obj, "emission")));
}
return dictionary;
}
private static Vec3 ReadVec3(Dictionary<string, object> obj, string key)
{
List<object> list = Arr(obj, key);
if (list.Count != 3 || !(list[0] is double num) || !(list[1] is double num2) || !(list[2] is double num3))
{
throw new FormatException("pickup json: '" + key + "' is not three numbers.");
}
return new Vec3((float)num, (float)num2, (float)num3);
}
private static object Field(Dictionary<string, object> obj, string key)
{
if (!obj.TryGetValue(key, out var value))
{
throw new FormatException("pickup json: missing '" + key + "'.");
}
return value;
}
private static string Str(Dictionary<string, object> obj, string key)
{
return (Field(obj, key) as string) ?? throw new FormatException("pickup json: '" + key + "' is not a string.");
}
private static double Num(Dictionary<string, object> obj, string key)
{
object obj2 = Field(obj, key);
if (obj2 is double)
{
return (double)obj2;
}
throw new FormatException("pickup json: '" + key + "' is not a number.");
}
private static List<object> Arr(Dictionary<string, object> obj, string key)
{
return (Field(obj, key) as List<object>) ?? throw new FormatException("pickup json: '" + key + "' is not an array.");
}
private static Dictionary<string, object> Obj(Dictionary<string, object> obj, string key)
{
return (Field(obj, key) as Dictionary<string, object>) ?? throw new FormatException("pickup json: '" + key + "' is not an object.");
}
}
internal sealed class PickupMesh
{
public readonly Vec3[] Positions;
public readonly Vec3[] Normals;
public readonly float[] U;
public readonly float[] R;
public readonly float[] G;
public readonly float[] B;
public readonly int[] Triangles;
public readonly IReadOnlyList<MaterialSpec> Palette;
private PickupMesh(Vec3[] positions, Vec3[] normals, float[] u, float[] r, float[] g, float[] b, int[] triangles, IReadOnlyList<MaterialSpec> palette)
{
Positions = positions;
Normals = normals;
U = u;
R = r;
G = g;
B = b;
Triangles = triangles;
Palette = palette;
}
public static PickupMesh From(PickupModel model)
{
Vec3 vec = new Vec3(float.MaxValue, float.MaxValue, float.MaxValue);
Vec3 vec2 = new Vec3(float.MinValue, float.MinValue, float.MinValue);
Vec3[] positions = model.Positions;
for (int i = 0; i < positions.Length; i++)
{
Vec3 vec3 = positions[i];
vec = new Vec3(Math.Min(vec.X, vec3.X), Math.Min(vec.Y, vec3.Y), Math.Min(vec.Z, vec3.Z));
vec2 = new Vec3(Math.Max(vec2.X, vec3.X), Math.Max(vec2.Y, vec3.Y), Math.Max(vec2.Z, vec3.Z));
}
Vec3 vec4 = new Vec3((vec.X + vec2.X) / 2f, (vec.Y + vec2.Y) / 2f, (vec.Z + vec2.Z) / 2f);
int count = model.SubMeshes.Count;
List<Vec3> list = new List<Vec3>(model.Positions.Length);
List<Vec3> list2 = new List<Vec3>(model.Positions.Length);
List<float> list3 = new List<float>(model.Positions.Length);
List<float> list4 = new List<float>(model.Positions.Length);
List<float> list5 = new List<float>(model.Positions.Length);
List<float> list6 = new List<float>(model.Positions.Length);
List<MaterialSpec> list7 = new List<MaterialSpec>(count);
for (int j = 0; j < count; j++)
{
SubMesh subMesh = model.SubMeshes[j];
MaterialSpec item = model.Materials[subMesh.Material];
list7.Add(item);
float item2 = ((float)j + 0.5f) / (float)count;
int[] triangles = subMesh.Triangles;
foreach (int num in triangles)
{
list.Add(model.Positions[num] - vec4);
list2.Add(model.Normals[num]);
list3.Add(item2);
list4.Add(item.R);
list5.Add(item.G);
list6.Add(item.B);
}
}
int[] array = new int[list.Count];
for (int k = 0; k < array.Length; k++)
{
array[k] = k;
}
return new PickupMesh(list.ToArray(), list2.ToArray(), list3.ToArray(), list4.ToArray(), list5.ToArray(), list6.ToArray(), array, list7);
}
}
internal sealed class JsonReader
{
private readonly string text;
private int pos;
private JsonReader(string text)
{
this.text = text;
}
public static object Parse(string text)
{
if (text == null)
{
throw new FormatException("JSON text is null.");
}
JsonReader jsonReader = new JsonReader(text);
object result = jsonReader.ReadValue();
jsonReader.SkipWhitespace();
if (jsonReader.pos != text.Length)
{
throw jsonReader.Error("trailing characters");
}
return result;
}
private object ReadValue()
{
SkipWhitespace();
if (pos >= text.Length)
{
throw Error("unexpected end");
}
char c = text[pos];
switch (c)
{
case '{':
return ReadObject();
case '[':
return ReadArray();
case '"':
return ReadString();
case 't':
Expect("true");
return true;
case 'f':
Expect("false");
return false;
case 'n':
Expect("null");
return null;
default:
switch (c)
{
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return ReadNumber();
default:
throw Error($"unexpected '{c}'");
}
}
}
private Dictionary<string, object> ReadObject()
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
pos++;
SkipWhitespace();
if (Peek() == '}')
{
pos++;
return dictionary;
}
while (true)
{
SkipWhitespace();
if (Peek() != '"')
{
throw Error("expected a key");
}
string key = ReadString();
SkipWhitespace();
if (Peek() != ':')
{
break;
}
pos++;
dictionary[key] = ReadValue();
SkipWhitespace();
char c = Peek();
pos++;
switch (c)
{
case ',':
break;
case '}':
return dictionary;
default:
throw Error("expected ',' or '}'");
}
}
throw Error("expected ':'");
}
private List<object> ReadArray()
{
List<object> list = new List<object>();
pos++;
SkipWhitespace();
if (Peek() == ']')
{
pos++;
return list;
}
while (true)
{
list.Add(ReadValue());
SkipWhitespace();
char c = Peek();
pos++;
switch (c)
{
case ',':
break;
case ']':
return list;
default:
throw Error("expected ',' or ']'");
}
}
}
private string ReadString()
{
pos++;
StringBuilder stringBuilder = new StringBuilder();
while (pos < text.Length)
{
char c = text[pos++];
switch (c)
{
case '"':
return stringBuilder.ToString();
default:
stringBuilder.Append(c);
break;
case '\\':
{
if (pos >= text.Length)
{
throw Error("unterminated escape");
}
char c2 = text[pos++];
switch (c2)
{
case '"':
stringBuilder.Append('"');
break;
case '\\':
stringBuilder.Append('\\');
break;
case '/':
stringBuilder.Append('/');
break;
case 'b':
stringBuilder.Append('\b');
break;
case 'f':
stringBuilder.Append('\f');
break;
case 'n':
stringBuilder.Append('\n');
break;
case 'r':
stringBuilder.Append('\r');
break;
case 't':
stringBuilder.Append('\t');
break;
case 'u':
if (pos + 4 > text.Length)
{
throw Error("short \\u escape");
}
stringBuilder.Append((char)int.Parse(text.Substring(pos, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture));
pos += 4;
break;
default:
throw Error($"bad escape '\\{c2}'");
}
break;
}
}
}
throw Error("unterminated string");
}
private double ReadNumber()
{
int num = pos;
while (pos < this.text.Length && "+-0123456789.eE".IndexOf(this.text[pos]) >= 0)
{
pos++;
}
string text = this.text.Substring(num, pos - num);
if (!double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
{
throw Error("bad number '" + text + "'");
}
return result;
}
private void Expect(string word)
{
if (string.CompareOrdinal(text, pos, word, 0, word.Length) != 0)
{
throw Error("expected '" + word + "'");
}
pos += word.Length;
}
private char Peek()
{
if (pos >= text.Length)
{
return '\0';
}
return text[pos];
}
private void SkipWhitespace()
{
while (pos < text.Length && char.IsWhiteSpace(text[pos]))
{
pos++;
}
}
private FormatException Error(string what)
{
return new FormatException($"JSON: {what} at offset {pos}.");
}
}
internal static class PowerupBar
{
private static FieldRef<PowerupUI, Dictionary<int, GameObject>> _entries;
private static bool _entriesFailed;
internal static void SetCount(int id, int count)
{
PowerupUI instance = PowerupUI.Instance;
Dictionary<int, GameObject> dictionary = Entries(instance);
if (!((Object)(object)instance == (Object)null) && dictionary != null)
{
int num = -1;
if (dictionary.TryGetValue(id, out var value) && (Object)(object)value != (Object)null)
{
num = value.transform.GetSiblingIndex();
value.SetActive(false);
Object.Destroy((Object)(object)value);
}
dictionary.Remove(id);
for (int i = 0; i < count; i++)
{
instance.AddPowerup(id);
}
if (count > 0 && num >= 0 && dictionary.TryGetValue(id, out var value2))
{
value2.transform.SetSiblingIndex(num);
}
}
}
private static Dictionary<int, GameObject> Entries(PowerupUI ui)
{
if ((Object)(object)ui == (Object)null || _entriesFailed)
{
return null;
}
if (_entries == null)
{
try
{
_entries = AccessTools.FieldRefAccess<PowerupUI, Dictionary<int, GameObject>>("powerups");
}
catch (Exception arg)
{
_entriesFailed = true;
DioPlugin.Log.LogWarning((object)$"Dio cannot update the powerup icon (PowerupUI.powerups): {arg}");
return null;
}
}
return _entries.Invoke(ui);
}
}
internal enum ClaimResult
{
Claimed,
NameTakenByOtherMod,
IdsNotContiguous
}
internal readonly struct PowerupClaim
{
public readonly ClaimResult Result;
public readonly int Id;
public PowerupClaim(ClaimResult result, int id)
{
Result = result;
Id = id;
}
public static PowerupClaim Resolve(bool nameExists, bool existingIsOurs, int existingId, IEnumerable<int> existingIds, int existingCount)
{
if (nameExists && !existingIsOurs)
{
return new PowerupClaim(ClaimResult.NameTakenByOtherMod, -1);
}
if (nameExists && existingIsOurs)
{
return new PowerupClaim(ClaimResult.Claimed, existingId);
}
int num = PowerupIds.Resolve(existingIds, nameExists: false, 0);
if (num != existingCount)
{
return new PowerupClaim(ClaimResult.IdsNotContiguous, -1);
}
return new PowerupClaim(ClaimResult.Claimed, num);
}
}
internal static class PowerupIds
{
public static int Resolve(IEnumerable<int> existingIds, bool nameExists, int existingId)
{
if (nameExists)
{
return existingId;
}
int num = 0;
bool flag = false;
foreach (int existingId2 in existingIds)
{
if (!flag || existingId2 > num)
{
num = existingId2;
flag = true;
}
}
if (!flag)
{
return 0;
}
return num + 1;
}
}
internal static class ReviveEffect
{
internal static void Play(Vector3 pos)
{
//IL_0026: Unknown result type (might be due to invalid IL or missing references)
//IL_0027: Unknown result type (might be due to invalid IL or missing references)
//IL_0042: Unknown result type (might be due to invalid IL or missing references)
//IL_0047: Unknown result type (might be due to invalid IL or missing references)
//IL_005e: Unknown result type (might be due to invalid IL or missing references)
//IL_0063: Unknown result type (might be due to invalid IL or missing references)
GameObject val = (((Object)(object)PowerupInventory.Instance != (Object)null) ? PowerupInventory.Instance.powerupFx : null);
if (!((Object)(object)val == (Object)null))
{
GameObject obj = Object.Instantiate<GameObject>(val, pos, Quaternion.identity);
ParticleSystem component = obj.GetComponent<ParticleSystem>();
if ((Object)(object)component != (Object)null)
{
MainModule main = component.main;
((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(new Color(1f, 0.78f, 0.2f, 1f));
}
Object.Destroy((Object)(object)obj, 5f);
}
}
}
internal readonly struct Vitals
{
public readonly float Hp;
public readonly float Shield;
public readonly float Stamina;
public readonly float Hunger;
public Vitals(float hp, float shield, float stamina, float hunger)
{
Hp = hp;
Shield = shield;
Stamina = stamina;
Hunger = hunger;
}
}
internal static class ReviveVitals
{
public static Vitals Compute(int maxHp, int maxShield, float maxStamina, float maxHunger, float currentHunger, float healthFraction, bool refillHungerAndStamina, float currentStamina)
{
float num = Clamp01NaN1(healthFraction);
float hp = Math.Max(1f, (float)maxHp * num);
float shield = Math.Max(0f, (float)maxShield * num);
float stamina = (refillHungerAndStamina ? maxStamina : Math.Max(0f, currentStamina));
float hunger = (refillHungerAndStamina ? maxHunger : Math.Max(0f, currentHunger));
return new Vitals(hp, shield, stamina, hunger);
}
internal static float Clamp01NaN1(float x)
{
if (float.IsNaN(x))
{
return 1f;
}
return Math.Min(1f, Math.Max(0f, x));
}
}
public static class MyPluginInfo
{
public const string PLUGIN_GUID = "MuckDio";
public const string PLUGIN_NAME = "Dio's Best Friend";
public const string PLUGIN_VERSION = "0.1.1";
}
}