Skip to main content

Crate anvil

Crate anvil 

Source
Expand description

Safe Rust API for plugins of Anvil, the native plugin loader for Europa Universalis IV 1.37.5.

The crate sits on the raw bindings of anvil-sys and adds what the C ABI leaves to every plugin:

  • plugin!: exports anvil_plugin_load, creates the plugin with Plugin::load and turns an Error or a panic into the result Anvil rolls the plugin back on.
  • Every callback Anvil or the game calls through an adapter of this crate (mid hooks, block replacements, events, settings, panel clicks, work for the main thread) runs under catch_unwind: a panic is logged once per callback and never crosses the FFI.
  • Change is a handle whose Drop removes the change.
  • Typed wrappers of the services Anvil ships: game (anvil-game.game), world (anvil-game.world), camera (anvil-game.camera), panel (anvil-overlay.panel), benchmark (anvil.benchmark), map (anvil-map.modes), script (anvil-script.effects, anvil-script.day_end) and log_throttle (anvil-log-throttle.messages).

§Where unsafe stays

Host and service calls are safe. What reaches the game’s memory by address or puts raw bytes and pointers into it stays an unsafe fn with its contract: calling a hook’s next (the generated function types are unsafe extern "C" fn), Host::hook (a symbol id is a plain u32, so the caller ties it to its sym::<Name>Fn; with the FnSymbols of anvil gen --lang rust-sdk, Host::hook_symbol is the safe form), Host::function, Host::data, writing the mid-hook context (Cpu::regs_mut), byte patches, pointer swaps, call redirects, import replacements, changes at raw addresses, and publishing a raw payload (Host::publish_raw).

Service tables are Tables: a provider older than this crate has a shorter table, and the crate reads a function only when the table’s size covers it, never through a reference to the whole table.

§A plugin

use anvil::{Change, Host, Plugin};

#[allow(dead_code)]
mod sym {
    // anvil gen --lang rust symbols.toml writes this file (build.rs).
    pub const IDLE_EXIT: u32 = 0;
}

struct Hello {
    // Dropping a Change removes it; the plugin is kept for the process.
    _idle_exit: Change,
}

impl Plugin for Hello {
    fn load(host: &mut Host) -> anvil::Result<Self> {
        host.info(format_args!("hello from Rust on Anvil {}", host.anvil_version()));
        let log = *host;
        let idle_exit = host.mid_hook(sym::IDLE_EXIT, move |cpu| {
            log.info(format_args!("returning to the menu (rcx={:#x})", cpu.rcx));
        })?;
        Ok(Hello { _idle_exit: idle_exit })
    }
}

anvil::plugin!(Hello);

Versions: this crate has its own 0.x line; the source compatibility of Anvil’s ADR 0001 covers it from its 1.0.

Re-exports§

pub use anvil_sys as sys;

Modules§

benchmark
anvil.benchmark: the core’s service through which a plugin joins the start-up benchmark and reports its own fields (anvil_benchmark.h).
camera
anvil-game.camera: the game’s map camera (anvil-game 1.25.0), client state rather than game state. Only this client’s view moves, as with the player’s own keys and mouse; nothing goes to the game state or to the other players in multiplayer.
commands
anvil-game.commands: the commands a player’s click on the unit panel would post, through the game’s own queue, and the choice of an event option as its button makes it (anvil-game 1.17.0, service versions 1 and 2), and the game speed as the speed bar’s buttons set it (anvil-game 1.22.0, version 3).
game
anvil-game.game: the game’s main loop, sessions and date, and the events anvil-game publishes on the game’s main thread (anvil_game.h).
input
anvil-overlay.input: keys and mouse buttons for plugins, from the game window’s procedure, held back while the player types in the game or uses Anvil’s panel (anvil_input.h, anvil-overlay 1.18.0).
log_throttle
The service of the standard plugin anvil-log-throttle (anvil_log_throttle.h).
map
anvil-map.modes: map modes of the plugin’s own, each a button on the minimap’s list, a colour for each province and lines in the province’s tooltip (anvil_map.h).
panel
anvil-overlay.panel: a window of the plugin in Anvil’s overlay. The plugin hands over rows of text and buttons and the overlay draws them (anvil_panel.h).
script
The services of the standard plugin anvil-script (anvil_script.h).
world
anvil-game.world: the world of the running session, read straight from the game (anvil-game 1.11.0; modifiers, units and the selection 1.15.0; rulers, heirs, consorts, flags and variables 1.20.0; pending events, statistics and timed modifiers 1.21.0; diplomacy 1.22.0).

Macros§

plugin
Exports anvil_plugin_load for the plugin type: anvil::plugin!(MyPlugin); once, at the root of the plugin’s cdylib.

Structs§

Change
A change’s handle: dropping it removes the change; keep keeps the change for the rest of the process.
Cpu
The registers at a mid hook or block replacement, as SafetyHook saves them (AnvilCpuContext, 408 bytes). Reading is safe through Deref (cpu.rcx); writing is regs_mut. Valid only during the callback.
Error
A call that failed: its ErrorCode and what was called, e.g. “hook_function symbol 0: conflict with another change”.
Event
An event name with the type of its payload. Host::subscribe hands the handler a &P; Host::subscribe_raw takes any name.
FnSymbol
A function symbol together with its declared type: what anvil gen --lang rust-sdk writes as sym::typed::<NAME> for each function symbol of symbols.toml, from the same signature as sym::<Name>Fn. Host::hook_symbol takes it with a hook and a detour of that type, so a detour of another shape does not compile and the call needs no unsafe.
FunctionHook
A function hook, call redirect or import replacement, and the rest of its chain. It lives in a static, so the detour (a plain function the game calls) reaches next, and Anvil can write next into it before the change is enabled:
GameInfo
The running game executable.
Host
The host: Anvil’s table and this plugin’s handle. It is Copy: capture it in callbacks, or get it anywhere with Host::current once the plugin is loading.
Key
A key binding (settings.toml type key): the Windows virtual-key code in bits 0-7 with the modifiers above it; 0 is no binding.
PointerSwap
A pointer swap on a slot symbol, and the rest of its chain. Anvil rewrites previous whenever the chain changes, so it lives in a static.
Table
A C table that starts with uint32_t size: Anvil’s host table or a service’s. Its provider may be older than this crate, so its table may be shorter than T. Table keeps the pointer and the provider’s size and never makes a &T that reaches past them: the crate reads a field only when size covers it (the ANVIL_*_HAS macros of the C headers), and get hands out &T only for a table at least as long as T.
Tag
A country’s tag: three ASCII letters or digits, e.g. RUS.

Enums§

ErrorCode
Why Anvil or a service refused a call: an AnvilResult other than ANVIL_OK.
LogLevel
A log level of anvil.log.

Constants§

PLUGINS_LOADED
anvil.plugins_loaded: every plugin is processed. Payload none.
RESUMED
anvil.resumed: to the plugin itself, its changes are back in the game. Payload none.
SUSPENDED
anvil.suspended: to the plugin itself, its changes are out of the game (ironman, multiplayer). Payload none.

Traits§

FnPtr
A function pointer type the game can call: unsafe extern "C" fn(…) -> R with up to 12 arguments, as anvil gen --lang rust writes them (sym::<Name>Fn).
Payload
The payload of an event, read from the publisher’s pointer during the handler.
Plugin
A plugin: one value, created by plugin! when Anvil loads the DLL and kept for the life of the process.

Functions§

catch_panic
Runs body; a panic is logged as “what panicked (…)” and fallback is returned instead of unwinding. For function-hook detours and other plain functions the game calls directly, where no adapter of this crate stands between: a panic out of an extern "C" function aborts the game.

Type Aliases§

Result
The result of a host or service call.