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 |
List all available commands
Show frames per second
Enable/disable frame per second limiter
Frame per second limit attribute
Print detailed entity list
Print detailed resource list
Enable parallel rendering and physics
Quits application
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 |
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/
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).
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”.
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:
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.
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.
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.
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.
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:
Key | Function |
---|---|
Ctrl-N | New file |
Ctrl-O | Open file |
Ctrl-S | Save file |
Ctrl-Shift-S | Save all files |
Ctrl-Q | Quit application |
Ctrl-Z | Undo |
Ctrl-Y | Redo |
Ctrl-F | Find |
Ctrl-H | Replace |
Ctrl-Shift-F | Find in files |
F3 | Find next |
Shift-F3 | Find previous |
Ctrl-Shift-G | Go to file |
Ctrl-G | Go to line |
Ctrl-K | Comment lines |
Ctrl-Shift-K | Uncomment lines |
Ctrl-W | Close tab |
Ctrl-Shift-T | Reopen tab |
Alt-Up | Move line up |
Alt-Down | Move line down |
Alt-Left | Navigate backwards |
Alt-Right | Navigate forward |
F5 | Run / Continue execution |
Ctrl-F5 | Run Without Debugging |
F7 | Pause execution |
F6 | Stop execution |
F9 | Toggle Breakpoint |
F11 | Step Into |
F10 | Step Over |
Shift-F11 | Step Out |
Achievement message display element.
-- Used to display a message in the HUD when a new achievement is unlocked.
--@category GUI
Create a new instance of AchievementMessage.Definition
new(string hudAtlasPath, table inputManager, table guiSoundPlayer, ContextActionDisplay ContextActionDisplay)Arguments
string | hudAtlasPath | Path the HUD texture atlas |
table | inputManager | InputBinding reference for achievement acknowledgment input |
table | guiSoundPlayer | GuiSoundPlayer reference for playing a sound cue |
ContextActionDisplay | ContextActionDisplay | reference for visibility checks (it occupies the same space on the HUD) |
table | AchievementMessage | instance |
Handle changes in menu visibility.Definition
Keeps track of menu visibility state to avoid showing (or updating) an achievement message when the menu is active.
onMenuVisibilityChange()
Show an achievement message.Definition
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.
showMessage(string title, string description, string iconFilename, table iconUVs, float duration)Arguments
string | title | Achievement title text |
string | description | Achievement description text |
string | iconFilename | Path to the achievement icon texture |
table | iconUVs | UV coordinates of achievement icon with icon texture |
float | duration | Maximum display duration in milliseconds |
Update display state.Definition
update()
Actually start showing the message when nothing is obstructing the view.Definition
beginShowMessage()
Hide the message, including animation.Definition
Also removes the acknowledgment input events.
hideMessage()
Draw the achievement message if necessary.Definition
draw()
Store scaled positioning, size and offset values.Definition
storeScaledValues()
Set this element's scale.Definition
setScale()
Get the position of the background element, which provides this element's absolute position.Definition
getBackgroundPosition(scale Current, float width)Arguments
scale | Current | UI scale |
float | width | Scaled background width in pixels |
float | X | position in screen space |
float | Y | position in screen space |
Create the empty background overlayDefinition
createBackground()
Create required display components.Definition
createComponents()
Create the message frame.Definition
createFrame()
Create the achievement icon.Definition
createIcon()
Animal Buying Screen.
AnimalScreen = {}
ConstructorDefinition
new(table target, table metatable)Arguments
table | target | |
table | metatable |
table | self | instance |
53 | function 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 |
83 | end |
Callback on openDefinition
onOpen()Code
87 | function 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) |
101 | end |
Callback on closeDefinition
onClose(table element)Arguments
table | element |
106 | function 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) |
117 | end |
Callback on click backDefinition
onClickBack()Code
262 | function AnimalScreen:onClickBack() |
263 | AnimalScreen:superClass().onClickBack(self) |
264 | self:changeScreen(nil) |
265 | end |
Callback on click cancelDefinition
onClickOk()Code
269 | function 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 |
277 | end |
Input context name for identification, does not take care of proper context handling
Create a new base missionDefinition
new(string baseDirectory, table customMt, table missionCollaborators)Arguments
string | baseDirectory | Mission scripts base directory |
table | customMt | Sub-class meta table |
table | missionCollaborators | MissionCollaborators object containing a defined collection required object references for a mission. |
Initialize mission after instantiation.Definition
Create complex members and call dependency methods in here so that mission instantiation cannot fail.
initialize()
Create the in-game HUD display.Definition
createHUD()
Deprecated: Replaced by InputBinding:setActionEventText()Definition
addHelpButtonText()
Subscribe to relevant game settings changes.Definition
subscribeSettingsChangeMessages()
Subscribe to GUI notifications of opening and closing.Definition
subscribeGuiOpenCloseMessages()
Handle a menu open event.Definition
onBeforeMenuOpen()
Handle a menu closed event.Definition
onAfterMenuClose()
Register required input action events.Definition
registerActionEvents()
Register action events for pause actions.Definition
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.
registerPauseActionEvents()
Input event for "pause".Definition
onPause()
Input event for breaking pause on consoles.Definition
onConsoleAcceptPause()
Input event for "toggle help text".Definition
onToggleHelpText()
Input event for "switch vehicle".Definition
onSwitchVehicle(directionValue Numeric)Arguments
directionValue | Numeric | value for switch direction, 1 is the next, -1 is the previous vehicle |
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.
Create a new Binding instance.Definition
new(action InputAction, deviceId ID, axisNames List, axisComponent Component, inputComponent Component, index Binding)Arguments
action | InputAction | reference which is being bound to an input |
deviceId | ID | of the input device whose input is being bound to the given action |
axisNames | List | of input axis names. If the list contains more than one axis, any axis before the last one is a modifier. |
axisComponent | Component | of the last given axis to bind to the given action. |
inputComponent | Component | of a physical axis (e.g. analog stick) to bind |
index | Binding | index, 1 primary, 2 secondary, etc. |
bool | true | if allowed |
New | Binding | instance |
Create a new Binding instance from an XML element.Definition
createFromXML(int xmlFile, string elementTag, bool isLocked)Arguments
int | xmlFile | XML file handle |
string | elementTag | Tag of the element to parse as a Binding |
bool | isLocked | If true, the binding belongs to a locked action |
boolean | isAllowed | true if fillType is supported else false |
Binding | instance | initialized with values from XML and the given parameters |
Save this binding to XML.Definition
saveToXMLFile(xmlFile Input, elementTag Element)Arguments
xmlFile | Input | binding settings XML file handle |
elementTag | Element | tag of this binding |
boolean | isSupported | true if fillType is supported else false |
Update a binding with a new input target.Definition
Always use this method to change existing bindings or risk invalid state.
updateData(deviceId (New), axisNames List, inputComponent [optional])Arguments
deviceId | (New) | device ID |
axisNames | List | of 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. |
float | freeCapacity | free capacity |
Update this binding's input state.Definition
updateInput(inputValue Current)Arguments
inputValue | Current | input value of the last axis in self.axisNames |
boolean | isAllowed | true if toolType is allowed else false |
Set this binding's analog input flag.Definition
setIsAnalog()Return Values
table | instance | instance of object |
Set this binding's index and update internal state.Definition
setIndex()Return Values
table | instance | instance of object |
Set this binding's active state.Definition
Only active bindings are updated and can trigger action events.
setActive()Return Values
integer | harvestPixelsSum | harvest of pixels sum |
integer | harvestNumPixels | harvest number of pixels |
float | sprayFactor | spray factor |
float | plowFactor | plow factor |
float | limeFactor | lime factor |
float | weedFactor | weed factor |
integer | growthState | growth state |
float | maxArea | max area |
Set the frame trigger flag which shows if this binding has triggered an event this frame.Definition
setFrameTriggered()
Get the frame trigger flag which shows if this binding has triggered an event this frame.Definition
getFrameTriggered()
Set and store the combo bit mask for this binding.Definition
This is agnostic of the actually bound device because a binding can only map input on one specific device.
setComboMask(int comboMask)Arguments
int | comboMask | Combo mask |
Get the combo bit mask.Definition
getComboMask()Return Values
int | Combo | bit mask |
Check if there is a collision between this binding and another one.Definition
Two bindings collide if they bind the same input on the same axes of the same device.
hasCollisionWith(otherBinding Other)Arguments
otherBinding | Other | binding to check for collision |
True | if | there is a collision. |
Check if this binding is an alternative to another one on the same action.Definition
Two bindings are alternatives if they bind different input on the same axis of the same device category to the same action.
isAlternativeTo(otherBinding Other)Arguments
otherBinding | Other | binding to check if it's an alternative |
True | if | this and the other binding are alternatives of each other |
Create a new instance of Binding with the same state as this instance.Definition
clone()Return Values
Cloned | Binding | instance |
Copy binding input state from another binding.Definition
copyInputStateFrom()Return Values
integer | ret | ret |
integer | total | total |
Check if this binding occupies the same binding slot as another binding on the same action.Definition
isSameSlot()
Get the opposite axis component for a given axis component.Definition
getOppositeAxisComponent(axisComponent One)Arguments
axisComponent | One | of the constant values of Binding.AXIS_COMPONENT |
integer | changedValue | changed value |
Get the opposite input component for a given input component.Definition
getOppositeInputComponent(inputComponent One)Arguments
inputComponent | One | of the constant values of Binding.INPUT_COMPONENT |
integer | changedArea | changed area pixels |
integer | totalArea | total area |
Make and assign a binding ID.Definition
makeId()
Determine if we need to swap buttons for Japanese Playstation controllers by their convention.Definition
needJapanesePlaystationButtonSwap()Return Values
integer | changedArea | changed area pixels |
integer | totalArea | total area pixles |
Swaps buttons for Japanese Playstation controllers if contained in the given axis names.Definition
swapJapanesePlaystationButtons(table axisNames)Arguments
table | axisNames | Axis names array, will be changed in place |
Get a string representation of this binding.Definition
toString()Return Values
integer | numPixels | number of pixels |
integer | totalNumPixels | total number of pixels |
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".
Set this element's image color.Definition
Omitted (nil value) color values have no effect and the previously set value for that channel is used.
setImageColor(state GuiOverlay, r Red, g Green, b Blue, a Alpha)Arguments
state | GuiOverlay | state for which the color is changed, use nil to set the default color |
r | Red | color value |
g | Green | color value |
b | Blue | color value |
a | Alpha | value (transparency) |
Set this element's image overlay's rotation.Definition
setImageRotation(float rotation)Arguments
float | rotation | Rotation in radians |
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".
Extract a flow / cell data table from this box layout's elements.Definition
getLayoutCells(ignoreVisibility Visibility)Arguments
ignoreVisibility | Visibility | flag for element eligibility |
Flows | and | cells as nested tables: [flowIndex][cell index] = cell data {element, flowSize, lateralSize} |
Calculate layout sizes based on flow cell data.Definition
getLayoutSizes()Return Values
List | of | lateral flow sizes, total lateral sizes (sum of lateral flow sizes), maximum flow size in direction of flow |
Get the layout space starting position offset for elements based on flow dimensions and alignments.Definition
getAlignmentOffset(flowSize Flow, flowLateralSize Total)Arguments
flowSize | Flow | size in flow direction (e.g. height for vertical flows) |
flowLateralSize | Total | flow size orthogonal to flow direction (e.g. combined width of all columns for vertical flows) |
Layout | X | starting offset, layout Y starting offset, Layout X direction {-1|1}, Layout Y direction {-1|1} |
Calculate element offsets for margins and to counteract alignment updates in GuiElement.updateAbsolutePositions()Definition
getElementAlignmentOffset(directionX Layout, directionY Layout)Arguments
directionX | Layout | X direction as a signed factor {-1|1} |
directionY | Layout | Y direction as a signed factor {-1|1} |
element | X | offset, element Y offset |
Apply layout positions to all given cells' elements.Definition
applyCellPositions(flowCells List, offsetStartX Layout, offsetStartY Layout, directionX Layout, directionY Layout, lateralFlowSizes List)Arguments
flowCells | List | of flows and their cell data |
offsetStartX | Layout | X starting offset |
offsetStartY | Layout | Y starting offset |
directionX | Layout | X direction as a signed factor {-1|1} |
directionY | Layout | Y direction as a signed factor {-1|1} |
lateralFlowSizes | List | of lateral flow sizes (e.g. widths of columns in vertical flows) |
Link layout cells' elements for focus navigation.Definition
focusLinkCells(flowCells List)Arguments
flowCells | List | of flows and their cell data |
Link a child element to others for focus navigationDefinition
focusLinkChildElement(element Current, previousElement Element, firstElement First, lastElement Last)Arguments
element | Current | element |
previousElement | Element | at previous position in layout flow, will be nil when the first element is being processed |
firstElement | First | element in layout |
lastElement | Last | element in layout |
Invalidate the layout, will reposition all elements and update focus navigation.Definition
invalidateLayout(ignoreVisibility If)Arguments
ignoreVisibility | If | true, elements will be considered for layouting even if invisible |
Return the actual focus target when this box layout is being focused. This can be a previously focused element withinDefinition
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).
getFocusTarget(incomingDirection Focus, moveDirection Actual)Arguments
incomingDirection | Focus | navigation direction from where this layout is being entered |
moveDirection | Actual | focus navigation direction per input |
GuiElement | which | should receive focus instead |
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"
Load glyph overlay colors.Definition
loadInputGlyphColors(profile If, xmlFile If, key XML)Arguments
profile | If | set, loads overlay properties from this button's GUI profile |
xmlFile | If | set, loads overlay properties from this button's XML configuration |
key | XML | base configuration node of this button |
Load the actual input glyph symbols to display if an input action is defined on the button.Definition
loadInputGlyph()
Set the keyboard mode flag.Definition
setKeyboardMode()
Set the input action for the display glyph by name.Definition
setInputAction()
Set UV coordinates for the button background and/or icon.Definition
setImageUVs()
Determine if this button is selectedDefinition
getIsSelected()
Determine if this button is highlightedDefinition
getIsHighlighted()
Get modified text offset including changes from icon position and dimensions.Definition
getIconModifiedTextOffset(float textOffsetX, float textOffsetY)Arguments
float | textOffsetX | Screen space text X offset |
float | textOffsetY | Screen space text Y offset |
float | Modified | X offset |
float | Modified | Y offset |
Get text offset from element position including modifications from icon.Definition
getTextOffset()
Get shadow text offset from element position including modifications from icon.Definition
getText2Offset()
Get the current icon size in screen space.Definition
getIconSize()
Update size of element depending on contentDefinition
updateSize()
Keyboard button display overlay.
-- Overlay type which displays a keyboard key button symbol.
--@category GUI
Delete this button overlay.Definition
delete()
Set this overlay's background color.Definition
setColor(r Red, g Green, b Blue, a Alpha)Arguments
r | Red | channel [0, 1] |
g | Green | channel [0, 1] |
b | Blue | channel [0, 1] |
a | Alpha | (transparency) channel [0, 1], 0 is fully transparent, 1 is opaque |
Render this overlay with the given parameters.Definition
renderButton(buttonText Text, posX Screen, posY Screen, height Button, alignment Text)Arguments
buttonText | Text | to display as the key value, e.g. "A", "Space", "Ctrl", etc. |
posX | Screen | x position |
posY | Screen | y position |
height | Button | display height |
alignment | Text | alignment, one of the constants of RenderText.ALIGN_[...] |
Get the total display width of this button overlay for a given button text and heightDefinition
getButtonWidth()
Career Screen.
Displays available save game slots.
-- @field savegameList Save game list
Set UI waiting state, which displays or hides a dialog that says to wait.Definition
setIsWaitingForSaveGameInfo()
Character Selection Screen.
Set the index of the character. Is turned into a player and body pair.Definition
setCharacterIndex()
Update the character with the currently configured options.Definition
updateCharacterWithSettings()
Update the character to match given options. Only reloads object if needed.Definition
updateCharacter()
Loading of the character object finishedDefinition
loadCharacterFinished()
Update the existing character with options that can be changedDefinition
updateCharacterOptions()
Set the visbility of the 'hat hair': special hair when wearing a hatDefinition
setHatHairNodeVisibility()
Multiplayer chat dialog
-- @field textElement User chat message input element
Handle menu up/down input.Definition
Scrolls through the chat history.
onMenuAxisUpDown()
HUD chat window.
-- Displays chat messages.
--@category GUI
Create a new ChatWindow.Definition
new(string hudAtlasPath)Arguments
string | hudAtlasPath | Path to the HUD atlas texture. |
table | ChatWindow | instance |
Set the chat message history reference for displaying.Definition
The array is owned by the caller and must not be modified.
setChatMessages(table messages)Arguments
table | messages | Messages array as {i={msg=<message text>, sender=<sender user nickname>}} |
Scroll chat messages by a given amount.Definition
scrollChatMessages(int delta, int numMessages)Arguments
int | delta | Number of lines (positive or negative) to scroll |
int | numMessages | Number of currently stored chat messages |
Handle menu visibility state change.Definition
onMenuVisibilityChange()
Update element state.Definition
update()
Draw the chat window.Definition
draw()
Set this element's UI scale.Definition
setScale()
Get this element's base background position.Definition
getBackgroundPosition(float uiScale)Arguments
float | uiScale | Current UI scale factor |
Store scaled positioning, size and offset values.Definition
storeScaledValues()
Create the background overlay.Definition
createBackground()
Color Picker Dialog
-- Lets the player pick from a set of colors.
-- @field buttonTemplate Color button template which is cloned per color
Set colors after opening.Definition
setColors(table colors, table defaultColor)Arguments
table | colors | Array of colors {i={r, g, b, a}, or {i={name="name", color={r,g,b,a}}} |
table | defaultColor | Default color setting as {r, g, b, a}, must be contained in colors array |
Apply custom grid-based focus linkingDefinition
focusLinkColorButtons()
Set the initial focus when entering this dialog.Definition
setInitialFocus()
Set the dialog callback.Definition
setCallback()
Handle activation of a color button.Definition
onClickColorButton()
Player context action display element.
-- Displays information about the current interaction context. Includes action names and current input scheme button
glyphs.
--@category GUI
Create a new instance of ContextActionDisplay.Definition
new(string hudAtlasPath)Arguments
string | hudAtlasPath | Path to the HUD texture atlas |
Sets the current action context.Definition
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.
setContext(string contextAction, string contextIconName, string targetText, int priority, string actionText)Arguments
string | contextAction | Input action name of the context action |
string | contextIconName | Name of the icon to display for the action context, use one of ContextActionDisplay.CONTEXT_ICON |
string | targetText | Display text which describes the context action target |
int | priority | [optional, default=0] Context priority, a higher number has higher priority. |
string | actionText | [optional] Context action description, if different from context action description |
Update the context action display state.Definition
update()
Reset context state after drawing.Definition
The context must be set anew on each frame.
resetContext()
Draw the context action display.Definition
draw()
Set the scale of this element.Definition
setScale()
Store scaled positioning, size and offset values.Definition
storeScaledValues()
Get the position of the background element, which provides this element's absolute position.Definition
getBackgroundPosition(scale Current, float width)Arguments
scale | Current | UI scale |
float | width | Scaled background width in pixels |
float | X | position in screen space |
float | Y | position in screen space |
Create an empty background overlay as a base frame for this element.Definition
createBackground()
Create display components.Definition
createComponents(string hudAtlasPath, table inputDisplayManager)Arguments
string | hudAtlasPath | Path to HUD atlas texture |
table | inputDisplayManager | InputDisplayManager reference |
Create the input glyph element.Definition
createInputGlyph()
Create the context display frame.Definition
createFrame()
Create action context icons.Definition
Only one of these will be visible at any time.
createActionIcons()
Controls settings controller.
-- Handles the input controls model and control logic for settings screen controls pages.
--@category GUI
Create a new ControlsController instance.Definition
new()
Set a callback for displaying status messages.Definition
Callback signature: messageCallback(messageId, additionalText, addLine)
setMessageCallback(messageCallback A)Arguments
messageCallback | A | function 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. |
Set a callback to react on input capture completion.Definition
Callback signature: inputDoneCallback(madeChange)
setInputDoneCallback(inputDoneCallback A)Arguments
inputDoneCallback | A | function to notify a collaborator that input gathering has finished and if there were any changes. |
Create a display action for displaying from bindings for a given axis direction.Definition
createDisplayAction(deviceCategory Device, actionBinding Action, isAxisPositive If)Arguments
deviceCategory | Device | category, only bindings of devices of this category are displayed |
actionBinding | Action | binding table reference: {action=Action, bindings={1=binding1, 2=binding2, ...}} |
isAxisPositive | If | true, the display action should show a positive action axis. |
{name="internalName", | displayName="displayName", | inputTexts={1=text1, 2=text2, ...}, inputBindings={1=binding1, 2=binding2, ...}, positiveInput=[true|false]} |
Get available action bindings per device category, including current changes (even before saving).Definition
getDeviceCategoryActionBindings(deviceCategory Device)Arguments
deviceCategory | Device | category name |
List | of | DisplayActionBinding instances |
Get display text for a single mouse axis.Definition
getMouseAxisDisplayText()
Get display text for a single gamepad axis.Definition
getGamepadAxisDisplayText()
Get display text for input axis names of a binding.Definition
getBindingInputDisplayText(Binding Binding)Arguments
Binding | Binding | reference |
Display |
Save changed bindings to user configuration.Definition
saveChanges()
Discard any previously made binding changes.Definition
discardChanges()
Load action input bindings.Definition
loadBindings()
Handles clicking an input binding button for a given device category and action.Definition
onClickInput(deviceCategory Input, bindingId ID, actionBinding Action)Arguments
deviceCategory | Input | device category |
bindingId | ID | of binding on the current device. E.g. 1 for main binding, 2 for secondary binding, etc. |
actionBinding | Action | binding table for the clicked action |
True | if | the controller starts listening for input, false otherwise (also if it is already listening!) |
Begin waiting for input.Definition
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().
beginWaitForInput(deviceCategory Category, bindingIndex Binding, DisplayActionBinding DisplayActionBinding)Arguments
deviceCategory | Category | of device which is being scanned for input |
bindingIndex | Binding | (primary, secondary, etc.) index which the scanned input will be assigned to. |
DisplayActionBinding | DisplayActionBinding | instance which describes the action binding to re-map. |
Input gathering abort event.Definition
onAbortInputGathering()
Input gathering binding deletion event.Definition
onDeleteInputBinding(DisplayActionBinding DisplayActionBinding, gatheringState {binding=DisplayActionBinding)Arguments
DisplayActionBinding | DisplayActionBinding | reference of the binding to delete |
gatheringState | {binding=DisplayActionBinding | reference of the binding to change, bindingIndex=Binding index} |
Input gathering keyboard input event.Definition
onCaptureKeyboardInput(keyName Key, isModifier True, inputValue 1, gatheringState {binding=DisplayActionBinding)Arguments
keyName | Key | name as defined in Input |
isModifier | True | if the key is used as a modifier for a combined input |
inputValue | 1 | for pressed, 0 for inactive |
gatheringState | {binding=DisplayActionBinding | reference of the binding to change, bindingIndex=Binding index, keyState={[keyName]=[lastValue]}} |
Input gathering mouse input event.Definition
onCaptureMouseInput(inputAxisName Mouse, isModifier True, inputValue Input, gatheringState {binding=DisplayActionBinding)Arguments
inputAxisName | Mouse | axis or button name as defined in Input |
isModifier | True | if the input axis is used as a modifier for a combined input |
inputValue | Input | value of the input axis |
gatheringState | {binding=DisplayActionBinding | reference of the binding to change, bindingIndex=Binding index, mouseState={[axisName]=[lastValue]}} |
Input gathering gamepad / controller event.Definition
onCaptureGamepadInput(deviceId Device, inputAxisName Axis, isModifier True, inputValue Input, gatheringState {binding=DisplayActionBinding)Arguments
deviceId | Device | ID of the gamepad / controller which has received input |
inputAxisName | Axis | or button name as defined in Input |
isModifier | True | if the input axis is used as a modifier for a combined input |
inputValue | Input | value of the input axis |
gatheringState | {binding=DisplayActionBinding | reference of the binding to change, bindingIndex=Binding index, gamepadState={[deviceId]={[axisName]=[lastValue]}}} |
Stop waiting for input.Definition
Lifts the input override and notifies the screen listener.
endWaitForInput(madeChange If)Arguments
madeChange | If | true, the player has changed at least one binding. |
Lock all UI input after capturing a new binding.Definition
lockInput()
Delete a binding from its action binding table.Definition
deleteBinding()Return Values
bool | True | if an actual binding was deleted, false otherwise |
Assign a (new) keyboard input binding.Definition
assignKeyboardBinding(DisplayActionBinding DisplayActionBinding, bindingIndex Binding, keyames List)Arguments
DisplayActionBinding | DisplayActionBinding | instance which holds information about the binding to be added or updated |
bindingIndex | Binding | index to set, 1 primary, 2 secondary, etc. |
keyames | List | of input key names to bind |
True | if | a binding change was made, false otherwise |
Check if the given axis names contain a supported mouse combo.Definition
validateMouseCombo()
Assign a (new) mouse input binding.Definition
assignMouseBinding(DisplayActionBinding DisplayActionBinding, inputAxisNames List, inputDirection Numeric)Arguments
DisplayActionBinding | DisplayActionBinding | instance which holds information about the binding to be added or updated |
inputAxisNames | List | of input axis names (axes and buttons) to bind |
inputDirection | Numeric | value 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. |
True | if | a binding change was made, false otherwise |
Assign a (new) gamepad / controller input binding.Definition
assignGamepadBinding(DisplayActionBinding DisplayActionBinding, bindingIndex Binding, deviceId Gamepad, inputAxisNames List, inputDirection Numeric)Arguments
DisplayActionBinding | DisplayActionBinding | instance which holds information about the binding to be added or updated |
bindingIndex | Binding | index to set, 1 primary, 2 secondary, etc. |
deviceId | Gamepad | / controller device ID of the input to bind |
inputAxisNames | List | of input axis names (axes and buttons) to bind |
inputDirection | Numeric | value 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. |
True | if | a binding change was made, false otherwise |
Assign a (new) binding.Definition
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.
assignBinding(deviceId Binding, displayAction Cloned, bindingIndex Intended, inputAxisNames List, isPositiveAxis If, inputDirection Numeric, previousDeviceId [optional])Arguments
deviceId | Binding | device ID |
displayAction | Cloned | InputAction passed back from display and capture process |
bindingIndex | Intended | binding index, 1 primary, 2 secondary, etc. |
inputAxisNames | List | of input axis names to bind |
isPositiveAxis | If | true, 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. |
inputDirection | Numeric | value 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. |
True | if | binding has been assigned; reference to first colliding binding or nil |
Load default input binding settings from the game's profile template.Definition
Handle with care, this will overwrite all the player's input binding settings.
loadDefaultSettings()
Creating data grid
@param table customMt custom metatableDefinition
new()Return Values
table | instance | instance of object |
19 | function 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 |
31 | end |
Deletes data gridDefinition
delete()Code
35 | function DataGrid:delete() |
36 | self.grid = nil |
37 | end |
@param integer colIndex index of columnDefinition
getValue()Return Values
table | value | value at the given position |
44 | function 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] |
57 | end |
@param integer colIndex index of columnDefinition
setValue(table value)Arguments
table | value | value at the given position |
64 | function 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 |
78 | end |
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
Create a new depth of field state.Definition
This will record the currently set parameters which are restored when calling reset().
new(float nearCoCRadius, float nearBlurEnd, float farCoCRadius, float farBlurStart, float farBlurEnd)Arguments
float | nearCoCRadius | Near circle of confusion radius (nearCoCRadius = 0 means no near blur (pinhole camera)) |
float | nearBlurEnd | Distance from the camera center where near blur ends |
float | farCoCRadius | Far circle of confusion radius (farCoCRadius = 0 means no far blur (pinhole camera)) |
float | farBlurStart | Distance from the camera center where far blur starts |
float | farBlurEnd | Distance from the camera center where far blur ends |
Record the current shader parameters for reset.Definition
This is called on instantiation. If another state should be recorded, call this again afterwards.
recordState()
Set one or more parameters after instantiation.Definition
If any of the parameters is omitted, the currently stored value is used.
setParameters(float nearCoCRadius, float nearBlurEnd, float farCoCRadius, float farBlurStart, float farBlurEnd)Arguments
float | nearCoCRadius | Near circle of confusion radius (nearCoCRadius = 0 means no near blur (pinhole camera)) |
float | nearBlurEnd | Distance from the camera center where near blur ends |
float | farCoCRadius | Far circle of confusion radius (farCoCRadius = 0 means no far blur (pinhole camera)) |
float | farBlurStart | Distance from the camera center where far blur starts |
float | farBlurEnd | Distance from the camera center where far blur ends |
Apply shader parameters which were provided on instantiation.Definition
apply()
Reset the shader parameters to the state they were in when this object had been created.Definition
reset()
Create a depth of field state for a full screen blur effect.Definition
createFullscreenBlur()
Vehicle selling or customization dialog
-- Opened when activating vehicle selling points.
-- @field headerText Dialog header text element
Create a new DirectSellDialog instance.Definition
new(table target, table custom_mt, table shopConfigScreen, table messageCenter)Arguments
table | target | DialogElement controller reference |
table | custom_mt | [optional] Sub-class meta table for inheritance |
table | shopConfigScreen | ShopConfigScreen reference for vehicle selling / customization |
table | messageCenter | MessageCenter reference for local network UI event handling |
table | DirectSellDialog | instance |
Handle "sell" button event.Definition
onClickOk()
Handle "customize" button event.Definition
onClickActivate()
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
Creates a new DisplayActionBinding.Definition
new(action InputAction, isPositive If, displayName Display, Binding Bindings)Arguments
action | InputAction | of this binding |
isPositive | If | true, this display action binding shows the binding for the positive input axis (always true for half-axis actions) |
displayName | Display | name of this action binding for the given input axis direction. |
Binding | Bindings | associated with the input axis component for the given action |
Set display information for binding.Definition
setBindingDisplay(Binding Binding, text Binding, column Display)Arguments
Binding | Binding | reference contained in this instance |
text | Binding | display text (button/key/axes names) |
column | Display | column index (1 for primary, 2 for secondary, etc) |
integer | numPixels | number of pixels |
integer | totalNumPixels | total number of pixels |
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
Create a new instance of EditFarmDialog.Definition
new(table target, table custom_mt, table l10n, table farmManager)Arguments
table | target | Optional input target override |
table | custom_mt | Sub-class metatable |
table | l10n | I18N reference for localization |
table | farmManager | FarmManager reference for farm data access |
Set existing farm ID whose properties are to be modified.Definition
If no farm ID is given, a new farm will be created.
setExistingFarm()
Find available farm colors and store them in fields.Definition
storeAvailableColors()
Handle activation of a color button.Definition
Shadows parent method which exits the dialog right away.
onClickColorButton()
Handle dialog confirmation click / activation.Definition
Depending on the mode, this will create a new farm or update an existing one.
onClickActivate()
Permission types.
Merge another farm into this farm. Used for creating an SP game from an MP game. (this is mutating)Definition
merge(table other)Arguments
table | other | Another Farm |
Get the farmhouse associated with the farm.Definition
getFarmhouse()Return Values
table | farmhouse | or nil |
Get the spawnpoint associated with the farm(house).Definition
getSpawnPoint()Return Values
integer | spawnpoint | node or the career spawnpoint node. |
Get the sleep camera.Definition
getSleepCamera()Return Values
integer | Camera | or 0 if no farmhouse. |
Get a list of active users. Useful for using their connection IDDefinition
getActiveUsers()
Determine if a user is a manager of this farm.Definition
isUserFarmManager(userId User)Arguments
userId | User | ID |
bool | True | if the user is a manager of this farm, false otherwise |
Get the farm permissions of a user.Definition
getUserPermissions(userId User)Arguments
userId | User | ID |
table | Permission | hash table {permission=<hasPermission>} |
Set a user's permission in this farm.Definition
setUserPermission(userId User, string permission, bool hasPermission)Arguments
userId | User | ID |
string | permission | Permission key from Farm.PERMISSION |
bool | hasPermission | True if the permission is to be granted, false to be denied |
Promote a user to farm manager.Definition
promoteUser()
Demote a user from farm manager.Definition
demoteUser()
Update contracting statusDefinition
setIsContractingFor(noSendEvent boolean)Arguments
noSendEvent | boolean | Send no event, forces setting of actual value without server feedback |
Add or remove money from the farmDefinition
changeBalance(number amount)Arguments
number | amount | Amount to add (positive) or remove (negative) |
Get the current account balance of the farm.Definition
getBalance()Return Values
float | Account | balance |
Get the current loan of the farm.Definition
getLoan()Return Values
float |
Get a list of filenames for accessible handtoolsDefinition
getHandTools()
Add a new user to the farm. This adds it to the players and active players list.Definition
And also gives default permissions.
addUser()
Remove a user from the farm.Definition
removeUser()
Called when a user joins the game. Active users is updated, and for spectator.Definition
a new user might be added. Server only.
onUserJoinGame()
Called when a user quits the game. The active user list is updated. Server only.Definition
onUserQuitGame()
Multiplayer
Creating managerDefinition
new()Return Values
table | instance | instance of object |
27 | function FarmManager:new(customMt) |
28 | local self = AbstractManager:new(customMt or FarmManager_mt) |
29 | |
30 | return self |
31 | end |
Load data on map loadDefinition
loadMapData()Return Values
boolean | true | if loading was successful else false |
43 | function 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 |
65 | end |
Unload data on mission deleteDefinition
unloadMapData()Code
69 | function 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) |
78 | end |
Write field mission data to savegame fileDefinition
saveToXMLFile(string xmlFilename)Arguments
string | xmlFilename | file path |
boolean | true | if loading was successful else false |
84 | function 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) |
99 | end |
Load fieldjob data from xml savegame fileDefinition
loadFromXMLFile(string filename)Arguments
string | filename | xml filename |
104 | function 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 |
149 | end |
Second step of merging: transfer all lands to the singleplayer farmDefinition
mergeFarmlandsForSingleplayer()
Third step of merging: move vehicles and bales to singleplayer farmDefinition
mergeObjectsForSingleplayer()
Deletes field mission managerDefinition
delete()Code
236 | function FarmManager:delete() |
237 | end |
Updates field mission ownage data from xml savegame fileDefinition
update(string filename)Arguments
string | filename | xml filename |
242 | function 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 |
249 | end |
Get farm for given userId. To be used when player is not in the gameDefinition
getFarmForUniqueUserId()
Get farm for given userId. To be used when player is in the game.Definition
getFarmByUserId()
On client, update the list of farms and set farm for given farmIdDefinition
updateFarms()
Get the array of known farms.Definition
Callers should not modify this array.
getFarms()
Transfer an amount of money from the current user's farm to a destination farm.Definition
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.
transferMoney()
Remove player from their farm. Only works if the caller has permission (master user, farm manager)Definition
removeUserFromFarm()
Farm has been destroyed. Remove from listsDefinition
removeFarm()
HUD field information display element.
-- Displays dynamic information about the field which the player is currently standing in (or close by).
--@category GUI
Create a new instance of FieldInfoDisplay.Definition
new(string hudAtlasPath)Arguments
string | hudAtlasPath | Path to the HUD texture atlas |
Set up rows data structures.Definition
setupRows()
Set the local player reference.Definition
setPlayer()
Set the current fruit type to display.Definition
setFruitType(int fruitTypeIndex, int fruitGrowthState)Arguments
int | fruitTypeIndex | Index of the field fruit type or a number <= 0 to clear the fruit type. |
int | fruitGrowthState | Current growth state of the given fruit type |
Set the field ownerDefinition
setOwnerFarmId(int ownerFarmId)Arguments
int | ownerFarmId | Current owner farm id |
Set the fertilization factor info to display.Definition
setFertilization(float fertilizationFactor)Arguments
float | fertilizationFactor | Current fertilization factor to display, this will be converted to a percentage. Values < 0 clear this info. |
Set the weed factor info to display.Definition
setWeed(float fertilizationFactor)Arguments
float | fertilizationFactor | Current weed factor to display, this will be converted to a percentage. Values < 0 clear this info. |
Set the plowing required display.Definition
setPlowingRequired(bool isRequired)Arguments
bool | isRequired | If true, will display that the current field needs to be plowed. Otherwise, the info is hidden. |
Set the lime required display.Definition
setLimeRequired(bool isRequired)Arguments
bool | isRequired | If true, will display that the current field needs lime. Otherwise, the info is hidden. |
Add a custom text row.Definition
The custom text will be added in order of calls to this function after the default information.
addCustomText(string leftText, string rightText, table leftColor)Arguments
string | leftText | Text to be displayed on the left side in bold print |
string | rightText | [optional] Text to be displayed on the right side in regular print |
table | leftColor | [optional, default=<white>] Color of left text as an array {r, g, b, a} |
int | Display | row index of the newly added custom text or 0 if it could not be added |
Clear a custom text row previously added by FieldInfoDisplay:addCustomText().Definition
clearCustomText(int rowIndex)Arguments
int | rowIndex | [optional] Custom text row index as returned by FieldInfoDisplay:addCustomText(). If no value is provided, all custom text is cleared. |
Clear a single info row's data.Definition
clearInfoRow()
Clear all previously set field data.Definition
This does not clear custom text rows, which need to be cleared specifically using clearCustomText().
clearFieldData()
Called when FSDensityMapUtil.getFieldStatusAsync() in update() has finished.Definition
onFieldDataUpdateFinished(table data)Arguments
table | data | Field information data as provided by processing in FSDensityMapUtil.getFieldStatusAsync() |
Update the info display size depending on used rows.Definition
updateSize()
Draw the display.Definition
draw()
Draw text parts of this display element.Definition
drawText()
Get the scaled background position.Definition
getBackgroundPosition()
Set this element's UI scale factor.Definition
setScale(float uiScale)Arguments
float | uiScale | UI scale factor |
Store scaled position and size values.Definition
storeScaledValues()
Create the background overlay.Definition
createBackground()
Create required display components.Definition
createComponents()
Create the background frame element.Definition
createFrame()
Create row list container.Definition
createRowListContainer()
Create row separators.Definition
createSeparators()
Vehicle HUD fill levels display element.
-- Displays fill level bars for the current vehicle configuration
--@category GUI
Creates a new FillLevelsDisplay instance.Definition
new(string hudAtlasPath)Arguments
string | hudAtlasPath | Path to the HUD texture atlas. |
Set the currently controlled vehicle which provides display data.Definition
setVehicle(table vehicle)Arguments
table | vehicle | Currently controlled vehicle |
Update fill levels data.Definition
updateFillLevelBuffers()
Update fill level frames display state.Definition
updateFillLevelFrames()
Update the fill levels state.Definition
update()
Draw this element.Definition
draw()
Set this element's scale.Definition
setScale()
Get the position of the background element, which provides this element's absolute position.Definition
getBackgroundPosition(scale Current, float width)Arguments
scale | Current | UI scale |
float | width | Scaled background width in pixels |
float | X | position in screen space |
float | Y | position in screen space |
Calculate and store scaling values based on the current UI scale.Definition
storeScaledValues()
Create an empty background overlay as a base frame for this element.Definition
createBackground()
Refresh fill type data and elements.Definition
refreshFillTypes(table fillTypeManager)Arguments
table | fillTypeManager | FillTypeManager reference |
Create fill type frames for all known fill types.Definition
createFillTypeFrames()
Create a fill type frame for the display of a fill type level state.Definition
createFillTypeFrame()
Create an icon for a fill type.Definition
createFillTypeIcon()
Create a fill type bar used to display a fill level.Definition
The newly created bar is added to the given parent frame and an internal collection indexable by fill type index.
createFillTypeBar(string hudAtlasPath, table frame, float baseX, float baseY, table fillType)Arguments
string | hudAtlasPath | Path to HUD texture atlas |
table | frame | Parent frame HUD element |
float | baseX | Origin X position in screen space |
float | baseY | Origin Y position in screen space |
table | fillType | Fill type whose fill level is represented by the created bar |
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
Set the active GUI for focus input.Definition
setGui(Gui Screen)Arguments
Gui | Screen | root GuiElement |
Get a focusable GuiElement in the current view by its ID.Definition
getElementById()
Get the currently focused GuiElementDefinition
getFocusedElement()
Get a new automatic focus ID.Definition
It's based on a simple integer increment and will be unique unless billions of elements require an ID.
serveAutoFocusId()
Load GuiElement focus data from its XML definition.Definition
This is called at the end of GuiElement:loadFromXML().
loadElementFromXML()
Add an element to the focus system with custom values.Definition
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).
loadElementFromCustomValues(element Element, focusId Focus, focusChangeData Custom, focusActive If, isAlwaysFocusedOnOpen If)Arguments
element | Element | to add to focus system |
focusId | Focus | ID for element |
focusChangeData | Custom | focus navigation data for the element (map of direction to focus ID) |
focusActive | If | true, the element should be focused right now |
isAlwaysFocusedOnOpen | If | true, the element is supposed to be focused when its parent view is opened. |
True | if | the element and all of its children could be set up with the given values, false otherwise. |
Remove a GuiElement from the current focus context.Definition
removeElement()
Links an element's focus navigation to another element for a given direction.Definition
The link is unidirectional from source to target. If bi-directional links are desired, call this method again with
swapped arguments.
linkElements(sourceElement Source, direction Navigation, targetElement Target)Arguments
sourceElement | Source | element which receives the focus link. |
direction | Navigation | direction for the link, is not required to be the actual visual direction. |
targetElement | Target | element |
Handles input and changes focus if required and possible.Definition
inputEvent(action Name, value Input, eventUsed Usage)Arguments
action | Name | of navigation action which triggered the event, see InputAction |
value | Input | value [-1, 1] |
eventUsed | Usage | flag, no action is taken if this is true |
True | if | the input event has been consumed, false otherwise |
Get a direction value for a given menu input action and valueDefinition
getDirectionForAxisValue()
Checks if the focus manager has an input lock on input.Definition
isFocusInputLocked(inputAxis InputAction, value Axis, True if)Arguments
inputAxis | InputAction | axis or action code |
value | Axis | value [-1, 1] or nil if not a directional axis |
True | if | locked, false otherwise |
Locks a given input axis action's input for a time. Until the delay has passed, the focus manager will not react toDefinition
that input.
lockFocusInput(inputAxis InputAction, delay Delay, value Axis)Arguments
inputAxis | InputAction | axis or action code |
delay | Delay | in ms |
value | Axis | value [-1, 1], only relevant to identify directional axes |
Release a focus movement input lock on an action.Definition
Called by the UI input handling code. Avoid calling this for anything else.
releaseMovementFocusInput(action Focus)Arguments
action | Focus | movement input action name |
Reset all locks of focus input.Definition
resetFocusInputLocks()
Given a point and bounding box, get the closest other point on the bounding box circumference. If the point liesDefinition
within the bounding box, it is returned unchanged.
getClosestPointOnBoundingBox(x Point, y Point, boxMinX Bounding, boxMinY Bounding, boxMaxX Bounding, boxMaxY Bounding)Arguments
x | Point | X |
y | Point | Y |
boxMinX | Bounding | box minimum point X |
boxMinY | Bounding | box minimum point Y |
boxMaxX | Bounding | box maximum point X |
boxMaxY | Bounding | box maximum point Y |
Closest | point | x, y |
Calculate the shortest connecting line segment between two bounding boxes. Overlapping boxes will result in flippedDefinition
directions, so take care.
getShortestBoundingBoxVector()
Checks the distance between two GuiElements with the aim of incrementally finding the closest other element in aDefinition
direction within a screen view.
checkElementDistance(curElement Current, other Other, dirX Scan, dirY Scan, curElementOffsetY Position, closestOther Previously, closestDistanceSq Squared)Arguments
curElement | Current | checking GuiElement |
other | Other | GuiElement to compare |
dirX | Scan | direction vector x component, normalized to unit length |
dirY | Scan | direction vector y component, normalized to unit length |
curElementOffsetY | Position | y offset of current element's bounding volume, used when checking for wrap-around |
closestOther | Previously | closest other GuiElement |
closestDistanceSq | Squared | distance from the current checking element to the previously closest other GuiElement |
Find the next other element to the one provided in a given navigation directionDefinition
getNextFocusElement(element GUI, direction Direction)Arguments
element | GUI | element which needs a focus link |
direction | Direction | constant [TOP | BOTTOM | LEFT | RIGHT] |
Next | GUI | element in given direction which can be linked, actual scanning direction used (may change in wrap around scenarios) |
Get an element's focus target at the deepest nesting depth, e.g. when multiple nested layouts point down to theirDefinition
child elements until only a single element is left which points to itself.
getNestedFocusTarget(element GuiElement, direction Focus)Arguments
element | GuiElement | whose focus target needs to be retrieved |
direction | Focus | navigation direction |
Focus |
Update the current focus target.Definition
updateFocus(element GuiElement, isFocusMoving Only, direction Focus, updateOnly If)Arguments
element | GuiElement | which should be the new focus target |
isFocusMoving | Only | move focus if this is true |
direction | Focus | navigation movement direction, one of FocusManager.[TOP | BOTTOM | LEFT | RIGHT] |
updateOnly | If | true, only updates the lock state of focus movement for the given parameters |
Activate a highlight on an element. Highlighted elements are only visually marked and do not receive focus activation.Definition
Only one element will be highlighted at any time, usually corresponding to the current mouse over target.
setHighlight(element Element)Arguments
element | Element | to be highlighted. |
Remove highlight status from an element.Definition
unsetHighlight(element Highlighted)Arguments
element | Highlighted | element to revert |
Set focus on a GuiElement or its focus target.Definition
Applies overlay state and triggers onFocusEnter() on the target.
setFocus(element Element, direction Focus, ... Variable)Arguments
element | Element | whose focus target (usually itself) receives focus. |
direction | Focus | navigation direction |
... | Variable | arguments to pass on to the onFocusEnter callback of the target element |
True | if | focus has changed, false otherwise |
Removes focus from an element.Definition
Applies overlay state and triggers onFocusLeave() on the target.
unsetFocus(element Element, ... Variable)Arguments
element | Element | which should lose focus |
... | Variable | arguments to pass on to the onFocusLeave callback of the target element |
Set an elements focus overlay state for displaying.Definition
setElementFocusOverlayState(element Target, isFocus If, handlePreviousState [optional])Arguments
element | Target | element |
isFocus | If | true, 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. |
Globally lock focus input.Definition
requireLock()
Release the global focus input lock.Definition
releaseLock()
Check if focus input is locked.Definition
isLocked()
Determine if focus navigation in a given direction is currently locked.Definition
isDirectionLocked(direction Navigation)Arguments
direction | Navigation | direction as defined in constants |
True | if | navigation in given direction is locked |
Determine if a GuiElement is currently focused.Definition
hasFocus()
Get a closure override function for elements' getFocusOverride() methods.Definition
getFocusOverrideFunction(forDirections List, substitute Element, useSubstituteForFocus (Optional))Arguments
forDirections | List | of directions to override |
substitute | Element | to 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. |
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
Override of GuiElement:clone().Definition
Also exposes registered control element fields.
clone()
Override of GuiElement:copyAttributes().Definition
Also resets registered control IDs so they can be exposed as fields again.
copyAttributes()
Get the frame's root GuiElement instance.Definition
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.
getRootElement()
Register a collection of control IDs for direct access in GUI views.Definition
registerControls(controlIDs Table)Arguments
controlIDs | Table | which holds control IDs as values, as they are required to be present in the view configuration. |
Adds registered controls as fields to this FrameElement instance.Definition
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.
exposeControlsAsFields(viewName View)Arguments
viewName | View | name of this frame element |
Set input disabling to a given duration.Definition
disableInputForDuration(float duration)Arguments
float | duration | Input disabling duration in milliseconds |
Check if input is currently disabled.Definition
isInputDisabled()
Set a callback for requesting a view change from within a frame or screen view.Definition
setChangeScreenCallback(func callback)Arguments
func | callback | Function reference, signature: function(sourceFrameElement, targetScreenClass, returnScreenClass) |
Set a callback function for requesting a custom menu input context for this frame.Definition
setInputContextCallback(func callback)Arguments
func | callback | Function reference, signature: function(isContextActive) |
Set a callback function for requesting to play a sound sample.Definition
setPlaySampleCallback(func callback)Arguments
func | callback | Function reference, signature: function(sampleName) |
Request a view change via the callback defined by setChangeScreenCallback().Definition
changeScreen(table targetScreenClass)Arguments
table | targetScreenClass | Class table of requested view (ScreenElement descendant, must be full view) |
Request toggling of a custom menu input context for this frame via the callback defined by setInputContextCallback().Definition
toggleCustomInputContext(bool isContextActive, string contextName)Arguments
bool | isContextActive | If true, will activate a custom menu input context. Otherwise, will clear a previously activated context. |
string | contextName | Name of the custom input context. Use a unique identifier value. |
Request playing a sound sample identified by name.Definition
playSample(string sampleName)Arguments
string | sampleName | Sample name, use one of GuiSoundPlayer.SOUND_SAMPLES |
(Un)loading stations
Initialize mission after instantiation.Definition
Create complex members and call dependency methods in here so that mission instantiation cannot fail.
initialize()
Sets harvest ratios for fertilizer, plow, lime and weed factorDefinition
setHarvestScaleRatio(float sprayRatio, float plowRatio, float limeRatio, float weedRatio)Arguments
float | sprayRatio | fertilizer ratio |
float | plowRatio | plow ratio |
float | limeRatio | lime ratio |
float | weedRatio | weed ratio |
Get harvest multiplier based on fertilizer, plow, lime and weed factor, 1 = bestDefinition
getHarvestScaleMultiplier(integer fruitTypeIndex, float sprayFactor, float plowFactor, float limeFactor, float weedFactor)Arguments
integer | fruitTypeIndex | fruit type index |
float | sprayFactor | fertilizer factor |
float | plowFactor | plow factor |
float | limeFactor | lime factor |
float | weedFactor | weed factor |
float | multiplier | harvest multiplier |
Check which vehicles are accessible and notify the menu.Definition
updateMenuAccessibleVehicles()
Add an item to the owned items collection.Definition
Also notifies the shop.
addOwnedItem()
Remove an item from the owned items collection.Definition
Also notifies the shop.
removeOwnedItem()
Add an item to the leased items collection.Definition
Also notifies the shop.
addLeasedItem()
Remove an item from the leased items collection.Definition
Also notifies the shop.
removeLeasedItem()
Set or revert the pause input context based on current state.Definition
updatePauseInputContext()
Update saving process.Definition
Notifies the UI to display dialogs.
updateSaving()
Savegame device selection confirmation dialog response callback.Definition
onYesNoSavegameSelectDevice()
Savegame overwrite completion callback.Definition
onSaveGameUpdateComplete(int errorCode)Arguments
int | errorCode | Saving process status code, one of Savegame.ERROR_... |
Savegame overwrite confirmation dialog response callback.Definition
onYesNoSavegameOverwrite()
Display vehicle attachment context information for the current frame.Definition
showAttachContext()
Display vehicle tipping context information for the current frame.Definition
showTipContext()
Display vehicle refueling context information for the current frame.Definition
showFuelContext()
Display dog companion food bowl fill context information for the current frame.Definition
showFillDogBowlContext()
Get money for farm or current player farmDefinition
getMoney(farmId integer)Arguments
farmId | integer | if nil, then current farm (client only) |
Get whether the current player has given permission.Definition
getHasPlayerPermission(string permission, table connection, integer farmId, boolean checkClient)Arguments
string | permission | Permission to check |
table | connection | [optional] Client connection to check permission for |
integer | farmId | [optional] Limit permission to given farm (otherwise any farm) |
boolean | checkClient | [optional] if true it will only check the client permission |
Get the in-game map rendering component.Definition
Should only be used for UI.
getIngameMap()
Start saving the game.Definition
startSaveCurrentGame(bool isDediSaving)Arguments
bool | isDediSaving | If true, this is a saving call on a dedicated server |
Actually save the game locally.Definition
saveSavegame()
Returns a doghouseDefinition
getDoghouse(integer farmId)Arguments
integer | farmId |
table | instance | of the doghouse |
3144 | function 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 |
3151 | end |
Register a husbandry in the mission.Definition
registerHusbandry()
Unregister a husbandry in the mission.Definition
unregisterHusbandry()
Extract a concrete vehicle's display name from its store data.Definition
getVehicleName(table vehicle)Arguments
table | vehicle | Vehicle instance |
string | Vehicle | display name |
Register required input action events.Definition
registerActionEvents()
Register action events for pause actions.Definition
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.
registerPauseActionEvents()
Input event for "open menu".Definition
onToggleMenu()
Input event for "open shop".Definition
onToggleStore()
Toggle chat display.Definition
Called from input to open the chat dialog and from the chat dialog to close it again.
toggleChat()
Input event for "toggle radio".Definition
onToggleRadio()
Input event for "increase timescale" and "decrease timescale"Definition
onChangeTimescale()
Handle a settings change for showing help icons.Definition
onShowHelpIconsChanged()
Handle a settings change for the radio vehicle only setting.Definition
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).
onRadioVehicleOnlyChanged()
Handle a settings change for the radio active state.Definition
onRadioIsActiveChanged()
Set the active state for the radio action events.Definition
setRadioActionEventsState()
Subscribe to FS-specific event messages.Definition
The BaseMission parent class unsubscribes from messages in delete(). No clean-up required in sub-classes like this.
subscribeMessages()
Handle a local client changing the farm.Definition
notifyPlayerFarmChanged()
HUD general game information display.
-- Displays current game information. This includes weather, current account balance and time settings.
--@category GUI
Create a new instance of GameInfoDisplay.Definition
new(string hudAtlasPath)Arguments
string | hudAtlasPath | Path to the HUD texture atlas |
Set the money unit for displaying the account balance.Definition
setMoneyUnit(int moneyUnit)Arguments
int | moneyUnit | Money unit ID, any of [GS_MONEY_EURO | GS_MONEY_POUND | GS_MONEY_DOLLAR]. Invalid values are substituted by GS_MONEY_DOLLAR. |
Set the MissionStats reference for displaying information.Definition
setMissionStats(table missionStats)Arguments
table | missionStats | MissionStats reference, do not change |
Set the mission information reference for base information display.Definition
setMissionInfo(table missionInfo)Arguments
table | missionInfo | MissionInfo reference, do not change |
Set the environment reference to use for weather information display.Definition
setEnvironment(table environment)Arguments
table | environment | Environment reference, do not change |
Set visibility of the money display.Definition
setMoneyVisible()
Set visibility of time display.Definition
setTimeVisible()
Set visibility of temperature display.Definition
setTemperatureVisible()
Set visibility of weather display.Definition
setWeatherVisible()
Set visibility of tutorial progress display.Definition
setTutorialVisible()
Set the current tutorial progress values.Definition
setTutorialProgress(float progress)Arguments
float | progress | Progress expressed as a number between 0 and 1 |
Update the game info display state.Definition
update()
Update time display.Definition
updateTime()
Update temperature display.Definition
updateTemperature()
Update weather displayDefinition
updateWeather()
Get the game info display's width based on its visible info boxes.Definition
getVisibleWidth()Return Values
float | Game | info display width of visible elements in screen space |
Update sizes and positions of this elements and its children.Definition
updateSizeAndPositions()
Draw the game info display.Definition
draw()
Draw the text part of the money display.Definition
drawMoneyText()
Draw the text part of the time display.Definition
drawTimeText()
Draw the text part of the temperature display.Definition
drawTemperatureText()
Draw the text part of the tutorial progress display.Definition
drawTutorialText()
Make an animation for a weather change.Definition
animateWeatherChange()
Animate a weather icon becoming active.Definition
addActiveWeatherAnimation()
Animate a weather icon becoming inactive.Definition
addInactiveWeatherAnimation()
Animate a weather icon becoming the current weather icon.Definition
addBecomeCurrentWeatherAnimation()
Animate weather icon position changes.Definition
addWeatherPositionAnimation()
Get this element's base background position.Definition
getBackgroundPosition(float uiScale)Arguments
float | uiScale | Current UI scale factor |
Set this element's UI scale factor.Definition
setScale(float uiScale)Arguments
float | uiScale | UI scale factor |
Store scaled positioning, size and offset values.Definition
storeScaledValues()
Create the background overlay.Definition
createBackground()
Create required display components.Definition
Also adds a separator HUDElement instance as a field (".separator") to all info boxes.
createComponents()
Create the money display box.Definition
createMoneyBox()
Create the time display box.Definition
createTimeBox()
Create the temperature display box.Definition
createTemperatureBox()
Create the weather display box.Definition
createWeatherBox()
Create a weather icon for current and upcoming weather conditions.Definition
createWeatherIcon(string hudAtlasPath, int weatherId, float boxHeight, table uvs, table color)Arguments
string | hudAtlasPath | Path to HUD texture atlas |
int | weatherId | Weather condition ID, as defined in WeatherType... constants |
float | boxHeight | Screen space height of the box which will hold this icon |
table | uvs | UV coordinates of the weather icon in the HUD texture atlas |
table | color | Color RGBA array |
table | Weather | icon HUDElement instance |
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
string | hudAtlasPath | Path to HUD texture atlas |
float | leftX | Screen space left X position of newly created icon |
float | bottomY | Screen space bottom Y position of the parent box |
float | boxHeight | Screen space height of the parent box |
table | uvs | UV coordinates of the icon in the HUD texture atlas |
table | color | Color RGBA array |
table | Temperature | icon HUDElement instance |
Create a rotatable clock hand icon element.Definition
createClockHand(string hudAtlasPath, float posX, float posY, table size, table uvs, table color, table pivot)Arguments
string | hudAtlasPath | Path to HUD texture atlas |
float | posX | Screen space X position of the clock hand |
float | posY | Screen space Y position of the clock hand |
table | size | Pixel size vector {width, height} |
table | uvs | UV coordinates of the icon in the HUD texture atlas |
table | color | Color RGBA array |
table | pivot | UV pixel space rotation pivot coordinates |
table | Clock | hand HUDElement instance |
Create a time scale arrow icon element.Definition
createTimeScaleArrow(string hudAtlasPath, float posX, float posY, table size, table uvs)Arguments
string | hudAtlasPath | Path to HUD texture atlas |
float | posX | Screen space X position of the arrow |
float | posY | Screen space Y position of the arrow |
table | size | Pixel size vector {width, height} |
table | uvs | UV coordinates of the icon in the HUD texture atlas |
table | Time | scale arrow icon HUDElement instance |
Create and return a vertical separator element.Definition
createVerticalSeparator()
Create the tutorial progress box.Definition
createTutorialBox()
Sign-In Screen before Main Menu.
-- Used in console version.
-- @field startText Button prompt text to start the game.
GUI input event callback.Definition
See GuiElement:inputEvent().
inputEvent()
Event function for button sign in.Definition
signIn()
HUD game pause display element.
-- Displays a customizable message when the game is paused.
--@category GUI
Create a new GamePausedDisplay.Definition
new(string hudAtlasPath)Arguments
string | hudAtlasPath | Path to the HUD atlas texture. |
table | GamePausedDisplay | instance |
Set a custom text to display.Definition
setPauseText()
Handle menu visibility state change.Definition
onMenuVisibilityChange()
Set uniform UI scale.Definition
setScale()
Store scaled positioning, size and offset values.Definition
storeScaledValues()
Get this element's base background position.Definition
createBackground()
Create required display components.Definition
createComponents()
Graphical User Interface controller.
-- Builds UI from configurations, provides dialog display and propagates UI input.
--@category GUI
Load UI profile data from XML.Definition
loadProfiles(xmlFilename UI)Arguments
xmlFilename | UI | profiles definition XML file path, relative to application root. |
Load a UI screen view's elements from an XML definition.Definition
loadGui(xmlFilename View, name Screen, controller FrameElement, isFrame [optional,)Arguments
xmlFilename | View | definition XML file path, relative to application root. |
name | Screen | name |
controller | FrameElement | instance 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. |
Root | GuiElement | instance of loaded view or nil if the definition XML file could not be loaded. |
Recursively load and build a UI configuration.Definition
loadGuiRec(xmlFile Opened, xmlNodePath Current, parentGuiElement Current, target Target)Arguments
xmlFile | Opened | GUI configuration XML file |
xmlNodePath | Current | XML node path |
parentGuiElement | Current | parent GuiElement |
target | Target | of newly instantiated elements |
Tries resolving a frame reference.Definition
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.
resolveFrameReference(self Gui, frameRefElement FrameReferenceElement)Arguments
self | Gui | instance |
frameRefElement | FrameReferenceElement | instance to resolve |
Cloned | FrameElement | instance or frameRefElement if resolution failed. |
Get a UI profile by name.Definition
getProfile()
Determine if any menu or dialog is visible.Definition
getIsGuiVisible()
Determine if any dialog is visible.Definition
getIsDialogVisible()
Get a menu action event ID by its name.Definition
Modify GUI action events with care, as they are globally defined for an entire session.
getActionEventId()
Display and return a screen identified by name.Definition
showGui()Return Values
Root | GuiElement | of screen or nil if the name did not match any known screen. |
Display a dialog identified by name.Definition
showDialog()Return Values
Root | GuiElement | of dialog or nil if the name did not match any known dialog. |
Close a dialog identified by name.Definition
closeDialogByName()
Close a dialog identified by its root GuiElement.Definition
This is always called when a dialog is closed, usually by itself.
closeDialog()
Close all open dialogs.Definition
closeAllDialogs()
Register menu input.Definition
registerMenuInput()
GUI mouse event hook.Definition
This is used primarily for mouse location checks, as button inputs are handled by InputBinding.
mouseEvent()
GUI key event hook.Definition
This is used for GuiElements which need to have direct access to raw key input, such as TextInputElement.
keyEvent()
Update the GUI.Definition
Propagates update to all active UI elements.
update()
Draw the GUI.Definition
Propagates draw calls to all active UI elements.
draw()
Notify controls of an action input with a value.Definition
notifyControls(action Action, value Action)Arguments
action | Action | name as defined by loaded actions, see also scripts/input/InputAction.lua |
value | Action | value [-1, 1] |
True | if | any control has consumed the action event |
Event callback for menu input.Definition
onMenuInput()
Event callback for released movement menu input.Definition
onReleaseMovement()
Determine if a given GuiElement has input focus.Definition
hasElementInputFocus()
Get a screen controller instance by class for special cases.Definition
getScreenInstanceByClass(table screenClass)Arguments
table | screenClass | Class table of the requested screen |
table | ScreenElement | descendant instance of the given class or nil if no such instance was registered |
Change the currently displayed screen.Definition
changeScreen(table source, table screenClass, table returnScreenClass)Arguments
table | source | Source screen instance |
table | screenClass | Class table of the requested screen to change to or nil to close the GUI |
table | returnScreenClass | [optional] Class table of the screen which will be opened on a "back" action in the new screen. |
table | Root | GuiElement instance of target screen |
Make a change screen callback function which encloses the Gui self reference.Definition
This avoids passing the reference around as a parameter or global reference.
makeChangeScreenClosure()
Toggle a custom menu input context for one of the managed frames or screens.Definition
toggleCustomInputContext()
Make a toggle custom input context function which encloses the Gui self reference.Definition
makeToggleCustomInputContextClosure()
Make a play sample function which encloses the Gui self reference.Definition
makePlaySampleClosure()
Assign the play sample closure to a GUI element which has the PlaySampleMixin included.Definition
assignPlaySampleCallback(table guiElement)Arguments
table | guiElement | GuiElement instance |
table | The | GuiElement instance given in the guiElement parameter |
Enter a new menu input context.Definition
Menu views which require special input should provide a context name to not collide with the base menu input scheme.
enterMenuContext(string contextName)Arguments
string | contextName | [optional] Custom menu input context name |
Leave a menu input context.Definition
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).
leaveMenuContext()
Add the instance of a specific reusable GUI frame.Definition
addFrame()
Add the instance of a specific GUI screen.Definition
addScreen()
Set the current mission reference for GUI screens.Definition
setCurrentMission()
Set the current economy manager for GUI screens.Definition
The manager is initialized during mission loading.
setEconomyManager()
Let the GUI (and its components) process map data when it's loaded.Definition
loadMapData(int mapXmlFile)Arguments
int | mapXmlFile | Map configuration XML file handle, do not close, will be handled by caller. |
Set the network client reference for GUI screens.Definition
setClient()
Set multiplayer state on screens which need to know about it.Definition
setIsMultiplayer(bool isMultiplayer)Arguments
bool | isMultiplayer | If true, the GUI needs work in multiplayer mode. Otherwise, it's single player. |
Source in UI modules.Definition
initGuiLibrary(baseDir Base)Arguments
baseDir | Base | scripts directory |
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 <Value name="property_name" value="value" />. 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.
Create a new GuiElement.Definition
new(target Target)Arguments
target | Target | ScreenElement instance |
Load element data from an XML definition file.Definition
loadFromXML(xmlFile Definition, key XML)Arguments
xmlFile | Definition | XML file handle |
key | XML | node path to this element's definition |
Load profile data for this element.Definition
loadProfile(profile Loaded, applyProfile If)Arguments
profile | Loaded | GUI profile |
applyProfile | If | true, will re-calculate some dynamic properties. Use this when setting profiles dynamically at run time. |
Apply a GUI profile with a given name to this element.Definition
applyProfile(profileName Name, bool force)Arguments
profileName | Name | of the profile to apply to this element |
bool | force | [optional] If true, will apply all profile settings, including position and size. |
Delete any created frame overlays.Definition
deleteFrame()
Delete this GuiElement.Definition
Also deletes all child elements and removes itself from its parent and focus.
delete()
Create a deep copy clone of this GuiElement.Definition
clone(parent Target, includeId [optional,, suppressOnCreate [optional,)Arguments
parent | Target | parent 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 |
Copy all attributes from a source GuiElement to this GuiElement.Definition
copyAttributes()
Called on a screen view's root GuiElement when all elements in a screen view have been created.Definition
The event is propagated to all children, depth-first.
onGuiSetupFinished()
Create frame overlays if this element has a frame.Definition
createFrame()
Toggle a frame side's visibility identified by index.Definition
If this element has no frame this will have no effect.
toggleFrameSide(int sideIndex)Arguments
int | sideIndex | Index of the frame side, use one of GuiElement.FRAME_... |
Update the frame overlay positions if necessary.Definition
updateFramePosition()
Cut horizontal frame borders if a vertical frame side is thicker.Definition
cutFrameBordersHorizontal()
Cut vertical frame borders if a horizontal frame side is thicker.Definition
cutFrameBordersVertical()
Mouse event hook for mouse movement checks.Definition
mouseEvent()
Handles an input event on a menu input action.Definition
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.
inputEvent(action Name, value Input, eventUsed If)Arguments
action | Name | of input action which was triggered. |
value | Input | value in the range of [-1, 1] for full axes and [0, 1] for half axes (includes buttons) |
eventUsed | If | true, the event has been used by an input handler and should only be acted upon in exceptional cases. |
True | if | the input event has been handled, false otherwise. |
Key event hook for raw keyboard input.Definition
keyEvent()Return Values
True | if | the keyboard input has been processed by this element. |
Update this GuiElement.Definition
update()
Draw this GuiElement.Definition
If defined, triggers the "onDrawCallback".
draw()
Called on the root element of a screen view when it is opened.Definition
This raises the "onOpenCallback" if defined and propagates to all children.
onOpen()
Called on the root element of a screen view when it is closed.Definition
This raises the "onCloseCallback" if defined and propagates to all children.
onClose()
Determine if this GuiElement should change focus in a given direction.Definition
shouldFocusChange()
Determine if this GuiElement can receive focus.Definition
canReceiveFocus()
Called when this element loses focus.Definition
This propagates to all children.
onFocusLeave()
Called when this element becomes focused.Definition
This propagates to all children.
onFocusEnter()
Called when this element has focus and the focus activation action is triggered.Definition
This propagates to all children.
onFocusActivate()
Called when this element is highlighted.Definition
This propagates to all children.
onHighlight()
Called when this element loses the highlight.Definition
This propagates to all children.
onHighlightRemove()
Definition
Store the current overlay state while another overrides it (e.g. pressed state)
storeOverlayState()
Restore a previously stored overlay state after an overriding state has expiredDefinition
restoreOverlayState()
Determine if this element can receive focus.Definition
getHandleFocus()
Set this elements capability to receive focus.Definition
setHandleFocus()
Add a child GuiElement to this GuiElement.Definition
addElement()
Remove a child GuiElement from this GuiElement.Definition
removeElement()
Safely remove this GuiElement from its parent, if it has a parent.Definition
unlinkElement()
Update this elements absolute screen position.Definition
This needs to be called whenever a position, alignment, origin or size value changes.
updateAbsolutePosition()
Resets the state of this GuiElement and its children.Definition
reset()
Check if this element is the child of another element.Definition
This checks the full parent hierarchy.
isChildOf()
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. |
GuiElement | Actual | element to focus. |
Set this element's position.Definition
setPosition()
Modify this element's position (i.e. translate position).Definition
move()
Directly set the absolute screen position of this GuiElement.Definition
Also updates children accordingly.
setAbsolutePosition()
Set this element's size.Definition
setSize()
Set this element's visibility.Definition
setVisible()
Determine if this element is visible.Definition
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.
getIsVisible()
Set this element's disabled state.Definition
Disabled elements can be displayed differently and do not respond to input actions.
setDisabled(disabled If, doNotUpdateChildren If)Arguments
disabled | If | true, disables the element. False enables it again. |
doNotUpdateChildren | If | true, does not apply the disabled state to child elements. |
Determine if this element is disabled.Definition
getIsDisabled()
Determine if this element is currently selected.Definition
getIsSelected()
Determine if this element is currently highlighted.Definition
getIsHighlighted()
Fade this element into visibility.Definition
fadeIn()
Fade this element out of visibility.Definition
fadeOut()
Directly set this element's alpha (transparency) valueDefinition
setAlpha(alpha Transparency)Arguments
alpha | Transparency | value in the floating point range of [0, 1], where 0 is invisible and 1 is opaque. |
Determine if this element is active (not disabled and visible).Definition
Does not take alpha value into account.
getIsActive()
Toggle a flag to suppress UI sounds issued by this element or by the FocusManager when handling this element.Definition
This setting will propagate to children.
setSoundSuppressed()
Get the sound suppression flag from this element.Definition
If the flag is set to true, no sounds should be played when interacting with this element.
getSoundSuppressed()
Definition
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.
findDescendantsRec(accumulator List, rootElement Current, predicateFunction [optional])Arguments
accumulator | List | which receives descendant elements |
rootElement | Current | element root whose direction children are added (after optional evaluation) |
predicateFunction | [optional] | If specified, will be evaluated per element (see getDescendants) |
Get all contained elements of this element in the entire hierarchy.Definition
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.
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. |
List | of | this element's descendants in depth-first order with contiguous numeric indices. |
Get the first descendant element of this element which matches a predicate function.Definition
This is a shorthand for getDescendants() which returns just the first element matching the predicate function or nil
if no matching element exists.
getFirstDescendant(predicateFunction A)Arguments
predicateFunction | 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. |
First | matching | descendant element in depth-first order or nil, if no element matched the predicate function |
Get a descendant element of this element by its ID.Definition
This is a shorthand for getDescendants() with an ID matching predicate function.
getDescendantById(id Element)Arguments
id | Element | id |
element | or | nil |
Get a descendant element of this element by its name.Definition
This is a shorthand for getDescendants() with an ID matching predicate function.
getDescendantByName(name Element)Arguments
name | Element | name |
element | or | nil |
Get the bit mask value for a position origin string value.Definition
updatePositionForOrigin()
Get the bit mask value for a screen alignment string value.Definition
updateScreenAlign()
Get the bottom left and top right corners of this element's parent's border rectangle.Definition
If this element has no parent, the full screen's borders are returned (i.e. {0, 0, 1, 1})
getParentBorders()Return Values
parent | element | or full screen borders in an array: {minX, minY, maxX, maxY} |
Get this element's border rectangle represented by minimum and maximum points.Definition
getBorders()Return Values
element | borders | in an array: {minX, minY, maxX, maxY} |
Get this element's center position.Definition
getCenter()
Apply screen alignment to this element and its children.Definition
Scales size, position and margin depending on alignment settings.
applyScreenAlignment()
Set this element's overlay stateDefinition
setOverlayState(overlayState Overlay)Arguments
overlayState | Overlay | state identified by one of the GuiOverlay.STATE_[...] constants. |
Get this element's overlay state.Definition
getOverlayState()
Add a callback to this element which was defined in its XML definition.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.
addCallback(xmlFile XML, key XML, funcName Name)Arguments
xmlFile | XML | file handle |
key | XML | node path of this GuiElement's definition. |
funcName | Name | of the callback function |
Raise a previously added callback by name.Definition
raiseCallback()
Try to extract a field name and index from an element ID.Definition
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.
extractIndexAndNameFromID(elementId Element)Arguments
elementId | Element | ID, to be used as a field name on a ScreenElement view. |
index | or | nil, field name |
Try setting this element's ID from its XML definition.Definition
setId()
Include a mixin in this element.Definition
See GuiMixin.lua for the details on usage and implementation of mixins.
include(guiMixinType Class)Arguments
guiMixinType | Class | table reference of a descendant of GuiMixin |
Get a nice string representation for this GUI element.Definition
toString()
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
Create a new GuiMixin instance.Definition
Subclasses need to provide their class type table for identification.
new(class Class, mixinType Class)Arguments
class | Class | metatable |
mixinType | Class | type table |
New |
Add a mixin to a GuiElement.Definition
Adds mixin methods to the element which can then be used. A mixin's state is located in "element[mixinType]".
addTo()
Determine if a GuiElement has a mixin type included.Definition
hasIncluded(GuiElement GuiElement, mixinType GuiMixin)Arguments
GuiElement | GuiElement | instance |
mixinType | GuiMixin | class reference |
Clone mixin states for a mixin type from a source to a destination GuiElement instance.Definition
cloneMixin()
Clone this mixin's state from a source to a destination GuiElement instance.Definition
clone()
GUI overlay manager.
-- Handles creation, loading and basic rendering of GUI overlays. This module has no interaction with Overlay.lua.
--@category GUI
Loads overlay data from XML or a profile into a table to turn it into an overlay.Definition
loadOverlay()
Load overlay UV data from XML.Definition
loadXMLUVs()
Load overlay UV data from a profile.Definition
loadProfileUVs()
Load overlay color data from XML.Definition
loadXMLColors()
Load overlay color data from a profile.Definition
loadProfileColors()
(Re-)Create an overlay.Definition
createOverlay(Overlay Overlay, filename Path)Arguments
Overlay | Overlay | table, see loadOverlay() |
filename | Path | to image file (can also be a URL for web images) |
Overlay | table | with added image data |
Copy an overlay.Definition
copyOverlay()
Delete an overlay.Definition
Primarily releases the associated image file handle.
deleteOverlay()
Get an overlay's color for a given overlay state.Definition
getOverlayColor(Overlay Overlay, state GuiOverlay.STATE_[...])Arguments
Overlay | Overlay | table |
state | GuiOverlay.STATE_[...] | constant value |
Color | as | {red, green, blue, alpha} with all values in the range of [0, 1] |
Get an overlay's UV coordinates for a given overlay state.Definition
getOverlayUVs(Overlay Overlay, state GuiOverlay.STATE_[...])Arguments
Overlay | Overlay | table |
state | GuiOverlay.STATE_[...] | constant value |
UV | coordinates | as {u1, v1, u2, v2, u3, v3, u4x, v4} with all values in the range of [0, 1] |
Renders an overlay with the given parameters.Definition
renderOverlay(Overlay Overlay, posX Screen, posY Screen, sizeX Screen, sizeY Screen, state GuiOverlay.STATE_[...])Arguments
Overlay | Overlay | table |
posX | Screen | x position |
posY | Screen | y position |
sizeX | Screen | x size |
sizeY | Screen | y size |
state | GuiOverlay.STATE_[...] | constant for the required display state |
GUI element display profile.
-- Holds GuiElement property data for re-use similar to a HTML/CSS definition.
--@category GUI
Create a new GuiProfile.Definition
new(profiles Reference, traits Reference)Arguments
profiles | Reference | to loaded profiles table for inheritance checking. |
traits | Reference | to loaded traits table for inheritance checking. |
New | GuiProfile | instance |
Load profile data from XML.Definition
loadFromXML(xmlFile XML, key Profile, presets Table, isTrait Whether)Arguments
xmlFile | XML | file handle |
key | Profile | XML element node path |
presets | Table | of presets for symbol resolution, {preset name=preset value} |
isTrait | Whether | this profile is a trait |
True | if | profile values could be loaded, false otherwise. |
Get a string value from this profile (and its ancestors) by name.Definition
getValue(name Name, default Default)Arguments
name | Name | of attribute value to retrieve |
default | Default | value to use if the attribute is not defined. |
Get a boolean value from this profile (and its ancestors) by name.Definition
getBool(name Name, default Default)Arguments
name | Name | of attribute value to retrieve |
default | Default | value to use if the attribute is not defined. |
Get a number value from this profile (and its ancestors) by name.Definition
getNumber(name Name, default Default)Arguments
name | Name | of attribute value to retrieve |
default | Default | value to use if the attribute is not defined. |
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
Create a new GuiSoundPlayer instance.Definition
new(table soundManager)Arguments
table | soundManager | SoundManager reference |
Load GUI sound samples from definitions.Definition
loadSounds()
Play a GUI sound sample identified by name.Definition
The sample must have been loaded when the GUI was created.
playSample(string sampleName)Arguments
string | sampleName | Name of the sample to play, use one of the identifiers in GuiSoundPlayer.SOUND_SAMPLES. |
GUI utility functions.
--@category GUI
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
str | Attribute | string containing numbers, either raw or with a pixel unit designation on each number (e.g. "12 24" or "12px 24px") |
refSize | Reference | size for normalization, e.g. a reference screen resolution used to scale pixel values, {sizeX, sizeY} |
defaultValue | Default | value to return if the "str" parameter value is nil |
array | of | normalized values |
Transform an attribute string representing a 2D array into an actual array.Definition
get2DArray(str Attribute, defaultValue Default)Arguments
str | Attribute | string containing exactly 2 numbers |
defaultValue | Default | value to return if the "str" parameter value is nil or invalid for transformation. |
array | of | the 2 converted values as numbers: {value1, value2} |
Transform an attribute string representing a 4D array into an actual array.Definition
get4DArray(str Attribute, defaultValue Default)Arguments
str | Attribute | string containing exactly 4 numbers |
defaultValue | Default | value to return if the "str" parameter value is nil or invalid for transformation. |
array | of | the 4 converted values as numbers: {value1, value2, value3, value4} |
Transform an attribute string representing a 4D color array into an actual array.Definition
getColorArray(str Attribute, defaultValue Default)Arguments
str | Attribute | string containing exactly 4 numbers |
defaultValue | Default | value to return if the "str" parameter value is nil or invalid for transformation. |
array | of | the 4 converted values as numbers: {red, green, blue, alpha} |
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
str | Attribute | string containing exactly 4 numbers, order and format: "x[px] y[px] sizeX[px] sizeY[px]" |
ref | Texture | reference size used to normalize pixel UV coordinates into unit sized UV coordinates |
defaultValue | Default | value to return if the "str" parameter value is nil or invalid for transformation. |
array | of | the UV coordinates as {u1, v1, u2, v2, u3, v3, u4, v4} |
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
posX | Point | or hotspot x position |
posY | Point | or hotspot y position |
overlayX | Overlay | x position |
overlayY | Overlay | y position |
overlaySizeX | Overlay | width |
overlaySizeY | Overlay | height |
hotspot | If | provided 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. |
HighPressureWasher Activatable
Creating placeable high pressure washerDefinition
new(boolean isServer, boolean isClient, table customMt)Arguments
boolean | isServer | is server |
boolean | isClient | is client |
table | customMt | custom metatable |
table | instance | Instance of object |
20 | function 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 |
30 | end |
Load high pressure washerDefinition
load(string xmlFilename, float x, float y, float z, float rx, float ry, float rz, boolean initRandom)Arguments
string | xmlFilename | xml file name |
float | x | x world position |
float | y | z world position |
float | z | z world position |
float | rx | rx world rotation |
float | ry | ry world rotation |
float | rz | rz world rotation |
boolean | initRandom | initialize random |
boolean | success | success |
43 | function 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 |
87 | end |
Deleting placeable high pressure washerDefinition
delete()Code
91 | function 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) |
103 | end |
Called on client side on joinDefinition
readStream(integer streamId, table connection)Arguments
integer | streamId | stream ID |
table | connection | connection |
109 | function 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 |
120 | end |
Called on server side on joinDefinition
writeStream(integer streamId, table connection)Arguments
integer | streamId | stream ID |
table | connection | connection |
126 | function 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 |
134 | end |
Activate hand toolDefinition
activateHandtool(table player)Arguments
table | player | player |
139 | function HighPressureWasher:activateHandtool(player) |
140 | self:setIsTurnedOn(true, player, true) |
141 | end |
UpdateDefinition
update(float dt)Arguments
float | dt | time since last call in ms |
146 | function 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() |
180 | end |
updateTickDefinition
updateTick(float dt)Arguments
float | dt | time since last call in ms |
197 | function 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 |
210 | end |
Set is turned onDefinition
setIsTurnedOn(boolean isTurnedOn, table player, boolean noEventSend)Arguments
boolean | isTurnedOn | is turned on |
table | player | player |
boolean | noEventSend | no event send |
217 | function 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 |
249 | end |
onPlayerDelete()Code
253 | function HighPressureWasher:onPlayerDelete() |
254 | self.currentPlayer = nil |
255 | self:setIsTurnedOn(false, nil, nil) |
256 | end |
onHandtoolDelete()Code
260 | function HighPressureWasher:onHandtoolDelete() |
261 | self.currentPlayer = nil |
262 | self:setIsTurnedOn(false, nil, nil) |
263 | end |
On deactivateDefinition
onDeactivate()Code
267 | function 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 |
284 | end |
Get is active for inputDefinition
getIsActiveForInput()Return Values
boolean | isActiveForInput | is active for input |
289 | function 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 |
294 | end |
Get is active for soundDefinition
getIsActiveForSound()Return Values
boolean | isActiveForSound | is active for sound |
299 | function HighPressureWasher:getIsActiveForSound() |
300 | return self:getIsActiveForInput() |
301 | end |
Get can be sold in current stateDefinition
canBeSold()Return Values
boolean | ||
string | warningMessage | warning message displayed in the shop |
307 | function 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 |
313 | end |
Minimum daily riding time for a horse below which it will lose fitness.
new()Code
22 | function 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 |
38 | end |
readStream()Code
42 | function 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) |
49 | end |
writeStream()Code
53 | function 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) |
60 | end |
readUpdateStream()Code
64 | function 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 |
74 | end |
writeUpdateStream()Code
78 | function 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 |
88 | end |
loadFromXMLFile()Code
92 | function 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 |
100 | end |
saveToXMLFile()Code
104 | function 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) |
111 | end |
setName()Code
115 | function 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 |
121 | end |
getName()Code
125 | function Horse:getName() |
126 | return self.name |
127 | end |
getValueScale()Code
131 | function Horse:getValueScale() |
132 | -- dirt scale should only count 10% |
133 | return 0.90 * (self.fitnessScale * self.healthScale) + 0.10 * (1-self.dirtScale) |
134 | end |
setFitnessScale()Code
138 | function 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 |
148 | end |
getFitnessScale()Code
152 | function Horse:getFitnessScale() |
153 | return self.fitnessScale |
154 | end |
setHealthScale()Code
158 | function 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 |
168 | end |
getHealthScale()Code
172 | function Horse:getHealthScale() |
173 | return self.healthScale |
174 | end |
Get the riding time of this horse for the current day in milliseconds.Definition
getTodaysRidingTime()
deactivateRiding()Code
183 | function Horse:deactivateRiding(noEventSend) |
184 | if self.rideableVehicle ~= nil then |
185 | self.rideableVehicle:setFitnessChangedCallback(nil, nil) |
186 | end |
187 | |
188 | Horse:superClass().deactivateRiding(self, noEventSend) |
189 | end |
onLoadedRideable()Code
193 | function 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 |
199 | end |
onFitnessChangedCallback()Code
203 | function Horse:onFitnessChangedCallback(deltaTime) |
204 | self.ridingTimer = self.ridingTimer + deltaTime |
205 | end |
updateFitness()Code
209 | function 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 |
225 | end |
Heads-up display.
-- The HUD displays information for the player when in game.
--@category GUI
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
bool | isServer | If true, the running game instance is a server |
bool | isServer | If true, the running game instance is a client |
bool | isConsoleVersion | If true, we are running on console |
table | messageCenter | MessageCenter reference for message subscriptions |
table | l10n | I18N reference for text localization |
table | inputManager | InputBinding reference |
table | inputDisplayManager | InputDisplayManager reference |
table | modManager | ModManager reference |
table | fillTypeManager | FillTypeManager reference |
table | fruitTypeManager | FruitTypeManager reference |
table | guiSoundPlayer | GuiSoundPlayer reference |
Create all required display components.Definition
createDisplayComponents(uiScale Current)Arguments
uiScale | Current | UI scale |
Delete the HUD and all its display components.Definition
delete()
Subscribe to relevant state messages.Definition
subscribeMessages()
Set the scale of the HUD.Definition
setScale(float scale)Arguments
float | scale | New scale value |
Draw the HUD components for the currently controlled entity (player or vehicle).Definition
drawControlledEntityHUD()
Draw the input help display panel and vehicle schema.Definition
drawInputHelp()
Draw a notification at the top center of the screen if one has been set.Definition
drawTopNotification()
Draw a blinking warning if necessary.Definition
drawBlinkingWarning()
Draw the presentation mode logo.Definition
drawPresentationVersion()
Draw the screen fade effect.Definition
drawFading()
Draw an overlay at a given screen space position with given dimensions.Definition
Omitting a parameter will use the last setting of that parameter (or initial setting if parameter is never supplied).
drawOverlayAtPositionWithDimensions(table overlay, float screenX, float screenY, float screenWidth, float screenHeight)Arguments
table | overlay | Overlay instance to draw |
float | screenX | Drawing origin X position in screen space |
float | screenY | Drawing origin Y position in screen space |
float | screenWidth | Drawing horizontal size in screen space |
float | screenHeight | Drawing vertical size in screen space |
Draw an overlay at a given screen space position.Definition
Omitting a parameter will use the last setting of that parameter.
drawOverlayAtPosition(table overlay, float screenX, float screenY)Arguments
table | overlay | Overlay instance to draw |
float | screenX | Drawing origin X position in screen space |
float | screenY | Drawing origin Y position in screen space |
Draw notification texts at the side of the screen.Definition
drawSideNotification()
Draw the regular HUD for career mode.Definition
drawBaseHUD()
Draw the platform communication display (chat or speaker icons).Definition
drawCommunicationDisplay()
Set the tutorial progress.Definition
setTutorialProgress(float progress)Arguments
float | progress | Progress expressed as a number between 0 and 1 |
Draw a pause notification with a message text and synchronizing background if the menu is visible.Definition
drawGamePaused(bool beforeMissionStart)Arguments
bool | beforeMissionStart | If true, draw a special overlay for cases when the menu has not yet loaded but the world is already visible. |
Draw the current vehicle name if it's active.Definition
drawVehicleName()
Draw the message window and icon at the bottom of the screen.Definition
drawInGameMessageAndIcon()
Show a "mission accomplished" message.Definition
drawMissionCompleted()
Show a "mission failed" message.Definition
drawMissionFailed()
Display an in-game message in a window at the bottom.Definition
This calls InGameMessage:showMessage(title, message, duration, controls, callback, target).
showInGameMessage()
Display a blinking warning text.Definition
showBlinkingWarning(string text, int duration, int priority)Arguments
string | text | Warning text |
int | duration | [optional, default=2000] Duration of warning visibility in milliseconds |
int | priority | [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. |
Accumulate a money transaction amount by type until shown by HUD.showMoneyChange().Definition
addMoneyChange(int moneyType, float amount)Arguments
int | moneyType | Type of transaction from EconomyManager.MONEY_TYPE_XYZ |
float | amount | Amount of money |
Display a money change notification at the right side of the screen.Definition
showMoneyChange(int moneyType, string text)Arguments
int | moneyType | Type of transaction from EconomyManager.MONEY_TYPE_XYZ |
string | text | Specific money type label (e.g. "loan interest") |
Add an extra text to display in the input help panel for this frame.Definition
addExtraPrintText()
Display the name of a vehicle at the bottom of the screen for a short time.Definition
showVehicleName(string vehicleName)Arguments
string | vehicleName | Name of a vehicle |
Add a notification to be displayed at the right side of the screen.Definition
addSideNotification(table color)Arguments
table | color | Color as an RGBA array |
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
string | title | Notification title |
string | text | Notification message text |
string | info | Additional info text |
table | iconKey | [optional] Icon key for a display icon, use a value from TopNotification.ICON |
int | duration | [optional] Display duration in milliseconds. Negative values or nil default to a long-ish standard duration. |
Hide a current notification shown by HUD:addTopNotification().Definition
hideTopNotification()
Check if the HUD is currently fading the screen.Definition
getIsFading()
Set the visibility of the game info display parts by flags.Definition
setGameInfoPartVisibility(partFlags Combination)Arguments
partFlags | Combination | of values from HUD.GAME_INFO_PART |
Handle menu visibility changes.Definition
Keeps track of the menu visibility to block relevant processes.
onMenuVisibilityChange()
Handle game pause state changes.Definition
onPauseGameChange(bool isPaused, string pauseText)Arguments
bool | isPaused | [optional] If true, the game is currently paused. If not set, will not change the pause state. |
string | pauseText | [optional] Text to display on the pause element |
Set HUD visibility.Definition
setIsVisible(bool isVisible)Arguments
bool | isVisible | If true, the HUD is made visible. If false, it's made invisible. |
Set input help visibility.Definition
setInputHelpVisible(bool isVisible)Arguments
bool | isVisible | If true, the input help is displayed. If false, it's made invisible |
Set field info display visibility.Definition
setFieldInfoVisible(bool isVisible)Arguments
bool | isVisible | If true, the field info display is shown. If false, it's hidden. |
Add a custom input help entry which is displayed until removed.Definition
Custom entries will be displayed in order of addition after any automatically detected input help entries and before
vehicle extensions.
addCustomInputHelpEntry()
Clear all custom input help entries.Definition
clearCustomInputHelpEntries()
Check if the HUD is visible.Definition
getIsVisible()Return Values
bool | If | true, the HUD is currently visible. |
Set current controlled vehicle.Definition
setControlledVehicle(table vehicle)Arguments
table | vehicle | Vehicle reference or nil (not controlling a vehicle) |
Set current player controlling state.Definition
setIsControllingPlayer(bool isControllingPlayer)Arguments
bool | isControllingPlayer | If true, the player is controlling their character on foot. |
Set the money unit (currency) to display.Definition
setMoneyUnit(int unit)Arguments
int | unit | One of [GS_MONEY_EURO | GS_MONEY_POUND], any other value will display a universal dollar sign. |
Display an achievement message.Definition
showAchievementMessage()
Display vehicle attachment context information for the current frame.Definition
showAttachContext()
Display vehicle tipping context information for the current frame.Definition
showTipContext()
Display vehicle refueling context information for the current frame.Definition
showFuelContext()
Display dog bowl refilling context information for the current frame.Definition
showFillDogBowlContext()
Set the reference to the current player.Definition
setPlayer()
Set the references to the currently connected users.Definition
setConnectedUsers()
Update in-game message window and icon.Definition
updateMessageAndIcon()
Update base HUD state.Definition
update()
Update the blinking warning if one is set.Definition
updateBlinkingWarning()
Update the in-game map.Definition
updateMap()
Update vehicle name display when a vehicle was entered.Definition
updateVehicleName()
Fade the screen.Definition
fadeScreen(int direction, int duration, func callbackFunc, table callbackTarget)Arguments
int | direction | If > 0 will fade to opaque (i.e. black screen), if < 0 will fade to transparent (i.e. clear) |
int | duration | Target duration of the fade animation in milliseconds |
func | callbackFunc | [optional] Callback function which is called when the fading animation completes |
table | callbackTarget | [optional] Callback function target which is passed to the callback function as its first argument if provided |
Load graphics and settings for the in-game map.Definition
loadIngameMap(string ingameMapFilename, int ingameMapWidth, int ingameMapHeight)Arguments
string | ingameMapFilename | Path to map image |
int | ingameMapWidth | Width of the map (X) |
int | ingameMapHeight | Height of the map (Y) |
Set the size index of the in-game map.Definition
setIngameMapSize(int sizeIndex)Arguments
int | sizeIndex | One of [IngameMap.STATE_MINIMAP | IngameMap.STATE_MAP | IngameMap.STATE_OFF] |
Get the in-game map reference.Definition
getIngameMap()
Check if the in-game message is currently active.Definition
isInGameMessageActive()
Mouse event function.Definition
Only delegates input to components.
mouseEvent()
Set the environment reference to use for weather information display.Definition
setEnvironment(table environment)Arguments
table | environment | Environment reference, do not change |
Set the mission information reference for base information display.Definition
setMissionInfo(table missionInfo)Arguments
table | missionInfo | MissionInfo reference, do not change |
Set the mission statistics reference for base information display.Definition
setMissionStats(table missionStats)Arguments
table | missionStats | MissionStats reference, do not change |
Set the in-game icon display when picking up an egg or nugget.Definition
setInGameIconOnPickup()
Scroll chat messages by a given amount.Definition
scrollChatMessages(int delta, int numMessages)Arguments
int | delta | Number of lines (positive or negative) to scroll |
int | numMessages | Number of currently stored chat messages |
Set chat window visibility.Definition
When disabled, the chat display will linger for some time.
setChatWindowVisible()
Set the chat messages array reference for the chat window.Definition
The array is owned by the caller and must not be modified by consumers.
setChatMessagesReference()
Register input events of HUD components.Definition
registerInput()
HUD display element whose subclasses implement more complex HUD display subsystems.
--@category GUI
Create a new HUD display element.Definition
new(table subClass, table overlay, table parentHudElement)Arguments
table | subClass | Subclass metatable for inheritance |
table | overlay | Wrapped Overlay instance |
table | parentHudElement | [optional] Parent HUD element of the newly created HUD element |
table | HUDDisplayElement | instance |
Set this element's visibility with optional animation.Definition
setVisible(bool isVisible, bool animate)Arguments
bool | isVisible | True is visible, false is not. |
bool | animate | If true, the element will play an animation before applying the visibility change. |
Simplification of scale setter because these high-level elements always use a uniform scale.Definition
setScale()
Store the current element position as its original positions.Definition
storeOriginalPosition()
Get the screen space translation for hiding.Definition
Override in sub-classes if a different translation is required.
getHidingTranslation()Return Values
float | Screen | space X translation |
float | Screen | space Y translation |
Animation setter function for X position.Definition
animationSetPositionX()
Animation setter function for Y position.Definition
animationSetPositionY()
Animate this element on hiding.Definition
animateHide()
Animate this element on showing.Definition
animateShow()
Called when a hiding or showing animation has finished.Definition
onAnimateVisibilityFinished()
Lightweight HUD UI element.
-- Wraps an Overlay instance to display and provides a transform hierarchy of child HUDElement instances.
--@category GUI
Create a new HUD element.Definition
new(table subClass, table overlay, table parentHudElement)Arguments
table | subClass | Subclass metatable for inheritance |
table | overlay | Wrapped Overlay instance |
table | parentHudElement | [optional] Parent HUD element of the newly created HUD element |
table | HUDElement | instance |
Delete this HUD element and all its children.Definition
This will also delete the overlay and thus release its engine handle.
delete()
Add a child HUD element to this element.Definition
addChild(table childHudElement)Arguments
table | childHudElement | HUDElement instance which is added as a child. |
Remove a child HUD element from this element.Definition
removeChild(table childHudElement)Arguments
table | childHudElement | HUDElement instance which is removed as a child. |
Set a HUD element's absolute screen space position.Definition
If the element has any children, they will be moved with this element.
setPosition()
Set this HUD element's rotation.Definition
Does not affect children. If no center position is given, the element's pivot values are used (default to 0)
setRotation(float rotation, float centerX, float centerY)Arguments
float | rotation | Rotation in radians |
float | centerX | [optional] Rotation pivot X position offset from overlay position in screen space |
float | centerY | [optional] Rotation pivot Y position offset from overlay position in screen space |
Set this HUD element's rotation pivot point.Definition
setRotationPivot(float pivotX, float pivotY)Arguments
float | pivotX | Pivot x position offset from element position in screen space |
float | pivotY | Pivot y position offset from element position in screen space |
Get this HUD element's rotation pivot point.Definition
getRotationPivot()Return Values
float | Pivot | x position offset from element position in screen space |
float | Pivot | y position offset from element position in screen space |
Get this HUD element's position.Definition
getPosition()Return Values
float | X | position in screen space |
float | Y | position in screen space |
Set this HUD element's scale.Definition
This will move and scale children proportionally.
setScale(float scaleWidth, float scaleHeight)Arguments
float | scaleWidth | Width scale factor |
float | scaleHeight | Height scale factor |
Get this HUD element's scale.Definition
getScale()Return Values
width | scale | factor |
height | scale | factor |
Set this HUD element's positional alignment.Definition
See Overlay:setAlignment for positioning logic.
setAlignment(int vertical, int horizontal)Arguments
int | vertical | Vertical alignment value [Overlay.ALIGN_VERTICAL_BOTTOM | Overlay.ALIGN_VERTICAL_MIDDLE | Overlay.ALIGN_VERTICAL_TOP] |
int | horizontal | Horizontal alignment value [Overlay.ALIGN_HORIZONTAL_LEFT | Overlay.ALIGN_HORIZONTAL_CENTER | Overlay.ALIGN_HORIZONTAL_RIGHT] |
Set this HUD element's visibility.Definition
setVisible()
Get this HUD element's visibility.Definition
getVisible()
Get this HUD element's color.Definition
getColor()Return Values
float | Red | value |
float | Green | value |
float | Blue | value |
float | Alpha | value |
Get this HUD element's color alpha value.Definition
getAlpha()Return Values
float | Alpha | value |
Get this HUD element's width in screen space.Definition
getWidth()
Get this HUD element's height in screen space.Definition
getHeight()
Set this HUD element's width and height.Definition
Either value can be omitted (== nil) for no change.
setDimension()
Reset this HUD element's dimensions to their default values.Definition
Resets width, height, scale and pivot.
resetDimensions()
Set this HUD element overlay's color.Definition
Children are unaffected.
setColor()
Set this HUD element overlay's color alpha value only.Definition
setAlpha()
Set this HUD element overlay's image file.Definition
setImage()
Set this HUD element overlay's UV coordinates.Definition
setUVs()
Update this HUD element's state.Definition
update()
Draw this HUD element and all of its children in order of addition.Definition
draw()
Convert a vector from pixel values into scaled screen space values.Definition
scalePixelToScreenVector(table vector2D)Arguments
table | vector2D | Array of two pixel values |
Convert a vertical pixel value into scaled screen space value.Definition
scalePixelToScreenHeight(float height)Arguments
float | height | Vertical pixel value |
Convert a horizontal pixel value into scaled screen space value.Definition
scalePixelToScreenWidth(float width)Arguments
float | width | Horizontal pixel value |
Convert a texture space pivot to an element-local pivot.Definition
normalizeUVPivot(table uvPivot, table uvs)Arguments
table | uvPivot | Array of two pixel pivot coordinates in texture space |
table | uvs | Array of UV coordinates as {x, y, width, height} |
HUD background frame element.
-- Displays a transparent frame with a thick bottom bar for use as a background in HUD elements.
--@category GUI
Create a new instance of FrameElement.Definition
new(string hudAtlasPath, float posX, float posY, float width, float height, table parent)Arguments
string | hudAtlasPath | Path to the HUD atlas texture |
float | posX | Initial X position in screen space |
float | posY | Initial Y position in screen space |
float | width | Frame width in screen space |
float | height | Frame height in screen space |
table | parent | [optional] Parent HUDElement which will receive this frame as its child element |
Create display components.Definition
createComponents()
Set frame element dimensions.Definition
Override from HUDElement to preserve border positioning and sizes.
setDimension()
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
Create a new instance of HUDPopupMessage.Definition
new(string hudAtlasPath, l10n I18N, inputManager InputBinding, InputDisplayManager InputDisplayManager, IngameMap IngameMap)Arguments
string | hudAtlasPath | Path to the HUD texture atlas |
l10n | I18N | reference for text localization |
inputManager | InputBinding | reference for custom input context handling |
InputDisplayManager | InputDisplayManager | for input glyph display |
IngameMap | IngameMap | reference used to notify the map when a message is shown |
table | HUDPopupMessage | instance |
Show a new message.Definition
showMessage(string title, string message, int duration, table controls, function callback, table target)Arguments
string | title | Title text |
string | message | Main message text |
int | duration | Message 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. |
table | controls | [optional] Array of InputHelpElement instance for input hint row display |
function | callback | [optional] Function to be called when the message is acknowledged or expires |
table | target | [optional] Callback target which is passed as the first argument to the given callback function |
Set the game's paused state on this element.Definition
If the game is paused, the message timer is stopped and no new messages are displayed.
setPaused()
Get this HUD element's visibility.Definition
getVisible()
Get the screen space translation for hiding.Definition
Override in sub-classes if a different translation is required.
DisplayElement:getHidingTranslation()Return Values
float | Screen | space X translation |
float | Screen | space Y translation |
Handle menu visibility changes.Definition
onMenuVisibilityChange()
Assign a new current message and adjust display state accordingly.Definition
This also resizes the message box according to the required space.
assignCurrentMessage()
Get the display height of the current message's title.Definition
getTitleHeight()
Get the display height of the current message's text.Definition
getTextHeight()
Get the display height of the current message's input rows.Definition
getInputRowsHeight()
Animate this element on showing.Definition
animateHide()
Start displaying a message dequeued from the currently pending messages.Definition
Sets all required display and input state.
startMessage()
Finish displaying a message after it has either elapsed or been acknowledged by the player.Definition
Resets display and input state and triggers any provided message callback.
finishMessage()
Update this element's state.Definition
update()
Update the current message.Definition
Disables this popup when time runs out and dequeues a pending messages for displaying.
updateCurrentMessage()
Update button glyphs when the player input mode has changed.Definition
updateButtonGlyphs()
Enable / disable input events for message confirmation / skipping.Definition
setInputActive()
Event function for either InputAction.SKIP_MESSAGE_BOX or InputAction.MENU_ACCEPT.Definition
onConfirmMessage()
Draw the message.Definition
draw()
Get this element's base background position.Definition
getBackgroundPosition(float uiScale)Arguments
float | uiScale | Current UI scale factor |
Set uniform UI scale.Definition
setScale()
Set this HUD element's width and height.Definition
setDimension()
Store scaled positioning, size and offset values.Definition
storeScaledValues()
Create the background overlay.Definition
createBackground()
Create required display components.Definition
createComponents()
Create components for an input button row.Definition
createInputRow()
HUD text display.
-- Displays a formatted single-line text with optional animations.
--@category GUI
Create a new HUDTextDisplay.Definition
new(float posX, float posY, float textSize, int textAlignment, table textColor, bool textBool)Arguments
float | posX | Screen space X position of the text display |
float | posY | Screen space Y position of the text display |
float | textSize | Text size in reference resolution pixels |
int | textAlignment | Text alignment as one of RenderText.[ALIGN_LEFT | ALIGN_CENTER | ALIGN_RIGHT] |
table | textColor | Text display color as an array {r, g, b, a} |
bool | textBool | If true, will render the text in bold |
table | HUDTextDisplay | instance |
Set the text to display.Definition
setText(string text, float textSize, int textAlignment, table textColor, bool textBool)Arguments
string | text | Display text |
float | textSize | Text size in reference resolution pixels |
int | textAlignment | Text alignment as one of RenderText.[ALIGN_LEFT | ALIGN_CENTER | ALIGN_RIGHT] |
table | textColor | Text display color as an array {r, g, b, a} |
bool | textBool | If true, will render the text in bold |
Set the text display UI scale.Definition
setScale()
Set this element's visibility.Definition
setVisible(bool isVisible, bool animate)Arguments
bool | isVisible | Visibility state |
bool | animate | If true, will play the currently set animation on becoming visible or and reset it when necessary. |
Set the global alpha value for this text display.Definition
The alpha value will be multiplied with any text color alpha channel value.
setAlpha()
Set the text color by channels.Definition
Use for dynamic changes and animation.
setTextColorChannels()
Set the text shadow state.Definition
setTextShadow(bool isShadowEnabled, table shadowColor)Arguments
bool | isShadowEnabled | If true, will cause a shadow to be rendered under the text |
table | shadowColor | Shadow text color as an array {r, g, b, a} |
Set an animation tween (sequence) for this text display.Definition
The animation can be played when calling HUDTextDisplay:setVisible() with the "animate" paramter set to true.
setAnimation()
Update this element's state.Definition
update()
Draw the text.Definition
draw()
Creating manager
Deletes instanceDefinition
delete()Code
29 | function HusbandryModuleFoodSpillage:delete() |
30 | end |
Initialize data structuresDefinition
initDataStructures()Code
34 | function 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 |
43 | end |
Loads data from xmlDefinition
load(table xmlFile, string xmlKey, table rootNode)Arguments
table | xmlFile | handle |
string | xmlKey | from which to read the configuration |
table | rootNode | of the husbandry |
boolean | true | if loading was successful else false |
51 | function 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 |
87 | end |
Reads network streamDefinition
readStream(integer streamId, table connection)Arguments
integer | streamId | network stream identification |
table | connection | connection information |
94 | function 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 |
100 | end |
Writes network streamDefinition
writeStream(integer streamId, table connection)Arguments
integer | streamId | network stream identification |
table | connection | connection information |
106 | function 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 |
113 | end |
Read updates from network streamDefinition
readUpdateStream(integer streamId, integer timestamp, table connection)Arguments
integer | streamId | network stream identification |
integer | timestamp | |
table | connection | connection information |
120 | function 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 |
126 | end |
Write updates from network streamDefinition
writeUpdateStream(integer streamId, table connection, integer dirtyMask)Arguments
integer | streamId | network stream identification |
table | connection | connection information |
integer | dirtyMask | is used to check if we need to update |
133 | function 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 |
140 | end |
Update water usageDefinition
onIntervalUpdate(float dayToInterval)Arguments
float | dayToInterval |
145 | function HusbandryModuleFoodSpillage:onIntervalUpdate(dayToInterval) |
146 | HusbandryModuleFoodSpillage:superClass().onIntervalUpdate(self, dayToInterval) |
147 | self:updateCleanlinessFactor(dayToInterval) |
148 | end |
Loads information from attributes and node. Retrives from xml file information.Definition
loadFromXMLFile(table xmlFile, string key)Arguments
table | xmlFile | XML file handler |
string | key | XML base key |
183 | function 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 |
190 | end |
Update spillage mechanics.Definition
updateFoodSpillage(float spillageDelta)Arguments
float | spillageDelta | amount of food to increase |
float | food | dropped |
205 | function 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 |
230 | end |
Get spillage levelDefinition
getFoodSpillageLevel()Return Values
float | spillage | total |
235 | function 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 |
245 | end |
getSpillageFactor()Code
249 | function HusbandryModuleFoodSpillage:getSpillageFactor() |
250 | if self.hasCleanliness then |
251 | return self.cleanlinessFactor |
252 | end |
253 | |
254 | return nil |
255 | end |
Sets the world direction for a given object
Checks if given index is validDefinition
checkChildIndex(integer node, string index)Arguments
integer | node | id of an object |
string | index | index |
boolean | isActivateable | is activateable |
boolean | isValid | true if index is valid else false |
Returns index of objectDefinition
indexToObject(table components, string index, table mappings)Arguments
table | components | components (also (integer) id of root node possible) |
string | index | index |
table | mappings | id to index mapping table |
table | instance | instance of object |
integer | id | id of object |
integer | id | id of used root node |
Sets the number shader attributesDefinition
setNumberShaderByValue(integer numbers, float value, integer precision, boolean showZero)Arguments
integer | numbers | id of the node containing the number shapes |
float | value | value |
integer | precision | precision |
boolean | showZero | true if zero should be shown |
table | self | returns the instance |
Wake up a collision objectDefinition
wakeUpObject(integer node)Arguments
integer | node | id of a collision object |
bool | return | true if successful |
limitedAxis 3: 0 degree = x axis, 90 degree = y axisDefinition
setWorldDirection(integer node, float dirX, float dirY, float dirZ, float upX, float upY, float upZ, integer limitedAxis, float minRot, float maxRot)Arguments
integer | node | id of object |
float | dirX | dirX |
float | dirY | dirY |
float | dirZ | dirZ |
float | upX | upX |
float | upY | upY |
float | upZ | upZ |
integer | limitedAxis | index of limited axis |
float | minRot | minRot |
float | maxRot | maxRot |
float | returns | the change delta |
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
integer | node | id of object |
float | dirX | dirX |
float | dirY | dirY |
float | dirZ | dirZ |
float | upX | upX |
float | upY | upY |
float | upZ | upZ |
table | self | returns the instance |
Sets a shader parameter recursivlyDefinition
setShaderParameterRec(integer node, string shaderParam, float x, float y, float z, float w)Arguments
integer | node | id of the top node |
string | shaderParam | the name of the shader param |
float | x | x |
float | y | y |
float | z | z |
float | w | w |
bool | return | true if successful |
Gets a list of nodes with shaderParam assigned to itDefinition
getNodesByShaderParam(integer node, string shaderParam, table nodes)Arguments
integer | node | id of the top node |
string | shaderParam | the name of the shader param |
table | nodes | a list of nodes |
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
See GuiMixin:addTo().Definition
addTo()
Add an index change observer with a callback.Definition
addIndexChangeObserver(GuiElement Decorated, observer Observer, indexChangeCallback Function(observer,)Arguments
GuiElement | Decorated | GuiElement instance which has received this method |
observer | Observer | object instance |
indexChangeCallback | Function(observer, | index, count), where index is the new index and count the current number of indexable items |
Notify observers of an index change.Definition
notifyIndexChange(GuiElement Decorated, index New, count Indexable)Arguments
GuiElement | Decorated | GuiElement instance which has received this method |
index | New | index |
count | Indexable | item count |
Clone this mixin's state from a source to a destination GuiElement instance.Definition
clone()
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).
Find and store the state element template which is configured in #stateElementTemplateId.Definition
The function searches from this elements parent downwards, so any descendant of this element or its siblings may
contain the state element template.
locateStateElementTemplate()
Find and store the indexable element which is configured in #indexableElementId.Definition
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.
locateIndexableElement()
Event handler for index changes.Definition
onIndexChange(index New, count (New))Arguments
index | New | index |
count | (New) | item count |
Set the page count.Definition
Clears current page elements and rebuilds as many as needed from the configured template.
setPageCount(count Number, initialIndex [optional])Arguments
count | Number | of page indicators to display |
initialIndex | [optional] | Page index to set after rebuilding |
Set the current page index and update display states.Definition
setPageIndex(index New)Arguments
index | New | page index |
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
Create a new instance of IngameMap.Definition
new(string hudAtlasPath, table inputDisplayManager)Arguments
string | hudAtlasPath | Path to the HUD atlas texture |
table | inputDisplayManager | InputDisplayManager reference |
Delete this element and all of its components.Definition
delete()
Set full-screen mode (for map overview) without affecting the mini-map state.Definition
setFullscreen()
Get the index of a hotspot in the hotspots list.Definition
getHotspotIndex()
Get the next or previous visible hotspot in order from a current hotspot.Definition
cycleVisibleHotspot(table currentHotspot, table categoriesHash, int direction)Arguments
table | currentHotspot | Currently selected hotspot |
table | categoriesHash | Table of valid hotspot categories to cycle, keys are categories |
int | direction | 1 for next, -1 for previous |
Override from HUDElement.Definition
Return zero height when turned off, because the map is only invisible.
getHeight()
Get required display height on screen including all auxiliary elements and texts.Definition
getRequiredHeight()
Set the map size.Definition
setSize(float width, float height)Arguments
float | width | Width of the map in screen space |
float | height | Height of the map in screen space |
Set the map's position.Definition
This sets the actual map display's position to the given values. This elements background is offset accordingly.
setPosition(float posX, float posY)Arguments
float | posX | New map X position in screen space |
float | posY | New map Y position in screen space |
Set the map's visibility (= active state).Definition
setIsVisible()
Called when the input for map size toggle is pressed and then released.Definition
onToggleMapSize()
Register map size toggle input event.Definition
registerInput()
Update the map's state.Definition
update()
Update the data about the player's current position.Definition
updatePlayerPosition()
Update the arrow indicating the player's current position.Definition
updatePlayerArrow()
Update map zoom and visibility state.Definition
updateMapHeightZoomFactor()Return Values
bool | True | if the left border of the map has been reached |
bool | True | if the right border of the map has been reached |
bool | True | if the top border of the map has been reached |
bool | True | if the bottom border of the map has been reached |
Update input display glyphs with the current input context.Definition
updateInputGlyphs()
Update map overlay UVs based on the currently focused position, e.g. a player or hotspot.Definition
updateMapUVs()Return Values
boolean | true | if loading was successful else false |
bool | True | if the left border of the map has been reached |
bool | True | if the right border of the map has been reached |
bool | True | if the top border of the map has been reached |
bool | True | if the bottom border of the map has been reached |
Draw the map as hud elementDefinition
draw()Return Values
boolean | true | if loading was successful else false |
Draw the current player's arrow.Definition
drawPlayerArrow()Return Values
table | achievement | achievement object |
Draw the map label on top of the map display.Definition
drawMapLabel()Return Values
table | instance | instance of object |
Draw the map.Definition
drawMap(float alpha, bool isStandalone)Arguments
float | alpha | [optional] Map opacity value |
bool | isStandalone | [optional] If true, will draw the map border and other elements. |
boolean | true | if loading was successful else false |
Draw map hotspot and arrow elements.Definition
drawPointsOfInterest()Return Values
boolean | true | if loading was successful else false |
Draw arrows for other players' positions.Definition
drawOtherPlayerArrows()Return Values
boolean | true | if added successful else false |
Draw arrows for enterable vehicles controlled by players.Definition
drawEnterableArrows()Return Values
table | helper | a random helper object |
Draw all known hotspots on the map.Definition
renderHotspots()Return Values
integer | helperIndex | a random helper index |
Draw a single hotspot on the map.Definition
drawHotspot()Return Values
table | helper | the helper object |
Draw the player's current coordinates as text.Definition
drawPlayersCoordinates()Return Values
table | helper | the helper object |
Draw current latency to server as text.Definition
drawLatencyToServer()Return Values
boolean | success | true if helper is marked else false |
Set this element's scale.Definition
setScale(float uiScale)Arguments
float | uiScale | Current UI scale applied to both width and height of elements |
integer | numOfHelpers | total number of helpers |
Store scaled positioning, size and offset values.Definition
storeScaledValues()Return Values
table | instance | instance of object |
Get the base position of the entire element.Definition
getBackgroundPosition()Return Values
boolean | true | if loading was successful else false |
Create the empty background overlay.Definition
createBackground()Return Values
boolean | true | if loading was successful else false |
Create required display components.Definition
createComponents(string hudAtlasPath)Arguments
string | hudAtlasPath | Path to the HUD texture atlas |
boolean | true | if loading was successful else false |
Create the map frame.Definition
createFrame()Return Values
boolean | true | if added successful else false |
Create the input glyph for map size toggling.Definition
createToggleMapSizeGlyph()Return Values
table | npc | a random npc object |
Create the map arrow for the player's position.Definition
createPlayerMapArrow()Return Values
integer | npcIndex | a random npc index |
Create an arrow overlay used for other player's and their vehicles in multiplayer.Definition
createOtherMapArrowOverlay()Return Values
table | npc | the npc object |
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.
Add a dead zone wherein the map will not react to cursor inputs.Definition
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.
addCursorDeadzone()
Clear cursor dead zones.Definition
clearCursorDeadzones()
Check if a cursor position is within one of the stored deadzones.Definition
isCursorInDeadzones()
Custom mouse event handling for the in-game map.Definition
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.
mouseEvent()
Update base map element values for displaying as an embedded UI element.Definition
updateBaseMapValues()
Set the IngameMap reference to use for display.Definition
setIngameMap()
Set the current map's terrain size for map display.Definition
setTerrainSize()
Register non-GUI input action events.Definition
registerActionEvents()
Remove non-GUI input action events.Definition
removeActionEvents()
Event function for horizontal cursor input bound to InputAction.AXIS_LOOK_LEFTRIGHT_VEHICLE.Definition
onHorizontalCursorInput()
Event function for vertical cursor input bound to InputAction.AXIS_LOOK_UPDOWN_VEHICLE.Definition
onVerticalCursorInput()
Event function for gamepad cursor accept input bound to InputAction.INGAMEMAP_ACCEPT.Definition
onAccept()
Event function for map zoom input bound to InputAction.AXIS_ACCELERATE_VEHICLE and InputAction.AXIS_BRAKE_VEHICLE.Definition
onZoomInput(inputValue Zoom, direction Zoom)Arguments
inputValue | Zoom | input value |
direction | Zoom | input sign value, 1 for zoom in, -1 for zoom out |
Check if mouse input was active before a bound input was triggered and queue a reset of the mouse state for the nextDefinition
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.
checkAndResetMouse()
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
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
table | target | Callback target |
table | custom_mt | Sub-class meta table |
table | messageCenter | MessageCenter reference |
table | l10n | I18N reference for text localization |
table | savegameController | SavegameController reference for savegame persistence |
table | inputManager | InputBinding reference |
table | fruitTypeManager | FruitTypeManager reference for fruit type information access |
table | fillTypeManager | FillTypeManager reference for fill type information access |
table | storeManager | StoreManager reference |
table | shopController | ShopController reference |
table | shopConfigScreen | ShopConfigScreen reference |
table | placementScreen | PlacementScreen reference |
bool | isConsoleVersion | If true, the game is running on a console |
table | instance | instance of object |
Set the menu mode.Definition
Switches the menu between pause menu mode or shop mode.
setMode(int menuMode)Arguments
int | menuMode | One of [InGameMenu.MODE_MENU | InGameMenu.MODE_SHOP] |
table | instance | instance of object |
Set the in-game map component to use by pages.Definition
setInGameMap()Return Values
table | brandColor | brandColor object |
Set the current terrain size to use by pages.Definition
setTerrainSize()Return Values
table | farmhouse | or nil |
Set the known fruit types when loaded for the mission.Definition
setMissionFruitTypes()Return Values
integer | spawnpoint | node or the career spawnpoint node. |
Set the current list of selling stations for displaying.Definition
setSellingStations()Return Values
integer | Camera | or 0 if no farmhouse. |
Set the current list of accessible vehicles for displaying.Definition
setAccessibleVehicles()Return Values
bool | True | if the user is a manager of this farm, false otherwise |
Set the reference to the ban storage.Definition
setBanStorage()Return Values
table | Permission | hash table {permission=<hasPermission>} |
Set the current list of connected users for displaying.Definition
setConnectedUsers()Return Values
float | Account | balance |
Set the network client reference.Definition
setClient()Return Values
float |
Set the network server reference.Definition
setServer()Return Values
table | instance | instance of object |
Update master rights status.Definition
updateHasMasterRights()Return Values
boolean | true | if loading was successful else false |
Update garage items display data.Definition
updateGarageItems()Return Values
boolean | true | if loading was successful else false |
Called when the mission is fully loaded.Definition
Used for late initialization of UI components which rely on mission information.
onLoadMapFinished()Return Values
table | data | Data for the menu |
Initialize pages for the pause mode.Definition
initializePausePages()Return Values
table | instance | Instance of object |
Initialize pages for the shop mode.Definition
initializeShopPages()Return Values
boolean | true | if loading was successful else false |
Set up displayed menu pages and their tabs.Definition
setupMenuPages()Return Values
table | instance | instance of object |
Define default properties and retrieval collections for menu buttons.Definition
setupMenuButtonInfo()Return Values
boolean | true | if loading was successful else false |
Add a page tab in the menu header.Definition
Call this synchronously with InGameMenu:registerPage() to ensure a correct order of pages and tabs.
addPageTab()Return Values
fruit | type | index to be planted |
Set enabled state of a page tab in the header.Definition
setPageTabEnabled()Return Values
float | sprayFactor | the spray factor of the given field |
Rebuild page tab list in order.Definition
rebuildTabList()Return Values
float | plowFactor | the plow factor of the given field |
Set environment reference on loading.Definition
setEnvironment()Return Values
float | plowFactor | the lime factor of the given field |
Set mission info data on loading.Definition
setMissionInfo()Return Values
float | plowFactor | the weed factor of the given field |
Set the player's current farm reference.Definition
setPlayerFarm()Return Values
float | area | area found |
float | totalArea | total area checked |
Set the reference to the current player.Definition
setPlayer()
Set the current user ID.Definition
setCurrentUserId()Return Values
table | instance | instance of object |
Set manure triggers of the current map/mission.Definition
setManureTriggers()Return Values
boolean | true | if loading was successful else false |
Set the reference to the current husbandries collection.Definition
setHusbandries()Return Values
boolean | true | if loading was successful else false |
Reset menu state and go back to the main menu.Definition
leaveCurrentGame()Return Values
List | of | vehicles. Each element is a table with filanema and configuration properties. |
Reward | ||
Exit the menu if allowed.Definition
exitMenu()
Exit the menu from the shop configuration screen.Definition
exitMenuFromConfig()
Reset menu state (and all pages).Definition
reset()Return Values
float | multiplier | harvest multiplier |
Handle in-game menu opening event.Definition
onOpen()Return Values
table | instance | of the doghouse |
Handle in-game menu closing event.Definition
onClose()Return Values
string | Vehicle | display name |
Button function for saving the game.Definition
onButtonSaveGame()Return Values
mixed | value | Value of the setting. The type depends on the setting |
Button function for backing out of the menu.Definition
onButtonBack()Return Values
boolean | successful | Returns true, if the setting was changed |
Button function for quitting the game to the main menu.Definition
onButtonQuit()Return Values
table | instance | instance of object |
Button function for switching to the garage view.Definition
onButtonGarage()Return Values
table | self | instance |
Button function for switching to the shop view from the garage.Definition
onButtonShop()Return Values
True | if | the element and all of its children could be set up with the given values, false otherwise. |
Button function for repairing an owned vehicle in the garage.Definition
onButtonRepair()Return Values
True | if | the input event has been consumed, false otherwise |
Handle confirmation of vehicle repairing.Definition
onYesNoRepairDialog()Return Values
Closest | point | x, y |
Handle a local vehicle repaired event.Definition
Updates the garage view buttons if currently viewing the repaired vehicle.
onVehicleRepairEvent()Return Values
Next | GUI | element in given direction which can be linked, actual scanning direction used (may change in wrap around scenarios) |
Button function for explicit clicking of item details action buttons.Definition
onButtonAcceptItem()Return Values
Focus |
Button function for switching owned / leased items in the garage.Definition
onButtonSwitchOwnedLeased()Return Values
True | if | focus has changed, false otherwise |
Enter placement mode.Definition
startPlacementMode()Return Values
True | if | navigation in given direction is locked |
Enter saving mode.Definition
startSavingGameDisplay()Return Values
Root | GuiElement | instance of loaded view or nil if the definition XML file could not be loaded. |
Update page enabled states.Definition
updatePages()Return Values
Cloned | FrameElement | instance or frameRefElement if resolution failed. |
Update page tabs display after any page changes.Definition
updatePageTabDisplay()Return Values
Root | GuiElement | of screen or nil if the name did not match any known screen. |
Clear menu button actions, events and callbacks.Definition
clearMenuButtonActions()Return Values
Root | GuiElement | of dialog or nil if the name did not match any known dialog. |
Assign menu button information to the in-game menu buttons.Definition
assignMenuButtonInfo()Return Values
True | if | any control has consumed the action event |
Get page titles from currently visible pages and apply to the selector element.Definition
setPageSelectorTitles()Return Values
table | ScreenElement | descendant instance of the given class or nil if no such instance was registered |
Switch to or from shop detail mode.Definition
This can switch to a category's item list, the owned object or leased object overview by passing in the corresponding
detail page.
setShopDetailMode()Return Values
table | Root | GuiElement instance of target screen |
Update the menu state each frame.Definition
This uses a state machine approach for the game saving process.
update()Return Values
table | The | GuiElement instance given in the guiElement parameter |
Directly switch to the finances screen.Definition
openFinancesScreen()Return Values
New |
Directly switch to the farms screen.Definition
openFarmsScreen()Return Values
table | with added image data |
Notify the menu that the master server could not be connected to.Definition
setMasterServerConnectionFailed()Return Values
Color | as | {red, green, blue, alpha} with all values in the range of [0, 1] |
Set the menu state to master user.Definition
Called by the mission if the current player is a master user.
setMasterUserLocal()Return Values
UV | coordinates | as {u1, v1, u2, v2, u3, v3, u4x, v4} with all values in the range of [0, 1] |
Show the vehicle configuration screen for a given store item.Definition
showConfigurationScreen()Return Values
New | GuiProfile | instance |
Custom input handling to check shop toggle button when in shop mode.Definition
inputEvent()Return Values
True | if | profile values could be loaded, false otherwise. |
Handle a menu action click by calling one of the menu button callbacks.Definition
onMenuActionClick()Return Values
int | Camera | node ID (view point, child of camera base node) |
int | Camera | base node ID (view target, parent of camera node) |
bool | True | if no callback was present and no action was taken, false otherwise |
Handle menu confirmation input event.Definition
onClickOk()
Handle menu back input event.Definition
onClickBack()Return Values
Camera | X | world space position |
Camera | Z | world space position |
Camera | Y | rotation in radians |
Handle menu cancel input event.Definition
Bound to quite the game to the main menu.
onClickCancel()
Handle menu active input event.Definition
Bound to save the game.
onClickActivate()
Handle a balance change in game.Definition
onMoneyChanged()
Handle a change of the current slot usage.Definition
onSlotUsageChanged()Return Values
x | direction | movement [-1, 1] |
Z | direction | movement [-1, 1] |
Handle selection of a detail item element when in buy mode.Definition
onSelectItemBuyDetail()
Handle selection of a detail item element in the garage.Definition
onSelectItemSellDetail()Return Values
array | of | normalized values |
Handle tutorial restart confirmation dialog response.Definition
onYesNoRestartTutorial()Return Values
array | of | the 2 converted values as numbers: {value1, value2} |
Server end game confirmation dialog response callback.Definition
onYesNoEnd()Return Values
array | of | the 4 converted values as numbers: {value1, value2, value3, value4} |
Handle activation of page selection.Definition
onClickPageSelection()Return Values
array | of | the 4 converted values as numbers: {red, green, blue, alpha} |
Handle previous page event.Definition
onPagePrevious()Return Values
array | of | the UV coordinates as {u1, v1, u2, v2, u3, v3, u4, v4} |
Handle next page event.Definition
onPageNext()Return Values
bool | True | if overlay generation has started, false if generation is already in progress or an invalid overlay type has been provided |
Handle changing to another menu page.Definition
onPageChange()Return Values
bool | True | if overlay generation has started, false if generation is already in progress or an invalid overlay type has been provided |
Update the buttons panel when a given page is visible.Definition
updateButtonsPanel()Return Values
bool | True | if overlay generation has started, false if generation is already in progress or an invalid overlay type has been provided |
Get button actions and display information for a given menu page.Definition
getPageButtonInfo()Return Values
bool | True | if overlay generation has started, false if generation is already in progress or an invalid overlay type has been provided |
Handle a page being disabled.Definition
onPageUpdate()Return Values
array | of | display 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}} |
Handle saving game confirmation when losing master server connection.Definition
onConnectionFailedDialogClick()Return Values
array | of | display information, {i={colors={true={i={r,g,b,a}}, false={i={r,g,b,a}}}, description=text}} |
Called from the mission controller when vehicles are modified.Definition
onVehiclesChanged()Return Values
array | of | display information, {i={colors={true={i={r,g,b,a}}, false={i={r,g,b,a}}}, description=text}} |
Handle clicking on a brand in shop mode.Definition
onClickBrand()Return Values
float | X | position in screen space |
float | Y | position in screen space |
Handle clicking on an item category in shop mode.Definition
onClickItemCategory()
Notify the player when validating the savegame list.Definition
Will prompt to select a storage device or inform that the chosen device has no more space available.
notifyValidateSavegameList()Return Values
float | Width | scale factor |
float | Height | scale factor |
Notify the player that the game is saving, block input via dialog until the operation finishes.Definition
notifyStartSaving()
Notify the menu when a save completes successfully so we can set the saving state flag.Definition
notifySaveComplete()Return Values
table | SettingsModel | instance |
Notify the player that the savegame could not be saved.Definition
notifySavegameNotSaved()Return Values
table | Currently | active (changed) settings value |
Prompt the player to confirm overwriting an existing savegame.Definition
notifyOverwriteSavegame()Return Values
bool | True | if any setting has been changed, false otherwise |
Notify the player that saving failed because the current device has no more space, ask to select another device.Definition
notifySaveFailedNoSpace()Return Values
bool | True | if any setting has been changed, false otherwise |
Register a page frame element in the menu.Definition
This does not add the page to the paging component of the menu.
registerPage(table pageFrameElement, int position, function enablingPredicateFunction)Arguments
table | pageFrameElement | Page FrameElement instance |
int | position | [optional] Page position index in menu |
function | enablingPredicateFunction | [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. |
bool | True | if no callback was present and no action was taken, false otherwise |
Unregister a page frame element identified by class from the menu.Definition
This does not remove the page from the paging component of the menu or the corresponding page tab from the header.
unregisterPage(table pageFrameClass)Arguments
table | pageFrameClass | FrameElement descendant class of a page which was previously registered |
bool | True | if there was a page of the given class and it was unregistered |
table | Unregistered | page controller instance or nil |
table | Unregistered | page root GuiElement instance or nil |
table | Unregistered | page tab ListElement instance of nil |
bool | True | if there was a page of the given class and it was unregistered |
table | Unregistered | page controller instance or nil |
table | Unregistered | page root GuiElement instance or nil |
table | Unregistered | page tab ListElement instance of nil |
Add a page frame to be displayed in the menu at runtime.Definition
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.
addPage(int position, string tabIconFilename, table tabIconUVs, function enablingPredicateFunction)Arguments
int | position | Position index of added page, starting from left at 1 going to right. |
string | tabIconFilename | Path to the texture file which contains the icon for the page tab in the header |
table | tabIconUVs | UV array for the tab icon. Format: {x, y, width, height} in pixels on the texture. |
function | enablingPredicateFunction | [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. |
Remove a page from the menu at runtime by its class type.Definition
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
removePage()
Set the enabled state of a page identified by its controller class type.Definition
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.
setPageEnabled(table pageFrameClass, bool isEnabled)Arguments
table | pageFrameClass | Class table of a FrameElement sub-class |
bool | isEnabled | True for enabled, false for disabled |
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]} |
Make a callback which encloses the self reference and handles arbitrary arguments afterwards.Definition
makeSelfCallback()Return Values
List | of | DisplayActionBinding instances |
In-game menu animals statistics frame.
-- Displays information for all owned animal pens and horses.
--@category GUI
Create a new InGameMenuAnimalsFrame instance.Definition
new(table subclass_mt, table messageCenter, table l10n, table animalManager, table animalFoodManager, table fillTypeManager)Arguments
table | subclass_mt | [optional] Meta table of subclass |
table | messageCenter | MessageCenter reference for local message subscriptions |
table | l10n | I18N reference for localization |
table | animalManager | AnimalManager reference for animal type and information resolution |
table | animalFoodManager | AnimalFoodManager reference for food mixture information |
table | fillTypeManager | FillTypeManager reference for fill type resolution |
Display | ||
table | InGameMenuAnimalsFrame | instance |
Late initialization.Definition
initialize()Return Values
True | if | the controller starts listening for input, false otherwise (also if it is already listening!) |
Set the reference to the husbandries collection.Definition
The husbandries are defined as {<husbandry ID> = AnimalHusbandry}
setHusbandries()Return Values
bool | True | if an actual binding was deleted, false otherwise |
Build a livestock list item for a husbandry.Definition
buildLivestockListItem()Return Values
True | if | a binding change was made, false otherwise |
Build animal list items for all horses in a horse husbandry.Definition
buildHorseListItems()Return Values
True | if | a binding change was made, false otherwise |
Rebuild the animal list from husbandry data.Definition
rebuildAnimalList()Return Values
True | if | a binding change was made, false otherwise |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
True | if | binding has been assigned; reference to first colliding binding or nil |
Get the frame's main content element's screen position.Definition
getMainElementPosition()Return Values
table | DirectSellDialog | instance |
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
table | statusBarElement | BitmapElement instance which receives a new size and profile depending on the value |
float | value | Fractional value in the range of [0, 1] |
float | startOffset | Start offset value in the range of [0, 1], value will be displayed from there on until 1. |
table | profiles | Large or small status bar profile table, either InGameMenuAnimalsFrame.PROFILE.STATUS_BAR_LARGE or InGameMenuAnimalsFrame.PROFILE.STATUS_BAR_SMALL |
float | overrideStatusValue | [optional] If provided, tests this value against the color thresholds instead of the given status bar value |
Flows | and | cells as nested tables: [flowIndex][cell index] = cell data {element, flowSize, lateralSize} |
Display a husbandry requirements row with the given data.Definition
If no label text is specified, the row will be hidden.
displayRequirement()Return Values
List | of | lateral flow sizes, total lateral sizes (sum of lateral flow sizes), maximum flow size in direction of flow |
Display a husbandry conditions row with the given data.Definition
If no label text is specified, the row will be hidden.
displayCondition()Return Values
Layout | X | starting offset, layout Y starting offset, Layout X direction {-1|1}, Layout Y direction {-1|1} |
Sum up the values of an array of animal husbandry fill level info tables.Definition
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.
sumFillLevelInfos()Return Values
element | X | offset, element Y offset |
Update production display for a livestock husbandry.Definition
WIP, no assets ready for testing!
updateLivestockHusbandryProductionDisplay()Return Values
which | should receive focus instead |
Update base conditions (dirt, water, straw) display for a husbandry.Definition
updateHusbandryConditionsDisplay()Return Values
float | Modified | X offset |
float | Modified | Y offset |
Update food levels and capacities display for a husbandry.Definition
updateHusbandryFoodDisplay()
Display data of a single horse in the detail view.Definition
displayHorse()Return Values
True | if | the input event has been handled, false otherwise. |
Display data of a livestock husbandry (pigs, cows, etc.) in the detail view.Definition
displayLivestock()Return Values
True | if | the keyboard input has been processed by this element. |
Update contextual menu buttons.Definition
updateMenuButtons()Return Values
Actual | element to focus. |
Rename the currently selected horse if the new name has been confirmed.Definition
renameCurrentHorse()Return Values
List | of | this element's descendants in depth-first order with contiguous numeric indices. |
Get a formatted food description text for an animal type.Definition
getFoodDescription()Return Values
First | matching | descendant element in depth-first order or nil, if no element matched the predicate function |
Handle "rename" button activation when a horse is selected.Definition
onButtonRename()Return Values
element | or | nil |
Handle animal list selection changes.Definition
onListSelectionChanged()Return Values
element | or | nil |
Exposed controls usable as fields in this frame, identified in configuration.
Create a new InGameMenuContractsFrame instance.Definition
new(table subclass_mt)Arguments
table | subclass_mt | [optional] Meta table of subclass |
parent | element | or full screen borders in an array: {minX, minY, maxX, maxY} |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
element | borders | in an array: {minX, minY, maxX, maxY} |
Get the frame's main content element's screen position.Definition
getMainElementPosition()Return Values
float | X | aspect scale factor |
float | Y | aspect scale factor |
Update the state of the frame buttons.Definition
setButtonsForState()
Request a mission list update, but remember the position of the selectionDefinition
If the mission is still in the list, the selection stays
updateList()Return Values
index | or | nil, field name |
Update the contents of the contract detail screen (context sensitive)Definition
updateDetailContents()Return Values
Actual | element to focus. |
Update the content of the box with farmer information, using the field.Definition
updateFarmersBox()Return Values
bool | True | if the page changed |
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
Create a new InGameMenuFinancesFrame instance.Definition
new(table subclass_mt)Arguments
table | subclass_mt | [optional] Meta table of subclass |
Page |
Initialize the finances frame after component creation.Definition
initialize()Return Values
Page | container | GuiElement instance |
Set networking client reference.Definition
setClient()Return Values
int | Page | index |
Set the mission environment reference.Definition
setEnvironment()Return Values
int | Page | mapping index |
Set the player's current farm reference.Definition
setPlayerFarm()Return Values
bool | True | if the event was not used, false if it was used. |
Set the player's master rights status.Definition
setHasMasterRights()Return Values
bool | True | if the event was not used, false if it was used. |
Get the array of days before today counting back to the number of displayed past days.Definition
The method resolves days to display labels which can be used directly.
getPastDays()Return Values
bool | True | if the event was not used, false if it was used. |
Late setup of finances table called on initialization.Definition
setupFinancesTable()Return Values
bool | True | if the event was not used, false if it was used. |
Update the current balance display text.Definition
updateBalance()Return Values
bool | True | if the event was not used, false if it was used. |
Update the loan display text.Definition
updateLoan()Return Values
bool | True | if the event was not used, false if it was used. |
Update the expenses/incomes total for all displayed days.Definition
updateDayTotals()Return Values
number | of | list items in data source |
Update statically positioned totals display.Definition
updateFinancesFooter()Return Values
table | Array | of button info as {i={inputAction=<action name>, text=<optional display text>, callback=<optional callback>}} |
Update table display data.Definition
updateFinancesTable()Return Values
DataCell | or | nil if not found. |
Update finances display.Definition
updateFinances()Return Values
DataCell | or | nil if not found. |
Update loan button active states.Definition
updateFinancesLoanButtons()Return Values
List | of | SortCell for the requested column name |
Update the current money unit.Definition
Also applies the unit change to the borrow/repay button labels.
updateMoneyUnit()Return Values
index | of | selected row |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
Get the frame's main content element's screen position.Definition
getMainElementPosition()Return Values
dataRow | instance | or nil, selected data index or 0 |
Build a table data row for a given financial statistic.Definition
buildDataRow()Return Values
dataRow | instance | or nil (element not part of table row) |
Handle borrow money action.Definition
onButtonBorrow()Return Values
number | of | data view rows |
Handle repay money action.Definition
onButtonRepay()Return Values
Actual | element to focus. |
Base class for frame elements for the in-game menu.
--@category GUI
Create a new InGameMenuFrameElement instance.Definition
new()
Late initialization of a menu frame.Definition
Override in sub-classes.
initialize()
Check if this menu frame requires menu button customization.Definition
getHasCustomMenuButtons()
Get custom menu button information.Definition
getMenuButtonInfo()Return Values
table | Array | of button info as {i={inputAction=<action name>, text=<optional display text>, callback=<optional callback>}} |
Set custom menu button information.Definition
setMenuButtonInfo(table menuButtonInfo)Arguments
table | menuButtonInfo | Array of button info as {i={inputAction=<action name>, text=<optional display text>, callback=<optional callback>}} or nil to reset. |
Set the menu button info dirty flag which causes the menu to update the buttons from this element's information.Definition
setMenuButtonInfoDirty()
Get the menu button info dirty state (has changed).Definition
isMenuButtonInfoDirty()
Clear menu button dirty flag.Definition
clearMenuButtonInfoDirty()
Get the frame's main content element's screen size.Definition
getMainElementSize()
Get the frame's main content element's screen position.Definition
getMainElementPosition()
Request to close the frame.Definition
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.
requestClose()
Called when this frame is opened by its container.Definition
onFrameOpen()
Called when this frame is closed by its container.Definition
onFrameClose()
Current savegame settings page for the in-game menu.
--@category GUI
Create a new InGameMenuGameSettingsFrame instance.Definition
new(table subclass_mt)Arguments
table | subclass_mt | [optional] Meta table of subclass |
The | new | sorting order |
Initialize the game settings frame with concrete page references.Definition
This must be called after loading, since page frames are cloned and references cannot be injected in the constructor.
initialize()Return Values
table | AchievementMessage | instance |
Set the current mission's info.Definition
Required to get current settings and to modify game name.
setMissionInfo()Return Values
float | X | position in screen space |
float | Y | position in screen space |
Set the currently known manure triggers in the game for helper manure refill settings.Definition
setManureTriggers()
Set master rights status of the current game instance / player.Definition
setHasMasterRights()Return Values
table | ChatWindow | instance |
Update settings display with values from the current mission info / savegame.Definition
updateGameSettings()Return Values
float | X | position in screen space |
float | Y | position in screen space |
Update the pause buttons visuals for pausing/unpausing based on the game state.Definition
updatePauseButtonState()
Assign static option settings texts.Definition
assignStaticTexts()Return Values
int | Display | row index of the newly added custom text or 0 if it could not be added |
Assign time scale setting texts.Definition
assignTimeScaleTexts()Return Values
float | X | position in screen space |
float | Y | position in screen space |
Assign dirt setting texts.Definition
assignDirtTexts()
Assign plant growth texts.Definition
assignPlantGrowthTexts()Return Values
float | Game | info display width of visible elements in screen space |
Assign auto save texts.Definition
assignAutoSaveTexts()Return Values
table | Weather | icon HUDElement instance |
Assign game state dependent setting texts.Definition
assignDynamicTexts()Return Values
table | Temperature | icon HUDElement instance |
Update visibility of tool tip box, only show when there is text to display.Definition
updateToolTipBoxVisibility()Return Values
table | Clock | hand HUDElement instance |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
table | Time | scale arrow icon HUDElement instance |
Get the frame's main content element's screen position.Definition
getMainElementPosition()Return Values
table | GamePausedDisplay | instance |
Handle accepting savegame name input.Definition
onEnterPressedSavegameName()Return Values
bool | If | true, the HUD is currently visible. |
Handle changing of the tool tip text.Definition
onToolTipBoxTextChanged()Return Values
table | HUDDisplayElement | instance |
General game settings page for the in-game menu.
--@category GUI
Create a new InGameMenuGeneralSettingsFrame instance.Definition
new(table subclass_mt, table settingsModel)Arguments
table | subclass_mt | [optional] Meta table of subclass |
table | settingsModel | SettingsModel reference which handles settings display state across the UI |
float | Screen | space X translation |
float | Screen | space Y translation |
Update display values from settings.Definition
updateGeneralSettings()
Update visibility of tool tip box, only show when there is text to display.Definition
updateToolTipBoxVisibility()Return Values
table | HUDElement | instance |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
float | Pivot | x position offset from element position in screen space |
float | Pivot | y position offset from element position in screen space |
Get the frame's main content element's screen position.Definition
getMainElementPosition()
Handle clicks on a check box.Definition
onClickCheckbox()Return Values
float | X | position in screen space |
float | Y | position in screen space |
Handle clicks on a multi option element.Definition
onClickMultiOption()
Handle a button click on the native help button which is only visible and active on XBOX.Definition
onClickNativeHelp()Return Values
width | scale | factor |
height | scale | factor |
Handle changing of the tool tip text.Definition
onToolTipBoxTextChanged()
Exposed controls usable as fields in this frame, identified in configuration.
Create a new InGameMenuHelpFrame instance.Definition
new(table subclass_mt)Arguments
table | subclass_mt | [optional] Meta table of subclass |
float | Red | value |
float | Green | value |
float | Blue | value |
float | Alpha | value |
Set the current mission's base directory to let this frame load images from that location.Definition
setMissionBaseDirectory()
Set up UI elements for a given category index.Definition
createList()
Load help category texts.Definition
loadHelpLine()
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
float | Alpha | value |
Get the frame's main content element's screen position.Definition
getMainElementPosition()Return Values
table | HUDPopupMessage | instance |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
float | Screen | space X translation |
float | Screen | space Y translation |
Get the frame's main content element's screen position.Definition
getMainElementPosition()
Handle a change of row in the current category's help list.Definition
onHelpLineListSelectionChanged()Return Values
table | HUDTextDisplay | instance |
Map overview frame of the in-game menu.
-- Displays the current map with markers for points of interest and terrain overlays.
--@category GUI
Create a new InGameMenuMapFrame instance.Definition
new(table subclass_mt)Arguments
table | subclass_mt | [optional] Meta table of subclass |
bool | True | if the left border of the map has been reached |
bool | True | if the right border of the map has been reached |
bool | True | if the top border of the map has been reached |
bool | True | if the bottom border of the map has been reached |
Create input help glyphs.Definition
createInputGlyphs()
Initialize map frame after GUI setup.Definition
initialize()
Called by InGameMenu when a map has finished loading.Definition
onLoadMapFinished()
Toggle map overview-specific input.Definition
Make sure this is called exactly once for activation and deactivation each when the map frame is opened or closed.
toggleMapInput()Return Values
bool | True | if the left border of the map has been reached |
bool | True | if the right border of the map has been reached |
bool | True | if the top border of the map has been reached |
bool | True | if the bottom border of the map has been reached |
Disable alternate bindings for menu navigation.Definition
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.
disableAlternateBindings()
Get the context box position and orientation for a given hotspot.Definition
getContextBoxPositionAndOrientation()Return Values
float | Screen | space X position |
float | Screen | space Y position |
string | Orientation | value, one of InGameMenuMapFrame.CONTEXT_BOX_ORIENTATION |
float | Rotation | angle value |
Update the position of the hotspot context box if it's active.Definition
updateContextBoxPosition()
Set the IngameMap reference in this frame's required IngameMapElement for display.Definition
setInGameMap()Return Values
float | X | position in screen space after the last glyph |
Set the terrain size for use in the ingameMapElement.Definition
setTerrainSize()Return Values
float | X | position in screen space after the last glyph |
Set the fruit types used in the current mission.Definition
setMissionFruitTypes()Return Values
float | Screen | space height used by the combo header (0 if invisible) |
Set the client connection object for event dispatching.Definition
setClient()Return Values
table | Input | help elements |
float | Screen | space height used by the returned help elements |
Set the current player's farm ID.Definition
setPlayerFarm()
Assign filter data after map loading.Definition
assignFilterData()Return Values
int | Maximum | number of entries to show |
Assign display data for the crop type filters.Definition
assignCropTypeFilterData()Return Values
boolean | isAllowed | isAllowed |
Assign display data for the ground state filters (growth and soil state).Definition
assignGroundStateFilterData()Return Values
table | Combo | InputGlyphElement instance |
Assign colors for ground state (growth or soil) elements.Definition
assignGroundStateColors()Return Values
table | Combo | header HUDElement |
Reset the UI dead zones for the map.Definition
resetUIDeadzones()Return Values
float | Display | height in screen space |
Set a static UI dead zone for the map to make it ignore cursor/mouse input within that screen region.Definition
This dead zone is always in effect, regardless of map mode.
setStaticUIDeadzone()Return Values
float | Modified | input help panel drawing vertical offset |
Called when the overview overlay is finished for display.Definition
onOverviewOverlayFinished()Return Values
table | SideNotification | instance |
Called when the farmland overlay is finished for display.Definition
onFarmlandOverlayFinished()Return Values
table | SpeakerDisplay | instance |
(Re-)Generate the map overlay for crop types, growth and soil states.Definition
generateOverviewOverlay()Return Values
table | Overlay | instance |
(Re-)Generate the map overlay for farmlands.Definition
generateFarmlandOverlay()Return Values
table | HUDElement | instance |
Set the display state of a filter icon based on the current filter settings.Definition
setFilterIconState()Return Values
table | TopNotification | instance |
Toggle hotspot filter settings for the farmlands view mode.Definition
toggleFarmlandsHotspotFilterSettings()Return Values
float | Screen | space X translation |
float | Screen | space Y translation |
Show input buttons based on the current map selection context.Definition
showContextInput()
Update the context input bar's visibility.Definition
Turns it invisible if there are no buttons visile, otherwise turns it visible.
updateContextInputBarVisibility()Return Values
bool | If | true, the HUD extension should be drawn in the current frame. |
Show marker button according to context.Definition
showContextMarker()Return Values
float | Modified | input help panel drawing vertical offset |
Show the context box for a selected hotspot.Definition
showContextBox()Return Values
table | HUD | extension instance or nil of no extension has been registered for the given specialization |
Hide the hotspot context box.Definition
hideContextBox()Return Values
table | Array | of overlay descriptions: {overlay=overlay, x=0, y=0, rotation=0, invertX=false, invisibleBorderRight=vehicle.schemaOverlay.invisibleBorderRight, invisibleBorderLeft=vehicle.schemaOverlay.invisibleBorderLeft} |
float | Screen | space height of root vehicle schema overlay |
Set the map selection to a hotspot.Definition
setMapSelectionItem()
Get display data for a selectable map hotspot.Definition
getHotspotData()Return Values
float | Minimum | X position (left) |
float | Maximum | X position (right) |
string | Description | text |
string | Display | image file path |
table | Display | image UVs |
table | Vehicle | instance if a vehicle has been selected, or nil otherwise |
Set the current color blind mode.Definition
Updates colors on buttons and overlays.
setColorBlindMode(bool isActive)Arguments
bool | isActive | If true, color blind mode is active |
Initialize filter buttons with the current filter state.Definition
initializeFilterButtonState()Return Values
table | Schema | Overlay instance |
Reset farmland selection state.Definition
resetFarmlandSelection()Return Values
table | InGameMenuAnimalsFrame | instance |
Check if there are any placeables owned by the player on a given farmland.Definition
checkPlaceablesOnFarmland()Return Values
float | Screen | space X position |
float | Screen | space Y position |
string | Orientation | value, one of InGameMenuMapFrame.CONTEXT_BOX_ORIENTATION |
float | Rotation | angle value |
Handle changes to farm balance values.Definition
onMoneyChanged(int farmId, float newBalance)Arguments
int | farmId | ID of farm whose current balance has changed |
float | newBalance | New balance value of the given farm |
Called after the in-game map has been drawn.Definition
Draws the mode-dependent state overlay on top of the map
onDrawPostIngameMap()
Handle clicking the map overview selector which switches map overlay context (crop types, growth states, soil states).Definition
onClickMapOverviewSelector()
Handle filter button focus or highlight activation.Definition
onFilterButtonSelect()Return Values
string | Description | text |
string | Display | image file path |
table | Display | image UVs |
table | Vehicle | instance if a vehicle has been selected, or nil otherwise |
Handle filter button focus or highlight deactivation.Definition
onFilterButtonUnselect()
Set the display state of a filter button.Definition
setFilterButtonDisplayEnabled()
Toggle filter state on filter button click.Definition
toggleFilter()
Handle activation of a crop type filter.Definition
onClickCropFilter(table element, int fruitTypeIndex)Arguments
table | element | Clicked button element |
int | fruitTypeIndex | Fruit type index as valid in the current mission. |
int | List | index corresponding to the farm ID or 1 if it could not be found or was the spectator farm ID |
Handle activation of a growth state filter.Definition
onClickGrowthFilter(table element, int growthStateIndex)Arguments
table | element | Clicked button element |
int | growthStateIndex | Growth state index |
dataRow | instance | with prices data for the given selling point |
Handle activation of a soil state filter.Definition
onClickSoilFilter(table element, int growthStateIndex)Arguments
table | element | Clicked button element |
int | growthStateIndex | Soil state index |
float | Sorting | value, see TableElement:setCustomSortFunction(...) |
Handle clicking / activating a map hotspot.Definition
onClickHotspot()Return Values
float | Current | fill level >= 0 or a value < 0 if no storage exists for the requested fill type index |
float | Total | capacity for the fill type >= 0 or a value < 0 if no storage exists for the requested fill type index |
Handle clicking within the map.Definition
onClickMap()
Called from FarmlandManager whenever a significant farmland change (mainly ownership) occurs.Definition
onFarmlandStateChanged()Return Values
table | TableElement.DataRow | instance |
Handle ResetVehicleEvent local event.Definition
onVehicleReset()Return Values
dataRow | instance | with vehicle data for the given vehicle |
Handle activation of map mode switch button.Definition
onClickSwitchMapMode()Return Values
float | Sorting | value, see TableElement:setCustomSortFunction(...) |
Dialog confirmation callback for resetting a vehicle.Definition
onYesNoReset()Return Values
True | if | the server matches the current filter settings, false otherwise |
Notify this frame when pausing the game.Definition
notifyPause()Return Values
dataRow | instance | with server data |
Select the first visible hotspot on the mapDefinition
selectFirstHotspot()Return Values
table | LandscapingScreen | instance |
Fit an input glyph into its corresponding placeholder GuiElement instance.Definition
updateInputGlyphTransform()Return Values
table | new | LandscapingScreenController instance |
Update input glyphs when input context changes.Definition
updateInputGlyphs()Return Values
int | Node | ID of the actual indicator shape in the loaded indicator asset |
int | Node | ID of the attached light source of the loaded indicator asset |
Handle confirmation result of farmland buying dialog.Definition
onYesNoBuyFarmland()
Handle confirmation result of farmland selling dialog.Definition
onYesNoSellFarmland()Return Values
table | categories | list of categories |
Register input actions.Definition
registerInput()Return Values
table | PlacementScreen | instance |
Menu activate event, bound to vehicle enter, place visit or buying farmlands.Definition
onMenuActivate()Return Values
True | if | the placement is valid, false otherwise |
string | Reason | of being invalid |
Menu cancel event, bound to hotspot tagging, vehicle reset or selling farmlands.Definition
onMenuCancel()
Switch vehicle action event, bound to cycle visible hotspots.Definition
onSwitchVehicle()Return Values
table | ShopConfigScreen | instance |
Exposed controls usable as fields in this frame, identified in configuration.
Create a new InGameMenuMultiplayerFarmsFrame instance.Definition
new(table subclass_mt)Arguments
table | subclass_mt | [optional] Meta table of subclass |
float | Fuel | capacity in liters |
Late initialization after frame cloning.Definition
initialize()Return Values
float | Base | price |
float | Upgrade | price |
bool | True | if there are changes |
Set the reference to the current user.Definition
setCurrentUserId()
Set the current users reference.Definition
setUsers()
Set the reference to the current player.Definition
setPlayer()Return Values
int | Number | of used config option elements |
Set the reference to the current player's farm.Definition
setPlayerFarm()Return Values
table | New | collection of filtered owned items |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
table | Array | of brands in the form of {i={id = brand.index, iconFilename = brand.image, label = brand.title}} |
Get the frame's main content element's screen position.Definition
getMainElementPosition()Return Values
table | Array | of vehicle categories in the form of {i={id = category.index, iconFilename = category.image, label = category.title}} |
Build the farm list items from the known farms.Definition
buildFarmListItems()Return Values
table | Array | of tool categories in the form of {i={id = category.index, iconFilename = category.image, label = category.title}} |
Update farm list.Definition
updateFarmList()Return Values
table | Array | of object categories in the form of {i={id = category.index, iconFilename = category.image, label = category.title}} |
Get the list index for a given farm ID.Definition
getListFarmIndex(int farmId)Arguments
int | farmId | Farm ID |
table | Array | of placeable categories in the form of {i={id = category.index, iconFilename = category.image, label = category.title}} |
int | List | index corresponding to the farm ID or 1 if it could not be found or was the spectator farm ID |
Update a farm's balance display.Definition
updateFarmBalance()Return Values
int | Next | usable attribute slot index after these fill types |
Update displayed player names on a farm.Definition
updateFarmPlayers()Return Values
int | Number | of attributes used for text data |
Update context menu buttons.Definition
updateMenuButtons()Return Values
table | instance | Instance of object |
Let the current player join a given farm.Definition
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.
joinFarm()Return Values
boolean | success | success |
Let the current player leave their farm.Definition
The player will join the spectator farm and be able to choose a new farm to join.
leaveFarm()Return Values
Delete a given farmDefinition
The current player must have admin privileges on the server and the farm must be empty.
deleteFarm()Return Values
float | ||
float | ||
float | ||
float | ||
float | ||
float |
Show a dialog to edit farm properties.Definition
The current player must have farm manager or administrator privileges on the server.
editFarm()
Show a dialog to create a new farmDefinition
The current player must have administrator privileges on the server.
createFarm()
Handle an answer to PlayerSetFarmEvent.Definition
onPlayerSetFarmAnswer(int answerState, int farmId, string password)Arguments
int | answerState | PlayerSetFarmAnswerEvent.STATE member |
int | farmId | If the state is OK, will contain the newly joined farm |
string | password | If the state is OK, will contain the newly joined farm's password |
Handle confirmation of farm password input when joining a farm.Definition
onFarmPasswordEntered()
Handle changes to user permissions.Definition
If the current user's permissions change, update the menu buttons in case they were elevated to farm manager status.
onPermissionChanged()
Handle creation of a new farm.Definition
onFarmCreated()Return Values
table | self | instance of class event |
Handle state update of any farm.Definition
onFarmsChanged()Return Values
table | instance | instance of event |
Handle a player changing their farm.Definition
onPlayerFarmChanged()Return Values
table | self | instance of class event |
Handle a balance change of a farm.Definition
onFarmMoneyChanged()Return Values
table | instance | instance of event |
Handle clicking on the left navigation button.Definition
onClickLeft()Return Values
table | self | instance of class event |
Handle clicking on the right navigation button.Definition
onClickRight()Return Values
table | instance | instance of event |
Handle a click / activation of a farm item.Definition
onClickFarm()Return Values
table | instance | Instance of object |
Handle a double click of a farm item.Definition
onDoubleClickFarm()Return Values
boolean | success | success |
Handle a farm selection change.Definition
onSelectionChanged()Return Values
float | dailyUpkeep | daily up keep |
Handle farm deletion dialog confirmation.Definition
onDeleteFarmYesNo()Return Values
float | sellPrice | sell price |
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
Create a new InGameMenuMultiplayerUsersFrame instance.Definition
new(table subclass_mt)Arguments
table | subclass_mt | [optional] Meta table of subclass |
boolean | isActiveForInput | is active for input |
Late initialization.Definition
initialize()Return Values
table | self | instance of class event |
Called when this frame is opened by its container.Definition
onFrameOpen()Return Values
table | instance | instance of event |
Called when this frame is closed by its container.Definition
onFrameClose()Return Values
table | instance | instance of object |
Set up the user list to store an instance flag when navigating users or not for menu button context.Definition
setupUserListFocusContext()Return Values
integer | id | i3d rootnode |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
boolean | isValid | true if index is valid else false |
Get the frame's main content element's screen position.Definition
getMainElementPosition()Return Values
integer | id | id of object |
integer | id | id of used root node |
Set the reference to the current player's farm.Definition
setPlayerFarm()
Set the current user ID.Definition
setCurrentUserId()Return Values
New | Binding | instance |
Set the ban storage reference.Definition
setBanStorage()Return Values
instance | initialized with values from XML and the given parameters |
Set the current users reference.Definition
setUsers()Return Values
int | Combo | bit mask |
Get a new sorted array of known users for displaying.Definition
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.
getSortedUsers()Return Values
True | if | there is a collision. |
Build a display name for a given user and their special privilege flags.Definition
buildUserDisplayInfo()Return Values
Cloned | Binding | instance |
Update connected player information.Definition
rebuildUserList(table missionUsers)Arguments
table | missionUsers | Array of users managed by the current mission instance. |
Update menu buttons based on the current user's admin status.Definition
updateMenuButtons()Return Values
instance | initialized with values from XML |
Update the current balance display.Definition
updateBalance()Return Values
Cloned | InputAction | instance |
Set the current money balance display.Definition
setCurrentBalance(float balance, string balanceString)Arguments
float | balance | Current balance of the current player |
string | balanceString | Properly formatted money string |
table | InputBinding | instance |
Update all display states and text.Definition
updateDisplay()Return Values
table | Set | of required device categories, {<category> = true} |
Handle a ban button activation.Definition
onButtonBan()Return Values
bool | True | if there are any configured bindings for the given device, false otherwise |
Handle ban confirmation dialog result.Definition
onYesNoBan()Return Values
GS_INPUT_HELP_MODE_KEYBOARD | or | GS_INPUT_HELP_MODE_GAMEPAD |
Handle a kick button activation.Definition
onButtonKick()Return Values
GS_INPUT_HELP_MODE_KEYBOARD | or | GS_INPUT_HELP_MODE_GAMEPAD |
Handle kick confirmation dialog result.Definition
onYesNoKick()Return Values
True | if | the parameters are valid, false otherwise. |
Handle an unban button activationDefinition
onButtonUnBan()Return Values
bool | True | if the event could be registered, false otherwise |
string | event | ID if successful, empty string otherwise |
table | Action | reference of a colliding action if there would be a collision, nil otherwise |
Handle a show user profile button activation.Definition
onButtonShowProfile()
Handle an invite friends button activationDefinition
onButtonInviteFriends()
Handle an admin login button activation.Definition
onButtonAdminLogin()Return Values
bool | True | if there would be a collision, false otherwise |
table | Colliding | action if there would be a collision, nil otherwise |
Handle selection changes in the user list.Definition
onUserSelected()
Handle clicking a permission check box.Definition
onClickPermission(table checkboxElement, bool isActive)Arguments
table | checkboxElement | ToggleButtonElement which received the click |
bool | isActive | New checked state |
array | of | tuples: {i={action=InputAction, event=InputEvent}} |
Handle clicking the transfer buttonDefinition
onClickTransferButton()Return Values
Gamepad | combo | mask, Mouse combo mask |
Transfer money from the current player's farm to the selected farm.Definition
transferMoney()Return Values
instance | or nil if ID is invalid |
Handle clicking the remove player from farm button.Definition
onClickRemoveFromFarm()Return Values
instance | or nil if ID is invalid |
Handle remove player from farm confirmation dialog result.Definition
onYesNoRemoveFromFarm()Return Values
instance | or nil if ID is invalid |
Handle clicking the promote player to farm manager button.Definition
onClickPromote()Return Values
float | Mouse | cursor X position in screen space |
float | Mouse | cursor Y position in screen space |
Handle promote user confirmation dialog result.Definition
onYesNoPromoteToFarmManager()
Handle clicking the contractor toggle button.Definition
onClickContractor()Return Values
previousDevices | Table | of internal ID -> InputDevice before the current initialization |
Handle contractor state toggle confirmation dialog result.Definition
onYesNoToggleContractorState()Return Values
List | of | device information tables, format: {deviceId=[device ID], name=[device name]} |
Handle a local money change event for any farm.Definition
onFarmMoneyChanged()Return Values
Modifier | bit | mask |
Handle state update of any farm.Definition
onFarmsChanged()Return Values
True | if | the binding's device ID could be resolved, false otherwise |
Handle a player changing their farm.Definition
onPlayerFarmChanged()Return Values
function | results | table {checkFunctionRef=[functionResult]} |
Handle a local player permission change event.Definition
onPermissionChanged()Return Values
Handle a local contracting state change event.Definition
onContractingStateChanged()Return Values
bool | True | if the new binding could be added |
table | Reference | to an Action containing a binding which collided with the added binding or nil |
Handle admin login password dialog response.Definition
onAdminPassword()
Handle successfully logging in as an admin.Definition
onAdminLoginSuccess()Return Values
True | if | a binding could be found and updated, false if there was a collision |
and | Action reference of a collision as {collisionBinding=Binding, collisionAction=Action} or nil |
Prices overview frame of the in-game menu.
-- Displays current prices of sellable goods and produce.
--@category GUI
Create a new InGameMenuPricesFrame instance.Definition
new(table subclass_mt, table l10n, table fillTypeManager)Arguments
table | subclass_mt | [optional] Meta table of subclass |
table | l10n | I18N reference |
table | fillTypeManager | FillTypeManager reference |
Create a focus override function for the prices table which scrolls horizontally if possible instead of exiting theDefinition
table.
makeTableFocusOverrideFunction()Return Values
True | if | all given axes are currently active, input value of the non-modified axis (last in list) |
Get the display name of a selling station.Definition
getStationName()Return Values
True | if | all axes are active (digital interpretation), input value of the non-modified axis (last in list) |
Set the current list of selling stations for displaying.Definition
setSellingStations()Return Values
Input | value | of the axis in the range [-1, 1] for full axes or [0, 1] for half axes. |
Update item counts and handle size of the vertical slider.Definition
updateVerticalSlider()Return Values
Initial setup of the prices table and required data.Definition
setupPriceTable()Return Values
Ordered | action | bindings in the form of {i={action=InputAction, bindings={Binding}}} |
Update prices table display data.Definition
updatePriceTable()Return Values
Update table headers with fill type icons according to current horizontal slider position.Definition
updateHeaderIcons()Return Values
table | Array | of events |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
table | First | active event or InputEvent.NO_EVENT |
Get the frame's main content element's screen position.Definition
getMainElementPosition()Return Values
x | motion | scale, Y motion scale |
Handle horizontal slider changes.Definition
onChangedPriceSlider()Return Values
True | if | the user settings have passed the integrity check, false otherwise. |
Handle price table header clicks.Definition
Causes the table to be sorted by the clicked header column's numeric price values.
onClickPriceHeader()Return Values
True | if | the axis name represents a physical full axis, false otherwise |
Handle selling point table header clicks.Definition
Causes the table to be sorted by selling point names.
onClickSellingPointHeader()Return Values
True | if | the input name represents an analog input |
Handle table row clicks.Definition
onClickPrices()Return Values
True | if | the axis is at zero position, false otherwise |
Handle table row double-clicks.Definition
Sets a map marker on the selected selling point or clears it again.
onDoubleClickPrices()Return Values
New | InputDevice | instance |
Bind an element to the selling point data.Definition
onDataBindSellingPoint()Return Values
Device | ID | or empty string |
Bind an element to the indexed price data.Definition
onDataBindPrice()Return Values
Device | name | or empty string |
Bind an element to the silo capacity label data.Definition
onDataBindSiloCapacityLabel()Return Values
Prefix | number, | or -1 if none exists; raw engine-issued device ID |
Binding an element to the indexed silo capacity value data.Definition
onDataBindSiloCapacityValue()Return Values
instance | containing the symbol overlays in its "buttons" field |
Set data for a selling point table cell.Definition
setSellingPointData(table dataCell, table sellingStation)Arguments
table | dataCell | TableElement.DataCell instance for a selling point cell |
table | sellingStation | SellingStation instance of the current data row |
array | of | help elements (see InputDisplayManager:makeHelpElement() for structure) |
Set data for a price table cell.Definition
setPriceData(table dataCell, int priceIndex, table sellingStation)Arguments
table | dataCell | TableElement.DataCell instance for a price cell |
int | priceIndex | Price column index |
table | sellingStation | SellingStation instance of the current data row |
Hash | table | of currently active combo button action names, {action name=true} |
Build a DataRow from selling point properties to add to the prices tableDefinition
buildDataRow(table sellingStation)Arguments
table | sellingStation | SellingStation reference |
Axis | name | or nil if not found, internal ID of binding device |
dataRow | instance | with prices data for the given selling point |
Table sorting function for prices.Definition
sortPrices(table sortCell1, table sortCell1)Arguments
table | sortCell1 | TableElement.SortCell instance representing the first cell to compare |
table | sortCell1 | TableElement.SortCell instance representing the second cell to compare |
instance | or nil if no overlay is available for the action's bindings | |
float | Sorting | value, see TableElement:setCustomSortFunction(...) |
Get the storage fill level for a given fill type index.Definition
getStorageFillLevel(int index, bool farmSilo)Arguments
int | index | Fill type index of the requested storage fill level |
bool | farmSilo | If true, only counts storage of owned farm silos |
key | text | (e.g. "F" for "KEY_f") for the keyboard action binding or nil if no resolution is possible |
float | Current | fill level >= 0 or a value < 0 if no storage exists for the requested fill type index |
float | Total | capacity for the fill type >= 0 or a value < 0 if no storage exists for the requested fill type index |
Game statistics display frame for the in-game menu.
--@category GUI
Create a new InGameMenuStatisticsFrame instance.Definition
new(table subclass_mt)Arguments
table | subclass_mt | [optional] Meta table of subclass |
controller | symbols | configuration key name |
Update statistics data in tables.Definition
updateStatistics()Return Values
controller | symbols | configuration key name |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
New | InputEvent | instance |
Get the frame's main content element's screen position.Definition
getMainElementPosition()Return Values
table | instance | instance of object |
Build a table data row for a given statistics attribute.Definition
buildDataRow(table statAttribute)Arguments
table | statAttribute | Statistics attribute as defined in FarmStats |
boolean | true | if loading was successful else false |
table | TableElement.DataRow | instance |
Exposed controls usable as fields in this frame, identified in configuration.
Create a new InGameMenuFinancesFrame instance.Definition
new(table subclass_mt)Arguments
table | subclass_mt | [optional] Meta table of subclass |
string | cutterEffectType | the real cutterEffect name, nil if not defined |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
table | cutterEffects | cutter effects |
Get the frame's main content element's screen position.Definition
getMainElementPosition()Return Values
table | instance | instance of object |
Exposed controls usable as fields in this frame, identified in configuration.
Create a new InGameMenuVehiclesFrame instance.Definition
new(table subclass_mt, table messageCenter, table l10n, table storeManager, table brandManager)Arguments
table | subclass_mt | Sub-class meta table |
table | messageCenter | MessageCenter reference for notifications |
table | l10n | I180N reference for display text resolution |
table | storeManager | StoreManager reference for vehicle store data look-ups |
table | brandManager | BrandManager reference for vehicle brand data look-ups |
boolean | true | if loading was successful else false |
Late initialization.Definition
initialize()Return Values
string | materialType | the real material name, nil if not defined |
Update the garage view.Definition
updateGarage()Return Values
integer | materialId | id of material |
Update item counts and handle size of the vertical slider.Definition
updateVerticalSlider()Return Values
table | instance | instance of object |
Set a list of vehicles currently accessible by the player.Definition
setAccessibleVehicles()Return Values
boolean | true | if loading was successful else false |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
string | particleType | the real particle name, nil if not defined |
Get the frame's main content element's screen position.Definition
getMainElementPosition()Return Values
table | particleSystem | particleSystem |
Create a focus override function for a table header which modifies the scroll bar instead of navigation whenDefinition
vertical navigation input is received.
makeTableHeaderFocusOverrideFunction()Return Values
table | instance | instance of object |
Set data for a vehicle name table cell.Definition
setNameData()Return Values
boolean | true | if loading was successful else false |
Set data for a vehicle age table cell.Definition
setAgeData()Return Values
boolean | true | if loading was successful else false |
Set data for a vehicle operating hours table cell.Definition
setOperatingHoursData()Return Values
table | instance | instance of object |
Set data for a vehicle damage table cell.Definition
setDamageData()Return Values
table | instance | instance of object |
Set data for a vehicle leasing costs table cell.Definition
setLeasingData()Return Values
table | instance | instance of object |
Set data for a vehicle selling value table cell.Definition
setValueData()Return Values
boolean | true | if loading was successful else false |
Build a DataRow from vehicle properties to add to the table.Definition
buildDataRow(table vehicle)Arguments
table | vehicle | Vehicle reference |
table | baleType | baleType object |
dataRow | instance | with vehicle data for the given vehicle |
Table sorting function for numeric values.Definition
sortAttributes(table sortCell1, table sortCell1)Arguments
table | sortCell1 | TableElement.SortCell instance representing the first cell to compare |
table | sortCell1 | TableElement.SortCell instance representing the second cell to compare |
table | baleType | baleType object |
float | Sorting | value, see TableElement:setCustomSortFunction(...) |
Handle clicks on the vehicle name header.Definition
Switches table to default string sorting.
onClickVehicleHeader()Return Values
table | bale | bale |
Handle clicks on an attribute header.Definition
Switches table to numerical sorting.
onClickAttributeHeader()Return Values
string | baleKey | bale key |
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.
Create a new InputAction instanceDefinition
new(name Action, axisType Type, isLocked If, ignoreComboMask If, displayNamePositive [optional], displayNameNegative [optional])Arguments
name | Action | name, unique |
axisType | Type | of action axis (HALF or FULL) |
isLocked | If | true, bindings for this action cannot be changed in the game |
ignoreComboMask | If | true, 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. |
InputAction |
Create a new InputAction instance from an XML element.Definition
createFromXML(xmlFile XML, elementTag Tag)Arguments
xmlFile | XML | file handle |
elementTag | Tag | of the element to parse as an InputAction |
integer | numPixels | number of pixels |
InputAction | instance | initialized with values from XML |
Add a Binding to this action.Definition
addBinding()Return Values
integer | changedArea | changed area pixels |
integer | totalArea | total area pixels |
Remove a binding from this action.Definition
removeBinding()
Get the bindings for this action.Definition
getBindings()Return Values
integer | changedArea | changed area pixels |
integer | totalArea | total area pixels |
Clear this action's bindings.Definition
clearBindings()
Let this action know which binding is its primary keyboard binding.Definition
Stores the input axes as a concatenated string for comparisons.
setPrimaryKeyboardBinding(Binding Binding)Arguments
Binding | Binding | instance which is the primary keyboard binding for this action |
integer | numChangedPixels | number of changed pixels |
Determine if this action represents a logical full axis.Definition
isFullAxis()Return Values
table | color | tire track color |
Determine if bindings of this action should trigger any associated events if the bindings are not combos but a comboDefinition
button is currently pressed.
getIgnoreComboMask()Return Values
string | encodedString | the encoded string |
Create a new InputAction instance with the same state as this instance.Definition
clone()Return Values
string | decodedString | the decoded string |
Cloned | InputAction | instance |
Get a string representation for this InputAction.Definition
toString()Return Values
table | copy | the copied table |
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
Create the InputBinding instance.Definition
new(table logManager, table modManager, table messageCenter, bool isConsoleVersion)Arguments
table | logManager | LogManager reference |
table | modManager | ModManager reference |
table | messageCenter | MessageCenter reference |
bool | isConsoleVersion | If true, the game is running on console |
table | copy | the copied table |
table | InputBinding | instance |
Load the input binding configuration.Definition
load(bool isInitializing, bool forceDefaultBindings)Arguments
bool | isInitializing | [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. |
bool | forceDefaultBindings | [optional, default=false] If true, will forcibly load default bindings and override any user input settings. |
boolean | isElementOfList | true if element is part of the list, else false |
Load default input bindings.Definition
Will apply defaults for newly connected devices or override all bindings with template defaults if requested.
loadDefaultBindings(bool forceReplace)Arguments
bool | forceReplace | [optional, default=false] If true, will overwrite all user bindings with the default templates. |
integer | index | index of first occurrence |
Load actions defined by mods.Definition
loadModActions()Return Values
boolean | areEqual | true if lists are equal, else false |
Load default mod input binding data.Definition
loadModBindingDefaults()Return Values
any | value | value of the random element |
Assign bindings configuration file paths depending on platform and devices.Definition
assignPlatformBindingPaths()Return Values
table | set | the converted set |
Overwrites user input settings with the default template.Definition
overwriteSettingsWithDefault(forceOverwrite If)Arguments
forceOverwrite | If | true, will overwrite an existing settings file. If false, will only perform the operation if no user settings are present. |
table | list | the converted list |
Restore input contexts after reloading the input settings, e.g. when devices change.Definition
restoreInputContexts()Return Values
table | hash | the converted hash |
Set the visibility state of the mouse cursor.Definition
setShowMouseCursor(bool doShow, bool saveCursorPosition)Arguments
bool | doShow | If true, the cursor will be shown. Otherwise, it will be hidden. |
bool | saveCursorPosition | [optional] If true, saves the current cursor position to restore when showing it again |
boolean | areEqual | true if sets are equal, else false |
Determine if the mouse cursor is currently being shown.Definition
getShowMouseCursor()Return Values
boolean | isSubset | true if set1 is a subset of set2 |
Get the current input help mode for the input hint display.Definition
If the input help mode has been set to automatic, the last button or key input will determine which device scheme
is used.
getInputHelpMode()Return Values
boolean | isSubset | true if set1 is a real subset of set2 |
GS_INPUT_HELP_MODE_KEYBOARD | or | GS_INPUT_HELP_MODE_GAMEPAD |
Get the current input mode, independent of input help mode settings.Definition
getLastInputMode()Return Values
boolean | hasIntersection | true if set1 and set2 have an intersection |
GS_INPUT_HELP_MODE_KEYBOARD | or | GS_INPUT_HELP_MODE_GAMEPAD |
Validate parameters for registerActionEvent().Definition
Prints warnings if there are problems and returns the validation status.
validateActionEventParameters()Return Values
table | intersection | the intersection of both sets |
True | if | the parameters are valid, false otherwise. |
Register an event callback for an input action.Definition
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
registerActionEvent(table targetObject, function eventCallback, bool triggerUp, bool triggerDown, bool triggerAlways, bool startActive, table callbackState)Arguments
table | targetObject | Event target, first argument to event callback |
function | eventCallback | Event callback, called when the action has input. Signature: callback(targetObject, actionName, inputValue, callbackState) |
bool | triggerUp | If true, the event fires once when an input signal of the given action goes to "up" state, e.g. a released key. |
bool | triggerDown | If true, the event fires once when an input signal of the given action goes to "down" state, e.g. a pressed key. |
bool | triggerAlways | If 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. |
bool | startActive | [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. |
table | 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 additional class fields. |
table | substraction | the substraction of both set |
bool | True | if the event could be registered, false otherwise |
string | event | ID if successful, empty string otherwise |
table | Action | reference of a colliding action if there would be a collision, nil otherwise |
Check if adding an event for a given action name would cause colliding input bindings to be active.Definition
checkEventCollision(string actionName)Arguments
string | actionName | Name of an InputAction |
table | union | the union of both sets |
bool | True | if there would be a collision, false otherwise |
table | Colliding | action if there would be a collision, nil otherwise |
Start registering action events in a given context.Definition
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.
beginActionEventsModification(string inContext, bool createNew)Arguments
string | inContext | Name of the input context which receives any registered events until endActionEventsModification is called. |
bool | createNew | [optional, default=false] If true, will create a new context of the given name, potentially overwriting any existing one. |
table | filtered | list (non-deep copy) |
End registering action events in a context.Definition
Resets the registration context set in InputBinding:beginActionEventsModification() for any later registrations.
endActionEventsModification()Return Values
table | filtered | list (non-deep copy) |
Refresh derived event collections for retrieval purposes.Definition
refreshEventCollections()Return Values
integer | sign | the sign of the value |
Store an array of action-event tuples for all action events which need an input hint display.Definition
storeDisplayActionEvents()Return Values
boolean | true | if value is nan else false |
Store all bindings associated with registered and active events in collections for iteration.Definition
storeEventBindings()Return Values
number | rounted | value |
Iterates the action event collection, calling a given function on each event.Definition
If the processing function returns a "truthy" value, the iteration is stopped.
iterateEvents(processingFunction function(event,)Arguments
processingFunction | function(event, | actionName, actionEventList, actionEventListIndex) |
float | value | radian angle |
Internal function for event removal.Definition
removeEventInternal()Return Values
float | value | interpolated value |
Remove a previously registered action event by ID.Definition
removeActionEvent(eventId Event)Arguments
eventId | Event | ID as returned by registerActionEvent(). |
float | value | interpolated value |
Remove all previously registered action events which are triggered by an action identified by name.Definition
removeActionEventsByActionName(actionName If)Arguments
actionName | If | an event is triggered by the action of that name, it is removed. |
float | alpha | alpha |
Remove all previously registered action events which have a given target.Definition
removeActionEventsByTarget(targetObject If)Arguments
targetObject | If | an event has this object as a target, it is removed. |
float | value | value |
Get action-event tuples for registered events which require an input hint.Definition
Note that the data is live and should be treated as read-only.
getDisplayActionEvents()Return Values
float | isOutOfBounds | is out of bounds |
array | of | tuples: {i={action=InputAction, event=InputEvent}} |
Set a specific action text to display as an input hint for a given event.Definition
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.
setActionEventText(eventId ID, actionText Localized)Arguments
eventId | ID | of a registered event |
actionText | Localized | display text for the event's action |
float | value | the floored percent value |
Set the name of an icon to display as an input hint instead of text for a given event.Definition
If an icon has been specified for an event with this function, any text setting will have no effect.
setActionEventIcon(eventId ID, iconName Input)Arguments
eventId | ID | of a registered event |
iconName | Input | hint icon name as defined in axisIcons.xml or InputHelpElement.AXIS_ICON |
float | value | the floored clamped value |
Set the visibility of an action event input hint display.Definition
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.
setActionEventTextVisibility(eventId ID, isVisible If)Arguments
eventId | ID | of a registered event |
isVisible | If | false, hides the input hint for this event. Default is visible. |
float | angle | the resized angle in the range -pi to pi |
Set the priority of an action event input hint display.Definition
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.
setActionEventTextPriority(eventId ID, priority Priority)Arguments
eventId | ID | of a registered event |
priority | Priority | number value, lower is more important. Use GS_PRIO_[...] constants. |
float | angle | the radian difference in range -pi to pi |
Set the active state of an action event.Definition
Only active events can be triggered by input and be displayed as input hints.
setActionEventActive(eventId ID, isActive New)Arguments
eventId | ID | of a registered event |
isActive | New | active state |
float | length | length |
Set the active state of all action events targeting a given object.Definition
Only active events can be triggered by input and be displayed as input hints.
setActionEventsActiveByTarget(targetObject Action, isActive New)Arguments
targetObject | Action | event target object |
isActive | New | active state |
float | length | square length |
Get the combo input masks for any currently active gamepad and mouse combo inputs.Definition
The returned masks are bit-wise combined masks made from the InputBinding.COMBO_MASK_[...] constants.
getComboCommandPressedMask()Return Values
float | x | normalized x |
float | y | normalized y |
Gamepad | combo | mask, Mouse combo mask |
Get the combo action name for a given set of modifier axes.Definition
getComboActionNameForAxisSet()
Resolve a device ID sting to the engine-internal integer ID.Definition
getInternalIdByDeviceId()Return Values
float | length | length |
Retrieve an InputDevice by its internal device ID.Definition
getDeviceByInternalId(internalDeviceId Internally)Arguments
internalDeviceId | Internally | assigned device ID (= device index assigned by engine, zero based) |
float | length | square length |
InputDevice | instance | or nil if ID is invalid |
Assign an input help mode as the last used mode.Definition
This triggers a message center notification to all subscribed components if the input help mode has changed.
assignLastInputHelpMode()Return Values
float | x | normalized x |
float | y | normalized y |
float | z | normalized z |
Prepare for incoming binding changes.Definition
Must be called before InputBinding:startInputCapture() to guarantee a valid state.
startBindingChanges()
Commit all binding changes since the last call to InputBinding:startBindingChanges().Definition
Accepts the current, modified binding state and notifies any change listeners.
commitBindingChanges()
Rolls back all binding changes since the last calls to InputBinding:startBindingChanges().Definition
rollbackBindingChanges()Return Values
float | x | scaled x |
float | y | scaled y |
float | z | scaled z |
Capture all input and run a callback if input has been received on a device.Definition
Overrides the global input event functions.
startInputCapture(isKeyboard True, isMouse True, callbackTarget If, callbackState Free, inputCallback Called, abortCallback Called, deleteCallback Called)Arguments
isKeyboard | True | if target device is keyboard input |
isMouse | True | if target device is mouse input |
callbackTarget | If | specified, will be supplied as the first argument to the callback function (usually caller self) |
callbackState | Free | parameter which is returned with callbacks to the callback target |
inputCallback | Called | when the target device receives input. function(deviceId, inputAxisName, isModifier, inputValue, callbackState) |
abortCallback | Called | when an abort input is received on any device. function() |
deleteCallback | Called | when a delete input is received on any device. function(callbackState) |
Capture keyboard input.Definition
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.
captureKeyboardInput(abortCallback function(), deleteCallback function(), inputCallback function(deviceId,)Arguments
abortCallback | function() | to be called when the abort key is pressed |
deleteCallback | function() | to be called when the delete key is pressed |
inputCallback | function(deviceId, | axisName, isModifier, inputValue), see startInputCapture() |
Capture mouse input.Definition
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.
captureMouseInput(callback function(deviceId,)Arguments
callback | function(deviceId, | axisName, isModifier, inputValue), see startInputCapture() |
float | x | clamped x |
float | y | clamped y |
float | z | clamped z |
Capture gamepad / controller input.Definition
Continously fires callbacks for all known gamepad buttons and axes for each frame.
captureGamepadInput(callback function(deviceId,)Arguments
callback | function(deviceId, | axisName, isModifier, inputValue), see startInputCapture() |
Stop the current input gathering run.Definition
Restores global input event functions.
stopInputGathering()
Restore default bindingsDefinition
restoreDefaultBindings()Return Values
float | x | interpolated x |
float | y | interpolated y |
float | z | interpolated z |
Clear relevant state for loading and resetting.Definition
clearState()
Load input actions which are later bound to input axes.Definition
loadActions(xmlFile Action, modName [optional])Arguments
xmlFile | Action | definition XML file handle |
modName | [optional] | Name of the mod which defines actions. If not set, actions are assumed to be default game actions. |
Reset stored device information.Definition
Clears all device information and returns the previous device list for comparisons. Call this for
initialization and before enumerating system devices.
resetDeviceInformation()Return Values
float | x | interpolated x |
float | y | interpolated y |
float | z | interpolated z |
previousDevices | Table | of internal ID -> InputDevice before the current initialization |
(Re-)Creates the internal keyboard and mouse virtual device.Definition
createDefaultDevices()
Find gamepad devices in the system and store their information.Definition
enumerateGamepadDevices(previousDevices Table)Arguments
previousDevices | Table | of internal ID -> InputDevice before the current initialization |
Get a list of recognized gamepad (and other controller) input devices.Definition
getGamepadDevices()Return Values
float | x | transformed x |
float | y | transformed y |
float | z | transformed z |
List | of | device information tables, format: {deviceId=[device ID], name=[device name]} |
Load device input settings (other than bindings) from an input binding XML file.Definition
loadDeviceSettingsFromXML(xmlFile XML)Arguments
xmlFile | XML | file handle |
Apply deadzone settings to all gamepad device axes.Definition
If no deadzone value had been configured for a valid axis, the global default deadzone value is applied.
applyGamepadDeadzones()
Initialize gamepad settings from XML.Definition
initializeGamepadMapping()Return Values
dot | the | dot product |
Check if combo action bindings are valid and restore proper bindings if necessary.Definition
validateAndRepairComboActionBindings()Return Values
float | x | x |
float | y | y |
float | z | z |
Load bindings of actions to input axes from a configuration XML file.Definition
loadActionBindingsFromXML(xmlFile Configuration, silentIgnoreDuplicates [optional], modName [optional], doNotReplace [optional])Arguments
xmlFile | Configuration | XML 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 |
Load all bindings within an XML actionBindings definition element.Definition
loadBindingsFromXML()
Store input axis names of combo command actions for combo mask checking.Definition
storeComboInputMappings()Return Values
float | y | rotation |
Get a combo modifier mask for a binding.Definition
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.
getBindingComboMask(Binding Binding)Arguments
Binding | Binding | instance |
float | x | x direction |
float | z | z direction |
Modifier | bit | mask |
Assign combination input bitmasks on actions based on their bindings.Definition
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.
assignComboMasks()
Store binding links based on connections set in InputAction.LINKED_ACTIONS.Definition
storeLinkedBindings()Return Values
float | x | limited x direction |
float | z | limited z direction |
Assign primary keyboard bindings to actions if applicable.Definition
assignActionPrimaryBindings()
Adjust a binding's slot index.Definition
adjustBindingSlotIndex(Binding Binding, usedSlots Set)Arguments
Binding | Binding | to adjust |
usedSlots | Set | of used slot indices for the binding's context (action, device, axis) |
float | x | x position |
float | x | z position |
Resolve a binding's device ID to an engine-issued internal device ID.Definition
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.
resolveBindingDevice(Binding Binding)Arguments
Binding | Binding | whose device ID is checked and replaced, if necessary |
True | if | the binding's device ID could be resolved, false otherwise |
Resolve and assign the first device of a given category to a binding.Definition
resolveFirstDeviceOfCategoryToBinding()Return Values
float | dot | product |
Resolve and assign the last device with a given base ID (without prefix) to a binding.Definition
resolveSameIdDeviceWithPrefixToBinding()Return Values
float | x | x part of quaternion |
float | y | y part of quaternion |
float | z | z part of quaternion |
float | w | w part of quaternion |
Resolve and assign the last device with a given name to a binding.Definition
resolveMissingDeviceByNameToBinding()
Resolve and assign the first known device to a binding.Definition
resolveDefaultDeviceToBinding()
Run a a list of functions on all known bindings in the context of a given action if provided.Definition
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.
checkBindings(action Action, checkFunctions List)Arguments
action | Action | reference for the current context, e.g. check bindings for an action |
checkFunctions | List | of functions with the signature function(Binding), return [bool hasResult], result |
function | results | table {checkFunctionRef=[functionResult]} |
Validate a new binding before it's added to the system.Definition
Returns boolean flags for constraints and a colliding binding if there was one.
validateBinding(Binding New)Arguments
Binding | New | binding instance |
float | x | x part of quaternion |
float | y | y part of quaternion |
float | z | z part of quaternion |
float | w | w part of quaternion |
Add a new input binding.Definition
Checks for duplicates and collisions and stores the binding only if everything's okay.
addBinding(table binding, bool silentIgnoreDuplicates, bool doNotReplace)Arguments
table | binding | New binding |
bool | silentIgnoreDuplicates | If true, will not print warnings on duplicate bindings |
bool | doNotReplace | If true, will not replace existing bindings |
bool | True | if the new binding could be added |
table | Reference | to an Action containing a binding which collided with the added binding or nil |
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
findDeviceId | Binding | device ID |
findActionName | Name | of binding action |
findBindingIndex | Binding | index, 1 primary, 2 secondary, etc. |
findAxisComponent | Logical | binding axis direction component to assign, always positive for buttons/keys/half-axes |
deviceId | New | device ID |
axisNames | List | of new input axis names |
inputComponent | Physical | input axis direction component to bind (direction of last axis in axisNames) |
True | if | a binding could be found and updated, false if there was a collision |
Binding | and | Action reference of a collision as {collisionBinding=Binding, collisionAction=Action} or nil |
Delete a binding.Definition
deleteBinding(findDeviceId Binding, findActionName Name, findBindingIndex Binding, findAxisComponent Logical)Arguments
findDeviceId | Binding | device ID |
findActionName | Name | of binding action |
findBindingIndex | Binding | index, 1 primary, 2 secondary, etc. |
findAxisComponent | Logical | binding axis direction component to assign, always positive for buttons/keys/half-axes |
Check if a keyboard or mouse input is active.Definition
getKeyboardMouseInputActiveAndValue(axes List, axisDirection 1, inputDirection 1)Arguments
axes | List | of input axis names which are all required to be pressed for the input to be active |
axisDirection | 1 | or -1, determining the direction of the bound logical axis. |
inputDirection | 1 | or -1, determining the direction of the requested physical axis component. |
float | x | x part of quaternion |
float | y | y part of quaternion |
float | z | z part of quaternion |
float | w | w part of quaternion |
True | if | all given axes are currently active, input value of the non-modified axis (last in list) |
Scan gamepad / controller binding input.Definition
Both buttons and controller physical axes are checked for a given device and list of logical axes.
getGamepadInputActiveAndValue(internalDeviceId Engine-internal, axes List, axisDirection 1, inputDirection 1)Arguments
internalDeviceId | Engine-internal | device ID of device to scan |
axes | List | of axis names to scan |
axisDirection | 1 | or -1, determining the direction of the bound logical axis component. |
inputDirection | 1 | or -1, determining the direction of the requested physical axis component. |
True | if | all axes are active (digital interpretation), input value of the non-modified axis (last in list) |
Scan a controller axis on a device for input.Definition
getGamepadAxisValue()Return Values
Input | value | of the axis in the range [-1, 1] for full axes or [0, 1] for half axes. |
Update input for the current frame.Definition
update(dt Delta)Arguments
dt | Delta | time in milliseconds |
Check if any gamepad button or axis is pressed and set the input help mode if necessary.Definition
checkGamepadActive()Return Values
float | rotation | the final rotation |
Update mouse input state.Definition
updateMouseInput()Return Values
float | x | x part of quaternion |
float | y | y part of quaternion |
float | z | z part of quaternion |
float | w | w part of quaternion |
Finalize mouse input processing for the current frame.Definition
Wraps the mouse position around if required and resets movement accumulators.
finalizeMouseInput()
Clear an active binding buffer for re-use to avoid table allocation each frame.Definition
Automatically adds device entries if new devices are added.
clearActiveBindingBuffer()
Update input bindings associated with all registered and active events.Definition
updateEventBindings()
Check if there is currently any binding matching the pressed mouse combo mask.Definition
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).
hasBindingForPressedMouseComboMask()Return Values
float | x | x part of quaternion |
float | y | y part of quaternion |
float | z | z part of quaternion |
float | w | w part of quaternion |
Apply binding input shadow flag to bindings of linked actions for currently active input.Definition
shadowLinkedBindings()
Update binding input for combo action bindings.Definition
updateComboBindings()
Update input bindings with the current input state and trigger events.Definition
updateInput()
Update the input state of a single action-to-input binding.Definition
updateBindingInput()Return Values
float | x | x part of quaternion |
float | y | y part of quaternion |
float | z | z part of quaternion |
float | w | w part of quaternion |
Reset binding input state for bindings used in continuous trigger events.Definition
resetContinuousEventBindings(bool checkComboMasks, int gamepadComboMask, int gamepadMouseMask)Arguments
bool | checkComboMasks | [optional, default=false] If true, checks binding combo masks against provided parameters |
int | gamepadComboMask | [optional] Gamepad combo input bit mask |
int | gamepadMouseMask | [optional] Mouse combo input bit mask |
Set an event's binding's input to a neutral value and notify the event's listeners of that neutral position.Definition
neutralizeEventBindingInput()
Update and debug information display.Definition
updateDebugDisplay()
Save action bindings to player custom settings.Definition
saveToXMLFile()Return Values
float | distance | distance to rectangle |
Save all device settings.Definition
Updates and adds settings for active devices.
saveDeviceSettings(xmlFile Input)Arguments
xmlFile | Input | settings XML file handle |
float | distance | distance to line segment |
Get a deep copy of the action definitions list.Definition
getActionList()Return Values
boolean | hasIntersection | true if both lines intersect |
float | t1 | x position |
float | t2 | z position |
Get a loaded InputAction by name.Definition
Only use the returned action to assign references and do not change its state.
getActionByName(actionName Name)Arguments
actionName | Name | of the action to be returned |
InputAction |
Disable alternate bindings for a given action.Definition
This setting is only valid in the current input context and will be overwritten the next time any input event is
changed.
disableAlternateBindingsForAction(string actionName)Arguments
string | actionName | InputAction name |
Set the current input context.Definition
If no context of the given name exists, it will be created.
setContext(string name, bool createNew, bool deletePrevious)Arguments
string | name | Input context name |
bool | createNew | [optional, default=false] If true, will create a clear context with the given name, overriding any other with the same name. |
bool | deletePrevious | [optional, default=false] If true, will delete the previous context after setting the new context. |
boolean | hasIntersection | true if the line segment is completly in the rectangle OR if it intersects with one of the four rectangle sides |
Revert the input context to the previously set input context.Definition
Use this method only if you can guarantee a valid state, e.g. when calling setContext in a modal interaction context.
revertContext(bool deleteCurrent)Arguments
bool | deleteCurrent | [optional, default=false] If true, will delete the current input context before reverting to the previous context. |
float | pos1X | x pos of intersection 1, else nil |
float | pos1Y | y pos of intersection 1, else nil |
float | pos2X | x pos of intersection 2, else nil |
float | pos2Z | z pos of intersection 2, else nil |
Set the previous context for another context.Definition
This modifies the previous context value which is used to revert input contexts.
setPreviousContext(string forContextName, string previousContextName)Arguments
string | forContextName | Name of the input context whose previous context will be set |
string | previousContextName | New previous context name |
Clear all contexts except the root.Definition
The current context will also be set to root.
clearAllContexts()
Get the name of the current input context.Definition
getContextName()
Get an ordered copy of the action bindings table for manipulation.Definition
getActionBindingsCopy(onlyAssignable If)Arguments
onlyAssignable | If | true, will only copy assignable action bindings |
boolean | hasIntersection | true if spheres have an intersection else false |
Ordered | action | bindings in the form of {i={action=InputAction, bindings={Binding}}} |
Get the current action bindings table.Definition
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.
getActionBindings()Return Values
float | area | area in hectars |
Get an array of registered events in the current input context for a given action name.Definition
getEventsForActionName(string actionName)Arguments
string | actionName | Action name as valid in InputAction |
float | brightness | brightness |
table | Array | of events |
Get the first active event in the current input context for a given action name.Definition
getFirstActiveEventForActionName(string actionName)Arguments
string | actionName | Action name as valid in InputAction |
float | averageSpeed | average speed |
table | First | active event or InputEvent.NO_EVENT |
Set the mouse motion scale.Definition
The given scale factor is multiplied with the default mouse motion scale of 0.75 on the X and Y axes.
setMouseMotionScale(scale Mouse)Arguments
scale | Mouse | motion scale factor |
float | speed | speed |
Get the current mouse motion scale.Definition
getMouseMotionScale()Return Values
float | speedRandom | speed random |
x | motion | scale, Y motion scale |
Set a callback for binding changes.Definition
The callback function must accept the action bindings table as a single argument.
setBindingChangeCallback(callback Callback)Arguments
callback | Callback | function which takes a single table parameter in the form of {InputAction: {i=Binding}} |
float | normalSpeed | normal speed |
Set a callback for event changes.Definition
The callback function must accept the action-event tuples in an array as a single argument.
setEventChangeCallback(callback Callback)Arguments
callback | Callback | function which takes a single table parameter in the form of {i={action=InputAction, event=InputEvent}} |
float | tangentSpeed | tangent speed |
Notify a listener of binding changes.Definition
The notification callback is set via setBindingChangeCallback().
notifyBindingChanges()Return Values
float | spriteScaleX | X sprite scale |
Notify a listener of event changes.Definition
The notification callback is set via setEventChangeCallback().
notifyEventChanges()Return Values
float | spriteScaleY | Y sprite scale |
Notify components of an input mode change via the message center.Definition
notifyInputModeChange()Return Values
float | spriteScaleXGain | X sprite scale gain |
Check if user input bindings are corrupted and compare input configuration XML file versions.Definition
checkSettingsIntegrity()Return Values
float | spriteScaleYGain | Y sprite scale gain |
True | if | the user settings have passed the integrity check, false otherwise. |
Checks loaded default input bindings according to exclusive locked action groups defined in InputAction.Definition
This is a developer check to verify critical input plausibility.
checkDefaultInputExclusiveActionBindings()Return Values
True | if | there is a collision, false otherwise |
Determine if an axis name represents a physical full axis on any device.Definition
getIsPhysicalFullAxis(inputAxisName Axis)Arguments
inputAxisName | Axis | name |
object | instance or nil if no object could be created | |
True | if | no placeable object could be created at the requested position because there was no valid space, false otherwise |
True | if | the axis name represents a physical full axis, false otherwise |
Determine if an axis name represents a physical half-axis on any device.Definition
getIsHalfAxis(inputAxisName Axis, True if)Arguments
inputAxisName | Axis | name |
True | if | the axis name represents a physical half-axis, false otherwise |
Determine if an input name represents an analog (i.e. continuous) physical input.Definition
getIsAnalogInput(inputName Input)Arguments
inputName | Input | name (potentially a key, button or axis identifier) |
object | instance or nil if no object could be created | |
True | if | no placeable object could be created at the requested position because there was no valid space, false otherwise |
True | if | the input name represents an analog input |
Determine if an input name list represents keyboard input.Definition
getIsKeyboardInput()
Determine if an input name list represents mouse input.Definition
getIsMouseInput()Return Values
float | Ray | origin X position in world space |
float | Ray | origin Y position in world space |
float | Ray | origin Z position in world space |
float | Ray | direction X component |
float | Ray | direction Y component |
float | Ray | direction Z component |
Determine if an input name list represents a single mouse wheel step input.Definition
getIsMouseWheelInput()
Determine if an input name list represents gamepad / controller input.Definition
getIsGamepadInput()
Check if an input name list represents a single D-Pad input.Definition
getIsDPadInput()
Check if the input value of an axis can be considered zero.Definition
isAxisZero(value Axis)Arguments
value | Axis | input value |
True | if | the axis is at zero position, false otherwise |
Get the maximum number of bindings per action for a given device ID.Definition
getMaximumBindingCountForDeviceId()
Get the device category for a device identified by its engine-internal IDDefinition
getDeviceCategory()Return Values
any_type | unpackedValues | returns unpacked values found in string |
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.
Create a new InputDevice instance.Definition
new(internalId Internal, deviceId Device, deviceName Device, category Device)Arguments
internalId | Internal | device ID as issued by the engine (~ device index) |
deviceId | Device | ID as received by the operating system |
deviceName | Device | name as assembled by the engine |
category | Device | category, use one of the values of InputDevice.CATEGORY |
table | values | values |
New | InputDevice | instance |
Load device settings from an XML file.Definition
This will load settings other than input bindings, e.g. sensitivity for gamepad axes.
loadSettingsFromXML(xmlFile XML, deviceElement XML)Arguments
xmlFile | XML | file handle |
deviceElement | XML | data element for this device |
table | values | radian values |
Save device settings to an XML file.Definition
saveSettingsToXML(xmlFile XML, deviceElement XML)Arguments
xmlFile | XML | file handle |
deviceElement | XML | data element for this device |
table | result | text elements |
Determine if this device is a controller/gamepad.Definition
isController()Return Values
boolean | startsWidth | true if given string starts with pattern else false |
Load a device's ID from an XML file.Definition
loadIdFromXML(xmlFile XML, deviceElement XML)Arguments
xmlFile | XML | file handle |
deviceElement | XML | data element for this device |
boolean | startsWidth | true if given string ends with pattern else false |
Device | ID | or empty string |
Load a device's name from an XML file.Definition
loadNameFromXML(xmlFile XML, deviceElement XML)Arguments
xmlFile | XML | file handle |
deviceElement | XML | data element for this device |
string | trimedString | trimed text |
Device | name | or empty string |
Load a device's category from an XML file.Definition
loadCategoryFromXML(xmlFile XML, deviceElement XML, Device category)Arguments
xmlFile | XML | file handle |
deviceElement | XML | data element for this device |
Device | category |
any_type | value | not nil value |
Get a device ID prefix' numeric value, if it exists.Definition
getDeviceIdPrefix()Return Values
float | lx | x direction |
float | lz | z direction |
Prefix | number, | or -1 if none exists; raw engine-issued device ID |
Get a device ID prefixed with a given number.Definition
getPrefixedDeviceId()
Get a string representation for this device.Definition
toString()Return Values
float | lx | average x direction |
float | lz | average z direction |
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 the required base data for this manager.Definition
Loads controller symbols / UI overlays.
load()
Set up development-only gamepad label function if necessary.Definition
setDevGamepadLabelMapping()Return Values
boolean | isAttached | is attached |
Load controller symbols and create UI overlays.Definition
Reads a UV values from an XML configuration to create UI overlays from a texture atlas.
loadControllerSymbolsAndOverlays()Return Values
boolean | doesBlock | implement does block |
Create a single button overlay.Definition
createButtonOverlay()Return Values
integer | aiToolReverserDirectionNode | reverser direction node of ai tool |
Load vehicle axis input hint icons.Definition
The icons are kept in memory as overlays until the game is closed.
loadAxisIcons(xmlFile XML, modPath [optional])Arguments
xmlFile | XML | file handle |
modPath | [optional] | Path to loaded mod, will load defaults if set to nil |
float | maxTurnRadius | max turn radius |
Load axis icons defined by mods.Definition
loadModAxisIcons()Return Values
float | leftAreaPercentage | left area percentage |
float | rightAreaPercentage | right area percentage |
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
contextBindings | Bindings | list for the required context |
action | InputAction | reference |
isContextGamepad | If | true, we require gamepad bindings. Otherwise, keyboard and mouse is needed. |
Get bindings from one or two actions for the current input context (either gamepad or keyboard and mouse).Definition
getActionBindingsForContext()Return Values
float | area | area found |
float | totalArea | total area checked |
Get bindings for one or two actions for keyboard input, exclusively.Definition
getKeyboardBindings()
Resolve modifier symbols and add them to an overlays collection.Definition
resolveModifierSymbols(table overlays, table separators, table firstContextBinding)Arguments
table | overlays | Overlays collection which receives resolved modifier symbols |
table | separators | Array of separator types inbetween symbols |
table | firstContextBinding | Binding reference |
float | area | area found |
float | totalArea | total area checked |
Recursively permutate symbol names to resolve dynamically ordered names to fixed definitions.Definition
resolveAccumulatedSymbolPermutations()
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
table | overlays | Overlays collection which receives resolved symbols |
table | contextBindings | Array of Binding instances |
bool | isContextGamepad | If true, resolve gamepad symbols. Otherwise, resolve mouse symbols. |
float | area | area found |
float | totalArea | total area checked |
Add regular input display symbols to an overlays array.Definition
addRegularSymbols()
Add combo input display symbols to an overlays array.Definition
addComboSymbols()Return Values
table | instance | instance of object |
Get input symbol overlays for one or two actions.Definition
Use the second action parameter to display complementary actions, e.g. action1 is moving forward/backward, action 2
is moving left/right.
getControllerSymbolOverlays(actionName1 First, actionName2 [optional])Arguments
actionName1 | First | action name as defined and/or loaded in InputAction |
actionName2 | [optional] | Second action name as defined and/or loaded in InputAction |
integer | numOfConfigurationTypes | number of configuration types |
InputHelpElement | instance | containing the symbol overlays in its "buttons" field |
Determine if an action and bindings combinations requires their input symbols to be accumulated to get a combinedDefinition
symbol for better display.
requireSymbolAccumulation()Return Values
integer | numOfConfigurationTypes | number of configuration types |
Make a help element to display in the HUD.Definition
makeHelpElement()Return Values
string | name | name of config |
Called when action events in the input system have changed.Definition
onActionEventsChanged(displayActionEvents Array)Arguments
displayActionEvents | Array | of action-event tuples which require an input hint display, {i={action=InputAction, event=InputEvent}} |
integer | index | index of config |
Table sorting function for event help elements.Definition
Priority > primaryKeyboardInput > text
sortEventHelpElements()Return Values
table | configuration | configuration |
Sorting function for gamepad modeDefinition
sortEventHelpElementsGamepad()Return Values
any_type | value | value of attribute |
Store display help elements for currently active action events.Definition
storeEventHelpElements()Return Values
boolean | configurationHasBeenBought | configuration has been bought |
Store combo button help elements for any modifier buttons required by currently active action events.Definition
storeComboHelpElements()Return Values
table | color | color (r, g, b) |
Get the input help element for a given action.Definition
getEventHelpElementForAction(inputActionName Name)Arguments
inputActionName | Name | of the requested input action. |
integer | material | material |
Get input help elements for the current input context.Definition
getEventHelpElements(pressedComboMask Bit, isContextGamepad If)Arguments
pressedComboMask | Bit | mask of the currently pressed combo button input |
isContextGamepad | If | true, the player should be shown input hints for gamepad input. Otherwise, keyboard / mouse input help is required. |
any_type | value | value of config |
array | of | help elements (see InputDisplayManager:makeHelpElement() for structure) |
Get input help elements for currently available combo buttons.Definition
getComboHelpElements(isContextGamepad If)Arguments
isContextGamepad | If | true, the player should be shown input hints for gamepad input. Otherwise, keyboard / mouse input help is required. |
string | configKey | key of configuration |
integer | configIndex | index of configuration |
Hash | table | of currently active combo button action names, {action name=true} |
Get the controller symbol prefix for a device identified by its internal ID.Definition
getPrefix()
Get the "plus" sign overlay.Definition
This overlay is (re-)used in several places. Take care not to invalidate its state between uses.
getPlusOverlay()Return Values
table | color | color (r, g, b) |
Get the "or" sign overlay.Definition
This overlay is (re-)used in several places. Take care not to invalidate its state between uses.
getOrOverlay()Return Values
table | instance | instance of object |
Get the keyboard key glyph overlay (ButtonOverlay instance).Definition
This overlay is (re-)used in several places. Take care not to invalidate its state between uses.
getKeyboardKeyOverlay()Return Values
boolean | true | if loading was successful else false |
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
inputActionName | Name | of 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. |
boolean | success | true if added else false |
Axis | name | or nil if not found, internal ID of binding device |
Get an input action glyph overlay for the first gamepad button of the first binding of a given input action.Definition
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().
getGamepadInputActionOverlay(inputActionName Name, axisComponent [optional,)Arguments
inputActionName | Name | of an action as defined in InputAction |
axisComponent | [optional, | default=POSITIVE] Binding.AXIS_COMPONENT value |
boolean | hasPrerequisite | true if all prerequisite specializations are loaded |
Overlay | instance | or nil if no overlay is available for the action's bindings |
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
inputActionName | Name | of an action as defined in InputAction |
axisComponent | [optional, | default=POSITIVE] Binding.AXIS_COMPONENT value |
boolean | hasPrerequisite | true if all prerequisite specializations are loaded |
key | text | (e.g. "F" for "KEY_f") for the keyboard action binding or nil if no resolution is possible |
Get the controller symbol key name for a single gamepad / controller binding.Definition
For full axes, call this for each axis component binding and concatenate the symbol keys with a space inbetween.
getGamepadInputSymbolName(internalDeviceId Internal, axisName Input, isAxisInput If)Arguments
internalDeviceId | Internal | gamepad device ID |
axisName | Input | axis name |
isAxisInput | If | true, the bound input axis is an analog physical axis |
boolean | hasPrerequisite | true if all prerequisite specializations are loaded |
controller | symbols | configuration key name |
Get the controller symbol key name for a single mouse binding.Definition
For full axes, call this for each axis component binding and concatenate the symbol keys with a space inbetween.
getMouseInputSymbolName(axisNames Mouse)Arguments
axisNames | Mouse | binding axis names |
boolean | canStart | can start ai |
controller | symbols | configuration key name |
Called when action bindings have changed.Definition
onActionBindingsChanged(actionBindings Action)Arguments
actionBindings | Action | bindings table, {InputAction: {Binding}} |
boolean | canContiue | can contiue ai |
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
Create a new instance of InputEvent.Definition
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.
new(actionName Name, targetObject Event, eventCallback Event, triggerUp If, triggerDown If, triggerAlways If, startActive [optional,, callbackState [optional])Arguments
actionName | Name | of action, see InputAction |
targetObject | Event | target, first argument to event callback |
eventCallback | Event | callback, called when the action has input. Signature: callback(targetObject, actionName, inputValue, callbackState, isAnalog) |
triggerUp | If | true, the event fires once when an input signal of the given action goes to "up" state, e.g. a released key. |
triggerDown | If | true, the event fires once when an input signal of the given action goes to "down" state, e.g. a pressed key. |
triggerAlways | If | 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. |
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. |
float | direction | shape angle |
New | InputEvent | instance |
Set the ignore flag for input binding combo masks.Definition
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.
setIgnoreComboMask()Return Values
boolean | isNeeded | collision box is needed |
Get the ignore flag for input binding combo masks.Definition
getIgnoreComboMask()Return Values
string | attributes | stats attributes |
Notify this event of the input status of an associated action.Definition
-- 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
notifyInput(isDown If, isPressed If, inputValue Action, isAnalog True)Arguments
isDown | If | true, the action input had a "down" flank, i.e. the input has crossed the "down" threshold |
isPressed | If | true, the action input is in "pressed" state, i.e. the magnitude of the input is above the "down" threshold |
inputValue | Action | input 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. |
isAnalog | True | if the binding which provides the input value is analog. |
boolean | deactivateOnLeave | deactivate on leaving |
Reset this event after a frame.Definition
frameReset()Return Values
boolean | hasPrerequisite | true if all prerequisite specializations are loaded |
Make this InputEvent instance's ID.Definition
makeId()Return Values
boolean | exists | animation axists |
Return trigger codeDefinition
getTriggerCode()Return Values
boolean | isPlaying | animation is playing |
Initialize this event's input hint display text with information from its associated action.Definition
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().
initializeDisplayText(InputAction InputAction)Arguments
InputAction | InputAction | which this event references. |
float | animTime | real animation time in ms |
Input glyph display element.
-- Displays a key or button glyph for an input.
--@category GUI
Create a new instance of InputGlyphElement.Definition
new(table inputDisplayManager, float baseWidth, float baseHeight)Arguments
table | inputDisplayManager | InputDisplayManager reference |
float | baseWidth | Default width of this element in screen space |
float | baseHeight | Default height of this element in screen space |
table | npc | the npc object |
Delete this element and release its resources.Definition
delete()Return Values
table | instance | instance of object |
Delete any overlay copies.Definition
deleteOverlayCopies()Return Values
boolean | true | if loading was successful else false |
Set the scale of this element.Definition
setScale(float widthScale, float heightScale)Arguments
float | widthScale | Width scale factor |
float | heightScale | Height scale factor |
bool | true | if successful |
Set the glyph text to be displayed in all upper case or not.Definition
This resets the lower case setting if upper case is enabled.
setUpperCase()Return Values
bool | true | if successful |
Set the glyph text to be displayed in all lower case or not.Definition
This resets the upper case setting if lower case is enabled.
setLowerCase()Return Values
bool | true | if normalized |
Set the glyph text to be displayed in bold print or not.Definition
setBold()Return Values
bool | true | if normalized |
Set the button frame color for the keyboard glyphs.Definition
setKeyboardGlyphColor(table color)Arguments
table | color | Color as an RGBA array |
table | returns | a food group or nil if nothing is found |
Set the color for button glyphs.Definition
setButtonGlyphColor(table color)Arguments
table | color | Color as an RGBA array |
table | returns | a food group or nil if nothing is found |
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
string | actionName | InputAction name |
string | actionText | [optional] Additional action text to display after the glyph |
float | actionTextSize | [optional] Additional action text size in screen space |
bool | noModifiers | [optional] If true, will only show the input glyph of the last unmodified input binding axis |
bool | copyOverlays | [optional] If true, will create and handle a separate copy of an input glyph. Do not use this when updating the action each frame! |
table | returns | a food mixture or nil if nothing is found |
Set multiple actions whose input glyphs need to be displayed by this element.Definition
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.
setActions(table actionNames, string actionText, float actionTextSize, bool noModifiers, bool copyOverlays)Arguments
table | actionNames | InputAction names array |
string | actionText | [optional] Additional action text to display after the glyph |
float | actionTextSize | [optional] Additional action text size in screen space |
bool | noModifiers | [optional] If true, will only show the input glyph of the last unmodified input binding axis |
bool | copyOverlays | [optional] If true, will create and handle a separate copy of an input glyph. Do not use this when updating the action each frame! |
int | Food | consumption type, one of [AnimalFoodManager.FOOD_CONSUME_TYPE_SERIAL | AnimalFoodManager.FOOD_CONSUME_TYPE_PARALLEL] |
Update the display text from the set action text according to current casing settings.Definition
updateDisplayText()Return Values
table | returns | a food group or nil if not found |
Get the screen space width required by the glyphs used to display input in the current input context.Definition
getGlyphWidth()Return Values
float | returns | a production weight between 0 and 1 |
Draw the input glyph(s).Definition
draw()Return Values
table | instance | Instance of object |
Draw controller button glyphs.Definition
drawControllerButtons(table Array, float posX, float posY)Arguments
table | Array | of controller button glyph overlays |
float | posX | Initial drawing X position in screen space |
float | posY | Initial drawing Y position in screen space |
bool | returns | true if loading is fine |
float | X | position in screen space after the last glyph |
Draw keyboard key glyphs.Definition
drawKeyboardKeys(table Array, float posX, float posY)Arguments
table | Array | of keyboard key names |
float | posX | Initial drawing X position in screen space |
float | posY | Initial drawing Y position in screen space |
bool | returns | true if module init after placement is fine |
float | X | position in screen space after the last glyph |
Draw the action text after the input glyphs.Definition
drawActionText(float posX, float posY)Arguments
float | posX | Drawing X position in screen space |
float | posY | Drawing Y position in screen space |
HUD input help display.
-- Displays controls and further information for the current input context.
--@category GUI
Create a new instance of InputHelpDisplay.Definition
new(string hudAtlasPath)Arguments
string | hudAtlasPath | Path to the HUD texture atlas |
Add a help text line for this frame.Definition
Will be cleared after the current frame.
addHelpText()Return Values
bool | returns | true if initialization is fine |
Set the currently controlled vehicle.Definition
setVehicle(table vehicle)Arguments
table | vehicle | Vehicle reference or nil if no vehicle is controlled. |
string | fill | level |
Override of HUDDisplayElement.Definition
Moves out to the left to hide.
getHidingTranslation()Return Values
integer | total | animals. Default is zero |
Add a custom input help entry which is displayed in the current input context until removed.Definition
Custom entries will be displayed in order of addition after any automatically detected input help entries and before
vehicle extensions.
addCustomEntry()Return Values
string | return | animal type. nil if not available |
Clear all custom input help entries in the current context.Definition
clearCustomEntries()Return Values
table | of | cosumed food (result[fillTypeIndex]=amount) |
Update the input help's state.Definition
update()Return Values
table | Production | fill type information as {i={j={fillType=fillType, fillLevel=fillLevel, capacity=capacity}}} |
Update sizes and positions of this elements and its children.Definition
updateSizeAndPositions()Return Values
Create any required HUD extensions when the current vehicle configuration changes.Definition
refreshHUDExtensions()Return Values
bool | true | if registration went well |
Update HUD extensions if controlled vehicles have changed.Definition
updateHUDExtensions()Return Values
bool | true | if registration went well |
Recursively get vehicle specializations for a vehicle configuration.Definition
collectVehicleSpecializations()Return Values
float | dirty | factor [0-1] |
Get the available screen space height for displaying input help.Definition
getAvailableHeight()Return Values
table | instance | instance of object |
Update display elements with the current input context.Definition
updateInputContext()Return Values
boolean | true | if loading was successful else false |
Update entry glyphs and visibility with the current input help elements.Definition
updateEntries(table helpElements)Arguments
table | helpElements | Array of InputHelpElement for the current input context |
bool | true | if successful |
Update combo header state.Definition
updateComboHeaders(bool useGamepadButtons, int pressedComboMaskMouse, int pressedComboMaskGamepad)Arguments
bool | useGamepadButtons | If true, check gamepad input. Otherwise, check keyboard / mouse. |
int | pressedComboMaskMouse | Bit mask of pressed mouse combo actions |
int | pressedComboMaskGamepad | Bit mask of pressed gamepad combo actions |
bool | true | if animal is in the husbandry |
float | Screen | space height used by the combo header (0 if invisible) |
Update visibility and color of combo input glyphs.Definition
updateComboInputGlyphs(table comboActionStatus, int pressedComboMaskMouse, int pressedComboMaskGamepad)Arguments
table | comboActionStatus | Hashtable of combo action names which are currently available |
int | pressedComboMaskMouse | Bit mask of pressed mouse combo actions |
int | pressedComboMaskGamepad | Bit mask of pressed gamepad combo actions |
table |
Get input help elements based on the current input context.Definition
getInputHelpElements(float availableHeight, int pressedComboMaskGamepad, int pressedComboMaskMouse, bool useGamepadButtons)Arguments
float | availableHeight | Maximum available height to use for input help elements |
int | pressedComboMaskGamepad | Bit mask of pressed gamepad combo buttons |
int | pressedComboMaskMouse | Bit mask of pressed mouse combo buttons |
bool | useGamepadButtons | If true, we should draw gamepad / controller combo button glyphs |
table | instance | instance of object |
table | Input | help elements |
float | Screen | space height used by the returned help elements |
Set the current animation value for available height.Definition
setAnimationAvailableHeight()Return Values
boolean | true | if loading was successful else false |
Set the current animation position offset.Definition
setAnimationOffset()Return Values
bool | true | if successful |
Animate this element on hiding.Definition
animateHide()Return Values
bool | true | if successful |
Animate this element on showing.Definition
animateShow()Return Values
float | amount | effectively changed |
Called when a hiding or showing animation has finished.Definition
onAnimateVisibilityFinished()Return Values
float | delta | of amount changed |
Called when the connected input devices have changed.Definition
onInputDevicesChanged()Return Values
float | returns | the fillLevel of a fillType |
Draw the input help.Definition
Only draws if the element is visible and there are any help elements.
draw()Return Values
float | returns | the fillLevel of all fillType |
Draw the "controls" label on top of the display frame.Definition
drawControlsLabel()Return Values
float | returns | the capacity of a fillType |
Draw icons and text in help entries.Definition
drawHelpInfos()Return Values
float | returns | a progress of the fillType between 0 and 1. Default is 0. |
Draw vehicle HUD extensions.Definition
drawVehicleHUDExtensions()Return Values
float | actual | delta filled |
Set this element's UI scale.Definition
setScale(float uiScale)Arguments
float | uiScale | UI scale factor |
Store scaled positioning, size and offset values.Definition
storeScaledValues()Return Values
table | module | instance or nil of no module has been registered |
Get this element's base background position in screen space.Definition
getBackgroundPosition()Return Values
table | instance | instance of object |
Get the current top left position of the input help, including animation.Definition
getTopLeftPosition()Return Values
boolean | true | if loading was successful else false |
Get the maximum number of help entries which may be shown at any time.Definition
getMaxEntryCount()Return Values
float | returns | the capacity of a fillType |
int | Maximum | number of entries to show |
Returns if it is still allowed to add more help elementsDefinition
getIsHelpElementAllowed(table helpElements, table helpElement)Arguments
table | helpElements | existing table of help elements |
table | helpElement | help element to add |
float | amount | effectively changed |
boolean | isAllowed | isAllowed |
Set this element's dimensions.Definition
Override from HUDElement which adjusts frame with offset.
setDimension()Return Values
boolean | true | if loading was successful else false |
Create the background overlay for positioning.Definition
createBackground()Return Values
float | food | dropped |
Create required display components.Definition
createComponents()Return Values
float | spillage | total |
Create the frame around input help elements.Definition
createFrame()Return Values
table | instance | instance of object |
Create a vertical separator element.Definition
createVerticalSeparator()Return Values
boolean | true | if loading was successful else false |
Create a horizontal separator element.Definition
createHorizontalSeparator()Return Values
table | instance | instance of object |
Create an input glyph for displaying combo input buttons.Definition
createComboInputGlyph(float posX, float posY, float width, float height, string actionName)Arguments
float | posX | Screen space X position |
float | posY | Screen space Y position |
float | width | Screen space width |
float | height | Screen space height |
string | actionName | InputAction name of the combo action whose input glyphs need to be displayed |
boolean | true | if loading was successful else false |
table | Combo | InputGlyphElement instance |
Create a combo input glyph header.Definition
createComboHeader(hudAtlasPath Path, frameX Screen, frameY Screen, table combos, table boxSize, table separatorPositions)Arguments
hudAtlasPath | Path | to HUD texture atlas |
frameX | Screen | space X position of the display frame |
frameY | Screen | space Y position of the display frame |
table | combos | Array of input combination descriptions as defined in InputBinding |
table | boxSize | 2D vector which holds the pixel size of one combo input box within the header |
table | separatorPositions | Array of 2D vectors of separator pixel positions |
float | manure | dropped |
table | Combo | header HUDElement |
Create the mouse combo header.Definition
createMouseComboHeader()Return Values
float | manure | fill level |
Create the gamepad / controller combo header.Definition
createControllerComboHeader()Return Values
float | manure | used |
Create an input help entry box.Definition
createEntry()Return Values
table | instance | instance of object |
Create all required input help entry boxes.Definition
The boxes are modified as required to reflect the current input context.
createEntries()Return Values
boolean | true | if loading was successful else false |
Input help element.
-- Holds help and hint information about the current input context for display in the HUD.
--@category Input
Get an array of action names which were validly set in the constructor.Definition
getActionNames()Return Values
float | animTime | animation time [0..1] |
Maps key IDs to localization glyph symbols.
Get a display string for a list of mouse input axis namesDefinition
MouseHelper.getInputDisplayText()Return Values
float | duration | duration in ms |
Get a display name for a given key ID.Definition
Encapsulates engine getKeyName() function.
KeyboardHelper.getDisplayKeyName()Return Values
boolean | rightOrder | returns true if parts are in right order |
Get a display string for a list of keyboard input keys.Definition
KeyboardHelper.getInputDisplayText()Return Values
boolean | rightOrder | returns true if parts are in reverse right order |
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
inputList | List | of input button / axis names |
internalDeviceId | ID | of device as issued by the engine |
float | ret | limited value |
Join Multiplayer Game Screen.
-- @field mainBox Layout box for most of the screen, used to quickly show / hide everything.
Handle clicks on table header elementsDefinition
Triggers sorting and a view update.
onClickHeader()Return Values
table | instance | instance of object |
Handle changes in the server name filter fieldDefinition
onServerNameChanged(element TextInputElement, text New)Arguments
element | TextInputElement | instance |
text | New | text |
table | baleType | baleType object |
Save the current filter settings.Definition
saveFilterSettings()Return Values
table | brandColor | brandColor object |
Get the server info of the currently selected serverDefinition
getSelectedServer()Return Values
table | instance | instance of object |
Assign the "Start Game" button state.Definition
Enables the button if the currently selected server is valid for playing. Disables it otherwise.
setStartButtonState()Return Values
boolean | true | if loading was successful else false |
Filter a server with the current filter settings.Definition
filterServer(server Server)Arguments
server | Server | information (see onServerInfo()) for data structure |
boolean | true | if loading was successful else false |
True | if | the server matches the current filter settings, false otherwise |
Apply server filters to server list.Definition
setTableFiltersAndSorting()Return Values
boolean | success | success |
Update the server table.Definition
This causes a full rebuild of the table data.
rebuildServerList()Return Values
table | instance | instance of object |
Build a DataRow from server properties to add to the server list GuiElement.Definition
buildServerDataRow()Return Values
table | instance | instance of object |
dataRow | instance | with server data |
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.
Get the actual focus target, in case a child or parent element needs to be targeted instead.Definition
Override from BitmapElement: Only focuses children if #autoSelectChildren is true
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. |
GuiElement | Actual | element to focus. |
Main Menu Screen.
-- @field backgroundImage Main background image
Set up notifications display and animation.Definition
setupNotifications()Return Values
float | nearCoCRadius | Near circle of confusion radius (nearCoCRadius = 0 means no near blur (pinhole camera)) |
float | nearBlurEnd | Distance from the camera center where near blur ends |
float | farCoCRadius | Far circle of confusion radius (farCoCRadius = 0 means no far blur (pinhole camera)) |
float | farBlurStart | Distance from the camera center where far blur starts |
float | farBlurEnd | Distance from the camera center where far blur ends |
Set notification buttons disabled state.Definition
If fewer than 2 notifications are available to show, the cycle buttons will always be disabled.
setNotificationButtonsDisabled()
Reset notification data and display.Definition
resetNotifications()
Cycle through available notifications.Definition
cycleNotification(int signedDelta)Arguments
int | signedDelta | 1 or -1 for next or previous |
Handle an activation of the notification open button or input action.Definition
onNotificationBoxClick()
Update notifications.Definition
updateNotifications()Return Values
float | nearCoCRadius | Near circle of confusion radius (nearCoCRadius = 0 means no near blur (pinhole camera)) |
float | nearBlurEnd | Distance from the camera center where near blur ends |
float | farCoCRadius | Far circle of confusion radius (farCoCRadius = 0 means no far blur (pinhole camera)) |
float | farBlurStart | Distance from the camera center where far blur starts |
float | farBlurEnd | Distance from the camera center where far blur ends |
Update screen fading values.Definition
updateFading()
Creating data grid
@param table customMt custom metatableDefinition
new()Return Values
table | instance | instance of object |
19 | function 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 |
27 | end |
@param float worldZ world position zDefinition
getValueAtWorldPos()Return Values
table | value | value at the given position |
34 | function MapDataGrid:getValueAtWorldPos(worldX, worldZ) |
35 | local rowIndex, colIndex = self:getRowColumnFromWorldPos(worldX, worldZ) |
36 | return self:getValue(rowIndex, colIndex), rowIndex, colIndex |
37 | end |
@param float worldZ world position zDefinition
setValueAtWorldPos(table value)Arguments
table | value | value at the given position |
44 | function MapDataGrid:setValueAtWorldPos(worldX, worldZ, value) |
45 | local rowIndex, colIndex = self:getRowColumnFromWorldPos(worldX, worldZ) |
46 | self:setValue(rowIndex, colIndex, value) |
47 | end |
@param float worldZ world position zDefinition
getRowColumnFromWorldPos()Return Values
integer | row | row |
integer | column | column |
55 | function 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 |
68 | end |
UV coordinates in the map hotspot atlas.
Set the text offset using a raw value string in the form of "<X>px <Y>px".Definition
setRawTextOffset()Return Values
boolean | true | if loading was successful else false |
Set the farm this hotspot should be shown for. Use AccessHandler.EVERYONE for showing it to everybody (default)Definition
setOwnerFarmId()Return Values
bool | is | true if available Pallet has been assigned with a vehicle object |
Map overlay generator.
-- Provides density map based data overlays on top of an in-game map.
Create a MapOverlayGenerator instance.Definition
new(table l10n, table fruitTypeManager, table fillTypeManager, table farmlandManager, table farmManager)Arguments
table | l10n | I18N reference for text localization |
table | fruitTypeManager | FruitTypeManager reference for fruit type resolution |
table | fillTypeManager | FillTypeManager reference for fruit fill type resolution |
table | farmlandManager | FarmlandManager reference for farm land data access |
table | farmManager | FarmManager reference for farm land ownership data access |
Delete this instance and any used overlays.Definition
delete()
Set the valid fruit types of the current mission.Definition
setMissionFruitTypes()
Set the color blind mode for overlay creation.Definition
setColorBlindMode()
Build the map overlay for fruit types.Definition
buildFruitTypeMapOverlay()
Build the map overlay for growth states.Definition
buildGrowthStateMapOverlay()
Build the map overlay for soil states.Definition
buildSoilStateMapOverlay()
Build the map overlay for farm lands.Definition
buildFarmlandsMapOverlay()
Generate a map overlay of a given type.Definition
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().
generateOverlay(int mapOverlayType, function finishedCallback, table overlayState)Arguments
int | mapOverlayType | Overlay type as one of MapOverlayGenerator.OVERLAY_TYPE.[CROPS|GROWTH|SOIL|FARMLANDS] |
function | finishedCallback | Function which is called with the overlay ID as its argument when processing is finished, signature: function(overlayId) |
table | overlayState | Overlay state data which defines parameters (e.g. colors) of the map overlays. |
bool | True | if overlay generation has started, false if generation is already in progress or an invalid overlay type has been provided |
Generate a fruit type overlay.Definition
generateFruitTypeOverlay(function finishedCallback, table fruitTypeFilter)Arguments
function | finishedCallback | Called when generation is finished, signature: function(overlayId) |
table | fruitTypeFilter | Map of fruit type indices to booleans. If the value is true, the fruit type will be displayed. |
bool | True | if overlay generation has started, false if generation is already in progress or an invalid overlay type has been provided |
Generate a growth state overlay.Definition
generateGrowthStateOverlay(function finishedCallback, table fruitTypeFilter)Arguments
function | finishedCallback | Called when generation is finished, signature: function(overlayId) |
table | fruitTypeFilter | Map of growth state indices (MapOverlayGenerator.GROWTH_STATE_INDEX members) to booleans. If the value is true, the growth state will be displayed. |
bool | True | if overlay generation has started, false if generation is already in progress or an invalid overlay type has been provided |
Generate a soil state overlay.Definition
generateSoilStateOverlay(function finishedCallback, table fruitTypeFilter)Arguments
function | finishedCallback | Called when generation is finished, signature: function(overlayId) |
table | fruitTypeFilter | Map of soil state indices (MapOverlayGenerator.SOIL_STATE_INDEX members) to booleans. If the value is true, the soil state will be displayed. |
bool | True | if overlay generation has started, false if generation is already in progress or an invalid overlay type has been provided |
Generate a farm land overlay.Definition
generateFarmlandOverlay(function finishedCallback, table mapPosition)Arguments
function | finishedCallback | Called when generation is finished, signature: function(overlayId) |
table | mapPosition | Map position vector of a selection position. If the position is within a farm land, it will be highlighted. |
Check if any overlay is currently being generated and triggers a callback when it's finished.Definition
checkOverlayFinished()
Reset overlay generation state.Definition
reset()
Update the state each frame.Definition
Checks the overlay generation state.
update()
Get display information for crop types.Definition
Override to add new crop types or change information.
getDisplayCropTypes()Return Values
array | of | display 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}} |
373 | function 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 |
397 | end |
Get display information for growth states.Definition
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.
getDisplayGrowthStates()Return Values
array | of | display information, {i={colors={true={i={r,g,b,a}}, false={i={r,g,b,a}}}, description=text}} |
404 | function 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 | } |
451 | end |
Get display information for soil states.Definition
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.
getDisplaySoilStates()Return Values
array | of | display information, {i={colors={true={i={r,g,b,a}}, false={i={r,g,b,a}}}, description=text}} |
458 | function 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 | } |
490 | end |
Map Selection Screen.
-- Used when starting a new game.
-- @field mapSelector Map selection option at top of view
Creation event for map preview BitmapElement instances.Definition
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.
onCreateMapImage(element BitmapElement)Arguments
element | BitmapElement | instance which shows a map preview image |
Message center message types.
Use these identifiers to subscribe to and publish messages.
Subscribe the target to given message type.Definition
subscribe(integer messageType, function callback, table callbackTarget, any argument)Arguments
integer | messageType | Type of message |
function | callback | Callback function |
table | callbackTarget | Optional target |
any | argument | Optional argument, will be last in callback argument list |
table | implement | implement |
Unsubscribe the observer from messageDefinition
This is relatively slow, do not use in :update or :draw
unsubscribe(integer messageType, table callbackTarget)Arguments
integer | messageType | Type of message |
table | callbackTarget | Observer object |
boolean | success | success |
Unsubscribe the observer from all messagesDefinition
unsubscribeAll(table callbackTarget)Arguments
table | callbackTarget | Observer object |
boolean | supportsHardAttach | attacher joint supports hard attach |
Publish a message with given type and possible argumentsDefinition
publish(integer messageType, table arguments)Arguments
integer | messageType | Type of the message, used with the subscriptions |
table | arguments | Optional arguments passed to function |
boolean | success | success |
Publish a message with given type and possible arguments. This message is handled in the next frame.Definition
Useful for within networking code
publishDelayed(integer messageType, table arguments)Arguments
integer | messageType | Type of the message, used with the subscriptions |
table | arguments | Optional arguments passed to function |
float | totalMass | total mass |
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.
Create a new MissionCollaborators instance.Definition
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.
new()Return Values
float | total | amount of consumed pto torque in kNm |
Dismiss a (finished or cancelled) mission. Deletes it completely. Calls dismiss on the mission to handle money exchange to farm.
Creating managerDefinition
new()Return Values
table | instance | instance of object |
31 | function 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 |
47 | end |
Load data on map loadDefinition
loadMapData()Return Values
boolean | true | if loading was successful else false |
74 | function 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 |
124 | end |
Load map-configured transport missionsDefinition
loadTransportMissions()
Load vehicles for use with field missionsDefinition
loadMissionVehicles()
Unload data on mission deleteDefinition
unloadMapData()Code
349 | function 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) |
368 | end |
Write field mission data to savegame fileDefinition
saveToXMLFile(string xmlFilename)Arguments
string | xmlFilename | file path |
boolean | true | if loading was successful else false |
374 | function 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 |
394 | end |
Load fieldjob data from xml savegame fileDefinition
loadFromXMLFile(string filename)Arguments
string | filename | xml filename |
399 | function 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 |
462 | end |
Deletes field mission managerDefinition
delete()Code
466 | function MissionManager:delete() |
467 | end |
Updates field mission ownage data from xml savegame fileDefinition
update(string filename)Arguments
string | filename | xml filename |
472 | function 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 |
485 | end |
Get mission configuration given the nameDefinition
getTransportMissionConfig()
Get a mission config given an ID. Used by TransportMission:readStreamDefinition
getTransportMissionConfigById()
Get whether given farm has an active missionDefinition
hasFarmActiveMission()
Start given mission for a farm.Definition
startMission()
Cancel mission: sets it to finished without successDefinition
cancelMission()
Delete a missionDefinition
deleteMission()
On a client it sends an event insteadDefinition
dismissMission()
Get a list of active missionsDefinition
getActiveMissions()
Get whether any mission is currently runningDefinition
getIsAnyMissionActive()
Test whether the given mission is still able to runDefinition
canMissionStillRun()
Add a new transport trigger. Requires triggerId and index properties.Definition
addTransportMissionTrigger()
Remove a transport trigger.Definition
removeTransportMissionTrigger()
Generate a mission for given field. Returns nil if field already has an active missionDefinition
generateNewFieldMission()
Generation time is used for reliably sortingDefinition
assignGenerationTime()
Get a randomly chosen group of vehicles fitting for given mission type and field sizeDefinition
getRandomVehicleGroup(missionType type, fieldSize size)Arguments
missionType | type | of mission (string) |
fieldSize | size | of field: 'SMALL', 'MEDIUM', 'LARGE' |
List | of | vehicles. Each element is a table with filanema and configuration properties. |
Reward | ||
Used on the client. Make sure it never crashes on nil (patches)Definition
getVehicleGroupFromIdentifier()
Get a free activeMissionId, used for active missions only.Definition
getFreeActiveMissionId()
Validate missions on given field, after something happened to the field (event)Definition
validateMissionOnField()
Get a value at given world coordinatesDefinition
getMissionMapValue()
Get the mission associated with the activeMissionIdDefinition
getMissionForActiveMissionId()
Custom HUD drawing extension for MixerWagon.
-- Displays the fill levels of the mixer wagon.
--@category GUI
Create a new instance of MixerWagonHUDExtension.Definition
new(table vehicle, float uiScale, table uiTextColor, float uiTextSize)Arguments
table | vehicle | Vehicle which has the specialization required by a sub-class |
float | uiScale | Current UI scale |
table | uiTextColor | HUD text drawing color as an RGBA array |
float | uiTextSize | HUD text size |
table | instance | instance of object |
Determine if the HUD extension should be drawn.Definition
canDraw()Return Values
boolean | true | if loading was successful else false |
Get this HUD extension's display height.Definition
getDisplayHeight()Return Values
table | instance | instance of object |
float | Display | height in screen space |
Draw mixing ratio information for a mixing wagon when it is active.Definition
draw(float leftPosX, float rightPosX, float posY)Arguments
float | leftPosX | Left input help panel column start position |
float | rightPosX | Right input help panel column start position |
float | posY | Current input help panel drawing vertical offset |
boolean | true | if loading was successful else false |
float | Modified | input help panel drawing vertical offset |
ModHub categories frame
-- Displays categories.
--@category GUI
Create a new ModHubCategoriesFrame instance.Definition
new(table subclass_mt)Arguments
table | subclass_mt | [optional] Meta table of subclass |
Initialize with categories to be displayed.Definition
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.
initialize(table categories, function categoryClickedCallback, table headerIconUVs, string headerText)Arguments
table | categories | Category definitions array |
function | categoryClickedCallback | Notification callback for category activation(click/enter), signature: function(selectedId, baseCategoryIconUVs, baseCategoryLabel, clickedCategoryLabel) |
table | headerIconUVs | UV coordinates of the header icon to display |
string | headerText | Header text to display |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
float | nearCoCRadius | Near circle of confusion radius (nearCoCRadius = 0 means no near blur (pinhole camera)) |
float | nearBlurEnd | Distance from the camera center where near blur ends |
float | farCoCRadius | Far circle of confusion radius (farCoCRadius = 0 means no far blur (pinhole camera)) |
float | farBlurStart | Distance from the camera center where far blur starts |
float | farBlurEnd | Distance from the camera center where far blur ends |
Get the frame's main content element's screen position.Definition
getMainElementPosition()
Update scroll button visibility based on the currently visible list items.Definition
updateScrollButtons()
Handle a click / button activation on a category.Definition
onClickCategory()
Handle a double click on a category.Definition
onDoubleClickCategory()
Handle navigation selection of a category element.Definition
onCategorySelected()Return Values
boolean | isAllowed | state change is allowed |
Handle click on left navigation button.Definition
onClickLeft()Return Values
table | instance | instance of object |
Handle click on right navigation button.Definition
onClickRight()Return Values
boolean | true | if loading was successful else false |
Handle a list scrolling event.Definition
onScroll()Return Values
boolean | success | success |
Shop items frame for the in-game menu shop.
-- Displays purchasable items of a common category in a horizontal list layout.
--@category GUI
Create a new ModHubDetailsFrame instance.Definition
new(table subclass_mt)Arguments
table | subclass_mt | [optional] Meta table of subclass |
integer | fillTypeIndex | the fillType index |
Set the category to display.Definition
setCategory()Return Values
table | fillType | the fillType object |
Set an ordered array of ShopDisplayItem instances to display in this frame.Definition
setModInfo()Return Values
table | fillTypes | list of fillTypes |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
table | fillTypeCategory | fillType category object |
Get the frame's main content element's screen position.Definition
getMainElementPosition()Return Values
table | success | true if added else false |
Shop items frame for the in-game menu shop.
-- Displays purchasable items of a common category in a horizontal list layout.
--@category GUI
Create a new ModHubItemsFrame instance.Definition
new(table subclass_mt)Arguments
table | subclass_mt | [optional] Meta table of subclass |
table | fillTypes | list of fillTypes |
Set the callback to use when an item is activated (for buying or selling).Definition
setItemClickCallback()Return Values
table | fillTypes | fill types |
Set the callback to use when an item is selected in the view.Definition
setItemSelectCallback()Return Values
integer | converterIndex | index of converterIndex |
Set the category to display.Definition
setCategory()Return Values
table | converterData | converter data |
Get the frame's main content element's screen size.Definition
getMainElementSize()Return Values
table | sample | sample |
Get the frame's main content element's screen position.Definition
getMainElementPosition()Return Values
table | instance | instance of object |
Update scroll button visibility based on the currently visible list items.Definition
updateScrollButtons()Return Values
boolean | true | if loading was successful else false |
Handle a click / button activation on an item.Definition
onClickItem()Return Values
boolean | success | success |
Handle a double-click on an item.Definition
onDoubleClickItem()Return Values
table | fruitType | fruitType type object |
Handle click on left navigation button.Definition
onClickLeft()Return Values
table | fruit | the fruit object |
Handle click on right navigation button.Definition
onClickRight()Return Values
table | fruit | the fruit object |
Handle selection of an item.Definition
onItemSelected()Return Values
table | fruitTypes | a list of fruitTypes |
Mode
Create a new instance of ModHubScreen.Definition
new(table target, table custom_mt, table messageCenter, table l10n, table inputManager, table modHubController, bool isConsoleVersion)Arguments
table | target | Callback target |
table | custom_mt | Sub-class meta table |
table | messageCenter | MessageCenter reference |
table | l10n | I18N reference for text localization |
table | inputManager | InputBinding reference |
table | modHubController | modHubController reference |
bool | isConsoleVersion | If true, the game is running on a console |
table | fruitTypeCategory | fruitType category object |
Reset menu state (and all pages).Definition
reset()Return Values
table | success | true if added else false |
Button function for backing out of the menu.Definition
clickBackCallback()Return Values
table | fruitTypes | list of fruitTypes |
Clear menu button actions, events and callbacks.Definition
clearMenuButtonActions()Return Values
table | fruitTypes | fruit types |
Assign menu button information to the in-game menu buttons.Definition
assignMenuButtonInfo()Return Values
table | fillTypes | fill types |
Handle a menu action click by calling one of the menu button callbacks.Definition
onMenuActionClick()Return Values
table | fillTypes | fill types |
bool | True | if no callback was present and no action was taken, false otherwise |
Handle menu confirmation input event.Definition
onClickOk()Return Values
float | literPerSqm | liter per sqm |
Handle menu back input event.Definition
onClickBack()Return Values
integer | converterIndex | index of converterIndex |
Handle menu cancel input event.Definition
Bound to quite the game to the main menu.
onClickCancel()Return Values
table | converterData | converter data |
Handle menu active input event.Definition
Bound to save the game.
onClickActivate()Return Values
table | instance | instance of object |
Update the buttons panel when a given page is visible.Definition
updateButtonsPanel()Return Values
boolean | true | if loading was successful else false |
Make a callback which encloses the self reference and handles arbitrary arguments afterwards.Definition
makeSelfCallback()Return Values
table | gameplayHintGroup | a random gameplay hint group |
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.
Disable automatic playing of sound samples in child buttons.Definition
disableButtonSounds()
Trigger a "left" input.Definition
inputLeft(isShoulderButton If)Arguments
isShoulderButton | If | true, assume a shoulder button input (PC or console) |
Trigger a "right" input.Definition
inputRight(isShoulderButton If)Arguments
isShoulderButton | If | true, assume a shoulder button input (PC or console) |
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
Create a new Tween.Definition
new(table subClass, function setterFunction, table startValues, table endValues, float duration)Arguments
table | subClass | Subclass metatable for inheritance |
function | setterFunction | Values setter function. Signature: callback(v1, ..., vn) or callback(target, v1, ..., vn). |
table | startValues | Original values |
table | endValues | Target values |
float | duration | Duration of tween in milliseconds |
Set a callback target for this tween.Definition
If a target has been set, the setter function must support receiving the target as its first argument.
setTarget()
Get the current tween value.Definition
tweenValue()
Apply a value via the setter function.Definition
applyValue()
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
Create a new Overlay.Definition
new(overlayFilename File, x Screen, y Screen, width Display, height Display)Arguments
overlayFilename | File | path of the source texture |
x | Screen | position x |
y | Screen | position y |
width | Display | width |
height | Display | height |
Delete this overlay.Definition
Releases the texture file handle.
delete()
Set this overlay's color.Definition
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}.
setColor(r Red, g Green, b Blue, a Alpha)Arguments
r | Red | channel |
g | Green | channel |
b | Blue | channel |
a | Alpha | channel |
Set this overlay's UVs which define the area to be displayed within the target texture.Definition
setUVs(uvs UV)Arguments
uvs | UV | coordinates in the form of {u1, v1, u2, v2, u3, v3, u4, v4} |
Set this overlay's position.Definition
setPosition()
Get this overlay's position.Definition
getPosition()Return Values
float | X | position in screen space |
float | Y | position in screen space |
Set this overlay's width and height.Definition
Either value can be omitted (== nil) for no change.
setDimension()
Reset width, height and scale to initial values set in the constructor.Definition
resetDimensions()
Set horizontal flipping state.Definition
setInvertX(invertX If)Arguments
invertX | If | true, will set the overlay to display its image flipped horizontally |
Set this overlay's rotation.Definition
setRotation(rotation Rotation, centerX Rotation, centerY Rotation)Arguments
rotation | Rotation | in radians |
centerX | Rotation | pivot X position offset from overlay position in screen space |
centerY | Rotation | pivot Y position offset from overlay position in screen space |
Set this overlay's scale.Definition
Multiplies the scale values with the initial dimensions and sets those as the current dimensions.
setScale(float scaleWidth, float scaleHeight)Arguments
float | scaleWidth | Width scale factor |
float | scaleHeight | Height scale factor |
Get this overlay's scale values.Definition
getScale()Return Values
float | Width | scale factor |
float | Height | scale factor |
Render this overlay.Definition
render()
Set this overlay's alignment.Definition
setAlignment(vertical Vertical, horizontal Horizontal)Arguments
vertical | Vertical | alignment value, one of Overlay.ALIGN_VERTICAL_[...] |
horizontal | Horizontal | alignment value, one of Overlay.ALIGN_HORIZONTAL_[...] |
Set this overlay's visibility.Definition
setIsVisible()
Set a different image for this overlay.Definition
The previously targeted image's handle will be released.
setImage(overlayFilename File)Arguments
overlayFilename | File | path to new target image |
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.
Set the current page index.Definition
Indices are based on mapped pages, which are all available and visible pages added to this element.
setPage(pageMappingIndex Index)Arguments
pageMappingIndex | Index | of page in page mappings |
bool | True | if the page changed |
Get a new page ID based on an internal counter.Definition
getNextID()
Add a new page.Definition
addPage(id Page, element Page, title Page, index [optional])Arguments
id | Page | ID |
element | Page | container GuiElement |
title | Page | title for displaying |
index | [optional] | Insertion index for page. If undefined or outside of valid range, will add the page at the end. |
Get the number of currently visible pages.Definition
getVisiblePagesCount()
Get a page ID by the page container element reference.Definition
getPageIdByElement(element Page)Arguments
element | Page | container GuiElement instance |
Page |
Get a page container element by page index.Definition
getPageElementByIndex(pageIndex Index)Arguments
pageIndex | Index | of page in all (incl. disabled and invisible) pages |
Page | container | GuiElement instance |
Get the page index in this element's page array for a given element reference.Definition
getPageIndexByElement(table element)Arguments
table | element | GuiElement instance |
int | Page | index |
Get the page index in this elements page mapping array (visible pages) for a given element reference.Definition
getPageMappingIndexByElement(table element)Arguments
table | element | GuiElement instance |
int | Page | mapping index |
Remove a page, identified by its page container element, from this element.Definition
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.
removePageByElement(pageElement Page)Arguments
pageElement | Page | container element |
Get the page ID of the currently displayed page.Definition
getCurrentPageId()
Get the index of a page in the page mappings (only visible pages) by page ID.Definition
getPageMappingIndex()
Determine if a page, identified by page ID, is disabled.Definition
getIsPageDisabled()
Get a page by ID.Definition
getPageById()
Set a page's disabled state.Definition
setPageIdDisabled(pageId Page, disabled True)Arguments
pageId | Page | ID |
disabled | True | for disabled, false for enabled |
Get page titles of all pages which were visible at the latest call to updatePageMapping()Definition
getPageTitles()
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
On create glow materialDefinition
onCreateGlowMaterial(empty empty, integer id)Arguments
empty | empty | empty |
integer | id | id of node |
90 | function Placeable.onCreateGlowMaterial(_, id) |
91 | if getHasShaderParameter(id, "colorScale") then |
92 | Placeable.GLOW_MATERIAL = getMaterial(id, 0) |
93 | end |
94 | end |
Creating placeableDefinition
new(boolean isServer, boolean isClient, table customMt)Arguments
boolean | isServer | is server |
boolean | isClient | is client |
table | customMt | custom metatable |
table | instance | Instance of object |
106 | function 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 |
146 | end |
Deleting placeableDefinition
delete()Code
150 | function 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) |
205 | end |
Deleting placeable finalDefinition
deleteFinal()Code
209 | function Placeable:deleteFinal() |
210 | if self.nodeId ~= 0 then |
211 | delete(self.nodeId) |
212 | self.nodeId = 0 |
213 | end |
214 | end |
Set collision mask of node and its childrenDefinition
setCollisionMask(integer nodeId, integer mask)Arguments
integer | nodeId | id of node |
integer | mask | collision mask |
220 | function 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 |
227 | end |
Returns true if player is in rangeDefinition
getIsPlayerInRange(float distance, table player)Arguments
float | distance | distance |
table | player | player |
boolean | isInRange | is in range |
234 | function 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 |
248 | end |
Returns true if player is in rangeDefinition
isInActionDistance(table player, integer refNode, float distance)Arguments
table | player | player |
integer | refNode | id of reference node |
float | distance | distance |
boolean | isInRange | is in range |
256 | function 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 |
265 | end |
Called on client side on joinDefinition
readStream(integer streamId, table connection)Arguments
integer | streamId | stream ID |
table | connection | connection |
271 | function 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 |
298 | end |
Called on server side on joinDefinition
writeStream(integer streamId, table connection)Arguments
integer | streamId | stream ID |
table | connection | connection |
304 | function 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 |
325 | end |
Create nodeDefinition
createNode(string i3dFilename)Arguments
string | i3dFilename | i3d file name |
boolean | success | success |
362 | function 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 |
384 | end |
Sets the preview material to all nodes in the placeableDefinition
setPreviewMaterials(integer node, table nodeTable)Arguments
integer | node | id of node |
table | nodeTable | table to save the nodes |
390 | function 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 |
400 | end |
Set placable preview stateDefinition
setPlaceablePreviewState(int state)Arguments
int | state | Placement state [Placeable.PREVIEW_STATE.CHECKING | Placeable.PREVIEW_STATE.VALID | Placeable.PREVIEW_STATE.INVALID] |
405 | function 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 |
454 | end |
Load placeableDefinition
load(string xmlFilename, float x, float y, float z, float rx, float ry, float rz, boolean initRandom)Arguments
string | xmlFilename | xml file name |
float | x | x world position |
float | y | z world position |
float | z | z world position |
float | rx | rx world rotation |
float | ry | ry world rotation |
float | rz | rz world rotation |
boolean | initRandom | initialize random |
boolean | success | success |
467 | function 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 |
645 | end |
Load area definitions from XML into an area array.Definition
loadAreasFromXML(table areaArray, string xmlFile, string xmlPathTemplate, bool isRamp)Arguments
table | areaArray | Array instance which receives loaded area definitions. |
string | xmlFile | Loaded XML file handle |
string | xmlPathTemplate | XML element path template for an area type |
bool | isRamp | If true, the targeted areas are ramps |
Load a single area definition from XML.Definition
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.
loadAreaFromXML(table area, integer xmlFile, string key, bool isRamp)Arguments
table | area | Empty area definition table which receives the loaded node IDs. |
integer | xmlFile | ID of the XML file |
string | key | String Key to the XML element |
bool | isRamp | If true, the targeted areas are ramps |
boolean | success | success |
685 | function 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 |
712 | end |
Load foliage definitons from XML.Definition
loadFoliageAreaFromXML()Code
716 | function 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 |
731 | end |
Load hotspot from XML definitonsDefinition
loadHotspotFromXML()Code
735 | function 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) |