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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
use std::time::Duration;

use hashbrown::HashMap;
use serde::{Deserialize, Serialize};
use specs::{
    storage::GenericWriteStorage, Component, DerefFlaggedStorage, Entities, Read, ReadStorage,
    WriteStorage,
};

use crate::{
    comp::{Alignment, CharacterState, Health, Pos},
    consts::{MAX_INTERACT_RANGE, MAX_MOUNT_RANGE},
    link::{Is, Link, LinkHandle, Role},
    uid::{IdMaps, Uid},
};

#[derive(Serialize, Deserialize, Debug)]
pub struct Interactor;

impl Role for Interactor {
    type Link = Interaction;
}

#[derive(Default, Serialize, Deserialize, Debug, Clone)]
pub struct Interactors {
    interactors: HashMap<Uid, LinkHandle<Interaction>>,
}

impl Interactors {
    pub fn get(&self, uid: Uid) -> Option<&LinkHandle<Interaction>> { self.interactors.get(&uid) }

    pub fn iter(&self) -> impl Iterator<Item = &LinkHandle<Interaction>> {
        self.interactors.values()
    }

    pub fn has_interaction(&self, kind: InteractionKind) -> bool {
        self.iter().any(|i| i.kind == kind)
    }
}

impl Component for Interactors {
    type Storage = DerefFlaggedStorage<Interactors>;
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum InteractionKind {
    HelpDowned,
    Pet,
}

// TODO: Do we want to use this for sprite interactions too?
#[derive(Serialize, Deserialize, Debug)]
pub struct Interaction {
    pub interactor: Uid,
    pub target: Uid,
    pub kind: InteractionKind,
}

#[derive(Debug)]
pub enum InteractionError {
    NoSuchEntity,
    NotInteractable,
    CannotInteract,
}

pub fn can_help_downed(pos: Pos, target_pos: Pos, target_health: Option<&Health>) -> bool {
    let within_distance = pos.0.distance_squared(target_pos.0) <= MAX_INTERACT_RANGE.powi(2);
    let consumed_death_protection =
        target_health.map_or(false, |health| health.has_consumed_death_protection());

    within_distance && consumed_death_protection
}

pub fn can_pet(pos: Pos, target_pos: Pos, target_alignment: Option<&Alignment>) -> bool {
    let within_distance = pos.0.distance_squared(target_pos.0) <= MAX_MOUNT_RANGE.powi(2);
    let valid_alignment = matches!(
        target_alignment,
        Some(Alignment::Owned(_) | Alignment::Tame)
    );

    within_distance && valid_alignment
}

impl Link for Interaction {
    type CreateData<'a> = (
        Read<'a, IdMaps>,
        WriteStorage<'a, Is<Interactor>>,
        WriteStorage<'a, Interactors>,
        WriteStorage<'a, CharacterState>,
        ReadStorage<'a, Health>,
        ReadStorage<'a, Pos>,
        ReadStorage<'a, Alignment>,
    );
    type DeleteData<'a> = (
        Read<'a, IdMaps>,
        WriteStorage<'a, Is<Interactor>>,
        WriteStorage<'a, Interactors>,
        WriteStorage<'a, CharacterState>,
    );
    type Error = InteractionError;
    type PersistData<'a> = (
        Read<'a, IdMaps>,
        Entities<'a>,
        ReadStorage<'a, Health>,
        ReadStorage<'a, Is<Interactor>>,
        ReadStorage<'a, Interactors>,
        ReadStorage<'a, CharacterState>,
        ReadStorage<'a, Pos>,
        ReadStorage<'a, Alignment>,
    );

    fn create(
        this: &crate::link::LinkHandle<Self>,
        (id_maps, is_interactors, interactors, character_states, healths, positions, alignments): &mut Self::CreateData<
            '_,
        >,
    ) -> Result<(), Self::Error> {
        let entity = |uid: Uid| id_maps.uid_entity(uid);

        if this.interactor == this.target {
            // Can't interact with itself
            Err(InteractionError::NotInteractable)
        } else if let Some(interactor) = entity(this.interactor)
            && let Some(target) = entity(this.target)
        {
            // Can only interact with one thing at a time.
            if !is_interactors.contains(interactor)
                && character_states
                    .get(interactor)
                    .map_or(true, |state| state.can_interact())
                && let Some(pos) = positions.get(interactor)
                && let Some(target_pos) = positions.get(target)
                && match this.kind {
                    InteractionKind::HelpDowned => {
                        can_help_downed(*pos, *target_pos, healths.get(target))
                    },
                    InteractionKind::Pet => can_pet(*pos, *target_pos, alignments.get(target)),
                }
            {
                if let Some(mut character_state) = character_states.get_mut(interactor) {
                    let (buildup_duration, use_duration, recover_duration) = this.kind.durations();
                    *character_state = CharacterState::Interact(crate::states::interact::Data {
                        static_data: crate::states::interact::StaticData {
                            buildup_duration,
                            use_duration,
                            recover_duration,
                            interact: crate::states::interact::InteractKind::Entity {
                                target: this.target,
                                kind: this.kind,
                            },
                            was_wielded: character_state.is_wield(),
                            was_sneak: character_state.is_stealthy(),
                            required_item: None,
                        },
                        timer: Duration::default(),
                        stage_section: crate::states::utils::StageSection::Buildup,
                    });

                    let _ = is_interactors.insert(interactor, this.make_role());
                    if let Some(mut interactors) = interactors.get_mut_or_default(target) {
                        interactors
                            .interactors
                            .insert(this.interactor, this.clone());
                    } else {
                        return Err(InteractionError::CannotInteract);
                    }

                    Ok(())
                } else {
                    Err(InteractionError::CannotInteract)
                }
            } else {
                Err(InteractionError::CannotInteract)
            }
        } else {
            Err(InteractionError::NoSuchEntity)
        }
    }

    fn persist(
        this: &crate::link::LinkHandle<Self>,
        (
            id_maps,
            entities,
            healths,
            is_interactors,
            interactors,
            character_states,
            positions,
            alignments,
        ): &mut Self::PersistData<'_>,
    ) -> bool {
        let entity = |uid: Uid| id_maps.uid_entity(uid);
        let is_alive =
            |entity| entities.is_alive(entity) && healths.get(entity).map_or(true, |h| !h.is_dead);

        if let Some(interactor) = entity(this.interactor)
            && let Some(target) = entity(this.target)
            && is_interactors.contains(interactor)
            && let Some(interactors) = interactors.get(target)
            && interactors.interactors.contains_key(&this.interactor)
            && is_alive(interactor)
            && is_alive(target)
            && let Some(pos) = positions.get(interactor)
            && let Some(target_pos) = positions.get(target)
            && match this.kind {
                InteractionKind::HelpDowned => {
                    can_help_downed(*pos, *target_pos, healths.get(target))
                },
                InteractionKind::Pet => can_pet(*pos, *target_pos, alignments.get(target)),
            }
            && let Some(CharacterState::Interact(crate::states::interact::Data {
                static_data:
                    crate::states::interact::StaticData {
                        interact:
                            crate::states::interact::InteractKind::Entity {
                                target: state_target,
                                kind: state_kind,
                            },
                        ..
                    },
                ..
            })) = character_states.get(interactor)
            && *state_target == this.target
            && *state_kind == this.kind
        {
            true
        } else {
            false
        }
    }

    fn delete(
        this: &crate::link::LinkHandle<Self>,
        (id_maps, is_interactors, interactors, character_states): &mut Self::DeleteData<'_>,
    ) {
        let entity = |uid: Uid| id_maps.uid_entity(uid);

        let interactor = entity(this.interactor);
        let target = entity(this.target);

        interactor.map(|interactor| is_interactors.remove(interactor));
        target.map(|target| {
            if let Some(mut i) = interactors.get_mut(target) {
                i.interactors.remove(&this.interactor);

                if i.interactors.is_empty() {
                    interactors.remove(target);
                }
            }
        });

        // yay pattern matching 🦀
        if let Some(character_state) = interactor
            .and_then(|interactor| character_states.get_mut(interactor))
            .as_deref_mut()
            && let CharacterState::Interact(crate::states::interact::Data {
                static_data:
                    crate::states::interact::StaticData {
                        interact:
                            ref mut interact @ crate::states::interact::InteractKind::Entity {
                                target: state_target,
                                kind: state_kind,
                                ..
                            },
                        ..
                    },
                ..
            }) = *character_state
            && state_target == this.target
            && state_kind == this.kind
        {
            // If the character state we created with this link still persists, the target
            // has become invalid so we set it to that. And the character state decides how
            // it handles that, be it ending or something else.
            *interact = crate::states::interact::InteractKind::Invalid;
        }
    }
}