From cd278b4ff6304236f729f0e64649116869e5cc05 Mon Sep 17 00:00:00 2001 From: vddCore Date: Thu, 25 Jul 2024 09:43:35 +0200 Subject: [PATCH] ...do the same for examples. --- Chroma.Examples/ArbitraryGeometry/GameCore.cs | 398 +++++++------- Chroma.Examples/ArbitraryGeometry/Program.cs | 3 +- Chroma.Examples/Asynchronicity/GameCore.cs | 168 +++--- Chroma.Examples/Asynchronicity/Program.cs | 3 +- Chroma.Examples/AudioRecording/GameCore.cs | 135 +++-- Chroma.Examples/AudioRecording/Program.cs | 3 +- Chroma.Examples/BoingBall/GameCore.cs | 294 +++++----- Chroma.Examples/BoingBall/Program.cs | 3 +- Chroma.Examples/CallbackHooks/GameCore.cs | 97 ++-- Chroma.Examples/CallbackHooks/Program.cs | 3 +- Chroma.Examples/Cameras/GameCore.cs | 219 ++++---- Chroma.Examples/Cameras/Program.cs | 3 +- Chroma.Examples/CellularAutomaton/Cell.cs | 41 +- .../CellularAutomaton/CorruptorCell.cs | 73 ++- .../CellularAutomaton/FaderCell.cs | 59 +- Chroma.Examples/CellularAutomaton/GameCore.cs | 83 ++- Chroma.Examples/CellularAutomaton/Map.cs | 163 +++--- Chroma.Examples/CellularAutomaton/Program.cs | 3 +- Chroma.Examples/Clipboard/GameCore.cs | 39 +- Chroma.Examples/Clipboard/Program.cs | 3 +- .../CustomContentProvider/GameCore.cs | 82 ++- .../CustomContentProvider/Program.cs | 3 +- .../ZipContentProvider.cs | 154 +++--- .../CustomHardwareCursor/GameCore.cs | 87 ++- .../CustomHardwareCursor/Program.cs | 3 +- Chroma.Examples/DrawBatching/GameCore.cs | 91 ++-- Chroma.Examples/DrawBatching/Program.cs | 3 +- Chroma.Examples/EmptyProject/GameCore.cs | 15 +- Chroma.Examples/EmptyProject/Program.cs | 3 +- Chroma.Examples/FixedTimeStep/GameCore.cs | 119 ++--- Chroma.Examples/FixedTimeStep/Program.cs | 3 +- Chroma.Examples/Fonts/GameCore.cs | 235 ++++---- Chroma.Examples/Fonts/Program.cs | 3 +- Chroma.Examples/GameController/GameCore.cs | 129 +++-- Chroma.Examples/GameController/PlayerView.cs | 33 +- Chroma.Examples/GameController/Program.cs | 3 +- .../Views/DualSenseControllerView.cs | 202 ++++--- .../Views/DualShockControllerView.cs | 161 +++--- .../Views/GenericControllerView.cs | 502 +++++++++--------- .../Views/NintendoControllerView.cs | 168 +++--- Chroma.Examples/GlyphTransforms/GameCore.cs | 246 +++++---- Chroma.Examples/GlyphTransforms/Program.cs | 3 +- .../InstancedSoundPlayback/GameCore.cs | 77 ++- .../InstancedSoundPlayback/InstancedSound.cs | 95 ++-- .../InstancedSoundPlayback/Program.cs | 3 +- Chroma.Examples/KeyboardInput/GameCore.cs | 130 +++-- Chroma.Examples/KeyboardInput/Program.cs | 3 +- Chroma.Examples/LerpingCameras/GameCore.cs | 75 ++- Chroma.Examples/LerpingCameras/LerpCamera.cs | 83 ++- Chroma.Examples/LerpingCameras/Program.cs | 4 +- Chroma.Examples/MusicAndSounds/GameCore.cs | 384 +++++++------- Chroma.Examples/MusicAndSounds/Program.cs | 3 +- Chroma.Examples/ParticleSystems/GameCore.cs | 137 +++-- Chroma.Examples/ParticleSystems/Program.cs | 3 +- Chroma.Examples/PixelShaders/GameCore.cs | 199 ++++--- Chroma.Examples/PixelShaders/Program.cs | 3 +- Chroma.Examples/PixelShaders2/GameCore.cs | 296 +++++------ Chroma.Examples/PixelShaders2/Program.cs | 3 +- Chroma.Examples/Pong/Assets.cs | 36 +- Chroma.Examples/Pong/Ball.cs | 164 +++--- Chroma.Examples/Pong/Board.cs | 192 ++++--- Chroma.Examples/Pong/GameCore.cs | 43 +- Chroma.Examples/Pong/Paddle.cs | 100 ++-- Chroma.Examples/Pong/Program.cs | 3 +- Chroma.Examples/PrimitiveShapes/GameCore.cs | 256 +++++---- Chroma.Examples/PrimitiveShapes/Program.cs | 3 +- Chroma.Examples/ProgressFlag/GameCore.cs | 173 +++--- Chroma.Examples/ProgressFlag/Program.cs | 3 +- Chroma.Examples/RenderTargets/GameCore.cs | 121 +++-- Chroma.Examples/RenderTargets/Program.cs | 3 +- Chroma.Examples/RenderTransforms/GameCore.cs | 97 ++-- Chroma.Examples/RenderTransforms/Program.cs | 3 +- Chroma.Examples/Scissors/GameCore.cs | 149 +++--- Chroma.Examples/Scissors/Program.cs | 3 +- Chroma.Examples/Scissors/ResizeBorder.cs | 15 +- Chroma.Examples/TextInput/GameCore.cs | 243 +++++---- Chroma.Examples/TextInput/Program.cs | 3 +- Chroma.Examples/TextInput/Terminal.cs | 161 +++--- Chroma.Examples/TextInput/VGA.cs | 273 +++++----- Chroma.Examples/Textures/GameCore.cs | 333 ++++++------ Chroma.Examples/Textures/Program.cs | 3 +- Chroma.Examples/WindowOperations/GameCore.cs | 339 ++++++------ Chroma.Examples/WindowOperations/Program.cs | 3 +- 83 files changed, 4109 insertions(+), 4152 deletions(-) diff --git a/Chroma.Examples/ArbitraryGeometry/GameCore.cs b/Chroma.Examples/ArbitraryGeometry/GameCore.cs index 34b663c2..aa8be87a 100644 --- a/Chroma.Examples/ArbitraryGeometry/GameCore.cs +++ b/Chroma.Examples/ArbitraryGeometry/GameCore.cs @@ -1,3 +1,5 @@ +namespace ArbitraryGeometry; + using System; using System.IO; using System.Numerics; @@ -6,227 +8,223 @@ using Chroma.ContentManagement.FileSystem; using Chroma.Graphics; using Chroma.Graphics.Accelerated; -using Chroma.Graphics.TextRendering; using Chroma.Graphics.TextRendering.TrueType; -namespace ArbitraryGeometry +public class GameCore : Game { - public class GameCore : Game + private Texture _texture; + private PixelShader _ps; + private float _t; + + private float[] _box = new[] { - private Texture _texture; - private PixelShader _ps; - private float _t; + -0.25f, -0.25f, -0.25f, + -0.25f, -0.25f, 0.25f, + -0.25f, 0.25f, 0.25f, + 0.25f, 0.25f, -0.25f, + -0.25f, -0.25f, -0.25f, + -0.25f, 0.25f, -0.25f, + 0.25f, -0.25f, 0.25f, + -0.25f, -0.25f, -0.25f, + 0.25f, -0.25f, -0.25f, + 0.25f, 0.25f, -0.25f, + 0.25f, -0.25f, -0.25f, + -0.25f, -0.25f, -0.25f, + -0.25f, -0.25f, -0.25f, + -0.25f, 0.25f, 0.25f, + -0.25f, 0.25f, -0.25f, + 0.25f, -0.25f, 0.25f, + -0.25f, -0.25f, 0.25f, + -0.25f, -0.25f, -0.25f, + -0.25f, 0.25f, 0.25f, + -0.25f, -0.25f, 0.25f, + 0.25f, -0.25f, 0.25f, + 0.25f, 0.25f, 0.25f, + 0.25f, -0.25f, -0.25f, + 0.25f, 0.25f, -0.25f, + 0.25f, -0.25f, -0.25f, + 0.25f, 0.25f, 0.25f, + 0.25f, -0.25f, 0.25f, + 0.25f, 0.25f, 0.25f, + 0.25f, 0.25f, -0.25f, + -0.25f, 0.25f, -0.25f, + 0.25f, 0.25f, 0.25f, + -0.25f, 0.25f, -0.25f, + -0.25f, 0.25f, 0.25f, + 0.25f, 0.25f, 0.25f, + -0.25f, 0.25f, 0.25f, + 0.25f, -0.25f, 0.25f, + }; + + public GameCore() : base(new(false, true, 4)) + { + RenderSettings.MultiSamplingEnabled = true; + } - private float[] _box = new[] - { - -0.25f, -0.25f, -0.25f, - -0.25f, -0.25f, 0.25f, - -0.25f, 0.25f, 0.25f, - 0.25f, 0.25f, -0.25f, - -0.25f, -0.25f, -0.25f, - -0.25f, 0.25f, -0.25f, - 0.25f, -0.25f, 0.25f, - -0.25f, -0.25f, -0.25f, - 0.25f, -0.25f, -0.25f, - 0.25f, 0.25f, -0.25f, - 0.25f, -0.25f, -0.25f, - -0.25f, -0.25f, -0.25f, - -0.25f, -0.25f, -0.25f, - -0.25f, 0.25f, 0.25f, - -0.25f, 0.25f, -0.25f, - 0.25f, -0.25f, 0.25f, - -0.25f, -0.25f, 0.25f, - -0.25f, -0.25f, -0.25f, - -0.25f, 0.25f, 0.25f, - -0.25f, -0.25f, 0.25f, - 0.25f, -0.25f, 0.25f, - 0.25f, 0.25f, 0.25f, - 0.25f, -0.25f, -0.25f, - 0.25f, 0.25f, -0.25f, - 0.25f, -0.25f, -0.25f, - 0.25f, 0.25f, 0.25f, - 0.25f, -0.25f, 0.25f, - 0.25f, 0.25f, 0.25f, - 0.25f, 0.25f, -0.25f, - -0.25f, 0.25f, -0.25f, - 0.25f, 0.25f, 0.25f, - -0.25f, 0.25f, -0.25f, - -0.25f, 0.25f, 0.25f, - 0.25f, 0.25f, 0.25f, - -0.25f, 0.25f, 0.25f, - 0.25f, -0.25f, 0.25f, - }; - - public GameCore() : base(new(false, true, 4)) - { - RenderSettings.MultiSamplingEnabled = true; - } + protected override void Initialize(IContentProvider content) + { + _texture = new Texture(1, 1); + _texture[0, 0] = Color.White; - protected override void Initialize(IContentProvider content) - { - _texture = new Texture(1, 1); - _texture[0, 0] = Color.White; + _ps = content.Load("Shaders/untextured.frag"); + } - _ps = content.Load("Shaders/untextured.frag"); - } + private void With3D(Action action) + { + RenderTransform.SetMatrixMode(MatrixMode.Model, Window); + RenderTransform.Push(); + RenderTransform.LoadIdentity(); - private void With3D(Action action) - { - RenderTransform.SetMatrixMode(MatrixMode.Model, Window); - RenderTransform.Push(); - RenderTransform.LoadIdentity(); + RenderTransform.SetMatrixMode(MatrixMode.View, Window); + RenderTransform.Push(); + RenderTransform.LoadIdentity(); - RenderTransform.SetMatrixMode(MatrixMode.View, Window); - RenderTransform.Push(); - RenderTransform.LoadIdentity(); + RenderTransform.SetMatrixMode(MatrixMode.Projection, Window); + RenderTransform.Push(); + RenderTransform.LoadIdentity(); - RenderTransform.SetMatrixMode(MatrixMode.Projection, Window); - RenderTransform.Push(); - RenderTransform.LoadIdentity(); + action(); - action(); + RenderTransform.SetMatrixMode(MatrixMode.Projection, Window); + RenderTransform.Pop(); - RenderTransform.SetMatrixMode(MatrixMode.Projection, Window); - RenderTransform.Pop(); + RenderTransform.SetMatrixMode(MatrixMode.View, Window); + RenderTransform.Pop(); - RenderTransform.SetMatrixMode(MatrixMode.View, Window); - RenderTransform.Pop(); + RenderTransform.SetMatrixMode(MatrixMode.Model, Window); + RenderTransform.Pop(); + } - RenderTransform.SetMatrixMode(MatrixMode.Model, Window); - RenderTransform.Pop(); - } + protected override IContentProvider InitializeContentPipeline() + { + return new FileSystemContentProvider( + Path.Combine( + AppContext.BaseDirectory, + "../../../../_common" + ) + ); + } - protected override IContentProvider InitializeContentPipeline() - { - return new FileSystemContentProvider( - Path.Combine( - AppContext.BaseDirectory, - "../../../../_common" - ) - ); - } + protected override void Update(float delta) + { + _t += delta; + } - protected override void Update(float delta) + protected override void Draw(RenderContext context) + { + _ps.Activate(); + RenderSettings.DepthTestingEnabled = true; { - _t += delta; + With3D(() => + { + RenderTransform.Translate( + new Vector3( + 0, + MathF.Sin(_t) * 0.5f, + 0 + ) + ); + + RenderTransform.Rotate(111 * _t, new Vector3(0, 0.5f, 0.5f)); + RenderTransform.Rotate(27 * _t, new Vector3(0.5f, 0.5f, 0.0f)); + + _ps.SetUniform("tri_color", Color.Red); + context.RenderArbitraryGeometry( + _texture, + VertexFormat.XYZ, + 36, + _box, + new ushort[] + { + 3, 4, 5, + 9, 10, 11 + } + ); + + _ps.SetUniform("tri_color", Color.Magenta); + context.RenderArbitraryGeometry( + _texture, + VertexFormat.XYZ, + 36, + _box, + new ushort[] + { + 0, 1, 2, + 12, 13, 14, + } + ); + + _ps.SetUniform("tri_color", Color.Yellow); + context.RenderArbitraryGeometry( + _texture, + VertexFormat.XYZ, + 36, + _box, + new ushort[] + { + 6, 7, 8, + 15, 16, 17, + } + ); + + _ps.SetUniform("tri_color", Color.CornflowerBlue); + context.RenderArbitraryGeometry( + _texture, + VertexFormat.XYZ, + 36, + _box, + new ushort[] + { + 18, 19, 20, + 33, 34, 35 + } + ); + + _ps.SetUniform("tri_color", Color.White); + context.RenderArbitraryGeometry( + _texture, + VertexFormat.XYZ, + 36, + _box, + new ushort[] + { + 21, 22, 23, + 24, 25, 26, + } + ); + + _ps.SetUniform("tri_color", Color.Lime); + context.RenderArbitraryGeometry( + _texture, + VertexFormat.XYZ, + 36, + _box, + new ushort[] + { + 27, 28, 29, + 30, 31, 32, + } + ); + }); } + RenderSettings.DepthTestingEnabled = false; + Shader.Deactivate(); - protected override void Draw(RenderContext context) - { - _ps.Activate(); - RenderSettings.DepthTestingEnabled = true; + var text = "I'm just some random text don't mind me :)"; + var measure = TrueTypeFont.Default.Measure(text); + + context.DrawString( + text, + new Vector2( + Window.Center.X - (measure.Width / 2), + Window.Center.Y + ), + (d, _, i, p) => { - With3D(() => - { - RenderTransform.Translate( - new Vector3( - 0, - MathF.Sin(_t) * 0.5f, - 0 - ) - ); - - RenderTransform.Rotate(111 * _t, new Vector3(0, 0.5f, 0.5f)); - RenderTransform.Rotate(27 * _t, new Vector3(0.5f, 0.5f, 0.0f)); - - _ps.SetUniform("tri_color", Color.Red); - context.RenderArbitraryGeometry( - _texture, - VertexFormat.XYZ, - 36, - _box, - new ushort[] - { - 3, 4, 5, - 9, 10, 11 - } - ); - - _ps.SetUniform("tri_color", Color.Magenta); - context.RenderArbitraryGeometry( - _texture, - VertexFormat.XYZ, - 36, - _box, - new ushort[] - { - 0, 1, 2, - 12, 13, 14, - } - ); - - _ps.SetUniform("tri_color", Color.Yellow); - context.RenderArbitraryGeometry( - _texture, - VertexFormat.XYZ, - 36, - _box, - new ushort[] - { - 6, 7, 8, - 15, 16, 17, - } - ); - - _ps.SetUniform("tri_color", Color.CornflowerBlue); - context.RenderArbitraryGeometry( - _texture, - VertexFormat.XYZ, - 36, - _box, - new ushort[] - { - 18, 19, 20, - 33, 34, 35 - } - ); - - _ps.SetUniform("tri_color", Color.White); - context.RenderArbitraryGeometry( - _texture, - VertexFormat.XYZ, - 36, - _box, - new ushort[] - { - 21, 22, 23, - 24, 25, 26, - } - ); - - _ps.SetUniform("tri_color", Color.Lime); - context.RenderArbitraryGeometry( - _texture, - VertexFormat.XYZ, - 36, - _box, - new ushort[] - { - 27, 28, 29, - 30, 31, 32, - } - ); - }); + d.Color = Color.Orange; + d.Position = p + new Vector2(0, MathF.Sin(_t * 4 + i) * 4); } - RenderSettings.DepthTestingEnabled = false; - Shader.Deactivate(); - - var text = "I'm just some random text don't mind me :)"; - var measure = TrueTypeFont.Default.Measure(text); - - context.DrawString( - text, - new Vector2( - Window.Center.X - (measure.Width / 2), - Window.Center.Y - ), - (d, _, i, p) => - { - d.Color = Color.Orange; - d.Position = p + new Vector2(0, MathF.Sin(_t * 4 + i) * 4); - } - ); - } + ); } } \ No newline at end of file diff --git a/Chroma.Examples/ArbitraryGeometry/Program.cs b/Chroma.Examples/ArbitraryGeometry/Program.cs index 3b8e8a13..6e97285c 100644 --- a/Chroma.Examples/ArbitraryGeometry/Program.cs +++ b/Chroma.Examples/ArbitraryGeometry/Program.cs @@ -1,3 +1,4 @@ using ArbitraryGeometry; -new GameCore().Run(); \ No newline at end of file +using(var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/Asynchronicity/GameCore.cs b/Chroma.Examples/Asynchronicity/GameCore.cs index 3213d917..3b2e3903 100644 --- a/Chroma.Examples/Asynchronicity/GameCore.cs +++ b/Chroma.Examples/Asynchronicity/GameCore.cs @@ -1,127 +1,125 @@ -using System; +namespace Asynchronicity; + +using System; using System.Drawing; using System.Numerics; using System.Threading.Tasks; using Chroma; -using Chroma.ContentManagement; using Chroma.Diagnostics.Logging; using Chroma.Graphics; using Chroma.Input; using Chroma.Threading; using Color = System.Drawing.Color; -namespace Asynchronicity +public class GameCore : Game { - public class GameCore : Game - { - private static readonly Log _log = LogManager.GetForCurrentAssembly(); + private static readonly Log _log = LogManager.GetForCurrentAssembly(); - private RenderTarget _target; - private Task _longRunningTask; + private RenderTarget _target; + private Task _longRunningTask; - public GameCore() : base(new(false, false)) + public GameCore() : base(new(false, false)) + { + _longRunningTask = new Task(async () => { - _longRunningTask = new Task(async () => + while (true) { - while (true) - { - ProcessInSeparateTask(); - await Task.Delay(10); - } - }); + ProcessInSeparateTask(); + await Task.Delay(10); + } + }); - _longRunningTask.Start(); - } + _longRunningTask.Start(); + } - protected override void Draw(RenderContext context) - { - context.DrawString( - "Press to asynchronously dispose and recreate the render target\n" + - "causing an InvalidOperationException.\n\n" + - "Press to asynchronously queue the render target creation for execution on the main thread.\n" + - "Press to asynchronously queue render target destruction for execution on the main thread.", - new Vector2(8) - ); + protected override void Draw(RenderContext context) + { + context.DrawString( + "Press to asynchronously dispose and recreate the render target\n" + + "causing an InvalidOperationException.\n\n" + + "Press to asynchronously queue the render target creation for execution on the main thread.\n" + + "Press to asynchronously queue render target destruction for execution on the main thread.", + new Vector2(8) + ); - if (_target != null && !_target.Disposed) + if (_target != null && !_target.Disposed) + { + context.RenderTo(_target, (ctx, tgt) => { - context.RenderTo(_target, (ctx, tgt) => - { - ctx.Rectangle( - ShapeMode.Fill, - new Vector2(16), - new Size(32, 32), - Color.Aqua - ); - }); + ctx.Rectangle( + ShapeMode.Fill, + new Vector2(16), + new Size(32, 32), + Color.Aqua + ); + }); - context.DrawTexture(_target, Vector2.Zero, Vector2.One, Vector2.Zero, 0); - } + context.DrawTexture(_target, Vector2.Zero, Vector2.One, Vector2.Zero, 0); } + } - protected override void Update(float delta) - { - } + protected override void Update(float delta) + { + } - protected override void KeyPressed(KeyEventArgs e) + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.F1) { - if (e.KeyCode == KeyCode.F1) + Task.Run(() => { - Task.Run(() => + try { - try - { - _target?.Dispose(); - _target = new RenderTarget(Window.Size); - } - catch (InvalidOperationException ioe) - { - _log.Error($"Caught exception: {ioe.Message}"); - } - }); - } - else if (e.KeyCode == KeyCode.F2) + _target?.Dispose(); + _target = new RenderTarget(Window.Size); + } + catch (InvalidOperationException ioe) + { + _log.Error($"Caught exception: {ioe.Message}"); + } + }); + } + else if (e.KeyCode == KeyCode.F2) + { + Task.Run(async () => { - Task.Run(async () => + await Dispatcher.RunOnMainThread(() => { - await Dispatcher.RunOnMainThread(() => + if (_target != null && !_target.Disposed) { - if (_target != null && !_target.Disposed) - { - _target.Dispose(); - } + _target.Dispose(); + } - _target = new RenderTarget(Window.Size); - }); + _target = new RenderTarget(Window.Size); }); - } - else if (e.KeyCode == KeyCode.F3) + }); + } + else if (e.KeyCode == KeyCode.F3) + { + Task.Run(async () => { - Task.Run(async () => + await Dispatcher.RunOnMainThread(() => { - await Dispatcher.RunOnMainThread(() => + if (_target != null && !_target.Disposed) { - if (_target != null && !_target.Disposed) - { - _target.Dispose(); - } - }); + _target.Dispose(); + } }); - } + }); } + } - private void ProcessInSeparateTask() + private void ProcessInSeparateTask() + { + var target = Dispatcher.RunOnMainThread(() => { - var target = Dispatcher.RunOnMainThread(() => - { - return new RenderTarget(10, 10); - }, true).Result; + return new RenderTarget(10, 10); + }, true).Result; - if (target != null) - { - _log.Info(target.ToString()); - Dispatcher.RunOnMainThread(target.Dispose, true).GetAwaiter().GetResult(); - } + if (target != null) + { + _log.Info(target.ToString()); + Dispatcher.RunOnMainThread(target.Dispose, true).GetAwaiter().GetResult(); } } } \ No newline at end of file diff --git a/Chroma.Examples/Asynchronicity/Program.cs b/Chroma.Examples/Asynchronicity/Program.cs index 525362aa..722f8c4a 100644 --- a/Chroma.Examples/Asynchronicity/Program.cs +++ b/Chroma.Examples/Asynchronicity/Program.cs @@ -1,3 +1,4 @@ using Asynchronicity; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/AudioRecording/GameCore.cs b/Chroma.Examples/AudioRecording/GameCore.cs index b2c23f61..ed8f0e33 100644 --- a/Chroma.Examples/AudioRecording/GameCore.cs +++ b/Chroma.Examples/AudioRecording/GameCore.cs @@ -1,3 +1,5 @@ +namespace AudioRecording; + using System; using System.IO; using Chroma; @@ -7,91 +9,88 @@ using Chroma.Graphics; using Chroma.Input; -namespace AudioRecording +public class GameCore : Game { - public class GameCore : Game - { - private AudioCapture _recording; - private MemoryStream _stream = new(); + private AudioCapture _recording; + private MemoryStream _stream = new(); + + private Waveform _waveform; - private Waveform _waveform; + private byte[] _data; + private int _dataPointer; + + public GameCore() : base(new(false, false)) + { + } - private byte[] _data; - private int _dataPointer; + protected override void Draw(RenderContext context) + { + context.DrawString( + "Press to start recording.\n" + + "Press to stop the recording.\n" + + "Press to pause/resume the recording.\n" + + "Press to play the recorded sample back.", + new(8) + ); - public GameCore() : base(new(false, false)) + if (_recording != null) { + Window.Title = $"{_recording.Status} | {_recording.TotalSize}"; } + } - protected override void Draw(RenderContext context) + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.F1) { - context.DrawString( - "Press to start recording.\n" + - "Press to stop the recording.\n" + - "Press to pause/resume the recording.\n" + - "Press to play the recorded sample back.", - new(8) - ); - if (_recording != null) - { - Window.Title = $"{_recording.Status} | {_recording.TotalSize}"; - } + _recording.Dispose(); + + _recording = new StreamAudioCapture(_stream); + _recording.Start(); } + else if (e.KeyCode == KeyCode.F2) + { + if (_recording == null) + return; - protected override void KeyPressed(KeyEventArgs e) + _recording.Stop(); + } + else if (e.KeyCode == KeyCode.F3) { - if (e.KeyCode == KeyCode.F1) - { - if (_recording != null) - _recording.Dispose(); - - _recording = new StreamAudioCapture(_stream); - _recording.Start(); - } - else if (e.KeyCode == KeyCode.F2) - { - if (_recording == null) - return; + if (_recording == null) + return; + if (_recording.Status == CaptureStatus.Paused) + _recording.Resume(); + else if (_recording.Status == CaptureStatus.Recording) + _recording.Pause(); + } + else if (e.KeyCode == KeyCode.F4) + { + if (_recording.Status != CaptureStatus.Stopped) _recording.Stop(); - } - else if (e.KeyCode == KeyCode.F3) - { - if (_recording == null) - return; - - if (_recording.Status == CaptureStatus.Paused) - _recording.Resume(); - else if (_recording.Status == CaptureStatus.Recording) - _recording.Pause(); - } - else if (e.KeyCode == KeyCode.F4) - { - if (_recording.Status != CaptureStatus.Stopped) - _recording.Stop(); - - if (_waveform != null) - _waveform.Dispose(); - - _data = _stream.GetBuffer(); - - _waveform = new Waveform( - _recording.Format, - PlaybackDelegate, - _recording.ChannelMode - ); - - _waveform.Play(); - } + + if (_waveform != null) + _waveform.Dispose(); + + _data = _stream.GetBuffer(); + + _waveform = new Waveform( + _recording.Format, + PlaybackDelegate, + _recording.ChannelMode + ); + + _waveform.Play(); } + } - private void PlaybackDelegate(Span data, AudioFormat format) + private void PlaybackDelegate(Span data, AudioFormat format) + { + for (var i = 0; i < data.Length && _dataPointer < _data.Length; i++, _dataPointer++) { - for (var i = 0; i < data.Length && _dataPointer < _data.Length; i++, _dataPointer++) - { - data[i] = _data[_dataPointer]; - } + data[i] = _data[_dataPointer]; } } } \ No newline at end of file diff --git a/Chroma.Examples/AudioRecording/Program.cs b/Chroma.Examples/AudioRecording/Program.cs index f64f4097..81b25b71 100644 --- a/Chroma.Examples/AudioRecording/Program.cs +++ b/Chroma.Examples/AudioRecording/Program.cs @@ -1,3 +1,4 @@ using AudioRecording; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/BoingBall/GameCore.cs b/Chroma.Examples/BoingBall/GameCore.cs index ee2b0051..bce84e53 100644 --- a/Chroma.Examples/BoingBall/GameCore.cs +++ b/Chroma.Examples/BoingBall/GameCore.cs @@ -1,5 +1,6 @@ +namespace BoingBall; + using System; -using System.Drawing; using System.IO; using System.Numerics; using Chroma; @@ -10,188 +11,185 @@ using Chroma.Graphics.Accelerated; using Chroma.Input; -namespace BoingBall +public class GameCore : Game { - public class GameCore : Game + private enum EffectMode { - private enum EffectMode - { - Shadow, - Sphere, - Shade - } + Shadow, + Sphere, + Shade + } - private static readonly Vector2 _maxPos = new(175, 96); - private Vector2 _pos = Vector2.Zero; - private Vector2 _dir = Vector2.One; - private Vector2 _vel = new(45, 0); - private float _grav = 3.2f; + private static readonly Vector2 _maxPos = new(175, 96); + private Vector2 _pos = Vector2.Zero; + private Vector2 _dir = Vector2.One; + private Vector2 _vel = new(45, 0); + private float _grav = 3.2f; - private float _texshift; - private RenderTarget _target; - private Texture _texture; - private Texture _shade; - private Cursor _cursor; - private Effect _effect; + private float _texshift; + private RenderTarget _target; + private Texture _texture; + private Texture _shade; + private Cursor _cursor; + private Effect _effect; - private Sound _bounce1; - private Sound _bounce2; + private Sound _bounce1; + private Sound _bounce2; - public GameCore() - : base(new(false, false)) - { - Window.Mode.SetWindowed(960, 600, true); - FixedTimeStepTarget = 60; - } + public GameCore() + : base(new(false, false)) + { + Window.Mode.SetWindowed(960, 600, true); + FixedTimeStepTarget = 60; + } - protected override IContentProvider InitializeContentPipeline() - { - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); - } + protected override IContentProvider InitializeContentPipeline() + { + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } - protected override void Initialize(IContentProvider content) - { - _target = new RenderTarget(320, 200); - _target.VirtualResolution = new(Window.Width, Window.Height); - _target.FilteringMode = TextureFilteringMode.NearestNeighbor; + protected override void Initialize(IContentProvider content) + { + _target = new RenderTarget(320, 200); + _target.VirtualResolution = new(Window.Width, Window.Height); + _target.FilteringMode = TextureFilteringMode.NearestNeighbor; - _texture = content.Load("Textures/boing.png"); - _texture.FilteringMode = TextureFilteringMode.NearestNeighbor; - _texture.VerticalWrappingMode = TextureWrappingMode.Repeat; - _texture.HorizontalWrappingMode = TextureWrappingMode.Repeat; + _texture = content.Load("Textures/boing.png"); + _texture.FilteringMode = TextureFilteringMode.NearestNeighbor; + _texture.VerticalWrappingMode = TextureWrappingMode.Repeat; + _texture.HorizontalWrappingMode = TextureWrappingMode.Repeat; - _shade = content.Load("Textures/shade.png"); - _shade.FilteringMode = TextureFilteringMode.NearestNeighbor; + _shade = content.Load("Textures/shade.png"); + _shade.FilteringMode = TextureFilteringMode.NearestNeighbor; - _cursor = content.Load("Cursors/ami13.png"); - _cursor.SetCurrent(); + _cursor = content.Load("Cursors/ami13.png"); + _cursor.SetCurrent(); - _effect = content.Load("Shaders/distort.frag"); - _bounce1 = content.Load("Sounds/bounce1.ogg"); - _bounce2 = content.Load("Sounds/bounce2.ogg"); - } + _effect = content.Load("Shaders/distort.frag"); + _bounce1 = content.Load("Sounds/bounce1.ogg"); + _bounce2 = content.Load("Sounds/bounce2.ogg"); + } - protected override void FixedUpdate(float delta) - { - _texshift += delta / 1.66f * _dir.X; + protected override void FixedUpdate(float delta) + { + _texshift += delta / 1.66f * _dir.X; - if (_dir.Y > 0) - { - _vel.Y += _grav * delta; - } - else - { - _vel.Y -= _grav * delta; + if (_dir.Y > 0) + { + _vel.Y += _grav * delta; + } + else + { + _vel.Y -= _grav * delta; - if (_vel.Y < 0) - { - _vel.Y = 0; - _dir.Y *= -1; - } + if (_vel.Y < 0) + { + _vel.Y = 0; + _dir.Y *= -1; } + } - _pos.X += _dir.X * _vel.X * delta; - _pos.Y += _dir.Y * _vel.Y; + _pos.X += _dir.X * _vel.X * delta; + _pos.Y += _dir.Y * _vel.Y; - if (_pos.X > _maxPos.X) - { - _dir.X *= -1; - _pos.X = _maxPos.X - 1; + if (_pos.X > _maxPos.X) + { + _dir.X *= -1; + _pos.X = _maxPos.X - 1; - _bounce2.Play(); - } + _bounce2.Play(); + } - if (_pos.X < 0) - { - _dir.X *= -1; - _pos.X = 0; + if (_pos.X < 0) + { + _dir.X *= -1; + _pos.X = 0; - _bounce2.Play(); - } + _bounce2.Play(); + } - if (_pos.Y > _maxPos.Y) - { - _dir.Y *= -1; - _pos.Y = _maxPos.Y - 1; - _vel.Y = 2.8f; + if (_pos.Y > _maxPos.Y) + { + _dir.Y *= -1; + _pos.Y = _maxPos.Y - 1; + _vel.Y = 2.8f; - _bounce1.Play(); - } + _bounce1.Play(); } + } - protected override void Draw(RenderContext context) - { - var scale = new Vector2(4f); - var basePosition = new Vector2(72, 47); - var shadowOffset = new Vector2(16, 4); - var sphereTilt = 25f; + protected override void Draw(RenderContext context) + { + var scale = new Vector2(4f); + var basePosition = new Vector2(72, 47); + var shadowOffset = new Vector2(16, 4); + var sphereTilt = 25f; - context.RenderTo(_target, (ctx, _) => - { - ctx.Clear(127, 127, 127); - - DrawGrid(new(40, 16), ctx); - - _effect.Activate(); - _effect.SetUniform("mode", (int)EffectMode.Shadow); - _texture.ColorMask = new(0, 0, 0, 127); - ctx.DrawTexture( - _texture, - basePosition + shadowOffset + _pos, - scale, - _texture.AbsoluteCenter, 25f - ); + context.RenderTo(_target, (ctx, _) => + { + ctx.Clear(127, 127, 127); + + DrawGrid(new(40, 16), ctx); + + _effect.Activate(); + _effect.SetUniform("mode", (int)EffectMode.Shadow); + _texture.ColorMask = new(0, 0, 0, 127); + ctx.DrawTexture( + _texture, + basePosition + shadowOffset + _pos, + scale, + _texture.AbsoluteCenter, 25f + ); - _effect.SetUniform("mode", (int)EffectMode.Sphere); - _effect.SetUniform("texshift", _texshift); - ctx.DrawTexture( - _texture, - basePosition + _pos, - scale, - _texture.AbsoluteCenter, - sphereTilt - ); - Shader.Deactivate(); + _effect.SetUniform("mode", (int)EffectMode.Sphere); + _effect.SetUniform("texshift", _texshift); + ctx.DrawTexture( + _texture, + basePosition + _pos, + scale, + _texture.AbsoluteCenter, + sphereTilt + ); + Shader.Deactivate(); - _effect.Activate(); - _effect.SetUniform("mode", (int)EffectMode.Shade); - ctx.DrawTexture( - _shade, - basePosition + _pos, - scale, - _shade.AbsoluteCenter, - sphereTilt - ); - Shader.Deactivate(); - }); + _effect.Activate(); + _effect.SetUniform("mode", (int)EffectMode.Shade); + ctx.DrawTexture( + _shade, + basePosition + _pos, + scale, + _shade.AbsoluteCenter, + sphereTilt + ); + Shader.Deactivate(); + }); - context.DrawTexture(_target, Vector2.Zero); - } + context.DrawTexture(_target, Vector2.Zero); + } - private void DrawGrid(Vector2 origin, RenderContext context) + private void DrawGrid(Vector2 origin, RenderContext context) + { + for (var i = 0; i < 16; i++) { - for (var i = 0; i < 16; i++) + context.Line( + origin.X + 16 * i, + origin.Y, + origin.X + 16 * i, + origin.Y + 160, + new(170, 0, 170) + ); + + if (i < 11) { context.Line( - origin.X + 16 * i, - origin.Y, - origin.X + 16 * i, - origin.Y + 160, + origin.X - 0.5f, + origin.Y + 16 * i, + origin.X + 240, + origin.Y + 16 * i, new(170, 0, 170) ); - - if (i < 11) - { - context.Line( - origin.X - 0.5f, - origin.Y + 16 * i, - origin.X + 240, - origin.Y + 16 * i, - new(170, 0, 170) - ); - } } } } diff --git a/Chroma.Examples/BoingBall/Program.cs b/Chroma.Examples/BoingBall/Program.cs index 58f87d41..b2536c3b 100644 --- a/Chroma.Examples/BoingBall/Program.cs +++ b/Chroma.Examples/BoingBall/Program.cs @@ -1,3 +1,4 @@ using BoingBall; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/CallbackHooks/GameCore.cs b/Chroma.Examples/CallbackHooks/GameCore.cs index 6397cb9f..bfdd77a6 100644 --- a/Chroma.Examples/CallbackHooks/GameCore.cs +++ b/Chroma.Examples/CallbackHooks/GameCore.cs @@ -1,72 +1,71 @@ +namespace CallbackHooks; + using System.Numerics; using Chroma; using Chroma.Extensibility; using Chroma.Graphics; using Chroma.Input; -namespace CallbackHooks +public class GameCore : Game { - public class GameCore : Game + private int _interceptionCount; + private int _nonInterceptedKeypressCount; + private int _f4pressCount; + + public GameCore() + : base(new(false, false)) { - private int _interceptionCount; - private int _nonInterceptedKeypressCount; - private int _f4pressCount; + HookRegistry.AttachAll(); + } - public GameCore() - : base(new(false, false)) - { - HookRegistry.AttachAll(); - } + protected override void Draw(RenderContext context) + { + context.DrawString( + $"F1 interception(s): {_interceptionCount}\n" + + $"Non-intercepted key events: {_nonInterceptedKeypressCount}\n" + + $"F4 (or is it? ^^) press count: {_f4pressCount}\n", + new Vector2(8, 8) + ); + } - protected override void Draw(RenderContext context) + protected override void Update(float delta) + { + } + + protected override void KeyPressed(KeyEventArgs e) + { + _nonInterceptedKeypressCount++; + + if (e.KeyCode == KeyCode.F2) { - context.DrawString( - $"F1 interception(s): {_interceptionCount}\n" + - $"Non-intercepted key events: {_nonInterceptedKeypressCount}\n" + - $"F4 (or is it? ^^) press count: {_f4pressCount}\n", - new Vector2(8, 8) - ); + HookRegistry.Detach(HookPoint.KeyPressed, HookAttachment.Prefix, BeforeKeyPressed); } - - protected override void Update(float delta) + else if (e.KeyCode == KeyCode.F3) { + HookRegistry.Attach(HookPoint.KeyPressed, HookAttachment.Prefix, BeforeKeyPressed); } - - protected override void KeyPressed(KeyEventArgs e) + else if (e.KeyCode == KeyCode.F4) { - _nonInterceptedKeypressCount++; - - if (e.KeyCode == KeyCode.F2) - { - HookRegistry.Detach(HookPoint.KeyPressed, HookAttachment.Prefix, BeforeKeyPressed); - } - else if (e.KeyCode == KeyCode.F3) - { - HookRegistry.Attach(HookPoint.KeyPressed, HookAttachment.Prefix, BeforeKeyPressed); - } - else if (e.KeyCode == KeyCode.F4) - { - _f4pressCount++; - } + _f4pressCount++; } + } - // Signature of a hook must match (Game game, T e) where T is the hooked callback's argument type. - // Optionally some parameters may be mutated by providing `ref` parameter modifier. - [Hook(HookPoint.KeyPressed, HookAttachment.Prefix)] - private static bool BeforeKeyPressed(Game game, ref KeyEventArgs e) - { - var gameInstance = (game as GameCore)!; + // Signature of a hook must match (Game game, T e) where T is the hooked callback's argument type. + // Optionally some parameters may be mutated by providing `ref` parameter modifier. + [Hook(HookPoint.KeyPressed, HookAttachment.Prefix)] + private static bool BeforeKeyPressed(Game game, ref KeyEventArgs e) + { + var gameInstance = (game as GameCore)!; - if (e.KeyCode == KeyCode.F1) - { - e = e.WithScanCode(ScanCode.F4) - .WithKeyCode(KeyCode.F4); + if (e.KeyCode == KeyCode.F1) + { + e = e.WithScanCode(ScanCode.F4) + .WithKeyCode(KeyCode.F4); - gameInstance._interceptionCount++; - return true; - } - + gameInstance._interceptionCount++; return true; } + + return true; } } \ No newline at end of file diff --git a/Chroma.Examples/CallbackHooks/Program.cs b/Chroma.Examples/CallbackHooks/Program.cs index d7b87484..09427bb4 100644 --- a/Chroma.Examples/CallbackHooks/Program.cs +++ b/Chroma.Examples/CallbackHooks/Program.cs @@ -1,3 +1,4 @@ using CallbackHooks; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/Cameras/GameCore.cs b/Chroma.Examples/Cameras/GameCore.cs index 877ad2d4..37bc4759 100644 --- a/Chroma.Examples/Cameras/GameCore.cs +++ b/Chroma.Examples/Cameras/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace Cameras; + +using System; using System.IO; using System.Numerics; using Chroma; @@ -8,141 +10,138 @@ using Chroma.Graphics; using Chroma.Input; -namespace Cameras +public class GameCore : Game { - public class GameCore : Game + private Camera _cam; + private Vector2 _burgpos; + private Texture _grid; + private Texture _burg; + + public GameCore() : base(new(false, false)) + { + } + + protected override IContentProvider InitializeContentPipeline() { - private Camera _cam; - private Vector2 _burgpos; - private Texture _grid; - private Texture _burg; + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } - public GameCore() : base(new(false, false)) + protected override void Initialize(IContentProvider content) + { + _cam = new Camera { - } + UseCenteredOrigin = true + }; + + _grid = content.Load("Textures/grid.png"); + _burg = content.Load("Textures/burg.png"); + } - protected override IContentProvider InitializeContentPipeline() + protected override void Update(float delta) + { + Window.Title = $"{PerformanceCounter.FPS} | {PerformanceCounter.Delta}"; + + if (Keyboard.IsKeyDown(KeyCode.W)) { - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); + _cam.Y += (int)(500 * delta); } - - protected override void Initialize(IContentProvider content) + else if (Keyboard.IsKeyDown(KeyCode.S)) { - _cam = new Camera - { - UseCenteredOrigin = true - }; - - _grid = content.Load("Textures/grid.png"); - _burg = content.Load("Textures/burg.png"); + _cam.Y -= (int)(500 * delta); } - protected override void Update(float delta) + if (Keyboard.IsKeyDown(KeyCode.A)) { - Window.Title = $"{PerformanceCounter.FPS} | {PerformanceCounter.Delta}"; - - if (Keyboard.IsKeyDown(KeyCode.W)) - { - _cam.Y += (int)(500 * delta); - } - else if (Keyboard.IsKeyDown(KeyCode.S)) - { - _cam.Y -= (int)(500 * delta); - } - - if (Keyboard.IsKeyDown(KeyCode.A)) - { - _cam.X -= (int)(500 * delta); - } - else if (Keyboard.IsKeyDown(KeyCode.D)) - { - _cam.X += (int)(500 * delta); - } + _cam.X -= (int)(500 * delta); + } + else if (Keyboard.IsKeyDown(KeyCode.D)) + { + _cam.X += (int)(500 * delta); + } - if (Keyboard.IsKeyDown(KeyCode.Up)) - { - _burgpos.Y -= 200 * delta; - } - else if(Keyboard.IsKeyDown(KeyCode.Down)) - { - _burgpos.Y += 200 * delta; - } + if (Keyboard.IsKeyDown(KeyCode.Up)) + { + _burgpos.Y -= 200 * delta; + } + else if(Keyboard.IsKeyDown(KeyCode.Down)) + { + _burgpos.Y += 200 * delta; + } - if (Keyboard.IsKeyDown(KeyCode.Left)) - { - _burgpos.X -= 200 * delta; - } - else if (Keyboard.IsKeyDown(KeyCode.Right)) - { - _burgpos.X += 200 * delta; - } + if (Keyboard.IsKeyDown(KeyCode.Left)) + { + _burgpos.X -= 200 * delta; } + else if (Keyboard.IsKeyDown(KeyCode.Right)) + { + _burgpos.X += 200 * delta; + } + } - protected override void Draw(RenderContext context) + protected override void Draw(RenderContext context) + { + context.WithCamera(_cam, (ctx, cam) => { - context.WithCamera(_cam, (ctx, cam) => - { - ctx.DrawTexture( - _grid, - Vector2.Zero, - Vector2.One, - Vector2.Zero, - rotation: 0f - ); + ctx.DrawTexture( + _grid, + Vector2.Zero, + Vector2.One, + Vector2.Zero, + rotation: 0f + ); - ctx.DrawTexture( - _burg, - _burgpos, - Vector2.One, - Vector2.Zero, - 0 - ); - }); - - context.DrawString( - "Use to move camera around the screen.\n" + - "Use mouse to rotate the camera around the center.\n" + - "Use to lock the mouse cursor into the window.\n" + - "Use mouse wheel to zoom the camera in/out.", - new Vector2(8), - Color.Red + ctx.DrawTexture( + _burg, + _burgpos, + Vector2.One, + Vector2.Zero, + 0 ); - } + }); + + context.DrawString( + "Use to move camera around the screen.\n" + + "Use mouse to rotate the camera around the center.\n" + + "Use to lock the mouse cursor into the window.\n" + + "Use mouse wheel to zoom the camera in/out.", + new Vector2(8), + Color.Red + ); + } - protected override void WheelMoved(MouseWheelEventArgs e) + protected override void WheelMoved(MouseWheelEventArgs e) + { + if (_cam.ZoomX <= 0.3f || _cam.ZoomY <= 0.3f) { - if (_cam.ZoomX <= 0.3f || _cam.ZoomY <= 0.3f) - { - _cam.ZoomX = _cam.ZoomY = 0.3f; - } + _cam.ZoomX = _cam.ZoomY = 0.3f; + } - if (e.Motion.Y > 0) - { - _cam.ZoomX *= 2; - _cam.ZoomY *= 2; - } - else - { - _cam.ZoomX *= 0.5f; - _cam.ZoomY *= 0.5f; - } + if (e.Motion.Y > 0) + { + _cam.ZoomX *= 2; + _cam.ZoomY *= 2; } - - protected override void MouseMoved(MouseMoveEventArgs e) + else { - _cam.Rotation += e.Delta.X / 8; - _cam.Rotation %= 360; + _cam.ZoomX *= 0.5f; + _cam.ZoomY *= 0.5f; } + } - protected override void KeyPressed(KeyEventArgs e) + protected override void MouseMoved(MouseMoveEventArgs e) + { + _cam.Rotation += e.Delta.X / 8; + _cam.Rotation %= 360; + } + + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.F1) { - if (e.KeyCode == KeyCode.F1) - { - Mouse.IsCaptured = !Mouse.IsCaptured; - Mouse.IsRelativeModeEnabled = !Mouse.IsRelativeModeEnabled; - } + Mouse.IsCaptured = !Mouse.IsCaptured; + Mouse.IsRelativeModeEnabled = !Mouse.IsRelativeModeEnabled; } } } \ No newline at end of file diff --git a/Chroma.Examples/Cameras/Program.cs b/Chroma.Examples/Cameras/Program.cs index 4d5c8feb..93e9770c 100644 --- a/Chroma.Examples/Cameras/Program.cs +++ b/Chroma.Examples/Cameras/Program.cs @@ -1,3 +1,4 @@ using Cameras; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/CellularAutomaton/Cell.cs b/Chroma.Examples/CellularAutomaton/Cell.cs index 3a746276..26a01047 100644 --- a/Chroma.Examples/CellularAutomaton/Cell.cs +++ b/Chroma.Examples/CellularAutomaton/Cell.cs @@ -1,32 +1,31 @@ +namespace CellularAutomaton; + using Chroma.Graphics; -namespace CellularAutomaton +public class Cell { - public class Cell - { - protected Map Map { get; } + protected Map Map { get; } - public int X { get; } - public int Y { get; } + public int X { get; } + public int Y { get; } - public Color Color { get; set; } = Color.CornflowerBlue; + public Color Color { get; set; } = Color.CornflowerBlue; - public Cell(Map map, int x, int y) - { - Map = map; + public Cell(Map map, int x, int y) + { + Map = map; - X = x; - Y = y; - } + X = x; + Y = y; + } - public void Draw(RenderContext context) - { - // +2 because opengl rasterization. - context.Pixel(X + 2, Y + 2, Color); - } + public void Draw(RenderContext context) + { + // +2 because opengl rasterization. + context.Pixel(X + 2, Y + 2, Color); + } - public virtual void Update(float delta) - { - } + public virtual void Update(float delta) + { } } \ No newline at end of file diff --git a/Chroma.Examples/CellularAutomaton/CorruptorCell.cs b/Chroma.Examples/CellularAutomaton/CorruptorCell.cs index cdabe65e..2ca8e07b 100644 --- a/Chroma.Examples/CellularAutomaton/CorruptorCell.cs +++ b/Chroma.Examples/CellularAutomaton/CorruptorCell.cs @@ -1,52 +1,51 @@ +namespace CellularAutomaton; + using System; using Chroma.Graphics; -namespace CellularAutomaton +public class CorruptorCell : Cell { - public class CorruptorCell : Cell + private static Random _rnd = new(); + private static int _totalCorruption = 1; + private static byte _effectiveness = 9; + + public CorruptorCell(Map map, int x, int y) + : base(map, x, y) { - private static Random _rnd = new(); - private static int _totalCorruption = 1; - private static byte _effectiveness = 9; - - public CorruptorCell(Map map, int x, int y) - : base(map, x, y) - { - Color = new Color( - _totalCorruption + (byte)(255 * Math.Sinh(Map.Width / 2 - y)), - 0, - _totalCorruption + (byte)(255 * Math.Tanh(Map.Width / 2 - y)), - (byte)(_rnd.NextSingle() * 255) - ); + Color = new Color( + _totalCorruption + (byte)(255 * Math.Sinh(Map.Width / 2 - y)), + 0, + _totalCorruption + (byte)(255 * Math.Tanh(Map.Width / 2 - y)), + (byte)(_rnd.NextSingle() * 255) + ); - } + } - public override void Update(float delta) - { - var (n, w, s, e) = ( - Map.GetNeighbor(this, Map.Direction.North), - Map.GetNeighbor(this, Map.Direction.West), - Map.GetNeighbor(this, Map.Direction.South), - Map.GetNeighbor(this, Map.Direction.East) - ); + public override void Update(float delta) + { + var (n, w, s, e) = ( + Map.GetNeighbor(this, Map.Direction.North), + Map.GetNeighbor(this, Map.Direction.West), + Map.GetNeighbor(this, Map.Direction.South), + Map.GetNeighbor(this, Map.Direction.East) + ); - if (n != null && n is FaderCell && n.Color.A > 255 - _effectiveness) - Grow(n.X, n.Y); + if (n != null && n is FaderCell && n.Color.A > 255 - _effectiveness) + Grow(n.X, n.Y); - if (w != null && w is FaderCell && w.Color.A > 255 - _effectiveness) - Grow(w.X, w.Y); + if (w != null && w is FaderCell && w.Color.A > 255 - _effectiveness) + Grow(w.X, w.Y); - if (s != null && s is FaderCell && s.Color.A > 255 - _effectiveness) - Grow(s.X, s.Y); + if (s != null && s is FaderCell && s.Color.A > 255 - _effectiveness) + Grow(s.X, s.Y); - if (e != null && e is FaderCell && e.Color.A > 255 - _effectiveness) - Grow(e.X, e.Y); - } + if (e != null && e is FaderCell && e.Color.A > 255 - _effectiveness) + Grow(e.X, e.Y); + } - private void Grow(int x, int y) - { - Map.SpawnCell(x, y); - } + private void Grow(int x, int y) + { + Map.SpawnCell(x, y); } } \ No newline at end of file diff --git a/Chroma.Examples/CellularAutomaton/FaderCell.cs b/Chroma.Examples/CellularAutomaton/FaderCell.cs index e27ad0bc..0bbbdbac 100644 --- a/Chroma.Examples/CellularAutomaton/FaderCell.cs +++ b/Chroma.Examples/CellularAutomaton/FaderCell.cs @@ -1,45 +1,44 @@ +namespace CellularAutomaton; + using System; using Chroma.Graphics; -namespace CellularAutomaton +public class FaderCell : Cell { - public class FaderCell : Cell - { - private static Random _rnd = new(); + private static Random _rnd = new(); - private int _fadeDirection = -1; - private float _alpha; + private int _fadeDirection = -1; + private float _alpha; - public float FadeSpeed { get; private set; } + public float FadeSpeed { get; private set; } - public FaderCell(Map map, int x, int y) - : base(map, x, y) - { - _alpha = _rnd.NextSingle(); - FadeSpeed = _rnd.NextSingle() + 1.0f; - - var rgb = new byte[3]; - _rnd.NextBytes(rgb); + public FaderCell(Map map, int x, int y) + : base(map, x, y) + { + _alpha = _rnd.NextSingle(); + FadeSpeed = _rnd.NextSingle() + 1.0f; + + var rgb = new byte[3]; + _rnd.NextBytes(rgb); - Color = new Color(0, rgb[1], 0, (byte)(255 * _alpha)); - } + Color = new Color(0, rgb[1], 0, (byte)(255 * _alpha)); + } - public override void Update(float delta) - { + public override void Update(float delta) + { - if (_alpha <= 0) - _fadeDirection = 1; - else if (_alpha >= 1.0f) - _fadeDirection = -1; + if (_alpha <= 0) + _fadeDirection = 1; + else if (_alpha >= 1.0f) + _fadeDirection = -1; - _alpha += _fadeDirection * (FadeSpeed * delta); + _alpha += _fadeDirection * (FadeSpeed * delta); - if (_alpha > 1.0f) - _alpha = 1.0f; - else if (_alpha <= 0.0f) - _alpha = 0.0f; + if (_alpha > 1.0f) + _alpha = 1.0f; + else if (_alpha <= 0.0f) + _alpha = 0.0f; - Color = new Color(Color.R, Color.G, Color.B, (byte)(255 * _alpha)); - } + Color = new Color(Color.R, Color.G, Color.B, (byte)(255 * _alpha)); } } \ No newline at end of file diff --git a/Chroma.Examples/CellularAutomaton/GameCore.cs b/Chroma.Examples/CellularAutomaton/GameCore.cs index c511480e..6b10bb58 100644 --- a/Chroma.Examples/CellularAutomaton/GameCore.cs +++ b/Chroma.Examples/CellularAutomaton/GameCore.cs @@ -1,3 +1,5 @@ +namespace CellularAutomaton; + using System.Numerics; using Chroma; using Chroma.ContentManagement; @@ -5,49 +7,46 @@ using Chroma.Graphics; using Chroma.Input; -namespace CellularAutomaton +public class GameCore : Game { - public class GameCore : Game + private bool _go; + private Map _map; + + public GameCore() + : base(new(false, false)) + { + Window.Mode.SetWindowed(1280, 800, true); + } + + protected override void Initialize(IContentProvider content) + { + _map = new Map(384, 384); + _map.RenderSize = new(768, 768); + + _map.Position = Window.Center - new Vector2( + _map.RenderSize.Value.Width / 2, + _map.RenderSize.Value.Height / 2 + ); + + _map.SpawnCell(_map.Width / 2, _map.Height / 2); + } + + protected override void Draw(RenderContext context) + { + if (!_go) return; + _map.Draw(context); + } + + protected override void Update(float delta) + { + Window.Title = $"{PerformanceCounter.FPS} FPS"; + + if (!_go) return; + _map.Update(delta); + } + + protected override void KeyPressed(KeyEventArgs e) { - private bool _go; - private Map _map; - - public GameCore() - : base(new(false, false)) - { - Window.Mode.SetWindowed(1280, 800, true); - } - - protected override void Initialize(IContentProvider content) - { - _map = new Map(384, 384); - _map.RenderSize = new(768, 768); - - _map.Position = Window.Center - new Vector2( - _map.RenderSize.Value.Width / 2, - _map.RenderSize.Value.Height / 2 - ); - - _map.SpawnCell(_map.Width / 2, _map.Height / 2); - } - - protected override void Draw(RenderContext context) - { - if (!_go) return; - _map.Draw(context); - } - - protected override void Update(float delta) - { - Window.Title = $"{PerformanceCounter.FPS} FPS"; - - if (!_go) return; - _map.Update(delta); - } - - protected override void KeyPressed(KeyEventArgs e) - { - _go = true; - } + _go = true; } } \ No newline at end of file diff --git a/Chroma.Examples/CellularAutomaton/Map.cs b/Chroma.Examples/CellularAutomaton/Map.cs index 22de9bb4..472f95d3 100644 --- a/Chroma.Examples/CellularAutomaton/Map.cs +++ b/Chroma.Examples/CellularAutomaton/Map.cs @@ -1,117 +1,116 @@ +namespace CellularAutomaton; + using System; using System.Drawing; using System.Numerics; using Chroma.Graphics; using Color = Chroma.Graphics.Color; -namespace CellularAutomaton +public class Map { - public class Map + public enum Direction { - public enum Direction - { - West, - North, - East, - South - } + West, + North, + East, + South + } - private Cell[] _cells; - private RenderTarget _target; + private Cell[] _cells; + private RenderTarget _target; - public Cell this[int x, int y] + public Cell this[int x, int y] + { + get { - get - { - if (x < 0 || x >= Width) return null; - if (y < 0 || y >= Height) return null; + if (x < 0 || x >= Width) return null; + if (y < 0 || y >= Height) return null; - return _cells[y * Width + x]; - } + return _cells[y * Width + x]; + } - set - { - if (x < 0 || x >= Width) return; - if (y < 0 || y >= Height) return; + set + { + if (x < 0 || x >= Width) return; + if (y < 0 || y >= Height) return; - _cells[y * Width + x] = value; - } + _cells[y * Width + x] = value; } + } - public Vector2 Position { get; set; } + public Vector2 Position { get; set; } - public Size? RenderSize - { - get => _target.VirtualResolution; - set => _target.VirtualResolution = value; - } + public Size? RenderSize + { + get => _target.VirtualResolution; + set => _target.VirtualResolution = value; + } - public int Width { get; } - public int Height { get; } + public int Width { get; } + public int Height { get; } - public Map(int width, int height) - { - _cells = new Cell[width * height]; + public Map(int width, int height) + { + _cells = new Cell[width * height]; - for (var i = 0; i < _cells.Length; i++) - { - _cells[i] = new FaderCell( - this, - i % width, i / width - ); - } + for (var i = 0; i < _cells.Length; i++) + { + _cells[i] = new FaderCell( + this, + i % width, i / width + ); + } - Width = width; - Height = height; + Width = width; + Height = height; - _target = new RenderTarget(width + 2, height + 2) { FilteringMode = TextureFilteringMode.NearestNeighbor }; - } + _target = new RenderTarget(width + 2, height + 2) { FilteringMode = TextureFilteringMode.NearestNeighbor }; + } - public T SpawnCell(int x, int y) where T : Cell - { - var cell = (T)Activator.CreateInstance(typeof(T), new object[] { this, x, y }); - _cells[y * Width + x] = cell; + public T SpawnCell(int x, int y) where T : Cell + { + var cell = (T)Activator.CreateInstance(typeof(T), new object[] { this, x, y }); + _cells[y * Width + x] = cell; - return cell; - } + return cell; + } - public Cell GetNeighbor(Cell cell, Direction direction) + public Cell GetNeighbor(Cell cell, Direction direction) + { + var (hoff, voff) = direction switch { - var (hoff, voff) = direction switch - { - Direction.West => (-1, 0), - Direction.North => (0, -1), - Direction.East => (1, 0), - Direction.South => (0, 1), - _ => throw new ArgumentOutOfRangeException(nameof(direction)) - }; - - return this[cell.X + hoff, cell.Y + voff]; - } + Direction.West => (-1, 0), + Direction.North => (0, -1), + Direction.East => (1, 0), + Direction.South => (0, 1), + _ => throw new ArgumentOutOfRangeException(nameof(direction)) + }; + + return this[cell.X + hoff, cell.Y + voff]; + } - public void Draw(RenderContext context) + public void Draw(RenderContext context) + { + context.RenderTo(_target, (ctx, tgt) => { - context.RenderTo(_target, (ctx, tgt) => - { - ctx.Clear(Color.White); - ctx.Rectangle(ShapeMode.Fill, 1, 1, Height - 2, Width - 2, Color.Black); + ctx.Clear(Color.White); + ctx.Rectangle(ShapeMode.Fill, 1, 1, Height - 2, Width - 2, Color.Black); - for (var i = 0; i < _cells.Length; i++) + for (var i = 0; i < _cells.Length; i++) + { + if (_cells[i] != null) { - if (_cells[i] != null) - { - _cells[i]?.Draw(ctx); - } + _cells[i]?.Draw(ctx); } - }); + } + }); - context.DrawTexture(_target, Position); - } + context.DrawTexture(_target, Position); + } - public void Update(float delta) - { - for (var i = 0; i < _cells.Length; i++) - _cells[i]?.Update(delta); - } + public void Update(float delta) + { + for (var i = 0; i < _cells.Length; i++) + _cells[i]?.Update(delta); } } \ No newline at end of file diff --git a/Chroma.Examples/CellularAutomaton/Program.cs b/Chroma.Examples/CellularAutomaton/Program.cs index 3c386cc6..14c681cf 100644 --- a/Chroma.Examples/CellularAutomaton/Program.cs +++ b/Chroma.Examples/CellularAutomaton/Program.cs @@ -1,3 +1,4 @@ using CellularAutomaton; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/Clipboard/GameCore.cs b/Chroma.Examples/Clipboard/GameCore.cs index 3409d645..a2d48451 100644 --- a/Chroma.Examples/Clipboard/GameCore.cs +++ b/Chroma.Examples/Clipboard/GameCore.cs @@ -1,34 +1,33 @@ -using System; +namespace Clipboard; + +using System; using System.Globalization; using System.Numerics; using Chroma; using Chroma.Graphics; using Chroma.Input; -namespace Clipboard +public class GameCore : Game { - public class GameCore : Game + public GameCore() : base(new(false, false)) { - public GameCore() : base(new(false, false)) - { - } + } - protected override void Draw(RenderContext context) - { - context.DrawString( - "Use to set clipboard text to the current date and time.\n\n" + - $"Current clipboard text: {Chroma.Clipboard.Text}\n" + - $"Clipboard has text? {Chroma.Clipboard.HasText}", - new Vector2(8) - ); - } + protected override void Draw(RenderContext context) + { + context.DrawString( + "Use to set clipboard text to the current date and time.\n\n" + + $"Current clipboard text: {Clipboard.Text}\n" + + $"Clipboard has text? {Clipboard.HasText}", + new Vector2(8) + ); + } - protected override void KeyPressed(KeyEventArgs e) + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.F1) { - if (e.KeyCode == KeyCode.F1) - { - Chroma.Clipboard.Text = DateTime.Now.ToString(CultureInfo.InvariantCulture); - } + Clipboard.Text = DateTime.Now.ToString(CultureInfo.InvariantCulture); } } } \ No newline at end of file diff --git a/Chroma.Examples/Clipboard/Program.cs b/Chroma.Examples/Clipboard/Program.cs index bb49b7e5..48360f71 100644 --- a/Chroma.Examples/Clipboard/Program.cs +++ b/Chroma.Examples/Clipboard/Program.cs @@ -1,3 +1,4 @@ using Clipboard; -new GameCore().Run(); \ No newline at end of file +using(var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/CustomContentProvider/GameCore.cs b/Chroma.Examples/CustomContentProvider/GameCore.cs index 9e4dc36b..08c9d4c8 100644 --- a/Chroma.Examples/CustomContentProvider/GameCore.cs +++ b/Chroma.Examples/CustomContentProvider/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace CustomContentProvider; + +using System; using System.IO; using System.Numerics; using Chroma; @@ -7,55 +9,51 @@ using Chroma.Graphics; using Chroma.Input; -namespace CustomContentProvider +public class GameCore : Game { - public class GameCore : Game - { - private Sound _shotgun; - private Texture _texture; - private float _rotation; + private Sound _shotgun; + private Texture _texture; + private float _rotation; - public GameCore() : base(new(false, false)) - { - RenderSettings.DefaultTextureFilteringMode = TextureFilteringMode.NearestNeighbor; - } + public GameCore() : base(new(false, false)) + { + RenderSettings.DefaultTextureFilteringMode = TextureFilteringMode.NearestNeighbor; + } - protected override IContentProvider InitializeContentPipeline() - { - return new ZipContentProvider( - this, - Path.Combine(AppContext.BaseDirectory, "../../../../_common/assets.zip") - ); - } + protected override IContentProvider InitializeContentPipeline() + { + return new ZipContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common/assets.zip") + ); + } - protected override void Initialize(IContentProvider content) - { - _texture = content.Load("Textures/pentagram.png"); - _shotgun = content.Load("doomsg.wav"); - } + protected override void Initialize(IContentProvider content) + { + _texture = content.Load("Textures/pentagram.png"); + _shotgun = content.Load("doomsg.wav"); + } - protected override void Draw(RenderContext context) - { - context.DrawTexture( - _texture, - (Window.Center - _texture.Center), - new Vector2(8), - _texture.Center, - _rotation - ); - } + protected override void Draw(RenderContext context) + { + context.DrawTexture( + _texture, + (Window.Center - _texture.Center), + new Vector2(8), + _texture.Center, + _rotation + ); + } - protected override void Update(float delta) - { - _rotation += 15 * delta; - } + protected override void Update(float delta) + { + _rotation += 15 * delta; + } - protected override void KeyPressed(KeyEventArgs e) + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.Space) { - if (e.KeyCode == KeyCode.Space) - { - _shotgun.Play(); - } + _shotgun.Play(); } } } \ No newline at end of file diff --git a/Chroma.Examples/CustomContentProvider/Program.cs b/Chroma.Examples/CustomContentProvider/Program.cs index 40030cd7..2d654133 100644 --- a/Chroma.Examples/CustomContentProvider/Program.cs +++ b/Chroma.Examples/CustomContentProvider/Program.cs @@ -1,3 +1,4 @@ using CustomContentProvider; -new GameCore().Run(); \ No newline at end of file +using(var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/CustomContentProvider/ZipContentProvider.cs b/Chroma.Examples/CustomContentProvider/ZipContentProvider.cs index d42e3ca2..0d5eb9df 100644 --- a/Chroma.Examples/CustomContentProvider/ZipContentProvider.cs +++ b/Chroma.Examples/CustomContentProvider/ZipContentProvider.cs @@ -1,121 +1,117 @@ -using System; +namespace CustomContentProvider; + +using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; -using Chroma; using Chroma.Audio.Sources; using Chroma.ContentManagement; using Chroma.Diagnostics.Logging; using Chroma.Graphics; using Chroma.MemoryManagement; -namespace CustomContentProvider +public class ZipContentProvider : DisposableResource, IContentProvider { - public class ZipContentProvider : DisposableResource, IContentProvider - { - private Dictionary> _importers = new(); + private Dictionary> _importers = new(); - private Game _game; - private FileStream _zipFileStream; - private ZipArchive _zipArchive; + private FileStream _zipFileStream; + private ZipArchive _zipArchive; - private Log Log { get; } = LogManager.GetForCurrentAssembly(); + private Log Log { get; } = LogManager.GetForCurrentAssembly(); - public string ContentRoot { get; } + public string ContentRoot { get; } - public ZipContentProvider(Game game, string zipFile) - { - ContentRoot = zipFile; + public ZipContentProvider(string zipFile) + { + ContentRoot = zipFile; - _game = game; - _zipFileStream = new FileStream(zipFile, FileMode.Open); - _zipArchive = new ZipArchive(_zipFileStream, ZipArchiveMode.Read); + _zipFileStream = new FileStream(zipFile, FileMode.Open); + _zipArchive = new ZipArchive(_zipFileStream, ZipArchiveMode.Read); - foreach (var entry in _zipArchive.Entries) - { - if (entry.FullName.EndsWith('/')) - continue; + foreach (var entry in _zipArchive.Entries) + { + if (entry.FullName.EndsWith('/')) + continue; - Log.Info(entry.FullName); - } + Log.Info(entry.FullName); + } - _importers.Add(typeof(Texture), (path, _) => + _importers.Add(typeof(Texture), (path, _) => + { + using (var stream = Open(path)) { - using (var stream = Open(path)) + using (var ms = new MemoryStream()) { - using (var ms = new MemoryStream()) - { - stream.CopyTo(ms); - ms.Seek(0, SeekOrigin.Begin); + stream.CopyTo(ms); + ms.Seek(0, SeekOrigin.Begin); - return new Texture(ms); - } + return new Texture(ms); } - }); + } + }); - _importers.Add(typeof(Sound), (path, _) => + _importers.Add(typeof(Sound), (path, _) => + { + using (var stream = Open(path)) { - using (var stream = Open(path)) + using (var ms = new MemoryStream()) { - using (var ms = new MemoryStream()) - { - stream.CopyTo(ms); - ms.Seek(0, SeekOrigin.Begin); + stream.CopyTo(ms); + ms.Seek(0, SeekOrigin.Begin); - return new Sound(ms); - } + return new Sound(ms); } - }); - } + } + }); + } - public T Load(string relativePath, params object[] args) where T : DisposableResource - { - return _importers[typeof(T)](relativePath, args) as T; - } + public T Load(string relativePath, params object[] args) where T : DisposableResource + { + return _importers[typeof(T)](relativePath, args) as T; + } - public void Unload(T resource) where T : DisposableResource - { - throw new NotImplementedException(); - } + public void Unload(T resource) where T : DisposableResource + { + throw new NotImplementedException(); + } - public void Track(T resource) where T : DisposableResource - { - throw new NotImplementedException(); - } + public void Track(T resource) where T : DisposableResource + { + throw new NotImplementedException(); + } - public void StopTracking(T resource) where T : DisposableResource - { - throw new NotImplementedException(); - } + public void StopTracking(T resource) where T : DisposableResource + { + throw new NotImplementedException(); + } - public byte[] Read(string relativePath) + public byte[] Read(string relativePath) + { + using (var stream = _zipArchive.GetEntry(relativePath)?.Open()) { - using (var stream = _zipArchive.GetEntry(relativePath)?.Open()) + using (var ms = new MemoryStream()) { - using (var ms = new MemoryStream()) - { - stream?.CopyTo(ms); - return ms.ToArray(); - } + stream?.CopyTo(ms); + return ms.ToArray(); } } + } - public Stream Open(string relativePath) - => _zipArchive.GetEntry(relativePath)?.Open(); + public Stream Open(string relativePath) + => _zipArchive.GetEntry(relativePath)?.Open(); - public void RegisterImporter(Func importer) where T : DisposableResource - { - throw new NotImplementedException(); - } + public void RegisterImporter(Func importer) where T : DisposableResource + { + throw new NotImplementedException(); + } - public void UnregisterImporter() where T : DisposableResource - { - throw new NotImplementedException(); - } + public void UnregisterImporter() where T : DisposableResource + { + throw new NotImplementedException(); + } - public bool IsImporterPresent() where T : DisposableResource - { - throw new NotImplementedException(); - } + public bool IsImporterPresent() where T : DisposableResource + { + throw new NotImplementedException(); } } \ No newline at end of file diff --git a/Chroma.Examples/CustomHardwareCursor/GameCore.cs b/Chroma.Examples/CustomHardwareCursor/GameCore.cs index 66e51836..8f8d73a7 100644 --- a/Chroma.Examples/CustomHardwareCursor/GameCore.cs +++ b/Chroma.Examples/CustomHardwareCursor/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace CustomHardwareCursor; + +using System; using System.IO; using System.Numerics; using Chroma; @@ -7,59 +9,56 @@ using Chroma.Graphics; using Chroma.Input; -namespace CustomHardwareCursor +public class GameCore : Game { - public class GameCore : Game + private Cursor _cursor; + + public GameCore() : base(new(false, false)) { - private Cursor _cursor; + } - public GameCore() : base(new(false, false)) - { - } + protected override IContentProvider InitializeContentPipeline() + { + // in normal use cases this is completely unnecessary + // but there is more than one example project + // so sharing between them is necessary to keep the + // source tree clean + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } - protected override IContentProvider InitializeContentPipeline() - { - // in normal use cases this is completely unnecessary - // but there is more than one example project - // so sharing between them is necessary to keep the - // source tree clean - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); - } + protected override void Initialize(IContentProvider content) + { + _cursor = content.Load("Cursors/cursor.png"); + } + + protected override void Draw(RenderContext context) + { + context.DrawString( + "Press to toggle between default and custom cursor.\n" + + "Press to toggle the cursor's visibility.\n" + + $"Press to confine the cursor to the current window (captured? {Mouse.IsCaptured}).\n" + + $"Mouse screen-space position: {Mouse.ScreenSpacePosition}\n" + + $"Mouse window-space position: {Mouse.WindowSpacePosition}\n", + new Vector2(8, 8) + ); + } - protected override void Initialize(IContentProvider content) + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.F1) { - _cursor = content.Load("Cursors/cursor.png"); + if (!_cursor.IsCurrent) _cursor.SetCurrent(); + else Cursor.Reset(); } - - protected override void Draw(RenderContext context) + else if (e.KeyCode == KeyCode.F2) { - context.DrawString( - "Press to toggle between default and custom cursor.\n" + - "Press to toggle the cursor's visibility.\n" + - $"Press to confine the cursor to the current window (captured? {Mouse.IsCaptured}).\n" + - $"Mouse screen-space position: {Mouse.ScreenSpacePosition}\n" + - $"Mouse window-space position: {Mouse.WindowSpacePosition}\n", - new Vector2(8, 8) - ); + Cursor.IsVisible = !Cursor.IsVisible; } - - protected override void KeyPressed(KeyEventArgs e) + else if (e.KeyCode == KeyCode.F3) { - if (e.KeyCode == KeyCode.F1) - { - if (!_cursor.IsCurrent) _cursor.SetCurrent(); - else Cursor.Reset(); - } - else if (e.KeyCode == KeyCode.F2) - { - Cursor.IsVisible = !Cursor.IsVisible; - } - else if (e.KeyCode == KeyCode.F3) - { - Mouse.IsCaptured = !Mouse.IsCaptured; - } + Mouse.IsCaptured = !Mouse.IsCaptured; } } } \ No newline at end of file diff --git a/Chroma.Examples/CustomHardwareCursor/Program.cs b/Chroma.Examples/CustomHardwareCursor/Program.cs index dae9ea84..6030f2eb 100644 --- a/Chroma.Examples/CustomHardwareCursor/Program.cs +++ b/Chroma.Examples/CustomHardwareCursor/Program.cs @@ -1,3 +1,4 @@ using CustomHardwareCursor; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/DrawBatching/GameCore.cs b/Chroma.Examples/DrawBatching/GameCore.cs index 452a36e5..042f23d8 100644 --- a/Chroma.Examples/DrawBatching/GameCore.cs +++ b/Chroma.Examples/DrawBatching/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace DrawBatching; + +using System; using System.Drawing; using System.IO; using System.Numerics; @@ -9,63 +11,60 @@ using Chroma.Graphics.Batching; using Chroma.Input; -namespace DrawBatching +public class GameCore : Game { - public class GameCore : Game - { - private Texture _texA; - private Texture _texB; - private Texture _texC; + private Texture _texA; + private Texture _texB; + private Texture _texC; - private DrawOrder _order; + private DrawOrder _order; - public GameCore() : base(new(false, false)) - { - } + public GameCore() : base(new(false, false)) + { + } - protected override IContentProvider InitializeContentPipeline() - { - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); - } + protected override IContentProvider InitializeContentPipeline() + { + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } - protected override void Initialize(IContentProvider content) - { - _texA = content.Load("Textures/burg.png"); + protected override void Initialize(IContentProvider content) + { + _texA = content.Load("Textures/burg.png"); - _texB = content.Load("Textures/pentagram.png"); - _texB.VirtualResolution = new Size(256, 256); - _texB.FilteringMode = TextureFilteringMode.NearestNeighbor; + _texB = content.Load("Textures/pentagram.png"); + _texB.VirtualResolution = new Size(256, 256); + _texB.FilteringMode = TextureFilteringMode.NearestNeighbor; - _texC = content.Load("Textures/walls.jpeg"); - } + _texC = content.Load("Textures/walls.jpeg"); + } - protected override void Draw(RenderContext context) - { - context.Batch((ctx) => ctx.DrawTexture(_texA, new Vector2(48, 48), Vector2.One, Vector2.Zero, 0f), 0); - context.Batch((ctx) => ctx.DrawTexture(_texC, new Vector2(72, 72), Vector2.One, Vector2.Zero, 0f), 1); - context.Batch((ctx) => ctx.DrawTexture(_texB, new Vector2(96, 96), Vector2.One, Vector2.Zero, 0f), 2); + protected override void Draw(RenderContext context) + { + context.Batch((ctx) => ctx.DrawTexture(_texA, new Vector2(48, 48), Vector2.One, Vector2.Zero, 0f), 0); + context.Batch((ctx) => ctx.DrawTexture(_texC, new Vector2(72, 72), Vector2.One, Vector2.Zero, 0f), 1); + context.Batch((ctx) => ctx.DrawTexture(_texB, new Vector2(96, 96), Vector2.One, Vector2.Zero, 0f), 2); - context.DrawBatch(_order); + context.DrawBatch(_order); - context.DrawString( - "Use to change the order the batch in back-to-front fashion.\n" + - "Use to change the order the batch in front-to-back fashion.", - new Vector2(8) - ); - } + context.DrawString( + "Use to change the order the batch in back-to-front fashion.\n" + + "Use to change the order the batch in front-to-back fashion.", + new Vector2(8) + ); + } - protected override void KeyPressed(KeyEventArgs e) + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.F1) + { + _order = DrawOrder.BackToFront; + } + else if(e.KeyCode == KeyCode.F2) { - if (e.KeyCode == KeyCode.F1) - { - _order = DrawOrder.BackToFront; - } - else if(e.KeyCode == KeyCode.F2) - { - _order = DrawOrder.FrontToBack; - } + _order = DrawOrder.FrontToBack; } } } \ No newline at end of file diff --git a/Chroma.Examples/DrawBatching/Program.cs b/Chroma.Examples/DrawBatching/Program.cs index 1a1e7052..be646f26 100644 --- a/Chroma.Examples/DrawBatching/Program.cs +++ b/Chroma.Examples/DrawBatching/Program.cs @@ -1,3 +1,4 @@ using DrawBatching; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/EmptyProject/GameCore.cs b/Chroma.Examples/EmptyProject/GameCore.cs index a9f97bdd..50e8fc24 100644 --- a/Chroma.Examples/EmptyProject/GameCore.cs +++ b/Chroma.Examples/EmptyProject/GameCore.cs @@ -1,15 +1,14 @@ +namespace EmptyProject; + using Chroma; using Chroma.Diagnostics.Logging; -namespace EmptyProject +internal class GameCore : Game { - internal class GameCore : Game - { - private Log Log { get; } = LogManager.GetForCurrentAssembly(); + private Log Log { get; } = LogManager.GetForCurrentAssembly(); - internal GameCore() - { - Log.Info("Hello, world!"); - } + internal GameCore() + { + Log.Info("Hello, world!"); } } \ No newline at end of file diff --git a/Chroma.Examples/EmptyProject/Program.cs b/Chroma.Examples/EmptyProject/Program.cs index 994dcc83..53b92400 100644 --- a/Chroma.Examples/EmptyProject/Program.cs +++ b/Chroma.Examples/EmptyProject/Program.cs @@ -1,3 +1,4 @@ using EmptyProject; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/FixedTimeStep/GameCore.cs b/Chroma.Examples/FixedTimeStep/GameCore.cs index be961934..5513b1af 100644 --- a/Chroma.Examples/FixedTimeStep/GameCore.cs +++ b/Chroma.Examples/FixedTimeStep/GameCore.cs @@ -1,86 +1,85 @@ -using System; +namespace FixedTimeStep; + +using System; using System.Numerics; using Chroma; using Chroma.Graphics; using Chroma.Input; -namespace FixedTimeStep +public class GameCore : Game { - public class GameCore : Game + private Action _currentLagInducer; + + public GameCore() : base(new(false, false)) { - private Action _currentLagInducer; + } - public GameCore() : base(new(false, false)) + protected override void Update(float delta) + { + _currentLagInducer?.Invoke(); + Console.WriteLine($"Update: {delta}"); + } + + protected override void FixedUpdate(float delta) + { + Console.WriteLine($"FixedUpdate: {delta}"); + } + + protected override void Draw(RenderContext context) + { + Console.WriteLine("Draw"); + + context.DrawString( + "Press to switch to mega lag inducer.\n"+ + "Press to switch to small lag inducer.\n"+ + "Press to disable lag inducing.\n" + + "Press to change fixed time step target to 30 FPS.\n" + + "Press to reset fixed time step back to 75 FPS.\n\n"+ + $"Current fixed time step target: {FixedTimeStepTarget} FPS.\n" + + "Check console for change in behavior.", + new Vector2(16) + ); + } + + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.F1) { + _currentLagInducer = MegaLagInducer; } - - protected override void Update(float delta) + else if(e.KeyCode == KeyCode.F2) { - _currentLagInducer?.Invoke(); - Console.WriteLine($"Update: {delta}"); + _currentLagInducer = SmallLagInducer; } - - protected override void FixedUpdate(float delta) + else if (e.KeyCode == KeyCode.F3) { - Console.WriteLine($"FixedUpdate: {delta}"); + _currentLagInducer = null; } - - protected override void Draw(RenderContext context) + else if (e.KeyCode == KeyCode.F4) { - Console.WriteLine("Draw"); - - context.DrawString( - "Press to switch to mega lag inducer.\n"+ - "Press to switch to small lag inducer.\n"+ - "Press to disable lag inducing.\n" + - "Press to change fixed time step target to 30 FPS.\n" + - "Press to reset fixed time step back to 75 FPS.\n\n"+ - $"Current fixed time step target: {FixedTimeStepTarget} FPS.\n" + - "Check console for change in behavior.", - new Vector2(16) - ); + FixedTimeStepTarget = 30; } - - protected override void KeyPressed(KeyEventArgs e) + else if (e.KeyCode == KeyCode.F5) { - if (e.KeyCode == KeyCode.F1) - { - _currentLagInducer = MegaLagInducer; - } - else if(e.KeyCode == KeyCode.F2) - { - _currentLagInducer = SmallLagInducer; - } - else if (e.KeyCode == KeyCode.F3) - { - _currentLagInducer = null; - } - else if (e.KeyCode == KeyCode.F4) - { - FixedTimeStepTarget = 30; - } - else if (e.KeyCode == KeyCode.F5) - { - FixedTimeStepTarget = 75; - } + FixedTimeStepTarget = 75; } + } - private void MegaLagInducer() + private void MegaLagInducer() + { + int x = 0; + for (var i = 0; i < 1000000000; i++) { - int x = 0; - for (var i = 0; i < 1000000000; i++) - { - x++; - } + x++; } + } - private void SmallLagInducer() + private void SmallLagInducer() + { + int x = 0; + for (var i = 0; i < 1000000; i++) { - int x = 0; - for (var i = 0; i < 1000000; i++) - { - x++; - } + x++; } } } \ No newline at end of file diff --git a/Chroma.Examples/FixedTimeStep/Program.cs b/Chroma.Examples/FixedTimeStep/Program.cs index 240b7bd7..e32dc2b4 100644 --- a/Chroma.Examples/FixedTimeStep/Program.cs +++ b/Chroma.Examples/FixedTimeStep/Program.cs @@ -1,3 +1,4 @@ using FixedTimeStep; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/Fonts/GameCore.cs b/Chroma.Examples/Fonts/GameCore.cs index ecb67dfa..23c80c3c 100644 --- a/Chroma.Examples/Fonts/GameCore.cs +++ b/Chroma.Examples/Fonts/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace Fonts; + +using System; using System.Diagnostics; using System.IO; using System.Numerics; @@ -10,143 +12,140 @@ using Chroma.Graphics.TextRendering.TrueType; using Chroma.Input; -namespace Fonts +public class GameCore : Game { - public class GameCore : Game - { - private TrueTypeFont _republika; - private TrueTypeFont _alienlines; - private TrueTypeFont _renegade; - private TrueTypeFont _plasticBag; - private TrueTypeFont _copam8x8; + private TrueTypeFont _republika; + private TrueTypeFont _alienlines; + private TrueTypeFont _renegade; + private TrueTypeFont _plasticBag; + private TrueTypeFont _copam8x8; - private BitmapFont _plasticBagBmf; + private BitmapFont _plasticBagBmf; - public GameCore() : base(new(false, false)) - { - Graphics.VerticalSyncMode = VerticalSyncMode.None; - Cursor.IsVisible = false; - } + public GameCore() : base(new(false, false)) + { + Graphics.VerticalSyncMode = VerticalSyncMode.None; + Cursor.IsVisible = false; + } - protected override IContentProvider InitializeContentPipeline() - { - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); - } + protected override IContentProvider InitializeContentPipeline() + { + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } - protected override void Initialize(IContentProvider content) - { - _republika = content.Load("Fonts/republika.ttf", 32); - _republika.PreferAutoHinter = false; + protected override void Initialize(IContentProvider content) + { + _republika = content.Load("Fonts/republika.ttf", 32); + _republika.PreferAutoHinter = false; - _alienlines = content.Load("Fonts/alienlines.ttf", 24); - _renegade = content.Load("Fonts/renegade.otf", 48); - _plasticBag = content.Load("Fonts/plasticbag.ttf", 16); - _copam8x8 = content.Load("Fonts/Copam_8x8.ttf", 16); - _plasticBagBmf = content.Load("BitmapFonts/plasticbag.fnt"); - } + _alienlines = content.Load("Fonts/alienlines.ttf", 24); + _renegade = content.Load("Fonts/renegade.otf", 48); + _plasticBag = content.Load("Fonts/plasticbag.ttf", 16); + _copam8x8 = content.Load("Fonts/Copam_8x8.ttf", 16); + _plasticBagBmf = content.Load("BitmapFonts/plasticbag.fnt"); + } - protected override void Update(float delta) - { - Window.Title = $"Mem [MGD: {(GC.GetTotalMemory(true) / 1024f / 1024f).ToString("F3")}MB]" + - $" | [ALL: {(Process.GetCurrentProcess().PrivateMemorySize64 / 1024f / 1024f).ToString("F3")}MB]"; - } + protected override void Update(float delta) + { + Window.Title = $"Mem [MGD: {(GC.GetTotalMemory(true) / 1024f / 1024f).ToString("F3")}MB]" + + $" | [ALL: {(Process.GetCurrentProcess().PrivateMemorySize64 / 1024f / 1024f).ToString("F3")}MB]"; + } - protected override void Draw(RenderContext context) - { - context.DrawString( - _republika, - "This is a test of 32px high Republika TTF.\n" + - "And here's its line break.", - new Vector2(8), - Color.Red - ); + protected override void Draw(RenderContext context) + { + context.DrawString( + _republika, + "This is a test of 32px high Republika TTF.\n" + + "And here's its line break.", + new Vector2(8), + Color.Red + ); - var alienlinesStr = "This is a test of 24px high Alien Lines TTF.\n" + - "And here's its line break.1234567890!@#$%^&*()_+_-=[];'\\"; - context.DrawString( - _alienlines, - alienlinesStr, - new Vector2(8, 96), - Color.Aqua - ); + var alienlinesStr = "This is a test of 24px high Alien Lines TTF.\n" + + "And here's its line break.1234567890!@#$%^&*()_+_-=[];'\\"; + context.DrawString( + _alienlines, + alienlinesStr, + new Vector2(8, 96), + Color.Aqua + ); - var measure1 = _alienlines.Measure(alienlinesStr); - context.Rectangle( - ShapeMode.Stroke, - new Vector2(8, 96), - measure1.Width, - measure1.Height, - Color.Red); + var measure1 = _alienlines.Measure(alienlinesStr); + context.Rectangle( + ShapeMode.Stroke, + new Vector2(8, 96), + measure1.Width, + measure1.Height, + Color.Red); - var plasticBagBmfStr = "This is a test of 16px high Plastic Bag Bitmap Font.\n" + - "And here's its line break.\n1234567890-=!@#$aA"; - context.DrawString( - _plasticBagBmf, - plasticBagBmfStr, - new Vector2(8, 152), - Color.Lime - ); + var plasticBagBmfStr = "This is a test of 16px high Plastic Bag Bitmap Font.\n" + + "And here's its line break.\n1234567890-=!@#$aA"; + context.DrawString( + _plasticBagBmf, + plasticBagBmfStr, + new Vector2(8, 152), + Color.Lime + ); - var measure2 = _plasticBagBmf.Measure(plasticBagBmfStr); - context.Rectangle( - ShapeMode.Stroke, - new Vector2(8, 152), - measure2.Width, - measure2.Height, - Color.Red - ); + var measure2 = _plasticBagBmf.Measure(plasticBagBmfStr); + context.Rectangle( + ShapeMode.Stroke, + new Vector2(8, 152), + measure2.Width, + measure2.Height, + Color.Red + ); - var plasticBagTtfStr = "This is a test of 16px high Plastic Bag TTF.\n" + - "And here's its line break. 1234567890-=!@#$aA"; - context.DrawString( - _plasticBag, - plasticBagTtfStr, - new Vector2(16 + measure2.Width, 152), - Color.Violet - ); + var plasticBagTtfStr = "This is a test of 16px high Plastic Bag TTF.\n" + + "And here's its line break. 1234567890-=!@#$aA"; + context.DrawString( + _plasticBag, + plasticBagTtfStr, + new Vector2(16 + measure2.Width, 152), + Color.Violet + ); - var measure3 = _plasticBag.Measure(plasticBagTtfStr); - context.Rectangle( - ShapeMode.Stroke, - new Vector2(16 + measure2.Width, 152), - measure3.Width, - measure3.Height, - Color.Red - ); + var measure3 = _plasticBag.Measure(plasticBagTtfStr); + context.Rectangle( + ShapeMode.Stroke, + new Vector2(16 + measure2.Width, 152), + measure3.Width, + measure3.Height, + Color.Red + ); - context.DrawString( - _renegade, - "This is a test of 48px high\n" + - "Renegade OTF.", - new Vector2(8, 204), - Color.HotPink - ); + context.DrawString( + _renegade, + "This is a test of 48px high\n" + + "Renegade OTF.", + new Vector2(8, 204), + Color.HotPink + ); - context.DrawString( - _copam8x8, - _renegade.HintingMode.ToString() + $"\nHinting: {_renegade.HintingEnabled}\nAutoHint: {_renegade.PreferAutoHinter}", - Mouse.GetPosition() - ); - } + context.DrawString( + _copam8x8, + _renegade.HintingMode.ToString() + $"\nHinting: {_renegade.HintingEnabled}\nAutoHint: {_renegade.PreferAutoHinter}", + Mouse.GetPosition() + ); + } - protected override void KeyPressed(KeyEventArgs e) + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.Space) { - if (e.KeyCode == KeyCode.Space) - { - _renegade.HintingMode = (HintingMode)((((int)_renegade.HintingMode) + 1) % 3); - } + _renegade.HintingMode = (HintingMode)((((int)_renegade.HintingMode) + 1) % 3); + } - if (e.KeyCode == KeyCode.F1) - { - _renegade.PreferAutoHinter = !_renegade.PreferAutoHinter; - } + if (e.KeyCode == KeyCode.F1) + { + _renegade.PreferAutoHinter = !_renegade.PreferAutoHinter; + } - if (e.KeyCode == KeyCode.F2) - { - _renegade.HintingEnabled = !_renegade.HintingEnabled; - } + if (e.KeyCode == KeyCode.F2) + { + _renegade.HintingEnabled = !_renegade.HintingEnabled; } } } \ No newline at end of file diff --git a/Chroma.Examples/Fonts/Program.cs b/Chroma.Examples/Fonts/Program.cs index fa359fa6..6b96bb0b 100644 --- a/Chroma.Examples/Fonts/Program.cs +++ b/Chroma.Examples/Fonts/Program.cs @@ -1,3 +1,4 @@ using Fonts; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/GameController/GameCore.cs b/Chroma.Examples/GameController/GameCore.cs index bc138a43..bc167bb2 100644 --- a/Chroma.Examples/GameController/GameCore.cs +++ b/Chroma.Examples/GameController/GameCore.cs @@ -1,97 +1,96 @@ -using System.Collections.Generic; +namespace GameController; + +using System.Collections.Generic; using Chroma; using Chroma.Diagnostics; using Chroma.Graphics; using Chroma.Input.GameControllers; using GameController.Views; -namespace GameController +public class GameCore : Game { - public class GameCore : Game - { - private List _views; + private List _views; - public GameCore() - : base(new(false, false)) - { - Graphics.LimitFramerate = true; - Graphics.VerticalSyncMode = VerticalSyncMode.None; + public GameCore() + : base(new(false, false)) + { + Graphics.LimitFramerate = true; + Graphics.VerticalSyncMode = VerticalSyncMode.None; - Window.Mode.SetWindowed(1024, 600, true); - RenderSettings.AutoClearColor = Color.DimGray; + Window.Mode.SetWindowed(1024, 600, true); + RenderSettings.AutoClearColor = Color.DimGray; - _views = new List - { - new GenericControllerView(Window), - new DualShockControllerView(Window), - new DualSenseControllerView(Window), - new NintendoControllerView(Window) - }; + _views = new List + { + new GenericControllerView(Window), + new DualShockControllerView(Window), + new DualSenseControllerView(Window), + new NintendoControllerView(Window) + }; - // Enabled to simplify label rendering. - RenderSettings.ShapeBlendingEnabled = true; - } + // Enabled to simplify label rendering. + RenderSettings.ShapeBlendingEnabled = true; + } - protected override void ControllerDisconnected(ControllerEventArgs e) + protected override void ControllerDisconnected(ControllerEventArgs e) + { + for (var i = 0; i < _views.Count; i++) { - for (var i = 0; i < _views.Count; i++) - { - if (_views[i].AcceptedControllers.Contains(e.Controller.Info.Type)) - _views[i].OnDisconnected(e); - } + if (_views[i].AcceptedControllers.Contains(e.Controller.Info.Type)) + _views[i].OnDisconnected(e); } + } - protected override void ControllerConnected(ControllerEventArgs e) + protected override void ControllerConnected(ControllerEventArgs e) + { + for (var i = 0; i < _views.Count; i++) { - for (var i = 0; i < _views.Count; i++) - { - if (_views[i].AcceptedControllers.Contains(e.Controller.Info.Type)) - _views[i].OnConnected(e); - } + if (_views[i].AcceptedControllers.Contains(e.Controller.Info.Type)) + _views[i].OnConnected(e); } + } - protected override void ControllerAxisMoved(ControllerAxisEventArgs e) + protected override void ControllerAxisMoved(ControllerAxisEventArgs e) + { + for (var i = 0; i < _views.Count; i++) { - for (var i = 0; i < _views.Count; i++) - { - if (_views[i].AcceptedControllers.Contains(e.Controller.Info.Type)) - _views[i].OnAxisMoved(e); - } + if (_views[i].AcceptedControllers.Contains(e.Controller.Info.Type)) + _views[i].OnAxisMoved(e); } + } - protected override void ControllerButtonPressed(ControllerButtonEventArgs e) + protected override void ControllerButtonPressed(ControllerButtonEventArgs e) + { + for (var i = 0; i < _views.Count; i++) { - for (var i = 0; i < _views.Count; i++) - { - if (_views[i].AcceptedControllers.Contains(e.Controller.Info.Type)) - _views[i].OnButtonPressed(e); - } + if (_views[i].AcceptedControllers.Contains(e.Controller.Info.Type)) + _views[i].OnButtonPressed(e); } + } - protected override void ControllerButtonReleased(ControllerButtonEventArgs e) + protected override void ControllerButtonReleased(ControllerButtonEventArgs e) + { + for (var i = 0; i < _views.Count; i++) { - for (var i = 0; i < _views.Count; i++) - { - if (_views[i].AcceptedControllers.Contains(e.Controller.Info.Type)) - _views[i].OnButtonReleased(e); - } + if (_views[i].AcceptedControllers.Contains(e.Controller.Info.Type)) + _views[i].OnButtonReleased(e); } + } - protected override void Update(float delta) - { - Window.Title = $"Chroma Framework - {PerformanceCounter.FPS} FPS"; + protected override void Update(float delta) + { + Window.Title = $"Chroma Framework - {PerformanceCounter.FPS} FPS"; - for (var i = 0; i < _views.Count; i++) - _views[i].Update(delta); - } + for (var i = 0; i < _views.Count; i++) + _views[i].Update(delta); + } - protected override void Draw(RenderContext context) - { - for (var i = 0; i < _views.Count; i++) - _views[i].Draw(context); + protected override void Draw(RenderContext context) + { + for (var i = 0; i < _views.Count; i++) + _views[i].Draw(context); - context.Line(Window.Width / 2f, 0, Window.Width / 2f, Window.Height / 2f, Color.DimGray); - context.Line(0, Window.Height / 2f, Window.Width / 2f, Window.Height / 2f, Color.DimGray); - } + context.Line(Window.Width / 2f, 0, Window.Width / 2f, Window.Height / 2f, Color.DimGray); + context.Line(0, Window.Height / 2f, Window.Width / 2f, Window.Height / 2f, Color.DimGray); } } \ No newline at end of file diff --git a/Chroma.Examples/GameController/PlayerView.cs b/Chroma.Examples/GameController/PlayerView.cs index 1072de03..f4630613 100644 --- a/Chroma.Examples/GameController/PlayerView.cs +++ b/Chroma.Examples/GameController/PlayerView.cs @@ -1,25 +1,24 @@ -using Chroma.Input.GameControllers; +namespace GameController; + using System.Drawing; using System.Numerics; +using Chroma.Input.GameControllers; using Color = Chroma.Graphics.Color; -namespace GameController +public class PlayerView { - public class PlayerView - { - public RectangleF Rectangle; - public float TriggerLeft; - public float TriggerRight; - public float RightStickX; - public float RightStickY; - public Vector3 Accelerometer; - public Vector3 Gyroscope; - public ControllerTouchPoint[] TouchPoints; - public Color Color = Color.White; + public RectangleF Rectangle; + public float TriggerLeft; + public float TriggerRight; + public float RightStickX; + public float RightStickY; + public Vector3 Accelerometer; + public Vector3 Gyroscope; + public ControllerTouchPoint[] TouchPoints; + public Color Color = Color.White; - public PlayerView(float x, float y, int width, int height) - { - Rectangle = new RectangleF(x, y, width, height); - } + public PlayerView(float x, float y, int width, int height) + { + Rectangle = new RectangleF(x, y, width, height); } } \ No newline at end of file diff --git a/Chroma.Examples/GameController/Program.cs b/Chroma.Examples/GameController/Program.cs index d1187004..8343f8cd 100644 --- a/Chroma.Examples/GameController/Program.cs +++ b/Chroma.Examples/GameController/Program.cs @@ -1,3 +1,4 @@ using GameController; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/GameController/Views/DualSenseControllerView.cs b/Chroma.Examples/GameController/Views/DualSenseControllerView.cs index a468cae4..a909e43c 100644 --- a/Chroma.Examples/GameController/Views/DualSenseControllerView.cs +++ b/Chroma.Examples/GameController/Views/DualSenseControllerView.cs @@ -1,146 +1,144 @@ +namespace GameController.Views; + using System.Collections.Generic; using System.Linq; using System.Numerics; -using Chroma.Input; using Chroma.Input.GameControllers; using Chroma.Input.GameControllers.Drivers.Sony; using Chroma.Input.GameControllers.Drivers.Sony.DualSense; using Chroma.Input.GameControllers.Drivers.Sony.DualSense.TriggerEffectPresets; using Chroma.Windowing; -namespace GameController.Views +public class DualSenseControllerView : DualShockControllerView { - public class DualSenseControllerView : DualShockControllerView - { - private LinearTriggerEffectPreset _leftTriggerPreset; - private LinearTriggerEffectPreset _rightTriggerPreset; - private byte _currentTouchpadLightMask = 0; + private LinearTriggerEffectPreset _leftTriggerPreset; + private LinearTriggerEffectPreset _rightTriggerPreset; + private byte _currentTouchpadLightMask = 0; - public override string ViewName { get; } = "DualSense controllers"; + public override string ViewName { get; } = "DualSense controllers"; + + public override Vector2 PositionOnScreen => new( + 0, + _window.Height / 2f + ); + + public override List AcceptedControllers { get; } = new() + { + ControllerType.PlayStation5 + }; - public override Vector2 PositionOnScreen => new( - 0, - _window.Height / 2f + public DualSenseControllerView(Window window) : base(window) + { + _leftTriggerPreset = new LinearTriggerEffectPreset( + 0, 0, 0, 0, -1, -1, -1, -1, -1, -1 ); - public override List AcceptedControllers { get; } = new() - { - ControllerType.PlayStation5 - }; + _rightTriggerPreset = new LinearTriggerEffectPreset( + 5, 0, 0, 0, 0, 7, 7, 7, 7, 7 + ); + } - public DualSenseControllerView(Window window) : base(window) + public override void Update(float delta) + { + base.Update(delta); + + foreach (var kvp in _controllers) { - _leftTriggerPreset = new LinearTriggerEffectPreset( - 0, 0, 0, 0, -1, -1, -1, -1, -1, -1 - ); + if (kvp.Key is DualSenseControllerDriver ds5) + { + if (ds5.AccelerometerEnabled) + kvp.Value.Accelerometer = Vector3.Normalize(ds5.ReadAccelerometerSensor()); + else kvp.Value.Accelerometer = Vector3.Zero; + + if (ds5.GyroscopeEnabled) + kvp.Value.Gyroscope = Vector3.Normalize(ds5.ReadGyroscopeSensor()); + else kvp.Value.Gyroscope = Vector3.Zero; - _rightTriggerPreset = new LinearTriggerEffectPreset( - 5, 0, 0, 0, 0, 7, 7, 7, 7, 7 - ); + kvp.Value.TouchPoints = ds5.TouchPoints.ToArray(); + } } + } - public override void Update(float delta) + public override void OnButtonPressed(ControllerButtonEventArgs e) + { + var ds5 = e.Controller.As(); + + if (e.Controller.IsButtonDown(ControllerButton.RightBumper)) { - base.Update(delta); + ds5.TriggerEffect.ClearRight(); - foreach (var kvp in _controllers) + if (e.Button == ControllerButton.A) + { + ds5.TriggerEffect.Linear(0, 0, 96, 255); + } + else if (e.Button == ControllerButton.B) { - if (kvp.Key is DualSenseControllerDriver ds5) - { - if (ds5.AccelerometerEnabled) - kvp.Value.Accelerometer = Vector3.Normalize(ds5.ReadAccelerometerSensor()); - else kvp.Value.Accelerometer = Vector3.Zero; - - if (ds5.GyroscopeEnabled) - kvp.Value.Gyroscope = Vector3.Normalize(ds5.ReadGyroscopeSensor()); - else kvp.Value.Gyroscope = Vector3.Zero; - - kvp.Value.TouchPoints = ds5.TouchPoints.ToArray(); - } + ds5.TriggerEffect.Linear(null, _rightTriggerPreset); + } + else if (e.Button == ControllerButton.X) + { + ds5.TriggerEffect.ActuationZone(0, 0, 0, 30, 90, 255); + } + else if (e.Button == ControllerButton.Y) + { + ds5.TriggerEffect.ActuationZoneRumble(0, 0, 0, 30, 255, 60); } } - public override void OnButtonPressed(ControllerButtonEventArgs e) + if (e.Controller.IsButtonDown(ControllerButton.LeftBumper)) { - var ds5 = e.Controller.As(); + ds5.TriggerEffect.ClearLeft(); - if (e.Controller.IsButtonDown(ControllerButton.RightBumper)) + if (e.Button == ControllerButton.A) { - ds5.TriggerEffect.ClearRight(); - - if (e.Button == ControllerButton.A) - { - ds5.TriggerEffect.Linear(0, 0, 96, 255); - } - else if (e.Button == ControllerButton.B) - { - ds5.TriggerEffect.Linear(null, _rightTriggerPreset); - } - else if (e.Button == ControllerButton.X) - { - ds5.TriggerEffect.ActuationZone(0, 0, 0, 30, 90, 255); - } - else if (e.Button == ControllerButton.Y) - { - ds5.TriggerEffect.ActuationZoneRumble(0, 0, 0, 30, 255, 60); - } + ds5.TriggerEffect.Linear(96, 255, 0, 0); } - - if (e.Controller.IsButtonDown(ControllerButton.LeftBumper)) + else if (e.Button == ControllerButton.B) { - ds5.TriggerEffect.ClearLeft(); - - if (e.Button == ControllerButton.A) - { - ds5.TriggerEffect.Linear(96, 255, 0, 0); - } - else if (e.Button == ControllerButton.B) - { - ds5.TriggerEffect.Linear(_leftTriggerPreset, null); - } - else if (e.Button == ControllerButton.X) - { - ds5.TriggerEffect.ActuationZone(30, 255, 255, 0, 0, 0); - } - else if (e.Button == ControllerButton.Y) - { - ds5.TriggerEffect.ActuationZoneRumble(30, 255, 30, 0, 0, 0); - } + ds5.TriggerEffect.Linear(_leftTriggerPreset, null); } - - if (e.Button == ControllerButton.Menu) + else if (e.Button == ControllerButton.X) + { + ds5.TriggerEffect.ActuationZone(30, 255, 255, 0, 0, 0); + } + else if (e.Button == ControllerButton.Y) { - if (ds5.MicrophoneLedMode == DualSenseMicrophoneLedMode.Off) - { - ds5.MicrophoneLedMode = DualSenseMicrophoneLedMode.Pulse; - } - else if (ds5.MicrophoneLedMode == DualSenseMicrophoneLedMode.Pulse) - { - ds5.MicrophoneLedMode = DualSenseMicrophoneLedMode.Solid; - } - else if (ds5.MicrophoneLedMode == DualSenseMicrophoneLedMode.Solid) - { - ds5.MicrophoneLedMode = DualSenseMicrophoneLedMode.Off; - } + ds5.TriggerEffect.ActuationZoneRumble(30, 255, 30, 0, 0, 0); } + } - if (e.Button == ControllerButton.DpadUp) + if (e.Button == ControllerButton.Menu) + { + if (ds5.MicrophoneLedMode == DualSenseMicrophoneLedMode.Off) { - ds5.SetTouchpadLights(_currentTouchpadLightMask++); + ds5.MicrophoneLedMode = DualSenseMicrophoneLedMode.Pulse; + } + else if (ds5.MicrophoneLedMode == DualSenseMicrophoneLedMode.Pulse) + { + ds5.MicrophoneLedMode = DualSenseMicrophoneLedMode.Solid; + } + else if (ds5.MicrophoneLedMode == DualSenseMicrophoneLedMode.Solid) + { + ds5.MicrophoneLedMode = DualSenseMicrophoneLedMode.Off; } } - public override void OnAxisMoved(ControllerAxisEventArgs e) + if (e.Button == ControllerButton.DpadUp) { - base.OnAxisMoved(e); + ds5.SetTouchpadLights(_currentTouchpadLightMask++); + } + } + + public override void OnAxisMoved(ControllerAxisEventArgs e) + { + base.OnAxisMoved(e); - if (e.Axis == ControllerAxis.LeftTrigger) + if (e.Axis == ControllerAxis.LeftTrigger) + { + var norm = e.Controller.GetAxisValueNormalized(e.Axis); + if (norm >= 0.60f && norm <= 0.60f) { - var norm = e.Controller.GetAxisValueNormalized(e.Axis); - if (norm >= 0.60f && norm <= 0.60f) - { - e.Controller.Rumble(32768, 32768, 100); - } + e.Controller.Rumble(32768, 32768, 100); } } } diff --git a/Chroma.Examples/GameController/Views/DualShockControllerView.cs b/Chroma.Examples/GameController/Views/DualShockControllerView.cs index c8733bcf..033aa442 100644 --- a/Chroma.Examples/GameController/Views/DualShockControllerView.cs +++ b/Chroma.Examples/GameController/Views/DualShockControllerView.cs @@ -1,3 +1,5 @@ +namespace GameController.Views; + using System; using System.Collections.Generic; using System.Linq; @@ -7,113 +9,110 @@ using Chroma.Input.GameControllers.Drivers.Sony; using Chroma.Windowing; -namespace GameController.Views +public class DualShockControllerView : GenericControllerView { - public class DualShockControllerView : GenericControllerView - { - public override string ViewName => "DualShock 4 controllers"; + public override string ViewName => "DualShock 4 controllers"; - public override Vector2 PositionOnScreen => Vector2.Zero; + public override Vector2 PositionOnScreen => Vector2.Zero; - public override List AcceptedControllers { get; } = new() - { - ControllerType.PlayStation4 - }; + public override List AcceptedControllers { get; } = new() + { + ControllerType.PlayStation4 + }; - public override Dictionary ButtonColors { get; } = new() - { - { ControllerButton.A, Color.Blue }, - { ControllerButton.B, Color.Red }, - { ControllerButton.X, Color.HotPink }, - { ControllerButton.Y, Color.Lime } - }; + public override Dictionary ButtonColors { get; } = new() + { + { ControllerButton.A, Color.Blue }, + { ControllerButton.B, Color.Red }, + { ControllerButton.X, Color.HotPink }, + { ControllerButton.Y, Color.Lime } + }; - public override Color RightStickHatColor { get; } = Color.Orange; + public override Color RightStickHatColor { get; } = Color.Orange; - public DualShockControllerView(Window window) : base(window) - { - } + public DualShockControllerView(Window window) : base(window) + { + } - public override void Update(float delta) - { - base.Update(delta); + public override void Update(float delta) + { + base.Update(delta); - foreach (var kvp in _controllers) + foreach (var kvp in _controllers) + { + if (kvp.Key is SonyControllerDriver ds) { - if (kvp.Key is SonyControllerDriver ds) - { - if (ds.AccelerometerEnabled) - kvp.Value.Accelerometer = Vector3.Normalize(ds.ReadAccelerometerSensor()); - else kvp.Value.Accelerometer = Vector3.Zero; + if (ds.AccelerometerEnabled) + kvp.Value.Accelerometer = Vector3.Normalize(ds.ReadAccelerometerSensor()); + else kvp.Value.Accelerometer = Vector3.Zero; - if (ds.GyroscopeEnabled) - kvp.Value.Gyroscope = Vector3.Normalize(ds.ReadGyroscopeSensor()); - else kvp.Value.Gyroscope = Vector3.Zero; + if (ds.GyroscopeEnabled) + kvp.Value.Gyroscope = Vector3.Normalize(ds.ReadGyroscopeSensor()); + else kvp.Value.Gyroscope = Vector3.Zero; - kvp.Value.TouchPoints = ds.TouchPoints.ToArray(); - } + kvp.Value.TouchPoints = ds.TouchPoints.ToArray(); } } + } - protected override void DrawViewSpecific(ControllerDriver controller, PlayerView player, RenderContext context) + protected override void DrawViewSpecific(ControllerDriver controller, PlayerView player, RenderContext context) + { + if (Math.Abs(player.Accelerometer.X) > 0.03f || Math.Abs(player.Accelerometer.Z) > 0.03f) { - if (Math.Abs(player.Accelerometer.X) > 0.03f || Math.Abs(player.Accelerometer.Z) > 0.03f) - { - context.Line( - player.Rectangle.X + player.Rectangle.Width / 2, - player.Rectangle.Y + player.Rectangle.Height / 2, - player.Rectangle.X + player.Rectangle.Width / 2 - 72 * player.Accelerometer.X, - player.Rectangle.Y + player.Rectangle.Width / 2 - 72 * player.Accelerometer.Z, - Color.Cyan - ); - } + context.Line( + player.Rectangle.X + player.Rectangle.Width / 2, + player.Rectangle.Y + player.Rectangle.Height / 2, + player.Rectangle.X + player.Rectangle.Width / 2 - 72 * player.Accelerometer.X, + player.Rectangle.Y + player.Rectangle.Width / 2 - 72 * player.Accelerometer.Z, + Color.Cyan + ); + } - if (Math.Abs(player.Gyroscope.X) > 0.03f || Math.Abs(player.Gyroscope.Z) > 0.03f) - { - context.Line( - player.Rectangle.X + player.Rectangle.Width / 2, - player.Rectangle.Y + player.Rectangle.Height / 2, - player.Rectangle.X + player.Rectangle.Width / 2 - 72 * player.Gyroscope.Y, - player.Rectangle.Y + player.Rectangle.Width / 2 - 72 * player.Gyroscope.X, - Color.Gold - ); - } + if (Math.Abs(player.Gyroscope.X) > 0.03f || Math.Abs(player.Gyroscope.Z) > 0.03f) + { + context.Line( + player.Rectangle.X + player.Rectangle.Width / 2, + player.Rectangle.Y + player.Rectangle.Height / 2, + player.Rectangle.X + player.Rectangle.Width / 2 - 72 * player.Gyroscope.Y, + player.Rectangle.Y + player.Rectangle.Width / 2 - 72 * player.Gyroscope.X, + Color.Gold + ); + } - foreach (var touchPoint in player.TouchPoints) + foreach (var touchPoint in player.TouchPoints) + { + if (touchPoint.Touching) { - if (touchPoint.Touching) - { - context.Circle( - ShapeMode.Stroke, - player.Rectangle.X + player.Rectangle.Width / 2 + 128 * touchPoint.Position.X - 64, - player.Rectangle.Y + player.Rectangle.Height / 2 + 64 * touchPoint.Position.Y - 32, - 8, - Color.Magenta - ); - } + context.Circle( + ShapeMode.Stroke, + player.Rectangle.X + player.Rectangle.Width / 2 + 128 * touchPoint.Position.X - 64, + player.Rectangle.Y + player.Rectangle.Height / 2 + 64 * touchPoint.Position.Y - 32, + 8, + Color.Magenta + ); } } + } - public override void OnButtonPressed(ControllerButtonEventArgs e) + public override void OnButtonPressed(ControllerButtonEventArgs e) + { + if (e.Button == ControllerButton.Touchpad) { - if (e.Button == ControllerButton.Touchpad) - { - var ds4 = e.Controller.As(); + var ds4 = e.Controller.As(); - foreach (var tp in ds4.TouchPoints) + foreach (var tp in ds4.TouchPoints) + { + if (tp.Touching) { - if (tp.Touching) + if (tp.Position.X > 0.5) + { + ds4.AccelerometerEnabled = !ds4.AccelerometerEnabled; + } + else if (tp.Position.X < 0.5) { - if (tp.Position.X > 0.5) - { - ds4.AccelerometerEnabled = !ds4.AccelerometerEnabled; - } - else if (tp.Position.X < 0.5) - { - ds4.GyroscopeEnabled = !ds4.GyroscopeEnabled; - } - break; + ds4.GyroscopeEnabled = !ds4.GyroscopeEnabled; } + break; } } } diff --git a/Chroma.Examples/GameController/Views/GenericControllerView.cs b/Chroma.Examples/GameController/Views/GenericControllerView.cs index 81c99132..3280bc90 100644 --- a/Chroma.Examples/GameController/Views/GenericControllerView.cs +++ b/Chroma.Examples/GameController/Views/GenericControllerView.cs @@ -1,327 +1,325 @@ +namespace GameController.Views; + using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using Chroma.Graphics; -using Chroma.Input.GameControllers; -using Chroma; using Chroma.Graphics.TextRendering.TrueType; +using Chroma.Input.GameControllers; using Chroma.Windowing; -namespace GameController.Views +public class GenericControllerView { - public class GenericControllerView - { - private Queue _scheduledForConnection = new(); - private Queue _scheduledForRemoval = new(); + private Queue _scheduledForConnection = new(); + private Queue _scheduledForRemoval = new(); - protected Window _window; - protected RenderTarget _renderTarget; + protected Window _window; + protected RenderTarget _renderTarget; - protected Dictionary _controllers = new(); + protected Dictionary _controllers = new(); - protected float _movementSpeed = 300.0f; + protected float _movementSpeed = 300.0f; - public virtual string ViewName => "Generic controllers"; + public virtual string ViewName => "Generic controllers"; - public virtual Color RightStickHatColor { get; } = Color.HotPink; - - public virtual List AcceptedControllers { get; } = new() - { - ControllerType.Unknown, - ControllerType.Virtual, - ControllerType.Xbox360, - ControllerType.XboxOne, - ControllerType.AmazonLuna, - ControllerType.GoogleStadia - }; - - public virtual Dictionary ButtonColors { get; } = new() - { - { ControllerButton.A, Color.Lime }, - { ControllerButton.B, Color.Red }, - { ControllerButton.X, Color.Blue }, - { ControllerButton.Y, Color.Yellow } - }; - - public virtual Vector2 PositionOnScreen => new( - _window.Width - _renderTarget.Width, - _window.Height - _renderTarget.Height - ); + public virtual Color RightStickHatColor { get; } = Color.HotPink; - public GenericControllerView(Window window) - { - _window = window; - _renderTarget = new RenderTarget(window.Size / 2); - } + public virtual List AcceptedControllers { get; } = new() + { + ControllerType.Unknown, + ControllerType.Virtual, + ControllerType.Xbox360, + ControllerType.XboxOne, + ControllerType.AmazonLuna, + ControllerType.GoogleStadia + }; + + public virtual Dictionary ButtonColors { get; } = new() + { + { ControllerButton.A, Color.Lime }, + { ControllerButton.B, Color.Red }, + { ControllerButton.X, Color.Blue }, + { ControllerButton.Y, Color.Yellow } + }; + + public virtual Vector2 PositionOnScreen => new( + _window.Width - _renderTarget.Width, + _window.Height - _renderTarget.Height + ); + + public GenericControllerView(Window window) + { + _window = window; + _renderTarget = new RenderTarget(window.Size / 2); + } - public virtual void OnConnected(ControllerEventArgs e) - { - if (!AcceptedControllers.Contains(e.Controller.Info.Type)) - return; + public virtual void OnConnected(ControllerEventArgs e) + { + if (!AcceptedControllers.Contains(e.Controller.Info.Type)) + return; - e.Controller.SetDeadZone(ControllerAxis.LeftStickX, 4000); - e.Controller.SetDeadZone(ControllerAxis.LeftStickY, 4000); + e.Controller.SetDeadZone(ControllerAxis.LeftStickX, 4000); + e.Controller.SetDeadZone(ControllerAxis.LeftStickY, 4000); - _scheduledForConnection.Enqueue(e.Controller); - } + _scheduledForConnection.Enqueue(e.Controller); + } - public virtual void OnDisconnected(ControllerEventArgs e) - { - if (!_controllers.ContainsKey(e.Controller)) - return; + public virtual void OnDisconnected(ControllerEventArgs e) + { + if (!_controllers.ContainsKey(e.Controller)) + return; - _scheduledForRemoval.Enqueue(e.Controller); - } + _scheduledForRemoval.Enqueue(e.Controller); + } - public virtual void OnTouchpadMoved(ControllerTouchpadEventArgs e) - { - } + public virtual void OnTouchpadMoved(ControllerTouchpadEventArgs e) + { + } - public virtual void OnTouchpadTouched(ControllerTouchpadEventArgs e) - { - } + public virtual void OnTouchpadTouched(ControllerTouchpadEventArgs e) + { + } - public virtual void OnTouchpadReleased(ControllerTouchpadEventArgs e) - { - } + public virtual void OnTouchpadReleased(ControllerTouchpadEventArgs e) + { + } - public virtual void OnSensorStateChanged(ControllerSensorEventArgs e) - { - } + public virtual void OnSensorStateChanged(ControllerSensorEventArgs e) + { + } - public virtual void OnAxisMoved(ControllerAxisEventArgs e) - { - } + public virtual void OnAxisMoved(ControllerAxisEventArgs e) + { + } - public virtual void OnButtonPressed(ControllerButtonEventArgs e) - { - } + public virtual void OnButtonPressed(ControllerButtonEventArgs e) + { + } - public virtual void OnButtonReleased(ControllerButtonEventArgs e) - { - } + public virtual void OnButtonReleased(ControllerButtonEventArgs e) + { + } - public virtual void Update(float delta) + public virtual void Update(float delta) + { + while (_scheduledForConnection.Any()) { - while (_scheduledForConnection.Any()) - { - var controller = _scheduledForConnection.Dequeue(); + var controller = _scheduledForConnection.Dequeue(); - _controllers.Add( - controller, - new PlayerView( - _renderTarget.Width / 2 - 16, - _renderTarget.Height / 2 - 16, - 32, - 32 - ) - ); - } + _controllers.Add( + controller, + new PlayerView( + _renderTarget.Width / 2 - 16, + _renderTarget.Height / 2 - 16, + 32, + 32 + ) + ); + } - foreach (var kvp in _controllers) - { - var playerView = kvp.Value; + foreach (var kvp in _controllers) + { + var playerView = kvp.Value; - playerView.Rectangle.X += kvp.Key.GetAxisValueNormalized(ControllerAxis.LeftStickX) * delta * _movementSpeed; - playerView.Rectangle.Y += kvp.Key.GetAxisValueNormalized(ControllerAxis.LeftStickY) * delta * _movementSpeed; - - if (playerView.Rectangle.X < 0) - playerView.Rectangle.X = 0; - else if (playerView.Rectangle.X + playerView.Rectangle.Width > _renderTarget.Width) - playerView.Rectangle.X = _renderTarget.Width - playerView.Rectangle.Width; - - if (playerView.Rectangle.Y < 0) - playerView.Rectangle.Y = 0; - else if (playerView.Rectangle.Y + playerView.Rectangle.Height > _renderTarget.Height) - playerView.Rectangle.Y = _renderTarget.Height - playerView.Rectangle.Height; + playerView.Rectangle.X += kvp.Key.GetAxisValueNormalized(ControllerAxis.LeftStickX) * delta * _movementSpeed; + playerView.Rectangle.Y += kvp.Key.GetAxisValueNormalized(ControllerAxis.LeftStickY) * delta * _movementSpeed; + + if (playerView.Rectangle.X < 0) + playerView.Rectangle.X = 0; + else if (playerView.Rectangle.X + playerView.Rectangle.Width > _renderTarget.Width) + playerView.Rectangle.X = _renderTarget.Width - playerView.Rectangle.Width; + + if (playerView.Rectangle.Y < 0) + playerView.Rectangle.Y = 0; + else if (playerView.Rectangle.Y + playerView.Rectangle.Height > _renderTarget.Height) + playerView.Rectangle.Y = _renderTarget.Height - playerView.Rectangle.Height; - playerView.TriggerLeft = kvp.Key.GetAxisValueNormalized(ControllerAxis.LeftTrigger); - playerView.TriggerRight = kvp.Key.GetAxisValueNormalized(ControllerAxis.RightTrigger); - playerView.RightStickX = kvp.Key.GetAxisValueNormalized(ControllerAxis.RightStickX); - playerView.RightStickY = kvp.Key.GetAxisValueNormalized(ControllerAxis.RightStickY); + playerView.TriggerLeft = kvp.Key.GetAxisValueNormalized(ControllerAxis.LeftTrigger); + playerView.TriggerRight = kvp.Key.GetAxisValueNormalized(ControllerAxis.RightTrigger); + playerView.RightStickX = kvp.Key.GetAxisValueNormalized(ControllerAxis.RightStickX); + playerView.RightStickY = kvp.Key.GetAxisValueNormalized(ControllerAxis.RightStickY); - _controllers[kvp.Key] = playerView; + _controllers[kvp.Key] = playerView; - if (kvp.Key.IsButtonDown(ControllerButton.A)) - playerView.Color = ButtonColors[ControllerButton.A]; + if (kvp.Key.IsButtonDown(ControllerButton.A)) + playerView.Color = ButtonColors[ControllerButton.A]; - if (kvp.Key.IsButtonDown(ControllerButton.B)) - playerView.Color = ButtonColors[ControllerButton.B]; + if (kvp.Key.IsButtonDown(ControllerButton.B)) + playerView.Color = ButtonColors[ControllerButton.B]; - if (kvp.Key.IsButtonDown(ControllerButton.X)) - playerView.Color = ButtonColors[ControllerButton.X]; + if (kvp.Key.IsButtonDown(ControllerButton.X)) + playerView.Color = ButtonColors[ControllerButton.X]; - if (kvp.Key.IsButtonDown(ControllerButton.Y)) - playerView.Color = ButtonColors[ControllerButton.Y]; + if (kvp.Key.IsButtonDown(ControllerButton.Y)) + playerView.Color = ButtonColors[ControllerButton.Y]; - kvp.Key.SetLedColor(playerView.Color); - } + kvp.Key.SetLedColor(playerView.Color); + } - while (_scheduledForRemoval.Any()) - { - var controller = _scheduledForRemoval.Dequeue(); - _controllers.Remove(controller); - } + while (_scheduledForRemoval.Any()) + { + var controller = _scheduledForRemoval.Dequeue(); + _controllers.Remove(controller); } + } - public virtual void Draw(RenderContext context) + public virtual void Draw(RenderContext context) + { + context.RenderTo(_renderTarget, (ctx, tgt) => { - context.RenderTo(_renderTarget, (ctx, tgt) => - { - ctx.Clear(Color.Black); + ctx.Clear(Color.Black); - foreach (var kvp in _controllers) - { - var controller = kvp.Key; - var player = kvp.Value; - ctx.Rectangle(ShapeMode.Fill, player.Rectangle, player.Color); + foreach (var kvp in _controllers) + { + var controller = kvp.Key; + var player = kvp.Value; + ctx.Rectangle(ShapeMode.Fill, player.Rectangle, player.Color); - var playerLabel = controller.Info.PlayerIndex.ToString(); - var labelMeasure = TrueTypeFont.Default.Measure(playerLabel); - - ctx.DrawString( - playerLabel, - new Vector2( - player.Rectangle.X + (player.Rectangle.Width / 2f - labelMeasure.Width / 2f), - player.Rectangle.Y + (player.Rectangle.Height / 2f - labelMeasure.Height / 2f) - ), - Color.Black - ); + var playerLabel = controller.Info.PlayerIndex.ToString(); + var labelMeasure = TrueTypeFont.Default.Measure(playerLabel); + + ctx.DrawString( + playerLabel, + new Vector2( + player.Rectangle.X + (player.Rectangle.Width / 2f - labelMeasure.Width / 2f), + player.Rectangle.Y + (player.Rectangle.Height / 2f - labelMeasure.Height / 2f) + ), + Color.Black + ); - var playerButtonsLabel = string.Join(", ", controller.ActiveButtons); - var playerButtonsMeasure = TrueTypeFont.Default.Measure(playerButtonsLabel); + var playerButtonsLabel = string.Join(", ", controller.ActiveButtons); + var playerButtonsMeasure = TrueTypeFont.Default.Measure(playerButtonsLabel); + ctx.DrawString( + playerButtonsLabel, + new Vector2( + player.Rectangle.X + (player.Rectangle.Width / 2f - playerButtonsMeasure.Width / 2f), + player.Rectangle.Y - TrueTypeFont.Default.Height - 8 + ) + ); + + if (player.TriggerLeft > 0) + { + var triggerLabel = player.TriggerLeft.ToString("F3"); + var triggerMeasure = TrueTypeFont.Default.Measure(triggerLabel); + ctx.DrawString( - playerButtonsLabel, + triggerLabel, new Vector2( - player.Rectangle.X + (player.Rectangle.Width / 2f - playerButtonsMeasure.Width / 2f), - player.Rectangle.Y - TrueTypeFont.Default.Height - 8 + player.Rectangle.X - triggerMeasure.Width - 8, + player.Rectangle.Y + (player.Rectangle.Height / 2f - triggerMeasure.Height / 2f) ) ); - if (player.TriggerLeft > 0) + BlendTriggerBar(() => { - var triggerLabel = player.TriggerLeft.ToString("F3"); - var triggerMeasure = TrueTypeFont.Default.Measure(triggerLabel); - - ctx.DrawString( - triggerLabel, - new Vector2( - player.Rectangle.X - triggerMeasure.Width - 8, - player.Rectangle.Y + (player.Rectangle.Height / 2f - triggerMeasure.Height / 2f) - ) + ctx.Rectangle( + ShapeMode.Fill, + player.Rectangle.X, + player.Rectangle.Y + player.Rectangle.Height / 2 - 8, + -((triggerMeasure.Width + 16) * player.TriggerLeft), + 16, + player.Color ); + }); + } - BlendTriggerBar(() => - { - ctx.Rectangle( - ShapeMode.Fill, - player.Rectangle.X, - player.Rectangle.Y + player.Rectangle.Height / 2 - 8, - -((triggerMeasure.Width + 16) * player.TriggerLeft), - 16, - player.Color - ); - }); - } - - if (player.TriggerRight > 0) - { - var triggerLabel = player.TriggerRight.ToString("F3"); - var triggerMeasure = TrueTypeFont.Default.Measure(triggerLabel); - - ctx.DrawString( - triggerLabel, - new Vector2( - player.Rectangle.X + player.Rectangle.Width + 8, - player.Rectangle.Y + (player.Rectangle.Height / 2f - triggerMeasure.Height / 2f) - ) - ); + if (player.TriggerRight > 0) + { + var triggerLabel = player.TriggerRight.ToString("F3"); + var triggerMeasure = TrueTypeFont.Default.Measure(triggerLabel); - BlendTriggerBar(() => - { - ctx.Rectangle( - ShapeMode.Fill, - player.Rectangle.X + player.Rectangle.Width, - player.Rectangle.Y + player.Rectangle.Height / 2 - 8, - (triggerMeasure.Width + 16) * player.TriggerRight, - 16, - player.Color - ); - }); - } - - var typeLabel = controller.Info.Type.ToString(); - var typeMeasure = TrueTypeFont.Default.Measure(typeLabel); ctx.DrawString( - typeLabel, + triggerLabel, new Vector2( - player.Rectangle.X + (player.Rectangle.Width / 2f - typeMeasure.Width / 2f), - player.Rectangle.Y + player.Rectangle.Height + 4 - ), - player.Color + player.Rectangle.X + player.Rectangle.Width + 8, + player.Rectangle.Y + (player.Rectangle.Height / 2f - triggerMeasure.Height / 2f) + ) ); - - if (Math.Abs(player.RightStickX) > 0.09 || Math.Abs(player.RightStickY) > 0.09) + + BlendTriggerBar(() => { - ctx.Circle( - ShapeMode.Fill, - new Vector2( - player.Rectangle.X + player.Rectangle.Width / 2 + (32 * player.RightStickX), - player.Rectangle.Y + player.Rectangle.Height / 2 + (32 * player.RightStickY) - ), - 6, - RightStickHatColor + ctx.Rectangle( + ShapeMode.Fill, + player.Rectangle.X + player.Rectangle.Width, + player.Rectangle.Y + player.Rectangle.Height / 2 - 8, + (triggerMeasure.Width + 16) * player.TriggerRight, + 16, + player.Color ); - } - - DrawViewSpecific(controller, player, ctx); + }); } - PostDraw(context); - - context.DrawString( - ViewName, - new(8, 8), - Color.White + var typeLabel = controller.Info.Type.ToString(); + var typeMeasure = TrueTypeFont.Default.Measure(typeLabel); + ctx.DrawString( + typeLabel, + new Vector2( + player.Rectangle.X + (player.Rectangle.Width / 2f - typeMeasure.Width / 2f), + player.Rectangle.Y + player.Rectangle.Height + 4 + ), + player.Color ); - }); + + if (Math.Abs(player.RightStickX) > 0.09 || Math.Abs(player.RightStickY) > 0.09) + { + ctx.Circle( + ShapeMode.Fill, + new Vector2( + player.Rectangle.X + player.Rectangle.Width / 2 + (32 * player.RightStickX), + player.Rectangle.Y + player.Rectangle.Height / 2 + (32 * player.RightStickY) + ), + 6, + RightStickHatColor + ); + } + + DrawViewSpecific(controller, player, ctx); + } + + PostDraw(context); - context.DrawTexture( - _renderTarget, - PositionOnScreen + context.DrawString( + ViewName, + new(8, 8), + Color.White ); - } + }); + + context.DrawTexture( + _renderTarget, + PositionOnScreen + ); + } - protected virtual void DrawViewSpecific(ControllerDriver controller, PlayerView player, RenderContext context) - { - } + protected virtual void DrawViewSpecific(ControllerDriver controller, PlayerView player, RenderContext context) + { + } - protected virtual void PostDraw(RenderContext context) - { + protected virtual void PostDraw(RenderContext context) + { - } + } - private void BlendTriggerBar(Action renderLogic) - { - if (renderLogic == null) - return; + private void BlendTriggerBar(Action renderLogic) + { + if (renderLogic == null) + return; - RenderSettings.SetShapeBlendingEquations( - BlendingEquation.Subtract, - BlendingEquation.Add - ); - RenderSettings.SetShapeBlendingFunctions( - BlendingFunction.SourceColor, - BlendingFunction.One, - BlendingFunction.One, - BlendingFunction.Zero - ); + RenderSettings.SetShapeBlendingEquations( + BlendingEquation.Subtract, + BlendingEquation.Add + ); + RenderSettings.SetShapeBlendingFunctions( + BlendingFunction.SourceColor, + BlendingFunction.One, + BlendingFunction.One, + BlendingFunction.Zero + ); - renderLogic(); + renderLogic(); - RenderSettings.ResetShapeBlending(); - } + RenderSettings.ResetShapeBlending(); } } \ No newline at end of file diff --git a/Chroma.Examples/GameController/Views/NintendoControllerView.cs b/Chroma.Examples/GameController/Views/NintendoControllerView.cs index 3db30d80..9b98bb23 100644 --- a/Chroma.Examples/GameController/Views/NintendoControllerView.cs +++ b/Chroma.Examples/GameController/Views/NintendoControllerView.cs @@ -1,120 +1,116 @@ +namespace GameController.Views; + using System; using System.Collections.Generic; -using System.Linq; using System.Numerics; -using Chroma; using Chroma.Graphics; using Chroma.Graphics.TextRendering.TrueType; using Chroma.Input.GameControllers; -using Chroma.Input.GameControllers.Drivers; using Chroma.Input.GameControllers.Drivers.Capabilities; using Chroma.Input.GameControllers.Drivers.Nintendo; using Chroma.Windowing; -namespace GameController.Views +public class NintendoControllerView : GenericControllerView { - public class NintendoControllerView : GenericControllerView + public override string ViewName { get; } = "Nintendo controllers"; + public override Vector2 PositionOnScreen => new(_window.Width / 2f, 0); + + public override List AcceptedControllers { get; } = new() { - public override string ViewName { get; } = "Nintendo controllers"; - public override Vector2 PositionOnScreen => new(_window.Width / 2f, 0); + ControllerType.NintendoSwitch + }; - public override List AcceptedControllers { get; } = new() - { - ControllerType.NintendoSwitch - }; + public NintendoControllerView(Window window) + : base(window) + { + } - public NintendoControllerView(Window window) - : base(window) - { - } + public override void Update(float delta) + { + base.Update(delta); - public override void Update(float delta) + foreach (var kvp in _controllers) { - base.Update(delta); - - foreach (var kvp in _controllers) + if (kvp.Key is IAccelerometerEnabled accel) { - if (kvp.Key is IAccelerometerEnabled accel) - { - if (accel.AccelerometerEnabled) - kvp.Value.Accelerometer = Vector3.Normalize(accel.ReadAccelerometerSensor()); - else kvp.Value.Accelerometer = Vector3.Zero; - } - if (kvp.Key is IGyroscopeEnabled gyro) - { - if (gyro.GyroscopeEnabled) - kvp.Value.Gyroscope = Vector3.Normalize(gyro.ReadGyroscopeSensor()); - else kvp.Value.Gyroscope = Vector3.Zero; - } + if (accel.AccelerometerEnabled) + kvp.Value.Accelerometer = Vector3.Normalize(accel.ReadAccelerometerSensor()); + else kvp.Value.Accelerometer = Vector3.Zero; + } + if (kvp.Key is IGyroscopeEnabled gyro) + { + if (gyro.GyroscopeEnabled) + kvp.Value.Gyroscope = Vector3.Normalize(gyro.ReadGyroscopeSensor()); + else kvp.Value.Gyroscope = Vector3.Zero; } } + } - protected override void DrawViewSpecific(ControllerDriver controller, PlayerView player, RenderContext context) + protected override void DrawViewSpecific(ControllerDriver controller, PlayerView player, RenderContext context) + { + if (controller is SwitchJoyConControllerDriver joycon) { - if (controller is SwitchJoyConControllerDriver joycon) - { - var label = (joycon.IsLeftSide ? "L" : "R") + (joycon.UseInputRemapping ? "" : "*"); - var labelMeasure = TrueTypeFont.Default.Measure(label); - context.DrawString(label, new Vector2( - player.Rectangle.X + - (joycon.IsLeftSide ? -16 : player.Rectangle.Width + 16) - (labelMeasure.Width / 2), - player.Rectangle.Y + (player.Rectangle.Height / 2f - labelMeasure.Height / 2f) - )); - } + var label = (joycon.IsLeftSide ? "L" : "R") + (joycon.UseInputRemapping ? "" : "*"); + var labelMeasure = TrueTypeFont.Default.Measure(label); + context.DrawString(label, new Vector2( + player.Rectangle.X + + (joycon.IsLeftSide ? -16 : player.Rectangle.Width + 16) - (labelMeasure.Width / 2), + player.Rectangle.Y + (player.Rectangle.Height / 2f - labelMeasure.Height / 2f) + )); + } - if (controller is NintendoControllerDriver { UseXboxButtonLayout: true }) - { - context.DrawString("X", new Vector2(player.Rectangle.X, player.Rectangle.Y - 5), Color.Black); - } + if (controller is NintendoControllerDriver { UseXboxButtonLayout: true }) + { + context.DrawString("X", new Vector2(player.Rectangle.X, player.Rectangle.Y - 5), Color.Black); + } - if (Math.Abs(player.Accelerometer.X) > 0.03f || Math.Abs(player.Accelerometer.Z) > 0.03f) - { - context.Line( - player.Rectangle.X + player.Rectangle.Width / 2, - player.Rectangle.Y + player.Rectangle.Height / 2, - player.Rectangle.X + player.Rectangle.Width / 2 - 72 * player.Accelerometer.X, - player.Rectangle.Y + player.Rectangle.Width / 2 - 72 * player.Accelerometer.Z, - Color.Cyan - ); - } + if (Math.Abs(player.Accelerometer.X) > 0.03f || Math.Abs(player.Accelerometer.Z) > 0.03f) + { + context.Line( + player.Rectangle.X + player.Rectangle.Width / 2, + player.Rectangle.Y + player.Rectangle.Height / 2, + player.Rectangle.X + player.Rectangle.Width / 2 - 72 * player.Accelerometer.X, + player.Rectangle.Y + player.Rectangle.Width / 2 - 72 * player.Accelerometer.Z, + Color.Cyan + ); + } - if (Math.Abs(player.Gyroscope.X) > 0.03f || Math.Abs(player.Gyroscope.Z) > 0.03f) - { - context.Line( - player.Rectangle.X + player.Rectangle.Width / 2, - player.Rectangle.Y + player.Rectangle.Height / 2, - player.Rectangle.X + player.Rectangle.Width / 2 - 72 * player.Gyroscope.Y, - player.Rectangle.Y + player.Rectangle.Width / 2 - 72 * player.Gyroscope.X, - Color.Gold - ); - } + if (Math.Abs(player.Gyroscope.X) > 0.03f || Math.Abs(player.Gyroscope.Z) > 0.03f) + { + context.Line( + player.Rectangle.X + player.Rectangle.Width / 2, + player.Rectangle.Y + player.Rectangle.Height / 2, + player.Rectangle.X + player.Rectangle.Width / 2 - 72 * player.Gyroscope.Y, + player.Rectangle.Y + player.Rectangle.Width / 2 - 72 * player.Gyroscope.X, + Color.Gold + ); + } + } + + public override void OnButtonPressed(ControllerButtonEventArgs e) + { + if (e.Button is ControllerButton.Logo or ControllerButton.Special + && e.Controller is SwitchJoyConControllerDriver joycon) + { + joycon.UseInputRemapping = !joycon.UseInputRemapping; } - public override void OnButtonPressed(ControllerButtonEventArgs e) + if (e.Button is ControllerButton.Menu && e.Controller is NintendoControllerDriver nintendoController) { - if (e.Button is ControllerButton.Logo or ControllerButton.Special - && e.Controller is SwitchJoyConControllerDriver joycon) - { - joycon.UseInputRemapping = !joycon.UseInputRemapping; - } + nintendoController.UseXboxButtonLayout = !nintendoController.UseXboxButtonLayout; + } - if (e.Button is ControllerButton.Menu && e.Controller is NintendoControllerDriver nintendoController) + if (e.Button is ControllerButton.LeftStick) + { + if (e.Controller is SwitchProControllerDriver pro) { - nintendoController.UseXboxButtonLayout = !nintendoController.UseXboxButtonLayout; + pro.GyroscopeEnabled = !pro.GyroscopeEnabled; + pro.AccelerometerEnabled = !pro.AccelerometerEnabled; } - - if (e.Button is ControllerButton.LeftStick) + else if (e.Controller is SwitchJoyConControllerDriver con) { - if (e.Controller is SwitchProControllerDriver pro) - { - pro.GyroscopeEnabled = !pro.GyroscopeEnabled; - pro.AccelerometerEnabled = !pro.AccelerometerEnabled; - } - else if (e.Controller is SwitchJoyConControllerDriver con) - { - con.GyroscopeEnabled = !con.GyroscopeEnabled; - con.AccelerometerEnabled = !con.AccelerometerEnabled; - } + con.GyroscopeEnabled = !con.GyroscopeEnabled; + con.AccelerometerEnabled = !con.AccelerometerEnabled; } } } diff --git a/Chroma.Examples/GlyphTransforms/GameCore.cs b/Chroma.Examples/GlyphTransforms/GameCore.cs index 982d6983..9374b315 100644 --- a/Chroma.Examples/GlyphTransforms/GameCore.cs +++ b/Chroma.Examples/GlyphTransforms/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace GlyphTransforms; + +using System; using System.Collections.Generic; using System.Drawing; using System.Geometry; @@ -7,143 +9,139 @@ using Chroma; using Chroma.Diagnostics; using Chroma.Graphics; -using Chroma.Graphics.TextRendering; using Chroma.Graphics.TextRendering.TrueType; using Color = Chroma.Graphics.Color; -namespace GlyphTransforms +public class GameCore : Game { - public class GameCore : Game + private float _angle; + + private List _colors = new() { - private float _angle; + Color.Red, + Color.Orange, + Color.Yellow, + Color.Lime, + Color.DodgerBlue, + Color.Indigo, + Color.Purple + }; + + private Random _random = new(); + + public GameCore() : base(new(false, false)) + { + } - private List _colors = new() - { - Color.Red, - Color.Orange, - Color.Yellow, - Color.Lime, - Color.DodgerBlue, - Color.Indigo, - Color.Purple - }; - - private Random _random = new(); - - public GameCore() : base(new(false, false)) - { - } + protected override void Update(float delta) + { + _angle += 10 * delta; + } - protected override void Update(float delta) - { - _angle += 10 * delta; - } + private List _floats = new(); + private List _pos = new(); - private List _floats = new(); - private List _pos = new(); + protected override void Draw(RenderContext context) + { + context.DrawString( + "This text should be colored like a rainbow UwU", + new Vector2(8), + (d, _, i, p) => + { + d.Position = p; + d.Color = _colors[i % _colors.Count]; + } + ); - protected override void Draw(RenderContext context) - { - context.DrawString( - "This text should be colored like a rainbow UwU", - new Vector2(8), - (d, _, i, p) => - { - d.Position = p; - d.Color = _colors[i % _colors.Count]; - } - ); - - context.DrawString( - "This text should be wavy!", - new Vector2(64), - (d, _, i, p) => - { - var offsetY = 3 * MathF.Sin(_angle + (i * 4)); - d.Position = p + new Vector2(0, offsetY); - } - ); - - context.DrawString( - "This text should be circley!", - new Vector2(200), - (d, _, i, _) => - { - // this example uses Bezier nuget library - // it's excellent for geometry calculations. - // - // also thanks to using .NET's System.Numerics - // types, interop between different libraries - // and Chroma is easy af. - var circle = new Circle(160); - var pointOnCircle = circle.Position((i * 2 + _angle) / 100); - var offsetY = 3 * MathF.Sin(_angle + (i * 4)); - pointOnCircle.Y += offsetY; - - d.Position = pointOnCircle + new Vector2(300); - d.Rotation = _angle * 10; - d.Color = _colors[i % _colors.Count]; - } - ); - - context.DrawString( - "This text should be rotated 90 degrees right.", - new Vector2(120, 250), - (d, c, i, p) => - { - var offsets = TrueTypeFont.Default.GetRenderOffsets(c); - var bounds = TrueTypeFont.Default.GetGlyphBounds(c); - TrueTypeFont.Default.GetGlyphControlBox( - c, - out _, - out _, - out var yMin, - out _ - ); - - d.Position = new(p.Y - offsets.Y + bounds.Height + yMin, p.X); - d.Rotation = 90; - } - ); - - var str = "spoopy text be like shakin"; - if (PerformanceCounter.LifetimeFrames % 10 == 0 || !_pos.Any()) + context.DrawString( + "This text should be wavy!", + new Vector2(64), + (d, _, i, p) => { - _pos.Clear(); - _floats.Clear(); + var offsetY = 3 * MathF.Sin(_angle + (i * 4)); + d.Position = p + new Vector2(0, offsetY); + } + ); + + context.DrawString( + "This text should be circley!", + new Vector2(200), + (d, _, i, _) => + { + // this example uses Bezier nuget library + // it's excellent for geometry calculations. + // + // also thanks to using .NET's System.Numerics + // types, interop between different libraries + // and Chroma is easy af. + var circle = new Circle(160); + var pointOnCircle = circle.Position((i * 2 + _angle) / 100); + var offsetY = 3 * MathF.Sin(_angle + (i * 4)); + pointOnCircle.Y += offsetY; + + d.Position = pointOnCircle + new Vector2(300); + d.Rotation = _angle * 10; + d.Color = _colors[i % _colors.Count]; + } + ); + + context.DrawString( + "This text should be rotated 90 degrees right.", + new Vector2(120, 250), + (d, c, i, p) => + { + var offsets = TrueTypeFont.Default.GetRenderOffsets(c); + var bounds = TrueTypeFont.Default.GetGlyphBounds(c); + TrueTypeFont.Default.GetGlyphControlBox( + c, + out _, + out _, + out var yMin, + out _ + ); + + d.Position = new(p.Y - offsets.Y + bounds.Height + yMin, p.X); + d.Rotation = 90; + } + ); + + var str = "spoopy text be like shakin"; + if (PerformanceCounter.LifetimeFrames % 10 == 0 || !_pos.Any()) + { + _pos.Clear(); + _floats.Clear(); - for (var i = 0; i < str.Length; i++) - { - _floats.Add(_random.Next(-20, 20)); - _pos.Add(new Vector2(_random.Next(-2, 2), _random.Next(-2, 2))); - } + for (var i = 0; i < str.Length; i++) + { + _floats.Add(_random.Next(-20, 20)); + _pos.Add(new Vector2(_random.Next(-2, 2), _random.Next(-2, 2))); } + } - context.DrawString( - str, - new Vector2(300, 340), - (d, c, i, p) => - { - var bounds = TrueTypeFont.Default.GetGlyphBounds(c); + context.DrawString( + str, + new Vector2(300, 340), + (d, c, i, p) => + { + var bounds = TrueTypeFont.Default.GetGlyphBounds(c); - var origin = new Vector2(bounds.Width / 2f, bounds.Height / 2f); + var origin = new Vector2(bounds.Width / 2f, bounds.Height / 2f); - d.Position = p + _pos[i] + origin; - d.Rotation = _floats[i]; - d.Origin = origin; - } - ); - - var rect = new Rectangle(200, 200, 240, TrueTypeFont.Default.Height); - context.Rectangle(ShapeMode.Fill, rect, Color.Red); - - var text = "this should be centered"; - var measure = TrueTypeFont.Default.Measure(text); - var targetPos = new Vector2( - rect.X + (rect.Width / 2) - measure.Width / 2, - rect.Y + (rect.Height / 2) - measure.Height / 2 - ); - context.DrawString(text, targetPos); - } + d.Position = p + _pos[i] + origin; + d.Rotation = _floats[i]; + d.Origin = origin; + } + ); + + var rect = new Rectangle(200, 200, 240, TrueTypeFont.Default.Height); + context.Rectangle(ShapeMode.Fill, rect, Color.Red); + + var text = "this should be centered"; + var measure = TrueTypeFont.Default.Measure(text); + var targetPos = new Vector2( + rect.X + (rect.Width / 2) - measure.Width / 2, + rect.Y + (rect.Height / 2) - measure.Height / 2 + ); + context.DrawString(text, targetPos); } } \ No newline at end of file diff --git a/Chroma.Examples/GlyphTransforms/Program.cs b/Chroma.Examples/GlyphTransforms/Program.cs index b7ed4709..4048d2fb 100644 --- a/Chroma.Examples/GlyphTransforms/Program.cs +++ b/Chroma.Examples/GlyphTransforms/Program.cs @@ -1,3 +1,4 @@ using GlyphTransforms; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/InstancedSoundPlayback/GameCore.cs b/Chroma.Examples/InstancedSoundPlayback/GameCore.cs index 12ce21c0..a68ba287 100644 --- a/Chroma.Examples/InstancedSoundPlayback/GameCore.cs +++ b/Chroma.Examples/InstancedSoundPlayback/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace InstancedSoundPlayback; + +using System; using System.IO; using Chroma; using Chroma.Audio; @@ -7,53 +9,50 @@ using Chroma.Graphics; using Chroma.Input; -namespace InstancedSoundPlayback +public class GameCore : Game { - public class GameCore : Game - { - private InstancedSound _instancedSound; + private InstancedSound _instancedSound; - internal static AudioOutput AudioOutput { get; set; } + internal static AudioOutput AudioOutput { get; set; } - public GameCore() - : base(new(false, false)) - { - AudioOutput = Audio.Output; - } + public GameCore() + : base(new(false, false)) + { + AudioOutput = Audio.Output; + } - protected override IContentProvider InitializeContentPipeline() - { - var pipeline = new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); + protected override IContentProvider InitializeContentPipeline() + { + var pipeline = new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); - pipeline.RegisterImporter((path, _) => new InstancedSound(path)); + pipeline.RegisterImporter((path, _) => new InstancedSound(path)); - return pipeline; - } + return pipeline; + } - protected override void Initialize(IContentProvider content) - { - _instancedSound = content.Load("Sounds/doomsg.wav"); - } + protected override void Initialize(IContentProvider content) + { + _instancedSound = content.Load("Sounds/doomsg.wav"); + } - protected override void Update(float delta) - { - InstancedSound.Update(); - } + protected override void Update(float delta) + { + InstancedSound.Update(); + } - protected override void Draw(RenderContext context) - { - context.DrawString( - "Press and/or hold any key to play a new instance of the same sound.\n" + - $"{InstancedSound.LiveInstanceCount} live instance(s).", - 8, 8 - ); - } + protected override void Draw(RenderContext context) + { + context.DrawString( + "Press and/or hold any key to play a new instance of the same sound.\n" + + $"{InstancedSound.LiveInstanceCount} live instance(s).", + 8, 8 + ); + } - protected override void KeyPressed(KeyEventArgs e) - { - _instancedSound.PlayInstance(); - } + protected override void KeyPressed(KeyEventArgs e) + { + _instancedSound.PlayInstance(); } } \ No newline at end of file diff --git a/Chroma.Examples/InstancedSoundPlayback/InstancedSound.cs b/Chroma.Examples/InstancedSoundPlayback/InstancedSound.cs index 402ce967..c0217dad 100644 --- a/Chroma.Examples/InstancedSoundPlayback/InstancedSound.cs +++ b/Chroma.Examples/InstancedSoundPlayback/InstancedSound.cs @@ -1,3 +1,5 @@ +namespace InstancedSoundPlayback; + using System.Collections.Generic; using System.IO; using System.Linq; @@ -5,70 +7,67 @@ using Chroma.Audio.Sources; using Chroma.MemoryManagement; -namespace InstancedSoundPlayback +public class InstancedSound : DisposableResource { - public class InstancedSound : DisposableResource - { - private static Queue _expiredInstances = new(); - private static List _liveInstances = new(); - private Stream _template; + private static Queue _expiredInstances = new(); + private static List _liveInstances = new(); + private Stream _template; - public static int LiveInstanceCount => _liveInstances.Count; + public static int LiveInstanceCount => _liveInstances.Count; - public InstancedSound(string filePath) - : this(new FileStream(filePath, FileMode.Open)) - { - } + public InstancedSound(string filePath) + : this(new FileStream(filePath, FileMode.Open)) + { + } - public InstancedSound(Stream stream) - { - GameCore.AudioOutput.AudioSourceFinished += OnAudioSourceFinished; - _template = stream; - } + public InstancedSound(Stream stream) + { + GameCore.AudioOutput.AudioSourceFinished += OnAudioSourceFinished; + _template = stream; + } - public static void Update() + public static void Update() + { + while (_expiredInstances.Any()) { - while (_expiredInstances.Any()) - { - var instance = _expiredInstances.Dequeue(); + var instance = _expiredInstances.Dequeue(); - if (_liveInstances.Remove(instance)) - instance.Dispose(); - } + if (_liveInstances.Remove(instance)) + instance.Dispose(); } + } - public void PlayInstance() - { - if (_template == null) - return; + public void PlayInstance() + { + if (_template == null) + return; - using (var ms = new MemoryStream()) - { - _template.CopyTo(ms); - _template.Seek(0, SeekOrigin.Begin); + using (var ms = new MemoryStream()) + { + _template.CopyTo(ms); + _template.Seek(0, SeekOrigin.Begin); - var snd = new Sound(ms); - _liveInstances.Add(snd); + var snd = new Sound(ms); + _liveInstances.Add(snd); - snd.Play(); - } + snd.Play(); } + } - protected override void FreeManagedResources() - { - GameCore.AudioOutput.AudioSourceFinished -= OnAudioSourceFinished; - _template.Dispose(); - } + protected override void FreeManagedResources() + { + GameCore.AudioOutput.AudioSourceFinished -= OnAudioSourceFinished; + _template.Dispose(); + } - private void OnAudioSourceFinished(object sender, AudioSourceEventArgs e) - { - if (e.IsLooping) - return; + private void OnAudioSourceFinished(object sender, AudioSourceEventArgs e) + { + if (e.IsLooping) + return; - if (e.Source is Sound snd) - { - _expiredInstances.Enqueue(snd); - } + if (e.Source is Sound snd) + { + _expiredInstances.Enqueue(snd); } } } \ No newline at end of file diff --git a/Chroma.Examples/InstancedSoundPlayback/Program.cs b/Chroma.Examples/InstancedSoundPlayback/Program.cs index 27604177..9abcb549 100644 --- a/Chroma.Examples/InstancedSoundPlayback/Program.cs +++ b/Chroma.Examples/InstancedSoundPlayback/Program.cs @@ -1,3 +1,4 @@ using InstancedSoundPlayback; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/KeyboardInput/GameCore.cs b/Chroma.Examples/KeyboardInput/GameCore.cs index 69cf675d..9696109e 100644 --- a/Chroma.Examples/KeyboardInput/GameCore.cs +++ b/Chroma.Examples/KeyboardInput/GameCore.cs @@ -1,3 +1,5 @@ +namespace KeyboardInput; + using System; using System.IO; using System.Numerics; @@ -6,85 +8,81 @@ using Chroma.ContentManagement.FileSystem; using Chroma.Graphics; using Chroma.Input; -using Color = Chroma.Graphics.Color; -namespace KeyboardInput +public class GameCore : Game { - public class GameCore : Game - { - private KeyCode _lastPressedKeyCode; - private ScanCode _lastPressedScanCode; + private KeyCode _lastPressedKeyCode; + private ScanCode _lastPressedScanCode; - private KeyCode _lastReleasedKeyCode; - private ScanCode _lastReleasedScanCode; + private KeyCode _lastReleasedKeyCode; + private ScanCode _lastReleasedScanCode; - private Vector2 _pos = new(256); - private Vector2 _spd = new(256); - private Texture _burg; + private Vector2 _pos = new(256); + private Vector2 _spd = new(256); + private Texture _burg; - public GameCore() - : base(new(false, false)) - { - } + public GameCore() + : base(new(false, false)) + { + } - protected override IContentProvider InitializeContentPipeline() - { - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); - } + protected override IContentProvider InitializeContentPipeline() + { + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } - protected override void Initialize(IContentProvider content) - { - _burg = content.Load("Textures/burg.png"); - } + protected override void Initialize(IContentProvider content) + { + _burg = content.Load("Textures/burg.png"); + } - protected override void Update(float delta) - { - var vposd = _spd.Y * delta; - var hposd = _spd.X * delta; + protected override void Update(float delta) + { + var vposd = _spd.Y * delta; + var hposd = _spd.X * delta; - if (Keyboard.IsKeyDown(KeyCode.Up)) - _pos.Y -= vposd; - else if (Keyboard.IsKeyDown(KeyCode.Down)) - _pos.Y += vposd; + if (Keyboard.IsKeyDown(KeyCode.Up)) + _pos.Y -= vposd; + else if (Keyboard.IsKeyDown(KeyCode.Down)) + _pos.Y += vposd; - if (Keyboard.IsKeyDown(KeyCode.Left)) - _pos.X -= hposd; - else if (Keyboard.IsKeyDown(KeyCode.Right)) - _pos.X += hposd; - } + if (Keyboard.IsKeyDown(KeyCode.Left)) + _pos.X -= hposd; + else if (Keyboard.IsKeyDown(KeyCode.Right)) + _pos.X += hposd; + } - protected override void Draw(RenderContext context) - { - context.DrawTexture( - _burg, - _pos, - new(0.5f) - ); + protected override void Draw(RenderContext context) + { + context.DrawTexture( + _burg, + _pos, + new(0.5f) + ); - context.DrawString( - $"Last pressed key code: {(_lastPressedKeyCode == 0 ? "none" : _lastPressedKeyCode.ToString() + " (SC: " + Keyboard.KeyCodeToScanCode(_lastPressedKeyCode) + ")")}\n" + - $"Last released key code: {(_lastReleasedKeyCode == 0 ? "none" : _lastReleasedKeyCode.ToString() + " (SC: " + Keyboard.KeyCodeToScanCode(_lastReleasedKeyCode) + ")")}\n\n" + - $"Last pressed scan code: {(_lastPressedScanCode == 0 ? "none" : _lastPressedScanCode.ToString() + " (KC: " + Keyboard.ScanCodeToKeyCode(_lastPressedScanCode) + ")")}\n" + - $"Last released scan code: {(_lastReleasedScanCode == 0 ? "none" : _lastReleasedScanCode.ToString() + " (KC: " + Keyboard.ScanCodeToKeyCode(_lastReleasedScanCode) + ")")}\n\n" + - $"Currently active modifiers: {Keyboard.ActiveModifiers.ToString()}\n" + - $"Currently pressed keys: {string.Join(", ", Keyboard.ActiveKeys)}" + - "\n\nUse arrow keys to move the burger around.", - 16, 16, Color.White - ); - } + context.DrawString( + $"Last pressed key code: {(_lastPressedKeyCode == 0 ? "none" : _lastPressedKeyCode.ToString() + " (SC: " + Keyboard.KeyCodeToScanCode(_lastPressedKeyCode) + ")")}\n" + + $"Last released key code: {(_lastReleasedKeyCode == 0 ? "none" : _lastReleasedKeyCode.ToString() + " (SC: " + Keyboard.KeyCodeToScanCode(_lastReleasedKeyCode) + ")")}\n\n" + + $"Last pressed scan code: {(_lastPressedScanCode == 0 ? "none" : _lastPressedScanCode.ToString() + " (KC: " + Keyboard.ScanCodeToKeyCode(_lastPressedScanCode) + ")")}\n" + + $"Last released scan code: {(_lastReleasedScanCode == 0 ? "none" : _lastReleasedScanCode.ToString() + " (KC: " + Keyboard.ScanCodeToKeyCode(_lastReleasedScanCode) + ")")}\n\n" + + $"Currently active modifiers: {Keyboard.ActiveModifiers.ToString()}\n" + + $"Currently pressed keys: {string.Join(", ", Keyboard.ActiveKeys)}" + + "\n\nUse arrow keys to move the burger around.", + 16, 16, Color.White + ); + } - protected override void KeyPressed(KeyEventArgs e) - { - _lastPressedKeyCode = e.KeyCode; - _lastPressedScanCode = e.ScanCode; - } + protected override void KeyPressed(KeyEventArgs e) + { + _lastPressedKeyCode = e.KeyCode; + _lastPressedScanCode = e.ScanCode; + } - protected override void KeyReleased(KeyEventArgs e) - { - _lastReleasedKeyCode = e.KeyCode; - _lastReleasedScanCode = e.ScanCode; - } + protected override void KeyReleased(KeyEventArgs e) + { + _lastReleasedKeyCode = e.KeyCode; + _lastReleasedScanCode = e.ScanCode; } } \ No newline at end of file diff --git a/Chroma.Examples/KeyboardInput/Program.cs b/Chroma.Examples/KeyboardInput/Program.cs index 9d6e800e..1631b267 100644 --- a/Chroma.Examples/KeyboardInput/Program.cs +++ b/Chroma.Examples/KeyboardInput/Program.cs @@ -1,3 +1,4 @@ using KeyboardInput; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/LerpingCameras/GameCore.cs b/Chroma.Examples/LerpingCameras/GameCore.cs index 0d3bb9a5..cd7d3d79 100644 --- a/Chroma.Examples/LerpingCameras/GameCore.cs +++ b/Chroma.Examples/LerpingCameras/GameCore.cs @@ -1,56 +1,55 @@ +namespace LerpingCameras; + using System.Numerics; using Chroma; using Chroma.ContentManagement; using Chroma.Graphics; using Chroma.Input; -namespace LerpingCameras +public class GameCore : Game { - public class GameCore : Game - { - private LerpCamera _lerpCamera; + private LerpCamera _lerpCamera; - public GameCore() - : base(new(true, false)) - { - Graphics.VerticalSyncMode = VerticalSyncMode.None; - } + public GameCore() + : base(new(true, false)) + { + Graphics.VerticalSyncMode = VerticalSyncMode.None; + } - protected override void Initialize(IContentProvider content) - { - _lerpCamera = new LerpCamera(Vector2.Zero); - } + protected override void Initialize(IContentProvider content) + { + _lerpCamera = new LerpCamera(Vector2.Zero); + } - protected override void Draw(RenderContext context) + protected override void Draw(RenderContext context) + { + context.WithCamera(_lerpCamera, (ctx, tgt) => { - context.WithCamera(_lerpCamera, (ctx, tgt) => - { - base.Draw(ctx); - ctx.Pixel(Window.Center, Color.Red); - }); + base.Draw(ctx); + ctx.Pixel(Window.Center, Color.Red); + }); - context.DrawString( - (_lerpCamera.EndTime - _lerpCamera.StartTime).TotalMilliseconds.ToString("F0"), - Window.Center, - Color.Red - ); - } + context.DrawString( + (_lerpCamera.EndTime - _lerpCamera.StartTime).TotalMilliseconds.ToString("F0"), + Window.Center, + Color.Red + ); + } - protected override void Update(float delta) - { - _lerpCamera.Update(delta); - base.Update(delta); - } + protected override void Update(float delta) + { + _lerpCamera.Update(delta); + base.Update(delta); + } - protected override void KeyPressed(KeyEventArgs e) + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.Space) { - if (e.KeyCode == KeyCode.Space) - { - _lerpCamera.StartMoving( - Window.Center, - 3.5f - ); - } + _lerpCamera.StartMoving( + Window.Center, + 3.5f + ); } } } \ No newline at end of file diff --git a/Chroma.Examples/LerpingCameras/LerpCamera.cs b/Chroma.Examples/LerpingCameras/LerpCamera.cs index 39fda857..7c1b05e0 100644 --- a/Chroma.Examples/LerpingCameras/LerpCamera.cs +++ b/Chroma.Examples/LerpingCameras/LerpCamera.cs @@ -1,61 +1,60 @@ +namespace LerpingCameras; + using System; using System.Numerics; using Chroma.Graphics; -namespace LerpingCameras +public class LerpCamera : Camera { - public class LerpCamera : Camera - { - private float _time; - private float _secondsToReachTarget; + private float _time; + private float _secondsToReachTarget; - public bool IsMoving { get; private set; } + public bool IsMoving { get; private set; } - public Vector3 StartPosition { get; private set; } - public Vector3 EndPosition { get; private set; } + public Vector3 StartPosition { get; private set; } + public Vector3 EndPosition { get; private set; } - public DateTime StartTime { get; private set; } - public DateTime EndTime { get; private set; } + public DateTime StartTime { get; private set; } + public DateTime EndTime { get; private set; } - public LerpCamera(Vector2 startPosition) - { - Zoom = Vector2.One; - Position = new(startPosition.X, startPosition.Y, 0); - } + public LerpCamera(Vector2 startPosition) + { + Zoom = Vector2.One; + Position = new(startPosition.X, startPosition.Y, 0); + } - public void Update(float delta) + public void Update(float delta) + { + if (IsMoving) { - if (IsMoving) - { - _time += delta / _secondsToReachTarget; + _time += delta / _secondsToReachTarget; - Position = Vector3.Lerp( - StartPosition, - EndPosition, - _time - ); - - Position = Vector3.Clamp(Position, StartPosition, EndPosition); - EndTime = DateTime.Now; - - if (Vector3.Distance(Position, EndPosition) <= 0.5f) - IsMoving = false; - } + Position = Vector3.Lerp( + StartPosition, + EndPosition, + _time + ); + + Position = Vector3.Clamp(Position, StartPosition, EndPosition); + EndTime = DateTime.Now; + + if (Vector3.Distance(Position, EndPosition) <= 0.5f) + IsMoving = false; } + } - public void StartMoving(Vector2 endPosition, float secondsToReachTarget) - { - if (IsMoving) - return; + public void StartMoving(Vector2 endPosition, float secondsToReachTarget) + { + if (IsMoving) + return; - StartPosition = Position; - EndPosition = new(endPosition.X, endPosition.Y, 0); + StartPosition = Position; + EndPosition = new(endPosition.X, endPosition.Y, 0); - _time = 0; - _secondsToReachTarget = secondsToReachTarget; + _time = 0; + _secondsToReachTarget = secondsToReachTarget; - IsMoving = true; - StartTime = DateTime.Now; - } + IsMoving = true; + StartTime = DateTime.Now; } } \ No newline at end of file diff --git a/Chroma.Examples/LerpingCameras/Program.cs b/Chroma.Examples/LerpingCameras/Program.cs index d7f53913..4dea8fcd 100644 --- a/Chroma.Examples/LerpingCameras/Program.cs +++ b/Chroma.Examples/LerpingCameras/Program.cs @@ -1,2 +1,4 @@ using LerpingCameras; -new GameCore().Run(); \ No newline at end of file + +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/MusicAndSounds/GameCore.cs b/Chroma.Examples/MusicAndSounds/GameCore.cs index 920ee61b..4cf756e9 100644 --- a/Chroma.Examples/MusicAndSounds/GameCore.cs +++ b/Chroma.Examples/MusicAndSounds/GameCore.cs @@ -1,11 +1,11 @@ -using System; +namespace MusicAndSounds; + +using System; using System.Drawing; using System.IO; using System.Linq; using System.Numerics; using System.Runtime.InteropServices; -using System.Threading; -using System.Threading.Tasks; using Chroma; using Chroma.Audio; using Chroma.Audio.Sources; @@ -14,244 +14,242 @@ using Chroma.Diagnostics.Logging; using Chroma.Graphics; using Chroma.Input; +using FftSharp; using Color = Chroma.Graphics.Color; -namespace MusicAndSounds +public class GameCore : Game { - public class GameCore : Game - { - private static readonly Log _log = LogManager.GetForCurrentAssembly(); - private IContentProvider _content; + private static readonly Log _log = LogManager.GetForCurrentAssembly(); + private IContentProvider _content; - private Sound _doomShotgun; - private Music _elysiumMod; - private Waveform _waveform; + private Sound _doomShotgun; + private Music _elysiumMod; + private Waveform _waveform; - private double[] _frequencies; + private double[] _frequencies; - public GameCore() : base(new(false, false)) + public GameCore() : base(new(false, false)) + { + Window.Mode.SetWindowed(new Size(800, 600)); + Audio.DeviceConnected += (_, e) => { - Window.Mode.SetWindowed(new Size(800, 600)); - Audio.DeviceConnected += (_, e) => - { - _log.Info( - $"Connected {(e.Device.IsCapture ? "input" : "output")} device {e.Device.Index}: '{e.Device.Name}'."); - }; - - Audio.DeviceDisconnected += (_, e) => - { - _log.Info($"Disconnected: {e.Device.Index}"); - }; + _log.Info( + $"Connected {(e.Device.IsCapture ? "input" : "output")} device {e.Device.Index}: '{e.Device.Name}'."); + }; - foreach (var e in Audio.Output.Decoders) - { - _log.Info($"Decoder: {string.Join(',', e.SupportedFormats)}"); - } - - FixedTimeStepTarget = 75; - } + Audio.DeviceDisconnected += (_, e) => + { + _log.Info($"Disconnected: {e.Device.Index}"); + }; - protected override IContentProvider InitializeContentPipeline() + foreach (var e in Audio.Output.Decoders) { - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); + _log.Info($"Decoder: {string.Join(',', e.SupportedFormats)}"); } - protected override void Initialize(IContentProvider content) - { - _content ??= content; + FixedTimeStepTarget = 75; + } + + protected override IContentProvider InitializeContentPipeline() + { + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } + + protected override void Initialize(IContentProvider content) + { + _content ??= content; - _doomShotgun = content.Load("Sounds/doomsg.wav"); - _elysiumMod = content.Load("Music/elysium.mod"); + _doomShotgun = content.Load("Sounds/doomsg.wav"); + _elysiumMod = content.Load("Music/elysium.mod"); - var time = 0; - _waveform = new Waveform( - new AudioFormat(SampleFormat.F32), - (s, e) => - { - var floats = MemoryMarshal.Cast(s); + var time = 0; + _waveform = new Waveform( + new AudioFormat(SampleFormat.F32), + (s, e) => + { + var floats = MemoryMarshal.Cast(s); - var freq = 554.365f; - var amp = 0.6f; - var angle = MathF.PI * 2 * freq / _waveform.Frequency; + var freq = 554.365f; + var amp = 0.6f; + var angle = MathF.PI * 2 * freq / _waveform.Frequency; - for (var i = 0; i < floats.Length; i++) - { - floats[i] = amp * MathF.Sin(angle * time++); - } - }, ChannelMode.Mono - ); + for (var i = 0; i < floats.Length; i++) + { + floats[i] = amp * MathF.Sin(angle * time++); + } + }, ChannelMode.Mono + ); - RenderSettings.LineThickness = 1; - } - - protected override void Draw(RenderContext context) - { - context.DrawString( - $"Use to resume/pause the groovy music ({_elysiumMod.Status}) [{_elysiumMod.Position:F3}s / {_elysiumMod.Duration:F3}s].\n" + - "Use to stop the groovy music.\n" + - "Use Ctrl+F1 to skip 10 seconds of groovy music.\n" + - $"Use to play the shotgun sound. ({_doomShotgun.Status}) [{_doomShotgun.Position:F3}s / {_doomShotgun.Duration:F3}s]\n" + - $"Use / to tweak the shotgun sound volume -/+ ({_doomShotgun.Volume}).\n" + - $"Use / to tweak master volume -/+ ({Audio.Output.MasterVolume}).\n" + - $"Use to play/pause the sine waveform.", - new Vector2(8) - ); - - if (_frequencies == null) - return; - - var upBeat = 128 * (_frequencies[0] + _frequencies[1] + _frequencies[2] + _frequencies[3]); - var upBeat2 = 128 * (_frequencies[4] + _frequencies[5] + _frequencies[6] + _frequencies[7]); - var upBeat3 = 128 * (_frequencies[8] + _frequencies[9] + _frequencies[10] + _frequencies[11]); - - context.Rectangle( - ShapeMode.Fill, - Window.Center - new Vector2(0, (float)upBeat), - new Size(32, 32), - new Color(0, (byte)(upBeat % 255), 200) - ); + RenderSettings.LineThickness = 1; + } - context.Rectangle( - ShapeMode.Fill, - Window.Center - new Vector2(32, 0 + (float)upBeat2), - new Size(32, 32), - new Color(0, 200, (byte)(upBeat2 % 255)) - ); + protected override void Draw(RenderContext context) + { + context.DrawString( + $"Use to resume/pause the groovy music ({_elysiumMod.Status}) [{_elysiumMod.Position:F3}s / {_elysiumMod.Duration:F3}s].\n" + + "Use to stop the groovy music.\n" + + "Use Ctrl+F1 to skip 10 seconds of groovy music.\n" + + $"Use to play the shotgun sound. ({_doomShotgun.Status}) [{_doomShotgun.Position:F3}s / {_doomShotgun.Duration:F3}s]\n" + + $"Use / to tweak the shotgun sound volume -/+ ({_doomShotgun.Volume}).\n" + + $"Use / to tweak master volume -/+ ({Audio.Output.MasterVolume}).\n" + + $"Use to play/pause the sine waveform.", + new Vector2(8) + ); + + if (_frequencies == null) + return; + + var upBeat = 128 * (_frequencies[0] + _frequencies[1] + _frequencies[2] + _frequencies[3]); + var upBeat2 = 128 * (_frequencies[4] + _frequencies[5] + _frequencies[6] + _frequencies[7]); + var upBeat3 = 128 * (_frequencies[8] + _frequencies[9] + _frequencies[10] + _frequencies[11]); + + context.Rectangle( + ShapeMode.Fill, + Window.Center - new Vector2(0, (float)upBeat), + new Size(32, 32), + new Color(0, (byte)(upBeat % 255), 200) + ); + + context.Rectangle( + ShapeMode.Fill, + Window.Center - new Vector2(32, 0 + (float)upBeat2), + new Size(32, 32), + new Color(0, 200, (byte)(upBeat2 % 255)) + ); - context.Rectangle( - ShapeMode.Fill, - Window.Center - new Vector2(64, 0 + (float)upBeat3), - new Size(32, 32), - new Color(200, 0, (byte)(upBeat3 % 255)) + context.Rectangle( + ShapeMode.Fill, + Window.Center - new Vector2(64, 0 + (float)upBeat3), + new Size(32, 32), + new Color(200, 0, (byte)(upBeat3 % 255)) + ); + + for (var i = 0; i < _frequencies.Length / 4; i ++) + { + context.Line( + new Vector2( + (2 + i) * (2 + RenderSettings.LineThickness - 1), + Window.Height + ), + new Vector2( + (2 + i) * (2 + RenderSettings.LineThickness - 1), + Window.Height - 1 - (float)_frequencies[i] * 768 + ), + new Color( + i / ((float)_frequencies.Length / 4), + 1f - i / ((float)_frequencies.Length / 4), + 1f, + 1f + ) ); - - for (var i = 0; i < _frequencies.Length / 4; i ++) - { - context.Line( - new Vector2( - (2 + i) * (2 + RenderSettings.LineThickness - 1), - Window.Height - ), - new Vector2( - (2 + i) * (2 + RenderSettings.LineThickness - 1), - Window.Height - 1 - (float)_frequencies[i] * 768 - ), - new Color( - i / ((float)_frequencies.Length / 4), - 1f - i / ((float)_frequencies.Length / 4), - 1f, - 1f - ) - ); - } } + } - protected override void FixedUpdate(float delta) - { - DoFFT(_elysiumMod.InBuffer, _elysiumMod.Format); - } + protected override void FixedUpdate(float delta) + { + DoFFT(_elysiumMod.InBuffer, _elysiumMod.Format); + } - protected override void KeyPressed(KeyEventArgs e) + protected override void KeyPressed(KeyEventArgs e) + { + switch (e.KeyCode) { - switch (e.KeyCode) + case KeyCode.F1: { - case KeyCode.F1: - { - var skip = 10; + var skip = 10; - if (e.Modifiers.HasFlag(KeyModifiers.LeftControl)) - { - if (e.Modifiers.HasFlag(KeyModifiers.LeftShift)) - skip *= -1; + if (e.Modifiers.HasFlag(KeyModifiers.LeftControl)) + { + if (e.Modifiers.HasFlag(KeyModifiers.LeftShift)) + skip *= -1; - _elysiumMod.Seek(skip, SeekOrigin.Current); - } + _elysiumMod.Seek(skip, SeekOrigin.Current); + } + else + { + if (_elysiumMod.IsPlaying) + _elysiumMod.Pause(); else - { - if (_elysiumMod.IsPlaying) - _elysiumMod.Pause(); - else - _elysiumMod.Play(); - } - - break; + _elysiumMod.Play(); } - case KeyCode.F2: - _elysiumMod.Stop(); - break; + break; + } - case KeyCode.Space: - _doomShotgun.Play(); - break; + case KeyCode.F2: + _elysiumMod.Stop(); + break; - case KeyCode.F3: - _doomShotgun.Volume -= 0.1f; - break; + case KeyCode.Space: + _doomShotgun.Play(); + break; - case KeyCode.F4: - _doomShotgun.Volume += 0.1f; - break; + case KeyCode.F3: + _doomShotgun.Volume -= 0.1f; + break; - case KeyCode.F5: - Audio.Output.MasterVolume -= 0.1f; - break; + case KeyCode.F4: + _doomShotgun.Volume += 0.1f; + break; - case KeyCode.F6: - Audio.Output.MasterVolume += 0.1f; - break; + case KeyCode.F5: + Audio.Output.MasterVolume -= 0.1f; + break; - case KeyCode.F7: - if (_waveform.IsPlaying) - _waveform.Pause(); - else - _waveform.Play(); - break; + case KeyCode.F6: + Audio.Output.MasterVolume += 0.1f; + break; + + case KeyCode.F7: + if (_waveform.IsPlaying) + _waveform.Pause(); + else + _waveform.Play(); + break; - case KeyCode.F8: - _waveform.Dispose(); - _doomShotgun.Dispose(); - _elysiumMod.Dispose(); + case KeyCode.F8: + _waveform.Dispose(); + _doomShotgun.Dispose(); + _elysiumMod.Dispose(); - Audio.Output.Close(); - Audio.Output.Open(); + Audio.Output.Close(); + Audio.Output.Open(); - Initialize(_content); + Initialize(_content); - break; + break; - case KeyCode.F9: - _waveform.Dispose(); - break; - } + case KeyCode.F9: + _waveform.Dispose(); + break; } + } - private void DoFFT(Span audioBufferData, AudioFormat format) - { - float[] chunk; + private void DoFFT(Span audioBufferData, AudioFormat format) + { + float[] chunk; - if (format.SampleFormat != SampleFormat.F32) - { - var shortSamples = MemoryMarshal.Cast(audioBufferData); + if (format.SampleFormat != SampleFormat.F32) + { + var shortSamples = MemoryMarshal.Cast(audioBufferData); - chunk = new float[2048]; + chunk = new float[2048]; - for (var i = 0; i < shortSamples.Length; i++) - { - if (i >= chunk.Length) - break; - - chunk[i] = shortSamples[i] / 32767f; - } - } - else + for (var i = 0; i < shortSamples.Length; i++) { - chunk = MemoryMarshal.Cast(audioBufferData).ToArray(); - } + if (i >= chunk.Length) + break; - _frequencies = FftSharp.Transform.FFTmagnitude(chunk.Select(x => (double)x).ToArray()); + chunk[i] = shortSamples[i] / 32767f; + } + } + else + { + chunk = MemoryMarshal.Cast(audioBufferData).ToArray(); } + + _frequencies = Transform.FFTmagnitude(chunk.Select(x => (double)x).ToArray()); } } \ No newline at end of file diff --git a/Chroma.Examples/MusicAndSounds/Program.cs b/Chroma.Examples/MusicAndSounds/Program.cs index dfdc80ad..a0dd92dd 100644 --- a/Chroma.Examples/MusicAndSounds/Program.cs +++ b/Chroma.Examples/MusicAndSounds/Program.cs @@ -1,3 +1,4 @@ using MusicAndSounds; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/ParticleSystems/GameCore.cs b/Chroma.Examples/ParticleSystems/GameCore.cs index c4159e4c..6e208378 100644 --- a/Chroma.Examples/ParticleSystems/GameCore.cs +++ b/Chroma.Examples/ParticleSystems/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace ParticleSystems; + +using System; using System.IO; using System.Numerics; using Chroma; @@ -9,87 +11,84 @@ using Chroma.Graphics.Particles; using Chroma.Input; -namespace ParticleSystems +public class GameCore : Game { - public class GameCore : Game + private Texture _particle; + private RenderTarget _target; + private ParticleEmitter _emitter; + + public GameCore() : base(new(false, false)) { - private Texture _particle; - private RenderTarget _target; - private ParticleEmitter _emitter; + } - public GameCore() : base(new(false, false)) - { - } + protected override IContentProvider InitializeContentPipeline() + { + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } - protected override IContentProvider InitializeContentPipeline() - { - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); - } - - // Please see Chroma/Graphics/Particles/StateInitializers/RandomizedStateInitializer - // for how to implement a working particle state initializer. - // - // You can assign a new particle state initializer while instantiating - // the particle emitter. - // - protected override void Initialize(IContentProvider content) - { - _target = new RenderTarget(Window.Width, Window.Height); + // Please see Chroma/Graphics/Particles/StateInitializers/RandomizedStateInitializer + // for how to implement a working particle state initializer. + // + // You can assign a new particle state initializer while instantiating + // the particle emitter. + // + protected override void Initialize(IContentProvider content) + { + _target = new RenderTarget(Window.Width, Window.Height); - _particle = content.Load("Textures/pentagram.png"); - _particle.FilteringMode = TextureFilteringMode.NearestNeighbor; + _particle = content.Load("Textures/pentagram.png"); + _particle.FilteringMode = TextureFilteringMode.NearestNeighbor; - _emitter = new ParticleEmitter(_particle) - { - Density = 300 - }; + _emitter = new ParticleEmitter(_particle) + { + Density = 300 + }; - _emitter.RegisterIntegrator(BuiltInParticleStateIntegrators.ScaleDown); - _emitter.RegisterIntegrator(BuiltInParticleStateIntegrators.FadeOut); - _emitter.RegisterIntegrator(CustomStateIntegrator); - } + _emitter.RegisterIntegrator(BuiltInParticleStateIntegrators.ScaleDown); + _emitter.RegisterIntegrator(BuiltInParticleStateIntegrators.FadeOut); + _emitter.RegisterIntegrator(CustomStateIntegrator); + } - protected override void Draw(RenderContext context) - { - context.RenderTo(_target, (ctx, tgt) => - { - ctx.Clear(Color.Black); - _emitter.Draw(context); - }); - - context.DrawTexture(_target, Vector2.Zero, Vector2.One, Vector2.Zero, 0); - - context.DrawString( - "Move mouse around the window to change particle spawn position.\n" + - "Press to activate the particle emitter.", - new Vector2(8) - ); - } - - protected override void Update(float delta) + protected override void Draw(RenderContext context) + { + context.RenderTo(_target, (ctx, tgt) => { - Window.Title = $"{PerformanceCounter.FPS} | {_emitter.Particles.Count} particles shown"; + ctx.Clear(Color.Black); + _emitter.Draw(context); + }); - if (Mouse.IsButtonDown(MouseButton.Left)) - _emitter.Emit(Mouse.GetPosition(), 10); + context.DrawTexture(_target, Vector2.Zero, Vector2.One, Vector2.Zero, 0); - _emitter.Update(delta); - } + context.DrawString( + "Move mouse around the window to change particle spawn position.\n" + + "Press to activate the particle emitter.", + new Vector2(8) + ); + } - private void CustomStateIntegrator(Particle part, float delta) - { - part.Origin = part.Owner.Texture.Center; + protected override void Update(float delta) + { + Window.Title = $"{PerformanceCounter.FPS} | {_emitter.Particles.Count} particles shown"; + + if (Mouse.IsButtonDown(MouseButton.Left)) + _emitter.Emit(Mouse.GetPosition(), 10); + + _emitter.Update(delta); + } + + private void CustomStateIntegrator(Particle part, float delta) + { + part.Origin = part.Owner.Texture.Center; - part.Position.X += part.Velocity.X * 5 * delta; - part.Position.Y += part.Velocity.Y * delta; + part.Position.X += part.Velocity.X * 5 * delta; + part.Position.Y += part.Velocity.Y * delta; - part.Rotation += part.Velocity.X - part.Velocity.Y * delta; + part.Rotation += part.Velocity.X - part.Velocity.Y * delta; - part.Velocity.X *= (float)part.TTL / part.InitialTTL; - if (part.Velocity.Y < 0) - part.Velocity.Y *= -1; - } + part.Velocity.X *= (float)part.TTL / part.InitialTTL; + if (part.Velocity.Y < 0) + part.Velocity.Y *= -1; } -} +} \ No newline at end of file diff --git a/Chroma.Examples/ParticleSystems/Program.cs b/Chroma.Examples/ParticleSystems/Program.cs index 0ede1359..867dc3dd 100644 --- a/Chroma.Examples/ParticleSystems/Program.cs +++ b/Chroma.Examples/ParticleSystems/Program.cs @@ -1,3 +1,4 @@ using ParticleSystems; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/PixelShaders/GameCore.cs b/Chroma.Examples/PixelShaders/GameCore.cs index f299f0ce..4227b1da 100644 --- a/Chroma.Examples/PixelShaders/GameCore.cs +++ b/Chroma.Examples/PixelShaders/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace PixelShaders; + +using System; using System.Drawing; using System.IO; using System.Numerics; @@ -13,124 +15,121 @@ using Chroma.Input; using Color = Chroma.Graphics.Color; -namespace PixelShaders +public class GameCore : Game { - public class GameCore : Game - { - private static readonly Log _log = LogManager.GetForCurrentAssembly(); + private static readonly Log _log = LogManager.GetForCurrentAssembly(); - private RenderTarget _target; - private Effect _tintEffect; - private Texture _burger; - private Texture _overlay; + private RenderTarget _target; + private Effect _tintEffect; + private Texture _burger; + private Texture _overlay; - private bool _showOverlay = true; - private bool _showEdge = true; - private bool _showTweak = true; + private bool _showOverlay = true; + private bool _showEdge = true; + private bool _showTweak = true; - private float _rotation; + private float _rotation; - private StringBuilder _messageBuilder = new(); + private StringBuilder _messageBuilder = new(); - public GameCore() : base(new(false, false)) - { - _log.Info( - $"GLSL {Shader.MinimumSupportedGlslVersion}-{Shader.MaximumSupportedGlslVersion} supported."); + public GameCore() : base(new(false, false)) + { + _log.Info( + $"GLSL {Shader.MinimumSupportedGlslVersion}-{Shader.MaximumSupportedGlslVersion} supported."); - Window.Mode.SetWindowed(new Size(1024, 600)); - Window.CenterOnScreen(); - } + Window.Mode.SetWindowed(new Size(1024, 600)); + Window.CenterOnScreen(); + } - protected override IContentProvider InitializeContentPipeline() - { - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); - } + protected override IContentProvider InitializeContentPipeline() + { + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } - protected override void Initialize(IContentProvider content) - { - _target = new RenderTarget(Window.Size); - _tintEffect = content.Load("Shaders/tint.frag"); - _burger = content.Load("Textures/burg.png"); - _burger.FilteringMode = TextureFilteringMode.NearestNeighbor; - - _overlay = content.Load("Textures/checkerboard.jpg"); - _overlay.HorizontalWrappingMode = TextureWrappingMode.Mirror; - _overlay.VerticalWrappingMode = TextureWrappingMode.Mirror; - } + protected override void Initialize(IContentProvider content) + { + _target = new RenderTarget(Window.Size); + _tintEffect = content.Load("Shaders/tint.frag"); + _burger = content.Load("Textures/burg.png"); + _burger.FilteringMode = TextureFilteringMode.NearestNeighbor; + + _overlay = content.Load("Textures/checkerboard.jpg"); + _overlay.HorizontalWrappingMode = TextureWrappingMode.Mirror; + _overlay.VerticalWrappingMode = TextureWrappingMode.Mirror; + } - protected override void Update(float delta) - { - _rotation += 50 * delta; - _rotation %= 360; + protected override void Update(float delta) + { + _rotation += 50 * delta; + _rotation %= 360; - Window.Title = $"Chroma Framework - pixel shader example. {PerformanceCounter.FPS} FPS"; + Window.Title = $"Chroma Framework - pixel shader example. {PerformanceCounter.FPS} FPS"; - _messageBuilder.Clear(); - _messageBuilder.Append("Press to toggle sprite edge detection.\n" + - "Press to toggle texture overlay.\n" + - "Press to toggle cursor position-based color modulation for the sprite.\n\n"); + _messageBuilder.Clear(); + _messageBuilder.Append("Press to toggle sprite edge detection.\n" + + "Press to toggle texture overlay.\n" + + "Press to toggle cursor position-based color modulation for the sprite.\n\n"); - if (_showEdge) - _messageBuilder.AppendLine("Edge detection active."); + if (_showEdge) + _messageBuilder.AppendLine("Edge detection active."); - if (_showOverlay) - _messageBuilder.AppendLine("Texture overlay active."); + if (_showOverlay) + _messageBuilder.AppendLine("Texture overlay active."); - if (_showTweak) - _messageBuilder.Append("Cursor position-based color modulation active."); - } + if (_showTweak) + _messageBuilder.Append("Cursor position-based color modulation active."); + } - protected override void Draw(RenderContext context) + protected override void Draw(RenderContext context) + { + context.RenderTo(_target, (ctx, _) => { - context.RenderTo(_target, (ctx, _) => - { - ctx.Clear(Color.Black); - - _tintEffect.Activate(); - _tintEffect.SetUniform("mouse_loc", Mouse.GetPosition() / Window.Width); - _tintEffect.SetUniform("overlay", _overlay, 1); - _tintEffect.SetUniform("border_color", Color.Yellow); - - _tintEffect.SetUniform("show_edge", _showEdge); - _tintEffect.SetUniform("show_overlay", _showOverlay); - _tintEffect.SetUniform("show_tweak", _showTweak); - - ctx.DrawTexture( - _burger, - Window.Center - (_burger.Center / 2), - Vector2.One * 2, - _burger.Center, - _rotation - ); - Shader.Deactivate(); - - ctx.DrawString( - _messageBuilder.ToString(), - new Vector2(8) - ); - }); - - context.DrawTexture(_target, Vector2.Zero, Vector2.One, Vector2.Zero, 0f); - } + ctx.Clear(Color.Black); + + _tintEffect.Activate(); + _tintEffect.SetUniform("mouse_loc", Mouse.GetPosition() / Window.Width); + _tintEffect.SetUniform("overlay", _overlay, 1); + _tintEffect.SetUniform("border_color", Color.Yellow); + + _tintEffect.SetUniform("show_edge", _showEdge); + _tintEffect.SetUniform("show_overlay", _showOverlay); + _tintEffect.SetUniform("show_tweak", _showTweak); + + ctx.DrawTexture( + _burger, + Window.Center - (_burger.Center / 2), + Vector2.One * 2, + _burger.Center, + _rotation + ); + Shader.Deactivate(); - protected override void KeyPressed(KeyEventArgs e) + ctx.DrawString( + _messageBuilder.ToString(), + new Vector2(8) + ); + }); + + context.DrawTexture(_target, Vector2.Zero, Vector2.One, Vector2.Zero, 0f); + } + + protected override void KeyPressed(KeyEventArgs e) + { + switch (e.KeyCode) { - switch (e.KeyCode) - { - case KeyCode.F1: - _showEdge = !_showEdge; - break; - - case KeyCode.F2: - _showOverlay = !_showOverlay; - break; - - case KeyCode.F3: - _showTweak = !_showTweak; - break; - } + case KeyCode.F1: + _showEdge = !_showEdge; + break; + + case KeyCode.F2: + _showOverlay = !_showOverlay; + break; + + case KeyCode.F3: + _showTweak = !_showTweak; + break; } } } \ No newline at end of file diff --git a/Chroma.Examples/PixelShaders/Program.cs b/Chroma.Examples/PixelShaders/Program.cs index d7583951..25fa01bb 100644 --- a/Chroma.Examples/PixelShaders/Program.cs +++ b/Chroma.Examples/PixelShaders/Program.cs @@ -1,3 +1,4 @@ using PixelShaders; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/PixelShaders2/GameCore.cs b/Chroma.Examples/PixelShaders2/GameCore.cs index 4c15e79c..1dd00f9d 100644 --- a/Chroma.Examples/PixelShaders2/GameCore.cs +++ b/Chroma.Examples/PixelShaders2/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace PixelShaders2; + +using System; using System.IO; using System.Linq; using System.Numerics; @@ -12,205 +14,201 @@ using Chroma.Graphics.Accelerated; using Chroma.Input; using FftSharp; -using FftSharp.Windows; -namespace PixelShaders2 +public class GameCore : Game { - public class GameCore : Game + private Effect _effect = null!; + private RenderTarget _target = null!; + private Music _music = null!; + + private double[] _frequencies = new double[2048]; + private double[] _lowFrequencies = new double[0]; + private double[] _midFrequencies = new double[0]; + private double[] _highFrequencies = new double[0]; + + public GameCore() + : base(new(false, false)) { - private Effect _effect = null!; - private RenderTarget _target = null!; - private Music _music = null!; + } - private double[] _frequencies = new double[2048]; - private double[] _lowFrequencies = new double[0]; - private double[] _midFrequencies = new double[0]; - private double[] _highFrequencies = new double[0]; + protected override IContentProvider InitializeContentPipeline() + { + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } - public GameCore() - : base(new(false, false)) - { - } + protected override void Initialize(IContentProvider content) + { + _effect = content.Load("Shaders/glowyrings.frag"); + _music = content.Load("Music/groovy.mp3"); + _music.Filters.Add(FftTunnel); + _music.IsLooping = true; + _music.Play(); - protected override IContentProvider InitializeContentPipeline() - { - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); - } + _target = new RenderTarget(Window.Size); + } - protected override void Initialize(IContentProvider content) - { - _effect = content.Load("Shaders/glowyrings.frag"); - _music = content.Load("Music/groovy.mp3"); - _music.Filters.Add(FftTunnel); - _music.IsLooping = true; - _music.Play(); + protected override void Update(float delta) + { + Window.Title = $"{_music.Position}/{_music.Duration}"; + } - _target = new RenderTarget(Window.Size); + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.Left) + { + _music.Seek(-10, SeekOrigin.Current); } - - protected override void Update(float delta) + else if (e.KeyCode == KeyCode.Right) { - Window.Title = $"{_music.Position}/{_music.Duration}"; + _music.Seek(10, SeekOrigin.Current); } - - protected override void KeyPressed(KeyEventArgs e) + else if (e.KeyCode == KeyCode.Space) { - if (e.KeyCode == KeyCode.Left) + if (_music.Status == PlaybackStatus.Playing) { - _music.Seek(-10, SeekOrigin.Current); + _music.Pause(); } - else if (e.KeyCode == KeyCode.Right) + else { - _music.Seek(10, SeekOrigin.Current); - } - else if (e.KeyCode == KeyCode.Space) - { - if (_music.Status == PlaybackStatus.Playing) - { - _music.Pause(); - } - else - { - _music.Play(); - } + _music.Play(); } } + } - protected override void Draw(RenderContext context) - { - context.RenderTo(_target, (ctx, tgt) => { ctx.Clear(Color.Black); }); + protected override void Draw(RenderContext context) + { + context.RenderTo(_target, (ctx, tgt) => { ctx.Clear(Color.Black); }); - var mp = Mouse.WindowSpacePosition; - var dx = Window.Center.X - mp.X; - var dy = Window.Center.Y - mp.Y; + var mp = Mouse.WindowSpacePosition; + var dx = Window.Center.X - mp.X; + var dy = Window.Center.Y - mp.Y; - _effect.Activate(); + _effect.Activate(); + _effect.SetUniform( + "mouse_pos", + new Vector2(dx / Window.Width, dy / Window.Height) + ); + + if (_lowFrequencies.Any()) + { _effect.SetUniform( - "mouse_pos", - new Vector2(dx / Window.Width, dy / Window.Height) + "low_fft", + (float)_lowFrequencies.Select(Math.Abs).Average() * 1000f ); + } - if (_lowFrequencies.Any()) - { - _effect.SetUniform( - "low_fft", - (float)_lowFrequencies.Select(Math.Abs).Average() * 1000f - ); - } - - if (_midFrequencies.Any()) - { - _effect.SetUniform( - "mid_fft", - (float)_midFrequencies.Select(Math.Abs).Average() * 1000f - ); - } + if (_midFrequencies.Any()) + { + _effect.SetUniform( + "mid_fft", + (float)_midFrequencies.Select(Math.Abs).Average() * 1000f + ); + } - if (_highFrequencies.Any()) - { - _effect.SetUniform( - "high_fft", - (float)_highFrequencies.Select(Math.Abs).Average() * 1000f - ); - } - - context.DrawTexture(_target, Vector2.Zero); - Shader.Deactivate(); + if (_highFrequencies.Any()) + { + _effect.SetUniform( + "high_fft", + (float)_highFrequencies.Select(Math.Abs).Average() * 1000f + ); } - private void FftTunnel(Span audioBufferData, AudioFormat format) + context.DrawTexture(_target, Vector2.Zero); + Shader.Deactivate(); + } + + private void FftTunnel(Span audioBufferData, AudioFormat format) + { + float[] chunk; + + if (format.SampleFormat != SampleFormat.F32) { - float[] chunk; + var shortSamples = MemoryMarshal.Cast(audioBufferData); + + chunk = new float[shortSamples.Length]; - if (format.SampleFormat != SampleFormat.F32) + for (var i = 0; i < shortSamples.Length; i++) { - var shortSamples = MemoryMarshal.Cast(audioBufferData); + chunk[i] = shortSamples[i] / 32767f; + } + } + else + { + chunk = MemoryMarshal.Cast(audioBufferData).ToArray(); + } - chunk = new float[shortSamples.Length]; + var values = FFT.Forward(chunk.Select(x => (double)x).ToArray()); - for (var i = 0; i < shortSamples.Length; i++) - { - chunk[i] = shortSamples[i] / 32767f; - } + lock (_frequencies) + { + if (!_frequencies.Any()) + { + _frequencies = FFT.Magnitude(values); } else { - chunk = MemoryMarshal.Cast(audioBufferData).ToArray(); - } + var freqs = FFT.Magnitude(values); - var values = FFT.Forward(chunk.Select(x => (double)x).ToArray()); - - lock (_frequencies) - { - if (!_frequencies.Any()) - { - _frequencies = FFT.Magnitude(values); - } - else + for (var i = 0; i < _frequencies.Length; i++) { - var freqs = FFT.Magnitude(values); - - for (var i = 0; i < _frequencies.Length; i++) - { - _frequencies[i] += freqs[i / 2]; - _frequencies[i] /= 2; - } + _frequencies[i] += freqs[i / 2]; + _frequencies[i] /= 2; } } + } - lock (_lowFrequencies) + lock (_lowFrequencies) + { + if (!_lowFrequencies.Any()) { - if (!_lowFrequencies.Any()) - { - _lowFrequencies = Filter.BandPass(_frequencies, 44100, 40, 110); - } - else - { - var freqs = Filter.BandPass(_frequencies, 44100, 40, 110); + _lowFrequencies = Filter.BandPass(_frequencies, 44100, 40, 110); + } + else + { + var freqs = Filter.BandPass(_frequencies, 44100, 40, 110); - for (var i = 0; i < _lowFrequencies.Length; i++) - { - _lowFrequencies[i] += freqs[i]; - _lowFrequencies[i] /= 2; - } + for (var i = 0; i < _lowFrequencies.Length; i++) + { + _lowFrequencies[i] += freqs[i]; + _lowFrequencies[i] /= 2; } } + } - lock (_midFrequencies) + lock (_midFrequencies) + { + if (!_midFrequencies.Any()) { - if (!_midFrequencies.Any()) - { - _midFrequencies = Filter.BandPass(_frequencies, 44100, 800, 1000); - } - else - { - var freqs = Filter.BandPass(_frequencies, 44100, 800, 1000); + _midFrequencies = Filter.BandPass(_frequencies, 44100, 800, 1000); + } + else + { + var freqs = Filter.BandPass(_frequencies, 44100, 800, 1000); - for (var i = 0; i < _midFrequencies.Length; i++) - { - _midFrequencies[i] += freqs[i]; - _midFrequencies[i] /= 2; - } + for (var i = 0; i < _midFrequencies.Length; i++) + { + _midFrequencies[i] += freqs[i]; + _midFrequencies[i] /= 2; } } + } - lock (_highFrequencies) + lock (_highFrequencies) + { + if (!_highFrequencies.Any()) { - if (!_highFrequencies.Any()) - { - _highFrequencies = Filter.BandPass(_frequencies, 44100, 1400, 3000); - } - else - { - var freqs = Filter.BandPass(_frequencies, 44100, 1400, 3000); + _highFrequencies = Filter.BandPass(_frequencies, 44100, 1400, 3000); + } + else + { + var freqs = Filter.BandPass(_frequencies, 44100, 1400, 3000); - for (var i = 0; i < _highFrequencies.Length; i++) - { - _highFrequencies[i] += freqs[i]; - _highFrequencies[i] /= 2; - } + for (var i = 0; i < _highFrequencies.Length; i++) + { + _highFrequencies[i] += freqs[i]; + _highFrequencies[i] /= 2; } } } diff --git a/Chroma.Examples/PixelShaders2/Program.cs b/Chroma.Examples/PixelShaders2/Program.cs index 21572cc5..a68debbf 100644 --- a/Chroma.Examples/PixelShaders2/Program.cs +++ b/Chroma.Examples/PixelShaders2/Program.cs @@ -1,3 +1,4 @@ using PixelShaders2; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/Pong/Assets.cs b/Chroma.Examples/Pong/Assets.cs index 39db08a7..d8c5c891 100644 --- a/Chroma.Examples/Pong/Assets.cs +++ b/Chroma.Examples/Pong/Assets.cs @@ -1,31 +1,29 @@ +namespace Pong; + using Chroma.Audio.Sfxr; using Chroma.ContentManagement; using Chroma.Graphics; -using Chroma.Graphics.TextRendering; using Chroma.Graphics.TextRendering.TrueType; -namespace Pong +public static class Assets { - public static class Assets - { - public static Texture Stretchy { get; private set; } - public static TrueTypeFont ScoreFont { get; private set; } + public static Texture Stretchy { get; private set; } + public static TrueTypeFont ScoreFont { get; private set; } - public static SfxrWaveform WallHit { get; private set; } - public static SfxrWaveform PaddleHit { get; private set; } - public static SfxrWaveform OutsidePlayfield { get; private set; } + public static SfxrWaveform WallHit { get; private set; } + public static SfxrWaveform PaddleHit { get; private set; } + public static SfxrWaveform OutsidePlayfield { get; private set; } - public static void Load(IContentProvider content) - { - Stretchy = content.Load("Sprites/stretchy.png"); - ScoreFont = content.Load("Fonts/visitor2.ttf", 120); - ScoreFont.HintingMode = HintingMode.Monochrome; + public static void Load(IContentProvider content) + { + Stretchy = content.Load("Sprites/stretchy.png"); + ScoreFont = content.Load("Fonts/visitor2.ttf", 120); + ScoreFont.HintingMode = HintingMode.Monochrome; - WallHit = content.Load("Sounds/wall.sfxr", ParameterFormat.Binary); - PaddleHit = content.Load("Sounds/paddle.sfxr", ParameterFormat.Binary); + WallHit = content.Load("Sounds/wall.sfxr", ParameterFormat.Binary); + PaddleHit = content.Load("Sounds/paddle.sfxr", ParameterFormat.Binary); - OutsidePlayfield = content.Load("Sounds/outsidePlayfield.sfxr", ParameterFormat.Binary); - OutsidePlayfield.Volume -= 0.3f; - } + OutsidePlayfield = content.Load("Sounds/outsidePlayfield.sfxr", ParameterFormat.Binary); + OutsidePlayfield.Volume -= 0.3f; } } \ No newline at end of file diff --git a/Chroma.Examples/Pong/Ball.cs b/Chroma.Examples/Pong/Ball.cs index 9e06188f..eb14a575 100644 --- a/Chroma.Examples/Pong/Ball.cs +++ b/Chroma.Examples/Pong/Ball.cs @@ -1,111 +1,109 @@ +namespace Pong; + using System; using System.Drawing; using System.Numerics; -using Chroma; using Chroma.Graphics; using Color = Chroma.Graphics.Color; -namespace Pong +public class Ball { - public class Ball - { - private readonly Board _board; - private readonly Random _random; - - public bool CanMove = false; - public RectangleF Rectangle; - public Vector2 Direction = new(1, -1); - public Vector2 Speed = new(200); - public Color Color = Color.Lime; - - public Ball(Board board) - { - _board = board; - _random = new Random(); - - Rectangle = new( - _board.Size.Width / 2f - 12, - _board.Size.Height / 2f - 12, - 24, 24 - ); - } + private readonly Board _board; + private readonly Random _random; - public void Update(float dt) - { - if (CanMove) - { - Rectangle.X += Speed.X * Direction.X * dt; - Rectangle.Y += Speed.Y * Direction.Y * dt; - } - } - - public void Draw(RenderContext context) - { - context.Rectangle( - ShapeMode.Fill, - Rectangle, - Color - ); - } + public bool CanMove = false; + public RectangleF Rectangle; + public Vector2 Direction = new(1, -1); + public Vector2 Speed = new(200); + public Color Color = Color.Lime; - public bool CollidesWithPaddle(Paddle p) - { - return Rectangle.IntersectsWith(p.Rectangle); - } + public Ball(Board board) + { + _board = board; + _random = new Random(); + + Rectangle = new( + _board.Size.Width / 2f - 12, + _board.Size.Height / 2f - 12, + 24, 24 + ); + } - public bool CollidesWithBoardSide() + public void Update(float dt) + { + if (CanMove) { - return Rectangle.Y + Rectangle.Height >= _board.Size.Height - || Rectangle.Y <= 0; + Rectangle.X += Speed.X * Direction.X * dt; + Rectangle.Y += Speed.Y * Direction.Y * dt; } + } - public bool CollidesWithEndOfPlayfield(out bool left) - { - left = Rectangle.X <= 0; + public void Draw(RenderContext context) + { + context.Rectangle( + ShapeMode.Fill, + Rectangle, + Color + ); + } - return Rectangle.X + Rectangle.Width >= _board.Size.Width - || left; - } + public bool CollidesWithPaddle(Paddle p) + { + return Rectangle.IntersectsWith(p.Rectangle); + } - private RectangleF Intersection(RectangleF r1, RectangleF r2) - { - var intersect = new RectangleF( - r1.X, r1.Y, r1.Width, r1.Height - ); + public bool CollidesWithBoardSide() + { + return Rectangle.Y + Rectangle.Height >= _board.Size.Height + || Rectangle.Y <= 0; + } - intersect.Intersect(r2); + public bool CollidesWithEndOfPlayfield(out bool left) + { + left = Rectangle.X <= 0; - return intersect; - } + return Rectangle.X + Rectangle.Width >= _board.Size.Width + || left; + } - public void BounceFromPaddle(Paddle p) - { - var intersection = Intersection(Rectangle, p.Rectangle); + private RectangleF Intersection(RectangleF r1, RectangleF r2) + { + var intersect = new RectangleF( + r1.X, r1.Y, r1.Width, r1.Height + ); - if (Rectangle.X > _board.Size.Width / 2) - { - Rectangle.X -= intersection.Width; - } - else - { - Rectangle.X += intersection.Width; - } + intersect.Intersect(r2); - Direction.X = -Direction.X; + return intersect; + } - Speed.X = _random.Next(150, 300); - Speed.Y = _random.Next(150, 300); - } + public void BounceFromPaddle(Paddle p) + { + var intersection = Intersection(Rectangle, p.Rectangle); - public void BounceFromSide() + if (Rectangle.X > _board.Size.Width / 2) { - Direction.Y = -Direction.Y; + Rectangle.X -= intersection.Width; } - - public void Center() + else { - Rectangle.X = _board.Size.Width / 2f - Rectangle.Width / 2; - Rectangle.Y = _board.Size.Height / 2f - Rectangle.Height / 2; + Rectangle.X += intersection.Width; } + + Direction.X = -Direction.X; + + Speed.X = _random.Next(150, 300); + Speed.Y = _random.Next(150, 300); + } + + public void BounceFromSide() + { + Direction.Y = -Direction.Y; + } + + public void Center() + { + Rectangle.X = _board.Size.Width / 2f - Rectangle.Width / 2; + Rectangle.Y = _board.Size.Height / 2f - Rectangle.Height / 2; } } \ No newline at end of file diff --git a/Chroma.Examples/Pong/Board.cs b/Chroma.Examples/Pong/Board.cs index e46f7cbb..6e4eb571 100644 --- a/Chroma.Examples/Pong/Board.cs +++ b/Chroma.Examples/Pong/Board.cs @@ -1,125 +1,123 @@ +namespace Pong; + using System.Drawing; using System.Numerics; -using Chroma; using Chroma.Graphics; using Chroma.Input; using Color = Chroma.Graphics.Color; -namespace Pong +public class Board { - public class Board + public Size Size { get; } + + public int LeftScore; + public int RightScore; + + private Paddle _leftPaddle; + private Paddle _rightPaddle; + private Ball _ball; + + public Board(Size size) { - public Size Size { get; } + Size = size; - public int LeftScore; - public int RightScore; + Assets.Stretchy.VirtualResolution = new Size( + 8, + size.Height + ); - private Paddle _leftPaddle; - private Paddle _rightPaddle; - private Ball _ball; + Assets.Stretchy.FilteringMode = TextureFilteringMode.NearestNeighbor; - public Board(Size size) + _leftPaddle = new Paddle(this) { - Size = size; - - Assets.Stretchy.VirtualResolution = new Size( - 8, - size.Height - ); + UpKey = KeyCode.W, + DownKey = KeyCode.S, + }; + _leftPaddle.Position = new( + 48, + Size.Height / 2f - _leftPaddle.Size.Y / 2 + ); + + _rightPaddle = new Paddle(this); + _rightPaddle.Position = new( + Size.Width - 48 - _rightPaddle.Size.X, + Size.Height / 2f - _rightPaddle.Size.Y / 2 + ); + + _ball = new Ball(this); + } - Assets.Stretchy.FilteringMode = TextureFilteringMode.NearestNeighbor; + public void Draw(RenderContext context) + { + context.DrawTexture( + Assets.Stretchy, + new Vector2( + Size.Width / 2f - Assets.Stretchy.VirtualResolution!.Value.Width / 2f, + -12 + ), + Vector2.One, + Vector2.Zero, + 0 + ); + + var scoreStr = $"{LeftScore} {RightScore}"; + var scoreSize = Assets.ScoreFont.Measure(scoreStr); + + context.DrawString( + Assets.ScoreFont, + scoreStr, + Size.Width / 2f - scoreSize.Width / 2f, + Size.Height / 2f - scoreSize.Height / 2f, + Color.White + ); + + _leftPaddle.Draw(context); + _rightPaddle.Draw(context); + _ball.Draw(context); + } - _leftPaddle = new Paddle(this) - { - UpKey = KeyCode.W, - DownKey = KeyCode.S, - }; - _leftPaddle.Position = new( - 48, - Size.Height / 2f - _leftPaddle.Size.Y / 2 - ); - - _rightPaddle = new Paddle(this); - _rightPaddle.Position = new( - Size.Width - 48 - _rightPaddle.Size.X, - Size.Height / 2f - _rightPaddle.Size.Y / 2 - ); - - _ball = new Ball(this); + public void Update(float delta) + { + if (Keyboard.IsKeyDown(KeyCode.Space)) + { + _ball.CanMove = true; } - public void Draw(RenderContext context) + _leftPaddle.Update(delta); + _rightPaddle.Update(delta); + _ball.Update(delta); + + if (_ball.CollidesWithPaddle(_leftPaddle)) { - context.DrawTexture( - Assets.Stretchy, - new Vector2( - Size.Width / 2f - Assets.Stretchy.VirtualResolution!.Value.Width / 2f, - -12 - ), - Vector2.One, - Vector2.Zero, - 0 - ); - - var scoreStr = $"{LeftScore} {RightScore}"; - var scoreSize = Assets.ScoreFont.Measure(scoreStr); - - context.DrawString( - Assets.ScoreFont, - scoreStr, - Size.Width / 2f - scoreSize.Width / 2f, - Size.Height / 2f - scoreSize.Height / 2f, - Color.White - ); - - _leftPaddle.Draw(context); - _rightPaddle.Draw(context); - _ball.Draw(context); + _ball.BounceFromPaddle(_leftPaddle); + Assets.PaddleHit.Play(); } - - public void Update(float delta) + else if (_ball.CollidesWithPaddle(_rightPaddle)) { - if (Keyboard.IsKeyDown(KeyCode.Space)) - { - _ball.CanMove = true; - } - - _leftPaddle.Update(delta); - _rightPaddle.Update(delta); - _ball.Update(delta); + _ball.BounceFromPaddle(_rightPaddle); + Assets.PaddleHit.Play(); + } + else if (_ball.CollidesWithBoardSide()) + { + _ball.BounceFromSide(); + Assets.WallHit.Play(); + } - if (_ball.CollidesWithPaddle(_leftPaddle)) - { - _ball.BounceFromPaddle(_leftPaddle); - Assets.PaddleHit.Play(); - } - else if (_ball.CollidesWithPaddle(_rightPaddle)) + if (_ball.CollidesWithEndOfPlayfield(out var left)) + { + if (left) { - _ball.BounceFromPaddle(_rightPaddle); - Assets.PaddleHit.Play(); + RightScore++; } - else if (_ball.CollidesWithBoardSide()) + else { - _ball.BounceFromSide(); - Assets.WallHit.Play(); + LeftScore++; } - if (_ball.CollidesWithEndOfPlayfield(out var left)) - { - if (left) - { - RightScore++; - } - else - { - LeftScore++; - } - - _ball.Center(); - Assets.OutsidePlayfield.Play(); - - _ball.CanMove = false; - } + _ball.Center(); + Assets.OutsidePlayfield.Play(); + + _ball.CanMove = false; } } } \ No newline at end of file diff --git a/Chroma.Examples/Pong/GameCore.cs b/Chroma.Examples/Pong/GameCore.cs index a801339c..367d1e89 100644 --- a/Chroma.Examples/Pong/GameCore.cs +++ b/Chroma.Examples/Pong/GameCore.cs @@ -1,35 +1,34 @@ +namespace Pong; + using Chroma; using Chroma.Audio.Sfxr; using Chroma.ContentManagement; using Chroma.Graphics; -namespace Pong +public class GameCore : Game { - public class GameCore : Game - { - private Board _board; + private Board _board; - public GameCore() : base(new(false, false)) - { - Window.Title = "Chroma Framework - Pong Example"; - } + public GameCore() : base(new(false, false)) + { + Window.Title = "Chroma Framework - Pong Example"; + } - protected override void Initialize(IContentProvider content) - { - Sfxr.Initialize(this); - Assets.Load(content); + protected override void Initialize(IContentProvider content) + { + Sfxr.Initialize(this); + Assets.Load(content); - _board = new Board(Window.Size); - } + _board = new Board(Window.Size); + } - protected override void Update(float delta) - { - _board.Update(delta); - } + protected override void Update(float delta) + { + _board.Update(delta); + } - protected override void Draw(RenderContext context) - { - _board.Draw(context); - } + protected override void Draw(RenderContext context) + { + _board.Draw(context); } } \ No newline at end of file diff --git a/Chroma.Examples/Pong/Paddle.cs b/Chroma.Examples/Pong/Paddle.cs index 0ffec7a1..fb767a90 100644 --- a/Chroma.Examples/Pong/Paddle.cs +++ b/Chroma.Examples/Pong/Paddle.cs @@ -1,77 +1,75 @@ +namespace Pong; + using System.Drawing; using System.Numerics; -using Chroma; using Chroma.Graphics; using Chroma.Input; using Color = Chroma.Graphics.Color; -namespace Pong +public class Paddle { - public class Paddle - { - private Board _board; + private Board _board; - public RectangleF Rectangle; - public Color Color = Color.White; - public float Acceleration = 200f; + public RectangleF Rectangle; + public Color Color = Color.White; + public float Acceleration = 200f; - public Vector2 Position + public Vector2 Position + { + get => new(Rectangle.X, Rectangle.Y); + set { - get => new(Rectangle.X, Rectangle.Y); - set - { - Rectangle.X = value.X; - Rectangle.Y = value.Y; - } + Rectangle.X = value.X; + Rectangle.Y = value.Y; } + } - public Vector2 Size => new(Rectangle.Width, Rectangle.Height); + public Vector2 Size => new(Rectangle.Width, Rectangle.Height); - public KeyCode UpKey = KeyCode.Up; - public KeyCode DownKey = KeyCode.Down; + public KeyCode UpKey = KeyCode.Up; + public KeyCode DownKey = KeyCode.Down; - public Paddle(Board board) - { - Rectangle = new Rectangle( - 16, 16, 20, 120 - ); + public Paddle(Board board) + { + Rectangle = new Rectangle( + 16, 16, 20, 120 + ); - _board = board; - } + _board = board; + } - public void Update(float dt) + public void Update(float dt) + { + if (Keyboard.IsKeyDown(UpKey)) { - if (Keyboard.IsKeyDown(UpKey)) + if (Rectangle.Y - (Acceleration * dt) > 0) { - if (Rectangle.Y - (Acceleration * dt) > 0) - { - Rectangle.Y -= Acceleration * dt; - } - else - { - Rectangle.Y = 0; - } + Rectangle.Y -= Acceleration * dt; } - else if (Keyboard.IsKeyDown(DownKey)) + else { - if (Rectangle.Y + (Acceleration * dt) < _board.Size.Height - Rectangle.Height) - { - Rectangle.Y += Acceleration * dt; - } - else - { - Rectangle.Y = _board.Size.Height - Rectangle.Height; - } + Rectangle.Y = 0; } } - - public void Draw(RenderContext context) + else if (Keyboard.IsKeyDown(DownKey)) { - context.Rectangle( - ShapeMode.Fill, - Rectangle, - Color - ); + if (Rectangle.Y + (Acceleration * dt) < _board.Size.Height - Rectangle.Height) + { + Rectangle.Y += Acceleration * dt; + } + else + { + Rectangle.Y = _board.Size.Height - Rectangle.Height; + } } } + + public void Draw(RenderContext context) + { + context.Rectangle( + ShapeMode.Fill, + Rectangle, + Color + ); + } } \ No newline at end of file diff --git a/Chroma.Examples/Pong/Program.cs b/Chroma.Examples/Pong/Program.cs index 4aeed200..bc9452f1 100644 --- a/Chroma.Examples/Pong/Program.cs +++ b/Chroma.Examples/Pong/Program.cs @@ -1,3 +1,4 @@ using Pong; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/PrimitiveShapes/GameCore.cs b/Chroma.Examples/PrimitiveShapes/GameCore.cs index a856759e..5f006c79 100644 --- a/Chroma.Examples/PrimitiveShapes/GameCore.cs +++ b/Chroma.Examples/PrimitiveShapes/GameCore.cs @@ -1,146 +1,142 @@ -using System.Collections.Generic; -using System.Drawing; +namespace PrimitiveShapes; + using System.Numerics; using Chroma; using Chroma.Graphics; using Chroma.Input; -using Color = Chroma.Graphics.Color; -namespace PrimitiveShapes +public class GameCore : Game { - public class GameCore : Game - { - private Vector2 _cursorPosition; + private Vector2 _cursorPosition; - public GameCore() : base(new(false, true, 8)) - { - Cursor.IsVisible = false; - Graphics.VerticalSyncMode = VerticalSyncMode.None; - } + public GameCore() : base(new(false, true, 8)) + { + Cursor.IsVisible = false; + Graphics.VerticalSyncMode = VerticalSyncMode.None; + } - protected override void Draw(RenderContext context) - { - context.Rectangle(ShapeMode.Stroke, 0, 0, 32, 32, Color.Cyan); - context.Line(0, 120, 0, 180, Color.Red); - context.Line(Window.Width - 1, 120, Window.Width - 1, 180, Color.Red); - context.Line(48, 0, 96, 0, Color.Lime); - context.Line(48, Window.Height - 1, 96, Window.Height - 1, Color.Gold); + protected override void Draw(RenderContext context) + { + context.Rectangle(ShapeMode.Stroke, 0, 0, 32, 32, Color.Cyan); + context.Line(0, 120, 0, 180, Color.Red); + context.Line(Window.Width - 1, 120, Window.Width - 1, 180, Color.Red); + context.Line(48, 0, 96, 0, Color.Lime); + context.Line(48, Window.Height - 1, 96, Window.Height - 1, Color.Gold); - context.Arc( - ShapeMode.Fill, - new Vector2(256, 32), - radius: 32, - startAngle: 0, - endAngle: 90, - Color.HotPink - ); - - RenderSettings.LineThickness = 2; - context.Circle( - ShapeMode.Stroke, - new Vector2(296, 32), - radius: 32, - Color.Lime - ); - RenderSettings.LineThickness = 1; - - context.Ellipse( - ShapeMode.Fill, - new Vector2(296, 96), - new Vector2(16, 48), - rotation: 45f, - Color.Aqua - ); - - RenderSettings.LineThickness = 4; - context.Line( - new Vector2(120, 120), - new Vector2(48, 48), - Color.Yellow - ); - RenderSettings.LineThickness = 1; - context.Polygon( - ShapeMode.Fill, - new() - { - new(200, 200), - new(232, 200), - new(260, 230), - new(243, 240), - new(160, 220) - }, Color.Purple - ); - - context.Polyline( - new() - { - new(300, 300), - new(310, 310), - new(320, 295), - new(330, 315), - new(340, 290), - new(350, 320) - }, - Color.DodgerBlue, - closeLoop: false - ); - - context.Rectangle( - ShapeMode.Fill, - new Vector2(400, 400), - 100, - 100, - Color.Red - ); - - RenderSettings.LineThickness = 1; - context.Rectangle( - ShapeMode.Stroke, - _cursorPosition - new Vector2(1), - 34, 34, - Color.White - ); - - context.Rectangle( - ShapeMode.Fill, - _cursorPosition, - 32, 32, Color.Green - ); - - context.DrawString( - $"Shape blending [F1]: {RenderSettings.ShapeBlendingEnabled}\n" + - $"Multisampling [F2] {RenderSettings.MultiSamplingEnabled}\n" + - "Hit [F3] to set blending functions.", - new Vector2(16, 16) - ); - } + context.Arc( + ShapeMode.Fill, + new Vector2(256, 32), + radius: 32, + startAngle: 0, + endAngle: 90, + Color.HotPink + ); - protected override void KeyPressed(KeyEventArgs e) - { - switch (e.KeyCode) + RenderSettings.LineThickness = 2; + context.Circle( + ShapeMode.Stroke, + new Vector2(296, 32), + radius: 32, + Color.Lime + ); + RenderSettings.LineThickness = 1; + + context.Ellipse( + ShapeMode.Fill, + new Vector2(296, 96), + new Vector2(16, 48), + rotation: 45f, + Color.Aqua + ); + + RenderSettings.LineThickness = 4; + context.Line( + new Vector2(120, 120), + new Vector2(48, 48), + Color.Yellow + ); + RenderSettings.LineThickness = 1; + context.Polygon( + ShapeMode.Fill, + new() { - case KeyCode.F1: - RenderSettings.ShapeBlendingEnabled = !RenderSettings.ShapeBlendingEnabled; - break; - - case KeyCode.F2: - RenderSettings.MultiSamplingEnabled = !RenderSettings.MultiSamplingEnabled; - break; - - case KeyCode.F3: - RenderSettings.SetShapeBlendingFunctions( - destinationColorBlend: BlendingFunction.SourceAlpha, - destinationAlphaBlend: BlendingFunction.DestinationColor, - sourceColorBlend: BlendingFunction.OneMinusDestinationAlpha, - sourceAlphaBlend: BlendingFunction.OneMinusSourceAlpha - ); - break; - } - } + new(200, 200), + new(232, 200), + new(260, 230), + new(243, 240), + new(160, 220) + }, Color.Purple + ); - protected override void MouseMoved(MouseMoveEventArgs e) + context.Polyline( + new() + { + new(300, 300), + new(310, 310), + new(320, 295), + new(330, 315), + new(340, 290), + new(350, 320) + }, + Color.DodgerBlue, + closeLoop: false + ); + + context.Rectangle( + ShapeMode.Fill, + new Vector2(400, 400), + 100, + 100, + Color.Red + ); + + RenderSettings.LineThickness = 1; + context.Rectangle( + ShapeMode.Stroke, + _cursorPosition - new Vector2(1), + 34, 34, + Color.White + ); + + context.Rectangle( + ShapeMode.Fill, + _cursorPosition, + 32, 32, Color.Green + ); + + context.DrawString( + $"Shape blending [F1]: {RenderSettings.ShapeBlendingEnabled}\n" + + $"Multisampling [F2] {RenderSettings.MultiSamplingEnabled}\n" + + "Hit [F3] to set blending functions.", + new Vector2(16, 16) + ); + } + + protected override void KeyPressed(KeyEventArgs e) + { + switch (e.KeyCode) { - _cursorPosition = e.Position; + case KeyCode.F1: + RenderSettings.ShapeBlendingEnabled = !RenderSettings.ShapeBlendingEnabled; + break; + + case KeyCode.F2: + RenderSettings.MultiSamplingEnabled = !RenderSettings.MultiSamplingEnabled; + break; + + case KeyCode.F3: + RenderSettings.SetShapeBlendingFunctions( + destinationColorBlend: BlendingFunction.SourceAlpha, + destinationAlphaBlend: BlendingFunction.DestinationColor, + sourceColorBlend: BlendingFunction.OneMinusDestinationAlpha, + sourceAlphaBlend: BlendingFunction.OneMinusSourceAlpha + ); + break; } } + + protected override void MouseMoved(MouseMoveEventArgs e) + { + _cursorPosition = e.Position; + } } \ No newline at end of file diff --git a/Chroma.Examples/PrimitiveShapes/Program.cs b/Chroma.Examples/PrimitiveShapes/Program.cs index bee57e8e..04039727 100644 --- a/Chroma.Examples/PrimitiveShapes/Program.cs +++ b/Chroma.Examples/PrimitiveShapes/Program.cs @@ -1,3 +1,4 @@ using PrimitiveShapes; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game .Run(); \ No newline at end of file diff --git a/Chroma.Examples/ProgressFlag/GameCore.cs b/Chroma.Examples/ProgressFlag/GameCore.cs index b2bb8b70..a68516b1 100644 --- a/Chroma.Examples/ProgressFlag/GameCore.cs +++ b/Chroma.Examples/ProgressFlag/GameCore.cs @@ -1,110 +1,109 @@ -using System.Collections.Generic; +namespace ProgressFlag; + +using System.Collections.Generic; using System.Numerics; using Chroma; using Chroma.Graphics; -namespace ProgressFlag +public class GameCore : Game { - public class GameCore : Game + private readonly List _flagColors = new() { - private readonly List _flagColors = new() - { - new(226, 32, 22), - new(242, 137, 23), - new(239, 229, 36), - new(120, 184, 42), - new(44, 88, 164), - new(109, 35, 128) - }; - - private readonly List _chevronColors = new() - { - new(29, 29, 27), - new(148, 85, 22), - new(123, 204, 229), - new(244, 174, 200), - new(255, 255, 255), - new(253, 216, 23) - }; - - private readonly Color _circleColor = new(102, 51, 139); + new(226, 32, 22), + new(242, 137, 23), + new(239, 229, 36), + new(120, 184, 42), + new(44, 88, 164), + new(109, 35, 128) + }; - private int _stripeHeight; - private int _chevronWidth = 90; - private Vector2 _centerPoint; + private readonly List _chevronColors = new() + { + new(29, 29, 27), + new(148, 85, 22), + new(123, 204, 229), + new(244, 174, 200), + new(255, 255, 255), + new(253, 216, 23) + }; - public GameCore() - : base(new(false, false, 4)) - { - RenderSettings.MultiSamplingEnabled = true; - Window.Mode.SetWindowed(1200, 768); - } + private readonly Color _circleColor = new(102, 51, 139); - protected override void Update(float delta) - { - _stripeHeight = Window.Height / _flagColors.Count; - _centerPoint = Window.Center + new Vector2(Window.Width / 6.66f, 0); - } + private int _stripeHeight; + private int _chevronWidth = 90; + private Vector2 _centerPoint; - protected override void Draw(RenderContext context) - { - DrawStripes(context); - DrawChevrons(context); - DrawCircle(context); - } + public GameCore() + : base(new(false, false, 4)) + { + RenderSettings.MultiSamplingEnabled = true; + Window.Mode.SetWindowed(1200, 768); + } - private void DrawStripes(RenderContext context) - { - for (var i = 0; i < _flagColors.Count; i++) - { - context.Rectangle( - ShapeMode.Fill, - 0, - i * _stripeHeight, - Window.Width, - _stripeHeight, - _flagColors[i] - ); - } - } + protected override void Update(float delta) + { + _stripeHeight = Window.Height / _flagColors.Count; + _centerPoint = Window.Center + new Vector2(Window.Width / 6.66f, 0); + } - private void DrawChevrons(RenderContext context) - { - for (var i = 0; i < _chevronColors.Count; i++) - { - DrawChevron( - context, - _chevronColors[i], - -i * _chevronWidth - ); - } - } + protected override void Draw(RenderContext context) + { + DrawStripes(context); + DrawChevrons(context); + DrawCircle(context); + } - // - // "can't draw it with triangles" ~ncommander - // - private void DrawChevron(RenderContext context, Color color, int xOffset = 0) + private void DrawStripes(RenderContext context) + { + for (var i = 0; i < _flagColors.Count; i++) { - context.Triangle( + context.Rectangle( ShapeMode.Fill, - new Vector2(xOffset, -(Window.Height / 2.10f)), - _centerPoint + new Vector2(xOffset, 0), - new(xOffset, Window.Height + Window.Height / 2.10f), - color + 0, + i * _stripeHeight, + Window.Width, + _stripeHeight, + _flagColors[i] ); } + } - private void DrawCircle(RenderContext context) + private void DrawChevrons(RenderContext context) + { + for (var i = 0; i < _chevronColors.Count; i++) { - RenderSettings.LineThickness = 12 * ((float)Window.Width / Window.Height); - - context.Ellipse( - ShapeMode.Stroke, - new Vector2(Window.Width / 9.5f, Window.Center.Y), - new Vector2(Window.Width / 12.63f, Window.Height / 8.08f), - 0, - _circleColor + DrawChevron( + context, + _chevronColors[i], + -i * _chevronWidth ); } } + + // + // "can't draw it with triangles" ~ncommander + // + private void DrawChevron(RenderContext context, Color color, int xOffset = 0) + { + context.Triangle( + ShapeMode.Fill, + new Vector2(xOffset, -(Window.Height / 2.10f)), + _centerPoint + new Vector2(xOffset, 0), + new(xOffset, Window.Height + Window.Height / 2.10f), + color + ); + } + + private void DrawCircle(RenderContext context) + { + RenderSettings.LineThickness = 12 * ((float)Window.Width / Window.Height); + + context.Ellipse( + ShapeMode.Stroke, + new Vector2(Window.Width / 9.5f, Window.Center.Y), + new Vector2(Window.Width / 12.63f, Window.Height / 8.08f), + 0, + _circleColor + ); + } } \ No newline at end of file diff --git a/Chroma.Examples/ProgressFlag/Program.cs b/Chroma.Examples/ProgressFlag/Program.cs index 5ff32608..155728aa 100644 --- a/Chroma.Examples/ProgressFlag/Program.cs +++ b/Chroma.Examples/ProgressFlag/Program.cs @@ -1,3 +1,4 @@ using ProgressFlag; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/RenderTargets/GameCore.cs b/Chroma.Examples/RenderTargets/GameCore.cs index 3515fab8..c5e24d9e 100644 --- a/Chroma.Examples/RenderTargets/GameCore.cs +++ b/Chroma.Examples/RenderTargets/GameCore.cs @@ -1,83 +1,82 @@ -using System.Numerics; +namespace RenderTargets; + +using System.Numerics; using Chroma; using Chroma.ContentManagement; using Chroma.Graphics; using Chroma.Input; -namespace RenderTargets +public class GameCore : Game { - public class GameCore : Game - { - private RenderTarget _tgt; + private RenderTarget _tgt; - private float _rotation; - private Vector2 _position = new(32); + private float _rotation; + private Vector2 _position = new(32); - public GameCore() : base(new(false, false)) + public GameCore() : base(new(false, false)) + { + } + + protected override void Initialize(IContentProvider content) + { + _tgt = new RenderTarget(Window.Size); + + if (RenderSettings.ShapeBlendingEnabled) + RenderSettings.ShapeBlendingEnabled = false; + } + + protected override void Update(float delta) + { + if (Keyboard.IsKeyDown(KeyCode.W)) { + _position.Y -= 50 * delta; } - - protected override void Initialize(IContentProvider content) + else if (Keyboard.IsKeyDown(KeyCode.S)) { - _tgt = new RenderTarget(Window.Size); - - if (RenderSettings.ShapeBlendingEnabled) - RenderSettings.ShapeBlendingEnabled = false; + _position.Y += 50 * delta; } - protected override void Update(float delta) + if (Keyboard.IsKeyDown(KeyCode.A)) { - if (Keyboard.IsKeyDown(KeyCode.W)) - { - _position.Y -= 50 * delta; - } - else if (Keyboard.IsKeyDown(KeyCode.S)) - { - _position.Y += 50 * delta; - } - - if (Keyboard.IsKeyDown(KeyCode.A)) - { - _position.X -= 50 * delta; - } - else if (Keyboard.IsKeyDown(KeyCode.D)) - { - _position.X += 50 * delta; - } + _position.X -= 50 * delta; + } + else if (Keyboard.IsKeyDown(KeyCode.D)) + { + _position.X += 50 * delta; } + } - protected override void Draw(RenderContext context) + protected override void Draw(RenderContext context) + { + context.RenderTo(_tgt, (ctx, tgt) => { - context.RenderTo(_tgt, (ctx, tgt) => - { - ctx.Clear(Color.Black); - ctx.Rectangle(ShapeMode.Fill, _position, 64, 64, Color.Cyan); - ctx.DrawString("This was rendered inside a render target.", new Vector2(16)); - }); + ctx.Clear(Color.Black); + ctx.Rectangle(ShapeMode.Fill, _position, 64, 64, Color.Cyan); + ctx.DrawString("This was rendered inside a render target.", new Vector2(16)); + }); - context.Clear(Color.Crimson); + context.Clear(Color.Crimson); - context.DrawTexture( - _tgt, - Window.Center, - Vector2.One, - _tgt.Center, - _rotation - ); + context.DrawTexture( + _tgt, + Window.Center, + Vector2.One, + _tgt.Center, + _rotation + ); - context.DrawString( - "Use left and right cursor keys to rotate the render target around its center.\n" + - "Use to move the cyan rectangle around the render target.", - new Vector2(8) - ); - } + context.DrawString( + "Use left and right cursor keys to rotate the render target around its center.\n" + + "Use to move the cyan rectangle around the render target.", + new Vector2(8) + ); + } - protected override void KeyPressed(KeyEventArgs e) - { - if (e.KeyCode == KeyCode.Left) - _rotation -= 10; - else if (e.KeyCode == KeyCode.Right) - _rotation += 10; - } + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.Left) + _rotation -= 10; + else if (e.KeyCode == KeyCode.Right) + _rotation += 10; } -} +} \ No newline at end of file diff --git a/Chroma.Examples/RenderTargets/Program.cs b/Chroma.Examples/RenderTargets/Program.cs index cc20cc7e..479e146e 100644 --- a/Chroma.Examples/RenderTargets/Program.cs +++ b/Chroma.Examples/RenderTargets/Program.cs @@ -1,3 +1,4 @@ using RenderTargets; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/RenderTransforms/GameCore.cs b/Chroma.Examples/RenderTransforms/GameCore.cs index f1b95bda..7a74cbb2 100644 --- a/Chroma.Examples/RenderTransforms/GameCore.cs +++ b/Chroma.Examples/RenderTransforms/GameCore.cs @@ -1,3 +1,5 @@ +namespace RenderTransforms; + using System; using System.IO; using System.Numerics; @@ -6,66 +8,63 @@ using Chroma.ContentManagement.FileSystem; using Chroma.Graphics; -namespace RenderTransforms +public class GameCore : Game { - public class GameCore : Game + private Texture _burger; + private RenderTarget _rt; + private float _angle = 0; + + public GameCore() : base(new(false, false)) { - private Texture _burger; - private RenderTarget _rt; - private float _angle = 0; + } - public GameCore() : base(new(false, false)) - { - } + protected override IContentProvider InitializeContentPipeline() + { + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } - protected override IContentProvider InitializeContentPipeline() - { - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); - } + protected override void Initialize(IContentProvider content) + { + _burger = content.Load("Textures/burg.png"); + _rt = new RenderTarget(_burger.Width * 2, _burger.Height * 2); - protected override void Initialize(IContentProvider content) - { - _burger = content.Load("Textures/burg.png"); - _rt = new RenderTarget(_burger.Width * 2, _burger.Height * 2); + RenderTransform.SetMatrixMode(MatrixMode.Projection, Window); + RenderTransform.LoadIdentity(); + RenderTransform.Orthographic( + 0, + 0, + Window.Width, + Window.Height, + 1, + -1 + ); + } - RenderTransform.SetMatrixMode(MatrixMode.Projection, Window); - RenderTransform.LoadIdentity(); - RenderTransform.Orthographic( - 0, - 0, - Window.Width, - Window.Height, - 1, - -1 - ); - } + protected override void Update(float delta) + { + _angle += 200f * delta; + } - protected override void Update(float delta) + protected override void Draw(RenderContext context) + { + context.RenderTo(_rt, (ctx, tgt) => { - _angle += 200f * delta; - } - - protected override void Draw(RenderContext context) - { - context.RenderTo(_rt, (ctx, tgt) => - { - ctx.Clear(Color.Aqua); + ctx.Clear(Color.Aqua); - RenderTransform.SetMatrixMode(MatrixMode.Model, _rt); - RenderTransform.Push(); - RenderTransform.LoadIdentity(); + RenderTransform.SetMatrixMode(MatrixMode.Model, _rt); + RenderTransform.Push(); + RenderTransform.LoadIdentity(); - RenderTransform.Translate(_burger.Center); - RenderTransform.Rotate(_angle, new Vector3(0, 0, 1f)); - RenderTransform.Translate(-_burger.Center); + RenderTransform.Translate(_burger.Center); + RenderTransform.Rotate(_angle, new Vector3(0, 0, 1f)); + RenderTransform.Translate(-_burger.Center); - ctx.DrawTexture(_burger, Vector2.Zero, Vector2.One, Vector2.Zero, 0); - RenderTransform.Pop(); - }); + ctx.DrawTexture(_burger, Vector2.Zero, Vector2.One, Vector2.Zero, 0); + RenderTransform.Pop(); + }); - context.DrawTexture(_rt, Window.Center, Vector2.One, _rt.Center, 0); - } + context.DrawTexture(_rt, Window.Center, Vector2.One, _rt.Center, 0); } } \ No newline at end of file diff --git a/Chroma.Examples/RenderTransforms/Program.cs b/Chroma.Examples/RenderTransforms/Program.cs index d037ea37..004bd5b8 100644 --- a/Chroma.Examples/RenderTransforms/Program.cs +++ b/Chroma.Examples/RenderTransforms/Program.cs @@ -1,3 +1,4 @@ using RenderTransforms; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/Scissors/GameCore.cs b/Chroma.Examples/Scissors/GameCore.cs index 33ccd2c5..fdf9154d 100644 --- a/Chroma.Examples/Scissors/GameCore.cs +++ b/Chroma.Examples/Scissors/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace Scissors; + +using System; using System.Drawing; using System.IO; using System.Numerics; @@ -9,97 +11,94 @@ using Chroma.Input; using Color = Chroma.Graphics.Color; -namespace Scissors +public class GameCore : Game { - public class GameCore : Game + private bool _useScissor = true; + private Rectangle _scissor = new(64, 64, 128, 128); + private Texture _grid; + + public GameCore() : base(new(false, false)) { - private bool _useScissor = true; - private Rectangle _scissor = new(64, 64, 128, 128); - private Texture _grid; + } - public GameCore() : base(new(false, false)) - { - } + protected override IContentProvider InitializeContentPipeline() + { + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } + + protected override void Initialize(IContentProvider content) + { + _grid = content.Load("Textures/grid.png"); + } + + protected override void Update(float delta) + { + } + + protected override void Draw(RenderContext context) + { + if (_useScissor) + RenderSettings.Scissor = _scissor; + + context.DrawTexture(_grid, Vector2.Zero, Vector2.One, Vector2.Zero, 0f); - protected override IContentProvider InitializeContentPipeline() + if (_useScissor) { - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") + RenderSettings.Scissor = Rectangle.Empty; + + RenderSettings.LineThickness = 1; + context.Rectangle( + ShapeMode.Stroke, + _scissor, + Color.Red ); } - protected override void Initialize(IContentProvider content) + context.DrawString( + "Use to toggle scissor on/off.\n" + + "Use to move the scissor around the screen.\nHold shift to modify the size instead.", + new Vector2(8), + Color.Red + ); + } + + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.F1) { - _grid = content.Load("Textures/grid.png"); + _useScissor = !_useScissor; } - protected override void Update(float delta) + if (e.KeyCode == KeyCode.Up) { + if (e.Modifiers.HasFlag(KeyModifiers.LeftShift)) + _scissor.Height -= 10; + else + _scissor.Y -= 10; } - - protected override void Draw(RenderContext context) + else if (e.KeyCode == KeyCode.Down) { - if (_useScissor) - RenderSettings.Scissor = _scissor; - - context.DrawTexture(_grid, Vector2.Zero, Vector2.One, Vector2.Zero, 0f); - - if (_useScissor) - { - RenderSettings.Scissor = Rectangle.Empty; - - RenderSettings.LineThickness = 1; - context.Rectangle( - ShapeMode.Stroke, - _scissor, - Color.Red - ); - } - - context.DrawString( - "Use to toggle scissor on/off.\n" + - "Use to move the scissor around the screen.\nHold shift to modify the size instead.", - new Vector2(8), - Color.Red - ); + if (e.Modifiers.HasFlag(KeyModifiers.LeftShift)) + _scissor.Height += 10; + else + _scissor.Y += 10; } - protected override void KeyPressed(KeyEventArgs e) + if (e.KeyCode == KeyCode.Left) { - if (e.KeyCode == KeyCode.F1) - { - _useScissor = !_useScissor; - } - - if (e.KeyCode == KeyCode.Up) - { - if (e.Modifiers.HasFlag(KeyModifiers.LeftShift)) - _scissor.Height -= 10; - else - _scissor.Y -= 10; - } - else if (e.KeyCode == KeyCode.Down) - { - if (e.Modifiers.HasFlag(KeyModifiers.LeftShift)) - _scissor.Height += 10; - else - _scissor.Y += 10; - } - - if (e.KeyCode == KeyCode.Left) - { - if (e.Modifiers.HasFlag(KeyModifiers.LeftShift)) - _scissor.Width -= 10; - else - _scissor.X -= 10; - } - else if (e.KeyCode == KeyCode.Right) - { - if (e.Modifiers.HasFlag(KeyModifiers.LeftShift)) - _scissor.Width += 10; - else - _scissor.X += 10; - } + if (e.Modifiers.HasFlag(KeyModifiers.LeftShift)) + _scissor.Width -= 10; + else + _scissor.X -= 10; + } + else if (e.KeyCode == KeyCode.Right) + { + if (e.Modifiers.HasFlag(KeyModifiers.LeftShift)) + _scissor.Width += 10; + else + _scissor.X += 10; } } } \ No newline at end of file diff --git a/Chroma.Examples/Scissors/Program.cs b/Chroma.Examples/Scissors/Program.cs index 84d803c1..f98ad155 100644 --- a/Chroma.Examples/Scissors/Program.cs +++ b/Chroma.Examples/Scissors/Program.cs @@ -1,3 +1,4 @@ using Scissors; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/Scissors/ResizeBorder.cs b/Chroma.Examples/Scissors/ResizeBorder.cs index 34d6ef68..356cd874 100644 --- a/Chroma.Examples/Scissors/ResizeBorder.cs +++ b/Chroma.Examples/Scissors/ResizeBorder.cs @@ -1,10 +1,9 @@ -namespace Scissors +namespace Scissors; + +public enum ResizeBorder { - public enum ResizeBorder - { - Left, - Top, - Right, - Bottom - } + Left, + Top, + Right, + Bottom } \ No newline at end of file diff --git a/Chroma.Examples/TextInput/GameCore.cs b/Chroma.Examples/TextInput/GameCore.cs index 60f6683e..c6802a65 100644 --- a/Chroma.Examples/TextInput/GameCore.cs +++ b/Chroma.Examples/TextInput/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace TextInput; + +using System; using System.Drawing; using System.IO; using Chroma; @@ -9,157 +11,154 @@ using Chroma.Input; using Color = Chroma.Graphics.Color; -namespace TextInput +public class GameCore : Game { - public class GameCore : Game - { - private TrueTypeFont _font; - - private bool _colorCycle; + private TrueTypeFont _font; - private int _colorOffset; - private float _cycleTimer; - - private Color[] _colors = new[] - { - Color.Red, - Color.Orange, - Color.Yellow, - Color.Lime, - Color.DodgerBlue, - Color.Indigo, - Color.Violet - }; + private bool _colorCycle; - private Terminal _terminal; - private VGA _vga; + private int _colorOffset; + private float _cycleTimer; - public GameCore() : base(new(false, false)) - { - } + private Color[] _colors = new[] + { + Color.Red, + Color.Orange, + Color.Yellow, + Color.Lime, + Color.DodgerBlue, + Color.Indigo, + Color.Violet + }; + + private Terminal _terminal; + private VGA _vga; + + public GameCore() : base(new(false, false)) + { + } - protected override IContentProvider InitializeContentPipeline() - { - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); - } + protected override IContentProvider InitializeContentPipeline() + { + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } - protected override void Initialize(IContentProvider content) - { - using var fs = new FileStream( - Path.Combine(AppContext.BaseDirectory, "../../../../_common/Fonts/dos8x14.ttf"), - FileMode.Open - ); + protected override void Initialize(IContentProvider content) + { + using var fs = new FileStream( + Path.Combine(AppContext.BaseDirectory, "../../../../_common/Fonts/dos8x14.ttf"), + FileMode.Open + ); - _font = new TrueTypeFont(fs, 16); - _font.PreferAutoHinter = true; + _font = new TrueTypeFont(fs, 16); + _font.PreferAutoHinter = true; - Window.SizeChanged += (_, _) => { InitializeDisplay(); }; + Window.SizeChanged += (_, _) => { InitializeDisplay(); }; - InitializeDisplay(); - } + InitializeDisplay(); + } - private void InitializeDisplay() + private void InitializeDisplay() + { + _vga = new VGA(Window, _font) { - _vga = new VGA(Window, _font) - { - CursorEnabled = true - }; + CursorEnabled = true + }; - _terminal = new Terminal(_vga) + _terminal = new Terminal(_vga) + { + InputAccepted = (input) => { - InputAccepted = (input) => + if (!string.IsNullOrWhiteSpace(input)) { - if (!string.IsNullOrWhiteSpace(input)) - { - _terminal.WriteLine($" ECHO -> {input}"); - } - - _terminal.Write("root # "); + _terminal.WriteLine($" ECHO -> {input}"); } - }; - _terminal.WriteLine( - "Welcome to the faux terminal shell!\nInput text to get it echoed back. Hit for a surprise.\n"); - _terminal.Write("root # "); - } - protected override void Update(float delta) - { - _terminal.Update(delta); + _terminal.Write("root # "); + } + }; + _terminal.WriteLine( + "Welcome to the faux terminal shell!\nInput text to get it echoed back. Hit for a surprise.\n"); + _terminal.Write("root # "); + } - if (_colorCycle) + protected override void Update(float delta) + { + _terminal.Update(delta); + + if (_colorCycle) + { + _cycleTimer += 25 * delta; + if (_cycleTimer > 5) { - _cycleTimer += 25 * delta; - if (_cycleTimer > 5) - { - for (var y = 0; y < _vga.TotalRows; y++) - _vga.SetLineToColor(_colors[(y + _colorOffset) % _colors.Length], y); + for (var y = 0; y < _vga.TotalRows; y++) + _vga.SetLineToColor(_colors[(y + _colorOffset) % _colors.Length], y); - _colorOffset++; - _cycleTimer = 0; - } + _colorOffset++; + _cycleTimer = 0; } } + } - protected override void Draw(RenderContext context) + protected override void Draw(RenderContext context) + { + _terminal.Draw(context); + } + + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.Return || e.KeyCode == KeyCode.NumEnter) { - _terminal.Draw(context); + _terminal.PutChar('\n'); + _terminal.AcceptInput(); } - - protected override void KeyPressed(KeyEventArgs e) + else if (e.KeyCode == KeyCode.Backspace) { - if (e.KeyCode == KeyCode.Return || e.KeyCode == KeyCode.NumEnter) - { - _terminal.PutChar('\n'); - _terminal.AcceptInput(); - } - else if (e.KeyCode == KeyCode.Backspace) - { - _terminal.PutChar('\b'); - } - else if (e.KeyCode == KeyCode.F1) - { - _colorCycle = !_colorCycle; + _terminal.PutChar('\b'); + } + else if (e.KeyCode == KeyCode.F1) + { + _colorCycle = !_colorCycle; - if (!_colorCycle) - { - _vga.Clear(false, true); - } - } - else if (e.KeyCode == KeyCode.F2) - { - _font.IsKerningEnabled = !_font.IsKerningEnabled; - } - else if (e.KeyCode == KeyCode.F3) - { - _font.PreferAutoHinter = !_font.PreferAutoHinter; - } - else if (e.KeyCode == KeyCode.F4) + if (!_colorCycle) { - _font.HintingMode = HintingMode.Light; - } - else if (e.KeyCode == KeyCode.F5) - { - _font.HintingMode = HintingMode.Monochrome; - } - else if (e.KeyCode == KeyCode.F6) - { - Window.Mode.SetBorderlessFullScreen(); - } - else if (e.KeyCode == KeyCode.F7) - { - Window.Mode.SetWindowed(new Size(800, 600), true); - } - else if (e.KeyCode == KeyCode.F8) - { - Window.CanResize = !Window.CanResize; + _vga.Clear(false, true); } } - - protected override void TextInput(TextInputEventArgs e) + else if (e.KeyCode == KeyCode.F2) + { + _font.IsKerningEnabled = !_font.IsKerningEnabled; + } + else if (e.KeyCode == KeyCode.F3) + { + _font.PreferAutoHinter = !_font.PreferAutoHinter; + } + else if (e.KeyCode == KeyCode.F4) + { + _font.HintingMode = HintingMode.Light; + } + else if (e.KeyCode == KeyCode.F5) { - _terminal.TextInput(e); + _font.HintingMode = HintingMode.Monochrome; } + else if (e.KeyCode == KeyCode.F6) + { + Window.Mode.SetBorderlessFullScreen(); + } + else if (e.KeyCode == KeyCode.F7) + { + Window.Mode.SetWindowed(new Size(800, 600), true); + } + else if (e.KeyCode == KeyCode.F8) + { + Window.CanResize = !Window.CanResize; + } + } + + protected override void TextInput(TextInputEventArgs e) + { + _terminal.TextInput(e); } } \ No newline at end of file diff --git a/Chroma.Examples/TextInput/Program.cs b/Chroma.Examples/TextInput/Program.cs index f4e65e7b..9b5fcfac 100644 --- a/Chroma.Examples/TextInput/Program.cs +++ b/Chroma.Examples/TextInput/Program.cs @@ -1,3 +1,4 @@ using TextInput; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/TextInput/Terminal.cs b/Chroma.Examples/TextInput/Terminal.cs index dfc1f359..45f85a19 100644 --- a/Chroma.Examples/TextInput/Terminal.cs +++ b/Chroma.Examples/TextInput/Terminal.cs @@ -1,116 +1,115 @@ +namespace TextInput; + using System; using Chroma.Graphics; using Chroma.Input; -namespace TextInput +public class Terminal { - public class Terminal - { - private VGA _vga; + private VGA _vga; - private int _x; - private int _y; + private int _x; + private int _y; - private string _input; + private string _input; - public Action InputAccepted { get; set; } + public Action InputAccepted { get; set; } - public Terminal(VGA vga) - { - _vga = vga; - } + public Terminal(VGA vga) + { + _vga = vga; + } - public void Reset() - { - _x = 0; - _y = 0; + public void Reset() + { + _x = 0; + _y = 0; - _vga.Reset(); - } + _vga.Reset(); + } + + public void WriteLine(string text) + { + Write($"{text}\n"); + } + + public void Write(string text) + { + for (var i = 0; i < text.Length; i++) + PutChar(text[i]); + } - public void WriteLine(string text) + public void PutChar(char c) + { + if (c == '\n') { - Write($"{text}\n"); + _x = 0; + _y++; } - - public void Write(string text) + else if (c == '\r') { - for (var i = 0; i < text.Length; i++) - PutChar(text[i]); + _x = 0; } - - public void PutChar(char c) + else if (c == '\b') { - if (c == '\n') - { - _x = 0; - _y++; - } - else if (c == '\r') - { - _x = 0; - } - else if (c == '\b') - { - if ((_x == 0 && _y == 0) || _input.Length == 0) - return; - - _input = _input[0..(_input.Length - 1)]; - _x--; + if ((_x == 0 && _y == 0) || _input.Length == 0) + return; - if (_x < 0) - { - _x = 0; + _input = _input[0..(_input.Length - 1)]; + _x--; - if (_y - 1 >= 0) - _y--; - } - - _vga.SetCharAt(_x, _y, ' '); - } - else - { - _vga.SetCharAt(_x++, _y, c); - } - - if (_x >= _vga.TotalCols) + if (_x < 0) { _x = 0; - _y++; - } - if (_y >= _vga.TotalRows) - { - _x = 0; - _y--; - - _vga.ScrollUp(); + if (_y - 1 >= 0) + _y--; } - } - - public void Update(float delta) - { - _vga.CursorX = _x; - _vga.CursorY = _y; - _vga.Update(delta); + _vga.SetCharAt(_x, _y, ' '); } - - public void Draw(RenderContext context) + else { - _vga.Draw(context); + _vga.SetCharAt(_x++, _y, c); } - public void AcceptInput() + if (_x >= _vga.TotalCols) { - InputAccepted?.Invoke(_input); - _input = string.Empty; + _x = 0; + _y++; } - public void TextInput(TextInputEventArgs e) + if (_y >= _vga.TotalRows) { - _input += e.Text; - Write(e.Text); + _x = 0; + _y--; + + _vga.ScrollUp(); } } + + public void Update(float delta) + { + _vga.CursorX = _x; + _vga.CursorY = _y; + + _vga.Update(delta); + } + + public void Draw(RenderContext context) + { + _vga.Draw(context); + } + + public void AcceptInput() + { + InputAccepted?.Invoke(_input); + _input = string.Empty; + } + + public void TextInput(TextInputEventArgs e) + { + _input += e.Text; + Write(e.Text); + } } \ No newline at end of file diff --git a/Chroma.Examples/TextInput/VGA.cs b/Chroma.Examples/TextInput/VGA.cs index 824de8d3..593aba04 100644 --- a/Chroma.Examples/TextInput/VGA.cs +++ b/Chroma.Examples/TextInput/VGA.cs @@ -1,195 +1,192 @@ -using System.Numerics; -using Chroma; +namespace TextInput; + +using System.Numerics; using Chroma.Graphics; -using Chroma.Graphics.TextRendering; using Chroma.Graphics.TextRendering.TrueType; using Chroma.Windowing; -namespace TextInput +public class VGA { - public class VGA - { - private readonly TrueTypeFont _ttf; - private Color[] _fgColorBuffer; - private char[] _charBuffer; + private readonly TrueTypeFont _ttf; + private Color[] _fgColorBuffer; + private char[] _charBuffer; - private int _cx; - private int _cy; + private int _cx; + private int _cy; - private float _cursorTimer; - private bool _drawCursor; + private float _cursorTimer; + private bool _drawCursor; - public int TotalCols { get; } - public int TotalRows { get; } + public int TotalCols { get; } + public int TotalRows { get; } - public int RowSize { get; } - public int ColSize { get; } + public int RowSize { get; } + public int ColSize { get; } - public int CursorX + public int CursorX + { + get => _cx; + set { - get => _cx; - set - { - if (value >= TotalCols) - _cx = TotalCols - 1; - else if (value < 0) - _cx = 0; - else _cx = value; - } + if (value >= TotalCols) + _cx = TotalCols - 1; + else if (value < 0) + _cx = 0; + else _cx = value; } + } - public int CursorY + public int CursorY + { + get => _cy; + set { - get => _cy; - set - { - if (value >= TotalRows) - _cy = TotalRows - 1; - else if (value < 0) - _cy = 0; - else _cy = value; - } + if (value >= TotalRows) + _cy = TotalRows - 1; + else if (value < 0) + _cy = 0; + else _cy = value; } + } - public bool CursorEnabled { get; set; } + public bool CursorEnabled { get; set; } - public VGA(Window window, TrueTypeFont ttf) - { - _ttf = ttf; + public VGA(Window window, TrueTypeFont ttf) + { + _ttf = ttf; - ColSize = _ttf.Measure("A").Width; - RowSize = _ttf.Height; + ColSize = _ttf.Measure("A").Width; + RowSize = _ttf.Height; - TotalCols = window.Width / ColSize; - TotalRows = window.Height / RowSize; + TotalCols = window.Width / ColSize; + TotalRows = window.Height / RowSize; - Reset(); - } + Reset(); + } - public void Reset() - { - _cx = 0; - _cy = 0; + public void Reset() + { + _cx = 0; + _cy = 0; - _fgColorBuffer = new Color[TotalCols * TotalRows]; - _charBuffer = new char[TotalCols * TotalRows]; + _fgColorBuffer = new Color[TotalCols * TotalRows]; + _charBuffer = new char[TotalCols * TotalRows]; - Clear(true, true); - } + Clear(true, true); + } - public void Clear(bool chars, bool colors) + public void Clear(bool chars, bool colors) + { + for (var y = 0; y < TotalRows; y++) { - for (var y = 0; y < TotalRows; y++) + for (var x = 0; x < TotalCols; x++) { - for (var x = 0; x < TotalCols; x++) - { - if (chars) - _charBuffer[y * TotalCols + x] = ' '; + if (chars) + _charBuffer[y * TotalCols + x] = ' '; - if (colors) - _fgColorBuffer[y * TotalCols + x] = Color.White; - } + if (colors) + _fgColorBuffer[y * TotalCols + x] = Color.White; } } + } - public void SetCharAt(int x, int y, char c) - => _charBuffer[y * TotalCols + x] = c; + public void SetCharAt(int x, int y, char c) + => _charBuffer[y * TotalCols + x] = c; - public void SetColorAt(int x, int y, Color c) - => _fgColorBuffer[y * TotalCols + x] = c; + public void SetColorAt(int x, int y, Color c) + => _fgColorBuffer[y * TotalCols + x] = c; - public void WriteStringTo(int x, int y, string str) - { - var tx = x; - var ty = y; + public void WriteStringTo(int x, int y, string str) + { + var tx = x; + var ty = y; - for (var i = 0; i < str.Length; i++) - { - SetCharAt(tx, ty, str[i]); + for (var i = 0; i < str.Length; i++) + { + SetCharAt(tx, ty, str[i]); - tx++; + tx++; - if (tx >= TotalCols) - { - tx = 0; - ty++; + if (tx >= TotalCols) + { + tx = 0; + ty++; - if (ty >= TotalRows) - ty = 0; - } + if (ty >= TotalRows) + ty = 0; } } + } - public void ScrollUp() + public void ScrollUp() + { + for (var y = 1; y < TotalRows; y++) { - for (var y = 1; y < TotalRows; y++) - { - for (var x = 0; x < TotalCols; x++) - { - _charBuffer[(y - 1) * TotalCols + x] = _charBuffer[y * TotalCols + x]; - } - } - for (var x = 0; x < TotalCols; x++) { - _charBuffer[(TotalRows - 1) * TotalCols + x] = ' '; - _fgColorBuffer[(TotalRows - 1) * TotalCols + x] = Color.White; + _charBuffer[(y - 1) * TotalCols + x] = _charBuffer[y * TotalCols + x]; } } - public void SetLineToColor(Color color, int y) + for (var x = 0; x < TotalCols; x++) { - if (y < 0 || y >= TotalRows) - return; + _charBuffer[(TotalRows - 1) * TotalCols + x] = ' '; + _fgColorBuffer[(TotalRows - 1) * TotalCols + x] = Color.White; + } + } - for (var x = 0; x < TotalCols; x++) - _fgColorBuffer[y * TotalCols + x] = color; + public void SetLineToColor(Color color, int y) + { + if (y < 0 || y >= TotalRows) + return; + + for (var x = 0; x < TotalCols; x++) + _fgColorBuffer[y * TotalCols + x] = color; + } + + public void Update(float delta) + { + _cursorTimer += 2000 * delta; + + if (_cursorTimer > 1000) + { + _drawCursor = !_drawCursor; + _cursorTimer = 0; } + } - public void Update(float delta) + public void Draw(RenderContext context) + { + for (var y = 0; y < TotalRows; y++) { - _cursorTimer += 2000 * delta; + var start = y * TotalCols; + var end = start + TotalCols; - if (_cursorTimer > 1000) - { - _drawCursor = !_drawCursor; - _cursorTimer = 0; - } + var str = new string(_charBuffer[start..end]); + + context.DrawString( + _ttf, + str, + new Vector2(0, y * _ttf.Height), + (d, _, i, _) => + { + d.Color = _fgColorBuffer[y * TotalCols + i]; + } + ); } - public void Draw(RenderContext context) + if (CursorEnabled && _drawCursor) { - for (var y = 0; y < TotalRows; y++) - { - var start = y * TotalCols; - var end = start + TotalCols; - - var str = new string(_charBuffer[start..end]); - - context.DrawString( - _ttf, - str, - new Vector2(0, y * _ttf.Height), - (d, _, i, _) => - { - d.Color = _fgColorBuffer[y * TotalCols + i]; - } - ); - } - - if (CursorEnabled && _drawCursor) - { - context.Rectangle( - ShapeMode.Stroke, - new Vector2( - _cx * ColSize + 4, - _cy * RowSize - 1 - ), - ColSize, - RowSize - 2, - _fgColorBuffer[_cy * TotalCols + _cx] - ); - } + context.Rectangle( + ShapeMode.Stroke, + new Vector2( + _cx * ColSize + 4, + _cy * RowSize - 1 + ), + ColSize, + RowSize - 2, + _fgColorBuffer[_cy * TotalCols + _cx] + ); } } } \ No newline at end of file diff --git a/Chroma.Examples/Textures/GameCore.cs b/Chroma.Examples/Textures/GameCore.cs index c033d4e0..71e55526 100644 --- a/Chroma.Examples/Textures/GameCore.cs +++ b/Chroma.Examples/Textures/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace Textures; + +using System; using System.Drawing; using System.IO; using System.Numerics; @@ -10,198 +12,195 @@ using Chroma.Input; using Color = Chroma.Graphics.Color; -namespace Textures +public class GameCore : Game { - public class GameCore : Game - { - private Texture _tileMap; - private Texture _tile1; + private Texture _tileMap; + private Texture _tile1; - private Texture _burger; - private Texture _dynTex; - - private int _totalTiles; - private int _currentTileIndex; - private Size _virtRes; + private Texture _burger; + private Texture _dynTex; - private Random _rnd = new(); - private float _rotation; - private float _wave; + private int _totalTiles; + private int _currentTileIndex; + private Size _virtRes; - private Color[] _colors = new[] - { - Color.Aqua, - Color.Yellow, - Color.Green, - Color.CornflowerBlue, - Color.Violet, - Color.Thistle, - Color.Orange - }; - - public GameCore() : base(new(false, false)) - { - Graphics.LimitFramerate = false; - Cursor.IsVisible = false; - } + private Random _rnd = new(); + private float _rotation; + private float _wave; - protected override IContentProvider InitializeContentPipeline() - { - return new FileSystemContentProvider( - Path.Combine(AppContext.BaseDirectory, "../../../../_common") - ); - } + private Color[] _colors = new[] + { + Color.Aqua, + Color.Yellow, + Color.Green, + Color.CornflowerBlue, + Color.Violet, + Color.Thistle, + Color.Orange + }; + + public GameCore() : base(new(false, false)) + { + Graphics.LimitFramerate = false; + Cursor.IsVisible = false; + } - protected override void Initialize(IContentProvider content) - { - _tileMap = content.Load("Textures/walls.jpeg"); - _totalTiles = _tileMap.Width / 64; - _tile1 = _tileMap.SubTexture(new(64, 0, 64, 64)); + protected override IContentProvider InitializeContentPipeline() + { + return new FileSystemContentProvider( + Path.Combine(AppContext.BaseDirectory, "../../../../_common") + ); + } - _burger = content.Load("Textures/burg.png"); - _virtRes = new Size(_burger.Width, _burger.Height); + protected override void Initialize(IContentProvider content) + { + _tileMap = content.Load("Textures/walls.jpeg"); + _totalTiles = _tileMap.Width / 64; + _tile1 = _tileMap.SubTexture(new(64, 0, 64, 64)); - _dynTex = new Texture(256, 256); - _dynTex.FilteringMode = TextureFilteringMode.NearestNeighbor; - } + _burger = content.Load("Textures/burg.png"); + _virtRes = new Size(_burger.Width, _burger.Height); - protected override void Draw(RenderContext context) - { - context.DrawString( - "Use left/right arrows to switch between tiles on the tile map.\n" + - "Use num+/num- to adjust burger's virtual resolution by 32 pixels.\n" + - "Use F1 to reset burger's virtual resolution.\n" + - "Use F2-F5 to switch between different blending modes.\n" + - $"{Color.Brown.R}, {Color.Brown.G}, {Color.Brown.B}: {Color.Brown.Hue}, {Color.Brown.Saturation}, {Color.Brown.Value}", - new Vector2(8) - ); + _dynTex = new Texture(256, 256); + _dynTex.FilteringMode = TextureFilteringMode.NearestNeighbor; + } - _dynTex.Flush(); - context.DrawTexture( - _dynTex, - Window.Center + new Vector2(127, 0), - Vector2.One, - Vector2.Zero, - 0 - ); + protected override void Draw(RenderContext context) + { + context.DrawString( + "Use left/right arrows to switch between tiles on the tile map.\n" + + "Use num+/num- to adjust burger's virtual resolution by 32 pixels.\n" + + "Use F1 to reset burger's virtual resolution.\n" + + "Use F2-F5 to switch between different blending modes.\n" + + $"{Color.Brown.R}, {Color.Brown.G}, {Color.Brown.B}: {Color.Brown.Hue}, {Color.Brown.Saturation}, {Color.Brown.Value}", + new Vector2(8) + ); + + _dynTex.Flush(); + context.DrawTexture( + _dynTex, + Window.Center + new Vector2(127, 0), + Vector2.One, + Vector2.Zero, + 0 + ); - context.DrawTexture( - _tile1, - Window.Center - new Vector2(0, 127), - Vector2.One, - Vector2.Zero, - 0 - ); - - context.DrawTexture( - _tileMap, - new Vector2(32, 128), - Vector2.One, - Vector2.Zero, - rotation: 0f, - new Rectangle(_currentTileIndex * 64, 0, 64, 64) - ); + context.DrawTexture( + _tile1, + Window.Center - new Vector2(0, 127), + Vector2.One, + Vector2.Zero, + 0 + ); + + context.DrawTexture( + _tileMap, + new Vector2(32, 128), + Vector2.One, + Vector2.Zero, + rotation: 0f, + new Rectangle(_currentTileIndex * 64, 0, 64, 64) + ); + + context.Rectangle( + ShapeMode.Fill, + new Vector2(256), + 128, 128, Color.HotPink + ); + + context.DrawTexture( + _burger, + Mouse.GetPosition() + _burger.Center + new Vector2(0, 5 * MathF.Sin(_wave)), + Vector2.One, + _burger.Center, + _rotation + ); + } - context.Rectangle( - ShapeMode.Fill, - new Vector2(256), - 128, 128, Color.HotPink - ); + protected override void Update(float delta) + { + Window.Title = PerformanceCounter.FPS.ToString("F2"); - context.DrawTexture( - _burger, - Mouse.GetPosition() + _burger.Center + new Vector2(0, 5 * MathF.Sin(_wave)), - Vector2.One, - _burger.Center, - _rotation - ); - } + _wave += 10 * delta; + _rotation += 50 * delta; - protected override void Update(float delta) + for (var y = 0; y < _dynTex.Height; y++) { - Window.Title = PerformanceCounter.FPS.ToString("F2"); - - _wave += 10 * delta; - _rotation += 50 * delta; - - for (var y = 0; y < _dynTex.Height; y++) + for (var x = 0; x < _dynTex.Width; x++) { - for (var x = 0; x < _dynTex.Width; x++) - { - var mod = x / (y + 1); + var mod = x / (y + 1); - if (y > 127) - mod = (x / 2) * (y / 2); + if (y > 127) + mod = (x / 2) * (y / 2); - if (x > 127) - mod = (x + y) / 2; + if (x > 127) + mod = (x + y) / 2; - if (x > 127 && y < 127) - mod = (int)(Math.Abs(x / 2 - y / 2) + (5 * MathF.Sin(_wave))); + if (x > 127 && y < 127) + mod = (int)(Math.Abs(x / 2 - y / 2) + (5 * MathF.Sin(_wave))); - _dynTex[x, y] = _colors[Math.Abs(((int)PerformanceCounter.LifetimeFrames + mod) % _colors.Length)]; - } + _dynTex[x, y] = _colors[Math.Abs(((int)PerformanceCounter.LifetimeFrames + mod) % _colors.Length)]; } } + } - protected override void KeyPressed(KeyEventArgs e) + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.Right) { - if (e.KeyCode == KeyCode.Right) - { - _currentTileIndex++; - _currentTileIndex %= _totalTiles; - } - else if (e.KeyCode == KeyCode.Left) - { - _currentTileIndex--; + _currentTileIndex++; + _currentTileIndex %= _totalTiles; + } + else if (e.KeyCode == KeyCode.Left) + { + _currentTileIndex--; - if (_currentTileIndex < 0) - _currentTileIndex = _totalTiles - 1; - } - else if (e.KeyCode == KeyCode.NumPlus) - { - _burger.VirtualResolution = _virtRes = new Size(_virtRes.Width + 32, _virtRes.Height + 32); - } - else if (e.KeyCode == KeyCode.NumMinus) - { - if (_virtRes.Width <= 0 || _virtRes.Height <= 0) return; + if (_currentTileIndex < 0) + _currentTileIndex = _totalTiles - 1; + } + else if (e.KeyCode == KeyCode.NumPlus) + { + _burger.VirtualResolution = _virtRes = new Size(_virtRes.Width + 32, _virtRes.Height + 32); + } + else if (e.KeyCode == KeyCode.NumMinus) + { + if (_virtRes.Width <= 0 || _virtRes.Height <= 0) return; - _burger.VirtualResolution = _virtRes = new Size(_virtRes.Width - 32, _virtRes.Height - 32); - } - else if (e.KeyCode == KeyCode.F1) - { - _burger.VirtualResolution = _virtRes = new Size(_burger.Width, _burger.Height); - } - else if (e.KeyCode == KeyCode.F2) - { - _burger.SetBlendingMode(BlendingPreset.Add); - } - else if (e.KeyCode == KeyCode.F3) - { - _burger.SetBlendingFunctions( - BlendingFunction.One, - BlendingFunction.OneMinusSourceAlpha, - BlendingFunction.DestinationAlpha, - BlendingFunction.One - ); - - _burger.SetBlendingEquations( - BlendingEquation.ReverseSubtract, - BlendingEquation.ReverseSubtract - ); - } - else if (e.KeyCode == KeyCode.F4) - { - _burger.SetBlendingMode(BlendingPreset.Multiply); - } - else if (e.KeyCode == KeyCode.F5) - { - _burger.SetBlendingMode(BlendingPreset.Normal); - } - else if (e.KeyCode == KeyCode.F6) - { - _dynTex.Save("dyntex.png", ImageFileFormat.PNG); - } + _burger.VirtualResolution = _virtRes = new Size(_virtRes.Width - 32, _virtRes.Height - 32); + } + else if (e.KeyCode == KeyCode.F1) + { + _burger.VirtualResolution = _virtRes = new Size(_burger.Width, _burger.Height); + } + else if (e.KeyCode == KeyCode.F2) + { + _burger.SetBlendingMode(BlendingPreset.Add); + } + else if (e.KeyCode == KeyCode.F3) + { + _burger.SetBlendingFunctions( + BlendingFunction.One, + BlendingFunction.OneMinusSourceAlpha, + BlendingFunction.DestinationAlpha, + BlendingFunction.One + ); + + _burger.SetBlendingEquations( + BlendingEquation.ReverseSubtract, + BlendingEquation.ReverseSubtract + ); + } + else if (e.KeyCode == KeyCode.F4) + { + _burger.SetBlendingMode(BlendingPreset.Multiply); + } + else if (e.KeyCode == KeyCode.F5) + { + _burger.SetBlendingMode(BlendingPreset.Normal); + } + else if (e.KeyCode == KeyCode.F6) + { + _dynTex.Save("dyntex.png", ImageFileFormat.PNG); } } } \ No newline at end of file diff --git a/Chroma.Examples/Textures/Program.cs b/Chroma.Examples/Textures/Program.cs index a7fe2029..8eb47aa1 100644 --- a/Chroma.Examples/Textures/Program.cs +++ b/Chroma.Examples/Textures/Program.cs @@ -1,3 +1,4 @@ using Textures; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file diff --git a/Chroma.Examples/WindowOperations/GameCore.cs b/Chroma.Examples/WindowOperations/GameCore.cs index f068751e..f7545712 100644 --- a/Chroma.Examples/WindowOperations/GameCore.cs +++ b/Chroma.Examples/WindowOperations/GameCore.cs @@ -1,4 +1,6 @@ -using System; +namespace WindowOperations; + +using System; using System.Diagnostics; using System.Drawing; using System.Numerics; @@ -12,212 +14,209 @@ using Chroma.Windowing.DragDrop; using Color = Chroma.Graphics.Color; -namespace WindowOperations +public class GameCore : Game { - public class GameCore : Game - { - private static readonly Log _log = LogManager.GetForCurrentAssembly(); + private static readonly Log _log = LogManager.GetForCurrentAssembly(); + + private bool _drawCenterVector; + private int _lastResult; - private bool _drawCenterVector; - private int _lastResult; + private string _diagText; - private string _diagText; + private string _lastDroppedText; + private string _lastDroppedFileList; + + public GameCore() : base(new(false, false)) + { + Window.FilesDropped += WindowOnFilesDropped; + Window.TextDropped += WindowOnTextDropped; - private string _lastDroppedText; - private string _lastDroppedFileList; + var sb = new StringBuilder(); - public GameCore() : base(new(false, false)) + var exts = Graphics.GlExtensions; + for (var i = 0; i < exts.Count; i++) { - Window.FilesDropped += WindowOnFilesDropped; - Window.TextDropped += WindowOnTextDropped; + _log.Info(exts[i]); + } - var sb = new StringBuilder(); + var displays = Graphics.GetDisplayList(); - var exts = Graphics.GlExtensions; - for (var i = 0; i < exts.Count; i++) - { - _log.Info(exts[i]); - } + for (var i = 0; i < displays.Count; i++) + { + sb.AppendLine($"Display {i} DPI: {displays[i].DPI}"); + sb.AppendLine($"Display {i} Bounds: {displays[i].Bounds}"); + sb.AppendLine($"Display {i} Desktop Bounds: {displays[i].DesktopBounds}"); - var displays = Graphics.GetDisplayList(); + sb.AppendLine($"Display {i} supports:"); + var modes = displays[i].QuerySupportedDisplayModes(); - for (var i = 0; i < displays.Count; i++) - { - sb.AppendLine($"Display {i} DPI: {displays[i].DPI}"); - sb.AppendLine($"Display {i} Bounds: {displays[i].Bounds}"); - sb.AppendLine($"Display {i} Desktop Bounds: {displays[i].DesktopBounds}"); + foreach (var m in modes) + sb.AppendLine($" {m.Width}x{m.Height}@{m.RefreshRate}"); + } - sb.AppendLine($"Display {i} supports:"); - var modes = displays[i].QuerySupportedDisplayModes(); + _log.Info(sb.ToString()); + } - foreach (var m in modes) - sb.AppendLine($" {m.Width}x{m.Height}@{m.RefreshRate}"); - } + private void WindowOnTextDropped(object sender, TextDragDropEventArgs e) + { + _lastDroppedText = e.Text; + _log.Info($"Text has been dropped onto the game window:\n{e.Text}."); + } - _log.Info(sb.ToString()); - } + private void WindowOnFilesDropped(object sender, FileDragDropEventArgs e) + { + _lastDroppedFileList = string.Join('\n', e.Files); + _log.Info($"Files have been dropped onto the game window:\n{_lastDroppedFileList}."); + } - private void WindowOnTextDropped(object sender, TextDragDropEventArgs e) + protected override void Draw(RenderContext context) + { + if (_drawCenterVector) { - _lastDroppedText = e.Text; - _log.Info($"Text has been dropped onto the game window:\n{e.Text}."); + context.Line( + Mouse.GetPosition(), + Window.Center, + Color.Lime + ); } - private void WindowOnFilesDropped(object sender, FileDragDropEventArgs e) + context.DrawString( + $"Use to toggle window resizable status ({(Window.CanResize ? "resizable" : "fixed")}).\n" + + $"Use to switch into exclusive fullscreen mode with native resolution: {Window.IsFullScreen}\n" + + $"Use to switch into borderless fullscreen mode with native resolution: {Window.IsBorderlessFullScreen}\n" + + "Use to switch into 1024x600 windowed mode - hold any to center the window afterwards.\n" + + "Use toggle always-on-top status of the window.\n" + + $"Use to toggle window border ({(Window.EnableBorder ? "enabled" : "disabled")}).\n" + + "Use to set maximum window size to 800x600.\n" + + "Use to set minimum window size to 320x240.\n" + + "Use to reset minimum and maximum window sizes.\n" + + $"Use to cycle between display synchronization modes ({Graphics.VerticalSyncMode}).\n" + + $"Use to show a cross-platform message box (last result: {_lastResult}).\n" + + "Use to toggle the center vector on/off.\n" + + $"Use <~> to toggle window hit testing ({Window.IsHitTestEnabled}).\n\n" + + $"Current screen position: {Window.Position}\n" + + $"Current viewport resolution: {Window.Width}x{Window.Height}\n" + + $"Maximum screen dimensions: {Window.MaximumWidth}x{Window.MaximumHeight}\n" + + $"Minimum screen dimensions: {Window.MinimumWidth}x{Window.MinimumHeight}\n" + + $"Has keyboard focus: {Window.HasKeyboardFocus}\n" + + $"Is mouse over: {Window.IsMouseOver}\n" + + $"Last dropped file: {_lastDroppedFileList}\n" + + $"Last dropped text: {_lastDroppedText}\n" + + $"System window handle: {Window.SystemWindowHandle:X8}\n" + + $"{_diagText}", + new Vector2(8) + ); + } + + protected override void Update(float delta) + { + _diagText = + $"FPS: {PerformanceCounter.FPS}, frame {PerformanceCounter.LifetimeFrames}. On display: {Window.CurrentDisplay.Index}\n" + + $"Total memory usage: {Process.GetCurrentProcess().PrivateMemorySize64} bytes ({Process.GetCurrentProcess().PrivateMemorySize64 / 1024 / 1024} MB)"; + } + + protected override void KeyPressed(KeyEventArgs e) + { + if (e.KeyCode == KeyCode.F1) { - _lastDroppedFileList = string.Join('\n', e.Files); - _log.Info($"Files have been dropped onto the game window:\n{_lastDroppedFileList}."); + Window.CanResize = !Window.CanResize; } - - protected override void Draw(RenderContext context) + else if (e.KeyCode == KeyCode.F2) { - if (_drawCenterVector) - { - context.Line( - Mouse.GetPosition(), - Window.Center, - Color.Lime - ); - } - - context.DrawString( - $"Use to toggle window resizable status ({(Window.CanResize ? "resizable" : "fixed")}).\n" + - $"Use to switch into exclusive fullscreen mode with native resolution: {Window.IsFullScreen}\n" + - $"Use to switch into borderless fullscreen mode with native resolution: {Window.IsBorderlessFullScreen}\n" + - "Use to switch into 1024x600 windowed mode - hold any to center the window afterwards.\n" + - "Use toggle always-on-top status of the window.\n" + - $"Use to toggle window border ({(Window.EnableBorder ? "enabled" : "disabled")}).\n" + - "Use to set maximum window size to 800x600.\n" + - "Use to set minimum window size to 320x240.\n" + - "Use to reset minimum and maximum window sizes.\n" + - $"Use to cycle between display synchronization modes ({Graphics.VerticalSyncMode}).\n" + - $"Use to show a cross-platform message box (last result: {_lastResult}).\n" + - "Use to toggle the center vector on/off.\n" + - $"Use <~> to toggle window hit testing ({Window.IsHitTestEnabled}).\n\n" + - $"Current screen position: {Window.Position}\n" + - $"Current viewport resolution: {Window.Width}x{Window.Height}\n" + - $"Maximum screen dimensions: {Window.MaximumWidth}x{Window.MaximumHeight}\n" + - $"Minimum screen dimensions: {Window.MinimumWidth}x{Window.MinimumHeight}\n" + - $"Has keyboard focus: {Window.HasKeyboardFocus}\n" + - $"Is mouse over: {Window.IsMouseOver}\n" + - $"Last dropped file: {_lastDroppedFileList}\n" + - $"Last dropped text: {_lastDroppedText}\n" + - $"System window handle: {Window.SystemWindowHandle:X8}\n" + - $"{_diagText}", - new Vector2(8) + Window.Mode.SetExclusiveFullScreen(Window.CurrentDisplay.DesktopMode); + } + else if (e.KeyCode == KeyCode.F3) + { + Window.Mode.SetBorderlessFullScreen(); + } + else if (e.KeyCode == KeyCode.F4) + { + Window.Mode.SetWindowed( + new Size(1024, 600), + e.IsAnyShiftPressed ); } - - protected override void Update(float delta) + else if (e.KeyCode == KeyCode.F5) { - _diagText = - $"FPS: {PerformanceCounter.FPS}, frame {PerformanceCounter.LifetimeFrames}. On display: {Window.CurrentDisplay.Index}\n" + - $"Total memory usage: {Process.GetCurrentProcess().PrivateMemorySize64} bytes ({Process.GetCurrentProcess().PrivateMemorySize64 / 1024 / 1024} MB)"; + Window.TopMost = !Window.TopMost; } - - protected override void KeyPressed(KeyEventArgs e) + else if (e.KeyCode == KeyCode.F6) { - if (e.KeyCode == KeyCode.F1) - { - Window.CanResize = !Window.CanResize; - } - else if (e.KeyCode == KeyCode.F2) - { - Window.Mode.SetExclusiveFullScreen(Window.CurrentDisplay.DesktopMode); - } - else if (e.KeyCode == KeyCode.F3) - { - Window.Mode.SetBorderlessFullScreen(); - } - else if (e.KeyCode == KeyCode.F4) - { - Window.Mode.SetWindowed( - new Size(1024, 600), - e.IsAnyShiftPressed - ); - } - else if (e.KeyCode == KeyCode.F5) - { - Window.TopMost = !Window.TopMost; - } - else if (e.KeyCode == KeyCode.F6) - { - Window.EnableBorder = !Window.EnableBorder; - } - else if (e.KeyCode == KeyCode.F7) - { - Window.MaximumSize = new Size(800, 600); - } - else if (e.KeyCode == KeyCode.F8) - { - Window.MinimumSize = new Size(320, 240); - } - else if (e.KeyCode == KeyCode.F9) - { - Window.MaximumSize = Window.MinimumSize = Size.Empty; - } - else if (e.KeyCode == KeyCode.F10) - { - if (Graphics.VerticalSyncMode == VerticalSyncMode.Adaptive) - { - Graphics.VerticalSyncMode = VerticalSyncMode.None; - } - else if (Graphics.VerticalSyncMode == VerticalSyncMode.None) - { - Graphics.VerticalSyncMode = VerticalSyncMode.Retrace; - } - else if (Graphics.VerticalSyncMode == VerticalSyncMode.Retrace) - { - Graphics.VerticalSyncMode = VerticalSyncMode.Adaptive; - } - } - else if (e.KeyCode == KeyCode.Space) + Window.EnableBorder = !Window.EnableBorder; + } + else if (e.KeyCode == KeyCode.F7) + { + Window.MaximumSize = new Size(800, 600); + } + else if (e.KeyCode == KeyCode.F8) + { + Window.MinimumSize = new Size(320, 240); + } + else if (e.KeyCode == KeyCode.F9) + { + Window.MaximumSize = Window.MinimumSize = Size.Empty; + } + else if (e.KeyCode == KeyCode.F10) + { + if (Graphics.VerticalSyncMode == VerticalSyncMode.Adaptive) { - _drawCenterVector = !_drawCenterVector; + Graphics.VerticalSyncMode = VerticalSyncMode.None; } - else if (e.KeyCode == KeyCode.F11) + else if (Graphics.VerticalSyncMode == VerticalSyncMode.None) { - _lastResult = new MessageBox(MessageBoxSeverity.Information) - .Titled("Test message box") - .WithMessage("This is a test message. For testing!") - .WithButton("Alright?") - .WithButton("Okay...", _ => _drawCenterVector = true) - .WithButton("/shrug", _ => _drawCenterVector = false) - .HandleAbnormalClosureWith(() => Console.WriteLine("Fukc. MessageBox closed abnormally.")) - .Show(Window); + Graphics.VerticalSyncMode = VerticalSyncMode.Retrace; } - else if (e.KeyCode == KeyCode.F12) + else if (Graphics.VerticalSyncMode == VerticalSyncMode.Retrace) { - if (e.Modifiers.HasFlag(KeyModifiers.LeftShift)) - { - Window.Flash(WindowFlash.Continuous); - } - else - { - MessageBox.Show( - MessageBoxSeverity.Error, - "A test error message box.", - "This is a test message to let you know about the error.", - Window - ); - } + Graphics.VerticalSyncMode = VerticalSyncMode.Adaptive; } - else if (e.KeyCode == KeyCode.Tilde) + } + else if (e.KeyCode == KeyCode.Space) + { + _drawCenterVector = !_drawCenterVector; + } + else if (e.KeyCode == KeyCode.F11) + { + _lastResult = new MessageBox(MessageBoxSeverity.Information) + .Titled("Test message box") + .WithMessage("This is a test message. For testing!") + .WithButton("Alright?") + .WithButton("Okay...", _ => _drawCenterVector = true) + .WithButton("/shrug", _ => _drawCenterVector = false) + .HandleAbnormalClosureWith(() => Console.WriteLine("Fukc. MessageBox closed abnormally.")) + .Show(Window); + } + else if (e.KeyCode == KeyCode.F12) + { + if (e.Modifiers.HasFlag(KeyModifiers.LeftShift)) { - if (Window.IsHitTestEnabled) - Window.HitTest = null; - else - Window.HitTest = HitTest; + Window.Flash(WindowFlash.Continuous); } - else if (e.KeyCode == KeyCode.LeftBracket) + else { - Window.SaveScreenshot("screenshot.bmp"); + MessageBox.Show( + MessageBoxSeverity.Error, + "A test error message box.", + "This is a test message to let you know about the error.", + Window + ); } } - - private WindowHitTestResult HitTest(Window window, Vector2 position) + else if (e.KeyCode == KeyCode.Tilde) { - return WindowHitTestResult.Draggable; + if (Window.IsHitTestEnabled) + Window.HitTest = null; + else + Window.HitTest = HitTest; } + else if (e.KeyCode == KeyCode.LeftBracket) + { + Window.SaveScreenshot("screenshot.bmp"); + } + } + + private WindowHitTestResult HitTest(Window window, Vector2 position) + { + return WindowHitTestResult.Draggable; } } \ No newline at end of file diff --git a/Chroma.Examples/WindowOperations/Program.cs b/Chroma.Examples/WindowOperations/Program.cs index 96ff1c51..a1e987ff 100644 --- a/Chroma.Examples/WindowOperations/Program.cs +++ b/Chroma.Examples/WindowOperations/Program.cs @@ -1,3 +1,4 @@ using WindowOperations; -new GameCore().Run(); \ No newline at end of file +using (var game = new GameCore()) + game.Run(); \ No newline at end of file