A script lets your mod react to what happens in a game: a war starts, a month ends, a player clicks a button your mod added. The game calls functions your script exports (hooks), and your script calls functions the game provides (host functions). A script can be a sandboxed WebAssembly (WASM) module or a C# DLL. Both get the same hooks and the same permission checks.
What a script can do
- React to events in the simulation through hooks.
- Read a country’s GDP, treasury, stability and manpower, and the date.
- Read the world: the list of countries, wars, alliances, province owners, event flags and variables.
- Change a treasury, set flags and variables, keep its own saved numbers, fire events.
- Found and change alliance organisations, and start or end a world ceasefire.
- Show popups and add lines to the end screen.
A core WASM module can call only the host functions listed on this page, and every call that changes the game needs a permission you declare in mod.json.
Runtimes and platforms
| Runtime | What you ship | Where it runs | Notes |
|---|---|---|---|
| Core WASM module | A .wasm file named by entrypoints.wasm | Windows and Linux | The default. Runs in the game’s built-in interpreter. |
| Component-model WASM | A .wasm component, plus "enableComponentRuntime": true | Windows and Linux | Opt-in. See Component-model modules. |
| C# DLL | Mods/*.dll in the mod folder | No platform check in the loader | Not sandboxed. See The C# path. |
On macOS the game does not run WASM modules. A mod that ships one loads data-only: its events, overrides, scenario and text work, its script does not run, and the MODS screen shows a warning that names the mod.
runtimePolicy in mod.json chooses which of a mod’s runtimes load:
| Value | Effect |
|---|---|
coexist | The default. The WASM module and the DLLs both load, and each is called for the hooks it handles. |
csharp_only | The mod’s WASM module is not loaded. |
wasm_only | The mod’s DLLs are not loaded. If any C# code is already listening to hooks when the WASM host starts, the host does not subscribe at all and reports a load error. |
Declaring a script in mod.json
{
"id": "com.example.warchest",
"displayName": "War Chest",
"version": "1.0.0",
"wasmAbiVersion": 4,
"permissions": ["WriteTreasury", "world.read"],
"entrypoints": {
"wasm": "Content/mod.wasm"
}
}
entrypoints.wasmis a path inside the mod folder. If it is missing or does not resolve, the game looks forscripts/main.wasm.wasmAbiVersionis the version of the script interface your module was built for. The game accepts 1 to 4, and 1 is the default. Each host function has a minimum version (the tables below say which need 4). A module that imports a function its declared version does not include fails to load, and the load error names the import.- A save made while the active mods declared a higher
wasmAbiVersiondoes not load under mods that declare a lower one. The other direction works.
Hooks
Export any of these functions and the game calls them. All are optional, and the game calls every one it finds whatever wasmAbiVersion you declare. Arguments are 32-bit integers unless noted. A country argument is a country handle (see Handles).
| Export | Arguments | When the game calls it |
|---|---|---|
on_init | none | Once, right after the module loads. No game world exists at this point, so world reads return neutral values. |
on_reload | none | Instead of on_init, when the module is reloaded into a running single-player game from the Mod Builder. |
on_game_tick | tick, year, month | Once per game tick (one in-game day). At high speed several ticks can pass in one frame; each gets its own call. |
on_economy_tick | year, month | Once per monthly economy tick. |
on_war_declared | attacker, defender, tick | A country declares war. |
on_peace_signed | proposer, target | A peace deal is signed. |
on_tech_researched | country, tech_index | A country completes a doctrine tier: tech_index is branch × 5 + (tier − 1). A node of a mod’s research track reports 64 + the node’s gate index. |
on_building_completed | province_id, building_def | A new building finishes, on the monthly economy tick. Upgrades are not reported. building_def is the building’s index in this game’s building table. |
on_event_fired | country, event_index | An event is queued for a country, whatever queued it, including a script’s fire_event. |
on_country_eliminated | country | A country is eliminated. |
on_province_captured | province_id, new_owner, old_owner | A province changes owner through a peace deal or an annexation event effect, once per province. Occupation in a war changes only who controls a province and does not raise it. |
on_alliance_formed | country1, country2 | An alliance is formed. country1 proposed it. |
on_alliance_broken | country1, country2 | A bilateral alliance ends: one side breaks it, one ally declares war on the other, or a call to arms is dishonoured. country1 ended it. |
on_trade_agreement_signed | country1, country2 | A trade agreement is signed. country1 proposed it. |
on_espionage_resolved | source, target, mission_type, state | A covert mission reaches an outcome. mission_type: 0 gather intelligence, 1 sabotage economy, 2 sabotage infrastructure, 3 steal technology, 4 counter-intelligence, 5 influence government, 6 satellite surveillance, 7 fund opposition. state: 1 success, 2 failed, 3 caught. |
on_game_ended | winner, victory_type, mod_row | The game ends, once. victory_type: 1 military hegemony, 2 economic superpower, 3 diplomatic leader, 4 technological ascendancy, 5 nuclear deterrence, 6 one of the scenario’s own endings. mod_row is that ending’s position among the scenario’s endings, or -1. |
on_ui_action | hook_name_ptr, hook_name_len, mod_id_ptr, mod_id_len | A button your mod added is clicked. Only the module of the mod that owns the button is called. |
Within one frame the order is: every on_game_tick for the ticks that passed, then the queued event hooks, then on_economy_tick. Hooks run on the main thread.
If a hook traps (for example an out-of-bounds memory access), the game logs one warning, lists one load error for the mod, and stops calling that module for the rest of the session.
on_ui_action writes into your memory. For a core module, the game copies the hook name and the mod id into the module’s linear memory starting at byte offset 4096 (hook name first, mod id directly after it) and passes those addresses. Keep that region free of your own data. A module whose memory is too small for the two strings does not get the call.
Hooks in multiplayer
Every hook except on_ui_action is raised by the simulation and runs the same way on every player’s game. A button click runs on_ui_action on the clicking player’s game only. In a multiplayer session, calls made from on_ui_action that would change the game are refused: the treasury functions, fire_event, fire_trigger, the flag, variable and state writes, and the diplomacy writes. The mod gets one warning in the log. log and the popup functions still work, because they only affect the local screen. Do not store a click and apply it later from a simulation hook: the stored click exists on one player’s game only. Single-player has no such limit.
Host functions
A core module imports these from the module name gp. The signature column uses the form result(arguments): i is a 32-bit integer, I a 64-bit integer, f a 32-bit float, F a 64-bit float, v no result. Declare an import with exactly the listed signature; any other signature fails to load, and the load error names the import.
A string argument is a (pointer, length) pair into your module’s memory: UTF-8, no terminator. Money is in US dollars. Stability runs from 0 to 100.
Basics (any wasmAbiVersion)
| Function | Signature | What it does | Permission |
|---|---|---|---|
log | v(ii) | (msg_ptr, msg_len): writes a line to the game log. | none |
get_tick | i() | The current game tick. | none |
get_year | i() | The current year. | none |
get_month | i() | The current month, 1 to 12. | none |
country_get_gdp | F(i) | (country): annual GDP. | none |
country_get_treasury | F(i) | (country): treasury. | none |
country_get_stability | f(i) | (country): stability. | none |
country_get_tech_level | i(i) | (country): number of completed doctrine tiers. | none |
get_country_manpower | I(i) | (country): available manpower, in people. | none |
country_set_treasury | v(iF) | (country, value): sets the treasury to value. | WriteTreasury |
add_treasury | v(if) | (country, amount): adds amount to the treasury. | WriteTreasury |
fire_event | v(iii) | (country, id_ptr, id_len): queues an event by id for that country. | FireTriggers |
fire_trigger | v(iii) | (trigger_type, source, target): raises a reactive event trigger between two countries. | FireTriggers |
show_mod_popup | v(iiii) | (title_ptr, title_len, body_ptr, body_len): shows a popup. | InjectUI |
A call that needs a permission the mod did not declare does nothing. fire_event and show_mod_popup also write a warning to the log.
The game also links older names for some of these: log_string v(i) (logs a fixed line and ignores its argument), get_current_tick, get_current_year, get_current_month, get_country_stability, the 32-bit forms get_country_gdp f(i) and get_country_treasury f(i), and get_country_manpower as i(i) (capped at the 32-bit range). Use the names in the table for new scripts.
fire_event looks the id up among the base game’s events and the events of every active mod. A match goes into that country’s event queue and runs like any other event. The event’s own conditions and cooldowns are not checked, because the script decided when it fires. Three rules still apply: an event whose target is player is refused for a country no human controls, an event that is already waiting in that country’s queue is not queued again, and a fire_once event is refused once it has fired. An unknown id is ignored, with a one-time warning in the log.
fire_trigger takes one of these trigger types: 0 war declared, 1 peace signed, 2 alliance formed, 3 alliance broken, 4 tech researched, 5 country collapse, 6 coup, 7 nuke launched, 8 sanction applied, 9 building completed, 10 leader death, 11 revolution, 12 espionage resolved.
World reads (wasmAbiVersion 4, permission world.read)
| Function | Signature | What it does |
|---|---|---|
country_count | i() | Number of countries in the game’s list. |
country_at | i(i) | (n): handle of the n-th country in ISO3 order, or -1. |
country_by_iso3 | i(ii) | (iso3_ptr, iso3_len): handle, or -1. |
country_iso3 | i(iii) | (country, out_ptr, cap): writes the ISO3 code to your buffer; returns the bytes needed, or -1. |
country_at_war_with | i(ii) | (a, b): 1 when the two are at war, else 0. |
country_allied_with | i(ii) | (a, b): 1 for a bilateral alliance or two members of the same collective-defence organisation, else 0. |
country_war_count | i(i) | (country): number of countries it is at war with. |
country_war_enemy | i(ii) | (country, n): handle of its n-th enemy in ISO3 order, or -1. |
province_owner | i(i) | (province_id): handle of the legal owner, or -1. |
province_controller | i(i) | (province_id): handle of the occupier if there is one, else the owner, or -1. |
country_has_flag | i(iii) | (country, name_ptr, name_len): 1 when the event flag is set, else 0. |
country_flag_age_months | i(iii) | (country, name_ptr, name_len): whole months since the flag was set, 0 for this month, -1 when not set. |
country_get_var | i(iii) | (country, name_ptr, name_len): the country’s event variable, 0 when never set. |
country_lifetime | I(ii) | (country, counter): a whole-campaign counter. 0 personnel lost, 1 regiments lost, 2 ships lost, 3 aircraft lost, 4 civilians affected, 5 provinces gained, 6 provinces lost, 7 wars won, 8 wars lost. |
state_get | i(ii) | (key_ptr, key_len): a number from the mod’s own saved state, 0 when never set. |
Flags and variables are the same per-country state that event files set and test, by the exact name the event file uses. Call these from a hook such as on_game_tick: from on_init there is no world and every read returns its neutral value.
State writes (wasmAbiVersion 4, permission flags.write)
| Function | Signature | What it does |
|---|---|---|
country_set_flag | i(iii) | (country, name_ptr, name_len): sets an event flag, stamped with the current tick. |
country_clear_flag | i(iii) | (country, name_ptr, name_len): clears a flag. Returns 1 only when the flag was set. |
country_set_var | i(iiii) | (country, name_ptr, name_len, value): sets an event variable. |
country_add_var | i(iiii) | (country, name_ptr, name_len, delta): adds to an event variable. |
state_set | i(iii) | (key_ptr, key_len, value): sets a number in the mod’s own saved state. |
state_add | i(iii) | (key_ptr, key_len, delta): adds to it. |
Each returns 1 when the write took effect and 0 when it was refused. A write applies at once, and a read later in the same hook sees it. Variables and state values are whole numbers kept within ±1,000,000,000. A country holds at most events.max_flags_per_country flags (64 in the base game) and the same number of variables, and a mod holds at most that many state keys.
The mod’s own state is saved with the game, synced in multiplayer, and starts empty in a new game. Another mod’s key of the same name is a different key. Event files reach the same store with "scope": "mod" on their variable effects and conditions, so an event can test a counter a script keeps.
Text by key (wasmAbiVersion 4)
| Function | Signature | What it does | Permission |
|---|---|---|---|
localize | i(iiii) | (key_ptr, key_len, out_ptr, cap): writes the key’s text in the player’s language to your buffer. | none |
format | i(iiiiii) | (key_ptr, key_len, args_ptr, args_len, out_ptr, cap): the same, with {0}, {1} and so on filled from the arguments. | none |
show_mod_popup_key | v(iiiiii) | (title_key_ptr, title_key_len, body_key_ptr, body_key_len, args_ptr, args_len): shows a popup whose title and body are keys, resolved in each player’s language. | inject_ui |
register_end_screen_row | i(iiii) | (label_key_ptr, label_key_len, value_ptr, value_len): adds a line to the end screen’s mod record. Returns 1 when added. | inject_ui |
Arguments are UTF-8 strings joined with a NUL byte, at most 32. A key that no string table defines comes back as the key itself. Do not branch on what localize or format return: the text differs by language, so a script that compares it would behave differently for two players in the same multiplayer game. show_mod_popup_key is safe from a simulation hook, because only the keys and arguments cross.
The value of an end-screen row says where its number comes from: lifetime.<counter> (for example lifetime.ships_lost, the player’s country), mod_state.<key> (the mod’s own state) or variable.<name> (an event variable of the player’s country). A mod can add at most 12 rows.
The text of show_mod_popup can also be a key. A title or body that is exactly a localization key (no spaces or commas, at least one dot inside) and is defined in a string table is shown as that key’s text. Anything else is shown as written.
Diplomacy writes (wasmAbiVersion 4, permission write_diplomacy)
| Function | Signature | What it does |
|---|---|---|
organization_create | i(iiii) | (id_ptr, id_len, collective_defence, founder): founds an alliance organisation with that country as first member. |
organization_join | i(iiii) | (id_ptr, id_len, country, force): makes the country a member. |
organization_leave | i(iii) | (id_ptr, id_len, country): removes the country. |
organization_invite | i(iiii) | (id_ptr, id_len, inviter, target): a member invites another country. |
world_ceasefire_start | i(iii) | (months, until_flag_ptr, until_flag_len): starts a world ceasefire. Months 0 means no end date; an empty flag means none. |
world_ceasefire_end | i() | Ends a running world ceasefire. |
Each returns 1 when the action ran and 0 when it did not. An organisation id is lower-case letters, digits and underscores. collective_defence and force are 0 or 1.
Handles
A country handle is the number hooks pass you and host functions take. It is valid for the current session only, and it differs between a multiplayer host and the other players. Do not store a handle in saved state. To remember a country, store its ISO3 code (country_iso3) or its position in country_at, and look the handle up again. A loop from 0 to country_count() visits every country in the same order for every player.
A handle that names no country reads as 0 (or -1 where the table says so) and turns a write into a no-op.
Strings and buffers
- The game checks every
(pointer, length)pair against your module’s memory before reading it. A string outside that memory is ignored, with a one-time warning in the log. The game reads at most 64 KB of any one string. - For a function that returns text (
country_iso3,localize,format) you pass a buffer as(out_ptr, cap). The game writes at mostcapbytes and returns the number of bytes the whole value needs. If that is larger thancap, call again with a bigger buffer. A buffer outside your memory gets nothing written and the call returns -1. - The game never frees memory in your module.
Permissions
Declare permissions in the permissions list of mod.json. Each has more than one accepted spelling.
| Permission | Also accepted | What it allows |
|---|---|---|
WriteTreasury | write_treasury | country_set_treasury, add_treasury |
FireTriggers | fire_triggers | fire_event, fire_trigger |
InjectUI | inject_ui | show_mod_popup, show_mod_popup_key, register_end_screen_row, and every interface file of the mod |
world.read | ReadWorld, read_world | The world reads and state_get |
flags.write | WriteFlags, write_flags | The flag, variable and state writes |
write_diplomacy | WriteDiplomacy | The organisation and world ceasefire functions |
ReadEconomy | read_economy | Nothing. The basic reads work without a permission. |
A core module that imports a world.read, flags.write, write_diplomacy or ABI 4 inject_ui function without declaring both the permission and "wasmAbiVersion": 4 fails to load, and the load error names the import and what is missing.
A minimal script
This AssemblyScript module logs when it loads and tops up the treasury of a country that declares war while short of money. Save it as mod.ts.
@external("gp", "log")
declare function gp_log(ptr: i32, len: i32): void;
@external("gp", "country_get_treasury")
declare function country_get_treasury(country: i32): f64;
@external("gp", "country_set_treasury")
declare function country_set_treasury(country: i32, value: f64): void;
function log(message: string): void {
const bytes = String.UTF8.encode(message);
gp_log(changetype<i32>(bytes), bytes.byteLength);
}
export function on_init(): void {
log("war chest script loaded");
}
export function on_war_declared(attacker: i32, defender: i32, tick: i32): void {
const treasury = country_get_treasury(attacker); // US dollars
if (treasury < 5.0e9) {
country_set_treasury(attacker, treasury + 1.0e10); // needs WriteTreasury
}
}
The script needs only "permissions": ["WriteTreasury"], and works with any wasmAbiVersion.
Building and deploying
-
Compile to a core WASM module. The example mod builds its AssemblyScript source with:
asc mod.ts --target release -o ../mod.wasm --runtime stub --use abort= --exportRuntime -
Put the
.wasmfile in the mod folder and name it inentrypoints.wasm. -
Set
wasmAbiVersionandpermissionsto match the functions you import. -
Run VALIDATE in the Mod Builder, then RELOAD & TEST.
In a running single-player game, the Mod Builder’s APPLY TO RUNNING GAME reloads a rebuilt module. The new module is loaded first and replaces the old one only if it loads; otherwise the previous one keeps running and the Mod Builder says why. Its memory and globals start fresh, and on_reload is called instead of on_init. Flags, variables and the mod’s saved state are untouched. C# DLLs are not reloaded this way.
The script file the game loads and every Mods/*.dll are part of the multiplayer lobby check. Players whose script files differ in any byte cannot join the same game, even when the mod’s id and version match.
The C# path
The game also loads compiled C# from a mod. Put the DLL directly in a Mods folder inside the mod folder (<mod folder>/Mods/YourMod.dll). There is no manifest entry for it.
At load, the game creates one instance of every public, non-abstract class in the DLL that implements IModEntrypoint and has a public constructor without parameters, then calls its Initialize(IModServices services). It calls Dispose() when the mods shut down.
using GlobalProtocol.Core.Mods;
public sealed class WarChestMod : ModBase
{
private const string ModId = "com.example.warchest";
protected override void OnInitialize(IModServices services)
{
ModHookBus.OnEconomyTick += OnMonth;
}
protected override void OnDispose()
{
ModHookBus.OnEconomyTick -= OnMonth;
}
protected override void OnWarDeclared(int attacker, int defender, int tick)
{
ModHookBus.ShowPopup(ModId, "War", "A war has started."); // needs InjectUI
}
private void OnMonth(int year, int month)
{
// runs once per monthly economy tick
}
}
- Hooks. Every hook is a static event on
ModHookBus(OnGameTick,OnWarDeclared,OnEconomyTick,OnProvinceCaptured,OnGameEndedand the rest, with the same arguments as the table above). The game’sModBasesubscribes eight of them for you as overridable methods:OnTick,OnWarDeclared,OnPeaceSigned,OnTechResearched,OnBuildingCompleted,OnEventFired,OnCountryEliminatedandOnUiAction. It wires no others, so subscribe to any other event yourself, as the example does.OnUiActionis raised for every mod’s buttons, so check themodIdargument. - Services. The
IModServicesobject passed toInitializecarries the mod’s id (ModId), the world reads (CountryCount,CountryAt,FindCountry,CountryIso3,AtWar,Allied,WarCount,WarEnemyAt,ProvinceOwner,ProvinceController,HasFlag,FlagAgeMonths,GetVariable,GetLifetime,GetState), the state writes (SetFlag,ClearFlag,SetVariable,AddVariable,SetState,AddState), the diplomacy writes (CreateOrganization,JoinOrganization,LeaveOrganization,InviteToOrganization,StartWorldCeasefire,EndWorldCeasefire) and text (Localize,Format,ShowPopupLocalized,RegisterEndScreenRow). They need the same permissions as the WASM functions. They work inside a hook; outside one they return neutral values. - Popups and events.
ModHookBus.ShowPopup(modId, title, body)needsInjectUI.ModHookBus.FireEvent(modId, countryIndex, eventId)needsFireTriggers. - SDK version.
managedSdkVersioninmod.jsonis optional. When present, its major number must match the game’s (the game provides 1.1), or the DLLs are skipped with a load error.
Limits of the C# path:
- It is not sandboxed. The DLL runs inside the game process.
- A loaded DLL cannot be unloaded or replaced while the game runs. After you rebuild it, restart the game.
- In the released game the DLL is interpreted rather than compiled ahead of time. Generic types from libraries outside the game’s supported set can fail at run time.
- A DLL whose assembly name is the name of one of the game’s own assemblies is skipped.
- In multiplayer, a flag, variable or state write made outside a simulation hook (from your own callback, for example) is refused, like a write from
OnUiAction.
The example mod compiles its C# against a small stub project in its sdk folder. The stub’s assembly is named GlobalProtocol.Core, so the compiled DLL binds to the game’s own types by name when it loads. The stub DLL itself is not shipped with the mod. Because the binding is by name, the stub must declare each type and member you call with the same name and signature as the game’s.
Component-model modules
The game can also load a WebAssembly component (for example C# compiled for WASI, as in the example mod’s Content/wasm-dotnet folder). Set "enableComponentRuntime": true in mod.json; without it a component is refused with a load error.
A component imports the host functions from an interface named globalprotocol:hooks/[email protected], with hyphens in place of underscores (country-get-gdp, show-mod-popup), and strings are component string values instead of pointer pairs. It exports its hooks from globalprotocol:hooks/[email protected], also hyphenated (on-init, on-game-tick, on-war-declared, on-peace-signed, on-tech-researched, on-building-completed, on-country-eliminated, on-event-fired, on-ui-action).
A component cannot be refused at load for a missing permission. A call it is not entitled to returns the neutral value, with one warning in RELOAD & TEST and the log.
Debugging
loglines go toPlayer.log, prefixed with[Mod:<your mod id>].- Load errors (an unsupported ABI version, an import with the wrong signature, a missing permission) show on the MODS screen and in the Mod Builder’s RELOAD & TEST, with the stage (
read,validate,parse,link,instantiate,init,run) and the import name where there is one. - A hook the module does not export is not an error.
- VALIDATE in the Mod Builder reports an unsupported
wasmAbiVersion, a permission that needs version 4, and an import that needs a newer version thanmod.jsondeclares.