MG/Scripted Scenarios Beta

Lua is the scripting language used in MegaGlest's scenarios. It allows scenarios to expand and do things not normally possible in regular games of Glest.

Lua/XML Intermixture Problem
Due to XML's nature of using angle brackets for elements the parser will get confused and give an error if you try to use the left angle bracket in the scenario's XML file.

A solution is to either swap the logic:

ie. if you wanted, a &lt;= b you would have to do, b &gt;= a

Or use an external lua file as mentioned in the next section.

Loading a Lua File
To run Lua code in an external file you use the dofile function and provide the file path from the executable.

Example:

dofile("gae_scenarios/Tutorials/basic_tutorial/startup.lua")

Language System
Each scenario is stored in its own folder. In this folder should be an xml file of the same name as the folder with xml as the extension. Glest also looks for a lng file (scenario_name_english.lng as default) to allow for translations of text.

Example
In advanced_tutorial.xml is : showMessage('MagicBrief', 'GlestAdvancedTutorial')

In advanced_tutorial_english.lng is : MagicBrief=You are in command of the Magic faction, which uses mages and summoned creatures to fight.

Coordinates
Coordinates are specified as an array of two elements, the 'x' coordinate in the first element, and the 'y' coordinate in the second.

The origin {0,0} is at the 'top left' (or north-west if you like) of the screen. A map's size is defined in 'Tiles', each of which is a block of 2x2 Cells. For technical reasons the last row &amp; column of Tiles are not valid. So a 64 * 64 map is (64-1)*2 = 126 Cells wide and high. The co-ordinates you supply in LUA are Cell coordinates, not Tile coordinates, and are 'zero indexed' (the first one is 0, the last is NumCells - 1).

eg. A 128 x 128 Map has 254 x 254 Cells. The northwest corner is {0,0} and the southeast corner is {253,253}.

When a function returns a 'Vec2i' you can access the individual co-ordinates by sub-scripting the array, myPos = someFunction x = myPos[1] y = myPos[2] When ever there is a parameter requiring positions of type Vec2i you can use the format {x,y} (where x and y are number values within the required range, as defined above) to select a position on the map. someFunction ( {x,y} ) Here 'x' and 'y' could be numbers, variables, or 'expressions'.

You can also pass a 'pre created' array to these functions, which may be useful for scripting advanced scenarios.

Faction Index and Players
You need to specify the players like: &lt;players&gt; &lt;player control="human" faction="tech" team="1"/&gt; &lt;player control="cpu" faction="magic" team="2"/&gt; &lt;player control="closed"/&gt; &lt;player control="closed"/&gt; &lt;/players&gt; The first player's factionIndex is 0. The second player's factionIndex is 1 and so on. There must be exactly 4 player tags.

Commands
WARNING: All of these functions return type void and should not be used as arguments for other functions.

showMessage ( text, header )
Displays a message box on the screen, that will have to be dismissed by the player.

Parameters: text - a string identifying the text from a language file header - a string identifying the title bar text from a language file

addConsoleText ( text )
Displays a message in the game console messages area. Will remain until the message timeout has elapsed.

Parameters: text - a string identifying the text from a language file

setDisplayText ( text )
Displays a message at the top of the 'playing area'. Will remain until dismissed with clearDisplayText or setDisplayText is called again.

Parameters: text - a string identifying the text from a language file

clearDisplayText
Clears the message from the top of the playing area, previously set with setDisplayText.

setCameraPosition ( pos )
Move the camera to the coordinates of pos.

Parameters: pos - an array of two elements, specifying the co-ordinates {x,y}

createUnit ( unit, faction, pos )
Spawns a unit. If pos is occupied a nearby cell will be chosen. The game attempts to keep a 2 cell 'border' between the new unit and other units or objects (ie. trees). Warning: If a position can not be found, the game crashes.

Parameters: unit - name of a unit in the loaded factions. faction - the index of the faction this unit will belong to. pos - an array of two elements, specifying the co-ordinates {x,y}

destroyUnit ( unitId )
Destroys a unit.

Parameters: unitId - the id of the unit to destroy

morphToUnit ( unitId, morphName, ignoreRequirements )
Morphs a unit into another unit of type morphName. If ignoreRequirements is set to 1 then the morph is executed even if the unit does not satisfy the morph requirements.

Parameters: unitId - the id of a unit. morphName - the name of the morph to execute. ignoreRequirements - a 0 or 1 value indicating whether to respect morph requirements (0) or not (1)

moveToUnit ( unitId, destUnitId )
Move unitId to the location of destUnitId.

Parameters: unitId - the id of the unit to move (Starting location) destUnitId - the id of the unit to move to (Ending location of unitId). This would essentially make unitId 'follow' destUnitId until it arrives at the location of destUnitId.

giveAttackStoppedCommand ( unitId, valueName, ignoreRequirements )
Executes the attack stopped command for a unit specified by 'valueName'. If ignoreRequirements is set to 1 then the command is executed even if the unit does not satisfy the command requirements.

Parameters: unitId - the id of a unit. valueName - the name of the attack stopped command to execute. ignoreRequirements - a 0 or 1 value indicating whether to respect command requirements (0) or not (1)

giveResource ( resource, faction, amount )
Give an amount of a specified resource to a player, negative values are valid and have the obvious effect. Parameters: resource - a corresponding resource in the tech tree faction - the index of the faction to give the resource amount - the amount of resource the faction will receive

givePositionCommand ( unitId, command, pos )
Instruct a unit to carry out a command of type 'attack' or 'move'.

Parameters: unitId - the id of a unit that has an attack and/or move command. command - the type of command to carry out ('attack' or 'move') pos - an array of two elements, specifying the co-ordinates {x,y}

giveProductionCommand ( unitId, produced )
Instruct a unit to carry out a command of type 'produce'.

Parameters: unitId - the id of a unit that is to produce the new unit. produced - the type of unit to create. (ie. "worker")

giveUpgradeCommand ( unitId, upgrade )
Instruct a unit to carry out a command of type 'upgrade'.

Parameters: unitId - the id of the unit to perform the upgrade. upgrade - the type of upgrade to perform. (ie. "hell_gate")

setPlayerAsWinner ( faction )
Sets the player with index 'faction' as the winner, would typically be followed by endGame.

Parameters: faction - the index of the faction [0-3, Player1=0]

endGame
End the scenario, usually would be called after setPlayerAsWinner when victory conditions have been met.

displayFormattedText (const char *fmt,...)
Displays a message at the top of the 'playing area'. Will remain until dismissed with clearDisplayText or setDisplayText is called again.

Parameters: fmt - a string identifying the format of text (like in printf) ... - variable parameter list to pass values to fmt (like in printf)

displayFormattedLangText (const char *fmt,...)
Displays a message at the top of the 'playing area'. Will remain until dismissed with clearDisplayText or setDisplayText is called again. It's like displayFormattedText besides the fact that displayFormattedLangText uses the language-file for resolving the format of the text.

Parameters: fmt - a string identifying the format of text (like in printf) ... - variable parameter list to pass values to fmt (like in printf)

enableAi ( int faction )
Enables a factions AI. All of the faction's units will move with this command.

Parameters: faction - the index of the faction [0-7, Player1=0]

disableAi ( int faction )
Disables a factions AI. None of the faction's units will move with this command.

Parameters: faction - the index of the faction [0-7, Player1=0]

bool getAiEnabled ( int faction )
Checks the enabled status of a factions AI.

Parameters: faction - the index of the faction [0-7, Player1=0]

enableConsume ( int faction )
Enables a factions requirement to consume resources like food. All of the faction's units will consume food type resources with this command.

Parameters: faction - the index of the faction [0-7, Player1=0]

disableConsume ( int faction )
Disbles a factions requirement to consume resources like food. All of the faction's units will not consume food type resources with this command.

Parameters: faction - the index of the faction [0-7, Player1=0]

bool getConsumeEnabled ( int faction )
Checks the consume status of a factions AI.

Parameters: faction - the index of the faction [0-7, Player1=0]

giveAttackCommand ( unitId, unitToAttackId )
Instruct a unit to carry out a command of type 'attack' on a specific unit.

Parameters: unitId - the id of a unit that has an attack and/or move command. unitId - the id of a unit that should be attacked.

playStaticSound ( soundFile )
Play a static sound file specified by 'soundFile'

Parameters: soundFile - the filename of the sound file to play (ogg or wav)

playStreamingSound ( soundFile )
Play a streaming sound file (background music) specified by 'soundFile'

Parameters: soundFile - the filename of the sound file to play (ogg or wav)

stopStreamingSound ( soundFile )
Stop playing a streaming sound file (background music) specified by 'soundFile'

Parameters: soundFile - the filename of the sound file to play (ogg or wav)

stopAllSound
Stop playing all sounds

togglePauseGame ( pauseStatus )
Toggle the pause state of the existing game.

Parameters: pauseStatus - 0 indicates normal game play, 1 indicates a paused game

int registerCellTriggerEventForUnitToUnit ( sourceUnitId, destUnitId )
Register a cell 'trigger' event. Any time sourceUnit comes next to destUnit the eventID returned by this function will be triggered

inside an event called ''

Parameters: sourceUnitId - the id of a unit moves next to destUnit. destUnitId - the id of a unit that source moves next to.

example: unitA = 'guard' unitB = 'castle' createUnit(unitB, 1, startLocation(2)) castleUnit= lastCreatedUnit createUnit(unitA, 0, startLocation(2)) guard= lastCreatedUnit cell_event1 = registerCellTriggerEventForUnitToUnit(guard,castleUnit)  if triggeredCellEventId == cell_event1 then clearDisplayText DisplayFormattedText('You captured the FLAG!') unregisterCellTriggerEvent(cell_event1) end 

int registerCellTriggerEventForUnitToLocation ( sourceUnitId, Vec2i pos )
Register a cell 'trigger' event. Any time sourceUnit comes into the cell co-ordinates specified by pos, the

event called '' is triggered using the eventid returned by this function

Parameters: sourceUnitId - the id of a unit moves next to destUnit. Vec2i pos - the x and y cell co-ordinates that will trigger the event when sourceUnitID enters the cell

int registerCellTriggerEventForFactionToUnit ( sourceFactionId, destUnitId )
Register a cell 'trigger' event. Any time a unit from sourceFaction comes next to destUnit the eventID returned by this function will be triggered

inside an event called ''

Parameters: sourceFactionId - the id of a faction who has at least one unit that moves next to destUnit. destUnitId - the id of a unit that source moves next to.

int registerCellTriggerEventForFactionToLocation ( sourceFactionId,Vec2i pos)
Register a cell 'trigger' event. Any time a unit from sourceFaction comes into the cell co-ordinates specified by pos, the

event called '' is triggered using the eventid returned by this function

Parameters: sourceFactionId - the id of a faction who has at least one unit that moves next to destUnit. Vec2i pos - the x and y cell co-ordinates that will trigger the event when a unit from sourceFactionID enters the cell

int getCellTriggerEventCount ( eventId)
Returns the number of times the event specified by eventId has been triggered.

Parameters:

eventId - the id of a previously registered event

unregisterCellTriggerEvent (eventId)
Unregister the event specified by eventId.

Parameters:

eventId - the id of a previously registered event

int startTimerEvent
Registers a timer and returns its unqiue Id, which can later be compared within a '' event.

example:  if triggeredTimerEventId == timer_event1 then if timerEventSecondsElapsed(triggeredTimerEventId) >= captureTheFlagSeconds then clearDisplayText DisplayFormattedText('Your time ran out of time to capture the FLAG!') stopTimerEvent(timer_event1) unregisterCellTriggerEvent(cell_event1) end end 

int resetTimerEvent ( eventId)
Reset the timer specified by eventId. This function also returns the number of seconds elapsed since the timer started.

Parameters:

eventId - the id of a previously registered timer

int stopTimerEvent ( eventId)
Stop the timer specified by eventId. This function also returns the number of seconds elapsed since the timer started.

Parameters:

eventId - the id of a previously registered timer

int timerEventSecondsElapsed ( eventId)
This function returns the number of seconds elapsed since the timer started.

Parameters:

eventId - the id of a previously registered timer

int triggeredCellEventId
This function returns the eventId that is currently triggering a ''

int triggeredTimerEventId
This function returns the eventId that is currently triggering a ''

Queries
These function return useful information that can be used in command functions.

Vec2i startLocation ( faction )
Returns the start location for a given faction.

Parameters: faction - the index of the faction [0-3, Player1=0]

Example: createUnit ( "someunit", 0, {startLocation(0)[1] + 5, startLocation(0)[2]} ) This would create a unit 5 cells east of startLocation 0.

Vec2i unitPosition ( unitId )
Returns the current location of a given unit.

Parameters:

unitId - the unitId of the unit whose position you wish to know.

Example: if ( unitPosition(myUnit)[1] &gt; 47 and 75 &gt; unitPosition(myUnit)[1] and unitPostion(myUnit)[2] &gt; 95 ) then -- The unit's x co-ord is between 47 and 75, and its y cord is larger than 95. -- trigger some action here ? end

int unitFaction ( unitId )
Returns the faction index of the unit with unitId.

int resourceAmount ( resource, faction )
Returns the amount of a given resource is possessed by a faction.

string lastCreatedUnitName
Returns the unit type of the last created unit.

int lastCreatedUnit
Returns the unit ID of the last created unit.

string lastDeadUnitName
Returns the type of the last unit to die.

int lastDeadUnit
Returns the ID of the last unit to die.

int unitCount ( faction )
Returns the number of units a given faction has.

int unitCountOfType ( faction, type )
Returns the number of units of a specific type a given faction has.

bool gameWon
Returns true if the human player won the game

Events
These are XML tags used to execute Lua code on its specified event. Variables can be used across different events.

&lt;startup&gt; [insert code]

&lt;startup&gt;

&lt;unitCreatedOfType type="unitname"&gt; [insert code] &lt;/unitCreatedOfType&gt;

&lt;unitDied&gt; [insert code] &lt;/unitDied&gt;

&lt;resourceHarvested&gt; [insert code] &lt;/resourceHarvested&gt;

&lt;gameOver&gt; [insert code] &lt;/gameOver&gt;

&lt;cellTriggerEvent&gt;

[insert code]

&lt;/cellTriggerEvent&gt;

&lt;timerTriggerEvent&gt;

[insert code]

&lt;/timerTriggerEvent&gt;