1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
use std::time::Duration;

use common_assets::AssetExt;
use rand::thread_rng;
use serde::{Deserialize, Serialize};
use tracing::error;
use vek::Vec3;

use crate::{
    comp::{item::Reagent, CharacterState, StateUpdate},
    event::TransformEvent,
    generation::{EntityConfig, EntityInfo},
    states::utils::{end_ability, tick_attack_or_default},
};

use super::{
    behavior::CharacterBehavior,
    utils::{AbilityInfo, StageSection},
};

#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum FrontendSpecifier {
    Evolve,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StaticData {
    /// How long until state has until transformation
    pub buildup_duration: Duration,
    /// How long the state has until exiting
    pub recover_duration: Duration,
    /// The entity configuration you will be transformed into
    pub target: String,
    pub ability_info: AbilityInfo,
    /// Whether players are allowed to transform
    pub allow_players: bool,
    /// Used to specify the transformation to the frontend
    pub specifier: Option<FrontendSpecifier>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Data {
    /// Struct containing data that does not change over the course of the
    /// character state
    pub static_data: StaticData,
    /// Timer for each stage
    pub timer: Duration,
    /// What section the character stage is in
    pub stage_section: StageSection,
}

impl CharacterBehavior for Data {
    fn behavior(
        &self,
        data: &super::behavior::JoinData,
        output_events: &mut crate::comp::character_state::OutputEvents,
    ) -> crate::comp::StateUpdate {
        let mut update = StateUpdate::from(data);
        match self.stage_section {
            StageSection::Buildup => {
                // Tick the timer as long as buildup hasn't finihsed
                if self.timer < self.static_data.buildup_duration {
                    update.character = CharacterState::Transform(Data {
                        static_data: self.static_data.clone(),
                        timer: tick_attack_or_default(data, self.timer, None),
                        ..*self
                    });
                // Buildup finished, start transformation
                } else {
                    let Ok(entity_config) = EntityConfig::load(&self.static_data.target) else {
                        error!(?self.static_data.target, "Failed to load entity configuration");
                        end_ability(data, &mut update);
                        return update;
                    };

                    let entity_info = EntityInfo::at(Vec3::zero()).with_entity_config(
                        entity_config.read().clone(),
                        Some(&self.static_data.target),
                        &mut thread_rng(),
                        None,
                    );

                    // Handle frontend events
                    if let Some(specifier) = self.static_data.specifier {
                        match specifier {
                            FrontendSpecifier::Evolve => {
                                output_events.emit_local(crate::event::LocalEvent::CreateOutcome(
                                    crate::outcome::Outcome::Explosion {
                                        pos: data.pos.0,
                                        power: 5.0,
                                        radius: 2.0,
                                        is_attack: false,
                                        reagent: Some(Reagent::White),
                                    },
                                ))
                            },
                        }
                    }

                    output_events.emit_server(TransformEvent {
                        target_entity: *data.uid,
                        entity_info,
                        allow_players: self.static_data.allow_players,
                    });
                    update.character = CharacterState::Transform(Data {
                        static_data: self.static_data.clone(),
                        timer: Duration::default(),
                        stage_section: StageSection::Recover,
                    });
                }
            },
            StageSection::Recover => {
                // Wait for recovery period to finish
                if self.timer < self.static_data.recover_duration {
                    update.character = CharacterState::Transform(Data {
                        static_data: self.static_data.clone(),
                        timer: tick_attack_or_default(data, self.timer, None),
                        ..*self
                    });
                } else {
                    // End the ability after recovery is done
                    end_ability(data, &mut update);
                }
            },
            _ => {
                // If we somehow ended up in an incorrect character state, end the ability
                end_ability(data, &mut update);
            },
        }

        update
    }
}