Global

Members

(constant) g_AIColor

Highlight AIs in the player-dropdownlist.
Source:

(constant) g_Ambient

A random file will be played. TODO: more variety
Source:

g_availableFormations

Contains the layout and button settings per selection panel getItems returns a list of basic items used to fill the panel. This method is obligated. If the items list is empty, the panel won't be rendered. Then there's a loop over all items provided. In the loop, the item and some other standard data is added to a data object. The standard data is var data = { "i": index "item": item coming from the getItems function "selection": list of currently selected items "playerState": playerState "unitEntState": first selected entity state "rowLength": rowLength "numberOfItems": number of items that will be processed "button": gui Button object "icon": gui Icon object "guiSelection": gui button Selection overlay "countDisplay": gui caption space }; Then, addData is called, and can be used to abort the processing of the current item by returning false. It should return true if you want the panel to be filled. addData is used to add data to the data object on top (or instead of) the standard data. addData is not obligated, the function will just continue with the content setters if no addData is present. After the addData, all functions starting with "set" are called. These are used to set various parts of content.
Source:

g_CachedLastStates

Cache concatenated list of player states ("active", "defeated" or "won").
Source:

g_ChatCommands

Chatmessage shown after commands like /me or /enemies.
Source:

(constant) g_ChatLines

Maximum number of lines to display simultaneously.
Source:

g_ChatMessages

The strings to be displayed including sender and formating.
Source:

g_ChatMessages

All chat messages received since init (i.e. after lobby join and after returning from a game).
Source:

(constant) g_ChatTimeout

Number of seconds after which chatmessages will disappear.
Source:

g_ChatTimers

Holds the timer-IDs used for hiding the chat after g_ChatTimeout seconds.
Source:

(constant) g_Cheats :Object

All known cheat commands.
Type:
  • Object
Source:

(constant) g_CivData

Offer users to select playable civs only. Load unselectable civs as they could appear in scenario maps.
Source:

(constant) g_CivData

To show the titles of the selected civs in the replay details.
Source:

g_CivData

Not constant as we add "gaia".
Source:

(constant) g_CivData

Load playable civs.
Source:

(constant) g_ColorRandom

Highlight the "random" dropdownlist item.
Source:

(constant) g_DefaultPopulationColor

Colors to flash when pop limit reached.
Source:

g_DevSettings

Cache dev-mode settings that are frequently or widely used.
Source:

g_DiplomacyMessages

Chatmessage shown on diplomacy change.
Source:

g_Disconnected

True if the connection to the server has been lost.
Source:

(constant) g_DurationFilterIntervals

Allow to filter replays by duration in 15min / 30min intervals.
Source:

(constant) g_EngineInfo

Used for checking replay compability.
Source:

g_fadeAttackUnit

PREDEFINED FUNCTIONS
Source:

g_FollowPlayer

True if the camera should focus on attacks and player commands and select the affected units.
Source:

(constant) g_GameColors

Current games will be listed in these colors.
Source:

g_GameEnded

Whether the current player has lost/won and reached the end of their game. Used for reporting the gamestate and showing the game-end message only once.
Source:

g_GameList

All games currently running.
Source:

g_GameStarted

Used to prevent calling resetReadyData when starting a game.
Source:

(constant) g_GameStatusOrder

Initial sorting order of the gamelist.
Source:

g_HasIdleWorker

Cache the idle worker status.
Source:

g_IsChatAddressee

Returns true if the current player is an addressee, given the chat message type and sender.
Source:

g_IsController

Is this user in control of game settings (i.e. is a network server, or offline player).
Source:

g_IsNetworked

True if this is a multiplayer game.
Source:

g_IsObserver

True if the current user has observer capabilities.
Source:

g_IsTrainingBlocked

Blink the population counter if the player can't train more units.
Source:

g_LastGameStanza

Only send a lobby update if something actually changed.
Source:

g_MapData

Cache containing the mapsettings for scenario/skirmish maps. Just-in-time loading.
Source:

(constant) g_MapFilters

The dropdownlist items will appear in the order they are added.
Source:

g_MapNames

Sorted list of unique maptitles. Used by mapfilter.
Source:

(constant) g_MapPath

Directory containing all maps of the given type.
Source:

(constant) g_MapSizes

Used for creating the mapsize filter.
Source:

(constant) g_MapSizes

Used for the gamelist-filtering.
Source:

(constant) g_MapTypes

Used for the gamelist-filtering.
Source:

g_MatchID

Unique ID for lobby reports.
Source:

(constant) g_MaxPlayers

The maximum number of players that the engine supports. TODO: Maybe we can support more than 8 players sometime.
Source:

(constant) g_MaxTeams

The maximum number of teams allowed.
Source:

g_messageBoxBtnFunctions

Contains global GUI functions accessible from every GUI script/file.
Source:

(constant) g_ModeratorPrefix

A symbol which is prepended to the username of moderators.
Source:

g_NetMessageTypes

Handle all netmessage types that can occur.
Source:

(constant) g_NetMessageTypes

Processes a CNetMessage (see NetMessage.h, NetMessages.h) sent by the CNetServer.
Source:

g_NetMessageTypes

Notifications sent by XmppClient.cpp
Source:

g_NetworkWarnings

Currently displayed network warnings. At most one message per user.
Source:

g_NetworkWarningTexts

Message-types to be displayed.
Source:

(constant) g_NetworkWarningTimeout

Number of milliseconds to display network warnings.
Source:

g_NotificationsTypes

Defines how the GUI reacts to notifications that are sent by the simulation.
Source:

g_PanelsOrder

If two panels need the same space, so they collide, the one appearing first in the order is rendered. Note that the panel needs to appear in the list to get rendered.
Source:

(constant) g_PlayerColors

All selectable playercolors except gaia.
Source:

g_Playernames

Array of unique usernames of all replays. Used for autocompleting usernames.
Source:

g_Players

Cache the basic player data (name, civ, color).
Source:

(constant) g_PlayerStatuses

The playerlist will be assembled using these values.
Source:

(constant) g_PopulationCapacities

Allow to filter by population capacity.
Source:

g_PreviousHeroHitPoints

Blink the hero selection if that entity has lost health since the last turn.
Source:

(constant) g_RandomCiv

Placeholder item for the civ-dropdownlists.
Source:

(constant) g_RandomMap

Placeholder item for the map-dropdownlist.
Source:

(constant) g_ReadyColor

Highlight ready players.
Source:

g_Replays

All replays found in the directory.
Source:

g_ReplaysFiltered

List of replays after applying the display filter.
Source:

g_ResearchListTop

Top coordinate of the research list. Changes depending on the number of displayed counters.
Source:

(constant) g_RomanNumbers

Used for generating the botnames.
Source:

g_SelectedGameIP

Used to restore the selection after updating the gamelist.
Source:

g_SelectedPlayer

Used to restore the selection after updating the playerlist.
Source:

g_selectedReplayDirectory

Directory name of the currently selected replay. Used to restore the selection after changing filters.
Source:

g_Selection

Cache some quantities which depends only on selection
Source:

(constant) g_SenderFont

Used for highlighting the sender of chat messages.
Source:

(constant) g_SenderFont

Used for highlighting the sender of chat messages.
Source:

(constant) g_Settings

An object containing all values given by setting name. Used by lobby, gamesetup, session, summary screen and replay menu.
Source:

(constant) g_SettingsDirectory

Directory containing all editable settings.
Source:

g_ShowAllStatusBars

Whether status bars should be shown for all of the player's units.
Source:

g_ShowGuarding

List of additional entities to highlight.
Source:

(constant) g_ShowTimestamp

Whether or not to display timestamps in the chat window.
Source:

g_SimState

Cache simulation state (updated on every simulation update).
Source:

(constant) g_SpamBlockDuration

Mute spammers for this time.
Source:

(constant) g_SpamBlockTimeframe

Mute clients who exceed the rate of 1 message per second for this time
Source:

g_SpamMonitor

Remembers how many messages were sent by each user since the last reset. For example { "username": [numMessagesSinceReset, lastReset, timeBlocked] }
Source:

g_StatusMessageTypes

Show a label and grey overlay or hide both on connection change.
Source:

(constant) g_SystemColor

Color for error messages in the chat.
Source:

(constant) g_UnassignedColor

Color for "Unassigned"-placeholder item in the dropdownlist.
Source:

(constant) g_UnassignedPlayerColor

Highlight observer players in the dropdownlist.
Source:

(constant) g_Username

Current username. Cannot contain whitespace.
Source:

g_UserRating

Rating of the current user. Contains the number or an empty string in case the user has no rating.
Source:

(constant) g_VictoryColor

Highlights the victory condition in the game-description.
Source:

g_ViewedPlayer

The playerID selected in the change perspective tool.
Source:

g_WorkerTypes

Unit classes to be checked for the idle-worker-hotkey.
Source:

lastTickTime

Last time when onTick was called(). Used for animating the main menu.
Source:

Methods

addAnimals()

Create huntable animals.
Source:

addBases(type, distance)

Chose starting locations for the given players.
Parameters:
Name Type Description
type string "radial", "stacked", "stronghold", "random"
distance number radial distance from the center of the map
Source:

addBerries()

Create fruits.
Source:

addBluffs(constraint, size, deviation, fill)

Create bluffs, i.e. a slope hill reachable from ground level. Fill it with wood, mines, animals and decoratives.
Parameters:
Name Type Description
constraint Array where to place them
size number size of the bluffs (1.2 would be 120% of normal)
deviation number degree of deviation from the defined size (0.2 would be 20% plus/minus)
fill number size of map to fill (1.5 would be 150% of normal)
Source:

addChatMessage(msg)

Displays the prepared chatmessage.
Parameters:
Name Type Description
msg Object
Source:

addChatMessage(msg)

Process and if appropriate, display a formatted message.
Parameters:
Name Type Description
msg Object The message to be processed.
Source:

addDecoration()

Add grass, rocks and bushes.
Source:

addElements()

Adds an array of elements to the map.
Source:

addElevation(constraint, el)

Create varying elevations.
Parameters:
Name Type Description
constraint Array avoid/stay-classes
el Object the element to be rendered, for example: "class": g_TileClasses.hill, "painter": [g_Terrains.mainTerrain, g_Terrains.mainTerrain], "size": 1, "deviation": 0.2, "fill": 1, "count": scaleByMapSize(8, 8), "minSize": Math.floor(scaleByMapSize(5, 5)), "maxSize": Math.floor(scaleByMapSize(8, 8)), "spread": Math.floor(scaleByMapSize(20, 20)), "minElevation": 6, "maxElevation": 12, "steepness": 1.5
Source:

addFish()

Create fish.
Source:

addForests()

Create dense forests.
Source:

addHills()

Create rolling hills.
Source:

addLakes()

Create random lakes with fish in it.
Source:

addLayeredPatches()

Universal function to create layered patches.
Source:

addMetal()

Create metal mines.
Source:

addMountains()

Create steep mountains.
Source:

addNetworkWarning(msg)

Remember this warning for a few seconds. Overwrite previous warnings for this user.
Parameters:
Name Type Description
msg GUI message sent by NetServer or NetClient
Source:

addPlateaus()

Create plateaus.
Source:

addProps()

Place less usual decoratives like barrels or crates.
Source:

addRivers()

Create rivers.
Source:

addStone()

Create stone mines.
Source:

addStragglerTrees()

Create straggler trees.
Source:

addToClass()

Add point to given class by id
Source:

addValleys()

Create valleys.
Source:

assembleTooltip(template)

Assemble a tooltip text
Parameters:
Name Type Description
template Information about a Unit, a Structure or a Technology
Source:
Returns:
The tooltip text, formatted.

avoidClasses()

Create an avoid constraint for the given classes by the given distances
Source:

bigFirstLetter()

Give the first character a larger font.
Source:

borderClasses()

Create a border constraint for the given classes by the given distances
Source:

calcReqs(op, val)

Calculate the prerequisite requirements of a technology. Works recursively if needed.
Parameters:
Name Type Description
op The base operation. Can be "civ", "tech", "all" or "any".
val The value associated with the above operation.
Source:
Returns:
Sorted requirments.

checkIfInClass()

Checks if the given tile is in class "id"
Source:

checkSpamMonitor()

Reset timer used to measure message send speed. Clear message count every 5 seconds.
Source:

clampColorValue(value) → {number}

Ensure `value` is between 0 and 1.
Parameters:
Name Type Description
value number
Source:
Returns:
Type
number

clone()

returns a clone of a simple object or array Only valid JSON objects are accepted So no recursion, and only plain objects or arrays
Source:

closePage()

Close GUI page and call callbacks if they exist.
Source:

colorDistance(color1, color2) → {number}

Computes the euclidian distance between the two colors. The smaller the return value, the close the colors. Zero if identical.
Parameters:
Name Type Description
color1 Object
color2 Object
Source:
Returns:
Type
number

colorizePlayernameByID()

This function is used for AIs, whose names don't exist in g_PlayerAssignments.
Source:

colorPlayerName(playername)

Returns the given playername wrapped in an appropriate color-tag.
Parameters:
Name Type Description
playername string
Source:

controlsPlayer()

Returns true if the current user can issue commands for that player.
Source:

createAreas()

Attempts to place the given number of areas in random places of the map. Returns actually placed areas.
Source:

createAreasInAreas()

Attempts to place the given number of areas in random places of the given areas. Returns actually placed areas.
Source:

createBase(player, walls)

Create the base for a single player.
Parameters:
Name Type Description
player Object contains id, angle, x, z
walls boolean Whether or not iberian gets starting walls
Source:

createBoundingBox()

Create an array of points the fill a bounding box around a terrain feature.
Source:

createObjectGroups()

Attempts to place the given number of groups in random places of the map. Returns the number of actually placed groups.
Source:

createObjectGroupsByAreas()

Attempts to place the given number of groups in random places of the given areas. Returns the number of actually placed groups.
Source:

deleteReplay()

Shows a confirmation dialog and deletes the selected replay from the disk in case.
Source:

deleteReplayButtonPressed()

Callback.
Source:

deleteReplayWithoutConfirmation()

Attempts to delete the selected replay from the disk.
Source:

displayGamestateNotifications()

Update the overlay with the most recent network warning of each client.
Source:

displayProfile(caller)

Display the profile of the selected player. Displays N/A for all stats until updateProfile is called when the stats are actually received from the bot.
Parameters:
Name Type Description
caller string From which screen is the user requesting data from?
Source:

displayReplayCompatibilityError(replay)

Shows an error message stating why the replay is not compatible.
Parameters:
Name Type Description
replay Object
Source:

displayReplayDetails()

Shows preview image, description and player text in the right panel.
Source:

displayReplayList()

Filter g_Replays, fill the GUI list with that data and show the description of the current replay.
Source:

DoesModificationApply()

Returns whether the given modification applies to the entity containing the given class list
Source:

draw()

Draw the structree (Actually resizes and changes visibility of elements, and populates text)
Source:

EndGameManager()

System component which regularly checks victory/defeat conditions and if they are satisfied then it marks the player as victorious/defeated.
Source:

EntityGroups()

EntityGroups class for managing grouped entities
Source:

EntityGroupsContainer()

EntityGroupsContainer class for managing grouped entities
Source:

EntitySelection()

EntitySelection class for managing the entity selection list and the primary selection
Source:

escapeQuotation(str) → {string}

Prepends a backslash to all quotation marks.
Parameters:
Name Type Description
str string
Source:
Returns:
Type
string

euclid_distance()

Euclidian distance between two points.
Source:

executeCheat(text) → {boolean}

Reads userinput from the chat and sends a simulation command in case it is a known cheat. Hence cheats won't be sent as chat over network.
Parameters:
Name Type Description
text string
Source:
Returns:
- True if a cheat was executed.
Type
boolean

executeNetworkCommand(input) → {Boolean}

Execute a command locally. Requires addChatMessage.
Parameters:
Name Type Description
input string
Source:
Returns:
whether a command was executed
Type
Boolean

fadeColorTick()

makes the color changes in a tick name: name of the object which color should be faded
Source:

fadeToGround()

Flattens the ground touching a terrain feature.
Source:

fetchTokens()

Fetch tokens from an entity's template
Source:
See:
Returns:
An array containing all tokens if found, else an empty array

fetchValue(templateName, keypath)

Fetch a value from an entity's template
Parameters:
Name Type Description
templateName The template to retreive the value from
keypath
Source:
Returns:
The content requested at the key-path defined, or a blank array if not found

filterGame(game) → {boolean}

Filter a game based on the status of the filter dropdowns.
Parameters:
Name Type Description
game Object
Source:
Returns:
- True if game should not be displayed.
Type
boolean

filterReplay() → {bool}

Decides whether the replay should be listed.
Source:
Returns:
- true if replay should be visible
Type
bool

filterReplays()

Initializes g_ReplaysFiltered with replays that are not filtered out and sort it.
Source:

findClearLine()

Find a 45 degree line in a bounding box that does not intersect any terrain feature.
Source:

findCorners()

Returns the corners of a bounding box.
Source:

footprintRadius()

Returns the radius of a circle surrounding this entity's footprint.
Source:

formatBatchTrainingString()

Format batch training string for the tooltip Examples: buildingsCountToTrainFullBatch = 1, fullBatchSize = 5, remainderBatch = 0: "Shift-click to train 5" buildingsCountToTrainFullBatch = 2, fullBatchSize = 5, remainderBatch = 0: "Shift-click to train 10 (2*5)" buildingsCountToTrainFullBatch = 1, fullBatchSize = 15, remainderBatch = 12: "Shift-click to train 27 (15 + 12)"
Source:

formatLimitString()

Format entity count/limit message for the tooltip
Source:

getAngle()

Returns the angle of the vector between point 1 and point 2. The angle is counterclockwise from the positive x axis.
Source:

getCheatsData() → {Object}

Loads all known cheat commands.
Source:
Returns:
Type
Object

getCostComponentDisplayName()

Translates a cost component identifier as they are used internally (e.g. "population", "food", etc.) to proper display names.
Source:

getDisconnectReason()

Must be kept in sync with source/network/NetHost.h
Source:

getDistance()

Returns the distance between 2 points
Source:

getEntityCostComponentsTooltipString()

Helper function for getEntityCostTooltip.
Source:

getEntityCostTooltip()

Returns the cost information to display in the specified entity's construction button tooltip.
Source:

getEntityOrHolder()

Returns the entity itself except when garrisoned where it returns its garrisonHolder
Source:

getGatherRates()

Calculates gather rates. All available rates that have a value greater than 0 are summed and averaged
Source:

getGradient()

Returns the gradient of the line between point 1 and 2 in the form dz/dx
Source:

GetIdentityClasses()

Gets an array of all classes for this identity template
Source:

getInitColorFadeRGB()

returns the init RGB color setting
Source:

getLocalizedResourceAmounts()

Format resource amounts to proper english and translate (for example: "200 food, 100 wood, and 300 metal").
Source:

getMetadata()

Returns extra data that the AI scripts have associated with this entity, for arbitrary local annotations. (This data should not be shared with any other AI scripts.)
Source:

getNeededResourcesTooltip()

Returns a message with the amount of each resource needed to create an entity.
Source:

getNetworkWarnings()

Colorizes and concatenates all network warnings. Returns text and textWidth.
Source:

getPlayerColor(playername)

Generate a (mostly) unique color for this player based on their name. See http://stackoverflow.com/questions/3426404/create-a-hexadecimal-colour-based-on-a-string-with-jquery-javascript
Parameters:
Name Type Description
playername string
Source:

getPlayerTileCoordinates()

Returns starting position in tile coordinates for the given player.
Source:

getPopulationBonusTooltip()

Returns the population bonus information to display in the specified entity's construction button tooltip.
Source:

getPositionOffset()

Calculate row position offset (accounting for different number of prod rows per phase).
Source:

getRandomDeviation()

Returns a number within a random deviation of a base number.
Source:

getReplayDateTime()

Returns a human-readable version of the replay date.
Source:

getReplayDuration() → {string}

Returns a human-readable version of the time when the replay started.
Source:
Returns:
Type
string

getReplayMapName() → {string}

Returns the name of the map of the given replay.
Source:
Returns:
Type
string

getReplayMonth() → {string}

Returns the month of the given replay in the format "yyyy-MM".
Source:
Returns:
Type
string

getReplayPlayernames() → {string}

Returns a human-readable list of the playernames of that replay.
Source:
Returns:
Type
string

getReplayTeamText() → {string}

Returns a description of the player assignments. Including civs, teams, AI settings and player colors. If the spoiler-checkbox is checked, it also shows defeated players.
Source:
Returns:
Type
string

getTeams()

Return an array where each element is an array of playerIndices of a team.
Source:

GetTechModifiedProperty()

Returns modified property value if at least one tech modification is found applicable to the given entity template; else, returns its original value. currentTechModifications: mapping of property names to modification arrays, retrieved from the intended player's TechnologyManager. entityTemplateData: raw entity template object. propertyName: name of the tech modification to apply. propertyValue: original value of property to be modified.
Source:

GetTechnologyDataHelper(template, civ)

Get information about a technology template.
Parameters:
Name Type Description
template A valid template as obtained by loading the tech JSON file.
civ Civilization for which the specific name should be returned.
Source:

GetTemplateData()

This is needed because getEntityCostTooltip in tooltip.js needs to get the template data of the different wallSet pieces. In the session this function does some caching, but here we do that in loadTemplate already.
Source:

GetTemplateDataHelper(template, player)

Get information about a template with or without technology modifications.
Parameters:
Name Type Description
template A valid template as returned by the template loader.
player An optional player id to get the technology modifications of properties.
Source:

getTradingTooltip()

Returns a message with the details of the trade gain.
Source:

getUsernameList() → {string}

Get a colorized list of usernames sorted by player slot, observers last. Requires g_PlayerAssignments and colorizePlayernameByGUID.
Source:
Returns:
Type
string

GetVisibleIdentityClasses()

Gets an array with all classes for this identity template that should be shown in the GUI
Source:

getWallPieceTooltip()

Returns an array of strings for a set of wall pieces. If the pieces share resource type requirements, output will be of the form '10 to 30 Stone', otherwise output will be, e.g. '10 Stone, 20 Stone, 30 Stone'.
Source:

greyout()

Adds grey font if replay is not compatible.
Source:

handleGamesetupMessage(message)

Called whenever the host changed any setting.
Parameters:
Name Type Description
message Object
Source:

handleGamestartMessage(message)

Called after every player is ready and the host decided to finally start the game.
Parameters:
Name Type Description
message Object
Source:

handleNetMessage(msg)

Processes a CNetMessage (see NetMessage.h, NetMessages.h) sent by the CNetServer. Saves the received object to mainlog.html.
Parameters:
Name Type Description
msg Object
Source:

handleNetStatusMessage(message)

Called when the client disconnects. The other cases from NetClient should never occur in the gamesetup.
Parameters:
Name Type Description
message Object
Source:

handleNetStatusMessage(message)

Parameters:
Name Type Description
message Object
Source:

handleNotifications()

Processes all pending notifications sent from the GUIInterface simulation component.
Source:

handlePlayerAssignmentMessage(message)

Called whenever a client joins/leaves or any gamesetting is changed.
Parameters:
Name Type Description
message Object
Source:

handleReadyMessage(message)

Called whenever a client clicks on ready (or not ready).
Parameters:
Name Type Description
message Object
Source:

handleSpecialCommand(text) → {boolean}

Handle all '/' commands.
Parameters:
Name Type Description
text string Text to be checked for commands.
Source:
Returns:
true if more text processing is needed, false otherwise.
Type
boolean

hasSameEngineVersion()

Check the version compatibility between the saved game to be loaded and the engine
Source:

hasSameMods(metadata, engineInfo) → {boolean}

Check the mod compatibility between the saved game to be loaded and the engine
Parameters:
Name Type Description
metadata Array.<string>
engineInfo Array.<string>
Source:
Returns:
Type
boolean

hasSameSavegameVersion()

Check the version compatibility between the saved game to be loaded and the engine
Source:

heading(string, size) → {string}

Set heading font - bold and mixed caps
Parameters:
Name Type Description
string string
size number Font size
Source:
Returns:
Type
string

hideControl(control, label, allowControlopt)

Hides the GUI controls for clients and shows the read-only label instead.
Parameters:
Name Type Attributes Description
control string name of the GUI object able to change a setting
label string name of the GUI object displaying a setting
allowControl boolean <optional>
Whether the current user is allowed to change the control.
Source:

hideControls()

If we're a network client, hide the controls and show the text instead.
Source:

hostGame()

Open the dialog box to enter the game name.
Source:

hslToRgb(h, s, l) → {Array}

Convert color value from HSL to RGB space.
Parameters:
Name Type Description
h number hueness
s number saturation
l number lightness
Source:
See:
Returns:
Type
Array

init(attribs)

Initializes some globals without touching the GUI.
Parameters:
Name Type Description
attribs Object context data sent by the lobby / mainmenu
Source:

init(attribs)

Called after the XmppConnection succeeded and when returning from a game.
Parameters:
Name Type Description
attribs Object
Source:

init()

Initialize the dropdown containing all the available civs.
Source:

init()

Initializes globals, loads replays and displays the list.
Source:

initBiome()

Get biome-specific names of entities and terrain after randomization.
Source:

initCivNameList()

Initialize the dropdowns containing all selectable civs (including random).
Source:

initDateFilter()

Allow to filter by month. Uses g_Replays.
Source:

initDurationFilter()

Allow to filter by game duration. Uses g_DurationFilterIntervals.
Source:

initFilters()

Reloads the selectable values in the filters. The filters depend on g_Settings and g_Replays (including its derivatives g_MapSizes, g_MapNames).
Source:

initGUIObjects()

Called after the first tick.
Source:

initMapNameFilter()

Allow to filter by mapname. Uses g_MapNames.
Source:

initMapNameList()

Initialize the dropdown containing all maps for the selected maptype and mapfilter.
Source:

initMapSettings()

Creates an object of commonly used functions.
Source:

initMapSizeFilter()

Allow to filter by mapsize. Uses g_MapSizes.
Source:

initMultiplayerSettings()

Hide and set some elements depending on whether we play single- or multiplayer.
Source:

initPlayerAssignments()

Populate team-, color- and civ-dropdowns.
Source:

initPopCapFilter()

Allow to filter by population capacity.
Source:

initRadioButtons()

Assign update-functions to all checkboxes.
Source:

initTileClasses(newClasses) → {Object}

Creates tileClass for the default classes and every class given.
Parameters:
Name Type Description
newClasses Array
Source:
Returns:
- maps from classname to ID
Type
Object

ircFormat(msg) → {string}

Format text in an IRC-like way.
Parameters:
Name Type Description
msg Object Received chat message.
Source:
Returns:
- Formatted text.
Type
string

ircSplit(string) → {Array}

Splits given input into command and argument.
Parameters:
Name Type Description
string string
Source:
Returns:
Type
Array

isColorFadeRunning()

checks, if a color fade on that object is running name: name of the object which color fade should be checked return: true a running fade was found
Source:

isNegativeZero()

Tests for consistent and correct math results
Source:

IsOwnedByAllyOfEntity()

Returns true if the entity 'target' is owned by an ally of the owner of 'entity'.
Source:

IsOwnedByAllyOfPlayer()

Returns true if the entity 'target' is owned by an ally of player
Source:

IsOwnedByEnemyOfPlayer()

Returns true if the entity 'target' is owned by an enemy of player
Source:

IsOwnedByGaia()

Returns true if the entity 'target' is owned by gaia (player 0)
Source:

IsOwnedByMutualAllyOfEntity()

Returns true if the entity 'target' is owned by a mutual ally of the owner of 'entity'.
Source:

IsOwnedByMutualAllyOfPlayer()

Returns true if the entity 'target' is owned by a mutual ally of player
Source:

IsOwnedByNeutralOfPlayer()

Returns true if the entity 'target' is owned by someone neutral to player
Source:

IsOwnedByPlayer()

Returns true if the entity 'target' is owned by player
Source:

isPlayerObserver()

Returns true if the player with that ID is in observermode.
Source:

isReplayCompatible()

True if we can start the given replay with the currently loaded mods.
Source:

isSpam(text, from) → {boolean}

Check if a message is spam.
Parameters:
Name Type Description
text string Body of message.
from string Sender of message.
Source:
Returns:
- True if message should be blocked.
Type
boolean

isUnhuntable()

Returns whether this is an animal that is too difficult to hunt. (Any non domestic currently.)
Source:

joinButton()

Immediately rejoin and join gamesetups. Otherwise confirm late-observer join attempt.
Source:

joinSelectedGame()

Attempt to join the selected game without asking for confirmation.
Source:

leaveGame(willRejoin)

Leave the game
Parameters:
Name Type Description
willRejoin If player is going to be rejoining a networked game.
Source:

loadAIDescriptions() → {Array}

Loads the descriptions as defined in simulation/ai/.../data.json and loaded by ICmpAIManager.cpp.
Source:
Returns:
Type
Array

loadAIDifficulties() → {Array}

Hardcoded, as modding is not supported without major changes. Notice the AI code parses the difficulty level by the index, not by name.
Source:
Returns:
Type
Array

loadCeasefire() → {Array|undefined}

Loads available ceasefire settings.
Source:
Returns:
Type
Array | undefined

loadCivData(selectableOnly)

Loads history and some gameplay data for civs.
Parameters:
Name Type Default Description
selectableOnly boolean false Only load those which can be selected in the gamesetup. Scenario maps might set non-selectable civs.
Source:

loadMapTypes() → {Array}

Hardcoded, as modding is not supported without major changes.
Source:
Returns:
Type
Array

loadPersistMatchSettings()

Sets the gameattributes the way they were the last time the user left the gamesetup.
Source:

loadPlayerDefaults() → {Array|undefined}

Loads the default player settings (like civs and colors).
Source:
Returns:
Type
Array | undefined

LoadPlayerSettings()

Used to create player entities prior to reading the rest of a map, all other initialization must be done after loading map (terrain/entities). DO NOT use other components here, as they may fail unpredictably. settings is the object containing settings for this map. newPlayers if true will remove old player entities or add new ones until the new number of player entities is obtained (used when loading a map or when Atlas changes the number of players).
Source:

loadPopulationCapacities() → {Array|undefined}

Loads available population capacities.
Source:
Returns:
Type
Array | undefined

loadReplays()

Store the list of replays loaded in C++ in g_Replays. Check timestamp and compatibility and extract g_Playernames, g_MapNames
Source:

loadSettingsValues() → {Object|undefined}

Loads and translates all values of all settings which can be configured by dropdowns in the gamesetup.
Source:
Returns:
Type
Object | undefined

loadSettingValuesFile(filename) → {Array|undefined}

Returns an array of objects reflecting all possible values for a given setting.
Parameters:
Name Type Description
filename string
Source:
See:
  • simulation/data/settings/
Returns:
Type
Array | undefined

loadVictoryConditions() → {Array|undefined}

Loads available gametypes.
Source:
Returns:
Type
Array | undefined

MatchesClassList(classes, match)

Check if the classes given in the identity template match a list of classes
Parameters:
Name Type Description
classes List of the classes to check against
match Either a string in the form "Class1 Class2+Class3" where spaces are handled as OR and '+'-signs as AND, and ! is handled as NOT, thus Class1+!Class2 = Class1 AND NOT Class2 Or a list in the form [["Class1"], ["Class2", "Class3"]] where the outer list is combined as OR, and the inner lists are AND-ed Or a hybrid format containing a list of strings, where the list is combined as OR, and the strings are split by space and '+' and AND-ed
Source:
Returns:
undefined if there are no classes or no match object true if the the logical combination in the match object matches the classes false otherwise

matchUsername()

Returns the guid of the user with the longest name that is a prefix of the given string.
Source:

multiplyEntityCosts()

Multiplies the costs for a template by a given batch size.
Source:

nextToFeature()

Determines if a point in a bounding box array is next to a terrain feature.
Source:

obstructionRadius()

Returns the radius of a circle surrounding this entity's obstruction shape, or undefined if no obstruction.
Source:

onTick()

Processes GUI messages sent by the XmppClient.
Source:

onTick()

Called every frame.
Source:

openDialog()

Unused multiplayer-dialog.
Source:

paintClass()

Create a painter for the given class
Source:

parseChatAddressee(msg)

Checks if the current user is an addressee of the chatmessage sent by another player. Sets the context of that message. Returns true if the message should be displayed.
Parameters:
Name Type Description
msg Object
Source:

pauseGame()

Pause the game in single player mode.
Source:

pickAmount()

Converts "amount" terms to numbers.
Source:

pickMix()

Converts "mix" terms to numbers.
Source:

pickSize()

Converts "size" terms to numbers.
Source:

placeLine(playerIDs, distance, groupedDistance) → {Array}

Place teams in a line-pattern.
Parameters:
Name Type Description
playerIDs Array typically randomized indices of players of a single team
distance number radial distance from the center of the map
groupedDistance number distance between players
Source:
Returns:
- contains id, angle, x, z for every player
Type
Array

placeRadial(distance)

Place players in a circle-pattern.
Parameters:
Name Type Description
distance number radial distance from the center of the map
Source:

placeRandom()

Chose arbitrary starting locations.
Source:

placeStronghold(distance, groupedDistance)

Place given players in a stronghold-pattern.
Parameters:
Name Type Description
distance radial distance from the center of the map
groupedDistance distance between neighboring players
Source:

PlaySound(name)

Simple wrapper function for playing sounds that are associated with entities
Parameters:
Name Type Description
name Typically one of 'walk', 'run', 'attack', 'death', 'build', 'gather_fruit', 'gather_grain', 'gather_wood', 'gather_stone', 'gather_metal'
Source:

predraw()

Positions certain elements that only need to be positioned once (as does not reposition automatically). Also detects limits on what the GUI can display by iterating through the set elements of the GUI. These limits are then used by draw().
Source:

PreInitGame()

Called when the map has been loaded, but before the simulation has started. Only called when a new game is started, not when loading a saved game.
Source:

prepareForDropdown(settingValues) → {Object|undefined}

Creates an object with all values of that property of the given setting and finds the index of the default value. This allows easy copying of setting values to dropdown lists.
Parameters:
Name Type Description
settingValues Array
Source:
Returns:
Type
Object | undefined

QueryBuilderListInterface()

Similar to Engine.QueryInterface, but checks for all interfaces implementing a builder list (currently Foundation and Repairable) TODO Foundation and Repairable could both implement a BuilderList component
Source:

QueryMiragedInterface()

Similar to Engine.QueryInterface but first checks if the entity mirages the interface.
Source:

QueryOwnerInterface()

Similar to Engine.QueryInterface but applies to the player entity that owns the given entity. iid is typically IID_Player.
Source:

QueryPlayerIDInterface()

Similar to Engine.QueryInterface but applies to the player entity with the given ID number. iid is typically IID_Player.
Source:

RandomInt()

Returns a random integer from min (inclusive) to max (exclusive)
Source:

randomizeBiome()

Randomizes environment, optionally excluding some biome IDs.
Source:

randomizePlacerCoordinates()

Helper function for randomly placing areas and groups on the map.
Source:

randomizePlacerCoordinatesFromAreas()

Helper function for randomly placing areas and groups in the given areas.
Source:

randomizePlayers() → {Array}

Mix player indices but sort by team.
Source:
Returns:
- every item is an array of player indices
Type
Array

randomStartingPositionPattern()

Chose a random pattern for placing the bases of the players.
Source:

reallyDeleteReplay(replayDirectory)

Attempts to delete the given replay directory from the disk.
Parameters:
Name Type Description
replayDirectory string
Source:

reallyStartGame()

This is a reserved function name that is executed by the engine when it is ready to start the game (i.e. loading progress has reached 100%).
Source:

reallyStartVisualReplay(replayDirectory)

Attempts the visual replay, regardless of the compatibility.
Parameters:
Name Type Description
replayDirectory string
Source:

recalculateStatusBarDisplay()

Toggles the display of status bars for all of the player's entities.
Source:

registerChanges()

Register changes of input (text and number) controls
Source:

removeBluff()

Remove the bluff class and turn it into a plateau.
Source:

removeFromClass()

Remove point from the given class by id
Source:

removeOldChatMessage()

Called when the timer has run out for the oldest chatmessage or when the message limit is reached.
Source:

replayHasSameEngineVersion()

True if we can start the given replay with the currently loaded mods.
Source:

reportDisconnect(reason)

Show the disconnect reason in a message box.
Parameters:
Name Type Description
reason number
Source:

reportGame()

Send a report on the gamestatus to the lobby.
Source:

resetTerrain()

Paints the entire map with a single tile type.
Source:

resignGame(leaveGameAfterResign)

Resign a player.
Parameters:
Name Type Description
leaveGameAfterResign If player is quitting after resignation.
Source:

resizeMoreOptionsWindow()

Sets the size of the more-options dialog.
Source:

resourcesToAlphaMask()

Returns a "color:255 0 0 Alpha" string based on how many resources are needed.
Source:

restartColorFade()

restarts a color fade see paramter in startColorFade function
Source:

retryPlacing()

Retries the given function with those arguments as often as specified.
Source:

rgbToGuiColor(color, alpha) → {string}

Concatenate integer color values to a string (for use in GUI objects)
Parameters:
Name Type Description
color Object
alpha number
Source:
Returns:
Type
string

rgbToHsl(r, g, b) → {Array}

Convert color value from RGB to HSL space.
Parameters:
Name Type Description
r number red
g number green
b number blue
Source:
See:
Returns:
Type
Array

sameColor(color1, color2) → {boolean}

True if the colors are identical.
Parameters:
Name Type Description
color1 Object
color2 Object
Source:
Returns:
Type
boolean

sanitizeGameAttributes()

We may encounter malformed replays.
Source:

selectCiv(code)

Updates the GUI after the user selected a civ from dropdown.
Parameters:
Name Type Description
code string
Source:

selectMapType(type)

Called when the user selects a map type from the list.
Parameters:
Name Type Description
type string scenario, skirmish or random
Source:

selectNumPlayers(num)

Called when the host choses the number of players on a random map.
Parameters:
Name Type Description
num Number
Source:

selectPanel(panelNumber)

Select active panel
Parameters:
Name Type Description
panelNumber Number of panel, which should get active state (integer)
Source:

selectPlayerColor()

Assigns the given color to that player.
Source:

selectViewPlayer()

Change perspective tool. Shown to observers or when enabling the developers option.
Source:

sendDialogAnswer()

Unused multiplayer-dialog.
Source:

sendRegisterGameStanza()

Send the relevant gamesettings to the lobbybot.
Source:

setGUIBoolean(control, label, checked)

Checks a boolean checkbox for the host and sets the text of the label for the client.
Parameters:
Name Type Description
control string name of the GUI object able to change a setting
label string name of the GUI object displaying a setting
checked boolean Whether the setting is active / enabled.
Source:

setMapDescription()

Sets an additional map label, map preview image and mapsettings description.
Source:

setMetadata()

Sets extra data to be associated with this entity.
Source:

setPanelObjectPosition()

Set the position of a panel object according to the index, from left to right, from top to bottom. Will wrap around to subsequent rows if the index is larger than rowLength.
Source:

setTeamChat()

If the teamchat hotkey was pressed, set allies or observers as addressees, otherwise send to everyone.
Source:

setupControl(option, prefix)

Setup the apropriate control for a given option.
Parameters:
Name Type Description
option Structure containing the data to setup an option.
prefix Prefix to use when accessing control, for example "generalSetting" when the tickbox name is generalSettingTickbox[i].
Source:

setupUnitPanel(guiName, unitEntState, payerState)

Helper function for updateUnitCommands; sets up "unit panels" (i.e. panels with rows of icons) for the currently selected unit.
Parameters:
Name Type Description
guiName Short identifier string of this panel. See g_SelectionPanels.
unitEntState Entity state of the selected unit with the lowest id.
payerState Player state
Source:

showReplaySummary()

Opens the summary screen of the given replay, if its data was found in that directory.
Source:

shuffleArray()

"Inside-out" implementation of Fisher-Yates shuffle
Source:

smoothElevation()

Finds the average elevation around a point.
Source:

SortEntitiesByPriority()

Returns entities ordered by decreasing priority Do not alter order when units have the same priority
Source:

sortGUIDsByPlayerID()

Sort GUIDs of connected users sorted by playerindex, observers last. Requires g_PlayerAssignments.
Source:

sortPlayers()

Sorts an array of player IDs by team index. Players without teams come first. Randomize order for players of the same team.
Source:

startColorFade()

starts fading a color of a GUI object using the sprite argument name: name of the object which color should be faded tickInterval: interval in ms when the next color change should be made duration: maximal duration of the complete fade (if 0 it runs until it is stopped) fun_colorTransform: function which transform the colors; arguments: [var data] restartAble [optional: if false, the fade can not be restarted; default: true fun_smoothRestart [optional]: a function, which returns a smooth tick counter, if the fade should be started; arguments: [var data]; must return false, if smooth restart was not possible and true, if it was ok
Source:

startReplay()

Starts the selected visual replay, or shows an error message in case of incompatibility.
Source:

stayClasses()

Create a stay constraint for the given classes by the given distances
Source:

stopColorFade()

stops fading a color name: name of the object which color fade should be stopped hideOverlay [optional]: hides the overlay, if true [default: true] return: true a running fade was stopped
Source:

subHeading(obj) → {string}

Returns a styled concatenation of Name, History and Description of the given object.
Parameters:
Name Type Description
obj Object
Source:
Returns:
Type
string

submitChatDirectly(text)

Send text as chat. Don't look for commands.
Parameters:
Name Type Description
text string
Source:

submitChatInput()

Loads the text from the GUI window, checks if it is a local command or cheat and executes it. Otherwise sends it as chat.
Source:

submitChatInput()

Executes a lobby command or sends GUI input directly as chat.
Source:

TechnologyTemplateManager()

System component which loads the technology data files
Source:

toggleChatWindow()

Opens chat-window or closes it and sends the userinput.
Source:

trainingQueue()

Returns the current training queue state, of the form [ { "id": 0, "template": "...", "count": 1, "progress": 0.5, "metadata": ... }, ... ]
Source:

translateAIDifficulty(index)

Returns title or placeholder.
Parameters:
Name Type Description
index Number index of AIDifficulties
Source:

translateAIName(aiName)

Returns title or placeholder.
Parameters:
Name Type Description
aiName string for example "petra"
Source:

translateMapSize(mapSize) → {string}

Returns title or placeholder "Default".
Parameters:
Name Type Description
mapSize Number tilecount
Source:
Returns:
Type
string

translateMapType(mapType) → {string}

Returns title or placeholder.
Parameters:
Name Type Description
mapType string for example "skirmish"
Source:
Returns:
Type
string

translatePopulationCapacity(population) → {string}

Returns title or placeholder.
Parameters:
Name Type Description
population Number for example 300
Source:
Returns:
Type
string

translateVictoryCondition(gameType) → {string}

Returns title or placeholder.
Parameters:
Name Type Description
gameType string for example "conquest"
Source:
Returns:
Type
string

unPaintClass()

Create a painter for the given class
Source:

unravelPhases(techs)

Unravel phases
Parameters:
Name Type Description
techs The current available store of techs
Source:
Returns:
List of phases

unreachableBluff() → {Number}

Determine if the endline of the bluff is within the tilemap.
Source:
Returns:
0 if the bluff is reachable, otherwise a positive number
Type
Number

updateDiplomacy()

Updates playerdata cache and refresh diplomacy panel.
Source:

updateGameAttributes()

Broadcast the changed settings to all clients and the lobbybot.
Source:

updateGameList()

Update the game listing from data cached in C++.
Source:

updateGameSelection()

Populate the game info area with information on the current game selection.
Source:

updateGUIObjects()

Don't set any attributes here, just show the changes in the GUI. Unless the mapsettings don't specify a property and the user didn't set it in g_GameAttributes previously.
Source:

updateGUIStatusBar()

updates a status bar on the GUI nameOfBar: name of the bar points: points to show maxPoints: max points direction: gets less from (right to left) 0; (top to bottom) 1; (left to right) 2; (bottom to top) 3;
Source:

updateLeaderboard()

Update the leaderboard from data cached in C++.
Source:

updatePlayerList()

Do a full update of the player listing, including ratings from cached C++ information.
Source:

updateProfile()

Update the profile of the selected player with data from the bot.
Source:

updateSpamMonitor(from)

Update the spam monitor.
Parameters:
Name Type Description
from string User to update.
Source:

updateSubject(newSubject)

Update the subject GUI object.
Parameters:
Name Type Description
newSubject string
Source:

updateTimeNotifications()

Displays all active counters (messages showing the remaining time) for wonder-victory, ceasefire etc.
Source:

updateTopPanel()

Sets civ icon for the currently viewed player. Hides most gui objects for observers.
Source:

updateUnitCommands(entState, supplementalDetailsPanel, commandsPanel, selection)

Updates the selection panels where buttons are supposed to depend on the context. Runs in the main session loop via updateSelectionDetails(). Delegates to setupUnitPanel to set up individual subpanels, appropriately activated depending on the selected unit's state.
Parameters:
Name Type Description
entState Entity state of the selected unit with the lowest id.
supplementalDetailsPanel Reference to the "supplementalSelectionDetails" GUI Object
commandsPanel Reference to the "commandsPanel" GUI Object
selection Array of currently selected entity IDs.
Source: