Battle Script Documentation
Battle Script
Creating a Battle Script
TEd does not automatically write a battle script, one must be created manually. The example battle contains a a sample script.
Battle scripts should live in one or more files with .lua extensions within the battle folder. A link to the first, main or starter script file (however your script is laid out) is made in the battle XML. For more information on this, see the Battle XML.docx file.
At a Glance
The battle object model is a LUA-script based system for controlling battles. First, an instance of empire_battle() is created:-
battle = empire_battle:new();
Use the alliances() collection to gain access to units & ships:-
alliances = battle:alliances();
The alliances object is the root object in a hierarchy (Alliances,Alliance,Armies,Army) that ultimately yields the list of units & ships for a given Army. You can index into this list to get a reference to individual units, by ordinal or by name.
alliance_01 = alliances:item(1); -- get a handle to the first alliance
armies_01 = alliance_01:armies(); -- get the armies collection from this alliance
army_01 = armies_01:item(1); -- get the first army within this collection
units_01 = army_01:units(); -- get the collection of units from this army
unit_01 = units_01:item(1); -- get the first unit from this collection
Various methods can be used on a ship or unit object to query it's current state (e.g. position in the world, number of men alive etc.)
if unit_01:number_of_men_alive() == 0 then
unit_01_has_died();
end;
Issue commands to one or more units by creating a unitcontroller object on the army, adding the unit(s) to the controller, and calling command methods on the controller:-
uc_01 = army_01:create_unit_controller();
uc_01:add_units(unit_01);
uc_01:halt();
Ships and shipcontrollers are used in place of units and unitcontrollers in naval battles:-
alliance_01 = alliances:item(1);
armies_01 = alliance_01:armies();
army_01 = armies_01:item(1);
ships_01 = army_01:ships(); -- get ships() instead of units()
ship_01 = ships_01:item(1);
sc_01 = army_01:create_ship_controller(); -- create_ship_controller instead of unit
sc_01:add_ships(ship_01);
sc_01:rotate(90); -- order the ship to spin on the spot
Debug text can be printed to the lua logfile by using battle:print():-
battle:print("This will appear in %appdata%\The Creative Assembly\Shogun2\logs\lua.log");
Script functions can be triggered in the future by calling battle:register_singleshot_timer():-
battle:register_singleshot_timer("test_function", 5000);
function test_function()
battle:print("This will happen in 5000ms …");
end;
They can also be repeatedly called by using battle:register_repeating_timer():-
battle:register_repeating_timer("test_repeat_function", 5000);
function test_repeat_function()
battle:print("This will happen EVERY 5000ms …");
end;
Positions on the battlefield can be declared with battle_vector:new(), and then set to a co-ordinate using set();
pos_test = battle_vector:new();
Pos_test:set(234, 0, -392);
Script API
Clearing cached files
If the script pulls in script files externally, it may be beneficial to clear these out before referencing them again at the start of the script:-
system.ClearRequiredFiles();
This probably isn't necessary for simple scripts that live in one file.
empire_battle
The empire_battle object is the root object for accessing (nearly) all other objects. In order to use it you must first create an instance of this object:-
battle = empire_battle:new();
This creates a new instance of the empire_battle object, and assigns it to the global LUA variable named battle. Nearly all subsequent object model access then occurs via this object.
Methods:
nil print(String str)
outputs the string to the lua log file.
random_number
number random_number()
Returns a random floating point number in the range 0 to 1.
modify_battle_speed
nil modify_battle_speed(Number speed)
Adjusts the games speed pause = 0.0, slow = 0.4, play = 1.0, fwd = 2.0, ffwd = 4.0.
NOTE: using this within a timer event may produce undesirable results, due to them being updated at the battle speed
restore_battle_speed
nil restore_battle_speed()
restores the battle speed to the speed previously stored when modify_battle_speed() was called.
change_conflict_time_update_overridden
nil change_conflict_time_update_overridden(bool overridden)
call with overridden = true to stop the timer countdown towards victory; call with overridden = false to leave the clock counting down like normal. Useful if a cutscene is playing where the battle time should not count down.
change_victory_countdown_limit
nil change_victory_countdown_limit(Number time)
call with time < 0 to make it infinite. Call with time >= 0 to set the countdown time. This is in seconds. This sets the countdown period from the point the game thinks the battle has been won to the appearance of the battle results screen, which is useful if an outro is required.
suspend_contextual_advice
nil suspend_contextual_advice(bool suspend)
Call with suspend=true to suppress contextual advisor message, call with suspend = false to enable contextual advisor messages
show_advisor_message
nil show_advisor_message(String localization_key, String default_message)
Outputs text to the in-game Advisor window UI. For user-created battles only un-localized text is supported.
Example:-
battle:show_advisor_message(“”, “Help help I’m being repressed”);
close_advisor
nil close_advisor()
Dismisses the currently displayed advice.
nil place_naval_mine(Vector)
Place a naval mine at the specified position; which will be on the surface of the sea
alliances
Alliances alliances()
Returns an Alliances object, which is the root of the unit/ship hierarchy.
buildings
Buildings buildings()
Returns a Buildings object, which is a collection of all buildings in the scene.
camera
Camera camera()
Returns a Camera object, which can be used to control the camera.
register_battle_phase_handler
nil register_battle_phase_handler(String handler_name)
Registers the function named handler_name as the name of the script function that will handle battle phase changes. This is used to start the main body of the script when the battle starts (as opposed to when the battle/script loads).
The function is called with an event object as its argument. The get_name() method on this object will return the name of the battle phase. Phase changes are:
Event name |
Description |
Startup |
This event is fired once after the script is loaded. All inline script commands will have been executed. This event may fire after any timers that were registered with inline script. |
Deployment |
This event is fired at the start of the Deployment phase. Note that if you have disabled deployment in your battle XML, you will not receive this event. |
Deployed |
This event is fired when deployment has been completed. For battles that have an explicit deployment phase, this event is fired when the player hits the start battle UI button. For battles that skip deployment, this event is fired shortly after the “Startup” phase change event is received. |
VictoryCountdown |
Battle is complete, and victor has been decided; there is a time that will pass before actually finishing the battle. |
Complete |
Battle is complete, this is the last event that a script will receive on completion of the battle. |
An example of all this is given here:-
--phase change handler function
function handle_phase_change(event)
--any function registered as the phase change handler will be passed
--an event as a single parameter, which it can then inspect as follows
if event:get_name == "Deployment" then
entering_deployment() --we have entered "deployment" phase
elseif event:get_name == "Deployed" then
entering_battle(); --we have entered "deployed" phase (battle start)
end;
end;
--register the function above as the phase change handler
battle:register_battle_phase_handler("handle_phase_change");
function entering_deployment()
battle:out("Entering deployment phase!");
end;
function entering_battle()
battle:out("Battle has started!");
end;
unregister_battle_phase_handler
nil unregister_battle_phase_handler()
Unregisters the current battle phase handler, the currently registered function will no longer be called.
register_singleshot_timer
nil register_singleshot_timer(String handler_name, [opt]Number ms_interval)
Registers the function named handler_name as a single shot timer handler. The function will be called once ms_interval milliseconds after the function is registered (actual time may be >= ms_interval). The default interval, if none is provided, is 1000ms (1 second).
The handler function should be declared with one arg, which is the elapsed game time, in milliseconds (scripts generally don't need to refer to this arg).
The handler is called once, when the interval expires.
The function is automatically unregistered prior to calling the handler function.
The handler should be declared as follows:
function my_timer_handler()
-- do stuff
end
battle:register_singleshot_timer("my_timer_handler", 5000); --call my fn in 5 seconds
The function must be declared in the source code before the call to register_singleshot_timer(), otherwise a script error will be raised.
register_repeating_timer
nil register_repeating_timer(String handler_name, [opt] Number ms_interval)
Registers the function named handler_name as a timer handler. The function will be called repeatedly every ms_interval milliseconds after the function is registered (actual time may be >= ms_interval). The default interval, if none is provided, is 1000ms (1 second).
The handler function should be declared with one arg, which is the elapsed game time, in milliseconds (scripts generally don't need to refer to this arg).
The handler is called repeatedly, until the timer is unregistered.
Example, declare a repeating handler and unregister it after five calls.
num_calls = 0
function my_timer_handler(game_time)
num_calls = num_calls + 1
if numcalls == 5 then
unregister_timer(“my_timer_handler”)
end
end
battle:register_repeating_timer("my_timer_handler", 2000); -- call my fn every 2 seconds
The function must be declared in the source code before the call to register_singleshot_timer(), otherwise a script error will be raised.
unregister_timer
nil unregister_timer(String handler_name)
Unregisters the specified timer handler, the currently registered function will no longer be called. This can be used to unregister both singleshot and repeating timers. In the case of singleshot timers, it is only legal to remove them before they have been called, calling unregister_timer on a singleshot timer after the handler function has been called will raise a script error.
steal_escape_key
nil steal_escape_key()
Steals the escape key from the UI to allow lua scripts to detect and process key presses.
Escape key maps directly to a function called “Esc_Key_Pressed()” which you will need to implement in your lua files. Note: you must call release_escape_key when you are finished with it in order for the UI to retain its functionality.
release_escape_key
nil release_escape_key()
Releases the escape key back to the UI.
steal_input_focus
nil steal_input_focus()
Allows script to capture all input received, effectively disabling the keyboard in game, input focus MUST be released after it is no longer required. Useful for cutscenes.
release_input_focus
nil release_input_focus()
Releases the input focus back to the UI.
enable_cinematic_ui
nil enable_cinematic_ui(bool cinematic_ui, bool cursor, bool borders)
Enables or disables the cinematic ui and related ui options, which is useful for cutscene creation. Set the first parameter to true to enable the cinematic ui - this makes the regular ui disappear (set to false to achieve the reverse). The second parameter controls the visibility of the cursor, true is visible and false is not.
The third parameter controls the visibility of cinematic borders at the top and bottom of the screen - again, true is visible and false is not.
Therefore, the following call will disable the regular UI in order to go into a cutscene:-
battle:enable_cinematic_ui(true, false, true);
This call re-enables the regular ui when coming out again:-
battle:enable_cinematic_ui(false, true, false);
game_time
Number game_time()
Returns the elapsed game time, in seconds. This is *not* real time, as the returned time incorporates any time multipliers due to the current game speed.
suppress_unit_voices
nil suppress_unit_voices(bool suppress)
Call with suppress=true to suppress unit voice over, suppress=false to resume unit voice over. Useful for cutscenes with spoken dialogue.
Alliances
This object is the root object of a hierarchy of objects that mirror the organization of the units & ships in the battle environment xml file.
The Alliances is a collection of Alliance objects.
count
Number count()
Retrieves the count of alliances in the alliance list.
item
Alliance item(Number n)
Retrieves the n'th Alliance object in the list of alliances, where n is a 1-based index. By convention item(1) is the friendly Alliance, and item(2) is the enemy Alliance.
Alliance
This object wraps a collection of armies for an alliance.
armies
Armies armies()
Returns an Armies object, which is collection of Army objects.
create_ai_unit_planner
AI_Unit_Planner create_ai_unit_planner()
Create an instance of an AI objective planner. These can be used to give general objectives to groups of units such as "defend this position" or "attack that unit".
Army
This object represents an individual Army.
units
Units units()
Returns a Units object, which is a list of all the units in the Army
get_reinforcement_units
Units get_reinforcement_units()
Returns a Units object, containing a list of any reinforcing units to this Army.
ships
Ships ships()
Returns a Ships object, which is a list of all the units in the Army.
get_reinforcement_ships
Ships get_reinforcement_ships()
Returns a Ships object, containing a list of any reinforcing units to this Army.
create_unit_controller
UnitController create_unit_controller()
Creates a new UnitController Object, which is used to issue commands to units.
create_ship_controller
ShipController create_ship_controller()
Creates a new ShipController Object, which is used to issue commands to ships.
is_commander_alive
Bool is_commander_alive()
Returns whether the commander of this army is still alive.
quit_battle
Bool quit_battle()
Instantly tell this army to quit the battle.
army_handicap
Number army_handicap()
Returns the handicap for the army, which is based on an enum list:-
Difficulty |
Value |
Easy |
1 |
Normal |
0 |
Hard |
-1 |
Very Hard |
-2 |
Units
There is a single unique Unit object for every unit in the battle.
The Units object is a collection of Unit objects. The collection can be queried by ordinal index, or by unit name.
count
Number count()
Retrieves the count of units in the units list.
item
Unit item(Number n)
Unit item(String unit_name)
If an integer parameter is given, this function retrieves the n'th Unit object in the list of units, where n is a 1-based index. If a string parameter is given the function looks up the unit by name, the name being given in the battle XML.
kill_commander
Nil kill_commander()
Kills the commanding entity of the current army.
Unit
Represents an individual unit.
name
String name()
Returns the name of the unit. If the unit has a script_name parameter in the battlefield def file, the return value will be the script_name. If the unit has no script_name attribute, the 1-based index of the unit in it's armies Units collection will be returned e.g. "1" for the first "10" for the 10th.
type
String type()
Returns the type of the unit, this corresponds to the unit_type element's type attribute in the battle xml file. e.g. "24_lber_howitzer" or "guard_infantry".
position
Vector position()
Returns a Vector object containing the position of the main body of soldiers in the unit.
ordered_width
float ordered_width()
Returns the width of the unit; if the unit is moving this will be the width the unit desires.
bearing
Number bearing()
Returns the bearing of the unit, in degrees, relative to North (bearing = 0)
is_moving
bool is_moving()
Returns true if the unit is moving, false otherwise.
is_moving_fast
bool is_moving_fast()
Returns true if the unit is moving fast (or routing), false otherwise.
is_idle
bool is_idle()
Returns true if the unit has finished their order and are not doing an interrupted action e.g. firing at will.
unit_in_range
bool unit_in_range(Unit unit)
Returns true if the enemy unit is in firing range of this unit. This method takes into account the firing arc, orientation etc. of the unit (using exactly the same logic as the AI)
initial_number_of_men
Number initial_number_of_men()
Returns the number of men initially in the unit.
number_of_men_alive
Number number_of_men_alive()
Returns the number of men alive in the unit.
unary_of_men_alive
Number unary_of_men_alive()
Returns the ratio of men alive in the unit, as a float (between 0 - 1).
number_of_enemies_killed
Number number_of_enemies_killed()
Returns the number of enemies this unit has killed.
kill_number_of_men
nil kill_number_of_men(Number amount_to_kill)
Kill off a number of men in the unit.
position_of_officer
Vector position_of_officer()
Returns a Vector object containing the position of the man in charge.
is_leaving_battle
bool is_leaving_battle()
Returns true if the unit is leaving the battlefield, false otherwise.
is_routing
bool is_routing()
Returns true if the unit is routing, false otherwise.
is_shattered
bool is_shattered()
Returns true if the unit is shattered, false otherwise.
is_valid_target
bool is_valid_target()
Returns true if the unit is valid to attack, false otherwise.
invalid = leaving or entering battlefield / hidden / dead
missile_range
Number missile_range()
Returns the distance, in game units (meters) for the range of the unit's currently selected missile.
unit_distance
Number unit_distance(Unit unit)
Returns the distance, in game units (meters) for distance between both units, taking into account the units bounding box and direction, in order to provide the shortest distance between units as opposed to just going off the centred positions.
ammo_left
Number ammo_left()
Returns the amount of ammo left for a particular unit.
starting_ammo
Number starting_ammo()
Returns the amount of ammo a particular unit started with.
set_current_ammo_unary
Nil set_current_ammo_unary(Number unary_amount)
Sets the amount of ammo left, relative to the unit's starting ammo. set_current_ammo_unary(1) would reset the units ammo to the starting amount.
is_cavalry
bool is_cavalry()
Returns true if the unit is a cavalry unit, false otherwise.
is_currently_garrisoned
bool is_currently_garrisoned()
Returns true if the unit is inside a building.
is_infantry
bool is_infantry()
Returns true if the unit is a infantry unit, false otherwise.
is_artillery
bool is_artillery()
Returns true if the unit is a artillery unit, false otherwise.
is_limbered_artillery
bool is_limbered_artillery()
Returns true if the artillery unit is limbered, false otherwise.
can_perform_special_ability
bool can_perform_special_ability(String ability)
Queries the unit to see if the special ability is in its capabilities.
current_special_ability
String current_special_ability()
Returns a string containing the units current special ability (if any).
deploy_reinforcement
nil deploy_reinforcement(bool manual)
If the unit is a reinforcement that is not yet deployed, setting this to false will prevent it from deploying until it is set to true again (keeping with the current constraints of units being drip fed into a battle), allowing you to be able to delay deployment of reinforcements.
Unitcontroller
A UnitController is a container for Unit objects that you want to control of i.e. issue commands to.
In order for a UnitController to issue commands it must take the unit's it controls out of AI control - to avoid conflicting control. The UnitController implicitly takes control of any units it controls prior to issuing a given command. You can explicitly take and release control (back to the AI) using methods on the UnitController (take_control() & release_control()).
A UnitController manages one or more unit groups and a list of individual units. Each group of units that the controller manages moves together - organising themselves into a specific formation. The individual units under control all move autonomously.
Theer are two 'flavours' of command for many of the commands - immediate execution or queued. Any command with the "_q" suffix e.g. "withdraw_q" is a queued variation of the command. Queuing commands is a way of setting up a sequence of actions to be taken - e.g. setting a series of way points.
add_group
nil add_group(<list>)
Adds one or more units to the controller as an independent group.
<list> is a list of units, either Unit object pointers, or the name of a unit (refer to Unit:name() for info on valid unit names) e.g.
-- get a reference to the friendly army
army = battle:alliances():item(1):armies():item(1);
units = army:units();
controller1 = army:create_unit_controller();
-- now add the first and second unit plus the unit named "generals_unit" as a group
-- these will move together in formation
controller1:add_group(units:item(1),units:item(2),units:item("generals_unit"));
-- now add the fourth & fifth units as individual units
controller:add_units(units:item(4), units:item(5))
add_units
nil add_units(<list>)
Adds one or more units to the controller as independent autonomous units.
take_control
nil take_control()
Takes script control of all units, removing them from AI control. take_control() is called internally prior to issuing any command - so all units in the controller will be under script control until explicitly removed.
release_control
nil release_control()
Returns control of units back to the AI. Note that the AI may, in some circumstances, appear behave strangely when they are returned to the AI, as the AI will start to provide orders based on it's own algorithms.
clear_all
nil clear_all()
Removes all units from the controller - units are still left under script control unless explicitly released with release_control()
halt
nil halt()
Issue the halt command immediately to controlled units. All units will come to a stand-still. Takes script control of all units.
withdraw
nil withdraw()
Issues the withdraw command immediately to all units, causing them to retreat. Takes script control of all units.
withdraw_q
nil withdraw_q()
Queues a withdraw command to all units, which will be processed after all currently queued commands have been executed. Otherwise identical to withdraw()
add_all_units
nil add_all_units()
Adds all units to the controller as a group.
fire_at_will
nil fire_at_will(bool fire_at_will)
Sets the fire-at-will status of all controlled units to true or false.
kill
nil kill()
Instantly kills all controlled units. Units will be rendered in thier dead pose.
attack_unit
nil attack_unit(Unit unitTarget, bool primary_attack, bool move_fast)
Instructs controlled units to immediately attack the target unit.
If primary_atatck is true, units will use their primary attack.
If move_fast is true, units will use fast move speed.
attack_unit_q
nil attack_unit_q(Unit unitTarget, bool primary_attack, bool move_fast)
Queues up an order to attack the target unit.
If primary_atatck is true, units will use their primary attack.
If move_fast is true, units will use fast move speed.
rotate
nil rotate(Number degrees, [optional] bool move_fast)
Order controlled units to rotate about their current heading by the number of degrees. The optional second arg controls whether they move fast, or not.
rotate_q
nil rotate_q(Number degrees, [optional] bool move_fast)
Queues an order for the controlled units to rotate about their current heading by the number of degrees. The optional second arg controls whether they move fast, or not.
step_forward
nil step_forward()
Orders controlled units to take a single step forward.
step_backward
nil step_backward()
Orders controlled units to take a single step backward.
change_move_speed
nil change_move_speed(bool move_fast)
Orders controlled units to move fast, or at regular speed.
increment_formation_width
nil increment_formation_width()
Orders controlled units to increase their formation width by one soldier.
decrement_formation_width
nil decrement_formation_width()
Orders controlled units to decrease their formation width by one soldier.
guard_mode
nil guard_mode()
Toggles guard mode on/off for controlled units.
change_formation
nil change_formation(String formation_name)
Instructs controlled units to adopt a new named formation.
change_formation_q
nil change_formation_q(String formation_name)
Queues an order to adopt a new formation.
perform_special_ability
nil perform_special_ability(String ability_name)
Orders units to perform a special ability.
Before issuing this command we check that all the special ability is legal for all controlled units. If the ability is not valid for any of the units, a script error results.
perform_special_ability_q
nil perform_special_ability_q(String ability_name)
Queues an order to perform a special ability.
change_shot_type
nil change_shot_type(String shot_type)
Orders units to change shot type.
Before issuing this command we check that all the shot typeis legal for all controlled units. If the shot type is not valid for any of the units, a script error results.
change_shot_type_q
nil change_shot_type_q(String shot_type)
Queues an order to perform change of shot_type.
skirmish
nil skirmish(bool on_off)
Orders units to go into skirmish mode, or not.
goto_location
nil goto_location(Vector vector, [optional] bool move_fast)
Orders units to move to a specified position. The optional move_fast arg controls the speed of the move.
goto_location_q
nil goto_location_q(Vector vector, [optional] bool move_fast)
Queues an order to move to a specified location.
attack_location
nil attack_location(Vector vector, [optional] bool move_fast)
Orders units to attack a specified position.
This command is intended for ranged missile units, such a cannons, to order them to shell a specific location.
attack_location_q
nil attack_location_q(Vector vector, [optional] bool move_fast)
Queues an order to attack a specified position.
occupy_zone
nil occupy_zone(Vector vector, bool move_fast)
Instructs units to occupy a zone near the location specified, if found. A battlefield zone is a defensible position, like a castle wall.
occupy_zone_q
nil occupy_zone_q(Vector vector, bool move_fast)
Instructs units to occupy a zone near the location specified, if found.
defend_building
nil defend_building(Building building,[optional] bool move_fast)
Orders units to defend the given building. The optional move_fast flag controls the speed that they move to the target building.
If the target building is not defensible, a script error is thrown.
defend_building_q
nil defend_building_q(Building building,[optional] bool move_fast)
Queues an order to defend the given building. The optional move_fast flag controls the speed that they move to the target building. If the target building is not defensible, a script error is thrown.
attack_building
nil attack_building(Building building, [optional] piece index, [optional] bool move_fast)
Instructs units to attack the given building. The optional piece index identifies the piece of the building to attack, as a 1-based index.
attack_building_q
nil attack_building_q(Building building, [optional] piece index, [optional] bool move_fast)
Queues an order to attack the given building. The optional piece index identifies the piece of the building to attack, as a 1-based index.
climb_building
nil climb_building(Building building, [optional] piece index, [optional] bool move_fast)
Instructs units to scale the given building. The optional piece index identifies the piece of the building to attack, as a 1-based index.
climb_building_q
nil climb_building_q(Building building, [optional] piece index, [optional] bool move_fast)
Queues an order to scale the given building. The optional piece index identifies the piece of the building to attack, as a 1-based index.
leave_building
nil leave_building()
Orders all controlled units to leave the building. Troops will form up outside the building. Issue a goto_location_q() command following this order to direct the units to form up at a specific location outside the building they are occupying.
occupy_vehicle
nil occupy_vehicle(Building building, [optional] piece index, [optional] bool move_fast)
Instructs units to attack the given vehicle. The optional piece index identifies the piece of the vehicle to attack, as a 1-based index.
occupy_vehicle_q
nil occupy_vehicle_q(vehicle vehicle, [optional] piece index, [optional] bool move_fast)
Queues an order to attack the given vehicle. The optional piece index identifies the piece of the vehicle to attack, as a 1-based index.
attack_line
nil attack_line(Vector start, Vector end, [optional] move_fast)
Orders controlled units to attack a given line, running from start to end. The optional move_fast flag controls the speed that they move to attack the line.
attack_line_q
nil attack_line_q(Vector start, Vector end, [optional] move_fast)
Queues an order to attack a given line, running from start to end. The optional move_fast flag controls the speed that they move to attack the line.
goto_location_angle_width
nil goto_location_angle_width(Vector location, Number angle_degrees, Number width, [optional] move_fast)
Orders units to go to a given location, and align the formation to angle_degrees, with a formation width of width world units (meters).
goto_location_angle_width_q
nil goto_location_angle_width_q(Vector location, Number angle_degrees, Number width, [optional] move_fast)
Queues an order to go to a given location, and align the formation to angle_degrees, with a formation width of width world units (meters).
teleport_to_location
nil teleport_to_location(Vector location, Number angle_degrees, Number width )
Tells the controller to go a given location, instantaneously. Align the formation to angle_degrees, with a formation width of width world units (meters).
morale_behavior_fearless
nil morale_behavior_fearless()
Causes all units in the controller to behave fearlessly, units will never rout.
morale_behavior_rout
nil morale_behavior_rout()
Causes all units in the controller to immediately rout.
morale_behavior_default
nil morale_behavior_default()
Switches all units in the controller to default morale behavior, cancelling any previous call to morale_behavior_fearless() or morale_behavior_rout().
set_invincible
nil set_invincible(bool invincible)
Call with a true argument to make all units in the controller invincible, set to false to return them to being mortal.
set_invisible_to_all
nil set_invisible_to_all(bool invisible, [optional] bool update_ui)
Call with a true argument to make all units in the controller invisible to everyone (including yourself; including on the UI), set to false to return them to being seen normally (including hiding as normal)
The second parameter allow you to not update the UI, defaulting to true. Highly recommended not to change this, except under specific circumstances
change_enabled
nil change_enabled(bool visible)
Call with a true argument to make all units in the controller enabled; which is normal behaviour.
Call with false to stop them from taking ANY part in the battle.
melee
nil melee(bool active)
Switches all units in the controller between melee and normal.
close_formation
nil close_formation(bool close)
Switches all units in the controller between loose and normal (true for close, false for loose).
select_deployable_object
nil select_deployable_object(String ability_name)
Allows the units to use deployable objects such as gabionades etc.
change_fatigue_amount
nil change_fatigue_amount(number relative amount)
Change the fdatigue omount of the units; relative to their current level
i.e. 0.5 is half, 1.0 is same, 2.0 is double.
NB: don't pass in 0.0, as this would cause divide by 0, just make it something like 0.01
Ships
A collection of all the ships in an Army. There is a single unique Ship object for every ship in the battle.
The Ships object is a collection of Ship objects. The collection can be queried by ordinal index, or by ship name, as-per Units versus Unit objects.
count
Number count()
Retrieves the count of ships in the ships list.
item
Ship item(Number n)
Ship item(String ship_name)
If the supplied parameter is an integer, item retrieves the n'th Ship object in the list of ships, where n is a 1-based index. If it's a string it retrieves the Ship object with the corresponding ship_name as defined in the battle XML.
Ship
name
String name()
Returns the name of the ship. If the ship has a script_name parameter in the battlefield def file, the return value will be the script_name. If the ship has no script_name attribute, the 1-based index of the ship in it's armies Ships collection will be returned e.g. "1" for the first "10" for the 10th.
type
String type()
Returns the type of the ship, this corresponds to the ship_type element's type attribute in the battle xml file.
position
Vector position()
Returns a Vector object representing the position of the centre of the ship.
bearing
Number bearing()
Returns the bearing of the ship, in degrees, relative to North (bearing = 0).
ship_in_range
bool ship_in_range(Ship enemy_ship)
Returns true if the enemy_ship is in range, false otherwise.
hull_damage
Number hull_damage()
Returns the amount of hull damage a ship has sustained as a floating point number from 0.0 (no damage) to 1.0 (maximum damage).
sail_damage
Number sail_damage()
Returns the amount of sail damage a ship has sustained as a floating point number from 0.0 (no damage) to 1.0 (maximum damage).
is_routing
bool is_routing()
Returns true if the ship is routing, false otherwise.
is_surrendered
bool is_surrendered()
Returns true if the ship is surrendered, false otherwise.
number_of_men_alive
Number number_of_men_alive()
Returns the number of men alive on a ship.
deploy_reinforcement
nil deploy_reinforcement(bool manual)
If the ship is a reinforcement that is not yet deployed, setting this to false will prevent it from deploying until it is set to true again (keeping with the current constraints of ships being drip fed into a battle), allowing you to be able to delay deployment of reinforcements.
Shipcontroller
A ShipController is a container for Ship objects that you want to take control of i.e. issue commands to.
In order for a ShipController to issue commands it must take the ships it controls out of AI control - to avoid conflicting control. The ShipController implicitly takes control of any ships it controls prior to issuing a given command. You can explicitly take and release control (back to the AI) using methods on the ShipController (take_control() & release_control()).
A ShipController manages one or more ship groups and a list of individual ships. Each group of ships that the controller manages moves together - organising themselves into a specific formation. The individual ships under control all move autonomously.
There are two 'flavours' of command for many of the commands - immediate execution or queued. Any command with the "_q" suffix e.g. withdraw_q() is a queued variation of the command withdraw(). Queuing commands is a way of setting up a sequence of actions to be taken - e.g. setting a series of way points.
add_group
nil add_group(<list>)
Adds one or more ships to the controller as an independent group. See unitcontroller:add_group() for usage demonstration.
add_ships
nil add_ships(<list>)
Adds one or more ships to the controller as independent autonomous ships.
take_control
nil take_control()
Takes script control of all ships, removing them from AI control. take_control() is called internally prior to issuing any command - so all ships in the controller will be under script control until explicitly removed.
release_control
nil release_control()
Returns control of ship back to the AI. Note that the AI may, in some circumstances, appear behave strangely when they are returned to the AI, as the AI will start to provide orders based on it's own algorithms.
clear_all
nil clear_all()
Removes all ships from the controller - ships are still left under script control unless explicitly released with release_control().
attack_ship
nil attack_ship(Ship shipTarget)
Instructs controlled ships to immediately attack the target enemy ship.
attack_ship_q
nil attack_ship_q(Ship shipTarget)
Queues up an order to attack the target ship.
attack_unit
nil attack_unit(Unit shipTarget)
Instructs controlled ships to immediately attack the target enemy unit.
attack_unit_q
nil attack_unit_q(Unit shipTarget)
Queues up an order to attack the target unit.
fire_at_ship
nil fire_at_ship(Ship shipTarget)
Instructs controlled ships to target an enemy ship.
board_ship
nil board_ship(Ship shipTarget)
Instructs controlled ships to immediately board an enemy ship.
board_ship
nil board_ship_q(Ship shipTarget)
Queus up a command to board an enemy ship.
halt
nil halt()
issue the halt command immediately to controlled ships. All ships furl sails &l come to a stand-still. Takes script control of all ships.
withdraw
nil withdraw()
Issues the withdraw command immediately to all ships, causing them to retreat. Takes script control of all ships.
withdraw_q
nil withdraw_q()
Queues a withdraw command to all ships, which will be processed after all currently queued commands have been executed. Otherwise identical to withdraw().
add_all_ships
nil add_all_ships()
Adds all ships to the controller as a group.
fire_at_will
nil fire_at_will(bool fire_at_will)
Sets the fire-at-will status of all controlled ships to true or false.
sink
nil sink()
Instantly sinks all ships in the controller.
rotate
nil rotate(Number angle_degrees, [optional] bool move_fast)
Issues command to rotate by angle_degrees. If move_fast is set, ships start turning at maximum speed.
rotate_q
nil rotate_q()
Queues a command to rotate by angle_degrees. If move_fast is set, ships start turning at maximum speed.
broadside_attack
nil broadside_attack( bool left_or_right)
Issues the command to fire a broadside. if left_or_right is true, broadside is fired from left side (starboard), otherwise fired from right side (port).
toggle_boarding_mode
bool toggle_boarding_mode()
Toggles the ships boarding mode on/off.
change_shot_type
nil change_shot_type(String shot_type)
Change the shot type for all controlled ships.
move_forward
nil move_forward()
Orders the controlled ships to move forward, unfurling sails if the ship is halted.
set_sail
nil set_sail(String sail_type)
Changes the sail configuration for all controlled ships. Valid values are "stationary", "battle sail", "half sail" and "full sail".
goto_location
nil goto_location(Vector vector, [optional] String sail_configuration)
Orders ships to move to a specified location, where the location can be specified as a Vector object or as a Location object.
The optional sail_configuration arg controls the speed of the move. Possible string values for sail_configuration are as given in the documentation for set_sail(). The default is "half sail".
teleport_to_location
nil teleport_to_location(Vector location, Number angle_degrees, Number width)
Tells the controller to go a given location, instantaneously. Align the formation to angle_degrees, with a formation width of width world units (meters).
change_formation
nil change_formation(String formation)
Changes the formation of the ships.
change_formation_q
nil change_formation_q(String formation)
Queues an order to change the formation of ships.
morale_behavior_fearless
nil morale_behavior_fearless()
Causes all ships in the controller to behave fearlessly, ships will never rout.
morale_behavior_rout
nil morale_behavior_rout()
Causes all ships in the controller to immediately rout.
morale_behavior_default
nil morale_behavior_default()
Switches all ships in the controller to default morale behavior, cancelling any previous call to morale_behavior_fearless() or morale_behavior_rout()
blow_up_ship
nil blow_up_ship()
For each ship in the controller, triggers a magazine explosion that blows up the ship.
destroy_mast
nil destroy_mast()
For each ship in the controller, triggers the destruction of the main mast.
ignite_deck
nil ignite_deck()
For each ship in the controller, triggers a small fire on deck. This will extinguish itself after a few seconds. Multiple calls to ignite_deck() will cause the fire to build up and spread. After 4 or 5 sequential calls to ignite_deck() the fire will be fatal, and it will rapidly spread across the ship, leading to an explosion.
ignite_sails
nil ignite_sails()
For each ship in the controller, triggers a fire in the sails that will spread and engulf the sails.
change_is_immune_to_fire_damage
nil change_is_immune_to_fire_damage(bool is_immune)
For each ship in the controller, change whether it takes damage from fires.
force_surrender
nil force_surrender()
Forces all controlled ships to surrender.
set_invisible_to_all
nil set_invisible_to_all(bool invisible, [optional] bool update_ui)
Call with a true argument to make all units in the controller invisible to everyone (including yourself; including on the UI), set to false to return them to being seen normally (including hiding as normal)
The second parameter allow you to not update the UI, defaulting to true. Highly recommended not to change this, except under specific circumstances.
change_enabled
nil change_enabled(bool visible)
Call with a true argument to make all units in the controller enabled; which is normal behaviour.
Call with false to stop them from taking ANY part in the battle.
Buildings
A collection of buildings present in the scene, accessed from the battle object.
count
Number count()
Retrieves the count of buildings in the building list.
item
Building item(Number n)
Retrieves the n'th Building object in the list of buildings, where n is a 1-based index.
Building
position
Vector position()
Returns a Vector containing the 3D position of the Building in the scene.
central_position
Vector central_position()
Returns a Vector containing the central position of the Building model, not the pivot point.
alliance_owner_id
Number alliance_owner_id()
Returns a Number containing the alliance owner's id (-1 if nobody).
name
String name()
Returns the name of the building.
show
nil show()
Shows the building visually, and adds it from the object-avoidance list – so troops path-find around the hidden building.
hide
nil hide()
Hides the building visually, and removes it from the object-avoidance list – so troops can pass right though the hidden building.
is_garrisoned
bool is_garrisoned()
Will return true/false based on whether there are any units occupying the building.
health
Number health()
Returns the current health of the building, floating point value ranging from 0.0 to 1.0.
currently_garrisoned
Number currently_garrisoned()
Will return how many people are currently occupying the building.
capacity
Number capacity()
Will return how many people the building can contain.
change_on_fire
nil change_on_fire(bool)
Change whether the building should be on fire.
change_immune_to_fire_damage
nil change_immune_to_fire_damage(bool);
Change whether the building should take damage from being on fire.
change_immune_to_catching_fire
nil change_immune_to_catching_fire(bool);
Change whether the building should be allowed catch fire.
change_is_destructible
nil change_is_destructible(bool)
Change whether the building should take damage.
Vector
The Vector Object represents a 3D [x,y,z] point on the battlefield. NB the y component is the height of the position above the sea plane, with the x and z components being longitude/latitude from the centre of the map, which is at [0,0]. Thus, a co-ordinate of [-160, 40, 300] is 160m west and 300m north of the centre of the map, and 40m above the sea plane. Note that that doesn't necessarily mean the point is above the ground.
In addition to the methods on the Vector object, Vector objects also obey Vector arithmetic, and so can be added, subtracted, divided and multiplied using standard LUA operators.
Various script methods return a pointer to a Vector object; in addition you can create a new instance of a Vector object in script, using the new() operator, or using the constructor syntax.
e.g.
my_vector = battle_vector:new();
This creates a new instance of a Vector object, and returns a reference to it in the variable named my_vector.
or
battle_vector([optional] [Number x, Number y, Number z] )
Vector constructor, takes either zero or three args. A Vector constructed with zero args is initialized with (0,0,0)
my_vector = battle_vector(2,20,3);
get_x
Number get_x()
Returns the x property.
get_y
Number get_y()
Returns the y property.
get_z
Number get_z()
Returns the z property.
set_x
nil set_x(Number n)
Sets the x property.
set_y
nil set_y(Number n)
Sets the y property.
set_z
nil set_z(Number n)
Sets the z property.
set
nil set(Number x, Number y, Number z)
nil set(Vector v)
Sets the x,y & z properties simultaneously. Alternatively pass in another vector to set the subject vector to the same value.
distance
Number distance(Vector from_vector)
Returns the distance from this Vector to another Vector
distance_xz
Number distance_xz(Vector from_vector)
Returns the distance from this Vector to another Vector in flat XZ space.
to_screen_position
Vector to_screen_position()
Returns the screen coordinates of a world-space position, using the current camera to compute the projection.
The returned Vector is in screen space coordinates so +1..-1 in screen X & Y, 0..1 in Z space.
length
Number length()
Returns the length of this vector, the distance from the origin [0,0,0]
length_xz
Number length_xz()
Returns the length of this vector in flat XZ space.
Camera
The Camera object is used to trigger camera transitions to focus the camera on activity in the battle being scripted.
look_at
nil look_at(Vector point, Number transition_duration, [optional] Number angle_degrees, [optional] bool linear, [optional] Number field_of_view)
Triggers a camera transition which ends with the camera looking at the specified point in the world, from the given angle, if specified. If no angle is specified, the camera’s current facing is used instead.
transition_duration - duration of transition in seconds if positve, scale of auto calculated transition duration if negative.
linear - is transition linear or slow-fast-slow, default is false
field_of_view - field of view in degrees if positive, in game default field of view if zero, use current field of view if negative
move_to
nil move_to(Vector target, Vector position, Number transition_duration, [optional] bool linear, [optional] Number field_of_view)
Triggers a camera transition which ends with the camera looking at the specified target in the world, from the specified position.
transition_duration - duration of transition in seconds if positve, scale of auto calculated transition duration if negative.
linear - is transition linear or slow-fast-slow, default is false
field_of_view - field of view in degrees if positive, in game default field of view if zero, use current field of view if negative
position
Vector position()
Returns the battle cameras position vector.
target
Vector target()
Returns the battle cameras look at vector.
change_depth_of_field
nil change_depth_of_field(Number transition_duration, [optional] Number focal_distance, [optional] Number focal_length, [optional] Number blur_size)
Changes the camera depth of field.
transition_duration - duration of transition in seconds
focal_distance - if ommitted use game defaults for this and all subsequent parameters
focal_length - must be present if focal_distance is present
blur_size - must be present if focal_distance is present
fade
nil fade(bool to_black, Number transition_duration)
to_black - fades out to black if true, fades in if false
transition_duration - duration of transition in seconds
change_height_range
nil change_height_range(Number min_height, Number max_height)
Changes the height range of the camera above the ground.
min_height - minimum height of the camera above the ground - if negative use game default
max_height - maximum height of the camera above the ground - if negative use game default
enable_shake
nil enable_shake()
Enables the functionality of camera shake.
disable_shake
nil disable_shake()
Disables the functionality of camera shake.
enable_anchor_to_army
nil enable_anchor_to_army()
Enables the anchor which restricts the camera to the vicinity of the player's army.
disable_anchor_to_army
nil disable_anchor_to_army()
Disables the anchor which restricts the camera to the vicinity of the player's army.
AIObjectivePlanner
Note: these are created by the alliance by calling: create_ai_unit_planner()
An AI Objective planner is a simple class where you can collect AI units or ships into a structure (think of it like a controller); and then tell them to do certain high-level actions. This is useful if you want the AI to worry about the specifics of what it’s doing, but you can give it ‘hints’ about what you want it to do.
Example of an AIObjectivePlanner script:-
--declare the AI planner
AI_Planner = Alliance_01:create_ai_unit_planner();
--load it with units
AI_Planner:add_units(
Unit_01,
Unit_02,
Unit_03
);
--give it an order
AI_Planner:defend_position(Pos_Defence_Position, 60);
add_units
nil add_units(<list>)
This adds one or more units to the controller as an independent group. See the notes in the Unitcontroller for more detailed information.
remove_units
nil remove_units(<list>)
Remove the passed in units from the objective and allow the AI to do what it wants with it.
defend_position
nil defend_position(Vector position, Number radius)
Tell the units to try defend the position specified, while staying in the area specified by the radius.
attack_unit
nil attack_unit(Unit target)
Tell the units to try attack the specified unit.
capture_settlement
nil capture_settlement(Vector start_position, Vector end_position)
Tell the units under control to attempt to take a settlement. The attack line with be along the specified Vector positions
clear_objective
nil clear_objective()
Clear the current objective that the controlled AI have.