Skip to content

18 — Event scripts: libraries, patterns and checking

Index · The language · Events and actions · SELECT and functions

The standard libraries the shipped campaigns are built from, common patterns, pitfalls, a complete faction script and how to check a script. For the campaign structure above the scripts see chapter 11.

Contents

  1. Standard libraries
  2. LIB/Common.txt
  3. LIB/Invasion.txt: airborne operations
  4. LIB/Invasion.txt: moving units
  5. LIB/Invasion.txt: invasion and defence
  6. LIB/Invasion.txt: region analysis
  7. LIB/Invasion.txt: spawning armies
  8. LIB/Invasion_ext.txt: landings and bases
  9. LIB/Invasion_ext.txt: automatic invasion
  10. LIB/Invasion_ext.txt: defence and support
  11. LIB/Invasion_ext_1.txt
  12. Campaign helper blocks
  13. Map event scripts
  14. Common patterns
  15. Pitfalls checklist
  16. Complete example

Standard libraries

The game ships reusable blocks in Scenario/LIB/. Campaign scripts include them either directly or through a small wrapper in the campaign's Common folder. Reuse these blocks instead of rewriting them. All of them work for the faction whose script runs them (SelfID) unless a faction parameter says otherwise.

File Contents Needs
Scenario/LIB/Common.txt casualty and mission-state helpers nothing
Scenario/LIB/Invasion.txt airborne drops, moving groups, simulated invasions, border analysis, spawning armies nothing
Scenario/LIB/Invasion_ext.txt naval landings, auto-invasion, region defence, aircraft replenishment Invasion.txt
Scenario/LIB/Invasion_ext_1.txt whole-faction defence, recalling invaders, random points, landings with patrol Invasion.txt and Invasion_ext.txt

Campaign wrappers. Scenario/Main/Common/Invasion.txt uses Invasion.txt only. Scenario/DLC_1/Common/Invasion.txt and Scenario/DLC_2/Common/Invasion.txt add Invasion_ext.txt. Scenario/DLC_3/Common/Invasion.txt adds Invasion_ext_1.txt too. Scenario/SNARE/Common/Common.txt uses all four files directly. A USEd file may contain blocks only, so a wrapper is just a list of USE lines.

Invasion.txt, Invasion_ext.txt and Invasion_ext_1.txt each start with a comment that lists their blocks and signatures.

Conventions used by the libraries:

  • Parameters marked ref set are output sets or large input sets passed for speed. You can still pass a constant set such as {EnemyID}; it is then handled by value.
  • Blocks that move units call SUSPEND AI FOR on them first, so the AI doesn't give them other orders. Units the blocks create have their AI on until then.
  • Several blocks re-arm themselves with ON triggers and are stopped by custom events. Those events are listed with each block.
  • "Army" means a unit whose principal type is "Army_Division".

Quick index

LIB/Common.txt

GetFactionCasualties

Syntax: int GetFactionCasualties(int ID)

Returns the faction's casualties in the regions it owns now: STAT("INITIAL_POPULATION", ID) - STAT("POPULATION", ID).

if (GetFactionCasualties(SelfID) > 500000)
  throw "Global War" globally
end

GetFactionTrueCasualties

Syntax: int GetFactionTrueCasualties(int ID)

Returns the casualties in the faction's originally owned regions: STAT("INITIAL_ORIGINAL_POPULATION", ID) - STAT("ORIGINAL_POPULATION", ID). Unlike GetFactionCasualties, it isn't affected by regions changing hands.

def int Casualties = GetFactionTrueCasualties(SelfID)

MissionOK

Syntax: bool MissionOK(string Mis)

Returns true if the mission's state is m_Success. See MISSION_STATE.

if (NOT MissionOK("Push Soviets"))

MissionInProgress

Syntax: bool MissionInProgress(string Mis)

Returns true if the mission's state is m_InProgress.

if (CURRENT_TICK<=QuickMissionTimer AND MissionInProgress("25Minutes"))

LIB/Invasion.txt: airborne operations

ReplenishBasesWithTroopsMaxNum / ReplenishBasesWithTroops

Syntax: int ReplenishBasesWithTroopsMaxNum(unit Base, string TransportUT, string HostedUT, int MaxNum)
int ReplenishBasesWithTroops(unit Base, string TransportUT, string HostedUT)

Refills a base with transports and loads them.

  1. Creates transports of type TransportUT until the base holds its maximum, counting transports that are out on a mission.
  2. Creates HostedUT units inside the base until there is one per transport at home, but no more than MaxNum.

Returns the number of HostedUT units in the base (searched recursively). Returns 0 and does nothing if the base is dead. ReplenishBasesWithTroops uses the base's full transport capacity as MaxNum.

ReplenishBasesWithTroops(ThisBase, "Spec_Ops_Helicopter", "Spec_Ops_Team")

SendAirborneFromBaseMaxNum / SendAirborneFromBase

Syntax: int SendAirborneFromBaseMaxNum(unit Base, coord Target, string TransportUT, string HostedUT, int MaxNum)
int SendAirborneFromBase(unit Base, coord Target, string TransportUT, string HostedUT)

Refills the base with ReplenishBasesWithTroopsMaxNum, then launches the loaded transports at random points around Target (one point per loaded unit, from GET_VICINITY_POINTS). Returns true if the base is alive, false otherwise.

SendAirborneFromBaseMaxNum(GetBase(CITY("Delhi")), @(0.741866, 0.329272), "Air_Transport", "Army_Division", 2)

SendAirborneTroopsFromBase / SendSpecOpsFromBase

Syntax: int SendAirborneTroopsFromBase(unit Base, coord Target)
int SendSpecOpsFromBase(unit Base, coord Target)

Shortcuts for SendAirborneFromBase: armies ("Army_Division") in "Air_Transport" planes, or spec-ops teams ("Spec_Ops_Team") in "Spec_Ops_Helicopter" helicopters.

on each TICK +MINUTES(3) SendSpecOpsFromBase(MyBase, TargetCity)

LIB/Invasion.txt: moving units

MoveGroup

Syntax: int MoveGroup(ref set FullGroup, coord Destination)

Suspends the AI for the group, makes it a follow group with MAKE_GROUP, and orders the leader to Destination if it isn't already heading there (within 10 km). Returns the leader, or 0.

def unit GroupLeader = MoveGroup(CanberraGroup, Destination)

SecureMoveUnit

Syntax: SecureMoveUnit(int This, coord Dest, string TargetRegion)

Moves one unit to Dest and keeps re-issuing the order each time the unit's orders complete, until it arrives (within 10 km).

  • Stops when: the unit is destroyed, TargetRegion is occupied by our faction, or the custom event "Cancel SecureMoveUnit " + This is thrown.
  • Each call first throws "Cancel SecureMoveUnit " + This, so a new call replaces any earlier one for the same unit.
SecureMoveUnit(GET_LAST(Armies), CITY("Ufa"), "South Urals")

SecureMoveNavalGroup

Syntax: SecureMoveNavalGroup(set Group, coord Destination)

Moves a naval group to Destination with MoveGroup, with AutoAttack on. Whenever the leader is destroyed or its orders complete before arrival, it calls itself again, so a new leader takes over.

SecureMoveNavalGroup(SupportGroup, @(0.857695, 0.28180))

SecureMoveNavalGroupSignalArrival

Syntax: SecureMoveNavalGroupSignalArrival(set Group, coord Destination, string Signal)

As SecureMoveNavalGroup, but throws the custom event Signal (to our own script only) when the group arrives, or when the group no longer exists.

SecureMoveNavalGroupSignalArrival(Fleet, Rendezvous, "Fleet Arrived")
...
on "Fleet Arrived" StartLanding()

SecureMoveNavalGroupToUnload

Syntax: SecureMoveNavalGroupToUnload(set Group, coord Destination, string RegionToUnload, coord ReturnToOrigin)

Moves a naval group like SecureMoveNavalGroup. On arrival, unloads its troops into RegionToUnload with UnloadTroopsFromGroup, then sails back to ReturnToOrigin after 20 seconds.

  • Destination must be a water point. The landing points in RegionToUnload are chosen automatically.
  • Pass ReturnToOrigin equal to Destination (within 100 km) to make the group stay in place.
SecureMoveNavalGroupToUnload(NamibiaGroup, NamibiaLanding, "Namibia", NamibiaLanding)   // unload and stay

UnloadTroopsFromGroup

Syntax: UnloadTroopsFromGroup(ref set Group, string RegionToUnload)

Every unit of the group that has a hangar launches all its hosted units at points around the cities of RegionToUnload (three points per city, see CollectOccupationPoints), spreading them across the cities.

  • Throws "Convoy Arrived " + RegionToUnload (to our own script) if the group isn't empty.
UnloadTroopsFromGroup(LandingShips, "South Korea")
on "Convoy Arrived South Korea" StdMessage(9020)

CollectOccupationPoints

Syntax: int CollectOccupationPoints(ref set DestinationPoints, ref set CitiesToGo, int PointsPerCity)

Adds PointsPerCity random points around each city of CitiesToGo (inside the city's region) to DestinationPoints, ordered so that consecutive points belong to different cities. Returns the number of points. CitiesToGo can hold city units or city names.

def set DestinationPoints
def int TotalSize = CollectOccupationPoints(DestinationPoints, CitiesToGo, 3)

LIB/Invasion.txt: invasion and defence

SimulateInvasion

Syntax: SimulateInvasion(string TargetRegion, ref set Invaders)

Sends the Invaders to occupy all cities of TargetRegion, using SimulateInvasionCities. This is the scripted replacement for the AI's own Invasion order. Suspend the AI for the invaders first.

SUSPEND AI FOR InvasionGroup
SimulateInvasion("Manchuria", InvasionGroup)

SimulateInvasionCities

Syntax: SimulateInvasionCities(string TargetRegion, ref set CitiesToGo, ref set Invaders)

Spreads the live Invaders over points around the given cities (three per city, cycling if there are more invaders than points) and moves each with SecureMoveUnit. Each unit stops once TargetRegion is occupied by our faction. Does nothing if CitiesToGo is empty.

SimulateInvasionCities(TargetRegion, TargetCities, InvasionGroup)

SimulateInvasionCitiesOnly

Syntax: SimulateInvasionCitiesOnly(ref set CitiesToGo, ref set Invaders)

As SimulateInvasionCities, but the cities can be in different regions: each unit stops when the region of its own destination is occupied.

on each Launched Hosted ANY "Army_Division" ->(unit ThisArmy) OF ME SimulateInvasionCitiesOnly({"Lhasa"}, {ThisArmy})

GetPotentialOccupiersFromRegion

Syntax: GetPotentialOccupiersFromRegion(int AttackerID, ref set CheckRegions, ref set PotentialInvaders)

Fills PotentialInvaders, replacing what it held, with the armies of AttackerID that are in CheckRegions and are either idle or moving within those regions. It then leaves out one unit per city so the cities stay held: for each city in those regions, the first unit of the attacker blocking it is removed from the result.

GetPotentialOccupiersFromRegion(SelfID, {ThisRegion}, DefendingForce)

SelectNonSiedgedCities / SelectNonSiedgedCitiesFromList

Syntax: SelectNonSiedgedCities(int AttackerID, string RegionName, ref set CitiesToOccupy)
SelectNonSiedgedCitiesFromList(int AttackerID, ref set CitiesToOccupy)

SelectNonSiedgedCities fills CitiesToOccupy with the cities of RegionName. Both then remove the cities that are already blocked (occupied or besieged) by AttackerID or its allies, leaving the cities still to be taken.

SelectNonSiedgedCities(SelfID, TargetRegion, TargetCities)
SimulateInvasionCities(TargetRegion, TargetCities, InvasionGroup)

SpreadDefenders

Syntax: SpreadDefenders(string RegionName, ref set Defenders)

Moves the Defenders to random points 50–350 km around the cities of RegionName, inside that region, using each point once before reusing any. Throws "Cancel SecureMoveUnit " + unit for each defender first, cancelling any SecureMoveUnit in progress.

SpreadDefenders(ThisRegion, DefendingForce)

LIB/Invasion.txt: region analysis

ListImmediateBorderingRegions

Syntax: ListImmediateBorderingRegions(string ThisRegion, int EnemyID, ref set FoundRegions)

Adds to FoundRegions the neighbours of ThisRegion owned by EnemyID.

ListImmediateBorderingRegions(CurrentInvasion, EnemyID, FoundRegions)

ListBorderingRegions / ListBorderingRegionsMultiEnemy

Syntax: ListBorderingRegions(string StartRegion, int MyID, int EnemyID, ref set FoundRegions)
ListBorderingRegionsMultiEnemy(string StartRegion, int MyID, ref set EnemyIDs, ref set FoundRegions)

Starting from StartRegion, walks through all connected regions owned by MyID or its permanent allies, and adds to FoundRegions every enemy-owned region on the border of that area. Use it to find the next invasion targets beyond a front. The header comment of Invasion.txt lists EnemyIDs without ref; the actual parameter is ref set.

ListBorderingRegions(REGION_NAME(SpawnBase), SelfID, PlayerID, EnemyRegions)
ListBorderingRegionsMultiEnemy(SpawnRegion, SelfID, EnemyIDs, RegionsToInvade)

ListEndangeredRegions / ListEndangeredRegionsMultiEnemy

Syntax: ListEndangeredRegions(int MyID, ref set FoundRegions)
ListEndangeredRegionsMultiEnemy(int MyID, ref set EnemyIDs, ref set FoundRegions)

Adds to FoundRegions the regions of MyID that border a region of an enemy: all current enemies (GET_ENEMIES), or the given EnemyIDs.

ListEndangeredRegions(SelfID, Endangered)
ListEndangeredRegionsMultiEnemy(SelfID, {PlayerID}, BorderRegions)

LIB/Invasion.txt: spawning armies

CreateArmiesAroundPoint / CreateArmiesAroundPointForFaction

Syntax: CreateArmiesAroundPoint(coord Start, int Number, ref set Result)
CreateArmiesAroundPointForFaction(int FactionID, coord Start, int Number, ref set Result)

Creates Number armies at random points around Start, inside the territory of FactionID (our own faction for the short form), and adds them to Result. If fewer points are found than armies, points are reused. The armies are created for the faction running the script, with AI on.

CreateArmiesAroundPoint(ThisBase, 3, NewArmies)
CreateArmiesAroundPointForFaction(TERRITORY(Start), Start, Number, Result)

CreateBaseAndArmiesAroundPoint

Syntax: int CreateBaseAndArmiesAroundPoint(coord Start, int Number, ref set Result)

Makes sure we have an army base within 50 km of Start, then creates Number armies around it in the territory of whoever owns Start, adding them to Result.

  • If there is no base and a non-allied unit's occupation radius covers Start, nothing is created and it returns false.
  • Otherwise it returns true.
if (CreateBaseAndArmiesAroundPoint(ThisCity, 3, NewArmies))
  SimulateInvasionCitiesOnly(TargetCities, NewArmies)
end

LIB/Invasion_ext.txt: landings and bases

SendTroopsFromPoint / SendTroopsFromPointCheckRepeat

Syntax: SendTroopsFromPoint(coord SpawnPoint, coord DestinationPoint, string RegionToUnload, ref set LandingGroup)
SendTroopsFromPointCheckRepeat(coord SpawnPoint, coord DestinationPoint, string RegionToUnload, ref set LandingGroup, bool Repeat)

A complete naval landing. Both points must be on water.

  1. Looks for our "Landing_Ship" group within 100 km of SpawnPoint, such as ships that came back from an earlier run. It creates whatever unit types of LandingGroup (a set of unit types) are missing. If there are none, it creates the whole group with CREATE_GROUP.
  2. Suspends the AI for the group and loads every landing ship up to 4 armies.
  3. Sends the group with SecureMoveNavalGroupToUnload to unload into RegionToUnload.

With Repeat true (the short form), the ships return to SpawnPoint after unloading, ready for the next call. With Repeat false, they stay at the destination.

def set LandingGroup = {"Landing_Ship", "Landing_Ship", "Destroyer"}
on each TICK +MINUTES(4) SendTroopsFromPoint(SeaStart, SeaLanding, "Hokkaido", LandingGroup)

CreateLandingGroup

Syntax: unit CreateLandingGroup(ref set GroupComposition, coord SpawnPoint, ref set Result)

Creates a group of the unit types in GroupComposition at SpawnPoint, fills every landing ship with as many armies as fit, puts all group units into Result, and returns the leader. It doesn't move the group or suspend its AI.

def unit Leader = CreateLandingGroup({"Cruiser", "Destroyer", "Destroyer", "Landing_Ship", "Landing_Ship"}, SpawnPoint, LandingGroup)

RecreateArmyBase

Syntax: unit RecreateArmyBase(coord StartFrom)

Returns an army base of ours or of an ally within 100 km of StartFrom, creating one at StartFrom if there is none.

def unit Base = RecreateArmyBase(CITY("Busan"))

CreateArmiesAroundPointMaxNumber

Syntax: CreateArmiesAroundPointMaxNumber(coord Start, int Number, int MaxNumber, ref set Result)

As CreateArmiesAroundPoint, but creates fewer armies if needed so that our armies near Start don't exceed MaxNumber.

CreateArmiesAroundPointMaxNumber(This, 3, 8, NewArmies)

InvadeRegion

Syntax: InvadeRegion(string RegionToInvade, coord StartFrom, int Count)

Gets an army base at StartFrom (RecreateArmyBase), spawns Count armies around it, adds the idle armies already in the base's region, and sends them all to invade RegionToInvade (SimulateInvasion) with their AI suspended.

InvadeRegion("South Korea", CITY("Pyongyang"), 4)

TryOccupyCities

Syntax: int TryOccupyCities(coord BasePoint, ref set CitiesToOccupy, int NumberOfArmiesToSpawnPerCity)

Removes the cities we already block from CitiesToOccupy, then tries CreateBaseAndArmiesAroundPoint at BasePoint with 1 + NumberOfArmiesToSpawnPerCity per remaining city. On success it sends the new armies to the cities (SimulateInvasionCitiesOnly) and returns true. If every city was already blocked, the original list is used. Returns false if the base point is blocked by enemies.

Note: it modifies CitiesToOccupy.

TryOccupyCities(LongBinCoord, {"Phnom Penh"}, 2)

LIB/Invasion_ext.txt: automatic invasion

AutoInvade

Syntax: AutoInvade(string RegionToStart)

Runs a self-continuing scripted invasion.

  1. If RegionToStart is held by us or an ally, it picks the best enemy region bordering our connected territory (SelectRegionToAutoInvade). Otherwise RegionToStart itself is the target.
  2. It gathers the idle armies in our regions connected to the start (GetPotentialOccupiersFromRegion), suspends their AI and invades the target.
  3. When we or an ally occupy the target, it waits 20 seconds and calls itself on that region. Every 20 seconds until then it sends reinforcements (AutoCheckForReinforcement).

Custom events:

  • Throws "auto invasion region" PARM TargetRegion each time a target is chosen. When no target is left, it throws "auto invasion finished", then "auto invasion region" with the region name "none".
  • Stops on "cancel auto invasion", or when our faction surrenders.
on "Phase 2" AutoInvade("Kashmir")
on "Ceasefire" throw "cancel auto invasion"
on "auto invasion region" ->(string TargetRegion) CurrentTarget = TargetRegion

AutoCheckForReinforcement

Syntax: AutoCheckForReinforcement(string TargetRegion)

Sends the idle armies from our regions connected to TargetRegion to its cities that we don't yet block, or to all its cities if none are left.

on each TICK +SECONDS(20) AutoCheckForReinforcement(TargetRegion)

SelectRegionToAutoInvade

Syntax: string SelectRegionToAutoInvade(ref set Regions)

Returns the region with the highest initial production plus science, weighting ×10 the regions originally owned by an ally (liberation first). Returns "none" for an empty set.

TargetRegion = SelectRegionToAutoInvade(RegionsToInvade)

CreateEnemySet

Syntax: CreateEnemySet(ref set EnemyIDs)

Clears EnemyIDs and fills it with the IDs of the factions at war with us. GET_ENEMIES returns the same set directly.

CreateEnemySet(EnemyIDs)

ListMyConnectedRegions

Syntax: ListMyConnectedRegions(int MyID, string StartRegion, ref set FoundRegions)

Adds to FoundRegions StartRegion and every region reachable from it through regions owned by MyID or its permanent allies.

ListMyConnectedRegions(SelfID, RegionToStart, RegSet)

ListInvadedRegions

Syntax: ListInvadedRegions(int FactionID, ref set Result)

Adds to Result the names of the faction's regions in which there are enemy armies (units with an occupation radius over 10 km).

ListInvadedRegions(SelfID, AllInvaded)

LIB/Invasion_ext.txt: defence and support

SelectNonDefendedCities / SelectNonDefendedCitiesFromList

Syntax: SelectNonDefendedCities(string RegionName, ref set CitiesToDefend)
SelectNonDefendedCitiesFromList(ref set CitiesToDefend)

SelectNonDefendedCities fills CitiesToDefend with the cities of RegionName. Both then remove the cities that already have more friendly blockers than enemy ones, counting the owner's units heading there, so the cities that still need defenders are left.

SelectNonDefendedCities(ThisRegion, CitiesToDefend)
SimulateInvasionCitiesOnly(CitiesToDefend, Armies)

SimulateDefendRegion / SimulateDefendRegionForGroup

Syntax: SimulateDefendRegion(string RegionName)
SimulateDefendRegionForGroup(string RegionName, ref set AllDefenders)

A scripted defence of a region. Half of the defenders go to the region's cities (SimulateInvasionCities) and the other half spread around them (SpreadDefenders). SimulateDefendRegion uses all our armies in the region, after deleting their orders.

Note: SimulateDefendRegionForGroup removes the city garrison from AllDefenders, so afterwards the set holds only the spread defenders.

SimulateDefendRegion("South Korea")
SimulateDefendRegionForGroup(ToDefend, NewArmies)

AttachSupportToArmies

Syntax: AttachSupportToArmies(ref set Armies, int Number, string UType)

Creates Number units of type UType next to the armies, cycling through them, suspends their AI, and makes each follow its army. Use it for escorts such as mobile air defence.

AttachSupportToArmies(NewArmies, 2, "AA_Site_Old")

ReplenishAircraft

Syntax: ReplenishAircraft()

Tops up our air bases towards their maximum, counting aircraft in flight. Each call adds at most:

  • 5 "Attack" planes per "Tactical_Airbase", "Carrier" and "Improvised_Airbase";
  • 5 "Fighter" planes per "Airport" and "Tactical_Airbase";
  • 2 "Bomber" planes per "Airport".
on each TICK +SECONDS(120) ReplenishAircraft()

SelectAttackTargetsForSpecOps

Syntax: SelectAttackTargetsForSpecOps(ref set TargetRegions, ref set Targets)

Puts into Targets the enemy ground units in TargetRegions, except checkpoints, army bases and armies.

SelectAttackTargetsForSpecOps(FACTION_REGIONS("Anti-Communists"), SpecOpsTargets)

LIB/Invasion_ext_1.txt

SimulateDefenceWholeFaction

Syntax: SimulateDefenceWholeFaction(bool MoveForcesFromSafeRegions)

Runs SimulateDefendRegion for every region of ours that borders an enemy. With MoveForcesFromSafeRegions true, the armies in our other regions are sent to defend a random endangered neighbour.

on "Phase 2" SimulateDefenceWholeFaction(true)

RecallArmiesFromRegion / RecallArmiesFromRegionForGroup

Syntax: RecallArmiesFromRegion(string RegionName)
RecallArmiesFromRegionForGroup(string RegionName, ref set Group)

If RegionName isn't ours, our armies there (or Group) are sent to defend a random region of ours next to it. If it is ours, they defend it in place.

RecallArmiesFromRegion(RegionName)
RecallArmiesFromRegionForGroup(REGION(SelectedBase), NewArmies)

RecallAllInvaders

Syntax: RecallAllInvaders()

Calls RecallArmiesFromRegion for every foreign region where we have armies. Use it to end an offensive, for example after a ceasefire.

on Ceasefire BETWEEN ME AND PlayerID RecallAllInvaders()

MakeRandomPoints

Syntax: MakeRandomPoints(ref set MyRegions, int Num, ref set RandomPoints)

Fills RandomPoints with exactly Num random points, trying to avoid units, spread over the regions in MyRegions. If the regions give too few, it adds points 50–250 km around our ground units. The result is shuffled.

MakeRandomPoints(FACTION_REGIONS(SelfID), Num, RandomPoints)

SecureMoveNavalGroupToUnloadAndPatrol

Syntax: SecureMoveNavalGroupToUnloadAndPatrol(set Group, set Route, string RegionToUnload, set ToPatrolAfterUnloading)

Moves a naval group through the water points of Route in order. At the last point, the landing ships unload into RegionToUnload (UnloadTroopsFromGroup). The other ships then form a new group and patrol ToPatrolAfterUnloading in a loop, if that set isn't empty.

SecureMoveNavalGroupToUnloadAndPatrol(CarrierGroup, {@(0.838023, 0.369442)}, "Taiwan", {@(0.857278, 0.346745)})

Campaign helper blocks

The DLC campaigns and SNARE also have a Scenario/<Campaign>/Common/Common.txt, which uses LIB/Common.txt and adds blocks shared by the campaign's missions. The DLC_3 version is the most complete; DLC_1 stops at DisableMassDestruction(), and DLC_2 has everything but StartAirstrikesNoCarriers():

  • StdMessage(int ID): the house-style advisor message, Message UI_STRING(ID) Position TopLeft Portrait ADVISOR_PORTRAIT.
  • SwitchOffChems(): switches all chemical artillery off for our armies and bases, and by default for new ones.
  • EnableTacticalNukesForFaction(int WRace): grants "Tactical_nukes", enables tactical nuke categories and sets armies' nuclear artillery to Always.
  • EnableTacticalNukesForAlliesAndMe(): throws "Tactical Nukes Enabled" globally and runs the block above for all our allies.
  • DisableMassDestruction(): disables chemical, biological and nuclear weapons, and re-enables each category for our side when we are attacked with it.
  • EnableMassDestruction(): enables them all.
  • StartAirstrikes(), StartAirstrikesNoCarriers(), StartBallisticMissiles(), StartCoastal(), StartICBMs(): every 20–30 seconds, order idle launchers of that kind to attack enemy targets BY BEST. They are self-rescheduling and stop on "Stop Airstrikes " + SelfID, "Stop BallisticMissiles " + SelfID, "Stop Costal " + SelfID (sic) and "Stop ICBMs " + SelfID respectively.

Scenario/DLC_3/Common/MonitorUnits.txt adds MonitorEnemyUnits(), which throws "Phase 2" globally as soon as a player unit (other than a spec-ops team) crosses into our territory, or attacks us.

Scenario/SNARE/Common/Common.txt has its own StdMessage(int ID) with the campaign's badge as the portrait, and the blocks its missions share: CheckUnitsAndStockpile(string MissionName), UpdateMissionScore(string MissionName, int FactionID, int Multiplier, bool Negative), RouteSpecOpsTeam(unit ThisSpecOps), AttackEnemy(unit EnemySpecOps) and StartMovingSpecOps().

USE "Scenario/DLC_3/Common/Common.txt"
...
StdMessage(7527)
DisableMassDestruction()
on "Phase 2" StartAirstrikes()

Map event scripts

A map's faction scripts live in Maps/<Map>.virtual/Events/. Maps/Events/CommonAI.txt holds one empty block, SetCommonAIEvents(), as a place for events shared by the factions of every map. Each map's Events/CommonAI.txt is a single USE of it, and the faction scripts call the block FOR AI. A map that needs its own shared events replaces its CommonAI.txt.

USE "Maps/IronCurtain.Virtual/Events/CommonAI.txt"

FOR AI
  SetCommonAIEvents()

FOR BOTH

END

Common patterns

These idioms appear throughout the shipped campaigns.

Mission phases driven by global custom events. One faction's script throws "Phase 2" globally, and every faction reacts:

// in any faction
on destroyed any "Army_Base" throw "Phase 2" globally

// in every faction
FOR AI
  ON "Phase 2" StartPhase2()
  ON "Phase 3" StartPhase3()
END

Suspended AI with scripted behaviour. Many enemy factions start with SUSPEND AI and then drive units with blocks, resuming AI when the player crosses a line:

BLOCK ResumeAI()
  RESUME AI
  throw "Phase 2" globally
END

FOR AI
  SUSPEND AI
  on "Allow AI" OR Attacked ANYTHING ResumeAI()
    delete when "Global War"
END

A recurring job with a cancel switch:

on each TICK +SECONDS(30) SpawnMRBM()
  delete when "Global War"

Or use a self-rescheduling block (lets you change the delay each time):

BLOCK StartBallisticMissiles()
  def set SRBMs
  Select UNITS OWNER==SelfID AND TYPE in {"Mobile_SRBM", "SRBM_Site"} AND false==HAS_ORDER(otAttack) INTO SRBMs
  unit SRBMs attack any {Ground, Naval} of ENEMY
  on TICK +SECONDS(30) StartBallisticMissiles()
     delete when "Stop BallisticMissiles " + SelfID
END

Counting objectives into a mission:

Mission "Arab royal families" SET SIZE_OF(VIPs)
on each destroyed any "VIP_KILL" Mission "Arab royal families" add 1

Escalation ladder on casualties:

BLOCK CheckCasualties()
  def int Casualties = GetFactionCasualties(SelfID)   // from LIB/Common.txt
  if (Casualties > 600000)
    throw "Global War"
  end
END

FOR AI
  on each TICK +SECONDS(10) CheckCasualties()
    delete when "Global War"
  on "Global War" StartGlobalWar()
END

Standard advisor message:

BLOCK StdMessage(int ID)
  Message UI_STRING(ID) Position TopLeft Portrait ADVISOR_PORTRAIT
END

Pitfalls checklist

Mistakes that load without complaint and show up only as a mission that doesn't behave.

  1. SELECT without INTO. The word can be left out, but then the first word after the expression is the result variable. If the variable is missing too, the first word of the next statement is swallowed as the variable. Always write INTO Set.
  2. Wrong number of arguments to a block. Too few is an error too: the missing parameters have no defined value.
  3. SIZE_OF(x) < 0 is always false; write <= 0.
  4. Custom event names must match exactly, and nothing warns you at run time when they don't. delete when "Nuclear Weapons Used" never matches a thrown "Nuclear Weapons Used China", and a typo such as "Stop Costal " must be repeated identically everywhere.
  5. Mission events need the MISSION keyword. delete when "Arabian peninsula" anything listens for a custom event named "Arabian peninsula", not the mission. Write delete when Mission "Arabian peninsula" anything.
  6. Copy-paste recursion. A self-rescheduling block such as StartAirstrikesNoCarriers() must re-schedule itself, not the block it was copied from.
  7. Overriding a block on purpose vs. by accident. Redeclaring a block name is allowed and overrides the earlier one, but check it was intentional: an accidental re-declaration (for example, an empty stub left above the real block) silently discards the real one.
  8. A return type without a return value. BLOCK int Name(…) must return a value on every path the caller relies on.
  9. Missing comma between parameters. The game reads (string MType int WRace), but write (string MType, int WRace).
  10. ForEach NewVar in Set without a type doesn't declare NewVar. Write ForEach unit NewVar in Set, or declare the variable first.
  11. ANYONE ELSE is a faction parameter, not an ELSE. It's fine, but keep it on the same line as ANYONE.
  12. Using a single = in a condition. Always compare with ==.
  13. GET_VICINITY_POINTS returns the target itself for points it couldn't place, and GET_RANDOM_POINTS_IN_REGION may return fewer points than asked. Check the result before spawning.
  14. Units created with CREATE_UNIT / CREATE_GROUP / TRANSFER_UNIT have AI on. Use SUSPEND AI FOR if a script controls them.
  15. Two FOR … END sections. FOR AI … END followed by FOR PLAYER … END looks natural, but the first END finishes the script and the rest is never parsed. Use switches inside one body.
  16. DEF after USE or BLOCK, or globals inside a USEd file. Globals always come first, and USE inlines blocks only: a USEd file that starts with DEF loads no blocks at all.
  17. THEN covers everything to its left. (A) or (B) or (C) THEN TICK +SECONDS(30) … waits 30 seconds after any of the three events, not only after C. Put parentheses around the part that should be delayed: (A) or (B) or ((C) THEN TICK +SECONDS(30)). See Event combination.
  18. The SELECT form of a function outside SELECT, or the ordinary form inside. DISTANCE(Start) measures from the tested unit only inside a SELECT; elsewhere it gives no value and needs DISTANCE(ThisBase, Start). Inside a SELECT, HAS_HOSTED(This, "Attack") reads This as the type. See SELECT functions.
  19. A variable named like a SELECT variable. Inside a SELECT, REGION==Region compares the unit's region with itself, whatever your Region holds.
  20. Built-in constants in the wrong case. In an expression true, false, E1_UNDEFINED, Ground and otAttack need their exact case; see Constants.
  21. Misspelt names that give a value anyway. STAT with an unknown name gives a meaningless number. HAS_HOSTED and MAX_HOSTED with an unknown unit type count every type.

Complete example

This is a small but complete faction script. The AI waits, reacts when the player crosses the border, escalates on losses and tracks a mission. The human player only gets a briefing message. Note the order: globals, then USE and blocks, then one main body with switches, then the final END.

// Scenario/MyCampaign/Mission-1/EVENTS/Red Army.txt
def set FrontCities = {CITY("Kiev"), CITY("Minsk")}   // store units, not names: no string -> unit conversion later
def int BasesLost = 0

USE "Scenario/LIB/Common.txt"
USE "Scenario/LIB/Invasion.txt"

BLOCK StdMessage(int ID)
  Message UI_STRING(ID) Position TopLeft Portrait ADVISOR_PORTRAIT
END

BLOCK CheckBorder(unit Intruder)
  if (TERRITORY(Intruder) == SelfID AND TYPE(Intruder) != "Spec_Ops_Team")
    throw "Phase 2" globally
  end
END

BLOCK StartPhase2()
  RESUME AI
  StdMessage(9001)

  def set Defenders
  select units OWNER==SelfID AND PRINCIPAL_TYPE=="Army_Division" into Defenders
  SimulateInvasionCitiesOnly(FrontCities, Defenders)     // from LIB/Invasion.txt
END

BLOCK OnBaseLost()
  BasesLost++
  Mission "Destroy bases" add 1
  if (BasesLost >= 3)
    throw "Global War" globally
  end
END

BLOCK CheckCasualties()
  if (GetFactionCasualties(SelfID) > 500000)             // from LIB/Common.txt
    throw "Global War" globally
  end
END

FOR AI
  SUSPEND AI
  DISABLE Missiles NUKE

  on each visible any {Ground, Naval} ->(unit U) of PlayerID CheckBorder(U)
    delete when "Phase 2"

  on "Phase 2" StartPhase2()
  on each destroyed any "Army_Base" OnBaseLost()
    delete when "Global War"

  on each TICK +SECONDS(10) CheckCasualties()
    delete when "Global War"

  on "Global War" ENABLE Missiles NUKE
  on Population less 20 Surrender

FOR PLAYER
  StdMessage(9000)
END