1
0
mirror of https://github.com/ppy/osu.git synced 2024-12-31 06:52:55 +08:00
osu-lazer/osu.Game/Screens/Play/Player.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

1113 lines
44 KiB
C#
Raw Normal View History

2019-06-04 15:13:16 +08:00
// 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.
2018-04-13 17:19:50 +08:00
2018-01-21 23:11:43 +08:00
using System;
2020-03-24 13:13:46 +08:00
using System.IO;
2018-01-21 23:11:43 +08:00
using System.Linq;
using System.Threading.Tasks;
2016-11-09 07:13:20 +08:00
using osu.Framework.Allocation;
using osu.Framework.Audio;
2018-01-21 23:11:43 +08:00
using osu.Framework.Audio.Sample;
2019-02-21 18:04:31 +08:00
using osu.Framework.Bindables;
using osu.Framework.Extensions;
2016-11-14 16:23:33 +08:00
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
2018-10-02 11:02:47 +08:00
using osu.Framework.Input.Events;
using osu.Framework.Logging;
using osu.Framework.Screens;
using osu.Framework.Threading;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
2019-01-04 12:29:37 +08:00
using osu.Game.Graphics.Containers;
2020-03-24 13:13:46 +08:00
using osu.Game.IO.Archives;
using osu.Game.Online.API;
using osu.Game.Online.Spectator;
2018-06-06 14:10:09 +08:00
using osu.Game.Overlays;
2017-04-18 15:05:58 +08:00
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
2017-04-18 15:05:58 +08:00
using osu.Game.Rulesets.Scoring;
2018-01-21 23:11:43 +08:00
using osu.Game.Rulesets.UI;
2018-11-28 15:12:57 +08:00
using osu.Game.Scoring;
2020-03-24 13:13:46 +08:00
using osu.Game.Scoring.Legacy;
2018-01-21 23:11:43 +08:00
using osu.Game.Screens.Ranking;
2018-03-20 15:26:36 +08:00
using osu.Game.Skinning;
using osu.Game.Users;
using osuTK.Graphics;
2018-04-13 17:19:50 +08:00
2016-11-14 16:23:33 +08:00
namespace osu.Game.Screens.Play
2016-09-29 19:13:58 +08:00
{
2019-11-01 14:32:06 +08:00
[Cached]
public abstract class Player : ScreenWithBeatmapBackground, ISamplePlaybackDisabler, ILocalUserPlayInfo
2016-09-29 19:13:58 +08:00
{
/// <summary>
/// The delay upon completion of the beatmap before displaying the results screen.
/// </summary>
public const double RESULTS_DISPLAY_DELAY = 1000.0;
2021-08-11 17:16:25 +08:00
/// <summary>
/// Raised after <see cref="StartGameplay"/> is called.
/// </summary>
public event Action OnGameplayStarted;
2019-06-25 15:55:49 +08:00
public override bool AllowBackButton => false; // handled by HoldForMenuButton
2018-04-13 17:19:50 +08:00
protected override UserActivity InitialActivity => new UserActivity.InSoloGame(Beatmap.Value.BeatmapInfo, Ruleset.Value);
2018-04-13 17:19:50 +08:00
2019-01-23 19:52:00 +08:00
public override float BackgroundParallaxAmount => 0.1f;
2018-04-13 17:19:50 +08:00
public override bool HideOverlaysOnEnter => true;
2018-04-13 17:19:50 +08:00
protected override OverlayActivation InitialOverlayActivationMode => OverlayActivation.UserTriggered;
2020-09-01 15:55:10 +08:00
// We are managing our own adjustments (see OnEntering/OnExiting).
public override bool? AllowTrackAdjustments => false;
2018-06-06 14:10:09 +08:00
private readonly IBindable<bool> gameActive = new Bindable<bool>(true);
private readonly Bindable<bool> samplePlaybackDisabled = new Bindable<bool>();
2018-06-06 14:10:09 +08:00
/// <summary>
/// Whether gameplay should pause when the game window focus is lost.
/// </summary>
protected virtual bool PauseOnFocusLost => true;
2018-06-06 14:10:09 +08:00
public Action RestartRequested;
2018-04-13 17:19:50 +08:00
private Bindable<bool> mouseWheelDisabled;
2019-02-25 12:27:44 +08:00
private readonly Bindable<bool> storyboardReplacesBackground = new Bindable<bool>();
2018-04-13 17:19:50 +08:00
public IBindable<bool> LocalUserPlaying => localUserPlaying;
private readonly Bindable<bool> localUserPlaying = new Bindable<bool>();
public int RestartCount;
2018-04-13 17:19:50 +08:00
2018-11-29 13:56:29 +08:00
[Resolved]
private ScoreManager scoreManager { get; set; }
2018-04-13 17:19:50 +08:00
2020-02-14 21:14:00 +08:00
[Resolved]
private IAPIProvider api { get; set; }
2018-04-13 17:19:50 +08:00
[Resolved]
private MusicController musicController { get; set; }
[Resolved]
private SpectatorClient spectatorClient { get; set; }
2021-10-02 01:22:23 +08:00
public GameplayState GameplayState { get; private set; }
2021-10-02 01:22:23 +08:00
private Ruleset ruleset;
2021-01-19 16:11:40 +08:00
private Sample sampleRestart;
2018-04-13 17:19:50 +08:00
2019-12-12 14:14:59 +08:00
public BreakOverlay BreakOverlay;
2018-04-13 17:19:50 +08:00
/// <summary>
/// Whether the gameplay is currently in a break.
/// </summary>
2020-10-11 20:46:55 +08:00
public readonly IBindable<bool> IsBreakTime = new BindableBool();
2020-10-10 21:07:17 +08:00
private BreakTracker breakTracker;
private SkipOverlay skipIntroOverlay;
private SkipOverlay skipOutroOverlay;
protected ScoreProcessor ScoreProcessor { get; private set; }
protected HealthProcessor HealthProcessor { get; private set; }
protected DrawableRuleset DrawableRuleset { get; private set; }
2018-04-13 17:19:50 +08:00
protected HUDOverlay HUDOverlay { get; private set; }
2018-04-13 17:19:50 +08:00
public bool LoadedBeatmapSuccessfully => DrawableRuleset?.Objects.Any() == true;
2018-04-13 17:19:50 +08:00
2019-03-17 23:46:15 +08:00
protected GameplayClockContainer GameplayClockContainer { get; private set; }
2018-04-13 17:19:50 +08:00
public DimmableStoryboard DimmableStoryboard { get; private set; }
2018-04-13 17:19:50 +08:00
2019-09-19 03:49:28 +08:00
/// <summary>
/// Whether failing should be allowed.
2019-09-19 13:31:11 +08:00
/// By default, this checks whether all selected mods allow failing.
2019-09-19 03:49:28 +08:00
/// </summary>
protected virtual bool CheckModsAllowFailure() => GameplayState.Mods.OfType<IApplicableFailOverride>().All(m => m.PerformFail());
2019-09-19 03:49:28 +08:00
public readonly PlayerConfiguration Configuration;
/// <summary>
/// The score for the current play session.
/// Available only after the player is loaded.
/// </summary>
public Score Score { get; private set; }
/// <summary>
/// Create a new player instance.
/// </summary>
protected Player(PlayerConfiguration configuration = null)
{
2020-12-23 17:07:38 +08:00
Configuration = configuration ?? new PlayerConfiguration();
}
2018-04-13 17:19:50 +08:00
private ScreenSuspensionHandler screenSuspension;
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
=> dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
2020-03-23 18:31:43 +08:00
protected override void LoadComplete()
{
base.LoadComplete();
if (!LoadedBeatmapSuccessfully)
return;
PrepareReplay();
ScoreProcessor.NewJudgement += result => ScoreProcessor.PopulateScore(Score.ScoreInfo);
ScoreProcessor.OnResetFromReplayFrame += () => ScoreProcessor.PopulateScore(Score.ScoreInfo);
gameActive.BindValueChanged(_ => updatePauseOnFocusLostState(), true);
2020-03-23 18:31:43 +08:00
}
/// <summary>
/// Run any recording / playback setup for replays.
/// </summary>
protected virtual void PrepareReplay()
{
DrawableRuleset.SetRecordTarget(Score);
}
[BackgroundDependencyLoader(true)]
2021-02-08 18:59:07 +08:00
private void load(AudioManager audio, OsuConfigManager config, OsuGameBase game)
2016-10-05 19:49:31 +08:00
{
var gameplayMods = Mods.Value.Select(m => m.DeepClone()).ToArray();
2019-04-09 12:33:16 +08:00
if (gameplayMods.Any(m => m is UnknownMod))
{
Logger.Log("Gameplay was started with an unknown mod applied.", level: LogLevel.Important);
return;
}
if (Beatmap.Value is DummyWorkingBeatmap)
return;
IBeatmap playableBeatmap = loadPlayableBeatmap(gameplayMods);
if (playableBeatmap == null)
return;
2018-04-13 17:19:50 +08:00
sampleRestart = audio.Samples.Get(@"Gameplay/restart");
2018-04-13 17:19:50 +08:00
mouseWheelDisabled = config.GetBindable<bool>(OsuSetting.MouseDisableWheel);
2018-04-13 17:19:50 +08:00
if (game != null)
gameActive.BindTo(game.IsActive);
2021-02-08 19:05:16 +08:00
2021-02-08 18:59:07 +08:00
if (game is OsuGame osuGame)
LocalUserPlaying.BindTo(osuGame.LocalUserPlaying);
DrawableRuleset = ruleset.CreateDrawableRulesetWith(playableBeatmap, gameplayMods);
dependencies.CacheAs(DrawableRuleset);
2021-10-02 01:22:23 +08:00
ScoreProcessor = ruleset.CreateScoreProcessor();
ScoreProcessor.ApplyBeatmap(playableBeatmap);
ScoreProcessor.Mods.Value = gameplayMods;
2018-04-13 17:19:50 +08:00
dependencies.CacheAs(ScoreProcessor);
2021-10-02 01:22:23 +08:00
HealthProcessor = ruleset.CreateHealthProcessor(playableBeatmap.HitObjects[0].StartTime);
HealthProcessor.ApplyBeatmap(playableBeatmap);
dependencies.CacheAs(HealthProcessor);
if (!ScoreProcessor.Mode.Disabled)
config.BindWith(OsuSetting.ScoreDisplayMode, ScoreProcessor.Mode);
2018-04-13 17:19:50 +08:00
InternalChild = GameplayClockContainer = CreateGameplayClockContainer(Beatmap.Value, DrawableRuleset.GameplayStartTime);
2018-04-13 17:19:50 +08:00
AddInternal(screenSuspension = new ScreenSuspensionHandler(GameplayClockContainer));
2021-10-05 13:48:10 +08:00
Score = CreateScore(playableBeatmap);
2021-10-05 13:48:10 +08:00
// ensure the score is in a consistent state with the current player.
Score.ScoreInfo.BeatmapInfo = Beatmap.Value.BeatmapInfo;
Score.ScoreInfo.Ruleset = ruleset.RulesetInfo;
Score.ScoreInfo.Mods = gameplayMods;
2021-10-05 13:48:10 +08:00
dependencies.CacheAs(GameplayState = new GameplayState(playableBeatmap, ruleset, gameplayMods, Score));
2021-10-02 01:22:23 +08:00
var rulesetSkinProvider = new RulesetSkinProvidingContainer(ruleset, playableBeatmap, Beatmap.Value.Skin);
// load the skinning hierarchy first.
// this is intentionally done in two stages to ensure things are in a loaded state before exposing the ruleset to skin sources.
GameplayClockContainer.Add(rulesetSkinProvider);
2021-10-15 18:35:08 +08:00
rulesetSkinProvider.AddRange(new Drawable[]
{
2021-10-15 18:35:08 +08:00
failAnimationLayer = new FailAnimation(DrawableRuleset)
{
OnComplete = onFailComplete,
Children = new[]
{
// underlay and gameplay should have access to the skinning sources.
createUnderlayComponents(),
createGameplayComponents(Beatmap.Value)
2021-10-15 18:35:08 +08:00
}
},
FailOverlay = new FailOverlay
{
OnRetry = Restart,
OnQuit = () => PerformExit(true),
},
new HotkeyExitOverlay
{
Action = () =>
{
if (!this.IsCurrentScreen()) return;
fadeOut(true);
PerformExit(false);
},
},
});
if (Configuration.AllowRestart)
{
rulesetSkinProvider.Add(new HotkeyRetryOverlay
{
Action = () =>
{
if (!this.IsCurrentScreen()) return;
fadeOut(true);
Restart();
},
});
}
// add the overlay components as a separate step as they proxy some elements from the above underlay/gameplay components.
// also give the overlays the ruleset skin provider to allow rulesets to potentially override HUD elements (used to disable combo counters etc.)
// we may want to limit this in the future to disallow rulesets from outright replacing elements the user expects to be there.
failAnimationLayer.Add(createOverlayComponents(Beatmap.Value));
2018-04-13 17:19:50 +08:00
if (!DrawableRuleset.AllowGameplayOverlays)
{
HUDOverlay.ShowHud.Value = false;
HUDOverlay.ShowHud.Disabled = true;
BreakOverlay.Hide();
}
2020-10-27 17:13:45 +08:00
DrawableRuleset.FrameStableClock.WaitingOnFrames.BindValueChanged(waiting =>
{
if (waiting.NewValue)
GameplayClockContainer.Stop();
else
GameplayClockContainer.Start();
});
2020-10-27 13:10:12 +08:00
DrawableRuleset.IsPaused.BindValueChanged(paused =>
{
updateGameplayState();
updateSampleDisabledState();
});
DrawableRuleset.FrameStableClock.IsCatchingUp.BindValueChanged(_ => updateSampleDisabledState());
DrawableRuleset.HasReplayLoaded.BindValueChanged(_ => updateGameplayState());
2020-08-16 23:18:40 +08:00
// bind clock into components that require it
DrawableRuleset.IsPaused.BindTo(GameplayClockContainer.IsPaused);
2018-04-13 17:19:50 +08:00
DrawableRuleset.NewResult += r =>
{
HealthProcessor.ApplyResult(r);
ScoreProcessor.ApplyResult(r);
2021-10-02 01:22:23 +08:00
GameplayState.ApplyResult(r);
};
DrawableRuleset.RevertResult += r =>
{
HealthProcessor.RevertResult(r);
ScoreProcessor.RevertResult(r);
};
2019-12-11 16:25:06 +08:00
DimmableStoryboard.HasStoryboardEnded.ValueChanged += storyboardEnded =>
{
if (storyboardEnded.NewValue)
progressToResults(true);
};
// Bind the judgement processors to ourselves
ScoreProcessor.HasCompleted.BindValueChanged(scoreCompletionChanged);
HealthProcessor.Failed += onFail;
2018-04-13 17:19:50 +08:00
2021-08-02 02:14:54 +08:00
// Provide judgement processors to mods after they're loaded so that they're on the gameplay clock,
// this is required for mods that apply transforms to these processors.
ScoreProcessor.OnLoadComplete += _ =>
{
foreach (var mod in gameplayMods.OfType<IApplicableToScoreProcessor>())
mod.ApplyToScoreProcessor(ScoreProcessor);
};
HealthProcessor.OnLoadComplete += _ =>
{
foreach (var mod in gameplayMods.OfType<IApplicableToHealthProcessor>())
mod.ApplyToHealthProcessor(HealthProcessor);
};
2020-10-11 20:46:55 +08:00
IsBreakTime.BindTo(breakTracker.IsBreakTime);
IsBreakTime.BindValueChanged(onBreakTimeChanged, true);
}
2018-04-13 17:19:50 +08:00
2021-04-14 16:47:11 +08:00
protected virtual GameplayClockContainer CreateGameplayClockContainer(WorkingBeatmap beatmap, double gameplayStart) => new MasterGameplayClockContainer(beatmap, gameplayStart);
private Drawable createUnderlayComponents() =>
DimmableStoryboard = new DimmableStoryboard(Beatmap.Value.Storyboard, GameplayState.Mods) { RelativeSizeAxes = Axes.Both };
2018-04-13 17:19:50 +08:00
private Drawable createGameplayComponents(IWorkingBeatmap working) => new ScalingContainer(ScalingMode.Gameplay)
{
Children = new Drawable[]
{
DrawableRuleset.With(r =>
r.FrameStableComponents.Children = new Drawable[]
{
ScoreProcessor,
HealthProcessor,
new ComboEffects(ScoreProcessor),
breakTracker = new BreakTracker(DrawableRuleset.GameplayStartTime, ScoreProcessor)
{
Breaks = working.Beatmap.Breaks
}
}),
}
};
2018-04-13 17:19:50 +08:00
private Drawable createOverlayComponents(IWorkingBeatmap working)
{
var container = new Container
2016-10-06 22:33:09 +08:00
{
RelativeSizeAxes = Axes.Both,
2021-10-15 18:35:08 +08:00
Children = new[]
{
2021-10-15 18:35:08 +08:00
DimmableStoryboard.OverlayLayerContainer.CreateProxy(),
BreakOverlay = new BreakOverlay(working.Beatmap.BeatmapInfo.LetterboxInBreaks, ScoreProcessor)
{
2021-10-15 18:35:08 +08:00
Clock = DrawableRuleset.FrameStableClock,
ProcessCustomClock = false,
Breaks = working.Beatmap.Breaks
},
// display the cursor above some HUD elements.
DrawableRuleset.Cursor?.CreateProxy() ?? new Container(),
DrawableRuleset.ResumeOverlay?.CreateProxy() ?? new Container(),
HUDOverlay = new HUDOverlay(DrawableRuleset, GameplayState.Mods)
{
HoldToQuit =
{
2021-10-15 18:35:08 +08:00
Action = () => PerformExit(true),
IsPaused = { BindTarget = GameplayClockContainer.IsPaused }
},
KeyCounter =
{
AlwaysVisible = { BindTarget = DrawableRuleset.HasReplayLoaded },
IsCounting = false
},
Anchor = Anchor.Centre,
Origin = Anchor.Centre
},
skipIntroOverlay = new SkipOverlay(DrawableRuleset.GameplayStartTime)
{
RequestSkip = performUserRequestedSkip
},
2021-10-15 18:35:08 +08:00
skipOutroOverlay = new SkipOverlay(Beatmap.Value.Storyboard.LatestEventTime ?? 0)
{
2021-10-15 18:35:08 +08:00
RequestSkip = () => progressToResults(false),
Alpha = 0
},
PauseOverlay = new PauseOverlay
{
OnResume = Resume,
Retries = RestartCount,
OnRetry = Restart,
OnQuit = () => PerformExit(true),
2021-10-15 18:35:08 +08:00
},
},
};
if (!Configuration.AllowSkipping || !DrawableRuleset.AllowGameplayOverlays)
{
skipIntroOverlay.Expire();
skipOutroOverlay.Expire();
}
2021-04-14 16:47:11 +08:00
if (GameplayClockContainer is MasterGameplayClockContainer master)
HUDOverlay.PlayerSettingsOverlay.PlaybackSettings.UserPlaybackRate.BindTarget = master.UserPlaybackRate;
return container;
}
2018-04-13 17:19:50 +08:00
private void onBreakTimeChanged(ValueChangedEvent<bool> isBreakTime)
{
updateGameplayState();
updatePauseOnFocusLostState();
HUDOverlay.KeyCounter.IsCounting = !isBreakTime.NewValue;
}
private void updateGameplayState()
2020-08-04 03:25:45 +08:00
{
bool inGameplay = !DrawableRuleset.HasReplayLoaded.Value && !DrawableRuleset.IsPaused.Value && !breakTracker.IsBreakTime.Value && !GameplayState.HasFailed;
OverlayActivationMode.Value = inGameplay ? OverlayActivation.Disabled : OverlayActivation.UserTriggered;
localUserPlaying.Value = inGameplay;
2020-08-04 03:25:45 +08:00
}
2020-10-27 13:10:12 +08:00
private void updateSampleDisabledState()
{
samplePlaybackDisabled.Value = DrawableRuleset.FrameStableClock.IsCatchingUp.Value || GameplayClockContainer.GameplayClock.IsPaused.Value;
}
private void updatePauseOnFocusLostState()
{
2021-02-22 21:59:35 +08:00
if (!PauseOnFocusLost || !pausingSupportedByCurrentState || breakTracker.IsBreakTime.Value)
return;
if (gameActive.Value == false)
{
bool paused = Pause();
// if the initial pause could not be satisfied, the pause cooldown may be active.
// reschedule the pause attempt until it can be achieved.
if (!paused)
2021-02-19 16:33:26 +08:00
Scheduler.AddOnce(updatePauseOnFocusLostState);
}
}
private IBeatmap loadPlayableBeatmap(Mod[] gameplayMods)
{
IBeatmap playable;
try
{
if (Beatmap.Value.Beatmap == null)
throw new InvalidOperationException("Beatmap was not loaded");
2018-04-13 17:19:50 +08:00
var rulesetInfo = Ruleset.Value ?? Beatmap.Value.BeatmapInfo.Ruleset;
2021-10-02 01:22:23 +08:00
ruleset = rulesetInfo.CreateInstance();
if (ruleset == null)
throw new RulesetLoadException("Instantiation failure");
try
{
playable = Beatmap.Value.GetPlayableBeatmap(ruleset.RulesetInfo, gameplayMods);
}
catch (BeatmapInvalidForRulesetException)
{
// A playable beatmap may not be creatable with the user's preferred ruleset, so try using the beatmap's default ruleset
rulesetInfo = Beatmap.Value.BeatmapInfo.Ruleset;
2021-10-02 01:22:23 +08:00
ruleset = rulesetInfo.CreateInstance();
playable = Beatmap.Value.GetPlayableBeatmap(rulesetInfo, gameplayMods);
2017-04-06 14:34:52 +08:00
}
2018-04-13 17:19:50 +08:00
if (playable.HitObjects.Count == 0)
{
Logger.Log("Beatmap contains no hit objects!", level: LogLevel.Error);
return null;
}
}
catch (Exception e)
{
Logger.Error(e, "Could not load beatmap successfully!");
//couldn't load, hard abort!
return null;
}
return playable;
}
2018-07-19 00:18:07 +08:00
/// <summary>
/// Attempts to complete a user request to exit gameplay.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item>This should only be called in response to a user interaction. Exiting is not guaranteed.</item>
/// <item>This will interrupt any pending progression to the results screen, even if the transition has begun.</item>
/// </list>
/// </remarks>
2021-02-09 16:14:16 +08:00
/// <param name="showDialogFirst">
/// Whether the pause or fail dialog should be shown before performing an exit.
2021-06-17 22:04:58 +08:00
/// If <see langword="true"/> and a dialog is not yet displayed, the exit will be blocked and the relevant dialog will display instead.
/// </param>
2021-02-09 16:14:16 +08:00
protected void PerformExit(bool showDialogFirst)
{
2021-06-17 22:04:58 +08:00
// if an exit has been requested, cancel any pending completion (the user has shown intention to exit).
resultsDisplayDelegate?.Cancel();
2018-04-13 17:19:50 +08:00
// there is a chance that an exit request occurs after the transition to results has already started.
// even in such a case, the user has shown intent, so forcefully return to this screen (to proceed with the upwards exit process).
2021-05-24 14:14:55 +08:00
if (!this.IsCurrentScreen())
{
ValidForResume = false;
2021-05-24 14:14:55 +08:00
// in the potential case that this instance has already been exited, this is required to avoid a crash.
if (this.GetChildScreen() != null)
this.MakeCurrent();
return;
}
2018-04-13 17:19:50 +08:00
bool pauseOrFailDialogVisible =
PauseOverlay.State.Value == Visibility.Visible || FailOverlay.State.Value == Visibility.Visible;
if (showDialogFirst && !pauseOrFailDialogVisible)
{
// if the fail animation is currently in progress, accelerate it (it will show the pause dialog on completion).
if (ValidForResume && GameplayState.HasFailed)
{
2021-10-15 18:35:08 +08:00
failAnimationLayer.FinishTransforms(true);
return;
}
// even if this call has requested a dialog, there is a chance the current player mode doesn't support pausing.
if (pausingSupportedByCurrentState)
{
// in the case a dialog needs to be shown, attempt to pause and show it.
// this may fail (see internal checks in Pause()) but the fail cases are temporary, so don't fall through to Exit().
Pause();
return;
}
}
// The actual exit is performed if
// - the pause / fail dialog was not requested
// - the pause / fail dialog was requested but is already displayed (user showing intention to exit).
// - the pause / fail dialog was requested but couldn't be displayed due to the type or state of this Player instance.
this.Exit();
}
2018-04-13 17:19:50 +08:00
private void performUserRequestedSkip()
{
// user requested skip
// disable sample playback to stop currently playing samples and perform skip
samplePlaybackDisabled.Value = true;
2021-04-14 16:47:11 +08:00
(GameplayClockContainer as MasterGameplayClockContainer)?.Skip();
// return samplePlaybackDisabled.Value to what is defined by the beatmap's current state
updateSampleDisabledState();
}
2021-05-17 17:41:56 +08:00
/// <summary>
/// Seek to a specific time in gameplay.
/// </summary>
/// <param name="time">The destination time to seek to.</param>
public void Seek(double time) => GameplayClockContainer.Seek(time);
private ScheduledDelegate frameStablePlaybackResetDelegate;
/// <summary>
/// Specify and seek to a custom start time from which gameplay should be observed.
/// </summary>
/// <remarks>
/// This performs a non-frame-stable seek. Intermediate hitobject judgements may not be applied or reverted correctly during this seek.
/// </remarks>
/// <param name="time">The destination time to seek to.</param>
protected void SetGameplayStartTime(double time)
{
if (frameStablePlaybackResetDelegate?.Cancelled == false && !frameStablePlaybackResetDelegate.Completed)
frameStablePlaybackResetDelegate.RunTask();
bool wasFrameStable = DrawableRuleset.FrameStablePlayback;
DrawableRuleset.FrameStablePlayback = false;
GameplayClockContainer.StartTime = time;
GameplayClockContainer.Reset();
// Delay resetting frame-stable playback for one frame to give the FrameStabilityContainer a chance to seek.
frameStablePlaybackResetDelegate = ScheduleAfterChildren(() => DrawableRuleset.FrameStablePlayback = wasFrameStable);
}
2019-11-01 14:51:45 +08:00
/// <summary>
/// Restart gameplay via a parent <see cref="PlayerLoader"/>.
/// <remarks>This can be called from a child screen in order to trigger the restart process.</remarks>
/// </summary>
public void Restart()
{
if (!Configuration.AllowRestart)
return;
// at the point of restarting the track should either already be paused or the volume should be zero.
// stopping here is to ensure music doesn't become audible after exiting back to PlayerLoader.
musicController.Stop();
sampleRestart?.Play();
RestartRequested?.Invoke();
2019-11-01 14:32:06 +08:00
2021-02-09 16:14:16 +08:00
PerformExit(false);
}
2018-04-13 17:19:50 +08:00
/// <summary>
/// This delegate, when set, means the results screen has been queued to appear.
/// The display of the results screen may be delayed by any work being done in <see cref="PrepareScoreForResultsAsync"/>.
/// </summary>
/// <remarks>
/// Once set, this can *only* be cancelled by rewinding, ie. if <see cref="JudgementProcessor.HasCompleted">ScoreProcessor.HasCompleted</see> becomes <see langword="false"/>.
/// Even if the user requests an exit, it will forcefully proceed to the results screen (see special case in <see cref="OnExiting"/>).
/// </remarks>
private ScheduledDelegate resultsDisplayDelegate;
/// <summary>
/// A task which asynchronously prepares a completed score for display at results.
/// This may include performing net requests or importing the score into the database, generally to ensure things are in a sane state for the play session.
/// </summary>
private Task<ScoreInfo> prepareScoreForDisplayTask;
2018-04-13 17:19:50 +08:00
2021-05-04 15:43:51 +08:00
/// <summary>
/// Handles changes in player state which may progress the completion of gameplay / this screen's lifetime.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if this method is called more than once without changing state.</exception>
private void scoreCompletionChanged(ValueChangedEvent<bool> completed)
2016-11-29 22:59:56 +08:00
{
// If this player instance is in the middle of an exit, don't attempt any kind of state update.
if (!this.IsCurrentScreen())
return;
// Special case to handle rewinding post-completion. This is the only way already queued forward progress can be cancelled.
// TODO: Investigate whether this can be moved to a RewindablePlayer subclass or similar.
// Currently, even if this scenario is hit, prepareScoreForDisplay has already been queued (and potentially run).
// In scenarios where rewinding is possible (replay, spectating) this is a non-issue as no submission/import work is done,
// but it still doesn't feel right that this exists here.
if (!completed.NewValue)
{
resultsDisplayDelegate?.Cancel();
resultsDisplayDelegate = null;
GameplayState.HasPassed = false;
ValidForResume = true;
skipOutroOverlay.Hide();
return;
}
// Only show the completion screen if the player hasn't failed
if (HealthProcessor.HasFailed)
return;
2018-04-13 17:19:50 +08:00
GameplayState.HasPassed = true;
// Setting this early in the process means that even if something were to go wrong in the order of events following, there
// is no chance that a user could return to the (already completed) Player instance from a child screen.
ValidForResume = false;
2018-04-13 17:19:50 +08:00
// Ensure we are not writing to the replay any more, as we are about to consume and store the score.
DrawableRuleset.SetRecordTarget(null);
if (!Configuration.ShowResults)
return;
prepareScoreForDisplayTask ??= Task.Run(prepareScoreForResults);
2021-05-04 15:35:50 +08:00
bool storyboardHasOutro = DimmableStoryboard.ContentDisplayed && !DimmableStoryboard.HasStoryboardEnded.Value;
if (storyboardHasOutro)
{
// if the current beatmap has a storyboard, the progression to results will be handled by the storyboard ending
// or the user pressing the skip outro button.
skipOutroOverlay.Show();
return;
}
progressToResults(true);
2016-11-29 22:59:56 +08:00
}
2018-04-13 17:19:50 +08:00
2021-06-18 15:49:43 +08:00
/// <summary>
/// Asynchronously run score preparation operations (database import, online submission etc.).
/// </summary>
/// <returns>The final score.</returns>
2021-06-18 15:46:40 +08:00
private async Task<ScoreInfo> prepareScoreForResults()
{
2021-07-19 18:18:04 +08:00
var scoreCopy = Score.DeepClone();
2021-06-18 15:46:40 +08:00
try
{
2021-07-19 18:18:04 +08:00
await PrepareScoreForResultsAsync(scoreCopy).ConfigureAwait(false);
2021-06-18 15:46:40 +08:00
}
catch (Exception ex)
{
Logger.Error(ex, @"Score preparation failed!");
}
2021-06-18 15:46:40 +08:00
try
{
2021-07-19 18:18:04 +08:00
await ImportScore(scoreCopy).ConfigureAwait(false);
2021-06-18 15:46:40 +08:00
}
catch (Exception ex)
{
Logger.Error(ex, @"Score import failed!");
}
2021-07-19 18:18:04 +08:00
return scoreCopy.ScoreInfo;
2021-06-18 15:46:40 +08:00
}
/// <summary>
/// Queue the results screen for display.
/// </summary>
/// <remarks>
2021-06-18 15:18:20 +08:00
/// A final display will only occur once all work is completed in <see cref="PrepareScoreForResultsAsync"/>. This means that even after calling this method, the results screen will never be shown until <see cref="JudgementProcessor.HasCompleted">ScoreProcessor.HasCompleted</see> becomes <see langword="true"/>.
///
/// Calling this method multiple times will have no effect.
/// </remarks>
/// <param name="withDelay">Whether a minimum delay (<see cref="RESULTS_DISPLAY_DELAY"/>) should be added before the screen is displayed.</param>
private void progressToResults(bool withDelay)
{
if (resultsDisplayDelegate != null)
2021-06-18 15:18:20 +08:00
// Note that if progressToResults is called one withDelay=true and then withDelay=false, this no-delay timing will not be
// accounted for. shouldn't be a huge concern (a user pressing the skip button after a results progression has already been queued
// may take x00 more milliseconds than expected in the very rare edge case).
//
// If required we can handle this more correctly by rescheduling here.
return;
double delay = withDelay ? RESULTS_DISPLAY_DELAY : 0;
resultsDisplayDelegate = new ScheduledDelegate(() =>
{
if (prepareScoreForDisplayTask?.IsCompleted != true)
2021-06-18 15:18:20 +08:00
// If the asynchronous preparation has not completed, keep repeating this delegate.
return;
resultsDisplayDelegate?.Cancel();
if (!this.IsCurrentScreen())
// This player instance may already be in the process of exiting.
return;
2022-01-06 21:54:43 +08:00
this.Push(CreateResults(prepareScoreForDisplayTask.GetResultSafely()));
}, Time.Current + delay, 50);
Scheduler.Add(resultsDisplayDelegate);
2016-11-29 22:59:56 +08:00
}
protected override bool OnScroll(ScrollEvent e)
{
// During pause, allow global volume adjust regardless of settings.
if (GameplayClockContainer.IsPaused.Value)
return false;
// Block global volume adjust if the user has asked for it (special case when holding "Alt").
return mouseWheelDisabled.Value && !e.AltPressed;
}
2019-03-18 10:48:11 +08:00
#region Fail Logic
protected FailOverlay FailOverlay { get; private set; }
2021-10-15 18:35:08 +08:00
private FailAnimation failAnimationLayer;
2019-06-04 15:13:16 +08:00
2017-08-05 10:59:58 +08:00
private bool onFail()
2017-01-20 15:51:43 +08:00
{
if (!CheckModsAllowFailure())
2017-08-05 10:59:58 +08:00
return false;
2018-04-13 17:19:50 +08:00
GameplayState.HasFailed = true;
2021-07-01 16:38:28 +08:00
Score.ScoreInfo.Passed = false;
updateGameplayState();
2019-03-18 10:48:11 +08:00
// There is a chance that we could be in a paused state as the ruleset's internal clock (see FrameStabilityContainer)
// could process an extra frame after the GameplayClock is stopped.
// In such cases we want the fail state to precede a user triggered pause.
if (PauseOverlay.State.Value == Visibility.Visible)
2019-03-18 10:48:11 +08:00
PauseOverlay.Hide();
2021-10-15 18:35:08 +08:00
failAnimationLayer.Start();
if (GameplayState.Mods.OfType<IApplicableFailOverride>().Any(m => m.RestartOnFail))
2018-10-14 23:18:52 +08:00
Restart();
2017-08-05 10:59:58 +08:00
return true;
2017-01-20 15:51:43 +08:00
}
2018-04-13 17:19:50 +08:00
2019-06-04 15:13:16 +08:00
// Called back when the transform finishes
private void onFailComplete()
{
GameplayClockContainer.Stop();
2019-03-18 10:48:11 +08:00
FailOverlay.Retries = RestartCount;
FailOverlay.Show();
2017-01-20 15:51:43 +08:00
}
2018-04-13 17:19:50 +08:00
2019-03-18 10:48:11 +08:00
#endregion
#region Pause Logic
public bool IsResuming { get; private set; }
/// <summary>
/// The amount of gameplay time after which a second pause is allowed.
/// </summary>
private const double pause_cooldown = 1000;
protected PauseOverlay PauseOverlay { get; private set; }
private double? lastPauseActionTime;
protected bool PauseCooldownActive =>
2021-02-19 14:34:39 +08:00
lastPauseActionTime.HasValue && GameplayClockContainer.GameplayClock.CurrentTime < lastPauseActionTime + pause_cooldown;
/// <summary>
/// A set of conditionals which defines whether the current game state and configuration allows for
/// pausing to be attempted via <see cref="Pause"/>. If false, the game should generally exit if a user pause
/// is attempted.
/// </summary>
private bool pausingSupportedByCurrentState =>
2019-03-18 10:48:11 +08:00
// must pass basic screen conditions (beatmap loaded, instance allows pause)
LoadedBeatmapSuccessfully && Configuration.AllowPause && ValidForResume
2019-03-18 10:48:11 +08:00
// replays cannot be paused and exit immediately
&& !DrawableRuleset.HasReplayLoaded.Value
2019-03-18 10:48:11 +08:00
// cannot pause if we are already in a fail state
&& !GameplayState.HasFailed;
2019-03-18 10:48:11 +08:00
private bool canResume =>
// cannot resume from a non-paused state
GameplayClockContainer.IsPaused.Value
// cannot resume if we are already in a fail state
&& !GameplayState.HasFailed
2019-03-18 10:48:11 +08:00
// already resuming
&& !IsResuming;
public bool Pause()
2019-03-18 10:48:11 +08:00
{
if (!pausingSupportedByCurrentState) return false;
if (!IsResuming && PauseCooldownActive)
return false;
2019-03-18 10:48:11 +08:00
2019-10-26 03:57:49 +08:00
if (IsResuming)
{
DrawableRuleset.CancelResume();
2019-11-01 13:43:52 +08:00
IsResuming = false;
2019-10-26 03:57:49 +08:00
}
2019-03-18 10:48:11 +08:00
GameplayClockContainer.Stop();
PauseOverlay.Show();
lastPauseActionTime = GameplayClockContainer.GameplayClock.CurrentTime;
return true;
2019-03-18 10:48:11 +08:00
}
public void Resume()
{
if (!canResume) return;
IsResuming = true;
PauseOverlay.Hide();
// breaks and time-based conditions may allow instant resume.
if (breakTracker.IsBreakTime.Value)
completeResume();
else
DrawableRuleset.RequestResume(completeResume);
void completeResume()
{
GameplayClockContainer.Start();
IsResuming = false;
}
2019-03-18 10:48:11 +08:00
}
#endregion
#region Screen Logic
public override void OnEntering(ScreenTransitionEvent e)
{
base.OnEntering(e);
2018-04-13 17:19:50 +08:00
if (!LoadedBeatmapSuccessfully)
2017-07-19 18:10:04 +08:00
return;
2018-04-13 17:19:50 +08:00
2019-01-23 19:52:00 +08:00
Alpha = 0;
this
2017-07-16 23:28:20 +08:00
.ScaleTo(0.7f)
2017-07-23 02:50:25 +08:00
.ScaleTo(1, 750, Easing.OutQuint)
2017-07-16 23:28:20 +08:00
.Delay(250)
.FadeIn(250);
2018-04-13 17:19:50 +08:00
ApplyToBackground(b =>
{
b.IgnoreUserSettings.Value = false;
b.BlurAmount.Value = 0;
b.FadeColour(Color4.White, 250);
// bind component bindables.
b.IsBreakTime.BindTo(breakTracker.IsBreakTime);
b.StoryboardReplacesBackground.BindTo(storyboardReplacesBackground);
failAnimationLayer.Background = b;
});
2018-04-13 17:19:50 +08:00
HUDOverlay.IsPlaying.BindTo(localUserPlaying);
DimmableStoryboard.IsBreakTime.BindTo(breakTracker.IsBreakTime);
2019-12-11 04:06:13 +08:00
DimmableStoryboard.StoryboardReplacesBackground.BindTo(storyboardReplacesBackground);
2018-04-13 17:19:50 +08:00
storyboardReplacesBackground.Value = Beatmap.Value.Storyboard.ReplacesBackground && Beatmap.Value.Storyboard.HasDrawable;
foreach (var mod in GameplayState.Mods.OfType<IApplicableToPlayer>())
mod.ApplyToPlayer(this);
foreach (var mod in GameplayState.Mods.OfType<IApplicableToHUD>())
2019-06-29 09:23:59 +08:00
mod.ApplyToHUD(HUDOverlay);
// Our mods are local copies of the global mods so they need to be re-applied to the track.
// This is done through the music controller (for now), because resetting speed adjustments on the beatmap track also removes adjustments provided by DrawableTrack.
// Todo: In the future, player will receive in a track and will probably not have to worry about this...
musicController.ResetTrackAdjustments();
foreach (var mod in GameplayState.Mods.OfType<IApplicableToTrack>())
mod.ApplyToTrack(musicController.CurrentTrack);
2020-09-04 03:56:47 +08:00
updateGameplayState();
GameplayClockContainer.FadeInFromZero(750, Easing.OutQuint);
2021-08-11 17:16:25 +08:00
StartGameplay();
2021-08-11 17:16:25 +08:00
OnGameplayStarted?.Invoke();
}
/// <summary>
/// Called to trigger the starting of the gameplay clock and underlying gameplay.
/// This will be called on entering the player screen once. A derived class may block the first call to this to delay the start of gameplay.
/// </summary>
protected virtual void StartGameplay()
{
if (GameplayClockContainer.GameplayClock.IsRunning)
throw new InvalidOperationException($"{nameof(StartGameplay)} should not be called when the gameplay clock is already running");
GameplayClockContainer.Reset(true);
}
2018-04-13 17:19:50 +08:00
public override void OnSuspending(ScreenTransitionEvent e)
{
screenSuspension?.RemoveAndDisposeImmediately();
fadeOut();
base.OnSuspending(e);
}
2018-04-13 17:19:50 +08:00
public override bool OnExiting(ScreenExitEvent e)
2016-12-17 00:13:24 +08:00
{
screenSuspension?.RemoveAndDisposeImmediately();
2021-10-15 20:22:38 +08:00
failAnimationLayer?.RemoveFilters();
if (LoadedBeatmapSuccessfully)
{
if (!GameplayState.HasPassed && !GameplayState.HasFailed)
GameplayState.HasQuit = true;
// if arriving here and the results screen preparation task hasn't run, it's safe to say the user has not completed the beatmap.
if (prepareScoreForDisplayTask == null)
{
Score.ScoreInfo.Passed = false;
// potentially should be ScoreRank.F instead? this is the best alternative for now.
Score.ScoreInfo.Rank = ScoreRank.D;
}
2021-07-01 16:38:28 +08:00
// EndPlaying() is typically called from ReplayRecorder.Dispose(). Disposal is currently asynchronous.
// To resolve test failures, forcefully end playing synchronously when this screen exits.
// Todo: Replace this with a more permanent solution once osu-framework has a synchronous cleanup method.
spectatorClient.EndPlaying(GameplayState);
}
// GameplayClockContainer performs seeks / start / stop operations on the beatmap's track.
// as we are no longer the current screen, we cannot guarantee the track is still usable.
2021-04-14 16:47:11 +08:00
(GameplayClockContainer as MasterGameplayClockContainer)?.StopUsingBeatmapClock();
musicController.ResetTrackAdjustments();
2020-09-01 15:55:10 +08:00
fadeOut();
return base.OnExiting(e);
2016-12-17 00:13:24 +08:00
}
2018-04-13 17:19:50 +08:00
2020-12-18 16:47:33 +08:00
/// <summary>
/// Creates the player's <see cref="Scoring.Score"/>.
2020-12-18 16:47:33 +08:00
/// </summary>
2021-10-05 13:48:10 +08:00
/// <param name="beatmap"></param>
/// <returns>The <see cref="Scoring.Score"/>.</returns>
2021-10-05 13:48:10 +08:00
protected virtual Score CreateScore(IBeatmap beatmap) => new Score
{
ScoreInfo = new ScoreInfo { User = api.LocalUser.Value },
};
2020-12-18 14:36:24 +08:00
2020-12-18 16:47:33 +08:00
/// <summary>
/// Imports the player's <see cref="Scoring.Score"/> to the local database.
2020-12-18 16:47:33 +08:00
/// </summary>
/// <param name="score">The <see cref="Scoring.Score"/> to import.</param>
/// <returns>The imported score.</returns>
protected virtual Task ImportScore(Score score)
{
// Replays are already populated and present in the game's database, so should not be re-imported.
if (DrawableRuleset.ReplayScore != null)
return Task.CompletedTask;
LegacyByteArrayReader replayReader;
using (var stream = new MemoryStream())
{
2021-10-02 01:22:23 +08:00
new LegacyScoreEncoder(score, GameplayState.Beatmap).Encode(stream);
replayReader = new LegacyByteArrayReader(stream.ToArray(), "replay.osr");
}
// the import process will re-attach managed beatmap/rulesets to this score. we don't want this for now, so create a temporary copy to import.
var importableScore = score.ScoreInfo.DeepClone();
// For the time being, online ID responses are not really useful for anything.
// In addition, the IDs provided via new (lazer) endpoints are based on a different autoincrement from legacy (stable) scores.
//
// Until we better define the server-side logic behind this, let's not store the online ID to avoid potential unique constraint
// conflicts across various systems (ie. solo and multiplayer).
importableScore.OnlineID = -1;
var imported = scoreManager.Import(importableScore, replayReader);
imported.PerformRead(s =>
{
// because of the clone above, it's required that we copy back the post-import hash/ID to use for availability matching.
score.ScoreInfo.Hash = s.Hash;
score.ScoreInfo.ID = s.ID;
});
return Task.CompletedTask;
}
/// <summary>
/// Prepare the <see cref="Scoring.Score"/> for display at results.
/// </summary>
/// <param name="score">The <see cref="Scoring.Score"/> to prepare.</param>
/// <returns>A task that prepares the provided score. On completion, the score is assumed to be ready for display.</returns>
protected virtual Task PrepareScoreForResultsAsync(Score score) => Task.CompletedTask;
2020-12-18 16:47:33 +08:00
/// <summary>
/// Creates the <see cref="ResultsScreen"/> for a <see cref="ScoreInfo"/>.
/// </summary>
/// <param name="score">The <see cref="ScoreInfo"/> to be displayed in the results screen.</param>
/// <returns>The <see cref="ResultsScreen"/>.</returns>
2020-12-18 14:36:24 +08:00
protected virtual ResultsScreen CreateResults(ScoreInfo score) => new SoloResultsScreen(score, true);
private void fadeOut(bool instant = false)
2017-09-14 20:28:53 +08:00
{
float fadeOutDuration = instant ? 0 : 250;
2019-01-23 19:52:00 +08:00
this.FadeOut(fadeOutDuration);
2018-04-13 17:19:50 +08:00
ApplyToBackground(b => b.IgnoreUserSettings.Value = true);
storyboardReplacesBackground.Value = false;
2017-09-14 20:28:53 +08:00
}
2018-04-13 17:19:50 +08:00
2019-03-18 10:48:11 +08:00
#endregion
IBindable<bool> ISamplePlaybackDisabler.SamplePlaybackDisabled => samplePlaybackDisabled;
IBindable<bool> ILocalUserPlayInfo.IsPlaying => LocalUserPlaying;
2016-09-29 19:13:58 +08:00
}
2017-04-11 23:09:45 +08:00
}