Lua Scripting

## Introduction

In Dual Universe, you can script interactions between Elements using Lua. The principle is the following: you can plug Elements into a Control Unit "CONTROL" slots, and each of the plugged Element will present itself as a Lua object capable to emit events and execute functions. The name of the slot is simply the name of the Lua object. The Control Unit has a dedicated "Edit Lua" window where you can then associate a piece of Lua code to any event emitted by one of your plugged Element. This code will be executed when the event occurs. Inside the Lua script, you can use the functions offered by the plugged Elements to generate any behavior you like. These functions are simply methods of the Lua object that represents the slot where your Element is plugged into.

## Concepts

To script Elements in Lua, here are the necessary steps:

* Identify the Control Unit that you want to host your Lua scripting. You Lua code will run when you activate this Control Unit.
* Plug all the Elements that you want to script together inside the Control Unit, using CONTROL links. You can simply click the Control Unit and then the desired plugged Element, this will pick the first free CONTROL plug in your Control Unit. You may want to selectively pick a particular plug, in that case you need to right-click on the Control Unit first and select the desired plug in the menu.
* Once all the Elements are plugged, open the "Edit Lua" window from the context menu of the Control Unit. This will open the "Control Unit Editor".
* The Control Unit Editor is composed of three columns. The first column lists all the slots available, with the corresponding Element plugged inside them. Each Slot correspond to one of the CONTROL plug of the Control Unit. Note that there are some predefined slots:
	+ System: the System DPU, to access things like keystrokes, updates, timers. See the doc below.
	+ Unit: this is the Control Unit itself
	+ Library: contains useful functions that are implemented in C++ for performance reasons The rest of the slots are the slots you used to plug your Elements. You can rename them to help you remember who is what.
* Select one slot, for example the System slot.
* In the middle column (which is initially empty), you can define event handlers to react to events associated to the slot you have selected.
* Add an event, for example "actionStart", and select the "forward" action in the dropdown menu that appears when you try to edit the event argument.
* When you click on an event handler, the third column will display the associated Lua code that must be run when this event occurs.
* The Lua code can use any of the functions of any slot, using the syntax: slotname.function(...)
* The documentation below details all the functions and events available for all the type of Element in the game

The Lua community in Dual Universe is very active and have produced some outstanding work. See page on Community Links

## Physics scripting, how is your ship flying?

Piloting a ship is a complex topic, a bit like... rocket science actually! We tried to simplify it to a few core concepts. The ship will move because it has some engines attached to it, and engines are capable to exert a force on the body of the ship. To be more precise, there are two things an engine can generate:

* Forces: they actually push your ship and make it move in a given direction
* Torques: they make your ship rotate on itself

To simplify the control problem, we made a first move by defining engines that can do "torque" only, called the "Adjustors", vs engines that can do "force" only, basically the other engines. Hovercraft engines are the only engines capable to produce force and torque at the same time.

You can control the thrust of each individual engine in your ship by plugging them in the Control Unit and using the setThrust method. However, this can become tedious as the number of engines grow, and it is quite difficult to calculate exactly what thrust to apply to which engine if you want to control the overall global cumulative effect. So, we introduce a cool notion to simplify the process of controlling your engines: grouping.

Grouping engines is done via a tagging mechanism, that you can access by right-clicking an engine and setting its associated tags. By default, all engines are tagged with "all" and some other tags indicating their typical role in the ship control. The default tagging is the following:

* Adjustors: all, torque
* Hovercraft: all, vertical, torque
* Vertical Boosters: all, vertical
* Air brake or Retro Engines: all, brake
* All the others: all, horizontal

These are the default, and you can freely modify them and add you custom groups.

Once you have a group of engines, you have a facility within your Control Unit to address them as a whole, just as if they were one single engine, and assign them a given linear and angular acceleration. The system will then calculate the corresponding force and torque that are needed to produce these accelerations, and figure out a thrust assignment for all the engines in the group, so that the end result will be equal or as close as possible to the requested command. This is the "setEngineCommand" method, available in the Control Unit slot (called "unit").

Using this facility, the auto configurator that generates a Lua script for you the first time you enter into a cockpit will typically produce Lua code of this form:

* control.setEngineCommand("vertical,torque", acceleration, angularAcceleration)
* control.setEngineCommand("horizontal", forwardAcceleration, nullvector)
* control.setEngineCommand("brake", brake, nullvector)

The linear acceleration in the horizontal or vertical direction, as well as the angular acceleration, are the result of a computation that is done in the Navigator Lua code, which you may freely modify (it's the ControlCommand.lua file, which is loaded whenever you start a Control Unit), and which defines how controlling of your ship by pressing keys will affect the desired acceleration requested.

All these calculation and the final call to the setEngineCommand method are done in the "flush" event of the System slot. Flush is called several times per frame to calculate the physics simulation. You should never put anything else but physics-related calculation in flush. Anything else this is gameplay related, like connecting buttons or displaying things on screens, should be done in the "update" event, which is called at each frame rendering.

## System events and methods

The System DPU, available in the "system" slot is a crucial part of your Lua programming. This virtual element (it is always plugged and always there) will send various events that you can catch to orchestrate your Lua scripting.

There are three fundamental ways to get events are regular intervals from System:

* update: this event is triggered at each frame (its frequency will depend on the framerate)
* flush: this event is triggered at each step of the physics calculation, usually more than once per frame. Be careful to limit its use to setting engine thrusts, for example with the setEngineCommand method.
* tick(n): this event is repeatedly triggered whenever the timer 'n' is reaching its duration. You can create a timer with index "n" and with a given duration using the setTimer(n, duration) method in System. The duration is expressed in seconds, and the event will tick at quasi-regular intervals, independently of the framerate if the duration is larger that the typical frame duration.

The other important event type that System is managing are keystroke events. We call these "actions" to make it independent on the particular key binding that will be associated to it. System then defines three types of events associated to an action:

* actionStart(action): this event is triggered when the action starts (key pressed down)
* actionStop(action): this event is triggered when the action stops (key released)
* actionLoop(action): this event is triggered at each frame as long as the key is pressed (think of it as a filter on the "update" event)

Actions are referred to by their name, and the Control Unit Editor will pop a list of available actions to choose from whenever you click on the argument of an action event.

## Lua code associated to an event filter

Inside the code window that is associated to an event filter on a given slot, you can type in any Lua code you like. There are limits in memory and CPU usage however, as well as in the total size of the code (currently 10Ko compressed).

Note that the Lua interpreter that runs the Lua code is specific to each Control Unit, so there is not automatic sharing of the memory between two running Control Units. You may however exchange variable between different event handlers, simply define them without the "local" keyword and they will become global variables.

The Lua code will typically refer to some of the slots in the Control Unit to call methods associated to the elements that are plugged in these slots. Suppose you have a "screen" slot where you have plugged a Screen Unit, you may write code of the form:
screen.setCenteredText("Hello World")
To know what methods and what events are available for all the different Elements in the game, simply refer to the documentation below.

## How to expose some values outside of Lua editor

You can edit Lua variable values without opening the Lua editor. This can be handy to expose some configuration variables. They only have to be declared with the "export" keyword:

* rotationSpeed = 2 --export local rotationSpeed = 2 --export: rotation speed in rad/s

Then, you can right click on your ControlUnit and select the "Edit Lua Parameters" action to modify those exported values.

## Element API

### Generic element

All elements share the same generic methods described below:

#### show()

Show the element widget in the in-game widget stack

#### hide()

Hide the element widget in the in-game widget stack

#### getWidgetType()

Get widget type compatible with the element data

#### getHitPoints()

The element current hit points (0 = destroyed)

#### getMaxHitPoints()

The element's maximal hit points when it's fully functional

#### setSignalIn(plug, state)

Set the value of a signal in the specified IN plug of the element standard plug names are composed with the following syntax => direction-type-index where 'direction' can be IN or OUT, 'type' is one of the following => ITEM, FUEL, ELECTRICITY, SIGNAL, HEAT, FLUID, CONTROL, and 'index' is a number between 0 and the total number of plugs of the given type in the given direction. Some plugs have special names like "on" or "off" for the manual switch unit, just check in-game for the plug names if you have a doubt.

 state

#### getSignalIn(plug)

Return the value of a signal in the specified IN plug of the element. Standard plug names are composed with the following syntax => direction-type-index where 'direction' can be IN or OUT, 'type' is one of the following => ITEM, FUEL, ELECTRICITY, SIGNAL, HEAT, FLUID, CONTROL, and 'index' is a number between 0 and the total number of plugs of the given type in the given direction. Some plugs have special names like "on" or "off" for the manual switch unit, just check in-game for the plug names if you have a doubt.

 return

#### getSignalOut(plug)

Return the value of a signal in the specified OUT plug of the element standard plug names are composed with the following syntax => direction-type-index where 'direction' can be IN or OUT, 'type' is one of the following => ITEM, FUEL, ELECTRICITY, SIGNAL, HEAT, FLUID, CONTROL, and 'index' is a number between 0 and the total number of plugs of the given type in the given direction. Some plugs have special names like "on" or "off" for the manual switch unit, just check in-game for the plug names if you have a doubt.

 return

#### getItemsMass()

Returns the container content mass (the sum of the mass of all the items it contains)

### Control unit

Control units come in various forms: cockpits, programming boards, emergency control units, etc. A control unit stores a set of Lua scripts that can be used to control the elements that are plugged on its CONTROL plugs. Kinematics control units like cockpit or command seats are also capable of controlling the ship's engines via the update ICC method.

#### exit()

Stops the control unit's Lua code and exits. Warning: calling this might cause your ship to fall from the sky, use it with care. It is typically used in the coding of emergency control unit scripts to stop control once the ECU thinks that the ship has safely landed.

#### setTimer(timerTagId, period)

Set up a timer with a given tag ID in a given period. This will start to trigger the 'tick' event with the corresponding ID as an argument, to help you identify what is ticking, and when.

 period

#### getAtmosphereDensity()

Returns the local atmosphere density, between 0 and 1

#### getClosestPlanetInfluence()

Returns the closest planet influence, between 0 and 1

#### getMasterPlayerRelativePosition()

Return the relative position (in world coordinates) of the player currently running the control unit

#### getMasterPlayerId()

Return the ID of the player currently running the control unit

#### setEngineCommand(taglist, acceleration, angularAcceleration, keepForceCollinearity, keepTorqueCollinearity, priority1SubTags, priority2SubTags, priority3SubTags, toleranceRatioToStopCommand)

Automatically assign the engines within the taglist to result in the given acceleration and angular acceleration provided. Can only be called within the system.flush event. If engines designated by the tags are not capable of producing the desired command, setEngineCommand will try to do its best to approximate it.

#### setEngineThrust(taglist, thrust)

Force the thrust value for all the engines within the tag list

 thrust

#### setAxisCommandValue(axis, commandValue)

Set the value of throttle in the cockpit, which will be displayed in the cockpit widget when flying

 commandValue

#### getAxisCommandValue(axis)

Get the value of throttle in the cockpit

 return

#### setupAxisCommandProperties(axis, commandType)

Set the properties of an axis command These properties will be used to display the command in UI

 commandType
 targetSpeedRanges

#### getControlMasterModeId()

Get the current master mode in use. The mode is set by clicking the UI button or using the associated keybinding

#### isMouseControlActivated()

Check if a mouse control scheme is selected

#### isMouseDirectControlActivated()

Check if the mouse control direct scheme is selected

#### isMouseVirtualJoystickActivated()

Check if the mouse control virtual joystick scheme is selected

#### isRemoteControlled()

Check if the construct is remote controlled

#### activateGroundEngineAltitudeStabilization(targetAltitude)

The ground engines will stabilize to this altitude within their limits The stabilization will be done by adjusting thrust to never go over the target altitude This includes VerticalBooster and HoverEngine

#### getSurfaceEngineAltitudeStabilization()

return the ground engines stabilization altitude

#### deactivateGroundEngineAltitudeStabilization()

The ground engines will behave like regular engine This includes VerticalBooster and HoverEngine

#### computeGroundEngineAltitudeStabilizationCapabilities()

Returns ground engine stabilization altitude capabilities (lower and upper ranges)

#### tick(timerId)   *event*

Emitted when the timer with id 'timerId' is ticking

### Databank unit

Stores key/value pairs in a persistent way.

#### getNbKeys()

Returns the number of keys that are stored inside the data bank

#### hasKey(key)

Returns 1 if the key is present in the data bank, 0 otherwise

#### setStringValue(key,val)

Stores a string value at the given key

 val

#### getStringValue(key)

Returns value stored in the given key as a string

 return

#### setIntValue(key,val)

Stores an integer value at the given key

 val

#### getIntValue(key)

Returns value stored in the given key as an integer

 return

#### setFloatValue(key,val)

Stores a floating number value at the given key

 val

#### getFloatValue(key)

Returns value stored in the given key as a floating number

 return

### Engine unit

An engine is capable to produce a force and/or a torque to move your construct.

#### activate()

Start the engine at full power (works only when run inside a cockpit or under remote control)

#### deactivate()

Stops the engine (works only when run inside a cockpit or under remote control)

#### getState()

Returns the state of activation of the anti-g generator

#### setThrust(thrust)

Set the engine thrust between 0 and maxThrust

#### getMaxThrustBase()

Returns the maximal thrust the engine can deliver in principle, under optimal conditions. Note that the actual maxThrust will most of the time be less than maxThrustBase.

#### getCurrentMaxThrust()

Returns the maximal thrust the engine can deliver at the moment, which might depend on various conditions like atmospheric density, obstruction, orientation, etc. The actual thrust will be anything below this maxThrust, which defines the current max capability of the engine.

#### getCurrentMinThrust()

Returns the minimal thrust the engine can deliver at the moment (can be more than zero), which will depend on various conditions like atmospheric density, obstruction, orientation, etc. Most of the time, this will be 0 but it can be greater than 0, particularly for ailerons, in which case the actual thrust will be at least equal to minThrust.

#### getMaxThrustEfficiency()

Returns the ratio between the current MaxThrust and the base MaxThrust

#### getThrust()

Returns the current thrust level of the engine

#### getDistanceToObstacle()

Returns the distance to the first object detected in the direction of the thrust

#### hasBrokenFuelTank()

Is the engine linked to a broken fuel tank?

#### getCurrentFuelRate()

The engine rate of fuel consumption per newton delivered per second

#### getFuelRateEfficiency()

Returns the ratio between the current fuel rate and the theoretical nominal fuel rate

#### getT50()

The time needed for the engine to reach 50% of its maximal thrust (all engines do not instantly reach the thrust that is set for them, but they can take time to "warm up" to the final value)

#### isObstructed()

If the engine exhaust is obstructed by some element or voxel material, it will stop working or may work randomly in an instable way and you should probably fix your design.

#### getObstructionFactor()

Returns the obstruction ratio of the engine exhaust by elements and voxels. The more obstructed the engine is, the less properly it will work. Try to fix your design if this is the case.

### Fireworks unit

A unit capable to launch fireworks that are stored in the attached container.

#### setExplosionDelay(t)

Set the delay before the launched fireworks explodes. Max=5s

#### setLaunchSpeed(v)

Set the speed at which the firework will be launched (impacts its altitude, depending on the local gravity). Max=200m/s

#### setType(type)

Set the type of launched firework (will affect which firework is picked in the attached container)

#### setColor(color)

Set the color of the launched firework (will affect which firework is picked in the attached container)

### Force field unit

A forcefield to create an uncrossable energy barrier.

#### getState()

Returns the activation state of the field

### Landing gear unit

A landing gear that can be opened or closed.

#### getState()

Returns the activation state of the landing gear

#### getState()

Returns the activation state of the light

#### setRGBColor(r,g,b)

Set the light color in RGB

 g
 b

## Lua Scripting

### Anti gravity generator unit

Generates graviton condensates to power anti-gravity pulsors

#### getState()

Returns the state of activation of the anti-g generator

#### setBaseAltitude(altitude)

Set the base altitude for the anti-gravity field

#### getBaseAltitude()

Return the base altitude for the anti-gravity field

### Industry unit

Can mass-produce produce any item/element.

#### start()

Start the production, and it will run unless it is stopped or the input resources run out.

#### startAndMaintain()

Start maintaining the specified quantity. Resumes production when the quantity in the output container is too low, and pauses production when it is equal or higher

#### batchStart()

Start the production of numBatches and then stop

#### softStop()

End the job and stop. The production keeps going until it is complete, then it switches to "STOPPED" status. If the output container is full, then it switches to "JAMMED"

#### hardStop()

Stop production immediately. The resources are given back to the input container. If there is not enough room in the input containers, production stoppage is skipped if allowIngredientLoss is set to 0, or ingredients are lost if set to 1

#### getCycleCountSinceStartup()

Get the count of completed cycles since the player started the unit

#### getUptime()

Get the time elapsed in seconds since the player started the unit for the latest time

#### completed()   *event*

Emitted when the industry unit has completed a run

#### statusChanged(status)   *event*

Emitted when the industry status has changed

### Counter unit

Cycle its output signal over a set of n-plugs, incrementing the activate plug by one step at each impulse received on its IN plug.

#### getCounterState()

Returns the rank of the currently active OUT plug

#### next()

Moves the counter one step further (equivalent to signal received on the IN plug)

### Emitter unit

This unit is capable of emitting messages on channels.

#### send(channel,message)

Send a message on the given channel

 message

#### receive(channel,message)   *event*

Emitted when a message is received on any channel

 message

### Core unit

This is the heart of your construct. It represents the construct and gives access to all construct-related information.

#### getConstructIMass()

Returns the inertial mass of the construct, calculated as 1/3 of the trace of the inertial tensor.

#### getConstructCrossSection()

Returns the construct's cross sectional surface in the current direction of movement

#### getMaxKinematicsParametersAlongAxis()

Returns the construct max kinematics parameters in both atmo and space range, in newtons. Kinematics parameters designate here the maximal positive and negative base force the construct is capable of producing along the chosen Axisvector, as defined by the core unit or the gyro unit, if active. In practice, this gives you an estimate of the maximum thrust your ship is capable of producing in space or in atmosphere, as well as the max reverse thrust. These are theoretical estimates and correspond with the addition of the maxThrustBase along the corresponding axis. It might not reflect the accurate current max thrust capacity of your ship, which depends on various local conditions (atmospheric density, orientation, obstruction, engine damage, etc). This is typically used in conjunction with the control unit throttle to setup the desired forward acceleration.

 CRefAxis
 return

#### getConstructWorldPos()

Returns the world position of the construct

#### getWorldAirFrictionAngularAcceleration()

Returns the acceleration torque generated by air resistance

#### getWorldAirFrictionAcceleration()

Returns the acceleration generated by air resistance

#### spawnNumberSticker(nb,x,y,z,orientation)

Spawns a number sticker in the 3D world, with coordinates relative to the construct.

 x
 y
 z
 orientation
 return

#### spawnArrowSticker(x,y,z,orientation)

Spawns an arrow sticker in the 3D world, with coordinates relative to the construct.

 y
 z
 orientation
 return

#### deleteSticker(index)

Delete the referenced sticker.

 return

#### moveSticker(index,x,y,z)

Move the referenced sticker.

 y
 z
 index
 return

#### rotateSticker(index,angle\_x,angle\_y,angle\_z)

Rotate the referenced sticker.

 angle\_y
 angle\_z
 index
 return

#### getElementIdList()

List of all the UIDs of the elements of this construct

#### getElementNameById(uid)

Name of the element, identified by its UID

 return

#### getElementTypeById(uid)

Type of the element, identified by its UID

 return

#### getElementHitPointsById(uid)

Current level of hit points of the element, identified by its UID

 return

#### getElementMaxHitPointsById(uid)

Max level of hit points of the element, identified by its UID

 return

#### getElementMassById(uid)

Mass of the element, identified by its UID

 return

#### getAltitude()

Altitude above sea level, with respect to the closest planet (0 in space)

#### getWorldGravity()

Local gravity vector in world coordinates

#### getWorldVertical()

Vertical unit vector along gravity, in world coordinates (0 in space)

#### getAngularVelocity()

The construct's angular velocity, in construct local coordinates

#### getWorldAngularVelocity()

The construct's angular velocity, in world coordinates

#### getAngularAcceleration()

The construct's angular acceleration, in construct local coordinates

#### getWorldAngularAcceleration()

The construct's angular acceleration, in world coordinates

#### getVelocity()

The construct's linear velocity, in construct local coordinates

#### getWorldVelocity()

The construct's linear velocity, in world coordinates

#### getWorldAcceleration()

The construct's linear acceleration, in world coordinates

#### getAcceleration()

The construct's linear acceleration, in construct local coordinates

#### getConstructOrientationUp()

The construct's current orientation up vector, in construct local coordinates

#### getConstructOrientationRight()

The construct's current orientation right vector, in construct local coordinates

#### getConstructOrientationForward()

The construct's current orientation forward vector ,in construct local coordinates

#### getConstructWorldOrientationUp()

The construct's current orientation up vector, in world coordinates

#### getConstructWorldOrientationRight()

The construct's current orientation right vector, in world coordinates

#### getConstructWorldOrientationForward()

The construct's current orientation forward vector, in world coordinates

### Screen unit

Screen units can display any HTML code or text message, and you can use them to create visually interactive feedback for your running Lua script by connecting one or more of them to your control unit.

#### addText(x,y,fontSize,text)

Displays the given text at the given coordinates in the screen, and returns an ID to move it later

 y
 fontSize
 text
 return

#### setCenteredText(text)

Displays the given text centered in the screen with a font to maximize its visibility

#### setHTML(html)

Set the whole screen HTML content (overrides anything already set)

#### addContent(x,y,html)

Displays the given HTML content at the given coordinates in the screen, and returns an ID to move it later

 y
 html
 return

#### setSVG(svg)

Displays SVG code (anything that fits within a <svg> section), which overrides any preexisting content

#### resetContent(id,html)

Update the element with the given ID (returned by setContent) with a new HTML content

 html

#### deleteContent(id)

Delete the element with the given ID (returned by setContent)

#### showContent(id, state)

Update the visibility of the element with the given ID (returned by setContent)

 state

#### moveContent(id,x,y)

Move the element with the given id (returned by setContent) to a new position in the screen

 y
 id

#### getMouseX()

Returns the x-coordinate of the position pointed at in the screen

#### getMouseY()

Returns the y-coordinate of the position pointed at in the screen

#### mouseDown(x,y)   *event*

Emitted when the player starts a click on the screen unit

 y

#### mouseUp(x,y)   *event*

Emitted when the player releases a click on the screen unit

 y

### Detection zone unit

Detect the intrusion of any player inside the effect zone.

### Gyro unit

A general kinematic unit to obtain information about the ship orientation, velocity, and acceleration.

#### activate()

Selects this gyro as the main gyro used for ship orientation

#### deactivate()

Deselects this gyro as the main gyro used for ship orientation, using the core unit instead

#### localUp()

The up vector of the gyro unit, in construct local coordinates

#### localForward()

The forward vector of the gyro unit, in construct local coordinates

#### localRight()

The right vector of the gyro unit, in construct local coordinates

#### worldUp()

The up vector of the gyro unit, in world coordinates

#### worldForward()

The forward vector of the gyro unit, in world coordinates

#### worldRight()

The right vector of the gyro unit, in construct local coordinates

#### getPitch()

The pitch value relative to the gyro orientation and the local gravity

#### getRoll()

The roll value relative to the gyro orientation and the local gravity

#### getState()

Returns the current state of the laser detector

#### laserRelease()   *event*

All lasers have stopped hitting the detector

### Laser emitter unit

Emits a laser ray that can be use to detect the passage of a player or on a laser detector unit.

#### getState()

Returns the activation state of the laser

### Manual button

Emits a signal for the duration it is pressed.

#### getState()

Returns the activation state of the button

### Manual switch unit

A manual switch that can be in an on/off state.

#### getState()

Returns the activation state of the switch

### Pressure tile unit

Emits a signal when a player walks on the tile.

#### getState()

Returns the activation state of the pressure tile

### Radar unit

List local constructs and access their ID.

#### getEntries()

Returns the list of construct IDs currently detected in the range

#### getConstructOwner(id)

Return the player id of the owner of the given construct, if in range

 return

#### getConstructSize(id)

Return the size of the bounding box of the given construct, if in range

 return

#### getConstructType(id)

Return the type of the given construct

 return

#### getConstructWorldPos(id)

Return the world coordinates of the given construct, if in range

 return

#### getConstructWorldVelocity(id)

Return the world coordinates of the given construct's speed, if in range

 return

#### getConstructWorldAcceleration(id)

Return the world coordinates of the given construct's acceleration, if in range

 return

#### getConstructPos(id)

Return the radar local coordinates of the given construct, if in range

 return

#### getConstructVelocity(id)

Return the radar local coordinates of the given construct's speed, if in range

 return

#### getConstructAcceleration(id)

Return the radar local coordinates of the acceleration of the given construct, if in range

 return

#### getConstructName(id)

Return the name of the given construct, if defined

 return

#### enter(id)   *event*

Emitted when a construct enters the range of the radar unit

#### leave(id)   *event*

Emitted when a construct leaves the range of the radar unit

### Telemeter unit

Measures the distance to an obstacle in front of it.

#### getDistance()

Returns the distance to the first obstacle in front of the telemeter

#### getMaxDistance()

Returns the max distance from which an obstacle can be detected (default is 20m)

### Warp drive unit

Based on the principle of the Alcubierre drive, this unit creates a powerful negative energy-density field capable to distort space-time and transport your ship at hyper speeds through space.

#### activateWarp()

Start the warp drive, if a warp destination has been selected

### Library

Contains a list of useful math and helper methods that would be slow to implement in Lua, and which are given here as fast C++ implementation.

#### systemResolution3(vec\_c1,vec\_c2,vec\_c3,vec\_c0)

Solve the 3D linear system M\*x=c0 where M is defined by its column vectors c1,c2,c3

 vec\_c2
 vec\_c3
 vec\_c0
 return

#### systemResolution2(vec\_c1,vec\_c2,vec\_c0)

Solve the 2D linear system M\*x=c0 where M is defined by its column vectors c1,c2

 vec\_c2
 vec\_c0
 return

### System

System is a virtual element that represents your computer. It gives access to events like key strokes or mouse movements that can be used inside your scripts. It also gives you access to regular updates that can be used to pace the execution of your script.

#### getActionKeyName(actionName)

Return the currently key bound to the given action. Useful to display tips.

#### showScreen(bool)

Control the display of the control unit custom screen, where you can define customized display information in HTML. Note that this function is disabled if the player is not running the script explicitly (pressing F on the Control unit, vs. via a plug signal).

#### setScreen(content)

Set the content of the control unit custom screen with some HTML code. Note that this function is disabled if the player is not running the script explicitly (pressing F on the control unit, vs. via a plug signal).

#### createWidgetPanel(label)

Create an empty panel. Note that this function is disabled if the player is not running the script explicitly (pressing F on the Control unit, vs. via a plug signal).

 return

#### destroyWidgetPanel(panelId)

Destroy the panel. Note that this function is disabled if the player is not running the script explicitly (pressing F on the control unit, vs. via a plug signal).

 return

#### createWidget(panelId, type)

Create an empty widget and add it to a panel. Note that this function is disabled if the player is not running the script explicitly (pressing F on the Control unit, vs. via a plug signal).

 type
 return

#### destroyWidget(widgetId)

Destroy the widget. Note that this function is disabled if the player is not running the script explicitly (pressing F on the control unit, vs. via a plug signal).

 return

#### createData(dataJson)

Create data. Note that this function is disabled if the player is not running the script explicitly (pressing F on the Control unit, vs. via a plug signal).

 return

#### destroyData(dataId)

Destroy the data. Note that this function is disabled if the player is not running the script explicitly (pressing F on the control unit, vs. via a plug signal).

 return

#### updateData(dataId, dataJson)

Update JSON associated to data. Note that this function is disabled if the player is not running the script explicitly (pressing F on the Control unit, vs. via a plug signal).

 dataJson
 return

#### addDataToWidget(dataId, widgetId)

Add data to widget. Note that this function is disabled if the player is not running the script explicitly (pressing F on the Control unit, vs. via a plug signal).

 widgetId
 return

#### removeDataFromWidget(dataId, widgetId)

Remove data from widget. Note that this function is disabled if the player is not running the script explicitly (pressing F on the Control unit, vs. via a plug signal).

 widgetId
 return

#### getMouseWheel()

Return the current value of the mouse wheel

#### getMouseDeltaX()

Return the current value of the mouse delta X

#### getMouseDeltaY()

Return the current value of the mouse delta Y

#### getMousePosX()

Return the current value of the mouse pos X

#### getMousePosY()

Return the current value of the mouse pos Y

#### getThrottleInputFromMouseWheel()

Return the current value of the mouse wheel (for the throttle speedUp/speedDown action)

#### getControlDeviceForwardInput()

Return the mouse input for the ship control action (forward/backward)

#### getControlDeviceYawInput()

Return the mouse input for the ship control action (yaw right/left)

#### getControlDeviceLeftRightInput()

Return the mouse input for the ship control action (right/left)

#### lockView()

Lock or unlock the mouse free look. Note that this function is disabled if the player is not running the script explicitly (pressing F on the Control unit, vs. via a plug signal).

#### isViewLocked()

Return the lock state of the mouse free look

#### freeze(bool)

Freezes the character, liberating the associated movement keys to be used by the script. Note that this function is disabled if the player is not running the script explicitly (pressing F on the control unit, vs. via a plug signal).

#### isFrozen()

Return the frozen status of the character (see 'freeze')

#### getTime()

Return the current time since the arrival of the Arkship

#### getActionUpdateDeltaTime()

Return delta time of action updates (to use in ActionLoop)

#### getPlayerName(id)

Return the name of the given player, if in range of visibility

 return

#### getPlayerWorldPos(id)

Return the world position of the given player, if in range of visibility

 return

#### actionLoop(action)   *event*

Emitted at each update as long as the action is maintained

#### update()   *event*

Game update event. This is equivalent to a timer set at 0 seconds, as updates will go as fast as the FPS can go.

#### flush()   *event*

physics update. Do not use to put anything else by a call to updateICC on your control unit, as many functions are disabled when called from 'flush'. This is only to update the physics (engine control, etc), not to setup some gameplay code.

### **Lua Changes and Additions - added 18/10/2021**

Lua Improvements and Changes

* Changes in the management of construct and element referentials.
For more consistency and to pave the way for future radar changes, the Lua now uses the construct building zone center as origin for all. This change affects local elements or player position and radar construct positions.
We removed the quaternions from the Lua API are now exposing the direction vectors of the objects instead. This change was made to improve the overall player experience as not all players may be familiar with this mathematical notion of representing rotation.
For more information you can read the Lua Improvements and Changes devblog, Part 1.

	+ Added Lua functions on Core Unit:
		- core.getOrientationUnitId() : Returns the UID of the currently active orientation unit (the core unit or the gyro unit).
		- core.getVelocity(): Returns the construct's linear velocity, relative to its parent, in construct local coordinates.
		- core.getWorldVelocity(): Returns the construct's linear velocity, relative to its parent, in world coordinates.
		- core.getAbsoluteVelocity(): Returns the construct's absolute linear velocity in construct local coordinates.
		- core.getWorldAbsoluteVelocity(): Returns the construct's absolute linear velocity in world coordinates.
		- core.getParentPosition(): Returns the position of the construct's parent when docked in construct local coordinates.
		- core.getParentWorldPosition(): Returns the position of the construct's parent when docked in world coordinates.
		- core.getParentForward(): Returns the construct's parent forward direction vector in construct local coordinates.
		- core.getParentUp(): Returns the construct's parent up direction vector in construct local coordinates.
		- core.getParentRight(): Returns the construct's parent right direction vector in construct local coordinates.
		- core.getParentWorldForward(): Returns the construct's parent forward direction vector in world coordinates.
		- core.getParentWorldUp(): Returns the construct's parent up direction vector in world coordinates.
		- core.getParentWorldRight(): Returns the construct's parent right direction vector in world coordinates.
		- core.getElementForwardById( uid) : Returns the forward direction vector of the element identified by its UID in construct local coordinates.
		- core.getElementUpById( uid) : Returns the up direction vector of the element identified by its UID in construct local coordinates.
		- core.getElementRightById( uid) : Returns the right direction vector of the element identified by its UID in construct local coordinates.
	+ Added Lua functions on Control Unit:
		- unit.getMasterPlayerPosition() : Returns the position of the player currently running the control unit in construct local coordinates (relative to the construct center instead of the control unit).
		- unit.getMasterPlayerWorldPosition() : Returns the position of the player currently running the control unit in world coordinates.
		- unit.getMasterPlayerForward() : Returns the forward direction vector of the player currently running the control unit in construct local coordinates.
		- unit.getMasterPlayerUp() : Returns the up direction vector of the player currently running the control unit in construct local coordinates.
		- unit.getMasterPlayerRight() : Returns the right direction vector of the player currently running the control unit in construct local coordinates.
		- unit.getMasterPlayerWorldForward() : Returns the forward direction vector of the player currently running the control unit in world coordinates.
		- unit.getMasterPlayerWorldUp() : Returns the up direction vector of the player currently running the control unit in world coordinates.
		- unit.getMasterPlayerWorldRight() : Returns the right direction vector of the player currently running the control unit in world coordinates.
	+ Changed existing Lua functions:
		- core.getConstructOrientationForward() : Returns the forward direction vector of the active orientation unit in construct local coordinates.
		- core.getConstructOrientationUp() : Returns the up direction vector of the active orientation unit in construct local coordinates.
		- core.getConstructOrientationRight() : Returns the right direction vector of the active orientation unit in construct local coordinates.
		- core.getConstructWorldOrientationForward() : Returns the forward direction vector of the active orientation unit in world coordinates.
		- core.getConstructWorldOrientationUp() : Returns the up direction vector of the active orientation unit in world coordinates.
		- core.getConstructWorldOrientationForward() : Returns the right direction vector of the active orientation unit in world coordinates.
		- core.getConstructWorldPos() : Returns the position of the center of the construct in world coordinates (instead of orientation units position).
		- core.getElementPositionById(<int> uid) : Returns the position of the element, identified by its UID in construct local coordinates (instead of the construct corner).
	+ Deprecated existing Lua functions:
		- core.getElementRotationById() : Deprecated.
		- unit.getMasterPlayerRelativePosition() : Deprecated.
		- unit.getMasterPlayerRelativeOrientation() : Deprecated.
	+ Removed Lua functions that were previously deprecated:
		- unit.getOwnerRelativePosition(),
		- core.getElementList(),
		- core.getElementName(),
		- core.getElementType(),
		- core.getElementHitPoints(),
		- core.getElementMaxHitPoints(),
		- core.getElementMass(),
		- engine.getFuelRate(),
		- engine.isObstructed(),
		- gyro.setYawWorldReference(),
		- gyro.getYaw()
* Radar and transponder changes. There are some future backend radar changes in the planning stages now. In preparation, we have made some improvements to the Lua implementation of the radar. These should not only have a usability benefit but also improve performance as we reduce the usage of JSON strings to deliver payloads in Lua in favor of tables and values. We also heard your feedback that many of you found the transponder lacking in usability. To counter this,  we’ve added the transponder Lua API. For more information on the radar changes, you can read the Lua Improvements and Changes, Part 2 devblog.
	+ Added Lua functions on radar unit:
		- radar.isOperational() : Returns 1 if the radar is not broken, works in the current environment and is not used by another control unit.
		- radar.getRange() : Returns the scan range of the radar unit.
		- radar.getIdentifyRanges() : Returns ranges to identify a target based on its core size.
		- radar.getConstructIds() : Returns the list of construct IDs in the scan range.
		- radar.getIdentifiedConstructIds() : Returns the list of identified construct IDs.
		- radar.getTargetId() : Returns the ID of the target construct.
		- radar.getConstructDistance( cid) : Returns the distance to the given construct.
		- radar.isConstructIdentified( cid) : Returns 1 if the given construct is identified.
		- radar.isConstructAbandoned( cid) : Returns 1 if the given construct was abandoned.
		- radar.getConstructCoreSize( cid) : Returns the core size of the given construct.
		- radar.getThreatTo( cid) : Returns the threat rate your construct is for the given construct.
		- radar.getThreatFrom( cid) : Returns the threat rate the given construct is for your construct.
		- radar.getConstructOwner( cid) : Returns a table with ID of the owner entities (player or organization) of the given construct if in range and if active transponder tags match.
		- radar.getConstructPos( cid) : Returns the position of the given construct in construct local coordinates if the active transponder tags match.
		- radar.getConstructWorldPos( cid) : Returns the position of the given construct in world coordinates if in range and if the active transponder tags match.
		- radar.getConstructSpeed( cid) : Returns the speed of the given construct if identified.
		- radar.getConstructAngularSpeed( cid) : Returns the angular speed of the given construct relative to your construct if identified.
		- radar.getConstructRadialSpeed( cid) : Returns the radial speed of the given construct relative to your construct if identified.
		- radar.getConstructMass( cid) : Returns the mass of the given construct if identified.
		- radar.getConstructInfos( cid) : Returns a list of working elements on the given construct if identified.
		- radar.getConstructVelocity( cid) : Returns the velocity vector of the given construct in construct local coordinates if identified and if the active transponder tags match.
		- radar.getConstructWorldVelocity( cid) : Returns the velocity vector of the given construct in world coordinates if identified and if the active transponder tags match.
	+ Added Lua functions on Transponder Unit:
		- transponder.activate() : Activate the transponder.
		- transponder.deactivate() : Deactivate the transponder.
		- transponder.toggle() : Toggle the state of the transponder.
		- transponder.getState() : Returns the activation state of the transponder.
		- transponder.setTags( tags) : Set the tags list with up to eight entries. Returns 1 if the application was successful, 0 if the tag format is invalid.
		- transponder.getTags() : Returns the tag list.
		- transponder.toggled( active) event : Emitted when the transponder is started or stopped.
	+ Deprecated existing Lua functions:
		- radar.getEntries() : has been renamed to getConstructIds for consistency.
	+ The radar can now be connected to all controllers. You can only use radar for PvP on restricted links or you will not be able to identify or engage a target with it.
* Additional local libraries and update We took the time to add a few minor features to the Lua following some popular requests that we felt would gel well with the other changes. For more information on the libraries, you can read the Lua Improvements and Changes, Part 3 devblog.
	+ Updated database Lua library:
		- database.getPlayer( pid) : Returns all information about a given player, identified by its ID.
		- database.getMasterPlayer( unit) : Returns all information about the player running the script.
		- database.getConstruct( cid) : Returns all information about a given construct, identified by its ID;  requires a radar to detect the construct.
		- database.getElement( core, uid) : Returns all information about a given element, identified by its ID, and requires a linked core unit.
	+ Added the atlas Lua library containing all the information about the stellar bodies. (Check the devblog or check the file in your local Lua game folder.)
	+ Added the event Lua library designed to help players create events in pure Lua. (Check the devblog or check the file in your local Lua game folder.)
* Other changes and improvements.
	+ Ammo containers now have the same Lua API as other container elements.
	+ Added a section on RenderScript and Lua screen units to the Codex.
	+ Added Lua functions on Lua screen units:
		- getTime(): Return the time, in seconds, relative to the first execution.
		- getAvailableFontCount(): Return the number of fonts available to be used by render script.
		- getAvailableFontName(index): Return the name of the nth available font
	+ Added additional Lua functions :
		- core.getConstructName() : Returns the name of the construct.
		- core.getCurrentPlanetId() : Returns the ID of the current close stellar body.
		- system.getPlayerName( pid) : Returns the name of the given player if in range of visibility or broadcasted by a transponder.
		- unit.getMasterPlayerOrgIds() : Returns the list of organization IDs of which the player running the script is a member.
		- system.getOrganizationName( oid) : Returns the name of the given organization, if known, e.g. broadcasted by a transponder.
		- system.getOrganizationTag( oid) : Returns the tag of the given organization, if known, e.g. broadcasted by a transponder.
	+ Deprecated isFontLoaded() function due to a bug fix related to font loading.