Left 4 Dead 2/Scripting: Difference between revisions

From Valve Developer Community
Jump to navigation Jump to search
mNo edit summary
m (Substituted IO templates)
 
(70 intermediate revisions by 21 users not shown)
Line 1: Line 1:
{{LanguageBar}}
{{TabsBar|main=Scripting}}
{{back|Left 4 Dead 2/Docs}}
{{toc-right}}
{{toc-right}}
{{sq}}{{l4d2}} '''Left 4 Dead 2 [[VScript|vscripts]]''' are Squirrel language-based scripts that can be run in-game. For examples, please see '''[[L4D2 Vscript Examples]]'''.


== Description ==
== Useful links ==
Left 4 Dead 2 vscripts are written in [http://squirrel-lang.org/ Squirrel], a compilable scripting language similar to [http://www.lua.org/ Lua]. The file extensions are .nut and .nuc, where .nuc denotes encryption of plain text .nut.
* [[/Game Events|List of game events]]
* [[/Script Functions|List of script functions]]
* [[/Director Scripts|Director Scripts]]
* [[/Expanded Mutation System|Expanded Mutation System]]
* [[/Mutation Gametype|Mutation Gametype]]
* [[/Decrypted mutations|Decrypted mutations]]


=== Usage ===
== Overview ==
*Director manipulation - onslaughts, CI wanderer options, complete emptiness/silence, [[L4D2_Level_Design/Boss_Prohibition|prohibition of boss infected]] (tanks and witches), direction of mobs, specific spawning behavior, etc.
{{sq}}{{l4d2}} '''Left 4 Dead 2 [[VScript]]s''' are server-side scripts that are run in an in-game virtual machine. They are written in [[Squirrel]], a compiled scripting language similar to [http://www.lua.org/ Lua]. It currently runs Squirrel version 3.0.4.
*Finale - Custom sequences of events, Gauntlet and Scavenge Logic
 
*Complex entity scripting - entity I/O, logic, arithmetic, loops, counters, timers, prop spawning, etc. (Example: Dark Carnival mini-games)
== Uses ==
*Game modes such as Mutations and Scavenge
 
*Miscellaneous!
=== [[L4D2_Director_Scripts|Director Scripts]] ===
The most common use of [[VScript]]s in ''Left 4 Dead 2'' is to temporarily influence the behavior of the AI Director. These scripts can range from simple adjustments of infected spawning and [[L4D2_Level_Design/Boss_Prohibition|prohibiting boss infected]], to custom events like onslaughts and gauntlets, and even complex staged panic events and fully [[L4D2_Level_Design/Custom_Finale|custom finales]]. Most of the events in the official campaigns are mainly implemented this way.
 
Director Scripts work mainly by writing overriding values of the various variables used by the Director into a <code>DirectorOptions</code> table.
 
Only one Director Script can be running at a time. Executing a new one will terminate any previous running one and remove any values it set in <code>DirectorOptions</code>.
 
=== [[#Entity Scripts 2|Entity Scripts ↓]] ===
Another common use is to attach a script to an entity. The script provides easy access to read and modify many of the entity's properties, and even to write new [[KeyValues]]. This allows for controlling entities in ways that would be very complicated or impossible to with the entity I/O system in Hammer.
 
Any entity is capable of running a script, and has the ability to set a specified ''think'' function to run every 0.1 seconds, as well as executing script code as an entity output.
 
Some entities also have specialized functions for VScripts, with the most prominent being {{ent|point_script_use_target}}, which allows for turning other entities into fully programmable timed buttons.
 
=== [[#Global Scripts 2|Global Scripts ↓]] ===
Scripts can also be made to run on map load, based on game mode and optionally map name. These scripts are commonly used to create pure script addons and modify global Director options for [[Mutation_Gametype_(L4D2)|mutations]].
 
Global scripts can have [[Left 4 Dead 2/Script Functions#Scripted_Mode_hooks|script hook functions]] added that get called from the game at certain events, like when players/objects take damage.
 
There are many utility functions and features readily available for these scripts, including a resource and building system, and custom panic wave spawning. Please see Valve's [[L4D2_EMS|Expanded Mutation System tutorial]] for more information.
 
=== Other Uses ===
All scripts can access functions for many features, including [[L4D2_EMS/Appendix:_Spawning|spawning entities]] either from precompiled lists or programmatically, [[L4D2_EMS/Appendix:_Spawning_Infected|spawning infected]], a [[L4D2_EMS/Appendix:_HUD|HUD system]], [[L4D2_EMS/Appendix:_Table_Save_Restore|storing data]] across levels and to disk, and much more.
 
Please see [[L4D2 Vscript Examples]] for more examples and ideas.
 
== Script Files ==
The scripts are loaded from text files with the file extensions <code>.nut</code> and <code>.nuc</code>, where <code>.nuc</code> denotes encryption of plaintext <code>.nut</code>. Custom scripts are read from '''\left 4 dead 2\left4dead2\scripts\vscripts\''', as well as '''\scripts\vscripts\''' when packed into a <code>.vpk</code> file.


=== Location ===
=== Location ===
;Official .nuc script files are located in '''scripts/vscripts''' in multiple locations
;Official <code>.nuc</code> script files are located in '''scripts/vscripts''' in multiple locations
{{note|Browse and extract [[VPK]] files with third-party programs like [[GCFScape]].}}
{{note|Browse and extract [[VPK]] files with third-party programs like [[GCFScape]].}}
*'''left 4 dead 2\left4dead2\pak01_dir.vpk'''
*'''left 4 dead 2\left4dead2\pak01_dir.vpk'''
Line 23: Line 57:
:March 22, 2011 Cold Stream Beta / L4D1 Transition Project update
:March 22, 2011 Cold Stream Beta / L4D1 Transition Project update
;*'''left 4 dead 2\update\pak01_dir.vpk'''
;*'''left 4 dead 2\update\pak01_dir.vpk'''
:This is where mutations were updated/replaced bi-weekly.
:This is where mutations were updated/replaced bi-weekly. Also contain files introduced with September 24, 2020 The Last Stand Community Update.
;*'''left 4 dead 2\sdk_content\scripting\scripts\vscripts\'''
;*'''left 4 dead 2\sdk_content\scripting\scripts\vscripts\'''
:Plaintext versions of many of the scripts introduced in the EMS update.
:Plaintext versions of many of the scripts introduced in the EMS update.


=== Decrypting NUC Files ===
.nuc files are ICE encrypted .nut files. The encryption key is '''SDhfi878'''. You can use [[VICE]] to decode them.<br>
You may find decrypted mutation vscripts [[L4D2_Decrypted_mutations|here]].
== Loading VScripts ==
VScripts are loaded in a variety of ways, depending on their context. They can also be manually loaded with the console command <code>script_execute ''filename''</code>.
=== Director Scripts ===
;*{{ent|info_director}} inputs
{{I|BeginScript|param=scriptlist|Executes generic Director scripts, whether for onslaught events or changing spawning behavior.}}
:They are placed in the <code>LocalScript</code> script scope.
{{I|EndScript|Ends the currently running local script, then resets the Director options to either map-specific values, or default values.}}
{{I|ScriptedPanicEvent|param=scriptlist|With the given scripts, set up the structure of a [[L4D2 Director Scripts#Finales and Scripted Panic Events|scripted panic event]].}}
:They are placed in the <code>LocalScript</code> script scope.
{{note|The scripts of these inputs ''must'' reside under the "vscripts" subfolder. Events will play out only the 1 second DELAY "stage 0" otherwise.}}
;*[[L4D2 Director Scripts#Finales and Scripted Panic Events|Finale scripts]]
:As a {{ent|trigger_finale}} finale starts, it loads a script of this format: <code>[mapname]_finale.nut</code>.
:They are placed in the <code>g_MapScript</code> script scope.


=== Decrypting NUC files ===
=== Entity Scripts ===
.nuc files are ICE encrypted .nut files. The encryption key is '''SDhfi878'''. You can use [[VICE]] to decode them.  
;*Keyvalue
{{KV|Entity Scripts|intn=vscripts|scriptlist|As an entity is preparing itself before it spawns, the VScript path names in that keyvalue will be ran. (See [[L4D2_Vscripts#Entity_Scripts_3|Entity Scripts]] for more info.)}}
;*Input
{{I|RunScriptFile|param=script|Inserts the given script into the entity's scope, then runs it.}}


[[#External_links|Packages with deciphered official scripts are also available.]]
Entity Scripts are placed in the <code>_<unique ID>_<entity name></code> script scope.


== Loading vscripts ==
=== Global Scripts ===
*Entities
;*Mode scripts
**Any entity is capable of loading a script on map spawn.
:A script with the same name as the current [[Mutation_Gametype_(L4D2)|game mode]]. Loaded when a new mode is set.
**The vscript can be reloaded with console command <code>ent_fire <name of entity> runscriptfile <relative vscript path></code>. This is useful for quick script reloading.
:They are placed in the <code>g_ModeScript</code> script scope.
**Script functions can be called with entity inputs like <code>RunScriptCode</code>.
:{{tip|The <code>map</code> command can also set gamemodes. For example, <code>map <map name> mutation12</code> loads the Realism Versus mode script, <code>mutation12.nuc</code>.}}
**Features '''thinkfunction''', a [[Keyvalue|keyvalue]] that calls a user-defined function every 0.1 seconds. While it has the potential to become expensive, a programmer is able to limit the amount of code executed. The shoot gallery in Dark Carnival relies on this.
:{{note|Adding a script for a mode will enable Scripted Mode.}}
**Some functions are specialized for certain entity classes, such as [[point_template]] and [[env_entity_maker]].
**Also available is [[logic_script]], an entity that registers multiple entities as an array EntityGroup.
*[[info_director]]
**Loads DirectorOptions such as onslaughts, panic events, infected limits, etc.
**Custom DirectorOptions are used frequently to tweak director behavior that best suits the environment. c1_mall_ambient.nut is one such example.
**Uses script scope <code>DirectorScript</code>
{{note|Scripts used with <code>ScriptedPanicEvent</code> will not work if they are in a subdirectory, even though you can use subdirectories in other script contexts. They must reside under the vscripts folder, or they will simply act as a 1 stage 1 second delay.}}
*Game Modes
**Mode Specific Script
***Will automatically run the script with the same name as the [[Mutation_Gametype_(L4D2)|game mode]].
***For example, running a map <code>map <map name> mutation12</code> will automatically load the Realism Versus script, mutation12.nuc.
***Uses script scope <code>g_ModeScript</code>
***{{note|Adding a script for a mode will enable Scripted Mode on it. This works on the base modes as well, and will enable [[L4D2_EMS|EMS]] [[L4D2_EMS/Appendix:_Game_Events|game event callbacks]] and hooks. {{todo|Does this have any other consequences?}} }}
**Map Specific Script
***Per-map scripts can be created that run when the map is loaded in the specified game mode.
***The script naming syntax is <map name>_<mode name>.nut.
***For example, c1m4_atrium_mutation12.nut.
***Uses script scope <code>g_MapScript</code>


*Finale
;*Map-specific mode scripts
**Loaded via [[trigger_finale]], either automatically or pointing to a specific vscript.
:Per-map scripts when the map is loaded in the specified game mode. They are in the name format: ''<nowiki>[mapname]_[modename].nut</nowiki>''.
**Automatically loads <map name>_finale.nut script on finale start.
:They are placed in the <code>g_MapScript</code> script scope.
**[[L4D2 Level Design/Scavenge Finale|Scavenge]], [[L4D2 Level Design/Custom Finale|Custom]], and [[L4D2 Level Design/Gauntlet Finale|Gauntlet]] finales are dependent on vscripts.
**Uses script scope <code>DirectorScript</code>


== Example scripts ==
;*Addon scripts
'''Please see [[L4D2 Vscript Examples]].'''
:These scripts vary in context, but they all share one big attribute: they don't override files with the same name, but instead load alongside them. They are executed in the order below, each after its respective base script (without <code>_addon</code> suffix). A script is considered an "addon script" if it's named as:
:# <code>mapspawn_addon.nut</code> (runs once every chapter) - <code>getroottable()</code> scope
:# <code>response_testbed_addon.nut</code> (runs once every chapter) - <code>g_rr</code> scope
:# <code>scriptedmode_addon.nut</code> (runs twice every round) - <code>g_MapScript</code> scope
:# <code>director_base_addon.nut</code> (runs twice every round) - <code>DirectorScript</code> scope


== Scripting environment ==
== Scripting Environment ==
'''Please see [[List of L4D2 Script Functions]] for built in classes and functions.'''  
'''Please see [[Left 4 Dead 2/Script Functions]] for built in classes and functions.'''  


{{todo|Add better description of the script scopes.}}
When a script is loaded, it is placed into a table, or Script Scope. Global and Director Scripts are put into set scopes, while a unique scope is generated for each Entity Script. Please see [[Vscript Fundamentals]] for more information.


=== Table structure ===
=== Table Structure ===
<source lang=cpp>
<source lang=cpp>
DirectorScript = //Director scripts get loaded here.
DirectorScript = // Base Director Scope.
{
{
DirectorOptions //Active when a director script is, and during scripted events and finales(?).
DirectorOptions // Base DirectorOptions table.
MapScript =  //Reference to g_MapScript. Contains initial values.
MapScript =  // Script scope for either map scripts or trigger_finale scripts
{
{
BaseScriptedDOTable //Hardcoded DirectorOptions.
DirectorOptions       
ChallengeScript = //Reference to g_ModeScript. Contains initial values.
BaseScriptedDOTable // Default DirectorOptions for Scripted mode
ChallengeScript = // Script scope for mode scripts
{
{
MutationState //Populated with the the mode and map names.
DirectorOptions // Filled with BaseScriptedDOTable, MutationOptions and MapOptions; if identical keys are present then the most-right table gets precedence.
MutationState // Filled with MapState overwriting previous values
MutationOptions // Initial values used if defined in mode script
}
}
LocalScript =
LocalScript = // Script scope for scripts executed through info_director 'BeginScript' or 'ScriptedPanicEvent' inputs
{
{
DirectorOptions //Current DirectorOptions(?).
DirectorOptions // DirectorOptions for current Director Script (like onslaughts). Only available when a script is active
}
}
MapOptions // Initial values used if defined in map script
MapState // Initial values used if defined in map script
}
}
}
}
g_MapScript = //Map specific scripts get loaded here.
g_MapScript // Global reference to the Map Script scope (DirectorScript.MapScript).
{
g_ModeScript // Global reference to the Mode Script scope (DirectorScript.MapScript.ChallengeScript).
MapOptions //Initial values for SessionOptions.
SessionOptions // Global reference to g_ModeScript.DirectorOptions (Scripted mode only).
MapState //Initial values for SessionState.
SessionState  // Global reference to g_ModeScript.MutationState (Scripted mode only).
}
 
g_ModeScript = //Mode specific scripts get loaded here (Scripted mode only).
g_rr // Scope holding the Response Rule system.
{
g_RoundState // TODO
DirectorOptions //Current Director options, outside scripted events.
MutationState //Initial values for SessionState.
MutationOptions //Initial values for SessionOptions.
}
g_rr
g_RoundState
SessionOptions //Global Director options (Scripted mode only).
SessionState  //State variables for game modes (Scripted mode only).
</source>
</source>


=== Delegation ===
=== Delegation ===
Some of the tables have [http://squirrel-lang.org/doc/squirrel3.html#d0e2038 delegation] set up, so that if a key isn't present in it, any operation done to done to the value, including creating the slot, is done to its parent-table instead.
Some of the tables have [http://squirrel-lang.org/doc/squirrel3.html#d0e2038 delegation] set up, so that if a key isn't present in it, it is read from its delegate (usually parent) table instead.


;DirectorOptions
The tables are delegated like this (delegates on the right):
:<code>DirectorScript.DirectorOptions < DirectorScript.MapScript.DirectorOptions < DirectorScript.MapScript.LocalScript.DirectorOptions < DirectorScript.MapScript.ChallengeScript.DirectorOptions</code>
; The Director Scope
: <code>(DirectorScript.MapScript.ChallengeScript or DirectorScript.MapScript.LocalScript) < DirectorScript.MapScript < DirectorScript < ::</code>
; DirectorOptions
: <code>DirectorScript.MapScript.ChallengeScript.DirectorOptions (Scripted mode only) < DirectorScript.MapScript.LocalScript.DirectorOptions (when Director Script active) < DirectorScript.MapScript.DirectorOptions < DirectorScript.DirectorOptions</code>
: See GetDirectorOptions in {{ent|director_base.nut}}.


== Director scripts ==
== Entity Scripts ==
Use script scope <code>_<unique ID>_<entity name></code>


{{Merge|L4D2 Director Scripts}}
Adding a script to the '''Entity Scripts''' KeyValue of a server-side entity loads the script as an Entity Script. The script is executed when the entity spawns, and loads into a unique script scope made up of an unique identifier followed by the entity name or class name.


{{Warning|}}NEVER use the = operator when trying to influence the director. Use <-. The difference is semantics. If you use =, it will throw an error if the table slot isn't defined (like if a previous script didn't define it). <-, on the other hand, will create the variable if it does not exist.
A think function can be set with the <code>thinkfunction</code> [[Keyvalue|KeyValue]], the specified script function every 0.1 seconds. While it has the potential to become expensive, a programmer is able to limit the amount of code executed. Functions can also be manually called through the I/O system with the input <code>RunScriptCode ''function_name(argument, …)</code>.


Entity Scripts have a <code>self</code> reference to their owning entity handle, allowing the script easy access to control the entity through its class methods. There are also hook functions available depending on the entity class. Both methods and hooks are documented [[Left 4 Dead 2/Script Functions#Classes|here]].


{{todo|There is a lot more where these came from.}}
Some entities have additional script functionality:
*Director Enumerations {{note|These are (or some are) '''script specific''', hence the duplicate values.}}
*{{ent|point_script_use_target}} - Has both methods and hooks for controlling the button.
**FINALE_CUSTOM_DELAY = 10
*{{ent|logic_script}} - Can pass multiple entity names to the script as an array called <code>EntityGroup</code>.
**FINALE_CUSTOM_PANIC = 7
*{{ent|point_template}}
**FINALE_CUSTOM_SCRIPTED = 9
*{{ent|env_entity_maker}}
**FINALE_CUSTOM_TANK = 8
*{{ent|info_item_position}}
**FINALE_FINAL_BOSS = 5
**FINALE_GAUNTLET_1 = 0
**FINALE_GAUNTLET_2 = 3
**FINALE_GAUNTLET_BOSS = 15
**FINALE_GAUNTLET_BOSS_INCOMING = 14
**FINALE_GAUNTLET_ESCAPE = 16
**FINALE_GAUNTLET_HORDE = 12
**FINALE_GAUNTLET_HORDE_BONUSTIME = 13
**FINALE_GAUNTLET_START = 11
**FINALE_HALFTIME_BOSS = 2
**FINALE_HORDE_ATTACK_1 = 1
**FINALE_HORDE_ATTACK_2 = 4
**FINALE_HORDE_ESCAPE = 6
**SPAWN_ABOVE_SURVIVORS = 6
**SPAWN_ANYWHERE = 0
**SPAWN_BEHIND_SURVIVORS = 1
**SPAWN_FAR_AWAY_FROM_SURVIVORS = 5
**SPAWN_IN_FRONT_OF_SURVIVORS = 7
**SPAWN_LARGE_VOLUME = 9
**SPAWN_NEAR_IT_VICTIM = 2
**SPAWN_NO_PREFERENCE = -1
**SPAWN_SPECIALS_ANYWHERE = 4
**SPAWN_SPECIALS_IN_FRONT_OF_SURVIVORS = 3
**SPAWN_VERSUS_FINALE_DISTANCE = 8
**ZOMBIE_TANK = 8
**ZOMBIE_WITCH = 7


The script can be reloaded with console command <code>ent_fire <name of entity> runscriptfile ''<relative vscript path>''</code>. This is useful for quick script reloading.


=== Director options ===
=== [[Inputs_and_Outputs|I/O system]] Interaction ===
Any script can use the <code>EntFire()</code> and <code>DoEntFire()</code> functions to fire outputs to map entities. Since the ''<code>activator</code>'' and ''<code>caller</code>'' arguments in <code>DoEntFire()</code> take a script handle, it can be used to fire an output to an entity using the {{ent|!self}} or {{ent|!activator}} keyword, even without having to know its name, as long as the entity handle is available.


This is by no means an exhaustive list of all the director options. Additions and updates can be found in the [http://forums.steampowered.com/forums/showthread.php?t=1238461 Steam Forums]
<source lang=cpp>
*'''A_CustomFinaleX''' = stage type (enumerated PANIC, ONSLAUGHT, DELAY, TANK); where X is the stage number. For scripted panic event or custom finale.
EntFire( "church_bell_relay", "Trigger", 0 ); // Fires an output to the Trigger input of the named entity.
*'''A_CustomFinaleValueX''' = Value depends on the stage type. Please see example article or official decrypted scripts. For scripted panic event or custom finale.
*'''AllowCrescendoEvents''' = ??? (not sure what this does)
*'''AllowWitchesInCheckpoints''' = ??? (not sure what this does)
*'''AlwaysAllowWanderers''' = true|false
*'''BehindSurvivorsSpawnDistance''' = Appears to require ''PreferredSpecialDirection = SPAWN_BEHIND_SURVIVORS''
*'''BileMobSize''' = number of commons that spawn when a bile bomb is thrown.  Appears to only work in finale. Found in Dead Center and The Sacrifice finales.
*'''BoomerLimit''' = maximum number of boomers allowed
*'''BuildUpMinInterval'''
*'''ChargerLimit''' = maximum number of chargers allowed
*'''ClearedWandererRespawnChance''' = percent chance (0-100) that cleared nav areas will get re-populated with wanderers.
*'''CommonLimit''' = maximum number of commons allowed
*'''DisallowThreatType''' = ZOMBIE_WITCH, ZOMBIE_TANK (other values???) Ex: c8m1_apartment.nut
*'''FallenSurvivorPotentialQuantity''' = int
*'''FallenSurvivorSpawnChance''' = float [0...1]
*'''DominatorLimit''' {{todo|confirm category/working}}
*'''GasCansOnBacks''' = true|false
*'''HunterLimit''' = maximum number of hunters allowed
*'''IgnoreNavThreatAreas''' = ??? (not sure what this does)
*'''InfectedFlags''' = INFECTED_FLAG_CANT_SEE_SURVIVORS, INFECTED_FLAG_CANT_HEAR_SURVIVORS, INFECTED_FLAG_CANT_FEEL_SURVIVORS
*'''IntensityRelaxAllowWanderersThreshold'''
*'''IntensityRelaxThreshold''' = All survivors must be below this intensity before a Peak is allowed to switch to Relax (in addition to the normal peak timer)
*'''IntensityThreshold'''
*'''JockeyLimit''' = maximum number of jockeys allowed
*'''LockTempo''' = (0/1) Endless panics consist of: spawn horde -> BUILD_UP -> SUSTAIN_PEAK -> RELAX -> spawn horde again. Locktempo = 1 removes the "BUILD_UP -> SUSTAIN_PEAK -> RELAX" bit making your hordes spawn constantly without a delay.
*'''MaxSpecials''' = number of specials allowed at once
*'''MegaMobMaxSize''' = maximum megamob size
*'''MegaMobMinSize''' = minimum megamob size
*'''MegaMobSize''' {{todo|confirm category/working}}
*'''MinimumStageTime''' = in seconds Ex: c1m4_delay.nut {{todo|possibly finale or custom panic event specific}}
*'''MobMaxPending''' = Guessing it's the maximum mob size that can be pending for spawn.
*'''MobMaxSize''' = max mob size
*'''MobMinSize''' = min mob size
*'''MobRechargeRate''' = Guessing it's the speed at which a mob regenerates (ie next mob)
*'''MobSpawnMaxTime''' = max time in seconds for mob spawn
*'''MobSpawnMinTime''' = min time in seconds? for mob spawn
*'''MobSpawnSize'''
*'''MusicDynamicMobScanStopSize''' = When see fewer than this many of a mob, music stops
*'''MusicDynamicMobSpawnSize''' = ???Spawning a mob this large can play music
*'''MusicDynamicMobStopSize''' = When a mob gets to this size we think about stopping the music
*'''NumReservedWanderers''' = the number of infected that cannot be absorbed
*'''PanicForever''' * this seems to only work in gauntlets
*'''PanicWavePauseMax''' (float) {{todo|confirm category/working}}
*'''PanicWavePauseMin''' (float) {{todo|confirm category/working}}


*'''PreferredMobDirection''' = SPAWN_ABOVE_SURVIVORS, SPAWN_ANYWHERE, SPAWN_BEHIND_SURVIVORS, SPAWN_FAR_AWAY_FROM_SURVIVORS, SPAWN_IN_FRONT_OF_SURVIVORS , SPAWN_LARGE_VOLUME, SPAWN_NEAR_IT_VICTIM, SPAWN_NO_PREFERENCE
player <- null;
 
while(player = Entities.FindByClassname(player, "player"))  // Iterate through the script handles of the players.
{{note|SPAWN_NEAR_IT_VICTIM does not exist before a finale and will cause an error, so I'm assuming the director picks someone as IT when the finale starts. SPAWN_LARGE_VOLUME is what makes you be a mile away on DC finale.}}
{
 
    DoEntFire("!self", "speakresponseconcept", "PlayerLaugh", 0, null, player); // Make each player laugh.
*'''PreferredSpecialDirection '''
}
{{note|The same values for PreferredMobDirection appear to work, BUT I've also seen the following, I don't know if it's just redundancy or what.
</source>
SPAWN_SPECIALS_ANYWHERE
SPAWN_SPECIALS_IN_FRONT_OF_SURVIVORS}}
 
*'''PreTankMobMax''' = int {{todo|confirm category/working; possibly gauntlet specific}}
*'''ProhibitBosses''' = true|false - prohibit tanks/witches
*'''RelaxMaxFlowTravel''' = 600
*'''RelaxMaxInterval''' = 5
*'''RelaxMinInterval''' = 5
*'''ShouldAllowMobsWithTank''' = true|false
*'''ShouldAllowSpecialsWithTank''' = true|false
*'''ShouldConstrainLargeVolumeSpawn''' = true|false
*'''SmokerLimit''' = maximum number of smokers allowed
*'''SpawnDirectionMask''' = a bitfield (using SPAWNDIR_N, _NE, _E, etc) of directors to spawn from _relative to_ a map entity named "Compass" in your map. So the idea is that if you are making a mutation in a confined area, put the compass at the middle (angle determines north) and then you can spawn relative directions around it. Note this layers onto the SpawnSetRule - i.e. if you set a POSITIONAL rule south of the compass, and then set a SpawnDirectonMask of SPAWNDIR_N, the Director will never find a valid place to spawn (since the position is saying "pick from this radius south of here" and the mask is saying "now take that list of valid places and find one north")
*'''SpawnSetRule''' = SPAWN_FINALE, SPAWN_BATTLEFIELD, SPAWN_SURVIVORS, SPAWN_POSITIONAL
**SpawnSetRadius/SpawnSetPosition: A radius in units, a Vector(x,y,z) center point for POSITIONAL spawning
*'''SpecialInfectedAssault''' = ??? (not sure what this does)
*'''SpecialInitialSpawnDelayMin'''
*'''SpecialInitialSpawnDelayMax'''
*'''SpecialRespawnInterval''' = time in seconds for special respawns
*'''SpitterLimit''' = maximum number of spitters allowed
*'''SurvivorMaxIncapacitatedCount''' = Maximum amount of survivor incapacitating before dying
*'''SustainPeakMaxTime''' = in minutes
*'''SustainPeakMinTime''' = in minutes
*'''TankHitDamageModifierCoop''' = float (mutation1.nut Last Man on Earth) {todo|confirm category}}
*'''TankHitDamageModifierVersus''' = float {{todo|confirm category}}
*'''TankLimit''' = maximum number of tanks allowed (for example, used in c7m3_port.nut)
*'''TankRunSpawnDelay''' = in seconds (mutation19.nut Taaannnkk!) {{todo|confirm category}}
*'''TempHealthDecayRate''' = 0.27 // pain_pills_decay_rate default, higher values equals quicker decay
*'''TotalBoomers''' = number of boomers allowed in a wave
*'''TotalChargers''' = number of chargers allowed in a wave
*'''TotalHunters''' = number of hunters allowed in a wave
*'''TotalJockeys''' = number of jockeys allowed in a wave
*'''TotalSmokers''' = number of smokers allowed in a wave
*'''TotalSpecials''' = number of specials allowed in a wave
*'''TotalSpitters''' = number of spitters allowed in a wave
*'''WanderingZombieDensityModifier''' = float {{todo|confirm category/working}}
*'''WitchLimit''' = maximum number of witches allowed (used in c7m3_port.nut)
*'''ZombieSpawnRange''' = How far away can zombies spawn?
*'''ZombieSpawnInFog''' = true|false
*'''ZombieTankHealth''' = tanks health


*'''function Update()'''
Conversely, the <code>[[Left 4 Dead 2/Script Functions#CBaseEntity|CBaseEntity]]::ConnectOutput()</code> and <code>DisconnectOutput()</code> functions can be used to call a script function when the specified entity output fires.
:If you define an Update() function in your vscript, it will run repeatedly much like a Think() function, but ONLY a finale via [[trigger_finale]] is triggered, if you have multiple scripts that are running that define it, they all will be called. The use of Update() is also found in the Bleed Out mutation (mutation3.nut), but needs further testing to see see if it behaves the same way like during a finale.
In addition, arbitrary VScript code can be run from the I/O system, using the <code>RunScriptCode</code> input available in all entities. The code will run in the current entities script scope.
{{warning|Never use double-quotation marks in any Hammer Output, since it will corrupt the map file. This means that strings cannot be passed with <code>RunScriptCode</code>.}}


==== Finale Specific/Related ====
== Global Scripts ==
A normal finale consists of X number of stages. Some variables in DirectorOptions can only be used during finales.
Naming a script file with a game mode name makes it a mode specific script which executes every time a map is loaded in the specified mode. If a Mode Script exists, a map specific script with the map name followed by an underscore and the mode name can also be loaded.
*'''A_CustomFinale_StageCount''' = number of stages. Needs to be set for Versus scoring to function properly.
*'''A_CustomFinaleX''' = stage type (enumerated PANIC, ONSLAUGHT (AKA SCRIPTED), DELAY, TANK), where X is the stage number. Also used in scripted panic events.
*'''A_CustomFinaleValueX''' = Value depends on the stage type above. Also used in scripted panic events. Please see the example.
*'''A_CustomFinaleMusicX''' = [[Soundscript]] entry to play. For instance, <code>A_CustomFinaleMusic1 = "C2M5.BadManTank2"</code>. Note that c2m5_concert_finale.nut does not use this method and instead opted to use entities within the map instead. In the c2m5 script <code>A_CustomFinaleMusic4 = ""</code>, suggesting that no song is actually played automatically via script.
{{note|There is also a D_CustomFinale_StageCount, D_CustomFinaleX, etc. found in c3m4_plantation_finale.nut but the difference between A and D are unknown. B_, C_, and E_ are also available. These are likely used to allow multiple staged panic events and/or a finale in the same script.}}
*'''EnforceFinaleNavSpawnRules''' = ??? Likely used to enforce the finale spawning behavior without running a finale. {{todo|confirm category/working}}
*'''EscapeSpawnTanks''' = true|false
*'''HordeEscapeCommonLimit''' = number of commons allowed when the escape vehicle has arrived
*'''function OnBeginCustomFinaleStage( num, type )'''
:If defined, will be called on every stage change with the number, and type, this is how you would change director options between stages (spawn directions, etc). <code>num</code> refers to the finale stage number passed by the director and <code>type</code> is the stage type (PANIC, TANK, etc.).
*'''function OnChangeFinaleMusic()''' {{todo|confirm category/working}}


A stage can be one of 4 types (other values will break the finale and go right to ESCAPE):
=== Mode Scripts ===
*PANIC - a panic event, the value is the number of them (ie 2 would be 2 panic events in a row)
Use script scope <code>g_ModeScript</code>
*TANK - spawn a tank(s), the value is the number of tanks to spawn
*DELAY - a delay, the value is the number of seconds to wait before proceeding to the next stage
*ONSLAUGHT/SCRIPTED - The value should be the name of a vscript to call or "" (which will do nothing), any bad value here will crash you to the desktop. Your onslaught script is responsible for sending an EndCustomScriptedStage input to the director (a goal of your choice, like a certain trigger volume, timer, random value, etc.). [[trigger_finale]] input AdvanceFinaleState may also work. Otherwise, the '''onslaught will not end.'''


An example custom finale script:
==== Tables ====
{{ScrollBox|<source lang=cpp>
;<code>MutationState</code>
ERROR <- -1
:Initial values for the <code>SessionState</code> table.
PANIC <- 0
;<code>MutationOptions</code>
TANK <- 1
:Initial values for the <code>SessionOptions</code> table.
DELAY <- 2
ONSLAUGHT <- 3 // In some vscripts (c8m5_rooftop_finale), ONSLAUGHT is labeled as SCRIPTED


DirectorOptions <-
=== Map Scripts ===
{
Use script scope <code>g_MapScript</code>
//-----------------------------------------------------
CommonLimit = 10
A_CustomFinale_StageCount = 8 
A_CustomFinale1 = PANIC
A_CustomFinaleValue1 = 2  // two panic events
A_CustomFinale2 = DELAY
A_CustomFinaleValue2 = 12  // delay for twelve seconds in addition to stage delay
A_CustomFinale3 = TANK
A_CustomFinaleValue3 = 3  // 3 tanks!
A_CustomFinale4 = DELAY
A_CustomFinaleValue4 = 12 // wait some more
A_CustomFinale5 = ONSLAUGHT
A_CustomFinaleValue5 = "my_onslaught_script.nut" // run our onslaught script
A_CustomFinale6 = DELAY
A_CustomFinaleValue6 = 15 // wait 15 seconds
A_CustomFinale7 = TANK
A_CustomFinaleValue7 = 1  // one more tank


A_CustomFinale8 = DELAY
==== Tables ====
A_CustomFinaleValue8 = 10 // wait ten seconds ... rescue!
;<code>MapState</code>
:Map specific values for the <code>SessionState</code> table.
SpecialRespawnInterval = 25
;<code>MapOptions</code>
:Map specific values for the <code>SessionOptions</code> table.


//-----------------------------------------------------
=== Scripted Mode ===
}
Adding a Mode Script will enable Scripted Mode for the game mode. This works on the base game modes included in the game as well.


function OnBeginCustomFinaleStage( num, type )
Scripted Mode loads utility functions into the <code>g_MapScript</code> scope, disables the hardcoded setting of 2 on the <code>MaxSpecials</code> Director option, and enables [[L4D2_EMS/Appendix:_Game_Events|game event callbacks]] and [[Left 4 Dead 2/Script Functions#Scripted_Mode_hooks|script hook functions]]. It also seems to break the finale tank music in Dark Carnival.
{
      printl( "Beginning custom finale stage " + num + " of type " + type );
      MapScript.DirectorOptions.CommonLimit = num * 10 // increase commons by 10 linearly with stages
}</source>}}


==== Gauntlet Specific/Related ====
{{todo|Does enabling Scripted Mode have any other consequences?}}
Most of these can be found in director_gauntlet.nut
*'''CustomTankKiteDistance''' (3000 is the default) {{todo|confirm category/working}}


Movement Bonus related options. The Movement Bonus successively increases the delay between hordes when the survivors are not making progress toward the Gauntlet goal. The Current Bonus value ticks down every second, allows a horde to spawn when it reaches 0. When a horde spawns the Current Bonus is reset to the Movement Bonus value. The Movement Bonus increases at set intervals, and is reset when the survivors cross the Movement Threshold, which is then incremented. Use ''director_debug 1'' to see the values.
==== Available Functions ====
*'''GauntletMovementThreshold''' = float The amount of flow units the survivors can advance before the Movement Bonus is reset.
{{todo|Document the available utility features.}}
*'''GauntletMovementTimerLength''' = float The interval between each Movement Bonus increase, in seconds.
*'''GauntletMovementBonus''' = float The initial value, and the amount the movement Bonus increases each interval, in seconds.
*'''GauntletMovementBonusMax''' = float The maximum value that the Movement Bonus can reach.


==== Mutation Specific/Related ====
=== Shared Tables ===
Some of these values are mutation specific values of the global ones (cm_CommonLimit,cm_MaxSpecials, etc.), so use them if you are making a mutation, incase any map scripts are changing the global values.
;<code>SessionState</code>
:A table for storing session specific variables. Not preserved across level transitions.
;<code>SessionOptions</code>
:Active [[L4D2_Director_Scripts#DirectorOptions|Director Options]] for the game mode.


*'''ActiveChallenge'''
== Glossary ==
*'''cm_AggressiveSpecials'''
;DirectorOptions
*'''cm_AllowPillConversion'''
:A table of named variables that override the AI Director behavior.
*'''cm_AllowSurvivorRescue'''
;Entity handle
*'''cm_AutoReviveFromSpecialIncap''' Used by "The Last Man On Earth" and "Lone Gunman" mutations (mutation1.nut and mutation17.nut)
:Also known as EHANDLE. {{todo|Looks like some sort of pointer reference to an entity.}}
*'''cm_AutoSpawnInfectedGhosts'''
;Script handle
*'''cm_BaseCommonAttackDamage'''
:An entity instance with accessors and mutators to the C++ entity object. Also known as HScript.
*'''cm_BaseSpecialLimit'''
;Script scope
*'''cm_CommonLimit'''
:The table where the variables, functions and classes of a VScript are placed.
*'''cm_DominatorLimit'''
*'''cm_FirstManOut''' Used by the "Room For One" mutation (mutation10.nut)
*'''cm_frustrationTimer'''
*'''cm_HeadshotOnly'''
*'''cm_HealingGnome'''
*'''cm_InfiniteFuel''' (mutation7.nut Chainsaw Massacre)
*'''cm_MaxSpecials'''
*'''cm_NoRescueClosets'''
*'''cm_NoSurvivorBots'''
*'''cm_ProhibitBosses'''
*'''cm_CommonLimit'''
*'''cm_ShouldEscortHumanPlayers'''
*'''cm_ShouldHurry'''
*'''cm_SingleScavengeCluster''' Used for scavenge cans to spawn one-by-one
*'''cm_SpecialRespawnInterval'''
*'''cm_SpecialSlotCountdownTime'''
*'''cm_SpecialsRetreatToCover'''
*'''cm_TankLimit'''
*'''cm_TankRun''' Used in Taaank! mutation (mutation19.nut)
*'''cm_TempHealthOnly''' Only temporary health
*'''cm_VIPTarget'''
*'''cm_WanderingZombieDensityModifier'''
*'''cm_WitchLimit'''
 
*'''function AllowWeaponSpawn()'''
:Returns true or false if the given classname is allowed to spawn, used by several mutations
*'''function ConvertWeaponSpawn()'''
:Converts a weapon spawn of given classname to another, used by several mutations
*'''function ConvertZombieClass()'''
:Converts one spawn into another, used by the tankss! mutation (mutation19.nut)
*'''function GetDefaultItem()'''
:ID starts from 0 and ends in an unknown point. Return a string of a weapon name to make it a default item for survivors. Used in several mutations
*'''function ShouldAvoidItem()'''
:Probably a bot related function or spawn related, not sure


==== Scavenge Specific/Related ====
== Director Options ==
*'''ScavengeClusterBonusTime''' = float {{todo|confirm category/working}}
'''Please see [[L4D2 Director Scripts#DirectorOptions|L4D2 Director Scripts]] for a table of available options.'''
*'''ScavengeRoundInitialTime''' = float {{todo|confirm category/working}}
*'''ScavengeScoreBonusTime''' = float (used in mutation13.nut Follow the Liter)


==== Survival Specific/Related ====
== Third-Party Tools ==
*'''SurvivalSetupTime''' = (Used in mutation15.nut for Survival Versus with setup time of 90 seconds)


== Third party tools ==
===VSLib===
{{todo|Add info about VSLib}}
'''VSLib''' (''VS''cript ''Lib''rary) is a simple, lightweight library for L4D2's VScript mutation system. It greatly simplifies coding VScripts by taking care of a lot of tedious work for you. It is used in several popular mods like [http://steamcommunity.com/sharedfiles/filedetails/?id=214630948 Rayman1103's Admin System] and [http://steamcommunity.com/sharedfiles/filedetails/?id=157525096 Stranded]. Read more about [[VSLib]].


== See also ==
== See also ==
=== Intros ===
*[[VScript]]
*[[Mutation Gametype (L4D2)]]
=== Documentations ===
*[[VSLib]]
*[[L4D2 Vscript Examples]]
*[[L4D2 Vscript Examples]]
*[[List of L4D2 Script Functions]]
*[[L4D2_Director_Scripts|L4D2 Director Scripts]]
*[[Left 4 Dead 2/Script Functions|L4D2 Script Functions]]
*[[L4D2_Decrypted_mutations|Decrypted Mutation Vscripts]]
*[[L4D2_Level_Design/Boss_Prohibition|L4D2 Level Design/Boss Prohibition]]
*[[L4D2_Level_Design/Custom_Finale|Custom Finales]] ''Contains all original finale scripts as reference.''
*[[L4D2 EMS|Extended Mutation System]]
*[[L4D2 EMS|Extended Mutation System]]
*[[L4D2_Level_Design/Boss_Prohibition|L4D2 Level Design/Boss Prohibition]]
*[[Left_4_Dead_2_Tool_Updates|Left 4 Dead 2 Tool Updates]]
*[[Left_4_Dead_2_Tool_Updates|Left 4 Dead 2 Tool Updates]]
*[[Mutation Gametype (L4D2)]]
 
*[[Trigger_finale|trigger_finale]]
=== Miscelleanous ===
*[[Info_director|info_director]]
*{{ent|logic_script}}
*[[Logic_script|logic_script]]
*{{ent|trigger_finale}}
*[[VScript|vscripts]]
*{{ent|info_director}}


== External links ==
== External links ==
;Alternative Tool
* [http://www.mediafire.com/?q4dqbs554p494vk (mediafire)L4D2 VScript Editor Beta 0.5 by Cynick:support nut (de)compile for l4d2]
;Alternative Documentation
;Alternative Documentation
* [http://forums.steampowered.com/forums/showthread.php?t=1128303 Director Scripts - .nuc files (Steam forums)]
* [http://forums.steampowered.com/forums/showthread.php?t=1128303 Director Scripts - .nuc files (Steam forums)] {{deadlink}}
* [http://forums.steampowered.com/forums/showthread.php?t=1238461 It's the vscript'ing documentation FAQ! (Steam forums)]
* [http://forums.steampowered.com/forums/showthread.php?t=1238461 It's the vscript'ing documentation FAQ! (Steam forums)] {{deadlink}}
* [http://forums.steampowered.com/forums/showthread.php?t=1242468 Tutorial - Writing a Mini Game - Tic Tac Toe - Part One (Steam Forums)]
* [http://forums.steampowered.com/forums/showthread.php?t=1242468 Tutorial - Writing a Mini Game - Tic Tac Toe - Part One (Steam Forums)] {{deadlink}}
**[http://www.leeland.net/l4d2-scripts-play-tic-tac-toe.html Writing a Mini Game - Tic Tac Toe - Part One] - Author's Website
**[http://leeland.stores.yahoo.net/l4d2-scripts-play-tic-tac-toe.html Writing a Mini Game - Tic Tac Toe - Part One] - Author's Website {{deadlink}}
**[http://www.youtube.com/watch?v=B9hASsoHK54 l4d2 - Vscript example - Tic-Tac-Toe] - Video of early Prototype
**[http://www.youtube.com/watch?v=B9hASsoHK54 l4d2 - Vscript example - Tic-Tac-Toe] - Video of early Prototype
**[http://www.youtube.com/watch?v=mvDFEoA0ib0 l4d2 - Vscript example - Tic-Tac-Toe - updated] - Video of current version with "brutally misanthropic AI"
**[http://www.youtube.com/watch?v=mvDFEoA0ib0 l4d2 - Vscript example - Tic-Tac-Toe - updated] - Video of current version with "brutally misanthropic AI"
* [http://forums.steampowered.com/forums/showthread.php?t=1238004 Mutation scripts (Steam forums)]
* [http://forums.steampowered.com/forums/showthread.php?t=1238004 Mutation scripts (Steam forums)] {{deadlink}}
* [http://modulatum.wordpress.com/2008/03/20/squirrel-binary-for-windows/ Squirrel Binary for Windows]
* [http://modulatum.wordpress.com/2008/03/20/squirrel-binary-for-windows/ Squirrel Binary for Windows]
* [http://en.wikipedia.org/wiki/Squirrel_(programming_language) Squirrel (programming language)] - Wikipedia Article on Squirrel
* [http://en.wikipedia.org/wiki/Squirrel_(programming_language) Squirrel (programming language)] - Wikipedia Article on Squirrel
* {{sq}}[http://squirrel-lang.org/ Squirrel: The Programming Language - Documentation and Sample Code]
* {{sq}}[http://squirrel-lang.org/ Squirrel: The Programming Language - Documentation and Sample Code]
* [http://www.valvesoftware.com/publications/2009/ai_systems_of_l4d_mike_booth.pdf The AI Systems of Left 4 Dead by Michael Booth (PDF)]
* [https://steamcdn-a.akamaihd.net/apps/valve/2009/ai_systems_of_l4d_mike_booth.pdf The AI Systems of Left 4 Dead by Michael Booth (PDF)]
* {{as}}[http://swarmarmory.com/forums/viewtopic.php?f=19&t=541 "Creating a "Money"/Point System"] - Swarm Armory
* {{as}}[http://swarmarmory.com/forums/viewtopic.php?f=19&t=541 "Creating a "Money"/Point System"] - Swarm Armory
;Deciphered Official Scripts:
;Deciphered Official Scripts:
*[http://www.multiupload.com/OXO3T2S1YA Version 2.0.1.8 and all mutations]
*[http://www.mediafire.com/?k280fhwjsp21sn8 Version 2.1.3.6 and all mutations]
*[http://ata4.info/downloads/left4dead2/scriptsrc.zip Version 2.0.8.4 (August 16, 2011)]
*[http://ata4.info/downloads/left4dead2/scriptsrc.zip Version 2.0.8.4 (August 16, 2011)]
<div style="text-align: right; direction: ltr; margin-left: 1em;">{{sq}}+{{l4d2}} = [[image:pnkhrt-16px.png]]</div>
<div style="text-align: right; direction: ltr; margin-left: 1em;">{{sq}}+ {{l4d2}} = [[File:PinkHeartCensor.png|16px]]</div>


[[Category:Left_4_Dead_2]]
[[Category:Left_4_Dead_2]]
[[Category:VScript]]
[[Category:Scripting]]
[[Category:Scripting]]

Latest revision as of 11:06, 21 April 2025

English (en)Translate (Translate)
edit
Left 4 Dead 2/Docs

Useful links

Overview

SquirrelLeft 4 Dead 2 Left 4 Dead 2 VScripts are server-side scripts that are run in an in-game virtual machine. They are written in Squirrel, a compiled scripting language similar to Lua. It currently runs Squirrel version 3.0.4.

Uses

Director Scripts

The most common use of VScripts in Left 4 Dead 2 is to temporarily influence the behavior of the AI Director. These scripts can range from simple adjustments of infected spawning and prohibiting boss infected, to custom events like onslaughts and gauntlets, and even complex staged panic events and fully custom finales. Most of the events in the official campaigns are mainly implemented this way.

Director Scripts work mainly by writing overriding values of the various variables used by the Director into a DirectorOptions table.

Only one Director Script can be running at a time. Executing a new one will terminate any previous running one and remove any values it set in DirectorOptions.

Entity Scripts ↓

Another common use is to attach a script to an entity. The script provides easy access to read and modify many of the entity's properties, and even to write new KeyValues. This allows for controlling entities in ways that would be very complicated or impossible to with the entity I/O system in Hammer.

Any entity is capable of running a script, and has the ability to set a specified think function to run every 0.1 seconds, as well as executing script code as an entity output.

Some entities also have specialized functions for VScripts, with the most prominent being point_script_use_target, which allows for turning other entities into fully programmable timed buttons.

Global Scripts ↓

Scripts can also be made to run on map load, based on game mode and optionally map name. These scripts are commonly used to create pure script addons and modify global Director options for mutations.

Global scripts can have script hook functions added that get called from the game at certain events, like when players/objects take damage.

There are many utility functions and features readily available for these scripts, including a resource and building system, and custom panic wave spawning. Please see Valve's Expanded Mutation System tutorial for more information.

Other Uses

All scripts can access functions for many features, including spawning entities either from precompiled lists or programmatically, spawning infected, a HUD system, storing data across levels and to disk, and much more.

Please see L4D2 Vscript Examples for more examples and ideas.

Script Files

The scripts are loaded from text files with the file extensions .nut and .nuc, where .nuc denotes encryption of plaintext .nut. Custom scripts are read from \left 4 dead 2\left4dead2\scripts\vscripts\, as well as \scripts\vscripts\ when packed into a .vpk file.

Location

Official .nuc script files are located in scripts/vscripts in multiple locations
Note.pngNote:Browse and extract VPK files with third-party programs like GCFScape.
  • left 4 dead 2\left4dead2\pak01_dir.vpk
  • left 4 dead 2\left4dead2_dlc1\pak01_dir.vpk
April 22, 2010 The Passing update
  • left 4 dead 2\left4dead2_dlc2\pak01_dir.vpk
October 5, 2010 The Sacrifice update
  • left 4 dead 2\left4dead2_dlc3\pak01_dir.vpk
March 22, 2011 Cold Stream Beta / L4D1 Transition Project update
  • left 4 dead 2\update\pak01_dir.vpk
This is where mutations were updated/replaced bi-weekly. Also contain files introduced with September 24, 2020 The Last Stand Community Update.
  • left 4 dead 2\sdk_content\scripting\scripts\vscripts\
Plaintext versions of many of the scripts introduced in the EMS update.

Decrypting NUC Files

.nuc files are ICE encrypted .nut files. The encryption key is SDhfi878. You can use VICE to decode them.
You may find decrypted mutation vscripts here.

Loading VScripts

VScripts are loaded in a variety of ways, depending on their context. They can also be manually loaded with the console command script_execute filename.

Director Scripts

BeginScript <scriptlistRedirectInput/string>
Executes generic Director scripts, whether for onslaught events or changing spawning behavior.
They are placed in the LocalScript script scope.
EndScript
Ends the currently running local script, then resets the Director options to either map-specific values, or default values.
ScriptedPanicEvent <scriptlistRedirectInput/string>
With the given scripts, set up the structure of a scripted panic event.
They are placed in the LocalScript script scope.
Note.pngNote:The scripts of these inputs must reside under the "vscripts" subfolder. Events will play out only the 1 second DELAY "stage 0" otherwise.
As a trigger_finale finale starts, it loads a script of this format: [mapname]_finale.nut.
They are placed in the g_MapScript script scope.

Entity Scripts

  • Keyvalue
Entity Scripts (vscripts) <scriptlist>
As an entity is preparing itself before it spawns, the VScript path names in that keyvalue will be ran. (See Entity Scripts for more info.)
  • Input
RunScriptFile <scriptRedirectInput/string>
Inserts the given script into the entity's scope, then runs it.

Entity Scripts are placed in the _<unique ID>_<entity name> script scope.

Global Scripts

  • Mode scripts
A script with the same name as the current game mode. Loaded when a new mode is set.
They are placed in the g_ModeScript script scope.
Tip.pngTip:The map command can also set gamemodes. For example, map <map name> mutation12 loads the Realism Versus mode script, mutation12.nuc.
Note.pngNote:Adding a script for a mode will enable Scripted Mode.
  • Map-specific mode scripts
Per-map scripts when the map is loaded in the specified game mode. They are in the name format: [mapname]_[modename].nut.
They are placed in the g_MapScript script scope.
  • Addon scripts
These scripts vary in context, but they all share one big attribute: they don't override files with the same name, but instead load alongside them. They are executed in the order below, each after its respective base script (without _addon suffix). A script is considered an "addon script" if it's named as:
  1. mapspawn_addon.nut (runs once every chapter) - getroottable() scope
  2. response_testbed_addon.nut (runs once every chapter) - g_rr scope
  3. scriptedmode_addon.nut (runs twice every round) - g_MapScript scope
  4. director_base_addon.nut (runs twice every round) - DirectorScript scope

Scripting Environment

Please see Left 4 Dead 2/Script Functions for built in classes and functions.

When a script is loaded, it is placed into a table, or Script Scope. Global and Director Scripts are put into set scopes, while a unique scope is generated for each Entity Script. Please see Vscript Fundamentals for more information.

Table Structure

DirectorScript = 			// Base Director Scope.
{
	DirectorOptions 		// Base DirectorOptions table.
	MapScript =  			// Script scope for either map scripts or trigger_finale scripts
	{
		DirectorOptions         
		BaseScriptedDOTable 	// Default DirectorOptions for Scripted mode
		ChallengeScript = 	// Script scope for mode scripts
		{
			DirectorOptions // Filled with BaseScriptedDOTable, MutationOptions and MapOptions; if identical keys are present then the most-right table gets precedence.
			MutationState 	// Filled with MapState overwriting previous values
			MutationOptions // Initial values used if defined in mode script 
		}
		LocalScript =		// Script scope for scripts executed through info_director 'BeginScript' or 'ScriptedPanicEvent' inputs
		{
			DirectorOptions // DirectorOptions for current Director Script (like onslaughts). Only available when a script is active
		}
		MapOptions 		// Initial values used if defined in map script 
		MapState 		// Initial values used if defined in map script 
	}
}
g_MapScript 	// Global reference to the Map Script scope (DirectorScript.MapScript).
g_ModeScript 	// Global reference to the Mode Script scope (DirectorScript.MapScript.ChallengeScript).
SessionOptions 	// Global reference to g_ModeScript.DirectorOptions (Scripted mode only).
SessionState  	// Global reference to g_ModeScript.MutationState (Scripted mode only).

g_rr		// Scope holding the Response Rule system.
g_RoundState	// TODO

Delegation

Some of the tables have delegation set up, so that if a key isn't present in it, it is read from its delegate (usually parent) table instead.

The tables are delegated like this (delegates on the right):

The Director Scope
(DirectorScript.MapScript.ChallengeScript or DirectorScript.MapScript.LocalScript) < DirectorScript.MapScript < DirectorScript < ::
DirectorOptions
DirectorScript.MapScript.ChallengeScript.DirectorOptions (Scripted mode only) < DirectorScript.MapScript.LocalScript.DirectorOptions (when Director Script active) < DirectorScript.MapScript.DirectorOptions < DirectorScript.DirectorOptions
See GetDirectorOptions in director_base.nut.

Entity Scripts

Use script scope _<unique ID>_<entity name>

Adding a script to the Entity Scripts KeyValue of a server-side entity loads the script as an Entity Script. The script is executed when the entity spawns, and loads into a unique script scope made up of an unique identifier followed by the entity name or class name.

A think function can be set with the thinkfunction KeyValue, the specified script function every 0.1 seconds. While it has the potential to become expensive, a programmer is able to limit the amount of code executed. Functions can also be manually called through the I/O system with the input RunScriptCode function_name(argument, …).

Entity Scripts have a self reference to their owning entity handle, allowing the script easy access to control the entity through its class methods. There are also hook functions available depending on the entity class. Both methods and hooks are documented here.

Some entities have additional script functionality:

The script can be reloaded with console command ent_fire <name of entity> runscriptfile <relative vscript path>. This is useful for quick script reloading.

I/O system Interaction

Any script can use the EntFire() and DoEntFire() functions to fire outputs to map entities. Since the activator and caller arguments in DoEntFire() take a script handle, it can be used to fire an output to an entity using the !self or !activator keyword, even without having to know its name, as long as the entity handle is available.

EntFire( "church_bell_relay", "Trigger", 0 ); // Fires an output to the Trigger input of the named entity.

player <- null;
while(player = Entities.FindByClassname(player, "player"))   // Iterate through the script handles of the players.
{
    DoEntFire("!self", "speakresponseconcept", "PlayerLaugh", 0, null, player); // Make each player laugh.
}

Conversely, the CBaseEntity::ConnectOutput() and DisconnectOutput() functions can be used to call a script function when the specified entity output fires. In addition, arbitrary VScript code can be run from the I/O system, using the RunScriptCode input available in all entities. The code will run in the current entities script scope.

Warning.pngWarning:Never use double-quotation marks in any Hammer Output, since it will corrupt the map file. This means that strings cannot be passed with RunScriptCode.

Global Scripts

Naming a script file with a game mode name makes it a mode specific script which executes every time a map is loaded in the specified mode. If a Mode Script exists, a map specific script with the map name followed by an underscore and the mode name can also be loaded.

Mode Scripts

Use script scope g_ModeScript

Tables

MutationState
Initial values for the SessionState table.
MutationOptions
Initial values for the SessionOptions table.

Map Scripts

Use script scope g_MapScript

Tables

MapState
Map specific values for the SessionState table.
MapOptions
Map specific values for the SessionOptions table.

Scripted Mode

Adding a Mode Script will enable Scripted Mode for the game mode. This works on the base game modes included in the game as well.

Scripted Mode loads utility functions into the g_MapScript scope, disables the hardcoded setting of 2 on the MaxSpecials Director option, and enables game event callbacks and script hook functions. It also seems to break the finale tank music in Dark Carnival.

Todo: Does enabling Scripted Mode have any other consequences?

Available Functions

Todo: Document the available utility features.

Shared Tables

SessionState
A table for storing session specific variables. Not preserved across level transitions.
SessionOptions
Active Director Options for the game mode.

Glossary

DirectorOptions
A table of named variables that override the AI Director behavior.
Entity handle
Also known as EHANDLE.
Todo: Looks like some sort of pointer reference to an entity.
Script handle
An entity instance with accessors and mutators to the C++ entity object. Also known as HScript.
Script scope
The table where the variables, functions and classes of a VScript are placed.

Director Options

Please see L4D2 Director Scripts for a table of available options.

Third-Party Tools

VSLib

VSLib (VScript Library) is a simple, lightweight library for L4D2's VScript mutation system. It greatly simplifies coding VScripts by taking care of a lot of tedious work for you. It is used in several popular mods like Rayman1103's Admin System and Stranded. Read more about VSLib.

See also

Intros

Documentations

Miscelleanous

External links

Alternative Tool
Alternative Documentation
Deciphered Official Scripts
Squirrel+ Left 4 Dead 2 = PinkHeartCensor.png