PkmnLib_rs/src/dynamic_data/script_handling/mod.rs

103 lines
3.0 KiB
Rust
Raw Normal View History

2022-06-03 14:35:18 +00:00
use crate::dynamic_data::script_handling::script::Script;
use crate::dynamic_data::script_handling::script_set::ScriptSet;
2022-06-06 11:54:59 +00:00
use std::sync::Weak;
2022-06-03 14:35:18 +00:00
pub mod item_script;
pub mod script;
pub mod script_set;
2022-06-06 11:54:59 +00:00
pub mod volatile_scripts;
2022-06-03 14:35:18 +00:00
#[macro_export]
macro_rules! script_hook {
($hook_name: ident, $source: ident, $($parameters: expr),*) => {
let mut aggregator = $source.get_script_iterator();
while let Some(script) = aggregator.get_next() {
if script.is_suppressed() {
continue;
}
script.$hook_name($($parameters),*);
}
};
}
pub trait ScriptSource {
fn get_script_iterator(&self) -> ScriptAggregator {
todo!()
}
fn get_script_count(&self);
}
2022-06-06 11:54:59 +00:00
pub enum ScriptWrapper {
Script(Weak<Box<dyn Script>>),
Set(Weak<ScriptSet>),
2022-06-03 14:35:18 +00:00
}
2022-06-06 11:54:59 +00:00
pub struct ScriptAggregator {
scripts: Vec<Option<ScriptWrapper>>,
2022-06-03 14:35:18 +00:00
size: i32,
index: i32,
set_index: i32,
}
2022-06-06 11:54:59 +00:00
impl ScriptAggregator {
pub fn new(scripts: Vec<Option<ScriptWrapper>>) -> Self {
2022-06-03 14:35:18 +00:00
let len = scripts.len();
Self {
scripts,
size: len as i32,
index: -1,
set_index: -1,
}
}
fn increment_to_next_value(&mut self) -> bool {
if self.index != -1 {
if let Some(wrapper) = &self.scripts[self.index as usize] {
if let ScriptWrapper::Set(set) = wrapper {
2022-06-06 11:54:59 +00:00
if let Some(set) = set.upgrade() {
self.set_index += 1;
if self.set_index as usize >= set.count() {
self.set_index = -1;
} else {
return true;
}
2022-06-03 14:35:18 +00:00
}
}
}
}
self.index += 1;
for index in self.index..self.size {
self.index = index;
if let Some(wrapper) = &self.scripts[index as usize] {
2022-06-06 11:54:59 +00:00
if let ScriptWrapper::Set(s) = wrapper {
if let Some(..) = s.upgrade() {
self.set_index = 0;
return true;
}
} else if let ScriptWrapper::Script(script) = wrapper {
if let Some(..) = script.upgrade() {
return true;
}
2022-06-03 14:35:18 +00:00
}
}
}
false
}
pub fn get_next(&mut self) -> Option<&Box<dyn Script>> {
if !self.increment_to_next_value() {
return None;
}
return match self.scripts[self.index as usize].as_ref().unwrap() {
2022-06-06 11:54:59 +00:00
// We can make this unsafe as we know there is a strong reference. This is validated in
// increment_to_next_value
ScriptWrapper::Script(script) => unsafe { Some(&*script.as_ptr()) },
ScriptWrapper::Set(set) => unsafe {
let r = (&*set.as_ptr()).at(self.set_index as usize);
Some(r.as_ref())
},
2022-06-03 14:35:18 +00:00
};
}
}