Lua API

Note

Some platform-specific sections have been removed from this document.

Contents

1. Math

1.1 Vector3 (temporary)

1.2 Vector3Box (full userdata)

1.3 Quaternion (temporary)

1.4 QuaternionBox (full userdata)

1.5 Matrix4x4 (temporary)

1.6 Matrix4x4Box (full userdata)

1.7 Math (library)

2. Worlds and units

2.1 Application (singleton)

2.1.1 Win32

2.1.2 Development

2.2 Game (singleton)

2.3 Window (singleton or regular)

2.4 World

2.4.1 Units

2.4.2 Physics

2.4.3 Line Objects

2.4.4 Particles

2.4.5 GUI

2.4.6 Level

2.4.7 Level (deprecated)

2.4.8 Sound

2.4.9 Timpani

2.4.10 Data

2.4.11 Debug helpers

2.4.12 Shading Environment

2.5 Level

2.6 Unit

2.7 Light

2.8 Camera

2.9 Viewport

2.10 Material

2.11 LineObject

2.12 Mesh

2.13 ShadingEnvironment

3. Physics

3.1 PhysicsWorld

3.2 Actor

3.3 Mover

4. Sound

4.1 TimpaniWorld

4.1.1 Tool Interface

4.2 Timpani (singleton)

4.2.1 Tool interface

5. Input

5.1 InputController (singleton)

5.1.1 General

5.1.2 Buttons

5.1.3 Axes

5.1.4 Rumble

6. Utility Libraries

6.1 ResourcePackage

6.2 Profiler (singleton)

6.3 Script (singleton)

6.4 Localizer

7. AI

7.1 Broadphase (full userdata)

7.2 NavigationMesh

8. GUI

8.1 Color (temporary)

8.2 Vector2 (temporary)

8.3 Rotation2D (temporary)

8.4 Gui

10. Windows specific

10.1 SaveSystem (singleton)

10.1.1 Functions

12. Network

12.1 Network (singleton)

12.1.1 Common

12.1.2 Debugging

12.1.3 Config

12.1.4 LAN

12.2 RPC (singleton)

12.3 NetworkGame

12.4 UnitSynchronizer

13. Network -- LAN

13.1 LanClient

13.2 LanLobby

13.3 LanLobbyBrowser

1. Math

1.1 Vector3 (temporary)

A Vector3 is a three component vector (x, y, z). It is used to represents positions, directions, velocities, etc. Note that Vector3:s are temporary objects. You can only use a Vector3 during the frame it was created.

Vector3(x, y, z) : Vector3
Creates a new Vector3 with components (x, y, z).
add(a, b) : Vector3
Adds the two Vector3:s a and b and returns the result.
a + b
The same as add(a,b).
subtract(a, b) : Vector3
Subtracts b from a and returns the result.
a - b
The same as subtract(a, b)
- a
Negates a and returns the result.
multiply(a, f) : Vector3
Multiplies the vector a with the scalar f and returns the result.
a * f
f * a
The same as multiply(a, f).
divide(a, f) : Vector3
Divides the vector a with the scalar f and returns the result.
a / f
The same as divide(a,f).
multiply_elements(a,b) : Vector3
Multiplies the vectors a and b element by element and returns the result.
divide_elements(a,b) : Vector3
Divides the vectors a and b element by element and returns the result.
equal(a, b) : bool
Returns true if the vectors are equal.
to_string(v) : string
Returns a string representation of the vector. You should only use this for debugging purposes, do not save the string and read it back.
base(i) : Vector3
Returns the i:th base vector. I. e., base(1) returns the x-axis, etc.
zero() : Vector3
Returns the zero Vector3.
x_axis() : Vector3
y_axis() : Vector3
z_axis() : Vector3
Returns the corresponding axis.
right() : Vector3
left() : Vector3
up() : Vector3
down() : Vector3
forward() : Vector3
backward() : Vector3
Returns the corresponding semantic axis.
element(v, i) : float
Returns the i:th element in the vector, i. e., element(v, 1) returns the x-component of v.
set_element(v, i, f)
Sets the i:th element in the vector to f.
x(v) : float
Returns the x component of v.
y(v) : float
Returns the y component of v.
z(v) : float
Returns the z component of v.
set_x(v, x)
Sets the x component of v to x.
set_y(v, y)
Sets the y component of v to y.
set_z(v, z)
Sets the z component of v to z.
length(v) : float
Returns the length (the 2-norm) of the vector v.
normalize(v) : Vector3
Normalizes v and returns the result.
dot(a,b) : float
Returns the dot product of vectors a and b.
cross(a,b) : Vector3
Returns the cross product of vectors a and b.
distance(a,b) : float
Returns the distance between points a and b.
make_axes(x) : Vector3, Vector3
Given the x vector, returns two orthogonal vectors y and z, in such a way that x, y, and z form the basis for a coordinate system.
lerp(a, b, t) : Vector3
Returns the result of lerp:ing between vectors a and b with a fraction t.
.x : float
Returns the x component. You can assign this to set the x component.
.y : float
Returns the y component. You can assign this to set the y component.
.z : float
Returns the z component. You can assign this to set the z component.
min(v1, v2) : Vector3
Returns a vector that contains the minimum of each component in v1 and v2.
max(v1, v2) : Vector3
Returns a vector that contains the maximum of each component in v1 and v2.
to_elements(v) : x, y, z
Returns the elements in v.

1.2 Vector3Box (full userdata)

A "boxed" version of a Vector3.

You can store a Vector3 in a Vector3Box when you want to use it in a later frame. To use the Vector3 call unbox() to extract it from the box.

Vector3Box()
Creates a new Vector3Box. This will allocate memory, so use sparingly. Typically you should create the boxes in the init() function of your class and then just use store() to store values in it.
Vector3Box(v3)
Creates a new Vector3Box and stores the Vector3 v3 in the box.
Vector3Box(x, y, z)
Creates a new Vector3Box and stores Vector3(x,y,z) in the box.
store(v3)
Stores the Vector3 v3 in the box.
store(x, y, z)
Stores Vector3(x,y,z) in the box.
unbox() : Vector3
Extracts the stored value from the box.
.x : float
.y : float
.z : float
Get or set the correspoding component of the vector.

1.3 Quaternion (temporary)

Represents a rotation in the quaternion formulation (x, y, z, w). Note that it is not strictly necessary to understand quaternions to use this class, you can just treat it as an opaque representation of a rotation.

Quaternion(axis, angle) : Quaternion
Creates a quaternion that represents a rotation of angle radians around the vector axis.
from_elements(x,y,z,w) : Quaternion
Creates a quaternion from components.
identity(): Quaternion
Returns the identity quaternion.
axis_angle(axis, angle) : Quaternion
Creates a quaternion from an axis angle representation. (This is the same as Quaternion(axis,angle).)
from_matrix4x4(m) : Quaternion
Creates a quaternion from the matrix m.
look(dir, up) : Quaternion
Creates a quaternion with the rotation needed to represent an object looking in the direction dir with up as its up vector.
multiply(q1, q2) : Quaternion
Multiplies the two quaternions and returns the result. This creates the rotation you get by first rotating the object with q1 and then with q2.
equal(q1, q2) : bool
Returns true if the quaternions are equal.
normalize(q) : Quaternion
Normalizes the quaternion q and returns the result.
inverse(q) : Quaternion
Inverts the quaternion q and returns the result.
conjugate(q) : Quaternion
Returns the conjugate of the quaternion q.
dot(q1, q2) : float
Returns the dot product of the quaternions q1 and q2.
lerp(q1, q2, t) : Quaternion
Lerps between quaternions q1 and q2 and returns the result. The lerp performed by this function is a normalized lerp, or nlerp, which usually gives the best result.
norm(q) : float
Returns the length of the quaternion q.
matrix4x4(q) : Matrix4x4
Converts the quaternion to a matrix and returns the result.
decompose(q) : Vector3, float
Decomposes the quaternion q into a representation as a rotation around a vector and returns both the vector and the rotation angle.
to_elements(q) : x, y, z, w
Returns the elements of the quaternion as four individual floats.
angle(q) : float
Returns the rotation angle represented by q.
rotate(q, v) : Vector3
Rotates the Vector3 v by the quaternion q and returns the result.
to_string(q) : string
Returns a string representation of q. This should only be used for debugging purposes.
forward(q) : Vector3
Returns the forward direction of the rotation represented by the quaternion q.
up(q): Vector3
Returns the up direction of the rotation represented by the quaternion q.
right(q) : Vector3
Returns the right direction of the rotation represented by the quaternion q.

1.4 QuaternionBox (full userdata)

A "boxed" version of a Quaternion.

You can store a Quaternion in a QuaternionBox when you want to use it in a later frame. To use the Quaternion call unbox() to extract it from the box.

QuaternionBox()
Creates a new QuaternionBox. This will allocate memory, so use sparingly. Typically you should create the boxes in the init() function of your class and then just use store() to store values in it.
QuaternionBox(q)
Creates a new QuaternionBox and stores the Quaternion q in the box.
QuaternionBox(x, y, z, w)
Creates a new QuaternionBox and stores Quaternion.from_elements(x,y,z,w) in the box.
store(q)
Stores the Quaternion q in the box.
store(x, y, z, w)
Stores Quaternion.from_elements(x,y,z,w) in the box.
unbox() : Quaternion
Extracts the stored value from the box.

1.5 Matrix4x4 (temporary)

Represents a 4x4 matrix that stores both the position and the orientation of an object.

Matrix4x4(xx, xy, xz, yx, yy, yz, zx, zy, zz, tx, ty, tz) : Matrix4x4
Creates a matrix with x-axis (xx, xy, xz), y-axis (yx, yy, yz), z-axis (zx, zy, zz) and translation (tx, ty, tz).
from_elements(xx, xy, xz, yx, yy, yz, zx, zy, zz, tx, ty, tz) : Matrix4x4
The same as Matrix4x4().
to_elements(m) : xx, xy, xz, yx, yy, yz, zx, zy, zz, tx, ty, tz
Returns the elements of the matrix m.
zero() : Matrix4x4
Returns the zero matrix with all fields initialized to zero.
identity() : Matrix4x4
Returns the identity matrix that represents an object with no translation and no rotation.
from_translation(t) : Matrix4x4
Returns a matrix that represents the translation t.
from_quaternion(q) : Matrix4x4
Returns a matrix with the same rotation as the quaternion q.
from_quaternion_position(q, p) : Matrix4x4
Creates a Matrix4x4 using the rotation q and the position p.
from_axes(x, y, z, t) : Matrix4x4
Creates a Matrix4x4 from x-, y-, z-axes and a translation component.
copy(m) : Matrix4x4
Returns a copy of the matrix m.
multiply(m1, m2) : Matrix4x4
Multiplies two matrices. This will create the composite transform of the individual matrix transforms.
inverse(m) : Matrix4x4
Returns the inverse of the matrix m.
element(m, i, j) : float
Returns the element at index (i, j) in the matrix. Indices are 1-based, i.e. element(1,2) returns the y-component of the matrix’ x-axis.
set_element(m, i, j, f)
Sets the element at index (i,j) to f.
translation(m) : Vector3
Returns the translation in the matrix.
set_translation(m, v)
Sets the translation component of the matrix to v.
rotation(m) : Quaternion
Returns the rotation of the matrix as a quaternion.
set_rotation(m, q)
Sets the rotation of the matrix.
x(m) : Vector3
y(m) : Vector3
z(m) : Vector3
Returns the x-axis, the y-axis or the z-axis of the matrix.
axis(m, i) : Vector3
Returns the i’th axis of the matrix. 1 = x, 2 = y, 3 = z.
set_x(m,v)
set_y(m,v)
set_z(m,v)
Sets the x-, y- or z-axis of the matrix.
set_axis(m, i, v)
Sets the i’th axis of the matrix. 1 = x, 2 = y, 3 = z.
forward(m) : Vector3
up(m) : Vector3
right(m) : Vector3
Returns the forward, up or right axis of the matrix.
set_forward(m,v)
set_up(m,v)
set_right(m,v)
Sets the forward, up or right axis of the matrix.
transform(m, p) : Vector3
Transforms the point p using the matrix.
transform_without_translation(m, v) : Vector3
Transforms the vector v using the matrix, without translating. This is useful when you want to transform directions, rather than positions, from one coordinate system to another.
to_string(m) : string
Returns a string representation of the matrix. This should only be used for debugging purposes.
lerp(m1, m2, t) : Matrix4x4
Produces a new matrix by lerping between m1 and m2. This is accomplished by lerping the translation and rotation of the matrix individually. (Scale, etc, is not lerped.)

1.6 Matrix4x4Box (full userdata)

A "boxed" version of a Matrix4x4.

You can store a Matrix4x4 in a Matrix4x4Box when you want to use it in a later frame. To use the Matrix4x4 call unbox() to extract it from the box.

Matrix4x4Box()
Creates a new Matrix4x4Box. This will allocate memory, so use sparingly. Typically you should create the boxes in the init() function of your class and then just use store() to store values in it.
Matrix4x4Box(m)
Creates a new Matrix4x4Box and stores the Matrix4x4 m in the box.
store(m)
Stores the Matrix4x4 m in the box.
unbox() : Matrix4x4
Extracts the stored value from the box.

1.7 Math (library)

Generic math functions.

ray_box_intersection(from, dir, pose, radius) : float
Computes the intersection between the ray (from, dir) and the OOBB (pose, radius). If the ray collides with any of the planes of the OOBB, the distance to the collision point along the ray is returned (regardless of whether the ray started inside or outside the OOBB). If there is no collision, -1 is returned.
box_in_frustum(pose, radius, n1, o1, n2, o2, …) : bool
Returns true if the OOBB defined by (pose, radius) is completely enclosed by frustum defined by (n1, o1), (n2, o2). Each such pair specifies one plane of the frustum, with n being the normal of the plane (pointing out of the frustum) and o being the position of the plane along the normal n.
merge_boxes(pose_1, r_1, pose_2, r_2, … ) : pose, r
Merges a number of OOBBs (described by a Matrix4x4 and a radius) into a single OOBBs. The resulting OOBB will have the same axes as the first OOBB in the input. (I. e., the function will not return the minimum fitting OOBB.)
random([i1], [i2]) : float
Works as luas built-in math.random() but uses the Bitsquid random number generator instead of Lua's.

2. Worlds and units

2.1 Application (singleton)

Interface to access global application functionality. Note that since the application is a singleton (there is only one application), you don’t need to pass any Application object to the application functions. All the functions operate on the application singleton.

platform() : string
Returns a string identifying what platform the game is running on. “win32” for Windows and “ps3” for Playstation 3.
build() : string
Returns a string identifying the engine build, can be "debug", "dev" or "release".
build_identifier() : string
Returns a string identifying the build version (such as "2437 branch:release2".
You can set the build identifier in a post processing step after you have built your exe. The built exe will contain the string "a4e915264ceaa4424b3ed6d3d2fe5e1a" followed by 128 zero characters. You can replace the zero characters with whatever you want build_identifier() to return.
settings() : any
Returns an object containing the script settings from the settings.ini file. I. e., anything found under the "script_data" tag in the settings.ini file.
new_world() : World
Creates a new game world and returns it. You can have as many game worlds as you like. Multiple game worlds are useful for things like loading screens or inventory rooms.
render_world(world, camera, viewport, shading_environment)
Renders the world with shading environment shading_environment using the camera into the viewport.
release_world(world)
Destroys the world. You should call this when you are completely done with a particular world.
worlds() : table
Returns a table containing all the game worlds.
main_world() : World
Debug helper function that tries to find the "most important" world. This is usually the world where stuff is happening and where you want to test particle effects, sounds, etc. The "most important" world is defined as the world that was rendered last frame that contains the most units.
resource_package(name) : ResourcePackage
Creates a resource package from the .package file with the specified name.
release_resource_package(package)
Frees a resource package that was previously allocated with resource_package().
set_resource_property_preference_order(property_1, property_2, ...)
Sets the property preference order for loading resources. See the documentation on localization. Note that the platform should never be specified here, since that is automatic.
resolution() : width, height
Returns the screen resolution.
argv() : arg1, arg2, arg3, …
Returns the command line arguments supplied to the application.
create_viewport(world, viewport_template) : Viewport
Creates a viewport to be used when rendering the specified world using the named viewport_template. The viewport_template properties are specified in the render config file.
destroy_viewport(world, viewport)
Destroys the viewport.
get_data(i1, i2, …, in) : object
Gets a global script data object from the Application. i1, i2, …, in is a sequence of indices that can be either integers or strings. See section 3.5 Storing Data in Units for a description of how to use script data.
set_data(i1, i2, … in, value)
Sets the script data at the location specified by the sequence of indices to the specified value.
has_data(i1, i2, …, in) : bool
Returns true if data has been stored at the specified path and false otherwise.
quit()
Quits the application.
time_since_launch() : number
The time in seconds since the launch of the application.
make_hash(value [, ...]) : hash
Creates a combined hash out of the arguments. Numbers, nil, strings and hex numbers as strings can be hashed. The result is a string with a 64 bit hexadecimal hash.

2.1.1 Win32

win32_user_setting(i1, i2, ..., in) : object
Gets a value from the win32 user settings file. i1, i2, ..., in is a sequence of keys that can be either integers or strings.
set_win32_user_setting(i1, i2, ..., in, value)
Sets a value in the win32 user settings file.
save_win32_user_settings()
Saves the win32 user settings file to disk. The file which the data is saved to is determined by the key win32.user_settings in the settings.ini file. There you can specify a filename. The string %APPDATA% in the file name will be expanded to the user's AppData folder, i.e.:
win32 = {
	user_settings = "%APPDATA%\\Fatshark\\Hamilton\\user_settings.config"
}
enum_display_modes() : table
Returns a table with Vector3 containing all available display modes for all screens in the form (width, height, screen_index). Win32 specific.
open_url_in_browser(url)
Opens the URL in the default browser.
process_id() : int
Returns the id of the process.
restart_file_log([local_filename [, remote_filename]])
Closes the current file log and copies the remote log and then restarts logging.
local_filename
If specified, the new log will use this path. If not specified, the last log will be overwritten.
remote_filename
If specified, the new remote log will use this path. If not specified, the last remote log will be overwritten.
The following special tags can be used in the filenames:
%APPDATA%
The folder for user storage in Windows.
%HOSTNAME%
The name of the computer.
%DATE%
The date on the form YYYY-MM-DD.
%TIME%
The time on the form HH.MM.SS.
%RANDOM%
Eight random letters.
set_time_step_policy(params, ...)
Controls how the application's time step is advanced. Possible parameters are:
"variable"
Configures the engine to use variable time stepping. (This is the default.)
"fixed", fps
Configures the engine to run with fixed time steps at the specified frame rate. This means that the time steps taken will always be a multiple of 1/fps. If the engine runs faster than the specified frame rate it will take zero-length time steps to compensate.
"throttle", fps
Throttles the engine to the specified frame rate. The engine will be slowed down to run at the requested rate. This can be used to debug problems that only appear when the frame rate is low.
"no_throttle"
Disables throttling. (This is the default.)
"smoothing", frames, outliers, lerp
Configures the engine to use time step smoothing. When variable time stepping is used, smoothing the time steps over a number of frames can make the game feel less jerky. frames specifies the number of frames that should be averaged. outliers specifies how many extreme values to remove. With outliers=2, the two highest and the two lowest values are removed before the average is computed. lerp specifies how fast the value is allowed to change from the computed average. A low value means more smoothing, a higher value less smoothing. (Default is 11, 2, 0.1.)
"no_smoothing"
Disables time step smoothing.
"debt_payback", frames
If set to a non-zero value, the timer will try to keep track of its time debt -- i.e. how much the game time has drifted from an external world clock (because of smoothing, etc) and pay that debt back over the specified number of frames by adding extra time to them. This can be useful if you need your game to stay in sync to external clocks (for example for networking), because otherwise your game can "lose" time. (Default is 0.)
"external_step_range", min, max
Specifies that the external world time should be clamped to the specified range before it is inputted to the system. This is useful for preventing the system from taking really large steps when you break in the debugger. (Default value is 0, 0.02.)
"external_multiplier", multiplier
Sets a multiplier that can be used to accelerate or slow down the time for debugging purposes. (Default value is 1.)
"system_step_range", min, max
Specifies the minimum and maximum steps that the game is allowed to take. (Default value is 0, 0.02.)
"clear_history"
Clears the history of accumulated time debt, smoothing history, etc.

2.1.2 Development

sleep(ms)
Sleeps the specified number of milliseconds.
guid() : string
Only available for editors. Returns a globally unique identifier useful for uniquely identifying objects.
set_autoload_enabled(enabled)
If set to true, the package system will be disabled and resources will be autoloaded as they are accessed.
can_get(type, name) : bool
Returns true if the specified resource is available.
flush_autoloaded_dependencies()
Flush any dependencies loaded by autoload.
console_send(table)
Sends the table as a console command (same as if it had been sent from an external editor).
console_port() : int
Returns the number of the port that the console is listening on.

2.2 Game (singleton)

Represents the running game.

job_thread_require(script)
Runs require(script) in all the script worker threads.
add_job(function, unit)
Adds a job to be run in the script worker threads. function is the name of the global function that should be called in the worker threads and unit is the unit that should be passed as argument.
run_jobs()
Runs all the jobs that have been queued with add_job() and waits until they have completed.

2.3 Window (singleton or regular)

Represents an application window. (On Win32, on other platforms there may not be a window.)

This class can be used either as a singleton or as a regular class. When it is used as a singleton it affects the main application window.

-- Sets the title of the main window
Window.set_title("main window")

-- Creates a new window and sets its title
win = Window.open()
Window.set_title(win, "new window")
mouse_focus(window?) : bool
Returns true if the window has mouse focus. When the window has mouse focus it will hide the mouse pointer from the user and prevent it from leaving the window.
set_mouse_focus(window?, b)
Sets whether the window should have mouse focus or not.
set_focus(window?)
Gives the window the keyboard focus.
has_focus(window?) : bool
Returns true if the window has the keybaord focus.
set_title(window?, title)
Sets the title of the window.
show_cursor(window?) : bool
Returns true if mouse cursor is visible when window has focus.
set_show_cursor(window?, b)
Sets whether the mouse cursor should be shown when the window has mouse focus.
clip_cursor(window?) : bool
Returns true if mouse cursor should be confined within the window borders.
set_clip_cursor(window?, b)
Sets whether the mouse cursor should be confined within the window borders.
set_cursor(window?, cursor)
Sets what mouse_cursor resource to use as cursor when window has focus and show_cursor is set to true.
open( {x, y, width, height, parent, title} ) : Window
Creates a new window using the settings from the table. If parent is true, it is interpreted as an integer representation of a HWND pointer. The window is created as a child window to that window and all other parameters are ignored.
close(window)
Closes the specified window.
is_closing(window?) : Window
Returns true if the user has pressed the close button for the specified window.
minimize(window?)
Minimizes the window to the task bar.

2.4 World

Represents a game world.

update(world, [delta_time])
Updates the engine representation of the world. You should call this as part of the update() callback. The delta_time is the time step that the world should use when updating. If you don’t specify a time step, the application’s global time step will be used.
Instead of calling update() you can call update_animations() and then update_scene(). This allows the script to do some processing between the update of the animations and the update of the scene.
update_animations(world, [delta_time])
Updates the animations in the world.
update_scene(world, [delta_time])
Updates the physics and the scene graphs in the world.
time(world) : float
Returns the current time in the world. (The accumulated delta times.)
delta_time(world) : float
Returns the last delta time that the world was stepped with.

2.4.1 Units

spawn_unit(world, name, [position, rotation]) : Unit
Spawns a new instance of the game unit name at the specified position and rotation (should be a Quaternion). You can leave out position and rotation to spawn at (0,0,0) with default rotation.
destroy_unit(world, unit)
Destroys a unit that was previously created with spawn_unit().
num_units(world) : int
Returns the number of units in the world.
units(world) : table
Returns a table with all the units in the world.
link_unit(world, child, parent, node)
Links the root node of the unit child to the node with index node in the parent unit. The child unit will slave after the parent node’s movement after this call. Calling link_unit() automatically resets the transform of the child’s root node to the identity matrix, so it will be positioned at the exact location of the parent node. If you want to offset the child from the parent node, you should set the local position of the root node after the call to link_unit().
unlink_unit(world, child)
Unlinks the unit child from its parent node if it has any. When unlinked, the root node’s local position is set to its world position, so it will remain in its current position unless it is moved after it is unlinked.
update_unit(world, unit)
Forces an update of the unit’s scene graph after the main world update has been performed. This can be used to implement units that are dependent on other units positions in complicated ways that cannot be expressed just with link_unit(). It should be used sparingly.

2.4.2 Physics

physics_world(world) : PhysicsWorld
Returns the physics interface for the world.

2.4.3 Line Objects

create_line_object(world, disable_depth_test = false) : LineObject
Creates a new line object to be used for debug drawing. If disable_depth_test is specified and set to true, the lines will be drawn without depth test.
destroy_line_object(world, line_object)
Destroys a line object created by create_line_object().

2.4.4 Particles

create_particles(world, effect, position, [rotation]) : id
Creates a particle effect with the name effect at the specified position and with the specified rotation. Returns the id of the effect.
destroy_particles(world, id)
Destroys the particle effect with the specified id.
stop_spawning_particles(world, id)
Stops the particle effect with the specified id from spawning. The effect will be destroyed when all the particles have been played out.
move_particles(world, id, position, [rotation])
Moves the spawn point of particles with the specified id to the given position and rotation. Note that existing particles are not affected.
link_particles(world, id, unit, object, pose, orphaned_policy)
Links the particle effect id to the unit in the world. The effect is linked to the unit object with its coordinates in the local coordinate system of that object specified by pose.
Orphaned_policy specifies what happens to the effect if the unit dies. The possible values are:
"destroy"
The effect is destroyed when the unit dies.
"stop"
The effect stops spawning new particles but remains in place.
"unlink"
The effect is unlinked from the unit. It stays at its current position in the world and keeps spawning particles.
num_particles(world, [id], [cloud_index]) : int (development only)
Returns the number of active particles in the world. If an id is specified, returns the number of particles in that effect. If a cloud index is specified, returns the number of particles in that cloud.
find_particles_variable(world, effect, name) : int
Finds the index of a particle effect variable. effect should be the name of the effect whose variable you want to look up.
set_particles_variable(world, id, index, value)
Sets the particle effect variable with the specified index to the value (a Vector3) in the effect instance given by id.

2.4.5 GUI

create_screen_gui(world, [x=0, y=0], [“scale”, w_scale, h_scale], [“material”, material], [“immediate”], [“dock_right”], [“dock_top”]) : Gui
Creates a new screen space gui at pixel coordinates (x,y). (0,0) is the bottom left corner of the screen. Use Application.resolution() to find the size of the screen.
"scale", w_scale, h_scale
If specified, the coordinates in the gui will be scaled by the specified amount. With a scale of 2 an object that has size 100 pixels in the gui will be drawn with 200 pixels on the screen.
"material", material
Specifies the name of a .material file to use for this gui. A gui that contains textures and/or fonts needs a material files that contains the used textures and fonts.
You can have more than one material file for the gui, just add more “material” parameters. The different material files should not contain any materials with the same name.
"immediate"
If specified, the gui will be run in immediate mode. This means that everything you place on the gui will be drawn for just one frame. You have to redraw the objects you want to see every frame. If not in immediate mode, objects remain until you explicitly remove them.
"dock_right"
Specifies that the gui should dock to the right margin when the window is resized.
"dock_top"
Specifies that the gui should dock to the top when the window is resized.
create_world_gui(world, pose, width, height, [“material”, material], [“immediate”]) : Gui
Creates a new gui that lives in the 3D world. pose specifies the position of the Gui as a Matrix4x4. width and height specfies the internal width and height of the Gui in pixels, i.e. the internal coordinate system.
destroy_gui(world, gui)
Destroys a gui created with create_screen_gui() or create_world_gui().

2.4.6 Level

set_flow_callback_object(world, callback_object)
Assigns a Lua object that will receive events (method calls) from flow scripts executing in the specified world. The following events can occur:
spawn_unit(u)
A flow script has spawned the unit u.
unspawn_unit(u)
A flow script is about to unspawn the unit u.
load_level(world, name, [position, rotation]) : Level
Loads the named level into the world at the specified position and rotation (should be a Quaternion). If not supplied, the level will be loaded at the world origin with the default rotation.
load_level_with_object_sets(world, name, object_set_names, [position, rotation]) : Level
Same as load_level above, but does not spawn any objects that are members of object sets unless explicitly told to do so. The object_set_names parameter should be a Lua table listing the names of the object sets to spawn. An object will be spawned if it is a member of any of the named object sets, or if it is not a member of any object set. Object sets are defined using the level editor. You can get a list of all object set names within a level resource using the Level.object_set_names() function.
destroy_level(world, level)
Destroys the supplied level and all units that were spawned when the level was loaded. You are not required to call this function, since all levels will be destroyed when the world ends.
num_levels(world) : int
Returns the number of levels in the world.
levels(world) : table
Returns a table with all the levels in the world.

2.4.7 Level (deprecated)

load_level(world, name, [callback_object]) : Level
Deprecated. Use set_flow_callback_object(callback_object), followed by load_level(world, name, [position, rotation]) instead.
level(world) : Level
Deprecated. You can use levels(world)[1], but this creates a table that will have to be garbage collected. A better approach is to store the Level reference returned from load_level().

2.4.8 Sound

These functions provide a simple sound interface that is available on all platforms.

play_sound(world, name, [loop = false], [range = 50], [position = nil], [mixer_category = nil]) : id
Plays the sound resource name in the world and returns an id to it. If loop is set to true the sound will be played looping. range is the distance in meters that the sound is heard. position is the position of the sound source. If the position is not specified the sound is played as a 2D sound. mixer_category is the mixer category used for the sound, see set_mixer_volume().
stop_sound(world, id)
Stops the sound with the specified id.
set_listener(world, pose)
Sets the pose (as a Matrix4x4) of the listener.
set_sound_position(world, id, position)
Sets the position of the sound with the specified id.
link_sound(world, id, unit, node)
Links the position of the sound id to the position of the node in the unit.
set_sound_range(world, id, range)
Sets the range of the sound in meters.
set_sound_volume(world, id, volume)
Sets the volume of the sound in the range 0-1. For 2D sounds, this is the output volume of the sound. For 3D sound, this volume is multiplied by the distance attenuation caused by the distance between the sound and the listener.
set_mixer_volume(world, category, volume)
Sets the volume for a mixer category such as "music" or "fx". The volume should be a value in the range 0-1. The volume of the category is multiplied with the sound's own volume.
set_sound_environment(world, environment)
Sets the reverb environment for sounds. The environment parameter should be the name of a .sound_environment file.

2.4.9 Timpani

timpani_world(world) : TimpaniWorld_
Returns the Timpani sound world corresponding to this world.

2.4.10 Data

get_data(world, i1, i2, …, in) : object
Gets a script data object from the world. i1, i2, …, in is a sequence of indices that can be either integers or strings. See section 3.5 Storing Data in Units for a description of how to use script data.
set_data(world, i1, i2, … in, value)
Sets the script data at the location specified by the sequence of indices to the specified value.
has_data(world, i1, i2, …, in) : bool
Returns true if data has been stored at the specified path and false otherwise.

2.4.11 Debug helpers

clear_permanent_lines(world)
Clears any permanent lines that have been debug-drawn into the world.
debug_camera_pose(world) : Matrix4x4
Returns the pose of the last camera that was used to render the world.

2.4.12 Shading Environment

create_shading_environment(world, name) : ShadingEnvironment
Creates a new instance of the ShadingEnvironment named name.
destroy_shading_environment(world, shading_environment)
Destroys a shading environment previously created with create_shading_environment().
set_shading_environment(world, shading_environment, name)
Changes the shading environment instance to point to shading environment data named name.

2.5 Level

Represents a level from the level editor that has been loaded into the world.

object_set_names(level_name) : table
Returns a list of object set names defined inside the named level resource. The level resource must be loaded prior to calling this function.
trigger_level_loaded(level)
Triggers the level loaded event in the level flow script.
trigger_event(level, name)
Triggers the external event named name in the level flow script.
flow_variable(level, unit, name) : object_
Returns the value of the external flow variable with the specified name. Note that a variable shown as "My Unit" in the editor has the real name: "my_unit".
set_flow_variable(level, unit, name, value)
Sets the value of the specified external flow variable.
get_data(level, ...) : object
Accesses dynamic script data set in the level. The function is used in the same way as Unit.get_data.
has_data(level, ...) : bool
Accesses dynamic script data set in the level. The function is used in the same way as Unit.has_data.
set_data(level, ...) : object
Accesses dynamic script data set in the level. The function is used in the same way as Unit.set_data.
spline(level, name) : table
Returns the control points for the bezier spline with the specified name. If there is no such spline in the level, an empty table is returned.
navigation_mesh(level) : NavigationMesh
Returns the navigation mesh for the level.
units(level) : table
Returns a list of all the still remaining units that were spawned when the level was loaded. You should not keep this list around, since it will contain invalid references if a unit is destroyed after the list was obtained.
unit_index(level, unit) : int?
Returns the index of the unit in the level or nil if the unit is not in the level. You can turn the index back to a unit with unit_by_index(). This can be used to send unit identities over the network. Note that you can only use this function with units that are statically spawned in the level, not with units that are spawned by scripts or flow nodes.
unit_by_index(level, i) : Unit?
Converts an index back to a unit in the level, or nil the unit no longer exists (i.e., it has been unspawned).
is_point_inside_volume(level, name, position) : bool
Returns true if the specified point is inside the named volume.
random_point_inside_volume(level, name) : Vector3
Returns the world-space position of a random point inside the named volume.

2.6 Unit

Represents a game unit/entity. This is the main organizational object of the world.

node(unit, name) : int
Returns the index of the object node with the specified name.
has_node(unit, name) : bool
Returns true if the unit has an object node with the specified name.
num_scene_graph_items(unit) : int
Returns the number of scene graph nodes in the unit.
local_position(unit, i) : Vector3
local_rotation(unit, i) : Quaternion
local_pose(unit, i) : Matrix4x4
Returns the local position, rotation or pose of a node in the unit.
set_local_position(unit, i, v)
set_local_rotation(unit, i, q)
set_local_rotation_and_scale(unit, i, q, s)
set_local_pose(unit, i, m)
Sets the local position, rotation or pose of a node in the unit.
set_local_rotation() will clear the scale of the node to Vector3(1,1,1), if you want to preserve the scale you must use set_local_rotation_and_scale().
With set_local_rotation_and_scale() the scale is specified as a Vector3 specifying the ammount to scale the node in each principle axis. Note that you cannot set scale and rotation separately. The reason is that doing so could cause the scale of the underlying Matrix4x4 to drift if you repeatedly changed the rotation without resetting the scale.
teleport_local_position(unit, i, v)
teleport_local_rotation(unit, i, q)
teleport_local_rotation_and_scale(unit, i, q, s)
teleport_local_pose(unit, i, m)
As set_local_position(), but the node is teleported rather than moved to the specified location. This affects how keyframed physic objects behave. When objects are moved, they will collide with everything between the current position and the destination. When they are teleported, they will pop up at the destination without colliding with objects on the way there.
world_position(unit, i) : Vector3
world_rotation(unit, i) : Quaternion
world_pose(unit, i) : Matrix4x4
Returns the world position, rotation or pose of a node in the unit.
scene_graph_parent(unit, i) : [int]
Returns the index of the parent of a node in the unit’s scene graph or nil if the node is a root node.
scene_graph_link(unit, i, parent)
Links the scene graph node i to the scene graph node parent. Note that you can only link objects to earlier objects in the scene graph (i.e. objects with a lower index).
copy_scene_graph_local_from(dest_unit, src_unit)
Copy all local matrixes from the unit src_unit to the unit dest_unit, except for the root node. This can be used to support "instancing". An expensive unit is simulated and then its transforms are copied to simpler units.
camera(unit, camera) : Camera
Returns the camera named camera.
light(unit, light) : Light
Returns the light named light.
light(unit, n) : Light
Returns the n-th light in the unit.
num_lights(unit) : int
Returns the number of lights in the unit.
get_data(unit, i1, i2, …, in) : object
Gets a script data object from the unit. i1, i2, …, in is a sequence of indices that can be either integers or strings. See section 3.5 Storing Data in Units for a description of how to use script data.
set_data(unit, i1, i2, … in, value)
Sets the script data at the location specified by the sequence of indices to the specified value.
has_data(unit, i1, i2, …, in) : bool
Returns true if data has been stored at the specified path and false otherwise.
num_actors(unit) : int
Returns the number of actors in the unit.
find_actor(unit, name) : int?
Returns the index of the actor with the specified name, or nil if there is no such actor.
actor(unit, name) : Actor
Returns the physics actor with the specified name.
actor(unit, i) : Actor
Returns the i’th actor in the unit.
mover(unit) : Mover
Returns the unit’s physics mover if it has any.
create_actor(unit, name|i) : Actor
If the actor with the specified name/index in the unit has not been created, this function creates it.
destroy_actor(unit, name|i)
If the actor with the specified name/index has been created, this function destroys it.
create_joint(unit, name) : Joint
If the joint with the specified name has not been created, this function creates it.
destroy_joint(unit, name)
If the joint with the specified name has been created, this function destroys it.
create_custom_joint(unit, desc, params…) : Joint
Creates a physics joint in the unit based on a joint description. desc is the name of the joint to create.
The joint can be configured by the parameter list which is a sequence of strings followed by arguments. The following arguments are supported:
“actor_1”, actor
Specifies the first actor that should be joined by the constraint.
“actor_2”, actor
Specifies the second actor that should be joined by the constraint.
“anchor_1”, anchor
Specifies the first anchor point in local coordinates of the first actor as a Vector3.
“anchor_2”, anchor
Specifies the second anchor point in local coordinates of the second actor as a Vector3.
“global_anchor”
Specifies an anchor point in global coordinates that will be used for both the joined actors.
“global_axis”
Specifies a constraint axis in global coordinates that will be used for both the joined actors.
set_moving(unit, frames)
Marks the unit as moving for the following number of frames. This means that the world will update the unit.
When you call one of the set_local functions on a unit, the unit is automatically marked as moving, so in that case you do not need to mark the unit as moving. However, if you do some other special processing on the unit, you may need to call this function.

Note

Currently this function is not needed. Maybe it will never be. It is a tradeoff between speed and convenience if all operations that change a unit should automatically set it as moving, or if the gameplay programmer has to do that explicitly.

play_simple_animation(unit, from = nil, to = nil, loop = false, speed = 1, group = "")
Plays the simple animation track stored in the unit (the animation exported from MAX). The animation is played from the time from to the time to. You can use nil for from to start at the current time and nil for to to play to the end of the animation. If loop is set the animation will loop in the specified time interval. speed controls the playback speed.
If a group is specified, that simple animation group is played, otherwise the simple animation affects all bones in the unit.
stop_simple_animation(unit, group = "")
Stops a simple animation playing for the unit.
crossfade_animation(unit, animation, [layer = 0, blend_time = 0, loop = true]) : id
Crossfades in the animation on the specified unit in the specified animation layer over the specified blend time. animation is the name of the animation. layer is the number of the layer. blend_time is the time for the crossfade. And loop specified if the animation should loop when it reaches the end or just stay in the end pose.
You should only use these calls on units that have an animation blender but no animation state machine. (I. e., units with a script driven blender.)
Returns an id that can be used to control the animation.
is_crossfading_animation(unit) : bool
Returns true if the unit is currently crossfading any animation. You can use this to avoid overlaying too many crossfading animations on top of each other.
crossfade_animation_set_speed(unit, id, speed)
Sets the speed at which the crossfaded animation id will play with respect to the blender. A value of 1 means it uses the same time step as the blender. A value of 0 means it is frozen. You cannot use negative values for the speed.
crossfade_animation_set_time(unit, id, t)
Explicitly sets the time of the crossfaded animation id to t.
animation_event(unit, event)
Triggers the event named event in the unit’s animation state machine, possibly causing a transition to a different animation state. You should only call this on units that have an animation state machine.
animation_find_variable(unit, name) : int
Finds the index of a variable in the unit’s animation state machine.
animation_get_variable(unit, i) : float
Returns the value of an animation state machine variable.
animation_set_variable(unit, i, value)
Sets the value of an animation state machine variable.
animation_find_constraint_target(unit, name) : int
Finds the index of a constraint target in the unit’s animation state machine.
animation_get_constraint_target(unit, i) : Matrix4x4
Returns the value of an animation state machine constraint target.
animation_set_constraint_target(unit, i, value)
Sets the value of an animation state machine constraint target. The value can be a Matrix4x4, a Quaternion or a Vector3, depending on if you whether you want to set position and rotation or just one of them.
set_animation_root_mode(unit, mode)
Sets the way in which animations will update the root node of a unit. There are two possible values:
"ignore"
Root animations are ignored, they will not affect the unit’s root node. This is the default mode.
If you use this mode you use animation_wanted_root_pose() to extract the position the animation wanted to move the root to and apply that position programmatically.
"delta_transform"
The delta changes to the root position and rotation that occur in the animation will be applied to the root node of the Unit. I.e., the unit’s root will be moved by the animation.
"delta_position"
As delta_transform, but only position updates are transferred to the root node.
"delta_rotation"
As delta_transform, but only rotation updates are transferred to the root node.
animation_root_mode(unit) : string
Returns the current animation root mode: "ignore", "delta_transform", "delta_position" or "delta_rotation".
animation_wanted_root_pose (unit) : Matrix4x4
In “ignore” mode, this function returns the pose that the animation would have wanted to move the root node to. You can use this to apply the animation movement manually from the script or pass it through other systems (such as the unit’s mover, etc).
disable_animation_state_machine(unit)
Disables the unit’s animation state machine, so that you can control its blender directly with the crossfade operations. This is typically only used by tools and for debugging purposes.
enable_animation_state_machine(unit)
Enables a state machine that has been disabled.
set_animation_state_machine(unit, machine)
Sets the animation state machine of the unit to something other than the default. machine should be the name of the state machine resource you want to use.
set_animation_logging(unit, enabled) (DEVELOPMENT)
If set to true, animation state machine events will be logged to the command console. This method is only available in development mode.
animation_get_state(unit) : int, int, ...
Returns the current animation state of the unit as a tuple of data. You can restore this state later with a call to set_state(). Note that the state only includes the state of the state machine, not the play head offsets, animation variables or constraint targets.
animation_set_state(unit, int, int, ...)
Restores a state fetched with animation_get_state().
bones(unit) : table
Returns a list of the bones in the state machine.
disable_physics(unit)
Disables all physics for the unit. This is typically only used by tools and for debugging purposes.
enable_physics(unit)
Re-enables physics that has been disabled.
debug_name(unit) : string
Returns the name of the unit. This should only be used to print the name for debugging purposes. In release versions the real name will not be available and this function will return a hexadecimal string instead of the name.
name_hash(unit) : string
Returns a hash representation of the unit name. The representation will not be meaningful, but you can pass it as an argument to World.spawn_unit() in order to create another unit of the same type.
set_visibility(unit, group, visibility)
Sets the visibility of all objects included in visibility group. Visibility groups are declared in the unit file.
set_unit_visibility(unit, visibility)
Sets the visibility of all meshes in the unit to the specified visibility.
alive(unit) : bool
Returns false if the unit has been deleted. Units are always held as weak references by the script and the script can check if the reference is still valid by calling Unit.alive on the unit. Note: only units are held as weak references, the script cannot call alive() on any other objects to detect if they have been deleted.
Calling any other function than alive() on a unit that has been deleted will result in a script error.
box(unit) : Matrix4x4, Vector3
Returns an object-oriented box that encloses all the meshes in the unit. The box is represented by Matrix4x4 that describes the position and orientation of the box center and a Vector3 that describes the radius of the box (i.e. its half-extent in the x-, y- and z-directions).
flow_event(unit, name)
Triggers the external event with the specified name in the unit’s flow graph.
flow_variable(unit, name) : object_
Returns the value of the flow variable with the specified name. Note that a variable shown as "My Unit" in the editor has the real name: "my_unit".
set_flow_variable(unit, name, value)
Sets the value of the specified external flow variable.
mesh(unit, mesh) : Mesh
Returns the Mesh named mesh.
is_a(unit, name) : string?
Returns name if the unit is of the type name, otherwise returns nil.
set_material_variation(unit, material_variation)
Assigns all meshes to use the materials declared in the material resource named material_variation.

2.7 Light

Describes a game light.

node(light) : int
Returns the light’s node index in the unit scene graph.
local_position(light) : Vector3
local_rotation(light) : Quaternion
local_pose(light) : Matrix4x4
Returns the light’s local position, rotation or pose.
world_position(light) : Vector3
world_rotation(light) : Quaternion
world_pose(light) : Matrix4x4
Returns the light’s world position, rotation or pose.
set_local_position(light, unit, v)
set_local_rotation(light, unit, q)
set_local_pose(light, unit, m)
Sets the light's local position, orientation or pose. When changing the light position you must pass the unit that the light belongs to, so that it knows that it needs updating.
falloff_start(Light) : float
Returns the distance where the light starts to falloff.
set_falloff_start(Light, float)
Sets the distance where the light start to falloff.
falloff_end(Light) : float
Returns the distance where the light has reached zero intensity.
set_falloff_end(Light, float)
Sets the distance where the light should reach zero intensity.
color(Light) : Vector3
Returns the color of the light.
set_color (Light, Vector3)
Sets the color of the light.
set_falloff_exponent(Light, float)
Set the light falloff exponent. Defaults to 1, linear falloff.
set_spot_angle_start(Light, float)
(Only valid for spot lights) Set the cone angle where the light starts to falloff. Angle is in radians.
set_spot_angle_end(Light, float)
(Only valid for spot lights) Set the cone angle where the light has reached zero intensity. Angle is in radians.
set_cats_shadows(Light, bool)
Enable/disables shadow casting from the light.
set_type(Light, type)
Set type of light source, valid input values for type are: “omni”, “spot”, “directional”.

2.8 Camera

Describes a game camera.

node(camera) : int
Returns the camera’s node index in the unit scene graph.
local_position(camera) : Vector3
local_rotation(camera) : Quaternion
local_pose(camera) : Matrix4x4
Returns the camera’s local position, rotation or pose.
world_position(camera) : Vector3
world_rotation(camera) : Quaternion
world_pose(camera) : Matrix4x4
Returns the camera’s world position, rotation or pose.
set_local_position(camera, unit, v)
set_local_rotation(camera, unit, q)
set_local_pose(camera, unit, m)
Sets the camera's local position, orientation or pose. When changing the camera position you must pass the unit that the camera belongs to, so that it knows that it needs updating.
near_range(camera) : float
Returns the camera’s near range.
set_near_range(camera, float)
Sets the camera’s near range.
far_range(camera) : float
Returns the camera’s far range.
set_far_range(camera, float)
Sets the camera’s far range.
vertical_fov(camera) : float
Returns the camera’s vertical field of view angle.
set_vertical_fov(camera, angle)
Sets the camera’s vertical field of view angle.
projection_type(camera) : int
Returns the cameras projection type. The return value will be one of the values that can be specified to set_projection_type().
set_projection_type(camera, type)
Sets the projection type. You should specify one of the values:
Camera.PERSPECTIVE
Perspective projection is used.
Camera.ORTHOGRAPHIC
Orthographic projection is used
set_orthographic_view(camera, min_x, max_x, min_z, max_z)
Sets the minimum and maximum coordinates for the orthographic view.
screen_to_world(camera, p) : Vector3
Converts a point p from screen coordinates to world coordinates. In screen coordinates, (x,z) are the pixel positions of the point on the screen and the y-coordinate indicates the depth into the screen where the point lies (the distance from the camera plane) in meters.
world_to_screen(camera, p) : Vector3
Performs the inverse operation of screen_to_world(), converts from world coordinates to screen coordinates.
inside_frustum(camera, p) : float
Tests whether the Vector3 p is inside the camera's frustum. A positive return value means the point is inside the frustum. The value specifies how many meters inside the frustum the point is. A negative value means the point is outside the frustum. The value specifies how far outside the frustum the point is.
set_data(unit, i1, i2, … in, value)
The function is used in the same way as Unit.set_data.
get_data(unit, i1, i2, …, in) : object
The function is used in the same way as Unit.get_data.
has_data(unit, i1, i2, …, in) : bool
The function is used in the same way as Unit.has_data.

2.9 Viewport

Describes a viewport.

material(viewport, material_name) : Material
Returns the Material named material_name associated with the viewport.
set_rect(viewport, x, y, width, height) : void
Sets position and dimension of viewport. x and y represents the upper left corner. Input range is in normalized coordinates.
set_data(unit, i1, i2, … in, value)
The function is used in the same way as Unit.set_data.
get_data(unit, i1, i2, …, in) : object
The function is used in the same way as Unit.get_data.
has_data(unit, i1, i2, …, in) : bool
The function is used in the same way as Unit.has_data.

2.10 Material

Describes a material.

set_scalar(material, variable, float) : void
Sets the value of variable in the material material to the value float.
set_vector2(material, variable, vector2) : void
Set the value of variable in the material material to the value vector2.
set_vector3(material, variable, vector3) : void
Set the value of variable in the material material to the value vector3.

2.11 LineObject

A LineObject is used to draw debug lines in the game world. It is created with World.create_line_object(). You add lines to a line object using the add_* functions and queue it for rendering with dispatch(). The lines in a line object are not cleared automatically between frames, so any lines you add will persist on screen as long as you continue to dispatch the line object. To clear the lines of a line object call reset().

To draw lines that follow a moving object, you should call reset() every frame to clear out the old lines and then add the new lines.

reset(line_object)
Clears the lines of the line object.
dispatch(world, line_object)
Queues the line object for rendering in the specified world. The world should be the same world that created the line object.
add_line(line_object, color, from, to)
Adds a line between (from, to) to the line_object. The line will be given the specified color.
The color of a line object is specified as an ARGB value in a Quaternion with each component ranging from 0-255. You can create such a value with Color(), passing three arguments for an RGB value and four for an ARGB value. So to draw a bright yellow line you would use the color Color(255, 255, 0).
add_circle(line_object, color, center, radius, normal, [segments=20])
Adds a circle at center with specified radius and normal vector. If segments is given, it specifies how many individual line segments the circle will be composed of.
add_sphere(line_object, color, center, radius, [segments = 20, parts = 2])
Adds a sphere at center with specified radius. segments specifies the number of line segments in the circles making up the sphere and parts specifies the number of circles.
add_half_sphere(line_object, color, center, radius, normal, [segments = 20, parts = 2])
Adds a half-sphere with specified normal from the circular plane.
add_box(line_object, color, pose, extents)
Adds an oriented box. The pose is a Matrix4x4 specifying the position and orientation of the box. Extents is a Vector3 specifying the size of the box in the x-, y- and z-directions.
add_capsule(line_object, color, from, to, radius, [segments = 20, circles = 4, bars = 10])
Adds a capsule as a line between (from, to) fattened to radius. segments, circles and bars specify how detailed to make the capsule.
add_cone(line_object, color, from, to, radius, [segments = 20, bars = 10])
Adds a cone with the tip in from and the base in to. radius is the radius of the base.

2.12 Mesh

Describes a mesh.

node(mesh) : int
Returns the mesh’s node index in the unit scene graph.
local_position(mesh) : Vector3
local_rotation(mesh) : Quaternion
local_pose(mesh) : Matrix4x4
Returns the mesh’s local position, rotation or pose.
world_position(mesh) : Vector3
world_rotation(mesh) : Quaternion
world_pose(mesh) : Matrix4x4
Returns the mesh’s world position, rotation or pose.
set_local_position(mesh, unit, v)
set_local_rotation(mesh, unit, q)
set_local_pose(mesh, unit, m)
Sets the mesh local position, orientation or pose. When changing the mesh position you must pass the unit that the mesh belongs to, so that it knows that it needs updating.
material(Unit, material) : Material
Returns the material named material.

2.13 ShadingEnvironment

Shading Environments specify a set of variables used for lighting and post processing when rendering a World. Typically it includes data such as sun direction, sun color, shadow settings etc. The contents of a shading environment is defined from shading_environment_template files and is setup on a per project basis. The Lighting Editor is used to author shading environments.

update(ShadingEnvironment, [[setting, blend]])
Updates the shading environment settings blend.

3. Physics

3.1 PhysicsWorld

Represents a physics world where actors live. In the Bitsquid engine, exactly one PhysicsWorld is associated with each game World.

set_kinematic(world, actor)
Makes the actor kinematic, i.e. keyframed.
clear_kinematic(world, actor)
Makes the actor non-kinematic, i.e., not keyframed.
make_raycast(world, callback, params…) : Raycast
Creates a raycast object that can be used to make raycasts. Doing a raycast is a two step process. First you use make_raycast() to create the raycast object. Then you call cast() on that object to perform the actual raycast. The raycast object keeps an internal cache that makes it more efficient if you use it to make many similar raycasts. If you just want a one-off raycast, you can call make_raycast():cast() and then forget about the raycast object.
The callback is the function that will be called with the result of the raycast in the next few frames. In the Bitsquid engine all raycasts are asynchronous operations.

Note

We may change this in the future if there is enough pressure… But asynchronous raycasts are much better from an engine efficiency standpoint.

params is a list of parameters for the raycast. The possible parameters are:
“closest” (default)
Specifies that the raycast should return a single hit, the closest to the origin of the raycast.
“any”
Specifies that this raycast should just return a true or false value that specifies whether it has hit anything or not.
“all”
Specifies that the raycast should return all hits along the ray path.
“types”, “both” (default)
Specifies that the ray should test against both static and dynamic objects.
“types”, “statics”
Specifies that the ray should only test against static objects.
“types”, “dynamics”
Specifies that the ray should only test against dynamic objects.
“collision_filter”, name
Specifies the name of the collision filter that the ray should use to determine which objects it collides with. By default, the ray collides with all objects in the scene.
The Raycast object returned by make_raycast() is a full userdata object that will be automatically garbage collected when the script no longer refers to it.
Raycast.cast(raycast, from, dir, [length])
Call this on the raycast returned by make_raycast to actually perform the raycast.
from should be a Vector3 containing the origin of the ray. dir should be a unit vector specifying the direction of the raycast. If length is given, it specifies the length of the raycast, otherwise the ray is assumed to be infinitely long.
The result of the raycast is returned with a call to the callback function specified in make_raycast. The callback will use one of the following forms:
callback(any_hit)
For an “any” cast the callback is called with just true or false depending on whether the ray hit anything or not.
callback(any_hit, [position, distance, normal, actor])
For a “closest” hit, the first argument will tell if there was a hit or not, as before. If there was a hit, the callback will also be called with the position of the hit, the distance from the origin, the normal of the surface that was hit and the actor that was hit.
callback(hits)
For an “all” raycast the callback will be called with a table containing all the hits. If there were no hits, the table will be empty.
Each entry in the table is in turn a table with four elements: {position, distance, normal, actor}.
overlap(world, callback, params…)
Performs an overlap test in the physics world. I. e., it finds all the actors in the world that are in a particular shape. (For example, all actors in a 20 meter sphere around the player.)
All overlap calls are performed asynchronously and returned to the gameplay programmer a couple of frames after the request has been made through a call to the specified callback function.
The parameters specify the shape of the overlap. Possible values are:
“shape”, “sphere” (default)
Specifies that the shape should be a sphere.
“shape”, “aabb”
Specifies that the shape should be an axis-aligned bounding box.
“shape”, “oobb”
Specifies that the shape should be an object-oriented bounding box.
“shape”, “capsule”
Specifies that the shape should be a capsule.
“position”, v (default is 0,0,0)
Specifies the position of the shape as a Vector3.
“rotation”, q (default is no rotation)
Specifies the rotation of the shape as a Quaternion.
“pose”, m
Specifies the pose of the shape with a Matrix4x4.
“size”, size
Specifies the size of the shape. The value can either be a Vector3 specifying the size in the x, y and z-directions or a float specifying the size in all three directions with a single value.
“types”, “both” (default)
Specifies that the overlap function should find both static and dynamic actors.
“types”, “dynamics”
Specifies that the overlap function should only find dynamic actors.
“types”, “statics”
Specifies that the overlap function should only find static actors.
“collision_filter”, filter
Specifies the name of a collision filter to use for the overlap test. If no collision filter is specified, a filter that matches all actors in the scene will be used.
When the overlap test completes, the callback function will be called as:
callback(actors)
Where actors is a table containing all the actors that were found in the overlap test.
spawn_sphere(world, position, radius, actor, shape, material) : Actor
Most physics objects in a scene come from the units through the physics settings specified in the .physics file. But sometimes it can be useful to spawn a completely improvised physics actor. This function spawns an improvised sphere.
The sphere will be spawned at position with radius. The actor, shape and material parameters are the names of the actor template, shape template and material template that should be used when constructing the sphere.
spawn_box(world, position, size, actor, shape, material) : Actor
Spawns an improvised box at position, with x, y and z size specified by the Vector3 size.
spawn_plane(world, position, normal) : Actor
Spawns a static plane with specified position and normal.
destroy(world, actor)
Destroys a dynamic actor that was created with spawn_sphere() or spawn_box(). You should not use it to destroy actors belonging to units.

3.2 Actor

Interface to a physics actor. An actor is a rigid body living in the physics world.

collision_disabled(actor) : bool
Returns true if collision has been disabled for this actor.
disable_collision(actor)
Disables collision for the actor.
enable_collision(actor)
Enables collision for the actor.
gravity_disabled(actor) : bool
Returns true if gravity has been disabled for the actor.
disable_gravity(actor)
Disables gravity for the actor
enable_gravity(actor)
Enables gravity for the actor
is_static(actor) : bool
Returns true if the actor is static.
is_dynamic(actor) : bool
Returns true if the actor is non-static, i.e. either kinematic/keyframed or physical (physics driven).
is_kinematic(actor) : bool
Returns true if the actor is kinematic (keyframed).
is_physical(actor) : bool
Returns true if the actor is physical (physics driven).
linear_damping(actor) : float
Returns the linear damping of the actor.
set_linear_damping(actor, f)
Sets the linear damping of the actor to f.
angular_damping(actor) : float
Returns the angular damping of the actor.
set_angular_damping(actor, f)
Sets the angular damping of the actor.
velocity(actor) : Vector3
Returns the velocity of the actor.
set_velocity(actor, v)
Sets the velocity of the actor. (This call, and all the other calls that change velocity or add forces, only affect physical actors.)
angular_velocity(actor) : Vector3
Returns the angular velocity of the actor.
set_angular_velocity(actor, v)
Sets the angular velocity of the actor to v.
point_velocity(actor, p)
Returns the velocity at a point p on the surface of the actor. The point is specified in global coordinates.
add_impulse(actor, impulse)
Adds a momentary impulse (mass * velocity) to the actor.
add_impulse_at(actor, impulse, pos)
As add_impulse(), but applies the impulse at a particular position in the actor, causing rotation.
add_velocity(actor, delta_velocity)
Adds a delta velocity to the actor’s velocity.
add_velocity_at(actor, delta_velocity, pos)
As above, but applies it at position pos, causing rotation.
add_torque_impulse(actor, impulse)
Adds a rotational impulse to the actor.
add_angular_velocity(actor, delta_velocity)
Adds a delta angular velocity.
push(actor, velocity, mass)
Pushes the actor as if it was hit by an object with velocity and mass. Use this to simulate collision with objects that are not physics simulated, such as bullets.
push_at(actor, velocity, mass, pos)
As push, but applies the force at a particular position, causing rotation.
is_sleeping(actor) : bool
Returns true if the actor is sleeping.
wake_up(actor)
Wakes the actor up.
unit(actor) : Unit
Returns the unit that owns this actor. Note that some actors may not have an owning unit.
set_collision_filter(filter)
Changes the collision filter used by the actor.

3.3 Mover

Provides an interface to a physics mover / character controller.

move(mover, delta_position)
Attempts to move the mover by the specified delta position. The mover will slide against physical objects.
position(mover) : Vector3
Returns the current position of the mover.
set_position(mover, p)
Teleports the mover to the specified position. Rember to call Unit.set_moving() to update the unit position.
unit(mover) : Unit
Returns the unit that owns the mover.
collides_down(mover) : bool
Returns true if the mover is standing (i.e. if it collides in the downward direction).
collides_up(mover) : bool
Returns true if the mover is hitting its head (i.e. colliding in the upward direction).
collides_sides(mover): bool
Returns true if the mover is colliding horizontally.
standing_frames() : int
Returns the number of frames the mover has been standing on a surface.
flying_frames() : int
Returns the number of frames the mover has been flying.
set_collision_filter(filter)
Changes the collision filter used by the mover.

4. Sound

4.1 TimpaniWorld

Represents a world managed by the Timpani sound system.

trigger_event(timpani_world, event_name) : int
Triggers a timpani event, the event will be played as a 2D sound. Returns an id for the playing event.
trigger_event(timpani_world, event_name, pose) : int
Triggers a timpani event played at the specified Matrix4x4 pose.
trigger_event(timpani_world, event_name, position, [rotation]) : int
Triggers a timpani event played at the specifeid position.
trigger_event(timpani_world, event_name, unit, [object]) : int
Triggers a timpani event linked to the specified unit (and object if specified).
stop(timpani_world, playing_event_id)
Stops an event created by trigger_event.
stop_all(timpani_world)
Stops all sounds playing in the world.
set_listener(timpani_world, index, pose/position)
Sets the timpani listener at the specified index to the specified pose or position. Currently, only one listener is allowed, so you can only set the listener at index 0.
set_listeners(timpani_world, index_1, index_2, ...)
Sets the listener indices that should be used for this world. Currently, you can only use the listener at index 0.
set_environment(timpani_world, name)
Sets the reverb environment.
@note Currently separate environments per world are not supported, so if you call this function, you will set the environments for all worlds.

4.1.1 Tool Interface

trigger_sound(timpani_world, sound_id) : int
trigger_sound(timpani_world, sound_id, pose) : int
trigger_sound(timpani_world, sound_id, position, [rotation]) : int
trigger_sound(timpani_world, sound_id, unit, [object]) : int
As trigger_event, but triggers a sound based on its editor ID. Only used by the sound editor.

4.2 Timpani (singleton)

Represents the Timpani sound system.

Timpani.update_banks()
Call this when you have loaded or unloaded banks to make timpani update its bank list.
Timpani.set_bus_volume(name, volume)
Sets the volume (in dB) of the specified Timpani bus.
Typically you only specify negative volumes to this functions. 0 dB means full strength. -10 dB means lowered by 10 dB.
Note that bus volumes stack, so if there are volumes set for parent buses, the volumes will be added to determine the final output volume.

4.2.1 Tool interface

Timpani.load_master(master)
Loads a timpani master file. Normally you specify the Timpani master file in your .ini settings. This function is mostly for tools that are not able to do that.
Note that any Worlds created before load_master() will still point to the old timpani master and are likely to cause errors. You should have no active worlds when calling load_master().
Timpani.load_bank(bank_name)
Directly loads a timpani bank. Normally, you should never do this, you should only load the banks through the resource packages. This function is just called by tools that use autoloading and need to load banks directly.

5. Input

5.1 InputController (singleton)

Represents the interface to an input controller. There are a number of input controllers exposed as singletons: Mouse, Keyboard, Pad1, Pad2, Pad3, up to the number of pads supported. So to check if the keyboard button k is pressed, you can use:

Keyboard.button(Keyboard.button_index("k")).

5.1.1 General

type() : string
Returns a string describing the type of the controller.
name() : string
Returns a string with the name of the controller.
active() : bool
Returns true if the controller is connected and working.
connected() : bool
Returns true if the controller was attached this frame.
disconnected() : bool
Returns true if the controller was removed this frame.

5.1.2 Buttons

num_buttons() : int
Returns the number of buttons on the controller.
button(i) : float
Returns the current value of the i’th button, as a value between 0 and 1.
pressed(i) : bool
Returns true if the button was pressed this frame.
any_pressed() : bool
Returns true if any button was pressed this frame.
released(i) : bool
Returns true if the button was released this frame.
any_released() : bool
Returns true if any button was released this frame.
button_name(i) : string
Returns the name of the i’th button.
button_locale_name(i) : string
For keyboards this returns the name of the i’th button with respect to the keyboard type (locale). This string may be empty if there is no name for the key. Shift and alt for example will be empty strings.
button_index(name) : int
Returns the index of the button with the specified name, or nil if no such button is found.
down_threshold() : float
Returns the current down threshold. Default is 0.5.
set_down_threshold()
Set the threshold([0,1]) of when a button is considered 'down'. Default is 0.5. Larger values will result in the user has to press the button harder in order indicate it as 'down'.

5.1.3 Axes

num_axes() : int
Returns the number of axes on the controller.
axis(i) : Vector3
Returns the value of the i’th axis on the controller.
axis_name(i) : string
Returns the name of the i’th axis.
axis_index(name) : int
Returns the index of the axis with the specified name or nil if no such axis is found.

5.1.4 Rumble

The engine has a built-in "rumble effect system" that lets you play rumble pulses with specific strength and duration. When you use the rumble effect system you only need to call rumble_effect() once to start a rumble effect. The engine will take care of modulating the rumble and fade it out at the end of its duration. If there are multiple rumble effects in play, their effects are added.

A rumble effect in the rumble effect system works a lot like a synthesizer note, it is a sine wave played within an ADSR-envelope (see http://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope).

If you need more detailed control over the rumbling you can use the set_rumble() method instead. That method allows you to directly set the rumble strength of each motor. Note, that if you use that method you are responsible for fading out rumbles, etc.

If you use both set_rumble() and rumble_effect() the values are added.

set_rumble_enabled(enabled)
Disables (or reenables) rumbling for the controller.
num_rumble_motors() : int
Returns the number of rumble motors in the controller.
set_rumble(i, value)
Sets the strength of the rumbling in the i'th motor as a value between 0.0 and 1.0. The rumbling remains at this strength until you call set_rumble() again to set a different value.
rumble_effect(i, params) : id
Creates a rumble effect on the i'th motor. parameters is a table that specifies the properties of the effect. Note that you only need to specify the parameters that you want to change from their default values.
frequency = 0
The frequency of the sine wave. If you use a frequency of 0, the sine wave will not be used and the strength of the rumble will only be affected by the ADSR envelope.
Note that since the motors on most controllers cannot change speed instantly it does not make sense to use frequencies above 6 Hz or so.
period = #inf
The period of the sine wave. You can specify this instead of the frequency if you want. Note that period = 1 / frequency.
offset = 0
The offset of the sine wave. Normally the sine wave is offset so that it starts in its lowest position. You can specify a value between 0 and 1 to start the oscillation at a different position. For example, with a value of 0.5 the sine wave will start in its highest position.
attack_level = 1
The strength of the rumble at the maximum attack position.
sustain_level = 1
The strength of the rumble in the sustain part of the envelope.
attack = 0
The time for the attack part of the envelope.
decay = 0
The time for the decay part of the envelope.
sustain = 0
The time for the sustain part of the envelope.
release = 0
The time for the release part of the envelope.
stop_rumble_effect(i, id)
Stops the rumble effect with the specified id.
stop_all_rumble_effects(i)
Stops all rumble effects on the i'th motor. Note that this doesn't zero any rumble value set with set_rumble(). You need to call set_rumble(i,0) for that.
rumble_motor_name(i) : string
Returns the name of the i’th rumble motor.
rumble_motor_index(name) : int
Returns the index of the rumble motor with the specified name or nil if no such rumble motor is found.

6. Utility Libraries

6.1 ResourcePackage

Interface to a package/group of resources.

load(package)
Starts loading the resources in the background.
has_loaded(package)
Returns true if the background thread has completed loading the package.
flush(package)
Brings the resources on the package online. If the package has not completed loading, this call will stall until the package has been loaded.
unload(package)
Unloads the resources in the package. You must make sure that the resources are no longer in use before unloading them.

6.2 Profiler (singleton)

Interface to the built-in profiler.

start(name)
Starts a profiling scope with the name. The scope will appear in the in-game profiler. Use this to profile expensive script functions.
stop()
Stops the last started profile scope.

Note

Calls to start() and stop() must be balanced, i. e., every start must be followed by a stop. Otherwise you will mess up the nesting of the profile scopes.

record_statistics(name, value)
Records statistics data (a float or a vector3) for the in-game graph drawer.

6.3 Script (singleton)

Interface to script manipulation functions

temp_count() : int, int, int
Returns the number of temporary vectors, quaternions and matrices currently used.
set_temp_count(v, q, m)
Sets the number of temporary vectors, quaternions and matrices.
If you have a function that uses a lot of temporary objects you can use this call to reset the temporary buffers and free those objects. Be aware though, that the function has not exported any of those objects to variables that live beyond the length of the function call. If so, those variables may be assigned new values, since the system considers them “freed”.
type_name(o) : string
Returns the type name of the object o.
callstack() : string
Returns the current script call stack.

6.4 Localizer

Interface to localization functionality.

Use Application.set_resource_property_preference_order() to set the language you want to use, for example: Application.set_resource_property_preference_order("fr").

Localizer(strings)
Creates a new localizer using the .strings resource strings.
lookup(localizer, key) : s
Looks up the key in the localizer. If a string with the specified key is found in the database that string is returned, otherwise the function returns nil.

7. AI

7.1 Broadphase (full userdata)

A data structure that allows you to quickly search for units in a game level. The units inserted into the broadphase gets sorted into a grid for quick access.

Broadphase(cell_radius, num_objects)
Creates a new broadphase data structure.
cell_radius
is the radius of the grid cells. For maximum efficiency you should set the cell radius to the radius of the largest query you are going to make to the broadphase. (The broadphase will not allow you to make queries larger than the cell radius, also, you cannot insert objects bigger than the cell radius.)
num_objects
is the expected number of objects that will be inserted into the broadphase. This will determine how many grid cells are created.
add(broadphase, unit, pos, radius) : int
Adds a new unit to the broadphase at the specified position and with the specified radius. Returns an item index to be used for manipulating the item.
move(broadphase, item, pos)
Moves the item to the specified position. The item should be a value returned by add().
remove(broadphase, item)
Removes the item from the broadphase.
query(broadphase, pos, radius, table)
Finds all the units whose spheres intersects a sphere at pos with radius and returns them by inserting them into the supplied lua table.

7.2 NavigationMesh

A navigation mesh in a level.

find_polygon(mesh, p) : int?
Finds the polygon in the mesh that the Vector3 p is closest to and returns its index. If the point is outside the navmesh, the function will return nil.
constrain_to_polygon(mesh, p, poly) : Vector3, bool
Constrains the Vector3 p to the polygon with index poly and returns the result. Also returns a bool specifying whether the character was outside the polygon and needed to be moved.
update_polygon(mesh, p, poly) : Vector3, Vector3, int, bool
Used to move a character on the navigation mesh. Given a new position p and the index poly of the polygon the character was on the last frame, this function will compute which polygon the character is on now. It will also constrain the character's position to the navmesh.
The return values are:
A typical use case might be:
self.position = self.position + move_vector
self.position, self.normal, self.poly = NavigationMesh.update_polygon(self.mesh, self.position, self.poly)
polygon_vertices(mesh, poly) : int, int, int, ...
Returns the vertex indices of the polygon with index poly.
vertex(mesh, v) : Vector3
Returns the position of the vertex with index v.
polygon_neighbors(mesh, poly) : int?, int?, int?, ...
Returns the indices of the polygon neighbors to the polygon with index poly. If an edge of the polygon doesn't have a neighbor the corresponding index will be returned as nil.
search(mesh, start, end, focus = 1.1, max_search_nodes = 100) : table
Does an A* search to find the closest path from polygon start to polygon end. The resulting path is returned as a table of nodes.
focus specifies how aggressive the search should be. A value > 1 means a more aggressive search that expands fewer nodes but may not find the absolute shortest path. For example, with a focus of 1.2 the returned path is allowed to be 1.2 times longer than the shortest possible path.
max_search_nodes specifies the maximum number of graph nodes that will be looked at in the search. It is a way of bounding the run time of the search. If you specify a low value, you may not always be able to find a path between two nodes, even when such a path exists.
funnel(mesh, path) : table, table
Given a polygon path, such as returned by search(), returns two lists with the left and right edge vertices for that path. This can be used to implement the funnel algorithm (see http://digestingduck.blogspot.com/2010/03/simple-stupid-funnel-algorithm.html ).
Note that vertices can be repeated in the returned lists (when the polygons form a fan). The returned lists will always contain #path - 1 items. I.e., one item for each polygon edge crossed.

8. GUI

8.1 Color (temporary)

Colors are internally represented as quaternions (i.e. a value with four floats). This means that they are temporary objects that cannot be stored from one frame to another.

Color(red, green, blue)
Color(alpha, red, green, blue)
Specifies a color for use with gui objects. The parameters should range from 0 to 255.

8.2 Vector2 (temporary)

An object for specifying 2D-positions for the Gui.

Internally the Vector2 is represented as a Vector3, so it is a temporary object that cannot be stored from one frame to another.

Vector2(x,y)
Creates a vector with two components for specifying 2D positions and sizes.

8.3 Rotation2D (temporary)

Returns a Matrix4x4 that can be used with the 3D functions in the gui to create a rotated object.

Rotation2D(pos, angle, [pivot]) : Matrix4x4
Creates a matrix that can be used to draw a rotated 2D object with the 3D functions.
pos is a Vector2 specifying the position of the object.
angle is the angle the object should be rotated (clockwise in radians).
If a pivot is specified it specifies the Vector2 position that the object should be rotated around. If no pivot is specified the object is rotated around pos.
Example:

local tm = Rotation2D(Vector2(100,100), angle, Vector2(250,125))
Gui.rect_3d(self.gui, tm, Vector2(0,0), 0, Vector2(300, 50), Color(255,0,0))
	

8.4 Gui

Represents a gui created by World.create_screen_gui() or World.create_world_gui(). Depending on the creation parameters the Gui can either be in immediate mode (which means that you draw all the GUI objects that you want visible every frame) or in retained mode (which means that you use a create/update/destroy pattern to manage gui objects).

Gui.resolution()
Returns the width and height of pixels that can be used in a screen Gui. This is normally the same as Application.resolution(). The two values only differ if the screen has non-square pixels. In that case, the Gui pixels are stretched horizontally to ensure that a Gui object with size (100,100) is still a perfect square. This means that there will be fewer or more Gui pixels horizontally than actual screen pixels.
move(gui, [pose], [x, y])
Moves the gui to a different world pose (for a world gui) or a different (x,y) location (for a screen gui).
rect(gui, pos, size, [color]) : id
Creates (or in immediate mode – draws) a rectangle on the gui. pos is a Vector3 that specifies the position. (x,y) are the x- and y- coordinates and z is an integer specifying the draw layer. Objects with a high value of z appear in front of other objects. size is a Vector2 specifying the dimensions.
The function returns an id identifying this rectangle. (This id is only useful in retained mode.)
triangle(gui, p1, p2, p3, layer, [color])
Creates (or draws) a triangle on the gui. (p1, p2, p3) are the Vector3 positions of the triangle corners.
bitmap(gui, material, pos, size, [color]) : id
Creates (or draws) a bitmap with the specified material.
bitmap_uv(gui, material, uv_00, uv_11, pos, size, [color]) : id
Creates (or draws) a bitmap using the specified UV-coordinates for the top left and bottom right corner.
text(gui, text, font, font_size, material, pos, [color]) : id
Draws a single line of text. text is the string to draw. font specifies the name of the font. material is the material to use. font_size specifies the size of the font in pixels. It should match the font size used to generate the font for pixel perfect drawing.
rect_3d(gui, tm, pos, layer, size, [color]) : id
bitmap_3d(gui, material, tm, pos, layer, size, [color]) : id
bitmap_3d_uv(gui, material, uv_00, uv_11, tm, pos, layer, size, [color]) : id
text_3d(gui, text, font, font_size, material, tm, pos, layer, [color]) : id
As rect(…), etc, but positions the objects in 3D with the transform matrix tm. This allows you to rotate the objects freely in the 3D world. Using this method, you can use a single world gui to draw objects at lots of different positions in the world which is useful. Note that with this method, the layer is specified separately from the position, so you can use the z-coordinate of the position to offset the depth of the object.
text_extents(gui, text, font, font_size) : min, max
Returns two Vector3’s min and max describing the extent of the text text when drawn with the specified font and font_size. This can be used to center or right-align the text.
The width of the text is returned in the x component of the vectors and the height of the text is returned in the z component of the vectors.
has_all_glyphs(gui, text, font) : bool
Returns true if the font has all the glyphs in the specified text.
update_rect(gui, id, pos, size, [color])
update_triangle(gui, id, p1, p2, p3, layer, [color])
update_bitmap(gui, id, material, pos, size, [color])
update_bitmap_uv(gui, id, material, uv_00, uv_11, pos, size, [color])
update_text(gui, id, text, font, material, font_size, pos, [color])
update_rect_3d(gui, id, tm, pos, layer, size, [color])
update_bitmap_3d (gui, id, material, tm, pos, layer, size, [color])
update_bitmap_3d_uv (gui, id, material, uv_00, uv_11, tm, pos, layer, size, [color])
update_text_3d (gui, id, text, font, material, font_size, tm, pos, layer, [color])
In retained mode, updates the object with the specified id.
destroy_rect(gui, id)
destroy_triangle(gui, id)
destroy_bitmap(gui, id)
destroy_text(gui, id)
destroy_rect_3d(gui, id)
destroy_bitmap_3d (gui, id)
destroy_text_3d (gui, id)
In retained mode, destroys the object with the specified id.

10. Windows specific

10.1 SaveSystem (singleton)

Interface to access save functionality on Windows. Note that since the object is a singleton (there is only one SaveSystem), you don’t need to pass any SaveSystem object to the functions. All the functions operate on the SaveSystem singleton. This interface is described here is specific to Windows and may exist but be different on other platforms.

Asynchronous operations return a SaveToken object that is used to fetch progress during the operation. This object should be closed to free the information that is used during the save, otherwise the game will run out of memory eventually.

10.1.1 Functions

auto_save(filename, data) : token
Call this function to start an auto save. An auto save is a silent save that is used when the game knows the save game to save to and will overwrite this file silently.
filename [string]
Name of file to store. No directory needs to be specified and is not allowed. Only a-z, 0-9 and _ is allowed in the filename.
data [table, number, string, bool or vector3]
Normally this is a table containing the stuff that needs to be saved. Supported datatypes are tables, numbers, strings, bools and vector3s.
You must call close() on the token returned to release the memory.
auto_load(filename)
Call this function to start an auto load. An auto load is a silent load that is used when the game knows the save game to load to and will read this save game silently.pt the file.
filename [string]
Name of file to load. No directory needs to be specified and is not allowed. Only a-z, 0-9 and _ is allowed in the filename.
You must call close() on the token returned to release the memory.
progress(token) : table
This function will fetch a table with information about the load och save progress.
All progress tables will contain the following keys:
done [bool]
Set to true if the load or save has finished.
error [string or nil]
nil if there was no error and a string with the error description if there was an error. This text is not suitable for user display.
progress [number]
A number from 0 to 1 indicating the current progress.

Typical error codes are:
BITSQUID_SAVEDATA_ERROR_MISSING
The specified save game does not exist.
BITSQUID_SAVEDATA_INVALID_FILENAME
Invalid filename.
BITSQUID_SAVEDATA_IO_ERROR
Disk error.
BITSQUID_SAVEDATA_BROKEN
Save data has been corrupted.

A load progress table will contain the following additional keys:
data [any]
The data that was loaded.
close(token)
You must call this function for every token you get from the save system. This frees the memory used by the save operation.

12. Network

12.1 Network (singleton)

Main interface to the system used for playing multiplayer games over the network. (Other network functionality, such as DLC, leaderboards, etc is not found here.)

The Network system is set up with one of the init-functions that determines which network subsystem to use (LanClient, etc). You need to call one of the init functions before you can use any other parts of the Network interface.

You can only have one network subsystem running at any one time. Once you are completely done with using the network, you should call the corresponding shutdown() function to shutdown the network subsystem.

After initializing the network, you use the lobby-functionality of the network subsystem you are using to either create a new lobby or find an existing one (with a lobby browser). When you have enough players in the lobby you can start a NetworkGame.

The NetworkGame class is used to manage a running multiplayer game. You use the same class no matter which network subsystem you are using.

12.1.1 Common

create_game() : NetworkGame
Creates a new network game. You can only have one network game running at any one time. If you have an existing game, you must shut it down first with shutdown_game() before creating a new one.
Note: Both the server and the client should call create_game(), the server when it starts the game, and the client when it drops into the game.
shutdown_game()
Shuts down the network game.
game() : NetworkGame
Returns the current network game or nil if no network game has been set up.
player_id() : string
Returns an id identifying the player. In a LAN game, the id is a random number.
update(dt, callback_object)
Updates the network system. dt is the current time step.
The callback_object is a lua object that will receive callbacks from the network. There are two types of callbacks that can be received: RPC callbacks and NetworkGame callbacks.
RPC callbacks are received whenever another network entity sends us an RPC message. A method with the same name as the RPC message will be called in the callback_object. The first argument to the method will be the player_id of the sender and the remaining arguments will be the parameters of the message.
So if someone sends us the message set_score(10) it will be convert to the call object:set_score(remote_id, 10). See the RPC class for documentation on how to send RPC messages.
NetworkGame callbacks inform you about changes to game_objects in a game that you are participating in. The following functions can be called:
game_object_created(id, remote_id)
The game object identified by id was created by remote_id.
game_object_destroyed(id, remote_id)
The game object identified by id was destroyed by remote_id.
game_object_migrated_to_me(id, remote_id)
You have now become the owner of the game object identified by id. remote_id is the old owner of the game object.
game_object_migrated_away(id, remote_id)
You are no longer the owner of the game object identified by id. remote_id is the new owner of the game object.
Note that you will only receive callbacks during the update call, not at any other time.

Note

In the future it will be possible to make separate calls to receive() and transmit() instead of a single call to update() in order to minimize network latency.

ping(player_id) : ping
Returns the ping time to the specified player in milliseconds, or 0 if no contact has been made to that player yet.
config_hash(config) : hash
Construct a hash based on the contents of a network config. This can be used to determine if two peers are compatible. Specify the resource name of the network configuration as argument to the function.

12.1.2 Debugging

log(level)
Controls how much debugging information is sent to the console. Use one of the following constants:
Network.SILENT
No debugging output at all.
Network.WARNINGS
Only warning messages.
Network.MESSAGES
Game object creation, migration and destruction is printed as well as warning messages.
Network.SPEW
Game object updates and detailed information are printed as well as everything above.

12.1.3 Config

set_resend_time(time)
Set time in seconds between resend of assumed dropped packets. Default is 0.2.
set_max_transmit_rate(time)
Set time in seconds between transmits. Default is 0.03.
set_pong_timeout(time)
Set timeout in seconds before a receiver is considered lost. Default is 60.0
set_ping_send_time(time)
Set time in seconds between a keep-alive response and the next keep-alive message. Default is 1.
set_ping_resend_time(time)
Set time in seconds between a keep-alive messages when there is no response. Default is 0.5.

12.1.4 LAN

init_lan_client(config, [game_port=0]) : LanClient
Inits the network as a client running on a LAN. config should be the name of the .network_game_config file that you want to use, it specifies the supported game objects and RPC messages.
game_port is the network TCP/IP port you want to use for network configuration. If you specify 0, a random free port will be picked. This is good for testing multiple network nodes on the same machine, since it ensures port numbers won't collide.
shutdown_lan_client(client)
Shuts down a LanClient created by init_lan_client().
create_lan_lobby(lobby_port, max_members) : LanLobby
Creates a lobby on the LAN. lobby_port is the TCP/IP port that the lobby should run on. Note that this should not be the same as the game_port. Clients browsing for lobbies will specify the lobby_port number so you should use a single well-known number to run the port on.
max_members is the maximum number of members allowed in the lobby.
When you create a lobby you automatically join it, you don't have to call join_lan_lobby().
join_lan_lobby(address, [lobby_port=0]) : LanLobby
Joins the lobby at the specified address. The address is a string on the format "127.0.0.1:21000". lobby_port specifies the port that the lobby should use. There are two options. You can use 0 at let the computer pick a random free port. This is good when you are testing multiple nodes on the same machine, because it means the port won't collide with the public port used by create_lan_lobby().
The drawback of this is that if the lobby host quits and the lobby migrates to you, other nodes won't find the lobby because it is running on a random port. To make the lobby publicly findable if it migrates to you, you need to use the same public port as you use in create_lan_lobby(). But this means that you cannot run multiple network nodes on the same machine.
leave_lan_lobby(lobby)
Leaves the specified lobby. If you are hosting the lobby, it will migrate to a different user in the lobby. If you are the last member of the lobby, the lobby will be removed.

12.2 RPC (singleton)

The RPC class is used to make remote procedure calls to other nodes in the network.

The members of the RPC class are determined by the content of the network_game_config file you have loaded. All the messages in the config file appear as members of the RPC class. So if you have this in your config file:

types = {
	score = {type = "int" min = 0 max = 255}
}

messages = {
	wants_to_drop_in = {}
	notify_score = { args = ["score"] }
}

Then you can send those messages to a remote player by calling:

RPC.wants_to_drop_in(remote_id)
RPC.notify_score(remote_id, 100)

The remote player will receive the messages as calls to the callback object he specifies when he calls Network.update().

You don't have to create a NetworkGame in order to send RPC messages, but you must have established a connection with the remote player (by being in the same lobby, etc).

Note

Some way of conveniently sending messages to more than one recipient will be added.

12.3 NetworkGame

NetworkGame is responsible for replicating and synchronizing game objects between the players that participate in a game session.

To the NetworkGame a game object is just a table of fields (keys and values) identified by an ID. When you create a game object, you become its owner and get back an ID that you can use to manipulate the object. As owner, you can change the values of the object fields. The changes you make get replicated to all other players. If you delete the object, that too gets replicated.

Game objects can have different types. Each type has its own set of keys and values. The game object types are defined in the .network_game_config file.

Typically, the game objects represent something in the game world, such as units, physical bodies, etc, but the NetworkGame layer does not care about that. It is the responsibility of the user to move data back and forth between the network game objects and the real world entities.

Ownership of objects can be moved between players in the game. This can be used for network load balancing or to get a better fidelity of the play experience (the owner of an object does not have to worry about lag or synchronization problems when interacting with it).

When a remote node has created, destroyed or migrated a game object, you get notified by a callback to the callback object you specify when you call Network.update() see the documentation of Network.update() for a description of these calls.

make_server(game)
Become the server of the game. You can only call this on a game that was just created and that doesn't have any other players in it. The server of the game is the only one that can add players to or remove players from the game.
When you call make_server() you automatically also join the game.
shutdown_server(game)
Called by the game server to shut down the game.
add_client(game, player_id)
Adds the player with the specified id to the game. Only the server can add players.
remove_client(game, player_id, callback_object)
Removes the player with the specified id from the game. Only the server can remove players.
callback_object is used to make callbacks to in case an object is destroyed as a result of the player being removed.
The following function can be called:
game_object_destroyed(id, remote_id)
The game object identified by id was destroyed by remote_id.
leave(game)
Called by a client to tell the server that it wants to leave the game. After calling this you should wait until in_game() returns false before shutting down the game. This ensures that all other players are informed that you have left the game.
players(game) : table
Returns a table with the player ids of all players in the game.
other_players(game) : table
Returns a table with the player ids of all players except for yourself.
in_game(game) : bool
Returns true if you are in the game. If this function returns false you have been removed from the game because of a bad connection or because the server kicked you out. In that case you should shut down the game.
server() : player_id
Returns the player id if the game server.
broken_connection(game) : player_id?
Called by the server to detect broken connections. If the connection to a player has been broken, the function will return that player's id. The server should respond by removing the player from the game after destroying or migrating his objects.
If all connections are good, the function will return nil.
If there are more than one broken connections you will get them by calling this function repeatedly.
wants_to_leave(game) : player_id?
If a player has asked to leave the game, this function will return that player's id. The server should respond by removing the player from the game after destroying or migrating his objects.
If no one wants to leave, the function will return nil.
If there are more than one player that wants to leave, you will get them by calling this function repeatedly.
create_game_object(game, type, fields) : id
Creates a new game object of the specified type and returns its id.
fields is a table that provides initial values for the game object's fields, such as {position = Vector3(0,0,0), hitpoints = 50}.
game_object_field(game, id, field) : object
Returns the value of the specified field in the game object with the id.
game_object_is_type(game, id, type) : bool
Returns true if the game object is of the specified type.

Note

There is no function for returning the type of the object, because internally it is represented by a hash rather than a string.

set_game_object_field(game, id, field, value)
Changes the field in the object to the specified value. This can only be called by the owner of the object.
destroy_game_object(game, id)
Destroys the game object with the specified id. This can only be called by the owner of the object.
migrate_game_object(game, id, player_id, callback)
Migrates the game object to a new owner. After this call player_id will be the new owner of the object. This function can only be called by the game server.
callback is a callback object similar to the one passed to Network.update(). If you are migrating the object from or to yourself you will receive an immediate game_object_migrated_away() or game_object_migrated_to_me() message to the callback object.
game_object_exists(game, id)
Returns true if the game object exists.
objects_owned_by(game, player_id) : table
Returns all the objects owned by the player.
unit_synchronizer(game) : UnitSynchronizer
Returns the unit synchronizer corresponding to the game. The unit synchronizer is a helper class that can do automatic synchronizing between game objects and units. You don't have to use the UnitSynchronizer if you don't want to, you can also synhronize game objects and units manually.
set_perfhud_pie_update_interval(time)
Sets the interval in seconds between updates of the upload and download pies in the network perfhud. A short interval will find spikes but will change rapidly. The default is 1.

12.4 UnitSynchronizer

A helper class to make it easier to synchronize units with game objects.

If you use this class it will synchronize the creation and destruction of units. It will also synchronize the position and rotation of the units' root objects.

This class can provide a "quick-and-dirty" way of synchronizing game units without having to handle game_object_created callbacks, etc. If you want more detailed control over how the units are synchronized, you probably want to do your own unit synchronization instead of using the synchronizer.

To use the unit synchronizer, the game objects you sync must have four standard fields: synchronizer_id, unit_name, position and rotation. You can have additional fields if you want to that you synchronize manually, outside the scope of the unit synchronizer.

types = {
	position = {type = "vector3" min = -1000 max = 1000 
		bits = 20 tolerance=0.05 interpolated=true}
	rotation = {type = "quaternion" tolerance=0.01 interpolated=true}
	unit_name = {type = "resource_id"}
	synchronizer_id = {type = "int" min = 0 max = 255}
}

objects = {
	unit = {
		fields = [
			"synchronizer_id"
			"unit_name"
			"position"
			"rotation"
		]
	}
}
set_world(synchronizer, world)
Sets the World that the UnitSynchronizer should use to spawn units in. You have to call this before starting to use the synchronizer.
spawn_unit(synchronizer, type, unit_type, [position], [rotation]) : Unit
Spawns a synchronized unit using the game object type type.
destroy_unit(synchronizer, unit)
Destroys the unit. The unit must have been spawned with UnitSynchronizer.spawn_unit().
game_object_id_to_unit(synchronizer, id) : Unit
Returns the Unit corresponding to the game object with specified id.
unit_to_game_object_id(synchronizer, unit) : id
Returns the game object id of the specified unit. The unit must have been spawned with UnitSynchronizer.spawn_unit().

13. Network -- LAN

13.1 LanClient

Represents a network node in a LAN game.

lobby_browser(client) : LanLobbyBrowser
Returns the lobby browser that can be used to browse for LAN games.

13.2 LanLobby

Represents a lobby in a LAN game.

You can create a lobby with Network.create_lan_lobby() or join an existing one with Network.join_lan_lobby().

state(lobby) : int
Returns the current state of the lobby. The state can be one of the following values:
LanLobby.CREATING
This is the state of the lobby after it has been created with Network.create_lan_lobby(). If the lobby is successfully created, the state will change to LanLobby.JOINED. If the creation fails, the state will be LanLobby.FAILED.
LanLobby.JOINING
The state of the lobby after it has been created with Network.join_lan_lobby(). This state means the lobby is waiting for the lobby server to accept us as a lobby member. When we are accepted the state will change to LanLobby.JOINED. If we are not accepted, the state will be LanLobby.FAILED.
LanLobby.JOINED
The player is in the lobby.
LanLobby.FAILED
The player has dropped out of the lobby for some reason, connection problem, rejected by the server, etc.
owner(lobby) : player_id
Returns the PlayerId of the current lobby owner.
num_members(lobby) : int
Returns the number of members currently in the lobby.
member(lobby, i) : player_id
Returns the PlayerId of the i'th lobby member.
kick(lobby, player_id)
Removes the player from the lobby. Only the lobby owner can do this.
set_data(lobby, key, value)
Each lobby can contain a number of string values identified by string keys. You can use that to store a description of the lobby, name of the game, map name, etc.
get_data(lobby, key) : string
Gets the lobby string value identified by the key.
set_player_data(lobby, key, value)
As set_data() but sets a data field for the current player in the lobby. The data will be mirrored out to other members and they can use get_member_data() to query it.
get_player_data(lobby, key) : string
Gets data for the local player.
get_member_data(lobby, i, key) : string
Gets data for the specified lobby member.
set_game_server(lobby, player_id)
Sets the game server of the lobby to the specified player. This is used by the lobby host to indicate that a game has started.
You can set the game server to nil to clear out the game server.
game_server(lobby) : player_id?
Returns the game server of the lobby or nil if no game server has been set. If a client detects that a game server has been set, it should typically first load the level map and then send a message to the game server saying that it wants to drop into the game. Upon receiving that message the game server should call NetworkGame.add_client() to add the player to the game.

13.3 LanLobbyBrowser

Used to search for LAN lobbies. The class keeps a list of all LAN lobbies found. Call refresh() to refresh the list.

refresh(browser, port)
Refreshes the list of game lobbies by broadcasting a search on the LAN. port is the port number that the broadcast should search on. The search will only find LanLobbies with a matching port number.
is_refreshing(browser) : bool
Returns true if the list is currently refreshing. If you are already refreshing refresh() will do nothing. You can't refresh more than once every 3 seconds.
num_lobbies(browser) : int
Returns the number of lobbies found.
lobby(browser, i) : table
Returns the i'th lobby found. The return value is a table with the following fields:
name
The name of the lobby -- a suitable string to display in the browser interface.
address
The address (ip:port) of the lobby. This is the address you should use to call Network.join_lan_lobby() if you want to join the lobby.