dota-gsi 0.5.0

Game State Integration with Dota 2 in Rust. Provides a server that listens for events sent by Dota 2.
Documentation
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use std::collections::HashMap;
use std::fmt;

use serde::{Deserialize, Serialize, de, de::Error, ser};
use thiserror;

use super::{PlayerID, Team};

#[cfg(feature = "diff")]
use crate::diff::Diffable;
#[cfg(feature = "diff")]
use crate::event::{Ability as AbilityEvent, GameEvent};

#[derive(thiserror::Error, Debug)]
pub enum AbilitiesError {
    #[error("failed to parse ability ID number in `{0}`")]
    ParseIDError(String),
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Ability {
    pub name: String,
    pub level: u8,
    pub can_cast: bool,
    pub passive: bool,
    pub ability_active: bool,
    pub cooldown: u16,
    pub ultimate: bool,
}

impl fmt::Display for Ability {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut cd_status = String::from("");

        if self.can_cast && !self.passive {
            cd_status.push_str("READY");
        } else if self.passive {
            cd_status.push_str("PASSIVE");
        } else {
            let cd_str = format!("IN CD: {}s", self.cooldown);
            cd_status.push_str(&cd_str);
        }

        write!(f, "{} level {}, {}", self.name, self.level, cd_status)
    }
}

#[cfg(feature = "diff")]
impl Diffable for Ability {
    fn diff<'a>(&'a self, new: &'a Self) -> Vec<GameEvent> {
        let mut events = Vec::new();

        if self.level < new.level {
            events.push(GameEvent::AbilityEvent(AbilityEvent::LevelledUp(new.level)));
        }

        match (self.can_cast, new.can_cast) {
            (true, false) => events.push(GameEvent::AbilityEvent(AbilityEvent::WentOnCooldown(
                new.cooldown,
            ))),
            (false, true) => events.push(GameEvent::AbilityEvent(AbilityEvent::WentOffCooldown)),
            _ => {}
        }

        match (self.ability_active, new.ability_active) {
            (true, false) => events.push(GameEvent::AbilityEvent(AbilityEvent::Deactivated)),
            (false, true) => events.push(GameEvent::AbilityEvent(AbilityEvent::Activated)),
            _ => {}
        }

        events
    }
}

#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct AbilityID(pub u8);

impl<'de> Deserialize<'de> for AbilityID {
    fn deserialize<D>(deserializer: D) -> Result<AbilityID, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let mut slot_split = s.split("ability").map(|s| s.parse::<u8>());

        if let (_, Some(index)) = (slot_split.next(), slot_split.next()) {
            return Ok(AbilityID(index.expect("failed to parse ID")));
        }

        Err(D::Error::custom(AbilitiesError::ParseIDError(s)))
    }
}

impl Serialize for AbilityID {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: ser::Serializer,
    {
        serializer.serialize_str(&format!("ability{}", self.0))
    }
}

#[derive(Deserialize, Debug, Clone, PartialEq, Serialize)]
#[serde(untagged)]
pub enum GameAbilities {
    Spectating(HashMap<Team, HashMap<PlayerID, HashMap<AbilityID, Ability>>>),
    Playing(HashMap<AbilityID, Ability>),
}

#[cfg(feature = "diff")]
impl Diffable for GameAbilities {
    fn diff<'a>(&'a self, new: &'a Self) -> Vec<GameEvent> {
        let mut events = Vec::new();

        match (self, new) {
            (GameAbilities::Spectating(current), GameAbilities::Spectating(new)) => {
                for (team, players) in current.iter() {
                    let Some(team_new) = new.get(team) else {
                        continue;
                    };

                    for (player_id, abilities) in players.iter() {
                        let Some(abilities_new) = team_new.get(player_id) else {
                            continue;
                        };

                        for (ability_id, ability) in abilities.iter() {
                            let Some(ability_new) = abilities_new.get(ability_id) else {
                                continue;
                            };

                            events.extend(ability.diff(ability_new));
                        }
                    }
                }
            }
            (GameAbilities::Playing(abilities), GameAbilities::Playing(abilities_new)) => {
                for (ability_id, ability) in abilities.iter() {
                    let Some(ability_new) = abilities_new.get(ability_id) else {
                        continue;
                    };
                    events.extend(ability.diff(ability_new));
                }
            }
            (_, _) => panic!("cannot mix playing and spectating state"),
        }

        events
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    #[test]
    fn test_abilities_deserialize() {
        let json_str = r#"[{
          "ability_active": true,
          "can_cast": true,
          "cooldown": 0,
          "level": 4,
          "name": "marci_grapple",
          "passive": false,
          "ultimate": false
        },
        {
          "ability_active": true,
          "can_cast": true,
          "cooldown": 0,
          "level": 1,
          "name": "marci_companion_run",
          "passive": false,
          "ultimate": false
        },
        {
          "ability_active": true,
          "can_cast": true,
          "cooldown": 0,
          "level": 1,
          "name": "marci_guardian",
          "passive": false,
          "ultimate": false
        },
        {
          "ability_active": true,
          "can_cast": true,
          "cooldown": 0,
          "level": 1,
          "name": "marci_unleash",
          "passive": false,
          "ultimate": true
        },
        {
          "ability_active": true,
          "can_cast": true,
          "cooldown": 0,
          "level": 1,
          "name": "plus_high_five",
          "passive": false,
          "ultimate": false
        },
        {
          "ability_active": true,
          "can_cast": true,
          "cooldown": 0,
          "level": 1,
          "name": "plus_guild_banner",
          "passive": false,
          "ultimate": false
        }
      ]"#;
        let abilities: Vec<Ability> =
            serde_json::from_str(json_str).expect("Failed to deserialize Abilities");

        assert_eq!(abilities.len(), 6);
        assert!(abilities.iter().all(|a| a.ability_active));
        assert!(abilities.iter().all(|a| a.can_cast));
        assert!(
            abilities
                .iter()
                .any(|a| a.name == "plus_guild_banner".to_owned())
        );
        assert!(
            abilities
                .iter()
                .any(|a| a.name == "marci_unleash".to_owned())
        );
    }

    pub(crate) fn make_ability(level: u8, can_cast: bool, cooldown: u16, active: bool) -> Ability {
        Ability {
            name: "test_ability".to_string(),
            level,
            can_cast,
            passive: false,
            ability_active: active,
            cooldown,
            ultimate: false,
        }
    }

    #[test]
    fn test_ability_no_change() {
        let ability = make_ability(1, true, 0, true);
        let events = ability.diff(&ability.clone());
        assert!(events.is_empty());
    }

    #[test]
    fn test_ability_level_up() {
        let prev = make_ability(1, true, 0, true);
        let cur = make_ability(2, true, 0, true);
        let events = prev.diff(&cur);
        assert_eq!(
            events,
            vec![GameEvent::AbilityEvent(AbilityEvent::LevelledUp(2))]
        );
    }

    #[test]
    fn test_ability_level_up_multiple() {
        let prev = make_ability(1, true, 0, true);
        let cur = make_ability(4, true, 0, true);
        let events = prev.diff(&cur);
        assert_eq!(
            events,
            vec![GameEvent::AbilityEvent(AbilityEvent::LevelledUp(4))]
        );
    }

    #[test]
    fn test_ability_went_on_cooldown() {
        let prev = make_ability(1, true, 0, true);
        let cur = make_ability(1, false, 12, true);
        let events = prev.diff(&cur);
        assert_eq!(
            events,
            vec![GameEvent::AbilityEvent(AbilityEvent::WentOnCooldown(12))]
        );
    }

    #[test]
    fn test_ability_went_off_cooldown() {
        let prev = make_ability(1, false, 5, true);
        let cur = make_ability(1, true, 0, true);
        let events = prev.diff(&cur);
        assert_eq!(
            events,
            vec![GameEvent::AbilityEvent(AbilityEvent::WentOffCooldown)]
        );
    }

    #[test]
    fn test_ability_still_on_cooldown_no_event() {
        let prev = make_ability(1, false, 10, true);
        let cur = make_ability(1, false, 5, true);
        let events = prev.diff(&cur);
        assert!(events.is_empty());
    }

    #[test]
    fn test_ability_activated() {
        let prev = make_ability(1, true, 0, false);
        let cur = make_ability(1, true, 0, true);
        let events = prev.diff(&cur);
        assert_eq!(
            events,
            vec![GameEvent::AbilityEvent(AbilityEvent::Activated)]
        );
    }

    #[test]
    fn test_ability_deactivated() {
        let prev = make_ability(1, true, 0, true);
        let cur = make_ability(1, true, 0, false);
        let events = prev.diff(&cur);
        assert_eq!(
            events,
            vec![GameEvent::AbilityEvent(AbilityEvent::Deactivated)]
        );
    }

    #[test]
    fn test_ability_multiple_events_simultaneous() {
        let prev = make_ability(1, true, 0, true);
        let cur = make_ability(2, false, 8, true);
        let events = prev.diff(&cur);
        assert_eq!(
            events,
            vec![
                GameEvent::AbilityEvent(AbilityEvent::LevelledUp(2)),
                GameEvent::AbilityEvent(AbilityEvent::WentOnCooldown(8)),
            ]
        );
    }

    #[test]
    fn test_game_abilities_playing_no_change() {
        let mut abilities = HashMap::new();
        abilities.insert(AbilityID(0), make_ability(1, true, 0, true));
        abilities.insert(AbilityID(1), make_ability(2, false, 5, true));

        let prev = GameAbilities::Playing(abilities.clone());
        let cur = GameAbilities::Playing(abilities);
        let events = prev.diff(&cur);
        assert!(events.is_empty());
    }

    #[test]
    fn test_game_abilities_playing_one_levels_up() {
        let mut prev_abilities = HashMap::new();
        prev_abilities.insert(AbilityID(0), make_ability(1, true, 0, true));
        prev_abilities.insert(AbilityID(1), make_ability(2, true, 0, true));

        let mut cur_abilities = HashMap::new();
        cur_abilities.insert(AbilityID(0), make_ability(2, true, 0, true));
        cur_abilities.insert(AbilityID(1), make_ability(2, true, 0, true));

        let prev = GameAbilities::Playing(prev_abilities);
        let cur = GameAbilities::Playing(cur_abilities);
        let events = prev.diff(&cur);
        assert_eq!(
            events,
            vec![GameEvent::AbilityEvent(AbilityEvent::LevelledUp(2))]
        );
    }

    #[test]
    fn test_game_abilities_playing_new_ability_ignored() {
        let mut prev_abilities = HashMap::new();
        prev_abilities.insert(AbilityID(0), make_ability(1, true, 0, true));

        let mut cur_abilities = HashMap::new();
        cur_abilities.insert(AbilityID(0), make_ability(1, true, 0, true));
        cur_abilities.insert(AbilityID(1), make_ability(1, true, 0, true));

        let prev = GameAbilities::Playing(prev_abilities);
        let cur = GameAbilities::Playing(cur_abilities);
        let events = prev.diff(&cur);
        assert!(events.is_empty());
    }

    #[test]
    fn test_game_abilities_spectating_one_player_levels_up() {
        let mut radiant_prev = HashMap::new();
        let mut player0_abilities = HashMap::new();
        player0_abilities.insert(AbilityID(0), make_ability(1, true, 0, true));
        radiant_prev.insert(PlayerID(0), player0_abilities);

        let mut radiant_cur = HashMap::new();
        let mut player0_abilities_new = HashMap::new();
        player0_abilities_new.insert(AbilityID(0), make_ability(2, true, 0, true));
        radiant_cur.insert(PlayerID(0), player0_abilities_new);

        let mut prev_map = HashMap::new();
        prev_map.insert(Team::Radiant, radiant_prev);
        let mut cur_map = HashMap::new();
        cur_map.insert(Team::Radiant, radiant_cur);

        let prev = GameAbilities::Spectating(prev_map);
        let cur = GameAbilities::Spectating(cur_map);
        let events = prev.diff(&cur);
        assert_eq!(
            events,
            vec![GameEvent::AbilityEvent(AbilityEvent::LevelledUp(2))]
        );
    }

    #[test]
    fn test_game_abilities_spectating_missing_team_no_panic() {
        let mut prev_map = HashMap::new();
        let mut radiant = HashMap::new();
        let mut abilities_map = HashMap::new();
        abilities_map.insert(AbilityID(0), make_ability(1, true, 0, true));
        radiant.insert(PlayerID(0), abilities_map);
        prev_map.insert(Team::Radiant, radiant);

        // New state has no Radiant team
        let cur_map = HashMap::new();

        let prev = GameAbilities::Spectating(prev_map);
        let cur = GameAbilities::Spectating(cur_map);
        let events = prev.diff(&cur);
        assert!(events.is_empty());
    }

    #[test]
    fn test_game_abilities_spectating_missing_player_no_panic() {
        let mut radiant_prev = HashMap::new();
        let mut p0_abilities = HashMap::new();
        p0_abilities.insert(AbilityID(0), make_ability(1, true, 0, true));
        radiant_prev.insert(PlayerID(0), p0_abilities);

        // New state has the team but not the player
        let radiant_cur: HashMap<PlayerID, HashMap<AbilityID, Ability>> = HashMap::new();

        let mut prev_map = HashMap::new();
        prev_map.insert(Team::Radiant, radiant_prev);
        let mut cur_map = HashMap::new();
        cur_map.insert(Team::Radiant, radiant_cur);

        let prev = GameAbilities::Spectating(prev_map);
        let cur = GameAbilities::Spectating(cur_map);
        let events = prev.diff(&cur);
        assert!(events.is_empty());
    }

    #[test]
    #[should_panic(expected = "cannot mix playing and spectating state")]
    fn test_game_abilities_mixed_mode_panics() {
        let abilities = HashMap::new();
        let playing = GameAbilities::Playing(abilities);
        let spectating = GameAbilities::Spectating(HashMap::new());
        playing.diff(&spectating);
    }
}