1
0
mirror of https://github.com/ppy/osu.git synced 2024-09-21 16:07:24 +08:00

Merge remote-tracking branch 'upstream/master' into tournament-tools

This commit is contained in:
Dean Herbert 2018-12-20 15:57:20 +09:00
commit bb4b54799f
65 changed files with 879 additions and 881 deletions

View File

@ -1,17 +1,20 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="osu!" type="DotNetProject" factoryName=".NET Project">
<option name="EXE_PATH" value="$PROJECT_DIR$/osu.Desktop/bin/Debug/netcoreapp2.1/osu!.dll" />
<option name="EXE_PATH" value="$PROJECT_DIR$/osu.Desktop/bin/Debug/netcoreapp2.2/osu!.dll" />
<option name="PROGRAM_PARAMETERS" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/osu.Desktop" />
<option name="PASS_PARENT_ENVS" value="1" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="PROJECT_PATH" value="$PROJECT_DIR$/osu.Desktop/osu.Desktop.csproj" />
<option name="PROJECT_EXE_PATH_TRACKING" value="1" />
<option name="PROJECT_ARGUMENTS_TRACKING" value="1" />
<option name="PROJECT_WORKING_DIRECTORY_TRACKING" value="1" />
<option name="PROJECT_KIND" value="DotNetCore" />
<option name="PROJECT_TFM" value=".NETCoreApp,Version=v2.1" />
<method />
<option name="PROJECT_TFM" value=".NETCoreApp,Version=v2.2" />
<method v="2">
<option name="Build" enabled="true" />
</method>
</configuration>
</component>

View File

@ -41,24 +41,32 @@ namespace osu.Desktop.Updater
private async void checkForUpdateAsync()
{
var releases = new JsonWebRequest<GitHubRelease>("https://api.github.com/repos/ppy/osu/releases/latest");
await releases.PerformAsync();
var latest = releases.ResponseObject;
if (latest.TagName != version)
try
{
notificationOverlay.Post(new SimpleNotification
var releases = new JsonWebRequest<GitHubRelease>("https://api.github.com/repos/ppy/osu/releases/latest");
await releases.PerformAsync();
var latest = releases.ResponseObject;
if (latest.TagName != version)
{
Text = $"A newer release of osu! has been found ({version} → {latest.TagName}).\n\n"
+ "Click here to download the new version, which can be installed over the top of your existing installation",
Icon = FontAwesome.fa_upload,
Activated = () =>
notificationOverlay.Post(new SimpleNotification
{
host.OpenUrlExternally(getBestUrl(latest));
return true;
}
});
Text = $"A newer release of osu! has been found ({version} → {latest.TagName}).\n\n"
+ "Click here to download the new version, which can be installed over the top of your existing installation",
Icon = FontAwesome.fa_upload,
Activated = () =>
{
host.OpenUrlExternally(getBestUrl(latest));
return true;
}
});
}
}
catch
{
// we shouldn't crash on a web failure. or any failure for the matter.
}
}

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\osu.Game.props" />
<PropertyGroup Label="Project">
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>netcoreapp2.2</TargetFramework>
<OutputType>WinExe</OutputType>
<PlatformTarget>AnyCPU</PlatformTarget>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
@ -29,8 +29,8 @@
<ItemGroup Label="Package References">
<PackageReference Include="System.IO.Packaging" Version="4.5.0" />
<PackageReference Include="ppy.squirrel.windows" Version="1.9.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.0" />
</ItemGroup>
<ItemGroup Label="Resources">
<EmbeddedResource Include="lazer.ico" />

View File

@ -4,12 +4,12 @@
<PackageReference Include="Appveyor.TestLogger" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.11.2" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />
</ItemGroup>
<PropertyGroup Label="Project">
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\osu.Game.Rulesets.Catch\osu.Game.Rulesets.Catch.csproj" />

View File

@ -21,7 +21,7 @@ namespace osu.Game.Rulesets.Catch.Judgements
}
}
protected override float HealthIncreaseFor(HitResult result)
protected override double HealthIncreaseFor(HitResult result)
{
switch (result)
{

View File

@ -18,7 +18,7 @@ namespace osu.Game.Rulesets.Catch.Judgements
}
}
protected override float HealthIncreaseFor(HitResult result)
protected override double HealthIncreaseFor(HitResult result)
{
switch (result)
{

View File

@ -22,29 +22,17 @@ namespace osu.Game.Rulesets.Catch.Judgements
}
}
/// <summary>
/// Retrieves the numeric health increase of a <see cref="HitResult"/>.
/// </summary>
/// <param name="result">The <see cref="HitResult"/> to find the numeric health increase for.</param>
/// <returns>The numeric health increase of <paramref name="result"/>.</returns>
protected virtual float HealthIncreaseFor(HitResult result)
protected override double HealthIncreaseFor(HitResult result)
{
switch (result)
{
default:
return 0;
case HitResult.Perfect:
return 10.2f;
return 10.2;
}
}
/// <summary>
/// Retrieves the numeric health increase of a <see cref="JudgementResult"/>.
/// </summary>
/// <param name="result">The <see cref="JudgementResult"/> to find the numeric health increase for.</param>
/// <returns>The numeric health increase of <paramref name="result"/>.</returns>
public float HealthIncreaseFor(JudgementResult result) => HealthIncreaseFor(result.Type);
/// <summary>
/// Whether fruit on the platter should explode or drop.
/// Note that this is only checked if the owning object is also <see cref="IHasComboInformation.LastInCombo" />

View File

@ -20,7 +20,7 @@ namespace osu.Game.Rulesets.Catch.Judgements
}
}
protected override float HealthIncreaseFor(HitResult result)
protected override double HealthIncreaseFor(HitResult result)
{
switch (result)
{

View File

@ -3,7 +3,6 @@
using System;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Judgements;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
@ -40,8 +39,7 @@ namespace osu.Game.Rulesets.Catch.Scoring
return;
}
if (result.Judgement is CatchJudgement catchJudgement)
Health.Value += Math.Max(catchJudgement.HealthIncreaseFor(result) - hpDrainRate, 0) * harshness;
Health.Value += Math.Max(result.Judgement.HealthIncreaseFor(result) - hpDrainRate, 0) * harshness;
}
}
}

View File

@ -4,12 +4,12 @@
<PackageReference Include="Appveyor.TestLogger" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.11.2" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />
</ItemGroup>
<PropertyGroup Label="Project">
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\osu.Game.Rulesets.Mania\osu.Game.Rulesets.Mania.csproj" />

View File

@ -20,11 +20,10 @@ namespace osu.Game.Rulesets.Mania.Objects
{ HitResult.Miss, (376, 346, 316) },
};
public override bool IsHitResultAllowed(HitResult result) => true;
public override void SetDifficulty(double difficulty)
{
AllowsPerfect = true;
AllowsOk = true;
Perfect = BeatmapDifficulty.DifficultyRange(difficulty, base_ranges[HitResult.Perfect]);
Great = BeatmapDifficulty.DifficultyRange(difficulty, base_ranges[HitResult.Great]);
Good = BeatmapDifficulty.DifficultyRange(difficulty, base_ranges[HitResult.Good]);

View File

@ -4,12 +4,12 @@
<PackageReference Include="Appveyor.TestLogger" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.11.2" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />
</ItemGroup>
<PropertyGroup Label="Project">
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\osu.Game.Rulesets.Osu\osu.Game.Rulesets.Osu.csproj" />

View File

@ -4,12 +4,12 @@
<PackageReference Include="Appveyor.TestLogger" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.11.2" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />
</ItemGroup>
<PropertyGroup Label="Project">
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\osu.Game.Rulesets.Taiko\osu.Game.Rulesets.Taiko.csproj" />

View File

@ -0,0 +1,24 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Taiko.Judgements
{
public class TaikoDrumRollJudgement : TaikoJudgement
{
public override bool AffectsCombo => false;
protected override double HealthIncreaseFor(HitResult result)
{
// Drum rolls can be ignored with no health penalty
switch (result)
{
case HitResult.Miss:
return 0;
default:
return base.HealthIncreaseFor(result);
}
}
}
}

View File

@ -13,10 +13,21 @@ namespace osu.Game.Rulesets.Taiko.Judgements
{
switch (result)
{
default:
return 0;
case HitResult.Great:
return 200;
default:
return 0;
}
}
protected override double HealthIncreaseFor(HitResult result)
{
switch (result)
{
case HitResult.Great:
return 0.15;
default:
return 0;
}
}
}

View File

@ -1,21 +0,0 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Taiko.Judgements
{
public class TaikoIntermediateSwellJudgement : TaikoJudgement
{
public override HitResult MaxResult => HitResult.Great;
public override bool AffectsCombo => false;
/// <summary>
/// Computes the numeric result value for the combo portion of the score.
/// </summary>
/// <param name="result">The result to compute the value for.</param>
/// <returns>The numeric result value.</returns>
protected override int NumericResultFor(HitResult result) => 0;
}
}

View File

@ -10,21 +10,31 @@ namespace osu.Game.Rulesets.Taiko.Judgements
{
public override HitResult MaxResult => HitResult.Great;
/// <summary>
/// Computes the numeric result value for the combo portion of the score.
/// </summary>
/// <param name="result">The result to compute the value for.</param>
/// <returns>The numeric result value.</returns>
protected override int NumericResultFor(HitResult result)
{
switch (result)
{
default:
return 0;
case HitResult.Good:
return 100;
case HitResult.Great:
return 300;
default:
return 0;
}
}
protected override double HealthIncreaseFor(HitResult result)
{
switch (result)
{
case HitResult.Miss:
return -1.0;
case HitResult.Good:
return 1.1;
case HitResult.Great:
return 3.0;
default:
return 0;
}
}
}

View File

@ -1,10 +1,15 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Taiko.Judgements
{
public class TaikoStrongJudgement : TaikoJudgement
{
// MainObject already changes the HP
protected override double HealthIncreaseFor(HitResult result) => 0;
public override bool AffectsCombo => false;
}
}

View File

@ -0,0 +1,23 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Taiko.Judgements
{
public class TaikoSwellJudgement : TaikoJudgement
{
public override bool AffectsCombo => false;
protected override double HealthIncreaseFor(HitResult result)
{
switch (result)
{
case HitResult.Miss:
return -0.65;
default:
return 0;
}
}
}
}

View File

@ -0,0 +1,16 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Taiko.Judgements
{
public class TaikoSwellTickJudgement : TaikoJudgement
{
public override bool AffectsCombo => false;
protected override int NumericResultFor(HitResult result) => 0;
protected override double HealthIncreaseFor(HitResult result) => 0;
}
}

View File

@ -173,13 +173,13 @@ namespace osu.Game.Rulesets.Taiko.Objects.Drawables
if (!userTriggered)
{
if (timeOffset > second_hit_window)
if (timeOffset - MainObject.Result.TimeOffset > second_hit_window)
ApplyResult(r => r.Type = HitResult.Miss);
return;
}
if (Math.Abs(MainObject.Result.TimeOffset - timeOffset) < second_hit_window)
ApplyResult(r => r.Type = HitResult.Great);
if (Math.Abs(timeOffset - MainObject.Result.TimeOffset) <= second_hit_window)
ApplyResult(r => r.Type = MainObject.Result.Type);
}
public override bool OnPressed(TaikoAction action)

View File

@ -6,11 +6,11 @@ using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Taiko.Objects.Drawables
{
public class DrawableSwellTick : DrawableTaikoHitObject
public class DrawableSwellTick : DrawableTaikoHitObject<SwellTick>
{
public override bool DisplayResult => false;
public DrawableSwellTick(TaikoHitObject hitObject)
public DrawableSwellTick(SwellTick hitObject)
: base(hitObject)
{
}

View File

@ -5,6 +5,8 @@ using osu.Game.Rulesets.Objects.Types;
using System;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Taiko.Judgements;
namespace osu.Game.Rulesets.Taiko.Objects
{
@ -81,5 +83,7 @@ namespace osu.Game.Rulesets.Taiko.Objects
first = false;
}
}
public override Judgement CreateJudgement() => new TaikoDrumRollJudgement();
}
}

View File

@ -3,6 +3,8 @@
using System;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Taiko.Judgements;
namespace osu.Game.Rulesets.Taiko.Objects
{
@ -26,5 +28,7 @@ namespace osu.Game.Rulesets.Taiko.Objects
for (int i = 0; i < RequiredHits; i++)
AddNested(new SwellTick());
}
public override Judgement CreateJudgement() => new TaikoSwellJudgement();
}
}

View File

@ -1,9 +1,13 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Taiko.Judgements;
namespace osu.Game.Rulesets.Taiko.Objects
{
public class SwellTick : TaikoHitObject
{
public override Judgement CreateJudgement() => new TaikoSwellTickJudgement();
}
}

View File

@ -14,15 +14,26 @@ namespace osu.Game.Rulesets.Taiko.Objects
{
{ HitResult.Great, (100, 70, 40) },
{ HitResult.Good, (240, 160, 100) },
{ HitResult.Meh, (270, 190, 140) },
{ HitResult.Miss, (400, 400, 400) },
{ HitResult.Miss, (270, 190, 140) },
};
public override bool IsHitResultAllowed(HitResult result)
{
switch (result)
{
case HitResult.Great:
case HitResult.Good:
case HitResult.Miss:
return true;
default:
return false;
}
}
public override void SetDifficulty(double difficulty)
{
Great = BeatmapDifficulty.DifficultyRange(difficulty, base_ranges[HitResult.Great]);
Good = BeatmapDifficulty.DifficultyRange(difficulty, base_ranges[HitResult.Good]);
Meh = BeatmapDifficulty.DifficultyRange(difficulty, base_ranges[HitResult.Meh]);
Miss = BeatmapDifficulty.DifficultyRange(difficulty, base_ranges[HitResult.Miss]);
}
}

View File

@ -4,7 +4,6 @@
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.Taiko.Judgements;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.UI;
@ -13,51 +12,24 @@ namespace osu.Game.Rulesets.Taiko.Scoring
internal class TaikoScoreProcessor : ScoreProcessor<TaikoHitObject>
{
/// <summary>
/// The HP awarded by a <see cref="HitResult.Great"/> hit.
/// A value used for calculating <see cref="hpMultiplier"/>.
/// </summary>
private const double hp_hit_great = 0.03;
/// <summary>
/// The HP awarded for a <see cref="HitResult.Good"/> hit.
/// </summary>
private const double hp_hit_good = 0.011;
/// <summary>
/// The minimum HP deducted for a <see cref="HitResult.Miss"/>.
/// This occurs when HP Drain = 0.
/// </summary>
private const double hp_miss_min = -0.0018;
/// <summary>
/// The median HP deducted for a <see cref="HitResult.Miss"/>.
/// This occurs when HP Drain = 5.
/// </summary>
private const double hp_miss_mid = -0.0075;
/// <summary>
/// The maximum HP deducted for a <see cref="HitResult.Miss"/>.
/// This occurs when HP Drain = 10.
/// </summary>
private const double hp_miss_max = -0.12;
/// <summary>
/// The HP awarded for a <see cref="DrumRollTick"/> hit.
/// <para>
/// <see cref="DrumRollTick"/> hits award less HP as they're more spammable, although in hindsight
/// this probably awards too little HP and is kept at this value for now for compatibility.
/// </para>
/// </summary>
private const double hp_hit_tick = 0.00000003;
private const double object_count_factor = 3;
/// <summary>
/// Taiko fails at the end of the map if the player has not half-filled their HP bar.
/// </summary>
protected override bool DefaultFailCondition => JudgedHits == MaxHits && Health.Value <= 0.5;
private double hpIncreaseTick;
private double hpIncreaseGreat;
private double hpIncreaseGood;
private double hpIncreaseMiss;
/// <summary>
/// HP multiplier for a successful <see cref="HitResult"/>.
/// </summary>
private double hpMultiplier;
/// <summary>
/// HP multiplier for a <see cref="HitResult.Miss"/>.
/// </summary>
private double hpMissMultiplier;
public TaikoScoreProcessor(RulesetContainer<TaikoHitObject> rulesetContainer)
: base(rulesetContainer)
@ -68,38 +40,23 @@ namespace osu.Game.Rulesets.Taiko.Scoring
{
base.ApplyBeatmap(beatmap);
double hpMultiplierNormal = 1 / (hp_hit_great * beatmap.HitObjects.FindAll(o => o is Hit).Count * BeatmapDifficulty.DifficultyRange(beatmap.BeatmapInfo.BaseDifficulty.DrainRate, 0.5, 0.75, 0.98));
hpMultiplier = 1 / (object_count_factor * beatmap.HitObjects.FindAll(o => o is Hit).Count * BeatmapDifficulty.DifficultyRange(beatmap.BeatmapInfo.BaseDifficulty.DrainRate, 0.5, 0.75, 0.98));
hpIncreaseTick = hp_hit_tick;
hpIncreaseGreat = hpMultiplierNormal * hp_hit_great;
hpIncreaseGood = hpMultiplierNormal * hp_hit_good;
hpIncreaseMiss = BeatmapDifficulty.DifficultyRange(beatmap.BeatmapInfo.BaseDifficulty.DrainRate, hp_miss_min, hp_miss_mid, hp_miss_max);
hpMissMultiplier = BeatmapDifficulty.DifficultyRange(beatmap.BeatmapInfo.BaseDifficulty.DrainRate, 0.0018, 0.0075, 0.0120);
}
protected override void ApplyResult(JudgementResult result)
{
base.ApplyResult(result);
bool isTick = result.Judgement is TaikoDrumRollTickJudgement;
double hpIncrease = result.Judgement.HealthIncreaseFor(result);
// Apply HP changes
switch (result.Type)
{
case HitResult.Miss:
// Missing ticks shouldn't drop HP
if (!isTick)
Health.Value += hpIncreaseMiss;
break;
case HitResult.Good:
Health.Value += hpIncreaseGood;
break;
case HitResult.Great:
if (isTick)
Health.Value += hpIncreaseTick;
else
Health.Value += hpIncreaseGreat;
break;
}
if (result.Type == HitResult.Miss)
hpIncrease *= hpMissMultiplier;
else
hpIncrease *= hpMultiplier;
Health.Value += hpIncrease;
}
protected override void Reset(bool storeResults)

View File

@ -295,6 +295,9 @@ namespace osu.Game.Tests.Beatmaps.Formats
Assert.AreEqual("normal-hitnormal", getTestableSampleInfo(hitObjects[1]).LookupNames.First());
Assert.AreEqual("normal-hitnormal2", getTestableSampleInfo(hitObjects[2]).LookupNames.First());
Assert.AreEqual("normal-hitnormal", getTestableSampleInfo(hitObjects[3]).LookupNames.First());
// The control point at the end time of the slider should be applied
Assert.AreEqual("soft-hitnormal8", getTestableSampleInfo(hitObjects[4]).LookupNames.First());
}
SampleInfo getTestableSampleInfo(HitObject hitObject) => hitObject.SampleControlPoint.ApplyTo(hitObject.Samples[0]);

View File

@ -8,9 +8,12 @@ SampleSet: Normal
2638,-100,4,1,1,40,0,0
3107,-100,4,1,2,40,0,0
3576,-100,4,1,0,40,0,0
18287,-100,4,2,11,80,0,1
18595,-100,4,2,8,80,0,1
[HitObjects]
255,193,2170,1,0,0:0:0:0:
256,191,2638,5,0,0:0:0:0:
255,193,3107,1,0,0:0:0:0:
256,191,3576,1,0,0:0:0:0:
112,200,18493,6,0,L|104:248,1,35,8|0,0:0|0:0,0:0:0:0:

View File

@ -100,7 +100,7 @@ namespace osu.Game.Tests.Scores.IO
var toImport = new ScoreInfo
{
Statistics = new Dictionary<HitResult, object>
Statistics = new Dictionary<HitResult, int>
{
{ HitResult.Perfect, 100 },
{ HitResult.Miss, 50 }

View File

@ -4,15 +4,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.MathUtils;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.Chat;
using osu.Game.Overlays.Chat.Tabs;
using osu.Game.Users;
@ -74,50 +71,50 @@ namespace osu.Game.Tests.Visual
channelTabControl.OnRequestLeave += channel => channelTabControl.RemoveChannel(channel);
channelTabControl.Current.ValueChanged += channel => currentText.Text = "Currently selected channel: " + channel.ToString();
AddStep("Add random private channel", addRandomUser);
AddStep("Add random private channel", addRandomPrivateChannel);
AddAssert("There is only one channels", () => channelTabControl.Items.Count() == 2);
AddRepeatStep("Add 3 random private channels", addRandomUser, 3);
AddRepeatStep("Add 3 random private channels", addRandomPrivateChannel, 3);
AddAssert("There are four channels", () => channelTabControl.Items.Count() == 5);
AddStep("Add random public channel", () => addChannel(RNG.Next().ToString()));
AddRepeatStep("Select a random channel", () => channelTabControl.Current.Value = channelTabControl.Items.ElementAt(RNG.Next(channelTabControl.Items.Count())), 20);
}
AddRepeatStep("Select a random channel", () => channelTabControl.Current.Value = channelTabControl.Items.ElementAt(RNG.Next(channelTabControl.Items.Count() - 1)), 20);
private List<User> users;
Channel channelBefore = channelTabControl.Items.First();
AddStep("set first channel", () => channelTabControl.Current.Value = channelBefore);
private void addRandomUser()
{
channelTabControl.AddChannel(new Channel
AddStep("select selector tab", () => channelTabControl.Current.Value = channelTabControl.Items.Last());
AddAssert("selector tab is active", () => channelTabControl.ChannelSelectorActive.Value);
AddAssert("check channel unchanged", () => channelBefore == channelTabControl.Current.Value);
AddStep("set second channel", () => channelTabControl.Current.Value = channelTabControl.Items.Skip(1).First());
AddAssert("selector tab is inactive", () => !channelTabControl.ChannelSelectorActive.Value);
AddUntilStep(() =>
{
Users =
{
users?.Count > 0
? users[RNG.Next(0, users.Count - 1)]
: new User
{
Id = RNG.Next(),
Username = "testuser" + RNG.Next(1000)
}
}
});
var first = channelTabControl.Items.First();
if (first.Name == "+")
return true;
channelTabControl.RemoveChannel(first);
return false;
}, "remove all channels");
AddAssert("selector tab is active", () => channelTabControl.ChannelSelectorActive.Value);
}
private void addChannel(string name)
{
private void addRandomPrivateChannel() =>
channelTabControl.AddChannel(new Channel(new User
{
Id = RNG.Next(1000, 10000000),
Username = "Test User " + RNG.Next(1000)
}));
private void addChannel(string name) =>
channelTabControl.AddChannel(new Channel
{
Type = ChannelType.Public,
Name = name
});
}
[BackgroundDependencyLoader]
private void load(IAPIProvider api)
{
GetUsersRequest req = new GetUsersRequest();
req.Success += list => users = list.Select(e => e.User).ToList();
api.Queue(req);
}
}
}

View File

@ -98,8 +98,11 @@ namespace osu.Game.Tests.Visual
[SetUp]
public virtual void SetUp()
{
manager?.Delete(manager.GetAllUsableBeatmapSets());
Child = songSelect = new TestSongSelect();
Schedule(() =>
{
manager?.Delete(manager.GetAllUsableBeatmapSets());
Child = songSelect = new TestSongSelect();
});
}
[Test]

View File

@ -0,0 +1,143 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Logging;
using osu.Game.Graphics.Sprites;
using osu.Game.Online;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual
{
public class TestCasePollingComponent : OsuTestCase
{
private Container pollBox;
private TestPoller poller;
private const float safety_adjust = 1f;
private int count;
[SetUp]
public void SetUp() => Schedule(() =>
{
count = 0;
Children = new Drawable[]
{
pollBox = new Container
{
Alpha = 0,
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Scale = new Vector2(0.4f),
Colour = Color4.LimeGreen,
RelativeSizeAxes = Axes.Both,
},
new OsuSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Text = "Poll!",
}
}
}
};
});
[Test]
public void TestInstantPolling()
{
createPoller(true);
AddStep("set poll interval to 1", () => poller.TimeBetweenPolls = TimePerAction * safety_adjust);
checkCount(1);
checkCount(2);
checkCount(3);
AddStep("set poll interval to 5", () => poller.TimeBetweenPolls = TimePerAction * safety_adjust * 5);
checkCount(4);
checkCount(4);
checkCount(4);
skip();
checkCount(5);
checkCount(5);
AddStep("set poll interval to 1", () => poller.TimeBetweenPolls = TimePerAction * safety_adjust);
checkCount(6);
checkCount(7);
}
[Test]
[Ignore("i have no idea how to fix the timing of this one")]
public void TestSlowPolling()
{
createPoller(false);
AddStep("set poll interval to 1", () => poller.TimeBetweenPolls = TimePerAction * safety_adjust * 5);
checkCount(0);
skip();
checkCount(0);
skip();
skip();
checkCount(0);
skip();
skip();
checkCount(0);
}
private void skip() => AddStep("skip", () =>
{
// could be 4 or 5 at this point due to timing discrepancies (safety_adjust @ 0.2 * 5 ~= 1)
// easiest to just ignore the value at this point and move on.
});
private void checkCount(int checkValue)
{
Logger.Log($"value is {count}");
AddAssert($"count is {checkValue}", () => count == checkValue);
}
private void createPoller(bool instant) => AddStep("create poller", () =>
{
poller?.Expire();
Add(poller = instant ? new TestPoller() : new TestSlowPoller());
poller.OnPoll += () =>
{
pollBox.FadeOutFromOne(500);
count++;
};
});
protected override double TimePerAction => 500;
public class TestPoller : PollingComponent
{
public event Action OnPoll;
protected override Task Poll()
{
Schedule(() => OnPoll?.Invoke());
return base.Poll();
}
}
public class TestSlowPoller : TestPoller
{
protected override Task Poll() => Task.Delay((int)(TimeBetweenPolls / 2f / Clock.Rate)).ContinueWith(_ => base.Poll());
}
}
}

View File

@ -48,7 +48,7 @@ namespace osu.Game.Tests.Visual
MaxCombo = 123,
Rank = ScoreRank.A,
Date = DateTimeOffset.Now,
Statistics = new Dictionary<HitResult, dynamic>
Statistics = new Dictionary<HitResult, int>
{
{ HitResult.Great, 50 },
{ HitResult.Good, 20 },

View File

@ -2,15 +2,15 @@
<Import Project="..\osu.TestProject.props" />
<ItemGroup Label="Package References">
<PackageReference Include="Appveyor.TestLogger" Version="2.0.0" />
<PackageReference Include="DeepEqual" Version="1.6.0" />
<PackageReference Include="DeepEqual" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.11.2" />
<PackageReference Update="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />
</ItemGroup>
<PropertyGroup Label="Project">
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\osu.Game.Rulesets.Osu\osu.Game.Rulesets.Osu.csproj" />

View File

@ -249,10 +249,13 @@ namespace osu.Game.Beatmaps
/// Retrieve a <see cref="WorkingBeatmap"/> instance for the provided <see cref="BeatmapInfo"/>
/// </summary>
/// <param name="beatmapInfo">The beatmap to lookup.</param>
/// <param name="previous">The currently loaded <see cref="WorkingBeatmap"/>. Allows for optimisation where elements are shared with the new beatmap.</param>
/// <param name="previous">The currently loaded <see cref="WorkingBeatmap"/>. Allows for optimisation where elements are shared with the new beatmap. May be returned if beatmapInfo requested matches</param>
/// <returns>A <see cref="WorkingBeatmap"/> instance correlating to the provided <see cref="BeatmapInfo"/>.</returns>
public WorkingBeatmap GetWorkingBeatmap(BeatmapInfo beatmapInfo, WorkingBeatmap previous = null)
{
if (beatmapInfo?.ID > 0 && previous != null && previous.BeatmapInfo?.ID == beatmapInfo.ID)
return previous;
if (beatmapInfo?.BeatmapSet == null || beatmapInfo == DefaultBeatmap?.BeatmapInfo)
return DefaultBeatmap;

View File

@ -149,8 +149,10 @@ namespace osu.Game.Database
try
{
notification.Text = $"Importing ({++current} of {paths.Length})\n{Path.GetFileName(path)}";
TModel import;
using (ArchiveReader reader = getReaderFrom(path))
imported.Add(Import(reader));
imported.Add(import = Import(reader));
notification.Progress = (float)current / paths.Length;
@ -160,7 +162,7 @@ namespace osu.Game.Database
// TODO: Add a check to prevent files from storage to be deleted.
try
{
if (File.Exists(path))
if (import != null && File.Exists(path))
File.Delete(path);
}
catch (Exception e)

View File

@ -102,7 +102,7 @@ namespace osu.Game.Online.API
if (queue.Count == 0)
{
log.Add(@"Queueing a ping request");
Queue(new ListChannelsRequest { Timeout = 5000 });
Queue(new GetUserRequest());
}
break;
@ -173,7 +173,6 @@ namespace osu.Game.Online.API
req = queue.Dequeue();
}
// TODO: handle failures better
handleRequest(req);
}
@ -191,64 +190,30 @@ namespace osu.Game.Online.API
/// <summary>
/// Handle a single API request.
/// Ensures all exceptions are caught and dealt with correctly.
/// </summary>
/// <param name="req">The request.</param>
/// <returns>true if we should remove this request from the queue.</returns>
/// <returns>true if the request succeeded.</returns>
private bool handleRequest(APIRequest req)
{
try
{
Logger.Log($@"Performing request {req}", LoggingTarget.Network);
req.Perform(this);
//we could still be in initialisation, at which point we don't want to say we're Online yet.
if (IsLoggedIn)
State = APIState.Online;
if (IsLoggedIn) State = APIState.Online;
failureCount = 0;
return true;
}
catch (WebException we)
{
HttpStatusCode statusCode = (we.Response as HttpWebResponse)?.StatusCode
?? (we.Status == WebExceptionStatus.UnknownError ? HttpStatusCode.NotAcceptable : HttpStatusCode.RequestTimeout);
// special cases for un-typed but useful message responses.
switch (we.Message)
{
case "Unauthorized":
statusCode = HttpStatusCode.Unauthorized;
break;
}
switch (statusCode)
{
case HttpStatusCode.Unauthorized:
Logout(false);
return true;
case HttpStatusCode.RequestTimeout:
failureCount++;
log.Add($@"API failure count is now {failureCount}");
if (failureCount < 3)
//we might try again at an api level.
return false;
State = APIState.Failing;
flushQueue();
return true;
}
req.Fail(we);
return true;
handleWebException(we);
return false;
}
catch (Exception e)
{
if (e is TimeoutException)
log.Add(@"API level timeout exception was hit");
req.Fail(e);
return true;
return false;
}
}
@ -276,6 +241,45 @@ namespace osu.Game.Online.API
}
}
private bool handleWebException(WebException we)
{
HttpStatusCode statusCode = (we.Response as HttpWebResponse)?.StatusCode
?? (we.Status == WebExceptionStatus.UnknownError ? HttpStatusCode.NotAcceptable : HttpStatusCode.RequestTimeout);
// special cases for un-typed but useful message responses.
switch (we.Message)
{
case "Unauthorized":
case "Forbidden":
statusCode = HttpStatusCode.Unauthorized;
break;
}
switch (statusCode)
{
case HttpStatusCode.Unauthorized:
Logout(false);
return true;
case HttpStatusCode.RequestTimeout:
failureCount++;
log.Add($@"API failure count is now {failureCount}");
if (failureCount < 3)
//we might try again at an api level.
return false;
if (State == APIState.Online)
{
State = APIState.Failing;
flushQueue();
}
return true;
}
return true;
}
public bool IsLoggedIn => LocalUser.Value.Id > 1;
public void Queue(APIRequest request)

View File

@ -3,6 +3,7 @@
using System;
using osu.Framework.IO.Network;
using osu.Framework.Logging;
namespace osu.Game.Online.API
{
@ -35,23 +36,12 @@ namespace osu.Game.Online.API
/// </summary>
public abstract class APIRequest
{
/// <summary>
/// The maximum amount of time before this request will fail.
/// </summary>
public int Timeout = WebRequest.DEFAULT_TIMEOUT;
protected virtual string Target => string.Empty;
protected virtual WebRequest CreateWebRequest() => new WebRequest(Uri);
protected virtual string Uri => $@"{API.Endpoint}/api/v2/{Target}";
private double remainingTime => Math.Max(0, Timeout - (DateTimeOffset.UtcNow - (startTime ?? DateTimeOffset.MinValue)).TotalMilliseconds);
public bool ExceededTimeout => remainingTime == 0;
private DateTimeOffset? startTime;
protected APIAccess API;
protected WebRequest WebRequest;
@ -75,27 +65,24 @@ namespace osu.Game.Online.API
{
API = api;
if (checkAndProcessFailure())
if (checkAndScheduleFailure())
return;
if (startTime == null)
startTime = DateTimeOffset.UtcNow;
if (remainingTime <= 0)
throw new TimeoutException(@"API request timeout hit");
WebRequest = CreateWebRequest();
WebRequest.Failed += Fail;
WebRequest.AllowRetryOnTimeout = false;
WebRequest.AddHeader("Authorization", $"Bearer {api.AccessToken}");
if (checkAndProcessFailure())
if (checkAndScheduleFailure())
return;
if (!WebRequest.Aborted) //could have been aborted by a Cancel() call
{
Logger.Log($@"Performing request {this}", LoggingTarget.Network);
WebRequest.Perform();
}
if (checkAndProcessFailure())
if (checkAndScheduleFailure())
return;
api.Schedule(delegate { Success?.Invoke(); });
@ -105,19 +92,21 @@ namespace osu.Game.Online.API
public void Fail(Exception e)
{
cancelled = true;
if (cancelled) return;
cancelled = true;
WebRequest?.Abort();
Logger.Log($@"Failing request {this} ({e})", LoggingTarget.Network);
pendingFailure = () => Failure?.Invoke(e);
checkAndProcessFailure();
checkAndScheduleFailure();
}
/// <summary>
/// Checked for cancellation or error. Also queues up the Failed event if we can.
/// </summary>
/// <returns>Whether we are in a failed or cancelled state.</returns>
private bool checkAndProcessFailure()
private bool checkAndScheduleFailure()
{
if (API == null || pendingFailure == null) return cancelled;

View File

@ -65,7 +65,7 @@ namespace osu.Game.Online.API.Requests.Responses
}
[JsonProperty(@"statistics")]
private Dictionary<string, object> jsonStats
private Dictionary<string, int> jsonStats
{
set
{

View File

@ -88,6 +88,17 @@ namespace osu.Game.Online.Chat
{
}
/// <summary>
/// Create a private messaging channel with the specified user.
/// </summary>
/// <param name="user">The user to create the private conversation with.</param>
public Channel(User user)
{
Type = ChannelType.PM;
Users.Add(user);
Name = user.Username;
}
/// <summary>
/// Adds the argument message as a local echo. When this local echo is resolved <see cref="PendingMessageResolved"/> will get called.
/// </summary>

View File

@ -4,11 +4,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Logging;
using osu.Framework.Threading;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Users;
@ -18,7 +17,7 @@ namespace osu.Game.Online.Chat
/// <summary>
/// Manages everything channel related
/// </summary>
public class ChannelManager : Component, IOnlineComponent
public class ChannelManager : PollingComponent
{
/// <summary>
/// The channels the player joins on startup
@ -49,11 +48,14 @@ namespace osu.Game.Online.Chat
public IBindableCollection<Channel> AvailableChannels => availableChannels;
private IAPIProvider api;
private ScheduledDelegate fetchMessagesScheduleder;
public readonly BindableBool HighPollRate = new BindableBool();
public ChannelManager()
{
CurrentChannel.ValueChanged += currentChannelChanged;
HighPollRate.BindValueChanged(high => TimeBetweenPolls = high ? 1000 : 6000, true);
}
/// <summary>
@ -79,7 +81,7 @@ namespace osu.Game.Online.Chat
throw new ArgumentNullException(nameof(user));
CurrentChannel.Value = JoinedChannels.FirstOrDefault(c => c.Type == ChannelType.PM && c.Users.Count == 1 && c.Users.Any(u => u.Id == user.Id))
?? new Channel { Name = user.Username, Users = { user }, Type = ChannelType.PM };
?? new Channel(user);
}
private void currentChannelChanged(Channel channel) => JoinChannel(channel);
@ -360,73 +362,60 @@ namespace osu.Game.Online.Chat
}
}
public void APIStateChanged(APIAccess api, APIState state)
{
switch (state)
{
case APIState.Online:
fetchUpdates();
break;
default:
fetchMessagesScheduleder?.Cancel();
fetchMessagesScheduleder = null;
break;
}
}
private long lastMessageId;
private const int update_poll_interval = 1000;
private bool channelsInitialised;
private void fetchUpdates()
protected override Task Poll()
{
fetchMessagesScheduleder?.Cancel();
fetchMessagesScheduleder = Scheduler.AddDelayed(() =>
if (!api.IsLoggedIn)
return base.Poll();
var fetchReq = new GetUpdatesRequest(lastMessageId);
var tcs = new TaskCompletionSource<bool>();
fetchReq.Success += updates =>
{
var fetchReq = new GetUpdatesRequest(lastMessageId);
fetchReq.Success += updates =>
if (updates?.Presence != null)
{
if (updates?.Presence != null)
foreach (var channel in updates.Presence)
{
foreach (var channel in updates.Presence)
{
// we received this from the server so should mark the channel already joined.
JoinChannel(channel, true);
}
//todo: handle left channels
handleChannelMessages(updates.Messages);
foreach (var group in updates.Messages.GroupBy(m => m.ChannelId))
JoinedChannels.FirstOrDefault(c => c.Id == group.Key)?.AddNewMessages(group.ToArray());
lastMessageId = updates.Messages.LastOrDefault()?.Id ?? lastMessageId;
// we received this from the server so should mark the channel already joined.
JoinChannel(channel, true);
}
if (!channelsInitialised)
{
channelsInitialised = true;
// we want this to run after the first presence so we can see if the user is in any channels already.
initializeChannels();
}
//todo: handle left channels
fetchUpdates();
};
handleChannelMessages(updates.Messages);
fetchReq.Failure += delegate { fetchUpdates(); };
foreach (var group in updates.Messages.GroupBy(m => m.ChannelId))
JoinedChannels.FirstOrDefault(c => c.Id == group.Key)?.AddNewMessages(group.ToArray());
api.Queue(fetchReq);
}, update_poll_interval);
lastMessageId = updates.Messages.LastOrDefault()?.Id ?? lastMessageId;
}
if (!channelsInitialised)
{
channelsInitialised = true;
// we want this to run after the first presence so we can see if the user is in any channels already.
initializeChannels();
}
tcs.SetResult(true);
};
fetchReq.Failure += _ => tcs.SetResult(false);
api.Queue(fetchReq);
return tcs.Task;
}
[BackgroundDependencyLoader]
private void load(IAPIProvider api)
{
this.api = api;
api.Register(this);
}
}

View File

@ -0,0 +1,118 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Threading.Tasks;
using osu.Framework.Graphics;
using osu.Framework.Threading;
namespace osu.Game.Online
{
/// <summary>
/// A component which requires a constant polling process.
/// </summary>
public abstract class PollingComponent : Component
{
private double? lastTimePolled;
private ScheduledDelegate scheduledPoll;
private bool pollingActive;
private double timeBetweenPolls;
/// <summary>
/// The time in milliseconds to wait between polls.
/// Setting to zero stops all polling.
/// </summary>
public double TimeBetweenPolls
{
get => timeBetweenPolls;
set
{
timeBetweenPolls = value;
scheduledPoll?.Cancel();
pollIfNecessary();
}
}
/// <summary>
///
/// </summary>
/// <param name="timeBetweenPolls">The initial time in milliseconds to wait between polls. Setting to zero stops al polling.</param>
protected PollingComponent(double timeBetweenPolls = 0)
{
TimeBetweenPolls = timeBetweenPolls;
}
protected override void LoadComplete()
{
base.LoadComplete();
pollIfNecessary();
}
private bool pollIfNecessary()
{
// we must be loaded so we have access to clock.
if (!IsLoaded) return false;
// there's already a poll process running.
if (pollingActive) return false;
// don't try polling if the time between polls hasn't been set.
if (timeBetweenPolls == 0) return false;
if (!lastTimePolled.HasValue)
{
doPoll();
return true;
}
if (Time.Current - lastTimePolled.Value > timeBetweenPolls)
{
doPoll();
return true;
}
// not ennough time has passed since the last poll. we do want to schedule a poll to happen, though.
scheduleNextPoll();
return false;
}
private void doPoll()
{
scheduledPoll = null;
pollingActive = true;
Poll().ContinueWith(_ => pollComplete());
}
/// <summary>
/// Perform the polling in this method. Call <see cref="pollComplete"/> when done.
/// </summary>
protected virtual Task Poll()
{
return Task.CompletedTask;
}
/// <summary>
/// Call when a poll operation has completed.
/// </summary>
private void pollComplete()
{
lastTimePolled = Time.Current;
pollingActive = false;
if (scheduledPoll == null)
scheduleNextPoll();
}
private void scheduleNextPoll()
{
scheduledPoll?.Cancel();
double lastPollDuration = lastTimePolled.HasValue ? Time.Current - lastTimePolled.Value : 0;
scheduledPoll = Scheduler.AddDelayed(doPoll, Math.Max(0, timeBetweenPolls - lastPollDuration));
}
}
}

View File

@ -418,6 +418,8 @@ namespace osu.Game
dependencies.Cache(notifications);
dependencies.Cache(dialogOverlay);
chatOverlay.StateChanged += state => channelManager.HighPollRate.Value = state == Visibility.Visible;
Add(externalLinkOpener = new ExternalLinkOpener());
var singleDisplaySideOverlays = new OverlayContainer[] { settings, notifications };

View File

@ -1,348 +0,0 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.Chat;
using osuTK;
using osuTK.Input;
using osuTK.Graphics;
using osu.Framework.Configuration;
using System;
using osu.Framework.Input.Events;
using osu.Game.Graphics.Containers;
namespace osu.Game.Overlays.Chat
{
public class ChatTabControl : OsuTabControl<Channel>
{
private const float shear_width = 10;
public Action<Channel> OnRequestLeave;
public readonly Bindable<bool> ChannelSelectorActive = new Bindable<bool>();
private readonly ChannelTabItem.ChannelSelectorTabItem selectorTab;
public ChatTabControl()
{
TabContainer.Margin = new MarginPadding { Left = 50 };
TabContainer.Spacing = new Vector2(-shear_width, 0);
TabContainer.Masking = false;
AddInternal(new SpriteIcon
{
Icon = FontAwesome.fa_comments,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Size = new Vector2(20),
Margin = new MarginPadding(10),
});
AddTabItem(selectorTab = new ChannelTabItem.ChannelSelectorTabItem(new Channel { Name = "+" }));
ChannelSelectorActive.BindTo(selectorTab.Active);
}
protected override void AddTabItem(TabItem<Channel> item, bool addToDropdown = true)
{
if (item != selectorTab && TabContainer.GetLayoutPosition(selectorTab) < float.MaxValue)
// performTabSort might've made selectorTab's position wonky, fix it
TabContainer.SetLayoutPosition(selectorTab, float.MaxValue);
base.AddTabItem(item, addToDropdown);
if (SelectedTab == null)
SelectTab(item);
}
protected override TabItem<Channel> CreateTabItem(Channel value) => new ChannelTabItem(value) { OnRequestClose = tabCloseRequested };
protected override void SelectTab(TabItem<Channel> tab)
{
if (tab is ChannelTabItem.ChannelSelectorTabItem)
{
tab.Active.Toggle();
return;
}
selectorTab.Active.Value = false;
base.SelectTab(tab);
}
private void tabCloseRequested(TabItem<Channel> tab)
{
int totalTabs = TabContainer.Count - 1; // account for selectorTab
int currentIndex = MathHelper.Clamp(TabContainer.IndexOf(tab), 1, totalTabs);
if (tab == SelectedTab && totalTabs > 1)
// Select the tab after tab-to-be-removed's index, or the tab before if current == last
SelectTab(TabContainer[currentIndex == totalTabs ? currentIndex - 1 : currentIndex + 1]);
else if (totalTabs == 1 && !selectorTab.Active)
// Open channel selection overlay if all channel tabs will be closed after removing this tab
SelectTab(selectorTab);
OnRequestLeave?.Invoke(tab.Value);
}
private class ChannelTabItem : TabItem<Channel>
{
private Color4 backgroundInactive;
private Color4 backgroundHover;
private Color4 backgroundActive;
public override bool IsRemovable => !Pinned;
private readonly SpriteText text;
private readonly SpriteText textBold;
private readonly ClickableContainer closeButton;
private readonly Box box;
private readonly Box highlightBox;
private readonly SpriteIcon icon;
public Action<ChannelTabItem> OnRequestClose;
private void updateState()
{
if (Active)
fadeActive();
else
fadeInactive();
}
private const float transition_length = 400;
private void fadeActive()
{
this.ResizeTo(new Vector2(Width, 1.1f), transition_length, Easing.OutQuint);
box.FadeColour(backgroundActive, transition_length, Easing.OutQuint);
highlightBox.FadeIn(transition_length, Easing.OutQuint);
text.FadeOut(transition_length, Easing.OutQuint);
textBold.FadeIn(transition_length, Easing.OutQuint);
}
private void fadeInactive()
{
this.ResizeTo(new Vector2(Width, 1), transition_length, Easing.OutQuint);
box.FadeColour(backgroundInactive, transition_length, Easing.OutQuint);
highlightBox.FadeOut(transition_length, Easing.OutQuint);
text.FadeIn(transition_length, Easing.OutQuint);
textBold.FadeOut(transition_length, Easing.OutQuint);
}
protected override bool OnMouseUp(MouseUpEvent e)
{
if (e.Button == MouseButton.Middle)
{
closeButton.Action();
return true;
}
return false;
}
protected override bool OnHover(HoverEvent e)
{
if (IsRemovable)
closeButton.FadeIn(200, Easing.OutQuint);
if (!Active)
box.FadeColour(backgroundHover, transition_length, Easing.OutQuint);
return true;
}
protected override void OnHoverLost(HoverLostEvent e)
{
closeButton.FadeOut(200, Easing.OutQuint);
updateState();
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
backgroundActive = colours.ChatBlue;
backgroundInactive = colours.Gray4;
backgroundHover = colours.Gray7;
highlightBox.Colour = colours.Yellow;
}
protected override void LoadComplete()
{
base.LoadComplete();
updateState();
}
public ChannelTabItem(Channel value) : base(value)
{
Width = 150;
RelativeSizeAxes = Axes.Y;
Anchor = Anchor.BottomLeft;
Origin = Anchor.BottomLeft;
Shear = new Vector2(shear_width / ChatOverlay.TAB_AREA_HEIGHT, 0);
Masking = true;
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Radius = 10,
Colour = Color4.Black.Opacity(0.2f),
};
Children = new Drawable[]
{
box = new Box
{
EdgeSmoothness = new Vector2(1, 0),
RelativeSizeAxes = Axes.Both,
},
highlightBox = new Box
{
Width = 5,
Alpha = 0,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
EdgeSmoothness = new Vector2(1, 0),
RelativeSizeAxes = Axes.Y,
},
new Container
{
Shear = new Vector2(-shear_width / ChatOverlay.TAB_AREA_HEIGHT, 0),
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
icon = new SpriteIcon
{
Icon = FontAwesome.fa_hashtag,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Colour = Color4.Black,
X = -10,
Alpha = 0.2f,
Size = new Vector2(ChatOverlay.TAB_AREA_HEIGHT),
},
text = new OsuSpriteText
{
Margin = new MarginPadding(5),
Origin = Anchor.CentreLeft,
Anchor = Anchor.CentreLeft,
Text = value.ToString(),
TextSize = 18,
},
textBold = new OsuSpriteText
{
Alpha = 0,
Margin = new MarginPadding(5),
Origin = Anchor.CentreLeft,
Anchor = Anchor.CentreLeft,
Text = value.ToString(),
Font = @"Exo2.0-Bold",
TextSize = 18,
},
closeButton = new CloseButton
{
Alpha = 0,
Margin = new MarginPadding { Right = 20 },
Origin = Anchor.CentreRight,
Anchor = Anchor.CentreRight,
Action = delegate
{
if (IsRemovable) OnRequestClose?.Invoke(this);
},
},
},
},
};
}
public class CloseButton : OsuClickableContainer
{
private readonly SpriteIcon icon;
public CloseButton()
{
Size = new Vector2(20);
Child = icon = new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Scale = new Vector2(0.75f),
Icon = FontAwesome.fa_close,
RelativeSizeAxes = Axes.Both,
};
}
protected override bool OnMouseDown(MouseDownEvent e)
{
icon.ScaleTo(0.5f, 1000, Easing.OutQuint);
return base.OnMouseDown(e);
}
protected override bool OnMouseUp(MouseUpEvent e)
{
icon.ScaleTo(0.75f, 1000, Easing.OutElastic);
return base.OnMouseUp(e);
}
protected override bool OnHover(HoverEvent e)
{
icon.FadeColour(Color4.Red, 200, Easing.OutQuint);
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
icon.FadeColour(Color4.White, 200, Easing.OutQuint);
base.OnHoverLost(e);
}
}
public class ChannelSelectorTabItem : ChannelTabItem
{
public override bool IsRemovable => false;
public override bool IsSwitchable => false;
public ChannelSelectorTabItem(Channel value) : base(value)
{
Depth = float.MaxValue;
Width = 45;
icon.Alpha = 0;
text.TextSize = 45;
textBold.TextSize = 45;
}
[BackgroundDependencyLoader]
private new void load(OsuColour colour)
{
backgroundInactive = colour.Gray2;
backgroundActive = colour.Gray3;
}
}
protected override void OnActivated() => updateState();
protected override void OnDeactivated() => updateState();
}
}
}

View File

@ -48,10 +48,6 @@ namespace osu.Game.Overlays.Chat
},
}
};
Channel.NewMessagesArrived += newMessagesArrived;
Channel.MessageRemoved += messageRemoved;
Channel.PendingMessageResolved += pendingMessageResolved;
}
protected override void LoadComplete()
@ -59,6 +55,11 @@ namespace osu.Game.Overlays.Chat
base.LoadComplete();
newMessagesArrived(Channel.Messages);
Channel.NewMessagesArrived += newMessagesArrived;
Channel.MessageRemoved += messageRemoved;
Channel.PendingMessageResolved += pendingMessageResolved;
scrollToEnd();
}
@ -78,8 +79,6 @@ namespace osu.Game.Overlays.Chat
flow.AddRange(displayMessages.Select(m => new ChatLine(m)));
if (!IsLoaded) return;
if (scroll.IsScrolledToEnd(10) || !flow.Children.Any() || newMessages.Any(m => m is LocalMessage))
scrollToEnd();

View File

@ -20,7 +20,7 @@ using osu.Game.Graphics.Containers;
namespace osu.Game.Overlays.Chat.Selection
{
public class ChannelSelectionOverlay : OsuFocusedOverlayContainer
public class ChannelSelectionOverlay : WaveOverlayContainer
{
public static readonly float WIDTH_PADDING = 170;
@ -39,6 +39,11 @@ namespace osu.Game.Overlays.Chat.Selection
{
RelativeSizeAxes = Axes.X;
Waves.FirstWaveColour = OsuColour.FromHex("353535");
Waves.SecondWaveColour = OsuColour.FromHex("434343");
Waves.ThirdWaveColour = OsuColour.FromHex("515151");
Waves.FourthWaveColour = OsuColour.FromHex("595959");
Children = new Drawable[]
{
new Container

View File

@ -11,6 +11,8 @@ namespace osu.Game.Overlays.Chat.Tabs
{
public override bool IsRemovable => false;
public override bool IsSwitchable => false;
public ChannelSelectorTabItem(Channel value) : base(value)
{
Depth = float.MaxValue;

View File

@ -94,13 +94,12 @@ namespace osu.Game.Overlays.Chat.Tabs
{
if (tab is ChannelSelectorTabItem)
{
tab.Active.Toggle();
tab.Active.Value = true;
return;
}
selectorTab.Active.Value = false;
base.SelectTab(tab);
selectorTab.Active.Value = false;
}
private void tabCloseRequested(TabItem<Channel> tab)

View File

@ -52,9 +52,9 @@ namespace osu.Game.Overlays
public Bindable<double> ChatHeight { get; set; }
private readonly Container channelSelectionContainer;
private readonly ChannelSelectionOverlay channelSelection;
private readonly ChannelSelectionOverlay channelSelectionOverlay;
public override bool Contains(Vector2 screenSpacePos) => chatContainer.ReceivePositionalInputAt(screenSpacePos) || channelSelection.State == Visibility.Visible && channelSelection.ReceivePositionalInputAt(screenSpacePos);
public override bool Contains(Vector2 screenSpacePos) => chatContainer.ReceivePositionalInputAt(screenSpacePos) || channelSelectionOverlay.State == Visibility.Visible && channelSelectionOverlay.ReceivePositionalInputAt(screenSpacePos);
public ChatOverlay()
{
@ -74,7 +74,7 @@ namespace osu.Game.Overlays
Masking = true,
Children = new[]
{
channelSelection = new ChannelSelectionOverlay
channelSelectionOverlay = new ChannelSelectionOverlay
{
RelativeSizeAxes = Axes.Both,
},
@ -161,9 +161,16 @@ namespace osu.Game.Overlays
};
channelTabControl.Current.ValueChanged += chat => channelManager.CurrentChannel.Value = chat;
channelTabControl.ChannelSelectorActive.ValueChanged += value => channelSelection.State = value ? Visibility.Visible : Visibility.Hidden;
channelSelection.StateChanged += state =>
channelTabControl.ChannelSelectorActive.ValueChanged += value => channelSelectionOverlay.State = value ? Visibility.Visible : Visibility.Hidden;
channelSelectionOverlay.StateChanged += state =>
{
if (state == Visibility.Hidden && channelManager.CurrentChannel.Value == null)
{
channelSelectionOverlay.State = Visibility.Visible;
State = Visibility.Hidden;
return;
}
channelTabControl.ChannelSelectorActive.Value = state == Visibility.Visible;
if (state == Visibility.Visible)
@ -176,8 +183,8 @@ namespace osu.Game.Overlays
textbox.HoldFocus = true;
};
channelSelection.OnRequestJoin = channel => channelManager.JoinChannel(channel);
channelSelection.OnRequestLeave = channel => channelManager.LeaveChannel(channel);
channelSelectionOverlay.OnRequestJoin = channel => channelManager.JoinChannel(channel);
channelSelectionOverlay.OnRequestLeave = channel => channelManager.LeaveChannel(channel);
}
private void currentChannelChanged(Channel channel)
@ -186,6 +193,7 @@ namespace osu.Game.Overlays
{
textbox.Current.Disabled = true;
currentChannelContainer.Clear(false);
channelSelectionOverlay.State = Visibility.Visible;
return;
}
@ -239,7 +247,7 @@ namespace osu.Game.Overlays
double targetChatHeight = startDragChatHeight - (e.MousePosition.Y - e.MouseDownPosition.Y) / Parent.DrawSize.Y;
// If the channel selection screen is shown, mind its minimum height
if (channelSelection.State == Visibility.Visible && targetChatHeight > 1f - channel_selection_min_height)
if (channelSelectionOverlay.State == Visibility.Visible && targetChatHeight > 1f - channel_selection_min_height)
targetChatHeight = 1f - channel_selection_min_height;
ChatHeight.Value = targetChatHeight;
@ -305,7 +313,7 @@ namespace osu.Game.Overlays
channelManager.AvailableChannels.ItemsRemoved += availableChannelsChanged;
//for the case that channelmanager was faster at fetching the channels than our attachment to CollectionChanged.
channelSelection.UpdateAvailableChannels(channelManager.AvailableChannels);
channelSelectionOverlay.UpdateAvailableChannels(channelManager.AvailableChannels);
foreach (Channel channel in channelManager.JoinedChannels)
channelTabControl.AddChannel(channel);
}
@ -326,7 +334,7 @@ namespace osu.Game.Overlays
}
private void availableChannelsChanged(IEnumerable<Channel> channels)
=> channelSelection.UpdateAvailableChannels(channelManager.AvailableChannels);
=> channelSelectionOverlay.UpdateAvailableChannels(channelManager.AvailableChannels);
protected override void Dispose(bool isDisposing)
{

View File

@ -7,8 +7,8 @@ using osu.Framework.Graphics.Containers;
using osu.Game.Online.API.Requests;
using osu.Game.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Overlays.Profile.Sections.Ranks
{
@ -39,33 +39,34 @@ namespace osu.Game.Overlays.Profile.Sections.Ranks
foreach (var s in scores)
s.Ruleset = Rulesets.GetRuleset(s.RulesetID);
ShowMoreButton.FadeTo(scores.Count == ItemsPerPage ? 1 : 0);
ShowMoreLoading.Hide();
if (!scores.Any() && VisiblePages == 1)
{
ShowMoreButton.Hide();
ShowMoreLoading.Hide();
MissingText.Show();
return;
}
MissingText.Hide();
IEnumerable<DrawableProfileScore> drawableScores;
foreach (APIScoreInfo score in scores)
switch (type)
{
DrawableProfileScore drawableScore;
switch (type)
{
default:
drawableScore = new DrawablePerformanceScore(score, includeWeight ? Math.Pow(0.95, ItemsContainer.Count) : (double?)null);
break;
case ScoreType.Recent:
drawableScore = new DrawableTotalScore(score);
break;
}
ItemsContainer.Add(drawableScore);
default:
drawableScores = scores.Select(score => new DrawablePerformanceScore(score, includeWeight ? Math.Pow(0.95, ItemsContainer.Count) : (double?)null));
break;
case ScoreType.Recent:
drawableScores = scores.Select(score => new DrawableTotalScore(score));
break;
}
LoadComponentsAsync(drawableScores, s =>
{
MissingText.Hide();
ShowMoreButton.FadeTo(scores.Count == ItemsPerPage ? 1 : 0);
ShowMoreLoading.Hide();
ItemsContainer.AddRange(s);
});
});
Api.Queue(request);

View File

@ -21,7 +21,7 @@ namespace osu.Game.Overlays.Settings.Sections
public override FontAwesome Icon => FontAwesome.fa_paint_brush;
private readonly Bindable<SkinInfo> dropdownBindable = new Bindable<SkinInfo>();
private readonly Bindable<SkinInfo> dropdownBindable = new Bindable<SkinInfo> { Default = SkinInfo.Default };
private readonly Bindable<int> configBindable = new Bindable<int>();
private SkinManager skins;

View File

@ -44,5 +44,19 @@ namespace osu.Game.Rulesets.Judgements
/// <param name="result">The <see cref="JudgementResult"/> to find the numeric score representation for.</param>
/// <returns>The numeric score representation of <paramref name="result"/>.</returns>
public int NumericResultFor(JudgementResult result) => NumericResultFor(result.Type);
/// <summary>
/// Retrieves the numeric health increase of a <see cref="HitResult"/>.
/// </summary>
/// <param name="result">The <see cref="HitResult"/> to find the numeric health increase for.</param>
/// <returns>The numeric health increase of <paramref name="result"/>.</returns>
protected virtual double HealthIncreaseFor(HitResult result) => 0;
/// <summary>
/// Retrieves the numeric health increase of a <see cref="JudgementResult"/>.
/// </summary>
/// <param name="result">The <see cref="JudgementResult"/> to find the numeric health increase for.</param>
/// <returns>The numeric health increase of <paramref name="result"/>.</returns>
public double HealthIncreaseFor(JudgementResult result) => HealthIncreaseFor(result.Type);
}
}

View File

@ -147,6 +147,7 @@ namespace osu.Game.Rulesets.Objects.Drawables
/// <summary>
/// Plays all the hit sounds for this <see cref="DrawableHitObject"/>.
/// This is invoked automatically when this <see cref="DrawableHitObject"/> is hit.
/// </summary>
public void PlaySamples() => Samples?.Play();

View File

@ -19,6 +19,11 @@ namespace osu.Game.Rulesets.Objects
/// </summary>
public class HitObject
{
/// <summary>
/// A small adjustment to the start time of control points to account for rounding/precision errors.
/// </summary>
private const double control_point_leniency = 1;
/// <summary>
/// The time at which the HitObject starts.
/// </summary>
@ -69,6 +74,9 @@ namespace osu.Game.Rulesets.Objects
{
ApplyDefaultsToSelf(controlPointInfo, difficulty);
// This is done here since ApplyDefaultsToSelf may be used to determine the end time
SampleControlPoint = controlPointInfo.SamplePointAt(((this as IHasEndTime)?.EndTime ?? StartTime) + control_point_leniency);
nestedHitObjects.Clear();
CreateNestedHitObjects();
@ -84,11 +92,7 @@ namespace osu.Game.Rulesets.Objects
protected virtual void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty)
{
SampleControlPoint samplePoint = controlPointInfo.SamplePointAt(StartTime);
EffectControlPoint effectPoint = controlPointInfo.EffectPointAt(StartTime);
Kiai = effectPoint.KiaiMode;
SampleControlPoint = samplePoint;
Kiai = controlPointInfo.EffectPointAt(StartTime + control_point_leniency).KiaiMode;
if (HitWindows == null)
HitWindows = CreateHitWindows();

View File

@ -22,7 +22,6 @@ namespace osu.Game.Rulesets.Objects
/// <summary>
/// Hit window for a <see cref="HitResult.Perfect"/> result.
/// The user can only achieve receive this result if <see cref="AllowsPerfect"/> is true.
/// </summary>
public double Perfect { get; protected set; }
@ -38,7 +37,6 @@ namespace osu.Game.Rulesets.Objects
/// <summary>
/// Hit window for an <see cref="HitResult.Ok"/> result.
/// The user can only achieve this result if <see cref="AllowsOk"/> is true.
/// </summary>
public double Ok { get; protected set; }
@ -53,14 +51,36 @@ namespace osu.Game.Rulesets.Objects
public double Miss { get; protected set; }
/// <summary>
/// Whether it's possible to achieve a <see cref="HitResult.Perfect"/> result.
/// Retrieves the <see cref="HitResult"/> with the largest hit window that produces a successful hit.
/// </summary>
public bool AllowsPerfect;
/// <returns>The lowest allowed successful <see cref="HitResult"/>.</returns>
protected HitResult LowestSuccessfulHitResult()
{
for (var result = HitResult.Meh; result <= HitResult.Perfect; ++result)
{
if (IsHitResultAllowed(result))
return result;
}
return HitResult.None;
}
/// <summary>
/// Whether it's possible to achieve a <see cref="HitResult.Ok"/> result.
/// Check whether it is possible to achieve the provided <see cref="HitResult"/>.
/// </summary>
public bool AllowsOk;
/// <param name="result">The result type to check.</param>
/// <returns>Whether the <see cref="HitResult"/> can be achieved.</returns>
public virtual bool IsHitResultAllowed(HitResult result)
{
switch (result)
{
case HitResult.Perfect:
case HitResult.Ok:
return false;
default:
return true;
}
}
/// <summary>
/// Sets hit windows with values that correspond to a difficulty parameter.
@ -85,18 +105,11 @@ namespace osu.Game.Rulesets.Objects
{
timeOffset = Math.Abs(timeOffset);
if (AllowsPerfect && timeOffset <= HalfWindowFor(HitResult.Perfect))
return HitResult.Perfect;
if (timeOffset <= HalfWindowFor(HitResult.Great))
return HitResult.Great;
if (timeOffset <= HalfWindowFor(HitResult.Good))
return HitResult.Good;
if (AllowsOk && timeOffset <= HalfWindowFor(HitResult.Ok))
return HitResult.Ok;
if (timeOffset <= HalfWindowFor(HitResult.Meh))
return HitResult.Meh;
if (timeOffset <= HalfWindowFor(HitResult.Miss))
return HitResult.Miss;
for (var result = HitResult.Perfect; result >= HitResult.Miss; --result)
{
if (IsHitResultAllowed(result) && timeOffset <= HalfWindowFor(result))
return result;
}
return HitResult.None;
}
@ -130,10 +143,10 @@ namespace osu.Game.Rulesets.Objects
/// <summary>
/// Given a time offset, whether the <see cref="HitObject"/> can ever be hit in the future with a non-<see cref="HitResult.Miss"/> result.
/// This happens if <paramref name="timeOffset"/> is less than what is required for a <see cref="Meh"/> result.
/// This happens if <paramref name="timeOffset"/> is less than what is required for a <see cref="SuccessfulHitWindow"/> result.
/// </summary>
/// <param name="timeOffset">The time offset.</param>
/// <returns>Whether the <see cref="HitObject"/> can be hit at any point in the future from this time offset.</returns>
public bool CanBeHit(double timeOffset) => timeOffset <= HalfWindowFor(HitResult.Meh);
public bool CanBeHit(double timeOffset) => timeOffset <= HalfWindowFor(LowestSuccessfulHitResult());
}
}

View File

@ -116,12 +116,12 @@ namespace osu.Game.Scoring.Legacy
private void calculateAccuracy(ScoreInfo score)
{
int countMiss = (int)score.Statistics[HitResult.Miss];
int count50 = (int)score.Statistics[HitResult.Meh];
int count100 = (int)score.Statistics[HitResult.Good];
int count300 = (int)score.Statistics[HitResult.Great];
int countGeki = (int)score.Statistics[HitResult.Perfect];
int countKatu = (int)score.Statistics[HitResult.Ok];
int countMiss = score.Statistics[HitResult.Miss];
int count50 = score.Statistics[HitResult.Meh];
int count100 = score.Statistics[HitResult.Good];
int count300 = score.Statistics[HitResult.Great];
int countGeki = score.Statistics[HitResult.Perfect];
int countKatu = score.Statistics[HitResult.Ok];
switch (score.Ruleset.ID)
{

View File

@ -104,7 +104,7 @@ namespace osu.Game.Scoring
public DateTimeOffset Date { get; set; }
[JsonIgnore]
public Dictionary<HitResult, object> Statistics = new Dictionary<HitResult, object>();
public Dictionary<HitResult, int> Statistics = new Dictionary<HitResult, int>();
[Column("Statistics")]
public string StatisticsJson
@ -118,7 +118,7 @@ namespace osu.Game.Scoring
return;
}
Statistics = JsonConvert.DeserializeObject<Dictionary<HitResult, object>>(value);
Statistics = JsonConvert.DeserializeObject<Dictionary<HitResult, int>>(value);
}
}

View File

@ -48,7 +48,7 @@ namespace osu.Game.Screens.Play
Add(content = new Container
{
RelativeSizeAxes = Axes.Both,
AlwaysPresent = true, // The hud may be hidden but certain elements may need to still be updated
Children = new Drawable[]
{
ComboCounter = CreateComboCounter(),

View File

@ -170,7 +170,7 @@ namespace osu.Game.Screens.Play
{
Retries = RestartCount,
OnRetry = Restart,
OnQuit = Exit,
OnQuit = performUserRequestedExit,
CheckCanPause = () => AllowPause && ValidForResume && !HasFailed && !RulesetContainer.HasReplayLoaded,
Children = new[]
{
@ -211,7 +211,7 @@ namespace osu.Game.Screens.Play
failOverlay = new FailOverlay
{
OnRetry = Restart,
OnQuit = Exit,
OnQuit = performUserRequestedExit,
},
new HotkeyRetryOverlay
{
@ -225,7 +225,7 @@ namespace osu.Game.Screens.Play
}
};
hudOverlay.HoldToQuit.Action = Exit;
hudOverlay.HoldToQuit.Action = performUserRequestedExit;
hudOverlay.KeyCounter.Visible.BindTo(RulesetContainer.HasReplayLoaded);
RulesetContainer.IsPaused.BindTo(pauseContainer.IsPaused);
@ -250,8 +250,16 @@ namespace osu.Game.Screens.Play
mod.ApplyToClock(sourceClock);
}
private void performUserRequestedExit()
{
if (!IsCurrentScreen) return;
Exit();
}
public void Restart()
{
if (!IsCurrentScreen) return;
sampleRestart?.Play();
ValidForResume = false;
RestartRequested?.Invoke();

View File

@ -196,9 +196,9 @@ namespace osu.Game.Screens.Ranking
private class DrawableScoreStatistic : Container
{
private readonly KeyValuePair<HitResult, object> statistic;
private readonly KeyValuePair<HitResult, int> statistic;
public DrawableScoreStatistic(KeyValuePair<HitResult, object> statistic)
public DrawableScoreStatistic(KeyValuePair<HitResult, int> statistic)
{
this.statistic = statistic;

View File

@ -1,100 +1,28 @@
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using System.Linq;
using osuTK.Input;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Overlays;
using osu.Game.Overlays.Mods;
using osu.Game.Rulesets.Mods;
using osu.Game.Screens.Play;
using osu.Game.Screens.Ranking;
using osu.Game.Skinning;
using osuTK.Input;
namespace osu.Game.Screens.Select
{
public class PlaySongSelect : SongSelect
{
private OsuScreen player;
private readonly ModSelectOverlay modSelect;
protected readonly BeatmapDetailArea BeatmapDetails;
private bool removeAutoModOnResume;
private OsuScreen player;
public PlaySongSelect()
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
FooterPanels.Add(modSelect = new ModSelectOverlay
{
RelativeSizeAxes = Axes.X,
Origin = Anchor.BottomCentre,
Anchor = Anchor.BottomCentre,
});
LeftContent.Add(BeatmapDetails = new BeatmapDetailArea
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Top = 10, Right = 5 },
});
BeatmapDetails.Leaderboard.ScoreSelected += s => Push(new Results(s));
}
private SampleChannel sampleConfirm;
[Cached]
[Cached(Type = typeof(IBindable<IEnumerable<Mod>>))]
private readonly Bindable<IEnumerable<Mod>> selectedMods = new Bindable<IEnumerable<Mod>>(new Mod[] { });
[BackgroundDependencyLoader(true)]
private void load(OsuColour colours, AudioManager audio, BeatmapManager beatmaps, SkinManager skins, DialogOverlay dialogOverlay, Bindable<IEnumerable<Mod>> selectedMods)
{
if (selectedMods != null) this.selectedMods.BindTo(selectedMods);
sampleConfirm = audio.Sample.Get(@"SongSelect/confirm-selection");
Footer.AddButton(@"mods", colours.Yellow, modSelect, Key.F1, float.MaxValue);
BeatmapOptions.AddButton(@"Remove", @"from unplayed", FontAwesome.fa_times_circle_o, colours.Purple, null, Key.Number1);
BeatmapOptions.AddButton(@"Clear", @"local scores", FontAwesome.fa_eraser, colours.Purple, null, Key.Number2);
BeatmapOptions.AddButton(@"Edit", @"beatmap", FontAwesome.fa_pencil, colours.Yellow, () =>
{
ValidForResume = false;
Edit();
}, Key.Number3);
if (dialogOverlay != null)
{
Schedule(() =>
{
// if we have no beatmaps but osu-stable is found, let's prompt the user to import.
if (!beatmaps.GetAllUsableBeatmapSets().Any() && beatmaps.StableInstallationAvailable)
dialogOverlay.Push(new ImportFromStablePopup(() =>
{
beatmaps.ImportFromStableAsync();
skins.ImportFromStableAsync();
}));
});
}
}
protected override void UpdateBeatmap(WorkingBeatmap beatmap)
{
beatmap.Mods.BindTo(selectedMods);
base.UpdateBeatmap(beatmap);
BeatmapDetails.Beatmap = beatmap;
if (beatmap.Track != null)
beatmap.Track.Looping = true;
}
protected override void OnResuming(Screen last)
@ -104,44 +32,13 @@ namespace osu.Game.Screens.Select
if (removeAutoModOnResume)
{
var autoType = Ruleset.Value.CreateInstance().GetAutoplayMod().GetType();
modSelect.DeselectTypes(new[] { autoType }, true);
ModSelect.DeselectTypes(new[] { autoType }, true);
removeAutoModOnResume = false;
}
BeatmapDetails.Leaderboard.RefreshScores();
Beatmap.Value.Track.Looping = true;
base.OnResuming(last);
}
protected override void OnSuspending(Screen next)
{
modSelect.Hide();
base.OnSuspending(next);
}
protected override bool OnExiting(Screen next)
{
if (modSelect.State == Visibility.Visible)
{
modSelect.Hide();
return true;
}
if (base.OnExiting(next))
return true;
if (Beatmap.Value.Track != null)
Beatmap.Value.Track.Looping = false;
selectedMods.UnbindAll();
Beatmap.Value.Mods.Value = new Mod[] { };
return false;
}
protected override bool OnStart()
{
if (player != null) return false;
@ -152,10 +49,10 @@ namespace osu.Game.Screens.Select
var auto = Ruleset.Value.CreateInstance().GetAutoplayMod();
var autoType = auto.GetType();
var mods = selectedMods.Value;
var mods = SelectedMods.Value;
if (mods.All(m => m.GetType() != autoType))
{
selectedMods.Value = mods.Append(auto);
SelectedMods.Value = mods.Append(auto);
removeAutoModOnResume = true;
}
}
@ -163,7 +60,7 @@ namespace osu.Game.Screens.Select
Beatmap.Value.Track.Looping = false;
Beatmap.Disabled = true;
sampleConfirm?.Play();
SampleConfirm?.Play();
LoadComponentAsync(player = new PlayerLoader(new Player()), l =>
{

View File

@ -2,6 +2,7 @@
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using osuTK;
using osuTK.Input;
@ -21,12 +22,15 @@ using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Input.Bindings;
using osu.Game.Overlays;
using osu.Game.Overlays.Mods;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Screens.Backgrounds;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Menu;
using osu.Game.Screens.Ranking;
using osu.Game.Screens.Select.Options;
using osu.Game.Skinning;
namespace osu.Game.Screens.Select
{
@ -60,29 +64,24 @@ namespace osu.Game.Screens.Select
protected override BackgroundScreen CreateBackground() => new BackgroundScreenBeatmap();
protected Container LeftContent;
protected readonly BeatmapCarousel Carousel;
private readonly BeatmapInfoWedge beatmapInfoWedge;
private DialogOverlay dialogOverlay;
private BeatmapManager beatmaps;
protected readonly ModSelectOverlay ModSelect;
protected SampleChannel SampleConfirm;
private SampleChannel sampleChangeDifficulty;
private SampleChannel sampleChangeBeatmap;
protected readonly BeatmapDetailArea BeatmapDetails;
protected new readonly Bindable<RulesetInfo> Ruleset = new Bindable<RulesetInfo>();
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
{
dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
dependencies.CacheAs(this);
dependencies.CacheAs(Ruleset);
dependencies.CacheAs<IBindable<RulesetInfo>>(Ruleset);
return dependencies;
}
[Cached]
[Cached(Type = typeof(IBindable<IEnumerable<Mod>>))]
protected readonly Bindable<IEnumerable<Mod>> SelectedMods = new Bindable<IEnumerable<Mod>>(new Mod[] { });
protected SongSelect()
{
@ -105,7 +104,7 @@ namespace osu.Game.Screens.Select
}
}
},
LeftContent = new Container
new Container
{
Origin = Anchor.BottomLeft,
Anchor = Anchor.BottomLeft,
@ -117,6 +116,11 @@ namespace osu.Game.Screens.Select
Top = wedged_container_size.Y + left_area_padding,
Left = left_area_padding,
Right = left_area_padding * 2,
},
Child = BeatmapDetails = new BeatmapDetailArea
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Top = 10, Right = 5 },
}
},
new Container
@ -191,22 +195,39 @@ namespace osu.Game.Screens.Select
});
Add(Footer = new Footer
{
OnBack = Exit,
OnBack = ExitFromBack,
});
FooterPanels.Add(BeatmapOptions = new BeatmapOptionsOverlay());
FooterPanels.AddRange(new Drawable[]
{
BeatmapOptions = new BeatmapOptionsOverlay(),
ModSelect = new ModSelectOverlay
{
RelativeSizeAxes = Axes.X,
Origin = Anchor.BottomCentre,
Anchor = Anchor.BottomCentre,
}
});
}
BeatmapDetails.Leaderboard.ScoreSelected += s => Push(new Results(s));
}
[BackgroundDependencyLoader(true)]
private void load(BeatmapManager beatmaps, AudioManager audio, DialogOverlay dialog, OsuColour colours)
private void load(BeatmapManager beatmaps, AudioManager audio, DialogOverlay dialog, OsuColour colours, SkinManager skins, Bindable<IEnumerable<Mod>> selectedMods)
{
if (selectedMods != null)
SelectedMods.BindTo(selectedMods);
if (Footer != null)
{
Footer.AddButton(@"mods", colours.Yellow, ModSelect, Key.F1);
Footer.AddButton(@"random", colours.Green, triggerRandom, Key.F2);
Footer.AddButton(@"options", colours.Blue, BeatmapOptions, Key.F3);
BeatmapOptions.AddButton(@"Delete", @"all difficulties", FontAwesome.fa_trash, colours.Pink, () => delete(Beatmap.Value.BeatmapSetInfo), Key.Number4, float.MaxValue);
BeatmapOptions.AddButton(@"Remove", @"from unplayed", FontAwesome.fa_times_circle_o, colours.Purple, null, Key.Number1);
BeatmapOptions.AddButton(@"Clear", @"local scores", FontAwesome.fa_eraser, colours.Purple, null, Key.Number2);
}
if (this.beatmaps == null)
@ -221,8 +242,46 @@ namespace osu.Game.Screens.Select
sampleChangeDifficulty = audio.Sample.Get(@"SongSelect/select-difficulty");
sampleChangeBeatmap = audio.Sample.Get(@"SongSelect/select-expand");
SampleConfirm = audio.Sample.Get(@"SongSelect/confirm-selection");
Carousel.LoadBeatmapSetsFromManager(this.beatmaps);
if (dialogOverlay != null)
{
Schedule(() =>
{
// if we have no beatmaps but osu-stable is found, let's prompt the user to import.
if (!beatmaps.GetAllUsableBeatmapSets().Any() && beatmaps.StableInstallationAvailable)
dialogOverlay.Push(new ImportFromStablePopup(() =>
{
beatmaps.ImportFromStableAsync();
skins.ImportFromStableAsync();
}));
});
}
}
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
{
dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
dependencies.CacheAs(this);
dependencies.CacheAs(Ruleset);
dependencies.CacheAs<IBindable<RulesetInfo>>(Ruleset);
return dependencies;
}
protected virtual void ExitFromBack()
{
if (ModSelect.State == Visibility.Visible)
{
ModSelect.Hide();
return;
}
Exit();
}
public void Edit(BeatmapInfo beatmap = null)
@ -419,6 +478,10 @@ namespace osu.Game.Screens.Select
protected override void OnResuming(Screen last)
{
BeatmapDetails.Leaderboard.RefreshScores();
Beatmap.Value.Track.Looping = true;
if (Beatmap != null && !Beatmap.Value.BeatmapSetInfo.DeletePending)
{
UpdateBeatmap(Beatmap.Value);
@ -436,6 +499,8 @@ namespace osu.Game.Screens.Select
protected override void OnSuspending(Screen next)
{
ModSelect.Hide();
Content.ScaleTo(1.1f, 250, Easing.InSine);
Content.FadeOut(250);
@ -446,6 +511,12 @@ namespace osu.Game.Screens.Select
protected override bool OnExiting(Screen next)
{
if (ModSelect.State == Visibility.Visible)
{
ModSelect.Hide();
return true;
}
FinaliseSelection(performStartAction: false);
beatmapInfoWedge.State = Visibility.Hidden;
@ -454,6 +525,12 @@ namespace osu.Game.Screens.Select
FilterControl.Deactivate();
if (Beatmap.Value.Track != null)
Beatmap.Value.Track.Looping = false;
SelectedMods.UnbindAll();
Beatmap.Value.Mods.Value = new Mod[] { };
return base.OnExiting(next);
}
@ -479,6 +556,8 @@ namespace osu.Game.Screens.Select
/// <param name="beatmap">The working beatmap.</param>
protected virtual void UpdateBeatmap(WorkingBeatmap beatmap)
{
beatmap.Mods.BindTo(SelectedMods);
Logger.Log($"working beatmap updated to {beatmap}");
if (Background is BackgroundScreenBeatmap backgroundModeBeatmap)
@ -489,6 +568,11 @@ namespace osu.Game.Screens.Select
}
beatmapInfoWedge.Beatmap = beatmap;
BeatmapDetails.Beatmap = beatmap;
if (beatmap.Track != null)
beatmap.Track.Looping = true;
}
private void ensurePlayingSelected(bool preview = false)

View File

@ -16,8 +16,8 @@ namespace osu.Game.Skinning
{
public event Action SourceChanged;
private Bindable<bool> beatmapSkins = new Bindable<bool>();
private Bindable<bool> beatmapHitsounds = new Bindable<bool>();
private readonly Bindable<bool> beatmapSkins = new Bindable<bool>();
private readonly Bindable<bool> beatmapHitsounds = new Bindable<bool>();
public Drawable GetDrawableComponent(string componentName)
{
@ -84,11 +84,8 @@ namespace osu.Game.Skinning
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
beatmapSkins = config.GetBindable<bool>(OsuSetting.BeatmapSkins);
beatmapSkins.BindValueChanged(_ => onSourceChanged());
beatmapHitsounds = config.GetBindable<bool>(OsuSetting.BeatmapHitsounds);
beatmapHitsounds.BindValueChanged(_ => onSourceChanged(), true);
config.BindWith(OsuSetting.BeatmapSkins, beatmapSkins);
config.BindWith(OsuSetting.BeatmapHitsounds, beatmapHitsounds);
}
protected override void LoadComplete()
@ -97,6 +94,9 @@ namespace osu.Game.Skinning
if (fallbackSource != null)
fallbackSource.SourceChanged += onSourceChanged;
beatmapSkins.BindValueChanged(_ => onSourceChanged());
beatmapHitsounds.BindValueChanged(_ => onSourceChanged(), true);
}
protected override void Dispose(bool isDisposing)

View File

@ -15,10 +15,10 @@
<ProjectReference Include="..\osu-resources\osu.Game.Resources\osu.Game.Resources.csproj" />
</ItemGroup>
<ItemGroup Label="Package References">
<PackageReference Include="Humanizer" Version="2.5.1" />
<PackageReference Include="Humanizer" Version="2.5.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.1.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="2.1.4" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="2.2.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="SharpCompress" Version="0.22.0" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="SharpRaven" Version="2.4.0" />