78 lines
2.7 KiB
Rust
78 lines
2.7 KiB
Rust
use crate::ffi::{ExternPointer, IdentifiablePointer, NativeResult, OwnedPtr};
|
|
use crate::static_data::{Ability, AbilityImpl, EffectParameter};
|
|
use crate::StringKey;
|
|
use anyhow::anyhow;
|
|
use std::ffi::{c_char, CStr, CString};
|
|
use std::ptr::drop_in_place;
|
|
use std::sync::Arc;
|
|
|
|
/// Instantiates a new ability.
|
|
#[no_mangle]
|
|
unsafe extern "C" fn ability_new(
|
|
name: *const c_char,
|
|
effect: *const c_char,
|
|
parameters: *const OwnedPtr<EffectParameter>,
|
|
parameters_length: usize,
|
|
) -> NativeResult<IdentifiablePointer<Arc<dyn Ability>>> {
|
|
let parameters = std::slice::from_raw_parts(parameters, parameters_length);
|
|
let mut parameters_vec: Vec<EffectParameter> = Vec::with_capacity(parameters_length);
|
|
for parameter in parameters {
|
|
parameters_vec.push(*Box::from_raw(*parameter));
|
|
}
|
|
|
|
let name: StringKey = match CStr::from_ptr(name).to_str() {
|
|
Ok(s) => s.into(),
|
|
Err(_) => return NativeResult::err(anyhow!("Failed to convert name to CStr")),
|
|
};
|
|
let effect: StringKey = match CStr::from_ptr(effect).to_str() {
|
|
Ok(s) => s.into(),
|
|
Err(_) => return NativeResult::err(anyhow!("Failed to convert effect to CStr")),
|
|
};
|
|
|
|
let arc: Arc<dyn Ability> = Arc::new(AbilityImpl::new(&name, &effect, parameters_vec));
|
|
NativeResult::ok(arc.into())
|
|
}
|
|
|
|
/// Drops a reference counted ability.
|
|
#[no_mangle]
|
|
unsafe extern "C" fn ability_drop(ptr: OwnedPtr<Arc<dyn Ability>>) {
|
|
drop_in_place(ptr)
|
|
}
|
|
|
|
/// The name of the ability.
|
|
#[no_mangle]
|
|
unsafe extern "C" fn ability_name(ptr: ExternPointer<Arc<dyn Ability>>) -> NativeResult<OwnedPtr<c_char>> {
|
|
match CString::new(ptr.as_ref().name().str()) {
|
|
Ok(s) => NativeResult::ok(s.into_raw()),
|
|
Err(_) => NativeResult::err(anyhow!("Failed to convert name to CString")),
|
|
}
|
|
}
|
|
|
|
/// The name of the script effect of the ability.
|
|
#[no_mangle]
|
|
unsafe extern "C" fn ability_effect(ptr: ExternPointer<Arc<dyn Ability>>) -> NativeResult<OwnedPtr<c_char>> {
|
|
match CString::new(ptr.as_ref().effect().str()) {
|
|
Ok(s) => NativeResult::ok(s.into_raw()),
|
|
Err(_) => NativeResult::err(anyhow!("Failed to convert effect to CString")),
|
|
}
|
|
}
|
|
|
|
/// The length of the parameters for the script effect of the ability.
|
|
#[no_mangle]
|
|
unsafe extern "C" fn ability_parameter_length(ptr: ExternPointer<Arc<dyn Ability>>) -> usize {
|
|
ptr.as_ref().parameters().len()
|
|
}
|
|
|
|
/// Gets a parameter for the script effect of the ability.
|
|
#[no_mangle]
|
|
unsafe extern "C" fn ability_parameter_get(
|
|
ptr: ExternPointer<Arc<dyn Ability>>,
|
|
index: usize,
|
|
) -> IdentifiablePointer<EffectParameter> {
|
|
if let Some(p) = ptr.as_ref().parameters().get(index) {
|
|
(p as *const EffectParameter).into()
|
|
} else {
|
|
IdentifiablePointer::none()
|
|
}
|
|
}
|