anvil/commands.rs
1//! `anvil-game.commands`: the commands a player's click on the unit panel
2//! would post, through the game's own queue, and the choice of an event
3//! option as its button makes it (anvil-game 1.17.0, service versions 1 and 2),
4//! and the game speed as the speed bar's buttons set it (anvil-game 1.22.0,
5//! version 3).
6//!
7//! **Who.** Only a plugin with `affects_gameplay = true`, and only while Anvil
8//! has not suspended it (ironman or multiplayer without the player's opt-in):
9//! otherwise [`ErrorCode::Unsupported`] or [`ErrorCode::Suspended`], and
10//! nothing reaches the game.
11//!
12//! **What.** Only the player's own units, as [`UnitRef`]s from
13//! [`World`](crate::world::World). A unit that is gone or another country's is
14//! [`ErrorCode::NotFound`]; one of the wrong kind, given twice, or a bad
15//! combination is [`ErrorCode::InvalidArgument`]. Nothing of such a call is
16//! posted.
17//!
18//! **When.** On the game's main thread after an outer frame, in a session, as
19//! for `World`; anywhere else, and during a hot-join,
20//! [`ErrorCode::WrongPhase`]. At most [`MAX_UNITS`] units a call and
21//! [`MAX_PER_FRAME`] commands a frame for all plugins together, above that
22//! [`ErrorCode::Limit`].
23//!
24//! **Posted is not done.** A posted command runs at the session's next turn
25//! of the queue on every machine; in multiplayer it is only on its way to the
26//! host. Read `World` a few frames later for the outcome.
27//!
28//! [`ErrorCode::Unsupported`]: crate::ErrorCode::Unsupported
29//! [`ErrorCode::Suspended`]: crate::ErrorCode::Suspended
30//! [`ErrorCode::NotFound`]: crate::ErrorCode::NotFound
31//! [`ErrorCode::InvalidArgument`]: crate::ErrorCode::InvalidArgument
32//! [`ErrorCode::WrongPhase`]: crate::ErrorCode::WrongPhase
33//! [`ErrorCode::Limit`]: crate::ErrorCode::Limit
34
35use std::fmt;
36use std::mem::size_of;
37
38use crate::error::{check, Result};
39use crate::host::Host;
40use crate::sys::{
41 AnvilGameCommand, AnvilGameCommandResult, AnvilGameCommandsService, AnvilGameUnitRef,
42 AnvilPlugin, ANVIL_GAME_COMMANDS_SERVICE_VERSION, ANVIL_GAME_COMMAND_DRILL,
43 ANVIL_GAME_COMMAND_EVENT_OPTION, ANVIL_GAME_COMMAND_EXPLORE, ANVIL_GAME_COMMAND_MAX_PER_FRAME,
44 ANVIL_GAME_COMMAND_MAX_UNITS, ANVIL_GAME_COMMAND_MERGE, ANVIL_GAME_COMMAND_MOVE,
45 ANVIL_GAME_COMMAND_QUEUE, ANVIL_GAME_COMMAND_SIEGE_AREA, ANVIL_GAME_COMMAND_SPEED,
46 ANVIL_GAME_COMMAND_SPLIT, ANVIL_GAME_COMMAND_START, ANVIL_GAME_COMMAND_SUPPRESS_AREA,
47 ANVIL_GAME_EXPLORE_CIRCUMNAVIGATE, ANVIL_GAME_EXPLORE_LAND, ANVIL_GAME_EXPLORE_STOP,
48};
49use crate::table::Table;
50use crate::world::UnitRef;
51
52/// The service's name.
53pub const SERVICE: &std::ffi::CStr = c"anvil-game.commands";
54/// The service's major version.
55pub const VERSION: u32 = ANVIL_GAME_COMMANDS_SERVICE_VERSION;
56/// The most units one call takes.
57pub const MAX_UNITS: usize = ANVIL_GAME_COMMAND_MAX_UNITS as usize;
58/// The most commands one frame takes, for all plugins together.
59pub const MAX_PER_FRAME: u32 = ANVIL_GAME_COMMAND_MAX_PER_FRAME;
60
61/// What one call posted.
62#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
63pub struct Posted {
64 /// Commands the session took (in multiplayer: sent to the host).
65 pub posted: u32,
66 /// Units already in the asked state: nothing posted for them.
67 pub skipped: u32,
68 /// Commands the session's own check refused; the service freed them.
69 pub refused: u32,
70}
71
72/// The `anvil-game.commands` service, for this plugin.
73#[derive(Clone, Copy)]
74pub struct Commands {
75 table: Table<AnvilGameCommandsService>,
76 plugin: *mut AnvilPlugin,
77 version: u32,
78}
79
80// SAFETY: the table lives for the process and its function may be called from
81// any thread (it answers WrongPhase off the main thread); the plugin handle is
82// Anvil's, valid for the process, and only passed back to it.
83unsafe impl Send for Commands {}
84// SAFETY: as for Send; the value is never written.
85unsafe impl Sync for Commands {}
86
87impl fmt::Debug for Commands {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 f.debug_struct("Commands")
90 .field("size", &self.table.size())
91 .finish()
92 }
93}
94
95fn raw_ref(unit: &UnitRef) -> AnvilGameUnitRef {
96 unit.to_raw()
97}
98
99impl Commands {
100 /// The service, posting for this plugin: the newest version anvil-game
101 /// has (3, 2, then 1); `None` without anvil-game 1.17.0 or on a game build
102 /// whose symbols for it are declared absent.
103 pub fn get(host: &Host) -> Option<Self> {
104 [VERSION, 2, 1].into_iter().find_map(|version| {
105 // SAFETY: the table type of anvil-game.commands; each version only appends.
106 let table = unsafe { host.service::<AnvilGameCommandsService>(SERVICE, version) }?;
107 Some(Self {
108 table,
109 plugin: host.raw_plugin(),
110 version,
111 })
112 })
113 }
114
115 /// The service version found: 2 chooses event options, 3 also sets the
116 /// game speed.
117 pub fn version(&self) -> u32 {
118 self.version
119 }
120
121 /// The C table, for what this crate does not wrap.
122 pub fn c_api(&self) -> Table<AnvilGameCommandsService> {
123 self.table
124 }
125
126 fn post(&self, kind: u32, flags: u32, units: &[UnitRef], what: &str) -> Result<Posted> {
127 self.post_with(kind, flags, units, 0, 0, what)
128 }
129
130 fn post_with(
131 &self,
132 kind: u32,
133 flags: u32,
134 units: &[UnitRef],
135 explore: i32,
136 province: i32,
137 what: &str,
138 ) -> Result<Posted> {
139 let raw: Vec<AnvilGameUnitRef> = units.iter().map(raw_ref).collect();
140 let command = AnvilGameCommand {
141 // Version 1 takes the fields up to `units` only.
142 size: if self.version >= 2 {
143 size_of::<AnvilGameCommand>()
144 } else {
145 std::mem::offset_of!(AnvilGameCommand, pending_event_id)
146 } as u32,
147 type_: kind,
148 flags,
149 // Over u32::MAX is over the limit too: the service answers Limit.
150 count: u32::try_from(raw.len()).unwrap_or(u32::MAX),
151 units: if raw.is_empty() {
152 std::ptr::null()
153 } else {
154 raw.as_ptr()
155 },
156 pending_event_id: 0,
157 option_index: 0,
158 speed: 0,
159 explore,
160 province,
161 };
162 self.send(&command, what, units.len())
163 }
164
165 fn send(&self, command: &AnvilGameCommand, what: &str, units: usize) -> Result<Posted> {
166 let f = function!(self.table, AnvilGameCommandsService, post)?;
167 let mut out = AnvilGameCommandResult {
168 size: size_of::<AnvilGameCommandResult>() as u32,
169 posted: 0,
170 skipped: 0,
171 refused: 0,
172 };
173 // SAFETY: this plugin's handle, a command whose units live until the
174 // call returns, and a result the service fills as far as its size says.
175 check(unsafe { f(self.plugin, command, &mut out) }, || {
176 format!("commands {what} ({units} units)")
177 })?;
178 Ok(Posted {
179 posted: out.posted,
180 skipped: out.skipped,
181 refused: out.refused,
182 })
183 }
184
185 /// Armies: start drilling (`start`) or stop. Only the armies not yet in
186 /// that state get a command; the others count as `skipped`.
187 pub fn drill(&self, armies: &[UnitRef], start: bool) -> Result<Posted> {
188 let flags = if start { ANVIL_GAME_COMMAND_START } else { 0 };
189 self.post(ANVIL_GAME_COMMAND_DRILL, flags, armies, "drill")
190 }
191
192 /// Two or more armies, or navies, in one province: merged into the first.
193 pub fn merge(&self, units: &[UnitRef]) -> Result<Posted> {
194 self.post(ANVIL_GAME_COMMAND_MERGE, 0, units, "merge")
195 }
196
197 /// One army or navy: split in half, rounded up, as the button does.
198 pub fn split(&self, unit: &UnitRef) -> Result<Posted> {
199 self.post(
200 ANVIL_GAME_COMMAND_SPLIT,
201 0,
202 std::slice::from_ref(unit),
203 "split",
204 )
205 }
206
207 /// Version 2: chooses `option` (the event file's order, from 0) of the
208 /// local player's pending event `pending_event_id`, as its button does.
209 /// `NotFound` without its event window, `InvalidArgument` for an option
210 /// without a button, `WrongPhase` while the button is disabled (the half
211 /// second after the window opens: try a frame later); `skipped` when the
212 /// window is already chosen, `refused` when the session would not take it.
213 /// `Unsupported` on version 1.
214 pub fn choose_event_option(&self, pending_event_id: i32, option: i32) -> Result<Posted> {
215 if self.version < 2 {
216 return Err(crate::Error::new(
217 crate::ErrorCode::Unsupported,
218 "commands event option: anvil-game.commands version 1",
219 ));
220 }
221 let command = AnvilGameCommand {
222 size: size_of::<AnvilGameCommand>() as u32,
223 type_: ANVIL_GAME_COMMAND_EVENT_OPTION,
224 flags: 0,
225 count: 0,
226 units: std::ptr::null(),
227 pending_event_id,
228 option_index: option,
229 speed: 0,
230 explore: 0,
231 province: 0,
232 };
233 self.send(&command, "event option", 0)
234 }
235
236 /// Version 3: sets the game speed to `speed` (1 the slowest .. 5), as that
237 /// many clicks on the speed bar's + or - would: one command a step.
238 /// `skipped` 1 at that speed already; `refused` 1 when the bar's buttons
239 /// would do nothing (the in-game menu is shown, or a multiplayer client
240 /// without admin rights); `InvalidArgument` outside 1..5. `Unsupported`
241 /// before version 3.
242 pub fn set_speed(&self, speed: i32) -> Result<Posted> {
243 if self.version < 3 {
244 return Err(crate::Error::new(
245 crate::ErrorCode::Unsupported,
246 "commands speed: anvil-game.commands before version 3",
247 ));
248 }
249 let command = AnvilGameCommand {
250 size: size_of::<AnvilGameCommand>() as u32,
251 type_: ANVIL_GAME_COMMAND_SPEED,
252 flags: 0,
253 count: 0,
254 units: std::ptr::null(),
255 pending_event_id: 0,
256 option_index: 0,
257 speed,
258 explore: 0,
259 province: 0,
260 };
261 self.send(&command, "speed", 0)
262 }
263
264 /// Version 3: armies (`Explore::Land`) or fleets (`Explore::Circumnavigate`)
265 /// start exploring, as the unit panel's button and the exploration dialog
266 /// do; `Explore::Stop` stops the units that explore. Units already in the
267 /// asked state count as `skipped`. The game checks each command when it
268 /// runs it. `Unsupported` before version 3.
269 pub fn explore(&self, units: &[UnitRef], how: Explore) -> Result<Posted> {
270 self.need_version_3("explore")?;
271 let mission = match how {
272 Explore::Stop => ANVIL_GAME_EXPLORE_STOP,
273 Explore::Land => ANVIL_GAME_EXPLORE_LAND,
274 Explore::Circumnavigate => ANVIL_GAME_EXPLORE_CIRCUMNAVIGATE,
275 };
276 self.post_with(
277 ANVIL_GAME_COMMAND_EXPLORE,
278 0,
279 units,
280 mission as i32,
281 0,
282 "explore",
283 )
284 }
285
286 /// Version 3: armies or fleets move to `province`, as a right-click on the
287 /// map does for a plain move: the path is replaced, or added to with
288 /// `queue` (as Shift). A move the game does not allow now counts as
289 /// `refused`. `Unsupported` before version 3.
290 pub fn move_to(&self, units: &[UnitRef], province: i32, queue: bool) -> Result<Posted> {
291 self.need_version_3("move")?;
292 let flags = if queue { ANVIL_GAME_COMMAND_QUEUE } else { 0 };
293 self.post_with(ANVIL_GAME_COMMAND_MOVE, flags, units, 0, province, "move")
294 }
295
296 /// Version 3: each army's click on the map area of `province` in the siege
297 /// map mode: the area joins the army's autonomous siege, or leaves it when
298 /// it is in it already. The game checks the area for each army and posts
299 /// the command itself; an army it says no for counts as `refused`.
300 /// `NotFound` for a province without a map area.
301 pub fn siege_area(&self, armies: &[UnitRef], province: i32) -> Result<Posted> {
302 self.need_version_3("siege area")?;
303 self.post_with(
304 ANVIL_GAME_COMMAND_SIEGE_AREA,
305 0,
306 armies,
307 0,
308 province,
309 "siege area",
310 )
311 }
312
313 /// Version 3: the same in the rebel-suppression map mode: the area joins
314 /// the army's rebel hunt, or leaves it.
315 pub fn suppress_area(&self, armies: &[UnitRef], province: i32) -> Result<Posted> {
316 self.need_version_3("suppress area")?;
317 self.post_with(
318 ANVIL_GAME_COMMAND_SUPPRESS_AREA,
319 0,
320 armies,
321 0,
322 province,
323 "suppress area",
324 )
325 }
326
327 fn need_version_3(&self, what: &str) -> Result<()> {
328 if self.version < 3 {
329 return Err(crate::Error::new(
330 crate::ErrorCode::Unsupported,
331 format!("commands {what}: anvil-game.commands before version 3"),
332 ));
333 }
334 Ok(())
335 }
336}
337
338/// What [`Commands::explore`] asks of the units.
339#[derive(Clone, Copy, Debug, PartialEq, Eq)]
340pub enum Explore {
341 /// Units that explore (land, sea or a circumnavigation) stop.
342 Stop,
343 /// Armies explore the land around them.
344 Land,
345 /// Fleets sail around the world.
346 Circumnavigate,
347}