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
use std::{
    borrow::Cow,
    fmt::{Debug, Formatter, Result as FmtResult},
    num::NonZeroU32,
};

use rosu_map::section::general::GameMode;

use crate::{
    catch::Catch,
    mania::Mania,
    model::beatmap::{Beatmap, Converted},
    osu::Osu,
    taiko::Taiko,
    GradualDifficulty, GradualPerformance,
};

use self::converted::ConvertedDifficulty;

use super::{attributes::DifficultyAttributes, InspectDifficulty, Strains};

pub mod converted;
pub mod gradual;
pub mod inspect;
pub mod object;
pub mod skills;

use crate::{model::mode::IGameMode, util::mods::Mods};

/// Difficulty calculator on maps of any mode.
///
/// # Example
///
/// ```
/// use rosu_pp::{Beatmap, Difficulty, any::DifficultyAttributes};
///
/// let map = Beatmap::from_path("./resources/2118524.osu").unwrap();
///
/// let attrs: DifficultyAttributes = Difficulty::new()
///     .mods(8 + 1024) // HDFL
///     .calculate(&map);
/// ```
#[derive(Clone, PartialEq)]
#[must_use]
pub struct Difficulty {
    mods: u32,
    passed_objects: Option<u32>,
    /// Clock rate will be clamped internally between 0.01 and 100.0.
    ///
    /// Since its minimum value is 0.01, its bits are never zero.
    /// Additionally, values between 0.01 and 100 are represented sufficiently
    /// precise with 32 bits.
    ///
    /// This allows for an optimization to reduce the struct size by storing its
    /// bits as a [`NonZeroU32`].
    clock_rate: Option<NonZeroU32>,
    ar: Option<ModsDependent>,
    cs: Option<ModsDependent>,
    hp: Option<ModsDependent>,
    od: Option<ModsDependent>,
    hardrock_offsets: Option<bool>,
}

/// Wrapper for beatmap attributes in [`Difficulty`].
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct ModsDependent {
    /// Value of the beatmap attribute.
    pub value: f32,
    /// Whether `value` should be used as is or modified based on mods.
    ///
    /// `true` means "value already considers mods" i.e. use as is;
    /// `false` means modify with mods.
    pub with_mods: bool,
}

impl ModsDependent {
    pub const fn new(value: f32) -> Self {
        Self {
            value,
            with_mods: false,
        }
    }
}

impl Difficulty {
    /// Create a new difficulty calculator.
    pub const fn new() -> Self {
        Self {
            mods: 0,
            passed_objects: None,
            clock_rate: None,
            ar: None,
            cs: None,
            hp: None,
            od: None,
            hardrock_offsets: None,
        }
    }

    /// Use this [`Difficulty`] as a calculator for a specific [`IGameMode`].
    ///
    /// Note that [`ConvertedDifficulty`] won't allow to further customize
    /// fields so be sure they're all set before converting to it.
    pub const fn with_mode<M: IGameMode>(&self) -> ConvertedDifficulty<'_, M> {
        ConvertedDifficulty::new(self)
    }

    /// Turn this [`Difficulty`] into a [`InspectDifficulty`] to inspect its
    /// configured values.
    pub fn inspect(self) -> InspectDifficulty {
        let Self {
            mods,
            passed_objects,
            clock_rate,
            ar,
            cs,
            hp,
            od,
            hardrock_offsets,
        } = self;

        InspectDifficulty {
            mods,
            passed_objects,
            clock_rate: clock_rate.map(non_zero_u32_to_f64),
            ar,
            cs,
            hp,
            od,
            hardrock_offsets,
        }
    }

    /// Specify mods through their bit values.
    ///
    /// See <https://github.com/ppy/osu-api/wiki#mods>
    pub const fn mods(self, mods: u32) -> Self {
        Self { mods, ..self }
    }

    /// Amount of passed objects for partial plays, e.g. a fail.
    pub const fn passed_objects(self, passed_objects: u32) -> Self {
        Self {
            passed_objects: Some(passed_objects),
            ..self
        }
    }

    /// Adjust the clock rate used in the calculation.
    ///
    /// If none is specified, it will take the clock rate based on the mods
    /// i.e. 1.5 for DT, 0.75 for HT and 1.0 otherwise.
    ///
    /// | Minimum | Maximum |
    /// | :-----: | :-----: |
    /// | 0.01    | 100     |
    pub fn clock_rate(self, clock_rate: f64) -> Self {
        let clock_rate = (clock_rate as f32).clamp(0.01, 100.0).to_bits();

        // SAFETY: The minimum value is 0.01 so its bits can never be fully
        // zero.
        let non_zero = unsafe { NonZeroU32::new_unchecked(clock_rate) };

        Self {
            clock_rate: Some(non_zero),
            ..self
        }
    }

    /// Override a beatmap's set AR.
    ///
    /// Only relevant for osu! and osu!catch.
    ///
    /// `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.
    ///
    /// | Minimum | Maximum |
    /// | :-----: | :-----: |
    /// | -20     | 20      |
    pub fn ar(self, ar: f32, with_mods: bool) -> Self {
        Self {
            ar: Some(ModsDependent {
                value: ar.clamp(-20.0, 20.0),
                with_mods,
            }),
            ..self
        }
    }

    /// Override a beatmap's set CS.
    ///
    /// Only relevant for osu! and osu!catch.
    ///
    /// `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.
    ///
    /// | Minimum | Maximum |
    /// | :-----: | :-----: |
    /// | -20     | 20      |
    pub fn cs(self, cs: f32, with_mods: bool) -> Self {
        Self {
            cs: Some(ModsDependent {
                value: cs.clamp(-20.0, 20.0),
                with_mods,
            }),
            ..self
        }
    }

    /// Override a beatmap's set HP.
    ///
    /// `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.
    ///
    /// | Minimum | Maximum |
    /// | :-----: | :-----: |
    /// | -20     | 20      |
    pub fn hp(self, hp: f32, with_mods: bool) -> Self {
        Self {
            hp: Some(ModsDependent {
                value: hp.clamp(-20.0, 20.0),
                with_mods,
            }),
            ..self
        }
    }

    /// Override a beatmap's set OD.
    ///
    /// `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.
    ///
    /// | Minimum | Maximum |
    /// | :-----: | :-----: |
    /// | -20     | 20      |
    pub fn od(self, od: f32, with_mods: bool) -> Self {
        Self {
            od: Some(ModsDependent {
                value: od.clamp(-20.0, 20.0),
                with_mods,
            }),
            ..self
        }
    }

    /// Adjust patterns as if the HR mod is enabled.
    ///
    /// Only relevant for osu!catch.
    pub const fn hardrock_offsets(self, hardrock_offsets: bool) -> Self {
        Self {
            hardrock_offsets: Some(hardrock_offsets),
            ..self
        }
    }

    /// Perform the difficulty calculation.
    pub fn calculate(&self, map: &Beatmap) -> DifficultyAttributes {
        let map = Cow::Borrowed(map);

        match map.mode {
            GameMode::Osu => DifficultyAttributes::Osu(Osu::difficulty(self, &Converted::new(map))),
            GameMode::Taiko => {
                DifficultyAttributes::Taiko(Taiko::difficulty(self, &Converted::new(map)))
            }
            GameMode::Catch => {
                DifficultyAttributes::Catch(Catch::difficulty(self, &Converted::new(map)))
            }
            GameMode::Mania => {
                DifficultyAttributes::Mania(Mania::difficulty(self, &Converted::new(map)))
            }
        }
    }

    /// Perform the difficulty calculation but instead of evaluating the skill
    /// strains, return them as is.
    ///
    /// Suitable to plot the difficulty of a map over time.
    pub fn strains(&self, map: &Beatmap) -> Strains {
        let map = Cow::Borrowed(map);

        match map.mode {
            GameMode::Osu => Strains::Osu(Osu::strains(self, &Converted::new(map))),
            GameMode::Taiko => Strains::Taiko(Taiko::strains(self, &Converted::new(map))),
            GameMode::Catch => Strains::Catch(Catch::strains(self, &Converted::new(map))),
            GameMode::Mania => Strains::Mania(Mania::strains(self, &Converted::new(map))),
        }
    }

    /// Create a gradual difficulty calculator for a [`Beatmap`].
    pub fn gradual_difficulty(self, map: &Beatmap) -> GradualDifficulty {
        GradualDifficulty::new(self, map)
    }

    /// Create a gradual performance calculator for a [`Beatmap`].
    pub fn gradual_performance(self, map: &Beatmap) -> GradualPerformance {
        GradualPerformance::new(self, map)
    }

    pub(crate) const fn get_mods(&self) -> u32 {
        self.mods
    }

    pub(crate) fn get_clock_rate(&self) -> f64 {
        self.clock_rate
            .map_or(self.mods.clock_rate(), non_zero_u32_to_f64)
    }

    pub(crate) fn get_passed_objects(&self) -> usize {
        self.passed_objects.map_or(usize::MAX, |n| n as usize)
    }

    pub(crate) const fn get_ar(&self) -> Option<ModsDependent> {
        self.ar
    }

    pub(crate) const fn get_cs(&self) -> Option<ModsDependent> {
        self.cs
    }

    pub(crate) const fn get_hp(&self) -> Option<ModsDependent> {
        self.hp
    }

    pub(crate) const fn get_od(&self) -> Option<ModsDependent> {
        self.od
    }

    pub(crate) fn get_hardrock_offsets(&self) -> bool {
        self.hardrock_offsets.unwrap_or(self.mods.hr())
    }
}

fn non_zero_u32_to_f64(n: NonZeroU32) -> f64 {
    f64::from(f32::from_bits(n.get()))
}

impl Debug for Difficulty {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let Self {
            mods,
            passed_objects,
            clock_rate,
            ar,
            cs,
            hp,
            od,
            hardrock_offsets,
        } = self;

        f.debug_struct("Difficulty")
            .field("mods", mods)
            .field("passed_objects", passed_objects)
            .field("clock_rate", &clock_rate.map(non_zero_u32_to_f64))
            .field("ar", ar)
            .field("cs", cs)
            .field("hp", hp)
            .field("od", od)
            .field("hardrock_offsets", hardrock_offsets)
            .finish()
    }
}

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