use std::fmt;
use std::mem::size_of;
use crate::error::{check, Result};
use crate::host::Host;
use crate::sys::{
AnvilGameCommand, AnvilGameCommandResult, AnvilGameCommandsService, AnvilGameUnitRef,
AnvilPlugin, ANVIL_GAME_COMMANDS_SERVICE_VERSION, ANVIL_GAME_COMMAND_DRILL,
ANVIL_GAME_COMMAND_EVENT_OPTION, ANVIL_GAME_COMMAND_MAX_PER_FRAME,
ANVIL_GAME_COMMAND_MAX_UNITS, ANVIL_GAME_COMMAND_MERGE, ANVIL_GAME_COMMAND_SPLIT,
ANVIL_GAME_COMMAND_START, ANVIL_GAME_UNIT_ARMY, ANVIL_GAME_UNIT_NAVY,
};
use crate::world::{UnitKind, UnitRef};
pub const SERVICE: &std::ffi::CStr = c"anvil-game.commands";
pub const VERSION: u32 = ANVIL_GAME_COMMANDS_SERVICE_VERSION;
pub const MAX_UNITS: usize = ANVIL_GAME_COMMAND_MAX_UNITS as usize;
pub const MAX_PER_FRAME: u32 = ANVIL_GAME_COMMAND_MAX_PER_FRAME;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Posted {
pub posted: u32,
pub skipped: u32,
pub refused: u32,
}
#[derive(Clone, Copy)]
pub struct Commands {
table: &'static AnvilGameCommandsService,
plugin: *mut AnvilPlugin,
version: u32,
}
unsafe impl Send for Commands {}
unsafe impl Sync for Commands {}
impl fmt::Debug for Commands {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Commands")
.field("size", &self.table.size)
.finish()
}
}
fn raw_ref(unit: &UnitRef) -> AnvilGameUnitRef {
AnvilGameUnitRef {
id: unit.id,
country: unit
.country
.map(|tag| tag.to_raw())
.unwrap_or(crate::sys::AnvilGameTag { text: [0; 4] }),
kind: match unit.kind {
UnitKind::Army => ANVIL_GAME_UNIT_ARMY,
UnitKind::Navy => ANVIL_GAME_UNIT_NAVY,
UnitKind::Other(other) => other,
},
}
}
impl Commands {
pub fn get(host: &Host) -> Option<Self> {
[VERSION, 1].into_iter().find_map(|version| {
let table = unsafe { host.service::<AnvilGameCommandsService>(SERVICE, version) }?;
Some(Self {
table,
plugin: host.raw_plugin(),
version,
})
})
}
pub fn version(&self) -> u32 {
self.version
}
pub fn c_api(&self) -> &'static AnvilGameCommandsService {
self.table
}
fn post(&self, kind: u32, flags: u32, units: &[UnitRef], what: &str) -> Result<Posted> {
let raw: Vec<AnvilGameUnitRef> = units.iter().map(raw_ref).collect();
let command = AnvilGameCommand {
size: if self.version >= 2 {
size_of::<AnvilGameCommand>()
} else {
std::mem::offset_of!(AnvilGameCommand, pending_event_id)
} as u32,
type_: kind,
flags,
count: u32::try_from(raw.len()).unwrap_or(u32::MAX),
units: if raw.is_empty() {
std::ptr::null()
} else {
raw.as_ptr()
},
pending_event_id: 0,
option_index: 0,
};
self.send(&command, what, units.len())
}
fn send(&self, command: &AnvilGameCommand, what: &str, units: usize) -> Result<Posted> {
let f = function!(self.table, AnvilGameCommandsService, post)?;
let mut out = AnvilGameCommandResult {
size: size_of::<AnvilGameCommandResult>() as u32,
posted: 0,
skipped: 0,
refused: 0,
};
check(unsafe { f(self.plugin, command, &mut out) }, || {
format!("commands {what} ({units} units)")
})?;
Ok(Posted {
posted: out.posted,
skipped: out.skipped,
refused: out.refused,
})
}
pub fn drill(&self, armies: &[UnitRef], start: bool) -> Result<Posted> {
let flags = if start { ANVIL_GAME_COMMAND_START } else { 0 };
self.post(ANVIL_GAME_COMMAND_DRILL, flags, armies, "drill")
}
pub fn merge(&self, units: &[UnitRef]) -> Result<Posted> {
self.post(ANVIL_GAME_COMMAND_MERGE, 0, units, "merge")
}
pub fn split(&self, unit: &UnitRef) -> Result<Posted> {
self.post(
ANVIL_GAME_COMMAND_SPLIT,
0,
std::slice::from_ref(unit),
"split",
)
}
pub fn choose_event_option(&self, pending_event_id: i32, option: i32) -> Result<Posted> {
if self.version < 2 {
return Err(crate::Error::new(
crate::ErrorCode::Unsupported,
"commands event option: anvil-game.commands version 1",
));
}
let command = AnvilGameCommand {
size: size_of::<AnvilGameCommand>() as u32,
type_: ANVIL_GAME_COMMAND_EVENT_OPTION,
flags: 0,
count: 0,
units: std::ptr::null(),
pending_event_id,
option_index: option,
};
self.send(&command, "event option", 0)
}
}