Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of ForgeOdds v0.1.3
plugins/ForgeOdds.dll
Decompiled 16 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ForgeOdds { internal readonly struct Odds { internal readonly float Success; internal readonly float Break; internal readonly float Fail; internal Odds(float success, float broken, float fail) { Success = success; Break = broken; Fail = fail; } } internal static class Forge { private static readonly Regex Numbers = new Regex("[-+]?\\d+([.,]\\d+)?", RegexOptions.Compiled); internal const string Arrow = " » "; internal static Odds Chances(float upgradeChance, float breakChance) { float num = Mathf.Clamp01(upgradeChance); float num2 = Mathf.Clamp01(breakChance); float num3 = Mathf.Max(0f, 1f - Mathf.Max(num, 1f - num2)); float fail = Mathf.Max(0f, 1f - num - num3); return new Odds(num, num3, fail); } internal static Requirement Idol(Requirement[] resources) { if (resources == null) { return null; } foreach (Requirement val in resources) { if (val != null && val.m_upgraderResource) { return val; } } return null; } internal static List<(Requirement req, int amount)> Costs(Requirement[] resources, int targetQuality) { List<(Requirement, int)> list = new List<(Requirement, int)>(); if (resources == null) { return list; } foreach (Requirement val in resources) { if (val != null && val.m_upgraderResource) { int amount = val.GetAmount(targetQuality); if (amount > 0) { list.Add((val, amount)); } } } return list; } internal static List<(Requirement req, int amount)> BreakReturns(Requirement[] resources, int quality, float share) { List<(Requirement, int)> list = new List<(Requirement, int)>(); if (resources == null || !(share > 0f)) { return list; } foreach (Requirement val in resources) { if (val != null && val.m_recover) { int num = 0; for (int j = 1; j < quality + 1; j++) { num += val.GetAmount(j); } int num2 = Mathf.RoundToInt((float)num * share); if (num2 > 0) { list.Add((val, num2)); } } } return list; } internal static ItemData Successor(ItemData old, int quality, int worldLevel, long crafterID, string crafterName) { ItemData obj = old.Clone(); obj.m_quality = quality; obj.m_worldLevel = (byte)worldLevel; obj.m_crafterID = crafterID; obj.m_crafterName = crafterName; obj.m_customData = new Dictionary<string, string>(); obj.m_equipped = false; obj.m_durability = obj.GetMaxDurability(); return obj; } internal static string Percent(float p) { return (Mathf.Round(p * 1000f) / 10f).ToString("0.#", CultureInfo.InvariantCulture) + "%"; } internal static List<(string key, string label, string value, string line)> Lines(string tooltip) { List<(string, string, string, string)> list = new List<(string, string, string, string)>(); if (string.IsNullOrEmpty(tooltip)) { return list; } Dictionary<string, int> dictionary = new Dictionary<string, int>(); string[] array = tooltip.Split('\n'); for (int i = 0; i < array.Length; i++) { string text = array[i].TrimEnd(' ', '\r'); if (text.Trim().Length != 0) { int num = text.IndexOf(':'); string text2 = null; string item = null; string text3; if (num > 0 && num < text.Length - 1) { text2 = text.Substring(0, num); item = text.Substring(num + 1).Trim(); text3 = text2; } else { text3 = "~" + Numbers.Replace(text, "#"); } dictionary.TryGetValue(text3, out var value); dictionary[text3] = value + 1; if (value > 0) { text3 = text3 + "#" + value; } list.Add((text3, text2, item, text)); } } return list; } internal static List<string> Changes(string before, string after, string newWord) { List<(string, string, string, string)> list = Lines(before); List<(string, string, string, string)> list2 = Lines(after); Dictionary<string, (string, string, string)> dictionary = new Dictionary<string, (string, string, string)>(); foreach (var item in list) { dictionary[item.Item1] = (item.Item2, item.Item3, item.Item4); } HashSet<string> hashSet = new HashSet<string>(); List<string> list3 = new List<string>(); foreach (var item2 in list2) { if (dictionary.TryGetValue(item2.Item1, out var value)) { hashSet.Add(item2.Item1); if (!(value.Item3 == item2.Item4)) { list3.Add((item2.Item2 != null && value.Item1 != null) ? (item2.Item2 + ": " + value.Item2 + " » " + item2.Item3) : (value.Item3.Trim() + " » " + item2.Item4.Trim())); } } else { list3.Add(item2.Item4.Trim() + " " + newWord); } } foreach (var item3 in list) { if (!hashSet.Contains(item3.Item1)) { list3.Add((item3.Item2 != null) ? (item3.Item2 + ": " + item3.Item3 + " » -") : (item3.Item4.Trim() + " » -")); } } return list3; } internal static string Insert(string tooltip, string description, string block, bool atTop) { if (string.IsNullOrEmpty(block)) { return tooltip; } if (string.IsNullOrEmpty(tooltip)) { return block; } if (!atTop) { return tooltip.TrimEnd('\n') + "\n\n" + block; } if (!string.IsNullOrEmpty(description) && tooltip.StartsWith(description, StringComparison.Ordinal)) { string text = tooltip.Substring(description.Length).TrimStart('\n'); return description + "\n\n" + block + ((text.Length > 0) ? ("\n\n" + text) : ""); } return block + "\n\n" + tooltip; } internal static void Line(StringBuilder sb, string text) { if (sb.Length > 0) { sb.Append('\n'); } sb.Append(text); } } [HarmonyPatch(typeof(ItemData), "GetTooltip", new Type[] { typeof(ItemData), typeof(int), typeof(bool), typeof(float), typeof(int), typeof(bool) })] internal static class RecipeText { private static void Postfix(ref string __result, ItemData item, int qualityLevel, bool crafting, bool appending) { try { __result = Preview.Extend(__result, item, qualityLevel, crafting, appending); } catch (Exception ex) { Plugin.Warn("tooltip: " + ex.Message); } } } [HarmonyPatch(typeof(InventoryGui), "DoCrafting")] internal static class ForgeRoll { internal sealed class Saved { internal SharedData Shared; internal float Success; internal float Break; internal float Return; } internal static Saved Active; private static void Prefix(InventoryGui __instance, out Saved __state) { __state = null; try { Rules current = HostSync.Current; if (current.IsGame) { return; } Player localPlayer = Player.m_localPlayer; CraftingStation val = (((Object)(object)localPlayer != (Object)null) ? localPlayer.GetCurrentCraftingStation() : null); Recipe craftRecipe = __instance.m_craftRecipe; if (!((Object)(object)val == (Object)null) && val.m_upgrader && !((Object)(object)craftRecipe == (Object)null)) { SharedData val2 = Forge.Idol(craftRecipe.m_resources)?.m_resItem?.m_itemData?.m_shared; if (val2 != null) { __state = new Saved { Shared = val2, Success = val2.m_upgradeChance, Break = val2.m_breakChance, Return = val2.m_breakReturnIngreientsAmount }; Active = __state; val2.m_upgradeChance = current.SuccessOf(__state.Success); val2.m_breakChance = current.BreakOf(__state.Break); val2.m_breakReturnIngreientsAmount = current.ReturnOf(__state.Return); } } } catch (Exception ex) { Plugin.Warn("forge odds: " + ex.Message); } } private static Exception Finalizer(Exception __exception, Saved __state) { Active = null; if (__state?.Shared != null) { __state.Shared.m_upgradeChance = __state.Success; __state.Shared.m_breakChance = __state.Break; __state.Shared.m_breakReturnIngreientsAmount = __state.Return; } return __exception; } } [HarmonyPatch(typeof(InventoryGui), "Awake")] internal static class ForgeTime { private static InventoryGui known; private static float baseTime; private static float perLevel; private static void Postfix(InventoryGui __instance) { try { known = __instance; baseTime = __instance.m_upgraderDuration; perLevel = __instance.m_upgraderDurationPerLevel; Apply(__instance); } catch (Exception ex) { Plugin.Warn("forge time: " + ex.Message); } } internal static void Apply(InventoryGui inv) { if (!((Object)(object)inv == (Object)null) && !((Object)(object)inv != (Object)(object)known) && Plugin.UpgradeSpeed != null) { inv.m_upgraderDuration = Rules.Duration(baseTime, Plugin.UpgradeSpeed.Value); inv.m_upgraderDurationPerLevel = Rules.Duration(perLevel, Plugin.UpgradeSpeed.Value); } } } internal static class HostSync { private const string Push = "ForgeOdds_Rules"; private const string Ask = "ForgeOdds_Ask"; internal static Func<Rules> Local = () => Rules.Game; private static bool received; private static Rules host = Rules.Game; private static long asked; private static bool IsHost { get { if (!((Object)(object)ZNet.instance == (Object)null)) { return ZNet.instance.IsServer(); } return true; } } internal static Rules Current { get { if (!IsHost) { if (!received) { return Rules.Game; } return host; } return Local(); } } internal static bool FromHost { get { if (!IsHost) { return received; } return false; } } internal static void Register() { received = false; asked = 0L; host = Rules.Game; ZRoutedRpc instance = ZRoutedRpc.instance; if (instance != null) { instance.Register<string>("ForgeOdds_Rules", (Action<long, string>)Receive); instance.Register("ForgeOdds_Ask", (Action<long>)Asked); } } private static void Receive(long sender, string text) { if (IsHost || ZRoutedRpc.instance == null || sender != ZRoutedRpc.instance.GetServerPeerID()) { return; } if (!Rules.Read(text, out var rules)) { Plugin.Warn("the host's odds were not understood: " + text); return; } bool num = !received || !rules.Same(host); received = true; host = rules; Preview.Stamp++; if (num) { Plugin.Info("the host's forge odds: " + text + " (success|break|return, -1 = the idol's own)"); } } private static void Asked(long sender) { if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()) { Send(sender); } } internal static void Send(long target) { if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && ZRoutedRpc.instance != null) { ZRoutedRpc.instance.InvokeRoutedRPC(target, "ForgeOdds_Rules", new object[1] { Local().Write() }); } } internal static void Changed() { Preview.Stamp++; Send(0L); } internal static void AskOnce() { if (!received && !IsHost && ZRoutedRpc.instance != null) { long serverPeerID = ZRoutedRpc.instance.GetServerPeerID(); if (serverPeerID != 0L && serverPeerID != asked) { asked = serverPeerID; ZRoutedRpc.instance.InvokeRoutedRPC(serverPeerID, "ForgeOdds_Ask", Array.Empty<object>()); } } } internal static void Forget() { received = false; asked = 0L; host = Rules.Game; } } internal sealed class CfgWatch : IDisposable { private readonly ConfigFile config; private readonly FileSystemWatcher watcher; private volatile bool touched; private float due; internal CfgWatch(ConfigFile config) { this.config = config; try { watcher = new FileSystemWatcher(Path.GetDirectoryName(config.ConfigFilePath), Path.GetFileName(config.ConfigFilePath)) { NotifyFilter = (NotifyFilters.Size | NotifyFilters.LastWrite), EnableRaisingEvents = true }; watcher.Changed += delegate { touched = true; }; } catch { watcher = null; } } internal void Tick() { if (!touched) { return; } if (due == 0f) { due = Time.unscaledTime + 0.5f; } else if (!(Time.unscaledTime < due)) { touched = false; due = 0f; try { config.Reload(); } catch { } } } public void Dispose() { if (watcher != null) { watcher.EnableRaisingEvents = false; watcher.Dispose(); } } } [HarmonyPatch] internal static class HostSyncHooks { [HarmonyPostfix] [HarmonyPatch(typeof(ZNet), "Awake")] private static void Session() { HostSync.Register(); } [HarmonyPostfix] [HarmonyPatch(typeof(ZNet), "OnDestroy")] private static void Left() { HostSync.Forget(); } [HarmonyPostfix] [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private static void Joined(ZNet __instance, ZRpc rpc) { if (__instance.IsServer()) { ZNetPeer peer = __instance.GetPeer(rpc); if (peer != null && peer.m_uid != 0L) { HostSync.Send(peer.m_uid); } } } [HarmonyPostfix] [HarmonyPatch(typeof(Player), "OnSpawned")] private static void Spawned(Player __instance) { if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer) { HostSync.AskOnce(); } } } [BepInPlugin("chistix.forgeodds", "ForgeOdds", "0.1.3")] public sealed class Plugin : BaseUnityPlugin { public const string Guid = "chistix.forgeodds"; public const string Version = "0.1.3"; private static ManualLogSource log; internal static ConfigEntry<bool> Enabled; internal static ConfigEntry<bool> AtTop; internal static ConfigEntry<bool> StatChanges; internal static ConfigEntry<bool> Returns; internal static ConfigEntry<bool> ModDataNote; internal static ConfigEntry<int> Success; internal static ConfigEntry<int> Break; internal static ConfigEntry<int> ReturnShare; internal static ConfigEntry<int> UpgradeSpeed; private CfgWatch watch; internal static bool Russian { get { if (Localization.instance != null) { return Localization.instance.GetSelectedLanguage() == "Russian"; } return false; } } private void Awake() { //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Expected O, but got Unknown //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Expected O, but got Unknown //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Expected O, but got Unknown //IL_01df: Unknown result type (might be due to invalid IL or missing references) log = ((BaseUnityPlugin)this).Logger; Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "The forecast in the crafting window at the Forge of Potential.\nПрогноз в окне ремесла у Кузни потенциала."); AtTop = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AtTop", true, "The forecast at the top of the item's text (under its description); off - at the bottom.\nПрогноз вверху текста предмета (под описанием); выключено — внизу."); StatChanges = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "StatChanges", true, "The item's stats that change: before → after (the game's own tooltip lines).\nХарактеристики предмета, которые изменятся: было → станет (строки родной подсказки игры)."); Returns = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Returns", true, "What comes back if the item breaks.\nЧто вернётся, если предмет сломается."); ModDataNote = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ModDataNote", true, "A line when the item carries data of other mods (the game makes the upgraded item anew).\nСтрока, если на предмете есть данные других модов (улучшенный предмет игра делает заново)."); Success = ((BaseUnityPlugin)this).Config.Bind<int>("Odds", "SuccessPercent", -1, new ConfigDescription("Chance of success at the Forge of Potential, 0-100 (the game's idols: 65). Only the world's host's value counts (alone - yours; on a server - the server's, sent to every player with the mod). -1 - the idol's own.\nШанс успеха у Кузни потенциала, 0-100 (у идолов игры: 65). Действует только значение хоста мира (в одиночной игре — ваше; на сервере — серверное, рассылается всем игрокам с модом). -1 — как у идола.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(-1, 100), Array.Empty<object>())); Break = ((BaseUnityPlugin)this).Config.Bind<int>("Odds", "BreakPercent", -1, new ConfigDescription("Chance of a break, 0-100 (the game's idols: 100, i.e. every roll that is not a success). The game takes success first: break = min(this, 100 - success); the rest is a lower level. Only the world's host's value counts (alone - yours; on a server - the server's, sent to every player with the mod). -1 - the idol's own.\nШанс поломки, 0-100 (у идолов игры: 100, т. е. всё, что не успех). Игра сначала берёт успех: поломка = min(это, 100 - успех); остаток — понижение уровня. Действует только значение хоста мира (в одиночной игре — ваше; на сервере — серверное, рассылается всем игрокам с модом). -1 — как у идола.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(-1, 100), Array.Empty<object>())); ReturnShare = ((BaseUnityPlugin)this).Config.Bind<int>("Odds", "ReturnPercent", -1, new ConfigDescription("Share of the resources given back on a break, 0-100 (the game's idols: 35). Only the world's host's value counts (alone - yours; on a server - the server's, sent to every player with the mod). -1 - the idol's own.\nДоля ресурсов, возвращаемых при поломке, 0-100 (у идолов игры: 35). Действует только значение хоста мира (в одиночной игре — ваше; на сервере — серверное, рассылается всем игрокам с модом). -1 — как у идола.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(-1, 100), Array.Empty<object>())); HostSync.Local = () => new Rules(Success.Value, Break.Value, ReturnShare.Value); UpgradeSpeed = ((BaseUnityPlugin)this).Config.Bind<int>("Speed", "UpgradeSpeedPercent", 200, new ConfigDescription("How fast the Forge of Potential upgrades, in percent of the game's time (100 - as in the game, 8 s + 1 s a level; 200 - twice as fast). Your own setting, also on a server.\nСкорость улучшения у Кузни потенциала, в процентах от времени игры (100 - как в игре, 8 с + 1 с за уровень; 200 - вдвое быстрее). Ваша собственная настройка, и на сервере тоже.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(50, 500), Array.Empty<object>())); ((BaseUnityPlugin)this).Config.SettingChanged += delegate(object _, SettingChangedEventArgs args) { if (args.ChangedSetting.Definition.Section == "Odds") { HostSync.Changed(); } else if ((object)args.ChangedSetting == UpgradeSpeed) { ForgeTime.Apply(InventoryGui.instance); } else { Preview.Stamp++; } }; watch = new CfgWatch(((BaseUnityPlugin)this).Config); new Harmony("chistix.forgeodds").PatchAll(typeof(Plugin).Assembly); log.LogInfo((object)"ForgeOdds 0.1.3"); } private void Update() { watch?.Tick(); } private void OnDestroy() { watch?.Dispose(); } internal static string T(string ru, string en) { if (!Russian) { return en; } return ru; } internal static void Info(string text) { ManualLogSource obj = log; if (obj != null) { obj.LogInfo((object)text); } } internal static void Warn(string text) { ManualLogSource obj = log; if (obj != null) { obj.LogWarning((object)text); } } } internal static class Preview { private static bool busy; private static object shownItem; private static int shownQuality = -1; private static int shownStamp = -1; private static string shownLanguage; private static string shownBlock; private static float builtAt; internal static int Stamp; internal static string Extend(string text, ItemData item, int quality, bool crafting, bool appending) { if (busy || appending || !crafting || item?.m_shared == null || Plugin.Enabled == null || !Plugin.Enabled.Value) { return text; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return text; } CraftingStation currentCraftingStation = localPlayer.GetCurrentCraftingStation(); if ((Object)(object)currentCraftingStation == (Object)null || !currentCraftingStation.m_upgrader) { return text; } InventoryGui instance = InventoryGui.instance; if ((Object)(object)instance == (Object)null || !InventoryGui.IsVisible()) { return text; } int num = quality - 1; if (num < 0 || !Find(instance, localPlayer, item, num, out var recipe, out var old)) { return text; } busy = true; string block; try { block = Block(localPlayer, recipe, old, num); } catch (Exception ex) { Plugin.Warn("forecast: " + ex.Message); block = null; } finally { busy = false; } return Forge.Insert(text, item.m_shared.m_description, block, Plugin.AtTop.Value); } private static bool Same(SharedData a, SharedData b) { if (a != null && b != null) { if (a != b) { return a.m_name == b.m_name; } return true; } return false; } private static bool Find(InventoryGui inv, Player player, ItemData item, int q, out Recipe recipe, out ItemData old) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: 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_0059: Unknown result type (might be due to invalid IL or missing references) recipe = null; old = null; RecipeDataPair selectedRecipe = inv.m_selectedRecipe; if (Fits(((RecipeDataPair)(ref selectedRecipe)).Recipe, ((RecipeDataPair)(ref selectedRecipe)).ItemData, item, q)) { recipe = ((RecipeDataPair)(ref selectedRecipe)).Recipe; old = ((RecipeDataPair)(ref selectedRecipe)).ItemData; } else if (inv.m_availableRecipes != null) { foreach (RecipeDataPair availableRecipe in inv.m_availableRecipes) { RecipeDataPair current = availableRecipe; if (Fits(((RecipeDataPair)(ref current)).Recipe, ((RecipeDataPair)(ref current)).ItemData, item, q)) { recipe = ((RecipeDataPair)(ref current)).Recipe; old = ((RecipeDataPair)(ref current)).ItemData; break; } } } if ((Object)(object)recipe == (Object)null) { Recipe val = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetRecipe(item) : null); Inventory inventory = ((Humanoid)player).GetInventory(); List<ItemData> list = ((inventory != null) ? inventory.GetAllItems() : null); if ((Object)(object)val == (Object)null || list == null) { return false; } if (item.m_quality == q && list.Contains(item)) { old = item; } else { foreach (ItemData item2 in list) { if (Same(item2.m_shared, item.m_shared) && item2.m_quality == q) { old = item2; break; } } } if (old == null) { return false; } recipe = val; } return (Object)(object)Forge.Idol(recipe.m_resources)?.m_resItem != (Object)null; } private static bool Fits(Recipe recipe, ItemData data, ItemData item, int q) { if ((Object)(object)recipe != (Object)null && data != null && data.m_quality == q && (Object)(object)recipe.m_item != (Object)null) { return Same(recipe.m_item.m_itemData?.m_shared, item.m_shared); } return false; } private static string Block(Player player, Recipe recipe, ItemData old, int q) { string text = ((Localization.instance != null) ? Localization.instance.GetSelectedLanguage() : ""); float unscaledTime = Time.unscaledTime; if (shownItem == old && shownQuality == q && shownStamp == Stamp && shownLanguage == text && unscaledTime - builtAt < 1f && shownBlock != null) { return shownBlock; } shownItem = old; shownQuality = q; shownStamp = Stamp; shownLanguage = text; builtAt = unscaledTime; shownBlock = Make(player, recipe, old, q); return shownBlock; } private static string Make(Player player, Recipe recipe, ItemData old, int q) { SharedData shared = Forge.Idol(recipe.m_resources).m_resItem.m_itemData.m_shared; ForgeRoll.Saved active = ForgeRoll.Active; int num; float num2; if (active != null) { num = ((active.Shared == shared) ? 1 : 0); if (num != 0) { num2 = active.Success; goto IL_0041; } } else { num = 0; } num2 = shared.m_upgradeChance; goto IL_0041; IL_0041: float num3 = num2; float num4 = ((num != 0) ? active.Break : shared.m_breakChance); float num5 = ((num != 0) ? active.Return : shared.m_breakReturnIngreientsAmount); Rules current = HostSync.Current; float num6 = current.ReturnOf(num5); Odds odds = Forge.Chances(current.SuccessOf(num3), current.BreakOf(num4)); Odds odds2 = Forge.Chances(num3, num4); StringBuilder stringBuilder = new StringBuilder(512); int maxQuality = recipe.m_item.m_itemData.m_shared.m_maxQuality; Forge.Line(stringBuilder, Plugin.T("Кузня потенциала", "Forge of Potential") + ": " + V(q + " » ".TrimEnd() + " " + (q + 1)) + ((q + 1 > maxQuality) ? Plugin.T(" (сверх обычного предела " + maxQuality + ")", " (beyond the usual limit of " + maxQuality + ")") : "")); if (odds.Success != odds2.Success || odds.Break != odds2.Break || num6 != num5) { Forge.Line(stringBuilder, Plugin.T("Шансы изменены настройкой " + (HostSync.FromHost ? "хоста" : "мода") + ", у идола", "Odds set by the " + (HostSync.FromHost ? "host's" : "mod's") + " settings, the idol's own") + ": " + V(Forge.Percent(odds2.Success) + " / " + Forge.Percent(odds2.Break) + " / " + Forge.Percent(num5))); } if (player.NoCostCheat() || ((Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.GetGlobalKey((GlobalKeys)25))) { Forge.Line(stringBuilder, Plugin.T("Тратится", "Spent") + ": " + V(Plugin.T("ничего (мир без затрат на ремесло)", "nothing (no crafting cost in this world)"))); } else { StringBuilder stringBuilder2 = new StringBuilder(); foreach (var (val, value) in Forge.Costs(recipe.m_resources, q + 1)) { if (stringBuilder2.Length > 0) { stringBuilder2.Append(", "); } stringBuilder2.Append(val.m_resItem.m_itemData.m_shared.m_name).Append(" x").Append(value); } if (stringBuilder2.Length > 0) { Forge.Line(stringBuilder, Plugin.T("Тратится при любом исходе", "Spent whatever the outcome") + ": " + V(stringBuilder2.ToString())); } } stringBuilder.Append('\n'); Forge.Line(stringBuilder, Plugin.T("Успех, станет ур. ", "Success, becomes level ") + (q + 1) + ": " + V(Forge.Percent(odds.Success))); if (odds.Success > 0f && Plugin.StatChanges.Value) { Changes(stringBuilder, player, old, q + 1); } if (odds.Break > 0f || odds.Fail <= 0f) { stringBuilder.Append('\n'); Forge.Line(stringBuilder, Plugin.T("Поломка, предмет пропадёт", "Break, the item is destroyed") + ": " + V(Forge.Percent(odds.Break))); if (odds.Break > 0f && Plugin.Returns.Value) { Returns(stringBuilder, player, recipe, q, num6); } } if (odds.Fail > 0f) { stringBuilder.Append('\n'); Forge.Line(stringBuilder, Plugin.T("Неудача, станет ур. ", "Failure, becomes level ") + (q - 1) + ": " + V(Forge.Percent(odds.Fail))); if (Plugin.StatChanges.Value) { Changes(stringBuilder, player, old, q - 1); } } if (Plugin.ModDataNote.Value && old.m_customData != null && old.m_customData.Count > 0 && (odds.Success > 0f || odds.Fail > 0f)) { stringBuilder.Append('\n'); Forge.Line(stringBuilder, Plugin.T("На предмете есть данные модов (" + old.m_customData.Count + "): игра делает предмет заново и сама их не переносит.", "The item carries data of mods (" + old.m_customData.Count + "): the game makes the item anew and does not carry them over itself.")); } return stringBuilder.ToString(); } private static string V(string value) { return "<color=orange>" + value + "</color>"; } private static void Changes(StringBuilder sb, Player player, ItemData old, int quality) { ItemData val = Forge.Successor(old, quality, Game.m_worldLevel, player.GetPlayerID(), player.GetPlayerName()); string tooltip = ItemData.GetTooltip(old, old.m_quality, false, (float)old.m_worldLevel, -1, false); string tooltip2 = ItemData.GetTooltip(val, quality, false, (float)val.m_worldLevel, -1, false); foreach (string item in Forge.Changes(tooltip, tooltip2, Plugin.T("(новое)", "(new)"))) { Forge.Line(sb, item); } } private static void Returns(StringBuilder sb, Player player, Recipe recipe, int q, float share) { List<(Requirement, int)> list = Forge.BreakReturns(recipe.m_resources, q, share); string text = Plugin.T("Вернётся (от всей цены ур. 1-" + q + ")", "Given back (of all it cost, levels 1-" + q + ")"); if (list.Count == 0) { Forge.Line(sb, text + ": " + V(Plugin.T("ничего", "nothing"))); return; } Forge.Line(sb, text + ": " + V(Forge.Percent(share))); foreach (var (val, num) in list) { Forge.Line(sb, val.m_resItem.m_itemData.m_shared.m_name + ": " + V(num.ToString())); } Inventory inventory = ((Humanoid)player).GetInventory(); if (inventory != null && inventory.GetEmptySlots() < list.Count) { Forge.Line(sb, Plugin.T("В инвентаре мало места: возврат может не поместиться.", "Little room in the inventory: the returns may not fit.")); } } } internal readonly struct Rules { internal readonly int Success; internal readonly int Break; internal readonly int Return; internal static readonly Rules Game = new Rules(-1, -1, -1); internal bool IsGame { get { if (Success < 0 && Break < 0) { return Return < 0; } return false; } } internal Rules(int success, int broken, int share) { Success = Norm(success); Break = Norm(broken); Return = Norm(share); } private static int Norm(int v) { if (v >= 0) { return Mathf.Min(v, 100); } return -1; } internal static float Pick(int setting, float idol) { if (setting >= 0) { return (float)setting / 100f; } return idol; } internal float SuccessOf(float idol) { return Pick(Success, idol); } internal float BreakOf(float idol) { return Pick(Break, idol); } internal float ReturnOf(float idol) { return Pick(Return, idol); } internal string Write() { return Success + "|" + Break + "|" + Return; } internal static bool Read(string text, out Rules rules) { rules = Game; string[] array = (text ?? "").Split('|'); if (array.Length != 3) { return false; } int[] array2 = new int[3]; for (int i = 0; i < 3; i++) { if (!int.TryParse(array[i], out array2[i]) || array2[i] < -1 || array2[i] > 100) { return false; } } rules = new Rules(array2[0], array2[1], array2[2]); return true; } internal static float Duration(float game, int speedPercent) { return game * 100f / (float)Mathf.Clamp(speedPercent, 50, 500); } internal bool Same(Rules o) { if (Success == o.Success && Break == o.Break) { return Return == o.Return; } return false; } } }