GIANTS Game Engine v8 Documentation



Table of Contents

  1. Chapter 01: Overview
    1. Enable development controls
    2. Runtime development key short-cuts
    3. Console Command Reference
  2. Chapter 02: Editor
    1. Viewport
    2. Scenegraph
    3. Attributes
    4. Toolbar
    5. Terrain
    6. User Attributes
    7. Scripting
    8. Terrain Editing
    9. Replace Dialog
    10. Interactive Placement
    11. Other functionality
    12. Key short-cuts
  3. Chapter 03: Debugger
    1. GIANTS Debugger
    2. Overview of panels
    3. Creating a new project
    4. Global and local variables
    5. Callstack panel
    6. Running new scripts during debugging
    7. Breakpoints
    8. Game output
    9. Searching in code
    10. Shortcuts
  4. Chapter 04: Scripting API Reference
    1. Script Reference(1.2.0.1)
      1. General
      2. Animation
      3. AI
      4. I3D
      5. Handtools
      6. Events
      7. Objects
      8. Placeables
      9. Triggers
      10. Utils
      11. Vehicles
      12. Specializations
      13. animals
      14. AnimalHusbandryModules
      15. shop
      16. collections
      17. densityMaps
      18. economy
      19. effects
      20. weather
      21. farms
      22. fieldJobs
      23. dialogs
      24. GUI
      25. materials
      26. misc
      27. missions
      28. modHub
      29. Player
      30. sounds
      31. trainSystem
      32. tutorials
      Engine Reference(8.0.0.0)
      1. General
      2. Entity
      3. Node
      4. Scenegraph
      5. Lighting
      6. Camera
      7. Shape
      8. Particle System
      9. Physics
      10. Spline
      11. Animation
      12. Overlays
      13. Sound
      14. Input
      15. XML
      16. Network
      17. Callbacks
      18. Text Rendering
      19. Terrain Detail
      20. Tire Track
      21. Editor
      22. AI
      23. Rendering
      24. String
      25. Math
      26. I3D
      27. Fillplanes
      28. ModDownloadManager
    2. Foundation Reference
      1. Scenegraph
      2. Input
  5. Chapter 05: Tutorials
    1. Tutorial 1 - Load i3d files and basics
    2. Tutorial 2 - Light functions, global time and rendering text
    3. Tutorial 3 - User Attributes
    4. Tutorial 4 - Timers
    5. Tutorial 5 - Physics
    6. Tutorial 6 - Overlays
    7. Tutorial 7 - Audio
  6. Chapter 06: Exporter
    1. Autodesk Maya1 I3D Exporter
      1. Material Export Options
      2. Manual Installation
    2. Autodesk 3ds MAX2 I3D Exporter
      1. Manual Installation
    3. Blender I3D Exporter
  7. Chapter 07: Content Creation - Artwork Guide
    1. Autodesk Maya
    2. Autodesk 3DS MAX
    3. Texturing
  8. Chapter 08: I3D Format
    1. Introduction
    2. Features
    3. Overview
    4. Specification
      1. General Layout
      2. Materials
      3. Shapes
      4. Dynamics
      5. Scenegraph
      6. Animation


Overview



Enable development controls



Open the file game.xml and change the value of controls from false to true.

<?xml version="1.0" encoding="utf-8" standalone="no" ?>
<game>
  ...
  <development>
    <controls>true</controls>
  </development>
</game>


Runtime development key short-cuts


Key Function
~ or ` Toggle console
F2 Show frame rate
F3 Toggle frame rate limiter
F4 Wireframe mode
F5 Toggle debug rendering
F7 Toggle camera
F8 Toggle stats


Console command reference


help

Description
List all available commands

showFps

Description
Show frames per second

enableFramerateLimit

Description
Enable/disable frame per second limiter

framerateLimitFPS

Description
Frame per second limit attribute

listEntities

Description
Print detailed entity list

listResources

Description
Print detailed resource list

parallelRenderingAndPhysics

Description
Enable parallel rendering and physics

exit, quit or q

Description
Quits application






Editor

Table of Contents

  1. Viewport
  2. Scenegraph Panel
  3. Attributes Panel
  4. Toolbar
  5. Terrain Editing
  6. User Attributes
  7. Animation Panel
  8. Particle System Panel
  9. Spline Editing
  10. Scripting
  11. Replace Dialog
  12. Interactive Placement
  13. Other functionality
  14. Keyboard short-cuts



If you start up the Editor, you might not have all the panel windows open. To open other panel windows open the menu option window and enable the panel you want. You can adjust the width and height of the panels by dragging the outlines and if you want to close a window you can simply press the cross right of the panel name.


Viewport




Navigation

The navigation is quite like in Maya. If you have nothing open in your editor I suggest you quickly open a simple i3d file otherwise you won’t see much of an effect. If its to dark in your scene just create a light by going to Create–>Light.

Some shortcuts:
LMB = Left Mouse Button
RMB = Right Mouse Button
MMB = Middle Mouse Button
Alt + LMB = Press and hold the Alt-Key and the left mouse button.

Alt + LMB rotates the camera.
Alt + RMB moves the camera forward and backward.
Alt + MMB causes the camera to pan.

If you don’t have a middle mouse button, you can press LMB and RMB instead.

View Options

By simply right-clicking into the viewport panel you get the View Options. Sometimes it’s useful too use different cameras in a scene. You can create them once and then with the View Options you can choose the camera to view at your scene from different angles quickly.

You might notice that if you rotate, the camera is rotated. If you have a big level this behaviour is very useful, but if you want to look at one particular object this can be quite awkward. To change the rotation to Framed Rotate you first have to select your object either by clicking on it directly or by choosing it from the scene-graph and the framing the selected object by pressing the F key. Now you can simply click (RMB) on the screen to open the View Options and choose Framed Rotate. Now the camera is rotating around your last framed object.

You can select the visual appearance of the object with Shaded (solid surface) or Wireframe (only edges of the object are visible)

If you have large scenes, you can toggle the visibility of lights, audio sources, physics and the cameras by checking them on the show submenu.

You can also use the Selectable submenu to toggle whether you can select lights, audio sources or cameras.

Furthermore you can toggle the grid and the polycount on and off.

Profile gives you the ability to choose different hardware profiles adequate for your system.

Debug can be used to find errors (e.g. on your 3D model)


Scenegraph Panel

A very useful feature of the GIANTS Editor is the scenegraph. If you don’t have it on the screen, just go to menu window and hit scenegraph. It is basically the same you have in Maya. It shows all objects you have in your scene and also the parent-child relationship between your objects.



Let’s just make a little scene with some Transform Groups. The Transform Group is the basic building block of your scene. You can use a TransformGroup to move all the attached objects just by moving the Transform Group since the children inherit the transformations of the parent. To create a new Transform Group go to Create and hit TransformGroup. Now you can see it in the Scenegraph, its name is transform. To change the name just select it and go to the attributes panel. At the very top of the panel you can choose the name of your object. Make two TransformGroups and name them Parent and Child. If you move them around you see that their transformations are independent, the movement of the parent doesn’t affect the child. Now let’s make the appropriate relationship between the two. Select the child in the scenegraph panel and go to Edit->Cut. Now select your parent and hit Edit->Paste. Additionally by pressing MMB on the child, dragging it over parent and releasing MMB, the same as above will happen.

As you can see now, the child is now connected to the parent. If you now move around the parent, the transformation of the child is affected too whereas the child can be moved around without affecting the parent.




There can be 6 types of objects in your scene: Triangle Meshes, Splines, Cameras, Transform Groups, Lights, Terrains and Audio Sources.

It is also possible to use CTRL + C to copy objets, CTRL + X to cut objects and CTRL + V to paste objects. Notice that pasted objects are always children of the currently selected object. If you want to paste an object on the highest hierarchy level of the scenegraph be sure that nothing is selected in the scenegraph. This can be achieved by clicking at an empty space in the scenegraph panel.


Attributes Panel

If you don’t see the attributes panel go to Windows->Attributes then select an object in the scenegraph or the viewport. One important thing to notice is, that if the background color of an attribute turns red, you entered a value that isn’t allowed. (eg scale values other than 1 for a dynamic rigid body object) The background color of animated attributes is yellow.




Toolbar




The toolbar looks like this. If your pointing on the icons with your mouse, a text with the functionality of the tool is displayed.

Let’s quickly go through them from left to right.

File Operations
History
Physics
If you hit the play icon, the physics will simulate.

Toggle Local- World Mode
A handy tool is the toggle Local- World Mode, it changes the orientation of the viewport transform gizmo from the local space of your object to world space.

Grid Snapping
Use this option to snap objects to a predefined grid.

Terrain and Terrain Foliage
Texture Reload
Script Editor


Terrain Editing




To test the terrain sculpting, just open the terrain test scene. Now you have a terrain to play with. Open the terrain editing panel with window->Terrain Editing. (If the scenegraph panel is still open it might cut off a bit, just close it to get more space.)



If the terrain sculpt mode is active now, you can rise or lower the surface of your terrain by using RMB and LMB. MMB can be used to smooth and the value defines the force with which you pull or push. What happens here is, that you are painting a height map, that defines the height of each point of your terrain by giving it a grey-value. The attributes Opacity, Hardness and the Value are defining the "brush" you are painting the height map with. Just play around with the setting. You can change the radius of the brush with the shortcuts "V" and "B" and you can change the opacity value of the brush quickly with "N" and "M".

In the terrain texture paint mode next to the terrain sculpt icon you can colorize your terrain with different textures.
The used texture layers are defined in the i3d-file. (If you want to change the texture layers, you have to open the i3d with a text editor and change the layers there) Just choose your texture and paint onto your terrain. With the Chunk vis checkbox on, you can see exactly which texture layers you used in a chunk by what amout. You can use as many texture layers as you want, but you are limited to a maximum of four texture layers per chunk.

With the Terrain Foliage Paint Mode active, you can paint your foliage onto your terrain, it`s the same thing as if you would paint onto your terrain - not with a texture but with foliage. LMB adds foliage, RMB removes foliage.


User Attributes




The user attributes panel is typically not visible if you open the editor for the first time. So go to Windows->User Attributes. Select an object in the scenegraph to see its user attributes.

User Attributes can be defined in the editor and then be used in the engine (eg. within a script). This enables you to define object specific attributes for every object in the scene.


Animation Panel




You can preview animation sets with the animation panel.

Particle System Panel




The particle system panel allows you to edit particle systems with real time preview.

Spline Editing




You can edit splines by picking a control vertex (CV) of a spline an moving it around. Delete or insert new control vertices with the keys delete and insert.

Scripting

Here you can execute script snippets. With ENTER, you can add new lines. SHIFT+ENTER will execute the code in the text field.

Type in the following:

print("hello world from the GIANTS Editor");

Then hit SHIFT + ENTER and the string is printed out above.


The scripting can be useful for many things. For example you can run this script snippet to test the fog settings in an i3d scene:

setFog("exp2", 0.002, 0, 0.8, 0.81, 0.97);


Replace Dialog




If you want to replace an object in your scene, you can go to Edit->Replace to open the replace panel. Select the object you want to replace, then hit load. Do likewise with the object you want to replace with and choose whether you want to keep the User Attributes or not. Now you can replace one single object by hitting replace or you can replace all objects that are similar to the one you selected by hitting replace all.

Note: replace all does only work with single objects, but not with hierarchies of objects, however the single replace function works.
This feature is quite useful because you can use it to substitute an object reference feature within your i3d scene file.


Interactive Placement

This is a really nice feature of the editor, you should try it at least once!
To place an object on the surface of another object, you can simply select the object you want to place and then press CTRL + B + LMB, while pointing at your desired location. The selected object will then instantly be set to the location you’ve chosen.

Hint: you can do this with all your objects within your scenegraph and also with the camera or light sources. E.g. you can select the current camera and then place the camera at a location far away, allowing for fast relocation of the camera.

If you keep the LMB pressed and hit SHIFT or CRTL you can clone the selected object at the currect mouse position. SHIFT will just clone the object while CRTL will add a random rotation in the Y-axis. (Useful feature if you want to create a group with hundreds of randomly rotated objects like a forest)

Other functionality


Edit->Clear History: This clears the undo/redo history.

Edit->Move to Camera: Moves the selected object in front of the current camera

Navigation Speed: Moves the camera faster or slower. Use - and + to ajust the speed.


Default keyboard short-cuts

Key Function
W A S D Navigation
Alt + LMB Rotate camera
Alt + MMB Pan camera
Alt + RMB Zoom camera
Alt + LMB + RMB Move camera up or down and left or right camera
F Frame selected object
- Decrease navigation speed
+ Increase navigation speed
4 Wireframe mode
6 Shaded mode
Ctrl-S Save
Ctrl-Z Undo
Ctrl-W Replace Dialog
Ctrl-X Cut
Ctrl-C Copy
Ctrl-V Paste
Ctrl-Shift-C Copy X,Y,Z components at once
Ctrl-Shift-V Paste X,Y,Z components at once (can also be copied from a text source in the format "x y z")
Delete Delete
Ctrl-D Duplicate
Ctrl-F Move to Camera
Ctrl-B Interactive placement (hold left mouse button to move around)
Shift Interactive placement paint
Ctrl Interactive placement paint with random rotation around y axis
Ctrl-H Hide object
Shift-H Show object
Ctrl-G Group objects
Ctrl-R Pick replace value in viewport (Terrain edit modes)
V Decrease brush radius
B Increase brush radius
N Decrease brush opacity
M Increase brush opacity
F8 Toggle stats
Shift + Enter Execute Script (Script Window)
X Absolute grid snapping
J Relative grid snapping
Delete Delete spline control vertex
Insert Insert new spline control vertex
Left Previous spline control vertex
Right Next spline control vertex
Up or Down First spline control vertex
S Stitch spline endpoints
O Toggle spline open/close
R Reverse spline
Ctrl-L Create light


Debugger

Table of Contents

  1. GIANTS Debugger
  2. Overview of panels
  3. Creating a new project
  4. Global and local variables
  5. Callstack panel
  6. Running new scripts during debugging
  7. Breakpoints
  8. Game output
  9. Searching in code
  10. Shortcuts

GIANTS Debugger

The GIANTS Debugger is a new tool for creating, editing and debugging script mods. It works as an editor and a “remote” debugger in one. It interacts with the game state and provides you with information about the game state.

Possible use-case scenarios:

The Debugger can be used on all kinds of mod configurations. These are the most common three configurations:

Working on a single mod (fast iteration time, but only compatible with singeplayer):
Unzip your mod and put the mod in the “mods” directory (by default in Documents/My Games/FarmingSimulator2019/mods). Make sure that the layout of the mod is correct, i.e. the modDesc.xml is directly in the mod folder (i.e. mods//modDesc.xml). Then create a new project in the Debugger. In “Project Settings”, set “Mod Name” to be the same name as the name of the mod folder and set the “Mod Directory” as a path to the directory of the mod (mods/). In case the mod zip file is already in the “mods” directory remove the zip file for the “mods”, because the zip file has priority over the directory when the game is loading.

Working on multiple mods at the same time (fast iteration time, but only compatible with singeplayer):
Follow the instructions above, but when you create a project in the Debugger, set the “Mod Directory” to “mods” directory instead of the specific mod directory. This way you can edit several mods at the same time. In this configuration, the “Mod Name” is not important, you can call it anything you like.

Working on a single mod outside the “mods” directory (also compatible with multiplayer):
This is the most complex configuration, and it is the only one that lets you debug mods in multiplayer. Place the mod zip file in the “mods” directory and unzip it somewhere else. In “Project Settings” set the “Mod Name” to match with the name of the zip file but without .zip at the end) and set the “Mod Directory” as a path to the unzipped directory. For every change you make in the Debugger, you will have to re-create the mod zip file and copy it to the “mods” directory before you start the game. External tools for zipping are useful for this purpose (not included).


Overview of panels



Creating a new project

First you need to open or create a project.


Most of the required parameters are self-explanatory. The “Mod Directory” can be a path to a single mod or a “mods” directory if you are working on several mods at the same time. If you are working on a single mod, the “Mod Name” must have the same name as the .zip file. The “User Profile App Directory” should be saved as a path to a folder where the game stores user data (changes are not needed by default if the game configuration has not been changed manually). The debugger uses sockets to communicate with the game and listens at the port defined as the “Debug Network Port”.


Global and local variables

The function of the “Globals” and “Locals” panels is the same: to explore the value of local and global variables at a current execution point (using breakpoints to halt execution and observe these variables, or by hitting the ‘break all’ button). By right-clicking on a variable, you can add it as a “Watch” or a “Breakpoint”.


The ”Watch” panel is similar to the “Globals” and “Locals” panel, but instead of global or local variables, you can select variables that you would like to ‘watch’. Values are updated every time a breakpoint is hit or when you execute the code step-by-step. Variable names can be written like most other simple Lua statements:



Callstack panel

The “Callstack” panel shows you the callstack at a current execution point. Double-click on a line to open a file at the location of the call. The Debugger even allows you step through some of the base game functions for which the source code has been made public. Grayed-out lines are parts of code that have not been made public.



Running new scripts during debugging

The “Script Console” executes user-defined Lua code when execution is paused (by hitting a breakpoint or break-all being pressed). Enter your code in the bottom part of the panel and press Ctrl + Enter to execute it.



Breakpoints

The “Breakpoints” panel is where you manage breakpoints.

Regular breakpoints can be placed in the code by clicking on the vertical gray bar on the left of the code panel. You can also use F9 to enable/disable a breakpoint at the current position. The program will stop running when it tries to execute a line with a breakpoint.

Data breakpoints can be placed by right-clicking on a variable name in the “Globals”/”Locals”/”Watch” panel or by right-clicking on a name in the text editor. A data breakpoint will be hit when the data for the specified variable changes.


You can fine-tune a breakpoint by adding a conditional expression and/or hit count condition to it. These conditions are evaluated each time a breakpoint is hit and the code will only stop executing once the conditions are met.



Game output

The “Output” panel shows the game’s log output. If a script error is reported, this panel will provide you with the file name and line number, so that you can double-click on it and view the code causing the error. The output is the same as the log file written by the game.



Searching in code

The “Find Results” panel shows search results from the “Find in Files” dialog. Double-clicking on a result opens a file at the search hit location.


The “Find Replace” window behaves in a similar way to other text editors. “Find” and “Replace” directly show the results in the text editor; while “Find in Files” searches through the entire file and shows results in the “Find Results” panel. Other search modes are available too:





Default keyboard short-cuts

KeyFunction
Ctrl-NNew file
Ctrl-OOpen file
Ctrl-SSave file
Ctrl-Shift-SSave all files
Ctrl-QQuit application
Ctrl-ZUndo
Ctrl-YRedo
Ctrl-FFind
Ctrl-HReplace
Ctrl-Shift-FFind in files
F3Find next
Shift-F3Find previous
Ctrl-Shift-GGo to file
Ctrl-GGo to line
Ctrl-KComment lines
Ctrl-Shift-KUncomment lines
Ctrl-WClose tab
Ctrl-Shift-TReopen tab
Alt-UpMove line up
Alt-DownMove line down
Alt-LeftNavigate backwards
Alt-RightNavigate forward
F5Run / Continue execution
Ctrl-F5Run Without Debugging
F7Pause execution
F6Stop execution
F9Toggle Breakpoint
F11Step Into
F10Step Over
Shift-F11Step Out

Scripting API Reference

Script Version: 1.2.0.1

AchievementMessage

Description
Achievement message display element.
-- Used to display a message in the HUD when a new achievement is unlocked.
--@category GUI

new

Description
Create a new instance of AchievementMessage.
Definition
new(string hudAtlasPath, table inputManager, table guiSoundPlayer, ContextActionDisplay ContextActionDisplay)
Arguments
stringhudAtlasPathPath the HUD texture atlas
tableinputManagerInputBinding reference for achievement acknowledgment input
tableguiSoundPlayerGuiSoundPlayer reference for playing a sound cue
ContextActionDisplayContextActionDisplayreference for visibility checks (it occupies the same space on the HUD)
Return Values
tableAchievementMessageinstance

onMenuVisibilityChange

Description
Handle changes in menu visibility.
Keeps track of menu visibility state to avoid showing (or updating) an achievement message when the menu is active.
Definition
onMenuVisibilityChange()

showMessage

Description
Show an achievement message.
The message will be shown as soon as the player is not in a menu and there is no context action display visible.
Messages will however not be checked for overlaps. The caller has to make sure that achievements are displayed
sequentially.
Definition
showMessage(string title, string description, string iconFilename, table iconUVs, float duration)
Arguments
stringtitleAchievement title text
stringdescriptionAchievement description text
stringiconFilenamePath to the achievement icon texture
tableiconUVsUV coordinates of achievement icon with icon texture
floatdurationMaximum display duration in milliseconds

update

Description
Update display state.
Definition
update()

beginShowMessage

Description
Actually start showing the message when nothing is obstructing the view.
Definition
beginShowMessage()

hideMessage

Description
Hide the message, including animation.
Also removes the acknowledgment input events.
Definition
hideMessage()

draw

Description
Draw the achievement message if necessary.
Definition
draw()

storeScaledValues

Description
Store scaled positioning, size and offset values.
Definition
storeScaledValues()

setScale

Description
Set this element's scale.
Definition
setScale()

getBackgroundPosition

Description
Get the position of the background element, which provides this element's absolute position.
Definition
getBackgroundPosition(scale Current, float width)
Arguments
scaleCurrentUI scale
floatwidthScaled background width in pixels
Return Values
floatXposition in screen space
floatYposition in screen space

createBackground

Description
Create the empty background overlay
Definition
createBackground()

createComponents

Description
Create required display components.
Definition
createComponents()

createFrame

Description
Create the message frame.
Definition
createFrame()

createIcon

Description
Create the achievement icon.
Definition
createIcon()

AnimalScreen

Description
Animal Buying Screen.
AnimalScreen = {}

new

Description
Constructor
Definition
new(table target, table metatable)
Arguments
tabletarget
tablemetatable
Return Values
tableselfinstance
Code
53function AnimalScreen:new(target, custom_mt, animalController, l10n, messageCenter)
54 local self = ScreenElement:new(target, custom_mt or AnimalScreen_mt)
55
56 self:registerControls(AnimalScreen.CONTROLS)
57
58 self.l10n = l10n
59 self.messageCenter = messageCenter
60 self.animalController = animalController
61
62 self.animalController:setSourceUpdateCallback(self.onSourceUpdate, self)
63 self.animalController:setTargetUpdateCallback(self.onTargetUpdate, self)
64 self.animalController:setNoValidHusbandryCallback(self.onNoValidHusbandry, self)
65 self.animalController:setHusbandryIsFullCallback(self.onHusbandryIsFull, self)
66 self.animalController:setTrailerFullCallback(self.onTrailerIsFull, self)
67 self.animalController:setInvalidAnimalTypeCallback(self.onInvalidAnimalType, self)
68 self.animalController:setAnimalNotSupportedByTrailerCallback(self.onAnimalNotSupportedByTrailer, self)
69 self.animalController:setNotEnoughMoneyCallback(self.onNotEnoughMoney, self)
70 self.animalController:setCanNotAddToTrailerCallback(self.onCanNotAddToTrailer, self)
71 self.animalController:setAnimalInUseCallback(self.onAnimalInUse, self)
72
73 self.isSourceSelected = true
74
75 self.isOpen = false
76 self.lastBalance = 0
77 self.sourceElementToAnimal = {}
78 self.targetElementToAnimal = {}
79
80 self.dofState = DepthOfFieldState.createFullscreenBlur()
81
82 return self
83end

onOpen

Description
Callback on open
Definition
onOpen()
Code
87function AnimalScreen:onOpen()
88 AnimalScreen:superClass().onOpen(self)
89
90 self.isOpen = true
91 self.isUpdating = false
92
93 g_gameStateManager:setGameState(GameState.MENU_ANIMAL_SHOP)
94
95 self.dofState:recordState() -- record current state before changing
96 self.dofState:apply() -- apply blur effect
97
98 self:updateScreen()
99
100 self.messageCenter:subscribe(MessageType.HUSBANDRY_ANIMALS_CHANGED, self.onAnimalsChanged, self)
101end

onClose

Description
Callback on close
Definition
onClose(table element)
Arguments
tableelement
Code
106function AnimalScreen:onClose(element)
107 AnimalScreen:superClass().onClose(self)
108 self.animalController:close()
109 self.isOpen = false
110 self.sourceElementToAnimal = {}
111
112 g_currentMission:resetGameState()
113
114 self.messageCenter:unsubscribeAll(self)
115
116 self.dofState:reset() -- reset depth of field parameters (blur effect)
117end

onClickBack

Description
Callback on click back
Definition
onClickBack()
Code
262function AnimalScreen:onClickBack()
263 AnimalScreen:superClass().onClickBack(self)
264 self:changeScreen(nil)
265end

onClickOk

Description
Callback on click cancel
Definition
onClickOk()
Code
269function AnimalScreen:onClickOk()
270 AnimalScreen:superClass().onClickOk(self)
271
272 if self.isSourceSelected then
273 self.animalController:moveToTarget(self.listSource.selectedIndex)
274 else
275 self.animalController:moveToSource(self.listTarget.selectedIndex)
276 end
277end

BaseMission

Description
Input context name for identification, does not take care of proper context handling

new

Description
Create a new base mission
Definition
new(string baseDirectory, table customMt, table missionCollaborators)
Arguments
stringbaseDirectoryMission scripts base directory
tablecustomMtSub-class meta table
tablemissionCollaboratorsMissionCollaborators object containing a defined collection required object
references for a mission.

initialize

Description
Initialize mission after instantiation.
Create complex members and call dependency methods in here so that mission instantiation cannot fail.
Definition
initialize()

createHUD

Description
Create the in-game HUD display.
Definition
createHUD()

addHelpButtonText

Description
Deprecated: Replaced by InputBinding:setActionEventText()
Definition
addHelpButtonText()

subscribeSettingsChangeMessages

Description
Subscribe to relevant game settings changes.
Definition
subscribeSettingsChangeMessages()

subscribeGuiOpenCloseMessages

Description
Subscribe to GUI notifications of opening and closing.
Definition
subscribeGuiOpenCloseMessages()

onBeforeMenuOpen

Description
Handle a menu open event.
Definition
onBeforeMenuOpen()

onAfterMenuClose

Description
Handle a menu closed event.
Definition
onAfterMenuClose()

registerActionEvents

Description
Register required input action events.
Definition
registerActionEvents()

registerPauseActionEvents

Description
Register action events for pause actions.
Event registration in this method is enclosed in an input binding registration context (InputBinding:beginActionEventsModification()).
Make sure that this is only called when all other registration-context altering code is done.
Definition
registerPauseActionEvents()

onPause

Description
Input event for "pause".
Definition
onPause()

onConsoleAcceptPause

Description
Input event for breaking pause on consoles.
Definition
onConsoleAcceptPause()

onToggleHelpText

Description
Input event for "toggle help text".
Definition
onToggleHelpText()

onSwitchVehicle

Description
Input event for "switch vehicle".
Definition
onSwitchVehicle(directionValue Numeric)
Arguments
directionValueNumericvalue for switch direction, 1 is the next, -1 is the previous vehicle

Binding

Description
Binding of input to actions.
--@category Input
--@xmlConfig binding#device Device ID, must match a value returned by engine function getGamepadId() or one of the
constants of InputDevice.DEFAULT_DEVICE_NAMES.

new

Description
Create a new Binding instance.
Definition
new(action InputAction, deviceId ID, axisNames List, axisComponent Component, inputComponent Component, index Binding)
Arguments
actionInputActionreference which is being bound to an input
deviceIdIDof the input device whose input is being bound to the given action
axisNamesListof input axis names. If the list contains more than one axis, any axis before the last one is a modifier.
axisComponentComponentof the last given axis to bind to the given action.
inputComponentComponentof a physical axis (e.g. analog stick) to bind
indexBindingindex, 1 primary, 2 secondary, etc.
Return Values
booltrueif allowed
NewBindinginstance

createFromXML

Description
Create a new Binding instance from an XML element.
Definition
createFromXML(int xmlFile, string elementTag, bool isLocked)
Arguments
intxmlFileXML file handle
stringelementTagTag of the element to parse as a Binding
boolisLockedIf true, the binding belongs to a locked action
Return Values
booleanisAllowedtrue if fillType is supported else false
Bindinginstanceinitialized with values from XML and the given parameters

saveToXMLFile

Description
Save this binding to XML.
Definition
saveToXMLFile(xmlFile Input, elementTag Element)
Arguments
xmlFileInputbinding settings XML file handle
elementTagElementtag of this binding
Return Values
booleanisSupportedtrue if fillType is supported else false

updateData

Description
Update a binding with a new input target.
Always use this method to change existing bindings or risk invalid state.
Definition
updateData(deviceId (New), axisNames List, inputComponent [optional])
Arguments
deviceId(New)device ID
axisNamesListof input axis names. Make sure these are valid in the context of this binding's state (i.e. device and action axis type).
inputComponent[optional]Direction of a physical axis (e.g. analog stick) to bind, defaults to positive.
Return Values
floatfreeCapacityfree capacity

updateInput

Description
Update this binding's input state.
Definition
updateInput(inputValue Current)
Arguments
inputValueCurrentinput value of the last axis in self.axisNames
Return Values
booleanisAllowedtrue if toolType is allowed else false

setIsAnalog

Description
Set this binding's analog input flag.
Definition
setIsAnalog()
Return Values
tableinstanceinstance of object

setIndex

Description
Set this binding's index and update internal state.
Definition
setIndex()
Return Values
tableinstanceinstance of object

setActive

Description
Set this binding's active state.
Only active bindings are updated and can trigger action events.
Definition
setActive()
Return Values
integerharvestPixelsSumharvest of pixels sum
integerharvestNumPixelsharvest number of pixels
floatsprayFactorspray factor
floatplowFactorplow factor
floatlimeFactorlime factor
floatweedFactorweed factor
integergrowthStategrowth state
floatmaxAreamax area

setFrameTriggered

Description
Set the frame trigger flag which shows if this binding has triggered an event this frame.
Definition
setFrameTriggered()

getFrameTriggered

Description
Get the frame trigger flag which shows if this binding has triggered an event this frame.
Definition
getFrameTriggered()

setComboMask

Description
Set and store the combo bit mask for this binding.
This is agnostic of the actually bound device because a binding can only map input on one specific device.
Definition
setComboMask(int comboMask)
Arguments
intcomboMaskCombo mask

getComboMask

Description
Get the combo bit mask.
Definition
getComboMask()
Return Values
intCombobit mask

hasCollisionWith

Description
Check if there is a collision between this binding and another one.
Two bindings collide if they bind the same input on the same axes of the same device.
Definition
hasCollisionWith(otherBinding Other)
Arguments
otherBindingOtherbinding to check for collision
Return Values
Trueifthere is a collision.

isAlternativeTo

Description
Check if this binding is an alternative to another one on the same action.
Two bindings are alternatives if they bind different input on the same axis of the same device category to the same action.
Definition
isAlternativeTo(otherBinding Other)
Arguments
otherBindingOtherbinding to check if it's an alternative
Return Values
Trueifthis and the other binding are alternatives of each other

clone

Description
Create a new instance of Binding with the same state as this instance.
Definition
clone()
Return Values
ClonedBindinginstance

copyInputStateFrom

Description
Copy binding input state from another binding.
Definition
copyInputStateFrom()
Return Values
integerretret
integertotaltotal

isSameSlot

Description
Check if this binding occupies the same binding slot as another binding on the same action.
Definition
isSameSlot()

getOppositeAxisComponent

Description
Get the opposite axis component for a given axis component.
Definition
getOppositeAxisComponent(axisComponent One)
Arguments
axisComponentOneof the constant values of Binding.AXIS_COMPONENT
Return Values
integerchangedValuechanged value

getOppositeInputComponent

Description
Get the opposite input component for a given input component.
Definition
getOppositeInputComponent(inputComponent One)
Arguments
inputComponentOneof the constant values of Binding.INPUT_COMPONENT
Return Values
integerchangedAreachanged area pixels
integertotalAreatotal area

makeId

Description
Make and assign a binding ID.
Definition
makeId()

needJapanesePlaystationButtonSwap

Description
Determine if we need to swap buttons for Japanese Playstation controllers by their convention.
Definition
needJapanesePlaystationButtonSwap()
Return Values
integerchangedAreachanged area pixels
integertotalAreatotal area pixles

swapJapanesePlaystationButtons

Description
Swaps buttons for Japanese Playstation controllers if contained in the given axis names.
Definition
swapJapanesePlaystationButtons(table axisNames)
Arguments
tableaxisNamesAxis names array, will be changed in place

toString

Description
Get a string representation of this binding.
Definition
toString()
Return Values
integernumPixelsnumber of pixels
integertotalNumPixelstotal number of pixels

BitmapElement

Description
Display element for images.
-- Used layers: "image" for the display image.
--@xmlConfig GuiElement#offset string [optional] Position offset of the displayed image relative to this element's origin in reference resolution, defaults to [0, 0]. Format: "[x]px [y]px".

setImageColor

Description
Set this element's image color.
Omitted (nil value) color values have no effect and the previously set value for that channel is used.
Definition
setImageColor(state GuiOverlay, r Red, g Green, b Blue, a Alpha)
Arguments
stateGuiOverlaystate for which the color is changed, use nil to set the default color
rRedcolor value
gGreencolor value
bBluecolor value
aAlphavalue (transparency)

setImageRotation

Description
Set this element's image overlay's rotation.
Definition
setImageRotation(float rotation)
Arguments
floatrotationRotation in radians

BoxLayoutElement

Description
Layout element which lays out child elements in regular rows or columns.
-- Exceptions are elements whose "layoutIgnore" property is true.
-- Used layers: "image" for a background image.
--@category GUI
--@xmlConfig GuiElement#alignmentX string [optional] Horizontal alignment of the layout, defaults to "left". Valid values are "left", "right" and "center".

getLayoutCells

Description
Extract a flow / cell data table from this box layout's elements.
Definition
getLayoutCells(ignoreVisibility Visibility)
Arguments
ignoreVisibilityVisibilityflag for element eligibility
Return Values
Flowsandcells as nested tables: [flowIndex][cell index] = cell data {element, flowSize, lateralSize}

getLayoutSizes

Description
Calculate layout sizes based on flow cell data.
Definition
getLayoutSizes()
Return Values
Listoflateral flow sizes, total lateral sizes (sum of lateral flow sizes), maximum flow size in direction of flow

getAlignmentOffset

Description
Get the layout space starting position offset for elements based on flow dimensions and alignments.
Definition
getAlignmentOffset(flowSize Flow, flowLateralSize Total)
Arguments
flowSizeFlowsize in flow direction (e.g. height for vertical flows)
flowLateralSizeTotalflow size orthogonal to flow direction (e.g. combined width of all columns for vertical flows)
Return Values
LayoutXstarting offset, layout Y starting offset, Layout X direction {-1|1}, Layout Y direction {-1|1}

getElementAlignmentOffset

Description
Calculate element offsets for margins and to counteract alignment updates in GuiElement.updateAbsolutePositions()
Definition
getElementAlignmentOffset(directionX Layout, directionY Layout)
Arguments
directionXLayoutX direction as a signed factor {-1|1}
directionYLayoutY direction as a signed factor {-1|1}
Return Values
elementXoffset, element Y offset

applyCellPositions

Description
Apply layout positions to all given cells' elements.
Definition
applyCellPositions(flowCells List, offsetStartX Layout, offsetStartY Layout, directionX Layout, directionY Layout, lateralFlowSizes List)
Arguments
flowCellsListof flows and their cell data
offsetStartXLayoutX starting offset
offsetStartYLayoutY starting offset
directionXLayoutX direction as a signed factor {-1|1}
directionYLayoutY direction as a signed factor {-1|1}
lateralFlowSizesListof lateral flow sizes (e.g. widths of columns in vertical flows)

focusLinkCells

Description
Link layout cells' elements for focus navigation.
Definition
focusLinkCells(flowCells List)
Arguments
flowCellsListof flows and their cell data

focusLinkChildElement

Description
Link a child element to others for focus navigation
Definition
focusLinkChildElement(element Current, previousElement Element, firstElement First, lastElement Last)
Arguments
elementCurrentelement
previousElementElementat previous position in layout flow, will be nil when the first element is being processed
firstElementFirstelement in layout
lastElementLastelement in layout

invalidateLayout

Description
Invalidate the layout, will reposition all elements and update focus navigation.
Definition
invalidateLayout(ignoreVisibility If)
Arguments
ignoreVisibilityIftrue, elements will be considered for layouting even if invisible

getFocusTarget

Description
Return the actual focus target when this box layout is being focused. This can be a previously focused element within
the layout (depends on rememberLastFocus attribute), a programmatically defined entry point based on the incoming
direction or simply the first layout element (when no other options apply).
Definition
getFocusTarget(incomingDirection Focus, moveDirection Actual)
Arguments
incomingDirectionFocusnavigation direction from where this layout is being entered
moveDirectionActualfocus navigation direction per input
Return Values
GuiElementwhichshould receive focus instead

ButtonElement

Description
Clickable button element.
-- Used layers: "image" for the background, "icon" for a button glyph.
-- All button UI callbacks do not require or provide any arguments.
--@category GUI
--@xmlConfig GuiElement#iconSize string [optional] Pixel size of button glyph in reference resolution. Format: "[width]px [height]px"

loadInputGlyphColors

Description
Load glyph overlay colors.
Definition
loadInputGlyphColors(profile If, xmlFile If, key XML)
Arguments
profileIfset, loads overlay properties from this button's GUI profile
xmlFileIfset, loads overlay properties from this button's XML configuration
keyXMLbase configuration node of this button

loadInputGlyph

Description
Load the actual input glyph symbols to display if an input action is defined on the button.
Definition
loadInputGlyph()

setKeyboardMode

Description
Set the keyboard mode flag.
Definition
setKeyboardMode()

setInputAction

Description
Set the input action for the display glyph by name.
Definition
setInputAction()

setImageUVs

Description
Set UV coordinates for the button background and/or icon.
Definition
setImageUVs()

getIsSelected

Description
Determine if this button is selected
Definition
getIsSelected()

getIsHighlighted

Description
Determine if this button is highlighted
Definition
getIsHighlighted()

getIconModifiedTextOffset

Description
Get modified text offset including changes from icon position and dimensions.
Definition
getIconModifiedTextOffset(float textOffsetX, float textOffsetY)
Arguments
floattextOffsetXScreen space text X offset
floattextOffsetYScreen space text Y offset
Return Values
floatModifiedX offset
floatModifiedY offset

getTextOffset

Description
Get text offset from element position including modifications from icon.
Definition
getTextOffset()

getText2Offset

Description
Get shadow text offset from element position including modifications from icon.
Definition
getText2Offset()

getIconSize

Description
Get the current icon size in screen space.
Definition
getIconSize()

updateSize

Description
Update size of element depending on content
Definition
updateSize()

ButtonOverlay

Description
Keyboard button display overlay.
-- Overlay type which displays a keyboard key button symbol.
--@category GUI

delete

Description
Delete this button overlay.
Definition
delete()

setColor

Description
Set this overlay's background color.
Definition
setColor(r Red, g Green, b Blue, a Alpha)
Arguments
rRedchannel [0, 1]
gGreenchannel [0, 1]
bBluechannel [0, 1]
aAlpha(transparency) channel [0, 1], 0 is fully transparent, 1 is opaque

renderButton

Description
Render this overlay with the given parameters.
Definition
renderButton(buttonText Text, posX Screen, posY Screen, height Button, alignment Text)
Arguments
buttonTextTextto display as the key value, e.g. "A", "Space", "Ctrl", etc.
posXScreenx position
posYScreeny position
heightButtondisplay height
alignmentTextalignment, one of the constants of RenderText.ALIGN_[...]

getButtonWidth

Description
Get the total display width of this button overlay for a given button text and height
Definition
getButtonWidth()

CareerScreen

Description
Career Screen.
Displays available save game slots.
-- @field savegameList Save game list

setIsWaitingForSaveGameInfo

Description
Set UI waiting state, which displays or hides a dialog that says to wait.
Definition
setIsWaitingForSaveGameInfo()

CharacterCreationScreen

Description
Character Selection Screen.

setCharacterIndex

Description
Set the index of the character. Is turned into a player and body pair.
Definition
setCharacterIndex()

updateCharacterWithSettings

Description
Update the character with the currently configured options.
Definition
updateCharacterWithSettings()

updateCharacter

Description
Update the character to match given options. Only reloads object if needed.
Definition
updateCharacter()

loadCharacterFinished

Description
Loading of the character object finished
Definition
loadCharacterFinished()

updateCharacterOptions

Description
Update the existing character with options that can be changed
Definition
updateCharacterOptions()

setHatHairNodeVisibility

Description
Set the visbility of the 'hat hair': special hair when wearing a hat
Definition
setHatHairNodeVisibility()

ChatDialog

Description
Multiplayer chat dialog
-- @field textElement User chat message input element

onMenuAxisUpDown

Description
Handle menu up/down input.
Scrolls through the chat history.
Definition
onMenuAxisUpDown()

ChatWindow

Description
HUD chat window.
-- Displays chat messages.
--@category GUI

new

Description
Create a new ChatWindow.
Definition
new(string hudAtlasPath)
Arguments
stringhudAtlasPathPath to the HUD atlas texture.
Return Values
tableChatWindowinstance

setChatMessages

Description
Set the chat message history reference for displaying.
The array is owned by the caller and must not be modified.
Definition
setChatMessages(table messages)
Arguments
tablemessagesMessages array as {i={msg=<message text>, sender=<sender user nickname>}}

scrollChatMessages

Description
Scroll chat messages by a given amount.
Definition
scrollChatMessages(int delta, int numMessages)
Arguments
intdeltaNumber of lines (positive or negative) to scroll
intnumMessagesNumber of currently stored chat messages

onMenuVisibilityChange

Description
Handle menu visibility state change.
Definition
onMenuVisibilityChange()

update

Description
Update element state.
Definition
update()

draw

Description
Draw the chat window.
Definition
draw()

setScale

Description
Set this element's UI scale.
Definition
setScale()

getBackgroundPosition

Description
Get this element's base background position.
Definition
getBackgroundPosition(float uiScale)
Arguments
floatuiScaleCurrent UI scale factor

storeScaledValues

Description
Store scaled positioning, size and offset values.
Definition
storeScaledValues()

createBackground

Description
Create the background overlay.
Definition
createBackground()

ColorPickerDialog

Description
Color Picker Dialog
-- Lets the player pick from a set of colors.
-- @field buttonTemplate Color button template which is cloned per color

setColors

Description
Set colors after opening.
Definition
setColors(table colors, table defaultColor)
Arguments
tablecolorsArray of colors {i={r, g, b, a}, or {i={name="name", color={r,g,b,a}}}
tabledefaultColorDefault color setting as {r, g, b, a}, must be contained in colors array

focusLinkColorButtons

Description
Apply custom grid-based focus linking
Definition
focusLinkColorButtons()

setInitialFocus

Description
Set the initial focus when entering this dialog.
Definition
setInitialFocus()

setCallback

Description
Set the dialog callback.
Definition
setCallback()

onClickColorButton

Description
Handle activation of a color button.
Definition
onClickColorButton()

ContextActionDisplay

Description
Player context action display element.
-- Displays information about the current interaction context. Includes action names and current input scheme button
glyphs.
--@category GUI

new

Description
Create a new instance of ContextActionDisplay.
Definition
new(string hudAtlasPath)
Arguments
stringhudAtlasPathPath to the HUD texture atlas

setContext

Description
Sets the current action context.
This must be called each frame when a given context is active. The highest priority context is displayed or the one
which was set the latest if two or more contexts have the same priority.
Definition
setContext(string contextAction, string contextIconName, string targetText, int priority, string actionText)
Arguments
stringcontextActionInput action name of the context action
stringcontextIconNameName of the icon to display for the action context, use one of ContextActionDisplay.CONTEXT_ICON
stringtargetTextDisplay text which describes the context action target
intpriority[optional, default=0] Context priority, a higher number has higher priority.
stringactionText[optional] Context action description, if different from context action description

update

Description
Update the context action display state.
Definition
update()

resetContext

Description
Reset context state after drawing.
The context must be set anew on each frame.
Definition
resetContext()

draw

Description
Draw the context action display.
Definition
draw()

setScale

Description
Set the scale of this element.
Definition
setScale()

storeScaledValues

Description
Store scaled positioning, size and offset values.
Definition
storeScaledValues()

getBackgroundPosition

Description
Get the position of the background element, which provides this element's absolute position.
Definition
getBackgroundPosition(scale Current, float width)
Arguments
scaleCurrentUI scale
floatwidthScaled background width in pixels
Return Values
floatXposition in screen space
floatYposition in screen space

createBackground

Description
Create an empty background overlay as a base frame for this element.
Definition
createBackground()

createComponents

Description
Create display components.
Definition
createComponents(string hudAtlasPath, table inputDisplayManager)
Arguments
stringhudAtlasPathPath to HUD atlas texture
tableinputDisplayManagerInputDisplayManager reference

createInputGlyph

Description
Create the input glyph element.
Definition
createInputGlyph()

createFrame

Description
Create the context display frame.
Definition
createFrame()

createActionIcons

Description
Create action context icons.
Only one of these will be visible at any time.
Definition
createActionIcons()

ControlsController

Description
Controls settings controller.
-- Handles the input controls model and control logic for settings screen controls pages.
--@category GUI

new

Description
Create a new ControlsController instance.
Definition
new()

setMessageCallback

Description
Set a callback for displaying status messages.
Callback signature: messageCallback(messageId, additionalText, addLine)
Definition
setMessageCallback(messageCallback A)
Arguments
messageCallbackAfunction which takes a message ID (see class constants), a optional list of additional strings and an optional addition flag (add instead of overwrite) to display a message.

setInputDoneCallback

Description
Set a callback to react on input capture completion.
Callback signature: inputDoneCallback(madeChange)
Definition
setInputDoneCallback(inputDoneCallback A)
Arguments
inputDoneCallbackAfunction to notify a collaborator that input gathering has finished and if there were any changes.

createDisplayAction

Description
Create a display action for displaying from bindings for a given axis direction.
Definition
createDisplayAction(deviceCategory Device, actionBinding Action, isAxisPositive If)
Arguments
deviceCategoryDevicecategory, only bindings of devices of this category are displayed
actionBindingActionbinding table reference: {action=Action, bindings={1=binding1, 2=binding2, ...}}
isAxisPositiveIftrue, the display action should show a positive action axis.
Return Values
{name="internalName",displayName="displayName",inputTexts={1=text1, 2=text2, ...}, inputBindings={1=binding1, 2=binding2, ...}, positiveInput=[true|false]}

getDeviceCategoryActionBindings

Description
Get available action bindings per device category, including current changes (even before saving).
Definition
getDeviceCategoryActionBindings(deviceCategory Device)
Arguments
deviceCategoryDevicecategory name
Return Values
ListofDisplayActionBinding instances

getMouseAxisDisplayText

Description
Get display text for a single mouse axis.
Definition
getMouseAxisDisplayText()

getGamepadAxisDisplayText

Description
Get display text for a single gamepad axis.
Definition
getGamepadAxisDisplayText()

getBindingInputDisplayText

Description
Get display text for input axis names of a binding.
Definition
getBindingInputDisplayText(Binding Binding)
Arguments
BindingBindingreference
Return Values
Display

saveChanges

Description
Save changed bindings to user configuration.
Definition
saveChanges()

discardChanges

Description
Discard any previously made binding changes.
Definition
discardChanges()

loadBindings

Description
Load action input bindings.
Definition
loadBindings()

onClickInput

Description
Handles clicking an input binding button for a given device category and action.
Definition
onClickInput(deviceCategory Input, bindingId ID, actionBinding Action)
Arguments
deviceCategoryInputdevice category
bindingIdIDof binding on the current device. E.g. 1 for main binding, 2 for secondary binding, etc.
actionBindingActionbinding table for the clicked action
Return Values
Trueifthe controller starts listening for input, false otherwise (also if it is already listening!)

beginWaitForInput

Description
Begin waiting for input.
Overrides the global input hooks keyEvent() and mouseEvent() as well as the global update() loop, depending on which
device is being scanned. Also see InputBinding:startInputCapture().
Definition
beginWaitForInput(deviceCategory Category, bindingIndex Binding, DisplayActionBinding DisplayActionBinding)
Arguments
deviceCategoryCategoryof device which is being scanned for input
bindingIndexBinding(primary, secondary, etc.) index which the scanned input will be assigned to.
DisplayActionBindingDisplayActionBindinginstance which describes the action binding to re-map.

onAbortInputGathering

Description
Input gathering abort event.
Definition
onAbortInputGathering()

onDeleteInputBinding

Description
Input gathering binding deletion event.
Definition
onDeleteInputBinding(DisplayActionBinding DisplayActionBinding, gatheringState {binding=DisplayActionBinding)
Arguments
DisplayActionBindingDisplayActionBindingreference of the binding to delete
gatheringState{binding=DisplayActionBindingreference of the binding to change, bindingIndex=Binding index}

onCaptureKeyboardInput

Description
Input gathering keyboard input event.
Definition
onCaptureKeyboardInput(keyName Key, isModifier True, inputValue 1, gatheringState {binding=DisplayActionBinding)
Arguments
keyNameKeyname as defined in Input
isModifierTrueif the key is used as a modifier for a combined input
inputValue1for pressed, 0 for inactive
gatheringState{binding=DisplayActionBindingreference of the binding to change, bindingIndex=Binding index, keyState={[keyName]=[lastValue]}}

onCaptureMouseInput

Description
Input gathering mouse input event.
Definition
onCaptureMouseInput(inputAxisName Mouse, isModifier True, inputValue Input, gatheringState {binding=DisplayActionBinding)
Arguments
inputAxisNameMouseaxis or button name as defined in Input
isModifierTrueif the input axis is used as a modifier for a combined input
inputValueInputvalue of the input axis
gatheringState{binding=DisplayActionBindingreference of the binding to change, bindingIndex=Binding index, mouseState={[axisName]=[lastValue]}}

onCaptureGamepadInput

Description
Input gathering gamepad / controller event.
Definition
onCaptureGamepadInput(deviceId Device, inputAxisName Axis, isModifier True, inputValue Input, gatheringState {binding=DisplayActionBinding)
Arguments
deviceIdDeviceID of the gamepad / controller which has received input
inputAxisNameAxisor button name as defined in Input
isModifierTrueif the input axis is used as a modifier for a combined input
inputValueInputvalue of the input axis
gatheringState{binding=DisplayActionBindingreference of the binding to change, bindingIndex=Binding index, gamepadState={[deviceId]={[axisName]=[lastValue]}}}

endWaitForInput

Description
Stop waiting for input.
Lifts the input override and notifies the screen listener.
Definition
endWaitForInput(madeChange If)
Arguments
madeChangeIftrue, the player has changed at least one binding.

lockInput

Description
Lock all UI input after capturing a new binding.
Definition
lockInput()

deleteBinding

Description
Delete a binding from its action binding table.
Definition
deleteBinding()
Return Values
boolTrueif an actual binding was deleted, false otherwise

assignKeyboardBinding

Description
Assign a (new) keyboard input binding.
Definition
assignKeyboardBinding(DisplayActionBinding DisplayActionBinding, bindingIndex Binding, keyames List)
Arguments
DisplayActionBindingDisplayActionBindinginstance which holds information about the binding to be added or updated
bindingIndexBindingindex to set, 1 primary, 2 secondary, etc.
keyamesListof input key names to bind
Return Values
Trueifa binding change was made, false otherwise

validateMouseCombo

Description
Check if the given axis names contain a supported mouse combo.
Definition
validateMouseCombo()

assignMouseBinding

Description
Assign a (new) mouse input binding.
Definition
assignMouseBinding(DisplayActionBinding DisplayActionBinding, inputAxisNames List, inputDirection Numeric)
Arguments
DisplayActionBindingDisplayActionBindinginstance which holds information about the binding to be added or updated
inputAxisNamesListof input axis names (axes and buttons) to bind
inputDirectionNumericvalue which defines the physical input axis direction component to bind. Values greater than or equal to 0 will be interpreted as positive, lesser than 0 as negative.
Return Values
Trueifa binding change was made, false otherwise

assignGamepadBinding

Description
Assign a (new) gamepad / controller input binding.
Definition
assignGamepadBinding(DisplayActionBinding DisplayActionBinding, bindingIndex Binding, deviceId Gamepad, inputAxisNames List, inputDirection Numeric)
Arguments
DisplayActionBindingDisplayActionBindinginstance which holds information about the binding to be added or updated
bindingIndexBindingindex to set, 1 primary, 2 secondary, etc.
deviceIdGamepad/ controller device ID of the input to bind
inputAxisNamesListof input axis names (axes and buttons) to bind
inputDirectionNumericvalue which defines the physical input axis direction component to bind. Values greater than or equal to 0 will be interpreted as positive, lesser than 0 as negative.
Return Values
Trueifa binding change was made, false otherwise

assignBinding

Description
Assign a (new) binding.
First tries to update an existing binding. If no binding with the given parameters exists to be updated, a new
binding is created instead, unless this would lead to an number of alternative bindings exceeding the maximum.
Definition
assignBinding(deviceId Binding, displayAction Cloned, bindingIndex Intended, inputAxisNames List, isPositiveAxis If, inputDirection Numeric, previousDeviceId [optional])
Arguments
deviceIdBindingdevice ID
displayActionClonedInputAction passed back from display and capture process
bindingIndexIntendedbinding index, 1 primary, 2 secondary, etc.
inputAxisNamesListof input axis names to bind
isPositiveAxisIftrue, the binding covers the positive part of the action's logical axis (always true for half-axis / button / key actions). False covers the negative part.
inputDirectionNumericvalue which defines the physical input axis direction component to bind. Values greater than or equal to 0 will be interpreted as positive, lesser than 0 as negative.
previousDeviceId[optional]Previous device ID of an existing binding. If not set, will use the given deviceId parameter instead.
Return Values
Trueifbinding has been assigned; reference to first colliding binding or nil

loadDefaultSettings

Description
Load default input binding settings from the game's profile template.
Handle with care, this will overwrite all the player's input binding settings.
Definition
loadDefaultSettings()

DataGrid

Description
Creating data grid

new

Description
@param table customMt custom metatable
Definition
new()
Return Values
tableinstanceinstance of object
Code
19function DataGrid:new(numRows, numColumns, customMt)
20 local self = {}
21 setmetatable(self, customMt or DataGrid_mt)
22
23 self.grid = {}
24 self.numRows = numRows
25 self.numColumns = numColumns
26 for i=1, numRows do
27 table.insert(self.grid, {})
28 end
29
30 return self
31end

delete

Description
Deletes data grid
Definition
delete()
Code
35function DataGrid:delete()
36 self.grid = nil
37end

getValue

Description
@param integer colIndex index of column
Definition
getValue()
Return Values
tablevaluevalue at the given position
Code
44function DataGrid:getValue(rowIndex, colIndex)
45 if rowIndex < 1 or rowIndex > self.numRows then
46 g_logManager:error("rowIndex out of bounds!")
47 printCallstack()
48 return nil
49 end
50 if colIndex < 1 or colIndex > self.numColumns then
51 g_logManager:error("colIndex out of bounds!")
52 printCallstack()
53 return nil
54 end
55
56 return self.grid[rowIndex][colIndex]
57end

setValue

Description
@param integer colIndex index of column
Definition
setValue(table value)
Arguments
tablevaluevalue at the given position
Code
64function DataGrid:setValue(rowIndex, colIndex, value)
65 if rowIndex < 1 or rowIndex > self.numRows then
66 g_logManager:error("rowIndex out of bounds!")
67 printCallstack()
68 return false
69 end
70 if colIndex < 1 or colIndex > self.numColumns then
71 g_logManager:error("colIndex out of bounds!")
72 printCallstack()
73 return false
74 end
75
76 self.grid[rowIndex][colIndex] = value
77 return true
78end

DepthOfFieldState

Description
Depth of field shader state.
-- This class wraps the depth of field shader parameter calls to allow convenient setting and resetting a specific
shader parameter state.
--@category GUI

new

Description
Create a new depth of field state.
This will record the currently set parameters which are restored when calling reset().
Definition
new(float nearCoCRadius, float nearBlurEnd, float farCoCRadius, float farBlurStart, float farBlurEnd)
Arguments
floatnearCoCRadiusNear circle of confusion radius (nearCoCRadius = 0 means no near blur (pinhole camera))
floatnearBlurEndDistance from the camera center where near blur ends
floatfarCoCRadiusFar circle of confusion radius (farCoCRadius = 0 means no far blur (pinhole camera))
floatfarBlurStartDistance from the camera center where far blur starts
floatfarBlurEndDistance from the camera center where far blur ends

recordState

Description
Record the current shader parameters for reset.
This is called on instantiation. If another state should be recorded, call this again afterwards.
Definition
recordState()

setParameters

Description
Set one or more parameters after instantiation.
If any of the parameters is omitted, the currently stored value is used.
Definition
setParameters(float nearCoCRadius, float nearBlurEnd, float farCoCRadius, float farBlurStart, float farBlurEnd)
Arguments
floatnearCoCRadiusNear circle of confusion radius (nearCoCRadius = 0 means no near blur (pinhole camera))
floatnearBlurEndDistance from the camera center where near blur ends
floatfarCoCRadiusFar circle of confusion radius (farCoCRadius = 0 means no far blur (pinhole camera))
floatfarBlurStartDistance from the camera center where far blur starts
floatfarBlurEndDistance from the camera center where far blur ends

apply

Description
Apply shader parameters which were provided on instantiation.
Definition
apply()

reset

Description
Reset the shader parameters to the state they were in when this object had been created.
Definition
reset()

createFullscreenBlur

Description
Create a depth of field state for a full screen blur effect.
Definition
createFullscreenBlur()

DirectSellDialog

Description
Vehicle selling or customization dialog
-- Opened when activating vehicle selling points.
-- @field headerText Dialog header text element

new

Description
Create a new DirectSellDialog instance.
Definition
new(table target, table custom_mt, table shopConfigScreen, table messageCenter)
Arguments
tabletargetDialogElement controller reference
tablecustom_mt[optional] Sub-class meta table for inheritance
tableshopConfigScreenShopConfigScreen reference for vehicle selling / customization
tablemessageCenterMessageCenter reference for local network UI event handling
Return Values
tableDirectSellDialoginstance

onClickOk

Description
Handle "sell" button event.
Definition
onClickOk()

onClickActivate

Description
Handle "customize" button event.
Definition
onClickActivate()

DisplayActionBinding

Description
Holds information about an action binding for display purposes.
-- This class is used to transfer input binding information between ControlsController and UI components.
--@category Input

new

Description
Creates a new DisplayActionBinding.
Definition
new(action InputAction, isPositive If, displayName Display, Binding Bindings)
Arguments
actionInputActionof this binding
isPositiveIftrue, this display action binding shows the binding for the positive input axis (always true for half-axis actions)
displayNameDisplayname of this action binding for the given input axis direction.
BindingBindingsassociated with the input axis component for the given action

setBindingDisplay

Description
Set display information for binding.
Definition
setBindingDisplay(Binding Binding, text Binding, column Display)
Arguments
BindingBindingreference contained in this instance
textBindingdisplay text (button/key/axes names)
columnDisplaycolumn index (1 for primary, 2 for secondary, etc)
Return Values
integernumPixelsnumber of pixels
integertotalNumPixelstotal number of pixels

EditFarmDialog

Description
Farm edit and create dialog.
-- Lets a player edit a farm's properties or create a new farm.
-- @field buttonTemplate Color button template which is cloned per color

new

Description
Create a new instance of EditFarmDialog.
Definition
new(table target, table custom_mt, table l10n, table farmManager)
Arguments
tabletargetOptional input target override
tablecustom_mtSub-class metatable
tablel10nI18N reference for localization
tablefarmManagerFarmManager reference for farm data access

setExistingFarm

Description
Set existing farm ID whose properties are to be modified.
If no farm ID is given, a new farm will be created.
Definition
setExistingFarm()

storeAvailableColors

Description
Find available farm colors and store them in fields.
Definition
storeAvailableColors()

onClickColorButton

Description
Handle activation of a color button.
Shadows parent method which exits the dialog right away.
Definition
onClickColorButton()

onClickActivate

Description
Handle dialog confirmation click / activation.
Depending on the mode, this will create a new farm or update an existing one.
Definition
onClickActivate()

Farm

Description
Permission types.

merge

Description
Merge another farm into this farm. Used for creating an SP game from an MP game. (this is mutating)
Definition
merge(table other)
Arguments
tableotherAnother Farm

getFarmhouse

Description
Get the farmhouse associated with the farm.
Definition
getFarmhouse()
Return Values
tablefarmhouseor nil

getSpawnPoint

Description
Get the spawnpoint associated with the farm(house).
Definition
getSpawnPoint()
Return Values
integerspawnpointnode or the career spawnpoint node.

getSleepCamera

Description
Get the sleep camera.
Definition
getSleepCamera()
Return Values
integerCameraor 0 if no farmhouse.

getActiveUsers

Description
Get a list of active users. Useful for using their connection ID
Definition
getActiveUsers()

isUserFarmManager

Description
Determine if a user is a manager of this farm.
Definition
isUserFarmManager(userId User)
Arguments
userIdUserID
Return Values
boolTrueif the user is a manager of this farm, false otherwise

getUserPermissions

Description
Get the farm permissions of a user.
Definition
getUserPermissions(userId User)
Arguments
userIdUserID
Return Values
tablePermissionhash table {permission=<hasPermission>}

setUserPermission

Description
Set a user's permission in this farm.
Definition
setUserPermission(userId User, string permission, bool hasPermission)
Arguments
userIdUserID
stringpermissionPermission key from Farm.PERMISSION
boolhasPermissionTrue if the permission is to be granted, false to be denied

promoteUser

Description
Promote a user to farm manager.
Definition
promoteUser()

demoteUser

Description
Demote a user from farm manager.
Definition
demoteUser()

setIsContractingFor

Description
Update contracting status
Definition
setIsContractingFor(noSendEvent boolean)
Arguments
noSendEventbooleanSend no event, forces setting of actual value without server feedback

changeBalance

Description
Add or remove money from the farm
Definition
changeBalance(number amount)
Arguments
numberamountAmount to add (positive) or remove (negative)

getBalance

Description
Get the current account balance of the farm.
Definition
getBalance()
Return Values
floatAccountbalance

getLoan

Description
Get the current loan of the farm.
Definition
getLoan()
Return Values
float

getHandTools

Description
Get a list of filenames for accessible handtools
Definition
getHandTools()

addUser

Description
Add a new user to the farm. This adds it to the players and active players list.
And also gives default permissions.
Definition
addUser()

removeUser

Description
Remove a user from the farm.
Definition
removeUser()

onUserJoinGame

Description
Called when a user joins the game. Active users is updated, and for spectator.
a new user might be added. Server only.
Definition
onUserJoinGame()

onUserQuitGame

Description
Called when a user quits the game. The active user list is updated. Server only.
Definition
onUserQuitGame()

FarmManager

Description
Multiplayer

new

Description
Creating manager
Definition
new()
Return Values
tableinstanceinstance of object
Code
27function FarmManager:new(customMt)
28 local self = AbstractManager:new(customMt or FarmManager_mt)
29
30 return self
31end

loadMapData

Description
Load data on map load
Definition
loadMapData()
Return Values
booleantrueif loading was successful else false
Code
43function FarmManager:loadMapData(xmlFile)
44 FarmManager:superClass().loadMapData(self)
45
46 if g_currentMission:getIsServer() then
47 g_currentMission:addUpdateable(self)
48
49 -- Create spectator farm
50 local spectatorFarm = Farm:new(true, g_client ~= nil, nil, true)
51 spectatorFarm.farmId = FarmManager.SPECTATOR_FARM_ID
52 spectatorFarm.isSpectator = true
53
54 spectatorFarm:register()
55
56 table.insert(self.farms, spectatorFarm)
57 self.farmIdToFarm[spectatorFarm.farmId] = spectatorFarm
58 end
59
60 addConsoleCommand("gsSetFarm", "Set farm for current player or vehicle", "consoleCommandSetFarm", self)
61
62 if g_addTestCommands then
63 addConsoleCommand("debugCreateFarm", "Create a new farm", "consoleCommandCreateFarm", self)
64 end
65end

unloadMapData

Description
Unload data on mission delete
Definition
unloadMapData()
Code
69function FarmManager:unloadMapData()
70 g_currentMission:removeUpdateable(self)
71
72 removeConsoleCommand("gsSetFarm")
73 if g_addTestCommands then
74 removeConsoleCommand("debugCreateFarm")
75 end
76
77 FarmManager:superClass().unloadMapData(self)
78end

saveToXMLFile

Description
Write field mission data to savegame file
Definition
saveToXMLFile(string xmlFilename)
Arguments
stringxmlFilenamefile path
Return Values
booleantrueif loading was successful else false
Code
84function FarmManager:saveToXMLFile(xmlFilename)
85 local xmlFile = createXMLFile("farmsXML", xmlFilename, "farms");
86
87 local index = 0
88 for i, farm in ipairs(self.farms) do
89 if farm.farmId ~= 0 then
90 local key = string.format("farms.farm(%d)", index)
91
92 farm:saveToXMLFile(xmlFile, key)
93 index = index + 1
94 end
95 end
96
97 saveXMLFile(xmlFile)
98 delete(xmlFile)
99end

loadFromXMLFile

Description
Load fieldjob data from xml savegame file
Definition
loadFromXMLFile(string filename)
Arguments
stringfilenamexml filename
Code
104function FarmManager:loadFromXMLFile(xmlFilename)
105 if xmlFilename == nil then
106 self:loadDefaults()
107 return false
108 end
109
110 local xmlFile = loadXMLFile("TempXML", xmlFilename)
111 if not xmlFile then
112 return false
113 end
114
115 local i = 0
116 while true do
117 local key = string.format("farms.farm(%d)", i)
118 if not hasXMLProperty(xmlFile, key) then
119 break
120 end
121
122 local farm = Farm:new(true, g_client ~= nil)
123
124 if not farm:loadFromXMLFile(xmlFile, key) then
125 farm:delete()
126 else
127 farm:register()
128
129 table.insert(self.farms, farm)
130 self.farmIdToFarm[farm.farmId] = farm
131 end
132
133 i = i + 1
134 end
135
136 self:mergeFarmsForSingleplayer()
137
138 -- Emulate an MP player join for local MP or SP game
139 if g_currentMission:getIsClient() then
140 local uniqueUserId = g_currentMission.missionDynamicInfo.isMultiplayer and getUniqueUserId() or FarmManager.SINGLEPLAYER_UUID
141 self:playerJoinedGame(uniqueUserId, g_currentMission:getServerUserId())
142 end
143
144 g_fieldManager:updateFieldOwnership()
145
146 delete(xmlFile)
147
148 return true
149end

mergeFarmlandsForSingleplayer

Description
Second step of merging: transfer all lands to the singleplayer farm
Definition
mergeFarmlandsForSingleplayer()

mergeObjectsForSingleplayer

Description
Third step of merging: move vehicles and bales to singleplayer farm
Definition
mergeObjectsForSingleplayer()

delete

Description
Deletes field mission manager
Definition
delete()
Code
236function FarmManager:delete()
237end

update

Description
Updates field mission ownage data from xml savegame file
Definition
update(string filename)
Arguments
stringfilenamexml filename
Code
242function FarmManager:update(dt)
243 if g_currentMission:getIsClient() then
244 if self.spFarmWasMerged and not self.mergedMessageShown then
245 g_gui:showInfoDialog({visible=true, text=g_i18n:getText("ui_farmedMergedSP"), dialogType=DialogElement.TYPE_INFO, isCloseAllowed=true})
246 self.mergedMessageShown = true
247 end
248 end
249end

getFarmForUniqueUserId

Description
Get farm for given userId. To be used when player is not in the game
Definition
getFarmForUniqueUserId()

getFarmByUserId

Description
Get farm for given userId. To be used when player is in the game.
Definition
getFarmByUserId()

updateFarms

Description
On client, update the list of farms and set farm for given farmId
Definition
updateFarms()

getFarms

Description
Get the array of known farms.
Callers should not modify this array.
Definition
getFarms()

transferMoney

Description
Transfer an amount of money from the current user's farm to a destination farm.
Triggers a network event which checks farm balances and applies the change. Successful execution requires the current
user to have permission to transfer money as well as their current farm to have a sufficient balance.
Definition
transferMoney()

removeUserFromFarm

Description
Remove player from their farm. Only works if the caller has permission (master user, farm manager)
Definition
removeUserFromFarm()

removeFarm

Description
Farm has been destroyed. Remove from lists
Definition
removeFarm()

FieldInfoDisplay

Description
HUD field information display element.
-- Displays dynamic information about the field which the player is currently standing in (or close by).
--@category GUI

new

Description
Create a new instance of FieldInfoDisplay.
Definition
new(string hudAtlasPath)
Arguments
stringhudAtlasPathPath to the HUD texture atlas

setupRows

Description
Set up rows data structures.
Definition
setupRows()

setPlayer

Description
Set the local player reference.
Definition
setPlayer()

setFruitType

Description
Set the current fruit type to display.
Definition
setFruitType(int fruitTypeIndex, int fruitGrowthState)
Arguments
intfruitTypeIndexIndex of the field fruit type or a number <= 0 to clear the fruit type.
intfruitGrowthStateCurrent growth state of the given fruit type

setOwnerFarmId

Description
Set the field owner
Definition
setOwnerFarmId(int ownerFarmId)
Arguments
intownerFarmIdCurrent owner farm id

setFertilization

Description
Set the fertilization factor info to display.
Definition
setFertilization(float fertilizationFactor)
Arguments
floatfertilizationFactorCurrent fertilization factor to display, this will be converted to a percentage. Values < 0 clear this info.

setWeed

Description
Set the weed factor info to display.
Definition
setWeed(float fertilizationFactor)
Arguments
floatfertilizationFactorCurrent weed factor to display, this will be converted to a percentage. Values < 0 clear this info.

setPlowingRequired

Description
Set the plowing required display.
Definition
setPlowingRequired(bool isRequired)
Arguments
boolisRequiredIf true, will display that the current field needs to be plowed. Otherwise, the info is hidden.

setLimeRequired

Description
Set the lime required display.
Definition
setLimeRequired(bool isRequired)
Arguments
boolisRequiredIf true, will display that the current field needs lime. Otherwise, the info is hidden.

addCustomText

Description
Add a custom text row.
The custom text will be added in order of calls to this function after the default information.
Definition
addCustomText(string leftText, string rightText, table leftColor)
Arguments
stringleftTextText to be displayed on the left side in bold print
stringrightText[optional] Text to be displayed on the right side in regular print
tableleftColor[optional, default=<white>] Color of left text as an array {r, g, b, a}
Return Values
intDisplayrow index of the newly added custom text or 0 if it could not be added

clearCustomText

Description
Clear a custom text row previously added by FieldInfoDisplay:addCustomText().
Definition
clearCustomText(int rowIndex)
Arguments
introwIndex[optional] Custom text row index as returned by FieldInfoDisplay:addCustomText(). If no value is provided, all custom text is cleared.

clearInfoRow

Description
Clear a single info row's data.
Definition
clearInfoRow()

clearFieldData

Description
Clear all previously set field data.
This does not clear custom text rows, which need to be cleared specifically using clearCustomText().
Definition
clearFieldData()

onFieldDataUpdateFinished

Description
Called when FSDensityMapUtil.getFieldStatusAsync() in update() has finished.
Definition
onFieldDataUpdateFinished(table data)
Arguments
tabledataField information data as provided by processing in FSDensityMapUtil.getFieldStatusAsync()

updateSize

Description
Update the info display size depending on used rows.
Definition
updateSize()

draw

Description
Draw the display.
Definition
draw()

drawText

Description
Draw text parts of this display element.
Definition
drawText()

getBackgroundPosition

Description
Get the scaled background position.
Definition
getBackgroundPosition()

setScale

Description
Set this element's UI scale factor.
Definition
setScale(float uiScale)
Arguments
floatuiScaleUI scale factor

storeScaledValues

Description
Store scaled position and size values.
Definition
storeScaledValues()

createBackground

Description
Create the background overlay.
Definition
createBackground()

createComponents

Description
Create required display components.
Definition
createComponents()

createFrame

Description
Create the background frame element.
Definition
createFrame()

createRowListContainer

Description
Create row list container.
Definition
createRowListContainer()

createSeparators

Description
Create row separators.
Definition
createSeparators()

FillLevelsDisplay

Description
Vehicle HUD fill levels display element.
-- Displays fill level bars for the current vehicle configuration
--@category GUI

new

Description
Creates a new FillLevelsDisplay instance.
Definition
new(string hudAtlasPath)
Arguments
stringhudAtlasPathPath to the HUD texture atlas.

setVehicle

Description
Set the currently controlled vehicle which provides display data.
Definition
setVehicle(table vehicle)
Arguments
tablevehicleCurrently controlled vehicle

updateFillLevelBuffers

Description
Update fill levels data.
Definition
updateFillLevelBuffers()

updateFillLevelFrames

Description
Update fill level frames display state.
Definition
updateFillLevelFrames()

update

Description
Update the fill levels state.
Definition
update()

draw

Description
Draw this element.
Definition
draw()

setScale

Description
Set this element's scale.
Definition
setScale()

getBackgroundPosition

Description
Get the position of the background element, which provides this element's absolute position.
Definition
getBackgroundPosition(scale Current, float width)
Arguments
scaleCurrentUI scale
floatwidthScaled background width in pixels
Return Values
floatXposition in screen space
floatYposition in screen space

storeScaledValues

Description
Calculate and store scaling values based on the current UI scale.
Definition
storeScaledValues()

createBackground

Description
Create an empty background overlay as a base frame for this element.
Definition
createBackground()

refreshFillTypes

Description
Refresh fill type data and elements.
Definition
refreshFillTypes(table fillTypeManager)
Arguments
tablefillTypeManagerFillTypeManager reference

createFillTypeFrames

Description
Create fill type frames for all known fill types.
Definition
createFillTypeFrames()

createFillTypeFrame

Description
Create a fill type frame for the display of a fill type level state.
Definition
createFillTypeFrame()

createFillTypeIcon

Description
Create an icon for a fill type.
Definition
createFillTypeIcon()

createFillTypeBar

Description
Create a fill type bar used to display a fill level.
The newly created bar is added to the given parent frame and an internal collection indexable by fill type index.
Definition
createFillTypeBar(string hudAtlasPath, table frame, float baseX, float baseY, table fillType)
Arguments
stringhudAtlasPathPath to HUD texture atlas
tableframeParent frame HUD element
floatbaseXOrigin X position in screen space
floatbaseYOrigin Y position in screen space
tablefillTypeFill type whose fill level is represented by the created bar

FocusManager

Description
The FocusManager controls which element in the menu system is currently focused
and allows menu control with only keyboard or gamepad.
For each participating gui element the focus state and the next focused gui element
in each direction is stored. This data is set up directly in the xml file of the gui screen
and loaded through the loadElementFromXML() function or manually loaded within code by using
the loadElementFromCustomValues() method.
Focus handling is independent for every screen in the GUI. To swap screens the setGui() method
has to be used.
The focus system is then controlled with 5 actions: MENU_UP, MENU_DOWN, MENU_RIGHT and MENU_LEFT to
change the currently focused element in the specified direction and MENU_ACCEPT to activate
the currently focused element.
-- When using dynamically changing objects which cannot be set directly in the XML file of the screen
the method createLinkageSystemForElements() can be used to set up direction links between the
passed elements automatically.
--@category GUI

setGui

Description
Set the active GUI for focus input.
Definition
setGui(Gui Screen)
Arguments
GuiScreenroot GuiElement

getElementById

Description
Get a focusable GuiElement in the current view by its ID.
Definition
getElementById()

getFocusedElement

Description
Get the currently focused GuiElement
Definition
getFocusedElement()

serveAutoFocusId

Description
Get a new automatic focus ID.
It's based on a simple integer increment and will be unique unless billions of elements require an ID.
Definition
serveAutoFocusId()

loadElementFromXML

Description
Load GuiElement focus data from its XML definition.
This is called at the end of GuiElement:loadFromXML().
Definition
loadElementFromXML()

loadElementFromCustomValues

Description
Add an element to the focus system with custom values.
The caller should ensure that explicitly set focus IDs are unique. If a duplicate ID is encountered, only the first
element with that focus ID is considered for focusing. The method returns a boolean value to indicate any problems
with data assignment. Callers can evaluate the value to check if the given parameters were valid. If in doubt or
when no elaborate focus navigation is needed, rely on automatic focus ID generation by omitting the ID parameter
(or set it to nil).
Definition
loadElementFromCustomValues(element Element, focusId Focus, focusChangeData Custom, focusActive If, isAlwaysFocusedOnOpen If)
Arguments
elementElementto add to focus system
focusIdFocusID for element
focusChangeDataCustomfocus navigation data for the element (map of direction to focus ID)
focusActiveIftrue, the element should be focused right now
isAlwaysFocusedOnOpenIftrue, the element is supposed to be focused when its parent view is opened.
Return Values
Trueifthe element and all of its children could be set up with the given values, false otherwise.

removeElement

Description
Remove a GuiElement from the current focus context.
Definition
removeElement()

linkElements

Description
Links an element's focus navigation to another element for a given direction.
The link is unidirectional from source to target. If bi-directional links are desired, call this method again with
swapped arguments.
Definition
linkElements(sourceElement Source, direction Navigation, targetElement Target)
Arguments
sourceElementSourceelement which receives the focus link.
directionNavigationdirection for the link, is not required to be the actual visual direction.
targetElementTargetelement

inputEvent

Description
Handles input and changes focus if required and possible.
Definition
inputEvent(action Name, value Input, eventUsed Usage)
Arguments
actionNameof navigation action which triggered the event, see InputAction
valueInputvalue [-1, 1]
eventUsedUsageflag, no action is taken if this is true
Return Values
Trueifthe input event has been consumed, false otherwise

getDirectionForAxisValue

Description
Get a direction value for a given menu input action and value
Definition
getDirectionForAxisValue()

isFocusInputLocked

Description
Checks if the focus manager has an input lock on input.
Definition
isFocusInputLocked(inputAxis InputAction, value Axis, True if)
Arguments
inputAxisInputActionaxis or action code
valueAxisvalue [-1, 1] or nil if not a directional axis
Trueiflocked, false otherwise

lockFocusInput

Description
Locks a given input axis action's input for a time. Until the delay has passed, the focus manager will not react to
that input.
Definition
lockFocusInput(inputAxis InputAction, delay Delay, value Axis)
Arguments
inputAxisInputActionaxis or action code
delayDelayin ms
valueAxisvalue [-1, 1], only relevant to identify directional axes

releaseMovementFocusInput

Description
Release a focus movement input lock on an action.
Called by the UI input handling code. Avoid calling this for anything else.
Definition
releaseMovementFocusInput(action Focus)
Arguments
actionFocusmovement input action name

resetFocusInputLocks

Description
Reset all locks of focus input.
Definition
resetFocusInputLocks()

getClosestPointOnBoundingBox

Description
Given a point and bounding box, get the closest other point on the bounding box circumference. If the point lies
within the bounding box, it is returned unchanged.
Definition
getClosestPointOnBoundingBox(x Point, y Point, boxMinX Bounding, boxMinY Bounding, boxMaxX Bounding, boxMaxY Bounding)
Arguments
xPointX
yPointY
boxMinXBoundingbox minimum point X
boxMinYBoundingbox minimum point Y
boxMaxXBoundingbox maximum point X
boxMaxYBoundingbox maximum point Y
Return Values
Closestpointx, y

getShortestBoundingBoxVector

Description
Calculate the shortest connecting line segment between two bounding boxes. Overlapping boxes will result in flipped
directions, so take care.
Definition
getShortestBoundingBoxVector()

checkElementDistance

Description
Checks the distance between two GuiElements with the aim of incrementally finding the closest other element in a
direction within a screen view.
Definition
checkElementDistance(curElement Current, other Other, dirX Scan, dirY Scan, curElementOffsetY Position, closestOther Previously, closestDistanceSq Squared)
Arguments
curElementCurrentchecking GuiElement
otherOtherGuiElement to compare
dirXScandirection vector x component, normalized to unit length
dirYScandirection vector y component, normalized to unit length
curElementOffsetYPositiony offset of current element's bounding volume, used when checking for wrap-around
closestOtherPreviouslyclosest other GuiElement
closestDistanceSqSquareddistance from the current checking element to the previously closest other GuiElement

getNextFocusElement

Description
Find the next other element to the one provided in a given navigation direction
Definition
getNextFocusElement(element GUI, direction Direction)
Arguments
elementGUIelement which needs a focus link
directionDirectionconstant [TOP | BOTTOM | LEFT | RIGHT]
Return Values
NextGUIelement in given direction which can be linked, actual scanning direction used (may change in wrap around scenarios)

getNestedFocusTarget

Description
Get an element's focus target at the deepest nesting depth, e.g. when multiple nested layouts point down to their
child elements until only a single element is left which points to itself.
Definition
getNestedFocusTarget(element GuiElement, direction Focus)
Arguments
elementGuiElementwhose focus target needs to be retrieved
directionFocusnavigation direction
Return Values
Focus

updateFocus

Description
Update the current focus target.
Definition
updateFocus(element GuiElement, isFocusMoving Only, direction Focus, updateOnly If)
Arguments
elementGuiElementwhich should be the new focus target
isFocusMovingOnlymove focus if this is true
directionFocusnavigation movement direction, one of FocusManager.[TOP | BOTTOM | LEFT | RIGHT]
updateOnlyIftrue, only updates the lock state of focus movement for the given parameters

setHighlight

Description
Activate a highlight on an element. Highlighted elements are only visually marked and do not receive focus activation.
Only one element will be highlighted at any time, usually corresponding to the current mouse over target.
Definition
setHighlight(element Element)
Arguments
elementElementto be highlighted.

unsetHighlight

Description
Remove highlight status from an element.
Definition
unsetHighlight(element Highlighted)
Arguments
elementHighlightedelement to revert

setFocus

Description
Set focus on a GuiElement or its focus target.
Applies overlay state and triggers onFocusEnter() on the target.
Definition
setFocus(element Element, direction Focus, ... Variable)
Arguments
elementElementwhose focus target (usually itself) receives focus.
directionFocusnavigation direction
...Variablearguments to pass on to the onFocusEnter callback of the target element
Return Values
Trueiffocus has changed, false otherwise

unsetFocus

Description
Removes focus from an element.
Applies overlay state and triggers onFocusLeave() on the target.
Definition
unsetFocus(element Element, ... Variable)
Arguments
elementElementwhich should lose focus
...Variablearguments to pass on to the onFocusLeave callback of the target element

setElementFocusOverlayState

Description
Set an elements focus overlay state for displaying.
Definition
setElementFocusOverlayState(element Target, isFocus If, handlePreviousState [optional])
Arguments
elementTargetelement
isFocusIftrue, the element's state will be set to focused. Otherwise, it's state will be either restored or set to normal.
handlePreviousState[optional]If true or undefined, makes the element store its previous overlay state before modification or restore it when isFocused is false.

requireLock

Description
Globally lock focus input.
Definition
requireLock()

releaseLock

Description
Release the global focus input lock.
Definition
releaseLock()

isLocked

Description
Check if focus input is locked.
Definition
isLocked()

isDirectionLocked

Description
Determine if focus navigation in a given direction is currently locked.
Definition
isDirectionLocked(direction Navigation)
Arguments
directionNavigationdirection as defined in constants
Return Values
Trueifnavigation in given direction is locked

hasFocus

Description
Determine if a GuiElement is currently focused.
Definition
hasFocus()

getFocusOverrideFunction

Description
Get a closure override function for elements' getFocusOverride() methods.
Definition
getFocusOverrideFunction(forDirections List, substitute Element, useSubstituteForFocus (Optional))
Arguments
forDirectionsListof directions to override
substituteElementto substitute as focus target in overridden direction
useSubstituteForFocus(Optional)If true, the substitute parameter will be used as the origin for finding the
next focus target in the overridden direction.

FrameElement

Description
Base display frame element. All GUI views (partial and full screen) inherit from this.
-- This element provides the functionality to register control IDs, which are then exposed as fields of the concrete
descendant class (e.g. MainScreen or PasswordDialog). The control IDs must be assigned verbatim to any control
in the corresponding configuration XML file. If a registered ID is not used, the field will not be assigned and
access will fail. Available field IDs are documented as field properties per class. When creating a new view, take
care to include the call to registerControls() in the constructor to declare and expose control elements as fields.
--@category GUI

clone

Description
Override of GuiElement:clone().
Also exposes registered control element fields.
Definition
clone()

copyAttributes

Description
Override of GuiElement:copyAttributes().
Also resets registered control IDs so they can be exposed as fields again.
Definition
copyAttributes()

getRootElement

Description
Get the frame's root GuiElement instance.
This is the first and only direct child of a FrameElement, as defined by the GUI instantiation logic. This method
will always return a GuiElement instance, even if a new one must be created first.
Definition
getRootElement()

registerControls

Description
Register a collection of control IDs for direct access in GUI views.
Definition
registerControls(controlIDs Table)
Arguments
controlIDsTablewhich holds control IDs as values, as they are required to be present in the view configuration.

exposeControlsAsFields

Description
Adds registered controls as fields to this FrameElement instance.
Called by the GUI system after loading.
The new fields will have the same name as the registered ID, so make sure there are no collision to avoid overrides
and that IDs are also valid as identifiers in Lua. If a control has been registered but no corresponding element is
available (e.g. when sub-classing and omitting some elements), the field will remain undefined. It's up to callers
to ensure that field configuration and usage in views matches.
Definition
exposeControlsAsFields(viewName View)
Arguments
viewNameViewname of this frame element

disableInputForDuration

Description
Set input disabling to a given duration.
Definition
disableInputForDuration(float duration)
Arguments
floatdurationInput disabling duration in milliseconds

isInputDisabled

Description
Check if input is currently disabled.
Definition
isInputDisabled()

setChangeScreenCallback

Description
Set a callback for requesting a view change from within a frame or screen view.
Definition
setChangeScreenCallback(func callback)
Arguments
funccallbackFunction reference, signature: function(sourceFrameElement, targetScreenClass, returnScreenClass)

setInputContextCallback

Description
Set a callback function for requesting a custom menu input context for this frame.
Definition
setInputContextCallback(func callback)
Arguments
funccallbackFunction reference, signature: function(isContextActive)

setPlaySampleCallback

Description
Set a callback function for requesting to play a sound sample.
Definition
setPlaySampleCallback(func callback)
Arguments
funccallbackFunction reference, signature: function(sampleName)

changeScreen

Description
Request a view change via the callback defined by setChangeScreenCallback().
Definition
changeScreen(table targetScreenClass)
Arguments
tabletargetScreenClassClass table of requested view (ScreenElement descendant, must be full view)

toggleCustomInputContext

Description
Request toggling of a custom menu input context for this frame via the callback defined by setInputContextCallback().
Definition
toggleCustomInputContext(bool isContextActive, string contextName)
Arguments
boolisContextActiveIf true, will activate a custom menu input context. Otherwise, will clear a previously
activated context.
stringcontextNameName of the custom input context. Use a unique identifier value.

playSample

Description
Request playing a sound sample identified by name.
Definition
playSample(string sampleName)
Arguments
stringsampleNameSample name, use one of GuiSoundPlayer.SOUND_SAMPLES

FSBaseMission

Description
(Un)loading stations

initialize

Description
Initialize mission after instantiation.
Create complex members and call dependency methods in here so that mission instantiation cannot fail.
Definition
initialize()

setHarvestScaleRatio

Description
Sets harvest ratios for fertilizer, plow, lime and weed factor
Definition
setHarvestScaleRatio(float sprayRatio, float plowRatio, float limeRatio, float weedRatio)
Arguments
floatsprayRatiofertilizer ratio
floatplowRatioplow ratio
floatlimeRatiolime ratio
floatweedRatioweed ratio

getHarvestScaleMultiplier

Description
Get harvest multiplier based on fertilizer, plow, lime and weed factor, 1 = best
Definition
getHarvestScaleMultiplier(integer fruitTypeIndex, float sprayFactor, float plowFactor, float limeFactor, float weedFactor)
Arguments
integerfruitTypeIndexfruit type index
floatsprayFactorfertilizer factor
floatplowFactorplow factor
floatlimeFactorlime factor
floatweedFactorweed factor
Return Values
floatmultiplierharvest multiplier

updateMenuAccessibleVehicles

Description
Check which vehicles are accessible and notify the menu.
Definition
updateMenuAccessibleVehicles()

addOwnedItem

Description
Add an item to the owned items collection.
Also notifies the shop.
Definition
addOwnedItem()

removeOwnedItem

Description
Remove an item from the owned items collection.
Also notifies the shop.
Definition
removeOwnedItem()

addLeasedItem

Description
Add an item to the leased items collection.
Also notifies the shop.
Definition
addLeasedItem()

removeLeasedItem

Description
Remove an item from the leased items collection.
Also notifies the shop.
Definition
removeLeasedItem()

updatePauseInputContext

Description
Set or revert the pause input context based on current state.
Definition
updatePauseInputContext()

updateSaving

Description
Update saving process.
Notifies the UI to display dialogs.
Definition
updateSaving()

onYesNoSavegameSelectDevice

Description
Savegame device selection confirmation dialog response callback.
Definition
onYesNoSavegameSelectDevice()

onSaveGameUpdateComplete

Description
Savegame overwrite completion callback.
Definition
onSaveGameUpdateComplete(int errorCode)
Arguments
interrorCodeSaving process status code, one of Savegame.ERROR_...

onYesNoSavegameOverwrite

Description
Savegame overwrite confirmation dialog response callback.
Definition
onYesNoSavegameOverwrite()

showAttachContext

Description
Display vehicle attachment context information for the current frame.
Definition
showAttachContext()

showTipContext

Description
Display vehicle tipping context information for the current frame.
Definition
showTipContext()

showFuelContext

Description
Display vehicle refueling context information for the current frame.
Definition
showFuelContext()

showFillDogBowlContext

Description
Display dog companion food bowl fill context information for the current frame.
Definition
showFillDogBowlContext()

getMoney

Description
Get money for farm or current player farm
Definition
getMoney(farmId integer)
Arguments
farmIdintegerif nil, then current farm (client only)

getHasPlayerPermission

Description
Get whether the current player has given permission.
Definition
getHasPlayerPermission(string permission, table connection, integer farmId, boolean checkClient)
Arguments
stringpermissionPermission to check
tableconnection[optional] Client connection to check permission for
integerfarmId[optional] Limit permission to given farm (otherwise any farm)
booleancheckClient[optional] if true it will only check the client permission

getIngameMap

Description
Get the in-game map rendering component.
Should only be used for UI.
Definition
getIngameMap()

startSaveCurrentGame

Description
Start saving the game.
Definition
startSaveCurrentGame(bool isDediSaving)
Arguments
boolisDediSavingIf true, this is a saving call on a dedicated server

saveSavegame

Description
Actually save the game locally.
Definition
saveSavegame()

getDoghouse

Description
Returns a doghouse
Definition
getDoghouse(integer farmId)
Arguments
integerfarmId
Return Values
tableinstanceof the doghouse
Code
3144function FSBaseMission:getDoghouse(farmId)
3145 for _, doghouse in pairs(self.doghouses) do
3146 if doghouse:getOwnerFarmId() == farmId then
3147 return doghouse
3148 end
3149 end
3150 return nil
3151end

registerHusbandry

Description
Register a husbandry in the mission.
Definition
registerHusbandry()

unregisterHusbandry

Description
Unregister a husbandry in the mission.
Definition
unregisterHusbandry()

getVehicleName

Description
Extract a concrete vehicle's display name from its store data.
Definition
getVehicleName(table vehicle)
Arguments
tablevehicleVehicle instance
Return Values
stringVehicledisplay name

registerActionEvents

Description
Register required input action events.
Definition
registerActionEvents()

registerPauseActionEvents

Description
Register action events for pause actions.
Event registration in this method is enclosed in an input binding registration context (InputBinding:beginActionEventsModification()).
Make sure that this is only called when all other registration-context altering code is done.
Definition
registerPauseActionEvents()

onToggleMenu

Description
Input event for "open menu".
Definition
onToggleMenu()

onToggleStore

Description
Input event for "open shop".
Definition
onToggleStore()

toggleChat

Description
Toggle chat display.
Called from input to open the chat dialog and from the chat dialog to close it again.
Definition
toggleChat()

onToggleRadio

Description
Input event for "toggle radio".
Definition
onToggleRadio()

onChangeTimescale

Description
Input event for "increase timescale" and "decrease timescale"
Definition
onChangeTimescale()

onShowHelpIconsChanged

Description
Handle a settings change for showing help icons.
Definition
onShowHelpIconsChanged()

onRadioVehicleOnlyChanged

Description
Handle a settings change for the radio vehicle only setting.
If the current radio state is active, the radio will start playing if the context fits (e.g. turn to global, and
player is on foot).
Definition
onRadioVehicleOnlyChanged()

onRadioIsActiveChanged

Description
Handle a settings change for the radio active state.
Definition
onRadioIsActiveChanged()

setRadioActionEventsState

Description
Set the active state for the radio action events.
Definition
setRadioActionEventsState()

subscribeMessages

Description
Subscribe to FS-specific event messages.
The BaseMission parent class unsubscribes from messages in delete(). No clean-up required in sub-classes like this.
Definition
subscribeMessages()

notifyPlayerFarmChanged

Description
Handle a local client changing the farm.
Definition
notifyPlayerFarmChanged()

GameInfoDisplay

Description
HUD general game information display.
-- Displays current game information. This includes weather, current account balance and time settings.
--@category GUI

new

Description
Create a new instance of GameInfoDisplay.
Definition
new(string hudAtlasPath)
Arguments
stringhudAtlasPathPath to the HUD texture atlas

setMoneyUnit

Description
Set the money unit for displaying the account balance.
Definition
setMoneyUnit(int moneyUnit)
Arguments
intmoneyUnitMoney unit ID, any of [GS_MONEY_EURO | GS_MONEY_POUND | GS_MONEY_DOLLAR]. Invalid values are substituted by GS_MONEY_DOLLAR.

setMissionStats

Description
Set the MissionStats reference for displaying information.
Definition
setMissionStats(table missionStats)
Arguments
tablemissionStatsMissionStats reference, do not change

setMissionInfo

Description
Set the mission information reference for base information display.
Definition
setMissionInfo(table missionInfo)
Arguments
tablemissionInfoMissionInfo reference, do not change

setEnvironment

Description
Set the environment reference to use for weather information display.
Definition
setEnvironment(table environment)
Arguments
tableenvironmentEnvironment reference, do not change

setMoneyVisible

Description
Set visibility of the money display.
Definition
setMoneyVisible()

setTimeVisible

Description
Set visibility of time display.
Definition
setTimeVisible()

setTemperatureVisible

Description
Set visibility of temperature display.
Definition
setTemperatureVisible()

setWeatherVisible

Description
Set visibility of weather display.
Definition
setWeatherVisible()

setTutorialVisible

Description
Set visibility of tutorial progress display.
Definition
setTutorialVisible()

setTutorialProgress

Description
Set the current tutorial progress values.
Definition
setTutorialProgress(float progress)
Arguments
floatprogressProgress expressed as a number between 0 and 1

update

Description
Update the game info display state.
Definition
update()

updateTime

Description
Update time display.
Definition
updateTime()

updateTemperature

Description
Update temperature display.
Definition
updateTemperature()

updateWeather

Description
Update weather display
Definition
updateWeather()

getVisibleWidth

Description
Get the game info display's width based on its visible info boxes.
Definition
getVisibleWidth()
Return Values
floatGameinfo display width of visible elements in screen space

updateSizeAndPositions

Description
Update sizes and positions of this elements and its children.
Definition
updateSizeAndPositions()

draw

Description
Draw the game info display.
Definition
draw()

drawMoneyText

Description
Draw the text part of the money display.
Definition
drawMoneyText()

drawTimeText

Description
Draw the text part of the time display.
Definition
drawTimeText()

drawTemperatureText

Description
Draw the text part of the temperature display.
Definition
drawTemperatureText()

drawTutorialText

Description
Draw the text part of the tutorial progress display.
Definition
drawTutorialText()

animateWeatherChange

Description
Make an animation for a weather change.
Definition
animateWeatherChange()

addActiveWeatherAnimation

Description
Animate a weather icon becoming active.
Definition
addActiveWeatherAnimation()

addInactiveWeatherAnimation

Description
Animate a weather icon becoming inactive.
Definition
addInactiveWeatherAnimation()

addBecomeCurrentWeatherAnimation

Description
Animate a weather icon becoming the current weather icon.
Definition
addBecomeCurrentWeatherAnimation()

addWeatherPositionAnimation

Description
Animate weather icon position changes.
Definition
addWeatherPositionAnimation()

getBackgroundPosition

Description
Get this element's base background position.
Definition
getBackgroundPosition(float uiScale)
Arguments
floatuiScaleCurrent UI scale factor

setScale

Description
Set this element's UI scale factor.
Definition
setScale(float uiScale)
Arguments
floatuiScaleUI scale factor

storeScaledValues

Description
Store scaled positioning, size and offset values.
Definition
storeScaledValues()

createBackground

Description
Create the background overlay.
Definition
createBackground()

createComponents

Description
Create required display components.
Also adds a separator HUDElement instance as a field (".separator") to all info boxes.
Definition
createComponents()

createMoneyBox

Description
Create the money display box.
Definition
createMoneyBox()

createTimeBox

Description
Create the time display box.
Definition
createTimeBox()

createTemperatureBox

Description
Create the temperature display box.
Definition
createTemperatureBox()

createWeatherBox

Description
Create the weather display box.
Definition
createWeatherBox()

createWeatherIcon

Description
Create a weather icon for current and upcoming weather conditions.
Definition
createWeatherIcon(string hudAtlasPath, int weatherId, float boxHeight, table uvs, table color)
Arguments
stringhudAtlasPathPath to HUD texture atlas
intweatherIdWeather condition ID, as defined in WeatherType... constants
floatboxHeightScreen space height of the box which will hold this icon
tableuvsUV coordinates of the weather icon in the HUD texture atlas
tablecolorColor RGBA array
Return Values
tableWeathericon HUDElement instance

createTemperatureIcon

Description
Create a temperature icon to display stable or changing temperatures.
Definition
createTemperatureIcon(string hudAtlasPath, float leftX, float bottomY, float boxHeight, table uvs, table color)
Arguments
stringhudAtlasPathPath to HUD texture atlas
floatleftXScreen space left X position of newly created icon
floatbottomYScreen space bottom Y position of the parent box
floatboxHeightScreen space height of the parent box
tableuvsUV coordinates of the icon in the HUD texture atlas
tablecolorColor RGBA array
Return Values
tableTemperatureicon HUDElement instance

createClockHand

Description
Create a rotatable clock hand icon element.
Definition
createClockHand(string hudAtlasPath, float posX, float posY, table size, table uvs, table color, table pivot)
Arguments
stringhudAtlasPathPath to HUD texture atlas
floatposXScreen space X position of the clock hand
floatposYScreen space Y position of the clock hand
tablesizePixel size vector {width, height}
tableuvsUV coordinates of the icon in the HUD texture atlas
tablecolorColor RGBA array
tablepivotUV pixel space rotation pivot coordinates
Return Values
tableClockhand HUDElement instance

createTimeScaleArrow

Description
Create a time scale arrow icon element.
Definition
createTimeScaleArrow(string hudAtlasPath, float posX, float posY, table size, table uvs)
Arguments
stringhudAtlasPathPath to HUD texture atlas
floatposXScreen space X position of the arrow
floatposYScreen space Y position of the arrow
tablesizePixel size vector {width, height}
tableuvsUV coordinates of the icon in the HUD texture atlas
Return Values
tableTimescale arrow icon HUDElement instance

createVerticalSeparator

Description
Create and return a vertical separator element.
Definition
createVerticalSeparator()

createTutorialBox

Description
Create the tutorial progress box.
Definition
createTutorialBox()

GamepadSigninScreen

Description
Sign-In Screen before Main Menu.
-- Used in console version.
-- @field startText Button prompt text to start the game.

inputEvent

Description
GUI input event callback.
See GuiElement:inputEvent().
Definition
inputEvent()

signIn

Description
Event function for button sign in.
Definition
signIn()

GamePausedDisplay

Description
HUD game pause display element.
-- Displays a customizable message when the game is paused.
--@category GUI

new

Description
Create a new GamePausedDisplay.
Definition
new(string hudAtlasPath)
Arguments
stringhudAtlasPathPath to the HUD atlas texture.
Return Values
tableGamePausedDisplayinstance

setPauseText

Description
Set a custom text to display.
Definition
setPauseText()

onMenuVisibilityChange

Description
Handle menu visibility state change.
Definition
onMenuVisibilityChange()

setScale

Description
Set uniform UI scale.
Definition
setScale()

storeScaledValues

Description
Store scaled positioning, size and offset values.
Definition
storeScaledValues()

createBackground

Description
Get this element's base background position.
Definition
createBackground()

createComponents

Description
Create required display components.
Definition
createComponents()

Gui

Description
Graphical User Interface controller.
-- Builds UI from configurations, provides dialog display and propagates UI input.
--@category GUI

loadProfiles

Description
Load UI profile data from XML.
Definition
loadProfiles(xmlFilename UI)
Arguments
xmlFilenameUIprofiles definition XML file path, relative to application root.

loadGui

Description
Load a UI screen view's elements from an XML definition.
Definition
loadGui(xmlFilename View, name Screen, controller FrameElement, isFrame [optional,)
Arguments
xmlFilenameViewdefinition XML file path, relative to application root.
nameScreenname
controllerFrameElementinstance which serves as the controller for loaded elements
isFrame[optional,default=false] If true, will interpret the loaded view as a frame to be used in multiple places.
Return Values
RootGuiElementinstance of loaded view or nil if the definition XML file could not be loaded.

loadGuiRec

Description
Recursively load and build a UI configuration.
Definition
loadGuiRec(xmlFile Opened, xmlNodePath Current, parentGuiElement Current, target Target)
Arguments
xmlFileOpenedGUI configuration XML file
xmlNodePathCurrentXML node path
parentGuiElementCurrentparent GuiElement
targetTargetof newly instantiated elements

resolveFrameReference

Description
Tries resolving a frame reference.
If no frame has been loaded with the name given by the reference, then the reference element itself is returned.
Otherwise, the registered frame is cloned and returned.
Definition
resolveFrameReference(self Gui, frameRefElement FrameReferenceElement)
Arguments
selfGuiinstance
frameRefElementFrameReferenceElementinstance to resolve
Return Values
ClonedFrameElementinstance or frameRefElement if resolution failed.

getProfile

Description
Get a UI profile by name.
Definition
getProfile()

getIsGuiVisible

Description
Determine if any menu or dialog is visible.
Definition
getIsGuiVisible()

getIsDialogVisible

Description
Determine if any dialog is visible.
Definition
getIsDialogVisible()

getActionEventId

Description
Get a menu action event ID by its name.
Modify GUI action events with care, as they are globally defined for an entire session.
Definition
getActionEventId()

showGui

Description
Display and return a screen identified by name.
Definition
showGui()
Return Values
RootGuiElementof screen or nil if the name did not match any known screen.

showDialog

Description
Display a dialog identified by name.
Definition
showDialog()
Return Values
RootGuiElementof dialog or nil if the name did not match any known dialog.

closeDialogByName

Description
Close a dialog identified by name.
Definition
closeDialogByName()

closeDialog

Description
Close a dialog identified by its root GuiElement.
This is always called when a dialog is closed, usually by itself.
Definition
closeDialog()

closeAllDialogs

Description
Close all open dialogs.
Definition
closeAllDialogs()

registerMenuInput

Description
Register menu input.
Definition
registerMenuInput()

mouseEvent

Description
GUI mouse event hook.
This is used primarily for mouse location checks, as button inputs are handled by InputBinding.
Definition
mouseEvent()

keyEvent

Description
GUI key event hook.
This is used for GuiElements which need to have direct access to raw key input, such as TextInputElement.
Definition
keyEvent()

update

Description
Update the GUI.
Propagates update to all active UI elements.
Definition
update()

draw

Description
Draw the GUI.
Propagates draw calls to all active UI elements.
Definition
draw()

notifyControls

Description
Notify controls of an action input with a value.
Definition
notifyControls(action Action, value Action)
Arguments
actionActionname as defined by loaded actions, see also scripts/input/InputAction.lua
valueActionvalue [-1, 1]
Return Values
Trueifany control has consumed the action event

onMenuInput

Description
Event callback for menu input.
Definition
onMenuInput()

onReleaseMovement

Description
Event callback for released movement menu input.
Definition
onReleaseMovement()

hasElementInputFocus

Description
Determine if a given GuiElement has input focus.
Definition
hasElementInputFocus()

getScreenInstanceByClass

Description
Get a screen controller instance by class for special cases.
Definition
getScreenInstanceByClass(table screenClass)
Arguments
tablescreenClassClass table of the requested screen
Return Values
tableScreenElementdescendant instance of the given class or nil if no such instance was registered

changeScreen

Description
Change the currently displayed screen.
Definition
changeScreen(table source, table screenClass, table returnScreenClass)
Arguments
tablesourceSource screen instance
tablescreenClassClass table of the requested screen to change to or nil to close the GUI
tablereturnScreenClass[optional] Class table of the screen which will be opened on a "back" action in the
new screen.
Return Values
tableRootGuiElement instance of target screen

makeChangeScreenClosure

Description
Make a change screen callback function which encloses the Gui self reference.
This avoids passing the reference around as a parameter or global reference.
Definition
makeChangeScreenClosure()

toggleCustomInputContext

Description
Toggle a custom menu input context for one of the managed frames or screens.
Definition
toggleCustomInputContext()

makeToggleCustomInputContextClosure

Description
Make a toggle custom input context function which encloses the Gui self reference.
Definition
makeToggleCustomInputContextClosure()

makePlaySampleClosure

Description
Make a play sample function which encloses the Gui self reference.
Definition
makePlaySampleClosure()

assignPlaySampleCallback

Description
Assign the play sample closure to a GUI element which has the PlaySampleMixin included.
Definition
assignPlaySampleCallback(table guiElement)
Arguments
tableguiElementGuiElement instance
Return Values
tableTheGuiElement instance given in the guiElement parameter

enterMenuContext

Description
Enter a new menu input context.
Menu views which require special input should provide a context name to not collide with the base menu input scheme.
Definition
enterMenuContext(string contextName)
Arguments
stringcontextName[optional] Custom menu input context name

leaveMenuContext

Description
Leave a menu input context.
This wraps the input context setting to check if the menu is actually active and the context should be reverted to
the state before entering the menu (or a custom menu input context within the menu).
Definition
leaveMenuContext()

addFrame

Description
Add the instance of a specific reusable GUI frame.
Definition
addFrame()

addScreen

Description
Add the instance of a specific GUI screen.
Definition
addScreen()

setCurrentMission

Description
Set the current mission reference for GUI screens.
Definition
setCurrentMission()

setEconomyManager

Description
Set the current economy manager for GUI screens.
The manager is initialized during mission loading.
Definition
setEconomyManager()

loadMapData

Description
Let the GUI (and its components) process map data when it's loaded.
Definition
loadMapData(int mapXmlFile)
Arguments
intmapXmlFileMap configuration XML file handle, do not close, will be handled by caller.

setClient

Description
Set the network client reference for GUI screens.
Definition
setClient()

setIsMultiplayer

Description
Set multiplayer state on screens which need to know about it.
Definition
setIsMultiplayer(bool isMultiplayer)
Arguments
boolisMultiplayerIf true, the GUI needs work in multiplayer mode. Otherwise, it's single player.

initGuiLibrary

Description
Source in UI modules.
Definition
initGuiLibrary(baseDir Base)
Arguments
baseDirBasescripts directory

GuiElement

Description
GUI Element base class.
All elements displayed in the game UI must be instances or descendants of this class.
-- All XML configuration properties as declared below (and in subclasses) are mirrored in guiProfiles.xml as key-value
pairs in the form of &ltValue name="property_name" value="value" /&gt. Profiles are able to inherit from other
profiles, so take care to check their hierarchy if any of your settings do not seem to have any effect. Directly set
properties in the XML configuration will always override profile values, however.
-- Layer properties, prefixed with "[layer]", interact with an overlay system and provide display images. Usable
layers, whose names are substituted for the prefix, are primarily "image" and "icon". UI elements define layer names
on their own and read them from these generated properties. Whenever an element requires a layer, it is described
in its documentation such as this one. Example for an icon layer focus color property:
iconFocusedColor="0.9 0.1 0.5 1.0".
-- A note regarding callbacks: All callbacks are called on an element's target first. When GUI elements are created from
configuration, their top-level view (e.g. MainScreen) is the callback target, i.e. MainScreen:callbackName() is
executed. Unless an element's target has been set to another value explicitly via code, this will always be the case.
--@category GUI
--@xmlConfig GuiElement#id string [optional] Element ID. Must be unique per GUI screen. If set on an element, will expose it as an indexable field on the view class (e.g. id="buttonOk" -> MainScreen.buttonOk). Use this feature sparingly, as it creates implicit coupling which leads to tedious debugging.

new

Description
Create a new GuiElement.
Definition
new(target Target)
Arguments
targetTargetScreenElement instance

loadFromXML

Description
Load element data from an XML definition file.
Definition
loadFromXML(xmlFile Definition, key XML)
Arguments
xmlFileDefinitionXML file handle
keyXMLnode path to this element's definition

loadProfile

Description
Load profile data for this element.
Definition
loadProfile(profile Loaded, applyProfile If)
Arguments
profileLoadedGUI profile
applyProfileIftrue, will re-calculate some dynamic properties. Use this when setting profiles dynamically at run time.

applyProfile

Description
Apply a GUI profile with a given name to this element.
Definition
applyProfile(profileName Name, bool force)
Arguments
profileNameNameof the profile to apply to this element
boolforce[optional] If true, will apply all profile settings, including position and size.

deleteFrame

Description
Delete any created frame overlays.
Definition
deleteFrame()

delete

Description
Delete this GuiElement.
Also deletes all child elements and removes itself from its parent and focus.
Definition
delete()

clone

Description
Create a deep copy clone of this GuiElement.
Definition
clone(parent Target, includeId [optional,, suppressOnCreate [optional,)
Arguments
parentTargetparent element of the cloned element
includeId[optional,default=false] If true, will also clone ID values
suppressOnCreate[optional,default=false] If true, will not trigger the "onCreate" callback

copyAttributes

Description
Copy all attributes from a source GuiElement to this GuiElement.
Definition
copyAttributes()

onGuiSetupFinished

Description
Called on a screen view's root GuiElement when all elements in a screen view have been created.
The event is propagated to all children, depth-first.
Definition
onGuiSetupFinished()

createFrame

Description
Create frame overlays if this element has a frame.
Definition
createFrame()

toggleFrameSide

Description
Toggle a frame side's visibility identified by index.
If this element has no frame this will have no effect.
Definition
toggleFrameSide(int sideIndex)
Arguments
intsideIndexIndex of the frame side, use one of GuiElement.FRAME_...

updateFramePosition

Description
Update the frame overlay positions if necessary.
Definition
updateFramePosition()

cutFrameBordersHorizontal

Description
Cut horizontal frame borders if a vertical frame side is thicker.
Definition
cutFrameBordersHorizontal()

cutFrameBordersVertical

Description
Cut vertical frame borders if a horizontal frame side is thicker.
Definition
cutFrameBordersVertical()

mouseEvent

Description
Mouse event hook for mouse movement checks.
Definition
mouseEvent()

inputEvent

Description
Handles an input event on a menu input action.
Input is first passed to the current GUI view, then to the focused element, then to the focus manager for navigation.
When a GUI element receives input, it should always propagate the input to its parent element first so they may
override behavior and/or set the event used flag. If properly inherited from GuiElement and descendants, this
behavior is guaranteed.
Definition
inputEvent(action Name, value Input, eventUsed If)
Arguments
actionNameof input action which was triggered.
valueInputvalue in the range of [-1, 1] for full axes and [0, 1] for half axes (includes buttons)
eventUsedIftrue, the event has been used by an input handler and should only be acted upon in exceptional cases.
Return Values
Trueifthe input event has been handled, false otherwise.

keyEvent

Description
Key event hook for raw keyboard input.
Definition
keyEvent()
Return Values
Trueifthe keyboard input has been processed by this element.

update

Description
Update this GuiElement.
Definition
update()

draw

Description
Draw this GuiElement.
If defined, triggers the "onDrawCallback".
Definition
draw()

onOpen

Description
Called on the root element of a screen view when it is opened.
This raises the "onOpenCallback" if defined and propagates to all children.
Definition
onOpen()

onClose

Description
Called on the root element of a screen view when it is closed.
This raises the "onCloseCallback" if defined and propagates to all children.
Definition
onClose()

shouldFocusChange

Description
Determine if this GuiElement should change focus in a given direction.
Definition
shouldFocusChange()

canReceiveFocus

Description
Determine if this GuiElement can receive focus.
Definition
canReceiveFocus()

onFocusLeave

Description
Called when this element loses focus.
This propagates to all children.
Definition
onFocusLeave()

onFocusEnter

Description
Called when this element becomes focused.
This propagates to all children.
Definition
onFocusEnter()

onFocusActivate

Description
Called when this element has focus and the focus activation action is triggered.
This propagates to all children.
Definition
onFocusActivate()

onHighlight

Description
Called when this element is highlighted.
This propagates to all children.
Definition
onHighlight()

onHighlightRemove

Description
Called when this element loses the highlight.
This propagates to all children.
Definition
onHighlightRemove()

storeOverlayState

Description

Store the current overlay state while another overrides it (e.g. pressed state)
Definition
storeOverlayState()

restoreOverlayState

Description
Restore a previously stored overlay state after an overriding state has expired
Definition
restoreOverlayState()

getHandleFocus

Description
Determine if this element can receive focus.
Definition
getHandleFocus()

setHandleFocus

Description
Set this elements capability to receive focus.
Definition
setHandleFocus()

addElement

Description
Add a child GuiElement to this GuiElement.
Definition
addElement()

removeElement

Description
Remove a child GuiElement from this GuiElement.
Definition
removeElement()

unlinkElement

Description
Safely remove this GuiElement from its parent, if it has a parent.
Definition
unlinkElement()

updateAbsolutePosition

Description
Update this elements absolute screen position.
This needs to be called whenever a position, alignment, origin or size value changes.
Definition
updateAbsolutePosition()

reset

Description
Resets the state of this GuiElement and its children.
Definition
reset()

isChildOf

Description
Check if this element is the child of another element.
This checks the full parent hierarchy.
Definition
isChildOf()

getFocusTarget

Description
Get the actual focus target, in case a child or parent element needs to be targeted instead.
Definition
getFocusTarget(incomingDirection (Optional), moveDirection (Optional))
Arguments
incomingDirection(Optional)If specified, may return different targets for different incoming directions.
moveDirection(Optional)Actual movement direction per input. This is the opposing direction of incomingDirection.
Return Values
GuiElementActualelement to focus.

setPosition

Description
Set this element's position.
Definition
setPosition()

move

Description
Modify this element's position (i.e. translate position).
Definition
move()

setAbsolutePosition

Description
Directly set the absolute screen position of this GuiElement.
Also updates children accordingly.
Definition
setAbsolutePosition()

setSize

Description
Set this element's size.
Definition
setSize()

setVisible

Description
Set this element's visibility.
Definition
setVisible()

getIsVisible

Description
Determine if this element is visible.
This checks both its current alpha value (set by fadeIn() / fadeOut()) as well as the visibility flag. If the parent
is invisible, then so is this element.
Definition
getIsVisible()

setDisabled

Description
Set this element's disabled state.
Disabled elements can be displayed differently and do not respond to input actions.
Definition
setDisabled(disabled If, doNotUpdateChildren If)
Arguments
disabledIftrue, disables the element. False enables it again.
doNotUpdateChildrenIftrue, does not apply the disabled state to child elements.

getIsDisabled

Description
Determine if this element is disabled.
Definition
getIsDisabled()

getIsSelected

Description
Determine if this element is currently selected.
Definition
getIsSelected()

getIsHighlighted

Description
Determine if this element is currently highlighted.
Definition
getIsHighlighted()

fadeIn

Description
Fade this element into visibility.
Definition
fadeIn()

fadeOut

Description
Fade this element out of visibility.
Definition
fadeOut()

setAlpha

Description
Directly set this element's alpha (transparency) value
Definition
setAlpha(alpha Transparency)
Arguments
alphaTransparencyvalue in the floating point range of [0, 1], where 0 is invisible and 1 is opaque.

getIsActive

Description
Determine if this element is active (not disabled and visible).
Does not take alpha value into account.
Definition
getIsActive()

setSoundSuppressed

Description
Toggle a flag to suppress UI sounds issued by this element or by the FocusManager when handling this element.
This setting will propagate to children.
Definition
setSoundSuppressed()

getSoundSuppressed

Description
Get the sound suppression flag from this element.
If the flag is set to true, no sounds should be played when interacting with this element.
Definition
getSoundSuppressed()

findDescendantsRec

Description

Recursively add descendant elements of a root to an accumulator list. If a predicate function is given, it is
evaluated per element and only elements which yield a true value for the function are added to the accumulator.
Definition
findDescendantsRec(accumulator List, rootElement Current, predicateFunction [optional])
Arguments
accumulatorListwhich receives descendant elements
rootElementCurrentelement root whose direction children are added (after optional evaluation)
predicateFunction[optional]If specified, will be evaluated per element (see getDescendants)

getDescendants

Description
Get all contained elements of this element in the entire hierarchy.
Descendants are traversed depth-first, meaning that if elements have been properly added, the element order mirrors
the order in the XML configuration (lines). Use this method sparingly, especially on high-level elements.
Optionally, a predicate function can be passed which filters descendant elements. The function must return true for
any desired element and false otherwise.
Definition
getDescendants(predicateFunction [optional])
Arguments
predicateFunction[optional]A function which determines if a descendant element should be returned. Must
take a GuiElement as an argument and return true if that element should be returned or false otherwise.
Return Values
Listofthis element's descendants in depth-first order with contiguous numeric indices.

getFirstDescendant

Description
Get the first descendant element of this element which matches a predicate function.
This is a shorthand for getDescendants() which returns just the first element matching the predicate function or nil
if no matching element exists.
Definition
getFirstDescendant(predicateFunction A)
Arguments
predicateFunctionAfunction which determines if a descendant element should be returned. Must take a
GuiElement as an argument and return true if that element should be returned or false otherwise.
Return Values
Firstmatchingdescendant element in depth-first order or nil, if no element matched the predicate function

getDescendantById

Description
Get a descendant element of this element by its ID.
This is a shorthand for getDescendants() with an ID matching predicate function.
Definition
getDescendantById(id Element)
Arguments
idElementid
Return Values
elementornil

getDescendantByName

Description
Get a descendant element of this element by its name.
This is a shorthand for getDescendants() with an ID matching predicate function.
Definition
getDescendantByName(name Element)
Arguments
nameElementname
Return Values
elementornil

updatePositionForOrigin

Description
Get the bit mask value for a position origin string value.
Definition
updatePositionForOrigin()

updateScreenAlign

Description
Get the bit mask value for a screen alignment string value.
Definition
updateScreenAlign()

getParentBorders

Description
Get the bottom left and top right corners of this element's parent's border rectangle.
If this element has no parent, the full screen's borders are returned (i.e. {0, 0, 1, 1})
Definition
getParentBorders()
Return Values
parentelementor full screen borders in an array: {minX, minY, maxX, maxY}

getBorders

Description
Get this element's border rectangle represented by minimum and maximum points.
Definition
getBorders()
Return Values
elementbordersin an array: {minX, minY, maxX, maxY}

getCenter

Description
Get this element's center position.
Definition
getCenter()

applyScreenAlignment

Description
Apply screen alignment to this element and its children.
Scales size, position and margin depending on alignment settings.
Definition
applyScreenAlignment()

setOverlayState

Description
Set this element's overlay state
Definition
setOverlayState(overlayState Overlay)
Arguments
overlayStateOverlaystate identified by one of the GuiOverlay.STATE_[...] constants.

getOverlayState

Description
Get this element's overlay state.
Definition
getOverlayState()

addCallback

Description
Add a callback to this element which was defined in its XML definition.
If this element has a target, the given function name will be called on the target. Otherwise, the function is
assumed to be global.
Definition
addCallback(xmlFile XML, key XML, funcName Name)
Arguments
xmlFileXMLfile handle
keyXMLnode path of this GuiElement's definition.
funcNameNameof the callback function

raiseCallback

Description
Raise a previously added callback by name.
Definition
raiseCallback()

extractIndexAndNameFromID

Description
Try to extract a field name and index from an element ID.
IDs in configurations may be indexed on definition (e.g. fillTypes[2]). This function extracts the list name and
index if such a case is found. Otherwise, it will return no index and the original element ID.
Definition
extractIndexAndNameFromID(elementId Element)
Arguments
elementIdElementID, to be used as a field name on a ScreenElement view.
Return Values
indexornil, field name

setId

Description
Try setting this element's ID from its XML definition.
Definition
setId()

include

Description
Include a mixin in this element.
See GuiMixin.lua for the details on usage and implementation of mixins.
Definition
include(guiMixinType Class)
Arguments
guiMixinTypeClasstable reference of a descendant of GuiMixin

toString

Description
Get a nice string representation for this GUI element.
Definition
toString()

GuiMixin

Description
GuiElement mixin base class.
-- Implements base functionality for GUI element mixins. All other GUI mixins should be descendants of this class.
-- Added methods:
GuiElement:hasIncluded(mixinType) Test if the GuiElement has included a mixin of the given type (class).
--@category GUI

new

Description
Create a new GuiMixin instance.
Subclasses need to provide their class type table for identification.
Definition
new(class Class, mixinType Class)
Arguments
classClassmetatable
mixinTypeClasstype table
Return Values
New

addTo

Description
Add a mixin to a GuiElement.
Adds mixin methods to the element which can then be used. A mixin's state is located in "element[mixinType]".
Definition
addTo()

hasIncluded

Description
Determine if a GuiElement has a mixin type included.
Definition
hasIncluded(GuiElement GuiElement, mixinType GuiMixin)
Arguments
GuiElementGuiElementinstance
mixinTypeGuiMixinclass reference

cloneMixin

Description
Clone mixin states for a mixin type from a source to a destination GuiElement instance.
Definition
cloneMixin()

clone

Description
Clone this mixin's state from a source to a destination GuiElement instance.
Definition
clone()

GuiOverlay

Description
GUI overlay manager.
-- Handles creation, loading and basic rendering of GUI overlays. This module has no interaction with Overlay.lua.
--@category GUI

loadOverlay

Description
Loads overlay data from XML or a profile into a table to turn it into an overlay.
Definition
loadOverlay()

loadXMLUVs

Description
Load overlay UV data from XML.
Definition
loadXMLUVs()

loadProfileUVs

Description
Load overlay UV data from a profile.
Definition
loadProfileUVs()

loadXMLColors

Description
Load overlay color data from XML.
Definition
loadXMLColors()

loadProfileColors

Description
Load overlay color data from a profile.
Definition
loadProfileColors()

createOverlay

Description
(Re-)Create an overlay.
Definition
createOverlay(Overlay Overlay, filename Path)
Arguments
OverlayOverlaytable, see loadOverlay()
filenamePathto image file (can also be a URL for web images)
Return Values
Overlaytablewith added image data

copyOverlay

Description
Copy an overlay.
Definition
copyOverlay()

deleteOverlay

Description
Delete an overlay.
Primarily releases the associated image file handle.
Definition
deleteOverlay()

getOverlayColor

Description
Get an overlay's color for a given overlay state.
Definition
getOverlayColor(Overlay Overlay, state GuiOverlay.STATE_[...])
Arguments
OverlayOverlaytable
stateGuiOverlay.STATE_[...]constant value
Return Values
Coloras{red, green, blue, alpha} with all values in the range of [0, 1]

getOverlayUVs

Description
Get an overlay's UV coordinates for a given overlay state.
Definition
getOverlayUVs(Overlay Overlay, state GuiOverlay.STATE_[...])
Arguments
OverlayOverlaytable
stateGuiOverlay.STATE_[...]constant value
Return Values
UVcoordinatesas {u1, v1, u2, v2, u3, v3, u4x, v4} with all values in the range of [0, 1]

renderOverlay

Description
Renders an overlay with the given parameters.
Definition
renderOverlay(Overlay Overlay, posX Screen, posY Screen, sizeX Screen, sizeY Screen, state GuiOverlay.STATE_[...])
Arguments
OverlayOverlaytable
posXScreenx position
posYScreeny position
sizeXScreenx size
sizeYScreeny size
stateGuiOverlay.STATE_[...]constant for the required display state

GuiProfile

Description
GUI element display profile.
-- Holds GuiElement property data for re-use similar to a HTML/CSS definition.
--@category GUI

new

Description
Create a new GuiProfile.
Definition
new(profiles Reference, traits Reference)
Arguments
profilesReferenceto loaded profiles table for inheritance checking.
traitsReferenceto loaded traits table for inheritance checking.
Return Values
NewGuiProfileinstance

loadFromXML

Description
Load profile data from XML.
Definition
loadFromXML(xmlFile XML, key Profile, presets Table, isTrait Whether)
Arguments
xmlFileXMLfile handle
keyProfileXML element node path
presetsTableof presets for symbol resolution, {preset name=preset value}
isTraitWhetherthis profile is a trait
Return Values
Trueifprofile values could be loaded, false otherwise.

getValue

Description
Get a string value from this profile (and its ancestors) by name.
Definition
getValue(name Name, default Default)
Arguments
nameNameof attribute value to retrieve
defaultDefaultvalue to use if the attribute is not defined.

getBool

Description
Get a boolean value from this profile (and its ancestors) by name.
Definition
getBool(name Name, default Default)
Arguments
nameNameof attribute value to retrieve
defaultDefaultvalue to use if the attribute is not defined.

getNumber

Description
Get a number value from this profile (and its ancestors) by name.
Definition
getNumber(name Name, default Default)
Arguments
nameNameof attribute value to retrieve
defaultDefaultvalue to use if the attribute is not defined.

GuiSoundPlayer

Description
GUI sound player.
-- This class loads known GUI sound samples as non-spatial samples to be played in the GUI (menu and HUD).
--@category GUI

new

Description
Create a new GuiSoundPlayer instance.
Definition
new(table soundManager)
Arguments
tablesoundManagerSoundManager reference

loadSounds

Description
Load GUI sound samples from definitions.
Definition
loadSounds()

playSample

Description
Play a GUI sound sample identified by name.
The sample must have been loaded when the GUI was created.
Definition
playSample(string sampleName)
Arguments
stringsampleNameName of the sample to play, use one of the identifiers in GuiSoundPlayer.SOUND_SAMPLES.

GuiUtils

Description
GUI utility functions.
--@category GUI

getNormalizedValues

Description
Transform an attribute string representing a list of numbers into an array and normalize the values.
Definition
getNormalizedValues(str Attribute, refSize Reference, defaultValue Default)
Arguments
strAttributestring containing numbers, either raw or with a pixel unit designation on each number (e.g. "12 24" or "12px 24px")
refSizeReferencesize for normalization, e.g. a reference screen resolution used to scale pixel values, {sizeX, sizeY}
defaultValueDefaultvalue to return if the "str" parameter value is nil
Return Values
arrayofnormalized values

get2DArray

Description
Transform an attribute string representing a 2D array into an actual array.
Definition
get2DArray(str Attribute, defaultValue Default)
Arguments
strAttributestring containing exactly 2 numbers
defaultValueDefaultvalue to return if the "str" parameter value is nil or invalid for transformation.
Return Values
arrayofthe 2 converted values as numbers: {value1, value2}

get4DArray

Description
Transform an attribute string representing a 4D array into an actual array.
Definition
get4DArray(str Attribute, defaultValue Default)
Arguments
strAttributestring containing exactly 4 numbers
defaultValueDefaultvalue to return if the "str" parameter value is nil or invalid for transformation.
Return Values
arrayofthe 4 converted values as numbers: {value1, value2, value3, value4}

getColorArray

Description
Transform an attribute string representing a 4D color array into an actual array.
Definition
getColorArray(str Attribute, defaultValue Default)
Arguments
strAttributestring containing exactly 4 numbers
defaultValueDefaultvalue to return if the "str" parameter value is nil or invalid for transformation.
Return Values
arrayofthe 4 converted values as numbers: {red, green, blue, alpha}

getUVs

Description
Transform an attribute string representing a UV array into an actual array and normalize the values.
Definition
getUVs(str Attribute, ref Texture, defaultValue Default)
Arguments
strAttributestring containing exactly 4 numbers, order and format: "x[px] y[px] sizeX[px] sizeY[px]"
refTexturereference size used to normalize pixel UV coordinates into unit sized UV coordinates
defaultValueDefaultvalue to return if the "str" parameter value is nil or invalid for transformation.
Return Values
arrayofthe UV coordinates as {u1, v1, u2, v2, u3, v3, u4, v4}

checkOverlayOverlap

Description
Check if a point lies within or a hotspot overlaps an overlay.
Definition
checkOverlayOverlap(posX Point, posY Point, overlayX Overlay, overlayY Overlay, overlaySizeX Overlay, overlaySizeY Overlay, hotspot If)
Arguments
posXPointor hotspot x position
posYPointor hotspot y position
overlayXOverlayx position
overlayYOverlayy position
overlaySizeXOverlaywidth
overlaySizeYOverlayheight
hotspotIfprovided as an array having 4 numbers for the bounding points of a rectangle {minX, minY, maxX, maxY}, will be checked if it overlaps the overlay area given by the other parameters.

HighPressureWasherPlaceable

Description

HighPressureWasher Activatable

new

Description
Creating placeable high pressure washer
Definition
new(boolean isServer, boolean isClient, table customMt)
Arguments
booleanisServeris server
booleanisClientis client
tablecustomMtcustom metatable
Return Values
tableinstanceInstance of object
Code
20function HighPressureWasher:new(isServer, isClient, customMt)
21 local mt = customMt
22 if mt == nil then
23 mt = HighPressureWasher_mt
24 end
25
26 local self = Placeable:new(isServer, isClient, mt)
27 registerObjectClassName(self, "HighPressureWasher")
28
29 return self
30end

load

Description
Load high pressure washer
Definition
load(string xmlFilename, float x, float y, float z, float rx, float ry, float rz, boolean initRandom)
Arguments
stringxmlFilenamexml file name
floatxx world position
floatyz world position
floatzz world position
floatrxrx world rotation
floatryry world rotation
floatrzrz world rotation
booleaninitRandominitialize random
Return Values
booleansuccesssuccess
Code
43function HighPressureWasher:load(xmlFilename, x,y,z, rx,ry,rz, initRandom)
44 if not HighPressureWasher:superClass().load(self, xmlFilename, x,y,z, rx,ry,rz, initRandom) then
45 return false
46 end
47
48 local xmlFile = loadXMLFile("TempXML", xmlFilename)
49
50 self.lanceNode = I3DUtil.indexToObject(self.nodeId, getXMLString(xmlFile, "placeable.highPressureWasher.lance#index"))
51 self.handtoolXML = Utils.getFilename(getXMLString(xmlFile, "placeable.highPressureWasher.handtool#filename"), self.baseDirectory)
52 self.playerInRangeDistance = Utils.getNoNil(getXMLFloat(xmlFile, "placeable.highPressureWasher.playerInRangeDistance"), 3)
53 self.actionRadius = Utils.getNoNil(getXMLFloat(xmlFile, "placeable.highPressureWasher.actionRadius#distance"), 15)
54
55 if self.isClient then
56 self.hpwSamples = {}
57 if self.isClient then
58 self.hpwSamples.compressor = g_soundManager:loadSampleFromXML(xmlFile, "placeable.highPressureWasher.sounds", "compressor", self.baseDirectory, self.nodeId, 0, AudioGroup.VEHICLE, nil, self)
59 self.hpwSamples.switch = g_soundManager:loadSampleFromXML(xmlFile, "placeable.highPressureWasher.sounds", "switch", self.baseDirectory, self.nodeId, 1, AudioGroup.VEHICLE, nil, self)
60 end
61
62 local filename = getXMLString(xmlFile, "placeable.highPressureWasher.exhaust#filename")
63 if filename ~= nil then
64 local i3dNode = g_i3DManager:loadSharedI3DFile(filename, self.baseDirectory, false, false, false)
65 if i3dNode ~= 0 then
66 local linkNode = Utils.getNoNil(I3DUtil.indexToObject(self.nodeId, getXMLString(xmlFile, "placeable.highPressureWasher.exhaust#index")), self.nodeId)
67 self.exhaustFilename = filename
68 self.exhaustNode = getChildAt(i3dNode, 0)
69 link(linkNode, self.exhaustNode)
70 setVisibility(self.exhaustNode, false)
71 delete(i3dNode)
72 end
73 end
74 end
75
76 delete(xmlFile)
77
78 self.isPlayerInRange = false
79 self.isTurnedOn = false
80 self.isTurningOff = false
81 self.turnOffTime = 0
82 self.turnOffDuration = 500
83 self.activatable = HighPressureWasherActivatable:new(self)
84 self.lastInRangePosition = {0,0,0}
85
86 return true
87end

delete

Description
Deleting placeable high pressure washer
Definition
delete()
Code
91function HighPressureWasher:delete()
92 self:setIsTurnedOn(false, nil, false)
93 if self.isClient then
94 if self.exhaustFilename ~= nil then
95 g_i3DManager:releaseSharedI3DFile(self.exhaustFilename, self.baseDirectory, true)
96 end
97 g_soundManager:deleteSamples(self.hpwSamples)
98 end
99
100 unregisterObjectClassName(self)
101 g_currentMission:removeActivatableObject(self.activatable)
102 HighPressureWasher:superClass().delete(self)
103end

readStream

Description
Called on client side on join
Definition
readStream(integer streamId, table connection)
Arguments
integerstreamIdstream ID
tableconnectionconnection
Code
109function HighPressureWasher:readStream(streamId, connection)
110 HighPressureWasher:superClass().readStream(self, streamId, connection)
111 if connection:getIsServer() then
112 local isTurnedOn = streamReadBool(streamId)
113 if isTurnedOn then
114 local player = NetworkUtil.readNodeObject(streamId)
115 if player ~= nil then
116 self:setIsTurnedOn(isTurnedOn, player, true)
117 end
118 end
119 end
120end

writeStream

Description
Called on server side on join
Definition
writeStream(integer streamId, table connection)
Arguments
integerstreamIdstream ID
tableconnectionconnection
Code
126function HighPressureWasher:writeStream(streamId, connection)
127 HighPressureWasher:superClass().writeStream(self, streamId, connection)
128 if not connection:getIsServer() then
129 streamWriteBool(streamId, self.isTurnedOn)
130 if self.isTurnedOn then
131 NetworkUtil.writeNodeObject(streamId, self.currentPlayer)
132 end
133 end
134end

activateHandtool

Description
Activate hand tool
Definition
activateHandtool(table player)
Arguments
tableplayerplayer
Code
139function HighPressureWasher:activateHandtool(player)
140 self:setIsTurnedOn(true, player, true)
141end

update

Description
Update
Definition
update(float dt)
Arguments
floatdttime since last call in ms
Code
146function HighPressureWasher:update(dt)
147 HighPressureWasher:superClass().update(self, dt)
148
149 if self.currentPlayer ~= nil then
150 local isPlayerInRange = self:getIsPlayerInRange(self.actionRadius, self.currentPlayer)
151 if isPlayerInRange then
152 self.lastInRangePosition = {getTranslation(self.currentPlayer.rootNode)}
153 else
154 local kx, _, kz = getWorldTranslation(self.nodeId)
155 local px, py, pz = getWorldTranslation(self.currentPlayer.rootNode)
156 local len = MathUtil.vector2Length(px-kx, pz-kz)
157
158 local x,y,z = unpack(self.lastInRangePosition)
159 x = kx + ((px-kx) / len) * (self.actionRadius-0.00001*dt)
160 z = kz + ((pz-kz) / len) * (self.actionRadius-0.00001*dt)
161 self.currentPlayer:moveToAbsoluteInternal(x, py, z)
162 self.lastInRangePosition = {x,y,z}
163
164 if self.currentPlayer == g_currentMission.player then
165 g_currentMission:showBlinkingWarning(g_i18n:getText("warning_hpwRangeRestriction"), 4000)
166 end
167 end
168 end
169
170 if self.isClient then
171 if self.isTurningOff then
172 if g_currentMission.time > self.turnOffTime then
173 self.isTurningOff = false
174 g_soundManager:stopSample(self.hpwSamples.compressor)
175 end
176 end
177 end
178
179 self:raiseActive()
180end

updateTick

Description
updateTick
Definition
updateTick(float dt)
Arguments
floatdttime since last call in ms
Code
197function HighPressureWasher:updateTick(dt)
198 HighPressureWasher:superClass().updateTick(self, dt)
199 local isPlayerInRange, player = self:getIsPlayerInRange(self.playerInRangeDistance)
200
201 if isPlayerInRange and g_currentMission.accessHandler:canPlayerAccess(self, player) then
202 self.playerInRange = player
203 self.isPlayerInRange = true
204 g_currentMission:addActivatableObject(self.activatable)
205 else
206 self.playerInRange = nil
207 self.isPlayerInRange = false
208 g_currentMission:removeActivatableObject(self.activatable)
209 end
210end

setIsTurnedOn

Description
Set is turned on
Definition
setIsTurnedOn(boolean isTurnedOn, table player, boolean noEventSend)
Arguments
booleanisTurnedOnis turned on
tableplayerplayer
booleannoEventSendno event send
Code
217function HighPressureWasher:setIsTurnedOn(isTurnedOn, player, noEventSend)
218 HPWPlaceableTurnOnEvent.sendEvent(self, isTurnedOn, player, noEventSend)
219
220 if self.isTurnedOn ~= isTurnedOn then
221 if isTurnedOn then
222 self.isTurnedOn = isTurnedOn
223
224 if player ~= nil then
225 self.currentPlayer = player
226 self.currentPlayer:addDeleteListener(self, "onPlayerDelete")
227 if noEventSend ~= true then
228 self.currentPlayer:equipHandtool(self.handtoolXML, true, noEventSend)
229 self.currentPlayer.baseInformation.currentHandtool:addDeleteListener(self, "onHandtoolDelete")
230 end
231 end
232
233 if self.isClient then
234 g_soundManager:playSample(self.hpwSamples.switch)
235 g_soundManager:playSample(self.hpwSamples.compressor)
236
237 if self.isTurningOff then
238 self.isTurningOff = false
239 end
240 setVisibility(self.lanceNode, false)
241 end
242 else
243 self:onDeactivate()
244 end
245 if self.exhaustNode ~= nil then
246 setVisibility(self.exhaustNode, isTurnedOn)
247 end
248 end
249end

onPlayerDelete

Description
Definition
onPlayerDelete()
Code
253function HighPressureWasher:onPlayerDelete()
254 self.currentPlayer = nil
255 self:setIsTurnedOn(false, nil, nil)
256end

onHandtoolDelete

Description
Definition
onHandtoolDelete()
Code
260function HighPressureWasher:onHandtoolDelete()
261 self.currentPlayer = nil
262 self:setIsTurnedOn(false, nil, nil)
263end

onDeactivate

Description
On deactivate
Definition
onDeactivate()
Code
267function HighPressureWasher:onDeactivate()
268 if self.isClient then
269 g_soundManager:playSample(self.hpwSamples.switch)
270 g_soundManager:stopSample(self.hpwSamples.washing, true)
271 self.isTurningOff = true
272 self.turnOffTime = g_currentMission.time + self.turnOffDuration
273 end
274 self.isTurnedOn = false
275 setVisibility(self.lanceNode, true)
276 if self.currentPlayer ~= nil then
277 if self.currentPlayer:hasHandtoolEquipped() then
278 self.currentPlayer.baseInformation.currentHandtool:removeDeleteListener(self, "onHandtoolDelete")
279 self.currentPlayer:unequipHandtool()
280 end
281 self.currentPlayer:removeDeleteListener(self, "onPlayerDelete")
282 self.currentPlayer = nil
283 end
284end

getIsActiveForInput

Description
Get is active for input
Definition
getIsActiveForInput()
Return Values
booleanisActiveForInputis active for input
Code
289function HighPressureWasher:getIsActiveForInput()
290 if self.isTurnedOn and self.currentPlayer == g_currentMission.player and not g_gui:getIsGuiVisible() then
291 return true
292 end
293 return false
294end

getIsActiveForSound

Description
Get is active for sound
Definition
getIsActiveForSound()
Return Values
booleanisActiveForSoundis active for sound
Code
299function HighPressureWasher:getIsActiveForSound()
300 return self:getIsActiveForInput()
301end

canBeSold

Description
Get can be sold in current state
Definition
canBeSold()
Return Values
boolean
stringwarningMessagewarning message displayed in the shop
Code
307function HighPressureWasher:canBeSold()
308 local warning = g_i18n:getText("shop_messageReturnVehicleInUse")
309 if self.currentPlayer ~= nil then
310 return false, warning
311 end
312 return true, nil
313end

Horse

Description
Minimum daily riding time for a horse below which it will lose fitness.

new

Description
Definition
new()
Code
22function Horse:new(isServer, isClient, owner, fillTypeIndex, customMt)
23 local self = RideableAnimal:new(isServer, isClient, owner, fillTypeIndex, customMt or Horse_mt)
24
25 self.name = g_animalNameManager:getRandomName()
26
27 self.fitnessScale = 0.0
28 self.fitnessScaleSent = 0.0
29
30 self.healthScale = 1.0
31 self.healthScaleSent = 1.0
32
33 self.ridingTimer = 0.0
34
35 self.horseDirtyFlag = self:getNextDirtyFlag()
36
37 return self
38end

readStream

Description
Definition
readStream()
Code
42function Horse:readStream(streamId)
43 Horse:superClass().readStream(self, streamId)
44
45 self.name = streamReadString(streamId)
46 self.fitnessScale = streamReadFloat32(streamId)
47 self.healthScale = streamReadFloat32(streamId)
48 self.ridingTimer = streamReadFloat32(streamId)
49end

writeStream

Description
Definition
writeStream()
Code
53function Horse:writeStream(streamId)
54 Horse:superClass().writeStream(self, streamId)
55
56 streamWriteString(streamId, self.name)
57 streamWriteFloat32(streamId, self.fitnessScale)
58 streamWriteFloat32(streamId, self.healthScale)
59 streamWriteFloat32(streamId, self.ridingTimer)
60end

readUpdateStream

Description
Definition
readUpdateStream()
Code
64function Horse:readUpdateStream(streamId, timestamp, connection)
65 Horse:superClass().readUpdateStream(self, streamId, timestamp, connection)
66
67 -- server to client only
68 if connection:getIsServer() then
69 if streamReadBool(streamId) then
70 self.fitnessScale = NetworkUtil.readCompressedPercentages(streamId, 7)
71 self.healthScale = NetworkUtil.readCompressedPercentages(streamId, 7)
72 end
73 end
74end

writeUpdateStream

Description
Definition
writeUpdateStream()
Code
78function Horse:writeUpdateStream(streamId, connection, dirtyMask)
79 Horse:superClass().writeUpdateStream(self, streamId, connection, dirtyMask)
80
81 -- server to client only
82 if not connection:getIsServer() then
83 if streamWriteBool(streamId, bitAND(dirtyMask, self.horseDirtyFlag) ~= 0) then
84 NetworkUtil.writeCompressedPercentages(streamId, self.fitnessScaleSent, 7)
85 NetworkUtil.writeCompressedPercentages(streamId, self.healthScaleSent, 7)
86 end
87 end
88end

loadFromXMLFile

Description
Definition
loadFromXMLFile()
Code
92function Horse:loadFromXMLFile(xmlFile, key)
93 Horse:superClass().loadFromXMLFile(self, xmlFile, key)
94
95 self.name = getXMLString(xmlFile, key.."#name") or self.name
96 self.fitnessScale = getXMLFloat(xmlFile, key.."#fitnessScale") or self.fitnessScale
97 self.healthScale = getXMLFloat(xmlFile, key.."#healthScale") or self.healthScale
98 self.ridingTimer = getXMLFloat(xmlFile, key.."#ridingTimer") or self.ridingTimer
99 self.fitnessScaleSent = self.fitnessScale
100end

saveToXMLFile

Description
Definition
saveToXMLFile()
Code
104function Horse:saveToXMLFile(xmlFile, key, usedModNames)
105 Horse:superClass().saveToXMLFile(self, xmlFile, key, usedModNames)
106
107 setXMLString(xmlFile, key.."#name", self.name)
108 setXMLFloat(xmlFile, key.."#fitnessScale", self.fitnessScale)
109 setXMLFloat(xmlFile, key.."#healthScale", self.healthScale)
110 setXMLFloat(xmlFile, key.."#ridingTimer", self.ridingTimer)
111end

setName

Description
Definition
setName()
Code
115function Horse:setName(name)
116
117 if self.name ~= nil and self.name ~= name then
118 self.name = name
119 g_messageCenter:publish(MessageType.HUSBANDRY_ANIMALS_CHANGED, self.owner)
120 end
121end

getName

Description
Definition
getName()
Code
125function Horse:getName()
126 return self.name
127end

getValueScale

Description
Definition
getValueScale()
Code
131function Horse:getValueScale()
132 -- dirt scale should only count 10%
133 return 0.90 * (self.fitnessScale * self.healthScale) + 0.10 * (1-self.dirtScale)
134end

setFitnessScale

Description
Definition
setFitnessScale()
Code
138function Horse:setFitnessScale(scale, noEventSend)
139 self.fitnessScale = scale
140 if math.abs(self.fitnessScaleSent - self.fitnessScale) > 0.01 then
141 self.fitnessScaleSent = self.fitnessScale
142 g_messageCenter:publish(MessageType.HUSBANDRY_ANIMALS_CHANGED, self.owner)
143
144 if noEventSend == nil or not noEventSend then
145 self:raiseDirtyFlags(self.horseDirtyFlag)
146 end
147 end
148end

getFitnessScale

Description
Definition
getFitnessScale()
Code
152function Horse:getFitnessScale()
153 return self.fitnessScale
154end

setHealthScale

Description
Definition
setHealthScale()
Code
158function Horse:setHealthScale(scale, noEventSend)
159 self.healthScale = scale
160 if math.abs(self.healthScaleSent - self.healthScale) > 0.01 then
161 self.healthScaleSent = self.healthScale
162 g_messageCenter:publish(MessageType.HUSBANDRY_ANIMALS_CHANGED, self.owner)
163
164 if noEventSend == nil or not noEventSend then
165 self:raiseDirtyFlags(self.horseDirtyFlag)
166 end
167 end
168end

getHealthScale

Description
Definition
getHealthScale()
Code
172function Horse:getHealthScale()
173 return self.healthScale
174end

getTodaysRidingTime

Description
Get the riding time of this horse for the current day in milliseconds.
Definition
getTodaysRidingTime()

deactivateRiding

Description
Definition
deactivateRiding()
Code
183function Horse:deactivateRiding(noEventSend)
184 if self.rideableVehicle ~= nil then
185 self.rideableVehicle:setFitnessChangedCallback(nil, nil)
186 end
187
188 Horse:superClass().deactivateRiding(self, noEventSend)
189end

onLoadedRideable

Description
Definition
onLoadedRideable()
Code
193function Horse:onLoadedRideable(rideableVehicle, vehicleLoadState, arguments)
194 Horse:superClass().onLoadedRideable(self, rideableVehicle, vehicleLoadState, arguments)
195
196 if self.rideableVehicle ~= nil then
197 self.rideableVehicle:setFitnessChangedCallback(self.onFitnessChangedCallback, self)
198 end
199end

onFitnessChangedCallback

Description
Definition
onFitnessChangedCallback()
Code
203function Horse:onFitnessChangedCallback(deltaTime)
204 self.ridingTimer = self.ridingTimer + deltaTime
205end

updateFitness

Description
Definition
updateFitness()
Code
209function Horse:updateFitness()
210 if self.isServer then
211 local fitness = self:getFitnessScale()
212
213 if self.ridingTimer < Horse.DAILY_MINIMUM_RIDING_TIME then
214 fitness = fitness - 0.02
215 else -- add capped gain
216 local fitnessGain = math.min(0.1, 0.1 * self.ridingTimer / Horse.DAILY_TARGET_RIDING_TIME)
217 fitness = fitness + fitnessGain
218 end
219
220 fitness = MathUtil.clamp(fitness, 0.0, 1.0)
221 self:setFitnessScale(fitness)
222 end
223
224 self.ridingTimer = 0.0
225end

HUD

Description
Heads-up display.
-- The HUD displays information for the player when in game.
--@category GUI

new

Description
Create a new HUD instance.
Definition
new(bool isServer, bool isServer, bool isConsoleVersion, table messageCenter, table l10n, table inputManager, table inputDisplayManager, table modManager, table fillTypeManager, table fruitTypeManager, table guiSoundPlayer)
Arguments
boolisServerIf true, the running game instance is a server
boolisServerIf true, the running game instance is a client
boolisConsoleVersionIf true, we are running on console
tablemessageCenterMessageCenter reference for message subscriptions
tablel10nI18N reference for text localization
tableinputManagerInputBinding reference
tableinputDisplayManagerInputDisplayManager reference
tablemodManagerModManager reference
tablefillTypeManagerFillTypeManager reference
tablefruitTypeManagerFruitTypeManager reference
tableguiSoundPlayerGuiSoundPlayer reference

createDisplayComponents

Description
Create all required display components.
Definition
createDisplayComponents(uiScale Current)
Arguments
uiScaleCurrentUI scale

delete

Description
Delete the HUD and all its display components.
Definition
delete()

subscribeMessages

Description
Subscribe to relevant state messages.
Definition
subscribeMessages()

setScale

Description
Set the scale of the HUD.
Definition
setScale(float scale)
Arguments
floatscaleNew scale value

drawControlledEntityHUD

Description
Draw the HUD components for the currently controlled entity (player or vehicle).
Definition
drawControlledEntityHUD()

drawInputHelp

Description
Draw the input help display panel and vehicle schema.
Definition
drawInputHelp()

drawTopNotification

Description
Draw a notification at the top center of the screen if one has been set.
Definition
drawTopNotification()

drawBlinkingWarning

Description
Draw a blinking warning if necessary.
Definition
drawBlinkingWarning()

drawPresentationVersion

Description
Draw the presentation mode logo.
Definition
drawPresentationVersion()

drawFading

Description
Draw the screen fade effect.
Definition
drawFading()

drawOverlayAtPositionWithDimensions

Description
Draw an overlay at a given screen space position with given dimensions.
Omitting a parameter will use the last setting of that parameter (or initial setting if parameter is never supplied).
Definition
drawOverlayAtPositionWithDimensions(table overlay, float screenX, float screenY, float screenWidth, float screenHeight)
Arguments
tableoverlayOverlay instance to draw
floatscreenXDrawing origin X position in screen space
floatscreenYDrawing origin Y position in screen space
floatscreenWidthDrawing horizontal size in screen space
floatscreenHeightDrawing vertical size in screen space

drawOverlayAtPosition

Description
Draw an overlay at a given screen space position.
Omitting a parameter will use the last setting of that parameter.
Definition
drawOverlayAtPosition(table overlay, float screenX, float screenY)
Arguments
tableoverlayOverlay instance to draw
floatscreenXDrawing origin X position in screen space
floatscreenYDrawing origin Y position in screen space

drawSideNotification

Description
Draw notification texts at the side of the screen.
Definition
drawSideNotification()

drawBaseHUD

Description
Draw the regular HUD for career mode.
Definition
drawBaseHUD()

drawCommunicationDisplay

Description
Draw the platform communication display (chat or speaker icons).
Definition
drawCommunicationDisplay()

setTutorialProgress

Description
Set the tutorial progress.
Definition
setTutorialProgress(float progress)
Arguments
floatprogressProgress expressed as a number between 0 and 1

drawGamePaused

Description
Draw a pause notification with a message text and synchronizing background if the menu is visible.
Definition
drawGamePaused(bool beforeMissionStart)
Arguments
boolbeforeMissionStartIf true, draw a special overlay for cases when the menu has not yet loaded but the world is already visible.

drawVehicleName

Description
Draw the current vehicle name if it's active.
Definition
drawVehicleName()

drawInGameMessageAndIcon

Description
Draw the message window and icon at the bottom of the screen.
Definition
drawInGameMessageAndIcon()

drawMissionCompleted

Description
Show a "mission accomplished" message.
Definition
drawMissionCompleted()

drawMissionFailed

Description
Show a "mission failed" message.
Definition
drawMissionFailed()

showInGameMessage

Description
Display an in-game message in a window at the bottom.
This calls InGameMessage:showMessage(title, message, duration, controls, callback, target).
Definition
showInGameMessage()

showBlinkingWarning

Description
Display a blinking warning text.
Definition
showBlinkingWarning(string text, int duration, int priority)
Arguments
stringtextWarning text
intduration[optional, default=2000] Duration of warning visibility in milliseconds
intpriority[optional, default=0] Warning priority value. If a new warning is triggered with the same or higher priority as a current
one, the current warning is replaced.

addMoneyChange

Description
Accumulate a money transaction amount by type until shown by HUD.showMoneyChange().
Definition
addMoneyChange(int moneyType, float amount)
Arguments
intmoneyTypeType of transaction from EconomyManager.MONEY_TYPE_XYZ
floatamountAmount of money

showMoneyChange

Description
Display a money change notification at the right side of the screen.
Definition
showMoneyChange(int moneyType, string text)
Arguments
intmoneyTypeType of transaction from EconomyManager.MONEY_TYPE_XYZ
stringtextSpecific money type label (e.g. "loan interest")

addExtraPrintText

Description
Add an extra text to display in the input help panel for this frame.
Definition
addExtraPrintText()

showVehicleName

Description
Display the name of a vehicle at the bottom of the screen for a short time.
Definition
showVehicleName(string vehicleName)
Arguments
stringvehicleNameName of a vehicle

addSideNotification

Description
Add a notification to be displayed at the right side of the screen.
Definition
addSideNotification(table color)
Arguments
tablecolorColor as an RGBA array

addTopNotification

Description
Add a notification to be displayed in a frame at the top of the screen.
Definition
addTopNotification(string title, string text, string info, table iconKey, int duration)
Arguments
stringtitleNotification title
stringtextNotification message text
stringinfoAdditional info text
tableiconKey[optional] Icon key for a display icon, use a value from TopNotification.ICON
intduration[optional] Display duration in milliseconds. Negative values or nil default to a long-ish standard duration.

hideTopNotification

Description
Hide a current notification shown by HUD:addTopNotification().
Definition
hideTopNotification()

getIsFading

Description
Check if the HUD is currently fading the screen.
Definition
getIsFading()

setGameInfoPartVisibility

Description
Set the visibility of the game info display parts by flags.
Definition
setGameInfoPartVisibility(partFlags Combination)
Arguments
partFlagsCombinationof values from HUD.GAME_INFO_PART

onMenuVisibilityChange

Description
Handle menu visibility changes.
Keeps track of the menu visibility to block relevant processes.
Definition
onMenuVisibilityChange()

onPauseGameChange

Description
Handle game pause state changes.
Definition
onPauseGameChange(bool isPaused, string pauseText)
Arguments
boolisPaused[optional] If true, the game is currently paused. If not set, will not change the pause state.
stringpauseText[optional] Text to display on the pause element

setIsVisible

Description
Set HUD visibility.
Definition
setIsVisible(bool isVisible)
Arguments
boolisVisibleIf true, the HUD is made visible. If false, it's made invisible.

setInputHelpVisible

Description
Set input help visibility.
Definition
setInputHelpVisible(bool isVisible)
Arguments
boolisVisibleIf true, the input help is displayed. If false, it's made invisible

setFieldInfoVisible

Description
Set field info display visibility.
Definition
setFieldInfoVisible(bool isVisible)
Arguments
boolisVisibleIf true, the field info display is shown. If false, it's hidden.

addCustomInputHelpEntry

Description
Add a custom input help entry which is displayed until removed.
Custom entries will be displayed in order of addition after any automatically detected input help entries and before
vehicle extensions.
Definition
addCustomInputHelpEntry()

clearCustomInputHelpEntries

Description
Clear all custom input help entries.
Definition
clearCustomInputHelpEntries()

getIsVisible

Description
Check if the HUD is visible.
Definition
getIsVisible()
Return Values
boolIftrue, the HUD is currently visible.

setControlledVehicle

Description
Set current controlled vehicle.
Definition
setControlledVehicle(table vehicle)
Arguments
tablevehicleVehicle reference or nil (not controlling a vehicle)

setIsControllingPlayer

Description
Set current player controlling state.
Definition
setIsControllingPlayer(bool isControllingPlayer)
Arguments
boolisControllingPlayerIf true, the player is controlling their character on foot.

setMoneyUnit

Description
Set the money unit (currency) to display.
Definition
setMoneyUnit(int unit)
Arguments
intunitOne of [GS_MONEY_EURO | GS_MONEY_POUND], any other value will display a universal dollar sign.

showAchievementMessage

Description
Display an achievement message.
Definition
showAchievementMessage()

showAttachContext

Description
Display vehicle attachment context information for the current frame.
Definition
showAttachContext()

showTipContext

Description
Display vehicle tipping context information for the current frame.
Definition
showTipContext()

showFuelContext

Description
Display vehicle refueling context information for the current frame.
Definition
showFuelContext()

showFillDogBowlContext

Description
Display dog bowl refilling context information for the current frame.
Definition
showFillDogBowlContext()

setPlayer

Description
Set the reference to the current player.
Definition
setPlayer()

setConnectedUsers

Description
Set the references to the currently connected users.
Definition
setConnectedUsers()

updateMessageAndIcon

Description
Update in-game message window and icon.
Definition
updateMessageAndIcon()

update

Description
Update base HUD state.
Definition
update()

updateBlinkingWarning

Description
Update the blinking warning if one is set.
Definition
updateBlinkingWarning()

updateMap

Description
Update the in-game map.
Definition
updateMap()

updateVehicleName

Description
Update vehicle name display when a vehicle was entered.
Definition
updateVehicleName()

fadeScreen

Description
Fade the screen.
Definition
fadeScreen(int direction, int duration, func callbackFunc, table callbackTarget)
Arguments
intdirectionIf > 0 will fade to opaque (i.e. black screen), if < 0 will fade to transparent (i.e. clear)
intdurationTarget duration of the fade animation in milliseconds
funccallbackFunc[optional] Callback function which is called when the fading animation completes
tablecallbackTarget[optional] Callback function target which is passed to the callback function as its first
argument if provided

loadIngameMap

Description
Load graphics and settings for the in-game map.
Definition
loadIngameMap(string ingameMapFilename, int ingameMapWidth, int ingameMapHeight)
Arguments
stringingameMapFilenamePath to map image
intingameMapWidthWidth of the map (X)
intingameMapHeightHeight of the map (Y)

setIngameMapSize

Description
Set the size index of the in-game map.
Definition
setIngameMapSize(int sizeIndex)
Arguments
intsizeIndexOne of [IngameMap.STATE_MINIMAP | IngameMap.STATE_MAP | IngameMap.STATE_OFF]

getIngameMap

Description
Get the in-game map reference.
Definition
getIngameMap()

isInGameMessageActive

Description
Check if the in-game message is currently active.
Definition
isInGameMessageActive()

mouseEvent

Description
Mouse event function.
Only delegates input to components.
Definition
mouseEvent()

setEnvironment

Description
Set the environment reference to use for weather information display.
Definition
setEnvironment(table environment)
Arguments
tableenvironmentEnvironment reference, do not change

setMissionInfo

Description
Set the mission information reference for base information display.
Definition
setMissionInfo(table missionInfo)
Arguments
tablemissionInfoMissionInfo reference, do not change

setMissionStats

Description
Set the mission statistics reference for base information display.
Definition
setMissionStats(table missionStats)
Arguments
tablemissionStatsMissionStats reference, do not change

setInGameIconOnPickup

Description
Set the in-game icon display when picking up an egg or nugget.
Definition
setInGameIconOnPickup()

scrollChatMessages

Description
Scroll chat messages by a given amount.
Definition
scrollChatMessages(int delta, int numMessages)
Arguments
intdeltaNumber of lines (positive or negative) to scroll
intnumMessagesNumber of currently stored chat messages

setChatWindowVisible

Description
Set chat window visibility.
When disabled, the chat display will linger for some time.
Definition
setChatWindowVisible()

setChatMessagesReference

Description
Set the chat messages array reference for the chat window.
The array is owned by the caller and must not be modified by consumers.
Definition
setChatMessagesReference()

registerInput

Description
Register input events of HUD components.
Definition
registerInput()

HUDDisplayElement

Description
HUD display element whose subclasses implement more complex HUD display subsystems.
--@category GUI

new

Description
Create a new HUD display element.
Definition
new(table subClass, table overlay, table parentHudElement)
Arguments
tablesubClassSubclass metatable for inheritance
tableoverlayWrapped Overlay instance
tableparentHudElement[optional] Parent HUD element of the newly created HUD element
Return Values
tableHUDDisplayElementinstance

setVisible

Description
Set this element's visibility with optional animation.
Definition
setVisible(bool isVisible, bool animate)
Arguments
boolisVisibleTrue is visible, false is not.
boolanimateIf true, the element will play an animation before applying the visibility change.

setScale

Description
Simplification of scale setter because these high-level elements always use a uniform scale.
Definition
setScale()

storeOriginalPosition

Description
Store the current element position as its original positions.
Definition
storeOriginalPosition()

getHidingTranslation

Description
Get the screen space translation for hiding.
Override in sub-classes if a different translation is required.
Definition
getHidingTranslation()
Return Values
floatScreenspace X translation
floatScreenspace Y translation

animationSetPositionX

Description
Animation setter function for X position.
Definition
animationSetPositionX()

animationSetPositionY

Description
Animation setter function for Y position.
Definition
animationSetPositionY()

animateHide

Description
Animate this element on hiding.
Definition
animateHide()

animateShow

Description
Animate this element on showing.
Definition
animateShow()

onAnimateVisibilityFinished

Description
Called when a hiding or showing animation has finished.
Definition
onAnimateVisibilityFinished()

HUDElement

Description
Lightweight HUD UI element.
-- Wraps an Overlay instance to display and provides a transform hierarchy of child HUDElement instances.
--@category GUI

new

Description
Create a new HUD element.
Definition
new(table subClass, table overlay, table parentHudElement)
Arguments
tablesubClassSubclass metatable for inheritance
tableoverlayWrapped Overlay instance
tableparentHudElement[optional] Parent HUD element of the newly created HUD element
Return Values
tableHUDElementinstance

delete

Description
Delete this HUD element and all its children.
This will also delete the overlay and thus release its engine handle.
Definition
delete()

addChild

Description
Add a child HUD element to this element.
Definition
addChild(table childHudElement)
Arguments
tablechildHudElementHUDElement instance which is added as a child.

removeChild

Description
Remove a child HUD element from this element.
Definition
removeChild(table childHudElement)
Arguments
tablechildHudElementHUDElement instance which is removed as a child.

setPosition

Description
Set a HUD element's absolute screen space position.
If the element has any children, they will be moved with this element.
Definition
setPosition()

setRotation

Description
Set this HUD element's rotation.
Does not affect children. If no center position is given, the element's pivot values are used (default to 0)
Definition
setRotation(float rotation, float centerX, float centerY)
Arguments
floatrotationRotation in radians
floatcenterX[optional] Rotation pivot X position offset from overlay position in screen space
floatcenterY[optional] Rotation pivot Y position offset from overlay position in screen space

setRotationPivot

Description
Set this HUD element's rotation pivot point.
Definition
setRotationPivot(float pivotX, float pivotY)
Arguments
floatpivotXPivot x position offset from element position in screen space
floatpivotYPivot y position offset from element position in screen space

getRotationPivot

Description
Get this HUD element's rotation pivot point.
Definition
getRotationPivot()
Return Values
floatPivotx position offset from element position in screen space
floatPivoty position offset from element position in screen space

getPosition

Description
Get this HUD element's position.
Definition
getPosition()
Return Values
floatXposition in screen space
floatYposition in screen space

setScale

Description
Set this HUD element's scale.
This will move and scale children proportionally.
Definition
setScale(float scaleWidth, float scaleHeight)
Arguments
floatscaleWidthWidth scale factor
floatscaleHeightHeight scale factor

getScale

Description
Get this HUD element's scale.
Definition
getScale()
Return Values
widthscalefactor
heightscalefactor

setAlignment

Description
Set this HUD element's positional alignment.
See Overlay:setAlignment for positioning logic.
Definition
setAlignment(int vertical, int horizontal)
Arguments
intverticalVertical alignment value [Overlay.ALIGN_VERTICAL_BOTTOM | Overlay.ALIGN_VERTICAL_MIDDLE | Overlay.ALIGN_VERTICAL_TOP]
inthorizontalHorizontal alignment value [Overlay.ALIGN_HORIZONTAL_LEFT | Overlay.ALIGN_HORIZONTAL_CENTER | Overlay.ALIGN_HORIZONTAL_RIGHT]

setVisible

Description
Set this HUD element's visibility.
Definition
setVisible()

getVisible

Description
Get this HUD element's visibility.
Definition
getVisible()

getColor

Description
Get this HUD element's color.
Definition
getColor()
Return Values
floatRedvalue
floatGreenvalue
floatBluevalue
floatAlphavalue

getAlpha

Description
Get this HUD element's color alpha value.
Definition
getAlpha()
Return Values
floatAlphavalue

getWidth

Description
Get this HUD element's width in screen space.
Definition
getWidth()

getHeight

Description
Get this HUD element's height in screen space.
Definition
getHeight()

setDimension

Description
Set this HUD element's width and height.
Either value can be omitted (== nil) for no change.
Definition
setDimension()

resetDimensions

Description
Reset this HUD element's dimensions to their default values.
Resets width, height, scale and pivot.
Definition
resetDimensions()

setColor

Description
Set this HUD element overlay's color.
Children are unaffected.
Definition
setColor()

setAlpha

Description
Set this HUD element overlay's color alpha value only.
Definition
setAlpha()

setImage

Description
Set this HUD element overlay's image file.
Definition
setImage()

setUVs

Description
Set this HUD element overlay's UV coordinates.
Definition
setUVs()

update

Description
Update this HUD element's state.
Definition
update()

draw

Description
Draw this HUD element and all of its children in order of addition.
Definition
draw()

scalePixelToScreenVector

Description
Convert a vector from pixel values into scaled screen space values.
Definition
scalePixelToScreenVector(table vector2D)
Arguments
tablevector2DArray of two pixel values

scalePixelToScreenHeight

Description
Convert a vertical pixel value into scaled screen space value.
Definition
scalePixelToScreenHeight(float height)
Arguments
floatheightVertical pixel value

scalePixelToScreenWidth

Description
Convert a horizontal pixel value into scaled screen space value.
Definition
scalePixelToScreenWidth(float width)
Arguments
floatwidthHorizontal pixel value

normalizeUVPivot

Description
Convert a texture space pivot to an element-local pivot.
Definition
normalizeUVPivot(table uvPivot, table uvs)
Arguments
tableuvPivotArray of two pixel pivot coordinates in texture space
tableuvsArray of UV coordinates as {x, y, width, height}

HUDFrameElement

Description
HUD background frame element.
-- Displays a transparent frame with a thick bottom bar for use as a background in HUD elements.
--@category GUI

new

Description
Create a new instance of FrameElement.
Definition
new(string hudAtlasPath, float posX, float posY, float width, float height, table parent)
Arguments
stringhudAtlasPathPath to the HUD atlas texture
floatposXInitial X position in screen space
floatposYInitial Y position in screen space
floatwidthFrame width in screen space
floatheightFrame height in screen space
tableparent[optional] Parent HUDElement which will receive this frame as its child element

createComponents

Description
Create display components.
Definition
createComponents()

setDimension

Description
Set frame element dimensions.
Override from HUDElement to preserve border positioning and sizes.
Definition
setDimension()

HUDPopupMessage

Description
HUD popup message.
-- Displays a modal popup message which requires a player input to be accepted / dismissed or expires after a given
time.
--@category GUI

new

Description
Create a new instance of HUDPopupMessage.
Definition
new(string hudAtlasPath, l10n I18N, inputManager InputBinding, InputDisplayManager InputDisplayManager, IngameMap IngameMap)
Arguments
stringhudAtlasPathPath to the HUD texture atlas
l10nI18Nreference for text localization
inputManagerInputBindingreference for custom input context handling
InputDisplayManagerInputDisplayManagerfor input glyph display
IngameMapIngameMapreference used to notify the map when a message is shown
Return Values
tableHUDPopupMessageinstance

showMessage

Description
Show a new message.
Definition
showMessage(string title, string message, int duration, table controls, function callback, table target)
Arguments
stringtitleTitle text
stringmessageMain message text
intdurationMessage display duration in milliseconds. If set to 0, will cause the message to be
displayed for a duration derived from the message length. If set to <0, will cause the message to be displayed
for a very long time.
tablecontrols[optional] Array of InputHelpElement instance for input hint row display
functioncallback[optional] Function to be called when the message is acknowledged or expires
tabletarget[optional] Callback target which is passed as the first argument to the given callback function

setPaused

Description
Set the game's paused state on this element.
If the game is paused, the message timer is stopped and no new messages are displayed.
Definition
setPaused()

getVisible

Description
Get this HUD element's visibility.
Definition
getVisible()

DisplayElement:getHidingTranslation

Description
Get the screen space translation for hiding.
Override in sub-classes if a different translation is required.
Definition
DisplayElement:getHidingTranslation()
Return Values
floatScreenspace X translation
floatScreenspace Y translation

onMenuVisibilityChange

Description
Handle menu visibility changes.
Definition
onMenuVisibilityChange()

assignCurrentMessage

Description
Assign a new current message and adjust display state accordingly.
This also resizes the message box according to the required space.
Definition
assignCurrentMessage()

getTitleHeight

Description
Get the display height of the current message's title.
Definition
getTitleHeight()

getTextHeight

Description
Get the display height of the current message's text.
Definition
getTextHeight()

getInputRowsHeight

Description
Get the display height of the current message's input rows.
Definition
getInputRowsHeight()

animateHide

Description
Animate this element on showing.
Definition
animateHide()

startMessage

Description
Start displaying a message dequeued from the currently pending messages.
Sets all required display and input state.
Definition
startMessage()

finishMessage

Description
Finish displaying a message after it has either elapsed or been acknowledged by the player.
Resets display and input state and triggers any provided message callback.
Definition
finishMessage()

update

Description
Update this element's state.
Definition
update()

updateCurrentMessage

Description
Update the current message.
Disables this popup when time runs out and dequeues a pending messages for displaying.
Definition
updateCurrentMessage()

updateButtonGlyphs

Description
Update button glyphs when the player input mode has changed.
Definition
updateButtonGlyphs()

setInputActive

Description
Enable / disable input events for message confirmation / skipping.
Definition
setInputActive()

onConfirmMessage

Description
Event function for either InputAction.SKIP_MESSAGE_BOX or InputAction.MENU_ACCEPT.
Definition
onConfirmMessage()

draw

Description
Draw the message.
Definition
draw()

getBackgroundPosition

Description
Get this element's base background position.
Definition
getBackgroundPosition(float uiScale)
Arguments
floatuiScaleCurrent UI scale factor

setScale

Description
Set uniform UI scale.
Definition
setScale()

setDimension

Description
Set this HUD element's width and height.
Definition
setDimension()

storeScaledValues

Description
Store scaled positioning, size and offset values.
Definition
storeScaledValues()

createBackground

Description
Create the background overlay.
Definition
createBackground()

createComponents

Description
Create required display components.
Definition
createComponents()

createInputRow

Description
Create components for an input button row.
Definition
createInputRow()

HUDTextDisplay

Description
HUD text display.
-- Displays a formatted single-line text with optional animations.
--@category GUI

new

Description
Create a new HUDTextDisplay.
Definition
new(float posX, float posY, float textSize, int textAlignment, table textColor, bool textBool)
Arguments
floatposXScreen space X position of the text display
floatposYScreen space Y position of the text display
floattextSizeText size in reference resolution pixels
inttextAlignmentText alignment as one of RenderText.[ALIGN_LEFT | ALIGN_CENTER | ALIGN_RIGHT]
tabletextColorText display color as an array {r, g, b, a}
booltextBoolIf true, will render the text in bold
Return Values
tableHUDTextDisplayinstance

setText

Description
Set the text to display.
Definition
setText(string text, float textSize, int textAlignment, table textColor, bool textBool)
Arguments
stringtextDisplay text
floattextSizeText size in reference resolution pixels
inttextAlignmentText alignment as one of RenderText.[ALIGN_LEFT | ALIGN_CENTER | ALIGN_RIGHT]
tabletextColorText display color as an array {r, g, b, a}
booltextBoolIf true, will render the text in bold

setScale

Description
Set the text display UI scale.
Definition
setScale()

setVisible

Description
Set this element's visibility.
Definition
setVisible(bool isVisible, bool animate)
Arguments
boolisVisibleVisibility state
boolanimateIf true, will play the currently set animation on becoming visible or and reset it when necessary.

setAlpha

Description
Set the global alpha value for this text display.
The alpha value will be multiplied with any text color alpha channel value.
Definition
setAlpha()

setTextColorChannels

Description
Set the text color by channels.
Use for dynamic changes and animation.
Definition
setTextColorChannels()

setTextShadow

Description
Set the text shadow state.
Definition
setTextShadow(bool isShadowEnabled, table shadowColor)
Arguments
boolisShadowEnabledIf true, will cause a shadow to be rendered under the text
tableshadowColorShadow text color as an array {r, g, b, a}

setAnimation

Description
Set an animation tween (sequence) for this text display.
The animation can be played when calling HUDTextDisplay:setVisible() with the "animate" paramter set to true.
Definition
setAnimation()

update

Description
Update this element's state.
Definition
update()

draw

Description
Draw the text.
Definition
draw()

HusbandryModuleFoodSpillage

Description
Creating manager

delete

Description
Deletes instance
Definition
delete()
Code
29function HusbandryModuleFoodSpillage:delete()
30end

initDataStructures

Description
Initialize data structures
Definition
initDataStructures()
Code
34function HusbandryModuleFoodSpillage:initDataStructures()
35 HusbandryModuleFoodSpillage:superClass().initDataStructures(self)
36
37 self.spillageAreas = {}
38 self.foodToDrop = 0
39 self.spillageFillType = FillType.UNKNOWN
40 self.lineOffset = 0
41 self.cleanlinessFactor = 0.0
42 self.hasCleanliness = false
43end

load

Description
Loads data from xml
Definition
load(table xmlFile, string xmlKey, table rootNode)
Arguments
tablexmlFilehandle
stringxmlKeyfrom which to read the configuration
tablerootNodeof the husbandry
Return Values
booleantrueif loading was successful else false
Code
51function HusbandryModuleFoodSpillage:load(xmlFile, configKey, rootNode, owner)
52 if not HusbandryModuleFoodSpillage:superClass().load(self, xmlFile, configKey, rootNode, owner) then
53 return false
54 end
55
56 if not hasXMLProperty(xmlFile, configKey) then
57 return false
58 end
59
60 local i = 0
61 while true do
62 local areaKey = string.format("%s.area(%d)", configKey, i)
63 if not hasXMLProperty(xmlFile, areaKey) then
64 break
65 end
66 local start = I3DUtil.indexToObject(rootNode, getXMLString(xmlFile, areaKey .. "#startNode"))
67 local width = I3DUtil.indexToObject(rootNode, getXMLString(xmlFile, areaKey .. "#widthNode"))
68 local height = I3DUtil.indexToObject(rootNode, getXMLString(xmlFile, areaKey .. "#heightNode"))
69
70 if start ~= nil and width ~= nil and height ~= nil then
71 table.insert(self.spillageAreas, {start = start, width = width, height = height})
72 end
73 i = i + 1
74 end
75
76 local spillageFillType = getXMLString(xmlFile, configKey .. "#fillType")
77 if spillageFillType ~= nil then
78 local fillTypeIndex = g_fillTypeManager:getFillTypeIndexByName(spillageFillType)
79 if fillTypeIndex ~= nil then
80 self.spillageFillType = fillTypeIndex
81 end
82 end
83
84 self.hasCleanliness = true
85
86 return self.spillageFillType ~= nil and #self.spillageAreas > 0
87end

readStream

Description
Reads network stream
Definition
readStream(integer streamId, table connection)
Arguments
integerstreamIdnetwork stream identification
tableconnectionconnection information
Code
94function HusbandryModuleFoodSpillage:readStream(streamId, connection)
95 HusbandryModuleFoodSpillage:superClass().readStream(self, streamId, connection)
96
97 if self.hasCleanliness then
98 self.cleanlinessFactor = streamReadUInt8(streamId) / 255
99 end
100end

writeStream

Description
Writes network stream
Definition
writeStream(integer streamId, table connection)
Arguments
integerstreamIdnetwork stream identification
tableconnectionconnection information
Code
106function HusbandryModuleFoodSpillage:writeStream(streamId, connection)
107 HusbandryModuleFoodSpillage:superClass().writeStream(self, streamId, connection)
108
109 if self.hasCleanliness then
110 local cleanliness = math.floor(self.cleanlinessFactor * 255 + 0.5)
111 streamWriteUInt8(streamId, cleanliness)
112 end
113end

readUpdateStream

Description
Read updates from network stream
Definition
readUpdateStream(integer streamId, integer timestamp, table connection)
Arguments
integerstreamIdnetwork stream identification
integertimestamp
tableconnectionconnection information
Code
120function HusbandryModuleFoodSpillage:readUpdateStream(streamId, timestamp, connection)
121 HusbandryModuleFoodSpillage:superClass().readUpdateStream(self, streamId, timestamp, connection)
122
123 if self.hasCleanliness then
124 self.cleanlinessFactor = streamReadUInt8(streamId) / 255
125 end
126end

writeUpdateStream

Description
Write updates from network stream
Definition
writeUpdateStream(integer streamId, table connection, integer dirtyMask)
Arguments
integerstreamIdnetwork stream identification
tableconnectionconnection information
integerdirtyMaskis used to check if we need to update
Code
133function HusbandryModuleFoodSpillage:writeUpdateStream(streamId, connection, dirtyMask)
134 HusbandryModuleFoodSpillage:superClass().writeUpdateStream(self, streamId, connection, dirtyMask)
135
136 if self.hasCleanliness then
137 local cleanliness = math.floor(self.cleanlinessFactor * 255 + 0.5)
138 streamWriteUInt8(streamId, cleanliness)
139 end
140end

onIntervalUpdate

Description
Update water usage
Definition
onIntervalUpdate(float dayToInterval)
Arguments
floatdayToInterval
Code
145function HusbandryModuleFoodSpillage:onIntervalUpdate(dayToInterval)
146 HusbandryModuleFoodSpillage:superClass().onIntervalUpdate(self, dayToInterval)
147 self:updateCleanlinessFactor(dayToInterval)
148end

loadFromXMLFile

Description
Loads information from attributes and node. Retrives from xml file information.
Definition
loadFromXMLFile(table xmlFile, string key)
Arguments
tablexmlFileXML file handler
stringkeyXML base key
Code
183function HusbandryModuleFoodSpillage:loadFromXMLFile(xmlFile, key)
184 HusbandryModuleFoodSpillage:superClass().loadFromXMLFile(self, xmlFile, key)
185
186 if self.hasCleanliness then
187 self.cleanlinessFactor = Utils.getNoNil(getXMLFloat(xmlFile, key.."#cleanlinessFactor"), self.cleanlinessFactor)
188 self.foodToDrop = Utils.getNoNil(getXMLFloat(xmlFile, key.."#foodToDrop"), self.foodToDrop)
189 end
190end

updateFoodSpillage

Description
Update spillage mechanics.
Definition
updateFoodSpillage(float spillageDelta)
Arguments
floatspillageDeltaamount of food to increase
Return Values
floatfooddropped
Code
205function HusbandryModuleFoodSpillage:updateFoodSpillage(spillageDelta)
206 local foodDropped = 0
207
208 if self.hasCleanliness and self.cleanlinessFactor > 0 and spillageDelta > g_densityMapHeightManager:getMinValidLiterValue(self.spillageFillType) then
209 local i = math.random(1, #self.spillageAreas)
210 local spillageArea = self.spillageAreas[i]
211 local xs,_,zs = getWorldTranslation(spillageArea.start)
212 local xw,_,zw = getWorldTranslation(spillageArea.width)
213 local xh,_,zh = getWorldTranslation(spillageArea.height)
214 local ux, uz = xw - xs, zw - zs
215 local vx, vz = xh - xs, zh - zs
216 local vLength = MathUtil.vector2Length(vx,vz)
217 local sx = xs + (math.random() * ux) + (math.random() * vx)
218 local sz = zs + (math.random() * uz) + (math.random() * vz)
219 local ex = xs + (math.random() * ux) + (math.random() * vx)
220 local ez = zs + (math.random() * uz) + (math.random() * vz)
221 local sy = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, sx, 0.0, sz)
222 local ey = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, ex, 0.0, ez)
223 local dropped, lineOffset = DensityMapHeightUtil.tipToGroundAroundLine(nil, spillageDelta, self.spillageFillType, sx,sy,sz, ex,ey,ez, 0, vLength, self.lineOffset, false, nil)
224
225 foodDropped = dropped
226 self.lineOffset = lineOffset
227 end
228
229 return foodDropped
230end

getFoodSpillageLevel

Description
Get spillage level
Definition
getFoodSpillageLevel()
Return Values
floatspillagetotal
Code
235function HusbandryModuleFoodSpillage:getFoodSpillageLevel()
236 local totalLevel = 0
237 for _, spillageArea in ipairs(self.spillageAreas) do
238 local xs,_,zs = getWorldTranslation(spillageArea.start)
239 local xw,_,zw = getWorldTranslation(spillageArea.width)
240 local xh,_,zh = getWorldTranslation(spillageArea.height)
241 local fillLevel = DensityMapHeightUtil.getFillLevelAtArea(self.spillageFillType, xs, zs, xw, zw, xh, zh)
242 totalLevel = totalLevel + fillLevel
243 end
244 return totalLevel
245end

getSpillageFactor

Description
Definition
getSpillageFactor()
Code
249function HusbandryModuleFoodSpillage:getSpillageFactor()
250 if self.hasCleanliness then
251 return self.cleanlinessFactor
252 end
253
254 return nil
255end

I3DUtil

Description
Sets the world direction for a given object

checkChildIndex

Description
Checks if given index is valid
Definition
checkChildIndex(integer node, string index)
Arguments
integernodeid of an object
stringindexindex
Return Values
booleanisActivateableis activateable
booleanisValidtrue if index is valid else false

indexToObject

Description
Returns index of object
Definition
indexToObject(table components, string index, table mappings)
Arguments
tablecomponentscomponents (also (integer) id of root node possible)
stringindexindex
tablemappingsid to index mapping table
Return Values
tableinstanceinstance of object
integeridid of object
integeridid of used root node

setNumberShaderByValue

Description
Sets the number shader attributes
Definition
setNumberShaderByValue(integer numbers, float value, integer precision, boolean showZero)
Arguments
integernumbersid of the node containing the number shapes
floatvaluevalue
integerprecisionprecision
booleanshowZerotrue if zero should be shown
Return Values
tableselfreturns the instance

wakeUpObject

Description
Wake up a collision object
Definition
wakeUpObject(integer node)
Arguments
integernodeid of a collision object
Return Values
boolreturntrue if successful

setWorldDirection

Description
limitedAxis 3: 0 degree = x axis, 90 degree = y axis
Definition
setWorldDirection(integer node, float dirX, float dirY, float dirZ, float upX, float upY, float upZ, integer limitedAxis, float minRot, float maxRot)
Arguments
integernodeid of object
floatdirXdirX
floatdirYdirY
floatdirZdirZ
floatupXupX
floatupYupY
floatupZupZ
integerlimitedAxisindex of limited axis
floatminRotminRot
floatmaxRotmaxRot
Return Values
floatreturnsthe change delta

setDirection

Description
Sets direction for a given object (only if the direction is valid)
Definition
setDirection(integer node, float dirX, float dirY, float dirZ, float upX, float upY, float upZ)
Arguments
integernodeid of object
floatdirXdirX
floatdirYdirY
floatdirZdirZ
floatupXupX
floatupYupY
floatupZupZ
Return Values
tableselfreturns the instance

setShaderParameterRec

Description
Sets a shader parameter recursivly
Definition
setShaderParameterRec(integer node, string shaderParam, float x, float y, float z, float w)
Arguments
integernodeid of the top node
stringshaderParamthe name of the shader param
floatxx
floatyy
floatzz
floatww
Return Values
boolreturntrue if successful

getNodesByShaderParam

Description
Gets a list of nodes with shaderParam assigned to it
Definition
getNodesByShaderParam(integer node, string shaderParam, table nodes)
Arguments
integernodeid of the top node
stringshaderParamthe name of the shader param
tablenodesa list of nodes
Return Values

IndexChangeSubjectMixin

Description
Index change subject mixin.
-- Add this mixin to a GuiElement to implement an observer pattern for index changes (e.g. paging, options, lists).
-- Added methods:
GuiElement:addIndexChangeObserver(observer, indexChangeCallback): Register an observer to be notified on index changes
observer is passed to the index change callback as the first argument, typically you would use "self"
indexChangeCallback must be a function with the signature function(observer, index, count)
GuiElement:notifyIndexChange(index, count): Called by the decorated GuiElement when the index or number of indexed items changes, triggers callbacks
index is the new index after the current change
count is the number of indexed items which may or may not have changed
--@category GUI

addTo

Description
See GuiMixin:addTo().
Definition
addTo()

addIndexChangeObserver

Description
Add an index change observer with a callback.
Definition
addIndexChangeObserver(GuiElement Decorated, observer Observer, indexChangeCallback Function(observer,)
Arguments
GuiElementDecoratedGuiElement instance which has received this method
observerObserverobject instance
indexChangeCallbackFunction(observer,index, count), where index is the new index and count the current number of indexable items

notifyIndexChange

Description
Notify observers of an index change.
Definition
notifyIndexChange(GuiElement Decorated, index New, count Indexable)
Arguments
GuiElementDecoratedGuiElement instance which has received this method
indexNewindex
countIndexableitem count

clone

Description
Clone this mixin's state from a source to a destination GuiElement instance.
Definition
clone()

IndexStateElement

Description
Index state display element.
-- Displays a visual element per screen page to let the player see an indication of their current list, page or multi-
option selection index. The element points at a UI element which supports indexed access, such as ListElement,
PageElement or MultiTextOption. For other cases, UI views directly manipulate the states (e.g. cycling hints in the
loading screen).
--@category GUI
--@xmlConfig GuiElement#stateElementTemplateId string ID of a descendant, sibling or sibling's descendant GUI element which is duplicated per page. The element should be configured to have different visuals for normal and selected GuiOverlay states (layers).

locateStateElementTemplate

Description
Find and store the state element template which is configured in #stateElementTemplateId.
The function searches from this elements parent downwards, so any descendant of this element or its siblings may
contain the state element template.
Definition
locateStateElementTemplate()

locateIndexableElement

Description
Find and store the indexable element which is configured in #indexableElementId.
The function first locates the current view root (if possible) and then searches downwards. The search is broader
than locateStateElementTemplate() to allow more flexibility in UI design and configuration.
Definition
locateIndexableElement()

onIndexChange

Description
Event handler for index changes.
Definition
onIndexChange(index New, count (New))
Arguments
indexNewindex
count(New)item count

setPageCount

Description
Set the page count.
Clears current page elements and rebuilds as many as needed from the configured template.
Definition
setPageCount(count Number, initialIndex [optional])
Arguments
countNumberof page indicators to display
initialIndex[optional]Page index to set after rebuilding

setPageIndex

Description
Set the current page index and update display states.
Definition
setPageIndex(index New)
Arguments
indexNewpage index

IngameMap

Description
In-game map display element.
-- This class is used to display the game map both in the HUD as well as in the in-game menu.
--@category GUI

new

Description
Create a new instance of IngameMap.
Definition
new(string hudAtlasPath, table inputDisplayManager)
Arguments
stringhudAtlasPathPath to the HUD atlas texture
tableinputDisplayManagerInputDisplayManager reference

delete

Description
Delete this element and all of its components.
Definition
delete()

setFullscreen

Description
Set full-screen mode (for map overview) without affecting the mini-map state.
Definition
setFullscreen()

getHotspotIndex

Description
Get the index of a hotspot in the hotspots list.
Definition
getHotspotIndex()

cycleVisibleHotspot

Description
Get the next or previous visible hotspot in order from a current hotspot.
Definition
cycleVisibleHotspot(table currentHotspot, table categoriesHash, int direction)
Arguments
tablecurrentHotspotCurrently selected hotspot
tablecategoriesHashTable of valid hotspot categories to cycle, keys are categories
intdirection1 for next, -1 for previous

getHeight

Description
Override from HUDElement.
Return zero height when turned off, because the map is only invisible.
Definition
getHeight()

getRequiredHeight

Description
Get required display height on screen including all auxiliary elements and texts.
Definition
getRequiredHeight()

setSize

Description
Set the map size.
Definition
setSize(float width, float height)
Arguments
floatwidthWidth of the map in screen space
floatheightHeight of the map in screen space

setPosition

Description
Set the map's position.
This sets the actual map display's position to the given values. This elements background is offset accordingly.
Definition
setPosition(float posX, float posY)
Arguments
floatposXNew map X position in screen space
floatposYNew map Y position in screen space

setIsVisible

Description
Set the map's visibility (= active state).
Definition
setIsVisible()

onToggleMapSize

Description
Called when the input for map size toggle is pressed and then released.
Definition
onToggleMapSize()

registerInput

Description
Register map size toggle input event.
Definition
registerInput()

update

Description
Update the map's state.
Definition
update()

updatePlayerPosition

Description
Update the data about the player's current position.
Definition
updatePlayerPosition()

updatePlayerArrow

Description
Update the arrow indicating the player's current position.
Definition
updatePlayerArrow()

updateMapHeightZoomFactor

Description
Update map zoom and visibility state.
Definition
updateMapHeightZoomFactor()
Return Values
boolTrueif the left border of the map has been reached
boolTrueif the right border of the map has been reached
boolTrueif the top border of the map has been reached
boolTrueif the bottom border of the map has been reached

updateInputGlyphs

Description
Update input display glyphs with the current input context.
Definition
updateInputGlyphs()

updateMapUVs

Description
Update map overlay UVs based on the currently focused position, e.g. a player or hotspot.
Definition
updateMapUVs()
Return Values
booleantrueif loading was successful else false
boolTrueif the left border of the map has been reached
boolTrueif the right border of the map has been reached
boolTrueif the top border of the map has been reached
boolTrueif the bottom border of the map has been reached

draw

Description
Draw the map as hud element
Definition
draw()
Return Values
booleantrueif loading was successful else false

drawPlayerArrow

Description
Draw the current player's arrow.
Definition
drawPlayerArrow()
Return Values
tableachievementachievement object

drawMapLabel

Description
Draw the map label on top of the map display.
Definition
drawMapLabel()
Return Values
tableinstanceinstance of object

drawMap

Description
Draw the map.
Definition
drawMap(float alpha, bool isStandalone)
Arguments
floatalpha[optional] Map opacity value
boolisStandalone[optional] If true, will draw the map border and other elements.
Return Values
booleantrueif loading was successful else false

drawPointsOfInterest

Description
Draw map hotspot and arrow elements.
Definition
drawPointsOfInterest()
Return Values
booleantrueif loading was successful else false

drawOtherPlayerArrows

Description
Draw arrows for other players' positions.
Definition
drawOtherPlayerArrows()
Return Values
booleantrueif added successful else false

drawEnterableArrows

Description
Draw arrows for enterable vehicles controlled by players.
Definition
drawEnterableArrows()
Return Values
tablehelpera random helper object

renderHotspots

Description
Draw all known hotspots on the map.
Definition
renderHotspots()
Return Values
integerhelperIndexa random helper index

drawHotspot

Description
Draw a single hotspot on the map.
Definition
drawHotspot()
Return Values
tablehelperthe helper object

drawPlayersCoordinates

Description
Draw the player's current coordinates as text.
Definition
drawPlayersCoordinates()
Return Values
tablehelperthe helper object

drawLatencyToServer

Description
Draw current latency to server as text.
Definition
drawLatencyToServer()
Return Values
booleansuccesstrue if helper is marked else false

setScale

Description
Set this element's scale.
Definition
setScale(float uiScale)
Arguments
floatuiScaleCurrent UI scale applied to both width and height of elements
Return Values
integernumOfHelperstotal number of helpers

storeScaledValues

Description
Store scaled positioning, size and offset values.
Definition
storeScaledValues()
Return Values
tableinstanceinstance of object

getBackgroundPosition

Description
Get the base position of the entire element.
Definition
getBackgroundPosition()
Return Values
booleantrueif loading was successful else false

createBackground

Description
Create the empty background overlay.
Definition
createBackground()
Return Values
booleantrueif loading was successful else false

createComponents

Description
Create required display components.
Definition
createComponents(string hudAtlasPath)
Arguments
stringhudAtlasPathPath to the HUD texture atlas
Return Values
booleantrueif loading was successful else false

createFrame

Description
Create the map frame.
Definition
createFrame()
Return Values
booleantrueif added successful else false

createToggleMapSizeGlyph

Description
Create the input glyph for map size toggling.
Definition
createToggleMapSizeGlyph()
Return Values
tablenpca random npc object

createPlayerMapArrow

Description
Create the map arrow for the player's position.
Definition
createPlayerMapArrow()
Return Values
integernpcIndexa random npc index

createOtherMapArrowOverlay

Description
Create an arrow overlay used for other player's and their vehicles in multiplayer.
Definition
createOtherMapArrowOverlay()
Return Values
tablenpcthe npc object

IngameMapElement

Description
In-game map element.
-- Controls input on the map in the in-game menu with objectives, vehicles, etc. The actual map rendering is deferred to
the map component of the current mission. The map reference and terrain size must be set during mission
initialization via the setIngameMap() and setTerrainSize() methods.
--@category GUI
--@xmlConfig GuiElement#cursorId string ID of element to use as a cursor on the map.

addCursorDeadzone

Description
Add a dead zone wherein the map will not react to cursor inputs.
Used this to designate areas where other controls should receive cursor input which would otherwise be used up by
the map (e.g. in full-screen mode in the map overview screen in-game). The deadzones will also restrict cursor
movement.
Definition
addCursorDeadzone()

clearCursorDeadzones

Description
Clear cursor dead zones.
Definition
clearCursorDeadzones()

isCursorInDeadzones

Description
Check if a cursor position is within one of the stored deadzones.
Definition
isCursorInDeadzones()

mouseEvent

Description
Custom mouse event handling for the in-game map.
Directly handles zoom, click and drag events on the map. See input events and IngameMapElement:checkAndResetMouse()
for the state checking code required to bypass player mouse input bindings.
Definition
mouseEvent()

updateBaseMapValues

Description
Update base map element values for displaying as an embedded UI element.
Definition
updateBaseMapValues()

setIngameMap

Description
Set the IngameMap reference to use for display.
Definition
setIngameMap()

setTerrainSize

Description
Set the current map's terrain size for map display.
Definition
setTerrainSize()

registerActionEvents

Description
Register non-GUI input action events.
Definition
registerActionEvents()

removeActionEvents

Description
Remove non-GUI input action events.
Definition
removeActionEvents()

onHorizontalCursorInput

Description
Event function for horizontal cursor input bound to InputAction.AXIS_LOOK_LEFTRIGHT_VEHICLE.
Definition
onHorizontalCursorInput()

onVerticalCursorInput

Description
Event function for vertical cursor input bound to InputAction.AXIS_LOOK_UPDOWN_VEHICLE.
Definition
onVerticalCursorInput()

onAccept

Description
Event function for gamepad cursor accept input bound to InputAction.INGAMEMAP_ACCEPT.
Definition
onAccept()

onZoomInput

Description
Event function for map zoom input bound to InputAction.AXIS_ACCELERATE_VEHICLE and InputAction.AXIS_BRAKE_VEHICLE.
Definition
onZoomInput(inputValue Zoom, direction Zoom)
Arguments
inputValueZoominput value
directionZoominput sign value, 1 for zoom in, -1 for zoom out

checkAndResetMouse

Description
Check if mouse input was active before a bound input was triggered and queue a reset of the mouse state for the next
frame.
Mouse input continuously sets the mouse input flag (self.useMouse) but does not receive any events when the mouse
is inert. Therefore we need to set and reset the state each frame to make sure we can seamlessly switch between mouse
and gamepad input on the map element while at the same time preventing any player bindings from interfering with the
custom mouse input logic of this class.
Definition
checkAndResetMouse()

InGameMenu

Description
In-Game Menu.
-- Displays the main in-game menu with several pages, depending on the game state and mode (e.g. tutorial or
multiplayer). This menu can be extended and modified by adding and removing pages. Default pages for the base game
are always loaded but can also be removed (effectively just disabled). Custom pages can be entirely new or modified
sub-classes of the default pages. See methods InGameMenu:addPage() and InGameMenu:removePage() for details.
--@category GUI
-- @field header Header panel

new

Description
Create a new instance of InGameMenu.
Definition
new(table target, table custom_mt, table messageCenter, table l10n, table savegameController, table inputManager, table fruitTypeManager, table fillTypeManager, table storeManager, table shopController, table shopConfigScreen, table placementScreen, bool isConsoleVersion)
Arguments
tabletargetCallback target
tablecustom_mtSub-class meta table
tablemessageCenterMessageCenter reference
tablel10nI18N reference for text localization
tablesavegameControllerSavegameController reference for savegame persistence
tableinputManagerInputBinding reference
tablefruitTypeManagerFruitTypeManager reference for fruit type information access
tablefillTypeManagerFillTypeManager reference for fill type information access
tablestoreManagerStoreManager reference
tableshopControllerShopController reference
tableshopConfigScreenShopConfigScreen reference
tableplacementScreenPlacementScreen reference
boolisConsoleVersionIf true, the game is running on a console
Return Values
tableinstanceinstance of object

setMode

Description
Set the menu mode.
Switches the menu between pause menu mode or shop mode.
Definition
setMode(int menuMode)
Arguments
intmenuModeOne of [InGameMenu.MODE_MENU | InGameMenu.MODE_SHOP]
Return Values
tableinstanceinstance of object

setInGameMap

Description
Set the in-game map component to use by pages.
Definition
setInGameMap()
Return Values
tablebrandColorbrandColor object

setTerrainSize

Description
Set the current terrain size to use by pages.
Definition
setTerrainSize()
Return Values
tablefarmhouseor nil

setMissionFruitTypes

Description
Set the known fruit types when loaded for the mission.
Definition
setMissionFruitTypes()
Return Values
integerspawnpointnode or the career spawnpoint node.

setSellingStations

Description
Set the current list of selling stations for displaying.
Definition
setSellingStations()
Return Values
integerCameraor 0 if no farmhouse.

setAccessibleVehicles

Description
Set the current list of accessible vehicles for displaying.
Definition
setAccessibleVehicles()
Return Values
boolTrueif the user is a manager of this farm, false otherwise

setBanStorage

Description
Set the reference to the ban storage.
Definition
setBanStorage()
Return Values
tablePermissionhash table {permission=<hasPermission>}

setConnectedUsers

Description
Set the current list of connected users for displaying.
Definition
setConnectedUsers()
Return Values
floatAccountbalance

setClient

Description
Set the network client reference.
Definition
setClient()
Return Values
float

setServer

Description
Set the network server reference.
Definition
setServer()
Return Values
tableinstanceinstance of object

updateHasMasterRights

Description
Update master rights status.
Definition
updateHasMasterRights()
Return Values
booleantrueif loading was successful else false

updateGarageItems

Description
Update garage items display data.
Definition
updateGarageItems()
Return Values
booleantrueif loading was successful else false

onLoadMapFinished

Description
Called when the mission is fully loaded.
Used for late initialization of UI components which rely on mission information.
Definition
onLoadMapFinished()
Return Values
tabledataData for the menu

initializePausePages

Description
Initialize pages for the pause mode.
Definition
initializePausePages()
Return Values
tableinstanceInstance of object

initializeShopPages

Description
Initialize pages for the shop mode.
Definition
initializeShopPages()
Return Values
booleantrueif loading was successful else false

setupMenuPages

Description
Set up displayed menu pages and their tabs.
Definition
setupMenuPages()
Return Values
tableinstanceinstance of object

setupMenuButtonInfo

Description
Define default properties and retrieval collections for menu buttons.
Definition
setupMenuButtonInfo()
Return Values
booleantrueif loading was successful else false

addPageTab

Description
Add a page tab in the menu header.
Call this synchronously with InGameMenu:registerPage() to ensure a correct order of pages and tabs.
Definition
addPageTab()
Return Values
fruittypeindex to be planted

setPageTabEnabled

Description
Set enabled state of a page tab in the header.
Definition
setPageTabEnabled()
Return Values
floatsprayFactorthe spray factor of the given field

rebuildTabList

Description
Rebuild page tab list in order.
Definition
rebuildTabList()
Return Values
floatplowFactorthe plow factor of the given field

setEnvironment

Description
Set environment reference on loading.
Definition
setEnvironment()
Return Values
floatplowFactorthe lime factor of the given field

setMissionInfo

Description
Set mission info data on loading.
Definition
setMissionInfo()
Return Values
floatplowFactorthe weed factor of the given field

setPlayerFarm

Description
Set the player's current farm reference.
Definition
setPlayerFarm()
Return Values
floatareaarea found
floattotalAreatotal area checked

setPlayer

Description
Set the reference to the current player.
Definition
setPlayer()

setCurrentUserId

Description
Set the current user ID.
Definition
setCurrentUserId()
Return Values
tableinstanceinstance of object

setManureTriggers

Description
Set manure triggers of the current map/mission.
Definition
setManureTriggers()
Return Values
booleantrueif loading was successful else false

setHusbandries

Description
Set the reference to the current husbandries collection.
Definition
setHusbandries()
Return Values
booleantrueif loading was successful else false

leaveCurrentGame

Description
Reset menu state and go back to the main menu.
Definition
leaveCurrentGame()
Return Values
Listofvehicles. Each element is a table with filanema and configuration properties.
Reward

exitMenu

Description
Exit the menu if allowed.
Definition
exitMenu()

exitMenuFromConfig

Description
Exit the menu from the shop configuration screen.
Definition
exitMenuFromConfig()

reset

Description
Reset menu state (and all pages).
Definition
reset()
Return Values
floatmultiplierharvest multiplier

onOpen

Description
Handle in-game menu opening event.
Definition
onOpen()
Return Values
tableinstanceof the doghouse

onClose

Description
Handle in-game menu closing event.
Definition
onClose()
Return Values
stringVehicledisplay name

onButtonSaveGame

Description
Button function for saving the game.
Definition
onButtonSaveGame()
Return Values
mixedvalueValue of the setting. The type depends on the setting

onButtonBack

Description
Button function for backing out of the menu.
Definition
onButtonBack()
Return Values
booleansuccessfulReturns true, if the setting was changed

onButtonQuit

Description
Button function for quitting the game to the main menu.
Definition
onButtonQuit()
Return Values
tableinstanceinstance of object

onButtonGarage

Description
Button function for switching to the garage view.
Definition
onButtonGarage()
Return Values
tableselfinstance

onButtonShop

Description
Button function for switching to the shop view from the garage.
Definition
onButtonShop()
Return Values
Trueifthe element and all of its children could be set up with the given values, false otherwise.

onButtonRepair

Description
Button function for repairing an owned vehicle in the garage.
Definition
onButtonRepair()
Return Values
Trueifthe input event has been consumed, false otherwise

onYesNoRepairDialog

Description
Handle confirmation of vehicle repairing.
Definition
onYesNoRepairDialog()
Return Values
Closestpointx, y

onVehicleRepairEvent

Description
Handle a local vehicle repaired event.
Updates the garage view buttons if currently viewing the repaired vehicle.
Definition
onVehicleRepairEvent()
Return Values
NextGUIelement in given direction which can be linked, actual scanning direction used (may change in wrap around scenarios)

onButtonAcceptItem

Description
Button function for explicit clicking of item details action buttons.
Definition
onButtonAcceptItem()
Return Values
Focus

onButtonSwitchOwnedLeased

Description
Button function for switching owned / leased items in the garage.
Definition
onButtonSwitchOwnedLeased()
Return Values
Trueiffocus has changed, false otherwise

startPlacementMode

Description
Enter placement mode.
Definition
startPlacementMode()
Return Values
Trueifnavigation in given direction is locked

startSavingGameDisplay

Description
Enter saving mode.
Definition
startSavingGameDisplay()
Return Values
RootGuiElementinstance of loaded view or nil if the definition XML file could not be loaded.

updatePages

Description
Update page enabled states.
Definition
updatePages()
Return Values
ClonedFrameElementinstance or frameRefElement if resolution failed.

updatePageTabDisplay

Description
Update page tabs display after any page changes.
Definition
updatePageTabDisplay()
Return Values
RootGuiElementof screen or nil if the name did not match any known screen.

clearMenuButtonActions

Description
Clear menu button actions, events and callbacks.
Definition
clearMenuButtonActions()
Return Values
RootGuiElementof dialog or nil if the name did not match any known dialog.

assignMenuButtonInfo

Description
Assign menu button information to the in-game menu buttons.
Definition
assignMenuButtonInfo()
Return Values
Trueifany control has consumed the action event

setPageSelectorTitles

Description
Get page titles from currently visible pages and apply to the selector element.
Definition
setPageSelectorTitles()
Return Values
tableScreenElementdescendant instance of the given class or nil if no such instance was registered

setShopDetailMode

Description
Switch to or from shop detail mode.
This can switch to a category's item list, the owned object or leased object overview by passing in the corresponding
detail page.
Definition
setShopDetailMode()
Return Values
tableRootGuiElement instance of target screen

update

Description
Update the menu state each frame.
This uses a state machine approach for the game saving process.
Definition
update()
Return Values
tableTheGuiElement instance given in the guiElement parameter

openFinancesScreen

Description
Directly switch to the finances screen.
Definition
openFinancesScreen()
Return Values
New

openFarmsScreen

Description
Directly switch to the farms screen.
Definition
openFarmsScreen()
Return Values
tablewith added image data

setMasterServerConnectionFailed

Description
Notify the menu that the master server could not be connected to.
Definition
setMasterServerConnectionFailed()
Return Values
Coloras{red, green, blue, alpha} with all values in the range of [0, 1]

setMasterUserLocal

Description
Set the menu state to master user.
Called by the mission if the current player is a master user.
Definition
setMasterUserLocal()
Return Values
UVcoordinatesas {u1, v1, u2, v2, u3, v3, u4x, v4} with all values in the range of [0, 1]

showConfigurationScreen

Description
Show the vehicle configuration screen for a given store item.
Definition
showConfigurationScreen()
Return Values
NewGuiProfileinstance

inputEvent

Description
Custom input handling to check shop toggle button when in shop mode.
Definition
inputEvent()
Return Values
Trueifprofile values could be loaded, false otherwise.

onMenuActionClick

Description
Handle a menu action click by calling one of the menu button callbacks.
Definition
onMenuActionClick()
Return Values
intCameranode ID (view point, child of camera base node)
intCamerabase node ID (view target, parent of camera node)
boolTrueif no callback was present and no action was taken, false otherwise

onClickOk

Description
Handle menu confirmation input event.
Definition
onClickOk()

onClickBack

Description
Handle menu back input event.
Definition
onClickBack()
Return Values
CameraXworld space position
CameraZworld space position
CameraYrotation in radians

onClickCancel

Description
Handle menu cancel input event.
Bound to quite the game to the main menu.
Definition
onClickCancel()

onClickActivate

Description
Handle menu active input event.
Bound to save the game.
Definition
onClickActivate()

onMoneyChanged

Description
Handle a balance change in game.
Definition
onMoneyChanged()

onSlotUsageChanged

Description
Handle a change of the current slot usage.
Definition
onSlotUsageChanged()
Return Values
xdirectionmovement [-1, 1]
Zdirectionmovement [-1, 1]

onSelectItemBuyDetail

Description
Handle selection of a detail item element when in buy mode.
Definition
onSelectItemBuyDetail()

onSelectItemSellDetail

Description
Handle selection of a detail item element in the garage.
Definition
onSelectItemSellDetail()
Return Values
arrayofnormalized values

onYesNoRestartTutorial

Description
Handle tutorial restart confirmation dialog response.
Definition
onYesNoRestartTutorial()
Return Values
arrayofthe 2 converted values as numbers: {value1, value2}

onYesNoEnd

Description
Server end game confirmation dialog response callback.
Definition
onYesNoEnd()
Return Values
arrayofthe 4 converted values as numbers: {value1, value2, value3, value4}

onClickPageSelection

Description
Handle activation of page selection.
Definition
onClickPageSelection()
Return Values
arrayofthe 4 converted values as numbers: {red, green, blue, alpha}

onPagePrevious

Description
Handle previous page event.
Definition
onPagePrevious()
Return Values
arrayofthe UV coordinates as {u1, v1, u2, v2, u3, v3, u4, v4}

onPageNext

Description
Handle next page event.
Definition
onPageNext()
Return Values
boolTrueif overlay generation has started, false if generation is already in progress or an invalid overlay
type has been provided

onPageChange

Description
Handle changing to another menu page.
Definition
onPageChange()
Return Values
boolTrueif overlay generation has started, false if generation is already in progress or an invalid overlay
type has been provided

updateButtonsPanel

Description
Update the buttons panel when a given page is visible.
Definition
updateButtonsPanel()
Return Values
boolTrueif overlay generation has started, false if generation is already in progress or an invalid overlay
type has been provided

getPageButtonInfo

Description
Get button actions and display information for a given menu page.
Definition
getPageButtonInfo()
Return Values
boolTrueif overlay generation has started, false if generation is already in progress or an invalid overlay
type has been provided

onPageUpdate

Description
Handle a page being disabled.
Definition
onPageUpdate()
Return Values
arrayofdisplay information, {i={colors={true=[{r,g,b,a} colorblind], false=[{r,g,b,a} default], iconFilename=path,
iconUVs={u1, v1, u2, v2, u3, v3, u4, v4}, description=text, fruitTypeIndex=index}}

onConnectionFailedDialogClick

Description
Handle saving game confirmation when losing master server connection.
Definition
onConnectionFailedDialogClick()
Return Values
arrayofdisplay information, {i={colors={true={i={r,g,b,a}}, false={i={r,g,b,a}}}, description=text}}

onVehiclesChanged

Description
Called from the mission controller when vehicles are modified.
Definition
onVehiclesChanged()
Return Values
arrayofdisplay information, {i={colors={true={i={r,g,b,a}}, false={i={r,g,b,a}}}, description=text}}

onClickBrand

Description
Handle clicking on a brand in shop mode.
Definition
onClickBrand()
Return Values
floatXposition in screen space
floatYposition in screen space

onClickItemCategory

Description
Handle clicking on an item category in shop mode.
Definition
onClickItemCategory()

notifyValidateSavegameList

Description
Notify the player when validating the savegame list.
Will prompt to select a storage device or inform that the chosen device has no more space available.
Definition
notifyValidateSavegameList()
Return Values
floatWidthscale factor
floatHeightscale factor

notifyStartSaving

Description
Notify the player that the game is saving, block input via dialog until the operation finishes.
Definition
notifyStartSaving()

notifySaveComplete

Description
Notify the menu when a save completes successfully so we can set the saving state flag.
Definition
notifySaveComplete()
Return Values
tableSettingsModelinstance

notifySavegameNotSaved

Description
Notify the player that the savegame could not be saved.
Definition
notifySavegameNotSaved()
Return Values
tableCurrentlyactive (changed) settings value

notifyOverwriteSavegame

Description
Prompt the player to confirm overwriting an existing savegame.
Definition
notifyOverwriteSavegame()
Return Values
boolTrueif any setting has been changed, false otherwise

notifySaveFailedNoSpace

Description
Notify the player that saving failed because the current device has no more space, ask to select another device.
Definition
notifySaveFailedNoSpace()
Return Values
boolTrueif any setting has been changed, false otherwise

registerPage

Description
Register a page frame element in the menu.
This does not add the page to the paging component of the menu.
Definition
registerPage(table pageFrameElement, int position, function enablingPredicateFunction)
Arguments
tablepageFrameElementPage FrameElement instance
intposition[optional] Page position index in menu
functionenablingPredicateFunction[optional] A function which returns the current enabling state of the page
at any time. If the function returns true, the page should be enabled. If no argument is given, the page is
always enabled.
Return Values
boolTrueif no callback was present and no action was taken, false otherwise

unregisterPage

Description
Unregister a page frame element identified by class from the menu.
This does not remove the page from the paging component of the menu or the corresponding page tab from the header.
Definition
unregisterPage(table pageFrameClass)
Arguments
tablepageFrameClassFrameElement descendant class of a page which was previously registered
Return Values
boolTrueif there was a page of the given class and it was unregistered
tableUnregisteredpage controller instance or nil
tableUnregisteredpage root GuiElement instance or nil
tableUnregisteredpage tab ListElement instance of nil
boolTrueif there was a page of the given class and it was unregistered
tableUnregisteredpage controller instance or nil
tableUnregisteredpage root GuiElement instance or nil
tableUnregisteredpage tab ListElement instance of nil

addPage

Description
Add a page frame to be displayed in the menu at runtime.
The page will be part of the in-game menu until restarting the game or removing the page again.
-- @usage
local frameController = CustomFrameElement:new(...) -- create controller instance
g_gui:loadGui("<frame layout XML path>", "<frame name>", frameController, true) -- load UI components, attach controller
local enablePage = function() -- define predicate function which returns true when the page should be enabled
return self.example.isSkyBlue
end
self:addPage(frameController, position, enablePage) -- add page to menu (self)
-- @param table pageFrameElement FrameElement instance which is used as a page.
Definition
addPage(int position, string tabIconFilename, table tabIconUVs, function enablingPredicateFunction)
Arguments
intpositionPosition index of added page, starting from left at 1 going to right.
stringtabIconFilenamePath to the texture file which contains the icon for the page tab in the header
tabletabIconUVsUV array for the tab icon. Format: {x, y, width, height} in pixels on the texture.
functionenablingPredicateFunction[optional] A function which returns the current enabling state of the page
at any time. If the function returns true, the page should be enabled. If no argument is given, the page is
always enabled.

removePage

Description
Remove a page from the menu at runtime by its class type.
The removed page is also deleted, including all of its children. Note that this method removes the page for an entire
game run, because the UI is loaded on game start. If you only need to disable a page, use InGameMenu:setPageEnabled()
instead.
-- The method will not remove game default pages, but only disable them.
-- @usage
self:removePage(CustomFrameElement) -- where CustomFrameElement is a sub-class of FrameElement
-- @param table pageFrameClass Class table of a FrameElement sub-class
Definition
removePage()

setPageEnabled

Description
Set the enabled state of a page identified by its controller class type.
This will also set the controller's state, so it can react to being enabled/disabled. The setting will persist
through calls to InGameMenu:reset() and must be reverted manually, if necessary.
Definition
setPageEnabled(table pageFrameClass, bool isEnabled)
Arguments
tablepageFrameClassClass table of a FrameElement sub-class
boolisEnabledTrue for enabled, false for disabled

updateGarageButtonInfo

Description
Update the button information for the garage.
Definition
updateGarageButtonInfo()
Return Values
{name="internalName",displayName="displayName",inputTexts={1=text1, 2=text2, ...}, inputBindings={1=binding1, 2=binding2, ...}, positiveInput=[true|false]}

makeSelfCallback

Description
Make a callback which encloses the self reference and handles arbitrary arguments afterwards.
Definition
makeSelfCallback()
Return Values
ListofDisplayActionBinding instances

InGameMenuAnimalsFrame

Description
In-game menu animals statistics frame.
-- Displays information for all owned animal pens and horses.
--@category GUI

new

Description
Create a new InGameMenuAnimalsFrame instance.
Definition
new(table subclass_mt, table messageCenter, table l10n, table animalManager, table animalFoodManager, table fillTypeManager)
Arguments
tablesubclass_mt[optional] Meta table of subclass
tablemessageCenterMessageCenter reference for local message subscriptions
tablel10nI18N reference for localization
tableanimalManagerAnimalManager reference for animal type and information resolution
tableanimalFoodManagerAnimalFoodManager reference for food mixture information
tablefillTypeManagerFillTypeManager reference for fill type resolution
Return Values
Display
tableInGameMenuAnimalsFrameinstance

initialize

Description
Late initialization.
Definition
initialize()
Return Values
Trueifthe controller starts listening for input, false otherwise (also if it is already listening!)

setHusbandries

Description
Set the reference to the husbandries collection.
The husbandries are defined as {<husbandry ID> = AnimalHusbandry}
Definition
setHusbandries()
Return Values
boolTrueif an actual binding was deleted, false otherwise

buildLivestockListItem

Description
Build a livestock list item for a husbandry.
Definition
buildLivestockListItem()
Return Values
Trueifa binding change was made, false otherwise

buildHorseListItems

Description
Build animal list items for all horses in a horse husbandry.
Definition
buildHorseListItems()
Return Values
Trueifa binding change was made, false otherwise

rebuildAnimalList

Description
Rebuild the animal list from husbandry data.
Definition
rebuildAnimalList()
Return Values
Trueifa binding change was made, false otherwise

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
Trueifbinding has been assigned; reference to first colliding binding or nil

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()
Return Values
tableDirectSellDialoginstance

setStatusBarValue

Description
Modify a status bar's value, applying the correct size and color as needed.
Definition
setStatusBarValue(table statusBarElement, float value, float startOffset, table profiles, float overrideStatusValue)
Arguments
tablestatusBarElementBitmapElement instance which receives a new size and profile depending on the value
floatvalueFractional value in the range of [0, 1]
floatstartOffsetStart offset value in the range of [0, 1], value will be displayed from there on until 1.
tableprofilesLarge or small status bar profile table, either InGameMenuAnimalsFrame.PROFILE.STATUS_BAR_LARGE or InGameMenuAnimalsFrame.PROFILE.STATUS_BAR_SMALL
floatoverrideStatusValue[optional] If provided, tests this value against the color thresholds instead of the given status bar value
Return Values
Flowsandcells as nested tables: [flowIndex][cell index] = cell data {element, flowSize, lateralSize}

displayRequirement

Description
Display a husbandry requirements row with the given data.
If no label text is specified, the row will be hidden.
Definition
displayRequirement()
Return Values
Listoflateral flow sizes, total lateral sizes (sum of lateral flow sizes), maximum flow size in direction of flow

displayCondition

Description
Display a husbandry conditions row with the given data.
If no label text is specified, the row will be hidden.
Definition
displayCondition()
Return Values
LayoutXstarting offset, layout Y starting offset, Layout X direction {-1|1}, Layout Y direction {-1|1}

sumFillLevelInfos

Description
Sum up the values of an array of animal husbandry fill level info tables.
The fill level info tables have the form of {fillType=fillType, fillLevel=fillLevel, capacity=capacity}. The method
assumes that the array contains only different instances of the same fill type.
Definition
sumFillLevelInfos()
Return Values
elementXoffset, element Y offset

updateLivestockHusbandryProductionDisplay

Description
Update production display for a livestock husbandry.
WIP, no assets ready for testing!
Definition
updateLivestockHusbandryProductionDisplay()
Return Values
whichshould receive focus instead

updateHusbandryConditionsDisplay

Description
Update base conditions (dirt, water, straw) display for a husbandry.
Definition
updateHusbandryConditionsDisplay()
Return Values
floatModifiedX offset
floatModifiedY offset

updateHusbandryFoodDisplay

Description
Update food levels and capacities display for a husbandry.
Definition
updateHusbandryFoodDisplay()

displayHorse

Description
Display data of a single horse in the detail view.
Definition
displayHorse()
Return Values
Trueifthe input event has been handled, false otherwise.

displayLivestock

Description
Display data of a livestock husbandry (pigs, cows, etc.) in the detail view.
Definition
displayLivestock()
Return Values
Trueifthe keyboard input has been processed by this element.

updateMenuButtons

Description
Update contextual menu buttons.
Definition
updateMenuButtons()
Return Values
Actualelement to focus.

renameCurrentHorse

Description
Rename the currently selected horse if the new name has been confirmed.
Definition
renameCurrentHorse()
Return Values
Listofthis element's descendants in depth-first order with contiguous numeric indices.

getFoodDescription

Description
Get a formatted food description text for an animal type.
Definition
getFoodDescription()
Return Values
Firstmatchingdescendant element in depth-first order or nil, if no element matched the predicate function

onButtonRename

Description
Handle "rename" button activation when a horse is selected.
Definition
onButtonRename()
Return Values
elementornil

onListSelectionChanged

Description
Handle animal list selection changes.
Definition
onListSelectionChanged()
Return Values
elementornil

InGameMenuContractsFrame

Description
Exposed controls usable as fields in this frame, identified in configuration.

new

Description
Create a new InGameMenuContractsFrame instance.
Definition
new(table subclass_mt)
Arguments
tablesubclass_mt[optional] Meta table of subclass
Return Values
parentelementor full screen borders in an array: {minX, minY, maxX, maxY}

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
elementbordersin an array: {minX, minY, maxX, maxY}

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()
Return Values
floatXaspect scale factor
floatYaspect scale factor

setButtonsForState

Description
Update the state of the frame buttons.
Definition
setButtonsForState()

updateList

Description
Request a mission list update, but remember the position of the selection
If the mission is still in the list, the selection stays
Definition
updateList()
Return Values
indexornil, field name

updateDetailContents

Description
Update the contents of the contract detail screen (context sensitive)
Definition
updateDetailContents()
Return Values
Actualelement to focus.

updateFarmersBox

Description
Update the content of the box with farmer information, using the field.
Definition
updateFarmersBox()
Return Values
boolTrueif the page changed

InGameMenuFinancesFrame

Description
Financial overview of the player's farm for the in-game menu.
-- Displays current balance and loan situation as well as past and present incomes and expenses.
--@category GUI

new

Description
Create a new InGameMenuFinancesFrame instance.
Definition
new(table subclass_mt)
Arguments
tablesubclass_mt[optional] Meta table of subclass
Return Values
Page

initialize

Description
Initialize the finances frame after component creation.
Definition
initialize()
Return Values
PagecontainerGuiElement instance

setClient

Description
Set networking client reference.
Definition
setClient()
Return Values
intPageindex

setEnvironment

Description
Set the mission environment reference.
Definition
setEnvironment()
Return Values
intPagemapping index

setPlayerFarm

Description
Set the player's current farm reference.
Definition
setPlayerFarm()
Return Values
boolTrueif the event was not used, false if it was used.

setHasMasterRights

Description
Set the player's master rights status.
Definition
setHasMasterRights()
Return Values
boolTrueif the event was not used, false if it was used.

getPastDays

Description
Get the array of days before today counting back to the number of displayed past days.
The method resolves days to display labels which can be used directly.
Definition
getPastDays()
Return Values
boolTrueif the event was not used, false if it was used.

setupFinancesTable

Description
Late setup of finances table called on initialization.
Definition
setupFinancesTable()
Return Values
boolTrueif the event was not used, false if it was used.

updateBalance

Description
Update the current balance display text.
Definition
updateBalance()
Return Values
boolTrueif the event was not used, false if it was used.

updateLoan

Description
Update the loan display text.
Definition
updateLoan()
Return Values
boolTrueif the event was not used, false if it was used.

updateDayTotals

Description
Update the expenses/incomes total for all displayed days.
Definition
updateDayTotals()
Return Values
numberoflist items in data source

updateFinancesFooter

Description
Update statically positioned totals display.
Definition
updateFinancesFooter()
Return Values
tableArrayof button info as {i={inputAction=<action name>, text=<optional display text>, callback=<optional callback>}}

updateFinancesTable

Description
Update table display data.
Definition
updateFinancesTable()
Return Values
DataCellornil if not found.

updateFinances

Description
Update finances display.
Definition
updateFinances()
Return Values
DataCellornil if not found.

updateFinancesLoanButtons

Description
Update loan button active states.
Definition
updateFinancesLoanButtons()
Return Values
ListofSortCell for the requested column name

updateMoneyUnit

Description
Update the current money unit.
Also applies the unit change to the borrow/repay button labels.
Definition
updateMoneyUnit()
Return Values
indexofselected row

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()
Return Values
dataRowinstanceor nil, selected data index or 0

buildDataRow

Description
Build a table data row for a given financial statistic.
Definition
buildDataRow()
Return Values
dataRowinstanceor nil (element not part of table row)

onButtonBorrow

Description
Handle borrow money action.
Definition
onButtonBorrow()
Return Values
numberofdata view rows

onButtonRepay

Description
Handle repay money action.
Definition
onButtonRepay()
Return Values
Actualelement to focus.

InGameMenuFrameElement

Description
Base class for frame elements for the in-game menu.
--@category GUI

new

Description
Create a new InGameMenuFrameElement instance.
Definition
new()

initialize

Description
Late initialization of a menu frame.
Override in sub-classes.
Definition
initialize()

getHasCustomMenuButtons

Description
Check if this menu frame requires menu button customization.
Definition
getHasCustomMenuButtons()

getMenuButtonInfo

Description
Get custom menu button information.
Definition
getMenuButtonInfo()
Return Values
tableArrayof button info as {i={inputAction=<action name>, text=<optional display text>, callback=<optional callback>}}

setMenuButtonInfo

Description
Set custom menu button information.
Definition
setMenuButtonInfo(table menuButtonInfo)
Arguments
tablemenuButtonInfoArray of button info as {i={inputAction=<action name>, text=<optional display text>, callback=<optional callback>}} or nil to reset.

setMenuButtonInfoDirty

Description
Set the menu button info dirty flag which causes the menu to update the buttons from this element's information.
Definition
setMenuButtonInfoDirty()

isMenuButtonInfoDirty

Description
Get the menu button info dirty state (has changed).
Definition
isMenuButtonInfoDirty()

clearMenuButtonInfoDirty

Description
Clear menu button dirty flag.
Definition
clearMenuButtonInfoDirty()

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()

requestClose

Description
Request to close the frame.
Frames can contain logic (e.g. saving pending changes) which should be handled before closing. Use this method in
sub-classes request closing the frame so it can wrap up first. If a callback is provided and the initial request
could not close the frame, the callback will be called as soon as the frame can be closed.
Definition
requestClose()

onFrameOpen

Description
Called when this frame is opened by its container.
Definition
onFrameOpen()

onFrameClose

Description
Called when this frame is closed by its container.
Definition
onFrameClose()

InGameMenuGameSettingsFrame

Description
Current savegame settings page for the in-game menu.
--@category GUI

new

Description
Create a new InGameMenuGameSettingsFrame instance.
Definition
new(table subclass_mt)
Arguments
tablesubclass_mt[optional] Meta table of subclass
Return Values
Thenewsorting order

initialize

Description
Initialize the game settings frame with concrete page references.
This must be called after loading, since page frames are cloned and references cannot be injected in the constructor.
Definition
initialize()
Return Values
tableAchievementMessageinstance

setMissionInfo

Description
Set the current mission's info.
Required to get current settings and to modify game name.
Definition
setMissionInfo()
Return Values
floatXposition in screen space
floatYposition in screen space

setManureTriggers

Description
Set the currently known manure triggers in the game for helper manure refill settings.
Definition
setManureTriggers()

setHasMasterRights

Description
Set master rights status of the current game instance / player.
Definition
setHasMasterRights()
Return Values
tableChatWindowinstance

updateGameSettings

Description
Update settings display with values from the current mission info / savegame.
Definition
updateGameSettings()
Return Values
floatXposition in screen space
floatYposition in screen space

updatePauseButtonState

Description
Update the pause buttons visuals for pausing/unpausing based on the game state.
Definition
updatePauseButtonState()

assignStaticTexts

Description
Assign static option settings texts.
Definition
assignStaticTexts()
Return Values
intDisplayrow index of the newly added custom text or 0 if it could not be added

assignTimeScaleTexts

Description
Assign time scale setting texts.
Definition
assignTimeScaleTexts()
Return Values
floatXposition in screen space
floatYposition in screen space

assignDirtTexts

Description
Assign dirt setting texts.
Definition
assignDirtTexts()

assignPlantGrowthTexts

Description
Assign plant growth texts.
Definition
assignPlantGrowthTexts()
Return Values
floatGameinfo display width of visible elements in screen space

assignAutoSaveTexts

Description
Assign auto save texts.
Definition
assignAutoSaveTexts()
Return Values
tableWeathericon HUDElement instance

assignDynamicTexts

Description
Assign game state dependent setting texts.
Definition
assignDynamicTexts()
Return Values
tableTemperatureicon HUDElement instance

updateToolTipBoxVisibility

Description
Update visibility of tool tip box, only show when there is text to display.
Definition
updateToolTipBoxVisibility()
Return Values
tableClockhand HUDElement instance

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
tableTimescale arrow icon HUDElement instance

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()
Return Values
tableGamePausedDisplayinstance

onEnterPressedSavegameName

Description
Handle accepting savegame name input.
Definition
onEnterPressedSavegameName()
Return Values
boolIftrue, the HUD is currently visible.

onToolTipBoxTextChanged

Description
Handle changing of the tool tip text.
Definition
onToolTipBoxTextChanged()
Return Values
tableHUDDisplayElementinstance

InGameMenuGeneralSettingsFrame

Description
General game settings page for the in-game menu.
--@category GUI

new

Description
Create a new InGameMenuGeneralSettingsFrame instance.
Definition
new(table subclass_mt, table settingsModel)
Arguments
tablesubclass_mt[optional] Meta table of subclass
tablesettingsModelSettingsModel reference which handles settings display state across the UI
Return Values
floatScreenspace X translation
floatScreenspace Y translation

updateGeneralSettings

Description
Update display values from settings.
Definition
updateGeneralSettings()

updateToolTipBoxVisibility

Description
Update visibility of tool tip box, only show when there is text to display.
Definition
updateToolTipBoxVisibility()
Return Values
tableHUDElementinstance

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
floatPivotx position offset from element position in screen space
floatPivoty position offset from element position in screen space

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()

onClickCheckbox

Description
Handle clicks on a check box.
Definition
onClickCheckbox()
Return Values
floatXposition in screen space
floatYposition in screen space

onClickMultiOption

Description
Handle clicks on a multi option element.
Definition
onClickMultiOption()

onClickNativeHelp

Description
Handle a button click on the native help button which is only visible and active on XBOX.
Definition
onClickNativeHelp()
Return Values
widthscalefactor
heightscalefactor

onToolTipBoxTextChanged

Description
Handle changing of the tool tip text.
Definition
onToolTipBoxTextChanged()

InGameMenuHelpFrame

Description
Exposed controls usable as fields in this frame, identified in configuration.

new

Description
Create a new InGameMenuHelpFrame instance.
Definition
new(table subclass_mt)
Arguments
tablesubclass_mt[optional] Meta table of subclass
Return Values
floatRedvalue
floatGreenvalue
floatBluevalue
floatAlphavalue

setMissionBaseDirectory

Description
Set the current mission's base directory to let this frame load images from that location.
Definition
setMissionBaseDirectory()

createList

Description
Set up UI elements for a given category index.
Definition
createList()

loadHelpLine

Description
Load help category texts.
Definition
loadHelpLine()

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
floatAlphavalue

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()
Return Values
tableHUDPopupMessageinstance

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
floatScreenspace X translation
floatScreenspace Y translation

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()

onHelpLineListSelectionChanged

Description
Handle a change of row in the current category's help list.
Definition
onHelpLineListSelectionChanged()
Return Values
tableHUDTextDisplayinstance

InGameMenuMapFrame

Description
Map overview frame of the in-game menu.
-- Displays the current map with markers for points of interest and terrain overlays.
--@category GUI

new

Description
Create a new InGameMenuMapFrame instance.
Definition
new(table subclass_mt)
Arguments
tablesubclass_mt[optional] Meta table of subclass
Return Values
boolTrueif the left border of the map has been reached
boolTrueif the right border of the map has been reached
boolTrueif the top border of the map has been reached
boolTrueif the bottom border of the map has been reached

createInputGlyphs

Description
Create input help glyphs.
Definition
createInputGlyphs()

initialize

Description
Initialize map frame after GUI setup.
Definition
initialize()

onLoadMapFinished

Description
Called by InGameMenu when a map has finished loading.
Definition
onLoadMapFinished()

toggleMapInput

Description
Toggle map overview-specific input.
Make sure this is called exactly once for activation and deactivation each when the map frame is opened or closed.
Definition
toggleMapInput()
Return Values
boolTrueif the left border of the map has been reached
boolTrueif the right border of the map has been reached
boolTrueif the top border of the map has been reached
boolTrueif the bottom border of the map has been reached

disableAlternateBindings

Description
Disable alternate bindings for menu navigation.
This will disable some default bindings which interfere with camera controls (e.g. D-Pad on controller). Whenever any
input event is modified, this method must be called again afterwards.
Definition
disableAlternateBindings()

getContextBoxPositionAndOrientation

Description
Get the context box position and orientation for a given hotspot.
Definition
getContextBoxPositionAndOrientation()
Return Values
floatScreenspace X position
floatScreenspace Y position
stringOrientationvalue, one of InGameMenuMapFrame.CONTEXT_BOX_ORIENTATION
floatRotationangle value

updateContextBoxPosition

Description
Update the position of the hotspot context box if it's active.
Definition
updateContextBoxPosition()

setInGameMap

Description
Set the IngameMap reference in this frame's required IngameMapElement for display.
Definition
setInGameMap()
Return Values
floatXposition in screen space after the last glyph

setTerrainSize

Description
Set the terrain size for use in the ingameMapElement.
Definition
setTerrainSize()
Return Values
floatXposition in screen space after the last glyph

setMissionFruitTypes

Description
Set the fruit types used in the current mission.
Definition
setMissionFruitTypes()
Return Values
floatScreenspace height used by the combo header (0 if invisible)

setClient

Description
Set the client connection object for event dispatching.
Definition
setClient()
Return Values
tableInputhelp elements
floatScreenspace height used by the returned help elements

setPlayerFarm

Description
Set the current player's farm ID.
Definition
setPlayerFarm()

assignFilterData

Description
Assign filter data after map loading.
Definition
assignFilterData()
Return Values
intMaximumnumber of entries to show

assignCropTypeFilterData

Description
Assign display data for the crop type filters.
Definition
assignCropTypeFilterData()
Return Values
booleanisAllowedisAllowed

assignGroundStateFilterData

Description
Assign display data for the ground state filters (growth and soil state).
Definition
assignGroundStateFilterData()
Return Values
tableComboInputGlyphElement instance

assignGroundStateColors

Description
Assign colors for ground state (growth or soil) elements.
Definition
assignGroundStateColors()
Return Values
tableComboheader HUDElement

resetUIDeadzones

Description
Reset the UI dead zones for the map.
Definition
resetUIDeadzones()
Return Values
floatDisplayheight in screen space

setStaticUIDeadzone

Description
Set a static UI dead zone for the map to make it ignore cursor/mouse input within that screen region.
This dead zone is always in effect, regardless of map mode.
Definition
setStaticUIDeadzone()
Return Values
floatModifiedinput help panel drawing vertical offset

onOverviewOverlayFinished

Description
Called when the overview overlay is finished for display.
Definition
onOverviewOverlayFinished()
Return Values
tableSideNotificationinstance

onFarmlandOverlayFinished

Description
Called when the farmland overlay is finished for display.
Definition
onFarmlandOverlayFinished()
Return Values
tableSpeakerDisplayinstance

generateOverviewOverlay

Description
(Re-)Generate the map overlay for crop types, growth and soil states.
Definition
generateOverviewOverlay()
Return Values
tableOverlayinstance

generateFarmlandOverlay

Description
(Re-)Generate the map overlay for farmlands.
Definition
generateFarmlandOverlay()
Return Values
tableHUDElementinstance

setFilterIconState

Description
Set the display state of a filter icon based on the current filter settings.
Definition
setFilterIconState()
Return Values
tableTopNotificationinstance

toggleFarmlandsHotspotFilterSettings

Description
Toggle hotspot filter settings for the farmlands view mode.
Definition
toggleFarmlandsHotspotFilterSettings()
Return Values
floatScreenspace X translation
floatScreenspace Y translation

showContextInput

Description
Show input buttons based on the current map selection context.
Definition
showContextInput()

updateContextInputBarVisibility

Description
Update the context input bar's visibility.
Turns it invisible if there are no buttons visile, otherwise turns it visible.
Definition
updateContextInputBarVisibility()
Return Values
boolIftrue, the HUD extension should be drawn in the current frame.

showContextMarker

Description
Show marker button according to context.
Definition
showContextMarker()
Return Values
floatModifiedinput help panel drawing vertical offset

showContextBox

Description
Show the context box for a selected hotspot.
Definition
showContextBox()
Return Values
tableHUDextension instance or nil of no extension has been registered for the given specialization

hideContextBox

Description
Hide the hotspot context box.
Definition
hideContextBox()
Return Values
tableArrayof overlay descriptions: {overlay=overlay, x=0, y=0, rotation=0, invertX=false, invisibleBorderRight=vehicle.schemaOverlay.invisibleBorderRight, invisibleBorderLeft=vehicle.schemaOverlay.invisibleBorderLeft}
floatScreenspace height of root vehicle schema overlay

setMapSelectionItem

Description
Set the map selection to a hotspot.
Definition
setMapSelectionItem()

getHotspotData

Description
Get display data for a selectable map hotspot.
Definition
getHotspotData()
Return Values
floatMinimumX position (left)
floatMaximumX position (right)
stringDescriptiontext
stringDisplayimage file path
tableDisplayimage UVs
tableVehicleinstance if a vehicle has been selected, or nil otherwise

setColorBlindMode

Description
Set the current color blind mode.
Updates colors on buttons and overlays.
Definition
setColorBlindMode(bool isActive)
Arguments
boolisActiveIf true, color blind mode is active

initializeFilterButtonState

Description
Initialize filter buttons with the current filter state.
Definition
initializeFilterButtonState()
Return Values
tableSchemaOverlay instance

resetFarmlandSelection

Description
Reset farmland selection state.
Definition
resetFarmlandSelection()
Return Values
tableInGameMenuAnimalsFrameinstance

checkPlaceablesOnFarmland

Description
Check if there are any placeables owned by the player on a given farmland.
Definition
checkPlaceablesOnFarmland()
Return Values
floatScreenspace X position
floatScreenspace Y position
stringOrientationvalue, one of InGameMenuMapFrame.CONTEXT_BOX_ORIENTATION
floatRotationangle value

onMoneyChanged

Description
Handle changes to farm balance values.
Definition
onMoneyChanged(int farmId, float newBalance)
Arguments
intfarmIdID of farm whose current balance has changed
floatnewBalanceNew balance value of the given farm

onDrawPostIngameMap

Description
Called after the in-game map has been drawn.
Draws the mode-dependent state overlay on top of the map
Definition
onDrawPostIngameMap()

onClickMapOverviewSelector

Description
Handle clicking the map overview selector which switches map overlay context (crop types, growth states, soil states).
Definition
onClickMapOverviewSelector()

onFilterButtonSelect

Description
Handle filter button focus or highlight activation.
Definition
onFilterButtonSelect()
Return Values
stringDescriptiontext
stringDisplayimage file path
tableDisplayimage UVs
tableVehicleinstance if a vehicle has been selected, or nil otherwise

onFilterButtonUnselect

Description
Handle filter button focus or highlight deactivation.
Definition
onFilterButtonUnselect()

setFilterButtonDisplayEnabled

Description
Set the display state of a filter button.
Definition
setFilterButtonDisplayEnabled()

toggleFilter

Description
Toggle filter state on filter button click.
Definition
toggleFilter()

onClickCropFilter

Description
Handle activation of a crop type filter.
Definition
onClickCropFilter(table element, int fruitTypeIndex)
Arguments
tableelementClicked button element
intfruitTypeIndexFruit type index as valid in the current mission.
Return Values
intListindex corresponding to the farm ID or 1 if it could not be found or was the spectator farm ID

onClickGrowthFilter

Description
Handle activation of a growth state filter.
Definition
onClickGrowthFilter(table element, int growthStateIndex)
Arguments
tableelementClicked button element
intgrowthStateIndexGrowth state index
Return Values
dataRowinstancewith prices data for the given selling point

onClickSoilFilter

Description
Handle activation of a soil state filter.
Definition
onClickSoilFilter(table element, int growthStateIndex)
Arguments
tableelementClicked button element
intgrowthStateIndexSoil state index
Return Values
floatSortingvalue, see TableElement:setCustomSortFunction(...)

onClickHotspot

Description
Handle clicking / activating a map hotspot.
Definition
onClickHotspot()
Return Values
floatCurrentfill level >= 0 or a value < 0 if no storage exists for the requested fill type index
floatTotalcapacity for the fill type >= 0 or a value < 0 if no storage exists for the requested fill type index

onClickMap

Description
Handle clicking within the map.
Definition
onClickMap()

onFarmlandStateChanged

Description
Called from FarmlandManager whenever a significant farmland change (mainly ownership) occurs.
Definition
onFarmlandStateChanged()
Return Values
tableTableElement.DataRowinstance

onVehicleReset

Description
Handle ResetVehicleEvent local event.
Definition
onVehicleReset()
Return Values
dataRowinstancewith vehicle data for the given vehicle

onClickSwitchMapMode

Description
Handle activation of map mode switch button.
Definition
onClickSwitchMapMode()
Return Values
floatSortingvalue, see TableElement:setCustomSortFunction(...)

onYesNoReset

Description
Dialog confirmation callback for resetting a vehicle.
Definition
onYesNoReset()
Return Values
Trueifthe server matches the current filter settings, false otherwise

notifyPause

Description
Notify this frame when pausing the game.
Definition
notifyPause()
Return Values
dataRowinstancewith server data

selectFirstHotspot

Description
Select the first visible hotspot on the map
Definition
selectFirstHotspot()
Return Values
tableLandscapingScreeninstance

updateInputGlyphTransform

Description
Fit an input glyph into its corresponding placeholder GuiElement instance.
Definition
updateInputGlyphTransform()
Return Values
tablenewLandscapingScreenController instance

updateInputGlyphs

Description
Update input glyphs when input context changes.
Definition
updateInputGlyphs()
Return Values
intNodeID of the actual indicator shape in the loaded indicator asset
intNodeID of the attached light source of the loaded indicator asset

onYesNoBuyFarmland

Description
Handle confirmation result of farmland buying dialog.
Definition
onYesNoBuyFarmland()

onYesNoSellFarmland

Description
Handle confirmation result of farmland selling dialog.
Definition
onYesNoSellFarmland()
Return Values
tablecategorieslist of categories

registerInput

Description
Register input actions.
Definition
registerInput()
Return Values
tablePlacementScreeninstance

onMenuActivate

Description
Menu activate event, bound to vehicle enter, place visit or buying farmlands.
Definition
onMenuActivate()
Return Values
Trueifthe placement is valid, false otherwise
stringReasonof being invalid

onMenuCancel

Description
Menu cancel event, bound to hotspot tagging, vehicle reset or selling farmlands.
Definition
onMenuCancel()

onSwitchVehicle

Description
Switch vehicle action event, bound to cycle visible hotspots.
Definition
onSwitchVehicle()
Return Values
tableShopConfigScreeninstance

InGameMenuMultiplayerFarmsFrame

Description
Exposed controls usable as fields in this frame, identified in configuration.

new

Description
Create a new InGameMenuMultiplayerFarmsFrame instance.
Definition
new(table subclass_mt)
Arguments
tablesubclass_mt[optional] Meta table of subclass
Return Values
floatFuelcapacity in liters

initialize

Description
Late initialization after frame cloning.
Definition
initialize()
Return Values
floatBaseprice
floatUpgradeprice
boolTrueif there are changes

setCurrentUserId

Description
Set the reference to the current user.
Definition
setCurrentUserId()

setUsers

Description
Set the current users reference.
Definition
setUsers()

setPlayer

Description
Set the reference to the current player.
Definition
setPlayer()
Return Values
intNumberof used config option elements

setPlayerFarm

Description
Set the reference to the current player's farm.
Definition
setPlayerFarm()
Return Values
tableNewcollection of filtered owned items

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
tableArrayof brands in the form of {i={id = brand.index, iconFilename = brand.image, label = brand.title}}

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()
Return Values
tableArrayof vehicle categories in the form of {i={id = category.index, iconFilename = category.image, label = category.title}}

buildFarmListItems

Description
Build the farm list items from the known farms.
Definition
buildFarmListItems()
Return Values
tableArrayof tool categories in the form of {i={id = category.index, iconFilename = category.image, label = category.title}}

updateFarmList

Description
Update farm list.
Definition
updateFarmList()
Return Values
tableArrayof object categories in the form of {i={id = category.index, iconFilename = category.image, label = category.title}}

getListFarmIndex

Description
Get the list index for a given farm ID.
Definition
getListFarmIndex(int farmId)
Arguments
intfarmIdFarm ID
Return Values
tableArrayof placeable categories in the form of {i={id = category.index, iconFilename = category.image, label = category.title}}
intListindex corresponding to the farm ID or 1 if it could not be found or was the spectator farm ID

updateFarmBalance

Description
Update a farm's balance display.
Definition
updateFarmBalance()
Return Values
intNextusable attribute slot index after these fill types

updateFarmPlayers

Description
Update displayed player names on a farm.
Definition
updateFarmPlayers()
Return Values
intNumberof attributes used for text data

updateMenuButtons

Description
Update context menu buttons.
Definition
updateMenuButtons()
Return Values
tableinstanceInstance of object

joinFarm

Description
Let the current player join a given farm.
The player will leave their current farm (can be spectator farm) and join the new farm if possible. This sends
a PlayerSetFarmEvent which will check any farm password on the server side. In response, a PlayerSetFarmAnswerEvent
is sent back. The method will try using a previously recorded farm password if one has been received during a join
event.
Definition
joinFarm()
Return Values
booleansuccesssuccess

leaveFarm

Description
Let the current player leave their farm.
The player will join the spectator farm and be able to choose a new farm to join.
Definition
leaveFarm()
Return Values

deleteFarm

Description
Delete a given farm
The current player must have admin privileges on the server and the farm must be empty.
Definition
deleteFarm()
Return Values
float
float
float
float
float
float

editFarm

Description
Show a dialog to edit farm properties.
The current player must have farm manager or administrator privileges on the server.
Definition
editFarm()

createFarm

Description
Show a dialog to create a new farm
The current player must have administrator privileges on the server.
Definition
createFarm()

onPlayerSetFarmAnswer

Description
Handle an answer to PlayerSetFarmEvent.
Definition
onPlayerSetFarmAnswer(int answerState, int farmId, string password)
Arguments
intanswerStatePlayerSetFarmAnswerEvent.STATE member
intfarmIdIf the state is OK, will contain the newly joined farm
stringpasswordIf the state is OK, will contain the newly joined farm's password

onFarmPasswordEntered

Description
Handle confirmation of farm password input when joining a farm.
Definition
onFarmPasswordEntered()

onPermissionChanged

Description
Handle changes to user permissions.
If the current user's permissions change, update the menu buttons in case they were elevated to farm manager status.
Definition
onPermissionChanged()

onFarmCreated

Description
Handle creation of a new farm.
Definition
onFarmCreated()
Return Values
tableselfinstance of class event

onFarmsChanged

Description
Handle state update of any farm.
Definition
onFarmsChanged()
Return Values
tableinstanceinstance of event

onPlayerFarmChanged

Description
Handle a player changing their farm.
Definition
onPlayerFarmChanged()
Return Values
tableselfinstance of class event

onFarmMoneyChanged

Description
Handle a balance change of a farm.
Definition
onFarmMoneyChanged()
Return Values
tableinstanceinstance of event

onClickLeft

Description
Handle clicking on the left navigation button.
Definition
onClickLeft()
Return Values
tableselfinstance of class event

onClickRight

Description
Handle clicking on the right navigation button.
Definition
onClickRight()
Return Values
tableinstanceinstance of event

onClickFarm

Description
Handle a click / activation of a farm item.
Definition
onClickFarm()
Return Values
tableinstanceInstance of object

onDoubleClickFarm

Description
Handle a double click of a farm item.
Definition
onDoubleClickFarm()
Return Values
booleansuccesssuccess

onSelectionChanged

Description
Handle a farm selection change.
Definition
onSelectionChanged()
Return Values
floatdailyUpkeepdaily up keep

onDeleteFarmYesNo

Description
Handle farm deletion dialog confirmation.
Definition
onDeleteFarmYesNo()
Return Values
floatsellPricesell price

InGameMenuMultiplayerUsersFrame

Description
Multiplayer user management frame for the in-game menu.
-- Displays a user list and allows modification of permissions as well as money transfers between farms. Administrators
can log in using a password and kick/ban/unban users when logged in.
--@category GUI

new

Description
Create a new InGameMenuMultiplayerUsersFrame instance.
Definition
new(table subclass_mt)
Arguments
tablesubclass_mt[optional] Meta table of subclass
Return Values
booleanisActiveForInputis active for input

initialize

Description
Late initialization.
Definition
initialize()
Return Values
tableselfinstance of class event

onFrameOpen

Description
Called when this frame is opened by its container.
Definition
onFrameOpen()
Return Values
tableinstanceinstance of event

onFrameClose

Description
Called when this frame is closed by its container.
Definition
onFrameClose()
Return Values
tableinstanceinstance of object

setupUserListFocusContext

Description
Set up the user list to store an instance flag when navigating users or not for menu button context.
Definition
setupUserListFocusContext()
Return Values
integeridi3d rootnode

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
booleanisValidtrue if index is valid else false

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()
Return Values
integeridid of object
integeridid of used root node

setPlayerFarm

Description
Set the reference to the current player's farm.
Definition
setPlayerFarm()

setCurrentUserId

Description
Set the current user ID.
Definition
setCurrentUserId()
Return Values
NewBindinginstance

setBanStorage

Description
Set the ban storage reference.
Definition
setBanStorage()
Return Values
instanceinitialized with values from XML and the given parameters

setUsers

Description
Set the current users reference.
Definition
setUsers()
Return Values
intCombobit mask

getSortedUsers

Description
Get a new sorted array of known users for displaying.
Users are grouped by farms, starting with the current player's farm (unless they're a spectator). Within groups,
users are sorted alphabetically by name.
Definition
getSortedUsers()
Return Values
Trueifthere is a collision.

buildUserDisplayInfo

Description
Build a display name for a given user and their special privilege flags.
Definition
buildUserDisplayInfo()
Return Values
ClonedBindinginstance

rebuildUserList

Description
Update connected player information.
Definition
rebuildUserList(table missionUsers)
Arguments
tablemissionUsersArray of users managed by the current mission instance.
Return Values

updateMenuButtons

Description
Update menu buttons based on the current user's admin status.
Definition
updateMenuButtons()
Return Values
instanceinitialized with values from XML

updateBalance

Description
Update the current balance display.
Definition
updateBalance()
Return Values
ClonedInputActioninstance

setCurrentBalance

Description
Set the current money balance display.
Definition
setCurrentBalance(float balance, string balanceString)
Arguments
floatbalanceCurrent balance of the current player
stringbalanceStringProperly formatted money string
Return Values
tableInputBindinginstance

updateDisplay

Description
Update all display states and text.
Definition
updateDisplay()
Return Values
tableSetof required device categories, {<category> = true}

onButtonBan

Description
Handle a ban button activation.
Definition
onButtonBan()
Return Values
boolTrueif there are any configured bindings for the given device, false otherwise

onYesNoBan

Description
Handle ban confirmation dialog result.
Definition
onYesNoBan()
Return Values
GS_INPUT_HELP_MODE_KEYBOARDorGS_INPUT_HELP_MODE_GAMEPAD

onButtonKick

Description
Handle a kick button activation.
Definition
onButtonKick()
Return Values
GS_INPUT_HELP_MODE_KEYBOARDorGS_INPUT_HELP_MODE_GAMEPAD

onYesNoKick

Description
Handle kick confirmation dialog result.
Definition
onYesNoKick()
Return Values
Trueifthe parameters are valid, false otherwise.

onButtonUnBan

Description
Handle an unban button activation
Definition
onButtonUnBan()
Return Values
boolTrueif the event could be registered, false otherwise
stringeventID if successful, empty string otherwise
tableActionreference of a colliding action if there would be a collision, nil otherwise

onButtonShowProfile

Description
Handle a show user profile button activation.
Definition
onButtonShowProfile()

onButtonInviteFriends

Description
Handle an invite friends button activation
Definition
onButtonInviteFriends()

onButtonAdminLogin

Description
Handle an admin login button activation.
Definition
onButtonAdminLogin()
Return Values
boolTrueif there would be a collision, false otherwise
tableCollidingaction if there would be a collision, nil otherwise

onUserSelected

Description
Handle selection changes in the user list.
Definition
onUserSelected()

onClickPermission

Description
Handle clicking a permission check box.
Definition
onClickPermission(table checkboxElement, bool isActive)
Arguments
tablecheckboxElementToggleButtonElement which received the click
boolisActiveNew checked state
Return Values
arrayoftuples: {i={action=InputAction, event=InputEvent}}

onClickTransferButton

Description
Handle clicking the transfer button
Definition
onClickTransferButton()
Return Values
Gamepadcombomask, Mouse combo mask

transferMoney

Description
Transfer money from the current player's farm to the selected farm.
Definition
transferMoney()
Return Values
instanceor nil if ID is invalid

onClickRemoveFromFarm

Description
Handle clicking the remove player from farm button.
Definition
onClickRemoveFromFarm()
Return Values
instanceor nil if ID is invalid

onYesNoRemoveFromFarm

Description
Handle remove player from farm confirmation dialog result.
Definition
onYesNoRemoveFromFarm()
Return Values
instanceor nil if ID is invalid

onClickPromote

Description
Handle clicking the promote player to farm manager button.
Definition
onClickPromote()
Return Values
floatMousecursor X position in screen space
floatMousecursor Y position in screen space

onYesNoPromoteToFarmManager

Description
Handle promote user confirmation dialog result.
Definition
onYesNoPromoteToFarmManager()

onClickContractor

Description
Handle clicking the contractor toggle button.
Definition
onClickContractor()
Return Values
previousDevicesTableof internal ID -> InputDevice before the current initialization

onYesNoToggleContractorState

Description
Handle contractor state toggle confirmation dialog result.
Definition
onYesNoToggleContractorState()
Return Values
Listofdevice information tables, format: {deviceId=[device ID], name=[device name]}

onFarmMoneyChanged

Description
Handle a local money change event for any farm.
Definition
onFarmMoneyChanged()
Return Values
Modifierbitmask

onFarmsChanged

Description
Handle state update of any farm.
Definition
onFarmsChanged()
Return Values
Trueifthe binding's device ID could be resolved, false otherwise

onPlayerFarmChanged

Description
Handle a player changing their farm.
Definition
onPlayerFarmChanged()
Return Values
functionresultstable {checkFunctionRef=[functionResult]}

onPermissionChanged

Description
Handle a local player permission change event.
Definition
onPermissionChanged()
Return Values

onContractingStateChanged

Description
Handle a local contracting state change event.
Definition
onContractingStateChanged()
Return Values
boolTrueif the new binding could be added
tableReferenceto an Action containing a binding which collided with the added binding or nil

onAdminPassword

Description
Handle admin login password dialog response.
Definition
onAdminPassword()

onAdminLoginSuccess

Description
Handle successfully logging in as an admin.
Definition
onAdminLoginSuccess()
Return Values
Trueifa binding could be found and updated, false if there was a collision
andAction reference of a collision as {collisionBinding=Binding, collisionAction=Action} or nil

InGameMenuPricesFrame

Description
Prices overview frame of the in-game menu.
-- Displays current prices of sellable goods and produce.
--@category GUI

new

Description
Create a new InGameMenuPricesFrame instance.
Definition
new(table subclass_mt, table l10n, table fillTypeManager)
Arguments
tablesubclass_mt[optional] Meta table of subclass
tablel10nI18N reference
tablefillTypeManagerFillTypeManager reference

makeTableFocusOverrideFunction

Description
Create a focus override function for the prices table which scrolls horizontally if possible instead of exiting the
table.
Definition
makeTableFocusOverrideFunction()
Return Values
Trueifall given axes are currently active, input value of the non-modified axis (last in list)

getStationName

Description
Get the display name of a selling station.
Definition
getStationName()
Return Values
Trueifall axes are active (digital interpretation), input value of the non-modified axis (last in list)

setSellingStations

Description
Set the current list of selling stations for displaying.
Definition
setSellingStations()
Return Values
Inputvalueof the axis in the range [-1, 1] for full axes or [0, 1] for half axes.

updateVerticalSlider

Description
Update item counts and handle size of the vertical slider.
Definition
updateVerticalSlider()
Return Values

setupPriceTable

Description
Initial setup of the prices table and required data.
Definition
setupPriceTable()
Return Values
Orderedactionbindings in the form of {i={action=InputAction, bindings={Binding}}}

updatePriceTable

Description
Update prices table display data.
Definition
updatePriceTable()
Return Values

updateHeaderIcons

Description
Update table headers with fill type icons according to current horizontal slider position.
Definition
updateHeaderIcons()
Return Values
tableArrayof events

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
tableFirstactive event or InputEvent.NO_EVENT

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()
Return Values
xmotionscale, Y motion scale

onChangedPriceSlider

Description
Handle horizontal slider changes.
Definition
onChangedPriceSlider()
Return Values
Trueifthe user settings have passed the integrity check, false otherwise.

onClickPriceHeader

Description
Handle price table header clicks.
Causes the table to be sorted by the clicked header column's numeric price values.
Definition
onClickPriceHeader()
Return Values
Trueifthe axis name represents a physical full axis, false otherwise

onClickSellingPointHeader

Description
Handle selling point table header clicks.
Causes the table to be sorted by selling point names.
Definition
onClickSellingPointHeader()
Return Values
Trueifthe input name represents an analog input

onClickPrices

Description
Handle table row clicks.
Definition
onClickPrices()
Return Values
Trueifthe axis is at zero position, false otherwise

onDoubleClickPrices

Description
Handle table row double-clicks.
Sets a map marker on the selected selling point or clears it again.
Definition
onDoubleClickPrices()
Return Values
NewInputDeviceinstance

onDataBindSellingPoint

Description
Bind an element to the selling point data.
Definition
onDataBindSellingPoint()
Return Values
DeviceIDor empty string

onDataBindPrice

Description
Bind an element to the indexed price data.
Definition
onDataBindPrice()
Return Values
Devicenameor empty string

onDataBindSiloCapacityLabel

Description
Bind an element to the silo capacity label data.
Definition
onDataBindSiloCapacityLabel()
Return Values
Prefixnumber,or -1 if none exists; raw engine-issued device ID

onDataBindSiloCapacityValue

Description
Binding an element to the indexed silo capacity value data.
Definition
onDataBindSiloCapacityValue()
Return Values
instancecontaining the symbol overlays in its "buttons" field

setSellingPointData

Description
Set data for a selling point table cell.
Definition
setSellingPointData(table dataCell, table sellingStation)
Arguments
tabledataCellTableElement.DataCell instance for a selling point cell
tablesellingStationSellingStation instance of the current data row
Return Values
arrayofhelp elements (see InputDisplayManager:makeHelpElement() for structure)

setPriceData

Description
Set data for a price table cell.
Definition
setPriceData(table dataCell, int priceIndex, table sellingStation)
Arguments
tabledataCellTableElement.DataCell instance for a price cell
intpriceIndexPrice column index
tablesellingStationSellingStation instance of the current data row
Return Values
Hashtableof currently active combo button action names, {action name=true}

buildDataRow

Description
Build a DataRow from selling point properties to add to the prices table
Definition
buildDataRow(table sellingStation)
Arguments
tablesellingStationSellingStation reference
Return Values
Axisnameor nil if not found, internal ID of binding device
dataRowinstancewith prices data for the given selling point

sortPrices

Description
Table sorting function for prices.
Definition
sortPrices(table sortCell1, table sortCell1)
Arguments
tablesortCell1TableElement.SortCell instance representing the first cell to compare
tablesortCell1TableElement.SortCell instance representing the second cell to compare
Return Values
instanceor nil if no overlay is available for the action's bindings
floatSortingvalue, see TableElement:setCustomSortFunction(...)

getStorageFillLevel

Description
Get the storage fill level for a given fill type index.
Definition
getStorageFillLevel(int index, bool farmSilo)
Arguments
intindexFill type index of the requested storage fill level
boolfarmSiloIf true, only counts storage of owned farm silos
Return Values
keytext(e.g. "F" for "KEY_f") for the keyboard action binding or nil if no resolution is possible
floatCurrentfill level >= 0 or a value < 0 if no storage exists for the requested fill type index
floatTotalcapacity for the fill type >= 0 or a value < 0 if no storage exists for the requested fill type index

InGameMenuStatisticsFrame

Description
Game statistics display frame for the in-game menu.
--@category GUI

new

Description
Create a new InGameMenuStatisticsFrame instance.
Definition
new(table subclass_mt)
Arguments
tablesubclass_mt[optional] Meta table of subclass
Return Values
controllersymbolsconfiguration key name

updateStatistics

Description
Update statistics data in tables.
Definition
updateStatistics()
Return Values
controllersymbolsconfiguration key name

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
NewInputEventinstance

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()
Return Values
tableinstanceinstance of object

buildDataRow

Description
Build a table data row for a given statistics attribute.
Definition
buildDataRow(table statAttribute)
Arguments
tablestatAttributeStatistics attribute as defined in FarmStats
Return Values
booleantrueif loading was successful else false
tableTableElement.DataRowinstance

InGameMenuTutorialFrame

Description
Exposed controls usable as fields in this frame, identified in configuration.

new

Description
Create a new InGameMenuFinancesFrame instance.
Definition
new(table subclass_mt)
Arguments
tablesubclass_mt[optional] Meta table of subclass
Return Values
stringcutterEffectTypethe real cutterEffect name, nil if not defined

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
tablecutterEffectscutter effects

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()
Return Values
tableinstanceinstance of object

InGameMenuVehiclesFrame

Description
Exposed controls usable as fields in this frame, identified in configuration.

new

Description
Create a new InGameMenuVehiclesFrame instance.
Definition
new(table subclass_mt, table messageCenter, table l10n, table storeManager, table brandManager)
Arguments
tablesubclass_mtSub-class meta table
tablemessageCenterMessageCenter reference for notifications
tablel10nI180N reference for display text resolution
tablestoreManagerStoreManager reference for vehicle store data look-ups
tablebrandManagerBrandManager reference for vehicle brand data look-ups
Return Values
booleantrueif loading was successful else false

initialize

Description
Late initialization.
Definition
initialize()
Return Values
stringmaterialTypethe real material name, nil if not defined

updateGarage

Description
Update the garage view.
Definition
updateGarage()
Return Values
integermaterialIdid of material

updateVerticalSlider

Description
Update item counts and handle size of the vertical slider.
Definition
updateVerticalSlider()
Return Values
tableinstanceinstance of object

setAccessibleVehicles

Description
Set a list of vehicles currently accessible by the player.
Definition
setAccessibleVehicles()
Return Values
booleantrueif loading was successful else false

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
stringparticleTypethe real particle name, nil if not defined

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()
Return Values
tableparticleSystemparticleSystem

makeTableHeaderFocusOverrideFunction

Description
Create a focus override function for a table header which modifies the scroll bar instead of navigation when
vertical navigation input is received.
Definition
makeTableHeaderFocusOverrideFunction()
Return Values
tableinstanceinstance of object

setNameData

Description
Set data for a vehicle name table cell.
Definition
setNameData()
Return Values
booleantrueif loading was successful else false

setAgeData

Description
Set data for a vehicle age table cell.
Definition
setAgeData()
Return Values
booleantrueif loading was successful else false

setOperatingHoursData

Description
Set data for a vehicle operating hours table cell.
Definition
setOperatingHoursData()
Return Values
tableinstanceinstance of object

setDamageData

Description
Set data for a vehicle damage table cell.
Definition
setDamageData()
Return Values
tableinstanceinstance of object

setLeasingData

Description
Set data for a vehicle leasing costs table cell.
Definition
setLeasingData()
Return Values
tableinstanceinstance of object

setValueData

Description
Set data for a vehicle selling value table cell.
Definition
setValueData()
Return Values
booleantrueif loading was successful else false

buildDataRow

Description
Build a DataRow from vehicle properties to add to the table.
Definition
buildDataRow(table vehicle)
Arguments
tablevehicleVehicle reference
Return Values
tablebaleTypebaleType object
dataRowinstancewith vehicle data for the given vehicle

sortAttributes

Description
Table sorting function for numeric values.
Definition
sortAttributes(table sortCell1, table sortCell1)
Arguments
tablesortCell1TableElement.SortCell instance representing the first cell to compare
tablesortCell1TableElement.SortCell instance representing the second cell to compare
Return Values
tablebaleTypebaleType object
floatSortingvalue, see TableElement:setCustomSortFunction(...)

onClickVehicleHeader

Description
Handle clicks on the vehicle name header.
Switches table to default string sorting.
Definition
onClickVehicleHeader()
Return Values
tablebalebale

onClickAttributeHeader

Description
Handle clicks on an attribute header.
Switches table to numerical sorting.
Definition
onClickAttributeHeader()
Return Values
stringbaleKeybale key

InputAction

Description
Logical input action.
-- Game components react to actions to alter their state. Available actions are loaded from "dataS/inputActions.xml".
Default action names are available for use as constants in the form of InputAction.ACTION_NAME (see end of file).
Additional actions (e.g. from mods) will be dynamically added as such constants at run time.
--@category Input
--@xmlConfig action#name Action name. This serves as a unique identifier in both configuration and code.

new

Description
Create a new InputAction instance
Definition
new(name Action, axisType Type, isLocked If, ignoreComboMask If, displayNamePositive [optional], displayNameNegative [optional])
Arguments
nameActionname, unique
axisTypeTypeof action axis (HALF or FULL)
isLockedIftrue, bindings for this action cannot be changed in the game
ignoreComboMaskIftrue, non-combo bindings will trigger this action even if a combo button is currently active
displayNamePositive[optional]Display name of the action in positive direction for the current localization
setting. This is the default display name.
displayNameNegative[optional]Display name of the action in negative direction for the current localization
setting. Only used for full axes.
Return Values
InputAction

createFromXML

Description
Create a new InputAction instance from an XML element.
Definition
createFromXML(xmlFile XML, elementTag Tag)
Arguments
xmlFileXMLfile handle
elementTagTagof the element to parse as an InputAction
Return Values
integernumPixelsnumber of pixels
InputActioninstanceinitialized with values from XML

addBinding

Description
Add a Binding to this action.
Definition
addBinding()
Return Values
integerchangedAreachanged area pixels
integertotalAreatotal area pixels

removeBinding

Description
Remove a binding from this action.
Definition
removeBinding()

getBindings

Description
Get the bindings for this action.
Definition
getBindings()
Return Values
integerchangedAreachanged area pixels
integertotalAreatotal area pixels

clearBindings

Description
Clear this action's bindings.
Definition
clearBindings()

setPrimaryKeyboardBinding

Description
Let this action know which binding is its primary keyboard binding.
Stores the input axes as a concatenated string for comparisons.
Definition
setPrimaryKeyboardBinding(Binding Binding)
Arguments
BindingBindinginstance which is the primary keyboard binding for this action
Return Values
integernumChangedPixelsnumber of changed pixels

isFullAxis

Description
Determine if this action represents a logical full axis.
Definition
isFullAxis()
Return Values
tablecolortire track color

getIgnoreComboMask

Description
Determine if bindings of this action should trigger any associated events if the bindings are not combos but a combo
button is currently pressed.
Definition
getIgnoreComboMask()
Return Values
stringencodedStringthe encoded string

clone

Description
Create a new InputAction instance with the same state as this instance.
Definition
clone()
Return Values
stringdecodedStringthe decoded string
ClonedInputActioninstance

toString

Description
Get a string representation for this InputAction.
Definition
toString()
Return Values
tablecopythe copied table

InputBinding

Description
Input binding manager.
-- Loads and saves action input bindings and provides action trigger information.
-- Methods of note (see the documentation of the actual methods for more detailed descriptions):
registerActionEvent() Register an event callback for an action (for action values, see InputAction.lua)
removeActionEvent() Removes a previously registered event. Also see removeActionEventsByTarget().
setActionEvent...() Group of methods to adjust event states, e.g. activity or input display hint parameters.
-- Input event usage scenarios:
1. Long lifetime components / much interaction: Register event at creation of a component, modify event in component
update method depending on its state, remove event at component destruction
2. Short lifetime components / little interaction: Register event when necessary (e.g. when in range of an object),
remove again when no interaction is possible anymore
-- Player input settings are loaded from the file "inputBindings.xml" in their profile directory. If the file is not
present or corrupted whenever input is loaded, it will be restored from a suitable template. If a binding of a locked
action is changed directly on the file system, it will be overwritten with its template counterpart on the next
loading call to ensure that critical inputs are always available (e.g. menu navigation).
--@category Input

new

Description
Create the InputBinding instance.
Definition
new(table logManager, table modManager, table messageCenter, bool isConsoleVersion)
Arguments
tablelogManagerLogManager reference
tablemodManagerModManager reference
tablemessageCenterMessageCenter reference
boolisConsoleVersionIf true, the game is running on console
Return Values
tablecopythe copied table
tableInputBindinginstance

load

Description
Load the input binding configuration.
Definition
load(bool isInitializing, bool forceDefaultBindings)
Arguments
boolisInitializing[optional, default=false] If true, loads the input bindings in initialization mode and
saves at the end of loading to store any resolved device IDs to the user settings.
boolforceDefaultBindings[optional, default=false] If true, will forcibly load default bindings and override
any user input settings.
Return Values
booleanisElementOfListtrue if element is part of the list, else false

loadDefaultBindings

Description
Load default input bindings.
Will apply defaults for newly connected devices or override all bindings with template defaults if requested.
Definition
loadDefaultBindings(bool forceReplace)
Arguments
boolforceReplace[optional, default=false] If true, will overwrite all user bindings with the default templates.
Return Values
integerindexindex of first occurrence

loadModActions

Description
Load actions defined by mods.
Definition
loadModActions()
Return Values
booleanareEqualtrue if lists are equal, else false

loadModBindingDefaults

Description
Load default mod input binding data.
Definition
loadModBindingDefaults()
Return Values
anyvaluevalue of the random element

assignPlatformBindingPaths

Description
Assign bindings configuration file paths depending on platform and devices.
Definition
assignPlatformBindingPaths()
Return Values
tablesetthe converted set

overwriteSettingsWithDefault

Description
Overwrites user input settings with the default template.
Definition
overwriteSettingsWithDefault(forceOverwrite If)
Arguments
forceOverwriteIftrue, will overwrite an existing settings file. If false, will only perform the operation if no user settings are present.
Return Values
tablelistthe converted list

restoreInputContexts

Description
Restore input contexts after reloading the input settings, e.g. when devices change.
Definition
restoreInputContexts()
Return Values
tablehashthe converted hash

setShowMouseCursor

Description
Set the visibility state of the mouse cursor.
Definition
setShowMouseCursor(bool doShow, bool saveCursorPosition)
Arguments
booldoShowIf true, the cursor will be shown. Otherwise, it will be hidden.
boolsaveCursorPosition[optional] If true, saves the current cursor position to restore when showing it again
Return Values
booleanareEqualtrue if sets are equal, else false

getShowMouseCursor

Description
Determine if the mouse cursor is currently being shown.
Definition
getShowMouseCursor()
Return Values
booleanisSubsettrue if set1 is a subset of set2

getInputHelpMode

Description
Get the current input help mode for the input hint display.
If the input help mode has been set to automatic, the last button or key input will determine which device scheme
is used.
Definition
getInputHelpMode()
Return Values
booleanisSubsettrue if set1 is a real subset of set2
GS_INPUT_HELP_MODE_KEYBOARDorGS_INPUT_HELP_MODE_GAMEPAD

getLastInputMode

Description
Get the current input mode, independent of input help mode settings.
Definition
getLastInputMode()
Return Values
booleanhasIntersectiontrue if set1 and set2 have an intersection
GS_INPUT_HELP_MODE_KEYBOARDorGS_INPUT_HELP_MODE_GAMEPAD

validateActionEventParameters

Description
Validate parameters for registerActionEvent().
Prints warnings if there are problems and returns the validation status.
Definition
validateActionEventParameters()
Return Values
tableintersectionthe intersection of both sets
Trueifthe parameters are valid, false otherwise.

registerActionEvent

Description
Register an event callback for an input action.
Use InputAction constants for action names. At least one of the trigger parameters must be set to true to receive
events. This methods also checks if there would be any input binding collision when an event is added for the given
action. If there are any collisions, the registration will fail.
-- Note the interaction of the "down" and "always" triggers: If "down" is set and not "always", only an input down-flank
will raise an event. If both "down" and "always" are set, an event is raised as long as the input is pressed beyond a
threshold. If only "always" and not "down" is set, an event will be raised on each frame with the current input value
even if no input is active.
-- @param string actionName Name of action, see InputAction
Definition
registerActionEvent(table targetObject, function eventCallback, bool triggerUp, bool triggerDown, bool triggerAlways, bool startActive, table callbackState)
Arguments
tabletargetObjectEvent target, first argument to event callback
functioneventCallbackEvent callback, called when the action has input. Signature: callback(targetObject, actionName, inputValue, callbackState)
booltriggerUpIf true, the event fires once when an input signal of the given action goes to "up" state, e.g. a released key.
booltriggerDownIf true, the event fires once when an input signal of the given action goes to "down" state, e.g. a pressed key.
booltriggerAlwaysIf true, the event fires on any signal input change, potentially every frame. This is mostly useful for required continuous axis input, e.g. steering actions.
boolstartActive[optional] If true, the event is active right after registration and will be checked for input collisions. Otherwise, set its activation state using InputBinding:setActionEventActive() and handle collisions yourself.
tablecallbackState[optional] An arbitrary value or reference which serves as a closure state within callbacks, useful e.g. when checking input state between events without requiring additional class fields.
Return Values
tablesubstractionthe substraction of both set
boolTrueif the event could be registered, false otherwise
stringeventID if successful, empty string otherwise
tableActionreference of a colliding action if there would be a collision, nil otherwise

checkEventCollision

Description
Check if adding an event for a given action name would cause colliding input bindings to be active.
Definition
checkEventCollision(string actionName)
Arguments
stringactionNameName of an InputAction
Return Values
tableunionthe union of both sets
boolTrueif there would be a collision, false otherwise
tableCollidingaction if there would be a collision, nil otherwise

beginActionEventsModification

Description
Start registering action events in a given context.
This method must be accompanied by a finalizing call to InputBinding:endActionEventsModification() when registration is
complete. While a registration context is set, all calls to InputBinding:registerActionEvent() will add events to
that context. Also, derived event collections (i.e. data structures for display and fast iteration) will only be
updated when InputBinding:endActionEventsModification() is called instead of each time an event is added.
If no context with the given name exists, a new empty one will be created and added to the known contexts.
Definition
beginActionEventsModification(string inContext, bool createNew)
Arguments
stringinContextName of the input context which receives any registered events until endActionEventsModification is called.
boolcreateNew[optional, default=false] If true, will create a new context of the given name, potentially overwriting any existing one.
Return Values
tablefilteredlist (non-deep copy)

endActionEventsModification

Description
End registering action events in a context.
Resets the registration context set in InputBinding:beginActionEventsModification() for any later registrations.
Definition
endActionEventsModification()
Return Values
tablefilteredlist (non-deep copy)

refreshEventCollections

Description
Refresh derived event collections for retrieval purposes.
Definition
refreshEventCollections()
Return Values
integersignthe sign of the value

storeDisplayActionEvents

Description
Store an array of action-event tuples for all action events which need an input hint display.
Definition
storeDisplayActionEvents()
Return Values
booleantrueif value is nan else false

storeEventBindings

Description
Store all bindings associated with registered and active events in collections for iteration.
Definition
storeEventBindings()
Return Values
numberrountedvalue

iterateEvents

Description
Iterates the action event collection, calling a given function on each event.
If the processing function returns a "truthy" value, the iteration is stopped.
Definition
iterateEvents(processingFunction function(event,)
Arguments
processingFunctionfunction(event,actionName, actionEventList, actionEventListIndex)
Return Values
floatvalueradian angle

removeEventInternal

Description
Internal function for event removal.
Definition
removeEventInternal()
Return Values
floatvalueinterpolated value

removeActionEvent

Description
Remove a previously registered action event by ID.
Definition
removeActionEvent(eventId Event)
Arguments
eventIdEventID as returned by registerActionEvent().
Return Values
floatvalueinterpolated value

removeActionEventsByActionName

Description
Remove all previously registered action events which are triggered by an action identified by name.
Definition
removeActionEventsByActionName(actionName If)
Arguments
actionNameIfan event is triggered by the action of that name, it is removed.
Return Values
floatalphaalpha

removeActionEventsByTarget

Description
Remove all previously registered action events which have a given target.
Definition
removeActionEventsByTarget(targetObject If)
Arguments
targetObjectIfan event has this object as a target, it is removed.
Return Values
floatvaluevalue

getDisplayActionEvents

Description
Get action-event tuples for registered events which require an input hint.
Note that the data is live and should be treated as read-only.
Definition
getDisplayActionEvents()
Return Values
floatisOutOfBoundsis out of bounds
arrayoftuples: {i={action=InputAction, event=InputEvent}}

setActionEventText

Description
Set a specific action text to display as an input hint for a given event.
Use this to adjust display texts depending on context, e.g. "Attach" / "Detach" for the vehicle attach action.
Additionally, it serves as a way to display neutral full axis action names, e.g. "Move player" instead of any
specific label depending on the input direction.
Definition
setActionEventText(eventId ID, actionText Localized)
Arguments
eventIdIDof a registered event
actionTextLocalizeddisplay text for the event's action
Return Values
floatvaluethe floored percent value

setActionEventIcon

Description
Set the name of an icon to display as an input hint instead of text for a given event.
If an icon has been specified for an event with this function, any text setting will have no effect.
Definition
setActionEventIcon(eventId ID, iconName Input)
Arguments
eventIdIDof a registered event
iconNameInputhint icon name as defined in axisIcons.xml or InputHelpElement.AXIS_ICON
Return Values
floatvaluethe floored clamped value

setActionEventTextVisibility

Description
Set the visibility of an action event input hint display.
The most basic controls, such as player movement, do not need any input hints and can be hidden this way. If more
than one event is registered on an action, make sure to only set one of them to visible. The system will
automatically set all events after the first per action to invisible to ensure a valid ground state.
Definition
setActionEventTextVisibility(eventId ID, isVisible If)
Arguments
eventIdIDof a registered event
isVisibleIffalse, hides the input hint for this event. Default is visible.
Return Values
floatanglethe resized angle in the range -pi to pi

setActionEventTextPriority

Description
Set the priority of an action event input hint display.
Use any of the following script constants: GS_PRIO_VERY_HIGH, GS_PRIO_HIGH, GS_PRIO_NORMAL, GS_PRIO_LOW,
GS_PRIO_VERY_LOW. Higher priority will be shown first in the input hint display box.
Definition
setActionEventTextPriority(eventId ID, priority Priority)
Arguments
eventIdIDof a registered event
priorityPrioritynumber value, lower is more important. Use GS_PRIO_[...] constants.
Return Values
floatanglethe radian difference in range -pi to pi

setActionEventActive

Description
Set the active state of an action event.
Only active events can be triggered by input and be displayed as input hints.
Definition
setActionEventActive(eventId ID, isActive New)
Arguments
eventIdIDof a registered event
isActiveNewactive state
Return Values
floatlengthlength

setActionEventsActiveByTarget

Description
Set the active state of all action events targeting a given object.
Only active events can be triggered by input and be displayed as input hints.
Definition
setActionEventsActiveByTarget(targetObject Action, isActive New)
Arguments
targetObjectActionevent target object
isActiveNewactive state
Return Values
floatlengthsquare length

getComboCommandPressedMask

Description
Get the combo input masks for any currently active gamepad and mouse combo inputs.
The returned masks are bit-wise combined masks made from the InputBinding.COMBO_MASK_[...] constants.
Definition
getComboCommandPressedMask()
Return Values
floatxnormalized x
floatynormalized y
Gamepadcombomask, Mouse combo mask

getComboActionNameForAxisSet

Description
Get the combo action name for a given set of modifier axes.
Definition
getComboActionNameForAxisSet()

getInternalIdByDeviceId

Description
Resolve a device ID sting to the engine-internal integer ID.
Definition
getInternalIdByDeviceId()
Return Values
floatlengthlength

getDeviceByInternalId

Description
Retrieve an InputDevice by its internal device ID.
Definition
getDeviceByInternalId(internalDeviceId Internally)
Arguments
internalDeviceIdInternallyassigned device ID (= device index assigned by engine, zero based)
Return Values
floatlengthsquare length
InputDeviceinstanceor nil if ID is invalid

assignLastInputHelpMode

Description
Assign an input help mode as the last used mode.
This triggers a message center notification to all subscribed components if the input help mode has changed.
Definition
assignLastInputHelpMode()
Return Values
floatxnormalized x
floatynormalized y
floatznormalized z

startBindingChanges

Description
Prepare for incoming binding changes.
Must be called before InputBinding:startInputCapture() to guarantee a valid state.
Definition
startBindingChanges()

commitBindingChanges

Description
Commit all binding changes since the last call to InputBinding:startBindingChanges().
Accepts the current, modified binding state and notifies any change listeners.
Definition
commitBindingChanges()

rollbackBindingChanges

Description
Rolls back all binding changes since the last calls to InputBinding:startBindingChanges().
Definition
rollbackBindingChanges()
Return Values
floatxscaled x
floatyscaled y
floatzscaled z

startInputCapture

Description
Capture all input and run a callback if input has been received on a device.
Overrides the global input event functions.
Definition
startInputCapture(isKeyboard True, isMouse True, callbackTarget If, callbackState Free, inputCallback Called, abortCallback Called, deleteCallback Called)
Arguments
isKeyboardTrueif target device is keyboard input
isMouseTrueif target device is mouse input
callbackTargetIfspecified, will be supplied as the first argument to the callback function (usually caller self)
callbackStateFreeparameter which is returned with callbacks to the callback target
inputCallbackCalledwhen the target device receives input. function(deviceId, inputAxisName, isModifier, inputValue, callbackState)
abortCallbackCalledwhen an abort input is received on any device. function()
deleteCallbackCalledwhen a delete input is received on any device. function(callbackState)

captureKeyboardInput

Description
Capture keyboard input.
Fires an input callback as soon as a key is pressed. Modifier keys (e.g. shift, alt) only trigger callbacks when
they are pressed alongside a regular key. Modifier callbacks always arrive before non-modifier key callbacks.
Definition
captureKeyboardInput(abortCallback function(), deleteCallback function(), inputCallback function(deviceId,)
Arguments
abortCallbackfunction()to be called when the abort key is pressed
deleteCallbackfunction()to be called when the delete key is pressed
inputCallbackfunction(deviceId,axisName, isModifier, inputValue), see startInputCapture()

captureMouseInput

Description
Capture mouse input.
Axis input continuously fires callbacks while the player is moving the mouse. Button callbacks are triggered once
when a mouse button is held down and again when it is released.
Definition
captureMouseInput(callback function(deviceId,)
Arguments
callbackfunction(deviceId,axisName, isModifier, inputValue), see startInputCapture()
Return Values
floatxclamped x
floatyclamped y
floatzclamped z

captureGamepadInput

Description
Capture gamepad / controller input.
Continously fires callbacks for all known gamepad buttons and axes for each frame.
Definition
captureGamepadInput(callback function(deviceId,)
Arguments
callbackfunction(deviceId,axisName, isModifier, inputValue), see startInputCapture()

stopInputGathering

Description
Stop the current input gathering run.
Restores global input event functions.
Definition
stopInputGathering()

restoreDefaultBindings

Description
Restore default bindings
Definition
restoreDefaultBindings()
Return Values
floatxinterpolated x
floatyinterpolated y
floatzinterpolated z

clearState

Description
Clear relevant state for loading and resetting.
Definition
clearState()

loadActions

Description
Load input actions which are later bound to input axes.
Definition
loadActions(xmlFile Action, modName [optional])
Arguments
xmlFileActiondefinition XML file handle
modName[optional]Name of the mod which defines actions. If not set, actions are assumed to be default game actions.

resetDeviceInformation

Description
Reset stored device information.
Clears all device information and returns the previous device list for comparisons. Call this for
initialization and before enumerating system devices.
Definition
resetDeviceInformation()
Return Values
floatxinterpolated x
floatyinterpolated y
floatzinterpolated z
previousDevicesTableof internal ID -> InputDevice before the current initialization

createDefaultDevices

Description
(Re-)Creates the internal keyboard and mouse virtual device.
Definition
createDefaultDevices()

enumerateGamepadDevices

Description
Find gamepad devices in the system and store their information.
Definition
enumerateGamepadDevices(previousDevices Table)
Arguments
previousDevicesTableof internal ID -> InputDevice before the current initialization

getGamepadDevices

Description
Get a list of recognized gamepad (and other controller) input devices.
Definition
getGamepadDevices()
Return Values
floatxtransformed x
floatytransformed y
floatztransformed z
Listofdevice information tables, format: {deviceId=[device ID], name=[device name]}

loadDeviceSettingsFromXML

Description
Load device input settings (other than bindings) from an input binding XML file.
Definition
loadDeviceSettingsFromXML(xmlFile XML)
Arguments
xmlFileXMLfile handle

applyGamepadDeadzones

Description
Apply deadzone settings to all gamepad device axes.
If no deadzone value had been configured for a valid axis, the global default deadzone value is applied.
Definition
applyGamepadDeadzones()

initializeGamepadMapping

Description
Initialize gamepad settings from XML.
Definition
initializeGamepadMapping()
Return Values
dotthedot product

validateAndRepairComboActionBindings

Description
Check if combo action bindings are valid and restore proper bindings if necessary.
Definition
validateAndRepairComboActionBindings()
Return Values
floatxx
floatyy
floatzz

loadActionBindingsFromXML

Description
Load bindings of actions to input axes from a configuration XML file.
Definition
loadActionBindingsFromXML(xmlFile Configuration, silentIgnoreDuplicates [optional], modName [optional], doNotReplace [optional])
Arguments
xmlFileConfigurationXML file handle
silentIgnoreDuplicates[optional]If true, will not give a warning on duplicate bindings and just ignore them
modName[optional]Name of the mod for which action bindings are loaded. If not set, will load bindings for the default game.
doNotReplace[optional]If true, will not replace existing bindings with a loaded ones

loadBindingsFromXML

Description
Load all bindings within an XML actionBindings definition element.
Definition
loadBindingsFromXML()

storeComboInputMappings

Description
Store input axis names of combo command actions for combo mask checking.
Definition
storeComboInputMappings()
Return Values
floatyrotation

getBindingComboMask

Description
Get a combo modifier mask for a binding.
Because input axis names are different, this is safe to use for any binding as long as the calling context sticks
to either gamepad or mouse input bindings to check.
Definition
getBindingComboMask(Binding Binding)
Arguments
BindingBindinginstance
Return Values
floatxx direction
floatzz direction
Modifierbitmask

assignComboMasks

Description
Assign combination input bitmasks on actions based on their bindings.
This will update all actions and should be run whenever any binding changes. Axis inputs will have two valid bindings
for modifiers (component + and -). Ensure that players cannot set differently modified inputs on a single axis
action.
Definition
assignComboMasks()

storeLinkedBindings

Description
Store binding links based on connections set in InputAction.LINKED_ACTIONS.
Definition
storeLinkedBindings()
Return Values
floatxlimited x direction
floatzlimited z direction

assignActionPrimaryBindings

Description
Assign primary keyboard bindings to actions if applicable.
Definition
assignActionPrimaryBindings()

adjustBindingSlotIndex

Description
Adjust a binding's slot index.
Definition
adjustBindingSlotIndex(Binding Binding, usedSlots Set)
Arguments
BindingBindingto adjust
usedSlotsSetof used slot indices for the binding's context (action, device, axis)
Return Values
floatxx position
floatxz position

resolveBindingDevice

Description
Resolve a binding's device ID to an engine-issued internal device ID.
Replaces default device IDs in bindings with the ID of the first device of the corresponding category. This
effectively binds default or template bindings to first devices. Also updates the binding's internal device ID field.
If a binding's device is missing, the method tries resolving a suitable replacement device. First, device IDs are
checked to see if the missing device simply changed order (and therefore its prefix). Then, the device names are
compared. If no identifiers match, the binding is assigned to the first device of the category of the missing device.
If all else fails, the binding is assigned to the first controller, possibly losing some bindings due to collisions.
Definition
resolveBindingDevice(Binding Binding)
Arguments
BindingBindingwhose device ID is checked and replaced, if necessary
Return Values
Trueifthe binding's device ID could be resolved, false otherwise

resolveFirstDeviceOfCategoryToBinding

Description
Resolve and assign the first device of a given category to a binding.
Definition
resolveFirstDeviceOfCategoryToBinding()
Return Values
floatdotproduct

resolveSameIdDeviceWithPrefixToBinding

Description
Resolve and assign the last device with a given base ID (without prefix) to a binding.
Definition
resolveSameIdDeviceWithPrefixToBinding()
Return Values
floatxx part of quaternion
floatyy part of quaternion
floatzz part of quaternion
floatww part of quaternion

resolveMissingDeviceByNameToBinding

Description
Resolve and assign the last device with a given name to a binding.
Definition
resolveMissingDeviceByNameToBinding()

resolveDefaultDeviceToBinding

Description
Resolve and assign the first known device to a binding.
Definition
resolveDefaultDeviceToBinding()

checkBindings

Description
Run a a list of functions on all known bindings in the context of a given action if provided.
The functions' return values are written to a results table which is returned at the end. Callers can retrieve
function results by indexing the results table with the corresponding function reference.
Definition
checkBindings(action Action, checkFunctions List)
Arguments
actionActionreference for the current context, e.g. check bindings for an action
checkFunctionsListof functions with the signature function(Binding), return [bool hasResult], result
Return Values
functionresultstable {checkFunctionRef=[functionResult]}

validateBinding

Description
Validate a new binding before it's added to the system.
Returns boolean flags for constraints and a colliding binding if there was one.
Definition
validateBinding(Binding New)
Arguments
BindingNewbinding instance
Return Values
floatxx part of quaternion
floatyy part of quaternion
floatzz part of quaternion
floatww part of quaternion

addBinding

Description
Add a new input binding.
Checks for duplicates and collisions and stores the binding only if everything's okay.
Definition
addBinding(table binding, bool silentIgnoreDuplicates, bool doNotReplace)
Arguments
tablebindingNew binding
boolsilentIgnoreDuplicatesIf true, will not print warnings on duplicate bindings
booldoNotReplaceIf true, will not replace existing bindings
Return Values
boolTrueif the new binding could be added
tableReferenceto an Action containing a binding which collided with the added binding or nil

updateBinding

Description
Update an existing binding with new device ID, input axes and input component data.
Definition
updateBinding(findDeviceId Binding, findActionName Name, findBindingIndex Binding, findAxisComponent Logical, deviceId New, axisNames List, inputComponent Physical)
Arguments
findDeviceIdBindingdevice ID
findActionNameNameof binding action
findBindingIndexBindingindex, 1 primary, 2 secondary, etc.
findAxisComponentLogicalbinding axis direction component to assign, always positive for buttons/keys/half-axes
deviceIdNewdevice ID
axisNamesListof new input axis names
inputComponentPhysicalinput axis direction component to bind (direction of last axis in axisNames)
Return Values
Trueifa binding could be found and updated, false if there was a collision
BindingandAction reference of a collision as {collisionBinding=Binding, collisionAction=Action} or nil

deleteBinding

Description
Delete a binding.
Definition
deleteBinding(findDeviceId Binding, findActionName Name, findBindingIndex Binding, findAxisComponent Logical)
Arguments
findDeviceIdBindingdevice ID
findActionNameNameof binding action
findBindingIndexBindingindex, 1 primary, 2 secondary, etc.
findAxisComponentLogicalbinding axis direction component to assign, always positive for buttons/keys/half-axes

getKeyboardMouseInputActiveAndValue

Description
Check if a keyboard or mouse input is active.
Definition
getKeyboardMouseInputActiveAndValue(axes List, axisDirection 1, inputDirection 1)
Arguments
axesListof input axis names which are all required to be pressed for the input to be active
axisDirection1or -1, determining the direction of the bound logical axis.
inputDirection1or -1, determining the direction of the requested physical axis component.
Return Values
floatxx part of quaternion
floatyy part of quaternion
floatzz part of quaternion
floatww part of quaternion
Trueifall given axes are currently active, input value of the non-modified axis (last in list)

getGamepadInputActiveAndValue

Description
Scan gamepad / controller binding input.
Both buttons and controller physical axes are checked for a given device and list of logical axes.
Definition
getGamepadInputActiveAndValue(internalDeviceId Engine-internal, axes List, axisDirection 1, inputDirection 1)
Arguments
internalDeviceIdEngine-internaldevice ID of device to scan
axesListof axis names to scan
axisDirection1or -1, determining the direction of the bound logical axis component.
inputDirection1or -1, determining the direction of the requested physical axis component.
Return Values
Trueifall axes are active (digital interpretation), input value of the non-modified axis (last in list)

getGamepadAxisValue

Description
Scan a controller axis on a device for input.
Definition
getGamepadAxisValue()
Return Values
Inputvalueof the axis in the range [-1, 1] for full axes or [0, 1] for half axes.

update

Description
Update input for the current frame.
Definition
update(dt Delta)
Arguments
dtDeltatime in milliseconds

checkGamepadActive

Description
Check if any gamepad button or axis is pressed and set the input help mode if necessary.
Definition
checkGamepadActive()
Return Values
floatrotationthe final rotation

updateMouseInput

Description
Update mouse input state.
Definition
updateMouseInput()
Return Values
floatxx part of quaternion
floatyy part of quaternion
floatzz part of quaternion
floatww part of quaternion

finalizeMouseInput

Description
Finalize mouse input processing for the current frame.
Wraps the mouse position around if required and resets movement accumulators.
Definition
finalizeMouseInput()

clearActiveBindingBuffer

Description
Clear an active binding buffer for re-use to avoid table allocation each frame.
Automatically adds device entries if new devices are added.
Definition
clearActiveBindingBuffer()

updateEventBindings

Description
Update input bindings associated with all registered and active events.
Definition
updateEventBindings()

hasBindingForPressedMouseComboMask

Description
Check if there is currently any binding matching the pressed mouse combo mask.
This is used to override the combo mask ignore flag for mouse look in special cases. E.g. when rotating a tool axis
with a mouse dragging movement, mouse look should be disabled for the other axis as well, even if it has no active
binding with the same combo button (which would have been handled by input shadowing).
Definition
hasBindingForPressedMouseComboMask()
Return Values
floatxx part of quaternion
floatyy part of quaternion
floatzz part of quaternion
floatww part of quaternion

shadowLinkedBindings

Description
Apply binding input shadow flag to bindings of linked actions for currently active input.
Definition
shadowLinkedBindings()

updateComboBindings

Description
Update binding input for combo action bindings.
Definition
updateComboBindings()

updateInput

Description
Update input bindings with the current input state and trigger events.
Definition
updateInput()

updateBindingInput

Description
Update the input state of a single action-to-input binding.
Definition
updateBindingInput()
Return Values
floatxx part of quaternion
floatyy part of quaternion
floatzz part of quaternion
floatww part of quaternion

resetContinuousEventBindings

Description
Reset binding input state for bindings used in continuous trigger events.
Definition
resetContinuousEventBindings(bool checkComboMasks, int gamepadComboMask, int gamepadMouseMask)
Arguments
boolcheckComboMasks[optional, default=false] If true, checks binding combo masks against provided parameters
intgamepadComboMask[optional] Gamepad combo input bit mask
intgamepadMouseMask[optional] Mouse combo input bit mask

neutralizeEventBindingInput

Description
Set an event's binding's input to a neutral value and notify the event's listeners of that neutral position.
Definition
neutralizeEventBindingInput()

updateDebugDisplay

Description
Update and debug information display.
Definition
updateDebugDisplay()

saveToXMLFile

Description
Save action bindings to player custom settings.
Definition
saveToXMLFile()
Return Values
floatdistancedistance to rectangle

saveDeviceSettings

Description
Save all device settings.
Updates and adds settings for active devices.
Definition
saveDeviceSettings(xmlFile Input)
Arguments
xmlFileInputsettings XML file handle
Return Values
floatdistancedistance to line segment

getActionList

Description
Get a deep copy of the action definitions list.
Definition
getActionList()
Return Values
booleanhasIntersectiontrue if both lines intersect
floatt1x position
floatt2z position

getActionByName

Description
Get a loaded InputAction by name.
Only use the returned action to assign references and do not change its state.
Definition
getActionByName(actionName Name)
Arguments
actionNameNameof the action to be returned
Return Values
InputAction

disableAlternateBindingsForAction

Description
Disable alternate bindings for a given action.
This setting is only valid in the current input context and will be overwritten the next time any input event is
changed.
Definition
disableAlternateBindingsForAction(string actionName)
Arguments
stringactionNameInputAction name

setContext

Description
Set the current input context.
If no context of the given name exists, it will be created.
Definition
setContext(string name, bool createNew, bool deletePrevious)
Arguments
stringnameInput context name
boolcreateNew[optional, default=false] If true, will create a clear context with the given name, overriding any other with the same name.
booldeletePrevious[optional, default=false] If true, will delete the previous context after setting the new context.
Return Values
booleanhasIntersectiontrue if the line segment is completly in the rectangle OR if it intersects with one of the four rectangle sides

revertContext

Description
Revert the input context to the previously set input context.
Use this method only if you can guarantee a valid state, e.g. when calling setContext in a modal interaction context.
Definition
revertContext(bool deleteCurrent)
Arguments
booldeleteCurrent[optional, default=false] If true, will delete the current input context before reverting to the previous context.
Return Values
floatpos1Xx pos of intersection 1, else nil
floatpos1Yy pos of intersection 1, else nil
floatpos2Xx pos of intersection 2, else nil
floatpos2Zz pos of intersection 2, else nil

setPreviousContext

Description
Set the previous context for another context.
This modifies the previous context value which is used to revert input contexts.
Definition
setPreviousContext(string forContextName, string previousContextName)
Arguments
stringforContextNameName of the input context whose previous context will be set
stringpreviousContextNameNew previous context name

clearAllContexts

Description
Clear all contexts except the root.
The current context will also be set to root.
Definition
clearAllContexts()

getContextName

Description
Get the name of the current input context.
Definition
getContextName()

getActionBindingsCopy

Description
Get an ordered copy of the action bindings table for manipulation.
Definition
getActionBindingsCopy(onlyAssignable If)
Arguments
onlyAssignableIftrue, will only copy assignable action bindings
Return Values
booleanhasIntersectiontrue if spheres have an intersection else false
Orderedactionbindings in the form of {i={action=InputAction, bindings={Binding}}}

getActionBindings

Description
Get the current action bindings table.
The returned table is the current live state and can thus contain unconfirmed modifications. Treat the table as
read-only so as not to interfere with the correct workings of this class. Only use this getter for initializations
and otherwise rely on setBindingChangeCallback() to receive a confirmed working state.
Definition
getActionBindings()
Return Values
floatareaarea in hectars

getEventsForActionName

Description
Get an array of registered events in the current input context for a given action name.
Definition
getEventsForActionName(string actionName)
Arguments
stringactionNameAction name as valid in InputAction
Return Values
floatbrightnessbrightness
tableArrayof events

getFirstActiveEventForActionName

Description
Get the first active event in the current input context for a given action name.
Definition
getFirstActiveEventForActionName(string actionName)
Arguments
stringactionNameAction name as valid in InputAction
Return Values
floataverageSpeedaverage speed
tableFirstactive event or InputEvent.NO_EVENT

setMouseMotionScale

Description
Set the mouse motion scale.
The given scale factor is multiplied with the default mouse motion scale of 0.75 on the X and Y axes.
Definition
setMouseMotionScale(scale Mouse)
Arguments
scaleMousemotion scale factor
Return Values
floatspeedspeed

getMouseMotionScale

Description
Get the current mouse motion scale.
Definition
getMouseMotionScale()
Return Values
floatspeedRandomspeed random
xmotionscale, Y motion scale

setBindingChangeCallback

Description
Set a callback for binding changes.
The callback function must accept the action bindings table as a single argument.
Definition
setBindingChangeCallback(callback Callback)
Arguments
callbackCallbackfunction which takes a single table parameter in the form of {InputAction: {i=Binding}}
Return Values
floatnormalSpeednormal speed

setEventChangeCallback

Description
Set a callback for event changes.
The callback function must accept the action-event tuples in an array as a single argument.
Definition
setEventChangeCallback(callback Callback)
Arguments
callbackCallbackfunction which takes a single table parameter in the form of {i={action=InputAction, event=InputEvent}}
Return Values
floattangentSpeedtangent speed

notifyBindingChanges

Description
Notify a listener of binding changes.
The notification callback is set via setBindingChangeCallback().
Definition
notifyBindingChanges()
Return Values
floatspriteScaleXX sprite scale

notifyEventChanges

Description
Notify a listener of event changes.
The notification callback is set via setEventChangeCallback().
Definition
notifyEventChanges()
Return Values
floatspriteScaleYY sprite scale

notifyInputModeChange

Description
Notify components of an input mode change via the message center.
Definition
notifyInputModeChange()
Return Values
floatspriteScaleXGainX sprite scale gain

checkSettingsIntegrity

Description
Check if user input bindings are corrupted and compare input configuration XML file versions.
Definition
checkSettingsIntegrity()
Return Values
floatspriteScaleYGainY sprite scale gain
Trueifthe user settings have passed the integrity check, false otherwise.

checkDefaultInputExclusiveActionBindings

Description
Checks loaded default input bindings according to exclusive locked action groups defined in InputAction.
This is a developer check to verify critical input plausibility.
Definition
checkDefaultInputExclusiveActionBindings()
Return Values
Trueifthere is a collision, false otherwise

getIsPhysicalFullAxis

Description
Determine if an axis name represents a physical full axis on any device.
Definition
getIsPhysicalFullAxis(inputAxisName Axis)
Arguments
inputAxisNameAxisname
Return Values
objectinstance or nil if no object could be created
Trueifno placeable object could be created at the requested position because there was no valid space, false otherwise
Trueifthe axis name represents a physical full axis, false otherwise

getIsHalfAxis

Description
Determine if an axis name represents a physical half-axis on any device.
Definition
getIsHalfAxis(inputAxisName Axis, True if)
Arguments
inputAxisNameAxisname
Trueifthe axis name represents a physical half-axis, false otherwise

getIsAnalogInput

Description
Determine if an input name represents an analog (i.e. continuous) physical input.
Definition
getIsAnalogInput(inputName Input)
Arguments
inputNameInputname (potentially a key, button or axis identifier)
Return Values
objectinstance or nil if no object could be created
Trueifno placeable object could be created at the requested position because there was no valid space, false otherwise
Trueifthe input name represents an analog input

getIsKeyboardInput

Description
Determine if an input name list represents keyboard input.
Definition
getIsKeyboardInput()

getIsMouseInput

Description
Determine if an input name list represents mouse input.
Definition
getIsMouseInput()
Return Values
floatRayorigin X position in world space
floatRayorigin Y position in world space
floatRayorigin Z position in world space
floatRaydirection X component
floatRaydirection Y component
floatRaydirection Z component

getIsMouseWheelInput

Description
Determine if an input name list represents a single mouse wheel step input.
Definition
getIsMouseWheelInput()

getIsGamepadInput

Description
Determine if an input name list represents gamepad / controller input.
Definition
getIsGamepadInput()

getIsDPadInput

Description
Check if an input name list represents a single D-Pad input.
Definition
getIsDPadInput()

isAxisZero

Description
Check if the input value of an axis can be considered zero.
Definition
isAxisZero(value Axis)
Arguments
valueAxisinput value
Return Values
Trueifthe axis is at zero position, false otherwise

getMaximumBindingCountForDeviceId

Description
Get the maximum number of bindings per action for a given device ID.
Definition
getMaximumBindingCountForDeviceId()

getDeviceCategory

Description
Get the device category for a device identified by its engine-internal ID
Definition
getDeviceCategory()
Return Values
any_typeunpackedValuesreturns unpacked values found in string

InputDevice

Description
Game input device.
-- The class stores name and IDs of a device as well as physical to logical key / button / axis mappings.
--@category Input
--@xmlConfig device#id Device ID, must match a value returned by engine function getGamepadId() or one of the constants
of InputDevice.DEFAULT_DEVICE_NAMES.

new

Description
Create a new InputDevice instance.
Definition
new(internalId Internal, deviceId Device, deviceName Device, category Device)
Arguments
internalIdInternaldevice ID as issued by the engine (~ device index)
deviceIdDeviceID as received by the operating system
deviceNameDevicename as assembled by the engine
categoryDevicecategory, use one of the values of InputDevice.CATEGORY
Return Values
tablevaluesvalues
NewInputDeviceinstance

loadSettingsFromXML

Description
Load device settings from an XML file.
This will load settings other than input bindings, e.g. sensitivity for gamepad axes.
Definition
loadSettingsFromXML(xmlFile XML, deviceElement XML)
Arguments
xmlFileXMLfile handle
deviceElementXMLdata element for this device
Return Values
tablevaluesradian values

saveSettingsToXML

Description
Save device settings to an XML file.
Definition
saveSettingsToXML(xmlFile XML, deviceElement XML)
Arguments
xmlFileXMLfile handle
deviceElementXMLdata element for this device
Return Values
tableresulttext elements

isController

Description
Determine if this device is a controller/gamepad.
Definition
isController()
Return Values
booleanstartsWidthtrue if given string starts with pattern else false

loadIdFromXML

Description
Load a device's ID from an XML file.
Definition
loadIdFromXML(xmlFile XML, deviceElement XML)
Arguments
xmlFileXMLfile handle
deviceElementXMLdata element for this device
Return Values
booleanstartsWidthtrue if given string ends with pattern else false
DeviceIDor empty string

loadNameFromXML

Description
Load a device's name from an XML file.
Definition
loadNameFromXML(xmlFile XML, deviceElement XML)
Arguments
xmlFileXMLfile handle
deviceElementXMLdata element for this device
Return Values
stringtrimedStringtrimed text
Devicenameor empty string

loadCategoryFromXML

Description
Load a device's category from an XML file.
Definition
loadCategoryFromXML(xmlFile XML, deviceElement XML, Device category)
Arguments
xmlFileXMLfile handle
deviceElementXMLdata element for this device
Devicecategory
Return Values
any_typevaluenot nil value

getDeviceIdPrefix

Description
Get a device ID prefix' numeric value, if it exists.
Definition
getDeviceIdPrefix()
Return Values
floatlxx direction
floatlzz direction
Prefixnumber,or -1 if none exists; raw engine-issued device ID

getPrefixedDeviceId

Description
Get a device ID prefixed with a given number.
Definition
getPrefixedDeviceId()

toString

Description
Get a string representation for this device.
Definition
toString()
Return Values
floatlxaverage x direction
floatlzaverage z direction

InputDisplayManager

Description
Bridge-component between input handling and UI.
-- Serves data and display elements for input controls. Accesses InputBinding data and is being accessed by UI
components.
--@category Input

load

Description
Load the required base data for this manager.
Loads controller symbols / UI overlays.
Definition
load()

setDevGamepadLabelMapping

Description
Set up development-only gamepad label function if necessary.
Definition
setDevGamepadLabelMapping()
Return Values
booleanisAttachedis attached

loadControllerSymbolsAndOverlays

Description
Load controller symbols and create UI overlays.
Reads a UV values from an XML configuration to create UI overlays from a texture atlas.
Definition
loadControllerSymbolsAndOverlays()
Return Values
booleandoesBlockimplement does block

createButtonOverlay

Description
Create a single button overlay.
Definition
createButtonOverlay()
Return Values
integeraiToolReverserDirectionNodereverser direction node of ai tool

loadAxisIcons

Description
Load vehicle axis input hint icons.
The icons are kept in memory as overlays until the game is closed.
Definition
loadAxisIcons(xmlFile XML, modPath [optional])
Arguments
xmlFileXMLfile handle
modPath[optional]Path to loaded mod, will load defaults if set to nil
Return Values
floatmaxTurnRadiusmax turn radius

loadModAxisIcons

Description
Load axis icons defined by mods.
Definition
loadModAxisIcons()
Return Values
floatleftAreaPercentageleft area percentage
floatrightAreaPercentageright area percentage

addContextBindings

Description
Add bindings of an action to a list if they fit the required context (gamepad or keyboard and mouse),
Definition
addContextBindings(contextBindings Bindings, action InputAction, isContextGamepad If)
Arguments
contextBindingsBindingslist for the required context
actionInputActionreference
isContextGamepadIftrue, we require gamepad bindings. Otherwise, keyboard and mouse is needed.

getActionBindingsForContext

Description
Get bindings from one or two actions for the current input context (either gamepad or keyboard and mouse).
Definition
getActionBindingsForContext()
Return Values
floatareaarea found
floattotalAreatotal area checked

getKeyboardBindings

Description
Get bindings for one or two actions for keyboard input, exclusively.
Definition
getKeyboardBindings()

resolveModifierSymbols

Description
Resolve modifier symbols and add them to an overlays collection.
Definition
resolveModifierSymbols(table overlays, table separators, table firstContextBinding)
Arguments
tableoverlaysOverlays collection which receives resolved modifier symbols
tableseparatorsArray of separator types inbetween symbols
tablefirstContextBindingBinding reference
Return Values
floatareaarea found
floattotalAreatotal area checked

resolveAccumulatedSymbolPermutations

Description
Recursively permutate symbol names to resolve dynamically ordered names to fixed definitions.
Definition
resolveAccumulatedSymbolPermutations()

resolveUnmodifiedSymbols

Description
Resolve unmodified binding axis names to symbol overlays and add those to the given overlays collection.
Definition
resolveUnmodifiedSymbols(table overlays, table contextBindings, bool isContextGamepad)
Arguments
tableoverlaysOverlays collection which receives resolved symbols
tablecontextBindingsArray of Binding instances
boolisContextGamepadIf true, resolve gamepad symbols. Otherwise, resolve mouse symbols.
Return Values
floatareaarea found
floattotalAreatotal area checked

addRegularSymbols

Description
Add regular input display symbols to an overlays array.
Definition
addRegularSymbols()

addComboSymbols

Description
Add combo input display symbols to an overlays array.
Definition
addComboSymbols()
Return Values
tableinstanceinstance of object

getControllerSymbolOverlays

Description
Get input symbol overlays for one or two actions.
Use the second action parameter to display complementary actions, e.g. action1 is moving forward/backward, action 2
is moving left/right.
Definition
getControllerSymbolOverlays(actionName1 First, actionName2 [optional])
Arguments
actionName1Firstaction name as defined and/or loaded in InputAction
actionName2[optional]Second action name as defined and/or loaded in InputAction
Return Values
integernumOfConfigurationTypesnumber of configuration types
InputHelpElementinstancecontaining the symbol overlays in its "buttons" field

requireSymbolAccumulation

Description
Determine if an action and bindings combinations requires their input symbols to be accumulated to get a combined
symbol for better display.
Definition
requireSymbolAccumulation()
Return Values
integernumOfConfigurationTypesnumber of configuration types

makeHelpElement

Description
Make a help element to display in the HUD.
Definition
makeHelpElement()
Return Values
stringnamename of config

onActionEventsChanged

Description
Called when action events in the input system have changed.
Definition
onActionEventsChanged(displayActionEvents Array)
Arguments
displayActionEventsArrayof action-event tuples which require an input hint display, {i={action=InputAction, event=InputEvent}}
Return Values
integerindexindex of config

sortEventHelpElements

Description
Table sorting function for event help elements.
Priority > primaryKeyboardInput > text
Definition
sortEventHelpElements()
Return Values
tableconfigurationconfiguration

sortEventHelpElementsGamepad

Description
Sorting function for gamepad mode
Definition
sortEventHelpElementsGamepad()
Return Values
any_typevaluevalue of attribute

storeEventHelpElements

Description
Store display help elements for currently active action events.
Definition
storeEventHelpElements()
Return Values
booleanconfigurationHasBeenBoughtconfiguration has been bought

storeComboHelpElements

Description
Store combo button help elements for any modifier buttons required by currently active action events.
Definition
storeComboHelpElements()
Return Values
tablecolorcolor (r, g, b)

getEventHelpElementForAction

Description
Get the input help element for a given action.
Definition
getEventHelpElementForAction(inputActionName Name)
Arguments
inputActionNameNameof the requested input action.
Return Values
integermaterialmaterial

getEventHelpElements

Description
Get input help elements for the current input context.
Definition
getEventHelpElements(pressedComboMask Bit, isContextGamepad If)
Arguments
pressedComboMaskBitmask of the currently pressed combo button input
isContextGamepadIftrue, the player should be shown input hints for gamepad input. Otherwise, keyboard / mouse input help is required.
Return Values
any_typevaluevalue of config
arrayofhelp elements (see InputDisplayManager:makeHelpElement() for structure)

getComboHelpElements

Description
Get input help elements for currently available combo buttons.
Definition
getComboHelpElements(isContextGamepad If)
Arguments
isContextGamepadIftrue, the player should be shown input hints for gamepad input. Otherwise, keyboard / mouse input help is required.
Return Values
stringconfigKeykey of configuration
integerconfigIndexindex of configuration
Hashtableof currently active combo button action names, {action name=true}

getPrefix

Description
Get the controller symbol prefix for a device identified by its internal ID.
Definition
getPrefix()

getPlusOverlay

Description
Get the "plus" sign overlay.
This overlay is (re-)used in several places. Take care not to invalidate its state between uses.
Definition
getPlusOverlay()
Return Values
tablecolorcolor (r, g, b)

getOrOverlay

Description
Get the "or" sign overlay.
This overlay is (re-)used in several places. Take care not to invalidate its state between uses.
Definition
getOrOverlay()
Return Values
tableinstanceinstance of object

getKeyboardKeyOverlay

Description
Get the keyboard key glyph overlay (ButtonOverlay instance).
This overlay is (re-)used in several places. Take care not to invalidate its state between uses.
Definition
getKeyboardKeyOverlay()
Return Values
booleantrueif loading was successful else false

getFirstBindingAxisAndDeviceForActionName

Description
Get the first input axis name of the first binding of an input action identified by name.
Definition
getFirstBindingAxisAndDeviceForActionName(inputActionName Name, axisComponent [optional,, isGamepad [optional,)
Arguments
inputActionNameNameof an action as defined in InputAction
axisComponent[optional,default=POSITIVE] Binding.AXIS_COMPONENT value
isGamepad[optional,default=false] If true, return the first gamepad binding. Otherwise, keyboard is requested.
Return Values
booleansuccesstrue if added else false
Axisnameor nil if not found, internal ID of binding device

getGamepadInputActionOverlay

Description
Get an input action glyph overlay for the first gamepad button of the first binding of a given input action.
The method is simplified by design to mainly provide menu button glyphs. It will only return an overlay for the
first input axis, i.e. a simple button binding without modifiers. The returned overlay is a new instance and callers
need to delete it after use via GuiOverlay.deleteOverlay().
Definition
getGamepadInputActionOverlay(inputActionName Name, axisComponent [optional,)
Arguments
inputActionNameNameof an action as defined in InputAction
axisComponent[optional,default=POSITIVE] Binding.AXIS_COMPONENT value
Return Values
booleanhasPrerequisitetrue if all prerequisite specializations are loaded
Overlayinstanceor nil if no overlay is available for the action's bindings

getKeyboardInputActionKey

Description
Get an input action key text for the key of the first binding of a given input action.
Definition
getKeyboardInputActionKey(inputActionName Name, axisComponent [optional,)
Arguments
inputActionNameNameof an action as defined in InputAction
axisComponent[optional,default=POSITIVE] Binding.AXIS_COMPONENT value
Return Values
booleanhasPrerequisitetrue if all prerequisite specializations are loaded
keytext(e.g. "F" for "KEY_f") for the keyboard action binding or nil if no resolution is possible

getGamepadInputSymbolName

Description
Get the controller symbol key name for a single gamepad / controller binding.
For full axes, call this for each axis component binding and concatenate the symbol keys with a space inbetween.
Definition
getGamepadInputSymbolName(internalDeviceId Internal, axisName Input, isAxisInput If)
Arguments
internalDeviceIdInternalgamepad device ID
axisNameInputaxis name
isAxisInputIftrue, the bound input axis is an analog physical axis
Return Values
booleanhasPrerequisitetrue if all prerequisite specializations are loaded
controllersymbolsconfiguration key name

getMouseInputSymbolName

Description
Get the controller symbol key name for a single mouse binding.
For full axes, call this for each axis component binding and concatenate the symbol keys with a space inbetween.
Definition
getMouseInputSymbolName(axisNames Mouse)
Arguments
axisNamesMousebinding axis names
Return Values
booleancanStartcan start ai
controllersymbolsconfiguration key name

onActionBindingsChanged

Description
Called when action bindings have changed.
Definition
onActionBindingsChanged(actionBindings Action)
Arguments
actionBindingsActionbindings table, {InputAction: {Binding}}
Return Values
booleancanContiuecan contiue ai

InputEvent

Description
Input event.
-- Holds information about an input event for an action, target, event callback and event trigger conditions. Also
stores input hint display information, because only actions with associated events need hints. When an action has
several events, callers need to make sure only one of the events' visibility is active.
--@category Input

new

Description
Create a new instance of InputEvent.
This constructor also assigns an ID to the instance, which should be used as a handle in most cases instead of the
actual instance reference.
Definition
new(actionName Name, targetObject Event, eventCallback Event, triggerUp If, triggerDown If, triggerAlways If, startActive [optional,, callbackState [optional])
Arguments
actionNameNameof action, see InputAction
targetObjectEventtarget, first argument to event callback
eventCallbackEventcallback, called when the action has input. Signature: callback(targetObject, actionName, inputValue, callbackState, isAnalog)
triggerUpIftrue, the event fires once when an input signal of the given action goes to "up" state, e.g. a released key.
triggerDownIftrue, the event fires once when an input signal of the given action goes to "down" state, e.g. a pressed key.
triggerAlwaysIftrue, the event fires on any signal input change, potentially every frame. This is mostly useful for required continuous axis input, e.g. steering actions.
startActive[optional,default=false] If true, the event is active right after registration.
callbackState[optional]An arbitrary value or reference which serves as a closure state within callbacks, useful e.g. when checking input state between events without requiring class fields.
Return Values
floatdirectionshape angle
NewInputEventinstance

setIgnoreComboMask

Description
Set the ignore flag for input binding combo masks.
If true, bindings which can trigger this event can be activated even if the do not match the currently pressed combo
mask. This is required for special cases, mostly player camera input, which should still be active when a combo
button is pressed.
Definition
setIgnoreComboMask()
Return Values
booleanisNeededcollision box is needed

getIgnoreComboMask

Description
Get the ignore flag for input binding combo masks.
Definition
getIgnoreComboMask()
Return Values
stringattributesstats attributes

notifyInput

Description
Notify this event of the input status of an associated action.
-- Note the interaction of the "down" and "always" triggers: If "down" is set and not "always", only an input down-flank
will raise an event. If both "down" and "always" are set, an event is raised as long as the input is pressed beyond a
threshold. If only "always" and not "down" is set, an event will be raised on each frame with the current input value
even if no input is active.
-- @param isUp If true, the action input had an "up" flank, i.e. the input was in "pressed" state and has returned to zero position
Definition
notifyInput(isDown If, isPressed If, inputValue Action, isAnalog True)
Arguments
isDownIftrue, the action input had a "down" flank, i.e. the input has crossed the "down" threshold
isPressedIftrue, the action input is in "pressed" state, i.e. the magnitude of the input is above the "down" threshold
inputValueActioninput value. This is not guaranteed to be in the range [-1, 1], because of sensitivity settings. Event handlers may clamp input values at their own discretion.
isAnalogTrueif the binding which provides the input value is analog.
Return Values
booleandeactivateOnLeavedeactivate on leaving

frameReset

Description
Reset this event after a frame.
Definition
frameReset()
Return Values
booleanhasPrerequisitetrue if all prerequisite specializations are loaded

makeId

Description
Make this InputEvent instance's ID.
Definition
makeId()
Return Values
booleanexistsanimation axists

getTriggerCode

Description
Return trigger code
Definition
getTriggerCode()
Return Values
booleanisPlayinganimation is playing

initializeDisplayText

Description
Initialize this event's input hint display text with information from its associated action.
Defaults to the action's positive display name. For most half-axis actions, this will be correct. If a more specific
text is required depending on the current player context, apply a different text through the input system using
InputBinding:setActionEventText().
Definition
initializeDisplayText(InputAction InputAction)
Arguments
InputActionInputActionwhich this event references.
Return Values
floatanimTimereal animation time in ms

InputGlyphElement

Description
Input glyph display element.
-- Displays a key or button glyph for an input.
--@category GUI

new

Description
Create a new instance of InputGlyphElement.
Definition
new(table inputDisplayManager, float baseWidth, float baseHeight)
Arguments
tableinputDisplayManagerInputDisplayManager reference
floatbaseWidthDefault width of this element in screen space
floatbaseHeightDefault height of this element in screen space
Return Values
tablenpcthe npc object

delete

Description
Delete this element and release its resources.
Definition
delete()
Return Values
tableinstanceinstance of object

deleteOverlayCopies

Description
Delete any overlay copies.
Definition
deleteOverlayCopies()
Return Values
booleantrueif loading was successful else false

setScale

Description
Set the scale of this element.
Definition
setScale(float widthScale, float heightScale)
Arguments
floatwidthScaleWidth scale factor
floatheightScaleHeight scale factor
Return Values
booltrueif successful

setUpperCase

Description
Set the glyph text to be displayed in all upper case or not.
This resets the lower case setting if upper case is enabled.
Definition
setUpperCase()
Return Values
booltrueif successful

setLowerCase

Description
Set the glyph text to be displayed in all lower case or not.
This resets the upper case setting if lower case is enabled.
Definition
setLowerCase()
Return Values
booltrueif normalized

setBold

Description
Set the glyph text to be displayed in bold print or not.
Definition
setBold()
Return Values
booltrueif normalized

setKeyboardGlyphColor

Description
Set the button frame color for the keyboard glyphs.
Definition
setKeyboardGlyphColor(table color)
Arguments
tablecolorColor as an RGBA array
Return Values
tablereturnsa food group or nil if nothing is found

setButtonGlyphColor

Description
Set the color for button glyphs.
Definition
setButtonGlyphColor(table color)
Arguments
tablecolorColor as an RGBA array
Return Values
tablereturnsa food group or nil if nothing is found

setAction

Description
Set the action whose input glyphs need to be displayed by this element.
Definition
setAction(string actionName, string actionText, float actionTextSize, bool noModifiers, bool copyOverlays)
Arguments
stringactionNameInputAction name
stringactionText[optional] Additional action text to display after the glyph
floatactionTextSize[optional] Additional action text size in screen space
boolnoModifiers[optional] If true, will only show the input glyph of the last unmodified input binding axis
boolcopyOverlays[optional] If true, will create and handle a separate copy of an input glyph. Do not use
this when updating the action each frame!
Return Values
tablereturnsa food mixture or nil if nothing is found

setActions

Description
Set multiple actions whose input glyphs need to be displayed by this element.
If exactly two actions are passed in, they will be interpreted as belonging to the same axis and the system tries
to resolved the actions to a combined glyph. Otherwise, the glyphs will just be displayed in order of the actions.
Definition
setActions(table actionNames, string actionText, float actionTextSize, bool noModifiers, bool copyOverlays)
Arguments
tableactionNamesInputAction names array
stringactionText[optional] Additional action text to display after the glyph
floatactionTextSize[optional] Additional action text size in screen space
boolnoModifiers[optional] If true, will only show the input glyph of the last unmodified input binding axis
boolcopyOverlays[optional] If true, will create and handle a separate copy of an input glyph. Do not use
this when updating the action each frame!
Return Values
intFoodconsumption type, one of [AnimalFoodManager.FOOD_CONSUME_TYPE_SERIAL | AnimalFoodManager.FOOD_CONSUME_TYPE_PARALLEL]

updateDisplayText

Description
Update the display text from the set action text according to current casing settings.
Definition
updateDisplayText()
Return Values
tablereturnsa food group or nil if not found

getGlyphWidth

Description
Get the screen space width required by the glyphs used to display input in the current input context.
Definition
getGlyphWidth()
Return Values
floatreturnsa production weight between 0 and 1

draw

Description
Draw the input glyph(s).
Definition
draw()
Return Values
tableinstanceInstance of object

drawControllerButtons

Description
Draw controller button glyphs.
Definition
drawControllerButtons(table Array, float posX, float posY)
Arguments
tableArrayof controller button glyph overlays
floatposXInitial drawing X position in screen space
floatposYInitial drawing Y position in screen space
Return Values
boolreturnstrue if loading is fine
floatXposition in screen space after the last glyph

drawKeyboardKeys

Description
Draw keyboard key glyphs.
Definition
drawKeyboardKeys(table Array, float posX, float posY)
Arguments
tableArrayof keyboard key names
floatposXInitial drawing X position in screen space
floatposYInitial drawing Y position in screen space
Return Values
boolreturnstrue if module init after placement is fine
floatXposition in screen space after the last glyph

drawActionText

Description
Draw the action text after the input glyphs.
Definition
drawActionText(float posX, float posY)
Arguments
floatposXDrawing X position in screen space
floatposYDrawing Y position in screen space
Return Values

InputHelpDisplay

Description
HUD input help display.
-- Displays controls and further information for the current input context.
--@category GUI

new

Description
Create a new instance of InputHelpDisplay.
Definition
new(string hudAtlasPath)
Arguments
stringhudAtlasPathPath to the HUD texture atlas
Return Values

addHelpText

Description
Add a help text line for this frame.
Will be cleared after the current frame.
Definition
addHelpText()
Return Values
boolreturnstrue if initialization is fine

setVehicle

Description
Set the currently controlled vehicle.
Definition
setVehicle(table vehicle)
Arguments
tablevehicleVehicle reference or nil if no vehicle is controlled.
Return Values
stringfilllevel

getHidingTranslation

Description
Override of HUDDisplayElement.
Moves out to the left to hide.
Definition
getHidingTranslation()
Return Values
integertotalanimals. Default is zero

addCustomEntry

Description
Add a custom input help entry which is displayed in the current input context until removed.
Custom entries will be displayed in order of addition after any automatically detected input help entries and before
vehicle extensions.
Definition
addCustomEntry()
Return Values
stringreturnanimal type. nil if not available

clearCustomEntries

Description
Clear all custom input help entries in the current context.
Definition
clearCustomEntries()
Return Values
tableofcosumed food (result[fillTypeIndex]=amount)

update

Description
Update the input help's state.
Definition
update()
Return Values
tableProductionfill type information as {i={j={fillType=fillType, fillLevel=fillLevel, capacity=capacity}}}

updateSizeAndPositions

Description
Update sizes and positions of this elements and its children.
Definition
updateSizeAndPositions()
Return Values

refreshHUDExtensions

Description
Create any required HUD extensions when the current vehicle configuration changes.
Definition
refreshHUDExtensions()
Return Values
booltrueif registration went well

updateHUDExtensions

Description
Update HUD extensions if controlled vehicles have changed.
Definition
updateHUDExtensions()
Return Values
booltrueif registration went well

collectVehicleSpecializations

Description
Recursively get vehicle specializations for a vehicle configuration.
Definition
collectVehicleSpecializations()
Return Values
floatdirtyfactor [0-1]

getAvailableHeight

Description
Get the available screen space height for displaying input help.
Definition
getAvailableHeight()
Return Values
tableinstanceinstance of object

updateInputContext

Description
Update display elements with the current input context.
Definition
updateInputContext()
Return Values
booleantrueif loading was successful else false

updateEntries

Description
Update entry glyphs and visibility with the current input help elements.
Definition
updateEntries(table helpElements)
Arguments
tablehelpElementsArray of InputHelpElement for the current input context
Return Values
booltrueif successful

updateComboHeaders

Description
Update combo header state.
Definition
updateComboHeaders(bool useGamepadButtons, int pressedComboMaskMouse, int pressedComboMaskGamepad)
Arguments
booluseGamepadButtonsIf true, check gamepad input. Otherwise, check keyboard / mouse.
intpressedComboMaskMouseBit mask of pressed mouse combo actions
intpressedComboMaskGamepadBit mask of pressed gamepad combo actions
Return Values
booltrueif animal is in the husbandry
floatScreenspace height used by the combo header (0 if invisible)

updateComboInputGlyphs

Description
Update visibility and color of combo input glyphs.
Definition
updateComboInputGlyphs(table comboActionStatus, int pressedComboMaskMouse, int pressedComboMaskGamepad)
Arguments
tablecomboActionStatusHashtable of combo action names which are currently available
intpressedComboMaskMouseBit mask of pressed mouse combo actions
intpressedComboMaskGamepadBit mask of pressed gamepad combo actions
Return Values
table

getInputHelpElements

Description
Get input help elements based on the current input context.
Definition
getInputHelpElements(float availableHeight, int pressedComboMaskGamepad, int pressedComboMaskMouse, bool useGamepadButtons)
Arguments
floatavailableHeightMaximum available height to use for input help elements
intpressedComboMaskGamepadBit mask of pressed gamepad combo buttons
intpressedComboMaskMouseBit mask of pressed mouse combo buttons
booluseGamepadButtonsIf true, we should draw gamepad / controller combo button glyphs
Return Values
tableinstanceinstance of object
tableInputhelp elements
floatScreenspace height used by the returned help elements

setAnimationAvailableHeight

Description
Set the current animation value for available height.
Definition
setAnimationAvailableHeight()
Return Values
booleantrueif loading was successful else false

setAnimationOffset

Description
Set the current animation position offset.
Definition
setAnimationOffset()
Return Values
booltrueif successful

animateHide

Description
Animate this element on hiding.
Definition
animateHide()
Return Values
booltrueif successful

animateShow

Description
Animate this element on showing.
Definition
animateShow()
Return Values
floatamounteffectively changed

onAnimateVisibilityFinished

Description
Called when a hiding or showing animation has finished.
Definition
onAnimateVisibilityFinished()
Return Values
floatdeltaof amount changed

onInputDevicesChanged

Description
Called when the connected input devices have changed.
Definition
onInputDevicesChanged()
Return Values
floatreturnsthe fillLevel of a fillType

draw

Description
Draw the input help.
Only draws if the element is visible and there are any help elements.
Definition
draw()
Return Values
floatreturnsthe fillLevel of all fillType

drawControlsLabel

Description
Draw the "controls" label on top of the display frame.
Definition
drawControlsLabel()
Return Values
floatreturnsthe capacity of a fillType

drawHelpInfos

Description
Draw icons and text in help entries.
Definition
drawHelpInfos()
Return Values
floatreturnsa progress of the fillType between 0 and 1. Default is 0.

drawVehicleHUDExtensions

Description
Draw vehicle HUD extensions.
Definition
drawVehicleHUDExtensions()
Return Values
floatactualdelta filled

setScale

Description
Set this element's UI scale.
Definition
setScale(float uiScale)
Arguments
floatuiScaleUI scale factor
Return Values

storeScaledValues

Description
Store scaled positioning, size and offset values.
Definition
storeScaledValues()
Return Values
tablemoduleinstance or nil of no module has been registered

getBackgroundPosition

Description
Get this element's base background position in screen space.
Definition
getBackgroundPosition()
Return Values
tableinstanceinstance of object

getTopLeftPosition

Description
Get the current top left position of the input help, including animation.
Definition
getTopLeftPosition()
Return Values
booleantrueif loading was successful else false

getMaxEntryCount

Description
Get the maximum number of help entries which may be shown at any time.
Definition
getMaxEntryCount()
Return Values
floatreturnsthe capacity of a fillType
intMaximumnumber of entries to show

getIsHelpElementAllowed

Description
Returns if it is still allowed to add more help elements
Definition
getIsHelpElementAllowed(table helpElements, table helpElement)
Arguments
tablehelpElementsexisting table of help elements
tablehelpElementhelp element to add
Return Values
floatamounteffectively changed
booleanisAllowedisAllowed

setDimension

Description
Set this element's dimensions.
Override from HUDElement which adjusts frame with offset.
Definition
setDimension()
Return Values
booleantrueif loading was successful else false

createBackground

Description
Create the background overlay for positioning.
Definition
createBackground()
Return Values
floatfooddropped

createComponents

Description
Create required display components.
Definition
createComponents()
Return Values
floatspillagetotal

createFrame

Description
Create the frame around input help elements.
Definition
createFrame()
Return Values
tableinstanceinstance of object

createVerticalSeparator

Description
Create a vertical separator element.
Definition
createVerticalSeparator()
Return Values
booleantrueif loading was successful else false

createHorizontalSeparator

Description
Create a horizontal separator element.
Definition
createHorizontalSeparator()
Return Values
tableinstanceinstance of object

createComboInputGlyph

Description
Create an input glyph for displaying combo input buttons.
Definition
createComboInputGlyph(float posX, float posY, float width, float height, string actionName)
Arguments
floatposXScreen space X position
floatposYScreen space Y position
floatwidthScreen space width
floatheightScreen space height
stringactionNameInputAction name of the combo action whose input glyphs need to be displayed
Return Values
booleantrueif loading was successful else false
tableComboInputGlyphElement instance

createComboHeader

Description
Create a combo input glyph header.
Definition
createComboHeader(hudAtlasPath Path, frameX Screen, frameY Screen, table combos, table boxSize, table separatorPositions)
Arguments
hudAtlasPathPathto HUD texture atlas
frameXScreenspace X position of the display frame
frameYScreenspace Y position of the display frame
tablecombosArray of input combination descriptions as defined in InputBinding
tableboxSize2D vector which holds the pixel size of one combo input box within the header
tableseparatorPositionsArray of 2D vectors of separator pixel positions
Return Values
floatmanuredropped
tableComboheader HUDElement

createMouseComboHeader

Description
Create the mouse combo header.
Definition
createMouseComboHeader()
Return Values
floatmanurefill level

createControllerComboHeader

Description
Create the gamepad / controller combo header.
Definition
createControllerComboHeader()
Return Values
floatmanureused

createEntry

Description
Create an input help entry box.
Definition
createEntry()
Return Values
tableinstanceinstance of object

createEntries

Description
Create all required input help entry boxes.
The boxes are modified as required to reflect the current input context.
Definition
createEntries()
Return Values
booleantrueif loading was successful else false

InputHelpElement

Description
Input help element.
-- Holds help and hint information about the current input context for display in the HUD.
--@category Input

getActionNames

Description
Get an array of action names which were validly set in the constructor.
Definition
getActionNames()
Return Values
floatanimTimeanimation time [0..1]

InputHelper

Description
Maps key IDs to localization glyph symbols.

MouseHelper.getInputDisplayText

Description
Get a display string for a list of mouse input axis names
Definition
MouseHelper.getInputDisplayText()
Return Values
floatdurationduration in ms

KeyboardHelper.getDisplayKeyName

Description
Get a display name for a given key ID.
Encapsulates engine getKeyName() function.
Definition
KeyboardHelper.getDisplayKeyName()
Return Values
booleanrightOrderreturns true if parts are in right order

KeyboardHelper.getInputDisplayText

Description
Get a display string for a list of keyboard input keys.
Definition
KeyboardHelper.getInputDisplayText()
Return Values
booleanrightOrderreturns true if parts are in reverse right order

GamepadHelper.getInputDisplayText

Description
Get a display string for a list of gamepad/controller input button/axis names and an associated device.
Definition
GamepadHelper.getInputDisplayText(inputList List, internalDeviceId ID)
Arguments
inputListListof input button / axis names
internalDeviceIdIDof device as issued by the engine
Return Values
floatretlimited value

JoinGameScreen

Description
Join Multiplayer Game Screen.
-- @field mainBox Layout box for most of the screen, used to quickly show / hide everything.

onClickHeader

Description
Handle clicks on table header elements
Triggers sorting and a view update.
Definition
onClickHeader()
Return Values
tableinstanceinstance of object

onServerNameChanged

Description
Handle changes in the server name filter field
Definition
onServerNameChanged(element TextInputElement, text New)
Arguments
elementTextInputElementinstance
textNewtext
Return Values
tablebaleTypebaleType object

saveFilterSettings

Description
Save the current filter settings.
Definition
saveFilterSettings()
Return Values
tablebrandColorbrandColor object

getSelectedServer

Description
Get the server info of the currently selected server
Definition
getSelectedServer()
Return Values
tableinstanceinstance of object

setStartButtonState

Description
Assign the "Start Game" button state.
Enables the button if the currently selected server is valid for playing. Disables it otherwise.
Definition
setStartButtonState()
Return Values
booleantrueif loading was successful else false

filterServer

Description
Filter a server with the current filter settings.
Definition
filterServer(server Server)
Arguments
serverServerinformation (see onServerInfo()) for data structure
Return Values
booleantrueif loading was successful else false
Trueifthe server matches the current filter settings, false otherwise

setTableFiltersAndSorting

Description
Apply server filters to server list.
Definition
setTableFiltersAndSorting()
Return Values
booleansuccesssuccess

rebuildServerList

Description
Update the server table.
This causes a full rebuild of the table data.
Definition
rebuildServerList()
Return Values
tableinstanceinstance of object

buildServerDataRow

Description
Build a DataRow from server properties to add to the server list GuiElement.
Definition
buildServerDataRow()
Return Values
tableinstanceinstance of object
dataRowinstancewith server data

ListItemElement

Description
List item element to be used and laid out by ListElement and TableElement.
-- Used layers: "image" for a background image.
--@category GUI
--@xmlConfig GuiElement#allowSelected bool [optional] If false, this element cannot be selected, only focused or activated.

getFocusTarget

Description
Get the actual focus target, in case a child or parent element needs to be targeted instead.
Override from BitmapElement: Only focuses children if #autoSelectChildren is true
Definition
getFocusTarget(incomingDirection (Optional), moveDirection (Optional))
Arguments
incomingDirection(Optional)If specified, may return different targets for different incoming directions.
moveDirection(Optional)Actual movement direction per input. This is the opposing direction of incomingDirection.
Return Values
GuiElementActualelement to focus.

MainScreen

Description
Main Menu Screen.
-- @field backgroundImage Main background image

setupNotifications

Description
Set up notifications display and animation.
Definition
setupNotifications()
Return Values
floatnearCoCRadiusNear circle of confusion radius (nearCoCRadius = 0 means no near blur (pinhole camera))
floatnearBlurEndDistance from the camera center where near blur ends
floatfarCoCRadiusFar circle of confusion radius (farCoCRadius = 0 means no far blur (pinhole camera))
floatfarBlurStartDistance from the camera center where far blur starts
floatfarBlurEndDistance from the camera center where far blur ends

setNotificationButtonsDisabled

Description
Set notification buttons disabled state.
If fewer than 2 notifications are available to show, the cycle buttons will always be disabled.
Definition
setNotificationButtonsDisabled()

resetNotifications

Description
Reset notification data and display.
Definition
resetNotifications()

cycleNotification

Description
Cycle through available notifications.
Definition
cycleNotification(int signedDelta)
Arguments
intsignedDelta1 or -1 for next or previous

onNotificationBoxClick

Description
Handle an activation of the notification open button or input action.
Definition
onNotificationBoxClick()

updateNotifications

Description
Update notifications.
Definition
updateNotifications()
Return Values
floatnearCoCRadiusNear circle of confusion radius (nearCoCRadius = 0 means no near blur (pinhole camera))
floatnearBlurEndDistance from the camera center where near blur ends
floatfarCoCRadiusFar circle of confusion radius (farCoCRadius = 0 means no far blur (pinhole camera))
floatfarBlurStartDistance from the camera center where far blur starts
floatfarBlurEndDistance from the camera center where far blur ends

updateFading

Description
Update screen fading values.
Definition
updateFading()

MapDataGrid

Description
Creating data grid

new

Description
@param table customMt custom metatable
Definition
new()
Return Values
tableinstanceinstance of object
Code
19function MapDataGrid:new(mapSize, blocksPerRowColumn, customMt)
20 local self = DataGrid:new(blocksPerRowColumn, blocksPerRowColumn, customMt or MapDataGrid_mt)
21
22 self.blocksPerRowColumn = blocksPerRowColumn
23 self.mapSize = mapSize
24 self.blockSize = self.mapSize/self.blocksPerRowColumn
25
26 return self
27end

getValueAtWorldPos

Description
@param float worldZ world position z
Definition
getValueAtWorldPos()
Return Values
tablevaluevalue at the given position
Code
34function MapDataGrid:getValueAtWorldPos(worldX, worldZ)
35 local rowIndex, colIndex = self:getRowColumnFromWorldPos(worldX, worldZ)
36 return self:getValue(rowIndex, colIndex), rowIndex, colIndex
37end

setValueAtWorldPos

Description
@param float worldZ world position z
Definition
setValueAtWorldPos(table value)
Arguments
tablevaluevalue at the given position
Code
44function MapDataGrid:setValueAtWorldPos(worldX, worldZ, value)
45 local rowIndex, colIndex = self:getRowColumnFromWorldPos(worldX, worldZ)
46 self:setValue(rowIndex, colIndex, value)
47end

getRowColumnFromWorldPos

Description
@param float worldZ world position z
Definition
getRowColumnFromWorldPos()
Return Values
integerrowrow
integercolumncolumn
Code
55function MapDataGrid:getRowColumnFromWorldPos(worldX, worldZ)
56 local mapSize = self.mapSize
57 local blocksPerRowColumn = self.blocksPerRowColumn
58
59 local x = (worldX + mapSize*0.5) / mapSize
60 local z = (worldZ + mapSize*0.5) / mapSize
61
62 local row = MathUtil.clamp(math.ceil(blocksPerRowColumn*z), 1, blocksPerRowColumn)
63 local column = MathUtil.clamp(math.ceil(blocksPerRowColumn*x), 1, blocksPerRowColumn)
64
65-- log(worldX, worldZ, " -> ", (worldX + self.mapSize*0.5), (worldZ + self.mapSize*0.5), z, x, row, column)
66
67 return row, column
68end

MapHotspot

Description
UV coordinates in the map hotspot atlas.

setRawTextOffset

Description
Set the text offset using a raw value string in the form of "<X>px <Y>px".
Definition
setRawTextOffset()
Return Values
booleantrueif loading was successful else false

setOwnerFarmId

Description
Set the farm this hotspot should be shown for. Use AccessHandler.EVERYONE for showing it to everybody (default)
Definition
setOwnerFarmId()
Return Values
boolistrue if available Pallet has been assigned with a vehicle object

MapOverlayGenerator

Description
Map overlay generator.
-- Provides density map based data overlays on top of an in-game map.

new

Description
Create a MapOverlayGenerator instance.
Definition
new(table l10n, table fruitTypeManager, table fillTypeManager, table farmlandManager, table farmManager)
Arguments
tablel10nI18N reference for text localization
tablefruitTypeManagerFruitTypeManager reference for fruit type resolution
tablefillTypeManagerFillTypeManager reference for fruit fill type resolution
tablefarmlandManagerFarmlandManager reference for farm land data access
tablefarmManagerFarmManager reference for farm land ownership data access

delete

Description
Delete this instance and any used overlays.
Definition
delete()

setMissionFruitTypes

Description
Set the valid fruit types of the current mission.
Definition
setMissionFruitTypes()

setColorBlindMode

Description
Set the color blind mode for overlay creation.
Definition
setColorBlindMode()

buildFruitTypeMapOverlay

Description
Build the map overlay for fruit types.
Definition
buildFruitTypeMapOverlay()

buildGrowthStateMapOverlay

Description
Build the map overlay for growth states.
Definition
buildGrowthStateMapOverlay()

buildSoilStateMapOverlay

Description
Build the map overlay for soil states.
Definition
buildSoilStateMapOverlay()

buildFarmlandsMapOverlay

Description
Build the map overlay for farm lands.
Definition
buildFarmlandsMapOverlay()

generateOverlay

Description
Generate a map overlay of a given type.
This is an internal generic interfacing method and should not be called externally. Consumers should use one of the
specific public methods instead, e.g. MapOverlayGenerator:generateFruitTypeOverlay().
Definition
generateOverlay(int mapOverlayType, function finishedCallback, table overlayState)
Arguments
intmapOverlayTypeOverlay type as one of MapOverlayGenerator.OVERLAY_TYPE.[CROPS|GROWTH|SOIL|FARMLANDS]
functionfinishedCallbackFunction which is called with the overlay ID as its argument when processing is
finished, signature: function(overlayId)
tableoverlayStateOverlay state data which defines parameters (e.g. colors) of the map overlays.
Return Values
boolTrueif overlay generation has started, false if generation is already in progress or an invalid overlay
type has been provided

generateFruitTypeOverlay

Description
Generate a fruit type overlay.
Definition
generateFruitTypeOverlay(function finishedCallback, table fruitTypeFilter)
Arguments
functionfinishedCallbackCalled when generation is finished, signature: function(overlayId)
tablefruitTypeFilterMap of fruit type indices to booleans. If the value is true, the fruit type will be displayed.
Return Values
boolTrueif overlay generation has started, false if generation is already in progress or an invalid overlay
type has been provided

generateGrowthStateOverlay

Description
Generate a growth state overlay.
Definition
generateGrowthStateOverlay(function finishedCallback, table fruitTypeFilter)
Arguments
functionfinishedCallbackCalled when generation is finished, signature: function(overlayId)
tablefruitTypeFilterMap of growth state indices (MapOverlayGenerator.GROWTH_STATE_INDEX members) to
booleans. If the value is true, the growth state will be displayed.
Return Values
boolTrueif overlay generation has started, false if generation is already in progress or an invalid overlay
type has been provided

generateSoilStateOverlay

Description
Generate a soil state overlay.
Definition
generateSoilStateOverlay(function finishedCallback, table fruitTypeFilter)
Arguments
functionfinishedCallbackCalled when generation is finished, signature: function(overlayId)
tablefruitTypeFilterMap of soil state indices (MapOverlayGenerator.SOIL_STATE_INDEX members) to
booleans. If the value is true, the soil state will be displayed.
Return Values
boolTrueif overlay generation has started, false if generation is already in progress or an invalid overlay
type has been provided

generateFarmlandOverlay

Description
Generate a farm land overlay.
Definition
generateFarmlandOverlay(function finishedCallback, table mapPosition)
Arguments
functionfinishedCallbackCalled when generation is finished, signature: function(overlayId)
tablemapPositionMap position vector of a selection position. If the position is within a farm land, it will
be highlighted.

checkOverlayFinished

Description
Check if any overlay is currently being generated and triggers a callback when it's finished.
Definition
checkOverlayFinished()

reset

Description
Reset overlay generation state.
Definition
reset()

update

Description
Update the state each frame.
Checks the overlay generation state.
Definition
update()

getDisplayCropTypes

Description
Get display information for crop types.
Override to add new crop types or change information.
Definition
getDisplayCropTypes()
Return Values
arrayofdisplay information, {i={colors={true=[{r,g,b,a} colorblind], false=[{r,g,b,a} default], iconFilename=path,
iconUVs={u1, v1, u2, v2, u3, v3, u4, v4}, description=text, fruitTypeIndex=index}}
Code
373function MapOverlayGenerator:getDisplayCropTypes()
374 local cropTypes = {}
375 -- load crop type icon definitions in order of map configuration
376 for i, fruitType in ipairs(self.missionFruitTypes) do
377 if fruitType.shownOnMap and fruitType.fruitTypeIndex ~= FruitType.WEED then -- weed is known as a fruit type, but is handled as a soil state
378 local fillableIndex = self.fruitTypeManager:getFillTypeIndexByFruitTypeIndex(fruitType.fruitTypeIndex)
379 local fillable = self.fillTypeManager:getFillTypeByIndex(fillableIndex)
380
381 local iconFilename = fillable.hudOverlayFilenameSmall
382 local iconUVs = Overlay.DEFAULT_UVS -- default crop type icons are separate files, use full texture
383 local description = fillable.title
384
385 table.insert(cropTypes, {
386 colors = {[false] = fruitType.defaultColor, [true] = fruitType.colorBlindColor},
387 iconFilename = iconFilename,
388 iconUVs = iconUVs,
389 description = description,
390 fruitTypeIndex = fruitType.fruitTypeIndex,
391 foliageId = fruitType.foliageId
392 })
393 end
394 end
395
396 return cropTypes
397end

getDisplayGrowthStates

Description
Get display information for growth states.
Growth states can be represented in multiple colors per state, so colors are defined in arrays per color blind mode.
Override to add new growth states or change information.
Definition
getDisplayGrowthStates()
Return Values
arrayofdisplay information, {i={colors={true={i={r,g,b,a}}, false={i={r,g,b,a}}}, description=text}}
Code
404function MapOverlayGenerator:getDisplayGrowthStates()
405 return {
406 -- indices are contiguous, so this definition is a valid array:
407 [MapOverlayGenerator.GROWTH_STATE_INDEX.CULTIVATED] = {
408 colors = {
409 [true] = {MapOverlayGenerator.FRUIT_COLOR_CULTIVATED[true]},
410 [false] = {MapOverlayGenerator.FRUIT_COLOR_CULTIVATED[false]}
411 },
412 description = self.l10n:getText(MapOverlayGenerator.L10N_SYMBOL.GROWTH_MAP_CULTIVATED)
413 },
414 [MapOverlayGenerator.GROWTH_STATE_INDEX.GROWING] = {
415 colors = MapOverlayGenerator.FRUIT_COLORS_GROWING,
416 description = self.l10n:getText(MapOverlayGenerator.L10N_SYMBOL.GROWTH_MAP_GROWING)
417 },
418 [MapOverlayGenerator.GROWTH_STATE_INDEX.HARVEST] = {
419 colors = MapOverlayGenerator.FRUIT_COLORS_HARVEST,
420 description = self.l10n:getText(MapOverlayGenerator.L10N_SYMBOL.GROWTH_MAP_HARVEST)
421 },
422 [MapOverlayGenerator.GROWTH_STATE_INDEX.HARVESTED] = {
423 colors = {
424 [true] = {MapOverlayGenerator.FRUIT_COLOR_CUT},
425 [false] = {MapOverlayGenerator.FRUIT_COLOR_CUT}
426 },
427 description = self.l10n:getText(MapOverlayGenerator.L10N_SYMBOL.GROWTH_MAP_HARVESTED)
428 },
429 [MapOverlayGenerator.GROWTH_STATE_INDEX.PLOWED] = {
430 colors = {
431 [true] = {MapOverlayGenerator.FRUIT_COLOR_PLOWED[true]},
432 [false] = {MapOverlayGenerator.FRUIT_COLOR_PLOWED[false]}
433 },
434 description = self.l10n:getText(MapOverlayGenerator.L10N_SYMBOL.GROWTH_MAP_PLOWED)
435 },
436 [MapOverlayGenerator.GROWTH_STATE_INDEX.TOPPING] = {
437 colors = {
438 [true] = {MapOverlayGenerator.FRUIT_COLOR_REMOVE_TOPS[true]},
439 [false] = {MapOverlayGenerator.FRUIT_COLOR_REMOVE_TOPS[false]}
440 },
441 description = self.l10n:getText(MapOverlayGenerator.L10N_SYMBOL.GROWTH_MAP_TOPPING)
442 },
443 [MapOverlayGenerator.GROWTH_STATE_INDEX.WITHERED] = {
444 colors = {
445 [true] = {MapOverlayGenerator.FRUIT_COLOR_WITHERED[true]},
446 [false] = {MapOverlayGenerator.FRUIT_COLOR_WITHERED[false]}
447 },
448 description = self.l10n:getText(MapOverlayGenerator.L10N_SYMBOL.GROWTH_MAP_WITHERED)
449 }
450 }
451end

getDisplaySoilStates

Description
Get display information for soil states.
Soil states can be represented in multiple colors per state, so colors are defined in arrays per color blind mode.
Override to add new soil states or change information.
Definition
getDisplaySoilStates()
Return Values
arrayofdisplay information, {i={colors={true={i={r,g,b,a}}, false={i={r,g,b,a}}}, description=text}}
Code
458function MapOverlayGenerator:getDisplaySoilStates()
459 local weedType = self.fruitTypeManager:getWeedFruitType()
460 local fillableIndex = self.fruitTypeManager:getFillTypeIndexByFruitTypeIndex(FruitType.WEED)
461 local weedFillable = self.fillTypeManager:getFillTypeByIndex(fillableIndex)
462
463 return {
464 [MapOverlayGenerator.SOIL_STATE_INDEX.WEEDS] = {
465 colors = {
466 [true] = {weedType.colorBlindMapColor},
467 [false] = {weedType.defaultMapColor}
468 },
469 description = weedFillable.title
470 },
471 [MapOverlayGenerator.SOIL_STATE_INDEX.FERTILIZED] = {
472 colors = MapOverlayGenerator.FRUIT_COLORS_FERTILIZED,
473 description = self.l10n:getText(MapOverlayGenerator.L10N_SYMBOL.SOIL_MAP_FERTILIZED)
474 },
475 [MapOverlayGenerator.SOIL_STATE_INDEX.NEEDS_PLOWING] = {
476 colors = {
477 [true] = {MapOverlayGenerator.FRUIT_COLOR_NEEDS_PLOWING[true]},
478 [false] = {MapOverlayGenerator.FRUIT_COLOR_NEEDS_PLOWING[false]}
479 },
480 description = self.l10n:getText(MapOverlayGenerator.L10N_SYMBOL.SOIL_MAP_NEED_PLOWING)
481 },
482 [MapOverlayGenerator.SOIL_STATE_INDEX.NEEDS_LIME] = {
483 colors = {
484 [true] = {MapOverlayGenerator.FRUIT_COLOR_NEEDS_LIME[true]},
485 [false] = {MapOverlayGenerator.FRUIT_COLOR_NEEDS_LIME[false]}
486 },
487 description = self.l10n:getText(MapOverlayGenerator.L10N_SYMBOL.SOIL_MAP_NEED_LIME)
488 }
489 }
490end

MapSelectionScreen

Description
Map Selection Screen.
-- Used when starting a new game.
-- @field mapSelector Map selection option at top of view

onCreateMapImage

Description
Creation event for map preview BitmapElement instances.
This gets called during onOpen when map data is iterated and added, so we can set the image state according to the
currently processed map.
Definition
onCreateMapImage(element BitmapElement)
Arguments
elementBitmapElementinstance which shows a map preview image

MessageCenter

Description
Message center message types.
Use these identifiers to subscribe to and publish messages.

subscribe

Description
Subscribe the target to given message type.
Definition
subscribe(integer messageType, function callback, table callbackTarget, any argument)
Arguments
integermessageTypeType of message
functioncallbackCallback function
tablecallbackTargetOptional target
anyargumentOptional argument, will be last in callback argument list
Return Values
tableimplementimplement

unsubscribe

Description
Unsubscribe the observer from message
This is relatively slow, do not use in :update or :draw
Definition
unsubscribe(integer messageType, table callbackTarget)
Arguments
integermessageTypeType of message
tablecallbackTargetObserver object
Return Values
booleansuccesssuccess

unsubscribeAll

Description
Unsubscribe the observer from all messages
Definition
unsubscribeAll(table callbackTarget)
Arguments
tablecallbackTargetObserver object
Return Values
booleansupportsHardAttachattacher joint supports hard attach

publish

Description
Publish a message with given type and possible arguments
Definition
publish(integer messageType, table arguments)
Arguments
integermessageTypeType of the message, used with the subscriptions
tableargumentsOptional arguments passed to function
Return Values
booleansuccesssuccess

publishDelayed

Description
Publish a message with given type and possible arguments. This message is handled in the next frame.
Useful for within networking code
Definition
publishDelayed(integer messageType, table arguments)
Arguments
integermessageTypeType of the message, used with the subscriptions
tableargumentsOptional arguments passed to function
Return Values
floattotalMasstotal mass

MissionCollaborators

Description
Mission class collaborator collection for initialization.
-- Serves as an explicitly defined value-object for Mission class constructors to pass in required collaborator
references without needing to change the constructor signature for each new collaborator class.

new

Description
Create a new MissionCollaborators instance.
The constructor declares fields for reference which are used by the Mission class constructors. Stick to only
assigning to these fields when using this class or add a suitable declaration below when more references are needed.
Definition
new()
Return Values
floattotalamount of consumed pto torque in kNm

MissionManager

Description
Dismiss a (finished or cancelled) mission. Deletes it completely. Calls dismiss on the mission to handle money exchange to farm.

new

Description
Creating manager
Definition
new()
Return Values
tableinstanceinstance of object
Code
31function MissionManager:new(customMt)
32 local self = AbstractManager:new(customMt or MissionManager_mt)
33
34 self.missionTypes = {}
35 self.missionTypeIdToType = {}
36
37 self.defaultMissionMapWidth = 512
38 self.defaultMissionMapHeight = 512
39 self.missionMapNumChannels = 4
40
41 -- Only on new game start. Reset is done when quitting a game.
42 -- This value is changed very early in the loading process
43 self.numTransportTriggers = 0
44 self.transportTriggers = {}
45
46 return self
47end

loadMapData

Description
Load data on map load
Definition
loadMapData()
Return Values
booleantrueif loading was successful else false
Code
74function MissionManager:loadMapData(xmlFile)
75 MissionManager:superClass().loadMapData(self)
76
77 self:createMissionMap()
78
79 if g_currentMission:getIsServer() then
80 g_currentMission:addUpdateable(self)
81
82 self.missionNextGenerationTime = g_currentMission.time + MissionManager.MISSION_GENERATION_INTERVAL
83
84 self.fieldDataDmod = DensityMapModifier:new(g_currentMission.terrainDetailId, g_currentMission.sprayFirstChannel, g_currentMission.sprayNumChannels)
85 self.fieldDataFilter = DensityMapFilter:new(g_currentMission.terrainDetailId, g_currentMission.terrainDetailTypeFirstChannel, g_currentMission.terrainDetailTypeNumChannels)
86 self.fieldDataFilter:setValueCompareParams("greater", 0)
87 end
88
89 local p = getXMLString(xmlFile, "map.transportMissions#filename")
90 if p ~= nil then
91 local path = Utils.getFilename(p, g_currentMission.baseDirectory)
92 if path ~= nil and path ~= "" then
93 self:loadTransportMissions(path)
94 end
95 end
96
97 local p = getXMLString(xmlFile, "map.missionVehicles#filename")
98 if p ~= nil then
99 local path = Utils.getFilename(p, g_currentMission.baseDirectory)
100 if path ~= nil then
101 self:loadMissionVehicles(path)
102 end
103 end
104
105 if g_currentMission:getIsServer() then
106 -- Generate a weighted list of transport missions
107 for _, missionType in ipairs(self.missionTypes) do
108 if missionType.category == MissionManager.CATEGORY_TRANSPORT then
109 for i = 1, missionType.priority do
110 table.insert(self.possibleTransportMissionsWeighted, missionType)
111 end
112 end
113 end
114 end
115
116 g_messageCenter:subscribe(MessageType.MISSION_DELETED, self.onMissionDeleted, self)
117
118 if g_addTestCommands then
119 addConsoleCommand("gsGenerateFieldMission", "Force generating a new mission for given field", "consoleGenerateFieldMission", self)
120 addConsoleCommand("gsMissionLoadAllVehicles", "Loading and unloading all field mission vehicles", "consoleLoadAllFieldMissionVehicles", self)
121
122 addConsoleCommand("gsMissionHarvestField", "Harvest a field and print the liters", "consoleHarvestField", self)
123 end
124end

loadTransportMissions

Description
Load map-configured transport missions
Definition
loadTransportMissions()

loadMissionVehicles

Description
Load vehicles for use with field missions
Definition
loadMissionVehicles()

unloadMapData

Description
Unload data on mission delete
Definition
unloadMapData()
Code
349function MissionManager:unloadMapData()
350 g_messageCenter:unsubscribeAll()
351 g_currentMission:removeUpdateable(self)
352
353 self.numTransportTriggers = 0
354 self.transportTriggers = {}
355
356 self.fieldDataDmod = nil
357 self.fieldDataFilter = nil
358
359 self:destroyMissionMap()
360
361 if g_addTestCommands then
362 removeConsoleCommand("gsGenerateFieldMission")
363 removeConsoleCommand("gsMissionLoadAllVehicles")
364 removeConsoleCommand("gsMissionHarvestField")
365 end
366
367 MissionManager:superClass().unloadMapData(self)
368end

saveToXMLFile

Description
Write field mission data to savegame file
Definition
saveToXMLFile(string xmlFilename)
Arguments
stringxmlFilenamefile path
Return Values
booleantrueif loading was successful else false
Code
374function MissionManager:saveToXMLFile(xmlFilename)
375 local xmlFile = createXMLFile("missionXML", xmlFilename, "missions")
376
377 if xmlFile ~= nil then
378 for k, mission in ipairs(self.missions) do
379 local missionKey = string.format("missions.mission(%d)", k - 1)
380
381 setXMLString(xmlFile, missionKey.."#type", mission.type.name)
382 if mission.activeMissionId ~= nil then
383 setXMLInt(xmlFile, missionKey.."#activeId", mission.activeMissionId)
384 end
385
386 mission:saveToXMLFile(xmlFile, missionKey)
387 end
388
389 saveXMLFile(xmlFile)
390 delete(xmlFile)
391 end
392
393 return false
394end

loadFromXMLFile

Description
Load fieldjob data from xml savegame file
Definition
loadFromXMLFile(string filename)
Arguments
stringfilenamexml filename
Code
399function MissionManager:loadFromXMLFile(xmlFilename)
400 if xmlFilename == nil then
401 return false
402 end
403
404 local xmlFile = loadXMLFile("missionsXML", xmlFilename)
405 if not xmlFile then
406 return false
407 end
408
409 -- Active missions
410 local i = 0
411 while true do
412 local key = string.format("missions.mission(%d)", i)
413 if not hasXMLProperty(xmlFile, key) then
414 break
415 end
416
417 local missionTypeName = getXMLString(xmlFile, key.."#type")
418 local missionType = self:getMissionType(missionTypeName)
419
420 if missionType ~= nil then
421 local mission = missionType.class:new(true, g_client ~= nil)
422 mission.type = missionType
423 mission.activeMissionId = getXMLInt(xmlFile, key .. "#activeId") -- can be nil
424 self:assignGenerationTime(mission)
425
426 if not mission:loadFromXMLFile(xmlFile, key) then
427 mission:delete()
428 else
429 if mission.field ~= nil then
430 self.fieldToMission[mission.field.fieldId] = mission
431 end
432
433 if mission.type.category == MissionManager.CATEGORY_TRANSPORT then
434 self.numTransportMissions = self.numTransportMissions + 1
435 end
436
437 mission:register()
438 table.insert(self.missions, mission)
439 end
440 else
441 print("Warning: Mission type '" .. tostring(missionType) .. "' not found!")
442 end
443
444 i = i + 1
445 end
446
447 -- If there are any active missions, find any associated vehicles
448 if table.getn(self.missions) > 0 then
449 for _, vehicle in pairs(g_currentMission.vehicles) do
450 if vehicle.activeMissionId ~= nil then
451 local mission = self:getMissionForActiveMissionId(vehicle.activeMissionId)
452 if mission ~= nil and mission.vehicles ~= nil then
453 table.insert(mission.vehicles, vehicle)
454 end
455 end
456 end
457 end
458
459 delete(xmlFile)
460
461 return true
462end

delete

Description
Deletes field mission manager
Definition
delete()
Code
466function MissionManager:delete()
467end

update

Description
Updates field mission ownage data from xml savegame file
Definition
update(string filename)
Arguments
stringfilenamexml filename
Code
472function MissionManager:update(dt)
473 if g_currentMission:getIsServer() then
474 self.generationTimer = self.generationTimer - g_currentMission.missionInfo.timeScale * dt
475
476 self:updateMissions(dt)
477
478 if table.getn(self.missions) < MissionManager.MAX_MISSIONS and self.generationTimer < g_time then
479 self:generateMissions(dt)
480
481 -- Limit generation
482 self.generationTimer = MissionManager.MISSION_GENERATION_INTERVAL
483 end
484 end
485end

getTransportMissionConfig

Description
Get mission configuration given the name
Definition
getTransportMissionConfig()

getTransportMissionConfigById

Description
Get a mission config given an ID. Used by TransportMission:readStream
Definition
getTransportMissionConfigById()

hasFarmActiveMission

Description
Get whether given farm has an active mission
Definition
hasFarmActiveMission()

startMission

Description
Start given mission for a farm.
Definition
startMission()

cancelMission

Description
Cancel mission: sets it to finished without success
Definition
cancelMission()

deleteMission

Description
Delete a mission
Definition
deleteMission()

dismissMission

Description
On a client it sends an event instead
Definition
dismissMission()

getActiveMissions

Description
Get a list of active missions
Definition
getActiveMissions()

getIsAnyMissionActive

Description
Get whether any mission is currently running
Definition
getIsAnyMissionActive()

canMissionStillRun

Description
Test whether the given mission is still able to run
Definition
canMissionStillRun()

addTransportMissionTrigger

Description
Add a new transport trigger. Requires triggerId and index properties.
Definition
addTransportMissionTrigger()

removeTransportMissionTrigger

Description
Remove a transport trigger.
Definition
removeTransportMissionTrigger()

generateNewFieldMission

Description
Generate a mission for given field. Returns nil if field already has an active mission
Definition
generateNewFieldMission()

assignGenerationTime

Description
Generation time is used for reliably sorting
Definition
assignGenerationTime()

getRandomVehicleGroup

Description
Get a randomly chosen group of vehicles fitting for given mission type and field size
Definition
getRandomVehicleGroup(missionType type, fieldSize size)
Arguments
missionTypetypeof mission (string)
fieldSizesizeof field: 'SMALL', 'MEDIUM', 'LARGE'
Return Values
Listofvehicles. Each element is a table with filanema and configuration properties.
Reward

getVehicleGroupFromIdentifier

Description
Used on the client. Make sure it never crashes on nil (patches)
Definition
getVehicleGroupFromIdentifier()

getFreeActiveMissionId

Description
Get a free activeMissionId, used for active missions only.
Definition
getFreeActiveMissionId()

validateMissionOnField

Description
Validate missions on given field, after something happened to the field (event)
Definition
validateMissionOnField()

getMissionMapValue

Description
Get a value at given world coordinates
Definition
getMissionMapValue()

getMissionForActiveMissionId

Description
Get the mission associated with the activeMissionId
Definition
getMissionForActiveMissionId()

MixerWagonHUDExtension

Description
Custom HUD drawing extension for MixerWagon.
-- Displays the fill levels of the mixer wagon.
--@category GUI

new

Description
Create a new instance of MixerWagonHUDExtension.
Definition
new(table vehicle, float uiScale, table uiTextColor, float uiTextSize)
Arguments
tablevehicleVehicle which has the specialization required by a sub-class
floatuiScaleCurrent UI scale
tableuiTextColorHUD text drawing color as an RGBA array
floatuiTextSizeHUD text size
Return Values
tableinstanceinstance of object

canDraw

Description
Determine if the HUD extension should be drawn.
Definition
canDraw()
Return Values
booleantrueif loading was successful else false

getDisplayHeight

Description
Get this HUD extension's display height.
Definition
getDisplayHeight()
Return Values
tableinstanceinstance of object
floatDisplayheight in screen space

draw

Description
Draw mixing ratio information for a mixing wagon when it is active.
Definition
draw(float leftPosX, float rightPosX, float posY)
Arguments
floatleftPosXLeft input help panel column start position
floatrightPosXRight input help panel column start position
floatposYCurrent input help panel drawing vertical offset
Return Values
booleantrueif loading was successful else false
floatModifiedinput help panel drawing vertical offset

ModHubCategoriesFrame

Description
ModHub categories frame
-- Displays categories.
--@category GUI

new

Description
Create a new ModHubCategoriesFrame instance.
Definition
new(table subclass_mt)
Arguments
tablesubclass_mt[optional] Meta table of subclass

initialize

Description
Initialize with categories to be displayed.
Categories must be provided as an array of tables like {id=<id>, iconFilename=<path>, label=<text>}. This will add
a category element per entry to the display list.
Definition
initialize(table categories, function categoryClickedCallback, table headerIconUVs, string headerText)
Arguments
tablecategoriesCategory definitions array
functioncategoryClickedCallbackNotification callback for category activation(click/enter), signature: function(selectedId, baseCategoryIconUVs, baseCategoryLabel, clickedCategoryLabel)
tableheaderIconUVsUV coordinates of the header icon to display
stringheaderTextHeader text to display

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
floatnearCoCRadiusNear circle of confusion radius (nearCoCRadius = 0 means no near blur (pinhole camera))
floatnearBlurEndDistance from the camera center where near blur ends
floatfarCoCRadiusFar circle of confusion radius (farCoCRadius = 0 means no far blur (pinhole camera))
floatfarBlurStartDistance from the camera center where far blur starts
floatfarBlurEndDistance from the camera center where far blur ends

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()

updateScrollButtons

Description
Update scroll button visibility based on the currently visible list items.
Definition
updateScrollButtons()

onClickCategory

Description
Handle a click / button activation on a category.
Definition
onClickCategory()

onDoubleClickCategory

Description
Handle a double click on a category.
Definition
onDoubleClickCategory()

onCategorySelected

Description
Handle navigation selection of a category element.
Definition
onCategorySelected()
Return Values
booleanisAllowedstate change is allowed

onClickLeft

Description
Handle click on left navigation button.
Definition
onClickLeft()
Return Values
tableinstanceinstance of object

onClickRight

Description
Handle click on right navigation button.
Definition
onClickRight()
Return Values
booleantrueif loading was successful else false

onScroll

Description
Handle a list scrolling event.
Definition
onScroll()
Return Values
booleansuccesssuccess

ModHubDetailsFrame

Description
Shop items frame for the in-game menu shop.
-- Displays purchasable items of a common category in a horizontal list layout.
--@category GUI

new

Description
Create a new ModHubDetailsFrame instance.
Definition
new(table subclass_mt)
Arguments
tablesubclass_mt[optional] Meta table of subclass
Return Values
integerfillTypeIndexthe fillType index

setCategory

Description
Set the category to display.
Definition
setCategory()
Return Values
tablefillTypethe fillType object

setModInfo

Description
Set an ordered array of ShopDisplayItem instances to display in this frame.
Definition
setModInfo()
Return Values
tablefillTypeslist of fillTypes

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
tablefillTypeCategoryfillType category object

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()
Return Values
tablesuccesstrue if added else false

ModHubItemsFrame

Description
Shop items frame for the in-game menu shop.
-- Displays purchasable items of a common category in a horizontal list layout.
--@category GUI

new

Description
Create a new ModHubItemsFrame instance.
Definition
new(table subclass_mt)
Arguments
tablesubclass_mt[optional] Meta table of subclass
Return Values
tablefillTypeslist of fillTypes

setItemClickCallback

Description
Set the callback to use when an item is activated (for buying or selling).
Definition
setItemClickCallback()
Return Values
tablefillTypesfill types

setItemSelectCallback

Description
Set the callback to use when an item is selected in the view.
Definition
setItemSelectCallback()
Return Values
integerconverterIndexindex of converterIndex

setCategory

Description
Set the category to display.
Definition
setCategory()
Return Values
tableconverterDataconverter data

getMainElementSize

Description
Get the frame's main content element's screen size.
Definition
getMainElementSize()
Return Values
tablesamplesample

getMainElementPosition

Description
Get the frame's main content element's screen position.
Definition
getMainElementPosition()
Return Values
tableinstanceinstance of object

updateScrollButtons

Description
Update scroll button visibility based on the currently visible list items.
Definition
updateScrollButtons()
Return Values
booleantrueif loading was successful else false

onClickItem

Description
Handle a click / button activation on an item.
Definition
onClickItem()
Return Values
booleansuccesssuccess

onDoubleClickItem

Description
Handle a double-click on an item.
Definition
onDoubleClickItem()
Return Values
tablefruitTypefruitType type object

onClickLeft

Description
Handle click on left navigation button.
Definition
onClickLeft()
Return Values
tablefruitthe fruit object

onClickRight

Description
Handle click on right navigation button.
Definition
onClickRight()
Return Values
tablefruitthe fruit object

onItemSelected

Description
Handle selection of an item.
Definition
onItemSelected()
Return Values
tablefruitTypesa list of fruitTypes

ModHubScreen

Description
Mode

new

Description
Create a new instance of ModHubScreen.
Definition
new(table target, table custom_mt, table messageCenter, table l10n, table inputManager, table modHubController, bool isConsoleVersion)
Arguments
tabletargetCallback target
tablecustom_mtSub-class meta table
tablemessageCenterMessageCenter reference
tablel10nI18N reference for text localization
tableinputManagerInputBinding reference
tablemodHubControllermodHubController reference
boolisConsoleVersionIf true, the game is running on a console
Return Values
tablefruitTypeCategoryfruitType category object

reset

Description
Reset menu state (and all pages).
Definition
reset()
Return Values
tablesuccesstrue if added else false

clickBackCallback

Description
Button function for backing out of the menu.
Definition
clickBackCallback()
Return Values
tablefruitTypeslist of fruitTypes

clearMenuButtonActions

Description
Clear menu button actions, events and callbacks.
Definition
clearMenuButtonActions()
Return Values
tablefruitTypesfruit types

assignMenuButtonInfo

Description
Assign menu button information to the in-game menu buttons.
Definition
assignMenuButtonInfo()
Return Values
tablefillTypesfill types

onMenuActionClick

Description
Handle a menu action click by calling one of the menu button callbacks.
Definition
onMenuActionClick()
Return Values
tablefillTypesfill types
boolTrueif no callback was present and no action was taken, false otherwise

onClickOk

Description
Handle menu confirmation input event.
Definition
onClickOk()
Return Values
floatliterPerSqmliter per sqm

onClickBack

Description
Handle menu back input event.
Definition
onClickBack()
Return Values
integerconverterIndexindex of converterIndex

onClickCancel

Description
Handle menu cancel input event.
Bound to quite the game to the main menu.
Definition
onClickCancel()
Return Values
tableconverterDataconverter data

onClickActivate

Description
Handle menu active input event.
Bound to save the game.
Definition
onClickActivate()
Return Values
tableinstanceinstance of object

updateButtonsPanel

Description
Update the buttons panel when a given page is visible.
Definition
updateButtonsPanel()
Return Values
booleantrueif loading was successful else false

makeSelfCallback

Description
Make a callback which encloses the self reference and handles arbitrary arguments afterwards.
Definition
makeSelfCallback()
Return Values
tablegameplayHintGroupa random gameplay hint group

MultiTextOptionElement

Description
Multiple choice text element.
-- This element requires a specific configuration setup to be properly used: In the configuration, it must contain the
following child elements in this order: 1. ButtonElement, 2. ButtonElement, 3. TextElement, 4. TextElement. The first
three elements are mandatory, as they are the buttons to change this element's value and the label which displays the
value. The fourth (text) element is optional and used as a header label for this element if defined.
--@category GUI
--@xmlConfig GuiElement#wrap bool [optional] If false, values will not cycle when the end or start of the value list is reached.

disableButtonSounds

Description
Disable automatic playing of sound samples in child buttons.
Definition
disableButtonSounds()

inputLeft

Description
Trigger a "left" input.
Definition
inputLeft(isShoulderButton If)
Arguments
isShoulderButtonIftrue, assume a shoulder button input (PC or console)

inputRight

Description
Trigger a "right" input.
Definition
inputRight(isShoulderButton If)
Arguments
isShoulderButtonIftrue, assume a shoulder button input (PC or console)

MultiValueTween

Description
Tween class which handles multiple values at the same time.
-- Start and end values must be passed in as arrays. The setter function must be able to handle as many arguments as
there were entries in the start and end values arrays: setter called as function(unpack(values)).
--@category GUI

new

Description
Create a new Tween.
Definition
new(table subClass, function setterFunction, table startValues, table endValues, float duration)
Arguments
tablesubClassSubclass metatable for inheritance
functionsetterFunctionValues setter function. Signature: callback(v1, ..., vn) or callback(target, v1, ..., vn).
tablestartValuesOriginal values
tableendValuesTarget values
floatdurationDuration of tween in milliseconds

setTarget

Description
Set a callback target for this tween.
If a target has been set, the setter function must support receiving the target as its first argument.
Definition
setTarget()

tweenValue

Description
Get the current tween value.
Definition
tweenValue()

applyValue

Description
Apply a value via the setter function.
Definition
applyValue()

Overlay

Description
Image display overlay.
-- This class is used to display textures or usually parts thereof as rectangular panels in the UI or on the HUD.
Example usages include button icons, showing images in the main menu or drawing the in-game map.
--@category GUI

new

Description
Create a new Overlay.
Definition
new(overlayFilename File, x Screen, y Screen, width Display, height Display)
Arguments
overlayFilenameFilepath of the source texture
xScreenposition x
yScreenposition y
widthDisplaywidth
heightDisplayheight

delete

Description
Delete this overlay.
Releases the texture file handle.
Definition
delete()

setColor

Description
Set this overlay's color.
The color is multiplied with the texture color. For no modification of the texture color, use full opaque white,
i.e. {1, 1, 1, 1}.
Definition
setColor(r Red, g Green, b Blue, a Alpha)
Arguments
rRedchannel
gGreenchannel
bBluechannel
aAlphachannel

setUVs

Description
Set this overlay's UVs which define the area to be displayed within the target texture.
Definition
setUVs(uvs UV)
Arguments
uvsUVcoordinates in the form of {u1, v1, u2, v2, u3, v3, u4, v4}

setPosition

Description
Set this overlay's position.
Definition
setPosition()

getPosition

Description
Get this overlay's position.
Definition
getPosition()
Return Values
floatXposition in screen space
floatYposition in screen space

setDimension

Description
Set this overlay's width and height.
Either value can be omitted (== nil) for no change.
Definition
setDimension()

resetDimensions

Description
Reset width, height and scale to initial values set in the constructor.
Definition
resetDimensions()

setInvertX

Description
Set horizontal flipping state.
Definition
setInvertX(invertX If)
Arguments
invertXIftrue, will set the overlay to display its image flipped horizontally

setRotation

Description
Set this overlay's rotation.
Definition
setRotation(rotation Rotation, centerX Rotation, centerY Rotation)
Arguments
rotationRotationin radians
centerXRotationpivot X position offset from overlay position in screen space
centerYRotationpivot Y position offset from overlay position in screen space

setScale

Description
Set this overlay's scale.
Multiplies the scale values with the initial dimensions and sets those as the current dimensions.
Definition
setScale(float scaleWidth, float scaleHeight)
Arguments
floatscaleWidthWidth scale factor
floatscaleHeightHeight scale factor

getScale

Description
Get this overlay's scale values.
Definition
getScale()
Return Values
floatWidthscale factor
floatHeightscale factor

render

Description
Render this overlay.
Definition
render()

setAlignment

Description
Set this overlay's alignment.
Definition
setAlignment(vertical Vertical, horizontal Horizontal)
Arguments
verticalVerticalalignment value, one of Overlay.ALIGN_VERTICAL_[...]
horizontalHorizontalalignment value, one of Overlay.ALIGN_HORIZONTAL_[...]

setIsVisible

Description
Set this overlay's visibility.
Definition
setIsVisible()

setImage

Description
Set a different image for this overlay.
The previously targeted image's handle will be released.
Definition
setImage(overlayFilename File)
Arguments
overlayFilenameFilepath to new target image

PagingElement

Description
Paging control element.
-- Organizes grouped elements into pages to be displayed one at a time. To set it up, one defines several
same-sized container elements (e.g. bare GuiElement) as children of the PagingElement to hold the pages' contents.
The pages should be given #name properties which are resolved to a localization text with a prepended "ui_" prefix.
On loading, any named child element of this PagingElement will be added as a page.
--@category GUI
--@xmlConfig GuiElement#onPageChange callback [optional] onPageChangeCallback(pageIndex, pageMappingIndex, element) Called when the page changes. Receives the current index in all pages, the current index in all enabled pages and this element.

setPage

Description
Set the current page index.
Indices are based on mapped pages, which are all available and visible pages added to this element.
Definition
setPage(pageMappingIndex Index)
Arguments
pageMappingIndexIndexof page in page mappings
Return Values
boolTrueif the page changed

getNextID

Description
Get a new page ID based on an internal counter.
Definition
getNextID()

addPage

Description
Add a new page.
Definition
addPage(id Page, element Page, title Page, index [optional])
Arguments
idPageID
elementPagecontainer GuiElement
titlePagetitle for displaying
index[optional]Insertion index for page. If undefined or outside of valid range, will add the page at the end.

getVisiblePagesCount

Description
Get the number of currently visible pages.
Definition
getVisiblePagesCount()

getPageIdByElement

Description
Get a page ID by the page container element reference.
Definition
getPageIdByElement(element Page)
Arguments
elementPagecontainer GuiElement instance
Return Values
Page

getPageElementByIndex

Description
Get a page container element by page index.
Definition
getPageElementByIndex(pageIndex Index)
Arguments
pageIndexIndexof page in all (incl. disabled and invisible) pages
Return Values
PagecontainerGuiElement instance

getPageIndexByElement

Description
Get the page index in this element's page array for a given element reference.
Definition
getPageIndexByElement(table element)
Arguments
tableelementGuiElement instance
Return Values
intPageindex

getPageMappingIndexByElement

Description
Get the page index in this elements page mapping array (visible pages) for a given element reference.
Definition
getPageMappingIndexByElement(table element)
Arguments
tableelementGuiElement instance
Return Values
intPagemapping index

removePageByElement

Description
Remove a page, identified by its page container element, from this element.
The method only removes the page from the display collection. Callers must take care of the page element's clean-up,
e.g. removing it from the element hierarchy.
Definition
removePageByElement(pageElement Page)
Arguments
pageElementPagecontainer element

getCurrentPageId

Description
Get the page ID of the currently displayed page.
Definition
getCurrentPageId()

getPageMappingIndex

Description
Get the index of a page in the page mappings (only visible pages) by page ID.
Definition
getPageMappingIndex()

getIsPageDisabled

Description
Determine if a page, identified by page ID, is disabled.
Definition
getIsPageDisabled()

getPageById

Description
Get a page by ID.
Definition
getPageById()

setPageIdDisabled

Description
Set a page's disabled state.
Definition
setPageIdDisabled(pageId Page, disabled True)
Arguments
pageIdPageID
disabledTruefor disabled, false for enabled

getPageTitles

Description
Get page titles of all pages which were visible at the latest call to updatePageMapping()
Definition
getPageTitles()

Placeable

Description
Base Class for placeables
-- Note about terrain modification on placement:
If terrain modification is enabled using the placeable.leveling#requireLeveling attribute, the configuration needs
at least one leveling area to be defined (ramps are optional). These areas represent parallelograms which are passed
to terrain modification functions. They are defined by start, width and height nodes which in this case should be
set up to form rectangular shapes. For the best results, create a new transform group for each area at the starting
positions and add separate nodes for the three defining points in the placeable object I3D file.
--@category Placeables
--@xmlConfig placeable.filename string File name of associated I3D file

onCreateGlowMaterial

Description
On create glow material
Definition
onCreateGlowMaterial(empty empty, integer id)
Arguments
emptyemptyempty
integeridid of node
Code
90function Placeable.onCreateGlowMaterial(_, id)
91 if getHasShaderParameter(id, "colorScale") then
92 Placeable.GLOW_MATERIAL = getMaterial(id, 0)
93 end
94end

new

Description
Creating placeable
Definition
new(boolean isServer, boolean isClient, table customMt)
Arguments
booleanisServeris server
booleanisClientis client
tablecustomMtcustom metatable
Return Values
tableinstanceInstance of object
Code
106function Placeable:new(isServer, isClient, customMt)
107 local self = Object:new(isServer, isClient, customMt or Placeable_mt)
108 self.nodeId = 0
109
110 self.useRandomYRotation = false
111 self.useManualYRotation = false
112 self.placementSizeX = 1
113 self.placementSizeZ = 1
114 self.placementTestSizeX = 1
115 self.placementTestSizeZ = 1
116 self.requireLeveling = false
117 self.maxSmoothDistance = 3
118 self.maxSlope = MathUtil.degToRad(45)
119 self.maxEdgeAngle = MathUtil.degToRad(45)
120 self.smoothingGroundType = nil
121
122 self.triggerMarkers = {}
123 self.clearAreas = {}
124 self.levelAreas = {}
125 self.rampAreas = {}
126 self.foliageAreas = {}
127 self.samples = {}
128 self.pickObjects = {}
129 self.animatedObjects = {}
130 self.triggerMarkers = {}
131 self.mapHotspots = {}
132 self.isolated = false
133 self.isDeleted = false
134 self.useMultiRootNode = false
135 self.price = 0
136 self.age = 0
137 self.isInPreviewMode = nil
138 self.placementPositionSnapSize = 0
139 self.placementRotationSnapAngle = 0
140
141 -- defines that a placeable is placed on a map directly, and with a unique ID
142 self.mapBoundId = nil
143
144 registerObjectClassName(self, "Placeable")
145 return self
146end

delete

Description
Deleting placeable
Definition
delete()
Code
150function Placeable:delete()
151 self.isDeleted = true
152 if self.i3dFilename ~= nil then
153 g_i3DManager:releaseSharedI3DFile(self.i3dFilename, nil, true)
154 end
155
156 for _, node in ipairs(self.triggerMarkers) do
157 g_currentMission:removeTriggerMarker(node)
158 end
159
160 if #self.rampAreas > 0 then
161 for _, area in pairs(self.rampAreas) do
162 if area.previewShape then
163 g_i3DManager:releaseSharedI3DFile(Placeable.RAMP_PREVIEW_PATH, nil, true)
164 end
165 end
166 end
167
168 for _, animatedObject in ipairs(self.animatedObjects) do
169 animatedObject:delete()
170 end
171
172 for _, hotspot in ipairs(self.mapHotspots) do
173 g_currentMission.hud:removeMapHotspot(hotspot)
174 hotspot:delete()
175 end
176
177 if g_currentMission ~= nil and g_currentMission.environment ~= nil then
178 g_currentMission.environment:removeDayChangeListener(self)
179 g_currentMission.environment:removeWeatherChangeListener(self)
180 g_currentMission.environment:removeHourChangeListener(self)
181 end
182
183 unregisterObjectClassName(self)
184 g_currentMission:removeItemToSave(self)
185 g_currentMission:removePlaceable(self)
186 for _, node in pairs(self.pickObjects) do
187 g_currentMission:removeNodeObject(node)
188 end
189
190 if self.nodeId ~= 0 and entityExists(self.nodeId) then
191 self:setCollisionMask(self.nodeId, 0)
192 setVisibility(self.nodeId, false)
193 else
194 self.nodeId = 0
195 end
196
197 if self.isClient then
198 g_soundManager:deleteSamples(self.samples)
199 end
200
201 g_currentMission:removeOwnedItem(self)
202
203 g_currentMission:addPlaceableToDelete(self, 300)
204 Placeable:superClass().delete(self)
205end

deleteFinal

Description
Deleting placeable final
Definition
deleteFinal()
Code
209function Placeable:deleteFinal()
210 if self.nodeId ~= 0 then
211 delete(self.nodeId)
212 self.nodeId = 0
213 end
214end

setCollisionMask

Description
Set collision mask of node and its children
Definition
setCollisionMask(integer nodeId, integer mask)
Arguments
integernodeIdid of node
integermaskcollision mask
Code
220function Placeable:setCollisionMask(nodeId, mask)
221 setCollisionMask(nodeId, mask)
222 local numChildren = getNumOfChildren(nodeId)
223 for i=0,numChildren-1 do
224 local childId = getChildAt(nodeId, i)
225 self:setCollisionMask(childId, mask)
226 end
227end

getIsPlayerInRange

Description
Returns true if player is in range
Definition
getIsPlayerInRange(float distance, table player)
Arguments
floatdistancedistance
tableplayerplayer
Return Values
booleanisInRangeis in range
Code
234function Placeable:getIsPlayerInRange(distance, player)
235 if self.nodeId ~= 0 then
236 distance = Utils.getNoNil(distance, 10)
237 if player == nil then
238 for _, player in pairs(g_currentMission.players) do
239 if self:isInActionDistance(player, self.nodeId, distance) then
240 return true, player
241 end
242 end
243 else
244 return self:isInActionDistance(player, self.nodeId, distance), player
245 end
246 end
247 return false, nil
248end

isInActionDistance

Description
Returns true if player is in range
Definition
isInActionDistance(table player, integer refNode, float distance)
Arguments
tableplayerplayer
integerrefNodeid of reference node
floatdistancedistance
Return Values
booleanisInRangeis in range
Code
256function Placeable:isInActionDistance(player, refNode, distance)
257 local x,_,z = getWorldTranslation(refNode)
258 local px,_,pz = getWorldTranslation(player.rootNode)
259 local dx,dz = px-x, pz-z
260 if dx*dx + dz*dz < distance*distance then
261 return true
262 end
263
264 return false
265end

readStream

Description
Called on client side on join
Definition
readStream(integer streamId, table connection)
Arguments
integerstreamIdstream ID
tableconnectionconnection
Code
271function Placeable:readStream(streamId, connection)
272 Placeable:superClass().readStream(self, streamId, connection)
273 if connection:getIsServer() then
274 local configFileName = NetworkUtil.convertFromNetworkFilename(streamReadString(streamId))
275 local x=streamReadFloat32(streamId)
276 local y=streamReadFloat32(streamId)
277 local z=streamReadFloat32(streamId)
278 local rx=NetworkUtil.readCompressedAngle(streamId)
279 local ry=NetworkUtil.readCompressedAngle(streamId)
280 local rz=NetworkUtil.readCompressedAngle(streamId)
281 local isNew = self.configFileName == nil
282 if isNew then
283 self:load(configFileName, x,y,z, rx,ry,rz, false, false)
284 end
285 self.age = streamReadUInt16(streamId)
286 self.price = streamReadInt32(streamId)
287
288 if isNew then
289 self:finalizePlacement()
290 end
291
292 for _, animatedObject in ipairs(self.animatedObjects) do
293 local animatedObjectId = NetworkUtil.readNodeObjectId(streamId)
294 animatedObject:readStream(streamId, connection)
295 g_client:finishRegisterObject(animatedObject, animatedObjectId)
296 end
297 end
298end

writeStream

Description
Called on server side on join
Definition
writeStream(integer streamId, table connection)
Arguments
integerstreamIdstream ID
tableconnectionconnection
Code
304function Placeable:writeStream(streamId, connection)
305 Placeable:superClass().writeStream(self, streamId, connection)
306 if not connection:getIsServer() then
307 streamWriteString(streamId, NetworkUtil.convertToNetworkFilename(self.configFileName))
308 local x,y,z = getTranslation(self.nodeId)
309 local x_rot,y_rot,z_rot = getRotation(self.nodeId)
310 streamWriteFloat32(streamId, x)
311 streamWriteFloat32(streamId, y)
312 streamWriteFloat32(streamId, z)
313 NetworkUtil.writeCompressedAngle(streamId, x_rot)
314 NetworkUtil.writeCompressedAngle(streamId, y_rot)
315 NetworkUtil.writeCompressedAngle(streamId, z_rot)
316 streamWriteUInt16(streamId, self.age)
317 streamWriteInt32(streamId, self.price)
318
319 for _, animatedObject in ipairs(self.animatedObjects) do
320 NetworkUtil.writeNodeObjectId(streamId, NetworkUtil.getObjectId(animatedObject))
321 animatedObject:writeStream(streamId, connection)
322 g_server:registerObjectInStream(connection, animatedObject)
323 end
324 end
325end

createNode

Description
Create node
Definition
createNode(string i3dFilename)
Arguments
stringi3dFilenamei3d file name
Return Values
booleansuccesssuccess
Code
362function Placeable:createNode(i3dFilename)
363 self.i3dFilename = i3dFilename
364 local nodeRoot = g_i3DManager:loadSharedI3DFile(i3dFilename, nil, false, false)
365 if nodeRoot == 0 then
366 return false
367 end
368
369 if self.useMultiRootNode then
370 link(getRootNode(), nodeRoot)
371 self.nodeId = nodeRoot
372 else
373 local nodeId = getChildAt(nodeRoot, 0)
374 if nodeId == 0 then
375 delete(nodeRoot)
376 return false
377 end
378 link(getRootNode(), nodeId)
379 delete(nodeRoot)
380 self.nodeId = nodeId
381 end
382
383 return true
384end

setPreviewMaterials

Description
Sets the preview material to all nodes in the placeable
Definition
setPreviewMaterials(integer node, table nodeTable)
Arguments
integernodeid of node
tablenodeTabletable to save the nodes
Code
390function Placeable:setPreviewMaterials(node, nodeTable)
391 if getHasClassId(node, ClassIds.SHAPE) then
392 nodeTable[node] = node
393 setMaterial(node, Placeable.GLOW_MATERIAL, 0)
394 end
395
396 local numChildren = getNumOfChildren(node)
397 for i=0, numChildren-1 do
398 self:setPreviewMaterials(getChildAt(node, i), nodeTable)
399 end
400end

setPlaceablePreviewState

Description
Set placable preview state
Definition
setPlaceablePreviewState(int state)
Arguments
intstatePlacement state [Placeable.PREVIEW_STATE.CHECKING | Placeable.PREVIEW_STATE.VALID | Placeable.PREVIEW_STATE.INVALID]
Code
405function Placeable:setPlaceablePreviewState(state)
406 if not self.isInPreviewMode then
407 self.isInPreviewMode = true
408
409 self.previewGlowingNodes = {}
410 if Placeable.GLOW_MATERIAL ~= nil then
411 -- replace materials with glowing material
412 self:setPreviewMaterials(self.nodeId, self.previewGlowingNodes)
413
414 -- load preview shapes for ramps
415 for _, area in pairs(self.rampAreas) do
416 local rampNode = g_i3DManager:loadSharedI3DFile(Placeable.RAMP_PREVIEW_PATH)
417 if rampNode ~= 0 then
418 link(area.root, rampNode) -- link the ramp root to the area -> can rotate the entire area hierarchy for preview
419 area.previewNode = rampNode
420
421 local rampRootTransform = getChildAt(rampNode, 0)
422 local rampShape = getChildAt(rampRootTransform, 0)
423 area.previewShape = rampShape
424
425 setMaterial(rampShape, Placeable.GLOW_MATERIAL, 0)
426
427 -- scale the ramp preview to the area dimensions, this assumes a rectangular area
428 local scaleX, _, scaleZ = getScale(rampShape)
429 local startX, startY, startZ = getWorldTranslation(area.start)
430 local widthX, widthY, widthZ = getWorldTranslation(area.width)
431 local heightX, heightY, heightZ = getWorldTranslation(area.height)
432
433 local width = MathUtil.vector3Length(widthX - startX, widthY - startY, widthZ - startZ)
434 local height = MathUtil.vector3Length(heightX - startX, heightY - startY, heightZ - startZ)
435
436 setScale(rampShape, width, Placeable.RAMP_PREVIEW_THICKNESS, height)
437 end
438 end
439 end
440 end
441 if Placeable.GLOW_MATERIAL ~= nil then
442 local color = Placeable.PREVIEW_COLOR[state]
443 for node in pairs(self.previewGlowingNodes) do
444 setShaderParameter(node, "colorScale", color[1], color[2], color[3], color[4], false)
445 end
446
447 local rampColor = Placeable.PREVIEW_RAMP_COLOR[state]
448 for _, area in pairs(self.rampAreas) do
449 if area.previewShape ~= nil then
450 setShaderParameter(area.previewShape, "colorScale", rampColor[1], rampColor[2], rampColor[3], rampColor[4], false)
451 end
452 end
453 end
454end

load

Description
Load placeable
Definition
load(string xmlFilename, float x, float y, float z, float rx, float ry, float rz, boolean initRandom)
Arguments
stringxmlFilenamexml file name
floatxx world position
floatyz world position
floatzz world position
floatrxrx world rotation
floatryry world rotation
floatrzrz world rotation
booleaninitRandominitialize random
Return Values
booleansuccesssuccess
Code
467function Placeable:load(xmlFilename, x,y,z, rx,ry,rz, initRandom)
468 self.configFileName = xmlFilename
469 self.customEnvironment, self.baseDirectory = Utils.getModNameAndBaseDirectory(xmlFilename)
470
471 local xmlFile = loadXMLFile("TempXML", xmlFilename)
472 if xmlFile == 0 then
473 return false
474 end
475 local i3dFilename = getXMLString(xmlFile, "placeable.filename")
476 self.placementSizeX = Utils.getNoNil(getXMLFloat(xmlFile, "placeable.placement#sizeX"), self.placementSizeX)
477 self.placementSizeZ = Utils.getNoNil(getXMLFloat(xmlFile, "placeable.placement#sizeZ"), self.placementSizeZ)
478 self.placementTestSizeX = Utils.getNoNil(getXMLFloat(xmlFile, "placeable.placement#testSizeX"), self.placementSizeX)
479 self.placementTestSizeZ = Utils.getNoNil(getXMLFloat(xmlFile, "placeable.placement#testSizeZ"), self.placementSizeZ)
480 self.useRandomYRotation = Utils.getNoNil(getXMLBool(xmlFile, "placeable.placement#useRandomYRotation"), self.useRandomYRotation)
481 self.useManualYRotation = Utils.getNoNil(getXMLBool(xmlFile, "placeable.placement#useManualYRotation"), self.useManualYRotation)
482 self.alignToWorldY = Utils.getNoNil(getXMLBool(xmlFile, "placeable.placement#alignToWorldY"), true)
483 self.placementPositionSnapSize = math.abs(Utils.getNoNil(getXMLFloat(xmlFile, "placeable.placement#placementPositionSnapSize"), 0.0))
484 self.placementRotationSnapAngle = math.rad(math.abs(Utils.getNoNil(getXMLFloat(xmlFile, "placeable.placement#placementRotationSnapAngle"), 0.0)))
485
486 self.incomePerHour = getXMLFloat(xmlFile, "placeable.incomePerHour" .. g_currentMission.missionInfo.difficulty)
487 -- fallback for old single value format
488 if self.incomePerHour == nil then
489 self.incomePerHour = Utils.getNoNil(getXMLFloat(xmlFile, "placeable.incomePerHour"), 0)
490 if g_currentMission.missionInfo.difficulty == 1 then
491 self.incomePerHour = self.incomePerHour * 1.5
492 elseif g_currentMission.missionInfo.difficulty == 3 then
493 self.incomePerHour = self.incomePerHour / 1.5
494 end
495 end
496
497 local storeItem = g_storeManager:getItemByXMLFilename(self.configFileName)
498 if storeItem ~= nil then
499 if self.price == 0 or self.price == nil then
500 self.price = StoreItemUtil.getDefaultPrice(storeItem)
501 end
502
503 if g_currentMission ~= nil and storeItem.canBeSold then
504 g_currentMission.environment:addDayChangeListener(self)
505 end
506 end
507
508 if i3dFilename == nil then
509 delete(xmlFile)
510 return false
511 end
512 self.i3dFilename = Utils.getFilename(i3dFilename, self.baseDirectory)
513
514 if not self:createNode(self.i3dFilename) then
515 delete(xmlFile)
516 return false
517 end
518 self:initPose(x,y,z, rx,ry,rz, initRandom)
519
520 if hasXMLProperty(xmlFile, "placeable.dayNightObjects") then
521 local i = 0
522 while true do
523 local key = string.format("placeable.dayNightObjects.dayNightObject(%d)", i)
524 if not hasXMLProperty(xmlFile, key) then
525 break
526 end
527
528 local node = I3DUtil.indexToObject(self.nodeId, getXMLString(xmlFile, key.."#node"))
529 if node ~= nil then
530 if self.dayNightObjects == nil then
531 self.dayNightObjects = {}
532 g_currentMission.environment:addWeatherChangeListener(self)
533 end
534
535 local visibleDay = getXMLBool(xmlFile, key.."#visibleDay")
536 local visibleNight = getXMLBool(xmlFile, key.."#visibleNight")
537 local intensityDay = getXMLFloat(xmlFile, key.."#intensityDay")
538 local intensityNight = getXMLFloat(xmlFile, key.."#intensityNight")
539
540 table.insert(self.dayNightObjects, {node=node, visibleDay=visibleDay, visibleNight=visibleNight, intensityDay=intensityDay, intensityNight=intensityNight})
541 end
542 i = i + 1
543 end
544 end
545
546 -- load leveling properties
547 self.requireLeveling = Utils.getNoNil(getXMLBool(xmlFile, "placeable.leveling#requireLeveling"), self.requireLeveling)
548 if self.requireLeveling then
549 self.maxSmoothDistance = Utils.getNoNil(getXMLFloat(xmlFile, "placeable.leveling#maxSmoothDistance"), 3)
550 self.maxSlope = MathUtil.degToRad(Utils.getNoNil(getXMLFloat(xmlFile, "placeable.leveling#maxSlope"), 45))
551 self.maxEdgeAngle = MathUtil.degToRad(Utils.getNoNil(getXMLFloat(xmlFile, "placeable.leveling#maxEdgeAngle"), 45))
552 self.smoothingGroundType = getXMLString(xmlFile, "placeable.leveling#smoothingGroundType")
553 end
554
555 self:loadAreasFromXML(self.clearAreas, xmlFile, "placeable.clearAreas.clearArea(%d)", false, false)
556 self:loadAreasFromXML(self.levelAreas, xmlFile, "placeable.leveling.levelAreas.levelArea(%d)", false, true) -- load leveling info
557 self:loadAreasFromXML(self.rampAreas, xmlFile, "placeable.leveling.rampAreas.rampArea(%d)", true, true) -- load ramps and leveling info
558 self:loadAreasFromXML(self.foliageAreas, xmlFile, "placeable.foliageAreas.foliageArea(%d)", false, false, true) -- load ramps and leveling info
559
560 if hasXMLProperty(xmlFile, "placeable.tipOcclusionUpdateArea") then
561 local sizeX = getXMLFloat(xmlFile, "placeable.tipOcclusionUpdateArea#sizeX")
562 local sizeZ = getXMLFloat(xmlFile, "placeable.tipOcclusionUpdateArea#sizeZ")
563
564 if sizeX ~= nil and sizeZ ~= nil then
565 local centerX = Utils.getNoNil(getXMLFloat(xmlFile, "placeable.tipOcclusionUpdateArea#centerX"), 0)
566 local centerZ = Utils.getNoNil(getXMLFloat(xmlFile, "placeable.tipOcclusionUpdateArea#centerZ"), 0)
567 self.tipOcclusionUpdateArea = {centerX, centerZ, sizeX, sizeZ}
568 end
569 end
570
571 if not self.alignToWorldY then
572 self.pos1Node = I3DUtil.indexToObject(self.nodeId, getXMLString(xmlFile, "placeable.placement#pos1Node"))
573 self.pos2Node = I3DUtil.indexToObject(self.nodeId, getXMLString(xmlFile, "placeable.placement#pos2Node"))
574 self.pos3Node = I3DUtil.indexToObject(self.nodeId, getXMLString(xmlFile, "placeable.placement#pos3Node"))
575 if self.pos1Node == nil or self.pos2Node == nil or self.pos3Node == nil then
576 self.alignToWorldY = true
577 print("Warning: Pos1Node, Pos2Node and Pos3Node has to be set when alignToWorldY is false!")
578 end
579 end
580
581 if hasXMLProperty(xmlFile, "placeable.animatedObjects") then
582 local i = 0
583 while true do
584 local animationKey = string.format("placeable.animatedObjects.animatedObject(%d)", i)
585 if not hasXMLProperty(xmlFile, animationKey) then
586 break
587 end
588
589 local animatedObject = AnimatedObject:new(self.isServer, self.isClient)
590 if not animatedObject:load(self.nodeId, xmlFile, animationKey) then
591 print("Error: Failed to load animated object " .. tostring(i))
592 else
593 if self.isServer then
594 animatedObject:register(true)
595 end
596
597 table.insert(self.animatedObjects, animatedObject)
598 end
599
600 i = i + 1
601 end
602 end
603
604 local i = 0
605 while true do
606 local triggerMarkerKey = string.format("placeable.triggerMarkers.triggerMarker(%d)", i)
607 if not hasXMLProperty(xmlFile, triggerMarkerKey) then
608 break
609 end
610
611 local node = I3DUtil.indexToObject(self.nodeId, getXMLString(xmlFile, triggerMarkerKey.."#node"))
612 if node ~= nil then
613 table.insert(self.triggerMarkers, node)
614 g_currentMission:addTriggerMarker(node)
615 end
616
617 i = i + 1
618 end
619
620 if hasXMLProperty(xmlFile, "placeable.hotspots") then
621 local i = 0
622 while true do
623 local hotspotKey = string.format("placeable.hotspots.hotspot(%d)", i)
624 if not hasXMLProperty(xmlFile, hotspotKey) then
625 break
626 end
627
628 local hotspot = self:loadHotspotFromXML(xmlFile, hotspotKey)
629 if hotspot ~= nil then
630 g_currentMission:addMapHotspot(hotspot)
631 table.insert(self.mapHotspots, hotspot)
632 end
633
634 i = i + 1
635 end
636 end
637
638 if self.isClient then
639 self.samples.idle = g_soundManager:loadSampleFromXML(xmlFile, "placeable.sounds", "idle", self.baseDirectory, self.nodeId, 1, AudioGroup.ENVIRONMENT, nil, nil)
640 end
641
642 delete(xmlFile)
643
644 return true
645end

loadAreasFromXML

Description
Load area definitions from XML into an area array.
Definition
loadAreasFromXML(table areaArray, string xmlFile, string xmlPathTemplate, bool isRamp)
Arguments
tableareaArrayArray instance which receives loaded area definitions.
stringxmlFileLoaded XML file handle
stringxmlPathTemplateXML element path template for an area type
boolisRampIf true, the targeted areas are ramps

loadAreaFromXML

Description
Load a single area definition from XML.
Areas are defined by three nodes: start, width and height. The start node denotes the origin of the area, while width
and height provide the dimensions of the spanned parallelogram. Usage of areas include clear areas (foliage is
cleared) and leveling areas (terrain is leveled) around placeable objects.
Definition
loadAreaFromXML(table area, integer xmlFile, string key, bool isRamp)
Arguments
tableareaEmpty area definition table which receives the loaded node IDs.
integerxmlFileID of the XML file
stringkeyString Key to the XML element
boolisRampIf true, the targeted areas are ramps
Return Values
booleansuccesssuccess
Code
685function Placeable:loadAreaFromXML(area, xmlFile, key, isRamp, isLeveling)
686 local start = I3DUtil.indexToObject(self.nodeId, getXMLString(xmlFile, key .. "#startNode"))
687 local width = I3DUtil.indexToObject(self.nodeId, getXMLString(xmlFile, key .. "#widthNode"))
688 local height = I3DUtil.indexToObject(self.nodeId, getXMLString(xmlFile, key .. "#heightNode"))
689
690 if start ~= nil and width ~= nil and height ~= nil then
691 area.root = I3DUtil.indexToObject(self.nodeId, getXMLString(xmlFile, key .. "#rootNode"))
692 area.start = start
693 area.width = width
694 area.height = height
695 area.texture = getXMLString(xmlFile, key .. "#texture")
696
697 if isRamp then
698 local rx, ry, rz = getRotation(area.root)
699 area.baseRotation = {rx, ry, rz} -- store base rotation for resetting during preview
700 local rampSlope = getXMLFloat(xmlFile, key .. "#maxSlope")
701 area.maxSlope = rampSlope and MathUtil.degToRad(rampSlope) or self.maxSlope
702 end
703
704 if isLeveling then
705 area.groundType = getXMLString(xmlFile, key .. "#groundType")
706 end
707
708 return true
709 end
710
711 return false
712end

loadFoliageAreaFromXML

Description
Load foliage definitons from XML.
Definition
loadFoliageAreaFromXML()
Code
716function Placeable:loadFoliageAreaFromXML(area, xmlFile, key)
717 local rootNode = I3DUtil.indexToObject(self.nodeId, getXMLString(xmlFile, key .. "#rootNode"))
718 local fruitType = getXMLString(xmlFile, key .. "#fruitType")
719 local fruitTypeDesc = g_fruitTypeManager:getFruitTypeByName(fruitType)
720 local state = getXMLInt(xmlFile, key .. "#state")
721
722 if rootNode ~= nil and fruitTypeDesc ~= nil then
723 area.fruitType = fruitTypeDesc.index
724 area.fieldDimensions = rootNode
725 area.fruitState = Utils.getNoNil(state, fruitTypeDesc.maxHarvestingGrowthState - 1)
726
727 return true
728 end
729
730 return false
731end

loadHotspotFromXML

Description
Load hotspot from XML definitons
Definition
loadHotspotFromXML()
Code
735function Placeable:loadHotspotFromXML(xmlFile, key)
736 local name = Utils.getNoNil(getXMLString(xmlFile, key.."#name"), "")
737
738 local category = Utils.getNoNil(getXMLString(xmlFile, key.."#category"), "CATEGORY_TRIGGER")
739 if MapHotspot[category] ~= nil then
740 category = MapHotspot[category]
741 else
742 category = MapHotspot.CATEGORY_DEFAULT
743 end
744
745 local hotspot = MapHotspot:new(name, category)
746
747 local text = g_i18n:convertText(Utils.getNoNil(getXMLString(xmlFile, key.."#fullName"), ""))
748 if text ~= "" then
749 local showName = Utils.getNoNil(getXMLBool(xmlFile, key.."#showName"), false)
750
751 hotspot:setText(text, not showName)
752 end
753
754 local imageFilename = getXMLString(xmlFile, key.."#imageFilename")
755 if imageFilename ~= nil then
756 imageFilename = Utils.getFilename(imageFilename, self.baseDirectory)
757 end
758
759 local imageUVs = StringUtil.getVectorNFromString(getXMLString(xmlFile, key.."#imageUVs"), 4)
760 local imageName = getXMLString(xmlFile, key.."#imageName")
761 if imageName ~= nil and MapHotspot.UV[imageName] ~= nil then
762 imageUVs = MapHotspot.UV[imageName]
763 end
764 if imageUVs ~= nil then
765 imageUVs = getNormalizedUVs(imageUVs)
766 end
767 if imageUVs ~= nil then
768 local baseColor = StringUtil.getVectorNFromString(getXMLString(xmlFile, key.."#baseColor"), 4)
769 hotspot:setBorderedImage(imageFilename, imageUVs, baseColor)
770 end
771
772 local linkNode = I3DUtil.indexToObject(self.nodeId, getXMLString(xmlFile, key .. "#linkNode"))
773 if linkNode == nil then
774 linkNode = self.nodeId
775 end
776 hotspot:setLinkedNode(linkNode)
777
778 local width = getXMLFloat(xmlFile, key.."#width")
779 local height = getXMLFloat(xmlFile, key.."#height")
780 if width ~= nil and heigth ~= nil then
781 hotspot:setSize(width, height)
782 end
783
784 hotspot:setBlinking(Utils.getNoNil(getXMLBool(xmlFile, key.."#blinking"), false))
785 hotspot:setPersistent(Utils.getNoNil(getXMLBool(xmlFile, key.."#persistent"), false))
786 hotspot:setRenderLast(Utils.getNoNil(getXMLBool(xmlFile, key.."#renderLast"), false))
787
788 local textSize = getXMLInt(xmlFile, key.."#textSize")
789 if textSize ~= nil then
790 _, textSize = getNormalizedScreenValues(0, textSize)
791 hotspot:setTextOptions(textSize)
792 end
793
794 local hotspotTextOffset = Utils.getNoNil(getXMLString(xmlFile, key .. "#hotspotTextOffset"), "0px 0px")
795 hotspot:setRawTextOffset(hotspotTextOffset)
796
797 local textColor = StringUtil.getVectorNFromString(getXMLString(xmlFile, key.."#textColor"), 4)
798 hotspot:setTextOptions(nil, nil, nil, textColor)