Example #1
0
 public static bool DrawInMenu_Prefix(CombinedRing __instance, SpriteBatch spriteBatch, Vector2 location, float scaleSize, float transparency, float layerDepth, StackDrawType drawStackNumber, Color color, bool drawShadow)
 {
     try
     {
         if (__instance.combinedRings.Count >= 2)
         {
             // Always use base rings as the sprites to draw. The first pair that are combined on the left hand side get used as the sprite.
             if (__instance.combinedRings[0] is CombinedRing)
             {
                 __instance.combinedRings[0].drawInMenu(spriteBatch, location, scaleSize, transparency, layerDepth, drawStackNumber, color, drawShadow);
                 return(false); // don't run original logic
             }
             else if (__instance.combinedRings[1] is CombinedRing)
             {
                 __instance.combinedRings[1].drawInMenu(spriteBatch, location, scaleSize, transparency, layerDepth, drawStackNumber, color, drawShadow);
                 return(false); // don't run original logic
             }
         }
         return(true); // run original logic
     }
     catch (Exception ex)
     {
         ModMonitor.Log($"Failed in {nameof(DrawInMenu_Prefix)}:\n{ex}", LogLevel.Error);
         return(true); // run original logic
     }
 }
Example #2
0
        public static void GetForgeCost_Postfix(ForgeMenu __instance, Item left_item, Item right_item, ref int __result)
        {
            try
            {
                if (left_item != null && right_item != null)
                {
                    // if merging rings, then calculate different cost based on the total amount of rings being combined
                    // if only two, rings, than keep normal cost of 20, otherwise, gets 100 per ring combined (max of 999)
                    if (left_item.getCategoryName().Equals("Ring") && left_item.category == right_item.category)
                    {
                        Ring left_ring  = (Ring)left_item;
                        Ring right_ring = (Ring)right_item;

                        int total_rings = GetCombinedRingTotal(left_ring) + GetCombinedRingTotal(right_ring);
                        if (total_rings > 2)
                        {
                            int new_cost = GetTotalCombinedRingsCost(total_rings);
                            __result = new_cost;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ModMonitor.Log($"Failed in {nameof(GetForgeCost_Postfix)}:\n{ex}", LogLevel.Error);
            }
        }
Example #3
0
 public static bool AddEnchantment_Prefix(Tool __instance, BaseEnchantment enchantment, ref bool __result)
 {
     try
     {
         if (enchantment == null)
         {
             return(true);
         }
         if (!enchantment.IsForge() && !enchantment.IsSecondaryEnchantment())
         {
             // Enchantment is a primary enchantment.
             __instance.enchantments.Add(enchantment);
             enchantment.ApplyTo(__instance, __instance.getLastFarmerToUse());
             __result = true;
             return(false);  // don't run original logic
         }
         if (__instance is MeleeWeapon && enchantment.IsForge())
         {
             if (enchantment is DiamondEnchantment)
             {
                 // Skip adding diamond enchantments, they should result in 3 other enchantments getting added in Forge.
                 __result = true;
                 return(false);  // don't run original logic
             }
             // Enchantment is a Weapon forging or Galaxy Soul enchantment
         }
         return(true);  // run original logic
     }
     catch (Exception ex)
     {
         ModMonitor.Log($"Failed in {nameof(AddEnchantment_Prefix)}:\n{ex}", LogLevel.Error);
         return(true);  // run original logic
     }
 }
Example #4
0
            /// <summary>Changes an argument in this.messageSubject.drawInMenu() to use StackDrawType.Draw instead of StackDrawType.Hide)</summary>
            internal static IEnumerable<CodeInstruction> HUDMessageDraw_Transpiler(IEnumerable<CodeInstruction> instructions)
            {
                try
                {
                    var codes = new List<CodeInstruction>(instructions);

                    for (int i = 0; i < codes.Count - 1; i++)
                    {
                        // find Enum value of 0 (StackDrawType.Hide) loaded for the last argument of this.messageSubject.drawInMenu()
                        if (codes[i].opcode == OpCodes.Ldc_I4_0 &&
                            codes[i + 1].opcode == OpCodes.Callvirt &&
                            codes[i + 1].operand.ToString() == "Void drawInMenu(Microsoft.Xna.Framework.Graphics.SpriteBatch, Microsoft.Xna.Framework.Vector2, Single, Single, Single, StardewValley.StackDrawType)")
                        {
                            // change to Enum value 1 (StackDrawType.Draw)
                            codes[i].opcode = OpCodes.Ldc_I4_1;
                            ModMonitor.LogOnce($"Changed StackDrawType Enum in HUDMessage.draw method: {nameof(HUDMessageDraw_Transpiler)}", LogLevel.Trace);
                            break;
                        }
                    }
                    return codes.AsEnumerable();
                }
                catch (Exception ex)
                {
                    ModMonitor.Log($"Failed in {nameof(HUDMessageDraw_Transpiler)}:\n{ex}", LogLevel.Error);
                    return instructions; // use original code
                }
            }
Example #5
0
            /// <summary>When adding an HUD message that stacks with a previous one, use the newest message to update messageSubject.</summary>
            internal static void addHUDMessage_Postfix(HUDMessage message)
            {
                try
                {
                    if (message.type != null || message.whatType != 0)
                    {   
                        for (int index = 0; index < Game1.hudMessages.Count; ++index)
                        {
                            if (message.type != null && Game1.hudMessages[index].type != null && (Game1.hudMessages[index].type.Equals(message.type) && Game1.hudMessages[index].add == message.add))
                            {
                                // Altered code to affect and keep current message in the place of existing one
                                // Keep the updated stack number
                                message.number = Game1.hudMessages[index].number; 
                                // Replace the old HUDMessage with the new one, instead of keeping the old.
                                Game1.hudMessages.RemoveAt(index);
                                Game1.hudMessages.Insert(index, message);

                                ModMonitor.LogOnce($"Ran patch for Game1.addHUDMessage method in game code: {nameof(addHUDMessage_Postfix)}", LogLevel.Trace);
                                return;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    ModMonitor.Log($"Failed in {nameof(addHUDMessage_Postfix)}:\n{ex}", LogLevel.Error);
                }
            }
Example #6
0
        public void LogTrace(LogOutput logOutput, string message     = "Trace Message:",
                             [CallerMemberName] string memberName    = "",
                             [CallerFilePath] string sourceFilePath  = "",
                             [CallerLineNumber] int sourceLineNumber = 0)
        {
            string time             = "[" + DateTime.Now.ToString("HH:mm:ss") + "]";
            int    timeLength       = time.Length + 1;
            string callerMemberName = "CallerMemberName: " + memberName;
            string callerFilePath   = "CallerFilePath: " + sourceFilePath;
            string callerLineNumber = "CallerLineNumber: " + sourceLineNumber;

            StringBuilder sb = new StringBuilder();

            sb.AppendLine(message);
            sb.AppendLine(callerMemberName.PadLeft(callerMemberName.Length + timeLength));
            sb.AppendLine(callerFilePath.PadLeft(callerFilePath.Length + timeLength));
            sb.Append(callerLineNumber.PadLeft(callerLineNumber.Length + timeLength));

            if (logOutput == LogOutput.File || logOutput == LogOutput.Both)
            {
                WriteLine($"{time} {sb.ToString()}");
            }

            if (logOutput == LogOutput.Console || logOutput == LogOutput.Both)
            {
                ModMonitor?.Log(sb.ToString());
            }
        }
Example #7
0
        public static SortedDictionary <string, int> GetCombinedRings(Ring ring)
        {
            SortedDictionary <string, int> result = new SortedDictionary <string, int>();
            Queue <Ring> to_process = new Queue <Ring>();

            to_process.Enqueue(ring);
            while (to_process.Count > 0)
            {
                Ring cur = to_process.Dequeue();
                ModMonitor.Log($"Processing {cur.DisplayName}", LogLevel.Trace);
                if (cur is CombinedRing)
                {
                    foreach (Ring r in (cur as CombinedRing).combinedRings)
                    {
                        to_process.Enqueue(r);
                    }
                }
                else
                {
                    string key = cur.displayName;
                    if (result.TryGetValue(key, out int val))
                    {
                        result.Add(key, val + 1);
                    }
                    else
                    {
                        result.Add(key, 1);
                    }
                }
            }
            return(result);
        }
Example #8
0
        /*********
        ** Private methods
        *********/
        /// <summary>Raised after the game is launched, right before the first update tick. This happens once per game session (unrelated to loading saves). All mods are loaded and initialised at this point, so this is a good time to set up mod integrations.</summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event data.</param>
        private void OnGameLaunched(object sender, GameLaunchedEventArgs e)
        {
            new DataLoader(Helper);

            var harmony = HarmonyInstance.Create("Digus.CustomCaskMod");

            harmony.Patch(
                original: AccessTools.Method(typeof(Cask), nameof(Cask.performObjectDropInAction)),
                prefix: new HarmonyMethod(typeof(CaskOverrides), nameof(CaskOverrides.PerformObjectDropInAction))
                );

            if (!DataLoader.ModConfig.DisableAutomateCompatibility && Helper.ModRegistry.IsLoaded("Pathoschild.Automate"))
            {
                ModMonitor.Log("Automated detected, patching it to work with configured items and aging rates.", LogLevel.Info);
                try
                {
                    Assembly automateAssembly = AppDomain.CurrentDomain.GetAssemblies().First(a => a.FullName.StartsWith("Automate,"));
                    harmony.Patch(
                        original: AccessTools.Constructor(automateAssembly.GetType("Pathoschild.Stardew.Automate.Framework.Machines.Objects.CaskMachine"), new Type[] { typeof(Cask), typeof(GameLocation), typeof(Vector2) }),
                        postfix: new HarmonyMethod(typeof(CaskOverrides), nameof(CaskOverrides.CaskMachine))
                        );
                }
                catch (Exception ex)
                {
                    ModMonitor.Log("Error trying to patch Automate. Configured items and aging rates will not work with Automate.", LogLevel.Warn);
                    ModMonitor.Log(ex.Message, LogLevel.Trace);
                    ModMonitor.Log(ex.StackTrace, LogLevel.Trace);
                }
            }
        }
Example #9
0
        public ActionResult DeleteConfirmed(int id)
        {
            ModMonitor modMonitor = db.ModMonitors.Find(id);

            db.ModMonitors.Remove(modMonitor);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #10
0
            /// <summary>Changes the spouse.Contains check to use spouse.Equals instead.</summary>
            public static IEnumerable <CIL> spouseContainsEquals_Transpiler(IEnumerable <CIL> instructions, MethodBase original)
            {
                try
                {
                    var codes      = new List <CodeInstruction>(instructions);
                    int patchCount = 0;

                    for (int i = 0; i < codes.Count - 4; i++)
                    {
                        // This is the snippet of code we want to find and change:
                        //     OLD Game1.player.spouse.Contains(this.Name) or who.spouse.Contains(this.Name) (who is Farmer)
                        //     NEW Game1.player.spouse.Equals(this.Name) or who.spouse.Equals(this.Name)
                        // It can be done with a single opcode call change from string.Contains to string.Equals

                        if (//callvirt instance string StardewValley.Farmer::get_spouse()
                            codes[i].opcode == OpCodes.Callvirt &&
                            (MethodInfo)codes[i].operand == typeof(Farmer).GetProperty("spouse").GetGetMethod() &&
                            //ldarg.0
                            codes[i + 1].opcode == OpCodes.Ldarg_0 &&
                            //call instance string StardewValley.Character::get_Name()
                            codes[i + 2].opcode == OpCodes.Call &&
                            (MethodInfo)codes[i + 2].operand == typeof(Character).GetProperty("Name").GetGetMethod() &&
                            //callvirt instance bool[mscorlib] System.String::Contains(string)
                            codes[i + 3].opcode == OpCodes.Callvirt &&
                            (MethodInfo)codes[i + 3].operand == typeof(string).GetMethod("Contains", new Type[] { typeof(string) }))
                        {
                            // Insert the new replacement instruction
                            codes[i + 3] = new CIL(OpCodes.Callvirt, typeof(string).GetMethod("Equals", new Type[] { typeof(string) }));
                            patchCount  += 1;
                        }
                    }
                    // Log results of the patch attempt
                    if (patchCount == 0)
                    {
                        ModMonitor.LogOnce($"Couldn't find a code location to apply {nameof(spouseContainsEquals_Transpiler)} patch to {original.DeclaringType.Name}.{original.Name}\n" +
                                           $"This is probably fine. Maybe a game update or another harmony mod already patched it?", LogLevel.Info);
                    }
                    else //patched at least once
                    {
                        //do stuff
                        ModMonitor.LogOnce($"Applied bugfix patch to {original.DeclaringType.Name}.{original.Name}: {nameof(spouseContainsEquals_Transpiler)}", LogLevel.Trace);

                        if (patchCount > 1)
                        {
                            ModMonitor.LogOnce($"Found an unusual number of patch locations for {nameof(spouseContainsEquals_Transpiler)} in {original.DeclaringType.Name}.{original.Name}\n" +
                                               $"This might cause unexpected behaviour. Please share your SMAPI log with the creator of this mod.", LogLevel.Warn);
                        }
                    }

                    return(codes.AsEnumerable());
                }
                catch (Exception ex)
                {
                    ModMonitor.Log($"Failed in {nameof(spouseContainsEquals_Transpiler)}:\n{ex}", LogLevel.Error);
                    return(instructions); // use original code
                }
            }
Example #11
0
            /// <summary>Adds a hook that calls FixedHUDMessage_Hook inside the game's addItemToInventoryBool method.</summary>
            public static IEnumerable<CIL> addItemToInventoryBool_Transpiler(IEnumerable<CIL> instructions)
            {
                try
                {
                    var codes = new List<CodeInstruction>(instructions);

                    for (int i = 0; i < codes.Count - 9; i++)
                    {
                        // This is the line of code we want to find and change:
                        //     Game1.addHUDMessage(new HUDMessage(displayName, Math.Max(1, item.Stack), true, color, item));
                        //     Game1.addHUDMessage(new HUDMessage(displayName, 1, true, color, item));
                        // We can most easily do this by replacing several instructions with nop

                        if (//ldloc.3
                            codes[i].opcode == OpCodes.Ldloc_3 &&
                            //ldc.i4.1                             // Replace with nop
                            codes[i + 1].opcode == OpCodes.Ldc_I4_1 &&
                            //ldarg.1                                // Replace with nop
                            codes[i + 2].opcode == OpCodes.Ldarg_1 &&
                            //callvirt instance int32 StardewValley.Item::get_Stack() // Replace with nop
                            codes[i + 3].opcode == OpCodes.Callvirt &&
                            (MethodInfo)codes[i + 3].operand == typeof(Item).GetMethod("get_Stack") &&
                            //call int32 [mscorlib]System.Math::Max(int32, int32) // Replace with Ldc_I4_1
                            codes[i + 4].opcode == OpCodes.Call &&
                            (MethodInfo)codes[i + 4].operand == typeof(Math).GetMethod("Max", types: new Type[] { typeof(int), typeof(int) }) &&
                            //ldc.i4.1
                            codes[i + 5].opcode == OpCodes.Ldc_I4_1 &&
                            //ldloc.2
                            codes[i + 6].opcode == OpCodes.Ldloc_2 &&
                            //ldarg.1
                            codes[i + 7].opcode == OpCodes.Ldarg_1 &&
                            //newobj instance void StardewValley.HUDMessage::.ctor(string, int32, bool, valuetype [Microsoft.Xna.Framework]Microsoft.Xna.Framework.Color, class StardewValley.Item)
                            codes[i + 8].opcode == OpCodes.Newobj &&
                            (ConstructorInfo)codes[i + 8].operand == typeof(HUDMessage).GetConstructor(
                                types: new Type[] { typeof(string), typeof(int), typeof(bool), typeof(Color), typeof(Item) }) &&
                            //call void StardewValley.Game1::addHUDMessage(class StardewValley.HUDMessage)
                            codes[i + 9].opcode == OpCodes.Call &&
                            (MethodInfo)codes[i + 9].operand == typeof(Game1).GetMethod("addHUDMessage"))
                        {
                            // Compose the new instructions to use as replacements
                            codes[i + 8] = new CIL(OpCodes.Call, Instance.Helper.Reflection.GetMethod(
                                typeof(FarmerPatch), nameof(FixedHUDMessage_Hook)).MethodInfo); // Call my function that returns a fixed HUDMessage
                            ModMonitor.LogOnce($"Added hook to Farmer.addItemToInventoryBool method: {nameof(addItemToInventoryBool_Transpiler)}", LogLevel.Trace);
                        }
                    }
                    return codes.AsEnumerable();
                }
                catch (Exception ex)
                {
                    ModMonitor.Log($"Failed in {nameof(addItemToInventoryBool_Transpiler)}:\n{ex}", LogLevel.Error);
                    return instructions; // use original code
                }
            }
Example #12
0
 /// <summary>
 /// Applies the patches for this mod.
 /// </summary>
 /// <param name="harmony">This mod's harmony instance.</param>
 /// <remarks>Delay until GameLaunched in order to patch other mods....</remarks>
 private void ApplyPatches(Harmony harmony)
 {
     try
     {
         harmony.PatchAll();
     }
     catch (Exception ex)
     {
         ModMonitor.Log(string.Format(ErrorMessageConsts.HARMONYCRASH, ex), LogLevel.Error);
     }
     harmony.Snitch(this.Monitor, harmony.Id, transpilersOnly: true);
 }
Example #13
0
 public ActionResult Edit([Bind(Include = "ModMonitorID,FabricanteID,FornecedorID,Modelo")] ModMonitor modMonitor)
 {
     if (ModelState.IsValid)
     {
         db.Entry(modMonitor).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.FabricanteID = new SelectList(db.Fabricantes, "IdFabricante", "Nome", modMonitor.FabricanteID);
     ViewBag.FornecedorID = new SelectList(db.Fornecedors, "FornecedorID", "Nome", modMonitor.FornecedorID);
     return(View(modMonitor));
 }
Example #14
0
 private void ApplyPatches(Harmony harmony)
 {
     try
     {
         harmony.PatchAll();
         CaveCrystalTranspiler.ApplyPatch(harmony);
     }
     catch (Exception ex)
     {
         ModMonitor.Log($"Mod failed while applying patches:\n{ex}", LogLevel.Error);
     }
     harmony.Snitch(this.Monitor, UniqueID, transpilersOnly: true);
 }
Example #15
0
        public void Log(params string[] messages)
        {
            string time       = "[" + DateTime.Now.ToString("HH:mm:ss") + "]";
            int    timeLength = time.Length + 1;

            WriteLine($"{time} {messages[0]}");
            ModMonitor?.Log(messages[0]);
            for (int i = 1; i < messages.Length; i++)
            {
                WriteLine($"{messages[i].PadLeft(messages[i].Length + timeLength)}");
                ModMonitor?.Log(messages[i]);
            }
        }
Example #16
0
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ModMonitor modMonitor = db.ModMonitors.Find(id);

            if (modMonitor == null)
            {
                return(HttpNotFound());
            }
            return(View(modMonitor));
        }
Example #17
0
            /// <summary>Insertable, altered HUDMessage constructor that uses a single-stack clone of the original object.</summary>
            public static HUDMessage FixedHUDMessage_Hook(string displayName, int number, bool add, Color color, Item item)
            {
                try
                {
                    Item hudItem = item.getOne(); // Grabs a clone of the item to display in HUDMessage

                    ModMonitor.LogOnce($"Ran patch for HUDMessage creation in Farmer.addItemToInventoryBool method: {nameof(FixedHUDMessage_Hook)}", LogLevel.Trace);
                    return new HUDMessage(displayName, number, add, color, hudItem);
                }
                catch (Exception ex)
                {
                    ModMonitor.Log($"Failed in {nameof(FixedHUDMessage_Hook)}:\n{ex}", LogLevel.Error);
                    return new HUDMessage(displayName, number, add, color, item);
                }
            }
Example #18
0
 /// <summary>
 /// Tries to get a handle on Child2NPC's IsChildNPC.
 /// </summary>
 /// <returns>True if successful, false otherwise.</returns>
 internal static bool GetIsChildToNPC()
 {
     if (ModRegistry.Get("Loe2run.ChildToNPC") is null)
     {
         ModMonitor.Log($"Child2NPC not installed - no need to adjust for that.", LogLevel.Trace);
         return(false);
     }
     if (Type.GetType("ChildToNPC.ModEntry, ChildToNPC")?.GetMethod("IsChildNPC", new Type[] { typeof(Character) }) is MethodInfo childToNPCMethod)
     {
         IsChildToNPC = childToNPCMethod.CreateDelegate <Func <NPC, bool> >();
         return(true);
     }
     ModMonitor.Log("IsChildNPC method not found - integration with Child2NPC failed.", LogLevel.Warn);
     return(false);
 }
Example #19
0
 /// <summary>
 /// Console commands to check the value of a tag.
 /// </summary>
 /// <param name="command">Name of the command.</param>
 /// <param name="args">List of tags to check.</param>
 private void ConsoleCheckTag(string command, string[] args)
 {
     if (!Context.IsWorldReady || CheckTagDelegate is null)
     {
         ModMonitor.Log(I18n.LoadSaveFirst(), LogLevel.Debug);
         return;
     }
     foreach (string tag in args)
     {
         string base_tag;
         bool   match = true;
         if (tag.StartsWith("!"))
         {
             match    = false;
             base_tag = tag.Trim()[1..];
Example #20
0
 /// <summary>
 /// Applies the patches that must be applied after all mods are initialized.
 /// IE - patches on other mods.
 /// </summary>
 /// <param name="harmony">A harmony instance.</param>
 private void ApplyLatePatches(Harmony harmony)
 {
     try
     {
         FruitTreesAvoidHoe.ApplyPatches(harmony, this.Helper.ModRegistry);
         if (!this.Helper.ModRegistry.IsLoaded("DecidedlyHuman.BetterReturnScepter"))
         {
             ConfirmWarp.ApplyWandPatches(harmony);
         }
     }
     catch (Exception ex)
     {
         ModMonitor.Log(string.Format(ErrorMessageConsts.HARMONYCRASH, ex), LogLevel.Error);
     }
     harmony.Snitch(this.Monitor, harmony.Id, transpilersOnly: true);
 }
Example #21
0
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.

    /// <inheritdoc />
    public override void Entry(IModHelper helper)
    {
        ModMonitor = this.Monitor;
        I18n.Init(helper.Translation);
        try
        {
            Config = this.Helper.ReadConfig <ModConfig>();
        }
        catch
        {
            ModMonitor.Log(I18n.IllFormatedConfig(), LogLevel.Warn);
            Config = new();
        }
        this.ApplyPatches(new Harmony(this.ModManifest.UniqueID));
        helper.Events.GameLoop.GameLaunched += this.SetUpConfig;
    }
Example #22
0
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ModMonitor modMonitor = db.ModMonitors.Find(id);

            if (modMonitor == null)
            {
                return(HttpNotFound());
            }
            ViewBag.FabricanteID = new SelectList(db.Fabricantes, "IdFabricante", "Nome", modMonitor.FabricanteID);
            ViewBag.FornecedorID = new SelectList(db.Fornecedors, "FornecedorID", "Nome", modMonitor.FornecedorID);
            return(View(modMonitor));
        }
        private static void PATCH__After_receiveGift(NPC __instance, SObject o)
        {
            try
            {
                string bdaySuffix = __instance.isBirthday(Game1.currentSeason, Game1.dayOfMonth) ? "_Birthday" : "";

                if (GiftDialogueHelper.FetchGiftReaction(__instance, o, out string giftDialogue, bdaySuffix))
                {
                    GiftDialogueHelper.CancelCurrentDialogue(__instance);
                    Game1.drawDialogue(__instance, giftDialogue);
                }
            }
            catch (Exception ex)
            {
                ModMonitor.Log($"An error occurred during handle custom gift reaction dialogue: {ex.Message}", LogLevel.Error);
                ModMonitor.Log(ex.ToString());
            }
        }
Example #24
0
 public static bool HighlightItems_Prefix(StardewValley.Menus.ForgeMenu __instance, Item i, ref bool __result)
 {
     // Override highlight items for the case when the tool is enchanted fully. Base game assumes that a tool will always be enchantable, as every tool has more than one enchantment.
     try
     {
         if (IsEnchantedOrEnchantable(i))
         {
             __result = true;
             return(false); // don't run original logic
         }
         return(true);      // run original logic
     }
     catch (Exception ex)
     {
         ModMonitor.Log($"Failed in {nameof(HighlightItems_Prefix)}:\n{ex}", LogLevel.Error);
         return(true);  // run original logic
     }
 }
Example #25
0
 public static void LoadDisplayFields_Postfix(CombinedRing __instance)
 {
     try
     {
         if (GetCombinedRingTotal(__instance) >= 8)
         {
             string description = "Many Rings forged into one:\n\n";
             foreach (KeyValuePair <string, int> entry in GetCombinedRings(__instance))
             {
                 description += String.Format("{1}x {0}\n", entry.Key, entry.Value);
             }
             ModMonitor.Log($"Combined Ring description is {description}", LogLevel.Trace);
             __instance.description = description.Trim();
         }
     }
     catch (Exception ex)
     {
         ModMonitor.Log($"Failed in {nameof(LoadDisplayFields_Postfix)}:\n{ex}", LogLevel.Error);
     }
 }
Example #26
0
        public void Log(LogOutput logOutput, params string[] messages)
        {
            string time       = "[" + DateTime.Now.ToString("HH:mm:ss") + "]";
            int    timeLength = time.Length + 1;

            if (logOutput == LogOutput.File || logOutput == LogOutput.Both)
            {
                WriteLine($"{time} {messages[0]}");
            }

            if (logOutput == LogOutput.Console || logOutput == LogOutput.Both)
            {
                ModMonitor?.Log(messages[0]);
                for (int i = 1; i < messages.Length; i++)
                {
                    WriteLine($"{messages[i].PadLeft(messages[i].Length + timeLength)}");
                    ModMonitor?.Log(messages[i]);
                }
            }
        }
Example #27
0
        public static bool SpendRightItem_Prefix(ref ForgeMenu.CraftState ____craftState)
        {
            try
            {
                if (____craftState == ForgeMenu.CraftState.InvalidRecipe)
                {
                    // return state to the original one, just to avoid messing up anymore than we already are.
                    ____craftState = ForgeMenu.CraftState.Valid;

                    ModMonitor.Log($"Was an unstable forge, but wont consume the right item.", LogLevel.Trace);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                ModMonitor.Log($"Failed in {nameof(SpendRightItem_Prefix)}:\n{ex}", LogLevel.Error);
            }
            ModMonitor.Log($"running Original SpendRightItem", LogLevel.Trace);
            return(true);
        }
Example #28
0
 public static bool CanAddEnchantment_Prefix(Tool __instance, BaseEnchantment enchantment, ref bool __result)
 {
     try
     {
         if (enchantment == null)
         {
             return(true); // run original logic
         }
         if (__instance is MeleeWeapon && enchantment.IsForge())
         {
             if (enchantment is DiamondEnchantment && GetValidForgeEnchantmentsForTool(__instance).Count <= 0)
             {
                 // No more forge enchantments can be added.
                 __result = false;
                 return(false);
             }
             // Enchantment is a normal forge enchantment, check the existing level if there is one
             foreach (BaseEnchantment exisiting_enchantment in __instance.enchantments)
             {
                 if (enchantment.GetType() == exisiting_enchantment.GetType())
                 {
                     if (exisiting_enchantment.GetLevel() >= 3)
                     {
                         __result = false;
                         return(false);
                     }
                     break;
                 }
             }
             __result = true;
             return(false);
         }
         return(true);
     }
     catch (Exception ex)
     {
         ModMonitor.Log($"Failed in {nameof(CanAddEnchantment_Prefix)}:\n{ex}", LogLevel.Error);
         return(true); // run original logic
     }
 }
Example #29
0
 public static bool CanCombine_Prefix(Ring __instance, Ring ring, ref bool __result)
 {
     try
     {
         __result = true;
         if (ring is CombinedRing)
         {
             foreach (Ring combinedRing in (ring as CombinedRing).combinedRings)
             {
                 if (!__instance.CanCombine(combinedRing))
                 {
                     __result = false;
                     break;
                 }
             }
         }
         else if (__instance is CombinedRing)
         {
             foreach (Ring combinedRing in (__instance as CombinedRing).combinedRings)
             {
                 if (!combinedRing.CanCombine(ring))
                 {
                     __result = false;
                     break;
                 }
             }
         }
         else if (__instance.ParentSheetIndex == ring.ParentSheetIndex)
         {
             __result = false;
         }
         return(false); // don't run original logic
     }
     catch (Exception ex)
     {
         ModMonitor.Log($"Failed in {nameof(CanCombine_Prefix)}:\n{ex}", LogLevel.Error);
         return(true); // run original logic
     }
 }
Example #30
0
        public static void _UpdateDescriptionText_Postfix(ForgeMenu __instance, ref string ___displayedDescription)
        {
            try
            {
                if (__instance.inventory != null && __instance.leftIngredientSpot != null && __instance.rightIngredientSpot != null)
                {
                    Item left_item  = __instance.leftIngredientSpot.item;
                    Item right_item = __instance.rightIngredientSpot.item;



                    if (left_item != null && right_item != null)
                    {
                        if (left_item.getCategoryName().Equals("Ring") && left_item.category == right_item.category)
                        {
                            Ring left_ring  = (Ring)left_item;
                            Ring right_ring = (Ring)right_item;

                            int total_left_rings  = GetCombinedRingTotal(left_ring);
                            int total_right_rings = GetCombinedRingTotal(right_ring);
                            int total_rings       = total_left_rings + total_right_rings;
                            int cost = GetTotalCombinedRingsCost(total_rings);
                            if (total_rings > 2)
                            {
                                ___displayedDescription += $"\nCost: {cost}";
                            }
                            int sucess_rate = 100 - GetBreakChance(total_rings);
                            ___displayedDescription += $"\nChance of sucess: {sucess_rate}%";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ModMonitor.Log($"Failed in {nameof(_UpdateDescriptionText_Postfix)}:\n{ex}", LogLevel.Error);
            }
        }