Skip to content

halfMod API Overview

nigel edited this page Oct 6, 2018 · 70 revisions

This page aims to be a complete reference for the halfMod API.

Table of Contents

Events

Events are functions in a plugin that are called from halfMod when a server output line triggers them.

Returning a non-0 value from an event will tell halfMod to stop processing this line entirely. This means that if the second plugin returns 1 from the onWarnThread event, then only the first and second plugins' onWarnThread event will be called. If any plugin after the second one has an onWarnThread event, it will never be called.

The arguments passed to every event are the same. The first argument is the hmHandle class that contains the current plugin. The second argument is a regex smatch. The smatch will contain various pieces of info. The first index, [0], of the smatch will contain the full, unmodified line of server output that triggered the event. The following indexes will contain split info from the line in the order of appearance.

Full list of built in events:

Event Description smatch Arguments
int onPlayerConnect(hmHandle&,smatch); Called when a player connects 1 = player name, 2 = ip, 3 = port
int onPlayerAuth(hmHandle&,smatch); Called when a player is authorized 1 = Auth #, 2 = player name, 3 = uuid
int onPlayerJoin(hmHandle&,smatch); Called when a player has fully joined the server 1 = player name
int onWarnThread(hmHandle&,smatch); Called on all [Server thread/WARN] lines 1 = thread message
int onInfoThread(hmHandle&,smatch); Called on all [Server thread/INFO] lines 1 = thread message
int onServerShutdown(hmHandle&,smatch); Called on all [Server Shutdown Thread/INFO] lines 1 = shutdown message
int onServerShutdownPost(hmHandle&,smatch); Called when the Minecraft server has completely finished shutting down and is no longer running 1 = exit status
int onPlayerDisconnect(hmHandle&,smatch); Called when a player disconnects 1 = player name, 2 = reason
int onPlayerLeave(hmHandle&,smatch); Called when a player has fully left the server 1 = player name
int onPlayerAdvancement(hmHandle&,smatch); Called when a player completes an advancement 1 = player name, 2 = advancement
int onPlayerGoal(hmHandle&,smatch); Called when a player completes a goal 1 = player name, 2 = goal
int onPlayerChallenge(hmHandle&,smatch); Called when a player completes a challenge 1 = player name, 2 = challenge
int onPlayerAction(hmHandle&,smatch); Called when a player sends an action message (/me) 1 = player name, 2 = message
int onPlayerText(hmHandle&,smatch); Called when a player sends a message (/say) 1 = player name, 2 = message
int onFakePlayerText(hmHandle&,smatch); Called when an entity or non-existant player uses the /say command (when the name is wrapped in square brackets instead of angles) 1 = player name, 2 = message
int onPlayerDeath(hmHandle&,smatch); Called when a player dies 1 = player name, 2 = death message
int onWorldInit(hmHandle&,smatch); Called when the world has completely finished initializing 1 = world prep time
int onHShellConnect(hmHandle&,smatch); Called when halfMod has connected to halfShell 1 = halfShell version, 2 = minecraft screen name, 3 = minecraft version
int onGamerule(hmHandle&,smatch); Called when a gamerule is queried or changes 1 = gamerule, 2 = "now" (has changed) or "currently" (query), 3 = value
int onGlobalMessage(hmHandle&,smatch); Called when the hmSendMessageAll command is used from anywhere, after the message is sent 1 = message
int onPrintMessage(hmHandle&,smatch); Called when any somewhat private or server related message is printed to the console 1 = message
int onConsoleReceive(hmHandle&,smatch); Called every time any message is received from the server that does NOT match any HM_BLOCK_OUTPUT filters 0 = message
int onCustom1(hmHandle&,smatch) Called when a console filter registered to ID 168 finds a matching line
int onCustom2(hmHandle&,smatch) Called when a console filter registered to ID 176 finds a matching line
int onCustom3(hmHandle&,smatch) Called when a console filter registered to ID 184 finds a matching line
int onCustom4(hmHandle&,smatch) Called when a console filter registered to ID 192 finds a matching line
int onCustom5(hmHandle&,smatch) Called when a console filter registered to ID 200 finds a matching line

There are some exceptions to the events:

Event Description
int onPluginStart(hmHandle&,hmGlobal*); Called on plugin load. Return non-0 to prevent the plugin from loading
int onPluginsLoaded(hmHandle&); Called when all plugins have finished loading
void onPluginEnd(hmHandle&); Called on plugin unload
int onHShellDisconnect(hmHandle&); Called when halfMod has disconnected from halfShell
int onRehashFilter(hmHandle&); Called when the console filter file has been rehashed or hashed for the first time.

Events within Extensions:

Extensions only have an event for when they are loaded, for all other things, create a hook.

Event Description
int onExtensionLoad(hmExtension&,hmGlobal*); Called on extension load

The hmGlobal struct is passed as a pointer to the onPluginStart and onExtensionLoad events. This is the only place a plugin or extension can obtain this info. It is very important that you always pass this struct to the recallGlobal(hmGlobal*) function from within this event.

recallGlobal()

hmGlobal *recallGlobal(hmGlobal *global);

This is a very basic function. It was the solution to passing all needed info including players and server settings to each plugin without using any global variables.

The first time you call this function from within a plugin, the pointer passed will be statically assigned inside the function. Each plugin has its own environment that no other plugin can communicate with or change. Whenever you call the recallGlobal() function it will return the stored pointer. So you can recall the struct elsewhere.

The struct contains the file descriptor for the halfShell server, so any calls that send data to halfShell will fail if the struct was not stored in the onPluginStart event.

Example onPluginStart event:

void onPluginStart(hmHandle &handle, hmGlobal *global)
{
    recallGlobal(global);
    handle.pluginInfo("Total Recall",
                      "nigel",
                      "Storing the hmGlobal struct for future use!"
                      "v0.0.1",
                      "http://arnold.schwarzenegger.justca.me/to/recall/his/struct");
}

The hmHandle::pluginInfo() function is required to be inside the onPluginStart event or the plugin will fail to load.
The plugin will now still be allowed to load, but may behave with unintended side affects without this.
The hmHandle::pluginInfo() function has become a requirement once again.

Now to recall and use some of the data:

int onPlayerJoin(hmHandle &handle, smatch args)
{
    hmGlobal *global;
    global = recallGlobal(global);
    hmReplyToClient(args[1].str(),"Welcome to the server! There are currently " + data2str("%i",global->players.size()) + " players online.");
    hmOutVerbose("Client " + args[1].str() + " has joined and has flags: " + data2str("%i",hmGetPlayerFlags(args[1].str())));
    return 0;
}

The only thing we needed to recallGlobal() for was to get the total number of players online, but inside of hmReplyToClient(), hmOutVerbose(), and hmGetPlayerFlags() there are calls to recallGlobal(). This means these functions would not have functioned without passing the pointer of hmGlobal to recallGlobal() in the onPluginStart event.

hmHandle Class

Each plugin is tied to an hmHandle object. Everything about the plugin is held inside of it. This is how you will register commands, hook regex patterns, create timers, and basically everything else the plugin does. Which is why it is passed to every single function in the plugin that halfMod calls.

Constructors

hmHandle::hmHandle()

Used internally by halfMod.

hmHandle::hmHandle(const std::string&,hmGlobal*)

Used internally by halfMod. Calls hmHandle::load().

hmHandle::load()

void hmHandle::load(const std::string&,hmGlobal*)

Used internally by halfMod to load the plugin. Using this inside of a plugin will likely break everything.

hmHandle::unload()

void hmHandle::unload()

Used internally by halfMod to unload the plugin. Using this inside of a plugin will likely break everything.

All of these constructors and load, unload functions should only be used in standalone programs.

For standalone programs using the halfMod API, see plugininfo.cpp.

hmHandle::isLoaded()

bool hmHandle::isLoaded()

Returns true only if the plugin is loaded.

hmHandle::getAPI()

std::string hmHandle::getAPI()

Returns the halfMod API version used to compile the plugin. This is initialized inside the hmHandle::load() function.

hmHandle::getPath()

std::string hmHandle::getPath()

Returns the full path to the plugin file.

hmHandle::getPlugin()

std::string hmHandle::getPlugin()

Returns the name of the plugin. Used in hm plugin calls.
It is effectively the name of the plugin without the path or extension.

hmHandle::pluginInfo()

void hmHandle::pluginInfo(const std::string &name, const std::string &author, const std::string &description, const std::string &version, const std::string &url)

This function defines the plugin information.
It must be called from within the onPluginStart event or the plugin will fail to load!!

Member Description
name The plugin's display name.
author The name of the person who wrote the plugin.
description A brief description of the plugin.
version The version number of the plugin.
url A url to the plugin or author's page of choice.

hmHandle::getInfo()

hmInfo hmHandle::getInfo()

Used internally by halfMod.

Returns the hmInfo struct that was defined by the hmHandle::pluginInfo() function.

hmHandle::hookEvent()

int hmHandle::hookEvent(int event,std::string function,bool withSmatch = true)
int hmHandle::hookEvent(int event,int (*func)(hmHandle&))
int hmHandle::hookEvent(int event,int (*func_with)(hmHandle&,std::smatch))

Used internally when loading the plugin to register any events found within the plugin. Can also be used within a plugin to create an event by a different name than default. This is also used within plugins to register custom events triggered via console filters.

Member Description
event The ID of the event.
function The name of the function to register.
withSmatch Register this event to send a smatch list on call.
func Function pointer to register. Without smatch.
func_with Function pointer to register. With smatch.

Event IDs:

#define HM_ONAUTH           8
#define HM_ONJOIN           16
#define HM_ONWARN           24
#define HM_ONINFO           32
#define HM_ONSHUTDOWN       40
#define HM_ONDISCONNECT     48
#define HM_ONPART           56
#define HM_ONADVANCE        64
#define HM_ONGOAL           72
#define HM_ONCHALLENGE      80
#define HM_ONACTION         88
#define HM_ONTEXT           96
#define HM_ONFAKETEXT       104
#define HM_ONDEATH          112
#define HM_ONWORLDINIT      120
#define HM_ONCONNECT        128
#define HM_ONHSCONNECT      136
#define HM_ONHSDISCONNECT   144
#define HM_ONSHUTDOWNPOST   152
#define HM_ONREHASHFILTER   160
#define HM_ONGAMERULE       168
#define HM_ONGLOBALMSG      176
#define HM_ONPRINTMSG       184
#define HM_ONCONSOLERECV    192
#define HM_ONCUSTOM_1       200
#define HM_ONCUSTOM_2       208
#define HM_ONCUSTOM_3       216
#define HM_ONCUSTOM_4       224
#define HM_ONCUSTOM_5       232

Returns the total number of events hooked by the plugin or -1 on error.

hmHandle::regAdminCmd()

int hmHandle::regAdminCmd(const std::string &command, const std::string &function, int flags, const std::string &description = "")
int hmHandle::regAdminCmd(const std::string &command, int (*func)(hmHandle&,std::string,std::string[],int), int flags, const std::string &description = "")

Registers an admin command to a function.

Member Description
command The command name used to call function.
function The name of the function to be called. This function is always an int.
flags The access level a player is required to have to be able to use the command.
description Optional and is displayed in the output of the hm_info command.
func A pointer to the function to be called.

Returns the total number of commands registered by the plugin or -1 on error.

hmHandle::regConsoleCmd()

int hmHandle::regConsoleCmd(const std::string &command, const std::string &function, const std::string &description = "")
int hmHandle::regConsoleCmd(const std::string &command, int (*func)(hmHandle&,std::string,std::string[],int), const std::string &description = "")

Registers a user command of the name function, not a pointer to the function, but just the name of it.

Member Description
command The command name used to call function.Member
function The name of the function to be called. This function is always an int.
description Optional and is displayed in the output of the hm_info command.
func A pointer to the function to be called.

Returns the total number of commands registered by the plugin or -1 on error.

hmHandle::unregCmd()

int hmHandle::unregCmd(const string &command)

Removes a command that was strictly registered by the plugin, works for both user and admin commands.
Always succeeds even if the command did not exist.

Member Description
command The name of the command.

Returns the total number of commands registered by the plugin.

Syntax for a command's function (both admin and console commands use the same syntax):

int comFunc(hmHandle &handle,std::string client,std::string args[],int argc)
Member Description
comFunc The name of the function defined when registering the command.
handle This plugin.
client The name of the player that ran the command.
args Filled with the arguments passed to the command. args[0] will always be the command name.
argc Size of args.

Returning non-0 halts further processing of the server line. Useful for chat messages so they don't trigger onPlayerText events as well, unless that's what you want to do.
In the event that multiple commands have been registered with the same name, the first one found is the only one that will trigger.

hmHandle::hookPattern()

int hmHandle::hookPattern(const std::string &name, const std::string &pattern, const std::string &function)
int hmHandle::hookPattern(const std::string &name, const std::string &pattern, int (*func)(hmHandle&,hmHook,std::smatch))

Hook a regex pattern to trigger a function.

Member Description
name The name you can specify to later reference this hook.
pattern The regex pattern.
function The name of the function to be called when a line matches pattern.
func A pointer to the function to be called when a line matches pattern.

Returns the total number of hooks registered by the plugin or -1 on error.

hmHandle::unhookPattern()

int hmHandle::unhookPattern(const std::string &name)

Removes a hook.
Always succeeds even if the hook did not exist.

Member Description
name The name used when creating the hook.

Returns the total number of hooks registered by the plugin.

Syntax for a hook's function:

int hookFunc(hmHandle &handle,hmHook hook,std::smatch)
Member Description
hookFunc The name of the function defined when hooking the pattern.
handle This plugin.
smatch The match list generated by the regex pattern.
hook The hmHook struct containing this hook's name, ptrn, and function pointer.

Returning non-0 will halt halfMod's processing of this line. You should always return non-0 when the data obtained was requested and nothing else should need this data. If something else needs the same data, it should request for it itself. It is a good habit to open the hook when requesting data, and closing the hook inside the hook's function.

You can close the hook from within the function with handle.unhookPattern(hook.name);.

hmHandle::createTimer()

int hmHandle::createTimer(const std::string &name, long interval, const std::string &function, const std::string &args = "", short type = SECONDS)
int hmHandle::createTimer(const std::string &name, long interval, int (*func)(hmHandle&,std::string), const std::string &args = "", short type = SECONDS)

Create a timer.

Member Description
name The name of this timer for future reference.
interval Amount of time before this timer will trigger.
function The name of the function to call when interval has passed.
args Optional string to pass to the function.
func A pointer to the function to call when interval has passed.
type The resolution of the timer.

Resolution types:

#define SECONDS         0
#define MILLISECONDS    1
#define MICROSECONDS    2
#define NANOSECONDS     3

Returns the total number of timers registered by this plugin or -1 on error.

hmHandle::killTimer()

int hmHandle::killTimer(const std::string &name)

Kill a timer registered by this plugin.
Always succeeds even if the timer did not exist.

Member Description
name The name assigned in hmHandle::createTimer()

Returns the total number of timers registered by this plugin.

hmHandle::triggerTimer()

int hmHandle::triggerTimer(const std::string &name)

Set all timers with name to run their function on the next tick.

Member Description
name The name assigned in hmHandle::createTimer()

Returns the total number of timers set to trigger.

Syntax for a timer's function:

int timerFunc(hmHandle &handle,std::string args)
Member Description
timerFunc The name of the function defined when creating the timer.
handle This plugin.
args The same string passed when creating the timer.

Returning 0 will make this timer loop. Returning non-0 will stop the timer.

hmHandle::findCmd()

hmCommand hmHandle::findCmd(const std::string &command)

Returns a copy of the hmCommand struct containing command. If command does not exist then an empty struct is returned.

hmHandle::findHook()

hmHook hmHandle::findHook(const std::string &name)

Returns a copy of the hmHook struct by name. If no hook exists by the name of name then an empty struct is returned.

hmHandle::findEvent()

hmEvent hmHandle::findEvent(int event)

Returns a copy of the hmEvent struct that is associated with event. If no event exists for event then an empty struct is returned.

hmHandle::findTimer()

hmTimer hmHandle::findTimer(const std::string &name)

Returns a copy of the hmTimer struct by name. If no timer exists by the name of name then an empty struct is returned.

hmHandle::totalCmds()

int hmHandle::totalCmds()

Returns the total number of commands registered by this plugin.

hmHandle::totalEvents()

int hmHandle::totalEvents()

Returns the total number of events registered by this plugin.

hmHandle::vars

std::string hmHandle::vars

This is a variable that the plugin can access for whatever reason it may want. halfMod does not use this variable for anything.

hmHandle::invalidTimers

bool hmHandle::invalidTimers

This variable is used internally by halfMod when iterating through timers.
This variable is set to true when a timer is created or removed, telling halfMod to re-validate the current iterator.

hmHandle::createConVar

hmConVar* hmHandle::createConVar(const std::string &name, const std::string &defaultValue, const std::string &description, short flags, bool hasMin, float min, bool hasMax, float max)

Creates a new ConVar with the variables set. More info here: hmConVar Class Members Returns a temporary pointer to the created ConVar. This pointer is only usable imediately after creation. You must revalidate the pointer to use it at any other time.
If the ConVar by name already exists, a pointer to it is returned and no new ConVar is created. If the plugin that created the plugin is unloaded, this ConVar will be lost.

hmHandle::hookConVarChange

int hmHandle::hookConVarChange(hmConVar *cvar, const std::string &function)
int hmHandle::hookConVarChange(hmConVar *cvar, int (*func)(hmConVar&,std::string,std::string))

Hooks a function to a ConVar, calling it when the value changes.

Member Description
cvar Pointer to the ConVar to hook.
function Name of the function to call when the value of this ConVar changes.

hmHandle::totalCvars()

int hmHandle::totalCvars()

Returns the total number of ConVars that the plugin has created.

hmExtension Class

Each extension is tied to an hmExtension object. Everything about the extension is held inside of it. This is how you will access members of the extension from within plugins.
The vector of hmExtension objects is stored within the hmGlobal object so everything can access them from anywhere.

Constructors

hmExtension::hmExtension()

Used internally by halfMod.

hmExtension::hmExtension(const std::string &extensionPath, hmGlobal *global)

Used internally by halfMod. Calls hmExtension::load().

hmExtension::load()

bool hmExtension::load(const std::string &extensionPath, hmGlobal *global)

Used internally by halfMod to load the extension. Using this from inside a plugin or extension will likely break everything.

hmExtension::unload()

void hmExtension::unload()

Currently not used anywhere. Often causes server crashing when unloading an extension. Excercise extreme caution with this function. Like with load() using this will very likely break everything.

hmExtension::isLoaded()

bool hmExtension::isLoaded()

Returns true only if the extension is loaded.

hmExtension::getAPI()

std::string hmExtension::getAPI()

Returns the halfMod API version used to compile the extension.

hmExtension::getPath()

std::string hmExtension::getPath()

Returns the full path to the extension file.

hmExtension::getExtension()

std::string hmExtension::getExtension()

Returns the name of the extension. Used in hm extension calls.
It is effectively the name of the extension without the path or file-type "extension".

hmExtension::extensionInfo()

void hmExtension::extensionInfo(const std::string &name, const std::string &author, const std::string &description, const std::string &version, const std::string &url)

This function defines the extension information.

Member Description
name The extensions's display name.
author The name of the person who wrote the extension.
description A brief description of the extension.
version The version number of the extension.
url A url to the extension or author's page of choice.

hmExtension::getInfo()

hmInfo hmExtension::getInfo()

Returns the hmInfo struct that was defined by the hmExtension::extensionInfo() function.

hmExtension::getFunc()

void* hmExtension::getFunc(const std::string &func)

Returns the address where the symbol func is loaded into memory. If the func is not found, returns NULL.
Technical info here: http://man7.org/linux/man-pages/man3/dlsym.3.html
This function directly returns the call to dlsym(this.module,func.c_str()) the handle has been loaded with these flags RTLD_NOW|RTLD_GLOBAL.

Storing the pointer returned from this function to a global scope variable will almost always cause a seg fault. Instead use static variables within the scope that will call them.

hmExtension::getFunc() Example

Let's start off by assuming the extension we want to pull from is called my_first_extension.
If the extension has this function defined:

void myExtensionFunction();

To get the pointer to this function from within a plugin, you will need to redefine the function yourself and point it to the address returned by getFunc():

hmGlobal *global = recallGlobal(NULL);
void (*theFunction)();
for (auto it = global->extensions.begin(), ite = global->extensions.end();it != ite;++it)
    if (it->getExtension() == "my_first_extension")
        *(void **) (&theFunction) = it->getFunc("myExtensionFunction");

Now within that same scope, to call the function, you will use this:

(*theFunction)();

This is the basic linking of symbols, but what if the function we want from the extension isn't a void? What if it returns a value that we want? What if the function has arguments that we need to pass?
Take this function from the extension, for example:

double product(double a, double b)
{
    return a*b;
}

Now let's point to this function and call it from within a plugin:

hmGlobal *global = recallGlobal(NULL);
double (*product)(double,double);
for (auto it = global->extensions.begin(), ite = global->extensions.end();it != ite;++it)
    if (it->getExtension() == "my_first_extension")
        *(void **) (&product) = it->getFunc("product");
double solution = (*product)(4.2,2.2);
hmOutDebug(to_string(solution));

After running this, (assuming --debug has been set) the console will output:

[DEBUG] 9.24

Now all of this is great, but we do not need to redefine the function and point to it each time we want to call it, so let's create a function that will statically create, store, and call the function all internally:

double extProduct(double a, double b)
{
    static bool loadfunc = true;
    static double (*func)(double)(double);
    if (loadfunc)
    {
        for (auto it = global->extensions.begin(), ite = global->extensions.end();it != ite;++it)
            if (it->getExtension() == "my_first_extension")
                *(void **) (&func) = it->getFunc("product");
        loadfunc = false;
    }
    return (*func)(a)(b);
}

Now we are free to make calls to extProduct() anywhere we want within our plugin and it will automatically be linked to product() from our extension.

Statically linking the function doesn't seem to be necessary all the time. Experiment with your extensions/plugins and find the best behaviour that works for your case.

For another example, check out src/extensions/sysinfo.cpp and src/plugins/statbar.cpp.

hmExtension::hookPattern()

int hmExtension::hookPattern(const std::string &name, const std::string &pattern, const std::string &function)
int hmExtension::hookPattern(const std::string &name, const std::string &pattern, int (*func)(hmHandle&,hmHook,std::smatch))

Hook a regex pattern to trigger a function.

Member Description
name The name you can specify to later reference this hook.
pattern The regex pattern.
function The name of the function to be called when a line matches pattern.
func A pointer to the function to be called when a line matches pattern.

Returns the total number of hooks registered by the extension or -1 on error.

hmExtension::unhookPattern()

int hmExtension::unhookPattern(const std::string &name)

Removes a hook.
Always succeeds even if the hook did not exist.

Member Description
name The name used when creating the hook.

Returns the total number of hooks registered by the extension.

Syntax for a hook's function:

int hookFunc(hmExtension &handle,hmHook hook,std::smatch)
Member Description
hookFunc The name of the function defined when hooking the pattern.
handle This plugin.
smatch The match list generated by the regex pattern.
hook The hmHook struct containing this hook's name, ptrn, and function pointer.

Returning non-0 will halt halfMod's processing of this line. You should always return non-0 when the data obtained was requested and nothing else should need this data. If something else needs the same data, it should request for it itself. It is a good habit to open the hook when requesting data, and closing the hook inside the hook's function.

You can close the hook from within the function with handle.unhookPattern(hook.name);.

hmExtension::createConVar

hmConVar* hmExtension::createConVar(const std::string &name, const std::string &defaultValue, const std::string &description, short flags, bool hasMin, float min, bool hasMax, float max)

Creates a new ConVar with the variables set. More info here: hmConVar Class Members Returns a temporary pointer to the created ConVar. This pointer is only usable imediately after creation. You must revalidate the pointer to use it at any other time.
If the ConVar by name already exists, a pointer to it is returned and no new ConVar is created.

hmExtension::hookConVarChange

int hmExtension::hookConVarChange(hmConVar *cvar, const std::string &function)
int hmExtension::hookConVarChange(hmConVar *cvar, int (*func)(hmConVar&,std::string,std::string))

Hooks a function to a ConVar, calling it when the value changes.

Member Description
cvar Pointer to the ConVar to hook.
function Name of the function to call when the value of this ConVar changes.

hmExtension::totalCvars()

int hmExtension::totalCvars()

Returns the total number of ConVars that the extension has created.

hmConVar Class

Each ConVar is tied to an hmConVar object. A vector of them is contained within hmGlobal, they are not directly tied to plugins or extensions.

Constructors

hmConVar::hmConVar()
hmConVar::hmConVar(const std::string &cname, const std::string &defVal, const std::string &description, short flag, bool hasMinimum, float minimum, bool hasMaximum, float maximum)

Used internally by halfMod.

hmConVar::flags

short hmConVar::flags

These flags define certain behaviour of the ConVar. These flags can be OR'd together for the desired effect:

Flag Meaning
FCVAR_NOTIFY Clients are notified of changes
FCVAR_CONSTANT The cvar is assigned to the default value and cannot be changed
FCVAR_READONLY Only internal methods will be able to change the value, gamerule will be able to change it, but hm_cvar will not
FCVAR_GAMERULE The cvar is tied to a gamerule of the same name

hmConVar::hasMin

bool hmConVar::hasMin

Whether or not the ConVar has a minimum boundary.

hmConvar::hasMax

bool hmConVar::hasMax

Whether or not the ConVar has a maximum boundary.

hmConVar::min

float hmConVar::min

The minimum boundary for the ConVar, requires hasMin to be true.

hmConVar::max

float hmConVar::max

The maximum boundary for the ConVar, requires hasMin to be true.

hmConVar::getName

std::string hmConVar::getName()

Returns the name of the ConVar.

hmConVar::getDesc

std::string hmConVar::getDesc()

Returns the description of the ConVar.

hmConVar::getDefault

std::string hmConVar::getName()

Returns the default value of the ConVar.

hmConVar::reset

void hmConVar::reset()

Resets the value of the ConVar to the default.

hmConVar::getAsString

std::string hmConVar::getAsString()

Returns the value of the ConVar as a string.

hmConVar::getAsBool

bool hmConVar::getAsBool()

Returns the value of the ConVar as a boolean.

hmConVar::getAsInt

int hmConVar::getAsInt()

Returns the value of the ConVar as an int.

hmConVar::getAsFloat

float hmConVar::getAsFloat()

Returns the value of the ConVar as a float.

hmConVar::setString

void hmConVar::setString(std::string newValue, bool wasSet = false)

Set the value of the ConVar to a string.

wasSet is used internally.

hmConVar::setBool

void hmConVar::setBool(bool newValue)

Set the value of the ConVar to a boolean.

hmConVar::setInt

void hmConVar::setInt(int newValue)

Set the value of the ConVar to an int.

hmConVar::setFloat

void hmConVar::setFloat(float newValue)

Set the value of the ConVar to a float.

hmConVar::hooks

std::vector<hmConVarHook> hooks

List of callback functions to call when the value of this ConVar is changed.

Vectors

std::vector<hmCommand> cmds
std::vector<hmHook> hooks
std::vector<hmTimer> timers

All of these are used internally by halfMod. More information about them in the structs section of this page.

Structs

These are mostly used internally, but some can be used by plugins as well.
These should only really be read from, but can be modified. Doing so should be avoided where possible; instead use the functions built for modifying/creating them.

hmInfo

struct hmInfo
{
    std::string name;
    std::string author;
    std::string description;
    std::string version;
    std::string url;
};

Each plugin's hmHandle class contains a private hmInfo struct that is filled with the pluginInfo() member function.

Member Description
name The plugin's display name.
author The name of the person who wrote the plugin.
description A brief description of the plugin.
version The version number of the plugin.
url A url to the plugin or author's page of choice.

hmPlugin

struct hmPlugin
{
    std::string path;
    std::string name;
    std::string version;
};

The hmGlobal struct contains a vector of these structs filled with info of each loaded plugin.
This is only simple information about the plugin, used to determine if a plugin is loaded from within another plugin.

Member Description
path The full filepath to the plugin.
name The formatted filepath with only the name of the file and any sub directories it lies in.
version The version number of the plugin.

hmCommand

struct hmCommand
{
    std::string cmd;
    int (*func)(hmHandle&,std::string,std::string[],int);
    int flag;
    std::string desc;
};

Each plugin's hmHandle class contains a vector of hmCommand structs. Each one contains the information of one command that the plugin has registered.

Member Description
cmd The command name.
func A pointer to the function to be called when the command is ran.
flag The access level required by a player to run this command.
desc Brief description of the command. Displayed in the output of the hm_info command.

hmHook

struct hmHook
{
    std::string name;
    std::string ptrn;
    int (*func)(hmHandle&,hmHook,std::smatch);
};

Each plugin's hmHandle class contains a vector of hmHook structs. Each one contains the information of one regex pattern that the plugin has hooked.

Member Description
name The reference name for this hook.
ptrn The regex pattern.
func A pointer to the function to be called when this hook triggers.

hmEvent

struct hmEvent
{
    int event;
    int (*func)(hmHandle&);
    int (*func_with)(hmHandle&,std::smatch);
};

Each plugin's hmHandle class contains a private vector of hmEvent structs. Each one contains the information of one event that the plugin has registered.

Member Description
event The associated event's ID.
func A pointer to the function to be called when the event triggers.
func_with A pointer to the function to be called when the event triggers. Expects a smatch.

hmTimer

struct hmTimer
{
    std::string name;
    long interval;
    std::chrono::high_resolution_clock::time_point last;
    int (*func)(hmHandle&,std::string);
    std::string args;
    short type;
};

Each plugin's hmHandle class conains a vector of hmTimer structs. Each one contains the information of one timer the plugin is currently running.

Member Description
name The reference name of this timer.
interval Amount of seconds to wait after initiated until triggering.
last The Unix timestamp of the time this either initiated or last triggered.
func A pointer to the function to call when the timer triggers.
args A string to pass to the function when triggering.

hmConsoleFilter

struct hmConsoleFilter
{
    std::regex filter;
    bool blockOut = false;
    bool blockEvent = false;
    bool blockHook = false;
    int event;
    std::string name;
};

The halfMod engine manages a vector of these, each one contains a different console filter. hmGlobal struct contains a pointer to that vector for reading and manipulation.

Member Description
filter Regex pattern to filter the console output
blockOut Whether or not to block printing output to console
blockEvent Whether or not to block event processing
blockHook Whether or not to block pattern hook processing
event Optional event ID to trigger when matched
name Name to identify the filter by

hmPlayer

struct hmPlayer
{
    std::string name;
    int flags;
    std::string uuid;
    std::string ip;
    int join;
    int quit;
    std::string quitmsg;
    int death;
    std::string deathmsg;
    std::string custom;
};

Each player on the server has their own hmPlayer struct containing various bits of info.
The data in this struct is automatically filled.

Member Description
name Player's name.
flags Player's admin flags. (0 for none.)
uuid Player's UUID string.
ip IP the player is connecting from or their most recent IP.
join Unix timestamp when the player most recently joined.
quit Unix timestamp when the player most recently quit.
quitmsg The string the player's client gave when leaving last.
death Unix timestamp when the player most recently died.
deathmsg The message of the player's last death without their name in it.
custom Only used in plugins. This variable is never saved to the player.dat file, but it is read to from it. In the player.dat file any unknown item is treated as custom and each line will be stored here seperated by newline characters. (\n)

hmAdmin

struct hmAdmin
{
    std::string client;
    int flags;
};

When the admin config file is loaded, it fills these structs for each entry.

Member Description
client Name of the player.
flags Player's admin flags.

hmGlobal

struct hmGlobal
{
    std::vector<hmPlayer> players;
    std::vector<hmAdmin> admins;
    std::vector<hmPlugin> pluginList;
    std::vector<hmConVar> conVars;
    std::string mcVer;
    std::string hmVer;
    std::string hsVer;
    std::string world;
    std::string mcScreen;
    bool quiet = false;
    bool verbose = false;
    bool debug = false;
    int hsSocket;
    int logMethod;
    int maxPlayers;
    std::vector<hmConsoleFilter>* conFilter;
    std::vector<hmExtension> extensions;
};

This struct is automatically filled with data. Some variables are set at different times.

Member Description
players Vector of hmPlayer structs. Each one for a different player currently online.
admins Vector of hmAdmin structs. Each one for a different admin definition in the admin config file.
pluginList Vector of hmPlugin structs. Each one for a different loaded plugin.
conVars Vector of hmConVar structs. Each one for a different ConVar.
mcVer Version of Minecraft that is running.
hmVer Version of halfMod that is running.
hsVer Version of halfShell that halfMod is connected to.
world Name of the world Minecraft is using.
mcScreen Name of the screen running Minecraft and halfShell.
quiet true if launched with --quiet.
verbose true if launched with --verbose.
debug true if launched with --debug.
hsSocket File descriptor to the open connection with halfShell.
logMethod Various log options OR'd together.
maxPlayers Max number of players the Minecraft server will allow.
conFilter Pointer to the vector of hmConsoleFilter structs the engine filters the console output with.
extensions Vector of hmExtension objects. Each one for a different extension that is currently loaded.

hmConVarHook

struct hmConVarHook
{
    int (*func)(hmConVar&,std::string,std::string);
};

This struct just simplifies the type for the vector of hooks.

Functions

mcVerInt()

int mcVerInt(std::string version)

Returns an integer representation of the Minecraft version.

Member Description
version The version to convert.

Return value is also stored statically so it will only reprocess in the case that you are requesting a different version.

Example return values:

Version Integer Representation
0.1.3 1030
1.7.2 107020
13w37a 13003701
1.8 108000
1.12.2 112020
1.13 113000
17w47b 17004702
17w48a 17004801

Usage:

hmGlobal *global;
int ver = mcVerInt(recallGlobal(global)->mcVer);
if ((ver > 17000000) || ((ver >= 113000) && (ver < 1000000)))
{
    // use 1.13 commands.
}
else if ((ver > 13003700) || ((ver >= 107020) && (ver < 1000000)))
{
    // use 1.7.2+ commands.
}
else
{
    // use pre-1.7.2 commands.
}

mkdirIf()

void mkdirIf(const char *path)

Makes a directory if it doesn't already exist.

stripFormat()

std::string stripFormat(std::string str)

Removes all Minecraft formatting codes from str. This means all colors, bold, italic, etc created with the § character.
Returns the stripped string.

recallGlobal()

hmGlobal *recallGlobal(hmGlobal *global);

This is a very basic function. It was the solution to passing all needed info including players and server settings to each plugin without using any global variables.
Statically stores the passed hmGlobal stuct the first time it is called.
Returns the stored hmGlobal struct.

hmSendRaw()

void hmSendRaw(std::string raw, bool output = true)

Sends a raw, unformatted, command to the Minecraft server.

Member Description
raw The command to send.
output Optional. If set to false will act the same as when launched with the --quiet switch.

hmServerCommand()

void hmServerCommand(std::string raw, bool output = true)

Sends a command to halfShell to be relayed back to halfMod and executed through the built-in hm_rcon command.
Utilizes the hs built-in halfShell command to bypass the inability to directly communicate with other plugins.
This function can be used to run Minecraft commands, but should be avoided if the command will always be a Minecraft command. In that case, using hmSendRaw() is encouraged.

Member Description
raw The command to run.
output Optional. If set to false will act the same as when launched with the --quiet switch.

hmReplyToClient()

void hmReplyToClient(std::string client, std::string message)

Sends a formatted tellraw message (or tell, if mcVer is less than 1.7.2) to the client. If client is #SERVER outputs unformatted to the console.
No need to stripFormat() on the client's name. This will happen internally.

Member Description
client The name of the player to send the message to.
message The message to send.

hmSendCommandFeedback()

void hmSendCommandFeedback(std::string client, std::string message)

Sends a formatted message to all players. Players will see this message differently depending on if they have the FLAG_ADMIN flag or not.
Players with the flag will see the name of the player that ran the command and other players will see ADMIN: instead.
No need to stripFormat() on the client's name. This will happen internally.

Member Description
client The player who ran the command.
message The feedback from the command.

Output for non-admins:

[HM] ADMIN: Kicked player PooPooHead (why ya such a poo?)

Output for admins:

[HM] goots_: Kicked player PooPooHead (why ya such a poo?)

Output for yourself:

[HM] Kicked player PooPooHead (why ya such a poo?)

hmSendMessageAll()

void hmSendMessageAll(std::string message)

Sends a message to all players.

Member Description
message The message to send.

hmIsPlayerOnline()

bool hmIsPlayerOnline(std::string client)
Member Description
client Name of the player in question.

Returns true if client is online.
No need to stripFormat() on the client's name. This will happen internally.

hmGetPlayerInfo()

hmPlayer hmGetPlayerInfo(std::string client)
Member Description
client Name of the player.

Returns the entire hmPlayer struct for an online player.
Returns an empty struct if the player is offline.
No need to stripFormat() on the client's name. This will happen internally.

hmGetPlayerIterator()

std::vector<hmPlayer>::iterator hmGetPlayerIterator(std::string client)
Member Description
client Name of the player.

Returns the iterator pointing to the hmPlayer struct for the player.
Returns an iterator pointing to the end of the vector if the player is offline.
No need to stripFormat() on the client's name. This will happen internally.
The returned iterator can be used to retrieve or to set data of a player.

hmGetPlayerData()

hmPlayer hmGetPlayerData(std::string client)
Member Description
client Name of the player.

Loads a player's data from their physical ./halfMod/userdata/player.dat file. Should not be used if the player is online. Returns the entire hmPlayer struct for a player that has joined the server. Returns a struct with only the name member set if the player has never joined.
No need to stripFormat() on the client's name. This will happen internally.

hmGetPlayerUUID()

std::string hmGetPlayerUUID(std::string client)

No need to stripFormat() on the client's name. This will happen internally.

Member Description
client Name of the player.

Returns the player's UUID.

hmGetPlayerIP()

std::string hmGetPlayerIP(std::string client)

No need to stripFormat() on the client's name. This will happen internally.

Member Description
client Name of the player.

Returns the player's IP.

hmGetPlayerFlags()

int hmGetPlayerFlags(std::string client)

No need to stripFormat() on the client's name. This will happen internally.

Member Description
client Name of the player.

Returns the player's access flags.

hmProcessTargets()

int hmProcessTargets(std::string client, std::string target, std::vector<hmPlayer> &targList, int filter)

Generates a vector of hmPlayer structs, one for each player that matches the target.
No need to stripFormat() on the client or target names. This will happen internally.

Member Description
client The player requesting the targets.
target The string to match against all online players.
targList A vector of hmPlayer structs. Will be cleared then filled with all matches.
filter A list of FILTER modes OR'd together.

Returns the total number of targets found.

Filters:

Filter Purpose
FILTER_NAME Filter by player name.
FILTER_NO_SELECTOR Do not allow @selectors (@a|@e|@p|@r|@s)
FILTER_IP Filter by player IP. target must perfectly match the player's IP.
FILTER_FLAG Filter by player's flags.
FILTER_UUID Filter by player UUID. target must perfectly match the player's UUID.
FILTER_NO_EVAL Do not evaluate %identifiers.

FILTER_FLAG and FILTER_NAME are the only filters that may not be used together. Any combination without both of these will work as expected.

Identifiers:

Identifier Purpose Example
%all Evaluates into all players %all
%f Evaluates into all players with (or without) a list of flags %fa = all players with FLAG_ADMIN. %fabc = all players with FLAG_ADMIN, FLAG_BAN, and FLAG_CONFIG. %f!abc = all players without FLAG_ADMIN, FLAG_BAN, and FLAG_CONFIG.
%me Evaluates into client. %me
%r Evaluates into one random player. %r = any random player, can be client. %r! = any random player with the exception of client.

About Targets:
Targets can be partial names of players, full names, IP's, UUID's, flags, or identifiers. You cannot mix any of them, only one may be used.

If using FILTER_FLAGS the target string changes slightly:
The string is only the alphabetical representation for each flag you wish to check: abc is the same as the identifier %fabc
Beginning the string with a ! negates the targets: !abc is the same as the identifier %f!abc

hmOutQuiet()

void hmOutQuiet(std::string text)

Outputs a message to the console unless halfMod was launched with --quiet.

Member Description
text Text to output to console.

hmOutVerbose()

void hmOutVerbose(std::string text)

Outputs a message to the console if halfMod was launched with --verbose.

Member Description
text Text to output to console.

hmOutDebug()

void hmOutDebug(std::string text)

Outputs a message to the console if halfMod was launched with --debug.

Member Description
text Text to output to console.

hmLog()

void hmLog(std::string data, int logType, std::string logFile)

Writes data to a logfile if logType is set.

Member Description
data Data to log.
logType A log method.
logFile The file to write to. Starting directory is ./halfMod/logs/.

Log Methods:

Method Purpose
LOG_KICK Used to log when a player is kicked.
LOG_BAN Used to log when a player is banned.
LOG_OP Used to log when a player is OP'd or DE-OP'd.
LOG_WHITELIST Used to log when a player has been added or removed from the whitelist or the whitelist settings have changed.
LOG_ALWAYS Ignores log settings.

hmIsPluginLoaded()

bool hmIsPluginLoaded(std::string nameOrPath, std::string version = "")
Member Description
nameOrPath Either the exact name or path of the plugin in question.
version Optional. If set, the plugin's version must exactly match this string.

Returns true is a plugin is currently loaded.
Use this function if the version does not matter or if you are looking for a specific version.
If you want to check that the plugin is at least a certain version or higher, use hmGetPluginVersion().

hmGetPluginVersion()

std::string hmGetPluginVersion(std::string nameOrPath)
Member Description
nameOrPath Either the exact name or path of the plugin in question.

Returns the version of a loaded plugin. If no matching plugin is found, returns an empty string.
If the version number of the plugin does not matter, use hmIsPluginLoaded() instead. Otherwise, this function is handy so you can perform some sort of comparison to determine if the plugin is of a sufficient version.

hmAddConsoleFilter

int hmAddConsoleFilter(std::string name, std::string ptrn, short blocking = HM_BLOCK_OUTPUT, int event = 0)

Creates a console filter and adds it to the engine's list.

Member Description
name Name used to reference this filter
ptrn Regex pattern to filter console output with
blocking Optional blocking method. OR the desired methods together
event Optional event ID to trigger on matches

Returns the total number of registered filters.

Blocking methods:

Method Description
HM_NON_BLOCK Does not block anything, allows total processing
HM_BLOCK_OUTPUT Blocks console output, allows total processing
HM_BLOCK_EVENT Blocks event processing
HM_BLOCK_HOOK Blocks pattern hook processing
HM_BLOCK_ALL Blocks everything

hmRemoveConsoleFilter

int hmRemoveConsoleFilter(std::string name)

Removes all console filters registered with name. All filters created via the consolefilters.txt file are given the name "config".

Returns the total number of registered filters.

hmWritePlayerDat

int hmWritePlayerDat(std::string client, std::string data, std::string ignore, bool ifNotPresent = false)

Writes data to the client's .dat file. The file is parsed first, ignoring any items matching ignore.

Member Description
client Name of the player
data Full line(s) to write
ignore List of tokens delimited by "=". Used to remove data from the file
ifNotPresent If true, does not edit the file if any line in the file is equivalent to data

If you wanted to remove the player's ip and uuid from the file without adding any new data, you would use this:

hmWritePlayerDat(client,"","uuid=ip");

You can also write new data to the file and ignore items at the same time.

hmFindConVar

hmConVar *hmFindConVar(const std::string &name)

Returns a pointer to the hmConVar in question.

hmFindConVarIt

std::vector<hmConVar>::iterator hmFindConVarIt(const std::string &name);

Returns an iterator to the hmConVar in question.

hmResolveFlag

int hmResolveFlag(char flag);

Returns the integer representation of flag.

hmResolveFlags

int hmResolveFlags(const std::string &flags);

Returns the integer representation of flags. Passes each char to hmResolveFlag() and OR's the values together.

Clone this wiki locally