rosu-pp 4.0.1

Difficulty and performance calculation for osu!
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
use std::{
    fmt::{Debug, Formatter, Result as FmtResult},
    num::NonZeroU64,
};

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

use crate::{
    GradualDifficulty, GradualPerformance,
    any::CalculateError,
    catch::Catch,
    mania::Mania,
    model::{
        beatmap::{Beatmap, BeatmapAttribute, TooSuspicious, attributes::BeatmapDifficulty},
        mode::ConvertError,
        mods::GameMods,
    },
    osu::Osu,
    taiko::Taiko,
};

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

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

use crate::model::mode::IGameMode;

/// 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: GameMods,
    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.
    ///
    /// This allows for an optimization to reduce the struct size by storing its
    /// bits as a [`NonZeroU64`].
    clock_rate: Option<NonZeroU64>,
    #[expect(
        clippy::struct_field_names,
        reason = "it's a different kind of difficulty"
    )]
    map_difficulty: BeatmapDifficulty,
    hardrock_offsets: Option<bool>,
    lazer: Option<bool>,
}

impl Difficulty {
    /// Create a new difficulty calculator.
    pub const fn new() -> Self {
        Self {
            mods: GameMods::DEFAULT,
            passed_objects: None,
            clock_rate: None,
            map_difficulty: BeatmapDifficulty::DEFAULT,
            hardrock_offsets: None,
            lazer: None,
        }
    }

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

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

    /// 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(self, mods: impl Into<GameMods>) -> Self {
        Self {
            mods: mods.into(),
            ..self
        }
    }

    /// Amount of passed objects for partial plays, e.g. a fail.
    pub const fn passed_objects(mut 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.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 { NonZeroU64::new_unchecked(clock_rate) };

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

    /// Override a beatmap's set AR.
    ///
    /// Only relevant for osu! and osu!catch.
    ///
    /// `fixed` 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 const fn ar(mut self, ar: f32, fixed: bool) -> Self {
        let ar = f32::clamp(ar, -20.0, 20.0);

        self.map_difficulty.ar = if fixed {
            BeatmapAttribute::Fixed(ar)
        } else {
            BeatmapAttribute::Given(ar)
        };

        self
    }

    /// Override a beatmap's set CS.
    ///
    /// Only relevant for osu! and osu!catch.
    ///
    /// `fixed` 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 const fn cs(mut self, cs: f32, fixed: bool) -> Self {
        let cs = f32::clamp(cs, -20.0, 20.0);

        self.map_difficulty.cs = if fixed {
            BeatmapAttribute::Fixed(cs)
        } else {
            BeatmapAttribute::Given(cs)
        };

        self
    }

    /// Override a beatmap's set HP.
    ///
    /// `fixed` 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 const fn hp(mut self, hp: f32, fixed: bool) -> Self {
        let hp = f32::clamp(hp, -20.0, 20.0);

        self.map_difficulty.hp = if fixed {
            BeatmapAttribute::Fixed(hp)
        } else {
            BeatmapAttribute::Given(hp)
        };

        self
    }

    /// Override a beatmap's set OD.
    ///
    /// `fixed` 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 const fn od(mut self, od: f32, fixed: bool) -> Self {
        let od = f32::clamp(od, -20.0, 20.0);

        self.map_difficulty.od = if fixed {
            BeatmapAttribute::Fixed(od)
        } else {
            BeatmapAttribute::Given(od)
        };

        self
    }

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

        self
    }

    /// Whether the calculated attributes belong to an osu!lazer or osu!stable
    /// score.
    ///
    /// Defaults to `true`.
    pub const fn lazer(mut self, lazer: bool) -> Self {
        self.lazer = Some(lazer);

        self
    }

    /// Perform the difficulty calculation.
    #[expect(clippy::missing_panics_doc, reason = "unreachable")]
    pub fn calculate(&self, map: &Beatmap) -> DifficultyAttributes {
        match map.mode {
            GameMode::Osu => DifficultyAttributes::Osu(
                Osu::difficulty(self, map).expect("no conversion required"),
            ),
            GameMode::Taiko => DifficultyAttributes::Taiko(
                Taiko::difficulty(self, map).expect("no conversion required"),
            ),
            GameMode::Catch => DifficultyAttributes::Catch(
                Catch::difficulty(self, map).expect("no conversion required"),
            ),
            GameMode::Mania => DifficultyAttributes::Mania(
                Mania::difficulty(self, map).expect("no conversion required"),
            ),
        }
    }

    /// Perform the difficulty calculation after verifying the map is not
    /// suspicious.
    pub fn checked_calculate(&self, map: &Beatmap) -> Result<DifficultyAttributes, TooSuspicious> {
        map.check_suspicion()?;

        Ok(self.calculate(map))
    }

    /// Perform the difficulty calculation for a specific [`IGameMode`].
    pub fn calculate_for_mode<M: IGameMode>(
        &self,
        map: &Beatmap,
    ) -> Result<M::DifficultyAttributes, ConvertError> {
        M::difficulty(self, map)
    }

    /// Same as [`Difficulty::calculate_for_mode`] but verifies that the
    /// [`Beatmap`] is not too suspicious for further calculation.
    pub fn checked_calculate_for_mode<M: IGameMode>(
        &self,
        map: &Beatmap,
    ) -> Result<M::DifficultyAttributes, CalculateError> {
        M::checked_difficulty(self, 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.
    #[expect(clippy::missing_panics_doc, reason = "unreachable")]
    pub fn strains(&self, map: &Beatmap) -> Strains {
        match map.mode {
            GameMode::Osu => Strains::Osu(Osu::strains(self, map).expect("no conversion required")),
            GameMode::Taiko => {
                Strains::Taiko(Taiko::strains(self, map).expect("no conversion required"))
            }
            GameMode::Catch => {
                Strains::Catch(Catch::strains(self, map).expect("no conversion required"))
            }
            GameMode::Mania => {
                Strains::Mania(Mania::strains(self, map).expect("no conversion required"))
            }
        }
    }

    /// Perform the strain calculation after verifying the map is not
    /// suspicious.
    ///
    /// See [`Difficulty::strains`].
    pub fn checked_strains(&self, map: &Beatmap) -> Result<Strains, TooSuspicious> {
        map.check_suspicion()?;

        Ok(self.strains(map))
    }

    /// Perform the strain calculation for a specific [`IGameMode`].
    pub fn strains_for_mode<M: IGameMode>(
        &self,
        map: &Beatmap,
    ) -> Result<M::Strains, ConvertError> {
        M::strains(self, map)
    }

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

    /// Same as [`Difficulty::gradual_difficulty`] but verifies that the map is
    /// not suspicious.
    pub fn checked_gradual_difficulty(
        self,
        map: &Beatmap,
    ) -> Result<GradualDifficulty, TooSuspicious> {
        GradualDifficulty::checked_new(self, map)
    }

    /// Create a gradual difficulty calculator for a [`Beatmap`] on a specific [`IGameMode`].
    pub fn gradual_difficulty_for_mode<M: IGameMode>(
        self,
        map: &Beatmap,
    ) -> Result<M::GradualDifficulty, ConvertError> {
        M::gradual_difficulty(self, map)
    }

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

    /// Same as [`Difficulty::gradual_performance`] but verifies that the map is
    /// not suspicious.
    pub fn checked_gradual_performance(
        self,
        map: &Beatmap,
    ) -> Result<GradualPerformance, TooSuspicious> {
        GradualPerformance::checked_new(self, map)
    }

    /// Create a gradual performance calculator for a [`Beatmap`] on a specific [`IGameMode`].
    pub fn gradual_performance_for_mode<M: IGameMode>(
        self,
        map: &Beatmap,
    ) -> Result<M::GradualPerformance, ConvertError> {
        M::gradual_performance(self, map)
    }

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

    pub(crate) fn get_clock_rate(&self) -> f64 {
        self.clock_rate
            .map_or(self.mods.clock_rate(), non_zero_u64_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_map_difficulty(&self) -> &BeatmapDifficulty {
        &self.map_difficulty
    }

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

    pub(crate) fn get_lazer(&self) -> bool {
        self.lazer.unwrap_or(true)
    }
}

const fn non_zero_u64_to_f64(n: NonZeroU64) -> f64 {
    f64::from_bits(n.get())
}

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

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

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