mirror of
https://github.com/Jackzmc/sourcemod-plugins.git
synced 2025-05-05 20:53:20 +00:00
Add includes
This commit is contained in:
parent
144e8fd7fc
commit
74f37a1454
34 changed files with 14547 additions and 8 deletions
13
.gitignore
vendored
13
.gitignore
vendored
|
@ -1,15 +1,12 @@
|
|||
**/
|
||||
!data/
|
||||
!data/**
|
||||
!gamedata/
|
||||
!plugins
|
||||
!scripting
|
||||
!scripting/include
|
||||
sm_*
|
||||
.*/
|
||||
scripting_ext/
|
||||
!scripting/include/guesswho/*
|
||||
!scripting/include/feedthetrolls
|
||||
!scripting/include/hideandseek
|
||||
!scripting/include/guessswho/*
|
||||
!scripting/hideandseek.sp
|
||||
!scripting/guessswho.sp
|
||||
!scripting/include/guessswho
|
||||
.push.settings.jsonc*
|
||||
template.config.js
|
||||
scripting/sm_give.sp
|
||||
|
|
382
scripting/include/guesswho/gwcmds.inc
Normal file
382
scripting/include/guesswho/gwcmds.inc
Normal file
|
@ -0,0 +1,382 @@
|
|||
#define GAMEMODE_PROP_NAME "gwprop"
|
||||
#define GAMEMODE_BLOCKER_NAME "gwblocker"
|
||||
|
||||
|
||||
|
||||
public Action Command_GuessWho(int client, int args) {
|
||||
if(!isEnabled) ReplyToCommand(client, "Warn: Guess Who is not active");
|
||||
if(args > 0) {
|
||||
char subcmd[32];
|
||||
GetCmdArg(1, subcmd, sizeof(subcmd));
|
||||
if(StrEqual(subcmd, "points")) {
|
||||
GetCmdArg(2, subcmd, sizeof(subcmd));
|
||||
if(StrEqual(subcmd, "clear")) {
|
||||
movePoints.Clear();
|
||||
ReplyToCommand(client, "Movement locations have been cleared");
|
||||
} else if(StrEqual(subcmd, "save")) {
|
||||
if(args == 3) {
|
||||
GetCmdArg(2, subcmd, sizeof(subcmd));
|
||||
} else {
|
||||
subcmd = currentSet;
|
||||
}
|
||||
if(SaveMapData(currentMap, subcmd)) {
|
||||
ReplyToCommand(client, "Saved movement data for %s/%s", currentMap, subcmd);
|
||||
} else {
|
||||
ReplyToCommand(client, "Failed to save map data");
|
||||
}
|
||||
} else if(StrEqual(subcmd, "load")) {
|
||||
if(LoadMapData(currentMap, currentSet)) {
|
||||
ReplyToCommand(client, "Loaded movement data for %s/%s", currentMap, currentSet);
|
||||
} else {
|
||||
ReplyToCommand(client, "Failed to load map data");
|
||||
}
|
||||
} else if(StrEqual(subcmd, "record")) {
|
||||
float recordInterval = 0.5;
|
||||
if(args == 3) {
|
||||
GetCmdArg(3, subcmd, sizeof(subcmd));
|
||||
recordInterval = StringToFloat(subcmd);
|
||||
if(recordInterval <= 0.0) {
|
||||
ReplyToCommand(client, "Invalid record interval (%f)", recordInterval);
|
||||
return Plugin_Handled;
|
||||
}
|
||||
}
|
||||
|
||||
if(recordTimer != null) {
|
||||
ReplyToCommand(client, "Stopped recording. %d ready to save. \"/guesswho points save\" to save", movePoints.Length);
|
||||
delete recordTimer;
|
||||
} else {
|
||||
// Assume recorder doesn't leav
|
||||
recordTimer = CreateTimer(recordInterval, Timer_RecordPoints, client, TIMER_FLAG_NO_MAPCHANGE | TIMER_REPEAT);
|
||||
ReplyToCommand(client, "Recording movement points every %.2f seconds. Type command again to stop", recordInterval);
|
||||
}
|
||||
} else {
|
||||
ReplyToCommand(client, "Unknown option. Valid options: 'clear', 'save', 'load'");
|
||||
}
|
||||
} else if(StrEqual(subcmd, "r") || StrEqual(subcmd, "reload", false)) {
|
||||
GetCurrentMap(currentMap, sizeof(currentMap));
|
||||
char arg[4];
|
||||
GetCmdArg(2, arg, sizeof(arg));
|
||||
if(ReloadMapDB()) {
|
||||
if(!LoadConfigForMap(currentMap)) {
|
||||
ReplyToCommand(client, "Warn: Map has no config file");
|
||||
}
|
||||
Game.Cleanup(true);
|
||||
if(arg[0] == 'f') {
|
||||
InitGamemode();
|
||||
}
|
||||
SetupEntities(isNavBlockersEnabled, isPropsEnabled, isPortalsEnabled);
|
||||
ReplyToCommand(client, "Reloaded map from config");
|
||||
} else {
|
||||
ReplyToCommand(client, "Error occurred while reloading map file");
|
||||
}
|
||||
} else if(StrEqual(subcmd, "set", false)) {
|
||||
char set[16];
|
||||
if(args == 1) {
|
||||
ReplyToCommand(client, "Current Map Set: \"%s\" (Specify with /gw set <set>)", currentSet);
|
||||
if(validSets.Length == 0) ReplyToCommand(client, "Available Sets: (no map config found)");
|
||||
else {
|
||||
ReplyToCommand(client, "Available Sets: ");
|
||||
for(int i = 0; i < validSets.Length; i++) {
|
||||
validSets.GetString(i, set, sizeof(set));
|
||||
ReplyToCommand(client, "%d. %s", i + 1, set);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
GetCmdArg(2, currentSet, sizeof(currentSet));
|
||||
for(int i = 0; i < validSets.Length; i++) {
|
||||
validSets.GetString(i, set, sizeof(set));
|
||||
if(StrEqual(set, currentSet)) {
|
||||
if(!LoadConfigForMap(currentMap)) {
|
||||
ReplyToCommand(client, "Warn: No config entry for %s", currentMap);
|
||||
}
|
||||
if(!LoadMapData(currentMap, currentSet)) {
|
||||
ReplyToCommand(client, "Warn: No map data found for %s/%s", currentMap, currentSet);
|
||||
} else if(movePoints.Length == 0) {
|
||||
ReplyToCommand(client, "Warn: %s/%s has 0 saved movement locations", currentMap, currentSet);
|
||||
}
|
||||
Game.Cleanup();
|
||||
SetupEntities(isNavBlockersEnabled, isPropsEnabled, isPortalsEnabled);
|
||||
PrintToChatAll("[GuessWho] Map set has been changed to \"%s\"", currentSet);
|
||||
return Plugin_Handled;
|
||||
}
|
||||
}
|
||||
ReplyToCommand(client, "Warning: Set was not found, use /gw r to force load.");
|
||||
}
|
||||
} else if(StrEqual(subcmd, "toggle")) {
|
||||
char type[32];
|
||||
GetCmdArg(2, type, sizeof(type));
|
||||
bool doAll = StrEqual(type, "all");
|
||||
bool isUnknown = true;
|
||||
|
||||
if(doAll || StrEqual(type, "blockers", false)) {
|
||||
if(isNavBlockersEnabled) {
|
||||
EntFire(GAMEMODE_BLOCKER_NAME, "Disable");
|
||||
ReplyToCommand(client, "Disabled all custom gamemode blockers");
|
||||
} else {
|
||||
EntFire(GAMEMODE_BLOCKER_NAME, "Enable");
|
||||
ReplyToCommand(client, "Enabled all custom gamemode blockers");
|
||||
}
|
||||
isNavBlockersEnabled = !isNavBlockersEnabled;
|
||||
isUnknown = false;
|
||||
}
|
||||
if(doAll || StrEqual(type, "props", false)) {
|
||||
if(isPropsEnabled) {
|
||||
EntFire(GAMEMODE_PROP_NAME, "Disable");
|
||||
EntFire(GAMEMODE_PROP_NAME, "DisableCollision");
|
||||
ReplyToCommand(client, "Disabled all custom gamemode props");
|
||||
} else {
|
||||
EntFire(GAMEMODE_PROP_NAME, "Enable");
|
||||
EntFire(GAMEMODE_PROP_NAME, "EnableCollision");
|
||||
ReplyToCommand(client, "Enabled all custom gamemode props");
|
||||
}
|
||||
isPropsEnabled = !isPropsEnabled;
|
||||
isUnknown = false;
|
||||
}
|
||||
if(isUnknown) ReplyToCommand(client, "Specify the type to affect: 'blockers', 'props', 'portals', or 'all'");
|
||||
} else if(StrEqual(subcmd, "clear", false)) {
|
||||
static char arg[16];
|
||||
GetCmdArg(2, arg, sizeof(arg));
|
||||
if(StrEqual(arg, "all")) {
|
||||
Game.Cleanup();
|
||||
ReplyToCommand(client, "Cleaned up everything.");
|
||||
} else if(StrEqual(arg, "props")) {
|
||||
EntFire(GAMEMODE_PROP_NAME, "kill");
|
||||
ReplyToCommand(client, "Removed all custom gamemode props");
|
||||
} else if(StrEqual(arg, "blockers")) {
|
||||
EntFire(GAMEMODE_BLOCKER_NAME, "kill");
|
||||
ReplyToCommand(client, "Removed all custom gamemode blockers");
|
||||
} else ReplyToCommand(client, "Specify the type to affect: 'blockers', 'props', 'portals', or 'all'");
|
||||
} else if(StrEqual(subcmd, "settime")) {
|
||||
int prev = Game.MapTime();
|
||||
static char arg[16];
|
||||
GetCmdArg(2, arg, sizeof(arg));
|
||||
int time = StringToInt(arg);
|
||||
mapConfig.mapTime = time;
|
||||
Game.MapTime = time;
|
||||
ReplyToCommand(client, "Map's time is temporarily set to %d seconds (was %d)", time, prev);
|
||||
} else if(StrEqual(subcmd, "settick")) {
|
||||
static char arg[16];
|
||||
GetCmdArg(2, arg, sizeof(arg));
|
||||
int tick = -StringToInt(arg);
|
||||
Game.Tick = tick;
|
||||
ReplyToCommand(client, "Set tick time to %d", tick);
|
||||
} else if(StrContains(subcmd, "map") >= 0) {
|
||||
static char arg[16];
|
||||
GetCmdArg(2, arg, sizeof(arg));
|
||||
if(StrEqual(arg, "list")) {
|
||||
ReplyToCommand(client, "See the console for available maps");
|
||||
char map[64];
|
||||
for(int i = 0; i < validMaps.Length; i++) {
|
||||
validMaps.GetString(i, map, sizeof(map));
|
||||
PrintToConsole(client, "%d. %s", i + 1, map);
|
||||
}
|
||||
} else if(StrEqual(arg, "random")) {
|
||||
bool foundMap;
|
||||
char map[64];
|
||||
do {
|
||||
int mapIndex = GetURandomInt() % validMaps.Length;
|
||||
validMaps.GetString(mapIndex, map, sizeof(map));
|
||||
if(!StrEqual(currentMap, map, false)) {
|
||||
foundMap = true;
|
||||
}
|
||||
} while(!foundMap);
|
||||
PrintToChatAll("[GuessWho] Switching map to %s", map);
|
||||
ChangeMap(map);
|
||||
} else if(StrEqual(arg, "next", false)) {
|
||||
if(args == 1) {
|
||||
ReplyToCommand(client, "Specify the map to change on the next round: 'next <map>'");
|
||||
} else {
|
||||
char arg2[64];
|
||||
GetCmdArg(3, arg2, sizeof(arg2));
|
||||
if(IsMapValid(arg2)) {
|
||||
strcopy(nextRoundMap, sizeof(nextRoundMap), arg2);
|
||||
PrintToChatAll("[H&S] Switching map next round to %s", arg2);
|
||||
ForceChangeLevel(arg, "SetMapSelect");
|
||||
} else {
|
||||
ReplyToCommand(client, "Map is not valid");
|
||||
}
|
||||
}
|
||||
} else if(StrEqual(arg, "force", false)) {
|
||||
if(args == 1) {
|
||||
ReplyToCommand(client, "Specify the map to change to: 'force <map>'");
|
||||
} else {
|
||||
char arg2[64];
|
||||
GetCmdArg(3, arg2, sizeof(arg2));
|
||||
if(IsMapValid(arg2)) {
|
||||
PrintToChatAll("[H&S] Switching map to %s", arg2);
|
||||
ChangeMap(arg2);
|
||||
} else {
|
||||
ReplyToCommand(client, "Map is not valid");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ReplyToCommand(client, "Syntax: 'map <list/random/force <mapname>/next <mapname>>");
|
||||
}
|
||||
return Plugin_Handled;
|
||||
} else if(StrEqual(subcmd, "pos", false)) {
|
||||
float pos[3];
|
||||
GetAbsOrigin(client, pos);
|
||||
ReplyToCommand(client, "\"origin\" \"%f %f %f\"", pos[0], pos[1], pos[2]);
|
||||
GetClientEyeAngles(client, pos);
|
||||
ReplyToCommand(client, "\"rotation\" \"%f %f %f\"", pos[0], pos[1], pos[2]);
|
||||
} else if(StrEqual(subcmd, "prop", false)) {
|
||||
float pos[3];
|
||||
GetAbsOrigin(client, pos);
|
||||
ReplyToCommand(client, "\"MYPROP\"");
|
||||
ReplyToCommand(client, "{");
|
||||
ReplyToCommand(client, "\t\"origin\" \"%f %f %f\"", pos[0], pos[1], pos[2]);
|
||||
GetClientAbsAngles(client, pos);
|
||||
ReplyToCommand(client, "\t\"rotation\" \"%f %f %f\"", pos[0], pos[1], pos[2]);
|
||||
ReplyToCommand(client, "\t\"type\" \"prop_dynamic\"");
|
||||
ReplyToCommand(client, "\t\"model\" \"props_junk/dumpster_2.mdl\"");
|
||||
ReplyToCommand(client, "}");
|
||||
} else if(StrEqual(subcmd, "setspawn", false)) {
|
||||
GetClientAbsOrigin(client, mapConfig.spawnpoint);
|
||||
ReplyToCommand(client, "Set map's temporarily spawnpoint to your location.");
|
||||
} else if(StrEqual(subcmd, "stuck")) {
|
||||
TeleportEntity(client, mapConfig.spawnpoint, NULL_VECTOR, NULL_VECTOR);
|
||||
} else if(StrEqual(subcmd, "peekfix")) {
|
||||
if(!PeekCam.Exists()) {
|
||||
PeekCam.Target = client;
|
||||
}
|
||||
|
||||
for(int i = 1; i <= MaxClients; i++) {
|
||||
if(IsClientConnected(i) && IsClientInGame(i)) {
|
||||
PeekCam.SetViewing(client, true);
|
||||
PeekCam.SetViewing(client, false);
|
||||
}
|
||||
}
|
||||
PeekCam.Destroy();
|
||||
ReplyToCommand(client, "Killing active camera");
|
||||
} else if(StrEqual(subcmd, "seeker")) {
|
||||
if(args == 2) {
|
||||
char arg1[32];
|
||||
GetCmdArg(2, arg1, sizeof(arg1));
|
||||
char target_name[MAX_TARGET_LENGTH];
|
||||
int target_list[1], target_count;
|
||||
bool tn_is_ml;
|
||||
if ((target_count = ProcessTargetString(
|
||||
arg1,
|
||||
client,
|
||||
target_list,
|
||||
1,
|
||||
0,
|
||||
target_name,
|
||||
sizeof(target_name),
|
||||
tn_is_ml)) <= 0
|
||||
|| target_list[0] == 0){
|
||||
/* This function replies to the admin with a failure message */
|
||||
ReplyToTargetError(client, target_count);
|
||||
return Plugin_Handled;
|
||||
}
|
||||
Game.ForceSetSeeker(target_list[0]);
|
||||
ReplyToCommand(client, "Set the current seeker to %N", target_list[0]);
|
||||
} else {
|
||||
ReplyToCommand(client, "The current seeker is: %N", Game.Seeker);
|
||||
}
|
||||
} else if(StrEqual(subcmd, "debug")) {
|
||||
ReplyToCommand(client, "- Game Info -");
|
||||
ReplyToCommand(client, "Current seeker: %N(%d)", Game.Seeker, Game.Seeker);
|
||||
ReplyToCommand(client, "State: %d | Tick: %d", view_as<int>(Game.State), Game.Tick);
|
||||
|
||||
ReplyToCommand(client, "- Map Info -");
|
||||
ReplyToCommand(client, "Map: %s (set %s)", currentMap, currentSet);
|
||||
if(mapConfig.hasSpawnpoint)
|
||||
ReplyToCommand(client, "Has Spawnpoint: yes (%f %f %f)", mapConfig.spawnpoint[0], mapConfig.spawnpoint[1], mapConfig.spawnpoint[2]);
|
||||
else
|
||||
ReplyToCommand(client, "Has Spawnpoint: no (possibly map spawn %f %f %f)", mapConfig.spawnpoint[0], mapConfig.spawnpoint[1], mapConfig.spawnpoint[2]);
|
||||
ReplyToCommand(client, "Map Time: %d", mapConfig.mapTime);
|
||||
ReplyToCommand(client, "Flow Bounds: (%f, %f)", flowMin, flowMax);
|
||||
} else {
|
||||
ReplyToCommand(client, "Unknown option. Leave blank for help");
|
||||
}
|
||||
return Plugin_Handled;
|
||||
}
|
||||
ReplyToCommand(client, " === [ Guess Who Commands ] ===");
|
||||
if(GetUserAdmin(client) != INVALID_ADMIN_ID) {
|
||||
ReplyToCommand(client, "- Dev Commands -");
|
||||
ReplyToCommand(client, "points:");
|
||||
ReplyToCommand(client, "\tsave [set]: Save all movement data for map, and a optional set (defaults to current set)");
|
||||
ReplyToCommand(client, "\tload: Loads movement data for current map & set");
|
||||
ReplyToCommand(client, "\tclear: Removes all active movement data");
|
||||
ReplyToCommand(client, "r/reload [force]: Reloads map config from file");
|
||||
ReplyToCommand(client, "toggle <blockers/props/all>: Toggles all specified entities");
|
||||
ReplyToCommand(client, "clear <props/blockers/all>: Clear all specified");
|
||||
ReplyToCommand(client, "settime [seconds]: Sets the time override for the map");
|
||||
ReplyToCommand(client, "settick [tick]: Sets the current tick timer value");
|
||||
ReplyToCommand(client, "- Admin Commands -");
|
||||
ReplyToCommand(client, "set [new set]: Change the prop set or view current");
|
||||
ReplyToCommand(client, "setspawn: Sets the temporary spawnpoint for the map");
|
||||
ReplyToCommand(client, "peekfix - Clear peek camera from all players");
|
||||
ReplyToCommand(client, "seeker [new seeker]: Get the active seeker, or set a new one.");
|
||||
ReplyToCommand(client, "- User Commands -");
|
||||
}
|
||||
ReplyToCommand(client, "stuck: Teleports you to spawn to unstuck yourself");
|
||||
return Plugin_Handled;
|
||||
}
|
||||
|
||||
public Action OnClientSayCommand(int client, const char[] command, const char[] sArgs) {
|
||||
if(isEnabled) {
|
||||
if(!StrEqual(command, "say")) { //Is team message
|
||||
if(currentSeeker <= 0 || currentSeeker == client) {
|
||||
return Plugin_Continue;
|
||||
}
|
||||
for(int i = 1; i <= MaxClients; i++) {
|
||||
if(IsClientConnected(i) && IsClientInGame(i) && i != currentSeeker)
|
||||
PrintToChat(i, "[Hiders] %N: %s", client, sArgs);
|
||||
}
|
||||
return Plugin_Handled;
|
||||
}
|
||||
}
|
||||
return Plugin_Continue;
|
||||
}
|
||||
|
||||
|
||||
public Action Command_Join(int client, int args) {
|
||||
if(!isEnabled) return Plugin_Continue;
|
||||
static float tpLoc[3];
|
||||
FindSpawnPosition(tpLoc);
|
||||
if(args == 1) {
|
||||
static char arg1[32];
|
||||
GetCmdArg(1, arg1, sizeof(arg1));
|
||||
char target_name[MAX_TARGET_LENGTH];
|
||||
int target_list[MAXPLAYERS], target_count;
|
||||
bool tn_is_ml;
|
||||
if ((target_count = ProcessTargetString(
|
||||
arg1,
|
||||
client,
|
||||
target_list,
|
||||
MAXPLAYERS,
|
||||
0,
|
||||
target_name,
|
||||
sizeof(target_name),
|
||||
tn_is_ml)) <= 0)
|
||||
{
|
||||
/* This function replies to the admin with a failure message */
|
||||
ReplyToTargetError(client, target_count);
|
||||
return Plugin_Handled;
|
||||
}
|
||||
for (int i = 0; i < target_count; i++) {
|
||||
int target = target_list[i];
|
||||
if(GetClientTeam(target) != 2) {
|
||||
ChangeClientTeam(target, 2);
|
||||
L4D_RespawnPlayer(target);
|
||||
TeleportEntity(target, tpLoc, NULL_VECTOR, NULL_VECTOR);
|
||||
isPendingPlay[client] = false;
|
||||
CheatCommand(target, "give", "knife");
|
||||
}
|
||||
}
|
||||
ReplyToCommand(client, "Joined %s", target_name);
|
||||
} else {
|
||||
if(currentSeeker == client) {
|
||||
ReplyToCommand(client, "You are already in-game as a seeker.");
|
||||
return Plugin_Handled;
|
||||
}
|
||||
isPendingPlay[client] = false;
|
||||
ChangeClientTeam(client, 2);
|
||||
L4D_RespawnPlayer(client);
|
||||
TeleportEntity(client, tpLoc, NULL_VECTOR, NULL_VECTOR);
|
||||
CheatCommand(client, "give", "gnome");
|
||||
}
|
||||
return Plugin_Handled;
|
||||
}
|
171
scripting/include/guesswho/gwcore.inc
Normal file
171
scripting/include/guesswho/gwcore.inc
Normal file
|
@ -0,0 +1,171 @@
|
|||
#include <guesswho/gwpoints>
|
||||
#include <guesswho/gwgame>
|
||||
#include <guesswho/gwcmds>
|
||||
#include <guesswho/gwents>
|
||||
#include <guesswho/gwtimers>
|
||||
|
||||
#define FOLDER_PERMS ( FPERM_U_READ | FPERM_U_WRITE | FPERM_U_EXEC | FPERM_G_EXEC | FPERM_G_WRITE | FPERM_G_READ | FPERM_O_EXEC )
|
||||
|
||||
static KeyValues kv;
|
||||
StringMap mapConfigs;
|
||||
|
||||
bool ReloadMapDB() {
|
||||
if(kv != null) {
|
||||
delete kv;
|
||||
}
|
||||
kv = new KeyValues("guesswho");
|
||||
|
||||
char sPath[PLATFORM_MAX_PATH];
|
||||
BuildPath(Path_SM, sPath, sizeof(sPath), "data/guesswho");
|
||||
CreateDirectory(sPath, FOLDER_PERMS);
|
||||
Format(sPath, sizeof(sPath), "%s/config.cfg", sPath);
|
||||
|
||||
if(!FileExists(sPath) || !kv.ImportFromFile(sPath)) {
|
||||
delete kv;
|
||||
return false;
|
||||
}
|
||||
|
||||
validMaps.Clear();
|
||||
|
||||
char map[64];
|
||||
kv.GotoFirstSubKey(true);
|
||||
do {
|
||||
kv.GetSectionName(map, sizeof(map));
|
||||
validMaps.PushString(map);
|
||||
} while(kv.GotoNextKey(true));
|
||||
kv.GoBack();
|
||||
return true;
|
||||
}
|
||||
|
||||
static float DEFAULT_SCALE[3] = { 5.0, 5.0, 5.0 };
|
||||
|
||||
bool LoadConfigForMap(const char[] map) {
|
||||
kv.Rewind();
|
||||
if (kv.JumpToKey(map)) {
|
||||
MapConfig config;
|
||||
config.entities = new ArrayList(sizeof(EntityConfig));
|
||||
config.inputs = new ArrayList(ByteCountToCells(64));
|
||||
validSets.Clear();
|
||||
|
||||
static char buffer[64];
|
||||
buffer[0] = '\0';
|
||||
if(StrEqual(currentSet, "default") && kv.GetString("defaultset", buffer, sizeof(buffer)) && buffer[0] != '\0') {
|
||||
strcopy(currentSet, sizeof(currentSet), buffer);
|
||||
}
|
||||
PrintToServer("[GuessWho] Loading config data for set %s on %s", currentSet, map);
|
||||
|
||||
if(kv.JumpToKey("ents")) {
|
||||
kv.GotoFirstSubKey();
|
||||
do {
|
||||
EntityConfig entCfg;
|
||||
kv.GetVector("origin", entCfg.origin, NULL_VECTOR);
|
||||
kv.GetVector("rotation", entCfg.rotation, NULL_VECTOR);
|
||||
kv.GetString("type", entCfg.type, sizeof(entCfg.type), "env_physics_blocker");
|
||||
kv.GetString("model", entCfg.model, sizeof(entCfg.model), "");
|
||||
if(entCfg.model[0] != '\0')
|
||||
Format(entCfg.model, sizeof(entCfg.model), "models/%s", entCfg.model);
|
||||
kv.GetVector("scale", entCfg.scale, DEFAULT_SCALE);
|
||||
kv.GetVector("offset", entCfg.offset, NULL_VECTOR);
|
||||
kv.GetString("set", buffer, sizeof(buffer), "default");
|
||||
if(validSets.FindString(buffer) == -1) {
|
||||
validSets.PushString(buffer);
|
||||
}
|
||||
if(StrEqual(buffer, "default") || StrEqual(currentSet, buffer, false)) {
|
||||
|
||||
config.entities.PushArray(entCfg);
|
||||
} else {
|
||||
kv.GetSectionName(buffer, sizeof(buffer));
|
||||
PrintToServer("Skipping %s", buffer);
|
||||
}
|
||||
} while (kv.GotoNextKey());
|
||||
// JumpToKey and GotoFirstSubKey both traverse, i guess, go back
|
||||
kv.GoBack();
|
||||
kv.GoBack();
|
||||
}
|
||||
if(kv.JumpToKey("inputs")) {
|
||||
kv.GotoFirstSubKey(false);
|
||||
do {
|
||||
kv.GetSectionName(buffer, sizeof(buffer));
|
||||
config.inputs.PushString(buffer);
|
||||
|
||||
kv.GetString(NULL_STRING, buffer, sizeof(buffer));
|
||||
config.inputs.PushString(buffer);
|
||||
} while (kv.GotoNextKey(false));
|
||||
kv.GoBack();
|
||||
kv.GoBack();
|
||||
}
|
||||
int mapTime;
|
||||
|
||||
config.hasSpawnpoint = false;
|
||||
config.canClimb = true;
|
||||
config.pressButtons = true;
|
||||
if(!StrEqual(currentSet, "default") && kv.JumpToKey("sets")) {
|
||||
char set[16];
|
||||
kv.GotoFirstSubKey(true);
|
||||
do {
|
||||
kv.GetSectionName(set, sizeof(set));
|
||||
if(validSets.FindString(set) == -1) {
|
||||
validSets.PushString(set);
|
||||
}
|
||||
if(StrEqual(currentSet, set, false)) {
|
||||
kv.GetVector("spawnpoint", config.spawnpoint);
|
||||
if(config.spawnpoint[0] != 0.0 && config.spawnpoint[1] != 0.0 && config.spawnpoint[2] != 0.0) {
|
||||
PrintToServer("[GuessWho] Using provided custom spawnpoint for set %s at %0.1f, %0.1f, %0.1f", currentSet, config.spawnpoint[0], config.spawnpoint[1], config.spawnpoint[2]);
|
||||
config.hasSpawnpoint = true;
|
||||
}
|
||||
mapTime = kv.GetNum("maptime", 0);
|
||||
if(kv.JumpToKey("inputs")) {
|
||||
kv.GotoFirstSubKey(false);
|
||||
do {
|
||||
kv.GetSectionName(buffer, sizeof(buffer));
|
||||
config.inputs.PushString(buffer);
|
||||
|
||||
kv.GetString(NULL_STRING, buffer, sizeof(buffer));
|
||||
config.inputs.PushString(buffer);
|
||||
} while (kv.GotoNextKey(false));
|
||||
kv.GoBack();
|
||||
kv.GoBack();
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
} while(kv.GotoNextKey(true));
|
||||
kv.GoBack();
|
||||
kv.GoBack();
|
||||
}
|
||||
|
||||
if(!config.hasSpawnpoint) {
|
||||
kv.GetVector("spawnpoint", config.spawnpoint);
|
||||
if(config.spawnpoint[0] != 0.0 && config.spawnpoint[1] != 0.0 && config.spawnpoint[2] != 0.0) {
|
||||
PrintToServer("[GuessWho] Using provided custom spawnpoint at %0.1f, %0.1f, %0.1f", config.spawnpoint[0], config.spawnpoint[1], config.spawnpoint[2]);
|
||||
config.hasSpawnpoint = true;
|
||||
} else if (FindSpawnPosition(config.spawnpoint, false)) {
|
||||
PrintToServer("[GuessWho] Using map spawnpoint at %0.1f, %0.1f, %0.1f", config.spawnpoint[0], config.spawnpoint[1], config.spawnpoint[2]);
|
||||
config.hasSpawnpoint = true;
|
||||
} else {
|
||||
PrintToServer("[GuessWho] Could not find any spawnpoints, using default spawn");
|
||||
config.hasSpawnpoint = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Use default maptime if exists
|
||||
if(mapTime == 0)
|
||||
mapTime = kv.GetNum("maptime", 0);
|
||||
if(mapTime > 0) {
|
||||
config.mapTime = mapTime;
|
||||
PrintToServer("[GuessWho] Map time overwritten to %d seconds", mapTime);
|
||||
}
|
||||
|
||||
mapConfigs.SetArray(map, config, sizeof(MapConfig));
|
||||
// Discard entInputs if unused
|
||||
if(config.inputs.Length == 0) {
|
||||
delete config.inputs;
|
||||
}
|
||||
mapConfig = config;
|
||||
return true;
|
||||
} else {
|
||||
mapConfig.hasSpawnpoint = false;
|
||||
PrintToServer("[GuessWho] %s has no config entry", map);
|
||||
return false;
|
||||
}
|
||||
}
|
291
scripting/include/guesswho/gwents.inc
Normal file
291
scripting/include/guesswho/gwents.inc
Normal file
|
@ -0,0 +1,291 @@
|
|||
#define GAMEMODE_PROP_NAME "gwprop"
|
||||
#define GAMEMODE_BLOCKER_NAME "gwblocker"
|
||||
stock int CreateEnvBlockerBox(const float pos[3], bool enabled = true) {
|
||||
int entity = CreateEntityByName("env_physics_blocker");
|
||||
if(entity == -1) return -1;
|
||||
DispatchKeyValue(entity, "targetname", GAMEMODE_BLOCKER_NAME);
|
||||
DispatchKeyValue(entity, "initialstate", "1");
|
||||
DispatchKeyValue(entity, "BlockType", "0");
|
||||
TeleportEntity(entity, pos, NULL_VECTOR, NULL_VECTOR);
|
||||
if(DispatchSpawn(entity)) {
|
||||
if(enabled)
|
||||
AcceptEntityInput(entity, "Enable");
|
||||
return entity;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
stock int CreateEnvBlockerScaled(const char[] entClass, const float pos[3], const float scale[3] = { 5.0, 5.0, 5.0 }, bool enabled = true) {
|
||||
int entity = CreateEntityByName(entClass);
|
||||
DispatchKeyValue(entity, "targetname", GAMEMODE_BLOCKER_NAME);
|
||||
DispatchKeyValue(entity, "initialstate", "1");
|
||||
DispatchKeyValue(entity, "BlockType", "0");
|
||||
static float mins[3];
|
||||
mins = scale;
|
||||
NegateVector(mins);
|
||||
DispatchKeyValueVector(entity, "boxmins", mins);
|
||||
DispatchKeyValueVector(entity, "boxmaxs", scale);
|
||||
DispatchKeyValueVector(entity, "mins", mins);
|
||||
DispatchKeyValueVector(entity, "maxs", scale);
|
||||
|
||||
TeleportEntity(entity, pos, NULL_VECTOR, NULL_VECTOR);
|
||||
if(DispatchSpawn(entity)) {
|
||||
#if defined DEBUG_LOG_MAPSTART
|
||||
PrintToServer("spawn blocker scaled %.1f %.1f %.1f scale [%.0f %.0f %.0f]", pos[0], pos[1], pos[2], scale[0], scale[1], scale[2]);
|
||||
#endif
|
||||
SetEntPropVector(entity, Prop_Send, "m_vecMaxs", scale);
|
||||
SetEntPropVector(entity, Prop_Send, "m_vecMins", mins);
|
||||
if(enabled)
|
||||
AcceptEntityInput(entity, "Enable");
|
||||
#if defined DEBUG_BLOCKERS
|
||||
Effect_DrawBeamBoxRotatableToAll(pos, mins, scale, NULL_VECTOR, g_iLaserIndex, 0, 0, 0, 150.0, 0.1, 0.1, 0, 0.0, {255, 0, 0, 255}, 0);
|
||||
#endif
|
||||
return entity;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
enum PortalType {
|
||||
Portal_Relative,
|
||||
Portal_Teleport
|
||||
}
|
||||
PortalType entityPortalType[2048];
|
||||
float entityPortalOffsets[2048][3];
|
||||
|
||||
stock int CreatePortal(PortalType type, const char model[64], const float pos[3], const float offset[3] = { 40.0, 40.0, 0.0 }, const float scale[3] = { 5.0, 5.0, 5.0 }) {
|
||||
int entity = CreateEntityByName("trigger_multiple");
|
||||
if(entity == -1) return -1;
|
||||
DispatchKeyValue(entity, "spawnflags", "513");
|
||||
DispatchKeyValue(entity, "solid", "6");
|
||||
DispatchKeyValue(entity, "targetname", "gwportal");
|
||||
DispatchKeyValue(entity, "wait", "0");
|
||||
if(DispatchSpawn(entity)) {
|
||||
TeleportEntity(entity, pos, NULL_VECTOR, NULL_VECTOR);
|
||||
static float mins[3];
|
||||
mins = scale;
|
||||
NegateVector(mins);
|
||||
SetEntPropVector(entity, Prop_Send, "m_vecMaxs", scale);
|
||||
SetEntPropVector(entity, Prop_Send, "m_vecMins", mins);
|
||||
SetEntProp(entity, Prop_Send, "m_nSolidType", 2);
|
||||
|
||||
HookSingleEntityOutput(entity, "OnStartTouch", OnPortalTouch, false);
|
||||
#if defined DEBUG_BLOCKERS
|
||||
Effect_DrawBeamBoxRotatableToAll(pos, mins, scale, NULL_VECTOR, g_iLaserIndex, 0, 0, 0, 150.0, 0.1, 0.1, 0, 0.0, {255, 0, 255, 255}, 0);
|
||||
#endif
|
||||
#if defined DEBUG_LOG_MAPSTART
|
||||
PrintToServer("spawn portal %d - pos %.1f %.1f %.1f - scale %.1f %.1f %.1f", entity, pos[0], pos[1], pos[2], scale[0], scale[1], scale[2]);
|
||||
#endif
|
||||
AcceptEntityInput(entity, "Enable");
|
||||
|
||||
entityPortalOffsets[entity] = NULL_VECTOR;
|
||||
|
||||
// Convert relative offset to one based off full scale:
|
||||
entityPortalType[entity] = type;
|
||||
if(type == Portal_Relative) {
|
||||
if(offset[0] != 0.0) entityPortalOffsets[entity][0] = (scale[0] * 2) + offset[0];
|
||||
if(offset[1] != 0.0) entityPortalOffsets[entity][1] = (scale[1] * 2) + offset[1];
|
||||
if(offset[2] != 0.0) entityPortalOffsets[entity][2] = (scale[2] * 2) + offset[2];
|
||||
} else {
|
||||
entityPortalOffsets[entity] = offset;
|
||||
}
|
||||
|
||||
return entity;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void OnPortalTouch(const char[] output, int caller, int activator, float delay) {
|
||||
if(entityPortalType[caller] == Portal_Relative) {
|
||||
float pos[3];
|
||||
GetClientAbsOrigin(activator, pos);
|
||||
float ang[3];
|
||||
GetClientAbsAngles(activator, ang);
|
||||
if(ang[0] < 0) pos[0] -= entityPortalOffsets[caller][0];
|
||||
else pos[0] += entityPortalOffsets[caller][0];
|
||||
if(ang[1] < 0) pos[1] -= entityPortalOffsets[caller][1];
|
||||
else pos[1] += entityPortalOffsets[caller][1];
|
||||
if(ang[2] < 0) pos[2] -= entityPortalOffsets[caller][2];
|
||||
else pos[2] += entityPortalOffsets[caller][2];
|
||||
TeleportEntity(activator, pos, NULL_VECTOR, NULL_VECTOR);
|
||||
} else {
|
||||
TeleportEntity(activator, entityPortalOffsets[caller], NULL_VECTOR, NULL_VECTOR);
|
||||
}
|
||||
}
|
||||
|
||||
stock int StartPropCreate(const char[] entClass, const char[] model, const float pos[3], const float ang[3]) {
|
||||
int entity = CreateEntityByName(entClass);
|
||||
if(entity == -1) return -1;
|
||||
DispatchKeyValue(entity, "model", model);
|
||||
DispatchKeyValue(entity, "solid", "6");
|
||||
DispatchKeyValue(entity, "targetname", GAMEMODE_PROP_NAME);
|
||||
DispatchKeyValue(entity, "disableshadows", "1");
|
||||
TeleportEntity(entity, pos, ang, NULL_VECTOR);
|
||||
return entity;
|
||||
}
|
||||
|
||||
stock int CreateProp(const char[] entClass, const char[] model, const float pos[3], const float ang[3]) {
|
||||
int entity = StartPropCreate(entClass, model, pos, ang);
|
||||
if(DispatchSpawn(entity)) {
|
||||
#if defined DEBUG_LOG_MAPSTART
|
||||
PrintToServer("spawn prop %.1f %.1f %.1f model %s", pos[0], pos[1], pos[2], model[7]);
|
||||
#endif
|
||||
return entity;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
stock int CreateDummy(const char[] model, const char[] anim, const float pos[3], const float ang[3] = NULL_VECTOR) {
|
||||
int entity = StartPropCreate("commentary_dummy", model, pos, ang);
|
||||
if(entity == -1) return -1;
|
||||
DispatchKeyValue(entity, "LookAtPlayers", "Yes");
|
||||
DispatchKeyValue(entity, "StartingWeapons", "weapon_rifle_ak47");
|
||||
DispatchKeyValue(entity, "StartingAnim", anim); //idle_calm_rifle
|
||||
DispatchKeyValueFloat(entity, "LookAtPlayers", 40.0);
|
||||
DispatchSpawn(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
// Taken from silver's https://forums.alliedmods.net/showthread.php?p=1658873
|
||||
stock int CreateDynamicLight(float vOrigin[3], float vAngles[3], int color, float brightness, int style = 0) {
|
||||
int entity = CreateEntityByName("light_dynamic");
|
||||
if( entity == -1)
|
||||
return -1;
|
||||
|
||||
DispatchKeyValue(entity, "_light", "0 0 0 255");
|
||||
DispatchKeyValue(entity, "brightness", "1");
|
||||
DispatchKeyValueFloat(entity, "spotlight_radius", 32.0);
|
||||
DispatchKeyValueFloat(entity, "distance", brightness);
|
||||
DispatchKeyValue(entity, "targetname", "gwlamp");
|
||||
DispatchKeyValueFloat(entity, "style", float(style));
|
||||
SetEntProp(entity, Prop_Send, "m_clrRender", color);
|
||||
if(DispatchSpawn(entity)) {
|
||||
TeleportEntity(entity, vOrigin, vAngles, NULL_VECTOR);
|
||||
AcceptEntityInput(entity, "TurnOn");
|
||||
#if defined DEBUG_LOG_MAPSTART
|
||||
PrintToServer("spawn dynamic light %.1f %.1f %.1f", vOrigin[0], vOrigin[1], vOrigin[2]);
|
||||
#endif
|
||||
return entity;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
stock void CheatCommand(int client, const char[] command, const char[] argument1) {
|
||||
int userFlags = GetUserFlagBits(client);
|
||||
SetUserFlagBits(client, ADMFLAG_ROOT);
|
||||
int flags = GetCommandFlags(command);
|
||||
SetCommandFlags(command, flags & ~FCVAR_CHEAT);
|
||||
FakeClientCommand(client, "%s %s", command, argument1);
|
||||
SetCommandFlags(command, flags);
|
||||
SetUserFlagBits(client, userFlags);
|
||||
}
|
||||
|
||||
stock void EntFire(const char[] name, const char[] input) {
|
||||
static char targetname[64];
|
||||
static char cmd[32];
|
||||
#if defined DEBUG_LOG_MAPSTART
|
||||
PrintToServer("[GuessWho] EntFire: %s \"%s\"", name, input);
|
||||
#endif
|
||||
int len = SplitString(input, " ", cmd, sizeof(cmd));
|
||||
if(len > -1) SetVariantString(input[len]);
|
||||
|
||||
int hammerId = name[0] == '!' ? StringToInt(name[1]) : 0;
|
||||
for(int i = MaxClients + 1; i <= 4096; i++) {
|
||||
if(IsValidEntity(i) && (IsValidEdict(i) || EntIndexToEntRef(i) != -1)) {
|
||||
if(hammerId > 0) {
|
||||
if(hammerId == GetHammerId(i)) {
|
||||
if(len > -1) AcceptEntityInput(i, cmd);
|
||||
else AcceptEntityInput(i, input);
|
||||
}
|
||||
} else {
|
||||
GetEntPropString(i, Prop_Data, "m_iName", targetname, sizeof(targetname));
|
||||
if(StrEqual(targetname, name, false)) {
|
||||
if(len > -1) AcceptEntityInput(i, cmd);
|
||||
else AcceptEntityInput(i, input);
|
||||
} else {
|
||||
GetEntityClassname(i, targetname, sizeof(targetname));
|
||||
if(StrEqual(targetname, name, false)) {
|
||||
if(len > -1) AcceptEntityInput(i, cmd);
|
||||
else AcceptEntityInput(i, input);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int GetHammerId(int entity) {
|
||||
return HasEntProp(entity, Prop_Data, "m_iHammerID") ? GetEntProp(entity, Prop_Data, "m_iHammerID") : -1;
|
||||
}
|
||||
|
||||
|
||||
|
||||
void SetupEntities(bool blockers = true, bool props = true, bool portals = true) {
|
||||
#if defined DEBUG_BLOCKERS
|
||||
if(mapConfig.hasSpawnpoint) {
|
||||
PrecacheModel("survivors/survivor_teenangst.mdl", true);
|
||||
int dummy = CreateDummy("models/survivors/survivor_teenangst.mdl", "idle", mapConfig.spawnpoint, NULL_VECTOR);
|
||||
SetEntProp(dummy, Prop_Data, "m_nSolidType", 0);
|
||||
SetEntProp(dummy, Prop_Send, "m_CollisionGroup", 0);
|
||||
SetEntProp(dummy, Prop_Send, "movetype", MOVETYPE_NONE);
|
||||
}
|
||||
#endif
|
||||
if(mapConfig.entities != null) {
|
||||
PrintToServer("[GuessWho] Deploying %d custom entities (Set: %s) (blockers:%b props:%b portals:%b)", mapConfig.entities.Length, currentSet, blockers, props, portals);
|
||||
for(int i = 0; i < mapConfig.entities.Length; i++) {
|
||||
EntityConfig config;
|
||||
mapConfig.entities.GetArray(i, config);
|
||||
|
||||
if(config.model[0] != '\0') PrecacheModel(config.model);
|
||||
|
||||
if(StrEqual(config.type, "env_physics_blocker")) {
|
||||
if(blockers && CreateEnvBlockerScaled(config.type, config.origin, config.scale, isNavBlockersEnabled) == -1) {
|
||||
PrintToServer("[H&S:WARN] Failed to spawn blocker [type=%s] at (%.1f,%.1f, %.1f)", config.type, config.origin[0], config.origin[1], config.origin[2]);
|
||||
}
|
||||
} else if(StrEqual(config.type, "_relportal")) {
|
||||
if(portals && CreatePortal(Portal_Relative, config.model, config.origin, config.offset, config.scale) == -1) {
|
||||
PrintToServer("[H&S:WARN] Failed to spawn rel portal at (%.1f,%.1f, %.1f)", config.origin[0], config.origin[1], config.origin[2]);
|
||||
}
|
||||
} else if(StrEqual(config.type, "_portal")) {
|
||||
if(portals && CreatePortal(Portal_Teleport, config.model, config.origin, config.offset, config.scale) == -1) {
|
||||
PrintToServer("[H&S:WARN] Failed to spawn portal at (%.1f,%.1f, %.1f)", config.origin[0], config.origin[1], config.origin[2]);
|
||||
}
|
||||
} else if(StrEqual(config.type, "_lantern")) {
|
||||
int parent = CreateProp("prop_dynamic", config.model, config.origin, config.rotation);
|
||||
if(parent == -1) {
|
||||
PrintToServer("[H&S:WARN] Failed to spawn prop [type=%s] [model=%s] at (%.1f,%.1f, %.1f)", config.type, config.model, config.origin[0], config.origin[1], config.origin[2]);
|
||||
} else {
|
||||
float pos[3];
|
||||
pos = config.origin;
|
||||
pos[2] += 15.0;
|
||||
int child = CreateDynamicLight(pos, config.rotation, GetColorInt(255, 255, 242), 80.0, 11);
|
||||
if(child == -1) {
|
||||
PrintToServer("[GuessWho] Failed to spawn light source for _lantern");
|
||||
} else {
|
||||
SetParent(child, parent);
|
||||
TeleportEntity(parent, config.origin, NULL_VECTOR, NULL_VECTOR);
|
||||
}
|
||||
}
|
||||
} else if(StrEqual(config.type, "_dummy")) {
|
||||
if(CreateDummy(config.model, "hitby_tankpunch", config.origin, config.rotation) == -1) {
|
||||
PrintToServer("[H&S:WARN] Failed to spawn dummy [model=%s] at (%.1f,%.1f, %.1f)", config.model, config.origin[0], config.origin[1], config.origin[2]);
|
||||
}
|
||||
}else if(props) {
|
||||
if(CreateProp(config.type, config.model, config.origin, config.rotation) == -1) {
|
||||
PrintToServer("[H&S:WARN] Failed to spawn prop [type=%s] [model=%s] at (%.1f,%.1f, %.1f)", config.type, config.model, config.origin[0], config.origin[1], config.origin[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static char key[64];
|
||||
static char value[64];
|
||||
if(mapConfig.inputs != null) {
|
||||
for(int i = 0; i < mapConfig.inputs.Length - 1; i += 2) {
|
||||
mapConfig.inputs.GetString(i, key, sizeof(key));
|
||||
mapConfig.inputs.GetString(i + 1, value, sizeof(value));
|
||||
EntFire(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
447
scripting/include/guesswho/gwgame.inc
Normal file
447
scripting/include/guesswho/gwgame.inc
Normal file
|
@ -0,0 +1,447 @@
|
|||
static int mapChangeMsgTicks = 5;
|
||||
|
||||
int GetColorInt(int r, int g, int b) {
|
||||
int color = r;
|
||||
color += 256 * g;
|
||||
color += 65536 * b;
|
||||
return color;
|
||||
}
|
||||
|
||||
Action Timer_ChangeMap(Handle h) {
|
||||
PrintToChatAll("Changing map to %s in %d seconds", nextRoundMap, mapChangeMsgTicks);
|
||||
if(mapChangeMsgTicks-- == 0) {
|
||||
ForceChangeLevel(nextRoundMap, "GuessWhoMapSelect");
|
||||
nextRoundMap[0] = '\0';
|
||||
return Plugin_Stop;
|
||||
}
|
||||
return Plugin_Continue;
|
||||
}
|
||||
|
||||
void ChangeMap(const char map[64], int time = 5) {
|
||||
strcopy(nextRoundMap, sizeof(nextRoundMap), map);
|
||||
mapChangeMsgTicks = time;
|
||||
CreateTimer(1.0, Timer_ChangeMap, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE);
|
||||
}
|
||||
|
||||
bool FindSpawnPosition(float pos[3], bool includePlayers = true) {
|
||||
if(includePlayers) {
|
||||
for(int i = 1; i <= MaxClients; i++) {
|
||||
if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) {
|
||||
GetClientAbsOrigin(i, pos);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
int entity = INVALID_ENT_REFERENCE;
|
||||
while ((entity = FindEntityByClassname(entity, "info_player_start")) != INVALID_ENT_REFERENCE) {
|
||||
GetEntPropVector(entity, Prop_Send, "m_vecOrigin", pos);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static char buffer[64];
|
||||
|
||||
methodmap GameConVar __nullable__ < ConVar {
|
||||
public GameConVar(const char[] name) {
|
||||
return view_as<GameConVar>(FindConVar(name));
|
||||
}
|
||||
|
||||
public void RecordInt(int value, bool record = false) {
|
||||
if(record) {
|
||||
this.GetName(buffer, sizeof(buffer));
|
||||
previousCvarValues.SetValue(buffer, float(value));
|
||||
}
|
||||
this.IntValue = value;
|
||||
}
|
||||
|
||||
public void RecordFloat(float value, bool record = false) {
|
||||
if(record) {
|
||||
this.GetName(buffer, sizeof(buffer));
|
||||
previousCvarValues.SetValue(buffer, value);
|
||||
}
|
||||
this.FloatValue = value;
|
||||
}
|
||||
|
||||
public void RecordString(const char[] value, bool record = false) {
|
||||
if(record) {
|
||||
char prevValue[32];
|
||||
this.GetName(buffer, sizeof(buffer));
|
||||
this.GetString(prevValue, sizeof(prevValue));
|
||||
previousCvarValues.SetString(buffer, prevValue);
|
||||
}
|
||||
this.SetString(value);
|
||||
}
|
||||
}
|
||||
|
||||
methodmap GuessWhoGame {
|
||||
|
||||
property int Seeker {
|
||||
public get() {
|
||||
if(currentSeeker > 0 && IsClientConnected(currentSeeker)) {
|
||||
return currentSeeker;
|
||||
} else {
|
||||
return this._FindSeeker();
|
||||
}
|
||||
}
|
||||
public set(int client) {
|
||||
for(int i = 1; i <= MaxClients; i++) {
|
||||
if(IsClientConnected(i) && IsClientInGame(i) && i != client) {
|
||||
ClearInventory(i);
|
||||
CheatCommand(i, "give", "gnome");
|
||||
}
|
||||
}
|
||||
// Reset things incase set mid-start
|
||||
if(currentSeeker > 0) {
|
||||
SetEntPropFloat(currentSeeker, Prop_Send, "m_flLaggedMovementValue", 1.0);
|
||||
SetPlayerBlind(currentSeeker, 0);
|
||||
L4D2_RemoveEntityGlow(currentSeeker);
|
||||
}
|
||||
|
||||
hasBeenSeeker[client] = true;
|
||||
Format(buffer, sizeof(buffer), "g_ModeScript.MutationState.CurrentSeeker = GetPlayerFromUserID(%d);", GetClientUserId(client));
|
||||
CheatCommand(client, "give", "fireaxe");
|
||||
L4D2_ExecVScriptCode(buffer);
|
||||
currentSeeker = client;
|
||||
}
|
||||
}
|
||||
|
||||
property int Tick {
|
||||
public get() {
|
||||
if(!isEnabled) return -1;
|
||||
L4D2_GetVScriptOutput("g_ModeScript.MutationState.Tick", buffer, sizeof(buffer));
|
||||
int value = -1;
|
||||
if(StringToIntEx(buffer, value) > 0) {
|
||||
return value;
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
public set(int tick) {
|
||||
Format(buffer, sizeof(buffer), "g_ModeScript.MutationState.Tick = %d", tick);
|
||||
L4D2_ExecVScriptCode(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
property GameState State {
|
||||
public get() {
|
||||
if(!isEnabled) return State_Unknown;
|
||||
L4D2_GetVScriptOutput("g_ModeScript.MutationState.State", buffer, sizeof(buffer));
|
||||
int stage = 0;
|
||||
if(StringToIntEx(buffer, stage) > 0) {
|
||||
return view_as<GameState>(stage);
|
||||
} else {
|
||||
return State_Unknown;
|
||||
}
|
||||
}
|
||||
public set(GameState state) {
|
||||
if(isEnabled) {
|
||||
Format(buffer, sizeof(buffer), "g_ModeScript.MutationState.State = %d", view_as<int>(state));
|
||||
L4D2_ExecVScriptCode(buffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
property int MapTime {
|
||||
public get() {
|
||||
L4D2_GetVScriptOutput("g_ModeScript.MutationState.MaxTime", buffer, sizeof(buffer));
|
||||
return StringToInt(buffer);
|
||||
}
|
||||
public set(int seconds) {
|
||||
Format(buffer, sizeof(buffer), "g_ModeScript.MutationState.MaxTime = %d", seconds);
|
||||
L4D2_ExecVScriptCode(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
public void Start() {
|
||||
|
||||
}
|
||||
|
||||
public void End(GameState state) {
|
||||
if(acquireLocationsTimer != null) delete acquireLocationsTimer;
|
||||
if(timesUpTimer != null) delete timesUpTimer;
|
||||
if(hiderCheckTimer != null) delete hiderCheckTimer;
|
||||
currentSeeker = 0;
|
||||
this.State = state;
|
||||
if(state == State_HidersWin) {
|
||||
// Show the hiders
|
||||
for(int i = 1; i <= MaxClients; i++) {
|
||||
if(IsClientConnected(i) && IsClientInGame(i) && IsFakeClient(i)) {
|
||||
if(IsFakeClient(i)) {
|
||||
ClearInventory(i);
|
||||
PrintToServer("PlayerDeath: Seeker kill %d", i);
|
||||
KickClient(i);
|
||||
} else {
|
||||
L4D2_SetEntityGlow(i, L4D2Glow_Constant, 0, 20, PLAYER_GLOW_COLOR, false);
|
||||
L4D2_SetPlayerSurvivorGlowState(i, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
CreateTimer(5.0, Timer_ResetAll);
|
||||
}
|
||||
|
||||
public void Cleanup(bool entsOnly = false) {
|
||||
EntFire("gwprop", "kill");
|
||||
EntFire("gwblocker", "kill");
|
||||
EntFire("gwportal", "kill");
|
||||
PeekCam.Destroy();
|
||||
if(entsOnly) return;
|
||||
for(int i = 1; i <= MaxClients; i++) {
|
||||
if(IsClientConnected(i) && IsClientInGame(i)) {
|
||||
if(isEnabled)
|
||||
ClearInventory(i);
|
||||
SDKUnhook(i, SDKHook_OnTakeDamageAlive, OnTakeDamageAlive);
|
||||
SDKUnhook(i, SDKHook_WeaponDrop, OnWeaponDrop);
|
||||
}
|
||||
}
|
||||
if(recordTimer != null) {
|
||||
delete recordTimer;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public int _FindSeeker() {
|
||||
if(!isEnabled) return -1;
|
||||
L4D2_GetVScriptOutput("g_ModeScript.MutationState.CurrentSeeker && \"GetPlayerUserId\" in g_ModeScript.MutationState.CurrentSeeker ? g_ModeScript.MutationState.CurrentSeeker.GetPlayerUserId() : -1", buffer, sizeof(buffer));
|
||||
int uid = StringToInt(buffer);
|
||||
if(uid > 0) {
|
||||
return GetClientOfUserId(uid);
|
||||
} else {
|
||||
PrintToServer("[GuessWho] Could not find real seeker, falling back to manual check");
|
||||
for(int i = 1; i <= MaxClients; i++) {
|
||||
if(IsClientConnected(i) && IsClientInGame(i)) {
|
||||
int entity = GetPlayerWeaponSlot(i, 1);
|
||||
if(entity > -1 && GetEntityClassname(entity, buffer, sizeof(buffer)) && StrEqual(buffer, "melee")) {
|
||||
GetEntPropString(entity, Prop_Data, "m_strMapSetScriptName", buffer, sizeof(buffer));
|
||||
if(StrEqual(buffer, "fireaxe")) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
public void ForceSetSeeker(int client, bool ignoreBalance = false) {
|
||||
ignoreSeekerBalance = true;
|
||||
this.Seeker = client;
|
||||
}
|
||||
|
||||
public bool TeleportToSpawn(int client) {
|
||||
if(mapConfig.hasSpawnpoint) {
|
||||
TeleportEntity(client, mapConfig.spawnpoint, NULL_VECTOR, NULL_VECTOR);
|
||||
return true;
|
||||
} else {
|
||||
float pos[3];
|
||||
if(FindSpawnPosition(pos)) {
|
||||
return false;
|
||||
}
|
||||
TeleportEntity(client, pos, NULL_VECTOR, NULL_VECTOR);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void TeleportAllToStart() {
|
||||
if(mapConfig.hasSpawnpoint) {
|
||||
PrintToServer("[GuessWho] Teleporting all players to provided spawnpoint (%f %f %f)", mapConfig.spawnpoint[0], mapConfig.spawnpoint[1], mapConfig.spawnpoint[2]);
|
||||
for(int i = 1; i <= MaxClients; i++) {
|
||||
if(IsClientConnected(i) && IsClientInGame(i)) {
|
||||
this.TeleportToSpawn(i);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
PrintToServer("[GuessWho] Warn: No spawnpoint found (provided or map spawn)");
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsPendingPlayers() {
|
||||
for(int i = 1; i <= MaxClients; i++) {
|
||||
if(IsClientConnected(i) && !IsClientInGame(i)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
stock void GetHorizontalPositionFromClient(int client, float units, float finalPosition[3]) {
|
||||
float pos[3], ang[3];
|
||||
GetClientEyeAngles(client, ang);
|
||||
GetClientAbsOrigin(client, pos);
|
||||
|
||||
float theta = DegToRad(ang[1]);
|
||||
pos[0] += units * Cosine(theta);
|
||||
pos[1] += units * Sine(theta);
|
||||
finalPosition = pos;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
stock void GetAnglesLookAt(int iClient, int iTarget, float fFinalPos[3]) {
|
||||
static float fTargetPos[3];
|
||||
static float fTargetAngles[3];
|
||||
static float fClientPos[3];
|
||||
|
||||
GetEntPropVector(iClient, Prop_Send, "m_vecOrigin", fClientPos);
|
||||
GetClientEyePosition(iTarget, fTargetPos);
|
||||
GetClientEyeAngles(iTarget, fTargetAngles);
|
||||
|
||||
float fVecFinal[3];
|
||||
AddInFrontOf(fTargetPos, fTargetAngles, 7.0, fVecFinal);
|
||||
MakeVectorFromPoints(fClientPos, fVecFinal, fFinalPos);
|
||||
|
||||
GetVectorAngles(fFinalPos, fFinalPos);
|
||||
|
||||
// TeleportEntity(iClient, NULL_VECTOR, fFinalPos, NULL_VECTOR);
|
||||
}
|
||||
stock void AddInFrontOf(const float fVecOrigin[3], const float fVecAngle[3], float fUnits, float fOutPut[3])
|
||||
{
|
||||
float fVecView[3]; GetViewVector(fVecAngle, fVecView);
|
||||
|
||||
fOutPut[0] = fVecView[0] * fUnits + fVecOrigin[0];
|
||||
fOutPut[1] = fVecView[1] * fUnits + fVecOrigin[1];
|
||||
fOutPut[2] = fVecView[2] * fUnits + fVecOrigin[2];
|
||||
}
|
||||
stock void GetViewVector(const float fVecAngle[3], float fOutPut[3])
|
||||
{
|
||||
fOutPut[0] = Cosine(fVecAngle[1] / (180 / FLOAT_PI));
|
||||
fOutPut[1] = Sine(fVecAngle[1] / (180 / FLOAT_PI));
|
||||
fOutPut[2] = -Sine(fVecAngle[0] / (180 / FLOAT_PI));
|
||||
}
|
||||
|
||||
stock void LookAtClient(int iClient, int iTarget) {
|
||||
static float fTargetPos[3];
|
||||
static float fTargetAngles[3];
|
||||
static float fClientPos[3];
|
||||
static float fFinalPos[3];
|
||||
|
||||
GetClientEyePosition(iClient, fClientPos);
|
||||
GetClientEyePosition(iTarget, fTargetPos);
|
||||
GetClientEyeAngles(iTarget, fTargetAngles);
|
||||
|
||||
float fVecFinal[3];
|
||||
AddInFrontOf(fTargetPos, fTargetAngles, 7.0, fVecFinal);
|
||||
MakeVectorFromPoints(fClientPos, fVecFinal, fFinalPos);
|
||||
|
||||
GetVectorAngles(fFinalPos, fFinalPos);
|
||||
|
||||
TeleportEntity(iClient, NULL_VECTOR, fFinalPos, NULL_VECTOR);
|
||||
}
|
||||
|
||||
stock void LookAtPoint(int client, const float targetPos[3]) {
|
||||
static float targetAngles[3];
|
||||
static float clientPos[3];
|
||||
static float fFinalPos[3];
|
||||
|
||||
GetClientEyePosition(client, clientPos);
|
||||
GetClientEyeAngles(client, targetAngles);
|
||||
|
||||
float fVecFinal[3];
|
||||
AddInFrontOf(targetPos, targetAngles, 7.0, fVecFinal);
|
||||
MakeVectorFromPoints(clientPos, fVecFinal, fFinalPos);
|
||||
|
||||
GetVectorAngles(fFinalPos, fFinalPos);
|
||||
|
||||
TeleportEntity(client, NULL_VECTOR, fFinalPos, NULL_VECTOR);
|
||||
}
|
||||
|
||||
bool Filter_IgnoreAll(int entity, int mask) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Ignores seeker
|
||||
int GetPlayersLeftAlive() {
|
||||
int amount = 0;
|
||||
for(int i = 1; i <= MaxClients; i++) {
|
||||
if(i != currentSeeker && IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i) && !IsFakeClient(i)) {
|
||||
amount++;
|
||||
}
|
||||
}
|
||||
return amount;
|
||||
}
|
||||
|
||||
|
||||
void SetPlayerBlind(int target, int amount) {
|
||||
int targets[1];
|
||||
targets[0] = target;
|
||||
|
||||
int duration = 1536;
|
||||
int holdtime = 1536;
|
||||
int flags = (amount == 0) ? (0x0001 | 0x0010) : (0x0002 | 0x0008);
|
||||
int color[4] = { 0, 0, 0, 0 };
|
||||
color[3] = amount;
|
||||
|
||||
Handle message = StartMessageEx(g_FadeUserMsgId, targets, 1);
|
||||
BfWrite bf = UserMessageToBfWrite(message);
|
||||
bf.WriteShort(duration);
|
||||
bf.WriteShort(holdtime);
|
||||
bf.WriteShort(flags);
|
||||
bf.WriteByte(color[0]);
|
||||
bf.WriteByte(color[1]);
|
||||
bf.WriteByte(color[2]);
|
||||
bf.WriteByte(color[3]);
|
||||
EndMessage();
|
||||
}
|
||||
|
||||
#define HIDER_DISTANCE_MAX_SIZE 10
|
||||
|
||||
|
||||
#define MAX_AUTO_VOCALIZATIONS 9
|
||||
static char AUTO_VOCALIZATIONS[MAX_AUTO_VOCALIZATIONS][] = {
|
||||
"PlayerLaugh",
|
||||
"PlayerSpotPill",
|
||||
"Playerlookout",
|
||||
"EatPills",
|
||||
"ReviveMeInterrupted",
|
||||
"PlayerIncapacitated",
|
||||
"PlayerNiceShot",
|
||||
"ResponseSoftDispleasureSwear",
|
||||
"PlayerAreaClear"
|
||||
};
|
||||
|
||||
enum struct HiderDistQueue {
|
||||
int index;
|
||||
float list[HIDER_DISTANCE_MAX_SIZE];
|
||||
int lastVocalize;
|
||||
|
||||
void AddPos(const float pos[3]) {
|
||||
this.list[this.index] = GetVectorDistance(seekerPos, pos);
|
||||
if(++this.index == HIDER_DISTANCE_MAX_SIZE) {
|
||||
this.index = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void Clear() {
|
||||
for(int i = 0; i < HIDER_DISTANCE_MAX_SIZE; i++) {
|
||||
this.list[i] = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
float GetAverage() {
|
||||
float sum = 0.0;
|
||||
for(int i = 0; i < HIDER_DISTANCE_MAX_SIZE; i++) {
|
||||
sum += this.list[i];
|
||||
}
|
||||
return sum / float(HIDER_DISTANCE_MAX_SIZE);
|
||||
}
|
||||
|
||||
void Check(int i) {
|
||||
if(this.GetAverage() > HIDER_MIN_AVG_DISTANCE_AUTO_VOCALIZE) {
|
||||
int time = GetTime();
|
||||
if(time - this.lastVocalize > HIDER_AUTO_VOCALIZE_GRACE_TIME) {
|
||||
this.lastVocalize = time;
|
||||
int index = GetRandomInt(0, MAX_AUTO_VOCALIZATIONS);
|
||||
PerformScene(i, AUTO_VOCALIZATIONS[index]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
HiderDistQueue distQueue[MAXPLAYERS+1];
|
59
scripting/include/guesswho/gwpoints.inc
Normal file
59
scripting/include/guesswho/gwpoints.inc
Normal file
|
@ -0,0 +1,59 @@
|
|||
enum struct LocationMeta {
|
||||
float pos[3];
|
||||
float ang[3];
|
||||
bool runto;
|
||||
bool jump;
|
||||
int attempts; // # of attempts player has moved until they will try to manage
|
||||
}
|
||||
|
||||
// Game settings
|
||||
LocationMeta activeBotLocations[MAXPLAYERS+1];
|
||||
|
||||
methodmap MovePoints < ArrayList {
|
||||
public MovePoints() {
|
||||
return view_as<MovePoints>(new ArrayList(sizeof(LocationMeta)));
|
||||
}
|
||||
|
||||
property float MinFlow {
|
||||
public get() { return flowMin; }
|
||||
}
|
||||
property float MaxFlow {
|
||||
public get() { return flowMax; }
|
||||
}
|
||||
|
||||
public void SetBounds(float min, float max) {
|
||||
flowMin = min;
|
||||
flowMax = max;
|
||||
}
|
||||
|
||||
public void GetRandomPoint(LocationMeta meta) {
|
||||
meta.runto = GetURandomFloat() < BOT_MOVE_RUN_CHANCE;
|
||||
meta.attempts = 0;
|
||||
this.GetArray(GetURandomInt() % this.Length, meta);
|
||||
#if defined DEBUG_SHOW_POINTS
|
||||
Effect_DrawBeamBoxRotatableToAll(meta.pos, DEBUG_POINT_VIEW_MIN, DEBUG_POINT_VIEW_MAX, NULL_VECTOR, g_iLaserIndex, 0, 0, 0, 150.0, 0.1, 0.1, 0, 0.0, {255, 0, 255, 120}, 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
public bool GetRandomPointFar(const float src[3], float pos[3], float distanceAway = 100.0, int tries = 3) {
|
||||
while(tries-- > 0) {
|
||||
this.GetArray(GetURandomInt() % this.Length, pos);
|
||||
if(FloatAbs(GetVectorDistance(src, pos)) > distanceAway) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool AddPoint(LocationMeta meta) {
|
||||
bool hitLimit = false;
|
||||
if(this.Length + 1 > MAX_VALID_LOCATIONS) {
|
||||
PrintToServer("[GuessWho] Hit MAX_VALID_LOCATIONS (%d), clearing some locations", MAX_VALID_LOCATIONS);
|
||||
this.Sort(Sort_Random, Sort_Float);
|
||||
this.Erase(RoundFloat(MAX_VALID_LOCATIONS * MAX_VALID_LOCATIONS_KEEP_PERCENT));
|
||||
hitLimit = true;
|
||||
}
|
||||
this.PushArray(meta);
|
||||
return hitLimit;
|
||||
}
|
||||
}
|
50
scripting/include/guesswho/gwtimers.inc
Normal file
50
scripting/include/guesswho/gwtimers.inc
Normal file
|
@ -0,0 +1,50 @@
|
|||
|
||||
Action Timer_RecordPoints(Handle h, int i) {
|
||||
if(GetEntityFlags(i) & FL_ONGROUND && IsPlayerAlive(i)) {
|
||||
LocationMeta meta;
|
||||
GetClientAbsOrigin(i, meta.pos);
|
||||
GetClientEyeAngles(i, meta.ang);
|
||||
if(meta.pos[0] != vecLastLocation[i][0] || meta.pos[1] != vecLastLocation[i][1] || meta.pos[2] != vecLastLocation[i][2]) {
|
||||
if(movePoints.AddPoint(meta)) {
|
||||
recordTimer = null;
|
||||
return Plugin_Stop;
|
||||
}
|
||||
Effect_DrawBeamBoxRotatableToClient(i, meta.pos, DEBUG_POINT_VIEW_MIN, DEBUG_POINT_VIEW_MAX, NULL_VECTOR, g_iLaserIndex, 0, 0, 0, 150.0, 0.1, 0.1, 0, 0.0, {0, 0, 255, 64}, 0);
|
||||
vecLastLocation[i] = meta.pos;
|
||||
}
|
||||
}
|
||||
PrintHintText(i, "Points: %d / %d", movePoints.Length, MAX_VALID_LOCATIONS);
|
||||
return Plugin_Continue;
|
||||
}
|
||||
|
||||
Action Timer_WaitForPlayers(Handle h) {
|
||||
if(!isEnabled) return Plugin_Stop;
|
||||
if(!Game.IsPendingPlayers()) {
|
||||
isStarting = true;
|
||||
InitGamemode();
|
||||
return Plugin_Stop;
|
||||
}
|
||||
return Plugin_Continue;
|
||||
}
|
||||
|
||||
Action Timer_CheckHiders(Handle h) {
|
||||
static float pos[3];
|
||||
for(int i = 1; i <= MaxClients; i++) {
|
||||
if(IsClientConnected(i) && IsClientInGame(i) && !IsFakeClient(i) && GetClientTeam(i) == 2 && IsPlayerAlive(i)) {
|
||||
GetClientAbsOrigin(i, pos);
|
||||
distQueue[i].AddPos(pos);
|
||||
distQueue[i].Check(i);
|
||||
}
|
||||
}
|
||||
|
||||
return Plugin_Continue;
|
||||
}
|
||||
|
||||
Action Timer_ResetAll(Handle h) {
|
||||
for(int i = 1; i <= MaxClients; i++) {
|
||||
if(IsClientConnected(i) && IsClientInGame(i) && GetClientTeam(i) == 2) {
|
||||
ForcePlayerSuicide(i);
|
||||
}
|
||||
}
|
||||
return Plugin_Handled;
|
||||
}
|
898
scripting/include/multicolors/colors.inc
Normal file
898
scripting/include/multicolors/colors.inc
Normal file
|
@ -0,0 +1,898 @@
|
|||
/**************************************************************************
|
||||
* *
|
||||
* Colored Chat Functions *
|
||||
* Author: exvel, Editor: Popoklopsi, Powerlord, Bara *
|
||||
* Version: 2.0.0-MC *
|
||||
* *
|
||||
**************************************************************************/
|
||||
|
||||
|
||||
#if defined _colors_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _colors_included
|
||||
|
||||
#define MAX_MESSAGE_LENGTH 250
|
||||
#define MAX_COLORS 18
|
||||
|
||||
#define SERVER_INDEX 0
|
||||
#define NO_INDEX -1
|
||||
#define NO_PLAYER -2
|
||||
|
||||
enum C_Colors {
|
||||
Color_Default = 0,
|
||||
Color_Darkred,
|
||||
Color_Green,
|
||||
Color_Lightgreen,
|
||||
Color_Red,
|
||||
Color_Blue,
|
||||
Color_Olive,
|
||||
Color_Lime,
|
||||
Color_Lightred,
|
||||
Color_Purple,
|
||||
Color_Grey,
|
||||
Color_Yellow,
|
||||
Color_Orange,
|
||||
Color_Bluegrey,
|
||||
Color_Lightblue,
|
||||
Color_Darkblue,
|
||||
Color_Grey2,
|
||||
Color_Orchid,
|
||||
Color_Lightred2
|
||||
}
|
||||
|
||||
/* C_Colors' properties */
|
||||
char C_Tag[][] = {"{default}", "{darkred}", "{green}", "{lightgreen}", "{red}", "{blue}", "{olive}", "{lime}", "{lightred}", "{purple}", "{grey}", "{yellow}", "{orange}", "{bluegrey}", "{lightblue}", "{darkblue}", "{grey2}", "{orchid}", "{lightred2}"};
|
||||
char C_TagCode[][] = {"\x01", "\x02", "\x04", "\x03", "\x03", "\x03", "\x05", "\x06", "\x07", "\x03", "\x08", "\x09", "\x10", "\x0A", "\x0B", "\x0C", "\x0D", "\x0E", "\x0F"};
|
||||
bool C_TagReqSayText2[] = {false, false, false, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false};
|
||||
bool C_EventIsHooked;
|
||||
bool C_SkipList[MAXPLAYERS+1];
|
||||
|
||||
/* Game default profile */
|
||||
bool C_Profile_Colors[] = {true, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false};
|
||||
int C_Profile_TeamIndex[] = {NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX};
|
||||
bool C_Profile_SayText2;
|
||||
|
||||
static ConVar sm_show_activity;
|
||||
|
||||
/**
|
||||
* Prints a message to a specific client in the chat area.
|
||||
* Supports color tags.
|
||||
*
|
||||
* @param client Client index.
|
||||
* @param szMessage Message (formatting rules).
|
||||
* @return No return
|
||||
*
|
||||
* On error/Errors: If the client is not connected an error will be thrown.
|
||||
*/
|
||||
stock void C_PrintToChat(int client, const char[] szMessage, any ...) {
|
||||
if (client <= 0 || client > MaxClients) {
|
||||
ThrowError("Invalid client index %d", client);
|
||||
}
|
||||
|
||||
if (!IsClientInGame(client)) {
|
||||
ThrowError("Client %d is not in game", client);
|
||||
}
|
||||
|
||||
char szBuffer[MAX_MESSAGE_LENGTH];
|
||||
char szCMessage[MAX_MESSAGE_LENGTH];
|
||||
|
||||
SetGlobalTransTarget(client);
|
||||
|
||||
Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage);
|
||||
VFormat(szCMessage, sizeof(szCMessage), szBuffer, 3);
|
||||
|
||||
int index = C_Format(szCMessage, sizeof(szCMessage));
|
||||
|
||||
if (index == NO_INDEX) {
|
||||
PrintToChat(client, "%s", szCMessage);
|
||||
}
|
||||
else {
|
||||
C_SayText2(client, index, szCMessage);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reples to a message in a command. A client index of 0 will use PrintToServer().
|
||||
* If the command was from the console, PrintToConsole() is used. If the command was from chat, C_PrintToChat() is used.
|
||||
* Supports color tags.
|
||||
*
|
||||
* @param client Client index, or 0 for server.
|
||||
* @param szMessage Formatting rules.
|
||||
* @param ... Variable number of format parameters.
|
||||
* @return No return
|
||||
*
|
||||
* On error/Errors: If the client is not connected or invalid.
|
||||
*/
|
||||
stock void C_ReplyToCommand(int client, const char[] szMessage, any ...) {
|
||||
char szCMessage[MAX_MESSAGE_LENGTH];
|
||||
SetGlobalTransTarget(client);
|
||||
VFormat(szCMessage, sizeof(szCMessage), szMessage, 3);
|
||||
|
||||
if (client == 0) {
|
||||
C_RemoveTags(szCMessage, sizeof(szCMessage));
|
||||
PrintToServer("%s", szCMessage);
|
||||
}
|
||||
else if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) {
|
||||
C_RemoveTags(szCMessage, sizeof(szCMessage));
|
||||
PrintToConsole(client, "%s", szCMessage);
|
||||
}
|
||||
else {
|
||||
C_PrintToChat(client, "%s", szCMessage);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reples to a message in a command. A client index of 0 will use PrintToServer().
|
||||
* If the command was from the console, PrintToConsole() is used. If the command was from chat, C_PrintToChat() is used.
|
||||
* Supports color tags.
|
||||
*
|
||||
* @param client Client index, or 0 for server.
|
||||
* @param author Author index whose color will be used for teamcolor tag.
|
||||
* @param szMessage Formatting rules.
|
||||
* @param ... Variable number of format parameters.
|
||||
* @return No return
|
||||
*
|
||||
* On error/Errors: If the client is not connected or invalid.
|
||||
*/
|
||||
stock void C_ReplyToCommandEx(int client, int author, const char[] szMessage, any ...) {
|
||||
char szCMessage[MAX_MESSAGE_LENGTH];
|
||||
SetGlobalTransTarget(client);
|
||||
VFormat(szCMessage, sizeof(szCMessage), szMessage, 4);
|
||||
|
||||
if (client == 0) {
|
||||
C_RemoveTags(szCMessage, sizeof(szCMessage));
|
||||
PrintToServer("%s", szCMessage);
|
||||
}
|
||||
else if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) {
|
||||
C_RemoveTags(szCMessage, sizeof(szCMessage));
|
||||
PrintToConsole(client, "%s", szCMessage);
|
||||
}
|
||||
else {
|
||||
C_PrintToChatEx(client, author, "%s", szCMessage);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a message to all clients in the chat area.
|
||||
* Supports color tags.
|
||||
*
|
||||
* @param client Client index.
|
||||
* @param szMessage Message (formatting rules)
|
||||
* @return No return
|
||||
*/
|
||||
stock void C_PrintToChatAll(const char[] szMessage, any ...) {
|
||||
char szBuffer[MAX_MESSAGE_LENGTH];
|
||||
|
||||
for (int i = 1; i <= MaxClients; ++i) {
|
||||
if (IsClientInGame(i) && !IsFakeClient(i) && !C_SkipList[i]) {
|
||||
SetGlobalTransTarget(i);
|
||||
VFormat(szBuffer, sizeof(szBuffer), szMessage, 2);
|
||||
|
||||
C_PrintToChat(i, "%s", szBuffer);
|
||||
}
|
||||
|
||||
C_SkipList[i] = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a message to a specific client in the chat area.
|
||||
* Supports color tags and teamcolor tag.
|
||||
*
|
||||
* @param client Client index.
|
||||
* @param author Author index whose color will be used for teamcolor tag.
|
||||
* @param szMessage Message (formatting rules).
|
||||
* @return No return
|
||||
*
|
||||
* On error/Errors: If the client or author are not connected an error will be thrown.
|
||||
*/
|
||||
stock void C_PrintToChatEx(int client, int author, const char[] szMessage, any ...) {
|
||||
if (client <= 0 || client > MaxClients) {
|
||||
ThrowError("Invalid client index %d", client);
|
||||
}
|
||||
|
||||
if (!IsClientInGame(client)) {
|
||||
ThrowError("Client %d is not in game", client);
|
||||
}
|
||||
|
||||
if (author < 0 || author > MaxClients) {
|
||||
ThrowError("Invalid client index %d", author);
|
||||
}
|
||||
|
||||
char szBuffer[MAX_MESSAGE_LENGTH];
|
||||
char szCMessage[MAX_MESSAGE_LENGTH];
|
||||
|
||||
SetGlobalTransTarget(client);
|
||||
|
||||
Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage);
|
||||
VFormat(szCMessage, sizeof(szCMessage), szBuffer, 4);
|
||||
|
||||
int index = C_Format(szCMessage, sizeof(szCMessage), author);
|
||||
|
||||
if (index == NO_INDEX) {
|
||||
PrintToChat(client, "%s", szCMessage);
|
||||
}
|
||||
else {
|
||||
C_SayText2(client, author, szCMessage);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a message to all clients in the chat area.
|
||||
* Supports color tags and teamcolor tag.
|
||||
*
|
||||
* @param author Author index whos color will be used for teamcolor tag.
|
||||
* @param szMessage Message (formatting rules).
|
||||
* @return No return
|
||||
*
|
||||
* On error/Errors: If the author is not connected an error will be thrown.
|
||||
*/
|
||||
stock void C_PrintToChatAllEx(int author, const char[] szMessage, any ...) {
|
||||
if (author < 0 || author > MaxClients) {
|
||||
ThrowError("Invalid client index %d", author);
|
||||
}
|
||||
|
||||
if (!IsClientInGame(author)) {
|
||||
ThrowError("Client %d is not in game", author);
|
||||
}
|
||||
|
||||
char szBuffer[MAX_MESSAGE_LENGTH];
|
||||
|
||||
for (int i = 1; i <= MaxClients; ++i) {
|
||||
if (IsClientInGame(i) && !IsFakeClient(i) && !C_SkipList[i]) {
|
||||
SetGlobalTransTarget(i);
|
||||
VFormat(szBuffer, sizeof(szBuffer), szMessage, 3);
|
||||
|
||||
C_PrintToChatEx(i, author, "%s", szBuffer);
|
||||
}
|
||||
|
||||
C_SkipList[i] = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes color tags from the string.
|
||||
*
|
||||
* @param szMessage String.
|
||||
* @return No return
|
||||
*/
|
||||
stock void C_RemoveTags(char[] szMessage, int maxlength) {
|
||||
for (int i = 0; i < MAX_COLORS; i++) {
|
||||
ReplaceString(szMessage, maxlength, C_Tag[i], "", false);
|
||||
}
|
||||
|
||||
ReplaceString(szMessage, maxlength, "{teamcolor}", "", false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a color is allowed or not
|
||||
*
|
||||
* @param tag Color Tag.
|
||||
* @return True when color is supported, otherwise false
|
||||
*/
|
||||
stock bool C_ColorAllowed(C_Colors color) {
|
||||
if (!C_EventIsHooked) {
|
||||
C_SetupProfile();
|
||||
|
||||
C_EventIsHooked = true;
|
||||
}
|
||||
|
||||
return C_Profile_Colors[color];
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the color with another color
|
||||
* Handle with care!
|
||||
*
|
||||
* @param color color to replace.
|
||||
* @param newColor color to replace with.
|
||||
* @noreturn
|
||||
*/
|
||||
stock void C_ReplaceColor(C_Colors color, C_Colors newColor) {
|
||||
if (!C_EventIsHooked) {
|
||||
C_SetupProfile();
|
||||
|
||||
C_EventIsHooked = true;
|
||||
}
|
||||
|
||||
C_Profile_Colors[color] = C_Profile_Colors[newColor];
|
||||
C_Profile_TeamIndex[color] = C_Profile_TeamIndex[newColor];
|
||||
|
||||
C_TagReqSayText2[color] = C_TagReqSayText2[newColor];
|
||||
Format(C_TagCode[color], sizeof(C_TagCode[]), C_TagCode[newColor]);
|
||||
}
|
||||
|
||||
/**
|
||||
* This function should only be used right in front of
|
||||
* C_PrintToChatAll or C_PrintToChatAllEx and it tells
|
||||
* to those funcions to skip specified client when printing
|
||||
* message to all clients. After message is printed client will
|
||||
* no more be skipped.
|
||||
*
|
||||
* @param client Client index
|
||||
* @return No return
|
||||
*/
|
||||
stock void C_SkipNextClient(int client) {
|
||||
if (client <= 0 || client > MaxClients) {
|
||||
ThrowError("Invalid client index %d", client);
|
||||
}
|
||||
|
||||
C_SkipList[client] = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces color tags in a string with color codes
|
||||
*
|
||||
* @param szMessage String.
|
||||
* @param maxlength Maximum length of the string buffer.
|
||||
* @return Client index that can be used for SayText2 author index
|
||||
*
|
||||
* On error/Errors: If there is more then one team color is used an error will be thrown.
|
||||
*/
|
||||
stock int C_Format(char[] szMessage, int maxlength, int author = NO_INDEX) {
|
||||
/* Hook event for auto profile setup on map start */
|
||||
if (!C_EventIsHooked) {
|
||||
C_SetupProfile();
|
||||
HookEvent("server_spawn", C_Event_MapStart, EventHookMode_PostNoCopy);
|
||||
|
||||
C_EventIsHooked = true;
|
||||
}
|
||||
|
||||
int iRandomPlayer = NO_INDEX;
|
||||
|
||||
// On CS:GO set invisible precolor
|
||||
if (GetEngineVersion() == Engine_CSGO) {
|
||||
Format(szMessage, maxlength, " %s", szMessage);
|
||||
}
|
||||
|
||||
/* If author was specified replace {teamcolor} tag */
|
||||
if (author != NO_INDEX) {
|
||||
if (C_Profile_SayText2) {
|
||||
ReplaceString(szMessage, maxlength, "{teamcolor}", "\x03", false);
|
||||
|
||||
iRandomPlayer = author;
|
||||
}
|
||||
/* If saytext2 is not supported by game replace {teamcolor} with green tag */
|
||||
else {
|
||||
ReplaceString(szMessage, maxlength, "{teamcolor}", C_TagCode[Color_Green], false);
|
||||
}
|
||||
}
|
||||
else {
|
||||
ReplaceString(szMessage, maxlength, "{teamcolor}", "", false);
|
||||
}
|
||||
|
||||
/* For other color tags we need a loop */
|
||||
for (int i = 0; i < MAX_COLORS; i++) {
|
||||
/* If tag not found - skip */
|
||||
if (StrContains(szMessage, C_Tag[i], false) == -1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
/* If tag is not supported by game replace it with green tag */
|
||||
else if (!C_Profile_Colors[i]) {
|
||||
ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[Color_Green], false);
|
||||
}
|
||||
|
||||
/* If tag doesn't need saytext2 simply replace */
|
||||
else if (!C_TagReqSayText2[i]) {
|
||||
ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[i], false);
|
||||
}
|
||||
|
||||
/* Tag needs saytext2 */
|
||||
else {
|
||||
/* If saytext2 is not supported by game replace tag with green tag */
|
||||
if (!C_Profile_SayText2) {
|
||||
ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[Color_Green], false);
|
||||
}
|
||||
|
||||
/* Game supports saytext2 */
|
||||
else {
|
||||
/* If random player for tag wasn't specified replace tag and find player */
|
||||
if (iRandomPlayer == NO_INDEX) {
|
||||
/* Searching for valid client for tag */
|
||||
iRandomPlayer = C_FindRandomPlayerByTeam(C_Profile_TeamIndex[i]);
|
||||
|
||||
/* If player not found replace tag with green color tag */
|
||||
if (iRandomPlayer == NO_PLAYER) {
|
||||
ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[Color_Green], false);
|
||||
}
|
||||
|
||||
/* If player was found simply replace */
|
||||
else {
|
||||
ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[i], false);
|
||||
}
|
||||
|
||||
}
|
||||
/* If found another team color tag throw error */
|
||||
else {
|
||||
//ReplaceString(szMessage, maxlength, C_Tag[i], "");
|
||||
ThrowError("Using two team colors in one message is not allowed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return iRandomPlayer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a random player with specified team
|
||||
*
|
||||
* @param color_team Client team.
|
||||
* @return Client index or NO_PLAYER if no player found
|
||||
*/
|
||||
stock int C_FindRandomPlayerByTeam(int color_team) {
|
||||
if (color_team == SERVER_INDEX) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int[] players = new int[MaxClients];
|
||||
int count;
|
||||
|
||||
for (int i = 1; i <= MaxClients; ++i) {
|
||||
if (IsClientInGame(i) && GetClientTeam(i) == color_team) {
|
||||
players[count++] = i;
|
||||
}
|
||||
}
|
||||
|
||||
if (count) {
|
||||
return players[GetRandomInt(0, count-1)];
|
||||
}
|
||||
|
||||
return NO_PLAYER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a SayText2 usermessage to a client
|
||||
*
|
||||
* @param szMessage Client index
|
||||
* @param maxlength Author index
|
||||
* @param szMessage Message
|
||||
* @return No return.
|
||||
*/
|
||||
stock void C_SayText2(int client, int author, const char[] szMessage) {
|
||||
Handle hBuffer = StartMessageOne("SayText2", client, USERMSG_RELIABLE|USERMSG_BLOCKHOOKS);
|
||||
|
||||
if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) {
|
||||
Protobuf pb = UserMessageToProtobuf(hBuffer);
|
||||
pb.SetInt("ent_idx", author);
|
||||
pb.SetBool("chat", true);
|
||||
pb.SetString("msg_name", szMessage);
|
||||
pb.AddString("params", "");
|
||||
pb.AddString("params", "");
|
||||
pb.AddString("params", "");
|
||||
pb.AddString("params", "");
|
||||
}
|
||||
else {
|
||||
BfWrite bf = UserMessageToBfWrite(hBuffer);
|
||||
bf.WriteByte(author);
|
||||
bf.WriteByte(true);
|
||||
bf.WriteString(szMessage);
|
||||
}
|
||||
|
||||
EndMessage();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates game color profile
|
||||
* This function must be edited if you want to add more games support
|
||||
*
|
||||
* @return No return.
|
||||
*/
|
||||
stock void C_SetupProfile() {
|
||||
EngineVersion engine = GetEngineVersion();
|
||||
|
||||
if (engine == Engine_CSS) {
|
||||
C_Profile_Colors[Color_Lightgreen] = true;
|
||||
C_Profile_Colors[Color_Red] = true;
|
||||
C_Profile_Colors[Color_Blue] = true;
|
||||
C_Profile_Colors[Color_Olive] = true;
|
||||
C_Profile_TeamIndex[Color_Lightgreen] = SERVER_INDEX;
|
||||
C_Profile_TeamIndex[Color_Red] = 2;
|
||||
C_Profile_TeamIndex[Color_Blue] = 3;
|
||||
C_Profile_SayText2 = true;
|
||||
}
|
||||
else if (engine == Engine_CSGO) {
|
||||
C_Profile_Colors[Color_Red] = true;
|
||||
C_Profile_Colors[Color_Blue] = true;
|
||||
C_Profile_Colors[Color_Olive] = true;
|
||||
C_Profile_Colors[Color_Darkred] = true;
|
||||
C_Profile_Colors[Color_Lime] = true;
|
||||
C_Profile_Colors[Color_Lightred] = true;
|
||||
C_Profile_Colors[Color_Purple] = true;
|
||||
C_Profile_Colors[Color_Grey] = true;
|
||||
C_Profile_Colors[Color_Yellow] = true;
|
||||
C_Profile_Colors[Color_Orange] = true;
|
||||
C_Profile_Colors[Color_Bluegrey] = true;
|
||||
C_Profile_Colors[Color_Lightblue] = true;
|
||||
C_Profile_Colors[Color_Darkblue] = true;
|
||||
C_Profile_Colors[Color_Grey2] = true;
|
||||
C_Profile_Colors[Color_Orchid] = true;
|
||||
C_Profile_Colors[Color_Lightred2] = true;
|
||||
C_Profile_TeamIndex[Color_Red] = 2;
|
||||
C_Profile_TeamIndex[Color_Blue] = 3;
|
||||
C_Profile_SayText2 = true;
|
||||
}
|
||||
else if (engine == Engine_TF2) {
|
||||
C_Profile_Colors[Color_Lightgreen] = true;
|
||||
C_Profile_Colors[Color_Red] = true;
|
||||
C_Profile_Colors[Color_Blue] = true;
|
||||
C_Profile_Colors[Color_Olive] = true;
|
||||
C_Profile_TeamIndex[Color_Lightgreen] = SERVER_INDEX;
|
||||
C_Profile_TeamIndex[Color_Red] = 2;
|
||||
C_Profile_TeamIndex[Color_Blue] = 3;
|
||||
C_Profile_SayText2 = true;
|
||||
}
|
||||
else if (engine == Engine_Left4Dead || engine == Engine_Left4Dead2) {
|
||||
C_Profile_Colors[Color_Lightgreen] = true;
|
||||
C_Profile_Colors[Color_Red] = true;
|
||||
C_Profile_Colors[Color_Blue] = true;
|
||||
C_Profile_Colors[Color_Olive] = true;
|
||||
C_Profile_TeamIndex[Color_Lightgreen] = SERVER_INDEX;
|
||||
C_Profile_TeamIndex[Color_Red] = 3;
|
||||
C_Profile_TeamIndex[Color_Blue] = 2;
|
||||
C_Profile_SayText2 = true;
|
||||
}
|
||||
else if (engine == Engine_HL2DM) {
|
||||
/* hl2mp profile is based on mp_teamplay convar */
|
||||
if (GetConVarBool(FindConVar("mp_teamplay"))) {
|
||||
C_Profile_Colors[Color_Red] = true;
|
||||
C_Profile_Colors[Color_Blue] = true;
|
||||
C_Profile_Colors[Color_Olive] = true;
|
||||
C_Profile_TeamIndex[Color_Red] = 3;
|
||||
C_Profile_TeamIndex[Color_Blue] = 2;
|
||||
C_Profile_SayText2 = true;
|
||||
}
|
||||
else {
|
||||
C_Profile_SayText2 = false;
|
||||
C_Profile_Colors[Color_Olive] = true;
|
||||
}
|
||||
}
|
||||
else if (engine == Engine_DODS) {
|
||||
C_Profile_Colors[Color_Olive] = true;
|
||||
C_Profile_SayText2 = false;
|
||||
}
|
||||
/* Profile for other games */
|
||||
else {
|
||||
if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID) {
|
||||
C_Profile_SayText2 = false;
|
||||
}
|
||||
else {
|
||||
C_Profile_Colors[Color_Red] = true;
|
||||
C_Profile_Colors[Color_Blue] = true;
|
||||
C_Profile_TeamIndex[Color_Red] = 2;
|
||||
C_Profile_TeamIndex[Color_Blue] = 3;
|
||||
C_Profile_SayText2 = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Action C_Event_MapStart(Event event, const char[] name, bool dontBroadcast) {
|
||||
C_SetupProfile();
|
||||
|
||||
for (int i = 1; i <= MaxClients; ++i) {
|
||||
C_SkipList[i] = false;
|
||||
}
|
||||
return Plugin_Continue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays usage of an admin command to users depending on the
|
||||
* setting of the sm_show_activity cvar.
|
||||
*
|
||||
* This version does not display a message to the originating client
|
||||
* if used from chat triggers or menus. If manual replies are used
|
||||
* for these cases, then this function will suffice. Otherwise,
|
||||
* C_ShowActivity2() is slightly more useful.
|
||||
* Supports color tags.
|
||||
*
|
||||
* @param client Client index doing the action, or 0 for server.
|
||||
* @param format Formatting rules.
|
||||
* @param ... Variable number of format parameters.
|
||||
* @noreturn
|
||||
* @error
|
||||
*/
|
||||
stock int C_ShowActivity(int client, const char[] format, any ...) {
|
||||
if (sm_show_activity == null) {
|
||||
sm_show_activity = FindConVar("sm_show_activity");
|
||||
}
|
||||
|
||||
char tag[] = "[SM] ";
|
||||
|
||||
char szBuffer[MAX_MESSAGE_LENGTH];
|
||||
//char szCMessage[MAX_MESSAGE_LENGTH];
|
||||
int value = sm_show_activity.IntValue;
|
||||
ReplySource replyto = GetCmdReplySource();
|
||||
|
||||
char name[MAX_NAME_LENGTH] = "Console";
|
||||
char sign[MAX_NAME_LENGTH] = "ADMIN";
|
||||
bool display_in_chat = false;
|
||||
if (client != 0) {
|
||||
if (client < 0 || client > MaxClients || !IsClientConnected(client)) {
|
||||
ThrowError("Client index %d is invalid", client);
|
||||
}
|
||||
|
||||
GetClientName(client, name, sizeof(name));
|
||||
AdminId id = GetUserAdmin(client);
|
||||
if (id == INVALID_ADMIN_ID || !GetAdminFlag(id, Admin_Generic, Access_Effective)) {
|
||||
sign = "PLAYER";
|
||||
}
|
||||
|
||||
/* Display the message to the client? */
|
||||
if (replyto == SM_REPLY_TO_CONSOLE) {
|
||||
SetGlobalTransTarget(client);
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 3);
|
||||
|
||||
C_RemoveTags(szBuffer, sizeof(szBuffer));
|
||||
PrintToConsole(client, "%s%s\n", tag, szBuffer);
|
||||
display_in_chat = true;
|
||||
}
|
||||
}
|
||||
else {
|
||||
SetGlobalTransTarget(LANG_SERVER);
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 3);
|
||||
|
||||
C_RemoveTags(szBuffer, sizeof(szBuffer));
|
||||
PrintToServer("%s%s\n", tag, szBuffer);
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
for (int i = 1; i <= MaxClients; ++i) {
|
||||
if (!IsClientInGame(i) || IsFakeClient(i) || (display_in_chat && i == client)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
AdminId id = GetUserAdmin(i);
|
||||
SetGlobalTransTarget(i);
|
||||
if (id == INVALID_ADMIN_ID || !GetAdminFlag(id, Admin_Generic, Access_Effective)) {
|
||||
/* Treat this as a normal user. */
|
||||
if ((value & 1) | (value & 2)) {
|
||||
char newsign[MAX_NAME_LENGTH];
|
||||
|
||||
if ((value & 2) || (i == client)) {
|
||||
newsign = name;
|
||||
}
|
||||
else {
|
||||
newsign = sign;
|
||||
}
|
||||
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 3);
|
||||
|
||||
C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
|
||||
}
|
||||
}
|
||||
else {
|
||||
/* Treat this as an admin user */
|
||||
bool is_root = GetAdminFlag(id, Admin_Root, Access_Effective);
|
||||
if ((value & 4) || (value & 8) || ((value & 16) && is_root)) {
|
||||
char newsign[MAX_NAME_LENGTH];
|
||||
|
||||
if ((value & 8) || ((value & 16) && is_root) || (i == client)) {
|
||||
newsign = name;
|
||||
}
|
||||
else {
|
||||
newsign = sign;
|
||||
}
|
||||
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 3);
|
||||
|
||||
C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as C_ShowActivity(), except the tag parameter is used instead of "[SM] " (note that you must supply any spacing).
|
||||
* Supports color tags.
|
||||
*
|
||||
* @param client Client index doing the action, or 0 for server.
|
||||
* @param tags Tag to display with.
|
||||
* @param format Formatting rules.
|
||||
* @param ... Variable number of format parameters.
|
||||
* @noreturn
|
||||
* @error
|
||||
*/
|
||||
stock int C_ShowActivityEx(int client, const char[] tag, const char[] format, any ...) {
|
||||
if (sm_show_activity == null) {
|
||||
sm_show_activity = FindConVar("sm_show_activity");
|
||||
}
|
||||
|
||||
char szBuffer[MAX_MESSAGE_LENGTH];
|
||||
//char szCMessage[MAX_MESSAGE_LENGTH];
|
||||
int value = sm_show_activity.IntValue;
|
||||
ReplySource replyto = GetCmdReplySource();
|
||||
|
||||
char name[MAX_NAME_LENGTH] = "Console";
|
||||
char sign[MAX_NAME_LENGTH] = "ADMIN";
|
||||
bool display_in_chat = false;
|
||||
if (client != 0) {
|
||||
if (client < 0 || client > MaxClients || !IsClientConnected(client)) {
|
||||
ThrowError("Client index %d is invalid", client);
|
||||
}
|
||||
|
||||
GetClientName(client, name, sizeof(name));
|
||||
AdminId id = GetUserAdmin(client);
|
||||
if (id == INVALID_ADMIN_ID || !GetAdminFlag(id, Admin_Generic, Access_Effective)) {
|
||||
sign = "PLAYER";
|
||||
}
|
||||
|
||||
/* Display the message to the client? */
|
||||
if (replyto == SM_REPLY_TO_CONSOLE) {
|
||||
SetGlobalTransTarget(client);
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
C_RemoveTags(szBuffer, sizeof(szBuffer));
|
||||
PrintToConsole(client, "%s%s\n", tag, szBuffer);
|
||||
display_in_chat = true;
|
||||
}
|
||||
}
|
||||
else {
|
||||
SetGlobalTransTarget(LANG_SERVER);
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
C_RemoveTags(szBuffer, sizeof(szBuffer));
|
||||
PrintToServer("%s%s\n", tag, szBuffer);
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
for (int i = 1; i <= MaxClients; ++i) {
|
||||
if (!IsClientInGame(i) || IsFakeClient(i) || (display_in_chat && i == client)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
AdminId id = GetUserAdmin(i);
|
||||
SetGlobalTransTarget(i);
|
||||
if (id == INVALID_ADMIN_ID || !GetAdminFlag(id, Admin_Generic, Access_Effective)) {
|
||||
/* Treat this as a normal user. */
|
||||
if ((value & 1) | (value & 2)) {
|
||||
char newsign[MAX_NAME_LENGTH];
|
||||
|
||||
if ((value & 2) || (i == client)) {
|
||||
newsign = name;
|
||||
}
|
||||
else {
|
||||
newsign = sign;
|
||||
}
|
||||
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
|
||||
}
|
||||
}
|
||||
else {
|
||||
/* Treat this as an admin user */
|
||||
bool is_root = GetAdminFlag(id, Admin_Root, Access_Effective);
|
||||
if ((value & 4) || (value & 8) || ((value & 16) && is_root)) {
|
||||
char newsign[MAX_NAME_LENGTH];
|
||||
|
||||
if ((value & 8) || ((value & 16) && is_root) || (i == client)) {
|
||||
newsign = name;
|
||||
}
|
||||
else {
|
||||
newsign = sign;
|
||||
}
|
||||
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays usage of an admin command to users depending on the setting of the sm_show_activity cvar.
|
||||
* All users receive a message in their chat text, except for the originating client,
|
||||
* who receives the message based on the current ReplySource.
|
||||
* Supports color tags.
|
||||
*
|
||||
* @param client Client index doing the action, or 0 for server.
|
||||
* @param tags Tag to prepend to the message.
|
||||
* @param format Formatting rules.
|
||||
* @param ... Variable number of format parameters.
|
||||
* @noreturn
|
||||
* @error
|
||||
*/
|
||||
stock int C_ShowActivity2(int client, const char[] tag, const char[] format, any ...) {
|
||||
if (sm_show_activity == null) {
|
||||
sm_show_activity = FindConVar("sm_show_activity");
|
||||
}
|
||||
|
||||
char szBuffer[MAX_MESSAGE_LENGTH];
|
||||
//char szCMessage[MAX_MESSAGE_LENGTH];
|
||||
int value = sm_show_activity.IntValue;
|
||||
// ReplySource replyto = GetCmdReplySource();
|
||||
|
||||
char name[MAX_NAME_LENGTH] = "Console";
|
||||
char sign[MAX_NAME_LENGTH] = "ADMIN";
|
||||
if (client != 0) {
|
||||
if (client < 0 || client > MaxClients || !IsClientConnected(client)) {
|
||||
ThrowError("Client index %d is invalid", client);
|
||||
}
|
||||
|
||||
GetClientName(client, name, sizeof(name));
|
||||
AdminId id = GetUserAdmin(client);
|
||||
if (id == INVALID_ADMIN_ID || !GetAdminFlag(id, Admin_Generic, Access_Effective)) {
|
||||
sign = "PLAYER";
|
||||
}
|
||||
|
||||
SetGlobalTransTarget(client);
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
/* We don't display directly to the console because the chat text
|
||||
* simply gets added to the console, so we don't want it to print
|
||||
* twice.
|
||||
*/
|
||||
C_PrintToChatEx(client, client, "%s%s", tag, szBuffer);
|
||||
}
|
||||
else {
|
||||
SetGlobalTransTarget(LANG_SERVER);
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
C_RemoveTags(szBuffer, sizeof(szBuffer));
|
||||
PrintToServer("%s%s\n", tag, szBuffer);
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
for (int i = 1; i <= MaxClients; ++i) {
|
||||
if (!IsClientInGame(i) || IsFakeClient(i) || i == client) {
|
||||
continue;
|
||||
}
|
||||
|
||||
AdminId id = GetUserAdmin(i);
|
||||
SetGlobalTransTarget(i);
|
||||
if (id == INVALID_ADMIN_ID
|
||||
|| !GetAdminFlag(id, Admin_Generic, Access_Effective)) {
|
||||
/* Treat this as a normal user. */
|
||||
if ((value & 1) | (value & 2)) {
|
||||
char newsign[MAX_NAME_LENGTH];
|
||||
|
||||
if ((value & 2)) {
|
||||
newsign = name;
|
||||
}
|
||||
else {
|
||||
newsign = sign;
|
||||
}
|
||||
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
|
||||
}
|
||||
}
|
||||
else {
|
||||
/* Treat this as an admin user */
|
||||
bool is_root = GetAdminFlag(id, Admin_Root, Access_Effective);
|
||||
if ((value & 4) || (value & 8) || ((value & 16) && is_root)) {
|
||||
char newsign[MAX_NAME_LENGTH];
|
||||
|
||||
if ((value & 8) || ((value & 16) && is_root)) {
|
||||
newsign = name;
|
||||
}
|
||||
else {
|
||||
newsign = sign;
|
||||
}
|
||||
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
992
scripting/include/multicolors/morecolors.inc
Normal file
992
scripting/include/multicolors/morecolors.inc
Normal file
|
@ -0,0 +1,992 @@
|
|||
// MOAR COLORS
|
||||
// By Dr. McKay
|
||||
// Inspired by: https://forums.alliedmods.net/showthread.php?t=96831
|
||||
|
||||
#if defined _more_colors_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _more_colors_included
|
||||
|
||||
#pragma newdecls optional
|
||||
#include <regex>
|
||||
|
||||
#define MORE_COLORS_VERSION "2.0.0-MC"
|
||||
#define MC_MAX_MESSAGE_LENGTH 256
|
||||
#define MAX_BUFFER_LENGTH (MC_MAX_MESSAGE_LENGTH * 4)
|
||||
|
||||
#define MCOLOR_RED 0xFF4040
|
||||
#define MCOLOR_BLUE 0x99CCFF
|
||||
#define MCOLOR_GRAY 0xCCCCCC
|
||||
#define MCOLOR_GREEN 0x3EFF3E
|
||||
|
||||
#define MC_GAME_DODS 0
|
||||
|
||||
bool MC_SkipList[MAXPLAYERS+1];
|
||||
StringMap MC_Trie;
|
||||
int MC_TeamColors[][] = {{0xCCCCCC, 0x4D7942, 0xFF4040}}; // Multi-dimensional array for games that don't support SayText2. First index is the game index (as defined by the GAME_ defines), second index is team. 0 = spectator, 1 = team1, 2 = team2
|
||||
|
||||
static ConVar sm_show_activity;
|
||||
|
||||
/**
|
||||
* Prints a message to a specific client in the chat area.
|
||||
* Supports color tags.
|
||||
*
|
||||
* @param client Client index.
|
||||
* @param message Message (formatting rules).
|
||||
*
|
||||
* On error/Errors: If the client is not connected an error will be thrown.
|
||||
*/
|
||||
stock void MC_PrintToChat(int client, const char[] message, any ...) {
|
||||
MC_CheckTrie();
|
||||
|
||||
if (client <= 0 || client > MaxClients) {
|
||||
ThrowError("Invalid client index %i", client);
|
||||
}
|
||||
|
||||
if (!IsClientInGame(client)) {
|
||||
ThrowError("Client %i is not in game", client);
|
||||
}
|
||||
|
||||
char buffer[MAX_BUFFER_LENGTH];
|
||||
char buffer2[MAX_BUFFER_LENGTH];
|
||||
|
||||
SetGlobalTransTarget(client);
|
||||
Format(buffer, sizeof(buffer), "\x01%s", message);
|
||||
VFormat(buffer2, sizeof(buffer2), buffer, 3);
|
||||
|
||||
MC_ReplaceColorCodes(buffer2);
|
||||
MC_SendMessage(client, buffer2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a message to all clients in the chat area.
|
||||
* Supports color tags.
|
||||
*
|
||||
* @param client Client index.
|
||||
* @param message Message (formatting rules).
|
||||
*/
|
||||
stock void MC_PrintToChatAll(const char[] message, any ...) {
|
||||
MC_CheckTrie();
|
||||
|
||||
char buffer[MAX_BUFFER_LENGTH], buffer2[MAX_BUFFER_LENGTH];
|
||||
|
||||
for (int i = 1; i <= MaxClients; ++i) {
|
||||
if (!IsClientInGame(i) || MC_SkipList[i]) {
|
||||
MC_SkipList[i] = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
SetGlobalTransTarget(i);
|
||||
Format(buffer, sizeof(buffer), "\x01%s", message);
|
||||
VFormat(buffer2, sizeof(buffer2), buffer, 2);
|
||||
|
||||
MC_ReplaceColorCodes(buffer2);
|
||||
MC_SendMessage(i, buffer2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a message to a specific client in the chat area.
|
||||
* Supports color tags and teamcolor tag.
|
||||
*
|
||||
* @param client Client index.
|
||||
* @param author Author index whose color will be used for teamcolor tag.
|
||||
* @param message Message (formatting rules).
|
||||
*
|
||||
* On error/Errors: If the client or author are not connected an error will be thrown
|
||||
*/
|
||||
stock void MC_PrintToChatEx(int client, int author, const char[] message, any ...) {
|
||||
MC_CheckTrie();
|
||||
|
||||
if (client <= 0 || client > MaxClients) {
|
||||
ThrowError("Invalid client index %i", client);
|
||||
}
|
||||
|
||||
if (!IsClientInGame(client)) {
|
||||
ThrowError("Client %i is not in game", client);
|
||||
}
|
||||
|
||||
if (author <= 0 || author > MaxClients) {
|
||||
ThrowError("Invalid client index %i", author);
|
||||
}
|
||||
|
||||
if (!IsClientInGame(author)) {
|
||||
ThrowError("Client %i is not in game", author);
|
||||
}
|
||||
|
||||
char buffer[MAX_BUFFER_LENGTH], buffer2[MAX_BUFFER_LENGTH];
|
||||
SetGlobalTransTarget(client);
|
||||
Format(buffer, sizeof(buffer), "\x01%s", message);
|
||||
VFormat(buffer2, sizeof(buffer2), buffer, 4);
|
||||
MC_ReplaceColorCodes(buffer2, author);
|
||||
MC_SendMessage(client, buffer2, author);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a message to all clients in the chat area.
|
||||
* Supports color tags and teamcolor tag.
|
||||
*
|
||||
* @param author Author index whose color will be used for teamcolor tag.
|
||||
* @param message Message (formatting rules).
|
||||
*
|
||||
* On error/Errors: If the author is not connected an error will be thrown.
|
||||
*/
|
||||
stock void MC_PrintToChatAllEx(int author, const char[] message, any ...) {
|
||||
MC_CheckTrie();
|
||||
|
||||
if (author <= 0 || author > MaxClients) {
|
||||
ThrowError("Invalid client index %i", author);
|
||||
}
|
||||
|
||||
if (!IsClientInGame(author)) {
|
||||
ThrowError("Client %i is not in game", author);
|
||||
}
|
||||
|
||||
char buffer[MAX_BUFFER_LENGTH];
|
||||
char buffer2[MAX_BUFFER_LENGTH];
|
||||
|
||||
for (int i = 1; i <= MaxClients; ++i) {
|
||||
if (!IsClientInGame(i) || MC_SkipList[i]) {
|
||||
MC_SkipList[i] = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
SetGlobalTransTarget(i);
|
||||
Format(buffer, sizeof(buffer), "\x01%s", message);
|
||||
VFormat(buffer2, sizeof(buffer2), buffer, 3);
|
||||
|
||||
MC_ReplaceColorCodes(buffer2, author);
|
||||
MC_SendMessage(i, buffer2, author);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a SayText2 usermessage
|
||||
*
|
||||
* @param client Client to send usermessage to
|
||||
* @param message Message to send
|
||||
*/
|
||||
stock void MC_SendMessage(int client, const char[] message, int author = 0) {
|
||||
if (author == 0) {
|
||||
author = client;
|
||||
}
|
||||
|
||||
char buffer[MC_MAX_MESSAGE_LENGTH];
|
||||
strcopy(buffer, sizeof(buffer), message);
|
||||
|
||||
UserMsg index = GetUserMessageId("SayText2");
|
||||
if (index == INVALID_MESSAGE_ID) {
|
||||
if (GetEngineVersion() == Engine_DODS) {
|
||||
int team = GetClientTeam(author);
|
||||
if (team == 0) {
|
||||
ReplaceString(buffer, sizeof(buffer), "\x03", "\x04", false); // Unassigned gets green
|
||||
}
|
||||
else {
|
||||
char temp[16];
|
||||
Format(temp, sizeof(temp), "\x07%06X", MC_TeamColors[MC_GAME_DODS][team - 1]);
|
||||
ReplaceString(buffer, sizeof(buffer), "\x03", temp, false);
|
||||
}
|
||||
}
|
||||
|
||||
PrintToChat(client, "%s", buffer);
|
||||
return;
|
||||
}
|
||||
|
||||
Handle buf = StartMessageOne("SayText2", client, USERMSG_RELIABLE|USERMSG_BLOCKHOOKS);
|
||||
if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) {
|
||||
Protobuf pb = UserMessageToProtobuf(buf);
|
||||
pb.SetInt("ent_idx", author);
|
||||
pb.SetBool("chat", true);
|
||||
pb.SetString("msg_name", buffer);
|
||||
pb.AddString("params", "");
|
||||
pb.AddString("params", "");
|
||||
pb.AddString("params", "");
|
||||
pb.AddString("params", "");
|
||||
}
|
||||
else {
|
||||
BfWrite bf = UserMessageToBfWrite(buf);
|
||||
bf.WriteByte(author); // Message author
|
||||
bf.WriteByte(true); // Chat message
|
||||
bf.WriteString(buffer); // Message text
|
||||
}
|
||||
|
||||
EndMessage();
|
||||
}
|
||||
|
||||
/**
|
||||
* This function should only be used right in front of
|
||||
* MC_PrintToChatAll or MC_PrintToChatAllEx. It causes those functions
|
||||
* to skip the specified client when printing the message.
|
||||
* After printing the message, the client will no longer be skipped.
|
||||
*
|
||||
* @param client Client index
|
||||
*/
|
||||
stock void MC_SkipNextClient(int client) {
|
||||
if (client <= 0 || client > MaxClients) {
|
||||
ThrowError("Invalid client index %i", client);
|
||||
}
|
||||
|
||||
MC_SkipList[client] = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the colors trie is initialized and initializes it if it's not (used internally)
|
||||
*
|
||||
* @return No return
|
||||
*/
|
||||
stock void MC_CheckTrie() {
|
||||
if (MC_Trie == null) {
|
||||
MC_Trie = MC_InitColorTrie();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces color tags in a string with color codes (used internally by MC_PrintToChat, MC_PrintToChatAll, MC_PrintToChatEx, and MC_PrintToChatAllEx
|
||||
*
|
||||
* @param buffer String.
|
||||
* @param author Optional client index to use for {teamcolor} tags, or 0 for none
|
||||
* @param removeTags Optional boolean value to determine whether we're replacing tags with colors, or just removing tags, used by MC_RemoveTags
|
||||
* @param maxlen Optional value for max buffer length, used by MC_RemoveTags
|
||||
*
|
||||
* On error/Errors: If the client index passed for author is invalid or not in game.
|
||||
*/
|
||||
stock void MC_ReplaceColorCodes(char[] buffer, int author = 0, bool removeTags = false, int maxlen = MAX_BUFFER_LENGTH) {
|
||||
MC_CheckTrie();
|
||||
if (!removeTags) {
|
||||
ReplaceString(buffer, maxlen, "{default}", "\x01", false);
|
||||
}
|
||||
else {
|
||||
ReplaceString(buffer, maxlen, "{default}", "", false);
|
||||
ReplaceString(buffer, maxlen, "{teamcolor}", "", false);
|
||||
}
|
||||
|
||||
if (author != 0 && !removeTags) {
|
||||
if (author < 0 || author > MaxClients) {
|
||||
ThrowError("Invalid client index %i", author);
|
||||
}
|
||||
|
||||
if (!IsClientInGame(author)) {
|
||||
ThrowError("Client %i is not in game", author);
|
||||
}
|
||||
|
||||
ReplaceString(buffer, maxlen, "{teamcolor}", "\x03", false);
|
||||
}
|
||||
|
||||
int cursor = 0;
|
||||
int value;
|
||||
char tag[32], buff[32];
|
||||
char[] output = new char[maxlen];
|
||||
|
||||
strcopy(output, maxlen, buffer);
|
||||
// Since the string's size is going to be changing, output will hold the replaced string and we'll search buffer
|
||||
|
||||
Regex regex = new Regex("{[#a-zA-Z0-9]+}");
|
||||
for (int i = 0; i < 1000; i++) { // The RegEx extension is quite flaky, so we have to loop here :/. This loop is supposed to be infinite and broken by return, but conditions have been added to be safe.
|
||||
if (regex.Match(buffer[cursor]) < 1) {
|
||||
delete regex;
|
||||
strcopy(buffer, maxlen, output);
|
||||
return;
|
||||
}
|
||||
|
||||
regex.GetSubString(0, tag, sizeof(tag));
|
||||
MC_StrToLower(tag);
|
||||
cursor = StrContains(buffer[cursor], tag, false) + cursor + 1;
|
||||
strcopy(buff, sizeof(buff), tag);
|
||||
ReplaceString(buff, sizeof(buff), "{", "");
|
||||
ReplaceString(buff, sizeof(buff), "}", "");
|
||||
|
||||
if (buff[0] == '#') {
|
||||
if (strlen(buff) == 7) {
|
||||
Format(buff, sizeof(buff), "\x07%s", buff[1]);
|
||||
}
|
||||
else if (strlen(buff) == 9) {
|
||||
Format(buff, sizeof(buff), "\x08%s", buff[1]);
|
||||
}
|
||||
else {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (removeTags) {
|
||||
ReplaceString(output, maxlen, tag, "", false);
|
||||
}
|
||||
else {
|
||||
ReplaceString(output, maxlen, tag, buff, false);
|
||||
}
|
||||
}
|
||||
else if (!MC_Trie.GetValue(buff, value)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (removeTags) {
|
||||
ReplaceString(output, maxlen, tag, "", false);
|
||||
}
|
||||
else {
|
||||
Format(buff, sizeof(buff), "\x07%06X", value);
|
||||
ReplaceString(output, maxlen, tag, buff, false);
|
||||
}
|
||||
}
|
||||
LogError("[MORE COLORS] Infinite loop broken.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a part of a string
|
||||
*
|
||||
* @param input String to get the part from
|
||||
* @param output Buffer to write to
|
||||
* @param maxlen Max length of output buffer
|
||||
* @param start Position to start at
|
||||
* @param numChars Number of characters to return, or 0 for the end of the string
|
||||
*/
|
||||
stock void CSubString(const char[] input, char[] output, int maxlen, int start, int numChars = 0) {
|
||||
int i = 0;
|
||||
for (;;) {
|
||||
if (i == maxlen - 1 || i >= numChars || input[start + i] == '\0') {
|
||||
output[i] = '\0';
|
||||
return;
|
||||
}
|
||||
|
||||
output[i] = input[start + i];
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a string to lowercase
|
||||
*
|
||||
* @param buffer String to convert
|
||||
*/
|
||||
stock void MC_StrToLower(char[] buffer) {
|
||||
int len = strlen(buffer);
|
||||
for (int i = 0; i < len; i++) {
|
||||
buffer[i] = CharToLower(buffer[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a color to the colors trie
|
||||
*
|
||||
* @param name Color name, without braces
|
||||
* @param color Hexadecimal representation of the color (0xRRGGBB)
|
||||
* @return True if color was added successfully, false if a color already exists with that name
|
||||
*/
|
||||
stock bool MC_AddColor(const char[] name, int color) {
|
||||
MC_CheckTrie();
|
||||
|
||||
int value;
|
||||
|
||||
if (MC_Trie.GetValue(name, value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char newName[64];
|
||||
strcopy(newName, sizeof(newName), name);
|
||||
|
||||
MC_StrToLower(newName);
|
||||
MC_Trie.SetValue(newName, color);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes color tags from a message
|
||||
*
|
||||
* @param message Message to remove tags from
|
||||
* @param maxlen Maximum buffer length
|
||||
*/
|
||||
stock void MC_RemoveTags(char[] message, int maxlen) {
|
||||
MC_ReplaceColorCodes(message, 0, true, maxlen);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replies to a command with colors
|
||||
*
|
||||
* @param client Client to reply to
|
||||
* @param message Message (formatting rules)
|
||||
*/
|
||||
stock void MC_ReplyToCommand(int client, const char[] message, any ...) {
|
||||
char buffer[MAX_BUFFER_LENGTH];
|
||||
SetGlobalTransTarget(client);
|
||||
VFormat(buffer, sizeof(buffer), message, 3);
|
||||
|
||||
if (client == 0) {
|
||||
MC_RemoveTags(buffer, sizeof(buffer));
|
||||
PrintToServer("%s", buffer);
|
||||
}
|
||||
|
||||
if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) {
|
||||
MC_RemoveTags(buffer, sizeof(buffer));
|
||||
PrintToConsole(client, "%s", buffer);
|
||||
}
|
||||
else {
|
||||
MC_PrintToChat(client, "%s", buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replies to a command with colors
|
||||
*
|
||||
* @param client Client to reply to
|
||||
* @param author Client to use for {teamcolor}
|
||||
* @param message Message (formatting rules)
|
||||
*/
|
||||
stock void MC_ReplyToCommandEx(int client, int author, const char[] message, any ...) {
|
||||
char buffer[MAX_BUFFER_LENGTH];
|
||||
SetGlobalTransTarget(client);
|
||||
VFormat(buffer, sizeof(buffer), message, 4);
|
||||
|
||||
if (client == 0) {
|
||||
MC_RemoveTags(buffer, sizeof(buffer));
|
||||
PrintToServer("%s", buffer);
|
||||
}
|
||||
|
||||
if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) {
|
||||
MC_RemoveTags(buffer, sizeof(buffer));
|
||||
PrintToConsole(client, "%s", buffer);
|
||||
}
|
||||
else {
|
||||
MC_PrintToChatEx(client, author, "%s", buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays usage of an admin command to users depending on the
|
||||
* setting of the sm_show_activity cvar.
|
||||
*
|
||||
* This version does not display a message to the originating client
|
||||
* if used from chat triggers or menus. If manual replies are used
|
||||
* for these cases, then this function will suffice. Otherwise,
|
||||
* MC_ShowActivity2() is slightly more useful.
|
||||
* Supports color tags.
|
||||
*
|
||||
* @param client Client index doing the action, or 0 for server.
|
||||
* @param format Formatting rules.
|
||||
* @param ... Variable number of format parameters.
|
||||
* @error
|
||||
*/
|
||||
stock int MC_ShowActivity(int client, const char[] format, any ...) {
|
||||
if (sm_show_activity == null) {
|
||||
sm_show_activity = FindConVar("sm_show_activity");
|
||||
}
|
||||
|
||||
char tag[] = "[SM] ";
|
||||
|
||||
char szBuffer[MC_MAX_MESSAGE_LENGTH];
|
||||
//char szCMessage[MC_MAX_MESSAGE_LENGTH];
|
||||
int value = sm_show_activity.IntValue;
|
||||
ReplySource replyto = GetCmdReplySource();
|
||||
|
||||
char name[MAX_NAME_LENGTH] = "Console";
|
||||
char sign[MAX_NAME_LENGTH] = "ADMIN";
|
||||
bool display_in_chat = false;
|
||||
if (client != 0) {
|
||||
if (client < 0 || client > MaxClients || !IsClientConnected(client))
|
||||
ThrowError("Client index %d is invalid", client);
|
||||
|
||||
GetClientName(client, name, sizeof(name));
|
||||
AdminId id = GetUserAdmin(client);
|
||||
if (id == INVALID_ADMIN_ID || !id.HasFlag(Admin_Generic, Access_Effective)) {
|
||||
sign = "PLAYER";
|
||||
}
|
||||
|
||||
/* Display the message to the client? */
|
||||
if (replyto == SM_REPLY_TO_CONSOLE) {
|
||||
SetGlobalTransTarget(client);
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 3);
|
||||
|
||||
MC_RemoveTags(szBuffer, sizeof(szBuffer));
|
||||
PrintToConsole(client, "%s%s\n", tag, szBuffer);
|
||||
display_in_chat = true;
|
||||
}
|
||||
}
|
||||
else {
|
||||
SetGlobalTransTarget(LANG_SERVER);
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 3);
|
||||
|
||||
MC_RemoveTags(szBuffer, sizeof(szBuffer));
|
||||
PrintToServer("%s%s\n", tag, szBuffer);
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
for (int i = 1; i <= MaxClients; ++i) {
|
||||
if (!IsClientInGame(i) || IsFakeClient(i) || (display_in_chat && i == client)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
AdminId id = GetUserAdmin(i);
|
||||
SetGlobalTransTarget(i);
|
||||
if (id == INVALID_ADMIN_ID || !id.HasFlag(Admin_Generic, Access_Effective)) {
|
||||
/* Treat this as a normal user. */
|
||||
if ((value & 1) | (value & 2)) {
|
||||
char newsign[MAX_NAME_LENGTH];
|
||||
|
||||
if ((value & 2) || (i == client)) {
|
||||
newsign = name;
|
||||
}
|
||||
else {
|
||||
newsign = sign;
|
||||
}
|
||||
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 3);
|
||||
|
||||
MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
|
||||
}
|
||||
}
|
||||
else {
|
||||
/* Treat this as an admin user */
|
||||
bool is_root = id.HasFlag(Admin_Root, Access_Effective);
|
||||
if ((value & 4) || (value & 8) || ((value & 16) && is_root)) {
|
||||
char newsign[MAX_NAME_LENGTH];
|
||||
|
||||
if ((value & 8) || ((value & 16) && is_root) || (i == client)) {
|
||||
newsign = name;
|
||||
}
|
||||
else {
|
||||
newsign = sign;
|
||||
}
|
||||
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 3);
|
||||
|
||||
MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as MC_ShowActivity(), except the tag parameter is used instead of "[SM] " (note that you must supply any spacing).
|
||||
* Supports color tags.
|
||||
*
|
||||
* @param client Client index doing the action, or 0 for server.
|
||||
* @param tags Tag to display with.
|
||||
* @param format Formatting rules.
|
||||
* @param ... Variable number of format parameters.
|
||||
* @error
|
||||
*/
|
||||
stock int MC_ShowActivityEx(int client, const char[] tag, const char[] format, any ...) {
|
||||
if (sm_show_activity == null) {
|
||||
sm_show_activity = FindConVar("sm_show_activity");
|
||||
}
|
||||
|
||||
char szBuffer[MC_MAX_MESSAGE_LENGTH];
|
||||
//char szCMessage[MC_MAX_MESSAGE_LENGTH];
|
||||
int value = sm_show_activity.IntValue;
|
||||
ReplySource replyto = GetCmdReplySource();
|
||||
|
||||
char name[MAX_NAME_LENGTH] = "Console";
|
||||
char sign[MAX_NAME_LENGTH] = "ADMIN";
|
||||
bool display_in_chat = false;
|
||||
if (client != 0) {
|
||||
if (client < 0 || client > MaxClients || !IsClientConnected(client)) {
|
||||
ThrowError("Client index %d is invalid", client);
|
||||
}
|
||||
|
||||
GetClientName(client, name, sizeof(name));
|
||||
AdminId id = GetUserAdmin(client);
|
||||
if (id == INVALID_ADMIN_ID || !id.HasFlag(Admin_Generic, Access_Effective)) {
|
||||
sign = "PLAYER";
|
||||
}
|
||||
|
||||
/* Display the message to the client? */
|
||||
if (replyto == SM_REPLY_TO_CONSOLE) {
|
||||
SetGlobalTransTarget(client);
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
MC_RemoveTags(szBuffer, sizeof(szBuffer));
|
||||
PrintToConsole(client, "%s%s\n", tag, szBuffer);
|
||||
display_in_chat = true;
|
||||
}
|
||||
}
|
||||
else {
|
||||
SetGlobalTransTarget(LANG_SERVER);
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
MC_RemoveTags(szBuffer, sizeof(szBuffer));
|
||||
PrintToServer("%s%s\n", tag, szBuffer);
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
for (int i = 1; i <= MaxClients; ++i) {
|
||||
if (!IsClientInGame(i) || IsFakeClient(i) || (display_in_chat && i == client)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
AdminId id = GetUserAdmin(i);
|
||||
SetGlobalTransTarget(i);
|
||||
if (id == INVALID_ADMIN_ID || !id.HasFlag(Admin_Generic, Access_Effective)) {
|
||||
/* Treat this as a normal user. */
|
||||
if ((value & 1) | (value & 2)) {
|
||||
char newsign[MAX_NAME_LENGTH];
|
||||
|
||||
if ((value & 2) || (i == client)) {
|
||||
newsign = name;
|
||||
}
|
||||
else {
|
||||
newsign = sign;
|
||||
}
|
||||
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
|
||||
}
|
||||
}
|
||||
else {
|
||||
/* Treat this as an admin user */
|
||||
bool is_root = id.HasFlag(Admin_Root, Access_Effective);
|
||||
if ((value & 4) || (value & 8) || ((value & 16) && is_root)) {
|
||||
char newsign[MAX_NAME_LENGTH];
|
||||
|
||||
if ((value & 8) || ((value & 16) && is_root) || (i == client)) {
|
||||
newsign = name;
|
||||
}
|
||||
else {
|
||||
newsign = sign;
|
||||
}
|
||||
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays usage of an admin command to users depending on the setting of the sm_show_activity cvar.
|
||||
* All users receive a message in their chat text, except for the originating client,
|
||||
* who receives the message based on the current ReplySource.
|
||||
* Supports color tags.
|
||||
*
|
||||
* @param client Client index doing the action, or 0 for server.
|
||||
* @param tags Tag to prepend to the message.
|
||||
* @param format Formatting rules.
|
||||
* @param ... Variable number of format parameters.
|
||||
* @error
|
||||
*/
|
||||
stock int MC_ShowActivity2(int client, const char[] tag, const char[] format, any ...) {
|
||||
if (sm_show_activity == null) {
|
||||
sm_show_activity = FindConVar("sm_show_activity");
|
||||
}
|
||||
|
||||
char szBuffer[MC_MAX_MESSAGE_LENGTH];
|
||||
//char szCMessage[MC_MAX_MESSAGE_LENGTH];
|
||||
int value = sm_show_activity.IntValue;
|
||||
// ReplySource replyto = GetCmdReplySource();
|
||||
|
||||
char name[MAX_NAME_LENGTH] = "Console";
|
||||
char sign[MAX_NAME_LENGTH] = "ADMIN";
|
||||
|
||||
if (client != 0) {
|
||||
if (client < 0 || client > MaxClients || !IsClientConnected(client)) {
|
||||
ThrowError("Client index %d is invalid", client);
|
||||
}
|
||||
|
||||
GetClientName(client, name, sizeof(name));
|
||||
|
||||
AdminId id = GetUserAdmin(client);
|
||||
if (id == INVALID_ADMIN_ID || !id.HasFlag(Admin_Generic, Access_Effective)) {
|
||||
sign = "PLAYER";
|
||||
}
|
||||
|
||||
SetGlobalTransTarget(client);
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
/* We don't display directly to the console because the chat text
|
||||
* simply gets added to the console, so we don't want it to print
|
||||
* twice.
|
||||
*/
|
||||
MC_PrintToChatEx(client, client, "%s%s", tag, szBuffer);
|
||||
}
|
||||
else {
|
||||
SetGlobalTransTarget(LANG_SERVER);
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
MC_RemoveTags(szBuffer, sizeof(szBuffer));
|
||||
PrintToServer("%s%s\n", tag, szBuffer);
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
for (int i = 1; i <= MaxClients; ++i) {
|
||||
if (!IsClientInGame(i) || IsFakeClient(i) || i == client) {
|
||||
continue;
|
||||
}
|
||||
|
||||
AdminId id = GetUserAdmin(i);
|
||||
SetGlobalTransTarget(i);
|
||||
if (id == INVALID_ADMIN_ID || !id.HasFlag(Admin_Generic, Access_Effective)) {
|
||||
/* Treat this as a normal user. */
|
||||
if ((value & 1) | (value & 2)) {
|
||||
char newsign[MAX_NAME_LENGTH];
|
||||
|
||||
if ((value & 2)) {
|
||||
newsign = name;
|
||||
}
|
||||
else {
|
||||
newsign = sign;
|
||||
}
|
||||
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
|
||||
}
|
||||
}
|
||||
else {
|
||||
/* Treat this as an admin user */
|
||||
bool is_root = id.HasFlag(Admin_Root, Access_Effective);
|
||||
if ((value & 4) || (value & 8) || ((value & 16) && is_root)) {
|
||||
char newsign[MAX_NAME_LENGTH];
|
||||
|
||||
|
||||
if ((value & 8) || ((value & 16) && is_root)) {
|
||||
newsign = name;
|
||||
}
|
||||
else {
|
||||
newsign = sign;
|
||||
}
|
||||
|
||||
VFormat(szBuffer, sizeof(szBuffer), format, 4);
|
||||
|
||||
MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether a color name exists
|
||||
*
|
||||
* @param color The color name to check
|
||||
* @return True if the color exists, false otherwise
|
||||
*/
|
||||
stock bool CColorExists(const char[] color) {
|
||||
MC_CheckTrie();
|
||||
int temp;
|
||||
return MC_Trie.GetValue(color, temp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the hexadecimal representation of a client's team color (will NOT initialize the trie)
|
||||
*
|
||||
* @param client Client to get the team color for
|
||||
* @return Client's team color in hexadecimal, or green if unknown
|
||||
* On error/Errors: If the client index passed is invalid or not in game.
|
||||
*/
|
||||
stock int CGetTeamColor(int client) {
|
||||
if (client <= 0 || client > MaxClients) {
|
||||
ThrowError("Invalid client index %i", client);
|
||||
}
|
||||
|
||||
if (!IsClientInGame(client)) {
|
||||
ThrowError("Client %i is not in game", client);
|
||||
}
|
||||
|
||||
int value;
|
||||
switch(GetClientTeam(client)) {
|
||||
case 1: {
|
||||
value = MCOLOR_GRAY;
|
||||
}
|
||||
case 2: {
|
||||
value = MCOLOR_RED;
|
||||
}
|
||||
case 3: {
|
||||
value = MCOLOR_BLUE;
|
||||
}
|
||||
default: {
|
||||
value = MCOLOR_GREEN;
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
stock StringMap MC_InitColorTrie() {
|
||||
StringMap hTrie = new StringMap();
|
||||
hTrie.SetValue("aliceblue", 0xF0F8FF);
|
||||
hTrie.SetValue("allies", 0x4D7942); // same as Allies team in DoD:S
|
||||
hTrie.SetValue("ancient", 0xEB4B4B); // same as Ancient item rarity in Dota 2
|
||||
hTrie.SetValue("antiquewhite", 0xFAEBD7);
|
||||
hTrie.SetValue("aqua", 0x00FFFF);
|
||||
hTrie.SetValue("aquamarine", 0x7FFFD4);
|
||||
hTrie.SetValue("arcana", 0xADE55C); // same as Arcana item rarity in Dota 2
|
||||
hTrie.SetValue("axis", 0xFF4040); // same as Axis team in DoD:S
|
||||
hTrie.SetValue("azure", 0x007FFF);
|
||||
hTrie.SetValue("beige", 0xF5F5DC);
|
||||
hTrie.SetValue("bisque", 0xFFE4C4);
|
||||
hTrie.SetValue("black", 0x000000);
|
||||
hTrie.SetValue("blanchedalmond", 0xFFEBCD);
|
||||
hTrie.SetValue("blue", 0x99CCFF); // same as BLU/Counter-Terrorist team color
|
||||
hTrie.SetValue("blueviolet", 0x8A2BE2);
|
||||
hTrie.SetValue("brown", 0xA52A2A);
|
||||
hTrie.SetValue("burlywood", 0xDEB887);
|
||||
hTrie.SetValue("cadetblue", 0x5F9EA0);
|
||||
hTrie.SetValue("chartreuse", 0x7FFF00);
|
||||
hTrie.SetValue("chocolate", 0xD2691E);
|
||||
hTrie.SetValue("collectors", 0xAA0000); // same as Collector's item quality in TF2
|
||||
hTrie.SetValue("common", 0xB0C3D9); // same as Common item rarity in Dota 2
|
||||
hTrie.SetValue("community", 0x70B04A); // same as Community item quality in TF2
|
||||
hTrie.SetValue("coral", 0xFF7F50);
|
||||
hTrie.SetValue("cornflowerblue", 0x6495ED);
|
||||
hTrie.SetValue("cornsilk", 0xFFF8DC);
|
||||
hTrie.SetValue("corrupted", 0xA32C2E); // same as Corrupted item quality in Dota 2
|
||||
hTrie.SetValue("crimson", 0xDC143C);
|
||||
hTrie.SetValue("cyan", 0x00FFFF);
|
||||
hTrie.SetValue("darkblue", 0x00008B);
|
||||
hTrie.SetValue("darkcyan", 0x008B8B);
|
||||
hTrie.SetValue("darkgoldenrod", 0xB8860B);
|
||||
hTrie.SetValue("darkgray", 0xA9A9A9);
|
||||
hTrie.SetValue("darkgrey", 0xA9A9A9);
|
||||
hTrie.SetValue("darkgreen", 0x006400);
|
||||
hTrie.SetValue("darkkhaki", 0xBDB76B);
|
||||
hTrie.SetValue("darkmagenta", 0x8B008B);
|
||||
hTrie.SetValue("darkolivegreen", 0x556B2F);
|
||||
hTrie.SetValue("darkorange", 0xFF8C00);
|
||||
hTrie.SetValue("darkorchid", 0x9932CC);
|
||||
hTrie.SetValue("darkred", 0x8B0000);
|
||||
hTrie.SetValue("darksalmon", 0xE9967A);
|
||||
hTrie.SetValue("darkseagreen", 0x8FBC8F);
|
||||
hTrie.SetValue("darkslateblue", 0x483D8B);
|
||||
hTrie.SetValue("darkslategray", 0x2F4F4F);
|
||||
hTrie.SetValue("darkslategrey", 0x2F4F4F);
|
||||
hTrie.SetValue("darkturquoise", 0x00CED1);
|
||||
hTrie.SetValue("darkviolet", 0x9400D3);
|
||||
hTrie.SetValue("deeppink", 0xFF1493);
|
||||
hTrie.SetValue("deepskyblue", 0x00BFFF);
|
||||
hTrie.SetValue("dimgray", 0x696969);
|
||||
hTrie.SetValue("dimgrey", 0x696969);
|
||||
hTrie.SetValue("dodgerblue", 0x1E90FF);
|
||||
hTrie.SetValue("exalted", 0xCCCCCD); // same as Exalted item quality in Dota 2
|
||||
hTrie.SetValue("firebrick", 0xB22222);
|
||||
hTrie.SetValue("floralwhite", 0xFFFAF0);
|
||||
hTrie.SetValue("forestgreen", 0x228B22);
|
||||
hTrie.SetValue("frozen", 0x4983B3); // same as Frozen item quality in Dota 2
|
||||
hTrie.SetValue("fuchsia", 0xFF00FF);
|
||||
hTrie.SetValue("fullblue", 0x0000FF);
|
||||
hTrie.SetValue("fullred", 0xFF0000);
|
||||
hTrie.SetValue("gainsboro", 0xDCDCDC);
|
||||
hTrie.SetValue("genuine", 0x4D7455); // same as Genuine item quality in TF2
|
||||
hTrie.SetValue("ghostwhite", 0xF8F8FF);
|
||||
hTrie.SetValue("gold", 0xFFD700);
|
||||
hTrie.SetValue("goldenrod", 0xDAA520);
|
||||
hTrie.SetValue("gray", 0xCCCCCC); // same as spectator team color
|
||||
hTrie.SetValue("grey", 0xCCCCCC);
|
||||
hTrie.SetValue("green", 0x3EFF3E);
|
||||
hTrie.SetValue("greenyellow", 0xADFF2F);
|
||||
hTrie.SetValue("haunted", 0x38F3AB); // same as Haunted item quality in TF2
|
||||
hTrie.SetValue("honeydew", 0xF0FFF0);
|
||||
hTrie.SetValue("hotpink", 0xFF69B4);
|
||||
hTrie.SetValue("immortal", 0xE4AE33); // same as Immortal item rarity in Dota 2
|
||||
hTrie.SetValue("indianred", 0xCD5C5C);
|
||||
hTrie.SetValue("indigo", 0x4B0082);
|
||||
hTrie.SetValue("ivory", 0xFFFFF0);
|
||||
hTrie.SetValue("khaki", 0xF0E68C);
|
||||
hTrie.SetValue("lavender", 0xE6E6FA);
|
||||
hTrie.SetValue("lavenderblush", 0xFFF0F5);
|
||||
hTrie.SetValue("lawngreen", 0x7CFC00);
|
||||
hTrie.SetValue("legendary", 0xD32CE6); // same as Legendary item rarity in Dota 2
|
||||
hTrie.SetValue("lemonchiffon", 0xFFFACD);
|
||||
hTrie.SetValue("lightblue", 0xADD8E6);
|
||||
hTrie.SetValue("lightcoral", 0xF08080);
|
||||
hTrie.SetValue("lightcyan", 0xE0FFFF);
|
||||
hTrie.SetValue("lightgoldenrodyellow", 0xFAFAD2);
|
||||
hTrie.SetValue("lightgray", 0xD3D3D3);
|
||||
hTrie.SetValue("lightgrey", 0xD3D3D3);
|
||||
hTrie.SetValue("lightgreen", 0x99FF99);
|
||||
hTrie.SetValue("lightpink", 0xFFB6C1);
|
||||
hTrie.SetValue("lightsalmon", 0xFFA07A);
|
||||
hTrie.SetValue("lightseagreen", 0x20B2AA);
|
||||
hTrie.SetValue("lightskyblue", 0x87CEFA);
|
||||
hTrie.SetValue("lightslategray", 0x778899);
|
||||
hTrie.SetValue("lightslategrey", 0x778899);
|
||||
hTrie.SetValue("lightsteelblue", 0xB0C4DE);
|
||||
hTrie.SetValue("lightyellow", 0xFFFFE0);
|
||||
hTrie.SetValue("lime", 0x00FF00);
|
||||
hTrie.SetValue("limegreen", 0x32CD32);
|
||||
hTrie.SetValue("linen", 0xFAF0E6);
|
||||
hTrie.SetValue("magenta", 0xFF00FF);
|
||||
hTrie.SetValue("maroon", 0x800000);
|
||||
hTrie.SetValue("mediumaquamarine", 0x66CDAA);
|
||||
hTrie.SetValue("mediumblue", 0x0000CD);
|
||||
hTrie.SetValue("mediumorchid", 0xBA55D3);
|
||||
hTrie.SetValue("mediumpurple", 0x9370D8);
|
||||
hTrie.SetValue("mediumseagreen", 0x3CB371);
|
||||
hTrie.SetValue("mediumslateblue", 0x7B68EE);
|
||||
hTrie.SetValue("mediumspringgreen", 0x00FA9A);
|
||||
hTrie.SetValue("mediumturquoise", 0x48D1CC);
|
||||
hTrie.SetValue("mediumvioletred", 0xC71585);
|
||||
hTrie.SetValue("midnightblue", 0x191970);
|
||||
hTrie.SetValue("mintcream", 0xF5FFFA);
|
||||
hTrie.SetValue("mistyrose", 0xFFE4E1);
|
||||
hTrie.SetValue("moccasin", 0xFFE4B5);
|
||||
hTrie.SetValue("mythical", 0x8847FF); // same as Mythical item rarity in Dota 2
|
||||
hTrie.SetValue("navajowhite", 0xFFDEAD);
|
||||
hTrie.SetValue("navy", 0x000080);
|
||||
hTrie.SetValue("normal", 0xB2B2B2); // same as Normal item quality in TF2
|
||||
hTrie.SetValue("oldlace", 0xFDF5E6);
|
||||
hTrie.SetValue("olive", 0x9EC34F);
|
||||
hTrie.SetValue("olivedrab", 0x6B8E23);
|
||||
hTrie.SetValue("orange", 0xFFA500);
|
||||
hTrie.SetValue("orangered", 0xFF4500);
|
||||
hTrie.SetValue("orchid", 0xDA70D6);
|
||||
hTrie.SetValue("palegoldenrod", 0xEEE8AA);
|
||||
hTrie.SetValue("palegreen", 0x98FB98);
|
||||
hTrie.SetValue("paleturquoise", 0xAFEEEE);
|
||||
hTrie.SetValue("palevioletred", 0xD87093);
|
||||
hTrie.SetValue("papayawhip", 0xFFEFD5);
|
||||
hTrie.SetValue("peachpuff", 0xFFDAB9);
|
||||
hTrie.SetValue("peru", 0xCD853F);
|
||||
hTrie.SetValue("pink", 0xFFC0CB);
|
||||
hTrie.SetValue("plum", 0xDDA0DD);
|
||||
hTrie.SetValue("powderblue", 0xB0E0E6);
|
||||
hTrie.SetValue("purple", 0x800080);
|
||||
hTrie.SetValue("rare", 0x4B69FF); // same as Rare item rarity in Dota 2
|
||||
hTrie.SetValue("red", 0xFF4040); // same as RED/Terrorist team color
|
||||
hTrie.SetValue("rosybrown", 0xBC8F8F);
|
||||
hTrie.SetValue("royalblue", 0x4169E1);
|
||||
hTrie.SetValue("saddlebrown", 0x8B4513);
|
||||
hTrie.SetValue("salmon", 0xFA8072);
|
||||
hTrie.SetValue("sandybrown", 0xF4A460);
|
||||
hTrie.SetValue("seagreen", 0x2E8B57);
|
||||
hTrie.SetValue("seashell", 0xFFF5EE);
|
||||
hTrie.SetValue("selfmade", 0x70B04A); // same as Self-Made item quality in TF2
|
||||
hTrie.SetValue("sienna", 0xA0522D);
|
||||
hTrie.SetValue("silver", 0xC0C0C0);
|
||||
hTrie.SetValue("skyblue", 0x87CEEB);
|
||||
hTrie.SetValue("slateblue", 0x6A5ACD);
|
||||
hTrie.SetValue("slategray", 0x708090);
|
||||
hTrie.SetValue("slategrey", 0x708090);
|
||||
hTrie.SetValue("snow", 0xFFFAFA);
|
||||
hTrie.SetValue("springgreen", 0x00FF7F);
|
||||
hTrie.SetValue("steelblue", 0x4682B4);
|
||||
hTrie.SetValue("strange", 0xCF6A32); // same as Strange item quality in TF2
|
||||
hTrie.SetValue("tan", 0xD2B48C);
|
||||
hTrie.SetValue("teal", 0x008080);
|
||||
hTrie.SetValue("thistle", 0xD8BFD8);
|
||||
hTrie.SetValue("tomato", 0xFF6347);
|
||||
hTrie.SetValue("turquoise", 0x40E0D0);
|
||||
hTrie.SetValue("uncommon", 0xB0C3D9); // same as Uncommon item rarity in Dota 2
|
||||
hTrie.SetValue("unique", 0xFFD700); // same as Unique item quality in TF2
|
||||
hTrie.SetValue("unusual", 0x8650AC); // same as Unusual item quality in TF2
|
||||
hTrie.SetValue("valve", 0xA50F79); // same as Valve item quality in TF2
|
||||
hTrie.SetValue("vintage", 0x476291); // same as Vintage item quality in TF2
|
||||
hTrie.SetValue("violet", 0xEE82EE);
|
||||
hTrie.SetValue("wheat", 0xF5DEB3);
|
||||
hTrie.SetValue("white", 0xFFFFFF);
|
||||
hTrie.SetValue("whitesmoke", 0xF5F5F5);
|
||||
hTrie.SetValue("yellow", 0xFFFF00);
|
||||
hTrie.SetValue("yellowgreen", 0x9ACD32);
|
||||
|
||||
return hTrie;
|
||||
}
|
157
scripting/include/smlib/arrays.inc
Normal file
157
scripting/include/smlib/arrays.inc
Normal file
|
@ -0,0 +1,157 @@
|
|||
#if defined _smlib_array_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_array_included
|
||||
|
||||
#include <sourcemod>
|
||||
|
||||
/**
|
||||
* Returns the index for the first occurance of the given value.
|
||||
* If the value cannot be found, -1 will be returned.
|
||||
*
|
||||
* @param array Static Array.
|
||||
* @param size Size of the Array.
|
||||
* @param value Value to search for.
|
||||
* @param start Optional: Offset where to start (0 - (size-1)).
|
||||
* @return Array index, or -1 if the value couldn't be found.
|
||||
*/
|
||||
stock int Array_FindValue(const any[] array, int size, any value, int start=0)
|
||||
{
|
||||
if (start < 0) {
|
||||
start = 0;
|
||||
}
|
||||
|
||||
for (int i=start; i < size; i++) {
|
||||
|
||||
if (array[i] == value) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Searchs for the first occurance of a string in the array.
|
||||
* If the value cannot be located, -1 will be returned.
|
||||
*
|
||||
* @param array Static Array.
|
||||
* @param size Size of the Array.
|
||||
* @param value String to search for.
|
||||
* @param start Optional: Offset where to start(0 - (size-1)).
|
||||
* @return Array index, or -1 if the value couldn't be found.
|
||||
*/
|
||||
stock int Array_FindString(const char[][] array, int size, const char[] str, bool caseSensitive=true, int start=0)
|
||||
{
|
||||
if (start < 0) {
|
||||
start = 0;
|
||||
}
|
||||
|
||||
for (int i=start; i < size; i++) {
|
||||
|
||||
if (StrEqual(array[i], str, caseSensitive)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Index of the Lowest value in the array
|
||||
*
|
||||
* @param array Static Array.
|
||||
* @param size Size of the Array.
|
||||
* @param start Optional: Offset where to start (0 - (size-1)).
|
||||
* @return Array index.
|
||||
*/
|
||||
stock int Array_FindLowestValue(const any[] array, int size, int start=0)
|
||||
{
|
||||
if (start < 0) {
|
||||
start = 0;
|
||||
}
|
||||
|
||||
any value = array[start];
|
||||
any tempValue;
|
||||
int x = start;
|
||||
|
||||
for (int i=start; i < size; i++) {
|
||||
|
||||
tempValue = array[i];
|
||||
|
||||
if (tempValue < value) {
|
||||
value = tempValue;
|
||||
x = i;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Index of the Highest value in the array
|
||||
*
|
||||
* @param array Static Array.
|
||||
* @param size Size of the Array.
|
||||
* @param start Optional: Offset where to start (0 - (size-1)).
|
||||
* @return Array index.
|
||||
*/
|
||||
stock int Array_FindHighestValue(const any[] array, int size, int start=0)
|
||||
{
|
||||
if (start < 0) {
|
||||
start = 0;
|
||||
}
|
||||
|
||||
any value = array[start];
|
||||
any tempValue;
|
||||
int x = start;
|
||||
|
||||
for (int i=start; i < size; i++) {
|
||||
|
||||
tempValue = array[i];
|
||||
|
||||
if (tempValue > value) {
|
||||
value = tempValue;
|
||||
x = i;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills an array with a given value in a 1 dimensional static array.
|
||||
* You can specify the amount of cells to be written.
|
||||
*
|
||||
* @param array Static Array.
|
||||
* @param size Number of cells to write (eg. the array's size)
|
||||
* @param value Fill value.
|
||||
* @param start Optional: Offset where to start (0 - (size-1)).
|
||||
*/
|
||||
stock void Array_Fill(any[] array, int size, any value, int start=0)
|
||||
{
|
||||
if (start < 0) {
|
||||
start = 0;
|
||||
}
|
||||
|
||||
for (int i=start; i < size; i++) {
|
||||
array[i] = value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies a 1 dimensional static array.
|
||||
*
|
||||
* @param array Static Array to copy from.
|
||||
* @param newArray New Array to copy to.
|
||||
* @param size Size of the array (or number of cells to copy)
|
||||
* @noreturn
|
||||
*/
|
||||
stock void Array_Copy(const any[] array, any[] newArray, int size)
|
||||
{
|
||||
for (int i=0; i < size; i++) {
|
||||
newArray[i] = array[i];
|
||||
}
|
||||
}
|
3077
scripting/include/smlib/clients.inc
Normal file
3077
scripting/include/smlib/clients.inc
Normal file
File diff suppressed because it is too large
Load diff
575
scripting/include/smlib/colors.inc
Normal file
575
scripting/include/smlib/colors.inc
Normal file
|
@ -0,0 +1,575 @@
|
|||
#if defined _smlib_colors_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_colors_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <smlib/arrays>
|
||||
#include <smlib/teams>
|
||||
|
||||
#define CHATCOLOR_NOSUBJECT -2
|
||||
#define SMLIB_COLORS_GAMEDATAFILE "smlib_colors.games"
|
||||
|
||||
enum ChatColorSubjectType
|
||||
{
|
||||
ChatColorSubjectType_none = -3,
|
||||
|
||||
// Subject/Team colors
|
||||
ChatColorSubjectType_player = -2,
|
||||
ChatColorSubjectType_undefined = -1,
|
||||
ChatColorSubjectType_world = 0
|
||||
// Anything higher is a specific team
|
||||
}
|
||||
|
||||
enum struct ChatColorInfo
|
||||
{
|
||||
int ChatColorInfo_Code;
|
||||
int ChatColorInfo_Alternative;
|
||||
bool ChatColorInfo_Supported;
|
||||
ChatColorSubjectType ChatColorInfo_SubjectType;
|
||||
}
|
||||
|
||||
enum ChatColor
|
||||
{
|
||||
ChatColor_Normal,
|
||||
ChatColor_Orange,
|
||||
ChatColor_Red,
|
||||
ChatColor_RedBlue,
|
||||
ChatColor_Blue,
|
||||
ChatColor_BlueRed,
|
||||
ChatColor_Team,
|
||||
ChatColor_Lightgreen,
|
||||
ChatColor_Gray,
|
||||
ChatColor_Green,
|
||||
ChatColor_Olivegreen,
|
||||
ChatColor_Black,
|
||||
ChatColor_MAXCOLORS
|
||||
}
|
||||
|
||||
static char chatColorTags[][] = {
|
||||
"N", // Normal
|
||||
"O", // Orange
|
||||
"R", // Red
|
||||
"RB", // Red, Blue
|
||||
"B", // Blue
|
||||
"BR", // Blue, Red
|
||||
"T", // Team
|
||||
"L", // Light green
|
||||
"GRA", // Gray
|
||||
"G", // Green
|
||||
"OG", // Olive green
|
||||
"BLA" // Black
|
||||
};
|
||||
|
||||
static char chatColorNames[][] = {
|
||||
"normal", // Normal
|
||||
"orange", // Orange
|
||||
"red", // Red
|
||||
"redblue", // Red, Blue
|
||||
"blue", // Blue
|
||||
"bluered", // Blue, Red
|
||||
"team", // Team
|
||||
"lightgreen", // Light green
|
||||
"gray", // Gray
|
||||
"green", // Green
|
||||
"olivegreen", // Olive green
|
||||
"black" // Black
|
||||
};
|
||||
|
||||
static ChatColorInfo chatColorInfo[ChatColor_MAXCOLORS];
|
||||
|
||||
static bool checkTeamPlay = false;
|
||||
static ConVar mp_teamplay = null;
|
||||
static bool isSayText2_supported = true;
|
||||
static int chatSubject = CHATCOLOR_NOSUBJECT;
|
||||
|
||||
/**
|
||||
* Sets the subject (a client) for the chat color parser.
|
||||
* Call this before Color_ParseChatText() or Client_PrintToChat().
|
||||
*
|
||||
* @param client Client Index/Subject
|
||||
*/
|
||||
stock void Color_ChatSetSubject(int client)
|
||||
{
|
||||
chatSubject = client;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the subject used for the chat color parser.
|
||||
*
|
||||
* @return Client Index/Subject, or CHATCOLOR_NOSUBJECT if none
|
||||
*/
|
||||
stock int Color_ChatGetSubject()
|
||||
{
|
||||
return chatSubject;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the subject used for the chat color parser.
|
||||
* Call this after Color_ParseChatText().
|
||||
*/
|
||||
stock void Color_ChatClearSubject()
|
||||
{
|
||||
chatSubject = CHATCOLOR_NOSUBJECT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a chat string and converts all color tags to color codes.
|
||||
* This is a very powerful function that works recursively over the color information
|
||||
* table. The support colors are hardcoded, but can be overriden for each game by
|
||||
* creating the file gamedata/smlib_colors.games.txt.
|
||||
*
|
||||
* @param str Chat String
|
||||
* @param subject Output Buffer
|
||||
* @param size Output Buffer size
|
||||
* @return Returns a value for the subject
|
||||
*/
|
||||
stock int Color_ParseChatText(const char[] str, char[] buffer, int size)
|
||||
{
|
||||
bool inBracket = false;
|
||||
int x, x_buf, x_tag;
|
||||
int subject = CHATCOLOR_NOSUBJECT;
|
||||
|
||||
char sTag[10] = ""; // This should be able to hold "\x08RRGGBBAA"\0
|
||||
char colorCode[10] = ""; // This should be able to hold "\x08RRGGBBAA"\0
|
||||
char currentColor[10] = "\x01"; // Initialize with normal color
|
||||
|
||||
size--;
|
||||
|
||||
// Every chat message has to start with a
|
||||
// color code, otherwise it will ignore all colors.
|
||||
buffer[x_buf++] = '\x01';
|
||||
|
||||
while (str[x] != '\0') {
|
||||
|
||||
if (size == x_buf) {
|
||||
break;
|
||||
}
|
||||
|
||||
char character = str[x++];
|
||||
|
||||
if (inBracket) {
|
||||
// We allow up to 9 characters in the tag (#RRGGBBAA)
|
||||
if (character == '}' || x_tag > 9) {
|
||||
inBracket = false;
|
||||
sTag[x_tag] = '\0';
|
||||
x_tag = 0;
|
||||
|
||||
if (character == '}') {
|
||||
Color_TagToCode(sTag, subject, colorCode);
|
||||
|
||||
if (colorCode[0] == '\0') {
|
||||
// We got an unknown tag, ignore this
|
||||
// and forward it to the buffer.
|
||||
|
||||
// Terminate buffer with \0 so Format can handle it.
|
||||
buffer[x_buf] = '\0';
|
||||
x_buf = Format(buffer, size, "%s{%s}", buffer, sTag);
|
||||
|
||||
// We 'r done here
|
||||
continue;
|
||||
}
|
||||
else if (!StrEqual(colorCode, currentColor)) {
|
||||
// If we are already using this color,
|
||||
// we don't need to set it again.
|
||||
|
||||
// Write the color code to our buffer.
|
||||
// x_buf will be increased by the number of cells written.
|
||||
x_buf += strcopy(buffer[x_buf], size - x_buf, colorCode);
|
||||
|
||||
// Remember the current color.
|
||||
strcopy(currentColor, sizeof(currentColor), colorCode);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// If the tag character limit exceeds 9,
|
||||
// we have to do something.
|
||||
|
||||
// Terminate buffer with \0 so Format can handle it.
|
||||
buffer[x_buf] = '\0';
|
||||
x_buf = Format(buffer, size, "%s{%s%c", buffer, sTag, character);
|
||||
}
|
||||
}
|
||||
else if (character == '{' && !x_tag) {
|
||||
buffer[x_buf++] = '{';
|
||||
inBracket = false;
|
||||
}
|
||||
else {
|
||||
sTag[x_tag++] = character;
|
||||
}
|
||||
}
|
||||
else if (character == '{') {
|
||||
inBracket = true;
|
||||
}
|
||||
else {
|
||||
buffer[x_buf++] = character;
|
||||
}
|
||||
}
|
||||
|
||||
// Write remaining text to the buffer,
|
||||
// if we have been inside brackets.
|
||||
if (inBracket) {
|
||||
buffer[x_buf] = '\0';
|
||||
x_buf = Format(buffer, size, "%s{%s", buffer, sTag);
|
||||
}
|
||||
|
||||
buffer[x_buf] = '\0';
|
||||
|
||||
return subject;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a chat color tag to its code character.
|
||||
*
|
||||
* @param tag Color Tag String.
|
||||
* @param subject Subject variable to pass
|
||||
* @param result The result as character sequence (string). This will be \0 if the tag is unkown.
|
||||
*/
|
||||
stock void Color_TagToCode(const char[] tag, int &subject=-1, char result[10])
|
||||
{
|
||||
// Check if the tag starts with a '#'.
|
||||
// We will handle it has RGB(A)-color code then.
|
||||
if (tag[0] == '#') {
|
||||
int length_tag = strlen(tag);
|
||||
switch (length_tag - 1) {
|
||||
// #RGB -> \07RRGGBB
|
||||
case 3: {
|
||||
FormatEx(
|
||||
result, sizeof(result), "\x07%c%c%c%c%c%c",
|
||||
tag[1], tag[1], tag[2], tag[2], tag[3], tag[3]
|
||||
);
|
||||
}
|
||||
// #RGBA -> \08RRGGBBAA
|
||||
case 4: {
|
||||
FormatEx(
|
||||
result, sizeof(result), "\x08%c%c%c%c%c%c%c%c",
|
||||
tag[1], tag[1], tag[2], tag[2], tag[3], tag[3], tag[4], tag[4]
|
||||
);
|
||||
}
|
||||
// #RRGGBB -> \07RRGGBB
|
||||
case 6: {
|
||||
FormatEx(result, sizeof(result), "\x07%s", tag[1]);
|
||||
}
|
||||
// #RRGGBBAA -> \08RRGGBBAA
|
||||
case 8: {
|
||||
FormatEx(result, sizeof(result), "\x08%s", tag[1]);
|
||||
}
|
||||
default: {
|
||||
result[0] = '\0';
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
else {
|
||||
// Try to handle this string as color name
|
||||
int n = Array_FindString(chatColorTags, sizeof(chatColorTags), tag);
|
||||
|
||||
// Check if this tag is invalid
|
||||
if (n == -1) {
|
||||
result[0] = '\0';
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if the color is actually supported 'n stuff.
|
||||
Color_GetChatColorInfo(n, subject);
|
||||
|
||||
result[0] = chatColorInfo[n].ChatColorInfo_Code;
|
||||
result[1] = '\0';
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips all color control characters in a string.
|
||||
* The Output buffer can be the same as the input buffer.
|
||||
* Original code by Psychonic, thanks.
|
||||
*
|
||||
* @param input Input String.
|
||||
* @param output Output String.
|
||||
* @param size Max Size of the Output string
|
||||
*/
|
||||
stock void Color_StripFromChatText(const char[] input, char[] output, int size)
|
||||
{
|
||||
int x = 0;
|
||||
for (int i=0; input[i] != '\0'; i++) {
|
||||
|
||||
if (x+1 == size) {
|
||||
break;
|
||||
}
|
||||
|
||||
char character = input[i];
|
||||
|
||||
if (character > 0x08) {
|
||||
output[x++] = character;
|
||||
}
|
||||
}
|
||||
|
||||
output[x] = '\0';
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the gamename and sets default values.
|
||||
* For example if some colors are supported, or
|
||||
* if a game uses another color code for a specific color.
|
||||
* All those hardcoded default values can be overriden in
|
||||
* smlib's color gamedata file.
|
||||
*/
|
||||
static stock void Color_ChatInitialize()
|
||||
{
|
||||
static bool initialized = false;
|
||||
|
||||
if (initialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
initialized = true;
|
||||
|
||||
// Normal
|
||||
chatColorInfo[ChatColor_Normal].ChatColorInfo_Code = '\x01';
|
||||
chatColorInfo[ChatColor_Normal].ChatColorInfo_Alternative = -1; /* None */
|
||||
chatColorInfo[ChatColor_Normal].ChatColorInfo_Supported = true;
|
||||
chatColorInfo[ChatColor_Normal].ChatColorInfo_SubjectType = ChatColorSubjectType_none;
|
||||
|
||||
// Orange
|
||||
chatColorInfo[ChatColor_Orange].ChatColorInfo_Code = '\x01';
|
||||
chatColorInfo[ChatColor_Orange].ChatColorInfo_Alternative = 0; /* None */
|
||||
chatColorInfo[ChatColor_Orange].ChatColorInfo_Supported = true;
|
||||
chatColorInfo[ChatColor_Orange].ChatColorInfo_SubjectType = ChatColorSubjectType_none;
|
||||
|
||||
// Red
|
||||
chatColorInfo[ChatColor_Red].ChatColorInfo_Code = '\x03';
|
||||
chatColorInfo[ChatColor_Red].ChatColorInfo_Alternative = 9; /* Green */
|
||||
chatColorInfo[ChatColor_Red].ChatColorInfo_Supported = true;
|
||||
chatColorInfo[ChatColor_Red].ChatColorInfo_SubjectType = view_as<ChatColorSubjectType>(2);
|
||||
|
||||
// Red, Blue
|
||||
chatColorInfo[ChatColor_RedBlue].ChatColorInfo_Code = '\x03';
|
||||
chatColorInfo[ChatColor_RedBlue].ChatColorInfo_Alternative = 4; /* Blue */
|
||||
chatColorInfo[ChatColor_RedBlue].ChatColorInfo_Supported = true;
|
||||
chatColorInfo[ChatColor_RedBlue].ChatColorInfo_SubjectType = view_as<ChatColorSubjectType>(2);
|
||||
|
||||
// Blue
|
||||
chatColorInfo[ChatColor_Blue].ChatColorInfo_Code = '\x03';
|
||||
chatColorInfo[ChatColor_Blue].ChatColorInfo_Alternative = 9; /* Green */
|
||||
chatColorInfo[ChatColor_Blue].ChatColorInfo_Supported = true;
|
||||
chatColorInfo[ChatColor_Blue].ChatColorInfo_SubjectType = view_as<ChatColorSubjectType>(3);
|
||||
|
||||
// Blue, Red
|
||||
chatColorInfo[ChatColor_BlueRed].ChatColorInfo_Code = '\x03';
|
||||
chatColorInfo[ChatColor_BlueRed].ChatColorInfo_Alternative = 2; /* Red */
|
||||
chatColorInfo[ChatColor_BlueRed].ChatColorInfo_Supported = true;
|
||||
chatColorInfo[ChatColor_BlueRed].ChatColorInfo_SubjectType = view_as<ChatColorSubjectType>(3);
|
||||
|
||||
// Team
|
||||
chatColorInfo[ChatColor_Team].ChatColorInfo_Code = '\x03';
|
||||
chatColorInfo[ChatColor_Team].ChatColorInfo_Alternative = 9; /* Green */
|
||||
chatColorInfo[ChatColor_Team].ChatColorInfo_Supported = true;
|
||||
chatColorInfo[ChatColor_Team].ChatColorInfo_SubjectType = ChatColorSubjectType_player;
|
||||
|
||||
// Light green
|
||||
chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Code = '\x03';
|
||||
chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Alternative = 9; /* Green */
|
||||
chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Supported = true;
|
||||
chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_SubjectType = ChatColorSubjectType_world;
|
||||
|
||||
// Gray
|
||||
chatColorInfo[ChatColor_Gray].ChatColorInfo_Code = '\x03';
|
||||
chatColorInfo[ChatColor_Gray].ChatColorInfo_Alternative = 9; /* Green */
|
||||
chatColorInfo[ChatColor_Gray].ChatColorInfo_Supported = true;
|
||||
chatColorInfo[ChatColor_Gray].ChatColorInfo_SubjectType = ChatColorSubjectType_undefined;
|
||||
|
||||
// Green
|
||||
chatColorInfo[ChatColor_Green].ChatColorInfo_Code = '\x04';
|
||||
chatColorInfo[ChatColor_Green].ChatColorInfo_Alternative = 0; /* Normal*/
|
||||
chatColorInfo[ChatColor_Green].ChatColorInfo_Supported = true;
|
||||
chatColorInfo[ChatColor_Green].ChatColorInfo_SubjectType = ChatColorSubjectType_none;
|
||||
|
||||
// Olive green
|
||||
chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_Code = '\x05';
|
||||
chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_Alternative = 9; /* Green */
|
||||
chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_Supported = true;
|
||||
chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_SubjectType = ChatColorSubjectType_none;
|
||||
|
||||
// Black
|
||||
chatColorInfo[ChatColor_Black].ChatColorInfo_Code = '\x06';
|
||||
chatColorInfo[ChatColor_Black].ChatColorInfo_Alternative = 9; /* Green */
|
||||
chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true;
|
||||
chatColorInfo[ChatColor_Black].ChatColorInfo_SubjectType = ChatColorSubjectType_none;
|
||||
|
||||
char gameFolderName[PLATFORM_MAX_PATH];
|
||||
GetGameFolderName(gameFolderName, sizeof(gameFolderName));
|
||||
|
||||
chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = false;
|
||||
|
||||
if (strncmp(gameFolderName, "left4dead", 9, false) != 0 &&
|
||||
!StrEqual(gameFolderName, "cstrike", false) &&
|
||||
!StrEqual(gameFolderName, "tf", false))
|
||||
{
|
||||
chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Supported = false;
|
||||
chatColorInfo[ChatColor_Gray].ChatColorInfo_Supported = false;
|
||||
}
|
||||
|
||||
if (StrEqual(gameFolderName, "tf", false)) {
|
||||
chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true;
|
||||
|
||||
chatColorInfo[ChatColor_Gray].ChatColorInfo_Code = '\x01';
|
||||
chatColorInfo[ChatColor_Gray].ChatColorInfo_SubjectType = ChatColorSubjectType_none;
|
||||
}
|
||||
else if (strncmp(gameFolderName, "left4dead", 9, false) == 0) {
|
||||
chatColorInfo[ChatColor_Red].ChatColorInfo_SubjectType = view_as<ChatColorSubjectType>(3);
|
||||
chatColorInfo[ChatColor_RedBlue].ChatColorInfo_SubjectType = view_as<ChatColorSubjectType>(3);
|
||||
chatColorInfo[ChatColor_Blue].ChatColorInfo_SubjectType = view_as<ChatColorSubjectType>(2);
|
||||
chatColorInfo[ChatColor_BlueRed].ChatColorInfo_SubjectType = view_as<ChatColorSubjectType>(2);
|
||||
|
||||
chatColorInfo[ChatColor_Orange].ChatColorInfo_Code = '\x04';
|
||||
chatColorInfo[ChatColor_Green].ChatColorInfo_Code = '\x05';
|
||||
}
|
||||
else if (StrEqual(gameFolderName, "hl2mp", false)) {
|
||||
chatColorInfo[ChatColor_Red].ChatColorInfo_SubjectType = view_as<ChatColorSubjectType>(3);
|
||||
chatColorInfo[ChatColor_RedBlue].ChatColorInfo_SubjectType = view_as<ChatColorSubjectType>(3);
|
||||
chatColorInfo[ChatColor_Blue].ChatColorInfo_SubjectType = view_as<ChatColorSubjectType>(2);
|
||||
chatColorInfo[ChatColor_BlueRed].ChatColorInfo_SubjectType = view_as<ChatColorSubjectType>(2);
|
||||
chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true;
|
||||
|
||||
checkTeamPlay = true;
|
||||
}
|
||||
else if (StrEqual(gameFolderName, "dod", false)) {
|
||||
chatColorInfo[ChatColor_Gray].ChatColorInfo_Code = '\x01';
|
||||
chatColorInfo[ChatColor_Gray].ChatColorInfo_SubjectType = ChatColorSubjectType_none;
|
||||
|
||||
chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true;
|
||||
chatColorInfo[ChatColor_Orange].ChatColorInfo_Supported = false;
|
||||
}
|
||||
|
||||
if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID) {
|
||||
isSayText2_supported = false;
|
||||
}
|
||||
|
||||
char path_gamedata[PLATFORM_MAX_PATH];
|
||||
BuildPath(Path_SM, path_gamedata, sizeof(path_gamedata), "gamedata/%s.txt", SMLIB_COLORS_GAMEDATAFILE);
|
||||
|
||||
if (FileExists(path_gamedata)) {
|
||||
Handle gamedata = INVALID_HANDLE;
|
||||
|
||||
if ((gamedata = LoadGameConfigFile(SMLIB_COLORS_GAMEDATAFILE)) != INVALID_HANDLE) {
|
||||
|
||||
char keyName[32], buffer[6];
|
||||
|
||||
for (int i=0; i < sizeof(chatColorNames); i++) {
|
||||
|
||||
Format(keyName, sizeof(keyName), "%s_code", chatColorNames[i]);
|
||||
if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) {
|
||||
chatColorInfo[i].ChatColorInfo_Code = StringToInt(buffer);
|
||||
}
|
||||
|
||||
Format(keyName, sizeof(keyName), "%s_alternative", chatColorNames[i]);
|
||||
if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) {
|
||||
chatColorInfo[i].ChatColorInfo_Alternative = buffer[0];
|
||||
}
|
||||
|
||||
Format(keyName, sizeof(keyName), "%s_supported", chatColorNames[i]);
|
||||
if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) {
|
||||
chatColorInfo[i].ChatColorInfo_Supported = StrEqual(buffer, "true");
|
||||
}
|
||||
|
||||
Format(keyName, sizeof(keyName), "%s_subjecttype", chatColorNames[i]);
|
||||
if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) {
|
||||
chatColorInfo[i].ChatColorInfo_SubjectType = view_as<ChatColorSubjectType>(StringToInt(buffer));
|
||||
}
|
||||
}
|
||||
|
||||
if (GameConfGetKeyValue(gamedata, "checkteamplay", buffer, sizeof(buffer))) {
|
||||
checkTeamPlay = StrEqual(buffer, "true");
|
||||
}
|
||||
|
||||
CloseHandle(gamedata);
|
||||
}
|
||||
}
|
||||
|
||||
mp_teamplay = FindConVar("mp_teamplay");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the passed color index is actually supported
|
||||
* for the current game. If not, the index will be overwritten
|
||||
* The color resolving works recursively until a valid color is found.
|
||||
*
|
||||
* @param index
|
||||
* @param subject A client index or CHATCOLOR_NOSUBJECT
|
||||
*/
|
||||
static stock int Color_GetChatColorInfo(int &index, int &subject=CHATCOLOR_NOSUBJECT)
|
||||
{
|
||||
Color_ChatInitialize();
|
||||
|
||||
if (index == -1) {
|
||||
index = 0;
|
||||
}
|
||||
|
||||
while (!chatColorInfo[index].ChatColorInfo_Supported) {
|
||||
|
||||
int alternative = chatColorInfo[index].ChatColorInfo_Alternative;
|
||||
|
||||
if (alternative == -1) {
|
||||
index = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
index = alternative;
|
||||
}
|
||||
|
||||
if (index == -1) {
|
||||
index = 0;
|
||||
}
|
||||
|
||||
int newSubject = CHATCOLOR_NOSUBJECT;
|
||||
ChatColorSubjectType type = chatColorInfo[index].ChatColorInfo_SubjectType;
|
||||
|
||||
switch (type) {
|
||||
case ChatColorSubjectType_none: {
|
||||
}
|
||||
case ChatColorSubjectType_player: {
|
||||
newSubject = chatSubject;
|
||||
}
|
||||
case ChatColorSubjectType_undefined: {
|
||||
newSubject = -1;
|
||||
}
|
||||
case ChatColorSubjectType_world: {
|
||||
newSubject = 0;
|
||||
}
|
||||
default: {
|
||||
|
||||
if (!checkTeamPlay || mp_teamplay.BoolValue) {
|
||||
|
||||
if (subject > 0 && subject <= MaxClients) {
|
||||
|
||||
if (GetClientTeam(subject) == view_as<int>(type)) {
|
||||
newSubject = subject;
|
||||
}
|
||||
}
|
||||
else if (subject == CHATCOLOR_NOSUBJECT) {
|
||||
int client = Team_GetAnyClient(view_as<int>(type));
|
||||
|
||||
if (client != -1) {
|
||||
newSubject = client;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (type > ChatColorSubjectType_none &&
|
||||
((subject != CHATCOLOR_NOSUBJECT && subject != newSubject) || newSubject == CHATCOLOR_NOSUBJECT || !isSayText2_supported))
|
||||
{
|
||||
index = chatColorInfo[index].ChatColorInfo_Alternative;
|
||||
newSubject = Color_GetChatColorInfo(index, subject);
|
||||
}
|
||||
|
||||
// Only set the subject if there is no subject set already.
|
||||
if (subject == CHATCOLOR_NOSUBJECT) {
|
||||
subject = newSubject;
|
||||
}
|
||||
|
||||
return newSubject;
|
||||
}
|
45
scripting/include/smlib/concommands.inc
Normal file
45
scripting/include/smlib/concommands.inc
Normal file
|
@ -0,0 +1,45 @@
|
|||
#if defined _smlib_concommands_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_concommands_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <smlib/clients>
|
||||
|
||||
/**
|
||||
* Checks if a ConCommand has one or more flags set.
|
||||
*
|
||||
* @param command ConCommand name.
|
||||
* @param flags Flags to check.
|
||||
* @return True if flags are set, false otherwise.
|
||||
*/
|
||||
stock bool ConCommand_HasFlags(const char[] command, int flags)
|
||||
{
|
||||
return GetCommandFlags(command) & flags > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds one or more flags to a ConCommand.
|
||||
*
|
||||
* @param command ConCommand name.
|
||||
* @param flags Flags to add.
|
||||
*/
|
||||
stock void ConCommand_AddFlags(const char[] command, int flags)
|
||||
{
|
||||
int newFlags = GetCommandFlags(command);
|
||||
newFlags |= flags;
|
||||
SetCommandFlags(command, newFlags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes one ore more flags from a ConCommand.
|
||||
*
|
||||
* @param command ConCommand name.
|
||||
* @param flags Flags to remove
|
||||
*/
|
||||
stock void ConCommand_RemoveFlags(const char[] command, int flags)
|
||||
{
|
||||
int newFlags = GetCommandFlags(command);
|
||||
newFlags &= ~flags;
|
||||
SetCommandFlags(command, newFlags);
|
||||
}
|
71
scripting/include/smlib/convars.inc
Normal file
71
scripting/include/smlib/convars.inc
Normal file
|
@ -0,0 +1,71 @@
|
|||
#if defined _smlib_convars_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_convars_included
|
||||
|
||||
#include <sourcemod>
|
||||
|
||||
/**
|
||||
* Checks if a ConVar has one or more flags set.
|
||||
*
|
||||
* @param convar ConVar Handle.
|
||||
* @param flags Flags to check.
|
||||
* @return True if flags are set, false otherwise.
|
||||
*/
|
||||
stock bool Convar_HasFlags(ConVar convar, int flags)
|
||||
{
|
||||
return convar.Flags & flags > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds one or more flags to a ConVar.
|
||||
*
|
||||
* @param convar ConVar Handle.
|
||||
* @param flags Flags to add.
|
||||
*/
|
||||
stock void Convar_AddFlags(ConVar convar, int flags)
|
||||
{
|
||||
int newFlags = convar.Flags;
|
||||
newFlags |= flags;
|
||||
convar.Flags = newFlags;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes one ore more flags from a ConVar.
|
||||
*
|
||||
* @param convar ConVar Handle.
|
||||
* @param flags Flags to remove
|
||||
* @noreturn
|
||||
*/
|
||||
stock void Convar_RemoveFlags(ConVar convar, int flags)
|
||||
{
|
||||
int newFlags = convar.Flags;
|
||||
newFlags &= ~flags;
|
||||
convar.Flags = newFlags;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a String is a valid ConVar or
|
||||
* Console Command name.
|
||||
*
|
||||
* @param name String Name.
|
||||
* @return True if the name specified is a valid ConVar or console command name, false otherwise.
|
||||
*/
|
||||
stock bool Convar_IsValidName(const char[] name)
|
||||
{
|
||||
if (name[0] == '\0') {
|
||||
return false;
|
||||
}
|
||||
|
||||
int n=0;
|
||||
while (name[n] != '\0') {
|
||||
|
||||
if (!IsValidConVarChar(name[n])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
n++;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
625
scripting/include/smlib/crypt.inc
Normal file
625
scripting/include/smlib/crypt.inc
Normal file
|
@ -0,0 +1,625 @@
|
|||
#if defined _smlib_crypt_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_crypt_included
|
||||
|
||||
#include <sourcemod>
|
||||
|
||||
/**********************************************************************************
|
||||
*
|
||||
* Base64 Encoding/Decoding Functions
|
||||
* All Credits to to SirLamer & ScriptCoderPro
|
||||
* Taken from http://forums.alliedmods.net/showthread.php?t=101764
|
||||
*
|
||||
***********************************************************************************/
|
||||
|
||||
// The Base64 encoding table
|
||||
static const char base64_sTable[] =
|
||||
// 0000000000111111111122222222223333333333444444444455555555556666
|
||||
// 0123456789012345678901234567890123456789012345678901234567890123
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
// The Base64 decoding table
|
||||
static const int base64_decodeTable[] = {
|
||||
// 0 1 2 3 4 5 6 7 8 9
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 9
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 10 - 19
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20 - 29
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 30 - 39
|
||||
0, 0, 0, 62, 0, 0, 0, 63, 52, 53, // 40 - 49
|
||||
54, 55, 56, 57, 58, 59, 60, 61, 0, 0, // 50 - 59
|
||||
0, 0, 0, 0, 0, 0, 1, 2, 3, 4, // 60 - 69
|
||||
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 70 - 79
|
||||
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 80 - 89
|
||||
25, 0, 0, 0, 0, 0, 0, 26, 27, 28, // 90 - 99
|
||||
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // 100 - 109
|
||||
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, // 110 - 119
|
||||
49, 50, 51, 0, 0, 0, 0, 0, 0, 0, // 120 - 129
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 130 - 139
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 140 - 149
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 150 - 159
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160 - 169
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 170 - 179
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 180 - 189
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 190 - 199
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 200 - 209
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 210 - 219
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 220 - 229
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 230 - 239
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 240 - 249
|
||||
0, 0, 0, 0, 0, 0 // 250 - 256
|
||||
};
|
||||
|
||||
/*
|
||||
* For some reason the standard demands a string in 24-bit (3 character) intervals.
|
||||
* This fill character is used to identify unused bytes at the end of the string.
|
||||
*/
|
||||
static const char base64_cFillChar = '=';
|
||||
|
||||
// The conversion characters between the standard and URL-compliance Base64 protocols
|
||||
static const char base64_mime_chars[] = "+/=";
|
||||
static const char base64_url_chars[] = "-_.";
|
||||
|
||||
/*
|
||||
* Encodes a string or binary data into Base64
|
||||
*
|
||||
* @param sString The input string or binary data to be encoded.
|
||||
* @param sResult The storage buffer for the Base64-encoded result.
|
||||
* @param len The maximum length of the storage buffer, in characters/bytes.
|
||||
* @param sourcelen (optional): The number of characters or length in bytes to be read from the input source.
|
||||
* This is not needed for a text string, but is important for binary data since there is no end-of-line character.
|
||||
* @return The length of the written Base64 string, in bytes.
|
||||
*/
|
||||
stock int Crypt_Base64Encode(const char[] sString, char[] sResult, int len, int sourcelen=0)
|
||||
{
|
||||
int nLength; // The string length to be read from the input
|
||||
int resPos; // The string position in the result buffer
|
||||
|
||||
// If the read length was specified, use it; otherwise, pull the string length from the input.
|
||||
if (sourcelen > 0) {
|
||||
nLength = sourcelen;
|
||||
}
|
||||
else {
|
||||
nLength = strlen(sString);
|
||||
}
|
||||
|
||||
// Loop through and generate the Base64 encoded string
|
||||
// NOTE: This performs the standard encoding process. Do not manipulate the logic within this loop.
|
||||
for (int nPos = 0; nPos < nLength; nPos++) {
|
||||
int cCode;
|
||||
|
||||
cCode = (sString[nPos] >> 2) & 0x3f;
|
||||
|
||||
resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]);
|
||||
|
||||
cCode = (sString[nPos] << 4) & 0x3f;
|
||||
if (++nPos < nLength) {
|
||||
cCode |= (sString[nPos] >> 4) & 0x0f;
|
||||
}
|
||||
resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]);
|
||||
|
||||
if ( nPos < nLength ) {
|
||||
cCode = (sString[nPos] << 2) & 0x3f;
|
||||
if (++nPos < nLength) {
|
||||
cCode |= (sString[nPos] >> 6) & 0x03;
|
||||
}
|
||||
|
||||
resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]);
|
||||
}
|
||||
else {
|
||||
nPos++;
|
||||
resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_cFillChar);
|
||||
}
|
||||
|
||||
if (nPos < nLength) {
|
||||
cCode = sString[nPos] & 0x3f;
|
||||
resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]);
|
||||
}
|
||||
else {
|
||||
resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_cFillChar);
|
||||
}
|
||||
}
|
||||
|
||||
return resPos;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Decodes a Base64 string.
|
||||
*
|
||||
* @param sString The input string in compliant Base64 format to be decoded.
|
||||
* @param sResult The storage buffer for the decoded text strihg or binary data.
|
||||
* @param len The maximum length of the storage buffer, in characters/bytes.
|
||||
* @return The length of the decoded data, in bytes.
|
||||
*/
|
||||
stock int Crypt_Base64Decode(const char[] sString, char[] sResult, int len)
|
||||
{
|
||||
int nLength = strlen(sString); // The string length to be read from the input
|
||||
int resPos; // The string position in the result buffer
|
||||
|
||||
// Loop through and generate the Base64 encoded string
|
||||
// NOTE: This performs the standard encoding process. Do not manipulate the logic within this loop.
|
||||
for (int nPos = 0; nPos < nLength; nPos++) {
|
||||
|
||||
int c, c1;
|
||||
|
||||
c = base64_decodeTable[sString[nPos++]];
|
||||
c1 = base64_decodeTable[sString[nPos]];
|
||||
|
||||
c = (c << 2) | ((c1 >> 4) & 0x3);
|
||||
|
||||
resPos += FormatEx(sResult[resPos], len - resPos, "%c", c);
|
||||
|
||||
if (++nPos < nLength) {
|
||||
|
||||
c = sString[nPos];
|
||||
|
||||
if (c == base64_cFillChar)
|
||||
break;
|
||||
|
||||
c = base64_decodeTable[sString[nPos]];
|
||||
c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
|
||||
|
||||
resPos += FormatEx(sResult[resPos], len - resPos, "%c", c1);
|
||||
}
|
||||
|
||||
if (++nPos < nLength) {
|
||||
|
||||
c1 = sString[nPos];
|
||||
|
||||
if (c1 == base64_cFillChar)
|
||||
break;
|
||||
|
||||
c1 = base64_decodeTable[sString[nPos]];
|
||||
c = ((c << 6) & 0xc0) | c1;
|
||||
|
||||
resPos += FormatEx(sResult[resPos], len - resPos, "%c", c);
|
||||
}
|
||||
}
|
||||
|
||||
return resPos;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Converts a standards-compliant Base64 string to the commonly accepted URL-compliant alternative.
|
||||
* Note: The result will be the same length as the input string as long as the output buffer is large enough.
|
||||
*
|
||||
* @param sString The standards-compliant Base64 input string to converted.
|
||||
* @param sResult The storage buffer for the URL-compliant result.
|
||||
* @param len The maximum length of the storage buffer in characters/bytes.
|
||||
* @return Number of cells written.
|
||||
*/
|
||||
stock int Crypt_Base64MimeToUrl(const char[] sString, char[] sResult, int len)
|
||||
{
|
||||
int chars_len = sizeof(base64_mime_chars); // Length of the two standards vs. URL character lists
|
||||
int nLength; // The string length to be read from the input
|
||||
int temp_char; // Buffer character
|
||||
|
||||
nLength = strlen(sString);
|
||||
|
||||
char[] sTemp = new char[nLength+1]; // Buffer string
|
||||
|
||||
// Loop through string
|
||||
for (int i = 0; i < nLength; i++) {
|
||||
temp_char = sString[i];
|
||||
|
||||
for (int j = 0; j < chars_len; j++) {
|
||||
|
||||
if(temp_char == base64_mime_chars[j]) {
|
||||
temp_char = base64_url_chars[j];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
sTemp[i] = temp_char;
|
||||
}
|
||||
|
||||
sTemp[nLength] = '\0';
|
||||
|
||||
return strcopy(sResult, len, sTemp);
|
||||
}
|
||||
|
||||
/*
|
||||
* Base64UrlToMime(String:sResult[], len, const String:sString[], sourcelen)
|
||||
* Converts a URL-compliant Base64 string to the standards-compliant version.
|
||||
* Note: The result will be the same length as the input string as long as the output buffer is large enough.
|
||||
*
|
||||
* @param sString The URL-compliant Base64 input string to converted.
|
||||
* @param sResult The storage buffer for the standards-compliant result.
|
||||
* @param len The maximum length of the storage buffer in characters/bytes.
|
||||
* @return Number of cells written.
|
||||
*/
|
||||
stock int Crypt_Base64UrlToMime(const char[] sString, char[] sResult, int len)
|
||||
{
|
||||
int chars_len = sizeof(base64_mime_chars); // Length of the two standards vs. URL character lists
|
||||
int nLength; // The string length to be read from the input
|
||||
int temp_char; // Buffer character
|
||||
|
||||
nLength = strlen(sString);
|
||||
|
||||
char[] sTemp = new char[nLength+1]; // Buffer string
|
||||
|
||||
// Loop through string
|
||||
for (int i = 0; i < nLength; i++) {
|
||||
temp_char = sString[i];
|
||||
for (int j = 0; j < chars_len; j++) {
|
||||
if (temp_char == base64_url_chars[j]) {
|
||||
temp_char = base64_mime_chars[j];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
sTemp[i] = temp_char;
|
||||
}
|
||||
|
||||
sTemp[nLength] = '\0';
|
||||
|
||||
return strcopy(sResult, len, sTemp);
|
||||
}
|
||||
|
||||
/**********************************************************************************
|
||||
*
|
||||
* MD5 Encoding Functions
|
||||
* All Credits go to sslice
|
||||
* RSA Data Security, Inc. MD5 Message Digest Algorithm
|
||||
* Taken from http://forums.alliedmods.net/showthread.php?t=67683
|
||||
*
|
||||
***********************************************************************************/
|
||||
|
||||
/*
|
||||
* Calculate the md5 hash of a string.
|
||||
*
|
||||
* @param str Input String
|
||||
* @param output Output String Buffer
|
||||
* @param maxlen Size of the Output String Buffer
|
||||
*/
|
||||
stock void Crypt_MD5(const char[] str, char[] output, int maxlen)
|
||||
{
|
||||
int x[2];
|
||||
int buf[4];
|
||||
int input[64];
|
||||
int i, ii;
|
||||
|
||||
int len = strlen(str);
|
||||
|
||||
// MD5Init
|
||||
x[0] = x[1] = 0;
|
||||
buf[0] = 0x67452301;
|
||||
buf[1] = 0xefcdab89;
|
||||
buf[2] = 0x98badcfe;
|
||||
buf[3] = 0x10325476;
|
||||
|
||||
// MD5Update
|
||||
int update[16];
|
||||
|
||||
update[14] = x[0];
|
||||
update[15] = x[1];
|
||||
|
||||
int mdi = (x[0] >>> 3) & 0x3F;
|
||||
|
||||
if ((x[0] + (len << 3)) < x[0]) {
|
||||
x[1] += 1;
|
||||
}
|
||||
|
||||
x[0] += len << 3;
|
||||
x[1] += len >>> 29;
|
||||
|
||||
int c = 0;
|
||||
while (len--) {
|
||||
input[mdi] = str[c];
|
||||
mdi += 1;
|
||||
c += 1;
|
||||
|
||||
if (mdi == 0x40) {
|
||||
|
||||
for (i = 0, ii = 0; i < 16; ++i, ii += 4)
|
||||
{
|
||||
update[i] = (input[ii + 3] << 24) | (input[ii + 2] << 16) | (input[ii + 1] << 8) | input[ii];
|
||||
}
|
||||
|
||||
// Transform
|
||||
MD5Transform(buf, update);
|
||||
|
||||
mdi = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// MD5Final
|
||||
int padding[64] = {
|
||||
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
|
||||
};
|
||||
|
||||
int inx[16];
|
||||
inx[14] = x[0];
|
||||
inx[15] = x[1];
|
||||
|
||||
mdi = (x[0] >>> 3) & 0x3F;
|
||||
|
||||
len = (mdi < 56) ? (56 - mdi) : (120 - mdi);
|
||||
update[14] = x[0];
|
||||
update[15] = x[1];
|
||||
|
||||
mdi = (x[0] >>> 3) & 0x3F;
|
||||
|
||||
if ((x[0] + (len << 3)) < x[0]) {
|
||||
x[1] += 1;
|
||||
}
|
||||
|
||||
x[0] += len << 3;
|
||||
x[1] += len >>> 29;
|
||||
|
||||
c = 0;
|
||||
while (len--) {
|
||||
input[mdi] = padding[c];
|
||||
mdi += 1;
|
||||
c += 1;
|
||||
|
||||
if (mdi == 0x40) {
|
||||
|
||||
for (i = 0, ii = 0; i < 16; ++i, ii += 4) {
|
||||
update[i] = (input[ii + 3] << 24) | (input[ii + 2] << 16) | (input[ii + 1] << 8) | input[ii];
|
||||
}
|
||||
|
||||
// Transform
|
||||
MD5Transform(buf, update);
|
||||
|
||||
mdi = 0;
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0, ii = 0; i < 14; ++i, ii += 4) {
|
||||
inx[i] = (input[ii + 3] << 24) | (input[ii + 2] << 16) | (input[ii + 1] << 8) | input[ii];
|
||||
}
|
||||
|
||||
MD5Transform(buf, inx);
|
||||
|
||||
int digest[16];
|
||||
for (i = 0, ii = 0; i < 4; ++i, ii += 4) {
|
||||
digest[ii] = (buf[i]) & 0xFF;
|
||||
digest[ii + 1] = (buf[i] >>> 8) & 0xFF;
|
||||
digest[ii + 2] = (buf[i] >>> 16) & 0xFF;
|
||||
digest[ii + 3] = (buf[i] >>> 24) & 0xFF;
|
||||
}
|
||||
|
||||
FormatEx(output, maxlen, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
|
||||
digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7],
|
||||
digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15]);
|
||||
}
|
||||
|
||||
static stock void MD5Transform_FF(int &a, int &b, int &c, int &d, int x, int s, int ac)
|
||||
{
|
||||
a += (((b) & (c)) | ((~b) & (d))) + x + ac;
|
||||
a = (((a) << (s)) | ((a) >>> (32-(s))));
|
||||
a += b;
|
||||
}
|
||||
|
||||
static stock void MD5Transform_GG(int &a, int &b, int &c, int &d, int x, int s, int ac)
|
||||
{
|
||||
a += (((b) & (d)) | ((c) & (~d))) + x + ac;
|
||||
a = (((a) << (s)) | ((a) >>> (32-(s))));
|
||||
a += b;
|
||||
}
|
||||
|
||||
static stock void MD5Transform_HH(int &a, int &b, int &c, int &d, int x, int s, int ac)
|
||||
{
|
||||
a += ((b) ^ (c) ^ (d)) + x + ac;
|
||||
a = (((a) << (s)) | ((a) >>> (32-(s))));
|
||||
a += b;
|
||||
}
|
||||
|
||||
static stock void MD5Transform_II(int &a, int &b, int &c, int &d, int x, int s, int ac)
|
||||
{
|
||||
a += ((c) ^ ((b) | (~d))) + x + ac;
|
||||
a = (((a) << (s)) | ((a) >>> (32-(s))));
|
||||
a += b;
|
||||
}
|
||||
|
||||
static stock void MD5Transform(int[] buf, int[] input){
|
||||
int a = buf[0];
|
||||
int b = buf[1];
|
||||
int c = buf[2];
|
||||
int d = buf[3];
|
||||
|
||||
MD5Transform_FF(a, b, c, d, input[0], 7, 0xd76aa478);
|
||||
MD5Transform_FF(d, a, b, c, input[1], 12, 0xe8c7b756);
|
||||
MD5Transform_FF(c, d, a, b, input[2], 17, 0x242070db);
|
||||
MD5Transform_FF(b, c, d, a, input[3], 22, 0xc1bdceee);
|
||||
MD5Transform_FF(a, b, c, d, input[4], 7, 0xf57c0faf);
|
||||
MD5Transform_FF(d, a, b, c, input[5], 12, 0x4787c62a);
|
||||
MD5Transform_FF(c, d, a, b, input[6], 17, 0xa8304613);
|
||||
MD5Transform_FF(b, c, d, a, input[7], 22, 0xfd469501);
|
||||
MD5Transform_FF(a, b, c, d, input[8], 7, 0x698098d8);
|
||||
MD5Transform_FF(d, a, b, c, input[9], 12, 0x8b44f7af);
|
||||
MD5Transform_FF(c, d, a, b, input[10], 17, 0xffff5bb1);
|
||||
MD5Transform_FF(b, c, d, a, input[11], 22, 0x895cd7be);
|
||||
MD5Transform_FF(a, b, c, d, input[12], 7, 0x6b901122);
|
||||
MD5Transform_FF(d, a, b, c, input[13], 12, 0xfd987193);
|
||||
MD5Transform_FF(c, d, a, b, input[14], 17, 0xa679438e);
|
||||
MD5Transform_FF(b, c, d, a, input[15], 22, 0x49b40821);
|
||||
|
||||
MD5Transform_GG(a, b, c, d, input[1], 5, 0xf61e2562);
|
||||
MD5Transform_GG(d, a, b, c, input[6], 9, 0xc040b340);
|
||||
MD5Transform_GG(c, d, a, b, input[11], 14, 0x265e5a51);
|
||||
MD5Transform_GG(b, c, d, a, input[0], 20, 0xe9b6c7aa);
|
||||
MD5Transform_GG(a, b, c, d, input[5], 5, 0xd62f105d);
|
||||
MD5Transform_GG(d, a, b, c, input[10], 9, 0x02441453);
|
||||
MD5Transform_GG(c, d, a, b, input[15], 14, 0xd8a1e681);
|
||||
MD5Transform_GG(b, c, d, a, input[4], 20, 0xe7d3fbc8);
|
||||
MD5Transform_GG(a, b, c, d, input[9], 5, 0x21e1cde6);
|
||||
MD5Transform_GG(d, a, b, c, input[14], 9, 0xc33707d6);
|
||||
MD5Transform_GG(c, d, a, b, input[3], 14, 0xf4d50d87);
|
||||
MD5Transform_GG(b, c, d, a, input[8], 20, 0x455a14ed);
|
||||
MD5Transform_GG(a, b, c, d, input[13], 5, 0xa9e3e905);
|
||||
MD5Transform_GG(d, a, b, c, input[2], 9, 0xfcefa3f8);
|
||||
MD5Transform_GG(c, d, a, b, input[7], 14, 0x676f02d9);
|
||||
MD5Transform_GG(b, c, d, a, input[12], 20, 0x8d2a4c8a);
|
||||
|
||||
MD5Transform_HH(a, b, c, d, input[5], 4, 0xfffa3942);
|
||||
MD5Transform_HH(d, a, b, c, input[8], 11, 0x8771f681);
|
||||
MD5Transform_HH(c, d, a, b, input[11], 16, 0x6d9d6122);
|
||||
MD5Transform_HH(b, c, d, a, input[14], 23, 0xfde5380c);
|
||||
MD5Transform_HH(a, b, c, d, input[1], 4, 0xa4beea44);
|
||||
MD5Transform_HH(d, a, b, c, input[4], 11, 0x4bdecfa9);
|
||||
MD5Transform_HH(c, d, a, b, input[7], 16, 0xf6bb4b60);
|
||||
MD5Transform_HH(b, c, d, a, input[10], 23, 0xbebfbc70);
|
||||
MD5Transform_HH(a, b, c, d, input[13], 4, 0x289b7ec6);
|
||||
MD5Transform_HH(d, a, b, c, input[0], 11, 0xeaa127fa);
|
||||
MD5Transform_HH(c, d, a, b, input[3], 16, 0xd4ef3085);
|
||||
MD5Transform_HH(b, c, d, a, input[6], 23, 0x04881d05);
|
||||
MD5Transform_HH(a, b, c, d, input[9], 4, 0xd9d4d039);
|
||||
MD5Transform_HH(d, a, b, c, input[12], 11, 0xe6db99e5);
|
||||
MD5Transform_HH(c, d, a, b, input[15], 16, 0x1fa27cf8);
|
||||
MD5Transform_HH(b, c, d, a, input[2], 23, 0xc4ac5665);
|
||||
|
||||
MD5Transform_II(a, b, c, d, input[0], 6, 0xf4292244);
|
||||
MD5Transform_II(d, a, b, c, input[7], 10, 0x432aff97);
|
||||
MD5Transform_II(c, d, a, b, input[14], 15, 0xab9423a7);
|
||||
MD5Transform_II(b, c, d, a, input[5], 21, 0xfc93a039);
|
||||
MD5Transform_II(a, b, c, d, input[12], 6, 0x655b59c3);
|
||||
MD5Transform_II(d, a, b, c, input[3], 10, 0x8f0ccc92);
|
||||
MD5Transform_II(c, d, a, b, input[10], 15, 0xffeff47d);
|
||||
MD5Transform_II(b, c, d, a, input[1], 21, 0x85845dd1);
|
||||
MD5Transform_II(a, b, c, d, input[8], 6, 0x6fa87e4f);
|
||||
MD5Transform_II(d, a, b, c, input[15], 10, 0xfe2ce6e0);
|
||||
MD5Transform_II(c, d, a, b, input[6], 15, 0xa3014314);
|
||||
MD5Transform_II(b, c, d, a, input[13], 21, 0x4e0811a1);
|
||||
MD5Transform_II(a, b, c, d, input[4], 6, 0xf7537e82);
|
||||
MD5Transform_II(d, a, b, c, input[11], 10, 0xbd3af235);
|
||||
MD5Transform_II(c, d, a, b, input[2], 15, 0x2ad7d2bb);
|
||||
MD5Transform_II(b, c, d, a, input[9], 21, 0xeb86d391);
|
||||
|
||||
buf[0] += a;
|
||||
buf[1] += b;
|
||||
buf[2] += c;
|
||||
buf[3] += d;
|
||||
}
|
||||
|
||||
/**********************************************************************************
|
||||
*
|
||||
* RC4 Encoding Functions
|
||||
* All Credits go to SirLamer and Raydan
|
||||
* Taken from http://forums.alliedmods.net/showthread.php?t=101834
|
||||
*
|
||||
***********************************************************************************/
|
||||
|
||||
/*
|
||||
* Encrypts a text string using RC4.
|
||||
* Note: This function is NOT binary safe.
|
||||
* Use Crypt_RC4EncodeBinary to encode binary data.
|
||||
*
|
||||
* @param input The source data to be encrypted.
|
||||
* @param pwd The password/key used to encode and decode the data.
|
||||
* @param output The encoded result.
|
||||
* @param maxlen The maximum length of the output buffer.
|
||||
*/
|
||||
stock void Crypt_RC4Encode(const char[] input, const char[] pwd, char[] output, int maxlen)
|
||||
{
|
||||
int pwd_len,str_len,i,j,a,k;
|
||||
int key[256];
|
||||
int box[256];
|
||||
int tmp;
|
||||
|
||||
pwd_len = strlen(pwd);
|
||||
str_len = strlen(input);
|
||||
|
||||
if (pwd_len > 0 && str_len > 0) {
|
||||
|
||||
for (i=0; i < 256; i++) {
|
||||
key[i] = pwd[i%pwd_len];
|
||||
box[i]=i;
|
||||
}
|
||||
|
||||
i=0; j=0;
|
||||
|
||||
for (; i < 256; i++) {
|
||||
j = (j + box[i] + key[i]) % 256;
|
||||
tmp = box[i];
|
||||
box[i] = box[j];
|
||||
box[j] = tmp;
|
||||
}
|
||||
|
||||
i=0; j=0; a=0;
|
||||
|
||||
for (; i < str_len; i++) {
|
||||
a = (a + 1) % 256;
|
||||
j = (j + box[a]) % 256;
|
||||
tmp = box[a];
|
||||
box[a] = box[j];
|
||||
box[j] = tmp;
|
||||
k = box[((box[a] + box[j]) % 256)];
|
||||
FormatEx(output[2*i], maxlen-2*i, "%02x", input[i] ^ k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Encrypts binary data using RC4.
|
||||
*
|
||||
* @param input The source data to be encrypted.
|
||||
* @param str_len The length of the source data.
|
||||
* @param pwd The password/key used to encode and decode the data.
|
||||
* @param output The encoded result.
|
||||
* @param maxlen The maximum length of the output buffer.
|
||||
*/
|
||||
stock int Crypt_RC4EncodeBinary(const char[] input, int str_len, const char[] pwd, char[] output, int maxlen)
|
||||
{
|
||||
int pwd_len,i,j,a,k;
|
||||
int key[256];
|
||||
int box[256];
|
||||
int tmp;
|
||||
|
||||
pwd_len = strlen(pwd);
|
||||
|
||||
if (pwd_len > 0 && str_len > 0) {
|
||||
|
||||
for(i=0;i<256;i++) {
|
||||
key[i] = pwd[i%pwd_len];
|
||||
box[i]=i;
|
||||
}
|
||||
|
||||
i=0; j=0;
|
||||
|
||||
for (; i < 256; i++) {
|
||||
j = (j + box[i] + key[i]) % 256;
|
||||
tmp = box[i];
|
||||
box[i] = box[j];
|
||||
box[j] = tmp;
|
||||
}
|
||||
|
||||
i=0; j=0; a=0;
|
||||
|
||||
if (str_len+1 > maxlen) {
|
||||
str_len = maxlen - 1;
|
||||
}
|
||||
|
||||
for(; i < str_len; i++) {
|
||||
a = (a + 1) % 256;
|
||||
j = (j + box[a]) % 256;
|
||||
tmp = box[a];
|
||||
box[a] = box[j];
|
||||
box[j] = tmp;
|
||||
k = box[((box[a] + box[j]) % 256)];
|
||||
FormatEx(output[i], maxlen-i, "%c", input[i] ^ k);
|
||||
}
|
||||
|
||||
/*
|
||||
* i = number of written bits (remember increment occurs at end of for loop, and THEN it fails the loop condition)
|
||||
* Since we're working with binary data, the calling function should not depend on the escape
|
||||
* character, but putting it here prevents crashes in case someone tries to read the data like a string
|
||||
*/
|
||||
output[i] = '\0';
|
||||
|
||||
return i;
|
||||
}
|
||||
else {
|
||||
return -1;
|
||||
}
|
||||
}
|
28
scripting/include/smlib/debug.inc
Normal file
28
scripting/include/smlib/debug.inc
Normal file
|
@ -0,0 +1,28 @@
|
|||
#if defined _smlib_debug_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_debug_included
|
||||
|
||||
#include <sourcemod>
|
||||
|
||||
/**
|
||||
* Prints the values of a static Float-Array to the server console.
|
||||
*
|
||||
* @param array Static Float-Array.
|
||||
* @param size Size of the Array.
|
||||
*/
|
||||
stock void Debug_FloatArray(const float[] array, int size=3)
|
||||
{
|
||||
char output[64] = "";
|
||||
|
||||
for (int i=0; i < size; ++i) {
|
||||
|
||||
if (i > 0 && i < size) {
|
||||
StrCat(output, sizeof(output), ", ");
|
||||
}
|
||||
|
||||
Format(output, sizeof(output), "%s%f", output, array[i]);
|
||||
}
|
||||
|
||||
PrintToServer("[DEBUG] Vector[%d] = { %s }", size, output);
|
||||
}
|
24
scripting/include/smlib/dynarrays.inc
Normal file
24
scripting/include/smlib/dynarrays.inc
Normal file
|
@ -0,0 +1,24 @@
|
|||
#if defined _smlib_dynarray_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_dynarray_included
|
||||
|
||||
#include <sourcemod>
|
||||
|
||||
/**
|
||||
* Retrieves a cell value from an array.
|
||||
* This is a wrapper around the Sourcemod Function GetArrayCell,
|
||||
* but it casts the result as bool
|
||||
*
|
||||
* @param array Array Handle.
|
||||
* @param index Index in the array.
|
||||
* @param block Optionally specify which block to read from
|
||||
* (useful if the blocksize > 0).
|
||||
* @param asChar Optionally read as a byte instead of a cell.
|
||||
* @return Value read.
|
||||
* @error Invalid Handle, invalid index, or invalid block.
|
||||
*/
|
||||
stock bool DynArray_GetBool(ArrayList array, int index, int block=0, bool asChar=false)
|
||||
{
|
||||
return array.Get(index, block, asChar) != 0;
|
||||
}
|
127
scripting/include/smlib/edicts.inc
Normal file
127
scripting/include/smlib/edicts.inc
Normal file
|
@ -0,0 +1,127 @@
|
|||
#if defined _smlib_edicts_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_edicts_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <smlib/entities>
|
||||
|
||||
/*
|
||||
* Finds an edict by it's name
|
||||
* It only finds the first occurence.
|
||||
*
|
||||
* @param name Name of the entity you want so search.
|
||||
* @return Edict Index or INVALID_ENT_REFERENCE if no entity was found.
|
||||
*/
|
||||
stock int Edict_FindByName(const char[] name)
|
||||
{
|
||||
int maxEntities = GetMaxEntities();
|
||||
for (int edict=0; edict < maxEntities; edict++) {
|
||||
|
||||
if (!IsValidEdict(edict)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Entity_NameMatches(edict, name)) {
|
||||
return edict;
|
||||
}
|
||||
}
|
||||
|
||||
return INVALID_ENT_REFERENCE;
|
||||
}
|
||||
|
||||
/*
|
||||
* Finds an edict by its HammerID.
|
||||
* The newer version of Valve's Hammer editor
|
||||
* sets a unique ID for each entity in a map.
|
||||
* It only finds the first occurence.
|
||||
*
|
||||
* @param hammerId Hammer editor ID
|
||||
* @return Edict Index or INVALID_ENT_REFERENCE if no entity was found.
|
||||
*/
|
||||
stock int Edict_FindByHammerId(int hammerId)
|
||||
{
|
||||
int maxEntities = GetMaxEntities();
|
||||
for (int edict=0; edict < maxEntities; edict++) {
|
||||
|
||||
if (!IsValidEdict(edict)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Entity_GetHammerId(edict) == hammerId) {
|
||||
return edict;
|
||||
}
|
||||
}
|
||||
|
||||
return INVALID_ENT_REFERENCE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for the closest edict in relation to the given origin
|
||||
*
|
||||
* @param vecOrigin_center 3 dimensional origin array
|
||||
* @param clientsOnly True if you only want to search for clients
|
||||
* @param ignoreEntity Ignore this entity
|
||||
* @return Edict Index or INVALID_ENT_REFERENCE if no entity was found.
|
||||
*/
|
||||
stock int Edict_GetClosest(float vecOrigin_center[3], bool clientsOnly=false, int ignoreEntity=-1)
|
||||
{
|
||||
float vecOrigin_edict[3];
|
||||
float smallestDistance = 0.0;
|
||||
int closestEdict = INVALID_ENT_REFERENCE;
|
||||
|
||||
int maxEntities;
|
||||
|
||||
if (clientsOnly) {
|
||||
maxEntities = MaxClients;
|
||||
}
|
||||
else {
|
||||
maxEntities = GetMaxEntities();
|
||||
}
|
||||
|
||||
for (int edict=1; edict <= maxEntities; edict++) {
|
||||
|
||||
if (!IsValidEdict(edict)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ignoreEntity >= 0 && edict == ignoreEntity) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (GetEntSendPropOffs(edict, "m_vecOrigin") == -1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Entity_GetAbsOrigin(edict, vecOrigin_edict);
|
||||
|
||||
float edict_distance = GetVectorDistance(vecOrigin_center, vecOrigin_edict, true);
|
||||
|
||||
if (edict_distance < smallestDistance || smallestDistance == 0.0) {
|
||||
smallestDistance = edict_distance;
|
||||
closestEdict = edict;
|
||||
}
|
||||
}
|
||||
|
||||
return closestEdict;
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for the closest edict in relation to the given edict.
|
||||
*
|
||||
* @param edict Edict index
|
||||
* @param clientsOnly True if you only want to search for clients
|
||||
* @return The closest edict or INVALID_ENT_REFERENCE
|
||||
*/
|
||||
stock int Edict_GetClosestToEdict(int edict, bool clientsOnly=false)
|
||||
{
|
||||
float vecOrigin[3];
|
||||
|
||||
if (!HasEntProp(edict, Prop_Send, "m_vecOrigin")) {
|
||||
return INVALID_ENT_REFERENCE;
|
||||
}
|
||||
|
||||
Entity_GetAbsOrigin(edict, vecOrigin);
|
||||
|
||||
return Edict_GetClosest(vecOrigin, clientsOnly, edict);
|
||||
}
|
722
scripting/include/smlib/effects.inc
Normal file
722
scripting/include/smlib/effects.inc
Normal file
|
@ -0,0 +1,722 @@
|
|||
#if defined _smlib_effects_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_effects_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <sdktools_entinput>
|
||||
#include <sdktools_tempents>
|
||||
#include <sdktools_tempents_stocks>
|
||||
#include <smlib/clients>
|
||||
#include <smlib/effects>
|
||||
#include <smlib/entities>
|
||||
#include <smlib/math>
|
||||
|
||||
|
||||
|
||||
// Entity Dissolve types
|
||||
enum DissolveType
|
||||
{
|
||||
DISSOLVE_NORMAL = 0,
|
||||
DISSOLVE_ELECTRICAL,
|
||||
DISSOLVE_ELECTRICAL_LIGHT,
|
||||
DISSOLVE_CORE
|
||||
};
|
||||
|
||||
/**
|
||||
* Dissolves a player
|
||||
*
|
||||
* @param client Client Index.
|
||||
* @param dissolveType Dissolve Type, use the DissolveType enum.
|
||||
* @param magnitude How strongly to push away from the center.
|
||||
* @return True on success, otherwise false.
|
||||
*/
|
||||
stock bool Effect_DissolveEntity(int entity, DissolveType dissolveType=DISSOLVE_NORMAL, int magnitude=1)
|
||||
{
|
||||
int env_entity_dissolver = CreateEntityByName("env_entity_dissolver");
|
||||
|
||||
if (env_entity_dissolver == -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Entity_PointAtTarget(env_entity_dissolver, entity);
|
||||
SetEntProp(env_entity_dissolver, Prop_Send, "m_nDissolveType", dissolveType);
|
||||
SetEntProp(env_entity_dissolver, Prop_Send, "m_nMagnitude", magnitude);
|
||||
AcceptEntityInput(env_entity_dissolver, "Dissolve");
|
||||
Entity_Kill(env_entity_dissolver);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dissolves a player's Ragdoll
|
||||
*
|
||||
* @param client Client Index.
|
||||
* @param dissolveType Dissolve Type, use the DissolveType enum.
|
||||
* @return True on success, otherwise false.
|
||||
*/
|
||||
stock bool Effect_DissolvePlayerRagDoll(int client, DissolveType dissolveType=DISSOLVE_NORMAL)
|
||||
{
|
||||
int m_hRagdoll = GetEntPropEnt(client, Prop_Send, "m_hRagdoll");
|
||||
|
||||
if (m_hRagdoll == -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Effect_DissolveEntity(m_hRagdoll, dissolveType);
|
||||
}
|
||||
|
||||
typedef EffectCallback = function void(int entity, any data);
|
||||
|
||||
/**
|
||||
* Fades an entity in our out.
|
||||
* You can specifiy a callback function which will get called
|
||||
* when the fade is finished.
|
||||
* Important: The callback will be called if it is passed,
|
||||
* no matter if the entity is still valid or not. That means you
|
||||
* have to check if the entity is valid yourself.
|
||||
*
|
||||
* @param entity Entity Index.
|
||||
* @param fadeOut Optional: Fade the entity out (true) or in (false).
|
||||
* @param kill Optional: If to kill the entity when the fade is finished.
|
||||
* @param fast Optional: Fade the entity fast (~0.7 secs) or slow (~3 secs)
|
||||
* @param callback Optional: You can specify a callback Function that will get called when the fade is finished.
|
||||
* @param data Optional: You can pass any data to the callback.
|
||||
*/
|
||||
stock void Effect_Fade(int entity, bool fadeOut=true, bool kill=false, bool fast=true, EffectCallback callback=INVALID_FUNCTION, any data=0)
|
||||
{
|
||||
float timerTime = 0.0;
|
||||
|
||||
if (fast) {
|
||||
timerTime = 0.6;
|
||||
|
||||
if (fadeOut) {
|
||||
SetEntityRenderFx(entity, RENDERFX_FADE_FAST);
|
||||
}
|
||||
else {
|
||||
SetEntityRenderFx(entity, RENDERFX_SOLID_FAST);
|
||||
}
|
||||
}
|
||||
else {
|
||||
timerTime = 3.0;
|
||||
|
||||
if (fadeOut) {
|
||||
SetEntityRenderFx(entity, RENDERFX_FADE_SLOW);
|
||||
}
|
||||
else {
|
||||
SetEntityRenderFx(entity, RENDERFX_SOLID_SLOW);
|
||||
}
|
||||
}
|
||||
|
||||
ChangeEdictState(entity, GetEntSendPropOffs(entity, "m_nRenderFX", true));
|
||||
|
||||
if (kill || callback != INVALID_FUNCTION) {
|
||||
DataPack dataPack = null;
|
||||
CreateDataTimer(timerTime, _smlib_Timer_Effect_Fade, dataPack, TIMER_FLAG_NO_MAPCHANGE | TIMER_DATA_HNDL_CLOSE);
|
||||
|
||||
WritePackCell(dataPack, EntIndexToEntRef(entity));
|
||||
WritePackCell(dataPack, kill);
|
||||
WritePackFunction(dataPack, callback);
|
||||
WritePackCell(dataPack, data);
|
||||
ResetPack(dataPack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fades the entity in.
|
||||
* A wrapper function around Effect_Fade().
|
||||
*
|
||||
* @param entity Entity Index.
|
||||
* @param fast Optional: Fade the entity fast (~0.7 secs) or slow (~3 secs)
|
||||
* @param callback Optional: You can specify a callback Function that will get called when the fade is finished.
|
||||
* @param data Optional: You can pass any data to the callback.
|
||||
*/
|
||||
stock void Effect_FadeIn(int entity, bool fast=true, EffectCallback callback=INVALID_FUNCTION, any data=0)
|
||||
{
|
||||
Effect_Fade(entity, false, false, fast, callback, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fades the entity out.
|
||||
* A wrapper function around Effect_Fade().
|
||||
*
|
||||
* @param entity Entity Index.
|
||||
* @param fadeOut Optional: Fade the entity out (true) or in (false).
|
||||
* @param kill Optional: If to kill the entity when the fade is finished.
|
||||
* @param fast Optional: Fade the entity fast (~0.7 secs) or slow (~3 secs)
|
||||
* @param callback Optional: You can specify a callback Function that will get called when the fade is finished.
|
||||
* @param data Optional: You can pass any data to the callback.
|
||||
*/
|
||||
stock void Effect_FadeOut(int entity, bool kill=false, bool fast=true, EffectCallback callback=INVALID_FUNCTION, any data=0)
|
||||
{
|
||||
Effect_Fade(entity, true, kill, fast, callback, data);
|
||||
}
|
||||
|
||||
public Action _smlib_Timer_Effect_Fade(Handle Timer, DataPack dataPack)
|
||||
{
|
||||
int entity = ReadPackCell(dataPack);
|
||||
int kill = ReadPackCell(dataPack);
|
||||
Function callback = ReadPackFunction(dataPack);
|
||||
any data = ReadPackCell(dataPack);
|
||||
|
||||
if (callback != INVALID_FUNCTION) {
|
||||
Call_StartFunction(INVALID_HANDLE, callback);
|
||||
Call_PushCell(entity);
|
||||
Call_PushCell(data);
|
||||
Call_Finish();
|
||||
}
|
||||
|
||||
if (kill && IsValidEntity(entity)) {
|
||||
Entity_Kill(entity);
|
||||
}
|
||||
|
||||
return Plugin_Stop;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a boxed beam effect to one player.
|
||||
*
|
||||
* Ported from eventscripts vecmath library.
|
||||
*
|
||||
* @param client The client to show the box to.
|
||||
* @param bottomCorner One bottom corner of the box.
|
||||
* @param upperCorner One upper corner of the box.
|
||||
* @param modelIndex Precached model index.
|
||||
* @param haloIndex Precached model index.
|
||||
* @param startFrame Initital frame to render.
|
||||
* @param frameRate Beam frame rate.
|
||||
* @param life Time duration of the beam.
|
||||
* @param width Initial beam width.
|
||||
* @param endWidth Final beam width.
|
||||
* @param fadeLength Beam fade time duration.
|
||||
* @param amplitude Beam amplitude.
|
||||
* @param color Color array (r, g, b, a).
|
||||
* @param speed Speed of the beam.
|
||||
*/
|
||||
stock void Effect_DrawBeamBoxToClient(
|
||||
int client,
|
||||
const float bottomCorner[3],
|
||||
const float upperCorner[3],
|
||||
int modelIndex,
|
||||
int haloIndex,
|
||||
int startFrame=0,
|
||||
int frameRate=30,
|
||||
float life=5.0,
|
||||
float width=5.0,
|
||||
float endWidth=5.0,
|
||||
int fadeLength=2,
|
||||
float amplitude=1.0,
|
||||
const int color[4]={ 255, 0, 0, 255 },
|
||||
int speed=0
|
||||
) {
|
||||
int clients[1];
|
||||
clients[0] = client;
|
||||
Effect_DrawBeamBox(clients, 1, bottomCorner, upperCorner, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a boxed beam effect to all players.
|
||||
*
|
||||
* Ported from eventscripts vecmath library.
|
||||
*
|
||||
* @param bottomCorner One bottom corner of the box.
|
||||
* @param upperCorner One upper corner of the box.
|
||||
* @param modelIndex Precached model index.
|
||||
* @param haloIndex Precached model index.
|
||||
* @param startFrame Initital frame to render.
|
||||
* @param frameRate Beam frame rate.
|
||||
* @param life Time duration of the beam.
|
||||
* @param width Initial beam width.
|
||||
* @param endWidth Final beam width.
|
||||
* @param fadeLength Beam fade time duration.
|
||||
* @param amplitude Beam amplitude.
|
||||
* @param color Color array (r, g, b, a).
|
||||
* @param speed Speed of the beam.
|
||||
*/
|
||||
stock void Effect_DrawBeamBoxToAll(
|
||||
const float bottomCorner[3],
|
||||
const float upperCorner[3],
|
||||
int modelIndex,
|
||||
int haloIndex,
|
||||
int startFrame=0,
|
||||
int frameRate=30,
|
||||
float life=5.0,
|
||||
float width=5.0,
|
||||
float endWidth=5.0,
|
||||
int fadeLength=2,
|
||||
float amplitude=1.0,
|
||||
const int color[4]={ 255, 0, 0, 255 },
|
||||
int speed=0
|
||||
)
|
||||
{
|
||||
int[] clients = new int[MaxClients];
|
||||
int numClients = Client_Get(clients, CLIENTFILTER_INGAME);
|
||||
|
||||
Effect_DrawBeamBox(clients, numClients, bottomCorner, upperCorner, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a boxed beam effect to a list of players.
|
||||
*
|
||||
* Ported from eventscripts vecmath library.
|
||||
*
|
||||
* @param clients An array of clients to show the box to.
|
||||
* @param numClients Number of players in the array.
|
||||
* @param bottomCorner One bottom corner of the box.
|
||||
* @param upperCorner One upper corner of the box.
|
||||
* @param modelIndex Precached model index.
|
||||
* @param haloIndex Precached model index.
|
||||
* @param startFrame Initital frame to render.
|
||||
* @param frameRate Beam frame rate.
|
||||
* @param life Time duration of the beam.
|
||||
* @param width Initial beam width.
|
||||
* @param endWidth Final beam width.
|
||||
* @param fadeLength Beam fade time duration.
|
||||
* @param amplitude Beam amplitude.
|
||||
* @param color Color array (r, g, b, a).
|
||||
* @param speed Speed of the beam.
|
||||
*/
|
||||
stock void Effect_DrawBeamBox(
|
||||
int[] clients,
|
||||
int numClients,
|
||||
const float bottomCorner[3],
|
||||
const float upperCorner[3],
|
||||
int modelIndex,
|
||||
int haloIndex,
|
||||
int startFrame=0,
|
||||
int frameRate=30,
|
||||
float life=5.0,
|
||||
float width=5.0,
|
||||
float endWidth=5.0,
|
||||
int fadeLength=2,
|
||||
float amplitude=1.0,
|
||||
const int color[4]={ 255, 0, 0, 255 },
|
||||
int speed=0
|
||||
) {
|
||||
// Create the additional corners of the box
|
||||
float corners[8][3];
|
||||
|
||||
for (int i=0; i < 4; i++) {
|
||||
Array_Copy(bottomCorner, corners[i], 3);
|
||||
Array_Copy(upperCorner, corners[i+4], 3);
|
||||
}
|
||||
|
||||
corners[1][0] = upperCorner[0];
|
||||
corners[2][0] = upperCorner[0];
|
||||
corners[2][1] = upperCorner[1];
|
||||
corners[3][1] = upperCorner[1];
|
||||
corners[4][0] = bottomCorner[0];
|
||||
corners[4][1] = bottomCorner[1];
|
||||
corners[5][1] = bottomCorner[1];
|
||||
corners[7][0] = bottomCorner[0];
|
||||
|
||||
// Draw all the edges
|
||||
|
||||
// Horizontal Lines
|
||||
// Bottom
|
||||
for (int i=0; i < 4; i++) {
|
||||
int j = ( i == 3 ? 0 : i+1 );
|
||||
TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed);
|
||||
TE_Send(clients, numClients);
|
||||
}
|
||||
|
||||
// Top
|
||||
for (int i=4; i < 8; i++) {
|
||||
int j = ( i == 7 ? 4 : i+1 );
|
||||
TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed);
|
||||
TE_Send(clients, numClients);
|
||||
}
|
||||
|
||||
// All Vertical Lines
|
||||
for (int i=0; i < 4; i++) {
|
||||
TE_SetupBeamPoints(corners[i], corners[i+4], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed);
|
||||
TE_Send(clients, numClients);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sends a boxed beam effect to one player.
|
||||
*
|
||||
* Ported from eventscripts vecmath library.
|
||||
*
|
||||
* @param client The client to show the box to.
|
||||
* @param origin Origin/center of the box.
|
||||
* @param mins Min size Vector
|
||||
* @param maxs Max size Vector
|
||||
* @param angles Angles used to rotate the box.
|
||||
* @param modelIndex Precached model index.
|
||||
* @param haloIndex Precached model index.
|
||||
* @param startFrame Initital frame to render.
|
||||
* @param frameRate Beam frame rate.
|
||||
* @param life Time duration of the beam.
|
||||
* @param width Initial beam width.
|
||||
* @param endWidth Final beam width.
|
||||
* @param fadeLength Beam fade time duration.
|
||||
* @param amplitude Beam amplitude.
|
||||
* @param color Color array (r, g, b, a).
|
||||
* @param speed Speed of the beam.
|
||||
*/
|
||||
stock void Effect_DrawBeamBoxRotatableToClient(
|
||||
int client,
|
||||
const float origin[3],
|
||||
const float mins[3],
|
||||
const float maxs[3],
|
||||
const float angles[3],
|
||||
int modelIndex,
|
||||
int haloIndex,
|
||||
int startFrame=0,
|
||||
int frameRate=30,
|
||||
float life=5.0,
|
||||
float width=5.0,
|
||||
float endWidth=5.0,
|
||||
int fadeLength=2,
|
||||
float amplitude=1.0,
|
||||
const int color[4]={ 255, 0, 0, 255 },
|
||||
int speed=0
|
||||
) {
|
||||
int clients[1];
|
||||
clients[0] = client;
|
||||
Effect_DrawBeamBoxRotatable(clients, 1, origin, mins, maxs, angles, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Sends a boxed beam effect to all players.
|
||||
*
|
||||
* Ported from eventscripts vecmath library.
|
||||
*
|
||||
* @param origin Origin/center of the box.
|
||||
* @param mins Min size Vector
|
||||
* @param maxs Max size Vector
|
||||
* @param angles Angles used to rotate the box.
|
||||
* @param modelIndex Precached model index.
|
||||
* @param haloIndex Precached model index.
|
||||
* @param startFrame Initital frame to render.
|
||||
* @param frameRate Beam frame rate.
|
||||
* @param life Time duration of the beam.
|
||||
* @param width Initial beam width.
|
||||
* @param endWidth Final beam width.
|
||||
* @param fadeLength Beam fade time duration.
|
||||
* @param amplitude Beam amplitude.
|
||||
* @param color Color array (r, g, b, a).
|
||||
* @param speed Speed of the beam.
|
||||
*/
|
||||
stock void Effect_DrawBeamBoxRotatableToAll(
|
||||
const float origin[3],
|
||||
const float mins[3],
|
||||
const float maxs[3],
|
||||
const float angles[3],
|
||||
int modelIndex,
|
||||
int haloIndex,
|
||||
int startFrame=0,
|
||||
int frameRate=30,
|
||||
float life=5.0,
|
||||
float width=5.0,
|
||||
float endWidth=5.0,
|
||||
int fadeLength=2,
|
||||
float amplitude=1.0,
|
||||
const int color[4]={ 255, 0, 0, 255 },
|
||||
int speed=0
|
||||
)
|
||||
{
|
||||
int[] clients = new int[MaxClients];
|
||||
int numClients = Client_Get(clients, CLIENTFILTER_INGAME);
|
||||
|
||||
Effect_DrawBeamBoxRotatable(clients, numClients, origin, mins, maxs, angles, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a boxed beam effect to a list of players.
|
||||
*
|
||||
* Ported from eventscripts vecmath library.
|
||||
*
|
||||
* @param clients An array of clients to show the box to.
|
||||
* @param numClients Number of players in the array.
|
||||
* @param origin Origin/center of the box.
|
||||
* @param mins Min size Vector
|
||||
* @param maxs Max size Vector
|
||||
* @param angles Angles used to rotate the box.
|
||||
* @param modelIndex Precached model index.
|
||||
* @param haloIndex Precached model index.
|
||||
* @param startFrame Initital frame to render.
|
||||
* @param frameRate Beam frame rate.
|
||||
* @param life Time duration of the beam.
|
||||
* @param width Initial beam width.
|
||||
* @param endWidth Final beam width.
|
||||
* @param fadeLength Beam fade time duration.
|
||||
* @param amplitude Beam amplitude.
|
||||
* @param color Color array (r, g, b, a).
|
||||
* @param speed Speed of the beam.
|
||||
*/
|
||||
stock void Effect_DrawBeamBoxRotatable(
|
||||
int[] clients,
|
||||
int numClients,
|
||||
const float origin[3],
|
||||
const float mins[3],
|
||||
const float maxs[3],
|
||||
const float angles[3],
|
||||
int modelIndex,
|
||||
int haloIndex,
|
||||
int startFrame=0,
|
||||
int frameRate=30,
|
||||
float life=5.0,
|
||||
float width=5.0,
|
||||
float endWidth=5.0,
|
||||
int fadeLength=2,
|
||||
float amplitude=1.0,
|
||||
const int color[4]={ 255, 0, 0, 255 },
|
||||
int speed=0
|
||||
) {
|
||||
// Create the additional corners of the box
|
||||
float corners[8][3];
|
||||
Array_Copy(mins, corners[0], 3);
|
||||
Math_MakeVector(maxs[0], mins[1], mins[2], corners[1]);
|
||||
Math_MakeVector(maxs[0], maxs[1], mins[2], corners[2]);
|
||||
Math_MakeVector(mins[0], maxs[1], mins[2], corners[3]);
|
||||
Math_MakeVector(mins[0], mins[1], maxs[2], corners[4]);
|
||||
Math_MakeVector(maxs[0], mins[1], maxs[2], corners[5]);
|
||||
Array_Copy(maxs, corners[6], 3);
|
||||
Math_MakeVector(mins[0], maxs[1], maxs[2], corners[7]);
|
||||
|
||||
// Rotate all edges
|
||||
for (int i=0; i < sizeof(corners); i++) {
|
||||
Math_RotateVector(corners[i], angles, corners[i]);
|
||||
}
|
||||
|
||||
// Apply world offset (after rotation)
|
||||
for (int i=0; i < sizeof(corners); i++) {
|
||||
AddVectors(origin, corners[i], corners[i]);
|
||||
}
|
||||
|
||||
// Draw all the edges
|
||||
// Horizontal Lines
|
||||
// Bottom
|
||||
for (int i=0; i < 4; i++) {
|
||||
int j = ( i == 3 ? 0 : i+1 );
|
||||
TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed);
|
||||
TE_Send(clients, numClients);
|
||||
}
|
||||
|
||||
// Top
|
||||
for (int i=4; i < 8; i++) {
|
||||
int j = ( i == 7 ? 4 : i+1 );
|
||||
TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed);
|
||||
TE_Send(clients, numClients);
|
||||
}
|
||||
|
||||
// All Vertical Lines
|
||||
for (int i=0; i < 4; i++) {
|
||||
TE_SetupBeamPoints(corners[i], corners[i+4], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed);
|
||||
TE_Send(clients, numClients);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the given axis of rotation as beam effect to one player.
|
||||
*
|
||||
* @param client The client to show the box to.
|
||||
* @param origin Origin/center of the box.
|
||||
* @param angles Angles used to rotate the box.
|
||||
* @param length The length in each direction.
|
||||
* @param modelIndex Precached model index.
|
||||
* @param haloIndex Precached model index.
|
||||
* @param startFrame Initital frame to render.
|
||||
* @param frameRate Beam frame rate.
|
||||
* @param life Time duration of the beam.
|
||||
* @param width Initial beam width.
|
||||
* @param endWidth Final beam width.
|
||||
* @param fadeLength Beam fade time duration.
|
||||
* @param amplitude Beam amplitude.
|
||||
* @param color Color array (r, g, b, a).
|
||||
* @param speed Speed of the beam.
|
||||
*/
|
||||
stock void Effect_DrawAxisOfRotationToClient(
|
||||
int client,
|
||||
const float origin[3],
|
||||
const float angles[3],
|
||||
const float length[3],
|
||||
int modelIndex,
|
||||
int haloIndex,
|
||||
int startFrame=0,
|
||||
int frameRate=30,
|
||||
float life=5.0,
|
||||
float width=5.0,
|
||||
float endWidth=5.0,
|
||||
int fadeLength=2,
|
||||
float amplitude=1.0,
|
||||
int speed=0
|
||||
) {
|
||||
int clients[1];
|
||||
clients[0] = client;
|
||||
Effect_DrawAxisOfRotation(clients, 1, origin, angles, length, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, speed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the given axis of rotation as beam effect to all players.
|
||||
*
|
||||
* @param origin Origin/center of the box.
|
||||
* @param angles Angles used to rotate the box.
|
||||
* @param length The length in each direction.
|
||||
* @param modelIndex Precached model index.
|
||||
* @param haloIndex Precached model index.
|
||||
* @param startFrame Initital frame to render.
|
||||
* @param frameRate Beam frame rate.
|
||||
* @param life Time duration of the beam.
|
||||
* @param width Initial beam width.
|
||||
* @param endWidth Final beam width.
|
||||
* @param fadeLength Beam fade time duration.
|
||||
* @param amplitude Beam amplitude.
|
||||
* @param color Color array (r, g, b, a).
|
||||
* @param speed Speed of the beam.
|
||||
*/
|
||||
stock void Effect_DrawAxisOfRotationToAll(
|
||||
const float origin[3],
|
||||
const float angles[3],
|
||||
const float length[3],
|
||||
int modelIndex,
|
||||
int haloIndex,
|
||||
int startFrame=0,
|
||||
int frameRate=30,
|
||||
float life=5.0,
|
||||
float width=5.0,
|
||||
float endWidth=5.0,
|
||||
int fadeLength=2,
|
||||
float amplitude=1.0,
|
||||
int speed=0
|
||||
)
|
||||
{
|
||||
int[] clients = new int[MaxClients];
|
||||
int numClients = Client_Get(clients, CLIENTFILTER_INGAME);
|
||||
|
||||
Effect_DrawAxisOfRotation(clients, numClients, origin, angles, length, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, speed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the given axis of rotation as beam effect to a list of players.
|
||||
*
|
||||
* @param clients An array of clients to show the box to.
|
||||
* @param numClients Number of players in the array.
|
||||
* @param origin Origin/center of the box.
|
||||
* @param angles Angles used to rotate the box.
|
||||
* @param length The length in each direction.
|
||||
* @param modelIndex Precached model index.
|
||||
* @param haloIndex Precached model index.
|
||||
* @param startFrame Initital frame to render.
|
||||
* @param frameRate Beam frame rate.
|
||||
* @param life Time duration of the beam.
|
||||
* @param width Initial beam width.
|
||||
* @param endWidth Final beam width.
|
||||
* @param fadeLength Beam fade time duration.
|
||||
* @param amplitude Beam amplitude.
|
||||
* @param color Color array (r, g, b, a).
|
||||
* @param speed Speed of the beam.
|
||||
*/
|
||||
stock void Effect_DrawAxisOfRotation(
|
||||
int[] clients,
|
||||
int numClients,
|
||||
const float origin[3],
|
||||
const float angles[3],
|
||||
const float length[3],
|
||||
int modelIndex,
|
||||
int haloIndex,
|
||||
int startFrame=0,
|
||||
int frameRate=30,
|
||||
float life=5.0,
|
||||
float width=5.0,
|
||||
float endWidth=5.0,
|
||||
int fadeLength=2,
|
||||
float amplitude=1.0,
|
||||
int speed=0
|
||||
) {
|
||||
// Create the additional corners of the box
|
||||
float xAxis[3], yAxis[3], zAxis[3];
|
||||
xAxis[0] = length[0];
|
||||
yAxis[1] = length[1];
|
||||
zAxis[2] = length[2];
|
||||
|
||||
// Rotate all edges
|
||||
Math_RotateVector(xAxis, angles, xAxis);
|
||||
Math_RotateVector(yAxis, angles, yAxis);
|
||||
Math_RotateVector(zAxis, angles, zAxis);
|
||||
|
||||
// Apply world offset (after rotation)
|
||||
AddVectors(origin, xAxis, xAxis);
|
||||
AddVectors(origin, yAxis, yAxis);
|
||||
AddVectors(origin, zAxis, zAxis);
|
||||
|
||||
// Draw all
|
||||
TE_SetupBeamPoints(origin, xAxis, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, {255, 0, 0, 255}, speed);
|
||||
TE_Send(clients, numClients);
|
||||
|
||||
TE_SetupBeamPoints(origin, yAxis, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, {0, 255, 0, 255}, speed);
|
||||
TE_Send(clients, numClients);
|
||||
|
||||
TE_SetupBeamPoints(origin, zAxis, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, {0, 0, 255, 255}, speed);
|
||||
TE_Send(clients, numClients);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates an env_sprite.
|
||||
*
|
||||
* @param origin Origin of the Sprite.
|
||||
* @param modelIndex Precached model index.
|
||||
* @param color Color array (r, g, b, a).
|
||||
* @param scale Scale (Note: many materials ignore a lower value than 0.25).
|
||||
* @param targetName Targetname of the sprite.
|
||||
* @param parent Entity Index of this sprite's parent in the movement hierarchy.
|
||||
* @param renderMode Render mode (use the enum).
|
||||
* @param renderFx Render fx (use the enum).
|
||||
* @param glowProxySize Radius size of the glow when to be rendered, if inside a geometry. Ex: a block 2x2x2 units big, if the glowProxySize is between 0.0 and 2.0 the sprite will not be rendered, even if the actual size of the sprite is bigger, everything above 2.0 will render the sprite. Using an abnormal high value will render Sprites trough walls.
|
||||
* @param frameRate Sprite frame rate.
|
||||
* @param hdrColorScale Float value to multiply sprite color by when running with HDR.
|
||||
* @param receiveShadows When false then this prevents the sprite from receiving shadows.
|
||||
* @return Entity Index of the created Sprite.
|
||||
*/
|
||||
stock int Effect_EnvSprite(
|
||||
const float origin[3],
|
||||
int modelIndex,
|
||||
const int color[4]={255, 255, 255, 255},
|
||||
float scale=0.25,
|
||||
const char targetName[MAX_NAME_LENGTH]="",
|
||||
int parent=-1,
|
||||
RenderMode renderMode=RENDER_WORLDGLOW,
|
||||
RenderFx renderFx=RENDERFX_NONE,
|
||||
float glowProxySize=2.0,
|
||||
float framerate=10.0,
|
||||
float hdrColorScale=1.0,
|
||||
bool receiveShadows = true
|
||||
) {
|
||||
int entity = Entity_Create("env_sprite");
|
||||
|
||||
if (entity == INVALID_ENT_REFERENCE) {
|
||||
return INVALID_ENT_REFERENCE;
|
||||
}
|
||||
|
||||
DispatchKeyValue (entity, "disablereceiveshadows", (receiveShadows) ? "0" : "1");
|
||||
DispatchKeyValueFloat (entity, "framerate", framerate);
|
||||
DispatchKeyValueFloat (entity, "GlowProxySize", glowProxySize);
|
||||
DispatchKeyValue (entity, "spawnflags", "1");
|
||||
DispatchKeyValueFloat (entity, "HDRColorScale", hdrColorScale);
|
||||
DispatchKeyValue (entity, "maxdxlevel", "0");
|
||||
DispatchKeyValue (entity, "mindxlevel", "0");
|
||||
DispatchKeyValueFloat (entity, "scale", scale);
|
||||
|
||||
DispatchSpawn(entity);
|
||||
|
||||
SetEntityRenderMode(entity, renderMode);
|
||||
SetEntityRenderColor(entity, color[0], color[1], color[2], color[3]);
|
||||
SetEntityRenderFx(entity, renderFx);
|
||||
|
||||
Entity_SetName(entity, targetName);
|
||||
Entity_SetModelIndex(entity, modelIndex);
|
||||
Entity_SetAbsOrigin(entity, origin);
|
||||
|
||||
if (parent != -1) {
|
||||
Entity_SetParent(entity, parent);
|
||||
}
|
||||
|
||||
return entity;
|
||||
}
|
2098
scripting/include/smlib/entities.inc
Normal file
2098
scripting/include/smlib/entities.inc
Normal file
File diff suppressed because it is too large
Load diff
451
scripting/include/smlib/files.inc
Normal file
451
scripting/include/smlib/files.inc
Normal file
|
@ -0,0 +1,451 @@
|
|||
#if defined _smlib_files_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_files_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <sdktools>
|
||||
#include <smlib/arrays>
|
||||
|
||||
/**
|
||||
* Gets the Base name of a path.
|
||||
* Examples:
|
||||
* blub.txt -> "blub.txt"
|
||||
* /sourcemod/extensions/example.ext.so -> "example.ext.so"
|
||||
*
|
||||
* @param path File path
|
||||
* @param buffer String buffer array
|
||||
* @param size Size of string buffer
|
||||
*/
|
||||
stock void File_GetBaseName(const char[] path, char[] buffer, int size)
|
||||
{
|
||||
if (path[0] == '\0') {
|
||||
buffer[0] = '\0';
|
||||
return;
|
||||
}
|
||||
|
||||
int pos_start = FindCharInString(path, '/', true);
|
||||
|
||||
if (pos_start == -1) {
|
||||
pos_start = FindCharInString(path, '\\', true);
|
||||
}
|
||||
|
||||
pos_start++;
|
||||
|
||||
strcopy(buffer, size, path[pos_start]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the Directory of a path (without the file name).
|
||||
* Does not work with "." as the path.
|
||||
* Examples:
|
||||
* blub.txt -> "blub.txt"
|
||||
* /sourcemod/extensions/example.ext.so -> "example.ext.so"
|
||||
*
|
||||
* @param path File path
|
||||
* @param buffer String buffer array
|
||||
* @param size Size of string buffer
|
||||
*/
|
||||
stock void File_GetDirName(const char[] path, char[] buffer, int size)
|
||||
{
|
||||
if (path[0] == '\0') {
|
||||
buffer[0] = '\0';
|
||||
return;
|
||||
}
|
||||
|
||||
int pos_start = FindCharInString(path, '/', true);
|
||||
|
||||
if (pos_start == -1) {
|
||||
pos_start = FindCharInString(path, '\\', true);
|
||||
|
||||
if (pos_start == -1) {
|
||||
buffer[0] = '\0';
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
strcopy(buffer, size, path);
|
||||
buffer[pos_start] = '\0';
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the File name of a path.
|
||||
* blub.txt -> "blub"
|
||||
* /sourcemod/extensions/example.ext.so -> "example.ext"
|
||||
*
|
||||
* @param path File path
|
||||
* @param buffer String buffer array
|
||||
* @param size Size of string buffer
|
||||
*/
|
||||
stock void File_GetFileName(const char[] path, char[] buffer, int size)
|
||||
{
|
||||
if (path[0] == '\0') {
|
||||
buffer[0] = '\0';
|
||||
return;
|
||||
}
|
||||
|
||||
File_GetBaseName(path, buffer, size);
|
||||
|
||||
int pos_ext = FindCharInString(buffer, '.', true);
|
||||
|
||||
if (pos_ext != -1) {
|
||||
buffer[pos_ext] = '\0';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the Extension of a file.
|
||||
* Examples:
|
||||
* blub.inc.txt -> "txt"
|
||||
* /sourcemod/extensions/example.ext.so -> "so"
|
||||
*
|
||||
* @param path Path String
|
||||
* @param buffer String buffer array
|
||||
* @param size Max length of string buffer
|
||||
*/
|
||||
stock void File_GetExtension(const char[] path, char[] buffer, int size)
|
||||
{
|
||||
int extpos = FindCharInString(path, '.', true);
|
||||
|
||||
if (extpos == -1) {
|
||||
buffer[0] = '\0';
|
||||
return;
|
||||
}
|
||||
|
||||
strcopy(buffer, size, path[++extpos]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a path to the downloadables network string table.
|
||||
* This can be a file or directory and also works recursed.
|
||||
* You can optionally specify file extensions that should be ignored.
|
||||
* Bz2 and ztmp are automatically ignored.
|
||||
* It only adds files that actually exist.
|
||||
* You can also specify a wildcard * after the ., very useful for models.
|
||||
* This forces a client to download the file if they do not already have it.
|
||||
*
|
||||
* @param path Path String
|
||||
* @param recursive Whether to do recursion or not.
|
||||
* @param ignoreExts Optional: 2 dimensional String array.You can define it like this: new String:ignore[][] = { ".ext1", ".ext2" };
|
||||
* @param size This should be set to the number of file extensions in the ignoreExts array (sizeof(ignore) for the example above)
|
||||
*/
|
||||
|
||||
// Damn you SourcePawn :( I didn't want to
|
||||
char _smlib_empty_twodimstring_array[][] = { { '\0' } };
|
||||
stock void File_AddToDownloadsTable(const char[] path, bool recursive=true, const char[][] ignoreExts=_smlib_empty_twodimstring_array, int size=0)
|
||||
{
|
||||
if (path[0] == '\0') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (FileExists(path)) {
|
||||
|
||||
char fileExtension[5];
|
||||
File_GetExtension(path, fileExtension, sizeof(fileExtension));
|
||||
|
||||
if (StrEqual(fileExtension, "bz2", false) || StrEqual(fileExtension, "ztmp", false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Array_FindString(ignoreExts, size, fileExtension) != -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
char path_new[PLATFORM_MAX_PATH];
|
||||
strcopy(path_new, sizeof(path_new), path);
|
||||
ReplaceString(path_new, sizeof(path_new), "//", "/");
|
||||
|
||||
AddFileToDownloadsTable(path_new);
|
||||
}
|
||||
else if (recursive && DirExists(path)) {
|
||||
|
||||
char dirEntry[PLATFORM_MAX_PATH];
|
||||
DirectoryListing __dir = OpenDirectory(path);
|
||||
|
||||
while (ReadDirEntry(__dir, dirEntry, sizeof(dirEntry))) {
|
||||
|
||||
if (StrEqual(dirEntry, ".") || StrEqual(dirEntry, "..")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Format(dirEntry, sizeof(dirEntry), "%s/%s", path, dirEntry);
|
||||
File_AddToDownloadsTable(dirEntry, recursive, ignoreExts, size);
|
||||
}
|
||||
|
||||
delete __dir;
|
||||
}
|
||||
else if (FindCharInString(path, '*', true)) {
|
||||
|
||||
char fileExtension[4];
|
||||
File_GetExtension(path, fileExtension, sizeof(fileExtension));
|
||||
|
||||
if (StrEqual(fileExtension, "*")) {
|
||||
|
||||
char dirName[PLATFORM_MAX_PATH],
|
||||
fileName[PLATFORM_MAX_PATH],
|
||||
dirEntry[PLATFORM_MAX_PATH];
|
||||
|
||||
File_GetDirName(path, dirName, sizeof(dirName));
|
||||
File_GetFileName(path, fileName, sizeof(fileName));
|
||||
StrCat(fileName, sizeof(fileName), ".");
|
||||
|
||||
DirectoryListing __dir = OpenDirectory(dirName);
|
||||
while (ReadDirEntry(__dir, dirEntry, sizeof(dirEntry))) {
|
||||
|
||||
if (StrEqual(dirEntry, ".") || StrEqual(dirEntry, "..")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (strncmp(dirEntry, fileName, strlen(fileName)) == 0) {
|
||||
Format(dirEntry, sizeof(dirEntry), "%s/%s", dirName, dirEntry);
|
||||
File_AddToDownloadsTable(dirEntry, recursive, ignoreExts, size);
|
||||
}
|
||||
}
|
||||
|
||||
delete __dir;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Adds all files/paths in the given text file to the download table.
|
||||
* Recursive mode enabled, see File_AddToDownloadsTable()
|
||||
* Comments are allowed ! Supported comment types are ; // #
|
||||
*
|
||||
* @param path Path to the .txt file.
|
||||
*/
|
||||
stock void File_ReadDownloadList(const char[] path)
|
||||
{
|
||||
File file = OpenFile(path, "r");
|
||||
|
||||
if (file == INVALID_HANDLE) {
|
||||
return;
|
||||
}
|
||||
|
||||
char buffer[PLATFORM_MAX_PATH];
|
||||
while (!IsEndOfFile(file)) {
|
||||
ReadFileLine(file, buffer, sizeof(buffer));
|
||||
|
||||
int pos;
|
||||
pos = StrContains(buffer, "//");
|
||||
if (pos != -1) {
|
||||
buffer[pos] = '\0';
|
||||
}
|
||||
|
||||
pos = StrContains(buffer, "#");
|
||||
if (pos != -1) {
|
||||
buffer[pos] = '\0';
|
||||
}
|
||||
|
||||
pos = StrContains(buffer, ";");
|
||||
if (pos != -1) {
|
||||
buffer[pos] = '\0';
|
||||
}
|
||||
|
||||
TrimString(buffer);
|
||||
|
||||
if (buffer[0] == '\0') {
|
||||
continue;
|
||||
}
|
||||
|
||||
File_AddToDownloadsTable(buffer);
|
||||
}
|
||||
|
||||
delete file;
|
||||
}
|
||||
|
||||
/*
|
||||
* Attempts to load a translation file and optionally unloads the plugin if the file
|
||||
* doesn't exist (also prints an error message).
|
||||
*
|
||||
* @param file Filename of the translations file (eg. <pluginname>.phrases).
|
||||
* @param setFailState If true, it sets the failstate if the translations file doesn't exist
|
||||
* @return True on success, false otherwise (only if setFailState is set to false)
|
||||
*/
|
||||
stock bool File_LoadTranslations(const char[] file, bool setFailState=true)
|
||||
{
|
||||
char path[PLATFORM_MAX_PATH];
|
||||
|
||||
BuildPath(Path_SM, path, sizeof(path), "translations/%s", file);
|
||||
|
||||
if (FileExists(path)) {
|
||||
LoadTranslations(file);
|
||||
return true;
|
||||
}
|
||||
|
||||
Format(path,sizeof(path), "%s.txt", path);
|
||||
|
||||
if (!FileExists(path)) {
|
||||
|
||||
if (setFailState) {
|
||||
SetFailState("Unable to locate translation file (%s).", path);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
LoadTranslations(file);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* Reads the contents of a given file into a string buffer in binary mode.
|
||||
*
|
||||
* @param path Path to the file
|
||||
* @param buffer String buffer
|
||||
* @param size If -1, reads until a null terminator is encountered in the file. Otherwise, read_count bytes are read into the buffer provided. In this case the buffer is not explicitly null terminated, and the buffer will contain any null terminators read from the file.
|
||||
* @return Number of characters written to the buffer, or -1 if an error was encountered.
|
||||
*/
|
||||
stock int File_ToString(const char[] path, char[] buffer, int size)
|
||||
{
|
||||
File file = OpenFile(path, "rb");
|
||||
|
||||
if (file == INVALID_HANDLE) {
|
||||
buffer[0] = '\0';
|
||||
return -1;
|
||||
}
|
||||
|
||||
int num_bytes_written = ReadFileString(file, buffer, size);
|
||||
delete file;
|
||||
|
||||
return num_bytes_written;
|
||||
}
|
||||
|
||||
/*
|
||||
* Writes a string into a file in binary mode.
|
||||
*
|
||||
* @param file Path to the file
|
||||
* @param str String to write
|
||||
* @return True on success, false otherwise
|
||||
*/
|
||||
stock bool File_StringToFile(const char[] path, char[] str)
|
||||
{
|
||||
File file = OpenFile(path, "wb");
|
||||
|
||||
if (file == INVALID_HANDLE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool success = WriteFileString(file, str, false);
|
||||
delete file;
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
/*
|
||||
* Copies file source to destination
|
||||
* Based on code of javalia:
|
||||
* http://forums.alliedmods.net/showthread.php?t=159895
|
||||
*
|
||||
* @param source Input file
|
||||
* @param destination Output file
|
||||
* @return True on success, false otherwise
|
||||
*/
|
||||
stock bool File_Copy(const char[] source, const char[] destination)
|
||||
{
|
||||
File file_source = OpenFile(source, "rb");
|
||||
|
||||
if (file_source == INVALID_HANDLE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
File file_destination = OpenFile(destination, "wb");
|
||||
|
||||
if (file_destination == INVALID_HANDLE) {
|
||||
delete file_source;
|
||||
return false;
|
||||
}
|
||||
|
||||
int buffer[32];
|
||||
int cache;
|
||||
|
||||
while (!IsEndOfFile(file_source)) {
|
||||
cache = ReadFile(file_source, buffer, sizeof(buffer), 1);
|
||||
WriteFile(file_destination, buffer, cache, 1);
|
||||
}
|
||||
|
||||
delete file_source;
|
||||
delete file_destination;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* Recursively copies (the content) of a directory or file specified
|
||||
* by "path" to "destination".
|
||||
* Note that because of Sourcemod API limitations this currently does not
|
||||
* takeover the file permissions (it leaves them default).
|
||||
* Links will be resolved.
|
||||
*
|
||||
* @param path Source path
|
||||
* @param destination Destination directory (This can only be a directory)
|
||||
* @param stop_on_error Optional: Set to true to stop on error (ie can't read a file)
|
||||
* @param dirMode Optional: File mode for directories that will be created (Default = 0755), don't forget to convert FROM octal
|
||||
* @return True on success, false otherwise
|
||||
*/
|
||||
stock bool File_CopyRecursive(const char[] path, const char[] destination, bool stop_on_error=false, int dirMode=493)
|
||||
{
|
||||
if (FileExists(path)) {
|
||||
return File_Copy(path, destination);
|
||||
}
|
||||
else if (DirExists(path)) {
|
||||
return Sub_File_CopyRecursive(path, destination, stop_on_error, FileType_Directory, dirMode);
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static stock bool Sub_File_CopyRecursive(const char[] path, const char[] destination, bool stop_on_error=false, FileType fileType, int dirMode)
|
||||
{
|
||||
if (fileType == FileType_File) {
|
||||
return File_Copy(path, destination);
|
||||
}
|
||||
else if (fileType == FileType_Directory) {
|
||||
|
||||
if (!CreateDirectory(destination, dirMode) && stop_on_error) {
|
||||
return false;
|
||||
}
|
||||
|
||||
DirectoryListing directory = OpenDirectory(path);
|
||||
|
||||
if (directory == INVALID_HANDLE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char
|
||||
source_buffer[PLATFORM_MAX_PATH],
|
||||
destination_buffer[PLATFORM_MAX_PATH];
|
||||
FileType type;
|
||||
|
||||
while (ReadDirEntry(directory, source_buffer, sizeof(source_buffer), type)) {
|
||||
|
||||
if (StrEqual(source_buffer, "..") || StrEqual(source_buffer, ".")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Format(destination_buffer, sizeof(destination_buffer), "%s/%s", destination, source_buffer);
|
||||
Format(source_buffer, sizeof(source_buffer), "%s/%s", path, source_buffer);
|
||||
|
||||
if (type == FileType_File) {
|
||||
File_Copy(source_buffer, destination_buffer);
|
||||
}
|
||||
else if (type == FileType_Directory) {
|
||||
|
||||
if (!File_CopyRecursive(source_buffer, destination_buffer, stop_on_error, dirMode) && stop_on_error) {
|
||||
delete directory;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
delete directory;
|
||||
}
|
||||
else if (fileType == FileType_Unknown) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
57
scripting/include/smlib/game.inc
Normal file
57
scripting/include/smlib/game.inc
Normal file
|
@ -0,0 +1,57 @@
|
|||
#if defined _smlib_game_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_game_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <sdktools_functions>
|
||||
#include <sdktools_entinput>
|
||||
|
||||
/*
|
||||
* End's the game and displays the scoreboard with intermission time.
|
||||
*
|
||||
* @return True on success, false otherwise
|
||||
*/
|
||||
stock bool Game_End()
|
||||
{
|
||||
int game_end = FindEntityByClassname(-1, "game_end");
|
||||
|
||||
if (game_end == -1) {
|
||||
game_end = CreateEntityByName("game_end");
|
||||
|
||||
if (game_end == -1) {
|
||||
ThrowError("Unable to find or create entity \"game_end\"");
|
||||
}
|
||||
}
|
||||
|
||||
return AcceptEntityInput(game_end, "EndGame");
|
||||
}
|
||||
|
||||
/*
|
||||
* End's the current round, allows specifying the winning
|
||||
* team and more.
|
||||
* This function currently works in TF2 only (it uses the game_round_win entity).
|
||||
*
|
||||
* @param team The winning Team, pass 0 for Sudden Death mode (no winning team)
|
||||
* @param forceMapReset If to force the map to reset during the force respawn after the round is over.
|
||||
* @param switchTeams If to switch the teams when the game is going to be reset.
|
||||
* @return True on success, false otherwise
|
||||
*/
|
||||
stock bool Game_EndRound(int team=0, bool forceMapReset=false, bool switchTeams=false)
|
||||
{
|
||||
int game_round_win = FindEntityByClassname(-1, "game_round_win");
|
||||
|
||||
if (game_round_win == -1) {
|
||||
game_round_win = CreateEntityByName("game_round_win");
|
||||
|
||||
if (game_round_win == -1) {
|
||||
ThrowError("Unable to find or create entity \"game_round_win\"");
|
||||
}
|
||||
}
|
||||
|
||||
DispatchKeyValue(game_round_win, "TeamNum" , (team ? "true" : "false"));
|
||||
DispatchKeyValue(game_round_win, "force_map_reset" , (forceMapReset? "true" : "false"));
|
||||
DispatchKeyValue(game_round_win, "switch_teams" , (switchTeams ? "true" : "false"));
|
||||
|
||||
return AcceptEntityInput(game_round_win, "RoundWin");
|
||||
}
|
251
scripting/include/smlib/general.inc
Normal file
251
scripting/include/smlib/general.inc
Normal file
|
@ -0,0 +1,251 @@
|
|||
#if defined _smlib_general_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_general_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <sdktools_stringtables>
|
||||
#include <smlib/math>
|
||||
|
||||
#define TIME_TO_TICKS(%1) ( (int)( 0.5 + (float)(%1) / GetTickInterval() ) )
|
||||
#define TICKS_TO_TIME(%1) ( GetTickInterval() * %1 )
|
||||
#define ROUND_TO_TICKS(%1) ( TICK_INTERVAL * TIME_TO_TICKS( %1 ) )
|
||||
|
||||
/*
|
||||
* Precaches the given model.
|
||||
* It's best to call this OnMapStart().
|
||||
*
|
||||
* @param material Path of the material to precache.
|
||||
* @return Returns the material index, INVALID_STRING_INDEX on error.
|
||||
*/
|
||||
stock int PrecacheMaterial(const char[] material)
|
||||
{
|
||||
static int materialNames = INVALID_STRING_TABLE;
|
||||
|
||||
if (materialNames == INVALID_STRING_TABLE) {
|
||||
if ((materialNames = FindStringTable("Materials")) == INVALID_STRING_TABLE) {
|
||||
return INVALID_STRING_INDEX;
|
||||
}
|
||||
}
|
||||
|
||||
int index = FindStringIndex2(materialNames, material);
|
||||
if (index == INVALID_STRING_INDEX) {
|
||||
int numStrings = GetStringTableNumStrings(materialNames);
|
||||
if (numStrings >= GetStringTableMaxStrings(materialNames)) {
|
||||
return INVALID_STRING_INDEX;
|
||||
}
|
||||
|
||||
AddToStringTable(materialNames, material);
|
||||
index = numStrings;
|
||||
}
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
/*
|
||||
* Checks if the material is precached.
|
||||
*
|
||||
* @param material Path of the material.
|
||||
* @return True if it is precached, false otherwise.
|
||||
*/
|
||||
stock bool IsMaterialPrecached(const char[] material)
|
||||
{
|
||||
static int materialNames = INVALID_STRING_TABLE;
|
||||
|
||||
if (materialNames == INVALID_STRING_TABLE) {
|
||||
if ((materialNames = FindStringTable("Materials")) == INVALID_STRING_TABLE) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return (FindStringIndex2(materialNames, material) != INVALID_STRING_INDEX);
|
||||
}
|
||||
|
||||
/*
|
||||
* Precaches the given particle system.
|
||||
* It's best to call this OnMapStart().
|
||||
* Code based on Rochellecrab's, thanks.
|
||||
*
|
||||
* @param particleSystem Name of the particle system to precache.
|
||||
* @return Returns the particle system index, INVALID_STRING_INDEX on error.
|
||||
*/
|
||||
stock int PrecacheParticleSystem(const char[] particleSystem)
|
||||
{
|
||||
static int particleEffectNames = INVALID_STRING_TABLE;
|
||||
|
||||
if (particleEffectNames == INVALID_STRING_TABLE) {
|
||||
if ((particleEffectNames = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) {
|
||||
return INVALID_STRING_INDEX;
|
||||
}
|
||||
}
|
||||
|
||||
int index = FindStringIndex2(particleEffectNames, particleSystem);
|
||||
if (index == INVALID_STRING_INDEX) {
|
||||
int numStrings = GetStringTableNumStrings(particleEffectNames);
|
||||
if (numStrings >= GetStringTableMaxStrings(particleEffectNames)) {
|
||||
return INVALID_STRING_INDEX;
|
||||
}
|
||||
|
||||
AddToStringTable(particleEffectNames, particleSystem);
|
||||
index = numStrings;
|
||||
}
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
/*
|
||||
* Checks if the particle system is precached.
|
||||
*
|
||||
* @param material Name of the particle system
|
||||
* @return True if it is precached, false otherwise.
|
||||
*/
|
||||
stock bool IsParticleSystemPrecached(const char[] particleSystem)
|
||||
{
|
||||
static int particleEffectNames = INVALID_STRING_TABLE;
|
||||
|
||||
if (particleEffectNames == INVALID_STRING_TABLE) {
|
||||
if ((particleEffectNames = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return (FindStringIndex2(particleEffectNames, particleSystem) != INVALID_STRING_INDEX);
|
||||
}
|
||||
|
||||
/*
|
||||
* Searches for the index of a given string in a string table.
|
||||
*
|
||||
* @param table String table name.
|
||||
* @param str String to find.
|
||||
* @return String index if found, INVALID_STRING_INDEX otherwise.
|
||||
*/
|
||||
stock int FindStringIndexByTableName(const char[] table, const char[] str)
|
||||
{
|
||||
int tableIndex = INVALID_STRING_TABLE;
|
||||
if ((tableIndex = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) {
|
||||
return INVALID_STRING_INDEX;
|
||||
}
|
||||
|
||||
return FindStringIndex2(tableIndex, str);
|
||||
}
|
||||
|
||||
/*
|
||||
* Rewrite of FindStringIndex, because in my tests
|
||||
* FindStringIndex failed to work correctly.
|
||||
* Searches for the index of a given string in a string table.
|
||||
*
|
||||
* @param tableidx A string table index.
|
||||
* @param str String to find.
|
||||
* @return String index if found, INVALID_STRING_INDEX otherwise.
|
||||
*/
|
||||
stock int FindStringIndex2(int tableidx, const char[] str)
|
||||
{
|
||||
char buf[1024];
|
||||
|
||||
int numStrings = GetStringTableNumStrings(tableidx);
|
||||
for (int i=0; i < numStrings; i++) {
|
||||
ReadStringTable(tableidx, i, buf, sizeof(buf));
|
||||
|
||||
if (StrEqual(buf, str)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return INVALID_STRING_INDEX;
|
||||
}
|
||||
|
||||
/*
|
||||
* Converts a long IP to a dotted format String.
|
||||
*
|
||||
* @param ip IP Long
|
||||
* @param buffer String Buffer (size = 16)
|
||||
* @param size String Buffer size
|
||||
*/
|
||||
stock void LongToIP(int ip, char[] buffer, int size)
|
||||
{
|
||||
Format(
|
||||
buffer, size,
|
||||
"%d.%d.%d.%d",
|
||||
(ip >> 24) & 0xFF,
|
||||
(ip >> 16) & 0xFF,
|
||||
(ip >> 8 ) & 0xFF,
|
||||
ip & 0xFF
|
||||
);
|
||||
}
|
||||
|
||||
/*
|
||||
* Converts a dotted format String IP to a long.
|
||||
*
|
||||
* @param ip IP String
|
||||
* @return Long IP
|
||||
*/
|
||||
stock int IPToLong(const char[] ip)
|
||||
{
|
||||
char pieces[4][4];
|
||||
|
||||
if (ExplodeString(ip, ".", pieces, sizeof(pieces), sizeof(pieces[])) != 4) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (
|
||||
StringToInt(pieces[0]) << 24 |
|
||||
StringToInt(pieces[1]) << 16 |
|
||||
StringToInt(pieces[2]) << 8 |
|
||||
StringToInt(pieces[3])
|
||||
);
|
||||
}
|
||||
|
||||
static int localIPRanges[] =
|
||||
{
|
||||
10 << 24, // 10.
|
||||
127 << 24 | 1 , // 127.0.0.1
|
||||
127 << 24 | 16 << 16, // 127.16.
|
||||
192 << 24 | 168 << 16, // 192.168.
|
||||
};
|
||||
|
||||
/*
|
||||
* Checks whether an IP is a private/internal IP
|
||||
*
|
||||
* @param ip IP Long
|
||||
* @return True if the IP is local, false otherwise.
|
||||
*/
|
||||
stock bool IsIPLocal(int ip)
|
||||
{
|
||||
int range, bits, move;
|
||||
bool matches;
|
||||
|
||||
for (int i=0; i < sizeof(localIPRanges); i++) {
|
||||
|
||||
range = localIPRanges[i];
|
||||
matches = true;
|
||||
|
||||
for (int j=0; j < 4; j++) {
|
||||
move = j * 8;
|
||||
bits = (range >> move) & 0xFF;
|
||||
|
||||
if (bits && bits != ((ip >> move) & 0xFF)) {
|
||||
matches = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (matches) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Closes the given hindle and sets it to INVALID_HANDLE.
|
||||
* Obsolete now. Just use |delete handle|.
|
||||
*
|
||||
* @param handle handle
|
||||
*/
|
||||
stock void ClearHandle(Handle &handle)
|
||||
{
|
||||
if (handle != INVALID_HANDLE) {
|
||||
CloseHandle(handle);
|
||||
handle = INVALID_HANDLE;
|
||||
}
|
||||
}
|
346
scripting/include/smlib/math.inc
Normal file
346
scripting/include/smlib/math.inc
Normal file
|
@ -0,0 +1,346 @@
|
|||
#if defined _smlib_math_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_math_included
|
||||
|
||||
#include <sourcemod>
|
||||
|
||||
#define SIZE_OF_INT 2147483647 // without 0
|
||||
#define INT_MAX_DIGITS 10
|
||||
|
||||
#define GAMEUNITS_TO_METERS 0.01905
|
||||
#define METERS_TO_GAMEUNITS 52.49343832020997
|
||||
#define METERS_TO_FEET 3.2808399
|
||||
#define FEET_TO_METERS 0.3048
|
||||
#define KILOMETERS_TO_MILES 0.62137
|
||||
|
||||
enum VecAngle
|
||||
{
|
||||
ANG_ALPHA,
|
||||
ANG_BETA,
|
||||
ANG_GAMMA
|
||||
};
|
||||
|
||||
/**
|
||||
* Makes a negative integer number to a positive integer number.
|
||||
* This is faster than Sourcemod's native FloatAbs() for integers.
|
||||
* Use FloatAbs() for Float numbers.
|
||||
*
|
||||
* @param number A number that can be positive or negative.
|
||||
* @return Positive number.
|
||||
*/
|
||||
stock int Math_Abs(int value)
|
||||
{
|
||||
return (value ^ (value >> 31)) - (value >> 31);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if 2 vectors are equal.
|
||||
* You can specfiy a tolerance, which is the maximum distance at which vectors are considered equals
|
||||
*
|
||||
* @param vec1 First vector (3 dim array)
|
||||
* @param vec2 Second vector (3 dim array)
|
||||
* @param tolerance If you want to check that those vectors are somewhat even. 0.0 means they are 100% even if this function returns true.
|
||||
* @return True if vectors are equal, false otherwise.
|
||||
*/
|
||||
stock bool Math_VectorsEqual(float vec1[3], float vec2[3], float tolerance=0.0)
|
||||
{
|
||||
float distance = GetVectorDistance(vec1, vec2, true);
|
||||
|
||||
return distance <= (tolerance * tolerance);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the given value to min
|
||||
* if the value is smaller than the given.
|
||||
* Don't use this with float values.
|
||||
*
|
||||
* @param value Value
|
||||
* @param min Min Value used as lower border
|
||||
* @return Correct value not lower than min
|
||||
*/
|
||||
stock any Math_Min(any value, any min)
|
||||
{
|
||||
if (value < min) {
|
||||
value = min;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the given value to max
|
||||
* if the value is greater than the given.
|
||||
* Don't use this with float values.
|
||||
*
|
||||
* @param value Value
|
||||
* @param max Max Value used as upper border
|
||||
* @return Correct value not upper than max
|
||||
*/
|
||||
stock any Math_Max(any value, any max)
|
||||
{
|
||||
if (value > max) {
|
||||
value = max;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes sure a value is within a certain range and
|
||||
* returns the value.
|
||||
* If the value is outside the range it is set to either
|
||||
* min or max, if it is inside the range it will just return
|
||||
* the specified value.
|
||||
* Don't use this with float values.
|
||||
*
|
||||
* @param value Value
|
||||
* @param min Min value used as lower border
|
||||
* @param max Max value used as upper border
|
||||
* @return Correct value not lower than min and not greater than max.
|
||||
*/
|
||||
stock any Math_Clamp(any value, any min, any max)
|
||||
{
|
||||
value = Math_Min(value, min);
|
||||
value = Math_Max(value, max);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/*
|
||||
* Checks if the value is within the given bounds (min & max).
|
||||
* Don't use this with float values.
|
||||
*
|
||||
* @param value The value you want to check.
|
||||
* @param min The lower border.
|
||||
* @param max The upper border.
|
||||
* @return True if the value is within bounds (bigger or equal min / smaller or equal max), false otherwise.
|
||||
*/
|
||||
stock bool Math_IsInBounds(any value, any min, any max)
|
||||
{
|
||||
if (value < min || value > max) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Let's the specified value "overflow" if it is outside the given limit.
|
||||
* This is like with integers when it reaches a value above the max possible
|
||||
* integer size.
|
||||
* Don't use this with float values.
|
||||
*
|
||||
* @param value Value
|
||||
* @param min Min value used as lower border
|
||||
* @param max Max value used as upper border
|
||||
* @return Overflowed number
|
||||
*/
|
||||
stock any Math_Overflow(any value, any min, any max)
|
||||
{
|
||||
return (value % max) + min;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a random, uniform Integer number in the specified (inclusive) range.
|
||||
* This is safe to use multiple times in a function.
|
||||
* The seed is set automatically for each plugin.
|
||||
* Rewritten by MatthiasVance, thanks.
|
||||
*
|
||||
* @param min Min value used as lower border
|
||||
* @param max Max value used as upper border
|
||||
* @return Random Integer number between min and max
|
||||
*/
|
||||
stock int Math_GetRandomInt(int min, int max)
|
||||
{
|
||||
int random = GetURandomInt();
|
||||
|
||||
if (random == 0) {
|
||||
random++;
|
||||
}
|
||||
|
||||
return RoundToCeil(float(random) / (float(SIZE_OF_INT) / float(max - min + 1))) + min - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a random, uniform Float number in the specified (inclusive) range.
|
||||
* This is safe to use multiple times in a function.
|
||||
* The seed is set automatically for each plugin.
|
||||
*
|
||||
* @param min Min value used as lower border
|
||||
* @param max Max value used as upper border
|
||||
* @return Random Float number between min and max
|
||||
*/
|
||||
stock float Math_GetRandomFloat(float min, float max)
|
||||
{
|
||||
return (GetURandomFloat() * (max - min)) + min;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the percentage of amount in all as Integer where
|
||||
* amount and all are numbers and amount usually
|
||||
* is a subset of all.
|
||||
*
|
||||
* @param value Integer value
|
||||
* @param all Integer value
|
||||
* @return An Integer value between 0 and 100 (inclusive).
|
||||
*/
|
||||
stock int Math_GetPercentage(int value, int all) {
|
||||
return RoundToNearest((float(value) / float(all)) * 100.0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the percentage of amount in all as Float where
|
||||
* amount and all are numbers and amount usually
|
||||
* is a subset of all.
|
||||
*
|
||||
* @param value Float value
|
||||
* @param all Float value
|
||||
* @return A Float value between 0.0 and 100.0 (inclusive).
|
||||
*/
|
||||
stock float Math_GetPercentageFloat(float value, float all) {
|
||||
return (value / all) * 100.0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Moves the start vector on a direct line to the end vector by the given scale.
|
||||
* Note: If scale is 0.0 the output will be the same as the start vector and if scale is 1.0 the output vector will be the same as the end vector.
|
||||
* Exmaple usage: Move an entity to another entity but only 12 units: Vector_MoveVector(entity1Origin,entity2Origin,(12.0 / GetVectorDistance(entity1Origin,entity2Origin)),newEntity1Origin); now only teleport your entity to newEntity1Origin.
|
||||
*
|
||||
* @param start The start vector where the imagined line starts.
|
||||
* @param end The end vector where the imagined line ends.
|
||||
* @param scale The position on the line 0.0 is the start 1.0 is the end.
|
||||
* @param output Output vector
|
||||
*/
|
||||
stock void Math_MoveVector(const float start[3], const float end[3], float scale, float output[3])
|
||||
{
|
||||
SubtractVectors(end,start,output);
|
||||
ScaleVector(output,scale);
|
||||
AddVectors(start,output,output);
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts x, y and z into a vector.
|
||||
*
|
||||
* @param x Float value.
|
||||
* @param y Float value.
|
||||
* @param z Float value.
|
||||
* @param result Output vector.
|
||||
*/
|
||||
stock void Math_MakeVector(float x, float y, float z, float result[3])
|
||||
{
|
||||
result[0] = x;
|
||||
result[1] = y;
|
||||
result[2] = z;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotates a vector around its zero-point.
|
||||
* Note: As example you can rotate mins and maxs of an entity and then add its origin to mins and maxs to get its bounding box in relation to the world and its rotation.
|
||||
* When used with players use the following angle input:
|
||||
* angles[0] = 0.0;
|
||||
* angles[1] = 0.0;
|
||||
* angles[2] = playerEyeAngles[1];
|
||||
*
|
||||
* @param vec Vector to rotate.
|
||||
* @param angles How to rotate the vector.
|
||||
* @param result Output vector.
|
||||
*/
|
||||
stock void Math_RotateVector(const float vec[3], const float angles[3], float result[3])
|
||||
{
|
||||
// First the angle/radiant calculations
|
||||
float rad[3];
|
||||
// I don't really know why, but the alpha, beta, gamma order of the angles are messed up...
|
||||
// 2 = xAxis
|
||||
// 0 = yAxis
|
||||
// 1 = zAxis
|
||||
rad[0] = DegToRad(angles[2]);
|
||||
rad[1] = DegToRad(angles[0]);
|
||||
rad[2] = DegToRad(angles[1]);
|
||||
|
||||
// Pre-calc function calls
|
||||
float cosAlpha = Cosine(rad[0]);
|
||||
float sinAlpha = Sine(rad[0]);
|
||||
float cosBeta = Cosine(rad[1]);
|
||||
float sinBeta = Sine(rad[1]);
|
||||
float cosGamma = Cosine(rad[2]);
|
||||
float sinGamma = Sine(rad[2]);
|
||||
|
||||
// 3D rotation matrix for more information: http://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions
|
||||
float x = vec[0], y = vec[1], z = vec[2];
|
||||
float newX, newY, newZ;
|
||||
newY = cosAlpha*y - sinAlpha*z;
|
||||
newZ = cosAlpha*z + sinAlpha*y;
|
||||
y = newY;
|
||||
z = newZ;
|
||||
|
||||
newX = cosBeta*x + sinBeta*z;
|
||||
newZ = cosBeta*z - sinBeta*x;
|
||||
x = newX;
|
||||
z = newZ;
|
||||
|
||||
newX = cosGamma*x - sinGamma*y;
|
||||
newY = cosGamma*y + sinGamma*x;
|
||||
x = newX;
|
||||
y = newY;
|
||||
|
||||
// Store everything...
|
||||
result[0] = x;
|
||||
result[1] = y;
|
||||
result[2] = z;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts Source Game Units to metric Meters
|
||||
*
|
||||
* @param units Float value
|
||||
* @return Meters as Float value.
|
||||
*/
|
||||
stock float Math_UnitsToMeters(float units)
|
||||
{
|
||||
return (units * GAMEUNITS_TO_METERS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts Source Game Units to Meters
|
||||
*
|
||||
* @param units Float value
|
||||
* @return Feet as Float value.
|
||||
*/
|
||||
stock float Math_UnitsToFeet(float units)
|
||||
{
|
||||
return (Math_UnitsToMeters(units) * METERS_TO_FEET);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts Source Game Units to Centimeters
|
||||
*
|
||||
* @param units Float value
|
||||
* @return Centimeters as Float value.
|
||||
*/
|
||||
stock float Math_UnitsToCentimeters(float units)
|
||||
{
|
||||
return (Math_UnitsToMeters(units) * 100.0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts Source Game Units to Kilometers
|
||||
*
|
||||
* @param units Float value
|
||||
* @return Kilometers as Float value.
|
||||
*/
|
||||
stock float Math_UnitsToKilometers(float units)
|
||||
{
|
||||
return (Math_UnitsToMeters(units) / 1000.0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts Source Game Units to Miles
|
||||
*
|
||||
* @param units Float value
|
||||
* @return Miles as Float value.
|
||||
*/
|
||||
stock float Math_UnitsToMiles(float units)
|
||||
{
|
||||
return (Math_UnitsToKilometers(units) * KILOMETERS_TO_MILES);
|
||||
}
|
37
scripting/include/smlib/menus.inc
Normal file
37
scripting/include/smlib/menus.inc
Normal file
|
@ -0,0 +1,37 @@
|
|||
#if defined _smlib_menus_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_menus_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <smlib/math>
|
||||
|
||||
/**
|
||||
* Adds an option to a menu with a String display but an integer
|
||||
* identifying the option.
|
||||
*
|
||||
* @param menu Handle to the menu
|
||||
* @param value Integer value for the option
|
||||
* @param display Display text for the menu
|
||||
*/
|
||||
stock void Menu_AddIntItem(Menu menu, any value, char[] display)
|
||||
{
|
||||
char buffer[INT_MAX_DIGITS + 1];
|
||||
IntToString(value, buffer, sizeof(buffer));
|
||||
menu.AddItem(buffer, display);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves an integer-value choice from a menu, where the
|
||||
* menu's information strings were created as integers.
|
||||
*
|
||||
* @param menu Handle to the menu
|
||||
* @param param2 The item position selected from the menu.
|
||||
* @return Integer choice from the menu, or 0 if the integer could not be parsed.
|
||||
*/
|
||||
stock any Menu_GetIntItem(Menu menu, any param2)
|
||||
{
|
||||
char buffer[INT_MAX_DIGITS + 1];
|
||||
menu.GetItem(param2, buffer, sizeof(buffer));
|
||||
return StringToInt(buffer);
|
||||
}
|
135
scripting/include/smlib/server.inc
Normal file
135
scripting/include/smlib/server.inc
Normal file
|
@ -0,0 +1,135 @@
|
|||
#if defined _smlib_server_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_server_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <smlib/general>
|
||||
|
||||
/*
|
||||
* Gets the server's public/external (default) or
|
||||
* private/local (usually server's behind a NAT) IP.
|
||||
* If your server is behind a NAT Router, you need the SteamTools
|
||||
* extension available at http://forums.alliedmods.net/showthread.php?t=129763
|
||||
* to get the public IP. <steamtools> has to be included BEFORE <smlib>.
|
||||
* If the server is not behind NAT, the public IP is the same as the private IP.
|
||||
*
|
||||
* @param public Set to true to retrieve the server's public/external IP, false otherwise.
|
||||
* @return Long IP or 0 if the IP couldn't be retrieved.
|
||||
*/
|
||||
stock int Server_GetIP(bool public_=true)
|
||||
{
|
||||
int ip = 0;
|
||||
|
||||
static ConVar cvHostip = null;
|
||||
|
||||
if (cvHostip == INVALID_HANDLE) {
|
||||
cvHostip = FindConVar("hostip");
|
||||
MarkNativeAsOptional("Steam_GetPublicIP");
|
||||
}
|
||||
|
||||
if (cvHostip != INVALID_HANDLE) {
|
||||
ip = cvHostip.IntValue;
|
||||
}
|
||||
|
||||
if (ip != 0 && IsIPLocal(ip) == public_) {
|
||||
ip = 0;
|
||||
}
|
||||
|
||||
#if defined _steamtools_included
|
||||
if (ip == 0) {
|
||||
if (CanTestFeatures() && GetFeatureStatus(FeatureType_Native, "Steam_GetPublicIP") == FeatureStatus_Available) {
|
||||
int octets[4];
|
||||
Steam_GetPublicIP(octets);
|
||||
|
||||
ip =
|
||||
octets[0] << 24 |
|
||||
octets[1] << 16 |
|
||||
octets[2] << 8 |
|
||||
octets[3];
|
||||
|
||||
if (IsIPLocal(ip) == public_) {
|
||||
ip = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
return ip;
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets the server's public/external (default) or
|
||||
* private/local (usually server's behind a NAT) as IP String in dotted format.
|
||||
* If your server is behind a NAT Router, you need the SteamTools
|
||||
* extension available at http://forums.alliedmods.net/showthread.php?t=129763
|
||||
* to get the public IP. <steamtools> has to be included BEFORE <smlib>.
|
||||
* If the public IP couldn't be found, an empty String is returned.
|
||||
* If the server is not behind NAT, the public IP is the same as the private IP.
|
||||
*
|
||||
* @param buffer String buffer (size=16)
|
||||
* @param size String buffer size.
|
||||
* @param public Set to true to retrieve the server's public/external IP, false otherwise.
|
||||
* @return True on success, false otherwise.
|
||||
*/
|
||||
stock bool Server_GetIPString(char[] buffer, int size, bool public_=true)
|
||||
{
|
||||
int ip;
|
||||
|
||||
if ((ip = Server_GetIP(public_)) == 0) {
|
||||
buffer[0] = '\0';
|
||||
return false;
|
||||
}
|
||||
|
||||
LongToIP(ip, buffer, size);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets the server's local port.
|
||||
*
|
||||
* @noparam
|
||||
* @return The server's port, 0 if there is no port.
|
||||
*/
|
||||
stock int Server_GetPort()
|
||||
{
|
||||
static ConVar cvHostport = null;
|
||||
|
||||
if (cvHostport == INVALID_HANDLE) {
|
||||
cvHostport = FindConVar("hostport");
|
||||
}
|
||||
|
||||
if (cvHostport == INVALID_HANDLE) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int port = cvHostport.IntValue;
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets the server's hostname
|
||||
*
|
||||
* @param hostname String buffer
|
||||
* @param size String buffer size
|
||||
* @return True on success, false otherwise.
|
||||
*/
|
||||
stock bool Server_GetHostName(char[] buffer, int size)
|
||||
{
|
||||
static ConVar cvHostname = null;
|
||||
|
||||
if (cvHostname == INVALID_HANDLE) {
|
||||
cvHostname = FindConVar("hostname");
|
||||
}
|
||||
|
||||
if (cvHostname == INVALID_HANDLE) {
|
||||
buffer[0] = '\0';
|
||||
return false;
|
||||
}
|
||||
|
||||
cvHostname.GetString(buffer, size);
|
||||
|
||||
return true;
|
||||
}
|
107
scripting/include/smlib/sql.inc
Normal file
107
scripting/include/smlib/sql.inc
Normal file
|
@ -0,0 +1,107 @@
|
|||
#if defined _smlib_sql_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_sql_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <dbi>
|
||||
|
||||
/**
|
||||
* Executes a threaded SQL Query (See: SQL_TQuery)
|
||||
* This function supports the printf Syntax.
|
||||
*
|
||||
*
|
||||
* @param database A database Handle.
|
||||
* @param callback Callback; database is in "owner" and the query Handle is passed in "hndl".
|
||||
* @param data Extra data value to pass to the callback.
|
||||
* @param format Query string, printf syntax supported
|
||||
* @param priority Priority queue to use
|
||||
* @param ... Variable number of format parameters.
|
||||
*/
|
||||
stock void SQL_TQueryF(Database database, SQLTCallback callback, any data, DBPriority priority=DBPrio_Normal, const char[] format, any ...) {
|
||||
|
||||
if (!database) {
|
||||
ThrowError("[SMLIB] Error: Invalid database handle.");
|
||||
return;
|
||||
}
|
||||
|
||||
char query[16384];
|
||||
VFormat(query, sizeof(query), format, 6);
|
||||
|
||||
SQL_TQuery(database, callback, query, data, priority);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches an integer from a field in the current row of a result set (See: SQL_FetchInt)
|
||||
*
|
||||
* @param query A query (or statement) Handle.
|
||||
* @param field The field index (starting from 0).
|
||||
* @param result Optional variable to store the status of the return value.
|
||||
* @return An integer value.
|
||||
* @error Invalid query Handle or field index, invalid
|
||||
* type conversion requested from the database,
|
||||
* or no current result set.
|
||||
*/
|
||||
stock int SQL_FetchIntByName(DBResultSet query, const char[] fieldName, DBResult &result=DBVal_Error) {
|
||||
|
||||
int fieldNum;
|
||||
SQL_FieldNameToNum(query, fieldName, fieldNum);
|
||||
|
||||
return SQL_FetchInt(query, fieldNum, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches a bool from a field in the current row of a result set (See: SQL_FetchInt)
|
||||
*
|
||||
* @param query A query (or statement) Handle.
|
||||
* @param field The field index (starting from 0).
|
||||
* @param result Optional variable to store the status of the return value.
|
||||
* @return A bool value.
|
||||
* @error Invalid query Handle or field index, invalid
|
||||
* type conversion requested from the database,
|
||||
* or no current result set.
|
||||
*/
|
||||
stock bool SQL_FetchBoolByName(DBResultSet query, const char[] fieldName, DBResult &result=DBVal_Error) {
|
||||
|
||||
return SQL_FetchIntByName(query, fieldName, result) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches a float from a field in the current row of a result set. (See: SQL_FetchFloat)
|
||||
*
|
||||
* @param query A query (or statement) Handle.
|
||||
* @param field The field index (starting from 0).
|
||||
* @param result Optional variable to store the status of the return value.
|
||||
* @return A float value.
|
||||
* @error Invalid query Handle or field index, invalid
|
||||
* type conversion requested from the database,
|
||||
* or no current result set.
|
||||
*/
|
||||
stock float SQL_FetchFloatByName(DBResultSet query, const char[] fieldName, DBResult &result=DBVal_Error) {
|
||||
|
||||
int fieldNum;
|
||||
SQL_FieldNameToNum(query, fieldName, fieldNum);
|
||||
|
||||
return SQL_FetchFloat(query, fieldNum, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches a string from a field in the current row of a result set. (See: SQL_FetchString)
|
||||
*
|
||||
* @param query A query (or statement) Handle.
|
||||
* @param field The field index (starting from 0).
|
||||
* @param buffer String buffer.
|
||||
* @param maxlength Maximum size of the string buffer.
|
||||
* @param result Optional variable to store the status of the return value.
|
||||
* @return Number of bytes written.
|
||||
* @error Invalid query Handle or field index, invalid
|
||||
* type conversion requested from the database,
|
||||
* or no current result set.
|
||||
*/
|
||||
stock int SQL_FetchStringByName(DBResultSet query, const char[] fieldName, char[] buffer, int maxlength, DBResult &result=DBVal_Error) {
|
||||
|
||||
int fieldNum;
|
||||
SQL_FieldNameToNum(query, fieldName, fieldNum);
|
||||
|
||||
return SQL_FetchString(query, fieldNum, buffer, maxlength, result);
|
||||
}
|
228
scripting/include/smlib/strings.inc
Normal file
228
scripting/include/smlib/strings.inc
Normal file
|
@ -0,0 +1,228 @@
|
|||
#if defined _smlib_strings_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_strings_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <smlib/math>
|
||||
|
||||
/**
|
||||
* Checks if the string is numeric.
|
||||
* This correctly handles + - . in the String.
|
||||
*
|
||||
* @param str String to check.
|
||||
* @return True if the String is numeric, false otherwise..
|
||||
*/
|
||||
stock bool String_IsNumeric(const char[] str)
|
||||
{
|
||||
int x=0;
|
||||
int dotsFound=0;
|
||||
int numbersFound=0;
|
||||
|
||||
if (str[x] == '+' || str[x] == '-') {
|
||||
x++;
|
||||
}
|
||||
|
||||
while (str[x] != '\0') {
|
||||
|
||||
if (IsCharNumeric(str[x])) {
|
||||
numbersFound++;
|
||||
}
|
||||
else if (str[x] == '.') {
|
||||
dotsFound++;
|
||||
|
||||
if (dotsFound > 1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
|
||||
x++;
|
||||
}
|
||||
|
||||
if (!numbersFound) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trims a string by removing the specified chars from beginning and ending.
|
||||
* Removes all ' ', '\t', '\r', '\n' characters by default.
|
||||
* The Output String can be the same as the Input String.
|
||||
*
|
||||
* @param str Input String.
|
||||
* @param output Output String (Can be the as the input).
|
||||
* @param size Size of the output String.
|
||||
* @param chars Characters to remove.
|
||||
*/
|
||||
stock void String_Trim(const char[] str, char[] output, int size, const char[] chrs=" \t\r\n")
|
||||
{
|
||||
int x=0;
|
||||
while (str[x] != '\0' && FindCharInString(chrs, str[x]) != -1) {
|
||||
x++;
|
||||
}
|
||||
|
||||
x = strcopy(output, size, str[x]);
|
||||
x--;
|
||||
|
||||
while (x >= 0 && FindCharInString(chrs, output[x]) != -1) {
|
||||
x--;
|
||||
}
|
||||
|
||||
output[++x] = '\0';
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a list of strings from a string.
|
||||
*
|
||||
* @param buffer Input/Output buffer.
|
||||
* @param removeList A list of strings which should be removed from buffer.
|
||||
* @param size Number of Strings in the List.
|
||||
* @param caseSensitive If true, comparison is case sensitive. If false (default), comparison is case insensitive.
|
||||
*/
|
||||
stock void String_RemoveList(char[] buffer, const char[][] removeList, int size, bool caseSensitive=false)
|
||||
{
|
||||
for (int i=0; i < size; i++) {
|
||||
ReplaceString(buffer, SIZE_OF_INT, removeList[i], "", caseSensitive);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the whole String to lower case.
|
||||
* Only works with alphabetical characters (not ÖÄÜ) because Sourcemod suxx !
|
||||
* The Output String can be the same as the Input String.
|
||||
*
|
||||
* @param input Input String.
|
||||
* @param output Output String.
|
||||
* @param size Max Size of the Output string
|
||||
*/
|
||||
stock void String_ToLower(const char[] input, char[] output, int size)
|
||||
{
|
||||
size--;
|
||||
|
||||
int x=0;
|
||||
while (input[x] != '\0' && x < size) {
|
||||
|
||||
output[x] = CharToLower(input[x]);
|
||||
|
||||
x++;
|
||||
}
|
||||
|
||||
output[x] = '\0';
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the whole String to upper case.
|
||||
* Only works with alphabetical characters (not öäü) because Sourcemod suxx !
|
||||
* The Output String can be the same as the Input String.
|
||||
*
|
||||
* @param input Input String.
|
||||
* @param output Output String.
|
||||
* @param size Max Size of the Output string
|
||||
*/
|
||||
stock void String_ToUpper(const char[] input, char[] output, int size)
|
||||
{
|
||||
size--;
|
||||
|
||||
int x=0;
|
||||
while (input[x] != '\0' && x < size) {
|
||||
|
||||
output[x] = CharToUpper(input[x]);
|
||||
|
||||
x++;
|
||||
}
|
||||
|
||||
output[x] = '\0';
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a random string.
|
||||
*
|
||||
*
|
||||
* @param buffer String Buffer.
|
||||
* @param size String Buffer size (must be length+1)
|
||||
* @param length Number of characters being generated.
|
||||
* @param chrs String for specifying the characters used for random character generation.
|
||||
* By default it will use all letters of the alphabet (upper and lower) and all numbers.
|
||||
* If you pass an empty String, it will use all readable ASCII characters (33 - 126)
|
||||
*/
|
||||
stock void String_GetRandom(char[] buffer, int size, int length=32, const char[] chrs="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234556789")
|
||||
{
|
||||
int random, len;
|
||||
size--;
|
||||
|
||||
if (chrs[0] != '\0') {
|
||||
len = strlen(chrs) - 1;
|
||||
}
|
||||
|
||||
int n = 0;
|
||||
while (n < length && n < size) {
|
||||
|
||||
if (chrs[0] == '\0') {
|
||||
random = Math_GetRandomInt(33, 126);
|
||||
buffer[n] = random;
|
||||
}
|
||||
else {
|
||||
random = Math_GetRandomInt(0, len);
|
||||
buffer[n] = chrs[random];
|
||||
}
|
||||
|
||||
n++;
|
||||
}
|
||||
|
||||
buffer[length] = '\0';
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if string str starts with subString.
|
||||
*
|
||||
*
|
||||
* @param str String to check
|
||||
* @param subString Sub-String to check in str
|
||||
* @return True if str starts with subString, false otherwise.
|
||||
*/
|
||||
stock bool String_StartsWith(const char[] str, const char[] subString)
|
||||
{
|
||||
int n = 0;
|
||||
while (subString[n] != '\0') {
|
||||
|
||||
if (str[n] == '\0' || str[n] != subString[n]) {
|
||||
return false;
|
||||
}
|
||||
|
||||
n++;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if string str ends with subString.
|
||||
*
|
||||
*
|
||||
* @param str String to check
|
||||
* @param subString Sub-String to check in str
|
||||
* @return True if str ends with subString, false otherwise.
|
||||
*/
|
||||
stock bool String_EndsWith(const char[] str, const char[] subString)
|
||||
{
|
||||
int n_str = strlen(str) - 1;
|
||||
int n_subString = strlen(subString) - 1;
|
||||
|
||||
if(n_str < n_subString) {
|
||||
return false;
|
||||
}
|
||||
|
||||
while (n_str != 0 && n_subString != 0) {
|
||||
|
||||
if (str[n_str--] != subString[n_subString--]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
317
scripting/include/smlib/teams.inc
Normal file
317
scripting/include/smlib/teams.inc
Normal file
|
@ -0,0 +1,317 @@
|
|||
#if defined _smlib_teams_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_teams_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <smlib/clients>
|
||||
#include <smlib/entities>
|
||||
|
||||
#define MAX_TEAMS 32 // Max number of teams in a game
|
||||
#define MAX_TEAM_NAME_LENGTH 32 // Max length of a team's name
|
||||
|
||||
// Team Defines
|
||||
#define TEAM_INVALID -1
|
||||
#define TEAM_UNASSIGNED 0
|
||||
#define TEAM_SPECTATOR 1
|
||||
#define TEAM_ONE 2
|
||||
#define TEAM_TWO 3
|
||||
#define TEAM_THREE 4
|
||||
#define TEAM_FOUR 5
|
||||
|
||||
/*
|
||||
* If one team is empty its assumed single team mode is enabled and the game won't start.
|
||||
*
|
||||
* @noparam
|
||||
* @return True if one team is empty, false otherwise.
|
||||
*/
|
||||
stock bool Team_HaveAllPlayers(bool countFakeClients=true) {
|
||||
|
||||
int teamCount = GetTeamCount();
|
||||
for (int i=2; i < teamCount; i++) {
|
||||
|
||||
if (Team_GetClientCount(i, ((countFakeClients) ? CLIENTFILTER_ALL : CLIENTFILTER_NOBOTS)) == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns the client count of the players in a team.
|
||||
*
|
||||
* @param team Team Index.
|
||||
* @param flags Client Filter Flags (Use the CLIENTFILTER_ constants).
|
||||
* @return Client count in the server.
|
||||
*/
|
||||
stock int Team_GetClientCount(int team, int flags=0)
|
||||
{
|
||||
flags |= CLIENTFILTER_INGAME;
|
||||
|
||||
int numClients = 0;
|
||||
for (int client=1; client <= MaxClients; client++) {
|
||||
|
||||
if (!Client_MatchesFilter(client, flags)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (GetClientTeam(client) == team) {
|
||||
numClients++;
|
||||
}
|
||||
}
|
||||
|
||||
return numClients;
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns the client counts of the first two teams (eg.: Terrorists - Counter).
|
||||
* Use this function for optimization if you have to get the counts of both teams,
|
||||
* otherwise use Team_GetClientCount().
|
||||
*
|
||||
* @param team1 Pass an integer variable by reference
|
||||
* @param team2 Pass an integer variable by reference
|
||||
* @param flags Client Filter Flags (Use the CLIENTFILTER_ constants).
|
||||
*/
|
||||
stock void Team_GetClientCounts(int &team1=0, int &team2=0, int flags=0)
|
||||
{
|
||||
flags |= CLIENTFILTER_INGAME;
|
||||
|
||||
for (int client=1; client <= MaxClients; client++) {
|
||||
|
||||
if (!Client_MatchesFilter(client, flags)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (GetClientTeam(client) == TEAM_ONE) {
|
||||
team1++;
|
||||
}
|
||||
else if (GetClientTeam(client) == TEAM_TWO) {
|
||||
team2++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets the name of a team.
|
||||
* Don't call this before OnMapStart()
|
||||
*
|
||||
* @param index Team Index.
|
||||
* @param str String buffer
|
||||
* @param size String Buffer Size
|
||||
* @return True on success, false otherwise
|
||||
*/
|
||||
stock bool Team_GetName(int index, char[] str, int size)
|
||||
{
|
||||
int edict = Team_GetEdict(index);
|
||||
|
||||
if (edict == -1) {
|
||||
str[0] = '\0';
|
||||
return false;
|
||||
}
|
||||
|
||||
GetEntPropString(edict, Prop_Send, "m_szTeamname", str, size);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* Changes a team's name.
|
||||
* Use this carefully !
|
||||
* Only set the teamname OnMapStart() or OnEntityCreated()
|
||||
* when no players are ingame, otherwise it can crash the server.
|
||||
*
|
||||
* @param index Team Index.
|
||||
* @param name New Name String
|
||||
* @return True on success, false otherwise
|
||||
*/
|
||||
stock bool Team_SetName(int index, const char[] name)
|
||||
{
|
||||
int edict = Team_GetEdict(index);
|
||||
|
||||
if (edict == -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
SetEntPropString(edict, Prop_Send, "m_szTeamname", name);
|
||||
ChangeEdictState(edict, GetEntSendPropOffs(edict, "m_szTeamname", true));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* Changes a team's score.
|
||||
* Don't use this before OnMapStart().
|
||||
*
|
||||
* @param index Team Index.
|
||||
* @return Team Score or -1 if the team is not valid.
|
||||
*/
|
||||
stock int Team_GetScore(int index)
|
||||
{
|
||||
int edict = Team_GetEdict(index);
|
||||
|
||||
if (edict == -1) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return GetEntProp(edict, Prop_Send, "m_iScore");
|
||||
}
|
||||
|
||||
/*
|
||||
* Changes a team's score.
|
||||
* Don't use this before OnMapStart().
|
||||
*
|
||||
* @param index Team Index.
|
||||
* @param score Score value.
|
||||
* @return True on success, false otherwise
|
||||
*/
|
||||
stock bool Team_SetScore(int index, int score)
|
||||
{
|
||||
int edict = Team_GetEdict(index);
|
||||
|
||||
if (edict == -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
SetEntProp(edict, Prop_Send, "m_iScore", score);
|
||||
|
||||
ChangeEdictState(edict, GetEntSendPropOffs(edict, "m_iScore", true));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets a team's edict (*team_manager) Team Index.
|
||||
* Don't call this before OnMapStart()
|
||||
*
|
||||
* @param edict Edict
|
||||
* @return Team Index
|
||||
*/
|
||||
stock int Team_EdictGetNum(int edict)
|
||||
{
|
||||
return GetEntProp(edict, Prop_Send, "m_iTeamNum");
|
||||
}
|
||||
|
||||
/*
|
||||
* Check's whether the index is a valid team index or not.
|
||||
* Don't call this before OnMapStart()
|
||||
*
|
||||
* @param index Index.
|
||||
* @return True if the Index is a valid team, false otherwise.
|
||||
*/
|
||||
stock bool Team_IsValid(int index)
|
||||
{
|
||||
return (Team_GetEdict(index) != -1);
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets a team's edict (team_manager) Team Index.
|
||||
* Don't call this before OnMapStart()
|
||||
*
|
||||
* @param index Edict
|
||||
* @return Team Index
|
||||
*/
|
||||
stock int Team_EdictIsValid(int edict)
|
||||
{
|
||||
return GetEntProp(edict, Prop_Send, "m_iTeamNum");
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets a team's edict (team_manager).
|
||||
* This function caches found team edicts.
|
||||
* Don't call this before OnMapStart()
|
||||
*
|
||||
* @param index Team Index.
|
||||
* @return Team edict or -1 if not found
|
||||
*/
|
||||
stock int Team_GetEdict(int index)
|
||||
{
|
||||
static int teams[MAX_TEAMS] = { INVALID_ENT_REFERENCE, ... };
|
||||
|
||||
if (index < 0 || index > MAX_TEAMS) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
int edict = teams[index];
|
||||
if (Entity_IsValid(edict)) {
|
||||
return edict;
|
||||
}
|
||||
|
||||
bool foundTeamManager = false;
|
||||
|
||||
int maxEntities = GetMaxEntities();
|
||||
for (int entity=MaxClients+1; entity < maxEntities; entity++) {
|
||||
|
||||
if (!IsValidEntity(entity)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Entity_ClassNameMatches(entity, "team_manager", true)) {
|
||||
foundTeamManager = true;
|
||||
}
|
||||
// Do not continue when no team managers are found anymore (for optimization)
|
||||
else if (foundTeamManager) {
|
||||
return -1;
|
||||
}
|
||||
else {
|
||||
continue;
|
||||
}
|
||||
|
||||
int num = Team_EdictGetNum(entity);
|
||||
|
||||
if (num >= 0 && num <= MAX_TEAMS) {
|
||||
teams[num] = EntIndexToEntRef(entity);
|
||||
}
|
||||
|
||||
if (num == index) {
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/*
|
||||
* Trys to find a client in the specified team.
|
||||
* This function is NOT random, it returns the first
|
||||
* or the cached player (Use Client_GetRandom() instead).
|
||||
*
|
||||
* @param index Team Index.
|
||||
* @return Client Index or -1 if no client was found in the specified team.
|
||||
*/
|
||||
stock int Team_GetAnyClient(int index)
|
||||
{
|
||||
static int client_cache[MAX_TEAMS] = {-1, ...};
|
||||
int client;
|
||||
|
||||
if (index > 0) {
|
||||
client = client_cache[index];
|
||||
|
||||
if (client > 0 && client <= MaxClients) {
|
||||
|
||||
if (IsClientInGame(client) && GetClientTeam(client) == index) {
|
||||
return client;
|
||||
}
|
||||
}
|
||||
else {
|
||||
client = -1;
|
||||
}
|
||||
}
|
||||
|
||||
for (client=1; client <= MaxClients; client++) {
|
||||
|
||||
if (!IsClientInGame(client)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (GetClientTeam(client) != index) {
|
||||
continue;
|
||||
}
|
||||
|
||||
client_cache[index] = client;
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
137
scripting/include/smlib/vehicles.inc
Normal file
137
scripting/include/smlib/vehicles.inc
Normal file
|
@ -0,0 +1,137 @@
|
|||
#if defined _smlib_vehicles_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_vehicles_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <sdktools_entinput>
|
||||
#include <sdktools_functions>
|
||||
#include <smlib/entities>
|
||||
|
||||
/**
|
||||
* Returns the vehicle's driver.
|
||||
* If there is no driver in the vehicle, -1 is returned.
|
||||
*
|
||||
* @param vehicle Entity index.
|
||||
* @return Client index, or -1 if there is no driver.
|
||||
*/
|
||||
stock int Vehicle_GetDriver(int vehicle)
|
||||
{
|
||||
int m_hVehicle = GetEntPropEnt(vehicle, Prop_Send, "m_hPlayer");
|
||||
|
||||
return m_hVehicle;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether there is a driver in the vehicle or not.
|
||||
*
|
||||
* @param vehicle Entity index.
|
||||
* @return True if the vehicle has a driver, false otherwise
|
||||
*/
|
||||
stock bool Vehicle_HasDriver(int vehicle)
|
||||
{
|
||||
return Vehicle_GetDriver(vehicle) != -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kicks the driver ouf of the vehicle
|
||||
*
|
||||
* @param vehicle Entity index.
|
||||
* @return True on success, false otherwise.
|
||||
*/
|
||||
stock bool Vehicle_ExitDriver(int vehicle)
|
||||
{
|
||||
if (!Vehicle_HasDriver(vehicle)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return AcceptEntityInput(vehicle, "ExitVehicle");
|
||||
}
|
||||
|
||||
/**
|
||||
* Start's the vehicle's engine
|
||||
*
|
||||
* @param vehicle Entity index.
|
||||
* @return True on success, false otherwise.
|
||||
*/
|
||||
stock bool Vehicle_TurnOn(int vehicle)
|
||||
{
|
||||
return AcceptEntityInput(vehicle, "TurnOn");
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuts down the vehicle's engine
|
||||
*
|
||||
* @param vehicle Entity index.
|
||||
* @return True on success, false otherwise.
|
||||
*/
|
||||
stock bool Vehicle_TurnOff(int vehicle)
|
||||
{
|
||||
return AcceptEntityInput(vehicle, "TurnOff");
|
||||
}
|
||||
|
||||
/**
|
||||
* Locks the vehicle.
|
||||
*
|
||||
* @param vehicle Entity index.
|
||||
* @return True on success, false otherwise.
|
||||
*/
|
||||
stock bool Vehicle_Lock(int vehicle)
|
||||
{
|
||||
return AcceptEntityInput(vehicle, "Lock");
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlocks the vehicle.
|
||||
*
|
||||
* @param vehicle Entity index.
|
||||
* @return True on success, false otherwise.
|
||||
*/
|
||||
stock bool Vehicle_Unlock(int vehicle)
|
||||
{
|
||||
return AcceptEntityInput(vehicle, "Unlock");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns wether the entity is a valid vehicle or not.
|
||||
*
|
||||
* @param vehicle Entity index.
|
||||
* @return True if it is a valid vehicle, false otherwise.
|
||||
*/
|
||||
stock bool Vehicle_IsValid(int vehicle)
|
||||
{
|
||||
if (!Entity_IsValid(vehicle)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Entity_ClassNameMatches(vehicle, "prop_vehicle", true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the vehicle script from a vehicle.
|
||||
* This script contains all the vehicle settings like its speed
|
||||
* and that stuff.
|
||||
*
|
||||
* @param vehicle Entity index.
|
||||
* @param buffer String Buffer.
|
||||
* @param size String Buffer size.
|
||||
* @noreturn
|
||||
*/
|
||||
stock void Vehicle_GetScript(int vehicle, char[] buffer, int size)
|
||||
{
|
||||
GetEntPropString(vehicle, Prop_Data, "m_vehicleScript", buffer, size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the script of a vehicle.
|
||||
* This script contains all the vehicle settings like its speed
|
||||
* and that stuff.
|
||||
*
|
||||
* @param vehicle Entity index.
|
||||
* @param buffer Vehicle Script path.
|
||||
* @noreturn
|
||||
*/
|
||||
stock void Vehicle_SetScript(int vehicle, char[] script)
|
||||
{
|
||||
DispatchKeyValue(vehicle, "vehiclescript", script);
|
||||
}
|
393
scripting/include/smlib/weapons.inc
Normal file
393
scripting/include/smlib/weapons.inc
Normal file
|
@ -0,0 +1,393 @@
|
|||
#if defined _smlib_weapons_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_weapons_included
|
||||
|
||||
#include <sourcemod>
|
||||
#include <sdktools_functions>
|
||||
#include <smlib/entities>
|
||||
|
||||
#define MAX_WEAPON_OFFSET 64
|
||||
#define MAX_WEAPON_SLOTS 6 // hud item selection slots
|
||||
#define MAX_WEAPON_POSITIONS 20 // max number of items within a slot
|
||||
#define MAX_WEAPONS 48 // Max number of weapons availabl
|
||||
#define WEAPON_NOCLIP -1 // clip sizes set to this tell the weapon it doesn't use a clip
|
||||
#define MAX_AMMO_TYPES 32
|
||||
#define MAX_AMMO_SLOTS 32 // not really slots
|
||||
|
||||
#define MAX_WEAPON_STRING 80
|
||||
#define MAX_WEAPON_PREFIX 16
|
||||
#define MAX_WEAPON_AMMO_NAME 32
|
||||
|
||||
/*
|
||||
* Gets the owner (usually a client) of the weapon
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return Owner of the weapon or INVALID_ENT_REFERENCE if the weapon has no owner.
|
||||
*/
|
||||
stock int Weapon_GetOwner(int weapon)
|
||||
{
|
||||
return GetEntPropEnt(weapon, Prop_Data, "m_hOwner");
|
||||
}
|
||||
|
||||
/*
|
||||
* Sets the owner (usually a client) of the weapon
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @param entity Entity Index.
|
||||
* @noreturn
|
||||
*/
|
||||
stock void Weapon_SetOwner(int weapon, int entity)
|
||||
{
|
||||
SetEntPropEnt(weapon, Prop_Data, "m_hOwner", entity);
|
||||
}
|
||||
|
||||
/*
|
||||
* Checks whether the entity is a valid weapon or not.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return True if the entity is a valid weapon, false otherwise.
|
||||
*/
|
||||
stock bool Weapon_IsValid(int weapon)
|
||||
{
|
||||
if (!IsValidEdict(weapon)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Entity_ClassNameMatches(weapon, "weapon_", true);
|
||||
}
|
||||
|
||||
/*
|
||||
* Create's a weapon and spawns it in the world at the specified location.
|
||||
*
|
||||
* @param className Classname String of the weapon to spawn
|
||||
* @param absOrigin Absolute Origin Vector where to spawn the weapon.
|
||||
* @param absAngles Absolute Angles Vector.
|
||||
* @return Weapon Index of the created weapon or INVALID_ENT_REFERENCE on error.
|
||||
*/
|
||||
stock int Weapon_Create(const char[] className, float absOrigin[3], float absAngles[3])
|
||||
{
|
||||
int weapon = Entity_Create(className);
|
||||
|
||||
if (weapon == INVALID_ENT_REFERENCE) {
|
||||
return INVALID_ENT_REFERENCE;
|
||||
}
|
||||
|
||||
Entity_SetAbsOrigin(weapon, absOrigin);
|
||||
Entity_SetAbsAngles(weapon, absAngles);
|
||||
|
||||
DispatchSpawn(weapon);
|
||||
|
||||
return weapon;
|
||||
}
|
||||
|
||||
/*
|
||||
* Create's a weapon and spawns it in the world at the specified location.
|
||||
*
|
||||
* @param className Classname String of the weapon to spawn
|
||||
* @param absOrigin Absolute Origin Vector where to spawn the weapon.
|
||||
* @param absAngles Absolute Angles Vector.
|
||||
* @return Weapon Index of the created weapon or INVALID_ENT_REFERENCE on error.
|
||||
*/
|
||||
stock int Weapon_CreateForOwner(int client, const char[] className)
|
||||
{
|
||||
float absOrigin[3], absAngles[3];
|
||||
Entity_GetAbsOrigin(client, absOrigin);
|
||||
Entity_GetAbsAngles(client, absAngles);
|
||||
|
||||
int weapon = Weapon_Create(className, absOrigin, absAngles);
|
||||
|
||||
if (weapon == INVALID_ENT_REFERENCE) {
|
||||
return INVALID_ENT_REFERENCE;
|
||||
}
|
||||
|
||||
Entity_SetOwner(weapon, client);
|
||||
|
||||
return weapon;
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets the weapon's subtype.
|
||||
* The subtype is only used when a player has multiple weapons of the same type.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return Subtype of the weapon.
|
||||
*/
|
||||
stock int Weapon_GetSubType(int weapon)
|
||||
{
|
||||
return GetEntProp(weapon, Prop_Data, "m_iSubType");
|
||||
}
|
||||
|
||||
/*
|
||||
* Is the weapon currently reloading ?
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return True if weapon is currently reloading, false if not.
|
||||
*/
|
||||
stock bool Weapon_IsReloading(int weapon)
|
||||
{
|
||||
return GetEntProp(weapon, Prop_Data, "m_bInReload") != 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Weapon m_iState
|
||||
*/
|
||||
#define WEAPON_IS_ONTARGET 0x40
|
||||
#define WEAPON_NOT_CARRIED 0 // Weapon is on the ground
|
||||
#define WEAPON_IS_CARRIED_BY_PLAYER 1 // This client is carrying this weapon.
|
||||
#define WEAPON_IS_ACTIVE 2 // This client is carrying this weapon and it's the currently held weapon
|
||||
|
||||
/*
|
||||
* Get's the state of the weapon.
|
||||
* This returns whether the weapon is currently carried by a client,
|
||||
* if it is active and if it is on a target.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return Weapon State.
|
||||
*/
|
||||
stock int Weapon_GetState(int weapon)
|
||||
{
|
||||
return GetEntProp(weapon, Prop_Data, "m_iState");
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns whether the weapon can fire primary ammo under water.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return True or False.
|
||||
*/
|
||||
stock bool Weapon_FiresUnderWater(int weapon)
|
||||
{
|
||||
return GetEntProp(weapon, Prop_Data, "m_bFiresUnderwater") != 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Sets if the weapon can fire primary ammo under water.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @param can True or False.
|
||||
*/
|
||||
stock void Weapon_SetFiresUnderWater(int weapon, bool can=true)
|
||||
{
|
||||
SetEntProp(weapon, Prop_Data, "m_bFiresUnderwater", can);
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns whether the weapon can fire secondary ammo under water.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return True or False.
|
||||
*/
|
||||
stock bool Weapon_FiresUnderWaterAlt(int weapon)
|
||||
{
|
||||
return GetEntProp(weapon, Prop_Data, "m_bAltFiresUnderwater") != 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Sets if the weapon can fire secondary ammo under water.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @param can True or False.
|
||||
*/
|
||||
stock void Weapon_SetFiresUnderWaterAlt(int weapon, bool can=true)
|
||||
{
|
||||
SetEntProp(weapon, Prop_Data, "m_bAltFiresUnderwater", can);
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets the primary ammo Type (int offset)
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return Primary ammo type value.
|
||||
*/
|
||||
stock int Weapon_GetPrimaryAmmoType(int weapon)
|
||||
{
|
||||
return GetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoType");
|
||||
}
|
||||
|
||||
/*
|
||||
* Sets the primary ammo Type (int offset)
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @param type Primary ammo type value.
|
||||
*/
|
||||
stock void Weapon_SetPrimaryAmmoType(int weapon, int type)
|
||||
{
|
||||
SetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoType", type);
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets the secondary ammo Type (int offset)
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return Secondary ammo type value.
|
||||
*/
|
||||
stock int Weapon_GetSecondaryAmmoType(int weapon)
|
||||
{
|
||||
return GetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoType");
|
||||
}
|
||||
|
||||
/*
|
||||
* Sets the secondary ammo Type (int offset)
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @param type Secondary ammo type value.
|
||||
*/
|
||||
stock void Weapon_SetSecondaryAmmoType(int weapon, int type)
|
||||
{
|
||||
SetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoType", type);
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets the primary clip count of a weapon.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return Primary Clip count.
|
||||
*/
|
||||
stock int Weapon_GetPrimaryClip(int weapon)
|
||||
{
|
||||
return GetEntProp(weapon, Prop_Data, "m_iClip1");
|
||||
}
|
||||
|
||||
/*
|
||||
* Sets the primary clip count of a weapon.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @param value Clip Count value.
|
||||
*/
|
||||
stock void Weapon_SetPrimaryClip(int weapon, int value)
|
||||
{
|
||||
SetEntProp(weapon, Prop_Data, "m_iClip1", value);
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets the secondary clip count of a weapon.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return Secondy Clip count.
|
||||
*/
|
||||
stock int Weapon_GetSecondaryClip(int weapon)
|
||||
{
|
||||
return GetEntProp(weapon, Prop_Data, "m_iClip2");
|
||||
}
|
||||
|
||||
/*
|
||||
* Sets the secondary clip count of a weapon.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @param value Clip Count value.
|
||||
*/
|
||||
stock void Weapon_SetSecondaryClip(int weapon, int value)
|
||||
{
|
||||
SetEntProp(weapon, Prop_Data, "m_iClip2", value);
|
||||
}
|
||||
|
||||
/*
|
||||
* Sets the primary & secondary clip count of a weapon.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @param primary Primary Clip Count value.
|
||||
* @param secondary Primary Clip Count value.
|
||||
*/
|
||||
stock void Weapon_SetClips(int weapon, int primary, int secondary)
|
||||
{
|
||||
Weapon_SetPrimaryClip(weapon, primary);
|
||||
Weapon_SetSecondaryClip(weapon, secondary);
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets the primary ammo count of a weapon.
|
||||
* This is only used when the weapon is not carried
|
||||
* by a player to give a player ammo when he picks up
|
||||
* the weapon.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return Primary Ammo Count.
|
||||
*/
|
||||
stock int Weapon_GetPrimaryAmmoCount(int weapon)
|
||||
{
|
||||
return GetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoCount");
|
||||
}
|
||||
|
||||
/*
|
||||
* Sets the primary ammo count of a weapon.
|
||||
* This is only used when the weapon is not carried
|
||||
* by a player to give a player ammo when he picks up
|
||||
* the weapon.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @param value Primary Ammo Count.
|
||||
*/
|
||||
stock void Weapon_SetPrimaryAmmoCount(int weapon, int value)
|
||||
{
|
||||
SetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoCount", value);
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets the secondary ammo count of a weapon.
|
||||
* This is only used when the weapon is not carried
|
||||
* by a player to give a player ammo when he picks up
|
||||
* the weapon.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return Secondary Ammo Count.
|
||||
*/
|
||||
stock int Weapon_GetSecondaryAmmoCount(int weapon)
|
||||
{
|
||||
return GetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoCount");
|
||||
}
|
||||
|
||||
/*
|
||||
* Sets the secodary ammo count of a weapon.
|
||||
* This is only used when the weapon is not carried
|
||||
* by a player to give a player ammo when he picks up
|
||||
* the weapon.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @param value Secondary Ammo Count.
|
||||
*/
|
||||
stock void Weapon_SetSecondaryAmmoCount(int weapon, int value)
|
||||
{
|
||||
SetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoCount", value);
|
||||
}
|
||||
|
||||
/*
|
||||
* Sets both, the primary & the secondary ammo count of a weapon.
|
||||
* This is only used when the weapon is not carried
|
||||
* by a player to give a player ammo when he picks up
|
||||
* the weapon.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @value primary Primary Ammo Count.
|
||||
* @value secondary Secondary Ammo Count.
|
||||
*/
|
||||
stock void Weapon_SetAmmoCounts(int weapon, int primary, int secondary)
|
||||
{
|
||||
Weapon_SetPrimaryAmmoCount(weapon, primary);
|
||||
Weapon_SetSecondaryAmmoCount(weapon, secondary);
|
||||
}
|
||||
|
||||
/*
|
||||
* Gets the Model Index of the weapon's view model.
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @return View Model Index.
|
||||
*/
|
||||
stock int Weapon_GetViewModelIndex(int weapon)
|
||||
{
|
||||
return GetEntProp(weapon, Prop_Data, "m_nViewModelIndex");
|
||||
}
|
||||
|
||||
/*
|
||||
* Sets the Model Index of the weapon's view model.
|
||||
* You can get the Model Index by precaching a model with PrecacheModel().
|
||||
*
|
||||
* @param weapon Weapon Entity.
|
||||
* @param index Model Index.
|
||||
* @noreturn
|
||||
*/
|
||||
stock void Weapon_SetViewModelIndex(int weapon, int index)
|
||||
{
|
||||
SetEntProp(weapon, Prop_Data, "m_nViewModelIndex", index);
|
||||
ChangeEdictState(weapon, FindDataMapInfo(weapon, "m_nViewModelIndex"));
|
||||
}
|
16
scripting/include/smlib/world.inc
Normal file
16
scripting/include/smlib/world.inc
Normal file
|
@ -0,0 +1,16 @@
|
|||
#if defined _smlib_world_included
|
||||
#endinput
|
||||
#endif
|
||||
#define _smlib_world_included
|
||||
|
||||
#include <sourcemod>
|
||||
|
||||
/*
|
||||
* Gets the world's max size
|
||||
*
|
||||
* @param vec Vector buffer
|
||||
*/
|
||||
stock void World_GetMaxs(float vec[3]) {
|
||||
|
||||
GetEntPropVector(0, Prop_Data, "m_WorldMaxs", vec);
|
||||
}
|
284
scripting/include/system2/legacy.inc
Normal file
284
scripting/include/system2/legacy.inc
Normal file
|
@ -0,0 +1,284 @@
|
|||
/**
|
||||
* -----------------------------------------------------
|
||||
* File legacy.inc
|
||||
* Authors David Ordnung
|
||||
* License GPLv3
|
||||
* Web http://dordnung.de
|
||||
* -----------------------------------------------------
|
||||
*
|
||||
* Copyright (C) 2013-2020 David Ordnung
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
*/
|
||||
|
||||
#if defined _system2_legacy_included
|
||||
#endinput
|
||||
#endif
|
||||
|
||||
#define _system2_legacy_included
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* DEPRECATED v2 STUFF, do not use that anymore!
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Max Size of the command or page output in CmdCallback.
|
||||
*/
|
||||
#define CMD_MAX_RETURN 4096
|
||||
|
||||
|
||||
/**
|
||||
* A list of possible command return states
|
||||
*/
|
||||
enum CMDReturn
|
||||
{
|
||||
CMD_SUCCESS, // Fully finished
|
||||
CMD_EMPTY, // Result is empty (only System2_RunThreadCommand)
|
||||
CMD_ERROR, // An error appeared
|
||||
CMD_PROGRESS // Not finished yet -> Wait for other state
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Called when finished with a command or when retrieving the content of a page.
|
||||
* Maybe called more than once, if output is greater than 4096 bytes.
|
||||
* Use status variable to check if it's the last call or not.
|
||||
*
|
||||
* @param output Output of the command / page.
|
||||
* @param size Size of output string.
|
||||
* @param status CMDReturn status.
|
||||
* @param data Data passed.
|
||||
* @param command The command that was executed. Will be empty with PageGet.
|
||||
*/
|
||||
typeset CmdCallback
|
||||
{
|
||||
function void (const char[] output, const int size, CMDReturn status, any data, const char[] command);
|
||||
function void (const char[] output, const int size, CMDReturn status, any data);
|
||||
function void (const char[] output, const int size, CMDReturn status);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Called on every update when downloading / uploading a file.
|
||||
*
|
||||
* @param finished Is downloading / uploading finished?
|
||||
* @param error Error when finished. If no error string is empty.
|
||||
* @param dltotal Total downloaded size in bytes.
|
||||
* @param dlnow Current downloaded size in bytes.
|
||||
* @param ultotal Total uploaded size in bytes.
|
||||
* @param ulnow Current uploaded size in bytes.
|
||||
* @param data Data passed.
|
||||
*/
|
||||
typeset TransferUpdated
|
||||
{
|
||||
function void (bool finished, const char[] error, float dltotal, float dlnow, float ultotal, float ulnow, any data);
|
||||
function void (bool finished, const char[] error, float dltotal, float dlnow, float ultotal, float ulnow);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Gets the content of a page.
|
||||
*
|
||||
* @param callback Callback function when finished. Check callback.status to check if process is finished.
|
||||
* @param url The URL of the page to load. Attach GET parameters here and leave post parameter empty to perform a GET request.
|
||||
* @param post POST parameters (use like this: "name=test&pw=test2"). Leave empty to perform a GET request.
|
||||
* @param userAgent Useragent to use. Leave empty for default one.
|
||||
* @param data Additional data to pass to the callback.
|
||||
*
|
||||
* @noreturn
|
||||
*/
|
||||
#pragma deprecated Use System2HTTPRequest instead.
|
||||
native void System2_GetPage(CmdCallback callback, const char[] url, const char[] post = "", const char[] userAgent = "", any data = INVALID_HANDLE);
|
||||
|
||||
|
||||
/**
|
||||
* Downloads a file from an URL.
|
||||
*
|
||||
* @param updateFunction Function to call on update. Check updateFunction.finished to check if downloading is finished.
|
||||
* @param url File URL to download from.
|
||||
* @param localFile Local file to save to.
|
||||
* @param data Additional data to pass to the callback.
|
||||
*
|
||||
* @noreturn
|
||||
*/
|
||||
#pragma deprecated Use System2HTTPRequest instead.
|
||||
native void System2_DownloadFile(TransferUpdated updateFunction, const char[] url, const char[] localFile, any data = INVALID_HANDLE);
|
||||
|
||||
|
||||
/**
|
||||
* Downloads a file from a FTP server.
|
||||
*
|
||||
* @param updateFunction Function to call on update. Check updateFunction.finished to check if downloading is finished.
|
||||
* @param remoteFile Path to the file on the FTP server.
|
||||
* @param localFile Local file to save to.
|
||||
* @param host The FTP host.
|
||||
* @param user The FTP username.
|
||||
* @param pass The FTP password.
|
||||
* @param port The FTP port (Default: 21).
|
||||
* @param data Additional data to pass to the callback.
|
||||
*
|
||||
* @noreturn
|
||||
*/
|
||||
#pragma deprecated Use System2FTPRequest instead.
|
||||
native void System2_DownloadFTPFile(TransferUpdated updateFunction, const char[] remoteFile, const char[] localFile, const char[] host, const char[] user = "", const char[] pass = "", int port = 21, any data = INVALID_HANDLE);
|
||||
|
||||
|
||||
/**
|
||||
* Uploads a file to a FTP server.
|
||||
*
|
||||
* @param updateFunction Function to call on update. Check updateFunction.finished to check if uploading is finished.
|
||||
* @param localFile Local file to upload.
|
||||
* @param remoteFile Path to the file on the FTP server.
|
||||
* @param host The FTP host.
|
||||
* @param user The FTP username.
|
||||
* @param pass The FTP password.
|
||||
* @param port The FTP port (Default: 21).
|
||||
* @param data Additional data to pass to the callback.
|
||||
*
|
||||
* @noreturn
|
||||
*/
|
||||
#pragma deprecated Use System2FTPRequest instead.
|
||||
native void System2_UploadFTPFile(TransferUpdated updateFunction, const char[] localFile, const char[] remoteFile, const char[] host, const char[] user = "", const char[] pass = "", int port = 21, any data = INVALID_HANDLE);
|
||||
|
||||
|
||||
/**
|
||||
* Compresses a file to an archive.
|
||||
*
|
||||
* @param callback Callback function when finished with compressing. Check callback.status to check if process is finished.
|
||||
* @param pathToFile Path to the file / folder to compress.
|
||||
* @param pathToCompress Path to save archive file to (including filename).
|
||||
* @param archive Archive type to use.
|
||||
* @param level Archive compress level to use.
|
||||
* @param data Additional data to pass to the callback.
|
||||
*
|
||||
* @noreturn
|
||||
*/
|
||||
#pragma deprecated Use System2_Compress instead.
|
||||
native void System2_CompressFile(CmdCallback callback, const char[] pathToFile, const char[] pathToArchive, CompressArchive archive = ARCHIVE_ZIP, CompressLevel level = LEVEL_9, any data = INVALID_HANDLE);
|
||||
|
||||
|
||||
/**
|
||||
* Extracts a lot of archive types with 7zip.
|
||||
*
|
||||
* @param callback Callback function when finished with extracting. Check callback.status to check if process is finished.
|
||||
* @param pathToArchive Path to the archive file.
|
||||
* @param pathToExtract Path to extract to.
|
||||
* @param data Additional data to pass to the callback.
|
||||
*
|
||||
* @noreturn
|
||||
*/
|
||||
#pragma deprecated Use System2_Extract instead.
|
||||
native void System2_ExtractArchive(CmdCallback callback, const char[] pathToArchive, const char[] pathToExtract, any data = INVALID_HANDLE);
|
||||
|
||||
|
||||
/**
|
||||
* Executes a threaded system command.
|
||||
*
|
||||
* @param callback Callback function when command was executed. Check callback.status to check if process is finished.
|
||||
* @param command Command string format.
|
||||
* @param ... Command string arguments.
|
||||
*
|
||||
* @noreturn
|
||||
*/
|
||||
#pragma deprecated Use System2_ExecuteThreaded instead.
|
||||
native void System2_RunThreadCommand(CmdCallback callback, const char[] command, any ...);
|
||||
|
||||
|
||||
/**
|
||||
* Executes a threaded system command and allows to pass additional data.
|
||||
*
|
||||
* @param callback Callback function when command was executed. Check callback.status to check if process is finished.
|
||||
* @param data Data to pass to the callback.
|
||||
* @param command Command string format.
|
||||
* @param ... Command string arguments.
|
||||
*
|
||||
* @noreturn
|
||||
*/
|
||||
#pragma deprecated Use System2_ExecuteThreaded instead.
|
||||
native void System2_RunThreadCommandWithData(CmdCallback callback, any data, const char[] command, any ...);
|
||||
|
||||
|
||||
/**
|
||||
* Executes a non threaded system command.
|
||||
*
|
||||
* @param output Variable to store the command output.
|
||||
* @param size Size of the output variable.
|
||||
* @param command Command string format.
|
||||
* @param ... Command string arguments.
|
||||
*
|
||||
* @return CMDReturn status.
|
||||
*/
|
||||
#pragma deprecated Use System2_Execute instead.
|
||||
native CMDReturn System2_RunCommand(char[] output, int size, const char[] command, any ...);
|
||||
|
||||
|
||||
/**
|
||||
* Encodes a string for safe url transfer.
|
||||
* Written by Peace-Maker (i guess), formatted for better readability.
|
||||
*
|
||||
* @param stringToEncode The string to encode.
|
||||
* @param maxlength The maxlength of the string.
|
||||
* @param safe Adding additional safe strings.
|
||||
* @param format Is the string formatted.
|
||||
*/
|
||||
#pragma deprecated Use System2_URLEncode instead.
|
||||
stock void URLEncode(char[] stringToEncode, int maxlength, char[] safe = "/", bool format = false)
|
||||
{
|
||||
char sAlwaysSafe[256];
|
||||
Format(sAlwaysSafe, sizeof(sAlwaysSafe), "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-%s", safe);
|
||||
|
||||
// Need 2 '%' since sp's Format parses one as a parameter to replace
|
||||
// http://wiki.alliedmods.net/Format_Class_Functions_%28SourceMod_Scripting%29
|
||||
if (format)
|
||||
{
|
||||
ReplaceString(stringToEncode, maxlength, "%", "%%25");
|
||||
}
|
||||
else
|
||||
{
|
||||
ReplaceString(stringToEncode, maxlength, "%", "%25");
|
||||
}
|
||||
|
||||
|
||||
char sChar[8];
|
||||
char sReplaceChar[8];
|
||||
|
||||
for (new int i = 1; i < 256; i++)
|
||||
{
|
||||
// Skip the '%' double replace ftw..
|
||||
if (i == 37)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
Format(sChar, sizeof(sChar), "%c", i);
|
||||
|
||||
if (StrContains(sAlwaysSafe, sChar) == -1 && StrContains(stringToEncode, sChar) != -1)
|
||||
{
|
||||
if (format)
|
||||
{
|
||||
Format(sReplaceChar, sizeof(sReplaceChar), "%%%%%02X", i);
|
||||
}
|
||||
else
|
||||
{
|
||||
Format(sReplaceChar, sizeof(sReplaceChar), "%%%02X", i);
|
||||
}
|
||||
|
||||
ReplaceString(stringToEncode, maxlength, sChar, sReplaceChar);
|
||||
}
|
||||
}
|
||||
}
|
944
scripting/include/system2/request.inc
Normal file
944
scripting/include/system2/request.inc
Normal file
|
@ -0,0 +1,944 @@
|
|||
/**
|
||||
* -----------------------------------------------------
|
||||
* File request.inc
|
||||
* Authors David Ordnung
|
||||
* License GPLv3
|
||||
* Web http://dordnung.de
|
||||
* -----------------------------------------------------
|
||||
*
|
||||
* Copyright (C) 2013-2020 David Ordnung
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
*/
|
||||
|
||||
#if defined _system2_request_included
|
||||
#endinput
|
||||
#endif
|
||||
|
||||
#define _system2_request_included
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* API for making HTTP and FTP requests.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* A list of possible HTTP request methods.
|
||||
*/
|
||||
enum HTTPRequestMethod
|
||||
{
|
||||
METHOD_GET,
|
||||
METHOD_POST,
|
||||
METHOD_PUT,
|
||||
METHOD_PATCH,
|
||||
METHOD_DELETE,
|
||||
METHOD_HEAD
|
||||
}
|
||||
|
||||
/**
|
||||
* A list of possible HTTP versions.
|
||||
*/
|
||||
enum HTTPVersion
|
||||
{
|
||||
VERSION_NONE,
|
||||
VERSION_1_0,
|
||||
VERSION_1_1,
|
||||
VERSION_2_0
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Called when a HTTP request was finished.
|
||||
*
|
||||
* The response will only be valid in the callback and will be destroyed afterwards.
|
||||
* The request is a copy of the original request and will be destroyed afterwards.
|
||||
* The request can be modified and made again.
|
||||
*
|
||||
* @param success Whether the request could made.
|
||||
* This not means that the request itself was successful, check the StatusCode of the response for that!
|
||||
* @param error If success is false this will contain the error message.
|
||||
* @param request A copy of the made HTTP request.
|
||||
* Can't be deleted, as it will be destroyed after the callback!
|
||||
* @param response HTTP response of the request. Is null if success is false.
|
||||
* Can't be deleted, as it will be destroyed after the callback!
|
||||
* @param method The HTTP request method that was made.
|
||||
*
|
||||
* @noreturn
|
||||
*/
|
||||
typeset System2HTTPResponseCallback
|
||||
{
|
||||
function void (bool success, const char[] error, System2HTTPRequest request, System2HTTPResponse response, HTTPRequestMethod method);
|
||||
};
|
||||
|
||||
/**
|
||||
* Called when a FTP request was finished.
|
||||
*
|
||||
* The response will only be valid in the callback and will be destroyed afterwards.
|
||||
* The request is a copy of the original request and will be destroyed afterwards.
|
||||
* The request can be modified and made again.
|
||||
*
|
||||
* @param success Whether the request could made.
|
||||
* This not means that the request itself was successful, check the StatusCode of the response for that!
|
||||
* @param error If success is false this will contain the error message.
|
||||
* @param request A copy of the made FTP request.
|
||||
* Can't be deleted, as it will be destroyed after the callback!
|
||||
* @param response FTP response of the request. Is null if success is false.
|
||||
* Can't be deleted, as it will be destroyed after the callback!
|
||||
*
|
||||
* @noreturn
|
||||
*/
|
||||
typeset System2FTPResponseCallback
|
||||
{
|
||||
function void (bool success, const char[] error, System2FTPRequest request, System2FTPResponse response);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Called on a frequent interval while data of a HTTP request is being transferred.
|
||||
* The request is a copy of the original request and will be destroyed afterwards.
|
||||
*
|
||||
* @param request A copy of the made HTTP request.
|
||||
* Can't be deleted, as it will be destroyed after the callback!
|
||||
* @param dlTotal Total expected download size in bytes.
|
||||
* @param dlNow Downloaded bytes so far.
|
||||
* @param ulTotal Total expected upload size in bytes.
|
||||
* @param ulNow Uploaded bytes so far.
|
||||
*
|
||||
* @noreturn
|
||||
*/
|
||||
typeset System2HTTPProgressCallback
|
||||
{
|
||||
function void (System2HTTPRequest request, int dlTotal, int dlNow, int ulTotal, int ulNow);
|
||||
};
|
||||
|
||||
/**
|
||||
* Called on a frequent interval while data of a FTP request is being transferred.
|
||||
* The request is a copy of the original request and will be destroyed afterwards.
|
||||
*
|
||||
* @param request A copy of the made FTP request.
|
||||
* Can't be deleted, as it will be destroyed after the callback!
|
||||
* @param dlTotal Total expected download size in bytes.
|
||||
* @param dlNow Downloaded bytes so far.
|
||||
* @param ulTotal Total expected upload size in bytes.
|
||||
* @param ulNow Uploaded bytes so far.
|
||||
*
|
||||
* @noreturn
|
||||
*/
|
||||
typeset System2FTPProgressCallback
|
||||
{
|
||||
function void (System2FTPRequest request, int dlTotal, int dlNow, int ulTotal, int ulNow);
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Basic methodmap for a request.
|
||||
* Use System2HTTPRequest or System2FTPRequest to actually create a request.
|
||||
*/
|
||||
methodmap System2Request < Handle {
|
||||
/**
|
||||
* Sets the URL of the request.
|
||||
* Query parameters have to be given directly in the URL.
|
||||
*
|
||||
* Must be URL-encoded (use System2_URLEncode) in the following format:
|
||||
* scheme://host:port/path
|
||||
*
|
||||
* Host is a hostname or dotted numerical IP address. A numerical IPv6 address must be written within [brackets].
|
||||
*
|
||||
* If the given URL is missing a scheme name (such as "http://" or "ftp://" etc)
|
||||
* then system2 will make a guess based on the host.
|
||||
*
|
||||
* @param url URL to use for the request.
|
||||
* @param ... URL format arguments.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void SetURL(const char[] url, any ...);
|
||||
|
||||
/**
|
||||
* Retrieves the URL of the request.
|
||||
*
|
||||
* @param url Buffer to store URL in.
|
||||
* @param maxlength Maxlength of the buffer.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void GetURL(char[] url, int maxlength);
|
||||
|
||||
/**
|
||||
* Sets the remote port number to connect to,
|
||||
* instead of the one specified in the URL or the default port for the used protocol
|
||||
*
|
||||
* @param port Port to use for the request.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
* @error Invalid port number.
|
||||
*/
|
||||
public native void SetPort(int port);
|
||||
|
||||
/**
|
||||
* Returns the port of the request.
|
||||
*
|
||||
* @return The port of the request or 0 if none set.
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native int GetPort();
|
||||
|
||||
/**
|
||||
* Sets the path to the file to which the output of the request will be written to.
|
||||
* Use this to download the output of a response to a file.
|
||||
*
|
||||
* @param file File to write the output to.
|
||||
* @param ... File format arguments.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void SetOutputFile(const char[] file, any ...);
|
||||
|
||||
/**
|
||||
* Retrieves the path to the file to which the output of the request will be written to.
|
||||
*
|
||||
* @param file Buffer to store file in.
|
||||
* @param maxlength Maxlength of the buffer.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void GetOutputFile(char[] file, int maxlength);
|
||||
|
||||
/**
|
||||
* Sets whether to verify authenticity of the peer's certificate and server cert is for the server it is known as.
|
||||
* Only disable this, when you know what you do!
|
||||
*
|
||||
* @param verify True to verify SSL certificates, otherwise false.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void SetVerifySSL(bool verify);
|
||||
|
||||
/**
|
||||
* Returns whether SSL certificates will be verified.
|
||||
*
|
||||
* @return True if SSL certificates will be verified, otherwise false.
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native bool GetVerifySSL();
|
||||
|
||||
/**
|
||||
* Sets proxy for the request.
|
||||
*
|
||||
* @param proxy Hostname or dotted numerical IP address. A numerical IPv6 address must be written within [brackets].
|
||||
* To specify port number in this string, append :[port] to the end of the host name (default: 1080).
|
||||
* The proxy string may be prefixed with [scheme]:// to specify which kind of proxy is used.
|
||||
* http://
|
||||
* HTTP Proxy. Default when no scheme is specified.
|
||||
* https://
|
||||
* HTTPS Proxy.
|
||||
* socks4://
|
||||
* SOCKS4 Proxy.
|
||||
* socks4a://
|
||||
* SOCKS4a Proxy. Proxy resolves URL hostname.
|
||||
* socks5://
|
||||
* SOCKS5 Proxy.
|
||||
* socks5h://
|
||||
* SOCKS5 Proxy. Proxy resolves URL hostname.
|
||||
* @param useHttpTunnel Tunnel all operations through the HTTP proxy (use http or https)-
|
||||
* Tunneling means that an HTTP CONNECT request is sent to the proxy, asking it to connect to a remote host
|
||||
* on a specific port number and then the traffic is just passed through the proxy. Proxies tend to white-list
|
||||
* specific port numbers it allows CONNECT requests to and often only port 80 and 443 are allowed.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void SetProxy(const char[] proxy, bool useHttpTunnel = false);
|
||||
|
||||
/**
|
||||
* Sets the username and password to be used in protocol authentication with the proxy.
|
||||
*
|
||||
* @param username Username to use for proxy authentication.
|
||||
* @param password Password to use for proxy authentication.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void SetProxyAuthentication(const char[] username, const char[] password);
|
||||
|
||||
|
||||
property int Timeout {
|
||||
/**
|
||||
* Returns the timeout for the request.
|
||||
* By default, there is no timeout.
|
||||
*
|
||||
* @return The timeout of the request in seconds or -1 if none set.
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native get();
|
||||
|
||||
/**
|
||||
* Sets the timeout for the request in seconds.
|
||||
* By default, there is no timeout.
|
||||
*
|
||||
* @param seconds The timeout for the request in seconds. 0 to disable.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
* @error Invalid timeout.
|
||||
*/
|
||||
public native set(int seconds);
|
||||
}
|
||||
|
||||
property any Any {
|
||||
/**
|
||||
* Returns the any data that was bound to this request.
|
||||
*
|
||||
* @return The any data that was bound or 0 if none set.
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native get();
|
||||
|
||||
/**
|
||||
* Sets any data to bind to the request (which you can then use in callbacks).
|
||||
*
|
||||
* @param Any The any data to bind.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native set(any Any);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Methodmap to create a HTTP request.
|
||||
*/
|
||||
methodmap System2HTTPRequest < System2Request {
|
||||
/**
|
||||
* Creates a new HTTP Request.
|
||||
*
|
||||
* @param callback Response callback to call when the request is finished.
|
||||
* @param url URL to use for the request.
|
||||
* Query parameters have to be given directly in the URL.
|
||||
*
|
||||
* Must be URL-encoded (use System2_URLEncode) in the following format:
|
||||
* scheme://host:port/path
|
||||
*
|
||||
* Host is a hostname or dotted numerical IP address. A numerical IPv6 address must be written within [brackets].
|
||||
* If no scheme is given, HTTP will be used.
|
||||
* @param ... URL format arguments.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Couldn't create request.
|
||||
*/
|
||||
public native System2HTTPRequest(System2HTTPResponseCallback callback, const char[] url, any ...);
|
||||
|
||||
/**
|
||||
* Sets the progress callback for the transfer of the request.
|
||||
* This will be called frequently while data is being transferred.
|
||||
* This is useful when downloading or uploading stuff.
|
||||
*
|
||||
* @param callback Progress callback to call for the transfer.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void SetProgressCallback(System2HTTPProgressCallback callback);
|
||||
|
||||
|
||||
/**
|
||||
* Sets the body data to send with the request.
|
||||
* You must make sure that the data is formatted the way you want the server to receive it.
|
||||
* Use System2_URLEncode to encode the data.
|
||||
*
|
||||
* For example: parameter=value¶meter2=value2
|
||||
* Or with JSON: {"parameter": "value", "parameter2": "value2"}
|
||||
*
|
||||
* @param data Body data to send with the request.
|
||||
* @param ... Data format arguments.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void SetData(const char[] data, any ...);
|
||||
|
||||
/**
|
||||
* Retrieves the body data of the request.
|
||||
*
|
||||
* @param url Buffer to store data in.
|
||||
* @param maxlength Maxlength of the buffer.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void GetData(char[] data, int maxlength);
|
||||
|
||||
|
||||
/**
|
||||
* Sets a HTTP request header.
|
||||
* Use System2_URLEncode to encode the header.
|
||||
*
|
||||
* @param name Name of the header.
|
||||
* @param value Value to set the header to.
|
||||
* @param ... Value format arguments.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void SetHeader(const char[] header, const char[] value, any ...);
|
||||
|
||||
/**
|
||||
* Retrieves a HTTP request header.
|
||||
*
|
||||
* @param name Name of the header to retrieve.
|
||||
* @param value Buffer to store value in.
|
||||
* @param maxlength Maxlength of the buffer.
|
||||
*
|
||||
* @return True if header was set, otherwise false.
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native bool GetHeader(const char[] header, char[] value, int maxlength);
|
||||
|
||||
/**
|
||||
* Retrieves the name of a header at a given index.
|
||||
* Use Headers property to retrieve the maximum index.
|
||||
*
|
||||
* @param index Index of the header name.
|
||||
* @param name Buffer to store name in.
|
||||
* @param maxlength Maxlength of the buffer.
|
||||
*
|
||||
* @return True if header was found, otherwise false.
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native bool GetHeaderName(int index, char[] name, int maxlength);
|
||||
|
||||
property int Headers {
|
||||
/**
|
||||
* Returns the number of set headers.
|
||||
*
|
||||
* @return The number of set headers.
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all set header names of the request as ArrayList.
|
||||
* Attention: ArrayList has to be deleted after use!
|
||||
|
||||
* @param maxlength Maxlength of a header.
|
||||
*
|
||||
* @return ArrayList with all set request header names. Must be deleted afterwards!
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public ArrayList GetHeaders(int maxlength = 256) {
|
||||
ArrayList headers = new ArrayList(maxlength);
|
||||
|
||||
char[] headerName = new char[maxlength];
|
||||
for (int i=0; i < this.Headers; i++) {
|
||||
this.GetHeaderName(i, headerName, maxlength);
|
||||
headers.PushString(headerName);
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets the user agent for the request.
|
||||
* This will set the User-Agent header to the given value.
|
||||
*
|
||||
* @param userAgent User agent to use.
|
||||
* @param ... User agent format arguments.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void SetUserAgent(const char[] userAgent, any ...);
|
||||
|
||||
/**
|
||||
* Sets basic authentication username and passowrd for the request.
|
||||
* This will set the Authorization header to the given values.
|
||||
*
|
||||
* @param username Username to use for basic authentication.
|
||||
* @param password Password to use for basic authentication.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void SetBasicAuthentication(const char[] username, const char[] password);
|
||||
|
||||
/**
|
||||
* Sends the request with the HTTP GET method.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void GET();
|
||||
|
||||
/**
|
||||
* Sends the request with the HTTP POST method.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void POST();
|
||||
|
||||
/**
|
||||
* Sends the request with the HTTP PUT method.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void PUT();
|
||||
|
||||
/**
|
||||
* Sends the request with the HTTP PATCH method.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void PATCH();
|
||||
|
||||
/**
|
||||
* Sends the request with the HTTP DELETE method.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void DELETE();
|
||||
|
||||
/**
|
||||
* Sends the request with the HTTP HEAD method.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void HEAD();
|
||||
|
||||
|
||||
property bool FollowRedirects {
|
||||
/**
|
||||
* Returns whether the request follow redirects or not.
|
||||
* By default, redirects will be followed.
|
||||
*
|
||||
* @return True if it follow redirects, otherwise false.
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native get();
|
||||
|
||||
/**
|
||||
* Sets to follow any Location: header that the server sends as part of an HTTP header in a 3xx response.
|
||||
* For 301, 302 and 303 responses system2 will switch method to GET. All other 3xx codes will make system2 send the same method again.
|
||||
* By default, redirects will be followed.
|
||||
*
|
||||
* @param follow True to follow redirects, otherwise false.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native set(bool follow);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Methodmap to create a FTP request.
|
||||
*/
|
||||
methodmap System2FTPRequest < System2Request {
|
||||
/**
|
||||
* Creates a new FTP Request.
|
||||
*
|
||||
* @param callback Response callback to call when the request is finished.
|
||||
* @param url URL to use for the request.
|
||||
*
|
||||
* Must be URL-encoded (use System2_URLEncode) in the following format:
|
||||
* scheme://host:port/path
|
||||
*
|
||||
* Host is a hostname or dotted numerical IP address. A numerical IPv6 address must be written within [brackets].
|
||||
* If no scheme is given, FTP will be used.
|
||||
* @param ... URL format arguments.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Couldn't create request.
|
||||
*/
|
||||
public native System2FTPRequest(System2FTPResponseCallback callback, const char[] url, any ...);
|
||||
|
||||
/**
|
||||
* Sets the progress callback for the transfer of the request.
|
||||
* This will be called frequently while data is being transferred.
|
||||
*
|
||||
* @param callback Progress callback to call for the transfer.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void SetProgressCallback(System2FTPProgressCallback callback);
|
||||
|
||||
|
||||
/**
|
||||
* Sets authentication needed to access the FTP server.
|
||||
*
|
||||
* @param username Username to use for authentication.
|
||||
* @param password Password to use for authentication.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void SetAuthentication(const char[] username, const char[] password);
|
||||
|
||||
|
||||
/**
|
||||
* Sets the path to the file which should be uploaded.
|
||||
* If this is set, an upload approach will be used.
|
||||
*
|
||||
* @param file File to upload.
|
||||
* @param ... File format arguments.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void SetInputFile(const char[] file, any ...);
|
||||
|
||||
/**
|
||||
* Retrieves the path to the file which should be uploaded.
|
||||
*
|
||||
* @param file Buffer to store file in.
|
||||
* @param maxlength Maxlength of the buffer.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void GetInputFile(char[] file, int maxlength);
|
||||
|
||||
|
||||
/**
|
||||
* Starts the request.
|
||||
*
|
||||
* If a input file is set the request will upload this file.
|
||||
* Otherwise it may result in a directory listing or a file download.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native void StartRequest();
|
||||
|
||||
|
||||
property bool AppendToFile {
|
||||
/**
|
||||
* Returns whether the request appends to the FTP file or replaces it when uploading a file.
|
||||
* By default, the file will be replaced.
|
||||
*
|
||||
* @return True if it appends to the file, false if the file will be replaced.
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native get();
|
||||
|
||||
/**
|
||||
* Sets whether to append to the FTP file or to replace it when uploading a file.
|
||||
* By default, the file will be replaced.
|
||||
*
|
||||
* @param append True to append to file, false to replace it.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native set(bool append);
|
||||
}
|
||||
|
||||
property bool CreateMissingDirs {
|
||||
/**
|
||||
* Returns whether the request creates missing dirs when uploading a file.
|
||||
* By default, missing dirs will be created.
|
||||
*
|
||||
* @return True if it creates missing dirs, otherwise false.
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native get();
|
||||
|
||||
/**
|
||||
* Sets whether to create any remote directory that it fails to "move" into.
|
||||
* By default, missing dirs will be created.
|
||||
*
|
||||
* @param create True to create missing dirs, otherwise false.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native set(bool create);
|
||||
}
|
||||
|
||||
property bool ListFilenamesOnly {
|
||||
/**
|
||||
* Returns whether only file names should be fetched for directory listing.
|
||||
* By default, all information will be fetched.
|
||||
*
|
||||
* @return True if only file names should be fetched, false for full directory listing.
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native get();
|
||||
|
||||
/**
|
||||
* Sets whether to list the names of files in a directory,
|
||||
* rather than performing a full directory listing that would normally include file sizes, dates etc.
|
||||
* By default, all information will be fetched.
|
||||
*
|
||||
* @param append True if only file names should be fetched, false for full directory listing.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public native set(bool append);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Basic methodmap for a response of a request.
|
||||
*/
|
||||
methodmap System2Response < Handle {
|
||||
/**
|
||||
* Retrieves the last used effective URL.
|
||||
* This may differ from the request URL, if a redirect was followed.
|
||||
*
|
||||
* @param url Buffer to store last URL in.
|
||||
* @param maxlength Maxlength of the URL buffer.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native void GetLastURL(char[] url, int maxlength);
|
||||
|
||||
/**
|
||||
* Retrieves the content of the response.
|
||||
* This shouldn't be used when retrieved binary stuff.
|
||||
*
|
||||
* @param content Buffer to store the content in.
|
||||
* @param maxlength Maxlength of the content buffer.
|
||||
* @param start Start byte to start reading from.
|
||||
* You can use this to retrieve the content step by step.
|
||||
* @param delimiter Delimiter until which the content should be retrieved.
|
||||
* @param include Whether the delimiter should be included or not.
|
||||
*
|
||||
* @return Number of read bytes.
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native int GetContent(char[] content, int maxlength, int start = 0, const char[] delimiter = "", bool include = true);
|
||||
|
||||
|
||||
property int ContentLength {
|
||||
/**
|
||||
* Returns the length of the complete response content.
|
||||
*
|
||||
* @return Length of the content.
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native get();
|
||||
}
|
||||
|
||||
property int StatusCode {
|
||||
/**
|
||||
* Returns the status code of the response.
|
||||
*
|
||||
* @return The status code.
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native get();
|
||||
}
|
||||
|
||||
property float TotalTime {
|
||||
/**
|
||||
* Returns the total time from the request until the response in seconds.
|
||||
* Includs name resolving, TCP connect etc.
|
||||
*
|
||||
* @return Total time from the request until the response in seconds.
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native get();
|
||||
}
|
||||
|
||||
property int DownloadSize {
|
||||
/**
|
||||
* Returns the total amount of bytes that were downloaded.
|
||||
* This counts actual payload data, what's also commonly called body.
|
||||
* All meta and header data are excluded and will not be counted in this number.
|
||||
*
|
||||
* @return Total amount of bytes that were downloaded.
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native get();
|
||||
}
|
||||
|
||||
property int UploadSize {
|
||||
/**
|
||||
* Returns the total amount of bytes that were uploaded.
|
||||
*
|
||||
* @return Total amount of bytes that were uploaded.
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native get();
|
||||
}
|
||||
|
||||
property int DownloadSpeed {
|
||||
/**
|
||||
* Returns the average download speed measured for the complete download in bytes per second.
|
||||
*
|
||||
* @return Average download speed in bytes per second.
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native get();
|
||||
}
|
||||
|
||||
property int UploadSpeed {
|
||||
/**
|
||||
* Returns the average upload speed measured for the complete upload in bytes per second.
|
||||
*
|
||||
* @return Average upload speed in bytes per second.
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native get();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Methodmap for a response of a HTTP request.
|
||||
*/
|
||||
methodmap System2HTTPResponse < System2Response {
|
||||
/**
|
||||
* Retrieves the content type of the response.
|
||||
* This is the value read from the Content-Type header.
|
||||
*
|
||||
* @param type Buffer to store content type in.
|
||||
* @param maxlength Maxlength of the buffer.
|
||||
*
|
||||
* @noreturn
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native void GetContentType(const char[] type, int maxlength);
|
||||
|
||||
/**
|
||||
* Retrieves a HTTP response header
|
||||
*
|
||||
* @param name Name of the header to retrieve.
|
||||
* @param value Buffer to store value in.
|
||||
* @param maxlength Maxlength of the buffer.
|
||||
*
|
||||
* @return True if header was set, otherwise false.
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native bool GetHeader(const char[] name, char[] value, int maxlength);
|
||||
|
||||
/**
|
||||
* Retrieves the name of a header at a given index.
|
||||
* Use Headers property to retrieve the maximum index.
|
||||
*
|
||||
* @param index Index of the header name.
|
||||
* @param name Buffer to store name in.
|
||||
* @param maxlength Maxlength of the buffer.
|
||||
*
|
||||
* @return True if header was found, otherwise false.
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native bool GetHeaderName(int index, char[] name, int maxlength);
|
||||
|
||||
property int Headers {
|
||||
/**
|
||||
* Returns the number of set headers in the response.
|
||||
*
|
||||
* @return The number of set headers.
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all header set names of the response as ArrayList.
|
||||
* Attention: ArrayList has to be deleted after use!
|
||||
|
||||
* @param maxlength Maxlength of a header.
|
||||
*
|
||||
* @return ArrayList with all set response header names. Must be deleted!
|
||||
* @error Invalid request.
|
||||
*/
|
||||
public ArrayList GetHeaders(int maxlength = 256) {
|
||||
ArrayList headers = new ArrayList(maxlength);
|
||||
|
||||
char[] headerName = new char[maxlength];
|
||||
for (int i=0; i < this.Headers; i++) {
|
||||
this.GetHeaderName(i, headerName, maxlength);
|
||||
headers.PushString(headerName);
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
|
||||
property HTTPVersion HTTPVersion {
|
||||
/**
|
||||
* Returns the HTTP version of the response.
|
||||
*
|
||||
* @return The HTTP version.
|
||||
* @error Invalid response.
|
||||
*/
|
||||
public native get();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Methodmap for a response of a FTP request.
|
||||
* Currently there are no special methods for that.
|
||||
*/
|
||||
methodmap System2FTPResponse < System2Response {
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Converts a plain string to an URL encoded string.
|
||||
* All input characters that are not a-z, A-Z, 0-9, '-', '.', '_' or '~'
|
||||
* are converted to their "URL escaped" version (%NN where NN is a two-digit hexadecimal number).
|
||||
*
|
||||
* Be aware that the output string may be larger then the input string.
|
||||
*
|
||||
* @param output Buffer to store encoded string in. May point to the input string (will replace the input string).
|
||||
* @param maxlength Maxlength of the output buffer.
|
||||
* @param input String to encode.
|
||||
* @param ... Input string format arguments
|
||||
*
|
||||
* @return True on success, false otherwise.
|
||||
*/
|
||||
native bool System2_URLEncode(char[] output, int maxlength, const char[] input, any ...);
|
||||
|
||||
/**
|
||||
* Converts an URL encoded string to a plain string.
|
||||
* All input characters that are URL encoded (%XX where XX is a two-digit hexadecimal number) are converted to their binary versions.
|
||||
*
|
||||
* @param output Buffer to store decoded string in. May point to the input string (will replace the input string).
|
||||
* @param maxlength Maxlength of the output buffer.
|
||||
* @param input String to decode.
|
||||
* @param ... Input string format arguments
|
||||
*
|
||||
* @return True on success, false otherwise.
|
||||
*/
|
||||
native bool System2_URLDecode(char[] output, int maxlength, const char[] input, any ...);
|
Loading…
Add table
Add a link
Reference in a new issue