Xyberviri

CraftingController.cs

Mar 29th, 2015
608
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 22.79 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using UnityEngine;
  6.  
  7. namespace Oxide.Plugins
  8. {
  9.  
  10.     [Info("Crafting Controller", "Mughisi", "2.4.1", ResourceId = 695)]
  11.     class CraftingController : RustPlugin
  12.     {
  13.  
  14.         #region Configuration Data
  15.         // Do not modify these values, to configure this plugin edit
  16.         // 'CraftingController.json' in your server's config folder.
  17.         // <drive>:\...\server\<server identity>\oxide\config\
  18.  
  19.         private bool configChanged;
  20.  
  21.         // Plugin settings
  22.         private const string DefaultChatPrefix = "Crafting Controller";
  23.         private const string DefaultChatPrefixColor = "#008000ff";
  24.  
  25.         public string ChatPrefix { get; private set; }
  26.         public string ChatPrefixColor { get; private set; }
  27.  
  28.         // Plugin options
  29.         private const float DefaultCraftingRate = 100;
  30.         private const bool DefaultAdminInstantCraft = true;
  31.         private const bool DefaultModeratorInstantCraft = false;
  32.         private const bool DefaultCompleteCurrentCraftingOnShutdown = false;
  33.  
  34.         public float CraftingRate { get; private set; }
  35.         public bool AdminInstantCraft { get; private set; }
  36.         public bool ModeratorInstantCraft { get; private set; }
  37.         public bool CompleteCurrentCrafting { get; private set; }
  38.  
  39.         // Plugin options - blocked items
  40.         private static readonly List<object> DefaultBlockedItems = new List<object>();
  41.         private static readonly Dictionary<string, object> DefaultIndividualRates = new Dictionary<string, object>();  
  42.  
  43.         public List<string> BlockedItems { get; private set; }
  44.         public Dictionary<string, float> IndividualRates { get; private set; }
  45.  
  46.         // Plugin messages
  47.         private const string DefaultCurrentCraftingRate = "The crafting rate is set to {0}%.";
  48.         private const string DefaultModifyCraftingRate = "The crafting rate is now set to {0}%.";
  49.         private const string DefaultModifyCraftingRateItem = "The crafting rate for {0} is now set to {1}%.";
  50.         private const string DefaultModifyError = "The new crafting rate must be a number. 0 is instant craft, 100 is normal and 200 is double!";
  51.         private const string DefaultCraftBlockedItem = "{0} is blocked and can not be crafted!";
  52.         private const string DefaultNoItemSpecified = "You need to specify an item for this command.";
  53.         private const string DefaultNoItemRate = "You need to specify an item and a new crafting rate for this command.";
  54.         private const string DefaultInvalidItem = "{0} is not a valid item. Please use the name of the item as it appears in the item list. Ex: Camp Fire";
  55.         private const string DefaultBlockedItem = "{0} has already been blocked!";
  56.         private const string DefaultBlockSucces = "{0} has been blocked from crafting.";
  57.         private const string DefaultUnblockItem = "{0} is not blocked!";
  58.         private const string DefaultUnblockSucces = "{0} is no longer blocked from crafting.";
  59.         private const string DefaultNoPermission = "You don't have permission to use this command.";
  60.         private const string DefaultShowBlockedItems = "The following items are blocked: ";
  61.         private const string DefaultNoBlockedItems = "No items have been blocked.";
  62.  
  63.         public string CurrentCraftingRate { get; private set; }
  64.         public string ModifyCraftingRate { get; private set; }
  65.         public string ModifyCraftingRateItem { get; private set; }
  66.         public string ModifyError { get; private set; }
  67.         public string CraftBlockedItem { get; private set; }
  68.         public string NoItemSpecified { get; private set; }
  69.         public string NoItemRate { get; private set; }
  70.         public string InvalidItem { get; private set; }
  71.         public string BlockedItem { get; private set; }
  72.         public string BlockSucces { get; private set; }
  73.         public string UnblockItem { get; private set; }
  74.         public string UnblockSucces { get; private set; }
  75.         public string NoPermission { get; private set; }
  76.         public string ShowBlockedItems { get; private set; }
  77.         public string NoBlockedItems { get; private set; }
  78.  
  79.         #endregion
  80.  
  81.         List<ItemBlueprint> blueprintDefinitions = new List<ItemBlueprint>();
  82.  
  83.         public Dictionary<string, float> Blueprints { get; } = new Dictionary<string, float>();
  84.  
  85.         List<ItemDefinition> itemDefinitions = new List<ItemDefinition>();
  86.  
  87.         public List<string> Items { get; } = new List<string>();
  88.  
  89.         private readonly MethodInfo finishCraftingTask = typeof(ItemCrafter).GetMethod("FinishCrafting", BindingFlags.NonPublic | BindingFlags.Instance);
  90.        
  91.         private void Loaded() => LoadConfigValues();
  92.  
  93.         private void OnServerInitialized()
  94.         {
  95.             var gameObjectArray = FileSystem.LoadAll<GameObject>("Assets/", ".item");
  96.  
  97.             blueprintDefinitions.Clear();
  98.             blueprintDefinitions = gameObjectArray.Select(x => x.GetComponent<ItemBlueprint>()).Where(x1 => x1 != null).ToList();
  99.             foreach (var bp in blueprintDefinitions)
  100.                 Blueprints.Add(bp.targetItem.shortname, bp.time);
  101.  
  102.             itemDefinitions.Clear();
  103.             itemDefinitions = gameObjectArray.Select(x => x.GetComponent<ItemDefinition>()).Where(x => x != null).ToList();
  104.             foreach (var itemdef in itemDefinitions)
  105.                 Items.Add(itemdef.displayName.english);
  106.  
  107.             UpdateCraftingRate();
  108.         }
  109.  
  110.         private void Unloaded()
  111.         {
  112.             foreach (var bp in blueprintDefinitions)
  113.                 bp.time = Blueprints[bp.targetItem.shortname];
  114.         }
  115.  
  116.         protected override void LoadDefaultConfig() => PrintWarning("New configuration file created.");
  117.  
  118.         private void LoadConfigValues()
  119.         {
  120.             // Plugin settings
  121.             ChatPrefix = GetConfigValue("Settings", "ChatPrefix", DefaultChatPrefix);
  122.             ChatPrefixColor = GetConfigValue("Settings", "ChatPrefixColor", DefaultChatPrefixColor);
  123.  
  124.             // Plugin options
  125.             AdminInstantCraft = GetConfigValue("Options", "InstantCraftForAdmins", DefaultAdminInstantCraft);
  126.             ModeratorInstantCraft = GetConfigValue("Options", "InstantCraftForModerators", DefaultModeratorInstantCraft);
  127.             CraftingRate = GetConfigValue("Options", "CraftingRate", DefaultCraftingRate);
  128.             CompleteCurrentCrafting = GetConfigValue("Options", "CompleteCurrentCraftingOnShutdown", DefaultCompleteCurrentCraftingOnShutdown);
  129.  
  130.            
  131.             // Plugin options - blocked items
  132.             var list = GetConfigValue("Options", "BlockedItems", DefaultBlockedItems);
  133.             var dict = GetConfigValue("Options", "IndividualCraftingRates", DefaultIndividualRates);
  134.  
  135.             BlockedItems = new List<string>();
  136.             foreach (var item in list)
  137.                 BlockedItems.Add(item.ToString());
  138.  
  139.             IndividualRates = new Dictionary<string, float>();
  140.             foreach (var entry in dict)
  141.             {
  142.                 float rate;
  143.                 if (!float.TryParse(entry.Value.ToString(), out rate)) continue;
  144.                 IndividualRates.Add(entry.Key, rate);
  145.             }
  146.  
  147.             // Plugin messages
  148.             CurrentCraftingRate = GetConfigValue("Messages", "CurrentCraftingRate", DefaultCurrentCraftingRate);
  149.             ModifyCraftingRate = GetConfigValue("Messages", "ModifyCraftingRate", DefaultModifyCraftingRate);
  150.             ModifyCraftingRateItem = GetConfigValue("Messages", "ModifyCraftingRateItem", DefaultModifyCraftingRateItem);
  151.             ModifyError = GetConfigValue("Messages", "ModifyCraftingRateError", DefaultModifyError);
  152.             CraftBlockedItem = GetConfigValue("Messages", "CraftBlockedItem", DefaultCraftBlockedItem);
  153.             NoItemSpecified = GetConfigValue("Messages", "NoItemSpecified", DefaultNoItemSpecified);
  154.             NoItemRate = GetConfigValue("Messages", "NoItemRate", DefaultNoItemRate);
  155.             InvalidItem = GetConfigValue("Messages", "InvalidItem", DefaultInvalidItem);
  156.             BlockedItem = GetConfigValue("Messages", "BlockedItem", DefaultBlockedItem);
  157.             BlockSucces = GetConfigValue("Messages", "BlockSucces", DefaultBlockSucces);
  158.             UnblockItem = GetConfigValue("Messages", "UnblockItem", DefaultUnblockItem);
  159.             UnblockSucces = GetConfigValue("Messages", "UnblockSucces", DefaultUnblockSucces);
  160.             NoPermission = GetConfigValue("Messages", "NoPermission", DefaultNoPermission);
  161.             ShowBlockedItems = GetConfigValue("Messages", "ShowBlockedItems", DefaultShowBlockedItems);
  162.             NoBlockedItems = GetConfigValue("Messages", "NoBlockedItems", DefaultNoBlockedItems);
  163.  
  164.             if (!configChanged) return;
  165.             Puts("Configuration file updated.");
  166.             SaveConfig();
  167.         }
  168.  
  169.         #region Chat/Console command to check/alter the crafting rate.
  170.  
  171.         [ChatCommand("rate")]
  172.         private void CraftCommandChat(BasePlayer player, string command, string[] args)
  173.         {
  174.             if (args.Length == 0)
  175.             {
  176.                 SendChatMessage(player, CurrentCraftingRate, CraftingRate);
  177.                 return;
  178.             }
  179.  
  180.             if (!player.IsAdmin())
  181.             {
  182.                 SendChatMessage(player, NoPermission);
  183.                 return;
  184.             }
  185.            
  186.             float rate;
  187.             if (!float.TryParse(args[0], out rate))
  188.             {
  189.                 SendChatMessage(player, ModifyError);
  190.                 return;
  191.             }
  192.            
  193.             CraftingRate = rate;
  194.             SetConfigValue("Options", "CraftingRate", rate);
  195.             UpdateCraftingRate();
  196.             SendChatMessage(player, ModifyCraftingRate, CraftingRate);
  197.         }
  198.  
  199.         [ConsoleCommand("crafting.rate")]
  200.         private void CraftCommandConsole(ConsoleSystem.Arg arg)
  201.         {
  202.             if (!arg.HasArgs())
  203.             {
  204.                 arg.ReplyWith(string.Format(CurrentCraftingRate, CraftingRate));
  205.                 return;
  206.             }
  207.  
  208.             if (arg.Player() != null && !arg.Player().IsAdmin())
  209.             {
  210.                 arg.ReplyWith(NoPermission);
  211.                 return;
  212.             }
  213.  
  214.             var rate = arg.GetFloat(0, -1f);
  215.             if (rate == -1f)
  216.             {
  217.                 arg.ReplyWith(ModifyError);
  218.                 return;
  219.             }
  220.  
  221.             CraftingRate = rate;
  222.             SetConfigValue("Options", "CraftingRate", rate);
  223.             UpdateCraftingRate();
  224.             arg.ReplyWith(string.Format(ModifyCraftingRate, CraftingRate));
  225.         }
  226.  
  227.         #endregion
  228.  
  229.         #region Chat/Console command to alter the crafting rate of a single item.
  230.  
  231.         [ChatCommand("itemrate")]
  232.         private void CraftItemCommandChat(BasePlayer player, string command, string[] args)
  233.         {
  234.             if (!player.IsAdmin())
  235.             {
  236.                 SendChatMessage(player, NoPermission);
  237.                 return;
  238.             }
  239.  
  240.             if (args.Length == 0 || args.Length < 2)
  241.             {
  242.                 SendChatMessage(player, NoItemRate);
  243.                 return;
  244.             }
  245.  
  246.             float rate;
  247.             if (!float.TryParse(args[args.Length -1], out rate))
  248.             {
  249.                 SendChatMessage(player, ModifyError);
  250.                 return;
  251.             }
  252.  
  253.             var item = string.Empty;
  254.             for (var i = 0; i < args.Length - 1; i++)
  255.                 item += args[i] + " ";
  256.             item = item.Trim();
  257.  
  258.             if (!Items.Contains(item))
  259.             {
  260.                 SendChatMessage(player, InvalidItem, item);
  261.                 return;
  262.             }
  263.  
  264.  
  265.             if (IndividualRates.ContainsKey(item))
  266.                 IndividualRates[item] = rate;
  267.             else
  268.                 IndividualRates.Add(item, rate);
  269.  
  270.             SetConfigValue("Options", "IndividualCraftingRates", IndividualRates);
  271.             SendChatMessage(player, ModifyCraftingRateItem, item, rate);
  272.             UpdateCraftingRate();
  273.         }
  274.  
  275.         [ConsoleCommand("crafting.itemrate")]
  276.         private void CraftItemCommandConsole(ConsoleSystem.Arg arg)
  277.         {
  278.             if (arg.Player() != null && !arg.Player().IsAdmin())
  279.             {
  280.                 arg.ReplyWith(NoPermission);
  281.                 return;
  282.             }
  283.            
  284.             if (!arg.HasArgs(2))
  285.             {
  286.                 arg.ReplyWith(NoItemRate);
  287.                 return;
  288.             }
  289.  
  290.             var rate = arg.GetFloat(arg.Args.Length - 1, -1f);
  291.             if (rate == -1f)
  292.             {
  293.                 arg.ReplyWith(ModifyError);
  294.                 return;
  295.             }
  296.  
  297.             var item = string.Empty;
  298.             for (var i = 0; i < arg.Args.Length - 1; i++)
  299.                 item += arg.Args[i] + " ";
  300.             item = item.Trim();
  301.  
  302.             if (!Items.Contains(item))
  303.             {
  304.                 arg.ReplyWith(string.Format(InvalidItem, item, rate));
  305.                 return;
  306.             }
  307.  
  308.             if (IndividualRates.ContainsKey(item))
  309.                 IndividualRates[item] = rate;
  310.             else
  311.                 IndividualRates.Add(item, rate);
  312.  
  313.             SetConfigValue("Options", "IndividualCraftingRates", IndividualRates);
  314.             arg.ReplyWith(string.Format(ModifyCraftingRateItem, item, rate));
  315.             UpdateCraftingRate();
  316.         }
  317.  
  318.         #endregion
  319.  
  320.         #region Chat/Console command to block an item from being crafted.
  321.  
  322.         [ChatCommand("block")]
  323.         private void BlockCommandChat(BasePlayer player, string command, string[] args)
  324.         {
  325.             if (!player.IsAdmin())
  326.             {
  327.                 SendChatMessage(player, NoPermission);
  328.                 return;
  329.             }
  330.  
  331.             if (args.Length == 0)
  332.             {
  333.                 SendChatMessage(player, NoItemSpecified);
  334.                 return;
  335.             }
  336.  
  337.             var item = string.Join(" ", args);
  338.             if (!Items.Contains(item))
  339.             {
  340.                 SendChatMessage(player, InvalidItem, item);
  341.                 return;
  342.             }
  343.  
  344.             if (BlockedItems.Contains(item))
  345.             {
  346.                 SendChatMessage(player, BlockedItem, item);
  347.                 return;
  348.             }
  349.  
  350.             BlockedItems.Add(item);
  351.             SetConfigValue("Options", "BlockedItems", BlockedItems);
  352.             SendChatMessage(player, BlockSucces, item);
  353.         }
  354.  
  355.         [ConsoleCommand("crafting.block")]
  356.         private void BlockCommandConsole(ConsoleSystem.Arg arg)
  357.         {
  358.             if (arg.Player() != null && !arg.Player().IsAdmin())
  359.             {
  360.                 arg.ReplyWith(NoPermission);
  361.                 return;
  362.             }
  363.  
  364.             if (!arg.HasArgs(1))
  365.             {
  366.                 arg.ReplyWith(NoItemSpecified);
  367.                 return;
  368.             }
  369.  
  370.             var item = string.Join(" ", arg.Args);
  371.             if (!Items.Contains(item))
  372.             {
  373.                 arg.ReplyWith(string.Format(InvalidItem, item));
  374.                 return;
  375.             }
  376.  
  377.             if (BlockedItems.Contains(item))
  378.             {
  379.                 arg.ReplyWith(string.Format(BlockedItem, item));
  380.                 return;
  381.             }
  382.  
  383.             BlockedItems.Add(item);
  384.             SetConfigValue("Options", "BlockedItems", BlockedItems);
  385.             arg.ReplyWith(string.Format(BlockSucces, item));
  386.         }
  387.  
  388.         #endregion
  389.  
  390.         #region Chat/Console command to unblock an item from being crafted.
  391.  
  392.         [ChatCommand("unblock")]
  393.         private void UnblockCommandChat(BasePlayer player, string command, string[] args)
  394.         {
  395.             if (player.net.connection.authLevel == 2)
  396.             {
  397.                 if (args.Length == 0)
  398.                 {
  399.                     SendChatMessage(player, NoItemSpecified);
  400.                     return;
  401.                 }
  402.  
  403.                 var item = string.Join(" ", args);
  404.                 if (item != "*")
  405.                 {
  406.                     if (!Items.Contains(item))
  407.                     {
  408.                         SendChatMessage(player, InvalidItem, item);
  409.                         return;
  410.                     }
  411.  
  412.                     if (!BlockedItems.Contains(item))
  413.                     {
  414.                         SendChatMessage(player, UnblockItem, item);
  415.                         return;
  416.                     }
  417.  
  418.                     BlockedItems.Remove(item);
  419.                 }
  420.                 else
  421.                     BlockedItems = new List<string>();
  422.  
  423.                 SetConfigValue("Options", "BlockedItems", BlockedItems);
  424.                 SendChatMessage(player, UnblockSucces, item);
  425.                 return;
  426.             }
  427.             SendChatMessage(player, NoPermission);
  428.         }
  429.  
  430.         [ConsoleCommand("crafting.unblock")]
  431.         private void UnblockCommandConsole(ConsoleSystem.Arg arg)
  432.         {
  433.             if (arg.Player() != null && !arg.Player().IsAdmin())
  434.             {
  435.                 arg.ReplyWith(NoPermission);
  436.                 return;
  437.             }
  438.  
  439.             if (!arg.HasArgs())
  440.             {
  441.                 arg.ReplyWith(NoItemSpecified);
  442.                 return;
  443.             }
  444.  
  445.             var item = string.Join(" ", arg.Args);
  446.             if (item != "*")
  447.             {
  448.                 if (!Items.Contains(item))
  449.                 {
  450.                     arg.ReplyWith(string.Format(InvalidItem, item));
  451.                     return;
  452.                 }
  453.  
  454.                 if (!BlockedItems.Contains(item))
  455.                 {
  456.                     arg.ReplyWith(string.Format(UnblockItem, item));
  457.                     return;
  458.                 }
  459.  
  460.                 BlockedItems.Remove(item);
  461.             }
  462.             else
  463.                 BlockedItems = new List<string>();
  464.  
  465.             SetConfigValue("Options", "BlockedItems", BlockedItems);
  466.             arg.ReplyWith(string.Format(UnblockSucces, item));
  467.         }
  468.  
  469.         #endregion
  470.  
  471.         [ChatCommand("blocked")]
  472.         private void BlockedItemsList(BasePlayer player, string command, string[] args)
  473.         {
  474.             if (BlockedItems.Count == 0)
  475.                 SendChatMessage(player, NoBlockedItems);
  476.             else
  477.             {
  478.                 SendChatMessage(player, ShowBlockedItems);
  479.                 foreach (var item in BlockedItems)
  480.                     SendChatMessage(player, item);
  481.             }
  482.         }
  483.  
  484.         private void SendHelpText(BasePlayer player) => SendChatMessage(player, CurrentCraftingRate, CraftingRate);
  485.  
  486.         private void OnServerQuit()
  487.         {
  488.             foreach (var player in BasePlayer.activePlayerList)
  489.             {
  490.                 if (CompleteCurrentCrafting)
  491.                     CompleteCrafting(player);
  492.  
  493.                 CancelAllCrafting(player);
  494.             }
  495.         }
  496.  
  497.         private void CompleteCrafting(BasePlayer player)
  498.         {
  499.             var crafter = player.inventory.crafting;
  500.             if (crafter.queue.Count == 0) return;
  501.             var task = crafter.queue.First<ItemCraftTask>();
  502.             finishCraftingTask.Invoke(crafter, new object[] { task });
  503.             crafter.queue.Dequeue();
  504.         }
  505.  
  506.         private static void CancelAllCrafting(BasePlayer player)
  507.         {
  508.             var crafter = player.inventory.crafting;
  509.             foreach (var task in crafter.queue)
  510.                 crafter.CancelTask(task.taskUID, true);
  511.         }
  512.  
  513.         private void UpdateCraftingRate()
  514.         {
  515.             foreach (var bp in blueprintDefinitions)
  516.             {
  517.                 if (IndividualRates.ContainsKey(bp.targetItem.displayName.english))
  518.                     bp.time = Blueprints[bp.targetItem.shortname] * IndividualRates[bp.targetItem.displayName.english] / 100;
  519.                 else
  520.                     bp.time = Blueprints[bp.targetItem.shortname]*CraftingRate/100;
  521.             }
  522.         }
  523.  
  524.         private object OnItemCraft(ItemCraftTask item, BasePlayer crafter)
  525.         {
  526.             var itemname = item.blueprint.targetItem.displayName.english;
  527.             if (AdminInstantCraft && item.owner.net.connection.authLevel == 2) return InstantAdminBulkCraft(crafter, item);
  528.             if (ModeratorInstantCraft && item.owner.net.connection.authLevel == 1) return InstantAdminBulkCraft(crafter, item);
  529.             if (!BlockedItems.Contains(itemname)) return null;
  530.             item.cancelled = true;
  531.             SendChatMessage(crafter, CraftBlockedItem, itemname);
  532.             for(var i = 1; i <= item.amount; i++)
  533.                 foreach (var amount in item.blueprint.ingredients)
  534.                     crafter.inventory.GiveItem(amount.itemid, (int)amount.amount * item.amount, false);
  535.  
  536.             return false;
  537.         }
  538.         private static bool InstantAdminBulkCraft(BasePlayer player, ItemCraftTask task)
  539.         {
  540.             var crafter = player.inventory.crafting;
  541.             var amount = task.amount;
  542.  
  543.             for (var i = 1; i <= amount; i++)
  544.             {
  545.                 crafter.taskUID++;
  546.                 var item = new ItemCraftTask
  547.                 {
  548.                     blueprint = task.blueprint,
  549.                     endTime = 1f,
  550.                     taskUID = crafter.taskUID,
  551.                     owner = player,
  552.                     instanceData = null
  553.                 };
  554.  
  555.                 crafter.queue.Enqueue(item);
  556.                 item.owner?.Command("note.craft_add", item.taskUID, item.blueprint.targetItem.itemid);
  557.             }
  558.  
  559.             return false;
  560.         }
  561.  
  562.         #region Helper methods
  563.  
  564.         private void SendChatMessage(BasePlayer player, string message, params object[] args) => player?.SendConsoleCommand("chat.add", -1, string.Format($"<color={ChatPrefixColor}>{ChatPrefix}</color>: {message}", args), 1.0);
  565.  
  566.         T GetConfigValue<T>(string category, string setting, T defaultValue)
  567.         {
  568.             var data = Config[category] as Dictionary<string, object>;
  569.             object value;
  570.             if (data == null)
  571.             {
  572.                 data = new Dictionary<string, object>();
  573.                 Config[category] = data;
  574.                 configChanged = true;
  575.             }
  576.             if (data.TryGetValue(setting, out value)) return (T)Convert.ChangeType(value, typeof(T));
  577.             value = defaultValue;
  578.             data[setting] = value;
  579.             configChanged = true;
  580.             return (T)Convert.ChangeType(value, typeof(T));
  581.         }
  582.  
  583.         void SetConfigValue<T>(string category, string setting, T newValue)
  584.         {
  585.             var data = Config[category] as Dictionary<string, object>;
  586.             object value;
  587.             if (data != null && data.TryGetValue(setting, out value))
  588.             {
  589.                 value = newValue;
  590.                 data[setting] = value;
  591.                 configChanged = true;
  592.             }
  593.             SaveConfig();
  594.         }
  595.  
  596.         #endregion
  597.     }
  598.  
  599. }
Advertisement
Add Comment
Please, Sign In to add comment