Introduction

T4Mod scripting

In addition to the commands explained in this reference, T4Mod provides most of the lua standard commands, these are:
assert, error, ipairs, module, next, pairs, print, require, select, tonumber, tostring, type, unpack

The supported lua standard libraries are:

* the package library in T4Mod mimics part of the original package behaviour, but does not allow for loading of system libraries or random file access.

The standard commands and libraries are not explained in this reference. Please refer to the standard lua documentation on how to use them.

Note:T4Mod is currently still under development. So it is likely that things may change and you scripts may or may not run on future versions.


Script operation

T4Mod scripts run per level. When a new level is loaded either by starting a new game or by a level jump, a script file with the same basename is loaded and executed right before the level starts. The general procedure is:

  1. Level mylevel.tr4 is loaded
  2. Script mylevel.lua is loaded and executed
  3. mylevel.tr4 is started and runs script callbacks as defined

Usually you would want to define all your functions and event callbacks and do the desired initialisations in the script.

While the game is running, whenever a callback event occurs, the callback function is called. When the function returns, the game loop continues (this means, that you must not i.e. loop inside a callback function and wait for something to happen).

For repeating actions timers can be used to periodically execute script functions.

With timers and coroutines you can also create independently running threads: This is a powerful feature and allows for complex scripting sequences, custom enemies and more.


Items and object types

An item is an instance of an item type (a moveable in a certain slot), i.e. you can have a couple of skeletons (each skeleton is an item), and while all skeleton items are instances of the same "moveable" type, each skeleton item can be at a different location and have a different current animation running, or can be in a different state (i.e. one is attacking lara, while another skeleton is wandering around elsewhere)

(The same will apply to statics and their types once they are implemented)


Positions and Rooms

In the TR4-engine, an item's location is determined by four values: x,y and z coordinates and a room number.

The coordinate axes are oriented so that:

(For item's local coordinates, this can be applied respectively, i.e. local the X-axis of enemies and Lara points to their right, and the Z-axis points in the direction which they are facing. The Y-axis always points down).

Every active/visible item must always be in a valid room: During item movement (either by the engine, i.e. for walking enemies or even grenades or crossbow arrows, or by scripting) an item's room is always updated on every change of position.

If an item moves around in a single room, this isn't much of an issue (since the item's room number stays the same), but it becomes important if items move into other rooms. This is usually done via doors, where each door leads into only one adjoining room. (the importance becomes obvious when you consider overlapped rooms)

All functions that deal with item positions and movement also require or return a room number, which is used to ensure that an item is always in a valid room.

This is the reason why functions like itemobj:moveBy() (which doesn't require a destination room number) only works reliable with movement steps less than 1024, (or less than a sector difference, because a sector is 1024x1024 units) to ensure it doesn't "skip" over a door and hence is unable to determine an adjoining room. For the same reasons you cannot simply move an item through a wall into a (seemingly) neighbour room.

So, whenever possible, keep track of an item's room number when you move it around !


Ticks and Timers

One tick is 1/30 of a second, and (for the tr4 engine) also one rendered frame: All animation and item movement is based on this timing.

As such, also T4Mod timers run with a precision of 1/30 second, or one tick. The T4Mod timers should not be confused with the 'timer' value for triggers: The mod's timers are something completely different: They can save you lots of rollingball-trigger rooms and even more, allow things that could hardly be done before.

See the startTimer for details.


Savegames and Hubs

Whenever you do a leveljump, the current script state for the level you are leaving is stored, so that (when going back) script operation resumes at the point where you left that level.
This goes hand in hand with the internal game hub information, and using the 'resethub' feature will also erase the scriptstate for the levels so that they will be reinitialized as expected.

Script state information is saved within the savegame file, as a result the savegames will grow in size - depending on the size of the scripts used - but still within acceptable limits for today's computers...


Configuration file

While a lot of options can be defined via the config functions during script runtime, some settings must be defined before the mod starts.
These are settings for memory allocation, vertex- and sprite buffers and the definition of keyboard aliases.

On startup, T4Mod read a file "t4mod.cfg" in the mod directory. The format is similar to an .ini file: comment lines start with a semikolon, section names are enclosed in square brackets.


Debug console

T4Mod has a debug console which can be toggled with the tilde key (left of the number 1 key, above the TAB key).

Messages can be printed to the debug console with the "print()" statement, and all script errors and warnings will be printed into this console. It is a good idea to check the console for script problems if things don't work as expected.

Note: The console will not be visible in fullscreen mode: The game must run in windowed mode for the console to be used. However, you can switch between fullscreen and windowed mode at any time by pressing ALT-ENTER.
Also, the console cannot be used for input right now, if the console becomes the active window (i.e. by clicking on it) then the game will pause - click on the game window to resume !


Audio

play music file

playMusic (  [music_id, loopmode] )

Parameters:
music_id
The number of the .wav file to be played
loopmode
Loop mode: 0-once then backgrnd, 1-loop, 2-once then silence

Play audio file "audio/<musicid>.wav" as background music.

music_id can be in the range from 0 to 999. The default (if no argument) is to play the level background music (as defined in the level file).


play sound effect

playSfx ( sound_id [, pitch, x, y, z] )

Parameters:
sound_id
which sound effect to play
pitch
pitch tuning
x
x position
y
y position
z
z position

Plays sound effect nr. sound_id. Sound ids are in the range from 0 to 369 (incl.). The sound should be included in the level file.

Note: regular (one-shot) samples are played differently than looping sounds. When this function is used to play a non-loop sound id, the whole sample is played once.
However, if the sample is marked as a loop-sound it will only play during this frame tick (1/30 sec) and stop in the next - unless triggered again, in which case it will loop the sample until it is not played on successive frame ticks anymore.
For now this means, that in order to play looping sounds you must play them each tick with the help of timers.

pitch is an optional value from -100 to 100 and will adjust the base pitch (as defined in the sounds list) by this value.

If x,y,z coordinate are given, the sound will be played at the specified location, otherwise it will play globally (like a background sound)

To play a sound at an item's location, use the item method itemobj:playSfx.


set background music

setDefaultMusic ( music_id )

Parameters:
music_id
The music number to play as background

Sets the default background music. Due to the way the value is handled by the game, only default music 0-254 is allowed.


Configuration

configuration functions

config

The global config table holds a couple of functions to control game and mod options.


pushables configuration

config.pushables

Pushables can currently be configured per type via this table.

Note: This will most likely change in the future, where the pushable config methods will be members of their own movable type object.

config.pushables[n] returns a pushable type object which has a couple of methods to configure the behaviour of the pushable (pushable1 to pushable5). (Where n is an integer from 1 to 5)

Example:

config.pushables[1]:setheight(4);

bigcrate = config.pushables[2];
bigcrate:setheight(7);
bigcrate:allowpull(false);

Whenever a pushable is configured to be 'solid' (which means, it has it's height set to a value larger than 0), it can be climbed onto at the given height and can have other solid pushables stacked on top of it.
However, if a solid pushable is pushed onto a twoblock platform, it will behave like a normal pushable until it is moved off the lift, where it will become solid again.

Pushables with a height of 0 behave like regular pushables. They can be mixed with solid pushables, have pull restricted and may have an optional grip offset, but they can not be stacked.

Note: pushables should only be set up at script startup. Changes to the pushable height after the level script is initially run will be silently ignored. It is still possible to adjust things like allowpull or changing the grab position during the game, but remember that pushables with randomly moving handles may not always be what the player expects...


get folumetric fx

config.getVolFx ( )

Return Values:  boolean
boolean
volumetric effects: on=true, off=false

Returns true, if volumetric effects are enabled, false if volfx are disabled.


set max visibility

config.setClipDistance ( range )

Parameters:
range
Visibility range

This will set the maximum rendering distance in sectors. The default value is 20480 (1024*20 = 20 sectors), the range value is limited to a minimum of 2048 (2 sectors) and a maximum of 102400 (100 sectors)

Note: increasing the visibility range will affect the number of rendered polygons, make sure you increase the vertexlimit in the t4mod.cfg file if needed.

Also see config.setFogFar


set fog color

config.setFogColor ( red, green, blue )

Parameters:
red
red color component
green
green color component
blue
blue color component

Sets the color of the distance fog.


set far distance

config.setFogFar ( distance )

Parameters:
distance
distance where the fog ends

Set the far distance of the fog: This is the distance at which the distance fog ends and has reached maximum density.

Anything beyond this distance will be completely colored with the defined fog color (if volfx is disabled) or black (if volfx is enabled).

Be aware that this will not affect the rendering depth, see config.setClipDistance for that.


set fog near distance

config.setFogNear ( distance )

Parameters:
distance
distance where the fog starts

Set the near distance of the fog: This is the distance at which the distance fog starts and has the lowest density.

If volfx is off, then things will start to fade into fog color from here. If volfx is on, they will start to fade to black.


set volumetric fx

config.setVolFx ( volfx )

Parameters:
volfx
volumetric effects flag: true: enable, false=diable

Enables or disables volumetric effects. For switching volfx on or off during the game, it must be enabled at game start (i.e. in the preferences), otherwise it may not be enabled ingame (or at least, the result is visually different...).

If this function is called without a parameter, the volumetric effects setting will be restored to the initial value when the game was started.


set fogbulb color

config.setVolFxColor ( red, green, blue )

Parameters:
red
red color component
green
green color component
blue
blue color component

Set color of volumetric effects (fog bulbs).


set sokoban mode

pushable:allowPull ( allow )

Parameters:
allow
boolean true or false

Controls whether a pushable can be pulled by lara. If allow is false, Lara will no be able to pull a pushable (i.e. if it has a flat surface with no handle).

If allow is true, the pushable can be pulled normally.

The default for all pushable types is true.


pushable grabbing

pushable:setGrip ( side [, distance] )

Parameters:
side
side grip offset
distance
grip distance offset

Adjusts the grip position of a pushable.
The side offset adjusts the horizonta grab position. The grab position is where Lara will hold the pushable. Positive values will adjust the grab position to the right, while negative number adjust it to the left of the center.

Note that this affects all four sides, so the pushable should be textured or modeled to provide handles at the specified offset positions.

The optional distance will adjust the distance away from the pushable. Normally you should leave this to 0 (the default).

Both offsets are in world units, which means 256 will be 1/4 sector width. To avoid grab problems near walls and pits, the side offset is clamped at (-384,384), and distance to (-128,128).

Note: With solid pushables there is a gap between Lara's hands position and the actual sector boundary. This is due to the fact that Lara can not stand as close to a wall as she can to a model and the grip offset is adjusted automatically in this case.
In most cases this is barely visible or not distracting. If howver this should become a matter of aesthetical interest, a possible solution would be i.e. to have protruding handles modeled on the pushable.
(It may be possible to add some kind of 'snap-in' to smooth this out, i'll see into this later...todo)


set pushable height

pushable:setHeight ( height )

Parameters:
height
height in steps

Sets the climbable height of the pushable to height clicks (1click=256 position units). A height of 4 will make the pushable 1 square block high.

This basically controls if a pushable is 'solid', which means that it can be climbed on.
Ideally the height will match the visual representation of the pushable mesh model, so that Lara will neither float above the object nor run through it.

Pushables with a height of 0 (the default) will act just like regular pushables, they have the regular model collision.


FlipEffect Triggers

bind flipeffect action

onFlipEffect ( nr, func )

Parameters:
nr
flipeffect number (0-1023)
func
function to call, when this flipeffect is triggered.

Set a function callback for flipeffect number nr. This is the number that is set in the level editor for the flipeffect.

The flipeffect numbers 0 to 46 are used internally by the engine, and you should never trigged these numbers in your maps (as some are exclusively meant to be triggered by animations).

While you can set callbacks for these builtin effects (the builtin effects are run in any case), you should use only flipeffect numbers starting from 47 and above (but not higher than 1023).

The highest flipeffect number which can be used is 1023.

The user function func is called with argument onoff true if the flipeffect is triggered on, and false if the flipeffect is triggered off, the timerval value ist the value set in the trigger's timer field:

func (timerval,onoff).

Note: Flipeffects can also be triggered by animation commands, the most present example is Lara's running animation where flipeffect 32 is triggered on each footstep.

In most cases you will receive two calls, where the effect is triggered on and off again at the next tick (i.e. shatter objects, switches - so it's generally a good idea to check for true/false in the callback function func). Triggers involving Lara (sector on ground/in air) however will trigger on when Lara enters a sector with an effect number that is not yet triggered on, and will trigger off when Lara enters a sector which does not trigger that effect number anymore.

Practically this means that you can put the same trigger effect number on an area of sectors and they will trigger on only once when Lara enters this area, and off only when she leaves that area of sectors.


remove flipeffect actions

unbindFlipEffect ( FEnr [, FEnr,...] )

Parameters:
FEnr
flipeffect number
FEnr,...
more optional flipeffect numbers

Removes function callbacks for one or more flipeffects with number nr.


Inventory

Inventory functions

inventory

Inventory functions currently use a string to list all the items that should be added or removed from the inventory. The string consists of a comma or semicolon separated list of inventory-item identifiers.

An inventory-item identifier consists of:

  1. A letter defining the item type (see the list below)
  2. Where appropriate, the letter 'c' for a combo item or the letter 'a' for the related ammo
  3. A number for item types which exist multiple times (i.e. puzzle items, pickups, ammo-type etc)
    for combo items the first digit is the item number, and the second digit is the combo part (1 or 2)
    for ammo, 0 or none means the first ammo type, 1 the second and 2 the third ammo type (where available)
  4. Optionally a colon (':') followed by the amount (i.e. how many of those items to add/remove), for ammo the asterisk '*' can be used to give infinite ammo of that type

Inventory string item type letters:

Only item types (movables/slots) that are included in the level file can be added to the inventory, i.e. if you want to add the mechanical beetle to your inventory, but do not have the object included in the level, a warning will be printed to the console and it will be ignored.

Examples:

inventory.add("u,ua:200")        -- add the uzi (u) and 200 shots of uzi-ammo (ua:200) to your inventory
inventory.add("x,xa:20,xa1:300") -- add crossbow (x), 20 normal arrows (xa:20) and 300 poison arrows (xa1:300)
inventory.remove("pa:*,u")       -- removes all pistol ammo (pa:*) and removes the uzi (u) but leaves uzi ammo
inventory.set("pa:100")          -- set pistol ammo to 100 bullets
inventory.add("zc42")            -- adds the second part of puzzle combo 4
inventory.remove("f:*")          -- removes all flares

-- check for items in the inventory should use only one item in the list, -- otherwise only the last item's count is retrieved: amount_uzi_ammo = inventory.count("ua") has_pickup2 = inventory.count("i2")


add items to inventory

inventory.add ( invstring )

Parameters:
invstring
Inventory string

Adds items to the inventory.


set item amount in inventory

inventory.count ( invstring )

Parameters:
invstring
Inventory string
Return Values:  amount
amount

Retrieve the amount of an in the inventory. Only one item should be given in the inventory string.


remove items from inventory

inventory.remove ( invstring )

Parameters:
invstring
Inventory string

Removes items from the inventory.


set item amount in inventory

inventory.set ( invstring )

Parameters:
invstring
Inventory string

Set the amount of countable items in the inventory. For now, should be used to set fixed amount of ammo only...

Todo: This currently only works on items where you can have multiple numbers of, i.e. does not work on keys,questitems,examines etc. - use add/remove for these.


Items

global items table

item

This is a global table that contains all item objects of the current loaded level. Items in this table are indexed by their sequence number in the level starting from 0 (this differs from the regular array indexing).

To find out the index number for a specific item it is currently necessary to use external tool, either using tretool (which generates appropriate import files, but works for DXTre only, see downloads) or a tool like fexinspect.

The length operator ( #item ) will return the number of items in the level, so that items range from item[0] to item[#item-1]. Item indices outside this range will return nil.

Index lara will return the most important item, Lara. (this is the same as getting the lara-item via the correct index).

print( "Number of items in level:", #item )
print( "Lara's health is:", item.lara:gethealth() )


get colliders at position

getColliders ( x, y, z, room, radius [, checkLara] )

Parameters:
x
X Coord
y
Y Coord
z
Z Coord
room
Room number
radius
Collision-check range
checkLara
Include checking Lara (true/false)

This can be used like the item method itemobj:getColliders, but doesn't require a real item. Instead, the items in the radius around the given coordinates are returned.


add health for an item

itemobj:addHealth ( amount, force )

Parameters:
amount
the amount of health to add
force
force health on non-health objects

Add an amount to an item's health. amount can be negative.

Not all items manage a health value. Setting the health of such an item will do nothing, unless the second parameter has the boolean value true. Note that the health of such items is not saved in any case.


get item's current animation

itemobj:getAnim ( )

Return Values:  current, next
current
anim
next
anim

Returns the item's animation numbers.

The "next" animation is often used for chaining anims for a particular movable.

Animations and states have a mutual dependancy, where states may affect an items animation and vice versa. Examine an item's animation number and states if the result isn't as expected.

See also: itemobj:getStates, itemobj:setStates, itemobj:setAnim


get objects colliding w/item

itemobj:getColliders ( radius [, checkLara] )

Parameters:
radius
Collision-check range
checkLara
Include checking Lara (true/false)
Return Values:  tab_items, tab_statics
tab_items
Table with colliding Items, or false
tab_statics
Table with colliding Statics types, or false

Returns two tables, the first as an arrray of items, which are partially or fully inside the collision radius, the second as an array of statics. (Until the Statics-Objects are implemented, the statics array only contains the static type)

If the are no collisions, both return values are false. Otherwise, one of the returned tables may be empty, if there are hits only in the other.


get an item's health

itemobj:getHealth ( force )

Parameters:
force
force getting health on non-health objects

Get an item's health. Not all items manage a health value. Getting the health of such an item will return nil, unless the second parameter has the boolean value true. Note that the health of such items is not saved in any case.


get lara's mesh positions

itemobj:getMeshPos ( mesh_nr [, x, y, z] )

Parameters:
mesh_nr
the mesh nr to get the position for
x
local x offset
y
local y offset
z
local z offset
Return Values:  x, y, z, room
x
Item X Position
y
Item Y Position
z
Item Z Position
room
Room number

This method is valid on the Lara Item only, and will return the world x,y,z coordinates of the center of the mesh with number mesh_nr .

If the optional x,y,z offset arguments are given, these offsets are added to the mesh center position, taking the mesh's rotation into account, and thus being local offsets. This can be used to retrieve a fixed point relative to a mesh, which is not the center.


get OCB value of item

itemobj:getOcb ( )

Return Values:  number
number
Item's current OCB Value

Returns the current OCB value of item.


rotate an item

itemobj:getPitch ( )

Return Values:  angle
angle
pitch (x-axis) rotation angle

Returns item's current x rotation angle.


get item position

itemobj:getPosition (  [x, y, z] )

Parameters:
x
local x offset
y
local y offset
z
local z offset
Return Values:  x, y, z, room
x
Item X Position
y
Item Y Position
z
Item Z Position
room
Room number of the item

This method will return the item's position and current room number. If the local offset parameters are used, then the returned position is adjusted by this offset taking into account the items current rotation, i.e. to get a position which is 100 units in front of Lara, you would use

lara:getPosition(0,0,100)
(since Lara is facing towards her local z-axis)

Note: Local offsets are currently limited to 0-1023 (= max 1 sector offset)

See also: itemobj:moveBy, itemobj:moveTo


rotate an item

itemobj:getRoll ( )

Return Values:  angle
angle
roll (z-axis) rotation angle

Returns item's current y rotation angle.


get item x/y/z rotation

itemobj:getRotation ( )

Return Values:  ax, ay, az
ax
X axis angle
ay
Y axis angle
az
Z axis angle

Return the x,y,z angle of item.

All angles are returned in radians.


get item special values

itemobj:getSpecials ( )

Return Values:  special1, special2, special3
special1
special value 1
special2
special value 2
special3
special value 3

Returns the item's special values.

Every item object has a set of private values, which are handled differently by each item type. For example, for the spikes these values define how much the they are extended, for rollingballs they hold additional side-speed values and so on.

NOTE: While it is possible to achieve some interesting and useful effect, an item type's special values should be carefully examined before setting them. If an item has invalid values (i.e. if they are used to reference another item) then crashes or erratic behavior is likely to happen.

See also: setSpecials


get item speed

itemobj:getSpeed ( )

Return Values:  vspeed, hspeed
vspeed
vertical speed
hspeed
horizontal speed

Returns the item's speed values. Some items have a pair of values that control their internal movement acceleration: Lara, most baddies, rollingball, and possibly a lot more.

NOTE:Similar to itemobj:getSpecials the speed values are not a generic item feature, so items that are not designed to move around will possibly not use these values.


get item's animation state

itemobj:getState ( )

Return Values:  current, next
current
state
next
state

Returns the item's animation states.

Animations and states have a mutual dependancy, where states may affect an items animation and vice versa. Examine an item's animation number and states if the result isn't as expected.

See also: itemobj:setStates, itemobj:getAnim, itemobj:setAnim


get item's type id

itemobj:getType ( )

Return Values:  item
item
type

Returns the item type index (this is the "slot"-number).


rotate an item

itemobj:getYaw ( )

Return Values:  angle
angle
yaw (y-axis) rotation angle

Returns item's current y rotation angle.


removes item from the level

itemobj:kill ( )


This method will instantly remove an item from the current running level.

The item cannot be re-triggered (yet).


move an item by an offset

itemobj:moveBy ( x, y, z [, telefix] )

Parameters:
x
x distance
y
y distance
z
z distance
telefix
Lara item only: If true, avoids hair movement and resets camera

Moves item by the given offset.

This method should be used for small movements only (less than 1024 units = 1 square block), i.e. for continuous object movement.

The optional fourth parameter, telefix, is a boolean value only used when moving Lara: If it is true, then some adjustments are made to avoid involuntary hair movement and resets the camera view to Lara's position. This should be used when teleporting Lara over a larger distance.

Note: Solid pushables cannot be moved by this method. Also you should not move raisingblocks,trapdoors,door or possibly other items which manipulate the level geometry unless you know what you are doing !

See also: itemobj:moveTo, itemobj:getPosition


move an item

itemobj:moveTo ( x, y, z, room [, telefix] )

Parameters:
x
world x position
y
world y position
z
world z position
room
room number
telefix
Lara item only: If true, avoids hair movement and resets camera

Moves item to the given coordinates/room.

The room parameter may be nil, in this case the room number is calculated for the given coordinates. However, this requires some extra calculations and thus a room number should be given whenever possible (i.e. taken from a dummy item at the destination position).

The optional telefix parameter is a boolean value only used when moving Lara: If it is true, then some adjustments are made to avoid involuntary hair movement and resets the camera view to Lara's position. This should be used when teleporting Lara over a larger distance.

Note: Solid pushables cannot be moved by this method. Also you should not move raisingblocks,trapdoors,door or possibly other items which manipulate the level geometry unless you know what you are doing !

See also: itemobj:moveBy, itemobj:getPosition


play sound at item position

itemobj:playSfx ( sound_id [, pitch, wateronly] )

Parameters:
sound_id
which sound effect to play
pitch
pitch tuning
wateronly
play sound in water (true), or air (false) only

This plays a sound like the regular playSfx function does, but the sound is played at the item's position.

If wateronly is nil or not given, the sound will always play.

See also: playSfx to play sound at an arbitrary location.


get item's current animation

itemobj:setAnim ( current, next )

Parameters:
current
current animation or NIL to ignore
next
next animation

Sets an item's current and/or next animation.

The "next" animation is often used for chaining anims for a particular movable.

Animations and states have a mutual dependancy, where states may affect an items animation and vice versa. Examine an item's animation number and states if the result isn't as expected.

See also: itemobj:getStates, itemobj:setStates, itemobj:getAnim


set an item as potential target

itemobj:setAsTarget ( bool )

Parameters:
bool
true: is target, false: is no target

Sets an item as potential target for lara (and other ai objects). Target distinction for other objects (troops, enemies,...) is done by object type (movable id) of the target, so they may or may not aim at this item.

Targets must have positive health (see itemobj:setHealth) for being actually targetted by others (including Lara). Health of the item decreases when hit, and the item will lose target status once health reaches 0.

Also note that the target status of an item does not last forever: Items may lose their target status when more than a maximum amount of targets is active (5 by default).

Setting an item as a target is also a prerequisite for using the pathfinding features.


set an item's health

itemobj:setHealth ( health, force ) 

Parameters:
health
the health value, 1000 is Max. for lara
force
force health on non-health objects

Set an item's health. Not all items manage a health value. Setting the health of a non-health item will do nothing, unless the second parameter has the boolean value true.

Note that the health of such items is not saved in any case. Some movable types (i.e. the wraiths) also use the health value as a reference for other items: Changing the health value in that case may cause problems or crashes.


set OCB value for item

itemobj:setOcb ( ocbval )

Parameters:
ocbval
new ocb value

Sets the ocb value of item to the new ocbval. This can be used to modify the bevahiour of game items (see itemobj:trigger), where the item allows it (or rather, reacts on ocb changes).

Note: T4Mod patches the operation of the twoblock platform so that it follows height and speed changes in the ocb value, up and down. This can be used i.e. to create multi-floor lifts with call buttons.


rotate an item

itemobj:setPitch (  [angle] )

Parameters:
angle
pitch (x-axis) rotation angle

Sets item's x rotation angle.

angle must be in radians.


rotate an item

itemobj:setRoll (  [angle] )

Parameters:
angle
roll (z-axis) rotation angle

Sets item's z rotation angle.

angle must be in radians.


rotate item around all three axis

itemobj:setRotation (  [x, y, z] )

Parameters:
x
x-axis rotation angle
y
y-axis rotation angle
z
z-axis rotation angle

TODO: Rotate item to the given (absolute) angles.

All angles must be in radians.


set item special values

itemobj:setSpecials ( special1, special2, special3 ) 

Parameters:
special1
special value 1
special2
special value 2
special3
special value 3

Sets the item's special values. If either param is nil, then it's current value will not be changed.

Every item object has a set of private values, which are handled differently by each item type. For example, for the spikes these values define how much the they are extended, for rollingballs they hold additional side-speed values and so on.

NOTE: While it is possible to achieve some interesting and useful effect, an item type's special values should be carefully examined before setting them. If an item has invalid values (i.e. if they are used to reference another item) then crashes or erratic behavior is likely to happen.

See also: getSpecials


set item speed

itemobj:setSpeed ( vspeed, hspeed )

Parameters:
vspeed
vertical speed
hspeed
horizontal speed

Sets the item's speed values. If either param is nil, then it's current value will not be changed.

Some items have a pair of values that control their internal movement acceleration: Lara, most baddies, rollingballs and possibly a lot more. By setting the speed values it is possible to control such item's built-in movement.

NOTE:Similar to itemobj:setSpecials the speed values are not a generic item feature, so it is likely that not all items respond to value changes.


set item's animation state

itemobj:setState ( current, next )

Parameters:
current
current state or NIL to ignore
next
next state

Set the item's current and/or next state.

Warning: Most item types (movables) have a different number of states. You must not use higher state number than what a specific movable can handle, otherwise errors and crashes will happen. Examine an items states/behaviour with itemobj:getStates first, before you set it's states.

Animations and states have a mutual dependancy, where states may affect an items animation and vice versa. Examine an item's animation number and states if the result isn't as expected.

See also: itemobj:getStates, itemobj:getAnim, itemobj:setAnim


rotate an item

itemobj:setYaw (  [angle] )

Parameters:
angle
yaw (y-axis) rotation angle

Sets item's y rotation angle.

angle must be in radians.


shatter an item's mesh

itemobj:shatterMesh ( meshnr, x, strength )

Parameters:
meshnr
the mesh number which should be shattered
x
the mesh number which should be shattered
strength
amount of debris

The item's mesh number meshnr is shattered, which means it explodes in little polygon shards. The effect is merely visual, and has no influence on an item's health or hitboxes. Shattered meshes are currently not saved, so they will reappear when a savegame is loaded. It may be a good idea to itemobj:kill an item once you are finished deconstructing it's meshes.


trigger item

itemobj:trigger (  [flag] )

Parameters:
flag
true: trigger on, false: trigger off. Default is true (on).

Triggers item on or off.
If no flag parameter is given, the the item wille be toggled to it's opposite trigger status. If flag is true, the item will be triggered on, if the flag parameter is false, the item will be deactivated (where possible)


rotate an item

itemobj:turnBy (  [x, y, z] )

Parameters:
x
X axis angle
y
Y axis angle
z
Z axis angle

Rotate item by the given angles.

All angles must be in radians.


Keyboard

bind keyboard action

onKey ( key, func [, upkey] )

Parameters:
key
The key name as defined in the keys cfg
func
The function to be called
upkey
Function receives key-up events [deprecated]

Set a keyboard callback for the specified keyboard alias key (key aliases are defined in the keys.cfg file).

The key parameter can be prefixed by '+' or '-': With a '+', function func will be called when the key is pressed down and a second time when the key is released again. With '-' the function will only be called when the key is released. Without prefix, the function will only be called when the key is pressed down.

The called function can distiguish between key-down and -up action by the function parameter, which is true if the key was pressed down, and false if the key was released.

Example:

function testkey(keydown)
    if keydown then
       print("Key was pressed down")
    else
       print("Key was released")
    end
end

onKey("h",testkey) -- key down only

onKey("+j",testkey) -- key up and down

onKey("-k",testkey) -- key up only


remove keyboard callbacks

unbindKey ( key [, key,...] )

Parameters:
key
key to remove
key,...
more optional keys

Removes one or more keyboard callback bindings.


Lights

add temporary foglight flash

addFlash ( x, y, z, r, color, radius )

Parameters:
x
x position
y
y position
z
z position
r
room
color
color rgb(r,g,b,intensity)
radius
light effect radius

Create a temporary explosion flash effect, much like a grenade explosion. radius shouldn't be less than 1024 (1 sector) or it may not be visible (good values are around 4096, which is 4 sectors).

As a side effect, this also produces some smoke particles and looks slightly different when created in a water room (which is the only reason why a room number is required), however, this effect isn't very fexible and may be removed in the future in favour of better fog bulb handling.


add temporary dynamic light

addLight ( x, y, z, color, duration )

Parameters:
x
x position
y
y position
z
z position
color
light color rgb(r,g,b,intensity)
duration
light lifetime in ticks

Creates a temporary dynamic light in the level that will be active at the given position for duration ticks.

color is a color value obtained via the rgb function, where the alpha value (4th parameter to rgb()) defines the light intensity.

Example:

-- create a red light over lara's head for one second:
lara=item["lara"]
x,y,z=lara:getPosition()
addLight(x,y-1024,z,rgb(200,0,0,100),30)

The minimum duration is 1 tick, and the maximum duration is currently at 255 ticks. The total number of lights that can be active a a given time (using this function) is 16: Any more lights added with this function are ignored until one of the 16 active lights 'goes out' (= it's duration has expired and it is removed).

The reson for these limits is to prevent 'losing' lights in the level: The engine's maximum amount of dynamic lights is 32, which means that if you have a christmas tree in a room with 32 lights on it, then there will be no dynamic light anywhere else in the level - you can still put up fires and torches, but they will not light their surroundings.


Misc

binary and

binAnd ( a, b )

Parameters:
a
Value a
b
Value b
Return Values:  a&b
a&b

Returns the result of the binary operation a&b (that is, the binary AND operation)


binary or

binOr ( a, b )

Parameters:
a
Value a
b
Value b
Return Values:  a|b
a|b

Returns the result of the binary operation a|b (that is, the binary OR operation)


binary exclusive or (xor)

binXor ( a, b )

Parameters:
a
Value a
b
Value b
Return Values:  a^b
a^b

Returns the result of the binary operation a^b (that is, the binary XOR operation)


jump to another level

changeLevel ( levelnumber [, startpos] )

Parameters:
levelnumber
The level number to jump to
startpos
Lara's starting position index

Initiates a levelchange. If startpos is not given, lara will start at the default position.

Note that the levelchange is deferred until the end of the current tick - it will not happen instantly. This means, when this function is called multiple times during a tick then the last given level number will be the one which is loaded.

Levelnumbers start from 1, and count in the order as defined in the trle script.txt file. Level number -1 can be used to go back to the title.


get Lara's hands/action state

getActionState ( )

Return Values:  actionstate
actionstate
Action status ID

Get Lara's current action state: The action state basically defines what Lara is currently doing (with her hands), and depending on that, if she may draw a weapon or can grab a ledge.

The action state can have values from 0 to 5 as follows:

  1. Idle: Lara's hands are free, so that she can draw a weapon, pick something up or grab a ledge etc.
  2. Hands are busy: Lara is currently in the process of picking something up, activating a switch, holding to a ledge/ladder or is crawling. This inhibits drawing a weapon or lighting a flare etc.
  3. Drawing a weapon or lighting a flare. When the draw-weapon animation is done, switches to 4, when a flare was lit, switches back to 0.
  4. Holstering a weapon. When the holstering animation is complete, the action state will change to 0.
  5. Holding a weapon (either just holding it, or firing)
  6. This rarely happens, seemingly only after she has just picked up a flare/torch from the ground (during which the action state was 1) and gets back up to her normal position (standing/crouching), where it will change back to 0.

See also: setActionState


get mouse coordinates and buttons

getMouse ( )

Return Values:  x, y, buttons
x
Mouse virtual x position
y
Mouse virtual y position
buttons
Mousebutton bits

Returns the mouse position in virtual coordinates, where 0,0 is the top left and 1000,1000 is the bottom right of the screen. This is to support consistent positions independant of the current resolution and is also used for other 2D-screen coordinates (see textBox).


get Lara's stamina

getStamina ( )

Return Values:  stamina
stamina
Current stamina (max:120)

Get Lara's stamina value (used for sprint).

See also: setStamina


create a color

rgb ( r, g, b [, alpha] )

Parameters:
r
red
g
green
b
blue
alpha
alpha/intensity, default:255

Creates a color value that can be used for various functions which require colors. All values are between 0 and 255.

The default value of the optional alpha parameter is 255.


set Lara's hands/action state

setActionState ( actionstate )

Parameters:
actionstate
Action status ID

Sets Lara's action state. The action state basically defines what Lara is currently doing (with her hands), and depending on that, if she may draw a weapon or can grab a ledge.

The actionstate is normally handled by the internal movement and animation handling, and setting it should rarely be necessary - it may be required in situations where custom animations are triggered or to disable weapons.

The action state can have values from 0 to 5 as follows:

  1. Idle: Lara's hands are free, so that she can draw a weapon, pick something up or grab a ledge etc.
  2. Hands are busy: Lara is currently in the process of picking something up, activating a switch, holding to a ledge/ladder or is crawling. This inhibits drawing a weapon or lighting a flare etc.
  3. Drawing a weapon or lighting a flare. When the draw-weapon animation is done, switches to 4, when a flare was lit, switches back to 0.
  4. Holstering a weapon. When the holstering animation is complete, the action state will change to 0.
  5. Holding a weapon (either just holding it, or firing)
  6. This rarely happens, seemingly only after she has just picked up a flare/torch from the ground (during which the action state was 1) and gets back up to her normal position (standing/crouching), where it will change back to 0.

See also: getActionState


set Lara's stamina

setStamina ( stamina )

Parameters:
stamina
Stamina value (max:120)

Set Lara's stamina value (used for sprint).

See also: getStamina


Particles

particle functions

particle

The tr4 engine uses numerous specialized particle mechanisms for all kind of different effects, like shockwaves, watersplashes, mesh-explosions, lightning beams and electric arcs and the like, but there's also one more generalized and versatile particle system.

Beside some of the more specialized effects, the generic particle system (used by particle.addSprite and particle.addStreak can be used for numerous cool effects.

(These functions may seem a bit complicated at first, due to the number of parameters required - this is probably being enhanced in future versions, which may allow to create and use particle-"templates")


add a electric arc beam effect

particle.addArc ( source_x, source_y, source_z, dest_x, dest_y, dest_z, color, lifetime, amplitude, beam_width, segments )

Parameters:
source_x
Origin X-position
source_y
Origin Y-position
source_z
Origin Z-position
dest_x
Destination X-Position
dest_y
Destination Y-Position
dest_z
Destination Z-Position
color
beam color
lifetime
brightness/duration of the beam (1-127)
amplitude
oscillation strength (1-255)
beam_width
width of the beam (0-255)
segments
number of segment splits (1-5)

Creates an electric arc between the source and destination coordinates. Duration of the beam also affects the brightness.

This effect is like a slow transforming electric arc, see addLightning for a similar effect.


add a lightning beam effect

particle.addLightning ( source_x, source_y, source_z, dest_x, dest_y, dest_z, color, lifetime, amplitude, beam_width, segments )

Parameters:
source_x
Origin X-position
source_y
Origin Y-position
source_z
Origin Z-position
dest_x
Destination X-Position
dest_y
Destination Y-Position
dest_z
Destination Z-Position
color
beam color
lifetime
brightness/duration of the beam (1-127)
amplitude
oscillation strength (1-255)
beam_width
width of the beam (0-255)
segments
number of segment splits (1-5)

Creates a lightning effect between the source and destination coordinates.

This is similar to addArc, but the beam is more like a flicker lightning strike.


start a shockwave effect

particle.addShockwave ( x, y, z, inner_radius, outer_radius, color, lifetime, speed [, damage, angle] )

Parameters:
x
X Position
y
Y Position
z
Z Position
inner_radius
Inner/slower starting radius
outer_radius
Outer/faster starting radius
color
color of shockwave
lifetime
duration of shockwave
speed
Expansion speed (>0: expand, <0 contract)
damage
damage scale (0:none, 1:low, 2:high)
angle
shockwave orientation (0-360, x-axis only)

Creates a shockwave effect at the given coordinates. The shockwave will grow or shrink according to the speed parameter, however, the outer_radius will always grow faster than the inner_radius. After @lifetime ticks the shockwave will fade out. There is a maximum of 16 shockwaves that can be active at a time.

Damage: Health damage to Lara will happen at the outer ring, note that the damage taken is also affected by the expansion speed !
Especially when using negative speed values (contracting shockwave), this will effectively heal Lara on contact! Caution: Health maximum is not checked by the engine, so it is possible to heal Lara above the maximum health value!

The shockwave is normally aligned to the floor (angle=0), orientation can only be rotated around the x axis.


add a sprite particle

particle.addSprite ( x, y, z, spd_x, spd_y, spd_z, gravity, falloff_x, falloff_z, color_start, color_end, lifetime, fade_in, fade_out, flags, sprite_nr, scale_start, scale_end, angle, rotation [, max_y_bounce, cycle_repeat] )

Parameters:
x
Origin X-position
y
Origin Y-position
z
Origin Z-position
spd_x
Particle X-speed
spd_y
Particle Y-speed
spd_z
Particle Z-speed
gravity
Y-speed acceleration (+/- 32768)
falloff_x
X-speed deceleration (slowdown, 0-15)
falloff_z
Z-speed deceleration (slowdown, 0-15)
color_start
Particle start color
color_end
Particle end color
lifetime
Particle duration (0-255)
fade_in
Color cycle fade-in time (0-255)
fade_out
Fadeout time (0-255)
flags
Particle flags ("fdwb": fire,damage,wind,blend)
sprite_nr
Sprite number to use
scale_start
Sprite start size (0-255)
scale_end
Sprite end size (0-255)
angle
Sprite initial rotation angle (0-360)
rotation
Sprite rotation speed (0-255)
max_y_bounce
Max y speed before bounce (0-255)
cycle_repeat
Cycle repeat time (0-255)

Produces a single sprite particle at the given coordinates.

The flags parameter is a string containing one or more letters which define some of the particles properties:

Lifetime, fade_in and fade_out define the color gradient through which the particle cycles:

|----------------------------------- lifetime --------------------------------|
|-------- fade_in time --------|               |------- fade_out time --------|
|<- color_start to color_end ->|<- color_end ->|<- color_end to transparent ->|


add a line streak particle

particle.addStreak ( x, y, z, spd_x, spd_y, spd_z, gravity, falloff_x, falloff_z, color_start, color_end, lifetime, fade_in, fade_out, flags [, max_y_bounce, cycle_repeat] )

Parameters:
x
Origin X-position
y
Origin Y-position
z
Origin Z-position
spd_x
Particle X-speed
spd_y
Particle Y-speed
spd_z
Particle Z-speed
gravity
Y-speed acceleration (+/- 32768)
falloff_x
X-speed deceleration (slowdown, 0-15)
falloff_z
Z-speed deceleration (slowdown, 0-15)
color_start
Particle start color
color_end
Particle end color
lifetime
Particle duration (0-255)
fade_in
Color cycle fade-in time (0-255)
fade_out
Fadeout time (0-255)
flags
Particle flags ("fdwb": fire,damage,wind,blend)
max_y_bounce
Max y speed before bounce (0-255)
cycle_repeat
Cycle repeat time (0-255)

Produces a single line particle at the given coordinates.

The flags parameter is a string containing one or more letters which define some of the particles properties:

Lifetime, fade_in and fade_out define the color gradient through which the particle cycles:

|----------------------------------- lifetime --------------------------------|
|-------- fade_in time --------|               |------- fade_out time --------|
|<- color_start to color_end ->|<- color_end ->|<- color_end to transparent ->|

Note: The length of a line particle is defined by it's velocity. I.e., if you have a slow particle with low x/y/z-speeds, then the particle may be hard to see.


Rooms

find room by world coords.

findRoom ( x, y, z )

Parameters:
x
worldpos x
y
worldpos y
z
worldpos z
Return Values:  room_nr
room_nr
room number or nil

Finds a room at the given world coordinates. If the is no room at that position, this function will return nil , otherwise the first found room number will be returned.

Note: This function may not always give the expected results: if there are overlapping rooms at the coordinates, it is hard to predict which one will be returned.

Wherever one of the room/sector functions returns a room value, this should be used instead for traversing along rooms !


toggle fliproom group

flipGroup ( group [, flag] )

Parameters:
group
fliproom group number
flag
true: trigger on, false: trigger off, none: toggle

Activate or deactivate a group of fliprooms. The fliproom group must be defined in the room editor. There also is only a limited game buffer (10 entries) for managing the fliprooms, so the group values must be between 0 and 9 (incl.).

If flag is true, the flipgroup will be activated, if the flag parameter is false, the flipgroup will be deactivated (restored).
If no flag parameter is given, the flipgroup will be toggled (i.e. on if it is currently off, and vice versa).


get exact ceiling height at room position

getCeiling ( x, y, z, roomnr )

Parameters:
x
X position
y
Y position
z
Z position
roomnr
Room number
Return Values:  ceil, room
ceil
Ceiling height (world y-pos)
room
Room number

Get the ceiling height at position x,y,z in room roomnr.

Note that this function is exact, as it considers floor- and ceiling tilts. If you only require a rough estimation of the height, or only want to check for walls or sector traversal, then use getSectorHeight, which is more efficient, but less exact.


get exact floor height at room position

getFloor ( x, y, z, roomnr )

Parameters:
x
X position
y
Y position
z
Z position
roomnr
Room number
Return Values:  floor, room
floor
Floor height (world y-pos)
room
Room number

Get the floor height at position x,y,z in room roomnr.

The height returned is in absolute world range (y position, a value of -32512 means it's a wall...).

Note that this function is exact, as it considers floor- and ceiling tilts. If you only require a rough estimation of the height, or only want to check for walls, then use getSectorHeight, which is more efficient, but less exact.


get exact floor and ceiling height

getFloorCeiling ( x, y, z, roomnr )

Parameters:
x
X position
y
Y position
z
Z position
roomnr
Room number
Return Values:  floor, ceil, room
floor
Floor height (world y-pos)
ceil
Floor height (world y-pos)
room
Room number

Get the floor and ceiling heights at position x,y,z in room roomnr.

It is usually slightly faster to use this function instead of separate calls to getFloor/getCeiling if you need both values for the same position.


get sector lowest/highest

getSectorHeight ( x, y, z, roomnr )

Parameters:
x
X position
y
Y position
z
Z position
roomnr
Room number
Return Values:  floor, ceil, room
floor
sector lowest (world y-pos)
ceil
sector highest (world y-pos)
room
Room number

Get the lowest and highest coordinates of a sector at the given x,y,z position in room roomnr.

The returned height values are the lowest and highest points in the whole sector, to obtain exact floor or ceiling heights, see getFloor etc.

This function is faster than the high resolution getFloor/getCeiling functions, and should be used when a coarse height check is sufficient (i.e. for wall-checks or sector traversal/room finding)


Screen and Camera Effects

screen fader

setFader ( start, end )

Parameters:
start
starting fade opacity
end
fade ending opacity

Fades the screen opacity from start to end (where 0 is black and 255 is normal). This will start instantly and the fading cycle happens in a fixed time (about 1/2 second).

Note: This command is bound to the built-in game function for the fader (used in screen transitions), but is quite limited in it's effect and may be removed in the future, as drawRect() will provide more flexibility.


set camera lens/field of view

setFov ( fov )

Parameters:
fov
Field-of-view in degrees

Sets the camera's field-of-view area in degrees (0-360). Passing nil as parameter resets the fov value to it's default (80).


cinematic borders

setMovieBars ( height, speed )

Parameters:
height
the height of the bars
speed
the speed of bar movement

If height is greater than 0, movie bars will appear on the top and bottom of the screen (like in cinematic sequences). These bars will grow from the top resp. bottom of the screen width a speed of speed until they have reached height.

Note: Load and Save is disabled while moviebars are active ! To deactivate the moviebars, set height to 0.


start earthquake rumble

startQuake ( strength )

Parameters:
strength
strength and length of quake

Starts an earthquake. Duration and strength of rumbling depend on strength parameter: Higher values result in longer and stronger quakes.

In general, even very strong quakes (>500) will rarely last longer than a few seconds, if you need longer lasting quakes without excessive shaking you should trigger them at regular intervals, i.e. in a timer loop.


Text Display

display text on screen

textBox ( layer, x, y [, text, bgcolor, style] )

Parameters:
layer
layer nr. (0-5)
x
x-position of layer (horizontal)
y
y-position of layer (vertical)
text
text string
bgcolor
background color (0x0000-0xffff)
style
style option string

Displays the string text in on the screen using textlayer layer (a number from 0-5).
There are currently 6 layers of text that can be displayed on screen at one time. Each of these layers has it's own idenpendent position, background and text color and style. To deactivate a layer, use an empty string ("") as text.

The textlayer will be positioned at horizontal position x and vertical position y on the screen. The position of the upper left corner is 0,0 and wthe screen position of the lower right corner is always 1000,1000; regardless of the actual screen resolution and text alignment.

Negative screen positions are legal and will move the layer beyond the left/upper screen border, while position greater than 1000 will move the text off screen beyond the right/lower screen border.

text is a string, that will be rendered starting at the given position. Linefeed and tab characters are allowed.

If text, style and bgcolor parameters are omitted (i.e. only layer,x and y are given), then the layer will be repositioned without changing the text. Setting text to an empty string will effectively remove the current layer from the screen.

It is possible to change the text color on the fly using the follow character escape sequences:

(Note: While there are color-affecting escape chars above 8, these mostly produce random flickering (at least on my machine) and should not be used)

Other useful character codes:

bgcolor is a color value obtained by the rgb function. The alpha value defines the transparency of the textbox background. (This parameter can be 0 for no background)

style is a string where each character defines an alignment or formatting style to be used for the text. The following style options are currently recognized:

(for l,r and c only the last one defined will be used)

Examples:

textBox(1,500,500,"Hello",rgb(0,128,0),"ci");

will display "Hello" (using layer 1) in the center of the screen (position 500,500) with a middle-green (rgb(0,128,0)) background. The text is horizontally centered and blinks (the 'c' and 'i' letters in the style string).

textBox(1,0,0,"Simple");

will just display "simple" in the top, left corner.

textBox(1,100,100);

will move the textbox to position 100,100 without changing the content.


hide text boxes

textBoxOff ( layer [, ...] )

Parameters:
layer
layer nr. (0-5)
...
more layer numbers

Hide one or more textbox layers.


Timers

start a timer

startTimer ( delay, func )

Parameters:
delay
delay in ticks
func
a function or coroutine that will be executed
Return Values:  timerid
timerid
the id of the started timer (for use with stopTimer())

Creates a timer that will execute function func when delay ticks (1 tick = 1/30 sec) have passed. func will be called with the corresponding timerid as it's first argument.

The current minimum for delay is 1 tick. Anything below will be set to 1. The upper limit is somewhere about 2 years.

Timers will not repeat by default: In order to make a timer repeat, the callback func must return true. If it returns true, then func will be called again when another delay ticks have passed.
If it returns false (or nothing), the timer will be removed from the timer queue and func will not be called again.

func can also be a coroutine:
In this case the timer will repeat until the coroutine has ended. If the coroutine yields, the first parameter to yield can be a value for the next delay after which the coroutine is resumed.
If no argument is given to yield, the coroutine will be resumed when delay ticks have passed.



stop all timers

stopAllTimers ( )


Stops and removes all currently waiting timers.

If this function is called from within a timer's callback function, the timer will not repeat, even if the callback returns true. Likewise, any timer controlled coroutines will be stopped.


stop a timer

stopTimer ( timerid )

Parameters:
timerid
the id of the timer

Removes timer with id timerid from the timer queue. timerid is the number returned by startTimer().

If stoptimer() is called from within the timer's callback function, the timer will not repeat, even if the function returns true. Likewise, coroutines controlled by this timer will be stopped.