Compare commits

...

16 Commits

Author SHA1 Message Date
Nereziel
2abe48f71a 123 2024-03-02 19:15:50 +01:00
Nereziel
219c201fde testref 2024-02-24 22:44:17 +01:00
Nereziel
acf4a766ca Update Commands.cs 2024-02-24 21:15:45 +01:00
Dawid Bepierszcz
ad73e0a85d Merge pull request #171 from daffyyyy/main
Some fixes
2024-02-23 02:58:01 +01:00
Dawid Bepierszcz
25c205e53d Merge branch 'Nereziel:main' into main 2024-02-23 02:56:42 +01:00
Dawid Bepierszcz
1366e141a7 Merge branch 'main' of https://github.com/daffyyyy/cs2-WeaponPaints 2024-02-23 02:46:00 +01:00
Dawid Bepierszcz
5465b982b7 Some fixes 2024-02-23 02:45:58 +01:00
Dawid Bepierszcz
ead5ae23a3 Merge pull request #170 from daffyyyy/main
1.9b
2024-02-22 22:46:31 +01:00
Dawid Bepierszcz
ff2e7ffd6b Merge branch 'Nereziel:main' into main 2024-02-22 22:43:46 +01:00
Dawid Bepierszcz
c9a1fad496 1.9b 2024-02-22 22:43:25 +01:00
Dawid Bepierszcz
0d4d01800d Merge branch 'main' of https://github.com/daffyyyy/cs2-WeaponPaints 2024-02-22 22:41:34 +01:00
Dawid Bepierszcz
19d004c21d 1.9b
- Fixed weapons on retake
- FIxed saving
2024-02-22 22:41:32 +01:00
Dawid Bepierszcz
391efd5cac Merge pull request #169 from daffyyyy/main
1.9a
2024-02-22 21:12:33 +01:00
Dawid Bepierszcz
3cf9a67ee2 Merge branch 'Nereziel:main' into main 2024-02-22 21:10:26 +01:00
Dawid Bepierszcz
ddb4fb7cba Merge branch 'main' of https://github.com/daffyyyy/cs2-WeaponPaints 2024-02-22 21:09:00 +01:00
Dawid Bepierszcz
e75d48bd0d 1.9a
- Removed GlobalShare
- More stability
2024-02-22 21:07:52 +01:00
16 changed files with 740 additions and 730 deletions

View File

@@ -1,7 +1,8 @@
using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Commands; using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Menu; using CounterStrikeSharp.API.Modules.Menu;
using Newtonsoft.Json.Linq;
using System.Text;
namespace WeaponPaints namespace WeaponPaints
{ {
@@ -13,39 +14,50 @@ namespace WeaponPaints
if (!Utility.IsPlayerValid(player)) return; if (!Utility.IsPlayerValid(player)) return;
if (player == null || !player.IsValid || player.UserId == null || player.IsBot) return; if (player == null || !player.IsValid || player.UserId == null || player.IsBot) return;
PlayerInfo playerInfo = new (
int playerIndex = (int)player!.Index; (int)player.Index,
player.Slot,
PlayerInfo playerInfo = new PlayerInfo player.UserId,
{ player.SteamID.ToString(),
UserId = player.UserId, player.PlayerName,
Index = (int)player.Index, player.IpAddress?.Split(":")[0]
SteamId = player?.SteamID.ToString(), );
Name = player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0]
};
if (player == null || !player.IsValid || player.UserId == null || player.IsBot) return;
try try
{ {
if (!commandsCooldown.TryGetValue((int)player.UserId, out DateTime cooldownEndTime) || if (player != null && !commandsCooldown.TryGetValue(player.Slot, out DateTime cooldownEndTime) ||
DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow)) player != null && DateTime.UtcNow >= (commandsCooldown.TryGetValue(player.Slot, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
{ {
commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds); commandsCooldown[player.Slot] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
if (weaponSync != null) if (weaponSync != null)
{ {
Task.Run(async () => await weaponSync.GetWeaponPaintsFromDatabase(playerInfo)); var weaponTasks = new List<Task>();
weaponTasks.Add(Task.Run(async () =>
{
await weaponSync.GetWeaponPaintsFromDatabase(playerInfo);
}));
if (Config.Additional.GloveEnabled) if (Config.Additional.GloveEnabled)
Task.Run(async () => await weaponSync.GetGloveFromDatabase(playerInfo)); {
weaponTasks.Add(Task.Run(async () =>
{
await weaponSync.GetGloveFromDatabase(playerInfo);
}));
}
if (Config.Additional.KnifeEnabled) if (Config.Additional.KnifeEnabled)
Task.Run(async () => await weaponSync.GetKnifeFromDatabase(playerInfo)); {
weaponTasks.Add(Task.Run(async () =>
{
await weaponSync.GetKnifeFromDatabase(playerInfo);
}));
}
Task.WaitAll(weaponTasks.ToArray());
RefreshWeapons(player);
RefreshGloves(player); RefreshGloves(player);
RefreshWeapons(player);
} }
if (!string.IsNullOrEmpty(Localizer["wp_command_refresh_done"])) if (!string.IsNullOrEmpty(Localizer["wp_command_refresh_done"]))
@@ -112,316 +124,372 @@ namespace WeaponPaints
} }
} }
private void SetupKnifeMenu() private void SetupKnifeMenu()
{ {
if (!Config.Additional.KnifeEnabled || !g_bCommandsAllowed) return; if (!Config.Additional.KnifeEnabled || !g_bCommandsAllowed) return;
var knivesOnly = weaponList var knivesOnly = GetKnivesOnly();
.Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet")) var giveItemMenu = new ChatMenu(Localizer["wp_knife_menu_title"]);
.ToDictionary(pair => pair.Key, pair => pair.Value);
var giveItemMenu = new ChatMenu(Localizer["wp_knife_menu_title"]); AddMenuOptions(giveItemMenu, knivesOnly);
var handleGive = (CCSPlayerController player, ChatMenuOption option) => AddCommandToOpenKnifeMenu(giveItemMenu);
{ }
if (!Utility.IsPlayerValid(player)) return;
var knifeName = option.Text; private Dictionary<string, string> GetKnivesOnly()
var knifeKey = knivesOnly.FirstOrDefault(x => x.Value == knifeName).Key; {
if (!string.IsNullOrEmpty(knifeKey)) return weaponList
{ .Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet"))
if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_select"])) .ToDictionary(pair => pair.Key, pair => pair.Value);
{ }
player!.Print(Localizer["wp_knife_menu_select", knifeName]);
}
if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_kill"]) && Config.Additional.CommandKillEnabled) private void AddMenuOptions(ChatMenu giveItemMenu, Dictionary<string, string> knivesOnly)
{ {
player!.Print(Localizer["wp_knife_menu_kill"]); foreach (var knifePair in knivesOnly)
} {
giveItemMenu.AddMenuOption(knifePair.Value, (player, option) => HandleGiveOption(player, option, knivesOnly));
}
}
PlayerInfo playerInfo = new PlayerInfo private void HandleGiveOption(CCSPlayerController player, ChatMenuOption option, Dictionary<string, string> knivesOnly)
{ {
UserId = player.UserId, if (!Utility.IsPlayerValid(player)) return;
Index = (int)player.Index,
SteamId = player.SteamID.ToString(),
Name = player.PlayerName,
IpAddress = player.IpAddress?.Split(":")[0]
};
g_playersKnife[(int)player!.Index] = knifeKey; var knifeName = option.Text;
var knifeKey = knivesOnly.FirstOrDefault(x => x.Value == knifeName).Key;
if (!string.IsNullOrEmpty(knifeKey))
{
PrintMessages(player, knifeName);
SetPlayerKnife(player, knifeKey);
SyncKnifeToDatabase(player, knifeKey);
}
}
if (weaponSync != null) private void PrintMessages(CCSPlayerController player, string knifeName)
Task.Run(async () => await weaponSync.SyncKnifeToDatabase(playerInfo, knifeKey)); {
if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_select"]))
{
player!.Print(Localizer["wp_knife_menu_select", knifeName]);
}
if (g_bCommandsAllowed && (LifeState_t)player.LifeState == LifeState_t.LIFE_ALIVE) if (!string.IsNullOrEmpty(Localizer["wp_knife_menu_kill"]) && Config.Additional.CommandKillEnabled)
AddTimer(0.2f, () => RefreshWeapons(player), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE); {
} player!.Print(Localizer["wp_knife_menu_kill"]);
}; }
foreach (var knifePair in knivesOnly) }
{
giveItemMenu.AddMenuOption(knifePair.Value, handleGive);
}
AddCommand($"css_{Config.Additional.CommandKnife}", "Knife Menu", (player, info) =>
{
if (!Utility.IsPlayerValid(player) || !g_bCommandsAllowed) return;
if (player == null || player.UserId == null) return; private void SetPlayerKnife(CCSPlayerController player, string knifeKey)
{
g_playersKnife[player.Slot] = knifeKey;
if (!commandsCooldown.TryGetValue((int)player.UserId, out DateTime cooldownEndTime) || if (g_bCommandsAllowed && (LifeState_t)player.LifeState == LifeState_t.LIFE_ALIVE)
DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow)) RefreshWeapons(player);
{ }
commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
giveItemMenu.PostSelectAction = PostSelectAction.Close;
MenuManager.OpenChatMenu(player, giveItemMenu);
return;
}
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
player!.Print(Localizer["wp_command_cooldown"]);
}
});
}
private void SetupSkinsMenu() private void SyncKnifeToDatabase(CCSPlayerController player, string knifeKey)
{ {
var classNamesByWeapon = weaponList.ToDictionary(kvp => kvp.Value, kvp => kvp.Key); if (weaponSync != null)
var weaponSelectionMenu = new ChatMenu(Localizer["wp_skin_menu_weapon_title"]); Task.Run(async () => await weaponSync.SyncKnifeToDatabase(GetPlayerInfo(player), knifeKey));
weaponSelectionMenu.PostSelectAction = PostSelectAction.Close; }
// Function to handle skin selection for a specific weapon private PlayerInfo GetPlayerInfo(CCSPlayerController player)
var handleWeaponSelection = (CCSPlayerController? player, ChatMenuOption option) => {
{ return new PlayerInfo
if (!Utility.IsPlayerValid(player)) return; {
UserId = player.UserId,
Slot = player.Slot,
Index = (int)player.Index,
SteamId = player.SteamID.ToString(),
Name = player.PlayerName,
IpAddress = player.IpAddress?.Split(":")[0]
};
}
int playerIndex = (int)player!.Index; private void AddCommandToOpenKnifeMenu(ChatMenu giveItemMenu)
string selectedWeapon = option.Text; {
if (classNamesByWeapon.TryGetValue(selectedWeapon, out string? selectedWeaponClassname)) AddCommand($"css_{Config.Additional.CommandKnife}", "Knife Menu", (player, info) =>
{ {
if (selectedWeaponClassname == null) return; if (!Utility.IsPlayerValid(player) || !g_bCommandsAllowed) return;
var skinsForSelectedWeapon = skinsList?.Where(skin =>
skin != null &&
skin.TryGetValue("weapon_name", out var weaponName) &&
weaponName?.ToString() == selectedWeaponClassname
)?.ToList();
var skinSubMenu = new ChatMenu(Localizer["wp_skin_menu_skin_title", selectedWeapon]); if (player == null || player.UserId == null) return;
skinSubMenu.PostSelectAction = PostSelectAction.Close;
// Function to handle skin selection for the chosen weapon if (IsCommandAllowed(player))
var handleSkinSelection = (CCSPlayerController p, ChatMenuOption opt) => {
{ commandsCooldown[player.Slot] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
if (!Utility.IsPlayerValid(p)) return; giveItemMenu.PostSelectAction = PostSelectAction.Close;
MenuManager.OpenChatMenu(player, giveItemMenu);
return;
}
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
player!.Print(Localizer["wp_command_cooldown"]);
}
});
}
playerIndex = (int)p.Index; private bool IsCommandAllowed(CCSPlayerController player)
{
if (!commandsCooldown.TryGetValue(player.Slot, out DateTime cooldownEndTime))
{
return true;
}
return DateTime.UtcNow >= cooldownEndTime;
}
string steamId = p.SteamID.ToString(); private void SetupSkinsMenu()
var firstSkin = skinsList?.FirstOrDefault(skin => {
{ var classNamesByWeapon = weaponList.ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
if (skin != null && skin.TryGetValue("weapon_name", out var weaponName)) var weaponSelectionMenu = new ChatMenu(Localizer["wp_skin_menu_weapon_title"]);
{
return weaponName?.ToString() == selectedWeaponClassname;
}
return false;
});
string selectedSkin = opt.Text; // Add weapon options to the weapon selection menu
string selectedPaintID = selectedSkin.Split('(')[1].Trim(')').Trim(); foreach (var weaponClass in weaponList.Keys)
{
string weaponName = weaponList[weaponClass];
weaponSelectionMenu.AddMenuOption(weaponName, (player, option) => HandleWeaponSelection(player, option, classNamesByWeapon));
}
if (firstSkin != null && // Command to open the weapon selection menu for players
firstSkin.TryGetValue("weapon_defindex", out var weaponDefIndexObj) && AddCommand($"css_{Config.Additional.CommandSkinSelection}", "Skins selection menu", (player, info) => OpenWeaponSelectionMenu(player, weaponSelectionMenu));
weaponDefIndexObj != null && }
int.TryParse(weaponDefIndexObj.ToString(), out var weaponDefIndex) &&
int.TryParse(selectedPaintID, out var paintID))
{
if (Config.Additional.ShowSkinImage && skinsList != null)
{
var foundSkin = skinsList.FirstOrDefault(skin =>
((int?)skin?["weapon_defindex"] ?? 0) == weaponDefIndex &&
((int?)skin?["paint"] ?? 0) == paintID &&
skin?["image"] != null
);
string image = foundSkin?["image"]?.ToString() ?? "";
PlayerWeaponImage[p.Slot] = image;
AddTimer(2.0f, () => PlayerWeaponImage.Remove(p.Slot), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE);
}
p.Print(Localizer["wp_skin_menu_select", selectedSkin]); private void HandleWeaponSelection(CCSPlayerController? player, ChatMenuOption option, Dictionary<string, string> classNamesByWeapon)
{
if (!Utility.IsPlayerValid(player)) return;
if (!gPlayerWeaponsInfo[playerIndex].ContainsKey(weaponDefIndex)) string selectedWeapon = option.Text;
{ if (classNamesByWeapon.TryGetValue(selectedWeapon, out string? selectedWeaponClassname))
gPlayerWeaponsInfo[playerIndex][weaponDefIndex] = new WeaponInfo(); {
} if (selectedWeaponClassname == null) return;
var skinsForSelectedWeapon = skinsList?.Where(skin =>
skin != null &&
skin.TryGetValue("weapon_name", out var weaponName) &&
weaponName?.ToString() == selectedWeaponClassname
)?.ToList();
gPlayerWeaponsInfo[playerIndex][weaponDefIndex].Paint = paintID; var skinSubMenu = new ChatMenu(Localizer["wp_skin_menu_skin_title", selectedWeapon]);
gPlayerWeaponsInfo[playerIndex][weaponDefIndex].Wear = 0.01f; skinSubMenu.PostSelectAction = PostSelectAction.Close;
gPlayerWeaponsInfo[playerIndex][weaponDefIndex].Seed = 0;
PlayerInfo playerInfo = new PlayerInfo // Add skin options to the submenu for the selected weapon
{ if (skinsForSelectedWeapon != null)
UserId = p.UserId, {
Index = (int)p.Index, foreach (var skin in skinsForSelectedWeapon.Where(s => s != null))
SteamId = p.SteamID.ToString(), {
Name = p.PlayerName, if (skin.TryGetValue("paint_name", out var paintNameObj) && skin.TryGetValue("paint", out var paintObj))
IpAddress = p.IpAddress?.Split(":")[0] {
}; var paintName = paintNameObj?.ToString();
var paint = paintObj?.ToString();
if (g_bCommandsAllowed && (LifeState_t)p.LifeState == LifeState_t.LIFE_ALIVE) if (!string.IsNullOrEmpty(paintName) && !string.IsNullOrEmpty(paint))
AddTimer(0.2f, () => RefreshWeapons(p), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE); {
} var optionText = new StringBuilder(paintName).Append(" (").Append(paint).Append(")").ToString();
}; skinSubMenu.AddMenuOption(optionText, (p, opt) => HandleSkinSelection(p, opt, selectedWeaponClassname));
}
}
}
}
if (player != null && Utility.IsPlayerValid(player))
MenuManager.OpenChatMenu(player, skinSubMenu);
}
}
// Add skin options to the submenu for the selected weapon private void HandleSkinSelection(CCSPlayerController p, ChatMenuOption opt, string selectedWeaponClassname)
if (skinsForSelectedWeapon != null) {
{ if (!Utility.IsPlayerValid(p)) return;
foreach (var skin in skinsForSelectedWeapon.Where(s => s != null))
{
if (skin.TryGetValue("paint_name", out var paintNameObj) && skin.TryGetValue("paint", out var paintObj))
{
var paintName = paintNameObj?.ToString();
var paint = paintObj?.ToString();
if (!string.IsNullOrEmpty(paintName) && !string.IsNullOrEmpty(paint)) string steamId = p.SteamID.ToString();
{ var firstSkin = skinsList?.Find(skin =>
skinSubMenu.AddMenuOption($"{paintName} ({paint})", handleSkinSelection); {
} if (skin != null && skin.TryGetValue("weapon_name", out var weaponName))
} {
} return weaponName?.ToString() == selectedWeaponClassname;
} }
return false;
});
// Open the submenu for skin selection of the chosen weapon string selectedSkin = opt.Text;
MenuManager.OpenChatMenu(player, skinSubMenu); string selectedPaintID = selectedSkin.Split('(')[1].Trim(')').Trim();
}
};
// Add weapon options to the weapon selection menu if (firstSkin != null &&
foreach (var weaponClass in weaponList.Keys) firstSkin.TryGetValue("weapon_defindex", out var weaponDefIndexObj) &&
{ weaponDefIndexObj != null &&
string weaponName = weaponList[weaponClass]; int.TryParse(weaponDefIndexObj.ToString(), out var weaponDefIndex) &&
weaponSelectionMenu.AddMenuOption(weaponName, handleWeaponSelection); int.TryParse(selectedPaintID, out var paintID))
} {
// Command to open the weapon selection menu for players HandleSkinImage(p, weaponDefIndex, paintID);
AddCommand($"css_{Config.Additional.CommandSkinSelection}", "Skins selection menu", (player, info) => p.Print(Localizer["wp_skin_menu_select", selectedSkin]);
{ UpdatePlayerWeaponInfo(p, weaponDefIndex, paintID);
if (!Utility.IsPlayerValid(player)) return; }
}
if (player == null || player.UserId == null) return; private void HandleSkinImage(CCSPlayerController p, int weaponDefIndex, int paintID)
{
if (Config.Additional.ShowSkinImage && skinsList != null)
{
var foundSkin = skinsList.FirstOrDefault(skin =>
((int?)skin?["weapon_defindex"] ?? 0) == weaponDefIndex &&
((int?)skin?["paint"] ?? 0) == paintID &&
skin?["image"] != null
);
string image = foundSkin?["image"]?.ToString() ?? "";
PlayerWeaponImage[p.Slot] = image;
AddTimer(2.0f, () => PlayerWeaponImage.Remove(p.Slot), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE);
}
}
if (!commandsCooldown.TryGetValue((int)player.UserId, out DateTime cooldownEndTime) || private void UpdatePlayerWeaponInfo(CCSPlayerController p, int weaponDefIndex, int paintID)
DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow)) {
{ if (!gPlayerWeaponsInfo[p.Slot].TryGetValue(weaponDefIndex, out WeaponInfo? value))
commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds); {
MenuManager.OpenChatMenu(player, weaponSelectionMenu); value = new WeaponInfo();
return; gPlayerWeaponsInfo[p.Slot][weaponDefIndex] = value;
} }
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
player!.Print(Localizer["wp_command_cooldown"]);
}
});
}
private void SetupGlovesMenu() value.Paint = paintID;
{ value.Wear = 0.00f;
var glovesSelectionMenu = new ChatMenu(Localizer["wp_glove_menu_title"]); value.Seed = 0;
glovesSelectionMenu.PostSelectAction = PostSelectAction.Close;
var handleGloveSelection = (CCSPlayerController? player, ChatMenuOption option) => if (g_bCommandsAllowed && (LifeState_t)p.LifeState == LifeState_t.LIFE_ALIVE)
{ {
if (!Utility.IsPlayerValid(player)) return; RefreshWeapons(p);
}
}
uint playerIndex = player!.Index; private void OpenWeaponSelectionMenu(CCSPlayerController? player, ChatMenu weaponSelectionMenu)
string selectedPaintName = option.Text; {
if (!Utility.IsPlayerValid(player)) return;
var selectedGlove = glovesList.FirstOrDefault(g => g.ContainsKey("paint_name") && g["paint_name"]?.ToString() == selectedPaintName); if (player == null || player.UserId == null) return;
if (selectedGlove != null)
{
if (
selectedGlove != null &&
selectedGlove.ContainsKey("weapon_defindex") &&
selectedGlove.ContainsKey("paint") &&
int.TryParse(selectedGlove["weapon_defindex"]?.ToString(), out int weaponDefindex) &&
int.TryParse(selectedGlove["paint"]?.ToString(), out int paint)
)
{
if (Config.Additional.ShowSkinImage)
{
string image = selectedGlove["image"]?.ToString() ?? "";
PlayerWeaponImage[player.Slot] = image;
AddTimer(2.0f, () => PlayerWeaponImage.Remove(player.Slot), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE);
}
PlayerInfo playerInfo = new PlayerInfo if (player != null && !commandsCooldown.TryGetValue(player.Slot, out DateTime cooldownEndTime) ||
{ player != null && DateTime.UtcNow >= (commandsCooldown.TryGetValue(player.Slot, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
UserId = player.UserId, {
Index = (int)player.Index, commandsCooldown[player.Slot] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
SteamId = player.SteamID.ToString(), MenuManager.OpenChatMenu(player, weaponSelectionMenu);
Name = player.PlayerName, return;
IpAddress = player.IpAddress?.Split(":")[0] }
}; if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
player!.Print(Localizer["wp_command_cooldown"]);
}
}
private void SetupGlovesMenu()
{
var glovesSelectionMenu = new ChatMenu(Localizer["wp_glove_menu_title"]);
glovesSelectionMenu.PostSelectAction = PostSelectAction.Close;
if (paint != 0) var handleGloveSelection = (CCSPlayerController? player, ChatMenuOption option) =>
{ {
g_playersGlove[playerIndex] = (ushort)weaponDefindex; if (!Utility.IsPlayerValid(player) || player is null) return;
if (!gPlayerWeaponsInfo[(int)playerIndex].ContainsKey(weaponDefindex)) string selectedPaintName = option.Text;
{ var selectedGlove = glovesList.FirstOrDefault(g => g.ContainsKey("paint_name") && g["paint_name"]?.ToString() == selectedPaintName);
WeaponInfo weaponInfo = new(); if (selectedGlove != null)
weaponInfo.Paint = paint; {
gPlayerWeaponsInfo[(int)playerIndex][weaponDefindex] = weaponInfo; HandleSelectedGlove(player, selectedGlove, selectedPaintName);
} }
} };
else
{
g_playersGlove.TryRemove(playerIndex, out _);
}
if (!string.IsNullOrEmpty(Localizer["wp_glove_menu_select"])) AddGloveOptionsToMenu(glovesSelectionMenu, handleGloveSelection);
{ AddCommandToOpenGloveSelectionMenu(glovesSelectionMenu);
player!.Print(Localizer["wp_glove_menu_select", selectedPaintName]); }
}
void HandleSelectedGlove(CCSPlayerController? player, JObject selectedGlove, string selectedPaintName)
{
if (selectedGlove != null &&
selectedGlove.ContainsKey("weapon_defindex") &&
selectedGlove.ContainsKey("paint") &&
int.TryParse(selectedGlove["weapon_defindex"]?.ToString(), out int weaponDefindex) &&
int.TryParse(selectedGlove["paint"]?.ToString(), out int paint))
{
if (Config.Additional.ShowSkinImage)
{
string image = selectedGlove["image"]?.ToString() ?? "";
PlayerWeaponImage[player.Slot] = image;
AddTimer(2.0f, () => PlayerWeaponImage.Remove(player.Slot), CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE);
}
PlayerInfo playerInfo = new(
(int)player.Index,
player.Slot,
player.UserId,
player.SteamID.ToString(),
player.PlayerName,
player.IpAddress?.Split(":")[0]
);
Server.NextFrame(() => if (paint != 0)
{ {
RefreshGloves(player); g_playersGlove[player.Slot] = (ushort)weaponDefindex;
});
if (weaponSync != null) if (!gPlayerWeaponsInfo[player.Slot].TryGetValue(weaponDefindex, out _))
{ {
Task.Run(async () => await weaponSync.SyncGloveToDatabase(playerInfo, (ushort)weaponDefindex)); WeaponInfo weaponInfo = new();
} weaponInfo.Paint = paint;
} gPlayerWeaponsInfo[player.Slot][weaponDefindex] = weaponInfo;
}; }
}; }
else
{
g_playersGlove.TryRemove(player.Slot, out _);
}
// Add weapon options to the weapon selection menu if (!string.IsNullOrEmpty(Localizer["wp_glove_menu_select"]))
foreach (var gloveObject in glovesList) {
{ player!.Print(Localizer["wp_glove_menu_select", selectedPaintName]);
string paintName = gloveObject["paint_name"]?.ToString() ?? ""; }
if (paintName.Length > 0) if (weaponSync != null)
glovesSelectionMenu.AddMenuOption(paintName, handleGloveSelection); {
} Task.Run(async () =>
{
await weaponSync.SyncGloveToDatabase(playerInfo, weaponDefindex);
// Command to open the weapon selection menu for players if (!gPlayerWeaponsInfo[playerInfo.Slot].TryGetValue(weaponDefindex, out var weaponInfo))
AddCommand($"css_{Config.Additional.CommandGlove}", "Gloves selection menu", (player, info) => {
{ weaponInfo = new WeaponInfo();
if (!Utility.IsPlayerValid(player) || !g_bCommandsAllowed) return; gPlayerWeaponsInfo[playerInfo.Slot][weaponDefindex] = weaponInfo;
}
if (player == null || player.UserId == null) return; weaponInfo.Paint = paint;
weaponInfo.Wear = 0.00f;
weaponInfo.Seed = 0;
if (!commandsCooldown.TryGetValue((int)player.UserId, out DateTime cooldownEndTime) || });
DateTime.UtcNow >= (commandsCooldown.TryGetValue((int)player.UserId, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow)) }
{ RefreshGloves(player);
commandsCooldown[(int)player.UserId] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds); }
MenuManager.OpenChatMenu(player, glovesSelectionMenu); }
return;
} private void AddGloveOptionsToMenu(ChatMenu glovesSelectionMenu, Action<CCSPlayerController?, ChatMenuOption> handleGloveSelection)
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"])) {
{ foreach (var gloveObject in glovesList)
player!.Print(Localizer["wp_command_cooldown"]); {
} string paintName = gloveObject["paint_name"]?.ToString() ?? "";
});
} if (paintName.Length > 0)
glovesSelectionMenu.AddMenuOption(paintName, handleGloveSelection);
}
}
private void AddCommandToOpenGloveSelectionMenu(ChatMenu glovesSelectionMenu)
{
AddCommand($"css_{Config.Additional.CommandGlove}", "Gloves selection menu", (player, info) =>
{
if (!Utility.IsPlayerValid(player) || !g_bCommandsAllowed) return;
if (player == null || player.UserId == null) return;
if (player != null && !commandsCooldown.TryGetValue(player.Slot, out DateTime cooldownEndTime) ||
player != null && DateTime.UtcNow >= (commandsCooldown.TryGetValue(player.Slot, out cooldownEndTime) ? cooldownEndTime : DateTime.UtcNow))
{
commandsCooldown[player.Slot] = DateTime.UtcNow.AddSeconds(Config.CmdRefreshCooldownSeconds);
MenuManager.OpenChatMenu(player, glovesSelectionMenu);
return;
}
if (!string.IsNullOrEmpty(Localizer["wp_command_cooldown"]))
{
player!.Print(Localizer["wp_command_cooldown"]);
}
});
}
} }
} }

View File

@@ -73,9 +73,6 @@ namespace WeaponPaints
[JsonPropertyName("DatabaseName")] [JsonPropertyName("DatabaseName")]
public string DatabaseName { get; set; } = ""; public string DatabaseName { get; set; } = "";
[JsonPropertyName("GlobalShare")]
public bool GlobalShare { get; set; } = false;
[JsonPropertyName("CmdRefreshCooldownSeconds")] [JsonPropertyName("CmdRefreshCooldownSeconds")]
public int CmdRefreshCooldownSeconds { get; set; } = 60; public int CmdRefreshCooldownSeconds { get; set; } = 60;

View File

@@ -11,18 +11,11 @@ namespace WeaponPaints
_dbConnectionString = dbConnectionString; _dbConnectionString = dbConnectionString;
} }
public async Task<MySqlConnection> GetConnectionAsync() public async Task<MySqlConnection> GetConnectionAsync()
{ {
try var connection = new MySqlConnection(_dbConnectionString);
{ await connection.OpenAsync();
var connection = new MySqlConnection(_dbConnectionString); return connection;
await connection.OpenAsync(); }
return connection;
}
catch (Exception)
{
throw;
}
}
} }
} }

148
Events.cs
View File

@@ -6,34 +6,42 @@ namespace WeaponPaints
{ {
public partial class WeaponPaints public partial class WeaponPaints
{ {
[GameEventHandler] [GameEventHandler]
public HookResult OnPlayerConnect(EventPlayerConnectFull @event, GameEventInfo info) public HookResult OnClientFullConnect(EventPlayerConnectFull @event, GameEventInfo info)
{ {
CCSPlayerController? player = @event.Userid; CCSPlayerController? player = @event.Userid;
if (player is null || !player.IsValid || player.IsBot || player.IsHLTV || player.SteamID.ToString().Length != 17 || if (player is null || !player.IsValid || player.IsBot || player.IsHLTV || player.SteamID.ToString().Length != 17 ||
weaponSync == null || _database == null) return HookResult.Continue; weaponSync == null || _database == null) return HookResult.Continue;
PlayerInfo playerInfo = new PlayerInfo PlayerInfo playerInfo = new(
{ (int)player.Index,
UserId = player.UserId, player.Slot,
Index = (int)player.Index, player.UserId,
SteamId = player.SteamID.ToString(), player.SteamID.ToString(),
Name = player.PlayerName, player.PlayerName,
IpAddress = player.IpAddress?.Split(":")[0] player.IpAddress?.Split(":")[0]
}; );
Task.Run(async () => try
{ {
// Run skin, knife, and glove tasks asynchronously if (Config.Additional.SkinEnabled)
var skinTask = Config.Additional.SkinEnabled ? weaponSync.GetWeaponPaintsFromDatabase(playerInfo) : Task.CompletedTask; {
var knifeTask = Config.Additional.KnifeEnabled ? weaponSync.GetKnifeFromDatabase(playerInfo) : Task.CompletedTask; Task.Run(() => weaponSync.GetWeaponPaintsFromDatabase(playerInfo));
var gloveTask = Config.Additional.GloveEnabled ? weaponSync.GetGloveFromDatabase(playerInfo) : Task.CompletedTask; }
if (Config.Additional.KnifeEnabled)
// Await all tasks to complete {
await Task.WhenAll(skinTask, knifeTask, gloveTask); Task.Run(() => weaponSync.GetKnifeFromDatabase(playerInfo));
}); }
if (Config.Additional.GloveEnabled)
{
Task.Run(() => weaponSync.GetGloveFromDatabase(playerInfo));
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
return HookResult.Continue; return HookResult.Continue;
} }
@@ -43,29 +51,43 @@ namespace WeaponPaints
{ {
CCSPlayerController player = @event.Userid; CCSPlayerController player = @event.Userid;
if (player is null || !player.IsValid || !player.UserId.HasValue || player.IsBot || if (player is null || !player.IsValid || player.IsBot ||
player.IsHLTV || player.SteamID.ToString().Length != 17) return HookResult.Continue; player.IsHLTV || player.SteamID.ToString().Length != 17) return HookResult.Continue;
PlayerInfo playerInfo = new PlayerInfo PlayerInfo playerInfo = new(
(int)player.Index,
player.Slot,
player.UserId,
player.SteamID.ToString(),
player.PlayerName,
player.IpAddress?.Split(":")[0]
);
if (weaponSync != null)
{ {
UserId = player.UserId, // Run weapon sync tasks asynchronously
Index = (int)player.Index, Task.Run(async () =>
SteamId = player.SteamID.ToString(), {
Name = player.PlayerName, await weaponSync.SyncWeaponPaintsToDatabase(playerInfo);
IpAddress = player.IpAddress?.Split(":")[0] });
};
if (weaponSync != null) // Remove player data
Task.Run(async () => await weaponSync.SyncWeaponPaintsToDatabase(playerInfo)); if (Config.Additional.SkinEnabled)
{
gPlayerWeaponsInfo.TryRemove(player.Slot, out _);
}
if (Config.Additional.KnifeEnabled)
{
g_playersKnife.TryRemove(player.Slot, out _);
}
if (Config.Additional.GloveEnabled)
{
g_playersGlove.TryRemove(player.Slot, out _);
}
}
if (Config.Additional.SkinEnabled) // Remove player's command cooldown
gPlayerWeaponsInfo.TryRemove((int)player.Index, out _); commandsCooldown.Remove(player.Slot);
if (Config.Additional.KnifeEnabled)
g_playersKnife.TryRemove((int)player.Index, out _);
if (Config.Additional.GloveEnabled)
g_playersGlove.TryRemove(player.Index, out _);
commandsCooldown.Remove((int)player.UserId);
return HookResult.Continue; return HookResult.Continue;
} }
@@ -92,8 +114,7 @@ namespace WeaponPaints
if (weapon.OwnerEntity.Value == null) return; if (weapon.OwnerEntity.Value == null) return;
if (weapon.OwnerEntity.Index <= 0) return; if (weapon.OwnerEntity.Index <= 0) return;
int weaponOwner = (int)weapon.OwnerEntity.Index; int weaponOwner = (int)weapon.OwnerEntity.Index;
CBasePlayerPawn? pawn = Utilities.GetEntityFromIndex<CCSPlayerPawn>((int)weaponOwner); CBasePlayerPawn? pawn = Utilities.GetEntityFromIndex<CCSPlayerPawn>(weaponOwner);
//var pawn = new CBasePlayerPawn(NativeAPI.GetEntityFromIndex(weaponOwner));
if (!pawn.IsValid) return; if (!pawn.IsValid) return;
var playerIndex = (int)pawn.Controller.Index; var playerIndex = (int)pawn.Controller.Index;
@@ -108,11 +129,14 @@ namespace WeaponPaints
public HookResult OnPickup(CEntityIOOutput output, string name, CEntityInstance activator, CEntityInstance caller, CVariant value, float delay) public HookResult OnPickup(CEntityIOOutput output, string name, CEntityInstance activator, CEntityInstance caller, CVariant value, float delay)
{ {
if (!Config.Additional.GiveKnifeAfterRemove)
return HookResult.Continue;
CCSPlayerController? player = Utilities.GetEntityFromIndex<CCSPlayerPawn>((int)activator.Index).OriginalController.Value; CCSPlayerController? player = Utilities.GetEntityFromIndex<CCSPlayerPawn>((int)activator.Index).OriginalController.Value;
if (player == null || player.IsBot || player.IsHLTV || if (player == null || player.IsBot || player.IsHLTV ||
player.SteamID.ToString().Length != 17 || !g_knifePickupCount.TryGetValue((int)player.Index, out var pickupCount) || player.SteamID.ToString().Length != 17 || !g_knifePickupCount.TryGetValue(player.Slot, out var pickupCount) ||
!g_playersKnife.ContainsKey((int)player.Index)) !g_playersKnife.ContainsKey(player.Slot))
{ {
return HookResult.Continue; return HookResult.Continue;
} }
@@ -129,18 +153,12 @@ namespace WeaponPaints
return HookResult.Continue; return HookResult.Continue;
} }
if (g_playersKnife[(int)player.Index] != "weapon_knife") if (g_playersKnife[player.Slot] != "weapon_knife")
{ {
pickupCount++; pickupCount++;
g_knifePickupCount[(int)player.Index] = pickupCount; g_knifePickupCount[player.Slot] = pickupCount;
if (Config.Additional.GiveKnifeAfterRemove) AddTimer(0.2f, () => RefreshWeapons(player));
{
AddTimer(0.10f, () =>
{
RefreshWeapons(player);
});
}
} }
return HookResult.Continue; return HookResult.Continue;
@@ -151,7 +169,7 @@ namespace WeaponPaints
if (!Config.Additional.KnifeEnabled && !Config.Additional.SkinEnabled && !Config.Additional.GloveEnabled) return; if (!Config.Additional.KnifeEnabled && !Config.Additional.SkinEnabled && !Config.Additional.GloveEnabled) return;
if (_database != null) if (_database != null)
weaponSync = new WeaponSynchronization(_database, Config, GlobalShareApi, GlobalShareServerId); weaponSync = new WeaponSynchronization(_database, Config);
// TODO // TODO
// needed for now // needed for now
@@ -160,9 +178,6 @@ namespace WeaponPaints
NativeAPI.IssueServerCommand("mp_t_default_melee \"\""); NativeAPI.IssueServerCommand("mp_t_default_melee \"\"");
NativeAPI.IssueServerCommand("mp_ct_default_melee \"\""); NativeAPI.IssueServerCommand("mp_ct_default_melee \"\"");
NativeAPI.IssueServerCommand("mp_equipment_reset_rounds 0"); NativeAPI.IssueServerCommand("mp_equipment_reset_rounds 0");
if (Config.GlobalShare)
GlobalShareConnect();
}); });
} }
@@ -170,13 +185,13 @@ namespace WeaponPaints
{ {
CCSPlayerController? player = @event.Userid; CCSPlayerController? player = @event.Userid;
if (player is null || !player.IsValid || player.PlayerPawn == null || if (player is null || !player.IsValid || !Config.Additional.KnifeEnabled && !Config.Additional.GloveEnabled)
!player.PlayerPawn.IsValid || player.IsHLTV
|| !Config.Additional.KnifeEnabled && !Config.Additional.GloveEnabled)
return HookResult.Continue; return HookResult.Continue;
g_knifePickupCount[(int)player.Index] = 0; g_knifePickupCount[player.Slot] = 0;
GiveKnifeToPlayer(player);
if (!PlayerHasKnife(player))
GiveKnifeToPlayer(player);
Server.NextFrame(() => Server.NextFrame(() =>
{ {
@@ -189,6 +204,7 @@ namespace WeaponPaints
private HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info) private HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info)
{ {
g_bCommandsAllowed = false; g_bCommandsAllowed = false;
return HookResult.Continue; return HookResult.Continue;
} }
@@ -244,20 +260,28 @@ namespace WeaponPaints
if (skeleton == null) if (skeleton == null)
continue; continue;
bool skeletonChange = false;
int[] newPaints = { 1171, 1170, 1169, 1164, 1162, 1161, 1159, 1175, 1174, 1167, 1165, 1168, 1163, 1160, 1166, 1173 }; int[] newPaints = { 1171, 1170, 1169, 1164, 1162, 1161, 1159, 1175, 1174, 1167, 1165, 1168, 1163, 1160, 1166, 1173 };
if (newPaints.Contains(weapon.FallbackPaintKit)) if (newPaints.Contains(weapon.FallbackPaintKit))
{ {
skeleton.ModelState.MeshGroupMask = 1; if (skeleton.ModelState.MeshGroupMask != 1)
{
skeleton.ModelState.MeshGroupMask = 1;
skeletonChange = true;
}
} }
else else
{ {
if (skeleton.ModelState.MeshGroupMask != 2) if (skeleton.ModelState.MeshGroupMask != 2)
{ {
skeleton.ModelState.MeshGroupMask = 2; skeleton.ModelState.MeshGroupMask = 2;
skeletonChange = true;
} }
} }
Utilities.SetStateChanged(viewModel.Value, "CBaseEntity", "m_CBodyComponent"); if (skeletonChange)
Utilities.SetStateChanged(viewModel.Value, "CBaseEntity", "m_CBodyComponent");
} }
catch (Exception) catch (Exception)
{ {
@@ -267,7 +291,7 @@ namespace WeaponPaints
private void RegisterListeners() private void RegisterListeners()
{ {
RegisterListener<Listeners.OnEntityCreated>(OnEntityCreated); RegisterListener<Listeners.OnEntitySpawned>(OnEntityCreated);
//RegisterListener<Listeners.OnClientPutInServer>(OnClientPutInServer); //RegisterListener<Listeners.OnClientPutInServer>(OnClientPutInServer);
//RegisterListener<Listeners.OnClientDisconnect>(OnClientDisconnect); //RegisterListener<Listeners.OnClientDisconnect>(OnClientDisconnect);
RegisterListener<Listeners.OnMapStart>(OnMapStart); RegisterListener<Listeners.OnMapStart>(OnMapStart);

View File

@@ -5,11 +5,17 @@ namespace WeaponPaints;
public static class PlayerExtensions public static class PlayerExtensions
{ {
public static void Print(this CCSPlayerController controller, string message) public static void Print(this CCSPlayerController controller, string message)
{ {
if (WeaponPaints._localizer == null) return; if (WeaponPaints._localizer == null)
StringBuilder _message = new(WeaponPaints._localizer["wp_prefix"]); {
_message.Append(message); controller.PrintToChat(message);
controller.PrintToChat(_message.ToString()); }
} else
{
StringBuilder _message = new(WeaponPaints._localizer["wp_prefix"]);
_message.Append(message);
controller.PrintToChat(_message.ToString());
}
}
} }

View File

@@ -1,11 +1,24 @@
namespace WeaponPaints namespace WeaponPaints
{ {
public class PlayerInfo public class PlayerInfo
{ {
public int Index { get; set; } public int Index { get; set; }
public int? UserId { get; set; } public int Slot { get; set; }
public string? SteamId { get; set; } public int? UserId { get; set; }
public string? Name { get; set; } public string? SteamId { get; set; }
public string? IpAddress { get; set; } public string? Name { get; set; }
} public string? IpAddress { get; set; }
public PlayerInfo() { }
public PlayerInfo(int index, int slot, int? userId, string? steamId, string? name, string? ipAddress)
{
Index = index;
Slot = slot;
UserId = userId;
SteamId = steamId;
Name = name;
IpAddress = ipAddress;
}
}
} }

View File

@@ -10,7 +10,7 @@ Unfinished, unoptimized and not fully functional ugly demo weapon paints plugin
## Features ## Features
- Changes only paint, seed and wear on weapons and knives - Changes only paint, seed and wear on weapons and knives
- MySQL based or global website, so you dont need MySQL/Website - MySQL based
- Data syncs on player connect - Data syncs on player connect
- Added command **`!wp`** to refresh skins ***(with cooldown in seconds can be configured)*** - Added command **`!wp`** to refresh skins ***(with cooldown in seconds can be configured)***
- Added command **`!ws`** to show website - Added command **`!ws`** to show website
@@ -18,13 +18,11 @@ Unfinished, unoptimized and not fully functional ugly demo weapon paints plugin
- Knife change is now limited to have these cvars empty **`mp_t_default_melee ""`** and **`mp_ct_default_melee ""`** - Knife change is now limited to have these cvars empty **`mp_t_default_melee ""`** and **`mp_ct_default_melee ""`**
- Translations support, submit a PR if you want to share your translation - Translations support, submit a PR if you want to share your translation
**GlobalShare** - global website accessible at [weaponpaints.fun](https://weaponpaints.fun/)
## CS2 Server ## CS2 Server
- Have working CounterStrikeSharp (**with RUNTIME!**) - Have working CounterStrikeSharp (**with RUNTIME!**)
- Download from Release and copy plugin to plugins - Download from Release and copy plugin to plugins
- Run server with plugin, **it will generate config if installed correctly!** - Run server with plugin, **it will generate config if installed correctly!**
- Edit `addons/counterstrikesharp/configs/`**`plugins/WeaponPaints/WeaponPaints.json`** set **`GlobalShare`** to **`true`** for global, or include database credentials - Edit `addons/counterstrikesharp/configs/`**`plugins/WeaponPaints/WeaponPaints.json`** include database credentials
- In `addons/counterstrikesharp/configs/`**`core.json`** set **FollowCS2ServerGuidelines** to **`false`** - In `addons/counterstrikesharp/configs/`**`core.json`** set **FollowCS2ServerGuidelines** to **`false`**
## Plugin Configuration ## Plugin Configuration
@@ -32,12 +30,11 @@ Unfinished, unoptimized and not fully functional ugly demo weapon paints plugin
<summary>Click to expand</summary> <summary>Click to expand</summary>
<code><pre>{ <code><pre>{
"Version": 4, // Don't touch "Version": 4, // Don't touch
"DatabaseHost": "", // MySQL host (required if GlobalShare = false) "DatabaseHost": "", // MySQL host
"DatabasePort": 3306, // MySQL port (required if GlobalShare = false) "DatabasePort": 3306, // MySQL port
"DatabaseUser": "", // MySQL username (required if GlobalShare = false) "DatabaseUser": "", // MySQL username
"DatabasePassword": "", // MySQL user password (required if GlobalShare = false) "DatabasePassword": "", // MySQL user password
"DatabaseName": "", // MySQL database name (required if GlobalShare = false) "DatabaseName": "", // MySQL database name
"GlobalShare": false, // Enable or disable GlobalShare, plugin can work without mysql credentials but with shared website at weaponpaints.fun
"CmdRefreshCooldownSeconds": 60, // Cooldown time in refreshing skins (!wp command) "CmdRefreshCooldownSeconds": 60, // Cooldown time in refreshing skins (!wp command)
"Prefix": "[WeaponPaints]", // Prefix every chat message "Prefix": "[WeaponPaints]", // Prefix every chat message
"Website": "example.com/skins", // Website used in WebsiteMessageCommand (!ws command) "Website": "example.com/skins", // Website used in WebsiteMessageCommand (!ws command)
@@ -74,7 +71,6 @@ Unfinished, unoptimized and not fully functional ugly demo weapon paints plugin
</details> </details>
## Web install ## Web install
Disregard if the config is **`GlobalShare = true`**
- Requires PHP >= 7.4 ***(Tested on php ver **`8.2.3`** and nginx webserver)*** - Requires PHP >= 7.4 ***(Tested on php ver **`8.2.3`** and nginx webserver)***
- **Before using website, make sure the plugin is correctly loaded in cs2 server!** Mysql tables are created by plugin not by website. - **Before using website, make sure the plugin is correctly loaded in cs2 server!** Mysql tables are created by plugin not by website.
- Copy website to web server ***(Folder `img` not needed)*** - Copy website to web server ***(Folder `img` not needed)***

View File

@@ -10,15 +10,16 @@ public class SchemaString<TSchemaClass> : NativeObject where TSchemaClass : Nati
internal SchemaString(TSchemaClass instance, string member) : base(Schema.GetSchemaValue<nint>(instance.Handle, typeof(TSchemaClass).Name!, member)) internal SchemaString(TSchemaClass instance, string member) : base(Schema.GetSchemaValue<nint>(instance.Handle, typeof(TSchemaClass).Name!, member))
{ } { }
internal unsafe void Set(string str) internal unsafe void Set(string str)
{ {
var bytes = Encoding.UTF8.GetBytes(str); var bytes = Encoding.UTF8.GetBytes(str);
var handle = Handle.ToInt64();
for (var i = 0; i < bytes.Length; i++) for (var i = 0; i < bytes.Length; i++)
{ {
Unsafe.Write((void*)(Handle.ToInt64() + i), bytes[i]); Unsafe.Write((void*)(handle + i), bytes[i]);
} }
Unsafe.Write((void*)(Handle.ToInt64() + bytes.Length), 0); Unsafe.Write((void*)(handle + bytes.Length), 0);
} }
} }

View File

@@ -43,26 +43,33 @@ namespace WeaponPaints
{ {
string[] createTableQueries = new[] string[] createTableQueries = new[]
{ {
@"CREATE TABLE IF NOT EXISTS `wp_player_skins` ( @"CREATE TABLE IF NOT EXISTS `wp_player_skins` (
`steamid` varchar(64) NOT NULL, `steamid` varchar(64) NOT NULL,
`weapon_defindex` int(6) NOT NULL, `weapon_defindex` int(6) NOT NULL,
`weapon_paint_id` int(6) NOT NULL, `weapon_paint_id` int(6) NOT NULL,
`weapon_wear` float NOT NULL DEFAULT 0.000001, `weapon_wear` float NOT NULL DEFAULT 0.000001,
`weapon_seed` int(16) NOT NULL DEFAULT 0 `weapon_seed` int(16) NOT NULL DEFAULT 0
) ENGINE=InnoDB", ) ENGINE=InnoDB",
@"CREATE TABLE IF NOT EXISTS `wp_player_knife` ( @"CREATE TABLE IF NOT EXISTS `wp_player_knife` (
`steamid` varchar(64) NOT NULL, `steamid` varchar(64) NOT NULL,
`knife` varchar(64) NOT NULL, `knife` varchar(64) NOT NULL,
UNIQUE (`steamid`) UNIQUE (`steamid`)
) ENGINE = InnoDB", ) ENGINE = InnoDB",
@"CREATE TABLE IF NOT EXISTS `wp_player_gloves` ( @"CREATE TABLE IF NOT EXISTS `wp_player_gloves` (
`steamid` varchar(64) NOT NULL, `steamid` varchar(64) NOT NULL,
`weapon_defindex` int(11) NOT NULL, `weapon_defindex` int(11) NOT NULL,
UNIQUE (`steamid`) UNIQUE (`steamid`)
) ENGINE=InnoDB" ) ENGINE=InnoDB"
}; };
/*string[] createTableQueries = new[]
foreach (var query in createTableQueries) {
@"CREATE TABLE IF NOT EXISTS `wp_players` (`steamid` BIGINT UNSIGNED NOT NULL, `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`steamid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
@"CREATE TABLE IF NOT EXISTS `wp_players_skins` (`steamid` BIGINT UNSIGNED NOT NULL, `team` SMALLINT UNSIGNED NOT NULL, `weapon` SMALLINT UNSIGNED NOT NULL, `paint` SMALLINT UNSIGNED NOT NULL, `wear` FLOAT NOT NULL DEFAULT 0.00001, `seed` SMALLINT UNSIGNED NOT NULL DEFAULT 0, `nametag` VARCHAR(20) DEFAULT NULL, `stattrack` INT UNSIGNED NOT NULL DEFAULT 0, `stattrack_enabled` SMALLINT NOT NULL DEFAULT 0, PRIMARY KEY (`steamid`,`weapon`,`team`), FOREIGN KEY (`steamid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
@"CREATE TABLE IF NOT EXISTS `wp_players_knife` (`steamid` BIGINT UNSIGNED NOT NULL, `knife_t` SMALLINT UNSIGNED NOT NULL, `knife_ct` SMALLINT UNSIGNED NOT NULL, PRIMARY KEY (`steamid`), FOREIGN KEY (`steamid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
@"CREATE TABLE IF NOT EXISTS `wp_players_music` (`steamid` BIGINT UNSIGNED NOT NULL, `music` SMALLINT UNSIGNED DEFAULT NULL, PRIMARY KEY (`steamid`), FOREIGN KEY (`steamid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
@"CREATE TABLE IF NOT EXISTS `wp_players_gloves` (`steamid` BIGINT UNSIGNED NOT NULL, `glove_t` SMALLINT UNSIGNED NOT NULL, `glove_ct` SMALLINT UNSIGNED NOT NULL, PRIMARY KEY (`steamid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"
};*/
foreach (var query in createTableQueries)
{ {
await connection.ExecuteAsync(query, transaction: transaction); await connection.ExecuteAsync(query, transaction: transaction);
} }
@@ -85,7 +92,7 @@ namespace WeaponPaints
{ {
if (player is null) return false; if (player is null) return false;
return (player is not null && player.IsValid && !player.IsBot && !player.IsHLTV return (player is not null && player.IsValid && !player.IsBot && !player.IsHLTV && player.UserId.HasValue
&& WeaponPaints.weaponSync != null && player.Connected == PlayerConnectedState.PlayerConnected && player.SteamID.ToString().Length == 17); && WeaponPaints.weaponSync != null && player.Connected == PlayerConnectedState.PlayerConnected && player.SteamID.ToString().Length == 17);
} }

View File

@@ -1 +1 @@
1.8d 1.9b

View File

@@ -13,12 +13,9 @@ namespace WeaponPaints
internal static void ChangeWeaponAttributes(CBasePlayerWeapon? weapon, CCSPlayerController? player, bool isKnife = false) internal static void ChangeWeaponAttributes(CBasePlayerWeapon? weapon, CCSPlayerController? player, bool isKnife = false)
{ {
if (player is null || weapon is null || !weapon.IsValid || !Utility.IsPlayerValid(player)) return; if (player is null || weapon is null || !weapon.IsValid || !Utility.IsPlayerValid(player)) return;
if (!gPlayerWeaponsInfo.TryGetValue(player.Slot, out _)) return;
int playerIndex = (int)player.Index; if (isKnife && !g_playersKnife.ContainsKey(player.Slot) || isKnife && g_playersKnife[player.Slot] == "weapon_knife") return;
if (!gPlayerWeaponsInfo.ContainsKey(playerIndex)) return;
if (isKnife && !g_playersKnife.ContainsKey(playerIndex) || isKnife && g_playersKnife[playerIndex] == "weapon_knife") return;
int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex; int weaponDefIndex = weapon.AttributeManager.Item.ItemDefinitionIndex;
@@ -30,7 +27,7 @@ namespace WeaponPaints
int fallbackPaintKit = weapon.FallbackPaintKit; int fallbackPaintKit = weapon.FallbackPaintKit;
if (_config.Additional.GiveRandomSkin && if (_config.Additional.GiveRandomSkin &&
!gPlayerWeaponsInfo[playerIndex].ContainsKey(weaponDefIndex)) !gPlayerWeaponsInfo[player.Slot].ContainsKey(weaponDefIndex))
{ {
// Random skins // Random skins
weapon.AttributeManager.Item.ItemID = 16384; weapon.AttributeManager.Item.ItemID = 16384;
@@ -87,8 +84,8 @@ namespace WeaponPaints
return; return;
} }
if (!gPlayerWeaponsInfo[playerIndex].ContainsKey(weaponDefIndex)) return; if (!gPlayerWeaponsInfo[player.Slot].ContainsKey(weaponDefIndex)) return;
WeaponInfo weaponInfo = gPlayerWeaponsInfo[playerIndex][weaponDefIndex]; WeaponInfo weaponInfo = gPlayerWeaponsInfo[player.Slot][weaponDefIndex];
//Log($"Apply on {weapon.DesignerName}({weapon.AttributeManager.Item.ItemDefinitionIndex}) paint {gPlayerWeaponPaints[steamId.SteamId64][weapon.AttributeManager.Item.ItemDefinitionIndex]} seed {gPlayerWeaponSeed[steamId.SteamId64][weapon.AttributeManager.Item.ItemDefinitionIndex]} wear {gPlayerWeaponWear[steamId.SteamId64][weapon.AttributeManager.Item.ItemDefinitionIndex]}"); //Log($"Apply on {weapon.DesignerName}({weapon.AttributeManager.Item.ItemDefinitionIndex}) paint {gPlayerWeaponPaints[steamId.SteamId64][weapon.AttributeManager.Item.ItemDefinitionIndex]} seed {gPlayerWeaponSeed[steamId.SteamId64][weapon.AttributeManager.Item.ItemDefinitionIndex]} wear {gPlayerWeaponWear[steamId.SteamId64][weapon.AttributeManager.Item.ItemDefinitionIndex]}");
weapon.AttributeManager.Item.ItemID = 16384; weapon.AttributeManager.Item.ItemID = 16384;
weapon.AttributeManager.Item.ItemIDLow = 16384 & 0xFFFFFFFF; weapon.AttributeManager.Item.ItemIDLow = 16384 & 0xFFFFFFFF;
@@ -144,38 +141,41 @@ namespace WeaponPaints
{ {
if (!_config.Additional.KnifeEnabled || player == null || !player.IsValid) return; if (!_config.Additional.KnifeEnabled || player == null || !player.IsValid) return;
string knifeToGive; WeaponPaints.Instance.AddTimer(1.0f, () =>
if (g_playersKnife.TryGetValue((int)player.Index, out var knife))
{ {
knifeToGive = knife; string knifeToGive;
} if (g_playersKnife.TryGetValue(player.Slot, out var knife))
else if (_config.Additional.GiveRandomKnife)
{
var knifeTypes = weaponList.Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet")).ToList();
if (knifeTypes.Count == 0)
{ {
Utility.Log("No valid knife types found."); knifeToGive = knife;
return; }
else if (_config.Additional.GiveRandomKnife)
{
var knifeTypes = weaponList.Where(pair => pair.Key.StartsWith("weapon_knife") || pair.Key.StartsWith("weapon_bayonet")).ToList();
if (knifeTypes.Count == 0)
{
Utility.Log("No valid knife types found.");
return;
}
Random random = new();
int index = random.Next(knifeTypes.Count);
knifeToGive = knifeTypes[index].Key;
}
else
{
knifeToGive = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife";
} }
Random random = new(); player.GiveNamedItem(knifeToGive);
int index = random.Next(knifeTypes.Count); });
knifeToGive = knifeTypes[index].Key;
}
else
{
knifeToGive = (CsTeam)player.TeamNum == CsTeam.Terrorist ? "weapon_knife_t" : "weapon_knife";
}
player.GiveNamedItem(knifeToGive);
} }
internal static bool PlayerHasKnife(CCSPlayerController? player) internal static bool PlayerHasKnife(CCSPlayerController? player)
{ {
if (!_config.Additional.KnifeEnabled) return false; if (!_config.Additional.KnifeEnabled) return false;
if (player == null || !player.IsValid || player.PlayerPawn == null || !player.PlayerPawn.IsValid || !player.PawnIsAlive) if (player == null || !player.IsValid || player.PlayerPawn == null || !player.PlayerPawn.IsValid)
{ {
return false; return false;
} }
@@ -214,9 +214,6 @@ namespace WeaponPaints
//Dictionary<string, (int, int)> weaponsWithAmmo = new Dictionary<string, (int, int)>(); //Dictionary<string, (int, int)> weaponsWithAmmo = new Dictionary<string, (int, int)>();
Dictionary<string, List<(int, int)>> weaponsWithAmmo = new Dictionary<string, List<(int, int)>>(); Dictionary<string, List<(int, int)>> weaponsWithAmmo = new Dictionary<string, List<(int, int)>>();
bool bomb = false;
bool defuser = player.PawnHasDefuser;
bool healthshot = false;
// Iterate through each weapon // Iterate through each weapon
foreach (var weapon in weapons) foreach (var weapon in weapons)
@@ -225,37 +222,29 @@ namespace WeaponPaints
!weapon.Value.IsValid || !weapon.Value.DesignerName.Contains("weapon_")) !weapon.Value.IsValid || !weapon.Value.DesignerName.Contains("weapon_"))
continue; continue;
CCSWeaponBaseGun gun = weapon.Value.As<CCSWeaponBaseGun>();
if (weapon.Value.Entity == null) continue;
if (weapon.Value.OwnerEntity == null) continue;
if (!weapon.Value.OwnerEntity.IsValid) continue;
if (gun == null) continue;
if (gun.Entity == null) continue;
if (!gun.IsValid) continue;
if (!gun.VisibleinPVS) continue;
try try
{ {
string? weaponByDefindex = null; string? weaponByDefindex = null;
CCSWeaponBaseVData? weaponData = weapon.Value.As<CCSWeaponBase>().VData; CCSWeaponBaseVData? weaponData = weapon.Value.As<CCSWeaponBase>().VData;
if (weaponData != null) if (weaponData == null) continue;
if (weaponData.GearSlot == gear_slot_t.GEAR_SLOT_RIFLE || weaponData.GearSlot == gear_slot_t.GEAR_SLOT_PISTOL)
{ {
if (weaponData.GearSlot == gear_slot_t.GEAR_SLOT_C4) if (!WeaponDefindex.TryGetValue(weapon.Value.AttributeManager.Item.ItemDefinitionIndex, out weaponByDefindex))
bomb = true; continue;
if (weaponData.Name.Equals("weapon_healtshot"))
healthshot = true;
if (weaponData.GearSlot == gear_slot_t.GEAR_SLOT_GRENADES || weaponData.GearSlot == gear_slot_t.GEAR_SLOT_UTILITY || weaponData.GearSlot == gear_slot_t.GEAR_SLOT_BOOSTS)
{
int clip1 = weapon.Value.Clip1;
int reservedAmmo = weapon.Value.ReserveAmmo[0];
weaponsWithAmmo.Add(weapon.Value.DesignerName, new List<(int, int)>() { (clip1, reservedAmmo) });
}
}
if (!weapon.Value.DesignerName.Contains("knife")
&&
!weapon.Value.DesignerName.Contains("bayonet")
&&
!weapon.Value.DesignerName.Contains("kukri")
&&
WeaponDefindex.TryGetValue(weapon.Value.AttributeManager.Item.ItemDefinitionIndex, out weaponByDefindex) && weaponByDefindex != null)
{
int clip1 = weapon.Value.Clip1; int clip1 = weapon.Value.Clip1;
int reservedAmmo = weapon.Value.ReserveAmmo[0]; int reservedAmmo = weapon.Value.ReserveAmmo[0];
@@ -266,6 +255,8 @@ namespace WeaponPaints
weaponsWithAmmo[weaponByDefindex].Add((clip1, reservedAmmo)); weaponsWithAmmo[weaponByDefindex].Add((clip1, reservedAmmo));
} }
//player.RemoveItemByDesignerName(weapon.Value.DesignerName, false);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -274,27 +265,36 @@ namespace WeaponPaints
} }
} }
player.RemoveWeapons(); for (int i = 1; i <= 3; i++)
AddTimer(0.3f, () => {
player.ExecuteClientCommand($"slot {i}");
player.ExecuteClientCommand($"slot {i}");
AddTimer(0.1f, () =>
{
var weapon = player.PlayerPawn.Value.WeaponServices.ActiveWeapon.Value;
CCSWeaponBaseGun? gun = weapon?.As<CCSWeaponBaseGun>();
if (gun == null || gun.VData == null) return;
if (gun?.VData?.GearSlot == gear_slot_t.GEAR_SLOT_C4 || gun?.VData?.GearSlot == gear_slot_t.GEAR_SLOT_GRENADES) return;
player.DropActiveWeapon();
AddTimer(0.22f, () =>
{
if (gun != null && gun.IsValid && gun.State == CSWeaponState_t.WEAPON_NOT_CARRIED)
{
weapon?.Remove();
}
});
});
}
AddTimer(1.2f, () =>
{ {
GiveKnifeToPlayer(player); GiveKnifeToPlayer(player);
if (bomb)
player.GiveNamedItem("weapon_c4");
if (defuser)
{
var itemServ = player.PlayerPawn?.Value?.ItemServices;
if (itemServ != null)
{
var items = new CCSPlayer_ItemServices(itemServ.Handle);
items.HasDefuser = true;
}
}
if (healthshot)
player.GiveNamedItem("weapon_healtshot");
foreach (var entry in weaponsWithAmmo) foreach (var entry in weaponsWithAmmo)
{ {
foreach (var ammo in entry.Value) foreach (var ammo in entry.Value)
@@ -322,10 +322,10 @@ namespace WeaponPaints
internal void RefreshKnife(CCSPlayerController? player) internal void RefreshKnife(CCSPlayerController? player)
{ {
if (player == null || !player.IsValid || player.PlayerPawn?.Value == null || (LifeState_t)player.LifeState != LifeState_t.LIFE_ALIVE) if (player == null || !player.IsValid || player.PlayerPawn?.Value == null)
return; return;
if (player.PlayerPawn.Value.WeaponServices == null || player.PlayerPawn.Value.ItemServices == null) if (player.PlayerPawn.Value.WeaponServices == null)
return; return;
var weapons = player.PlayerPawn.Value.WeaponServices.MyWeapons; var weapons = player.PlayerPawn.Value.WeaponServices.MyWeapons;
@@ -341,8 +341,10 @@ namespace WeaponPaints
if (weapon.Value.DesignerName.Contains("knife") || weaponData?.GearSlot == gear_slot_t.GEAR_SLOT_KNIFE) if (weapon.Value.DesignerName.Contains("knife") || weaponData?.GearSlot == gear_slot_t.GEAR_SLOT_KNIFE)
{ {
RefreshWeapons(player); player.ExecuteClientCommand("slot 3");
break;
weapon.Value.Remove();
GiveKnifeToPlayer(player);
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -373,16 +375,19 @@ namespace WeaponPaints
{ {
try try
{ {
if (!player.IsValid) if (player == null || !player.IsValid)
return; return;
if (g_playersGlove.TryGetValue(player.Index, out var gloveInfo) && gloveInfo != 0) if (pawn == null || !pawn.IsValid || pawn.LifeState != (byte)LifeState_t.LIFE_ALIVE)
return;
if (g_playersGlove.TryGetValue(player.Slot, out var gloveInfo) && gloveInfo != 0)
{ {
CCSPlayerPawn? pawn = player.PlayerPawn.Value; CCSPlayerPawn? pawn = player.PlayerPawn.Value;
if (pawn == null || !pawn.IsValid || pawn.LifeState != (byte)LifeState_t.LIFE_ALIVE) if (pawn == null || !pawn.IsValid || pawn.LifeState != (byte)LifeState_t.LIFE_ALIVE)
return; return;
WeaponInfo weaponInfo = gPlayerWeaponsInfo[(int)player.Index][gloveInfo]; WeaponInfo weaponInfo = gPlayerWeaponsInfo[player.Slot][gloveInfo];
CEconItemView item = pawn.EconGloves; CEconItemView item = pawn.EconGloves;
item.ItemDefinitionIndex = gloveInfo; item.ItemDefinitionIndex = gloveInfo;

View File

@@ -1,9 +1,18 @@
namespace WeaponPaints namespace WeaponPaints
{ {
public class WeaponInfo public class WeaponInfo
{ {
public int Paint { get; set; } public int Paint { get; set; }
public int Seed { get; set; } = 0; public int Seed { get; set; }
public float Wear { get; set; } = 0f; public float Wear { get; set; }
}
public WeaponInfo() : this(0, 0, 0f) { }
public WeaponInfo(int paint, int seed, float wear)
{
Paint = paint;
Seed = seed;
Wear = wear;
}
}
} }

View File

@@ -1,7 +1,6 @@
using CounterStrikeSharp.API; using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes; using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Modules.Cvars;
using CounterStrikeSharp.API.Modules.Memory.DynamicFunctions; using CounterStrikeSharp.API.Modules.Memory.DynamicFunctions;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -15,7 +14,8 @@ namespace WeaponPaints;
public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig> public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig>
{ {
internal static WeaponPaints Instance { get; private set; } = new(); internal static WeaponPaints Instance { get; private set; } = new();
internal static readonly Dictionary<string, string> weaponList = new() internal static readonly int[] newPaints = { 1171, 1170, 1169, 1164, 1162, 1161, 1159, 1175, 1174, 1167, 1165, 1168, 1163, 1160, 1166, 1173 };
internal static readonly Dictionary<string, string> weaponList = new()
{ {
{"weapon_deagle", "Desert Eagle"}, {"weapon_deagle", "Desert Eagle"},
{"weapon_elite", "Dual Berettas"}, {"weapon_elite", "Dual Berettas"},
@@ -79,7 +79,7 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
internal static IStringLocalizer? _localizer; internal static IStringLocalizer? _localizer;
internal static Dictionary<int, int> g_knifePickupCount = new Dictionary<int, int>(); internal static Dictionary<int, int> g_knifePickupCount = new Dictionary<int, int>();
internal static ConcurrentDictionary<int, string> g_playersKnife = new ConcurrentDictionary<int, string>(); internal static ConcurrentDictionary<int, string> g_playersKnife = new ConcurrentDictionary<int, string>();
internal static ConcurrentDictionary<uint, ushort> g_playersGlove = new ConcurrentDictionary<uint, ushort>(); internal static ConcurrentDictionary<int, ushort> g_playersGlove = new ConcurrentDictionary<int, ushort>();
internal static ConcurrentDictionary<int, ConcurrentDictionary<int, WeaponInfo>> gPlayerWeaponsInfo = new ConcurrentDictionary<int, ConcurrentDictionary<int, WeaponInfo>>(); internal static ConcurrentDictionary<int, ConcurrentDictionary<int, WeaponInfo>> gPlayerWeaponsInfo = new ConcurrentDictionary<int, ConcurrentDictionary<int, WeaponInfo>>();
internal static List<JObject> skinsList = new List<JObject>(); internal static List<JObject> skinsList = new List<JObject>();
internal static List<JObject> glovesList = new List<JObject>(); internal static List<JObject> glovesList = new List<JObject>();
@@ -87,8 +87,6 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
public static bool g_bCommandsAllowed = true; public static bool g_bCommandsAllowed = true;
internal Dictionary<int, string> PlayerWeaponImage = new(); internal Dictionary<int, string> PlayerWeaponImage = new();
internal Uri GlobalShareApi = new("https://weaponpaints.fun/api.php");
internal int GlobalShareServerId = 0;
internal static Dictionary<int, DateTime> commandsCooldown = new Dictionary<int, DateTime>(); internal static Dictionary<int, DateTime> commandsCooldown = new Dictionary<int, DateTime>();
internal static Database? _database; internal static Database? _database;
@@ -153,12 +151,12 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
{ 525, "weapon_knife_skeleton" }, { 525, "weapon_knife_skeleton" },
{ 526, "weapon_knife_kukri" } { 526, "weapon_knife_kukri" }
}; };
public static MemoryFunctionVoid<IntPtr, string, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr> GiveNamedItem2 = new(@"\x55\x48\x89\xE5\x41\x57\x41\x56\x41\x55\x41\x54\x53\x48\x83\xEC\x18\x48\x89\x7D\xC8\x48\x85\xF6\x74");
public WeaponPaintsConfig Config { get; set; } = new(); public WeaponPaintsConfig Config { get; set; } = new();
public override string ModuleAuthor => "Nereziel & daffyy"; public override string ModuleAuthor => "Nereziel & daffyy";
public override string ModuleDescription => "Skin, gloves and knife selector, standalone and web-based"; public override string ModuleDescription => "Skin, gloves and knife selector, standalone and web-based";
public override string ModuleName => "WeaponPaints"; public override string ModuleName => "WeaponPaints";
public override string ModuleVersion => "1.8d"; public override string ModuleVersion => "1.9b";
public static WeaponPaintsConfig GetWeaponPaintsConfig() public static WeaponPaintsConfig GetWeaponPaintsConfig()
{ {
@@ -179,25 +177,30 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
player.IsHLTV || player.Connected != PlayerConnectedState.PlayerConnected) player.IsHLTV || player.Connected != PlayerConnectedState.PlayerConnected)
continue; continue;
g_knifePickupCount[(int)player.Index] = 0; g_knifePickupCount[(int)player.Slot] = 0;
gPlayerWeaponsInfo.TryRemove((int)player.Index, out _); gPlayerWeaponsInfo.TryRemove((int)player.Slot, out _);
g_playersKnife.TryRemove((int)player.Index, out _); g_playersKnife.TryRemove((int)player.Slot, out _);
PlayerInfo playerInfo = new PlayerInfo PlayerInfo playerInfo = new PlayerInfo(
{ (int)player.Slot,
UserId = player.UserId, player.Slot,
Index = (int)player.Index, player.UserId,
SteamId = player?.SteamID.ToString(), player?.SteamID.ToString(),
Name = player?.PlayerName, player?.PlayerName,
IpAddress = player?.IpAddress?.Split(":")[0] player?.IpAddress?.Split(":")[0]);
};
if (Config.Additional.SkinEnabled) if (Config.Additional.SkinEnabled)
_ = weaponSync.GetWeaponPaintsFromDatabase(playerInfo); {
Task.Run(() => weaponSync.GetWeaponPaintsFromDatabase(playerInfo));
}
if (Config.Additional.KnifeEnabled) if (Config.Additional.KnifeEnabled)
_ = weaponSync.GetKnifeFromDatabase(playerInfo); {
Task.Run(() => weaponSync.GetKnifeFromDatabase(playerInfo));
}
if (Config.Additional.GloveEnabled) if (Config.Additional.GloveEnabled)
_ = weaponSync.GetGloveFromDatabase(playerInfo); {
Task.Run(() => weaponSync.GetGloveFromDatabase(playerInfo));
}
} }
} }
@@ -214,32 +217,37 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
RegisterListeners(); RegisterListeners();
RegisterCommands(); RegisterCommands();
} }
public static void PlayerGiveNamedItem(CCSPlayerController player, string item)
{
if (!player.PlayerPawn.IsValid) return;
if (player.PlayerPawn.Value == null) return;
if (!player.PlayerPawn.Value.IsValid) return;
if (player.PlayerPawn.Value.ItemServices == null) return;
public void OnConfigParsed(WeaponPaintsConfig config) GiveNamedItem2.Invoke(player.PlayerPawn.Value.ItemServices.Handle, item, 0, 0, 0, 0, 0, 0);
}
public void OnConfigParsed(WeaponPaintsConfig config)
{ {
if (!config.GlobalShare) if (config.DatabaseHost.Length < 1 || config.DatabaseName.Length < 1 || config.DatabaseUser.Length < 1)
{ {
if (config.DatabaseHost.Length < 1 || config.DatabaseName.Length < 1 || config.DatabaseUser.Length < 1) Logger.LogError("You need to setup Database credentials in config!");
{ throw new Exception("[WeaponPaints] You need to setup Database credentials in config!");
Logger.LogError("You need to setup Database credentials in config!");
throw new Exception("[WeaponPaints] You need to setup Database credentials in config!");
}
var builder = new MySqlConnectionStringBuilder
{
Server = config.DatabaseHost,
UserID = config.DatabaseUser,
Password = config.DatabasePassword,
Database = config.DatabaseName,
Port = (uint)config.DatabasePort,
Pooling = true
};
_database = new(builder.ConnectionString);
_ = Utility.CheckDatabaseTables();
} }
var builder = new MySqlConnectionStringBuilder
{
Server = config.DatabaseHost,
UserID = config.DatabaseUser,
Password = config.DatabasePassword,
Database = config.DatabaseName,
Port = (uint)config.DatabasePort,
Pooling = true
};
_database = new(builder.ConnectionString);
_ = Utility.CheckDatabaseTables();
Config = config; Config = config;
_config = config; _config = config;
_localizer = Localizer; _localizer = Localizer;
@@ -253,41 +261,4 @@ public partial class WeaponPaints : BasePlugin, IPluginConfig<WeaponPaintsConfig
{ {
base.Unload(hotReload); base.Unload(hotReload);
} }
private void GlobalShareConnect()
{
if (!Config.GlobalShare) return;
var values = new Dictionary<string, string>
{
{ "server_address", $"{ConVar.Find("ip")!.StringValue}:{ConVar.Find("hostport")!.GetPrimitiveValue<int>().ToString()}" },
{ "server_hostname", ConVar.Find("hostname")!.StringValue }
};
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = GlobalShareApi;
var formContent = new FormUrlEncodedContent(values);
Task<HttpResponseMessage> responseTask = httpClient.PostAsync("", formContent);
responseTask.Wait();
HttpResponseMessage response = responseTask.Result;
if (response.IsSuccessStatusCode)
{
Task<string> responseBodyTask = response.Content.ReadAsStringAsync();
responseBodyTask.Wait();
string responseBody = responseBodyTask.Result;
GlobalShareServerId = int.Parse(responseBody);
}
else
{
Logger.LogError("Unable to retrieve serverid from GlobalShare!");
throw new Exception("[WeaponPaints] Unable to retrieve serverid from GlobalShare!");
}
}
Logger.LogInformation("GlobalShare ONLINE!");
Console.WriteLine("[WeaponPaints] GlobalShare ONLINE");
}
} }

View File

@@ -9,7 +9,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CounterStrikeSharp.API" Version="1.0.168" /> <PackageReference Include="CounterStrikeSharp.API" Version="1.0.172" />
<PackageReference Include="Dapper" Version="2.1.28" /> <PackageReference Include="Dapper" Version="2.1.28" />
<PackageReference Include="MySqlConnector" Version="2.3.5" /> <PackageReference Include="MySqlConnector" Version="2.3.5" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />

View File

@@ -1,5 +1,4 @@
using Dapper; using Dapper;
using Newtonsoft.Json.Linq;
using System.Collections.Concurrent; using System.Collections.Concurrent;
namespace WeaponPaints namespace WeaponPaints
@@ -8,68 +7,25 @@ namespace WeaponPaints
{ {
private readonly WeaponPaintsConfig _config; private readonly WeaponPaintsConfig _config;
private readonly Database _database; private readonly Database _database;
private readonly Uri _globalShareApi;
private readonly int _globalShareServerId;
internal WeaponSynchronization(Database database, WeaponPaintsConfig config, Uri globalShareApi, int globalShareServerId) internal WeaponSynchronization(Database database, WeaponPaintsConfig config)
{ {
_database = database; _database = database;
_config = config; _config = config;
_globalShareApi = globalShareApi;
_globalShareServerId = globalShareServerId;
} }
internal async Task GetKnifeFromDatabase(PlayerInfo player) internal async Task GetKnifeFromDatabase(PlayerInfo player)
{ {
if (!_config.Additional.KnifeEnabled) return; if (!_config.Additional.KnifeEnabled) return;
if (player.SteamId == null || player.Index == 0) return;
try try
{ {
if (_config.GlobalShare)
{
var values = new Dictionary<string, string>
{
{ "server_id", _globalShareServerId.ToString() },
{ "steamid", player.SteamId },
{ "knife", "1" }
};
UriBuilder builder = new UriBuilder(_globalShareApi);
builder.Query = string.Join("&", values.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}"));
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = _globalShareApi;
var formContent = new FormUrlEncodedContent(values);
HttpResponseMessage response = await httpClient.GetAsync(builder.Uri);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(result))
{
WeaponPaints.g_playersKnife[player.Index] = result;
}
else
{
return;
}
}
else
{
return;
}
}
return;
}
await using var connection = await _database.GetConnectionAsync(); await using var connection = await _database.GetConnectionAsync();
string query = "SELECT `knife` FROM `wp_player_knife` WHERE `steamid` = @steamid"; string query = "SELECT `knife` FROM `wp_player_knife` WHERE `steamid` = @steamid";
string? playerKnife = await connection.QueryFirstOrDefaultAsync<string>(query, new { steamid = player.SteamId }); string? playerKnife = await connection.QueryFirstOrDefaultAsync<string>(query, new { steamid = player.SteamId });
if (!string.IsNullOrEmpty(playerKnife)) if (!string.IsNullOrEmpty(playerKnife))
{ {
WeaponPaints.g_playersKnife[player.Index] = playerKnife; WeaponPaints.g_playersKnife[player.Slot] = playerKnife;
} }
} }
catch (Exception e) catch (Exception e)
@@ -82,6 +38,7 @@ namespace WeaponPaints
internal async Task GetGloveFromDatabase(PlayerInfo player) internal async Task GetGloveFromDatabase(PlayerInfo player)
{ {
if (!_config.Additional.GloveEnabled) return; if (!_config.Additional.GloveEnabled) return;
try try
{ {
// Ensure proper disposal of resources using "using" statement // Ensure proper disposal of resources using "using" statement
@@ -97,7 +54,7 @@ namespace WeaponPaints
if (gloveData != null) if (gloveData != null)
{ {
// Update g_playersGlove dictionary with glove data // Update g_playersGlove dictionary with glove data
WeaponPaints.g_playersGlove[(uint)player.Index] = gloveData.Value; WeaponPaints.g_playersGlove[player.Slot] = gloveData.Value;
} }
} }
catch (Exception e) catch (Exception e)
@@ -109,96 +66,47 @@ namespace WeaponPaints
internal async Task GetWeaponPaintsFromDatabase(PlayerInfo player) internal async Task GetWeaponPaintsFromDatabase(PlayerInfo player)
{ {
if (!_config.Additional.SkinEnabled) return; if (!_config.Additional.SkinEnabled || player == null || player.SteamId == null) return;
if (!WeaponPaints.gPlayerWeaponsInfo.TryGetValue(player.Index, out _))
{
WeaponPaints.gPlayerWeaponsInfo[player.Index] = new ConcurrentDictionary<int, WeaponInfo>();
}
try try
{ {
if (_config.GlobalShare)
{
var values = new Dictionary<string, string>
{
{ "server_id", _globalShareServerId.ToString() },
{ "steamid", player.SteamId },
{ "skins", "1" }
};
UriBuilder builder = new UriBuilder(_globalShareApi);
builder.Query = string.Join("&", values.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value)}"));
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = _globalShareApi;
var formContent = new FormUrlEncodedContent(values);
HttpResponseMessage response = await httpClient.GetAsync(builder.Uri);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
JArray jsonArray = JArray.Parse(responseBody);
if (jsonArray != null && jsonArray.Count > 0)
{
foreach (var weapon in jsonArray)
{
int? weaponDefIndex = weapon["weapon_defindex"]?.Value<int>();
int? weaponPaintId = weapon["weapon_paint_id"]?.Value<int>();
float? weaponWear = weapon["weapon_wear"]?.Value<float>();
int? weaponSeed = weapon["weapon_seed"]?.Value<int>();
if (weaponDefIndex != null && weaponPaintId != null && weaponWear != null && weaponSeed != null)
{
WeaponInfo weaponInfo = new WeaponInfo
{
Paint = weaponPaintId.Value,
Seed = weaponSeed.Value,
Wear = weaponWear.Value
};
WeaponPaints.gPlayerWeaponsInfo[player.Index][weaponDefIndex.Value] = weaponInfo;
}
}
}
return;
}
else
{
return;
}
}
}
await using var connection = await _database.GetConnectionAsync(); await using var connection = await _database.GetConnectionAsync();
string query = "SELECT * FROM `wp_player_skins` WHERE `steamid` = @steamid"; string query = "SELECT `weapon_defindex`, `weapon_paint_id`, `weapon_wear`, `weapon_seed` FROM `wp_player_skins` WHERE `steamid` = @steamid";
var playerSkins = await connection.QueryAsync<dynamic>(query, new { steamid = player.SteamId });
var playerSkins = await connection.QueryAsync<dynamic>(query, new { steamid = player.SteamId });
if (playerSkins == null) return;
var weaponInfos = new ConcurrentDictionary<int, WeaponInfo>();
foreach (var row in playerSkins) foreach (var row in playerSkins)
{ {
int? weaponDefIndex = row.weapon_defindex; int weaponDefIndex = row?.weapon_defindex ?? 0;
int? weaponPaintId = row.weapon_paint_id; int weaponPaintId = row?.weapon_paint_id ?? 0;
float? weaponWear = row.weapon_wear; float weaponWear = row?.weapon_wear ?? 0f;
int? weaponSeed = row.weapon_seed; int weaponSeed = row?.weapon_seed ?? 0;
WeaponInfo weaponInfo = new WeaponInfo WeaponInfo weaponInfo = new WeaponInfo
{ {
Paint = weaponPaintId.HasValue ? weaponPaintId.Value : 0, Paint = weaponPaintId,
Seed = weaponSeed.HasValue ? weaponSeed.Value : 0, Seed = weaponSeed,
Wear = weaponWear.HasValue ? weaponWear.Value : 0f Wear = weaponWear
}; };
WeaponPaints.gPlayerWeaponsInfo[player.Index][weaponDefIndex.GetValueOrDefault()] = weaponInfo; weaponInfos[weaponDefIndex] = weaponInfo;
} }
WeaponPaints.gPlayerWeaponsInfo[player.Slot] = weaponInfos;
} }
catch (Exception e) catch (Exception e)
{ {
Utility.Log(e.Message); Utility.Log($"Database error occurred: {e.Message}");
return;
} }
} }
internal async Task SyncKnifeToDatabase(PlayerInfo player, string knife) internal async Task SyncKnifeToDatabase(PlayerInfo player, string knife)
{ {
if (!_config.Additional.KnifeEnabled) return; if (!_config.Additional.KnifeEnabled || player == null || string.IsNullOrEmpty(player.SteamId) || string.IsNullOrEmpty(knife)) return;
try try
{ {
@@ -208,13 +116,14 @@ namespace WeaponPaints
} }
catch (Exception e) catch (Exception e)
{ {
Utility.Log(e.Message); Utility.Log($"Error syncing knife to database: {e.Message}");
} }
} }
internal async Task SyncGloveToDatabase(PlayerInfo player, ushort defindex)
internal async Task SyncGloveToDatabase(PlayerInfo player, int defindex)
{ {
if (!_config.Additional.GloveEnabled) return; if (!_config.Additional.GloveEnabled || player == null || string.IsNullOrEmpty(player.SteamId)) return;
try try
{ {
@@ -224,37 +133,48 @@ namespace WeaponPaints
} }
catch (Exception e) catch (Exception e)
{ {
Utility.Log(e.Message); Utility.Log($"Error syncing glove to database: {e.Message}");
} }
} }
internal async Task SyncWeaponPaintsToDatabase(PlayerInfo player) internal async Task SyncWeaponPaintsToDatabase(PlayerInfo player)
{ {
if (player == null || player.Index <= 0 || player.SteamId == null) return; if (player == null || string.IsNullOrEmpty(player.SteamId) || !WeaponPaints.gPlayerWeaponsInfo.TryGetValue(player.Slot, out var weaponsInfo))
await using var connection = await _database.GetConnectionAsync();
if (!WeaponPaints.gPlayerWeaponsInfo.ContainsKey(player.Index))
return; return;
foreach (var weaponInfoPair in WeaponPaints.gPlayerWeaponsInfo[player.Index]) try
{ {
int weaponDefIndex = weaponInfoPair.Key; await using var connection = await _database.GetConnectionAsync();
WeaponInfo weaponInfo = weaponInfoPair.Value;
int paintId = weaponInfo.Paint; foreach (var weaponInfoPair in weaponsInfo)
float wear = weaponInfo.Wear; {
int seed = weaponInfo.Seed; int weaponDefIndex = weaponInfoPair.Key;
WeaponInfo weaponInfo = weaponInfoPair.Value;
string updateSql = "INSERT INTO `wp_player_skins` (`steamid`, `weapon_defindex`, " + int paintId = weaponInfo.Paint;
"`weapon_paint_id`, `weapon_wear`, `weapon_seed`) " + float wear = weaponInfo.Wear;
"VALUES (@steamid, @weaponDefIndex, @paintId, @wear, @seed) " + int seed = weaponInfo.Seed;
"ON DUPLICATE KEY UPDATE `weapon_paint_id` = @paintId, " +
"`weapon_wear` = @wear, `weapon_seed` = @seed";
var updateParams = new { steamid = player.SteamId, weaponDefIndex, paintId, wear, seed }; string query = "INSERT INTO `wp_player_skins` (`steamid`, `weapon_defindex`, `weapon_paint_id`, `weapon_wear`, `weapon_seed`) " +
await connection.ExecuteAsync(updateSql, updateParams); "VALUES (@steamid, @weaponDefIndex, @paintId, @wear, @seed) " +
"ON DUPLICATE KEY UPDATE `weapon_paint_id` = @paintId, `weapon_wear` = @wear, `weapon_seed` = @seed";
var parameters = new DynamicParameters();
parameters.Add("@steamid", player.SteamId);
parameters.Add("@weaponDefIndex", weaponDefIndex);
parameters.Add("@paintId", paintId);
parameters.Add("@wear", wear);
parameters.Add("@seed", seed);
await connection.ExecuteAsync(query, parameters);
}
}
catch (Exception e)
{
Utility.Log($"Error syncing weapon paints to database: {e.Message}");
} }
} }
} }
} }

View File

@@ -7,7 +7,7 @@
"wp_command_cooldown": "{lightred}Nie możesz teraz odświeżyć skórek broni", "wp_command_cooldown": "{lightred}Nie możesz teraz odświeżyć skórek broni",
"wp_command_refresh_done": "{lime}Odświeżanie skórek broni", "wp_command_refresh_done": "{lime}Odświeżanie skórek broni",
"wp_knife_menu_select": "Wybrałeś {lime}{0}{default} jako swój nóż", "wp_knife_menu_select": "Wybrałeś {lime}{0}{default} jako swój nóż",
"wp_knife_menu_kill": "", "wp_knife_menu_kill": "{lime}Wybrane skiny będą ustawione dopiero po ponownym wejściu na serwer lub wpisaniu komendy {orange}!kill",
"wp_knife_menu_title": "Menu Noży", "wp_knife_menu_title": "Menu Noży",
"wp_glove_menu_select": "Wybrałeś {lime}{0}{default} jako swoje rękawiczki", "wp_glove_menu_select": "Wybrałeś {lime}{0}{default} jako swoje rękawiczki",
"wp_glove_menu_title": "Menu Rękawiczek", "wp_glove_menu_title": "Menu Rękawiczek",