PkmnLib_rs/src/dynamic_data/script_handling/mod.rs

525 lines
18 KiB
Rust
Executable File

use std::sync::{Arc, Weak};
use parking_lot::RwLock;
#[doc(inline)]
pub use item_script::*;
#[doc(inline)]
pub use script::*;
#[doc(inline)]
pub use script_set::*;
#[doc(inline)]
pub use volatile_scripts_owner::*;
/// Scripts that are used for item usage
mod item_script;
/// Scripts that are used to change how a battle functions.
mod script;
/// Collections of scripts.
mod script_set;
/// A trait to add volatile scripts to any object.
mod volatile_scripts_owner;
/// This macro runs a script function on a given ScriptSource, and all its parents. It will ensure
/// to only run the script function if it is not suppressed, and can take any amount of parameters.
#[macro_export]
macro_rules! script_hook {
($hook_name: ident, $source: ident, $($parameters: expr),*) => {
let mut aggregator = $source.get_script_iterator();
while let Some(script_container) = aggregator.get_next() {
let script = script_container.get();
if let Some(script) = script {
if let Some(script) = script.read().as_deref() {
if !script.is_suppressed() {
script.$hook_name($($parameters),*);
}
}
}
}
};
}
/// This macro runs a script function on all scripts in a Vec of scripts. It will ensure it only
/// runs the script function if it is not suppressed, and can take any amount of parameters.
#[macro_export]
macro_rules! run_scripts {
($hook_name: ident, $source: ident, $($parameters: expr),*) => {
for script in $source {
match script {
ScriptWrapper::Script(s) => {
if let Some(s) = s.upgrade() {
let s = s.read();
if let Some(s) = s.deref() {
if !s.is_suppressed() {
s.$hook_name($($parameters),*);
}
}
}
}
ScriptWrapper::Set(s) => {
if let Some(set) = s.upgrade() {
let current_scripts = set.get_owning_iterator();
for s in current_scripts {
if let Some(s) = s.get() {
let s = s.read();
if let Some(s) = s.deref() {
if !s.is_suppressed() && set.has(s.name()) {
s.$hook_name($($parameters),*);
}
}
}
}
}
}
}
}
};
}
/// The script source data is the basic data required for any script source.
#[derive(Default, Debug)]
pub struct ScriptSourceData {
/// Whether or not the data has been initialized yet.
is_initialized: bool,
/// A list that references all possible scripts on this source, and it's parents.
scripts: Vec<ScriptWrapper>,
}
/// A script source is a struct on which we can trigger scripts to be run from.
pub trait ScriptSource {
/// Gets an iterator over all the scripts that are relevant to this script source. If the data
/// has not been initialised, it will do so here.
fn get_script_iterator(&self) -> ScriptIterator {
let lock = self.get_script_source_data();
if !lock.read().is_initialized {
let mut data = lock.write();
data.scripts = Vec::with_capacity(self.get_script_count());
self.collect_scripts(&mut data.scripts);
data.is_initialized = true;
}
ScriptIterator::new(&lock.read().scripts as *const Vec<ScriptWrapper>)
}
/// The number of scripts that are expected to be relevant for this source. This generally is
/// the number of its own scripts + the number of scripts for any parents.
fn get_script_count(&self) -> usize;
/// Returns the underlying data required for us to be a script source.
fn get_script_source_data(&self) -> &RwLock<ScriptSourceData>;
/// This should add all scripts belonging to this source to the scripts Vec, disregarding its
/// potential parents.
fn get_own_scripts(&self, scripts: &mut Vec<ScriptWrapper>);
/// This should add all scripts that are relevant to the source the the scripts Vec, including
/// everything that belongs to its parents.
fn collect_scripts(&self, scripts: &mut Vec<ScriptWrapper>);
}
/// Enum to store both ScriptSets and sets in a single value.
#[derive(Debug)]
pub enum ScriptWrapper {
/// A reference to a single script.
Script(Weak<RwLock<Option<Arc<dyn Script>>>>),
/// A reference to a ScriptSet.
Set(Weak<ScriptSet>),
}
impl From<&ScriptContainer> for ScriptWrapper {
fn from(c: &ScriptContainer) -> Self {
ScriptWrapper::Script(Arc::downgrade(c.arc()))
}
}
impl From<&Arc<ScriptSet>> for ScriptWrapper {
fn from(c: &Arc<ScriptSet>) -> Self {
ScriptWrapper::Set(Arc::downgrade(c))
}
}
/// This struct allows for the iteration over scripts.
pub struct ScriptIterator {
/// A pointer to the vector of ScriptWrappers. This can be a pointer, as we know it remains valid
/// while we're using it.
scripts: *const Vec<ScriptWrapper>,
/// The current index in the scripts.
index: i32,
/// If we're currently inside a set, the current index inside the set.
set_index: i32,
}
impl ScriptIterator {
/// Instantiates an iterator.
pub fn new(scripts: *const Vec<ScriptWrapper>) -> Self {
Self {
scripts,
index: -1,
set_index: -1,
}
}
/// Move to the next valid value in the scripts.
fn increment_to_next_value(&mut self) -> bool {
if self.index != -1 {
let wrapper = unsafe { &(*self.scripts)[self.index as usize] };
if let ScriptWrapper::Set(set) = wrapper {
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;
}
}
}
}
self.index += 1;
let len = (unsafe { &*self.scripts }).len() as i32;
for index in self.index..len {
self.index = index;
let wrapper = unsafe { &self.scripts.as_ref().unwrap()[self.index as usize] };
if let ScriptWrapper::Set(s) = wrapper {
if let Some(set) = s.upgrade() {
if set.count() > 0 {
self.set_index = 0;
return true;
}
}
} else if let ScriptWrapper::Script(script) = wrapper {
if let Some(v) = script.upgrade() {
if let Some(..) = v.read().as_ref() {
return true;
}
}
}
}
false
}
/// Gets the next valid script. If none is found, returns None.
pub fn get_next(&mut self) -> Option<ScriptContainer> {
if !self.increment_to_next_value() {
return None;
}
unsafe {
return match &self.scripts.as_ref().unwrap()[self.index as usize] {
// increment_to_next_value
ScriptWrapper::Script(script) => Some(script.upgrade().unwrap().into()),
ScriptWrapper::Set(set) => {
let set = set.upgrade().unwrap();
let sc = set.at(self.set_index as usize);
return Some(sc);
}
};
}
}
/// Resets the iterator to the start.
pub fn reset(&mut self) {
self.index = -1;
self.set_index = -1;
}
}
#[cfg(test)]
mod tests {
use std::any::Any;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use crate::dynamic_data::script_handling::script::ScriptContainer;
use crate::StringKey;
use super::*;
pub struct TestScript {
name: StringKey,
is_marked_for_deletion: AtomicBool,
suppressed_count: AtomicUsize,
test_count: AtomicUsize,
}
impl TestScript {
fn new() -> Self {
Self {
name: StringKey::new("test".into()),
is_marked_for_deletion: Default::default(),
suppressed_count: AtomicUsize::new(0),
test_count: AtomicUsize::new(0),
}
}
fn new_with_name(name: &str) -> Self {
Self {
name: StringKey::new(name.into()),
is_marked_for_deletion: Default::default(),
suppressed_count: AtomicUsize::new(0),
test_count: AtomicUsize::new(0),
}
}
}
impl Script for TestScript {
fn name(&self) -> &StringKey {
&self.name
}
fn get_marked_for_deletion(&self) -> &AtomicBool {
&self.is_marked_for_deletion
}
fn get_suppressed_count(&self) -> &AtomicUsize {
&self.suppressed_count
}
fn add_suppression(&self) {}
fn remove_suppression(&self) {}
fn stack(&self) {
self.test_count.fetch_add(1, Ordering::SeqCst);
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
#[test]
fn script_aggregator_property_iterates_single_script() {
let script = ScriptContainer::new(Arc::new(TestScript::new()));
let scripts = vec![ScriptWrapper::from(&script)];
let mut aggregator = ScriptIterator::new(&scripts as *const Vec<ScriptWrapper>);
while let Some(v) = aggregator.get_next() {
v.get().unwrap().read().as_ref().unwrap().stack();
}
let a = script.get_as::<TestScript>();
assert_eq!(a.test_count.load(Ordering::Relaxed), 1);
}
#[test]
fn script_aggregator_property_iterates_single_script_with_resets() {
let script = ScriptContainer::new(Arc::new(TestScript::new()));
let scripts = vec![ScriptWrapper::from(&script)];
let mut aggregator = ScriptIterator::new(&scripts as *const Vec<ScriptWrapper>);
for i in 1..11 {
aggregator.reset();
while let Some(v) = aggregator.get_next() {
v.get().unwrap().read().as_ref().unwrap().stack();
}
let a = script.get_as::<TestScript>();
assert_eq!(a.test_count.load(Ordering::Relaxed), i);
}
}
#[test]
fn script_aggregator_property_iterates_three_script() {
let script1 = ScriptContainer::new(Arc::new(TestScript::new()));
let script2 = ScriptContainer::new(Arc::new(TestScript::new()));
let script3 = ScriptContainer::new(Arc::new(TestScript::new()));
let scripts = vec![
ScriptWrapper::from(&script1),
ScriptWrapper::from(&script2),
ScriptWrapper::from(&script3),
];
let mut aggregator = ScriptIterator::new(&scripts as *const Vec<ScriptWrapper>);
while let Some(v) = aggregator.get_next() {
v.get().unwrap().read().as_ref().unwrap().stack();
}
let a = script1.get_as::<TestScript>();
assert_eq!(a.test_count.load(Ordering::Relaxed), 1);
let a = script2.get_as::<TestScript>();
assert_eq!(a.test_count.load(Ordering::Relaxed), 1);
let a = script3.get_as::<TestScript>();
assert_eq!(a.test_count.load(Ordering::Relaxed), 1);
}
#[test]
fn script_aggregator_property_iterates_three_script_with_resets() {
let script1 = ScriptContainer::new(Arc::new(TestScript::new()));
let script2 = ScriptContainer::new(Arc::new(TestScript::new()));
let script3 = ScriptContainer::new(Arc::new(TestScript::new()));
let scripts = vec![
ScriptWrapper::from(&script1),
ScriptWrapper::from(&script2),
ScriptWrapper::from(&script3),
];
let mut aggregator = ScriptIterator::new(&scripts as *const Vec<ScriptWrapper>);
for i in 1..11 {
aggregator.reset();
while let Some(v) = aggregator.get_next() {
v.get().unwrap().read().as_ref().unwrap().stack();
}
let a = script1.get_as::<TestScript>();
assert_eq!(a.test_count.load(Ordering::Relaxed), i);
let a = script2.get_as::<TestScript>();
assert_eq!(a.test_count.load(Ordering::Relaxed), i);
let a = script3.get_as::<TestScript>();
assert_eq!(a.test_count.load(Ordering::Relaxed), i);
}
}
#[test]
fn script_aggregator_property_iterates_script_set() {
let set = Arc::new(ScriptSet::default());
set.add(Arc::new(TestScript::new_with_name("test_a")));
set.add(Arc::new(TestScript::new_with_name("test_b")));
set.add(Arc::new(TestScript::new_with_name("test_c")));
let scripts = vec![ScriptWrapper::from(&set)];
let mut aggregator = ScriptIterator::new(&scripts as *const Vec<ScriptWrapper>);
for i in 1..11 {
aggregator.reset();
while let Some(v) = aggregator.get_next() {
v.get().unwrap().read().as_ref().unwrap().stack();
}
let s = set.at(0);
let s = s.get_as::<TestScript>();
assert_eq!(s.test_count.load(Ordering::Relaxed), i);
assert_eq!(s.name().str(), "test_a");
let s = set.at(1);
let s = s.get_as::<TestScript>();
assert_eq!(s.test_count.load(Ordering::Relaxed), i);
assert_eq!(s.name().str(), "test_b");
let s = set.at(2);
let s = s.get_as::<TestScript>();
assert_eq!(s.test_count.load(Ordering::Relaxed), i);
assert_eq!(s.name().str(), "test_c");
}
}
#[test]
fn script_aggregator_property_iterates_script_set_when_removing_last() {
let set = Arc::new(ScriptSet::default());
set.add(Arc::new(TestScript::new_with_name("test_a")));
set.add(Arc::new(TestScript::new_with_name("test_b")));
set.add(Arc::new(TestScript::new_with_name("test_c")));
let scripts = vec![ScriptWrapper::from(&set)];
let mut aggregator = ScriptIterator::new(&scripts as *const Vec<ScriptWrapper>);
assert_eq!(
aggregator
.get_next()
.unwrap()
.get()
.unwrap()
.read()
.as_ref()
.unwrap()
.name()
.str(),
"test_a"
);
assert_eq!(
aggregator
.get_next()
.unwrap()
.get()
.unwrap()
.read()
.as_ref()
.unwrap()
.name()
.str(),
"test_b"
);
set.remove(&StringKey::new("test_c".into()));
assert!(aggregator.get_next().is_none());
}
#[test]
fn script_aggregator_property_iterates_script_set_when_removing_middle() {
let set = Arc::new(ScriptSet::default());
set.add(Arc::new(TestScript::new_with_name("test_a")));
set.add(Arc::new(TestScript::new_with_name("test_b")));
set.add(Arc::new(TestScript::new_with_name("test_c")));
let scripts = vec![ScriptWrapper::from(&set)];
let mut aggregator = ScriptIterator::new(&scripts as *const Vec<ScriptWrapper>);
assert_eq!(
aggregator
.get_next()
.unwrap()
.get()
.unwrap()
.read()
.as_ref()
.unwrap()
.name()
.str(),
"test_a"
);
set.remove(&StringKey::new("test_b".into()));
assert_eq!(
aggregator
.get_next()
.unwrap()
.get()
.unwrap()
.read()
.as_ref()
.unwrap()
.name()
.str(),
"test_c"
);
assert!(aggregator.get_next().is_none());
}
pub struct TestScriptSource {
pub data: RwLock<ScriptSourceData>,
pub script: ScriptContainer,
}
impl ScriptSource for TestScriptSource {
fn get_script_count(&self) -> usize {
1
}
fn get_script_source_data(&self) -> &RwLock<ScriptSourceData> {
&self.data
}
fn get_own_scripts(&self, scripts: &mut Vec<ScriptWrapper>) {
scripts.push((&self.script).into());
}
fn collect_scripts(&self, scripts: &mut Vec<ScriptWrapper>) {
self.get_own_scripts(scripts);
}
}
#[test]
fn script_source_set_script_then_rerun() {
let source = TestScriptSource {
data: RwLock::new(ScriptSourceData::default()),
script: ScriptContainer::default(),
};
let mut aggregator = source.get_script_iterator();
aggregator.reset();
assert!(aggregator.get_next().is_none());
aggregator.reset();
source.script.set(Arc::new(TestScript::new()));
assert!(aggregator.get_next().is_some());
}
#[test]
fn script_source_clear_script_then_rerun() {
let source = TestScriptSource {
data: RwLock::new(ScriptSourceData::default()),
script: ScriptContainer::default(),
};
let mut aggregator = source.get_script_iterator();
source.script.set(Arc::new(TestScript::new()));
assert!(aggregator.get_next().is_some());
aggregator.reset();
source.script.clear();
assert!(aggregator.get_next().is_none());
}
}