use crate::defines::{LevelInt, MAX_MOVES}; use crate::dynamic_data::event_hooks::event_hook::Event; use crate::dynamic_data::libraries::dynamic_library::DynamicLibrary; use crate::dynamic_data::models::battle::Battle; use crate::dynamic_data::models::damage_source::DamageSource; use crate::dynamic_data::models::learned_move::{LearnedMove, MoveLearnMethod}; use crate::dynamic_data::script_handling::script::{Script, ScriptContainer}; use crate::dynamic_data::script_handling::script_set::ScriptSet; use crate::dynamic_data::script_handling::volatile_scripts::VolatileScripts; use crate::dynamic_data::script_handling::{ScriptSource, ScriptSourceData, ScriptWrapper}; use crate::static_data::items::item::Item; use crate::static_data::natures::Nature; use crate::static_data::species_data::ability::Ability; use crate::static_data::species_data::ability_index::AbilityIndex; use crate::static_data::species_data::form::Form; use crate::static_data::species_data::gender::Gender; use crate::static_data::species_data::species::Species; use crate::static_data::statistic_set::{ClampedStatisticSet, StatisticSet}; use crate::static_data::DataLibrary; use crate::utils::random::Random; use crate::{script_hook, PkmnResult, ScriptCategory, StringKey}; use parking_lot::RwLock; use std::sync::atomic::{AtomicI8, AtomicU32, AtomicU8, Ordering}; use std::sync::{Arc, Weak}; #[derive(Debug)] pub struct PokemonBattleData<'pokemon, 'library> { battle: *mut Battle<'pokemon, 'library>, battle_side_index: u8, index: u8, on_battle_field: bool, seen_opponents: Vec>>>, } impl<'pokemon, 'library> PokemonBattleData<'pokemon, 'library> { pub fn battle_mut(&mut self) -> Option<&mut Battle<'pokemon, 'library>> { unsafe { self.battle.as_mut() } } pub fn battle(&self) -> Option<&Battle<'pokemon, 'library>> { unsafe { self.battle.as_ref() } } pub fn battle_side_index(&self) -> u8 { self.battle_side_index } pub fn on_battle_field(&mut self) -> &mut bool { &mut self.on_battle_field } pub fn seen_opponents(&mut self) -> &mut Vec>>> { &mut self.seen_opponents } } #[derive(Debug)] pub struct Pokemon<'own, 'library> where 'own: 'library, { library: &'own DynamicLibrary, species: &'own Species, form: &'own Form, display_species: Option<&'own Species>, display_form: Option<&'own Form>, level: LevelInt, experience: AtomicU32, unique_identifier: u32, gender: Gender, coloring: u8, held_item: Option<&'own Item>, current_health: AtomicU32, weight: f32, height: f32, stat_boost: ClampedStatisticSet, flat_stats: StatisticSet, boosted_stats: StatisticSet, individual_values: ClampedStatisticSet, effort_values: ClampedStatisticSet, nature: &'own Nature, nickname: Option, ability_index: AbilityIndex, is_ability_overridden: bool, override_ability: Option, battle_data: Option>, moves: [Option>>; MAX_MOVES], allowed_experience: bool, types: Vec, is_egg: bool, is_caught: bool, held_item_trigger_script: ScriptContainer, ability_script: ScriptContainer, status_script: ScriptContainer, volatile: Arc>, script_source_data: RwLock, } impl<'own, 'library> Pokemon<'own, 'library> { pub fn new( library: &'own DynamicLibrary, species: &'own Species, form: &'own Form, ability: AbilityIndex, level: LevelInt, unique_identifier: u32, gender: Gender, coloring: u8, nature: &StringKey, ) -> Self { // Calculate experience from the level for the specified growth rate. let experience = library .static_data() .growth_rates() .calculate_experience(species.growth_rate(), level); let weight = form.weight(); let height = form.height(); let nature = library .static_data() .natures() .get_nature(nature) .unwrap_or_else(|| panic!("Unknown nature name was given: {}.", &nature)); let mut pokemon = Self { library, species, form, display_species: None, display_form: None, level, experience: AtomicU32::new(experience), unique_identifier, gender, coloring, held_item: None, current_health: AtomicU32::new(1), weight, height, stat_boost: Default::default(), flat_stats: Default::default(), boosted_stats: Default::default(), individual_values: Default::default(), effort_values: Default::default(), nature, nickname: None, ability_index: ability, is_ability_overridden: false, override_ability: None, battle_data: None, moves: [None, None, None, None], allowed_experience: false, types: form.types().to_vec(), is_egg: false, is_caught: false, held_item_trigger_script: ScriptContainer::default(), ability_script: ScriptContainer::default(), status_script: ScriptContainer::default(), volatile: Default::default(), script_source_data: Default::default(), }; pokemon.recalculate_flat_stats(); let health = pokemon.flat_stats().hp(); pokemon.current_health = AtomicU32::new(health); pokemon } pub fn library(&self) -> &'own DynamicLibrary { self.library } pub fn species(&self) -> &'own Species { self.species } pub fn form(&self) -> &'own Form { self.form } pub fn display_species(&self) -> &'own Species { if let Some(v) = self.display_species { v } else { self.species } } pub fn display_form(&self) -> &'own Form { if let Some(v) = self.display_form { v } else { self.form } } pub fn level(&self) -> LevelInt { self.level } pub fn experience(&self) -> u32 { self.experience.load(Ordering::Relaxed) } pub fn unique_identifier(&self) -> u32 { self.unique_identifier } pub fn gender(&self) -> Gender { self.gender } pub fn coloring(&self) -> u8 { self.coloring } pub fn held_item(&self) -> Option<&'own Item> { self.held_item } pub fn has_held_item(&self, name: &StringKey) -> bool { // Only true if we have an item, and the item name is the same as the requested item. if let Some(v) = self.held_item { return v.name() == name; } false } pub fn set_held_item(&mut self, item: &'own Item) { self.held_item = Some(item); } pub fn remove_held_item(&mut self) { self.held_item = None; } pub fn consume_held_item(&mut self) -> bool { if self.held_item.is_none() { return false; } let script = self.library.load_item_script(self.held_item.unwrap()).unwrap(); if script.is_none() { return false; } // TODO: the entire item use part. todo!(); } pub fn current_health(&self) -> u32 { self.current_health.load(Ordering::Relaxed) } pub fn max_health(&self) -> u32 { self.boosted_stats.hp() } pub fn weight(&self) -> f32 { self.weight } pub fn height(&self) -> f32 { self.height } pub fn nickname(&self) -> &Option { &self.nickname } pub fn real_ability(&self) -> &AbilityIndex { &self.ability_index } pub fn types(&self) -> &Vec { &self.types } pub fn learned_moves(&self) -> &[Option>>; MAX_MOVES] { &self.moves } pub fn status(&self) -> &ScriptContainer { &self.status_script } pub fn flat_stats(&self) -> &StatisticSet { &self.flat_stats } pub fn boosted_stats(&self) -> &StatisticSet { &self.boosted_stats } pub fn stat_boost(&self) -> &ClampedStatisticSet { &self.stat_boost } pub fn individual_values(&self) -> &ClampedStatisticSet { &self.individual_values } pub fn effort_values(&self) -> &ClampedStatisticSet { &self.effort_values } pub fn get_battle(&self) -> Option<&Battle<'own, 'library>> { if let Some(data) = &self.battle_data { Some(data.battle().unwrap()) } else { None } } pub fn get_battle_side_index(&self) -> Option { self.battle_data.as_ref().map(|data| data.battle_side_index) } pub fn get_battle_index(&self) -> Option { self.battle_data.as_ref().map(|data| data.index) } pub fn is_ability_overriden(&self) -> bool { self.is_ability_overridden } pub fn active_ability(&self) -> &Ability { if self.is_ability_overridden { if let Some(v) = &self.override_ability { return v; } } self.library .static_data() .abilities() .get(self.form.get_ability(self.ability_index)) .unwrap() } pub fn ability_script(&self) -> &ScriptContainer { &self.ability_script } pub fn seen_opponents(&self) -> Option<&Vec>>>> { if let Some(data) = &self.battle_data { Some(&data.seen_opponents) } else { None } } pub fn allowed_experience_gain(&self) -> bool { self.allowed_experience } pub fn nature(&self) -> &'own Nature { self.nature } pub fn recalculate_flat_stats(&mut self) { self.flat_stats = self.library.stat_calculator().calculate_flat_stats(self); self.recalculate_boosted_stats(); } pub fn recalculate_boosted_stats(&mut self) { self.boosted_stats = self.library.stat_calculator().calculate_boosted_stats(self); } pub fn change_species(&mut self, species: &'own Species, form: &'own Form) { self.species = species; self.form = form; // If the pokemon is genderless, but it's new species is not, we want to set its gender if self.gender != Gender::Genderless && species.gender_rate() < 0.0 { // If we're in battle, use the battle random for predictability if self.battle_data.is_some() { let battle_data = self.battle_data.as_mut().unwrap(); self.gender = species.get_random_gender(&mut battle_data.battle().unwrap().random().get_rng().lock().unwrap()); } else { // If we're not in battle, just use a new random. self.gender = species.get_random_gender(&mut Random::default()); } } // Else if the new species is genderless, but the pokemon has a gender, make the creature genderless. else if species.gender_rate() < 0.0 && self.gender != Gender::Genderless { self.gender = Gender::Genderless; } if let Some(battle_data) = &self.battle_data { if let Some(battle) = battle_data.battle() { battle.event_hook().trigger(Event::SpeciesChange { pokemon: self, species, form, }) } } } pub fn change_form(&mut self, form: &'own Form) { if std::ptr::eq(self.form, form) { return; } self.form = form; self.types.clear(); for t in form.types() { self.types.push(*t); } self.weight = form.weight(); self.height = form.height(); let ability_script = self .library .load_script(ScriptCategory::Ability, self.active_ability().name()) .unwrap(); if let Some(ability_script) = ability_script { self.ability_script.set(ability_script); // Ensure the ability script gets initialized with the parameters for the ability. self.ability_script() .get() .as_mut() .unwrap() .as_mut() .on_initialize(self.active_ability().parameters()) } else { self.ability_script.clear(); } let old_health = self.max_health(); self.recalculate_flat_stats(); let diff_health = (self.max_health() - old_health) as i32; if self.current_health() == 0 && (self.current_health() as i32) < -diff_health { self.current_health.store(0, Ordering::SeqCst); } else { self.current_health.fetch_add(diff_health as u32, Ordering::Acquire); } // TODO: consider form specific attacks? if let Some(battle_data) = &self.battle_data { if let Some(battle) = battle_data.battle() { battle.event_hook().trigger(Event::FormChange { pokemon: self, form }) } } } pub fn is_usable(&self) -> bool { !self.is_caught && !self.is_egg && !self.is_fainted() } pub fn is_fainted(&self) -> bool { self.current_health() == 0 } pub fn set_battle_data(&mut self, battle: *mut Battle<'own, 'library>, battle_side_index: u8) { if let Some(battle_data) = &mut self.battle_data { battle_data.battle = battle; battle_data.battle_side_index = battle_side_index; } else { self.battle_data = Some(PokemonBattleData { battle, battle_side_index, index: 0, on_battle_field: false, seen_opponents: Default::default(), }) } } pub fn set_on_battlefield(&mut self, value: bool) { if let Some(data) = &mut self.battle_data { data.on_battle_field = value; if !value { self.volatile.write().clear(); self.weight = self.form.weight(); self.height = self.form.height(); } } } pub fn set_battle_index(&mut self, index: u8) { if let Some(data) = &mut self.battle_data { data.index = index; } } pub fn is_on_battlefield(&self) -> bool { if let Some(data) = &self.battle_data { data.on_battle_field } else { false } } pub fn mark_opponent_as_seen(&mut self, pokemon: Weak>>) { if let Some(battle_data) = &mut self.battle_data { for seen_opponent in &battle_data.seen_opponents { if seen_opponent.ptr_eq(&pokemon) { return; } } battle_data.seen_opponents.push(pokemon); } } pub fn damage(&mut self, mut damage: u32, source: DamageSource) { if damage > self.current_health() { damage = self.current_health(); } if damage == 0 { return; } let new_health = self.current_health() - damage; if let Some(battle_data) = &self.battle_data { if let Some(battle) = battle_data.battle() { battle.event_hook().trigger(Event::Damage { pokemon: self, source, original_health: self.current_health(), new_health, }); // TODO: register history script_hook!(on_damage, self, self, source, self.current_health(), new_health); } } self.current_health.store(new_health, Ordering::SeqCst); if self.is_fainted() && damage > 0 { self.on_faint(source); } } pub fn on_faint(&mut self, source: DamageSource) { if self.battle_data.is_some() && self.battle_data.as_ref().unwrap().battle().is_some() { self.battle_data .as_ref() .unwrap() .battle() .unwrap() .event_hook() .trigger(Event::Faint { pokemon: self }); script_hook!(on_faint, self, self, source); script_hook!(on_remove, self,); let side_index = self.battle_data.as_ref().unwrap().battle_side_index; let index = self.battle_data.as_ref().unwrap().index; if !self .battle_data .as_ref() .unwrap() .battle() .unwrap() .can_slot_be_filled(side_index, index) { self.battle_data.as_mut().unwrap().battle_mut().unwrap().sides_mut()[side_index as usize] .mark_slot_as_unfillable(index); } self.battle_data .as_mut() .unwrap() .battle_mut() .unwrap() .validate_battle_state(); } } pub fn learn_move(&mut self, move_name: &StringKey, learn_method: MoveLearnMethod) { let move_pos = self.learned_moves().iter().position(|a| a.is_none()); if move_pos.is_none() { panic!("No more moves with an empty space found."); } let move_data = self.library.static_data().moves().get(move_name).unwrap(); self.moves[move_pos.unwrap()] = Some(Arc::new(LearnedMove::new(move_data, learn_method))); } } impl<'own, 'library> ScriptSource<'own> for Pokemon<'own, 'library> { fn get_script_count(&self) -> usize { let mut c = 3; if let Some(battle_data) = &self.battle_data { if let Some(battle) = battle_data.battle() { c += battle.sides()[battle_data.battle_side_index as usize].get_script_count(); } } c } fn get_script_source_data(&self) -> &RwLock { &self.script_source_data } fn get_own_scripts(&self, scripts: &mut Vec) { scripts.push((&self.held_item_trigger_script).into()); scripts.push((&self.ability_script).into()); scripts.push((&self.status_script).into()); scripts.push((&self.volatile).into()); } fn collect_scripts(&self, scripts: &mut Vec) { self.get_own_scripts(scripts); if let Some(battle_data) = &self.battle_data { if let Some(battle) = battle_data.battle() { battle.sides()[battle_data.battle_side_index as usize].collect_scripts(scripts); } } } } impl<'own, 'library> VolatileScripts<'own> for Pokemon<'own, 'library> { fn volatile_scripts(&self) -> &Arc> { &self.volatile } fn load_volatile_script(&self, key: &StringKey) -> PkmnResult>> { self.library.load_script(ScriptCategory::Pokemon, key) } } #[cfg(test)] pub mod test { use crate::dynamic_data::libraries::dynamic_library; use crate::dynamic_data::models::pokemon::Pokemon; use crate::static_data::libraries::data_library::DataLibrary; use crate::static_data::species_data::ability_index::AbilityIndex; use crate::static_data::species_data::gender::Gender; #[test] fn construct_pokemon() { let lib = dynamic_library::test::build(); let species = lib.static_data().species().get(&"foo".into()).unwrap(); let form = species.get_form(&"default".into()).unwrap(); let pokemon = Pokemon::new( &lib, species, form, AbilityIndex { hidden: false, index: 0, }, 10, 0, Gender::Male, 0, &"test_nature".into(), ); assert_eq!(pokemon.species.name(), &"foo".into()); assert_eq!(pokemon.form.name(), &"default".into()); } }