Sample Plugins
This page contains two small plugins and optional snippets. See Server plugins for the plugin system and loading commands. Use the build procedure from your introductory plugin tutorial.
Build each complete example separately. Replace the contents of the tutorial's myfirstplugin.cpp with one example and keep its VPC project. The DLL remains myfirstplugin.dll; the class name and version command do not change the output filename. To keep both plugins installed, create separate VPC projects with unique output names and VDF paths.
The complete examples and the combined optional snippets pass a GCC C++17 syntax-only check against Valve's SDK revision be57e3d01ac7d7aa6a2cacbfef187c0b46616db0. Windows linking and live-server behavior remain untested. Load before the first map.
Example 1: player rules from KeyValues
Prints a welcome message and handles cmd server_rules from a player's console. Configuration loads when the plugin starts and at each map change. A failed load keeps the previous rules.
Create <game>/cfg/rulesplugin.txt:
"RulesPlugin"
{
"rules" "Play fairly. Respect other players. Do not exploit map bugs."
}
Replace myfirstplugin.cpp:
#include "tier0/dbg.h"
#include "tier1/interface.h"
#include "tier1/tier1.h"
#include "tier1/convar.h"
#include "engine/iserverplugin.h"
#include "eiface.h"
#include "filesystem.h"
#include "tier1/strtools.h"
#include "tier0/memdbgon.h"
class CRulesPlugin final : public IServerPluginCallbacks
{
public:
bool Load(CreateInterfaceFn interfaceFactory,
CreateInterfaceFn gameServerFactory) override
{
ConnectTier1Libraries(&interfaceFactory, 1);
if (!g_pCVar)
{
Warning("[RulesPlugin] Could not acquire ICvar.\n");
DisconnectTier1Libraries();
return false;
}
m_Engine = static_cast<IVEngineServer *>(
interfaceFactory(INTERFACEVERSION_VENGINESERVER, nullptr));
m_Files = static_cast<IFileSystem *>(
interfaceFactory(FILESYSTEM_INTERFACE_VERSION, nullptr));
if (!m_Engine || !m_Files)
{
Warning("[RulesPlugin] Required interface unavailable.\n");
DisconnectTier1Libraries();
return false;
}
m_Paused = false;
ConVar_Register(0);
ReadRules();
Msg("[RulesPlugin] Loaded.\n");
return true;
}
void Unload() override
{
ConVar_Unregister();
DisconnectTier1Libraries();
Msg("[RulesPlugin] Unloaded.\n");
}
const char *GetPluginDescription() override
{
return "RulesPlugin 1.0";
}
void Pause() override { m_Paused = true; }
void UnPause() override { m_Paused = false; }
void LevelInit(const char *) override { ReadRules(); }
void ServerActivate(edict_t *, int, int) override {}
void GameFrame(bool) override {}
void LevelShutdown() override {}
void ClientActive(edict_t *player) override
{
if (!m_Paused && player && !player->IsFree())
m_Engine->ClientPrintf(player, "Type cmd server_rules in your console.\n");
}
void ClientDisconnect(edict_t *) override {}
void ClientPutInServer(edict_t *, const char *) override {}
void SetCommandClient(int) override {}
void ClientSettingsChanged(edict_t *) override {}
PLUGIN_RESULT ClientConnect(bool *, edict_t *, const char *,
const char *, char *, int) override
{
return PLUGIN_CONTINUE;
}
PLUGIN_RESULT ClientCommand(edict_t *player, const CCommand &args) override
{
if (m_Paused || !player || player->IsFree() || args.ArgC() < 1)
return PLUGIN_CONTINUE;
if (Q_stricmp(args[0], "server_rules"))
return PLUGIN_CONTINUE;
m_Engine->ClientPrintf(player, m_Rules);
return PLUGIN_STOP;
}
PLUGIN_RESULT NetworkIDValidated(const char *, const char *) override
{
return PLUGIN_CONTINUE;
}
void OnQueryCvarValueFinished(QueryCvarCookie_t, edict_t *,
EQueryCvarValueStatus, const char *,
const char *) override {}
void OnEdictAllocated(edict_t *) override {}
void OnEdictFreed(const edict_t *) override {}
private:
void ReadRules()
{
KeyValues *data = new KeyValues("RulesPlugin");
if (!data->LoadFromFile(m_Files, "cfg/rulesplugin.txt", "GAME"))
{
Warning("[RulesPlugin] Cannot read configuration; keeping current rules.\n");
data->deleteThis();
return;
}
const char *text = data->GetString("rules", "");
if (text[0] && Q_strlen(text) <= 400)
Q_snprintf(m_Rules, sizeof(m_Rules), "%s\n", text);
else
Warning("[RulesPlugin] Rules must contain 1 to 400 bytes.\n");
data->deleteThis();
}
IVEngineServer *m_Engine = nullptr;
IFileSystem *m_Files = nullptr;
bool m_Paused = false;
char m_Rules[512] = "Play fairly and respect other players.\n";
};
static CRulesPlugin g_RulesPlugin;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR(
CRulesPlugin,
IServerPluginCallbacks,
INTERFACEVERSION_ISERVERPLUGINCALLBACKS,
g_RulesPlugin);
CON_COMMAND(rulesplugin_version, "Print the RulesPlugin version.")
{
Msg("RulesPlugin 1.0\n");
}
Test: run rulesplugin_version in the server console, connect a player, then run cmd server_rules in the player's console. Output appears in the console, not the chat HUD.
Example 2: log player deaths
Listens for player_death and prints the connection userids. Event names and fields depend on the game. An attacker of 0 commonly represents the world; it is not a player slot.
Replace myfirstplugin.cpp with this separate example:
#include "tier0/dbg.h"
#include "tier1/interface.h"
#include "tier1/tier1.h"
#include "tier1/convar.h"
#include "engine/iserverplugin.h"
#include "igameevents.h"
#include "tier1/strtools.h"
#include "tier0/memdbgon.h"
class CDeathLogPlugin final : public IServerPluginCallbacks, public IGameEventListener2
{
public:
bool Load(CreateInterfaceFn interfaceFactory,
CreateInterfaceFn gameServerFactory) override
{
ConnectTier1Libraries(&interfaceFactory, 1);
if (!g_pCVar)
{
Warning("[DeathLogPlugin] Could not acquire ICvar.\n");
DisconnectTier1Libraries();
return false;
}
m_Events = static_cast<IGameEventManager2 *>(
interfaceFactory(INTERFACEVERSION_GAMEEVENTSMANAGER2, nullptr));
if (!m_Events)
{
DisconnectTier1Libraries();
return false;
}
m_Paused = false;
ConVar_Register(0);
Msg("[DeathLogPlugin] Loaded.\n");
return true;
}
void Unload() override
{
m_Events->RemoveListener(this);
ConVar_Unregister();
DisconnectTier1Libraries();
Msg("[DeathLogPlugin] Unloaded.\n");
}
const char *GetPluginDescription() override
{
return "DeathLogPlugin 1.0";
}
void Pause() override { m_Paused = true; }
void UnPause() override { m_Paused = false; }
void LevelInit(const char *) override {}
void ServerActivate(edict_t *, int, int) override
{
m_Events->RemoveListener(this);
if (!m_Events->AddListener(this, "player_death", true))
Warning("[DeathLogPlugin] player_death is unavailable.\n");
}
void GameFrame(bool) override {}
void LevelShutdown() override { m_Events->RemoveListener(this); }
void ClientActive(edict_t *) override {}
void ClientDisconnect(edict_t *) override {}
void ClientPutInServer(edict_t *, const char *) override {}
void SetCommandClient(int) override {}
void ClientSettingsChanged(edict_t *) override {}
PLUGIN_RESULT ClientConnect(bool *, edict_t *, const char *,
const char *, char *, int) override
{
return PLUGIN_CONTINUE;
}
PLUGIN_RESULT ClientCommand(edict_t *, const CCommand &) override
{
return PLUGIN_CONTINUE;
}
PLUGIN_RESULT NetworkIDValidated(const char *, const char *) override
{
return PLUGIN_CONTINUE;
}
void OnQueryCvarValueFinished(QueryCvarCookie_t, edict_t *,
EQueryCvarValueStatus, const char *,
const char *) override {}
void OnEdictAllocated(edict_t *) override {}
void OnEdictFreed(const edict_t *) override {}
void FireGameEvent(IGameEvent *event) override
{
if (m_Paused || !event || Q_stricmp(event->GetName(), "player_death"))
return;
Msg("[DeathLogPlugin] victim=%d attacker=%d\n",
event->GetInt("userid"), event->GetInt("attacker"));
}
private:
IGameEventManager2 *m_Events = nullptr;
bool m_Paused = false;
};
static CDeathLogPlugin g_DeathLogPlugin;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR(
CDeathLogPlugin,
IServerPluginCallbacks,
INTERFACEVERSION_ISERVERPLUGINCALLBACKS,
g_DeathLogPlugin);
CON_COMMAND(deathlog_version, "Print the DeathLogPlugin version.")
{
Msg("DeathLogPlugin 1.0\n");
}
Test: run deathlog_version, start a map, and cause a player death. Check the server console. The listener is removed on map shutdown and plugin unload. The event manager owns the event; do not delete it or retain its pointer.
Tips and snippets
These are additions to Example 1 unless stated otherwise. Put new includes before tier0/memdbgon.h, members inside the class, and interface acquisition inside Load. Replace existing callbacks rather than defining them twice.
Run periodic work without a busy loop
Include game/server/iplayerinfo.h. Add these members:
CGlobalVars *m_Globals = nullptr;
float m_NextUpdate = 0.0f;
In Load, before ConVar_Register, acquire the game DLL's globals:
IPlayerInfoManager *players = static_cast<IPlayerInfoManager *>(
gameServerFactory(INTERFACEVERSION_PLAYERINFOMANAGER, nullptr));
m_Globals = players ? players->GetGlobalVars() : nullptr;
if (!m_Globals)
{
DisconnectTier1Libraries();
return false;
}
Replace these callbacks:
void ServerActivate(edict_t *, int, int) override
{
m_NextUpdate = m_Globals->curtime + 10.0f;
}
void GameFrame(bool simulating) override
{
if (m_Paused || !simulating || m_Globals->curtime < m_NextUpdate)
return;
m_NextUpdate = m_Globals->curtime + 10.0f;
Msg("[RulesPlugin] Periodic update.\n");
}
This uses simulation time, not wall-clock time. A long pause produces one update when execution resumes, not a burst of catch-up calls. Keep disk reads and network requests out of this callback.
Save a small KeyValues file
Add this method inside the class and call it at a controlled checkpoint:
bool SaveRulesSnapshot()
{
m_Files->CreateDirHierarchy("data/rulesplugin", "DEFAULT_WRITE_PATH");
KeyValues *data = new KeyValues("RulesSnapshot");
data->SetInt("schema_version", 1);
data->SetString("rules", m_Rules);
bool saved = data->SaveToFile(m_Files,
"data/rulesplugin/snapshot.txt", "DEFAULT_WRITE_PATH");
data->deleteThis();
return saved;
}
Check the returned result. GAME searches mounted game paths; DEFAULT_WRITE_PATH selects the configured writable path. This is a basic snapshot, not a crash-safe database. Keep paths server-controlled.
KeyValues owns its strings and subkeys. Copy strings that must survive deleteThis(); do not delete owned subkeys separately.
Show a rules dialog
Add IServerPluginHelpers *m_Helpers = nullptr; to the class. Acquire it in Load:
m_Helpers = static_cast<IServerPluginHelpers *>(
interfaceFactory(INTERFACEVERSION_ISERVERPLUGINHELPERS, nullptr));
Add this method, then replace the rules command's ClientPrintf call with ShowRules(player):
void ShowRules(edict_t *player)
{
if (!m_Helpers)
{
m_Engine->ClientPrintf(player, m_Rules);
return;
}
KeyValues *dialog = new KeyValues("rules");
dialog->SetString("title", "Server rules");
dialog->SetString("msg", m_Rules);
dialog->SetInt("level", 1);
dialog->SetInt("time", 20);
m_Helpers->CreateMessage(player, DIALOG_TEXT, dialog, this);
dialog->deleteThis();
}
Client support varies. Keep a console alternative. Menu selections are client commands, not proof of administrator permission.
Add a dedicated-server admin command
Add int m_CommandClient = -2; to the class. Replace SetCommandClient and add the public method below:
void SetCommandClient(int index) override
{
m_CommandClient = index;
}
void AdminReload()
{
if (m_Paused || !m_Engine->IsDedicatedServer() || m_CommandClient != -1)
{
Warning("[RulesPlugin] Use the dedicated server console or RCON.\n");
return;
}
ReadRules();
}
After the global plugin object, add:
CON_COMMAND(rulesplugin_reload, "Reload rules from the dedicated server console or RCON.")
{
g_RulesPlugin.AdminReload();
}
This expects the target branch's -1 server-command origin convention. Test console, RCON, and attempted client invocation on your actual server. Other origins are denied; listen-server administration is deliberately unsupported here. RCON authentication belongs to the server.
For in-game admins, check a server-validated account ID against a server-owned allowlist on every privileged action. Never authorize by player name, client cvar, or a Steam ID supplied as command text.
Spawn an existing HL2DM health kit
Include toolframework/itoolentity.h. Add IServerTools *m_Tools = nullptr; to the class and acquire it from the game DLL in Load:
m_Tools = static_cast<IServerTools *>(
gameServerFactory(VSERVERTOOLS_INTERFACE_VERSION, nullptr));
Add this method:
bool SpawnHealthKit(const Vector &origin)
{
if (m_Paused || !m_Tools)
return false;
CBaseEntity *entity = m_Tools->CreateEntityByName("item_healthkit");
if (!entity)
return false;
if (!m_Tools->SetKeyValue(entity, "origin", origin))
{
m_Tools->RemoveEntity(entity);
return false;
}
m_Tools->DispatchSpawn(entity);
return true;
}
Call only while a map is active, after ServerActivate, from an authorized action. Supply a tested clear position; for dynamic placement, trace the surface and test the item's available space. Cap repeated spawns.
The class must exist in the target game. DispatchSpawn returns no success value, so true means the spawn was dispatched. Treat the entity pointer as opaque and do not use it afterward without revalidation. Test precaching and respawn behavior. This snippet leaves cleanup to the map; production plugins should track safe handles and clean up their own entities before unloading.
Useful rules
- Return
PLUGIN_CONTINUEfor commands you do not handle. ReturnPLUGIN_STOPonly for consumed commands. - A slot index, connection userid, and Steam account ID are different identifiers. Revalidate connections before delayed actions; slots can be reused.
- A death event observes a death. It cannot cancel the damage that caused it. Native VSP callbacks do not expose a general damage or movement hook.
- Use exported interfaces. Including
cbase.hdoes not make internal game-DLL functions available to a plugin. - Never concatenate player text into
ServerCommand. Prefer direct APIs or strictly validated arguments and predefined actions. - Use fixed log formats:
Msg("%s", text), notMsg(text). - Remove listeners and unregister commands before unload. Stop owned workers before their DLL code disappears.