mirror of
https://github.com/ppy/osu.git
synced 2024-12-14 08:52:55 +08:00
Merge branch 'master' into autoplay-rate-independence
This commit is contained in:
commit
1cb51fa8d2
@ -25,7 +25,7 @@ using osuTK;
|
||||
|
||||
namespace osu.Game.Rulesets.Osu.Tests
|
||||
{
|
||||
public class TestSceneOutOfOrderHits : RateAdjustedBeatmapTestScene
|
||||
public class TestSceneStartTimeOrderedHitPolicy : RateAdjustedBeatmapTestScene
|
||||
{
|
||||
private const double early_miss_window = 1000; // time after -1000 to -500 is considered a miss
|
||||
private const double late_miss_window = 500; // time after +500 is considered a miss
|
||||
@ -169,7 +169,7 @@ namespace osu.Game.Rulesets.Osu.Tests
|
||||
addJudgementAssert(hitObjects[0], HitResult.Great);
|
||||
addJudgementAssert(hitObjects[1], HitResult.Great);
|
||||
addJudgementOffsetAssert(hitObjects[0], -200); // time_first_circle - 200
|
||||
addJudgementOffsetAssert(hitObjects[0], -200); // time_second_circle - first_circle_time - 100
|
||||
addJudgementOffsetAssert(hitObjects[1], -200); // time_second_circle - first_circle_time - 100
|
||||
}
|
||||
|
||||
/// <summary>
|
31
osu.Game.Rulesets.Osu/UI/IHitPolicy.cs
Normal file
31
osu.Game.Rulesets.Osu/UI/IHitPolicy.cs
Normal file
@ -0,0 +1,31 @@
|
||||
// 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.Objects;
|
||||
using osu.Game.Rulesets.Objects.Drawables;
|
||||
using osu.Game.Rulesets.UI;
|
||||
|
||||
namespace osu.Game.Rulesets.Osu.UI
|
||||
{
|
||||
public interface IHitPolicy
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="IHitObjectContainer"/> containing the <see cref="DrawableHitObject"/>s which this <see cref="IHitPolicy"/> applies to.
|
||||
/// </summary>
|
||||
IHitObjectContainer HitObjectContainer { set; }
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether a <see cref="DrawableHitObject"/> can be hit at a point in time.
|
||||
/// </summary>
|
||||
/// <param name="hitObject">The <see cref="DrawableHitObject"/> to check.</param>
|
||||
/// <param name="time">The time to check.</param>
|
||||
/// <returns>Whether <paramref name="hitObject"/> can be hit at the given <paramref name="time"/>.</returns>
|
||||
bool IsHittable(DrawableHitObject hitObject, double time);
|
||||
|
||||
/// <summary>
|
||||
/// Handles a <see cref="HitObject"/> being hit.
|
||||
/// </summary>
|
||||
/// <param name="hitObject">The <see cref="HitObject"/> that was hit.</param>
|
||||
void HandleHit(DrawableHitObject hitObject);
|
||||
}
|
||||
}
|
@ -31,7 +31,7 @@ namespace osu.Game.Rulesets.Osu.UI
|
||||
private readonly ProxyContainer spinnerProxies;
|
||||
private readonly JudgementContainer<DrawableOsuJudgement> judgementLayer;
|
||||
private readonly FollowPointRenderer followPoints;
|
||||
private readonly OrderedHitPolicy hitPolicy;
|
||||
private readonly StartTimeOrderedHitPolicy hitPolicy;
|
||||
|
||||
public static readonly Vector2 BASE_SIZE = new Vector2(512, 384);
|
||||
|
||||
@ -54,7 +54,7 @@ namespace osu.Game.Rulesets.Osu.UI
|
||||
approachCircles = new ProxyContainer { RelativeSizeAxes = Axes.Both },
|
||||
};
|
||||
|
||||
hitPolicy = new OrderedHitPolicy(HitObjectContainer);
|
||||
hitPolicy = new StartTimeOrderedHitPolicy { HitObjectContainer = HitObjectContainer };
|
||||
|
||||
var hitWindows = new OsuHitWindows();
|
||||
|
||||
|
@ -11,28 +11,17 @@ using osu.Game.Rulesets.UI;
|
||||
namespace osu.Game.Rulesets.Osu.UI
|
||||
{
|
||||
/// <summary>
|
||||
/// Ensures that <see cref="HitObject"/>s are hit in-order. Affectionately known as "note lock".
|
||||
/// Ensures that <see cref="HitObject"/>s are hit in-order of their start times. Affectionately known as "note lock".
|
||||
/// If a <see cref="HitObject"/> is hit out of order:
|
||||
/// <list type="number">
|
||||
/// <item><description>The hit is blocked if it occurred earlier than the previous <see cref="HitObject"/>'s start time.</description></item>
|
||||
/// <item><description>The hit causes all previous <see cref="HitObject"/>s to missed otherwise.</description></item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public class OrderedHitPolicy
|
||||
public class StartTimeOrderedHitPolicy : IHitPolicy
|
||||
{
|
||||
private readonly HitObjectContainer hitObjectContainer;
|
||||
public IHitObjectContainer HitObjectContainer { get; set; }
|
||||
|
||||
public OrderedHitPolicy(HitObjectContainer hitObjectContainer)
|
||||
{
|
||||
this.hitObjectContainer = hitObjectContainer;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether a <see cref="DrawableHitObject"/> can be hit at a point in time.
|
||||
/// </summary>
|
||||
/// <param name="hitObject">The <see cref="DrawableHitObject"/> to check.</param>
|
||||
/// <param name="time">The time to check.</param>
|
||||
/// <returns>Whether <paramref name="hitObject"/> can be hit at the given <paramref name="time"/>.</returns>
|
||||
public bool IsHittable(DrawableHitObject hitObject, double time)
|
||||
{
|
||||
DrawableHitObject blockingObject = null;
|
||||
@ -54,10 +43,6 @@ namespace osu.Game.Rulesets.Osu.UI
|
||||
return blockingObject.Judged || time >= blockingObject.HitObject.StartTime;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles a <see cref="HitObject"/> being hit to potentially miss all earlier <see cref="HitObject"/>s.
|
||||
/// </summary>
|
||||
/// <param name="hitObject">The <see cref="HitObject"/> that was hit.</param>
|
||||
public void HandleHit(DrawableHitObject hitObject)
|
||||
{
|
||||
// Hitobjects which themselves don't block future hitobjects don't cause misses (e.g. slider ticks, spinners).
|
||||
@ -67,6 +52,7 @@ namespace osu.Game.Rulesets.Osu.UI
|
||||
if (!IsHittable(hitObject, hitObject.HitObject.StartTime + hitObject.Result.TimeOffset))
|
||||
throw new InvalidOperationException($"A {hitObject} was hit before it became hittable!");
|
||||
|
||||
// Miss all hitobjects prior to the hit one.
|
||||
foreach (var obj in enumerateHitObjectsUpTo(hitObject.HitObject.StartTime))
|
||||
{
|
||||
if (obj.Judged)
|
||||
@ -86,7 +72,7 @@ namespace osu.Game.Rulesets.Osu.UI
|
||||
|
||||
private IEnumerable<DrawableHitObject> enumerateHitObjectsUpTo(double targetTime)
|
||||
{
|
||||
foreach (var obj in hitObjectContainer.AliveObjects)
|
||||
foreach (var obj in HitObjectContainer.AliveObjects)
|
||||
{
|
||||
if (obj.HitObject.StartTime >= targetTime)
|
||||
yield break;
|
111
osu.Game.Tests/NonVisual/TaskChainTest.cs
Normal file
111
osu.Game.Tests/NonVisual/TaskChainTest.cs
Normal file
@ -0,0 +1,111 @@
|
||||
// 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.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using NUnit.Framework;
|
||||
using osu.Game.Utils;
|
||||
|
||||
namespace osu.Game.Tests.NonVisual
|
||||
{
|
||||
[TestFixture]
|
||||
public class TaskChainTest
|
||||
{
|
||||
private TaskChain taskChain;
|
||||
private int currentTask;
|
||||
private CancellationTokenSource globalCancellationToken;
|
||||
|
||||
[SetUp]
|
||||
public void Setup()
|
||||
{
|
||||
globalCancellationToken = new CancellationTokenSource();
|
||||
taskChain = new TaskChain();
|
||||
currentTask = 0;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
globalCancellationToken?.Cancel();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestChainedTasksRunSequentially()
|
||||
{
|
||||
var task1 = addTask();
|
||||
var task2 = addTask();
|
||||
var task3 = addTask();
|
||||
|
||||
task3.mutex.Set();
|
||||
task2.mutex.Set();
|
||||
task1.mutex.Set();
|
||||
|
||||
await Task.WhenAll(task1.task, task2.task, task3.task);
|
||||
|
||||
Assert.That(task1.task.Result, Is.EqualTo(1));
|
||||
Assert.That(task2.task.Result, Is.EqualTo(2));
|
||||
Assert.That(task3.task.Result, Is.EqualTo(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestChainedTaskWithIntermediateCancelRunsInSequence()
|
||||
{
|
||||
var task1 = addTask();
|
||||
var task2 = addTask();
|
||||
var task3 = addTask();
|
||||
|
||||
// Cancel task2, allow task3 to complete.
|
||||
task2.cancellation.Cancel();
|
||||
task2.mutex.Set();
|
||||
task3.mutex.Set();
|
||||
|
||||
// Allow task3 to potentially complete.
|
||||
Thread.Sleep(1000);
|
||||
|
||||
// Allow task1 to complete.
|
||||
task1.mutex.Set();
|
||||
|
||||
// Wait on both tasks.
|
||||
await Task.WhenAll(task1.task, task3.task);
|
||||
|
||||
Assert.That(task1.task.Result, Is.EqualTo(1));
|
||||
Assert.That(task2.task.IsCompleted, Is.False);
|
||||
Assert.That(task3.task.Result, Is.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TestChainedTaskDoesNotCompleteBeforeChildTasks()
|
||||
{
|
||||
var mutex = new ManualResetEventSlim(false);
|
||||
|
||||
var task = taskChain.Add(async () => await Task.Run(() => mutex.Wait(globalCancellationToken.Token)));
|
||||
|
||||
// Allow task to potentially complete
|
||||
Thread.Sleep(1000);
|
||||
|
||||
Assert.That(task.IsCompleted, Is.False);
|
||||
|
||||
// Allow the task to complete.
|
||||
mutex.Set();
|
||||
|
||||
await task;
|
||||
}
|
||||
|
||||
private (Task<int> task, ManualResetEventSlim mutex, CancellationTokenSource cancellation) addTask()
|
||||
{
|
||||
var mutex = new ManualResetEventSlim(false);
|
||||
var completionSource = new TaskCompletionSource<int>();
|
||||
|
||||
var cancellationSource = new CancellationTokenSource();
|
||||
var token = CancellationTokenSource.CreateLinkedTokenSource(cancellationSource.Token, globalCancellationToken.Token);
|
||||
|
||||
taskChain.Add(() =>
|
||||
{
|
||||
mutex.Wait(globalCancellationToken.Token);
|
||||
completionSource.SetResult(Interlocked.Increment(ref currentTask));
|
||||
}, token.Token);
|
||||
|
||||
return (completionSource.Task, mutex, cancellationSource);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
// 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;
|
||||
using osu.Framework.Testing;
|
||||
using osu.Game.Rulesets.Objects.Types;
|
||||
using osu.Game.Rulesets.Osu.Objects;
|
||||
using osu.Game.Screens.Edit.Compose.Components.Timeline;
|
||||
using osuTK;
|
||||
using osuTK.Input;
|
||||
using static osu.Game.Screens.Edit.Compose.Components.Timeline.TimelineHitObjectBlueprint;
|
||||
|
||||
namespace osu.Game.Tests.Visual.Editing
|
||||
{
|
||||
public class TestSceneTimelineHitObjectBlueprint : TimelineTestScene
|
||||
{
|
||||
public override Drawable CreateTestComponent() => new TimelineBlueprintContainer(Composer);
|
||||
|
||||
[Test]
|
||||
public void TestDisallowZeroDurationObjects()
|
||||
{
|
||||
DragBar dragBar;
|
||||
|
||||
AddStep("add spinner", () =>
|
||||
{
|
||||
EditorBeatmap.Clear();
|
||||
EditorBeatmap.Add(new Spinner
|
||||
{
|
||||
Position = new Vector2(256, 256),
|
||||
StartTime = 150,
|
||||
Duration = 500
|
||||
});
|
||||
});
|
||||
|
||||
AddStep("hold down drag bar", () =>
|
||||
{
|
||||
// distinguishes between the actual drag bar and its "underlay shadow".
|
||||
dragBar = this.ChildrenOfType<DragBar>().Single(bar => bar.HandlePositionalInput);
|
||||
InputManager.MoveMouseTo(dragBar);
|
||||
InputManager.PressButton(MouseButton.Left);
|
||||
});
|
||||
|
||||
AddStep("try to drag bar past start", () =>
|
||||
{
|
||||
var blueprint = this.ChildrenOfType<TimelineHitObjectBlueprint>().Single();
|
||||
InputManager.MoveMouseTo(blueprint.SelectionQuad.TopLeft - new Vector2(100, 0));
|
||||
InputManager.ReleaseButton(MouseButton.Left);
|
||||
});
|
||||
|
||||
AddAssert("object has non-zero duration", () => EditorBeatmap.HitObjects.OfType<IHasDuration>().Single().Duration > 0);
|
||||
}
|
||||
}
|
||||
}
|
@ -23,22 +23,24 @@ namespace osu.Game.Tests.Visual.Editing
|
||||
|
||||
protected HitObjectComposer Composer { get; private set; }
|
||||
|
||||
protected EditorBeatmap EditorBeatmap { get; private set; }
|
||||
|
||||
[BackgroundDependencyLoader]
|
||||
private void load(AudioManager audio)
|
||||
{
|
||||
Beatmap.Value = new WaveformTestBeatmap(audio);
|
||||
|
||||
var playable = Beatmap.Value.GetPlayableBeatmap(Beatmap.Value.BeatmapInfo.Ruleset);
|
||||
var editorBeatmap = new EditorBeatmap(playable);
|
||||
EditorBeatmap = new EditorBeatmap(playable);
|
||||
|
||||
Dependencies.Cache(editorBeatmap);
|
||||
Dependencies.CacheAs<IBeatSnapProvider>(editorBeatmap);
|
||||
Dependencies.Cache(EditorBeatmap);
|
||||
Dependencies.CacheAs<IBeatSnapProvider>(EditorBeatmap);
|
||||
|
||||
Composer = playable.BeatmapInfo.Ruleset.CreateInstance().CreateHitObjectComposer().With(d => d.Alpha = 0);
|
||||
|
||||
AddRange(new Drawable[]
|
||||
{
|
||||
editorBeatmap,
|
||||
EditorBeatmap,
|
||||
Composer,
|
||||
new FillFlowContainer
|
||||
{
|
||||
|
@ -101,7 +101,7 @@ namespace osu.Game.Tests.Visual.Multiplayer
|
||||
});
|
||||
});
|
||||
|
||||
AddAssert("multiplayer room joined", () => roomContainer.Client.Room != null);
|
||||
AddUntilStep("multiplayer room joined", () => roomContainer.Client.Room != null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@ -133,7 +133,7 @@ namespace osu.Game.Tests.Visual.Multiplayer
|
||||
});
|
||||
});
|
||||
|
||||
AddAssert("multiplayer room joined", () => roomContainer.Client.Room != null);
|
||||
AddUntilStep("multiplayer room joined", () => roomContainer.Client.Room != null);
|
||||
}
|
||||
|
||||
private TestMultiplayerRoomManager createRoomManager()
|
||||
|
@ -143,6 +143,7 @@ namespace osu.Game.Tests.Visual.Multiplayer
|
||||
/// Tests that the same <see cref="Mod"/> instances are not shared between two playlist items.
|
||||
/// </summary>
|
||||
[Test]
|
||||
[Ignore("Temporarily disabled due to a non-trivial test failure")]
|
||||
public void TestNewItemHasNewModInstances()
|
||||
{
|
||||
AddStep("set dt mod", () => SelectedMods.Value = new[] { new OsuModDoubleTime() });
|
||||
|
@ -1,6 +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.
|
||||
|
||||
using System;
|
||||
using osu.Game.Beatmaps.Timing;
|
||||
using osu.Game.Rulesets.Objects;
|
||||
using System.Collections.Generic;
|
||||
@ -48,6 +49,31 @@ namespace osu.Game.Beatmaps
|
||||
|
||||
public virtual IEnumerable<BeatmapStatistic> GetStatistics() => Enumerable.Empty<BeatmapStatistic>();
|
||||
|
||||
public double GetMostCommonBeatLength()
|
||||
{
|
||||
// The last playable time in the beatmap - the last timing point extends to this time.
|
||||
// Note: This is more accurate and may present different results because osu-stable didn't have the ability to calculate slider durations in this context.
|
||||
double lastTime = HitObjects.LastOrDefault()?.GetEndTime() ?? ControlPointInfo.TimingPoints.LastOrDefault()?.Time ?? 0;
|
||||
|
||||
var mostCommon =
|
||||
// Construct a set of (beatLength, duration) tuples for each individual timing point.
|
||||
ControlPointInfo.TimingPoints.Select((t, i) =>
|
||||
{
|
||||
if (t.Time > lastTime)
|
||||
return (beatLength: t.BeatLength, 0);
|
||||
|
||||
var nextTime = i == ControlPointInfo.TimingPoints.Count - 1 ? lastTime : ControlPointInfo.TimingPoints[i + 1].Time;
|
||||
return (beatLength: t.BeatLength, duration: nextTime - t.Time);
|
||||
})
|
||||
// Aggregate durations into a set of (beatLength, duration) tuples for each beat length
|
||||
.GroupBy(t => Math.Round(t.beatLength * 1000) / 1000)
|
||||
.Select(g => (beatLength: g.Key, duration: g.Sum(t => t.duration)))
|
||||
// Get the most common one, or 0 as a suitable default
|
||||
.OrderByDescending(i => i.duration).FirstOrDefault();
|
||||
|
||||
return mostCommon.beatLength;
|
||||
}
|
||||
|
||||
IBeatmap IBeatmap.Clone() => Clone();
|
||||
|
||||
public Beatmap<T> Clone() => (Beatmap<T>)MemberwiseClone();
|
||||
|
@ -451,7 +451,7 @@ namespace osu.Game.Beatmaps
|
||||
// TODO: this should be done in a better place once we actually need to dynamically update it.
|
||||
beatmap.BeatmapInfo.StarDifficulty = ruleset?.CreateInstance().CreateDifficultyCalculator(new DummyConversionBeatmap(beatmap)).Calculate().StarRating ?? 0;
|
||||
beatmap.BeatmapInfo.Length = calculateLength(beatmap);
|
||||
beatmap.BeatmapInfo.BPM = beatmap.ControlPointInfo.BPMMode;
|
||||
beatmap.BeatmapInfo.BPM = 60000 / beatmap.GetMostCommonBeatLength();
|
||||
|
||||
beatmapInfos.Add(beatmap.BeatmapInfo);
|
||||
}
|
||||
|
@ -101,13 +101,6 @@ namespace osu.Game.Beatmaps.ControlPoints
|
||||
public double BPMMinimum =>
|
||||
60000 / (TimingPoints.OrderByDescending(c => c.BeatLength).FirstOrDefault() ?? TimingControlPoint.DEFAULT).BeatLength;
|
||||
|
||||
/// <summary>
|
||||
/// Finds the mode BPM (most common BPM) represented by the control points.
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public double BPMMode =>
|
||||
60000 / (TimingPoints.GroupBy(c => c.BeatLength).OrderByDescending(grp => grp.Count()).FirstOrDefault()?.FirstOrDefault() ?? TimingControlPoint.DEFAULT).BeatLength;
|
||||
|
||||
/// <summary>
|
||||
/// Remove all <see cref="ControlPointGroup"/>s and return to a pristine state.
|
||||
/// </summary>
|
||||
|
@ -47,6 +47,11 @@ namespace osu.Game.Beatmaps
|
||||
/// <returns></returns>
|
||||
IEnumerable<BeatmapStatistic> GetStatistics();
|
||||
|
||||
/// <summary>
|
||||
/// Finds the most common beat length represented by the control points in this beatmap.
|
||||
/// </summary>
|
||||
double GetMostCommonBeatLength();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a shallow-clone of this beatmap and returns it.
|
||||
/// </summary>
|
||||
|
68
osu.Game/Extensions/TaskExtensions.cs
Normal file
68
osu.Game/Extensions/TaskExtensions.cs
Normal file
@ -0,0 +1,68 @@
|
||||
// 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 enable
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace osu.Game.Extensions
|
||||
{
|
||||
public static class TaskExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Add a continuation to be performed only after the attached task has completed.
|
||||
/// </summary>
|
||||
/// <param name="task">The previous task to be awaited on.</param>
|
||||
/// <param name="action">The action to run.</param>
|
||||
/// <param name="cancellationToken">An optional cancellation token. Will only cancel the provided action, not the sequence.</param>
|
||||
/// <returns>A task representing the provided action.</returns>
|
||||
public static Task ContinueWithSequential(this Task task, Action action, CancellationToken cancellationToken = default) =>
|
||||
task.ContinueWithSequential(() => Task.Run(action, cancellationToken), cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Add a continuation to be performed only after the attached task has completed.
|
||||
/// </summary>
|
||||
/// <param name="task">The previous task to be awaited on.</param>
|
||||
/// <param name="continuationFunction">The continuation to run. Generally should be an async function.</param>
|
||||
/// <param name="cancellationToken">An optional cancellation token. Will only cancel the provided action, not the sequence.</param>
|
||||
/// <returns>A task representing the provided action.</returns>
|
||||
public static Task ContinueWithSequential(this Task task, Func<Task> continuationFunction, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var tcs = new TaskCompletionSource<bool>();
|
||||
|
||||
task.ContinueWith(t =>
|
||||
{
|
||||
// the previous task has finished execution or been cancelled, so we can run the provided continuation.
|
||||
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
tcs.SetCanceled();
|
||||
}
|
||||
else
|
||||
{
|
||||
continuationFunction().ContinueWith(continuationTask =>
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested || continuationTask.IsCanceled)
|
||||
{
|
||||
tcs.TrySetCanceled();
|
||||
}
|
||||
else if (continuationTask.IsFaulted)
|
||||
{
|
||||
tcs.TrySetException(continuationTask.Exception);
|
||||
}
|
||||
else
|
||||
{
|
||||
tcs.TrySetResult(true);
|
||||
}
|
||||
}, cancellationToken: default);
|
||||
}
|
||||
}, cancellationToken: default);
|
||||
|
||||
// importantly, we are not returning the continuation itself but rather a task which represents its status in sequential execution order.
|
||||
// this will not be cancelled or completed until the previous task has also.
|
||||
return tcs.Task;
|
||||
}
|
||||
}
|
||||
}
|
@ -5,7 +5,6 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
@ -27,11 +26,15 @@ namespace osu.Game.Online.Multiplayer
|
||||
private readonly Bindable<bool> isConnected = new Bindable<bool>();
|
||||
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
|
||||
|
||||
private readonly SemaphoreSlim connectionLock = new SemaphoreSlim(1);
|
||||
|
||||
[Resolved]
|
||||
private IAPIProvider api { get; set; } = null!;
|
||||
|
||||
private HubConnection? connection;
|
||||
|
||||
private CancellationTokenSource connectCancelSource = new CancellationTokenSource();
|
||||
|
||||
private readonly string endpoint;
|
||||
|
||||
public MultiplayerClient(EndpointConfiguration endpoints)
|
||||
@ -52,87 +55,67 @@ namespace osu.Game.Online.Multiplayer
|
||||
{
|
||||
case APIState.Failing:
|
||||
case APIState.Offline:
|
||||
connection?.StopAsync();
|
||||
connection = null;
|
||||
Task.Run(() => disconnect(true));
|
||||
break;
|
||||
|
||||
case APIState.Online:
|
||||
Task.Run(Connect);
|
||||
Task.Run(connect);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual async Task Connect()
|
||||
private async Task connect()
|
||||
{
|
||||
if (connection != null)
|
||||
return;
|
||||
cancelExistingConnect();
|
||||
|
||||
var builder = new HubConnectionBuilder()
|
||||
.WithUrl(endpoint, options => { options.Headers.Add("Authorization", $"Bearer {api.AccessToken}"); });
|
||||
if (!await connectionLock.WaitAsync(10000))
|
||||
throw new TimeoutException("Could not obtain a lock to connect. A previous attempt is likely stuck.");
|
||||
|
||||
if (RuntimeInfo.SupportsJIT)
|
||||
builder.AddMessagePackProtocol();
|
||||
else
|
||||
try
|
||||
{
|
||||
// eventually we will precompile resolvers for messagepack, but this isn't working currently
|
||||
// see https://github.com/neuecc/MessagePack-CSharp/issues/780#issuecomment-768794308.
|
||||
builder.AddNewtonsoftJsonProtocol(options => { options.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; });
|
||||
}
|
||||
|
||||
connection = builder.Build();
|
||||
|
||||
// this is kind of SILLY
|
||||
// https://github.com/dotnet/aspnetcore/issues/15198
|
||||
connection.On<MultiplayerRoomState>(nameof(IMultiplayerClient.RoomStateChanged), ((IMultiplayerClient)this).RoomStateChanged);
|
||||
connection.On<MultiplayerRoomUser>(nameof(IMultiplayerClient.UserJoined), ((IMultiplayerClient)this).UserJoined);
|
||||
connection.On<MultiplayerRoomUser>(nameof(IMultiplayerClient.UserLeft), ((IMultiplayerClient)this).UserLeft);
|
||||
connection.On<int>(nameof(IMultiplayerClient.HostChanged), ((IMultiplayerClient)this).HostChanged);
|
||||
connection.On<MultiplayerRoomSettings>(nameof(IMultiplayerClient.SettingsChanged), ((IMultiplayerClient)this).SettingsChanged);
|
||||
connection.On<int, MultiplayerUserState>(nameof(IMultiplayerClient.UserStateChanged), ((IMultiplayerClient)this).UserStateChanged);
|
||||
connection.On(nameof(IMultiplayerClient.LoadRequested), ((IMultiplayerClient)this).LoadRequested);
|
||||
connection.On(nameof(IMultiplayerClient.MatchStarted), ((IMultiplayerClient)this).MatchStarted);
|
||||
connection.On(nameof(IMultiplayerClient.ResultsReady), ((IMultiplayerClient)this).ResultsReady);
|
||||
connection.On<int, IEnumerable<APIMod>>(nameof(IMultiplayerClient.UserModsChanged), ((IMultiplayerClient)this).UserModsChanged);
|
||||
|
||||
connection.Closed += async ex =>
|
||||
{
|
||||
isConnected.Value = false;
|
||||
|
||||
Logger.Log(ex != null
|
||||
? $"Multiplayer client lost connection: {ex}"
|
||||
: "Multiplayer client disconnected", LoggingTarget.Network);
|
||||
|
||||
if (connection != null)
|
||||
await tryUntilConnected();
|
||||
};
|
||||
|
||||
await tryUntilConnected();
|
||||
|
||||
async Task tryUntilConnected()
|
||||
{
|
||||
Logger.Log("Multiplayer client connecting...", LoggingTarget.Network);
|
||||
|
||||
while (api.State.Value == APIState.Online)
|
||||
{
|
||||
// ensure any previous connection was disposed.
|
||||
// this will also create a new cancellation token source.
|
||||
await disconnect(false);
|
||||
|
||||
// this token will be valid for the scope of this connection.
|
||||
// if cancelled, we can be sure that a disconnect or reconnect is handled elsewhere.
|
||||
var cancellationToken = connectCancelSource.Token;
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
Logger.Log("Multiplayer client connecting...", LoggingTarget.Network);
|
||||
|
||||
try
|
||||
{
|
||||
Debug.Assert(connection != null);
|
||||
// importantly, rebuild the connection each attempt to get an updated access token.
|
||||
connection = createConnection(cancellationToken);
|
||||
|
||||
await connection.StartAsync(cancellationToken);
|
||||
|
||||
// reconnect on any failure
|
||||
await connection.StartAsync();
|
||||
Logger.Log("Multiplayer client connected!", LoggingTarget.Network);
|
||||
|
||||
// Success.
|
||||
isConnected.Value = true;
|
||||
break;
|
||||
return;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
//connection process was cancelled.
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Log($"Multiplayer client connection error: {e}", LoggingTarget.Network);
|
||||
await Task.Delay(5000);
|
||||
|
||||
// retry on any failure.
|
||||
await Task.Delay(5000, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
connectionLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
protected override Task<MultiplayerRoom> JoinRoom(long roomId)
|
||||
@ -143,20 +126,12 @@ namespace osu.Game.Online.Multiplayer
|
||||
return connection.InvokeAsync<MultiplayerRoom>(nameof(IMultiplayerServer.JoinRoom), roomId);
|
||||
}
|
||||
|
||||
public override async Task LeaveRoom()
|
||||
protected override Task LeaveRoomInternal()
|
||||
{
|
||||
if (!isConnected.Value)
|
||||
{
|
||||
// even if not connected, make sure the local room state can be cleaned up.
|
||||
await base.LeaveRoom();
|
||||
return;
|
||||
}
|
||||
return Task.FromCanceled(new CancellationToken(true));
|
||||
|
||||
if (Room == null)
|
||||
return;
|
||||
|
||||
await base.LeaveRoom();
|
||||
await connection.InvokeAsync(nameof(IMultiplayerServer.LeaveRoom));
|
||||
return connection.InvokeAsync(nameof(IMultiplayerServer.LeaveRoom));
|
||||
}
|
||||
|
||||
public override Task TransferHost(int userId)
|
||||
@ -206,5 +181,85 @@ namespace osu.Game.Online.Multiplayer
|
||||
|
||||
return connection.InvokeAsync(nameof(IMultiplayerServer.StartMatch));
|
||||
}
|
||||
|
||||
private async Task disconnect(bool takeLock)
|
||||
{
|
||||
cancelExistingConnect();
|
||||
|
||||
if (takeLock)
|
||||
{
|
||||
if (!await connectionLock.WaitAsync(10000))
|
||||
throw new TimeoutException("Could not obtain a lock to disconnect. A previous attempt is likely stuck.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (connection != null)
|
||||
await connection.DisposeAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
connection = null;
|
||||
if (takeLock)
|
||||
connectionLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelExistingConnect()
|
||||
{
|
||||
connectCancelSource.Cancel();
|
||||
connectCancelSource = new CancellationTokenSource();
|
||||
}
|
||||
|
||||
private HubConnection createConnection(CancellationToken cancellationToken)
|
||||
{
|
||||
var builder = new HubConnectionBuilder()
|
||||
.WithUrl(endpoint, options => { options.Headers.Add("Authorization", $"Bearer {api.AccessToken}"); });
|
||||
|
||||
if (RuntimeInfo.SupportsJIT)
|
||||
builder.AddMessagePackProtocol();
|
||||
else
|
||||
{
|
||||
// eventually we will precompile resolvers for messagepack, but this isn't working currently
|
||||
// see https://github.com/neuecc/MessagePack-CSharp/issues/780#issuecomment-768794308.
|
||||
builder.AddNewtonsoftJsonProtocol(options => { options.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; });
|
||||
}
|
||||
|
||||
var newConnection = builder.Build();
|
||||
|
||||
// this is kind of SILLY
|
||||
// https://github.com/dotnet/aspnetcore/issues/15198
|
||||
newConnection.On<MultiplayerRoomState>(nameof(IMultiplayerClient.RoomStateChanged), ((IMultiplayerClient)this).RoomStateChanged);
|
||||
newConnection.On<MultiplayerRoomUser>(nameof(IMultiplayerClient.UserJoined), ((IMultiplayerClient)this).UserJoined);
|
||||
newConnection.On<MultiplayerRoomUser>(nameof(IMultiplayerClient.UserLeft), ((IMultiplayerClient)this).UserLeft);
|
||||
newConnection.On<int>(nameof(IMultiplayerClient.HostChanged), ((IMultiplayerClient)this).HostChanged);
|
||||
newConnection.On<MultiplayerRoomSettings>(nameof(IMultiplayerClient.SettingsChanged), ((IMultiplayerClient)this).SettingsChanged);
|
||||
newConnection.On<int, MultiplayerUserState>(nameof(IMultiplayerClient.UserStateChanged), ((IMultiplayerClient)this).UserStateChanged);
|
||||
newConnection.On(nameof(IMultiplayerClient.LoadRequested), ((IMultiplayerClient)this).LoadRequested);
|
||||
newConnection.On(nameof(IMultiplayerClient.MatchStarted), ((IMultiplayerClient)this).MatchStarted);
|
||||
newConnection.On(nameof(IMultiplayerClient.ResultsReady), ((IMultiplayerClient)this).ResultsReady);
|
||||
newConnection.On<int, IEnumerable<APIMod>>(nameof(IMultiplayerClient.UserModsChanged), ((IMultiplayerClient)this).UserModsChanged);
|
||||
|
||||
newConnection.Closed += ex =>
|
||||
{
|
||||
isConnected.Value = false;
|
||||
|
||||
Logger.Log(ex != null ? $"Multiplayer client lost connection: {ex}" : "Multiplayer client disconnected", LoggingTarget.Network);
|
||||
|
||||
// make sure a disconnect wasn't triggered (and this is still the active connection).
|
||||
if (!cancellationToken.IsCancellationRequested)
|
||||
Task.Run(connect, default);
|
||||
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
return newConnection;
|
||||
}
|
||||
|
||||
protected override void Dispose(bool isDisposing)
|
||||
{
|
||||
base.Dispose(isDisposing);
|
||||
|
||||
cancelExistingConnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -7,6 +7,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using osu.Framework.Allocation;
|
||||
using osu.Framework.Bindables;
|
||||
@ -109,30 +110,43 @@ namespace osu.Game.Online.Multiplayer
|
||||
});
|
||||
}
|
||||
|
||||
private readonly TaskChain joinOrLeaveTaskChain = new TaskChain();
|
||||
private CancellationTokenSource? joinCancellationSource;
|
||||
|
||||
/// <summary>
|
||||
/// Joins the <see cref="MultiplayerRoom"/> for a given API <see cref="Room"/>.
|
||||
/// </summary>
|
||||
/// <param name="room">The API <see cref="Room"/>.</param>
|
||||
public async Task JoinRoom(Room room)
|
||||
{
|
||||
if (Room != null)
|
||||
throw new InvalidOperationException("Cannot join a multiplayer room while already in one.");
|
||||
var cancellationSource = joinCancellationSource = new CancellationTokenSource();
|
||||
|
||||
Debug.Assert(room.RoomID.Value != null);
|
||||
await joinOrLeaveTaskChain.Add(async () =>
|
||||
{
|
||||
if (Room != null)
|
||||
throw new InvalidOperationException("Cannot join a multiplayer room while already in one.");
|
||||
|
||||
apiRoom = room;
|
||||
playlistItemId = room.Playlist.SingleOrDefault()?.ID ?? 0;
|
||||
Debug.Assert(room.RoomID.Value != null);
|
||||
|
||||
Room = await JoinRoom(room.RoomID.Value.Value);
|
||||
// Join the server-side room.
|
||||
var joinedRoom = await JoinRoom(room.RoomID.Value.Value);
|
||||
Debug.Assert(joinedRoom != null);
|
||||
|
||||
Debug.Assert(Room != null);
|
||||
// Populate users.
|
||||
Debug.Assert(joinedRoom.Users != null);
|
||||
await Task.WhenAll(joinedRoom.Users.Select(PopulateUser));
|
||||
|
||||
var users = await getRoomUsers();
|
||||
Debug.Assert(users != null);
|
||||
// Update the stored room (must be done on update thread for thread-safety).
|
||||
await scheduleAsync(() =>
|
||||
{
|
||||
Room = joinedRoom;
|
||||
apiRoom = room;
|
||||
playlistItemId = room.Playlist.SingleOrDefault()?.ID ?? 0;
|
||||
}, cancellationSource.Token);
|
||||
|
||||
await Task.WhenAll(users.Select(PopulateUser));
|
||||
|
||||
updateLocalRoomSettings(Room.Settings);
|
||||
// Update room settings.
|
||||
await updateLocalRoomSettings(joinedRoom.Settings, cancellationSource.Token);
|
||||
}, cancellationSource.Token);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -142,23 +156,33 @@ namespace osu.Game.Online.Multiplayer
|
||||
/// <returns>The joined <see cref="MultiplayerRoom"/>.</returns>
|
||||
protected abstract Task<MultiplayerRoom> JoinRoom(long roomId);
|
||||
|
||||
public virtual Task LeaveRoom()
|
||||
public Task LeaveRoom()
|
||||
{
|
||||
Scheduler.Add(() =>
|
||||
{
|
||||
if (Room == null)
|
||||
return;
|
||||
// The join may have not completed yet, so certain tasks that either update the room or reference the room should be cancelled.
|
||||
// This includes the setting of Room itself along with the initial update of the room settings on join.
|
||||
joinCancellationSource?.Cancel();
|
||||
|
||||
// Leaving rooms is expected to occur instantaneously whilst the operation is finalised in the background.
|
||||
// However a few members need to be reset immediately to prevent other components from entering invalid states whilst the operation hasn't yet completed.
|
||||
// For example, if a room was left and the user immediately pressed the "create room" button, then the user could be taken into the lobby if the value of Room is not reset in time.
|
||||
var scheduledReset = scheduleAsync(() =>
|
||||
{
|
||||
apiRoom = null;
|
||||
Room = null;
|
||||
CurrentMatchPlayingUserIds.Clear();
|
||||
|
||||
RoomUpdated?.Invoke();
|
||||
}, false);
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
return joinOrLeaveTaskChain.Add(async () =>
|
||||
{
|
||||
await scheduledReset;
|
||||
await LeaveRoomInternal();
|
||||
});
|
||||
}
|
||||
|
||||
protected abstract Task LeaveRoomInternal();
|
||||
|
||||
/// <summary>
|
||||
/// Change the current <see cref="MultiplayerRoom"/> settings.
|
||||
/// </summary>
|
||||
@ -462,27 +486,6 @@ namespace osu.Game.Online.Multiplayer
|
||||
/// <param name="multiplayerUser">The <see cref="MultiplayerRoomUser"/> to populate.</param>
|
||||
protected async Task PopulateUser(MultiplayerRoomUser multiplayerUser) => multiplayerUser.User ??= await userLookupCache.GetUserAsync(multiplayerUser.UserID);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve a copy of users currently in the joined <see cref="Room"/> in a thread-safe manner.
|
||||
/// This should be used whenever accessing users from outside of an Update thread context (ie. when not calling <see cref="Drawable.Schedule"/>).
|
||||
/// </summary>
|
||||
/// <returns>A copy of users in the current room, or null if unavailable.</returns>
|
||||
private Task<List<MultiplayerRoomUser>?> getRoomUsers()
|
||||
{
|
||||
var tcs = new TaskCompletionSource<List<MultiplayerRoomUser>?>();
|
||||
|
||||
// at some point we probably want to replace all these schedule calls with Room.LockForUpdate.
|
||||
// for now, as this would require quite some consideration due to the number of accesses to the room instance,
|
||||
// let's just add a manual schedule for the non-scheduled usages instead.
|
||||
Scheduler.Add(() =>
|
||||
{
|
||||
var users = Room?.Users.ToList();
|
||||
tcs.SetResult(users);
|
||||
}, false);
|
||||
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the local room settings with the given <see cref="MultiplayerRoomSettings"/>.
|
||||
/// </summary>
|
||||
@ -490,34 +493,36 @@ namespace osu.Game.Online.Multiplayer
|
||||
/// This updates both the joined <see cref="MultiplayerRoom"/> and the respective API <see cref="Room"/>.
|
||||
/// </remarks>
|
||||
/// <param name="settings">The new <see cref="MultiplayerRoomSettings"/> to update from.</param>
|
||||
private void updateLocalRoomSettings(MultiplayerRoomSettings settings)
|
||||
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to cancel the update.</param>
|
||||
private Task updateLocalRoomSettings(MultiplayerRoomSettings settings, CancellationToken cancellationToken = default) => scheduleAsync(() =>
|
||||
{
|
||||
if (Room == null)
|
||||
return;
|
||||
|
||||
Scheduler.Add(() =>
|
||||
Debug.Assert(apiRoom != null);
|
||||
|
||||
// Update a few properties of the room instantaneously.
|
||||
Room.Settings = settings;
|
||||
apiRoom.Name.Value = Room.Settings.Name;
|
||||
|
||||
// The playlist update is delayed until an online beatmap lookup (below) succeeds.
|
||||
// In-order for the client to not display an outdated beatmap, the playlist is forcefully cleared here.
|
||||
apiRoom.Playlist.Clear();
|
||||
|
||||
RoomUpdated?.Invoke();
|
||||
|
||||
var req = new GetBeatmapSetRequest(settings.BeatmapID, BeatmapSetLookupType.BeatmapId);
|
||||
|
||||
req.Success += res =>
|
||||
{
|
||||
if (Room == null)
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
return;
|
||||
|
||||
Debug.Assert(apiRoom != null);
|
||||
updatePlaylist(settings, res);
|
||||
};
|
||||
|
||||
// Update a few properties of the room instantaneously.
|
||||
Room.Settings = settings;
|
||||
apiRoom.Name.Value = Room.Settings.Name;
|
||||
|
||||
// The playlist update is delayed until an online beatmap lookup (below) succeeds.
|
||||
// In-order for the client to not display an outdated beatmap, the playlist is forcefully cleared here.
|
||||
apiRoom.Playlist.Clear();
|
||||
|
||||
RoomUpdated?.Invoke();
|
||||
|
||||
var req = new GetBeatmapSetRequest(settings.BeatmapID, BeatmapSetLookupType.BeatmapId);
|
||||
req.Success += res => updatePlaylist(settings, res);
|
||||
|
||||
api.Queue(req);
|
||||
}, false);
|
||||
}
|
||||
api.Queue(req);
|
||||
}, cancellationToken);
|
||||
|
||||
private void updatePlaylist(MultiplayerRoomSettings settings, APIBeatmapSet onlineSet)
|
||||
{
|
||||
@ -566,5 +571,31 @@ namespace osu.Game.Online.Multiplayer
|
||||
else
|
||||
CurrentMatchPlayingUserIds.Remove(userId);
|
||||
}
|
||||
|
||||
private Task scheduleAsync(Action action, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var tcs = new TaskCompletionSource<bool>();
|
||||
|
||||
Scheduler.Add(() =>
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
tcs.SetCanceled();
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
action();
|
||||
tcs.SetResult(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
tcs.SetException(ex);
|
||||
}
|
||||
});
|
||||
|
||||
return tcs.Task;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -17,19 +17,10 @@ using osu.Game.Rulesets.Objects.Drawables;
|
||||
|
||||
namespace osu.Game.Rulesets.UI
|
||||
{
|
||||
public class HitObjectContainer : LifetimeManagementContainer
|
||||
public class HitObjectContainer : LifetimeManagementContainer, IHitObjectContainer
|
||||
{
|
||||
/// <summary>
|
||||
/// All currently in-use <see cref="DrawableHitObject"/>s.
|
||||
/// </summary>
|
||||
public IEnumerable<DrawableHitObject> Objects => InternalChildren.Cast<DrawableHitObject>().OrderBy(h => h.HitObject.StartTime);
|
||||
|
||||
/// <summary>
|
||||
/// All currently in-use <see cref="DrawableHitObject"/>s that are alive.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If this <see cref="HitObjectContainer"/> uses pooled objects, this is equivalent to <see cref="Objects"/>.
|
||||
/// </remarks>
|
||||
public IEnumerable<DrawableHitObject> AliveObjects => AliveInternalChildren.Cast<DrawableHitObject>().OrderBy(h => h.HitObject.StartTime);
|
||||
|
||||
/// <summary>
|
||||
|
24
osu.Game/Rulesets/UI/IHitObjectContainer.cs
Normal file
24
osu.Game/Rulesets/UI/IHitObjectContainer.cs
Normal file
@ -0,0 +1,24 @@
|
||||
// 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.Objects.Drawables;
|
||||
|
||||
namespace osu.Game.Rulesets.UI
|
||||
{
|
||||
public interface IHitObjectContainer
|
||||
{
|
||||
/// <summary>
|
||||
/// All currently in-use <see cref="DrawableHitObject"/>s.
|
||||
/// </summary>
|
||||
IEnumerable<DrawableHitObject> Objects { get; }
|
||||
|
||||
/// <summary>
|
||||
/// All currently in-use <see cref="DrawableHitObject"/>s that are alive.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If this <see cref="IHitObjectContainer"/> uses pooled objects, this is equivalent to <see cref="Objects"/>.
|
||||
/// </remarks>
|
||||
IEnumerable<DrawableHitObject> AliveObjects { get; }
|
||||
}
|
||||
}
|
@ -13,6 +13,7 @@ using osu.Framework.Graphics.Effects;
|
||||
using osu.Framework.Graphics.Primitives;
|
||||
using osu.Framework.Graphics.Shapes;
|
||||
using osu.Framework.Input.Events;
|
||||
using osu.Framework.Utils;
|
||||
using osu.Game.Graphics;
|
||||
using osu.Game.Graphics.Sprites;
|
||||
using osu.Game.Graphics.UserInterface;
|
||||
@ -387,7 +388,7 @@ namespace osu.Game.Screens.Edit.Compose.Components.Timeline
|
||||
case IHasDuration endTimeHitObject:
|
||||
var snappedTime = Math.Max(hitObject.StartTime, beatSnapProvider.SnapTime(time));
|
||||
|
||||
if (endTimeHitObject.EndTime == snappedTime)
|
||||
if (endTimeHitObject.EndTime == snappedTime || Precision.AlmostEquals(snappedTime, hitObject.StartTime, beatmap.GetBeatLengthAtTime(snappedTime)))
|
||||
return;
|
||||
|
||||
endTimeHitObject.Duration = snappedTime - hitObject.StartTime;
|
||||
|
@ -88,6 +88,8 @@ namespace osu.Game.Screens.Edit
|
||||
|
||||
public IEnumerable<BeatmapStatistic> GetStatistics() => PlayableBeatmap.GetStatistics();
|
||||
|
||||
public double GetMostCommonBeatLength() => PlayableBeatmap.GetMostCommonBeatLength();
|
||||
|
||||
public IBeatmap Clone() => (EditorBeatmap)MemberwiseClone();
|
||||
|
||||
private IList mutableHitObjects => (IList)PlayableBeatmap.HitObjects;
|
||||
|
@ -74,7 +74,8 @@ namespace osu.Game.Screens.Edit.Timing
|
||||
{
|
||||
new TableColumn(string.Empty, Anchor.Centre, new Dimension(GridSizeMode.AutoSize)),
|
||||
new TableColumn("Time", Anchor.Centre, new Dimension(GridSizeMode.AutoSize)),
|
||||
new TableColumn("Attributes", Anchor.Centre),
|
||||
new TableColumn(),
|
||||
new TableColumn("Attributes", Anchor.CentreLeft),
|
||||
};
|
||||
|
||||
return columns.ToArray();
|
||||
@ -93,6 +94,7 @@ namespace osu.Game.Screens.Edit.Timing
|
||||
Text = group.Time.ToEditorFormattedString(),
|
||||
Font = OsuFont.GetFont(size: text_size, weight: FontWeight.Bold)
|
||||
},
|
||||
null,
|
||||
new ControlGroupAttributes(group),
|
||||
};
|
||||
|
||||
@ -104,11 +106,11 @@ namespace osu.Game.Screens.Edit.Timing
|
||||
|
||||
public ControlGroupAttributes(ControlPointGroup group)
|
||||
{
|
||||
RelativeSizeAxes = Axes.Both;
|
||||
InternalChild = fill = new FillFlowContainer
|
||||
{
|
||||
RelativeSizeAxes = Axes.Both,
|
||||
Direction = FillDirection.Horizontal,
|
||||
Padding = new MarginPadding(10),
|
||||
Spacing = new Vector2(2)
|
||||
};
|
||||
|
||||
@ -149,7 +151,10 @@ namespace osu.Game.Screens.Edit.Timing
|
||||
return new RowAttribute("difficulty", () => $"{difficulty.SpeedMultiplier:n2}x", colour);
|
||||
|
||||
case EffectControlPoint effect:
|
||||
return new RowAttribute("effect", () => $"{(effect.KiaiMode ? "Kiai " : "")}{(effect.OmitFirstBarLine ? "NoBarLine " : "")}", colour);
|
||||
return new RowAttribute("effect", () => string.Join(" ",
|
||||
effect.KiaiMode ? "Kiai" : string.Empty,
|
||||
effect.OmitFirstBarLine ? "NoBarLine" : string.Empty
|
||||
).Trim(), colour);
|
||||
|
||||
case SampleControlPoint sample:
|
||||
return new RowAttribute("sample", () => $"{sample.SampleBank} {sample.SampleVolume}%", colour);
|
||||
|
@ -87,7 +87,7 @@ namespace osu.Game.Screens.OnlinePlay.Multiplayer
|
||||
{
|
||||
if (t.IsCompletedSuccessfully)
|
||||
Schedule(() => onSuccess?.Invoke(room));
|
||||
else
|
||||
else if (t.IsFaulted)
|
||||
{
|
||||
const string message = "Failed to join multiplayer room.";
|
||||
|
||||
|
@ -23,32 +23,6 @@ namespace osu.Game.Screens.Play
|
||||
/// </summary>
|
||||
public class BeatmapMetadataDisplay : Container
|
||||
{
|
||||
private class MetadataLine : Container
|
||||
{
|
||||
public MetadataLine(string left, string right)
|
||||
{
|
||||
AutoSizeAxes = Axes.Both;
|
||||
Children = new Drawable[]
|
||||
{
|
||||
new OsuSpriteText
|
||||
{
|
||||
Anchor = Anchor.TopCentre,
|
||||
Origin = Anchor.TopRight,
|
||||
Margin = new MarginPadding { Right = 5 },
|
||||
Colour = OsuColour.Gray(0.8f),
|
||||
Text = left,
|
||||
},
|
||||
new OsuSpriteText
|
||||
{
|
||||
Anchor = Anchor.TopCentre,
|
||||
Origin = Anchor.TopLeft,
|
||||
Margin = new MarginPadding { Left = 5 },
|
||||
Text = string.IsNullOrEmpty(right) ? @"-" : right,
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private readonly WorkingBeatmap beatmap;
|
||||
private readonly Bindable<IReadOnlyList<Mod>> mods;
|
||||
private readonly Drawable facade;
|
||||
@ -144,15 +118,34 @@ namespace osu.Game.Screens.Play
|
||||
Bottom = 40
|
||||
},
|
||||
},
|
||||
new MetadataLine("Source", metadata.Source)
|
||||
new GridContainer
|
||||
{
|
||||
Origin = Anchor.TopCentre,
|
||||
Anchor = Anchor.TopCentre,
|
||||
},
|
||||
new MetadataLine("Mapper", metadata.AuthorString)
|
||||
{
|
||||
Origin = Anchor.TopCentre,
|
||||
Anchor = Anchor.TopCentre,
|
||||
AutoSizeAxes = Axes.Both,
|
||||
RowDimensions = new[]
|
||||
{
|
||||
new Dimension(GridSizeMode.AutoSize),
|
||||
new Dimension(GridSizeMode.AutoSize),
|
||||
},
|
||||
ColumnDimensions = new[]
|
||||
{
|
||||
new Dimension(GridSizeMode.AutoSize),
|
||||
new Dimension(GridSizeMode.AutoSize),
|
||||
},
|
||||
Content = new[]
|
||||
{
|
||||
new Drawable[]
|
||||
{
|
||||
new MetadataLineLabel("Source"),
|
||||
new MetadataLineInfo(metadata.Source)
|
||||
},
|
||||
new Drawable[]
|
||||
{
|
||||
new MetadataLineLabel("Mapper"),
|
||||
new MetadataLineInfo(metadata.AuthorString)
|
||||
}
|
||||
}
|
||||
},
|
||||
new ModDisplay
|
||||
{
|
||||
@ -168,5 +161,26 @@ namespace osu.Game.Screens.Play
|
||||
|
||||
Loading = true;
|
||||
}
|
||||
|
||||
private class MetadataLineLabel : OsuSpriteText
|
||||
{
|
||||
public MetadataLineLabel(string text)
|
||||
{
|
||||
Anchor = Anchor.TopRight;
|
||||
Origin = Anchor.TopRight;
|
||||
Margin = new MarginPadding { Right = 5 };
|
||||
Colour = OsuColour.Gray(0.8f);
|
||||
Text = text;
|
||||
}
|
||||
}
|
||||
|
||||
private class MetadataLineInfo : OsuSpriteText
|
||||
{
|
||||
public MetadataLineInfo(string text)
|
||||
{
|
||||
Margin = new MarginPadding { Left = 5 };
|
||||
Text = string.IsNullOrEmpty(text) ? @"-" : text;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -23,16 +23,17 @@ namespace osu.Game.Screens.Play
|
||||
/// </summary>
|
||||
public IBindable<bool> IsBreakTime => isBreakTime;
|
||||
|
||||
private readonly BindableBool isBreakTime = new BindableBool();
|
||||
private readonly BindableBool isBreakTime = new BindableBool(true);
|
||||
|
||||
public IReadOnlyList<BreakPeriod> Breaks
|
||||
{
|
||||
set
|
||||
{
|
||||
isBreakTime.Value = false;
|
||||
|
||||
breaks = new PeriodTracker(value.Where(b => b.HasEffect)
|
||||
.Select(b => new Period(b.StartTime, b.EndTime - BreakOverlay.BREAK_FADE_DURATION)));
|
||||
|
||||
if (IsLoaded)
|
||||
updateBreakTime();
|
||||
}
|
||||
}
|
||||
|
||||
@ -45,7 +46,11 @@ namespace osu.Game.Screens.Play
|
||||
protected override void Update()
|
||||
{
|
||||
base.Update();
|
||||
updateBreakTime();
|
||||
}
|
||||
|
||||
private void updateBreakTime()
|
||||
{
|
||||
var time = Clock.CurrentTime;
|
||||
|
||||
isBreakTime.Value = breaks?.IsInAny(time) == true
|
||||
|
@ -43,6 +43,8 @@ namespace osu.Game.Screens.Play
|
||||
|
||||
public IEnumerable<BeatmapStatistic> GetStatistics() => PlayableBeatmap.GetStatistics();
|
||||
|
||||
public double GetMostCommonBeatLength() => PlayableBeatmap.GetMostCommonBeatLength();
|
||||
|
||||
public IBeatmap Clone() => PlayableBeatmap.Clone();
|
||||
|
||||
private readonly Bindable<JudgementResult> lastJudgementResult = new Bindable<JudgementResult>();
|
||||
|
@ -88,11 +88,6 @@ namespace osu.Game.Screens.Play.HUD
|
||||
return base.OnMouseMove(e);
|
||||
}
|
||||
|
||||
public bool PauseOnFocusLost
|
||||
{
|
||||
set => button.PauseOnFocusLost = value;
|
||||
}
|
||||
|
||||
protected override void Update()
|
||||
{
|
||||
base.Update();
|
||||
@ -120,8 +115,6 @@ namespace osu.Game.Screens.Play.HUD
|
||||
public Action HoverGained;
|
||||
public Action HoverLost;
|
||||
|
||||
private readonly IBindable<bool> gameActive = new Bindable<bool>(true);
|
||||
|
||||
[BackgroundDependencyLoader]
|
||||
private void load(OsuColour colours, Framework.Game game)
|
||||
{
|
||||
@ -164,14 +157,6 @@ namespace osu.Game.Screens.Play.HUD
|
||||
};
|
||||
|
||||
bind();
|
||||
|
||||
gameActive.BindTo(game.IsActive);
|
||||
}
|
||||
|
||||
protected override void LoadComplete()
|
||||
{
|
||||
base.LoadComplete();
|
||||
gameActive.BindValueChanged(_ => updateActive(), true);
|
||||
}
|
||||
|
||||
private void bind()
|
||||
@ -221,31 +206,6 @@ namespace osu.Game.Screens.Play.HUD
|
||||
base.OnHoverLost(e);
|
||||
}
|
||||
|
||||
private bool pauseOnFocusLost = true;
|
||||
|
||||
public bool PauseOnFocusLost
|
||||
{
|
||||
set
|
||||
{
|
||||
if (pauseOnFocusLost == value)
|
||||
return;
|
||||
|
||||
pauseOnFocusLost = value;
|
||||
if (IsLoaded)
|
||||
updateActive();
|
||||
}
|
||||
}
|
||||
|
||||
private void updateActive()
|
||||
{
|
||||
if (!pauseOnFocusLost || IsPaused.Value) return;
|
||||
|
||||
if (gameActive.Value)
|
||||
AbortConfirm();
|
||||
else
|
||||
BeginConfirm();
|
||||
}
|
||||
|
||||
public bool OnPressed(GlobalAction action)
|
||||
{
|
||||
switch (action)
|
||||
|
@ -59,6 +59,8 @@ namespace osu.Game.Screens.Play
|
||||
// We are managing our own adjustments (see OnEntering/OnExiting).
|
||||
public override bool AllowRateAdjustments => false;
|
||||
|
||||
private readonly IBindable<bool> gameActive = new Bindable<bool>(true);
|
||||
|
||||
private readonly Bindable<bool> samplePlaybackDisabled = new Bindable<bool>();
|
||||
|
||||
/// <summary>
|
||||
@ -154,6 +156,8 @@ namespace osu.Game.Screens.Play
|
||||
// replays should never be recorded or played back when autoplay is enabled
|
||||
if (!Mods.Value.Any(m => m is ModAutoplay))
|
||||
PrepareReplay();
|
||||
|
||||
gameActive.BindValueChanged(_ => updatePauseOnFocusLostState(), true);
|
||||
}
|
||||
|
||||
[CanBeNull]
|
||||
@ -170,7 +174,7 @@ namespace osu.Game.Screens.Play
|
||||
}
|
||||
|
||||
[BackgroundDependencyLoader(true)]
|
||||
private void load(AudioManager audio, OsuConfigManager config, OsuGame game)
|
||||
private void load(AudioManager audio, OsuConfigManager config, OsuGameBase game)
|
||||
{
|
||||
Mods.Value = base.Mods.Value.Select(m => m.CreateCopy()).ToArray();
|
||||
|
||||
@ -187,7 +191,10 @@ namespace osu.Game.Screens.Play
|
||||
mouseWheelDisabled = config.GetBindable<bool>(OsuSetting.MouseDisableWheel);
|
||||
|
||||
if (game != null)
|
||||
LocalUserPlaying.BindTo(game.LocalUserPlaying);
|
||||
gameActive.BindTo(game.IsActive);
|
||||
|
||||
if (game is OsuGame osuGame)
|
||||
LocalUserPlaying.BindTo(osuGame.LocalUserPlaying);
|
||||
|
||||
DrawableRuleset = ruleset.CreateDrawableRulesetWith(playableBeatmap, Mods.Value);
|
||||
|
||||
@ -258,8 +265,6 @@ namespace osu.Game.Screens.Play
|
||||
|
||||
DrawableRuleset.HasReplayLoaded.BindValueChanged(_ => updateGameplayState());
|
||||
|
||||
DrawableRuleset.HasReplayLoaded.BindValueChanged(_ => updatePauseOnFocusLostState(), true);
|
||||
|
||||
// bind clock into components that require it
|
||||
DrawableRuleset.IsPaused.BindTo(GameplayClockContainer.IsPaused);
|
||||
|
||||
@ -420,10 +425,14 @@ namespace osu.Game.Screens.Play
|
||||
samplePlaybackDisabled.Value = DrawableRuleset.FrameStableClock.IsCatchingUp.Value || GameplayClockContainer.GameplayClock.IsPaused.Value;
|
||||
}
|
||||
|
||||
private void updatePauseOnFocusLostState() =>
|
||||
HUDOverlay.HoldToQuit.PauseOnFocusLost = PauseOnFocusLost
|
||||
&& !DrawableRuleset.HasReplayLoaded.Value
|
||||
&& !breakTracker.IsBreakTime.Value;
|
||||
private void updatePauseOnFocusLostState()
|
||||
{
|
||||
if (!PauseOnFocusLost || breakTracker.IsBreakTime.Value)
|
||||
return;
|
||||
|
||||
if (gameActive.Value == false)
|
||||
Pause();
|
||||
}
|
||||
|
||||
private IBeatmap loadPlayableBeatmap()
|
||||
{
|
||||
|
@ -391,7 +391,7 @@ namespace osu.Game.Screens.Select
|
||||
if (Precision.AlmostEquals(bpmMin, bpmMax))
|
||||
return $"{bpmMin:0}";
|
||||
|
||||
return $"{bpmMin:0}-{bpmMax:0} (mostly {beatmap.ControlPointInfo.BPMMode:0})";
|
||||
return $"{bpmMin:0}-{bpmMax:0} (mostly {60000 / beatmap.GetMostCommonBeatLength():0})";
|
||||
}
|
||||
|
||||
private OsuSpriteText[] getMapper(BeatmapMetadata metadata)
|
||||
|
@ -50,5 +50,13 @@ namespace osu.Game.Tests.Visual.Multiplayer
|
||||
if (joinRoom)
|
||||
RoomManager.Schedule(() => RoomManager.CreateRoom(Room));
|
||||
});
|
||||
|
||||
public override void SetUpSteps()
|
||||
{
|
||||
base.SetUpSteps();
|
||||
|
||||
if (joinRoom)
|
||||
AddUntilStep("wait for room join", () => Client.Room != null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -100,6 +100,8 @@ namespace osu.Game.Tests.Visual.Multiplayer
|
||||
return Task.FromResult(room);
|
||||
}
|
||||
|
||||
protected override Task LeaveRoomInternal() => Task.CompletedTask;
|
||||
|
||||
public override Task TransferHost(int userId) => ((IMultiplayerClient)this).HostChanged(userId);
|
||||
|
||||
public override async Task ChangeSettings(MultiplayerRoomSettings settings)
|
||||
|
46
osu.Game/Utils/TaskChain.cs
Normal file
46
osu.Game/Utils/TaskChain.cs
Normal 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.
|
||||
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using osu.Game.Extensions;
|
||||
|
||||
namespace osu.Game.Utils
|
||||
{
|
||||
/// <summary>
|
||||
/// A chain of <see cref="Task"/>s that run sequentially.
|
||||
/// </summary>
|
||||
public class TaskChain
|
||||
{
|
||||
private readonly object taskLock = new object();
|
||||
|
||||
private Task lastTaskInChain = Task.CompletedTask;
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new task to the end of this <see cref="TaskChain"/>.
|
||||
/// </summary>
|
||||
/// <param name="action">The action to be executed.</param>
|
||||
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for this task. Does not affect further tasks in the chain.</param>
|
||||
/// <returns>The awaitable <see cref="Task"/>.</returns>
|
||||
public Task Add(Action action, CancellationToken cancellationToken = default)
|
||||
{
|
||||
lock (taskLock)
|
||||
return lastTaskInChain = lastTaskInChain.ContinueWithSequential(action, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new task to the end of this <see cref="TaskChain"/>.
|
||||
/// </summary>
|
||||
/// <param name="task">The task to be executed.</param>
|
||||
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for this task. Does not affect further tasks in the chain.</param>
|
||||
/// <returns>The awaitable <see cref="Task"/>.</returns>
|
||||
public Task Add(Func<Task> task, CancellationToken cancellationToken = default)
|
||||
{
|
||||
lock (taskLock)
|
||||
return lastTaskInChain = lastTaskInChain.ContinueWithSequential(task, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user