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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
use rosu_map::section::general::GameMode;

use crate::{any::difficulty::ModsDependent, model::mods::GameMods, Difficulty};

use super::{converted::Converted, Beatmap};

/// Summary struct for a [`Beatmap`]'s attributes.
#[derive(Clone, Debug, PartialEq)]
pub struct BeatmapAttributes {
    /// The approach rate.
    pub ar: f64,
    /// The overall difficulty.
    pub od: f64,
    /// The circle size.
    pub cs: f64,
    /// The health drain rate
    pub hp: f64,
    /// The clock rate with respect to mods.
    pub clock_rate: f64,
    /// The hit windows for approach rate and overall difficulty.
    pub hit_windows: HitWindows,
}

/// AR and OD hit windows
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct HitWindows {
    /// Hit window for approach rate i.e. `TimePreempt` in milliseconds.
    pub ar: f64,
    /// Hit window for overall difficulty i.e. time to hit a 300 ("Great") in milliseconds.
    pub od: f64,
}

/// A builder for [`BeatmapAttributes`] and [`HitWindows`].
#[derive(Clone, Debug, PartialEq)]
#[must_use]
pub struct BeatmapAttributesBuilder {
    mode: GameMode,
    is_convert: bool,
    ar: ModsDependentKind,
    od: ModsDependentKind,
    cs: ModsDependentKind,
    hp: ModsDependentKind,
    mods: GameMods,
    clock_rate: Option<f64>,
}

impl BeatmapAttributesBuilder {
    const OSU_MIN: f64 = 80.0;
    const OSU_AVG: f64 = 50.0;
    const OSU_MAX: f64 = 20.0;

    const TAIKO_MIN: f64 = 50.0;
    const TAIKO_AVG: f64 = 35.0;
    const TAIKO_MAX: f64 = 20.0;

    /// Create a new [`BeatmapAttributesBuilder`].
    ///
    /// The mode will be `GameMode::Osu` and attributes are set to `5.0`.
    pub const fn new() -> Self {
        Self {
            mode: GameMode::Osu,
            is_convert: false,
            ar: ModsDependentKind::DEFAULT,
            od: ModsDependentKind::DEFAULT,
            cs: ModsDependentKind::DEFAULT,
            hp: ModsDependentKind::DEFAULT,
            mods: GameMods::DEFAULT,
            clock_rate: None,
        }
    }

    /// Use the given [`Beatmap`]'s attributes, mode, and convert status.
    pub fn map(self, map: &Beatmap) -> Self {
        Self {
            mode: map.mode,
            ar: ModsDependentKind::Default(ModsDependent::new(map.ar)),
            od: ModsDependentKind::Default(ModsDependent::new(map.od)),
            cs: ModsDependentKind::Default(ModsDependent::new(map.cs)),
            hp: ModsDependentKind::Default(ModsDependent::new(map.hp)),
            mods: GameMods::DEFAULT,
            clock_rate: None,
            is_convert: map.is_convert,
        }
    }

    /// Specify the approach rate.
    ///
    /// `with_mods` determines if the given value should be used before
    /// or after accounting for mods, e.g. on `true` the value will be
    /// used as is and on `false` it will be modified based on the mods.
    pub const fn ar(mut self, ar: f32, with_mods: bool) -> Self {
        self.ar = ModsDependentKind::Custom(ModsDependent {
            value: ar,
            with_mods,
        });

        self
    }

    /// Specify the overall difficulty.
    ///
    /// `with_mods` determines if the given value should be used before
    /// or after accounting for mods, e.g. on `true` the value will be
    /// used as is and on `false` it will be modified based on the mods.
    pub const fn od(mut self, od: f32, with_mods: bool) -> Self {
        self.od = ModsDependentKind::Custom(ModsDependent {
            value: od,
            with_mods,
        });

        self
    }

    /// Specify the circle size.
    ///
    /// `with_mods` determines if the given value should be used before
    /// or after accounting for mods, e.g. on `true` the value will be
    /// used as is and on `false` it will be modified based on the mods.
    pub const fn cs(mut self, cs: f32, with_mods: bool) -> Self {
        self.cs = ModsDependentKind::Custom(ModsDependent {
            value: cs,
            with_mods,
        });

        self
    }

    /// Specify the drain rate.
    ///
    /// `with_mods` determines if the given value should be used before
    /// or after accounting for mods, e.g. on `true` the value will be
    /// used as is and on `false` it will be modified based on the mods.
    pub const fn hp(mut self, hp: f32, with_mods: bool) -> Self {
        self.hp = ModsDependentKind::Custom(ModsDependent {
            value: hp,
            with_mods,
        });

        self
    }

    /// Specify mods.
    ///
    /// Accepted types are
    /// - `u32`
    /// - [`rosu_mods::GameModsLegacy`]
    /// - [`rosu_mods::GameMods`]
    /// - [`rosu_mods::GameModsIntermode`]
    /// - [`&rosu_mods::GameModsIntermode`](rosu_mods::GameModsIntermode)
    ///
    /// See <https://github.com/ppy/osu-api/wiki#mods>
    pub fn mods(mut self, mods: impl Into<GameMods>) -> Self {
        self.mods = mods.into();

        self
    }

    /// Specify a custom clock rate.
    pub const fn clock_rate(mut self, clock_rate: f64) -> Self {
        self.clock_rate = Some(clock_rate);

        self
    }

    /// Specify a [`GameMode`] and whether it's a converted map.
    pub const fn mode(mut self, mode: GameMode, is_convert: bool) -> Self {
        self.mode = mode;
        self.is_convert = is_convert;

        self
    }

    /// Specify all settings through [`Difficulty`].
    pub fn difficulty(self, difficulty: &Difficulty) -> Self {
        Self {
            mode: self.mode,
            is_convert: self.is_convert,
            ar: difficulty
                .get_ar()
                .map_or(self.ar, ModsDependentKind::Custom),
            od: difficulty
                .get_od()
                .map_or(self.od, ModsDependentKind::Custom),
            cs: difficulty
                .get_cs()
                .map_or(self.cs, ModsDependentKind::Custom),
            hp: difficulty
                .get_hp()
                .map_or(self.hp, ModsDependentKind::Custom),
            mods: difficulty.get_mods().clone(),
            clock_rate: Some(difficulty.get_clock_rate()),
        }
    }

    /// Calculate the AR and OD hit windows.
    pub fn hit_windows(&self) -> HitWindows {
        let mods = &self.mods;

        let clock_rate = self
            .clock_rate
            .unwrap_or_else(|| f64::from(mods.clock_rate()));

        let ar_clock_rate = if self.ar.with_mods() { 1.0 } else { clock_rate };
        let od_clock_rate = if self.od.with_mods() { 1.0 } else { clock_rate };

        let mod_mult = |val: f32| {
            if mods.hr() {
                (val * 1.4).min(10.0)
            } else if mods.ez() {
                val * 0.5
            } else {
                val
            }
        };

        let raw_ar = if self.ar.with_mods() {
            self.ar.value(mods, GameMods::ar)
        } else {
            mod_mult(self.ar.value(mods, GameMods::ar))
        };

        let preempt = difficulty_range(f64::from(raw_ar), 1800.0, 1200.0, 450.0) / ar_clock_rate;

        // OD
        let hit_window = match self.mode {
            GameMode::Osu | GameMode::Catch => {
                let raw_od = if self.od.with_mods() {
                    self.od.value(mods, GameMods::od)
                } else {
                    mod_mult(self.od.value(mods, GameMods::od))
                };

                difficulty_range(
                    f64::from(raw_od),
                    Self::OSU_MIN,
                    Self::OSU_AVG,
                    Self::OSU_MAX,
                ) / od_clock_rate
            }
            GameMode::Taiko => {
                let raw_od = if self.od.with_mods() {
                    self.od.value(mods, GameMods::od)
                } else {
                    mod_mult(self.od.value(mods, GameMods::od))
                };

                let diff_range = difficulty_range(
                    f64::from(raw_od),
                    Self::TAIKO_MIN,
                    Self::TAIKO_AVG,
                    Self::TAIKO_MAX,
                );

                diff_range / od_clock_rate
            }
            GameMode::Mania => {
                let mut value = if !self.is_convert {
                    34.0 + 3.0 * (10.0 - self.od.value(mods, GameMods::od)).clamp(0.0, 10.0)
                } else if self.od.value(mods, GameMods::od).round_ties_even() > 4.0 {
                    34.0
                } else {
                    47.0
                };

                if !self.od.with_mods() {
                    if mods.hr() {
                        value /= 1.4;
                    } else if mods.ez() {
                        value *= 1.4;
                    }
                }

                ((f64::from(value) * od_clock_rate).floor() / od_clock_rate).ceil()
            }
        };

        HitWindows {
            ar: preempt,
            od: hit_window,
        }
    }

    /// Calculate the [`BeatmapAttributes`].
    pub fn build(&self) -> BeatmapAttributes {
        let mods = &self.mods;
        let clock_rate = self
            .clock_rate
            .unwrap_or_else(|| f64::from(mods.clock_rate()));

        // HP
        let mut hp = self.hp.value(mods, GameMods::hp);

        if !self.hp.with_mods() {
            hp *= mods.od_ar_hp_multiplier() as f32;
        }

        hp = hp.min(10.0);

        // CS
        let mut cs = self.cs.value(mods, GameMods::cs);

        if !self.cs.with_mods() {
            if mods.hr() {
                cs = (cs * 1.3).min(10.0);
            } else if mods.ez() {
                cs *= 0.5;
            }
        }

        let hit_windows = self.hit_windows();
        let HitWindows { ar, od } = hit_windows;

        // AR
        let ar = if ar > 1200.0 {
            (1800.0 - ar) / 120.0
        } else {
            (1200.0 - ar) / 150.0 + 5.0
        };

        // OD
        let od = match self.mode {
            GameMode::Osu => (Self::OSU_MIN - od) / 6.0,
            GameMode::Taiko => (Self::TAIKO_MIN - od) / (Self::TAIKO_MIN - Self::TAIKO_AVG) * 5.0,
            GameMode::Catch | GameMode::Mania => f64::from(self.od.value(mods, GameMods::od)),
        };

        BeatmapAttributes {
            ar,
            od,
            cs: f64::from(cs),
            hp: f64::from(hp),
            clock_rate,
            hit_windows,
        }
    }
}

impl From<&Beatmap> for BeatmapAttributesBuilder {
    fn from(map: &Beatmap) -> Self {
        Self::new().map(map)
    }
}

impl<M> From<&Converted<'_, M>> for BeatmapAttributesBuilder {
    fn from(converted: &Converted<'_, M>) -> Self {
        Self::new().map(converted)
    }
}

fn difficulty_range(difficulty: f64, min: f64, mid: f64, max: f64) -> f64 {
    if difficulty > 5.0 {
        mid + (max - mid) * (difficulty - 5.0) / 5.0
    } else if difficulty < 5.0 {
        mid - (mid - min) * (5.0 - difficulty) / 5.0
    } else {
        mid
    }
}

impl Default for BeatmapAttributesBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Clone, Debug, PartialEq)]
enum ModsDependentKind {
    Default(ModsDependent),
    Custom(ModsDependent),
}

impl ModsDependentKind {
    const DEFAULT: Self = Self::Default(ModsDependent::new(5.0));

    const fn with_mods(&self) -> bool {
        match self {
            ModsDependentKind::Default(inner) | ModsDependentKind::Custom(inner) => inner.with_mods,
        }
    }

    fn value(&self, mods: &GameMods, mods_fn: impl Fn(&GameMods) -> Option<f32>) -> f32 {
        match self {
            ModsDependentKind::Default(inner) => mods_fn(mods).unwrap_or(inner.value),
            ModsDependentKind::Custom(inner) => inner.value,
        }
    }
}

#[cfg(test)]
mod tests {
    use rosu_mods::{generated_mods::DifficultyAdjustOsu, GameMod, GameMods};

    use super::*;

    #[test]
    fn default_ar() {
        let gamemod = GameMod::HiddenOsu(Default::default());
        let diff = Difficulty::new().mods(GameMods::from(gamemod));
        let attrs = BeatmapAttributesBuilder::new().difficulty(&diff).build();

        assert_eq!(attrs.ar, 5.0);
    }

    #[test]
    fn custom_ar_without_mods() {
        let gamemod = GameMod::DoubleTimeOsu(Default::default());
        let diff = Difficulty::new().mods(GameMods::from(gamemod));
        let attrs = BeatmapAttributesBuilder::new()
            .ar(8.5, false)
            .difficulty(&diff)
            .build();

        assert_eq!(attrs.ar, 10.0);
    }

    #[test]
    fn custom_ar_with_mods() {
        let gamemod = GameMod::DoubleTimeOsu(Default::default());
        let diff = Difficulty::new().mods(GameMods::from(gamemod));
        let attrs = BeatmapAttributesBuilder::new()
            .ar(8.5, true)
            .difficulty(&diff)
            .build();

        assert_eq!(attrs.ar, 8.5);
    }

    #[test]
    fn custom_mods_ar() {
        let mut mods = GameMods::new();
        mods.insert(GameMod::DoubleTimeCatch(Default::default()));
        mods.insert(GameMod::DifficultyAdjustOsu(DifficultyAdjustOsu {
            approach_rate: Some(7.0),
            ..Default::default()
        }));
        let diff = Difficulty::new().mods(mods);
        let attrs = BeatmapAttributesBuilder::new().difficulty(&diff).build();

        assert_eq!(attrs.ar, 9.0);
    }

    #[test]
    fn custom_ar_custom_mods_ar_without_mods() {
        let mut mods = GameMods::new();
        mods.insert(GameMod::DoubleTimeCatch(Default::default()));
        mods.insert(GameMod::DifficultyAdjustOsu(DifficultyAdjustOsu {
            approach_rate: Some(9.0),
            ..Default::default()
        }));

        let diff = Difficulty::new().mods(mods).ar(8.5, false);
        let attrs = BeatmapAttributesBuilder::new().difficulty(&diff).build();

        assert_eq!(attrs.ar, 10.0);
    }

    #[test]
    fn custom_ar_custom_mods_ar_with_mods() {
        let mut mods = GameMods::new();
        mods.insert(GameMod::DoubleTimeCatch(Default::default()));
        mods.insert(GameMod::DifficultyAdjustOsu(DifficultyAdjustOsu {
            approach_rate: Some(9.0),
            ..Default::default()
        }));

        let diff = Difficulty::new().mods(mods).ar(8.5, true);
        let attrs = BeatmapAttributesBuilder::new().difficulty(&diff).build();

        assert_eq!(attrs.ar, 8.5);
    }
}