English
Sign in

Porting AMX Mod X plugins

Classic Strike runs plugins written in Luau on its own API (docs/plugins_api.md, docs/plugins_reference.md). Plugins written for AMX Mod X can be ported in two ways:

The two mix freely: a port on compat/amxx can call cs.* anywhere.

compat/amxx is written from AMX Mod X's public documentation (what each function is called and what it does), never from its code.

Starting a port

local amxx = require("compat/amxx")

local function plugin_init()
	amxx.register_plugin("Hello", "1.0", "Me")
	amxx.register_clcmd("say /hello", "cmd_hello")
end

local function cmd_hello(id)
	amxx.client_print(id, amxx.print_chat, "Hello %n", id)
	return amxx.PLUGIN_HANDLED
end

amxx.publics({ plugin_init = plugin_init, cmd_hello = cmd_hello })

amxx.publics{} lists the plugin's public functions: the forwards it has (plugin_precache, plugin_init, plugin_cfg, plugin_end, client_connect, client_authorized, client_putinserver, client_disconnected, client_disconnect, client_infochanged, client_command, client_PreThink, client_PostThink, server_frame) and the callbacks other functions take by name (set_task("fn"), menu_create(title, "handler")). plugin_precache runs at each map's start; plugin_init and plugin_cfg once, after it (at once when a map is running already).

Conventions

PawnLuau
get_user_name(id, name, charsmax(name))local name = amxx.get_user_name(id)
get_players(players, num, "ach")local players, num = amxx.get_players("ach")
get_user_origin(id, origin)local origin = amxx.get_user_origin(id) (a vector)
new wid = get_user_weapon(id, clip, ammo)local wid, clip, ammo = amxx.get_user_weapon(id)
read_argv(1, arg, charsmax(arg))local arg = amxx.read_argv(1)

Coverage

amxmodx

AreaFunctions
Pluginregister_plugin, get_plugin_info, the forwards above
Commandsregister_clcmd, register_concmd, register_srvcmd, read_argc, read_argv, read_argv_int, read_argv_float, read_args, remove_quotes, cmd_access, cmd_target
Settingsregister_cvar, create_cvar, cvar_exists, get/set_cvar_num/float/string, get/set_pcvar_num/float/bool/string, hook_cvar_change
Tasksset_task (flags a and b), remove_task, task_exists, change_task
Textformat, formatex, client_print, client_print_color, console_print, server_print, log_amx, log_message, log_to_file, server_cmd, client_cmd, console_cmd, register_dictionary
Playersget_user_name/authid/ip/userid/index/team/health/armor/frags/deaths/ping/time/origin/aiming, get_players, get_playersnum, find_player, is_user_connected/alive/bot/hltv/admin, user_kill, user_silentkill, user_slap
Adminread_flags, get_flags, get_user_flags, set_user_flags, remove_user_flags, access, is_user_admin
WeaponsCSW_*, get_weaponname, get_weaponid, get_user_weapon, get_user_weapons, get_user_ammo
Serverget_mapname, get_maxplayers, get_time, get_timeleft, get/set_localinfo, precache_model/sound/generic, random_num, random_float, floatround
Stringsthe string functions (equal, equali, contain, containi, replace, replace_all, parse, strtok, trim, str_to_num, num_to_str...)
HUDset_hudmessage, show_hudmessage, CreateHudSyncObj, ShowSyncHudMsg, ClearSyncHud, set_dhudmessage, show_dhudmessage
Menusregister_menuid, register_menucmd, show_menu, get_user_menu; newmenus: menu_create, menu_additem, menu_addblank, menu_addtext, menu_items, menu_pages, menu_item_getinfo, menu_item_setname/setcmd/setcall, menu_setprop, menu_destroy, menu_display, menu_cancel, menu_makecallback, player_menu_info
Userinfoget_user_info, set_user_info (taken in the next frame: name renames), SetGlobalTransTarget with %l
Maps, MOTDis_map_valid, show_motd (a file of the data folder or the text), user_has_weapon
Floatsfloatsin/cos/tan/asin/acos/atan/atan2 (with radian, degrees, grades), floatsinh/cosh/tanh, floatlog, floatmax, floatmin, floatclamp, floatfract
xsthe vector and number stocks: xs_vec_set/copy/add/sub/add_scaled/sub_scaled/mul_scalar/div_scalar/neg/len/len_2d/normalize/distance/distance_2d/sqdistance/dot/cross/equal/nearlyequal/angle/reflect/make2d, xs_sqrt, xs_rsqrt, xs_abs, xs_sign, xs_deg2rad...
celltrieTrieCreate, TrieSet/GetCell/String/Array, TrieKeyExists, TrieDeleteKey, TrieClear, TrieGetSize, TrieDestroy, TrieSnapshot*, TrieIter*
cellarrayArrayCreate, ArrayClone, ArrayClear, ArraySize, ArrayResize, ArrayGet/Set/Push/InsertArray/Cell/String, ArraySwap, ArrayDeleteItem, ArrayFindString, ArrayFindValue, ArraySort, ArraySortEx, ArrayDestroy (items from 0)
Filesfopen (r, w, a, +), fclose, feof, fgets, fputs, fprintf, fputc, fgetc, fseek, ftell, fflush, fread, fwrite, fread_blocks, fwrite_blocks, read_file, write_file, file_exists, file_size, delete_file, rename_file, mkdir, dir_exists, rmdir, open_dir, next_file, close_dir, get_datadir, get_configsdir, get_basedir
Nativesregister_native (styles 0 and 1), register_library, get_param, get_param_f, get_param_byref, set_param_byref, get_string, set_string, get_array, set_array, LibraryExists; plugin_natives runs first
ForwardsCreateMultiForward (ET_IGNORE, ET_STOP, ET_STOP2, ET_CONTINUE), CreateOneForward, ExecuteForward, DestroyForward, PrepareArray; callfunc_begin, callfunc_begin_i, get_func_id, callfunc_push_*, callfunc_end
Pluginsis_plugin_loaded, find_plugin_byfile, get_pluginsnum, get_plugin

No equivalent: bind_pcvar_* (read the setting with get_pcvar_*, or keep a copy current with hook_cvar_change).

Files live in the plugin's data folder (plugin_data/<plugin>/): a leading addons/amxmodx/ goes, so get_datadir() (addons/amxmodx/data) names its data/ and the configs a plugin reads go in its configs/; characters the data folder does not take become _. A file opened for writing is written when it is closed or flushed. Files have no time stamps (GetFileTime).

Natives and forwards cross plugins: a plugin on compat/amxx that calls a native it does not have finds the plugin that registered it (any loaded one) and gets its result and then the parameters as the handler left them (cs_port writes them back into the caller's variables); ExecuteForward and callfunc_* run the public in each plugin on compat/amxx that has it. Values are copied between the plugins.

Behaviour notes:

fakemeta and engine

Entity variables go through raw access by their classic names, so a port that uses them needs permissions = ["raw_properties"] in plugin.toml. Each classic name (pev_health, EV_FL_health, EV_ENT_owner) is a constant naming itself; the names are in docs/plugins_fields.md.

AreaFunctions
Variablespev, set_pev (a vector, a table or three numbers), set_pev_string, pev_valid, entity_get/set_int/float/vector/string/edict/byte
Entitiescreate_entity, remove_entity, is_valid_ent, entity_count, entity_set_origin/model/size, DispatchSpawn, DispatchKeyValue, force_use, drop_to_floor
Findingfind_ent_by_class/tname/target/model/owner, find_ent_in_sphere, find_sphere_class
Tracestrace_line, trace_hull, trace_normal, point_contents, create_tr2, free_tr2, get_tr2, set_tr2, get_tr, set_tr
Vectorsangle_vector, vector_length, vector_distance, get_distance(_f), vector_to_angle, entity_range, get_speed, velocity_by_aim, get_user_button, get_user_oldbutton
engfuncPrecacheModel/Sound/Generic, SetModel, SetSize, SetOrigin, AllocString (gives the string back), CreateNamedEntity, RemoveEntity, FindEntityByString, FindEntityInSphere, TraceLine, TraceHull, TraceModel, TraceTexture, PointContents, EmitSound, MakeVectors, DropToFloor, GetInfoKeyBuffer, InfoKeyValue, Time, ServerCommand, NumberOfEntities, EntIsOnFloor
dllfuncSpawn, Use, KeyValue
Globalsglobal_get (glb_time, glb_frametime, glb_maxClients, glb_mapname, glb_v_forward/right/up, the glb_trace_*)
Forwardsregister_forward / unregister_forward: FM_Spawn, FM_Think, FM_Touch, FM_Use, FM_Blocked, FM_PlayerPreThink, FM_PlayerPostThink, FM_ClientConnect, FM_ClientPutInServer, FM_ClientDisconnect, FM_ClientUserInfoChanged, FM_ClientCommand, FM_CmdStart (get_uc/set_uc), FM_EmitSound, FM_StartFrame, FM_AddToFullPack (get_es/set_es)
engine callbacksregister_think, register_touch, register_impulse and their unregister_*
ConstantsMOVETYPE_*, SOLID_*, DEAD_*, DAMAGE_*, kRender*, USE_*, IN_*, FL_*, EF_*, DMG_*, CONTENTS_*, HULL_*, CHAN_*, ATTN_*, FMRES_*

Each forward runs on an event of the event model (docs/plugins_api.md, 5j): a pre forward is the before side, a post forward the after side, and FMRES_SUPERCEDE blocks a blockable event. An event with nothing to change or block (FM_PlayerPreThink, FM_StartFrame) runs pre forwards on its after side. forward_return has no value to set: hiding an entity in FM_AddToFullPack is returning FMRES_SUPERCEDE.

No equivalent: get_pdata_*/set_pdata_* and get_ent_data* (numeric offsets: read the member by name, Entity:get("m_iTeam")), fake_touch, call_think, attach_view, set_view, get_keyvalue, and the forwards FM_SetModel, FM_TraceLine, FM_TraceHull, FM_UpdateClientData, FM_KeyValue, FM_GetGameDescription, FM_ClientKill (each error names the replacement).

hamsandwich

RegisterHam(Ham_*, class, fn, post) (also RegisterHamPlayer, RegisterHamFromEntity), DisableHamForward, EnableHamForward, IsHamValid, SetHamParamInteger/Float/Vector/Entity/String, ExecuteHam, ExecuteHamB.

HamEventWritable parameters
Ham_Spawnplayer_spawn / entity_spawn
Ham_Think, Ham_Touch, Ham_Blocked, Ham_Usethink, touch, blocked, use
Ham_TakeDamageplayer_damage / entity_damage4 damage, 5 damage type (not for players)
Ham_TraceAttack (players)player_trace_attack3 damage; the trace handle gives TR_iHitgroup
Ham_Killedplayer_killed / entity_killed
Ham_Player_PreThink, PostThink, Jump, Duckplayer_pre_think, player_post_think, player_jump, player_duck
Ham_AddPlayerItem (player), Ham_Item_AddToPlayer (weapon)player_pickup
Ham_Item_Deploy, Ham_Item_Holsterweapon_deploy, weapon_holster
Ham_Weapon_PrimaryAttack, SecondaryAttack, Reload, WeaponIdleweapon_attack, weapon_reload, weapon_idle

HAM_SUPERCEDE blocks the call (before side). ExecuteHam and ExecuteHamB both go through the hooks: Ham_Spawn, Ham_TakeDamage, Ham_Killed, Ham_Use, Ham_CS_RoundRespawn, Ham_Respawn, Ham_Item_PreFrame and Ham_CS_Player_ResetMaxSpeed (the speed reset), Ham_IsPlayer. The hooks have no return value, so GetHamReturn* and SetHamReturn* raise an error.

cstrike and fun

Functions that read or write members of the game's classes (armor type, kits, night vision, VIP, ammunition, silencers) need permissions = ["raw_properties"].

AreaFunctions
Money and scorecs_get/set_user_money, cs_get/set_user_deaths, set_user_frags, cs_set_user_hostagekills
Teamscs_get_user_team (team, model number), cs_set_user_team
Equipmentcs_get/set_user_armor (amount, CS_ARMOR_*), cs_get/set_user_defuse, cs_get/set_user_nvg, cs_get/set_user_vip, cs_get_user_hasprim, cs_get_user_shield, give_item, strip_user_weapons
Ammunition and weaponscs_get/set_user_bpammo, cs_get/set_weapon_ammo, cs_get_weapon_id, cs_get/set_weapon_silen, cs_get/set_weapon_burst, cs_get_user_weapon_entity, cs_get_item_id, cs_get_translated_item_alias
Lookcs_get/set_user_model, cs_reset_user_model, cs_get/set_user_zoom, set_user_rendering, get_user_rendering
Placescs_get_user_buyzone, cs_get_user_mapzones (the buy zone only), set_user_origin, cs_user_spawn
Hostages and bombcs_get/set_hostage_foll, cs_get_hostage_id, cs_get/set_c4_explode_time, cs_get_c4_defusing
funget/set_user_godmode, set_user_health (0 kills), set_user_armor, get/set_user_maxspeed, get/set_user_gravity, get/set_user_noclip, get/set_user_footsteps, get/set_user_hitzones, get/set_client_listen, spawn

Notes: cs_set_user_team between T and CT keeps the player alive with the items, as the game's own team swap (Player:switch_team); to or from spectators it goes through the team menu's rules (Player:join_team). cs_get_user_buyzone is true where the player may buy now (the zone and the buy time). No equivalent (each error names the replacement): cs_get_user_driving, cs_get_user_stationary, cs_get_user_plant, cs_get/set_user_tked, cs_get/set_no_knives, cs_set_ent_class, cs_get_weapon_info, cs_get/set_armoury_type, cs_get/set_user_lastactivity, cs_get/set_user_submodel.

ReAPI

AreaFunctions
Members and variablesget_member, set_member (members by the game's names: m_iTeam; arrays from element 0), get_member_game, set_member_game, get_entvar, set_entvar (var_*)
Playersrg_set_user_team, rg_switch_team, rg_swap_all_players, rg_add_account (AS_ADD, AS_SET), rg_give_item (GT_APPEND, GT_REPLACE, GT_DROP_AND_REPLACE), rg_remove_item, rg_remove_all_items, rg_drop_item, rg_drop_items_by_slot, rg_remove_items_by_slot, rg_has_item_by_name, rg_get/set_user_bpammo, rg_get/set_user_armor, rg_set_user_model, rg_reset_user_model, rg_give_defusekit, rg_round_respawn, rg_reset_maxspeed, rg_find_ent_by_class
Roundsrg_round_end (WINSTATUS_*, ROUND_*), rg_update_teamscores, rg_restart_round
Hook chainsRegisterHookChain, DisableHookChain, EnableHookChain, SetHookChainArg, SetHookChainReturn (nothing to set: blocking is HC_SUPERCEDE), IsReapiHookOriginalWasCalled
Entitiesis_entity, get_member_s, set_member_s (only on a valid entity), rg_create_entity, rg_remove_entity, rg_find_ent_by_owner, SetTouch, SetUse, SetThink (the entity's own callback replaced; "" puts the game's back)
More playersrg_join_team, rg_switch_weapon, rg_send_audio, rh_emit_sound2
Movementget_pmove (pm_origin, pm_velocity, pm_basevelocity, pm_angles, pm_flags, pm_onground, pm_waterlevel, pm_movetype, pm_bInDuck, pm_oldbuttons, pm_maxspeed, pm_player_index, pm_cmd, pm_frametime) and get_ucmd (ucmd_*) in RG_PM_Move handlers; get_movevar
Hook chainEventWritable arguments
RG_CBasePlayer_Spawn, RG_CSGameRules_PlayerSpawnplayer_spawn
RG_CBasePlayer_TakeDamageplayer_damage4 damage
RG_CBasePlayer_TraceAttackplayer_trace_attack3 damage
RG_CBasePlayer_Killed, RG_CSGameRules_PlayerKilledplayer_killed
RG_CBasePlayer_PreThink, PostThink, Jump, Duckplayer_pre_think, player_post_think, player_jump, player_duck
RG_PM_Moveplayer_move (pre handlers read the state before the move, post ones after it)
RG_PM_Jumpplayer_jump
RG_CBasePlayer_AddAccountplayer_money2 amount
RG_CBasePlayer_GiveDefaultItemsplayer_equip
RG_CBasePlayer_DropPlayerItem, RG_CBasePlayer_AddPlayerItemplayer_drop, player_pickup
RG_CBasePlayer_SetClientUserInfoNameplayer_name3 name
RG_HandleMenu_ChooseTeamplayer_choose_team2 team (menu slot)
RG_CBasePlayer_Radioplayer_radio
RG_BuyWeaponByWeaponID, RG_BuyItemplayer_buy
RG_RoundEndround_end2 event (reason), 3 delay
RG_CSGameRules_RestartRound, OnRoundFreezeEnd, CheckWinConditionsround_start, freeze_end, team_win_check
RG_CGrenade_DefuseBombStart, DefuseBombEndbomb_defuse, bomb_defuse_end
RG_CGrenade_ExplodeBomb, ExplodeHeGrenade, ExplodeFlashbang, ExplodeSmokeGrenadegrenade_detonate
RG_ThrowHeGrenade, RG_ThrowFlashbang, RG_ThrowSmokeGrenadegrenade_thrown
RG_PlantBombbomb_planted
RG_CBasePlayerWeapon_DefaultDeploy, DefaultReloadweapon_deploy, weapon_reload
RG_CBasePlayer_Observer_SetModeplayer_spectate

HC_SUPERCEDE and HC_BREAK block the call (before side); HC_BREAK and HC_BYPASS also skip the later handlers. GetHookChainReturn raises an error (the hooks have no return value). The move itself cannot be changed (set_pmove, set_movevar): the server alone would break the client's prediction; Player:set_movement changes it for both. No equivalent: RG_PM_AirMove (movement settings, Player:set_movement; a slide fix that keeps players from stopping on a ramp's seams is its ramp_fix), RG_CBasePlayer_HasRestrictItem (block player_buy or player_pickup), RG_CSGameRules_FPlayerCanTakeDamage (block player_damage), and the others the errors name; rg_internal_cmd, rg_set_animation, rg_give_custom_item, rg_get/set_account_rules, rg_check_win_conditions; and elsewhere get_kvd/set_kvd (Entity:key_value), get_cd/set_cd, set_speak (Player:mute_voice), query_client_cvar, geoip_*.

Data: nvault, sqlx, json, EasyHttp

Messages and log events

Messages are named, not numbered: get_user_msgid("TextMsg") gives the name back and every function takes it (SVC_TEMPENTITY is TempEntity). A plugin that hard-codes message numbers must use the names.

Not covered

Modules that patch the server's memory or call its functions by signature (Orpheu, Okapi, RAGE, get_pdata_* by offset) have no equivalent: the game's state is reached by name (Entity:get, the field table) and its behaviour through the events. A function compat/amxx does not have is nil (calling it says which name); cs_port lists them per plugin.

cs_port: translating the source

cs_port.py translates a plugin's Pawn source into a Classic Strike plugin on compat/amxx. It comes in the server and tools package (the dedicated server and the authors' tools, apart from the game), in data/plugin_sdk/cs_port/ (Python 3.10 or newer; tools/cs_port/ in the game's source):

python3 data/plugin_sdk/cs_port/cs_port.py scripting/myplugin.sma -I scripting/include -o myplugin --check

--check compiles what it wrote (with the package's cs_plugin check).

What it translates, and how:

PawnLuau
#include, #define (with %1 patterns, name[%1], pasting), #if/#elseifDone before parsing; a constant #define keeps its name
cells, Float:, bool:numbers and booleans; conditions on cells become ~= 0
a / b, a % b on integersP.div, P.mod (truncated toward 0, as Pawn)
&, \|, ^, ~, <<, >>, >>>P.band ... P.ushr (32 bits, signed)
character arraysstrings: s[i] is P.ch(s, i), s[i] = c is P.setch, s[0] = EOS is s = ""
Float:v[3] (and number arrays compat fills with vectors)vectors: v[0] is v.x
other arraystables indexed from 0 (P.array({33, 32}, "")); assignment copies
enum with sized fields (g_data[33][PlayerData])a table per element keyed by the fields
switch (ranges, lists)if/elseif
for (new i = a; i < b; i++)for i = a, b - 1 when the body leaves i and b alone; else while
assignments and ++ inside expressionsdone before the statement (in a function where it must stay conditional)
out-parameters (get_user_name(id, name, len), &ref, arrays a stock writes)results: name = amxx.get_user_name(id); a stock returns its value and then its outputs
formatex(buf[len], ...)buf = string.sub(buf, 1, len) .. text
stockonly when called (Pawn compiles only those)
..., numargs, getarg, vformatLuau's ...
static localsa variable outside the function
gotoTODO(port) and P.todo() (Luau has no goto)

Which arrays hold text is not written in Pawn; it is found from use: string literals, the natives' string parameters, %s in format strings, characters written into them, and the arrays they are passed to or copied from. An array nothing tells apart is numbers, unless its name says text (szName, name, msg, ...).

What differs from Pawn:

compat/pawn (data/plugin_sdk/compat/pawn.luau) holds those helpers.

tools/cs_port/tests/run.sh checks the translator: tests/*.sma against tests/expected/ (--update after a deliberate change), every output and the compat libraries through cs_luau_check, and the translated plugins on a dedicated server: lang (each Pawn construct), game (the usual ways with players, hook chains and userinfo, with bots), data (celltrie, cellarray, files, floats, xs, forwards, callfunc) and natives_lib with natives_use (natives, callfunc and forwards between plugins). CS_PORT_EXTRA=.../plugin.sma also translates that plugin. tools/cs_port/dump_compat.sh rewrites compat_names.txt, the names compat/amxx exports, after it changes.

Testing a port

tools/plugin_compat_test.sh runs native/game/src/plugins/tests/compat (a plugin written as an AMXX port) with bots and a client that types commands and answers menus; it is a worked example of each function above.