Difference between revisions of "Introduction to SourceMod Plugins"
m (→Client Callbacks) |
(→Will SourceMod support Source 2? Will plugins for existing games continue to work if they are ported?: Add answers for ongoing development) |
||
(58 intermediate revisions by 18 users not shown) | |||
Line 1: | Line 1: | ||
This guide will give you a basic introduction to writing a [[SourceMod]] plugin. If you are not familiar with the SourcePawn language, it is recommended that you at least briefly read the [[Introduction to SourcePawn]] article. | This guide will give you a basic introduction to writing a [[SourceMod]] plugin. If you are not familiar with the SourcePawn language, it is recommended that you at least briefly read the [[Introduction to SourcePawn]] article. | ||
− | For information on compiling plugins, see [[Compiling SourceMod Plugins]]. You can use [ | + | For information on compiling plugins, see [[Compiling SourceMod Plugins]]. You can use [https://forums.alliedmods.net/showthread.php?p=2693577 SPCode], [https://www.crimsoneditor.com/ Crimson Editor], [http://www.pspad.com/ PSPad], [http://www.ultraedit.com/ UltraEdit], [https://notepad-plus-plus.org/ Notepad++], [https://www.textpad.com/ TextPad], [http://sourceforge.net/projects/pawnstudio/ Pawn Studio], [https://forums.alliedmods.net/showthread.php?t=289127 BasicPawn] or any other text editor you're comfortable with to write plugins. |
=Starting from scratch= | =Starting from scratch= | ||
− | Open your favorite text editor and create a new empty file. When you have an empty file you can just start writing code using the core language, however, you will not be able to use any of SourceMod features because the compiler does not | + | Open your favorite text editor and create a new empty file. When you have an empty file you can just start writing code using the core language, however, you will not be able to use any of SourceMod features because the compiler does not know about them. This is done deliberately so it is possible to use SourcePawn outside of SourceMod. But since we are writing a SourceMod plugin, it is a good idea to enable access to SourceMod features first. This is done using <tt>#include</tt> directive. It tells the compiler to "paste" the code from another file into yours. |
<pawn>#include <sourcemod></pawn> | <pawn>#include <sourcemod></pawn> | ||
− | How does this work? First of all, note that we enclosed file name into angle brackets. Angle brackets tell the compiler to look in the default include directory. By default, it is '''scripting/include'''. You can open it right now and see a lot of inc files there. Those are SourceMod include files that describe various functions, tags and other features available for SourceMod plugins. The files are plain-text and you are encouraged to read them. You will notice however, that there's not much code in there, certainly not enough to implement all the great features of SourceMod, so where are they? They are implemented inside a SourceMod core which is written in C++ and is compiled into binary files which end up in '''bin''' directory. So how does your SourcePawn code and SM core link together if compiler doesn't know about existence of the latter? SourceMod include files are written specially, so they say that the implementation of functions is ''somewhere else''. | + | How does this work? First of all, note that we enclosed file name into angle brackets. Angle brackets tell the compiler to look in the default include directory. By default, it is '''scripting/include'''. You can open it right now and see a lot of inc files there. Those are SourceMod include files that describe various functions, tags and other features available for SourceMod plugins. The files are plain-text and you are encouraged to read them. You will notice, however, that there's not much code in there, certainly not enough to implement all the great features of SourceMod, so where are they? They are implemented inside a SourceMod core which is written in C++ and is compiled into binary files which end up in '''bin''' directory. So how does your SourcePawn code and SM core link together if the compiler doesn't know about the existence of the latter? SourceMod include files are written specially, so they say that the implementation of functions is ''somewhere else''. The compiler understands that and generates a special code that says that this function call is going outside. When SourceMod loads your plugin, it inspects these bits of code and substitutes it's own internal functions instead. This is called [http://en.wikipedia.org/wiki/Dynamic_linking dynamic linking]. |
=Setting up plugin info= | =Setting up plugin info= | ||
− | Now that we got access to SourceMod features, it is time to | + | Now that we got access to SourceMod features, it is time to set up the information that will be displayed via <tt>sm plugins list</tt> command. No one likes unnamed plugins. To do that we are going to look inside '''sourcemod.inc''' file and see the format that information should be declared. It's always helpful to look inside SM include files to find out information you don't know. There is also an [http://docs.sourcemod.net/api/ API documentation] but it can be outdated and it only has SM core files so if your plugin is going to use any third party extension or another plugin, you will have to study inc files. So, open '''sourcemod.inc''' and scroll down a bit until you see this: |
− | < | + | <sourcepawn>/** |
* Plugin public information. | * Plugin public information. | ||
*/ | */ | ||
struct Plugin | struct Plugin | ||
{ | { | ||
− | const | + | public const char[] name; /**< Plugin Name */ |
− | const | + | public const char[] description; /**< Plugin Description */ |
− | const | + | public const char[] author; /**< Plugin Author */ |
− | const | + | public const char[] version; /**< Plugin Version */ |
− | const | + | public const char[] url; /**< Plugin URL */ |
− | };</ | + | };</sourcepawn> |
and this: | and this: | ||
− | < | + | <sourcepawn>/** |
* Declare this as a struct in your plugin to expose its information. | * Declare this as a struct in your plugin to expose its information. | ||
* Example: | * Example: | ||
* | * | ||
− | * public Plugin | + | * public Plugin myinfo = |
* { | * { | ||
* name = "My Plugin", | * name = "My Plugin", | ||
Line 32: | Line 32: | ||
* }; | * }; | ||
*/ | */ | ||
− | public Plugin | + | public Plugin myinfo;</sourcepawn> |
It tells us that we need to create a global public variable <tt>myinfo</tt> which must be of type <tt>Plugin</tt> which is a struct with 5 fields which themselves are strings. It may sound complicated for a beginner but it's easy. Let's go ahead and create one: | It tells us that we need to create a global public variable <tt>myinfo</tt> which must be of type <tt>Plugin</tt> which is a struct with 5 fields which themselves are strings. It may sound complicated for a beginner but it's easy. Let's go ahead and create one: | ||
− | < | + | <sourcepawn>public Plugin myinfo = |
{ | { | ||
name = "My First Plugin", | name = "My First Plugin", | ||
Line 42: | Line 42: | ||
version = "1.0", | version = "1.0", | ||
url = "http://www.sourcemod.net/" | url = "http://www.sourcemod.net/" | ||
− | };</ | + | };</sourcepawn> |
− | The <tt>public</tt> keyword means that SourceMod will be able to directly access our variable. <tt>Plugin | + | The <tt>public</tt> keyword means that SourceMod will be able to directly access our variable. <tt>Plugin</tt> defines a type of our variable. <tt>myinfo</tt> is, obviously, a name of our variable as required by SourceMod. You see that we initialize it right away. This is the preferable way to fill out plugin info. |
After that the full code of your plugin should look like this: | After that the full code of your plugin should look like this: | ||
− | < | + | <sourcepawn>#include <sourcemod> |
− | public Plugin | + | public Plugin myinfo = |
{ | { | ||
name = "My First Plugin", | name = "My First Plugin", | ||
Line 56: | Line 56: | ||
version = "1.0", | version = "1.0", | ||
url = "http://www.sourcemod.net/" | url = "http://www.sourcemod.net/" | ||
− | };</ | + | };</sourcepawn> |
=Getting code to run= | =Getting code to run= | ||
− | We already include SourceMod features and filled up or plugin info. We now have a perfectly well formed plugin which can be compiled and loaded by SourceMod. However, there is one problem - it does nothing. You might be tempted to just start writing a code after <tt>myinfo</tt> declaration just to see that it will not compile. SourcePawn, unlike other scripting languages like Lua, does not allow a code to be outside of functions. After reading that, you may probably want to just define some function, name it <tt>main</tt> probably, compile and load a plugin and see that your code never gets called. So how do we make SourceMod call our code? For this exact reason we have forwards. Forwards are function prototypes declared by one party that can be implemented by another party as a [http://en.wikipedia.org/wiki/Callback_%28computer_programming%29 callback]. When a first party starts a forward call, all parties that have matching callbacks receive the call. SourceMod declares a plenty of interesting forwards that we can implement. As you can see, forwards are the only way to get our code executed, keep that in mind. So let's implement <tt>OnPluginStart</tt> forward. As you may have guessed, it is called when our plugin starts. To do that, we'll have to look up the declaration of <tt>OnPluginStart</tt>. It is declared inside '''sourcemod.inc''', a file we are already familiar with, let's find it: | + | We already include SourceMod features and filled up or plugin info. We now have a perfectly well-formed plugin which can be compiled and loaded by SourceMod. However, there is one problem - it does nothing. You might be tempted to just start writing a code after <tt>myinfo</tt> declaration just to see that it will not compile. SourcePawn, unlike other scripting languages like Lua, does not allow a code to be outside of functions. After reading that, you may probably want to just define some function, name it <tt>main</tt> probably, compile and load a plugin and see that your code never gets called. So how do we make SourceMod call our code? For this exact reason, we have forwards. Forwards are function prototypes declared by one party that can be implemented by another party as a [http://en.wikipedia.org/wiki/Callback_%28computer_programming%29 callback]. When a first party starts a forward call, all parties that have matching callbacks receive the call. SourceMod declares a plenty of interesting forwards that we can implement. As you can see, forwards are the only way to get our code executed, keep that in mind. So let's implement <tt>OnPluginStart</tt> forward. As you may have guessed, it is called when our plugin starts. To do that, we'll have to look up the declaration of <tt>OnPluginStart</tt>. It is declared inside '''sourcemod.inc''', a file we are already familiar with, let's find it: |
− | < | + | <sourcepawn>/** |
* Called when the plugin is fully initialized and all known external references | * Called when the plugin is fully initialized and all known external references | ||
* are resolved. This is only called once in the lifetime of the plugin, and is | * are resolved. This is only called once in the lifetime of the plugin, and is | ||
Line 74: | Line 74: | ||
* @noreturn | * @noreturn | ||
*/ | */ | ||
− | forward OnPluginStart();</ | + | forward void OnPluginStart();</sourcepawn> |
− | Empty parentheses | + | Empty parentheses tell us that no arguments are passed inside this forward, <tt>@noreturn</tt> inside documentation tells us that we don't have to return anything, pretty simple forward. So how to write a correct callback for it? Firstly, our callback must have the same name, so it's <tt>OnPluginStart</tt>, secondly, our callback should have the same number of arguments, none in this case, and lastly, SourceMod needs to be able to call our callback so it needs to be <tt>public</tt>. So the implementation looks like this: |
− | < | + | <sourcepawn>public void OnPluginStart() |
{ | { | ||
− | }</ | + | }</sourcepawn> |
Now we can write code inside curly braces and it will be executed when our plugin starts. Let's output <tt>"Hello world!"</tt> to server console. To do that we are going to use <tt>PrintToServer</tt> function. It is declared inside '''console.inc''', however, we don't need to manually include '''console.inc''' because it is included automatically as part of '''sourcemod.inc'''. | Now we can write code inside curly braces and it will be executed when our plugin starts. Let's output <tt>"Hello world!"</tt> to server console. To do that we are going to use <tt>PrintToServer</tt> function. It is declared inside '''console.inc''', however, we don't need to manually include '''console.inc''' because it is included automatically as part of '''sourcemod.inc'''. | ||
− | < | + | <sourcepawn>/** |
* Sends a message to the server console. | * Sends a message to the server console. | ||
* | * | ||
Line 88: | Line 88: | ||
* @noreturn | * @noreturn | ||
*/ | */ | ||
− | native PrintToServer(const | + | native int PrintToServer(const char[] format, any ...);</sourcepawn> |
As you can see, this is a native function. It is implemented inside SM core. Judging by it's arguments, we can see that it is a [[Format_Class_Functions_%28SourceMod_Scripting%29|format class function]]. However, we don't need any formatting right now, so let's just pass <tt>"Hello world!"</tt> string as an only argument: | As you can see, this is a native function. It is implemented inside SM core. Judging by it's arguments, we can see that it is a [[Format_Class_Functions_%28SourceMod_Scripting%29|format class function]]. However, we don't need any formatting right now, so let's just pass <tt>"Hello world!"</tt> string as an only argument: | ||
− | < | + | <sourcepawn>public void OnPluginStart() |
{ | { | ||
PrintToServer("Hello world!"); | PrintToServer("Hello world!"); | ||
− | }</ | + | }</sourcepawn> |
That's it! The full code of your plugin should look like this: | That's it! The full code of your plugin should look like this: | ||
− | < | + | <sourcepawn>#include <sourcemod> |
− | public Plugin | + | public Plugin myinfo = |
{ | { | ||
name = "My First Plugin", | name = "My First Plugin", | ||
Line 106: | Line 106: | ||
}; | }; | ||
− | public OnPluginStart() | + | public void OnPluginStart() |
{ | { | ||
PrintToServer("Hello world!"); | PrintToServer("Hello world!"); | ||
− | }</ | + | }</sourcepawn> |
− | Compile and load your plugin on your server and see for yourself that the message is displayed in | + | Compile and load your plugin on your server and see for yourself that the message is displayed in the server console. |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
=Includes= | =Includes= | ||
Line 230: | Line 124: | ||
==Declaration== | ==Declaration== | ||
− | First, let's look at what an admin command requires. Admin commands are registered using the [ | + | First, let's look at what an admin command requires. Admin commands are registered using the [https://sm.alliedmods.net/new-api/console/RegAdminCmd RegAdminCmd] function. They require a '''name''', a '''callback function''', and '''default admin flags'''. |
− | The callback function is what's invoked every time the command is used. [ | + | The callback function is what's invoked every time the command is used. [https://sm.alliedmods.net/new-api/console/ConCmd Click here] to see its prototype. Example: |
− | < | + | <sourcepawn> |
− | public OnPluginStart() | + | public void OnPluginStart() |
{ | { | ||
RegAdminCmd("sm_myslap", Command_MySlap, ADMFLAG_SLAY); | RegAdminCmd("sm_myslap", Command_MySlap, ADMFLAG_SLAY); | ||
} | } | ||
− | public Action | + | public Action Command_MySlap(int client, int args) |
{ | { | ||
− | }</ | + | }</sourcepawn> |
− | Now we've successfully implemented a command -- though it doesn't do anything yet. In fact, it will say "Unknown command" if you use it! The reason is because of the | + | Now we've successfully implemented a command -- though it doesn't do anything yet. In fact, it will say "Unknown command" if you use it! This is because you're not returning Plugin_Handled in your callback. Since you haven't, SourceMod believes you didn't want the Source Engine to know the command was registered, and it handles it so. The reason SourceMod expects your function to return Plugin_Handled is because of the Action tag you put in your function's prototype. The Action tag specifies that Command_MySlap must return one of four things. See the [https://sm.alliedmods.net/new-api/core/Action Action] enumeration in the sourcemod API to learn more about these return types and when to use them. |
− | < | + | <sourcepawn>public Action Command_MySlap(int client, int args) |
{ | { | ||
return Plugin_Handled; | return Plugin_Handled; | ||
− | }</ | + | }</sourcepawn> |
Now the command will report no error, but it still won't do anything. This is because returning "Plugin_Handled" in a command callback will prevent the engine from processing the command. The engine will never even see that the command was run. This is what you will want to do if you are registering a completely new command through SourceMod. | Now the command will report no error, but it still won't do anything. This is because returning "Plugin_Handled" in a command callback will prevent the engine from processing the command. The engine will never even see that the command was run. This is what you will want to do if you are registering a completely new command through SourceMod. | ||
Line 258: | Line 152: | ||
To implement this, we'll need a few steps: | To implement this, we'll need a few steps: | ||
− | *Get the input from the console. For this we use [ | + | *Get the input from the console. For this we use [https://sm.alliedmods.net/new-api/console/GetCmdArg GetCmdArg()]. |
− | *Find a matching player. For this we use [ | + | *Find a matching player. For this we use [https://sm.alliedmods.net/new-api/helpers/FindTarget FindTarget()]. |
− | *Slap them. For this we use [ | + | *Slap them. For this we use [https://sm.alliedmods.net/new-api/sdktools_functions/SlapPlayer SlapPlayer()], which requires including <tt>sdktools</tt>, an extension bundled with SourceMod. |
− | *Respond to the admin. For this we use [ | + | *Respond to the admin. For this we use [https://sm.alliedmods.net/new-api/console/ReplyToCommand ReplyToCommand()]. |
Full example: | Full example: | ||
− | < | + | <sourcepawn> |
#include <sourcemod> | #include <sourcemod> | ||
#include <sdktools> | #include <sdktools> | ||
− | public Plugin | + | public Plugin myinfo = |
{ | { | ||
name = "My First Plugin", | name = "My First Plugin", | ||
Line 278: | Line 172: | ||
} | } | ||
− | public OnPluginStart() | + | public void OnPluginStart() |
{ | { | ||
RegAdminCmd("sm_myslap", Command_MySlap, ADMFLAG_SLAY); | RegAdminCmd("sm_myslap", Command_MySlap, ADMFLAG_SLAY); | ||
+ | LoadTranslations("common.phrases.txt"); // Required for FindTarget fail reply | ||
} | } | ||
− | public Action | + | public Action Command_MySlap(int client, int args) |
{ | { | ||
− | + | char arg1[32], arg2[32]; | |
− | + | ||
+ | /* By default, we set damage = 0 */ | ||
+ | int damage = 0; | ||
/* Get the first argument */ | /* Get the first argument */ | ||
GetCmdArg(1, arg1, sizeof(arg1)); | GetCmdArg(1, arg1, sizeof(arg1)); | ||
− | /* If there are 2 or more arguments, | + | /* If there are 2 or more arguments, we set damage to |
− | * | + | * what the user specified. If a damage isn't specified |
− | + | * then it will stay zero. */ | |
− | if (args >= 2 | + | if (args >= 2) |
{ | { | ||
+ | GetCmdArg(2, arg2, sizeof(arg2)); | ||
damage = StringToInt(arg2); | damage = StringToInt(arg2); | ||
} | } | ||
/* Try and find a matching player */ | /* Try and find a matching player */ | ||
− | + | int target = FindTarget(client, arg1); | |
if (target == -1) | if (target == -1) | ||
{ | { | ||
/* FindTarget() automatically replies with the | /* FindTarget() automatically replies with the | ||
− | * failure reason | + | * failure reason and returns -1 so we know not |
+ | * to continue | ||
*/ | */ | ||
return Plugin_Handled; | return Plugin_Handled; | ||
Line 310: | Line 209: | ||
SlapPlayer(target, damage); | SlapPlayer(target, damage); | ||
− | + | ReplyToCommand(client, "[SM] You slapped %N for %d damage!", target, damage); | |
− | |||
− | |||
− | |||
− | ReplyToCommand(client, "[SM] You slapped % | ||
return Plugin_Handled; | return Plugin_Handled; | ||
− | }</ | + | }</sourcepawn> |
− | For more information on what % | + | For more information on what %N and %d are, see [[Format Class Functions (SourceMod Scripting)|Format Class Functions]]. Note that you never need to unregister or remove your admin command. When a plugin is unloaded, SourceMod cleans it up for you. |
=ConVars= | =ConVars= | ||
ConVars, also known as cvars, are global console variables in the Source engine. They can have integer, float, or string values. ConVar accessing is done through [[Handles (SourceMod Scripting)|Handles]]. Since ConVars are global, you do not need to close ConVar Handles (in fact, you cannot). | ConVars, also known as cvars, are global console variables in the Source engine. They can have integer, float, or string values. ConVar accessing is done through [[Handles (SourceMod Scripting)|Handles]]. Since ConVars are global, you do not need to close ConVar Handles (in fact, you cannot). | ||
− | The handy feature of ConVars is that they are easy for users to configure. They can be placed in any .cfg file, such as <tt>server.cfg</tt> or <tt>sourcemod.cfg</tt>. To make this easier, SourceMod has an [ | + | The handy feature of ConVars is that they are easy for users to configure. They can be placed in any .cfg file, such as <tt>server.cfg</tt> or <tt>sourcemod.cfg</tt>. To make this easier, SourceMod has an [https://sm.alliedmods.net/new-api/sourcemod/AutoExecConfig AutoExecConfig()] function. This function will automatically build a default .cfg file containing all of your cvars, annotated with comments, for users. It is highly recommended that you call this if you have customizable ConVars. |
− | Let's extend your example from earlier with a new ConVar. Our ConVar will be <tt> | + | Let's extend your example from earlier with a new ConVar. Our ConVar will be <tt>g_cvarMySlapDamage</tt> and will specify the default damage someone is slapped for if no damage is specified. |
− | < | + | <sourcepawn>ConVar g_cvarMySlapDamage = null; |
− | public OnPluginStart() | + | public void OnPluginStart() |
{ | { | ||
RegAdminCmd("sm_myslap", Command_MySlap, ADMFLAG_SLAY); | RegAdminCmd("sm_myslap", Command_MySlap, ADMFLAG_SLAY); | ||
− | + | g_cvarMySlapDamage = CreateConVar("sm_myslap_damage", "5", "Default slap damage"); | |
AutoExecConfig(true, "plugin_myslap"); | AutoExecConfig(true, "plugin_myslap"); | ||
} | } | ||
− | public Action | + | public Action Command_MySlap(int client, int args) |
{ | { | ||
− | + | char arg1[32], arg2[32]; | |
− | + | int damage = g_cvarMySlapDamage.IntValue; | |
/* The rest remains unchanged! */ | /* The rest remains unchanged! */ | ||
− | </ | + | </sourcepawn> |
=Showing Activity, Logging= | =Showing Activity, Logging= | ||
− | Almost all admin commands should log their activity, and some admin commands should show their activity to in-game clients. This can be done via the [ | + | Almost all admin commands should log their activity, and some admin commands should show their activity to in-game clients. This can be done via the [https://sm.alliedmods.net/new-api/logging/LogAction LogAction()] and [https://sm.alliedmods.net/new-api/console/ShowActivity2 ShowActivity2()] functions. The exact functionality of ShowActivity2() is determined by the <tt>sm_show_activity</tt> cvar. |
For example, let's rewrite the last few lines of our slap command: | For example, let's rewrite the last few lines of our slap command: | ||
− | < | + | <sourcepawn> |
SlapPlayer(target, damage); | SlapPlayer(target, damage); | ||
− | + | char name[MAX_NAME_LENGTH]; | |
GetClientName(target, name, sizeof(name)); | GetClientName(target, name, sizeof(name)); | ||
Line 362: | Line 257: | ||
return Plugin_Handled; | return Plugin_Handled; | ||
} | } | ||
− | </ | + | </sourcepawn> |
=Multiple Targets= | =Multiple Targets= | ||
To fully complete our slap demonstration, let's make it support multiple targets. SourceMod's [[Admin_Commands_%28SourceMod%29#How_to_Target|targeting system]] is quite advanced, so using it may seem complicated at first. | To fully complete our slap demonstration, let's make it support multiple targets. SourceMod's [[Admin_Commands_%28SourceMod%29#How_to_Target|targeting system]] is quite advanced, so using it may seem complicated at first. | ||
− | The function we use is [ | + | The function we use is [https://sm.alliedmods.net/new-api/commandfilters/ProcessTargetString ProcessTargetString()]. It takes in input from the console and returns a list of matching clients. It also returns a noun that will identify either a single client or describe a list of clients. The idea is that each client is then processed, but the activity shown to all players is only processed once. This reduces screen spam. |
− | This method of target processing is used for almost every admin command in SourceMod, and in fact FindTarget() is just a simplified version. | + | This method of target processing is used for almost every admin command in SourceMod, and in fact, FindTarget() is just a simplified version. |
Full, final example: | Full, final example: | ||
− | < | + | <sourcepawn> |
#include <sourcemod> | #include <sourcemod> | ||
#include <sdktools> | #include <sdktools> | ||
− | + | ConVar g_cvarMySlapDamage = null; | |
− | public Plugin | + | public Plugin myinfo = |
{ | { | ||
name = "My First Plugin", | name = "My First Plugin", | ||
Line 387: | Line 282: | ||
} | } | ||
− | public OnPluginStart() | + | public void OnPluginStart() |
{ | { | ||
− | |||
RegAdminCmd("sm_myslap", Command_MySlap, ADMFLAG_SLAY); | RegAdminCmd("sm_myslap", Command_MySlap, ADMFLAG_SLAY); | ||
+ | LoadTranslations("common.phrases.txt"); | ||
− | + | g_cvarMySlapDamage = CreateConVar("sm_myslap_damage", "5", "Default slap damage"); | |
AutoExecConfig(true, "plugin_myslap"); | AutoExecConfig(true, "plugin_myslap"); | ||
} | } | ||
− | public Action | + | public Action Command_MySlap(int client, int args) |
{ | { | ||
− | + | char arg1[32], arg2[32]; | |
− | + | int damage = g_cvarMySlapDamage.IntValue; | |
/* Get the first argument */ | /* Get the first argument */ | ||
Line 418: | Line 313: | ||
* tn_is_ml - stores whether the noun must be translated | * tn_is_ml - stores whether the noun must be translated | ||
*/ | */ | ||
− | + | char target_name[MAX_TARGET_LENGTH]; | |
− | + | int target_list[MAXPLAYERS], target_count; | |
− | + | bool tn_is_ml; | |
if ((target_count = ProcessTargetString( | if ((target_count = ProcessTargetString( | ||
Line 437: | Line 332: | ||
} | } | ||
− | for ( | + | for (int i = 0; i < target_count; i++) |
{ | { | ||
SlapPlayer(target_list[i], damage); | SlapPlayer(target_list[i], damage); | ||
Line 453: | Line 348: | ||
return Plugin_Handled; | return Plugin_Handled; | ||
− | }</ | + | }</sourcepawn> |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
=Events= | =Events= | ||
Line 477: | Line 356: | ||
*They are almost always informational. That is, blocking <tt>player_death</tt> will not stop a player from dying. It may block a HUD or console message or something else minor. | *They are almost always informational. That is, blocking <tt>player_death</tt> will not stop a player from dying. It may block a HUD or console message or something else minor. | ||
*They almost always use userids instead of client indexes. | *They almost always use userids instead of client indexes. | ||
− | *Just because it is in a resource file does not mean it is ever called, or works the way you expect it to. Mods are notorious | + | *Just because it is in a resource file does not mean it is ever called, or works the way you expect it to. Mods are notorious for not properly documenting their event functionality. |
An example of finding when a player dies: | An example of finding when a player dies: | ||
− | < | + | <sourcepawn> |
− | public OnPluginStart() | + | public void OnPluginStart() |
{ | { | ||
HookEvent("player_death", Event_PlayerDeath); | HookEvent("player_death", Event_PlayerDeath); | ||
} | } | ||
− | public Event_PlayerDeath( | + | public void Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast) |
{ | { | ||
− | + | int victim_id = event.GetInt("userid"); | |
− | + | int attacker_id = event.GetInt("attacker"); | |
− | + | int victim = GetClientOfUserId(victim_id); | |
− | + | int attacker = GetClientOfUserId(attacker_id); | |
/* CODE */ | /* CODE */ | ||
− | }</ | + | }</sourcepawn> |
=Callback Orders and Pairing= | =Callback Orders and Pairing= | ||
− | SourceMod has a number of builtin callbacks about the state of the server and plugin. Some of these are paired in special ways which | + | SourceMod has a number of builtin callbacks about the state of the server and plugin. Some of these are paired in special ways which can confuse users. |
==Pairing== | ==Pairing== | ||
'''Pairing''' is SourceMod terminology. Examples of it are: | '''Pairing''' is SourceMod terminology. Examples of it are: | ||
*OnMapEnd() cannot be called without an OnMapStart(), and if OnMapStart() is called, it cannot be called again without an OnMapEnd(). | *OnMapEnd() cannot be called without an OnMapStart(), and if OnMapStart() is called, it cannot be called again without an OnMapEnd(). | ||
− | *OnClientConnected(N) for a given client N will only be called once | + | *OnClientConnected(N) for a given client N will only be called once until an OnClientDisconnected(N) for the same client N is called (which is guaranteed to happen). |
There is a formal definition of SourceMod's pairing. For two functions X and Y, both with input A, the following conditions hold: | There is a formal definition of SourceMod's pairing. For two functions X and Y, both with input A, the following conditions hold: | ||
Line 514: | Line 393: | ||
These callbacks are listed in the order they are called, in the lifetime of a plugin and the server. | These callbacks are listed in the order they are called, in the lifetime of a plugin and the server. | ||
− | * | + | * {{SourceMod API|file=sourcemod|function=AskPluginLoad2}} - Called once, immediately after the plugin is loaded from the disk. This function can be used to stop a plugin from loading and return a custom error message; return APLRes_Failure and use strcopy on to replace the error string. All CreateNative and RegPluginLibrary calls should be done here. |
− | * | + | * {{SourceMod API|file=sourcemod|function=OnPluginStart}} - Called once, after the plugin has been fully initialized and can proceed to load. Any run-time errors in this function will cause the plugin to fail to load. '''This is paired with OnPluginEnd()'''. |
− | * | + | * {{SourceMod API|file=sourcemod|function=OnAllPluginsLoaded}} - Called once, after all non-late loaded plugins have called OnPluginStart. |
− | * | + | * {{SourceMod API|file=sourcemod|function=OnMapStart}} - Called every time the map loads. If the plugin is loaded late, and the map has already started, this function is called anyway after load, in order to preserve pairing. '''This function is paired with OnMapEnd().''' |
+ | * {{SourceMod API|file=sourcemod|function=OnConfigsExecuted}} - Called once per map-change after <tt>servercfgfile</tt> (usually <tt>server.cfg</tt>), <tt>sourcemod.cfg</tt>, and all plugin config files have finished executing. If a plugin is loaded after this has happened, the callback is called anyway, in order to preserve pairing. '''This function is paired with OnMapEnd().''' | ||
*At this point, most game callbacks can occur, such as events and callbacks involving clients (or other things, like OnGameFrame). | *At this point, most game callbacks can occur, such as events and callbacks involving clients (or other things, like OnGameFrame). | ||
− | * | + | * {{SourceMod API|file=sourcemod|function=OnMapEnd}} - Called when the map is about to end. At this point, all clients are disconnected, but <tt>TIMER_NO_MAPCHANGE</tt> timers are not yet destroyed. '''This function is paired to OnMapStart().''' |
− | * | + | * {{SourceMod API|file=sourcemod|function=OnPluginEnd}} - Called once, immediately before the plugin is unloaded. '''This function is paired to OnPluginStart().''' |
==Client Callbacks== | ==Client Callbacks== | ||
These callbacks are listed in no specific order, however, their documentation holds for both fake and real clients. | These callbacks are listed in no specific order, however, their documentation holds for both fake and real clients. | ||
− | * | + | * {{SourceMod API|file=clients|function=OnClientConnect}} - Called when a player initiates a connection. You can block a player from connecting by returning <code>Plugin_Stop</code> and setting rejectmsg to an error message. |
− | * | + | * {{SourceMod API|file=clients|function=OnClientConnected}} - Called after a player connects. Signifies that the player is connected and {{SourceMod API|file=clients|function=IsClientConnected}} will return true. '''This is paired with <code>OnClientDisconnect</code> for successful connections only.''' |
− | * | + | *{{SourceMod API|file=clients|function=OnClientAuthorized}} - Called when a player gets a Steam ID. It is important to note that this may never be called. It may occur any time in between <code>OnClientConnected</code> and <code>OnClientPreAdminCheck</code>/<code>OnClientDisconnect</code>. Do not rely on it unless you are writing something that needs Steam IDs, and even then you should use <code>OnClientPostAdminCheck</code>. |
− | * | + | * {{SourceMod API|file=clients|function=OnClientPutInServer}} - Signifies that the player is fully in-game and {{SourceMod API|file=clients|function=IsClientInGame}} will return true. |
− | * | + | ** If you want to check if the player is in-game, you just need to call this; {{SourceMod API|file=clients|function=IsClientConnected}} will also be true if this is (but not the other way around - a player may be connected but not in-game yet). |
− | + | * {{SourceMod API|file=clients|function=OnClientPostAdminCheck}} - Called after the player is '''both authorized and in-game'''. This is the best callback for checking administrative access after connect. | |
− | * | + | * {{SourceMod API|file=clients|function=OnClientDisconnect}} - Called when a player's disconnection starts. '''This is paired to <code>OnClientConnected</code>.''' |
− | * | + | * {{SourceMod API|file=clients|function=OnClientDisconnect_Post}} - Called when a player's disconnection ends. '''This is paired to <code>OnClientConnected</code>.''' |
− | * | ||
=Frequently Asked Questions= | =Frequently Asked Questions= | ||
Line 554: | Line 433: | ||
All clients are fully disconnected before the map changes. They are all reconnected after the next map starts. | All clients are fully disconnected before the map changes. They are all reconnected after the next map starts. | ||
+ | If you only want to detect when a client initially connects or leaves your server, hook the [[Generic Source Server Events#player_connect|player_connect]] or [[Generic Source Server Events#player_disconnect|player_disconnect]] events respectively. | ||
+ | |||
+ | ==Why am I getting "function prototypes do not match" errors?== | ||
+ | When you see this error, you'll most likely find that the issue comes from any callback functions referenced in the line(s) that are causing the error. | ||
+ | |||
+ | When you call a function that takes another function as a callback, the callback function must be declared with the correct number of parameter and return types. | ||
+ | |||
+ | For example, [https://sm.alliedmods.net/new-api/console/RegConsoleCmd <tt>RegConsoleCommand</tt>] must be called with a callback that has with the exact arguments and return type as specified by the [https://sm.alliedmods.net/new-api/console/ConCmd <tt>ConCmd</tt>] definition. | ||
+ | |||
+ | ==When do I need to manually unhook things?== | ||
+ | You only need to do so when you do not want the callback to fire anymore while the plugin is running. SourceMod itself, as well as extensions such as SDKHooks, unhooks entities and players when they are removed and disconnected, respectively. Everything a plugin hooks is unhooked when it is unloaded. | ||
+ | |||
+ | == Why am I seeing references to <tt>STEAM_ID_STOP_IGNORING_RETVALS</tt>? == | ||
+ | When {{SourceMod API|file=clients|function=GetClientAuthId}} is called and returns <tt>false</tt>, the buffer that should have the client's auth id is populated with <tt>STEAM_ID_STOP_IGNORING_RETVALS</tt>, both to clear the previous contents of the buffer (thereby preventing accidental reuse of old values) and to inform the developer to stop ignoring the return value of the <code>GetClientAuthId</code> call. | ||
+ | |||
+ | == Will SourceMod support Source 2? Will plugins for existing games continue to work if they are ported? == | ||
+ | The engine already exists; Metamod:Source works to some extent. Further reverse engineering efforts are required to get Metamod:Source in a stable state before work can even start on SourceMod. | ||
+ | |||
+ | No decision has been made yet on if development will be focused on bringing SourceMod to Source 2, on creating a successor scripting ecosystem much like SourceMod was to [[AMX Mod X]], or on extending VScript functionality. | ||
+ | |||
+ | It's safe to say that SourceMod will currently not work on the day of release for any games powered by Source 2. | ||
+ | |||
+ | Notes as of the initial limited testing phase for Counter-Strike 2: | ||
+ | |||
+ | * <code>-dedicated</code> allows for the creation of listen servers. | ||
+ | * The VSP plugin / VDF loading capabilities have been removed. [[Installing_Metamod:Source#GameInfo|Metamod:Source needs to be loaded as a GameDLL.]] | ||
+ | |||
+ | Keep in mind that this is an ongoing development; nothing is ready for public use yet. | ||
=Further Reading= | =Further Reading= | ||
− | For further reading, see the "Scripting" section at the [http://docs.sourcemod.net/ SourceMod Documentation]. | + | For further reading, see the "Scripting" section at the [http://docs.sourcemod.net/ SourceMod Documentation], as well as [https://wiki.alliedmods.net/Scripting_FAQ_(SourceMod) Yak's FAQs on Scripting]. |
[[Category:SourceMod Scripting]] | [[Category:SourceMod Scripting]] | ||
{{LanguageSwitch}} | {{LanguageSwitch}} |
Latest revision as of 08:14, 23 March 2023
This guide will give you a basic introduction to writing a SourceMod plugin. If you are not familiar with the SourcePawn language, it is recommended that you at least briefly read the Introduction to SourcePawn article.
For information on compiling plugins, see Compiling SourceMod Plugins. You can use SPCode, Crimson Editor, PSPad, UltraEdit, Notepad++, TextPad, Pawn Studio, BasicPawn or any other text editor you're comfortable with to write plugins.
Contents
- 1 Starting from scratch
- 2 Setting up plugin info
- 3 Getting code to run
- 4 Includes
- 5 Commands
- 6 ConVars
- 7 Showing Activity, Logging
- 8 Multiple Targets
- 9 Events
- 10 Callback Orders and Pairing
- 11 Frequently Asked Questions
- 11.1 Are plugins reloaded every mapchange?
- 11.2 Do I need to call CloseHandle in OnPluginEnd?
- 11.3 Do I need to #include every individual .inc?
- 11.4 Why don't some events fire?
- 11.5 Do I need to CloseHandle timers?
- 11.6 Are clients disconnected on mapchange?
- 11.7 Why am I getting "function prototypes do not match" errors?
- 11.8 When do I need to manually unhook things?
- 11.9 Why am I seeing references to STEAM_ID_STOP_IGNORING_RETVALS?
- 11.10 Will SourceMod support Source 2? Will plugins for existing games continue to work if they are ported?
- 12 Further Reading
Starting from scratch
Open your favorite text editor and create a new empty file. When you have an empty file you can just start writing code using the core language, however, you will not be able to use any of SourceMod features because the compiler does not know about them. This is done deliberately so it is possible to use SourcePawn outside of SourceMod. But since we are writing a SourceMod plugin, it is a good idea to enable access to SourceMod features first. This is done using #include directive. It tells the compiler to "paste" the code from another file into yours.
#include <sourcemod>
How does this work? First of all, note that we enclosed file name into angle brackets. Angle brackets tell the compiler to look in the default include directory. By default, it is scripting/include. You can open it right now and see a lot of inc files there. Those are SourceMod include files that describe various functions, tags and other features available for SourceMod plugins. The files are plain-text and you are encouraged to read them. You will notice, however, that there's not much code in there, certainly not enough to implement all the great features of SourceMod, so where are they? They are implemented inside a SourceMod core which is written in C++ and is compiled into binary files which end up in bin directory. So how does your SourcePawn code and SM core link together if the compiler doesn't know about the existence of the latter? SourceMod include files are written specially, so they say that the implementation of functions is somewhere else. The compiler understands that and generates a special code that says that this function call is going outside. When SourceMod loads your plugin, it inspects these bits of code and substitutes it's own internal functions instead. This is called dynamic linking.
Setting up plugin info
Now that we got access to SourceMod features, it is time to set up the information that will be displayed via sm plugins list command. No one likes unnamed plugins. To do that we are going to look inside sourcemod.inc file and see the format that information should be declared. It's always helpful to look inside SM include files to find out information you don't know. There is also an API documentation but it can be outdated and it only has SM core files so if your plugin is going to use any third party extension or another plugin, you will have to study inc files. So, open sourcemod.inc and scroll down a bit until you see this:
/** * Plugin public information. */ struct Plugin { public const char[] name; /**< Plugin Name */ public const char[] description; /**< Plugin Description */ public const char[] author; /**< Plugin Author */ public const char[] version; /**< Plugin Version */ public const char[] url; /**< Plugin URL */ };
and this:
/** * Declare this as a struct in your plugin to expose its information. * Example: * * public Plugin myinfo = * { * name = "My Plugin", * //etc * }; */ public Plugin myinfo;
It tells us that we need to create a global public variable myinfo which must be of type Plugin which is a struct with 5 fields which themselves are strings. It may sound complicated for a beginner but it's easy. Let's go ahead and create one:
public Plugin myinfo = { name = "My First Plugin", author = "Me", description = "My first plugin ever", version = "1.0", url = "http://www.sourcemod.net/" };
The public keyword means that SourceMod will be able to directly access our variable. Plugin defines a type of our variable. myinfo is, obviously, a name of our variable as required by SourceMod. You see that we initialize it right away. This is the preferable way to fill out plugin info.
After that the full code of your plugin should look like this:
#include <sourcemod> public Plugin myinfo = { name = "My First Plugin", author = "Me", description = "My first plugin ever", version = "1.0", url = "http://www.sourcemod.net/" };
Getting code to run
We already include SourceMod features and filled up or plugin info. We now have a perfectly well-formed plugin which can be compiled and loaded by SourceMod. However, there is one problem - it does nothing. You might be tempted to just start writing a code after myinfo declaration just to see that it will not compile. SourcePawn, unlike other scripting languages like Lua, does not allow a code to be outside of functions. After reading that, you may probably want to just define some function, name it main probably, compile and load a plugin and see that your code never gets called. So how do we make SourceMod call our code? For this exact reason, we have forwards. Forwards are function prototypes declared by one party that can be implemented by another party as a callback. When a first party starts a forward call, all parties that have matching callbacks receive the call. SourceMod declares a plenty of interesting forwards that we can implement. As you can see, forwards are the only way to get our code executed, keep that in mind. So let's implement OnPluginStart forward. As you may have guessed, it is called when our plugin starts. To do that, we'll have to look up the declaration of OnPluginStart. It is declared inside sourcemod.inc, a file we are already familiar with, let's find it:
/** * Called when the plugin is fully initialized and all known external references * are resolved. This is only called once in the lifetime of the plugin, and is * paired with OnPluginEnd(). * * If any run-time error is thrown during this callback, the plugin will be marked * as failed. * * It is not necessary to close any handles or remove hooks in this function. * SourceMod guarantees that plugin shutdown automatically and correctly releases * all resources. * * @noreturn */ forward void OnPluginStart();
Empty parentheses tell us that no arguments are passed inside this forward, @noreturn inside documentation tells us that we don't have to return anything, pretty simple forward. So how to write a correct callback for it? Firstly, our callback must have the same name, so it's OnPluginStart, secondly, our callback should have the same number of arguments, none in this case, and lastly, SourceMod needs to be able to call our callback so it needs to be public. So the implementation looks like this:
public void OnPluginStart() { }
Now we can write code inside curly braces and it will be executed when our plugin starts. Let's output "Hello world!" to server console. To do that we are going to use PrintToServer function. It is declared inside console.inc, however, we don't need to manually include console.inc because it is included automatically as part of sourcemod.inc.
/** * Sends a message to the server console. * * @param format Formatting rules. * @param ... Variable number of format parameters. * @noreturn */ native int PrintToServer(const char[] format, any ...);
As you can see, this is a native function. It is implemented inside SM core. Judging by it's arguments, we can see that it is a format class function. However, we don't need any formatting right now, so let's just pass "Hello world!" string as an only argument:
public void OnPluginStart() { PrintToServer("Hello world!"); }
That's it! The full code of your plugin should look like this:
#include <sourcemod> public Plugin myinfo = { name = "My First Plugin", author = "Me", description = "My first plugin ever", version = "1.0", url = "http://www.sourcemod.net/" }; public void OnPluginStart() { PrintToServer("Hello world!"); }
Compile and load your plugin on your server and see for yourself that the message is displayed in the server console.
Includes
Pawn requires include files, much like C requires header files. Include files list all of the structures, functions, callbacks, and tags that are available. There are three types of include files:
- Core - sourcemod.inc and anything it includes. These are all provided by SourceMod's Core.
- Extension - adds a dependency against a certain extension.
- Plugin - adds a dependency against a certain plugin.
Include files are loaded using the #include compiler directive.
Commands
Our first example will be writing a simple admin command to slap a player. We'll continue to extend this example with more features until we have a final, complete result.
Declaration
First, let's look at what an admin command requires. Admin commands are registered using the RegAdminCmd function. They require a name, a callback function, and default admin flags.
The callback function is what's invoked every time the command is used. Click here to see its prototype. Example:
public void OnPluginStart() { RegAdminCmd("sm_myslap", Command_MySlap, ADMFLAG_SLAY); } public Action Command_MySlap(int client, int args) { }
Now we've successfully implemented a command -- though it doesn't do anything yet. In fact, it will say "Unknown command" if you use it! This is because you're not returning Plugin_Handled in your callback. Since you haven't, SourceMod believes you didn't want the Source Engine to know the command was registered, and it handles it so. The reason SourceMod expects your function to return Plugin_Handled is because of the Action tag you put in your function's prototype. The Action tag specifies that Command_MySlap must return one of four things. See the Action enumeration in the sourcemod API to learn more about these return types and when to use them.
public Action Command_MySlap(int client, int args) { return Plugin_Handled; }
Now the command will report no error, but it still won't do anything. This is because returning "Plugin_Handled" in a command callback will prevent the engine from processing the command. The engine will never even see that the command was run. This is what you will want to do if you are registering a completely new command through SourceMod.
Implementation
Let's decide what the command will look like. Let's have it act like the default sm_slap command:
sm_myslap <name|#userid> [damage]
To implement this, we'll need a few steps:
- Get the input from the console. For this we use GetCmdArg().
- Find a matching player. For this we use FindTarget().
- Slap them. For this we use SlapPlayer(), which requires including sdktools, an extension bundled with SourceMod.
- Respond to the admin. For this we use ReplyToCommand().
Full example:
#include <sourcemod> #include <sdktools> public Plugin myinfo = { name = "My First Plugin", author = "Me", description = "My first plugin ever", version = "1.0.0.0", url = "http://www.sourcemod.net/" } public void OnPluginStart() { RegAdminCmd("sm_myslap", Command_MySlap, ADMFLAG_SLAY); LoadTranslations("common.phrases.txt"); // Required for FindTarget fail reply } public Action Command_MySlap(int client, int args) { char arg1[32], arg2[32]; /* By default, we set damage = 0 */ int damage = 0; /* Get the first argument */ GetCmdArg(1, arg1, sizeof(arg1)); /* If there are 2 or more arguments, we set damage to * what the user specified. If a damage isn't specified * then it will stay zero. */ if (args >= 2) { GetCmdArg(2, arg2, sizeof(arg2)); damage = StringToInt(arg2); } /* Try and find a matching player */ int target = FindTarget(client, arg1); if (target == -1) { /* FindTarget() automatically replies with the * failure reason and returns -1 so we know not * to continue */ return Plugin_Handled; } SlapPlayer(target, damage); ReplyToCommand(client, "[SM] You slapped %N for %d damage!", target, damage); return Plugin_Handled; }
For more information on what %N and %d are, see Format Class Functions. Note that you never need to unregister or remove your admin command. When a plugin is unloaded, SourceMod cleans it up for you.
ConVars
ConVars, also known as cvars, are global console variables in the Source engine. They can have integer, float, or string values. ConVar accessing is done through Handles. Since ConVars are global, you do not need to close ConVar Handles (in fact, you cannot).
The handy feature of ConVars is that they are easy for users to configure. They can be placed in any .cfg file, such as server.cfg or sourcemod.cfg. To make this easier, SourceMod has an AutoExecConfig() function. This function will automatically build a default .cfg file containing all of your cvars, annotated with comments, for users. It is highly recommended that you call this if you have customizable ConVars.
Let's extend your example from earlier with a new ConVar. Our ConVar will be g_cvarMySlapDamage and will specify the default damage someone is slapped for if no damage is specified.
ConVar g_cvarMySlapDamage = null; public void OnPluginStart() { RegAdminCmd("sm_myslap", Command_MySlap, ADMFLAG_SLAY); g_cvarMySlapDamage = CreateConVar("sm_myslap_damage", "5", "Default slap damage"); AutoExecConfig(true, "plugin_myslap"); } public Action Command_MySlap(int client, int args) { char arg1[32], arg2[32]; int damage = g_cvarMySlapDamage.IntValue; /* The rest remains unchanged! */
Showing Activity, Logging
Almost all admin commands should log their activity, and some admin commands should show their activity to in-game clients. This can be done via the LogAction() and ShowActivity2() functions. The exact functionality of ShowActivity2() is determined by the sm_show_activity cvar.
For example, let's rewrite the last few lines of our slap command:
SlapPlayer(target, damage); char name[MAX_NAME_LENGTH]; GetClientName(target, name, sizeof(name)); ShowActivity2(client, "[SM] ", "Slapped %s for %d damage!", name, damage); LogAction(client, target, "\"%L\" slapped \"%L\" (damage %d)", client, target, damage); return Plugin_Handled; }
Multiple Targets
To fully complete our slap demonstration, let's make it support multiple targets. SourceMod's targeting system is quite advanced, so using it may seem complicated at first.
The function we use is ProcessTargetString(). It takes in input from the console and returns a list of matching clients. It also returns a noun that will identify either a single client or describe a list of clients. The idea is that each client is then processed, but the activity shown to all players is only processed once. This reduces screen spam.
This method of target processing is used for almost every admin command in SourceMod, and in fact, FindTarget() is just a simplified version.
Full, final example:
#include <sourcemod> #include <sdktools> ConVar g_cvarMySlapDamage = null; public Plugin myinfo = { name = "My First Plugin", author = "Me", description = "My first plugin ever", version = "1.0.0.0", url = "http://www.sourcemod.net/" } public void OnPluginStart() { RegAdminCmd("sm_myslap", Command_MySlap, ADMFLAG_SLAY); LoadTranslations("common.phrases.txt"); g_cvarMySlapDamage = CreateConVar("sm_myslap_damage", "5", "Default slap damage"); AutoExecConfig(true, "plugin_myslap"); } public Action Command_MySlap(int client, int args) { char arg1[32], arg2[32]; int damage = g_cvarMySlapDamage.IntValue; /* Get the first argument */ GetCmdArg(1, arg1, sizeof(arg1)); /* If there are 2 or more arguments, and the second argument fetch * is successful, convert it to an integer. */ if (args >= 2 && GetCmdArg(2, arg2, sizeof(arg2))) { damage = StringToInt(arg2); } /** * target_name - stores the noun identifying the target(s) * target_list - array to store clients * target_count - variable to store number of clients * tn_is_ml - stores whether the noun must be translated */ char target_name[MAX_TARGET_LENGTH]; int target_list[MAXPLAYERS], target_count; bool tn_is_ml; if ((target_count = ProcessTargetString( arg1, client, target_list, MAXPLAYERS, COMMAND_FILTER_ALIVE, /* Only allow alive players */ target_name, sizeof(target_name), tn_is_ml)) <= 0) { /* This function replies to the admin with a failure message */ ReplyToTargetError(client, target_count); return Plugin_Handled; } for (int i = 0; i < target_count; i++) { SlapPlayer(target_list[i], damage); LogAction(client, target_list[i], "\"%L\" slapped \"%L\" (damage %d)", client, target_list[i], damage); } if (tn_is_ml) { ShowActivity2(client, "[SM] ", "Slapped %t for %d damage!", target_name, damage); } else { ShowActivity2(client, "[SM] ", "Slapped %s for %d damage!", target_name, damage); } return Plugin_Handled; }
Events
Events are informational notification messages passed between objects in the server. Many are also passed from the server to the client. They are defined in .res files under the hl2/resource folder and resource folders of specific mods. For a basic listing, see Source Game Events.
It is important to note a few concepts about events:
- They are almost always informational. That is, blocking player_death will not stop a player from dying. It may block a HUD or console message or something else minor.
- They almost always use userids instead of client indexes.
- Just because it is in a resource file does not mean it is ever called, or works the way you expect it to. Mods are notorious for not properly documenting their event functionality.
An example of finding when a player dies:
public void OnPluginStart() { HookEvent("player_death", Event_PlayerDeath); } public void Event_PlayerDeath(Event event, const char[] name, bool dontBroadcast) { int victim_id = event.GetInt("userid"); int attacker_id = event.GetInt("attacker"); int victim = GetClientOfUserId(victim_id); int attacker = GetClientOfUserId(attacker_id); /* CODE */ }
Callback Orders and Pairing
SourceMod has a number of builtin callbacks about the state of the server and plugin. Some of these are paired in special ways which can confuse users.
Pairing
Pairing is SourceMod terminology. Examples of it are:
- OnMapEnd() cannot be called without an OnMapStart(), and if OnMapStart() is called, it cannot be called again without an OnMapEnd().
- OnClientConnected(N) for a given client N will only be called once until an OnClientDisconnected(N) for the same client N is called (which is guaranteed to happen).
There is a formal definition of SourceMod's pairing. For two functions X and Y, both with input A, the following conditions hold:
- If X is invoked with input A, it cannot be invoked again with the same input unless Y is called with input A.
- If X is invoked with input A, it is guaranteed that Y will, at some point, be called with input A.
- Y cannot be invoked with any input A unless X was called first with input A.
- The relationship is described as, "X is paired with Y," and "Y is paired to X."
General Callbacks
These callbacks are listed in the order they are called, in the lifetime of a plugin and the server.
AskPluginLoad2
- Called once, immediately after the plugin is loaded from the disk. This function can be used to stop a plugin from loading and return a custom error message; return APLRes_Failure and use strcopy on to replace the error string. All CreateNative and RegPluginLibrary calls should be done here.OnPluginStart
- Called once, after the plugin has been fully initialized and can proceed to load. Any run-time errors in this function will cause the plugin to fail to load. This is paired with OnPluginEnd().OnAllPluginsLoaded
- Called once, after all non-late loaded plugins have called OnPluginStart.OnMapStart
- Called every time the map loads. If the plugin is loaded late, and the map has already started, this function is called anyway after load, in order to preserve pairing. This function is paired with OnMapEnd().OnConfigsExecuted
- Called once per map-change after servercfgfile (usually server.cfg), sourcemod.cfg, and all plugin config files have finished executing. If a plugin is loaded after this has happened, the callback is called anyway, in order to preserve pairing. This function is paired with OnMapEnd().- At this point, most game callbacks can occur, such as events and callbacks involving clients (or other things, like OnGameFrame).
OnMapEnd
- Called when the map is about to end. At this point, all clients are disconnected, but TIMER_NO_MAPCHANGE timers are not yet destroyed. This function is paired to OnMapStart().OnPluginEnd
- Called once, immediately before the plugin is unloaded. This function is paired to OnPluginStart().
Client Callbacks
These callbacks are listed in no specific order, however, their documentation holds for both fake and real clients.
OnClientConnect
- Called when a player initiates a connection. You can block a player from connecting by returningPlugin_Stop
and setting rejectmsg to an error message.OnClientConnected
- Called after a player connects. Signifies that the player is connected andIsClientConnected
will return true. This is paired withOnClientDisconnect
for successful connections only.OnClientAuthorized
- Called when a player gets a Steam ID. It is important to note that this may never be called. It may occur any time in betweenOnClientConnected
andOnClientPreAdminCheck
/OnClientDisconnect
. Do not rely on it unless you are writing something that needs Steam IDs, and even then you should useOnClientPostAdminCheck
.OnClientPutInServer
- Signifies that the player is fully in-game andIsClientInGame
will return true.- If you want to check if the player is in-game, you just need to call this;
IsClientConnected
will also be true if this is (but not the other way around - a player may be connected but not in-game yet).
- If you want to check if the player is in-game, you just need to call this;
OnClientPostAdminCheck
- Called after the player is both authorized and in-game. This is the best callback for checking administrative access after connect.OnClientDisconnect
- Called when a player's disconnection starts. This is paired toOnClientConnected
.OnClientDisconnect_Post
- Called when a player's disconnection ends. This is paired toOnClientConnected
.
Frequently Asked Questions
Are plugins reloaded every mapchange?
Plugins, by default, are not reloaded on mapchange unless their timestamp changes. This is a feature so plugin authors have more flexibility with the state of their plugins.
Do I need to call CloseHandle in OnPluginEnd?
No. SourceMod automatically closes your Handles when your plugin is unloaded, in order to prevent memory errors.
Do I need to #include every individual .inc?
No. #include <sourcemod> will give you 95% of the .incs. Similarly, #include <sdktools> includes everything starting with <sdktools>.
Why don't some events fire?
There is no guarantee that events will fire. The event listing is not a specification, it is a list of the events that a game is capable of firing. Whether the game actually fires them is up to Valve or the developer.
Do I need to CloseHandle timers?
No. In fact, doing so may cause errors. Timers naturally die on their own unless they are infinite timers, in which case you can use KillTimer() or die gracefully by returning Plugin_Stop in the callback.
Are clients disconnected on mapchange?
All clients are fully disconnected before the map changes. They are all reconnected after the next map starts.
If you only want to detect when a client initially connects or leaves your server, hook the player_connect or player_disconnect events respectively.
Why am I getting "function prototypes do not match" errors?
When you see this error, you'll most likely find that the issue comes from any callback functions referenced in the line(s) that are causing the error.
When you call a function that takes another function as a callback, the callback function must be declared with the correct number of parameter and return types.
For example, RegConsoleCommand must be called with a callback that has with the exact arguments and return type as specified by the ConCmd definition.
When do I need to manually unhook things?
You only need to do so when you do not want the callback to fire anymore while the plugin is running. SourceMod itself, as well as extensions such as SDKHooks, unhooks entities and players when they are removed and disconnected, respectively. Everything a plugin hooks is unhooked when it is unloaded.
Why am I seeing references to STEAM_ID_STOP_IGNORING_RETVALS?
When GetClientAuthId
is called and returns false, the buffer that should have the client's auth id is populated with STEAM_ID_STOP_IGNORING_RETVALS, both to clear the previous contents of the buffer (thereby preventing accidental reuse of old values) and to inform the developer to stop ignoring the return value of the GetClientAuthId
call.
Will SourceMod support Source 2? Will plugins for existing games continue to work if they are ported?
The engine already exists; Metamod:Source works to some extent. Further reverse engineering efforts are required to get Metamod:Source in a stable state before work can even start on SourceMod.
No decision has been made yet on if development will be focused on bringing SourceMod to Source 2, on creating a successor scripting ecosystem much like SourceMod was to AMX Mod X, or on extending VScript functionality.
It's safe to say that SourceMod will currently not work on the day of release for any games powered by Source 2.
Notes as of the initial limited testing phase for Counter-Strike 2:
-dedicated
allows for the creation of listen servers.- The VSP plugin / VDF loading capabilities have been removed. Metamod:Source needs to be loaded as a GameDLL.
Keep in mind that this is an ongoing development; nothing is ready for public use yet.
Further Reading
For further reading, see the "Scripting" section at the SourceMod Documentation, as well as Yak's FAQs on Scripting.
Warning: This template (and by extension, language format) should not be used, any pages using it should be switched to Template:Languages | |
View this page in: English Russian 简体中文(Simplified Chinese) |