Fundamental Scripting Guide: Difference between revisions

From The DarkMod Wiki
Jump to navigationJump to search
Dragofer (talk | contribs)
Dragofer (talk | contribs)
No edit summary
Line 361: Line 361:
  sys.println(activator.getName() + "has activated the trigger brush.");
  sys.println(activator.getName() + "has activated the trigger brush.");
  }
  }
Potential pitfall: stationary AIs will not activate trigger_multiple brushes.
=== Path nodes ===
Many [[Path Nodes]] trigger all of their non-path-node targets whenever an AI reaches them. This can be combined with target_callscriptfunction entities to call a script.




Line 396: Line 403:


=== Objective system ===
=== Objective system ===
The [[Objectives Editor]] can be seen as a visual scripting editor. In that sense it synergises well with scripting.
The main way to use the objective system for scripting is by specifying completion scripts and failure scripts when editing an individual objective. These scripts will get called if the objective is completed or failed. Note that if the objective is reversible, it might call the scripts multiple times.
The objectives system allows you to do some things much more easily than with regular scripting, such as calling a script when reaching a certain page in a book (i.e. playing an ominous sound). Many maps therefore have hidden objectives, or a mix of hidden objectives and scripts, in order to achieve interesting scripted effects.
=== Location system ===  
=== Location system ===  
The location system (wiki page: [[Location Settings]] allows you to call scripts whenever the player enters or leaves specific locations.
It works by setting spawnargs on the info_location entity, referencing a script's name:
"call_on_entry"
"call_on_exit"
"call_once_on_entry"
"call_once_on_exit"
On the scripting side of things, your script must specify the location where it's called in its input brackets. Note that this is without a $ sign. Example:
void enter_location_streets(entity info_location_streets) //for an info_location entity with the name "info_location_streets"
To my knowledge, this way of setting up means a script can only be called from one location. If you have multiple locations, you will need multiple scripts even if they do the same thing.




Line 721: Line 747:
  thread move_mover($box2, 3, '-50 0 0');
  thread move_mover($box2, 3, '-50 0 0');
  }
  }
== Special methods ==
This section is devoted to useful practical applications of various scripting principles and for special cases.
=== Going through all entities of a certain type ===
The getNextEntity() function allows you to find every entity in the map that has a certain spawnarg. It finds one entity at a time, so you'll need to run it many times. Each time it runs you'll have an opportunity to run script events on the entity that was found.
As shown in "Looping/Repeating scripts", do + while() are well suited for this application:
//Example script by Obsttorte
void lamps_toggle() //finds and triggers all electric lamps in the map. They're identified based on the value of the "lightType" spawnarg
{
light lamp;
do //do repeat this...
{
lamp = sys.getNextEntity("lightType","AIUSE_LIGHTTYPE_ELECTRIC",lamp); //find the next entity with this spawnarg; continue the search from the previously discovered lamp entity
if (lamp != $null_entity) sys.trigger(lamp);
} while (lamp != $null_entity); //repeat for as long as sys.getNextEntity finds electric lights
}
=== Going through all targets of an entity ===
numTargets() returns the number of targets that an entity has. This can be combined with "for" to run script events once on every target:
void hide_targets() //finds all targets of an entity and runs a script event on them (in this case: hide)
{
for(i = 0; i < $func_static_267.numTargets(); i++) //identifies info_player_teleport entity and partner door
{
m_target = getTarget(i);
}
}
=== Going through all entities bound to an entity ===





Revision as of 16:59, 15 December 2020

Primary contributor - Dragofer

This is a (work in progress) resource written primarily for mappers with no background in scripting or coding, such as myself, though others too may find practical guidance for working with TDM's scripting system. This is what I've picked up over the years through experimentation, looking at existing scripts and interacting with other forum members.

My aim is for the article to be both comprehensive and down to earth, using many examples and avoiding unnecessary technical terms. There will be some overlap with existing wiki articles, since this aims to have everything in one place out of one hand.

The concept will be to start with teaching some basic script literacy, then introduce scripting principles one after another. Towards the end, practical examples show ways of tying everything together to get more complex scripted effects.


Anatomy of a script

This section will define essential terms, then look at some basic scripts of slightly increasing complexity to demonstrate what a script is made up of.

Basic terms

Script events Script events are an action of some kind, i.e. waiting x seconds or triggering an entity. They are the basic building blocks of scripting.
Script function This is the technically correct term for a "script". Script functions often contain multiple script events, and some can also be used like script events in other script functions. Usually this guide will refer to them simply as "scripts".
Scriptobject This is a powerful set of scripts that are applied to single entities. This allows you to write code once, but let it apply to an unlimited number of entities without conflicts. An example is the tdm_light_holder scriptobject, which controls the skin, particle, lit state etc. of its candle.
Variables Variables are another basic building block and allow a script to store data for further processing and to have variable effects. Each variable must be named and given a data type.
Data types Every variable and every input/output of a script event needs to have a data type to inform the engine whether it should be read as a text, number, vector etc.

Script events

Example script event: wait()

This is a very basic script event which instructs the script to wait for 3s:

sys.wait(3);

Here's a closer look at its components:

  • sys.
    • Every script event must be called on an entity. For very generic events like "wait", sys is typically used, shorthand for system.
  • wait(3)
    • This is the actual script event. Every script event must be accompanied by input brackets, even if they're left empty. In this case, "3" is the input.
  • ;
    • A semicolon is needed to mark the end of a line of instructions. Forgetting these is a common mistake that stops the map from loading.


Example script event: setOrigin()

This is another simple script event. It's called on player1 and teleports (sets the origin of) him to the position '0 150 0'.

$player1.setOrigin('0 150 0');
  • $player1
    • Notice the $ sign: this means the script engine should look for a specific entity in the game with that name. The player is always called "player1".


Scripts

Example script: rudimentary script for sending a message to the console

Script events can't work on their own, they need to be part of a script:

void test_script()
{
	sys.println(“Test message.”);
}
  • void
    • This defines what type of result the script puts out to other scripts: "void" means nothing while i.e. "float" would mean a number. In the large majority of cases you'd use void.
  • test_script()
    • This is the name of the script: "test_script".
    • Like with script events, input brackets are mandatory for scripts, even if the script doesn't use them. For a script that should damage various entities by various amounts, you could define an entity input and a float (number) input.
    • Note that no semicolon is needed at the end of this top line.
  • {}
    • Curly brackets mark the beginning and end of the body of the script.
  • sys.println("Test message");
    • This is a script event which prints a text to the console and then leaves a line (ln), so that every text is on its own line.


Example script: simple cutscene
void simple_cutscene()
{
	sys.fadeOut('0 0 0', 2);		//fade to black (colour vector '0 0 0') in 2s
	sys.wait(2);				//wait 2s for the fadeOut
	sys.trigger($speaker_narrator);	        //trigger a speaker with a narrator's voice
	$camera.activate($player1);		//activate a camera to disable player controls

	sys.wait(10);				//wait narrator is speaking
	sys.fadeIn('0 0 0', 2);			//fade back in from a black screen in 2s
	$camera.activate($player1);		//return player controls
}

This scripts a basic cutscene: fade to black, activate a speaker, fade back in. At both ends a camera is toggled so that the player can't move while the screen is black.

  • //
    • This is a comment for the reader: anything behind a double slash gets ignored. This is a useful habit for helping others and your future self understand how your script works.
    • An alternative way to comment, useful for mutli-line comments or temporarily disabling a section of the script, is to use /* at the beginning and */ at the end. This way you don't need to mark every single line as a comment.
  • sys.fadeOut('0 0 0', 2);
    • This script event uses 2 different inputs:
      • '0 0 0' is a vector defining the colour to which the screen should fade. Every number represents the intensity of red, green or blue colour.
      • 2 is a float (number) defining how long the fadeout should take.
  • sys.trigger($speaker_narrator);
    • This is a script event to trigger a specific entity called "speaker_narrator", which would simply be a speaker in the map with a custom soundshader.
  • $camera.activate($player1);
    • This is an alternative way to trigger, aka activate, an entity. This is needed when you want one entity to be triggered by another entity, instead of "sys". In this case, player1 is the activator who activates the camera. Another example would be the player activating a teleporter entity.


More scripting basics

General

  • Scripting is case-sensitive.
  • The scripting engine reads from top to bottom. That makes the order in which scripts and variables are arranged quite important.
  • The $ sign instructs the engine to look for an entity ingame with that name. If there's no $ sign, the engine will instead look for a variable with that name in the scripts.


Data types

Data type refers to whether something is to be treated as a text (string), number (float), vector etc. You will always want to be aware of this, since i.e. a script event designed to apply a force vector won't work if you give it a string instead of a vector.


String A string of letters/numbers, in other words plain text. It must always have double quotation marks. Example: “Text message 123”
Float A float is a single number, decimals are allowed. Example: 15.2
Vector A vector consists of 3 numbers, often used for 3D movements (x z y) or colours (red green blue). It must always have single quotation marks. Example: '0 90 0'
Boolean Can be true or false. Easily replaced by floats (0 or 1). Example: TRUE
Void No type. Most commonly used for scripts or script events that have no direct output.
Entity Indicates an entity, usually using the name as seen in DR. If it's a specific entity, instead of a variable, then a $ sign is required. Example: $player1
Subcategories of “entity” These are required for some script functions to work, such as ai, light or tdm_elevator. For example, you can check whether an “ai” is alerted or knocked out, which isn't possible with regular entity script functions.


Variables

Variables are a key principle in scripting. They allow the same script to have different results depending on the input, rather than always doing the exact same thing. Another use is for storing data, allowing it to be used by other script events or scripts.


Creating new variables

The first time the engine finds a variable in a script it needs to be given a data type. Afterwards you use just the name. Example:

float attempts;

sys.println("Player has " + attempts + " left.");

You may also want to assign an initial value. Otherwise, floats will default to 0, strings to "", vectors to '0 0 0' and entities to $null_entity. Example:

float attempts = 3;

Another option is to define a variable using the output of a script event. Examples:

vector starting_origin = $func_static_267.getOrigin();
float can_see = $guard_westwing_1.canSee($player1);
float sound_duration = $entity1.startSound("snd_move", SND_CHANNEL_ANY, false);  //stores the sound duration of the sound being played

Where a variable is defined is important. If it's inside a script, the variable will only be useable inside that script. If it's defined outside of a script, all later scripts will be able to use it.


Vector variables

It's possible to access individual numbers from a vector by appending _x, _z or _y to the end of the vector variable's name. These will get treated as floats.

Example: teleporting the player up by 16 units from wherever he is now

void teleport_player_up()
{
	vector player_position	= $player1.getOrigin();		//where is the player now? Store as a variable named "player_position"
	player_position_z	= player_position_z + 16;	//increase the z-component (height) of "player_position" by 16

	$player1.setOrigin(player_position);			//set the new origin of the player to the modified "player_position"
}


Another option is to get the magnitude of a vector, turning it into a float. This is useful for example in getting a percentage when checking the progress of a movement.

Example: checking the progress of a func_mover

void check_progress()
{
	vector start_position 	= '0 0 0';
	vector target_position	= '200 0 0';
	vector current_position	= $func_mover_1.getOrigin();

	float distance_moved 	= sys.vecLength(current_position - start_position);			//how far the mover has moved in units
	float percent_progress	= distance_moved / sys.vecLength(target_position - start_position);	//how far the mover has moved in percent
}


Example usage of variables: puzzle with max 3 attempts

Say you wanted to give a player 3 attempts to solve an optional puzzle, with a chance to reset his number of attempts:

float attempts;				//how many attempts the player has made. Defined outside of a script so both scripts can access it.
float attempts_left = 3;			//how many attempts the player has left, max 3

void attempt_failed()				//called every time the player fails an attempt
{
	attempts	= attempts + 1;		//increase attempts counter by 1
	attempts_left	= 3 – attempts;		//calculate how many attempts left

	if (attempts_left == 0) $puzzle.setFrobable(0);	//if no more attempts, make the puzzle entity unfrobable
}

void reset_attempts()				//calling this resets the player's attempts to 0
{
	attempts = 0;
	attempts_left = 3 – attempts;

	$puzzle.setFrobable(1);			//make sure the puzzle entity is frobable
}
  • The default value for new floats is 0, therefore "float attempts;" is the same as "float attempts = 0;"
  • There is some redundancy in this setup, i.e. it's not necessary to give attempts_left a value of 3 at the beginning because this gets calculated in the 2 scripts. But in my opinion it makes the script easier to follow, and it's good to make sure your variables are always up to date in case you later add another script that should work with them.



Using the TDM Script Reference

The TDM Script Reference is an essential wiki resource for scripting, listing all available script events for the current version of TDM. All script events are listed twice: the first time they're sorted alphabetically, the second time they're sorted based on which kinds of entities they can be called on. By far not all script events have received manual descriptions, so sometimes you may need to experiment with them to properly figure them out.

Here is an example:

scriptEvent float canSee(entity ent);

    no description

    Spawnclasses responding to this event: idAI

Interpretation:

  • the script event canSee() is suitable for being called on AIs.
  • an entity must be entered into its input bracket.
  • the script event returns a float. This means you could for example store the result of this check in a float variable and use that elsewhere in your scripting.


Actually using the script event may take some experimentation, mainly to see which entity the event should be called on and which entity should go into the brackets. In the end it could look something like this:

$guard_westwing_1.canSee($player1);


Alternatively, if you want to store the result as a variable (that we name "guard_sees_player") for later use:

float guard_sees_player = $guard_westwing_1.canSee($player1);


Setting up the .script files

Map scripts

The easiest way to setup scripts is as a map script: create a new .txt file in your maps folder with the same name as your map and change the .txt extension to .script. Any scripts in this file will only be available in that map.

If you're setting up a .script file for the first time, double click the file and set Notepad or Wordpad as the standard program for opening .script files.

The next step is to add a main() script at the very bottom of your map script:

void main()
{
	sys.waitFrame();
}

The main() script is automatically called at map start. This makes it convenient for testing scripts and initialising scripts that should run from the beginning of the mission.

It's good practice to let the main() script begin with sys.waitFrame();. This is because all entities are spawned in the first frame of the mission, so waiting a single frame makes sure they're ready for script events.


General scripts

It's possible to let your scripts be available in all missions. This requires an additional step and has the downside that you have to restart TDM (rather than just the map) before changes take effect. Therefore it's recommended to develop & test your script as a map script first.

The .script file can have any name and must be placed within a new "script" folder (without an s) instead of the "maps" folder.

You will need to tell the game to include that .script file. To do this, create a new file called tdm_custom_scripts.txt, change the extension to .script and type in the following to include a .script file called "my_custom_script":

#include script/my_custom_script.script

Any mistakes stop TDM from starting up with a blue screen. You will need to press "copy" and paste the error message somewhere like Notepad or Word to read it.


Scriptobjects

Scriptobjects are entity-specific sets of scripts. They should be defined in general scripts, since having scriptobjects in map scripts breaks saving/loading. However, it's recommended to develop scriptobjects in map scripts since you don't need to restart TDM to make the changes take effect. Scriptobjects will be discussed in more detail elsewhere.


Ways of calling a script

TDM has many methods for calling scripts. Often you can combine systems such as the objective systems with scripting in order to get powerful results that wouldn't easily be possible otherwise.

From other scripts

To call one script from another script, use the thread event. You can only call scripts that are higher up in the script or in the #inclusion chain of .script files (unless you're writing a scriptobject). If the script should start at the beginning of the map, you could use void main() since it gets called automatically.

Example:

void script1()			//prints a line to the console
{
	sys.println("Running script1");
}

void main()			//automatically runs script1 at the start of the map
{
	sys.waitFrame();	//give all entities enough time to spawn
	thread script1();	//run script1
}


If the script you're calling needs input parameters, don't forget to include them. See section "Scripts with input variables" for more.

Example:

void move_any_mover(entity func_mover, vector move_vector)	//this script expects 2 parameters: an entity and a vector
{
	vector current_position = func_mover.getOrigin();	//get current position
	func_mover.time(2);					//movement will take 2s
	func_mover.moveToPos(current_position + move_vector);	//make mover move to new position
}

void call_movement()						//this script calls move_any_mover() and passes it the required parameters
{
	thread move_any_mover($box1, '100 0 0'); 		//the parameters are the name of a func_mover entity to be moved and a vector for the movement
}


target_callscriptfunction

You can create an entity in DR called target_callscriptfunction and give it the spawnarg "call" with the name of the script without brackets. Whenever this entity is triggered, i.e. by a button or if an AI reaches a path_node that targets this, the script will be called. As far as I'm aware, it's not possible to pass any parameters this way.

Example:

The script in the .script file:

void script1()
{
...
}

The spawnarg on the target_callscriptfunction:

"call" "script1" 


Trigger brushes

Trigger brushes are a common way to call scripts, activated when the player or an AI enters the volume of the brush. Like with target_callscriptfunction entities, they need a "call" spawnarg naming the script to be called. See Triggers for details on how to create one.

If you want your script to know which entity has activated the trigger brush, you can give your script an entity as an input parameter.

Example:

void script1(entity activator)
{
	sys.println(activator.getName() + "has activated the trigger brush.");
}

Potential pitfall: stationary AIs will not activate trigger_multiple brushes.


Path nodes

Many Path Nodes trigger all of their non-path-node targets whenever an AI reaches them. This can be combined with target_callscriptfunction entities to call a script.


Stim/Response

The Stim/Response system is very powerful, in particular when combined with scripting.

In most cases, you'll likely be interested in only the "Response" tab of the S/R editor interface. This allows you to make an entity respond to certain stimuli, such as a frob, a trigger or water (left side of the window) by executing various effects (right side of the window). Many different effects are available from the dropdown list.


One common use is to make an entity frobable and give it a "Response" to frobbing which runs a script. To do so, set the spawnarg "frobable" "1" on the entity to make it frobable. Then open the S/R editor, go to the Response tab, in the left half of the window select "Frob", in the right half of the window right-click and add an effect to "Run script", naming the script you want to run.

To make this single-use you could add another effect to either:

  • disable frobability of this entity
  • or deactivate the response to frobbing (the ID of the frob stim is 0).


Action scripts

Entities can be given spawnargs that make them run scripts when certain actions are performed on them, such as frobbing or using. The value of the spawnarg must be the name of the script to be run. Example: "frob_action_script" "script1".

Like with trigger brushes (see earlier), these entities pass their own name to the script function. This allows you to reuse the same spawnarg & script on many entities.

frob_action_script Calls the specified script when the entity is frobbed by the player.
use_action_script Calls the specified script when the player uses an inventory item on the entity (i.e. use a key on a door). The inventory item must be specified in a "used_by" spawnarg on the entity. More info here: Tool, Key, custom used by inventory actions
equip_action_script Calls the specified script when the player is holding the entity and uses it (i.e. eating an apple).



Objective system

The Objectives Editor can be seen as a visual scripting editor. In that sense it synergises well with scripting.

The main way to use the objective system for scripting is by specifying completion scripts and failure scripts when editing an individual objective. These scripts will get called if the objective is completed or failed. Note that if the objective is reversible, it might call the scripts multiple times.

The objectives system allows you to do some things much more easily than with regular scripting, such as calling a script when reaching a certain page in a book (i.e. playing an ominous sound). Many maps therefore have hidden objectives, or a mix of hidden objectives and scripts, in order to achieve interesting scripted effects.


Location system

The location system (wiki page: Location Settings allows you to call scripts whenever the player enters or leaves specific locations.

It works by setting spawnargs on the info_location entity, referencing a script's name:

"call_on_entry"
"call_on_exit"
"call_once_on_entry"
"call_once_on_exit"

On the scripting side of things, your script must specify the location where it's called in its input brackets. Note that this is without a $ sign. Example:

void enter_location_streets(entity info_location_streets)		//for an info_location entity with the name "info_location_streets"

To my knowledge, this way of setting up means a script can only be called from one location. If you have multiple locations, you will need multiple scripts even if they do the same thing.


Making scripts read the map with "get" events

Your scripts unlock much potential if they can see and react to what's happening in the map. The way to get up-to-date information about the state of the entities is with "get" script events. There are a lot of them, and as said they have a ton of potential.


Often you'll store their results as a variable, like this:

	float health_current = $lord_marlow.getHealth();	//Lord Marlow's current health

Or use them directly in a conditional:

	if ($lord_marlow.getHealth() < 100)			//If Lord Marlow has been hurt...


Getting spawnargs

Spawnargs are a special case. All spawnargs are strings, so if you want to store them as a variable you need a "get" event which converts them into the matching data type:

string name		= $mover.getKey("name");		//for strings
float move_time		= $mover.getFloatKey("move_time");	//for floats
vector rotate		= $mover.getVectorKey("rotate");	//for vectors
boolean open		= $mover.getBoolKey("open");		//for booleans
entity frob_master	= $mover.getEntityKey("frob_master");	//for entities


Example useage: checking the current health of an AI for an objective

This script is for an objective to let no harm come to an AI. It would check the AI's "health" spawnarg to find what his max health is and check the AI's current health. Then it compares the two: if there's a difference, the objective fails.

void check_health()
{
	float health_max	= $lord_marlow.getFloatKey("health"); 	//get spawnarg for max health
	float health_current	= $lord_marlow.getHealth();		//get current health

	if(health_current != health_max) $player1.setObjectiveState(5, OBJ_FAILED);

	sys.wait(0.5);			//wait 0.5s...
	thread check_health();		//... before repeating this script
}


Conditionals

Conditionals check whether conditions have been met before carrying out the associated set of instructions. They're an important tool for making dynamic scripts that react to events in the map.


If there's only a single line of instructions to carry out, then it can be on the same line as the conditional check itself:

if($player1.getHealth == 100) sys.println("player1 has full health");


If you have a set of instructions, use curly brackets. Note that the line with the conditional needs no semicolon:

if($player1.getHealth != 100)
{
	sys.println("player1 doesn't have full health");
	$player1.setHealth(100);
	sys.println("player1 has been restored to full health");
}


Conditionals for comparisons

==, != equal, not equal
<, > less than, greater than
>=, <= less or equal to, greater or equal to


Example:

if (attempts < max_attempts)


An easy mistake is to use only a single equals sign in a conditional.

= means "set to this value"

== means "equal to this value"

Example:

attempts = 3;		//means: set "attempts" to 3
if (attempts == 3)	//means: check if "attempts" is equal to 3


Conditionals for checking if something is true

Booleans and floats are best suited for this kind of check. In the case of a float, 0 is considered false, while any positive value is considered true.

Example:

if ($lord_marlow.getFloatKey("can_unlock"))	//check whether an AI can unlock doors


If you want to check whether something is false, you need an exclamation mark within the brackets.

Example:

if (!$lord_marlow.canSee($player1))		//if the AI CAN'T see the player, do... 


Multiple conditionals

Sometimes you want to check multiple conditionals, i.e. if A and B are true but C is false. Important symbols here are:


&& and

|| or


Example useage: secret conversation occurring under specific circumstances

if ( ( ( $lord_marlow.getLocation() == $mansion_bedchamber ) || ( $lord_marlow.getLocation() == $mansion_secretchamber ) ) && ( !$lord_marlow.canSee($player1) )
{
	$lord_marlow.bark("snd_secretconversation");	//say a secret phrase
}

In other words: if Lord Marlow is either in his bed chamber or his secret chamber, and he can't see the player, make him say a secret line.

Getting the right number of brackets in the right place can be tricky. It can be helpful to write each conditional on its own line first, then combine them one by one into a single line.


Chains of conditionals

Other than "if", there are also "else" and "elseif". These only get considered if the preceding "if" has failed.

"Else" will always get carried out, while "elseif" checks whether its conditions are met.


Example useage: script for a lever with 3 positions and an inactive state

void lever()
{
	if ( lever_position == "inactive" ) return;		//if lever is inactive, stop processing this script

	if 	( lever_position == 1 )	sys.trigger($door1);	//check for lever position 1
	elseif	( lever_position == 2 )	sys.trigger($door2);	//otherwise check for lever position 2
	elseif	( lever_position == 3 )
sys.trigger($door3);	//otherwise check for lever_position 3
}

Looping / repeating scripts

You may want a script to keep repeating until stopped, for as long as a condition stays true, or repeat for a number of times.

With some exceptions there should always be a wait built into the script, otherwise the script will attempt to repeat an infinite number of times in one go and crash.


Looping with thread

The easiest way to loop is by making the script call itself at the end with "thread".

Example:

void looping_script()
{
	if ( $lord_marlow.getHealth() != 100 ) $player1.setObjectiveState(5, OBJ_FAILED);

	sys.wait(0.5);
	thread looping_script();
}


Looping with while()

while() lets you loop a script for as long as the condition inside the brackets is true. If it should loop permanently, put a 1 into the brackets (true).

Example useage: continually checking an AI's health for a "Don't harm" objective

while(1)
{
	if ( $lord_marlow.getHealth() != 100 ) $player1.setObjectiveState(5, OBJ_FAILED);
	sys.wait(0.5);
}

Example useage: timer for how long a box has been moving

while( $box.isMoving() )
{
	sys.wait(0.5);
	float time_moved = time_moved + 0.5;
}


Repeating with for()

for() lets a script repeat for a number of times that can be either pre-determined or variable. It's well-suited for gradually making a change in many small steps (increments).


Example useage: gradually changing a shader parameter on an entity

void materialise()
{
    float i;					//define a float (integer) to keep track of the number of steps
    for (i=0;i<100;i++)			//go from 0 to (one under) 100, one at a time
    {
        fade_entity.setShaderParm(5,i);	//set shaderParm5 to the current number of steps
        sys.waitFrame();			//wait one frame until the next step
    }
}


Repeating with do + while()

"Do this script for as long as this condition is met". This one is quite similar to just using while, the difference is it can start even if the condition is false at first. It also doesn't need to include a wait if you know the condition will only hold true a finite number of times.

Example usage: running a script on every entity of a certain type

//Script by Obsttorte
void lamps_toggle()				//finds and triggers all electric lamps in the map
{
	light lamp;
	do					//do repeat this...
	{
		lamp = sys.getNextEntity("lightType","AIUSE_LIGHTTYPE_ELECTRIC",lamp);
		if (lamp != $null_entity) sys.trigger(lamp);
	}	while (lamp != $null_entity);		//repeat for as long as sys.getNextEntity finds electric lights
}


Terminating a running script

Terminating with killthread()

It's possible to manually terminate any script by giving it a (thread) name, and letting another script terminate it.

Example:

void check_health()
{
	sys.threadname("looping_script");		//assign a name to this script or thread

	if ( $lord_marlow.getHealth() != 100 ) $player1.setObjectiveState(5, OBJ_FAILED);
	sys.wait(0.5);
}

void terminate_check_health()
{
	sys.killthread("looping_script");	//terminate the script that was named "looping_script"
}

Terminating with return

Alternatively you can terminate a script with "return". This causes the script to terminate and return a value, if it has one. Example:

if ( attempts == 3 ) return;


Giving scripts input variables

A good way to avoid script duplication is to make use of input variables, allowing you to write a single longer script and pass it instructions from elsewhere, such as smaller scripts.

Input variables are defined in the round brackets next to the name of the script. They can then be used in the script itself:


Example: this script can be used to apply to any ai ("guard") a variable amount of damage ("damage_amount"):

void damage_guard(ai guard, float damage_amount)
{
	float health_current	= guard.getHealth();
	float health_new	= health_current – damage_amount; 

	guard.setHealth(health_new);
}


Other, shorter scripts can call the above script and give it input parameters to tell it which AI should be affected and how much damage:

void hurt_guard1_severe()
{
	thread damage_guard($guard1, 50);		//reduce guard1's health by 50
}

void hurt_guard2_light()
{
	thread damage_guard($guard2, 20);		//reduce guard2's health by 20
}


Example useage: room with multiple func_movers and buttons, movement in various directions

This is the main script that does the heavy lifting in doing the movements. It's setup to be used on various entities (named "box") with variable "move_time" and "move_vector".

void move_mover(entity box, float move_time, vector move_vector)
{

/*
Main script that performs the movements.
Gets called by and receives input parameters from move_forward() or move_backward().
Checks if the box is stationary.
If box is stationary, calculates new target position, sets time taken to move and then initiates.
*/

	if(!box.isMoving())		//check if box has stopped moving
	{
		//define new target position based on current position + input move_vector
		vector target_position	= box.getOrigin() + move_vector;

		box.time(move_time);		//set time taken to move
		box.moveToPos(target_position);	//initiate movement
	}

}

These are the smaller scripts that pass instructions to the main script. Each one is called from a separate button in the map.

void move_forward_box1()		//called by button1 in the map
{
	thread move_mover($box1, 2, '50 0 0');
}

void move_backward_box1()		//called by button2 in the map
{
	thread move_mover($box1, 3, '-50 0 0');
}

void move_forward_box2()		//called by button3 in the map
{
	thread move_mover($box2, 2, '50 0 0');
}

void move_backward_box2()		//called by button4 in the map
{
	thread move_mover($box2, 3, '-50 0 0');
}


Special methods

This section is devoted to useful practical applications of various scripting principles and for special cases.

Going through all entities of a certain type

The getNextEntity() function allows you to find every entity in the map that has a certain spawnarg. It finds one entity at a time, so you'll need to run it many times. Each time it runs you'll have an opportunity to run script events on the entity that was found.

As shown in "Looping/Repeating scripts", do + while() are well suited for this application:

//Example script by Obsttorte
void lamps_toggle()				//finds and triggers all electric lamps in the map. They're identified based on the value of the "lightType" spawnarg
{
	light lamp;
	do					//do repeat this...
	{
		lamp = sys.getNextEntity("lightType","AIUSE_LIGHTTYPE_ELECTRIC",lamp);	//find the next entity with this spawnarg; continue the search from the previously discovered lamp entity
		if (lamp != $null_entity) sys.trigger(lamp);
	}	while (lamp != $null_entity);		//repeat for as long as sys.getNextEntity finds electric lights
}


Going through all targets of an entity

numTargets() returns the number of targets that an entity has. This can be combined with "for" to run script events once on every target:

void hide_targets()						//finds all targets of an entity and runs a script event on them (in this case: hide)
{
	for(i = 0; i < $func_static_267.numTargets(); i++)	//identifies info_player_teleport entity and partner door 
		{
			m_target = getTarget(i);
		}
}


Going through all entities bound to an entity

Troubleshooting

Debugging your script

If your script doesn't do what you expect it to, it can be helpful to add sys.println() at various stages in your script to print information about what's happened so far. This helps you narrow down where the problem lies.

For one, you can check whether a certain part of the script is actually running. Example:

void check_progress()		//checks whether the player has completed an objective. If yes, starts the patrol of a previously inactive AI.
{
	sys.println("Script check_progress has been called.");

	if($player1.getObjectiveState(5) == OBJ_COMPLETE)
	{
		sys.println("Player has completed objective 5");
		sys.trigger($ai_thief_1);				//start patrol of an AI that was previously sitting at a table
	}
}


You can also print variables to the console, allowing you to see if they have the values you expect at that stage of the script. Example:

void move_mover()		//moves a harmful mover towards the player as part of a trap
{
	entity func_mover	= $func_mover_1;
	vector starting_origin	= func_mover.getOrigin();
	vector target_origin	= $player1.getOrigin();

	sys.println(func_mover + " will move from " + starting_origin + " to " + target_origin);

	func_mover.time(1);
	func_mover.moveToPos(target_origin);

	sys.waitFor(func_mover);
	sys.println(func_mover + " has arrived at + " target_origin);
}


Common errors

  • Problem: after loading the map, the screen shows only a close-up of a random texture, can't move or use the inventory
    • This happens if you just started TDM but an error prevented you from loading the map the first time, you fixed the error and tried to reload your map again.
    • Fix: load into another map or restart TDM, then try to load the map again. The fastest way is to try to load a map that hasn't been dmapped yet, since that'll abort within seconds.