Left 4 Dead 2

Left 4 Dead 2

66 ratings
Speedrunner Tools API
By シェイディ♑
Here is listed not native functions from Speedrunner Tools addon, written in Squirrel programming language (to see the official L4D2 functions, check the Valve website List of L4D2 Script Functions). All include-files from this page in the addon's directory (root/scripts/vscripts/st_scripts/include/...), which can be opened via GCFScape program. Some functions support chat-commands to convenient interaction (for detailed information check the Commands page).

FUNCTION
SIGNATURE
DESCRIPTION
SpeedrunStart
void SpeedrunStart(bool isHUD)
Start a speedrun timer. Set parameter to start speedrun without time.
SpeedrunRestart
void SpeedrunRestart()
Restart the game. Function "OnRestart()" being called on restarting. You can restart speedrun from the game manually, typing "!restart" command.
Timer
void g_STLib.Funcs.Timer()
Adds a countdown after "!restart" (not necessary to add "SpeedrunStart()" in your script, this function already contains it). If timer is used, create "g_STLib.Funcs.Inventory()" and put there your speedrun settings (by the way, you may skip g_STLib.Funcs scope in your script file whenever you want, for convenience). Use "!timer <value>" command to manage countdown value. For more information, see the Customize Your Speedrun page.
HUDLoad
void g_STLib.Funcs.HUDLoad(float desiredTime)
Add desired time to the HUD in seconds (e.g. time from the previous map).


Hooks
This table collected all events, that can be hooked in your ScMp speedrun script file. Some signatures require SourceMod plugins to be installed in order to receive a call (check "sm_commands.nut" section for more info).

FUNCTION
SIGNATURE
DESCRIPTION
OnEntityOutput
::OnEntityOutput <- function()
May be executed after any I/O event, if entity output is connected and fired. When the function is called, the activating and calling entities Script Handles are written to the receiving entitys Script Scope in the activator and caller variables. Used by "speedrunner_tools.nut" include for SpawnTrigger as well.
OnEntityCreated
::OnEntityCreated <- function(hEntity, classname)
This hook is refers to OnEntityCreated[sm.alliedmods.net]forward, provided by this plugin[forums.alliedmods.net] for use in VScript environment. Called when an entity is created. It's necessary to enable st_allow_sdkhooks ConVar for access to this hook (disabled by default as it rather expensive, note well). Parameters: hEntity – any created entity; classname – this entity classname.
OnEntityDestroyed
::OnEntityDestroyed <- function(hEntity)
Refers to OnEntityDestroyed[sm.alliedmods.net]forward, provided by this plugin[forums.alliedmods.net] for use in VScript environment. Called when an entity is removed from the world. It's necessary to enable st_allow_sdkhooks ConVar for access to this hook. Parameters: hEntity – any removed entity.
Inventory
g_STLib.Funcs.Inventory <- function()
Called at the end of countdown.
Inventory2
g_STLib.Funcs.Inventory2 <- function()
Called after the Intro cameras fully played. Define this function in order to prevent "skipintro.nut" from executing.
Event
g_STLib.Funcs.Event <- function()
Called at the end of countdown, but on the next frame. Current event value you may get from "g_ST.event" variable. To set the new global event data, use "!dbg event <data>" command.
PKFW_Post
g_STLib.Funcs.PKFW_Post <- function(hPlayer)
Hook for PlayerKillFromWeapon. When the last scripted shot is made, this function will be called. Parameters: hPlayer – handle containing the player, who committed auto-kill.
OnPlayEnd
::OnPlayEnd <- function(hPlayer, sFileName)
Called from the SourceMod plugin[forums.alliedmods.net] when movement playback was fully ended. Parameters: hPlayer – player, who completed his movement; sFileName – file name.
OnPlayLine
::OnPlayLine <- function(hPlayer, sFileName, tick, buttons)
Called from the SourceMod plugin[forums.alliedmods.net] on each movement file line. Parameters: hPlayer – player, who performs his movement; sFileName – file name; tick – current file line; buttons – pressed buttons.
OnRestart
::OnRestart <- function()
Called on restarting the speedrun (it's not equal "round_end" event, our function will be executed a bit late).
OnSafe
::OnSafe <- function(hPlayer)
Called when the Survivor entered the saferoom.
OnAutoFired
::OnAutoFired <- function(hPlayer, data)
Event for AutoFire* functions, when scripted player commits auto-fire.
OnAutoFired_Post
::OnAutoFired_Post <- function(hPlayer, hClient, data)
Called after a player has received a boost. Parameters: hPlayer – booster player; hClient – player, who get boosted; data – user-defined data at the function execution.
OnAutoCB
::OnAutoCB <- function(hPlayer, sName)
Called from the SourceMod plugin[forums.alliedmods.net] in case a player used an auto-commonboost jump. Parameters: hPlayer – player, who get boosted; sName – zombie targetname.

Variables
Bunch of useful variables for ScMp scripts.

VARIABLE
TYPE
DESCRIPTION
g_ST.event
string
Event name to read within Event() function. To set the new global event data, use "!dbg event <data>" command.
g_ST.tick
int
Current speedrun tick.
g_STLib.Vars.host
handle
Contains listen server host.
   
Award
Favorite
Favorited
Unfavorite
speedrunner_tools.nut
Main functions of the Speedrunner Tools addon and helpers for Scripted Maps mode.

FUNCTION
SIGNATURE
DESCRIPTION
SpawnItem
handle SpawnItem(string itemName, Vector origin, Vector angles, int itemCount, string targetName, float removeRadius)
Returns CBaseEntity. Function for entity spawning. To spawn easier, it can be used with "!picker" command. Keywords[pastebin.com]: "item0", "item1" etc.
SpawnZombie
handle SpawnZombie(string zombieName, Vector origin, bool noAttack)
Returns CBasePlayer. Function for zombie spawning. Also, you can collect these functions, by typing in chat "!zdump" command. Use 3rd arg to force idle for zombie.
SpawnZombieEx
void SpawnZombieEx(string zombieName, Vector origin, Vector angles, bool AttackOnSpawn, float spawnTime)
Extended function for zombie spawning, which allows specify certain angles for infecteds (except PZs). For random zombie orientation set "null" in angles parameter. To spawn Uncommon Infected, type a zombie model name. Use 4th arg to force attack on spawn (functional for Tank and Spitter only).
SpawnZombieForCB
handle SpawnZombieForCB(Vector origin, Vector angles, float startTime, handle forcePlayer, bool bNotSolid, string targetName)
Returns CBaseEntity. Function for spawning common infected for Commonboost trick. To interact, press MOUSE1 key to trigger a mobs. Specify start time or set "null" to create idle zombie. Set player as target to trigger a mob immediately at creation. Set solid parameter to toggle zombie's collision. Also, Commonboost can be even easier with this[forums.alliedmods.net] SourceMod plugin.
SpawnCommon
handle SpawnCommon(string zombieName, Vector origin, Vector angles, int flags)
Returns CBaseEntity. Function to spawn infected with items. Note that, function spawns only precached in-map commons. Available infected models with items: "common_male_fallen_survivor" and "common_male_ceda". Flags: FALLEN_VJAR_OR_MOLOTOV | FALLEN_PIPE | FALLEN_PILLS | FALLEN_MEDKIT | FALLEN_SIT | FALLEN_LYING
SpawnTrigger
handle SpawnTrigger(string targetName, Vector origin, Vector maxs, Vector mins, string funcCallback, int spawnflags, string Outputs, string clsName)
Returns CBaseEntity. Spawn trigger at specified position. To spawn easier, use "!trigger" command. You may set several outputs by comma within string. After trigger is touched, callback "OnEntityOutput()" will be called.
RemoveItem
int RemoveItem(string itemName)
Returns the number of removed items. Set the item name to remove. Note that, function removes all items this class. Keywords[pastebin.com]: "item0", "item1" etc. Leave args field empty to remove all items from map.
RemoveItemEx
int RemoveItemEx(Vector origin, float radius)
Removes items at specific area.
RemoveSlot
void RemoveSlot(handle player, int slotNum)
Removes weapon from slot.
RemoveCI
void RemoveCI()
Removes Common Infected class from the map.
DirectorStop
void DirectorStop(bool mode)
Stop Director and remove population from the map. Specify mode arg to force start.
AutoOpen
vold AutoOpen()
Auto-opens the saferoom door.
AutoFire
void AutoFire(any playerBooster, Vector angles, Vector position, bool infinite, bool withoutDuck, float radius, handle whoJumps, float delayTime, any data, bool method3D, Vector speed)
Scripted grenade launcher boost. Function OnAutoFired* being called only if player get boosted. 1st arg: specify player's handle, index or targetname to make him as booster; 2nd arg: booster's angles; 3rd arg: you may lock position for a booster player for exact boost; 4th arg: should this script be infinite?; 5th arg: player doesn't use crouch; 6th: specify detection radius; 7th arg: specify player, who only boosted; 8th arg: set delay time after script executed to prevent detection; 9th arg: set any data value for OnAutoFired callback; 10th arg: shall we use 3D calculation of the detection radius?; 11th arg: set projectile velocity vector. Also, enable Developer mode to debug AutoFire* functions.
AutoFire2
void AutoFire2(any playerBooster, Vector angles, Vector position, bool infinite, bool withoutDuck, float radius, handle whoJumps, float delayTime, any data, bool method3D, bool scripted)
Scripted throwable boost. 11th arg: overrides projectile vectors in case early spawn.
AutoFire3
void AutoFire3(handle playerBooster, array whoJumps, float pitch, string weaponName, bool scripted, any data)
Scripted pipe/molotov boost. Set the handle of a single player or array for multiple players who will be boosted. Customize pitch angle of a booser player relative surface and desired projectile name. By the way, Long Boost is more stable while enabled scripted parameter.
AFStop
void AFStop()
Stops any used AutoFire* script.
ScriptedTP
void ScriptedTP(any player, any leader, float teleportTime, bool bStuckTeleport, int mode)
Simulates teleport with a certain timer. Specify survivor's handle, index or targetname. 4th arg: it's stuck teleport?; 5th arg: should bots stand still? (0 = default behavior, 1 = totally frozen, 2 = resets once before fast-tp.)
ScriptedShots
void ScriptedShots(any player, float distance)
Simulates shots to CI. Set distance to 0 to remove script.
PlayerKill
void PlayerKill(handle player)
Kill a player.
PlayerKillFromWeapon
void PlayerKillFromWeapon(handle player, handle attacker, int shotsCount, bool bWaitForWeaponReady, float startTime)
Simulates player kill from primary weapon with a sensitivity to current situation. Set the attacker and desired count of shots. Turn on a delay if necessary and set the start time. Available weapons: pumpshotgun, shotgun_chrome, autoshotgun, shotgun_spas. After the last shot is made, callback "g_STLib.Funcs.PKFW_Post(hPlayer)" will be called on the next frame if created.
PlayerGod
void PlayerGod(handle player, bool isGod)
Godmode for a certain player.
StdLib
Standard generic functions, as part of utils.nut include.

FUNCTION
SIGNATURE
DESCRIPTION
AngNorm
float AngNorm(float angle, bool unsigned)
Normalize angle.
absf
float absf(float x)
Positive float.
FEqual
bool FEqual(float a, float b, float deviation)
Returns true if values are close to equal.
Clamp
float Clamp(float x, float min, float max)
Clamps between min & max.
Lerp
float Lerp(float a, float b, float t)
Simple linear interpolation.
utils.nut
The list of Squirrel based wrapper functions and constants available in Left 4 Dead 2 for a general purpose. Defines from DirectorScript scope were collected in the constants table for convenience.

FUNCTION
SIGNATURE
DESCRIPTION
GetOwner
handle GetOwner(any player)
Returns CTerrorPlayer. Specify survivor bot handle, index or targetname to get its owner.
GetPicker
handle GetPicker(handle player, float traceLength, int flags)
Returns CBaseEntity where the player is looking.
GetPickerPos
Vector GetPickerPos(handle player, float traceLength, int flags)
Returns m_vecOrigin where the player is looking.
GetPlayer
handle GetPlayer(int survivorCharacter, bool checkSpectators)
Returns CBasePlayer. Get player from character (MDL_NI = 0, MDL_RO = 1, MDL_CO = 2, MDL_EL = 3) or leave args field empty to get first Survivor player. Specify 2nd arg to find specators as well.
GetAnySurv
handle GetAnySurv()
Returns CBasePlayer. Gets any Survivor randomly.
GetVecAng
QAngle GetVecAng(Vector vec)
Returns angles from a vector.
GetDisplayTime
string GetDisplayTime(float time, string separator)
Converts seconds to time (MM:SS) with a specific character in between.
GetEpoch
int GetEpoch()
Gets a unix timestamp from local time.
GetDate
table GetDate(int unix)
Returns table with local date to build timestamps. Available keys: day, month, year, hour, min, sec, timestamp. Key "timestamp" stores classic DD:MM:YYYY @ HH:MM:SS format string.
GetFinaleType
int GetFinaleType()
Returns finale type:
‎ ‎ 0 - Holdout (standart)
‎ ‎ 1 - Gauntlet
‎ ‎ 2 - Scavenge
‎ ‎ 3 - Custom
‎ ‎ -1 - N/A
IsFakeClient
bool IsFakeClient(handle player)
Is this player a fake client.
IsHuman
bool IsHuman(handle player)
Is real player.
IsFuncExist
bool IsFuncExist(string funcName)
Returns true if specified function does exist.
IsPlayer
bool IsPlayer(handle player)
Returns true if valid player. Checks excessively.
IsPlayerVictim
bool IsPlayerVictim(handle player)
Function to determine a player as a victim.
IsPlayerView
bool IsPlayerView(handle player, Vector pos)
Check if player in view.
IsPlayerDirect
bool IsPlayerDirect(handle player, Vector pos)
Check if player approaches.
IsMapL4D1
bool IsMapL4D1()
IsSpawnAllowed
bool IsSpawnAllowed()
Check if player spawn is available in accordance with MaxClients value.
Ent
handle Ent(any entity)
Replaces function from "scriptedmode.nut". Specify entity handle, index or targetname.
EmitSound
void EmitSound(Vector origin, string soundName, int radius)
Simulates sound with a specific radius.
EmitSoundAll
void EmitSoundAll(string soundName)
Simulates sound for all players.
EmitSoundEx
handle EmitSoundEx(handle entity, string soundName, int radius, int flags)
Extended and powerful sound function. It will be attached to specified entity to move with. By storing the sound entity will give the opportunity to use PlaySound or StopSound inputs, that might be useful. 1st arg as NULL emits sound for all players. Flags: SND_PLAY_EVERYWHERE | SND_START_SILENT | SND_IS_NOT_LOOPED | SND_ONCE
TeleportEntity
void TeleportEntity(handle entity, Vector origin, Vector angles, Vector velocity, bool kvOrigin)
Sets the world entity position, orientation and speed. Use "null" if you want to keep current vector without changes. Teleportation can be interpolated, if origin switched to KeyValue method.
ClearEvent
void ClearEvent(string eventName, table scopeName)
Removes all valid events by name. To remove certain hook, specify a scope name where callback is.
OnGameFrame
handle OnGameFrame(string funcName, float updateTime, float durationTime)
Returns CBaseEntity. Calls the specified function every game frame. Adjust update time and/or duration time to stop the calls after the timer ends. BUG: functions aren't being called, if specified more then one argument.
NavMark
void NavMark(Vector whereNav, int flags)
Used to mark navigation mesh without editing the NAV-files.
RegCvar
bool RegCvar(string cvar, any value)
Returns true if ConVar created successfully.
ptable
void ptable(table scopeName)
Wrapper for "g_ModeScript.DeepPrintTable()". Prints data table in console.
pvel
void pvel(any entity)
Show in the chat player's velocity. Specify handle, index or targetname. Leave empty arguments' field to get speed of localplayer.
pdist
void pdist(any entity, any entity2)
Show in the chat distance between two survivors.
ppos
void ppos(Vector origin, string targetName)
Puts marks on the map in a specified position for debugging.
ppos2
void ppos2(Vector origin)
More compact bullet-sized mark.
Timer
void Timer(bool remove)
Creates HUD stopwatch. 2nd arg to remove from screen.
CPTime
void CPTime(string chatMsg)
Used in conjunction with Timer() to print timestamps.
ptp
void ptp(any survivor)
Prints in chat TeleportEntity function structure for survivor player.
DebugTrace
void DebugTrace(Vector start, Vector end, float purgeTimer)
Similar to DebugDrawLine().
find
void find(string name, bool findex)
Specify entity name to find it on the map. 2nd arg to find by only class. ST addon provides chat-command !find instead.
sm_commands.nut
This include-file converts SourceMod commands to the VScript environment. All listed plugins Speedrunner Tools[forums.alliedmods.net] and Movement Reader[forums.alliedmods.net] must be installed in order to work properly. Note that, some functions work through the native function SendToServerConsole(), execution of them is delayed by one frame. Others with prefix ST_* are based on ConVars and execute normally (don't request for the next frame).

FUNCTION
SIGNATURE
DESCRIPTION
ClientCommand
void ClientCommand(handle player, string Command)
Send the command to client.
SetClientName
void SetClientName(handle player, string playerName)
Changes a client's name.
SetAmmo
void SetAmmo(handle player, int weaponSlot, int clipSize, int ammo, int upgradeAmmo)
Send the ammo size to client.
SetTeam
void SetTeam(string survivorCharacter)
Generate team with fake clients. Enter survivor character name to play as (before execute, create at least 1 bot).
CallVote
void CallVote(handle player, string Difficulty)
Call a vote from certain player. After it done, other players on the server vote "yes" immediately.
AutoKick
void AutoKick(handle caller, handle player)
Scripted survivor bot kick. Note that, an owner of a kicked bot being joined automatically on the round end.
PlayerReplace
void PlayerReplace(handle player, handle player2)
Replaces a non-bot players.
ST_Idle
void ST_Idle(handle player, bool IsTakeOver)
Make idle for player.
ST_PlayerReplace
void ST_PlayerReplace(handle player, handle player2)
Replaces non-bot players.
ST_MR
void ST_MR(handle player, int mode, string fileName, bool noTeleport)
Record or playback player's movement. See "Hooks" title above on this page about callbacks, that function used. Mode enumeration: 0 = start recording; 1 = playback; 2 = playback from default file; 3 = split movement.
ST_MRStop
void ST_MRStop(handle player)
Stop any record/playback for a specific player. Skip args to apply stop for all players.
debug.nut
Debuggers for ScMp mode.

FUNCTION
SIGNATURE
DESCRIPTION
CPTime
void CPTime(string text, handle player)
Print in the chat current speedrun time. May be used as checkpoints on the map.
CPSetTime
void CPSetTime(float hudTime)
Set the desired speedrun time value.
CPGetTime
float CPGetTime()
Returns speedrun time value.
DebugItems
int DebugItems(string itemName, bool withDelay)
Returns dumped items count. Creates glowing signs above the items, which is currently on the map (to mark all possible items, call this function on the "round_start" event or enable "director_must_create_all_scavenge_items" ConVar instead). Specify item name, based on item model to find certain item spawns. Set delay bool if you need delay after spawn. After function is called, dump file with spawns will be created as well (left4dead2/ems/st_config/items_dump.txt).
CheckMoving
void CheckMoving(float checkDuration, bool toChat, bool newTime)
Dumps information in console/chat what movement buttons bots are used.
ZDump
void ZDump(float withDelay)
Dump zombies position and orientation to the text file (left4dead2/ems/st_config/zdump.txt).
MobListener
handle MobListener(int flags, int mobMax)
Returns CBaseEntity. Shows current finale MegaMob progress on the screen. Flags: MOB_HUD | MOB_CHAT | MOB_CONSOLE. Use without args to remove.
OBSOLETE
These aliases aren't often used and usually being avoided in further code.

FUNCTION
SIGNATURE
DESCRIPTION
GetDistance
float GetDistance(handle entity, handle entity2)
Calculates the distance between two entities.
GetSpeed
float GetSpeed(handle entity)
Calculates the speed of entity.
PlayerVel
float PlayerVel(any p)
Old alias for pvel().
PlayerDist
float PlayerDist(any p1, any p2)
Old alias for pdist().
Links
Back to the Speedrunner Tools addon.
List of chat-commands on the Commands page.
Download Speedrunner Tools Full Pack[drive.google.com], which includes SourceMod build v1.9 and all required plugins inside.
Simplified guide Customize Your Speedrun.
18 Comments
Utena Hiiragi Sep 6, 2023 @ 4:50am 
скиньте образец функции для vs_st_speedrun spawnzombieforcb
idiot 3 Aug 25, 2023 @ 11:32am 
シェイディ♑  [author] Jun 27, 2021 @ 3:29am 
Yes, SpawnZombieEx("infected", Vector(0, 0, 0));

I'd recommend you to join our Discord and ask there https://discord.gg/XQQNJNe
Ppl will help you with more enthusiasm, than here
Mustang Jun 26, 2021 @ 8:32pm 
Sorry if im being annoying, but can you provide an example of a SpawnZombie() function being used? Also, if I want to use it to spawn an infected, do I need to write it inside:

if (sName == "trigger_area1")
{

caller.Kill();


Or all the way at the bottom of the .nut file?
シェイディ♑  [author] Jun 25, 2021 @ 4:22pm 
infected = ZOMBIE_NORMAL
mob = ZSPAWN_MOB
tank = ZOMBIE_TANK
witch = ZOMBIE_WITCH
witch_bride = ZSPAWN_WITCHBRIDE
hunter = ZOMBIE_HUNTER
smoker = ZOMBIE_SMOKER
boomer = ZOMBIE_BOOMER
jockey = ZOMBIE_JOCKEY
charger = ZOMBIE_CHARGER
spitter = ZOMBIE_SPITTER
Mustang Jun 25, 2021 @ 9:29am 
whats the string value for common infected?
Artemas™ Apr 30, 2020 @ 1:07pm 
отличный инструмент!
シェイディ♑  [author] Oct 29, 2019 @ 3:26am 
Your pleasure ~
undisputed Oct 28, 2019 @ 11:50pm 
nice guide shady u god like at speedrun tho :0
Mute Aug 5, 2018 @ 2:53am 
nice