#![deny(unsafe_op_in_unsafe_fn)]
#![warn(missing_docs, clippy::undocumented_unsafe_blocks)]
pub use anvil_sys as sys;
macro_rules! function {
($table:expr, $ty:ty, $field:ident) => {{
let table: &$ty = $table;
let present = table.size as usize
>= ::core::mem::offset_of!($ty, $field) + ::core::mem::size_of_val(&table.$field);
$crate::error::need(
if present { table.$field } else { None },
stringify!($field),
)
}};
}
mod change;
mod cpu;
mod error;
mod event;
mod fnptr;
mod host;
mod panic;
mod text;
pub mod benchmark;
pub mod commands;
pub mod game;
pub mod input;
pub mod log_throttle;
pub mod map;
pub mod panel;
pub mod script;
pub mod world;
#[cfg(test)]
mod tests;
pub use change::{Change, FunctionHook, PointerSwap};
pub use cpu::Cpu;
pub use error::{Error, ErrorCode, Result};
pub use event::{Event, Payload, PLUGINS_LOADED, RESUMED, SUSPENDED};
pub use fnptr::FnPtr;
pub use host::{GameInfo, Host, Key, LogLevel};
pub use panic::catch_panic;
pub use text::Tag;
pub trait Plugin: Sized + 'static {
fn load(host: &mut Host) -> Result<Self>;
}
#[macro_export]
macro_rules! plugin {
($plugin:ty) => {
#[unsafe(no_mangle)]
pub unsafe extern "C" fn anvil_plugin_load(
host: *const $crate::sys::AnvilHost,
plugin: *mut $crate::sys::AnvilPlugin,
) -> $crate::sys::AnvilResult {
unsafe { $crate::__private::load::<$plugin>(host, plugin) }
}
const _: $crate::sys::AnvilPluginLoadFn = anvil_plugin_load;
};
}
#[doc(hidden)]
pub mod __private {
use crate::sys::{
AnvilHost, AnvilPlugin, AnvilResult, ANVIL_API_VERSION, ANVIL_ERROR_INTERNAL,
ANVIL_ERROR_INVALID_ARGUMENT, ANVIL_ERROR_UNSUPPORTED, ANVIL_OK,
};
use crate::{host, panic, Host, LogLevel, Plugin};
pub unsafe fn load<P: Plugin>(
table: *const AnvilHost,
plugin: *mut AnvilPlugin,
) -> AnvilResult {
let Some(table) = (unsafe { table.as_ref() }) else {
return ANVIL_ERROR_INVALID_ARGUMENT;
};
if table.api_version != ANVIL_API_VERSION
|| !host::covers_api_2_0(table)
|| plugin.is_null()
{
return ANVIL_ERROR_UNSUPPORTED;
}
host::install(table, plugin);
panic::install_hook();
let mut host = Host::from_parts(table, plugin);
match panic::catch(|| P::load(&mut host)) {
Ok(Ok(loaded)) => {
std::mem::forget(loaded);
ANVIL_OK
}
Ok(Err(error)) => {
host.log(LogLevel::Error, format_args!("load() failed: {error}"));
error.code().result()
}
Err(message) => {
host.log(LogLevel::Error, format_args!("load() panicked: {message}"));
ANVIL_ERROR_INTERNAL
}
}
}
}