UNPKG

@rian8337/osu-difficulty-calculator

Version:

A module for calculating osu!standard beatmap difficulty and performance value with respect to the current difficulty and performance algorithm.

1,181 lines (1,166 loc) 144 kB
'use strict'; var osuBase = require('@rian8337/osu-base'); /** * An evaluator for calculating aim skill. * * This class should be considered an "evaluating" class and not persisted. */ class AimEvaluator { static wideAngleMultiplier = 1.5; static acuteAngleMultiplier = 1.95; static sliderMultiplier = 1.35; static velocityChangeMultiplier = 0.75; /** * Calculates the bonus of wide angles. */ static calculateWideAngleBonus(angle) { return Math.pow(Math.sin((3 / 4) * (Math.min((5 / 6) * Math.PI, Math.max(Math.PI / 6, angle)) - Math.PI / 6)), 2); } /** * Calculates the bonus of acute angles. */ static calculateAcuteAngleBonus(angle) { return 1 - this.calculateWideAngleBonus(angle); } } /** * Represents an osu!standard hit object with difficulty calculation values. */ class DifficultyHitObject { /** * The underlying hitobject. */ object; /** * The index of this hitobject in the list of all hitobjects. * * This is one less than the actual index of the hitobject in the beatmap. */ index = 0; /** * The preempt time of the hitobject. */ baseTimePreempt = 600; /** * Adjusted preempt time of the hitobject, taking speed multiplier into account. */ timePreempt = 600; /** * The fade in time of the hitobject. */ timeFadeIn = 400; /** * The aim strain generated by the hitobject if sliders are considered. */ aimStrainWithSliders = 0; /** * The aim strain generated by the hitobject if sliders are not considered. */ aimStrainWithoutSliders = 0; /** * The tap strain generated by the hitobject. * * This is also used for osu!standard as opposed to "speed strain". */ tapStrain = 0; /** * The tap strain generated by the hitobject if `strainTime` isn't modified by * OD. This is used in three-finger detection. */ originalTapStrain = 0; /** * The rhythm multiplier generated by the hitobject. This is used to alter tap strain. */ rhythmMultiplier = 0; /** * The rhythm strain generated by the hitobject. */ rhythmStrain = 0; /** * The flashlight strain generated by the hitobject if sliders are considered. */ flashlightStrain = 0; /** * The flashlight strain generated by the hitobject if sliders are not considered. */ flashlightStrainWithoutSliders = 0; /** * The visual strain generated by the hitobject if sliders are considered. */ visualStrain = 0; /** * The visual strain generated by the hitobject if sliders are not considered. */ visualStrainWithoutSliders = 0; /** * The normalized distance from the "lazy" end position of the previous hitobject to the start position of this hitobject. * * The "lazy" end position is the position at which the cursor ends up if the previous hitobject is followed with as minimal movement as possible (i.e. on the edge of slider follow circles). */ lazyJumpDistance = 0; /** * The normalized shortest distance to consider for a jump between the previous hitobject and this hitobject. * * This is bounded from above by `lazyJumpDistance`, and is smaller than the former if a more natural path is able to be taken through the previous hitobject. * * Suppose a linear slider - circle pattern. Following the slider lazily (see: `lazyJumpDistance`) will result in underestimating the true end position of the slider as being closer towards the start position. * As a result, `lazyJumpDistance` overestimates the jump distance because the player is able to take a more natural path by following through the slider to its end, * such that the jump is felt as only starting from the slider's true end position. * * Now consider a slider - circle pattern where the circle is stacked along the path inside the slider. * In this case, the lazy end position correctly estimates the true end position of the slider and provides the more natural movement path. */ minimumJumpDistance = 0; /** * The time taken to travel through `minimumJumpDistance`, with a minimum value of 25ms. */ minimumJumpTime = 0; /** * The normalized distance between the start and end position of this hitobject. */ travelDistance = 0; /** * The time taken to travel through `travelDistance`, with a minimum value of 25ms for sliders. */ travelTime = 0; /** * Angle the player has to take to hit this hitobject. * * Calculated as the angle between the circles (current-2, current-1, current). */ angle = null; /** * The amount of milliseconds elapsed between this hitobject and the last hitobject. */ deltaTime = 0; /** * The amount of milliseconds elapsed since the start time of the previous hitobject, with a minimum of 25ms. */ strainTime = 0; /** * Adjusted start time of the hitobject, taking speed multiplier into account. */ startTime = 0; /** * Adjusted end time of the hitobject, taking speed multiplier into account. */ endTime = 0; /** * The note density of the hitobject. */ noteDensity = 1; /** * The overlapping factor of the hitobject. * * This is used to scale visual skill. */ overlappingFactor = 0; /** * Adjusted velocity of the hitobject, taking speed multiplier into account. */ velocity = 0; /** * Other hitobjects in the beatmap, including this hitobject. */ hitObjects; /** * @param object The underlying hitobject. * @param hitObjects All difficulty hitobjects in the processed beatmap. */ constructor(object, hitObjects) { this.object = object; this.hitObjects = hitObjects; } /** * Gets the difficulty hitobject at a specific index with respect to the current * difficulty hitobject's index. * * Will return `null` if the index is out of range. * * @param backwardsIndex The index to move backwards for. * @returns The difficulty hitobject at the index with respect to the current * difficulty hitobject's index, `null` if the index is out of range. */ previous(backwardsIndex) { return this.hitObjects[this.index - backwardsIndex] ?? null; } /** * Gets the difficulty hitobject at a specific index with respect to the current * difficulty hitobject's index. * * Will return `null` if the index is out of range. * * @param forwardsIndex The index to move forwards for. * @returns The difficulty hitobject at the index with respect to the current * difficulty hitobject's index, `null` if the index is out of range. */ next(forwardsIndex) { return this.hitObjects[this.index + forwardsIndex + 2] ?? null; } /** * Calculates the opacity of the hitobject at a given time. * * @param time The time to calculate the hitobject's opacity at. * @param isHidden Whether Hidden mod is used. * @param mode The gamemode to calculate the opacity for. * @returns The opacity of the hitobject at the given time. */ opacityAt(time, isHidden, mode) { if (time > this.object.startTime) { // Consider a hitobject as being invisible when its start time is passed. // In reality the hitobject will be visible beyond its start time up until its hittable window has passed, // but this is an approximation and such a case is unlikely to be hit where this function is used. return 0; } const fadeInStartTime = this.object.startTime - this.baseTimePreempt; const fadeInDuration = this.timeFadeIn; if (isHidden) { const fadeOutStartTime = fadeInStartTime + fadeInDuration; const fadeOutDuration = this.baseTimePreempt * (mode === osuBase.Modes.droid ? 0.35 : osuBase.ModHidden.fadeOutDurationMultiplier); return Math.min(osuBase.MathUtils.clamp((time - fadeInStartTime) / fadeInDuration, 0, 1), 1 - osuBase.MathUtils.clamp((time - fadeOutStartTime) / fadeOutDuration, 0, 1)); } return osuBase.MathUtils.clamp((time - fadeInStartTime) / fadeInDuration, 0, 1); } /** * Determines whether this hitobject is considered overlapping with the hitobject before it. * * Keep in mind that "overlapping" in this case is overlapping to the point where both hitobjects * can be hit with just a single tap in osu!droid. * * @param considerDistance Whether to consider the distance between both hitobjects. * @returns Whether the hitobject is considered overlapping. */ isOverlapping(considerDistance) { if (this.object instanceof osuBase.Spinner) { return false; } const previous = this.previous(0); if (!previous || previous.object instanceof osuBase.Spinner) { return false; } if (this.deltaTime >= 5) { return false; } if (considerDistance) { const endPosition = this.object.getStackedPosition(osuBase.Modes.droid); let distance = previous.object .getStackedEndPosition(osuBase.Modes.droid) .getDistance(endPosition); if (previous.object instanceof osuBase.Slider && previous.object.lazyEndPosition) { distance = Math.min(distance, previous.object.lazyEndPosition.getDistance(endPosition)); } return distance <= 2 * this.object.getRadius(osuBase.Modes.droid); } return true; } } /** * A converter used to convert normal hitobjects into difficulty hitobjects. */ class DifficultyHitObjectCreator { /** * The threshold for small circle buff for osu!droid. */ DROID_CIRCLESIZE_BUFF_THRESHOLD = 70; /** * The threshold for small circle buff for osu!standard. */ PC_CIRCLESIZE_BUFF_THRESHOLD = 30; /** * The gamemode this creator is creating for. */ mode = osuBase.Modes.osu; /** * The base normalized radius of hitobjects. */ normalizedRadius = 50; maximumSliderRadius = this.normalizedRadius * 2.4; assumedSliderRadius = this.normalizedRadius * 1.8; minDeltaTime = 25; /** * Generates difficulty hitobjects for difficulty calculation. */ generateDifficultyObjects(params) { params.preempt ??= 600; this.mode = params.mode; if (this.mode === osuBase.Modes.droid) { this.maximumSliderRadius = this.normalizedRadius * 2; } const scalingFactor = this.getScalingFactor(params.objects[0].getRadius(this.mode)); const difficultyObjects = []; for (let i = 0; i < params.objects.length; ++i) { const object = new DifficultyHitObject(params.objects[i], difficultyObjects); object.index = difficultyObjects.length - 1; object.timePreempt = params.preempt; object.baseTimePreempt = params.preempt * params.speedMultiplier; if (object.object instanceof osuBase.Slider) { object.velocity = object.object.velocity * params.speedMultiplier; this.calculateSliderCursorPosition(object.object); object.travelDistance = object.object.lazyTravelDistance; // Bonus for repeat sliders until a better per nested object strain system can be achieved. if (this.mode === osuBase.Modes.droid) { object.travelDistance *= Math.pow(1 + object.object.repeats / 4, 1 / 4); } else { object.travelDistance *= Math.pow(1 + object.object.repeats / 2.5, 1 / 2.5); } object.travelTime = Math.max(object.object.lazyTravelTime / params.speedMultiplier, this.minDeltaTime); } const lastObject = difficultyObjects[i - 1]; const lastLastObject = difficultyObjects[i - 2]; object.startTime = object.object.startTime / params.speedMultiplier; object.endTime = object.object.endTime / params.speedMultiplier; if (!lastObject) { difficultyObjects.push(object); continue; } object.deltaTime = (object.object.startTime - lastObject.object.startTime) / params.speedMultiplier; // Cap to 25ms to prevent difficulty calculation breaking from simultaneous objects. object.strainTime = Math.max(this.minDeltaTime, object.deltaTime); if (object.object instanceof osuBase.Spinner) { difficultyObjects.push(object); continue; } // We'll have two visible object arrays. The first array contains objects before the current object starts in a reversed order, // while the second array contains objects after the current object ends. // For overlapping factor, we also need to consider previous visible objects. const prevVisibleObjects = []; const nextVisibleObjects = []; for (let j = i + 1; j < params.objects.length; ++j) { const o = params.objects[j]; if (o instanceof osuBase.Spinner) { continue; } if (o.startTime / params.speedMultiplier > object.endTime + object.timePreempt) { break; } nextVisibleObjects.push(o); } for (let j = 0; j < object.index; ++j) { const prev = object.previous(j); if (prev.object instanceof osuBase.Spinner) { continue; } if (prev.startTime >= object.startTime) { continue; } if (prev.startTime < object.startTime - object.timePreempt) { break; } prevVisibleObjects.push(prev.object); } for (const hitObject of prevVisibleObjects) { const distance = object.object .getStackedPosition(this.mode) .getDistance(hitObject.getStackedEndPosition(this.mode)); const deltaTime = object.startTime - hitObject.endTime / params.speedMultiplier; this.applyToOverlappingFactor(object, distance, deltaTime); } for (const hitObject of nextVisibleObjects) { const distance = hitObject .getStackedPosition(this.mode) .getDistance(object.object.getStackedEndPosition(this.mode)); const deltaTime = hitObject.startTime / params.speedMultiplier - object.endTime; if (deltaTime >= 0) { object.noteDensity += 1 - deltaTime / object.timePreempt; } this.applyToOverlappingFactor(object, distance, deltaTime); } if (lastObject.object instanceof osuBase.Spinner) { difficultyObjects.push(object); continue; } const lastCursorPosition = this.getEndCursorPosition(lastObject.object); object.lazyJumpDistance = object.object .getStackedPosition(this.mode) .scale(scalingFactor) .subtract(lastCursorPosition.scale(scalingFactor)).length; object.minimumJumpTime = object.strainTime; object.minimumJumpDistance = object.lazyJumpDistance; if (lastObject.object instanceof osuBase.Slider) { object.minimumJumpTime = Math.max(object.strainTime - lastObject.travelTime, this.minDeltaTime); // There are two types of slider-to-object patterns to consider in order to better approximate the real movement a player will take to jump between the hitobjects. // // 1. The anti-flow pattern, where players cut the slider short in order to move to the next hitobject. // // <======o==> ← slider // | ← most natural jump path // o ← a follow-up hitcircle // // In this case the most natural jump path is approximated by LazyJumpDistance. // // 2. The flow pattern, where players follow through the slider to its visual extent into the next hitobject. // // <======o==>---o // ↑ // most natural jump path // // In this case the most natural jump path is better approximated by a new distance called "tailJumpDistance" - the distance between the slider's tail and the next hitobject. // // Thus, the player is assumed to jump the minimum of these two distances in all cases. const tailJumpDistance = lastObject.object.tail .getStackedPosition(this.mode) .subtract(object.object.getStackedPosition(this.mode)) .length * scalingFactor; object.minimumJumpDistance = Math.max(0, Math.min(object.lazyJumpDistance - (this.maximumSliderRadius - this.assumedSliderRadius), tailJumpDistance - this.maximumSliderRadius)); } if (lastLastObject && !(lastLastObject.object instanceof osuBase.Spinner)) { const lastLastCursorPosition = this.getEndCursorPosition(lastLastObject.object); const v1 = lastLastCursorPosition.subtract(lastObject.object.getStackedPosition(this.mode)); const v2 = object.object .getStackedPosition(this.mode) .subtract(lastCursorPosition); const dot = v1.dot(v2); const det = v1.x * v2.y - v1.y * v2.x; object.angle = Math.abs(Math.atan2(det, dot)); } difficultyObjects.push(object); } return difficultyObjects; } /** * Calculates a slider's cursor position. */ calculateSliderCursorPosition(slider) { if (slider.lazyEndPosition) { return; } // Droid doesn't have a legacy slider tail. Since beatmap parser defaults slider tail // to legacy slider tail, it needs to be changed to real slider tail first. if (this.mode === osuBase.Modes.droid) { slider.tail.startTime += osuBase.Slider.legacyLastTickOffset; slider.tail.endTime += osuBase.Slider.legacyLastTickOffset; slider.nestedHitObjects.sort((a, b) => a.startTime - b.startTime); // Temporary lazy end position until a real result can be derived. slider.lazyEndPosition = slider.getStackedPosition(this.mode); // Stop here if the slider has too short duration due to float number limitation. // Incredibly close start and end time fluctuates travel distance and lazy // end position heavily, which we do not want to happen. // // In the real game, this shouldn't happen. Perhaps we need to reinvestigate this // in the future. if (osuBase.Precision.almostEqualsNumber(slider.startTime, slider.endTime)) { return; } } // Not using slider.endTime due to legacy last tick offset. slider.lazyTravelTime = slider.nestedHitObjects.at(-1).startTime - slider.startTime; let endTimeMin = slider.lazyTravelTime / slider.spanDuration; if (endTimeMin % 2 >= 1) { endTimeMin = 1 - (endTimeMin % 1); } else { endTimeMin %= 1; } // Temporary lazy end position until a real result can be derived. slider.lazyEndPosition = slider .getStackedPosition(this.mode) .add(slider.path.positionAt(endTimeMin)); let currentCursorPosition = slider.getStackedPosition(this.mode); const scalingFactor = this.normalizedRadius / slider.getRadius(this.mode); for (let i = 1; i < slider.nestedHitObjects.length; ++i) { const currentMovementObject = slider.nestedHitObjects[i]; let currentMovement = currentMovementObject .getStackedPosition(this.mode) .subtract(currentCursorPosition); let currentMovementLength = scalingFactor * currentMovement.length; // The amount of movement required so that the cursor position needs to be updated. let requiredMovement = this.assumedSliderRadius; if (i === slider.nestedHitObjects.length - 1) { // The end of a slider has special aim rules due to the relaxed time constraint on position. // There is both a lazy end position as well as the actual end slider position. We assume the player takes the simpler movement. // For sliders that are circular, the lazy end position may actually be farther away than the sliders' true end. // This code is designed to prevent buffing situations where lazy end is actually a less efficient movement. const lazyMovement = slider.lazyEndPosition.subtract(currentCursorPosition); if (lazyMovement.length < currentMovement.length) { currentMovement = lazyMovement; } currentMovementLength = scalingFactor * currentMovement.length; } else if (currentMovementObject instanceof osuBase.SliderRepeat) { // For a slider repeat, assume a tighter movement threshold to better assess repeat sliders. requiredMovement = this.normalizedRadius; } if (currentMovementLength > requiredMovement) { // This finds the positional delta from the required radius and the current position, // and updates the currentCursorPosition accordingly, as well as rewarding distance. currentCursorPosition = currentCursorPosition.add(currentMovement.scale((currentMovementLength - requiredMovement) / currentMovementLength)); currentMovementLength *= (currentMovementLength - requiredMovement) / currentMovementLength; slider.lazyTravelDistance += currentMovementLength; } if (i === slider.nestedHitObjects.length - 1) { slider.lazyEndPosition = currentCursorPosition; } } } /** * Gets the scaling factor of a radius. * * @param radius The radius to get the scaling factor from. */ getScalingFactor(radius) { // We will scale distances by this factor, so we can assume a uniform CircleSize among beatmaps. let scalingFactor = this.normalizedRadius / radius; // High circle size (small CS) bonus switch (this.mode) { case osuBase.Modes.droid: if (radius < this.DROID_CIRCLESIZE_BUFF_THRESHOLD) { scalingFactor *= 1 + Math.pow((this.DROID_CIRCLESIZE_BUFF_THRESHOLD - radius) / 50, 2); } break; case osuBase.Modes.osu: if (radius < this.PC_CIRCLESIZE_BUFF_THRESHOLD) { scalingFactor *= 1 + Math.min(this.PC_CIRCLESIZE_BUFF_THRESHOLD - radius, 5) / 50; } } return scalingFactor; } /** * Returns the end cursor position of a hitobject. */ getEndCursorPosition(object) { let pos = object.getStackedPosition(this.mode); if (object instanceof osuBase.Slider) { this.calculateSliderCursorPosition(object); pos = object.lazyEndPosition ?? pos; } return pos; } applyToOverlappingFactor(object, distance, deltaTime) { // Penalize objects that are too close to the object in both distance // and delta time to prevent stream maps from being overweighted. object.overlappingFactor += Math.max(0, 1 - distance / (3 * object.object.getRadius(this.mode))) * (7.5 / (1 + Math.exp(0.15 * (Math.max(deltaTime, this.minDeltaTime) - 75)))); } } /** * The base of difficulty calculators. */ class DifficultyCalculator { /** * The calculated beatmap. */ beatmap; /** * The difficulty objects of the beatmap. */ objects = []; /** * The modifications applied. */ mods = []; /** * The total star rating of the beatmap. */ total = 0; /** * The map statistics of the beatmap after modifications are applied. */ stats = new osuBase.MapStats(); /** * The strain peaks of various calculated difficulties. */ strainPeaks = { aimWithSliders: [], aimWithoutSliders: [], speed: [], flashlight: [], }; sectionLength = 400; /** * Constructs a new instance of the calculator. * * @param beatmap The beatmap to calculate. This beatmap will be deep-cloned to prevent reference changes. */ constructor(beatmap) { this.beatmap = osuBase.Utils.deepCopy(beatmap); } /** * Calculates the star rating of the specified beatmap. * * The beatmap is analyzed in chunks of `sectionLength` duration. * For each chunk the highest hitobject strains are added to * a list which is then collapsed into a weighted sum, much * like scores are weighted on a user's profile. * * For subsequent chunks, the initial max strain is calculated * by decaying the previous hitobject's strain until the * beginning of the new chunk. * * @param options Options for the difficulty calculation. * @returns The current instance. */ calculate(options) { this.mods = options?.mods ?? []; this.stats = new osuBase.MapStats({ cs: this.beatmap.difficulty.cs, ar: this.beatmap.difficulty.ar, od: this.beatmap.difficulty.od, hp: this.beatmap.difficulty.hp, mods: options?.mods, speedMultiplier: options?.stats?.speedMultiplier, oldStatistics: options?.stats?.oldStatistics, }).calculate({ mode: this.mode }); this.preProcess(); this.populateDifficultyAttributes(); this.generateDifficultyHitObjects(); this.calculateAll(); return this; } /** * Generates difficulty hitobjects for this calculator. */ generateDifficultyHitObjects() { this.objects.length = 0; this.objects.push(...new DifficultyHitObjectCreator().generateDifficultyObjects({ objects: this.beatmap.hitObjects.objects, circleSize: this.beatmap.difficulty.cs, mods: this.mods, speedMultiplier: this.stats.speedMultiplier, mode: this.mode, preempt: osuBase.MapStats.arToMS(this.stats.ar), })); } /** * Performs some pre-processing before proceeding with difficulty calculation. */ preProcess() { } /** * Calculates the skills provided. * * @param skills The skills to calculate. */ calculateSkills(...skills) { // The first object doesn't generate a strain, so we begin calculating from the second object. this.objects.slice(1).forEach((h, i) => { skills.forEach((skill) => { skill.process(h); if (i === this.objects.length - 2) { // Don't forget to save the last strain peak, which would otherwise be ignored. skill.saveCurrentPeak(); } }); }); } /** * Populates the stored difficulty attributes with necessary data. */ populateDifficultyAttributes() { this.attributes.approachRate = this.stats.ar; this.attributes.hitCircleCount = this.beatmap.hitObjects.circles; this.attributes.maxCombo = this.beatmap.maxCombo; this.attributes.mods = this.mods.slice(); this.attributes.overallDifficulty = this.stats.od; this.attributes.sliderCount = this.beatmap.hitObjects.sliders; this.attributes.spinnerCount = this.beatmap.hitObjects.spinners; } /** * Calculates the star rating value of a difficulty. * * @param difficulty The difficulty to calculate. */ starValue(difficulty) { return Math.sqrt(difficulty) * this.difficultyMultiplier; } /** * Calculates the base performance value of a difficulty rating. * * @param rating The difficulty rating. */ basePerformanceValue(rating) { return Math.pow(5 * Math.max(1, rating / 0.0675) - 4, 3) / 100000; } } /** * An evaluator for calculating osu!droid Aim skill. */ class DroidAimEvaluator extends AimEvaluator { static wideAngleMultiplier = 1.65; static sliderMultiplier = 1.5; static velocityChangeMultiplier = 0.85; /** * Spacing threshold for a single hitobject spacing. */ static SINGLE_SPACING_THRESHOLD = 175; // ~200 1/2 BPM jumps static minSpeedBonus = 150; /** * Evaluates the difficulty of aiming the current object, based on: * * - cursor velocity to the current object, * - angle difficulty, * - sharp velocity increases, * - and slider difficulty. * * @param current The current object. * @param withSliders Whether to take slider difficulty into account. */ static evaluateDifficultyOf(current, withSliders) { if (current.object instanceof osuBase.Spinner || // Exclude overlapping objects that can be tapped at once. current.isOverlapping(true)) { return 0; } return (this.aimStrainOf(current, withSliders) + this.movementStrainOf(current)); } /** * Calculates the aim strain of a hitobject. */ static aimStrainOf(current, withSliders) { if (current.index <= 1 || current.previous(0)?.object instanceof osuBase.Spinner) { return 0; } const last = current.previous(0); const lastLast = current.previous(1); // Calculate the velocity to the current hitobject, which starts with a base distance / time assuming the last object is a hitcircle. let currentVelocity = current.lazyJumpDistance / current.strainTime; // But if the last object is a slider, then we extend the travel velocity through the slider into the current object. if (last.object instanceof osuBase.Slider && withSliders) { // Calculate the slider velocity from slider head to slider end. const travelVelocity = last.travelDistance / last.travelTime; // Calculate the movement velocity from slider end to current object. const movementVelocity = current.minimumJumpTime !== 0 ? current.minimumJumpDistance / current.minimumJumpTime : 0; // Take the larger total combined velocity. currentVelocity = Math.max(currentVelocity, movementVelocity + travelVelocity); } // As above, do the same for the previous hitobject. let prevVelocity = last.lazyJumpDistance / last.strainTime; if (lastLast.object instanceof osuBase.Slider && withSliders) { const travelVelocity = lastLast.travelDistance / lastLast.travelTime; const movementVelocity = last.minimumJumpTime !== 0 ? last.minimumJumpDistance / last.minimumJumpTime : 0; prevVelocity = Math.max(prevVelocity, movementVelocity + travelVelocity); } let wideAngleBonus = 0; let acuteAngleBonus = 0; let sliderBonus = 0; let velocityChangeBonus = 0; // Start strain with regular velocity. let strain = currentVelocity; if ( // If rhythms are the same. Math.max(current.strainTime, last.strainTime) < 1.25 * Math.min(current.strainTime, last.strainTime) && current.angle !== null && last.angle !== null && lastLast.angle !== null) { // Rewarding angles, take the smaller velocity as base. const angleBonus = Math.min(currentVelocity, prevVelocity); wideAngleBonus = this.calculateWideAngleBonus(current.angle); acuteAngleBonus = this.calculateAcuteAngleBonus(current.angle); // Only buff deltaTime exceeding 300 BPM 1/2. if (current.strainTime > 100) { acuteAngleBonus = 0; } else { acuteAngleBonus *= // Multiply by previous angle, we don't want to buff unless this is a wiggle type pattern. this.calculateAcuteAngleBonus(last.angle) * // The maximum velocity we buff is equal to 125 / strainTime. Math.min(angleBonus, 125 / current.strainTime) * // Scale buff from 300 BPM 1/2 to 400 BPM 1/2. Math.pow(Math.sin((Math.PI / 2) * Math.min(1, (100 - current.strainTime) / 25)), 2) * // Buff distance exceeding 50 (radius) up to 100 (diameter). Math.pow(Math.sin(((Math.PI / 2) * (osuBase.MathUtils.clamp(current.lazyJumpDistance, 50, 100) - 50)) / 50), 2); } // Penalize wide angles if they're repeated, reducing the penalty as last.angle gets more acute. wideAngleBonus *= angleBonus * (1 - Math.min(wideAngleBonus, Math.pow(this.calculateWideAngleBonus(last.angle), 3))); // Penalize acute angles if they're repeated, reducing the penalty as lastLast.angle gets more obtuse. acuteAngleBonus *= 0.5 + 0.5 * (1 - Math.min(acuteAngleBonus, Math.pow(this.calculateAcuteAngleBonus(lastLast.angle), 3))); } if (Math.max(prevVelocity, currentVelocity)) { // We want to use the average velocity over the whole object when awarding differences, not the individual jump and slider path velocities. prevVelocity = (last.lazyJumpDistance + lastLast.travelDistance) / last.strainTime; currentVelocity = (current.lazyJumpDistance + last.travelDistance) / current.strainTime; // Scale with ratio of difference compared to half the max distance. const distanceRatio = Math.pow(Math.sin(((Math.PI / 2) * Math.abs(prevVelocity - currentVelocity)) / Math.max(prevVelocity, currentVelocity)), 2); // Reward for % distance up to 125 / strainTime for overlaps where velocity is still changing. const overlapVelocityBuff = Math.min(125 / Math.min(current.strainTime, last.strainTime), Math.abs(prevVelocity - currentVelocity)); velocityChangeBonus = overlapVelocityBuff * distanceRatio; // Penalize for rhythm changes. velocityChangeBonus *= Math.pow(Math.min(current.strainTime, last.strainTime) / Math.max(current.strainTime, last.strainTime), 2); } if (last.object instanceof osuBase.Slider) { // Reward sliders based on velocity. sliderBonus = last.travelDistance / last.travelTime; } // Add in acute angle bonus or wide angle bonus + velocity change bonus, whichever is larger. strain += Math.max(acuteAngleBonus * this.acuteAngleMultiplier, wideAngleBonus * this.wideAngleMultiplier + velocityChangeBonus * this.velocityChangeMultiplier); // Add in additional slider velocity bonus. if (withSliders) { strain += sliderBonus * this.sliderMultiplier; } return strain; } /** * Calculates the movement strain of a hitobject. */ static movementStrainOf(current) { let speedBonus = 1; if (current.strainTime < this.minSpeedBonus) { speedBonus += 0.75 * Math.pow((this.minSpeedBonus - current.strainTime) / 45, 2); } const travelDistance = current.previous(0)?.travelDistance ?? 0; const distance = Math.min(this.SINGLE_SPACING_THRESHOLD, travelDistance + current.minimumJumpDistance); return ((50 * speedBonus * Math.pow(distance / this.SINGLE_SPACING_THRESHOLD, 5)) / current.strainTime); } } /** * A bare minimal abstract skill for fully custom skill implementations. * * This class should be considered a "processing" class and not persisted. */ class Skill { /** * The mods that this skill processes. */ mods; constructor(mods) { this.mods = mods; } } /** * Used to processes strain values of difficulty hitobjects, keep track of strain levels caused by the processed objects * and to calculate a final difficulty value representing the difficulty of hitting all the processed objects. */ class StrainSkill extends Skill { /** * The strain of currently calculated hitobject. */ currentStrain = 0; /** * The current section's strain peak. */ currentSectionPeak = 0; /** * Strain peaks are stored here. */ strainPeaks = []; sectionLength = 400; currentSectionEnd = 0; isFirstObject = true; /** * Calculates the strain value of a hitobject and stores the value in it. This value is affected by previously processed objects. * * @param current The hitobject to process. */ process(current) { // The first object doesn't generate a strain, so we begin with an incremented section end if (this.isFirstObject) { this.currentSectionEnd = Math.ceil(current.startTime / this.sectionLength) * this.sectionLength; this.isFirstObject = false; } while (current.startTime > this.currentSectionEnd) { this.saveCurrentPeak(); this.startNewSectionFrom(this.currentSectionEnd, current); this.currentSectionEnd += this.sectionLength; } // Ignore the first hitobject. this.currentStrain = this.strainValueAt(current); this.saveToHitObject(current); this.currentSectionPeak = Math.max(this.currentStrain, this.currentSectionPeak); } /** * Saves the current peak strain level to the list of strain peaks, which will be used to calculate an overall difficulty. */ saveCurrentPeak() { this.strainPeaks.push(this.currentSectionPeak); } /** * Calculates strain decay for a specified time frame. * * @param ms The time frame to calculate. */ strainDecay(ms) { return Math.pow(this.strainDecayBase, ms / 1000); } /** * Sets the initial strain level for a new section. * * @param offset The beginning of the new section in milliseconds, adjusted by speed multiplier. * @param current The current hitobject. */ startNewSectionFrom(offset, current) { // The maximum strain of the new section is not zero by default, strain decays as usual regardless of section boundaries. // This means we need to capture the strain level at the beginning of the new section, and use that as the initial peak level. this.currentSectionPeak = this.currentStrain * this.strainDecay(offset - current.previous(0).startTime); } } /** * Used to processes strain values of difficulty hitobjects, keep track of strain levels caused by the processed objects * and to calculate a final difficulty value representing the difficulty of hitting all the processed objects. */ class DroidSkill extends StrainSkill { difficultyValue() { const strains = this.strainPeaks.slice(); if (this.reducedSectionCount > 0) { strains.sort((a, b) => b - a); // We are reducing the highest strains first to account for extreme difficulty spikes. for (let i = 0; i < Math.min(strains.length, this.reducedSectionCount); ++i) { const scale = Math.log10(osuBase.Interpolation.lerp(1, 10, osuBase.MathUtils.clamp(i / this.reducedSectionCount, 0, 1))); strains[i] *= osuBase.Interpolation.lerp(this.reducedSectionBaseline, 1, scale); } } // Math here preserves the property that two notes of equal difficulty x, we have their summed difficulty = x * starsPerDouble. // This also applies to two sets of notes with equal difficulty. return Math.pow(strains.reduce((a, v) => { if (v <= 0) { return a; } return a + Math.pow(v, 1 / Math.log2(this.starsPerDouble)); }, 0), Math.log2(this.starsPerDouble)); } } /** * Represents the skill required to correctly aim at every object in the map with a uniform CircleSize and normalized distances. */ class DroidAim extends DroidSkill { skillMultiplier = 24.55; strainDecayBase = 0.15; reducedSectionCount = 10; reducedSectionBaseline = 0.75; starsPerDouble = 1.05; withSliders; constructor(mods, withSliders) { super(mods); this.withSliders = withSliders; } /** * @param current The hitobject to calculate. */ strainValueAt(current) { this.currentStrain *= this.strainDecay(current.deltaTime); this.currentStrain += DroidAimEvaluator.evaluateDifficultyOf(current, this.withSliders) * this.skillMultiplier; return this.currentStrain; } /** * @param current The hitobject to save to. */ saveToHitObject(current) { if (this.withSliders) { current.aimStrainWithSliders = this.currentStrain; } else { current.aimStrainWithoutSliders = this.currentStrain; } } } /** * An evaluator for calculating speed or tap skill. * * This class should be considered an "evaluating" class and not persisted. */ class SpeedEvaluator { // ~200 1/4 BPM streams static minSpeedBonus = 75; } /** * An evaluator for calculating osu!droid tap skill. */ class DroidTapEvaluator extends SpeedEvaluator { /** * Evaluates the difficulty of tapping the current object, based on: * * - time between pressing the previous and current object, * - distance between those objects, * - and how easily they can be cheesed. * * @param current The current object. * @param greatWindow The great hit window of the current object. * @param considerCheesability Whether to consider cheesability. */ static evaluateDifficultyOf(current, greatWindow, considerCheesability) { if (current.object instanceof osuBase.Spinner || // Exclude overlapping objects that can be tapped at once. current.isOverlapping(false)) { return 0; } let strainTime = current.strainTime; let doubletapness = 1; if (considerCheesability) { const greatWindowFull = greatWindow * 2; // Nerf doubletappable doubles. const next = current.next(0); if (next) { const currentDeltaTime = Math.max(1, current.deltaTime); const nextDeltaTime = Math.max(1, next.deltaTime); const deltaDifference = Math.abs(nextDeltaTime - currentDeltaTime); const speedRatio = currentDeltaTime / Math.max(currentDeltaTime, deltaDifference); const windowRatio = Math.pow(Math.min(1, currentDeltaTime / greatWindowFull), 2); doubletapness = Math.pow(speedRatio, 1 - windowRatio); } // Cap deltatime to the OD 300 hitwindow. // 0.58 is derived from making sure 260 BPM 1/4 OD5 streams aren't nerfed harshly, whilst 0.91 limits the effect of the cap. strainTime /= osuBase.MathUtils.clamp(strainTime / greatWindowFull / 0.58, 0.91, 1); } let speedBonus = 1; if (strainTime < this.minSpeedBonus) { speedBonus += 0.75 * Math.pow((this.minSpeedBonus - strainTime) / 40, 2); } return (speedBonus * doubletapness) / strainTime; } } /** * Represents the skill required to press keys or tap with regards to keeping up with the speed at which objects need to be hit. */ class DroidTap extends DroidSkill { skillMultiplier = 1375; reducedSectionCount = 10; reducedSectionBaseline = 0.75; strainDecayBase = 0.3; starsPerDouble = 1.1; currentTapStrain = 0; currentOriginalTapStrain = 0; greatWindow; constructor(mods, overallDifficulty) { super(mods); this.greatWindow = new osuBase.OsuHitWindow(overallDifficulty).hitWindowFor300(); } /** * @param current The hitobject to calculate. */ strainValueAt(current) { const decay = this.strainDecay(current.strainTime); this.currentTapStrain *= decay; this.currentTapStrain += DroidTapEvaluator.evaluateDifficultyOf(current, this.greatWindow, true) * this.skillMultiplier; this.currentOriginalTapStrain *= decay; this.currentOriginalTapStrain += DroidTapEvaluator.evaluateDifficultyOf(current, this.greatWindow, false) * this.skillMultiplier; this.currentOriginalTapStrain *= current.rhythmMultiplier; return this.currentTapStrain * current.rhythmMultiplier; } /** * @param current The hitobject to save to. */ saveToHitObject(current) { current.tapStrain = this.currentStrain; current.originalTapStrain = this.currentOriginalTapStrain; } } /** * An evaluator for calculating flashlight skill. * * This class should be considered an "evaluating" class and not persisted. */ class FlashlightEvaluator { static maxOpacityBonus = 0.4; static hiddenBonus = 0.2; static minVelocity = 0.5; static sliderMultiplier = 1.3; static minAngleMultiplier = 0.2; } /** * An evaluator for calculating osu!droid Flashlight skill. */ class DroidFlashlightEvaluator extends FlashlightEvaluator { /** * Evaluates the difficulty of memorizing and hitting the current object, based on: * * - distance between a number of previous objects and the current object, * - the visual opacity of the current object, * - the angle made by the current object, * - length and speed of the current object (for sliders), * - and whether Hidden mod is enabled. * * @param current The current object. * @param isHiddenMod Whether the Hidden mod is enabled. * @param withSliders Whether to take slider difficulty into account. Defaults to `true`. */ static evaluateDifficultyOf(current, isHiddenMod, withSliders = true) { if (current.object instanceof osuBase.Spinner || // Exclude overlapping objects that can be tapped at once. current.isOverlapping(true)) { return 0; } const scalingFactor = 52 / current.object.getRadius(osuBase.Modes.droid); let smallDistNerf = 1; let cumulativeStrainTime = 0; let result = 0; let last = current; let angleRepeatCount = 0; for (let i = 0; i < Math.min(current.index, 10); ++i) { const currentObject = current.previous(i); if (!(currentObject.object instanceof osuBase.Spinner) && // Exclude overlapping objects that can be tapped at once. !currentObject.isOverlapping(false)) { const jumpDistance = current.object .getStackedPosition(osuBase.Modes.droid) .subtract(currentObject.object.getStackedEndPosition(osuBase.Modes.droid)).length; cumulativeStrainTime += last.strainTime; // We want to nerf objects that can be easily seen within the Flashlight circle radius. if (i === 0) { smallDistNerf = Math.min(1, jumpDistance / 75); } // We also want to nerf stacks so that only the first object of the stack is accounted for. const stackNerf = Math.min(1, currentObject.lazyJumpDistance / scalingFactor / 25); // Bonus based on how visible the object is. const opacityBonus = 1 + this.maxOpacityBonus * (1 - current.opacityAt(currentObject.object.startTime, isHiddenMod, os