-
Notifications
You must be signed in to change notification settings - Fork 435
/
Copy pathGame.cs
539 lines (422 loc) · 20.5 KB
/
Game.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Performance;
using osu.Framework.Graphics.Shaders;
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.Visualisation;
using osu.Framework.Graphics.Visualisation.Audio;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.Input.StateChanges;
using osu.Framework.IO.Stores;
using osu.Framework.Localisation;
using osu.Framework.Platform;
using osuTK;
namespace osu.Framework
{
public abstract partial class Game : Container, IKeyBindingHandler<FrameworkAction>, IKeyBindingHandler<PlatformAction>, IHandleGlobalKeyboardInput
{
public IWindow Window => Host?.Window;
public ResourceStore<byte[]> Resources { get; private set; }
public TextureStore Textures { get; private set; }
/// <summary>
/// The filtering mode to use for all textures fetched from <see cref="Textures"/>.
/// </summary>
protected virtual TextureFilteringMode DefaultTextureFilteringMode => TextureFilteringMode.Linear;
protected GameHost Host { get; private set; }
private readonly Bindable<bool> isActive = new Bindable<bool>(true);
/// <summary>
/// Whether the game is active (in the foreground).
/// </summary>
public IBindable<bool> IsActive => isActive;
public AudioManager Audio { get; private set; }
public ShaderManager Shaders { get; private set; }
/// <summary>
/// A store containing fonts accessible game-wide.
/// </summary>
/// <remarks>
/// It is recommended to use <see cref="AddFont"/> when adding new fonts.
/// </remarks>
public FontStore Fonts { get; private set; }
private FontStore localFonts;
protected LocalisationManager Localisation { get; private set; }
private readonly Container content;
private readonly Container overlayContent;
private DrawVisualiser drawVisualiser;
private TextureVisualiser textureVisualiser;
private LogOverlay logOverlay;
private AudioMixerVisualiser audioMixerVisualiser;
protected override Container<Drawable> Content => content;
/// <summary>
/// Creates a new <see cref="LocalisationManager"/>.
/// </summary>
/// <param name="frameworkConfig">The framework config manager.</param>
protected virtual LocalisationManager CreateLocalisationManager(FrameworkConfigManager frameworkConfig) => new LocalisationManager(frameworkConfig);
protected internal virtual UserInputManager CreateUserInputManager() => new UserInputManager();
/// <summary>
/// Provide <see cref="FrameworkSetting"/> defaults which should override those provided by osu-framework.
/// <remarks>
/// Please check https://github.com/ppy/osu-framework/blob/master/osu.Framework/Configuration/FrameworkConfigManager.cs for expected types.
/// </remarks>
/// </summary>
protected internal virtual IDictionary<FrameworkSetting, object> GetFrameworkConfigDefaults() => null;
/// <summary>
/// Creates the <see cref="Storage"/> where this <see cref="Game"/> will reside.
/// </summary>
/// <param name="host">The <see cref="GameHost"/>.</param>
/// <param name="defaultStorage">The default <see cref="Storage"/> to be used if a custom <see cref="Storage"/> isn't desired.</param>
/// <returns>The <see cref="Storage"/>.</returns>
protected internal virtual Storage CreateStorage(GameHost host, Storage defaultStorage) => defaultStorage;
protected Game()
{
RelativeSizeAxes = Axes.Both;
base.AddInternal(content = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
});
base.AddInternal(new SafeAreaContainer
{
RelativeSizeAxes = Axes.Both,
Child = overlayContent = new DrawSizePreservingFillContainer
{
TargetDrawSize = new Vector2(1280, 960),
RelativeSizeAxes = Axes.Both,
}
});
}
protected sealed override void AddInternal(Drawable drawable) => throw new InvalidOperationException($"Use {nameof(Add)} or {nameof(Content)} instead.");
/// <summary>
/// The earliest point of entry during <see cref="GameHost.Run"/> starting execution of a game.
/// This should be used to set up any low level tasks such as exception handling.
/// </summary>
/// <remarks>
/// At this point in execution, only <see cref="GameHost.Storage"/> and <see cref="GameHost.CacheStorage"/> are guaranteed to be valid for use.
/// They are provided as <paramref name="gameStorage"/> and <paramref name="cacheStorage"/> respectively for convenience.
/// </remarks>
/// <param name="gameStorage">The default game storage.</param>
/// <param name="cacheStorage">The default cache storage.</param>
public virtual void SetupLogging(Storage gameStorage, Storage cacheStorage)
{
}
/// <summary>
/// As Load is run post host creation, you can override this method to alter properties of the host before it makes itself visible to the user.
/// </summary>
/// <param name="host"></param>
public virtual void SetHost(GameHost host)
{
Host = host;
host.ExitRequested += RequestExit;
host.Activated += () => isActive.Value = true;
host.Deactivated += () => isActive.Value = false;
}
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) =>
dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
[BackgroundDependencyLoader]
private void load(FrameworkConfigManager config)
{
Resources = new ResourceStore<byte[]>();
Resources.AddStore(new NamespacedResourceStore<byte[]>(new DllResourceStore(typeof(Game).Assembly), @"Resources"));
Textures = new TextureStore(Host.Renderer, Host.CreateTextureLoaderStore(new NamespacedResourceStore<byte[]>(Resources, @"Textures")),
filteringMode: DefaultTextureFilteringMode);
Textures.AddTextureSource(Host.CreateTextureLoaderStore(CreateOnlineStore()));
dependencies.Cache(Textures);
var tracks = new ResourceStore<byte[]>();
tracks.AddStore(new NamespacedResourceStore<byte[]>(Resources, @"Tracks"));
tracks.AddStore(CreateOnlineStore());
var samples = new ResourceStore<byte[]>();
samples.AddStore(new NamespacedResourceStore<byte[]>(Resources, @"Samples"));
samples.AddStore(CreateOnlineStore());
Audio = new AudioManager(Host.AudioThread, tracks, samples) { EventScheduler = Scheduler };
dependencies.Cache(Audio);
dependencies.CacheAs(Audio.Tracks);
dependencies.CacheAs(Audio.Samples);
// attach our bindables to the audio subsystem.
config.BindWith(FrameworkSetting.AudioDevice, Audio.AudioDevice);
config.BindWith(FrameworkSetting.VolumeUniversal, Audio.Volume);
config.BindWith(FrameworkSetting.VolumeEffect, Audio.VolumeSample);
config.BindWith(FrameworkSetting.VolumeMusic, Audio.VolumeTrack);
Shaders = new ShaderManager(Host.Renderer, new NamespacedResourceStore<byte[]>(Resources, @"Shaders"));
dependencies.Cache(Shaders);
var cacheStorage = Host.CacheStorage.GetStorageForDirectory("fonts");
// base store is for user fonts
Fonts = new FontStore(Host.Renderer, useAtlas: true, cacheStorage: cacheStorage);
// nested store for framework provided fonts.
// note that currently this means there could be two async font load operations.
Fonts.AddStore(localFonts = new FontStore(Host.Renderer, useAtlas: false));
// Roboto (FrameworkFont.Regular)
addFont(localFonts, Resources, @"Fonts/Roboto/Roboto-Regular");
addFont(localFonts, Resources, @"Fonts/Roboto/Roboto-RegularItalic");
addFont(localFonts, Resources, @"Fonts/Roboto/Roboto-Bold");
addFont(localFonts, Resources, @"Fonts/Roboto/Roboto-BoldItalic");
// RobotoCondensed (FrameworkFont.Condensed)
addFont(localFonts, Resources, @"Fonts/RobotoCondensed/RobotoCondensed-Regular");
addFont(localFonts, Resources, @"Fonts/RobotoCondensed/RobotoCondensed-Bold");
addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Solid");
addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Regular");
addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Brands");
dependencies.Cache(Fonts);
Localisation = CreateLocalisationManager(config);
dependencies.CacheAs(Localisation);
frameSyncMode = config.GetBindable<FrameSync>(FrameworkSetting.FrameSync);
executionMode = config.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode);
logOverlayVisibility = config.GetBindable<bool>(FrameworkSetting.ShowLogOverlay);
logOverlayVisibility.BindValueChanged(visibility =>
{
if (visibility.NewValue)
{
if (logOverlay == null)
{
LoadComponentAsync(logOverlay = new LogOverlay
{
Depth = float.MinValue / 2,
}, overlayContent.Add);
}
logOverlay.Show();
}
else
{
logOverlay?.Hide();
}
}, true);
}
/// <summary>
/// Creates an <see cref="OnlineStore"/> to be used for online textures/tracks/samples lookups.
/// </summary>
protected virtual OnlineStore CreateOnlineStore() => new OnlineStore();
/// <summary>
/// Add a font to be globally accessible to the game.
/// </summary>
/// <param name="store">The backing store with font resources.</param>
/// <param name="assetName">The base name of the font.</param>
/// <param name="target">An optional target store to add the font to. If not specified, <see cref="Fonts"/> is used.</param>
public void AddFont(ResourceStore<byte[]> store, string assetName = null, FontStore target = null)
=> addFont(target ?? Fonts, store, assetName);
private void addFont(FontStore target, ResourceStore<byte[]> store, string assetName = null)
=> target.AddTextureSource(new RawCachingGlyphStore(store, assetName, Host.CreateTextureLoaderStore(store)));
protected override void LoadComplete()
{
base.LoadComplete();
PerformanceOverlay performanceOverlay;
LoadComponentAsync(performanceOverlay = new PerformanceOverlay
{
Margin = new MarginPadding(5),
Direction = FillDirection.Vertical,
Spacing = new Vector2(10, 10),
AutoSizeAxes = Axes.Both,
Alpha = 0,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
Depth = float.MinValue
}, overlayContent.Add);
FrameStatistics.BindValueChanged(e => performanceOverlay.State = e.NewValue, true);
if (FrameworkEnvironment.FrameStatisticsViaTouch)
{
base.AddInternal(new FrameStatisticsTouchReceptor(this)
{
Depth = float.MaxValue,
Anchor = Anchor.BottomRight,
Origin = Anchor.BottomRight,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.2f),
});
}
}
protected readonly Bindable<FrameStatisticsMode> FrameStatistics = new Bindable<FrameStatisticsMode>();
private GlobalStatisticsDisplay globalStatistics;
private Bindable<bool> logOverlayVisibility;
private Bindable<FrameSync> frameSyncMode;
private Bindable<ExecutionMode> executionMode;
private float currentOverlayDepth;
public bool OnPressed(KeyBindingPressEvent<FrameworkAction> e)
{
if (e.Repeat)
return false;
switch (e.Action)
{
case FrameworkAction.CycleFrameStatistics:
CycleFrameStatistics();
return true;
case FrameworkAction.ToggleDrawVisualiser:
if (drawVisualiser == null)
{
LoadComponentAsync(drawVisualiser = new DrawVisualiser
{
State = { Value = Visibility.Visible },
Depth = getNextFrontMostOverlayDepth(),
ToolPosition = getCascadeLocation(0),
}, overlayContent.Add);
}
else
toggleOverlay(drawVisualiser);
return true;
case FrameworkAction.ToggleGlobalStatistics:
if (globalStatistics == null)
{
LoadComponentAsync(globalStatistics = new GlobalStatisticsDisplay
{
State = { Value = Visibility.Visible },
Position = getCascadeLocation(1),
Depth = getNextFrontMostOverlayDepth(),
}, overlayContent.Add);
}
else
toggleOverlay(globalStatistics);
return true;
case FrameworkAction.ToggleAtlasVisualiser:
if (textureVisualiser == null)
{
LoadComponentAsync(textureVisualiser = new TextureVisualiser
{
State = { Value = Visibility.Visible },
Position = getCascadeLocation(2),
Depth = getNextFrontMostOverlayDepth(),
}, overlayContent.Add);
}
else
toggleOverlay(textureVisualiser);
return true;
case FrameworkAction.ToggleAudioMixerVisualiser:
if (audioMixerVisualiser == null)
{
LoadComponentAsync(audioMixerVisualiser = new AudioMixerVisualiser
{
State = { Value = Visibility.Visible },
Position = getCascadeLocation(3),
Depth = getNextFrontMostOverlayDepth(),
}, overlayContent.Add);
}
else
toggleOverlay(audioMixerVisualiser);
return true;
case FrameworkAction.ToggleLogOverlay:
logOverlayVisibility.Value = !logOverlayVisibility.Value;
return true;
case FrameworkAction.ToggleFullscreen:
Window?.CycleMode();
return true;
case FrameworkAction.CycleFrameSync:
var nextFrameSync = frameSyncMode.Value + 1;
if (nextFrameSync > FrameSync.Unlimited)
nextFrameSync = FrameSync.VSync;
frameSyncMode.Value = nextFrameSync;
break;
case FrameworkAction.CycleExecutionMode:
var nextExecutionMode = executionMode.Value + 1;
if (nextExecutionMode > ExecutionMode.MultiThreaded)
nextExecutionMode = ExecutionMode.SingleThread;
executionMode.Value = nextExecutionMode;
break;
}
return false;
static Vector2 getCascadeLocation(int index)
=> new Vector2(100 + index * (TitleBar.HEIGHT + 10));
}
protected void CycleFrameStatistics()
{
switch (FrameStatistics.Value)
{
case FrameStatisticsMode.None:
FrameStatistics.Value = FrameStatisticsMode.Minimal;
break;
case FrameStatisticsMode.Minimal:
FrameStatistics.Value = FrameStatisticsMode.Full;
break;
case FrameStatisticsMode.Full:
FrameStatistics.Value = FrameStatisticsMode.None;
break;
}
}
private void toggleOverlay(OverlayContainer overlay)
{
overlay.ToggleVisibility();
if (overlay.State.Value == Visibility.Visible)
overlayContent.ChangeChildDepth(overlay, getNextFrontMostOverlayDepth());
}
private float getNextFrontMostOverlayDepth() => currentOverlayDepth -= 0.01f;
public void OnReleased(KeyBindingReleaseEvent<FrameworkAction> e)
{
}
public virtual bool OnPressed(KeyBindingPressEvent<PlatformAction> e)
{
if (e.Repeat)
return false;
switch (e.Action)
{
case PlatformAction.Exit:
RequestExit();
return true;
}
return false;
}
public virtual void OnReleased(KeyBindingReleaseEvent<PlatformAction> e)
{
}
/// <summary>
/// Requests the game to exit. This exit can be blocked by <see cref="OnExiting"/>.
/// </summary>
public void RequestExit()
{
if (!OnExiting())
Exit();
}
/// <summary>
/// Force-closes the game, ignoring <see cref="OnExiting"/> return value.
/// </summary>
public void Exit()
{
if (Host == null)
throw new InvalidOperationException("Attempted to exit a game which has not yet been run");
Host.Exit();
}
/// <summary>
/// Fired when an exit has been requested.
/// </summary>
/// <remarks>Usually fired because <see cref="PlatformAction.Exit"/> or the window close (X) button was pressed.</remarks>
/// <returns>Return <c>true</c> to block the exit process.</returns>
protected virtual bool OnExiting() => false;
protected override void Dispose(bool isDisposing)
{
// ensure any async disposals are completed before we begin to rip components out.
// if we were to not wait, async disposals may throw unexpected exceptions.
AsyncDisposalQueue.WaitForEmpty();
base.Dispose(isDisposing);
// call a second time to protect against anything being potentially async disposed in the base.Dispose call.
AsyncDisposalQueue.WaitForEmpty();
Audio?.Dispose();
Audio = null;
Fonts?.Dispose();
Fonts = null;
localFonts?.Dispose();
localFonts = null;
Localisation?.Dispose();
Localisation = null;
}
private partial class FrameStatisticsTouchReceptor : Drawable
{
private readonly Game game;
public FrameStatisticsTouchReceptor(Game game)
{
this.game = game;
}
protected override bool OnClick(ClickEvent e) => e.CurrentState.Mouse.LastSource is ISourcedFromTouch;
protected override bool OnDoubleClick(DoubleClickEvent e)
{
game.CycleFrameStatistics();
return base.OnDoubleClick(e);
}
}
}
}