1
0
mirror of https://github.com/ppy/osu.git synced 2024-12-27 20:22:56 +08:00
osu-lazer/osu.Game/Screens/OnlinePlay/Multiplayer/MultiplayerPlayer.cs

249 lines
9.0 KiB
C#
Raw Normal View History

// 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.
2020-12-20 23:13:05 +08:00
using System;
using System.Diagnostics;
using System.Linq;
2020-12-20 23:13:05 +08:00
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Logging;
using osu.Framework.Screens;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.Multiplayer;
2020-12-25 12:38:11 +08:00
using osu.Game.Online.Rooms;
2020-12-20 23:13:05 +08:00
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
2020-12-20 23:13:05 +08:00
using osu.Game.Screens.Ranking;
using osu.Game.Users;
using osuTK;
namespace osu.Game.Screens.OnlinePlay.Multiplayer
{
public class MultiplayerPlayer : RoomSubmittingPlayer
{
2020-12-20 23:13:05 +08:00
protected override bool PauseOnFocusLost => false;
// Disallow fails in multiplayer for now.
protected override bool CheckModsAllowFailure() => false;
protected override UserActivity InitialActivity => new UserActivity.InMultiplayerGame(Beatmap.Value.BeatmapInfo, Ruleset.Value);
2020-12-20 23:13:05 +08:00
[Resolved]
2021-05-20 14:39:45 +08:00
private MultiplayerClient client { get; set; }
2020-12-20 23:13:05 +08:00
private IBindable<bool> isConnected;
2020-12-20 23:13:05 +08:00
private readonly TaskCompletionSource<bool> resultsReady = new TaskCompletionSource<bool>();
private MultiplayerGameplayLeaderboard leaderboard;
private readonly MultiplayerRoomUser[] users;
private readonly Bindable<bool> leaderboardExpanded = new BindableBool();
private LoadingLayer loadingDisplay;
private FillFlowContainer leaderboardFlow;
/// <summary>
/// Construct a multiplayer player.
/// </summary>
/// <param name="room">The room.</param>
/// <param name="playlistItem">The playlist item to be played.</param>
/// <param name="users">The users which are participating in this game.</param>
public MultiplayerPlayer(Room room, PlaylistItem playlistItem, MultiplayerRoomUser[] users)
: base(room, playlistItem, new PlayerConfiguration
{
AllowPause = false,
AllowRestart = false,
AllowSkipping = false,
})
2020-12-20 23:13:05 +08:00
{
this.users = users;
2020-12-20 23:13:05 +08:00
}
[BackgroundDependencyLoader]
private void load()
{
if (!LoadedBeatmapSuccessfully)
return;
HUDOverlay.Add(leaderboardFlow = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Spacing = new Vector2(5)
});
HUDOverlay.HoldingForHUD.BindValueChanged(_ => updateLeaderboardExpandedState());
LocalUserPlaying.BindValueChanged(_ => updateLeaderboardExpandedState(), true);
// todo: this should be implemented via a custom HUD implementation, and correctly masked to the main content area.
LoadComponentAsync(leaderboard = new MultiplayerGameplayLeaderboard(GameplayState.Ruleset.RulesetInfo, ScoreProcessor, users), l =>
{
if (!LoadedBeatmapSuccessfully)
return;
leaderboard.Expanded.BindTo(leaderboardExpanded);
leaderboardFlow.Insert(0, l);
if (leaderboard.TeamScores.Count >= 2)
{
LoadComponentAsync(new GameplayMatchScoreDisplay
{
Team1Score = { BindTarget = leaderboard.TeamScores.First().Value },
Team2Score = { BindTarget = leaderboard.TeamScores.Last().Value },
Expanded = { BindTarget = HUDOverlay.ShowHud },
}, scoreDisplay => leaderboardFlow.Insert(1, scoreDisplay));
}
});
LoadComponentAsync(new GameplayChatDisplay(Room)
{
Expanded = { BindTarget = leaderboardExpanded },
}, chat => leaderboardFlow.Insert(2, chat));
HUDOverlay.Add(loadingDisplay = new LoadingLayer(true) { Depth = float.MaxValue });
}
protected override void LoadAsyncComplete()
{
base.LoadAsyncComplete();
if (!LoadedBeatmapSuccessfully)
return;
2021-03-24 12:20:44 +08:00
if (!ValidForResume)
return; // token retrieval may have failed.
2020-12-20 23:13:05 +08:00
client.GameplayStarted += onGameplayStarted;
2020-12-20 23:13:05 +08:00
client.ResultsReady += onResultsReady;
ScoreProcessor.HasCompleted.BindValueChanged(completed =>
{
// wait for server to tell us that results are ready (see SubmitScore implementation)
loadingDisplay.Show();
});
isConnected = client.IsConnected.GetBoundCopy();
isConnected.BindValueChanged(connected => Schedule(() =>
{
if (!connected.NewValue)
{
2020-12-25 12:38:11 +08:00
// messaging to the user about this disconnect will be provided by the MultiplayerMatchSubScreen.
failAndBail();
}
}), true);
}
protected override void LoadComplete()
{
base.LoadComplete();
Debug.Assert(client.Room != null);
}
protected override void StartGameplay()
{
// We can enter this screen one of two ways:
// 1. Via the automatic natural progression of PlayerLoader into Player.
// We'll arrive here in a Loaded state, and we need to let the server know that we're ready to start.
// 2. Via the server forcefully starting gameplay because players have been hanging out in PlayerLoader for too long.
// We'll arrive here in a Playing state, and we should neither show the loading spinner nor tell the server that we're ready to start (gameplay has already started).
//
// The base call is blocked here because in both cases gameplay is started only when the server says so via onGameplayStarted().
if (client.LocalUser?.State == MultiplayerUserState.Loaded)
{
loadingDisplay.Show();
client.ChangeState(MultiplayerUserState.ReadyForGameplay);
}
}
private void updateLeaderboardExpandedState() =>
leaderboardExpanded.Value = !LocalUserPlaying.Value || HUDOverlay.HoldingForHUD.Value;
private void failAndBail(string message = null)
{
if (!string.IsNullOrEmpty(message))
Logger.Log(message, LoggingTarget.Runtime, LogLevel.Important);
Schedule(() => PerformExit(false));
2020-12-20 23:13:05 +08:00
}
protected override void Update()
{
base.Update();
if (!LoadedBeatmapSuccessfully)
return;
adjustLeaderboardPosition();
}
private void adjustLeaderboardPosition()
{
const float padding = 44; // enough margin to avoid the hit error display.
leaderboardFlow.Position = new Vector2(padding, padding + HUDOverlay.TopScoringElementsHeight);
2020-12-20 23:13:05 +08:00
}
private void onGameplayStarted() => Scheduler.Add(() =>
{
if (!this.IsCurrentScreen())
return;
loadingDisplay.Hide();
base.StartGameplay();
});
2020-12-20 23:13:05 +08:00
private void onResultsReady()
{
// Schedule is required to ensure that `TaskCompletionSource.SetResult` is not called more than once.
// A scenario where this can occur is if this instance is not immediately disposed (ie. async disposal queue).
Schedule(() =>
{
if (!this.IsCurrentScreen())
return;
resultsReady.SetResult(true);
});
}
2020-12-20 23:13:05 +08:00
protected override async Task PrepareScoreForResultsAsync(Score score)
2020-12-20 23:13:05 +08:00
{
await base.PrepareScoreForResultsAsync(score).ConfigureAwait(false);
2020-12-20 23:13:05 +08:00
await client.ChangeState(MultiplayerUserState.FinishedPlay).ConfigureAwait(false);
2020-12-20 23:13:05 +08:00
2020-12-24 18:33:49 +08:00
// Await up to 60 seconds for results to become available (6 api request timeouts).
2020-12-20 23:13:05 +08:00
// This is arbitrary just to not leave the player in an essentially deadlocked state if any connection issues occur.
await Task.WhenAny(resultsReady.Task, Task.Delay(TimeSpan.FromSeconds(60))).ConfigureAwait(false);
2020-12-20 23:13:05 +08:00
}
protected override ResultsScreen CreateResults(ScoreInfo score)
{
Debug.Assert(Room.RoomID.Value != null);
return leaderboard.TeamScores.Count == 2
? new MultiplayerTeamResultsScreen(score, Room.RoomID.Value.Value, PlaylistItem, leaderboard.TeamScores)
: new MultiplayerResultsScreen(score, Room.RoomID.Value.Value, PlaylistItem);
2020-12-20 23:13:05 +08:00
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (client != null)
{
client.GameplayStarted -= onGameplayStarted;
2020-12-20 23:13:05 +08:00
client.ResultsReady -= onResultsReady;
}
}
}
}