using System;
using System.Collections.Generic;
using System.Linq;
using Facepunch;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("TurboWeapons", "Marte6", "1.0.0")]
[Description("Customizes reload speeds and capacities for firearms.")]
public class TurboWeapons : RustPlugin
{
[PluginReference]
private Plugin ImageLibrary = null,
LangAPI = null,
Notify = null;
private const string UseFastReloadPermission = "turboweapons.use";
private const string ReloadConfigPermission = "turboweapons.reloadconfig";
private const string CommandOpenUi = "ui";
private const string CommandToggleFastReload = "turboweapons.togglefastreload";
private const string CommandSetCapacity = "turboweapons.setcapacity";
private const string CommandCloseUi = "turboweapons.closeui";
private const string CommandChangePage = "turboweapons.changepage";
private const string PanelName = "TurboWeaponsUI";
private const string DefaultImage = "DefaultImage";
private const int ItemsPerPage = 8;
private readonly Dictionary<ulong, int> playerPages = new Dictionary<ulong, int>();
private Configuration _configs;
#region Hooks
private void Init()
{
permission.RegisterPermission(UseFastReloadPermission, this);
permission.RegisterPermission(ReloadConfigPermission, this);
}
private void OnServerInitialized()
{
if (ImageLibrary == null || !ImageLibrary.IsLoaded)
{
PrintError("ImageLibrary is not loaded!");
return;
}
LoadWeaponImages();
}
private void Unload()
{
DestroyAllUis();
}
object OnWeaponReload(BaseProjectile weapon, BasePlayer player)
{
if (!HasPermission(player, UseFastReloadPermission))
return null;
var weaponConfig = GetWeaponConfig(weapon);
if (weaponConfig == null || !weaponConfig.FastReload)
return null;
if (!PrepareAmmoForReload(player, weapon, out var ammoType, out var ammoToLoad))
return null;
ExecuteReload(player, weapon, ammoToLoad, ammoType);
return false;
}
#endregion
#region Image Handling
private void LoadWeaponImages()
{
if (_configs == null || ImageLibrary == null || !ImageLibrary.IsLoaded)
{
PrintError("Configuration or ImageLibrary is not properly loaded.");
return;
}
ImageLibrary?.Call("AddImage", "https://i.ibb.co/nzvwD3N/pngegg.png", DefaultImage);
foreach (var weaponConfig in _configs.WeaponConfigurations)
{
string url = $"https://rustlabs.com/img/items180/{weaponConfig.Shortname}.png";
ImageLibrary?.Call("AddImage", url, weaponConfig.Shortname);
}
}
private string GetWeaponImage(string shortname)
{
string image;
if ((bool)(ImageLibrary?.Call("HasImage", shortname, 0UL) ?? false))
image = Convert.ToString(ImageLibrary?.Call("GetImage", shortname, 0UL, false));
else
image = Convert.ToString(ImageLibrary?.Call("GetImage", DefaultImage, 0UL, false));
return image;
}
#endregion
#region UI Methods
private void DestroyAllUis()
{
foreach (BasePlayer player in BasePlayer.activePlayerList)
CuiHelper.DestroyUi(player, PanelName);
}
private void ShowWeaponConfigUI(BasePlayer player, int page)
{
if (!HasPermission(player, ReloadConfigPermission))
{
NotifyPlayer(player, "NoPermission", 1);
return;
}
CuiHelper.DestroyUi(player, PanelName);
int totalPages = (int)Math.Ceiling(_configs.WeaponConfigurations.Count / (float)ItemsPerPage);
page = Mathf.Clamp(page, 0, totalPages - 1);
playerPages[player.userID] = page;
var container = new CuiElementContainer();
string panel = container.Add(
new CuiPanel
{
Image = { Color = "0.1 0.1 0.1 0.8" },
RectTransform = { AnchorMin = "0.2 0.2", AnchorMax = "0.8 0.8" },
CursorEnabled = true,
},
"Overlay",
PanelName
);
// Title Label
container.Add(
new CuiLabel
{
Text =
{
FontSize = 22,
Align = TextAnchor.MiddleCenter,
Text = "Turbo Weapons Configuration",
},
RectTransform = { AnchorMin = "0 0.95", AnchorMax = "1 1" },
},
panel
);
var sortedWeapons = _configs.WeaponConfigurations.OrderBy(config => GetItemDisplayName(player, config.Shortname)).ToList();
int start = page * ItemsPerPage;
int end = Math.Min(start + ItemsPerPage, sortedWeapons.Count);
for (int i = start; i < end; i++)
{
var weaponConfig = sortedWeapons[i];
int rowIndex = i - start;
float topY = 0.87f - rowIndex * 0.1f;
float bottomY = topY - 0.05f;
container.Add(
new CuiLabel
{
Text =
{
FontSize = 14,
Align = TextAnchor.MiddleLeft,
Text = GetItemDisplayName(player, weaponConfig.Shortname),
},
RectTransform = { AnchorMin = $"0.05 {bottomY}", AnchorMax = $"0.35 {topY}" },
},
panel
);
string imageUrl = GetWeaponImage(weaponConfig.Shortname);
if (!string.IsNullOrEmpty(imageUrl))
{
container.Add(
new CuiElement
{
Parent = panel,
Components =
{
new CuiRawImageComponent { Png = imageUrl },
new CuiRectTransformComponent { AnchorMin = $"0.36 {bottomY}", AnchorMax = $"0.39 {topY}" },
},
}
);
}
container.Add(
new CuiButton
{
Text =
{
Text = weaponConfig.FastReload ? "Enabled" : "Disabled",
FontSize = 14,
Align = TextAnchor.MiddleCenter,
},
Button = { Command = $"{CommandToggleFastReload} {weaponConfig.Shortname}", Color = weaponConfig.FastReload ? "0.1 0.8 0.1 0.8" : "0.8 0.1 0.1 0.8" },
RectTransform = { AnchorMin = $"0.4 {bottomY}", AnchorMax = $"0.5 {topY}" },
},
panel
);
// Input Field for Magazine Capacity
container.Add(
new CuiPanel
{
Image = { Color = "0.9 0.9 0.9 0.4" },
RectTransform = { AnchorMin = $"0.55 {bottomY}", AnchorMax = $"0.65 {topY}" },
CursorEnabled = true,
},
panel,
$"Input_{weaponConfig.Shortname}"
);
container.Add(
new CuiElement
{
Parent = $"Input_{weaponConfig.Shortname}",
Components =
{
new CuiInputFieldComponent
{
Align = TextAnchor.MiddleCenter,
FontSize = 14,
Text = weaponConfig.MagazineCapacity.ToString(),
Command = $"{CommandSetCapacity} {weaponConfig.Shortname} ",
Color = "0 0 0 1",
CharsLimit = 5,
},
new CuiRectTransformComponent { AnchorMin = "0 0", AnchorMax = "1 1" },
},
}
);
}
if (page > 0)
{
container.Add(
new CuiButton
{
Text =
{
Text = "Previous",
FontSize = 14,
Align = TextAnchor.MiddleCenter,
},
Button = { Command = $"{CommandChangePage} {page - 1}", Color = "0.2 0.6 0.2 0.8" },
RectTransform = { AnchorMin = "0.15 0.05", AnchorMax = "0.25 0.1" },
},
panel
);
}
if (page < totalPages - 1)
{
container.Add(
new CuiButton
{
Text =
{
Text = "Next",
FontSize = 14,
Align = TextAnchor.MiddleCenter,
},
Button = { Command = $"{CommandChangePage} {page + 1}", Color = "0.2 0.6 0.2 0.8" },
RectTransform = { AnchorMin = "0.75 0.05", AnchorMax = "0.85 0.1" },
},
panel
);
}
container.Add(
new CuiButton
{
Text =
{
Text = "Close",
FontSize = 14,
Align = TextAnchor.MiddleCenter,
},
Button = { Command = CommandCloseUi, Color = "0.7 0.3 0.3 0.8" },
RectTransform = { AnchorMin = "0.9 0", AnchorMax = "1 0.05" },
},
panel
);
CuiHelper.AddUi(player, container);
}
public string GetItemDisplayName(BasePlayer player, string itemShortName)
{
var itemDefinition = ItemManager.FindItemDefinition(itemShortName);
var displayName = itemDefinition.displayName.translated;
if (_configs.UseLangAPI && LangAPI != null && (bool)LangAPI.Call("IsDefaultDisplayName", displayName))
{
var displayNameTranslated = LangAPI.Call<string>("GetItemDisplayName", itemShortName, displayName, player.UserIDString);
if (!string.IsNullOrEmpty(displayNameTranslated))
return displayNameTranslated;
}
return displayName;
}
[ChatCommand(CommandOpenUi)]
private void OpenWeaponConfigUI(BasePlayer player, string command, string[] args)
{
int page = playerPages.ContainsKey(player.userID) ? playerPages[player.userID] : 0;
ShowWeaponConfigUI(player, page);
}
[ConsoleCommand(CommandChangePage)]
private void OnWeaponPageCommand(ConsoleSystem.Arg args)
{
var player = args.Player();
if (player == null)
return;
int page = args.GetInt(0, 0);
ShowWeaponConfigUI(player, page);
}
[ConsoleCommand(CommandToggleFastReload)]
private void ToggleFastReload(ConsoleSystem.Arg args)
{
var player = args.Player();
if (player == null)
return;
var shortname = args.GetString(0);
var weaponConfig = _configs.WeaponConfigurations.FirstOrDefault(x => x.Shortname == shortname);
if (weaponConfig != null)
{
weaponConfig.FastReload = !weaponConfig.FastReload;
SaveConfig();
int page = playerPages.ContainsKey(player.userID) ? playerPages[player.userID] : 0;
ShowWeaponConfigUI(player, page);
}
}
[ConsoleCommand(CommandSetCapacity)]
private void SetCapacity(ConsoleSystem.Arg args)
{
var player = args.Player();
if (player == null)
return;
var shortname = args.GetString(0);
var value = args.GetInt(1, -1);
var weaponConfig = _configs.WeaponConfigurations.FirstOrDefault(x => x.Shortname == shortname);
if (weaponConfig != null && value >= 1)
{
weaponConfig.MagazineCapacity = value;
SaveConfig();
int page = playerPages.ContainsKey(player.userID) ? playerPages[player.userID] : 0;
ShowWeaponConfigUI(player, page);
}
}
[ConsoleCommand(CommandCloseUi)]
private void CloseWeaponConfigUI(ConsoleSystem.Arg args)
{
var player = args.Player();
if (player == null)
return;
CuiHelper.DestroyUi(player, PanelName);
}
#endregion
#region Helper Methods
private bool HasPermission(BasePlayer player, string permissionName)
{
return permission.UserHasPermission(player.UserIDString, permissionName);
}
private bool PrepareAmmoForReload(BasePlayer player, BaseProjectile weapon, out ItemDefinition ammoType, out int ammoToLoad)
{
ammoType = GetAmmoType(player, weapon, out var availableAmmo);
if (ammoType == null || availableAmmo <= 0)
{
NotifyPlayer(player, "NoAmmo", 1);
ammoToLoad = 0;
return false;
}
var weaponConfig = GetWeaponConfig(weapon);
int capacityToUse = CalculateCapacity(weapon, weaponConfig);
ammoToLoad = Math.Min(capacityToUse - weapon.primaryMagazine.contents, availableAmmo);
return true;
}
private ItemDefinition GetAmmoType(BasePlayer player, BaseProjectile weapon, out int availableAmmo)
{
availableAmmo = CountPlayerAmmo(player, weapon.primaryMagazine.ammoType);
return availableAmmo > 0 ? weapon.primaryMagazine.ammoType : FindAlternativeAmmoType(player, weapon, out availableAmmo);
}
private ItemDefinition FindAlternativeAmmoType(BasePlayer player, BaseProjectile weapon, out int availableAmmo)
{
availableAmmo = 0;
foreach (var itemDef in GetAmmoDefinitions())
{
if (IsAmmoCompatible(weapon, itemDef) && TryGetAvailableAmmo(player, itemDef, out availableAmmo))
{
weapon.primaryMagazine.ammoType = itemDef;
return itemDef;
}
}
return null;
}
private bool IsAmmoCompatible(BaseProjectile weapon, ItemDefinition ammoDef)
{
var ammoFlags = ammoDef.GetComponent<ItemModProjectile>()?.ammoType ?? 0;
return (weapon.primaryMagazine.definition.ammoTypes & ammoFlags) != 0;
}
private bool TryGetAvailableAmmo(BasePlayer player, ItemDefinition ammoType, out int availableAmount)
{
availableAmount = CountPlayerAmmo(player, ammoType);
return availableAmount > 0;
}
private int CountPlayerAmmo(BasePlayer player, ItemDefinition ammoType)
{
var allItems = Pool.GetList<Item>();
player.inventory.GetAllItems(allItems);
int count = allItems.Where(item => item.info == ammoType).Sum(item => item.amount);
Pool.FreeList(ref allItems);
return count;
}
private void ConsumeAmmo(BasePlayer player, ItemDefinition ammoType, int amount)
{
var allItems = Pool.GetList<Item>();
player.inventory.GetAllItems(allItems);
foreach (var item in allItems.Where(item => item.info == ammoType && amount > 0))
{
int toTake = Math.Min(amount, item.amount);
item.UseItem(toTake);
amount -= toTake;
}
Pool.FreeList(ref allItems);
}
private void UpdateCapacityOnItemChange(BasePlayer player, Item newItem)
{
if (!HasPermission(player, UseFastReloadPermission) || !(newItem?.GetHeldEntity() is BaseProjectile weapon))
return;
var weaponConfig = GetWeaponConfig(weapon);
if (weaponConfig == null)
return;
int capacityToUse = CalculateCapacity(weapon, weaponConfig);
if (capacityToUse != weapon.primaryMagazine.capacity)
{
AdjustMagazineCapacity(weapon, capacityToUse);
NotifyPlayer(player, "NewCapacity", 1, weapon.GetItem()?.info?.shortname, capacityToUse);
}
}
private WeaponConfiguration GetWeaponConfig(BaseProjectile weapon)
{
return _configs.WeaponConfigurations.FirstOrDefault(config => config.Shortname == weapon.GetItem()?.info?.shortname);
}
private int CalculateCapacity(BaseProjectile weapon, WeaponConfiguration config)
{
return config.MagazineCapacity > 0 ? config.MagazineCapacity : weapon.primaryMagazine.definition.builtInSize;
}
private void ExecuteReload(BasePlayer player, BaseProjectile weapon, int ammoAmount, ItemDefinition ammoType)
{
if (ammoAmount <= 0)
return;
RefillMagazine(weapon, ammoAmount);
ConsumeAmmo(player, ammoType, ammoAmount);
RefreshPlayerWeapon(player, weapon);
}
private void RefillMagazine(BaseProjectile weapon, int ammoAmount)
{
weapon.primaryMagazine.contents += ammoAmount;
weapon.SendNetworkUpdateImmediate();
}
private void AdjustMagazineCapacity(BaseProjectile weapon, int capacity)
{
weapon.primaryMagazine.capacity = capacity;
weapon.SendNetworkUpdateImmediate();
}
private void RefreshPlayerWeapon(BasePlayer player, BaseProjectile weapon)
{
player.SetPlayerFlag(BasePlayer.PlayerFlags.SafeZone, true);
player.SendNetworkUpdateImmediate();
player.SetPlayerFlag(BasePlayer.PlayerFlags.SafeZone, false);
player.SendNetworkUpdateImmediate();
player.UpdateActiveItem(default);
player.UpdateActiveItem(weapon.GetItem().uid);
player.SendNetworkUpdateImmediate();
}
private IEnumerable<ItemDefinition> GetWeaponDefinitions()
{
var excludedWeapons = new HashSet<string> { "bow.hunting", "bow.compound", "crossbow", "bow", "legacy bow" };
var weaponDefs = Pool.GetList<ItemDefinition>();
weaponDefs.AddRange(ItemManager.GetItemDefinitions().Where(def => def.category == ItemCategory.Weapon && IsFirearm(def) && !excludedWeapons.Contains(def.shortname)));
var poolResult = weaponDefs.OrderBy(def => def.shortname).ToList();
Pool.FreeList(ref weaponDefs);
return poolResult;
}
private IEnumerable<ItemDefinition> GetAmmoDefinitions()
{
var ammoDefs = Pool.GetList<ItemDefinition>();
ammoDefs.AddRange(ItemManager.GetItemDefinitions().Where(def => def.category == ItemCategory.Ammunition));
var poolList = ammoDefs.ToList();
Pool.FreeList(ref ammoDefs);
return poolList;
}
private WeaponConfiguration CreateWeaponConfig(ItemDefinition itemDef)
{
var projectileComponent = itemDef.GetComponent<ItemModEntity>()?.entityPrefab.Get()?.GetComponent<BaseProjectile>();
int defaultCapacity = projectileComponent?.primaryMagazine.definition.builtInSize ?? 0;
return new WeaponConfiguration
{
Shortname = itemDef.shortname,
MagazineCapacity = defaultCapacity,
FastReload = true,
};
}
private void RefreshWeaponConfigs()
{
var knownShortnames = new HashSet<string>(_configs.WeaponConfigurations.Select(config => config.Shortname));
foreach (var itemDef in GetWeaponDefinitions())
{
if (!knownShortnames.Contains(itemDef.shortname))
{
_configs.WeaponConfigurations.Add(CreateWeaponConfig(itemDef));
PrintWarning($"Added new firearm {itemDef.shortname} to configuration.");
}
}
_configs.WeaponConfigurations = _configs.WeaponConfigurations.OrderBy(config => config.Shortname).ToList();
}
private bool IsFirearm(ItemDefinition itemDef)
{
return itemDef.GetComponent<ItemModEntity>()?.entityPrefab.Get()?.GetComponent<BaseProjectile>() != null;
}
#endregion
#region Localization
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "You do not have permission to use this command.",
["NoAmmo"] = "No compatible ammo available for reloading.",
["NewCapacity"] = "Your {0} now has a magazine capacity of {1}.",
},
this
);
}
private string Msg(string userId, string key, params object[] obj)
{
return string.Format(lang.GetMessage(key, this, userId), obj);
}
private void NotifyPlayer(BasePlayer player, string key, int type, params object[] obj)
{
var userIdString = player.UserIDString;
if (_configs.UseNotify && Notify != null)
Interface.Oxide.CallHook("SendNotify", userIdString, type, Msg(userIdString, key, obj));
else
player.ChatMessage(Msg(userIdString, key, obj));
}
#endregion
#region Configuration
private class Configuration
{
[JsonProperty("Use Notify Plugin")]
public bool UseNotify { get; set; }
[JsonProperty("Use LangAPI Plugin")]
public bool UseLangAPI { get; set; }
[JsonProperty("Weapon Configurations")]
public List<WeaponConfiguration> WeaponConfigurations { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
private class WeaponConfiguration
{
[JsonProperty("Weapon Shortname")]
public string Shortname { get; set; }
[JsonProperty("Magazine Capacity")]
public int MagazineCapacity { get; set; }
[JsonProperty("Fast Reload")]
public bool FastReload { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_configs = Config.ReadObject<Configuration>() ?? GenerateDefaultConfig();
RefreshWeaponConfigs();
SaveConfig();
}
catch
{
PrintError("Configuration error. Reverting to default values.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_configs = GenerateDefaultConfig();
SaveConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_configs);
}
private Configuration GenerateDefaultConfig()
{
return new Configuration
{
UseNotify = true,
UseLangAPI = true,
WeaponConfigurations = GetWeaponDefinitions().Select(CreateWeaponConfig).OrderBy(config => config.Shortname).ToList(),
Version = Version,
};
}
[ChatCommand("turboweapons.reload")]
private void ReloadPluginConfig(BasePlayer player, string command, string[] args)
{
if (!HasPermission(player, ReloadConfigPermission))
{
NotifyPlayer(player, "NoPermission", 1);
return;
}
LoadConfig();
NotifyPlayer(player, "TurboWeapons configuration reloaded.", 1);
}
#endregion
}
}