1
0
mirror of https://github.com/ppy/osu.git synced 2025-01-28 04:02:57 +08:00

Merge branch 'master' into kps

This commit is contained in:
Dean Herbert 2022-08-31 15:41:42 +09:00
commit 7337d4c1aa
134 changed files with 2993 additions and 1511 deletions

View File

@ -77,5 +77,8 @@ namespace osu.Game.Rulesets.EmptyFreeform
};
}
}
// Leave this line intact. It will bake the correct version into the ruleset on each build/release.
public override string RulesetAPIVersionSupported => CURRENT_RULESET_API_VERSION;
}
}

View File

@ -49,5 +49,8 @@ namespace osu.Game.Rulesets.Pippidon
};
public override Drawable CreateIcon() => new PippidonRulesetIcon(this);
// Leave this line intact. It will bake the correct version into the ruleset on each build/release.
public override string RulesetAPIVersionSupported => CURRENT_RULESET_API_VERSION;
}
}

View File

@ -54,5 +54,8 @@ namespace osu.Game.Rulesets.EmptyScrolling
Text = ShortName[0].ToString(),
Font = OsuFont.Default.With(size: 18),
};
// Leave this line intact. It will bake the correct version into the ruleset on each build/release.
public override string RulesetAPIVersionSupported => CURRENT_RULESET_API_VERSION;
}
}

View File

@ -46,5 +46,8 @@ namespace osu.Game.Rulesets.Pippidon
};
public override Drawable CreateIcon() => new PippidonRulesetIcon(this);
// Leave this line intact. It will bake the correct version into the ruleset on each build/release.
public override string RulesetAPIVersionSupported => CURRENT_RULESET_API_VERSION;
}
}

View File

@ -52,7 +52,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="ppy.osu.Game.Resources" Version="2022.819.0" />
<PackageReference Include="ppy.osu.Framework.Android" Version="2022.819.0" />
<PackageReference Include="ppy.osu.Framework.Android" Version="2022.825.0" />
</ItemGroup>
<ItemGroup Label="Transitive Dependencies">
<!-- Realm needs to be directly referenced in all Xamarin projects, as it will not pull in its transitive dependencies otherwise. -->

View File

@ -70,10 +70,17 @@ namespace osu.Game.Rulesets.Catch.Tests.Editor
[Cached]
private readonly BindableBeatDivisor beatDivisor;
protected override Container<Drawable> Content { get; } = new Container { RelativeSizeAxes = Axes.Both };
public EditorBeatmapDependencyContainer(IBeatmap beatmap, BindableBeatDivisor beatDivisor)
{
editorClock = new EditorClock(beatmap, beatDivisor);
this.beatDivisor = beatDivisor;
InternalChildren = new Drawable[]
{
editorClock = new EditorClock(beatmap, beatDivisor),
Content,
};
}
}
}

View File

@ -3,30 +3,30 @@
#nullable disable
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Rulesets.Catch.Mods;
using osu.Game.Rulesets.Catch.UI;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using System;
using System.Collections.Generic;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Bindings;
using osu.Game.Rulesets.Catch.Replays;
using osu.Game.Rulesets.Replays.Types;
using osu.Framework.Localisation;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Graphics;
using osu.Game.Rulesets.Catch.Beatmaps;
using osu.Game.Rulesets.Catch.Difficulty;
using osu.Game.Rulesets.Catch.Scoring;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Scoring;
using System;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Localisation;
using osu.Game.Rulesets.Catch.Edit;
using osu.Game.Rulesets.Catch.Mods;
using osu.Game.Rulesets.Catch.Replays;
using osu.Game.Rulesets.Catch.Scoring;
using osu.Game.Rulesets.Catch.Skinning.Legacy;
using osu.Game.Rulesets.Catch.UI;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Catch
@ -43,6 +43,8 @@ namespace osu.Game.Rulesets.Catch
public const string SHORT_NAME = "fruits";
public override string RulesetAPIVersionSupported => CURRENT_RULESET_API_VERSION;
public override IEnumerable<KeyBinding> GetDefaultKeyBindings(int variant = 0) => new[]
{
new KeyBinding(InputKey.Z, CatchAction.MoveLeft),

View File

@ -35,7 +35,7 @@ namespace osu.Game.Rulesets.Mania.Tests.Editor
public void Setup() => Schedule(() =>
{
BeatDivisor.Value = 8;
Clock.Seek(0);
EditorClock.Seek(0);
Child = composer = new TestComposer { RelativeSizeAxes = Axes.Both };
});
@ -53,7 +53,7 @@ namespace osu.Game.Rulesets.Mania.Tests.Editor
{
lastObject = this.ChildrenOfType<DrawableHitObject>().Single(d => d.HitObject == composer.EditorBeatmap.HitObjects.Last());
originalTime = lastObject.HitObject.StartTime;
Clock.Seek(composer.EditorBeatmap.HitObjects.Last().StartTime);
EditorClock.Seek(composer.EditorBeatmap.HitObjects.Last().StartTime);
});
AddStep("select all objects", () => composer.EditorBeatmap.SelectedHitObjects.AddRange(composer.EditorBeatmap.HitObjects));
@ -90,7 +90,7 @@ namespace osu.Game.Rulesets.Mania.Tests.Editor
{
lastObject = this.ChildrenOfType<DrawableHitObject>().Single(d => d.HitObject == composer.EditorBeatmap.HitObjects.Last());
originalTime = lastObject.HitObject.StartTime;
Clock.Seek(composer.EditorBeatmap.HitObjects.Last().StartTime);
EditorClock.Seek(composer.EditorBeatmap.HitObjects.Last().StartTime);
});
AddStep("select all objects", () => composer.EditorBeatmap.SelectedHitObjects.AddRange(composer.EditorBeatmap.HitObjects));
@ -125,7 +125,7 @@ namespace osu.Game.Rulesets.Mania.Tests.Editor
AddStep("seek to last object", () =>
{
lastObject = this.ChildrenOfType<DrawableHitObject>().Single(d => d.HitObject == composer.EditorBeatmap.HitObjects.Last());
Clock.Seek(composer.EditorBeatmap.HitObjects.Last().StartTime);
EditorClock.Seek(composer.EditorBeatmap.HitObjects.Last().StartTime);
});
AddStep("select all objects", () => composer.EditorBeatmap.SelectedHitObjects.AddRange(composer.EditorBeatmap.HitObjects));

View File

@ -4,11 +4,6 @@
#nullable disable
using System;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mania.Mods;
using osu.Game.Rulesets.Mania.UI;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Extensions.EnumExtensions;
@ -16,11 +11,10 @@ using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Bindings;
using osu.Framework.Localisation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mania.Replays;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Difficulty;
@ -31,13 +25,19 @@ using osu.Game.Rulesets.Mania.Configuration;
using osu.Game.Rulesets.Mania.Difficulty;
using osu.Game.Rulesets.Mania.Edit;
using osu.Game.Rulesets.Mania.Edit.Setup;
using osu.Game.Rulesets.Mania.Mods;
using osu.Game.Rulesets.Mania.Replays;
using osu.Game.Rulesets.Mania.Scoring;
using osu.Game.Rulesets.Mania.Skinning.Legacy;
using osu.Game.Rulesets.Mania.UI;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Rulesets.Scoring;
using osu.Game.Skinning;
using osu.Game.Rulesets.UI;
using osu.Game.Scoring;
using osu.Game.Screens.Edit.Setup;
using osu.Game.Screens.Ranking.Statistics;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Mania
{
@ -60,6 +60,8 @@ namespace osu.Game.Rulesets.Mania
public const string SHORT_NAME = "mania";
public override string RulesetAPIVersionSupported => CURRENT_RULESET_API_VERSION;
public override HitObjectComposer CreateHitObjectComposer() => new ManiaHitObjectComposer(this);
public override ISkin CreateLegacySkinProvider(ISkin skin, IBeatmap beatmap) => new ManiaLegacySkinTransformer(skin, beatmap);

View File

@ -3,9 +3,11 @@
using System.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Framework.Utils;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu.Edit;
using osu.Game.Rulesets.Osu.Objects;
using osuTK;
using osuTK.Input;
@ -14,6 +16,8 @@ namespace osu.Game.Rulesets.Osu.Tests.Editor
{
public class TestSceneObjectMerging : TestSceneOsuEditor
{
private OsuSelectionHandler selectionHandler => Editor.ChildrenOfType<OsuSelectionHandler>().First();
[Test]
public void TestSimpleMerge()
{
@ -29,6 +33,9 @@ namespace osu.Game.Rulesets.Osu.Tests.Editor
EditorBeatmap.SelectedHitObjects.Add(circle2);
});
moveMouseToHitObject(1);
AddAssert("merge option available", () => selectionHandler.ContextMenuItems.Any(o => o.Text.Value == "Merge selection"));
mergeSelection();
AddAssert("slider created", () => circle1 is not null && circle2 is not null && sliderCreatedFor(
@ -77,6 +84,8 @@ namespace osu.Game.Rulesets.Osu.Tests.Editor
return sliderCreatedFor(args);
});
AddAssert("samples exist", sliderSampleExist);
AddStep("undo", () => Editor.Undo());
AddAssert("merged objects restored", () => circle1 is not null && circle2 is not null && slider is not null && objectsRestored(circle1, slider, circle2));
}
@ -122,6 +131,8 @@ namespace osu.Game.Rulesets.Osu.Tests.Editor
return sliderCreatedFor(args);
});
AddAssert("samples exist", sliderSampleExist);
AddAssert("merged slider matches first slider", () =>
{
var mergedSlider = (Slider)EditorBeatmap.SelectedHitObjects.First();
@ -165,9 +176,35 @@ namespace osu.Game.Rulesets.Osu.Tests.Editor
(pos: circle1.Position, pathType: PathType.Linear),
(pos: circle2.Position, pathType: null)));
AddAssert("samples exist", sliderSampleExist);
AddAssert("spinner not merged", () => EditorBeatmap.HitObjects.Contains(spinner));
}
[Test]
public void TestIllegalMerge()
{
HitCircle? circle1 = null;
HitCircle? circle2 = null;
AddStep("add two circles on the same position", () =>
{
circle1 = new HitCircle();
circle2 = new HitCircle { Position = circle1.Position + Vector2.UnitX, StartTime = 1 };
EditorClock.Seek(0);
EditorBeatmap.Add(circle1);
EditorBeatmap.Add(circle2);
EditorBeatmap.SelectedHitObjects.Add(circle1);
EditorBeatmap.SelectedHitObjects.Add(circle2);
});
moveMouseToHitObject(1);
AddAssert("merge option not available", () => selectionHandler.ContextMenuItems.Length > 0 && selectionHandler.ContextMenuItems.All(o => o.Text.Value != "Merge selection"));
mergeSelection();
AddAssert("circles not merged", () => circle1 is not null && circle2 is not null
&& EditorBeatmap.HitObjects.Contains(circle1) && EditorBeatmap.HitObjects.Contains(circle2));
}
private void mergeSelection()
{
AddStep("merge selection", () =>
@ -209,5 +246,27 @@ namespace osu.Game.Rulesets.Osu.Tests.Editor
return true;
}
private bool sliderSampleExist()
{
if (EditorBeatmap.SelectedHitObjects.Count != 1)
return false;
var mergedSlider = (Slider)EditorBeatmap.SelectedHitObjects.First();
return mergedSlider.Samples[0] is not null;
}
private void moveMouseToHitObject(int index)
{
AddStep($"hover mouse over hit object {index}", () =>
{
if (EditorBeatmap.HitObjects.Count <= index)
return;
Vector2 position = ((OsuHitObject)EditorBeatmap.HitObjects[index]).Position;
InputManager.MoveMouseTo(selectionHandler.ToScreenSpace(position));
});
}
}
}

View File

@ -59,10 +59,9 @@ namespace osu.Game.Rulesets.Osu.Tests.Editor
}
});
editorClock = new EditorClock(editorBeatmap);
base.Content.Children = new Drawable[]
{
editorClock = new EditorClock(editorBeatmap),
snapProvider,
Content
};

View File

@ -182,7 +182,7 @@ namespace osu.Game.Rulesets.Osu.Tests.Editor
{
AddStep($"click context menu item \"{contextMenuText}\"", () =>
{
MenuItem item = visualiser.ContextMenuItems[1].Items.FirstOrDefault(menuItem => menuItem.Text.Value == contextMenuText);
MenuItem item = visualiser.ContextMenuItems.FirstOrDefault(menuItem => menuItem.Text.Value == "Curve type")?.Items.FirstOrDefault(menuItem => menuItem.Text.Value == contextMenuText);
item?.Action?.Value();
});

View File

@ -0,0 +1,255 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Testing;
using osu.Framework.Utils;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Screens.Edit.Compose.Components;
using osu.Game.Tests.Beatmaps;
using osu.Game.Tests.Visual;
using osuTK;
namespace osu.Game.Rulesets.Osu.Tests.Editor
{
public class TestSceneSliderSplitting : EditorTestScene
{
protected override Ruleset CreateEditorRuleset() => new OsuRuleset();
protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) => new TestBeatmap(ruleset, false);
private ComposeBlueprintContainer blueprintContainer
=> Editor.ChildrenOfType<ComposeBlueprintContainer>().First();
private Slider? slider;
private PathControlPointVisualiser? visualiser;
private const double split_gap = 100;
[Test]
public void TestBasicSplit()
{
double endTime = 0;
AddStep("add slider", () =>
{
slider = new Slider
{
Position = new Vector2(0, 50),
Path = new SliderPath(new[]
{
new PathControlPoint(Vector2.Zero, PathType.PerfectCurve),
new PathControlPoint(new Vector2(150, 150)),
new PathControlPoint(new Vector2(300, 0), PathType.PerfectCurve),
new PathControlPoint(new Vector2(400, 0)),
new PathControlPoint(new Vector2(400, 150))
})
};
EditorBeatmap.Add(slider);
endTime = slider.EndTime;
});
AddStep("select added slider", () =>
{
EditorBeatmap.SelectedHitObjects.Add(slider);
visualiser = blueprintContainer.SelectionBlueprints.First(o => o.Item == slider).ChildrenOfType<PathControlPointVisualiser>().First();
});
moveMouseToControlPoint(2);
AddStep("select control point", () =>
{
if (visualiser is not null) visualiser.Pieces[2].IsSelected.Value = true;
});
addContextMenuItemStep("Split control point");
AddAssert("slider split", () => slider is not null && EditorBeatmap.HitObjects.Count == 2 &&
sliderCreatedFor((Slider)EditorBeatmap.HitObjects[0], 0, EditorBeatmap.HitObjects[1].StartTime - split_gap,
(new Vector2(0, 50), PathType.PerfectCurve),
(new Vector2(150, 200), null),
(new Vector2(300, 50), null)
) && sliderCreatedFor((Slider)EditorBeatmap.HitObjects[1], slider.StartTime, endTime + split_gap,
(new Vector2(300, 50), PathType.PerfectCurve),
(new Vector2(400, 50), null),
(new Vector2(400, 200), null)
));
AddStep("undo", () => Editor.Undo());
AddAssert("original slider restored", () => EditorBeatmap.HitObjects.Count == 1 && sliderCreatedFor((Slider)EditorBeatmap.HitObjects[0], 0, endTime,
(new Vector2(0, 50), PathType.PerfectCurve),
(new Vector2(150, 200), null),
(new Vector2(300, 50), PathType.PerfectCurve),
(new Vector2(400, 50), null),
(new Vector2(400, 200), null)
));
}
[Test]
public void TestDoubleSplit()
{
double endTime = 0;
AddStep("add slider", () =>
{
slider = new Slider
{
Position = new Vector2(0, 50),
Path = new SliderPath(new[]
{
new PathControlPoint(Vector2.Zero, PathType.PerfectCurve),
new PathControlPoint(new Vector2(150, 150)),
new PathControlPoint(new Vector2(300, 0), PathType.Bezier),
new PathControlPoint(new Vector2(400, 0)),
new PathControlPoint(new Vector2(400, 150), PathType.Catmull),
new PathControlPoint(new Vector2(300, 200)),
new PathControlPoint(new Vector2(400, 250))
})
};
EditorBeatmap.Add(slider);
endTime = slider.EndTime;
});
AddStep("select added slider", () =>
{
EditorBeatmap.SelectedHitObjects.Add(slider);
visualiser = blueprintContainer.SelectionBlueprints.First(o => o.Item == slider).ChildrenOfType<PathControlPointVisualiser>().First();
});
moveMouseToControlPoint(2);
AddStep("select first control point", () =>
{
if (visualiser is not null) visualiser.Pieces[2].IsSelected.Value = true;
});
moveMouseToControlPoint(4);
AddStep("select second control point", () =>
{
if (visualiser is not null) visualiser.Pieces[4].IsSelected.Value = true;
});
addContextMenuItemStep("Split 2 control points");
AddAssert("slider split", () => slider is not null && EditorBeatmap.HitObjects.Count == 3 &&
sliderCreatedFor((Slider)EditorBeatmap.HitObjects[0], 0, EditorBeatmap.HitObjects[1].StartTime - split_gap,
(new Vector2(0, 50), PathType.PerfectCurve),
(new Vector2(150, 200), null),
(new Vector2(300, 50), null)
) && sliderCreatedFor((Slider)EditorBeatmap.HitObjects[1], EditorBeatmap.HitObjects[0].GetEndTime() + split_gap, slider.StartTime - split_gap,
(new Vector2(300, 50), PathType.Bezier),
(new Vector2(400, 50), null),
(new Vector2(400, 200), null)
) && sliderCreatedFor((Slider)EditorBeatmap.HitObjects[2], EditorBeatmap.HitObjects[1].GetEndTime() + split_gap, endTime + split_gap * 2,
(new Vector2(400, 200), PathType.Catmull),
(new Vector2(300, 250), null),
(new Vector2(400, 300), null)
));
}
[Test]
public void TestSplitRetainsHitsounds()
{
HitSampleInfo? sample = null;
AddStep("add slider", () =>
{
slider = new Slider
{
Position = new Vector2(0, 50),
LegacyLastTickOffset = 36, // This is necessary for undo to retain the sample control point
Path = new SliderPath(new[]
{
new PathControlPoint(Vector2.Zero, PathType.PerfectCurve),
new PathControlPoint(new Vector2(150, 150)),
new PathControlPoint(new Vector2(300, 0), PathType.PerfectCurve),
new PathControlPoint(new Vector2(400, 0)),
new PathControlPoint(new Vector2(400, 150))
})
};
EditorBeatmap.Add(slider);
});
AddStep("add hitsounds", () =>
{
if (slider is null) return;
slider.SampleControlPoint.SampleBank = "soft";
slider.SampleControlPoint.SampleVolume = 70;
sample = new HitSampleInfo("hitwhistle");
slider.Samples.Add(sample);
});
AddStep("select added slider", () =>
{
EditorBeatmap.SelectedHitObjects.Add(slider);
visualiser = blueprintContainer.SelectionBlueprints.First(o => o.Item == slider).ChildrenOfType<PathControlPointVisualiser>().First();
});
moveMouseToControlPoint(2);
AddStep("select control point", () =>
{
if (visualiser is not null) visualiser.Pieces[2].IsSelected.Value = true;
});
addContextMenuItemStep("Split control point");
AddAssert("sliders have hitsounds", hasHitsounds);
AddStep("select first slider", () => EditorBeatmap.SelectedHitObjects.Add(EditorBeatmap.HitObjects[0]));
AddStep("remove first slider", () => EditorBeatmap.RemoveAt(0));
AddStep("undo", () => Editor.Undo());
AddAssert("sliders have hitsounds", hasHitsounds);
bool hasHitsounds() => sample is not null &&
EditorBeatmap.HitObjects.All(o => o.SampleControlPoint.SampleBank == "soft" &&
o.SampleControlPoint.SampleVolume == 70 &&
o.Samples.Contains(sample));
}
private bool sliderCreatedFor(Slider s, double startTime, double endTime, params (Vector2 pos, PathType? pathType)[] expectedControlPoints)
{
if (!Precision.AlmostEquals(s.StartTime, startTime, 1) || !Precision.AlmostEquals(s.EndTime, endTime, 1)) return false;
int i = 0;
foreach ((Vector2 pos, PathType? pathType) in expectedControlPoints)
{
var controlPoint = s.Path.ControlPoints[i++];
if (!Precision.AlmostEquals(controlPoint.Position + s.Position, pos) || controlPoint.Type != pathType)
return false;
}
return true;
}
private void moveMouseToControlPoint(int index)
{
AddStep($"move mouse to control point {index}", () =>
{
if (slider is null || visualiser is null) return;
Vector2 position = slider.Path.ControlPoints[index].Position + slider.Position;
InputManager.MoveMouseTo(visualiser.Pieces[0].Parent.ToScreenSpace(position));
});
}
private void addContextMenuItemStep(string contextMenuText)
{
AddStep($"click context menu item \"{contextMenuText}\"", () =>
{
if (visualiser is null) return;
MenuItem? item = visualiser.ContextMenuItems.FirstOrDefault(menuItem => menuItem.Text.Value == contextMenuText);
item?.Action?.Value();
});
}
}
}

View File

@ -18,11 +18,14 @@ namespace osu.Game.Rulesets.Osu.Difficulty.Evaluators
private const double min_velocity = 0.5;
private const double slider_multiplier = 1.3;
private const double min_angle_multiplier = 0.2;
/// <summary>
/// Evaluates the difficulty of memorising and hitting an object, based on:
/// <list type="bullet">
/// <item><description>distance between a number of previous objects and the current object,</description></item>
/// <item><description>the visual opacity of the current object,</description></item>
/// <item><description>the angle made by the current object,</description></item>
/// <item><description>length and speed of the current object (for sliders),</description></item>
/// <item><description>and whether the hidden mod is enabled.</description></item>
/// </list>
@ -43,6 +46,8 @@ namespace osu.Game.Rulesets.Osu.Difficulty.Evaluators
OsuDifficultyHitObject lastObj = osuCurrent;
double angleRepeatCount = 0.0;
// This is iterating backwards in time from the current object.
for (int i = 0; i < Math.Min(current.Index, 10); i++)
{
@ -66,6 +71,13 @@ namespace osu.Game.Rulesets.Osu.Difficulty.Evaluators
double opacityBonus = 1.0 + max_opacity_bonus * (1.0 - osuCurrent.OpacityAt(currentHitObject.StartTime, hidden));
result += stackNerf * opacityBonus * scalingFactor * jumpDistance / cumulativeStrainTime;
if (currentObj.Angle != null && osuCurrent.Angle != null)
{
// Objects further back in time should count less for the nerf.
if (Math.Abs(currentObj.Angle.Value - osuCurrent.Angle.Value) < 0.02)
angleRepeatCount += Math.Max(1.0 - 0.1 * i, 0.0);
}
}
lastObj = currentObj;
@ -77,6 +89,9 @@ namespace osu.Game.Rulesets.Osu.Difficulty.Evaluators
if (hidden)
result *= 1.0 + hidden_bonus;
// Nerf patterns with repeated angles.
result *= min_angle_multiplier + (1.0 - min_angle_multiplier) / (angleRepeatCount + 1.0);
double sliderBonus = 0.0;
if (osuCurrent.BaseObject is Slider osuSlider)

View File

@ -26,7 +26,7 @@ namespace osu.Game.Rulesets.Osu.Difficulty.Skills
hasHiddenMod = mods.Any(m => m is OsuModHidden);
}
private double skillMultiplier => 0.05;
private double skillMultiplier => 0.052;
private double strainDecayBase => 0.15;
private double currentStrain;

View File

@ -43,6 +43,7 @@ namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components
private InputManager inputManager;
public Action<List<PathControlPoint>> RemoveControlPointsRequested;
public Action<List<PathControlPoint>> SplitControlPointsRequested;
[Resolved(CanBeNull = true)]
private IDistanceSnapProvider snapProvider { get; set; }
@ -104,6 +105,29 @@ namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components
return true;
}
private bool splitSelected()
{
List<PathControlPoint> controlPointsToSplitAt = Pieces.Where(p => p.IsSelected.Value && isSplittable(p)).Select(p => p.ControlPoint).ToList();
// Ensure that there are any points to be split
if (controlPointsToSplitAt.Count == 0)
return false;
changeHandler?.BeginChange();
SplitControlPointsRequested?.Invoke(controlPointsToSplitAt);
changeHandler?.EndChange();
// Since pieces are re-used, they will not point to the deleted control points while remaining selected
foreach (var piece in Pieces)
piece.IsSelected.Value = false;
return true;
}
private bool isSplittable(PathControlPointPiece p) =>
// A slider can only be split on control points which connect two different slider segments.
p.ControlPoint.Type.HasValue && p != Pieces.FirstOrDefault() && p != Pieces.LastOrDefault();
private void onControlPointsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
@ -142,8 +166,10 @@ namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components
case NotifyCollectionChangedAction.Remove:
foreach (var point in e.OldItems.Cast<PathControlPoint>())
{
Pieces.RemoveAll(p => p.ControlPoint == point);
Connections.RemoveAll(c => c.ControlPoint == point);
foreach (var piece in Pieces.Where(p => p.ControlPoint == point).ToArray())
piece.RemoveAndDisposeImmediately();
foreach (var connection in Connections.Where(c => c.ControlPoint == point).ToArray())
connection.RemoveAndDisposeImmediately();
}
// If removing before the end of the path,
@ -322,25 +348,42 @@ namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components
if (count == 0)
return null;
List<MenuItem> items = new List<MenuItem>();
var splittablePieces = selectedPieces.Where(isSplittable).ToList();
int splittableCount = splittablePieces.Count;
List<MenuItem> curveTypeItems = new List<MenuItem>();
if (!selectedPieces.Contains(Pieces[0]))
items.Add(createMenuItemForPathType(null));
curveTypeItems.Add(createMenuItemForPathType(null));
// todo: hide/disable items which aren't valid for selected points
items.Add(createMenuItemForPathType(PathType.Linear));
items.Add(createMenuItemForPathType(PathType.PerfectCurve));
items.Add(createMenuItemForPathType(PathType.Bezier));
items.Add(createMenuItemForPathType(PathType.Catmull));
curveTypeItems.Add(createMenuItemForPathType(PathType.Linear));
curveTypeItems.Add(createMenuItemForPathType(PathType.PerfectCurve));
curveTypeItems.Add(createMenuItemForPathType(PathType.Bezier));
curveTypeItems.Add(createMenuItemForPathType(PathType.Catmull));
return new MenuItem[]
var menuItems = new List<MenuItem>
{
new OsuMenuItem($"Delete {"control point".ToQuantity(count, count > 1 ? ShowQuantityAs.Numeric : ShowQuantityAs.None)}", MenuItemType.Destructive, () => DeleteSelected()),
new OsuMenuItem("Curve type")
{
Items = items
Items = curveTypeItems
}
};
if (splittableCount > 0)
{
menuItems.Add(new OsuMenuItem($"Split {"control point".ToQuantity(splittableCount, splittableCount > 1 ? ShowQuantityAs.Numeric : ShowQuantityAs.None)}",
MenuItemType.Destructive,
() => splitSelected()));
}
menuItems.Add(
new OsuMenuItem($"Delete {"control point".ToQuantity(count, count > 1 ? ShowQuantityAs.Numeric : ShowQuantityAs.None)}",
MenuItemType.Destructive,
() => DeleteSelected())
);
return menuItems.ToArray();
}
}

View File

@ -13,6 +13,7 @@ using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osu.Framework.Utils;
using osu.Game.Audio;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets.Edit;
@ -111,7 +112,8 @@ namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders
{
AddInternal(ControlPointVisualiser = new PathControlPointVisualiser(HitObject, true)
{
RemoveControlPointsRequested = removeControlPoints
RemoveControlPointsRequested = removeControlPoints,
SplitControlPointsRequested = splitControlPoints
});
base.OnSelected();
@ -249,6 +251,74 @@ namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders
HitObject.Position += first;
}
private void splitControlPoints(List<PathControlPoint> controlPointsToSplitAt)
{
// Arbitrary gap in milliseconds to put between split slider pieces
const double split_gap = 100;
// Ensure that there are any points to be split
if (controlPointsToSplitAt.Count == 0)
return;
editorBeatmap.SelectedHitObjects.Clear();
foreach (var splitPoint in controlPointsToSplitAt)
{
if (splitPoint == controlPoints[0] || splitPoint == controlPoints[^1] || splitPoint.Type is null)
continue;
// Split off the section of slider before this control point so the remaining control points to split are in the latter part of the slider.
int index = controlPoints.IndexOf(splitPoint);
if (index <= 0)
continue;
// Extract the split portion and remove from the original slider.
var splitControlPoints = controlPoints.Take(index + 1).ToList();
controlPoints.RemoveRange(0, index);
// Turn the control points which were split off into a new slider.
var samplePoint = (SampleControlPoint)HitObject.SampleControlPoint.DeepClone();
var difficultyPoint = (DifficultyControlPoint)HitObject.DifficultyControlPoint.DeepClone();
var newSlider = new Slider
{
StartTime = HitObject.StartTime,
Position = HitObject.Position + splitControlPoints[0].Position,
NewCombo = HitObject.NewCombo,
SampleControlPoint = samplePoint,
DifficultyControlPoint = difficultyPoint,
LegacyLastTickOffset = HitObject.LegacyLastTickOffset,
Samples = HitObject.Samples.Select(s => s.With()).ToList(),
RepeatCount = HitObject.RepeatCount,
NodeSamples = HitObject.NodeSamples.Select(n => (IList<HitSampleInfo>)n.Select(s => s.With()).ToList()).ToList(),
Path = new SliderPath(splitControlPoints.Select(o => new PathControlPoint(o.Position - splitControlPoints[0].Position, o == splitControlPoints[^1] ? null : o.Type)).ToArray())
};
// Increase the start time of the slider before adding the new slider so the new slider is immediately inserted at the correct index and internal state remains valid.
HitObject.StartTime += split_gap;
editorBeatmap.Add(newSlider);
HitObject.NewCombo = false;
HitObject.Path.ExpectedDistance.Value -= newSlider.Path.CalculatedDistance;
HitObject.StartTime += newSlider.SpanDuration;
// In case the remainder of the slider has no length left over, give it length anyways so we don't get a 0 length slider.
if (HitObject.Path.ExpectedDistance.Value <= Precision.DOUBLE_EPSILON)
{
HitObject.Path.ExpectedDistance.Value = null;
}
}
// Once all required pieces have been split off, the original slider has the final split.
// As a final step, we must reset its control points to have an origin of (0,0).
Vector2 first = controlPoints[0].Position;
foreach (var c in controlPoints)
c.Position -= first;
HitObject.Position += first;
}
private void convertToStream()
{
if (editorBeatmap == null || beatDivisor == null)

View File

@ -358,7 +358,7 @@ namespace osu.Game.Rulesets.Osu.Edit
{
var mergeableObjects = selectedMergeableObjects;
if (mergeableObjects.Length < 2)
if (!canMerge(mergeableObjects))
return;
ChangeHandler?.BeginChange();
@ -371,6 +371,7 @@ namespace osu.Game.Rulesets.Osu.Edit
Position = firstHitObject.Position,
NewCombo = firstHitObject.NewCombo,
SampleControlPoint = firstHitObject.SampleControlPoint,
Samples = firstHitObject.Samples,
};
if (mergedHitObject.Path.ControlPoints.Count == 0)
@ -444,8 +445,13 @@ namespace osu.Game.Rulesets.Osu.Edit
foreach (var item in base.GetContextMenuItemsForSelection(selection))
yield return item;
if (selectedMergeableObjects.Length > 1)
if (canMerge(selectedMergeableObjects))
yield return new OsuMenuItem("Merge selection", MenuItemType.Destructive, mergeSelection);
}
private bool canMerge(IReadOnlyList<OsuHitObject> objects) =>
objects.Count > 1
&& (objects.Any(h => h is Slider)
|| objects.Zip(objects.Skip(1), (h1, h2) => Precision.DefinitelyBigger(Vector2.DistanceSquared(h1.Position, h2.Position), 1)).Any(x => x));
}
}

View File

@ -31,8 +31,6 @@ namespace osu.Game.Rulesets.Osu.Mods
private OsuInputManager inputManager = null!;
private IFrameStableClock gameplayClock = null!;
private List<OsuReplayFrame> replayFrames = null!;
private int currentFrame;
@ -41,7 +39,7 @@ namespace osu.Game.Rulesets.Osu.Mods
{
if (currentFrame == replayFrames.Count - 1) return;
double time = gameplayClock.CurrentTime;
double time = playfield.Clock.CurrentTime;
// Very naive implementation of autopilot based on proximity to replay frames.
// TODO: this needs to be based on user interactions to better match stable (pausing until judgement is registered).
@ -56,8 +54,6 @@ namespace osu.Game.Rulesets.Osu.Mods
public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset)
{
gameplayClock = drawableRuleset.FrameStableClock;
// Grab the input manager to disable the user's cursor, and for future use
inputManager = (OsuInputManager)drawableRuleset.KeyBindingInputManager;
inputManager.AllowUserCursorMovement = false;

View File

@ -5,6 +5,7 @@ using System;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Framework.Timing;
using osu.Framework.Utils;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
@ -27,8 +28,6 @@ namespace osu.Game.Rulesets.Osu.Mods
public override double ScoreMultiplier => 0.5;
public override Type[] IncompatibleMods => new[] { typeof(OsuModAutopilot), typeof(OsuModWiggle), typeof(OsuModTransform), typeof(ModAutoplay), typeof(OsuModRelax), typeof(OsuModRepel) };
private IFrameStableClock gameplayClock = null!;
[SettingSource("Attraction strength", "How strong the pull is.", 0)]
public BindableFloat AttractionStrength { get; } = new BindableFloat(0.5f)
{
@ -39,8 +38,6 @@ namespace osu.Game.Rulesets.Osu.Mods
public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset)
{
gameplayClock = drawableRuleset.FrameStableClock;
// Hide judgment displays and follow points as they won't make any sense.
// Judgements can potentially be turned on in a future where they display at a position relative to their drawable counterpart.
drawableRuleset.Playfield.DisplayJudgements.Value = false;
@ -56,27 +53,27 @@ namespace osu.Game.Rulesets.Osu.Mods
switch (drawable)
{
case DrawableHitCircle circle:
easeTo(circle, cursorPos);
easeTo(playfield.Clock, circle, cursorPos);
break;
case DrawableSlider slider:
if (!slider.HeadCircle.Result.HasResult)
easeTo(slider, cursorPos);
easeTo(playfield.Clock, slider, cursorPos);
else
easeTo(slider, cursorPos - slider.Ball.DrawPosition);
easeTo(playfield.Clock, slider, cursorPos - slider.Ball.DrawPosition);
break;
}
}
}
private void easeTo(DrawableHitObject hitObject, Vector2 destination)
private void easeTo(IFrameBasedClock clock, DrawableHitObject hitObject, Vector2 destination)
{
double dampLength = Interpolation.Lerp(3000, 40, AttractionStrength.Value);
float x = (float)Interpolation.DampContinuously(hitObject.X, destination.X, dampLength, gameplayClock.ElapsedFrameTime);
float y = (float)Interpolation.DampContinuously(hitObject.Y, destination.Y, dampLength, gameplayClock.ElapsedFrameTime);
float x = (float)Interpolation.DampContinuously(hitObject.X, destination.X, dampLength, clock.ElapsedFrameTime);
float y = (float)Interpolation.DampContinuously(hitObject.Y, destination.Y, dampLength, clock.ElapsedFrameTime);
hitObject.Position = new Vector2(x, y);
}

View File

@ -2,9 +2,9 @@
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using osu.Framework.Bindables;
using osu.Framework.Localisation;
using osu.Framework.Timing;
using osu.Framework.Utils;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
@ -27,8 +27,6 @@ namespace osu.Game.Rulesets.Osu.Mods
public override double ScoreMultiplier => 1;
public override Type[] IncompatibleMods => new[] { typeof(OsuModAutopilot), typeof(OsuModWiggle), typeof(OsuModTransform), typeof(ModAutoplay), typeof(OsuModMagnetised) };
private IFrameStableClock? gameplayClock;
[SettingSource("Repulsion strength", "How strong the repulsion is.", 0)]
public BindableFloat RepulsionStrength { get; } = new BindableFloat(0.5f)
{
@ -39,8 +37,6 @@ namespace osu.Game.Rulesets.Osu.Mods
public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset)
{
gameplayClock = drawableRuleset.FrameStableClock;
// Hide judgment displays and follow points as they won't make any sense.
// Judgements can potentially be turned on in a future where they display at a position relative to their drawable counterpart.
drawableRuleset.Playfield.DisplayJudgements.Value = false;
@ -69,29 +65,27 @@ namespace osu.Game.Rulesets.Osu.Mods
switch (drawable)
{
case DrawableHitCircle circle:
easeTo(circle, destination, cursorPos);
easeTo(playfield.Clock, circle, destination, cursorPos);
break;
case DrawableSlider slider:
if (!slider.HeadCircle.Result.HasResult)
easeTo(slider, destination, cursorPos);
easeTo(playfield.Clock, slider, destination, cursorPos);
else
easeTo(slider, destination - slider.Ball.DrawPosition, cursorPos);
easeTo(playfield.Clock, slider, destination - slider.Ball.DrawPosition, cursorPos);
break;
}
}
}
private void easeTo(DrawableHitObject hitObject, Vector2 destination, Vector2 cursorPos)
private void easeTo(IFrameBasedClock clock, DrawableHitObject hitObject, Vector2 destination, Vector2 cursorPos)
{
Debug.Assert(gameplayClock != null);
double dampLength = Vector2.Distance(hitObject.Position, cursorPos) / (0.04 * RepulsionStrength.Value + 0.04);
float x = (float)Interpolation.DampContinuously(hitObject.X, destination.X, dampLength, gameplayClock.ElapsedFrameTime);
float y = (float)Interpolation.DampContinuously(hitObject.Y, destination.Y, dampLength, gameplayClock.ElapsedFrameTime);
float x = (float)Interpolation.DampContinuously(hitObject.X, destination.X, dampLength, clock.ElapsedFrameTime);
float y = (float)Interpolation.DampContinuously(hitObject.Y, destination.Y, dampLength, clock.ElapsedFrameTime);
hitObject.Position = new Vector2(x, y);
}

View File

@ -59,6 +59,9 @@ namespace osu.Game.Rulesets.Osu.Mods
Value = null
};
[SettingSource("Metronome ticks", "Whether a metronome beat should play in the background")]
public BindableBool Metronome { get; } = new BindableBool(true);
#region Constants
/// <summary>
@ -337,7 +340,8 @@ namespace osu.Game.Rulesets.Osu.Mods
public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset)
{
drawableRuleset.Overlays.Add(new MetronomeBeat(drawableRuleset.Beatmap.HitObjects.First().StartTime));
if (Metronome.Value)
drawableRuleset.Overlays.Add(new MetronomeBeat(drawableRuleset.Beatmap.HitObjects.First().StartTime));
}
#endregion

View File

@ -3,42 +3,42 @@
#nullable disable
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Rulesets.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Overlays.Settings;
using osu.Framework.Input.Bindings;
using osu.Game.Rulesets.Osu.Edit;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Replays;
using osu.Game.Rulesets.Replays.Types;
using osu.Framework.Localisation;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Rulesets.Osu.Configuration;
using osu.Game.Rulesets.Osu.Difficulty;
using osu.Game.Rulesets.Osu.Scoring;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Skinning;
using System;
using System.Linq;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Localisation;
using osu.Game.Rulesets.Osu.Edit;
using osu.Game.Rulesets.Osu.Edit.Setup;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Replays;
using osu.Game.Rulesets.Osu.Scoring;
using osu.Game.Rulesets.Osu.Skinning.Legacy;
using osu.Game.Rulesets.Osu.Statistics;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
using osu.Game.Scoring;
using osu.Game.Screens.Edit.Setup;
using osu.Game.Screens.Ranking.Statistics;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Osu
{
@ -54,6 +54,8 @@ namespace osu.Game.Rulesets.Osu
public const string SHORT_NAME = "osu";
public override string RulesetAPIVersionSupported => CURRENT_RULESET_API_VERSION;
public override IEnumerable<KeyBinding> GetDefaultKeyBindings(int variant = 0) => new[]
{
new KeyBinding(InputKey.Z, OsuAction.LeftButton),

View File

@ -22,7 +22,7 @@ namespace osu.Game.Rulesets.Taiko.Tests.Editor
public void Setup() => Schedule(() =>
{
BeatDivisor.Value = 8;
Clock.Seek(0);
EditorClock.Seek(0);
Child = new TestComposer { RelativeSizeAxes = Axes.Both };
});

View File

@ -16,13 +16,13 @@ namespace osu.Game.Rulesets.Taiko.Tests
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Taiko";
[TestCase(1.9971301024093662d, 200, "diffcalc-test")]
[TestCase(1.9971301024093662d, 200, "diffcalc-test-strong")]
[TestCase(3.1098944660126882d, 200, "diffcalc-test")]
[TestCase(3.1098944660126882d, 200, "diffcalc-test-strong")]
public void Test(double expectedStarRating, int expectedMaxCombo, string name)
=> base.Test(expectedStarRating, expectedMaxCombo, name);
[TestCase(3.1645810961313674d, 200, "diffcalc-test")]
[TestCase(3.1645810961313674d, 200, "diffcalc-test-strong")]
[TestCase(4.0974106752474251d, 200, "diffcalc-test")]
[TestCase(4.0974106752474251d, 200, "diffcalc-test-strong")]
public void TestClockRateAdjusted(double expectedStarRating, int expectedMaxCombo, string name)
=> Test(expectedStarRating, expectedMaxCombo, name, new TaikoModDoubleTime());

View File

@ -0,0 +1,67 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing.Colour;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing.Colour.Data;
namespace osu.Game.Rulesets.Taiko.Difficulty.Evaluators
{
public class ColourEvaluator
{
/// <summary>
/// A sigmoid function. It gives a value between (middle - height/2) and (middle + height/2).
/// </summary>
/// <param name="val">The input value.</param>
/// <param name="center">The center of the sigmoid, where the largest gradient occurs and value is equal to middle.</param>
/// <param name="width">The radius of the sigmoid, outside of which values are near the minimum/maximum.</param>
/// <param name="middle">The middle of the sigmoid output.</param>
/// <param name="height">The height of the sigmoid output. This will be equal to max value - min value.</param>
private static double sigmoid(double val, double center, double width, double middle, double height)
{
double sigmoid = Math.Tanh(Math.E * -(val - center) / width);
return sigmoid * (height / 2) + middle;
}
/// <summary>
/// Evaluate the difficulty of the first note of a <see cref="MonoStreak"/>.
/// </summary>
public static double EvaluateDifficultyOf(MonoStreak monoStreak)
{
return sigmoid(monoStreak.Index, 2, 2, 0.5, 1) * EvaluateDifficultyOf(monoStreak.Parent) * 0.5;
}
/// <summary>
/// Evaluate the difficulty of the first note of a <see cref="AlternatingMonoPattern"/>.
/// </summary>
public static double EvaluateDifficultyOf(AlternatingMonoPattern alternatingMonoPattern)
{
return sigmoid(alternatingMonoPattern.Index, 2, 2, 0.5, 1) * EvaluateDifficultyOf(alternatingMonoPattern.Parent);
}
/// <summary>
/// Evaluate the difficulty of the first note of a <see cref="RepeatingHitPatterns"/>.
/// </summary>
public static double EvaluateDifficultyOf(RepeatingHitPatterns repeatingHitPattern)
{
return 2 * (1 - sigmoid(repeatingHitPattern.RepetitionInterval, 2, 2, 0.5, 1));
}
public static double EvaluateDifficultyOf(DifficultyHitObject hitObject)
{
TaikoDifficultyHitObjectColour colour = ((TaikoDifficultyHitObject)hitObject).Colour;
double difficulty = 0.0d;
if (colour.MonoStreak != null) // Difficulty for MonoStreak
difficulty += EvaluateDifficultyOf(colour.MonoStreak);
if (colour.AlternatingMonoPattern != null) // Difficulty for AlternatingMonoPattern
difficulty += EvaluateDifficultyOf(colour.AlternatingMonoPattern);
if (colour.RepeatingHitPattern != null) // Difficulty for RepeatingHitPattern
difficulty += EvaluateDifficultyOf(colour.RepeatingHitPattern);
return difficulty;
}
}
}

View File

@ -0,0 +1,53 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Objects;
namespace osu.Game.Rulesets.Taiko.Difficulty.Evaluators
{
public class StaminaEvaluator
{
/// <summary>
/// Applies a speed bonus dependent on the time since the last hit performed using this key.
/// </summary>
/// <param name="interval">The interval between the current and previous note hit using the same key.</param>
private static double speedBonus(double interval)
{
// Cap to 600bpm 1/4, 25ms note interval, 50ms key interval
// Interval will be capped at a very small value to avoid infinite/negative speed bonuses.
// TODO - This is a temporary measure as we need to implement methods of detecting playstyle-abuse of SpeedBonus.
interval = Math.Max(interval, 50);
return 30 / interval;
}
/// <summary>
/// Evaluates the minimum mechanical stamina required to play the current object. This is calculated using the
/// maximum possible interval between two hits using the same key, by alternating 2 keys for each colour.
/// </summary>
public static double EvaluateDifficultyOf(DifficultyHitObject current)
{
if (current.BaseObject is not Hit)
{
return 0.0;
}
// Find the previous hit object hit by the current key, which is two notes of the same colour prior.
TaikoDifficultyHitObject taikoCurrent = (TaikoDifficultyHitObject)current;
TaikoDifficultyHitObject? keyPrevious = taikoCurrent.PreviousMono(1);
if (keyPrevious == null)
{
// There is no previous hit object hit by the current key
return 0.0;
}
double objectStrain = 0.5; // Add a base strain to all objects
objectStrain += speedBonus(taikoCurrent.StartTime - keyPrevious.StartTime);
return objectStrain;
}
}
}

View File

@ -0,0 +1,53 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
namespace osu.Game.Rulesets.Taiko.Difficulty.Preprocessing.Colour.Data
{
/// <summary>
/// Encodes a list of <see cref="MonoStreak"/>s.
/// <see cref="MonoStreak"/>s with the same <see cref="MonoStreak.RunLength"/> are grouped together.
/// </summary>
public class AlternatingMonoPattern
{
/// <summary>
/// <see cref="MonoStreak"/>s that are grouped together within this <see cref="AlternatingMonoPattern"/>.
/// </summary>
public readonly List<MonoStreak> MonoStreaks = new List<MonoStreak>();
/// <summary>
/// The parent <see cref="RepeatingHitPatterns"/> that contains this <see cref="AlternatingMonoPattern"/>
/// </summary>
public RepeatingHitPatterns Parent = null!;
/// <summary>
/// Index of this <see cref="AlternatingMonoPattern"/> within it's parent <see cref="RepeatingHitPatterns"/>
/// </summary>
public int Index;
/// <summary>
/// The first <see cref="TaikoDifficultyHitObject"/> in this <see cref="AlternatingMonoPattern"/>.
/// </summary>
public TaikoDifficultyHitObject FirstHitObject => MonoStreaks[0].FirstHitObject;
/// <summary>
/// Determine if this <see cref="AlternatingMonoPattern"/> is a repetition of another <see cref="AlternatingMonoPattern"/>. This
/// is a strict comparison and is true if and only if the colour sequence is exactly the same.
/// </summary>
public bool IsRepetitionOf(AlternatingMonoPattern other)
{
return HasIdenticalMonoLength(other) &&
other.MonoStreaks.Count == MonoStreaks.Count &&
other.MonoStreaks[0].HitType == MonoStreaks[0].HitType;
}
/// <summary>
/// Determine if this <see cref="AlternatingMonoPattern"/> has the same mono length of another <see cref="AlternatingMonoPattern"/>.
/// </summary>
public bool HasIdenticalMonoLength(AlternatingMonoPattern other)
{
return other.MonoStreaks[0].RunLength == MonoStreaks[0].RunLength;
}
}
}

View File

@ -0,0 +1,46 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Objects;
using System.Collections.Generic;
namespace osu.Game.Rulesets.Taiko.Difficulty.Preprocessing.Colour.Data
{
/// <summary>
/// Encode colour information for a sequence of <see cref="TaikoDifficultyHitObject"/>s. Consecutive <see cref="TaikoDifficultyHitObject"/>s
/// of the same <see cref="Objects.HitType"/> are encoded within the same <see cref="MonoStreak"/>.
/// </summary>
public class MonoStreak
{
/// <summary>
/// List of <see cref="DifficultyHitObject"/>s that are encoded within this <see cref="MonoStreak"/>.
/// </summary>
public List<TaikoDifficultyHitObject> HitObjects { get; private set; } = new List<TaikoDifficultyHitObject>();
/// <summary>
/// The parent <see cref="AlternatingMonoPattern"/> that contains this <see cref="MonoStreak"/>
/// </summary>
public AlternatingMonoPattern Parent = null!;
/// <summary>
/// Index of this <see cref="MonoStreak"/> within it's parent <see cref="AlternatingMonoPattern"/>
/// </summary>
public int Index;
/// <summary>
/// The first <see cref="TaikoDifficultyHitObject"/> in this <see cref="MonoStreak"/>.
/// </summary>
public TaikoDifficultyHitObject FirstHitObject => HitObjects[0];
/// <summary>
/// The hit type of all objects encoded within this <see cref="MonoStreak"/>
/// </summary>
public HitType? HitType => (HitObjects[0].BaseObject as Hit)?.Type;
/// <summary>
/// How long the mono pattern encoded within is
/// </summary>
public int RunLength => HitObjects.Count;
}
}

View File

@ -0,0 +1,94 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
namespace osu.Game.Rulesets.Taiko.Difficulty.Preprocessing.Colour.Data
{
/// <summary>
/// Encodes a list of <see cref="AlternatingMonoPattern"/>s, grouped together by back and forth repetition of the same
/// <see cref="AlternatingMonoPattern"/>. Also stores the repetition interval between this and the previous <see cref="RepeatingHitPatterns"/>.
/// </summary>
public class RepeatingHitPatterns
{
/// <summary>
/// Maximum amount of <see cref="RepeatingHitPatterns"/>s to look back to find a repetition.
/// </summary>
private const int max_repetition_interval = 16;
/// <summary>
/// The <see cref="AlternatingMonoPattern"/>s that are grouped together within this <see cref="RepeatingHitPatterns"/>.
/// </summary>
public readonly List<AlternatingMonoPattern> AlternatingMonoPatterns = new List<AlternatingMonoPattern>();
/// <summary>
/// The parent <see cref="TaikoDifficultyHitObject"/> in this <see cref="RepeatingHitPatterns"/>
/// </summary>
public TaikoDifficultyHitObject FirstHitObject => AlternatingMonoPatterns[0].FirstHitObject;
/// <summary>
/// The previous <see cref="RepeatingHitPatterns"/>. This is used to determine the repetition interval.
/// </summary>
public readonly RepeatingHitPatterns? Previous;
/// <summary>
/// How many <see cref="RepeatingHitPatterns"/> between the current and previous identical <see cref="RepeatingHitPatterns"/>.
/// If no repetition is found this will have a value of <see cref="max_repetition_interval"/> + 1.
/// </summary>
public int RepetitionInterval { get; private set; } = max_repetition_interval + 1;
public RepeatingHitPatterns(RepeatingHitPatterns? previous)
{
Previous = previous;
}
/// <summary>
/// Returns true if other is considered a repetition of this pattern. This is true if other's first two payloads
/// have identical mono lengths.
/// </summary>
private bool isRepetitionOf(RepeatingHitPatterns other)
{
if (AlternatingMonoPatterns.Count != other.AlternatingMonoPatterns.Count) return false;
for (int i = 0; i < Math.Min(AlternatingMonoPatterns.Count, 2); i++)
{
if (!AlternatingMonoPatterns[i].HasIdenticalMonoLength(other.AlternatingMonoPatterns[i])) return false;
}
return true;
}
/// <summary>
/// Finds the closest previous <see cref="RepeatingHitPatterns"/> that has the identical <see cref="AlternatingMonoPatterns"/>.
/// Interval is defined as the amount of <see cref="RepeatingHitPatterns"/> chunks between the current and repeated patterns.
/// </summary>
public void FindRepetitionInterval()
{
if (Previous == null)
{
RepetitionInterval = max_repetition_interval + 1;
return;
}
RepeatingHitPatterns? other = Previous;
int interval = 1;
while (interval < max_repetition_interval)
{
if (isRepetitionOf(other))
{
RepetitionInterval = Math.Min(interval, max_repetition_interval);
return;
}
other = other.Previous;
if (other == null) break;
++interval;
}
RepetitionInterval = max_repetition_interval + 1;
}
}
}

View File

@ -0,0 +1,167 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing.Colour.Data;
using osu.Game.Rulesets.Taiko.Objects;
namespace osu.Game.Rulesets.Taiko.Difficulty.Preprocessing.Colour
{
/// <summary>
/// Utility class to perform various encodings.
/// </summary>
public static class TaikoColourDifficultyPreprocessor
{
/// <summary>
/// Processes and encodes a list of <see cref="TaikoDifficultyHitObject"/>s into a list of <see cref="TaikoDifficultyHitObjectColour"/>s,
/// assigning the appropriate <see cref="TaikoDifficultyHitObjectColour"/>s to each <see cref="TaikoDifficultyHitObject"/>,
/// and pre-evaluating colour difficulty of each <see cref="TaikoDifficultyHitObject"/>.
/// </summary>
public static void ProcessAndAssign(List<DifficultyHitObject> hitObjects)
{
List<RepeatingHitPatterns> hitPatterns = encode(hitObjects);
// Assign indexing and encoding data to all relevant objects. Only the first note of each encoding type is
// assigned with the relevant encodings.
foreach (var repeatingHitPattern in hitPatterns)
{
repeatingHitPattern.FirstHitObject.Colour.RepeatingHitPattern = repeatingHitPattern;
// The outermost loop is kept a ForEach loop since it doesn't need index information, and we want to
// keep i and j for AlternatingMonoPattern's and MonoStreak's index respectively, to keep it in line with
// documentation.
for (int i = 0; i < repeatingHitPattern.AlternatingMonoPatterns.Count; ++i)
{
AlternatingMonoPattern monoPattern = repeatingHitPattern.AlternatingMonoPatterns[i];
monoPattern.Parent = repeatingHitPattern;
monoPattern.Index = i;
monoPattern.FirstHitObject.Colour.AlternatingMonoPattern = monoPattern;
for (int j = 0; j < monoPattern.MonoStreaks.Count; ++j)
{
MonoStreak monoStreak = monoPattern.MonoStreaks[j];
monoStreak.Parent = monoPattern;
monoStreak.Index = j;
monoStreak.FirstHitObject.Colour.MonoStreak = monoStreak;
}
}
}
}
/// <summary>
/// Encodes a list of <see cref="TaikoDifficultyHitObject"/>s into a list of <see cref="RepeatingHitPatterns"/>s.
/// </summary>
private static List<RepeatingHitPatterns> encode(List<DifficultyHitObject> data)
{
List<MonoStreak> monoStreaks = encodeMonoStreak(data);
List<AlternatingMonoPattern> alternatingMonoPatterns = encodeAlternatingMonoPattern(monoStreaks);
List<RepeatingHitPatterns> repeatingHitPatterns = encodeRepeatingHitPattern(alternatingMonoPatterns);
return repeatingHitPatterns;
}
/// <summary>
/// Encodes a list of <see cref="TaikoDifficultyHitObject"/>s into a list of <see cref="MonoStreak"/>s.
/// </summary>
private static List<MonoStreak> encodeMonoStreak(List<DifficultyHitObject> data)
{
List<MonoStreak> monoStreaks = new List<MonoStreak>();
MonoStreak? currentMonoStreak = null;
for (int i = 0; i < data.Count; i++)
{
TaikoDifficultyHitObject taikoObject = (TaikoDifficultyHitObject)data[i];
// This ignores all non-note objects, which may or may not be the desired behaviour
TaikoDifficultyHitObject? previousObject = taikoObject.PreviousNote(0);
// If this is the first object in the list or the colour changed, create a new mono streak
if (currentMonoStreak == null || previousObject == null || (taikoObject.BaseObject as Hit)?.Type != (previousObject.BaseObject as Hit)?.Type)
{
currentMonoStreak = new MonoStreak();
monoStreaks.Add(currentMonoStreak);
}
// Add the current object to the encoded payload.
currentMonoStreak.HitObjects.Add(taikoObject);
}
return monoStreaks;
}
/// <summary>
/// Encodes a list of <see cref="MonoStreak"/>s into a list of <see cref="AlternatingMonoPattern"/>s.
/// </summary>
private static List<AlternatingMonoPattern> encodeAlternatingMonoPattern(List<MonoStreak> data)
{
List<AlternatingMonoPattern> monoPatterns = new List<AlternatingMonoPattern>();
AlternatingMonoPattern? currentMonoPattern = null;
for (int i = 0; i < data.Count; i++)
{
// Start a new AlternatingMonoPattern if the previous MonoStreak has a different mono length, or if this is the first MonoStreak in the list.
if (currentMonoPattern == null || data[i].RunLength != data[i - 1].RunLength)
{
currentMonoPattern = new AlternatingMonoPattern();
monoPatterns.Add(currentMonoPattern);
}
// Add the current MonoStreak to the encoded payload.
currentMonoPattern.MonoStreaks.Add(data[i]);
}
return monoPatterns;
}
/// <summary>
/// Encodes a list of <see cref="AlternatingMonoPattern"/>s into a list of <see cref="RepeatingHitPatterns"/>s.
/// </summary>
private static List<RepeatingHitPatterns> encodeRepeatingHitPattern(List<AlternatingMonoPattern> data)
{
List<RepeatingHitPatterns> hitPatterns = new List<RepeatingHitPatterns>();
RepeatingHitPatterns? currentHitPattern = null;
for (int i = 0; i < data.Count; i++)
{
// Start a new RepeatingHitPattern. AlternatingMonoPatterns that should be grouped together will be handled later within this loop.
currentHitPattern = new RepeatingHitPatterns(currentHitPattern);
// Determine if future AlternatingMonoPatterns should be grouped.
bool isCoupled = i < data.Count - 2 && data[i].IsRepetitionOf(data[i + 2]);
if (!isCoupled)
{
// If not, add the current AlternatingMonoPattern to the encoded payload and continue.
currentHitPattern.AlternatingMonoPatterns.Add(data[i]);
}
else
{
// If so, add the current AlternatingMonoPattern to the encoded payload and start repeatedly checking if the
// subsequent AlternatingMonoPatterns should be grouped by increasing i and doing the appropriate isCoupled check.
while (isCoupled)
{
currentHitPattern.AlternatingMonoPatterns.Add(data[i]);
i++;
isCoupled = i < data.Count - 2 && data[i].IsRepetitionOf(data[i + 2]);
}
// Skip over viewed data and add the rest to the payload
currentHitPattern.AlternatingMonoPatterns.Add(data[i]);
currentHitPattern.AlternatingMonoPatterns.Add(data[i + 1]);
i++;
}
hitPatterns.Add(currentHitPattern);
}
// Final pass to find repetition intervals
for (int i = 0; i < hitPatterns.Count; i++)
{
hitPatterns[i].FindRepetitionInterval();
}
return hitPatterns;
}
}
}

View File

@ -0,0 +1,28 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing.Colour.Data;
namespace osu.Game.Rulesets.Taiko.Difficulty.Preprocessing.Colour
{
/// <summary>
/// Stores colour compression information for a <see cref="TaikoDifficultyHitObject"/>.
/// </summary>
public class TaikoDifficultyHitObjectColour
{
/// <summary>
/// The <see cref="MonoStreak"/> that encodes this note, only present if this is the first note within a <see cref="MonoStreak"/>
/// </summary>
public MonoStreak? MonoStreak;
/// <summary>
/// The <see cref="AlternatingMonoPattern"/> that encodes this note, only present if this is the first note within a <see cref="AlternatingMonoPattern"/>
/// </summary>
public AlternatingMonoPattern? AlternatingMonoPattern;
/// <summary>
/// The <see cref="RepeatingHitPattern"/> that encodes this note, only present if this is the first note within a <see cref="RepeatingHitPattern"/>
/// </summary>
public RepeatingHitPatterns? RepeatingHitPattern;
}
}

View File

@ -1,9 +1,7 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
namespace osu.Game.Rulesets.Taiko.Difficulty.Preprocessing
namespace osu.Game.Rulesets.Taiko.Difficulty.Preprocessing.Rhythm
{
/// <summary>
/// Represents a rhythm change in a taiko map.

View File

@ -1,14 +1,14 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing.Colour;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing.Rhythm;
namespace osu.Game.Rulesets.Taiko.Difficulty.Preprocessing
{
@ -17,21 +17,36 @@ namespace osu.Game.Rulesets.Taiko.Difficulty.Preprocessing
/// </summary>
public class TaikoDifficultyHitObject : DifficultyHitObject
{
/// <summary>
/// The list of all <see cref="TaikoDifficultyHitObject"/> of the same colour as this <see cref="TaikoDifficultyHitObject"/> in the beatmap.
/// </summary>
private readonly IReadOnlyList<TaikoDifficultyHitObject>? monoDifficultyHitObjects;
/// <summary>
/// The index of this <see cref="TaikoDifficultyHitObject"/> in <see cref="monoDifficultyHitObjects"/>.
/// </summary>
public readonly int MonoIndex;
/// <summary>
/// The list of all <see cref="TaikoDifficultyHitObject"/> that is either a regular note or finisher in the beatmap
/// </summary>
private readonly IReadOnlyList<TaikoDifficultyHitObject> noteDifficultyHitObjects;
/// <summary>
/// The index of this <see cref="TaikoDifficultyHitObject"/> in <see cref="noteDifficultyHitObjects"/>.
/// </summary>
public readonly int NoteIndex;
/// <summary>
/// The rhythm required to hit this hit object.
/// </summary>
public readonly TaikoDifficultyHitObjectRhythm Rhythm;
/// <summary>
/// The hit type of this hit object.
/// Colour data for this hit object. This is used by colour evaluator to calculate colour difficulty, but can be used
/// by other skills in the future.
/// </summary>
public readonly HitType? HitType;
/// <summary>
/// Whether the object should carry a penalty due to being hittable using special techniques
/// making it easier to do so.
/// </summary>
public bool StaminaCheese;
public readonly TaikoDifficultyHitObjectColour Colour;
/// <summary>
/// Creates a new difficulty hit object.
@ -40,15 +55,44 @@ namespace osu.Game.Rulesets.Taiko.Difficulty.Preprocessing
/// <param name="lastObject">The gameplay <see cref="HitObject"/> preceding <paramref name="hitObject"/>.</param>
/// <param name="lastLastObject">The gameplay <see cref="HitObject"/> preceding <paramref name="lastObject"/>.</param>
/// <param name="clockRate">The rate of the gameplay clock. Modified by speed-changing mods.</param>
/// <param name="objects">The list of <see cref="DifficultyHitObject"/>s in the current beatmap.</param>
/// /// <param name="index">The position of this <see cref="DifficultyHitObject"/> in the <paramref name="objects"/> list.</param>
public TaikoDifficultyHitObject(HitObject hitObject, HitObject lastObject, HitObject lastLastObject, double clockRate, List<DifficultyHitObject> objects, int index)
/// <param name="objects">The list of all <see cref="DifficultyHitObject"/>s in the current beatmap.</param>
/// <param name="centreHitObjects">The list of centre (don) <see cref="DifficultyHitObject"/>s in the current beatmap.</param>
/// <param name="rimHitObjects">The list of rim (kat) <see cref="DifficultyHitObject"/>s in the current beatmap.</param>
/// <param name="noteObjects">The list of <see cref="DifficultyHitObject"/>s that is a hit (i.e. not a drumroll or swell) in the current beatmap.</param>
/// <param name="index">The position of this <see cref="DifficultyHitObject"/> in the <paramref name="objects"/> list.</param>
public TaikoDifficultyHitObject(HitObject hitObject, HitObject lastObject, HitObject lastLastObject, double clockRate,
List<DifficultyHitObject> objects,
List<TaikoDifficultyHitObject> centreHitObjects,
List<TaikoDifficultyHitObject> rimHitObjects,
List<TaikoDifficultyHitObject> noteObjects, int index)
: base(hitObject, lastObject, clockRate, objects, index)
{
var currentHit = hitObject as Hit;
noteDifficultyHitObjects = noteObjects;
// Create the Colour object, its properties should be filled in by TaikoDifficultyPreprocessor
Colour = new TaikoDifficultyHitObjectColour();
Rhythm = getClosestRhythm(lastObject, lastLastObject, clockRate);
HitType = currentHit?.Type;
switch ((hitObject as Hit)?.Type)
{
case HitType.Centre:
MonoIndex = centreHitObjects.Count;
centreHitObjects.Add(this);
monoDifficultyHitObjects = centreHitObjects;
break;
case HitType.Rim:
MonoIndex = rimHitObjects.Count;
rimHitObjects.Add(this);
monoDifficultyHitObjects = rimHitObjects;
break;
}
if (hitObject is Hit)
{
NoteIndex = noteObjects.Count;
noteObjects.Add(this);
}
}
/// <summary>
@ -87,5 +131,13 @@ namespace osu.Game.Rulesets.Taiko.Difficulty.Preprocessing
return common_rhythms.OrderBy(x => Math.Abs(x.Ratio - ratio)).First();
}
public TaikoDifficultyHitObject? PreviousMono(int backwardsIndex) => monoDifficultyHitObjects?.ElementAtOrDefault(MonoIndex - (backwardsIndex + 1));
public TaikoDifficultyHitObject? NextMono(int forwardsIndex) => monoDifficultyHitObjects?.ElementAtOrDefault(MonoIndex + (forwardsIndex + 1));
public TaikoDifficultyHitObject? PreviousNote(int backwardsIndex) => noteDifficultyHitObjects.ElementAtOrDefault(NoteIndex - (backwardsIndex + 1));
public TaikoDifficultyHitObject? NextNote(int forwardsIndex) => noteDifficultyHitObjects.ElementAtOrDefault(NoteIndex + (forwardsIndex + 1));
}
}

View File

@ -1,15 +1,10 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Difficulty.Utils;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.Taiko.Difficulty.Evaluators;
namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
{
@ -18,29 +13,12 @@ namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
/// </summary>
public class Colour : StrainDecaySkill
{
protected override double SkillMultiplier => 1;
protected override double StrainDecayBase => 0.4;
protected override double SkillMultiplier => 0.12;
/// <summary>
/// Maximum number of entries to keep in <see cref="monoHistory"/>.
/// </summary>
private const int mono_history_max_length = 5;
/// <summary>
/// Queue with the lengths of the last <see cref="mono_history_max_length"/> most recent mono (single-colour) patterns,
/// with the most recent value at the end of the queue.
/// </summary>
private readonly LimitedCapacityQueue<int> monoHistory = new LimitedCapacityQueue<int>(mono_history_max_length);
/// <summary>
/// The <see cref="HitType"/> of the last object hit before the one being considered.
/// </summary>
private HitType? previousHitType;
/// <summary>
/// Length of the current mono pattern.
/// </summary>
private int currentMonoLength;
// This is set to decay slower than other skills, due to the fact that only the first note of each encoding class
// having any difficulty values, and we want to allow colour difficulty to be able to build up even on
// slower maps.
protected override double StrainDecayBase => 0.8;
public Colour(Mod[] mods)
: base(mods)
@ -49,95 +27,7 @@ namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
protected override double StrainValueOf(DifficultyHitObject current)
{
// changing from/to a drum roll or a swell does not constitute a colour change.
// hits spaced more than a second apart are also exempt from colour strain.
if (!(current.LastObject is Hit && current.BaseObject is Hit && current.DeltaTime < 1000))
{
monoHistory.Clear();
var currentHit = current.BaseObject as Hit;
currentMonoLength = currentHit != null ? 1 : 0;
previousHitType = currentHit?.Type;
return 0.0;
}
var taikoCurrent = (TaikoDifficultyHitObject)current;
double objectStrain = 0.0;
if (previousHitType != null && taikoCurrent.HitType != previousHitType)
{
// The colour has changed.
objectStrain = 1.0;
if (monoHistory.Count < 2)
{
// There needs to be at least two streaks to determine a strain.
objectStrain = 0.0;
}
else if ((monoHistory[^1] + currentMonoLength) % 2 == 0)
{
// The last streak in the history is guaranteed to be a different type to the current streak.
// If the total number of notes in the two streaks is even, nullify this object's strain.
objectStrain = 0.0;
}
objectStrain *= repetitionPenalties();
currentMonoLength = 1;
}
else
{
currentMonoLength += 1;
}
previousHitType = taikoCurrent.HitType;
return objectStrain;
return ColourEvaluator.EvaluateDifficultyOf(current);
}
/// <summary>
/// The penalty to apply due to the length of repetition in colour streaks.
/// </summary>
private double repetitionPenalties()
{
const int most_recent_patterns_to_compare = 2;
double penalty = 1.0;
monoHistory.Enqueue(currentMonoLength);
for (int start = monoHistory.Count - most_recent_patterns_to_compare - 1; start >= 0; start--)
{
if (!isSamePattern(start, most_recent_patterns_to_compare))
continue;
int notesSince = 0;
for (int i = start; i < monoHistory.Count; i++) notesSince += monoHistory[i];
penalty *= repetitionPenalty(notesSince);
break;
}
return penalty;
}
/// <summary>
/// Determines whether the last <paramref name="mostRecentPatternsToCompare"/> patterns have repeated in the history
/// of single-colour note sequences, starting from <paramref name="start"/>.
/// </summary>
private bool isSamePattern(int start, int mostRecentPatternsToCompare)
{
for (int i = 0; i < mostRecentPatternsToCompare; i++)
{
if (monoHistory[start + i] != monoHistory[monoHistory.Count - mostRecentPatternsToCompare + i])
return false;
}
return true;
}
/// <summary>
/// Calculates the strain penalty for a colour pattern repetition.
/// </summary>
/// <param name="notesSince">The number of notes since the last repetition of the pattern.</param>
private double repetitionPenalty(int notesSince) => Math.Min(1.0, 0.032 * notesSince);
}
}

View File

@ -0,0 +1,93 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
{
public class Peaks : Skill
{
private const double rhythm_skill_multiplier = 0.2 * final_multiplier;
private const double colour_skill_multiplier = 0.375 * final_multiplier;
private const double stamina_skill_multiplier = 0.375 * final_multiplier;
private const double final_multiplier = 0.0625;
private readonly Rhythm rhythm;
private readonly Colour colour;
private readonly Stamina stamina;
public double ColourDifficultyValue => colour.DifficultyValue() * colour_skill_multiplier;
public double RhythmDifficultyValue => rhythm.DifficultyValue() * rhythm_skill_multiplier;
public double StaminaDifficultyValue => stamina.DifficultyValue() * stamina_skill_multiplier;
public Peaks(Mod[] mods)
: base(mods)
{
rhythm = new Rhythm(mods);
colour = new Colour(mods);
stamina = new Stamina(mods);
}
/// <summary>
/// Returns the <i>p</i>-norm of an <i>n</i>-dimensional vector.
/// </summary>
/// <param name="p">The value of <i>p</i> to calculate the norm for.</param>
/// <param name="values">The coefficients of the vector.</param>
private double norm(double p, params double[] values) => Math.Pow(values.Sum(x => Math.Pow(x, p)), 1 / p);
public override void Process(DifficultyHitObject current)
{
rhythm.Process(current);
colour.Process(current);
stamina.Process(current);
}
/// <summary>
/// Returns the combined star rating of the beatmap, calculated using peak strains from all sections of the map.
/// </summary>
/// <remarks>
/// For each section, the peak strains of all separate skills are combined into a single peak strain for the section.
/// The resulting partial rating of the beatmap is a weighted sum of the combined peaks (higher peaks are weighted more).
/// </remarks>
public override double DifficultyValue()
{
List<double> peaks = new List<double>();
var colourPeaks = colour.GetCurrentStrainPeaks().ToList();
var rhythmPeaks = rhythm.GetCurrentStrainPeaks().ToList();
var staminaPeaks = stamina.GetCurrentStrainPeaks().ToList();
for (int i = 0; i < colourPeaks.Count; i++)
{
double colourPeak = colourPeaks[i] * colour_skill_multiplier;
double rhythmPeak = rhythmPeaks[i] * rhythm_skill_multiplier;
double staminaPeak = staminaPeaks[i] * stamina_skill_multiplier;
double peak = norm(1.5, colourPeak, staminaPeak);
peak = norm(2, peak, rhythmPeak);
// Sections with 0 strain are excluded to avoid worst-case time complexity of the following sort (e.g. /b/2351871).
// These sections will not contribute to the difficulty.
if (peak > 0)
peaks.Add(peak);
}
double difficulty = 0;
double weight = 1;
foreach (double strain in peaks.OrderByDescending(d => d))
{
difficulty += strain * weight;
weight *= 0.9;
}
return difficulty;
}
}
}

View File

@ -1,44 +0,0 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
{
/// <summary>
/// Stamina of a single key, calculated based on repetition speed.
/// </summary>
public class SingleKeyStamina
{
private double? previousHitTime;
/// <summary>
/// Similar to <see cref="StrainDecaySkill.StrainValueOf"/>
/// </summary>
public double StrainValueOf(DifficultyHitObject current)
{
if (previousHitTime == null)
{
previousHitTime = current.StartTime;
return 0;
}
double objectStrain = 0.5;
objectStrain += speedBonus(current.StartTime - previousHitTime.Value);
previousHitTime = current.StartTime;
return objectStrain;
}
/// <summary>
/// Applies a speed bonus dependent on the time since the last hit performed using this key.
/// </summary>
/// <param name="notePairDuration">The duration between the current and previous note hit using the same key.</param>
private double speedBonus(double notePairDuration)
{
return 175 / (notePairDuration + 100);
}
}
}

View File

@ -6,8 +6,7 @@
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.Taiko.Difficulty.Evaluators;
namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
{
@ -19,31 +18,9 @@ namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
/// </remarks>
public class Stamina : StrainDecaySkill
{
protected override double SkillMultiplier => 1;
protected override double SkillMultiplier => 1.1;
protected override double StrainDecayBase => 0.4;
private readonly SingleKeyStamina[] centreKeyStamina =
{
new SingleKeyStamina(),
new SingleKeyStamina()
};
private readonly SingleKeyStamina[] rimKeyStamina =
{
new SingleKeyStamina(),
new SingleKeyStamina()
};
/// <summary>
/// Current index into <see cref="centreKeyStamina" /> for a centre hit.
/// </summary>
private int centreKeyIndex;
/// <summary>
/// Current index into <see cref="rimKeyStamina" /> for a rim hit.
/// </summary>
private int rimKeyIndex;
/// <summary>
/// Creates a <see cref="Stamina"/> skill.
/// </summary>
@ -53,32 +30,9 @@ namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
{
}
/// <summary>
/// Get the next <see cref="SingleKeyStamina"/> to use for the given <see cref="TaikoDifficultyHitObject"/>.
/// </summary>
/// <param name="current">The current <see cref="TaikoDifficultyHitObject"/>.</param>
private SingleKeyStamina getNextSingleKeyStamina(TaikoDifficultyHitObject current)
{
// Alternate key for the same color.
if (current.HitType == HitType.Centre)
{
centreKeyIndex = (centreKeyIndex + 1) % 2;
return centreKeyStamina[centreKeyIndex];
}
rimKeyIndex = (rimKeyIndex + 1) % 2;
return rimKeyStamina[rimKeyIndex];
}
protected override double StrainValueOf(DifficultyHitObject current)
{
if (!(current.BaseObject is Hit))
{
return 0.0;
}
TaikoDifficultyHitObject hitObject = (TaikoDifficultyHitObject)current;
return getNextSingleKeyStamina(hitObject).StrainValueOf(hitObject);
return StaminaEvaluator.EvaluateDifficultyOf(current);
}
}
}

View File

@ -29,13 +29,10 @@ namespace osu.Game.Rulesets.Taiko.Difficulty
public double ColourDifficulty { get; set; }
/// <summary>
/// The perceived approach rate inclusive of rate-adjusting mods (DT/HT/etc).
/// The difficulty corresponding to the hardest parts of the map.
/// </summary>
/// <remarks>
/// Rate-adjusting mods don't directly affect the approach rate difficulty value, but have a perceived effect as a result of adjusting audio timing.
/// </remarks>
[JsonProperty("approach_rate")]
public double ApproachRate { get; set; }
[JsonProperty("peak_difficulty")]
public double PeakDifficulty { get; set; }
/// <summary>
/// The perceived hit window for a GREAT hit inclusive of rate-adjusting mods (DT/HT/etc).

View File

@ -13,6 +13,7 @@ using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing.Colour;
using osu.Game.Rulesets.Taiko.Difficulty.Skills;
using osu.Game.Rulesets.Taiko.Mods;
using osu.Game.Rulesets.Taiko.Objects;
@ -22,9 +23,7 @@ namespace osu.Game.Rulesets.Taiko.Difficulty
{
public class TaikoDifficultyCalculator : DifficultyCalculator
{
private const double rhythm_skill_multiplier = 0.014;
private const double colour_skill_multiplier = 0.01;
private const double stamina_skill_multiplier = 0.021;
private const double difficulty_multiplier = 1.35;
public override int Version => 20220701;
@ -33,12 +32,13 @@ namespace osu.Game.Rulesets.Taiko.Difficulty
{
}
protected override Skill[] CreateSkills(IBeatmap beatmap, Mod[] mods, double clockRate) => new Skill[]
protected override Skill[] CreateSkills(IBeatmap beatmap, Mod[] mods, double clockRate)
{
new Colour(mods),
new Rhythm(mods),
new Stamina(mods)
};
return new Skill[]
{
new Peaks(mods)
};
}
protected override Mod[] DifficultyAdjustmentMods => new Mod[]
{
@ -50,18 +50,23 @@ namespace osu.Game.Rulesets.Taiko.Difficulty
protected override IEnumerable<DifficultyHitObject> CreateDifficultyHitObjects(IBeatmap beatmap, double clockRate)
{
List<DifficultyHitObject> taikoDifficultyHitObjects = new List<DifficultyHitObject>();
List<DifficultyHitObject> difficultyHitObjects = new List<DifficultyHitObject>();
List<TaikoDifficultyHitObject> centreObjects = new List<TaikoDifficultyHitObject>();
List<TaikoDifficultyHitObject> rimObjects = new List<TaikoDifficultyHitObject>();
List<TaikoDifficultyHitObject> noteObjects = new List<TaikoDifficultyHitObject>();
for (int i = 2; i < beatmap.HitObjects.Count; i++)
{
taikoDifficultyHitObjects.Add(
difficultyHitObjects.Add(
new TaikoDifficultyHitObject(
beatmap.HitObjects[i], beatmap.HitObjects[i - 1], beatmap.HitObjects[i - 2], clockRate, taikoDifficultyHitObjects, taikoDifficultyHitObjects.Count
)
beatmap.HitObjects[i], beatmap.HitObjects[i - 1], beatmap.HitObjects[i - 2], clockRate, difficultyHitObjects,
centreObjects, rimObjects, noteObjects, difficultyHitObjects.Count)
);
}
return taikoDifficultyHitObjects;
TaikoColourDifficultyPreprocessor.ProcessAndAssign(difficultyHitObjects);
return difficultyHitObjects;
}
protected override DifficultyAttributes CreateDifficultyAttributes(IBeatmap beatmap, Mod[] mods, Skill[] skills, double clockRate)
@ -69,28 +74,24 @@ namespace osu.Game.Rulesets.Taiko.Difficulty
if (beatmap.HitObjects.Count == 0)
return new TaikoDifficultyAttributes { Mods = mods };
var colour = (Colour)skills[0];
var rhythm = (Rhythm)skills[1];
var stamina = (Stamina)skills[2];
var combined = (Peaks)skills[0];
double colourRating = colour.DifficultyValue() * colour_skill_multiplier;
double rhythmRating = rhythm.DifficultyValue() * rhythm_skill_multiplier;
double staminaRating = stamina.DifficultyValue() * stamina_skill_multiplier;
double colourRating = combined.ColourDifficultyValue * difficulty_multiplier;
double rhythmRating = combined.RhythmDifficultyValue * difficulty_multiplier;
double staminaRating = combined.StaminaDifficultyValue * difficulty_multiplier;
double staminaPenalty = simpleColourPenalty(staminaRating, colourRating);
staminaRating *= staminaPenalty;
double combinedRating = combined.DifficultyValue() * difficulty_multiplier;
double starRating = rescale(combinedRating * 1.4);
//TODO : This is a temporary fix for the stamina rating of converts, due to their low colour variance.
if (beatmap.BeatmapInfo.Ruleset.OnlineID == 0 && colourRating < 0.05)
// TODO: This is temporary measure as we don't detect abuse of multiple-input playstyles of converts within the current system.
if (beatmap.BeatmapInfo.Ruleset.OnlineID == 0)
{
staminaPenalty *= 0.25;
starRating *= 0.925;
// For maps with low colour variance and high stamina requirement, multiple inputs are more likely to be abused.
if (colourRating < 2 && staminaRating > 8)
starRating *= 0.80;
}
double combinedRating = locallyCombinedDifficulty(colour, rhythm, stamina, staminaPenalty);
double separatedRating = norm(1.5, colourRating, rhythmRating, staminaRating);
double starRating = 1.4 * separatedRating + 0.5 * combinedRating;
starRating = rescale(starRating);
HitWindows hitWindows = new TaikoHitWindows();
hitWindows.SetDifficulty(beatmap.Difficulty.OverallDifficulty);
@ -101,75 +102,14 @@ namespace osu.Game.Rulesets.Taiko.Difficulty
StaminaDifficulty = staminaRating,
RhythmDifficulty = rhythmRating,
ColourDifficulty = colourRating,
PeakDifficulty = combinedRating,
GreatHitWindow = hitWindows.WindowFor(HitResult.Great) / clockRate,
MaxCombo = beatmap.HitObjects.Count(h => h is Hit),
};
}
/// <summary>
/// Calculates the penalty for the stamina skill for maps with low colour difficulty.
/// </summary>
/// <remarks>
/// Some maps (especially converts) can be easy to read despite a high note density.
/// This penalty aims to reduce the star rating of such maps by factoring in colour difficulty to the stamina skill.
/// </remarks>
private double simpleColourPenalty(double staminaDifficulty, double colorDifficulty)
{
if (colorDifficulty <= 0) return 0.79 - 0.25;
return 0.79 - Math.Atan(staminaDifficulty / colorDifficulty - 12) / Math.PI / 2;
}
/// <summary>
/// Returns the <i>p</i>-norm of an <i>n</i>-dimensional vector.
/// </summary>
/// <param name="p">The value of <i>p</i> to calculate the norm for.</param>
/// <param name="values">The coefficients of the vector.</param>
private double norm(double p, params double[] values) => Math.Pow(values.Sum(x => Math.Pow(x, p)), 1 / p);
/// <summary>
/// Returns the partial star rating of the beatmap, calculated using peak strains from all sections of the map.
/// </summary>
/// <remarks>
/// For each section, the peak strains of all separate skills are combined into a single peak strain for the section.
/// The resulting partial rating of the beatmap is a weighted sum of the combined peaks (higher peaks are weighted more).
/// </remarks>
private double locallyCombinedDifficulty(Colour colour, Rhythm rhythm, Stamina stamina, double staminaPenalty)
{
List<double> peaks = new List<double>();
var colourPeaks = colour.GetCurrentStrainPeaks().ToList();
var rhythmPeaks = rhythm.GetCurrentStrainPeaks().ToList();
var staminaPeaks = stamina.GetCurrentStrainPeaks().ToList();
for (int i = 0; i < colourPeaks.Count; i++)
{
double colourPeak = colourPeaks[i] * colour_skill_multiplier;
double rhythmPeak = rhythmPeaks[i] * rhythm_skill_multiplier;
double staminaPeak = staminaPeaks[i] * stamina_skill_multiplier * staminaPenalty;
double peak = norm(2, colourPeak, rhythmPeak, staminaPeak);
// Sections with 0 strain are excluded to avoid worst-case time complexity of the following sort (e.g. /b/2351871).
// These sections will not contribute to the difficulty.
if (peak > 0)
peaks.Add(peak);
}
double difficulty = 0;
double weight = 1;
foreach (double strain in peaks.OrderByDescending(d => d))
{
difficulty += strain * weight;
weight *= 0.9;
}
return difficulty;
}
/// <summary>
/// Applies a final re-scaling of the star rating to bring maps with recorded full combos below 9.5 stars.
/// Applies a final re-scaling of the star rating.
/// </summary>
/// <param name="sr">The raw star rating value before re-scaling.</param>
private double rescale(double sr)

View File

@ -17,6 +17,9 @@ namespace osu.Game.Rulesets.Taiko.Difficulty
[JsonProperty("accuracy")]
public double Accuracy { get; set; }
[JsonProperty("effective_miss_count")]
public double EffectiveMissCount { get; set; }
public override IEnumerable<PerformanceDisplayAttribute> GetAttributesForDisplay()
{
foreach (var attribute in base.GetAttributesForDisplay())

View File

@ -21,6 +21,8 @@ namespace osu.Game.Rulesets.Taiko.Difficulty
private int countMeh;
private int countMiss;
private double effectiveMissCount;
public TaikoPerformanceCalculator()
: base(new TaikoRuleset())
{
@ -35,7 +37,11 @@ namespace osu.Game.Rulesets.Taiko.Difficulty
countMeh = score.Statistics.GetValueOrDefault(HitResult.Meh);
countMiss = score.Statistics.GetValueOrDefault(HitResult.Miss);
double multiplier = 1.12; // This is being adjusted to keep the final pp value scaled around what it used to be when changing things
// The effectiveMissCount is calculated by gaining a ratio for totalSuccessfulHits and increasing the miss penalty for shorter object counts lower than 1000.
if (totalSuccessfulHits > 0)
effectiveMissCount = Math.Max(1.0, 1000.0 / totalSuccessfulHits) * countMiss;
double multiplier = 1.13;
if (score.Mods.Any(m => m is ModHidden))
multiplier *= 1.075;
@ -55,6 +61,7 @@ namespace osu.Game.Rulesets.Taiko.Difficulty
{
Difficulty = difficultyValue,
Accuracy = accuracyValue,
EffectiveMissCount = effectiveMissCount,
Total = totalValue
};
}
@ -66,18 +73,21 @@ namespace osu.Game.Rulesets.Taiko.Difficulty
double lengthBonus = 1 + 0.1 * Math.Min(1.0, totalHits / 1500.0);
difficultyValue *= lengthBonus;
difficultyValue *= Math.Pow(0.986, countMiss);
difficultyValue *= Math.Pow(0.986, effectiveMissCount);
if (score.Mods.Any(m => m is ModEasy))
difficultyValue *= 0.980;
difficultyValue *= 0.985;
if (score.Mods.Any(m => m is ModHidden))
difficultyValue *= 1.025;
if (score.Mods.Any(m => m is ModFlashlight<TaikoHitObject>))
difficultyValue *= 1.05 * lengthBonus;
if (score.Mods.Any(m => m is ModHardRock))
difficultyValue *= 1.050;
return difficultyValue * Math.Pow(score.Accuracy, 1.5);
if (score.Mods.Any(m => m is ModFlashlight<TaikoHitObject>))
difficultyValue *= 1.050 * lengthBonus;
return difficultyValue * Math.Pow(score.Accuracy, 2.0);
}
private double computeAccuracyValue(ScoreInfo score, TaikoDifficultyAttributes attributes)
@ -85,18 +95,20 @@ namespace osu.Game.Rulesets.Taiko.Difficulty
if (attributes.GreatHitWindow <= 0)
return 0;
double accuracyValue = Math.Pow(140.0 / attributes.GreatHitWindow, 1.1) * Math.Pow(score.Accuracy, 12.0) * 27;
double accuracyValue = Math.Pow(60.0 / attributes.GreatHitWindow, 1.1) * Math.Pow(score.Accuracy, 8.0) * Math.Pow(attributes.StarRating, 0.4) * 27.0;
double lengthBonus = Math.Min(1.15, Math.Pow(totalHits / 1500.0, 0.3));
accuracyValue *= lengthBonus;
// Slight HDFL Bonus for accuracy.
// Slight HDFL Bonus for accuracy. A clamp is used to prevent against negative values
if (score.Mods.Any(m => m is ModFlashlight<TaikoHitObject>) && score.Mods.Any(m => m is ModHidden))
accuracyValue *= 1.10 * lengthBonus;
accuracyValue *= Math.Max(1.050, 1.075 * lengthBonus);
return accuracyValue;
}
private int totalHits => countGreat + countOk + countMeh + countMiss;
private int totalSuccessfulHits => countGreat + countOk + countMeh;
}
}

View File

@ -3,33 +3,33 @@
#nullable disable
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Taiko.Mods;
using osu.Game.Rulesets.Taiko.UI;
using osu.Game.Rulesets.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Bindings;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Rulesets.Taiko.Replays;
using osu.Framework.Localisation;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Graphics;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.Taiko.Beatmaps;
using osu.Game.Rulesets.Taiko.Difficulty;
using osu.Game.Rulesets.Taiko.Scoring;
using osu.Game.Scoring;
using System;
using System.Linq;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Localisation;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Taiko.Edit;
using osu.Game.Rulesets.Taiko.Mods;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.Taiko.Replays;
using osu.Game.Rulesets.Taiko.Scoring;
using osu.Game.Rulesets.Taiko.Skinning.Legacy;
using osu.Game.Rulesets.Taiko.UI;
using osu.Game.Rulesets.UI;
using osu.Game.Scoring;
using osu.Game.Screens.Ranking.Statistics;
using osu.Game.Skinning;
@ -49,6 +49,8 @@ namespace osu.Game.Rulesets.Taiko
public const string SHORT_NAME = "taiko";
public override string RulesetAPIVersionSupported => CURRENT_RULESET_API_VERSION;
public override IEnumerable<KeyBinding> GetDefaultKeyBindings(int variant = 0) => new[]
{
new KeyBinding(InputKey.MouseLeft, TaikoAction.LeftCentre),

View File

@ -1,11 +1,19 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Rulesets.Osu.Difficulty;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Rulesets.UI;
namespace osu.Game.Tests.Database
{
@ -51,5 +59,105 @@ namespace osu.Game.Tests.Database
Assert.IsFalse(rulesets.GetRuleset("mania")?.IsManaged);
});
}
[Test]
public void TestRulesetThrowingOnMethods()
{
RunTestWithRealm((realm, storage) =>
{
LoadTestRuleset.Version = Ruleset.CURRENT_RULESET_API_VERSION;
LoadTestRuleset.HasImplementations = false;
var ruleset = new LoadTestRuleset();
string rulesetShortName = ruleset.RulesetInfo.ShortName;
realm.Write(r => r.Add(new RulesetInfo(rulesetShortName, ruleset.RulesetInfo.Name, ruleset.RulesetInfo.InstantiationInfo, ruleset.RulesetInfo.OnlineID)
{
Available = true,
}));
Assert.That(realm.Run(r => r.Find<RulesetInfo>(rulesetShortName).Available), Is.True);
// Availability is updated on construction of a RealmRulesetStore
var _ = new RealmRulesetStore(realm, storage);
Assert.That(realm.Run(r => r.Find<RulesetInfo>(rulesetShortName).Available), Is.False);
});
}
[Test]
public void TestOutdatedRulesetNotAvailable()
{
RunTestWithRealm((realm, storage) =>
{
LoadTestRuleset.Version = "2021.101.0";
LoadTestRuleset.HasImplementations = true;
var ruleset = new LoadTestRuleset();
string rulesetShortName = ruleset.RulesetInfo.ShortName;
realm.Write(r => r.Add(new RulesetInfo(rulesetShortName, ruleset.RulesetInfo.Name, ruleset.RulesetInfo.InstantiationInfo, ruleset.RulesetInfo.OnlineID)
{
Available = true,
}));
Assert.That(realm.Run(r => r.Find<RulesetInfo>(rulesetShortName).Available), Is.True);
// Availability is updated on construction of a RealmRulesetStore
var _ = new RealmRulesetStore(realm, storage);
Assert.That(realm.Run(r => r.Find<RulesetInfo>(rulesetShortName).Available), Is.False);
// Simulate the ruleset getting updated
LoadTestRuleset.Version = Ruleset.CURRENT_RULESET_API_VERSION;
var __ = new RealmRulesetStore(realm, storage);
Assert.That(realm.Run(r => r.Find<RulesetInfo>(rulesetShortName).Available), Is.True);
});
}
private class LoadTestRuleset : Ruleset
{
public override string RulesetAPIVersionSupported => Version;
public static bool HasImplementations = true;
public static string Version { get; set; } = CURRENT_RULESET_API_VERSION;
public override IEnumerable<Mod> GetModsFor(ModType type)
{
if (!HasImplementations)
throw new NotImplementedException();
return Array.Empty<Mod>();
}
public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod>? mods = null)
{
if (!HasImplementations)
throw new NotImplementedException();
return new DrawableOsuRuleset(new OsuRuleset(), beatmap, mods);
}
public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap)
{
if (!HasImplementations)
throw new NotImplementedException();
return new OsuBeatmapConverter(beatmap, new OsuRuleset());
}
public override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap)
{
if (!HasImplementations)
throw new NotImplementedException();
return new OsuDifficultyCalculator(new OsuRuleset().RulesetInfo, beatmap);
}
public override string Description => "outdated ruleset";
public override string ShortName => "ruleset-outdated";
}
}
}

View File

@ -1,8 +1,6 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
@ -23,13 +21,13 @@ namespace osu.Game.Tests.Editing
[HeadlessTest]
public class TestSceneHitObjectComposerDistanceSnapping : EditorClockTestScene
{
private TestHitObjectComposer composer;
private TestHitObjectComposer composer = null!;
[Cached(typeof(EditorBeatmap))]
[Cached(typeof(IBeatSnapProvider))]
private readonly EditorBeatmap editorBeatmap;
protected override Container<Drawable> Content { get; }
protected override Container<Drawable> Content { get; } = new Container { RelativeSizeAxes = Axes.Both };
public TestSceneHitObjectComposerDistanceSnapping()
{
@ -40,15 +38,9 @@ namespace osu.Game.Tests.Editing
{
editorBeatmap = new EditorBeatmap(new OsuBeatmap
{
BeatmapInfo =
{
Ruleset = new OsuRuleset().RulesetInfo,
},
BeatmapInfo = { Ruleset = new OsuRuleset().RulesetInfo },
}),
Content = new Container
{
RelativeSizeAxes = Axes.Both,
}
Content
},
});
}
@ -205,7 +197,7 @@ namespace osu.Game.Tests.Editing
assertSnappedDistance(400, 400);
}
private void assertSnapDistance(float expectedDistance, HitObject hitObject = null)
private void assertSnapDistance(float expectedDistance, HitObject? hitObject = null)
=> AddAssert($"distance is {expectedDistance}", () => composer.GetBeatSnapDistanceAt(hitObject ?? new HitObject()), () => Is.EqualTo(expectedDistance));
private void assertDurationToDistance(double duration, float expectedDistance)

View File

@ -124,14 +124,19 @@ namespace osu.Game.Tests.Gameplay
Assert.That(score.Rank, Is.EqualTo(ScoreRank.F));
Assert.That(score.Passed, Is.False);
Assert.That(score.Statistics.Count(kvp => kvp.Value > 0), Is.EqualTo(7));
Assert.That(score.Statistics.Sum(kvp => kvp.Value), Is.EqualTo(4));
Assert.That(score.MaximumStatistics.Sum(kvp => kvp.Value), Is.EqualTo(8));
Assert.That(score.Statistics[HitResult.Ok], Is.EqualTo(1));
Assert.That(score.Statistics[HitResult.Miss], Is.EqualTo(1));
Assert.That(score.Statistics[HitResult.LargeTickHit], Is.EqualTo(1));
Assert.That(score.Statistics[HitResult.LargeTickMiss], Is.EqualTo(1));
Assert.That(score.Statistics[HitResult.SmallTickMiss], Is.EqualTo(2));
Assert.That(score.Statistics[HitResult.SmallTickMiss], Is.EqualTo(1));
Assert.That(score.Statistics[HitResult.SmallBonus], Is.EqualTo(1));
Assert.That(score.Statistics[HitResult.IgnoreMiss], Is.EqualTo(1));
Assert.That(score.MaximumStatistics[HitResult.Perfect], Is.EqualTo(2));
Assert.That(score.MaximumStatistics[HitResult.LargeTickHit], Is.EqualTo(2));
Assert.That(score.MaximumStatistics[HitResult.SmallTickHit], Is.EqualTo(2));
Assert.That(score.MaximumStatistics[HitResult.SmallBonus], Is.EqualTo(1));
Assert.That(score.MaximumStatistics[HitResult.LargeBonus], Is.EqualTo(1));
}
private class TestJudgement : Judgement

View File

@ -84,12 +84,15 @@ namespace osu.Game.Tests.Gameplay
});
});
AddStep("reset clock", () => gameplayContainer.Start());
AddStep("reset clock", () => gameplayContainer.Reset(startClock: true));
AddUntilStep("sample played", () => sample.RequestedPlaying);
AddUntilStep("sample has lifetime end", () => sample.LifetimeEnd < double.MaxValue);
}
/// <summary>
/// Sample at 0ms, start time at 1000ms (so the sample should not be played).
/// </summary>
[Test]
public void TestSampleHasLifetimeEndWithInitialClockTime()
{
@ -104,12 +107,13 @@ namespace osu.Game.Tests.Gameplay
Add(gameplayContainer = new MasterGameplayClockContainer(working, start_time)
{
StartTime = start_time,
Child = new FrameStabilityContainer
{
Child = sample = new DrawableStoryboardSample(new StoryboardSampleInfo(string.Empty, 0, 1))
}
});
gameplayContainer.Reset(start_time);
});
AddStep("start time", () => gameplayContainer.Start());
@ -143,7 +147,7 @@ namespace osu.Game.Tests.Gameplay
});
});
AddStep("start", () => gameplayContainer.Start());
AddStep("reset clock", () => gameplayContainer.Reset(startClock: true));
AddUntilStep("sample played", () => sample.IsPlayed);
AddUntilStep("sample has lifetime end", () => sample.LifetimeEnd < double.MaxValue);

View File

@ -194,8 +194,16 @@ namespace osu.Game.Tests.Resources
[HitResult.LargeTickHit] = 100,
[HitResult.LargeTickMiss] = 50,
[HitResult.SmallBonus] = 10,
[HitResult.SmallBonus] = 50
[HitResult.LargeBonus] = 50
},
MaximumStatistics = new Dictionary<HitResult, int>
{
[HitResult.Perfect] = 971,
[HitResult.SmallTickHit] = 75,
[HitResult.LargeTickHit] = 150,
[HitResult.SmallBonus] = 10,
[HitResult.LargeBonus] = 50,
}
};
private class TestModHardRock : ModHardRock

View File

@ -3,6 +3,7 @@
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
@ -306,7 +307,7 @@ namespace osu.Game.Tests.Rulesets.Scoring
HitObjects = { new TestHitObject(result) }
});
Assert.That(scoreProcessor.ComputeFinalScore(ScoringMode.Standardised, new ScoreInfo
Assert.That(scoreProcessor.ComputeScore(ScoringMode.Standardised, new ScoreInfo
{
Ruleset = new TestRuleset().RulesetInfo,
MaxCombo = result.AffectsCombo() ? 1 : 0,
@ -314,15 +315,55 @@ namespace osu.Game.Tests.Rulesets.Scoring
}), Is.EqualTo(expectedScore).Within(0.5d));
}
#pragma warning disable CS0618
[Test]
public void TestLegacyComboIncrease()
{
Assert.That(HitResult.LegacyComboIncrease.IncreasesCombo(), Is.True);
Assert.That(HitResult.LegacyComboIncrease.BreaksCombo(), Is.False);
Assert.That(HitResult.LegacyComboIncrease.AffectsCombo(), Is.True);
Assert.That(HitResult.LegacyComboIncrease.AffectsAccuracy(), Is.False);
Assert.That(HitResult.LegacyComboIncrease.IsBasic(), Is.False);
Assert.That(HitResult.LegacyComboIncrease.IsTick(), Is.False);
Assert.That(HitResult.LegacyComboIncrease.IsBonus(), Is.False);
Assert.That(HitResult.LegacyComboIncrease.IsHit(), Is.True);
Assert.That(HitResult.LegacyComboIncrease.IsScorable(), Is.True);
Assert.That(HitResultExtensions.ALL_TYPES, Does.Not.Contain(HitResult.LegacyComboIncrease));
// Cannot be used to apply results.
Assert.Throws<ArgumentException>(() => scoreProcessor.ApplyBeatmap(new Beatmap
{
HitObjects = { new TestHitObject(HitResult.LegacyComboIncrease) }
}));
ScoreInfo testScore = new ScoreInfo
{
MaxCombo = 1,
Statistics = new Dictionary<HitResult, int>
{
{ HitResult.Great, 1 }
},
MaximumStatistics = new Dictionary<HitResult, int>
{
{ HitResult.Great, 1 },
{ HitResult.LegacyComboIncrease, 1 }
}
};
double totalScore = new TestScoreProcessor().ComputeScore(ScoringMode.Standardised, testScore);
Assert.That(totalScore, Is.EqualTo(750_000)); // 500K from accuracy (100%), and 250K from combo (50%).
}
#pragma warning restore CS0618
private class TestRuleset : Ruleset
{
public override IEnumerable<Mod> GetModsFor(ModType type) => throw new System.NotImplementedException();
public override IEnumerable<Mod> GetModsFor(ModType type) => throw new NotImplementedException();
public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => throw new System.NotImplementedException();
public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => throw new NotImplementedException();
public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => throw new System.NotImplementedException();
public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => throw new NotImplementedException();
public override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => throw new System.NotImplementedException();
public override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => throw new NotImplementedException();
public override string Description => string.Empty;
public override string ShortName => string.Empty;
@ -352,5 +393,33 @@ namespace osu.Game.Tests.Rulesets.Scoring
this.maxResult = maxResult;
}
}
private class TestScoreProcessor : ScoreProcessor
{
protected override double DefaultAccuracyPortion => 0.5;
protected override double DefaultComboPortion => 0.5;
public TestScoreProcessor()
: base(new TestRuleset())
{
}
// ReSharper disable once MemberHidesStaticFromOuterClass
private class TestRuleset : Ruleset
{
protected override IEnumerable<HitResult> GetValidHitResults() => new[] { HitResult.Great };
public override IEnumerable<Mod> GetModsFor(ModType type) => throw new NotImplementedException();
public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => throw new NotImplementedException();
public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => throw new NotImplementedException();
public override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => throw new NotImplementedException();
public override string Description => string.Empty;
public override string ShortName => string.Empty;
}
}
}
}

View File

@ -55,51 +55,51 @@ namespace osu.Game.Tests.Visual.Editing
[Test]
public void TestStopAtTrackEnd()
{
AddStep("reset clock", () => Clock.Seek(0));
AddStep("reset clock", () => EditorClock.Seek(0));
AddStep("start clock", () => Clock.Start());
AddAssert("clock running", () => Clock.IsRunning);
AddStep("start clock", () => EditorClock.Start());
AddAssert("clock running", () => EditorClock.IsRunning);
AddStep("seek near end", () => Clock.Seek(Clock.TrackLength - 250));
AddUntilStep("clock stops", () => !Clock.IsRunning);
AddStep("seek near end", () => EditorClock.Seek(EditorClock.TrackLength - 250));
AddUntilStep("clock stops", () => !EditorClock.IsRunning);
AddUntilStep("clock stopped at end", () => Clock.CurrentTime, () => Is.EqualTo(Clock.TrackLength));
AddUntilStep("clock stopped at end", () => EditorClock.CurrentTime - EditorClock.TotalAppliedOffset, () => Is.EqualTo(EditorClock.TrackLength));
AddStep("start clock again", () => Clock.Start());
AddAssert("clock looped to start", () => Clock.IsRunning && Clock.CurrentTime < 500);
AddStep("start clock again", () => EditorClock.Start());
AddAssert("clock looped to start", () => EditorClock.IsRunning && EditorClock.CurrentTime < 500);
}
[Test]
public void TestWrapWhenStoppedAtTrackEnd()
{
AddStep("reset clock", () => Clock.Seek(0));
AddStep("reset clock", () => EditorClock.Seek(0));
AddStep("stop clock", () => Clock.Stop());
AddAssert("clock stopped", () => !Clock.IsRunning);
AddStep("stop clock", () => EditorClock.Stop());
AddAssert("clock stopped", () => !EditorClock.IsRunning);
AddStep("seek exactly to end", () => Clock.Seek(Clock.TrackLength));
AddAssert("clock stopped at end", () => Clock.CurrentTime, () => Is.EqualTo(Clock.TrackLength));
AddStep("seek exactly to end", () => EditorClock.Seek(EditorClock.TrackLength));
AddAssert("clock stopped at end", () => EditorClock.CurrentTime, () => Is.EqualTo(EditorClock.TrackLength));
AddStep("start clock again", () => Clock.Start());
AddAssert("clock looped to start", () => Clock.IsRunning && Clock.CurrentTime < 500);
AddStep("start clock again", () => EditorClock.Start());
AddAssert("clock looped to start", () => EditorClock.IsRunning && EditorClock.CurrentTime < 500);
}
[Test]
public void TestClampWhenSeekOutsideBeatmapBounds()
{
AddStep("stop clock", () => Clock.Stop());
AddStep("stop clock", () => EditorClock.Stop());
AddStep("seek before start time", () => Clock.Seek(-1000));
AddAssert("time is clamped to 0", () => Clock.CurrentTime, () => Is.EqualTo(0));
AddStep("seek before start time", () => EditorClock.Seek(-1000));
AddAssert("time is clamped to 0", () => EditorClock.CurrentTime, () => Is.EqualTo(0));
AddStep("seek beyond track length", () => Clock.Seek(Clock.TrackLength + 1000));
AddAssert("time is clamped to track length", () => Clock.CurrentTime, () => Is.EqualTo(Clock.TrackLength));
AddStep("seek beyond track length", () => EditorClock.Seek(EditorClock.TrackLength + 1000));
AddAssert("time is clamped to track length", () => EditorClock.CurrentTime, () => Is.EqualTo(EditorClock.TrackLength));
AddStep("seek smoothly before start time", () => Clock.SeekSmoothlyTo(-1000));
AddUntilStep("time is clamped to 0", () => Clock.CurrentTime, () => Is.EqualTo(0));
AddStep("seek smoothly before start time", () => EditorClock.SeekSmoothlyTo(-1000));
AddUntilStep("time is clamped to 0", () => EditorClock.CurrentTime, () => Is.EqualTo(0));
AddStep("seek smoothly beyond track length", () => Clock.SeekSmoothlyTo(Clock.TrackLength + 1000));
AddUntilStep("time is clamped to track length", () => Clock.CurrentTime, () => Is.EqualTo(Clock.TrackLength));
AddStep("seek smoothly beyond track length", () => EditorClock.SeekSmoothlyTo(EditorClock.TrackLength + 1000));
AddUntilStep("time is clamped to track length", () => EditorClock.CurrentTime, () => Is.EqualTo(EditorClock.TrackLength));
}
protected override void Dispose(bool isDisposing)

View File

@ -28,6 +28,11 @@ namespace osu.Game.Tests.Visual.Editing
{
base.LoadComplete();
Child = new TimingPointVisualiser(Beatmap.Value.Beatmap, 5000) { Clock = EditorClock };
}
protected override Beatmap CreateEditorClockBeatmap()
{
var testBeatmap = new Beatmap
{
ControlPointInfo = new ControlPointInfo(),
@ -45,9 +50,7 @@ namespace osu.Game.Tests.Visual.Editing
testBeatmap.ControlPointInfo.Add(450, new TimingControlPoint { BeatLength = 100 });
testBeatmap.ControlPointInfo.Add(500, new TimingControlPoint { BeatLength = 307.69230769230802 });
Beatmap.Value = CreateWorkingBeatmap(testBeatmap);
Child = new TimingPointVisualiser(testBeatmap, 5000) { Clock = Clock };
return testBeatmap;
}
/// <summary>
@ -59,17 +62,17 @@ namespace osu.Game.Tests.Visual.Editing
reset();
// Forwards
AddStep("Seek(0)", () => Clock.Seek(0));
AddStep("Seek(0)", () => EditorClock.Seek(0));
checkTime(0);
AddStep("Seek(33)", () => Clock.Seek(33));
AddStep("Seek(33)", () => EditorClock.Seek(33));
checkTime(33);
AddStep("Seek(89)", () => Clock.Seek(89));
AddStep("Seek(89)", () => EditorClock.Seek(89));
checkTime(89);
// Backwards
AddStep("Seek(25)", () => Clock.Seek(25));
AddStep("Seek(25)", () => EditorClock.Seek(25));
checkTime(25);
AddStep("Seek(0)", () => Clock.Seek(0));
AddStep("Seek(0)", () => EditorClock.Seek(0));
checkTime(0);
}
@ -82,19 +85,19 @@ namespace osu.Game.Tests.Visual.Editing
{
reset();
AddStep("Seek(0), Snap", () => Clock.SeekSnapped(0));
AddStep("Seek(0), Snap", () => EditorClock.SeekSnapped(0));
checkTime(0);
AddStep("Seek(50), Snap", () => Clock.SeekSnapped(50));
AddStep("Seek(50), Snap", () => EditorClock.SeekSnapped(50));
checkTime(50);
AddStep("Seek(100), Snap", () => Clock.SeekSnapped(100));
AddStep("Seek(100), Snap", () => EditorClock.SeekSnapped(100));
checkTime(100);
AddStep("Seek(175), Snap", () => Clock.SeekSnapped(175));
AddStep("Seek(175), Snap", () => EditorClock.SeekSnapped(175));
checkTime(175);
AddStep("Seek(350), Snap", () => Clock.SeekSnapped(350));
AddStep("Seek(350), Snap", () => EditorClock.SeekSnapped(350));
checkTime(350);
AddStep("Seek(400), Snap", () => Clock.SeekSnapped(400));
AddStep("Seek(400), Snap", () => EditorClock.SeekSnapped(400));
checkTime(400);
AddStep("Seek(450), Snap", () => Clock.SeekSnapped(450));
AddStep("Seek(450), Snap", () => EditorClock.SeekSnapped(450));
checkTime(450);
}
@ -107,17 +110,17 @@ namespace osu.Game.Tests.Visual.Editing
{
reset();
AddStep("Seek(24), Snap", () => Clock.SeekSnapped(24));
AddStep("Seek(24), Snap", () => EditorClock.SeekSnapped(24));
checkTime(0);
AddStep("Seek(26), Snap", () => Clock.SeekSnapped(26));
AddStep("Seek(26), Snap", () => EditorClock.SeekSnapped(26));
checkTime(50);
AddStep("Seek(150), Snap", () => Clock.SeekSnapped(150));
AddStep("Seek(150), Snap", () => EditorClock.SeekSnapped(150));
checkTime(100);
AddStep("Seek(170), Snap", () => Clock.SeekSnapped(170));
AddStep("Seek(170), Snap", () => EditorClock.SeekSnapped(170));
checkTime(175);
AddStep("Seek(274), Snap", () => Clock.SeekSnapped(274));
AddStep("Seek(274), Snap", () => EditorClock.SeekSnapped(274));
checkTime(175);
AddStep("Seek(276), Snap", () => Clock.SeekSnapped(276));
AddStep("Seek(276), Snap", () => EditorClock.SeekSnapped(276));
checkTime(350);
}
@ -129,15 +132,15 @@ namespace osu.Game.Tests.Visual.Editing
{
reset();
AddStep("SeekForward", () => Clock.SeekForward());
AddStep("SeekForward", () => EditorClock.SeekForward());
checkTime(50);
AddStep("SeekForward", () => Clock.SeekForward());
AddStep("SeekForward", () => EditorClock.SeekForward());
checkTime(100);
AddStep("SeekForward", () => Clock.SeekForward());
AddStep("SeekForward", () => EditorClock.SeekForward());
checkTime(200);
AddStep("SeekForward", () => Clock.SeekForward());
AddStep("SeekForward", () => EditorClock.SeekForward());
checkTime(400);
AddStep("SeekForward", () => Clock.SeekForward());
AddStep("SeekForward", () => EditorClock.SeekForward());
checkTime(450);
}
@ -149,17 +152,17 @@ namespace osu.Game.Tests.Visual.Editing
{
reset();
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(50);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(100);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(175);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(350);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(400);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(450);
}
@ -172,30 +175,30 @@ namespace osu.Game.Tests.Visual.Editing
{
reset();
AddStep("Seek(49)", () => Clock.Seek(49));
AddStep("Seek(49)", () => EditorClock.Seek(49));
checkTime(49);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(50);
AddStep("Seek(49.999)", () => Clock.Seek(49.999));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("Seek(49.999)", () => EditorClock.Seek(49.999));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(100);
AddStep("Seek(99)", () => Clock.Seek(99));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("Seek(99)", () => EditorClock.Seek(99));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(100);
AddStep("Seek(99.999)", () => Clock.Seek(99.999));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("Seek(99.999)", () => EditorClock.Seek(99.999));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(150);
AddStep("Seek(174)", () => Clock.Seek(174));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("Seek(174)", () => EditorClock.Seek(174));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(175);
AddStep("Seek(349)", () => Clock.Seek(349));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("Seek(349)", () => EditorClock.Seek(349));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(350);
AddStep("Seek(399)", () => Clock.Seek(399));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("Seek(399)", () => EditorClock.Seek(399));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(400);
AddStep("Seek(449)", () => Clock.Seek(449));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddStep("Seek(449)", () => EditorClock.Seek(449));
AddStep("SeekForward, Snap", () => EditorClock.SeekForward(true));
checkTime(450);
}
@ -207,17 +210,17 @@ namespace osu.Game.Tests.Visual.Editing
{
reset();
AddStep("Seek(450)", () => Clock.Seek(450));
AddStep("Seek(450)", () => EditorClock.Seek(450));
checkTime(450);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddStep("SeekBackward", () => EditorClock.SeekBackward());
checkTime(400);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddStep("SeekBackward", () => EditorClock.SeekBackward());
checkTime(350);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddStep("SeekBackward", () => EditorClock.SeekBackward());
checkTime(150);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddStep("SeekBackward", () => EditorClock.SeekBackward());
checkTime(50);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddStep("SeekBackward", () => EditorClock.SeekBackward());
checkTime(0);
}
@ -229,19 +232,19 @@ namespace osu.Game.Tests.Visual.Editing
{
reset();
AddStep("Seek(450)", () => Clock.Seek(450));
AddStep("Seek(450)", () => EditorClock.Seek(450));
checkTime(450);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddStep("SeekBackward, Snap", () => EditorClock.SeekBackward(true));
checkTime(400);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddStep("SeekBackward, Snap", () => EditorClock.SeekBackward(true));
checkTime(350);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddStep("SeekBackward, Snap", () => EditorClock.SeekBackward(true));
checkTime(175);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddStep("SeekBackward, Snap", () => EditorClock.SeekBackward(true));
checkTime(100);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddStep("SeekBackward, Snap", () => EditorClock.SeekBackward(true));
checkTime(50);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddStep("SeekBackward, Snap", () => EditorClock.SeekBackward(true));
checkTime(0);
}
@ -254,18 +257,18 @@ namespace osu.Game.Tests.Visual.Editing
{
reset();
AddStep("Seek(451)", () => Clock.Seek(451));
AddStep("Seek(451)", () => EditorClock.Seek(451));
checkTime(451);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddStep("SeekBackward, Snap", () => EditorClock.SeekBackward(true));
checkTime(450);
AddStep("Seek(450.999)", () => Clock.Seek(450.999));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddStep("Seek(450.999)", () => EditorClock.Seek(450.999));
AddStep("SeekBackward, Snap", () => EditorClock.SeekBackward(true));
checkTime(450);
AddStep("Seek(401)", () => Clock.Seek(401));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddStep("Seek(401)", () => EditorClock.Seek(401));
AddStep("SeekBackward, Snap", () => EditorClock.SeekBackward(true));
checkTime(400);
AddStep("Seek(401.999)", () => Clock.Seek(401.999));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddStep("Seek(401.999)", () => EditorClock.Seek(401.999));
AddStep("SeekBackward, Snap", () => EditorClock.SeekBackward(true));
checkTime(400);
}
@ -279,37 +282,37 @@ namespace osu.Game.Tests.Visual.Editing
double lastTime = 0;
AddStep("Seek(0)", () => Clock.Seek(0));
AddStep("Seek(0)", () => EditorClock.Seek(0));
checkTime(0);
for (int i = 0; i < 9; i++)
{
AddStep("SeekForward, Snap", () =>
{
lastTime = Clock.CurrentTime;
Clock.SeekForward(true);
lastTime = EditorClock.CurrentTime;
EditorClock.SeekForward(true);
});
AddAssert("Time > lastTime", () => Clock.CurrentTime > lastTime);
AddAssert("Time > lastTime", () => EditorClock.CurrentTime > lastTime);
}
for (int i = 0; i < 9; i++)
{
AddStep("SeekBackward, Snap", () =>
{
lastTime = Clock.CurrentTime;
Clock.SeekBackward(true);
lastTime = EditorClock.CurrentTime;
EditorClock.SeekBackward(true);
});
AddAssert("Time < lastTime", () => Clock.CurrentTime < lastTime);
AddAssert("Time < lastTime", () => EditorClock.CurrentTime < lastTime);
}
checkTime(0);
}
private void checkTime(double expectedTime) => AddAssert($"Current time is {expectedTime}", () => Clock.CurrentTime, () => Is.EqualTo(expectedTime));
private void checkTime(double expectedTime) => AddUntilStep($"Current time is {expectedTime}", () => EditorClock.CurrentTime, () => Is.EqualTo(expectedTime));
private void reset()
{
AddStep("Reset", () => Clock.Seek(0));
AddStep("Reset", () => EditorClock.Seek(0));
}
private class TimingPointVisualiser : CompositeDrawable

View File

@ -113,7 +113,7 @@ namespace osu.Game.Tests.Visual.Editing
.TriggerClick();
});
AddUntilStep("wait for track playing", () => Clock.IsRunning);
AddUntilStep("wait for track playing", () => EditorClock.IsRunning);
AddStep("click reset button", () =>
{
@ -122,7 +122,7 @@ namespace osu.Game.Tests.Visual.Editing
.TriggerClick();
});
AddUntilStep("wait for track stopped", () => !Clock.IsRunning);
AddUntilStep("wait for track stopped", () => !EditorClock.IsRunning);
}
protected override void Dispose(bool isDisposing)

View File

@ -17,7 +17,7 @@ namespace osu.Game.Tests.Visual.Editing
protected override void LoadComplete()
{
base.LoadComplete();
Clock.Seek(10000);
EditorClock.Seek(10000);
}
}
}

View File

@ -17,8 +17,6 @@ namespace osu.Game.Tests.Visual.Editing
{
double initialVisibleRange = 0;
AddUntilStep("wait for load", () => MusicController.TrackLoaded);
AddStep("reset zoom", () => TimelineArea.Timeline.Zoom = 100);
AddStep("get initial range", () => initialVisibleRange = TimelineArea.Timeline.VisibleRange);
@ -36,8 +34,6 @@ namespace osu.Game.Tests.Visual.Editing
{
double initialVisibleRange = 0;
AddUntilStep("wait for load", () => MusicController.TrackLoaded);
AddStep("reset timeline size", () => TimelineArea.Timeline.Width = 1);
AddStep("get initial range", () => initialVisibleRange = TimelineArea.Timeline.VisibleRange);

View File

@ -53,7 +53,7 @@ namespace osu.Game.Tests.Visual.Editing
[SetUpSteps]
public void SetUpSteps()
{
AddStep("Stop clock", () => Clock.Stop());
AddStep("Stop clock", () => EditorClock.Stop());
AddUntilStep("wait for rows to load", () => Child.ChildrenOfType<EffectRowAttribute>().Any());
}
@ -68,10 +68,10 @@ namespace osu.Game.Tests.Visual.Editing
});
AddUntilStep("Selection changed", () => timingScreen.SelectedGroup.Value.Time == 54670);
AddUntilStep("Ensure seeked to correct time", () => Clock.CurrentTimeAccurate == 54670);
AddUntilStep("Ensure seeked to correct time", () => EditorClock.CurrentTimeAccurate == 54670);
AddStep("Seek to just before next point", () => Clock.Seek(69000));
AddStep("Start clock", () => Clock.Start());
AddStep("Seek to just before next point", () => EditorClock.Seek(69000));
AddStep("Start clock", () => EditorClock.Start());
AddUntilStep("Selection changed", () => timingScreen.SelectedGroup.Value.Time == 69670);
}
@ -86,9 +86,9 @@ namespace osu.Game.Tests.Visual.Editing
});
AddUntilStep("Selection changed", () => timingScreen.SelectedGroup.Value.Time == 54670);
AddUntilStep("Ensure seeked to correct time", () => Clock.CurrentTimeAccurate == 54670);
AddUntilStep("Ensure seeked to correct time", () => EditorClock.CurrentTimeAccurate == 54670);
AddStep("Seek to later", () => Clock.Seek(80000));
AddStep("Seek to later", () => EditorClock.Seek(80000));
AddUntilStep("Selection changed", () => timingScreen.SelectedGroup.Value.Time == 69670);
}

View File

@ -9,12 +9,14 @@ using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Graphics.Cursor;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets.Edit;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Compose.Components.Timeline;
using osu.Game.Storyboards;
using osuTK;
using osuTK.Graphics;
@ -28,10 +30,14 @@ namespace osu.Game.Tests.Visual.Editing
protected EditorBeatmap EditorBeatmap { get; private set; }
[BackgroundDependencyLoader]
private void load(AudioManager audio)
[Resolved]
private AudioManager audio { get; set; }
protected override WorkingBeatmap CreateWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null) => new WaveformTestBeatmap(audio);
protected override void LoadComplete()
{
Beatmap.Value = new WaveformTestBeatmap(audio);
base.LoadComplete();
var playable = Beatmap.Value.GetPlayableBeatmap(Beatmap.Value.BeatmapInfo.Ruleset);
EditorBeatmap = new EditorBeatmap(playable);
@ -68,11 +74,11 @@ namespace osu.Game.Tests.Visual.Editing
});
}
protected override void LoadComplete()
[SetUpSteps]
public void SetUpSteps()
{
base.LoadComplete();
Clock.Seek(2500);
AddUntilStep("wait for track loaded", () => MusicController.TrackLoaded);
AddStep("seek forward", () => EditorClock.Seek(2500));
}
public abstract Drawable CreateTestComponent();

View File

@ -19,7 +19,7 @@ namespace osu.Game.Tests.Visual.Gameplay
{
private LeadInPlayer player = null!;
private const double lenience_ms = 10;
private const double lenience_ms = 100;
private const double first_hit_object = 2170;

View File

@ -0,0 +1,50 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Tests.Visual.Gameplay
{
[HeadlessTest]
public class TestSceneModValidity : TestSceneAllRulesetPlayers
{
protected override void AddCheckSteps()
{
AddStep("Check all mod acronyms are unique", () =>
{
var mods = Ruleset.Value.CreateInstance().AllMods;
IEnumerable<string> acronyms = mods.Select(m => m.Acronym);
Assert.That(acronyms, Is.Unique);
});
AddStep("Check all mods are two-way incompatible", () =>
{
var mods = Ruleset.Value.CreateInstance().AllMods;
IEnumerable<Mod> modInstances = mods.Select(mod => mod.CreateInstance());
foreach (var modToCheck in modInstances)
{
var incompatibleMods = modToCheck.IncompatibleMods;
foreach (var incompatible in incompatibleMods)
{
foreach (var incompatibleMod in modInstances.Where(m => incompatible.IsInstanceOfType(m)))
{
Assert.That(
incompatibleMod.IncompatibleMods.Any(m => m.IsInstanceOfType(modToCheck)),
$"{modToCheck} has {incompatibleMod} in it's incompatible mods, but {incompatibleMod} does not have {modToCheck} in it's incompatible mods."
);
}
}
}
});
}
}
}

View File

@ -1,27 +0,0 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
namespace osu.Game.Tests.Visual.Gameplay
{
[HeadlessTest]
public class TestSceneNoConflictingModAcronyms : TestSceneAllRulesetPlayers
{
protected override void AddCheckSteps()
{
AddStep("Check all mod acronyms are unique", () =>
{
var mods = Ruleset.Value.CreateInstance().AllMods;
IEnumerable<string> acronyms = mods.Select(m => m.Acronym);
Assert.That(acronyms, Is.Unique);
});
}
}
}

View File

@ -37,7 +37,7 @@ namespace osu.Game.Tests.Visual.Gameplay
{
Dependencies.Cache(rulesets = new RealmRulesetStore(Realm));
Dependencies.Cache(beatmaps = new BeatmapManager(LocalStorage, Realm, null, audio, Resources, host, Beatmap.Default));
Dependencies.Cache(new ScoreManager(rulesets, () => beatmaps, LocalStorage, Realm, Scheduler, API));
Dependencies.Cache(new ScoreManager(rulesets, () => beatmaps, LocalStorage, Realm, API));
Dependencies.Cache(Realm);
}

View File

@ -27,8 +27,7 @@ namespace osu.Game.Tests.Visual.Gameplay
private const double skip_time = 6000;
[SetUp]
public void SetUp() => Schedule(() =>
private void createTest(double skipTime = skip_time) => AddStep("create test", () =>
{
requestCount = 0;
increment = skip_time;
@ -40,7 +39,7 @@ namespace osu.Game.Tests.Visual.Gameplay
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
skip = new TestSkipOverlay(skip_time)
skip = new TestSkipOverlay(skipTime)
{
RequestSkip = () =>
{
@ -55,9 +54,25 @@ namespace osu.Game.Tests.Visual.Gameplay
gameplayClock = gameplayClockContainer;
});
[Test]
public void TestSkipTimeZero()
{
createTest(0);
AddUntilStep("wait for skip overlay expired", () => !skip.IsAlive);
}
[Test]
public void TestSkipTimeEqualToSkip()
{
createTest(MasterGameplayClockContainer.MINIMUM_SKIP_TIME);
AddUntilStep("wait for skip overlay expired", () => !skip.IsAlive);
}
[Test]
public void TestFadeOnIdle()
{
createTest();
AddStep("move mouse", () => InputManager.MoveMouseTo(Vector2.Zero));
AddUntilStep("fully visible", () => skip.FadingContent.Alpha == 1);
AddUntilStep("wait for fade", () => skip.FadingContent.Alpha < 1);
@ -70,6 +85,8 @@ namespace osu.Game.Tests.Visual.Gameplay
[Test]
public void TestClickableAfterFade()
{
createTest();
AddStep("move mouse", () => InputManager.MoveMouseTo(skip.ScreenSpaceDrawQuad.Centre));
AddUntilStep("wait for fade", () => skip.FadingContent.Alpha == 0);
AddStep("click", () => InputManager.Click(MouseButton.Left));
@ -79,6 +96,8 @@ namespace osu.Game.Tests.Visual.Gameplay
[Test]
public void TestClickOnlyActuatesOnce()
{
createTest();
AddStep("move mouse", () => InputManager.MoveMouseTo(skip.ScreenSpaceDrawQuad.Centre));
AddStep("click", () =>
{
@ -94,6 +113,8 @@ namespace osu.Game.Tests.Visual.Gameplay
[Test]
public void TestClickOnlyActuatesMultipleTimes()
{
createTest();
AddStep("set increment lower", () => increment = 3000);
AddStep("move mouse", () => InputManager.MoveMouseTo(skip.ScreenSpaceDrawQuad.Centre));
AddStep("click", () => InputManager.Click(MouseButton.Left));
@ -106,6 +127,8 @@ namespace osu.Game.Tests.Visual.Gameplay
[Test]
public void TestDoesntFadeOnMouseDown()
{
createTest();
AddStep("move mouse", () => InputManager.MoveMouseTo(skip.ScreenSpaceDrawQuad.Centre));
AddStep("button down", () => InputManager.PressButton(MouseButton.Left));
AddUntilStep("wait for overlay disappear", () => !skip.OverlayContent.IsPresent);

View File

@ -85,7 +85,7 @@ namespace osu.Game.Tests.Visual.Gameplay
sendFrames(startTime: gameplay_start);
AddAssert("time is greater than seek target", () => currentFrameStableTime > gameplay_start);
AddAssert("time is greater than seek target", () => currentFrameStableTime, () => Is.GreaterThan(gameplay_start));
}
/// <summary>
@ -119,7 +119,7 @@ namespace osu.Game.Tests.Visual.Gameplay
waitForPlayer();
AddUntilStep("state is playing", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Playing);
AddAssert("time is greater than seek target", () => currentFrameStableTime > gameplay_start);
AddAssert("time is greater than seek target", () => currentFrameStableTime, () => Is.GreaterThan(gameplay_start));
}
[Test]
@ -147,7 +147,7 @@ namespace osu.Game.Tests.Visual.Gameplay
AddUntilStep("wait for frame starvation", () => replayHandler.WaitingForFrame);
checkPaused(true);
AddAssert("time advanced", () => currentFrameStableTime > pausedTime);
AddAssert("time advanced", () => currentFrameStableTime, () => Is.GreaterThan(pausedTime));
}
[Test]
@ -176,7 +176,7 @@ namespace osu.Game.Tests.Visual.Gameplay
sendFrames(300);
AddUntilStep("playing from correct point in time", () => player.ChildrenOfType<DrawableRuleset>().First().FrameStableClock.CurrentTime > 30000);
AddUntilStep("playing from correct point in time", () => player.ChildrenOfType<DrawableRuleset>().First().FrameStableClock.CurrentTime, () => Is.GreaterThan(30000));
}
[Test]

View File

@ -165,11 +165,11 @@ namespace osu.Game.Tests.Visual.Multiplayer
sendFrames(PLAYER_1_ID, 40);
sendFrames(PLAYER_2_ID, 20);
checkPaused(PLAYER_2_ID, true);
checkPausedInstant(PLAYER_1_ID, false);
waitUntilPaused(PLAYER_2_ID);
checkRunningInstant(PLAYER_1_ID);
AddAssert("master clock still running", () => this.ChildrenOfType<MasterGameplayClockContainer>().Single().IsRunning);
checkPaused(PLAYER_1_ID, true);
waitUntilPaused(PLAYER_1_ID);
AddUntilStep("master clock paused", () => !this.ChildrenOfType<MasterGameplayClockContainer>().Single().IsRunning);
}
@ -181,13 +181,13 @@ namespace osu.Game.Tests.Visual.Multiplayer
// Send frames for one player only, both should remain paused.
sendFrames(PLAYER_1_ID, 20);
checkPausedInstant(PLAYER_1_ID, true);
checkPausedInstant(PLAYER_2_ID, true);
checkPausedInstant(PLAYER_1_ID);
checkPausedInstant(PLAYER_2_ID);
// Send frames for the other player, both should now start playing.
sendFrames(PLAYER_2_ID, 20);
checkPausedInstant(PLAYER_1_ID, false);
checkPausedInstant(PLAYER_2_ID, false);
checkRunningInstant(PLAYER_1_ID);
checkRunningInstant(PLAYER_2_ID);
}
[Test]
@ -198,15 +198,15 @@ namespace osu.Game.Tests.Visual.Multiplayer
// Send frames for one player only, both should remain paused.
sendFrames(PLAYER_1_ID, 1000);
checkPausedInstant(PLAYER_1_ID, true);
checkPausedInstant(PLAYER_2_ID, true);
checkPausedInstant(PLAYER_1_ID);
checkPausedInstant(PLAYER_2_ID);
// Wait for the start delay seconds...
AddWaitStep("wait maximum start delay seconds", (int)(SpectatorSyncManager.MAXIMUM_START_DELAY / TimePerAction));
// Player 1 should start playing by itself, player 2 should remain paused.
checkPausedInstant(PLAYER_1_ID, false);
checkPausedInstant(PLAYER_2_ID, true);
checkRunningInstant(PLAYER_1_ID);
checkPausedInstant(PLAYER_2_ID);
}
[Test]
@ -218,26 +218,26 @@ namespace osu.Game.Tests.Visual.Multiplayer
// Send initial frames for both players. A few more for player 1.
sendFrames(PLAYER_1_ID, 20);
sendFrames(PLAYER_2_ID);
checkPausedInstant(PLAYER_1_ID, false);
checkPausedInstant(PLAYER_2_ID, false);
checkRunningInstant(PLAYER_1_ID);
checkRunningInstant(PLAYER_2_ID);
// Eventually player 2 will pause, player 1 must remain running.
checkPaused(PLAYER_2_ID, true);
checkPausedInstant(PLAYER_1_ID, false);
waitUntilPaused(PLAYER_2_ID);
checkRunningInstant(PLAYER_1_ID);
// Eventually both players will run out of frames and should pause.
checkPaused(PLAYER_1_ID, true);
checkPausedInstant(PLAYER_2_ID, true);
waitUntilPaused(PLAYER_1_ID);
checkPausedInstant(PLAYER_2_ID);
// Send more frames for the first player only. Player 1 should start playing with player 2 remaining paused.
sendFrames(PLAYER_1_ID, 20);
checkPausedInstant(PLAYER_2_ID, true);
checkPausedInstant(PLAYER_1_ID, false);
checkPausedInstant(PLAYER_2_ID);
checkRunningInstant(PLAYER_1_ID);
// Send more frames for the second player. Both should be playing
sendFrames(PLAYER_2_ID, 20);
checkPausedInstant(PLAYER_2_ID, false);
checkPausedInstant(PLAYER_1_ID, false);
checkRunningInstant(PLAYER_2_ID);
checkRunningInstant(PLAYER_1_ID);
}
[Test]
@ -249,16 +249,16 @@ namespace osu.Game.Tests.Visual.Multiplayer
// Send initial frames for both players. A few more for player 1.
sendFrames(PLAYER_1_ID, 1000);
sendFrames(PLAYER_2_ID, 30);
checkPausedInstant(PLAYER_1_ID, false);
checkPausedInstant(PLAYER_2_ID, false);
checkRunningInstant(PLAYER_1_ID);
checkRunningInstant(PLAYER_2_ID);
// Eventually player 2 will run out of frames and should pause.
checkPaused(PLAYER_2_ID, true);
waitUntilPaused(PLAYER_2_ID);
AddWaitStep("wait a few more frames", 10);
// Send more frames for player 2. It should unpause.
sendFrames(PLAYER_2_ID, 1000);
checkPausedInstant(PLAYER_2_ID, false);
checkRunningInstant(PLAYER_2_ID);
// Player 2 should catch up to player 1 after unpausing.
waitForCatchup(PLAYER_2_ID);
@ -271,21 +271,28 @@ namespace osu.Game.Tests.Visual.Multiplayer
start(new[] { PLAYER_1_ID, PLAYER_2_ID });
loadSpectateScreen();
// With no frames, the synchronisation state will be TooFarAhead.
// In this state, all players should be muted.
assertMuted(PLAYER_1_ID, true);
assertMuted(PLAYER_2_ID, true);
sendFrames(PLAYER_1_ID);
// Send frames for both players, with more frames for player 2.
sendFrames(PLAYER_1_ID, 5);
sendFrames(PLAYER_2_ID, 20);
checkPaused(PLAYER_1_ID, false);
assertOneNotMuted();
checkPaused(PLAYER_1_ID, true);
// While both players are running, one of them should be un-muted.
waitUntilRunning(PLAYER_1_ID);
assertOnePlayerNotMuted();
// After player 1 runs out of frames, the un-muted player should always be player 2.
waitUntilPaused(PLAYER_1_ID);
waitUntilRunning(PLAYER_2_ID);
assertMuted(PLAYER_1_ID, true);
assertMuted(PLAYER_2_ID, false);
sendFrames(PLAYER_1_ID, 100);
waitForCatchup(PLAYER_1_ID);
checkPaused(PLAYER_2_ID, true);
waitUntilPaused(PLAYER_2_ID);
assertMuted(PLAYER_1_ID, false);
assertMuted(PLAYER_2_ID, true);
@ -319,7 +326,7 @@ namespace osu.Game.Tests.Visual.Multiplayer
sendFrames(PLAYER_1_ID, 300);
AddWaitStep("wait maximum start delay seconds", (int)(SpectatorSyncManager.MAXIMUM_START_DELAY / TimePerAction));
checkPaused(PLAYER_1_ID, false);
waitUntilRunning(PLAYER_1_ID);
sendFrames(PLAYER_2_ID, 300);
AddUntilStep("player 2 playing from correct point in time", () => getPlayer(PLAYER_2_ID).ChildrenOfType<DrawableRuleset>().Single().FrameStableClock.CurrentTime > 30000);
@ -357,12 +364,18 @@ namespace osu.Game.Tests.Visual.Multiplayer
/// <summary>
/// Tests spectating with a beatmap that has a high <see cref="BeatmapInfo.AudioLeadIn"/> value.
///
/// This test is not intended not to check the correct initial time value, but only to guard against
/// gameplay potentially getting stuck in a stopped state due to lead in time being present.
/// </summary>
[Test]
public void TestAudioLeadIn() => testLeadIn(b => b.BeatmapInfo.AudioLeadIn = 2000);
/// <summary>
/// Tests spectating with a beatmap that has a storyboard element with a negative start time (i.e. intro storyboard element).
///
/// This test is not intended not to check the correct initial time value, but only to guard against
/// gameplay potentially getting stuck in a stopped state due to lead in time being present.
/// </summary>
[Test]
public void TestIntroStoryboardElement() => testLeadIn(b =>
@ -384,10 +397,10 @@ namespace osu.Game.Tests.Visual.Multiplayer
AddUntilStep("wait for player load", () => spectatorScreen.AllPlayersLoaded);
AddWaitStep("wait for progression", 3);
AddUntilStep("wait for clock running", () => getInstance(PLAYER_1_ID).SpectatorPlayerClock.IsRunning);
assertNotCatchingUp(PLAYER_1_ID);
assertRunning(PLAYER_1_ID);
waitUntilRunning(PLAYER_1_ID);
}
private void loadSpectateScreen(bool waitForPlayerLoad = true, Action<WorkingBeatmap>? applyToBeatmap = null)
@ -439,6 +452,10 @@ namespace osu.Game.Tests.Visual.Multiplayer
});
}
/// <summary>
/// Send new frames on behalf of a user.
/// Frames will last for count * 100 milliseconds.
/// </summary>
private void sendFrames(int userId, int count = 10) => sendFrames(new[] { userId }, count);
private void sendFrames(int[] userIds, int count = 10)
@ -450,30 +467,41 @@ namespace osu.Game.Tests.Visual.Multiplayer
});
}
private void checkPaused(int userId, bool state)
=> AddUntilStep($"{userId} is {(state ? "paused" : "playing")}", () => getPlayer(userId).ChildrenOfType<GameplayClockContainer>().First().IsRunning != state);
private void checkPausedInstant(int userId, bool state)
private void checkRunningInstant(int userId)
{
checkPaused(userId, state);
waitUntilRunning(userId);
// Todo: The following should work, but is broken because SpectatorScreen retrieves the WorkingBeatmap via the BeatmapManager, bypassing the test scene clock and running real-time.
// AddAssert($"{userId} is {(state ? "paused" : "playing")}", () => getPlayer(userId).ChildrenOfType<GameplayClockContainer>().First().GameplayClock.IsRunning != state);
}
private void assertOneNotMuted() => AddAssert("one player not muted", () => spectatorScreen.ChildrenOfType<PlayerArea>().Count(p => !p.Mute) == 1);
private void checkPausedInstant(int userId)
{
waitUntilPaused(userId);
// Todo: The following should work, but is broken because SpectatorScreen retrieves the WorkingBeatmap via the BeatmapManager, bypassing the test scene clock and running real-time.
// AddAssert($"{userId} is {(state ? "paused" : "playing")}", () => getPlayer(userId).ChildrenOfType<GameplayClockContainer>().First().GameplayClock.IsRunning != state);
}
private void assertOnePlayerNotMuted() => AddAssert(nameof(assertOnePlayerNotMuted), () => spectatorScreen.ChildrenOfType<PlayerArea>().Count(p => !p.Mute) == 1);
private void assertMuted(int userId, bool muted)
=> AddAssert($"{userId} {(muted ? "is" : "is not")} muted", () => getInstance(userId).Mute == muted);
=> AddAssert($"{nameof(assertMuted)}({userId}, {muted})", () => getInstance(userId).Mute == muted);
private void assertRunning(int userId)
=> AddAssert($"{userId} clock running", () => getInstance(userId).GameplayClock.IsRunning);
=> AddAssert($"{nameof(assertRunning)}({userId})", () => getInstance(userId).SpectatorPlayerClock.IsRunning);
private void waitUntilPaused(int userId)
=> AddUntilStep($"{nameof(waitUntilPaused)}({userId})", () => !getPlayer(userId).ChildrenOfType<GameplayClockContainer>().First().IsRunning);
private void waitUntilRunning(int userId)
=> AddUntilStep($"{nameof(waitUntilRunning)}({userId})", () => getPlayer(userId).ChildrenOfType<GameplayClockContainer>().First().IsRunning);
private void assertNotCatchingUp(int userId)
=> AddAssert($"{userId} in sync", () => !getInstance(userId).GameplayClock.IsCatchingUp);
=> AddAssert($"{nameof(assertNotCatchingUp)}({userId})", () => !getInstance(userId).SpectatorPlayerClock.IsCatchingUp);
private void waitForCatchup(int userId)
=> AddUntilStep($"{userId} not catching up", () => !getInstance(userId).GameplayClock.IsCatchingUp);
=> AddUntilStep($"{nameof(waitForCatchup)}({userId})", () => !getInstance(userId).SpectatorPlayerClock.IsCatchingUp);
private Player getPlayer(int userId) => getInstance(userId).ChildrenOfType<Player>().Single();

View File

@ -61,6 +61,7 @@ namespace osu.Game.Tests.Visual.Playlists
userScore = TestResources.CreateTestScoreInfo();
userScore.TotalScore = 0;
userScore.Statistics = new Dictionary<HitResult, int>();
userScore.MaximumStatistics = new Dictionary<HitResult, int>();
bindHandler();

View File

@ -244,8 +244,12 @@ namespace osu.Game.Tests.Visual.SongSelect
const int total_set_count = 200;
for (int i = 0; i < total_set_count; i++)
sets.Add(TestResources.CreateTestBeatmapSetInfo());
AddStep("Populuate beatmap sets", () =>
{
sets.Clear();
for (int i = 0; i < total_set_count; i++)
sets.Add(TestResources.CreateTestBeatmapSetInfo());
});
loadBeatmaps(sets);
@ -275,8 +279,12 @@ namespace osu.Game.Tests.Visual.SongSelect
const int total_set_count = 20;
for (int i = 0; i < total_set_count; i++)
sets.Add(TestResources.CreateTestBeatmapSetInfo(3));
AddStep("Populuate beatmap sets", () =>
{
sets.Clear();
for (int i = 0; i < total_set_count; i++)
sets.Add(TestResources.CreateTestBeatmapSetInfo(3));
});
loadBeatmaps(sets);
@ -493,18 +501,23 @@ namespace osu.Game.Tests.Visual.SongSelect
const string zzz_string = "zzzzz";
for (int i = 0; i < 20; i++)
AddStep("Populuate beatmap sets", () =>
{
var set = TestResources.CreateTestBeatmapSetInfo();
sets.Clear();
if (i == 4)
set.Beatmaps.ForEach(b => b.Metadata.Artist = zzz_string);
for (int i = 0; i < 20; i++)
{
var set = TestResources.CreateTestBeatmapSetInfo();
if (i == 16)
set.Beatmaps.ForEach(b => b.Metadata.Author.Username = zzz_string);
if (i == 4)
set.Beatmaps.ForEach(b => b.Metadata.Artist = zzz_string);
sets.Add(set);
}
if (i == 16)
set.Beatmaps.ForEach(b => b.Metadata.Author.Username = zzz_string);
sets.Add(set);
}
});
loadBeatmaps(sets);
@ -521,21 +534,27 @@ namespace osu.Game.Tests.Visual.SongSelect
public void TestSortingStability()
{
var sets = new List<BeatmapSetInfo>();
int idOffset = 0;
for (int i = 0; i < 10; i++)
AddStep("Populuate beatmap sets", () =>
{
var set = TestResources.CreateTestBeatmapSetInfo();
sets.Clear();
// only need to set the first as they are a shared reference.
var beatmap = set.Beatmaps.First();
for (int i = 0; i < 10; i++)
{
var set = TestResources.CreateTestBeatmapSetInfo();
beatmap.Metadata.Artist = $"artist {i / 2}";
beatmap.Metadata.Title = $"title {9 - i}";
// only need to set the first as they are a shared reference.
var beatmap = set.Beatmaps.First();
sets.Add(set);
}
beatmap.Metadata.Artist = $"artist {i / 2}";
beatmap.Metadata.Title = $"title {9 - i}";
int idOffset = sets.First().OnlineID;
sets.Add(set);
}
idOffset = sets.First().OnlineID;
});
loadBeatmaps(sets);
@ -556,26 +575,32 @@ namespace osu.Game.Tests.Visual.SongSelect
public void TestSortingStabilityWithNewItems()
{
List<BeatmapSetInfo> sets = new List<BeatmapSetInfo>();
int idOffset = 0;
for (int i = 0; i < 3; i++)
AddStep("Populuate beatmap sets", () =>
{
var set = TestResources.CreateTestBeatmapSetInfo(3);
sets.Clear();
// only need to set the first as they are a shared reference.
var beatmap = set.Beatmaps.First();
for (int i = 0; i < 3; i++)
{
var set = TestResources.CreateTestBeatmapSetInfo(3);
beatmap.Metadata.Artist = "same artist";
beatmap.Metadata.Title = "same title";
// only need to set the first as they are a shared reference.
var beatmap = set.Beatmaps.First();
sets.Add(set);
}
beatmap.Metadata.Artist = "same artist";
beatmap.Metadata.Title = "same title";
int idOffset = sets.First().OnlineID;
sets.Add(set);
}
idOffset = sets.First().OnlineID;
});
loadBeatmaps(sets);
AddStep("Sort by artist", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Artist }, false));
AddAssert("Items remain in original order", () => carousel.BeatmapSets.Select((set, index) => set.OnlineID == idOffset + index).All(b => b));
assertOriginalOrderMaintained();
AddStep("Add new item", () =>
{
@ -590,10 +615,16 @@ namespace osu.Game.Tests.Visual.SongSelect
carousel.UpdateBeatmapSet(set);
});
AddAssert("Items remain in original order", () => carousel.BeatmapSets.Select((set, index) => set.OnlineID == idOffset + index).All(b => b));
assertOriginalOrderMaintained();
AddStep("Sort by title", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Title }, false));
AddAssert("Items remain in original order", () => carousel.BeatmapSets.Select((set, index) => set.OnlineID == idOffset + index).All(b => b));
assertOriginalOrderMaintained();
void assertOriginalOrderMaintained()
{
AddAssert("Items remain in original order",
() => carousel.BeatmapSets.Select(s => s.OnlineID), () => Is.EqualTo(carousel.BeatmapSets.Select((set, index) => idOffset + index)));
}
}
[Test]
@ -601,13 +632,18 @@ namespace osu.Game.Tests.Visual.SongSelect
{
List<BeatmapSetInfo> sets = new List<BeatmapSetInfo>();
for (int i = 0; i < 3; i++)
AddStep("Populuate beatmap sets", () =>
{
var set = TestResources.CreateTestBeatmapSetInfo(3);
set.Beatmaps[0].StarRating = 3 - i;
set.Beatmaps[2].StarRating = 6 + i;
sets.Add(set);
}
sets.Clear();
for (int i = 0; i < 3; i++)
{
var set = TestResources.CreateTestBeatmapSetInfo(3);
set.Beatmaps[0].StarRating = 3 - i;
set.Beatmaps[2].StarRating = 6 + i;
sets.Add(set);
}
});
loadBeatmaps(sets);
@ -759,8 +795,13 @@ namespace osu.Game.Tests.Visual.SongSelect
{
List<BeatmapSetInfo> manySets = new List<BeatmapSetInfo>();
for (int i = 1; i <= 50; i++)
manySets.Add(TestResources.CreateTestBeatmapSetInfo(3));
AddStep("Populuate beatmap sets", () =>
{
manySets.Clear();
for (int i = 1; i <= 50; i++)
manySets.Add(TestResources.CreateTestBeatmapSetInfo(3));
});
loadBeatmaps(manySets);
@ -791,6 +832,8 @@ namespace osu.Game.Tests.Visual.SongSelect
AddStep("populate maps", () =>
{
manySets.Clear();
for (int i = 0; i < 10; i++)
{
manySets.Add(TestResources.CreateTestBeatmapSetInfo(3, new[]

View File

@ -47,7 +47,7 @@ namespace osu.Game.Tests.Visual.SongSelect
dependencies.Cache(rulesetStore = new RealmRulesetStore(Realm));
dependencies.Cache(beatmapManager = new BeatmapManager(LocalStorage, Realm, null, dependencies.Get<AudioManager>(), Resources, dependencies.Get<GameHost>(), Beatmap.Default));
dependencies.Cache(scoreManager = new ScoreManager(rulesetStore, () => beatmapManager, LocalStorage, Realm, Scheduler, API));
dependencies.Cache(scoreManager = new ScoreManager(rulesetStore, () => beatmapManager, LocalStorage, Realm, API));
Dependencies.Cache(Realm);
return dependencies;

View File

@ -6,15 +6,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics.Containers;
using osu.Framework.Platform;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Database;
@ -24,6 +27,7 @@ using osu.Game.Online.API.Requests.Responses;
using osu.Game.Online.Chat;
using osu.Game.Overlays;
using osu.Game.Overlays.Mods;
using osu.Game.Overlays.Notifications;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu;
@ -413,6 +417,55 @@ namespace osu.Game.Tests.Visual.SongSelect
AddUntilStep("no selection", () => songSelect.Carousel.SelectedBeatmapInfo == null);
}
[Test]
public void TestSelectionRetainedOnBeatmapUpdate()
{
createSongSelect();
changeRuleset(0);
Live<BeatmapSetInfo> original = null!;
int originalOnlineSetID = 0;
AddStep(@"Sort by artist", () => config.SetValue(OsuSetting.SongSelectSortingMode, SortMode.Artist));
AddStep("import original", () =>
{
original = manager.Import(new ImportTask(TestResources.GetQuickTestBeatmapForImport())).GetResultSafely();
originalOnlineSetID = original!.Value.OnlineID;
});
// This will move the beatmap set to a different location in the carousel.
AddStep("Update original with bogus info", () =>
{
original.PerformWrite(set =>
{
foreach (var beatmap in set.Beatmaps)
{
beatmap.Metadata.Artist = "ZZZZZ";
beatmap.OnlineID = 12804;
}
});
});
AddRepeatStep("import other beatmaps", () =>
{
var testBeatmapSetInfo = TestResources.CreateTestBeatmapSetInfo();
foreach (var beatmap in testBeatmapSetInfo.Beatmaps)
beatmap.Metadata.Artist = ((char)RNG.Next('A', 'Z')).ToString();
manager.Import(testBeatmapSetInfo);
}, 10);
AddUntilStep("has selection", () => songSelect.Carousel.SelectedBeatmapInfo?.BeatmapSet?.OnlineID == originalOnlineSetID);
Task<Live<BeatmapSetInfo>> updateTask = null!;
AddStep("update beatmap", () => updateTask = manager.ImportAsUpdate(new ProgressNotification(), new ImportTask(TestResources.GetQuickTestBeatmapForImport()), original.Value));
AddUntilStep("wait for update completion", () => updateTask.IsCompleted);
AddUntilStep("retained selection", () => songSelect.Carousel.SelectedBeatmapInfo?.BeatmapSet?.OnlineID == originalOnlineSetID);
}
[Test]
public void TestPresentNewRulesetNewBeatmap()
{

View File

@ -32,7 +32,7 @@ namespace osu.Game.Tests.Visual.SongSelect
{
Dependencies.Cache(rulesets = new RealmRulesetStore(Realm));
Dependencies.Cache(beatmapManager = new BeatmapManager(LocalStorage, Realm, null, audio, Resources, host, Beatmap.Default));
Dependencies.Cache(scoreManager = new ScoreManager(rulesets, () => beatmapManager, LocalStorage, Realm, Scheduler, API));
Dependencies.Cache(scoreManager = new ScoreManager(rulesets, () => beatmapManager, LocalStorage, Realm, API));
Dependencies.Cache(Realm);
beatmapManager.Import(TestResources.GetQuickTestBeatmapForImport()).WaitSafely();

View File

@ -73,7 +73,7 @@ namespace osu.Game.Tests.Visual.UserInterface
dependencies.Cache(new RealmRulesetStore(Realm));
dependencies.Cache(beatmapManager = new BeatmapManager(LocalStorage, Realm, null, dependencies.Get<AudioManager>(), Resources, dependencies.Get<GameHost>(), Beatmap.Default));
dependencies.Cache(scoreManager = new ScoreManager(dependencies.Get<RulesetStore>(), () => beatmapManager, LocalStorage, Realm, Scheduler, API));
dependencies.Cache(scoreManager = new ScoreManager(dependencies.Get<RulesetStore>(), () => beatmapManager, LocalStorage, Realm, API));
Dependencies.Cache(Realm);
return dependencies;

View File

@ -1,8 +1,6 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
@ -19,11 +17,11 @@ namespace osu.Game.Tests.Visual.UserInterface
[TestFixture]
public class TestSceneNotificationOverlay : OsuTestScene
{
private NotificationOverlay notificationOverlay;
private NotificationOverlay notificationOverlay = null!;
private readonly List<ProgressNotification> progressingNotifications = new List<ProgressNotification>();
private SpriteText displayedCount;
private SpriteText displayedCount = null!;
[SetUp]
public void SetUp() => Schedule(() =>
@ -46,7 +44,7 @@ namespace osu.Game.Tests.Visual.UserInterface
[Test]
public void TestCompleteProgress()
{
ProgressNotification notification = null;
ProgressNotification notification = null!;
AddStep("add progress notification", () =>
{
notification = new ProgressNotification
@ -64,7 +62,7 @@ namespace osu.Game.Tests.Visual.UserInterface
[Test]
public void TestCancelProgress()
{
ProgressNotification notification = null;
ProgressNotification notification = null!;
AddStep("add progress notification", () =>
{
notification = new ProgressNotification

View File

@ -5,7 +5,6 @@ using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Platform;
@ -39,8 +38,6 @@ namespace osu.Game.Tests.Visual.UserInterface
Dependencies.Cache(new RealmRulesetStore(Realm));
Dependencies.Cache(beatmapManager = new BeatmapManager(LocalStorage, Realm, null, Audio, Resources, host, Beatmap.Default));
Dependencies.Cache(Realm);
beatmapManager.Import(TestResources.GetQuickTestBeatmapForImport()).WaitSafely();
}
[SetUp]
@ -66,6 +63,9 @@ namespace osu.Game.Tests.Visual.UserInterface
}
beatmapSets.First().ToLive(Realm);
// Ensure all the initial imports are present before running any tests.
Realm.Run(r => r.Refresh());
});
[Test]
@ -138,7 +138,7 @@ namespace osu.Game.Tests.Visual.UserInterface
AddStep("Add collection", () =>
{
Dependencies.Get<RealmAccess>().Write(r =>
Realm.Write(r =>
{
r.RemoveAll<BeatmapCollection>();
r.Add(new BeatmapCollection("wang"));

View File

@ -55,7 +55,14 @@ namespace osu.Game.Beatmaps
// If there were no changes, ensure we don't accidentally nuke ourselves.
if (first.ID == original.ID)
{
first.PerformRead(s =>
{
// Re-run processing even in this case. We might have outdated metadata.
ProcessBeatmap?.Invoke((s, false));
});
return first;
}
first.PerformWrite(updated =>
{

View File

@ -0,0 +1,213 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using osu.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Timing;
using osu.Game.Configuration;
using osu.Game.Database;
using osu.Game.Screens.Play;
namespace osu.Game.Beatmaps
{
/// <summary>
/// A clock intended to be the single source-of-truth for beatmap timing.
///
/// It provides some functionality:
/// - Optionally applies (and tracks changes of) beatmap, user, and platform offsets (see ctor argument applyOffsets).
/// - Adjusts <see cref="Seek"/> operations to account for any applied offsets, seeking in raw "beatmap" time values.
/// - Exposes track length.
/// - Allows changing the source to a new track (for cases like editor track updating).
/// </summary>
public class FramedBeatmapClock : Component, IFrameBasedClock, IAdjustableClock, ISourceChangeableClock
{
private readonly bool applyOffsets;
/// <summary>
/// The length of the underlying beatmap track. Will default to 60 seconds if unavailable.
/// </summary>
public double TrackLength => Track.Length;
/// <summary>
/// The underlying beatmap track, if available.
/// </summary>
public Track Track { get; private set; } = new TrackVirtual(60000);
/// <summary>
/// The total frequency adjustment from pause transforms. Should eventually be handled in a better way.
/// </summary>
public readonly BindableDouble ExternalPauseFrequencyAdjust = new BindableDouble(1);
private readonly OffsetCorrectionClock? userGlobalOffsetClock;
private readonly OffsetCorrectionClock? platformOffsetClock;
private readonly OffsetCorrectionClock? userBeatmapOffsetClock;
private readonly IFrameBasedClock finalClockSource;
private Bindable<double>? userAudioOffset;
private IDisposable? beatmapOffsetSubscription;
private readonly DecoupleableInterpolatingFramedClock decoupledClock;
[Resolved]
private OsuConfigManager config { get; set; } = null!;
[Resolved]
private RealmAccess realm { get; set; } = null!;
[Resolved]
private IBindable<WorkingBeatmap> beatmap { get; set; } = null!;
public bool IsCoupled
{
get => decoupledClock.IsCoupled;
set => decoupledClock.IsCoupled = value;
}
public FramedBeatmapClock(bool applyOffsets = false)
{
this.applyOffsets = applyOffsets;
// A decoupled clock is used to ensure precise time values even when the host audio subsystem is not reporting
// high precision times (on windows there's generally only 5-10ms reporting intervals, as an example).
decoupledClock = new DecoupleableInterpolatingFramedClock { IsCoupled = true };
if (applyOffsets)
{
// Audio timings in general with newer BASS versions don't match stable.
// This only seems to be required on windows. We need to eventually figure out why, with a bit of luck.
platformOffsetClock = new OffsetCorrectionClock(decoupledClock, ExternalPauseFrequencyAdjust) { Offset = RuntimeInfo.OS == RuntimeInfo.Platform.Windows ? 15 : 0 };
// User global offset (set in settings) should also be applied.
userGlobalOffsetClock = new OffsetCorrectionClock(platformOffsetClock, ExternalPauseFrequencyAdjust);
// User per-beatmap offset will be applied to this final clock.
finalClockSource = userBeatmapOffsetClock = new OffsetCorrectionClock(userGlobalOffsetClock, ExternalPauseFrequencyAdjust);
}
else
{
finalClockSource = decoupledClock;
}
}
protected override void LoadComplete()
{
base.LoadComplete();
if (applyOffsets)
{
Debug.Assert(userBeatmapOffsetClock != null);
Debug.Assert(userGlobalOffsetClock != null);
userAudioOffset = config.GetBindable<double>(OsuSetting.AudioOffset);
userAudioOffset.BindValueChanged(offset => userGlobalOffsetClock.Offset = offset.NewValue, true);
beatmapOffsetSubscription = realm.SubscribeToPropertyChanged(
r => r.Find<BeatmapInfo>(beatmap.Value.BeatmapInfo.ID)?.UserSettings,
settings => settings.Offset,
val =>
{
userBeatmapOffsetClock.Offset = val;
});
}
}
protected override void Update()
{
base.Update();
finalClockSource.ProcessFrame();
}
public double TotalAppliedOffset
{
get
{
if (!applyOffsets)
return 0;
Debug.Assert(userGlobalOffsetClock != null);
Debug.Assert(userBeatmapOffsetClock != null);
Debug.Assert(platformOffsetClock != null);
return userGlobalOffsetClock.RateAdjustedOffset + userBeatmapOffsetClock.RateAdjustedOffset + platformOffsetClock.RateAdjustedOffset;
}
}
#region Delegation of IAdjustableClock / ISourceChangeableClock to decoupled clock.
public void ChangeSource(IClock? source)
{
Track = source as Track ?? new TrackVirtual(60000);
decoupledClock.ChangeSource(source);
}
public IClock? Source => decoupledClock.Source;
public void Reset()
{
decoupledClock.Reset();
finalClockSource.ProcessFrame();
}
public void Start()
{
decoupledClock.Start();
finalClockSource.ProcessFrame();
}
public void Stop()
{
decoupledClock.Stop();
finalClockSource.ProcessFrame();
}
public bool Seek(double position)
{
bool success = decoupledClock.Seek(position - TotalAppliedOffset);
finalClockSource.ProcessFrame();
return success;
}
public void ResetSpeedAdjustments() => decoupledClock.ResetSpeedAdjustments();
public double Rate
{
get => decoupledClock.Rate;
set => decoupledClock.Rate = value;
}
#endregion
#region Delegation of IFrameBasedClock to clock with all offsets applied
public double CurrentTime => finalClockSource.CurrentTime;
public bool IsRunning => finalClockSource.IsRunning;
public void ProcessFrame()
{
// Noop to ensure an external consumer doesn't process the internal clock an extra time.
}
public double ElapsedFrameTime => finalClockSource.ElapsedFrameTime;
public double FramesPerSecond => finalClockSource.FramesPerSecond;
public FrameTimeInfo TimeInfo => finalClockSource.TimeInfo;
#endregion
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
beatmapOffsetSubscription?.Dispose();
}
}
}

View File

@ -146,6 +146,7 @@ namespace osu.Game.Beatmaps
/// Get the loaded audio track instance. <see cref="LoadTrack"/> must have first been called.
/// This generally happens via MusicController when changing the global beatmap.
/// </summary>
[NotNull]
public Track Track
{
get

View File

@ -75,7 +75,14 @@ namespace osu.Game.Collections
// changes. It's not great but honestly the whole dropdown menu structure isn't great. This needs to be fixed, but I'll issue
// a warning that it's going to be a frustrating journey.
Current.Value = allBeatmaps;
Schedule(() => Current.Value = filters.SingleOrDefault(f => f.Collection != null && f.Collection.ID == selectedItem?.ID) ?? filters[0]);
Schedule(() =>
{
// current may have changed before the scheduled call is run.
if (Current.Value != allBeatmaps)
return;
Current.Value = filters.SingleOrDefault(f => f.Collection != null && f.Collection.ID == selectedItem?.ID) ?? filters[0];
});
// Trigger a re-filter if the current item was in the change set.
if (selectedItem != null && changes != null)

View File

@ -4,10 +4,8 @@
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using osu.Framework.Configuration;
using osu.Framework.Configuration.Tracking;
using osu.Framework.Extensions;
@ -31,6 +29,12 @@ namespace osu.Game.Configuration
[ExcludeFromDynamicCompile]
public class OsuConfigManager : IniConfigManager<OsuSetting>
{
public OsuConfigManager(Storage storage)
: base(storage)
{
Migrate();
}
protected override void InitialiseDefaults()
{
// UI/selection defaults
@ -172,12 +176,9 @@ namespace osu.Game.Configuration
SetDefault(OsuSetting.LastProcessedMetadataId, -1);
}
public IDictionary<OsuSetting, string> GetLoggableState() =>
new Dictionary<OsuSetting, string>(ConfigStore.Where(kvp => !keyContainsPrivateInformation(kvp.Key)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString()));
private static bool keyContainsPrivateInformation(OsuSetting argKey)
protected override bool CheckLookupContainsPrivateInformation(OsuSetting lookup)
{
switch (argKey)
switch (lookup)
{
case OsuSetting.Token:
return true;
@ -186,12 +187,6 @@ namespace osu.Game.Configuration
return false;
}
public OsuConfigManager(Storage storage)
: base(storage)
{
Migrate();
}
public void Migrate()
{
// arrives as 2020.123.0

View File

@ -1,8 +1,6 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Game.Overlays.Notifications;
namespace osu.Game.Database

View File

@ -20,6 +20,10 @@ namespace osu.Game.Database
protected override IEnumerable<string> GetStableImportPaths(Storage storage)
{
// make sure the directory exists
if (!storage.ExistsDirectory(string.Empty))
yield break;
foreach (string directory in storage.GetDirectories(string.Empty))
{
var directoryStorage = storage.GetStorageForDirectory(directory);

View File

@ -69,8 +69,9 @@ namespace osu.Game.Database
/// 21 2022-07-27 Migrate collections to realm (BeatmapCollection).
/// 22 2022-07-31 Added ModPreset.
/// 23 2022-08-01 Added LastLocalUpdate to BeatmapInfo.
/// 24 2022-08-22 Added MaximumStatistics to ScoreInfo.
/// </summary>
private const int schema_version = 23;
private const int schema_version = 24;
/// <summary>
/// Lock object which is held during <see cref="BlockAllOperations"/> sections, blocking realm retrieval during blocking periods.

View File

@ -46,8 +46,24 @@ namespace osu.Game.Graphics.UserInterface
private Sample? textCommittedSample;
private Sample? caretMovedSample;
private Sample? selectCharSample;
private Sample? selectWordSample;
private Sample? selectAllSample;
private Sample? deselectSample;
private OsuCaret? caret;
private bool selectionStarted;
private double sampleLastPlaybackTime;
private enum SelectionSampleType
{
Character,
Word,
All,
Deselect
}
public OsuTextBox()
{
Height = 40;
@ -78,6 +94,11 @@ namespace osu.Game.Graphics.UserInterface
textRemovedSample = audio.Samples.Get(@"Keyboard/key-delete");
textCommittedSample = audio.Samples.Get(@"Keyboard/key-confirm");
caretMovedSample = audio.Samples.Get(@"Keyboard/key-movement");
selectCharSample = audio.Samples.Get(@"Keyboard/select-char");
selectWordSample = audio.Samples.Get(@"Keyboard/select-word");
selectAllSample = audio.Samples.Get(@"Keyboard/select-all");
deselectSample = audio.Samples.Get(@"Keyboard/deselect");
}
private Color4 selectionColour;
@ -112,7 +133,41 @@ namespace osu.Game.Graphics.UserInterface
{
base.OnCaretMoved(selecting);
caretMovedSample?.Play();
if (!selecting)
caretMovedSample?.Play();
}
protected override void OnTextSelectionChanged(TextSelectionType selectionType)
{
base.OnTextSelectionChanged(selectionType);
switch (selectionType)
{
case TextSelectionType.Character:
playSelectSample(SelectionSampleType.Character);
break;
case TextSelectionType.Word:
playSelectSample(selectionStarted ? SelectionSampleType.Character : SelectionSampleType.Word);
break;
case TextSelectionType.All:
playSelectSample(SelectionSampleType.All);
break;
}
selectionStarted = true;
}
protected override void OnTextDeselected()
{
base.OnTextDeselected();
if (!selectionStarted) return;
playSelectSample(SelectionSampleType.Deselect);
selectionStarted = false;
}
protected override void OnImeComposition(string newComposition, int removedTextLength, int addedTextLength, bool caretMoved)
@ -204,6 +259,41 @@ namespace osu.Game.Graphics.UserInterface
SelectionColour = SelectionColour,
};
private void playSelectSample(SelectionSampleType selectionType)
{
if (Time.Current < sampleLastPlaybackTime + 15) return;
SampleChannel? channel;
double pitch = 0.98 + RNG.NextDouble(0.04);
switch (selectionType)
{
case SelectionSampleType.All:
channel = selectAllSample?.GetChannel();
break;
case SelectionSampleType.Word:
channel = selectWordSample?.GetChannel();
break;
case SelectionSampleType.Deselect:
channel = deselectSample?.GetChannel();
break;
default:
channel = selectCharSample?.GetChannel();
pitch += (SelectedText.Length / (double)Text.Length) * 0.15f;
break;
}
if (channel == null) return;
channel.Frequency.Value = pitch;
channel.Play();
sampleLastPlaybackTime = Time.Current;
}
private void playTextAddedSample() => textAddedSamples[RNG.Next(0, textAddedSamples.Length)]?.Play();
private class OsuCaret : Caret

View File

@ -74,6 +74,15 @@ namespace osu.Game.Online.API.Requests.Responses
[JsonProperty("statistics")]
public Dictionary<HitResult, int> Statistics { get; set; } = new Dictionary<HitResult, int>();
[JsonProperty("maximum_statistics")]
public Dictionary<HitResult, int> MaximumStatistics { get; set; } = new Dictionary<HitResult, int>();
/// <summary>
/// Used to preserve the total score for legacy scores.
/// </summary>
[JsonProperty("legacy_total_score")]
public int? LegacyTotalScore { get; set; }
#region osu-web API additions (not stored to database).
[JsonProperty("id")]
@ -153,6 +162,7 @@ namespace osu.Game.Online.API.Requests.Responses
MaxCombo = MaxCombo,
Rank = Rank,
Statistics = Statistics,
MaximumStatistics = MaximumStatistics,
Date = EndedAt,
Hash = HasReplay ? "online" : string.Empty, // TODO: temporary?
Mods = mods,
@ -174,6 +184,7 @@ namespace osu.Game.Online.API.Requests.Responses
Passed = score.Passed,
Mods = score.APIMods,
Statistics = score.Statistics.Where(kvp => kvp.Value != 0).ToDictionary(kvp => kvp.Key, kvp => kvp.Value),
MaximumStatistics = score.MaximumStatistics.Where(kvp => kvp.Value != 0).ToDictionary(kvp => kvp.Key, kvp => kvp.Value),
};
public long OnlineID => ID ?? -1;

View File

@ -1,27 +1,27 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Platform;
using osu.Game.Configuration;
using osu.Game.Overlays;
using osu.Game.Overlays.Chat;
using osu.Game.Overlays.Dialog;
namespace osu.Game.Online.Chat
{
public class ExternalLinkOpener : Component
{
[Resolved]
private GameHost host { get; set; }
private GameHost host { get; set; } = null!;
[Resolved(CanBeNull = true)]
private IDialogOverlay dialogOverlay { get; set; }
private IDialogOverlay? dialogOverlay { get; set; }
private Bindable<bool> externalLinkWarning;
private Bindable<bool> externalLinkWarning = null!;
[BackgroundDependencyLoader(true)]
private void load(OsuConfigManager config)
@ -31,10 +31,39 @@ namespace osu.Game.Online.Chat
public void OpenUrlExternally(string url, bool bypassWarning = false)
{
if (!bypassWarning && externalLinkWarning.Value)
dialogOverlay.Push(new ExternalLinkDialog(url, () => host.OpenUrlExternally(url)));
if (!bypassWarning && externalLinkWarning.Value && dialogOverlay != null)
dialogOverlay.Push(new ExternalLinkDialog(url, () => host.OpenUrlExternally(url), () => host.GetClipboard()?.SetText(url)));
else
host.OpenUrlExternally(url);
}
public class ExternalLinkDialog : PopupDialog
{
public ExternalLinkDialog(string url, Action openExternalLinkAction, Action copyExternalLinkAction)
{
HeaderText = "Just checking...";
BodyText = $"You are about to leave osu! and open the following link in a web browser:\n\n{url}";
Icon = FontAwesome.Solid.ExclamationTriangle;
Buttons = new PopupDialogButton[]
{
new PopupDialogOkButton
{
Text = @"Yes. Go for it.",
Action = openExternalLinkAction
},
new PopupDialogCancelButton
{
Text = @"Copy URL to the clipboard instead.",
Action = copyExternalLinkAction
},
new PopupDialogCancelButton
{
Text = @"No! Abort mission!"
},
};
}
}
}
}

View File

@ -65,11 +65,12 @@ namespace osu.Game.Online.Spectator
public virtual event Action<int, SpectatorState>? OnUserFinishedPlaying;
/// <summary>
/// All users currently being watched.
/// A dictionary containing all users currently being watched, with the number of watching components for each user.
/// </summary>
private readonly List<int> watchedUsers = new List<int>();
private readonly Dictionary<int, int> watchedUsersRefCounts = new Dictionary<int, int>();
private readonly BindableDictionary<int, SpectatorState> watchedUserStates = new BindableDictionary<int, SpectatorState>();
private readonly BindableList<int> playingUsers = new BindableList<int>();
private readonly SpectatorState currentState = new SpectatorState();
@ -94,12 +95,15 @@ namespace osu.Game.Online.Spectator
if (connected.NewValue)
{
// get all the users that were previously being watched
int[] users = watchedUsers.ToArray();
watchedUsers.Clear();
var users = new Dictionary<int, int>(watchedUsersRefCounts);
watchedUsersRefCounts.Clear();
// resubscribe to watched users.
foreach (int userId in users)
WatchUser(userId);
foreach ((int user, int watchers) in users)
{
for (int i = 0; i < watchers; i++)
WatchUser(user);
}
// re-send state in case it wasn't received
if (IsPlaying)
@ -121,7 +125,7 @@ namespace osu.Game.Online.Spectator
if (!playingUsers.Contains(userId))
playingUsers.Add(userId);
if (watchedUsers.Contains(userId))
if (watchedUsersRefCounts.ContainsKey(userId))
watchedUserStates[userId] = state;
OnUserBeganPlaying?.Invoke(userId, state);
@ -136,7 +140,7 @@ namespace osu.Game.Online.Spectator
{
playingUsers.Remove(userId);
if (watchedUsers.Contains(userId))
if (watchedUsersRefCounts.ContainsKey(userId))
watchedUserStates[userId] = state;
OnUserFinishedPlaying?.Invoke(userId, state);
@ -232,11 +236,13 @@ namespace osu.Game.Online.Spectator
{
Debug.Assert(ThreadSafety.IsUpdateThread);
if (watchedUsers.Contains(userId))
if (watchedUsersRefCounts.ContainsKey(userId))
{
watchedUsersRefCounts[userId]++;
return;
}
watchedUsers.Add(userId);
watchedUsersRefCounts.Add(userId, 1);
WatchUserInternal(userId);
}
@ -246,7 +252,13 @@ namespace osu.Game.Online.Spectator
// Todo: This should not be a thing, but requires framework changes.
Schedule(() =>
{
watchedUsers.Remove(userId);
if (watchedUsersRefCounts.TryGetValue(userId, out int watchers) && watchers > 1)
{
watchedUsersRefCounts[userId]--;
return;
}
watchedUsersRefCounts.Remove(userId);
watchedUserStates.Remove(userId);
StopWatchingUserInternal(userId);
});

View File

@ -185,6 +185,12 @@ namespace osu.Game
private RealmAccess realm;
/// <summary>
/// For now, this is used as a source specifically for beat synced components.
/// Going forward, it could potentially be used as the single source-of-truth for beatmap timing.
/// </summary>
private readonly FramedBeatmapClock beatmapClock = new FramedBeatmapClock(true);
protected override Container<Drawable> Content => content;
private Container content;
@ -273,7 +279,7 @@ namespace osu.Game
dependencies.Cache(difficultyCache = new BeatmapDifficultyCache());
// ordering is important here to ensure foreign keys rules are not broken in ModelStore.Cleanup()
dependencies.Cache(ScoreManager = new ScoreManager(RulesetStore, () => BeatmapManager, Storage, realm, Scheduler, API, difficultyCache, LocalConfig));
dependencies.Cache(ScoreManager = new ScoreManager(RulesetStore, () => BeatmapManager, Storage, realm, API, LocalConfig));
dependencies.Cache(BeatmapManager = new BeatmapManager(Storage, realm, API, Audio, Resources, Host, defaultBeatmap, difficultyCache, performOnlineLookups: true));
@ -368,10 +374,24 @@ namespace osu.Game
AddInternal(MusicController = new MusicController());
dependencies.CacheAs(MusicController);
MusicController.TrackChanged += onTrackChanged;
AddInternal(beatmapClock);
Ruleset.BindValueChanged(onRulesetChanged);
Beatmap.BindValueChanged(onBeatmapChanged);
}
private void onTrackChanged(WorkingBeatmap beatmap, TrackChangeDirection direction)
{
// FramedBeatmapClock uses a decoupled clock internally which will mutate the source if it is an `IAdjustableClock`.
// We don't want this for now, as the intention of beatmapClock is to be a read-only source for beat sync components.
//
// Encapsulating in a FramedClock will avoid any mutations.
var framedClock = new FramedClock(beatmap.Track);
beatmapClock.ChangeSource(framedClock);
}
protected virtual void InitialiseFonts()
{
AddFont(Resources, @"Fonts/osuFont");
@ -587,7 +607,7 @@ namespace osu.Game
}
ControlPointInfo IBeatSyncProvider.ControlPoints => Beatmap.Value.BeatmapLoaded ? Beatmap.Value.Beatmap.ControlPointInfo : null;
IClock IBeatSyncProvider.Clock => Beatmap.Value.TrackLoaded ? Beatmap.Value.Track : (IClock)null;
IClock IBeatSyncProvider.Clock => beatmapClock;
ChannelAmplitudes IHasAmplitudes.CurrentAmplitudes => Beatmap.Value.TrackLoaded ? Beatmap.Value.Track.CurrentAmplitudes : ChannelAmplitudes.Empty;
}
}

View File

@ -6,10 +6,8 @@
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
@ -87,27 +85,19 @@ namespace osu.Game.Overlays.BeatmapSet.Scores
MD5Hash = apiBeatmap.MD5Hash
};
scoreManager.OrderByTotalScoreAsync(value.Scores.Select(s => s.ToScoreInfo(rulesets, beatmapInfo)).ToArray(), loadCancellationSource.Token)
.ContinueWith(task => Schedule(() =>
{
if (loadCancellationSource.IsCancellationRequested)
return;
var scores = scoreManager.OrderByTotalScore(value.Scores.Select(s => s.ToScoreInfo(rulesets, beatmapInfo))).ToArray();
var topScore = scores.First();
var scores = task.GetResultSafely();
scoreTable.DisplayScores(scores, apiBeatmap.Status.GrantsPerformancePoints());
scoreTable.Show();
var topScore = scores.First();
var userScore = value.UserScore;
var userScoreInfo = userScore?.Score.ToScoreInfo(rulesets, beatmapInfo);
scoreTable.DisplayScores(scores, apiBeatmap.Status.GrantsPerformancePoints());
scoreTable.Show();
topScoresContainer.Add(new DrawableTopScore(topScore));
var userScore = value.UserScore;
var userScoreInfo = userScore?.Score.ToScoreInfo(rulesets, beatmapInfo);
topScoresContainer.Add(new DrawableTopScore(topScore));
if (userScoreInfo != null && userScoreInfo.OnlineID != topScore.OnlineID)
topScoresContainer.Add(new DrawableTopScore(userScoreInfo, userScore.Position));
}), TaskContinuationOptions.OnlyOnRanToCompletion);
if (userScoreInfo != null && userScoreInfo.OnlineID != topScore.OnlineID)
topScoresContainer.Add(new DrawableTopScore(userScoreInfo, userScore.Position));
});
}

View File

@ -1,35 +0,0 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using osu.Framework.Graphics.Sprites;
using osu.Game.Overlays.Dialog;
namespace osu.Game.Overlays.Chat
{
public class ExternalLinkDialog : PopupDialog
{
public ExternalLinkDialog(string url, Action openExternalLinkAction)
{
HeaderText = "Just checking...";
BodyText = $"You are about to leave osu! and open the following link in a web browser:\n\n{url}";
Icon = FontAwesome.Solid.ExclamationTriangle;
Buttons = new PopupDialogButton[]
{
new PopupDialogOkButton
{
Text = @"Yes. Go for it.",
Action = openExternalLinkAction
},
new PopupDialogCancelButton
{
Text = @"No! Abort mission!"
},
};
}
}
}

View File

@ -27,6 +27,12 @@ namespace osu.Game.Overlays.Music
set => base.Padding = value;
}
protected override void OnItemsChanged()
{
base.OnItemsChanged();
Filter(currentCriteria);
}
public void Filter(FilterCriteria criteria)
{
var items = (SearchContainer<RearrangeableListItem<Live<BeatmapSetInfo>>>)ListContainer;
@ -44,12 +50,12 @@ namespace osu.Game.Overlays.Music
public Live<BeatmapSetInfo>? FirstVisibleSet => Items.FirstOrDefault(i => ((PlaylistItem)ItemMap[i]).MatchingFilter);
protected override OsuRearrangeableListItem<Live<BeatmapSetInfo>> CreateOsuDrawable(Live<BeatmapSetInfo> item) => new PlaylistItem(item)
{
InSelectedCollection = currentCriteria.Collection?.PerformRead(c => item.Value.Beatmaps.Select(b => b.MD5Hash).Any(c.BeatmapMD5Hashes.Contains)) != false,
SelectedSet = { BindTarget = SelectedSet },
RequestSelection = set => RequestSelection?.Invoke(set)
};
protected override OsuRearrangeableListItem<Live<BeatmapSetInfo>> CreateOsuDrawable(Live<BeatmapSetInfo> item) =>
new PlaylistItem(item)
{
SelectedSet = { BindTarget = SelectedSet },
RequestSelection = set => RequestSelection?.Invoke(set)
};
protected override FillFlowContainer<RearrangeableListItem<Live<BeatmapSetInfo>>> CreateListFillFlowContainer() => new SearchContainer<RearrangeableListItem<Live<BeatmapSetInfo>>>
{

View File

@ -64,14 +64,8 @@ namespace osu.Game.Overlays
RelativeSizeAxes = Axes.X,
Children = new[]
{
new NotificationSection(AccountsStrings.NotificationsTitle, "Clear All")
{
AcceptTypes = new[] { typeof(SimpleNotification) }
},
new NotificationSection(@"Running Tasks", @"Cancel All")
{
AcceptTypes = new[] { typeof(ProgressNotification) }
}
new NotificationSection(AccountsStrings.NotificationsTitle, new[] { typeof(SimpleNotification) }, "Clear All"),
new NotificationSection(@"Running Tasks", new[] { typeof(ProgressNotification) }, @"Cancel All"),
}
}
}
@ -133,7 +127,7 @@ namespace osu.Game.Overlays
var ourType = notification.GetType();
var section = sections.Children.FirstOrDefault(s => s.AcceptTypes.Any(accept => accept.IsAssignableFrom(ourType)));
var section = sections.Children.FirstOrDefault(s => s.AcceptedNotificationTypes.Any(accept => accept.IsAssignableFrom(ourType)));
section?.Add(notification, notification.DisplayOnTop ? -runningDepth : runningDepth);
if (notification.IsImportant)

View File

@ -1,8 +1,6 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
@ -26,7 +24,7 @@ namespace osu.Game.Overlays.Notifications
/// <summary>
/// User requested close.
/// </summary>
public event Action Closed;
public event Action? Closed;
public abstract LocalisableString Text { get; set; }
@ -38,7 +36,7 @@ namespace osu.Game.Overlays.Notifications
/// <summary>
/// Run on user activating the notification. Return true to close.
/// </summary>
public Func<bool> Activated;
public Func<bool>? Activated;
/// <summary>
/// Should we show at the top of our section on display?
@ -212,7 +210,7 @@ namespace osu.Game.Overlays.Notifications
public class NotificationLight : Container
{
private bool pulsate;
private Container pulsateLayer;
private Container pulsateLayer = null!;
public bool Pulsate
{

View File

@ -1,8 +1,6 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
@ -21,9 +19,9 @@ namespace osu.Game.Overlays.Notifications
{
public class NotificationSection : AlwaysUpdateFillFlowContainer<Drawable>
{
private OsuSpriteText countDrawable;
private OsuSpriteText countDrawable = null!;
private FlowContainer<Notification> notifications;
private FlowContainer<Notification> notifications = null!;
public int DisplayedCount => notifications.Count(n => !n.WasClosed);
public int UnreadCount => notifications.Count(n => !n.WasClosed && !n.Read);
@ -33,14 +31,16 @@ namespace osu.Game.Overlays.Notifications
notifications.Insert((int)position, notification);
}
public IEnumerable<Type> AcceptTypes;
public IEnumerable<Type> AcceptedNotificationTypes { get; }
private readonly string clearButtonText;
private readonly LocalisableString titleText;
public NotificationSection(LocalisableString title, string clearButtonText)
public NotificationSection(LocalisableString title, IEnumerable<Type> acceptedNotificationTypes, string clearButtonText)
{
AcceptedNotificationTypes = acceptedNotificationTypes.ToArray();
this.clearButtonText = clearButtonText.ToUpperInvariant();
titleText = title;
}
@ -159,7 +159,7 @@ namespace osu.Game.Overlays.Notifications
public void MarkAllRead()
{
notifications?.Children.ForEach(n => n.Read = true);
notifications.Children.ForEach(n => n.Read = true);
}
}

View File

@ -1,8 +1,6 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Threading;
using osu.Framework.Allocation;
@ -25,6 +23,18 @@ namespace osu.Game.Overlays.Notifications
{
private const float loading_spinner_size = 22;
public Func<bool>? CancelRequested { get; set; }
/// <summary>
/// The function to post completion notifications back to.
/// </summary>
public Action<Notification>? CompletionTarget { get; set; }
/// <summary>
/// An action to complete when the completion notification is clicked. Return true to close.
/// </summary>
public Func<bool>? CompletionClickAction { get; set; }
private LocalisableString text;
public override LocalisableString Text
@ -142,7 +152,7 @@ namespace osu.Game.Overlays.Notifications
Text = CompletionText
};
protected virtual void Completed()
protected void Completed()
{
CompletionTarget?.Invoke(CreateCompletionNotification());
base.Close();
@ -155,8 +165,8 @@ namespace osu.Game.Overlays.Notifications
private Color4 colourActive;
private Color4 colourCancelled;
private Box iconBackground;
private LoadingSpinner loadingSpinner;
private Box iconBackground = null!;
private LoadingSpinner loadingSpinner = null!;
private readonly TextFlowContainer textDrawable;
@ -222,18 +232,6 @@ namespace osu.Game.Overlays.Notifications
}
}
public Func<bool> CancelRequested { get; set; }
/// <summary>
/// The function to post completion notifications back to.
/// </summary>
public Action<Notification> CompletionTarget { get; set; }
/// <summary>
/// An action to complete when the completion notification is clicked. Return true to close.
/// </summary>
public Func<bool> CompletionClickAction;
private class ProgressBar : Container
{
private readonly Box box;

View File

@ -1,8 +1,6 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;

View File

@ -3,6 +3,7 @@
#nullable disable
using System.Diagnostics;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
@ -37,6 +38,10 @@ namespace osu.Game.Overlays.Profile
// todo: pending implementation.
// TabControl.AddItem(LayoutStrings.HeaderUsersModding);
// Haphazardly guaranteed by OverlayHeader constructor (see CreateBackground / CreateContent).
Debug.Assert(centreHeaderContainer != null);
Debug.Assert(detailHeaderContainer != null);
centreHeaderContainer.DetailsVisible.BindValueChanged(visible => detailHeaderContainer.Expanded = visible.NewValue, true);
}

View File

@ -66,7 +66,7 @@ namespace osu.Game.Rulesets.Difficulty
// calculate total score
ScoreProcessor scoreProcessor = ruleset.CreateScoreProcessor();
scoreProcessor.Mods.Value = perfectPlay.Mods;
perfectPlay.TotalScore = (long)scoreProcessor.ComputeFinalScore(ScoringMode.Standardised, perfectPlay);
perfectPlay.TotalScore = (long)scoreProcessor.ComputeScore(ScoringMode.Standardised, perfectPlay);
// compute rank achieved
// default to SS, then adjust the rank with mods

View File

@ -77,9 +77,16 @@ namespace osu.Game.Rulesets
continue;
}
var instanceInfo = (Activator.CreateInstance(resolvedType) as Ruleset)?.RulesetInfo
var instance = (Activator.CreateInstance(resolvedType) as Ruleset);
var instanceInfo = instance?.RulesetInfo
?? throw new RulesetLoadException(@"Instantiation failure");
if (!checkRulesetUpToDate(instance))
{
throw new ArgumentOutOfRangeException(nameof(instance.RulesetAPIVersionSupported),
$"Ruleset API version is too old (was {instance.RulesetAPIVersionSupported}, expected {Ruleset.CURRENT_RULESET_API_VERSION})");
}
// If a ruleset isn't up-to-date with the API, it could cause a crash at an arbitrary point of execution.
// To eagerly handle cases of missing implementations, enumerate all types here and mark as non-available on throw.
resolvedType.Assembly.GetTypes();
@ -104,6 +111,23 @@ namespace osu.Game.Rulesets
});
}
private bool checkRulesetUpToDate(Ruleset instance)
{
switch (instance.RulesetAPIVersionSupported)
{
// The default `virtual` implementation leaves the version string empty.
// Consider rulesets which haven't override the version as up-to-date for now.
// At some point (once ruleset devs add versioning), we'll probably want to disallow this for deployed builds.
case @"":
// Ruleset is up-to-date, all good.
case Ruleset.CURRENT_RULESET_API_VERSION:
return true;
default:
return false;
}
}
private void testRulesetCompatibility(RulesetInfo rulesetInfo)
{
// do various operations to ensure that we are in a good state.

View File

@ -7,33 +7,33 @@ using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Extensions;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Bindings;
using osu.Framework.IO.Stores;
using osu.Game.Beatmaps;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Rulesets.UI;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Skinning;
using osu.Game.Users;
using JetBrains.Annotations;
using osu.Framework.Extensions;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Localisation;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Configuration;
using osu.Game.Extensions;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Filter;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
using osu.Game.Scoring;
using osu.Game.Screens.Edit.Setup;
using osu.Game.Screens.Ranking.Statistics;
using osu.Game.Skinning;
using osu.Game.Users;
namespace osu.Game.Rulesets
{
@ -44,6 +44,24 @@ namespace osu.Game.Rulesets
private static readonly ConcurrentDictionary<string, IMod[]> mod_reference_cache = new ConcurrentDictionary<string, IMod[]>();
/// <summary>
/// Version history:
/// 2022.205.0 FramedReplayInputHandler.CollectPendingInputs renamed to FramedReplayHandler.CollectReplayInputs.
/// 2022.822.0 All strings return values have been converted to LocalisableString to allow for localisation support.
/// </summary>
public const string CURRENT_RULESET_API_VERSION = "2022.822.0";
/// <summary>
/// Define the ruleset API version supported by this ruleset.
/// Ruleset implementations should be updated to support the latest version to ensure they can still be loaded.
/// </summary>
/// <remarks>
/// Generally, all ruleset implementations should point this directly to <see cref="CURRENT_RULESET_API_VERSION"/>.
/// This will ensure that each time you compile a new release, it will pull in the most recent version.
/// See https://github.com/ppy/osu/wiki/Breaking-Changes for full details on required ongoing changes.
/// </remarks>
public virtual string RulesetAPIVersionSupported => string.Empty;
/// <summary>
/// A queryable source containing all available mods.
/// Call <see cref="IMod.CreateInstance"/> for consumption purposes.

View File

@ -119,8 +119,20 @@ namespace osu.Game.Rulesets.Scoring
[EnumMember(Value = "ignore_hit")]
[Order(12)]
IgnoreHit,
/// <summary>
/// A special result used as a padding value for legacy rulesets. It is a hit type and affects combo, but does not affect the base score (does not affect accuracy).
/// </summary>
/// <remarks>
/// DO NOT USE.
/// </remarks>
[EnumMember(Value = "legacy_combo_increase")]
[Order(99)]
[Obsolete("Do not use.")]
LegacyComboIncrease = 99
}
#pragma warning disable CS0618
public static class HitResultExtensions
{
/// <summary>
@ -150,6 +162,7 @@ namespace osu.Game.Rulesets.Scoring
case HitResult.Perfect:
case HitResult.LargeTickHit:
case HitResult.LargeTickMiss:
case HitResult.LegacyComboIncrease:
return true;
default:
@ -161,13 +174,25 @@ namespace osu.Game.Rulesets.Scoring
/// Whether a <see cref="HitResult"/> affects the accuracy portion of the score.
/// </summary>
public static bool AffectsAccuracy(this HitResult result)
=> IsScorable(result) && !IsBonus(result);
{
// LegacyComboIncrease is a special type which is neither a basic, tick, bonus, or accuracy-affecting result.
if (result == HitResult.LegacyComboIncrease)
return false;
return IsScorable(result) && !IsBonus(result);
}
/// <summary>
/// Whether a <see cref="HitResult"/> is a non-tick and non-bonus result.
/// </summary>
public static bool IsBasic(this HitResult result)
=> IsScorable(result) && !IsTick(result) && !IsBonus(result);
{
// LegacyComboIncrease is a special type which is neither a basic, tick, bonus, or accuracy-affecting result.
if (result == HitResult.LegacyComboIncrease)
return false;
return IsScorable(result) && !IsTick(result) && !IsBonus(result);
}
/// <summary>
/// Whether a <see cref="HitResult"/> should be counted as a tick.
@ -225,12 +250,19 @@ namespace osu.Game.Rulesets.Scoring
/// <summary>
/// Whether a <see cref="HitResult"/> is scorable.
/// </summary>
public static bool IsScorable(this HitResult result) => result >= HitResult.Miss && result < HitResult.IgnoreMiss;
public static bool IsScorable(this HitResult result)
{
// LegacyComboIncrease is not actually scorable (in terms of usable by rulesets for that purpose), but needs to be defined as such to be correctly included in statistics output.
if (result == HitResult.LegacyComboIncrease)
return true;
return result >= HitResult.Miss && result < HitResult.IgnoreMiss;
}
/// <summary>
/// An array of all scorable <see cref="HitResult"/>s.
/// </summary>
public static readonly HitResult[] ALL_TYPES = ((HitResult[])Enum.GetValues(typeof(HitResult))).ToArray();
public static readonly HitResult[] ALL_TYPES = ((HitResult[])Enum.GetValues(typeof(HitResult))).Except(new[] { HitResult.LegacyComboIncrease }).ToArray();
/// <summary>
/// Whether a <see cref="HitResult"/> is valid within a given <see cref="HitResult"/> range.
@ -251,4 +283,5 @@ namespace osu.Game.Rulesets.Scoring
return result > minResult && result < maxResult;
}
}
#pragma warning restore CS0618
}

View File

@ -61,6 +61,11 @@ namespace osu.Game.Rulesets.Scoring
/// <param name="result">The <see cref="JudgementResult"/> to apply.</param>
public void ApplyResult(JudgementResult result)
{
#pragma warning disable CS0618
if (result.Type == HitResult.LegacyComboIncrease)
throw new ArgumentException(@$"A {nameof(HitResult.LegacyComboIncrease)} hit result cannot be applied.");
#pragma warning restore CS0618
JudgedHits++;
lastAppliedResult = result;

View File

@ -121,15 +121,14 @@ namespace osu.Game.Rulesets.Scoring
/// <summary>
/// The maximum <see cref="HitResult"/> of a basic (non-tick and non-bonus) hitobject.
/// Only populated via <see cref="ComputeFinalScore"/> or <see cref="ResetFromReplayFrame"/>.
/// Only populated via <see cref="ComputeScore(osu.Game.Rulesets.Scoring.ScoringMode,osu.Game.Scoring.ScoreInfo)"/> or <see cref="ResetFromReplayFrame"/>.
/// </summary>
private HitResult? maxBasicResult;
private bool beatmapApplied;
private readonly Dictionary<HitResult, int> scoreResultCounts = new Dictionary<HitResult, int>();
private Dictionary<HitResult, int>? maximumResultCounts;
private readonly Dictionary<HitResult, int> maximumResultCounts = new Dictionary<HitResult, int>();
private readonly List<HitEvent> hitEvents = new List<HitEvent>();
private HitObject? lastHitObject;
@ -282,7 +281,7 @@ namespace osu.Game.Rulesets.Scoring
/// <param name="scoreInfo">The <see cref="ScoreInfo"/> to compute the total score of.</param>
/// <returns>The total score in the given <see cref="ScoringMode"/>.</returns>
[Pure]
public double ComputeFinalScore(ScoringMode mode, ScoreInfo scoreInfo)
public double ComputeScore(ScoringMode mode, ScoreInfo scoreInfo)
{
if (!ruleset.RulesetInfo.Equals(scoreInfo.Ruleset))
throw new ArgumentException($"Unexpected score ruleset. Expected \"{ruleset.RulesetInfo.ShortName}\" but was \"{scoreInfo.Ruleset.ShortName}\".");
@ -292,60 +291,6 @@ namespace osu.Game.Rulesets.Scoring
return ComputeScore(mode, current, maximum);
}
/// <summary>
/// Computes the total score of a partially-completed <see cref="ScoreInfo"/>. This should be used when it is unknown whether a score is complete.
/// </summary>
/// <remarks>
/// Requires <see cref="JudgementProcessor.ApplyBeatmap"/> to have been called before use.
/// </remarks>
/// <param name="mode">The <see cref="ScoringMode"/> to represent the score as.</param>
/// <param name="scoreInfo">The <see cref="ScoreInfo"/> to compute the total score of.</param>
/// <returns>The total score in the given <see cref="ScoringMode"/>.</returns>
[Pure]
public double ComputePartialScore(ScoringMode mode, ScoreInfo scoreInfo)
{
if (!ruleset.RulesetInfo.Equals(scoreInfo.Ruleset))
throw new ArgumentException($"Unexpected score ruleset. Expected \"{ruleset.RulesetInfo.ShortName}\" but was \"{scoreInfo.Ruleset.ShortName}\".");
if (!beatmapApplied)
throw new InvalidOperationException($"Cannot compute partial score without calling {nameof(ApplyBeatmap)}.");
ExtractScoringValues(scoreInfo, out var current, out _);
return ComputeScore(mode, current, MaximumScoringValues);
}
/// <summary>
/// Computes the total score of a given <see cref="ScoreInfo"/> with a given custom max achievable combo.
/// </summary>
/// <remarks>
/// This is useful for processing legacy scores in which the maximum achievable combo can be more accurately determined via external means (e.g. database values or difficulty calculation).
/// <p>Does not require <see cref="JudgementProcessor.ApplyBeatmap"/> to have been called before use.</p>
/// </remarks>
/// <param name="mode">The <see cref="ScoringMode"/> to represent the score as.</param>
/// <param name="scoreInfo">The <see cref="ScoreInfo"/> to compute the total score of.</param>
/// <param name="maxAchievableCombo">The maximum achievable combo for the provided beatmap.</param>
/// <returns>The total score in the given <see cref="ScoringMode"/>.</returns>
[Pure]
public double ComputeFinalLegacyScore(ScoringMode mode, ScoreInfo scoreInfo, int maxAchievableCombo)
{
if (!ruleset.RulesetInfo.Equals(scoreInfo.Ruleset))
throw new ArgumentException($"Unexpected score ruleset. Expected \"{ruleset.RulesetInfo.ShortName}\" but was \"{scoreInfo.Ruleset.ShortName}\".");
double accuracyRatio = scoreInfo.Accuracy;
double comboRatio = maxAchievableCombo > 0 ? (double)scoreInfo.MaxCombo / maxAchievableCombo : 1;
ExtractScoringValues(scoreInfo, out var current, out var maximum);
// For legacy osu!mania scores, a full-GREAT score has 100% accuracy. If combined with a full-combo, the score becomes indistinguishable from a full-PERFECT score.
// To get around this, the accuracy ratio is always recalculated based on the hit statistics rather than trusting the score.
// Note: This cannot be applied universally to all legacy scores, as some rulesets (e.g. catch) group multiple judgements together.
if (scoreInfo.IsLegacyScore && scoreInfo.Ruleset.OnlineID == 3 && maximum.BaseScore > 0)
accuracyRatio = current.BaseScore / maximum.BaseScore;
return ComputeScore(mode, accuracyRatio, comboRatio, current.BonusScore, maximum.CountBasicHitObjects);
}
/// <summary>
/// Computes the total score from scoring values.
/// </summary>
@ -405,8 +350,6 @@ namespace osu.Game.Rulesets.Scoring
return ScoreRank.D;
}
public int GetStatistic(HitResult result) => scoreResultCounts.GetValueOrDefault(result);
/// <summary>
/// Resets this ScoreProcessor to a default state.
/// </summary>
@ -421,7 +364,9 @@ namespace osu.Game.Rulesets.Scoring
if (storeResults)
{
maximumScoringValues = currentScoringValues;
maximumResultCounts = new Dictionary<HitResult, int>(scoreResultCounts);
maximumResultCounts.Clear();
maximumResultCounts.AddRange(scoreResultCounts);
}
scoreResultCounts.Clear();
@ -449,14 +394,17 @@ namespace osu.Game.Rulesets.Scoring
score.HitEvents = hitEvents;
foreach (var result in HitResultExtensions.ALL_TYPES)
score.Statistics[result] = GetStatistic(result);
score.Statistics[result] = scoreResultCounts.GetValueOrDefault(result);
foreach (var result in HitResultExtensions.ALL_TYPES)
score.MaximumStatistics[result] = maximumResultCounts.GetValueOrDefault(result);
// Populate total score after everything else.
score.TotalScore = (long)Math.Round(ComputeFinalScore(ScoringMode.Standardised, score));
score.TotalScore = (long)Math.Round(ComputeScore(ScoringMode.Standardised, score));
}
/// <summary>
/// Populates the given score with remaining statistics as "missed" and marks it with <see cref="ScoreRank.F"/> rank.
/// Populates a failed score, marking it with the <see cref="ScoreRank.F"/> rank.
/// </summary>
public void FailScore(ScoreInfo score)
{
@ -466,22 +414,6 @@ namespace osu.Game.Rulesets.Scoring
score.Passed = false;
Rank.Value = ScoreRank.F;
Debug.Assert(maximumResultCounts != null);
if (maximumResultCounts.TryGetValue(HitResult.LargeTickHit, out int maximumLargeTick))
scoreResultCounts[HitResult.LargeTickMiss] = maximumLargeTick - scoreResultCounts.GetValueOrDefault(HitResult.LargeTickHit);
if (maximumResultCounts.TryGetValue(HitResult.SmallTickHit, out int maximumSmallTick))
scoreResultCounts[HitResult.SmallTickMiss] = maximumSmallTick - scoreResultCounts.GetValueOrDefault(HitResult.SmallTickHit);
int maximumBonusOrIgnore = maximumResultCounts.Where(kvp => kvp.Key.IsBonus() || kvp.Key == HitResult.IgnoreHit).Sum(kvp => kvp.Value);
int currentBonusOrIgnore = scoreResultCounts.Where(kvp => kvp.Key.IsBonus() || kvp.Key == HitResult.IgnoreHit).Sum(kvp => kvp.Value);
scoreResultCounts[HitResult.IgnoreMiss] = maximumBonusOrIgnore - currentBonusOrIgnore;
int maximumBasic = maximumResultCounts.SingleOrDefault(kvp => kvp.Key.IsBasic()).Value;
int currentBasic = scoreResultCounts.Where(kvp => kvp.Key.IsBasic() && kvp.Key != HitResult.Miss).Sum(kvp => kvp.Value);
scoreResultCounts[HitResult.Miss] = maximumBasic - currentBasic;
PopulateScore(score);
}
@ -534,6 +466,9 @@ namespace osu.Game.Rulesets.Scoring
{
extractScoringValues(scoreInfo.Statistics, out current, out maximum);
current.MaxCombo = scoreInfo.MaxCombo;
if (scoreInfo.MaximumStatistics.Count > 0)
extractScoringValues(scoreInfo.MaximumStatistics, out _, out maximum);
}
/// <summary>
@ -589,7 +524,8 @@ namespace osu.Game.Rulesets.Scoring
if (result.IsBonus())
current.BonusScore += count * Judgement.ToNumericResult(result);
else
if (result.AffectsAccuracy())
{
// The maximum result of this judgement if it wasn't a miss.
// E.g. For a GOOD judgement, the max result is either GREAT/PERFECT depending on which one the ruleset uses (osu!: GREAT, osu!mania: PERFECT).

View File

@ -281,7 +281,7 @@ namespace osu.Game.Rulesets.UI
}
}
public double? StartTime => parentGameplayClock?.StartTime;
public double StartTime => parentGameplayClock?.StartTime ?? 0;
public IEnumerable<double> NonGameplayAdjustments => parentGameplayClock?.NonGameplayAdjustments ?? Enumerable.Empty<double>();

Some files were not shown because too many files have changed in this diff Show More