// Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Threading; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Game.Beatmaps; using osu.Game.Database; using osu.Game.Rulesets.Difficulty; namespace osu.Game.Scoring { /// /// A component which performs and acts as a central cache for performance calculations of locally databased scores. /// Currently not persisted between game sessions. /// public partial class ScorePerformanceCache : MemoryCachingComponent { [Resolved] private BeatmapDifficultyCache difficultyCache { get; set; } = null!; protected override bool CacheNullValues => false; /// /// Calculates performance for the given . /// /// The score to do the calculation on. /// An optional to cancel the operation. public Task CalculatePerformanceAsync(ScoreInfo score, CancellationToken token = default) => GetAsync(new PerformanceCacheLookup(score), token); protected override async Task ComputeValueAsync(PerformanceCacheLookup lookup, CancellationToken token = default) { var score = lookup.ScoreInfo; var attributes = await difficultyCache.GetDifficultyAsync(score.BeatmapInfo, score.Ruleset, score.Mods, token).ConfigureAwait(false); // Performance calculation requires the beatmap and ruleset to be locally available. If not, return a default value. if (attributes?.Attributes == null) return null; token.ThrowIfCancellationRequested(); return score.Ruleset.CreateInstance().CreatePerformanceCalculator()?.Calculate(score, attributes.Value.Attributes); } public readonly struct PerformanceCacheLookup { public readonly ScoreInfo ScoreInfo; public PerformanceCacheLookup(ScoreInfo info) { ScoreInfo = info; } public override int GetHashCode() { var hash = new HashCode(); hash.Add(ScoreInfo.Hash); hash.Add(ScoreInfo.ID); return hash.ToHashCode(); } } } }