This commit is contained in:
Flummi
2021-07-25 14:20:46 +02:00
parent d40cf7f51a
commit 7160566a94
193 changed files with 70108 additions and 1 deletions

View File

@ -0,0 +1,593 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
#if defined _amxconst_included
#endinput
#endif
#define _amxconst_included
#include <amxmodx_version>
/**
* Internal AMXX buffer size for string retrieval.
*
* @note This is the buffer size AMX Mod X uses internally to retrieve strings
* from plugins. Most natives that take strings as arguments will
* implicitly truncate them to this maximum length. This has been raised
* to the current value with AMXX 1.8.3. Previously the limit was 3072.
* @note This is here mainly for documentation purposes. By default plugins
* don't have enough memory available to allocate an array of this size.
* You probably should not use this to actually declare a buffer unless
* you *absolutely* have to. Look at #pragma dynamic to increase a plugins
* available memory.
*/
#define MAX_STRING_LENGTH 16384
/**
* The maximum buffer size required to store a map's name.
*/
#define MAX_MAPNAME_LENGTH 64
/**
* Defines and constants related to the maximum number of clients.
*
* @note MAX_PLAYERS is not the same as MaxClients. MAX_PLAYERS is a hardcoded
* value as an upper limit, used mainly to declare arrays big enough for
* all possible server situations. MaxClients changes based on the
* server the plugin is deployed on..
*/
#define MAX_PLAYERS 32 /* Maximum number of players AMX Mod X supports */
/**
* Maximum number of players the server supports
*/
public stock const MaxClients;
/**
* Current map name
*/
public stock const MapName[MAX_MAPNAME_LENGTH];
/**
* Pass this into certain functions to act as a C++ NULL
*/
public stock const NULL_STRING[1];
/**
* Pass this into certain functions to act as a C++ NULL
*/
public stock const Float:NULL_VECTOR[3];
/**
* The maximum buffer size required to store a client's name.
*/
#define MAX_NAME_LENGTH 32
/**
* The maximum buffer size required to store a client's IP address without a port.
*/
#define MAX_IP_LENGTH 16
/**
* The maximum buffer size required to store a client's IP address with a port.
*/
#define MAX_IP_WITH_PORT_LENGTH 22
/**
* The maximum buffer size required to store a client's AuthID.
*/
#define MAX_AUTHID_LENGTH 64
/**
* The maximum buffer size required to store a resource path.
*/
#define MAX_RESOURCE_PATH_LENGTH 64
/**
* The maximum buffer size that can be displayed in a MOTD.
*/
#define MAX_MOTD_LENGTH 1536
/**
* The maximum size accepted by the user info buffer.
*/
#define MAX_USER_INFO_LENGTH 256
/**
* The maximum buffer size that can be displayed in a menu.
*/
#define MAX_MENU_LENGTH 512
/**
* π
*/
#define M_PI 3.1415926535
/**
* @section Admin privilege and authentication constants
*/
/**
* Admin level constants
*/
#define ADMIN_ALL 0 /* everyone */
#define ADMIN_IMMUNITY (1<<0) /* flag "a" */
#define ADMIN_RESERVATION (1<<1) /* flag "b" */
#define ADMIN_KICK (1<<2) /* flag "c" */
#define ADMIN_BAN (1<<3) /* flag "d" */
#define ADMIN_SLAY (1<<4) /* flag "e" */
#define ADMIN_MAP (1<<5) /* flag "f" */
#define ADMIN_CVAR (1<<6) /* flag "g" */
#define ADMIN_CFG (1<<7) /* flag "h" */
#define ADMIN_CHAT (1<<8) /* flag "i" */
#define ADMIN_VOTE (1<<9) /* flag "j" */
#define ADMIN_PASSWORD (1<<10) /* flag "k" */
#define ADMIN_RCON (1<<11) /* flag "l" */
#define ADMIN_LEVEL_A (1<<12) /* flag "m" */
#define ADMIN_LEVEL_B (1<<13) /* flag "n" */
#define ADMIN_LEVEL_C (1<<14) /* flag "o" */
#define ADMIN_LEVEL_D (1<<15) /* flag "p" */
#define ADMIN_LEVEL_E (1<<16) /* flag "q" */
#define ADMIN_LEVEL_F (1<<17) /* flag "r" */
#define ADMIN_LEVEL_G (1<<18) /* flag "s" */
#define ADMIN_LEVEL_H (1<<19) /* flag "t" */
#define ADMIN_MENU (1<<20) /* flag "u" */
#define ADMIN_BAN_TEMP (1<<21) /* flag "v" */
#define ADMIN_ADMIN (1<<24) /* flag "y" */
#define ADMIN_USER (1<<25) /* flag "z" */
/**
* Admin authentication behavior flags
*/
#define FLAG_KICK (1<<0) /* flag "a" */
#define FLAG_TAG (1<<1) /* flag "b" */
#define FLAG_AUTHID (1<<2) /* flag "c" */
#define FLAG_IP (1<<3) /* flag "d" */
#define FLAG_NOPASS (1<<4) /* flag "e" */
#define FLAG_CASE_SENSITIVE (1<<10) /* flag "k" */
/**
* @endsection
*/
/**
* Return codes
*/
#define PLUGIN_CONTINUE 0 /* Results returned by public functions */
#define PLUGIN_HANDLED 1 /* stop other plugins */
#define PLUGIN_HANDLED_MAIN 2 /* to use in client_command(), continue all plugins but stop the command */
/**
* HI weapon constants
*/
#define HIW_BERETTA 1
#define HIW_SPAS12 2
#define HIW_M4A1 3
#define HIW_MP5A4 4
#define HIW_MP5SD5 5
#define HIW_AK47 6
#define HIW_AKS74U 7
#define HIW_GLOCK 8
#define HIW_M11 9
#define HIW_M11SD 10
#define HIW_PSG1 11
#define HIW_ZASTAVA 12
#define HIW_M16A2 13
#define HIW_REMINGTON 14
#define HIW_NATOGREN 15
#define HIW_TANGOGREN 16
#define HIW_FLASHBANG 17
/**
* Parts of body for hits
*/
#define HIT_GENERIC 0 /* none */
#define HIT_HEAD 1
#define HIT_CHEST 2
#define HIT_STOMACH 3
#define HIT_LEFTARM 4
#define HIT_RIGHTARM 5
#define HIT_LEFTLEG 6
#define HIT_RIGHTLEG 7
#define HIT_SHIELD 8 // CS only
#define MAX_BODYHITS 8
/**
* @section emit_sound() constants
*/
/**
* Channels
*/
#define CHAN_AUTO 0
#define CHAN_WEAPON 1
#define CHAN_VOICE 2
#define CHAN_ITEM 3
#define CHAN_BODY 4
#define CHAN_STREAM 5 /* allocate stream channel from the static or dynamic area */
#define CHAN_STATIC 6 /* allocate channel from the static area */
#define CHAN_NETWORKVOICE_BASE 7 /* voice data coming across the network */
#define CHAN_NETWORKVOICE_END 500 /* network voice data reserves slots (CHAN_NETWORKVOICE_BASE through CHAN_NETWORKVOICE_END). */
/**
*Attenuation values
*/
#define ATTN_NONE 0.00
#define ATTN_NORM 0.80
#define ATTN_IDLE 2.00
#define ATTN_STATIC 1.25
/**
* Pitch values
*/
#define PITCH_NORM 100 /* non-pitch shifted */
#define PITCH_LOW 95 /* other values are possible - 0-255, where 255 is very high */
#define PITCH_HIGH 120
/**
* Volume values
*/
#define VOL_NORM 1.0
/**
* Sound behavior constants
*/
#define SND_SPAWNING (1<<8) // we're spawing, used in some cases for ambients
#define SND_STOP (1<<5) // stop sound
#define SND_CHANGE_VOL (1<<6) // change sound vol
#define SND_CHANGE_PITCH (1<<7) // change sound pitch
/**
* @endsection
*/
/**
* Menu keys
*/
#define MENU_KEY_1 (1<<0)
#define MENU_KEY_2 (1<<1)
#define MENU_KEY_3 (1<<2)
#define MENU_KEY_4 (1<<3)
#define MENU_KEY_5 (1<<4)
#define MENU_KEY_6 (1<<5)
#define MENU_KEY_7 (1<<6)
#define MENU_KEY_8 (1<<7)
#define MENU_KEY_9 (1<<8)
#define MENU_KEY_0 (1<<9)
/**
* Language constants
*/
#define LANG_SERVER 0
#define LANG_PLAYER -1
/**
* @section Client print native constants
*/
/**
* Destination types for client_print()
*/
enum
{
print_notify = 1,
print_console,
print_chat,
print_center,
print_radio /* Counter-Strike only */
};
/**
* Color types for client_print_color()
*/
enum
{
print_team_default = 0,
print_team_grey = -1,
print_team_red = -2,
print_team_blue = -3,
};
/**
* Destination types for engclient_print()
*/
enum
{
engprint_console = 0,
engprint_center,
engprint_chat,
};
/**
* @endsection
*/
/**
* @section Entity rendering constants
*/
/**
* Rendering modes (i.e. for set_user_rendering())
*/
enum
{
kRenderNormal = 0, /* src */
kRenderTransColor, /* c*a+dest*(1-a) */
kRenderTransTexture, /* src*a+dest*(1-a) */
kRenderGlow, /* src*a+dest -- No Z buffer checks */
kRenderTransAlpha, /* src*srca+dest*(1-srca) */
kRenderTransAdd, /* src*a+dest */
};
/**
* Rendering fx (i.e. for set_user_rendering())
*/
enum
{
kRenderFxNone = 0,
kRenderFxPulseSlow,
kRenderFxPulseFast,
kRenderFxPulseSlowWide,
kRenderFxPulseFastWide,
kRenderFxFadeSlow,
kRenderFxFadeFast,
kRenderFxSolidSlow,
kRenderFxSolidFast,
kRenderFxStrobeSlow,
kRenderFxStrobeFast,
kRenderFxStrobeFaster,
kRenderFxFlickerSlow,
kRenderFxFlickerFast,
kRenderFxNoDissipation,
kRenderFxDistort, /* Distort/scale/translate flicker */
kRenderFxHologram, /* kRenderFxDistort + distance fade */
kRenderFxDeadPlayer, /* kRenderAmt is the player index */
kRenderFxExplode, /* Scale up really big! */
kRenderFxGlowShell, /* Glowing Shell */
kRenderFxClampMinScale, /* Keep this sprite from getting very small (SPRITES only!) */
};
/**
* @endsection
*/
/**
* Type for force_unmodified()
*/
enum
{
force_exactfile = 0, /* File on client must exactly match server's file */
force_model_samebounds, /* For model files only, the geometry must fit in the same bbox */
force_model_specifybounds, /* For model files only, the geometry must fit in the specified bbox */
};
/**
* Status for get_module()
*/
enum
{
module_none = 0,
module_query,
module_badload,
module_loaded,
module_noinfo,
module_noquery,
module_noattach,
module_old,
};
/**
* AMX flag constants
*/
#define AMX_FLAG_DEBUG 0x02 /* symbolic info. available */
#define AMX_FLAG_COMPACT 0x04 /* compact encoding */
#define AMX_FLAG_BYTEOPC 0x08 /* opcode is a byte (not a cell) */
#define AMX_FLAG_NOCHECKS 0x10 /* no array bounds checking; no STMT opcode */
#define AMX_FLAG_NTVREG 0x1000 /* all native functions are registered */
#define AMX_FLAG_JITC 0x2000 /* abstract machine is JIT compiled */
#define AMX_FLAG_BROWSE 0x4000 /* busy browsing */
#define AMX_FLAG_RELOC 0x8000 /* jump/call addresses relocated */
/**
* Invalid plugin id
*/
#define INVALID_PLUGIN_ID -1
/**
* Menu and menu item status codes
*/
#define MENU_TIMEOUT -4
#define MENU_EXIT -3
#define MENU_BACK -2
#define MENU_MORE -1
#define ITEM_IGNORE 0
#define ITEM_ENABLED 1
#define ITEM_DISABLED 2
/**
* AMX error codes
*/
#define AMX_ERR_NATIVE 10
#define AMX_ERR_MEMACCESS 5
#define AMX_ERR_NONE 0
#define AMX_ERR_BOUNDS 4
#define AMX_ERR_STACKERR 3
#define AMX_ERR_STACKLOW 7
#define AMX_ERR_HEAPLOW 8
#define AMX_ERR_DIVIDE 11
#define AMX_ERR_NOTFOUND 19
#define AMX_ERR_PARAMS 25
#define AMX_ERR_GENERAL 27
/**
* Generic invalid handle value
*/
#define INVALID_HANDLE -1
/**
* @section Plugin forward related constants
*/
/**
* Stop types for plugin forwards
*/
#define ET_IGNORE 0 //ignore return val
#define ET_STOP 1 //stop on PLUGIN_HANDLED
#define ET_STOP2 2 //same, except return biggest
#define ET_CONTINUE 3 //no stop, return biggest
/**
* Parameter types for plugin forwards
*/
#define FP_CELL 0
#define FP_FLOAT 1
#define FP_STRING 2
#define FP_ARRAY 4
#define FP_VAL_BYREF 5 //cell & float are handled in the same way
/**
* @endsection
*/
/**
* LibType constants
*/
enum LibType
{
LibType_Library,
LibType_Class
};
/**
* AdminProp constants
*/
enum AdminProp
{
AdminProp_Auth = 0,
AdminProp_Password,
AdminProp_Access,
AdminProp_Flags
};
/**
* HashType constants
* To be used on hash_file() and hash_string()
*/
enum HashType
{
Hash_Crc32 = 0, // Provides CRC32 hashing
Hash_Md5, // Provides MD5 hashing
Hash_Sha1, // Provides SHA1 hashing
Hash_Sha256, // Provides SHA256 hashing
Hash_Sha3_224, // Provides SHA3 224 bit hashing
Hash_Sha3_256, // Provides SHA3 256 bit hashing
Hash_Sha3_384, // Provides SHA3 384 bit hashing
Hash_Sha3_512, // Provides SHA3 512 bit hashing
Hash_Keccak_224, // Provides Keccak 224 bit hashing
Hash_Keccak_256, // Provides Keccak 256 bit hashing
Hash_Keccak_384, // Provides Keccak 384 bit hashing
Hash_Keccak_512 // Provides Keccak 512 bit hashing
};
/**
* SetTaskFlags constants for set_task_ex()
*/
enum SetTaskFlags (<<= 1)
{
SetTask_Once = 0, // None; execute callback after the specified amount of time (Default)
SetTask_RepeatTimes = 1, // Repeat timer a set amount of times
SetTask_Repeat, // Loop indefinitely until timer is stopped
SetTask_AfterMapStart, // Time interval is treated as absolute time after map start
SetTask_BeforeMapChange // Time interval is treated as absolute time before map change
};
/**
* RegisterEventFlags constants for register_event_ex()
*/
enum RegisterEventFlags (<<= 1)
{
RegisterEvent_None = 0, // None
RegisterEvent_Global = 1, // Global event (sent to every client)
RegisterEvent_Single, // Event sent to single client
RegisterEvent_OnceForMultiple, // Call only once when repeated to multiple clients
RegisterEvent_OnlyDead, // Call only if sent to dead client
RegisterEvent_OnlyAlive, // Call only if sent to alive client
RegisterEvent_OnlyHuman, // Call only if sent to human client (RegisterEvent_Single required)
RegisterEvent_OnlyBots // Call only if sent to bot (RegisterEvent_Single required)
};
/**
* GetPlayerFlags constants for get_players_ex()
*/
enum GetPlayersFlags (<<= 1)
{
GetPlayers_None = 0, // No filter (Default)
GetPlayers_ExcludeDead = 1, // Do not include dead clients
GetPlayers_ExcludeAlive, // Do not include alive clients
GetPlayers_ExcludeBots, // Do not include bots
GetPlayers_ExcludeHuman, // Do not include human clients
GetPlayers_MatchTeam, // Match with team
GetPlayers_MatchNameSubstring, // Match with part of name
GetPlayers_CaseInsensitive, // Match case insensitive
GetPlayers_ExcludeHLTV, // Do not include HLTV proxies
GetPlayers_IncludeConnecting // Include connecting clients
};
/**
* FindPlayerFlags constants for find_player_ex()
*/
enum FindPlayerFlags (<<= 1)
{
FindPlayer_None = 0, // None
FindPlayer_MatchName = 1, // Match with name
FindPlayer_MatchNameSubstring, // Match with name substring
FindPlayer_MatchAuthId, // Match with authid
FindPlayer_MatchIP, // Match with ip
FindPlayer_MatchTeam, // Match with team name
FindPlayer_ExcludeDead, // Do not include dead clients
FindPlayer_ExcludeAlive, // Do not include alive clients
FindPlayer_ExcludeBots, // Do not include bots
FindPlayer_ExcludeHuman, // Do not include human clients
FindPlayer_LastMatched, // Return last matched client instead of the first
FindPlayer_MatchUserId, // Match with userid
FindPlayer_CaseInsensitive, // Match case insensitively
FindPlayer_IncludeConnecting // Include connecting clients
}
/**
* Constants for client statistics
*/
enum
{
STATSX_KILLS = 0,
STATSX_DEATHS,
STATSX_HEADSHOTS,
STATSX_TEAMKILLS,
STATSX_SHOTS,
STATSX_HITS,
STATSX_DAMAGE,
STATSX_RANK,
STATSX_MAX_STATS
}
/**
* Constants for get_user_origin()
*/
enum
{
Origin_Client = 0, // Client's Origin
Origin_Eyes, // Eyes (and Weapon) Origin
Origin_AimEndClient, // Aim End Origin from Client's Position
Origin_AimEndEyes, // Aim End Origin from Eyes Position
Origin_CS_LastBullet // Last Bullet's Origin (Counter-Strike)
}
#include <cstrike_const> // To keep backward compatibility

View File

@ -0,0 +1,895 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
#if defined _amxmisc_included
#endinput
#endif
#define _amxmisc_included
#if !defined _amxmodx_included
#include <amxmodx>
#endif
/**
* Returns if the client has any admin flags set
*
* @param id Client index
*
* @return 1 if client has any admin flags, 0 otherwise
*/
stock is_user_admin(id)
{
new __flags = get_user_flags(id);
return (__flags > 0 && !(__flags & ADMIN_USER));
}
/**
* Returns if the user can execute the current command by checking the necessary
* admin flags and parameter count. Displays a denied access message to the user
* if missing privileges or a usage example if too few parameters are provided.
*
* @note This should be used inside of a command forward as it uses read_argc()
* to check the parameter count.
*
* @param id Client index
* @param level Required admin flags
* @param cid Command id
* @param num Required number of parameters
* @param acesssilent If true no denied access message will be printed
*
* @return 1 if access granted and parameters provided, 0 otherwise
*/
stock cmd_access(id, level, cid, num, bool:accesssilent = false)
{
new has_access = 0;
if (id == (is_dedicated_server() ? 0 : 1))
{
has_access = 1;
}
else if (level == ADMIN_ADMIN)
{
if (is_user_admin(id))
{
has_access = 1;
}
}
else if (get_user_flags(id) & level)
{
has_access = 1;
}
else if (level == ADMIN_ALL)
{
has_access = 1;
}
if (has_access == 0)
{
if (!accesssilent)
{
console_print(id, "%L", id, "NO_ACC_COM");
}
return 0;
}
if (read_argc() < num)
{
new hcmd[32], hinfo[128], hflag, bool:info_ml;
get_concmd(cid, hcmd, charsmax(hcmd), hflag, hinfo, charsmax(hinfo), level, _, info_ml);
if (info_ml)
{
LookupLangKey(hinfo, charsmax(hinfo), hinfo, id);
}
console_print(id, "%L: %s %s", id, "USAGE", hcmd, hinfo);
return 0;
}
return 1;
}
/**
* Returns if the client has the specified admin flags.
*
* @param id Client index
* @param level Required admin flags
*
* @return 1 if client has the admin flags, 0 otherwise
*/
stock access(id, level)
{
if (level == ADMIN_ADMIN)
{
return is_user_admin(id);
}
else if (level == ADMIN_ALL)
{
return 1;
}
return (get_user_flags(id) & level);
}
/**
* cmd_target flags
*/
#define CMDTARGET_OBEY_IMMUNITY (1<<0) // Obey immunity
#define CMDTARGET_ALLOW_SELF (1<<1) // Allow self targeting
#define CMDTARGET_ONLY_ALIVE (1<<2) // Target must be alive
#define CMDTARGET_NO_BOTS (1<<3) // Target can't be a bot
/**
* Processes a generic target pattern and tries to match it to a client based
* on filtering flags. If no unique target is found an appropriate message is
* displayed to the admin.
*
* @note The pattern is first matched case insensitively against client names.
* If no match is found it is matched against client authids. If still no
* match is found and the pattern starts with '#' it is finally matched
* against client userids.
* @note Since client names are matched by substring the pattern can potentially
* match multiple targets. In that case the function will return 0 and ask
* the admin to provide a unique pattern.
* @note The filtering flags are applied after the pattern matching has
* finished. That means the pattern has to be unique against all clients
* on the server even if some of them are not eligible.
*
* @param id Client index of admin performing an action
* @param arg Target pattern
* @param flags Filtering flags, see CMDTARGET_* constants above
*
* @return Client index, or 0 if no or multiple clients matched
*/
stock cmd_target(id, const arg[], flags = CMDTARGET_OBEY_IMMUNITY)
{
new player = find_player("bl", arg);
if (player)
{
if (player != find_player("blj", arg))
{
console_print(id, "%L", id, "MORE_CL_MATCHT");
return 0;
}
}
else if ((player = find_player("c", arg)) == 0 && arg[0] == '#' && arg[1])
{
player = find_player("k", str_to_num(arg[1]));
}
if (!player)
{
console_print(id, "%L", id, "CL_NOT_FOUND");
return 0;
}
if (flags & CMDTARGET_OBEY_IMMUNITY)
{
if ((get_user_flags(player) & ADMIN_IMMUNITY) && ((flags & CMDTARGET_ALLOW_SELF) ? (id != player) : true))
{
new imname[MAX_NAME_LENGTH];
get_user_name(player, imname, charsmax(imname));
console_print(id, "%L", id, "CLIENT_IMM", imname);
return 0;
}
}
if (flags & CMDTARGET_ONLY_ALIVE)
{
if (!is_user_alive(player))
{
new imname[MAX_NAME_LENGTH];
get_user_name(player, imname, charsmax(imname));
console_print(id, "%L", id, "CANT_PERF_DEAD", imname);
return 0;
}
}
if (flags & CMDTARGET_NO_BOTS)
{
if (is_user_bot(player))
{
new imname[MAX_NAME_LENGTH];
get_user_name(player, imname, charsmax(imname));
console_print(id, "%L", id, "CANT_PERF_BOT", imname);
return 0;
}
}
return player;
}
/**
* Standard method to show admin activity to clients connected to the server.
* This depends on the amx_show_activity cvar. See documentation for more details.
*
* @param id Client index performing the action
* @param name Name of client performing the action
* @param fmt Formatting rules
* @param ... Variable number of formatting parameters
*
* @noreturn
*/
stock show_activity(id, const name[], const fmt[], any:...)
{
static __amx_show_activity;
if (__amx_show_activity == 0)
{
__amx_show_activity = get_cvar_pointer("amx_show_activity");
// if still not found, then register the cvar as a dummy
if (__amx_show_activity == 0)
{
__amx_show_activity = register_cvar("amx_show_activity", "2", FCVAR_PROTECTED);
}
}
new prefix[10];
if (is_user_admin(id))
{
copy(prefix, charsmax(prefix), "ADMIN");
}
else
{
copy(prefix, charsmax(prefix), "PLAYER");
}
new buffer[512];
vformat(buffer, charsmax(buffer), fmt, 4);
switch (get_pcvar_num(__amx_show_activity))
{
case 5: // hide name only to admins, show nothing to normal users
{
for (new i = 1; i <= MaxClients; i++)
{
if (is_user_connected(i))
{
if (is_user_admin(i))
{
client_print(i, print_chat, "%L: %s", i, prefix, buffer);
}
}
}
}
case 4: // show name only to admins, show nothing to normal users
{
for (new i = 1; i <= MaxClients; i++)
{
if (is_user_connected(i))
{
if (is_user_admin(i))
{
client_print(i, print_chat, "%L %s: %s", i, prefix, name, buffer);
}
}
}
}
case 3: // show name only to admins, hide name from normal users
{
for (new i = 1; i <= MaxClients; i++)
{
if (is_user_connected(i))
{
if (is_user_admin(i))
{
client_print(i, print_chat, "%L %s: %s", i, prefix, name, buffer);
}
else
{
client_print(i, print_chat, "%L: %s", i, prefix, buffer);
}
}
}
}
case 2: // show name to all
{
client_print(0, print_chat, "%L %s: %s", LANG_PLAYER, prefix , name , buffer);
}
case 1: // hide name to all
{
client_print(0, print_chat, "%L: %s", LANG_PLAYER, prefix, buffer);
}
}
}
/**
* Standard method to show admin activity to a single client.
* This depends on the amx_show_activity cvar. See documentation for more details.
*
* @param idtarget Client index to display message to
* @param id Client index performing the action
* @param name Name of client performing the action
* @param fmt Formatting rules
* @param ... Variable number of formatting parameters
*
* @noreturn
*/
stock show_activity_id(idtarget, idadmin, const name[], const fmt[], any:...)
{
if (idtarget == 0 || !is_user_connected(idtarget))
{
return;
}
static __amx_show_activity;
if (__amx_show_activity == 0)
{
__amx_show_activity = get_cvar_pointer("amx_show_activity");
// if still not found, then register the cvar as a dummy
if (__amx_show_activity == 0)
{
__amx_show_activity = register_cvar("amx_show_activity", "2", FCVAR_PROTECTED);
}
}
static prefix[10];
if (is_user_admin(idadmin))
{
copy(prefix, charsmax(prefix), "ADMIN");
}
else
{
copy(prefix, charsmax(prefix), "PLAYER");
}
static buffer[512];
vformat(buffer, charsmax(buffer), fmt, 5);
switch (get_pcvar_num(__amx_show_activity))
{
case 5: // hide name only to admins, show nothing to normal users
{
if (is_user_admin(idtarget))
{
client_print(idtarget, print_chat, "%L: %s", idtarget, prefix, buffer);
}
}
case 4: // show name only to admins, show nothing to normal users
{
if (is_user_admin(idtarget))
{
client_print(idtarget, print_chat, "%L %s: %s", idtarget, prefix, name, buffer);
}
}
case 3: // show name only to admins, hide name from normal users
{
if (is_user_admin(idtarget))
{
client_print(idtarget, print_chat, "%L %s: %s", idtarget, prefix, name, buffer);
}
else
{
client_print(idtarget, print_chat, "%L: %s", idtarget, prefix, buffer);
}
}
case 2: // show name to all
{
client_print(idtarget, print_chat, "%L %s: %s", idtarget, prefix, name, buffer);
}
case 1: // hide name to all
{
client_print(idtarget, print_chat, "%L: %s", idtarget, prefix, buffer);
}
}
}
/**
* Standard method to show activity to one single client with normal language keys.
* These keys need to be in the format of standard AMXX keys:
* eg: ADMIN_KICK_1 = ADMIN: kick %s
* ADMIN_KICK_2 = ADMIN %s: kick %s
* This depends on the amx_show_activity cvar. See documentation for more details.
*
* @param KeyWithoutName The language key that does not have the name field.
* @param KeyWithName The language key that does have the name field.
* @param __AdminName The name of the person doing the action.
* @extra Pass any extra format arguments for the language key in the variable arguments list.
*
* @noreturn
*/
stock show_activity_key(const KeyWithoutName[], const KeyWithName[], const ___AdminName[], any:...)
{
// The variable gets used via vformat, but the compiler doesn't know that, so it still cries.
#pragma unused ___AdminName
static __amx_show_activity;
if (__amx_show_activity == 0)
{
__amx_show_activity = get_cvar_pointer("amx_show_activity");
// if still not found, then register the cvar as a dummy
if (__amx_show_activity == 0)
{
__amx_show_activity = register_cvar("amx_show_activity", "2", FCVAR_PROTECTED);
}
}
new buffer[512];
new keyfmt[256];
new i;
switch (get_pcvar_num(__amx_show_activity))
{
case 5: // hide name to admins, display nothing to normal players
{
while (i++ < MaxClients)
{
if (is_user_connected(i))
{
if (is_user_admin(i))
{
LookupLangKey(keyfmt, charsmax(keyfmt), KeyWithoutName, i);
// skip the "adminname" argument if not showing name
vformat(buffer, charsmax(buffer), keyfmt, 4);
client_print(i, print_chat, "%s", buffer);
}
}
}
}
case 4: // show name only to admins, display nothing to normal players
{
while (i++ < MaxClients)
{
if (is_user_connected(i))
{
if (is_user_admin(i))
{
LookupLangKey(keyfmt, charsmax(keyfmt), KeyWithName, i);
vformat(buffer, charsmax(buffer), keyfmt, 3);
client_print(i, print_chat, "%s", buffer);
}
}
}
}
case 3: // show name only to admins, hide name from normal users
{
while (i++ < MaxClients)
{
if (is_user_connected(i))
{
if (is_user_admin(i))
{
LookupLangKey(keyfmt, charsmax(keyfmt), KeyWithName, i);
vformat(buffer, charsmax(buffer), keyfmt, 3);
}
else
{
LookupLangKey(keyfmt, charsmax(keyfmt), KeyWithoutName, i);
// skip the "adminname" argument if not showing name
vformat(buffer, charsmax(buffer), keyfmt, 4);
}
client_print(i, print_chat, "%s", buffer);
}
}
}
case 2: // show name to all users
{
while (i++ < MaxClients)
{
if (is_user_connected(i))
{
LookupLangKey(keyfmt, charsmax(keyfmt), KeyWithName, i);
vformat(buffer, charsmax(buffer), keyfmt, 3);
client_print(i, print_chat, "%s", buffer);
}
}
}
case 1: // hide name from all users
{
while (i++ < MaxClients)
{
if (is_user_connected(i))
{
LookupLangKey(keyfmt, charsmax(keyfmt), KeyWithoutName, i);
// skip the "adminname" argument if not showing name
vformat(buffer, charsmax(buffer), keyfmt, 4);
client_print(i, print_chat, "%s", buffer);
}
}
}
}
}
/**
* Returns if the mod running on the server supports colored menus.
*
* @note The full list of mods supporting colored menus:
* Counter-Strike, Counter-Strike: Condition Zero, Deathmatch Classic,
* Day of Defeat, Team Fortress Classic and Half-Life: Deathmatch.
* @note Since this is a stock and compiled into the plugin, the list of
* supported mods will not update and require recompilation of the plugin
* if the list ever changed.
*
* @return 1 if colored menus are supported, 0 otherwise
*/
stock colored_menus()
{
static ColoredMenus = -1;
if (ColoredMenus == -1)
{
new const ModNames[][] = { "cstrike", "czero", "dmc", "dod", "tfc", "valve" };
new ModName[32];
get_modname(ModName, charsmax(ModName));
for (new Iterator = 0; Iterator < sizeof(ModNames); Iterator++)
{
if (equal(ModName, ModNames[Iterator]))
{
ColoredMenus = 1;
break;
}
}
if (ColoredMenus == -1)
ColoredMenus = 0;
}
return ColoredMenus;
}
/**
* Returns if the mod running on the server is a version of Counter-Strike.
*
* @return 1 if mod is Counter-Strike, 0 otherwise
*/
stock cstrike_running()
{
new mod_name[32];
get_modname(mod_name, charsmax(mod_name));
return (equal(mod_name, "cstrike") || equal(mod_name, "czero") || equal(mod_name, "csv15") || equal(mod_name, "cs13"));
}
/**
* Returns if the server is running a specific mod.
*
* @param mod Mod name to check for
*
* @return 1 if mod name matches, 0 otherwise
*/
stock is_running(const mod[])
{
new mod_name[32];
get_modname(mod_name, charsmax(mod_name));
return equal(mod_name, mod);
}
/**
* Retrieves the path to the AMXX base directory.
*
* @param name Buffer to copy path to
* @param len Maximum buffer size
*
* @return Number of cells written to buffer
*/
stock get_basedir(name[], len)
{
return get_localinfo("amxx_basedir", name, len);
}
/**
* Retrieves the path to the AMXX configs directory.
*
* @param name Buffer to copy path to
* @param len Maximum buffer size
*
* @return Number of cells written to buffer
*/
stock get_configsdir(name[], len)
{
return get_localinfo("amxx_configsdir", name, len);
}
/**
* Retrieves the path to the AMXX data directory.
*
* @param name Buffer to copy path to
* @param len Maximum buffer size
*
* @return Number of cells written to buffer
*/
stock get_datadir(name[], len)
{
return get_localinfo("amxx_datadir", name, len);
}
/**
* Provides a shorthand to register a working menu.
*
* @note Combines the necessary calls to register_menuid() and
* register_menucmd() into a single function.
*
* @param title Menu name
* @param keys Key flags
* @param function Callback function
* @param outside Catch menus outside the calling plugin
*
* @noreturn
* @error If an invalid callback function is specified, an error will
* be thrown.
*/
stock register_menu(const title[], keys, const function[], outside = 0)
{
register_menucmd(register_menuid(title, outside), keys, function);
}
/**
* Alias to get_configsdir provided for backwards compatibility. Originally
* intended to retrieve the AMXX custom directory.
*
* @deprecated Should not be used as the concept of a custom directory does no
* longer exists in AMXX.
*
* @param name Buffer to copy path to
* @param len Maximum buffer size
*
* @return Number of cells written to buffer
*/
#pragma deprecated The concept of a custom directory no longer exists in AMXX. Do not use.
stock get_customdir(name[], len)
{
return get_configsdir(name, len);
}
/**
* Adds a menu item/command to the admin menu (amxmodmenu) handled by the
* "Menus Front-End" plugin, if it is loaded.
*
* @param MENU_TEXT Item text that will be displayed in the menu
* @param MENU_CMD Command that will be executed on the client
* @param MENU_ACCESS Admin access required for menu command
* @param MENU_PLUGIN Case-insensitive name or filename of plugin providing
* the menu command
*
* @noreturn
*/
stock AddMenuItem(const MENU_TEXT[], const MENU_CMD[], const MENU_ACCESS, const MENU_PLUGIN[])
{
AddMenuItem_call(MENU_TEXT, MENU_CMD, MENU_ACCESS, MENU_PLUGIN, false);
}
/**
* Adds a menu item/command to the client menu (amx_menu) handled by the
* "Menus Front-End" plugin, if it is loaded. Items should be accessible by
* non-admins.
*
* @param MENU_TEXT Item text that will be displayed in the menu
* @param MENU_CMD Command that will be executed on the client
* @param MENU_ACCESS Admin access required for menu command
* @param MENU_PLUGIN Case-insensitive name or filename of plugin providing
* the menu command
*
* @noreturn
*/
stock AddClientMenuItem(const MENU_TEXT[], const MENU_CMD[], const MENU_ACCESS, const MENU_PLUGIN[])
{
AddMenuItem_call(MENU_TEXT, MENU_CMD, MENU_ACCESS, MENU_PLUGIN, true);
}
/**
* Helper function used by AddMenuItem() and AddClientMenuItem()
*
* @param MENU_TEXT Item text that will be displayed in the menu
* @param MENU_CMD Command that will be executed on the client
* @param MENU_ACCESS Admin access required for menu command
* @param MENU_PLUGIN Case-insensitive name or filename of plugin
* providing the menu command
* @param ADD_TO_CLIENT_MENU If true adds command to client menu, false adds
* to admin menu
*
* @noreturn
*/
stock AddMenuItem_call(const MENU_TEXT[], const MENU_CMD[], const MENU_ACCESS, const MENU_PLUGIN[], const bool:ADD_TO_CLIENT_MENU)
{
new pluginid = is_plugin_loaded("Menus Front-End");
if (pluginid == -1)
{
log_amx("Can't add menu item ^"%s^" from plugin ^"%s^" to menu set because the Menus Front-End plugin itself is not loaded!", MENU_TEXT, MENU_PLUGIN);
return; // Menus Front-End doesn't exist, return.
}
new filename[64], b[1];
get_plugin(pluginid, filename, charsmax(filename), b, charsmax(b), b, charsmax(b), b, charsmax(b), b, charsmax(b));
new status = callfunc_begin(ADD_TO_CLIENT_MENU ? "AddClientMenu" : "AddMenu", filename);
new bool:failed = true;
switch (status)
{
case 1:
{
failed = false;
}
case 0:
{
log_amx("Run time error! (AddMenuItem_call failed)");
}
case -2:
{
log_amx("Function not found! (AddMenuItem_call failed)");
}
case -1:
{
log_amx("Plugin not found! (AddMenuItem_call failed)");
}
}
if (failed)
{
return;
}
// Item text
callfunc_push_str(MENU_TEXT);
// Cmd
callfunc_push_str(MENU_CMD);
// Access
callfunc_push_int(MENU_ACCESS);
// Menu exists in this plugin
callfunc_push_str(MENU_PLUGIN);
callfunc_end();
}
/**
* Computes an offset from a given value while constraining it between the
* specified bounds, rolling over if necessary.
*
* @note Example: The range is 1-5 and the base value (seed) is 3, the offset
* that the value should be moved by is also 3. Offsetting the value by 3
* would result in 6, but it is to be constrained between 1 and 5. With
* clamp() this would result in 5, but this function rolls the value over
* and returns 1 instead.
*
* @param low Lower bound
* @param high Higher bound
* @param seed Base value
* @param offset Offset to move
*
* @return Computed offset value between specified bounds
*/
stock constraint_offset(low, high, seed, offset)
{
new numElements = high - low + 1;
offset += seed - low;
if (offset >= 0)
{
return low + (offset % numElements);
}
return high - (abs(offset) % numElements) + 1;
}
/**
* Returns if the client has any of the specified admin flags.
*
* @param id Client index
* @param flags Flag string
*
* @return 1 if the user has any of the specified flags, 0 otherwise
*/
stock has_flag(id, const flags[])
{
return (get_user_flags(id) & read_flags(flags));
}
/**
* Returns if the client has all of the specified admin flags.
*
* @param id Client index
* @param flags Flag string
*
* @return 1 if the user has all of the specified flags, 0 otherwise
*/
stock has_all_flags(id, const flags[])
{
new FlagsNumber = read_flags(flags);
return ((get_user_flags(id) & FlagsNumber) == FlagsNumber);
}
/**
* Resets the client's menu.
*
* @note This is a wrapper around show_menu() for the sake of readability.
*
* @param index Client to reset menu of, 0 to reset all clients
*
* @noreturn
*/
stock reset_menu(index)
{
show_menu(index, 0, "", 0);
}
/**
* Calls a function after a specified time has elapsed.
*
* @param time Time interval to assign
* @param function Function to execute
* @param id Task id to assign
* @param parameter Data to pass through to callback
* @param len Size of data
* @param flags Optional flags (enum SetTaskFlags); valid flags are:
* SetTask_Once - Execute callback once (Default)
* SetTask_RepeatTimes - repeat timer a set amount of times
* SetTask_Repeat - loop indefinitely until timer is stopped
* SetTask_AfterMapStart - time interval is treated as absolute
* time after map start
* SetTask_BeforeMapChange - time interval is treated as absolute
* time before map change
* @param repeat If the SetTask_RepeatTimes flag is set, the task will be repeated this
* many times
*
* @noreturn
* @error If an invalid callback function is provided, an error is
* thrown.
*/
stock set_task_ex(Float:time, const function[], id = 0, const any:parameter[] = "", len = 0, SetTaskFlags:flags = SetTask_Once, repeat = 0)
{
new strFlags[2]; // There should never be a need to set more than 1 flag
get_flags(_:flags, strFlags, charsmax(strFlags));
set_task(time, function, id, parameter, len, strFlags, repeat);
}
/**
* Stores a filtered list of client indexes to an array.
*
* @note Example retrieving all alive CTs:
* get_players_ex(players, num, GetPlayers_ExcludeDead | GetPlayers_MatchTeam, "CT")
*
* @param players Array to store indexes to
* @param num Variable to store number of indexes to
* @param flags Optional filtering flags (enum GetPlayersFlags); valid flags are:
* GetPlayers_None - No filter (Default)
* GetPlayers_ExcludeDead - do not include dead clients
* GetPlayers_ExcludeAlive - do not include alive clients
* GetPlayers_ExcludeBots - do not include bots
* GetPlayers_ExcludeHuman - do not include human clients
* GetPlayers_MatchTeam - match with team
* GetPlayers_MatchNameSubstring - match with part of name
* GetPlayers_CaseInsensitive - match case insensitive
* GetPlayers_ExcludeHLTV - do not include HLTV proxies
* GetPlayers_IncludeConnecting - include connecting clients
* @param team String to match against if the "e" or "f" flag is specified
*
* @noreturn
*/
stock get_players_ex(players[MAX_PLAYERS] = {}, &num, GetPlayersFlags:flags = GetPlayers_None, const team[] = "")
{
new strFlags[10];
get_flags(_:flags, strFlags, charsmax(strFlags));
get_players(players, num, strFlags, team);
}
/**
* Returns the number of clients on the server that match the specified flags.
*
* @note Example retrieving all alive CTs:
* new AliveCt = get_playersnum_ex(GetPlayers_ExcludeDead | GetPlayers_MatchTeam, "CT")
*
* @param flags Optional filtering flags (enum GetPlayersFlags); valid flags are:
* GetPlayers_None - No filter (Default)
* GetPlayers_ExcludeDead - do not include dead clients
* GetPlayers_ExcludeAlive - do not include alive clients
* GetPlayers_ExcludeBots - do not include bots
* GetPlayers_ExcludeHuman - do not include human clients
* GetPlayers_MatchTeam - match with team
* GetPlayers_MatchNameSubstring - match with part of name
* GetPlayers_CaseInsensitive - match case insensitive
* GetPlayers_ExcludeHLTV - do not include HLTV proxies
* GetPlayers_IncludeConnecting - include connecting clients
* @param team String to match against if the GetPlayers_MatchTeam or GetPlayers_MatchNameSubstring flag is specified
*
* @return Number of clients on the server that match the specified flags
*/
stock get_playersnum_ex(GetPlayersFlags:flags = GetPlayers_None, const team[] = "")
{
new PlayersNum;
get_players_ex(_, PlayersNum, flags, team);
return PlayersNum;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,20 @@
#if defined _amxmodx_version_included
#endinput
#endif
#define _amxmodx_version_included
#define AMXX_VERSION_TAG ""
#define AMXX_VERSION_CSET "9fbf91d"
#define AMXX_VERSION_MAJOR "1"
#define AMXX_VERSION_MAJOR_NUM 1
#define AMXX_VERSION_MINOR "10"
#define AMXX_VERSION_MINOR_NUM 10
#define AMXX_VERSION_RELEASE "0"
#define AMXX_VERSION_LOCAL_REV_NUM 5417
#define AMXX_VERSION_LOCAL_REV "5417"
#define AMXX_VERSION 1.100
#define AMXX_VERSION_NUM 200
stock const AMXX_VERSION_STR[] = "1.10.0.5417";

View File

@ -0,0 +1,43 @@
/*
*
* 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
* (at your option) 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/>.
*
* See LICENSE.TXT file for more information.
*
*/
#if defined _AmxxArch_included
#endinput
#endif
#define _AmxxArch_included
#if AMXX_VERSION_NUM >= 175
#pragma reqlib AmxxArch
#if !defined AMXMODX_NOAUTOLOAD
#pragma loadlib AmxxArch
#endif
#else
#pragma library AmxxArch
#endif
#define AA_NO_ERROR 0
/*
* @param filepath Path to the file
* @param outdir Directory where the archive will be unpacked
* @param callback Callback function (example: public OnComplete(idcaller, error))
* @param idcaller player id or 0
*
* @noreturn
*/
native AA_Unarchive( const filepath[], const outdir[], const callback[], const idcaller = 0);

View File

@ -0,0 +1,525 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
#if defined _cellarray_included
#endinput
#endif
#define _cellarray_included
/**
* Cellarray tag declaration
*
* @note These dynamic arrays are intended to be used for a form of global
* storage without requiring a #define that needs to be increased each
* time the plugin author requires more storage. These are not designed
* to be a full replacement for normal arrays, as those are faster and
* should be used whenever possible.
* @note Plugins are responsible for freeing all Array handles they acquire,
* including those from ArrayClone. Failing to free handles will result
* in the plugin and AMXX leaking memory.
*/
enum Array
{
Invalid_Array = 0
};
/**
* Returns the number of cells required to fit a string of the specified size
* (including the null terminator).
*
* @param size Number of bytes.
*
* @return Minimum number of cells required to fit the byte count.
*/
stock ByteCountToCells(size)
{
if (!size)
{
return 1;
}
return (size + 3) / 4;
}
/**
* Creates a handle to a dynamically sized array.
*
* @note It is very important that the provided cellsize matches up with the
* buffer sizes that are passed with subsequent Array[Get|Set|Push] calls.
* @note Initially the "reserved" parameter was intended to create blank entries
* that would immediately be usable with Array[Get|Set] functions. This
* functionality was never working as intended, and can now be achieved
* using ArrayResize().
*
* @param cellsize Size of each array entry in cells
* @param reserved Pre-allocates space in the array for the specified
* number of items. The items are not valid to read or set
* until they have actually been pushed into the array.
*
* @return New array handle, which must be freed via ArrayDestroy()
* @error If an invalid cellsize is provided an error will be
* thrown.
*/
native Array:ArrayCreate(cellsize = 1, reserved = 32);
/**
* Clones an array, returning a new handle with the same size and data.
*
* @param which Array handle
*
* @return Handle to the cloned array on success, 0 otherwise
* @error If an invalid handle is provided an error will be
* thrown.
*/
native Array:ArrayClone(Array:which);
/**
* Clears all entries from the array.
*
* @param which Array handle
*
* @noreturn
* @error Invalid handle
*/
native ArrayClear(Array:which);
/**
* Returns the number of elements in the array.
*
* @param which Array handle
*
* @return Number of elements in the array
* @error If an invalid handle is provided an error will be
* thrown.
*/
native ArraySize(Array:which);
/**
* Resizes an array.
*
* @note If the size is smaller than the current array size the array is
* truncated and data lost.
*
* @param which Array handle
* @param newsize New size
*
* @noreturn
* @error If an invalid handle is provided or the resizing
* operation runs out of memory, an error will be thrown.
*/
native bool:ArrayResize(Array:which, newsize);
/**
* Retrieves an array of data from a cellarray.
*
* @note If the size parameter is specified as -1 the output buffer has to match
* the size the array was created with.
*
* @param which Array handle
* @param item Item index in the array
* @param output Buffer to copy value to
* @param size If not set, assumes the buffer size is equal to the
* cellsize. Otherwise, the specified size is used.
*
* @return Number of cells copied
* @error If an invalid handle or index is provided an error will
* be thrown.
*/
native ArrayGetArray(Array:which, item, any:output[], size = -1);
/**
* Returns a single cell of data from an array
*
* @param which Array handle
* @param item Item index in the array
* @param block If the array has a cellsize >1 this optionally specifies
* which block to read from
* @param asChar If true reads the value as a byte instead of a cell
*
* @return Integer value
* @error If an invalid handle, index or block is provided an
* error will be thrown.
*/
native any:ArrayGetCell(Array:which, item, block = 0, bool:asChar = false);
/**
* Returieves string data from an array.
*
* @param which Array handle
* @param item Item index in the array
* @param output Buffer to copy value to
* @param size Maximum size of the buffer
*
* @return Number of characters copied
* @error If an invalid handle or an invalid index is provided an
* error will be thrown.
*/
native ArrayGetString(Array:which, item, output[], size);
/**
* Fills an item's data with the contents of an array.
*
* @note If the size parameter is specified as -1 the input buffer has to match
* the size the array was created with.
* @note The item index must already be valid. Use ArrayPushArray to create
* a new array item in the cellarray.
*
* @param which Array handle
* @param item Item index in the array
* @param input Array to copy to the cellarray
* @param size If not set, assumes the buffer size is equal to the
* cellsize. Otherwise, the specified size is used.
*
* @return Number of cells copied
* @error If an invalid handle or an invalid index is provided an
* error will be thrown.
*/
native ArraySetArray(Array:which, item, const any:input[], size =-1);
/**
* Sets an item's data to a single cell value.
*
* @note The item index must already be valid. Use ArrayPushArray to create
* a new array item in the cellarray.
*
* @param which Array handle
* @param item Item index in the array
* @param input Value to set
* @param block If the array has a cellsize >1 this optionally specifies
* which block to write to
* @param asChar If true writes the value as a byte instead of a cell
*
* @noreturn
* @error If an invalid handle, index or block is provided an
* error will be thrown.
*/
native ArraySetCell(Array:which, item, any:input, block = 0, bool:asChar = false);
/**
* Sets an item's data to a string value.
*
* @note The input will be truncated if it is longer than the cellsize the array
* was created with.
* @note The item index must already be valid. Use ArrayPushString to create
* a new array item in the cellarray.
*
* @param which Array handle
* @param item Item index in the array
* @param input String to copy to the array
*
* @return Number of characters copied
* @error If an invalid handle or an invalid index is provided an
* error will be thrown.
*/
native ArraySetString(Array:which, item, const input[]);
/**
* Creates a new item at the end of the cellarray and copies the provided array
* into it.
*
* @note The input will be truncated if it is bigger than the cellsize the array
* was created with.
*
* @param which Array handle
* @param input Array to copy to the cellarray
* @param size If not set, assumes the buffer size is equal to the
* cellsize. Otherwise, the specified size is used.
*
* @return Index of the new entry
* @error If an invalid handle is provided or the resizing
* operation runs out of memory, an error will be thrown.
*/
native ArrayPushArray(Array:which, const any:input[], size = -1);
/**
* Creates a new item at the end of the array and sets the item's single cell
* value.
*
* @param which Array handle
* @param input Value to set
*
* @return Index of the new entry
* @error If an invalid handle is provided or the resizing
* operation runs out of memory, an error will be thrown.
*/
native ArrayPushCell(Array:which, any:input);
/**
* Creates a new item at the end of the array and copies the provided string
* into it.
*
* @note The input will be truncated if it is longer than the cellsize the array
* was created with.
*
* @param which Array handle
* @param input String to copy to the array
*
* @return Index of the new entry
* @error If an invalid handle is provided or the resizing
* operation runs out of memory, an error will be thrown.
*/
native ArrayPushString(Array:which, const input[]);
/**
* Creates a new item behind the specified item and copies the provided array
* into it. All items beyond it get shifted up by one.
*
* @param which Array handle
* @param item Item index in the array
* @param input Array to copy to the cellarray
*
* @noreturn
* @error If an invalid handle or an invalid index is provided an
* error will be thrown.
*/
native ArrayInsertArrayAfter(Array:which, item, const any:input[]);
/**
* Creates a new item behind the specified item and sets the item's single cell
* value. All items beyond it get shifted up by one.
*
* @param which Array handle
* @param item Item index in the array
* @param input Value to set
*
* @noreturn
* @error If an invalid handle or an invalid index is provided an
* error will be thrown.
*/
native ArrayInsertCellAfter(Array:which, item, any:input);
/**
* Creates a new item behind the specified item and copies the provided string
* into it. All items beyond it get shifted up by one.
*
* @note The input will be truncated if it is longer than the cellsize the array
* was created with.
*
* @param which Array handle
* @param item Item index in the array
* @param input String to copy to the array
*
* @noreturn
* @error If an invalid handle or an invalid index is provided an
* error will be thrown.
*/
native ArrayInsertStringAfter(Array:which, item, const input[]);
/**
* Creates a new item in front of the specified item and copies the provided
* array into it. All items beyond it get shifted up by one.
*
* @param which Array handle
* @param item Item index in the array
* @param input Array to copy to the cellarray
*
* @noreturn
* @error If an invalid handle or an invalid index is provided an
* error will be thrown.
*/
native ArrayInsertArrayBefore(Array:which, item, const any:input[]);
/**
* Creates a new item in front of the specified item and sets the item's single
* cell value. All items beyond it get shifted up by one.
*
* @param which Array handle
* @param item Item index in the array
* @param input Value to set
*
* @noreturn
* @error If an invalid handle or an invalid index is provided an
* error will be thrown.
*/
native ArrayInsertCellBefore(Array:which, item, const any:input);
/**
* Creates a new item in front of the specified item and copies the provided
* string into it. All items beyond it get shifted up by one.
*
* @note The input will be truncated if it is longer than the cellsize the array
* was created with.
*
* @param which Array handle
* @param item Item index in the array
* @param input String to copy to the array
*
* @noreturn
* @error If an invalid handle or an invalid index is provided an
* error will be thrown.
*/
native ArrayInsertStringBefore(Array:which, item, const input[]);
/**
* Swaps the position of two items.
*
* @param which Array handle
* @param item1,item2 Item pair to swap
*
* @noreturn
* @error If an invalid handle or an invalid index is provided an
* error will be thrown.
*/
native ArraySwap(Array:which, item1, item2);
/**
* Deletes an item from the array. All items beyond it get shifted down by one.
*
* @param which Array handle
* @param item Item to delete
*
* @noreturn
* @error If an invalid handle or an invalid index is provided an
* error will be thrown.
*/
native ArrayDeleteItem(Array:which, item);
/**
* Searches through the array and returns the index of the first occurence of
* the specified string.
*
* @param which Array handle
* @param item String to search for
*
* @return Array index on success, -1 if the string can't be found
* @error Invalid handle.
*/
native ArrayFindString(Array:which, const item[]);
/**
* Searches through the array and returns the index of the first occurence of
* the specified value.
*
* @param which Array handle
* @param item Value to search for
*
* @return Array index on success, -1 if the value can't be found
* @error If an invalid handle is provided an error will be
* thrown.
*/
native ArrayFindValue(Array:which, any:item);
/**
* Creates a special handle that can be passed to a string format routine for
* printing as a string (with the %a format option).
*
* @note It is recommended to pass the function as a parameter to the format
* routine directly. The array item must contain a null-terminated string!
* @note Do not save or otherwise use the handles returned by this function.
* @note Example usage:
* console_print(id, "%a", ArrayGetStringHandle(MessageArray, i));
*
* @param which Array handle
* @param item Item to retrieve handle of
*
* @return Handle to the item
* @error If an invalid handle or an invalid index is provided an
* error will be thrown.
*/
native DoNotUse:ArrayGetStringHandle(Array:which, item);
/**
* Destroys the array and frees its memory.
*
* @note The function automatically sets the variable passed to it to 0 to aid
* in preventing accidental usage after destroy.
*
* @param which Array to destroy
*
* @return 1 if the Array was destroyed, 0 if nothing had to be
* destroyed (invalid handle)
*/
native ArrayDestroy(&Array:which);
/**
* Similar to sorting.inc's CustomSort, the sorting algorithm then uses the
* custom comparison function to sort the data.
*
* @note The function is called in the following manner:
*
* public MySortFunc(Array:array, item1, item2, const data[], data_size)
*
* array - Array handle in its current un-sorted state
* item1, item2 - Current item pair being compared
* data[] - Extra data array passed to the sort func
* data_size - Size of extra data
*
* @note The comparison function should return:
* -1 if item1 should go before item2
* 0 if item1 and item2 are equal
* 1 if item1 should go after item2
*
* @note All parameters after item2 are optional and do not need to be specified
* and used.
* @note Unlike the sorting.inc version, the array passed to the callback is not
* in mid-sorted state.
*
* @param array Array handle
* @param comparefunc Callback function used for comparison
* @param data Extra data that is passed through to the callback
* @param data_size Size of extra data
*
* @noreturn
* @error If an invalid handle or an invalid callback is provided
* an error will be thrown.
*/
native ArraySort(Array:array, const comparefunc[], data[]="", data_size=0);
/**
* A faster version of ArraySort, the sorting algorithm then uses the custom
* comparison function to sort the data.
*
* @note The advantage of this function is that the data of the elements being
* compared is directly passed to the function, instead of the item
* indexes that are passed by ArraySort. This removes the need for calling
* ArrayGet[Cell|String|Array] every time before being able to compare the
* elements.
*
* @note For Arrays with a cellsize of 1 (used for storing integers and floats),
* the function is called in the following manner:
*
* public MySortFunc(Array:array, elem1, elem2, const data[], data_size)
*
* array - Array handle in its current un-sorted state
* elem1, elem2 - Current element pair being compared
* data[] - Extra data array passed to the sort func
* data_size - Size of extra data
*
* @note For Arrays with a cellsize larger than 1 (used for storing arrays and
* strings), the function is called in the following manner:
*
* public MySortFunc(Array:array, elem1[], elem2[], const data[], data_size)
*
* array - Array handle in its current un-sorted state
* elem1[], elem2[] - Current element pair being compared
* data[] - Extra data array passed to the sort func
* data_size - Size of extra data
*
*
* @note The comparison function should return:
* -1 if elem1 should go before elem2
* 0 if elem1 and elem2 are equal
* 1 if elem1 should go after elem2
*
* @note All parameters after item2 are optional and do not need to be specified
* and used.
* @note Unlike the sorting.inc version, the array passed to the callback is not
* in mid-sorted state.
*
* @param array Array handle
* @param comparefunc Callback function used for comparison
* @param data Extra data that is passed through to the callback
* @param data_size Size of extra data
*
* @noreturn
* @error If an invalid handle or an invalid callback is provided
* an error will be thrown.
*/
native ArraySortEx(Array:array, const comparefunc[], data[]="", data_size=0);

View File

@ -0,0 +1,166 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
#if defined _cellstack_included
#endinput
#endif
#define _cellstack_included
/**
* Stack tag declaration
*
* @note Plugins are responsible for freeing all Stack handles they acquire.
* Failing to free handles will result in the plugin and AMXX leaking
* memory.
*/
enum Stack
{
Invalid_Stack = 0
};
/**
* Creates a stack structure. A stack is a LIFO (last in, first out) vector of
* of items. It has O(1) insertion and O(1) removal.
*
* @note Stacks provide only two operations: Push (adding an item to the top)
* and Pop (remove an item from the top, in reverse-push order).
* @note The contents of the stack are uniform; i.e. storing a string and then
* retrieving it as an integer is NOT the same as str_to_num()!
* @note The "blocksize" determines how many cells each stack slot has, it can
* not be changed after creation.
*
* @param blocksize The number of cells each entry in the stack can hold
*
* @return New stack Handle, which must be freed via DestroyStack()
* @error If an invalid blocksize is provided an error will be
* thrown.
*/
native Stack:CreateStack(blocksize = 1);
/**
* Pushes a value onto the end of the stack, adding a new index.
*
* @note This may safely be used even if the stack has a blocksize greater than
* 1.
*
* @param handle Stack handle
* @param value Value to push
*
* @noreturn
* @error If an invalid handle is provided or the resizing
* operation runs out of memory, an error will be thrown.
*/
native PushStackCell(Stack:handle, any:value);
/**
* Pushes a string onto the end of a stack, truncating it if it is too long.
*
* @param handle Stack handle
* @param value String to push
*
* @noreturn
* @error If an invalid handle is provided or the resizing
* operation runs out of memory, an error will be thrown.
*/
native PushStackString(Stack:handle, const value[]);
/**
* Pushes an array of cells onto the end of a stack. The cells are pushed as a
* block (i.e. the entire array takes up one stack slot), rather than pushing
* each cell individually.
*
* @param handle Stack handle
* @param values Block of values to copy
* @param size If not set, the number of elements copied from the array
* will be equal to the blocksize, if set higher than the
* blocksize, the operation will be truncated,
*
* @noreturn
* @error If an invalid handle is provided or the resizing
* operation runs out of memory, an error will be thrown.
*/
native PushStackArray(Stack:handle, const any:values[], size= -1);
/**
* Pops a cell value from a stack.
*
* @param handle Stack handle
* @param value Variable to store the value in
* @param block Optionally specify which block to read from (useful if the
* blocksize is > 0)
* @param asChar Optionally read as a byte instead of a cell
*
* @return True on success, false if the stack is empty.
* @error If an invalid handle, invalid block or invalid byte is
* provided, an error will be thrown.
*/
native bool:PopStackCell(Stack:handle, &any:value, block = 0, bool:asChar = false);
/**
* Pops a string value from a stack.
*
* @param handle Stack handle
* @param buffer Buffer to copy string to
* @param maxlength Maximum size of the buffer
* @param written Variable to store number of characters copied to
*
* @return True on success, false if the stack is empty
* @error If an invalid handle is provided an error will be thrown.
*/
native bool:PopStackString(Stack:handle, buffer[], maxlength, &written = 0);
/**
* Pops an array of cells from a stack.
*
* @param handle Stack handle
* @param buffer Array to copy value to
* @param size Size of buffer, if not set (-1) assumes the size is equal to
* the stack blocksize
*
* @return True on success, false if the stack is empty
* @error If an invalid handle is provided an error will be thrown.
*/
native bool:PopStackArray(Stack:handle, any:buffer[], size = -1);
/**
* Returns if a stack is empty.
*
* @param handle Stack handle
*
* @return True if empty, false if not empty
* @error If an invalid handle is provided an error will be thrown.
*/
native bool:IsStackEmpty(Stack:handle);
/**
* Pops a value off a stack, ignoring it completely.
*
* @param handle Stack handle
*
* @return True if a value was popped, false if stack is empty
* @error If an invalid handle is provided an error will be thrown.
*/
stock PopStack(Stack:handle)
{
new value;
return PopStackCell(handle, value);
}
/**
* Destroys a stack and frees its memory.
*
* @note The function automatically sets the variable passed to it to 0 to aid
* in preventing accidental usage after destroy.
*
* @param handle Stack to destroy
*
* @return 1 if the Stack was destroyed, 0 if nothing had to be
* destroyed (invalid handle)
*/
native DestroyStack(&Stack:handle);

View File

@ -0,0 +1,412 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
#if defined _celltrie_included
#endinput
#endif
#define _celltrie_included
/**
* Hash map tag declaration
*
* @note The word "Trie" in this API is historical. As of AMX Mod X 1.8.3,
* tries have been internally replaced with hash tables, which have O(1)
* insertion time instead of O(n).
* @note Plugins are responsible for freeing all Trie handles they acquire.
* Failing to free handles will result in the plugin and AMXX leaking
* memory.
*/
enum Trie
{
Invalid_Trie = 0
};
/**
* Hash map iterator tag declaration
*
* @note The word "Trie" in this API is historical. As of AMX Mod X 1.8.3,
* tries have been internally replaced with hash tables, which have O(1)
* insertion time instead of O(n).
* @note Plugins are responsible for freeing all TrieIter handles they acquire.
* Failing to free handles will result in the plugin and AMXX leaking
* memory.
*/
enum TrieIter
{
Invalid_TrieIter = 0
}
/**
* Hash map snapshot tag declaration
*
* @note Plugins are responsible for freeing all Snapshot handles they acquire.
* Failing to free handles will result in the plugin and AMXX leaking
* memory.
*/
enum Snapshot
{
Invalid_Snapshot = 0
};
/**
* Creates a hash map. A hash map is a container that maps strings (called keys)
* to arbitrary values (cells, arrays or strings).
*
* @note Keys in a hash map are unique so there is no more than one entry in the
* map for any given key.
* @note Insertion, deletion, and lookup in a hash map are all considered to be
* fast operations, amortized to O(1), or constant time.
*
* @return New Map handle, which must be freed via TrieDestroy()
*/
native Trie:TrieCreate();
/**
* Clears all entries from a Map.
*
* @param handle Map handle
*
* @error If an invalid handle is provided an error will be
* thrown.
* @noreturn
*/
native TrieClear(Trie:handle);
/**
* Sets a cell value in a hash map, either inserting a new entry or replacing
* an old one.
*
* @param handle Map handle
* @param key Key string
* @param value Value to store
* @param replace If false the operation will fail if the key is already set
*
* @return 1 on success, 0 otherwise
* @error If an invalid handle is provided an error will be
* thrown.
*/
native TrieSetCell(Trie:handle, const key[], any:value, bool:replace = true);
/**
* Sets a string value in a hash map, either inserting a new entry or replacing
* an old one.
*
* @param handle Map handle
* @param key Key string
* @param value String to store
* @param replace If false the operation will fail if the key is already set
*
* @return 1 on success, 0 otherwise
* @error If an invalid handle is provided an error will be
* thrown.
*/
native TrieSetString(Trie:handle, const key[], const value[], bool:replace = true);
/**
* Sets an array value in a hash map, either inserting a new entry or replacing
* an old one.
*
* @param handle Map handle
* @param key Key string
* @param buffer Array to store
* @param size Array size
* @param replace If false the operation will fail if the key is already set
*
* @return 1 on success, 0 otherwise
* @error If an invalid handle is provided an error will be
* thrown. or invalid array size
*/
native TrieSetArray(Trie:handle, const key[], const any:buffer[], size, bool:replace = true);
/**
* Retrieves a cell value from a hash map.
*
* @param handle Map handle
* @param key Key string
* @param value Variable to store value to
*
* @return True on success, false if either the key is not set or the
* value type does not match (value is string or array)
* @error If an invalid handle is provided an error will be
* thrown.
*/
native bool:TrieGetCell(Trie:handle, const key[], &any:value);
/**
* Retrieves a string from a hash map.
*
* @param handle Map handle
* @param key Key string
* @param output Buffer to copy the value to
* @param outputsize Maximum size of buffer
* @param size Optional variable to store the number of cells written
* to the buffer in
*
* @return True on success, false if either the key is not set or
* the value type does not match (value is cell or array)
* @error If an invalid handle is provided an error will be
* thrown.
*/
native bool:TrieGetString(Trie:handle, const key[], output[], outputsize, &size = 0);
/**
* Retrieves a string from a hash map.
*
* @param handle Map handle
* @param key Key string
* @param output Array to copy the value to
* @param outputsize Maximum size of array
* @param size Optional variable to store the number of cells written
* to the array in
*
* @return True on success, false if either the key is not set or
* the value type does not match (value is cell or string)
* @error If an invalid handle or array size is provided an error
* will be thrown.
*/
native bool:TrieGetArray(Trie:handle, const key[], any:output[], outputsize, &size = 0);
/**
* Removes an entry from a hash map.
*
* @param handle Map handle
* @param key Key string
*
* @return True on success, false if the key was never set
* @error If an invalid handle is provided an error will be
* thrown.
*/
native bool:TrieDeleteKey(Trie:handle, const key[]);
/**
* Checks a hash map for the existence of an entry.
*
* @param handle Map handle
* @param key Key string
*
* @return True if the key is set, false otherwise
* @error If an invalid handle is provided an error will be
* thrown.
*/
native bool:TrieKeyExists(Trie:handle, const key[]);
/**
* Destroys a hash map and frees its memory.
*
* @note The function automatically sets the variable passed to it to 0 to aid
* in preventing accidental usage after destroy.
*
* @param handle Map handle
*
* @return 1 on success, 0 if an invalid handle was passed in
*/
native TrieDestroy(&Trie:handle);
/**
* Returns the number of entries in a hash map.
*
* @param handle Map handle
*
* @return Number of elements in the hash map
* @error If an invalid handle is provided an error will be
* thrown.
*/
native TrieGetSize(Trie:handle);
/**
* Creates a snapshot of all keys in a hash map. If the map is changed
* afterwards, the changes are not reflected in the snapshot.
* Keys are not sorted.
*
* @param handle Map handle
*
* @return New map snapshot handle, which must be freed via
* TrieSnapshotDestroy()
* @error If an invalid handle is provided an error will be
* thrown.
*/
native Snapshot:TrieSnapshotCreate(Trie:handle);
/**
* Returns the number of keys in a map snapshot. Note that this may be
* different from the size of the map, since the map can change after the
* snapshot of its keys was taken.
*
* @param handle Map snapshot handle
*
* @return Number of keys
* @error If an invalid handle is provided an error will be
* thrown.
*/
native TrieSnapshotLength(Snapshot:handle);
/**
* Returns the buffer size required to store a given key. That is, it returns
* the length of the key plus one.
*
* @param handle Map snapshot handle
* @param index Key index (starting from 0)
*
* @return Buffer size required to store the key string
* @error If an invalid handle is provided an error will be
* thrown. or index out of range
*/
native TrieSnapshotKeyBufferSize(Snapshot:handle, index);
/**
* Retrieves the key string of a given key in a map snapshot.
*
* @param handle Map snapshot handle
* @param index Key index (starting from 0)
* @param buffer String buffer
* @param maxlength Maximum buffer length
*
* @return Number of bytes written to the buffer
* @error If an invalid handle is provided an error will be
* thrown. or index out of range
*/
native TrieSnapshotGetKey(Snapshot:handle, index, buffer[], maxlength);
/**
* Destroys a map snapshot and frees its memory.
*
* @note The function automatically sets the variable passed to it to 0 to aid
* in preventing accidental usage after destroy.
*
* @param handle Map snapshot handle
*
* @return 1 on success, 0 if an invalid handle was passed in
*/
native TrieSnapshotDestroy(&Snapshot:handle);
/**
* Creates an iterator for a map. It provides iterative read-only access to the
* maps contents.
*
* @note Removing or adding keys to the underlying map will invalidate all its
* iterators. Updating values of existing keys is allowed and the changes
* will be immediately reflected in the iterator.
* @note Iterators are designed to be short-lived and not stored, and creating
* them is very cheap. Reading data from an iterator is just as fast as
* reading directly from the map.
* @note Just like in snapshots the keys are not sorted.
*
* @return New iterator handle, which must be freed via TrieIterDestroy().
* @error Invalid Handle
*/
native TrieIter:TrieIterCreate(Trie:handle);
/**
* Returns if the iterator has reached its end and no more data can be read.
*
* @param handle Iterator handle
*
* @return True if iterator has reached the end, false otherwise
* @error Invalid Handle
* Iterator has been closed (underlying map destroyed)
* Iterator is outdated
*/
native bool:TrieIterEnded(TrieIter:handle);
/**
* Advances the iterator to the next key/value pair if one is available.
*
* @param handle Iterator handle
*
* @error Invalid Handle
* Iterator has been closed (underlying map destroyed)
* Iterator is outdated
*/
native TrieIterNext(TrieIter:handle);
/**
* Retrieves the key the iterator currently points to.
*
* @param handle Iterator handle.
* @param key Buffer to store the current key in.
* @param outputsize Maximum size of string buffer.
*
* @return Nnumber of bytes written to the buffer
* @error Invalid handle
* Iterator has been closed (underlying map destroyed)
* Iterator is outdated
*/
native TrieIterGetKey(TrieIter:handle, key[], outputsize);
/**
* Retrieves the number of elements in the underlying map.
*
* @note When used on a valid iterator this is exactly the same as calling TrieGetSize on the map directly.
*
* @param handle Iterator handle
*
* @return Number of elements in the map
* @error Invalid handle
* Iterator has been closed (underlying map destroyed)
* Iterator is outdated
*/
native TrieIterGetSize(TrieIter:handle);
/**
* Retrieves a value at the current position of the iterator.
*
* @param handle Iterator handle
* @param value Variable to store value in
*
* @return True on success, false if the iterator is empty or the current
* value is an array or a string.
* @error Invalid handle
* Iterator has been closed (underlying map destroyed)
* Iterator is outdated
*/
native bool:TrieIterGetCell(TrieIter:handle, &any:value);
/**
* Retrieves a string at the current position of the iterator.
*
* @param handle Iterator handle
* @param buffer Buffer to store the string in
* @param outputsize Maximum size of string buffer
* @param size Optional parameter to store the number of bytes written to the buffer.
*
* @return True on success, false if the iterator is empty or the current value
* is not a string.
* @error Invalid handle
* Invalid buffer size
* Iterator has been closed (underlying map destroyed)
* Iterator is outdated
*/
native bool:TrieIterGetString(TrieIter:handle, buffer[], outputsize, &size = 0);
/**
* Retrieves an array at the current position of the iterator.
*
* @param handle Iterator handle
* @param buffer Buffer to store the array
* @param outputsize Maximum size of buffer
* @param size Optional parameter to store the number of bytes written to the buffer
*
* @return True on success, false if the iterator is empty or the current
* value is not an array.
* @error Invalid handle
* Invalid buffer size
* Iterator has been closed (underlying map destroyed)
* Iterator is outdated
*/
native bool:TrieIterGetArray(TrieIter:handle, any:array[], outputsize, &size = 0);
/**
* Destroys an iterator handle.
*
* @param handle Iterator handle.
*
* @return True on success, false if the value was never set.
*/
native TrieIterDestroy(&TrieIter:handle);

View File

@ -0,0 +1,142 @@
/* Fun functions
*
* by Numb
*
* This file is provided as is (no warranties).
*/
#if defined _colorchat_included
#endinput
#endif
#define _colorchat_included
enum Color
{
NORMAL = 1, // clients scr_concolor cvar color
GREEN, // Green Color
TEAM_COLOR, // Red, grey, blue
GREY, // grey
RED, // Red
BLUE, // Blue
}
new TeamName[][] =
{
"",
"TERRORIST",
"CT",
"SPECTATOR"
}
ColorChat(id, Color:type, const msg[], {Float,Sql,Result,_}:...)
{
new message[256];
switch(type)
{
case NORMAL: // clients scr_concolor cvar color
{
message[0] = 0x01;
}
case GREEN: // Green
{
message[0] = 0x04;
}
default: // White, Red, Blue
{
message[0] = 0x03;
}
}
vformat(message[1], 251, msg, 4);
// Make sure message is not longer than 192 character. Will crash the server.
message[192] = '^0';
new team, ColorChange, index, MSG_Type;
if(id)
{
MSG_Type = MSG_ONE;
index = id;
} else {
index = FindPlayer();
MSG_Type = MSG_ALL;
}
team = get_user_team(index);
ColorChange = ColorSelection(index, MSG_Type, type);
ShowColorMessage(index, MSG_Type, message);
if(ColorChange)
{
Team_Info(index, MSG_Type, TeamName[team]);
}
}
ShowColorMessage(id, type, message[])
{
static bool:saytext_used;
static get_user_msgid_saytext;
if(!saytext_used)
{
get_user_msgid_saytext = get_user_msgid("SayText");
saytext_used = true;
}
message_begin(type, get_user_msgid_saytext, _, id);
write_byte(id)
write_string(message);
message_end();
}
Team_Info(id, type, team[])
{
static bool:teaminfo_used;
static get_user_msgid_teaminfo;
if(!teaminfo_used)
{
get_user_msgid_teaminfo = get_user_msgid("TeamInfo");
teaminfo_used = true;
}
message_begin(type, get_user_msgid_teaminfo, _, id);
write_byte(id);
write_string(team);
message_end();
return 1;
}
ColorSelection(index, type, Color:Type)
{
switch(Type)
{
case RED:
{
return Team_Info(index, type, TeamName[1]);
}
case BLUE:
{
return Team_Info(index, type, TeamName[2]);
}
case GREY:
{
return Team_Info(index, type, TeamName[0]);
}
}
return 0;
}
FindPlayer()
{
new i = -1;
while(i <= get_maxplayers())
{
if(is_user_connected(++i))
return i;
}
return -1;
}

View File

@ -0,0 +1,202 @@
/* Core functions
*
* (c) Copyright 1998-2003, ITB CompuPhase
*
* This file is provided as is (no warranties).
*/
#if defined _core_included
#endinput
#endif
#define _core_included
/**
* Returns the free memory space available to the plugin.
*
* @note This is a debugging function that is not intended for general plugin
* use.
*
* @return Free memory space in bytes
*/
native heapspace();
/**
* Returns the function index of a public function declared in the plugin.
*
* @param name Function name
*
* @return Function index > 0 on success, -1 if function was not found
* @error If the function name is too long (longer than 63 characters)
* an error will be thrown.
*/
native funcidx(const name[]);
/**
* Returns the number of arguments passed into the currently executed function.
*
* @return Number of arguments passed
*/
native numargs();
/**
* Retrieves an argument value passed into the currently executed function.
*
* @param arg Argument index
* @param index Index to retrieve from the argument (for arrays and strings)
*
* @return Argument value at given index
*/
native getarg(arg, index = 0);
/**
* Sets the value of an argument passed into the currently executed function.
*
* @note This is not equal to assigning a new value to a by-reference argument.
*
* @param arg Argument index
* @param index Index to set in the argument (for arrays and strings)
*/
native setarg(arg, index = 0, value);
/**
* Converts a character to lowercase.
*
* @note This is not UTF8 or locale-safe.
*
* @param c Character to convert
*
* @return Converted character
*/
native tolower(c);
/**
* Converts a character to uppercase.
*
* @note This is not UTF8 or locale-safe.
*
* @param c Character to convert
*
* @return Converted character
*/
native toupper(c);
/**
* Swaps the bytes of a value (the lowest byte becomes the highest byte).
*
* @param c Value to swap
*
* @return Byte-swapped value
*/
native swapchars(c);
/**
* Returns a random number between 0 and a specified upper bound.
*
* @param max Exclusive upper bound
*
* @return Random value
*/
native random(max);
/**
* Returns the smaller of two provided values.
*
* @param value1 Value one
* @param value2 Value two
*
* @return Smaller of the two values
*/
native min(value1, value2);
/**
* Returns the bigger of two provided values.
*
* @param value1 Value one
* @param value2 Value two
*
* @return Bigger of the two values
*/
native max(value1, value2);
/**
* Limits a provided value between two specified bounds.
*
* @param value Value to clamp
* @param min Lower bound
* @param max Upper bound
*
* @return The value if it is between the lower and upper bound, min if
* value is below, max if it is above the specified bounds.
*/
native clamp(value, min = cellmin, max = cellmax);
/**
* Returns a value raised to a specified exponent.
*
* @param value Value
* @param exponent Exponent to raise value to
*
* @return Value to the power of exponent
*/
native power(value, exponent);
/**
* Returns the approximated square root of a value.
*
* @note This uses a simple successice approximation algorithm (continuously
* dividing the value) and only deals with integers, this makes it very
* imprecise.
*
* @param value Value
*
* @return Square root of the value
*/
native sqroot(value);
/**
* Retrieves the current time in hours, minutes and seconds.
*
* @param hour Variable to store hours in
* @param minute Variable to store minutes in
* @param second Variable to store seconds in
*
* @return Unix timestamp
*/
native time(&hour = 0, &minute = 0, &second = 0);
/**
* Retrieves the current date in year, month and day.
*
* @param year Variable to store year in
* @param month Variable to store month in
* @param day Variable to store day in
*
* @noreturn
*/
native date(&year = 0, &month = 0, &day = 0);
/**
* Returns the elapsed CPU seconds.
*
* @note This is a debugging function that is not intended for general plugin
* use.
* @note This uses the C clock() function internally and comes with all its
* drawbacks attached.
*
* @param granularity Unused
*
* @return Number of CPU seconds elapsed
*/
native tickcount(&granularity = 0);
/**
* Returns the absolute value of a number.
*
* @param x Integral value
*
* @return Absolute value of x (x if it is greater than 0, -x otherwise)
*/
stock abs(x)
{
return x > 0 ? x : -x;
}

View File

@ -0,0 +1,298 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
#if defined _csstats_included
#endinput
#endif
#define _csstats_included
#include <csstats_const>
/**
* Retrieves the client's current weapon statistics.
*
* @note For a list of default CS weapon ids see the CSW_* constants in
* amxconst.inc, this function also works on custom weapons.
* @note For a list of possible body hitplaces see the HIT_* constants in
* amxconst.inc
* @note For a list of possible stat constants see the STATSX_* constants in
* amxconst.inc
* @note The fields in the statistics are:
* 0 - Kills
* 1 - Deaths
* 2 - Headshots
* 3 - Teamkills
* 4 - Shots
* 5 - Hits
* 6 - Damage
*
* @param index Client index
* @param wpnindex Weapon id, or 0 to retrieve total statistics across all
* weapons
* @param stats Buffer to copy statistics to
* @param bodyhits Buffer to copy body hits to
*
* @return 1 on success, 0 if no statistics are available for the weapon
* id
* @error If an invalid client index or weapon id is provided, an
* error will be thrown.
*/
native get_user_wstats(index, wpnindex, stats[STATSX_MAX_STATS], bodyhits[MAX_BODYHITS]);
/**
* Retrieves the client's weapon statistics from the current round.
*
* @note For a list of default CS weapon ids see the CSW_* constants in
* amxconst.inc, this function also works on custom weapons.
* @note For a list of possible body hitplaces see the HIT_* constants in
* amxconst.inc
* @note For a list of possible stat constants see the STATSX_* constants in
* amxconst.inc
* @note The fields in the statistics are:
* 0 - Kills
* 1 - Deaths
* 2 - Headshots
* 3 - Teamkills
* 4 - Shots
* 5 - Hits
* 6 - Damage
*
* @param index Client index
* @param wpnindex Weapon id, or 0 to retrieve total statistics across all
* weapons
* @param stats Buffer to copy statistics to
* @param bodyhits Buffer to copy body hits to
*
* @return 1 on success, 0 if no statistics are available for the
* weapon id
* @error If an invalid client index or weapon id is provided, an
* error will be thrown.
*/
native get_user_wrstats(index, wpnindex, stats[STATSX_MAX_STATS], bodyhits[MAX_BODYHITS]);
/**
* Retrieves the client's weapon statistics from the permanent storage on the
* server.
*
* @note The permanent storage is updated on every respawn or client disconnect.
* @note Player rank is determined by the customizable "get_score" function in
* "data/csstats.amxx". By default it uses the difference of kills to
* deaths/teamkills.
* @note For a list of possible body hitplaces see the HIT_* constants in
* amxconst.inc
* @note For a list of possible stat constants see the STATSX_* constants in
* amxconst.inc
* @note The fields in the statistics are:
* 0 - Kills
* 1 - Deaths
* 2 - Headshots
* 3 - Teamkills
* 4 - Shots
* 5 - Hits
* 6 - Damage
* 7 - Rank
*
* @param index Client index
* @param stats Buffer to copy statistics to
* @param bodyhits Buffer to copy body hits to
*
* @return Players rank > 0 on success, or 0 if player is not ranked
* and no statistics are available
* @error If an invalid client index is provided, an error will be
* thrown.
*/
native get_user_stats(index, stats[STATSX_MAX_STATS], bodyhits[MAX_BODYHITS]);
/**
* Retrieves the client's statistics from the current round.
*
* @note For a list of possible body hitplaces see the HIT_* constants in
* amxconst.inc
* @note For a list of possible stat constants see the STATSX_* constants in
* amxconst.inc
* @note The fields in the statistics are:
* 0 - Kills
* 1 - Deaths
* 2 - Headshots
* 3 - Teamkills
* 4 - Shots
* 5 - Hits
* 6 - Damage
*
* @param index Client index
* @param stats Buffer to copy statistics to
* @param bodyhits Buffer to copy body hits to
*
* @return 1 on success, 0 if no statistics are available
* @error If an invalid client index is provided, an error will be
* thrown.
*/
native get_user_rstats(index, stats[STATSX_MAX_STATS], bodyhits[MAX_BODYHITS]);
/**
* Retrieves the client's statistics inflicted upon another client from the
* current round.
*
* @note For a list of possible body hitplaces see the HIT_* constants in
* amxconst.inc
* @note For a list of possible stat constants see the STATSX_* constants in
* amxconst.inc
* @note The fields in the statistics are:
* 0 - Kills
* 1 - Deaths
* 2 - Headshots
* 3 - Teamkills
* 4 - Shots
* 5 - Hits
* 6 - Damage
*
* @param index Client index
* @param victim Victim client index, or 0 to retrieve the statistics against
* all victims
* @param stats Buffer to copy statistics to
* @param bodyhits Buffer to copy body hits to
* @param wpnname Optional buffer to copy last used weapon name to
* @param len Maximum buffer size
*
* @return 1 on success, 0 if no statistics are available against the
* specified victim
* @error If an invalid client index is provided, an error will be
* thrown.
*/
native get_user_vstats(index, victim, stats[STATSX_MAX_STATS], bodyhits[MAX_BODYHITS], wpnname[] = "", len = 0);
/**
* Retrieves the client's statistics received from another client from the
* current round.
*
* @note For a list of possible body hitplaces see the HIT_* constants in
* amxconst.inc
* @note For a list of possible stat constants see the STATSX_* constants in
* amxconst.inc
* @note The fields in the statistics are:
* 0 - Kills
* 1 - Deaths
* 2 - Headshots
* 3 - Teamkills
* 4 - Shots
* 5 - Hits
* 6 - Damage
*
* @param index Client index
* @param wpnindex Attacker client index, or 0 to retrieve the statistics from
* all attackers
* @param stats Buffer to copy statistics to
* @param bodyhits Buffer to copy body hits to
* @param wpnname Optional buffer to copy last used weapon name to
* @param len Maximum buffer size
*
* @return 1 on success, 0 if no statistics are available against the
* specified attacker
* @error If an invalid client index is provided, an error will be
* thrown.
*/
native get_user_astats(index, wpnindex, stats[STATSX_MAX_STATS], bodyhits[MAX_BODYHITS], wpnname[] = "", len = 0);
/**
* Resets the current round weapon, attacker and victim statistics.
*
* @param index Client index
*
* @noreturn
* @error If an invalid client index is provided, an error will be
* thrown.
*/
native reset_user_wstats(index);
/**
* Retrieves statistics from the permanent storage on the server via iterative,
* incremental access.
*
* @note The permanent storage is updated on every respawn or client disconnect.
* @note Player rank is determined by the customizable "get_score" function in
* "data/csstats.amxx". By default it uses the difference of kills to
* deaths/teamkills.
* @note For a list of possible body hitplaces see the HIT_* constants in
* amxconst.inc
* @note For a list of possible stat constants see the STATSX_* constants in
* amxconst.inc
* @note The fields in the statistics are:
* 0 - Kills
* 1 - Deaths
* 2 - Headshots
* 3 - Teamkills
* 4 - Shots
* 5 - Hits
* 6 - Damage
* 7 - Rank
*
* @param index Rank index
* @param stats Buffer to copy statistics to
* @param bodyhits Buffer to copy body hits to
* @param name Buffer to copy client name to
* @param len Maximum name buffer size
* @param authid Buffer to copy client auth id to
* @param authidlen Maximum authid buffer size
*
* @return Next rank index (> 0 and > index), or 0 if no more
* statistics exist
*/
native get_stats(index, stats[STATSX_MAX_STATS], bodyhits[MAX_BODYHITS], name[], len, authid[] = "", authidlen = 0);
/**
* Returns the number of all entries in the permanent statistics storage.
*
* @return Number of entries in statistics storage
*/
native get_statsnum();
/**
* Retrieves the client's objective statistics from the permanent storage.
*
* @note The permanent storage is updated on every respawn or client disconnect.
* @note For a list of possible stat constants see the STATSX_* constants in
* amxconst.inc
* @note The fields in the statistics are:
* 0 - total defusions
* 1 - bomb defused
* 2 - bomb plants
* 3 - bomb explosions
*
* @param index Client index
* @param stats Buffer to copy statistics to
*
* @return Players rank > 0 on success, or 0 if player is not ranked
* and no statistics are available
* @error If an invalid client index is provided, an error will be
* thrown.
*/
native get_user_stats2(index, stats[STATSX_MAX_OBJECTIVE]);
/**
* Retrieves objective statistics from the permanent storage on the server via
* iterative, incremental access.
*
* @note The permanent storage is updated on every respawn or client disconnect.
* @note For a list of possible stat constants see the STATSX_* constants in
* amxconst.inc
* @note The fields in the statistics are:
* 0 - total defusions
* 1 - bomb defused
* 2 - bomb plants
* 3 - bomb explosions
*
* @param index Client index
* @param stats Buffer to copy statistics to
* @param authid Buffer to copy client auth id to
* @param authidlen Maximum authid buffer size
*
* @return Next rank index (> 0 and > index), or 0 if no more
* statistics exist
*/
native get_stats2(index, stats[STATSX_MAX_OBJECTIVE], authid[] = "", authidlen = 0);

View File

@ -0,0 +1,29 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Counter-Strike Functions
//
#if defined _csstats_const_included
#endinput
#endif
#define _csstats_const_included
/**
* Constants for objective based statistics
*/
enum
{
STATSX_TOTAL_DEFUSIONS = 0,
STATSX_BOMBS_DEFUSED,
STATSX_BOMBS_PLANTED,
STATSX_BOMB_EXPLOSIONS,
STATSX_MAX_OBJECTIVE
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,521 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Counter-Strike Functions
//
#if defined _cstrike_const_included
#endinput
#endif
#define _cstrike_const_included
/**
* IDs of weapons in CS
*/
#define CSW_NONE 0
#define CSW_P228 1
#define CSW_GLOCK 2 // Unused by game, See CSW_GLOCK18.
#define CSW_SCOUT 3
#define CSW_HEGRENADE 4
#define CSW_XM1014 5
#define CSW_C4 6
#define CSW_MAC10 7
#define CSW_AUG 8
#define CSW_SMOKEGRENADE 9
#define CSW_ELITE 10
#define CSW_FIVESEVEN 11
#define CSW_UMP45 12
#define CSW_SG550 13
#define CSW_GALI 14
#define CSW_GALIL 14
#define CSW_FAMAS 15
#define CSW_USP 16
#define CSW_GLOCK18 17
#define CSW_AWP 18
#define CSW_MP5NAVY 19
#define CSW_M249 20
#define CSW_M3 21
#define CSW_M4A1 22
#define CSW_TMP 23
#define CSW_G3SG1 24
#define CSW_FLASHBANG 25
#define CSW_DEAGLE 26
#define CSW_SG552 27
#define CSW_AK47 28
#define CSW_KNIFE 29
#define CSW_P90 30
#define CSW_VEST 31 // Custom
#define CSW_VESTHELM 32 // Custom
#define CSW_SHIELDGUN 99
#define CSW_LAST_WEAPON CSW_P90
const CSW_ALL_WEAPONS = (~(1<<CSW_VEST));
const CSW_ALL_PISTOLS = (1<<CSW_P228 | 1<<CSW_ELITE | 1<<CSW_FIVESEVEN | 1<<CSW_USP | 1<<CSW_GLOCK18 | 1<<CSW_DEAGLE);
const CSW_ALL_SHOTGUNS = (1<<CSW_M3 | 1<<CSW_XM1014);
const CSW_ALL_SMGS = (1<<CSW_MAC10 | 1<<CSW_UMP45 | 1<<CSW_MP5NAVY | 1<<CSW_TMP | 1<<CSW_P90);
const CSW_ALL_RIFLES = (1<<CSW_AUG | 1<<CSW_GALIL | 1<<CSW_FAMAS | 1<<CSW_M4A1 | 1<<CSW_AK47 | 1<<CSW_SG552);
const CSW_ALL_SNIPERRIFLES = (1<<CSW_SCOUT | 1<<CSW_AWP | 1<<CSW_G3SG1 | 1<<CSW_SG550);
const CSW_ALL_MACHINEGUNS = (1<<CSW_M249);
const CSW_ALL_GRENADES = (1<<CSW_HEGRENADE | 1<<CSW_SMOKEGRENADE | 1<<CSW_FLASHBANG);
const CSW_ALL_ARMORS = (1<<CSW_VEST | 1<<CSW_VESTHELM);
const CSW_ALL_GUNS = (CSW_ALL_PISTOLS | CSW_ALL_SHOTGUNS | CSW_ALL_SMGS | CSW_ALL_RIFLES | CSW_ALL_SNIPERRIFLES | CSW_ALL_MACHINEGUNS);
/**
* @section Team and team model constants, used by cs_[get|set]_user_team().
*/
/**
* Internal Counter-Strike model id constants.
*
* @note Model ids starting with CZ_ are only valid in Condition Zero.
*/
enum CsInternalModel
{
CS_NORESET = -1,
CS_DONTCHANGE = 0,
CS_UNASSIGNED = 0,
CS_CT_URBAN = 1,
CS_T_TERROR = 2,
CS_T_LEET = 3,
CS_T_ARCTIC = 4,
CS_CT_GSG9 = 5,
CS_CT_GIGN = 6,
CS_CT_SAS = 7,
CS_T_GUERILLA = 8,
CS_CT_VIP = 9,
CZ_T_MILITIA = 10,
CZ_CT_SPETSNAZ = 11,
};
/**
* Counter-Strike team id constants.
*/
enum CsTeams
{
CS_TEAM_UNASSIGNED = 0,
CS_TEAM_T = 1,
CS_TEAM_CT = 2,
CS_TEAM_SPECTATOR = 3,
};
/**
* @endsection
*/
/**
* Counter-Strike armor types for use with cs_[get|set]_user_armor().
*/
enum CsArmorType
{
CS_ARMOR_NONE = 0, // no armor
CS_ARMOR_KEVLAR = 1, // body vest only
CS_ARMOR_VESTHELM = 2, // vest and helmet
};
/**
* Map zone flags returned by cs_get_user_mapzones().
*/
#define CS_MAPZONE_BUY (1<<0) // Buyzone
#define CS_MAPZONE_BOMBTARGET (1<<1) // Bomb target zone
#define CS_MAPZONE_HOSTAGE_RESCUE (1<<2) // Hostage rescue zone
#define CS_MAPZONE_ESCAPE (1<<3) // Terrorist escape zone
#define CS_MAPZONE_VIP_SAFETY (1<<4) // VIP escape zone
/**
* Constants used for cs_[get|set]_user_zoom().
*/
enum
{
CS_RESET_ZOOM = 0, // Reset any zoom blocking (mode has no effect)
CS_SET_NO_ZOOM, // Disable any sort of zoom
CS_SET_FIRST_ZOOM, // Set first zoom level (AWP style)
CS_SET_SECOND_ZOOM, // Set second zoom level (AWP style)
CS_SET_AUGSG552_ZOOM, // Set AUG/SG552 zoom style
};
/**
* Constants used for the CS_OnBuy() and CS_OnBuyAttempt() forwards.
*
* @note While these mostly overlap with the CSW_* constants the CSI_* constants
* contain custom AMXX values that do not correspond to any real value in
* the game. The CSI_* constants should therefore be used for consistency.
*/
#define CSI_NONE CSW_NONE
#define CSI_P228 CSW_P228
#define CSI_GLOCK CSW_GLOCK // Unused by game, See CSI_GLOCK18.
#define CSI_SCOUT CSW_SCOUT
#define CSI_HEGRENADE CSW_HEGRENADE
#define CSI_XM1014 CSW_XM1014
#define CSI_C4 CSW_C4
#define CSI_MAC10 CSW_MAC10
#define CSI_AUG CSW_AUG
#define CSI_SMOKEGRENADE CSW_SMOKEGRENADE
#define CSI_ELITE CSW_ELITE
#define CSI_FIVESEVEN CSW_FIVESEVEN
#define CSI_UMP45 CSW_UMP45
#define CSI_SG550 CSW_SG550
#define CSI_GALIL CSW_GALIL
#define CSI_FAMAS CSW_FAMAS
#define CSI_USP CSW_USP
#define CSI_GLOCK18 CSW_GLOCK18
#define CSI_AWP CSW_AWP
#define CSI_MP5NAVY CSW_MP5NAVY
#define CSI_M249 CSW_M249
#define CSI_M3 CSW_M3
#define CSI_M4A1 CSW_M4A1
#define CSI_TMP CSW_TMP
#define CSI_G3SG1 CSW_G3SG1
#define CSI_FLASHBANG CSW_FLASHBANG
#define CSI_DEAGLE CSW_DEAGLE
#define CSI_SG552 CSW_SG552
#define CSI_AK47 CSW_AK47
#define CSI_KNIFE CSW_KNIFE
#define CSI_P90 CSW_P90
#define CSI_SHIELDGUN CSW_SHIELDGUN // The real CS value, use CSI_SHELD instead.
#define CSI_VEST CSW_VEST // Custom
#define CSI_VESTHELM CSW_VESTHELM // Custom
#define CSI_DEFUSER 33 // Custom
#define CSI_NVGS 34 // Custom
#define CSI_SHIELD 35 // Custom - The value passed by the forward, more convenient for plugins.
#define CSI_PRIAMMO 36 // Custom
#define CSI_SECAMMO 37 // Custom
#define CSI_MAX_COUNT 38
#define CSI_LAST_WEAPON CSW_LAST_WEAPON
#define CSI_ALL_WEAPONS CSW_ALL_WEAPONS
#define CSI_ALL_PISTOLS CSW_ALL_PISTOLS
#define CSI_ALL_SHOTGUNS CSW_ALL_SHOTGUNS
#define CSI_ALL_SMGS CSW_ALL_SMGS
#define CSI_ALL_RIFLES CSW_ALL_RIFLES
#define CSI_ALL_SNIPERRIFLES CSW_ALL_SNIPERRIFLES
#define CSI_ALL_MACHINEGUNS CSW_ALL_MACHINEGUNS
#define CSI_ALL_GRENADES CSW_ALL_GRENADES
#define CSI_ALL_ARMORS CSW_ALL_ARMORS
#define CSI_ALL_GUNS CSW_ALL_GUNS
/**
* Player's movements constants.
*/
#define CS_PLAYER_FATAL_FALL_SPEED 1100.0
#define CS_PLAYER_MAX_SAFE_FALL_SPEED 500.0
#define CS_DAMAGE_FOR_FALL_SPEED 100.0 / (CS_PLAYER_FATAL_FALL_SPEED - CS_PLAYER_MAX_SAFE_FALL_SPEED)
#define CS_PLAYER_MIN_BOUNCE_SPEED 350
#define CS_PLAYER_FALL_PUNCH_THRESHHOLD 250.0
/**
* Hint message flags for use with m_flDisplayHistory.
*/
#define CS_HINT_ROUND_STARTED (1<<1)
#define CS_HINT_HOSTAGE_SEEN_FAR (1<<2)
#define CS_HINT_HOSTAGE_SEEN_NEAR (1<<3)
#define CS_HINT_HOSTAGE_USED (1<<4)
#define CS_HINT_HOSTAGE_INJURED (1<<5)
#define CS_HINT_HOSTAGE_KILLED (1<<6)
#define CS_HINT_FRIEND_SEEN (1<<7)
#define CS_HINT_ENEMY_SEEN (1<<8)
#define CS_HINT_FRIEND_INJURED (1<<9)
#define CS_HINT_FRIEND_KILLED (1<<10)
#define CS_HINT_ENEMY_KILLED (1<<11)
#define CS_HINT_BOMB_RETRIEVED (1<<12)
#define CS_HINT_AMMO_EXHAUSTED (1<<15)
#define CS_HINT_IN_TARGET_ZONE (1<<16)
#define CS_HINT_IN_RESCUE_ZONE (1<<17)
#define CS_HINT_IN_ESCAPE_ZONE (1<<18)
#define CS_HINT_IN_VIPSAFETY_ZONE (1<<19)
#define CS_HINT_NIGHTVISION (1<<20)
#define CS_HINT_HOSTAGE_CTMOVE (1<<21)
#define CS_HINT_SPEC_DUCK (1<<22)
/**
* Constants for use with m_iIgnoreGlobalChat (ignoremsg client's command)
*/
#define CS_IGNOREMSG_NONE 0
#define CS_IGNOREMSG_ENEMY 1
#define CS_IGNOREMSG_TEAM 2
/**
* Player's gait animation constants.
*/
enum CsPlayerAnim
{
CS_PLAYER_IDLE = 0,
CS_PLAYER_WALK = 1,
CS_PLAYER_JUMP = 2,
CS_PLAYER_SUPERJUMP = 3,
CS_PLAYER_DIE = 4,
CS_PLAYER_ATTACK1 = 5,
CS_PLAYER_ATTACK2 = 6,
CS_PLAYER_FLINCH = 7,
CS_PLAYER_LARGE_FLINCH = 8,
CS_PLAYER_RELOAD = 9,
CS_PLAYER_HOLDBOMB = 10,
};
/**
* Player's menu states for use with m_iMenu.
*/
enum CsMenu
{
CS_Menu_OFF = 0,
CS_Menu_ChooseTeam = 1,
CS_Menu_IGChooseTeam = 2,
CS_Menu_ChooseAppearance = 3,
CS_Menu_Buy = 4,
CS_Menu_BuyPistol = 5,
CS_Menu_BuyRifle = 6,
CS_Menu_BuyMachineGun = 7,
CS_Menu_BuyShotgun = 8,
CS_Menu_BuySubMachineGun = 9,
CS_Menu_BuyItem = 10,
CS_Menu_Radio1 = 11,
CS_Menu_Radio2 = 12,
CS_Menu_Radio3 = 13,
CS_Menu_ClientBuy = 14,
};
/**
* Player's join states for use with m_iJoiningState.
*/
enum CsJoinState
{
CS_STATE_JOINED = 0,
CS_STATE_SHOW_LTEXT = 1,
CS_STATE_READING_LTEXT = 2,
CS_STATE_SHOW_TEAM_SELECT = 3,
CS_STATE_PICKING_TEAM = 4,
CS_STATE_GET_INTO_GAME = 5,
};
/**
* Player's throw direction on killed for use with m_iThrowDirection.
*/
enum CsThrowDirection
{
CS_THROW_NONE = 0,
CS_THROW_FORWARD = 1,
CS_THROW_BACKWARD = 2,
CS_THROW_HITVEL = 3,
CS_THROW_BOMB = 4,
CS_THROW_GRENADE = 5,
CS_THROW_HITVEL_MINUS_AIRVEL = 6,
};
/**
* @section Player's status bar constants.
*/
/**
* Constants associated with mp_playerid server cvar.
*/
#define CS_PLAYERID_EVERYONE 0
#define CS_PLAYERID_TEAMONLY 1
#define CS_PLAYERID_OFF 2
/**
* Maximum range a status bar can be displayed.
*/
#define CS_MAX_ID_RANGE 2048
#define CS_MAX_SPECTATOR_ID_RANGE 8192
/**
* Maximum buffer length of a status bar message.
*/
#define CS_SBAR_STRING_SIZE 128
/**
* Constants associated to CS_SBAR_ID_TARGETTYPE.
*/
#define CS_SBAR_TARGETTYPE_TEAMMATE 1
#define CS_SBAR_TARGETTYPE_ENEMY 2
#define CS_SBAR_TARGETTYPE_HOSTAGE 3
/**
* Status bar states.
*/
enum CsStatusBar
{
CS_SBAR_ID_TARGETTYPE = 1,
CS_SBAR_ID_TARGETNAME = 2,
CS_SBAR_ID_TARGETHEALTH = 3,
};
/**
* @endsection
*/
/**
* Weapon slot types.
*/
#define CS_WEAPONSLOT_PRIMARY 1
#define CS_WEAPONSLOT_SECONDARY 2
#define CS_WEAPONSLOT_KNIFE 3
#define CS_WEAPONSLOT_GRENADE 4
#define CS_WEAPONSLOT_C4 5
/**
* Weapon class types.
*/
enum CsWeaponClassType
{
CS_WEAPONCLASS_NONE = 0,
CS_WEAPONCLASS_KNIFE = 1,
CS_WEAPONCLASS_PISTOL = 2,
CS_WEAPONCLASS_GRENADE = 3,
CS_WEAPONCLASS_SUBMACHINEGUN = 4,
CS_WEAPONCLASS_SHOTGUN = 5,
CS_WEAPONCLASS_MACHINEGUN = 6,
CS_WEAPONCLASS_RIFLE = 7,
CS_WEAPONCLASS_SNIPERRIFLE = 8,
};
/**
* Weapon autobuy class types.
*/
enum CsAutoBuyClassType
{
CS_AUTOBUYCLASS_PRIMARY = (1<<0),
CS_AUTOBUYCLASS_SECONDARY = (1<<1),
CS_AUTOBUYCLASS_AMMO = (1<<2),
CS_AUTOBUYCLASS_ARMOR = (1<<3),
CS_AUTOBUYCLASS_DEFUSER = (1<<4),
CS_AUTOBUYCLASS_PISTOL = (1<<5),
CS_AUTOBUYCLASS_SMG = (1<<6),
CS_AUTOBUYCLASS_RIFLE = (1<<7),
CS_AUTOBUYCLASS_SNIPERRIFLE = (1<<8),
CS_AUTOBUYCLASS_SHOTGUN = (1<<9),
CS_AUTOBUYCLASS_MACHINEGUN = (1<<10),
CS_AUTOBUYCLASS_GRENADE = (1<<11),
CS_AUTOBUYCLASS_NIGHTVISION = (1<<12),
CS_AUTOBUYCLASS_SHIELD = (1<<13),
};
/**
* Ammo types for use with cs_get_weapon_info().
*/
enum CsAmmoType
{
CS_AMMO_BUCKSHOT = 0,
CS_AMMO_9MM = 1,
CS_AMMO_556NATO = 2,
CS_AMMO_556NATOBOX = 3,
CS_AMMO_762NATO = 4,
CS_AMMO_45ACP = 5,
CS_AMMO_50AE = 6,
CS_AMMO_338MAGNUM = 7,
CS_AMMO_57MM = 8,
CS_AMMO_357SIG = 9,
};
/**
* Weapon info types for use with cs_get_weapon_info().
*/
enum CsWeaponInfo
{
CS_WEAPONINFO_COST = 0,
CS_WEAPONINFO_CLIP_COST = 1,
CS_WEAPONINFO_BUY_CLIP_SIZE = 2,
CS_WEAPONINFO_GUN_CLIP_SIZE = 3,
CS_WEAPONINFO_MAX_ROUNDS = 4,
CS_WEAPONINFO_AMMO_TYPE = 5,
};
/**
* Weapon default cost.
*/
enum CsWeaponCostType
{
CS_AK47_PRICE = 2500,
CS_AWP_PRICE = 4750,
CS_DEAGLE_PRICE = 650,
CS_G3SG1_PRICE = 5000,
CS_SG550_PRICE = 4200,
CS_GLOCK18_PRICE = 400,
CS_M249_PRICE = 5750,
CS_M3_PRICE = 1700,
CS_M4A1_PRICE = 3100,
CS_AUG_PRICE = 3500,
CS_MP5NAVY_PRICE = 1500,
CS_P228_PRICE = 600,
CS_P90_PRICE = 2350,
CS_UMP45_PRICE = 1700,
CS_MAC10_PRICE = 1400,
CS_SCOUT_PRICE = 2750,
CS_SG552_PRICE = 3500,
CS_TMP_PRICE = 1250,
CS_USP_PRICE = 500,
CS_ELITE_PRICE = 800,
CS_FIVESEVEN_PRICE = 750,
CS_XM1014_PRICE = 3000,
CS_GALIL_PRICE = 2000,
CS_FAMAS_PRICE = 2250,
CS_SHIELDGUN_PRICE = 2200
};
/**
* Equipment default cost.
*/
enum CsItemCostType
{
CS_ASSAULTSUIT_PRICE = 1000,
CS_FLASHBANG_PRICE = 200,
CS_HEGRENADE_PRICE = 300,
CS_SMOKEGRENADE_PRICE = 300,
CS_KEVLAR_PRICE = 650,
CS_HELMET_PRICE = 350,
CS_NVG_PRICE = 1250,
CS_DEFUSEKIT_PRICE = 200
};
/**
* Ammo default cost.
*/
enum CsAmmoCostType
{
CS_AMMO_338MAG_PRICE = 125,
CS_AMMO_357SIG_PRICE = 50,
CS_AMMO_45ACP_PRICE = 25,
CS_AMMO_50AE_PRICE = 40,
CS_AMMO_556NATO_PRICE = 60,
CS_AMMO_57MM_PRICE = 50,
CS_AMMO_762NATO_PRICE = 80,
CS_AMMO_9MM_PRICE = 20,
CS_AMMO_BUCKSHOT_PRICE = 65
};
/**
* Weapon state for use with m_iWeaponState.
*/
#define CS_WPNSTATE_USP_SILENCED (1<<0)
#define CS_WPNSTATE_GLOCK18_BURST_MODE (1<<1)
#define CS_WPNSTATE_M4A1_SILENCED (1<<2)
#define CS_WPNSTATE_ELITE_LEFT (1<<3)
#define CS_WPNSTATE_FAMAS_BURST_MODE (1<<4)
#define CS_WPNSTATE_SHIELD_DRAWN (1<<5)
/**
* Internal commands, for use with m_flLastCommandTime.
*/
#define CS_CMD_SAY 0
#define CS_CMD_SAYTEAM 1
#define CS_CMD_FULLUPDATE 2
#define CS_CMD_VOTE 3
#define CS_CMD_VOTEMAP 4
#define CS_CMD_LISTMAPS 5
#define CS_CMD_LISTPLAYERS 6
#define CS_CMD_NIGHTVISION 7
/**
* Signal state for use with m_signals.
*/
#define CS_SIGNAL_BUY (1<<0)
#define CS_SIGNAL_BOMB (1<<1)
#define CS_SIGNAL_RESCUE (1<<2)
#define CS_SIGNAL_ESCAPE (1<<3)
#define CS_SIGNAL_VIPSAFETY (1<<4)

View File

@ -0,0 +1,259 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// CSX Functions
//
#if defined _csx_included
#endinput
#endif
#define _csx_included
#include <csstats>
#pragma reqclass xstats
#if !defined AMXMODX_NOAUTOLOAD
#pragma defclasslib xstats csx
#endif
/**
* Map objective flags returned by get_map_objectives().
*/
enum MapObjective
{
MapObjective_Bomb = (1<<0),
MapObjective_Hostage = (1<<1),
MapObjective_Vip = (1<<2),
MapObjective_Escape = (1<<3),
};
/**
* Called after a client attacks another client.
*
* @note For a list of possible weapon ids see the CSW_* constants in
* amxconst.inc
* @note For a list of possible body hitplaces see the HIT_* constants in
* amxconst.inc
*
* @param attacker Attacker client index
* @param victim Victim client index
* @param damage Damage dealt to victim
* @param wpnindex Weapon id
* @param hitplace Body hitplace
* @param ta If nonzero the attack was a team attack
*
* @noreturn
*/
forward client_damage(attacker, victim, damage, wpnindex, hitplace, TA);
/**
* Called after a client death.
*
* @note For a list of possible weapon ids see the CSW_* constants in
* amxconst.inc
* @note For a list of possible body hitplaces see the HIT_* constants in
* amxconst.inc
*
* @param attacker Attacker client index
* @param victim Victim client index
* @param wpnindex Weapon id
* @param hitplace Body hitplace
* @param tk If nonzero the death was a teamkill
*
* @noreturn
*/
forward client_death(killer, victim, wpnindex, hitplace, TK);
/**
* Called after a grenade was thrown.
*
* @note Weapon id is one of CSW_HEGRENADE, CSW_SMOKEGRENADE or CSW_FLASHBANG.
*
* @param index Client index
* @param greindex Grenade entity index
* @param wId Weapon id
*
* @noreturn
*/
forward grenade_throw(index, greindex, wId);
/**
* Called after a bomb plant attempt has started.
*
* @param planter Planter client index
*
* @noreturn
*/
forward bomb_planting(planter);
/**
* Called after a bomb plant has finished.
*
* @param planter Planter client index
*
* @noreturn
*/
forward bomb_planted(planter);
/**
* Called when the bomb exploded.
*
* @param planter Planter client index
* @param defuser Defuser client index, if applicable
*
* @noreturn
*/
forward bomb_explode(planter, defuser);
/**
* Called after a bomb defuse attempt has started.
*
* @param defuser Defuser client index
*
* @noreturn
*/
forward bomb_defusing(defuser);
/**
* Called after a bomb defuse has finished.
*
* @param defuser Defuser client index
*
* @noreturn
*/
forward bomb_defused(defuser);
/**
* @section Shared natives
*/
/**
* Adds a custom weapon to the stats system.
*
* @note The weapon name should be the full display name of the gun such as
* "Desert Eagle" while the logname should be "weapon_deagle".
*
* @param wpnname Full weapon name
* @param melee If nonzero the weapon will be considered a melee weapon
* @param logname Weapon short name
*
* @return Cusom weapon id (>0) on success, 0 if no more custom weapons
* can be added
*/
native custom_weapon_add(const wpnname[], melee = 0, const logname[] = "");
/**
* Triggers a damage event on a custom weapon, adding it to the internal stats.
*
* @note This will also call the client_damage() and client_kill() forwards if
* applicable.
* @note For a list of possible body hitplaces see the HIT_* constants in
* amxconst.inc
*
* @param weapon Custom weapon id
* @param att Attacker client index
* @param vic Victim client index
* @param damage Damage dealt
* @param hitplace Optional body hitplace
*
* @noreturn
* @error If the weapon id is not a custom weapon, an invalid client
* index, damage value or hitplace is provided, an error will
* be thrown.
*/
native custom_weapon_dmg(weapon, att, vic, damage, hitplace = 0);
/**
* Adds a shot event on a custom weapon to the internal stats.
*
* @param weapon Custom weapon id
* @param index Client index
*
* @noreturn
* @error If the weapon id is not a custom weapon or an invalid client
* index is provided, an error will be thrown.
*/
native custom_weapon_shot(weapon, index);
/**
* Returns if the weapon is considered a melee weapon.
*
* @note For a list of default CS weapon ids see the CSW_* constants in
* amxconst.inc, this function also works on custom weapons.
* @note For the default CS weapons this obviously returns true only for
* CSW_KNIFE.
*
* @param wpnindex Weapon id
*
* @return 1 if weapon is a melee weapon, 0
* @error If an invalid weapon id is provided an error will be thrown.
*/
native xmod_is_melee_wpn(wpnindex);
/**
* Retrieves the full weapon name of a weapon id.
*
* @note For a list of default CS weapon ids see the CSW_* constants in
* amxconst.inc, this function also works on custom weapons.
* @note For the default CS weapons this obviously returns true only for
* CSW_KNIFE.
*
* @param wpnindex Weapon id
* @param name Buffer to copy weapon name to
* @param len Maximmum buffer size
*
* @return Number of cells written to buffer
* @error If an invalid weapon id is provided an error will be thrown.
*/
native xmod_get_wpnname(wpnindex, name[], len);
/**
* Retrieves the weapon log name of a weapon id.
*
* @note For a list of default CS weapon ids see the CSW_* constants in
* amxconst.inc, this function also works on custom weapons.
* @note For the default CS weapons this obviously returns true only for
* CSW_KNIFE.
*
* @param wpnindex Weapon id
* @param name Buffer to copy weapon log name to
* @param len Maximmum buffer size
*
* @return Number of cells written to buffer
* @error If an invalid weapon id is provided an error will be thrown.
*/
native xmod_get_wpnlogname(wpnindex, name[], len);
/**
* Returns the maximum amount of weapons that the stats system supports.
*
* @return Maximum number of weapons supported
*/
native xmod_get_maxweapons();
/**
* Returns the number of stats tracked by the stats system.
*
* @return Number of stats tracked
*/
native xmod_get_stats_size();
/**
* @endsection Shared natives
*/
/**
* Returns the current map's objectives as a bitflag value.
*
* @note For a list of possible map objective flags see the MapObjective enum.
*
* @return Bitflag value of map objectives
*/
native MapObjective:get_map_objectives();

View File

@ -0,0 +1,203 @@
#if defined _curl_included
#endinput
#endif
#define _curl_included
#include <curl_consts>
#if AMXX_VERSION_NUM >= 175
#pragma reqlib curl
#if !defined AMXMODX_NOAUTOLOAD
#pragma loadlib curl
#endif
#else
#pragma library curl
#endif
enum _:curl_off_t {
curl_off_left,
curl_off_right
};
enum curl_slist
{
SList_Empty
};
/**
* This function converts the given input string to a 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).
* see also https://curl.haxx.se/libcurl/c/curl_easy_escape.html
*
* @param handle Curl handle
* @param url URL for encoding
* @param buffer Buffer to copy encoded url
* @param maxlen Maximum size of the buffer
*
* @noreturn
* @error If passed curl handle is not a valid
*/
native curl_easy_escape(const CURL:handle, const url[], buffer[], const maxlen);
/**
* This function converts the given URL encoded input 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.
* see also https://curl.haxx.se/libcurl/c/curl_easy_unescape.html
*
* @param handle Curl handle
* @param url URL for decoding
* @param buffer Buffer to copy decoded url
* @param maxlen Maximum size of the buffer
*
* @noreturn
* @error If passed curl handle is not a valid
*/
native curl_easy_unescape(const CURL: handle, const url[], buffer[], const maxlen);
/**
* This function must be the first function to call, and it returns a CURL easy handle that you must
* use as input to other functions in the easy interface. This call MUST have a corresponding call to curl_easy_cleanup
* when the operation is complete.
* see also https://curl.haxx.se/libcurl/c/curl_easy_init.html
*
* @return Curl handle
*/
native CURL: curl_easy_init();
/**
* Invoke this function after curl_easy_init and all the curl_easy_setopt calls are made, and will perform the transfer as described in the options.
* It must be called with the same curl handle as input as the curl_easy_init call returned.
* You can do any amount of calls to curl_easy_perform while using the same curl handle. If you intend to transfer more than one file, you are even
* encouraged to do so. libcurl will then attempt to re-use the same connection for the following transfers, thus making the operations faster,
* less CPU intense and using less network resources. Just note that you will have to use curl_easy_setopt between the invokes to set options
* for the following curl_easy_perform.
* see also https://curl.haxx.se/libcurl/c/curl_easy_perform.html
*
* @param handle Curl handle
* @param callback The forward to call after request completed
* @param data Any data to pass to the callback forward
* @param len Maximum size of the data
*
* @noreturn
* @error If passed curl handle is not a valid or or undefined callback function
*/
native curl_easy_perform(const CURL: handle, const callback[], const data[] = {}, const len = 0);
/**
* This function is used to tell libcurl how to behave. By setting the appropriate options, the application can change libcurl's behavior.
* All options are set with an option followed by a parameter. That parameter can be a long, a function pointer, an object pointer or a curl_off_t,
* depending on what the specific option expects. Read this manual carefully as bad input values may cause libcurl to behave badly!
* You can only set one option in each function call. A typical application uses many curl_easy_setopt calls in the setup phase.
* Options set with this function call are valid for all forthcoming transfers performed using this handle. The options are not in any way reset between
* transfers, so if you want subsequent transfers with different options, you must change them between the transfers. You can optionally reset all options
* back to internal default with curl_easy_reset.
* see also https://curl.haxx.se/libcurl/c/curl_easy_setopt.html
*
* @param handle Curl handle
* @param option Necessary option (see CURLoption enum)
*
* @return If the operation was successful, CURLE_OK is returned. Otherwise an appropriate error code will be returned.
* @error If passed curl handle is not a valid or or undefined option
*/
native CURLcode: curl_easy_setopt(const CURL: handle, const CURLoption: option, any: ...);
/**
* This function must be the last function to call for an easy session. It is the opposite of the curl_easy_init function and must be called
* with the same handle as input that a curl_easy_init call returned.
* This might close all connections this handle has used and possibly has kept open until now - unless it was attached to a multi handle while
* doing the transfers. Don't call this function if you intend to transfer more files, re-using handles is a key to good performance with libcurl.
* see also https://curl.haxx.se/libcurl/c/curl_easy_cleanup.html
*
* @param handle Curl handle
*
* @noreturn
* @error If passed curl handle is not a valid
*/
native curl_easy_cleanup(const CURL: handle);
/**
* Re-initializes all options previously set on a specified CURL handle to the default values. This puts back the handle to the same state as it
* was in when it was just created with curl_easy_init.
* It does not change the following information kept in the handle: live connections, the Session ID cache, the DNS cache, the cookies and shares.
* see also https://curl.haxx.se/libcurl/c/curl_easy_reset.html
*
* @param handle Curl handle
*
* @noreturn
* @error If passed curl handle is not a valid
*/
native curl_easy_reset(const CURL: handle);
/**
* Request internal information from the curl session with this function. The third argument MUST be a buffer for value (num, string, float)
* The data pointed-to will be filled in accordingly and can be relied upon only if the function returns CURLE_OK. Use this function AFTER
* a performed transfer if you want to get transfer related data.
* see also https://curl.haxx.se/libcurl/c/curl_easy_getinfo.html
*
* @param handle Curl handle
* @param info Necessary info (see CURLINFO enum)
*
* @return If the operation was successful, CURLE_OK is returned. Otherwise an appropriate error code will be returned.
* @error If passed curl handle is not a valid or or undefined info
*/
native CURLcode: curl_easy_getinfo(const CURL: handle, const CURLINFO: info, any: ...);
/**
* The function receives a text description of the specified error code.
*
* @param code Error code (see CURLcode enum)
* @param buffer Buffer to copy error description
* @param maxlen Maximum size of the buffer
*
* @noreturn
*/
native curl_easy_strerror(const CURLcode: code, buffer[], const maxlen);
/**
* @deprecated This function does not catch all cases.
* #pragma deprecated This function is deprecated. Do not use!
*/
native CURLFORMcode: curl_formadd(&curl_httppost: first, &curl_httppost: last, any: ...);
/**
* @deprecated This function does not catch all cases.
* #pragma deprecated This function is deprecated. Do not use!
*/
native curl_formfree(&curl_httppost: first);
/**
* This function appends a string to a linked list of strings.
* The existing list should be passed as the first argument and the new list is returned from this function.
* Pass in SList_Empty (0) in the list argument to create a new list. The specified string has been appended when this function returns.
* see also https://curl.haxx.se/libcurl/c/curl_slist_append.html
*
* @param list Existing list
* @param string Some string
*
* @return A null pointer is returned if anything went wrong, otherwise the new list pointer is returned.
* To avoid overwriting an existing non-empty list on failure, the new list should be returned to a
* temporary variable which can be tested for SList_Empty (0) before updating the original list pointer
*/
native curl_slist: curl_slist_append(curl_slist: list, string[]);
/**
* This function removes all traces of a previously built curl_slist linked list.
* see also https://curl.haxx.se/libcurl/c/curl_slist_free_all.html
*
* @param list Existing list
*
* @noreturn
*/
native curl_slist_free_all(curl_slist: list);
/**
* Returns a human readable string with the version number of libcurl and some of its important components (like OpenSSL version).
* see also https://curl.haxx.se/libcurl/c/curl_version.html
*
* @param buffer Buffer to copy string with the version number
* @param maxlen Maximum size of the buffer
*
* @noreturn
*/
native curl_version(buffer[], const maxlen);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,547 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
#if defined _cvars_included
#endinput
#endif
#define _cvars_included
/**
* CVAR flags for create_cvar() and register_cvar().
*/
#define FCVAR_NONE 0 // No special behavior
#define FCVAR_ARCHIVE 1 // Cvar will be saved to vars.rc Set to cause it to be saved to vars.rc
#define FCVAR_USERINFO 2 // Cvar changes the client's info string
#define FCVAR_SERVER 4 // Clients get notified when cvar value is changed
#define FCVAR_EXTDLL 8 // Defined by an external DLL
#define FCVAR_CLIENTDLL 16 // Defined by the client DLL
#define FCVAR_PROTECTED 32 // Cvar value is masked from outside access, should be used for sensitive cvars like passwords
#define FCVAR_SPONLY 64 // Cvar can't be changed by clients connected to a multiplayer server
#define FCVAR_PRINTABLEONLY 128 // The cvar string value can not contain unprintable characters
#define FCVAR_UNLOGGED 256 // If the cvar is FCVAR_SERVER, don't log changes to a file/the console
#define FCVAR_NOEXTRAWHITEPACE 512 // Automatically strips trailing/leading white space from the string value
/**
* Cvar bound constants used with [get|set]_pcvar_bounds().
*/
enum CvarBounds
{
CvarBound_Upper = 0,
CvarBound_Lower
};
/**
* Creates a new cvar for the engine.
*
* @note This has the same effect as register_cvar() but provides more options.
* @note For a list of possible cvar flags see FCVAR_* constants above.
* @note If an already existing cvar is registered it will not be duplicated.
* The default value is only set when the cvar is registered for the very
* first time since the server was started. Cvar bounds are overwritten
* by the create_cvar() call just as if they were re-set using
* set_pcvar_bounds().
* @note The returned cvar pointer should be used with the get_pcvar_* and
* set_pcvar_* set of functions.
*
* @param name Cvar name
* @param string Default cvar value
* @param flags Optional bitsum of flags specifying cvar behavior
* @param description Optional description of the cvar
* @param has_min Optional boolean that specifies if the cvar has a
* minimum value
* @param min_val Minimum floating point value
* @param has_max Optional boolean that specifies if the cvar has a
* maximum value
* @param max_val Maximum floating point value
*
* @return Unique cvar pointer
* @error If invalid bounds are provided (min_val > max_val or
* vice versa), an error will be thrown.
*/
native create_cvar(const name[], const string[], flags = FCVAR_NONE, const description[] = "", bool:has_min = false, Float:min_val = 0.0, bool:has_max = false, Float:max_val = 0.0);
/**
* Registers a new cvar for the engine.
*
* @note Deprecated. Consider to use create_cvar for more options.
* @note For a list of possible cvar flags see FCVAR_* constants in cvars.inc
* @note If an already existing cvar is registered it will not be duplicated.
* The default value is only set when the cvar is registered for the very
* first time since the server was started.
* @note The returned cvar pointer should be used with the get_pcvar_* and
* set_pcvar_* set of functions.
*
* @param name Cvar name
* @param string Default cvar value
* @param flags Optional bitsum of flags specifying cvar behavior
* @param fvalue Unused
*
* @return Unique cvar pointer
*/
native register_cvar(const name[], const string[], flags = FCVAR_NONE, Float:fvalue = 0.0);
/**
* Returns if a cvar is registered on the server.
*
* @param cvar Cvar name to check
*
* @return 1 if the cvar exists, 0 otherwise
*/
native cvar_exists(const cvar[]);
/**
* Returns the cvar pointer of the specified cvar.
*
* @note A pointer is also returned by register_cvar() and create_cvar().
* Plugins can (and should) retrieve and use pointers for already existing
* mod cvars.
*
* @param cvar Cvar name to find
*
* @return Cvar pointer on success, 0 if cvar was not found
*/
native get_cvar_pointer(const cvar[]);
/**
* Creates a hook for when a cvar's value is changed.
*
* @note Changing the cvar value from within this forward can lead to infinite
* recursion and should be avoided.
* @note The callback will be called in the following manner:
*
* public cvar_change_callback(pcvar, const old_value[], const new_value[])
*
* pcvar - Pointer to cvar that was changed
* old_value - Buffer containing the previous value of the cvar
* new_value - Buffer containing the new value of the cvar
*
* The return value is ignored
*
* @param pcvar Pointer to cvar
* @param callback Name of callback function
*
* @return Callback handle that can be used with
* [disable|enable]_cvar_hook
* @error If an invalid cvar pointer or callback function is provided,
* an error will be thrown.
*/
native cvarhook:hook_cvar_change(pcvar, const callback[]);
/**
* Disables a cvar hook, stopping it from being called.
*
* @note Use the handle returned by hook_cvar_change as the parameter here.
*
* @param handle Forward to disable
* @error If an invalid hook handle is provided, an error will be
* thrown.
*/
native disable_cvar_hook(cvarhook:handle);
/**
* Enables a cvar hook, restoring it to being called.
*
* @note Use the handle returned by hook_cvar_change as the parameter here.
*
* @param handle Forward to enable
* @error If an invalid hook handle is provided, an error will be
* thrown.
*/
native enable_cvar_hook(cvarhook:handle);
/**
* Returns flags of a cvar. The cvar is accessed by name.
*
* @note For a list of possible flags see the FCVAR_* constants in amxconst.inc
* @note Accessing a Cvar by name is slower than direct pointer access, which is
* why the otherwise equivalent get_pcvar_flags() function should be used
* instead.
*
* @param cvar Cvar name to retrieve flags from
*
* @return Flag value
*/
native get_cvar_flags(const cvar[]);
/**
* Sets specified flags to a cvar. The cvar is accessed by name.
*
* @note Not permitted for the "amx_version", "amxmodx_version", "fun_version"
* and "sv_cheats" cvars.
* @note For a list of possible flags see the FCVAR_* constants in amxconst.inc
* @note This function just adds the flags using a bitwise-or operation. After
* it has run the flags may not exactly equal the specified bitflag sum.
* @note Accessing a Cvar by name is slower than direct pointer access, which is
* why the otherwise equivalent set_pcvar_flags() function should be used
* instead.
*
* @param cvar Cvar name to remove flags from
* @param flags Bitflag sum of flags to set
*
* @return 1 on success, 0 if cvar does not exist or is not permitted
*/
native set_cvar_flags(const cvar[], flags);
/**
* Removes specified flags from a cvar. The cvar is accessed by name.
*
* @note Not permitted for the "amx_version", "amxmodx_version", "fun_version"
* and "sv_cheats" cvars.
* @note For a list of possible flags see the FCVAR_* constants in amxconst.inc
* @note This function removes the flags using a bitwise-and operation.
* @note Accessing a Cvar by name is slower than direct pointer access, which is
* why the set_pcvar_flags() function should be used instead.
*
* @param cvar Cvar name to remove flags from
* @param flags Bitflag sum of flags to remove
*
* @return 1 on success, 0 if cvar does not exist or is not permitted
*/
native remove_cvar_flags(const cvar[], flags=-1);
/**
* Gets a string value from a cvar. The cvar is accessed by name.
*
* @note Accessing a Cvar by name is slower than direct pointer access, which is
* why the otherwise equivalent get_pcvar_string() function should be used
* instead.
*
* @param cvar Cvar name to retrieve value from
* @param output Buffer to copy cvar value to
* @param iLen Maximum size of the buffer
*
* @return Number of cells written to buffer.
*/
native get_cvar_string(const cvarname[], output[], iLen);
/**
* Sets a cvar to a given string value. The cvar is accessed by name.
*
* @note Accessing a Cvar by name is slower than direct pointer access, which is
* why the otherwise equivalent set_pcvar_string() function should be used
* instead.
*
* @param cvar Cvar name to set value of
* @param value Value to set cvar to
*
* @noreturn
*/
native set_cvar_string(const cvar[], const value[]);
/**
* Returns a floating value from a cvar. The cvar is accessed by name.
*
* @note Accessing a Cvar by name is slower than direct pointer access, which is
* why the otherwise equivalent get_pcvar_float() function should be used
* instead.
*
* @param cvarname Cvar name to retrieve value from
*
* @return Cvar value, converted to float
*/
native Float:get_cvar_float(const cvarname[]);
/**
* Sets a cvar to a given float value. The cvar is accessed by name.
*
* @note Accessing a Cvar by name is slower than direct pointer access, which is
* why the otherwise equivalent set_pcvar_float() function should be used
* instead.
*
* @param cvar Cvar name to set value of
* @param value Value to set cvar to
*
* @noreturn
*/
native set_cvar_float(const cvar[], Float:value);
/**
* Returns an integer value from a cvar. The cvar is accessed by name.
*
* @note Accessing a Cvar by name is slower than direct pointer access, which is
* why the otherwise equivalent get_pcvar_num() function should be used
* instead.
*
* @param cvarname Cvar name to retrieve value from
*
* @return Cvar value, converted to int
*/
native get_cvar_num(const cvarname[]);
/**
* Sets a cvar to a given integer value. The cvar is accessed by name.
*
* @note Accessing a Cvar by name is slower than direct pointer access, which is
* why the otherwise equivalent set_pcvar_num() function should be used
* instead.
*
* @param cvar Cvar name to set value of
* @param value Value to set cvar to
*
* @noreturn
*/
native set_cvar_num(const cvarname[], value);
/**
* Returns flags of a cvar via direct pointer access.
*
* @note For a list of possible flags see the FCVAR_* constants in amxconst.inc
*
* @param pcvar Pointer to cvar to retrieve flags from
*
* @return 1 on success, 0 if cvar pointer is invalid
* @error If an invalid cvar pointer is provided, an error will be
* thrown.
*/
native get_pcvar_flags(pcvar);
/**
* Sets specified flags to a cvar via direct pointer access.
*
* @note For a list of possible flags see the FCVAR_* constants in amxconst.inc
* @note This function directly sets the provided bitflag, unlike set_cvar_flags
* which adds them using a bitwise OR.
*
* @param pcvar Pointer to cvar to set flags of
* @param flags Bitflag sum of flags to set
*
* @return 1 on success, 0 if cvar does not exist or is not permitted
* @error If an invalid cvar pointer is provided, an error will be
* thrown.
*/
native set_pcvar_flags(pcvar, flags);
/**
* Returns an integer value from a cvar via direct pointer access.
*
* @param pcvar Pointer to cvar to retrieve value from
*
* @return Cvar value, converted to int
* @error If an invalid cvar pointer is provided, an error will be
* thrown.
*/
native get_pcvar_num(pcvar);
/**
* Returns an boolean value from a cvar via direct pointer access.
*
* @param pcvar Pointer to cvar to retrieve value from
*
* @return Cvar value, converted to bool
* @error If an invalid cvar pointer is provided, an error will be
* thrown.
*/
native bool:get_pcvar_bool(pcvar);
/**
* Sets an integer value to a cvar via direct pointer access.
*
* @param pcvar Pointer to cvar to set value of
* @param num Value to set cvar to
*
* @noreturn
* @error If an invalid cvar pointer is provided, an error will be
* thrown.
*/
native set_pcvar_num(pcvar, num);
/**
* Sets a boolean value to a cvar via direct pointer access.
*
* @param pcvar Pointer to cvar to set value of
* @param num Value to set cvar to
*
* @noreturn
* @error If an invalid cvar pointer is provided, an error will be
* thrown.
*/
native set_pcvar_bool(pcvar, bool:num);
/**
* Returns a float value from a cvar via direct pointer access.
*
* @param pcvar Pointer to cvar to retrieve value from
*
* @return Cvar value, converted to float
* @error If an invalid cvar pointer is provided, an error will be
* thrown.
*/
native Float:get_pcvar_float(pcvar);
/**
* Sets a float value to a cvar via direct pointer access.
*
* @param pcvar Pointer to cvar to set value of
* @param num Value to set cvar to
*
* @noreturn
* @error If an invalid cvar pointer is provided, an error will be
* thrown.
*/
native set_pcvar_float(pcvar, Float:num);
/**
* Returns a string value from a cvar via direct pointer access.
*
* @param pcvar Pointer to cvar to retrieve value from
* @param string Buffer to copy cvar value to
* @param maxlen Maximum size of the buffer
*
* @return Number of cells written to buffer.
* @error If an invalid cvar pointer is provided, an error will be
* thrown.
*/
native get_pcvar_string(pcvar, string[], maxlen);
/**
* Sets a string value to a cvar via direct pointer access.
*
* @param pcvar Pointer to cvar to retrieve value from
* @param string Value to set cvar to
*
* @noreturn
* @error If an invalid cvar pointer is provided, an error will be
* thrown.
*/
native set_pcvar_string(pcvar, const string[]);
/**
* Retrieves the specified value boundary of a cvar.
*
* @param pcvar Pointer to cvar
* @param type Type of boundary to retrieve
* @param value Variable to store the specified boundary to
*
* @return True if the cvar has a boundary set, false otherwise
* @error If an invalid cvar pointer or boundary type is provided,
* an error will be thrown.
*/
native bool:get_pcvar_bounds(pcvar, CvarBounds:type, &Float:value);
/**
* Sets the specified boundary of a cvar.
*
* @param pcvar Pointer to cvar
* @param type Type of boundary to set
* @param set If true the cvar boundary will be set, otherwise it will be
* removed (value is ignored)
* @param value Floating point value to use as the boundary
*
* @noreturn
* @error If an invalid cvar pointer or boundary type is provided, an
* error will be thrown.
*/
native set_pcvar_bounds(pcvar, CvarBounds:type, bool:set, Float:value = 0.0);
/**
* Binds a cvar's integer value to a global variable. The variable will then
* always contain the current cvar value as it is automatically kept up to date.
*
* @note The variable *has* to be a global or a static variable. Local variables
* created within functions can not be used for technical reasons.
* @note Variables can not be bound to multiple cvars.
*
* @param pcvar Pointer to cvar
* @param var Global variable to keep updated
*
* @noreturn
* @error If an invalid cvar pointer or variable is provided, an error
* will be thrown.
*/
native bind_pcvar_num(pcvar, &any:var);
/**
* Binds a cvar's float value to a global variable. The variable will then
* always contain the current cvar value as it is automatically kept up to date.
*
* @note The variable *has* to be a global or a static variable. Local variables
* created within functions can not be used for technical reasons.
* @note Variables can not be bound to multiple cvars.
*
* @param pcvar Pointer to cvar
* @param var Global variable to keep updated
*
* @noreturn
* @error If an invalid cvar pointer or variable is provided, an error
* will be thrown.
*/
native bind_pcvar_float(pcvar, &Float:var);
/**
* Binds a cvar's string value to a global array. The array will then
* always contain the current cvar value as it is automatically kept up to date.
*
* @note The array *has* to be a global or a static array. Local arrays
* created within functions can not be used for technical reasons.
* @note Arrays can not be bound to multiple cvars.
*
* @param pcvar Pointer to cvar
* @param var Global array to keep updated
* @param varlen Maximum length of string array
*
* @noreturn
* @error If an invalid cvar pointer or variable is provided, an error
* will be thrown.
*/
native bind_pcvar_string(pcvar, any:var[], varlen);
/**
* Returns the number of plugin-registered cvars.
*
* @return Number of registered cvars
*/
native get_plugins_cvarsnum();
/**
* Retrieves information about a plugin-registered cvar via iterative access.
*
* @note The returned cvar pointer should be used with the get_pcvar_* and
* set_pcvar_* set of functions.
* @note The cvar index does not equal the cvar pointer. It is the internal
* AMXX id of a cvar, incremented for each registered cvar.
*
* @param num Index to retrieve
* @param name Buffer to copy cvar name to
* @param namelen Maximum buffer size
* @param flags Variable to store cvar flags to
* @param plugin_id Variable to store id of the registering plugin to
* @param pcvar_handle Variable to store cvar pointer to
* @param description Variable to store cvar description to
* @param desc_len Maximum length of string buffer
*
* @return 1 on success, 0 if index is invalid
*/
native get_plugins_cvar(num, name[], namelen, &flags = 0, &plugin_id = 0, &pcvar_handle = 0, description[] = "", desc_len = 0);
/**
* Dispatches a client cvar query, allowing the plugin to query for its value on
* the client.
*
* @note The callback will be called in the following manner:
*
* public cvar_query_callback(id, const cvar[], const value[], const param[])
*
* id - Client index
* cvar - Cvar queried
* value - Cvar value on the client
* param - Optional extra data
*
* @param id Client index
* @param cvar Cvar to query
* @param resultFunc Callback function
* @param paramlen Size of extra data
* @param params Extra data to pass through to callback
*
* @noreturn
* @error If the client index is not within the range of 1 to
* MaxClients, the client is not connected, the callback
* function is invalid or the querying process encounters
* a problem, an error will be thrown.
*/
native query_client_cvar(id, const cvar[], const resultFunc[], paramlen = 0, const params[] = "");

View File

@ -0,0 +1,161 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
#if defined _datapack_included
#endinput
#endif
#define _datapack_included
/**
* Datapack tag declaration
*
* @note Datapacks provide a way to store and move around arbitrary amounts (and
* types) of data in AMX Mox X. Data is packed into a single cell value -
* the DataPack handle. This handle can be passed around more easily, can
* be returned by functions and can simulate advanced concepts like string
* consummation.
* @note Plugins are responsible for freeing all datapack handles they acquire.
* Failing to free handles will result in the plugin and AMXX leaking
* memory.
*/
enum DataPack
{
Invalid_DataPack = 0
};
/**
* Creates a new datapack.
*
* @return New datapack handle, which must be freed via DestroyDataPack().
*/
native DataPack:CreateDataPack();
/**
* Packs a cell value into a datapack.
*
* @param pack Datapack handle
* @param cell Cell value to pack
*
* @noreturn
* @error If an invalid handle is provided, an error will be thrown.
*/
native WritePackCell(DataPack:pack, any:cell);
/**
* Packs a float value into a datapack.
*
* @param pack Datapack handle
* @param val Float value to pack
*
* @noreturn
* @error If an invalid handle is provided, an error will be thrown.
*/
native WritePackFloat(DataPack:pack, Float:val);
/**
* Packs a string into a datapack.
*
* @param pack Datapack handle
* @param str String to pack
*
* @return Length of copied string
* @error If an invalid handle is provided, an error will be thrown.
*/
native WritePackString(DataPack:pack, const str[]);
/**
* Reads a cell from a Datapack.
*
* @param pack Datapack handle
*
* @return Cell value
* @error If an invalid handle is provided, or not enough data is left
* in the datapack, an error will be thrown.
*/
native any:ReadPackCell(DataPack:pack);
/**
* Reads a float from a datapack.
*
* @param pack Datapack handle
*
* @return Float value
* @error If an invalid handle is provided, or not enough data is left
* in the datapack, an error will be thrown.
*/
native Float:ReadPackFloat(DataPack:pack);
/**
* Reads a string from a Datapack.
*
* @param pack Datapack handle
* @param buffer Buffer to copy string to
* @param maxlen Maximum size of buffer
*
* @return Number of cells written to buffer
* @error If an invalid handle is provided, or not enough data is left
* in the datapack, an error will be thrown.
*/
native ReadPackString(DataPack:pack, buffer[], maxlen);
/**
* Resets the datapack read/write position to the start.
*
* @param pack Datapack handle
* @param clear If true, clears the contained data
*
* @noreturn
* @error If an invalid handle is provided, an error will be thrown.
*/
native ResetPack(DataPack:pack, bool:clear = false);
/**
* Returns the datapack read/write position.
*
* @param pack Datapack handle
*
* @return Position in the datapack, only usable with calls to SetPackPosition
* @error If an invalid handle is provided, an error will be thrown.
*/
native DataPackPos:GetPackPosition(DataPack:pack);
/**
* Sets the datapack read/write position.
*
* @note This should only ever be used with (known to be valid) positions
* returned by GetPackPosition(). It is not possible for plugins to safely
* compute datapack positions.
*
* @param pack Datapack handle
* @param position New position to set
*
* @noreturn
* @error If an invalid handle is provided, or the new position is
* out of datapack bounds, an error will be thrown.
*/
native SetPackPosition(DataPack:pack, DataPackPos:position);
/**
* Returns if the datapack has reached its end and no more data can be read.
*
* @param pack Datapack handle
*
* @return True if datapack has reached the end, false otherwise
* @error If an invalid handle is provided, an error will be thrown.
*/
native bool:IsPackEnded(DataPack:pack);
/**
* Destroys the datapack and frees its memory.
*
* @param pack Datapack handle
*
* @return True if disposed, false otherwise
*/
native DestroyDataPack(&DataPack:pack);

View File

@ -0,0 +1,154 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// SQL Database API
//
//
// Notes - Read the comments! Make sure your plugins use
// nice ANSI SQL and don't use database column names like "key"
// otherwise this API will be a nightmare
//
// Never do error checking with the not operator! This is bad:
// if (!dbi_query())
// You should do:
// ret = dbi_query()
// if (ret < 0)
// This is because DBI functions can and will return negative numbers
// Negative numbers evaluate to "true" in AMX.
//
#if defined _dbi_included
#endinput
#endif
#define _dbi_included
// You can't include SQLX first!
// there's really no reason to anyway.
#assert !defined _sqlx_included
#pragma reqclass dbi
enum Sql
{
SQL_FAILED=0,
SQL_OK
};
enum Result
{
RESULT_FAILED=-1,
RESULT_NONE,
RESULT_OK
};
/* This will return a number equal to or below 0 on failure.
* If it does fail, the error will be mirrored in dbi_error()
* The return value will otherwise be a resource handle, not an
* OK code or cell pointer.
*/
native Sql:dbi_connect(_host[], _user[], _pass[], _dbname[], _error[]="", _maxlength=0);
/* This will do a simple query execution on the SQL server.
* If it fails, it will return a number BELOW ZERO (0)
* If zero, it succeeded with NO RETURN RESULT.
* If greater than zero, make sure to call dbi_free_result() on it!
* The return is a handle to the result set
*/
native Result:dbi_query(Sql:_sql, _query[], any:...);
/* Has the same usage as dbi_query, but this native returns by
* reference the number of rows affected in the query. If the
* query fails rows will be equal to -1.
*/
native Result:dbi_query2(Sql:_sql, &rows, _query[], any:...);
/* Returns 0 on failure or End of Results.
* Advances result pointer by one row.
*/
native dbi_nextrow(Result:_result);
/* Gets a field by number. Returns 0 on failure.
* Although internally fields always start from 0,
* This function takes fieldnum starting from 1.
* No extra params: returns int
* One extra param: returns Float: byref
* Two extra param: Stores string with length
*/
native dbi_field(Result:_result, _fieldnum, any:... );
/* Gets a field by name. Returns 0 on failure.
* One extra param: returns Float: byref
* Two extra param: Stores string with length
*/
native dbi_result(Result:_result, _field[], any:... );
/* Returns the number of rows returned from a query
*/
native dbi_num_rows(Result:_result);
/* Frees memory used by a result handle. Do this or get memory leaks.
*/
native dbi_free_result(&Result:result);
/* Closes a database handle. Internally, it will also
* mark the handle as free, so this particular handle may
* be re-used in the future to save time.
*/
native dbi_close(&Sql:_sql);
/* Returns an error message set. For PGSQL and MySQL,
* this is a direct error return from the database handle/API.
* For MSSQL, it returns the last error message found from a
* thrown exception.
*/
native dbi_error(Sql:_sql, _error[], _len);
/* Returns the type of database being used. So far:
* "mysql", "pgsql", "mssql", "sqlite"
*/
native dbi_type(_type[], _len);
/* Returns the number of fields/colums in a result set.
* Unlike dbi_nextrow, you must pass a valid result handle.
*/
native dbi_num_fields(Result:result);
/* Retrieves the name of a field/column in a result set.
* Requires a valid result handle, and columns are numbered 1 to n.
*/
native dbi_field_name(Result:result, field, name[], maxLength);
/* This function can be used to find out if a table in a Sqlite database exists.
*/
stock bool:sqlite_table_exists(Sql:sql, table[])
{
new bool:exists;
new query[128];
format(query, 127, "SELECT name FROM sqlite_master WHERE type='table' AND name='%s' LIMIT 1;", table);
new Result:result = dbi_query(sql, query);
if (dbi_nextrow(result))
{
exists = true;
}
else
{
exists = false;
}
if (result > RESULT_NONE)
{
dbi_free_result(result);
}
return exists;
}

View File

@ -0,0 +1,152 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
#if defined _dodconst_included
#endinput
#endif
#define _dodconst_included
/* DoD teams */
#define ALLIES 1
#define AXIS 2
#define FT_NEW 1<<0
#define FT_OLD 1<<1
#define STAMINA_SET 0
#define STAMINA_RESET 1
#define FUSE_SET 0
#define FUSE_RESET 1
#define DODMAX_WEAPONS 46 // 5 slots for custom weapons
// DoD Weapon Types
enum
{
DODWT_PRIMARY = 0,
DODWT_SECONDARY,
DODWT_MELEE,
DODWT_GRENADE,
DODWT_OTHER
};
// Ammo Channels
#define AMMO_SMG 1 // thompson, greasegun, sten, mp40
#define AMMO_ALTRIFLE 2 // carbine, k43, mg34
#define AMMO_RIFLE 3 // garand, enfield, scoped enfield, k98, scoped k98
#define AMMO_PISTOL 4 // colt, webley, luger
#define AMMO_SPRING 5 // springfield
#define AMMO_HEAVY 6 // bar, bren, stg44, fg42, scoped fg42
#define AMMO_MG42 7 // mg42
#define AMMO_30CAL 8 // 30cal
#define AMMO_GREN 9 // grenades (should be all 3 types)
#define AMMO_ROCKET 13 // bazooka, piat, panzerschreck
enum {
PS_NOPRONE =0,
PS_PRONE,
PS_PRONEDEPLOY,
PS_DEPLOY,
};
/* info types for dod_get_map_info native */
enum {
MI_ALLIES_TEAM = 0,
MI_ALLIES_PARAS,
MI_AXIS_PARAS,
};
/* DoD weapons */
enum {
DODW_AMERKNIFE = 1,
DODW_GERKNIFE,
DODW_COLT,
DODW_LUGER,
DODW_GARAND,
DODW_SCOPED_KAR,
DODW_THOMPSON,
DODW_STG44,
DODW_SPRINGFIELD,
DODW_KAR,
DODW_BAR,
DODW_MP40,
DODW_HANDGRENADE,
DODW_STICKGRENADE,
DODW_STICKGRENADE_EX,
DODW_HANDGRENADE_EX,
DODW_MG42,
DODW_30_CAL,
DODW_SPADE,
DODW_M1_CARBINE,
DODW_MG34,
DODW_GREASEGUN,
DODW_FG42,
DODW_K43,
DODW_ENFIELD,
DODW_STEN,
DODW_BREN,
DODW_WEBLEY,
DODW_BAZOOKA,
DODW_PANZERSCHRECK,
DODW_PIAT,
DODW_SCOPED_FG42,
DODW_FOLDING_CARBINE,
DODW_KAR_BAYONET,
DODW_SCOPED_ENFIELD,
DODW_MILLS_BOMB,
DODW_BRITKNIFE,
DODW_GARAND_BUTT,
DODW_ENFIELD_BAYONET,
DODW_MORTAR,
DODW_K43_BUTT,
};
/* DoD Classes */
enum {
DODC_GARAND = 1,
DODC_CARBINE,
DODC_THOMPSON,
DODC_GREASE,
DODC_SNIPER,
DODC_BAR,
DODC_30CAL,
DODC_BAZOOKA,
//DODC_ALLIES_MORTAR,
DODC_KAR = 10,
DODC_K43,
DODC_MP40,
DODC_MP44,
DODC_SCHARFSCHUTZE,
DODC_FG42,
DODC_SCOPED_FG42,
DODC_MG34,
DODC_MG42,
DODC_PANZERJAGER,
//DODC_AXIS_MORTAR,
DODC_ENFIELD = 21,
DODC_STEN,
DODC_MARKSMAN,
DODC_BREN,
DODC_PIAT,
//DODC_BRIT_MORTAR,
};
/* DoD stats constants */
enum {
DODX_KILLS = 0,
DODX_DEATHS,
DODX_HEADSHOTS,
DODX_TEAMKILLS,
DODX_SHOTS,
DODX_HITS,
DODX_DAMAGE,
DODX_POINTS,
DODX_RANK,
DODX_MAX_STATS
}

View File

@ -0,0 +1,152 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// DoD Fun Functions
//
#if defined _dodfun_included
#endinput
#endif
#define _dodfun_included
#include <dodconst>
#pragma reqlib dodfun
#if !defined AMXMODX_NOAUTOLOAD
#pragma loadlib dodfun
#endif
/* Function is called after grenade throw */
forward grenade_throw(index,greindex,wId);
/* Function is called after a rocket is shot */
forward rocket_shoot(index,rocketindex,wId);
/* Example: for full stamina use dod_player_stamina(1,STAMINA_SET,100,100) */
/* value is from 0 - 100 */
native dod_set_stamina(index,set=STAMINA_SET,minvalue=0,maxvalue=100);
/* Sets fuse for grenades. Valid number is from 0.1-20.0 */
/* types : new or preprimed */
native dod_set_fuse(index,set=FUSE_SET,Float:newFuse=5.0, Type=FT_NEW);
/* Sets player class */
native dod_set_user_class(index,classId);
/* Sets player team and random class. Don't work for spectators. */
native dod_set_user_team(index,teamId,refresh=1);
/* Returns next player class. Usefull is player is using random class */
native dod_get_next_class(index);
/* Returns 1 if player choose random class */
native dod_is_randomclass(index);
/* Returns player deaths */
native dod_get_pl_deaths(index);
/* Sets player deaths.
* Note if you opt to refresh the scoreboard, it
* will make the player appear as "DEAD" in the scoreboard.
*/
native dod_set_pl_deaths(index,value,refresh=1);
/* Returns player deaths. */
native dod_get_user_kills(index);
/* Sets player kills. */
native dod_set_user_kills(index,value,refresh=1);
/* Sets player score. */
native dod_set_user_score(index,value,refresh=1);
/* Sets new team name for this player */
native dod_set_pl_teamname(index,const szName[]);
/* Gets player team name */
native dod_get_pl_teamname(index,szName[],len);
/* Returns 1 is player weapon is deployed (bar,mg..) */
native dod_is_deployed(index);
/*Sets the ammo of the specified weapon entity id */
native dod_set_user_ammo(index,wid,value);
/*Gets the ammo of the specified weapon entity id */
native dod_get_user_ammo(index,wid);
/* called after first InitObj */
forward controlpoints_init();
enum CP_VALUE {
CP_edict = 1, // read only
CP_area, // read only
CP_index, // read only
CP_owner,
CP_default_owner,
CP_visible, // reinit after change
CP_icon_neutral, // reinit after change
CP_icon_allies, // reinit after change
CP_icon_axis, // reinit after change
CP_origin_x, // reinit after change
CP_origin_y, // reinit after change
CP_can_touch,
CP_pointvalue,
CP_points_for_cap,
CP_team_points,
CP_model_body_neutral,
CP_model_body_allies,
CP_model_body_axis,
// strings
CP_name,
CP_reset_capsound,
CP_allies_capsound,
CP_axis_capsound,
CP_targetname,
CP_model_neutral,
CP_model_allies,
CP_model_axis,
};
/* returns number of objectives */
native objectives_get_num();
/* use this function to update client(s) hud. You need to do this sometimes. Check CP_VALUE comments.
if player is 0 , all clients will get this message */
native objectives_reinit( player=0 );
/* use this function to get info about specified control point */
native objective_get_data( index, CP_VALUE:key, szValue[]="", len=0 );
/* use this function to change control point's data */
native objective_set_data( index, CP_VALUE:key , iValue=-1, const szValue[]="" );
enum CA_VALUE {
CA_edict = 1,
CA_allies_numcap,
CA_axis_numcap,
CA_timetocap,
CA_can_cap,
// strings
CA_target,
CA_sprite,
};
/* use this function to get info about specified control point's area */
native area_get_data( index, CA_VALUE:key, szValue[]="", len=0 );
/* use this function to change control point's area data */
native area_set_data( index, CA_VALUE:key , iValue=-1, const szValue[]="" );

View File

@ -0,0 +1,69 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// DODX Stats Functions
//
#if defined _dodstats_included
#endinput
#endif
#define _dodstats_included
/* Gets stats from given weapon index. If wpnindex is 0
* then the stats are from all weapons. If weapon has not been used function
* returns 0 in other case 1. Fields in stats are:
* 0 - kills
* 1 - deaths
* 2 - headshots
* 3 - teamkilling
* 4 - shots
* 5 - hits
* 6 - damage
* 7 - score
* For body hits fields see amxconst.inc. */
native get_user_wstats(index,wpnindex,stats[DODX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets round stats from given weapon index.*/
native get_user_wrstats(index,wpnindex,stats[DODX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets life (from spawn to spawn) stats from given weapon index.*/
native get_user_wlstats(index,wpnindex,stats[DODX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets overall stats which are stored in file on server
* and updated on every respawn or user disconnect.
* Function returns the position in stats by diff. kills to deaths. */
native get_user_stats(index,stats[DODX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets round stats of player. */
native get_user_rstats(index,stats[DODX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets life (from spawn to spawn) stats of player. */
native get_user_lstats(index,stats[DODX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets stats with which user have killed/hurt his victim. If victim is 0
* then stats are from all victims. If victim has not been hurt, function
* returns 0 in other case 1. User stats are reset on his respawn. */
native get_user_vstats(index,victim,stats[DODX_MAX_STATS],bodyhits[MAX_BODYHITS],wpnname[]="",len=0);
/* Gets stats with which user have been killed/hurt. If killer is 0
* then stats are from all attacks. If killer has not hurt user, function
* returns 0 in other case 1. User stats are reset on his respawn. */
native get_user_astats(index,wpnindex,stats[DODX_MAX_STATS],bodyhits[MAX_BODYHITS],wpnname[]="",len=0);
/* Resets life, weapon, victims and attackers user stats. */
native reset_user_wstats(index);
/* Gets overall stats which stored in stats.dat file in amx folder
* and updated on every mapchange or user disconnect.
* Function returns next index of stats entry or 0 if no more exists. */
native get_stats(index,stats[DODX_MAX_STATS],bodyhits[MAX_BODYHITS],name[],len);
/* Returns number of all entries in stats. */
native get_statsnum();

View File

@ -0,0 +1,161 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// DODX Functions
//
#if defined _dodx_included
#endinput
#endif
#define _dodx_included
#include <dodconst>
#include <dodstats>
#pragma reqclass xstats
#if !defined AMXMODX_NOAUTOLOAD
#pragma defclasslib xstats dodx
#endif
/************* Shared Natives Start ********************************/
/* Forward types */
enum {
XMF_DAMAGE = 0,
XMF_DEATH,
XMF_SCORE,
};
/* Use this function to register forwards */
native register_statsfwd(ftype);
/* Function is called after player to player attacks ,
* if players were damaged by teammate TA is set to 1 */
forward client_damage(attacker, victim, damage, wpnindex, hitplace, TA);
/* Function is called after player death ,
* if player was killed by teammate TK is set to 1 */
forward client_death(killer, victim, wpnindex, hitplace, TK);
/* Function is called if player scored */
forward client_score(id, score, total);
/* This Forward is called when a player changes team */
forward dod_client_changeteam(id, team, oldteam);
/* This Forward is called if a player changes class, but just after spawn */
forward dod_client_changeclass(id, class, oldclass);
/* This Forward is called when a player spawns */
forward dod_client_spawn(id);
/* This will be called whenever a player scopes or unscopes
value = 1 scope up
value = 0 scope down */
forward dod_client_scope(id, value);
/* This will be called whenever a player drops a weapon
weapon is weapon dropped or picked up
value = 1 picked up
value = 0 dropped */
forward dod_client_weaponpickup(id, weapon, value);
/* Called whenever the the player goes to or comes from prone position
value = 1 going down
value = 0 getting up */
forward dod_client_prone(id, value);
/* This will be called whenever a player switches a weapon */
forward dod_client_weaponswitch(id, wpnew, wpnold);
/* Forward for when a grenade explodes and its location */
forward dod_grenade_explosion(id, Float:pos[3], wpnid);
/* Forward for when a rocket explodes and its location */
forward dod_rocket_explosion(id, Float:pos[3], wpnid);
/* Forward for when a player picks up a object */
forward dod_client_objectpickup(id, objid, Float:pos[3], value);
/* Forward for when a users stamina decreases */
forward dod_client_stamina(id, stamina);
/* We want to get just the weapon of whichever type that the player is on him
Use DODWT_* in dodconst.inc for type */
native dod_weapon_type(id, type);
/* This native will change the position of a weapon within the users slots and its ammo ammount */
native dod_set_weaponlist(id, wpnID, slot, dropslot, totalrds);
/* Sets the model for a player */
native dod_set_model(id, const model[]);
/* Sets the model for a player */
native dod_set_body_number(id, bodynumber);
/* Un-Sets the model for a player */
native dod_clear_model(id);
/* Custom Weapon Support */
/* function will return index of new weapon */
native custom_weapon_add( const wpnname[], melee = 0, const logname[]="" );
/* Function will pass damage done by this custom weapon to stats module and other plugins */
native custom_weapon_dmg( weapon, att, vic, damage, hitplace=0 );
/* Function will pass info about custom weapon shot to stats module */
native custom_weapon_shot( weapon, index ); // weapon id , player id
/* function will return 1 if true */
native xmod_is_melee_wpn(wpnindex);
/* Returns weapon name. */
native xmod_get_wpnname(wpnindex, name[], len);
/* Returns weapon logname. */
native xmod_get_wpnlogname(wpnindex, name[], len);
/* Returns weapons array size */
native xmod_get_maxweapons();
/* Returns stats array size ex. 8 in TS , 9 in DoD */
native xmod_get_stats_size();
/* Returns 1 if true */
native xmod_is_custom_wpn(wpnindex);
/************* Shared Natives End ********************************/
/* weapon logname to weapon name convertion */
native dod_wpnlog_to_name(const logname[],name[],len);
/* weapon logname to weapon index convertion */
native dod_wpnlog_to_id(const logname[]);
native dod_get_map_info( info );
/* Returns id of currently carried weapon. Gets also
* ammount of ammo in clip and backpack. */
native dod_get_user_weapon(index,&clip=0,&ammo=0);
/* Returns team score */
native dod_get_team_score(teamId);
/* Returns player class id */
native dod_get_user_class(index);
/* Returns player score */
native dod_get_user_score(index);
/* values are: 0-no prone, 1-prone, 2-prone + w_deploy */
native dod_get_pronestate(index);
/* It is not as safe as original but player deaths will not be increased */
native dod_user_kill(index);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,310 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Engine Constants
//
#if defined _engine_const_included
#endinput
#endif
#define _engine_const_included
#include <hlsdk_const>
/**
* Flags for the [set|get]_speak() natives.
*
* @note These do not correspond to any HLSDK constants and are only relevant to
* the custom functionality provided by the engine module.
*/
#define SPEAK_NORMAL 0 // Normal behavior, client follows alltalk rules
#define SPEAK_MUTED 1 // Client can not talk
#define SPEAK_ALL 2 // Client can talk to every other client
#define SPEAK_LISTENALL 4 // Client can listen to every other client
/**
* View types for the set_view() native.
*
* @note These do not correspond to any HLSDK constants and are only relevant to
* the custom functionality provided by the engine module.
*/
#define CAMERA_NONE 0
#define CAMERA_3RDPERSON 1
#define CAMERA_UPLEFT 2
#define CAMERA_TOPDOWN 3
/**
* @section Entvar constants used with entity_[get|set]_* functions.
*/
/**
* Integers, use with entity_[get|set]_int()
*/
enum {
EV_INT_gamestate = 0,
EV_INT_oldbuttons,
EV_INT_groupinfo,
EV_INT_iuser1,
EV_INT_iuser2,
EV_INT_iuser3,
EV_INT_iuser4,
EV_INT_weaponanim,
EV_INT_pushmsec,
EV_INT_bInDuck,
EV_INT_flTimeStepSound,
EV_INT_flSwimTime,
EV_INT_flDuckTime,
EV_INT_iStepLeft,
EV_INT_movetype,
EV_INT_solid,
EV_INT_skin,
EV_INT_body,
EV_INT_effects,
EV_INT_light_level,
EV_INT_sequence,
EV_INT_gaitsequence,
EV_INT_modelindex,
EV_INT_playerclass,
EV_INT_waterlevel,
EV_INT_watertype,
EV_INT_spawnflags,
EV_INT_flags,
EV_INT_colormap,
EV_INT_team,
EV_INT_fixangle,
EV_INT_weapons,
EV_INT_rendermode,
EV_INT_renderfx,
EV_INT_button,
EV_INT_impulse,
EV_INT_deadflag,
};
/**
* Floats, use with entity_[get|set]_float()
*/
enum {
EV_FL_impacttime = 0,
EV_FL_starttime,
EV_FL_idealpitch,
EV_FL_pitch_speed,
EV_FL_ideal_yaw,
EV_FL_yaw_speed,
EV_FL_ltime,
EV_FL_nextthink,
EV_FL_gravity,
EV_FL_friction,
EV_FL_frame,
EV_FL_animtime,
EV_FL_framerate,
EV_FL_health,
EV_FL_frags,
EV_FL_takedamage,
EV_FL_max_health,
EV_FL_teleport_time,
EV_FL_armortype,
EV_FL_armorvalue,
EV_FL_dmg_take,
EV_FL_dmg_save,
EV_FL_dmg,
EV_FL_dmgtime,
EV_FL_speed,
EV_FL_air_finished,
EV_FL_pain_finished,
EV_FL_radsuit_finished,
EV_FL_scale,
EV_FL_renderamt,
EV_FL_maxspeed,
EV_FL_fov,
EV_FL_flFallVelocity,
EV_FL_fuser1,
EV_FL_fuser2,
EV_FL_fuser3,
EV_FL_fuser4,
};
/**
* Vectors, use with entity_[get|set]_vector()
*/
enum {
EV_VEC_origin = 0,
EV_VEC_oldorigin,
EV_VEC_velocity,
EV_VEC_basevelocity,
EV_VEC_clbasevelocity,
EV_VEC_movedir,
EV_VEC_angles,
EV_VEC_avelocity,
EV_VEC_punchangle,
EV_VEC_v_angle,
EV_VEC_endpos,
EV_VEC_startpos,
EV_VEC_absmin,
EV_VEC_absmax,
EV_VEC_mins,
EV_VEC_maxs,
EV_VEC_size,
EV_VEC_rendercolor,
EV_VEC_view_ofs,
EV_VEC_vuser1,
EV_VEC_vuser2,
EV_VEC_vuser3,
EV_VEC_vuser4,
};
/**
* Edicts, use with entity_[get|set]_edict()
*/
enum {
EV_ENT_chain = 0,
EV_ENT_dmg_inflictor,
EV_ENT_enemy,
EV_ENT_aiment,
EV_ENT_owner,
EV_ENT_groundentity,
EV_ENT_pContainingEntity,
EV_ENT_euser1,
EV_ENT_euser2,
EV_ENT_euser3,
EV_ENT_euser4,
};
/**
* Strings, use with entity_[get|set]_string()
*/
enum {
EV_SZ_classname = 0,
EV_SZ_globalname,
EV_SZ_model,
EV_SZ_target,
EV_SZ_targetname,
EV_SZ_netname,
EV_SZ_message,
EV_SZ_noise,
EV_SZ_noise1,
EV_SZ_noise2,
EV_SZ_noise3,
EV_SZ_viewmodel,
EV_SZ_weaponmodel,
};
/**
* Bytearrays, use with entity_[get|set]_byte()
*/
enum {
EV_BYTE_controller1 = 0,
EV_BYTE_controller2,
EV_BYTE_controller3,
EV_BYTE_controller4,
EV_BYTE_blending1,
EV_BYTE_blending2,
};
/**
* @endsection
*/
#if defined _jghg_enums
#endinput
#endif
#define _jghg_enums
/**
* Used by get_global_[edict/float/int/string/vector]()
*/
enum {
// Edict
GL_trace_ent = 0,
// Float
GL_coop,
GL_deathmatch,
GL_force_retouch,
GL_found_secrets,
GL_frametime,
GL_serverflags,
GL_teamplay,
GL_time,
GL_trace_allsolid,
GL_trace_fraction,
GL_trace_inopen,
GL_trace_inwater,
GL_trace_plane_dist,
GL_trace_startsolid,
// Int
GL_cdAudioTrack,
GL_maxClients,
GL_maxEntities,
GL_msg_entity,
GL_trace_flags,
GL_trace_hitgroup,
// String
GL_pStringBase,
GL_mapname,
GL_startspot,
// Vector
GL_trace_endpos,
GL_trace_plane_normal,
GL_v_forward,
GL_v_right,
GL_v_up,
GL_vecLandmarkOffset,
// Void (not supported)
GL_pSaveData
};
/**
* Used by [get/set]_usercmd()
*/
enum
{
usercmd_float_start,
usercmd_forwardmove, // Float
usercmd_sidemove, // Float
usercmd_upmove, // Float
usercmd_float_end,
usercmd_int_start,
usercmd_lerp_msec, // short
usercmd_msec, // byte
usercmd_lightlevel, // byte
usercmd_buttons, // unsigned short
usercmd_impulse, // byte
usercmd_weaponselect, // byte
usercmd_impact_index, // int
usercmd_int_end,
usercmd_vec_start,
usercmd_viewangles, // Vector
usercmd_impact_position, // vec
usercmd_vec_end
};
/**
* Used by the traceresult()
*/
enum
{
TR_AllSolid, // (int) if true, plane is not valid
TR_StartSolid, // (int) if true, the initial point was in a solid area
TR_InOpen, // (int)
TR_InWater, // (int)
TR_Fraction, // (float) time completed, 1.0 = didn't hit anything
TR_EndPos, // (vector) final position
TR_PlaneDist, // (float)
TR_PlaneNormal, // (vector) surface normal at impact
TR_Hit, // (entity) entity the surface is on
TR_Hitgroup // (int) 0 == generic, non zero is specific body part
};

View File

@ -0,0 +1,248 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
// Special thanks to AssKicR, Freecode, and T(+)rget.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Engine Stocks
//
#if defined _engine_stocks_included
#endinput
#endif
#define _engine_stocks_included
#if !defined _amxmodx_included
#include <amxmodx>
#endif
#if !defined _engine_included
#include <engine>
#endif
stock fakedamage(idvictim,const szClassname[],Float:takedmgdamage,damagetype)
{
new entity = create_entity("trigger_hurt");
if (entity)
{
DispatchKeyValue(entity,"classname","trigger_hurt");
new szDamage[16];
// Takedamages only do half damage per attack (damage is damage per second, and it's triggered in 0.5 second intervals).
// Compensate for that.
format(szDamage,15,"%f",takedmgdamage * 2);
DispatchKeyValue(entity,"dmg",szDamage);
format(szDamage,15,"%i",damagetype);
DispatchKeyValue(entity,"damagetype",szDamage);
DispatchKeyValue(entity,"origin","8192 8192 8192");
DispatchSpawn(entity);
entity_set_string(entity, EV_SZ_classname, szClassname);
fake_touch(entity,idvictim);
remove_entity(entity);
return 1;
}
return 0;
}
//wrapper for find_ent_by_class
stock find_ent(iStart, const szClassname[])
{
return find_ent_by_class(iStart, szClassname);
}
/* Get the Button(s) user is pressing */
stock get_user_button(id)
{
return entity_get_int(id, EV_INT_button);
}
stock get_user_oldbutton(id)
{
return entity_get_int(id, EV_INT_oldbuttons);
}
/* Get flags an entity is flagged with */
stock get_entity_flags(ent)
{
return entity_get_int(ent, EV_INT_flags);
}
/* Get the distance between two entities */
stock get_entity_distance(ent1, ent2)
{
return floatround(entity_range(ent1, ent2));
}
/* Get grenade thrown by this user */
stock get_grenade(id)
{
new iGrenade = find_ent_by_class(-1, "grenade");
while(iGrenade > 0)
{
if(entity_get_edict(iGrenade, EV_ENT_owner) == id)
return iGrenade;
iGrenade = find_ent_by_class(iGrenade, "grenade");
}
return 0;
}
/* Get origin of a brush entity */
stock get_brush_entity_origin(ent, Float:orig[3])
{
new Float:Min[3], Float:Max[3];
entity_get_vector(ent, EV_VEC_origin, orig);
entity_get_vector(ent, EV_VEC_mins, Min);
entity_get_vector(ent, EV_VEC_maxs, Max);
orig[0] += (Min[0] + Max[0]) * 0.5;
orig[1] += (Min[1] + Max[1]) * 0.5;
orig[2] += (Min[2] + Max[2]) * 0.5;
return 1;
}
/* Remove entity by name */
stock remove_entity_name(const eName[])
{
new iEntity = find_ent_by_class(-1, eName);
while (iEntity > 0)
{
remove_entity(iEntity);
iEntity = find_ent_by_class(-1, eName);
}
return 1;
}
/* Get the contents of the point a user is aiming at */
stock ViewContents(id)
{
new origin[3], Float:Orig[3];
get_user_origin(id, origin, Origin_AimEndEyes);
Orig[0] = float(origin[0]);
Orig[1] = float(origin[1]);
Orig[2] = float(origin[2]);
return point_contents(Orig);
}
stock get_speed(ent)
{
new Float:Vel[3];
entity_get_vector(ent, EV_VEC_velocity, Vel);
return floatround(vector_length(Vel));
}
/* Set rendering of an entity */
stock set_rendering(index, fx=kRenderFxNone, r=255, g=255, b=255, render=kRenderNormal, amount=16)
{
entity_set_int(index,EV_INT_renderfx,fx);
new Float:RenderColor[3];
RenderColor[0] = float(r);
RenderColor[1] = float(g);
RenderColor[2] = float(b);
entity_set_vector(index,EV_VEC_rendercolor,RenderColor);
entity_set_int(index,EV_INT_rendermode,render);
entity_set_float(index,EV_FL_renderamt,float(amount));
return 1;
}
/* Set flags on an entity */
stock set_entity_flags(ent,flag,onoff)
{
new iFlags = entity_get_int(ent, EV_INT_flags);
if(iFlags & flag)
{
if(onoff == 1) return 2;
iFlags &= ~flag;
}
else
{
if(onoff == 0) return 2;
iFlags |= flag;
}
entity_set_int(ent, EV_INT_flags, iFlags);
return 1;
}
/* If visible = 1, entity will be set to be visible, else invisible. */
stock set_entity_visibility(entity, visible = 1)
{
entity_set_int(entity, EV_INT_effects, visible == 1 ? entity_get_int(entity, EV_INT_effects) & ~EF_NODRAW : entity_get_int(entity, EV_INT_effects) | EF_NODRAW);
return 1;
}
/* Returns 1 if entity is visible. */
stock get_entity_visibility(entity)
{
return !(entity_get_int(entity, EV_INT_effects) & EF_NODRAW);
}
stock set_user_velocity(entity, const Float:vec[3])
{
return entity_set_vector(entity, EV_VEC_velocity, vec);
}
stock get_user_velocity(entity, Float:vec[3])
{
return entity_get_vector(entity, EV_VEC_velocity, vec);
}
/* Backwards compatible */
/* Hurts/Kills players in a sphere, like an explosion, Multiplier determines damage. */
stock RadiusDamage(const Float:fExplodeAt[3], iDamageMultiplier, iRadiusMultiplier)
{
return radius_damage(fExplodeAt, iDamageMultiplier, iRadiusMultiplier);
}
/* Gives you a velocity in the direction a player is looking, iVelocity is the multiplier. */
stock VelocityByAim(iIndex,iVelocity, Float:vRetValue[3])
{
return velocity_by_aim(iIndex,iVelocity,vRetValue);
}
/* Will return the contents of a point (inside map? in sky? outside map? etc.). */
stock PointContents(const Float:fCheckAt[3])
{
return point_contents(fCheckAt);
}
stock set_size(index, const Float:mins[3], const Float:maxs[3])
{
return entity_set_size(index,mins,maxs);
}
//by Twilight Suzuka, request addition at29428
//"Lifted from HLSDK"
stock IsInWorld( ent )
{
new Float:origin[3];
entity_get_vector(ent,EV_VEC_origin,origin);
if (origin[0] >= 4096.0) return 0;
if (origin[1] >= 4096.0) return 0;
if (origin[2] >= 4096.0) return 0;
if (origin[0] <= -4096.0) return 0;
if (origin[1] <= -4096.0) return 0;
if (origin[2] <= -4096.0) return 0;
new Float:velocity[3];
entity_get_vector(ent,EV_VEC_velocity,velocity);
if (velocity[0] >= 2000) return 0;
if (velocity[1] >= 2000) return 0;
if (velocity[2] >= 2000) return 0;
if (velocity[0] <= -2000) return 0;
if (velocity[1] <= -2000) return 0;
if (velocity[2] <= -2000) return 0;
return 1;
}

View File

@ -0,0 +1,70 @@
/***********************************************
[ Corona-Bytes.NET ] EvolutionX Core Plugin
(c) Corona - Bytes .NET coders :: coders@corona-bytes.net
> 2005 Corona Bytes :: http://www.corona-bytes.net
***********************************************/
#if defined __EVOLUTION_CORE__
#endinput
#endif
#define __EVOLUTION_CORE__
#pragma library EvolutionXCore
native setClientPL ( Client, PowerLevel );
native getClientPL ( Client );
native setClientACPL ( Client, ActualPowerLevel );
native getClientACPL ( Client );
native setClientADPL ( Client, AfterDeathPowerLevel );
native getClientADPL ( Client );
native setClientSPL ( Client, PowerLevel );
native setClientPLtoADPL ( Client );
native setClientKI ( Client, Ki );
native getClientKI ( Client );
native setClientHP ( Client, Health );
native getClientHP ( Client );
native setClientMHP ( Client, MaximumHealth );
native getClientMHP ( Client );
native setClientSPEED ( Client, Speed );
native getClientSPEED ( Client );
native setClientSWOOPSPEED ( Client, SwoopSpeed );
native getClientSWOOPSPEED ( Client );
native setClientPROTECT ( Client, bool:Enable = true );
native getClientPROTECT ( Client );
native setClientFROZEN ( Client, bool:Enable = true );
native getClientFROZEN ( Client );
native setClientGOD ( Client, bool:Enable = true );
native getClientGOD ( Client );
native getClientFLY ( Client );
native setClientHiddenTURBO ( Client, bool:Enable = true );
native getClientTURBO ( Client );
native getClientBLOCK ( Client );
native setClientHiddenPOWERUP ( Client, bool:Enable = true );
native getClientPOWERUP ( Client );
native getClientSWOOPING ( Client );
native getClientATKSHOOT ( Client );
native getClientATKCHARGE ( Client );
native getClientMELEE ( Client );
native getClientTHROWAWAY ( Client );
native getClientTHROW ( Client );
native getClientWALLGND ( Client );
native getClientINFREEFALL ( Client );
native getClientBEAMJUMP ( Client );
// kills a player without score/death msg
native silentClientKILL ( Client );

View File

@ -0,0 +1,74 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
// Based on stocks and information provided by LynX.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
#if defined _esfconst_included
#endinput
#endif
#define _esfconst_included
enum
{
Character_Buu = 1,
Character_Goku = 2,
Character_Gohan = 3, //my favorite :)
Character_Krillin = 4,
Character_Frieza = 5,
Character_Piccolo = 6,
Character_Trunks = 7,
Character_Vegeta = 8,
Character_Cell = 9,
};
enum
{
Explosion_Blue = 0,
Explosion_Green,
Explosion_Orange,
Explosion_Purple,
Explosion_Yellow,
Explosion_Red,
Explosion_White,
Explosions_Total,
};
enum
{
Attack_Kamehameha=1,
Attack_SpiritBomb,
Attack_GalletGun,
Attack_FinalFlash,
Attack_Renzoku,
Attack_Kametorpedo,
Attack_GenericBeam,
Attack_Throw,
};
enum
{
Direction_Left=1,
Direction_Right,
Direction_Up,
Direction_Down,
Direction_Forward,
Direction_Backward,
};
enum
{
Recovery_Kicked=1,
Recovery_Tumbled,
Recovery_Lying,
Recovery_Thrown,
};
#define ESF_CHARGING 1
#define ESF_CONTROLLING 2
#define ESF_SHOOTING 3
#define ESF_SHOT 4

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,793 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Fakemeta Constants
//
#if defined _fakemeta_const_included
#endinput
#endif
#define _fakemeta_const_included
// For forward_return
#define FMV_STRING 1
#define FMV_FLOAT 2
#define FMV_CELL 3
#include <hlsdk_const>
/* The actual return value of the function, use these instead of PLUGIN_HANDLED etc when
* returning from registered forwards.
*/
#define FMRES_IGNORED 1 // Calls target function, returns normal value
#define FMRES_HANDLED 2 // Tells metamod you did something, still calls target function and returns normal value
#define FMRES_OVERRIDE 3 // Supposed to still call the target function but return your value instead
// however this does not work properly with metamod; use supercede instead.
#define FMRES_SUPERCEDE 4 // Block the target call, and use your return value (if applicable)
// Use this with GetInfoKeyBuffer if you want the server's localinfo buffer
#define FM_NULLENT -1
/* Used with engfunc()
*/
enum {
EngFunc_PrecacheModel, // int ) (char *s);
EngFunc_PrecacheSound, // int ) (char *s);
EngFunc_SetModel, // void ) (edict_t *e, const char *m);
EngFunc_ModelIndex, // int ) (const char *m);
EngFunc_ModelFrames, // int ) (int modelIndex);
EngFunc_SetSize, // void ) (edict_t *e, const float *rgflMin, const float *rgflMax);
EngFunc_ChangeLevel, // void ) (char* s1, char* s2);
EngFunc_VecToYaw, // float) (const float *rgflVector);
EngFunc_VecToAngles, // void ) (const float *rgflVectorIn, float *rgflVectorOut);
EngFunc_MoveToOrigin, // void ) (edict_t *ent, const float *pflGoal, float dist, int iMoveType);
EngFunc_ChangeYaw, // void ) (edict_t* ent);
EngFunc_ChangePitch, // void ) (edict_t* ent);
EngFunc_FindEntityByString, // edict) (edict_t *pEdictStartSearchAfter, const char *pszField, const char *pszValue);
EngFunc_GetEntityIllum, // int ) (edict_t* pEnt);
EngFunc_FindEntityInSphere, // edict) (edict_t *pEdictStartSearchAfter, const float *org, float rad);
EngFunc_FindClientInPVS, // edict) (edict_t *pEdict);
EngFunc_EntitiesInPVS, // edict) (edict_t *pplayer);
EngFunc_MakeVectors, // void ) (const float *rgflVector);
EngFunc_AngleVectors, // void ) (const float *rgflVector, float *forward, float *right, float *up);
EngFunc_CreateEntity, // edict) (void);
EngFunc_RemoveEntity, // void ) (edict_t *e);
EngFunc_CreateNamedEntity, // edict) (int className);
EngFunc_MakeStatic, // void ) (edict_t *ent);
EngFunc_EntIsOnFloor, // int ) (edict_t *e);
EngFunc_DropToFloor, // int ) (edict_t *e);
EngFunc_WalkMove, // int ) (edict_t *ent, float yaw, float dist, int iMode);
EngFunc_SetOrigin, // void ) (edict_t *e, const float *rgflOrigin);
EngFunc_EmitSound, // void ) (edict_t *entity, int channel, const char *sample, float volume, float attenuation, int fFlags, int pitch);
EngFunc_EmitAmbientSound, // void ) (edict_t *entity, float *pos, const char *samp, float vol, float attenuation, int fFlags, int pitch);
//With 1.71 you can pass an optional TraceLine ptr for trace natives
// it can be 0, for meaning "global tr handle" (for get/set_tr2), or
// it can be any other TR handle (such as one from a TR hook)
EngFunc_TraceLine, // void ) (const float *v1, const float *v2, int fNoMonsters, edict_t *pentToSkip, TraceResult *ptr);
EngFunc_TraceToss, // void ) (edict_t *pent, edict_t *pentToIgnore, TraceResult *ptr);
EngFunc_TraceMonsterHull, // int ) (edict_t *pEdict, const float *v1, const float *v2, int fNoMonsters, edict_t *pentToSkip, TraceResult *ptr);
EngFunc_TraceHull, // void ) (const float *v1, const float *v2, int fNoMonsters, int hullNumber, edict_t *pentToSkip, TraceResult *ptr);
EngFunc_TraceModel, // void ) (const float *v1, const float *v2, int hullNumber, edict_t *pent, TraceResult *ptr);
EngFunc_TraceTexture, // const char *) (edict_t *pTextureEntity, const float *v1, const float *v2 );
EngFunc_TraceSphere, // void ) (const float *v1, const float *v2, int fNoMonsters, float radius, edict_t *pentToSkip, TraceResult *ptr);
EngFunc_GetAimVector, // void ) (edict_t *ent, float speed, float *rgflReturn);
EngFunc_ParticleEffect, // void ) (const float *org, const float *dir, float color, float count);
EngFunc_LightStyle, // void ) (int style, char *val);
EngFunc_DecalIndex, // int ) (const char *name);
EngFunc_PointContents, // int ) (const float *rgflVector);
EngFunc_FreeEntPrivateData, // void ) (edict_t *pEdict);
EngFunc_SzFromIndex, // const char *) (int iString);
EngFunc_AllocString, // int ) (const char *szValue);
EngFunc_RegUserMsg, // int ) (const char *pszName, int iSize);
EngFunc_AnimationAutomove, // void ) (const edict_t *pEdict, float flTime);
EngFunc_GetBonePosition, // void ) (const edict_t *pEdict, int iBone, float *rgflOrigin, float *rgflAngles);
EngFunc_GetAttachment, // void ) (const edict_t *pEdict, int iAttachment, float *rgflOrigin, float *rgflAngles);
EngFunc_SetView, // void ) (const edict_t *pClient, const edict_t *pViewent);
EngFunc_Time, // float) ( void );
EngFunc_CrosshairAngle, // void ) (const edict_t *pClient, float pitch, float yaw);
EngFunc_FadeClientVolume, // void ) (const edict_t *pEdict, int fadePercent, int fadeOutSeconds, int holdTime, int fadeInSeconds);
EngFunc_SetClientMaxspeed, // void ) (const edict_t *pEdict, float fNewMaxspeed);
EngFunc_CreateFakeClient, // edict) (const char *netname); // returns NULL if fake client can't be created
EngFunc_RunPlayerMove, // void ) (edict_t *fakeclient, const float *viewangles, float forwardmove, float sidemove, float upmove, unsigned short buttons, byte impulse, byte msec);
EngFunc_NumberOfEntities, // int ) ( void );
EngFunc_StaticDecal, // void ) (const float *origin, int decalIndex, int entityIndex, int modelIndex);
EngFunc_PrecacheGeneric, // int ) (char* s);
EngFunc_BuildSoundMsg, // void ) (edict_t *entity, int channel, const char *sample, /*int*/float volume, float attenuation, int fFlags, int pitch, int msg_dest, int msg_type, const float *pOrigin, edict_t *ed);
EngFunc_GetPhysicsKeyValue, // const char *) (const edict_t *pClient, const char *key);
EngFunc_SetPhysicsKeyValue, // void ) (const edict_t *pClient, const char *key, const char *value);
EngFunc_GetPhysicsInfoString, // const char *) (const edict_t *pClient);
EngFunc_PrecacheEvent, // unsigned short) (int type, const char*psz);
EngFunc_PlaybackEvent, // void ) (int flags, const edict_t *pInvoker, unsigned short eventindex, float delay, float *origin, float *angles, float fparam1, float fparam2, int iparam1, int iparam2, int bparam1, int bparam2);
EngFunc_CheckVisibility, // int ) (const edict_t *entity, unsigned char *pset);
EngFunc_GetCurrentPlayer, // int ) ( void );
EngFunc_CanSkipPlayer, // int ) (const edict_t *player);
EngFunc_SetGroupMask, // void ) (int mask, int op);
EngFunc_GetClientListening, // bool ) (int iReceiver, int iSender)
EngFunc_SetClientListening, // bool ) (int iReceiver, int iSender, bool Listen)
EngFunc_MessageBegin, // void ) (int msg_dest, int msg_type, const float *pOrigin, edict_t *ed)
EngFunc_WriteCoord, // void ) (float flValue)
EngFunc_WriteAngle, // void ) (float flValue)
EngFunc_InfoKeyValue, // char*) (char *infobuffer, char *key);
EngFunc_SetKeyValue, // void ) (char *infobuffer, char *key, char *value);
EngFunc_SetClientKeyValue, // void ) (int clientIndex, char *infobuffer, char *key, char *value);
EngFunc_CreateInstBaseline, // int ) (int classname, struct entity_state_s *baseline);
// Returns pointer to info buffer that can be used with the infobuffer param of InfoKeyValue, SetKeyValue, and SetClientKeyValue
EngFunc_GetInfoKeyBuffer, // char*) (edict_t *e);
EngFunc_AlertMessage, // void ) (ALERT_TYPE atype, char *szFmt, ...);
EngFunc_ClientPrintf, // void ) (edict_t* pEdict, PRINT_TYPE ptype, const char *szMsg);
EngFunc_ServerPrint // void ) (const char *szMsg);
};
/* Used with dllfunc()
*/
enum
{
DLLFunc_GameInit, // void ) ( void );
DLLFunc_Spawn, // int ) (edict_t *pent);
DLLFunc_Think, // void ) (edict_t *pent);
DLLFunc_Use, // void ) (edict_t *pentUsed, edict_t *pentOther);
DLLFunc_Touch, // void ) (edict_t *pentTouched, edict_t *pentOther);
DLLFunc_Blocked, // void ) (edict_t *pentBlocked, edict_t *pentOther);
//You can pass in 0 for glb kvd handle or a kvd handle here
DLLFunc_KeyValue, // void ) (edict_t *pentKeyvalue, KeyValueData *pkvd);
DLLFunc_SetAbsBox, // void ) (edict_t *pent);
DLLFunc_ClientConnect, // bool ) (edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[128]);
DLLFunc_ClientDisconnect, // void ) (edict_t *pEntity);
DLLFunc_ClientKill, // void ) (edict_t *pEntity);
DLLFunc_ClientPutInServer, // void ) (edict_t *pEntity);
DLLFunc_ClientCommand, // void ) (edict_t *pEntity);
DLLFunc_ServerDeactivate, // void ) ( void );
DLLFunc_PlayerPreThink, // void ) (edict_t *pEntity);
DLLFunc_PlayerPostThink, // void ) (edict_t *pEntity);
DLLFunc_StartFrame, // void ) ( void );
DLLFunc_ParmsNewLevel, // void ) ( void );
DLLFunc_ParmsChangeLevel, // void ) ( void );
// Returns string describing current .dll. E.g., TeamFotrress 2, Half-Life
// This also gets called when the server is queried for information (for example, by a server browser tool)
DLLFunc_GetGameDescription, // const char *) ( void );
// Spectator funcs
DLLFunc_SpectatorConnect, // void ) (edict_t *pEntity);
DLLFunc_SpectatorDisconnect, // void ) (edict_t *pEntity);
DLLFunc_SpectatorThink, // void ) (edict_t *pEntity);
// Notify game .dll that engine is going to shut down. Allows mod authors to set a breakpoint.
DLLFunc_Sys_Error, // void ) (const char *error_string);
DLLFunc_PM_FindTextureType, // char ) (char *name);
DLLFunc_RegisterEncoders, // void ) ( void );
// Enumerates player hulls. Returns 0 if the hull number doesn't exist, 1 otherwise
DLLFunc_GetHullBounds, // int ) (int hullnumber, float *mins, float *maxs);
// Create baselines for certain "unplaced" items.
DLLFunc_CreateInstBaselines, // void ) ( void );
DLLFunc_pfnAllowLagCompensation, // int ) ( void );
// I know this does not fit with DLLFUNC(), but I don't want another native just for it.
MetaFunc_CallGameEntity, // bool ) (plid_t plid, const char *entStr,entvars_t *pev);
DLLFunc_ClientUserInfoChanged, // void ) (edict *pEntity, char *infobuffer);
// You can pass in 0 for global cd handle or another cd handle here
DLLFunc_UpdateClientData, // void ) (const struct edict_s *ent, int sendweapons, struct clientdata_s *cd);
// You can pass in 0 for global entity state handle or another entity state handle here
DLLFunc_AddToFullPack, // int ) (struct entity_state_s *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet);
// You can pass in 0 for global usercmd handle or another usercmd handle here
DLLFunc_CmdStart, // void ) (const edict_t *player, const struct usercmd_s *cmd, unsigned int random_seed);
DLLFunc_CmdEnd, // void ) (const edict_t *player);
DLLFunc_CreateBaseline // void ) (int player, int eindex, struct entity_state_s *baseline, struct edict_s *entity, int playermodelindex, vec3_t player_mins, vec3_t player_maxs);
};
enum {
pev_string_start = 0,
pev_classname,
pev_globalname,
pev_model,
pev_target,
pev_targetname,
pev_netname,
pev_message,
pev_noise,
pev_noise1,
pev_noise2,
pev_noise3,
pev_string_end,
pev_edict_start,
pev_chain,
pev_dmg_inflictor,
pev_enemy,
pev_aiment,
pev_owner,
pev_groundentity,
pev_euser1,
pev_euser2,
pev_euser3,
pev_euser4,
pev_edict_end,
pev_float_start,
pev_impacttime,
pev_starttime,
pev_idealpitch,
pev_ideal_yaw,
pev_pitch_speed,
pev_yaw_speed,
pev_ltime,
pev_nextthink,
pev_gravity,
pev_friction,
pev_frame,
pev_animtime,
pev_framerate,
pev_scale,
pev_renderamt,
pev_health,
pev_frags,
pev_takedamage,
pev_max_health,
pev_teleport_time,
pev_armortype,
pev_armorvalue,
pev_dmg_take,
pev_dmg_save,
pev_dmg,
pev_dmgtime,
pev_speed,
pev_air_finished,
pev_pain_finished,
pev_radsuit_finished,
pev_maxspeed,
pev_fov,
pev_flFallVelocity,
pev_fuser1,
pev_fuser2,
pev_fuser3,
pev_fuser4,
pev_float_end,
pev_int_start,
pev_fixangle,
pev_modelindex,
pev_viewmodel,
pev_weaponmodel,
pev_movetype,
pev_solid,
pev_skin,
pev_body,
pev_effects,
pev_light_level,
pev_sequence,
pev_gaitsequence,
pev_rendermode,
pev_renderfx,
pev_weapons,
pev_deadflag,
pev_button,
pev_impulse,
pev_spawnflags,
pev_flags,
pev_colormap,
pev_team,
pev_waterlevel,
pev_watertype,
pev_playerclass,
pev_weaponanim,
pev_pushmsec,
pev_bInDuck,
pev_flTimeStepSound,
pev_flSwimTime,
pev_flDuckTime,
pev_iStepLeft,
pev_gamestate,
pev_oldbuttons,
pev_groupinfo,
pev_iuser1,
pev_iuser2,
pev_iuser3,
pev_iuser4,
pev_int_end,
pev_byte_start,
pev_controller_0,
pev_controller_1,
pev_controller_2,
pev_controller_3,
pev_blending_0,
pev_blending_1,
pev_byte_end,
pev_bytearray_start,
pev_controller,
pev_blending,
pev_bytearray_end,
pev_vecarray_start,
pev_origin,
pev_oldorigin,
pev_velocity,
pev_basevelocity,
pev_clbasevelocity,
pev_movedir,
pev_angles,
pev_avelocity,
pev_v_angle,
pev_endpos,
pev_startpos,
pev_absmin,
pev_absmax,
pev_mins,
pev_maxs,
pev_size,
pev_rendercolor,
pev_view_ofs,
pev_vuser1,
pev_vuser2,
pev_vuser3,
pev_vuser4,
pev_punchangle,
pev_vecarray_end,
pev_string2_begin, /* anything after here are string corrections */
pev_weaponmodel2,
pev_viewmodel2,
pev_string2_end,
pev_edict2_start, /* edict corrections */
pev_pContainingEntity,
pev_absolute_end
};
/* Used with global_get()
*/
enum
{
glb_start_int = 0,
glb_trace_hitgroup,
glb_trace_flags,
glb_msg_entity,
glb_cdAudioTrack,
glb_maxClients,
glb_maxEntities,
glb_end_int,
glb_start_float,
glb_time,
glb_frametime,
glb_force_retouch,
glb_deathmatch,
glb_coop,
glb_teamplay,
glb_serverflags,
glb_found_secrets,
glb_trace_allsolid,
glb_trace_startsolid,
glb_trace_fraction,
glb_trace_plane_dist,
glb_trace_inopen,
glb_trace_inwater,
glb_end_float,
glb_start_edict,
glb_trace_ent,
glb_end_edict,
glb_start_vector,
glb_v_forward,
glb_v_up,
glb_v_right,
glb_trace_endpos,
glb_trace_plane_normal,
glb_vecLandmarkOffset,
glb_end_vector,
glb_start_string,
glb_mapname,
glb_startspot,
glb_end_string,
glb_start_pchar,
glb_pStringBase,
glb_end_pchar
};
/* Used with register_forward()
*/
enum {
FM_PrecacheModel = 1,
FM_PrecacheSound,
FM_SetModel,
FM_ModelIndex,
FM_ModelFrames,
FM_SetSize,
FM_ChangeLevel,
FM_VecToYaw,
FM_VecToAngles,
FM_MoveToOrigin,
FM_ChangeYaw,
FM_ChangePitch,
FM_FindEntityByString,
FM_GetEntityIllum,
FM_FindEntityInSphere,
FM_FindClientInPVS,
FM_EntitiesInPVS,
FM_MakeVectors,
FM_AngleVectors,
FM_CreateEntity,
FM_RemoveEntity,
FM_CreateNamedEntity,
FM_MakeStatic,
FM_EntIsOnFloor,
FM_DropToFloor,
FM_WalkMove,
FM_SetOrigin,
FM_EmitSound,
FM_EmitAmbientSound,
FM_TraceLine,
FM_TraceToss,
FM_TraceMonsterHull,
FM_TraceHull,
FM_TraceModel,
FM_TraceTexture,
FM_TraceSphere,
FM_GetAimVector,
FM_ParticleEffect,
FM_LightStyle,
FM_DecalIndex,
FM_PointContents,
FM_MessageBegin,
FM_MessageEnd,
FM_WriteByte,
FM_WriteChar,
FM_WriteShort,
FM_WriteLong,
FM_WriteAngle,
FM_WriteCoord,
FM_WriteString,
FM_WriteEntity,
FM_CVarGetFloat,
FM_CVarGetString,
FM_CVarSetFloat,
FM_CVarSetString,
FM_FreeEntPrivateData,
FM_SzFromIndex,
FM_AllocString,
FM_RegUserMsg,
FM_AnimationAutomove,
FM_GetBonePosition,
FM_GetAttachment,
FM_SetView,
FM_Time,
FM_CrosshairAngle,
FM_FadeClientVolume,
FM_SetClientMaxspeed,
FM_CreateFakeClient,
FM_RunPlayerMove,
FM_NumberOfEntities,
FM_StaticDecal,
FM_PrecacheGeneric,
FM_BuildSoundMsg,
FM_GetPhysicsKeyValue,
FM_SetPhysicsKeyValue,
FM_GetPhysicsInfoString,
FM_PrecacheEvent,
FM_PlaybackEvent,
FM_CheckVisibility,
FM_GetCurrentPlayer,
FM_CanSkipPlayer,
FM_SetGroupMask,
FM_Voice_GetClientListening,
FM_Voice_SetClientListening,
FM_InfoKeyValue,
FM_SetKeyValue,
FM_SetClientKeyValue,
FM_GetPlayerAuthId,
FM_GetPlayerWONId,
FM_IsMapValid,
FM_Spawn,
FM_Think,
FM_Use,
FM_Touch,
FM_Blocked,
FM_KeyValue,
FM_SetAbsBox,
FM_ClientConnect,
FM_ClientDisconnect,
FM_ClientKill,
FM_ClientPutInServer,
FM_ClientCommand,
FM_ServerDeactivate,
FM_PlayerPreThink,
FM_PlayerPostThink,
FM_StartFrame,
FM_ParmsNewLevel,
FM_ParmsChangeLevel,
// Returns string describing current .dll. E.g., TeamFotrress 2, Half-Life
// This also gets called when the server is queried for information (for example, by a server browser tool)
FM_GetGameDescription,
// Spectator funcs
FM_SpectatorConnect,
FM_SpectatorDisconnect,
FM_SpectatorThink,
// Notify game .dll that engine is going to shut down. Allows mod authors to set a breakpoint.
FM_Sys_Error,
FM_PM_FindTextureType,
FM_RegisterEncoders,
// Create baselines for certain "unplaced" items.
FM_CreateInstBaselines,
FM_AllowLagCompensation,
FM_AlertMessage,
// NEW_DLL_FUNCTIONS:
FM_OnFreeEntPrivateData,
FM_GameShutdown,
FM_ShouldCollide,
// LATE ADDITIONS (v1.71)
FM_ClientUserInfoChanged,
// LATE ADDITIONS (v1.75)
FM_UpdateClientData,
FM_AddToFullPack,
FM_CmdStart,
FM_CmdEnd,
FM_CreateInstBaseline,
FM_CreateBaseline,
FM_GetInfoKeyBuffer,
FM_ClientPrintf,
// LATE ADDITIONS (v1.80)
FM_ServerPrint
};
enum TraceResult
{
TR_AllSolid, // int
TR_StartSolid, // int
TR_InOpen, // int
TR_InWater, // int
TR_flFraction, // float
TR_vecEndPos, // float array[3]
TR_flPlaneDist, // float
TR_vecPlaneNormal, // float array[3]
TR_pHit, // int (edict_t*)
TR_iHitgroup, // int
};
enum KeyValueData
{
KV_ClassName, // string
KV_KeyName, // string
KV_Value, // string
KV_fHandled // int
};
enum ClientData
{
CD_Origin, // float array[3]
CD_Velocity, // float array[3]
CD_ViewModel, // int
CD_PunchAngle, // float array[3]
CD_Flags, // int
CD_WaterLevel, // int
CD_WaterType, // int
CD_ViewOfs, // float array[3]
CD_Health, // float
CD_bInDuck, // int
CD_Weapons, // int
CD_flTimeStepSound, // int
CD_flDuckTime, // int
CD_flSwimTime, // int
CD_WaterJumpTime, // int
CD_MaxSpeed, // float
CD_FOV, // float
CD_WeaponAnim, // int
CD_ID, // int
CD_AmmoShells, // int
CD_AmmoNails, // int
CD_AmmoCells, // int
CD_AmmoRockets, // int
CD_flNextAttack, // float
CD_tfState, // int
CD_PushMsec, // int
CD_DeadFlag, // int
CD_PhysInfo, // string[256]
CD_iUser1, // int
CD_iUser2, // int
CD_iUser3, // int
CD_iUser4, // int
CD_fUser1, // float
CD_fUser2, // float
CD_fUser3, // float
CD_fUser4, // float
CD_vUser1, // float array[3]
CD_vUser2, // float array[3]
CD_vUser3, // float array[3]
CD_vUser4 // float array[3]
};
enum EntityState
{
// Fields which are filled in by routines outside of delta compression
ES_EntityType, // int
// Index into cl_entities array for this entity
ES_Number, // int
ES_MsgTime, // float
// Message number last time the player/entity state was updated
ES_MessageNum, // int
// Fields which can be transitted and reconstructed over the network stream
ES_Origin, // float array[3]
ES_Angles, // float array[3]
ES_ModelIndex, // int
ES_Sequence, // int
ES_Frame, // float
ES_ColorMap, // int
ES_Skin, // short
ES_Solid, // short
ES_Effects, // int
ES_Scale, // float
ES_eFlags, // byte
// Render information
ES_RenderMode, // int
ES_RenderAmt, // int
ES_RenderColor, // byte array[3], RGB value
ES_RenderFx, // int
ES_MoveType, // int
ES_AnimTime, // float
ES_FrameRate, // float
ES_Body, // int
ES_Controller, // byte array[4]
ES_Blending, // byte array[4]
ES_Velocity, // float array[3]
// Send bbox down to client for use during prediction
ES_Mins, // float array[3]
ES_Maxs, // float array[3]
ES_AimEnt, // int
// If owned by a player, the index of that player (for projectiles)
ES_Owner, // int
// Friction, for prediction
ES_Friction, // float
// Gravity multiplier
ES_Gravity, // float
// PLAYER SPECIFIC
ES_Team, // int
ES_PlayerClass, // int
ES_Health, // int
ES_Spectator, // bool
ES_WeaponModel, // int
ES_GaitSequence, // int
// If standing on conveyor, e.g.
ES_BaseVelocity, // float array[3]
// Use the crouched hull, or the regular player hull
ES_UseHull, // int
// Latched buttons last time state updated
ES_OldButtons, // int
// -1 = in air, else pmove entity number
ES_OnGround, // int
ES_iStepLeft, // int
// How fast we are falling
ES_flFallVelocity, // float
ES_FOV, // float
ES_WeaponAnim, // int
// Parametric movement overrides
ES_StartPos, // float array[3]
ES_EndPos, // float array[3]
ES_ImpactTime, // float
ES_StartTime, // float
// For mods
ES_iUser1, // int
ES_iUser2, // int
ES_iUser3, // int
ES_iUser4, // int
ES_fUser1, // float
ES_fUser2, // float
ES_fUser3, // float
ES_fUser4, // float
ES_vUser1, // float array[3]
ES_vUser2, // float array[3]
ES_vUser3, // float array[3]
ES_vUser4 // float array[3]
};
enum UserCmd
{
// Interpolation time on client
UC_LerpMsec, // short
// Duration in ms of command
UC_Msec, // byte
// Command view angles
UC_ViewAngles, // float array[3]
// Intended velocities
// Forward velocity
UC_ForwardMove, // float
// Sideways velocity
UC_SideMove, // float
// Upward velocity
UC_UpMove, // float
// Light level at spot where we are standing
UC_LightLevel, // byte
// Attack buttons
UC_Buttons, // unsigned short
// Impulse command issued
UC_Impulse, // byte
// Current weapon id
UC_WeaponSelect, // byte
// Experimental player impact stuff
UC_ImpactIndex, // int
UC_ImpactPosition // float array[3]
};
enum AlertType
{
at_notice = 0,
at_console, // same as at_notice, but forces a ConPrintf, not a message box
at_aiconsole, // same as at_console, but only shown if developer level is 2!
at_warning,
at_error,
at_logged // Server print to console (only in multiplayer games)
};
/**
* Data field types for use with find_ent_data_info().
*/
enum FieldType
{
FIELD_NONE,
FIELD_FLOAT, // Floating point value
FIELD_STRINGINT, // String ID (return from ALLOC_STRING)
FIELD_STRINGPTR, // String, pointer-to-char
FIELD_STRING, // String, fixed size
FIELD_CLASSPTR, // Classes pointer derived of CBaseEntity
FIELD_CLASS, // Arbitrary classes, direct
FIELD_STRUCTURE, // Arbitrary structures, direct
FIELD_EHANDLE, // Entity handle
FIELD_ENTVARS, // entvars_t*
FIELD_EDICT, // edict_t*
FIELD_VECTOR, // Vector
FIELD_POINTER, // Arbitrary data pointer
FIELD_INTEGER, // Integer or enum
FIELD_FUNCTION, // Class function pointer (Think, Use, etc)
FIELD_BOOLEAN, // Boolean
FIELD_SHORT, // 2 bytes integer
FIELD_CHARACTER, // 1 byte
};
/**
* Base data field types for use with get_ent_data_basetype().
*/
enum BaseFieldType
{
BASEFIELD_NONE,
BASEFIELD_INTEGER,
BASEFIELD_FLOAT,
BASEFIELD_VECTOR,
BASEFIELD_ENTITY,
BASEFIELD_STRING,
};

View File

@ -0,0 +1,395 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Fakemeta Stocks
//
#if !defined _fakemeta_included
#include <fakemeta>
#endif
#if defined _fakemeta_stocks_included
#endinput
#endif
#define _fakemeta_stocks_included
// EngFuncs
stock EF_PrecacheModel(const string[]) {
return engfunc(EngFunc_PrecacheModel, string);
}
stock EF_PrecacheSound(const string[]) {
return engfunc(EngFunc_PrecacheSound, string);
}
stock EF_SetModel(const ID, const STRING[]) {
return engfunc(EngFunc_SetModel, ID, STRING);
}
stock EF_ModelIndex(const STRING[]) {
return engfunc(EngFunc_ModelIndex, STRING);
}
stock EF_ModelFrames(modelIndex) {
return engfunc(EngFunc_ModelFrames, modelIndex);
}
stock EF_SetSize(const ENTITY, const Float:MIN[3], const Float:MAX[3]) {
return engfunc(EngFunc_SetSize, ENTITY, MIN, MAX);
}
stock EF_ChangeLevel(const S1[], const S2[]) {
return engfunc(EngFunc_ChangeLevel, S1, S2);
}
stock EF_VecToYaw(const Float:VECTOR[3], &Float:returnValue) {
return engfunc(EngFunc_VecToYaw, VECTOR, returnValue);
}
stock EF_VecToAngles(const Float:VECTORIN[3], const Float:VECTOROUT[3]) {
return engfunc(EngFunc_VecToAngles, VECTORIN, VECTOROUT);
}
stock EF_MoveToOrigin(const ENTITY, const Float:GOAL[3], const Float:DISTANCE, const MOVETYPE) {
return engfunc(EngFunc_MoveToOrigin, ENTITY, GOAL, DISTANCE, MOVETYPE);
}
stock EF_ChangeYaw(const ENTITY) {
return engfunc(EngFunc_ChangeYaw, ENTITY);
}
stock EF_ChangePitch(const ENTITY) {
return engfunc(EngFunc_ChangePitch, ENTITY);
}
stock EF_FindEntityByString(const STARTSEARCHAFTER, const FIELD[], const VALUE[]) {
return engfunc(EngFunc_FindEntityByString, STARTSEARCHAFTER, FIELD, VALUE);
}
stock EF_GetEntityIllum(const ENTITY) {
return engfunc(EngFunc_GetEntityIllum, ENTITY);
}
stock EF_FindEntityInSphere(const STARTSEARCHAFTER, const Float:ORIGIN[3], Float:radius) {
return engfunc(EngFunc_FindEntityInSphere, STARTSEARCHAFTER, ORIGIN, radius);
}
stock EF_FindClientInPVS(const CLIENT) {
return engfunc(EngFunc_FindClientInPVS, CLIENT);
}
stock EF_EntitiesInPVS(const CLIENT) {
return engfunc(EngFunc_EntitiesInPVS, CLIENT);
}
stock EF_MakeVectors(const Float:VECTOR[3]) {
return engfunc(EngFunc_MakeVectors, VECTOR);
}
stock EF_AngleVectors(const Float:VECTOR[3], Float:forward_[3], Float:right[3], Float:up[3]) {
return engfunc(EngFunc_AngleVectors, VECTOR, forward_, right, up);
}
stock EF_CreateEntity() {
return engfunc(EngFunc_CreateEntity);
}
stock EF_RemoveEntity(const ENTITY) {
return engfunc(EngFunc_RemoveEntity, ENTITY);
}
stock EF_CreateNamedEntity(const CLASSNAME) {
return engfunc(EngFunc_CreateNamedEntity, CLASSNAME);
}
stock EF_MakeStatic(const ENTITY) {
return engfunc(EngFunc_MakeStatic, ENTITY);
}
stock EF_EntIsOnFloor(const ENTITY) {
return engfunc(EngFunc_EntIsOnFloor, ENTITY);
}
stock EF_DropToFloor(const ENTITY) {
return engfunc(EngFunc_DropToFloor, ENTITY);
}
stock EF_WalkMove(const ENTITY, Float:yaw, Float:distance, iMode) {
return engfunc(EngFunc_WalkMove, ENTITY, yaw, distance, iMode);
}
stock EF_SetOrigin(const ENTITY, const Float:ORIGIN[3]) {
return engfunc(EngFunc_SetOrigin, ENTITY, ORIGIN);
}
stock EF_EmitSound(const ENTITY, channel, const SAMPLE[], Float:volume, Float:attenuation, fFlags, pitch) {
return engfunc(EngFunc_EmitSound, ENTITY, channel, SAMPLE, volume, attenuation, fFlags, pitch);
}
stock EF_EmitAmbientSound(const ENTITY, Float:pos[3], const SAMPLE[], Float:volume, Float:attenuation, fFlags, pitch) {
return engfunc(EngFunc_EmitAmbientSound, ENTITY, pos, SAMPLE, volume, attenuation, fFlags, pitch);
}
stock EF_TraceLine(const Float:V1[3], const Float:V2[3], fNoMonsters, const ENT_TO_SKIP) {
return engfunc(EngFunc_TraceLine, V1, V2, fNoMonsters, ENT_TO_SKIP);
}
stock EF_TraceToss(const ENTITY, const ENTITY_TO_IGNORE) {
return engfunc(EngFunc_TraceToss, ENTITY, ENTITY_TO_IGNORE);
}
stock EF_TraceMonsterHull(const ENTITY, const Float:V1[3], const Float:V2[3], fNoMonsters, const ENTITY_TO_SKIP) {
return engfunc(EngFunc_TraceMonsterHull, ENTITY, V1, V2, fNoMonsters, ENTITY_TO_SKIP);
}
stock EF_TraceHull(const Float:V1[3], const Float:V2[3], fNoMonsters, hullNumber, const ENTITY_TO_SKIP) {
return engfunc(EngFunc_TraceHull, V1, V2, fNoMonsters, hullNumber, ENTITY_TO_SKIP);
}
stock EF_TraceModel(const Float:V1[3], const Float:V2[3], hullNumber, const ENTITY) {
return engfunc(EngFunc_TraceModel, V1, V2, hullNumber, ENTITY);
}
stock EF_TraceTexture(const TEXTURE_ENTITY, const Float:V1[3], const Float:V2[3]) {
return engfunc(EngFunc_TraceTexture, TEXTURE_ENTITY, V1, V2);
}
stock EF_TraceSphere(const Float:V1[3], const Float:V2[3], fNoMonsters, Float:radius, const ENTITY_TO_SKIP) {
return engfunc(EngFunc_TraceSphere, V1, V2, fNoMonsters, radius, ENTITY_TO_SKIP);
}
stock EF_GetAimVector(const ENTITY, Float:speed, Float:returnVector[3]) {
return engfunc(EngFunc_GetAimVector, ENTITY, speed, returnVector);
}
stock EF_ParticleEffect(const Float:ORIGIN[3], const Float:DIRECTION[3], Float:color, Float:count) {
return engfunc(EngFunc_ParticleEffect, ORIGIN, DIRECTION, color, count);
}
stock EF_LightStyle(style, val[]) {
return engfunc(EngFunc_LightStyle, style, val);
}
stock EF_DecalIndex(const NAME[]) {
return engfunc(EngFunc_DecalIndex, NAME);
}
stock EF_PointContents(const Float:VECTOR[3]) {
return engfunc(EngFunc_PointContents, VECTOR);
}
stock EF_FreeEntPrivateData(const ENTITY) {
return engfunc(EngFunc_FreeEntPrivateData, ENTITY);
}
stock EF_SzFromIndex(iString) {
return engfunc(EngFunc_SzFromIndex, iString);
}
stock EF_AllocString(const STRING[]) {
return engfunc(EngFunc_AllocString, STRING);
}
stock EF_RegUserMsg(const NAME[], iSize) {
return engfunc(EngFunc_RegUserMsg, NAME, iSize);
}
stock EF_AnimationAutomove(const ENTITY, Float:flTime) {
return engfunc(EngFunc_AnimationAutomove, ENTITY, flTime);
}
stock EF_GetBonePosition(const ENTITY, iBone, Float:origin[3], Float:angles[3]) {
return engfunc(EngFunc_GetBonePosition, ENTITY, iBone, origin, angles);
}
stock EF_GetAttachment(const ENTITY, iAttachment, Float:origin[3], Float:angles[3]) {
return engfunc(EngFunc_GetAttachment, ENTITY, iAttachment, origin, angles);
}
stock EF_SetView(const CLIENT, const VIEW_ENTITY) {
return engfunc(EngFunc_SetView, CLIENT, VIEW_ENTITY);
}
stock EF_Time(&Float:returnValue) {
return engfunc(EngFunc_Time, returnValue);
}
stock EF_CrosshairAngle(const CLIENT, Float:pitch, Float:yaw) {
return engfunc(EngFunc_CrosshairAngle, CLIENT, pitch, yaw);
}
stock EF_FadeClientVolume(const ENTITY, fadePercent, fadeOutSeconds, holdTime, fadeInSeconds) {
return engfunc(EngFunc_FadeClientVolume, ENTITY, fadePercent, fadeOutSeconds, holdTime, fadeInSeconds);
}
stock EF_SetClientMaxspeed(const ENTITY, Float:newMaxspeed) {
return engfunc(EngFunc_SetClientMaxspeed, ENTITY, newMaxspeed);
}
stock EF_CreateFakeClient(const NETNAME[]) {
return engfunc(EngFunc_CreateFakeClient, NETNAME);
}
stock EF_RunPlayerMove(const FAKECLIENT, const Float:VIEWANGLES[3], Float:forwardmove, Float:sidemove, Float:upmove, buttons, impulse, msec) {
return engfunc(EngFunc_RunPlayerMove, FAKECLIENT, VIEWANGLES, forwardmove, sidemove, upmove, buttons, impulse, msec);
}
stock EF_NumberOfEntities() {
return engfunc(EngFunc_NumberOfEntities);
}
stock EF_StaticDecal(const Float:ORIGIN[3], decalIndex, entityIndex, modelIndex)
return engfunc(EngFunc_StaticDecal, ORIGIN, decalIndex, entityIndex, modelIndex);
stock EF_PrecacheGeneric(const STRING[]) {
return engfunc(EngFunc_PrecacheGeneric, STRING);
}
stock EF_BuildSoundMSG(const ENTITY, channel, const SAMPLE[], Float:volume, Float:attenuation, fFlags, pitch, msg_dest, msg_type, const Float:ORIGIN[3], const ED) {
return engfunc(EngFunc_BuildSoundMsg, ENTITY, channel, SAMPLE, volume, attenuation, fFlags, pitch, msg_dest, msg_type, ORIGIN, ED);
}
stock EF_GetPhysicsKeyValue(const CLIENT, const KEY[]) {
return engfunc(EngFunc_GetPhysicsKeyValue, CLIENT, KEY);
}
stock EF_SetPhysicsKeyValue(const CLIENT, const KEY[], const VALUE[]) {
return engfunc(EngFunc_SetPhysicsKeyValue, CLIENT, KEY, VALUE);
}
stock EF_GetPhysicsInfoString(const CLIENT, returnString[], maxLength) {
return engfunc(EngFunc_GetPhysicsInfoString, CLIENT, returnString, maxLength);
}
stock EF_PrecacheEvent(type, const STRING[]) {
return engfunc(EngFunc_PrecacheEvent, type, STRING);
}
stock EF_PlaybackEvent(flags, const INVOKER, eventindex, Float:delay, Float:origin[3], Float:angles[3], Float:fparam1, Float:fparam2, iparam1, iparam2, bparam1, bparam2) {
return engfunc(EngFunc_PlaybackEvent, flags, INVOKER, eventindex, delay, origin, angles, fparam1, fparam2, iparam1, iparam2, bparam1, bparam2);
}
stock EF_CheckVisibility(const ENTITY, set) {
return engfunc(EngFunc_CheckVisibility, ENTITY, set);
}
stock EF_GetCurrentPlayer() {
return engfunc(EngFunc_GetCurrentPlayer);
}
stock EF_CanSkipPlayer(const PLAYER) {
return engfunc(EngFunc_CanSkipPlayer, PLAYER);
}
stock EF_SetGroupMask(mask, op) {
return engfunc(EngFunc_SetGroupMask, mask, op);
}
stock EF_GetClientListening(receiver, sender) {
return engfunc(EngFunc_GetClientListening, receiver, sender);
}
stock EF_SetClientListening(receiver, sender, bool:listen) {
return engfunc(EngFunc_SetClientListening, receiver, sender, listen);
}
stock EF_MessageBegin(msg_dest, msg_type, const Float:ORIGIN[3], const ED) {
return engfunc(EngFunc_MessageBegin, msg_dest, msg_type, ORIGIN, ED);
}
stock EF_WriteCoord(Float:value) {
return engfunc(EngFunc_WriteCoord, value);
}
stock EF_WriteAngle(Float:value) {
return engfunc(EngFunc_WriteAngle, value);
}
stock EF_InfoKeyValue(const INFOBUFFER, const KEY[], returnValue[], maxLength) {
return engfunc(EngFunc_InfoKeyValue, INFOBUFFER, KEY, returnValue, maxLength);
}
stock EF_SetKeyValue(const INFOBUFFER, const KEY[], const VALUE[]) {
return engfunc(EngFunc_SetKeyValue, INFOBUFFER, KEY, VALUE);
}
stock EF_SetClientKeyValue(const ID, const INFOBUFFER, const KEY[], const VALUE[]) {
return engfunc(EngFunc_SetClientKeyValue, ID, INFOBUFFER, KEY, VALUE);
}
stock EF_CreateInstBaseline(CLASSNAME, baseline) {
return engfunc(EngFunc_CreateInstBaseline, CLASSNAME, baseline);
}
// Returns pointer to info buffer that can be used with the INFOBUFFER param
// of EF_InfoKeyValue, EF_SetKeyValue, and EF_SetClientKeyValue
stock EF_GetInfoKeyBuffer(const ENTITY) {
return engfunc(EngFunc_GetInfoKeyBuffer, ENTITY);
}
stock EF_ClientPrintf(const ENTITY, const printType, const MESSAGE[]) {
return engfunc(EngFunc_ClientPrintf, ENTITY, printType, MESSAGE);
}
stock EF_ServerPrint(const MESSAGE[]) {
return engfunc(EngFunc_ServerPrint, MESSAGE);
}
// DLLFuncs
stock DF_GameInit() {
return dllfunc(DLLFunc_GameInit);
}
stock DF_Spawn(const ENTITY) {
return dllfunc(DLLFunc_Spawn, ENTITY);
}
stock DF_Think(const ENTITY) {
return dllfunc(DLLFunc_Think, ENTITY);
}
stock DF_Use(const ENT_Used, const ENT_User) {
return dllfunc(DLLFunc_Use, ENT_Used, ENT_User);
}
stock DF_Touch(const ENT_Touched, const ENT_Toucher) {
return dllfunc(DLLFunc_Touch, ENT_Touched, ENT_Toucher);
}
stock DF_Blocked(const ENT_Blocked, const ENT_Other) {
return dllfunc(DLLFunc_Blocked, ENT_Blocked, ENT_Other);
}
stock DF_SetAbsBox(const ENTITY) {
return dllfunc(DLLFunc_SetAbsBox, ENTITY);
}
stock DF_ClientConnect(const ENTITY, const NAME[], const ADDRESS[], RejectReason[128]) {
return dllfunc(DLLFunc_ClientConnect, ENTITY, NAME, ADDRESS, RejectReason);
}
stock DF_ClientDisconnect(const ENTITY) {
return dllfunc(DLLFunc_ClientDisconnect, ENTITY);
}
stock DF_ClientKill(const ENTITY) {
return dllfunc(DLLFunc_ClientKill, ENTITY);
}
stock DF_ClientPutInServer(const ENTITY) {
return dllfunc(DLLFunc_ClientPutInServer, ENTITY);
}
stock DF_ClientCommand(const ENTITY) {
return dllfunc(DLLFunc_ClientCommand, ENTITY);
}
stock DF_ServerDeactivate() {
return dllfunc(DLLFunc_ServerDeactivate);
}
stock DF_PlayerPreThink(const ENTITY) {
return dllfunc(DLLFunc_PlayerPreThink, ENTITY);
}
stock DF_PlayerPostThink(const ENTITY) {
return dllfunc(DLLFunc_PlayerPostThink, ENTITY);
}
stock DF_StartFrame() {
return dllfunc(DLLFunc_StartFrame);
}
stock DF_ParmsNewLevel() {
return dllfunc(DLLFunc_ParmsNewLevel);
}
stock DF_ParmsChangeLevel() {
return dllfunc(DLLFunc_ParmsChangeLevel);
}
stock DF_GetGameDescription() {
return dllfunc(DLLFunc_GetGameDescription);
}
stock DF_SpectatorConnect(const ENTITY) {
return dllfunc(DLLFunc_SpectatorConnect, ENTITY);
}
stock DF_SpectatorDisconnect(const ENTITY) {
return dllfunc(DLLFunc_SpectatorDisconnect, ENTITY);
}
stock DF_SpectatorThink(const ENTITY) {
return dllfunc(DLLFunc_SpectatorThink, ENTITY);
}
stock DF_Sys_Error(const ERROR_STRING[]) {
return dllfunc(DLLFunc_Sys_Error, ERROR_STRING);
}
stock DF_PM_FindTextureType(name[]) {
return dllfunc(DLLFunc_PM_FindTextureType, name);
}
stock DF_RegisterEncoders() {
return dllfunc(DLLFunc_RegisterEncoders);
}
stock DF_GetHullBounds(hullnumber, Float:mins[3], Float:maxs[3]) {
return dllfunc(DLLFunc_GetHullBounds, hullnumber, mins, maxs);
}
stock DF_CreateInstBaselines() {
return dllfunc(DLLFunc_CreateInstBaselines);
}
stock DF_pfnAllowLagCompensation() {
return dllfunc(DLLFunc_pfnAllowLagCompensation);
}
stock DF_MetaFunc_CallGameEntity(const STRING[], const ENTITY) {
return dllfunc(MetaFunc_CallGameEntity, STRING, ENTITY);
}
stock DF_ClientUserInfoChanged(const IDPLAYER) {
return dllfunc(DLLFunc_ClientUserInfoChanged, IDPLAYER);
}
stock DF_UpdateClientData(const ENTITY, sendweapons, const cd/* = 0*/) {
return dllfunc(DLLFunc_UpdateClientData, ENTITY, sendweapons, cd);
}
stock DF_AddToFullPack(const STATE/* = 0*/, e, ENT, HOST, hostflags, player, set) {
return dllfunc(DLLFunc_AddToFullPack, STATE, e, ENT, HOST, hostflags, player, set);
}
stock DF_CmdStart(const PLAYER, const CMD/* = 0*/, randomSeed) {
return dllfunc(DLLFunc_CmdStart, PLAYER, CMD, randomSeed);
}
stock DF_CmdEnd(const PLAYER) {
return dllfunc(DLLFunc_CmdEnd, PLAYER);
}
stock DF_CreateBaseline(PLAYER, eIndex, baseline, playerModelIndex, Float:playerMins[3], Float:playerMaxs[3]) {
return dllfunc(DLLFunc_CreateBaseline, PLAYER, eIndex, baseline, playerModelIndex, playerMins, playerMaxs);
}

View File

@ -0,0 +1,882 @@
/**
* This file provides various utility functions that use the Fakemeta module.
* This file is created and maintained by VEN.
* For support and issues, see:
* http://forums.alliedmods.net/showthread.php?t=28284
*/
/* Fakemeta Utilities
*
* by VEN
*
* This file is provided as is (no warranties).
*/
#if !defined _fakemeta_included
#include <fakemeta>
#endif
#if defined _fakemeta_util_included
#endinput
#endif
#define _fakemeta_util_included
#include <xs>
/* Engine functions */
#define fm_precache_generic(%1) engfunc(EngFunc_PrecacheGeneric, %1)
/* stock fm_precache_generic(const file[])
return engfunc(EngFunc_PrecacheGeneric, file) */
#define fm_precache_event(%1,%2) engfunc(EngFunc_PrecacheEvent, %1, %2)
/* stock fm_precache_event(type, const name[])
return engfunc(EngFunc_PrecacheEvent, type, name) */
// ported by v3x
#define fm_drop_to_floor(%1) engfunc(EngFunc_DropToFloor, %1)
/* stock fm_drop_to_floor(entity)
return engfunc(EngFunc_DropToFloor, entity) */
#define fm_force_use(%1,%2) dllfunc(DLLFunc_Use, %2, %1)
/* stock fm_force_use(user, used)
return dllfunc(DLLFunc_Use, used, user) */
#define fm_entity_set_size(%1,%2,%3) engfunc(EngFunc_SetSize, %1, %2, %3)
/* stock fm_entity_set_size(index, const Float:mins[3], const Float:maxs[3])
return engfunc(EngFunc_SetSize, index, mins, maxs) */
#define fm_get_decal_index(%1) engfunc(EngFunc_DecalIndex, %1)
/* stock fm_get_decal_index(const decalname[])
return engfunc(EngFunc_DecalIndex, decalname) */
stock Float:fm_entity_range(ent1, ent2) {
new Float:origin1[3], Float:origin2[3];
pev(ent1, pev_origin, origin1);
pev(ent2, pev_origin, origin2);
return get_distance_f(origin1, origin2);
}
// based on KoST's port, upgraded version fits into the macros
#define fm_create_entity(%1) engfunc(EngFunc_CreateNamedEntity, engfunc(EngFunc_AllocString, %1))
/* stock fm_create_entity(const classname[])
return engfunc(EngFunc_CreateNamedEntity, engfunc(EngFunc_AllocString, classname)) */
#define fm_find_ent_by_class(%1,%2) engfunc(EngFunc_FindEntityByString, %1, "classname", %2)
/* stock fm_find_ent_by_class(index, const classname[])
return engfunc(EngFunc_FindEntityByString, index, "classname", classname) */
stock fm_find_ent_by_owner(index, const classname[], owner, jghgtype = 0) {
new strtype[11] = "classname", ent = index;
switch (jghgtype) {
case 1: strtype = "target";
case 2: strtype = "targetname";
}
while ((ent = engfunc(EngFunc_FindEntityByString, ent, strtype, classname)) && pev(ent, pev_owner) != owner) {}
return ent;
}
#define fm_find_ent_by_target(%1,%2) engfunc(EngFunc_FindEntityByString, %1, "target", %2)
/* stock fm_find_ent_by_target(index, const target[])
return engfunc(EngFunc_FindEntityByString, index, "target", target) */
#define fm_find_ent_by_tname(%1,%2) engfunc(EngFunc_FindEntityByString, %1, "targetname", %2)
/* stock fm_find_ent_by_tname(index, const targetname[])
return engfunc(EngFunc_FindEntityByString, index, "targetname", targetname) */
stock fm_find_ent_by_model(index, const classname[], const model[]) {
new ent = index, mdl[72];
while ((ent = fm_find_ent_by_class(ent, classname))) {
pev(ent, pev_model, mdl, sizeof mdl - 1);
if (equal(mdl, model))
return ent;
}
return 0;
}
#define fm_find_ent_in_sphere(%1,%2,%3) engfunc(EngFunc_FindEntityInSphere, %1, %2, %3)
/* stock fm_find_ent_in_sphere(index, const Float:origin[3], Float:radius)
return engfunc(EngFunc_FindEntityInSphere, index, origin, radius) */
#define fm_call_think(%1) dllfunc(DLLFunc_Think, %1)
/* stock fm_call_think(entity)
return dllfunc(DLLFunc_Think, entity) */
#define fm_is_valid_ent(%1) pev_valid(%1)
/* stock fm_is_valid_ent(index)
return pev_valid(index) */
stock fm_entity_set_origin(index, const Float:origin[3]) {
new Float:mins[3], Float:maxs[3];
pev(index, pev_mins, mins);
pev(index, pev_maxs, maxs);
engfunc(EngFunc_SetSize, index, mins, maxs);
return engfunc(EngFunc_SetOrigin, index, origin);
}
#define fm_entity_set_model(%1,%2) engfunc(EngFunc_SetModel, %1, %2)
/* stock fm_entity_set_model(index, const model[])
return engfunc(EngFunc_SetModel, index, model) */
// ported by v3x
#define fm_remove_entity(%1) engfunc(EngFunc_RemoveEntity, %1)
/* stock fm_remove_entity(index)
return engfunc(EngFunc_RemoveEntity, index) */
#define fm_entity_count() engfunc(EngFunc_NumberOfEntities)
/* stock fm_entity_count()
return engfunc(EngFunc_NumberOfEntities) */
#define fm_fake_touch(%1,%2) dllfunc(DLLFunc_Touch, %1, %2)
/* stock fm_fake_touch(toucher, touched)
return dllfunc(DLLFunc_Touch, toucher, touched) */
#define fm_DispatchSpawn(%1) dllfunc(DLLFunc_Spawn, %1)
/* stock fm_DispatchSpawn(entity)
return dllfunc(DLLFunc_Spawn, entity) */
// ported by v3x
#define fm_point_contents(%1) engfunc(EngFunc_PointContents, %1)
/* stock fm_point_contents(const Float:point[3])
return engfunc(EngFunc_PointContents, point) */
stock fm_trace_line(ignoreent, const Float:start[3], const Float:end[3], Float:ret[3]) {
engfunc(EngFunc_TraceLine, start, end, ignoreent == -1 ? 1 : 0, ignoreent, 0);
new ent = get_tr2(0, TR_pHit);
get_tr2(0, TR_vecEndPos, ret);
return pev_valid(ent) ? ent : 0;
}
stock fm_trace_hull(const Float:origin[3], hull, ignoredent = 0, ignoremonsters = 0) {
new result = 0;
engfunc(EngFunc_TraceHull, origin, origin, ignoremonsters, hull, ignoredent > 0 ? ignoredent : 0, 0);
if (get_tr2(0, TR_StartSolid))
result += 1;
if (get_tr2(0, TR_AllSolid))
result += 2;
if (!get_tr2(0, TR_InOpen))
result += 4;
return result;
}
stock fm_trace_normal(ignoreent, const Float:start[3], const Float:end[3], Float:ret[3]) {
engfunc(EngFunc_TraceLine, start, end, 0, ignoreent, 0);
get_tr2(0, TR_vecPlaneNormal, ret);
new Float:fraction;
get_tr2(0, TR_flFraction, fraction);
if (fraction >= 1.0)
return 0;
return 1;
}
// note that for CS planted C4 has a "grenade" classname as well
stock fm_get_grenade_id(id, model[], len, grenadeid = 0) {
new ent = fm_find_ent_by_owner(grenadeid, "grenade", id);
if (ent && len > 0)
pev(ent, pev_model, model, len);
return ent;
}
#define fm_halflife_time() get_gametime()
/* stock Float:fm_halflife_time()
return get_gametime() */
#define fm_attach_view(%1,%2) engfunc(EngFunc_SetView, %1, %2)
/* stock fm_attach_view(index, entity)
return engfunc(EngFunc_SetView, index, entity) */
stock fm_playback_event(flags, invoker, eventindex, Float:delay, const Float:origin[3], const Float:angles[3], Float:fparam1, Float:fparam2, iparam1, iparam2, bparam1, bparam2) {
return engfunc(EngFunc_PlaybackEvent, flags, invoker, eventindex, delay, origin, angles, fparam1, fparam2, iparam1, iparam2, bparam1, bparam2);
}
#define fm_eng_get_string(%1,%2,%3) engfunc(EngFunc_SzFromIndex, %1, %2, %3)
/* stock fm_eng_get_string(istring, string[], len)
return engfunc(EngFunc_SzFromIndex, istring, string, len) */
/* HLSDK functions */
// the dot product is performed in 2d, making the view cone infinitely tall
stock bool:fm_is_in_viewcone(index, const Float:point[3]) {
new Float:angles[3];
pev(index, pev_angles, angles);
engfunc(EngFunc_MakeVectors, angles);
global_get(glb_v_forward, angles);
angles[2] = 0.0;
new Float:origin[3], Float:diff[3], Float:norm[3];
pev(index, pev_origin, origin);
xs_vec_sub(point, origin, diff);
diff[2] = 0.0;
xs_vec_normalize(diff, norm);
new Float:dot, Float:fov;
dot = xs_vec_dot(norm, angles);
pev(index, pev_fov, fov);
if (dot >= floatcos(fov * M_PI / 360))
return true;
return false;
}
stock bool:fm_is_visible(index, const Float:point[3], ignoremonsters = 0) {
new Float:start[3], Float:view_ofs[3];
pev(index, pev_origin, start);
pev(index, pev_view_ofs, view_ofs);
xs_vec_add(start, view_ofs, start);
engfunc(EngFunc_TraceLine, start, point, ignoremonsters, index, 0);
new Float:fraction;
get_tr2(0, TR_flFraction, fraction);
if (fraction == 1.0)
return true;
return false;
}
/* Engine_stocks functions */
stock fm_fakedamage(victim, const classname[], Float:takedmgdamage, damagetype) {
new class[] = "trigger_hurt";
new entity = fm_create_entity(class);
if (!entity)
return 0;
new value[16];
float_to_str(takedmgdamage * 2, value, sizeof value - 1);
fm_set_kvd(entity, "dmg", value, class);
num_to_str(damagetype, value, sizeof value - 1);
fm_set_kvd(entity, "damagetype", value, class);
fm_set_kvd(entity, "origin", "8192 8192 8192", class);
fm_DispatchSpawn(entity);
set_pev(entity, pev_classname, classname);
fm_fake_touch(entity, victim);
fm_remove_entity(entity);
return 1;
}
#define fm_find_ent(%1,%2) engfunc(EngFunc_FindEntityByString, %1, "classname", %2)
/* stock fm_find_ent(index, const classname[])
return engfunc(EngFunc_FindEntityByString, index, "classname", classname) */
#define fm_get_user_button(%1) pev(%1, pev_button)
/* stock fm_get_user_button(index)
return pev(index, pev_button) */
#define fm_get_user_oldbutton(%1) pev(%1, pev_oldbuttons)
/* stock fm_get_user_oldbutton(index)
return pev(index, pev_oldbuttons) */
#define fm_get_entity_flags(%1) pev(%1, pev_flags)
/* stock fm_get_entity_flags(index)
return pev(index, pev_flags) */
#define fm_get_entity_distance(%1,%2) floatround(fm_entity_range(%1, %2))
/* stock fm_get_entity_distance(ent1, ent2)
return floatround(fm_entity_range(ent1, ent2)) */
#define fm_get_grenade(%1) fm_get_grenade_id(%1, "", 0)
/* stock fm_get_grenade(id)
return fm_get_grenade_id(id, "", 0) */
// optimization idea by Orangutanz
stock fm_get_brush_entity_origin(index, Float:origin[3]) {
new Float:mins[3], Float:maxs[3];
pev(index, pev_origin, origin);
pev(index, pev_mins, mins);
pev(index, pev_maxs, maxs);
origin[0] += (mins[0] + maxs[0]) * 0.5;
origin[1] += (mins[1] + maxs[1]) * 0.5;
origin[2] += (mins[2] + maxs[2]) * 0.5;
return 1;
}
// based on v3x's port, upgraded version returns number of removed entities
stock fm_remove_entity_name(const classname[]) {
new ent = -1, num = 0;
while ((ent = fm_find_ent_by_class(ent, classname)))
num += fm_remove_entity(ent);
return num;
}
stock fm_ViewContents(id) {
new origin[3], Float:Orig[3];
get_user_origin(id, origin, Origin_AimEndEyes);
IVecFVec(origin, Orig);
return fm_point_contents(Orig);
}
stock fm_get_speed(entity) {
new Float:Vel[3];
pev(entity, pev_velocity, Vel);
return floatround(vector_length(Vel));
}
stock fm_set_rendering(entity, fx = kRenderFxNone, r = 255, g = 255, b = 255, render = kRenderNormal, amount = 16) {
new Float:RenderColor[3];
RenderColor[0] = float(r);
RenderColor[1] = float(g);
RenderColor[2] = float(b);
set_pev(entity, pev_renderfx, fx);
set_pev(entity, pev_rendercolor, RenderColor);
set_pev(entity, pev_rendermode, render);
set_pev(entity, pev_renderamt, float(amount));
return 1;
}
stock fm_set_entity_flags(index, flag, onoff) {
new flags = pev(index, pev_flags);
if ((flags & flag) > 0)
return onoff == 1 ? 2 : 1 + 0 * set_pev(index, pev_flags, flags - flag);
else
return onoff == 0 ? 2 : 1 + 0 * set_pev(index, pev_flags, flags + flag);
return 0;
}
stock fm_set_entity_visibility(index, visible = 1) {
set_pev(index, pev_effects, visible == 1 ? pev(index, pev_effects) & ~EF_NODRAW : pev(index, pev_effects) | EF_NODRAW);
return 1;
}
#define fm_get_entity_visibility(%1) (!(pev(%1, pev_effects) & EF_NODRAW))
/* stock fm_get_entity_visibility(index)
return !(pev(index, pev_effects) & EF_NODRAW) */
stock fm_set_user_velocity(entity, const Float:vector[3]) {
set_pev(entity, pev_velocity, vector);
return 1;
}
#define fm_get_user_velocity(%1,%2) pev(%1, pev_velocity, %2)
/* stock fm_get_user_velocity(entity, Float:vector[3])
return pev(entity, pev_velocity, vector) */
/* Fun functions */
#define fm_get_client_listen(%1,%2) engfunc(EngFunc_GetClientListening, %1, %2)
/* stock fm_get_client_listen(receiver, sender)
return engfunc(EngFunc_GetClientListening, receiver, sender) */
#define fm_set_client_listen(%1,%2,%3) engfunc(EngFunc_SetClientListening, %1, %2, %3)
/* stock fm_set_client_listen(receiver, sender, listen)
return engfunc(EngFunc_SetClientListening, receiver, sender, listen) */
stock fm_get_user_godmode(index) {
new Float:val;
pev(index, pev_takedamage, val);
return (val == DAMAGE_NO);
}
stock fm_set_user_godmode(index, godmode = 0) {
set_pev(index, pev_takedamage, godmode == 1 ? DAMAGE_NO : DAMAGE_AIM);
return 1;
}
stock fm_set_user_armor(index, armor) {
set_pev(index, pev_armorvalue, float(armor));
return 1;
}
stock fm_set_user_health(index, health) {
health > 0 ? set_pev(index, pev_health, float(health)) : dllfunc(DLLFunc_ClientKill, index);
return 1;
}
stock fm_set_user_origin(index, /* const */ origin[3]) {
new Float:orig[3];
IVecFVec(origin, orig);
return fm_entity_set_origin(index, orig);
}
stock fm_set_user_rendering(index, fx = kRenderFxNone, r = 255, g = 255, b = 255, render = kRenderNormal, amount = 16) {
return fm_set_rendering(index, fx, r, g, b, render, amount);
}
stock fm_give_item(index, const item[]) {
if (!equal(item, "weapon_", 7) && !equal(item, "ammo_", 5) && !equal(item, "item_", 5) && !equal(item, "tf_weapon_", 10))
return 0;
new ent = fm_create_entity(item);
if (!pev_valid(ent))
return 0;
new Float:origin[3];
pev(index, pev_origin, origin);
set_pev(ent, pev_origin, origin);
set_pev(ent, pev_spawnflags, pev(ent, pev_spawnflags) | SF_NORESPAWN);
dllfunc(DLLFunc_Spawn, ent);
new save = pev(ent, pev_solid);
dllfunc(DLLFunc_Touch, ent, index);
if (pev(ent, pev_solid) != save)
return ent;
engfunc(EngFunc_RemoveEntity, ent);
return -1;
}
stock fm_set_user_maxspeed(index, Float:speed = -1.0) {
engfunc(EngFunc_SetClientMaxspeed, index, speed);
set_pev(index, pev_maxspeed, speed);
return 1;
}
stock Float:fm_get_user_maxspeed(index) {
new Float:speed;
pev(index, pev_maxspeed, speed);
return speed;
}
stock fm_set_user_gravity(index, Float:gravity = 1.0) {
set_pev(index, pev_gravity, gravity);
return 1;
}
stock Float:fm_get_user_gravity(index) {
new Float:gravity;
pev(index, pev_gravity, gravity);
return gravity;
}
/* interferes with FM_Spawn enum, just use fm_DispatchSpawn
stock fm_spawn(entity) {
return dllfunc(DLLFunc_Spawn, entity)
}
*/
stock fm_set_user_noclip(index, noclip = 0) {
set_pev(index, pev_movetype, noclip == 1 ? MOVETYPE_NOCLIP : MOVETYPE_WALK);
return 1;
}
#define fm_get_user_noclip(%1) (pev(%1, pev_movetype) == MOVETYPE_NOCLIP)
/* stock fm_get_user_noclip(index)
return (pev(index, pev_movetype) == MOVETYPE_NOCLIP) */
// note: get_user_weapon will still return former weapon index
stock fm_strip_user_weapons(index) {
new ent = fm_create_entity("player_weaponstrip");
if (!pev_valid(ent))
return 0;
dllfunc(DLLFunc_Spawn, ent);
dllfunc(DLLFunc_Use, ent, index);
engfunc(EngFunc_RemoveEntity, ent);
return 1;
}
stock fm_set_user_frags(index, frags) {
set_pev(index, pev_frags, float(frags));
return 1;
}
/* Cstrike functions */
stock fm_cs_user_spawn(index) {
set_pev(index, pev_deadflag, DEAD_RESPAWNABLE);
dllfunc(DLLFunc_Spawn, index);
set_pev(index, pev_iuser1, 0);
return 1;
}
/* Custom functions */
// based on Basic-Master's set_keyvalue, upgraded version accepts an optional classname (a bit more efficient if it is passed)
stock fm_set_kvd(entity, const key[], const value[], const classname[] = "") {
if (classname[0])
set_kvd(0, KV_ClassName, classname);
else {
new class[32];
pev(entity, pev_classname, class, sizeof class - 1);
set_kvd(0, KV_ClassName, class);
}
set_kvd(0, KV_KeyName, key);
set_kvd(0, KV_Value, value);
set_kvd(0, KV_fHandled, 0);
return dllfunc(DLLFunc_KeyValue, entity, 0);
}
stock fm_find_ent_by_integer(index, pev_field, value) {
static maxents;
if (!maxents)
maxents = global_get(glb_maxEntities);
for (new i = index + 1; i < maxents; ++i) {
if (pev_valid(i) && pev(i, pev_field) == value)
return i;
}
return 0;
}
stock fm_find_ent_by_flags(index, pev_field, flags) {
static maxents;
if (!maxents)
maxents = global_get(glb_maxEntities);
for (new i = index + 1; i < maxents; ++i) {
if (pev_valid(i) && (pev(i, pev_field) & flags) == flags)
return i;
}
return 0;
}
stock Float:fm_distance_to_box(const Float:point[3], const Float:mins[3], const Float:maxs[3]) {
new Float:dist[3];
for (new i = 0; i < 3; ++i) {
if (point[i] > maxs[i])
dist[i] = point[i] - maxs[i];
else if (mins[i] > point[i])
dist[i] = mins[i] - point[i];
}
return vector_length(dist);
}
stock Float:fm_boxes_distance(const Float:mins1[3], const Float:maxs1[3], const Float:mins2[3], const Float:maxs2[3]) {
new Float:dist[3];
for (new i = 0; i < 3; ++i) {
if (mins1[i] > maxs2[i])
dist[i] = mins1[i] - maxs2[i];
else if (mins2[i] > maxs1[i])
dist[i] = mins2[i] - maxs1[i];
}
return vector_length(dist);
}
stock Float:fm_distance_to_boxent(entity, boxent) {
new Float:point[3];
pev(entity, pev_origin, point);
new Float:mins[3], Float:maxs[3];
pev(boxent, pev_absmin, mins);
pev(boxent, pev_absmax, maxs);
return fm_distance_to_box(point, mins, maxs);
}
stock Float:fm_boxents_distance(boxent1, boxent2) {
new Float:mins1[3], Float:maxs1[3];
pev(boxent1, pev_absmin, mins1);
pev(boxent1, pev_absmax, maxs1);
new Float:mins2[3], Float:maxs2[3];
pev(boxent2, pev_absmin, mins2);
pev(boxent2, pev_absmax, maxs2);
return fm_boxes_distance(mins1, maxs1, mins2, maxs2);
}
// projects a center of a player's feet base (originally by P34nut, improved)
stock Float:fm_distance_to_floor(index, ignoremonsters = 1) {
new Float:start[3], Float:dest[3], Float:end[3];
pev(index, pev_origin, start);
dest[0] = start[0];
dest[1] = start[1];
dest[2] = -8191.0;
engfunc(EngFunc_TraceLine, start, dest, ignoremonsters, index, 0);
get_tr2(0, TR_vecEndPos, end);
pev(index, pev_absmin, start);
new Float:ret = start[2] - end[2];
return ret > 0 ? ret : 0.0;
}
// potential to crash (?) if used on weaponbox+weapon_* entity pair (use fm_remove_weaponbox instead)
stock fm_kill_entity(index) {
set_pev(index, pev_flags, pev(index, pev_flags) | FL_KILLME);
return 1;
}
// if weapon index isn't passed then assuming that it's the current weapon
stock fm_get_user_weapon_entity(id, wid = 0) {
new weap = wid, clip, ammo;
if (!weap && !(weap = get_user_weapon(id, clip, ammo)))
return 0;
new class[32];
get_weaponname(weap, class, sizeof class - 1);
return fm_find_ent_by_owner(-1, class, id);
}
// only weapon index or its name can be passed, if neither is passed then the current gun will be stripped
stock bool:fm_strip_user_gun(index, wid = 0, const wname[] = "") {
new ent_class[32];
if (!wid && wname[0])
copy(ent_class, sizeof ent_class - 1, wname);
else {
new weapon = wid, clip, ammo;
if (!weapon && !(weapon = get_user_weapon(index, clip, ammo)))
return false;
get_weaponname(weapon, ent_class, sizeof ent_class - 1);
}
new ent_weap = fm_find_ent_by_owner(-1, ent_class, index);
if (!ent_weap)
return false;
engclient_cmd(index, "drop", ent_class);
new ent_box = pev(ent_weap, pev_owner);
if (!ent_box || ent_box == index)
return false;
dllfunc(DLLFunc_Think, ent_box);
return true;
}
// only weapon index or its name can be passed, if neither is passed then the current gun will be transferred
stock bool:fm_transfer_user_gun(index1, index2, wid = 0, const wname[] = "") {
new ent_class[32];
if (!wid && wname[0])
copy(ent_class, sizeof ent_class - 1, wname);
else {
new weapon = wid, clip, ammo;
if (!weapon && !(weapon = get_user_weapon(index1, clip, ammo)))
return false;
get_weaponname(weapon, ent_class, sizeof ent_class - 1);
}
new ent_weap = fm_find_ent_by_owner(-1, ent_class, index1);
if (!ent_weap)
return false;
engclient_cmd(index1, "drop", ent_class);
new ent_box = pev(ent_weap, pev_owner);
if (!ent_box || ent_box == index1)
return false;
set_pev(ent_box, pev_flags, pev(ent_box, pev_flags) | FL_ONGROUND);
dllfunc(DLLFunc_Touch, ent_box, index2);
if (pev(ent_weap, pev_owner) != index2)
return false;
return true;
}
stock bool:fm_is_ent_visible(index, entity, ignoremonsters = 0) {
new Float:start[3], Float:dest[3];
pev(index, pev_origin, start);
pev(index, pev_view_ofs, dest);
xs_vec_add(start, dest, start);
pev(entity, pev_origin, dest);
engfunc(EngFunc_TraceLine, start, dest, ignoremonsters, index, 0);
new Float:fraction;
get_tr2(0, TR_flFraction, fraction);
if (fraction == 1.0 || get_tr2(0, TR_pHit) == entity)
return true;
return false;
}
// ported from AMXX's core get_user_origin(..., 3) (suggested by Greenberet)
stock fm_get_aim_origin(index, Float:origin[3]) {
new Float:start[3], Float:view_ofs[3];
pev(index, pev_origin, start);
pev(index, pev_view_ofs, view_ofs);
xs_vec_add(start, view_ofs, start);
new Float:dest[3];
pev(index, pev_v_angle, dest);
engfunc(EngFunc_MakeVectors, dest);
global_get(glb_v_forward, dest);
xs_vec_mul_scalar(dest, 9999.0, dest);
xs_vec_add(start, dest, dest);
engfunc(EngFunc_TraceLine, start, dest, 0, index, 0);
get_tr2(0, TR_vecEndPos, origin);
return 1;
}
stock bool:fm_get_user_longjump(index) {
new value[2];
engfunc(EngFunc_GetPhysicsKeyValue, index, "slj", value, 1);
switch (value[0]) {
case '1': return true;
}
return false;
}
stock fm_set_user_longjump(index, bool:longjump = true, bool:tempicon = true) {
if (longjump == fm_get_user_longjump(index))
return;
if (longjump) {
engfunc(EngFunc_SetPhysicsKeyValue, index, "slj", "1");
if (tempicon) {
static msgid_itempickup;
if (!msgid_itempickup)
msgid_itempickup = get_user_msgid("ItemPickup");
message_begin(MSG_ONE, msgid_itempickup, _, index);
write_string("item_longjump");
message_end();
}
}
else
engfunc(EngFunc_SetPhysicsKeyValue, index, "slj", "0");
}
#define WEAPON_SUIT 31
stock bool:fm_get_user_suit(index) {
return bool:(!(!(pev(index, pev_weapons) & (1<<WEAPON_SUIT)))); // i'm not insane, this is a trick!
}
stock fm_set_user_suit(index, bool:suit = true, bool:sound = true) {
new weapons = pev(index, pev_weapons);
if (!suit)
set_pev(index, pev_weapons, weapons & ~(1<<WEAPON_SUIT));
else if (!(weapons & (1<<WEAPON_SUIT))) {
set_pev(index, pev_weapons, weapons | (1<<WEAPON_SUIT));
if (sound)
emit_sound(index, CHAN_VOICE, "items/tr_kevlar.wav", VOL_NORM, ATTN_NORM, 0, PITCH_NORM);
}
}
#define FEV_RELIABLE (1<<1)
#define FEV_GLOBAL (1<<2)
// removes all created decals and players' corpses from the world
// set a specific index to remove decals only for the given client
stock fm_cs_remove_decals(index = 0) {
static eventindex_decal_reset;
if (!eventindex_decal_reset)
eventindex_decal_reset = engfunc(EngFunc_PrecacheEvent, 1, "events/decal_reset.sc");
new flags = FEV_RELIABLE;
if (!index)
flags |= FEV_GLOBAL;
engfunc(EngFunc_PlaybackEvent, flags, index, eventindex_decal_reset, 0.0, Float:{0.0, 0.0, 0.0}, Float:{0.0, 0.0, 0.0}, 0.0, 0.0, 0, 0, 0, 0);
}
// checks whether the entity's classname is equal to the passed classname
stock bool:fm_is_ent_classname(index, const classname[]) {
if (!pev_valid(index))
return false;
new class[32];
pev(index, pev_classname, class, sizeof class - 1);
if (equal(class, classname))
return true;
return false;
}
// the same as AMXX's core user_kill but fixes the issue when the scoreboard doesn't update immediately if flag is set to 1
stock fm_user_kill(index, flag = 0) {
if (flag) {
new Float:frags;
pev(index, pev_frags, frags);
set_pev(index, pev_frags, ++frags);
}
dllfunc(DLLFunc_ClientKill, index);
return 1;
}
// returns a degree angle between player-to-point and player's view vectors
stock Float:fm_get_view_angle_diff(index, const Float:point[3]) {
new Float:vec[3], Float:ofs[3], Float:aim[3];
pev(index, pev_origin, vec);
pev(index, pev_view_ofs, ofs);
xs_vec_add(vec, ofs, vec);
xs_vec_sub(point, vec, vec);
xs_vec_normalize(vec, vec);
pev(index, pev_v_angle, aim);
engfunc(EngFunc_MakeVectors, aim);
global_get(glb_v_forward, aim);
return xs_vec_angle(vec, aim);
}
// gets a weapon type of the linked to weaponbox weapon_* entity
stock fm_get_weaponbox_type(entity) {
static max_clients, max_entities;
if (!max_clients)
max_clients = global_get(glb_maxClients);
if (!max_entities)
max_entities = global_get(glb_maxEntities);
for (new i = max_clients + 1; i < max_entities; ++i) {
if (pev_valid(i) && entity == pev(i, pev_owner)) {
new wname[32];
pev(i, pev_classname, wname, sizeof wname - 1);
return get_weaponid(wname);
}
}
return 0;
}
// safe removal of weaponbox+weapon_* entity pair (delay =~= 0.03 second)
#define fm_remove_weaponbox(%1) dllfunc(DLLFunc_Think, %1)
/* stock fm_remove_weaponbox(entity)
return dllfunc(DLLFunc_Think, entity) */

View File

@ -0,0 +1,666 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// File Functions
//
#if defined _file_included
#endinput
#endif
#define _file_included
/**
* @note All paths in AMX Mod X natives are relative to the mod folder
* unless otherwise noted.
*
* Most functions in AMX Mod X (at least, ones that deal with direct
* file manipulation) will support an alternate path specification.
*/
/**
* Maximum path length.
*/
#define PLATFORM_MAX_PATH 256
/**
* File inode types for use with open_dir() and next_file().
*/
enum FileType
{
FileType_Unknown, /* Unknown file type (device/socket) */
FileType_Directory, /* File is a directory */
FileType_File, /* File is a file */
};
/**
* File time modes for use with GetFileTime().
*/
enum FileTimeType
{
FileTime_LastAccess, /* Last access (not available on FAT) */
FileTime_Created, /* Creation (not available on FAT) */
FileTime_LastChange, /* Last modification */
};
/**
* File position modes for use with fseek().
*/
#define SEEK_SET 0 /* Seek from start */
#define SEEK_CUR 1 /* Seek from current position */
#define SEEK_END 2 /* Seek from end position */
/**
* Options for use with file_size() flag parameter.
*/
#define FSOPT_BYTES_COUNT 0 /* Returns the file size in number of bytes */
#define FSOPT_LINES_COUNT 1 /* Returns how many lines there are in this file */
#define FSOPT_END_WITH_LF 2 /* Returns whether the last line is '\n' */
/**
* Data block modes for use with fread*() and fwrite*().
*/
#define BLOCK_INT 4
#define BLOCK_SHORT 2
#define BLOCK_CHAR 1
#define BLOCK_BYTE 1
/**
* File permissions flags for use with mkdir() and SetFilePermissions().
*/
#define FPERM_U_READ 0x0100 /* User can read. */
#define FPERM_U_WRITE 0x0080 /* User can write. */
#define FPERM_U_EXEC 0x0040 /* User can exec. */
#define FPERM_U_RWX FPERM_U_READ | FPERM_U_WRITE | FPERM_U_EXEC
#define FPERM_G_READ 0x0020 /* Group can read. */
#define FPERM_G_WRITE 0x0010 /* Group can write. */
#define FPERM_G_EXEC 0x0008 /* Group can exec. */
#define FPERM_G_RWX FPERM_G_READ | FPERM_G_WRITE | FPERM_G_EXEC
#define FPERM_O_READ 0x0004 /* Anyone can read. */
#define FPERM_O_WRITE 0x0002 /* Anyone can write. */
#define FPERM_O_EXEC 0x0001 /* Anyone can exec. */
#define FPERM_O_RWX FPERM_O_READ | FPERM_O_WRITE | FPERM_O_EXEC
#define FPERM_DIR_DEFAULT FPERM_U_RWX | FPERM_G_RWX | FPERM_O_RWX /* rwx r-x r-x (0755) */
/**
* Reads content from directory
*
* @note This native is expensive. Consider the use of open_dir(), next_file() and close_dir() instead.
* @note Both the '.' and '..' automatic directory entries will be retrieved for Windows and Linux.
*
* @param dirname Path to open
* @param pos Index the element
* @param output String buffer to hold content
* @param len Maximum size of string buffer
* @param outlen Number of characters written to the buffer
*
* @return Returns index of next element, otherwiwe 0 when end of dir is reached
*/
native read_dir(const dirname[], pos, output[], len, &outlen = 0);
/**
* Reads line from file.
*
* @note This native is expensive. Consider the use of new file natives (fopen(), fgets(), etc.)
* if purpose is to read several lines of a file.
*
* @param file Path to open
* @param line Index of the line, starting to 0
* @param text String buffer to hold line read
* @param len Maximum size of string buffer
* @param txtlen Number of characters written to the buffer
*
* @return Returns index of next line, otherwise 0 when end of file is reached
* @error Unable to read the file
*/
native read_file(const file[], line, text[], len, &txtlen = 0);
/**
* Writes text to file.
*
* @note This native is expensive. Consider the use of new file natives (fopen(), fputs(), etc.)
* if purpose is to write several lines of a file.
*
* @param file Path to open
* @param text String to write to
* @param line Index of the line, starting to 0
* If < 0, content will be appended
*
* @noreturn
* @error Unable to write [temporary] file
*/
native write_file(const file[], const text[], line = -1);
/**
* Deletes a file.
*
* @param file Path of the file to delete
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to delete files existing in the Valve
* search path, rather than solely files existing directly
* in the gamedir.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths.
*
* @return 1 on success, 0 on failure or if file not immediately removed.
*/
native delete_file(const file[], bool:use_valve_fs = false, const valve_path_id[] = "GAMECONFIG");
/**
* Checks if a file exists.
*
* @param file Path to the file
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to find files existing in any of
* the Valve search paths, rather than solely files
* existing directly in the gamedir.
*
* @return 1 if the file exists, 0 otherwise
*/
native file_exists(const file[], bool:use_valve_fs = false);
/**
* Renames a file.
*
* @param oldname New path to the file
* @param newname Path to the existing file
* @param relative If true, native will act like other natives which
* use the moddir as a base directory. Otherwise, the
* current directory is undefined (but assumed to be hlds).
*
* @return 1 on success, 0 otherwise
*/
native rename_file(const oldname[], const newname[], relative = 0);
/**
* Checks if a directory exists.
*
* @param dir Path to the directory
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to find files existing in any of
* the Valve search paths, rather than solely files
* existing directly in the gamedir.
*
* @return 1 if the directory exists, 0 otherwise
*/
native dir_exists(const dir[], bool:use_valve_fs = false);
/**
* Get the file size in bytes.
*
* @param file Path to the file
* @param flag Flag options, see FSOPT_* constants
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to find files existing in any of
* the Valve search paths, rather than solely files
* existing directly in the gamedir.
* If used, flag option is ignored.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths
*
* @return If flag is FSOPT_BYTES_COUNT or use_valve_fs to true, the file size in bytes
* If flag is FSOPT_LINES_COUNT, the number of lines in the file
* If flag is FSOPT_END_WITH_LF, 1 is returned if file ends with line feed
* If file doesn't exist, -1
*/
native file_size(const file[], flag = FSOPT_BYTES_COUNT, bool:use_valve_fs = false, const valve_path_id[] = "GAME");
/**
* Opens or creates a file, returning a file handle on success. File handles
* should be closed with fclose().
*
* @note The open mode may be one of the following strings:
* "r": Open an existing file for reading.
* "w": Create a file for writing, or truncate (delete the contents of) an
* existing file and then open it for writing.
* "a": Create a file for writing, or open an existing file such that writes
* will be appended to the end.
* "r+": Open an existing file for both reading and writing.
* "w+": Create a file for reading and writing, or truncate an existing file
* and then open it for reading and writing.
* "a+": Create a file for both reading and writing, or open an existing file
* such that writes will be appended to the end.
*
* @note The open mode may also contain an additional character after "r", "w", or "a",
* but before any "+" sign. This character may be "b" (indicating binary mode) or
* "t" (indicating text mode). By default, "text" mode is implied. On Linux and
* Mac, this has no distinction from binary mode. On Windows, it causes the '\n'
* character (0xA) to be written as "\r\n" (0xD, 0xA).
*
* Example: "rb" opens a binary file for writing; "at" opens a text file for
* appending.
*
* @note Registered paths ID are (in priority order) :
* GAME All paths related to current mod, including fallback
* Depending settings, it includes: <gamedir>_lv/_addon/_<language>/_hd
* and <gamedir> itself
* GAMECONFIG The default writable directory (<gamedir>)
* GAMEDOWNLOAD The download directory (<gamedir>_download)
* GAME_FALLBACK All paths related to fallback game, same as GAME
* DEFAULTGAME All paths related to the default game which is "valve", same as GAME
* BASE The base path where server is installed
*
* Note that some paths are non-writable. It includes all <gamedir>_* (expect _download)
* and DEFAULTGAME. Any file inside a non-writable path will be ignored if you try to open
* it in writing mode.
*
* @param filename File to open
* @param mode Open mode
* @param use_valve_fs If true, the Valve file system will be used instead
* This can be used to finred files existing in valve
* search paths, rather than solely files existing directly
* in the gamedir.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths
*
* @return A file handle, or null if the file could not be opened.
*/
native fopen(const filename[], const mode[], bool:use_valve_fs = false, const valve_path_id[] = "GAME");
/**
* Closes a file handle.
*
* @param file File handle
*/
native fclose(file);
/**
* Reads a single binary data from a file.
*
* @param file Handle to the file
* @param data Variable to store item read
* @param mode Size of each element, in bytes, to be read
* See BLOCK_* constants
*
* @return Number of elements read
*/
native fread(file, &any:data, mode);
/**
* Reads binary data from a file.
*
* @param file Handle to the file
* @param data Array to store each item read
* @param blocks Number of items to read into the array
* @param mode Size of each element, in bytes, to be read
* Valid sizes are 1, 2, or 4. See BLOCK_* constants.
*
* @return Number of elements read
*/
native fread_blocks(file, any:data[], blocks, mode);
/**
* Reads raw binary data from a file.
*
* @param file Handle to the file
* @param stream Array to store each item read
* @param blocksize Number of items to read into the array
* @param blocks Size of each element, in bytes. The data is read directly.
* That is, in 1 or 2-byte mode, the lower byte(s) in
* each cell are used directly, rather than performing
* any casts from a 4-byte number to a smaller number.
*
* @return Number of elements read
*/
native fread_raw(file, any:stream[], blocksize, blocks);
/**
* Writes a single binary data to a file.
*
* @param file Handle to the file
* @param data Item to write
* @param mode Size of each item in the array in bytes
* Valid sizes are 1, 2, or 4. See BLOCK_* constants
*
* @return Number of elements written
*/
native fwrite(file, any:data, mode);
/**
* Writes binary data to a file.
*
* @param file Handle to the file
* @param data Array of items to write
* @param blocks Number of items in the array
* @param mode Size of each item in the array in bytes
* Valid sizes are 1, 2, or 4. See BLOCK_* constants
*
* @return Number of elements written
*/
native fwrite_blocks(file, const any:data[], blocks, mode);
/**
* Writes raw binary data to a file.
*
* @param file Handle to the file.
* @param stream Array of items to write. The data is written directly.
* That is, in 1 or 2-byte mode, the lower byte(s) in
* each cell are used directly, rather than performing
* any casts from a 4-byte number to a smaller number.
* @param blocks Size of each item in the array in bytes.
* @param mode Number of items in the array.
*
* @return Number of elements written
*/
native fwrite_raw(file, const any:stream[], blocks, mode);
/**
* Tests if the end of file has been reached.
*
* @param file Handle to the file
*
* @return 1 if end of file has been reached, 0 otherwise.
*/
native feof(file);
/**
* Reads a line from a text file.
*
* @param file Handle to the file.
* @param buffer String buffer to hold the line
* @param maxlength Maximum size of string buffer
*
* @return Total number of characters written on success, 0 otherwise
*/
native fgets(file, buffer[], maxlength);
/**
* Writes a line of text to a text file.
*
* @param file Handle to the file
* @param text String to write
* @param null_term True to append NULL terminator, false otherwise
*
* @return 0 on success, -1 otherwise
*/
native fputs(file, const text[], bool:null_term = false);
/**
* Writes a line of formatted text to a text file.
*
* @param file Handle to the file
* @param format Formatting rules
* @param ... Variable number of format parameters
*
* @return Total number of characters written on success, 0 otherwise
*/
native fprintf(file, const fmt[], any:...);
/**
* Sets the file position indicator.
*
* @param file Handle to the file
* @param position Position relative to what is specified in whence
* @param start SEEK_ constant value of where to see from
*
* @return 0 on success, a non-zero value otherwise
*/
native fseek(file, position, start);
/**
* Gets current position in the file.
*
* @param file Handle to the file
*
* @return Value for the file position indicator
*/
native ftell(file);
/**
* Gets character from file.
*
* @param file Handle to the file
*
* @return Character read on success, -1 otherwise
*/
native fgetc(file);
/**
* Writes character to file
*
* @param file Handle to the file
* @param data Character to put
*
* @return Character written on success, -1 otherwise
*/
native fputc(file, data);
/**
* Ungets character from file.
*
* @param file Handle to the file
* @param data Character to unget
*
* @return On success, the character put back is returned, -1 otherwise
*/
native fungetc(file, data);
/**
* Flushes a buffered output stream.
*
* @param file File handle, or 0 for all open streams
*
* @return 0 on success, -1 on failure
*/
native fflush(file);
/**
* Gets the formatted file size in bytes.
*
* @param filename Path to the file
* @param ... Variable number of format parameters
*
* @return File size in bytes, otherwise -1 if file not found
*/
native filesize(const filename[], any:...);
/**
* Removes a directory.
*
* @note On most Operating Systems you cannot remove a directory which has files inside it.
*
* @param path Path to the directory
*
* @return 1 on success, 0 otherwise
*/
native rmdir(const path[]);
/**
* Creates a directory.
*
* @param path Path to create
* @param mode Permissions (default is o=rx,g=rx,u=rwx). Note that folders must have
* the execute bit set on Linux. On Windows, the mode is ignored.
* @param use_valve_fs If true, the Valve file system will be used instead
* This can be used to create folders in the game's
* Valve search paths, rather than directly in the gamedir.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for default
* In this case, mode is ignored
*
* @return 0 on success, -1 otherwise
*/
native mkdir(const dirname[], mode = FPERM_DIR_DEFAULT, bool:use_valve_fs = false, const valve_path_id[] = "GAMECONFIG");
/**
* Deletes a file (delete_file macro)
*
* @param filename Path of the file to delete
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to delete files existing in the Valve
* search path, rather than solely files existing directly
* in the gamedir.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths
*
* @return 1 on success, 0 on failure or if file not immediately removed
*/
native unlink(const filename[], bool:use_valve_fs = false, const valve_path_id[] = "GAMECONFIG");
/**
* Opens a directory/folder for contents enumeration.
*
* @note Directories are closed with close_dir().
*
* @param dir Path to open.
* @param firstfile String buffer to hold first file name
* @param length Maximum size of the string buffer
* @param type Optional variable to store the file type
* @param use_valve_fs If true, the Valve file system will be used instead.
* This can be used to find files existing in any of
* the Valve search paths, rather than solely files
* existing directly in the gamedir.
* @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths.
*
* @return Handle to the directory, 0 otherwise
*/
native open_dir(const dir[], firstfile[], length, &FileType:type = FileType_Unknown, bool:use_valve_fs = false, const valve_path_id[] = "GAME");
/**
* Reads the next directory entry as a local filename.
*
* @note Contents of buffers are undefined when returning false.
* @note Both the '.' and '..' automatic directory entries will be retrieved for Windows and Linux.
*
* @param dirh Handle to a directory
* @param buffer String buffer to hold directory name
* @param length Maximum size of string buffer
* @param type Optional variable to store the file type. FileType_* constants
*
* @return 1 on success, 0 if there are no more files to read.
*/
native next_file(dirh, buffer[], length, &FileType:type = FileType_Unknown);
/**
* Closes the directory.
*
* @param dirh Handle to a directory
*/
native close_dir(dirh);
/**
* Loads a file using the LoadFileForMe engine function.
*
* The data is truncated if there is not enough space. No null-terminator
* is applied; the data is the raw contents of the file.
*
* @param file File to load (may be a file from the GCF)
* @param buffer Buffer to store file contents
* @param maxlength Maximum size of the file buffer
* @param length Variable to store the file length. This may return
* a number larger than the buffer size
* @return -1 if the file could not be loaded. Otherwise,
* the number of cells actually written to the buffer
* are returned.
*/
native LoadFileForMe(const file[], buffer[], maxlength, &length = 0);
/**
* Returns a file timestamp as a unix timestamp.
*
* @param file File name
* @param tmode Time mode, see FileTime_* constants
*
* @return Returns a file timestamp as a unix timestamp
*/
native GetFileTime(const file[], FileTimeType:tmode);
/**
* Changes a file or directories permissions.
*
* @param path Path to the file
* @param mode Permissions to set, see FPERM_* constants
*
* @return True on success, false otherwise
*/
native bool:SetFilePermissions(const path[], mode);
/**
* Reads a single int8 (byte) from a file. The returned value is sign-
* extended to an int32.
*
* @param file Handle to the file
* @param data Variable to store the data read
*
* @return True on success, false on failure
*/
native bool:FileReadInt8(file, &any:data);
/**
* Reads a single uint8 (unsigned byte) from a file. The returned value is
* zero-extended to an int32.
*
* @param file Handle to the file
* @param data Variable to store the data read
*
* @return True on success, false on failure
*/
native bool:FileReadUint8(file, &any:data);
/**
* Reads a single int16 (short) from a file. The value is sign-extended to
* an int32.
*
* @param file Handle to the file
* @param data Variable to store the data read
*
* @return True on success, false on failure
*/
native bool:FileReadInt16(file, &any:data);
/**
* Reads a single unt16 (unsigned short) from a file. The value is zero-
* extended to an int32.
*
* @param file Handle to the file
* @param data Variable to store the data read
*
* @return True on success, false on failure
*/
native bool:FileReadUint16(file, &any:data);
/**
* Reads a single int32 (int/cell) from a file.
*
* @param file Handle to the file
* @param data Variable to store the data read
*
* @return True on success, false on failure
*/
native bool:FileReadInt32(file, &any:data);
/**
* Writes a single int8 (byte) to a file.
*
* @param file Handle to the file
* @param data Data to write (truncated to an int8)
*
* @return True on success, false on failure
*/
native bool:FileWriteInt8(file, any:data);
/**
* Writes a single int16 (short) to a file.
*
* @param file Handle to the file
* @param data Data to write (truncated to an int16)
*
* @return True on success, false on failure
*/
native bool:FileWriteInt16(file, any:data);
/**
* Writes a single int32 (int/cell) to a file.
*
* @param file Handle to the file
* @param data Data to write
*
* @return True on success, false on failure
*/
native bool:FileWriteInt32(file, any:data);

View File

@ -0,0 +1,422 @@
/* Float arithmetic
*
* (c) Copyright 1999, Artran, Inc.
* Written by Greg Garner (gmg@artran.com)
* Modified in March 2001 to include user defined
* operators for the floating point functions.
*
* This file is provided as is (no warranties).
*/
#if defined _float_included
#endinput
#endif
#define _float_included
#pragma rational Float
/**
* Different methods of rounding
*/
enum floatround_method {
floatround_round = 0,
floatround_floor,
floatround_ceil,
floatround_tozero
};
/**
* Different units of measurement for angles
*/
enum anglemode {
radian = 0,
degrees,
grades
};
/**
* Converts an integer into a floating point value.
*
* @param value Value to be converted
*
* @return Converted value
*/
native Float:float(value);
/**
* Converts a string into a floating point value.
*
* @param string Input string to be converted
*
* @return Converted value
*/
native Float:floatstr(const string[]);
/**
* Returns the fractional part of a floating point value
*
* @param string Floating point value to get the fractional part from
*
* @return The fractional part
*/
native Float:floatfract(Float:value);
/**
* Rounds a floating point value to an integer value
*
* @note For the list of available rounding methods look at
* floatround_method enumeration.
*
* @param value Floating point value to be rounded
* @param method Rounding method
*
* @return Converted value
*/
native floatround(Float:value, floatround_method:method=floatround_round);
/**
* Compares two floating point values.
*
* @param fOne First value to be compared
* @param fTwo Second value to be compared
*
* @return If arguments are equal, returns 0.
* If the first one is greater, returns 1.
* If the second one is greater, returns -1.
*/
native floatcmp(Float:fOne, Float:fTwo);
/**
* Returns the square root of a floating point value
*
* @note Same as floatpower(value, 0.5)
*
* @param value Floating point value to get square root from
*
* @return Square root of the input value
*/
native Float:floatsqroot(Float:value);
/**
* Returns the value raised to the power of the exponent
*
* @param value Floating point value to be raised
* @param exponent The exponent
*
* @return Value raised to the power of the exponent
*/
native Float:floatpower(Float:value, Float:exponent);
/**
* Returns the logarithm of value
*
* @param value Floating point value to calculate the logarithm for
* @param base The optional logarithmic base to use.
* Defaults to 10, or the natural logarithm
*
* @return Square root of the input value
*/
native Float:floatlog(Float:value, Float:base=10.0);
/**
* Returns the sine of a given angle
*
* @note For available units of measurements(modes) look at the anglemode enum
*
* @param value The angle to calculate the sine from
* @param mode What unit of measurement is the angle specified in
* Defaults to radians
*
* @return The sine of a given angle
*/
native Float:floatsin(Float:value, anglemode:mode=radian);
/**
* Returns the cosine of a given angle
*
* @note For available units of measurements(modes) look at the anglemode enum
*
* @param value The angle to calculate the cosine from
* @param mode What unit of measurement is the angle specified in
* Defaults to radians
*
* @return The cosine of a given angle
*/
native Float:floatcos(Float:value, anglemode:mode=radian);
/**
* Returns the tangent of a given angle
*
* @note For available units of measurements(modes) look at the anglemode enum
*
* @param value The angle to calculate the tangent from
* @param mode What unit of measurement is the angle specified in
* Defaults to radians
*
* @return The tangent of a given angle
*/
native Float:floattan(Float:value, anglemode:mode=radian);
/**
* Returns the hyperbolic sine of a given angle
*
* @note For available units of measurements(modes) look at the anglemode enum
*
* @param value The angle to calculate the hyperbolic sine from
* @param mode What unit of measurement is the angle specified in
* Defaults to radians
*
* @return The hyperbolic sine of a given angle
*/
native Float:floatsinh(Float:angle, anglemode:mode=radian);
/**
* Returns the hyperbolic cosine of a given angle
*
* @note For available units of measurements(modes) look at the anglemode enum
*
* @param value The angle to calculate the hyperbolic cosine from
* @param mode What unit of measurement is the angle specified in
* Defaults to radians
*
* @return The hyperbolic cosine of a given angle
*/
native Float:floatcosh(Float:angle, anglemode:mode=radian);
/**
* Returns the hyperbolic tangent of a given angle
*
* @note For available units of measurements(modes) look at the anglemode enum
*
* @param value The angle to calculate the hyperbolic tangent from
* @param mode What unit of measurement is the angle specified in
* Defaults to radians
*
* @return The hyperbolic tangent of a given angle
*/
native Float:floattanh(Float:angle, anglemode:mode=radian);
/**
* Returns the absolute value of a floating point value
*
* @param value The floating point value to get the absolute value from
*
* @return The absolute value
*/
native Float:floatabs(Float:value);
/* Return the angle of a sine, cosine or tangent.
* The output angle may be in radians, degrees, or grades. */
/**
* Returns the angle of the given tangent
*
* @note For available units of measurements(modes) look at the anglemode enum
*
* @param value The tangent to calculate the angle from
* @param mode What unit of measurement should the output angle be in
*
* @return The angle of a tangent
*/
native Float:floatatan(Float:angle, {anglemode,_}:radix);
/**
* Returns the angle of the given cosine
*
* @note For available units of measurements(modes) look at the anglemode enum
*
* @param value The cosine to calculate the angle from
* @param mode What unit of measurement should the output angle be in
*
* @return The angle of a cosine
*/
native Float:floatacos(Float:angle, {anglemode,_}:radix);
/**
* Returns the angle of the given sine
*
* @note For available units of measurements(modes) look at the anglemode enum
*
* @param value The sine to calculate the angle from
* @param mode What unit of measurement should the output angle be in
*
* @return The angle of a sine
*/
native Float:floatasin(Float:angle, {anglemode,_}:radix);
/**
* Computes the principal value of arctangent of y/x
*
* @note Someone should verify this native, not sure what it actually does.
* @note For available units of measurements(modes) look at the anglemode enum
*
* @param x Value representing the proportion of the x-coordinate.
* @param y Value representing the proportion of the x-coordinate.
* @param mode What unit of measurement should the output angle be in
*
* @return Arctangent of y/x
*/
native Float:floatatan2(Float:x, Float:y, {anglemode,_}:radix);
/* Multiply two floats together */
native Float:floatmul(Float:oper1, Float:oper2);
/* Divide the dividend float by the divisor float */
native Float:floatdiv(Float:dividend, Float:divisor);
/* Add two floats together */
native Float:floatadd(Float:dividend, Float:divisor);
/* Subtract oper2 float from oper1 float */
native Float:floatsub(Float:oper1, Float:oper2);
/* user defined operators */
native Float:operator*(Float:oper1, Float:oper2) = floatmul;
native Float:operator/(Float:oper1, Float:oper2) = floatdiv;
native Float:operator+(Float:oper1, Float:oper2) = floatadd;
native Float:operator-(Float:oper1, Float:oper2) = floatsub;
stock Float:operator++(Float:oper)
return oper+1.0;
stock Float:operator--(Float:oper)
return oper-1.0;
stock Float:operator-(Float:oper)
return oper^Float:cellmin; /* IEEE values are sign/magnitude */
stock Float:operator*(Float:oper1, oper2)
return floatmul(oper1, float(oper2)); /* "*" is commutative */
stock Float:operator/(Float:oper1, oper2)
return floatdiv(oper1, float(oper2));
stock Float:operator/(oper1, Float:oper2)
return floatdiv(float(oper1), oper2);
stock Float:operator+(Float:oper1, oper2)
return floatadd(oper1, float(oper2)); /* "+" is commutative */
stock Float:operator-(Float:oper1, oper2)
return floatsub(oper1, float(oper2));
stock Float:operator-(oper1, Float:oper2)
return floatsub(float(oper1), oper2);
stock bool:operator==(Float:oper1, Float:oper2)
return floatcmp(oper1, oper2) == 0;
stock bool:operator==(Float:oper1, oper2)
return floatcmp(oper1, float(oper2)) == 0; /* "==" is commutative */
stock bool:operator!=(Float:oper1, Float:oper2)
return floatcmp(oper1, oper2) != 0;
stock bool:operator!=(Float:oper1, oper2)
return floatcmp(oper1, float(oper2)) != 0; /* "==" is commutative */
stock bool:operator>(Float:oper1, Float:oper2)
return floatcmp(oper1, oper2) > 0;
stock bool:operator>(Float:oper1, oper2)
return floatcmp(oper1, float(oper2)) > 0;
stock bool:operator>(oper1, Float:oper2)
return floatcmp(float(oper1), oper2) > 0;
stock bool:operator>=(Float:oper1, Float:oper2)
return floatcmp(oper1, oper2) >= 0;
stock bool:operator>=(Float:oper1, oper2)
return floatcmp(oper1, float(oper2)) >= 0;
stock bool:operator>=(oper1, Float:oper2)
return floatcmp(float(oper1), oper2) >= 0;
stock bool:operator<(Float:oper1, Float:oper2)
return floatcmp(oper1, oper2) < 0;
stock bool:operator<(Float:oper1, oper2)
return floatcmp(oper1, float(oper2)) < 0;
stock bool:operator<(oper1, Float:oper2)
return floatcmp(float(oper1), oper2) < 0;
stock bool:operator<=(Float:oper1, Float:oper2)
return floatcmp(oper1, oper2) <= 0;
stock bool:operator<=(Float:oper1, oper2)
return floatcmp(oper1, float(oper2)) <= 0;
stock bool:operator<=(oper1, Float:oper2)
return floatcmp(float(oper1), oper2) <= 0;
stock bool:operator!(Float:oper)
return (_:oper & ((-1)/2)) == 0; /* -1 = all bits to 1; /2 = remove most significant bit (sign)
works on both 32bit and 64bit systems; no constant required */
/* forbidden operations */
forward operator%(Float:oper1, Float:oper2);
forward operator%(Float:oper1, oper2);
forward operator%(oper1, Float:oper2);
/**
* Returns whichever value is the smaller one
*
* @param ValueA The first value
* @param ValueB The second value
*
* @return ValueA if it is smaller than ValueB, and vice versa
*/
stock Float:floatmin(Float:ValueA, Float:ValueB)
{
if (ValueA<=ValueB)
{
return ValueA;
}
return ValueB;
}
/**
* Returns whichever value is the greater one
*
* @param ValueA The first value
* @param ValueB The second value
*
* @return ValueA if it is greater than ValueB, and vice versa
*/
stock Float:floatmax(Float:ValueA, Float:ValueB)
{
if (ValueA>=ValueB)
{
return ValueA;
}
return ValueB;
}
/**
* Clamps a value between a minimum and a maximum floating point value
*
* @param Value The value to be clamped
* @param MinValue Minimum value
* @param MaxValue Maximum value
*
* @return The Value clamped between MinValue and MaxValue
*/
stock Float:floatclamp(Float:Value, Float:MinValue, Float:MaxValue)
{
if (Value<=MinValue)
{
return MinValue;
}
if (Value>=MaxValue)
{
return MaxValue;
}
return Value;
}

View File

@ -0,0 +1,333 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Fun Functions
//
#if defined _fun_included
#endinput
#endif
#define _fun_included
#pragma reqlib fun
#if !defined AMXMODX_NOAUTOLOAD
#pragma loadlib fun
#endif
/**
* Parts of body for hits, for use with set_user_hitzones().
*/
const HITZONE_GENERIC = (1 << HIT_GENERIC); // 1
const HITZONE_HEAD = (1 << HIT_HEAD); // 2
const HITZONE_CHEST = (1 << HIT_CHEST); // 4
const HITZONE_STOMACH = (1 << HIT_STOMACH); // 8
const HITZONE_LEFTARM = (1 << HIT_LEFTARM); // 16
const HITZONE_RIGHTARM = (1 << HIT_RIGHTARM); // 32
const HITZONE_LEFTLEG = (1 << HIT_LEFTLEG); // 64
const HITZONE_RIGHTLEG = (1 << HIT_RIGHTLEG); // 128
const HITZONES_DEFAULT = HITZONE_GENERIC | HITZONE_HEAD | HITZONE_CHEST | HITZONE_STOMACH |
HITZONE_LEFTARM | HITZONE_RIGHTARM | HITZONE_LEFTLEG | HITZONE_RIGHTLEG; // 255
/**
* Tells whether receiver hears sender via voice communication.
*
* @param receiver Receiver
* @param sender Sender
*
* @return 1 if receiver hears the sender, 0 otherwise.
* @error If receiver or sender are not connected or not
* within the range of 1 to MaxClients
*/
native get_client_listen(receiver, sender);
/**
* Sets who can listen who.
*
* @param receiver Receiver
* @param sender Sender
* @param listen 1 if receiver should be able to hear sender, 0 if not
*
* @return 0 if the setting can't be done for some reason
* @error If receiver or sender are not connected or not
* within the range of 1 to MaxClients.
*/
native set_client_listen(receiver, sender, listen);
/**
* Sets player's godmode.
*
* @param index Client index
* @param godmode 1 to enable godmode, 0 to disable
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native set_user_godmode(index, godmode = 0);
/**
* Tells whether a player has godmode on.
*
* @param index Client index
*
* @return 1 if player has godmode on, 0 if not
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native get_user_godmode(index);
/**
* Sets player's armor amount.
*
* @param index Client index
* @param armor The armor amount to set
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native set_user_armor(index, armor);
/**
* Sets player's health amount.
*
* @param index Client index
* @param health The health amount to set
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native set_user_health(index, health);
/**
* Moves a player to the given origin.
*
* @param index Client index
* @param origin Origin to move a player to
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native set_user_origin(index, const origin[3]);
/**
* Sets player's rendering mode.
*
* @note A really useful render modes reference:
* https://sites.google.com/site/svenmanor/rendermodes
*
* @param index Client index
* @param fx Rendering effects. One of kRenderFx* constants
* @param r The amount of red color (0 to 255)
* @param g The amount of green color (0 to 255)
* @param b The amount of blue color (0 to 255)
* @param render Render mode. One of kRender* constants
* @param amount Render amount (0 to 255)
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native set_user_rendering(index, fx = kRenderFxNone, r = 0, g = 0, b = 0, render = kRenderNormal, amount = 0);
/**
* Gets player's rendering mode.
*
* @note A really useful render modes reference:
* https://sites.google.com/site/svenmanor/rendermodes
*
* @param index Client index
* @param fx Variable to store the rendering effect
* @param r Variable to store the amount of red color
* @param g Variable to store the amount of green color
* @param b Variable to store the amount of blue color
* @param render Variable to store the render mode
* @param amount Variable to store the render amount
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native get_user_rendering(index, &fx = kRenderFxNone, &r = 0, &g = 0, &b = 0, &render = kRenderNormal, &amount = 0);
/**
* Gives an item to a player.
*
* @param index Client index
* @param item Classname of the item to give. Should start with either
* "weapon_", "ammo_", "item_" or "tf_weapon_"
*
* @return Item entity index. If an invalid item name is
* given or the item failed to create, it will return 0.
* If the item was removed, it will return -1
* @error If player is not connected or not within the range
* of 1 to MaxClients or item creation fails.
*/
native give_item(index, const item[]);
/**
* Sets (adds, removes) hit zones for a player.
*
* @note This actually sets rules of how any player can hit any other.
* Example: set_user_hitzones(id, target, 2) - makes @id able to
* hit @target only in the head.
*
* @param index Client index
* @param target The target player
* @param body A bitsum of the body parts that can/can't be shot. See HITZONE* constants.
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native set_user_hitzones(index = 0, target = 0, body = HITZONES_DEFAULT);
/**
* Gets the set of hit zone "rules" between @index and @target players.
*
* @note For the body part bitsum, see HITZONE* constants.
*
* @param index Client index
* @param target The target player
*
* @return The bitsum of @target's body parts @index is able to hit
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native get_user_hitzones(index, target);
/**
* Sets player's maximum movement speed.
*
* @param index Client index
* @param speed The maximum speed player will be able to run at
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native set_user_maxspeed(index, Float:speed = -1.0);
/**
* Gets player's maximum movement speed.
*
* @param index Client index
*
* @return Player's maximum movement speed
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native Float:get_user_maxspeed(index);
/**
* Sets player's gravity.
*
* @param index Client index
* @param gravity Gravity value to set, 1.0 being normal gravity (800)
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native set_user_gravity(index, Float:gravity = 1.0);
/**
* Gets player's gravity.
*
* @param index Client index
*
* @return Player's gravity value, 1.0 being normal gravity (800)
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native Float:get_user_gravity(index);
/**
* Spawns an entity.
*
* @param index Entity index
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native spawn(index);
/**
* Enables or disables player's noclip.
*
* @param index Client index
* @param noclip 1 to enable noclip, 0 to disable
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native set_user_noclip(index, noclip = 0);
/**
* Gets whether a player has noclip enabled or not.
*
* @param index Client index
*
* @return 1 if noclip is enabled, 0 if disabled
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native get_user_noclip(index);
/**
* Tells whether a player has silent footsteps enabled.
*
* @param index Client index
*
* @return 1 if silent footsteps are enabled, 0 if not
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native get_user_footsteps(index);
/**
* Enables or disables player's silent footsteps.
*
* @param index Client index
* @param set 1 if player should have silent footsteps, 0 otherwise
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native set_user_footsteps(id, set = 1);
/**
* Strips all weapons from a player, including their knife.
*
* @param index Client index
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native strip_user_weapons(index);
/**
* Sets player's frags amount.
*
* @param index Client index
* @param frags The amount of frags to set
*
* @noreturn
* @error If player is not connected or not within the range
* of 1 to MaxClients.
*/
native set_user_frags(index, frags);

View File

@ -0,0 +1,93 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Game Config Functions
//
#if defined _gameconfigs_included
#endinput
#endif
#define _gameconfigs_included
enum GameConfig
{
Invalid_GameConfig = 0
};
/**
* Loads a game config file.
*
* @note The file path must be relative to the 'gamedata' folder under the data folder
* and the extension should be omitted.
*
* @param file File to load
*
* @return A handle to the game config file
*/
native GameConfig:LoadGameConfigFile(const file[]);
/**
* Returns an offset value.
*
* @param handle Game config handle
* @param key Key to retrieve from the offset section
*
* @return An offset, or -1 on failure
* @error Invalid game config handle
*/
native GameConfGetOffset(GameConfig:handle, const key[]);
/**
* Returns an offset value given a classname.
*
* @param handle Game config handle
* @param classname Class name to match from the offset section
* @param key Key to retrieve from the offset section
*
* @return An offset, or -1 on failure
* @error Invalid game config handle
*/
native GameConfGetClassOffset(GameConfig:handle, const classname[], const key[]);
/**
* Gets the value of a key from the "Keys" section.
*
* @param handle Game config handle
* @param key Key to retrieve from the Keys section
* @param buffer Destination string buffer
* @param maxlen Maximum length of output string buffer
*
* @return True if key existed, false otherwise
* @error Invalid game config handle
*/
native bool:GameConfGetKeyValue(GameConfig:handle, const key[], buffer[], maxlen);
/**
* Finds an address calculation in a GameConfig file.
*
* @param handle Game config handle
* @param name Name of the property to find
*
* @return An address calculated on success, otherwise 0 on failure.
* @error Invalid game config handle
*/
native GameConfGetAddress(GameConfig:handle, const name[]);
/**
* Destroys a game config and frees its memory.
*
* @note The function automatically sets the variable passed to it to 0 to aid
* in preventing accidental usage after destroy.
*
* @param handle Game config handle
*
* @return 1 on success, 0 if an invalid handle was passed in
*/
native CloseGameConfigFile(&GameConfig:handle);

View File

@ -0,0 +1,264 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// GeoIP Module Functions
//
#if defined geoip_included
#endinput
#endif
#define _geoip_included
#pragma reqlib geoip
#if !defined AMXMODX_NOAUTOLOAD
#pragma loadlib geoip
#endif
/**
* @global IP addresses passed to these natives can contain ports, the ports will be ignored.
*/
/**
* Look up the two character country code for a given IP address.
* e.g: "US", "CA", etc.
*
* @param ip The IP address to lookup.
* @param result The result buffer. If the lookup does not succeed, the buffer is not modified.
*
* @return true on a successful lookup, false on a failed lookup.
*/
native bool:geoip_code2_ex(const ip[], result[3]);
/**
* Look up the three character country code for a given IP address.
* e.g: "USA", "cAN", etc.
*
* @param ip The IP address to lookup.
* @param result The result buffer. If the lookup does not succeed, the buffer is not modified.
*
* @return true on a successful lookup, false on a failed lookup.
*/
native bool:geoip_code3_ex(const ip[], result[4]);
/**
* Lookup the two character country code for a given IP address. Sets the buffer to "error" on
* an unsuccessful lookup.
*
* @deprecated This native will overflow the buffer by one cell on an unknown ip lookup!
* Use geoip_code2_ex instead.
*
* @param ip The IP address to lookup.
* @param result The result buffer.
*
* @return The result length.
*/
#pragma deprecated Use geoip_code2_ex() instead.
native geoip_code2(const ip[], ccode[3]);
/**
* Lookup the three character country code for a given IP address. Sets the buffer to "error" on
* an unsuccessful lookup.
*
* @deprecated This native will overflow the buffer by one cell on an unknown ip lookup!
* Use geoip_code3_ex instead.
*
* @param ip The IP address to lookup.
* @param result The result buffer.
*
* @return The result length.
*/
#pragma deprecated Use geoip_code3_ex() instead.
native geoip_code3(const ip[], result[4]);
/**
* Lookup the full country name for the given IP address. Sets the buffer to "error" on
* an unsuccessful lookup.
*
* @param ip The IP address to lookup.
* @param result The result of the geoip lookup.
* @param len The maximum length of the result buffer.
*
* @return The result length.
*/
#pragma deprecated Use geoip_country_ex() instead.
native geoip_country(const ip[], result[], len = 45);
/**
* Lookup the full country name for the given IP address.
*
* @param ip The IP address to lookup.
* @param result The result of the geoip lookup.
* @param len The maximum length of the result buffer.
* @param id An optional player's index in order to return the result
* in the player's language, if supported.
* -1: the default language, which is english.
* 0: the server language. You can use LANG_SERVER define.
* >=1: the player's language.
*
* @return The result length on successful lookup, 0 otherwise.
*/
native geoip_country_ex(const ip[], result[], len, id = -1);
/**
* Look up the full city name for the given IP address.
*
* @note This native requires GeoIP City database, which can be retrieved from:
* http://dev.maxmind.com/geoip/geoip2/geolite2/ (MaxMind DB binary)
*
* @param ip The IP address to look up.
* @param result The result of the geoip look up.
* @param len The maximum length of the result buffer.
* @param id An optional player's index in order to return the result
* in the player's language, if supported.
* -1: the default language, which is english.
* 0: the server language. You can use LANG_SERVER define.
* >=1: the player's language.
*
* @return The result length on successful lookup, 0 otherwise.
*/
native geoip_city(const ip[], result[], len, id = -1);
/**
* Look up the region/state code for the given IP address.
* e.g. "US-OH", "DE-HH", IT-82, "FR-U", etc.
*
* @note This native requires GeoIP City database, which can be retrieved from:
* http://dev.maxmind.com/geoip/geoip2/geolite2/ (MaxMind DB binary)
*
* @param ip The IP address to look up.
* @param result The result of the geoip look up.
* @param len The maximum length of the result buffer.
*
* @return The result length on successful lookup, 0 otherwise.
*/
native geoip_region_code(const ip[], result[], len);
/**
* Look up the full region/state name for the given IP address.
*
* @note This native requires GeoIP City database, which can be retrieved from:
* http://dev.maxmind.com/geoip/geoip2/geolite2/ (MaxMind DB binary)
*
* @param ip The IP address to look up.
* @param result The result of the geoip look up.
* @param len The maximum length of the result buffer.
* @param id An optional player's index in order to return the result
* in the player's language, if supported.
* -1: the default language, which is english.
* 0: the server language. You can use LANG_SERVER define.
* >=1: the player's language.
*
* @return The result length on successful lookup, 0 otherwise.
*/
native geoip_region_name(const ip[], result[], len, id = -1);
/**
* Look up the full time zone for the given IP address.
* e.g. America/Los_Angeles, Europe/Paris.
*
* @note This native requires GeoIP City database, which can be retrieved from:
* http://dev.maxmind.com/geoip/geoip2/geolite2/ (MaxMind DB binary)
*
* @param ip The IP address to look up.
* @param result The result of the geoip look up.
* @param len The maximum length of the result buffer.
*
* @return The result length on successful lookup, 0 otherwise.
*/
native geoip_timezone(const ip[], result[], len);
/**
* Look up the city's latitude for the given IP address.
*
* @note This native requires GeoIP City database, which can be retrieved from:
* http://dev.maxmind.com/geoip/geoip2/geolite2/ (MaxMind DB binary)
*
* @param ip The IP address to look up.
*
* @return The result of the geoip look up, 0 if latitude is not found.
*/
native Float:geoip_latitude(const ip[]);
/**
* Look up the city's longitude for the given IP address.
*
* @note This native requires GeoIP City database, which can be retrieved from:
* http://dev.maxmind.com/geoip/geoip2/geolite2/ (MaxMind DB binary)
*
* @param ip The IP address to look up.
*
* @return The result of the geoip look up, 0 if longitude is not found.
*/
native Float:geoip_longitude(const ip[]);
/**
* Calculate the distance between geographical coordinates, latitude and longitude.
*
* @note This native requires GeoIP City database, which can be retrieved from:
* http://dev.maxmind.com/geoip/geoip2/geolite2/ (MaxMind DB binary)
*
* @param lat1 The first IP latitude.
* @param lon1 The first IP longitude.
* @param lat2 The second IP latitude.
* @param lon2 The second IP longitude.
* @param system The system of measurement, 0 = Metric(kilometers) or 1 = English(miles).
*
* @return The distance as result in specified system of measurement.
*/
#define SYSTEM_METRIC 0 // kilometers
#define SYSTEM_IMPERIAL 1 // statute miles
native Float:geoip_distance(Float:lat1, Float:lon1, Float:lat2, Float:lon2, system = SYSTEM_METRIC);
/**
* Look up the continent code for a given IP address.
*
* @note This native requires GeoIP City database, which can be retrieved from:
* http://dev.maxmind.com/geoip/geoip2/geolite2/ (MaxMind DB binary)
* @note The code can be retrieved as integer (See CONTINENT_* constants.) or string (2 characters).
* @note Possible continent codes are AF, AN, AS, EU, NA, OC, SA for
* Africa(1), Antarctica(2), Asia(3), Europe(4), North America(5), Oceania(6), South America(7).
*
* @param ip The IP address to look up.
* @param result The result of the geoip look up.
*
* @return The continent id on successful lookup, 0 otherwise.
*/
enum Continent
{
CONTINENT_UNKNOWN = 0,
CONTINENT_AFRICA,
CONTINENT_ANTARCTICA,
CONTINENT_ASIA,
CONTINENT_EUROPE,
CONTINENT_NORTH_AMERICA,
CONTINENT_OCEANIA,
CONTINENT_SOUTH_AMERICA,
};
native Continent:geoip_continent_code(const ip[], result[3]);
/**
* Look up the full continent name for the given IP address.
*
* @note This native requires GeoIP City database, which can be retrieved from:
* http://dev.maxmind.com/geoip/geoip2/geolite2/ (MaxMind DB binary)
*
* @param ip The IP address to look up.
* @param result The result of the geoip look up.
* @param len The maximum length of the result buffer.
* @param id An optional player's index in order to return the result
* in the player's language, if supported.
* -1: the default language, which is english.
* 0: the server language. You can use LANG_SERVER define.
* >=1: the player's language.
*
* @return The result length on successful lookup, 0 otherwise.
*/
native geoip_continent_name(const ip[], result[], len, id = -1);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,439 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Ham Sandwich Functions
//
/**
* Ham Sandwich is a module that is used to hook and call virtual functions of
* entities.
* Virtual functions are mod-specific functions. This means that in order
* for this to work on a mod, it needs to be configured with the gamedata
* file.
* Be very careful with parameter passing to these functions.
*/
#if defined _hamsandwich_included
#endinput
#endif
#define _hamsandwich_included
#include <ham_const>
#pragma reqlib hamsandwich
#if !defined AMXMODX_NOAUTOLOAD
#pragma loadlib hamsandwich
#endif
/**
* Hooks the virtual table for the specified entity class.
* An example would be: RegisterHam(Ham_TakeDamage, "player", "player_hurt");
* Look at the Ham enum for parameter lists.
*
* @param function The function to hook.
* @param EntityClass The entity classname to hook.
* @param callback The forward to call.
* @param post Whether or not to forward this in post.
* @param specialbot Whether or not to enable support for bot without "player" classname.
* @return Returns a handle to the forward. Use EnableHamForward/DisableHamForward to toggle the forward on or off.
*/
native HamHook:RegisterHam(Ham:function, const EntityClass[], const Callback[], Post=0, bool:specialbot = false);
/**
* Hooks the virtual table for the player class.
* An example would be: RegisterHam(Ham_TakeDamage, "player_hurt");
* Look at the Ham enum for parameter lists.
*
* @param function The function to hook.
* @param callback The forward to call.
* @param post Whether or not to forward this in post.
* @return Returns a handle to the forward. Use EnableHamForward/DisableHamForward to toggle the forward on or off.
*/
stock HamHook:RegisterHamPlayer(Ham:function, const Callback[], Post=0)
{
return RegisterHam(function, "player", Callback, Post, true);
}
/**
* Hooks the virtual table for the specified entity's class.
* An example would be: RegisterHam(Ham_TakeDamage, id, "player_hurt");
* Look at the Ham enum for parameter lists.
* Note: This will cause hooks for the entire internal class that the entity is
* not exclusively for the provided entity.
*
* @param function The function to hook.
* @param EntityId The entity classname to hook.
* @param callback The forward to call.
* @param post Whether or not to forward this in post.
* @return Returns a handle to the forward. Use EnableHamForward/DisableHamForward to toggle the forward on or off.
*/
native HamHook:RegisterHamFromEntity(Ham:function, EntityId, const Callback[], Post=0);
/**
* Stops a ham forward from triggering.
* Use the return value from RegisterHam as the parameter here!
*
* @param fwd The forward to stop.
*/
native DisableHamForward(HamHook:fwd);
/**
* Starts a ham forward back up.
* Use the return value from RegisterHam as the parameter here!
*
* @param fwd The forward to re-enable.
*/
native EnableHamForward(HamHook:fwd);
/**
* Executes the virtual function on the entity.
* Look at the Ham enum for parameter lists.
*
* @param function The function to call.
* @param id The id of the entity to execute it on.
*/
native ExecuteHam(Ham:function, this, any:...);
/**
* Executes the virtual function on the entity, this will trigger all hooks on that function.
* Be very careful about recursion!
* Look at the Ham enum for parameter lists.
*
* @param function The function to call.
* @param id The id of the entity to execute it on.
*/
native ExecuteHamB(Ham:function, this, any:...);
/**
* Gets the return status of the current hook.
* This is useful to determine what return natives to use.
*
* @return The current status of the hook (such as HAM_SUPERCEDE).
*/
native GetHamReturnStatus();
/**
* Gets the return value of a hook for hooks that return integers or booleans.
*
* @param output The variable to store the value in.
*/
native GetHamReturnInteger(&output);
/**
* Gets the return value of a hook for hooks that return float.
*
* @param output The variable to store the value in.
*/
native GetHamReturnFloat(&Float:output);
/**
* Gets the return value of a hook for hooks that return Vectors.
*
* @param output The variable to store the value in.
*/
native GetHamReturnVector(Float:output[3]);
/**
* Gets the return value of a hook for hooks that return entities.
*
* @param output The variable to store the value in. Will be -1 on null.
*/
native GetHamReturnEntity(&output);
/**
* Gets the return value of a hook for hooks that return strings.
*
* @param output The buffer to store the string in.
* @param size The string size of the buffer.
*/
native GetHamReturnString(output[], size);
/**
* Gets the original return value of a hook for hooks that return integers or booleans.
*
* @param output The variable to store the value in.
*/
native GetOrigHamReturnInteger(&output);
/**
* Gets the original return value of a hook for hooks that return floats.
*
* @param output The variable to store the value in.
*/
native GetOrigHamReturnFloat(&Float:output);
/**
* Gets the original return value of a hook for hooks that return Vectors.
*
* @param output The variable to store the value in.
*/
native GetOrigHamReturnVector(Float:output[3]);
/**
* Gets the original return value of a hook for hooks that return entities.
*
* @param output The variable to store the value in. -1 on null.
*/
native GetOrigHamReturnEntity(&output);
/**
* Gets the original return value of a hook for hooks that return strings.
*
* @param output The buffer to store the string in.
* @param size The size of the buffer.
*/
native GetOrigHamReturnString(output[], size);
/**
* Sets the return value of a hook that returns an integer or boolean.
* This needs to be used in conjunction with HAM_OVERRIDE or HAM_SUPERCEDE.
*
* @param value The value to set the return to.
*/
native SetHamReturnInteger(value);
/**
* Sets the return value of a hook that returns a float.
* This needs to be used in conjunction with HAM_OVERRIDE or HAM_SUPERCEDE.
*
* @param value The value to set the return to.
*/
native SetHamReturnFloat(Float:value);
/**
* Sets the return value of a hook that returns a Vector.
* This needs to be used in conjunction with HAM_OVERRIDE or HAM_SUPERCEDE.
*
* @param value The value to set the return to.
*/
native SetHamReturnVector(const Float:value[3]);
/**
* Sets the return value of a hook that returns an entity. Set to -1 for null.
* This needs to be used in conjunction with HAM_OVERRIDE or HAM_SUPERCEDE.
*
* @param value The value to set the return to.
*/
native SetHamReturnEntity(value);
/**
* Sets the return value of a hook that returns a string.
* This needs to be used in conjunction with HAM_OVERRIDE or HAM_SUPERCEDE.
*
* @param value The value to set the return to.
*/
native SetHamReturnString(const value[]);
/**
* Sets a parameter on the fly of the current hook. This has no effect in post hooks.
* Use this on parameters that are integers.
*
* @param which Which parameter to change. Starts at 1, and works up from the left to right. 1 is always "this".
* @param value The value to change it to.
*/
native SetHamParamInteger(which, value);
/**
* Sets a parameter on the fly of the current hook. This has no effect in post hooks.
* Use this on parameters that are floats.
*
* @param which Which parameter to change. Starts at 1, and works up from the left to right. 1 is always "this".
* @param value The value to change it to.
*/
native SetHamParamFloat(which, Float:value);
/**
* Sets a parameter on the fly of the current hook. This has no effect in post hooks.
* Use this on parameters that are Vectors.
*
* @param which Which parameter to change. Starts at 1, and works up from the left to right. 1 is always "this".
* @param value The value to change it to.
*/
native SetHamParamVector(which, const Float:value[3]);
/**
* Sets a parameter on the fly of the current hook. This has no effect in post hooks.
* Use this on parameters that are entities.
*
* @note Due to a historical bug, the changes made by this native are not reflected in the corresponding post forward
* for backward compatibility reasons. Use SetHamParamEntity2 if this is required.
*
* @param which Which parameter to change. Starts at 1, and works up from the left to right. 1 is always "this".
* @param value The value to change it to.
*/
native SetHamParamEntity(which, value);
/**
* Sets a parameter on the fly of the current hook. This has no effect in post hooks.
* Use this on parameters that are entities.
*
* @note Same as SetHamParamEntity except the changes made by this native are reflected in the corresponding post forward.
*
* @param which Which parameter to change. Starts at 1, and works up from the left to right. 1 is always "this".
* @param value The value to change it to.
*/
native SetHamParamEntity2(which, value);
/**
* Sets a parameter on the fly of the current hook. This has no effect in post hooks.
* Use this on parameters that are strings.
*
* @param which Which parameter to change. Starts at 1, and works up from the left to right. 1 is always "this".
* @param ouput The value to change it to.
*/
native SetHamParamString(which, const output[]);
/**
* Sets a parameter on the fly of the current hook. This has no effect in post hooks.
* Use this on parameters that are trace result handles.
*
* @param which Which parameter to change. Starts at 1, and works up from the left to right. 1 is always "this".
* @param tr_handle The value to change it to.
*/
native SetHamParamTraceResult(which, tr_handle);
/**
* Sets a parameter on the fly of the current hook. This has no effect in post hooks.
* Use this on parameters that are trace result handles.
*
* @param which Which parameter to change. Starts at 1, and works up from the left to right. 1 is always "this".
* @param iteminfo_handle The value to change it to.
*/
native SetHamParamItemInfo(which, iteminfo_handle);
/**
* Gets a parameter on the fly of the current hook.
* Use this on parameters that are iteminfo result handles.
*
* @param iteminfo_handle Item info handle.
* @param type Item info type. See HamItemInfo constants.
*/
native GetHamItemInfo(iteminfo_handle, HamItemInfo:type, any:...);
/**
* Sets a parameter on the fly of the current hook.
* Use this on parameters that are iteminfo result handles.
*
* @param iteminfo_handle Item info handle.
* @param type Item info type. See HamItemInfo_ constants.
*/
native SetHamItemInfo(iteminfo_handle, HamItemInfo:type, any:...);
/**
* Creates an ItemInfo handle. This value should never be altered.
* The handle can be used in Get/SetHamItemInfo.
*
* NOTE: You must call FreeHamItemInfo() on every handle made with CreateHamItemInfo().
*
* @return A new ItemInfo handle.
*/
native CreateHamItemInfo();
/**
* Frees an ItemIndo handle created with CreateHamItemInfo(). Do not call
* this more than once per handle, or on handles not created through
* CreateHamItemInfo().
*
* @param itemInfo_handle ItemInfo handle created via CreateHamItemInfo().
* @noreturn
*/
native FreeHamItemInfo(itemInfo_handle);
/**
* Returns whether or not the function for the specified Ham is valid.
* Things that would make it invalid would be bounds (an older module version
* may not have all of the functions), and the function not being found in
* the mod's hamdata.ini file.
*
* @param function The function to look up.
* @return true if the function is valid, false otherwise.
*/
native bool:IsHamValid(Ham:function);
/**
* This is used to compliment fakemeta's {get,set}_pdata_{int,float,string}.
* This requires the mod to have the pev and base fields set in hamdata.ini.
* Note this dereferences memory! Improper use of this will crash the server.
* This will return an index of the corresponding cbase field in private data.
* Returns -1 on a null entry.
*
* @param id The entity to examine the private data.
* @param offset The windows offset of the data.
* @param linuxdiff The linux difference of the data.
* @param macdiff The mac os x difference of the data.
* @return The index of the corresponding pdata field. -1 for none set.
*/
native get_pdata_cbase(id, offset, linuxdiff=5, macdiff=5);
/**
* This is used to compliment fakemeta's {get,set}_pdata_{int,float,string}.
* This requires the mod to have the pev and base fields set in hamdata.ini.
* This will set the corresponding cbase field in private data with the index.
* Pass -1 to null the entry.
*
* @param id The entity to examine the private data.
* @param offset The windows offset of the data.
* @param value The index to store, -1 for invalid
* @param linuxdiff The linux difference of the data.
* @param macdiff The mac os x difference of the data.
*/
native set_pdata_cbase(id, offset, value, linuxdiff=5, macdiff=5);
/**
* This is similar to the get_pdata_cbase, however it does not dereference memory.
* This is many times slower than get_pdata_cbase, and this should only be used
* for testing and finding of offsets, not actual release quality plugins.
* This will return an index of the corresponding cbase field in private data.
* Returns -1 on a null entry. -2 on an invalid entry.
*
* @param id Entry to examine the private data.
* @param offset The windows offset of the data.
* @param linuxdiff The linux difference of the data.
* @param macdiff The mac os x difference of the data.
* @return The index of the corresponding pdata field, -1 for null, -2 for invalid.
*/
native get_pdata_cbase_safe(id, offset, linuxdiff=5, macdiff=5);
// This is the callback from the module, this handles any fatal errors.
// This will in turn call the "HamFilter(Ham:id, HamError:err, const reason[])" public, if it exists.
// Return PLUGIN_HANDLED from within the HamFilter to stop the plugin from failing.
// Any other return value will fail the plugin.
// You do not need to have a HamFilter, if there is none, all fatal errors will fail the plugin.
// Do not modify this!
public __fatal_ham_error(Ham:id, HamError:err, const reason[])
{
new func=get_func_id("HamFilter", -1);
new bool:fail=true;
if (func != -1 && callfunc_begin_i(func, -1)==1)
{
callfunc_push_int(_:id);
callfunc_push_int(_:err);
callfunc_push_str(reason, false);
if (callfunc_end()==PLUGIN_HANDLED)
{
fail=false;
}
}
if (fail)
{
set_fail_state(reason);
}
}

View File

@ -0,0 +1,808 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Half-Life SDK Constants
//
#if defined _hlsdk_const_included
#endinput
#endif
#define _hlsdk_const_included
/**
* pev(entity, pev_button) or pev(entity, pev_oldbuttons) values
*/
#define IN_ATTACK (1<<0)
#define IN_JUMP (1<<1)
#define IN_DUCK (1<<2)
#define IN_FORWARD (1<<3)
#define IN_BACK (1<<4)
#define IN_USE (1<<5)
#define IN_CANCEL (1<<6)
#define IN_LEFT (1<<7)
#define IN_RIGHT (1<<8)
#define IN_MOVELEFT (1<<9)
#define IN_MOVERIGHT (1<<10)
#define IN_ATTACK2 (1<<11)
#define IN_RUN (1<<12)
#define IN_RELOAD (1<<13)
#define IN_ALT1 (1<<14)
#define IN_SCORE (1<<15) // Used by client.dll for when scoreboard is held down
/**
* pev(entity, pev_flags) values
*/
#define FL_FLY (1<<0) // Changes the SV_Movestep() behavior to not need to be on ground
#define FL_SWIM (1<<1) // Changes the SV_Movestep() behavior to not need to be on ground (but stay in water)
#define FL_CONVEYOR (1<<2)
#define FL_CLIENT (1<<3)
#define FL_INWATER (1<<4)
#define FL_MONSTER (1<<5)
#define FL_GODMODE (1<<6)
#define FL_NOTARGET (1<<7)
#define FL_SKIPLOCALHOST (1<<8) // Don't send entity to local host, it's predicting this entity itself
#define FL_ONGROUND (1<<9) // At rest / on the ground
#define FL_PARTIALGROUND (1<<10) // Not all corners are valid
#define FL_WATERJUMP (1<<11) // Player jumping out of water
#define FL_FROZEN (1<<12) // Player is frozen for 3rd person camera
#define FL_FAKECLIENT (1<<13) // JAC: fake client, simulated server side; don't send network messages to them
#define FL_DUCKING (1<<14) // Player flag -- Player is fully crouched
#define FL_FLOAT (1<<15) // Apply floating force to this entity when in water
#define FL_GRAPHED (1<<16) // Worldgraph has this ent listed as something that blocks a connection
#define FL_IMMUNE_WATER (1<<17)
#define FL_IMMUNE_SLIME (1<<18)
#define FL_IMMUNE_LAVA (1<<19)
#define FL_PROXY (1<<20) // This is a spectator proxy
#define FL_ALWAYSTHINK (1<<21) // Brush model flag -- call think every frame regardless of nextthink - ltime (for constantly changing velocity/path)
#define FL_BASEVELOCITY (1<<22) // Base velocity has been applied this frame (used to convert base velocity into momentum)
#define FL_MONSTERCLIP (1<<23) // Only collide in with monsters who have FL_MONSTERCLIP set
#define FL_ONTRAIN (1<<24) // Player is _controlling_ a train, so movement commands should be ignored on client during prediction.
#define FL_WORLDBRUSH (1<<25) // Not moveable/removeable brush entity (really part of the world, but represented as an entity for transparency or something)
#define FL_SPECTATOR (1<<26) // This client is a spectator, don't run touch functions, etc.
#define FL_CUSTOMENTITY (1<<29) // This is a custom entity
#define FL_KILLME (1<<30) // This entity is marked for death -- This allows the engine to kill ents at the appropriate time
#define FL_DORMANT (1<<31) // Entity is dormant, no updates to client
/**
* engfunc(EngFunc_WalkMove, entity, Float:yaw, Float:dist, iMode) iMode values
*/
#define WALKMOVE_NORMAL 0 // Normal walkmove
#define WALKMOVE_WORLDONLY 1 // Doesn't hit ANY entities, no matter what the solid type
#define WALKMOVE_CHECKONLY 2 // Move, but don't touch triggers
/**
* engfunc(EngFunc_MoveToOrigin, entity, Float:goal[3], Float:distance, moveType) moveType values
*/
#define MOVE_NORMAL 0 // normal move in the direction monster is facing
#define MOVE_STRAFE 1 // moves in direction specified, no matter which way monster is facing
/**
* pev(entity, pev_movetype) values
*/
#define MOVETYPE_NONE 0 // Never moves
#define MOVETYPE_WALK 3 // Player only - moving on the ground
#define MOVETYPE_STEP 4 // Gravity, special edge handling -- monsters use this
#define MOVETYPE_FLY 5 // No gravity, but still collides with stuff
#define MOVETYPE_TOSS 6 // Gravity/Collisions
#define MOVETYPE_PUSH 7 // No clip to world, push and crush
#define MOVETYPE_NOCLIP 8 // No gravity, no collisions, still do velocity/avelocity
#define MOVETYPE_FLYMISSILE 9 // Extra size to monsters
#define MOVETYPE_BOUNCE 10 // Just like Toss, but reflect velocity when contacting surfaces
#define MOVETYPE_BOUNCEMISSILE 11 // Bounce w/o gravity
#define MOVETYPE_FOLLOW 12 // Track movement of aiment
#define MOVETYPE_PUSHSTEP 13 // BSP model that needs physics/world collisions (uses nearest hull for world collision)
/**
* pev(entity, pev_solid) values
*
* @note Some movetypes will cause collisions independent of SOLID_NOT and
* SOLID_TRIGGER when the entity moves. SOLID only effects OTHER entities
* colliding with this one when they move - UGH!
*/
#define SOLID_NOT 0 // No interaction with other objects
#define SOLID_TRIGGER 1 // Touch on edge, but not blocking
#define SOLID_BBOX 2 // Touch on edge, block
#define SOLID_SLIDEBOX 3 // Touch on edge, but not an onground
#define SOLID_BSP 4 // BSP clip, touch on edge, block
/**
* pev(entity, pev_deadflag) values
*/
#define DEAD_NO 0 // Alive
#define DEAD_DYING 1 // Playing death animation or still falling off of a ledge waiting to hit ground
#define DEAD_DEAD 2 // Dead, lying still
#define DEAD_RESPAWNABLE 3
#define DEAD_DISCARDBODY 4
/**
* new Float:takedamage, pev(entity, pev_takedamage, takedamage) values
*/
#define DAMAGE_NO 0.0
#define DAMAGE_YES 1.0
#define DAMAGE_AIM 2.0
/**
* pev(entity, pev_effects) values
*/
#define EF_BRIGHTFIELD 1 // Swirling cloud of particles
#define EF_MUZZLEFLASH 2 // Single frame ELIGHT on entity attachment 0
#define EF_BRIGHTLIGHT 4 // DLIGHT centered at entity origin
#define EF_DIMLIGHT 8 // Player flashlight
#define EF_INVLIGHT 16 // Get lighting from ceiling
#define EF_NOINTERP 32 // Don't interpolate the next frame
#define EF_LIGHT 64 // Rocket flare glow sprite
#define EF_NODRAW 128 // Don't draw entity
/**
* Spectating camera mode constants
*
* @note These constants are linked to different camera modes available when you
* are spectating (either dead or when in spectator team). Usually this is
* stored in the pev_iuser1 field in Counter-Strike and Half-Life games.
*/
#define OBS_NONE 0
#define OBS_CHASE_LOCKED 1 // Locked Chase Cam
#define OBS_CHASE_FREE 2 // Free Chase Cam
#define OBS_ROAMING 3 // Free Look
#define OBS_IN_EYE 4 // First Person
#define OBS_MAP_FREE 5 // Free Overview
#define OBS_MAP_CHASE 6 // Chase Overview
/**
* engfunc(EngFunc_PointContents, Float:origin) return values
*/
#define CONTENTS_EMPTY -1
#define CONTENTS_SOLID -2
#define CONTENTS_WATER -3
#define CONTENTS_SLIME -4
#define CONTENTS_LAVA -5
#define CONTENTS_SKY -6
#define CONTENTS_ORIGIN -7 // Removed at csg time
#define CONTENTS_CLIP -8 // Changed to contents_solid
#define CONTENTS_CURRENT_0 -9
#define CONTENTS_CURRENT_90 -10
#define CONTENTS_CURRENT_180 -11
#define CONTENTS_CURRENT_270 -12
#define CONTENTS_CURRENT_UP -13
#define CONTENTS_CURRENT_DOWN -14
#define CONTENTS_TRANSLUCENT -15
#define CONTENTS_LADDER -16
#define CONTENT_FLYFIELD -17
#define CONTENT_GRAVITY_FLYFIELD -18
#define CONTENT_FOG -19
/**
* Instant damage values for use with the 3rd parameter of the "Damage" client
* message.
*/
#define DMG_GENERIC 0 // Generic damage was done
#define DMG_CRUSH (1<<0) // Crushed by falling or moving object
#define DMG_BULLET (1<<1) // Shot
#define DMG_SLASH (1<<2) // Cut, clawed, stabbed
#define DMG_BURN (1<<3) // Heat burned
#define DMG_FREEZE (1<<4) // Frozen
#define DMG_FALL (1<<5) // Fell too far
#define DMG_BLAST (1<<6) // Explosive blast damage
#define DMG_CLUB (1<<7) // Crowbar, punch, headbutt
#define DMG_SHOCK (1<<8) // Electric shock
#define DMG_SONIC (1<<9) // Sound pulse shockwave
#define DMG_ENERGYBEAM (1<<10) // Laser or other high energy beam
#define DMG_NEVERGIB (1<<12) // With this bit OR'd in, no damage type will be able to gib victims upon death
#define DMG_ALWAYSGIB (1<<13) // With this bit OR'd in, any damage type can be made to gib victims upon death.
#define DMG_DROWN (1<<14) // Drowning
#define DMG_PARALYZE (1<<15) // Slows affected creature down
#define DMG_NERVEGAS (1<<16) // Nerve toxins, very bad
#define DMG_POISON (1<<17) // Blood poisioning
#define DMG_RADIATION (1<<18) // Radiation exposure
#define DMG_DROWNRECOVER (1<<19) // Drowning recovery
#define DMG_ACID (1<<20) // Toxic chemicals or acid burns
#define DMG_SLOWBURN (1<<21) // In an oven
#define DMG_SLOWFREEZE (1<<22) // In a subzero freezer
#define DMG_MORTAR (1<<23) // Hit by air raid (done to distinguish grenade from mortar)
#define DMG_GRENADE (1<<24) // Counter-Strike only - Hit by HE grenade
#define DMG_TIMEBASED (~(0x3fff)) // Mask for time-based damage
/**
* Gib values used on client kill based on instant damage values
*/
#define GIB_NORMAL 0 // Gib if entity was overkilled
#define GIB_NEVER 1 // Never gib, no matter how much death damage is done ( freezing, etc )
#define GIB_ALWAYS 2 // Always gib ( Houndeye Shock, Barnacle Bite )
#define GIB_TRY_HEALTH -9000 // Gib players if their health is under this value. (GIB_NEVER overrides this value)
/**
* Valid constants for fNoMonsters parameter of EngFunc_TraceLine,
* EngFunc_TraceMonsterHull, EngFunc_TraceHull and EngFunc_TraceSphere.
*/
#define DONT_IGNORE_MONSTERS 0
#define IGNORE_MONSTERS 1
#define IGNORE_MISSILE 2
#define IGNORE_GLASS 0x100
/**
* The hullnumber paramater of EngFunc_TraceHull, EngFunc_TraceModel and
* DLLFunc_GetHullBounds
*/
#define HULL_POINT 0
#define HULL_HUMAN 1
#define HULL_LARGE 2
#define HULL_HEAD 3
/**
* global_get(glb_trace_flags)
*/
#define FTRACE_SIMPLEBOX (1<<0) // Traceline with a simple box
/**
* Used with get/set_es(es_handle, ES_eFlags, ...) (entity_state data structure)
*/
#define EFLAG_SLERP 1 // Do studio interpolation of this entity
/**
* @section pev(entity, pev_spawnflags) values
*/
/**
* func_train
*/
#define SF_TRAIN_WAIT_RETRIGGER 1
#define SF_TRAIN_START_ON 4 // Train is initially moving
#define SF_TRAIN_PASSABLE 8 // Train is not solid -- used to make water trains
/**
* func_wall_toggle
*/
#define SF_WALL_START_OFF 0x0001
#define SF_WALL_NOTSOLID 0x0008
/**
* func_converyor
*/
#define SF_CONVEYOR_VISUAL 0x0001
#define SF_CONVEYOR_NOTSOLID 0x0002
/**
* func_button
*/
#define SF_BUTTON_DONTMOVE 1
#define SF_BUTTON_TOGGLE 32 // Button stays pushed until reactivated
#define SF_BUTTON_SPARK_IF_OFF 64 // Button sparks in OFF state
#define SF_BUTTON_TOUCH_ONLY 256 // Button only fires as a result of USE key.
/**
* func_rot_button
*/
#define SF_ROTBUTTON_NOTSOLID 1
#define SF_ROTBUTTON_BACKWARDS 2
/**
* env_global
*/
#define SF_GLOBAL_SET 1 // Set global state to initial state on spawn
/**
* multisource
*/
#define SF_MULTI_INIT 1
/**
* momentary_rot_button
*/
#define SF_MOMENTARY_DOOR 0x0001
/**
* button_target
*/
#define SF_BTARGET_USE 0x0001
#define SF_BTARGET_ON 0x0002
/**
* func_door, func_water, func_door_rotating, momementary_door
*/
#define SF_DOOR_ROTATE_Y 0
#define SF_DOOR_START_OPEN 1
#define SF_DOOR_ROTATE_BACKWARDS 2
#define SF_DOOR_PASSABLE 8
#define SF_DOOR_ONEWAY 16
#define SF_DOOR_NO_AUTO_RETURN 32
#define SF_DOOR_ROTATE_Z 64
#define SF_DOOR_ROTATE_X 128
#define SF_DOOR_USE_ONLY 256 // Door must be opened by player's use button
#define SF_DOOR_NOMONSTERS 512 // Monster can't open
#define SF_DOOR_TOUCH_ONLY_CLIENTS 1024 // Only clients can touch
#define SF_DOOR_SILENT 0x80000000 // This bit marks that func_door are actually func_water
/**
* gibshooter
*/
#define SF_GIBSHOOTER_REPEATABLE 1 // Allows a gibshooter to be refired
/**
* env_funnel
*/
#define SF_FUNNEL_REVERSE 1 // Funnel effect repels particles instead of attracting them
/**
* env_bubbles
*/
#define SF_BUBBLES_STARTOFF 0x0001
/**
* env_blood
*/
#define SF_BLOOD_RANDOM 0x0001
#define SF_BLOOD_STREAM 0x0002
#define SF_BLOOD_PLAYER 0x0004
#define SF_BLOOD_DECAL 0x0008
/**
* env_shake
*/
#define SF_SHAKE_EVERYONE 0x0001 // Don't check radius
#define SF_SHAKE_DISRUPT 0x0002 // Disrupt controls
#define SF_SHAKE_INAIR 0x0004 // Shake players in air
/**
* env_fade
*/
#define SF_FADE_IN 0x0001 // Fade in, not out
#define SF_FADE_MODULATE 0x0002 // Modulate, don't blend
#define SF_FADE_ONLYONE 0x0004
/**
* env_beam, env_lightning
*/
#define SF_BEAM_STARTON 0x0001
#define SF_BEAM_TOGGLE 0x0002
#define SF_BEAM_RANDOM 0x0004
#define SF_BEAM_RING 0x0008
#define SF_BEAM_SPARKSTART 0x0010
#define SF_BEAM_SPARKEND 0x0020
#define SF_BEAM_DECALS 0x0040
#define SF_BEAM_SHADEIN 0x0080
#define SF_BEAM_SHADEOUT 0x0100
#define SF_BEAM_TEMPORARY 0x8000
/**
* env_sprite
*/
#define SF_SPRITE_STARTON 0x0001
#define SF_SPRITE_ONCE 0x0002
#define SF_SPRITE_TEMPORARY 0x8000
/**
* env_message
*/
#define SF_MESSAGE_ONCE 0x0001 // Fade in, not out
#define SF_MESSAGE_ALL 0x0002 // Send to all clients
/**
* env_explosion
*/
#define SF_ENVEXPLOSION_NODAMAGE (1<<0) // When set, ENV_EXPLOSION will not actually inflict damage
#define SF_ENVEXPLOSION_REPEATABLE (1<<1) // Can this entity be refired?
#define SF_ENVEXPLOSION_NOFIREBALL (1<<2) // Don't draw the fireball
#define SF_ENVEXPLOSION_NOSMOKE (1<<3) // Don't draw the smoke
#define SF_ENVEXPLOSION_NODECAL (1<<4) // Don't make a scorch mark
#define SF_ENVEXPLOSION_NOSPARKS (1<<5) // Don't make a scorch mark
/**
* func_tank
*/
#define SF_TANK_ACTIVE 0x0001
#define SF_TANK_PLAYER 0x0002
#define SF_TANK_HUMANS 0x0004
#define SF_TANK_ALIENS 0x0008
#define SF_TANK_LINEOFSIGHT 0x0010
#define SF_TANK_CANCONTROL 0x0020
#define SF_TANK_SOUNDON 0x8000
/**
* grenade
*/
#define SF_DETONATE 0x0001
/**
* item_suit
*/
#define SF_SUIT_SHORTLOGON 0x0001
/**
* game_score
*/
#define SF_SCORE_NEGATIVE 0x0001
#define SF_SCORE_TEAM 0x0002
/**
* game_text
*/
#define SF_ENVTEXT_ALLPLAYERS 0x0001
/**
* game_team_master
*/
#define SF_TEAMMASTER_FIREONCE 0x0001
#define SF_TEAMMASTER_ANYTEAM 0x0002
/**
* game_team_set
*/
#define SF_TEAMSET_FIREONCE 0x0001
#define SF_TEAMSET_CLEARTEAM 0x0002
/**
* game_player_hurt
*/
#define SF_PKILL_FIREONCE 0x0001
/**
* game_counter
*/
#define SF_GAMECOUNT_FIREONCE 0x0001
#define SF_GAMECOUNT_RESET 0x0002
/**
* game_player_equip
*/
#define SF_PLAYEREQUIP_USEONLY 0x0001
/**
* game_player_team
*/
#define SF_PTEAM_FIREONCE 0x0001
#define SF_PTEAM_KILL 0x0002
#define SF_PTEAM_GIB 0x0004
/**
* func_trackchange
*/
#define SF_PLAT_TOGGLE 0x0001
#define SF_TRACK_ACTIVATETRAIN 0x00000001
#define SF_TRACK_RELINK 0x00000002
#define SF_TRACK_ROTMOVE 0x00000004
#define SF_TRACK_STARTBOTTOM 0x00000008
#define SF_TRACK_DONT_MOVE 0x00000010
/**
* func_tracktrain
*/
#define SF_TRACKTRAIN_NOPITCH 0x0001
#define SF_TRACKTRAIN_NOCONTROL 0x0002
#define SF_TRACKTRAIN_FORWARDONLY 0x0004
#define SF_TRACKTRAIN_PASSABLE 0x0008
#define SF_PATH_DISABLED 0x00000001
#define SF_PATH_FIREONCE 0x00000002
#define SF_PATH_ALTREVERSE 0x00000004
#define SF_PATH_DISABLE_TRAIN 0x00000008
#define SF_PATH_ALTERNATE 0x00008000
#define SF_CORNER_WAITFORTRIG 0x001
#define SF_CORNER_TELEPORT 0x002
#define SF_CORNER_FIREONCE 0x004
/**
* func_plat
*/
#define SF_PLAT_TOGGLE 0x0001
/**
* path_track
*/
#define SF_PATH_DISABLED 0x00000001
#define SF_PATH_FIREONCE 0x00000002
#define SF_PATH_ALTREVERSE 0x00000004
#define SF_PATH_DISABLE_TRAIN 0x00000008
#define SF_PATH_ALTERNATE 0x00008000
/**
* path_corner
*/
#define SF_CORNER_WAITFORTRIG 0x001
#define SF_CORNER_TELEPORT 0x002
#define SF_CORNER_FIREONCE 0x004
/**
* trigger_push
*/
#define SF_TRIGGER_PUSH_START_OFF 2 // Spawnflag that makes trigger_push spawn turned OFF
/**
* trigger_hurt
*/
#define SF_TRIGGER_HURT_TARGETONCE 1 // Only fire hurt target once
#define SF_TRIGGER_HURT_START_OFF 2 // Spawnflag that makes trigger_push spawn turned OFF
#define SF_TRIGGER_HURT_NO_CLIENTS 8 // Spawnflag that makes trigger_push spawn turned OFF
#define SF_TRIGGER_HURT_CLIENTONLYFIRE 16 // Trigger hurt will only fire its target if it is hurting a client
#define SF_TRIGGER_HURT_CLIENTONLYTOUCH 32 // Only clients may touch this trigger
/**
* trigger_auto
*/
#define SF_AUTO_FIREONCE 0x0001
#define SF_AUTO_NORESET 0x0002
/**
* trigger_relay
*/
#define SF_RELAY_FIREONCE 0x0001
/**
* multi_manager
*/
#define SF_MULTIMAN_CLONE 0x80000000
#define SF_MULTIMAN_THREAD 0x00000001
/**
* env_render
* @note These are flags to indicate masking off various render parameters that
* are usually copied to the targets
*/
#define SF_RENDER_MASKFX (1<<0)
#define SF_RENDER_MASKAMT (1<<1)
#define SF_RENDER_MASKMODE (1<<2)
#define SF_RENDER_MASKCOLOR (1<<3)
/**
* trigger_changelevel
*/
#define SF_CHANGELEVEL_USEONLY 0x0002
/**
* trigger_endsection
*/
#define SF_ENDSECTION_USEONLY 0x0001
/**
* trigger_camera
*/
#define SF_CAMERA_PLAYER_POSITION 1
#define SF_CAMERA_PLAYER_TARGET 2
#define SF_CAMERA_PLAYER_TAKECONTROL 4
/**
* func_rotating
*/
#define SF_BRUSH_ROTATE_Y_AXIS 0
#define SF_BRUSH_ROTATE_INSTANT 1
#define SF_BRUSH_ROTATE_BACKWARDS 2
#define SF_BRUSH_ROTATE_Z_AXIS 4
#define SF_BRUSH_ROTATE_X_AXIS 8
#define SF_PENDULUM_AUTO_RETURN 16
#define SF_PENDULUM_PASSABLE 32
#define SF_BRUSH_ROTATE_SMALLRADIUS 128
#define SF_BRUSH_ROTATE_MEDIUMRADIUS 256
#define SF_BRUSH_ROTATE_LARGERADIUS 512
/**
* triggers
*/
#define SF_TRIGGER_ALLOWMONSTERS 1 // Monsters allowed to fire this trigger
#define SF_TRIGGER_NOCLIENTS 2 // Players not allowed to fire this trigger
#define SF_TRIGGER_PUSHABLES 4 // Only pushables can fire this trigger
#define SF_TRIG_PUSH_ONCE 1
/**
* trigger_multiple
*/
#define SF_TRIGGER_MULTIPLE_NOTOUCH 0x0001
/**
* trigger_counter
*/
#define SF_TRIGGER_COUNTER_NOMESSAGE 0x0001
/**
* func_breakable
*/
#define SF_BREAK_TRIGGER_ONLY 1 // May only be broken by trigger
#define SF_BREAK_TOUCH 2 // Can be 'crashed through' by running player (plate glass)
#define SF_BREAK_PRESSURE 4 // Can be broken by a player standing on it
#define SF_BREAK_CROWBAR 256 // Instant break if hit with crowbar
/**
* func_pushable (also func_breakable, so don't collide with those flags)
*/
#define SF_PUSH_BREAKABLE 128
/**
* light_spawn
*/
#define SF_LIGHT_START_OFF 1
#define SPAWNFLAG_NOMESSAGE 1
#define SPAWNFLAG_NOTOUCH 1
#define SPAWNFLAG_DROIDONLY 4
#define SPAWNFLAG_USEONLY 1 // Can't be touched, must be used (buttons)
/**
* Monster Spawnflags
*/
#define SF_MONSTER_WAIT_TILL_SEEN 1 // Spawnflag that makes monsters wait until player can see them before attacking
#define SF_MONSTER_GAG 2 // No idle noises from this monster
#define SF_MONSTER_HITMONSTERCLIP 4
#define SF_MONSTER_PRISONER 16 // Monster won't attack anyone, no one will attacke him
#define SF_MONSTER_WAIT_FOR_SCRIPT 128 // Spawnflag that makes monsters wait to check for attacking until the script is done or they've been attacked
#define SF_MONSTER_PREDISASTER 256 // This is a predisaster scientist or barney; influences how they speak
#define SF_MONSTER_FADECORPSE 512 // Fade out corpse after death
#define SF_MONSTER_FALL_TO_GROUND 0x80000000
#define SF_MONSTER_TURRET_AUTOACTIVATE 32
#define SF_MONSTER_TURRET_STARTINACTIVE 64
#define SF_MONSTER_WAIT_UNTIL_PROVOKED 64 // Don't attack the player unless provoked
/**
* info_decal
*/
#define SF_DECAL_NOTINDEATHMATCH 2048
/**
* worldspawn
*/
#define SF_WORLD_DARK 0x0001 // Fade from black at startup
#define SF_WORLD_TITLE 0x0002 // Display game title at startup
#define SF_WORLD_FORCETEAM 0x0004 // Force teams
/**
* Set this bit on guns and stuff that should never respawn
*/
#define SF_NORESPAWN (1<<30)
/**
* @endsection
*/
/**
* Train status values
*/
#define TRAIN_ACTIVE 0x80
#define TRAIN_NEW 0xc0
#define TRAIN_OFF 0x00
#define TRAIN_NEUTRAL 0x01
#define TRAIN_SLOW 0x02
#define TRAIN_MEDIUM 0x03
#define TRAIN_FAST 0x04
#define TRAIN_BACK 0x05
/**
* Valve Mod Weapon Constants
*/
#define HLI_HEALTHKIT 1
#define HLI_ANTIDOTE 2
#define HLI_SECURITY 3
#define HLI_BATTERY 4
#define HLW_NONE 0
#define HLW_CROWBAR 1
#define HLW_GLOCK 2
#define HLW_PYTHON 3
#define HLW_MP5 4
#define HLW_CHAINGUN 5
#define HLW_CROSSBOW 6
#define HLW_SHOTGUN 7
#define HLW_RPG 8
#define HLW_GAUSS 9
#define HLW_EGON 10
#define HLW_HORNETGUN 11
#define HLW_HANDGRENADE 12
#define HLW_TRIPMINE 13
#define HLW_SATCHEL 14
#define HLW_SNARK 15
#define HLW_SUIT 31
#define HLW_ALLWEAPONS (~(1<<HLW_SUIT))
/**
* Item's flags
*/
#define ITEM_FLAG_SELECTONEMPTY (1<<0)
#define ITEM_FLAG_NOAUTORELOAD (1<<1)
#define ITEM_FLAG_NOAUTOSWITCHEMPTY (1<<2)
#define ITEM_FLAG_LIMITINWORLD (1<<3)
#define ITEM_FLAG_EXHAUSTIBLE (1<<4)
/**
* PlaybackEvent flags
*/
#define FEV_NOTHOST (1<<0) // Skip local host for event send.
#define FEV_RELIABLE (1<<1) // Send the event reliably. You must specify the origin and angles
// for this to work correctly on the server for anything
// that depends on the event origin/angles. I.e., the origin/angles are not
// taken from the invoking edict for reliable events.
#define FEV_GLOBAL (1<<2) // Don't restrict to PAS/PVS, send this event to _everybody_ on the server ( useful for stopping CHAN_STATIC
// sounds started by client event when client is not in PVS anymore ( hwguy in TFC e.g. ).
#define FEV_UPDATE (1<<3) // If this client already has one of these events in its queue, just update the event instead of sending it as a duplicate
#define FEV_HOSTONLY (1<<4) // Only send to entity specified as the invoker
#define FEV_SERVER (1<<5) // Only send if the event was created on the server.
#define FEV_CLIENT (1<<6) // Only issue event client side ( from shared code )
/**
* Cap bits to indicate what an object's capabilities are, currently used for
* save/restore and level transitions.
*/
#define FCAP_CUSTOMSAVE 0x00000001
#define FCAP_ACROSS_TRANSITION 0x00000002 // should transfer between transitions
#define FCAP_MUST_SPAWN 0x00000004 // Spawn after restore
#define FCAP_DONT_SAVE 0x80000000 // Don't save this
#define FCAP_IMPULSE_USE 0x00000008 // can be used by the player
#define FCAP_CONTINUOUS_USE 0x00000010 // can be used by the player
#define FCAP_ONOFF_USE 0x00000020 // can be used by the player
#define FCAP_DIRECTIONAL_USE 0x00000040 // Player sends +/- 1 when using (currently only tracktrains)
#define FCAP_MASTER 0x00000080 // Can be used to "master" other entities (like multisource)
#define FCAP_MUST_RESET 0x00000100 // Should reset on the new round
#define FCAP_MUST_RELEASE 0x00000200 // Should release on the new round
#define FCAP_DONT_SAVE 0x80000000 // Don't save this
// UNDONE: This will ignore transition volumes (trigger_transition), but not the PVS!!!
#define FCAP_FORCE_TRANSITION 0x00000080 // ALWAYS goes across transitions
/**
* All monsters need this data
*/
#define DONT_BLEED -1
#define BLOOD_COLOR_RED 247
#define BLOOD_COLOR_YELLOW 195
#define BLOOD_COLOR_GREEN BLOOD_COLOR_YELLOW
/**
* Player physics flags
*/
#define PFLAG_ONLADDER (1<<0)
#define PFLAG_ONSWING (1<<0)
#define PFLAG_ONTRAIN (1<<1)
#define PFLAG_ONBARNACLE (1<<2)
#define PFLAG_DUCKING (1<<3) // In the process of ducking, but totally squatted yet
#define PFLAG_USING (1<<4) // Using a continuous entity
#define PFLAG_OBSERVER (1<<5) // Player is locked in stationary cam mode. Spectators can move, observers can't.
/**
* Player hide HUD values
*/
#define HIDEHUD_WEAPONS (1<<0)
#define HIDEHUD_FLASHLIGHT (1<<1)
#define HIDEHUD_ALL (1<<2)
#define HIDEHUD_HEALTH (1<<3)
#define HIDEHUD_TIMER (1<<4)
#define HIDEHUD_MONEY (1<<5)
#define HIDEHUD_CROSSHAIR (1<<6)
#define HIDEHUD_OBSERVER_CROSSHAIR (1<<7)
/**
* Entity classification
*/
#define CLASS_NONE 0
#define CLASS_MACHINE 1
#define CLASS_PLAYER 2
#define CLASS_HUMAN_PASSIVE 3
#define CLASS_HUMAN_MILITARY 4
#define CLASS_ALIEN_MILITARY 5
#define CLASS_ALIEN_PASSIVE 6
#define CLASS_ALIEN_MONSTER 7
#define CLASS_ALIEN_PREY 8
#define CLASS_ALIEN_PREDATOR 9
#define CLASS_INSECT 10
#define CLASS_PLAYER_ALLY 11
#define CLASS_PLAYER_BIOWEAPON 12 // hornets and snarks.launched by players
#define CLASS_ALIEN_BIOWEAPON 13 // hornets and snarks.launched by the alien menace
#define CLASS_VEHICLE 14
#define CLASS_BARNACLE 99 // special because no one pays attention to it, and it eats a wide cross-section of creatures.
/**
* Entities that toggle (buttons/triggers/doors) need this
*/
#define TS_AT_TOP 0
#define TS_AT_BOTTOM 1
#define TS_GOING_UP 2
#define TS_GOING_DOWN 3
/**
* Entity use states (buttons/triggers/platforms)
*/
#define USE_OFF 0
#define USE_ON 1
#define USE_SET 2
#define USE_TOGGLE 3

View File

@ -0,0 +1,777 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// JSON Natives
//
#if defined _json_included
#endinput
#endif
#define _json_included
#pragma reqlib json
#if !defined AMXMODX_NOAUTOLOAD
#pragma loadlib json
#endif
/*
* JSON types
*/
enum JSONType
{
JSONError = -1,
JSONNull = 1,
JSONString = 2,
JSONNumber = 3,
JSONObject = 4,
JSONArray = 5,
JSONBoolean = 6
};
/*
* JSON invalid handle
*/
enum JSON
{
Invalid_JSON = -1
}
/**
* Helper macros for checking type
*/
#define json_is_object(%1) (%1 != Invalid_JSON && json_get_type(%1) == JSONObject)
#define json_is_array(%1) (%1 != Invalid_JSON && json_get_type(%1) == JSONArray)
#define json_is_string(%1) (%1 != Invalid_JSON && json_get_type(%1) == JSONString)
#define json_is_number(%1) (%1 != Invalid_JSON && json_get_type(%1) == JSONNumber)
#define json_is_bool(%1) (%1 != Invalid_JSON && json_get_type(%1) == JSONBoolean)
#define json_is_null(%1) (%1 != Invalid_JSON && json_get_type(%1) == JSONNull)
#define json_is_true(%1) (%1 != Invalid_JSON && json_is_bool(%1) && json_get_bool(%1))
#define json_is_false(%1) (%1 != Invalid_JSON && json_is_bool(%1) && !json_get_bool(%1))
/**
* Parses JSON string or a file that contains JSON.
*
* @note Needs to be freed using json_free() native.
*
* @param string String to parse
* @param is_file True to treat string param as filename, false otherwise
* @param with_comments True if parsing JSON includes comments (it will ignore them), false otherwise
*
* @return JSON handle, Invalid_JSON if error occurred
*/
native JSON:json_parse(const string[], bool:is_file = false, bool:with_comments = false);
/**
* Checks if the first value is the same as the second one.
*
* @param value1 JSON handle
* @param value2 JSON handle
*
* @return True if they are the same, false otherwise
* @error If passed value is not a valid handle
*/
native bool:json_equals(const JSON:value1, const JSON:value2);
/**
* Validates json by checking if object have identically named
* fields with matching types.
*
* @note Schema {"name":"", "age":0} will validate
* {"name":"Joe", "age":25} and {"name":"Joe", "age":25, "gender":"m"},
* but not {"name":"Joe"} or {"name":"Joe", "age":"Cucumber"}.
*
* @note In case of arrays, only first value in schema
* is checked against all values in tested array.
*
* @note Empty objects ({}) validate all objects,
* empty arrays ([]) validate all arrays,
* null validates values of every type.
*
* @param schema JSON handle
* @param value JSON handle
*
* @return True if passed value is valid, false otherwise
* @error If a schema handle or value handle is invalid
*/
native bool:json_validate(const JSON:schema, const JSON:value);
/**
* Gets value's parent handle.
*
* @note Parent's handle needs to be freed using json_free() native.
*
* @param value JSON handle
*
* @return Parent's handle
*/
native JSON:json_get_parent(const JSON:value);
/**
* Gets JSON type of passed value.
*
* @param value JSON handle
*
* @return JSON type (JSONType constants)
* @error If a value handle is invalid
*/
native JSONType:json_get_type(const JSON:value);
/**
* Inits an empty object.
*
* @note Needs to be freed using json_free() native.
*
* @return JSON handle, Invalid_JSON if error occurred
*/
native JSON:json_init_object();
/**
* Inits an empty array.
*
* @note Needs to be freed using json_free() native.
*
* @return JSON handle, Invalid_JSON if error occurred
*/
native JSON:json_init_array();
/**
* Inits string data.
*
* @note Needs to be freed using json_free() native.
*
* @param value String that the handle will be initialized with
*
* @return JSON handle, Invalid_JSON if error occurred
*/
native JSON:json_init_string(const value[]);
/**
* Inits a number.
*
* @note Needs to be freed using json_free() native.
*
* @param value Integer number that the handle will be initialized with
*
* @return JSON handle, Invalid_JSON if error occurred
*/
native JSON:json_init_number(value);
/**
* Inits a real number.
*
* @note Needs to be freed using json_free() native.
*
* @param value Real number that the handle will be initialized with
*
* @return JSON handle, Invalid_JSON if error occurred
*/
native JSON:json_init_real(Float:value);
/**
* Inits a boolean value.
*
* @note Needs to be freed using json_free() native.
*
* @param value Boolean value that the handle will be initialized with
*
* @return JSON handle, Invalid_JSON if error occurred
*/
native JSON:json_init_bool(bool:value);
/**
* Inits a null.
*
* @note Needs to be freed using json_free() native.
*
* @return JSON handle, Invalid_JSON if error occurred
*/
native JSON:json_init_null();
/**
* Creates deep copy of passed value.
*
* @note Needs to be freed using json_free() native.
*
* @param value JSON handle to be copied
*
* @return JSON handle, Invalid_JSON if error occurred
* @error If passed value is not a valid handle
*/
native JSON:json_deep_copy(const JSON:value);
/**
* Frees handle.
*
* @param handle JSON handle to be freed
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid handle
*/
native bool:json_free(&JSON:handle);
/**
* Gets string data.
*
* @param value JSON handle
* @param buffer Buffer to copy string to
* @param maxlen Maximum size of the buffer
*
* @return The number of cells written to the buffer
* @error If passed value is not a valid handle
*/
native json_get_string(const JSON:value, buffer[], maxlen);
/**
* Gets a number.
*
* @param value JSON handle
*
* @return Number
* @error If passed value is not a valid handle
*/
native json_get_number(const JSON:value);
/**
* Gets a real number.
*
* @param value JSON handle
*
* @return Real number
* @error If passed value is not a valid handle
*/
native Float:json_get_real(const JSON:value);
/**
* Gets a boolean value.
*
* @param value JSON handle
*
* @return Boolean value
* @error If passed value is not a valid handle
*/
native bool:json_get_bool(const JSON:value);
/**
* Gets a value from the array.
*
* @note Needs to be freed using json_free() native.
*
* @param array Array handle
* @param index Position in the array (starting from 0)
*
* @return JSON handle, Invalid_JSON if error occurred
* @error If passed handle is not a valid array
*/
native JSON:json_array_get_value(const JSON:array, index);
/**
* Gets string data from the array.
*
* @param array Array handle
* @param index Position in the array (starting from 0)
* @param buffer Buffer to copy string to
* @param maxlen Maximum size of the buffer
*
* @return The number of cells written to the buffer
* @error If passed handle is not a valid array
*/
native json_array_get_string(const JSON:array, index, buffer[], maxlen);
/**
* Gets a number from the array.
*
* @param array Array handle
* @param index Position in the array (starting from 0)
*
* @return The number as integer
* @error If passed handle is not a valid array
*/
native json_array_get_number(const JSON:array, index);
/**
* Gets a real number from the array.
*
* @param array Array handle
* @param index Position in the array (starting from 0)
*
* @return The number as float
* @error If passed handle is not a valid array
*/
native Float:json_array_get_real(const JSON:array, index);
/**
* Gets a boolean value from the array.
*
* @param array Array handle
* @param index Position in the array (starting from 0)
*
* @return Boolean value
* @error If passed handle is not a valid array
*/
native bool:json_array_get_bool(const JSON:array, index);
/**
* Gets count of the elements in the array.
*
* @param array Array handle
*
* @return Number of elements in the array
* @error If passed handle is not a valid array
*/
native json_array_get_count(const JSON:array);
/**
* Replaces an element in the array with value.
*
* @param array Array handle
* @param index Position in the array to be replaced
* @param value JSON handle to set
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_replace_value(JSON:array, index, const JSON:value);
/**
* Replaces an element in the array with string data.
*
* @param array Array handle
* @param index Position in the array to be replaced
* @param string String to copy
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_replace_string(JSON:array, index, const string[]);
/**
* Replaces an element in the array with number.
*
* @param array Array handle
* @param index Position in the array to be replaced
* @param number Number to set
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_replace_number(JSON:array, index, number);
/**
* Replaces an element in the array with real number.
*
* @param array Array handle
* @param index Position in the array to be replaced
* @param number Real number to set
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_replace_real(JSON:array, index, Float:number);
/**
* Replaces an element in the array with boolean value.
*
* @param array Array handle
* @param index Position in the array to be replaced
* @param boolean Boolean value to set
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_replace_bool(JSON:array, index, bool:boolean);
/**
* Replaces an element in the array with null.
*
* @param array Array handle
* @param index Position in the array to be replaced
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_replace_null(JSON:array, index);
/**
* Appends a value in the array.
*
* @param array Array handle
* @param value JSON handle to set
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_append_value(JSON:array, const JSON:value);
/**
* Appends string data in the array.
*
* @param array Array handle
* @param string String to copy
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_append_string(JSON:array, const string[]);
/**
* Appends a number in the array.
*
* @param array Array handle
* @param number Number to set
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_append_number(JSON:array, number);
/**
* Appends a real number in the array.
*
* @param array Array handle
* @param number Real number to set
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_append_real(JSON:array, Float:number);
/**
* Appends a boolean value in the array.
*
* @param array Array handle
* @param boolean Boolean value to set
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_append_bool(JSON:array, bool:boolean);
/**
* Appends a null in the array.
*
* @param array Array handle
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_append_null(JSON:array);
/**
* Removes an element from the array.
*
* @note Order of values in array may change during execution.
*
* @param array Array handle
* @param index Position in the array (starting from 0)
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_remove(JSON:array, index);
/**
* Removes all elements from the array.
*
* @param array Array handle
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid array
*/
native bool:json_array_clear(JSON:array);
/**
* Gets a value from the object.
*
* @note Needs to be freed using json_free() native.
* @note If dot notation is used some values may be inaccessible
* because valid names in JSON can contain dots.
*
* @param object Object handle
* @param name Key name
* @param dot_not True to use dot notation, false to not
*
* @return JSON handle, Invalid_JSON if error occurred
* @error If passed handle is not a valid object
*/
native JSON:json_object_get_value(const JSON:object, const name[], bool:dot_not = false);
/**
* Gets string data from the object.
*
* @note If dot notation is used some values may be inaccessible
* because valid names in JSON can contain dots.
*
* @param object Object handle
* @param name Key name
* @param buffer Buffer to copy string to
* @param maxlen Maximum size of the buffer
* @param dot_not True to use dot notation, false to not
*
* @return The number of cells written to the buffer
* @error If passed handle is not a valid object
*/
native json_object_get_string(const JSON:object, const name[], buffer[], maxlen, bool:dot_not = false);
/**
* Gets a number from the object.
*
* @note If dot notation is used some values may be inaccessible
* because valid names in JSON can contain dots.
*
* @param object Object handle
* @param name Key name
* @param dot_not True to use dot notation, false to not
*
* @return Number
* @error If passed handle is not a valid object
*/
native json_object_get_number(const JSON:object, const name[], bool:dot_not = false);
/**
* Gets a real number from the object.
*
* @note If dot notation is used some values may be inaccessible
* because valid names in JSON can contain dots.
*
* @param object Object handle
* @param name Key name
* @param dot_not True to use dot notation, false to not
*
* @return Real number
* @error If passed handle is not a valid object
*/
native Float:json_object_get_real(const JSON:object, const name[], bool:dot_not = false);
/**
* Gets a boolean value from the object.
*
* @note If dot notation is used some values may be inaccessible
* because valid names in JSON can contain dots.
*
* @param object Object handle
* @param name Key name
* @param dot_not True to use dot notation, false to not
*
* @return Boolean value
* @error If passed handle is not a valid object
*/
native bool:json_object_get_bool(const JSON:object, const name[], bool:dot_not = false);
/**
* Gets count of the keys in the object.
*
* @param object Object handle
*
* @return Keys count
* @error If passed handle is not a valid object
*/
native json_object_get_count(const JSON:object);
/**
* Gets name of the object's key.
*
* @param object Object handle
* @param index Position from which get key name
* @param buffer Buffer to copy string to
* @param maxlen Maximum size of the buffer
*
* @return The number of cells written to the buffer
* @error If passed handle is not a valid object
*/
native json_object_get_name(const JSON:object, index, buffer[], maxlen);
/**
* Gets a value at the specified position from the object.
*
* @note Needs to be freed using json_free() native.
*
* @param object Object handle
* @param index Position from which get key name
*
* @return JSON handle, Invalid_JSON if error occurred
* @error If passed handle is not a valid object
*/
native JSON:json_object_get_value_at(const JSON:object, index);
/**
* Checks if the object has a value with a specific name and type.
*
* @param object Object handle
* @param name Key name
* @param type Type of value, if JSONError type will not be checked
* @param dot_not True to use dot notation, false to not
*
* @return True if has, false if not
* @error If passed handle is not a valid object
*/
native bool:json_object_has_value(const JSON:object, const name[], JSONType:type = JSONError, bool:dot_not = false);
/**
* Sets a value in the object.
*
* @note If dot notation is used some values may be inaccessible
* because valid names in JSON can contain dots.
* @note It also removes the old value if any.
*
* @param object Object handle
* @param name Key name
* @param value JSON handle to set
* @param dot_not True to use dot notation, false to not
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid object
*/
native bool:json_object_set_value(JSON:object, const name[], const JSON:value, bool:dot_not = false);
/**
* Sets string data in the object.
*
* @note If dot notation is used some values may be inaccessible
* because valid names in JSON can contain dots.
* @note It also removes the old value if any.
*
* @param object Object handle
* @param name Key name
* @param string String to copy
* @param dot_not True to use dot notation, false to not
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid object
*/
native bool:json_object_set_string(JSON:object, const name[], const string[], bool:dot_not = false);
/**
* Sets a number in the object.
*
* @note If dot notation is used some values may be inaccessible
* because valid names in JSON can contain dots.
* @note It also removes the old value if any.
*
* @param object Object handle
* @param name Key name
* @param number Number to set
* @param dot_not True to use dot notation, false to not
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid object
*/
native bool:json_object_set_number(JSON:object, const name[], number, bool:dot_not = false);
/**
* Sets a real number in the object.
*
* @note If dot notation is used some values may be inaccessible
* because valid names in JSON can contain dots.
* @note It also removes the old value if any.
*
* @param object Object handle
* @param name Key name
* @param number Real number to set
* @param dot_not True to use dot notation, false to not
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid object
*/
native bool:json_object_set_real(JSON:object, const name[], Float:number, bool:dot_not = false);
/**
* Sets a boolean value in the object.
*
* @note If dot notation is used some values may be inaccessible
* because valid names in JSON can contain dots.
* @note It also removes the old value if any.
*
* @param object Object handle
* @param name Key name
* @param boolean Boolean value to set
* @param dot_not True to use dot notation, false to not
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid object
*/
native bool:json_object_set_bool(JSON:object, const name[], bool:boolean, bool:dot_not = false);
/**
* Sets a null in the object.
*
* @note If dot notation is used some values may be inaccessible
* because valid names in JSON can contain dots.
* @note It also removes the old value if any.
*
* @param object Object handle
* @param name Key name
* @param dot_not True to use dot notation, false to not
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid object
*/
native bool:json_object_set_null(JSON:object, const name[], bool:dot_not = false);
/**
* Removes a key and its value in the object.
*
* @note If dot notation is used some values may be inaccessible
* because valid names in JSON can contain dots.
*
* @param object Object handle
* @param name Key name
* @param dot_not True to use dot notation, false to not
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid object
*/
native bool:json_object_remove(JSON:object, const name[], bool:dot_not = false);
/**
* Removes all keys and their values in the object.
*
* @param object Object handle
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid object
*/
native bool:json_object_clear(JSON:object);
/**
* Gets size of serialization.
*
* @param value JSON handle
* @param pretty True to count size for pretty format, false to not
* @param null_byte True to include null byte, false to not
*
* @return Size of serialized string
* @error If passed handle is not a valid value
*/
native json_serial_size(const JSON:value, bool:pretty = false, bool:null_byte = false);
/**
* Copies serialized string to the buffer.
*
* @param value JSON handle
* @param buffer Buffer to copy string to
* @param maxlen Maximum size of the buffer
* @param pretty True to format pretty JSON string, false to not
*
* @return The number of cells written to the buffer
* @error If passed handle is not a valid value
*/
native json_serial_to_string(const JSON:value, buffer[], maxlen, bool:pretty = false);
/**
* Copies serialized string to the file.
*
* @param value JSON handle
* @param file Path to the file
* @param pretty True to format pretty JSON string, false to not
*
* @return True if succeed, false otherwise
* @error If passed handle is not a valid value
*/
native bool:json_serial_to_file(const JSON:value, const file[], bool:pretty = false);

View File

@ -0,0 +1,93 @@
native g_ArrayMapList();
#define prefix "^1[^4f0.gg^1]"
new sv_airaccelerate, sv_gravity;
public VIP_ACCESS(id) {
new access[32];
if(id > 0) {
if(get_user_flags(id) & ADMIN_IMMUNITY)
access = "Head Admin";
if(get_user_flags(id) & ADMIN_LEVEL_E)
access = "Honorary";
if(get_user_flags(id) & ADMIN_LEVEL_H)
access = "VIP LVL 3";
if(get_user_flags(id) & ADMIN_LEVEL_G)
access = "VIP LVL 2";
if(get_user_flags(id) & ADMIN_LEVEL_F)
access = "VIP LVL 1";
if(get_user_flags(id) & ADMIN_USER)
access = "User";
}
else
access = "Server";
return access;
}
stock StringTimer(const Float:flRealTime, szOutPut[], const iSizeOutPut) {
static Float:flTime, iMinutes, iSeconds, iMiliSeconds, Float:iMili;
new string[12]
flTime = flRealTime;
if(flTime < 0.0)
flTime = 0.0;
iMinutes = floatround(flTime / 60, floatround_floor);
iSeconds = floatround(flTime - (iMinutes * 60), floatround_floor);
iMili = floatfract(flRealTime);
formatex(string, 11, "%.02f", iMili >= 0 ? iMili + 0.005 : iMili - 0.005);
iMiliSeconds = floatround(str_to_float(string) * 100, floatround_floor);
formatex(szOutPut, iSizeOutPut, "%02d:%02d.%02d", iMinutes, iSeconds, iMiliSeconds);
}
stock Weapon_Converter(speed) {
new weapon_name[15];
if(speed == 250) weapon_name = "USP [250]";
if(speed == 245) weapon_name = "P90 [245]";
if(speed == 240) weapon_name = "FAMAS [240]";
if(speed == 235) weapon_name = "SG550 [235]";
if(speed == 230) weapon_name = "M4A1 [230]";
if(speed == 221) weapon_name = "AK47 [221]";
if(speed == 220) weapon_name = "M249 [220]";
if(speed == 210) weapon_name = "AWP [210]";
return weapon_name;
}
stock Weapon_ID_Converter(speed) {
new weapon_name[15];
if(speed == 250) weapon_name = "weapon_usp";
if(speed == 245) weapon_name = "weapon_p90";
if(speed == 240) weapon_name = "weapon_famas";
if(speed == 235) weapon_name = "weapon_sg550";
if(speed == 230) weapon_name = "weapon_m4a1";
if(speed == 221) weapon_name = "weapon_ak47";
if(speed == 220) weapon_name = "weapon_m249";
if(speed == 210) weapon_name = "weapon_awp";
return weapon_name;
}
stock ham_give_weapon(id, weapon[]) {
if(!equal(weapon,"weapon_",7))
return 0;
new wEnt = engfunc(EngFunc_CreateNamedEntity,engfunc(EngFunc_AllocString,weapon));
if(!pev_valid(wEnt))
return 0;
set_pev(wEnt,pev_spawnflags,SF_NORESPAWN);
dllfunc(DLLFunc_Spawn,wEnt);
if(!ExecuteHamB(Ham_AddPlayerItem,id,wEnt)) {
if(pev_valid(wEnt)) set_pev(wEnt,pev_flags,pev(wEnt,pev_flags) | FL_KILLME);
return 0;
}
ExecuteHamB(Ham_Item_AttachToPlayer,wEnt,id);
return 1;
}
stock kz_vector_add(const Float:in1[], const Float:in2[], Float:out[]) {
out[0] = in1[0] + in2[0];
out[1] = in1[1] + in2[1];
out[2] = in1[2] + in2[2];
}
stock kz_vecotr_mul_scalar(const Float:vec[], Float:scalar, Float:out[]) {
out[0] = vec[0] * scalar;
out[1] = vec[1] * scalar;
out[2] = vec[2] * scalar;
}

View File

@ -0,0 +1,435 @@
#define ACCESS_H ADMIN_LEVEL_E
#define ACCESS_3 ADMIN_LEVEL_H
#define ACCESS_2 ADMIN_LEVEL_G
#define ACCESS_1 ADMIN_LEVEL_F
#define ACCESS_0 ADMIN_USER
new Handle:g_SqlTuple;
new Handle:SqlConnection;
new g_Error[512];
// MapID in kz_maps SQL Table
new kz_mapID;
new kz_maptype[25];
new delete_entity;
new gMapName[64];
new weapon_name[33];
new Float:timer_time[33];
new Float:Update_timer[33];
// my time in top15
new Float:kz_my_protime[33];
new Float:kz_my_nubtime[33];
// Speclist
new SpecList[33] = { true, ... };
new SpecAdmImm[33];
// SQL Config
new InvisUser[33];
new InvisWater[33];
new full_Invisible[33];
new noTeleport[32];
new ShowTime[33];
new SaveCfgDate[33][40];
enum {
TOP_NULL,
PRO_TOP,
NUB_TOP,
STATS_TOP,
WeaponTop,
PROGEN,
LAST_PRO10,
PRO_RECORDS,
PLAYERS_RANKING,
GENERAL_RANKING,
MAPS_STATISTIC,
PL_STATS,
WR_PLAY,
HELP
};
new const g_weaponsnames[][] = {
"",
"p228", "shield", "scout", "250", "240", "250",
"mac10", "240", "250", "250", "250",
"250", "210", "240", "240", "250", "250",
"210", "250", "220", "230", "230", "tmp", "210",
"250", "250", "235", "221", "250", "245",
"250", "250", "fn57", "mp5", "vest", "vesthelm",
"250", "hegren", "sgren", "defuser", "nvgs", "primammo",
"secammo", "km45", "9x19mm", "nighthawk", "228compact",
"12gauge", "autoshotgun", "mp", "c90", "cv47", "defender",
"clarion", "krieg552", "bullpup", "magnum", "d3au1",
"krieg550"
};
new const other_weapons_name[8][] = {
"weapon_p90", "weapon_famas", "weapon_sg552", "weapon_awp",
"weapon_m4a1", "weapon_m249", "weapon_ak47", "weapon_awp"
};
public plugin_sql() {
new ErrorCode;
SqlConnection = SQL_Connect(g_SqlTuple,ErrorCode,g_Error,511);
if(!SqlConnection) {
server_print("[KZ] Could not connect to SQL database.!");
return pause("a");
}
QueryInstallTable();
return PLUGIN_CONTINUE;
}
public QueryHandle(iFailState, Handle:hQuery, szError[], iErrnum, cData[], iSize, Float:fQueueTime) {
if(iFailState != TQUERY_SUCCESS) {
log_amx("[KZ] TOP15 SQL: SQL Error #%d - %s", iErrnum, szError);
client_print_color(0, print_chat, "$s ^x01 Error mySQL connect", prefix);
}
else if(iFailState == TQUERY_QUERY_FAILED)
set_fail_state("Query failed. QueryHandle %s", szError);
SQL_FreeHandle(hQuery);
return PLUGIN_CONTINUE;
}
public QueryInstallTable() {
new CreateInto[1001];
formatex(CreateInto, 1000, "CREATE TABLE IF NOT EXISTS `kz_pro15` (`map_id` INT(10) NOT NULL,`mapname` VARCHAR(64) NOT NULL COLLATE 'utf8_general_ci',`authid` VARCHAR(64) NOT NULL COLLATE 'utf8_general_ci',`name` VARCHAR(64) NOT NULL COLLATE 'utf8_general_ci',`time` DECIMAL(65,2) NOT NULL,`date` DATETIME NOT NULL)");
SQL_ThreadQuery(g_SqlTuple, "QueryHandle", CreateInto);
formatex(CreateInto, 1000, "CREATE TABLE IF NOT EXISTS `kz_nub15` (`map_id` INT(10) NOT NULL,`mapname` VARCHAR(64) NOT NULL COLLATE 'utf8_general_ci',`authid` VARCHAR(64) NOT NULL COLLATE 'utf8_general_ci',`name` VARCHAR(64) NOT NULL COLLATE 'utf8_general_ci',`time` DECIMAL(65,2) NOT NULL,`date` DATETIME NOT NULL,`checkpoints` DOUBLE(22,0) NOT NULL,`gocheck` DOUBLE(22,0) NOT NULL)");
SQL_ThreadQuery(g_SqlTuple, "QueryHandle", CreateInto);
formatex(CreateInto, 1000, "CREATE TABLE IF NOT EXISTS `kz_maps` (`id` INT(11) NOT NULL AUTO_INCREMENT,`mapname` VARCHAR(64) NOT NULL COLLATE 'utf8_general_ci',`type` VARCHAR(64) NULL COLLATE 'utf8_general_ci',`challenge` INT(3) NOT NULL DEFAULT '0',`entity` INT(2) NOT NULL DEFAULT '1',`start` VARCHAR(50) NULL COLLATE 'utf8_general_ci',`finish` VARCHAR(50) NULL COLLATE 'utf8_general_ci',PRIMARY KEY (`id`))");
SQL_ThreadQuery(g_SqlTuple, "QueryHandle", CreateInto);
}
public SQL_MapID() {
new s_Error[128], startposition[64], finishposition[64], p_start[3][64], p_finish[3][64]
new Handle:h_Query = SQL_PrepareQuery(SqlConnection, "SELECT * FROM `kz_maps` WHERE mapname='%s'", gMapName)
if(!SQL_Execute(h_Query))
SQL_QueryError(h_Query, s_Error, charsmax(s_Error));
else {
new mapid = SQL_FieldNameToNum(h_Query, "id");
new type = SQL_FieldNameToNum(h_Query, "type");
new delentity = SQL_FieldNameToNum(h_Query, "entity");
new start = SQL_FieldNameToNum(h_Query, "start");
new finish = SQL_FieldNameToNum(h_Query, "finish");
while(SQL_MoreResults(h_Query)) {
kz_mapID = SQL_ReadResult(h_Query, mapid);
SQL_ReadResult(h_Query, type, kz_maptype, charsmax(kz_maptype));
delete_entity = SQL_ReadResult(h_Query, delentity);
SQL_ReadResult(h_Query, start, startposition, charsmax(startposition));
SQL_ReadResult(h_Query, finish, finishposition, charsmax(finishposition));
SQL_NextRow(h_Query);
}
}
if(!equali(startposition, "")) {
strtok(startposition, p_start[0], charsmax(p_start[]), startposition, charsmax(startposition), ' ', true);
strtok(startposition, p_start[1], charsmax(p_start[]), startposition, charsmax(startposition), ' ', true);
strtok(startposition, p_start[2], charsmax(p_start[]), startposition, charsmax(startposition), ' ', true);
DefaultStartPos[0] = str_to_float(p_start[0]);
DefaultStartPos[1] = str_to_float(p_start[1]);
DefaultStartPos[2] = str_to_float(p_start[2]);
Default_SF[0] = true;
}
else
Default_SF[0] = false;
if(!equali(finishposition, "")) {
strtok(finishposition, p_finish[0], charsmax(p_finish[]), finishposition, charsmax(finishposition), ' ', true);
strtok(finishposition, p_finish[1], charsmax(p_finish[]), finishposition, charsmax(finishposition), ' ', true);
strtok(finishposition, p_finish[2], charsmax(p_finish[]), finishposition, charsmax(finishposition), ' ', true);
DefaultFinishPos[0] = str_to_float(p_finish[0]);
DefaultFinishPos[1] = str_to_float(p_finish[1]);
DefaultFinishPos[2] = str_to_float(p_finish[2]);
Default_SF[1] = true;
}
else
Default_SF[1] = false;
if(equali(kz_maptype, "slide")) mapIsSlide = true;
if(equali(kz_maptype, "gravity")) mapIsGravity = true;
if(equali(kz_maptype, "")) kz_maptype = "n/a";
if(delete_entity)
for(new i = 0; i < sizeof(g_remove_ent); i++)
sx_remove_entity(g_remove_ent[i], "classname", 0, "");
if(!kz_mapID) {
new Handle:h_Query2 = SQL_PrepareQuery(SqlConnection, "INSERT INTO `kz_maps` (`mapname`) VALUES ('%s');", gMapName);
if(SQL_Execute(h_Query2))
kz_mapID = SQL_GetInsertId(h_Query2);
SQL_FreeHandle(h_Query2);
}
SQL_FreeHandle(h_Query);
server_print("[KZ_SQL] ID Map = %d", kz_mapID);
server_print("[KZ_SQL] Type map = %s", kz_maptype);
return PLUGIN_HANDLED;
}
public SQL_StartFinish(bool:L, Float:position[3]) {
if(L)
Default_SF[0] = true;
else
Default_SF[1] = true;
new createinto[1001];
formatex(createinto, sizeof createinto - 1, "UPDATE `kz_maps` SET `%s` = '%f %f %f' WHERE (`id` = %d)", (L ? "start":"finish"), position[0], position[1], position[2], kz_mapID);
SQL_ThreadQuery(g_SqlTuple, "SQL_WorkHandle", createinto);
}
public SQL_StatsAdd(iFailState, Handle:hQuery, szError[], iErrnum, cData[], iSize, Float:fQueueTime) {
new id = cData[0];
new style = cData[1];
new Float:time = Update_timer[id];
new check = cData[3];
new gocheck = cData[4];
if(iFailState != TQUERY_SUCCESS) {
log_amx("[KZ] TOP15 SQL: SQL Error #%d - %s", iErrnum, szError);
client_print_color(0, print_chat, "%s^x01 %F", prefix, LANG_PLAYER, "KZ_TOP15_SQL_ERROR");
}
new checkpoints[32], gochecks[32];
new createinto[1001];
new name[32], recdata[64];
get_user_name(id, name, 31);
get_time("%Y%m%d%H%M%S", recdata, sizeof recdata - 1);
new wpn = get_user_weapon(id);
replace_all(name, 31, "'", "");
new bool:user_weapon = false;
new weapon = get_user_weapon(id);
get_weaponname(weapon, weapon_name, charsmax(weapon_name));
for(new i = 0; i < 8; i++)
if(equali(other_weapons_name[i], weapon_name))
user_weapon = true;
if(SQL_NumResults(hQuery) == 0) {
formatex(checkpoints, 31, ", %d", check);
formatex(gochecks, 31, ", %d", gocheck);
if(user_weapon && get_pcvar_num(sv_airaccelerate) == 10) {
formatex(createinto, sizeof createinto - 1, "INSERT INTO `%s` VALUES (%d, '%s', '%s', '%s', '%s', '%f', '%s'%s%s)", style == PRO_TOP ? "kz_weapon_pro" : "kz_weapon_nub", kz_mapID, gMapName, g_weaponsnames[wpn], kz_authid[id], name, time, recdata, style == PRO_TOP ? "" : checkpoints, style == PRO_TOP ? "" : gochecks);
SQL_ThreadQuery(g_SqlTuple, "QueryHandle", createinto);
GetNewRank(id, style, true);
}
else {
formatex(createinto, sizeof createinto - 1, "INSERT INTO `%s` VALUES (%d, '%s', '%s', '%s', '%f', '%s'%s%s)", style == PRO_TOP ? "kz_pro15" : "kz_nub15", kz_mapID, gMapName, kz_authid[id], name, time, recdata, style == PRO_TOP ? "" : checkpoints, style == PRO_TOP ? "" : gochecks);
SQL_ThreadQuery(g_SqlTuple, "QueryHandle", createinto);
GetNewRank(id, style, false);
}
}
else {
new Float:oldtime, Float:thetime;
SQL_ReadResult(hQuery, 0, oldtime);
if(time < oldtime) {
formatex(checkpoints, 31, ", checkpoints=%d", check);
formatex(gochecks, 31, ", gocheck=%d", gocheck);
thetime = oldtime - time;
show_finish_message(id, thetime, false, true);
if(user_weapon && get_pcvar_num(sv_airaccelerate) == 10) {
formatex(createinto, sizeof createinto - 1, "UPDATE `%s` SET time='%f', date='%s' %s%s WHERE map_id=%d AND weapon='%s' AND authid='%s'", style == PRO_TOP ? "kz_weapon_pro" : "kz_weapon_nub", time, recdata, style == PRO_TOP ? "" : checkpoints, style == PRO_TOP ? "" : gochecks, kz_mapID, g_weaponsnames[wpn], kz_authid[id]);
SQL_ThreadQuery(g_SqlTuple, "QueryHandle", createinto);
GetNewRank(id, style, true);
}
else {
formatex(createinto, sizeof createinto - 1, "UPDATE `%s` SET time='%f', date='%s' %s%s WHERE map_id=%d AND authid='%s'", style == PRO_TOP ? "kz_pro15" : "kz_nub15", time, recdata, style == PRO_TOP ? "" : checkpoints, style == PRO_TOP ? "" : gochecks, kz_mapID, kz_authid[id]);
SQL_ThreadQuery(g_SqlTuple, "QueryHandle", createinto);
GetNewRank(id, style, false);
}
}
else {
thetime = time - oldtime;
show_finish_message(id, thetime, false, false);
}
}
return PLUGIN_HANDLED;
}
stock GetNewRank(id, type, bool:user_weapon) {
new createinto[1000];
new cData[2];
cData[0] = id;
cData[1] = type;
new wpn = get_user_weapon(id);
if(user_weapon && get_pcvar_num(sv_airaccelerate) == 10)
formatex(createinto, charsmax(createinto), "SELECT authid FROM `%s` WHERE map_id=%d AND weapon='%s' ORDER BY time", type == PRO_TOP ? "kz_weapon_pro" : "kz_weapon_nub", kz_mapID, g_weaponsnames[wpn]);
else
formatex(createinto, charsmax(createinto), "SELECT authid FROM `%s` WHERE map_id=%d ORDER BY time", type == PRO_TOP ? "kz_pro15" : "kz_nub15", kz_mapID);
SQL_ThreadQuery(g_SqlTuple, "GetNewRank_QueryHandler", createinto, cData, 2);
}
public GetNewRank_QueryHandler(iFailState, Handle:hQuery, szError[], iErrnum, cData[], iSize, Float:fQueueTime) {
new id = cData[0];
if(iFailState != TQUERY_SUCCESS)
return log_amx("TOP15 SQL: SQL Error #%d - %s", iErrnum, szError)
new authid[32], namez[32], i = 0;
get_user_name(id, namez, 31);
new bool:user_weapon = false;
new weapon = get_user_weapon(id);
get_weaponname(weapon, weapon_name, charsmax(weapon_name));
for(new i = 0; i < 8; i++)
if(equali(other_weapons_name[i], weapon_name))
user_weapon = true;
while(SQL_MoreResults(hQuery)) {
i++;
SQL_ReadResult(hQuery, 0, authid, 31);
if(equal(authid, kz_authid[id])) {
if(user_weapon)
client_print_color(0, print_chat, "^x04%s^x03 %s^x04 is now ^x03%d^x04 in^x03 %s^x04",prefix, namez, i, cData[1] == PRO_TOP ? "Professional Weapon Top" : "General Weapon Top");
else
client_print_color(0, print_chat, "^x04%s^x03 %s^x04 is now ^x03%d^x04 in^x03 %s^x04",prefix, namez, i, cData[1] == PRO_TOP ? "Professional Top" : "General Top");
break;
}
SQL_NextRow(hQuery);
}
SQL_FreeHandle(hQuery);
return PLUGIN_CONTINUE;
}
public mytime(id, type) {
new createinto[256], cData[2];
cData[0] = id;
cData[1] = type;
formatex(createinto, sizeof createinto - 1, "SELECT * FROM %s WHERE map_id=%d AND authid='%s'", type == PRO_TOP ? "kz_pro15" : "kz_nub15", kz_mapID, kz_authid[id]);
SQL_ThreadQuery(g_SqlTuple, "SQL_MyTimeHandle", createinto, cData, 2);
}
public SQL_MyTimeHandle(failstate, Handle:hQuery, error[], errcode, cData[], iSize, Float:fQueueTime) {
new id = cData[0];
new type = cData[1];
if(failstate == TQUERY_CONNECT_FAILED)
set_fail_state("Could not connect to database.");
else if(failstate == TQUERY_QUERY_FAILED)
set_fail_state("Query failed. SQL_MyTimeHandle %s", error);
else if(errcode)
log_amx("Error on query: %s", error);
else {
if(SQL_NumResults(hQuery)) {
if(type == PRO_TOP)
SQL_ReadResult(hQuery, 4, kz_my_protime[id]);
else
SQL_ReadResult(hQuery, 4, kz_my_nubtime[id]);
}
else {
if(type == PRO_TOP)
kz_my_protime[id] = 0.0;
else
kz_my_nubtime[id] = 0.0;
}
}
SQL_FreeHandle(hQuery);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SQL CFG ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public SQL_Config(id) {
new createinto[128], cData[1];
cData[0] = id;
formatex(createinto, sizeof createinto - 1, "SELECT * FROM kzp_players WHERE auth='%s'", kz_authid[id]);
g_SqlTuple = SQL_MakeStdTuple();
SQL_ThreadQuery(g_SqlTuple, "SQL_ConfigHandle", createinto, cData, 1);
}
public SQL_ConfigHandle(failstate, Handle:hQuery, error[], errcode, cData[], iSize, Float:fQueueTime) {
new id = cData[0];
if(failstate == TQUERY_CONNECT_FAILED)
set_fail_state("Could not connect to database.");
else if(failstate == TQUERY_QUERY_FAILED )
set_fail_state("Query failed. SQL_Config %s", error);
else if(errcode)
log_amx("Error on query: %s", error);
else {
if(SQL_NumResults(hQuery)) {
ShowTime[id] = SQL_ReadResult(hQuery, 8);
InvisUser[id] = SQL_ReadResult(hQuery, 9);
InvisWater[id] = SQL_ReadResult(hQuery, 10);
full_Invisible[id] = SQL_ReadResult(hQuery, 11);
noTeleport[id] = SQL_ReadResult(hQuery, 12);
SpecList[id] = SQL_ReadResult(hQuery, 13);
SpecAdmImm[id] = SQL_ReadResult(hQuery, 14);
SQL_ReadResult(hQuery, 4, SaveCfgDate[id], charsmax(SaveCfgDate));
}
else {
InvisUser[id] = 0;
InvisWater[id] = 0;
full_Invisible[id] = 0;
noTeleport[id] = 0;
SpecList[id] = 1;
SpecAdmImm[id] = 0;
ShowTime[id] = 2;
}
//server_print("user: %d, i_user: %d, i_water: %d, fullinvis: %d, notp: %d, spec: %d, specadm: %d, stime: %d, lastsave: %s", id, InvisUser[id], InvisWater[id], full_Invisible[id], noTeleport[id], SpecList[id], SpecAdmImm[id], ShowTime[id], SaveCfgDate[id]);
}
SQL_FreeHandle(hQuery);
}
public SQL_ConfigSave(id) {
new createinto[128], cData[1];
cData[0] = id;
formatex(createinto, sizeof createinto - 1, "SELECT * FROM kzp_players WHERE auth='%s'", kz_authid[id]);
SQL_ThreadQuery(g_SqlTuple, "SQL_ConfigSaveHandle", createinto, cData, 1);
}
public SQL_ConfigSaveHandle(failstate, Handle:hQuery, error[], errcode, cData[], iSize, Float:fQueueTime) {
new id = cData[0];
new nowdate[40];
get_time("%Y-%m-%d %H:%M:%S", nowdate, sizeof nowdate - 1);
SaveCfgDate[id] = nowdate;
if(failstate == TQUERY_CONNECT_FAILED)
set_fail_state("Could not connect to database.");
else if(failstate == TQUERY_QUERY_FAILED)
set_fail_state("Query failed. SQL_ConfigSaveHandle %s", error);
else if(errcode)
log_amx("Error on query: %s", error);
else {
if(SQL_NumResults(hQuery)) {
new createinto[1001];
formatex(createinto, sizeof createinto - 1, "UPDATE `kzp_players` SET `showTime` = %d,`invisUser` = %d,`invisWater` = %d,`invisFull` = %d,`noTeleport` = %d,`specList` = %d,`specAdmin` = %d, `date` = '%s' WHERE (`auth` = '%s')", ShowTime[id], InvisUser[id], InvisWater[id], full_Invisible[id], noTeleport[id], SpecList[id], SpecAdmImm[id], SaveCfgDate[id], kz_authid[id]);
SQL_ThreadQuery(g_SqlTuple, "SQL_WorkHandle", createinto);
client_print_color(id, print_chat, "^x01%s^x03 The config was saved successfully.", prefix);
}
/*else {
new createinto[1001];
formatex(createinto, sizeof createinto - 1, "INSERT INTO `kzp_players` VALUES (null, '%s', %d, %d, %d, %d, %d, %d, %d, '%s')", kz_authid[id], ShowTime[id], InvisUser[id], InvisWater[id], full_Invisible[id], noTeleport[id], SpecList[id], SpecAdmImm[id], SaveCfgDate[id]);
SQL_ThreadQuery(g_SqlTuple, "SQL_WorkHandle", createinto);
client_print_color(id, print_chat, "^x01%s^x03 The config was saved successfully.", prefix);
}*/
}
SQL_FreeHandle(hQuery);
}
public SQL_WorkHandle(failstate, Handle:hQuery, error[], errcode, cData[], iSize, Float:fQueueTime) {
if(failstate == TQUERY_CONNECT_FAILED)
set_fail_state("Could not connect to database.");
else if(failstate == TQUERY_QUERY_FAILED)
set_fail_state("Query failed. SQL_WorkHandle %s", error);
else if(errcode)
log_amx("Error on query: %s", error);
SQL_FreeHandle(hQuery);
}

View File

@ -0,0 +1,119 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Language Functions
//
#if defined _lang_included
#endinput
#endif
#define _lang_included
/**
* Returns the number of languages loaded.
*
* @return Number of languages loaded.
*/
native get_langsnum();
/**
* Returns the two-letter name of a language returned by get_langsnum()
*
* @param id Language index, starting at 0
* @param name Buffer to store the name in
*
* @noreturn
*/
native get_lang(id, name[3]);
/**
* Registers a dictionary file, making sure the words are in the dictionary.
*
* @note The file should be in "addons/amxmodx/data/lang", but only the name
* needs to be given. For example, register_dictionary("file.txt") will
* be "addons/amxmodx/data/lang/file.txt".
*
* @param filename Dictionary file name
*
* @return On success, the function will return 1, otherwise it will
* return 0 if the file couldn't be found or opened, and -1 if
* the dictionary was already registered by a plugin
*/
native register_dictionary(const filename[]);
/**
* Checks if the language is loaded.
*
* @return 1 if it is, 0 otherwise
*/
native lang_exists(const name[]);
enum TransKey
{
TransKey_Bad = -1,
};
/**
* Creates a new or finds an existing translation key.
*
* @param key Key to create or find
*
* @return Key index
*/
native TransKey:CreateLangKey(const key[]);
/**
* Finds a translation key index without adding on failure.
*
* @param key Key to search for
*
* @return Key index, or -1 if not found
*/
native TransKey:GetLangTransKey(const key[]);
/**
* Adds a new translation.
*
* @param lang Two-letter language name
* @param key Language key
* @param phrase Translated text
*
* @noreturn
*/
native AddTranslation(const lang[3], TransKey:key, const phrase[]);
/**
* Looks up the translation of the key for the given type.
*
* @note This does NOT format the output text! For example, if the key
* contains %s, the outputted text will also contain %s.
* @note LANG_PLAYER is invalid in this, use a player index or LANG_SERVER.
*
* @param Output Buffer to store the output in
* @param OutputSize Maximum buffer size
* @param Key Language key
* @param id Client index or LANG_SERVER
*
* @return 1 on success, 0 otherwise
*/
native LookupLangKey(Output[], OutputSize, const Key[], const &id);
/**
* Sets the global language target.
*
* @note This is useful for creating functions
* that will be compatible with the %l format specifier. Note that invalid
* indexes can be specified but the error will occur during translation,
* not during this function call.
*
* @param client Client index or LANG_SERVER
* @noreturn
*/
native SetGlobalTransTarget(client);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,161 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Message Stocks
//
#if defined _message_stocks_included
#endinput
#endif
#define _message_stocks_included
/**
* Sends a death message.
*
* @param killer Killer id
* @param victim Victim id
* @param weaponNUM Weapon index
*
* @noreturn
*/
stock dod_make_deathmsg(killer, victim, weaponNUM)
{
static msgid = 0;
if (!msgid)
{
msgid = get_user_msgid("DeathMsg");
}
message_begin(MSG_ALL, msgid, {0,0,0}, 0);
write_byte(killer);
write_byte(victim);
write_byte(weaponNUM);
message_end();
return 1;
}
/**
* Kills a user without a message.
*
* @param index Client index
* @param flag If nonzero, the death will not affect the client's score
*
* @noreturn
*/
stock user_silentkill(index, flag = 1)
{
static msgid = 0;
new msgblock;
if (!msgid)
{
msgid = get_user_msgid("DeathMsg");
}
msgblock = get_msg_block(msgid);
set_msg_block(msgid, BLOCK_ONCE);
user_kill(index, flag);
set_msg_block(msgid, msgblock);
return 1;
}
/**
* Creates a death message.
*
* @param killer Killer id
* @param victim Victim id
* @param headshot Headshot
* @param weapon Weapon
*
* @noreturn
*/
stock make_deathmsg(killer, victim, headshot, const weapon[])
{
static msgid = 0;
if (!msgid)
{
msgid = get_user_msgid("DeathMsg");
}
message_begin(MSG_ALL, msgid, {0,0,0}, 0);
write_byte(killer);
write_byte(victim);
new mod_name[32];
get_modname(mod_name, 31);
if (equal(mod_name, "cstrike") || equal(mod_name, "czero") || equal(mod_name, "csv15") || equal(mod_name, "cs13"))
write_byte(headshot);
write_string(weapon);
message_end();
return 1;
}
/**
* Sends a predefined text message to player.
* Predefined texts are default game messages which will be translated
* to player's game language, e.g. #Game_join_ct.
*
* @note Set index to 0 to send text globally.
*
* @note There does not necessarily have to be a total of 6 arguments.
* It will depend if message takes arguments, e.g.:
* client_printex(id, print_chat, "#Game_join_ct", "Pimp Daddy")
* client_printex(id, print_chat, "1", "#Game_radio", "Pimp Daddy", "Hello world!")
*
* @param index Index of the player, use 0 to send to all players.
* @param type The message destination. See print_* constants.
* @param msg_name The custom or predefined message to send.
* @param msg_param1 Optional message argument.
* @param msg_param2 Optional message argument.
* @param msg_param3 Optional message argument.
* @param msg_param4 Optional message argument.
*
* @noreturn
*/
stock client_printex(index, type, const msg_name[], const msg_param1[] = "", const msg_param2[] = "", const msg_param3[] = "", const msg_param4[] = "")
{
new ch = msg_name[0];
// If not a predefined message, we don't care about it and forward directly to client_print.
// Special case for radio message. msg_name is an index, msg_param1 #Game_radio*, etc. Checking index should be enough.
if (ch != '#' && (type != print_radio || !strtol(msg_name)))
{
return client_print(index, type, msg_name, msg_param1, msg_param2, msg_param3, msg_param4);
}
// Even if message starts with '#', we should check its length for safety.
new length = strlen(msg_name);
// If string is larger than expected, we forward to client_print which will cut message properly.
// This means also this can't be a predefined game message.
// Max console length: 128 = \n (126) + \0 (127)
// Max SayText length: 192 = \n (190) + \0 (191)
if ((length > 126 && (print_notify <= type <= print_console))
|| ( length > 190 && (print_chat <= type <= print_radio)))
{
return client_print(index, type, msg_name, msg_param1, msg_param2, msg_param3, msg_param4);
}
static msgTextMsg;
if (!msgTextMsg)
{
msgTextMsg = get_user_msgid("TextMsg");
}
message_begin(index > 0 ? MSG_ONE_UNRELIABLE : MSG_BROADCAST, msgTextMsg, {0,0,0}, index);
write_byte(type);
write_string(msg_name);
if (msg_param1[0]) { write_string(msg_param1); }
if (msg_param2[0]) { write_string(msg_param2); }
if (msg_param3[0]) { write_string(msg_param3); }
if (msg_param4[0]) { write_string(msg_param4); }
message_end();
return 1;
}

View File

@ -0,0 +1,604 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Message Functions
//
#if defined _coremsg_included
#endinput
#endif
#define _coremsg_included
#include <message_const>
/**
* Marks the beginning of a client message.
*
* @note You may generate menus, smoke, shockwaves, thunderlights,
* intermission and many other messages.
* @note For a list of HL game events, visit https://wiki.alliedmods.net/Half-Life_1_Game_Events
* @note For a list of HL engine messages, visit https://wiki.alliedmods.net/Half-Life_1_Engine_Messages
* @note You may also refer to the messages_const.inc file for examples.
* @note Each message starts with a message_begin() or message_begin_f() function
* and ends with message_end(). The specific message arguments go in between
* these two by using the write_*() functions found in messages.inc.
*
* @param dest Destination type (see MSG_* constants in messages_const.inc)
* @param msg_type Message id
* @param origin Message origin
* @param player Client index receiving the message or 0 for all clients
*
* @noreturn
* @error If an invalid message id is specified or an invalid number
* of parameters is passed, an error will be thrown.
*/
native message_begin(dest, msg_type, const origin[3] = {0,0,0}, player = 0);
/**
* Marks the beginning of a client message.
*
* @note You may generate menus, smoke, shockwaves, thunderlights,
* intermission and many other messages.
* @note For a list of HL game events, visit https://wiki.alliedmods.net/Half-Life_1_Game_Events
* @note For a list of HL engine messages, visit https://wiki.alliedmods.net/Half-Life_1_Engine_Messages
* @note You may also refer to the messages_const.inc file for examples.
* @note This function is the same as message_begin(), but the origin
* argument accepts only float values in this one.
* @note Each message starts with a message_begin() or message_begin_f() function
* and ends with message_end(). The specific message arguments go in between
* these two by using the write_*() functions found in messages.inc.
*
* @param dest Destination type (see MSG_* constants in messages_const.inc)
* @param msg_type Message id
* @param origin Message origin
* @param player Client index receiving the message or 0 for all clients
*
* @noreturn
* @error If an invalid message id is specified or an invalid number
* of parameters is passed, an error will be thrown.
*/
native message_begin_f(dest, msg_type, const Float:origin[3] = {0.0,0.0,0.0}, player = 0);
/**
* Ends a message that was started with message_begin() or message_begin_f().
*
* @note If the function is called without using message_begin() or
* message_begin_f() first, the server will crash immediately.
*
* @noreturn
*/
native message_end();
/**
* Writes a single byte to a message.
*
* @note This function should only be used in between a message_begin()
* or message_begin_f() and a message_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Byte to write
*
* @noreturn
*/
native write_byte(x);
/**
* Writes a single character to a message.
*
* @note This function should only be used in between a message_begin()
* or message_begin_f() and a message_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Character to write
*
* @noreturn
*/
native write_char(x);
/**
* Writes a single number to a message (short).
*
* @note This function should only be used in between a message_begin()
* or message_begin_f() and a message_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Number to write
*
* @noreturn
*/
native write_short(x);
/**
* Writes a single number to a message (long).
*
* @note This function should only be used in between a message_begin()
* or message_begin_f() and a message_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Number to write
*
* @noreturn
*/
native write_long(x);
/**
* Writes an entity index to a message.
*
* @note This function should only be used in between a message_begin()
* or message_begin_f() and a message_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Entity index to write
*
* @noreturn
*/
native write_entity(x);
/**
* Writes an angle entry to a message.
*
* @note This function should only be used in between a message_begin()
* or message_begin_f() and a message_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Angle to write
*
* @noreturn
*/
native write_angle(x);
/**
* Writes an angle entry to a message using a float value.
*
* @note This function should only be used in between a message_begin()
* or message_begin_f() and a message_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Angle to write
*
* @noreturn
*/
native write_angle_f(Float:x);
/**
* Writes a coordinate entry to a message.
*
* @note This function should only be used in between a message_begin()
* or message_begin_f() and a message_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Coordinate to write
*
* @noreturn
*/
native write_coord(x);
/**
* Writes a coordinate entry to a message using a float value.
*
* @note This function should only be used in between a message_begin()
* or message_begin_f() and a message_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Coordinate to write
*
* @noreturn
*/
native write_coord_f(Float:x);
/**
* Writes a string to a message.
*
* @note This function should only be used in between a message_begin()
* or message_begin_f() and a message_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x String to write
*
* @noreturn
*/
native write_string(const x[]);
/**
* Marks the beginning of a client message.
*
* @note You may generate menus, smoke, shockwaves, thunderlights,
* intermission and many other messages.
* @note For a list of HL game events, visit https://wiki.alliedmods.net/Half-Life_1_Game_Events
* @note For a list of HL engine messages, visit https://wiki.alliedmods.net/Half-Life_1_Engine_Messages
* @note You may also refer to the messages_const.inc file for examples.
* @note This function is the same as message_begin(), except that the messages
* sent with this one are also sent to all other AMXX and Metamod plugins.
* This means that if you send one of these messages, other plugins will
* be notified of that message, which was previously impossible.
* @note BE CAREFUL! Using this incorrectly, or not for its intended purpose,
* could cause infinite recursion or something just as bad!
* @note Each message starts with a emessage_begin() or emessage_begin_f() function
* and ends with emessage_end(). The specific message arguments go in between
* these two by using the ewrite_*() functions found in messages.inc.
*
* @param dest Destination type (see MSG_* constants in messages_const.inc)
* @param msg_type Message id
* @param origin Message origin
* @param player Client index receiving the message or 0 for all clients
*
* @noreturn
* @error If an invalid message id is specified or an invalid number
* of parameters is passed, an error will be thrown.
*/
native emessage_begin(dest, msg_type, const origin[3] = {0,0,0}, player = 0);
/**
* Marks the beginning of a client message.
*
* @note You may generate menus, smoke, shockwaves, thunderlights,
* intermission and many other messages.
* @note For a list of HL game events, visit https://wiki.alliedmods.net/Half-Life_1_Game_Events
* @note For a list of HL engine messages, visit https://wiki.alliedmods.net/Half-Life_1_Engine_Messages
* @note You may also refer to the messages_const.inc file for examples.
* @note This function is the same as message_begin_f(), except that the messages
* sent with this one are also sent to all other AMXX and Metamod plugins.
* This means that if you send one of these messages, other plugins will
* be notified of that message, which was previously impossible.
* @note BE CAREFUL! Using this incorrectly, or not for its intended purpose,
* could cause infinite recursion or something just as bad!
* @note This function is the same as emessage_begin(), but the origin
* argument accepts only float values in this one.
* @note Each message starts with a emessage_begin() or emessage_begin_f() function
* and ends with emessage_end(). The specific message arguments go in between
* these two by using the ewrite_*() functions found in messages.inc.
*
* @param dest Destination type (see MSG_* constants in messages_const.inc)
* @param msg_type Message id
* @param origin Message origin
* @param player Client index receiving the message or 0 for all clients
*
* @noreturn
* @error If an invalid message id is specified or an invalid number
* of parameters is passed, an error will be thrown.
*/
native emessage_begin_f(dest, msg_type, const Float:origin[3] = {0.0,0.0,0.0}, player = 0);
/**
* Ends a message that was started with emessage_begin() or emessage_begin_f().
*
* @note If the function is called without using emessage_begin() or
* emessage_begin_f() first, the server will crash immediately.
*
* @noreturn
*/
native emessage_end();
/**
* Writes a single byte to a message.
*
* @note This function should only be used in between a emessage_begin()
* or emessage_begin_f() and a emessage_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Byte to write
*
* @noreturn
*/
native ewrite_byte(x);
/**
* Writes a single character to a message.
*
* @note This function should only be used in between a emessage_begin()
* or emessage_begin_f() and a emessage_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Character to write
*
* @noreturn
*/
native ewrite_char(x);
/**
* Writes a single number to a message (short).
*
* @note This function should only be used in between a emessage_begin()
* or emessage_begin_f() and a emessage_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Number to write
*
* @noreturn
*/
native ewrite_short(x);
/**
* Writes a single number to a message (long).
*
* @note This function should only be used in between a emessage_begin()
* or emessage_begin_f() and a emessage_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Number to write
*
* @noreturn
*/
native ewrite_long(x);
/**
* Writes an entity index to a message.
*
* @note This function should only be used in between a emessage_begin()
* or emessage_begin_f() and a emessage_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Entity index to write
*
* @noreturn
*/
native ewrite_entity(x);
/**
* Writes an angle entry to a message.
*
* @note This function should only be used in between a emessage_begin()
* or emessage_begin_f() and a emessage_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Angle to write
*
* @noreturn
*/
native ewrite_angle(x);
/**
* Writes an angle entry to a message using a float value.
*
* @note This function should only be used in between a emessage_begin()
* or emessage_begin_f() and a emessage_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Angle to write
*
* @noreturn
*/
native ewrite_angle_f(Float:x);
/**
* Writes a coordinate entry to a message.
*
* @note This function should only be used in between a emessage_begin()
* or emessage_begin_f() and a emessage_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Coordinate to write
*
* @noreturn
*/
native ewrite_coord(x);
/**
* Writes a coordinate entry to a message using a float value.
*
* @note This function should only be used in between a emessage_begin()
* or emessage_begin_f() and a emessage_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x Coordinate to write
*
* @noreturn
*/
native ewrite_coord_f(Float:x);
/**
* Writes a string to a message.
*
* @note This function should only be used in between a emessage_begin()
* or emessage_begin_f() and a emessage_end() function. Trying to use
* it outside of these functions will crash the server immediately.
*
* @param x String to write
*
* @noreturn
*/
native ewrite_string(const x[]);
/**
* Sets whether or not an engine message will be blocked.
*
* @note For a list of message flags, have a look at the BLOCK_* constants
* in message_const.inc.
*
* @param iMessage Message id
* @param iMessageFlags BLOCK_* constant
*
* @noreturn
* @error If an invalid message id is specified, an error
* will be thrown.
*/
native set_msg_block(iMessage, iMessageFlags);
/**
* Gets whether or not an engine message is blocked.
*
* @param iMessage Message id
*
* @return BLOCK_* constant
* @error If an invalid message id is specified, an error
* will be thrown.
*/
native get_msg_block(iMessage);
/**
* Lets you directly hook a message in the engine.
*
* @note The function is called in the following manner:
* msg_id - Message id
* msg_dest - Destination type (see MSG_* constants in messages_const.inc)
* msg_entity - Entity receiving the message
*
* @note You can overwrite the message before anything happens by using the
* set_msg_arg_* functions and either let the message continue by
* returning PLUGIN_CONTINUE or fully block it with PLUGIN_HANDLED.
* @note If you hook a message, the message is stored but not sent. You have
* the opportunity to not only execute code, but to get/set the contents
* of the message before you choose to either block it or let it go on
* its way.
* @note The return value can be passed to unregister_message() in order to
* stop the message from being hooked.
*
* @param iMsgId Message id
* @param szFunction Function that will be called
*
* @return Id that can be passed to unregister_message() on
* success, or 0 if an invalid message id is passed
* @error If the specified function can't be found, an
* error will be thrown.
*/
native register_message(iMsgId, const szFunction[]);
/**
* Unregisters a message hook previously created with register_message().
*
* @note You must pass the proper message id and return value from the
* message to unregister the message successfully.
*
* @param iMsgId Message id
* @param registeredmsg Registered message id
*
* @return Id that can again be passed to register_message() on
* success, or 0 if an invalid message id is passed
* @error If an invalid registered message handle is passed, an
* error will be thrown.
*/
native unregister_message(iMsgId, registeredmsg);
/**
* Gets number of arguments that were passed to a message.
*
* @note This function will fail if used outside a hooked message scope, thus
* it should never be used unless inside a registered message function.
*
* @return Number of arguments
*/
native get_msg_args();
/**
* Gets the argument type of a specified argument.
*
* @note This function will fail if used outside a hooked message scope, thus
* it should never be used unless inside a registered message function.
*
* @param argn Argument number
*
* @return Argument type (see ARG_* constants in message_const.inc)
*/
native get_msg_argtype(argn);
/**
* Gets the integer value of a specified argument.
*
* @note This function will fail if used outside a hooked message scope, thus
* it should never be used unless inside a registered message function.
*
* @param argn Argument number
*
* @return Argument value as an integer
* @error If an invalid message argument is passed, an
* error will be thrown.
*/
native get_msg_arg_int(argn);
/**
* Gets the float value of a specified argument.
*
* @note This function will fail if used outside a hooked message scope, thus
* it should never be used unless inside a registered message function.
*
* @param argn Argument number
*
* @return Argument value as a float
* @error If an invalid message argument is passed, an
* error will be thrown.
*/
native Float:get_msg_arg_float(argn);
/**
* Gets the string value from a specified argument.
*
* @note This function will fail if used outside a hooked message scope, thus
* it should never be used unless inside a registered message function.
*
* @param argn Argument number
* @param szReturn Buffer to store the value in
* @param iLength Maximum buffer length
*
* @return String length
* @error If an invalid message argument is passed, an
* error will be thrown.
*/
native get_msg_arg_string(argn, szReturn[], iLength);
/**
* Sets the integer value of a specified argument.
*
* @note This function will fail if used outside a hooked message scope, thus
* it should never be used unless inside a registered message function.
*
* @param argn Argument number
* @param argtype Argument type (see ARG_* constants in message_const.inc)
* @param iValue Argument value
*
* @noreturn
* @error If an invalid message argument is passed, an
* error will be thrown.
*/
native set_msg_arg_int(argn, argtype, iValue);
/**
* Sets the float value of a specified argument.
*
* @note This function will fail if used outside a hooked message scope, thus
* it should never be used unless inside a registered message function.
*
* @param argn Argument number
* @param argtype Argument type (see ARG_* constants in message_const.inc)
* @param fValue Argument value
*
* @noreturn
* @error If an invalid message argument is passed, an
* error will be thrown.
*/
native set_msg_arg_float(argn, argtype, Float:fValue);
/**
* Sets the string value of a specified argument.
*
* @note This function will fail if used outside a hooked message scope, thus
* it should never be used unless inside a registered message function.
*
* @param argn Argument number
* @param szString Argument value
*
* @noreturn
* @error If an invalid message argument is passed, an
* error will be thrown.
*/
native set_msg_arg_string(argn, const szString[]);
/**
* Gets the origin of a message.
*
* @note This function will fail if used outside a hooked message scope, thus
* it should never be used unless inside a registered message function.
*
* @param _Origin Array to store the origin in
*
* @noreturn
* @error If the function is used outside a message hook, an
* error will be thrown.
*/
native get_msg_origin(const Float:_Origin[3]);

View File

@ -0,0 +1,391 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
#if defined _newmenus_included
#endinput
#endif
#define _newmenus_included
/**
* @section Menu properties for using in menu_setprop
*/
/**
* Menu will have an exit option (default)
*/
#define MEXIT_ALL 1
/**
* Menu will have an exit option, even when pagination is disabled.
* There have to be less than 10 items in the menu or it won't appear. The exit
* option will be appended to the last item with no extra slot padding. If you
* want it in the 10th slot you have to pad it manually with menu_addblank2
*/
#define MEXIT_FORCE 2
/**
* Menu will not have an exit option
*/
#define MEXIT_NEVER -1
/**
* Number of items per page (param1 = number, 0=no paginating, 7=default)
*/
#define MPROP_PERPAGE 1
/**
* Name of the back button (param1 = string)
*/
#define MPROP_BACKNAME 2
/**
* Name of the next button (param1 = string)
*/
#define MPROP_NEXTNAME 3
/**
* Name of the exit button (param1 = string)
*/
#define MPROP_EXITNAME 4
/**
* Menu title text (param1 = string)
*/
#define MPROP_TITLE 5
/**
* Exit functionality (param1 = number, see MEXIT constants)
*/
#define MPROP_EXIT 6
/**
* Sets whether colors are not auto (param1 = number, 0=default)
*/
#define MPROP_NOCOLORS 8
/**
* Color indicator to use for numbers (param1 = string, "\r"=default)
*/
#define MPROP_NUMBER_COLOR 10
/**
* Function to be called on Back and Next (param1 = string)
* public function(id, status, menu); where status is either MENU_BACK or MENU_MORE
* Pass NULL_STRING to disable the callback
*/
#define MPROP_PAGE_CALLBACK 11
/**
* Whether to show the page number in menu title (param1 = bool, true = default)
*/
#define MPROP_SHOWPAGE 12
/**
* @deprecated
*/
#define MEXIT_NORMAL 0 /* DEPRECATED, do not use (has no effect) */
#define MENUPAD_NONE 0 /* DEPRECATED, do not use (has no effect) */
#define MENUPAD_PAGE 1 /* DEPRECATED, do not use (has no effect) */
#define MPROP_ORDER 7 /* DEPRECATED, do not use (has no effect) */
#define MPROP_PADMENU 9 /* DEPRECATED, do not use (has no effect) */
/** @endsection */
/**
* @brief Creates a new menu object.
*
* The handler function should be prototyped as:
*
* public <function>(id, menu, item)
* id - Client the menu is being acted upon.
* menu - Menu resource identifier.
* item - Item the client selected. If less than 0, the menu was
* cancelled and the item is a status code. menu_display
* should never be called immediately if the item is a status
* code, for re-entrancy reasons.
*
* The handler function should always return PLUGIN_HANDLED to block
* any old menu handlers from potentially feeding on the menu, unless
* that is the desired functionality.
*
* @param title Title the menu should use.
* @param handler Name of the handler function. The function will be invoked
* once and only once to every menu_display() call.
* @param ml If true, the menu title and items will be looked up as multilingual keys
* when the menu displays.
* @return Menu resource identifier which must be destroyed via
* menu_destroy(). All menus are destroyed when the plugin
* unloads.
* @error Function name not found.
*/
native menu_create(const title[], const handler[], bool:ml = false);
/**
* Creates a menu item callback handler.
*
* The handler function should be prototyped as:
*
* public <function>(id, menu, item)
* id - Client index being displayed to.
* menu - Menu resource identifier.
* item - Item being drawn.
* <return> - ITEM_IGNORE to use the default functionality. ITEM_ENABLED to
* explicitly enable or ITEM_DISABLED to explicitly disable.
*
* @param function Function name.
* @return Menu callback ID.
*/
native menu_makecallback(const function[]);
/**
* Adds an menu to a menu.
*
* @param menu Menu resource identifier.
* @param name Item text to display.
* @param info Item info string for internal information.
* @param paccess Access required by the player viewing the menu.
* @param callback If set to a valid ID from menu_makecallback(), the
* callback will be invoked before drawing the item.
* @noreturn
* @error Invalid menu resource.
*/
native menu_additem(menu, const name[], const info[]="", paccess=0, callback=-1);
/**
* Returns the number of pages in a menu.
*
* @param menu Menu resource identifier.
* @return Number of pages in the menu.
* @error Invalid menu resource.
*/
native menu_pages(menu);
/**
* Returns the number of items in a menu.
*
* @param menu Menu resource identifier.
* @return Number of items in the menu.
* @error Invalid menu resource.
*/
native menu_items(menu);
/**
* Displays a menu to one client. This should never be called from a handler
* when the item is less than 0 (i.e. calling this from a cancelled menu will
* result in an error).
*
* Starting with 1.8.3 this allows to specify a menu timeout similar to the
* show_menu native. If the menu exists on the client past the timeout *any*
* further action will send the MENU_TIMEOUT status code to the menu handler.
* That includes actions which would otherwise send MENU_EXIT, such as the
* client selecting an item or disconnecting and calling menu_cancel or
* menu_destroy on a live menu.
*
* @param id Client index.
* @param menu Menu resource identifier.
* @param page Page to start from (starting from 0).
* @param time If >=0 menu will timeout after this many seconds
* @noreturn
* @error Invalid menu resource or client index.
*/
native menu_display(id, menu, page=0, time=-1);
/**
* Given a page on a menu and a keypress on that page, returns the item id selected.
* If the item is less than 0, a special option was chosen (such as MENU_EXIT).
*
* @param menu Menu resource identifier.
* @param page Page on the menu.
* @param key Key pressed (from 1 to 10).
* @return Item identifier, or <0 for a special selection code.
* @error Invalid menu resource.
*/
native menu_find_id(menu, page, key);
/**
* Retrieves info about a menu item.
*
* @param menu Menu resource identifier.
* @param item Item identifier.
* @param access Variable to store access value.
* @param info Buffer to store item info.
* @param infolen Item info buffer length.
* @param name Buffer to store item display text.
* @param namelen Item name buffer length.
* @param callback Callback ID.
* @return 1 on success, 0 on failure.
* @error Invalid menu resource.
*/
native menu_item_getinfo(menu, item, &access = 0, info[] = "", infolen = 0, name[]="", namelen=0, &callback = 0);
/**
* Sets an item's display text.
*
* @param menu Menu resource identifier.
* @param item Item identifier.
* @param name New item display text.
* @return 1 on success, 0 on failure.
* @error Invalid menu resource.
*/
native menu_item_setname(menu, item, const name[]);
/**
* Sets an item's info string.
*
* @param menu Menu resource identifier.
* @param item Item identifier.
* @param info New item info string.
* @return 1 on success, 0 on failure.
* @error Invalid menu resource.
*/
native menu_item_setcmd(menu, item, const info[]);
/**
* Sets an item's callback.
*
* @param menu Menu resource identifier.
* @param item Item identifier.
* @param callback New callback from menu_makecallback(), or -1 to clear.
* @return 1 on success, 0 on failure.
* @error Invalid menu resource.
*/
native menu_item_setcall(menu, item, callback=-1);
/**
* Sets an item's access.
*
* @param menu Menu resource identifier.
* @param item Item identifier.
* @param access New access required by the player for access to the item.
* @return 1 on success, 0 on failure.
* @error Invalid menu resource.
*/
native menu_item_setaccess(menu, item, access=0);
/**
* Destroys a menu. Player menus will be cancelled (although may still linger
* on the HUD), and future attempts to access the menu resource will result in
* an error.
*
* This must be called if you create menus dynamically, otherwise you will
* leak memory. For normal dynamic menus, you will destroy the menu in the
* handler function (remembering to handle the case of a menu being cancelled,
* it must still be destroyed).
*
* @param menu Menu resource identifier.
* @noreturn
* @error Invalid menu resource.
*/
native menu_destroy(menu);
/**
* Returns information about a menu (if any) the client is currently viewing.
*
* If newmenu is valid, then the menu will refer to the menuid associated with
* the title. If newmenu is not valid, and the menu is valid, then the player
* is viewing a menu displayed with show_menu().
*
* Both may be invalid if the player is not viewing a menu.
*
* @param id Client index.
* @param menu Variable to store old menu id. If none, then <1 will be
* stored.
* @param newmenu Variable to store new menu id. If none, then -1 will be
* stored.
* @param menupage Variable to store current page of the new menu, if any.
* @return 1 if the player is viewing a menu, 0 otherwise.
* @error Invalid client.
*/
native player_menu_info(id, &menu, &newmenu, &menupage=0);
/**
* Adds a blank line to a menu.
*
* When using slot=1 this might break your menu. To achieve this functionality
* menu_addblank2 should be used.
*
* @param menu Menu resource identifier.
* @param slot 1 (default) if the line should shift the numbering down.
* 0 if the line should be a visual shift only.
* @noreturn
* @error Invalid menu resource.
*/
native menu_addblank(menu, slot=1);
/**
* Adds a text line to a menu. Only available in amxmodx 1.8.1 and above.
*
* When using slot=1 this might break your menu. To achieve this functionality
* menu_addtext2 should be used.
*
* @param menu Menu resource identifier.
* @param text Text to add.
* @param slot 1 (default) if the line should shift the numbering down.
* 0 if the line should be a visual shift only.
* @noreturn
* @error Invalid menu resource.
*/
native menu_addtext(menu, const text[], slot=1);
/**
* Adds a blank line to a menu, always shifting the numbering down.
*
* This will add a special item to create a blank line. It will affect the menu
* item count and pagination. These items can be modified later but will ignore
* access and item callback results.
*
* Only available in 1.8.3 and above.
*
* @param menu Menu resource identifier.
*
* @return 1 on success, 0 on failure.
* @error Invalid menu resource.
* Too many items on non-paginated menu (max is 10)
*/
native menu_addblank2( menu );
/**
* Adds a text line to a menu, always shifting the numbering down.
*
* This will add a special item to create a blank line. It will affect the menu
* item count and pagination. These items can be modified later but will ignore
* access and item callback results.
*
* Only available in 1.8.3 and above.
*
* @param menu Menu resource identifier.
* @param text Text to add.
*
* @return 1 on success, 0 on failure.
* @error Invalid menu resource.
* Too many items on non-paginated menu (max is 10)
*/
native menu_addtext2( menu, const text[] );
/**
* Sets a menu property.
*
* @param menu Menu resource identifier.
* @param prop MPROP_ constant.
* @param ... Property parameters.
* @return 1 on success, 0 on failure.
* @error Invalid menu resource or property.
*/
native menu_setprop(menu, prop, ...);
/**
* Cancels a player's menu, effectively forcing the player to select MENU_EXIT.
* The menu will still exist on their screen but any results are invalidated,
* and the callback is invoked.
*
* @param player Client index.
* @noreturn
* @error Invalid client index.
*/
native menu_cancel(player);

View File

@ -0,0 +1,754 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Natural Selection Module Functions
//
#if defined NS_INC
#endinput
#endif
#define NS_INC
#pragma reqlib ns
#if !defined AMXMODX_NOAUTOLOAD
#pragma loadlib ns
#endif
#include <ns_const>
/**
* Called whenever the client's class is changed.
*
* @param id The index of the player who changed.
* @param newclass The class the client changed to. Check the class enum in ns_const.inc.
* @param oldclass The class the client changed from. Check the class enum in ns_const.inc.
* @noreturn
*/
forward client_changeclass(id, newclass, oldclass);
/**
* Called whenever the client builds a structure.
*
* @param idPlayer The player index who triggered the building.
* @param idStructure The structure index that was created.
* @param type The type of structure that was built (1 for marine, 2 for alien).
* @param impulse The impulse command that was issued to build this structure.
* @noreturn
*/
forward client_built(idPlayer, idStructure, type, impulse);
/**
* Tell whether or not the map is combat.
*
* @return 1 if combat, 0 otherwise.
*/
native ns_is_combat();
/**
* Returns the gameplay type for the currently active map.
* Refer to ns_const.inc's NSGameplay enum for details.
*
* @note The earliest this is guaranteed to be accurate is during plugin_init(). It needs
* the info_gameplay entity to be properly set within the map, or it will return "Unknown",
* or "Cantfind".
*
* @return Return the gameplay mode, as accurate as the module can tell.
*/
native NSGameplay:ns_get_gameplay();
/**
* Exact syntax as get_user_team, but should be more accurate.
*
* @param id Player id.
* @param buff Buffer to store team name in.
* @param len Buffer length.
* @return The pev_team setting for the player.
*/
native ns_get_user_team(id, buff[], len);
/**
* Send an NS-style popup message.
*
* @param target The client to receive the message. Set to 0 to send to everybody.
* @param szMsg The message to send, 180 characters max.
* @param ah Whether to only display the message on clients who have the cvar "cl_autohelp" set to 1.
* @noreturn
*/
native ns_popup(target, const szMsg[180], ah=0);
/**
* Sets a player model. Omit the second parameter to return to default
*
* @note The model does not revert on death, teamswitch, gestation, etc.
*
* @param id The player id to change.
* @param szModel The model to change to.
* @noreturn
*/
native ns_set_player_model(id, const szModel[]="");
/**
* Sets a player skin. Omit the second parameter to return to default
*
* @note The skin does not revert on death, teamswitch, gestation, etc.
*
* @param id The player id to change.
* @param skin The skin number to change to.
* @noreturn
*/
native ns_set_player_skin(id, skin=-1);
/**
* Sets a player body. Omit the second parameter to return to default
*
* @note The body does not revert on death, teamswitch, gestation, etc.
*
* @param id The player id to change.
* @param body The body number to change to.
* @noreturn
*/
native ns_set_player_body(id, body=-1);
/**
* Set this to modify the player's speed by a certain amount.
*
* @note The speed does not revert on death, teamswitch, gestation, etc.
*
* @param id The player id to change.
* @param speedchange The speed to modify the player speed by. Set to 0 to revert to default speed.
* @noreturn
*/
native ns_set_speedchange(id, speedchange=0);
/**
* Returns a client's current speed modifier.
*
* @param id The client id to check.
* @return The module's current speed modifier for the client.
*/
native ns_get_speedchange(id);
/**
* Returns a client's maxspeed before the speed change modifier is factored in.
*
* @param id The client id to check.
* @return The maxspeed for the client.
*/
native ns_get_maxspeed(id);
/* Returns whether or not this mask is set from the entity's iuser4 field. Use the "mask" enum for reference. */
native ns_get_mask(id,mask);
/* Sets or removes the mask from the entity's iuser4 field. Set "value" to 1 to turn the mask on, 0 to turn it off. */
native ns_set_mask(id,mask,value);
/* Returns built/unbuilt structures.
If:
builtOnly is 1 (default):
Only fully built structures are counted.
builtOnly is 0:
Any structure meeting the classname is counted.
Number is 0 (default):
The total number of matching structures is returned.
Number is any other value:
The index of the #th matching structure is returned.
*/
native ns_get_build(const classname[],builtOnly=1,Number=0);
/* Returns if the player has the weapon or not in their pev->weapons field.
set "setweapon" to 0 to turn the bit off, set to 1 to turn it on. Or omit it to just return the value. */
native ns_has_weapon(id,weapon,setweapon=-1);
/* Gets spawn point for specified team (type).
If:
Team is equal to 0:
Ready room spawns are returned.
Team is greater than 0:
Spawns for the team are returned.
Number is equal to 0:
Total number of spawns is returned.
Number is greater than 0:
The location of the specified spawn is returned.
*/
native ns_get_spawn(team,number=0,Float:ret[3]);
/* Returns the class of the player. Look in the classes enum in ns_const.inc for the value's meaning. */
native ns_get_class(id);
/**
* Gets the player's jetpack fuel reserve.
*
* @param id The player to get fuel from.
* @return The amount of fuel in the player's reserve. (0.0 through 100.0)
*/
native Float:ns_get_jpfuel(id);
/**
* Sets the player's jetpack fuel reserve.
*
* @param id The player to set fuel.
* @param fuel The amount of fuel to set, as a percentage (0.0 through 100.0)
* @noreturn
*/
native ns_set_jpfuel(id, Float:fuel);
/**
* Adds to the player's jetpack fuel reserve.
*
* @param id The player to add fuel to.
* @param amount The amount of fuel to add, as a percentage (0.0 through 100.0)
* @return The new amount of fuel in the player's reserve. (0.0 through 100.0)
*/
native Float:ns_add_jpfuel(id, Float:amount);
/**
* Gets the player's energy percentage.
*
* @param id The player to get the energy from.
* @return The amount of energy the player has (0.0 through 100.0)
*/
native Float:ns_get_energy(id);
/**
* Sets the player's energy percentage.
*
* @param id The player to set the energy on.
* @param energy The amount of energy to set (0.0 through 100.0)
* @noreturn
*/
native ns_set_energy(id, Float:energy);
/**
* Adds to the player's energy percentage.
*
* @param id The player to add the energy to.
* @param amount The amount of energy to add to the player.
* @return The new amount of energy the player has (0.0 through 100.0)
*/
native Float:ns_add_energy(id, Float:amount);
/**
* Returns a player's resources.
*
* @note This is only for alien players.
* @param id The id of the player to check.
* @return Amount of resources this player has.
*/
native Float:ns_get_res(id);
/**
* Sets a player's resources.
*
* @note This is only for alien players.
* @param id The id of the player to set.
* @param res Amount of resources to set on this player.
* @noreturn
*/
native ns_set_res(id, Float:res);
/**
* Adds an amount of resources to the player.
*
* @note This is only for alien players.
* @param id The id of the player to add resources to.
* @param amount The amount to add to the player.
* @return The new amount of resources the player has.
*/
native Float:ns_add_res(id, Float:amount);
/**
* Returns the team's resources.
*
* @param Team 1 for teama, 2 for teamb. (eg: in MvA maps, 1 is marines,
2 is aliens. In mvm, 1 is marine1, 2 is marine2)
* @return The amount of resources in this team's resource pool.
*/
native Float:ns_get_teamres(Team);
/**
* Sets the team's resources in the resource pool.
*
* @note If this is used on an alien team, the resources will be
* distributed between all of the players who need resources.
* @param Team 1 for teama, 2 for teamb. (eg: in MvA maps, 1 is marines,
* 2 is aliens. In mvm, 1 is marine1, 2 is marine2)
* @param value The amount to set the resources to set to.
* @noreturn
*/
native ns_set_teamres(Team, Float:value);
/**
* Adds to the team's resources in the resource pool.
*
* @note If this is used on an alien team, the resources will be
* distributed between all of the players who need resources.
* @param Team 1 for teama, 2 for teamb. (eg: in MvA maps, 1 is marines,
* 2 is aliens. In mvm, 1 is marine1, 2 is marine2)
* @param value The amount to set the resources to add to the pool
* @return The new amount of resources in the resource pool.
*/
native Float:ns_add_teamres(Team,Float:value);
/**
* Returns the player's experience.
*
* @note Combat only.
* @param id The player to get experience value from.
* @return The amount of experience this player has.
*/
native Float:ns_get_exp(id);
/**
* Sets the player's experience.
*
* @note Combat only.
* @param id The player to set experience value on.
* @param exp The amount of experience this player will have.
* @noreturn
*/
native ns_set_exp(id,Float:exp);
/**
* Adds to the player's experience.
*
* @note Combat only.
* @param id The player to add experience value to.
* @param value The amount of experience this player will receive.
* @return The new amount of experience this player has.
*/
native Float:ns_add_exp(id, Float:value);
/**
* Gets the player's points spent count in combat.
*
* @param id The player to check.
* @return The amount of points this player has spent.
*/
native ns_get_points(id);
/**
* Sets the player's points spent count in combat.
*
* @param id The player to set this on.
* @param points The amount to set this to.
* @noreturn
*/
native ns_set_points(id, points);
/**
* Adds to the player's points spent count in combat.
*
* @param id The player to add this to.
* @param value The value to add to the points spent.
* @return The new value of the points spent variable.
*/
native ns_add_points(id,points);
/**
* Gets the damage for this weapon.
*
* @note Use weapon index, not player index!
* @param idWeapon The entity index of the weapon to check.
* @return The damage this weapon does.
*/
native Float:ns_get_weap_dmg(idWeapon);
/**
* Sets the damage for this weapon.
*
* @note Use weapon index, not player index!
* @param idWeapon The entity index of the weapon to set.
* @param damage The damage to make this weapon cause.
* @noreturn
*/
native ns_set_weap_dmg(idWeapon, Float:damage);
/**
* Gets the maximum range for this weapon.
*
* @note Use weapon index, not player index!
* @param idWeapon The entity index of the weapon to check.
* @return The maximum range this weapon has.
*/
native Float:ns_get_weap_range(idWeapon);
/**
* Sets the maximum range for this weapon.
*
* @note Use weapon index, not player index!
* @param idWeapon The entity index of the weapon to set.
* @param range The maximum range this weapon will have.
* @noreturn
*/
native ns_set_weap_range(idWeapon, Float:range);
/**
* Gets the weapon's clip ammo.
*
* @note Use weapon index, not player index!
* @param idWeapon The weapon to get the clip ammo from.
* @return The amount of ammunition in the weapon's clip.
*/
native ns_get_weap_clip(idWeapon);
/**
* Sets the weapon's ammo in the clip.
*
* @note Use weapon index, not player index!
* @param idWeapon The weapon to set the clip ammo on.
* @param clipsize The amount of ammunition to set in the weapon's clip.
* @noreturn
*/
native ns_set_weap_clip(idWeapon, clipsize);
/**
* Gets the player's weapon reserve (backpack ammo) for the specified
* type of weapon.
*
* @note Use player index, not weapon index!
* @param id The player id to check ammo count on.
* @param weapon The weapon type to check ammo count for.
* @return The ammunition count in the player's reserve.
*/
native ns_get_weap_reserve(id,weapon);
/**
* Sets the player's weapon reserve (backpack ammo) for the specified
* type of weapon.
*
* @note Use player index, not weapon index!
* @param id The player id to set ammo count on.
* @param weapon The weapon type to set ammo count for.
* @param ammo The ammunition count to set.
* @noreturn
*/
native ns_set_weap_reserve(id,weapon,ammo);
/**
* Gets the player's score.
*
* @note The score from level is automatically factored into the scoreboard in combat.
* @param idPlayer The player to get the score for.
* @return The player's score.
*/
native ns_get_score(idPlayer);
/**
* Sets the player's score.
*
* @note The score from level is automatically factored into the scoreboard in combat.
* @param idPlayer The player to get the score for.
* @param score What to set the player's score as.
* @noreturn
*/
native ns_set_score(idPlayer, score);
/* Adds to a player's score
* Returns the new score on success
*/
native ns_add_score(idPlayer,score);
/* Gets a player's death count. */
native ns_get_deaths(idPlayer);
/* Sets a player's death count. */
native ns_set_deaths(idPlayer,numdeaths);
/* Adds to a player's death count
* Returns the new death count on success
*/
native ns_add_deaths(idPlayer,numdeaths);
/* Gets the index of the owner of a structure. -1 for no owner. */
native ns_get_struct_owner(idStructsure);
/* Sets the index of the owner of a structure. -1 for no owner. */
native ns_set_struct_owner(idStructure,indexOwner);
/* Gets the trait type tied to the hive. Look at the hivetrait enum for the values. */
native ns_get_hive_trait(idHive);
/* Sets the trait type tied to the hive. Look at the hivetrait enum for the values. */
native ns_set_hive_trait(idHive,trait);
/* Sets the players field of view, set "_fov" to 0.0 (or omit it) to return to normal. FOV change will persist until disconnect unless reset by a plugin */
native ns_set_fov(idPlayer,Float:_fov=0.0);
/**
* Give the player an item.
*
* @param id The player to give the item to.
* @param class The map-classname of the entity to give to the player.
* @noreturn
*/
native ns_give_item(id, const class[]);
/**
* Returns 1 if a player has the hive ability number.
* If ability is 0, it will return the number of active hives.
*
* @param idPlayer The player index to look up.
* @param ability The ability number to check, set to 0 to get number of active hives.
* @return If ability is != 0, returns 1 or 0 depending on if the client has the ability.
* If ability is 0, returns the number of active hives.
*/
native ns_get_hive_ability(idPlayer, ability=0);
/**
* Triggered whenever a client's pev->team changes.
*
* @param id The id of the client.
* @param newteam The team number of the new team.
* @param oldteam The team number of the old team.
* @noreturn
*/
forward client_changeteam(id, newteam, oldteam);
/**
* Triggered whenever a client's pev->deadflag changes from >0 to 0.
*
* @param id The id of the client.
* @noreturn
*/
forward client_spawn(id);
/**
* Calls NS's private damage routine on the victim entity.
*
* @deprecated
* @note This is provided for backwards compatibility with peachy's module.
* It is suggested to use hamsandwich for this action instead.
*
* @param IDVictim The victim that is taking the damage.
* @param IDInflictor The entity that is causing the damage (weapon, etc).
* @param IDAttacker The attacker who is triggering the damage (person shooting).
* @param Damage The amount of damage being done.
* @param DamageType The damage type being done (bitmask).
*/
#pragma deprecated It is suggested to use hamsandwich for this action instead.
native ns_takedamage(IDVictim, IDInflictor, IDAttacker, Float:Damage, DamageType);
/**
* Attempts to unstick a player.
*
* @param id Player to unstick.
* @param StartDistance Distance to start from the player to check for a new location.
* @param MaxAttempts How many attempts to try to find a new spot before giving up.
* @return 1 on success, 0 on cannot find a place to move player to,
* -1 on invalid state (stunned/webbed), -2 on invalid class (comm/egg)
* -3 if the player is dead or a spectator, -4 on invalid player,
* -5 if the player is not connected.
*/
native ns_unstick_player(id, StartDistance=32, MaxAttempts=128);
/**
* Whether or not there is a game in progress.
*
* @return true if a game is in progress, false otherwise.
*/
native bool:ns_round_in_progress();
/**
* Called at the approximate time that a round is started.
*
* @noreturn
*/
forward round_start();
/**
* Called immediately when a round ends
*
* @param roundtime The length of the round in seconds.
* @noreturn
*/
forward round_end(Float:roundtime);
forward map_reset(isload);
native ns_get_weapon(idPlayer,weaponid,&weapontype=0);
/* Returns the location name of the provided x/y position
* (z origin is ignored; can't have location over location)
* -
* Note that as of NS 3.2 beta 2, on the following maps
* the returned string should be passed through ns_lookup_title
* to be human readable:
* ns_bast, ns_hera, ns_nothing, ns_tanith,
* ns_nancy, ns_caged, ns_eclipse, ns_veil
*
* Passing the 5th parameter as non zero will auto look up
* the title if it exists.
*/
native ns_get_locationname(Float:x, Float:y, name[], len, titlelookup=0);
/* Looks up a key from titles.txt
* Returns -1 if the key is not found
* Otherwise it returns the length of the output
*/
native ns_lookup_title(const KeyName[], Output[], length);
/* Forces the structure to fully build
* Removes the ghost state from marine structures.
* Do not use this on hives! It wont work.
*/
native ns_build_structure(idStructure);
/* Forces the structure to begin recycling
* Passing an index other than a marine structure will
* have undefined results!
* -
* Note: This calls a private NS function!
* Be careful when using this!
*/
native ns_recycle(idStructure);
/* Forces the weldable to trigger
* Passing an index other than a weldable
* will have undefined results!
* -
* NS renames func_weldable to avhweldable
* at map load.
* -
* Note: This calls a private NS function!
* Be careful when using this!
*/
native ns_finish_weldable(idWeldable);
/* Gets the total time needed to weld this
* func_weldable shut.
* Note: NS renames "func_weldable"s to "avhweldable"s
* at run time!
*/
native Float:ns_get_weld_time(idWeldable);
/* Sets the total time needed to weld this
* func_weldable shut.
*/
native ns_set_weld_time(idWeldable,Float:value);
/* Adds to the weldable's time required to open.
* Returns the new required time on success.
* Note this native clamps the low value to 0.
*/
native Float:ns_add_weld_time(idWeldable,Float:value);
/* Gets the total time this func_weldable
* has been welded.
*/
native Float:ns_get_weld_done(idWeldable);
/* Sets the total time this func_weldable
* has been welded.
*/
native ns_set_weld_done(idWeldable,Float:value);
/* Adds to the total time this func_weldable
* has been welded. Returns the new value.
* Note this native clamps the low value to 0.0
*/
native Float:ns_add_weld_done(idWeldable,Float:value);
/* Gets/sets/adds to the energy pool of this observatory. */
native Float:ns_get_obs_energy(idObs);
native ns_set_obs_energy(idObs,Float:value);
native Float:ns_add_obs_energy(idObs,Float:value);
/**
* Removes an upgrade from the player's bought and active upgrade lists.
* This will not refund the points spent on the upgrade, nor will it
* immediately strip the upgrade if the player is alive. Rather, it will
* make it so the player no longer receives the upgrade on spawn.
*
* @note This only works in combat.
* @params idPlayer The player index to change upgrades for.
* @params ugprade The impulse number for the upgrade to strip.
* @return 2 for upgrade removed from player's bought and active list.
* 1 for upgrade removed from player's bought list only.
* 3 for upgrade removed from player's active list only (shouldn't happen, just incase.)
* 0 for the player didn't have the upgrade in either list.
*/
native ns_remove_upgrade(idPlayer, upgrade);
/**
* Particle system natives
* -
* The particle system emulates a map-based custom particle system.
* Familiarity with the keyvalues from the map-based particle systems
* is recommended! You will be lost otherwise!
* -
* prsearle's NSPEdit is also recommended for designing the systems:
* http://homepage.ntlworld.com/pr.searle/NSPSEdit/NSPSEdit.html
*/
/* Creates a handle to the a particle system to configure
* -
* Note! this is not a particle system you can pass to
* ns_fire_ps()!
*/
native RawPS:ns_create_ps();
/* Sets the name of the particle system.
* -
* This is used for things like ns_get_ps_id()
* and through calling another particle system
* through the "ps_to_gen" field
*/
native ns_set_ps_name(RawPS:system, const name[]);
/* Sets the sprite to use for the particle system
* -
* You do NOT have to precache the sprite, BUT
* the sprite must obviously be on the client to
* display.
*/
native ns_set_ps_sprite(RawPS:system, const sprite[]);
/* Finalizes the particle system. Do not configure it after this.
* A usable particle system handle is returned.
*/
native Particle:ns_spawn_ps(RawPS:system);
/* Draws a particle system at the given origin (and angles)
* Flags are the FEV_* defines from hlsdk_const.inc
* Only use handles returned by ns_spawn_ps or ns_get_ps_id here!
*/
native ns_fire_ps(Particle:system,const Float:origin[3],const Float:angles[3]={0.0,0.0,0.0}, flags=0);
/* Looks up a particle system by name
* Returns a usable particle system handle.
*/
native Particle:ns_get_ps_id(const Name[]);
/* The following are the parameters for configuring the
* particle system. Look through the fgd and NSPSEdit
* for details!
*/
native ns_set_ps_genrate(RawPS:system, genrate);
native ns_set_ps_genshape(RawPS:system, NSPS_GenShape:genshape);
native ns_set_ps_genshape_params(RawPS:system, const params[]);
native ns_set_ps_spriteframes(RawPS:system, spriteframes);
native ns_set_ps_numparticles(RawPS:system, numparticles);
native ns_set_ps_size(RawPS:system, Float:size);
native ns_set_ps_vel_params(RawPS:system, const params[]);
native ns_set_ps_vel_shape(RawPS:system, NSPS_VelShape:shape);
native ns_set_ps_sys_life(RawPS:system, Float:lifetime);
native ns_set_ps_particle_life(RawPS:system, Float:lifetime);
native ns_set_ps_rendermode(RawPS:system, NSPS_RenderMode:rendermode);
native ns_set_ps_to_gen(RawPS:system, const name[]);
native ns_set_ps_anim_speed(RawPS:system, speed);
native ns_set_ps_spawn_flags(RawPS:system, NSPS_Flags:flags);
native ns_set_ps_base_color(RawPS:system, const colors[]);
native ns_set_ps_scale(RawPS:system, Float:scale);
native ns_set_ps_max_alpha(RawPS:system, Float:maxalpha);

View File

@ -0,0 +1,196 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Natural Selection Module Constants
//
#if defined NS_CONST_INC
#endinput
#endif
#define NS_CONST_INC
enum NSGameplay
{
NSGame_CantTell, /**< It is too soon to tell (can't find avhgameplay
entity or it doesn't have private data) */
NSGame_MarineVAlien, /**< Marine vs Aliens (standard) gameplay */
NSGame_MarineVMarine, /**< Marine vs Marine */
NSGame_AlienVAlien, /**< Alien vs Alien */
NSGame_Unknown, /**< Can find the gameplay entity, but can't
determine gameplay type. */
};
// entity pev->iuser4 fields
enum {
MASK_NONE = 0,
MASK_SIGHTED = 1,
MASK_DETECTED = 2,
MASK_BUILDABLE = 4,
MASK_BASEBUILD0 = 8, // Base build slot #0
MASK_WEAPONS1 = 8, // Marine weapons 1
MASK_CARAPACE = 8, // Alien carapace
MASK_WEAPONS2 = 16, // Marines weapons 2
MASK_REGENERATION = 16, // Alien regeneration
MASK_BASEBUILD1 = 16, // Base build slot #1
MASK_WEAPONS3 = 32, // Marine weapons 3
MASK_REDEMPTION = 32, // Alien redemption
MASK_BASEBUILD2 = 32, // Base build slot #2
MASK_ARMOR1 = 64, // Marine armor 1
MASK_CELERITY = 64, // Alien celerity
MASK_BASEBUILD3 = 64, // Base build slot #3
MASK_ARMOR2 = 128, // Marine armor 2
MASK_ADRENALINE = 128, // Alien adrenaline
MASK_BASEBUILD4 = 128, // Base build slot #4
MASK_ARMOR3 = 256, // Marine armor 3
MASK_SILENCE = 256, // Alien silence
MASK_BASEBUILD5 = 256, // Base build slot #5
MASK_JETPACK = 512, // Marine jetpacks
MASK_CLOAKING = 512, // Alien cloaking
MASK_BASEBUILD6 = 512, // Base build slot #6
MASK_FOCUS = 1024, // Alien focus
MASK_MOTION = 1024, // Marine motion tracking
MASK_BASEBUILD7 = 1024, // Base build slot #7
MASK_SCENTOFFEAR = 2048, // Alien scent of fear
MASK_DEFENSE2 = 4096, // Defense level 2
MASK_DEFENSE3 = 8192, // Defense level 3
MASK_ELECTRICITY = 8192, // Electricy
MASK_MOVEMENT2 = 16384, // Movement level 2,
MASK_MOVEMENT3 = 32768, // Movement level 3
MASK_HEAVYARMOR = 32768, // Marine heavy armor
MASK_SENSORY2 = 65536, // Sensory level 2
MASK_SENSORY3 = 131072, // Sensory level 3
MASK_ALIEN_MOVEMENT = 262144, // Onos is charging
MASK_WALLSTICKING = 524288, // Flag for wall-sticking
MASK_PRIMALSCREAM = 1048576, // Alien is in range of active primal scream
MASK_UMBRA = 2097152, // In umbra
MASK_DIGESTING = 4194304, // When set on a visible player, player is digesting. When set on invisible player, player is being digested
MASK_RECYCLING = 8388608, // Building is recycling
MASK_TOPDOWN = 16777216, // Commander view
MASK_PLAYER_STUNNED = 33554432, // Player has been stunned by stomp
MASK_ENSNARED = 67108864, // Webbed
MASK_ALIEN_EMBRYO = 134217728, // Gestating
MASK_SELECTABLE = 268435456, // ???
MASK_PARASITED = 536870912, // Parasite flag
MASK_SENSORY_NEARBY = 1073741824 // Sensory chamber in range
};
enum {
CLASS_UNKNOWN = 0,
CLASS_SKULK,
CLASS_GORGE,
CLASS_LERK,
CLASS_FADE,
CLASS_ONOS,
CLASS_MARINE,
CLASS_JETPACK,
CLASS_HEAVY,
CLASS_COMMANDER,
CLASS_GESTATE,
CLASS_DEAD,
CLASS_NOTEAM
};
enum {
WEAPON_NONE = 0,
WEAPON_CLAWS,
WEAPON_SPIT,
WEAPON_SPORES,
WEAPON_SPIKE,
WEAPON_BITE,
WEAPON_BITE2,
WEAPON_SWIPE,
WEAPON_WEBSPINNER,
WEAPON_METABOLIZE,
WEAPON_PARASITE,
WEAPON_BLINK,
WEAPON_DIVINEWIND,
WEAPON_KNIFE,
WEAPON_PISTOL,
WEAPON_LMG,
WEAPON_SHOTGUN,
WEAPON_HMG,
WEAPON_WELDER,
WEAPON_MINE,
WEAPON_GRENADE_GUN,
WEAPON_LEAP,
WEAPON_CHARGE,
WEAPON_UMBRA,
WEAPON_PRIMALSCREAM,
WEAPON_BILEBOMB,
WEAPON_ACIDROCKET,
WEAPON_HEALINGSPRAY,
WEAPON_GRENADE,
WEAPON_STOMP,
WEAPON_DEVOUR,
WEAPON_MAX
};
enum {
HIVETRAIT_NONE = 0,
HIVETRAIT_DC = 92,
HIVETRAIT_SC = 93,
HIVETRAIT_MC = 94
};
enum NSPS_VelShape
{
NSPS_VS_POINT = 1,
NSPS_VS_BOX,
NSPS_VS_SPHERE,
NSPS_VS_BLOB
};
/* Genshape used in ns_set_ps_genshape
* NOTE: The following are in the ns.ps file but
* are not listed in the .fgd file. Use
* at your own risk!
* Line, Triangle, Plane, Cylinder,
* Cone, Disc, Rectangle and None
*/
enum NSPS_GenShape
{
NSPS_GS_POINT = 0,
NSPS_GS_LINE,
NSPS_GS_TRIANGLE,
NSPS_GS_PLANE,
NSPS_GS_BOX,
NSPS_GS_CYLINDER,
NSPS_GS_CONE,
NSPS_GS_BLOB,
NSPS_GS_DISC,
NSPS_GS_RECTANGLE,
NSPS_GS_NONE
};
enum NSPS_RenderMode
{
NSPS_R_NORMAL = 0,
NSPS_R_TRANSCOLOR,
NSPS_R_TRANSTEXTURE,
NSPS_R_GLOW,
NSPS_R_TRANSALPHA,
NSPS_R_ADDITIVE
};
enum NSPS_Flags
{
NSPS_FL_START_ON = 1,
NSPS_FL_PARTICLE_DENSITY = 2,
NSPS_FL_FADE_IN = 4,
NSPS_FL_FADE_OUT = 8,
NSPS_FL_USE_GRAVITY = 16,
NSPS_FL_USE_TRI = 32,
NSPS_FL_CONSTRAIN_PITCH = 128,
NSPS_FL_COLLIDE = 256,
NSPS_FL_HI_DETAIL = 512,
NSPS_FL_FACE_UP = 1024
};

View File

@ -0,0 +1,154 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// NVault Functions
//
#if defined _nvault_included
#endinput
#endif
#define _nvault_included
#pragma reqlib nvault
#if !defined AMXMODX_NOAUTOLOAD
#pragma loadlib nvault
#endif
/**
* @global All timestamps are in UNIX epoch form.
*/
/**
* Opens a vault by name. Creates a vault if it doesn't exist yet.
*
* @param name Name of the vault. The vault will be created in
* ${amxx_datadir}/vault directory.
*
* @return The vault handle to be used in other natives.
* INVALID_HANDLE (-1) if not successfully opened.
*/
native nvault_open(const name[]);
/**
* Retrieves a value from the given key.
*
* @note An example of retrieving a string:
* nvault_get(vaultHandle, "myKey", myString, charsmax(myString));
*
* @param vault A vault handle returned from nvault_open()
* @param key A key to get the value from
* @param ... If three argument are given, gets a float value and
* puts it in the third argument by reference.
* If four arguments are given, gets a string from the
* vault and copies it to the third argument, up to
* 4th argument characters.
*
* @return Result as integer if only the first two arguments
* of the function are used.
* 1 if only the first three arguments are used.
* String length if all four parameters are used.
* @error On invalid vault handle.
*/
native nvault_get(vault, const key[], any:...);
/**
* Retrieves full information about a vault entry.
*
* @param vault A vault handle returned from nvault_open()
* @param key A key to get information from
* @param value A string where the value should be stored
* @param maxlen Maximum length of the @value string
* @param timestamp The timestamp of the entry
*
* @return 1 if an entry was found, 0 otherwise.
* @error On invalid vault handle.
*/
native nvault_lookup(vault, const key[], value[], maxlen, &timestamp);
/**
* Sets value of a vault entry and updates the timestamp.
*
* @note A new entry is created if one with the given key doesn't exist.
*
* @param vault A vault handle returned from nvault_open()
* @param key A key to set the value for
* @param value A value to set
*
* @noreturn
* @error On invalid vault handle.
*/
native nvault_set(vault, const key[], const value[]);
/**
* Sets value of a vault entry and makes it permanent (non-erasable with nvault_prune()).
*
* @note A new entry is created if one with the given key doesn't exist.
* @note Permanent entries have no timestamp.
*
* @param vault A vault handle returned from nvault_open()
* @param key A key to set the permanent value for
* @param value A permanent value to set
*
* @noreturn
* @error On invalid vault handle.
*/
native nvault_pset(vault, const key[], const value[]);
/**
* Prunes the vault for entries that are within the given timestamps.
*
* @note This will not erase values set with nvault_pset().
* @note An example of pruning all entries that are older than 24 hours:
* nvault_prune(vaultHandle, 0, get_systime() - (60 * 60 * 24));
*
* @param vault A vault handle returned from nvault_open()
* @param start The timestamp to start erasing from
* @param end The timestamp to erase to
*
* @return Number of erased values.
* @error On invalid vault handle.
*/
native nvault_prune(vault, start, end);
/**
* Closes a vault.
*
* @param vault A vault handle returned from nvault_open()
*
* @noreturn
* @error On invalid vault handle.
*/
native nvault_close(vault);
/**
* Removes an entry from the vault by its key.
*
* @param vault A vault handle returned from nvault_open()
* @param key The key to remove from the vault
*
* @noreturn
* @error On invalid vault handle.
*/
native nvault_remove(vault, const key[]);
/**
* "Touches" an entry in the vault, updating its timestamp.
*
* @note If timestamp is equal to -1, it will use the current time.
* @note An empty entry is created if one with the given key doesn't exist.
*
* @param vault A vault handle returned from nvault_open()
* @param key The key to search for
* @param timestamp Update an entry's timestamp to this one. Default is -1.
*
* @noreturn
* @error On invalid vault handle.
*/
native nvault_touch(vault, const key[], timestamp=-1);

View File

@ -0,0 +1,348 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Regular Expressions API
//
#if defined _regex_included
#endinput
#endif
#define _regex_included
#pragma reqlib regex
#if !defined AMXMODX_NOAUTOLOAD
#pragma loadlib regex
#endif
enum Regex
{
REGEX_MATCH_FAIL = -2,
REGEX_PATTERN_FAIL = -1,
REGEX_NO_MATCH = 0,
REGEX_OK = 1
};
/**
* Flags for compiling regex expressions.
* These come directly from the pcre library and can be used in regex_compile_ex.
*/
#define PCRE_CASELESS 0x00000001 /* Ignore Case */
#define PCRE_MULTILINE 0x00000002 /* Multilines (affects ^ and $ so that they match the start/end of a line rather than matching the start/end of the string). */
#define PCRE_DOTALL 0x00000004 /* Single line (affects . so that it matches any character, even new line characters). */
#define PCRE_EXTENDED 0x00000008 /* Pattern extension (ignore whitespace and # comments). */
#define PCRE_ANCHORED 0x00000010 /* Force pattern anchoring. */
#define PCRE_DOLLAR_ENDONLY 0x00000020 /* $ not to match newline at end. */
#define PCRE_UNGREEDY 0x00000200 /* Invert greediness of quantifiers */
#define PCRE_NOTEMPTY 0x00000400 /* An empty string is not a valid match. */
#define PCRE_UTF8 0x00000800 /* Use UTF-8 Chars */
#define PCRE_NO_UTF8_CHECK 0x00002000 /* Do not check the pattern for UTF-8 validity (only relevant if PCRE_UTF8 is set) */
#define PCRE_NEVER_UTF 0x00010000 /* Lock out interpretation of the pattern as UTF-8 */
#define PCRE_FIRSTLINE 0x00040000 /* Force matching to be before newline */
#define PCRE_DUPNAMES 0x00080000 /* Allow duplicate names for subpattern */
#define PCRE_NEWLINE_CR 0x00100000 /* Specify that a newline is indicated by a single character CR ) */
#define PCRE_NEWLINE_CRLF 0x00300000 /* specify that a newline is indicated by the two-character CRLF sequence ) Overrides the default */
#define PCRE_NEWLINE_ANY 0x00400000 /* Specify that any Unicode newline sequence should be recognized. ) newline definition (LF) */
#define PCRE_NEWLINE_ANYCRLF 0x00500000 /* Specify that any of CR, LF and CRLF sequences should be recognized ) */
#define PCRE_UCP 0x20000000 /* Change the way PCRE processes \B, \b, \D, \d, \S, \s, \W, \w etc. to use Unicode properties */
/**
* Regex expression error codes.
* This can be used with regex_compile_ex and regex_match_ex.
*/
enum /*RegexError*/
{
REGEX_ERROR_NONE = 0, /* No error */
REGEX_ERROR_NOMATCH = -1, /* No match was found */
REGEX_ERROR_NULL = -2,
REGEX_ERROR_BADOPTION = -3,
REGEX_ERROR_BADMAGIC = -4,
REGEX_ERROR_UNKNOWN_OPCODE = -5,
REGEX_ERROR_NOMEMORY = -6,
REGEX_ERROR_NOSUBSTRING = -7,
REGEX_ERROR_MATCHLIMIT = -8,
REGEX_ERROR_CALLOUT = -9, /* Never used by PCRE itself */
REGEX_ERROR_BADUTF8 = -10,
REGEX_ERROR_BADUTF8_OFFSET = -11,
REGEX_ERROR_PARTIAL = -12,
REGEX_ERROR_BADPARTIAL = -13,
REGEX_ERROR_INTERNAL = -14,
REGEX_ERROR_BADCOUNT = -15,
REGEX_ERROR_DFA_UITEM = -16,
REGEX_ERROR_DFA_UCOND = -17,
REGEX_ERROR_DFA_UMLIMIT = -18,
REGEX_ERROR_DFA_WSSIZE = -19,
REGEX_ERROR_DFA_RECURSE = -20,
REGEX_ERROR_RECURSIONLIMIT = -21,
REGEX_ERROR_NULLWSLIMIT = -22, /* No longer actually used */
REGEX_ERROR_BADNEWLINE = -23,
REGEX_ERROR_BADOFFSET = -24,
REGEX_ERROR_SHORTUTF8 = -25,
REGEX_ERROR_RECURSELOOP = -26,
REGEX_ERROR_JIT_STACKLIMIT = -27,
REGEX_ERROR_BADMODE = -28,
REGEX_ERROR_BADENDIANNESS = -29,
REGEX_ERROR_DFA_BADRESTART = -30,
REGEX_ERROR_JIT_BADOPTION = -31,
REGEX_ERROR_BADLENGTH = -32,
REGEX_ERROR_UNSET = -33
};
/**
* Precompile a regular expression.
*
* @note Use this if you intend on using the same expression multiple times.
* Pass the regex handle returned here to regex_match_c to check for matches.
*
* @note This handle is automatically freed on map change. However,
* if you are completely done with it before then, you should
* call regex_free on this handle.
*
* @note Consider using regex_compile_ex instead if you want to use PCRE_* flags.
*
* @param pattern The regular expression pattern.
* @param ret Error code encountered, if applicable.
* @param error Error message encountered, if applicable.
* @param maxLen Maximum string length of the error buffer.
* @param flags General flags for the regular expression.
* i = Ignore case
* m = Multilines (affects ^ and $ so that they match
* the start/end of a line rather than matching the
* start/end of the string).
* s = Single line (affects . so that it matches any character,
* even new line characters).
* x = Pattern extension (ignore whitespace and # comments).
*
* @return -1 on error in the pattern, > valid regex handle (> 0) on success.
*/
native Regex:regex_compile(const pattern[], &ret = 0, error[] = "", maxLen = 0, const flags[]="");
/**
* Matches a string against a pre-compiled regular expression pattern.
*
* @note You should free the returned handle with regex_free()
* when you are done with this pattern.
*
* @note Use the regex handle passed to this function to extract
* matches with regex_substr().
*
* @param string The string to check.
* @param pattern The regular expression pattern.
* @param ret Error code, if applicable, or number of results on success. See REGEX_ERROR_* defines.
*
* @return -2 = Matching error (error code is stored in ret)
* 0 = No match.
* >1 = Number of results.
*/
native regex_match_c(const string[], Regex:pattern, &ret = 0);
/**
* Matches a string against a regular expression pattern.
*
* @note If you intend on using the same regular expression pattern
* multiple times, consider using regex_compile and regex_match_ex
* instead of making this function reparse the expression each time.
*
* @note Flags only exist in amxmodx 1.8 and later.
*
* @note You should free the returned handle with regex_free()
* when you are done extracting all of the substrings.
*
* @param string The string to check.
* @param pattern The regular expression pattern.
* @param ret Error code, or result state of the match.
* @param error Error message, if applicable.
* @param maxLen Maximum length of the error buffer.
* @param flags General flags for the regular expression.
* i = Ignore case
* m = Multilines (affects ^ and $ so that they match
* the start/end of a line rather than matching the
* start/end of the string).
* s = Single line (affects . so that it matches any character,
* even new line characters).
* x = Pattern extension (ignore whitespace and # comments).
*
* @return -2 = Matching error (error code is stored in ret)
* -1 = Error in pattern (error message and offset # in error and ret)
* 0 = No match.
* >1 = Handle for getting more information (via regex_substr)
*/
native Regex:regex_match(const string[], const pattern[], &ret = 0, error[] = "", maxLen = 0, const flags[] = "");
/**
* Returns a matched substring from a regex handle.
*
* @note Substring ids start at 0 and end at ret - 1, where ret is from the corresponding
* regex_match* function call.
*
* @param id The regex handle to extract data from.
* @param str_id The index of the expression to get - starts at 0, and ends at ret - 1.
* @param buffer The buffer to set to the matching substring.
* @param maxLen The maximum string length of the buffer.
*
* @return 1 on success, otherwise 0 on failure.
*/
native regex_substr(Regex:id, str_id, buffer[], maxLen);
/**
* Frees the memory associated with a regex result, and sets the handle to 0.
*
* @note This must be called on all results from regex_match() when you are done extracting
* the results with regex_substr().
*
* @note The results of regex_compile() or regex_compile_ex() (and subsequently, regex_match_c())
* only need to be freed when you are done using the pattern.
*
* @note Do not use the handle again after freeing it!
*
* @param id The regex handle to free.
* @noreturn
*/
native regex_free(&Regex:id);
/**
* The following natives are only available in 1.8.3 and above.
*/
/**
* Precompile a regular expression.
*
* @note Use this if you intend on using the same expression multiple times.
* Pass the regex handle returned here to regex_match_c() to check for matches.
*
* @note Unlike regex_compile(), this allows you to use PCRE flags directly.
*
* @param pattern The regular expression pattern.
* @param flags General flags for the regular expression, see PCRE_* defines.
* @param error Error message encountered, if applicable.
* @param maxLen Maximum string length of the error buffer.
* @param errcode Regex type error code encountered, if applicable. See REGEX_ERROR_* defines.
*
* @return Valid regex handle (> 0) on success, or -1 on failure.
*/
native Regex:regex_compile_ex(const pattern[], flags = 0, error[]= "", maxLen = 0, &errcode = 0);
/**
* Matches a string against a pre-compiled regular expression pattern, matching all
* occurrences of the pattern inside the string. This is similar to using the "g" flag
* in perl regex.
*
* @note You should free the returned handle (with regex_free())
* when you are done with this pattern.
*
* @note Use the regex handle passed to this function to extract
* matches with regex_substr().
*
* @param pattern The regular expression pattern.
* @param string The string to check.
* @param ret Error code, if applicable, or number of results on success.
* See REGEX_ERROR_* defines.
*
* @return -2 = Matching error (error code is stored in ret)
* 0 = No match.
* >1 = Number of results.
*/
native regex_match_all_c(const string[], Regex:pattern, &ret = 0);
/**
* Matches a string against a regular expression pattern, matching all occurrences of the
* pattern inside the string. This is similar to using the "g" flag in perl regex.
*
* @note If you intend on using the same regular expression pattern
* multiple times, consider using regex_compile and regex_match_ex
* instead of making this function reparse the expression each time.
*
* @note Flags only exist in amxmodx 1.8 and later.
*
* @note You should free the returned handle with regex_free()
* when you are done extracting all of the substrings.
*
* @param string The string to check.
* @param pattern The regular expression pattern.
* @param flags General flags for the regular expression, see PCRE_* defines.
* @param error Error message encountered, if applicable.
* @param maxLen Maximum string length of the error buffer.
* @param errcode Regex type error code encountered, if applicable. See REGEX_ERROR_* defines.
*
* @return -2 = Matching error (error code is stored in ret)
* -1 = Error in pattern (error message and offset # in error and ret)
* 0 = No match.
* >1 = Handle for getting more information (via regex_substr)
*/
native Regex:regex_match_all(const string[], const pattern[], flags = 0, error[]= "", maxLen = 0, &errcode = 0);
/**
* Matches a string against a regular expression pattern.
*
* @note If you intend on using the same regular expression pattern
* multiple times, consider using compile regex_compile_ex and regex_match*
* instead of making this function reparse the expression each time.
*
* @param str The string to check.
* @param pattern The regular expression pattern.
* @param flags General flags for the regular expression.
* @param error Error message, if applicable.
* @param maxLen Maximum length of the error buffer.
* @param errcode Regex type error code encountered, if applicable. See REGEX_ERROR_* defines.
*
* @return -2 = Matching error (error code is stored in ret)
* -1 = Pattern error (error code is stored in ret)
* 0 = No match.
* >1 = Number of results.
*/
stock regex_match_simple(const str[], const pattern[], flags = 0, error[]= "", maxLen = 0, &errcode = 0)
{
new Regex:regex = regex_compile_ex(pattern, flags, error, maxLen, errcode);
if (regex < REGEX_OK)
{
return -1;
}
new substrings = regex_match_c(str, regex);
regex_free(regex);
return substrings;
}
/**
* Flags used with regex_replace to control the replacement behavior.
*/
#define REGEX_FORMAT_DEFAULT 0 /* Uses the standard formatting rules to replace matches */
#define REGEX_FORMAT_NOCOPY (1<<0) /* The sections that do not match the regular expression are not copied when replacing matches. */
#define REGEX_FORMAT_FIRSTONLY (1<<1) /* Only the first occurrence of a regular expression is replaced. */
/**
* Perform a regular expression search and replace.
*
* An optional parameter, flags, allows you to specify options on how the replacement is performed.
* Supported format specifiers for replace parameter:
* $number : Substitutes the substring matched by group number.
* n must be an integer value designating a valid backreference, greater than 0, and of two digits at most.
* ${name} : Substitutes the substring matched by the named group name (a maximum of 32 characters).
* $& : Substitutes a copy of the whole match.
* $` : Substitutes all the text of the input string before the match.
* $' : Substitutes all the text of the input string after the match.
* $+ : Substitutes the last group that was captured.
* $_ : Substitutes the entire input string.
* $$ : Substitutes a literal "$".
* As note, the character \ can be also used with format specifier, this is same hehavior as $.
*
* @param pattern The regular expression pattern.
* @param string The string to check.
* @param error Error message, if applicable.
* @param maxLen Maximum length of the error buffer.
* @param replace The string will be used to replace any matches. See above for format specifiers.
* @param flags General flags to control how the string is replaced. See REGEX_FORMAT_* defines.
* @param errcode Regex type error code encountered, if applicable. See REGEX_ERROR_* defines.
*
* @return -2 = Matching error (error code is stored in ret)
* 0 = No match.
* >1 = Number of matches.
*/
native regex_replace(Regex:pattern, string[], maxLen, const replace[], flags = REGEX_FORMAT_DEFAULT, &errcode = 0);

View File

@ -0,0 +1,183 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Socket Functions
//
#if defined _socket_included
#endinput
#endif
#define _socket_included
#pragma reqlib sockets
#if !defined AMXMODX_NOAUTOLOAD
#pragma loadlib sockets
#endif
/**
* Socket connection type (TCP/UDP)
*/
#define SOCKET_TCP 1
#define SOCKET_UDP 2
/**
* Socket flags
*/
#define SOCK_NON_BLOCKING (1 << 0) /* Set the socket a nonblocking */
#define SOCK_LIBC_ERRORS (1 << 1) /* Enable libc error reporting */
/**
* Error reporting
*/
#define SOCK_ERROR_OK 0 /* No error */
#define SOCK_ERROR_CREATE_SOCKET 1 /* Couldn't create a socket */
#define SOCK_ERROR_SERVER_UNKNOWN 2 /* Server unknown */
#define SOCK_ERROR_WHILE_CONNECTING 3 /* Error while connecting */
/**
* Connects to the given node and service via TCP/UDP.
*
* @note There's 2 types of error reporting on this function that you can use.
* @note Default error codes:
* 0 - No error
* 1 - Error while creating socket
* 2 - Couldn't resolve hostname
* 3 - Couldn't connect
* @note New, more expressive libc error codes:
* https://www.gnu.org/software/libc/manual/html_node/Error-Codes.html
* https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/errno.h
* https://msdn.microsoft.com/en-us/library/ms740668.aspx
*
* @note The currently available bit flags are:
* - SOCK_NON_BLOCKING : if set, the socket will be on nonblocking mode
* - SOCK_LIBC_ERRORS : if set, the new libc errors will be seen on _error
*
* @note If no flags are set, the behaviour of the function will not be modified.
*
* @note Multiple flags may be set at the same time using the | operator.
* For example, SOCK_NON_BLOCKING|SOCK_LIBC_ERRORS will create a nonblocking socket with libc error codes.
*
* @note If you're creating a new nonblocking socket, _hostname should be numeric to avoid calling the
* name resolution server and potentially blocking the call.
*
* @note If the socket is a nonblocking one, the returned socket descriptor may be still connecting and
* further checks should be done with socket_is_writable() before trying to send data.
*
* @param _hostname Node to connect to
* @param _port Service to connect to
* @param _protocol Connect via SOCKET_TCP or SOCKET_UDP
* @param _error Set an error code here if anything goes wrong
* @param _flags Optional bit flags that change the behaviour of the function
*
* @return A socket descriptor (a positive integer) on success
* -1 on failure
*/
native socket_open(const _hostname[], _port, _protocol = SOCKET_TCP, &_error, _flags = 0);
/**
* Closes a socket.
*
* @param _socket Socket descriptor
*
* @return 1 on success
* 0 on failure
*/
native socket_close(_socket);
/**
* Receives data.
*
* @note The amount of bytes than you end up receiving can be less than the one you expected.
*
* @note This function will completely block the server until some data arrives
* to the given socket. Use this only if you are sure there is some data
* to be retrieved. You can do that by polling with socket_is_readable().
*
* @param _socket Socket descriptor
* @param _data Array to save the data
* @param _length Length of the array
*
* @return Amount of bytes received
* 0 if the peer closed the connection
* -1 on failure
*/
native socket_recv(_socket, _data[], _length);
/**
* Sends data.
*
* @note The amount of bytes that end up being sent may be lower than the total length of the array,
* check the return value and send the rest if needed.
*
* @param _socket Socket descriptor
* @param _data Array with the data to send
* @param _length Length of the array
*
* @return Amount of bytes sent
* -1 on failure
*/
native socket_send(_socket, const _data[], _length);
/**
* Sends data that can contain null bytes.
*
* @note The amount of bytes that end up being sent may be lower than the total length of the array,
* check the return value and send the rest if needed.
*
* @note strlen(_data) will return the wrong length if the array contains null bytes.
*
* @param _socket Socket descriptor
* @param _data Array with the data to send
* @param _length Length of the array
*
* @return Amount of bytes sent
* -1 on failure
*/
native socket_send2(_socket, const _data[], _length);
/**
* Backwards compatible function.
*
* @deprecated Renamed to socket_is_readable()
*/
#pragma deprecated Use socket_is_readable() instead
native socket_change(_socket, _timeout = 100000);
/**
* Checks if a socket is marked as readable.
*
* @note You can use this function to make sure there's something on the socket and avoid a blocking call.
* @note Set _timeout to 0 avoid blocking the call.
* @note A socket will become readable if there's any data or an EOF.
*
* @param _socket Socket descriptor
* @param _timeout Amount of time to block the call waiting for the socket to be marked as readable or
* for the timeout to expire, in µSeconds (1 sec = 1000000 µsec)
*
* @return 1 if the socket is marked as readable
* 0 otherwise
*/
native socket_is_readable(_socket, _timeout = 100000);
/**
* Checks if a socket is marked as writable.
*
* @note Use this function to check if a nonblocking socket is ready to be used.
* @note Set _timeout to 0 avoid blocking the call.
* @note An UDP socket is always writable.
*
* @param _socket Socket descriptor
* @param _timeout Amount of time to block the call waiting for the socket to be marked as writable or
* for the timeout to expire, in µSeconds (1 sec = 1000000 µsec)
*
* @return 1 if the socket is marked as writable
* 0 otherwise
*/
native socket_is_writable(_socket, _timeout = 100000);

View File

@ -0,0 +1,107 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Sorting Functions
//
//
// All sort functions are based off the qsort() function from the
// C standard library, which uses the Quick Sort algorithm.
// For more info, see: http://linux.wku.edu/~lamonml/algor/sort/sort.html
//
#if defined _sorting_included
#endinput
#endif
#define _sorting_included
/**
* Contains sorting orders.
*/
enum SortMethod
{
Sort_Ascending = 0,
Sort_Descending,
Sort_Random,
};
/**
* Data types for ADT Array Sorts
*/
enum SortType
{
Sort_Integer = 0,
Sort_Float,
Sort_String,
};
/**
* Basic sorting functions below.
*/
native SortIntegers(array[], array_size, SortMethod:order = Sort_Ascending);
native SortFloats(Float:array[], array_size, SortMethod:order = Sort_Ascending);
native SortStrings(array[][], num_strings, SortMethod:order = Sort_Ascending);
/**
* Custom sorting functions below.
*/
/**
* Sorts a custom 1D array. You must pass in a comparison function.
* The sorting algorithm then uses your comparison function to sort the data.
* The function is called in the following manner:
*
* public MySortFunc(elem1, elem2, const array[], const data[], data_size)
*
* elem1, elem2 - Current element pair being compared
* array[] - Array in its current mid-sorted state.
* data[] - Extra data array you passed to the sort func.
* data_size - Size of extra data you passed to the sort func.
*
* Your function should return:
* -1 if elem1 should go before elem2
* 0 if elem1 and elem2 are equal
* 1 if elem1 should go after elem2
* Note that the parameters after elem2 are all optional and you do not need to specify them.
*/
native SortCustom1D(array[], array_size, const comparefunc[], data[]="", data_size=0);
/**
* Sorts a custom 2D array.
* The sorting algorithm then uses your comparison function to sort the data.
* The function is called in the following manner:
*
* public MySortFunc(const elem1[], const elem2[], const array[], data[], data_size)
*
* elem1[], elem2[] - Current element array pairs being compared
* array[][] - Array in its currently being sorted state.
* data[] - Extra data array you passed to the sort func.
* data_size - Size of extra data you passed to the sort func.
*
* Your function should return:
* -1 if elem1[] should go before elem2[]
* 0 if elem1[] and elem2 are equal[]
* 1 if elem1[] should go after elem2[]
* Note that the parameters after elem2[] are all optional and you do not need to specify them.
*/
native SortCustom2D(array[][], array_size, const comparefunc[], data[]="", data_size=0);
/**
* Sort an ADT Array. Specify the type as Integer, Float, or String.
*
* @param array Array Handle to sort
* @param order Sort order to use, same as other sorts.
* @param type Data type stored in the ADT Array
* @noreturn
*/
native SortADTArray(Array:array, SortMethod:order, SortType:type);

View File

@ -0,0 +1,582 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// SQLX - Newer SQL Database API
//
#if defined _sqlx_included
#endinput
#endif
#define _sqlx_included
//eh..
#define SQL_NumRows SQL_NumResults
#pragma reqclass sqlx
#if !defined AMXMODX_NOAUTOLOAD
#pragma defclasslib sqlx mysql
#endif
enum Handle
{
Empty_Handle
};
/**
* Creates a connection information tuple. This tuple must be passed
* into connection routines.
*
* @note Freeing the tuple is not necessary, but is a good idea if you create
* many of them. You can cache these handles globally.
* @note This does not connect to the DB; it only caches the connection information.
*
* @param host Database host
* @param user Database user
* @param pass Database password
* @param db Database name to use
* @param timeout Specifies how long connections should wait before giving up.
* If <= 0, the default of 60s is used.
*
* @return A newly created tuple handle to be used in connection routines.
*/
native Handle:SQL_MakeDbTuple(const host[], const user[], const pass[], const db[], timeout=0);
/**
* Frees an SQL handle.
*
* @note The handle can be to anything (tuple, connection, query, results, etc).
* @note If you free the database connection handle, it closes the connection as well.
*
* @param h Handle to be freed.
*
* @noreturn
*/
native SQL_FreeHandle(Handle:h);
/**
* Opens a database connection.
*
* @param cn_tuple Tuple handle, returned from SQL_MakeDbTuple().
* @param errcode An error code set by reference.
* @param error String where error string will be stored.
* @param maxlength Maximum length of the error buffer.
*
* @return Returns an SQL connection handle, which must be freed.
* Returns Empty_Handle on failure.
* @error Invalid info tuple handle.
*/
native Handle:SQL_Connect(Handle:cn_tuple, &errcode, error[], maxlength);
/**
* Sets the character set of the current connection.
* Like SET NAMES .. in mysql, but stays after connection problems.
*
* @note If a connection tuple is supplied, this should be called before SQL_Connect or SQL_ThreadQuery.
* @note The change will remain until you call this function with another value.
* @note This native does nothing in SQLite.
*
* Example: "utf8", "latin1"
*
* @param h Database or connection tuple Handle.
* @param charset The character set string to change to.
*
* @return True, if character set was changed, false otherwise.
*/
native bool:SQL_SetCharset(Handle:h, const charset[]);
/**
* Prepares a query.
*
* @note This does not actually do a query!
*
* @param db Connection handle, returned from SQL_Connect().
* @param fmt Query string. Can be formated with format specifiers.
* @param ... Additional format specifiers used to format the query.
*
* @return Returns an SQL query handle, which must always be freed.
* Returns Empty_Handle on failure.
*/
native Handle:SQL_PrepareQuery(Handle:db, const fmt[], any:...);
/**
* Back-quotes characters in a string for database querying.
*
* @note The buffer's maximum size should be 2*strlen(string) to catch all scenarios.
*
* @param db Database handle for localization, or Empty_Handle
* for when a handle is not available.
* @param buffer Buffer to copy to.
* @param buflen Maximum size of the buffer.
* @param string String to backquote (should not overlap buffer).
*
* @return Length of new string, or -1 on failure.
* @error Invalid database handle.
*/
native SQL_QuoteString(Handle:db, buffer[], buflen, const string[]);
/**
* Back-quotes characters in a string for database querying.
* Note: The buffer's maximum size should be 2*strlen(string) to catch
* all scenarios.
*
* @param db Database handle for localization, or Empty_Handle
* for when a handle is not available.
* @param buffer Buffer to copy to.
* @param buflen Maximum size of the buffer.
* @param fmt Format of string to backquote (should not overlap buffer).
* @param ... Format arguments.
*
* @return Length of new string, or -1 on failure.
*/
native SQL_QuoteStringFmt(Handle:db, buffer[], buflen, const fmt[], any:...);
/**
* Threaded query states. Used to check the state of a complete threaded query.
*/
#define TQUERY_CONNECT_FAILED -2
#define TQUERY_QUERY_FAILED -1
#define TQUERY_SUCCESS 0
/**
* Prepares and executes a threaded query.
* @note The handler should look like:
* public QueryHandler(failstate, Handle:query, error[], errnum, data[], size, Float:queuetime)
* failstate - One of the three TQUERY_ defines.
* query - Handle to the query, do not free it.
* error - An error message, if any.
* errnum - An error code, if any.
* data - Data array you passed in.
* size - Size of the data array you passed in.
* queuetime - Amount of gametime that passed while the query was resolving.
* @note This will not interrupt gameplay in the event of a poor/lossed
* connection, however, the interface is more complicated and
* asynchronous. Furthermore, a new connection/disconnection is
* made for each query to simplify driver support.
* @note The handle does not need to be freed.
*
* @param db_tuple Tuple handle, returned from SQL_MakeDbTuple().
* @param handler A function to be called when the query finishes. It has to be public.
* @param query The query string.
* @param data Additional data array that will be passed to the handler function.
* @param dataSize The size of the additional data array.
*
* @noreturn
* @error Thread worker was unable to start.
* Invalid info tuple handle.
* Handler function not found.
*/
native SQL_ThreadQuery(Handle:db_tuple, const handler[], const query[], const data[]="", dataSize=0);
/**
* Executes an already prepared query.
*
* @note You can call this multiple times as long as its parent connection is kept open.
* Each time the result set from the previous call will be freed.
*
* @param query Handle of a prepared query to be executed.
*
* @return 1 if the query succeeded, 0 if the query failed.
* @error Invalid query handle.
*/
native SQL_Execute(Handle:query);
/**
* Gets information about a failed query error.
*
* @param query Handle of a query to extract the error from.
* @param error Buffer where to store the error string.
* @param maxlength The maximum length of the output buffer.
*
* @return The error code.
*/
native SQL_QueryError(Handle:query, error[], maxlength);
/**
* Checks whether there are more results to be read.
*
* @param query Handle of a query to check.
*
* @return 1 if there are more results, 0 otherwise.
* @error Invalid query handle.
*/
native SQL_MoreResults(Handle:query);
/**
* Tells whether a specific column in the current row is NULL or not.
*
* @param query Handle of a query to check.
* @param column Which column to check for NULL.
*
* @return 1 if the column is NULL, 0 otherwise.
* @error Invalid query handle.
* No result set in this query.
* Invalid column.
*/
native SQL_IsNull(Handle:query, column);
/**
* Retrieves the current result.
*
* @note A successful query starts at the first result, so you should not call
* SQL_NextRow() first.
*
* @note Example how to get different types of values:
* new num = SQL_ReadResult(query, 0)
* new Float:num2
* new string[32]
* SQL_ReadResult(query, 1, num2)
* SQL_ReadResult(query, 2, string, charsmax(string))
*
* @param query Handle of a query to read results from.
* @param column Which column to get the value from.
* @param ... Passing no extra arguments - returns an integer.
* Passing one extra argument - returns a float in the first extra argument
* Passing two extra params - returns a string in the first argument
* with a maximum string length in the second argument.
*
* @return If no extra arguments are passed, returns an integer value.
* @error Invalid query handle.
*/
native SQL_ReadResult(Handle:query, column, any:...);
/**
* Advances to the next result (row).
*
* @param query Handle of a query.
*
* @noreturn
* @error Invalid query handle.
* No result set in this query.
*/
native SQL_NextRow(Handle:query);
/**
* Returns the number of affected rows by a query.
*
* @param query Handle of a query to check.
*
* @return The number of affected rows.
* @error Invalid query handle.
*/
native SQL_AffectedRows(Handle:query);
/**
* The number of retrieved rows (results) after a query.
*
* @param query Handle of a query to check.
*
* @return The number of retrieved rows by the query.
* @error Invalid query handle.
*/
native SQL_NumResults(Handle:query);
/**
* Returns the total number of columns.
*
* @param query Handle of a query to check.
*
* @return The number of retrieved columns by the query.
* @error Invalid query handle.
* No result set in this query.
*/
native SQL_NumColumns(Handle:query);
/**
* Retrieves the name of a column by its index.
*
* @param query Handle of a query.
* @param num The number (index) of a column to retrieve the name from.
* @param name Buffer where to store the column's name.
* @param maxlength Maximum length of the output buffer.
*
* @noreturn
* @error Invalid query handle.
* No result set in this query.
* Invalid column index.
*/
native SQL_FieldNumToName(Handle:query, num, name[], maxlength);
/**
* Retrieves the number of a named column.
*
* @param query Handle of a query.
* @param name Name to search for.
*
* @return Column index if found (>= 0); -1 otherwise.
* @error Invalid query handle.
* No result set in this query.
*/
native SQL_FieldNameToNum(Handle:query, const name[]);
/**
* Rewinds a result set to the first row.
*
* @param query Handle of a query to rewind the result set of.
*
* @noreturn
* @error Invalid query handle.
* No result set in this query.
*/
native SQL_Rewind(Handle:query);
/**
* Retrieves the instert ID of the latest INSERT query.
*
* @param query Handle of a query.
*
* @return The insert ID of the latest INSERT query.
* @error Invalid query handle.
*/
native SQL_GetInsertId(Handle:query);
/**
* Retrieves which driver is this plugin currently bound to.
*
* @param driver Buffer to store the driver name in.
* @param maxlen Maximum length of the output buffer.
*
* @noreturn
*/
native SQL_GetAffinity(driver[], maxlen);
/**
* Sets driver affinity. You can use this to force a particular driver implementation.
* This will automatically change all SQL natives in your plugin to be "bound" to
* the module in question.
*
* @note Using this while you have open handles to another database type will
* cause problems. I.e., you cannot open a handle, switch affinity,
* then close the handle with a different driver.
* @note Switching affinity is an O(n * m) operation, where n is the number of
* SQL natives and m is the number of used natives in total.
* @note Intuitive programmers will note that this causes problems for
* threaded queries. You will have to either force your script to work
* under one affinity, or to pack the affinity type into the query data,
* check it against the current, then set the new affinity if necessary.
* Then, restore the old one for safety.
*
* @param driver The name of a driver to use.
*
* @return If no module with the given name is found, returns 0.
* Unless your plugin is bult to handle different driver
* types at once, you should let this error pass.
*/
native SQL_SetAffinity(const driver[]);
/**
* Returns the original query string that a query handle used.
*
* @param query Handle of a query.
* @param buffer Buffer where to put the query string in.
* @param maxlength The maximum length of the output buffer.
*
* @noreturn
* @error Invalid query handle.
*/
native SQL_GetQueryString(Handle:query, buffer[], maxlength);
/**
* For queries which return multiple result sets, this advances to the next
* result set if one is available. Otherwise, the current result set is
* destroyed and will no longer be accessible.
*
* @note This function will always return false on SQLite, and when using threaded
* queries in MySQL. Nonetheless, it has the same effect of removing the last
* result set.
*
* @param query Query Handle.
*
* @return True on success, false on failure.
* @error Invalid query handle.
* No result set in this query.
*/
native bool:SQL_NextResultSet(Handle:query);
/**
* This function can be used to find out if a table in a SQLite database exists.
*
* @param db Connection handle returned from SQL_Connect().
* @param table The table name to check for.
*
* @return True if it exists, false otherwise.
*/
stock bool:sqlite_TableExists(Handle:db, const table[])
{
new Handle:query = SQL_PrepareQuery(
db,
"SELECT name FROM sqlite_master WHERE type='table' AND name='%s' LIMIT 1;",
table);
if (!SQL_Execute(query) || !SQL_NumResults(query))
{
SQL_FreeHandle(query);
return false;
}
SQL_FreeHandle(query);
return true;
}
/**
* Use this for executing a query where you don't care about the result.
*
* @param db Connection handle returned from SQL_Connect().
* @param query The query string.
* @param error If an error occurs, it will be placed into this buffer.
* @param maxlength Maximum length of the error buffer.
* @param rows Optional. If put, retrieves the number of rows the query returned.
*
* @return 1 on success, 0 on failure.
*/
stock SQL_SimpleQuery(Handle:db, const query[], error[]="", maxlength=0, &rows=0)
{
new Handle:hQuery = SQL_PrepareQuery(db, "%s", query);
if (!SQL_Execute(hQuery))
{
SQL_QueryError(hQuery, error, maxlength);
SQL_FreeHandle(hQuery);
return 0;
}
rows = SQL_NumResults(hQuery);
SQL_FreeHandle(hQuery);
return 1;
}
/**
* Use this for executing a query where you don't care about the result.
*
* @note Differs from SQL_SimpleQuery() because the query can be formated.
*
* @param db Connection handle returned from SQL_Connect().
* @param error If an error occurs, it will be placed into this buffer.
* @param maxlength The maximum length of the error buffer.
* @param rows Optional. If put, retrieves the number of rows the query returned.
* @param fmt The query string that can be formated with format specifiers.
* @param ... Additional arguments for formating the query.
*
* @return 1 on success, 0 on failure.
*/
stock SQL_SimpleQueryFmt(Handle:db, error[]="", maxlength=0, &rows=0, const fmt[], any:...)
{
static query_buf[2048];
vformat(query_buf, 2047, fmt, 6);
new Handle:hQuery = SQL_PrepareQuery(db, "%s", query_buf);
if (!SQL_Execute(hQuery))
{
SQL_QueryError(hQuery, error, maxlength);
SQL_FreeHandle(hQuery);
return 0;
}
rows = SQL_NumResults(hQuery);
SQL_FreeHandle(hQuery);
return 1;
}
/**
* Use this for executing a query and not caring about the error.
*
* @param db A connection handle returned from SQL_Connect().
* @param queryfmt The query string that can be formated with format specifiers.
* @pram ... Additional arguments for formating the query.
*
* @return 1 on error.
* >= 0 on success (with the number of affected rows).
*/
stock SQL_QueryAndIgnore(Handle:db, const queryfmt[], any:...)
{
static query[4096];
new Handle:hQuery;
new ret;
vformat(query, sizeof(query)-1, queryfmt, 3);
hQuery = SQL_PrepareQuery(db, "%s", query);
if (SQL_Execute(hQuery))
{
ret = SQL_AffectedRows(hQuery);
} else {
ret = -1;
}
SQL_FreeHandle(hQuery);
return ret;
}
/**
* Use this for making a standard DB Tuple, using AMXX's database info cvars.
*
* @param timeout Specifies how long connections should wait before giving up.
* If 0, the value is read from "amx_sql_timeout" cvar.
*
* @return A newly created tuple handle to be used in connection routines.
*/
stock Handle:SQL_MakeStdTuple(timeout = 0)
{
static host[64], user[32], pass[32], db[128];
static get_type[12], set_type[12];
get_cvar_string("amx_sql_host", host, 63);
get_cvar_string("amx_sql_user", user, 31);
get_cvar_string("amx_sql_pass", pass, 31);
get_cvar_string("amx_sql_type", set_type, 11);
get_cvar_string("amx_sql_db", db, 127);
if (timeout <= 0)
{
timeout = get_cvar_num("amx_sql_timeout");
}
SQL_GetAffinity(get_type, 12);
if (!equali(get_type, set_type))
{
if (!SQL_SetAffinity(set_type))
{
log_amx("Failed to set affinity from %s to %s.", get_type, set_type);
}
}
return SQL_MakeDbTuple(host, user, pass, db, timeout);
}

View File

@ -0,0 +1,786 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// String Manipulation
//
#if defined _string_included
#endinput
#endif
#define _string_included
#include <string_const>
/**
* @global Unless otherwise noted, all string functions which take in a
* writable buffer and maximum length should NOT have the null terminator INCLUDED
* in the length. This means that this is valid:
* copy(string, charsmax(string), ...)
*/
/**
* Calculates the length of a string.
*
* @param string String to check.
* @return Number of valid character bytes in the string.
*/
native strlen(const string[]);
/**
* Tests whether a string is found inside another string.
*
* @param source String to search in.
* @param string Substring to find inside the original string.
*
* @return -1 on failure (no match found). Any other value
* indicates a position in the string where the match starts.
*/
native contain(const source[], const string[]);
/**
* Tests whether a string is found inside another string with case ignoring.
*
* @note This supports multi-byte characters (UTF-8) on comparison.
*
* @param source String to search in.
* @param string Substring to find inside the original string.
*
* @return -1 on failure (no match found). Any other value
* indicates a position in the string where the match starts.
*/
native containi(const source[], const string[]);
/**
* Given a string, replaces the first occurrence of a search string with a
* replacement string.
*
* @param text String to perform search and replacements on.
* @param len Maximum length of the string buffer.
* @param what String to search for.
* @param with String to replace the search string with.
*
* @return The new string length after replacement, or 0 if no replacements were made.
*/
native replace(text[], len, const what[], const with[]);
/**
* Given a string, replaces all occurrences of a search string with a
* replacement string.
*
* @note Similar to replace_all() stock, but implemented as native and
* with different algorithm. This native doesn't error on bad
* buffer size and will smartly cut off the string in a way
* that pushes old data out.
*
* @note Only available in 1.8.3 and above.
* @note This supports multi-byte characters (UTF-8) on case insensitive comparison.
*
* @param text String to perform search and replacements on.
* @param maxlength Maximum length of the string buffer.
* @param search String to search for.
* @param replace String to replace the search string with.
* @param caseSensitive If true (default), search is case sensitive.
*
* @return Number of replacements that were performed.
*/
native replace_string(text[], maxlength, const search[], const replace[], bool:caseSensitive = true);
/**
* Given a string, replaces the first occurrence of a search string with a
* replacement string.
*
* @note Similar to replace() native, but implemented with more options and
* with different algorithm. This native doesn't error on bad
* buffer size and will smartly cut off the string in a way
* that pushes old data out.
*
* @note Only available in 1.8.3 and above.
* @note This supports multi-byte characters (UTF-8) on case insensitive comparison.
*
* @param text String to perform search and replacements on.
* @param maxlength Maximum length of the string buffer.
* @param search String to search for.
* @param replace String to replace the search string with.
* @param searchLen If higher than -1, its value will be used instead of
* a strlen() call on the search parameter.
* @param replaceLen If higher than -1, its value will be used instead of
* a strlen() call on the replace parameter.
* @param caseSensitive If true (default), search is case sensitive.
*
* @return Index into the buffer (relative to the start) from where
* the last replacement ended, or -1 if no replacements were
* made.
*/
native replace_stringex(text[], maxlength, const search[], const replace[], searchLen = -1, replaceLen = -1, bool:caseSensitive = true);
/**
* Concatenates one string onto another.
*
* @param dest String to append to.
* @param len Maximum length of entire buffer.
* @param src Source string to concatenate.
* @param max Number of characters to add.
*
* @return Number of of all merged characters.
*/
native add(dest[],len,const src[],max=0);
/**
* Formats a string according to the AMX Mod X format rules (see documentation).
*
* @note Example: format(dest, "Hello %s. You are %d years old", "Tom", 17).
* If any of your input buffers overlap with the destination buffer,
* format() falls back to a "copy-back" version as of 1.65. This is
* slower, so you should using a source string that is the same as
* the destination.
*
* @param output Destination string buffer.
* @param len Maximum length of output string buffer.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
*
* @return Number of cells written.
*/
native format(output[], len, const format[], any:...);
/**
* Formats a string according to the AMX Mod X format rules (see documentation).
*
* @note Same as format(), except does not perform a "copy back" check.
* This means formatex() is faster, but DOES NOT ALLOW this type
* of call:
* formatex(buffer, len, "%s", buffer)
* formatex(buffer, len, buffer, buffer)
* formatex(buffer, len, "%s", buffer[5])
* This is because the output is directly stored into "buffer",
* rather than copied back at the end.
*
* @param output Destination string buffer.
* @param len Maximum length of output string buffer.
* @param format Formatting rules.
* @param ... Variable number of format parameters.
*
* @return Number of cells written.
*/
native formatex(output[], len, const format[], any:...);
/**
* Formats and returns a string according to the AMX Mod X format rules
* (see documentation).
*
* @note Example: menu_additem(menu, fmt("My first %s", "item")).
* @note This should only be used for simple inline formatting like in the above example.
* Avoid using this function to store strings into variables as an additional
* copying step is required.
* @note The buffer size is defined by MAX_FMT_LENGTH.
*
* @param format Formatting rules.
* @param ... Variable number of format parameters.
*
* @return Formatted string
*/
native [MAX_FMT_LENGTH]fmt(const format[], any:...);
/**
* Formats a string according to the AMX Mod X format rules (see documentation).
*
* @note This is the same as format(), except it grabs parameters from a
* parent parameter stack, rather than a local. This is useful for
* implementing your own variable argument functions.
*
* @note Replacement for format_args. Much faster and %L compatible.
* This works exactly like vsnprintf() from C.
* You must pass in the output buffer and its size,
* the string to format, and the number of the FIRST variable
* argument parameter. For example, for:
* function (a, b, c, ...)
* You would pass 4 (a is 1, b is 2, c is 3, et cetera).
* There is no vformatex().
*
* @param buffer Destination string buffer.
* @param len Maximum length of output string buffer.
* @param fmt Formatting rules.
* @param vararg Argument number which contains the '...' symbol.
* Note: Arguments start at 1.
* @return Number of bytes written.
*/
native vformat(buffer[], len, const fmt[], vararg);
/**
* Formats a string according to the AMX Mod X format rules (see documentation).
*
* @note Same as vformat(), except works in normal style dynamic natives.
* Instead of passing the format arg string, you can only pass the
* actual format argument number itself.
* If you pass 0, it will read the format string from an optional
* fifth parameter.
*
* @param buffer Destination string buffer.
* @param len Maximum length of output string buffer.
* @param fmt_arg Argument number which contains the format.
* @param vararg Argument number which contains the '...' symbol.
* Note: Arguments start at 1.
* @return Number of bytes written.
*/
native vdformat(buffer[], len, fmt_arg, vararg, ...);
/**
* Gets parameters from function as formated string.
*
* @param output Destination string buffer.
* @param len Maximum length of output string buffer.
* @param pos Argument number which contains the '...' symbol.
*
* @return Number of bytes written.
*/
native format_args(output[], len, pos = 0);
/**
* Converts an integer to a string.
*
* @param num Integer to convert.
* @param string Buffer to store string in.
* @param len Maximum length of string buffer.
*
* @return Number of cells written to buffer.
*/
native num_to_str(num,string[],len);
/**
* Converts a string to an integer.
*
* @param string String to convert.
* @return Integer conversion of string, or 0 on failure.
*/
native str_to_num(const string[]);
/**
* Parses the 'string' interpreting its content as an integral number of the specified 'base',
* which is returned as integer value. The function also sets the value of 'endPos' to point
* to the position of the first character after the number.
*
* This is the same as C++ strtol function with a difference on second param.
*
* The function first discards as many whitespace characters as necessary until the first
* non-whitespace character is found. Then, starting from this character, takes as many
* characters as possible that are valid following a syntax that depends on the 'base' parameter,
* and interprets them as a numerical value. Finally, a position of the first character following
* the integer representation in 'string' is stored in 'endPos'.
*
* If the value of 'base' is zero, the syntax expected is similar to that of integer constants,
* which is formed by a succession of :
* An optional sign character (+ or -)
* An optional prefix indicating octal or hexadecimal base ("0" or "0x"/"0X" respectively)
* A sequence of decimal digits (if no base prefix was specified) or either octal or hexadecimal digits if a specific prefix is present
*
* If the 'base' value is between 2 and 36, the format expected for the integral number is a succession
* of any of the valid digits and/or letters needed to represent integers of the specified radix
* (starting from '0' and up to 'z'/'Z' for radix 36). The sequence may optionally be preceded by
* a sign (either + or -) and, if base is 16, an optional "0x" or "0X" prefix.
*
* If the first sequence of non-whitespace characters in 'string' is not a valid integral number
* as defined above, or if no such sequence exists because either 'string' is empty or it contains
* only whitespace characters, no conversion is performed.
*
* @param string The string to parse.
* @param endPos The position of the first character following the number.
* On success and when containing only numbers, position is at the end of string, meaning equal to 'string' length.
* On failure, position is sets always to 0.
* @param base The numerical base (radix) that determines the valid characters and their interpretation.
* If this is 0, the base used is determined by the format in the sequence.
* @return On success, the function returns the converted integral number as integer value.
* If no valid conversion could be performed, a zero value is returned.
* If the value read is out of the range of representable values by a cell,
* the function returns 'cellmin' or 'cellmax'.
*/
native strtol(const string[], &endPos = 0, base = 0);
/**
* Parses the 'string' interpreting its content as an floating point number and returns its value as a float.
* The function also sets the value of 'endPos' to point to the position of the first character after the number.
*
* This is the same as C++ strtod function with a difference on second param.
*
* The function first discards as many whitespace characters as necessary until the first
* non-whitespace character is found. Then, starting from this character, takes as many
* characters as possible that are valid and interprets them as a numerical value.
* Finally, a position of the first character following the float representation in 'string'
* is stored in 'endPos'.
*
* If the first sequence of non-whitespace characters in 'string' is not a valid float number
* as defined above, or if no such sequence exists because either 'string' is empty or it contains
* only whitespace characters, no conversion is performed.
*
* @param string The string to parse.
* @param endPos The position of the first character following the number.
* On success and when containing only numbers, position is at the end of string, meaning equal to 'string' length.
* On failure, position is sets always to 0.
* @return On success, the function returns the converted floating point number as float value.
* If no valid conversion could be performed, a zero value is returned.
*/
native Float:strtof(const string[], &endPos = 0);
/**
* Converts a floating point number to a string.
*
* @param fl Floating point number to convert.
* @param string Buffer to store string in.
* @param len Maximum length of string buffer.
*
* @return Number of cells written to buffer.
*/
native float_to_str(Float:fl, string[], len);
/**
* Converts a string to a floating point number.
*
* @param string String to convert to a foat.
* @return Floating point result, or 0.0 on error.
*/
native Float:str_to_float(const string[]);
/**
* Returns whether two strings are equal.
*
* @param a First string (left).
* @param b Second string (right).
* @param c Number of characters to compare.
*
* @return True if equal, false otherwise.
*/
native equal(const a[],const b[],c=0);
/**
* Returns whether two strings are equal with case ignoring.
*
* @note This supports multi-byte characters (UTF-8) on comparison.
*
* @param a First string (left).
* @param b Second string (right).
* @param c Number of characters to compare.
*
* @return True if equal, false otherwise.
*/
native equali(const a[], const b[], c = 0);
/**
* Copies one string to another string.
*
* @note If the destination buffer is too small to hold the source string, the
* destination will be truncated.
*
* @param dest Destination string buffer to copy to.
* @param len Destination buffer length.
* @param src Source string buffer to copy from.
*
* @return Number of cells written.
*/
native copy(dest[],len,const src[]);
/**
* Copies one string to another string until ch is found.
*
* @param dest Destination string buffer to copy to.
* @param len Destination buffer length.
* @param src Source string buffer to copy from.
* @param ch Character to search for.
*
* @return Number of cells written.
*/
native copyc(dest[],len,const src[],ch);
/**
* Sets string with given character.
*
* @param src Destination string buffer to copy to.
* @param len Destination buffer length.
* @param ch Character to set string.
*
* @noreturn
*/
native setc(src[],len,ch);
/**
* Gets parameters from text.
*
* @note Example: to split text: "^"This is^" the best year",
* call function like this: parse(text,arg1,len1,arg2,len2,arg3,len3,arg4,len4)
* and you will get: "This is", "the", "best", "year"
* Function returns number of parsed parameters.
*
* @param text String to parse.
* @param ... Variable number of format parameters.
*
* @return Number of parsed parameters.
*/
native parse(const text[], ... );
/**
* Breaks a string in two by token.
*
* @note Trimming spaces is buggy. Consider strtok2 instead.
*
* @note See argbreak() for doing this with parameters.
* Example:
* str1[] = This *is*some text
* strtok(str1, left, 24, right, 24, '*')
* left will be "This "
* Right will be "is*some text"
* If you use trimSpaces, all spaces are trimmed from Left.
*
* @param text String to tokenize
* @param Left Buffer to store left half
* @param leftLen Size of left buffer
* @param Right Buffer to store right half
* @param rightLen Size of right buffer
* @param token Token to split by
* @param trimSpaces Whether spaces are trimmed.
*
* @noreturn
*/
native strtok(const text[], Left[], leftLen, Right[], rightLen, token=' ', trimSpaces=0);
/**
* Breaks a string in two by token.
*
* @note Only available in 1.8.3 and above.
*
* @param text String to tokenize
* @param left Buffer to store left half
* @param llen Size of left buffer
* @param right Buffer to store right half
* @param rlen Size of right buffer
* @param token Token to split by
* @param trim Flags for trimming behavior, see above
*
* @return Returns position of token in string if found,
* -1 if token was not found
*/
native strtok2(const text[], left[], const llen, right[], const rlen, const token = ' ', const trim = 0);
/**
* Removes whitespace characters from the beginning and end of a string.
*
* @param text The string to trim.
* @return Number of bytes written.
*/
native trim(text[]);
/**
* Converts all chars in string to lower case.
*
* @param string The string to convert.
* @return Number of bytes written.
*/
native strtolower(string[]);
/**
* Performs a multi-byte safe (UTF-8) conversion of all chars in string to lower case.
*
* @note Although most code points can be converted in-place, there are notable
* exceptions and the final length can vary.
* @note Case mapping is not reversible. That is, toUpper(toLower(x)) != toLower(toUpper(x)).
*
* @param string The string to convert.
* @param maxlength Optional size of the buffer. If 0, the length of the original string
* will be used instead.
*
* @return Number of bytes written.
*/
native mb_strtolower(string[], maxlength = 0);
/**
* Converts all chars in string to upper case.
*
* @param string The string to convert.
* @return Number of bytes written.
*/
native strtoupper(string[]);
/**
* Performs a multi-byte safe (UTF-8) conversion of all chars in string to upper case.
*
* @note Although most code points can be converted in-place, there are notable
* exceptions and the final length can vary.
* @note Case mapping is not reversible. That is, toUpper(toLower(x)) != toLower(toUpper(x)).
*
* @param string The string to convert.
* @param maxlength Optional size of the buffer. If 0, the length of the original string
* will be used instead.
*
* @return Number of bytes written.
*/
native mb_strtoupper(string[], maxlength = 0);
/**
* Make a string's first character uppercase.
*
* @param string The string to convert.
* @return 1 on success, otherwise 0.
*/
native ucfirst(string[]);
/**
* Performs a multi-byte safe (UTF-8) conversion of a string's first character to upper case.
*
* @note Although most code points can be converted in-place, there are notable
* exceptions and the final length can vary.
*
* @param string The string to convert.
* @param maxlength Optional size of the buffer. If 0, the length of the original string
* will be used instead.
*
* @return Number of bytes written.
*/
native mb_ucfirst(string[], maxlength = 0);
/**
* Performs a multi-byte safe (UTF-8) conversion of all chars in string to title case.
*
* @note Although most code points can be converted in-place, there are notable
* exceptions and the final length can vary.
* @note Any type of punctuation can break up a word, even if this is
* not grammatically valid. This happens because the titlecasing algorithm
* does not and cannot take grammar rules into account.
* @note Examples:
* The running man | The Running Man
* NATO Alliance | Nato Alliance
* You're amazing at building libraries | You'Re Amazing At Building Libraries
*
* @param string The string to convert.
* @param maxlength Optional size of the buffer. If 0, the length of the original string
* will be used instead.
*
* @return Number of bytes written.
*/
native mb_strtotitle(string[], maxlength = 0);
/**
* Checks if the input string conforms to the category specified by the flags.
*
* @note This function can be used to check if the code points in a string are part
* of a category. Valid flags are part of the UTF8C_* list of defines.
* The category for a code point is defined as part of the entry in
* UnicodeData.txt, the data file for the Unicode code point database.
* @note Flags parameter must be a combination of UTF8C_* flags or a single UTF8C_IS* flag.
* In order to main backwards compatibility with POSIX functions like `isdigit`
* and `isspace`, compatibility flags have been provided. Note, however, that
* the result is only guaranteed to be correct for code points in the Basic
* Latin range, between U+0000 and 0+007F. Combining a compatibility flag with
* a regular category flag will result in undefined behavior.
* @note The function is greedy. This means it will try to match as many code
* points with the matching category flags as possible and return the offset in
* the input in bytes.
*
* @param input The string to check
* @param input_size Size of the string, use 1 to check one character regardless its size
* @param flags Requested category, see UTF8C_* flags
* @param output_size Number of bytes in the input that conform to the specified
* category flags
* @return True if the whole input of `input_size` conforms to the specified
* category flags, false otherwise
*/
native bool:is_string_category(const input[], input_size, flags, &output_size = 0);
/**
* Returns whether a character is numeric.
*
* @note Multi-byte characters will always return false.
*
* @param ch Character to test.
* @return True if character is numeric, otherwise false.
*/
native isdigit(ch);
/**
* Returns whether a character is an ASCII alphabet character.
*
* @note Multi-byte characters will always return false.
*
* @param ch Character to test.
* @return True if character is alphabetical, otherwise false.
*/
native isalpha(ch);
/**
* Returns whether a character is whitespace.
*
* @note Multi-byte characters will always return false.
*
* @param ch Character to test.
* @return True if character is whitespace, otherwise false.
*/
native isspace(ch);
/**
* Returns whether a character is numeric or an ASCII alphabet character.
*
* @note Multi-byte characters will always return false.
*
* @param ch Character to test.
* @return True if character is numeric, otherwise false.
*/
native isalnum(ch);
/**
* Returns if a character is multi-byte or not.
*
* @note Only available in 1.8.3 and above.
*
* @param ch Character to test.
* @return 0 for a normal 7-bit ASCII character,
* otherwise number of bytes in multi-byte character.
*/
native is_char_mb(ch);
/**
* Returns whether an alphabetic character is uppercase.
*
* @note Only available in 1.8.3 and above.
* @note Multi-byte characters will always return false.
*
* @param ch Character to test.
* @return True if character is uppercase, otherwise false.
*/
native bool:is_char_upper(ch);
/**
* Returns whether an alphabetic character is lowercase.
*
* @note Only available in 1.8.3 and above.
* @note Multi-byte characters will always return false.
*
* @param ch Character to test.
* @return True if character is lowercase, otherwise false.
*/
native bool:is_char_lower(ch);
/**
* Returns the number of bytes a character is using. This is
* for multi-byte characters (UTF-8). For normal ASCII characters,
* this will return 1.
*
* @note Only available in 1.8.3 and above.
*
* @param source Source input string.
* @return Number of bytes the current character uses.
*/
native get_char_bytes(const source[]);
/**
* Concatenates one string onto another.
*
* @param dest String to append to.
* @param source Source string to concatenate.
* @param maxlength Maximum length of entire buffer.
* @return Number of bytes written.
*/
native strcat(dest[], const source[], maxlength);
/**
* Tests whether a string is found inside another string.
*
* @note This supports multi-byte characters (UTF-8) on case insensitive comparison.
*
* @param string String to search in.
* @param sub Substring to find inside the original string.
* @param ignorecase If true, search is case insensitive.
* If false (default), search is case sensitive.
* @param pos Start position to search from.
* @return -1 on failure (no match found). Any other value
* indicates a position in the string where the match starts.
*/
native strfind(const string[], const sub[], bool:ignorecase = false, pos = 0);
/**
* Compares two strings lexographically.
*
* @note This supports multi-byte characters (UTF-8) on case insensitive comparison.
*
* @param string1 First string (left).
* @param string2 Second string (right).
* @param ignorecase If true, comparison is case insensitive.
* If false (default), comparison is case sensitive.
* @return -1 if string1 < string2
* 0 if string1 == string2
* 1 if string1 > string2
*/
native strcmp(const string1[], const string2[], bool:ignorecase = false);
/**
* Compares two strings parts lexographically.
*
* @note Only available in 1.8.3 and above.
* @note This supports multi-byte characters (UTF-8) on case insensitive comparison.
*
* @param string1 First string (left).
* @param string2 Second string (right).
* @param num Number of characters to compare.
* @param ignorecase If true, comparison is case insensitive.
* If false (default), comparison is case sensitive.
* @return -1 if string1 < string2
* 0 if string1 == string2
* 1 if string1 > string2
*/
native strncmp(const string1[], const string2[], num, bool:ignorecase = false);
/**
* Parses an argument string to find the first argument. You can use this to
* replace strbreak().
*
* @note Only available in 1.8.3 and above.
*
* @note You can use argparse() to break a string into all of its arguments:
* new arg[N], pos;
* while (true) {
* pos = argparse(string, pos, arg, sizeof(arg) - 1);
* if (pos == -1)
* break;
* }
*
* @note All initial whitespace is removed. Remaining characters are read until an
* argument separator is encountered. A separator is any whitespace not inside
* a double-quotation pair (i.e. "x b" is one argument). If only one quotation
* mark appears, argparse() acts as if one existed at the end of the string.
* Quotation marks are never written back, and do not act as separators. For
* example, "a""b""c" will return "abc". An empty quote pair ("") will count
* as an argument containing no characters.
*
* @note argparse() will write an empty string to argbuffer if no argument is found.
*
* @param text String to tokenize.
* @param pos Position to start parsing from.
* @param argbuffer Buffer to store first argument.
* @param maxlen Size of the buffer.
* @return If no argument was found, -1 is returned. Otherwise,
* the index to the next position to parse from is
* returned. This might be the very end of the string.
*/
native argparse(const text[], pos, argbuffer[], maxlen);
/**
* Returns text in a string up until a certain character sequence is reached.
*
* @note Only available in 1.8.3 and above.
*
* @param source Source input string.
* @param split A string which specifies a search point to break at.
* @param part Buffer to store string part.
* @param partLen Maximum length of the string part buffer.
*
* @return -1 if no match was found; otherwise, an index into source
* marking the first index after the searched text. The
* index is always relative to the start of the input string.
*/
native split_string(const source[], const split[], part[], partLen);
// Always keep this at the bottom of this file.
#include <string_stocks>

View File

@ -0,0 +1,156 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// String Manipulation Constants
//
#if defined _string_const_included
#endinput
#endif
#define _string_const_included
#define charsmax(%1) (sizeof(%1)-1)
/**
* @global Unless otherwise noted, all string functions which take in a
* writable buffer and maximum length should NOT have the null terminator INCLUDED
* in the length. This means that this is valid:
* copy(string, charsmax(string), ...)
*/
/**
* Buffer size used by fmt().
*/
#define MAX_FMT_LENGTH 256
/**
* Below are the trim flags for strtok2
*
* You can specify how the left and right buffers will
* be trimmed by strtok2. LTRIM trims spaces from the
* left side. RTRIM trims from the right side.
*
* The defines TRIM_INNER, TRIM_OUTER and TRIM_FULL are
* shorthands for commonly used flag combinations.
*
* When the initial string is trimmed, using TRIM_INNER
* for all subsequent strtok2 calls will ensure that left
* and right are always trimmed from both sides.
*
* Examples:
* str1[] = " This is * some text "
* strtok2(str1, left, 24, right, 24, '*', TRIM_FULL)
* left will be "This is", right will be "some text"
*
* str2[] = " Here is | an | example "
* trim(str2)
* strtok2(str2, left, 24, right, 24, '|', TRIM_INNER)
* left will be "Here is", right will be "an | example"
* strtok2(right, left, 24, right, 24, '|', TRIM_INNER)
* left will be "an", right will be "example"
*
* str3[] = " One - more "
* strtok2(str3, left, 24, right, 24, '-', TRIM_OUTER)
* left will be "One ", right will be " more"
*
* str4[] = " Final . example "
* strtok2(str4, left, 24, right, 24, '.', LTRIM_LEFT|LTRIM_RIGHT)
* left will be "Final ", right will be "example "
*/
#define LTRIM_LEFT (1<<0)
#define RTRIM_LEFT (1<<1)
#define LTRIM_RIGHT (1<<2)
#define RTRIM_RIGHT (1<<3)
#define TRIM_INNER RTRIM_LEFT|LTRIM_RIGHT
#define TRIM_OUTER LTRIM_LEFT|RTRIM_RIGHT
#define TRIM_FULL TRIM_OUTER|TRIM_INNER
/**
* Category flags to be used with is_string_category(), to check whether code points in a
* string are part of that category.
*/
#define UTF8C_LETTER_UPPERCASE 0x00000001 // Uppercase letter code points, Lu in the Unicode database.
#define UTF8C_LETTER_LOWERCASE 0x00000002 // Lowercase letter code points, Ll in the Unicode database.
#define UTF8C_LETTER_TITLECASE 0x00000004 // Titlecase letter code points, Lt in the Unicode database.
#define UTF8C_LETTER_MODIFIER 0x00000008 // Modifier letter code points, Lm in the Unicode database.
#define UTF8C_LETTER_OTHER 0x00000010 // Other letter code points, Lo in the Unicode database.
// Combined flag for all letter categories with case mapping
// Combined flag for all letter categories
const UTF8C_LETTER = (UTF8C_LETTER_UPPERCASE | UTF8C_LETTER_LOWERCASE | UTF8C_LETTER_TITLECASE | UTF8C_LETTER_MODIFIER | UTF8C_LETTER_OTHER);
const UTF8C_CASE_MAPPED = (UTF8C_LETTER_UPPERCASE | UTF8C_LETTER_LOWERCASE | UTF8C_LETTER_TITLECASE);
#define UTF8C_MARK_NON_SPACING 0x00000020 // Non-spacing mark code points, Mn in the Unicode database.
#define UTF8C_MARK_SPACING 0x00000040 // Spacing mark code points, Mc in the Unicode database.
#define UTF8C_MARK_ENCLOSING 0x00000080 // Enclosing mark code points, Me in the Unicode database.
// Combined flag for all mark categories.
const UTF8C_MARK = (UTF8C_MARK_NON_SPACING | UTF8C_MARK_SPACING | UTF8C_MARK_ENCLOSING);
#define UTF8C_NUMBER_DECIMAL 0x00000100 // Decimal number code points, Nd in the Unicode database.
#define UTF8C_NUMBER_LETTER 0x00000200 // Letter number code points, Nl in the Unicode database.
#define UTF8C_NUMBER_OTHER 0x00000400 // Other number code points, No in the Unicode database.
// Combined flag for all number categories.
const UTF8C_NUMBER = (UTF8C_NUMBER_DECIMAL | UTF8C_NUMBER_LETTER | UTF8C_NUMBER_OTHER);
#define UTF8C_PUNCTUATION_CONNECTOR 0x00000800 // Connector punctuation category, Pc in the Unicode database.
#define UTF8C_PUNCTUATION_DASH 0x00001000 // Dash punctuation category, Pd in the Unicode database.
#define UTF8C_PUNCTUATION_OPEN 0x00002000 // Open punctuation category, Ps in the Unicode database.
#define UTF8C_PUNCTUATION_CLOSE 0x00004000 // Close punctuation category, Pe in the Unicode database.
#define UTF8C_PUNCTUATION_INITIAL 0x00008000 // Initial punctuation category, Pi in the Unicode database.
#define UTF8C_PUNCTUATION_FINAL 0x00010000 // Final punctuation category, Pf in the Unicode database.
#define UTF8C_PUNCTUATION_OTHER 0x00020000 // Other punctuation category, Po in the Unicode database.
// Combined flag for all punctuation categories.
const UTF8C_PUNCTUATION = (UTF8C_PUNCTUATION_CONNECTOR | UTF8C_PUNCTUATION_DASH | UTF8C_PUNCTUATION_OPEN | \
UTF8C_PUNCTUATION_CLOSE | UTF8C_PUNCTUATION_INITIAL | UTF8C_PUNCTUATION_FINAL | \
UTF8C_PUNCTUATION_OTHER);
#define UTF8C_SYMBOL_MATH 0x00040000 // Math symbol category, Sm in the Unicode database.
#define UTF8C_SYMBOL_CURRENCY 0x00080000 // Currency symbol category, Sc in the Unicode database.
#define UTF8C_SYMBOL_MODIFIER 0x00100000 // Modifier symbol category, Sk in the Unicode database.
#define UTF8C_SYMBOL_OTHER 0x00200000 // Other symbol category, So in the Unicode database.
// Combined flag for all symbol categories.
const UTF8C_SYMBOL = (UTF8C_SYMBOL_MATH | UTF8C_SYMBOL_CURRENCY | UTF8C_SYMBOL_MODIFIER | UTF8C_SYMBOL_OTHER);
#define UTF8C_SEPARATOR_SPACE 0x00400000 // Space separator category, Zs in the Unicode database.
#define UTF8C_SEPARATOR_LINE 0x00800000 // Line separator category, Zl in the Unicode database.
#define UTF8C_SEPARATOR_PARAGRAPH 0x01000000 // Paragraph separator category, Zp in the Unicode database.
// Combined flag for all separator categories.
const UTF8C_SEPARATOR = (UTF8C_SEPARATOR_SPACE | UTF8C_SEPARATOR_LINE | UTF8C_SEPARATOR_PARAGRAPH);
#define UTF8C_CONTROL 0x02000000 // Control category, Cc in the Unicode database.
#define UTF8C_FORMAT 0x04000000 // Format category, Cf in the Unicode database.
#define UTF8C_SURROGATE 0x08000000 // Surrogate category, Cs in the Unicode database.
#define UTF8C_PRIVATE_USE 0x10000000 // Private use category, Co in the Unicode database.
#define UTF8C_UNASSIGNED 0x20000000 // Unassigned category, Cn in the Unicode database.
#define UTF8C_COMPATIBILITY 0x40000000 // Flag used for maintaining backwards compatibility with POSIX
#define UTF8C_IGNORE_GRAPHEME_CLUSTER 0x80000000 // Flag used for checking only the general category of code points at the start of a grapheme cluster.
// Flag used for maintaining backwards compatibility with POSIX function
const UTF8C_ISCNTRL = (UTF8C_COMPATIBILITY | UTF8C_CONTROL);
const UTF8C_ISPRINT = (UTF8C_COMPATIBILITY | UTF8C_LETTER | UTF8C_NUMBER | UTF8C_PUNCTUATION | UTF8C_SYMBOL | UTF8C_SEPARATOR);
const UTF8C_ISSPACE = (UTF8C_COMPATIBILITY | UTF8C_SEPARATOR_SPACE);
const UTF8C_ISBLANK = (UTF8C_COMPATIBILITY | UTF8C_SEPARATOR_SPACE | UTF8C_PRIVATE_USE);
const UTF8C_ISGRAPH = (UTF8C_COMPATIBILITY | UTF8C_LETTER | UTF8C_NUMBER | UTF8C_PUNCTUATION | UTF8C_SYMBOL);
const UTF8C_ISPUNCT = (UTF8C_COMPATIBILITY | UTF8C_PUNCTUATION | UTF8C_SYMBOL);
const UTF8C_ISALNUM = (UTF8C_COMPATIBILITY | UTF8C_LETTER | UTF8C_NUMBER);
const UTF8C_ISALPHA = (UTF8C_COMPATIBILITY | UTF8C_LETTER);
const UTF8C_ISUPPER = (UTF8C_COMPATIBILITY | UTF8C_LETTER_UPPERCASE);
const UTF8C_ISLOWER = (UTF8C_COMPATIBILITY | UTF8C_LETTER_LOWERCASE);
const UTF8C_ISDIGIT = (UTF8C_COMPATIBILITY | UTF8C_NUMBER);
const UTF8C_ISXDIGIT = (UTF8C_COMPATIBILITY | UTF8C_NUMBER | UTF8C_PRIVATE_USE);
// All flags.
const UTF8C_ALL = 0xFFFFFFFF & (~UTF8C_COMPATIBILITY);

View File

@ -0,0 +1,325 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// String Manipulation Stocks
//
#if defined _string_stocks_included
#endinput
#endif
#define _string_stocks_included
#if !defined _string_included
#include <string>
#endif
/**
* @global Unless otherwise noted, all string functions which take in a
* writable buffer and maximum length should NOT have the null terminator INCLUDED
* in the length. This means that this is valid:
* copy(string, charsmax(string), ...)
*/
/**
* Returns whether a given string contains only digits.
* This returns false for zero-length strings.
*
* @param sString Character to test.
* @return True if string contains only digit, otherwise false.
*/
stock bool:is_str_num(const sString[])
{
new i = 0;
while (sString[i] && isdigit(sString[i]))
{
++i;
}
return sString[i] == 0 && i != 0;
}
/**
* Returns an uppercase character to a lowercase character.
*
* @note Only available in 1.8.3 and above.
*
* @param chr Characer to convert.
* @return Lowercase character on success,
* no change on failure.
*/
stock char_to_upper(chr)
{
if (is_char_lower(chr))
{
return (chr & ~(1<<5));
}
return chr;
}
/**
* Returns a lowercase character to an uppercase character.
*
* @note Only available in 1.8.3 and above.
*
* @param chr Characer to convert.
* @return Uppercase character on success,
* no change on failure.
*/
stock char_to_lower(chr)
{
if (is_char_upper(chr))
{
return (chr | (1<<5));
}
return chr;
}
/**
* Backwards compatibility stock - use argbreak or argparse.
* @deprecated this function does not work properly.
*/
#pragma deprecated Use argbreak() instead
stock strbreak(const text[], Left[], leftLen, Right[], rightLen)
{
return argbreak(text, Left, leftLen, Right, rightLen);
}
/**
* Emulates strbreak() using argparse().
*
* @param text Source input string.
* @param left Buffer to store string left part.
* @param leftlen Maximum length of the string part buffer.
* @param right Buffer to store string right part.
* @param rightlen Maximum length of the string part buffer.
*
* @return -1 if no match was found; otherwise, an index into source
* marking the first index after the searched text. The
* index is always relative to the start of the input string.
*/
stock argbreak(const text[], left[], leftlen, right[], rightlen)
{
new pos = argparse(text, 0, left, leftlen);
if (pos == -1)
{
return -1;
}
new textlen = strlen(text);
while (pos < textlen && isspace(text[pos]))
{
pos++;
}
copy(right, rightlen, text[pos]);
return pos;
}
/**
* It is basically strbreak but you have a delimiter that is more than one character in length. By Suicid3.
*
* @param szInput Source input string.
* @param szLeft Buffer to store left string part.
* @param pL_Max Maximum length of the string part buffer.
* @param szRight Buffer to store right string part.
* @param pR_Max Maximum length of the string part buffer.
* @param szDelim A string which specifies a search point to break at.
*
* @noreturn
*/
stock split(const szInput[], szLeft[], pL_Max, szRight[], pR_Max, const szDelim[])
{
new iEnd = contain(szInput, szDelim);
new iStart = iEnd + strlen(szDelim);
// If delimiter isnt in Input just split the string at max lengths
if (iEnd == -1)
{
iStart = copy(szLeft, pL_Max, szInput);
copy(szRight, pR_Max, szInput[iStart]);
return;
}
// If delimter is in Input then split at input for max lengths
if (pL_Max >= iEnd)
copy(szLeft, iEnd, szInput);
else
copy(szLeft, pL_Max, szInput);
copy(szRight, pR_Max, szInput[iStart]);
}
/**
* Removes a path from szFilePath leaving the name of the file in szFile for a pMax length.
*
* @param szFilePath String to perform search and replacements on.
* @param szFile Buffer to store file name.
* @param pMax Maximum length of the string buffer.
*
* @noreturn
*/
stock remove_filepath(const szFilePath[], szFile[], pMax)
{
new len = strlen(szFilePath);
while ((--len >= 0) && (szFilePath[len] != '/') && (szFilePath[len] != '\')) { }
copy(szFile, pMax, szFilePath[len + 1]);
return;
}
/**
* Replaces a contained string iteratively.
*
* @note Consider using replace_string() instead.
*
* @note This ensures that no infinite replacements will take place by
* intelligently moving to the next string position each iteration.
*
* @param string String to perform search and replacements on.
* @param len Maximum length of the string buffer.
* @param what String to search for.
* @param with String to replace the search string with.
*
* @return Number of replacements on success, otherwise 0.
*/
stock replace_all(string[], len, const what[], const with[])
{
new pos = 0;
if ((pos = contain(string, what)) == -1)
{
return 0;
}
new total = 0;
new with_len = strlen(with);
new diff = strlen(what) - with_len;
new total_len = strlen(string);
new temp_pos = 0;
while (replace(string[pos], len - pos, what, with) != 0)
{
total++;
/* jump to position after replacement */
pos += with_len;
/* update cached length of string */
total_len -= diff;
/* will the next call be operating on the last character? */
if (pos >= total_len)
{
break;
}
/* find the next position from our offset */
temp_pos = contain(string[pos], what);
/* if it's invalid, we're done */
if (temp_pos == -1)
{
break;
}
/* otherwise, reposition and update counters */
pos += temp_pos;
}
return total;
}
/**
* Breaks a string into pieces and stores each piece into an array of buffers.
*
* @param text The string to split.
* @param split The string to use as a split delimiter.
* @param buffers An array of string buffers (2D array).
* @param maxStrings Number of string buffers (first dimension size).
* @param maxStringLength Maximum length of each string buffer.
* @param copyRemainder False (default) discard excess pieces, true to ignore
* delimiters after last piece.
* @return Number of strings retrieved.
*/
stock explode_string(const text[], const split[], buffers[][], maxStrings, maxStringLength, bool:copyRemainder = false)
{
new reloc_idx, idx, total;
if (maxStrings < 1 || !split[0])
{
return 0;
}
while ((idx = split_string(text[reloc_idx], split, buffers[total], maxStringLength)) != -1)
{
reloc_idx += idx;
if (++total == maxStrings)
{
if (copyRemainder)
{
copy(buffers[total-1], maxStringLength, text[reloc_idx-idx]);
}
return total;
}
}
copy(buffers[total++], maxStringLength, text[reloc_idx]);
return total;
}
/**
* Joins an array of strings into one string, with a "join" string inserted in
* between each given string. This function complements ExplodeString.
*
* @param strings An array of strings.
* @param numStrings Number of strings in the array.
* @param join The join string to insert between each string.
* @param buffer Output buffer to write the joined string to.
* @param maxLength Maximum length of the output buffer.
* @return Number of bytes written to the output buffer.
*/
stock implode_strings(const strings[][], numStrings, const join[], buffer[], maxLength)
{
new total, length, part_length;
new join_length = strlen(join);
for (new i=0; i<numStrings; i++)
{
length = copy(buffer[total], maxLength-total, strings[i]);
total += length;
if (length < part_length)
{
break;
}
if (i != numStrings - 1)
{
length = copy(buffer[total], maxLength-total, join);
total += length;
if (length < join_length)
{
break;
}
}
}
return total;
}

View File

@ -0,0 +1,214 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// INI Parser Functions
//
#if defined _textparse_ini_included
#endinput
#endif
#define _textparse_ini_included
/**
* This parser API is entirely event based.
* You must hook events to receive data.
*/
/**
* The INI file format is defined as:
* WHITESPACE: 0x20, \n, \t, \r
* IDENTIFIER: A-Z a-z 0-9 _ - , + . $ ? /
* STRING : Any set of symbols
*
* Basic syntax is comprised of SECTIONs.
* A SECTION is defined as:
* [SECTIONNAME]
* OPTION
* OPTION
* OPTION...
*
* SECTIONNAME is an IDENTIFIER.
* OPTION can be repeated any number of times, once per line.
* OPTION is defined as one of:
* KEY = "VALUE"
* KEY = VALUE
* KEY
* Where KEY is an IDENTIFIER and VALUE is a STRING.
*
* WHITESPACE should always be omitted.
* COMMENTS should be stripped, and are defined as text occurring in:
* ;<TEXT>
*
* Example file below. Note that the second line is technically invalid.
* The event handler must decide whether this should be allowed.
* --FILE BELOW--
* [gaben]
* hi = clams
* bye = "NO CLAMS"
*
* [valve]
* cannot
* maintain
* products
*/
/**
* Parser invalid code.
*/
enum INIParser
{
Invalid_INIParser = 0
};
/**
* Creates a new INI parser.
* This is used to set parse hooks.
*
* @return A new handle to an INI Parse structure.
*/
native INIParser:INI_CreateParser();
/**
* Disposes of an INI parser.
*
* @param handle Handle to an INI Parse structure.
*
* @return True if disposed, false otherwise.
*/
native INI_DestroyParser(&INIParser:handle);
/**
* Parses an INI config file.
*
* @param handle A handle to an INI Parse structure.
* @param file A string containing the file path.
* @param line An optional by reference cell to store the last line number read.
* @param col An optional by reference cell to store the last column number read.
* @param data An optional handle or value to pass through to callback functions
*
* @return An SMCParseError result.
* @error Invalid or corrupt handle.
*/
native bool:INI_ParseFile(INIParser:handle, const file[], &line = 0, &col = 0, any:data = 0);
/**
* Sets the INI_ParseStart function of a parse handle.
*
* @note Below is the prototype of callback:
* -
* Called when parsing is started.
*
* @param handle A handle to an INI Parse structure.
* @param data Handle or value passed in INI_ParseFile
*
* @noreturn
*
* public OnParseStart(INIParser:handle, any:data)
* -
* @param handle Handle to an INI Parse structure.
* @param func A ParseStart callback.
*
* @noreturn
* @error Invalid or corrupt handle.
*/
native INI_SetParseStart(INIParser:handle, const func[]);
/**
* Sets the INI_ParseEnd function of a parse handle.
*
* @note Below is the prototype of callback:
* -
* Called when parsing is halted.
*
* @param handle A handle to an INI Parse structure.
* @param halted True if abnormally halted, false otherwise.
* @param data Handle or value passed in INI_ParseFile
*
* @noreturn
*
* public OnParseEnd(INIParser:handle, bool:halted, any:data)
* -
* @param handle Handle to an INI Parse structure.
* @param func A ParseEnd callback.
*
* @noreturn
* @error Invalid or corrupt handle.
*/
native INI_SetParseEnd(INIParser:handle, const func[]);
/**
* Sets the two main reader functions.
*
* @note Below is the prototype of callback:
* -
* NewSection:
* Called when the parser finds a new section.
*
* @param handle Handle to an INI Parse structure.
* @param section Name of section in between the [ and ] characters.
* @param invalid_tokens True if invalid tokens were detected in the name.
* @param close_bracket True if a closing bracket was detected, false otherwise.
* @param extra_tokens True if extra tokens were detected on the line.
* @param curtok Contains current token in the line where the section name starts.
* You can add to this offset when failing to point to a token.
* @param data Handle or value passed in INI_ParseFile
*
* @return True to keep parsing, false otherwise.
*
* public bool:OnNewSection(INIParser:handle, const section[], bool:invalid_tokens, bool:close_bracket, bool:extra_tokens, curtok, any:data)
*
* KeyValue:
* Called when the parser finds a new key/value pair.
*
* @param handle Handle to an INI Parse structure.
* @param key Name of key.
* @param value String containing value (with quotes stripped, if any).
* @param invalid_tokens Whether or not the key contained invalid tokens.
* @param equal_token There was an '=' sign present (in case the value is missing).
* @param quotes Whether value was enclosed in quotes.
* @param curtok Contains the token index of the start of the value string.
* This can be changed when returning false.
* @param data Handle or value passed in INI_ParseFile
*
* @return True to keep parsing, false otherwise.
*
* public bool:OnKeyValue(INIParser:handle, const key[], const value[], bool:invalid_tokens, bool:equal_token, bool:quotes, curtok, any:data)
* -
* @param handle Handle to an INI Parse structure.
* @param kv A KeyValue callback.
* @param ns An optional NewSection callback.
*
* @noreturn
*/
native INI_SetReaders(INIParser:smc, const kvFunc[], const nsFunc[] = "" );
/**
* Sets a raw line reader on an INI parser handle.
*
* @note Below is the prototype of callback:
* -
* Called whenever a raw line is read.
*
* @param handle The INI Parse handle.
* @param line Contents of line.
* @param lineno The line number it occurs on.
* @param curtok Pointer to optionally store failed position in string.
* @param data Handle or value passed in INI_ParseFile
*
* @return True to keep parsing, false otherwise.
*
* public bool:OnRawLine(INIParser:smc, const line[], lineno, curtok, any:data)
*
* @param handle Handle to an INI Parse structure.
* @param func A RawLine callback.
*
* @noreturn
*/
native INI_SetRawLine(INIParser:handle, const func[]);

View File

@ -0,0 +1,261 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// SMC Parser Functions
//
#if defined _textparse_smc_included
#endinput
#endif
#define _textparse_smc_included
/**
* Everything below describes the SMC Parse, or "SourceMod Configuration" format.
* This parser is entirely event based. You must hook events to receive data.
* The file format itself is nearly identical to Valve's KeyValues format (also known as VDF).
*/
/**
* The SMC file format is defined as:
* WHITESPACE: 0x20, \n, \t, \r
* IDENTIFIER: Any ASCII character EXCLUDING ", {, }, ;, //, / *, or WHITESPACE.
* STRING : Any set of symbols enclosed in quotes.
*
* Note: if a STRING does not have quotes, it is parsed as an IDENTIFIER.
*
* Basic syntax is comprised of SECTIONBLOCKs.
* A SECTIONBLOCK defined as:
*
* SECTIONNAME
* {
* OPTION
* }
*
* OPTION can be repeated any number of times inside a SECTIONBLOCK.
* A new line will terminate an OPTION, but there can be more than one OPTION per line.
* OPTION is defined any of:
* "KEY" "VALUE"
* SECTIONBLOCK
*
* SECTIONNAME, KEY, VALUE, and SINGLEKEY are strings
* SECTIONNAME cannot have trailing characters if quoted, but the quotes can be optionally removed.
* If SECTIONNAME is not enclosed in quotes, the entire sectionname string is used (minus surrounding whitespace).
* If KEY is not enclosed in quotes, the key is terminated at first whitespace.
* If VALUE is not properly enclosed in quotes, the entire value string is used (minus surrounding whitespace).
* The VALUE may have inner quotes, but the key string may not.
*
* For an example, see scripting/testsuite/textparse_test.cfg
*
* WHITESPACE should be ignored.
* Comments are text occurring inside the following tokens, and should be stripped
* unless they are inside literal strings:
* ;<TEXT>
* //<TEXT>
* / *<TEXT> * /
*/
/**
* Parser invalid code.
*/
enum SMCParser
{
Invalid_SMCParser = 0
};
/**
* Parse result directive.
*/
enum SMCResult
{
SMCParse_Continue, /* Continue parsing */
SMCParse_Halt, /* Stop parsing here */
SMCParse_HaltFail /* Stop parsing and return failure */
};
/**
* Parse error codes.
*/
enum SMCError
{
SMCError_Okay = 0, /* No error */
SMCError_StreamOpen, /* Stream failed to open */
SMCError_StreamError, /* The stream died... somehow */
SMCError_Custom, /* A custom handler threw an error */
SMCError_InvalidSection1, /* A section was declared without quotes, and had extra tokens */
SMCError_InvalidSection2, /* A section was declared without any header */
SMCError_InvalidSection3, /* A section ending was declared with too many unknown tokens */
SMCError_InvalidSection4, /* A section ending has no matching beginning */
SMCError_InvalidSection5, /* A section beginning has no matching ending */
SMCError_InvalidTokens, /* There were too many unidentifiable strings on one line */
SMCError_TokenOverflow, /* The token buffer overflowed */
SMCError_InvalidProperty1, /* A property was declared outside of any section */
};
/**
* Creates a new SMC parser.
* This is used to set parse hooks.
*
* @return A new handle to an SMC Parse structure.
*/
native SMCParser:SMC_CreateParser();
/**
* Disposes of an SMC parser.
*
* @param handle Handle to an SMC Parse structure.
*
* @return True if disposed, false otherwise.
*/
native SMC_DestroyParser(&SMCParser:handle);
/**
* Parses a config file.
*
* @param handle A handle to an SMC Parse structure.
* @param file A string containing the file path.
* @param line An optional by reference cell to store the last line number read.
* @param col An optional by reference cell to store the last column number read.
* @param data An optional handle or value to pass through to callback functions
*
* @return An SMCParseError result.
* @error Invalid or corrupt handle.
*/
native SMCError:SMC_ParseFile(SMCParser:handle, const file[], &line = 0, &col = 0, any:data = 0);
/**
* Sets the SMC_ParseStart function of a parse handle.
*
* @note Below is the prototype of callback:
* -
* Called when parsing is started.
*
* @param handle Handle to an SMC Parse structure.
* @param data Handle or value passed in SMC_ParseFile
*
* @noreturn
*
* public OnParseStart(SMCParser:handle, any:data)
* -
* @param handle Handle to an SMC Parse structure.
* @param func A ParseStart callback.
*
* @noreturn
* @error Invalid or corrupt handle.
*/
native SMC_SetParseStart(SMCParser:handle, const func[]);
/**
* Sets the SMC_ParseEnd function of a parse handle.
*
* @note Below is the prototype of callback:
* -
* Called when parsing is halted.
*
* @param handle Handle to an SMC Parse structure.
* @param halted True if abnormally halted, false otherwise.
* @param failed True if parsing failed, false otherwise.
* @param data Handle or value passed in SMC_ParseFile
*
* @noreturn
*
* public OnParseEnd(SMCParser:handle, bool:halted, bool:failed, any:data)
* -
* @param handle Handle to an SMC Parse structure.
* @param func A ParseEnd callback.
*
* @noreturn
* @error Invalid or corrupt handle.
*/
native SMC_SetParseEnd(SMCParser:handle, const func[]);
/**
* Sets the three main reader functions.
*
* @note Enclosing quotes are always stripped.
* @note Below is the prototype of callbacks:
* -
* NewSection:
* Called when the parser finds a new section or sub-section.
*
* @param handle Handle to an SMC Parse structure.
* @param name String containing section name.
* @param data Handle or value passed in SMC_ParseFile
*
* @return An SMCResult action to take.
*
* public SMCResult:OnNewSection(SMCParser:handle, const name[], any:data)
*
* KeyValue:
* Called when the parser finds a new key/value pair.
*
* @param handle Handle to an SMC Parse structure.
* @param key String containing key name.
* @param value String containing value name.
* @param data Handle or value passed in SMC_ParseFile
*
* @return An SMCResult action to take.
*
* public SMCResult:OnKeyValue(SMCParser:handle, const key[], const value[], any:data)
*
* EndSection:
* Called when the parser finds the end of the current section.
*
* @param handle Handle to an SMC Parse structure.
* @param data Handle or value passed in SMC_ParseFile
*
* @return An SMCResult action to take.
*
* public SMCResult:OnEndSection(SMCParser:handle, any:data)
* -
* @param handle Handle to an SMC Parse structure.
* @param kv A KeyValue callback.
* @param ns An optional NewSection callback.
* @param es An optional EndSection callback.
*
* @noreturn
*/
native SMC_SetReaders(SMCParser:smc, const kvFunc[], const nsFunc[] = "", const esFunc[] = "");
/**
* Sets a raw line reader on an text parser handle.
*
* @note Below is the prototype of callbacks:
* -
* Called whenever a raw line is read.
*
* @param handle Handle to an SMC Parse structure.
* @param line A string containing the raw line from the file.
* @param lineno The line number it occurs on.
* @param data Handle or value passed in SMC_ParseFile
*
* @return An SMCResult action to take.
*
* public SMCResult:SMC_RawLine(SMCParser:handle, const line[], lineno, any:data)
* -
* @param handle Handle to an SMC Parse structure.
* @param func A RawLine callback.
*
* @noreturn
*/
native SMC_SetRawLine(SMCParser:handle, const func[]);
/**
* Gets an error string for an SMCError code.
*
* @note SMCError_Okay returns false.
* @note SMCError_Custom (which is thrown on SMCParse_HaltFail) returns false.
*
* @param error The SMCParseError code.
* @param buffer A string buffer for the error (contents undefined on failure).
* @param buf_max The maximum size of the buffer.
*
* @return True on success, false otherwise.
*/
native bool:SMC_GetErrorString(SMCError:error, buffer[], buf_max);

View File

@ -0,0 +1,84 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// TFCX Constants
//
#if defined _tfcconst_included
#endinput
#endif
#define _tfcconst_included
#define TFCMAX_WEAPONS 37
enum {
TFC_AMMO_SHELLS = 0,
TFC_AMMO_BULLETS,
TFC_AMMO_CELLS,
TFC_AMMO_ROCKETS,
TFC_AMMO_NADE1,
TFC_AMMO_NADE2,
};
enum {
TFC_WPN_NONE = 0,
TFC_WPN_TIMER,//TFC_WPN_UNK1,
TFC_WPN_SENTRYGUN,//TFC_WPN_UNK2,
TFC_WPN_MEDIKIT,
TFC_WPN_SPANNER,
TFC_WPN_AXE,
TFC_WPN_SNIPERRIFLE,
TFC_WPN_AUTORIFLE,
TFC_WPN_SHOTGUN,
TFC_WPN_SUPERSHOTGUN,
TFC_WPN_NG,
TFC_WPN_SUPERNG,
TFC_WPN_GL,
TFC_WPN_FLAMETHROWER,
TFC_WPN_RPG,
TFC_WPN_IC,
TFC_WPN_FLAMES,//TFC_WPN_UNK16,
TFC_WPN_AC,
TFC_WPN_UNK18,
TFC_WPN_UNK19,
TFC_WPN_TRANQ,
TFC_WPN_RAILGUN,
TFC_WPN_PL,
TFC_WPN_KNIFE,
TFC_WPN_CALTROP, // 24
TFC_WPN_CONCUSSIONGRENADE,
TFC_WPN_NORMALGRENADE,
TFC_WPN_NAILGRENADE,
TFC_WPN_MIRVGRENADE,
TFC_WPN_NAPALMGRENADE,
TFC_WPN_GASGRENADE,
TFC_WPN_EMPGRENADE,
};
enum {
TFC_PC_SCOUT = 1,
TFC_PC_SNIPER,
TFC_PC_SOLDIER,
TFC_PC_DEMOMAN,
TFC_PC_MEDIC,
TFC_PC_HWGUY,
TFC_PC_PYRO,
TFC_PC_SPY,
TFC_PC_ENGENEER, // Typo; preserved for backward compatibility
TFC_PC_ENGINEER = 9,
TFC_PC_CIVILIAN = 11,
};
// Goal items
#define TFC_GOALITEM_BLUE (1 << 17)
#define TFC_GOALITEM_RED (1 << 18)
#define TFC_GOALITEM_YELLOW (1 << 24)
#define TFC_GOALITEM_GREEN (1 << 25)

View File

@ -0,0 +1,62 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// TFCX Stats Functions
//
#if defined _tfcstats_included
#endinput
#endif
#define _tfcstats_included
/* Gets stats from given weapon index. If wpnindex is 0
* then the stats are from all weapons. If weapon has not been used function
* returns 0 in other case 1. Fields in stats are:
* 0 - kills
* 1 - deaths
* 2 - headshots
* 3 - teamkilling
* 4 - shots
* 5 - hits
* 6 - damage
* For body hits fields see amxconst.inc. */
native get_user_wstats(index,wpnindex,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets round stats from given weapon index.*/
native get_user_wrstats(index,wpnindex,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets overall stats which are stored in file on server
* and updated on every respawn or user disconnect.
* Function returns the position in stats by diff. kills to deaths. */
native get_user_stats(index,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets round stats of player. */
native get_user_rstats(index,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets stats with which user have killed/hurt his victim. If victim is 0
* then stats are from all victims. If victim has not been hurt, function
* returns 0 in other case 1. User stats are reset on his respawn. */
native get_user_vstats(index,victim,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS],wpnname[]="",len=0);
/* Gets stats with which user have been killed/hurt. If killer is 0
* then stats are from all attacks. If killer has not hurt user, function
* returns 0 in other case 1. User stats are reset on his respawn. */
native get_user_astats(index,wpnindex,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS],wpnname[]="",len=0);
/* Resets life, weapon, victims and attackers user stats. */
native reset_user_wstats(index);
/* Gets overall stats which stored in stats.dat file in amx folder
* and updated on every mapchange or user disconnect.
* Function returns next index of stats entry or 0 if no more exists. */
native get_stats(index,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS],name[],len);
/* Returns number of all entries in stats. */
native get_statsnum();

View File

@ -0,0 +1,148 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// TFCX Functions
//
#if defined _tfcx_included
#endinput
#endif
#define _tfcx_included
#include <tfcconst>
#include <tfcstats>
#pragma reqclass xstats
#if !defined AMXMODX_NOAUTOLOAD
#pragma defclasslib xstats tfcx
#endif
/************* Shared Natives Start ********************************/
/* Forward types */
enum {
XMF_DAMAGE = 0,
XMF_DEATH,
};
/* Use this function to register forwards */
native register_statsfwd( ftype );
/* Function is called after player to player attacks ,
* if players were damaged by teammate TA is set to 1 */
forward client_damage(attacker,victim,damage,wpnindex,hitplace,TA);
/* Function is called after player death ,
* if player was killed by teammate TK is set to 1 */
forward client_death(killer,victim,wpnindex,hitplace,TK);
/* Custom Weapon Support */
/* function will return index of new weapon */
native custom_weapon_add( const wpnname[],melee = 0,const logname[]="" );
/* Function will pass damage done by this custom weapon to stats module and other plugins */
native custom_weapon_dmg( weapon, att, vic, damage, hitplace=0 );
/* Function will pass info about custom weapon shot to stats module */
native custom_weapon_shot( weapon,index ); // weapon id , player id
/* function will return 1 if true */
native xmod_is_melee_wpn(wpnindex);
/* Returns weapon name. */
native xmod_get_wpnname(wpnindex,name[],len);
/* Returns weapon logname. */
native xmod_get_wpnlogname(wpnindex,name[],len);
/* Returns weapons array size */
native xmod_get_maxweapons();
/* Returns stats array size ex. 8 in TS , 9 in DoD */
native xmod_get_stats_size();
/* Returns 1 if true */
native xmod_is_custom_wpn(wpnindex);
/************* Shared Natives End ********************************/
stock tfc_isgrenade( weapon ){
switch( weapon )
{
case TFC_WPN_CALTROP,
TFC_WPN_CONCUSSIONGRENADE,
TFC_WPN_NORMALGRENADE,
TFC_WPN_NAILGRENADE,
TFC_WPN_MIRVGRENADE,
TFC_WPN_NAPALMGRENADE,
TFC_WPN_GASGRENADE,
TFC_WPN_EMPGRENADE:
return 1;
default: return 0;
}
return 0;
}
native tfc_userkill( index );
/* Use this function to set private data offsets if needed
Default offsets:
timer: 932
sentrygun: 83
from AssKicR
shells: 53
bullets: 55
cells: 57
rockets: 59
nade1: 14
nade2: 15
*/
native tfc_setpddata(timer,sentrygun,shells,bullets,cells,rockets,nade1,nade2);
/*********************************************************************/
native tfc_setmodel(index, const Model[], const Skin[]);
native tfc_clearmodel(index);
/* Get amount of ammo in backpack on a user for a specific weapon */
/* Ammo Types in tfcconst.inc */
native tfc_getbammo(index, ammo);
/* Set amount of ammo in backpack on a user for a specific weapon */
native tfc_setbammo(index, ammo, value);
/* Returns amount of ammo in weapon's clip (backpack) */
/* Weapons list in tfcconst.inc */
native tfc_getweaponbammo(index, weapon);
/* Sets amount of ammo in weapon's clip (backpack) */
native tfc_setweaponbammo(index, weapon, value);
/* Returns amount of ammo in weapon's clip */
/* Index must be weapon's entity index */
native tfc_getweaponammo(index);
/* Sets amount of ammo in weapon's clip */
/* Index must be weapon's entity index */
native tfc_setweaponammo(index, value);
/* Returns 1 if user is carrying a goal item such as a flag or a keycard, else 0.
* Team is by reference parameter that will be set to owning team(s) of the goal item.
* Use the TFC_GOALITEM_* constants to determine the owning team.
*/
native tfc_get_user_goalitem(index, &team);
/* Returns 1 if the player is a spy and is currently feigning death */
native tfc_is_user_feigning(index);
/* Returns 1 if the two teams are allies, 0 otherwise
* Note: Team must be 1->4
* Team 0 will always return 0
* Any other team will result in an error
*/
native tfc_is_team_ally(TeamA,TeamB);

View File

@ -0,0 +1,100 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Time Specific Functions
//
#if defined _time_included
#endinput
#endif
#define _time_included
/* Time unit types for get_time_length() */
enum
{
timeunit_seconds = 0,
timeunit_minutes,
timeunit_hours,
timeunit_days,
timeunit_weeks,
};
/* Seconds in each time unit */
#define SECONDS_IN_MINUTE 60
#define SECONDS_IN_HOUR 3600
#define SECONDS_IN_DAY 86400
#define SECONDS_IN_WEEK 604800
/**
* Stock by Brad.
*
* @note You must add register_dictionary("time.txt") in plugin_init()
*
* @param id The player whose language the length should be translated to
* @param unitCnt The number of time units you want translated into verbose text
* @param type The type of unit (i.e. seconds, minutes, hours, days, weeks) that you are passing in
* @param output The variable you want the verbose text to be placed in
* @param outputLen The length of the output variable
*
* @noreturn
*/
stock get_time_length(id, unitCnt, type, output[], outputLen)
{
if (unitCnt > 0)
{
// determine the number of each time unit there are
new weekCnt = 0, dayCnt = 0, hourCnt = 0, minuteCnt = 0, secondCnt = 0;
switch (type)
{
case timeunit_seconds: secondCnt = unitCnt;
case timeunit_minutes: secondCnt = unitCnt * SECONDS_IN_MINUTE;
case timeunit_hours: secondCnt = unitCnt * SECONDS_IN_HOUR;
case timeunit_days: secondCnt = unitCnt * SECONDS_IN_DAY;
case timeunit_weeks: secondCnt = unitCnt * SECONDS_IN_WEEK;
}
weekCnt = secondCnt / SECONDS_IN_WEEK;
secondCnt -= (weekCnt * SECONDS_IN_WEEK);
dayCnt = secondCnt / SECONDS_IN_DAY;
secondCnt -= (dayCnt * SECONDS_IN_DAY);
hourCnt = secondCnt / SECONDS_IN_HOUR;
secondCnt -= (hourCnt * SECONDS_IN_HOUR);
minuteCnt = secondCnt / SECONDS_IN_MINUTE;
secondCnt -= (minuteCnt * SECONDS_IN_MINUTE);
// translate the unit counts into verbose text
new maxElementIdx = -1;
new timeElement[5][33];
if (weekCnt > 0)
format(timeElement[++maxElementIdx], charsmax(timeElement[]), "%i %L", weekCnt, id, (weekCnt == 1) ? "TIME_ELEMENT_WEEK" : "TIME_ELEMENT_WEEKS");
if (dayCnt > 0)
format(timeElement[++maxElementIdx], charsmax(timeElement[]), "%i %L", dayCnt, id, (dayCnt == 1) ? "TIME_ELEMENT_DAY" : "TIME_ELEMENT_DAYS");
if (hourCnt > 0)
format(timeElement[++maxElementIdx], charsmax(timeElement[]), "%i %L", hourCnt, id, (hourCnt == 1) ? "TIME_ELEMENT_HOUR" : "TIME_ELEMENT_HOURS");
if (minuteCnt > 0)
format(timeElement[++maxElementIdx], charsmax(timeElement[]), "%i %L", minuteCnt, id, (minuteCnt == 1) ? "TIME_ELEMENT_MINUTE" : "TIME_ELEMENT_MINUTES");
if (secondCnt > 0)
format(timeElement[++maxElementIdx], charsmax(timeElement[]), "%i %L", secondCnt, id, (secondCnt == 1) ? "TIME_ELEMENT_SECOND" : "TIME_ELEMENT_SECONDS");
switch(maxElementIdx)
{
case 0: formatex(output, outputLen, "%s", timeElement[0]);
case 1: formatex(output, outputLen, "%s %L %s", timeElement[0], id, "TIME_ELEMENT_AND", timeElement[1]);
case 2: formatex(output, outputLen, "%s, %s %L %s", timeElement[0], timeElement[1], id, "TIME_ELEMENT_AND", timeElement[2]);
case 3: formatex(output, outputLen, "%s, %s, %s %L %s", timeElement[0], timeElement[1], timeElement[2], id, "TIME_ELEMENT_AND", timeElement[3]);
case 4: formatex(output, outputLen, "%s, %s, %s, %s %L %s", timeElement[0], timeElement[1], timeElement[2], timeElement[3], id, "TIME_ELEMENT_AND", timeElement[4]);
}
}
}

View File

@ -0,0 +1,154 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
// Copyright (C) 2005 Suzuka.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// TSFUN Constants
//
#if defined _tsconst_included
#endinput
#endif
#define _tsconst_included
#define TSMAX_WEAPONS 44 // 37 + throwing knife + brekable + 5 custom weapon slots
#define TSPWUP_NONE 0
#define TSPWUP_RANDOM 0
#define TSPWUP_SLOWMO 1
#define TSPWUP_INFAMMO 2
#define TSPWUP_KUNGFU 4
#define TSPWUP_SLOWPAUSE 8
#define TSPWUP_DFIRERATE 16
#define TSPWUP_GRENADE 32
#define TSPWUP_HEALTH 64
#define TSPWUP_ARMOR 128
#define TSPWUP_SUPERJUMP 256
#define TSITEM_KUNGFU 1<<0
#define TSITEM_SUPERJUMP 1<<1
#define TSKF_STUNTKILL 1<<0
#define TSKF_SLIDINGKILL 1<<1
#define TSKF_DOUBLEKILL 1<<2
#define TSKF_ISSPEC 1<<3
#define TSKF_KILLEDSPEC 1<<4
#define TSA_SILENCER 1
#define TSA_LASERSIGHT 2
#define TSA_FLASHLIGHT 4
#define TSA_SCOPE 8
#define TSMSG_NORMAL 6
#define TSMSG_WAITING 11
#define TSMSG_DEAD 1
#define TSMSG_KILLER 2
#define TSMSG_DEMOLITION 3
#define TSMSG_SPECIALIST 4
#define TSMSG_UNSTOPPABLE 5
#define TSMSG_THEONE 10
#define STUNT_NONE 0
#define STUNT_DUCK 1
#define STUNT_ROLL 2
#define STUNT_DIVE 3
#define STUNT_GETUP 4
#define STUNT_FLIP 5
enum {
TSW_GLOCK18 = 1,
TSW_UNK1,
TSW_UZI,
TSW_M3,
TSW_M4A1,
TSW_MP5SD,
TSW_MP5K,
TSW_ABERETTAS,
TSW_MK23,
TSW_AMK23,
TSW_USAS,
TSW_DEAGLE,
TSW_AK47,
TSW_57,
TSW_AUG,
TSW_AUZI,
TSW_TMP,
TSW_M82A1,
TSW_MP7,
TSW_SPAS,
TSW_GCOLTS,
TSW_GLOCK20,
TSW_UMP,
TSW_M61GRENADE,
TSW_CKNIFE,
TSW_MOSSBERG,
TSW_M16A4,
TSW_MK1,
TSW_C4,
TSW_A57,
TSW_RBULL,
TSW_M60E3,
TSW_SAWED_OFF,
TSW_KATANA,
TSW_SKNIFE,
TSW_KUNG_FU,
TSW_TKNIFE,
};
/*
valid tsweaponid in TS_GiveWeapon
1: "Glock 18"
3: "Mini Uzi"
4: "Benelli M3"
5: "M4A1"
6: "MP5SD"
7: "MP5K"
8: "Akimbo Berettas"
9: "Socom Mk23"
11: "Usas12"
12: "Desert Eagle"
13: "Ak47"
14: "FiveSeven"
15: "Steyr Aug"
17: "Steyr Tmp"
18: "Barrett M82"
19: "HK Pdw"
20: "Spas12"
21: "Akimbo colts"
22: "Glock 20"
23: "Mac10"
25: "Combat Knife"
26: "Mossberg 500"
27: "M16A4"
28: "Ruger Mk1"
24: "M61 Grenade"
29: "C4"
31: "Raging Bull"
32: "M60"
33: "Sawed off"
34: "Katana"
35: "Seal Knife"
valid pwuptype in TS_GivePwUp
0: "Random"
1: "Slow Motion"
2: "Infinite Clip"
4: "Kung Fu"
8: "Slow Pause"
16: "Double Firerate"
32: "Grenade"
64: "Health"
128: "Armor"
256: "Superjump"
*/

View File

@ -0,0 +1,198 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// TSFUN Functions
//
#if defined _tsxfun_included
#endinput
#endif
#define _tsxfun_included
#include <tsx>
#include <tsconst>
/************* Shared Natives Start ********************************/
/* Forward types */
enum {
XMF_DAMAGE = 0,
XMF_DEATH,
};
#pragma reqlib tsfun
#if !defined AMXMODX_NOAUTOLOAD
#pragma loadlib tsfun
#endif
/************* Shared Natives End ********************************/
/* Function is called just before a kung foo attack is done,
* damage and time length may be altered with natives.
* Return PLUGIN_HANDLED to stop attack.
* UNAVAILABLE IN 1.70
*/
forward Melee_Attack(id,Float:time,Float:damage,UNAVAILABLE);
// Returns when someone stunts, after they do it.
//UNAVAILABLE IN 1.70
forward client_stunt(id,stunttype,UNAVAILABLE);
/* Function is called when powerups are ran,
* Returns value of powerup. Use TSPWUP_*'s
* to find exactly which one it is.
* UNAVAILABLE IN 1.70
*/
forward client_powerup(id,powerup,UNAVAILABLE);
/* weapon logname to weapon name convertion */
native ts_wpnlogtoname(const logname[],name[],len);
/* weapon logname to weapon index convertion */
native ts_wpnlogtoid(const logname[]);
//UNAVAILABLE IN 1.70
//native Float:ts_getusertime( index ); //!
//native ts_setusertime( index, Float:time ); //!
native ts_getusercash( index );
native ts_setusercash( index, money );
native ts_getuserslots( index );
native ts_setuserslots( index, slots );
native ts_getuserstate( index );
native ts_getuserwpn( index,&clip=0,&ammo=0,&mode=0,&extra=0 );
native ts_getuserspace( index );
native ts_getuserkillflags(killer);
native ts_getkillingstreak( index );
native ts_getuserlastfrag( index );
native ts_giveweapon( index,weapon,clips,extra );
native ts_getuserpwup( index );
stock ts_has_slowmo(id) {
return (ts_getuserpwup(id) &TSPWUP_SLOWMO);
}
stock ts_has_infammo(id) {
return (ts_getuserpwup(id) &TSPWUP_INFAMMO);
}
stock ts_has_slowpause(id) {
return (ts_getuserpwup(id) &TSPWUP_SLOWPAUSE);
}
stock ts_has_dfirerate(id) {
return (ts_getuserpwup(id) &TSPWUP_DFIRERATE);
}
stock ts_has_grenade(id) {
return (ts_getuserpwup(id) &TSPWUP_GRENADE);
}
stock ts_has_health(id) {
return (ts_getuserpwup(id) &TSPWUP_HEALTH);
}
stock ts_has_armor(id) {
return (ts_getuserpwup(id) &TSPWUP_ARMOR);
}
/* Function will create pwup entity and return its index (pwupent) */
native ts_createpwup( pwup );
native ts_givepwup( index,pwupent );
native ts_setpddata( knifeoffset );
// Alters a fu attack. Use with fu forward
// UNAVAILABLE IN 1.70
// native ts_set_fuattack(id,Float:time,Float:damage); //!
// Changes board message
native ts_set_message(id,message);
// Gets the message board message
native ts_get_message(id);
stock ts_is_normal(id)
{
new msg = ts_get_message(id);
if( (msg > 11) || (msg > 6 && msg < 10) ) return 1;
return 0;
}
stock ts_is_waiting(id) {
return (ts_get_message(id) == TSMSG_WAITING);
}
stock ts_is_dead(id) {
return (ts_get_message(id) == TSMSG_DEAD);
}
stock ts_is_killer(id) {
return (ts_get_message(id) == TSMSG_KILLER);
}
stock ts_is_demolition(id) {
return (ts_get_message(id) == TSMSG_DEMOLITION);
}
stock ts_is_specialist(id) {
return (ts_get_message(id) == TSMSG_SPECIALIST);
}
stock ts_is_unstoppable(id) {
return (ts_get_message(id) == TSMSG_UNSTOPPABLE);
}
stock ts_is_theone(id) {
return (ts_get_message(id) == TSMSG_THEONE);
}
// Return one on true, 0 on false
// UNAVAILABLE IN 1.70
native ts_has_superjump(id); //!
native ts_has_fupowerup(id); //!
native ts_is_in_slowmo(id);
// Get and set consecutive frags
//UNAVAILABLE IN 1.70
//native ts_get_cons_frags(id);
//native ts_set_cons_frags(id,num);
// Set to see cool bullet trails. Only id will see them.
native ts_set_bullettrail(id,yesorno);
// Sets fake versions of slow mo and slow pause. Use ts_set_speed for more options.
native ts_set_fakeslowmo(id,Float:time);
native ts_set_fakeslowpause(id,Float:time);
/* Sets speed artificially. 1.0 is default, Go into fractions and decimals for slower
* and put in higher numbers for higher speeds. Aura is how far things around you are effected
* Time is the time until it wears off. 0.0 for speed will freeze people. Do not use negatives. */
native ts_set_speed(id,Float:speed,Float:auradist,Float:time);
/* Sets physics speed artificially. Things like sparks and sounds will be effected.
* Any negative number will render all physics paused. */
native ts_set_physics_speed(id,Float:speed);
// Returns 0 if no powerup is running. Returns the powerup type otherwise.
native ts_is_running_powerup(id);
// Highly experimental command which overrides powerup types.
// Use if a powerup is already running, or if a powerup is not running.
// Safe to use in powerup forward.
native ts_force_run_powerup(id,PWUP_TYPE);

View File

@ -0,0 +1,65 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// TSX Stats Functions
//
#if defined _tsstats_included
#endinput
#endif
#define _tsstats_included
/* Gets stats from given weapon index. If wpnindex is 0
* then the stats are from all weapons. If weapon has not been used function
* returns 0 in other case 1. Fields in stats are:
* 0 - kills
* 1 - deaths
* 2 - headshots
* 3 - teamkilling
* 4 - shots
* 5 - hits
* 6 - damage
* For body hits fields see amxconst.inc. */
native get_user_wstats(index,wpnindex,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets round stats from given weapon index.*/
native get_user_wrstats(index,wpnindex,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets life (from spawn to spawn) stats from given weapon index.*/
native get_user_wlstats(index,wpnindex,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets overall stats which are stored in file on server
* and updated on every respawn or user disconnect.
* Function returns the position in stats by diff. kills to deaths. */
native get_user_stats(index,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets round stats of player. */
native get_user_rstats(index,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS]);
/* Gets stats with which user have killed/hurt his victim. If victim is 0
* then stats are from all victims. If victim has not been hurt, function
* returns 0 in other case 1. User stats are reset on his respawn. */
native get_user_vstats(index,victim,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS],wpnname[]="",len=0);
/* Gets stats with which user have been killed/hurt. If killer is 0
* then stats are from all attacks. If killer has not hurt user, function
* returns 0 in other case 1. User stats are reset on his respawn. */
native get_user_astats(index,wpnindex,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS],wpnname[]="",len=0);
/* Resets life, weapon, victims and attackers user stats. */
native reset_user_wstats(index);
/* Gets overall stats which stored in stats.dat file in amx folder
* and updated on every mapchange or user disconnect.
* Function returns next index of stats entry or 0 if no more exists. */
native get_stats(index,stats[STATSX_MAX_STATS],bodyhits[MAX_BODYHITS],name[],len);
/* Returns number of all entries in stats. */
native get_statsnum();

View File

@ -0,0 +1,88 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// TSX Functions
//
#if defined _tsx_included
#endinput
#endif
#define _tsx_included
#include <tsstats>
#pragma reqclass xstats
#if !defined AMXMODX_NOAUTOLOAD
#pragma defclasslib xstats tsx
#endif
/************* Shared Natives Start ********************************/
/* Forward types */
enum {
XMF_DAMAGE = 0,
XMF_DEATH,
};
/* Use this function to register forwards
* DEPRECATED
*/
native register_statsfwd( ftype );
/* Function is called after player to player attacks ,
* if players were damaged by teammate TA is set to 1 */
forward client_damage(attacker,victim,damage,wpnindex,hitplace,TA);
/* Function is called after player death ,
* if player was killed by teammate TK is set to 1 */
forward client_death(killer,victim,wpnindex,hitplace,TK);
/* Custom Weapon Support */
/* function will return index of new weapon */
native custom_weapon_add( const wpnname[],melee = 0,const logname[]="" );
/* Function will pass damage done by this custom weapon to stats module and other plugins */
native custom_weapon_dmg( weapon, att, vic, damage, hitplace=0 );
/* Function will pass info about custom weapon shot to stats module */
native custom_weapon_shot( weapon,index ); // weapon id , player id
/* function will return 1 if true */
native xmod_is_melee_wpn(wpnindex);
/* Returns weapon name. */
native xmod_get_wpnname(wpnindex,name[],len);
/* Returns weapon logname. */
native xmod_get_wpnlogname(wpnindex,name[],len);
/* Returns weapons array size */
native xmod_get_maxweapons();
/* Returns stats array size ex. 8 in TS , 9 in DoD */
native xmod_get_stats_size();
/* Returns 1 if true */
native xmod_is_custom_wpn(wpnindex);
/************* Shared Natives End ********************************/
/* Spawns a Weapon */
stock ts_weaponspawn(const weaponid[], const duration[], const extraclip[], const spawnflags[], const Float:Origin[3])
{
new ent = create_entity("ts_groundweapon");
DispatchKeyValue(ent, "tsweaponid", weaponid);
DispatchKeyValue(ent, "wduration", duration);
DispatchKeyValue(ent, "wextraclip", extraclip);
DispatchKeyValue(ent, "spawnflags", spawnflags);
DispatchSpawn(ent);
entity_set_origin(ent, Origin);
return PLUGIN_HANDLED;
}

View File

@ -0,0 +1,306 @@
#define TASK_CHECK_SQL_PLAYER 13378
public retrying_getinfo(id) {
id = id - 213134;
player_load_info(id);
}
public player_load_info(id) {
if(is_user_bot(id))
return PLUGIN_HANDLED;
new Handle:query,error[128],sql_query[128],quoted_name[65];
SQL_QuoteString(SqlConnection, quoted_name, 64, g_playername[id]);
if(strlen(g_playerip[id]) < 1) {
log_amx("STEAM BUG; output: %s; player id: %d", g_playersteam[id], get_user_userid(id));
get_user_authid(id, g_playersteam[id], 64);
}
query = SQL_PrepareQuery(SqlConnection, "SELECT `id` FROM kzp_players WHERE auth LIKE '%s'", g_playersteam[id]);
if(!SQL_Execute(query)) {
SQL_QueryError(query, error, 127);
new tmp_error;
SqlConnection = SQL_Connect(DB_TUPLE, tmp_error, g_error, 511);
set_task(2.0, "retrying_getinfo", 213134 + id);
}
else if(!SQL_NumResults(query)) {
new cData[1];
cData[0] = id;
formatex(sql_query, 511, "INSERT INTO kzp_players(name,ip,auth) VALUES('%s','%s','%s')", quoted_name, g_playerip[id], g_playersteam[id]);
SQL_ThreadQuery(DB_TUPLE, "QueryHandle_newPlayer", sql_query, cData, strlen(cData[0]));
}
else {
new cData[1];
cData[0] = id;
g_sql_pid[id] = SQL_ReadResult(query, 0);
format(sql_query, 511, "SELECT type,distance,maxspeed,prestrafe,strafes,sync,ddbh,pspeed,wpn FROM uq_jumps%s WHERE pid=%d", get_pcvar_num(sv_airaccelerate) == 100 ? "_100aa" : "", g_sql_pid[id]);
SQL_ThreadQuery(DB_TUPLE,"QueryHandle_LoadPlayerTops", sql_query, cData, strlen(cData[0]));
format(sql_query, 511, "SELECT type,distance,jumpoff,block,pspeed,wpn FROM uq_block_tops%s WHERE pid=%d", get_pcvar_num(sv_airaccelerate) == 100 ? "_100aa" : "", g_sql_pid[id]);
SQL_ThreadQuery(DB_TUPLE,"QueryHandle_LoadPlayerTopsBlock", sql_query, cData, strlen(cData[0]));
format(sql_query, 511, "UPDATE kzp_players SET name='%s',ip='%s',auth='%s' WHERE `id`=%d", quoted_name, g_playerip[id], g_playersteam[id], g_sql_pid[id]);
SQL_ThreadQuery(DB_TUPLE, "QueryHandle", sql_query);
}
return PLUGIN_CONTINUE;
}
public QueryHandle_LoadPlayerTops(iFailState, Handle:hQuery, szError[], iErrnum, cData[], iSize, Float:fQueueTime) {
if(iFailState != TQUERY_SUCCESS) {
log_amx("uq_jumpstats: SQL Error #%d - %s", iErrnum, szError);
return PLUGIN_HANDLED;
}
new type[64], distance, maxspeed, prestrafe, strafes, sync, ddbh, tmp_str[12], pspeed, wpn[33];
while(SQL_MoreResults(hQuery)) {
SQL_ReadResult(hQuery,0,type,64);
distance = SQL_ReadResult(hQuery,1);
maxspeed = SQL_ReadResult(hQuery,2);
prestrafe = SQL_ReadResult(hQuery,3);
strafes = SQL_ReadResult(hQuery,4);
sync = SQL_ReadResult(hQuery,5);
ddbh = SQL_ReadResult(hQuery,6);
pspeed = SQL_ReadResult(hQuery,7);
SQL_ReadResult(hQuery,8,wpn,32);
new Trie:JumpStat;
JumpStat = TrieCreate();
TrieSetString(JumpStat, "type", type);
TrieSetCell(JumpStat, "distance", distance);
TrieSetCell(JumpStat, "maxspeed", maxspeed);
TrieSetCell(JumpStat, "prestrafe", prestrafe);
TrieSetCell(JumpStat, "strafes", strafes);
TrieSetCell(JumpStat, "sync", sync);
TrieSetCell(JumpStat, "ddbh", ddbh);
TrieSetCell(JumpStat, "pspeed", pspeed);
TrieSetString(JumpStat, "wpn", wpn);
num_to_str(g_sql_pid[cData[0]],tmp_str,11);
format(type, 64, "%s_%s_%d", tmp_str, type, pspeed);
TrieSetCell(JumpPlayers, type, JumpStat);
SQL_NextRow(hQuery);
}
SQL_FreeHandle(hQuery);
return PLUGIN_CONTINUE;
}
public QueryHandle_LoadPlayerTopsBlock(iFailState, Handle:hQuery, szError[], iErrnum, cData[], iSize, Float:fQueueTime) {
if(iFailState != TQUERY_SUCCESS) {
log_amx("uq_jumpstats: SQL Error #%d - %s", iErrnum, szError);
return PLUGIN_HANDLED;
}
new type[65],distance,jumpoff,block,tmp_str[12],pspeed,wpn[33];
while(SQL_MoreResults(hQuery)) {
SQL_ReadResult(hQuery,0,type,64);
distance = SQL_ReadResult(hQuery,1);
jumpoff = SQL_ReadResult(hQuery,2);
block = SQL_ReadResult(hQuery,3);
pspeed = SQL_ReadResult(hQuery,4);
SQL_ReadResult(hQuery,5,wpn,32);
new Trie:JumpStat;
JumpStat = TrieCreate();
TrieSetString(JumpStat, "type", type);
TrieSetCell(JumpStat, "distance", distance);
TrieSetCell(JumpStat, "jumpoff", jumpoff);
TrieSetCell(JumpStat, "block", block);
TrieSetCell(JumpStat, "pspeed", pspeed);
TrieSetString(JumpStat, "wpn", wpn);
num_to_str(g_sql_pid[cData[0]],tmp_str,11);
format(type, 64, "block_%s_%s_%d", tmp_str, type, pspeed);
TrieSetCell(JumpPlayers, type, JumpStat);
SQL_NextRow(hQuery);
}
SQL_FreeHandle(hQuery);
return PLUGIN_CONTINUE;
}
public QueryHandle_newPlayer(iFailState, Handle:hQuery, szError[], iErrnum, cData[], iSize, Float:fQueueTime) {
if(iFailState != TQUERY_SUCCESS) {
log_amx("uq_jumpstats: SQL Error #%d - %s", iErrnum, szError);
return PLUGIN_HANDLED;
}
new task_data[2];
task_data[0] = SQL_GetInsertId(hQuery);
task_data[1] = cData[0];
set_task(1.0, "sql_check_reg", TASK_CHECK_SQL_PLAYER + cData[0], task_data, 2);
SQL_FreeHandle(hQuery);
return PLUGIN_CONTINUE;
}
public sql_check_reg(args[]) {
new id = args[1];
new inserted_id = args[0];
if(0 > id || id > get_maxplayers()) {
log_amx("Invalid id (%d) in sql_check_reg()", id);
return PLUGIN_HANDLED;
}
else {
if(inserted_id > 0) {
new tmp_str[12];
new Trie:JumpData;
JumpData = TrieCreate();
g_sql_pid[id] = inserted_id;
num_to_str(inserted_id, tmp_str, 11);
TrieSetCell(JumpPlayers, tmp_str, JumpData);
}
else {
log_amx("Bug? %s sql_id is %d; Retrying.", g_playername[id], inserted_id);
player_load_info(id);
}
}
return PLUGIN_HANDLED;
}
public PlayerSaveData_to_SQL(id, cData[]) {
new jt_str[65], Trie:JS, tmp_str[12], distance, query[512], wpn[33], type[33];
num_to_str(g_sql_pid[id], tmp_str, 11);
if(cData[8]) {
get_weaponname(cData[8], wpn, 32);
replace(wpn, 32, "weapon_", "");
}
else
formatex(wpn, 32, "Unknow");
formatex(type,32,"%s",Type_List[cData[6]]);
formatex(jt_str,64,"%s_%s_%d",tmp_str,Type_List[cData[6]],cData[7]);
if(TrieKeyExists(JumpPlayers, jt_str)) { // player is in trie
TrieGetCell(JumpPlayers, jt_str, JS);
if(TrieKeyExists(JS, "distance")) { // get distance
TrieGetCell(JS, "distance", distance);
if(distance < cData[0]) { // jumpdist > old jumpdist, updating
formatex(query, 511, "UPDATE uq_jumps%s SET distance=%d,maxspeed=%d,prestrafe=%d,strafes=%d,sync=%d,ddbh=%d,pspeed=%d,wpn='%s' WHERE pid=%d AND type LIKE '%s' AND pspeed=%d", get_pcvar_num(sv_airaccelerate) == 100 ? "_100aa" : "", cData[0], cData[1], cData[2], cData[3], cData[4], cData[5], cData[7], wpn, g_sql_pid[id], type, cData[7]);
SQL_ThreadQuery(DB_TUPLE,"QueryHandle", query);
TrieSetString(JS, "type", type);
TrieSetCell(JS, "distance", cData[0]);
TrieSetCell(JS, "maxspeed", cData[1]);
TrieSetCell(JS, "prestrafe", cData[2]);
TrieSetCell(JS, "strafes", cData[3]);
TrieSetCell(JS, "sync", cData[4]);
TrieSetCell(JS, "ddbh", cData[5]);
TrieSetCell(JS, "pspeed", cData[7]);
TrieSetString(JS, "wpn", wpn);
TrieSetCell(JumpPlayers, jt_str, JS);
}
}
else
log_amx("WTF?!");
}
else { // new jumptype to player, insert
formatex(query, 511, "INSERT INTO uq_jumps%s(pid,type,distance,maxspeed,prestrafe,strafes,sync,ddbh,pspeed,wpn) VALUES(%d,'%s',%d,%d,%d,%d,%d,%d,%d,'%s')", get_pcvar_num(sv_airaccelerate) == 100 ? "_100aa" : "", g_sql_pid[id], type, cData[0], cData[1], cData[2], cData[3], cData[4], cData[5], cData[7], wpn);
new Trie:JumpStat;
JumpStat = TrieCreate();
SQL_ThreadQuery(DB_TUPLE,"QueryHandle", query);
TrieSetString(JumpStat, "type", type);
TrieSetCell(JumpStat, "distance", cData[0]);
TrieSetCell(JumpStat, "maxspeed", cData[1]);
TrieSetCell(JumpStat, "prestrafe", cData[2]);
TrieSetCell(JumpStat, "strafes", cData[3]);
TrieSetCell(JumpStat, "sync", cData[4]);
TrieSetCell(JumpStat, "ddbh", cData[5]);
TrieSetCell(JumpStat, "pspeed", cData[7]);
TrieSetString(JumpStat, "wpn", wpn);
TrieSetCell(JumpPlayers, jt_str, JumpStat);
}
}
public PlayerSaveData_to_SQL_block(id, cData[]) {
new block,jt_str[65], Trie:JS, tmp_str[12], distance, query[512], wpn[33], type[33];
num_to_str(g_sql_pid[id], tmp_str, 11);
if(cData[5]) {
get_weaponname(cData[5], wpn, 32);
replace(wpn, 32, "weapon_", "");
}
else
formatex(wpn, 32, "Unknown");
if(cData[3] == 6) {
formatex(type, 32, "hj");
formatex(jt_str, 64, "block_%s_hj_%d", tmp_str, cData[4]);
}
else {
formatex(type, 32, "%s", Type_List[cData[3]]);
formatex(jt_str, 64, "block_%s_%s_%d", tmp_str, Type_List[cData[3]], cData[4]);
}
if(TrieKeyExists(JumpPlayers, jt_str)) { // player is in trie
TrieGetCell(JumpPlayers, jt_str, JS);
if(TrieKeyExists(JS, "block")) { // get block
TrieGetCell(JS, "block", block);
if(block <= cData[2]) { // block >= oldblock
if(TrieKeyExists(JS, "distance")) { // get distance
TrieGetCell(JS, "distance", distance);
if((distance < cData[0] && block==cData[2]) || (block<cData[2])) { // jumpdist > old jumpdist if block=oldblock or update if block<oldblock, updating
formatex(query, 511, "UPDATE uq_block_tops%s SET distance=%d,jumpoff=%d,block=%d,pspeed=%d,wpn='%s' WHERE pid=%d AND type LIKE '%s' AND pspeed=%d", get_pcvar_num(sv_airaccelerate) == 100 ? "_100aa" : "", cData[0], cData[1], cData[2], cData[4], wpn, g_sql_pid[id], type, cData[4]);
SQL_ThreadQuery(DB_TUPLE,"QueryHandle", query);
TrieSetString(JS, "type", type);
TrieSetCell(JS, "distance", cData[0]);
TrieSetCell(JS, "jumpoff", cData[1]);
TrieSetCell(JS, "block", cData[2]);
TrieSetCell(JS, "pspeed", cData[4]);
TrieSetString(JS, "wpn", wpn);
TrieSetCell(JumpPlayers, jt_str, JS);
}
}
else
log_amx("WTF?!");
}
}
else
log_amx("WTF?!");
}
else { // new jumptype to player, insert
formatex(query, 511, "INSERT INTO uq_block_tops%s(pid,type,distance,jumpoff,block,pspeed,wpn) VALUES(%d,'%s',%d,%d,%d,%d,'%s')", get_pcvar_num(sv_airaccelerate) == 100 ? "_100aa" : "", g_sql_pid[id], type, cData[0], cData[1], cData[2], cData[4], wpn);
new Trie:JumpStat;
JumpStat = TrieCreate();
SQL_ThreadQuery(DB_TUPLE,"QueryHandle", query);
TrieSetString(JumpStat, "type", type);
TrieSetCell(JumpStat, "distance", cData[0]);
TrieSetCell(JumpStat, "jumpoff", cData[1]);
TrieSetCell(JumpStat, "block", cData[2]);
TrieSetCell(JumpStat, "pspeed", cData[4]);
TrieSetString(JumpStat, "wpn", wpn);
TrieSetCell(JumpPlayers, jt_str, JumpStat);
}
}

View File

@ -0,0 +1,209 @@
#pragma tabsize 0
new bool:g_userConnected[33],bool:g_alive[33];
new Handle:DB_TUPLE;
new Handle:SqlConnection;
new g_error[512];
public stats_sql() {
DB_TUPLE = SQL_MakeStdTuple();
new error;
SqlConnection = SQL_Connect(DB_TUPLE,error,g_error,511);
if(!SqlConnection) {
server_print("uq_jumpstats: Could not connect to SQL database; Error #%d: %s", error, g_error);
log_amx("uq_jumpstats: Could not connect to SQL database; Error #%d: %s", error, g_error);
return pause("a");
}
new CreateInto[1001];
formatex(CreateInto, 1000, "CREATE TABLE IF NOT EXISTS uq_players (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,name VARCHAR(64) NOT NULL,ip VARCHAR(39) NOT NULL,authid VARCHAR(35) NOT NULL, lastseen INT(10) NOT NULL,INDEX(name,authid))");
SQL_ThreadQuery(DB_TUPLE,"QueryHandle", CreateInto);
formatex(CreateInto, 1000, "CREATE TABLE IF NOT EXISTS uq_jumps (pid INT(11) NOT NULL,type VARCHAR(32) NOT NULL,distance INT(10) NOT NULL,maxspeed INT(10) NOT NULL,prestrafe INT(10) NOT NULL,strafes INT(2) NOT NULL,sync INT(3) NOT NULL,ddbh INT(3) NOT NULL DEFAULT '0',pspeed INT(3) NOT NULL,wpn VARCHAR(32) NOT NULL,INDEX(pid,type,distance,maxspeed,prestrafe,strafes,sync,ddbh,pspeed,wpn))");
SQL_ThreadQuery(DB_TUPLE,"QueryHandle", CreateInto);
formatex(CreateInto, 1000, "CREATE TABLE IF NOT EXISTS uq_block_tops (pid INT(11) NOT NULL,type VARCHAR(32) NOT NULL,distance INT(10) NOT NULL,jumpoff INT(10) NOT NULL,block VARCHAR(5) NOT NULL,pspeed INT(3) NOT NULL,wpn VARCHAR(32) NOT NULL,INDEX(pid,type,distance,jumpoff,pspeed,wpn))");
SQL_ThreadQuery(DB_TUPLE,"QueryHandle", CreateInto);
return PLUGIN_CONTINUE;
}
public QueryHandle(iFailState, Handle:hQuery, szError[], iErrnum, cData[], iSize, Float:fQueueTime) {
if(iFailState != TQUERY_SUCCESS) {
log_amx("uq_jumpstats: SQL Error #%d - %s", iErrnum, szError);
client_print(0,print_chat, "SQL error. Data has not been not saved.");
}
SQL_FreeHandle(hQuery);
return PLUGIN_CONTINUE;
}
stock is_user_spectating_player(spectator, player) {
if(!valid_id(spectator) || !valid_id(player))
return 0;
if(g_userConnected[spectator] == false || g_userConnected[player] == false)
return 0;
if(g_alive[spectator] || !g_alive[player])
return 0;
if(pev(spectator, pev_deadflag) != 2)
return 0;
static specmode;
specmode = pev(spectator, pev_iuser1);
if(!(specmode == 1 || specmode == 2 || specmode == 4))
return 0;
if(pev(spectator, pev_iuser2) == player)
return 1;
return 0;
}
stock get_spectated_player(spectator) {
if(!valid_id(spectator))
return 0;
if(!g_userConnected[spectator])
return 0;
if(g_alive[spectator])
return 0;
if(pev(spectator, pev_deadflag) != 2)
return 0;
static player, specmode;
specmode = pev(spectator, pev_iuser1);
if(!(specmode == 1 || specmode == 2 || specmode == 4))
return 0;
player = pev(spectator, pev_iuser2);
if(!valid_id(player))
return 0;
if(!g_userConnected[player])
return 0;
if(!g_alive[player])
return 0;
return player;
}
stock Float:UpBhop_calc(Float:height) {
if(height <= 8 && height > 0)
return 227.0;
else if(height <= 16 && height > 8)
return 225.0;
else if(height <= 24 && height > 16)
return 223.0;
else if(height <= 32 && height > 24)
return 221.0;
else if(height <= 40 && height > 32)
return 219.0;
else if(height <= 48 && height > 40)
return 217.0;
else if(height <= 56 && height > 48)
return 215.0;
else if(height <= 64 && height > 56)
return 213.0;
return 0.0;
}
stock Float:GetFailedDistance(Float:ExDist, bool:ducking, Float:gravity, Float:jumpoff_origin[3], Float:current_velocity[3], Float:failed_origin[3], Float:failed_velocity[3]) {
static Float:airtime, Float:land_origin[3], Float:distance;
if(ducking)
jumpoff_origin[2] -= 18.0;
airtime = ((floatsqroot((failed_velocity[2] * failed_velocity[2]) - (2.0 * -gravity * (failed_origin[2] - jumpoff_origin[2])))*-1) - failed_velocity[2] ) / -gravity;
land_origin[0] = floatabs(failed_origin[0] - jumpoff_origin[0]) + floatabs(current_velocity[0] * airtime);
land_origin[1] = floatabs(failed_origin[1] - jumpoff_origin[1]) + floatabs(current_velocity[1] * airtime);
distance = vector_length(land_origin) + ExDist;
if(ducking)
jumpoff_origin[2] += 18.0;
return distance;
}
stock weapon_rank(maxspeed) {
new rank;
switch(maxspeed) {
case 0: rank = -1;
case 210: rank = 1;
case 220: rank = 2;
case 221: rank = 3;
case 230: rank = 4;
case 235: rank = 5;
case 240: rank = 6;
case 245: rank = 7;
case 250: rank = 0;
}
return rank;
}
stock weapon_maxspeed(rank) {
new maxspeed;
switch(rank) {
case 0: maxspeed = 250;
case 1: maxspeed = 210;
case 2: maxspeed = 220;
case 3: maxspeed = 221;
case 4: maxspeed = 230;
case 5: maxspeed = 235;
case 6: maxspeed = 240;
case 7: maxspeed = 245;
}
return maxspeed;
}
stock Float:LandingCalculate(id,Float:landing_orig[3], Float:jumpoff_origin[3]) {
new Float:tmplandorg[3],Float:tmplandorigin[3];
for(new i=0,ii=-18;i<3;i++,ii=ii+18) {
if(floatabs(landing_orig[0]-jumpoff_origin[0])>floatabs(landing_orig[1]-jumpoff_origin[1])) {
tmplandorigin=landing_orig;
tmplandorigin[1]=tmplandorigin[1]+ii;
if(landing_orig[0]-jumpoff_origin[0]>0) {
tmplandorigin[0]=tmplandorigin[0]+16;
tmplandorg[0]=landing_orig[0]-330;
tmplandorg[1]=landing_orig[1]+ii;
tmplandorg[2]=landing_orig[2];
}
else if(landing_orig[0]-jumpoff_origin[0]<0) {
tmplandorigin[0]=tmplandorigin[0]-16;
tmplandorg[0]=landing_orig[0]+330;
tmplandorg[1]=landing_orig[1]+ii;
tmplandorg[2]=landing_orig[2];
}
}
else if(floatabs(landing_orig[0]-jumpoff_origin[0])<floatabs(landing_orig[1]-jumpoff_origin[1])) {
tmplandorigin=landing_orig;
tmplandorigin[0]=tmplandorigin[0]+ii;
if(landing_orig[1]-jumpoff_origin[1]>0) {
tmplandorigin[1]=tmplandorigin[1]+16;
tmplandorg[0]=landing_orig[0]+ii;
tmplandorg[1]=landing_orig[1]-330;
tmplandorg[2]=landing_orig[2];
}
else if(landing_orig[1]-jumpoff_origin[1]<0) {
tmplandorigin[1]=tmplandorigin[1]-16;
tmplandorg[0]=landing_orig[0]+ii;
tmplandorg[1]=landing_orig[1]+330;
tmplandorg[2]=landing_orig[2];
}
}
new Float:Orgland[3],Float:startOrgland[3];
engfunc(EngFunc_TraceLine,tmplandorigin, tmplandorg, IGNORE_GLASS | IGNORE_MONSTERS, id, 0);
get_tr2(0, TR_vecEndPos, Orgland);
engfunc(EngFunc_TraceLine,Orgland, tmplandorigin, IGNORE_GLASS | IGNORE_MONSTERS, id, 0);
get_tr2(0, TR_vecEndPos, startOrgland);
if(get_distance_f(tmplandorigin,startOrgland)!=0.0)
return get_distance_f(tmplandorigin,startOrgland);
}
return 0.0;
}
stock kz_get_configsfile(name[], len) {
new lalin[64];
get_localinfo("amxx_configsdir", lalin,63);
return formatex(name, len, "%s/uqjumpstats.cfg", lalin);
}

View File

@ -0,0 +1,60 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Vault Functions
//
#if defined _vault_included
#endinput
#endif
#define _vault_included
/**
* Reads data from a given key.
*
*
* @param key Key to get the value from
* @param data Buffer to copy the value to
* @param len Buffer size. If len is set to 0 then the function will
* return the value as a number
*
* @return If len is not 0 the function will return the number of characters written.
If len is 0 the function will return the numerical value associated with the key.
*/
native get_vaultdata(const key[], data[] = "", len = 0);
/**
* Sets data for a given key.
*
* @param key Key to set the value for
* @param data Data to set for the given key
*
* @noreturn
*/
native set_vaultdata(const key[], const data[] = "");
/**
* Removes a key and its data from the vault.
*
* @param key Key to remove
*
* @noreturn
*/
native remove_vaultdata(const key[]);
/**
* Checks if a key exists in the vault.
*
* @param key Key to check
*
* @return 1 if an entry was found, 0 otherwise.
*/
native vaultdata_exists(const key[]);

View File

@ -0,0 +1,131 @@
// vim: set ts=4 sw=4 tw=99 noet:
//
// AMX Mod X, based on AMX Mod by Aleksander Naszko ("OLO").
// Copyright (C) The AMX Mod X Development Team.
//
// This software is licensed under the GNU General Public License, version 3 or higher.
// Additional exceptions apply. For full license details, see LICENSE.txt or visit:
// https://alliedmods.net/amxmodx-license
//
// Vector Functions
//
#if defined _corevector_included
#endinput
#endif
#define _corevector_included
/**
* Used for angle_vector()
*/
#define ANGLEVECTOR_FORWARD 1
#define ANGLEVECTOR_RIGHT 2
#define ANGLEVECTOR_UP 3
/**
* Calculates the distance between two input vectors.
*
* @param origin1 The first vector
* @param origin2 The second vector
*
* @return The distance between two input vectors
*/
native get_distance(const origin1[3], const origin2[3]);
/**
* Calculates the distance between two input float vectors.
*
* @param origin1 The first vector
* @param origin2 The second vector
*
* @return The distance between two input vectors
*/
native Float:get_distance_f(const Float:Origin1[3], const Float:Origin2[3]);
/**
* Calculates velocity in the direction player is looking.
*
* @param iIndex Client index
* @param iVelocity Multiply vRetValue length by this much
* @param vRetValue Store the calculated velocity in this vector.
*
* @noreturn
* @error If client is not connected or client index is not
* within the range of 1 to MaxClients.
*/
native velocity_by_aim(iIndex, iVelocity, Float:vRetValue[3]);
/**
* Changes a vector into an angle vector.
*
* @param fVector Input vector
* @param vReturn Output angle vector
*
* @noreturn
*/
native vector_to_angle(const Float:fVector[3], Float:vReturn[3]);
/**
* Changes an angle vector into a vector.
*
* @param vector Input angle vector
* @param FRU One of the ANGLEVECTOR_* constants
* @param ret Output vector
*
* @noreturn
*/
native angle_vector(const Float:vector[3], FRU, Float:ret[3]);
/**
* Calculates the length of a vector.
*
* @param vVector Input vector
*
* @return Length of the input vector
*/
native Float:vector_length(const Float:vVector[3]);
/**
* Calculates the distance between two vectors.
*
* @param vVector The first vector
* @param vVector2 The second vector
*
* @return Distance between two input vectors
*/
native Float:vector_distance(const Float:vVector[3], const Float:vVector2[3]);
/**
* Converts an integer vector to a floating point vector.
*
* @param IVec Input integer vector
* @param FVec Output float vector
*
* @noreturn
*/
stock IVecFVec(const IVec[3], Float:FVec[3])
{
FVec[0] = float(IVec[0]);
FVec[1] = float(IVec[1]);
FVec[2] = float(IVec[2]);
return 1;
}
/**
* Converts a floating point vector into an integer vector.
*
* @param FVec Input float vector
* @param IVec Output integer vector
*
* @noreturn
*/
stock FVecIVec(const Float:FVec[3], IVec[3])
{
IVec[0] = floatround(FVec[0]);
IVec[1] = floatround(FVec[1]);
IVec[2] = floatround(FVec[2]);
return 1;
}

File diff suppressed because it is too large Load Diff