C#:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using UnityEngine;
namespace Oxide.Plugins {
[Info("IQGradeRemove", "Mercury", "0.0.3")]
[Description("Умный Grade Remove")]
class IQGradeRemove : RustPlugin {
#region Vars
public static string PermissionGRMenu = "iqgraderemove.gruse";
public readonly Dictionary<int, string> StatusLevels = new Dictionary<int, string> {
[0]
= "ОТКЛЮЧЕНО", [1] = "ДЕРЕВА", [2] = "КАМНЯ", [3] = "МЕТАЛЛА", [4] = "МВК", [5] = "УДАЛЕНИЕ", [6] = "УДАЛЕНИЕ ВСЕГО", [7] = "УЛУЧШЕНИЕ ВСЕГО",
}
;
public readonly Dictionary<int, string> StatusLevelsAllGrades = new Dictionary<int, string> {
[0]
= "В СОЛОМУ", [1] = "В ДЕРЕВО", [2] = "В КАМЕНЬ", [3] = "В МЕТАЛЛ", [4] = "В МВК",
}
;
public readonly Dictionary<int, string> SoundLevelsGrade = new Dictionary<int, string> {
[0]
= "ОТКЛЮЧЕНО", [1] = "assets/bundled/prefabs/fx/build/frame_place.prefab", [2] = "assets/bundled/prefabs/fx/build/promote_stone.prefab", [3] = "assets/bundled/prefabs/fx/build/promote_metal.prefab", [4] = "assets/bundled/prefabs/fx/build/promote_toptier.prefab", [5] = "УДАЛЕНИЕ"
}
;
#region Format Time
static DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0);
static double CurrentTime() => DateTime.UtcNow.Subtract(epoch).TotalSeconds;
public static string FormatTime(TimeSpan time) {
string result = string.Empty;
if (time.Days != 0) result += $"{Format(time.Days, "д", "д", "д")} ";
if (time.Hours != 0) result += $"{Format(time.Hours, "ч", "ч", "ч")} ";
if (time.Minutes != 0) result += $"{Format(time.Minutes, "м", "м", "м")} ";
if (time.Seconds != 0) result += $"{Format(time.Seconds, "с", "с", "с")} ";
return result;
}
private static string Format(int units, string form1, string form2, string form3) {
var tmp = units % 10;
if (units >= 5 && units <= 20 || tmp >= 5 && tmp <= 9) return $"{units} {form1}";
if (tmp >= 2 && tmp <= 4) return $"{units} {form2}";
return $"{units} {form3}";
}
#endregion
#endregion
#region Reference
[PluginReference]
Plugin ImageLibrary, NoEscape, Friends;
public string GetImage(string shortname, ulong skin = 0) => (string)ImageLibrary?.Call("GetImage", shortname, skin);
public bool AddImage(string url, string shortname, ulong skin = 0) => (bool)ImageLibrary?.Call("AddImage", url, shortname, skin);
public void SendImage(BasePlayer player, string imageName, ulong imageId = 0) => ImageLibrary?.Call("SendImage", player, imageName, imageId);
public bool HasImage(string imageName) => (bool)ImageLibrary?.Call("HasImage", imageName);
public bool IsRaidBlocked(BasePlayer player) {
if (NoEscape) return (bool)NoEscape?.Call("IsRaidBlock", player.userID);
else return false;
}
bool hasFriend(ulong a, ulong b) {
var friends = Interface.Oxide.DataFileSystem.ReadObject<Dictionary<ulong, FriendData>>("SoFriends/FriendData");
if(!friends.ContainsKey(a)) return false;
if(friends[a].friendList.ContainsKey(b)) return true;
return false;
}
bool IsFriends(ulong playerID = 0, ulong friendId = 0) {
return (hasFriend(playerID, friendId) && hasFriend(friendId, playerID));
}
private class FriendData {
[JsonProperty("Ник")]
public string Name;
[JsonProperty("Список друзей")]
public Dictionary<ulong, FriendAcces> friendList = new Dictionary<ulong, FriendAcces>();
public class FriendAcces {
[JsonProperty("Ник")]
public string name;
[JsonProperty("Урон по человеку")]
public bool Damage;
[JsonProperty("Авторизациия в турелях")]
public bool Turret;
[JsonProperty("Авторизациия в дверях")]
public bool Door;
[JsonProperty("Авторизациия в пво")]
public bool Sam;
}
}
void LoadedImage() {
var Interface = config.InterfaceSetting;
if (!Interface.UseIL) return;
if (!HasImage($"REMOVE_IL")) AddImage(Interface.MainInterfaces.RemovePNG, $"REMOVE_IL");
if (!HasImage($"UPGRADE_IL")) AddImage(Interface.MainInterfaces.GradePNG, "UPGRADE_IL");
if (!HasImage($"ERROR_IL")) AddImage(Interface.ErrorInterfaces.ErrorPNG, "ERROR_IL");
}
void CahedImages(BasePlayer player) {
var Interface = config.InterfaceSetting;
if (!Interface.UseIL) return;
SendImage(player, $"REMOVE_IL");
SendImage(player, $"UPGRADE_IL");
SendImage(player, $"ERROR_IL");
}
void RegisteredPermissions() {
var RemoveTimed = config.RemoveSetting.TimedSetting;
foreach (var PermsBlockTimed in RemoveTimed.ItemsTimesAllPermissions) if (!permission.PermissionExists(PermsBlockTimed.Key, this)) permission.RegisterPermission(PermsBlockTimed.Key, this);
foreach (var PermsBlockTimed in RemoveTimed.ItemsTimesPermissions) if (!permission.PermissionExists(PermsBlockTimed.Key, this)) permission.RegisterPermission(PermsBlockTimed.Key, this);
if (!permission.PermissionExists(PermissionGRMenu, this)) permission.RegisterPermission(PermissionGRMenu, this);
}
#endregion
#region Configuration
private static Configuration config = new Configuration();
private class Configuration {
[JsonProperty("Настройка удаления объектов")]
public RemoveSettings RemoveSetting = new RemoveSettings();
[JsonProperty("Настройка улучшения объектов")]
public GradeSettings GradeSetting = new GradeSettings();
[JsonProperty("Настройка интерфейса")]
public InterfaceSettings InterfaceSetting = new InterfaceSettings();
#region Remove Configuration
internal class RemoveSettings {
[JsonProperty("Настройка возврата предметов после удаления")]
public ReturnedSettings ReturnedSetting = new ReturnedSettings();
[JsonProperty("Настройка удаления через время")]
public TimedSettings TimedSetting = new TimedSettings();
[JsonProperty("Настройка запретов")]
public SettingsBlocks SettingsBlock = new SettingsBlocks();
[JsonProperty("Время действия удаления")]
public int RemoveTime;
internal class ReturnedSettings {
[JsonProperty("Возвращать ресурсы за удаление строений?(true- да/false - нет)")]
public bool UseReturnedResource;
[JsonProperty("Процент возврата ресурсов за удаление строений?(true- да/false - нет)")]
public int PercentReturnRecource;
[JsonProperty("Возвращать все предметы при удалении?(true- да/false - нет)")]
public bool UseAllowedReturned;
[JsonProperty("Снижать состояние предмета при возврате?Эффект будто он поднял его через RUST систему")]
public bool UseDamageReturned;
[JsonProperty("Предметы,которые не возвращаются при удалении(Shortname)")]
public List<string> ShortnameNoteReturned = new List<string>();
}
internal class TimedSettings {
[JsonProperty("Включить полный запрет на удаление объекта через N время(Пример : Через 3 часа после постройки,его нельзя будет удалить вообще)")]
public bool UseAllBlock;
[JsonProperty("Через сколько нельзя будет удалять постройку вообще")]
public int TimeAllBlock;
[JsonProperty("Кастомный список предметов,которые нельзя будет удалить через время по правам.[[IQGradeRemove.NAME]] - Время(в сек)")]
public Dictionary<string, int> ItemsTimesAllPermissions = new Dictionary<string, int>();
[JsonProperty("Использовать запрет на удаление постройки на время(После постройки объекта,его N количество времени нельзя будет удалить)")]
public bool UseTimesBlock;
[JsonProperty("Через сколько можно будет удалять постройку(если включено)")]
public int TimesBlock;
[JsonProperty("Кастомный список предметов,которые можно будет удалить через время по правам.[[IQGradeRemove.NAME]] - Время(в сек)")]
public Dictionary<string, int> ItemsTimesPermissions = new Dictionary<string, int>();
}
internal class SettingsBlocks {
[JsonProperty("[NoEscape] Запретить удаление во время рейдблока(true - да/false - нет)")]
public bool NoEscape;
[JsonProperty("[Friends] Удалять постройки могут только друзья(Иначе все,кто есть в шкафу)(true - да/false - нет)")]
public bool Friends;
[JsonProperty("Предметы,которые нельзя удалить(Shortname)")]
public List<string> ShortnameNoteReturned = new List<string>();
}
}
#endregion
#region Grade Configuration
internal class GradeSettings {
[JsonProperty("Время действия улучшения")]
public int GradeTime;
[JsonProperty("Разрешить обратное улучшение?(Пример : МВК стенку откатить в деревянную)(true - да/false - нет)")]
public bool UseBackUp;
[JsonProperty("Настройка запретов")]
public SettingsBlocks SettingsBlock = new SettingsBlocks();
internal class SettingsBlocks {
[JsonProperty("[NoEscape] Запретить улучшение во время рейдблока(true - да/false - нет)")]
public bool NoEscape;
}
}
#endregion
#region Interface
internal class InterfaceSettings {
[JsonProperty("Настройка интерфейса")]
public MainInterface MainInterfaces = new MainInterface();
[JsonProperty("Настройка интерфейса уведомления")]
public ErrorInterface ErrorInterfaces = new ErrorInterface();
[JsonProperty("AnchorMin")]
public string AnchorMin;
[JsonProperty("AnchorMax")]
public string AnchorMax;
[JsonProperty("OffsetMin")]
public string OffsetMin;
[JsonProperty("OffsetMax")]
public string OffsetMax;
[JsonProperty("Использовать ImageLibrary для отображения фотки(true - да,false - нет(будут использоваться растовские иконки из спрайтов))")]
public bool UseIL;
internal class MainInterface {
[JsonProperty("Цвет панели(HEX)")]
public string ColorPanel;
[JsonProperty("Цвет текста(HEX)")]
public string ColorText;
[JsonProperty("Размер текста")]
public int FontSize;
[JsonProperty("Материал панели")]
public string Material;
[JsonProperty("Ссылка на иконку(PNG) для улучшений(24x24)")]
public string GradePNG;
[JsonProperty("Sprite для PNG улучшений")]
public string GradeSpritePNG;
[JsonProperty("Ссылка на иконку(PNG) для удаления(24x24)")]
public string RemovePNG;
[JsonProperty("Sprite для PNG удаления")]
public string RemoveSpritePNG;
}
internal class ErrorInterface {
[JsonProperty("Цвет панели(HEX)")]
public string ColorPanel;
[JsonProperty("Цвет текста(HEX)")]
public string ColorText;
[JsonProperty("Размер текста")]
public int FontSize;
[JsonProperty("Материал панели")]
public string Material;
[JsonProperty("Ссылка на иконку(PNG) для ошибки(24x24)")]
public string ErrorPNG;
[JsonProperty("Sprite для PNG для ошибки")]
public string ErrorSpritePNG;
}
}
#endregion
public static Configuration GetNewConfiguration() {
return new Configuration {
#region Remove Configuration
RemoveSetting = new RemoveSettings {
RemoveTime = 30, ReturnedSetting = new RemoveSettings.ReturnedSettings {
UseReturnedResource = true, PercentReturnRecource = 50, UseDamageReturned = true, UseAllowedReturned = true, ShortnameNoteReturned = new List<string> {
"campfire",
}
}
, TimedSetting = new RemoveSettings.TimedSettings {
UseAllBlock = false, TimeAllBlock = 60, ItemsTimesAllPermissions = new Dictionary<string, int> {
["iqgraderemove.vip"]
= 200, ["iqgraderemove.prem"] = 250, ["iqgraderemove.gold"] = 300,
}
, UseTimesBlock = false, TimesBlock = 100, ItemsTimesPermissions = new Dictionary<string, int> {
["iqgraderemove.vip"]
= 150, ["iqgraderemove.prem"] = 200, ["iqgraderemove.gold"] = 300,
}
,
}
, SettingsBlock = new RemoveSettings.SettingsBlocks {
Friends = true, NoEscape = true, ShortnameNoteReturned = new List<string> {
"campfire",
}
}
}
,
#endregion
#region Grade Configuration
GradeSetting = new GradeSettings {
GradeTime = 30, UseBackUp = false, SettingsBlock = new GradeSettings.SettingsBlocks {
NoEscape = true,
}
}
,
#endregion
#region Interface
InterfaceSetting = new InterfaceSettings {
UseIL = false, AnchorMin = "0 0", AnchorMax = "0 0", OffsetMin = "10 5", OffsetMax = "300 30", MainInterfaces = new InterfaceSettings.MainInterface {
ColorPanel = "#3A3834FF", ColorText = "#C9C0B9FF", FontSize = 13, Material = "assets/content/ui/uibackgroundblur.mat", GradePNG = "https://i.imgur.com/I2pqY34.png", RemovePNG = "https://i.imgur.com/cA1KOzd.png", GradeSpritePNG = "assets/icons/upgrade.png", RemoveSpritePNG = "assets/icons/level_stone.png",
}
, ErrorInterfaces = new InterfaceSettings.ErrorInterface {
ColorPanel = "#783B2FFF", ColorText = "#FF4B2EFF", FontSize = 13, Material = "assets/content/ui/uibackgroundblur.mat", ErrorPNG = "https://i.imgur.com/DaObrS0.png", ErrorSpritePNG = "assets/icons/close.png",
}
}
,
#endregion
}
;
}
}
protected override void LoadConfig() {
base.LoadConfig();
try {
config = Config.ReadObject<Configuration>();
if (config == null) LoadDefaultConfig();
}
catch {
PrintWarning("Ошибка #132" + $"чтения конфигурации 'oxide/config/{Name}', создаём новую конфигурацию!!");
LoadDefaultConfig();
}
NextTick(SaveConfig);
}
protected override void LoadDefaultConfig() => config = Configuration.GetNewConfiguration();
protected override void SaveConfig() => Config.WriteObject(config);
#endregion
#region Data
public Dictionary<ulong, GradeRemove> DataPlayer = new Dictionary<ulong, GradeRemove>();
public Dictionary<uint, int> BuildingRemoveTimers = new Dictionary<uint, int>();
public Dictionary<uint, int> BuildingRemoveBlock = new Dictionary<uint, int>();
void ReadData() {
BuildingRemoveTimers = Oxide.Core.Interface.Oxide.DataFileSystem.ReadObject<Dictionary<uint, int>>("IQGradeRemove/BlockBuilding");
BuildingRemoveBlock = Oxide.Core.Interface.Oxide.DataFileSystem.ReadObject<Dictionary<uint, int>>("IQGradeRemove/BuildingRemoveBlock");
}
void WriteData() {
Oxide.Core.Interface.Oxide.DataFileSystem.WriteObject("IQGradeRemove/BlockBuilding", BuildingRemoveTimers);
Oxide.Core.Interface.Oxide.DataFileSystem.WriteObject("IQGradeRemove/BuildingRemoveBlock", BuildingRemoveBlock);
}
///0 - солома
///1 - дерево
///2 - камень
///3 - металл
///4 - мвк
public class GradeRemove {
public int ActiveTime;
public int GradeLevel;
public int GradeAdmin;
public Timer TimerEvent = null;
public void GradeUP(bool UseMyGrade = false, int CustomGrade = 0) {
if (!UseMyGrade) {
if (GradeLevel > 4) GradeLevel = 0;
else GradeLevel++;
}
else GradeLevel = CustomGrade;
RebootTimer();
int TimeActive = CustomGrade != 0 & CustomGrade != 5 ? config.GradeSetting.GradeTime : config.RemoveSetting.RemoveTime;
ActiveTime = Convert.ToInt32(TimeActive + CurrentTime());
}
public void RebootTimer() {
if (TimerEvent != null) TimerEvent.Destroy();
}
}
void RegisteredUser(BasePlayer player) {
if (!DataPlayer.ContainsKey(player.userID)) DataPlayer.Add(player.userID, new GradeRemove {
ActiveTime = 0, GradeLevel = 0
}
);
}
#endregion
#region Grade Core
public string GradeErrorParse(BasePlayer player, BuildingBlock buildingBlock) {
var Data = DataPlayer[player.userID];
var Block = config.GradeSetting.SettingsBlock;
if (Block.NoEscape) if (NoEscape) if (IsRaidBlocked(player)) return lang.GetMessage("GRADE_NO_ESCAPE", this, player.UserIDString);
if (buildingBlock.SecondsSinceAttacked < 30) return String.Format(lang.GetMessage("GRADE_ATTACKED_BLOCK", this, player.UserIDString), FormatTime(TimeSpan.FromSeconds(30 - (int)buildingBlock.SecondsSinceAttacked)));
if (!player.CanBuild()) return lang.GetMessage("GRADE_NO_AUTH", this, player.UserIDString);
List<ItemAmount> itemAmounts = buildingBlock.blockDefinition.grades[Data.GradeLevel].costToBuild;
foreach (var Item in itemAmounts) if (player.inventory.GetAmount(Item.itemid) < Item.amount) return lang.GetMessage("GRADE_NO_RESOURCE", this, player.UserIDString);
return "";
}
public void GradeBuilding(BasePlayer player, BuildingBlock buildingBlock) {
var Data = DataPlayer[player.userID];
if (GradeErrorParse(player, buildingBlock) != "") {
Interface_UI_Error(player, GradeErrorParse(player, buildingBlock));
return;
}
if (!config.GradeSetting.UseBackUp) if (buildingBlock.grade > (BuildingGrade.Enum)Data.GradeLevel) return;
List<ItemAmount> itemAmounts = buildingBlock.blockDefinition.grades[Data.GradeLevel].costToBuild;
foreach (var check in itemAmounts) {
player.inventory.Take(null, check.itemid, (int)check.amount);
player.Command("note.inv", check.itemid, check.amount * -1f);
}
buildingBlock.SetGrade((BuildingGrade.Enum)Data.GradeLevel);
buildingBlock.UpdateSkin();
buildingBlock.SetHealthToMax();
buildingBlock.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
Effect.server.Run(SoundLevelsGrade[Data.GradeLevel], player.GetNetworkPosition());
DataPlayer[player.userID].ActiveTime = (int)(config.GradeSetting.GradeTime + CurrentTime());
}
/* public void GradeAll(BasePlayer player, BuildingBlock buildingBlock, bool IsAdmin = true)
{
if (buildingBlock.GetBuildingPrivilege() == null)
{
Interface_UI_Error(player, lang.GetMessage("GRADE_ALL_NO_AUTH", this, player.UserIDString));
return;
}
ListHashSet<BuildingBlock> Blocks = new ListHashSet<BuildingBlock>();
foreach (var Block in buildingBlock.GetBuildingPrivilege().GetBuilding().buildingBlocks.Where(x => x.grade != (BuildingGrade.Enum)DataPlayer[player.userID].GradeAdmin))
if (!Blocks.Contains(Block))
{
if (!IsAdmin)
{
List<ItemAmount> itemAmounts = buildingBlock.blockDefinition.grades[DataPlayer[player.userID].GradeAdmin].costToBuild;
foreach (var Item in itemAmounts)
if (player.inventory.GetAmount(Item.itemid) < Item.amount)
continue;
else
{
player.inventory.Take(null, Item.itemid, (int)Item.amount);
Blocks.Add(Block);
}
}
else Blocks.Add(Block);
}
NextTick(() =>
{
foreach (var Block in Blocks)
{
Block.SetGrade((BuildingGrade.Enum)DataPlayer[player.userID].GradeAdmin);
Block.UpdateSkin();
Block.SetHealthToMax();
Block.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
}
});
}*/
#endregion
#region Remove Core
#region Permanent Block
private void AddRemoveBlockBuild(uint netID, ulong userID) {
var RemoveTime = config.RemoveSetting.TimedSetting;
if (!RemoveTime.UseTimesBlock) return;
if (IsBlockAvailablePermanent(netID)) return;
int Time = GetTimeBlockPermanent(userID);
BuildingRemoveBlock.Add(netID, Time);
}
private bool IsBlockAvailablePermanent(uint netID) {
if (BuildingRemoveBlock.ContainsKey(netID)) return true;
else return false;
}
private bool IsBlockBuildPemanent(uint netID) {
if (IsBlockAvailablePermanent(netID)) if (BuildingRemoveBlock[netID] <= CurrentTime()) return true;
else return false;
else return false;
}
private int GetTimeBlockPermanent(ulong userID = 0) {
var RemoveTime = config.RemoveSetting.TimedSetting;
int Time = Convert.ToInt32(CurrentTime() + RemoveTime.TimeAllBlock);
if (!userID.IsSteamId()) return Time;
foreach (var Perms in RemoveTime.ItemsTimesAllPermissions) if (permission.UserHasPermission(userID.ToString(), Perms.Key)) {
Time = Convert.ToInt32(CurrentTime() + Perms.Value);
return Time;
}
return Time;
}
#endregion
#region Temporally Block
private void AddBlockBuild(uint netID, ulong userID) {
var RemoveTime = config.RemoveSetting.TimedSetting;
if (!RemoveTime.UseTimesBlock) return;
if (IsBlockAvailable(netID)) return;
int Time = GetTimeBlock(userID);
BuildingRemoveTimers.Add(netID, Time);
}
private bool IsBlockAvailable(uint netID) {
if (BuildingRemoveTimers.ContainsKey(netID)) return true;
else return false;
}
private bool IsBlockBuild(uint netID) {
if (IsBlockAvailable(netID)) if (BuildingRemoveTimers[netID] > CurrentTime()) return true;
else return false;
else return false;
}
private int GetTimeBlock(ulong userID = 0) {
var RemoveTime = config.RemoveSetting.TimedSetting;
int Time = Convert.ToInt32(CurrentTime() + RemoveTime.TimesBlock);
if (!userID.IsSteamId()) return Time;
foreach (var Perms in RemoveTime.ItemsTimesPermissions) if (permission.UserHasPermission(userID.ToString(), Perms.Key)) {
Time = Convert.ToInt32(CurrentTime() + Perms.Value);
return Time;
}
return Time;
}
private int GetTimerBlock(uint netID) {
int Time = 0;
if (IsBlockAvailable(netID)) Time = Convert.ToInt32(BuildingRemoveTimers[netID] - CurrentTime());
return Time;
}
#endregion
void ReturnedRemoveItems(BasePlayer player, BaseEntity buildingBlock) {
var Remove = config.RemoveSetting.ReturnedSetting;
if (buildingBlock is StabilityEntity) {
if (Remove.UseReturnedResource) {
float PercentResource = (float)((float)(Remove.PercentReturnRecource) / (float)(100));
foreach (var CostReturned in (buildingBlock as StabilityEntity).BuildCost()) player.GiveItem(ItemManager.Create(CostReturned.itemDef, Mathf.FloorToInt((float)CostReturned.amount * PercentResource)));
}
return;
}
if (Remove.UseAllowedReturned) {
Item ItemReturned = ItemManager.Create(buildingBlock.GetComponent<BaseCombatEntity>().pickup.itemTarget, 1);
if (ItemReturned == null) return;
if (Remove.UseDamageReturned) {
float healthFraction = buildingBlock.GetComponent<BaseCombatEntity>().Health() / buildingBlock.GetComponent<BaseCombatEntity>().MaxHealth();
ItemReturned.conditionNormalized = Mathf.Clamp01(healthFraction - buildingBlock.GetComponent<BaseCombatEntity>().pickup.subtractCondition);
}
player.GiveItem(ItemReturned);
return;
}
}
/*public void RemoveAll(BasePlayer player, BaseEntity buildingBlock)
{
if (player.GetBuildingPrivilege() == null)
{
Interface_UI_Error(player, lang.GetMessage("REMOVE_ALL_NO_AUTH", this, player.UserIDString));
return;
}
ListHashSet<BuildingPrivlidge> BlocksRemoveAll = new ListHashSet<BuildingPrivlidge>();
foreach (var Block in player.buildingPrivilege)
if (!BlocksRemoveAll.Contains(Block))
BlocksRemoveAll.Add(Block);
NextTick(() =>
{
foreach (var Block in BlocksRemoveAll)
Block.Kill();
});
}*/
public string RemoveErrorParseBuilding(BasePlayer player, BaseEntity buildingBlock) {
var Data = DataPlayer[player.userID];
var Remove = config.RemoveSetting;
var Block = Remove.SettingsBlock;
var RemoveTimed = Remove.TimedSetting;
if (Block.NoEscape) if (IsRaidBlocked(player)) return lang.GetMessage("REMOVE_NO_ESCAPE", this, player.UserIDString);
BuildingBlock buildingBlocks = buildingBlock.GetComponent<BuildingBlock>();
if (buildingBlocks != null) {
if (buildingBlocks.SecondsSinceAttacked < 30) return String.Format(lang.GetMessage("REMOVE_ATTACKED_BLOCK", this, player.UserIDString), FormatTime(TimeSpan.FromSeconds(30 - (int)buildingBlocks.SecondsSinceAttacked)));
}
if (Block.Friends) {
if (player.userID != buildingBlock.OwnerID) if (!IsFriends(player.userID, buildingBlock.OwnerID)) return lang.GetMessage("REMOVE_ONLY_FRIENDS", this, player.UserIDString);
}
else if (!player.CanBuild()) return lang.GetMessage("REMOVE_NO_AUTH", this, player.UserIDString);
if (RemoveTimed.UseTimesBlock) if (IsBlockBuild(buildingBlock.net.ID)) return String.Format(lang.GetMessage("REMOVE_TIME_EXECUTE", this, player.UserIDString), FormatTime(TimeSpan.FromSeconds(GetTimerBlock(buildingBlock.net.ID))));
if (RemoveTimed.UseAllBlock) if (IsBlockBuildPemanent(buildingBlock.net.ID)) return String.Format(lang.GetMessage("REMOVE_TIME_EXECUTE_UNREMOVE", this, player.UserIDString));
if (Block.ShortnameNoteReturned.Contains(buildingBlock.ShortPrefabName)) return lang.GetMessage("REMOVE_UNREMOVE", this, player.UserIDString);
return "";
}
public void RemoveBuilding(BasePlayer player, BaseEntity buildingBlock) {
if (RemoveErrorParseBuilding(player, buildingBlock) != "") {
Interface_UI_Error(player, RemoveErrorParseBuilding(player, buildingBlock));
return;
}
ReturnedRemoveItems(player, buildingBlock);
NextTick(() => {
{
StorageContainer container = buildingBlock.GetComponent<StorageContainer>();
if (container != null) {
container.DropItems();
}
buildingBlock.Kill();
}
}
);
DataPlayer[player.userID].ActiveTime = (int)(config.RemoveSetting.RemoveTime + CurrentTime());
}
#endregion
#region Commands
[ChatCommand("up")]
void UPCommand(BasePlayer player, string cmd, string[] arg) {
var Data = DataPlayer[player.userID];
switch (arg.Length) {
case 0 : {
Data.GradeUP();
break;
}
case 1 : {
int GradeLevel;
if (!int.TryParse(arg[0], out GradeLevel) || GradeLevel < 0 || GradeLevel > 4) {
CuiHelper.DestroyUi(player, UI_STATUS_PARENT);
return;
}
Data.GradeUP(true, GradeLevel);
break;
}
}
Interface_UI_Status(player);
}
[ChatCommand("remove")]
void RemoveCommand(BasePlayer player, string cmd, string[] arg) {
var Data = DataPlayer[player.userID];
if (Data.GradeLevel == 5) Data.GradeUP(true, 0);
else Data.GradeUP(true, 5);
Interface_UI_Status(player);
}
public List<ulong> IsOpenAdmin = new List<ulong>();
public void OpenMenuAdmin(BasePlayer player) {
if (!IsOpenAdmin.Contains(player.userID)) {
Interface_UI_Admin_Status(player);
IsOpenAdmin.Add(player.userID);
}
else {
CuiHelper.DestroyUi(player, UI_ADMIN_MENU_PARENT);
CuiHelper.DestroyUi(player, UI_STATUS_PARENT);
IsOpenAdmin.Remove(player.userID);
}
}
/*[ChatCommand("gr")]
void AdminMenu(BasePlayer player)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionGRMenu)) return;
OpenMenuAdmin(player);
}*/
[ConsoleCommand("gr_func")]
void ConsoleCommandAdminMenu(ConsoleSystem.Arg arg) {
BasePlayer player = arg.Player();
if (player == null) return;
var Data = DataPlayer[player.userID];
switch (arg.Args[0].ToLower()) {
case "removeall" : {
Data.GradeLevel = 6;
Interface_UI_Admin_Status(player);
break;
}
case "gradeall" : {
Data.GradeLevel = 7;
Interface_UI_Admin_Status(player);
break;
}
case "setgradeall" : {
int Grade = Convert.ToInt32(arg.Args[1]);
Data.GradeAdmin = Grade;
Interface_UI_Admin_Status(player);
break;
}
}
}
#endregion
#region Hooks
void OnHammerHit(BasePlayer player, HitInfo info) {
if (info == null) return;
if (player == null) return;
var Data = DataPlayer[player.userID];
if (Data.GradeLevel == 7) {
if (!permission.UserHasPermission(player.UserIDString, PermissionGRMenu)) return;
BuildingBlock buildingBlock = info.HitEntity as BuildingBlock;
if (buildingBlock == null) return;
bool IsAdmin = permission.UserHasPermission(player.UserIDString, PermissionGRMenu) ? false : true;
//GradeAll(player, buildingBlock, IsAdmin);
return;
}
if (Data.GradeLevel == 6) {
if (!permission.UserHasPermission(player.UserIDString, PermissionGRMenu)) return;
BuildingBlock buildingBlock = info.HitEntity as BuildingBlock;
if (buildingBlock == null) return;
//RemoveAll(player, buildingBlock);
return;
}
if (Data.GradeLevel == 5) if (info.HitEntity is BaseEntity) RemoveBuilding(player, info.HitEntity);
if (Data.GradeLevel != 0 && Data.GradeLevel != 5) {
BuildingBlock buildingBlock = info.HitEntity as BuildingBlock;
if (buildingBlock == null) return;
if (buildingBlock.grade == (BuildingGrade.Enum)Data.GradeLevel) return;
if (buildingBlock.PrefabName == "assets/prefabs/building core/foundation/foundation.prefab" || buildingBlock.PrefabName == "assets/prefabs/building core/foundation.triangle/foundation.triangle.prefab") {
var layers = LayerMask.GetMask("Default", "Player (Server)", "Deployed");
Vector3 positionEntity = buildingBlock.transform.position;
Vector3 PositionCollider = new Vector3(positionEntity.x, positionEntity.y - 2f, positionEntity.z);
bool CheckCollider = Physics.CheckSphere(PositionCollider, 2f, layers);
if (CheckCollider) {
Interface_UI_Error(player, lang.GetMessage("GRADE_NO_THIS_USER", this, player.UserIDString));
return;
}
}
GradeBuilding(player, buildingBlock);
}
}
private void OnEntityBuilt(Planner plan, GameObject go) {
BasePlayer player = plan?.GetOwnerPlayer();
if (player == null) return;
if (go == null) return;
if (go.ToBaseEntity() is BuildingBlock || go.ToBaseEntity() is BaseEntity) {
AddRemoveBlockBuild(go.ToBaseEntity().net.ID, player.userID);
AddBlockBuild(go.ToBaseEntity().net.ID, player.userID);
}
BuildingBlock buildingBlock = go.ToBaseEntity().GetComponent<BuildingBlock>();
if (buildingBlock == null) return;
var Data = DataPlayer[player.userID];
if (Data == null) return;
if (Data.GradeLevel == 6 || Data.GradeLevel == 7) return;
if (Data.GradeLevel != 0 && Data.GradeLevel != 5) GradeBuilding(player, buildingBlock);
}
#region Server Hooks
private void OnServerInitialized() {
ReadData();
LoadedImage();
foreach (var p in BasePlayer.activePlayerList) OnPlayerInit(p);
timer.Every(120f, () => {
WriteData();
}
);
RegisteredPermissions();
}
void OnPlayerInit(BasePlayer player) {
if (player.IsReceivingSnapshot) {
NextTick(() => OnPlayerInit(player));
return;
}
CahedImages(player);
RegisteredUser(player);
}
void Unload() {
foreach (var player in BasePlayer.activePlayerList) {
CuiHelper.DestroyUi(player, UI_STATUS_PARENT);
CuiHelper.DestroyUi(player, UI_ADMIN_MENU_PARENT);
CuiHelper.DestroyUi(player, UI_ERROR_ALERT_PARENT);
}
}
void OnNewSave(string filename) {
BuildingRemoveTimers.Clear();
BuildingRemoveBlock.Clear();
WriteData();
}
#endregion
#endregion
#region UI
public static string UI_STATUS_PARENT = "UI_STATUS_PARENT";
public static string UI_ADMIN_MENU_PARENT = "UI_ADMIN_MENU_PARENT";
public static string UI_ERROR_ALERT_PARENT = "UI_ERROR_ALERT_PARENT";
void Interface_UI_Admin_Status(BasePlayer player) {
CuiElementContainer container = new CuiElementContainer();
CuiHelper.DestroyUi(player, UI_ADMIN_MENU_PARENT);
CuiHelper.DestroyUi(player, UI_STATUS_PARENT);
var Interface = config.InterfaceSetting;
var MainInterface = Interface.MainInterfaces;
var Data = DataPlayer[player.userID];
Data.RebootTimer();
container.Add(new CuiPanel {
FadeOut = 0.15f, RectTransform = {
AnchorMin = Interface.AnchorMin, AnchorMax = Interface.AnchorMax, OffsetMin = Interface.OffsetMin, OffsetMax = Interface.OffsetMax
}
, Image = {
FadeIn = 0.15f, Color = HexToRustFormat(MainInterface.ColorPanel), Material = MainInterface.Material
}
}
, "Overlay", UI_ADMIN_MENU_PARENT);
container.Add(new CuiElement {
FadeOut = 0.15f, Parent = UI_ADMIN_MENU_PARENT, Components = {
new CuiImageComponent {
FadeIn = 0.15f, Sprite = "assets/icons/tools.png", Color = HexToRustFormat(MainInterface.ColorText)
}
, new CuiRectTransformComponent {
AnchorMin = "0.01149425 0.1866667", AnchorMax = "0.06666666 0.8266667"
}
,
}
}
);
string Text = Data.GradeLevel == 6 ? lang.GetMessage("REMOVE_ALL", this, player.UserIDString) : Data.GradeLevel == 7 ? String.Format(lang.GetMessage("GRADE_ALL", this, player.UserIDString), StatusLevelsAllGrades[Data.GradeAdmin]) : lang.GetMessage("TITLE_GR_ADMIN", this, player.UserIDString);
container.Add(new CuiLabel {
FadeOut = 0.15f, RectTransform = {
AnchorMin = "0.08275801 0", AnchorMax = "1 1"
}
, Text = {
FadeIn = 0.15f, Text = Text, FontSize = MainInterface.FontSize, Color = HexToRustFormat(MainInterface.ColorText), Font = "robotocondensed-regular.ttf", Align = TextAnchor.MiddleLeft
}
}
, UI_ADMIN_MENU_PARENT);
#region Actions
container.Add(new CuiPanel {
FadeOut = 0.15f, RectTransform = {
AnchorMin = "0 1", AnchorMax = "0 1", OffsetMin = "0 1", OffsetMax = "290 25"
}
, Image = {
FadeIn = 0.15f, Color = "0 0 0 0"
}
}
, UI_ADMIN_MENU_PARENT, "ACTION_PANEL");
container.Add(new CuiButton {
RectTransform = {
AnchorMin = "0 0", AnchorMax = "0.49 1"
}
, Button = {
Command = "gr_func gradeall", Color = HexToRustFormat(MainInterface.ColorPanel), Material = MainInterface.Material
}
, Text = {
Text = lang.GetMessage("GR_UP_ALL_USE", this, player.UserIDString), Color = HexToRustFormat(MainInterface.ColorText), Align = TextAnchor.MiddleCenter
}
}
, "ACTION_PANEL", "GRADE_ALL");
container.Add(new CuiButton {
RectTransform = {
AnchorMin = "0.51 0", AnchorMax = "1 1"
}
, Button = {
Command = "gr_func removeall", Color = HexToRustFormat(MainInterface.ColorPanel)
}
, Text = {
Text = lang.GetMessage("GR_REMOVE_ALL_USE", this, player.UserIDString), Color = HexToRustFormat(MainInterface.ColorText), Align = TextAnchor.MiddleCenter
}
}
, "ACTION_PANEL", "REMOVE_ALL");
#endregion
if (Data.GradeLevel == 7) {
container.Add(new CuiPanel {
FadeOut = 0.15f, RectTransform = {
AnchorMin = "0 1", AnchorMax = "0 1", OffsetMin = "0 2", OffsetMax = "142 25"
}
, Image = {
FadeIn = 0.15f, Color = "0 0 0 0", Material = MainInterface.Material
}
}
, "ACTION_PANEL", "GRADE_LEVELS");
for (int grade = 0; grade < 5; grade++) {
container.Add(new CuiButton {
RectTransform = {
AnchorMin = $"{0 + (0.205 * grade)} 0", AnchorMax = $"{0.1829255 + (0.205 * grade)} 1"
}
, Button = {
Command = $"gr_func setgradeall {grade}", Color = HexToRustFormat(MainInterface.ColorPanel)
}
, Text = {
Text = grade.ToString(), Color = HexToRustFormat(MainInterface.ColorText), Align = TextAnchor.MiddleCenter
}
}
, "GRADE_LEVELS", $"LEVEL_{grade}");
}
}
CuiHelper.AddUi(player, container);
}
void Interface_UI_Status(BasePlayer player) {
CuiElementContainer container = new CuiElementContainer();
CuiHelper.DestroyUi(player, UI_STATUS_PARENT);
CuiHelper.DestroyUi(player, UI_ADMIN_MENU_PARENT);
var Interface = config.InterfaceSetting;
var MainInterface = Interface.MainInterfaces;
var Data = DataPlayer[player.userID];
if (Data.GradeLevel == 0) {
CuiHelper.DestroyUi(player, UI_STATUS_PARENT);
return;
}
container.Add(new CuiPanel {
FadeOut = 0.15f, RectTransform = {
AnchorMin = Interface.AnchorMin, AnchorMax = Interface.AnchorMax, OffsetMin = Interface.OffsetMin, OffsetMax = Interface.OffsetMax
}
, Image = {
FadeIn = 0.15f, Color = HexToRustFormat(MainInterface.ColorPanel), Material = MainInterface.Material
}
}
, "Overlay", UI_STATUS_PARENT);
string ILPng = Data.GradeLevel != 5 ? "UPGRADE_IL" : "REMOVE_IL";
string SpritePng = Data.GradeLevel != 5 ? MainInterface.GradeSpritePNG : MainInterface.RemoveSpritePNG;
CuiImageComponent cuiRawImageComponent = Interface.UseIL ? new CuiImageComponent {
FadeIn = 0.15f, Png = GetImage(ILPng), Color = HexToRustFormat(MainInterface.ColorText)
}
: new CuiImageComponent {
FadeIn = 0.15f, Sprite = SpritePng, Color = HexToRustFormat(MainInterface.ColorText)
}
;
container.Add(new CuiElement {
FadeOut = 0.15f, Parent = UI_STATUS_PARENT, Components = {
cuiRawImageComponent, new CuiRectTransformComponent {
AnchorMin = "0.01149801 0.1866667", AnchorMax = "0.06666801 0.8266667"
}
,
}
}
);
CuiHelper.AddUi(player, container);
Interface_Update_Status(player);
}
void Interface_Update_Status(BasePlayer player) {
CuiElementContainer container = new CuiElementContainer();
CuiHelper.DestroyUi(player, "TITLE_TIMER");
var Interface = config.InterfaceSetting;
var MainInterface = Interface.MainInterfaces;
var Data = DataPlayer[player.userID];
string Text = Data.GradeLevel != 5 ? String.Format(lang.GetMessage("GRADE_TITLE", this, player.UserIDString), StatusLevels[Data.GradeLevel], FormatTime(TimeSpan.FromSeconds(Data.ActiveTime - CurrentTime()))) : String.Format(lang.GetMessage("REMOVE_TITLE", this, player.UserIDString), FormatTime(TimeSpan.FromSeconds(Data.ActiveTime - CurrentTime())));
container.Add(new CuiLabel {
FadeOut = 0.15f, RectTransform = {
AnchorMin = "0.08275861 0", AnchorMax = "1 1"
}
, Text = {
FadeIn = 0.15f, Text = Text, FontSize = MainInterface.FontSize, Color = HexToRustFormat(MainInterface.ColorText), Font = "robotocondensed-regular.ttf", Align = TextAnchor.MiddleLeft
}
}
, UI_STATUS_PARENT, "TITLE_TIMER");
CuiHelper.AddUi(player, container);
if (Data.ActiveTime - CurrentTime() <= 1) {
Data.GradeLevel = 0;
CuiHelper.DestroyUi(player, UI_STATUS_PARENT);
return;
}
Data.RebootTimer();
Data.TimerEvent = timer.Once(1f, () => Interface_Update_Status(player));
}
void Interface_UI_Error(BasePlayer player, string Text) {
CuiElementContainer container = new CuiElementContainer();
CuiHelper.DestroyUi(player, UI_ERROR_ALERT_PARENT);
var Interface = config.InterfaceSetting;
var ErrorInterface = Interface.ErrorInterfaces;
container.Add(new CuiPanel {
FadeOut = 0.15f, RectTransform = {
AnchorMin = Interface.AnchorMin, AnchorMax = Interface.AnchorMax, OffsetMin = Interface.OffsetMin, OffsetMax = Interface.OffsetMax
}
, Image = {
FadeIn = 0.15f, Color = HexToRustFormat(ErrorInterface.ColorPanel), Material = ErrorInterface.Material
}
}
, "Overlay", UI_ERROR_ALERT_PARENT);
CuiImageComponent cuiRawImageComponent = Interface.UseIL ? new CuiImageComponent {
FadeIn = 0.15f, Png = GetImage("ERROR_I
// ... [Code preview truncated due to length. Full source in attached file] ...