From 8973b3e658b72a609a56af5540cab9dc152524f9 Mon Sep 17 00:00:00 2001 From: cosmonaut Date: Tue, 22 Feb 2022 21:14:32 -0800 Subject: [PATCH] Formatting pass --- .editorconfig | 14 + src/Audio/AudioDevice.cs | 444 ++--- src/Audio/AudioEmitter.cs | 32 +- src/Audio/AudioListener.cs | 30 +- src/Audio/AudioResource.cs | 76 +- src/Audio/SoundInstance.cs | 486 ++--- src/Audio/SoundState.cs | 14 +- src/Audio/StaticSound.cs | 132 +- src/Audio/StaticSoundInstance.cs | 164 +- src/Audio/StreamingSound.cs | 300 +-- src/Audio/StreamingSoundOgg.cs | 144 +- src/Exceptions/AudioLoadException.cs | 14 +- src/Game.cs | 219 +-- src/Graphics/Bindings/BufferBinding.cs | 22 +- .../Bindings/TextureSamplerBinding.cs | 20 +- src/Graphics/Color.cs | 44 +- src/Graphics/CommandBuffer.cs | 1639 +++++++++-------- src/Graphics/GraphicsDevice.cs | 173 +- src/Graphics/GraphicsResource.cs | 74 +- src/Graphics/PackedVector/Alpha8.cs | 2 +- src/Graphics/PackedVector/Bgr565.cs | 2 +- src/Graphics/PackedVector/Bgra4444.cs | 2 +- src/Graphics/PackedVector/Bgra5551.cs | 2 +- src/Graphics/PackedVector/Byte4.cs | 2 +- src/Graphics/PackedVector/HalfSingle.cs | 2 +- src/Graphics/PackedVector/HalfTypeHelper.cs | 4 +- src/Graphics/PackedVector/HalfVector2.cs | 2 +- src/Graphics/PackedVector/HalfVector4.cs | 2 +- src/Graphics/PackedVector/IPackedVector.cs | 2 +- src/Graphics/PackedVector/NormalizedByte2.cs | 2 +- src/Graphics/PackedVector/NormalizedByte4.cs | 2 +- src/Graphics/PackedVector/NormalizedShort2.cs | 2 +- src/Graphics/PackedVector/NormalizedShort4.cs | 2 +- src/Graphics/PackedVector/Rg32.cs | 2 +- src/Graphics/PackedVector/Rgba1010102.cs | 2 +- src/Graphics/PackedVector/Rgba64.cs | 2 +- src/Graphics/PackedVector/Short2.cs | 2 +- src/Graphics/PackedVector/Short4.cs | 4 +- src/Graphics/RefreshEnums.cs | 530 +++--- src/Graphics/RefreshStructs.cs | 202 +- src/Graphics/Resources/Buffer.cs | 94 +- src/Graphics/Resources/ComputePipeline.cs | 65 +- src/Graphics/Resources/Framebuffer.cs | 130 +- src/Graphics/Resources/GraphicsPipeline.cs | 214 +-- src/Graphics/Resources/RenderPass.cs | 96 +- src/Graphics/Resources/RenderTarget.cs | 154 +- src/Graphics/Resources/Sampler.cs | 36 +- src/Graphics/Resources/ShaderModule.cs | 36 +- src/Graphics/Resources/Texture.cs | 349 ++-- src/Graphics/State/ColorBlendState.cs | 24 +- src/Graphics/State/ColorTargetBlendState.cs | 206 +-- src/Graphics/State/DepthStencilState.cs | 132 +- .../State/GraphicsPipelineCreateInfo.cs | 30 +- .../State/GraphicsPipelineLayoutInfo.cs | 18 +- src/Graphics/State/MultisampleState.cs | 28 +- src/Graphics/State/RasterizerState.cs | 208 +-- src/Graphics/State/SamplerCreateInfo.cs | 246 +-- src/Graphics/State/ShaderStageState.cs | 20 +- src/Graphics/State/TextureCreateInfo.cs | 50 +- src/Graphics/State/VertexInputState.cs | 18 +- src/Graphics/State/ViewportState.cs | 18 +- src/Graphics/Structs/BlendConstants.cs | 16 +- src/Graphics/TextureSlice.cs | 92 +- src/Graphics/Utility/Bytecode.cs | 52 +- src/Graphics/Utility/Conversions.cs | 24 +- src/Input/ButtonState.cs | 54 +- src/Input/ButtonStatus.cs | 32 +- src/Input/Gamepad.cs | 164 +- src/Input/Input.cs | 90 +- src/Input/Keyboard.cs | 116 +- src/Input/Keycode.cs | 222 +-- src/Input/Mouse.cs | 82 +- src/Logger.cs | 110 +- src/Math/BoundingBox.cs | 22 +- src/Math/BoundingFrustum.cs | 29 +- src/Math/BoundingSphere.cs | 9 +- src/Math/ContainmentType.cs | 2 +- src/Math/MathHelper.cs | 11 +- src/Math/Matrix3x2.cs | 1624 ++++++++-------- src/Math/Matrix4x4.cs | 91 +- src/Math/Plane.cs | 8 +- src/Math/PlaneIntersectionType.cs | 2 +- src/Math/Point.cs | 2 +- src/Math/Quaternion.cs | 68 +- src/Math/Ray.cs | 14 +- src/Math/Rectangle.cs | 41 +- src/Math/Vector2.cs | 67 +- src/Math/Vector3.cs | 84 +- src/Math/Vector4.cs | 64 +- src/MoonWorksDllMap.cs | 7 +- src/Window/OSWindow.cs | 100 +- src/Window/ScreenMode.cs | 14 +- src/Window/WindowCreateInfo.cs | 16 +- 93 files changed, 5236 insertions(+), 5080 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..b7f51b63 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +[*] +indent_style = tab +insert_final_newline = true +trim_trailing_whitespace = true + +[*.cs] +csharp_space_after_cast = true +charset = utf-8-bom +max_line_length = 100 diff --git a/src/Audio/AudioDevice.cs b/src/Audio/AudioDevice.cs index ebff250b..9dbb52be 100644 --- a/src/Audio/AudioDevice.cs +++ b/src/Audio/AudioDevice.cs @@ -1,277 +1,277 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace MoonWorks.Audio { - public class AudioDevice : IDisposable - { - public IntPtr Handle { get; } - public byte[] Handle3D { get; } - public IntPtr MasteringVoice { get; } - public FAudio.FAudioDeviceDetails DeviceDetails { get; } - public IntPtr ReverbVoice { get; } + public class AudioDevice : IDisposable + { + public IntPtr Handle { get; } + public byte[] Handle3D { get; } + public IntPtr MasteringVoice { get; } + public FAudio.FAudioDeviceDetails DeviceDetails { get; } + public IntPtr ReverbVoice { get; } - public float CurveDistanceScalar = 1f; - public float DopplerScale = 1f; - public float SpeedOfSound = 343.5f; + public float CurveDistanceScalar = 1f; + public float DopplerScale = 1f; + public float SpeedOfSound = 343.5f; - internal FAudio.FAudioVoiceSends ReverbSends; + internal FAudio.FAudioVoiceSends ReverbSends; - private readonly List> resources = new List>(); - private readonly List> streamingSounds = new List>(); + private readonly List> resources = new List>(); + private readonly List> streamingSounds = new List>(); - private bool IsDisposed; + private bool IsDisposed; - public unsafe AudioDevice() - { - FAudio.FAudioCreate(out var handle, 0, 0); - Handle = handle; + public unsafe AudioDevice() + { + FAudio.FAudioCreate(out var handle, 0, 0); + Handle = handle; - /* Find a suitable device */ + /* Find a suitable device */ - FAudio.FAudio_GetDeviceCount(Handle, out var devices); + FAudio.FAudio_GetDeviceCount(Handle, out var devices); - if (devices == 0) - { - Logger.LogError("No audio devices found!"); - Handle = IntPtr.Zero; - FAudio.FAudio_Release(Handle); - return; - } + if (devices == 0) + { + Logger.LogError("No audio devices found!"); + Handle = IntPtr.Zero; + FAudio.FAudio_Release(Handle); + return; + } - FAudio.FAudioDeviceDetails deviceDetails; + FAudio.FAudioDeviceDetails deviceDetails; - uint i = 0; - for (i = 0; i < devices; i++) - { - FAudio.FAudio_GetDeviceDetails( - Handle, - i, - out deviceDetails - ); - if ((deviceDetails.Role & FAudio.FAudioDeviceRole.FAudioDefaultGameDevice) == FAudio.FAudioDeviceRole.FAudioDefaultGameDevice) - { - DeviceDetails = deviceDetails; - break; - } - } + uint i = 0; + for (i = 0; i < devices; i++) + { + FAudio.FAudio_GetDeviceDetails( + Handle, + i, + out deviceDetails + ); + if ((deviceDetails.Role & FAudio.FAudioDeviceRole.FAudioDefaultGameDevice) == FAudio.FAudioDeviceRole.FAudioDefaultGameDevice) + { + DeviceDetails = deviceDetails; + break; + } + } - if (i == devices) - { - i = 0; /* whatever we'll just use the first one I guess */ - FAudio.FAudio_GetDeviceDetails( - Handle, - i, - out deviceDetails - ); - DeviceDetails = deviceDetails; - } + if (i == devices) + { + i = 0; /* whatever we'll just use the first one I guess */ + FAudio.FAudio_GetDeviceDetails( + Handle, + i, + out deviceDetails + ); + DeviceDetails = deviceDetails; + } - /* Init Mastering Voice */ - IntPtr masteringVoice; + /* Init Mastering Voice */ + IntPtr masteringVoice; - if (FAudio.FAudio_CreateMasteringVoice( - Handle, - out masteringVoice, - FAudio.FAUDIO_DEFAULT_CHANNELS, - FAudio.FAUDIO_DEFAULT_SAMPLERATE, - 0, - i, - IntPtr.Zero - ) != 0) - { - Logger.LogError("No mastering voice found!"); - Handle = IntPtr.Zero; - FAudio.FAudio_Release(Handle); - return; - } + if (FAudio.FAudio_CreateMasteringVoice( + Handle, + out masteringVoice, + FAudio.FAUDIO_DEFAULT_CHANNELS, + FAudio.FAUDIO_DEFAULT_SAMPLERATE, + 0, + i, + IntPtr.Zero + ) != 0) + { + Logger.LogError("No mastering voice found!"); + Handle = IntPtr.Zero; + FAudio.FAudio_Release(Handle); + return; + } - MasteringVoice = masteringVoice; + MasteringVoice = masteringVoice; - /* Init 3D Audio */ + /* Init 3D Audio */ - Handle3D = new byte[FAudio.F3DAUDIO_HANDLE_BYTESIZE]; - FAudio.F3DAudioInitialize( - DeviceDetails.OutputFormat.dwChannelMask, - SpeedOfSound, - Handle3D - ); + Handle3D = new byte[FAudio.F3DAUDIO_HANDLE_BYTESIZE]; + FAudio.F3DAudioInitialize( + DeviceDetails.OutputFormat.dwChannelMask, + SpeedOfSound, + Handle3D + ); - /* Init reverb */ + /* Init reverb */ - IntPtr reverbVoice; + IntPtr reverbVoice; - IntPtr reverb; - FAudio.FAudioCreateReverb(out reverb, 0); + IntPtr reverb; + FAudio.FAudioCreateReverb(out reverb, 0); - IntPtr chainPtr; - chainPtr = Marshal.AllocHGlobal( - Marshal.SizeOf() - ); + IntPtr chainPtr; + chainPtr = Marshal.AllocHGlobal( + Marshal.SizeOf() + ); - FAudio.FAudioEffectChain* reverbChain = (FAudio.FAudioEffectChain*) chainPtr; - reverbChain->EffectCount = 1; - reverbChain->pEffectDescriptors = Marshal.AllocHGlobal( - Marshal.SizeOf() - ); + FAudio.FAudioEffectChain* reverbChain = (FAudio.FAudioEffectChain*) chainPtr; + reverbChain->EffectCount = 1; + reverbChain->pEffectDescriptors = Marshal.AllocHGlobal( + Marshal.SizeOf() + ); - FAudio.FAudioEffectDescriptor* reverbDescriptor = - (FAudio.FAudioEffectDescriptor*) reverbChain->pEffectDescriptors; + FAudio.FAudioEffectDescriptor* reverbDescriptor = + (FAudio.FAudioEffectDescriptor*) reverbChain->pEffectDescriptors; - reverbDescriptor->InitialState = 1; - reverbDescriptor->OutputChannels = (uint) ( - (DeviceDetails.OutputFormat.Format.nChannels == 6) ? 6 : 1 - ); - reverbDescriptor->pEffect = reverb; + reverbDescriptor->InitialState = 1; + reverbDescriptor->OutputChannels = (uint) ( + (DeviceDetails.OutputFormat.Format.nChannels == 6) ? 6 : 1 + ); + reverbDescriptor->pEffect = reverb; - FAudio.FAudio_CreateSubmixVoice( - Handle, - out reverbVoice, - 1, /* omnidirectional reverb */ - DeviceDetails.OutputFormat.Format.nSamplesPerSec, - 0, - 0, - IntPtr.Zero, - chainPtr - ); - FAudio.FAPOBase_Release(reverb); + FAudio.FAudio_CreateSubmixVoice( + Handle, + out reverbVoice, + 1, /* omnidirectional reverb */ + DeviceDetails.OutputFormat.Format.nSamplesPerSec, + 0, + 0, + IntPtr.Zero, + chainPtr + ); + FAudio.FAPOBase_Release(reverb); - Marshal.FreeHGlobal(reverbChain->pEffectDescriptors); - Marshal.FreeHGlobal(chainPtr); + Marshal.FreeHGlobal(reverbChain->pEffectDescriptors); + Marshal.FreeHGlobal(chainPtr); - ReverbVoice = reverbVoice; + ReverbVoice = reverbVoice; - /* Init reverb params */ - // Defaults based on FAUDIOFX_I3DL2_PRESET_GENERIC + /* Init reverb params */ + // Defaults based on FAUDIOFX_I3DL2_PRESET_GENERIC - IntPtr reverbParamsPtr = Marshal.AllocHGlobal( - Marshal.SizeOf() - ); + IntPtr reverbParamsPtr = Marshal.AllocHGlobal( + Marshal.SizeOf() + ); - FAudio.FAudioFXReverbParameters* reverbParams = (FAudio.FAudioFXReverbParameters*) reverbParamsPtr; - reverbParams->WetDryMix = 100.0f; - reverbParams->ReflectionsDelay = 7; - reverbParams->ReverbDelay = 11; - reverbParams->RearDelay = FAudio.FAUDIOFX_REVERB_DEFAULT_REAR_DELAY; - reverbParams->PositionLeft = FAudio.FAUDIOFX_REVERB_DEFAULT_POSITION; - reverbParams->PositionRight = FAudio.FAUDIOFX_REVERB_DEFAULT_POSITION; - reverbParams->PositionMatrixLeft = FAudio.FAUDIOFX_REVERB_DEFAULT_POSITION_MATRIX; - reverbParams->PositionMatrixRight = FAudio.FAUDIOFX_REVERB_DEFAULT_POSITION_MATRIX; - reverbParams->EarlyDiffusion = 15; - reverbParams->LateDiffusion = 15; - reverbParams->LowEQGain = 8; - reverbParams->LowEQCutoff = 4; - reverbParams->HighEQGain = 8; - reverbParams->HighEQCutoff = 6; - reverbParams->RoomFilterFreq = 5000f; - reverbParams->RoomFilterMain = -10f; - reverbParams->RoomFilterHF = -1f; - reverbParams->ReflectionsGain = -26.0200005f; - reverbParams->ReverbGain = 10.0f; - reverbParams->DecayTime = 1.49000001f; - reverbParams->Density = 100.0f; - reverbParams->RoomSize = FAudio.FAUDIOFX_REVERB_DEFAULT_ROOM_SIZE; - FAudio.FAudioVoice_SetEffectParameters( - ReverbVoice, - 0, - reverbParamsPtr, - (uint) Marshal.SizeOf(), - 0 - ); - Marshal.FreeHGlobal(reverbParamsPtr); + FAudio.FAudioFXReverbParameters* reverbParams = (FAudio.FAudioFXReverbParameters*) reverbParamsPtr; + reverbParams->WetDryMix = 100.0f; + reverbParams->ReflectionsDelay = 7; + reverbParams->ReverbDelay = 11; + reverbParams->RearDelay = FAudio.FAUDIOFX_REVERB_DEFAULT_REAR_DELAY; + reverbParams->PositionLeft = FAudio.FAUDIOFX_REVERB_DEFAULT_POSITION; + reverbParams->PositionRight = FAudio.FAUDIOFX_REVERB_DEFAULT_POSITION; + reverbParams->PositionMatrixLeft = FAudio.FAUDIOFX_REVERB_DEFAULT_POSITION_MATRIX; + reverbParams->PositionMatrixRight = FAudio.FAUDIOFX_REVERB_DEFAULT_POSITION_MATRIX; + reverbParams->EarlyDiffusion = 15; + reverbParams->LateDiffusion = 15; + reverbParams->LowEQGain = 8; + reverbParams->LowEQCutoff = 4; + reverbParams->HighEQGain = 8; + reverbParams->HighEQCutoff = 6; + reverbParams->RoomFilterFreq = 5000f; + reverbParams->RoomFilterMain = -10f; + reverbParams->RoomFilterHF = -1f; + reverbParams->ReflectionsGain = -26.0200005f; + reverbParams->ReverbGain = 10.0f; + reverbParams->DecayTime = 1.49000001f; + reverbParams->Density = 100.0f; + reverbParams->RoomSize = FAudio.FAUDIOFX_REVERB_DEFAULT_ROOM_SIZE; + FAudio.FAudioVoice_SetEffectParameters( + ReverbVoice, + 0, + reverbParamsPtr, + (uint) Marshal.SizeOf(), + 0 + ); + Marshal.FreeHGlobal(reverbParamsPtr); - /* Init reverb sends */ + /* Init reverb sends */ - ReverbSends = new FAudio.FAudioVoiceSends - { - SendCount = 2, - pSends = Marshal.AllocHGlobal( - 2 * Marshal.SizeOf() - ) - }; - FAudio.FAudioSendDescriptor* sendDesc = (FAudio.FAudioSendDescriptor*) ReverbSends.pSends; - sendDesc[0].Flags = 0; - sendDesc[0].pOutputVoice = MasteringVoice; - sendDesc[1].Flags = 0; - sendDesc[1].pOutputVoice = ReverbVoice; - } + ReverbSends = new FAudio.FAudioVoiceSends + { + SendCount = 2, + pSends = Marshal.AllocHGlobal( + 2 * Marshal.SizeOf() + ) + }; + FAudio.FAudioSendDescriptor* sendDesc = (FAudio.FAudioSendDescriptor*) ReverbSends.pSends; + sendDesc[0].Flags = 0; + sendDesc[0].pOutputVoice = MasteringVoice; + sendDesc[1].Flags = 0; + sendDesc[1].pOutputVoice = ReverbVoice; + } - public void Update() - { - for (var i = streamingSounds.Count - 1; i >= 0; i--) - { - var weakReference = streamingSounds[i]; - if (weakReference.TryGetTarget(out var streamingSound)) - { - streamingSound.Update(); - } - else - { - streamingSounds.RemoveAt(i); - } - } - } + public void Update() + { + for (var i = streamingSounds.Count - 1; i >= 0; i--) + { + var weakReference = streamingSounds[i]; + if (weakReference.TryGetTarget(out var streamingSound)) + { + streamingSound.Update(); + } + else + { + streamingSounds.RemoveAt(i); + } + } + } - internal void AddDynamicSoundInstance(StreamingSound instance) - { - streamingSounds.Add(new WeakReference(instance)); - } + internal void AddDynamicSoundInstance(StreamingSound instance) + { + streamingSounds.Add(new WeakReference(instance)); + } - internal void AddResourceReference(WeakReference resourceReference) - { - lock (resources) - { - resources.Add(resourceReference); - } - } + internal void AddResourceReference(WeakReference resourceReference) + { + lock (resources) + { + resources.Add(resourceReference); + } + } - internal void RemoveResourceReference(WeakReference resourceReference) - { - lock (resources) - { - resources.Remove(resourceReference); - } - } + internal void RemoveResourceReference(WeakReference resourceReference) + { + lock (resources) + { + resources.Remove(resourceReference); + } + } - protected virtual void Dispose(bool disposing) - { - if (!IsDisposed) - { - if (disposing) - { + protected virtual void Dispose(bool disposing) + { + if (!IsDisposed) + { + if (disposing) + { for (var i = streamingSounds.Count - 1; i >= 0; i--) { var weakReference = streamingSounds[i]; if (weakReference.TryGetTarget(out var streamingSound)) - { - streamingSound.Dispose(); - } + { + streamingSound.Dispose(); + } } streamingSounds.Clear(); - } + } FAudio.FAudioVoice_DestroyVoice(ReverbVoice); FAudio.FAudioVoice_DestroyVoice(MasteringVoice); - FAudio.FAudio_Release(Handle); + FAudio.FAudio_Release(Handle); - IsDisposed = true; - } - } + IsDisposed = true; + } + } - // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources - ~AudioDevice() - { - // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method - Dispose(disposing: false); - } + // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources + ~AudioDevice() + { + // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method + Dispose(disposing: false); + } - public void Dispose() - { - // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - } + public void Dispose() + { + // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + } } diff --git a/src/Audio/AudioEmitter.cs b/src/Audio/AudioEmitter.cs index 51a9576e..c23becd3 100644 --- a/src/Audio/AudioEmitter.cs +++ b/src/Audio/AudioEmitter.cs @@ -1,12 +1,12 @@ -using System; +using System; using System.Runtime.InteropServices; using MoonWorks.Math; namespace MoonWorks.Audio { - public class AudioEmitter : AudioResource - { - internal FAudio.F3DAUDIO_EMITTER emitterData; + public class AudioEmitter : AudioResource + { + internal FAudio.F3DAUDIO_EMITTER emitterData; public float DopplerScale { @@ -107,17 +107,17 @@ namespace MoonWorks.Audio GCHandleType.Pinned ); - public AudioEmitter(AudioDevice device) : base(device) - { - emitterData = new FAudio.F3DAUDIO_EMITTER(); + public AudioEmitter(AudioDevice device) : base(device) + { + emitterData = new FAudio.F3DAUDIO_EMITTER(); - DopplerScale = 1f; - Forward = Vector3.Forward; - Position = Vector3.Zero; - Up = Vector3.Up; - Velocity = Vector3.Zero; + DopplerScale = 1f; + Forward = Vector3.Forward; + Position = Vector3.Zero; + Up = Vector3.Up; + Velocity = Vector3.Zero; - /* Unexposed variables, defaults based on XNA behavior */ + /* Unexposed variables, defaults based on XNA behavior */ emitterData.pCone = IntPtr.Zero; emitterData.ChannelCount = 1; emitterData.ChannelRadius = 1.0f; @@ -128,8 +128,8 @@ namespace MoonWorks.Audio emitterData.pLPFReverbCurve = IntPtr.Zero; emitterData.pReverbCurve = IntPtr.Zero; emitterData.CurveDistanceScaler = 1.0f; - } + } - protected override void Destroy() { } - } + protected override void Destroy() { } + } } diff --git a/src/Audio/AudioListener.cs b/src/Audio/AudioListener.cs index 67e44baf..0f9e5156 100644 --- a/src/Audio/AudioListener.cs +++ b/src/Audio/AudioListener.cs @@ -1,11 +1,11 @@ -using System; +using System; using MoonWorks.Math; namespace MoonWorks.Audio { - public class AudioListener : AudioResource - { - internal FAudio.F3DAUDIO_LISTENER listenerData; + public class AudioListener : AudioResource + { + internal FAudio.F3DAUDIO_LISTENER listenerData; public Vector3 Forward { @@ -80,18 +80,18 @@ namespace MoonWorks.Audio } } - public AudioListener(AudioDevice device) : base(device) - { - listenerData = new FAudio.F3DAUDIO_LISTENER(); - Forward = Vector3.Forward; - Position = Vector3.Zero; - Up = Vector3.Up; - Velocity = Vector3.Zero; + public AudioListener(AudioDevice device) : base(device) + { + listenerData = new FAudio.F3DAUDIO_LISTENER(); + Forward = Vector3.Forward; + Position = Vector3.Zero; + Up = Vector3.Up; + Velocity = Vector3.Zero; - /* Unexposed variables, defaults based on XNA behavior */ + /* Unexposed variables, defaults based on XNA behavior */ listenerData.pCone = IntPtr.Zero; - } + } - protected override void Destroy() { } - } + protected override void Destroy() { } + } } diff --git a/src/Audio/AudioResource.cs b/src/Audio/AudioResource.cs index e74166f5..edf8b497 100644 --- a/src/Audio/AudioResource.cs +++ b/src/Audio/AudioResource.cs @@ -1,52 +1,52 @@ -using System; +using System; namespace MoonWorks.Audio { - public abstract class AudioResource : IDisposable - { - public AudioDevice Device { get; } + public abstract class AudioResource : IDisposable + { + public AudioDevice Device { get; } - public bool IsDisposed { get; private set; } + public bool IsDisposed { get; private set; } - private WeakReference selfReference; + private WeakReference selfReference; - public AudioResource(AudioDevice device) - { - Device = device; + public AudioResource(AudioDevice device) + { + Device = device; - selfReference = new WeakReference(this); - Device.AddResourceReference(selfReference); - } + selfReference = new WeakReference(this); + Device.AddResourceReference(selfReference); + } - protected abstract void Destroy(); + protected abstract void Destroy(); - protected virtual void Dispose(bool disposing) - { - if (!IsDisposed) - { - Destroy(); + protected virtual void Dispose(bool disposing) + { + if (!IsDisposed) + { + Destroy(); - if (selfReference != null) - { - Device.RemoveResourceReference(selfReference); - selfReference = null; - } + if (selfReference != null) + { + Device.RemoveResourceReference(selfReference); + selfReference = null; + } - IsDisposed = true; - } - } + IsDisposed = true; + } + } - ~AudioResource() - { - // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method - Dispose(disposing: false); - } + ~AudioResource() + { + // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method + Dispose(disposing: false); + } - public void Dispose() - { - // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - } + public void Dispose() + { + // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + } } diff --git a/src/Audio/SoundInstance.cs b/src/Audio/SoundInstance.cs index bf4c028c..9d99697c 100644 --- a/src/Audio/SoundInstance.cs +++ b/src/Audio/SoundInstance.cs @@ -1,271 +1,271 @@ -using System; +using System; using System.Runtime.InteropServices; using MoonWorks.Math; namespace MoonWorks.Audio { - public abstract class SoundInstance : AudioResource - { - internal IntPtr Handle { get; } - internal FAudio.FAudioWaveFormatEx Format { get; } - public bool Loop { get; } + public abstract class SoundInstance : AudioResource + { + internal IntPtr Handle { get; } + internal FAudio.FAudioWaveFormatEx Format { get; } + public bool Loop { get; } - protected FAudio.F3DAUDIO_DSP_SETTINGS dspSettings; + protected FAudio.F3DAUDIO_DSP_SETTINGS dspSettings; - protected bool is3D; + protected bool is3D; - public abstract SoundState State { get; protected set; } + public abstract SoundState State { get; protected set; } - private float _pan = 0; - public float Pan - { - get => _pan; - set - { - _pan = value; + private float _pan = 0; + public float Pan + { + get => _pan; + set + { + _pan = value; - if (_pan < -1f) - { - _pan = -1f; - } - if (_pan > 1f) - { - _pan = 1f; - } + if (_pan < -1f) + { + _pan = -1f; + } + if (_pan > 1f) + { + _pan = 1f; + } - if (is3D) { return; } + if (is3D) { return; } - SetPanMatrixCoefficients(); - FAudio.FAudioVoice_SetOutputMatrix( - Handle, - Device.MasteringVoice, - dspSettings.SrcChannelCount, - dspSettings.DstChannelCount, - dspSettings.pMatrixCoefficients, - 0 - ); - } - } + SetPanMatrixCoefficients(); + FAudio.FAudioVoice_SetOutputMatrix( + Handle, + Device.MasteringVoice, + dspSettings.SrcChannelCount, + dspSettings.DstChannelCount, + dspSettings.pMatrixCoefficients, + 0 + ); + } + } - private float _pitch = 1; - public float Pitch - { - get => _pitch; - set - { - _pitch = MathHelper.Clamp(value, -1f, 1f); - UpdatePitch(); - } - } + private float _pitch = 1; + public float Pitch + { + get => _pitch; + set + { + _pitch = MathHelper.Clamp(value, -1f, 1f); + UpdatePitch(); + } + } - private float _volume = 1; - public float Volume - { - get => _volume; - set - { - _volume = value; - FAudio.FAudioVoice_SetVolume(Handle, _volume, 0); - } - } + private float _volume = 1; + public float Volume + { + get => _volume; + set + { + _volume = value; + FAudio.FAudioVoice_SetVolume(Handle, _volume, 0); + } + } - private float _reverb; - public unsafe float Reverb - { - get => _reverb; - set - { - _reverb = value; + private float _reverb; + public unsafe float Reverb + { + get => _reverb; + set + { + _reverb = value; - float* outputMatrix = (float*) dspSettings.pMatrixCoefficients; - outputMatrix[0] = _reverb; - if (dspSettings.SrcChannelCount == 2) - { - outputMatrix[1] = _reverb; - } + float* outputMatrix = (float*) dspSettings.pMatrixCoefficients; + outputMatrix[0] = _reverb; + if (dspSettings.SrcChannelCount == 2) + { + outputMatrix[1] = _reverb; + } - FAudio.FAudioVoice_SetOutputMatrix( - Handle, - Device.ReverbVoice, - dspSettings.SrcChannelCount, - 1, - dspSettings.pMatrixCoefficients, - 0 - ); - } - } + FAudio.FAudioVoice_SetOutputMatrix( + Handle, + Device.ReverbVoice, + dspSettings.SrcChannelCount, + 1, + dspSettings.pMatrixCoefficients, + 0 + ); + } + } - private float _lowPassFilter; - public float LowPassFilter - { - get => _lowPassFilter; - set - { - _lowPassFilter = value; + private float _lowPassFilter; + public float LowPassFilter + { + get => _lowPassFilter; + set + { + _lowPassFilter = value; - FAudio.FAudioFilterParameters p = new FAudio.FAudioFilterParameters - { - Type = FAudio.FAudioFilterType.FAudioLowPassFilter, - Frequency = _lowPassFilter, - OneOverQ = 1f - }; - FAudio.FAudioVoice_SetFilterParameters( - Handle, - ref p, - 0 - ); - } - } + FAudio.FAudioFilterParameters p = new FAudio.FAudioFilterParameters + { + Type = FAudio.FAudioFilterType.FAudioLowPassFilter, + Frequency = _lowPassFilter, + OneOverQ = 1f + }; + FAudio.FAudioVoice_SetFilterParameters( + Handle, + ref p, + 0 + ); + } + } - private float _highPassFilter; - public float HighPassFilter - { - get => _highPassFilter; - set - { - _highPassFilter = value; + private float _highPassFilter; + public float HighPassFilter + { + get => _highPassFilter; + set + { + _highPassFilter = value; - FAudio.FAudioFilterParameters p = new FAudio.FAudioFilterParameters - { - Type = FAudio.FAudioFilterType.FAudioHighPassFilter, - Frequency = _highPassFilter, - OneOverQ = 1f - }; - FAudio.FAudioVoice_SetFilterParameters( - Handle, - ref p, - 0 - ); - } - } + FAudio.FAudioFilterParameters p = new FAudio.FAudioFilterParameters + { + Type = FAudio.FAudioFilterType.FAudioHighPassFilter, + Frequency = _highPassFilter, + OneOverQ = 1f + }; + FAudio.FAudioVoice_SetFilterParameters( + Handle, + ref p, + 0 + ); + } + } - private float _bandPassFilter; - public float BandPassFilter - { - get => _bandPassFilter; - set - { - _bandPassFilter = value; + private float _bandPassFilter; + public float BandPassFilter + { + get => _bandPassFilter; + set + { + _bandPassFilter = value; - FAudio.FAudioFilterParameters p = new FAudio.FAudioFilterParameters - { - Type = FAudio.FAudioFilterType.FAudioBandPassFilter, - Frequency = _bandPassFilter, - OneOverQ = 1f - }; - FAudio.FAudioVoice_SetFilterParameters( - Handle, - ref p, - 0 - ); - } - } + FAudio.FAudioFilterParameters p = new FAudio.FAudioFilterParameters + { + Type = FAudio.FAudioFilterType.FAudioBandPassFilter, + Frequency = _bandPassFilter, + OneOverQ = 1f + }; + FAudio.FAudioVoice_SetFilterParameters( + Handle, + ref p, + 0 + ); + } + } - public SoundInstance( - AudioDevice device, - ushort channels, - uint samplesPerSecond, - bool is3D, - bool loop - ) : base(device) - { - var blockAlign = (ushort)(4 * channels); - var format = new FAudio.FAudioWaveFormatEx - { - wFormatTag = 3, - wBitsPerSample = 32, - nChannels = channels, - nBlockAlign = blockAlign, - nSamplesPerSec = samplesPerSecond, - nAvgBytesPerSec = blockAlign * samplesPerSecond - }; + public SoundInstance( + AudioDevice device, + ushort channels, + uint samplesPerSecond, + bool is3D, + bool loop + ) : base(device) + { + var blockAlign = (ushort) (4 * channels); + var format = new FAudio.FAudioWaveFormatEx + { + wFormatTag = 3, + wBitsPerSample = 32, + nChannels = channels, + nBlockAlign = blockAlign, + nSamplesPerSec = samplesPerSecond, + nAvgBytesPerSec = blockAlign * samplesPerSecond + }; - Format = format; + Format = format; - FAudio.FAudio_CreateSourceVoice( - Device.Handle, - out var handle, - ref format, - FAudio.FAUDIO_VOICE_USEFILTER, - FAudio.FAUDIO_DEFAULT_FREQ_RATIO, - IntPtr.Zero, - IntPtr.Zero, - IntPtr.Zero - ); + FAudio.FAudio_CreateSourceVoice( + Device.Handle, + out var handle, + ref format, + FAudio.FAUDIO_VOICE_USEFILTER, + FAudio.FAUDIO_DEFAULT_FREQ_RATIO, + IntPtr.Zero, + IntPtr.Zero, + IntPtr.Zero + ); - if (handle == IntPtr.Zero) - { - Logger.LogError("SoundInstance failed to initialize!"); - return; - } + if (handle == IntPtr.Zero) + { + Logger.LogError("SoundInstance failed to initialize!"); + return; + } - Handle = handle; - this.is3D = is3D; - InitDSPSettings(Format.nChannels); + Handle = handle; + this.is3D = is3D; + InitDSPSettings(Format.nChannels); - FAudio.FAudioVoice_SetOutputVoices( - handle, - ref Device.ReverbSends - ); + FAudio.FAudioVoice_SetOutputVoices( + handle, + ref Device.ReverbSends + ); - Loop = loop; - State = SoundState.Stopped; - } + Loop = loop; + State = SoundState.Stopped; + } - public void Apply3D(AudioListener listener, AudioEmitter emitter) - { - is3D = true; + public void Apply3D(AudioListener listener, AudioEmitter emitter) + { + is3D = true; - emitter.emitterData.CurveDistanceScaler = Device.CurveDistanceScalar; - emitter.emitterData.ChannelCount = dspSettings.SrcChannelCount; + emitter.emitterData.CurveDistanceScaler = Device.CurveDistanceScalar; + emitter.emitterData.ChannelCount = dspSettings.SrcChannelCount; - FAudio.F3DAudioCalculate( - Device.Handle3D, - ref listener.listenerData, - ref emitter.emitterData, - FAudio.F3DAUDIO_CALCULATE_MATRIX | FAudio.F3DAUDIO_CALCULATE_DOPPLER, - ref dspSettings - ); + FAudio.F3DAudioCalculate( + Device.Handle3D, + ref listener.listenerData, + ref emitter.emitterData, + FAudio.F3DAUDIO_CALCULATE_MATRIX | FAudio.F3DAUDIO_CALCULATE_DOPPLER, + ref dspSettings + ); - UpdatePitch(); - FAudio.FAudioVoice_SetOutputMatrix( - Handle, - Device.MasteringVoice, - dspSettings.SrcChannelCount, - dspSettings.DstChannelCount, - dspSettings.pMatrixCoefficients, - 0 - ); - } + UpdatePitch(); + FAudio.FAudioVoice_SetOutputMatrix( + Handle, + Device.MasteringVoice, + dspSettings.SrcChannelCount, + dspSettings.DstChannelCount, + dspSettings.pMatrixCoefficients, + 0 + ); + } - public abstract void Play(); - public abstract void Pause(); - public abstract void Stop(bool immediate); + public abstract void Play(); + public abstract void Pause(); + public abstract void Stop(bool immediate); - private void InitDSPSettings(uint srcChannels) - { - dspSettings = new FAudio.F3DAUDIO_DSP_SETTINGS(); - dspSettings.DopplerFactor = 1f; - dspSettings.SrcChannelCount = srcChannels; - dspSettings.DstChannelCount = Device.DeviceDetails.OutputFormat.Format.nChannels; + private void InitDSPSettings(uint srcChannels) + { + dspSettings = new FAudio.F3DAUDIO_DSP_SETTINGS(); + dspSettings.DopplerFactor = 1f; + dspSettings.SrcChannelCount = srcChannels; + dspSettings.DstChannelCount = Device.DeviceDetails.OutputFormat.Format.nChannels; - int memsize = ( - 4 * - (int) dspSettings.SrcChannelCount * - (int) dspSettings.DstChannelCount - ); + int memsize = ( + 4 * + (int) dspSettings.SrcChannelCount * + (int) dspSettings.DstChannelCount + ); - dspSettings.pMatrixCoefficients = Marshal.AllocHGlobal(memsize); - unsafe - { - byte* memPtr = (byte*) dspSettings.pMatrixCoefficients; - for (int i = 0; i < memsize; i += 1) - { - memPtr[i] = 0; - } - } - SetPanMatrixCoefficients(); - } + dspSettings.pMatrixCoefficients = Marshal.AllocHGlobal(memsize); + unsafe + { + byte* memPtr = (byte*) dspSettings.pMatrixCoefficients; + for (int i = 0; i < memsize; i += 1) + { + memPtr[i] = 0; + } + } + SetPanMatrixCoefficients(); + } private void UpdatePitch() { @@ -287,10 +287,10 @@ namespace MoonWorks.Audio ); } - // Taken from https://github.com/FNA-XNA/FNA/blob/master/src/Audio/SoundEffectInstance.cs - private unsafe void SetPanMatrixCoefficients() - { - /* Two major things to notice: + // Taken from https://github.com/FNA-XNA/FNA/blob/master/src/Audio/SoundEffectInstance.cs + private unsafe void SetPanMatrixCoefficients() + { + /* Two major things to notice: * 1. The spec assumes any speaker count >= 2 has Front Left/Right. * 2. Stereo panning is WAY more complicated than you think. * The main thing is that hard panning does NOT eliminate an @@ -307,7 +307,7 @@ namespace MoonWorks.Audio else { outputMatrix[0] = (_pan > 0.0f) ? (1.0f - _pan) : 1.0f; - outputMatrix[1] = (_pan < 0.0f) ? (1.0f + _pan) : 1.0f; + outputMatrix[1] = (_pan < 0.0f) ? (1.0f + _pan) : 1.0f; } } else @@ -339,14 +339,14 @@ namespace MoonWorks.Audio } } } - } + } - protected override void Destroy() - { - Stop(true); + protected override void Destroy() + { + Stop(true); - FAudio.FAudioVoice_DestroyVoice(Handle); - Marshal.FreeHGlobal(dspSettings.pMatrixCoefficients); - } - } + FAudio.FAudioVoice_DestroyVoice(Handle); + Marshal.FreeHGlobal(dspSettings.pMatrixCoefficients); + } + } } diff --git a/src/Audio/SoundState.cs b/src/Audio/SoundState.cs index 2a82ea23..4fb9cb2d 100644 --- a/src/Audio/SoundState.cs +++ b/src/Audio/SoundState.cs @@ -1,9 +1,9 @@ -namespace MoonWorks.Audio +namespace MoonWorks.Audio { - public enum SoundState - { - Playing, - Paused, - Stopped - } + public enum SoundState + { + Playing, + Paused, + Stopped + } } diff --git a/src/Audio/StaticSound.cs b/src/Audio/StaticSound.cs index 9d03dd8e..526c3847 100644 --- a/src/Audio/StaticSound.cs +++ b/src/Audio/StaticSound.cs @@ -1,82 +1,82 @@ -using System; +using System; using System.Runtime.InteropServices; namespace MoonWorks.Audio { - public class StaticSound : AudioResource - { - internal FAudio.FAudioBuffer Handle; - public ushort Channels { get; } - public uint SamplesPerSecond { get; } + public class StaticSound : AudioResource + { + internal FAudio.FAudioBuffer Handle; + public ushort Channels { get; } + public uint SamplesPerSecond { get; } - public uint LoopStart { get; set; } = 0; - public uint LoopLength { get; set; } = 0; + public uint LoopStart { get; set; } = 0; + public uint LoopLength { get; set; } = 0; - public static StaticSound LoadOgg(AudioDevice device, string filePath) - { - var filePointer = FAudio.stb_vorbis_open_filename(filePath, out var error, IntPtr.Zero); + public static StaticSound LoadOgg(AudioDevice device, string filePath) + { + var filePointer = FAudio.stb_vorbis_open_filename(filePath, out var error, IntPtr.Zero); - if (error != 0) - { - throw new AudioLoadException("Error loading file!"); - } - var info = FAudio.stb_vorbis_get_info(filePointer); - var bufferSize = FAudio.stb_vorbis_stream_length_in_samples(filePointer) * info.channels; - var buffer = new float[bufferSize]; + if (error != 0) + { + throw new AudioLoadException("Error loading file!"); + } + var info = FAudio.stb_vorbis_get_info(filePointer); + var bufferSize = FAudio.stb_vorbis_stream_length_in_samples(filePointer) * info.channels; + var buffer = new float[bufferSize]; - FAudio.stb_vorbis_get_samples_float_interleaved( - filePointer, - info.channels, - buffer, - (int) bufferSize - ); + FAudio.stb_vorbis_get_samples_float_interleaved( + filePointer, + info.channels, + buffer, + (int) bufferSize + ); - FAudio.stb_vorbis_close(filePointer); + FAudio.stb_vorbis_close(filePointer); - return new StaticSound( - device, - (ushort) info.channels, - info.sample_rate, - buffer, - 0, - (uint) buffer.Length - ); - } + return new StaticSound( + device, + (ushort) info.channels, + info.sample_rate, + buffer, + 0, + (uint) buffer.Length + ); + } - public StaticSound( - AudioDevice device, - ushort channels, - uint samplesPerSecond, - float[] buffer, - uint bufferOffset, /* in floats */ - uint bufferLength /* in floats */ - ) : base(device) - { - Channels = channels; - SamplesPerSecond = samplesPerSecond; + public StaticSound( + AudioDevice device, + ushort channels, + uint samplesPerSecond, + float[] buffer, + uint bufferOffset, /* in floats */ + uint bufferLength /* in floats */ + ) : base(device) + { + Channels = channels; + SamplesPerSecond = samplesPerSecond; - var bufferLengthInBytes = (int) (bufferLength * sizeof(float)); - Handle = new FAudio.FAudioBuffer(); - Handle.Flags = FAudio.FAUDIO_END_OF_STREAM; - Handle.pContext = IntPtr.Zero; - Handle.AudioBytes = (uint) bufferLengthInBytes; - Handle.pAudioData = Marshal.AllocHGlobal(bufferLengthInBytes); - Marshal.Copy(buffer, (int) bufferOffset, Handle.pAudioData, (int) bufferLength); - Handle.PlayBegin = 0; - Handle.PlayLength = 0; + var bufferLengthInBytes = (int) (bufferLength * sizeof(float)); + Handle = new FAudio.FAudioBuffer(); + Handle.Flags = FAudio.FAUDIO_END_OF_STREAM; + Handle.pContext = IntPtr.Zero; + Handle.AudioBytes = (uint) bufferLengthInBytes; + Handle.pAudioData = Marshal.AllocHGlobal(bufferLengthInBytes); + Marshal.Copy(buffer, (int) bufferOffset, Handle.pAudioData, (int) bufferLength); + Handle.PlayBegin = 0; + Handle.PlayLength = 0; - LoopStart = 0; - LoopLength = 0; - } + LoopStart = 0; + LoopLength = 0; + } - public StaticSoundInstance CreateInstance(bool loop = false) - { - return new StaticSoundInstance(Device, this, false, loop); - } + public StaticSoundInstance CreateInstance(bool loop = false) + { + return new StaticSoundInstance(Device, this, false, loop); + } - protected override void Destroy() - { - Marshal.FreeHGlobal(Handle.pAudioData); - } - } + protected override void Destroy() + { + Marshal.FreeHGlobal(Handle.pAudioData); + } + } } diff --git a/src/Audio/StaticSoundInstance.cs b/src/Audio/StaticSoundInstance.cs index 646adc59..7fac5e87 100644 --- a/src/Audio/StaticSoundInstance.cs +++ b/src/Audio/StaticSoundInstance.cs @@ -1,96 +1,96 @@ -using System; +using System; namespace MoonWorks.Audio { - public class StaticSoundInstance : SoundInstance - { - public StaticSound Parent { get; } + public class StaticSoundInstance : SoundInstance + { + public StaticSound Parent { get; } - private SoundState _state = SoundState.Stopped; - public override SoundState State - { - get - { - FAudio.FAudioSourceVoice_GetState( - Handle, - out var state, - FAudio.FAUDIO_VOICE_NOSAMPLESPLAYED - ); - if (state.BuffersQueued == 0) - { - Stop(true); - } + private SoundState _state = SoundState.Stopped; + public override SoundState State + { + get + { + FAudio.FAudioSourceVoice_GetState( + Handle, + out var state, + FAudio.FAUDIO_VOICE_NOSAMPLESPLAYED + ); + if (state.BuffersQueued == 0) + { + Stop(true); + } - return _state; - } + return _state; + } - protected set - { - _state = value; - } - } + protected set + { + _state = value; + } + } - internal StaticSoundInstance( - AudioDevice device, - StaticSound parent, - bool is3D, - bool loop - ) : base(device, parent.Channels, parent.SamplesPerSecond, is3D, loop) - { - Parent = parent; - } + internal StaticSoundInstance( + AudioDevice device, + StaticSound parent, + bool is3D, + bool loop + ) : base(device, parent.Channels, parent.SamplesPerSecond, is3D, loop) + { + Parent = parent; + } - public override void Play() - { - if (State == SoundState.Playing) - { - return; - } + public override void Play() + { + if (State == SoundState.Playing) + { + return; + } - if (Loop) - { - Parent.Handle.LoopCount = 255; - Parent.Handle.LoopBegin = Parent.LoopStart; - Parent.Handle.LoopLength = Parent.LoopLength; - } - else - { - Parent.Handle.LoopCount = 0; - Parent.Handle.LoopBegin = 0; - Parent.Handle.LoopLength = 0; - } + if (Loop) + { + Parent.Handle.LoopCount = 255; + Parent.Handle.LoopBegin = Parent.LoopStart; + Parent.Handle.LoopLength = Parent.LoopLength; + } + else + { + Parent.Handle.LoopCount = 0; + Parent.Handle.LoopBegin = 0; + Parent.Handle.LoopLength = 0; + } - FAudio.FAudioSourceVoice_SubmitSourceBuffer( - Handle, - ref Parent.Handle, - IntPtr.Zero - ); + FAudio.FAudioSourceVoice_SubmitSourceBuffer( + Handle, + ref Parent.Handle, + IntPtr.Zero + ); - FAudio.FAudioSourceVoice_Start(Handle, 0, 0); - State = SoundState.Playing; - } + FAudio.FAudioSourceVoice_Start(Handle, 0, 0); + State = SoundState.Playing; + } - public override void Pause() - { - if (State == SoundState.Paused) - { - FAudio.FAudioSourceVoice_Stop(Handle, 0, 0); - State = SoundState.Paused; - } - } + public override void Pause() + { + if (State == SoundState.Paused) + { + FAudio.FAudioSourceVoice_Stop(Handle, 0, 0); + State = SoundState.Paused; + } + } - public override void Stop(bool immediate = true) - { - if (immediate) - { - FAudio.FAudioSourceVoice_Stop(Handle, 0, 0); - FAudio.FAudioSourceVoice_FlushSourceBuffers(Handle); - State = SoundState.Stopped; - } - else - { - FAudio.FAudioSourceVoice_ExitLoop(Handle, 0); - } - } - } + public override void Stop(bool immediate = true) + { + if (immediate) + { + FAudio.FAudioSourceVoice_Stop(Handle, 0, 0); + FAudio.FAudioSourceVoice_FlushSourceBuffers(Handle); + State = SoundState.Stopped; + } + else + { + FAudio.FAudioSourceVoice_ExitLoop(Handle, 0); + } + } + } } diff --git a/src/Audio/StreamingSound.cs b/src/Audio/StreamingSound.cs index aa46e04e..238a001b 100644 --- a/src/Audio/StreamingSound.cs +++ b/src/Audio/StreamingSound.cs @@ -1,178 +1,178 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace MoonWorks.Audio { - /// - /// For streaming long playback. - /// Can be extended to support custom decoders. - /// - public abstract class StreamingSound : SoundInstance - { - private readonly List queuedBuffers = new List(); - private readonly List queuedSizes = new List(); - private const int MINIMUM_BUFFER_CHECK = 3; + /// + /// For streaming long playback. + /// Can be extended to support custom decoders. + /// + public abstract class StreamingSound : SoundInstance + { + private readonly List queuedBuffers = new List(); + private readonly List queuedSizes = new List(); + private const int MINIMUM_BUFFER_CHECK = 3; - public int PendingBufferCount => queuedBuffers.Count; + public int PendingBufferCount => queuedBuffers.Count; - public StreamingSound( - AudioDevice device, - ushort channels, - uint samplesPerSecond, - bool is3D, - bool loop - ) : base(device, channels, samplesPerSecond, is3D, loop) { } + public StreamingSound( + AudioDevice device, + ushort channels, + uint samplesPerSecond, + bool is3D, + bool loop + ) : base(device, channels, samplesPerSecond, is3D, loop) { } - public override void Play() - { - if (State == SoundState.Playing) - { - return; - } + public override void Play() + { + if (State == SoundState.Playing) + { + return; + } - State = SoundState.Playing; - Update(); - FAudio.FAudioSourceVoice_Start(Handle, 0, 0); - } + State = SoundState.Playing; + Update(); + FAudio.FAudioSourceVoice_Start(Handle, 0, 0); + } - public override void Pause() - { - if (State == SoundState.Playing) - { - FAudio.FAudioSourceVoice_Stop(Handle, 0, 0); - State = SoundState.Paused; - } - } + public override void Pause() + { + if (State == SoundState.Playing) + { + FAudio.FAudioSourceVoice_Stop(Handle, 0, 0); + State = SoundState.Paused; + } + } - public override void Stop(bool immediate = true) - { - if (immediate) - { - FAudio.FAudioSourceVoice_Stop(Handle, 0, 0); - FAudio.FAudioSourceVoice_FlushSourceBuffers(Handle); - ClearBuffers(); - } + public override void Stop(bool immediate = true) + { + if (immediate) + { + FAudio.FAudioSourceVoice_Stop(Handle, 0, 0); + FAudio.FAudioSourceVoice_FlushSourceBuffers(Handle); + ClearBuffers(); + } - State = SoundState.Stopped; - } + State = SoundState.Stopped; + } - internal void Update() - { - if (State != SoundState.Playing) - { - return; - } + internal void Update() + { + if (State != SoundState.Playing) + { + return; + } - FAudio.FAudioSourceVoice_GetState( - Handle, - out var state, - FAudio.FAUDIO_VOICE_NOSAMPLESPLAYED - ); + FAudio.FAudioSourceVoice_GetState( + Handle, + out var state, + FAudio.FAUDIO_VOICE_NOSAMPLESPLAYED + ); - while (PendingBufferCount > state.BuffersQueued) - lock (queuedBuffers) - { - Marshal.FreeHGlobal(queuedBuffers[0]); - queuedBuffers.RemoveAt(0); - } + while (PendingBufferCount > state.BuffersQueued) + lock (queuedBuffers) + { + Marshal.FreeHGlobal(queuedBuffers[0]); + queuedBuffers.RemoveAt(0); + } - QueueBuffers(); - } + QueueBuffers(); + } - protected void QueueBuffers() - { - for ( - int i = MINIMUM_BUFFER_CHECK - PendingBufferCount; - i > 0; - i -= 1 - ) - { - AddBuffer(); - } - } + protected void QueueBuffers() + { + for ( + int i = MINIMUM_BUFFER_CHECK - PendingBufferCount; + i > 0; + i -= 1 + ) + { + AddBuffer(); + } + } - protected void ClearBuffers() - { - lock (queuedBuffers) - { - foreach (IntPtr buf in queuedBuffers) - { - Marshal.FreeHGlobal(buf); - } - queuedBuffers.Clear(); - queuedSizes.Clear(); - } - } + protected void ClearBuffers() + { + lock (queuedBuffers) + { + foreach (IntPtr buf in queuedBuffers) + { + Marshal.FreeHGlobal(buf); + } + queuedBuffers.Clear(); + queuedSizes.Clear(); + } + } - protected void AddBuffer() - { - AddBuffer( - out var buffer, - out var bufferOffset, - out var bufferLength, - out var reachedEnd - ); + protected void AddBuffer() + { + AddBuffer( + out var buffer, + out var bufferOffset, + out var bufferLength, + out var reachedEnd + ); - var lengthInBytes = bufferLength * sizeof(float); + var lengthInBytes = bufferLength * sizeof(float); - IntPtr next = Marshal.AllocHGlobal((int) lengthInBytes); - Marshal.Copy(buffer, (int) bufferOffset, next, (int) bufferLength); + IntPtr next = Marshal.AllocHGlobal((int) lengthInBytes); + Marshal.Copy(buffer, (int) bufferOffset, next, (int) bufferLength); - lock (queuedBuffers) - { - queuedBuffers.Add(next); - if (State != SoundState.Stopped) - { - FAudio.FAudioBuffer buf = new FAudio.FAudioBuffer - { - AudioBytes = lengthInBytes, - pAudioData = next, - PlayLength = ( - lengthInBytes / - Format.nChannels / - (uint)(Format.wBitsPerSample / 8) - ) - }; + lock (queuedBuffers) + { + queuedBuffers.Add(next); + if (State != SoundState.Stopped) + { + FAudio.FAudioBuffer buf = new FAudio.FAudioBuffer + { + AudioBytes = lengthInBytes, + pAudioData = next, + PlayLength = ( + lengthInBytes / + Format.nChannels / + (uint) (Format.wBitsPerSample / 8) + ) + }; - FAudio.FAudioSourceVoice_SubmitSourceBuffer( - Handle, - ref buf, - IntPtr.Zero - ); - } - else - { - queuedSizes.Add(lengthInBytes); - } - } + FAudio.FAudioSourceVoice_SubmitSourceBuffer( + Handle, + ref buf, + IntPtr.Zero + ); + } + else + { + queuedSizes.Add(lengthInBytes); + } + } - /* We have reached the end of the file, what do we do? */ - if (reachedEnd) - { - if (Loop) - { - SeekStart(); - } - else - { - Stop(false); - } - } - } + /* We have reached the end of the file, what do we do? */ + if (reachedEnd) + { + if (Loop) + { + SeekStart(); + } + else + { + Stop(false); + } + } + } - protected abstract void AddBuffer( - out float[] buffer, - out uint bufferOffset, /* in floats */ - out uint bufferLength, /* in floats */ - out bool reachedEnd - ); + protected abstract void AddBuffer( + out float[] buffer, + out uint bufferOffset, /* in floats */ + out uint bufferLength, /* in floats */ + out bool reachedEnd + ); - protected abstract void SeekStart(); + protected abstract void SeekStart(); - protected override void Destroy() - { - Stop(true); - } - } + protected override void Destroy() + { + Stop(true); + } + } } diff --git a/src/Audio/StreamingSoundOgg.cs b/src/Audio/StreamingSoundOgg.cs index caf5151d..b962d407 100644 --- a/src/Audio/StreamingSoundOgg.cs +++ b/src/Audio/StreamingSoundOgg.cs @@ -1,89 +1,91 @@ -using System; +using System; using System.IO; namespace MoonWorks.Audio { - public class StreamingSoundOgg : StreamingSound - { - // FIXME: what should this value be? - public const int BUFFER_SIZE = 1024 * 128; + public class StreamingSoundOgg : StreamingSound + { + // FIXME: what should this value be? + public const int BUFFER_SIZE = 1024 * 128; - internal IntPtr FileHandle { get; } - internal FAudio.stb_vorbis_info Info { get; } + internal IntPtr FileHandle { get; } + internal FAudio.stb_vorbis_info Info { get; } - private readonly float[] buffer; + private readonly float[] buffer; - public override SoundState State { get; protected set; } + public override SoundState State { get; protected set; } - public static StreamingSoundOgg Load( - AudioDevice device, - string filePath, - bool is3D = false, - bool loop = false - ) { - var fileHandle = FAudio.stb_vorbis_open_filename(filePath, out var error, IntPtr.Zero); - if (error != 0) - { - Logger.LogError("Error opening OGG file!"); - throw new AudioLoadException("Error opening OGG file!"); - } + public static StreamingSoundOgg Load( + AudioDevice device, + string filePath, + bool is3D = false, + bool loop = false + ) + { + var fileHandle = FAudio.stb_vorbis_open_filename(filePath, out var error, IntPtr.Zero); + if (error != 0) + { + Logger.LogError("Error opening OGG file!"); + throw new AudioLoadException("Error opening OGG file!"); + } - var info = FAudio.stb_vorbis_get_info(fileHandle); + var info = FAudio.stb_vorbis_get_info(fileHandle); - return new StreamingSoundOgg( - device, - fileHandle, - info, - is3D, - loop - ); - } + return new StreamingSoundOgg( + device, + fileHandle, + info, + is3D, + loop + ); + } - internal StreamingSoundOgg( - AudioDevice device, - IntPtr fileHandle, - FAudio.stb_vorbis_info info, - bool is3D, - bool loop - ) : base(device, (ushort) info.channels, info.sample_rate, is3D, loop) - { - FileHandle = fileHandle; - Info = info; - buffer = new float[BUFFER_SIZE]; + internal StreamingSoundOgg( + AudioDevice device, + IntPtr fileHandle, + FAudio.stb_vorbis_info info, + bool is3D, + bool loop + ) : base(device, (ushort) info.channels, info.sample_rate, is3D, loop) + { + FileHandle = fileHandle; + Info = info; + buffer = new float[BUFFER_SIZE]; - device.AddDynamicSoundInstance(this); - } + device.AddDynamicSoundInstance(this); + } - protected override void AddBuffer( - out float[] buffer, - out uint bufferOffset, - out uint bufferLength, - out bool reachedEnd - ) { - buffer = this.buffer; + protected override void AddBuffer( + out float[] buffer, + out uint bufferOffset, + out uint bufferLength, + out bool reachedEnd + ) + { + buffer = this.buffer; - /* NOTE: this function returns samples per channel, not total samples */ - var samples = FAudio.stb_vorbis_get_samples_float_interleaved( - FileHandle, - Info.channels, - buffer, - buffer.Length - ); + /* NOTE: this function returns samples per channel, not total samples */ + var samples = FAudio.stb_vorbis_get_samples_float_interleaved( + FileHandle, + Info.channels, + buffer, + buffer.Length + ); - var sampleCount = samples * Info.channels; - bufferOffset = 0; - bufferLength = (uint) sampleCount; - reachedEnd = sampleCount < buffer.Length; - } + var sampleCount = samples * Info.channels; + bufferOffset = 0; + bufferLength = (uint) sampleCount; + reachedEnd = sampleCount < buffer.Length; + } - protected override void SeekStart() - { - FAudio.stb_vorbis_seek_start(FileHandle); - } + protected override void SeekStart() + { + FAudio.stb_vorbis_seek_start(FileHandle); + } - protected override void Destroy() - { - FAudio.stb_vorbis_close(FileHandle); - } - } + protected override void Destroy() + { + FAudio.stb_vorbis_close(FileHandle); + } + } } diff --git a/src/Exceptions/AudioLoadException.cs b/src/Exceptions/AudioLoadException.cs index 33bcdf32..7ebbf985 100644 --- a/src/Exceptions/AudioLoadException.cs +++ b/src/Exceptions/AudioLoadException.cs @@ -1,12 +1,12 @@ -using System; +using System; namespace MoonWorks { - public class AudioLoadException : Exception - { - public AudioLoadException(string message) : base(message) - { + public class AudioLoadException : Exception + { + public AudioLoadException(string message) : base(message) + { - } - } + } + } } diff --git a/src/Game.cs b/src/Game.cs index c63097ac..604d4ead 100644 --- a/src/Game.cs +++ b/src/Game.cs @@ -10,17 +10,17 @@ using System.Diagnostics; namespace MoonWorks { - public abstract class Game - { - public TimeSpan MAX_DELTA_TIME = TimeSpan.FromMilliseconds(100); + public abstract class Game + { + public TimeSpan MAX_DELTA_TIME = TimeSpan.FromMilliseconds(100); - private bool quit = false; - bool debugMode; + private bool quit = false; + bool debugMode; private Stopwatch gameTimer; - private TimeSpan timestep; + private TimeSpan timestep; private long previousTicks = 0; - TimeSpan accumulatedElapsedTime = TimeSpan.Zero; + TimeSpan accumulatedElapsedTime = TimeSpan.Zero; // must be a power of 2 so we can do a bitmask optimization when checking worst case private const int PREVIOUS_SLEEP_TIME_COUNT = 128; private const int SLEEP_TIME_MASK = PREVIOUS_SLEEP_TIME_COUNT - 1; @@ -28,26 +28,27 @@ namespace MoonWorks private int sleepTimeIndex = 0; private TimeSpan worstCaseSleepPrecision = TimeSpan.FromMilliseconds(1); - public OSWindow Window { get; } - public GraphicsDevice GraphicsDevice { get; } - public AudioDevice AudioDevice { get; } - public Inputs Inputs { get; } + public OSWindow Window { get; } + public GraphicsDevice GraphicsDevice { get; } + public AudioDevice AudioDevice { get; } + public Inputs Inputs { get; } - private Dictionary moonWorksToRefreshPresentMode = new Dictionary - { - { PresentMode.Immediate, RefreshCS.Refresh.PresentMode.Immediate }, - { PresentMode.Mailbox, RefreshCS.Refresh.PresentMode.Mailbox }, - { PresentMode.FIFO, RefreshCS.Refresh.PresentMode.FIFO }, - { PresentMode.FIFORelaxed, RefreshCS.Refresh.PresentMode.FIFORelaxed } - }; + private Dictionary moonWorksToRefreshPresentMode = new Dictionary + { + { PresentMode.Immediate, RefreshCS.Refresh.PresentMode.Immediate }, + { PresentMode.Mailbox, RefreshCS.Refresh.PresentMode.Mailbox }, + { PresentMode.FIFO, RefreshCS.Refresh.PresentMode.FIFO }, + { PresentMode.FIFORelaxed, RefreshCS.Refresh.PresentMode.FIFORelaxed } + }; - public Game( - WindowCreateInfo windowCreateInfo, - PresentMode presentMode, - int targetTimestep = 60, - bool debugMode = false - ) { - timestep = TimeSpan.FromTicks(TimeSpan.TicksPerSecond / targetTimestep); + public Game( + WindowCreateInfo windowCreateInfo, + PresentMode presentMode, + int targetTimestep = 60, + bool debugMode = false + ) + { + timestep = TimeSpan.FromTicks(TimeSpan.TicksPerSecond / targetTimestep); gameTimer = Stopwatch.StartNew(); for (int i = 0; i < previousSleepTimes.Length; i += 1) @@ -55,33 +56,33 @@ namespace MoonWorks previousSleepTimes[i] = TimeSpan.FromMilliseconds(1); } - if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_TIMER | SDL.SDL_INIT_GAMECONTROLLER) < 0) - { - System.Console.WriteLine("Failed to initialize SDL!"); - return; - } + if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_TIMER | SDL.SDL_INIT_GAMECONTROLLER) < 0) + { + System.Console.WriteLine("Failed to initialize SDL!"); + return; + } - Logger.Initialize(); + Logger.Initialize(); - Inputs = new Inputs(); + Inputs = new Inputs(); - Window = new OSWindow(windowCreateInfo); + Window = new OSWindow(windowCreateInfo); - GraphicsDevice = new GraphicsDevice( - Window.Handle, - moonWorksToRefreshPresentMode[presentMode], - debugMode - ); + GraphicsDevice = new GraphicsDevice( + Window.Handle, + moonWorksToRefreshPresentMode[presentMode], + debugMode + ); - AudioDevice = new AudioDevice(); + AudioDevice = new AudioDevice(); - this.debugMode = debugMode; - } + this.debugMode = debugMode; + } - public void Run() - { - while (!quit) - { + public void Run() + { + while (!quit) + { AdvanceElapsedTime(); /* We want to wait until the next frame, @@ -111,33 +112,33 @@ namespace MoonWorks HandleSDLEvents(); // Do not let any step take longer than our maximum. - if (accumulatedElapsedTime > MAX_DELTA_TIME) - { - accumulatedElapsedTime = MAX_DELTA_TIME; - } + if (accumulatedElapsedTime > MAX_DELTA_TIME) + { + accumulatedElapsedTime = MAX_DELTA_TIME; + } - if (!quit) - { - while (accumulatedElapsedTime >= timestep) - { - Inputs.Mouse.Wheel = 0; + if (!quit) + { + while (accumulatedElapsedTime >= timestep) + { + Inputs.Mouse.Wheel = 0; - Inputs.Update(); - AudioDevice.Update(); + Inputs.Update(); + AudioDevice.Update(); - Update(timestep); + Update(timestep); - accumulatedElapsedTime -= timestep; - } + accumulatedElapsedTime -= timestep; + } - var alpha = accumulatedElapsedTime / timestep; + var alpha = accumulatedElapsedTime / timestep; - Draw(timestep, alpha); + Draw(timestep, alpha); - } + } GraphicsDevice.SubmitDestroyCommandBuffer(); - } + } OnDestroy(); @@ -146,64 +147,64 @@ namespace MoonWorks Window.Dispose(); SDL.SDL_Quit(); - } + } - private void HandleSDLEvents() - { - while (SDL.SDL_PollEvent(out var _event) == 1) - { - switch (_event.type) - { - case SDL.SDL_EventType.SDL_QUIT: - quit = true; - break; + private void HandleSDLEvents() + { + while (SDL.SDL_PollEvent(out var _event) == 1) + { + switch (_event.type) + { + case SDL.SDL_EventType.SDL_QUIT: + quit = true; + break; - case SDL.SDL_EventType.SDL_TEXTINPUT: - HandleTextInput(_event); - break; + case SDL.SDL_EventType.SDL_TEXTINPUT: + HandleTextInput(_event); + break; - case SDL.SDL_EventType.SDL_MOUSEWHEEL: - Inputs.Mouse.Wheel += _event.wheel.y; - break; - } - } - } + case SDL.SDL_EventType.SDL_MOUSEWHEEL: + Inputs.Mouse.Wheel += _event.wheel.y; + break; + } + } + } - protected abstract void Update(TimeSpan dt); + protected abstract void Update(TimeSpan dt); // alpha refers to a percentage value between the current and next state - protected abstract void Draw(TimeSpan dt, double alpha); + protected abstract void Draw(TimeSpan dt, double alpha); // Clean up any objects you created in this function protected abstract void OnDestroy(); - private void HandleTextInput(SDL2.SDL.SDL_Event evt) - { - // Based on the SDL2# LPUtf8StrMarshaler - unsafe - { - int bytes = MeasureStringLength(evt.text.text); - if (bytes > 0) - { - /* UTF8 will never encode more characters + private void HandleTextInput(SDL2.SDL.SDL_Event evt) + { + // Based on the SDL2# LPUtf8StrMarshaler + unsafe + { + int bytes = MeasureStringLength(evt.text.text); + if (bytes > 0) + { + /* UTF8 will never encode more characters * than bytes in a string, so bytes is a * suitable upper estimate of size needed */ - char* charsBuffer = stackalloc char[bytes]; - int chars = Encoding.UTF8.GetChars( - evt.text.text, - bytes, - charsBuffer, - bytes - ); + char* charsBuffer = stackalloc char[bytes]; + int chars = Encoding.UTF8.GetChars( + evt.text.text, + bytes, + charsBuffer, + bytes + ); - for (int i = 0; i < chars; i += 1) - { - Inputs.OnTextInput(charsBuffer[i]); - } - } - } - } + for (int i = 0; i < chars; i += 1) + { + Inputs.OnTextInput(charsBuffer[i]); + } + } + } + } private TimeSpan AdvanceElapsedTime() { @@ -259,8 +260,8 @@ namespace MoonWorks private unsafe static int MeasureStringLength(byte* ptr) { int bytes; - for (bytes = 0; *ptr != 0; ptr += 1, bytes += 1); + for (bytes = 0; *ptr != 0; ptr += 1, bytes += 1) ; return bytes; } - } + } } diff --git a/src/Graphics/Bindings/BufferBinding.cs b/src/Graphics/Bindings/BufferBinding.cs index adc4ed89..3d9f5112 100644 --- a/src/Graphics/Bindings/BufferBinding.cs +++ b/src/Graphics/Bindings/BufferBinding.cs @@ -1,14 +1,14 @@ -namespace MoonWorks.Graphics +namespace MoonWorks.Graphics { - public struct BufferBinding - { - public Buffer Buffer; - public ulong Offset; + public struct BufferBinding + { + public Buffer Buffer; + public ulong Offset; - public BufferBinding(Buffer buffer, ulong offset) - { - Buffer = buffer; - Offset = offset; - } - } + public BufferBinding(Buffer buffer, ulong offset) + { + Buffer = buffer; + Offset = offset; + } + } } diff --git a/src/Graphics/Bindings/TextureSamplerBinding.cs b/src/Graphics/Bindings/TextureSamplerBinding.cs index cad832ff..effa5792 100644 --- a/src/Graphics/Bindings/TextureSamplerBinding.cs +++ b/src/Graphics/Bindings/TextureSamplerBinding.cs @@ -1,14 +1,14 @@ namespace MoonWorks.Graphics { - public struct TextureSamplerBinding - { - public Texture Texture; - public Sampler Sampler; + public struct TextureSamplerBinding + { + public Texture Texture; + public Sampler Sampler; - public TextureSamplerBinding(Texture texture, Sampler sampler) - { - Texture = texture; - Sampler = sampler; - } - } + public TextureSamplerBinding(Texture texture, Sampler sampler) + { + Texture = texture; + Sampler = sampler; + } + } } diff --git a/src/Graphics/Color.cs b/src/Graphics/Color.cs index 904b567a..413c8b2e 100644 --- a/src/Graphics/Color.cs +++ b/src/Graphics/Color.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -41,7 +41,7 @@ namespace MoonWorks.Graphics { unchecked { - return (byte)(this.packedValue); + return (byte) (this.packedValue); } } set @@ -59,12 +59,12 @@ namespace MoonWorks.Graphics { unchecked { - return (byte)(this.packedValue >> 8); + return (byte) (this.packedValue >> 8); } } set { - this.packedValue = (this.packedValue & 0xffff00ff) | ((uint)value << 8); + this.packedValue = (this.packedValue & 0xffff00ff) | ((uint) value << 8); } } @@ -1538,27 +1538,27 @@ namespace MoonWorks.Graphics RosyBrown = new Color(0xff8f8fbc); RoyalBlue = new Color(0xffe16941); SaddleBrown = new Color(0xff13458b); - Salmon= new Color(0xff7280fa); + Salmon = new Color(0xff7280fa); SandyBrown = new Color(0xff60a4f4); SeaGreen = new Color(0xff578b2e); SeaShell = new Color(0xffeef5ff); Sienna = new Color(0xff2d52a0); Silver = new Color(0xffc0c0c0); SkyBlue = new Color(0xffebce87); - SlateBlue= new Color(0xffcd5a6a); - SlateGray= new Color(0xff908070); - Snow= new Color(0xfffafaff); - SpringGreen= new Color(0xff7fff00); - SteelBlue= new Color(0xffb48246); - Tan= new Color(0xff8cb4d2); - Teal= new Color(0xff808000); - Thistle= new Color(0xffd8bfd8); - Tomato= new Color(0xff4763ff); - Turquoise= new Color(0xffd0e040); - Violet= new Color(0xffee82ee); - Wheat= new Color(0xffb3def5); - White= new Color(uint.MaxValue); - WhiteSmoke= new Color(0xfff5f5f5); + SlateBlue = new Color(0xffcd5a6a); + SlateGray = new Color(0xff908070); + Snow = new Color(0xfffafaff); + SpringGreen = new Color(0xff7fff00); + SteelBlue = new Color(0xffb48246); + Tan = new Color(0xff8cb4d2); + Teal = new Color(0xff808000); + Thistle = new Color(0xffd8bfd8); + Tomato = new Color(0xff4763ff); + Turquoise = new Color(0xffd0e040); + Violet = new Color(0xffee82ee); + Wheat = new Color(0xffb3def5); + White = new Color(uint.MaxValue); + WhiteSmoke = new Color(0xfff5f5f5); Yellow = new Color(0xff00ffff); YellowGreen = new Color(0xff32cd9a); } @@ -1623,7 +1623,7 @@ namespace MoonWorks.Graphics R = (byte) MathHelper.Clamp(r, Byte.MinValue, Byte.MaxValue); G = (byte) MathHelper.Clamp(g, Byte.MinValue, Byte.MaxValue); B = (byte) MathHelper.Clamp(b, Byte.MinValue, Byte.MaxValue); - A = (byte)255; + A = (byte) 255; } /// @@ -1769,10 +1769,10 @@ namespace MoonWorks.Graphics /// True if the instances are equal; false otherwise. public static bool operator ==(Color a, Color b) { - return ( a.A == b.A && + return (a.A == b.A && a.R == b.R && a.G == b.G && - a.B == b.B ); + a.B == b.B); } /// diff --git a/src/Graphics/CommandBuffer.cs b/src/Graphics/CommandBuffer.cs index 9c134c50..42576fc5 100644 --- a/src/Graphics/CommandBuffer.cs +++ b/src/Graphics/CommandBuffer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Runtime.InteropServices; using MoonWorks.Math; using MoonWorks.Window; @@ -6,880 +6,907 @@ using RefreshCS; namespace MoonWorks.Graphics { - /// - /// Command buffers are used to apply render state and issue draw calls. - /// NOTE: it is not recommended to hold references to command buffers long term. - /// - public struct CommandBuffer - { - public GraphicsDevice Device { get; } - public IntPtr Handle { get; internal set; } + /// + /// Command buffers are used to apply render state and issue draw calls. + /// NOTE: it is not recommended to hold references to command buffers long term. + /// + public struct CommandBuffer + { + public GraphicsDevice Device { get; } + public IntPtr Handle { get; internal set; } - // called from RefreshDevice - internal CommandBuffer(GraphicsDevice device, IntPtr handle) - { - Device = device; - Handle = handle; - } + // called from RefreshDevice + internal CommandBuffer(GraphicsDevice device, IntPtr handle) + { + Device = device; + Handle = handle; + } - /// - /// Begins a render pass. - /// All render state, resource binding, and draw commands must be made within a render pass. - /// It is an error to call this after calling BeginRenderPass but before calling EndRenderPass. - /// - /// The render pass object to begin. - /// The framebuffer used by the render pass. - /// The screen area of the render pass. - /// Clear values for the depth/stencil buffer. This is ignored if the render pass does not clear. - public unsafe void BeginRenderPass( - RenderPass renderPass, - Framebuffer framebuffer, - in Rect renderArea, - in DepthStencilValue depthStencilClearValue - ) { - Refresh.Refresh_BeginRenderPass( - Device.Handle, - Handle, - renderPass.Handle, - framebuffer.Handle, - renderArea.ToRefresh(), - IntPtr.Zero, - 0, - depthStencilClearValue.ToRefresh() - ); - } + /// + /// Begins a render pass. + /// All render state, resource binding, and draw commands must be made within a render pass. + /// It is an error to call this after calling BeginRenderPass but before calling EndRenderPass. + /// + /// The render pass object to begin. + /// The framebuffer used by the render pass. + /// The screen area of the render pass. + /// Clear values for the depth/stencil buffer. This is ignored if the render pass does not clear. + public unsafe void BeginRenderPass( + RenderPass renderPass, + Framebuffer framebuffer, + in Rect renderArea, + in DepthStencilValue depthStencilClearValue + ) + { + Refresh.Refresh_BeginRenderPass( + Device.Handle, + Handle, + renderPass.Handle, + framebuffer.Handle, + renderArea.ToRefresh(), + IntPtr.Zero, + 0, + depthStencilClearValue.ToRefresh() + ); + } - /// - /// Begins a render pass. - /// All render state, resource binding, and draw commands must be made within a render pass. - /// It is an error to call this after calling BeginRenderPass but before calling EndRenderPass. - /// - /// The render pass object to begin. - /// The framebuffer used by the render pass. - /// The screen area of the render pass. - /// Clear values for the depth/stencil buffer. This is ignored if the render pass does not clear. - /// Color clear values for each render target in the framebuffer. - public unsafe void BeginRenderPass( - RenderPass renderPass, - Framebuffer framebuffer, - in Rect renderArea, - in DepthStencilValue depthStencilClearValue, - params Vector4[] clearColors - ) { - Refresh.Vec4* colors = stackalloc Refresh.Vec4[clearColors.Length]; + /// + /// Begins a render pass. + /// All render state, resource binding, and draw commands must be made within a render pass. + /// It is an error to call this after calling BeginRenderPass but before calling EndRenderPass. + /// + /// The render pass object to begin. + /// The framebuffer used by the render pass. + /// The screen area of the render pass. + /// Clear values for the depth/stencil buffer. This is ignored if the render pass does not clear. + /// Color clear values for each render target in the framebuffer. + public unsafe void BeginRenderPass( + RenderPass renderPass, + Framebuffer framebuffer, + in Rect renderArea, + in DepthStencilValue depthStencilClearValue, + params Vector4[] clearColors + ) + { + Refresh.Vec4* colors = stackalloc Refresh.Vec4[clearColors.Length]; - for (var i = 0; i < clearColors.Length; i++) - { - colors[i] = new Refresh.Vec4 - { - x = clearColors[i].X, - y = clearColors[i].Y, - z = clearColors[i].Z, - w = clearColors[i].W - }; - } + for (var i = 0; i < clearColors.Length; i++) + { + colors[i] = new Refresh.Vec4 + { + x = clearColors[i].X, + y = clearColors[i].Y, + z = clearColors[i].Z, + w = clearColors[i].W + }; + } - Refresh.Refresh_BeginRenderPass( - Device.Handle, - Handle, - renderPass.Handle, - framebuffer.Handle, - renderArea.ToRefresh(), - (IntPtr) colors, - (uint)clearColors.Length, - depthStencilClearValue.ToRefresh() - ); - } + Refresh.Refresh_BeginRenderPass( + Device.Handle, + Handle, + renderPass.Handle, + framebuffer.Handle, + renderArea.ToRefresh(), + (IntPtr) colors, + (uint) clearColors.Length, + depthStencilClearValue.ToRefresh() + ); + } - /// - /// Begins a render pass. - /// All render state, resource binding, and draw commands must be made within a render pass. - /// It is an error to call this after calling BeginRenderPass but before calling EndRenderPass. - /// - /// The render pass object to begin. - /// The framebuffer used by the render pass. - /// The screen area of the render pass. - /// Color clear values for each render target in the framebuffer. - public unsafe void BeginRenderPass( - RenderPass renderPass, - Framebuffer framebuffer, - in Rect renderArea, - params Vector4[] clearColors - ) { - Refresh.Vec4* colors = stackalloc Refresh.Vec4[clearColors.Length]; + /// + /// Begins a render pass. + /// All render state, resource binding, and draw commands must be made within a render pass. + /// It is an error to call this after calling BeginRenderPass but before calling EndRenderPass. + /// + /// The render pass object to begin. + /// The framebuffer used by the render pass. + /// The screen area of the render pass. + /// Color clear values for each render target in the framebuffer. + public unsafe void BeginRenderPass( + RenderPass renderPass, + Framebuffer framebuffer, + in Rect renderArea, + params Vector4[] clearColors + ) + { + Refresh.Vec4* colors = stackalloc Refresh.Vec4[clearColors.Length]; - for (var i = 0; i < clearColors.Length; i++) - { - colors[i] = new Refresh.Vec4 - { - x = clearColors[i].X, - y = clearColors[i].Y, - z = clearColors[i].Z, - w = clearColors[i].W - }; - } + for (var i = 0; i < clearColors.Length; i++) + { + colors[i] = new Refresh.Vec4 + { + x = clearColors[i].X, + y = clearColors[i].Y, + z = clearColors[i].Z, + w = clearColors[i].W + }; + } - Refresh.Refresh_BeginRenderPass( - Device.Handle, - Handle, - renderPass.Handle, - framebuffer.Handle, - renderArea.ToRefresh(), - (IntPtr) colors, - (uint) clearColors.Length, - IntPtr.Zero - ); - } + Refresh.Refresh_BeginRenderPass( + Device.Handle, + Handle, + renderPass.Handle, + framebuffer.Handle, + renderArea.ToRefresh(), + (IntPtr) colors, + (uint) clearColors.Length, + IntPtr.Zero + ); + } - /// - /// Begins a render pass. - /// All render state, resource binding, and draw commands must be made within a render pass. - /// It is an error to call this after calling BeginRenderPass but before calling EndRenderPass. - /// - /// The render pass object to begin. - /// The framebuffer used by the render pass. - /// The screen area of the render pass. - public unsafe void BeginRenderPass( - RenderPass renderPass, - Framebuffer framebuffer, - in Rect renderArea - ) { - Refresh.Refresh_BeginRenderPass( - Device.Handle, - Handle, - renderPass.Handle, - framebuffer.Handle, - renderArea.ToRefresh(), - IntPtr.Zero, - 0, - IntPtr.Zero - ); - } + /// + /// Begins a render pass. + /// All render state, resource binding, and draw commands must be made within a render pass. + /// It is an error to call this after calling BeginRenderPass but before calling EndRenderPass. + /// + /// The render pass object to begin. + /// The framebuffer used by the render pass. + /// The screen area of the render pass. + public unsafe void BeginRenderPass( + RenderPass renderPass, + Framebuffer framebuffer, + in Rect renderArea + ) + { + Refresh.Refresh_BeginRenderPass( + Device.Handle, + Handle, + renderPass.Handle, + framebuffer.Handle, + renderArea.ToRefresh(), + IntPtr.Zero, + 0, + IntPtr.Zero + ); + } - /// - /// Binds a compute pipeline so that compute work may be dispatched. - /// - /// The compute pipeline to bind. - public void BindComputePipeline( - ComputePipeline computePipeline - ) { - Refresh.Refresh_BindComputePipeline( - Device.Handle, - Handle, - computePipeline.Handle - ); - } + /// + /// Binds a compute pipeline so that compute work may be dispatched. + /// + /// The compute pipeline to bind. + public void BindComputePipeline( + ComputePipeline computePipeline + ) + { + Refresh.Refresh_BindComputePipeline( + Device.Handle, + Handle, + computePipeline.Handle + ); + } - /// - /// Binds buffers to be used in the compute shader. - /// - /// A set of buffers to bind. - public unsafe void BindComputeBuffers( - params Buffer[] buffers - ) { - var bufferPtrs = stackalloc IntPtr[buffers.Length]; + /// + /// Binds buffers to be used in the compute shader. + /// + /// A set of buffers to bind. + public unsafe void BindComputeBuffers( + params Buffer[] buffers + ) + { + var bufferPtrs = stackalloc IntPtr[buffers.Length]; - for (var i = 0; i < buffers.Length; i += 1) - { - bufferPtrs[i] = buffers[i].Handle; - } + for (var i = 0; i < buffers.Length; i += 1) + { + bufferPtrs[i] = buffers[i].Handle; + } - Refresh.Refresh_BindComputeBuffers( - Device.Handle, - Handle, - (IntPtr) bufferPtrs - ); - } + Refresh.Refresh_BindComputeBuffers( + Device.Handle, + Handle, + (IntPtr) bufferPtrs + ); + } - /// - /// Binds textures to be used in the compute shader. - /// - /// A set of textures to bind. - public unsafe void BindComputeTextures( - params Texture[] textures - ) { - var texturePtrs = stackalloc IntPtr[textures.Length]; + /// + /// Binds textures to be used in the compute shader. + /// + /// A set of textures to bind. + public unsafe void BindComputeTextures( + params Texture[] textures + ) + { + var texturePtrs = stackalloc IntPtr[textures.Length]; - for (var i = 0; i < textures.Length; i += 1) - { - texturePtrs[i] = textures[i].Handle; - } + for (var i = 0; i < textures.Length; i += 1) + { + texturePtrs[i] = textures[i].Handle; + } - Refresh.Refresh_BindComputeTextures( - Device.Handle, - Handle, - (IntPtr) texturePtrs - ); - } + Refresh.Refresh_BindComputeTextures( + Device.Handle, + Handle, + (IntPtr) texturePtrs + ); + } - /// - /// Dispatches compute work. - /// - /// - /// - /// - /// - public void DispatchCompute( - uint groupCountX, - uint groupCountY, - uint groupCountZ, - uint computeParamOffset - ) { - Refresh.Refresh_DispatchCompute( - Device.Handle, - Handle, - groupCountX, - groupCountY, - groupCountZ, - computeParamOffset - ); - } + /// + /// Dispatches compute work. + /// + /// + /// + /// + /// + public void DispatchCompute( + uint groupCountX, + uint groupCountY, + uint groupCountZ, + uint computeParamOffset + ) + { + Refresh.Refresh_DispatchCompute( + Device.Handle, + Handle, + groupCountX, + groupCountY, + groupCountZ, + computeParamOffset + ); + } - /// - /// Binds a graphics pipeline so that rendering work may be performed. - /// - /// The graphics pipeline to bind. - public void BindGraphicsPipeline( - GraphicsPipeline graphicsPipeline - ) { - Refresh.Refresh_BindGraphicsPipeline( - Device.Handle, - Handle, - graphicsPipeline.Handle - ); - } + /// + /// Binds a graphics pipeline so that rendering work may be performed. + /// + /// The graphics pipeline to bind. + public void BindGraphicsPipeline( + GraphicsPipeline graphicsPipeline + ) + { + Refresh.Refresh_BindGraphicsPipeline( + Device.Handle, + Handle, + graphicsPipeline.Handle + ); + } - /// - /// Binds vertex buffers to be used by subsequent draw calls. - /// - /// The index of the first buffer to bind. - /// Buffers to bind and their associated offsets. - public unsafe void BindVertexBuffers( - uint firstBinding, - params BufferBinding[] bufferBindings - ) { - var bufferPtrs = stackalloc IntPtr[bufferBindings.Length]; - var offsets = stackalloc ulong[bufferBindings.Length]; + /// + /// Binds vertex buffers to be used by subsequent draw calls. + /// + /// The index of the first buffer to bind. + /// Buffers to bind and their associated offsets. + public unsafe void BindVertexBuffers( + uint firstBinding, + params BufferBinding[] bufferBindings + ) + { + var bufferPtrs = stackalloc IntPtr[bufferBindings.Length]; + var offsets = stackalloc ulong[bufferBindings.Length]; - for (var i = 0; i < bufferBindings.Length; i += 1) - { - bufferPtrs[i] = bufferBindings[i].Buffer.Handle; - offsets[i] = bufferBindings[i].Offset; - } + for (var i = 0; i < bufferBindings.Length; i += 1) + { + bufferPtrs[i] = bufferBindings[i].Buffer.Handle; + offsets[i] = bufferBindings[i].Offset; + } - Refresh.Refresh_BindVertexBuffers( - Device.Handle, - Handle, - firstBinding, - (uint) bufferBindings.Length, - (IntPtr) bufferPtrs, - (IntPtr) offsets - ); - } + Refresh.Refresh_BindVertexBuffers( + Device.Handle, + Handle, + firstBinding, + (uint) bufferBindings.Length, + (IntPtr) bufferPtrs, + (IntPtr) offsets + ); + } - /// - /// Binds vertex buffers to be used by subsequent draw calls. - /// - /// The buffers to bind. - public unsafe void BindVertexBuffers( - params Buffer[] buffers - ) { - var bufferPtrs = stackalloc IntPtr[buffers.Length]; - var offsets = stackalloc ulong[buffers.Length]; + /// + /// Binds vertex buffers to be used by subsequent draw calls. + /// + /// The buffers to bind. + public unsafe void BindVertexBuffers( + params Buffer[] buffers + ) + { + var bufferPtrs = stackalloc IntPtr[buffers.Length]; + var offsets = stackalloc ulong[buffers.Length]; - for (var i = 0; i < buffers.Length; i += 1) - { - bufferPtrs[i] = buffers[i].Handle; - offsets[i] = 0; - } + for (var i = 0; i < buffers.Length; i += 1) + { + bufferPtrs[i] = buffers[i].Handle; + offsets[i] = 0; + } - Refresh.Refresh_BindVertexBuffers( - Device.Handle, - Handle, - 0, - (uint) buffers.Length, - (IntPtr) bufferPtrs, - (IntPtr) offsets - ); - } + Refresh.Refresh_BindVertexBuffers( + Device.Handle, + Handle, + 0, + (uint) buffers.Length, + (IntPtr) bufferPtrs, + (IntPtr) offsets + ); + } - /// - /// Binds an index buffer to be used by subsequent draw calls. - /// - /// The index buffer to bind. - /// The size in bytes of the index buffer elements. - /// The offset index for the buffer. - public void BindIndexBuffer( - Buffer indexBuffer, - IndexElementSize indexElementSize, - uint offset = 0 - ) { - Refresh.Refresh_BindIndexBuffer( - Device.Handle, - Handle, - indexBuffer.Handle, - offset, - (Refresh.IndexElementSize) indexElementSize - ); - } + /// + /// Binds an index buffer to be used by subsequent draw calls. + /// + /// The index buffer to bind. + /// The size in bytes of the index buffer elements. + /// The offset index for the buffer. + public void BindIndexBuffer( + Buffer indexBuffer, + IndexElementSize indexElementSize, + uint offset = 0 + ) + { + Refresh.Refresh_BindIndexBuffer( + Device.Handle, + Handle, + indexBuffer.Handle, + offset, + (Refresh.IndexElementSize) indexElementSize + ); + } - /// - /// Binds samplers to be used by the vertex shader. - /// - /// An array of texture-sampler pairs to bind. - /// The number of texture-sampler pairs from the array to bind. - public unsafe void BindVertexSamplers( - TextureSamplerBinding[] textureSamplerBindings, - int length - ) { - var texturePtrs = stackalloc IntPtr[textureSamplerBindings.Length]; - var samplerPtrs = stackalloc IntPtr[textureSamplerBindings.Length]; + /// + /// Binds samplers to be used by the vertex shader. + /// + /// An array of texture-sampler pairs to bind. + /// The number of texture-sampler pairs from the array to bind. + public unsafe void BindVertexSamplers( + TextureSamplerBinding[] textureSamplerBindings, + int length + ) + { + var texturePtrs = stackalloc IntPtr[textureSamplerBindings.Length]; + var samplerPtrs = stackalloc IntPtr[textureSamplerBindings.Length]; - for (var i = 0; i < length; i += 1) - { - texturePtrs[i] = textureSamplerBindings[i].Texture.Handle; - samplerPtrs[i] = textureSamplerBindings[i].Sampler.Handle; - } + for (var i = 0; i < length; i += 1) + { + texturePtrs[i] = textureSamplerBindings[i].Texture.Handle; + samplerPtrs[i] = textureSamplerBindings[i].Sampler.Handle; + } - Refresh.Refresh_BindVertexSamplers( - Device.Handle, - Handle, - (IntPtr) texturePtrs, - (IntPtr) samplerPtrs - ); - } + Refresh.Refresh_BindVertexSamplers( + Device.Handle, + Handle, + (IntPtr) texturePtrs, + (IntPtr) samplerPtrs + ); + } - /// - /// Binds samplers to be used by the vertex shader. - /// - /// The texture-sampler pairs to bind. - public unsafe void BindVertexSamplers( - params TextureSamplerBinding[] textureSamplerBindings - ) { - BindVertexSamplers(textureSamplerBindings, textureSamplerBindings.Length); - } + /// + /// Binds samplers to be used by the vertex shader. + /// + /// The texture-sampler pairs to bind. + public unsafe void BindVertexSamplers( + params TextureSamplerBinding[] textureSamplerBindings + ) + { + BindVertexSamplers(textureSamplerBindings, textureSamplerBindings.Length); + } - /// - /// Binds samplers to be used by the fragment shader. - /// - /// An array of texture-sampler pairs to bind. - /// The number of texture-sampler pairs from the given array to bind. - public unsafe void BindFragmentSamplers( - TextureSamplerBinding[] textureSamplerBindings, - int length - ) { - var texturePtrs = stackalloc IntPtr[textureSamplerBindings.Length]; - var samplerPtrs = stackalloc IntPtr[textureSamplerBindings.Length]; + /// + /// Binds samplers to be used by the fragment shader. + /// + /// An array of texture-sampler pairs to bind. + /// The number of texture-sampler pairs from the given array to bind. + public unsafe void BindFragmentSamplers( + TextureSamplerBinding[] textureSamplerBindings, + int length + ) + { + var texturePtrs = stackalloc IntPtr[textureSamplerBindings.Length]; + var samplerPtrs = stackalloc IntPtr[textureSamplerBindings.Length]; - for (var i = 0; i < length; i += 1) - { - texturePtrs[i] = textureSamplerBindings[i].Texture.Handle; - samplerPtrs[i] = textureSamplerBindings[i].Sampler.Handle; - } + for (var i = 0; i < length; i += 1) + { + texturePtrs[i] = textureSamplerBindings[i].Texture.Handle; + samplerPtrs[i] = textureSamplerBindings[i].Sampler.Handle; + } - Refresh.Refresh_BindFragmentSamplers( - Device.Handle, - Handle, - (IntPtr) texturePtrs, - (IntPtr) samplerPtrs - ); - } + Refresh.Refresh_BindFragmentSamplers( + Device.Handle, + Handle, + (IntPtr) texturePtrs, + (IntPtr) samplerPtrs + ); + } - /// - /// Binds samplers to be used by the fragment shader. - /// - /// An array of texture-sampler pairs to bind. - public unsafe void BindFragmentSamplers( - params TextureSamplerBinding[] textureSamplerBindings - ) { - BindFragmentSamplers(textureSamplerBindings, textureSamplerBindings.Length); - } + /// + /// Binds samplers to be used by the fragment shader. + /// + /// An array of texture-sampler pairs to bind. + public unsafe void BindFragmentSamplers( + params TextureSamplerBinding[] textureSamplerBindings + ) + { + BindFragmentSamplers(textureSamplerBindings, textureSamplerBindings.Length); + } - /// - /// Pushes vertex shader uniforms to the device. - /// - /// A starting offset value to be used with draw calls. - public unsafe uint PushVertexShaderUniforms( - params T[] uniforms - ) where T : unmanaged - { - fixed (T* ptr = &uniforms[0]) - { - return Refresh.Refresh_PushVertexShaderUniforms( - Device.Handle, - Handle, - (IntPtr) ptr, - (uint) (uniforms.Length * Marshal.SizeOf()) - ); - } - } + /// + /// Pushes vertex shader uniforms to the device. + /// + /// A starting offset value to be used with draw calls. + public unsafe uint PushVertexShaderUniforms( + params T[] uniforms + ) where T : unmanaged + { + fixed (T* ptr = &uniforms[0]) + { + return Refresh.Refresh_PushVertexShaderUniforms( + Device.Handle, + Handle, + (IntPtr) ptr, + (uint) (uniforms.Length * Marshal.SizeOf()) + ); + } + } - /// - /// Pushes fragment shader uniforms to the device. - /// - /// A starting offset to be used with draw calls. - public unsafe uint PushFragmentShaderUniforms( - params T[] uniforms - ) where T : unmanaged - { - fixed (T* ptr = &uniforms[0]) - { - return Refresh.Refresh_PushFragmentShaderUniforms( - Device.Handle, - Handle, - (IntPtr) ptr, - (uint) (uniforms.Length * Marshal.SizeOf()) - ); - } - } + /// + /// Pushes fragment shader uniforms to the device. + /// + /// A starting offset to be used with draw calls. + public unsafe uint PushFragmentShaderUniforms( + params T[] uniforms + ) where T : unmanaged + { + fixed (T* ptr = &uniforms[0]) + { + return Refresh.Refresh_PushFragmentShaderUniforms( + Device.Handle, + Handle, + (IntPtr) ptr, + (uint) (uniforms.Length * Marshal.SizeOf()) + ); + } + } - /// - /// Pushes compute shader uniforms to the device. - /// - /// A starting offset to be used with dispatch calls. - public unsafe uint PushComputeShaderUniforms( - params T[] uniforms - ) where T : unmanaged - { - fixed (T* ptr = &uniforms[0]) - { - return Refresh.Refresh_PushComputeShaderUniforms( - Device.Handle, - Handle, - (IntPtr) ptr, - (uint) (uniforms.Length * Marshal.SizeOf()) - ); - } - } + /// + /// Pushes compute shader uniforms to the device. + /// + /// A starting offset to be used with dispatch calls. + public unsafe uint PushComputeShaderUniforms( + params T[] uniforms + ) where T : unmanaged + { + fixed (T* ptr = &uniforms[0]) + { + return Refresh.Refresh_PushComputeShaderUniforms( + Device.Handle, + Handle, + (IntPtr) ptr, + (uint) (uniforms.Length * Marshal.SizeOf()) + ); + } + } - /// - /// Clears the render targets on the current framebuffer to a single color or depth/stencil value. - /// NOTE: It is recommended that you clear when beginning render passes unless you have a good reason to clear mid-pass. - /// - /// The area of the framebuffer to clear. - /// Whether to clear colors, depth, or stencil value, or multiple. - /// The depth/stencil clear values. Will be ignored if color is not provided in ClearOptions. - /// The color clear values. Must provide one per render target. Can be omitted if depth/stencil is not cleared. - public unsafe void Clear( - in Rect clearRect, - ClearOptionsFlags clearOptions, - in DepthStencilValue depthStencilClearValue, - params Vector4[] clearColors - ) { - Refresh.Vec4* colors = stackalloc Refresh.Vec4[clearColors.Length]; - for (var i = 0; i < clearColors.Length; i++) - { - colors[i] = new Refresh.Vec4 - { - x = clearColors[i].X, - y = clearColors[i].Y, - z = clearColors[i].Z, - w = clearColors[i].W - }; - } + /// + /// Clears the render targets on the current framebuffer to a single color or depth/stencil value. + /// NOTE: It is recommended that you clear when beginning render passes unless you have a good reason to clear mid-pass. + /// + /// The area of the framebuffer to clear. + /// Whether to clear colors, depth, or stencil value, or multiple. + /// The depth/stencil clear values. Will be ignored if color is not provided in ClearOptions. + /// The color clear values. Must provide one per render target. Can be omitted if depth/stencil is not cleared. + public unsafe void Clear( + in Rect clearRect, + ClearOptionsFlags clearOptions, + in DepthStencilValue depthStencilClearValue, + params Vector4[] clearColors + ) + { + Refresh.Vec4* colors = stackalloc Refresh.Vec4[clearColors.Length]; + for (var i = 0; i < clearColors.Length; i++) + { + colors[i] = new Refresh.Vec4 + { + x = clearColors[i].X, + y = clearColors[i].Y, + z = clearColors[i].Z, + w = clearColors[i].W + }; + } - Refresh.Refresh_Clear( - Device.Handle, - Handle, - clearRect.ToRefresh(), - (Refresh.ClearOptionsFlags)clearOptions, - (IntPtr) colors, - (uint) clearColors.Length, - depthStencilClearValue.ToRefresh() - ); - } + Refresh.Refresh_Clear( + Device.Handle, + Handle, + clearRect.ToRefresh(), + (Refresh.ClearOptionsFlags) clearOptions, + (IntPtr) colors, + (uint) clearColors.Length, + depthStencilClearValue.ToRefresh() + ); + } - /// - /// Draws using instanced rendering. - /// It is an error to call this method unless two vertex buffers have been bound. - /// - /// The starting index offset for the vertex buffer. - /// The starting index offset for the index buffer. - /// The number of primitives to draw. - /// The number of instances to draw. - /// An offset value obtained from PushVertexShaderUniforms. If no uniforms are required then use 0. - /// An offset value obtained from PushFragmentShaderUniforms. If no uniforms are required the use 0. - public void DrawInstancedPrimitives( - uint baseVertex, - uint startIndex, - uint primitiveCount, - uint instanceCount, - uint vertexParamOffset, - uint fragmentParamOffset - ) { - Refresh.Refresh_DrawInstancedPrimitives( - Device.Handle, - Handle, - baseVertex, - startIndex, - primitiveCount, - instanceCount, - vertexParamOffset, - fragmentParamOffset - ); - } + /// + /// Draws using instanced rendering. + /// It is an error to call this method unless two vertex buffers have been bound. + /// + /// The starting index offset for the vertex buffer. + /// The starting index offset for the index buffer. + /// The number of primitives to draw. + /// The number of instances to draw. + /// An offset value obtained from PushVertexShaderUniforms. If no uniforms are required then use 0. + /// An offset value obtained from PushFragmentShaderUniforms. If no uniforms are required the use 0. + public void DrawInstancedPrimitives( + uint baseVertex, + uint startIndex, + uint primitiveCount, + uint instanceCount, + uint vertexParamOffset, + uint fragmentParamOffset + ) + { + Refresh.Refresh_DrawInstancedPrimitives( + Device.Handle, + Handle, + baseVertex, + startIndex, + primitiveCount, + instanceCount, + vertexParamOffset, + fragmentParamOffset + ); + } - /// - /// Draws using a vertex buffer and an index buffer. - /// - /// The starting index offset for the vertex buffer. - /// The starting index offset for the index buffer. - /// The number of primitives to draw. - /// An offset value obtained from PushVertexShaderUniforms. If no uniforms are required then use 0. - /// An offset value obtained from PushFragmentShaderUniforms. If no uniforms are required the use 0. - public void DrawIndexedPrimitives( - uint baseVertex, - uint startIndex, - uint primitiveCount, - uint vertexParamOffset, - uint fragmentParamOffset - ) { - Refresh.Refresh_DrawIndexedPrimitives( - Device.Handle, - Handle, - baseVertex, - startIndex, - primitiveCount, - vertexParamOffset, - fragmentParamOffset - ); - } + /// + /// Draws using a vertex buffer and an index buffer. + /// + /// The starting index offset for the vertex buffer. + /// The starting index offset for the index buffer. + /// The number of primitives to draw. + /// An offset value obtained from PushVertexShaderUniforms. If no uniforms are required then use 0. + /// An offset value obtained from PushFragmentShaderUniforms. If no uniforms are required the use 0. + public void DrawIndexedPrimitives( + uint baseVertex, + uint startIndex, + uint primitiveCount, + uint vertexParamOffset, + uint fragmentParamOffset + ) + { + Refresh.Refresh_DrawIndexedPrimitives( + Device.Handle, + Handle, + baseVertex, + startIndex, + primitiveCount, + vertexParamOffset, + fragmentParamOffset + ); + } - /// - /// Draws using a vertex buffer. - /// - /// - /// - /// - /// - public void DrawPrimitives( - uint vertexStart, - uint primitiveCount, - uint vertexParamOffset, - uint fragmentParamOffset - ) { - Refresh.Refresh_DrawPrimitives( - Device.Handle, - Handle, - vertexStart, - primitiveCount, - vertexParamOffset, - fragmentParamOffset - ); - } + /// + /// Draws using a vertex buffer. + /// + /// + /// + /// + /// + public void DrawPrimitives( + uint vertexStart, + uint primitiveCount, + uint vertexParamOffset, + uint fragmentParamOffset + ) + { + Refresh.Refresh_DrawPrimitives( + Device.Handle, + Handle, + vertexStart, + primitiveCount, + vertexParamOffset, + fragmentParamOffset + ); + } - /// - /// Ends the current render pass. - /// This must be called before beginning another render pass or submitting the command buffer. - /// - public void EndRenderPass() - { - Refresh.Refresh_EndRenderPass( - Device.Handle, - Handle - ); - } + /// + /// Ends the current render pass. + /// This must be called before beginning another render pass or submitting the command buffer. + /// + public void EndRenderPass() + { + Refresh.Refresh_EndRenderPass( + Device.Handle, + Handle + ); + } - /// - /// Prepares a texture to be presented to a window. - /// - /// The texture to present. - /// The area of the window to present to. - /// The filter to use when the texture size differs from the destination rectangle. - public void QueuePresent( - in Texture texture, - in Rect destinationRectangle, - Filter filter, + /// + /// Prepares a texture to be presented to a window. + /// + /// The texture to present. + /// The area of the window to present to. + /// The filter to use when the texture size differs from the destination rectangle. + public void QueuePresent( + in Texture texture, + in Rect destinationRectangle, + Filter filter, OSWindow window - ) { - var refreshRect = destinationRectangle.ToRefresh(); - var refreshTextureSlice = new Refresh.TextureSlice - { - texture = texture.Handle, - rectangle = new Refresh.Rect - { - x = 0, - y = 0, - w = (int)texture.Width, - h = (int)texture.Height - }, - layer = 0, - level = 0, - depth = 0 - }; + ) + { + var refreshRect = destinationRectangle.ToRefresh(); + var refreshTextureSlice = new Refresh.TextureSlice + { + texture = texture.Handle, + rectangle = new Refresh.Rect + { + x = 0, + y = 0, + w = (int) texture.Width, + h = (int) texture.Height + }, + layer = 0, + level = 0, + depth = 0 + }; - Refresh.Refresh_QueuePresent( - Device.Handle, - Handle, - refreshTextureSlice, - refreshRect, - (Refresh.Filter)filter, + Refresh.Refresh_QueuePresent( + Device.Handle, + Handle, + refreshTextureSlice, + refreshRect, + (Refresh.Filter) filter, window.Handle - ); - } + ); + } - /// - /// Prepares a texture slice to be presented to a window. - /// - /// The texture slice to present. - /// The area of the window to present to. - /// The filter to use when the texture size differs from the destination rectangle. - public void QueuePresent( - in TextureSlice textureSlice, - in Rect destinationRectangle, - Filter filter, + /// + /// Prepares a texture slice to be presented to a window. + /// + /// The texture slice to present. + /// The area of the window to present to. + /// The filter to use when the texture size differs from the destination rectangle. + public void QueuePresent( + in TextureSlice textureSlice, + in Rect destinationRectangle, + Filter filter, OSWindow window - ) { - var refreshTextureSlice = textureSlice.ToRefreshTextureSlice(); - var refreshRect = destinationRectangle.ToRefresh(); + ) + { + var refreshTextureSlice = textureSlice.ToRefreshTextureSlice(); + var refreshRect = destinationRectangle.ToRefresh(); - Refresh.Refresh_QueuePresent( - Device.Handle, - Handle, - refreshTextureSlice, - refreshRect, - (Refresh.Filter) filter, + Refresh.Refresh_QueuePresent( + Device.Handle, + Handle, + refreshTextureSlice, + refreshRect, + (Refresh.Filter) filter, window.Handle - ); - } + ); + } - /// - /// Prepares a texture slice to be presented to a window. - /// This particular variant of this method will present to the entire window area. - /// - /// The texture slice to present. - /// The filter to use when the texture size differs from the window size. - public void QueuePresent( - in TextureSlice textureSlice, - Filter filter, + /// + /// Prepares a texture slice to be presented to a window. + /// This particular variant of this method will present to the entire window area. + /// + /// The texture slice to present. + /// The filter to use when the texture size differs from the window size. + public void QueuePresent( + in TextureSlice textureSlice, + Filter filter, OSWindow window - ) { - Refresh.Refresh_QueuePresent( - Device.Handle, - Handle, - textureSlice.ToRefreshTextureSlice(), - IntPtr.Zero, - (Refresh.Filter) filter, + ) + { + Refresh.Refresh_QueuePresent( + Device.Handle, + Handle, + textureSlice.ToRefreshTextureSlice(), + IntPtr.Zero, + (Refresh.Filter) filter, window.Handle - ); - } + ); + } - /// - /// Prepares a texture to be presented to a window. - /// This particular variant of this method will present to the entire window area. - /// - /// The texture to present. - /// The filter to use when the texture size differs from the window size. - public void QueuePresent( - Texture texture, - Filter filter, + /// + /// Prepares a texture to be presented to a window. + /// This particular variant of this method will present to the entire window area. + /// + /// The texture to present. + /// The filter to use when the texture size differs from the window size. + public void QueuePresent( + Texture texture, + Filter filter, OSWindow window - ) { - var refreshTextureSlice = new Refresh.TextureSlice - { - texture = texture.Handle, - rectangle = new Refresh.Rect - { - x = 0, - y = 0, - w = (int) texture.Width, - h = (int) texture.Height - }, - layer = 0, - level = 0, - depth = 0 - }; + ) + { + var refreshTextureSlice = new Refresh.TextureSlice + { + texture = texture.Handle, + rectangle = new Refresh.Rect + { + x = 0, + y = 0, + w = (int) texture.Width, + h = (int) texture.Height + }, + layer = 0, + level = 0, + depth = 0 + }; - Refresh.Refresh_QueuePresent( - Device.Handle, - Handle, - refreshTextureSlice, - IntPtr.Zero, - (Refresh.Filter) filter, + Refresh.Refresh_QueuePresent( + Device.Handle, + Handle, + refreshTextureSlice, + IntPtr.Zero, + (Refresh.Filter) filter, window.Handle - ); - } + ); + } - /// - /// Copies arbitrary data into a buffer. - /// - /// The buffer to copy into. - /// Pointer to the data to copy into the buffer. - /// Specifies where in the buffer to copy data. - /// The length of data that should be copied. - /// Specifies whether the buffer should be copied in immediate or deferred mode. When in doubt, use deferred. - public void SetBufferData( - Buffer buffer, - IntPtr dataPtr, - uint bufferOffsetInBytes, - uint dataLengthInBytes - ) { - Refresh.Refresh_SetBufferData( - Device.Handle, - Handle, - buffer.Handle, - bufferOffsetInBytes, - dataPtr, - dataLengthInBytes - ); - } + /// + /// Copies arbitrary data into a buffer. + /// + /// The buffer to copy into. + /// Pointer to the data to copy into the buffer. + /// Specifies where in the buffer to copy data. + /// The length of data that should be copied. + /// Specifies whether the buffer should be copied in immediate or deferred mode. When in doubt, use deferred. + public void SetBufferData( + Buffer buffer, + IntPtr dataPtr, + uint bufferOffsetInBytes, + uint dataLengthInBytes + ) + { + Refresh.Refresh_SetBufferData( + Device.Handle, + Handle, + buffer.Handle, + bufferOffsetInBytes, + dataPtr, + dataLengthInBytes + ); + } - /// - /// Copies array data into a buffer. - /// - /// The buffer to copy to. - /// The array to copy from. - /// Specifies where in the buffer to start copying. - /// The index of the first element to copy from the array. - /// How many elements to copy. - /// Specifies whether the buffer should be copied in immediate or deferred mode. When in doubt, use deferred. - public unsafe void SetBufferData( - Buffer buffer, - T[] data, - uint bufferOffsetInBytes, - uint startElement, - uint numElements - ) where T : unmanaged - { - var elementSize = Marshal.SizeOf(); + /// + /// Copies array data into a buffer. + /// + /// The buffer to copy to. + /// The array to copy from. + /// Specifies where in the buffer to start copying. + /// The index of the first element to copy from the array. + /// How many elements to copy. + /// Specifies whether the buffer should be copied in immediate or deferred mode. When in doubt, use deferred. + public unsafe void SetBufferData( + Buffer buffer, + T[] data, + uint bufferOffsetInBytes, + uint startElement, + uint numElements + ) where T : unmanaged + { + var elementSize = Marshal.SizeOf(); - fixed (T* ptr = &data[0]) - { - var dataPtr = ptr + (startElement * elementSize); + fixed (T* ptr = &data[0]) + { + var dataPtr = ptr + (startElement * elementSize); - Refresh.Refresh_SetBufferData( - Device.Handle, - Handle, - buffer.Handle, - bufferOffsetInBytes, - (IntPtr) dataPtr, - (uint) (numElements * elementSize) - ); - } - } + Refresh.Refresh_SetBufferData( + Device.Handle, + Handle, + buffer.Handle, + bufferOffsetInBytes, + (IntPtr) dataPtr, + (uint) (numElements * elementSize) + ); + } + } - /// - /// Copies array data into a buffer. - /// - /// The buffer to copy to. - /// The array to copy from. - /// Specifies where in the buffer to start copying. - /// Specifies whether the buffer should be copied in immediate or deferred mode. When in doubt, use deferred. - public unsafe void SetBufferData( - Buffer buffer, - T[] data, - uint bufferOffsetInBytes = 0 - ) where T : unmanaged - { - SetBufferData( - buffer, - data, - bufferOffsetInBytes, - 0, - (uint) data.Length - ); - } + /// + /// Copies array data into a buffer. + /// + /// The buffer to copy to. + /// The array to copy from. + /// Specifies where in the buffer to start copying. + /// Specifies whether the buffer should be copied in immediate or deferred mode. When in doubt, use deferred. + public unsafe void SetBufferData( + Buffer buffer, + T[] data, + uint bufferOffsetInBytes = 0 + ) where T : unmanaged + { + SetBufferData( + buffer, + data, + bufferOffsetInBytes, + 0, + (uint) data.Length + ); + } - /// - /// Asynchronously copies data into a texture. - /// - /// The texture slice to copy into. - /// A pointer to an array of data to copy from. - /// The amount of data to copy from the array. - public void SetTextureData(in TextureSlice textureSlice, IntPtr dataPtr, uint dataLengthInBytes) - { - Refresh.Refresh_SetTextureData( - Device.Handle, - Handle, - textureSlice.ToRefreshTextureSlice(), - dataPtr, - dataLengthInBytes - ); - } + /// + /// Asynchronously copies data into a texture. + /// + /// The texture slice to copy into. + /// A pointer to an array of data to copy from. + /// The amount of data to copy from the array. + public void SetTextureData(in TextureSlice textureSlice, IntPtr dataPtr, uint dataLengthInBytes) + { + Refresh.Refresh_SetTextureData( + Device.Handle, + Handle, + textureSlice.ToRefreshTextureSlice(), + dataPtr, + dataLengthInBytes + ); + } - /// - /// Asynchronously copies data into a texture. - /// This variant copies into the entire texture. - /// - /// A pointer to an array of data to copy from. - /// The amount of data to copy from the array. - public void SetTextureData(Texture texture, IntPtr dataPtr, uint dataLengthInBytes) - { - SetTextureData(new TextureSlice(texture), dataPtr, dataLengthInBytes); - } + /// + /// Asynchronously copies data into a texture. + /// This variant copies into the entire texture. + /// + /// A pointer to an array of data to copy from. + /// The amount of data to copy from the array. + public void SetTextureData(Texture texture, IntPtr dataPtr, uint dataLengthInBytes) + { + SetTextureData(new TextureSlice(texture), dataPtr, dataLengthInBytes); + } - /// - /// Asynchronously copies data into the texture. - /// - /// The texture slice to copy into. - /// An array of data to copy into the texture. - public unsafe void SetTextureData(in TextureSlice textureSlice, T[] data) where T : unmanaged - { - var size = Marshal.SizeOf(); + /// + /// Asynchronously copies data into the texture. + /// + /// The texture slice to copy into. + /// An array of data to copy into the texture. + public unsafe void SetTextureData(in TextureSlice textureSlice, T[] data) where T : unmanaged + { + var size = Marshal.SizeOf(); - fixed (T* ptr = &data[0]) - { - Refresh.Refresh_SetTextureData( - Device.Handle, - Handle, - textureSlice.ToRefreshTextureSlice(), - (IntPtr) ptr, - (uint) (data.Length * size) - ); - } - } + fixed (T* ptr = &data[0]) + { + Refresh.Refresh_SetTextureData( + Device.Handle, + Handle, + textureSlice.ToRefreshTextureSlice(), + (IntPtr) ptr, + (uint) (data.Length * size) + ); + } + } - /// - /// Asynchronously copies data into a texture. - /// This variant copies data into the entire texture. - /// - /// An array of data to copy into the texture. - public unsafe void SetTextureData(Texture texture, T[] data) where T : unmanaged - { - SetTextureData(new TextureSlice(texture), data); - } + /// + /// Asynchronously copies data into a texture. + /// This variant copies data into the entire texture. + /// + /// An array of data to copy into the texture. + public unsafe void SetTextureData(Texture texture, T[] data) where T : unmanaged + { + SetTextureData(new TextureSlice(texture), data); + } - /// - /// Performs an asynchronous texture-to-texture copy on the GPU. - /// - /// The texture slice to copy from. - /// The texture slice to copy to. - /// The filter to use if the sizes of the texture slices differ. - public void CopyTextureToTexture( - in TextureSlice sourceTextureSlice, - in TextureSlice destinationTextureSlice, - Filter filter - ) { - var sourceRefreshTextureSlice = sourceTextureSlice.ToRefreshTextureSlice(); - var destRefreshTextureSlice = destinationTextureSlice.ToRefreshTextureSlice(); + /// + /// Performs an asynchronous texture-to-texture copy on the GPU. + /// + /// The texture slice to copy from. + /// The texture slice to copy to. + /// The filter to use if the sizes of the texture slices differ. + public void CopyTextureToTexture( + in TextureSlice sourceTextureSlice, + in TextureSlice destinationTextureSlice, + Filter filter + ) + { + var sourceRefreshTextureSlice = sourceTextureSlice.ToRefreshTextureSlice(); + var destRefreshTextureSlice = destinationTextureSlice.ToRefreshTextureSlice(); - Refresh.Refresh_CopyTextureToTexture( - Device.Handle, - Handle, - sourceRefreshTextureSlice, - destRefreshTextureSlice, - (Refresh.Filter) filter - ); - } + Refresh.Refresh_CopyTextureToTexture( + Device.Handle, + Handle, + sourceRefreshTextureSlice, + destRefreshTextureSlice, + (Refresh.Filter) filter + ); + } - /// - /// Performs an asynchronous texture-to-buffer copy. - /// Note that the buffer is not guaranteed to be filled until you call GraphicsDevice.Wait() - /// - /// - /// - public void CopyTextureToBuffer( - in TextureSlice textureSlice, - Buffer buffer - ) { - var refreshTextureSlice = textureSlice.ToRefreshTextureSlice(); + /// + /// Performs an asynchronous texture-to-buffer copy. + /// Note that the buffer is not guaranteed to be filled until you call GraphicsDevice.Wait() + /// + /// + /// + public void CopyTextureToBuffer( + in TextureSlice textureSlice, + Buffer buffer + ) + { + var refreshTextureSlice = textureSlice.ToRefreshTextureSlice(); - Refresh.Refresh_CopyTextureToBuffer( - Device.Handle, - Handle, - refreshTextureSlice, - buffer.Handle - ); - } - } + Refresh.Refresh_CopyTextureToBuffer( + Device.Handle, + Handle, + refreshTextureSlice, + buffer.Handle + ); + } + } } diff --git a/src/Graphics/GraphicsDevice.cs b/src/Graphics/GraphicsDevice.cs index c1c0e0f8..59c499a7 100644 --- a/src/Graphics/GraphicsDevice.cs +++ b/src/Graphics/GraphicsDevice.cs @@ -4,58 +4,59 @@ using RefreshCS; namespace MoonWorks.Graphics { - public class GraphicsDevice : IDisposable - { - public IntPtr Handle { get; } + public class GraphicsDevice : IDisposable + { + public IntPtr Handle { get; } - public bool IsDisposed { get; private set; } + public bool IsDisposed { get; private set; } - private readonly List> resources = new List>(); + private readonly List> resources = new List>(); private Dictionary> resourcesToDestroy = new Dictionary>(); - public GraphicsDevice( - IntPtr deviceWindowHandle, - Refresh.PresentMode presentMode, - bool debugMode, - int initialCommandBufferPoolSize = 4 - ) { - var presentationParameters = new Refresh.PresentationParameters - { - deviceWindowHandle = deviceWindowHandle, - presentMode = presentMode - }; + public GraphicsDevice( + IntPtr deviceWindowHandle, + Refresh.PresentMode presentMode, + bool debugMode, + int initialCommandBufferPoolSize = 4 + ) + { + var presentationParameters = new Refresh.PresentationParameters + { + deviceWindowHandle = deviceWindowHandle, + presentMode = presentMode + }; - Handle = Refresh.Refresh_CreateDevice( - presentationParameters, - Conversions.BoolToByte(debugMode) - ); - } + Handle = Refresh.Refresh_CreateDevice( + presentationParameters, + Conversions.BoolToByte(debugMode) + ); + } - public CommandBuffer AcquireCommandBuffer() - { - return new CommandBuffer(this, Refresh.Refresh_AcquireCommandBuffer(Handle, 0)); - } + public CommandBuffer AcquireCommandBuffer() + { + return new CommandBuffer(this, Refresh.Refresh_AcquireCommandBuffer(Handle, 0)); + } - public unsafe void Submit(params CommandBuffer[] commandBuffers) - { - var commandBufferPtrs = stackalloc IntPtr[commandBuffers.Length]; + public unsafe void Submit(params CommandBuffer[] commandBuffers) + { + var commandBufferPtrs = stackalloc IntPtr[commandBuffers.Length]; - for (var i = 0; i < commandBuffers.Length; i += 1) - { - commandBufferPtrs[i] = commandBuffers[i].Handle; - } + for (var i = 0; i < commandBuffers.Length; i += 1) + { + commandBufferPtrs[i] = commandBuffers[i].Handle; + } - Refresh.Refresh_Submit( - Handle, - (uint) commandBuffers.Length, - (IntPtr) commandBufferPtrs - ); - } + Refresh.Refresh_Submit( + Handle, + (uint) commandBuffers.Length, + (IntPtr) commandBufferPtrs + ); + } - public void Wait() - { - Refresh.Refresh_Wait(Handle); - } + public void Wait() + { + Refresh.Refresh_Wait(Handle); + } internal void SubmitDestroyCommandBuffer() { @@ -77,60 +78,60 @@ namespace MoonWorks.Graphics resourcesToDestroy.Add(resource.Handle, destroyFunction); } - internal void AddResourceReference(WeakReference resourceReference) - { - lock (resources) - { - resources.Add(resourceReference); - } - } + internal void AddResourceReference(WeakReference resourceReference) + { + lock (resources) + { + resources.Add(resourceReference); + } + } - internal void RemoveResourceReference(WeakReference resourceReference) - { - lock (resources) - { - resources.Remove(resourceReference); - } - } + internal void RemoveResourceReference(WeakReference resourceReference) + { + lock (resources) + { + resources.Remove(resourceReference); + } + } - protected virtual void Dispose(bool disposing) - { - if (!IsDisposed) - { - if (disposing) - { - lock (resources) - { + protected virtual void Dispose(bool disposing) + { + if (!IsDisposed) + { + if (disposing) + { + lock (resources) + { for (var i = resources.Count - 1; i >= 0; i--) { var resource = resources[i]; if (resource.TryGetTarget(out var target)) - { - target.Dispose(); - } + { + target.Dispose(); + } } - resources.Clear(); - } + resources.Clear(); + } SubmitDestroyCommandBuffer(); - Refresh.Refresh_DestroyDevice(Handle); - } + Refresh.Refresh_DestroyDevice(Handle); + } - IsDisposed = true; - } - } + IsDisposed = true; + } + } - ~GraphicsDevice() - { - // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method - Dispose(disposing: false); - } + ~GraphicsDevice() + { + // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method + Dispose(disposing: false); + } - public void Dispose() - { - // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - } + public void Dispose() + { + // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + } } diff --git a/src/Graphics/GraphicsResource.cs b/src/Graphics/GraphicsResource.cs index a39aa0e9..e6f749ed 100644 --- a/src/Graphics/GraphicsResource.cs +++ b/src/Graphics/GraphicsResource.cs @@ -2,51 +2,51 @@ namespace MoonWorks.Graphics { - public abstract class GraphicsResource : IDisposable - { - public GraphicsDevice Device { get; } - public IntPtr Handle { get; protected set; } + public abstract class GraphicsResource : IDisposable + { + public GraphicsDevice Device { get; } + public IntPtr Handle { get; protected set; } - public bool IsDisposed { get; private set; } - protected abstract Action QueueDestroyFunction { get; } + public bool IsDisposed { get; private set; } + protected abstract Action QueueDestroyFunction { get; } - private WeakReference selfReference; + private WeakReference selfReference; - public GraphicsResource(GraphicsDevice device) - { - Device = device; + public GraphicsResource(GraphicsDevice device) + { + Device = device; - selfReference = new WeakReference(this); - Device.AddResourceReference(selfReference); - } + selfReference = new WeakReference(this); + Device.AddResourceReference(selfReference); + } - protected virtual void Dispose(bool disposing) - { - if (!IsDisposed) - { + protected virtual void Dispose(bool disposing) + { + if (!IsDisposed) + { Device.PrepareDestroyResource(this, QueueDestroyFunction); - if (selfReference != null) - { - Device.RemoveResourceReference(selfReference); - selfReference = null; - } + if (selfReference != null) + { + Device.RemoveResourceReference(selfReference); + selfReference = null; + } - IsDisposed = true; - } - } + IsDisposed = true; + } + } - ~GraphicsResource() - { - // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method - Dispose(disposing: false); - } + ~GraphicsResource() + { + // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method + Dispose(disposing: false); + } - public void Dispose() - { - // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - } + public void Dispose() + { + // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + } } diff --git a/src/Graphics/PackedVector/Alpha8.cs b/src/Graphics/PackedVector/Alpha8.cs index 8139bae3..a6eb8c48 100644 --- a/src/Graphics/PackedVector/Alpha8.cs +++ b/src/Graphics/PackedVector/Alpha8.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/Bgr565.cs b/src/Graphics/PackedVector/Bgr565.cs index 416c49c3..cc932c86 100644 --- a/src/Graphics/PackedVector/Bgr565.cs +++ b/src/Graphics/PackedVector/Bgr565.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/Bgra4444.cs b/src/Graphics/PackedVector/Bgra4444.cs index 96f62f89..5726e720 100644 --- a/src/Graphics/PackedVector/Bgra4444.cs +++ b/src/Graphics/PackedVector/Bgra4444.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/Bgra5551.cs b/src/Graphics/PackedVector/Bgra5551.cs index 84bcce16..6ac652ac 100644 --- a/src/Graphics/PackedVector/Bgra5551.cs +++ b/src/Graphics/PackedVector/Bgra5551.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/Byte4.cs b/src/Graphics/PackedVector/Byte4.cs index 03c08bd8..f98e4967 100644 --- a/src/Graphics/PackedVector/Byte4.cs +++ b/src/Graphics/PackedVector/Byte4.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/HalfSingle.cs b/src/Graphics/PackedVector/HalfSingle.cs index 245af11d..7bf4d578 100644 --- a/src/Graphics/PackedVector/HalfSingle.cs +++ b/src/Graphics/PackedVector/HalfSingle.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/HalfTypeHelper.cs b/src/Graphics/PackedVector/HalfTypeHelper.cs index 857e7ac8..5f9f59de 100644 --- a/src/Graphics/PackedVector/HalfTypeHelper.cs +++ b/src/Graphics/PackedVector/HalfTypeHelper.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -104,7 +104,7 @@ namespace MoonWorks.Graphics internal static float Convert(ushort value) { uint rst; - uint mantissa = (uint)(value & 1023); + uint mantissa = (uint) (value & 1023); uint exp = 0xfffffff2; if ((value & -33792) == 0) diff --git a/src/Graphics/PackedVector/HalfVector2.cs b/src/Graphics/PackedVector/HalfVector2.cs index 7a6d0bcf..e8ed5213 100644 --- a/src/Graphics/PackedVector/HalfVector2.cs +++ b/src/Graphics/PackedVector/HalfVector2.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/HalfVector4.cs b/src/Graphics/PackedVector/HalfVector4.cs index e99d1c4d..d93f29eb 100644 --- a/src/Graphics/PackedVector/HalfVector4.cs +++ b/src/Graphics/PackedVector/HalfVector4.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/IPackedVector.cs b/src/Graphics/PackedVector/IPackedVector.cs index 8a107201..6c0df0ee 100644 --- a/src/Graphics/PackedVector/IPackedVector.cs +++ b/src/Graphics/PackedVector/IPackedVector.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/NormalizedByte2.cs b/src/Graphics/PackedVector/NormalizedByte2.cs index 8ed0933f..26c25bd8 100644 --- a/src/Graphics/PackedVector/NormalizedByte2.cs +++ b/src/Graphics/PackedVector/NormalizedByte2.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/NormalizedByte4.cs b/src/Graphics/PackedVector/NormalizedByte4.cs index af8c434d..b3bf6c21 100644 --- a/src/Graphics/PackedVector/NormalizedByte4.cs +++ b/src/Graphics/PackedVector/NormalizedByte4.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/NormalizedShort2.cs b/src/Graphics/PackedVector/NormalizedShort2.cs index 82595ec7..0b094392 100644 --- a/src/Graphics/PackedVector/NormalizedShort2.cs +++ b/src/Graphics/PackedVector/NormalizedShort2.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/NormalizedShort4.cs b/src/Graphics/PackedVector/NormalizedShort4.cs index 401874a3..4d3c6c51 100644 --- a/src/Graphics/PackedVector/NormalizedShort4.cs +++ b/src/Graphics/PackedVector/NormalizedShort4.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/Rg32.cs b/src/Graphics/PackedVector/Rg32.cs index cfda3cfb..fd95b030 100644 --- a/src/Graphics/PackedVector/Rg32.cs +++ b/src/Graphics/PackedVector/Rg32.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/Rgba1010102.cs b/src/Graphics/PackedVector/Rgba1010102.cs index bedd3346..78909d20 100644 --- a/src/Graphics/PackedVector/Rgba1010102.cs +++ b/src/Graphics/PackedVector/Rgba1010102.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/Rgba64.cs b/src/Graphics/PackedVector/Rgba64.cs index 7d5bb30f..a3701ad0 100644 --- a/src/Graphics/PackedVector/Rgba64.cs +++ b/src/Graphics/PackedVector/Rgba64.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/Short2.cs b/src/Graphics/PackedVector/Short2.cs index 5577eb3a..02a90694 100644 --- a/src/Graphics/PackedVector/Short2.cs +++ b/src/Graphics/PackedVector/Short2.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Graphics/PackedVector/Short4.cs b/src/Graphics/PackedVector/Short4.cs index da0e1e44..c04c0810 100644 --- a/src/Graphics/PackedVector/Short4.cs +++ b/src/Graphics/PackedVector/Short4.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -192,7 +192,7 @@ namespace MoonWorks.Graphics static ulong Pack(float x, float y, float z, float w) { return (ulong) ( - ((long) System.Math.Round(MathHelper.Clamp(x, -32768, 32767)) & 0xFFFF ) | + ((long) System.Math.Round(MathHelper.Clamp(x, -32768, 32767)) & 0xFFFF) | (((long) System.Math.Round(MathHelper.Clamp(y, -32768, 32767)) << 16) & 0xFFFF0000) | (((long) System.Math.Round(MathHelper.Clamp(z, -32768, 32767)) << 32) & 0xFFFF00000000) | ((long) System.Math.Round(MathHelper.Clamp(w, -32768, 32767)) << 48) diff --git a/src/Graphics/RefreshEnums.cs b/src/Graphics/RefreshEnums.cs index 4cb9ffba..4ec22845 100644 --- a/src/Graphics/RefreshEnums.cs +++ b/src/Graphics/RefreshEnums.cs @@ -5,298 +5,298 @@ */ namespace MoonWorks.Graphics { - public enum PresentMode - { - Immediate, - Mailbox, - FIFO, - FIFORelaxed - } + public enum PresentMode + { + Immediate, + Mailbox, + FIFO, + FIFORelaxed + } - public enum PrimitiveType - { - PointList, - LineList, - LineStrip, - TriangleList, - TriangleStrip - } + public enum PrimitiveType + { + PointList, + LineList, + LineStrip, + TriangleList, + TriangleStrip + } - /// - /// Describes the operation that a render pass will use when loading a render target. - /// - public enum LoadOp - { - Load, - Clear, - DontCare - } + /// + /// Describes the operation that a render pass will use when loading a render target. + /// + public enum LoadOp + { + Load, + Clear, + DontCare + } - /// - /// Describes the operation that a render pass will use when storing a render target. - /// - public enum StoreOp - { - Store, - DontCare - } + /// + /// Describes the operation that a render pass will use when storing a render target. + /// + public enum StoreOp + { + Store, + DontCare + } - [Flags] - public enum ClearOptionsFlags : uint - { - Color = 1, - Depth = 2, - Stencil = 4, - DepthStencil = Depth | Stencil, - All = Color | Depth | Stencil - } + [Flags] + public enum ClearOptionsFlags : uint + { + Color = 1, + Depth = 2, + Stencil = 4, + DepthStencil = Depth | Stencil, + All = Color | Depth | Stencil + } - public enum IndexElementSize - { - Sixteen, - ThirtyTwo - } + public enum IndexElementSize + { + Sixteen, + ThirtyTwo + } - public enum TextureFormat - { - R8G8B8A8, - R5G6B5, - A1R5G5B5, - B4G4R4A4, - BC1, - BC2, - BC3, - R8G8_SNORM, - R8G8B8A8_SNORM, - A2R10G10B10, - R16G16, - R16G16B16A16, - R8, - R32_SFLOAT, - R32G32_SFLOAT, - R32G32B32A32_SFLOAT, - R16_SFLOAT, - R16G16_SFLOAT, - R16G16B16A16_SFLOAT, - D16, - D32, - D16S8, - D32S8 - } + public enum TextureFormat + { + R8G8B8A8, + R5G6B5, + A1R5G5B5, + B4G4R4A4, + BC1, + BC2, + BC3, + R8G8_SNORM, + R8G8B8A8_SNORM, + A2R10G10B10, + R16G16, + R16G16B16A16, + R8, + R32_SFLOAT, + R32G32_SFLOAT, + R32G32B32A32_SFLOAT, + R16_SFLOAT, + R16G16_SFLOAT, + R16G16B16A16_SFLOAT, + D16, + D32, + D16S8, + D32S8 + } - [Flags] - public enum TextureUsageFlags : uint - { - Sampler = 1, - ColorTarget = 2, - DepthStencilTarget = 4 - } + [Flags] + public enum TextureUsageFlags : uint + { + Sampler = 1, + ColorTarget = 2, + DepthStencilTarget = 4 + } - public enum SampleCount - { - One, - Two, - Four, - Eight, - Sixteen, - ThirtyTwo, - SixtyFour - } + public enum SampleCount + { + One, + Two, + Four, + Eight, + Sixteen, + ThirtyTwo, + SixtyFour + } - public enum CubeMapFace : uint - { - PositiveX, - NegativeX, - PositiveY, - NegativeY, - PositiveZ, - NegativeZ - } + public enum CubeMapFace : uint + { + PositiveX, + NegativeX, + PositiveY, + NegativeY, + PositiveZ, + NegativeZ + } - [Flags] - public enum BufferUsageFlags : uint - { - Vertex = 1, - Index = 2, - Compute = 4 - } + [Flags] + public enum BufferUsageFlags : uint + { + Vertex = 1, + Index = 2, + Compute = 4 + } - public enum VertexElementFormat - { - Single, - Vector2, - Vector3, - Vector4, - Color, - Byte4, - Short2, - Short4, - NormalizedShort2, - NormalizedShort4, - HalfVector2, - HalfVector4 - } + public enum VertexElementFormat + { + Single, + Vector2, + Vector3, + Vector4, + Color, + Byte4, + Short2, + Short4, + NormalizedShort2, + NormalizedShort4, + HalfVector2, + HalfVector4 + } - public enum VertexInputRate - { - Vertex, - Instance - } + public enum VertexInputRate + { + Vertex, + Instance + } - public enum FillMode - { - Fill, - Line, - Point - } + public enum FillMode + { + Fill, + Line, + Point + } - public enum CullMode - { - None, - Front, - Back, - FrontAndBack - } + public enum CullMode + { + None, + Front, + Back, + FrontAndBack + } - public enum FrontFace - { - CounterClockwise, - Clockwise - } + public enum FrontFace + { + CounterClockwise, + Clockwise + } - public enum CompareOp - { - Never, - Less, - Equal, - LessOrEqual, - Greater, - NotEqual, - GreaterOrEqual, - Always - } + public enum CompareOp + { + Never, + Less, + Equal, + LessOrEqual, + Greater, + NotEqual, + GreaterOrEqual, + Always + } - public enum StencilOp - { - Keep, - Zero, - Replace, - IncrementAndClamp, - DecrementAndClamp, - Invert, - IncrementAndWrap, - DecrementAndWrap - } + public enum StencilOp + { + Keep, + Zero, + Replace, + IncrementAndClamp, + DecrementAndClamp, + Invert, + IncrementAndWrap, + DecrementAndWrap + } - public enum BlendOp - { - Add, - Subtract, - ReverseSubtract, - Min, - Max - } + public enum BlendOp + { + Add, + Subtract, + ReverseSubtract, + Min, + Max + } - public enum LogicOp - { - Clear, - And, - AndReverse, - Copy, - AndInverted, - NoOp, - Xor, - Or, - Nor, - Equivalent, - Invert, - OrReverse, - CopyInverted, - OrInverted, - Nand, - Set - } + public enum LogicOp + { + Clear, + And, + AndReverse, + Copy, + AndInverted, + NoOp, + Xor, + Or, + Nor, + Equivalent, + Invert, + OrReverse, + CopyInverted, + OrInverted, + Nand, + Set + } - public enum BlendFactor - { - Zero, - One, - SourceColor, - OneMinusSourceColor, - DestinationColor, - OneMinusDestinationColor, - SourceAlpha, - OneMinusSourceAlpha, - DestinationAlpha, - OneMinusDestinationAlpha, - ConstantColor, - OneMinusConstantColor, - ConstantAlpha, - OneMinusConstantAlpha, - SourceAlphaSaturate, - SourceOneColor, - OneMinusSourceOneColor, - SourceOneAlpha, - OneMinusSourceOneAlpha - } + public enum BlendFactor + { + Zero, + One, + SourceColor, + OneMinusSourceColor, + DestinationColor, + OneMinusDestinationColor, + SourceAlpha, + OneMinusSourceAlpha, + DestinationAlpha, + OneMinusDestinationAlpha, + ConstantColor, + OneMinusConstantColor, + ConstantAlpha, + OneMinusConstantAlpha, + SourceAlphaSaturate, + SourceOneColor, + OneMinusSourceOneColor, + SourceOneAlpha, + OneMinusSourceOneAlpha + } - [Flags] - public enum ColorComponentFlags : uint - { - R = 1, - G = 2, - B = 4, - A = 8, + [Flags] + public enum ColorComponentFlags : uint + { + R = 1, + G = 2, + B = 4, + A = 8, - RG = R | G, - RB = R | B, - RA = R | A, - GB = G | B, - GA = G | A, - BA = B | A, + RG = R | G, + RB = R | B, + RA = R | A, + GB = G | B, + GA = G | A, + BA = B | A, - RGB = R | G | B, - RGA = R | G | A, - GBA = G | B | A, + RGB = R | G | B, + RGA = R | G | A, + GBA = G | B | A, - RGBA = R | G | B | A, - None = 0 - } + RGBA = R | G | B | A, + None = 0 + } - public enum ShaderStageType - { - Vertex, - Fragment - } + public enum ShaderStageType + { + Vertex, + Fragment + } - public enum Filter - { - Nearest, - Linear, - Cubic - } + public enum Filter + { + Nearest, + Linear, + Cubic + } - public enum SamplerMipmapMode - { - Nearest, - Linear - } + public enum SamplerMipmapMode + { + Nearest, + Linear + } - public enum SamplerAddressMode - { - Repeat, - MirroredRepeat, - ClampToEdge, - ClampToBorder - } + public enum SamplerAddressMode + { + Repeat, + MirroredRepeat, + ClampToEdge, + ClampToBorder + } - public enum BorderColor - { - FloatTransparentBlack, - IntTransparentBlack, - FloatOpaqueBlack, - IntOpaqueBlack, - FloatOpaqueWhite, - IntOpaqueWhite - } + public enum BorderColor + { + FloatTransparentBlack, + IntTransparentBlack, + FloatOpaqueBlack, + IntOpaqueBlack, + FloatOpaqueWhite, + IntOpaqueWhite + } } diff --git a/src/Graphics/RefreshStructs.cs b/src/Graphics/RefreshStructs.cs index 9e34b792..890bff1a 100644 --- a/src/Graphics/RefreshStructs.cs +++ b/src/Graphics/RefreshStructs.cs @@ -6,115 +6,115 @@ using System.Runtime.InteropServices; */ namespace MoonWorks.Graphics { - [StructLayout(LayoutKind.Sequential)] - public struct DepthStencilValue - { - public float Depth; - public uint Stencil; + [StructLayout(LayoutKind.Sequential)] + public struct DepthStencilValue + { + public float Depth; + public uint Stencil; - // FIXME: can we do an unsafe cast somehow? - public Refresh.DepthStencilValue ToRefresh() - { - return new Refresh.DepthStencilValue - { - depth = Depth, - stencil = Stencil - }; - } - } + // FIXME: can we do an unsafe cast somehow? + public Refresh.DepthStencilValue ToRefresh() + { + return new Refresh.DepthStencilValue + { + depth = Depth, + stencil = Stencil + }; + } + } - [StructLayout(LayoutKind.Sequential)] - public struct Rect - { - public int X; - public int Y; - public int W; - public int H; + [StructLayout(LayoutKind.Sequential)] + public struct Rect + { + public int X; + public int Y; + public int W; + public int H; - // FIXME: can we do an unsafe cast somehow? - public Refresh.Rect ToRefresh() - { - return new Refresh.Rect - { - x = X, - y = Y, - w = W, - h = H - }; - } - } + // FIXME: can we do an unsafe cast somehow? + public Refresh.Rect ToRefresh() + { + return new Refresh.Rect + { + x = X, + y = Y, + w = W, + h = H + }; + } + } - [StructLayout(LayoutKind.Sequential)] - public struct Viewport - { - public float X; - public float Y; - public float W; - public float H; - public float MinDepth; - public float MaxDepth; - } + [StructLayout(LayoutKind.Sequential)] + public struct Viewport + { + public float X; + public float Y; + public float W; + public float H; + public float MinDepth; + public float MaxDepth; + } - [StructLayout(LayoutKind.Sequential)] - public struct VertexBinding - { - public uint Binding; - public uint Stride; - public VertexInputRate InputRate; - } + [StructLayout(LayoutKind.Sequential)] + public struct VertexBinding + { + public uint Binding; + public uint Stride; + public VertexInputRate InputRate; + } - [StructLayout(LayoutKind.Sequential)] - public struct VertexAttribute - { - public uint Location; - public uint Binding; - public VertexElementFormat Format; - public uint Offset; - } + [StructLayout(LayoutKind.Sequential)] + public struct VertexAttribute + { + public uint Location; + public uint Binding; + public VertexElementFormat Format; + public uint Offset; + } - [StructLayout(LayoutKind.Sequential)] - public struct ColorTargetDescription - { - public TextureFormat Format; - public SampleCount MultisampleCount; - public LoadOp LoadOp; - public StoreOp StoreOp; - } + [StructLayout(LayoutKind.Sequential)] + public struct ColorTargetDescription + { + public TextureFormat Format; + public SampleCount MultisampleCount; + public LoadOp LoadOp; + public StoreOp StoreOp; + } - [StructLayout(LayoutKind.Sequential)] - public struct DepthStencilTargetDescription - { - public TextureFormat Format; - public LoadOp LoadOp; - public StoreOp StoreOp; - public LoadOp StencilLoadOp; - public StoreOp StencilStoreOp; - } + [StructLayout(LayoutKind.Sequential)] + public struct DepthStencilTargetDescription + { + public TextureFormat Format; + public LoadOp LoadOp; + public StoreOp StoreOp; + public LoadOp StencilLoadOp; + public StoreOp StencilStoreOp; + } - [StructLayout(LayoutKind.Sequential)] - public struct StencilOpState - { - public StencilOp FailOp; - public StencilOp PassOp; - public StencilOp DepthFailOp; - public CompareOp CompareOp; - public uint CompareMask; - public uint WriteMask; - public uint Reference; + [StructLayout(LayoutKind.Sequential)] + public struct StencilOpState + { + public StencilOp FailOp; + public StencilOp PassOp; + public StencilOp DepthFailOp; + public CompareOp CompareOp; + public uint CompareMask; + public uint WriteMask; + public uint Reference; - // FIXME: can we do an explicit cast here? - public Refresh.StencilOpState ToRefresh() - { - return new Refresh.StencilOpState - { - failOp = (Refresh.StencilOp)FailOp, - passOp = (Refresh.StencilOp)PassOp, - depthFailOp = (Refresh.StencilOp)DepthFailOp, - compareOp = (Refresh.CompareOp)CompareOp, - compareMask = CompareMask, - writeMask = WriteMask, - reference = Reference - }; - } - } + // FIXME: can we do an explicit cast here? + public Refresh.StencilOpState ToRefresh() + { + return new Refresh.StencilOpState + { + failOp = (Refresh.StencilOp) FailOp, + passOp = (Refresh.StencilOp) PassOp, + depthFailOp = (Refresh.StencilOp) DepthFailOp, + compareOp = (Refresh.CompareOp) CompareOp, + compareMask = CompareMask, + writeMask = WriteMask, + reference = Reference + }; + } + } } diff --git a/src/Graphics/Resources/Buffer.cs b/src/Graphics/Resources/Buffer.cs index 61ef5f1f..be11ec27 100644 --- a/src/Graphics/Resources/Buffer.cs +++ b/src/Graphics/Resources/Buffer.cs @@ -1,55 +1,55 @@ -using System; +using System; using System.Runtime.InteropServices; using RefreshCS; namespace MoonWorks.Graphics { - /// - /// Buffers are generic data containers that can be used by the GPU. - /// - public class Buffer : GraphicsResource - { - protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyBuffer; + /// + /// Buffers are generic data containers that can be used by the GPU. + /// + public class Buffer : GraphicsResource + { + protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyBuffer; - /// - /// Creates a buffer. - /// - /// An initialized GraphicsDevice. - /// Specifies how the buffer will be used. - /// The length of the array. Cannot be resized. - public Buffer( - GraphicsDevice device, - BufferUsageFlags usageFlags, - uint sizeInBytes - ) : base(device) - { - Handle = Refresh.Refresh_CreateBuffer( - device.Handle, - (Refresh.BufferUsageFlags) usageFlags, - sizeInBytes - ); - } + /// + /// Creates a buffer. + /// + /// An initialized GraphicsDevice. + /// Specifies how the buffer will be used. + /// The length of the array. Cannot be resized. + public Buffer( + GraphicsDevice device, + BufferUsageFlags usageFlags, + uint sizeInBytes + ) : base(device) + { + Handle = Refresh.Refresh_CreateBuffer( + device.Handle, + (Refresh.BufferUsageFlags) usageFlags, + sizeInBytes + ); + } - /// - /// Reads data out of a buffer and into an array. - /// This operation is only guaranteed to read up-to-date data if GraphicsDevice.Wait is called first. - /// - /// The array that data will be copied to. - /// The length of the data to read. - public unsafe void GetData( - T[] data, - uint dataLengthInBytes - ) where T : unmanaged - { - fixed (T* ptr = &data[0]) - { - Refresh.Refresh_GetBufferData( - Device.Handle, - Handle, - (IntPtr)ptr, - dataLengthInBytes - ); - } - } - } + /// + /// Reads data out of a buffer and into an array. + /// This operation is only guaranteed to read up-to-date data if GraphicsDevice.Wait is called first. + /// + /// The array that data will be copied to. + /// The length of the data to read. + public unsafe void GetData( + T[] data, + uint dataLengthInBytes + ) where T : unmanaged + { + fixed (T* ptr = &data[0]) + { + Refresh.Refresh_GetBufferData( + Device.Handle, + Handle, + (IntPtr) ptr, + dataLengthInBytes + ); + } + } + } } diff --git a/src/Graphics/Resources/ComputePipeline.cs b/src/Graphics/Resources/ComputePipeline.cs index 9f74804d..ed57dcbd 100644 --- a/src/Graphics/Resources/ComputePipeline.cs +++ b/src/Graphics/Resources/ComputePipeline.cs @@ -4,41 +4,42 @@ using System.Runtime.InteropServices; namespace MoonWorks.Graphics { - public class ComputePipeline : GraphicsResource - { - protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyComputePipeline; + public class ComputePipeline : GraphicsResource + { + protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyComputePipeline; - public ShaderStageState ComputeShaderState { get; } + public ShaderStageState ComputeShaderState { get; } - public unsafe ComputePipeline( - GraphicsDevice device, - ShaderStageState computeShaderState, - uint bufferBindingCount, - uint imageBindingCount - ) : base(device) { - var computePipelineLayoutCreateInfo = new Refresh.ComputePipelineLayoutCreateInfo - { - bufferBindingCount = bufferBindingCount, - imageBindingCount = imageBindingCount - }; + public unsafe ComputePipeline( + GraphicsDevice device, + ShaderStageState computeShaderState, + uint bufferBindingCount, + uint imageBindingCount + ) : base(device) + { + var computePipelineLayoutCreateInfo = new Refresh.ComputePipelineLayoutCreateInfo + { + bufferBindingCount = bufferBindingCount, + imageBindingCount = imageBindingCount + }; - var computePipelineCreateInfo = new Refresh.ComputePipelineCreateInfo - { - pipelineLayoutCreateInfo = computePipelineLayoutCreateInfo, - computeShaderState = new Refresh.ShaderStageState - { - entryPointName = computeShaderState.EntryPointName, - shaderModule = computeShaderState.ShaderModule.Handle, - uniformBufferSize = computeShaderState.UniformBufferSize - } - }; + var computePipelineCreateInfo = new Refresh.ComputePipelineCreateInfo + { + pipelineLayoutCreateInfo = computePipelineLayoutCreateInfo, + computeShaderState = new Refresh.ShaderStageState + { + entryPointName = computeShaderState.EntryPointName, + shaderModule = computeShaderState.ShaderModule.Handle, + uniformBufferSize = computeShaderState.UniformBufferSize + } + }; - Handle = Refresh.Refresh_CreateComputePipeline( - device.Handle, - computePipelineCreateInfo - ); + Handle = Refresh.Refresh_CreateComputePipeline( + device.Handle, + computePipelineCreateInfo + ); - ComputeShaderState = computeShaderState; - } - } + ComputeShaderState = computeShaderState; + } + } } diff --git a/src/Graphics/Resources/Framebuffer.cs b/src/Graphics/Resources/Framebuffer.cs index 9040551e..5d3439f5 100644 --- a/src/Graphics/Resources/Framebuffer.cs +++ b/src/Graphics/Resources/Framebuffer.cs @@ -1,81 +1,81 @@ -using System; +using System; using System.Collections.Generic; using RefreshCS; namespace MoonWorks.Graphics { - /// - /// A framebuffer is a collection of render targets that is rendered to during a render pass. - /// - public class Framebuffer : GraphicsResource - { - protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyFramebuffer; + /// + /// A framebuffer is a collection of render targets that is rendered to during a render pass. + /// + public class Framebuffer : GraphicsResource + { + protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyFramebuffer; - public RenderTarget DepthStencilTarget { get; } + public RenderTarget DepthStencilTarget { get; } - private RenderTarget[] colorTargets { get; } - public IEnumerable ColorTargets => colorTargets; + private RenderTarget[] colorTargets { get; } + public IEnumerable ColorTargets => colorTargets; - public RenderPass RenderPass { get; } + public RenderPass RenderPass { get; } - /// - /// Creates a framebuffer. - /// - /// An initialized GraphicsDevice. - /// The width of the framebuffer. - /// The height of the framebuffer. - /// The reference render pass for the framebuffer. - /// The depth stencil target. Can be null. - /// Anywhere from 0-4 color targets can be provided. - public unsafe Framebuffer( - GraphicsDevice device, - uint width, - uint height, - RenderPass renderPass, - RenderTarget depthStencilTarget, - params RenderTarget[] colorTargets - ) : base(device) - { - IntPtr[] colorTargetHandles = new IntPtr[colorTargets.Length]; - for (var i = 0; i < colorTargets.Length; i += 1) - { - colorTargetHandles[i] = colorTargets[i].Handle; - } + /// + /// Creates a framebuffer. + /// + /// An initialized GraphicsDevice. + /// The width of the framebuffer. + /// The height of the framebuffer. + /// The reference render pass for the framebuffer. + /// The depth stencil target. Can be null. + /// Anywhere from 0-4 color targets can be provided. + public unsafe Framebuffer( + GraphicsDevice device, + uint width, + uint height, + RenderPass renderPass, + RenderTarget depthStencilTarget, + params RenderTarget[] colorTargets + ) : base(device) + { + IntPtr[] colorTargetHandles = new IntPtr[colorTargets.Length]; + for (var i = 0; i < colorTargets.Length; i += 1) + { + colorTargetHandles[i] = colorTargets[i].Handle; + } - IntPtr depthStencilTargetHandle; - if (depthStencilTarget == null) - { - depthStencilTargetHandle = IntPtr.Zero; - } - else - { - depthStencilTargetHandle = depthStencilTarget.Handle; - } + IntPtr depthStencilTargetHandle; + if (depthStencilTarget == null) + { + depthStencilTargetHandle = IntPtr.Zero; + } + else + { + depthStencilTargetHandle = depthStencilTarget.Handle; + } - fixed (IntPtr* colorTargetHandlesPtr = colorTargetHandles) - { - Refresh.FramebufferCreateInfo framebufferCreateInfo = new Refresh.FramebufferCreateInfo - { - width = width, - height = height, - colorTargetCount = (uint) colorTargets.Length, - pColorTargets = (IntPtr) colorTargetHandlesPtr, - depthStencilTarget = depthStencilTargetHandle, - renderPass = renderPass.Handle - }; + fixed (IntPtr* colorTargetHandlesPtr = colorTargetHandles) + { + Refresh.FramebufferCreateInfo framebufferCreateInfo = new Refresh.FramebufferCreateInfo + { + width = width, + height = height, + colorTargetCount = (uint) colorTargets.Length, + pColorTargets = (IntPtr) colorTargetHandlesPtr, + depthStencilTarget = depthStencilTargetHandle, + renderPass = renderPass.Handle + }; - Handle = Refresh.Refresh_CreateFramebuffer(device.Handle, framebufferCreateInfo); - } + Handle = Refresh.Refresh_CreateFramebuffer(device.Handle, framebufferCreateInfo); + } - DepthStencilTarget = depthStencilTarget; + DepthStencilTarget = depthStencilTarget; - this.colorTargets = new RenderTarget[colorTargets.Length]; - for (var i = 0; i < colorTargets.Length; i++) - { - this.colorTargets[i] = colorTargets[i]; - } + this.colorTargets = new RenderTarget[colorTargets.Length]; + for (var i = 0; i < colorTargets.Length; i++) + { + this.colorTargets[i] = colorTargets[i]; + } - RenderPass = renderPass; - } - } + RenderPass = renderPass; + } + } } diff --git a/src/Graphics/Resources/GraphicsPipeline.cs b/src/Graphics/Resources/GraphicsPipeline.cs index a1c545e4..af0d67e0 100644 --- a/src/Graphics/Resources/GraphicsPipeline.cs +++ b/src/Graphics/Resources/GraphicsPipeline.cs @@ -1,132 +1,132 @@ -using System; +using System; using System.Runtime.InteropServices; using RefreshCS; namespace MoonWorks.Graphics { - /// - /// Graphics pipelines encapsulate all of the render state in a single object. - /// These pipelines are bound before draw calls are issued. - /// - public class GraphicsPipeline : GraphicsResource - { - protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyGraphicsPipeline; + /// + /// Graphics pipelines encapsulate all of the render state in a single object. + /// These pipelines are bound before draw calls are issued. + /// + public class GraphicsPipeline : GraphicsResource + { + protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyGraphicsPipeline; - public ShaderStageState VertexShaderState { get; } - public ShaderStageState FragmentShaderState { get; } - public RenderPass RenderPass { get; } + public ShaderStageState VertexShaderState { get; } + public ShaderStageState FragmentShaderState { get; } + public RenderPass RenderPass { get; } - public unsafe GraphicsPipeline( - GraphicsDevice device, - in GraphicsPipelineCreateInfo graphicsPipelineCreateInfo - ) : base(device) - { - ColorBlendState colorBlendState = graphicsPipelineCreateInfo.ColorBlendState; - DepthStencilState depthStencilState = graphicsPipelineCreateInfo.DepthStencilState; - ShaderStageState vertexShaderState = graphicsPipelineCreateInfo.VertexShaderState; - ShaderStageState fragmentShaderState = graphicsPipelineCreateInfo.FragmentShaderState; - MultisampleState multisampleState = graphicsPipelineCreateInfo.MultisampleState; - GraphicsPipelineLayoutInfo pipelineLayoutInfo = graphicsPipelineCreateInfo.PipelineLayoutInfo; - RasterizerState rasterizerState = graphicsPipelineCreateInfo.RasterizerState; - PrimitiveType primitiveType = graphicsPipelineCreateInfo.PrimitiveType; - VertexInputState vertexInputState = graphicsPipelineCreateInfo.VertexInputState; - ViewportState viewportState = graphicsPipelineCreateInfo.ViewportState; - RenderPass renderPass = graphicsPipelineCreateInfo.RenderPass; + public unsafe GraphicsPipeline( + GraphicsDevice device, + in GraphicsPipelineCreateInfo graphicsPipelineCreateInfo + ) : base(device) + { + ColorBlendState colorBlendState = graphicsPipelineCreateInfo.ColorBlendState; + DepthStencilState depthStencilState = graphicsPipelineCreateInfo.DepthStencilState; + ShaderStageState vertexShaderState = graphicsPipelineCreateInfo.VertexShaderState; + ShaderStageState fragmentShaderState = graphicsPipelineCreateInfo.FragmentShaderState; + MultisampleState multisampleState = graphicsPipelineCreateInfo.MultisampleState; + GraphicsPipelineLayoutInfo pipelineLayoutInfo = graphicsPipelineCreateInfo.PipelineLayoutInfo; + RasterizerState rasterizerState = graphicsPipelineCreateInfo.RasterizerState; + PrimitiveType primitiveType = graphicsPipelineCreateInfo.PrimitiveType; + VertexInputState vertexInputState = graphicsPipelineCreateInfo.VertexInputState; + ViewportState viewportState = graphicsPipelineCreateInfo.ViewportState; + RenderPass renderPass = graphicsPipelineCreateInfo.RenderPass; - var vertexAttributesHandle = GCHandle.Alloc( - vertexInputState.VertexAttributes, - GCHandleType.Pinned - ); - var vertexBindingsHandle = GCHandle.Alloc( - vertexInputState.VertexBindings, - GCHandleType.Pinned - ); - var viewportHandle = GCHandle.Alloc( - viewportState.Viewports, - GCHandleType.Pinned - ); - var scissorHandle = GCHandle.Alloc( - viewportState.Scissors, - GCHandleType.Pinned - ); + var vertexAttributesHandle = GCHandle.Alloc( + vertexInputState.VertexAttributes, + GCHandleType.Pinned + ); + var vertexBindingsHandle = GCHandle.Alloc( + vertexInputState.VertexBindings, + GCHandleType.Pinned + ); + var viewportHandle = GCHandle.Alloc( + viewportState.Viewports, + GCHandleType.Pinned + ); + var scissorHandle = GCHandle.Alloc( + viewportState.Scissors, + GCHandleType.Pinned + ); - var colorTargetBlendStates = stackalloc Refresh.ColorTargetBlendState[ - colorBlendState.ColorTargetBlendStates.Length - ]; + var colorTargetBlendStates = stackalloc Refresh.ColorTargetBlendState[ + colorBlendState.ColorTargetBlendStates.Length + ]; - for (var i = 0; i < colorBlendState.ColorTargetBlendStates.Length; i += 1) - { - colorTargetBlendStates[i] = colorBlendState.ColorTargetBlendStates[i].ToRefreshColorTargetBlendState(); - } + for (var i = 0; i < colorBlendState.ColorTargetBlendStates.Length; i += 1) + { + colorTargetBlendStates[i] = colorBlendState.ColorTargetBlendStates[i].ToRefreshColorTargetBlendState(); + } - Refresh.GraphicsPipelineCreateInfo refreshGraphicsPipelineCreateInfo; + Refresh.GraphicsPipelineCreateInfo refreshGraphicsPipelineCreateInfo; - refreshGraphicsPipelineCreateInfo.colorBlendState.logicOpEnable = Conversions.BoolToByte(colorBlendState.LogicOpEnable); - refreshGraphicsPipelineCreateInfo.colorBlendState.logicOp = (Refresh.LogicOp) colorBlendState.LogicOp; - refreshGraphicsPipelineCreateInfo.colorBlendState.blendStates = (IntPtr) colorTargetBlendStates; - refreshGraphicsPipelineCreateInfo.colorBlendState.blendStateCount = (uint) colorBlendState.ColorTargetBlendStates.Length; - refreshGraphicsPipelineCreateInfo.colorBlendState.blendConstants[0] = colorBlendState.BlendConstants.R; - refreshGraphicsPipelineCreateInfo.colorBlendState.blendConstants[1] = colorBlendState.BlendConstants.G; - refreshGraphicsPipelineCreateInfo.colorBlendState.blendConstants[2] = colorBlendState.BlendConstants.B; - refreshGraphicsPipelineCreateInfo.colorBlendState.blendConstants[3] = colorBlendState.BlendConstants.A; + refreshGraphicsPipelineCreateInfo.colorBlendState.logicOpEnable = Conversions.BoolToByte(colorBlendState.LogicOpEnable); + refreshGraphicsPipelineCreateInfo.colorBlendState.logicOp = (Refresh.LogicOp) colorBlendState.LogicOp; + refreshGraphicsPipelineCreateInfo.colorBlendState.blendStates = (IntPtr) colorTargetBlendStates; + refreshGraphicsPipelineCreateInfo.colorBlendState.blendStateCount = (uint) colorBlendState.ColorTargetBlendStates.Length; + refreshGraphicsPipelineCreateInfo.colorBlendState.blendConstants[0] = colorBlendState.BlendConstants.R; + refreshGraphicsPipelineCreateInfo.colorBlendState.blendConstants[1] = colorBlendState.BlendConstants.G; + refreshGraphicsPipelineCreateInfo.colorBlendState.blendConstants[2] = colorBlendState.BlendConstants.B; + refreshGraphicsPipelineCreateInfo.colorBlendState.blendConstants[3] = colorBlendState.BlendConstants.A; - refreshGraphicsPipelineCreateInfo.depthStencilState.backStencilState = depthStencilState.BackStencilState.ToRefresh(); - refreshGraphicsPipelineCreateInfo.depthStencilState.compareOp = (Refresh.CompareOp) depthStencilState.CompareOp; - refreshGraphicsPipelineCreateInfo.depthStencilState.depthBoundsTestEnable = Conversions.BoolToByte(depthStencilState.DepthBoundsTestEnable); - refreshGraphicsPipelineCreateInfo.depthStencilState.depthTestEnable = Conversions.BoolToByte(depthStencilState.DepthTestEnable); - refreshGraphicsPipelineCreateInfo.depthStencilState.depthWriteEnable = Conversions.BoolToByte(depthStencilState.DepthWriteEnable); - refreshGraphicsPipelineCreateInfo.depthStencilState.frontStencilState = depthStencilState.FrontStencilState.ToRefresh(); - refreshGraphicsPipelineCreateInfo.depthStencilState.maxDepthBounds = depthStencilState.MaxDepthBounds; - refreshGraphicsPipelineCreateInfo.depthStencilState.minDepthBounds = depthStencilState.MinDepthBounds; - refreshGraphicsPipelineCreateInfo.depthStencilState.stencilTestEnable = Conversions.BoolToByte(depthStencilState.StencilTestEnable); + refreshGraphicsPipelineCreateInfo.depthStencilState.backStencilState = depthStencilState.BackStencilState.ToRefresh(); + refreshGraphicsPipelineCreateInfo.depthStencilState.compareOp = (Refresh.CompareOp) depthStencilState.CompareOp; + refreshGraphicsPipelineCreateInfo.depthStencilState.depthBoundsTestEnable = Conversions.BoolToByte(depthStencilState.DepthBoundsTestEnable); + refreshGraphicsPipelineCreateInfo.depthStencilState.depthTestEnable = Conversions.BoolToByte(depthStencilState.DepthTestEnable); + refreshGraphicsPipelineCreateInfo.depthStencilState.depthWriteEnable = Conversions.BoolToByte(depthStencilState.DepthWriteEnable); + refreshGraphicsPipelineCreateInfo.depthStencilState.frontStencilState = depthStencilState.FrontStencilState.ToRefresh(); + refreshGraphicsPipelineCreateInfo.depthStencilState.maxDepthBounds = depthStencilState.MaxDepthBounds; + refreshGraphicsPipelineCreateInfo.depthStencilState.minDepthBounds = depthStencilState.MinDepthBounds; + refreshGraphicsPipelineCreateInfo.depthStencilState.stencilTestEnable = Conversions.BoolToByte(depthStencilState.StencilTestEnable); - refreshGraphicsPipelineCreateInfo.vertexShaderState.entryPointName = vertexShaderState.EntryPointName; - refreshGraphicsPipelineCreateInfo.vertexShaderState.shaderModule = vertexShaderState.ShaderModule.Handle; - refreshGraphicsPipelineCreateInfo.vertexShaderState.uniformBufferSize = vertexShaderState.UniformBufferSize; + refreshGraphicsPipelineCreateInfo.vertexShaderState.entryPointName = vertexShaderState.EntryPointName; + refreshGraphicsPipelineCreateInfo.vertexShaderState.shaderModule = vertexShaderState.ShaderModule.Handle; + refreshGraphicsPipelineCreateInfo.vertexShaderState.uniformBufferSize = vertexShaderState.UniformBufferSize; - refreshGraphicsPipelineCreateInfo.fragmentShaderState.entryPointName = fragmentShaderState.EntryPointName; - refreshGraphicsPipelineCreateInfo.fragmentShaderState.shaderModule = fragmentShaderState.ShaderModule.Handle; - refreshGraphicsPipelineCreateInfo.fragmentShaderState.uniformBufferSize = fragmentShaderState.UniformBufferSize; + refreshGraphicsPipelineCreateInfo.fragmentShaderState.entryPointName = fragmentShaderState.EntryPointName; + refreshGraphicsPipelineCreateInfo.fragmentShaderState.shaderModule = fragmentShaderState.ShaderModule.Handle; + refreshGraphicsPipelineCreateInfo.fragmentShaderState.uniformBufferSize = fragmentShaderState.UniformBufferSize; - refreshGraphicsPipelineCreateInfo.multisampleState.multisampleCount = (Refresh.SampleCount)multisampleState.MultisampleCount; - refreshGraphicsPipelineCreateInfo.multisampleState.sampleMask = multisampleState.SampleMask; + refreshGraphicsPipelineCreateInfo.multisampleState.multisampleCount = (Refresh.SampleCount) multisampleState.MultisampleCount; + refreshGraphicsPipelineCreateInfo.multisampleState.sampleMask = multisampleState.SampleMask; - refreshGraphicsPipelineCreateInfo.pipelineLayoutCreateInfo.vertexSamplerBindingCount = pipelineLayoutInfo.VertexSamplerBindingCount; - refreshGraphicsPipelineCreateInfo.pipelineLayoutCreateInfo.fragmentSamplerBindingCount = pipelineLayoutInfo.FragmentSamplerBindingCount; + refreshGraphicsPipelineCreateInfo.pipelineLayoutCreateInfo.vertexSamplerBindingCount = pipelineLayoutInfo.VertexSamplerBindingCount; + refreshGraphicsPipelineCreateInfo.pipelineLayoutCreateInfo.fragmentSamplerBindingCount = pipelineLayoutInfo.FragmentSamplerBindingCount; - refreshGraphicsPipelineCreateInfo.rasterizerState.cullMode = (Refresh.CullMode)rasterizerState.CullMode; - refreshGraphicsPipelineCreateInfo.rasterizerState.depthBiasClamp = rasterizerState.DepthBiasClamp; - refreshGraphicsPipelineCreateInfo.rasterizerState.depthBiasConstantFactor = rasterizerState.DepthBiasConstantFactor; - refreshGraphicsPipelineCreateInfo.rasterizerState.depthBiasEnable = Conversions.BoolToByte(rasterizerState.DepthBiasEnable); - refreshGraphicsPipelineCreateInfo.rasterizerState.depthBiasSlopeFactor = rasterizerState.DepthBiasSlopeFactor; - refreshGraphicsPipelineCreateInfo.rasterizerState.depthClampEnable = Conversions.BoolToByte(rasterizerState.DepthClampEnable); - refreshGraphicsPipelineCreateInfo.rasterizerState.fillMode = (Refresh.FillMode)rasterizerState.FillMode; - refreshGraphicsPipelineCreateInfo.rasterizerState.frontFace = (Refresh.FrontFace)rasterizerState.FrontFace; - refreshGraphicsPipelineCreateInfo.rasterizerState.lineWidth = rasterizerState.LineWidth; + refreshGraphicsPipelineCreateInfo.rasterizerState.cullMode = (Refresh.CullMode) rasterizerState.CullMode; + refreshGraphicsPipelineCreateInfo.rasterizerState.depthBiasClamp = rasterizerState.DepthBiasClamp; + refreshGraphicsPipelineCreateInfo.rasterizerState.depthBiasConstantFactor = rasterizerState.DepthBiasConstantFactor; + refreshGraphicsPipelineCreateInfo.rasterizerState.depthBiasEnable = Conversions.BoolToByte(rasterizerState.DepthBiasEnable); + refreshGraphicsPipelineCreateInfo.rasterizerState.depthBiasSlopeFactor = rasterizerState.DepthBiasSlopeFactor; + refreshGraphicsPipelineCreateInfo.rasterizerState.depthClampEnable = Conversions.BoolToByte(rasterizerState.DepthClampEnable); + refreshGraphicsPipelineCreateInfo.rasterizerState.fillMode = (Refresh.FillMode) rasterizerState.FillMode; + refreshGraphicsPipelineCreateInfo.rasterizerState.frontFace = (Refresh.FrontFace) rasterizerState.FrontFace; + refreshGraphicsPipelineCreateInfo.rasterizerState.lineWidth = rasterizerState.LineWidth; - refreshGraphicsPipelineCreateInfo.vertexInputState.vertexAttributes = vertexAttributesHandle.AddrOfPinnedObject(); - refreshGraphicsPipelineCreateInfo.vertexInputState.vertexAttributeCount = (uint) vertexInputState.VertexAttributes.Length; - refreshGraphicsPipelineCreateInfo.vertexInputState.vertexBindings = vertexBindingsHandle.AddrOfPinnedObject(); - refreshGraphicsPipelineCreateInfo.vertexInputState.vertexBindingCount = (uint) vertexInputState.VertexBindings.Length; + refreshGraphicsPipelineCreateInfo.vertexInputState.vertexAttributes = vertexAttributesHandle.AddrOfPinnedObject(); + refreshGraphicsPipelineCreateInfo.vertexInputState.vertexAttributeCount = (uint) vertexInputState.VertexAttributes.Length; + refreshGraphicsPipelineCreateInfo.vertexInputState.vertexBindings = vertexBindingsHandle.AddrOfPinnedObject(); + refreshGraphicsPipelineCreateInfo.vertexInputState.vertexBindingCount = (uint) vertexInputState.VertexBindings.Length; - refreshGraphicsPipelineCreateInfo.viewportState.viewports = viewportHandle.AddrOfPinnedObject(); - refreshGraphicsPipelineCreateInfo.viewportState.viewportCount = (uint) viewportState.Viewports.Length; - refreshGraphicsPipelineCreateInfo.viewportState.scissors = scissorHandle.AddrOfPinnedObject(); - refreshGraphicsPipelineCreateInfo.viewportState.scissorCount = (uint) viewportState.Scissors.Length; + refreshGraphicsPipelineCreateInfo.viewportState.viewports = viewportHandle.AddrOfPinnedObject(); + refreshGraphicsPipelineCreateInfo.viewportState.viewportCount = (uint) viewportState.Viewports.Length; + refreshGraphicsPipelineCreateInfo.viewportState.scissors = scissorHandle.AddrOfPinnedObject(); + refreshGraphicsPipelineCreateInfo.viewportState.scissorCount = (uint) viewportState.Scissors.Length; - refreshGraphicsPipelineCreateInfo.primitiveType = (Refresh.PrimitiveType) primitiveType; - refreshGraphicsPipelineCreateInfo.renderPass = renderPass.Handle; + refreshGraphicsPipelineCreateInfo.primitiveType = (Refresh.PrimitiveType) primitiveType; + refreshGraphicsPipelineCreateInfo.renderPass = renderPass.Handle; - Handle = Refresh.Refresh_CreateGraphicsPipeline(device.Handle, refreshGraphicsPipelineCreateInfo); + Handle = Refresh.Refresh_CreateGraphicsPipeline(device.Handle, refreshGraphicsPipelineCreateInfo); - vertexAttributesHandle.Free(); - vertexBindingsHandle.Free(); - viewportHandle.Free(); - scissorHandle.Free(); + vertexAttributesHandle.Free(); + vertexBindingsHandle.Free(); + viewportHandle.Free(); + scissorHandle.Free(); - VertexShaderState = vertexShaderState; - FragmentShaderState = fragmentShaderState; - RenderPass = renderPass; - } - } + VertexShaderState = vertexShaderState; + FragmentShaderState = fragmentShaderState; + RenderPass = renderPass; + } + } } diff --git a/src/Graphics/Resources/RenderPass.cs b/src/Graphics/Resources/RenderPass.cs index 1dadc481..37cebef3 100644 --- a/src/Graphics/Resources/RenderPass.cs +++ b/src/Graphics/Resources/RenderPass.cs @@ -3,57 +3,57 @@ using RefreshCS; namespace MoonWorks.Graphics { - /// - /// A render pass describes the kind of render targets that will be used in rendering. - /// - public class RenderPass : GraphicsResource - { - protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyRenderPass; + /// + /// A render pass describes the kind of render targets that will be used in rendering. + /// + public class RenderPass : GraphicsResource + { + protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyRenderPass; - /// - /// Creates a render pass using color target descriptions. - /// - /// An initialized GraphicsDevice. - /// Up to 4 color target descriptions may be provided. - public unsafe RenderPass( - GraphicsDevice device, - params ColorTargetDescription[] colorTargetDescriptions - ) : base(device) - { - fixed (ColorTargetDescription* ptr = colorTargetDescriptions) - { - Refresh.RenderPassCreateInfo renderPassCreateInfo; - renderPassCreateInfo.colorTargetCount = (uint) colorTargetDescriptions.Length; - renderPassCreateInfo.colorTargetDescriptions = (IntPtr) ptr; - renderPassCreateInfo.depthStencilTargetDescription = IntPtr.Zero; + /// + /// Creates a render pass using color target descriptions. + /// + /// An initialized GraphicsDevice. + /// Up to 4 color target descriptions may be provided. + public unsafe RenderPass( + GraphicsDevice device, + params ColorTargetDescription[] colorTargetDescriptions + ) : base(device) + { + fixed (ColorTargetDescription* ptr = colorTargetDescriptions) + { + Refresh.RenderPassCreateInfo renderPassCreateInfo; + renderPassCreateInfo.colorTargetCount = (uint) colorTargetDescriptions.Length; + renderPassCreateInfo.colorTargetDescriptions = (IntPtr) ptr; + renderPassCreateInfo.depthStencilTargetDescription = IntPtr.Zero; - Handle = Refresh.Refresh_CreateRenderPass(device.Handle, renderPassCreateInfo); - } - } + Handle = Refresh.Refresh_CreateRenderPass(device.Handle, renderPassCreateInfo); + } + } - /// - /// Creates a render pass using a depth/stencil target description and optional color target descriptions. - /// - /// An initialized GraphicsDevice. - /// A depth/stencil target description. - /// Up to 4 color target descriptions may be provided. - public unsafe RenderPass( - GraphicsDevice device, - in DepthStencilTargetDescription depthStencilTargetDescription, - params ColorTargetDescription[] colorTargetDescriptions - ) : base(device) - { + /// + /// Creates a render pass using a depth/stencil target description and optional color target descriptions. + /// + /// An initialized GraphicsDevice. + /// A depth/stencil target description. + /// Up to 4 color target descriptions may be provided. + public unsafe RenderPass( + GraphicsDevice device, + in DepthStencilTargetDescription depthStencilTargetDescription, + params ColorTargetDescription[] colorTargetDescriptions + ) : base(device) + { - fixed (DepthStencilTargetDescription* depthStencilPtr = &depthStencilTargetDescription) - fixed (ColorTargetDescription* colorPtr = colorTargetDescriptions) - { - Refresh.RenderPassCreateInfo renderPassCreateInfo; - renderPassCreateInfo.colorTargetCount = (uint)colorTargetDescriptions.Length; - renderPassCreateInfo.colorTargetDescriptions = (IntPtr)colorPtr; - renderPassCreateInfo.depthStencilTargetDescription = (IntPtr) depthStencilPtr; + fixed (DepthStencilTargetDescription* depthStencilPtr = &depthStencilTargetDescription) + fixed (ColorTargetDescription* colorPtr = colorTargetDescriptions) + { + Refresh.RenderPassCreateInfo renderPassCreateInfo; + renderPassCreateInfo.colorTargetCount = (uint) colorTargetDescriptions.Length; + renderPassCreateInfo.colorTargetDescriptions = (IntPtr) colorPtr; + renderPassCreateInfo.depthStencilTargetDescription = (IntPtr) depthStencilPtr; - Handle = Refresh.Refresh_CreateRenderPass(device.Handle, renderPassCreateInfo); - } - } - } + Handle = Refresh.Refresh_CreateRenderPass(device.Handle, renderPassCreateInfo); + } + } + } } diff --git a/src/Graphics/Resources/RenderTarget.cs b/src/Graphics/Resources/RenderTarget.cs index fc20f45f..ca84c1ad 100644 --- a/src/Graphics/Resources/RenderTarget.cs +++ b/src/Graphics/Resources/RenderTarget.cs @@ -3,87 +3,89 @@ using RefreshCS; namespace MoonWorks.Graphics { - /// - /// A render target is a structure that wraps a texture so that it can be rendered to. - /// - public class RenderTarget : GraphicsResource - { - public TextureSlice TextureSlice { get; } - public TextureFormat Format => TextureSlice.Texture.Format; + /// + /// A render target is a structure that wraps a texture so that it can be rendered to. + /// + public class RenderTarget : GraphicsResource + { + public TextureSlice TextureSlice { get; } + public TextureFormat Format => TextureSlice.Texture.Format; - protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyRenderTarget; + protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyRenderTarget; - /// - /// Creates a render target backed by a texture. - /// - /// An initialized GraphicsDevice. - /// The width of the render target. - /// The height of the render target. - /// The format of the render target. - /// Whether the render target can be used by a sampler. - /// The multisample count of the render target. - /// The mip level of the render target. - /// - public static RenderTarget CreateBackedRenderTarget( - GraphicsDevice device, - uint width, - uint height, - TextureFormat format, - bool canBeSampled, - SampleCount sampleCount = SampleCount.One, - uint levelCount = 1 - ) { - TextureUsageFlags flags = 0; + /// + /// Creates a render target backed by a texture. + /// + /// An initialized GraphicsDevice. + /// The width of the render target. + /// The height of the render target. + /// The format of the render target. + /// Whether the render target can be used by a sampler. + /// The multisample count of the render target. + /// The mip level of the render target. + /// + public static RenderTarget CreateBackedRenderTarget( + GraphicsDevice device, + uint width, + uint height, + TextureFormat format, + bool canBeSampled, + SampleCount sampleCount = SampleCount.One, + uint levelCount = 1 + ) + { + TextureUsageFlags flags = 0; - if ( - format == TextureFormat.D16 || - format == TextureFormat.D32 || - format == TextureFormat.D16S8 || - format == TextureFormat.D32S8 - ) { - flags |= TextureUsageFlags.DepthStencilTarget; - } - else - { - flags |= TextureUsageFlags.ColorTarget; - } + if ( + format == TextureFormat.D16 || + format == TextureFormat.D32 || + format == TextureFormat.D16S8 || + format == TextureFormat.D32S8 + ) + { + flags |= TextureUsageFlags.DepthStencilTarget; + } + else + { + flags |= TextureUsageFlags.ColorTarget; + } - if (canBeSampled) - { - flags |= TextureUsageFlags.Sampler; - } + if (canBeSampled) + { + flags |= TextureUsageFlags.Sampler; + } - var texture = Texture.CreateTexture2D( - device, - width, - height, - format, - flags, - sampleCount, - levelCount - ); + var texture = Texture.CreateTexture2D( + device, + width, + height, + format, + flags, + sampleCount, + levelCount + ); - return new RenderTarget(device, new TextureSlice(texture), sampleCount); - } + return new RenderTarget(device, new TextureSlice(texture), sampleCount); + } - /// - /// Creates a render target using a texture slice and an optional sample count. - /// - /// An initialized GraphicsDevice. - /// The texture slice that will be rendered to. - /// The desired multisample count of the render target. - public RenderTarget( - GraphicsDevice device, - in TextureSlice textureSlice, - SampleCount sampleCount = SampleCount.One - ) : base(device) - { - Handle = Refresh.Refresh_CreateRenderTarget( - device.Handle, - textureSlice.ToRefreshTextureSlice(), - (Refresh.SampleCount) sampleCount - ); - TextureSlice = textureSlice; - } - } + /// + /// Creates a render target using a texture slice and an optional sample count. + /// + /// An initialized GraphicsDevice. + /// The texture slice that will be rendered to. + /// The desired multisample count of the render target. + public RenderTarget( + GraphicsDevice device, + in TextureSlice textureSlice, + SampleCount sampleCount = SampleCount.One + ) : base(device) + { + Handle = Refresh.Refresh_CreateRenderTarget( + device.Handle, + textureSlice.ToRefreshTextureSlice(), + (Refresh.SampleCount) sampleCount + ); + TextureSlice = textureSlice; + } + } } diff --git a/src/Graphics/Resources/Sampler.cs b/src/Graphics/Resources/Sampler.cs index ffa4d60e..9aa805b4 100644 --- a/src/Graphics/Resources/Sampler.cs +++ b/src/Graphics/Resources/Sampler.cs @@ -1,24 +1,24 @@ -using System; +using System; using RefreshCS; namespace MoonWorks.Graphics { - /// - /// A sampler specifies how a texture will be sampled in a shader. - /// - public class Sampler : GraphicsResource - { - protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroySampler; + /// + /// A sampler specifies how a texture will be sampled in a shader. + /// + public class Sampler : GraphicsResource + { + protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroySampler; - public Sampler( - GraphicsDevice device, - in SamplerCreateInfo samplerCreateInfo - ) : base(device) - { - Handle = Refresh.Refresh_CreateSampler( - device.Handle, - samplerCreateInfo.ToRefreshSamplerStateCreateInfo() - ); - } - } + public Sampler( + GraphicsDevice device, + in SamplerCreateInfo samplerCreateInfo + ) : base(device) + { + Handle = Refresh.Refresh_CreateSampler( + device.Handle, + samplerCreateInfo.ToRefreshSamplerStateCreateInfo() + ); + } + } } diff --git a/src/Graphics/Resources/ShaderModule.cs b/src/Graphics/Resources/ShaderModule.cs index 59fd171a..8699634f 100644 --- a/src/Graphics/Resources/ShaderModule.cs +++ b/src/Graphics/Resources/ShaderModule.cs @@ -3,25 +3,25 @@ using System; namespace MoonWorks.Graphics { - /// - /// Shader modules expect input in SPIR-V bytecode format. - /// - public class ShaderModule : GraphicsResource - { - protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyShaderModule; + /// + /// Shader modules expect input in SPIR-V bytecode format. + /// + public class ShaderModule : GraphicsResource + { + protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyShaderModule; - public unsafe ShaderModule(GraphicsDevice device, string filePath) : base(device) - { - var bytecode = Bytecode.ReadBytecodeAsUInt32(filePath); + public unsafe ShaderModule(GraphicsDevice device, string filePath) : base(device) + { + var bytecode = Bytecode.ReadBytecodeAsUInt32(filePath); - fixed (uint* ptr = bytecode) - { - Refresh.ShaderModuleCreateInfo shaderModuleCreateInfo; - shaderModuleCreateInfo.codeSize = (UIntPtr) (bytecode.Length * sizeof(uint)); - shaderModuleCreateInfo.byteCode = (IntPtr) ptr; + fixed (uint* ptr = bytecode) + { + Refresh.ShaderModuleCreateInfo shaderModuleCreateInfo; + shaderModuleCreateInfo.codeSize = (UIntPtr) (bytecode.Length * sizeof(uint)); + shaderModuleCreateInfo.byteCode = (IntPtr) ptr; - Handle = Refresh.Refresh_CreateShaderModule(device.Handle, shaderModuleCreateInfo); - } - } - } + Handle = Refresh.Refresh_CreateShaderModule(device.Handle, shaderModuleCreateInfo); + } + } + } } diff --git a/src/Graphics/Resources/Texture.cs b/src/Graphics/Resources/Texture.cs index d537e43a..fcd41144 100644 --- a/src/Graphics/Resources/Texture.cs +++ b/src/Graphics/Resources/Texture.cs @@ -3,193 +3,196 @@ using RefreshCS; namespace MoonWorks.Graphics { - /// - /// A container for pixel data. - /// - public class Texture : GraphicsResource - { - public uint Width { get; } - public uint Height { get; } - public uint Depth { get; } - public TextureFormat Format { get; } - public bool IsCube { get; } - public uint LevelCount { get; } - public SampleCount SampleCount { get; } - public TextureUsageFlags UsageFlags { get; } + /// + /// A container for pixel data. + /// + public class Texture : GraphicsResource + { + public uint Width { get; } + public uint Height { get; } + public uint Depth { get; } + public TextureFormat Format { get; } + public bool IsCube { get; } + public uint LevelCount { get; } + public SampleCount SampleCount { get; } + public TextureUsageFlags UsageFlags { get; } - protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyTexture; + protected override Action QueueDestroyFunction => Refresh.Refresh_QueueDestroyTexture; - /// - /// Loads a PNG from a file path. - /// NOTE: You can queue as many of these as you want on to a command buffer but it MUST be submitted! - /// - /// - /// - /// - /// - public static Texture LoadPNG(GraphicsDevice device, CommandBuffer commandBuffer, string filePath) - { - var pixels = Refresh.Refresh_Image_Load( - filePath, - out var width, - out var height, - out var channels - ); + /// + /// Loads a PNG from a file path. + /// NOTE: You can queue as many of these as you want on to a command buffer but it MUST be submitted! + /// + /// + /// + /// + /// + public static Texture LoadPNG(GraphicsDevice device, CommandBuffer commandBuffer, string filePath) + { + var pixels = Refresh.Refresh_Image_Load( + filePath, + out var width, + out var height, + out var channels + ); - var byteCount = (uint)(width * height * channels); + var byteCount = (uint) (width * height * channels); - TextureCreateInfo textureCreateInfo; - textureCreateInfo.Width = (uint)width; - textureCreateInfo.Height = (uint)height; - textureCreateInfo.Depth = 1; - textureCreateInfo.Format = TextureFormat.R8G8B8A8; - textureCreateInfo.IsCube = false; - textureCreateInfo.LevelCount = 1; - textureCreateInfo.SampleCount = SampleCount.One; - textureCreateInfo.UsageFlags = TextureUsageFlags.Sampler; + TextureCreateInfo textureCreateInfo; + textureCreateInfo.Width = (uint) width; + textureCreateInfo.Height = (uint) height; + textureCreateInfo.Depth = 1; + textureCreateInfo.Format = TextureFormat.R8G8B8A8; + textureCreateInfo.IsCube = false; + textureCreateInfo.LevelCount = 1; + textureCreateInfo.SampleCount = SampleCount.One; + textureCreateInfo.UsageFlags = TextureUsageFlags.Sampler; - var texture = new Texture(device, textureCreateInfo); - commandBuffer.SetTextureData(texture, pixels, byteCount); + var texture = new Texture(device, textureCreateInfo); + commandBuffer.SetTextureData(texture, pixels, byteCount); - Refresh.Refresh_Image_Free(pixels); + Refresh.Refresh_Image_Free(pixels); - return texture; - } + return texture; + } - public unsafe static void SavePNG(string path, int width, int height, byte[] pixels) - { - fixed (byte* ptr = &pixels[0]) - { - Refresh.Refresh_Image_SavePNG(path, width, height, (IntPtr) ptr); - } - } + public unsafe static void SavePNG(string path, int width, int height, byte[] pixels) + { + fixed (byte* ptr = &pixels[0]) + { + Refresh.Refresh_Image_SavePNG(path, width, height, (IntPtr) ptr); + } + } - /// - /// Creates a 2D texture. - /// - /// An initialized GraphicsDevice. - /// The width of the texture. - /// The height of the texture. - /// The format of the texture. - /// Specifies how the texture will be used. - /// Specifies the multisample count. - /// Specifies the number of mip levels. - public static Texture CreateTexture2D( - GraphicsDevice device, - uint width, - uint height, - TextureFormat format, - TextureUsageFlags usageFlags, - SampleCount sampleCount = SampleCount.One, - uint levelCount = 1 - ) { - var textureCreateInfo = new TextureCreateInfo - { - Width = width, - Height = height, - Depth = 1, - IsCube = false, - SampleCount = sampleCount, - LevelCount = levelCount, - Format = format, - UsageFlags = usageFlags - }; + /// + /// Creates a 2D texture. + /// + /// An initialized GraphicsDevice. + /// The width of the texture. + /// The height of the texture. + /// The format of the texture. + /// Specifies how the texture will be used. + /// Specifies the multisample count. + /// Specifies the number of mip levels. + public static Texture CreateTexture2D( + GraphicsDevice device, + uint width, + uint height, + TextureFormat format, + TextureUsageFlags usageFlags, + SampleCount sampleCount = SampleCount.One, + uint levelCount = 1 + ) + { + var textureCreateInfo = new TextureCreateInfo + { + Width = width, + Height = height, + Depth = 1, + IsCube = false, + SampleCount = sampleCount, + LevelCount = levelCount, + Format = format, + UsageFlags = usageFlags + }; - return new Texture(device, textureCreateInfo); - } + return new Texture(device, textureCreateInfo); + } - /// - /// Creates a 3D texture. - /// - /// An initialized GraphicsDevice. - /// The width of the texture. - /// The height of the texture. - /// The depth of the texture. - /// The format of the texture. - /// Specifies how the texture will be used. - /// Specifies the multisample count. - /// Specifies the number of mip levels. - public static Texture CreateTexture3D( - GraphicsDevice device, - uint width, - uint height, - uint depth, - TextureFormat format, - TextureUsageFlags usageFlags, - SampleCount sampleCount = SampleCount.One, - uint levelCount = 1 - ) { - var textureCreateInfo = new TextureCreateInfo - { - Width = width, - Height = height, - Depth = depth, - IsCube = false, - SampleCount = sampleCount, - LevelCount = levelCount, - Format = format, - UsageFlags = usageFlags - }; + /// + /// Creates a 3D texture. + /// + /// An initialized GraphicsDevice. + /// The width of the texture. + /// The height of the texture. + /// The depth of the texture. + /// The format of the texture. + /// Specifies how the texture will be used. + /// Specifies the multisample count. + /// Specifies the number of mip levels. + public static Texture CreateTexture3D( + GraphicsDevice device, + uint width, + uint height, + uint depth, + TextureFormat format, + TextureUsageFlags usageFlags, + SampleCount sampleCount = SampleCount.One, + uint levelCount = 1 + ) + { + var textureCreateInfo = new TextureCreateInfo + { + Width = width, + Height = height, + Depth = depth, + IsCube = false, + SampleCount = sampleCount, + LevelCount = levelCount, + Format = format, + UsageFlags = usageFlags + }; - return new Texture(device, textureCreateInfo); - } + return new Texture(device, textureCreateInfo); + } - /// - /// Creates a cube texture. - /// - /// An initialized GraphicsDevice. - /// The length of one side of the cube. - /// The format of the texture. - /// Specifies how the texture will be used. - /// Specifies the multisample count. - /// Specifies the number of mip levels. - public static Texture CreateTextureCube( - GraphicsDevice device, - uint size, - TextureFormat format, - TextureUsageFlags usageFlags, - SampleCount sampleCount = SampleCount.One, - uint levelCount = 1 - ) { - var textureCreateInfo = new TextureCreateInfo - { - Width = size, - Height = size, - Depth = 1, - IsCube = true, - SampleCount = sampleCount, - LevelCount = levelCount, - Format = format, - UsageFlags = usageFlags - }; + /// + /// Creates a cube texture. + /// + /// An initialized GraphicsDevice. + /// The length of one side of the cube. + /// The format of the texture. + /// Specifies how the texture will be used. + /// Specifies the multisample count. + /// Specifies the number of mip levels. + public static Texture CreateTextureCube( + GraphicsDevice device, + uint size, + TextureFormat format, + TextureUsageFlags usageFlags, + SampleCount sampleCount = SampleCount.One, + uint levelCount = 1 + ) + { + var textureCreateInfo = new TextureCreateInfo + { + Width = size, + Height = size, + Depth = 1, + IsCube = true, + SampleCount = sampleCount, + LevelCount = levelCount, + Format = format, + UsageFlags = usageFlags + }; - return new Texture(device, textureCreateInfo); - } + return new Texture(device, textureCreateInfo); + } - /// - /// Creates a new texture using a TextureCreateInfo struct. - /// - /// An initialized GraphicsDevice. - /// The parameters to use when creating the texture. - public Texture( - GraphicsDevice device, - in TextureCreateInfo textureCreateInfo - ) : base(device) - { - Handle = Refresh.Refresh_CreateTexture( - device.Handle, - textureCreateInfo.ToRefreshTextureCreateInfo() - ); + /// + /// Creates a new texture using a TextureCreateInfo struct. + /// + /// An initialized GraphicsDevice. + /// The parameters to use when creating the texture. + public Texture( + GraphicsDevice device, + in TextureCreateInfo textureCreateInfo + ) : base(device) + { + Handle = Refresh.Refresh_CreateTexture( + device.Handle, + textureCreateInfo.ToRefreshTextureCreateInfo() + ); - Format = textureCreateInfo.Format; - Width = textureCreateInfo.Width; - Height = textureCreateInfo.Height; - Depth = textureCreateInfo.Depth; - IsCube = textureCreateInfo.IsCube; - SampleCount = textureCreateInfo.SampleCount; - LevelCount = textureCreateInfo.LevelCount; - SampleCount = textureCreateInfo.SampleCount; - UsageFlags = textureCreateInfo.UsageFlags; - } - } + Format = textureCreateInfo.Format; + Width = textureCreateInfo.Width; + Height = textureCreateInfo.Height; + Depth = textureCreateInfo.Depth; + IsCube = textureCreateInfo.IsCube; + SampleCount = textureCreateInfo.SampleCount; + LevelCount = textureCreateInfo.LevelCount; + SampleCount = textureCreateInfo.SampleCount; + UsageFlags = textureCreateInfo.UsageFlags; + } + } } diff --git a/src/Graphics/State/ColorBlendState.cs b/src/Graphics/State/ColorBlendState.cs index e9e81eca..ca01e17d 100644 --- a/src/Graphics/State/ColorBlendState.cs +++ b/src/Graphics/State/ColorBlendState.cs @@ -1,14 +1,14 @@ -namespace MoonWorks.Graphics +namespace MoonWorks.Graphics { - /// - /// Describes how the graphics pipeline will blend colors. - /// You must provide one ColorTargetBlendState per color target in the pipeline. - /// - public unsafe struct ColorBlendState - { - public bool LogicOpEnable; - public LogicOp LogicOp; - public BlendConstants BlendConstants; - public ColorTargetBlendState[] ColorTargetBlendStates; - } + /// + /// Describes how the graphics pipeline will blend colors. + /// You must provide one ColorTargetBlendState per color target in the pipeline. + /// + public unsafe struct ColorBlendState + { + public bool LogicOpEnable; + public LogicOp LogicOp; + public BlendConstants BlendConstants; + public ColorTargetBlendState[] ColorTargetBlendStates; + } } diff --git a/src/Graphics/State/ColorTargetBlendState.cs b/src/Graphics/State/ColorTargetBlendState.cs index d51e442c..c12e7064 100644 --- a/src/Graphics/State/ColorTargetBlendState.cs +++ b/src/Graphics/State/ColorTargetBlendState.cs @@ -2,120 +2,120 @@ namespace MoonWorks.Graphics { - public struct ColorTargetBlendState - { - /// - /// If disabled, no blending will occur. - /// - public bool BlendEnable; + public struct ColorTargetBlendState + { + /// + /// If disabled, no blending will occur. + /// + public bool BlendEnable; - /// - /// Selects which blend operation to use with alpha values. - /// - public BlendOp AlphaBlendOp; - /// - /// Selects which blend operation to use with color values. - /// - public BlendOp ColorBlendOp; + /// + /// Selects which blend operation to use with alpha values. + /// + public BlendOp AlphaBlendOp; + /// + /// Selects which blend operation to use with color values. + /// + public BlendOp ColorBlendOp; - /// - /// Specifies which of the RGBA components are enabled for writing. - /// - public ColorComponentFlags ColorWriteMask; + /// + /// Specifies which of the RGBA components are enabled for writing. + /// + public ColorComponentFlags ColorWriteMask; - /// - /// Selects which blend factor is used to determine the alpha destination factor. - /// - public BlendFactor DestinationAlphaBlendFactor; + /// + /// Selects which blend factor is used to determine the alpha destination factor. + /// + public BlendFactor DestinationAlphaBlendFactor; - /// - /// Selects which blend factor is used to determine the color destination factor. - /// - public BlendFactor DestinationColorBlendFactor; + /// + /// Selects which blend factor is used to determine the color destination factor. + /// + public BlendFactor DestinationColorBlendFactor; - /// - /// Selects which blend factor is used to determine the alpha source factor. - /// - public BlendFactor SourceAlphaBlendFactor; + /// + /// Selects which blend factor is used to determine the alpha source factor. + /// + public BlendFactor SourceAlphaBlendFactor; - /// - /// Selects which blend factor is used to determine the color source factor. - /// - public BlendFactor SourceColorBlendFactor; + /// + /// Selects which blend factor is used to determine the color source factor. + /// + public BlendFactor SourceColorBlendFactor; - public static readonly ColorTargetBlendState Additive = new ColorTargetBlendState - { - BlendEnable = true, - AlphaBlendOp = BlendOp.Add, - ColorBlendOp = BlendOp.Add, - ColorWriteMask = ColorComponentFlags.RGBA, - SourceColorBlendFactor = BlendFactor.SourceAlpha, - SourceAlphaBlendFactor = BlendFactor.SourceAlpha, - DestinationColorBlendFactor = BlendFactor.One, - DestinationAlphaBlendFactor = BlendFactor.One - }; + public static readonly ColorTargetBlendState Additive = new ColorTargetBlendState + { + BlendEnable = true, + AlphaBlendOp = BlendOp.Add, + ColorBlendOp = BlendOp.Add, + ColorWriteMask = ColorComponentFlags.RGBA, + SourceColorBlendFactor = BlendFactor.SourceAlpha, + SourceAlphaBlendFactor = BlendFactor.SourceAlpha, + DestinationColorBlendFactor = BlendFactor.One, + DestinationAlphaBlendFactor = BlendFactor.One + }; - public static readonly ColorTargetBlendState AlphaBlend = new ColorTargetBlendState - { - BlendEnable = true, - AlphaBlendOp = BlendOp.Add, - ColorBlendOp = BlendOp.Add, - ColorWriteMask = ColorComponentFlags.RGBA, - SourceColorBlendFactor = BlendFactor.One, - SourceAlphaBlendFactor = BlendFactor.One, - DestinationColorBlendFactor = BlendFactor.OneMinusSourceAlpha, - DestinationAlphaBlendFactor = BlendFactor.OneMinusSourceAlpha - }; + public static readonly ColorTargetBlendState AlphaBlend = new ColorTargetBlendState + { + BlendEnable = true, + AlphaBlendOp = BlendOp.Add, + ColorBlendOp = BlendOp.Add, + ColorWriteMask = ColorComponentFlags.RGBA, + SourceColorBlendFactor = BlendFactor.One, + SourceAlphaBlendFactor = BlendFactor.One, + DestinationColorBlendFactor = BlendFactor.OneMinusSourceAlpha, + DestinationAlphaBlendFactor = BlendFactor.OneMinusSourceAlpha + }; - public static readonly ColorTargetBlendState NonPremultiplied = new ColorTargetBlendState - { - BlendEnable = true, - AlphaBlendOp = BlendOp.Add, - ColorBlendOp = BlendOp.Add, - ColorWriteMask = ColorComponentFlags.RGBA, - SourceColorBlendFactor = BlendFactor.SourceAlpha, - SourceAlphaBlendFactor = BlendFactor.SourceAlpha, - DestinationColorBlendFactor = BlendFactor.OneMinusSourceAlpha, - DestinationAlphaBlendFactor = BlendFactor.OneMinusSourceAlpha - }; + public static readonly ColorTargetBlendState NonPremultiplied = new ColorTargetBlendState + { + BlendEnable = true, + AlphaBlendOp = BlendOp.Add, + ColorBlendOp = BlendOp.Add, + ColorWriteMask = ColorComponentFlags.RGBA, + SourceColorBlendFactor = BlendFactor.SourceAlpha, + SourceAlphaBlendFactor = BlendFactor.SourceAlpha, + DestinationColorBlendFactor = BlendFactor.OneMinusSourceAlpha, + DestinationAlphaBlendFactor = BlendFactor.OneMinusSourceAlpha + }; - public static readonly ColorTargetBlendState Opaque = new ColorTargetBlendState - { - BlendEnable = true, - AlphaBlendOp = BlendOp.Add, - ColorBlendOp = BlendOp.Add, - ColorWriteMask = ColorComponentFlags.RGBA, - SourceColorBlendFactor = BlendFactor.One, - SourceAlphaBlendFactor = BlendFactor.One, - DestinationColorBlendFactor = BlendFactor.Zero, - DestinationAlphaBlendFactor = BlendFactor.Zero - }; + public static readonly ColorTargetBlendState Opaque = new ColorTargetBlendState + { + BlendEnable = true, + AlphaBlendOp = BlendOp.Add, + ColorBlendOp = BlendOp.Add, + ColorWriteMask = ColorComponentFlags.RGBA, + SourceColorBlendFactor = BlendFactor.One, + SourceAlphaBlendFactor = BlendFactor.One, + DestinationColorBlendFactor = BlendFactor.Zero, + DestinationAlphaBlendFactor = BlendFactor.Zero + }; - public static readonly ColorTargetBlendState None = new ColorTargetBlendState - { - BlendEnable = false, - ColorWriteMask = ColorComponentFlags.RGBA - }; + public static readonly ColorTargetBlendState None = new ColorTargetBlendState + { + BlendEnable = false, + ColorWriteMask = ColorComponentFlags.RGBA + }; - public static readonly ColorTargetBlendState Disable = new ColorTargetBlendState - { - BlendEnable = false, - ColorWriteMask = ColorComponentFlags.None - }; + public static readonly ColorTargetBlendState Disable = new ColorTargetBlendState + { + BlendEnable = false, + ColorWriteMask = ColorComponentFlags.None + }; - public Refresh.ColorTargetBlendState ToRefreshColorTargetBlendState() - { - return new Refresh.ColorTargetBlendState - { - blendEnable = Conversions.BoolToByte(BlendEnable), - alphaBlendOp = (Refresh.BlendOp)AlphaBlendOp, - colorBlendOp = (Refresh.BlendOp)ColorBlendOp, - colorWriteMask = (Refresh.ColorComponentFlags)ColorWriteMask, - destinationAlphaBlendFactor = (Refresh.BlendFactor)DestinationAlphaBlendFactor, - destinationColorBlendFactor = (Refresh.BlendFactor)DestinationColorBlendFactor, - sourceAlphaBlendFactor = (Refresh.BlendFactor)SourceAlphaBlendFactor, - sourceColorBlendFactor = (Refresh.BlendFactor)SourceColorBlendFactor - }; - } - } + public Refresh.ColorTargetBlendState ToRefreshColorTargetBlendState() + { + return new Refresh.ColorTargetBlendState + { + blendEnable = Conversions.BoolToByte(BlendEnable), + alphaBlendOp = (Refresh.BlendOp) AlphaBlendOp, + colorBlendOp = (Refresh.BlendOp) ColorBlendOp, + colorWriteMask = (Refresh.ColorComponentFlags) ColorWriteMask, + destinationAlphaBlendFactor = (Refresh.BlendFactor) DestinationAlphaBlendFactor, + destinationColorBlendFactor = (Refresh.BlendFactor) DestinationColorBlendFactor, + sourceAlphaBlendFactor = (Refresh.BlendFactor) SourceAlphaBlendFactor, + sourceColorBlendFactor = (Refresh.BlendFactor) SourceColorBlendFactor + }; + } + } } diff --git a/src/Graphics/State/DepthStencilState.cs b/src/Graphics/State/DepthStencilState.cs index 044df3d7..000b86dd 100644 --- a/src/Graphics/State/DepthStencilState.cs +++ b/src/Graphics/State/DepthStencilState.cs @@ -1,79 +1,79 @@ -namespace MoonWorks.Graphics +namespace MoonWorks.Graphics { - /// - /// Determines how data is written to and read from the depth/stencil buffer. - /// - public struct DepthStencilState - { - /// - /// If disabled, no depth culling will occur. - /// - public bool DepthTestEnable; + /// + /// Determines how data is written to and read from the depth/stencil buffer. + /// + public struct DepthStencilState + { + /// + /// If disabled, no depth culling will occur. + /// + public bool DepthTestEnable; - /// - /// Describes the stencil operation for back-facing primitives. - /// - public StencilOpState BackStencilState; + /// + /// Describes the stencil operation for back-facing primitives. + /// + public StencilOpState BackStencilState; - /// - /// Describes the stencil operation for front-facing primitives. - /// - public StencilOpState FrontStencilState; + /// + /// Describes the stencil operation for front-facing primitives. + /// + public StencilOpState FrontStencilState; - /// - /// The comparison operator used in the depth test. - /// - public CompareOp CompareOp; + /// + /// The comparison operator used in the depth test. + /// + public CompareOp CompareOp; - /// - /// If depth lies outside of these bounds the pixel will be culled. - /// - public bool DepthBoundsTestEnable; + /// + /// If depth lies outside of these bounds the pixel will be culled. + /// + public bool DepthBoundsTestEnable; - /// - /// Specifies whether depth values will be written to the buffer during rendering. - /// - public bool DepthWriteEnable; + /// + /// Specifies whether depth values will be written to the buffer during rendering. + /// + public bool DepthWriteEnable; - /// - /// The minimum depth value in the depth bounds test. - /// - public float MinDepthBounds; + /// + /// The minimum depth value in the depth bounds test. + /// + public float MinDepthBounds; - /// - /// The maximum depth value in the depth bounds test. - /// - public float MaxDepthBounds; + /// + /// The maximum depth value in the depth bounds test. + /// + public float MaxDepthBounds; - /// - /// If disabled, no stencil culling will occur. - /// - public bool StencilTestEnable; + /// + /// If disabled, no stencil culling will occur. + /// + public bool StencilTestEnable; - public static readonly DepthStencilState DepthReadWrite = new DepthStencilState - { - DepthTestEnable = true, - DepthWriteEnable = true, - DepthBoundsTestEnable = false, - StencilTestEnable = false, - CompareOp = CompareOp.LessOrEqual - }; + public static readonly DepthStencilState DepthReadWrite = new DepthStencilState + { + DepthTestEnable = true, + DepthWriteEnable = true, + DepthBoundsTestEnable = false, + StencilTestEnable = false, + CompareOp = CompareOp.LessOrEqual + }; - public static readonly DepthStencilState DepthRead = new DepthStencilState - { - DepthTestEnable = true, - DepthWriteEnable = false, - DepthBoundsTestEnable = false, - StencilTestEnable = false, - CompareOp = CompareOp.LessOrEqual - }; + public static readonly DepthStencilState DepthRead = new DepthStencilState + { + DepthTestEnable = true, + DepthWriteEnable = false, + DepthBoundsTestEnable = false, + StencilTestEnable = false, + CompareOp = CompareOp.LessOrEqual + }; - public static readonly DepthStencilState Disable = new DepthStencilState - { - DepthTestEnable = false, - DepthWriteEnable = false, - DepthBoundsTestEnable = false, - StencilTestEnable = false - }; - } + public static readonly DepthStencilState Disable = new DepthStencilState + { + DepthTestEnable = false, + DepthWriteEnable = false, + DepthBoundsTestEnable = false, + StencilTestEnable = false + }; + } } diff --git a/src/Graphics/State/GraphicsPipelineCreateInfo.cs b/src/Graphics/State/GraphicsPipelineCreateInfo.cs index 68178b26..67c0b7d1 100644 --- a/src/Graphics/State/GraphicsPipelineCreateInfo.cs +++ b/src/Graphics/State/GraphicsPipelineCreateInfo.cs @@ -1,17 +1,17 @@ -namespace MoonWorks.Graphics +namespace MoonWorks.Graphics { - public struct GraphicsPipelineCreateInfo - { - public ColorBlendState ColorBlendState; - public DepthStencilState DepthStencilState; - public ShaderStageState VertexShaderState; - public ShaderStageState FragmentShaderState; - public MultisampleState MultisampleState; - public GraphicsPipelineLayoutInfo PipelineLayoutInfo; - public RasterizerState RasterizerState; - public PrimitiveType PrimitiveType; - public VertexInputState VertexInputState; - public ViewportState ViewportState; - public RenderPass RenderPass; - } + public struct GraphicsPipelineCreateInfo + { + public ColorBlendState ColorBlendState; + public DepthStencilState DepthStencilState; + public ShaderStageState VertexShaderState; + public ShaderStageState FragmentShaderState; + public MultisampleState MultisampleState; + public GraphicsPipelineLayoutInfo PipelineLayoutInfo; + public RasterizerState RasterizerState; + public PrimitiveType PrimitiveType; + public VertexInputState VertexInputState; + public ViewportState ViewportState; + public RenderPass RenderPass; + } } diff --git a/src/Graphics/State/GraphicsPipelineLayoutInfo.cs b/src/Graphics/State/GraphicsPipelineLayoutInfo.cs index 7a237bdf..40cd14c1 100644 --- a/src/Graphics/State/GraphicsPipelineLayoutInfo.cs +++ b/src/Graphics/State/GraphicsPipelineLayoutInfo.cs @@ -1,11 +1,11 @@ -namespace MoonWorks.Graphics +namespace MoonWorks.Graphics { - /// - /// Describes how many samplers will be used in each shader stage. - /// - public struct GraphicsPipelineLayoutInfo - { - public uint VertexSamplerBindingCount; - public uint FragmentSamplerBindingCount; - } + /// + /// Describes how many samplers will be used in each shader stage. + /// + public struct GraphicsPipelineLayoutInfo + { + public uint VertexSamplerBindingCount; + public uint FragmentSamplerBindingCount; + } } diff --git a/src/Graphics/State/MultisampleState.cs b/src/Graphics/State/MultisampleState.cs index a6915688..4b6806fa 100644 --- a/src/Graphics/State/MultisampleState.cs +++ b/src/Graphics/State/MultisampleState.cs @@ -1,17 +1,17 @@ -namespace MoonWorks.Graphics +namespace MoonWorks.Graphics { - /// - /// Specifies how many samples should be used in rasterization. - /// - public struct MultisampleState - { - public SampleCount MultisampleCount; - public uint SampleMask; + /// + /// Specifies how many samples should be used in rasterization. + /// + public struct MultisampleState + { + public SampleCount MultisampleCount; + public uint SampleMask; - public static readonly MultisampleState None = new MultisampleState - { - MultisampleCount = SampleCount.One, - SampleMask = uint.MaxValue - }; - } + public static readonly MultisampleState None = new MultisampleState + { + MultisampleCount = SampleCount.One, + SampleMask = uint.MaxValue + }; + } } diff --git a/src/Graphics/State/RasterizerState.cs b/src/Graphics/State/RasterizerState.cs index ec669802..9763ce59 100644 --- a/src/Graphics/State/RasterizerState.cs +++ b/src/Graphics/State/RasterizerState.cs @@ -1,121 +1,121 @@ -namespace MoonWorks.Graphics +namespace MoonWorks.Graphics { - /// - /// Specifies how the rasterizer should be configured for a graphics pipeline. - /// - public struct RasterizerState - { - /// - /// Specifies whether front faces, back faces, none, or both should be culled. - /// - public CullMode CullMode; + /// + /// Specifies how the rasterizer should be configured for a graphics pipeline. + /// + public struct RasterizerState + { + /// + /// Specifies whether front faces, back faces, none, or both should be culled. + /// + public CullMode CullMode; - /// - /// Specifies maximum depth bias of a fragment. Only applies if depth biasing is enabled. - /// - public float DepthBiasClamp; + /// + /// Specifies maximum depth bias of a fragment. Only applies if depth biasing is enabled. + /// + public float DepthBiasClamp; - /// - /// The constant depth value added to each fragment. Only applies if depth biasing is enabled. - /// - public float DepthBiasConstantFactor; + /// + /// The constant depth value added to each fragment. Only applies if depth biasing is enabled. + /// + public float DepthBiasConstantFactor; - /// - /// Specifies whether depth biasing is enabled. Only applies if depth biasing is enabled. - /// - public bool DepthBiasEnable; + /// + /// Specifies whether depth biasing is enabled. Only applies if depth biasing is enabled. + /// + public bool DepthBiasEnable; - /// - /// Factor applied to a fragment's slope in depth bias calculations. Only applies if depth biasing is enabled. - /// - public float DepthBiasSlopeFactor; - public bool DepthClampEnable; + /// + /// Factor applied to a fragment's slope in depth bias calculations. Only applies if depth biasing is enabled. + /// + public float DepthBiasSlopeFactor; + public bool DepthClampEnable; - /// - /// Specifies how triangles should be drawn. - /// - public FillMode FillMode; + /// + /// Specifies how triangles should be drawn. + /// + public FillMode FillMode; - /// - /// Specifies which triangle winding order is designated as front-facing. - /// - public FrontFace FrontFace; + /// + /// Specifies which triangle winding order is designated as front-facing. + /// + public FrontFace FrontFace; - /// - /// Describes the width of the line rendering in terms of pixels. - /// - public float LineWidth; + /// + /// Describes the width of the line rendering in terms of pixels. + /// + public float LineWidth; - public static readonly RasterizerState CW_CullFront = new RasterizerState - { - CullMode = CullMode.Front, - FrontFace = FrontFace.Clockwise, - FillMode = FillMode.Fill, - DepthBiasEnable = false, - LineWidth = 1f - }; + public static readonly RasterizerState CW_CullFront = new RasterizerState + { + CullMode = CullMode.Front, + FrontFace = FrontFace.Clockwise, + FillMode = FillMode.Fill, + DepthBiasEnable = false, + LineWidth = 1f + }; - public static readonly RasterizerState CW_CullBack = new RasterizerState - { - CullMode = CullMode.Back, - FrontFace = FrontFace.Clockwise, - FillMode = FillMode.Fill, - DepthBiasEnable = false, - LineWidth = 1f - }; + public static readonly RasterizerState CW_CullBack = new RasterizerState + { + CullMode = CullMode.Back, + FrontFace = FrontFace.Clockwise, + FillMode = FillMode.Fill, + DepthBiasEnable = false, + LineWidth = 1f + }; - public static readonly RasterizerState CW_CullNone = new RasterizerState - { - CullMode = CullMode.None, - FrontFace = FrontFace.Clockwise, - FillMode = FillMode.Fill, - DepthBiasEnable = false, - LineWidth = 1f - }; + public static readonly RasterizerState CW_CullNone = new RasterizerState + { + CullMode = CullMode.None, + FrontFace = FrontFace.Clockwise, + FillMode = FillMode.Fill, + DepthBiasEnable = false, + LineWidth = 1f + }; - public static readonly RasterizerState CW_Wireframe = new RasterizerState - { - CullMode = CullMode.None, - FrontFace = FrontFace.Clockwise, - FillMode = FillMode.Fill, - DepthBiasEnable = false, - LineWidth = 1f - }; + public static readonly RasterizerState CW_Wireframe = new RasterizerState + { + CullMode = CullMode.None, + FrontFace = FrontFace.Clockwise, + FillMode = FillMode.Fill, + DepthBiasEnable = false, + LineWidth = 1f + }; - public static readonly RasterizerState CCW_CullFront = new RasterizerState - { - CullMode = CullMode.Front, - FrontFace = FrontFace.CounterClockwise, - FillMode = FillMode.Fill, - DepthBiasEnable = false, - LineWidth = 1f - }; + public static readonly RasterizerState CCW_CullFront = new RasterizerState + { + CullMode = CullMode.Front, + FrontFace = FrontFace.CounterClockwise, + FillMode = FillMode.Fill, + DepthBiasEnable = false, + LineWidth = 1f + }; - public static readonly RasterizerState CCW_CullBack = new RasterizerState - { - CullMode = CullMode.Back, - FrontFace = FrontFace.CounterClockwise, - FillMode = FillMode.Fill, - DepthBiasEnable = false, - LineWidth = 1f - }; + public static readonly RasterizerState CCW_CullBack = new RasterizerState + { + CullMode = CullMode.Back, + FrontFace = FrontFace.CounterClockwise, + FillMode = FillMode.Fill, + DepthBiasEnable = false, + LineWidth = 1f + }; - public static readonly RasterizerState CCW_CullNone = new RasterizerState - { - CullMode = CullMode.None, - FrontFace = FrontFace.CounterClockwise, - FillMode = FillMode.Fill, - DepthBiasEnable = false, - LineWidth = 1f - }; + public static readonly RasterizerState CCW_CullNone = new RasterizerState + { + CullMode = CullMode.None, + FrontFace = FrontFace.CounterClockwise, + FillMode = FillMode.Fill, + DepthBiasEnable = false, + LineWidth = 1f + }; - public static readonly RasterizerState CCW_Wireframe = new RasterizerState - { - CullMode = CullMode.None, - FrontFace = FrontFace.CounterClockwise, - FillMode = FillMode.Fill, - DepthBiasEnable = false, - LineWidth = 1f - }; - } + public static readonly RasterizerState CCW_Wireframe = new RasterizerState + { + CullMode = CullMode.None, + FrontFace = FrontFace.CounterClockwise, + FillMode = FillMode.Fill, + DepthBiasEnable = false, + LineWidth = 1f + }; + } } diff --git a/src/Graphics/State/SamplerCreateInfo.cs b/src/Graphics/State/SamplerCreateInfo.cs index 6e5831b5..bc5e958a 100644 --- a/src/Graphics/State/SamplerCreateInfo.cs +++ b/src/Graphics/State/SamplerCreateInfo.cs @@ -2,134 +2,134 @@ namespace MoonWorks.Graphics { - public struct SamplerCreateInfo - { - public Filter MinFilter; - public Filter MagFilter; - public SamplerMipmapMode MipmapMode; - public SamplerAddressMode AddressModeU; - public SamplerAddressMode AddressModeV; - public SamplerAddressMode AddressModeW; - public float MipLodBias; - public bool AnisotropyEnable; - public float MaxAnisotropy; - public bool CompareEnable; - public CompareOp CompareOp; - public float MinLod; - public float MaxLod; - public BorderColor BorderColor; + public struct SamplerCreateInfo + { + public Filter MinFilter; + public Filter MagFilter; + public SamplerMipmapMode MipmapMode; + public SamplerAddressMode AddressModeU; + public SamplerAddressMode AddressModeV; + public SamplerAddressMode AddressModeW; + public float MipLodBias; + public bool AnisotropyEnable; + public float MaxAnisotropy; + public bool CompareEnable; + public CompareOp CompareOp; + public float MinLod; + public float MaxLod; + public BorderColor BorderColor; - public static readonly SamplerCreateInfo AnisotropicClamp = new SamplerCreateInfo - { - MinFilter = Filter.Linear, - MagFilter = Filter.Linear, - MipmapMode = SamplerMipmapMode.Linear, - AddressModeU = SamplerAddressMode.ClampToEdge, - AddressModeV = SamplerAddressMode.ClampToEdge, - AddressModeW = SamplerAddressMode.ClampToEdge, - CompareEnable = false, - AnisotropyEnable = true, - MaxAnisotropy = 4, - MipLodBias = 0f, - MinLod = 0, - MaxLod = 1000 /* VK_LOD_CLAMP_NONE */ - }; + public static readonly SamplerCreateInfo AnisotropicClamp = new SamplerCreateInfo + { + MinFilter = Filter.Linear, + MagFilter = Filter.Linear, + MipmapMode = SamplerMipmapMode.Linear, + AddressModeU = SamplerAddressMode.ClampToEdge, + AddressModeV = SamplerAddressMode.ClampToEdge, + AddressModeW = SamplerAddressMode.ClampToEdge, + CompareEnable = false, + AnisotropyEnable = true, + MaxAnisotropy = 4, + MipLodBias = 0f, + MinLod = 0, + MaxLod = 1000 /* VK_LOD_CLAMP_NONE */ + }; - public static readonly SamplerCreateInfo AnisotropicWrap = new SamplerCreateInfo - { - MinFilter = Filter.Linear, - MagFilter = Filter.Linear, - MipmapMode = SamplerMipmapMode.Linear, - AddressModeU = SamplerAddressMode.Repeat, - AddressModeV = SamplerAddressMode.Repeat, - AddressModeW = SamplerAddressMode.Repeat, - CompareEnable = false, - AnisotropyEnable = true, - MaxAnisotropy = 4, - MipLodBias = 0f, - MinLod = 0, - MaxLod = 1000 /* VK_LOD_CLAMP_NONE */ - }; + public static readonly SamplerCreateInfo AnisotropicWrap = new SamplerCreateInfo + { + MinFilter = Filter.Linear, + MagFilter = Filter.Linear, + MipmapMode = SamplerMipmapMode.Linear, + AddressModeU = SamplerAddressMode.Repeat, + AddressModeV = SamplerAddressMode.Repeat, + AddressModeW = SamplerAddressMode.Repeat, + CompareEnable = false, + AnisotropyEnable = true, + MaxAnisotropy = 4, + MipLodBias = 0f, + MinLod = 0, + MaxLod = 1000 /* VK_LOD_CLAMP_NONE */ + }; - public static readonly SamplerCreateInfo LinearClamp = new SamplerCreateInfo - { - MinFilter = Filter.Linear, - MagFilter = Filter.Linear, - MipmapMode = SamplerMipmapMode.Linear, - AddressModeU = SamplerAddressMode.ClampToEdge, - AddressModeV = SamplerAddressMode.ClampToEdge, - AddressModeW = SamplerAddressMode.ClampToEdge, - CompareEnable = false, - AnisotropyEnable = false, - MipLodBias = 0f, - MinLod = 0, - MaxLod = 1000 - }; + public static readonly SamplerCreateInfo LinearClamp = new SamplerCreateInfo + { + MinFilter = Filter.Linear, + MagFilter = Filter.Linear, + MipmapMode = SamplerMipmapMode.Linear, + AddressModeU = SamplerAddressMode.ClampToEdge, + AddressModeV = SamplerAddressMode.ClampToEdge, + AddressModeW = SamplerAddressMode.ClampToEdge, + CompareEnable = false, + AnisotropyEnable = false, + MipLodBias = 0f, + MinLod = 0, + MaxLod = 1000 + }; - public static readonly SamplerCreateInfo LinearWrap = new SamplerCreateInfo - { - MinFilter = Filter.Linear, - MagFilter = Filter.Linear, - MipmapMode = SamplerMipmapMode.Linear, - AddressModeU = SamplerAddressMode.Repeat, - AddressModeV = SamplerAddressMode.Repeat, - AddressModeW = SamplerAddressMode.Repeat, - CompareEnable = false, - AnisotropyEnable = false, - MipLodBias = 0f, - MinLod = 0, - MaxLod = 1000 - }; + public static readonly SamplerCreateInfo LinearWrap = new SamplerCreateInfo + { + MinFilter = Filter.Linear, + MagFilter = Filter.Linear, + MipmapMode = SamplerMipmapMode.Linear, + AddressModeU = SamplerAddressMode.Repeat, + AddressModeV = SamplerAddressMode.Repeat, + AddressModeW = SamplerAddressMode.Repeat, + CompareEnable = false, + AnisotropyEnable = false, + MipLodBias = 0f, + MinLod = 0, + MaxLod = 1000 + }; - public static readonly SamplerCreateInfo PointClamp = new SamplerCreateInfo - { - MinFilter = Filter.Nearest, - MagFilter = Filter.Nearest, - MipmapMode = SamplerMipmapMode.Nearest, - AddressModeU = SamplerAddressMode.ClampToEdge, - AddressModeV = SamplerAddressMode.ClampToEdge, - AddressModeW = SamplerAddressMode.ClampToEdge, - CompareEnable = false, - AnisotropyEnable = false, - MipLodBias = 0f, - MinLod = 0, - MaxLod = 1000 - }; + public static readonly SamplerCreateInfo PointClamp = new SamplerCreateInfo + { + MinFilter = Filter.Nearest, + MagFilter = Filter.Nearest, + MipmapMode = SamplerMipmapMode.Nearest, + AddressModeU = SamplerAddressMode.ClampToEdge, + AddressModeV = SamplerAddressMode.ClampToEdge, + AddressModeW = SamplerAddressMode.ClampToEdge, + CompareEnable = false, + AnisotropyEnable = false, + MipLodBias = 0f, + MinLod = 0, + MaxLod = 1000 + }; - public static readonly SamplerCreateInfo PointWrap = new SamplerCreateInfo - { - MinFilter = Filter.Nearest, - MagFilter = Filter.Nearest, - MipmapMode = SamplerMipmapMode.Nearest, - AddressModeU = SamplerAddressMode.Repeat, - AddressModeV = SamplerAddressMode.Repeat, - AddressModeW = SamplerAddressMode.Repeat, - CompareEnable = false, - AnisotropyEnable = false, - MipLodBias = 0f, - MinLod = 0, - MaxLod = 1000 - }; + public static readonly SamplerCreateInfo PointWrap = new SamplerCreateInfo + { + MinFilter = Filter.Nearest, + MagFilter = Filter.Nearest, + MipmapMode = SamplerMipmapMode.Nearest, + AddressModeU = SamplerAddressMode.Repeat, + AddressModeV = SamplerAddressMode.Repeat, + AddressModeW = SamplerAddressMode.Repeat, + CompareEnable = false, + AnisotropyEnable = false, + MipLodBias = 0f, + MinLod = 0, + MaxLod = 1000 + }; - public Refresh.SamplerStateCreateInfo ToRefreshSamplerStateCreateInfo() - { - return new Refresh.SamplerStateCreateInfo - { - minFilter = (Refresh.Filter)MinFilter, - magFilter = (Refresh.Filter)MagFilter, - mipmapMode = (Refresh.SamplerMipmapMode)MipmapMode, - addressModeU = (Refresh.SamplerAddressMode)AddressModeU, - addressModeV = (Refresh.SamplerAddressMode)AddressModeV, - addressModeW = (Refresh.SamplerAddressMode)AddressModeW, - mipLodBias = MipLodBias, - anisotropyEnable = Conversions.BoolToByte(AnisotropyEnable), - maxAnisotropy = MaxAnisotropy, - compareEnable = Conversions.BoolToByte(CompareEnable), - compareOp = (Refresh.CompareOp)CompareOp, - minLod = MinLod, - maxLod = MaxLod, - borderColor = (Refresh.BorderColor)BorderColor - }; - } - } + public Refresh.SamplerStateCreateInfo ToRefreshSamplerStateCreateInfo() + { + return new Refresh.SamplerStateCreateInfo + { + minFilter = (Refresh.Filter) MinFilter, + magFilter = (Refresh.Filter) MagFilter, + mipmapMode = (Refresh.SamplerMipmapMode) MipmapMode, + addressModeU = (Refresh.SamplerAddressMode) AddressModeU, + addressModeV = (Refresh.SamplerAddressMode) AddressModeV, + addressModeW = (Refresh.SamplerAddressMode) AddressModeW, + mipLodBias = MipLodBias, + anisotropyEnable = Conversions.BoolToByte(AnisotropyEnable), + maxAnisotropy = MaxAnisotropy, + compareEnable = Conversions.BoolToByte(CompareEnable), + compareOp = (Refresh.CompareOp) CompareOp, + minLod = MinLod, + maxLod = MaxLod, + borderColor = (Refresh.BorderColor) BorderColor + }; + } + } } diff --git a/src/Graphics/State/ShaderStageState.cs b/src/Graphics/State/ShaderStageState.cs index 83ce53cd..e691b41b 100644 --- a/src/Graphics/State/ShaderStageState.cs +++ b/src/Graphics/State/ShaderStageState.cs @@ -1,12 +1,12 @@ -namespace MoonWorks.Graphics +namespace MoonWorks.Graphics { - /// - /// Specifies how the graphics pipeline will make use of a shader. - /// - public struct ShaderStageState - { - public ShaderModule ShaderModule; - public string EntryPointName; - public uint UniformBufferSize; - } + /// + /// Specifies how the graphics pipeline will make use of a shader. + /// + public struct ShaderStageState + { + public ShaderModule ShaderModule; + public string EntryPointName; + public uint UniformBufferSize; + } } diff --git a/src/Graphics/State/TextureCreateInfo.cs b/src/Graphics/State/TextureCreateInfo.cs index fad07b56..f7044bfa 100644 --- a/src/Graphics/State/TextureCreateInfo.cs +++ b/src/Graphics/State/TextureCreateInfo.cs @@ -2,30 +2,30 @@ namespace MoonWorks.Graphics { - public struct TextureCreateInfo - { - public uint Width; - public uint Height; - public uint Depth; - public bool IsCube; - public SampleCount SampleCount; - public uint LevelCount; - public TextureFormat Format; - public TextureUsageFlags UsageFlags; + public struct TextureCreateInfo + { + public uint Width; + public uint Height; + public uint Depth; + public bool IsCube; + public SampleCount SampleCount; + public uint LevelCount; + public TextureFormat Format; + public TextureUsageFlags UsageFlags; - public Refresh.TextureCreateInfo ToRefreshTextureCreateInfo() - { - return new Refresh.TextureCreateInfo - { - width = Width, - height = Height, - depth = Depth, - isCube = Conversions.BoolToByte(IsCube), - sampleCount = (Refresh.SampleCount) SampleCount, - levelCount = LevelCount, - format = (Refresh.TextureFormat) Format, - usageFlags = (Refresh.TextureUsageFlags) UsageFlags - }; - } - } + public Refresh.TextureCreateInfo ToRefreshTextureCreateInfo() + { + return new Refresh.TextureCreateInfo + { + width = Width, + height = Height, + depth = Depth, + isCube = Conversions.BoolToByte(IsCube), + sampleCount = (Refresh.SampleCount) SampleCount, + levelCount = LevelCount, + format = (Refresh.TextureFormat) Format, + usageFlags = (Refresh.TextureUsageFlags) UsageFlags + }; + } + } } diff --git a/src/Graphics/State/VertexInputState.cs b/src/Graphics/State/VertexInputState.cs index f80731a9..1c7233ff 100644 --- a/src/Graphics/State/VertexInputState.cs +++ b/src/Graphics/State/VertexInputState.cs @@ -1,11 +1,11 @@ -namespace MoonWorks.Graphics +namespace MoonWorks.Graphics { - /// - /// Specifies how to interpet vertex data in a buffer to be passed to the vertex shader. - /// - public struct VertexInputState - { - public VertexBinding[] VertexBindings; - public VertexAttribute[] VertexAttributes; - } + /// + /// Specifies how to interpet vertex data in a buffer to be passed to the vertex shader. + /// + public struct VertexInputState + { + public VertexBinding[] VertexBindings; + public VertexAttribute[] VertexAttributes; + } } diff --git a/src/Graphics/State/ViewportState.cs b/src/Graphics/State/ViewportState.cs index 1fd1c76b..294b6ec7 100644 --- a/src/Graphics/State/ViewportState.cs +++ b/src/Graphics/State/ViewportState.cs @@ -1,11 +1,11 @@ -namespace MoonWorks.Graphics +namespace MoonWorks.Graphics { - /// - /// Describes the dimensions of viewports and scissor areas. - /// - public struct ViewportState - { - public Viewport[] Viewports; - public Rect[] Scissors; - } + /// + /// Describes the dimensions of viewports and scissor areas. + /// + public struct ViewportState + { + public Viewport[] Viewports; + public Rect[] Scissors; + } } diff --git a/src/Graphics/Structs/BlendConstants.cs b/src/Graphics/Structs/BlendConstants.cs index 71a3582c..40951855 100644 --- a/src/Graphics/Structs/BlendConstants.cs +++ b/src/Graphics/Structs/BlendConstants.cs @@ -1,10 +1,10 @@ -namespace MoonWorks.Graphics +namespace MoonWorks.Graphics { - public struct BlendConstants - { - public float R; - public float G; - public float B; - public float A; - } + public struct BlendConstants + { + public float R; + public float G; + public float B; + public float A; + } } diff --git a/src/Graphics/TextureSlice.cs b/src/Graphics/TextureSlice.cs index de5b2253..e6400832 100644 --- a/src/Graphics/TextureSlice.cs +++ b/src/Graphics/TextureSlice.cs @@ -2,54 +2,54 @@ namespace MoonWorks.Graphics { - /// - /// A texture slice specifies a subregion of a texture. - /// Many operations can use texture slices in place of textures for the sake of convenience. - /// - public struct TextureSlice - { - public Texture Texture { get; } - public Rect Rectangle { get; } - public uint Depth { get; } - public uint Layer { get; } - public uint Level { get; } + /// + /// A texture slice specifies a subregion of a texture. + /// Many operations can use texture slices in place of textures for the sake of convenience. + /// + public struct TextureSlice + { + public Texture Texture { get; } + public Rect Rectangle { get; } + public uint Depth { get; } + public uint Layer { get; } + public uint Level { get; } - public TextureSlice(Texture texture) - { - Texture = texture; - Rectangle = new Rect - { - X = 0, - Y = 0, - W = (int) texture.Width, - H = (int) texture.Height - }; - Depth = 0; - Layer = 0; - Level = 0; - } + public TextureSlice(Texture texture) + { + Texture = texture; + Rectangle = new Rect + { + X = 0, + Y = 0, + W = (int) texture.Width, + H = (int) texture.Height + }; + Depth = 0; + Layer = 0; + Level = 0; + } - public TextureSlice(Texture texture, Rect rectangle, uint depth = 0, uint layer = 0, uint level = 0) - { - Texture = texture; - Rectangle = rectangle; - Depth = depth; - Layer = layer; - Level = level; - } + public TextureSlice(Texture texture, Rect rectangle, uint depth = 0, uint layer = 0, uint level = 0) + { + Texture = texture; + Rectangle = rectangle; + Depth = depth; + Layer = layer; + Level = level; + } - public Refresh.TextureSlice ToRefreshTextureSlice() - { - Refresh.TextureSlice textureSlice = new Refresh.TextureSlice - { - texture = Texture.Handle, - rectangle = Rectangle.ToRefresh(), - depth = Depth, - layer = Layer, - level = Level - }; + public Refresh.TextureSlice ToRefreshTextureSlice() + { + Refresh.TextureSlice textureSlice = new Refresh.TextureSlice + { + texture = Texture.Handle, + rectangle = Rectangle.ToRefresh(), + depth = Depth, + layer = Layer, + level = Level + }; - return textureSlice; - } - } + return textureSlice; + } + } } diff --git a/src/Graphics/Utility/Bytecode.cs b/src/Graphics/Utility/Bytecode.cs index e64091e0..76eed8dc 100644 --- a/src/Graphics/Utility/Bytecode.cs +++ b/src/Graphics/Utility/Bytecode.cs @@ -2,32 +2,32 @@ namespace MoonWorks.Graphics { - public static class Bytecode - { - public static uint[] ReadBytecodeAsUInt32(string filePath) - { - byte[] data; - int size; - using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) - { - size = (int)stream.Length; - data = new byte[size]; - stream.Read(data, 0, size); - } + public static class Bytecode + { + public static uint[] ReadBytecodeAsUInt32(string filePath) + { + byte[] data; + int size; + using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) + { + size = (int) stream.Length; + data = new byte[size]; + stream.Read(data, 0, size); + } - uint[] uintData = new uint[size / 4]; - using (var memoryStream = new MemoryStream(data)) - { - using (var reader = new BinaryReader(memoryStream)) - { - for (int i = 0; i < size / 4; i++) - { - uintData[i] = reader.ReadUInt32(); - } - } - } + uint[] uintData = new uint[size / 4]; + using (var memoryStream = new MemoryStream(data)) + { + using (var reader = new BinaryReader(memoryStream)) + { + for (int i = 0; i < size / 4; i++) + { + uintData[i] = reader.ReadUInt32(); + } + } + } - return uintData; - } - } + return uintData; + } + } } diff --git a/src/Graphics/Utility/Conversions.cs b/src/Graphics/Utility/Conversions.cs index 5a8f43ec..aaadd6c2 100644 --- a/src/Graphics/Utility/Conversions.cs +++ b/src/Graphics/Utility/Conversions.cs @@ -1,15 +1,15 @@ -namespace MoonWorks +namespace MoonWorks { - public static class Conversions - { - public static byte BoolToByte(bool b) - { - return (byte)(b ? 1 : 0); - } + public static class Conversions + { + public static byte BoolToByte(bool b) + { + return (byte) (b ? 1 : 0); + } - public static bool ByteToBool(byte b) - { - return b == 0 ? false : true; - } - } + public static bool ByteToBool(byte b) + { + return b == 0 ? false : true; + } + } } diff --git a/src/Input/ButtonState.cs b/src/Input/ButtonState.cs index 714c09c4..20e60f84 100644 --- a/src/Input/ButtonState.cs +++ b/src/Input/ButtonState.cs @@ -1,31 +1,31 @@ -namespace MoonWorks.Input +namespace MoonWorks.Input { - public class ButtonState - { - private ButtonStatus ButtonStatus { get; set; } + public class ButtonState + { + private ButtonStatus ButtonStatus { get; set; } - public bool IsPressed => ButtonStatus == ButtonStatus.Pressed; - public bool IsHeld => ButtonStatus == ButtonStatus.Held; - public bool IsDown => ButtonStatus == ButtonStatus.Pressed || ButtonStatus == ButtonStatus.Held; - public bool IsReleased => ButtonStatus == ButtonStatus.Released; + public bool IsPressed => ButtonStatus == ButtonStatus.Pressed; + public bool IsHeld => ButtonStatus == ButtonStatus.Held; + public bool IsDown => ButtonStatus == ButtonStatus.Pressed || ButtonStatus == ButtonStatus.Held; + public bool IsReleased => ButtonStatus == ButtonStatus.Released; - internal void Update(bool isPressed) - { - if (isPressed) - { - if (ButtonStatus == ButtonStatus.Pressed) - { - ButtonStatus = ButtonStatus.Held; - } - else if (ButtonStatus == ButtonStatus.Released) - { - ButtonStatus = ButtonStatus.Pressed; - } - } - else - { - ButtonStatus = ButtonStatus.Released; - } - } - } + internal void Update(bool isPressed) + { + if (isPressed) + { + if (ButtonStatus == ButtonStatus.Pressed) + { + ButtonStatus = ButtonStatus.Held; + } + else if (ButtonStatus == ButtonStatus.Released) + { + ButtonStatus = ButtonStatus.Pressed; + } + } + else + { + ButtonStatus = ButtonStatus.Released; + } + } + } } diff --git a/src/Input/ButtonStatus.cs b/src/Input/ButtonStatus.cs index 61446055..13bd6a7b 100644 --- a/src/Input/ButtonStatus.cs +++ b/src/Input/ButtonStatus.cs @@ -1,18 +1,18 @@ -namespace MoonWorks.Input +namespace MoonWorks.Input { - internal enum ButtonStatus - { - /// - /// Indicates that the input is not pressed. - /// - Released, - /// - /// Indicates that the input was pressed this frame. - /// - Pressed, - /// - /// Indicates that the input has been held for multiple frames. - /// - Held - } + internal enum ButtonStatus + { + /// + /// Indicates that the input is not pressed. + /// + Released, + /// + /// Indicates that the input was pressed this frame. + /// + Pressed, + /// + /// Indicates that the input has been held for multiple frames. + /// + Held + } } diff --git a/src/Input/Gamepad.cs b/src/Input/Gamepad.cs index d90939b8..7475f56a 100644 --- a/src/Input/Gamepad.cs +++ b/src/Input/Gamepad.cs @@ -1,98 +1,98 @@ -using System; +using System; using MoonWorks.Math; using SDL2; namespace MoonWorks.Input { - public class Gamepad - { - internal IntPtr Handle; + public class Gamepad + { + internal IntPtr Handle; - public ButtonState A { get; } = new ButtonState(); - public ButtonState B { get; } = new ButtonState(); - public ButtonState X { get; } = new ButtonState(); - public ButtonState Y { get; } = new ButtonState(); - public ButtonState Back { get; } = new ButtonState(); - public ButtonState Guide { get; } = new ButtonState(); - public ButtonState Start { get; } = new ButtonState(); - public ButtonState LeftStick { get; } = new ButtonState(); - public ButtonState RightStick { get; } = new ButtonState(); - public ButtonState LeftShoulder { get; } = new ButtonState(); - public ButtonState RightShoulder { get; } = new ButtonState(); - public ButtonState DpadUp { get; } = new ButtonState(); - public ButtonState DpadDown { get; } = new ButtonState(); - public ButtonState DpadLeft { get; } = new ButtonState(); - public ButtonState DpadRight { get; } = new ButtonState(); + public ButtonState A { get; } = new ButtonState(); + public ButtonState B { get; } = new ButtonState(); + public ButtonState X { get; } = new ButtonState(); + public ButtonState Y { get; } = new ButtonState(); + public ButtonState Back { get; } = new ButtonState(); + public ButtonState Guide { get; } = new ButtonState(); + public ButtonState Start { get; } = new ButtonState(); + public ButtonState LeftStick { get; } = new ButtonState(); + public ButtonState RightStick { get; } = new ButtonState(); + public ButtonState LeftShoulder { get; } = new ButtonState(); + public ButtonState RightShoulder { get; } = new ButtonState(); + public ButtonState DpadUp { get; } = new ButtonState(); + public ButtonState DpadDown { get; } = new ButtonState(); + public ButtonState DpadLeft { get; } = new ButtonState(); + public ButtonState DpadRight { get; } = new ButtonState(); - public float LeftX { get; private set; } - public float LeftY { get; private set; } - public float RightX { get; private set; } - public float RightY { get; private set; } - public float TriggerLeft { get; private set; } - public float TriggerRight { get; private set; } + public float LeftX { get; private set; } + public float LeftY { get; private set; } + public float RightX { get; private set; } + public float RightY { get; private set; } + public float TriggerLeft { get; private set; } + public float TriggerRight { get; private set; } - internal Gamepad(IntPtr handle) - { - Handle = handle; - } + internal Gamepad(IntPtr handle) + { + Handle = handle; + } - public bool SetVibration(float leftMotor, float rightMotor, uint durationInMilliseconds) - { - return SDL.SDL_GameControllerRumble( - Handle, - (ushort)(MathHelper.Clamp(leftMotor, 0f, 1f) * 0xFFFF), - (ushort)(MathHelper.Clamp(rightMotor, 0f, 1f) * 0xFFFF), - durationInMilliseconds - ) == 0; - } + public bool SetVibration(float leftMotor, float rightMotor, uint durationInMilliseconds) + { + return SDL.SDL_GameControllerRumble( + Handle, + (ushort) (MathHelper.Clamp(leftMotor, 0f, 1f) * 0xFFFF), + (ushort) (MathHelper.Clamp(rightMotor, 0f, 1f) * 0xFFFF), + durationInMilliseconds + ) == 0; + } - internal void Update() - { - A.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_A)); - B.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_B)); - X.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_X)); - Y.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_Y)); - Back.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_BACK)); - Guide.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_GUIDE)); - Start.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_START)); - LeftStick.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_LEFTSTICK)); - RightStick.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_RIGHTSTICK)); - LeftShoulder.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_LEFTSHOULDER)); - RightShoulder.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)); - DpadUp.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_UP)); - DpadDown.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_DOWN)); - DpadLeft.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_LEFT)); - DpadRight.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_RIGHT)); + internal void Update() + { + A.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_A)); + B.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_B)); + X.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_X)); + Y.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_Y)); + Back.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_BACK)); + Guide.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_GUIDE)); + Start.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_START)); + LeftStick.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_LEFTSTICK)); + RightStick.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_RIGHTSTICK)); + LeftShoulder.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_LEFTSHOULDER)); + RightShoulder.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)); + DpadUp.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_UP)); + DpadDown.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_DOWN)); + DpadLeft.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_LEFT)); + DpadRight.Update(IsPressed(SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_RIGHT)); - LeftX = UpdateAxis(SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_LEFTX); - LeftY = UpdateAxis(SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_LEFTY); - RightX = UpdateAxis(SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_RIGHTX); - RightY = UpdateAxis(SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_RIGHTY); - TriggerLeft = UpdateTrigger(SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_TRIGGERLEFT); - TriggerRight = UpdateTrigger(SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_TRIGGERRIGHT); - } + LeftX = UpdateAxis(SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_LEFTX); + LeftY = UpdateAxis(SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_LEFTY); + RightX = UpdateAxis(SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_RIGHTX); + RightY = UpdateAxis(SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_RIGHTY); + TriggerLeft = UpdateTrigger(SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_TRIGGERLEFT); + TriggerRight = UpdateTrigger(SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_TRIGGERRIGHT); + } - private bool IsPressed(SDL.SDL_GameControllerButton button) - { - return MoonWorks.Conversions.ByteToBool(SDL.SDL_GameControllerGetButton(Handle, button)); - } + private bool IsPressed(SDL.SDL_GameControllerButton button) + { + return MoonWorks.Conversions.ByteToBool(SDL.SDL_GameControllerGetButton(Handle, button)); + } - private float UpdateAxis(SDL.SDL_GameControllerAxis axis) - { - var axisValue = SDL.SDL_GameControllerGetAxis(Handle, axis); - return Normalize(axisValue, short.MinValue, short.MaxValue, -1, 1); - } + private float UpdateAxis(SDL.SDL_GameControllerAxis axis) + { + var axisValue = SDL.SDL_GameControllerGetAxis(Handle, axis); + return Normalize(axisValue, short.MinValue, short.MaxValue, -1, 1); + } - // Triggers only go from 0 to short.MaxValue - private float UpdateTrigger(SDL.SDL_GameControllerAxis trigger) - { - var triggerValue = SDL.SDL_GameControllerGetAxis(Handle, trigger); - return Normalize(triggerValue, 0, short.MaxValue, 0, 1); - } + // Triggers only go from 0 to short.MaxValue + private float UpdateTrigger(SDL.SDL_GameControllerAxis trigger) + { + var triggerValue = SDL.SDL_GameControllerGetAxis(Handle, trigger); + return Normalize(triggerValue, 0, short.MaxValue, 0, 1); + } - private float Normalize(float value, short min, short max, short newMin, short newMax) - { - return ((value - min) * (newMax - newMin)) / (max - min) + newMin; - } - } + private float Normalize(float value, short min, short max, short newMin, short newMax) + { + return ((value - min) * (newMax - newMin)) / (max - min) + newMin; + } + } } diff --git a/src/Input/Input.cs b/src/Input/Input.cs index 43baf60b..b476f846 100644 --- a/src/Input/Input.cs +++ b/src/Input/Input.cs @@ -1,60 +1,60 @@ -using SDL2; +using SDL2; using System; using System.Collections.Generic; namespace MoonWorks.Input { - public class Inputs - { - public Keyboard Keyboard { get; } - public Mouse Mouse { get; } + public class Inputs + { + public Keyboard Keyboard { get; } + public Mouse Mouse { get; } - List gamepads = new List(); + List gamepads = new List(); - public static event Action TextInput; + public static event Action TextInput; - internal Inputs() - { - Keyboard = new Keyboard(); - Mouse = new Mouse(); + internal Inputs() + { + Keyboard = new Keyboard(); + Mouse = new Mouse(); - for (int i = 0; i < SDL.SDL_NumJoysticks(); i++) - { - if (SDL.SDL_IsGameController(i) == SDL.SDL_bool.SDL_TRUE) - { - gamepads.Add(new Gamepad(SDL.SDL_GameControllerOpen(i))); - } - } - } + for (int i = 0; i < SDL.SDL_NumJoysticks(); i++) + { + if (SDL.SDL_IsGameController(i) == SDL.SDL_bool.SDL_TRUE) + { + gamepads.Add(new Gamepad(SDL.SDL_GameControllerOpen(i))); + } + } + } - // Assumes that SDL_PumpEvents has been called! - internal void Update() - { - Keyboard.Update(); - Mouse.Update(); + // Assumes that SDL_PumpEvents has been called! + internal void Update() + { + Keyboard.Update(); + Mouse.Update(); - foreach (var gamepad in gamepads) - { - gamepad.Update(); - } - } + foreach (var gamepad in gamepads) + { + gamepad.Update(); + } + } - public bool GamepadExists(int slot) - { - return slot < gamepads.Count; - } + public bool GamepadExists(int slot) + { + return slot < gamepads.Count; + } - public Gamepad GetGamepad(int slot) - { - return gamepads[slot]; - } + public Gamepad GetGamepad(int slot) + { + return gamepads[slot]; + } - internal static void OnTextInput(char c) - { - if (TextInput != null) - { - TextInput(c); - } - } - } + internal static void OnTextInput(char c) + { + if (TextInput != null) + { + TextInput(c); + } + } + } } diff --git a/src/Input/Keyboard.cs b/src/Input/Keyboard.cs index 3fcc45d2..821060ad 100644 --- a/src/Input/Keyboard.cs +++ b/src/Input/Keyboard.cs @@ -1,14 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.InteropServices; using SDL2; namespace MoonWorks.Input { - public class Keyboard - { - private ButtonState[] Keys { get; } - private int numKeys; + public class Keyboard + { + private ButtonState[] Keys { get; } + private int numKeys; private static readonly char[] TextInputCharacters = new char[] { @@ -21,69 +21,69 @@ namespace MoonWorks.Input (char) 22 // Ctrl+V (Paste) }; - private static readonly Dictionary TextInputBindings = new Dictionary() + private static readonly Dictionary TextInputBindings = new Dictionary() { - { Keycode.Home, 0 }, - { Keycode.End, 1 }, - { Keycode.Backspace, 2 }, - { Keycode.Tab, 3 }, - { Keycode.Return, 4 }, - { Keycode.Delete, 5 } + { Keycode.Home, 0 }, + { Keycode.End, 1 }, + { Keycode.Backspace, 2 }, + { Keycode.Tab, 3 }, + { Keycode.Return, 4 }, + { Keycode.Delete, 5 } // Ctrl+V is special! }; - internal Keyboard() - { - SDL.SDL_GetKeyboardState(out numKeys); + internal Keyboard() + { + SDL.SDL_GetKeyboardState(out numKeys); - Keys = new ButtonState[numKeys]; - foreach (Keycode keycode in Enum.GetValues(typeof(Keycode))) - { - Keys[(int)keycode] = new ButtonState(); - } - } + Keys = new ButtonState[numKeys]; + foreach (Keycode keycode in Enum.GetValues(typeof(Keycode))) + { + Keys[(int) keycode] = new ButtonState(); + } + } - internal void Update() - { - IntPtr keyboardState = SDL.SDL_GetKeyboardState(out _); + internal void Update() + { + IntPtr keyboardState = SDL.SDL_GetKeyboardState(out _); - foreach (int keycode in Enum.GetValues(typeof(Keycode))) - { - var keyDown = Marshal.ReadByte(keyboardState, keycode); - Keys[keycode].Update(Conversions.ByteToBool(keyDown)); + foreach (int keycode in Enum.GetValues(typeof(Keycode))) + { + var keyDown = Marshal.ReadByte(keyboardState, keycode); + Keys[keycode].Update(Conversions.ByteToBool(keyDown)); - if (Conversions.ByteToBool(keyDown)) - { - if (TextInputBindings.TryGetValue((Keycode)keycode, out var textIndex)) - { - Inputs.OnTextInput(TextInputCharacters[(textIndex)]); - } - else if (IsDown(Keycode.LeftControl) && (Keycode)keycode == Keycode.V) - { - Inputs.OnTextInput(TextInputCharacters[6]); - } - } - } - } + if (Conversions.ByteToBool(keyDown)) + { + if (TextInputBindings.TryGetValue((Keycode) keycode, out var textIndex)) + { + Inputs.OnTextInput(TextInputCharacters[(textIndex)]); + } + else if (IsDown(Keycode.LeftControl) && (Keycode) keycode == Keycode.V) + { + Inputs.OnTextInput(TextInputCharacters[6]); + } + } + } + } - public bool IsDown(Keycode keycode) - { - return Keys[(int)keycode].IsDown; - } + public bool IsDown(Keycode keycode) + { + return Keys[(int) keycode].IsDown; + } - public bool IsPressed(Keycode keycode) - { - return Keys[(int)keycode].IsPressed; - } + public bool IsPressed(Keycode keycode) + { + return Keys[(int) keycode].IsPressed; + } - public bool IsHeld(Keycode keycode) - { - return Keys[(int)keycode].IsHeld; - } + public bool IsHeld(Keycode keycode) + { + return Keys[(int) keycode].IsHeld; + } - public bool IsReleased(Keycode keycode) - { - return Keys[(int)keycode].IsReleased; - } - } + public bool IsReleased(Keycode keycode) + { + return Keys[(int) keycode].IsReleased; + } + } } diff --git a/src/Input/Keycode.cs b/src/Input/Keycode.cs index ac306478..88dadd9a 100644 --- a/src/Input/Keycode.cs +++ b/src/Input/Keycode.cs @@ -1,113 +1,113 @@ -namespace MoonWorks.Input +namespace MoonWorks.Input { - // Enum values are equivalent to the SDL Scancode value. - public enum Keycode : int - { - Unknown = 0, - A = 4, - B = 5, - C = 6, - D = 7, - E = 8, - F = 9, - G = 10, - H = 11, - I = 12, - J = 13, - K = 14, - L = 15, - M = 16, - N = 17, - O = 18, - P = 19, - Q = 20, - R = 21, - S = 22, - T = 23, - U = 24, - V = 25, - W = 26, - X = 27, - Y = 28, - Z = 29, - D1 = 30, - D2 = 31, - D3 = 32, - D4 = 33, - D5 = 34, - D6 = 35, - D7 = 36, - D8 = 37, - D9 = 38, - D0 = 39, - Return = 40, - Escape = 41, - Backspace = 42, - Tab = 43, - Space = 44, - Minus = 45, - Equals = 46, - LeftBracket = 47, - RightBracket = 48, - Backslash = 49, - NonUSHash = 50, - Semicolon = 51, - Apostrophe = 52, - Grave = 53, - Comma = 54, - Period = 55, - Slash = 56, - CapsLock = 57, - F1 = 58, - F2 = 59, - F3 = 60, - F4 = 61, - F5 = 62, - F6 = 63, - F7 = 64, - F8 = 65, - F9 = 66, - F10 = 67, - F11 = 68, - F12 = 69, - PrintScreen = 70, - ScrollLock = 71, - Pause = 72, - Insert = 73, - Home = 74, - PageUp = 75, - Delete = 76, - End = 77, - PageDown = 78, - Right = 79, - Left = 80, - Down = 81, - Up = 82, - NumLockClear = 83, - KeypadDivide = 84, - KeypadMultiply = 85, - KeypadMinus = 86, - KeypadPlus = 87, - KeypadEnter = 88, - Keypad1 = 89, - Keypad2 = 90, - Keypad3 = 91, - Keypad4 = 92, - Keypad5 = 93, - Keypad6 = 94, - Keypad7 = 95, - Keypad8 = 96, - Keypad9 = 97, - Keypad0 = 98, - KeypadPeriod = 99, - NonUSBackslash = 100, - LeftControl = 224, - LeftShift = 225, - LeftAlt = 226, - LeftMeta = 227, // Windows, Command, Meta - RightControl = 228, - RightShift = 229, - RightAlt = 230, - RightMeta = 231 // Windows, Command, Meta - } + // Enum values are equivalent to the SDL Scancode value. + public enum Keycode : int + { + Unknown = 0, + A = 4, + B = 5, + C = 6, + D = 7, + E = 8, + F = 9, + G = 10, + H = 11, + I = 12, + J = 13, + K = 14, + L = 15, + M = 16, + N = 17, + O = 18, + P = 19, + Q = 20, + R = 21, + S = 22, + T = 23, + U = 24, + V = 25, + W = 26, + X = 27, + Y = 28, + Z = 29, + D1 = 30, + D2 = 31, + D3 = 32, + D4 = 33, + D5 = 34, + D6 = 35, + D7 = 36, + D8 = 37, + D9 = 38, + D0 = 39, + Return = 40, + Escape = 41, + Backspace = 42, + Tab = 43, + Space = 44, + Minus = 45, + Equals = 46, + LeftBracket = 47, + RightBracket = 48, + Backslash = 49, + NonUSHash = 50, + Semicolon = 51, + Apostrophe = 52, + Grave = 53, + Comma = 54, + Period = 55, + Slash = 56, + CapsLock = 57, + F1 = 58, + F2 = 59, + F3 = 60, + F4 = 61, + F5 = 62, + F6 = 63, + F7 = 64, + F8 = 65, + F9 = 66, + F10 = 67, + F11 = 68, + F12 = 69, + PrintScreen = 70, + ScrollLock = 71, + Pause = 72, + Insert = 73, + Home = 74, + PageUp = 75, + Delete = 76, + End = 77, + PageDown = 78, + Right = 79, + Left = 80, + Down = 81, + Up = 82, + NumLockClear = 83, + KeypadDivide = 84, + KeypadMultiply = 85, + KeypadMinus = 86, + KeypadPlus = 87, + KeypadEnter = 88, + Keypad1 = 89, + Keypad2 = 90, + Keypad3 = 91, + Keypad4 = 92, + Keypad5 = 93, + Keypad6 = 94, + Keypad7 = 95, + Keypad8 = 96, + Keypad9 = 97, + Keypad0 = 98, + KeypadPeriod = 99, + NonUSBackslash = 100, + LeftControl = 224, + LeftShift = 225, + LeftAlt = 226, + LeftMeta = 227, // Windows, Command, Meta + RightControl = 228, + RightShift = 229, + RightAlt = 230, + RightMeta = 231 // Windows, Command, Meta + } } diff --git a/src/Input/Mouse.cs b/src/Input/Mouse.cs index 5f0c7376..9ff84614 100644 --- a/src/Input/Mouse.cs +++ b/src/Input/Mouse.cs @@ -2,52 +2,52 @@ namespace MoonWorks.Input { - public class Mouse - { - public ButtonState LeftButton { get; } = new ButtonState(); - public ButtonState MiddleButton { get; } = new ButtonState(); - public ButtonState RightButton { get; } = new ButtonState(); + public class Mouse + { + public ButtonState LeftButton { get; } = new ButtonState(); + public ButtonState MiddleButton { get; } = new ButtonState(); + public ButtonState RightButton { get; } = new ButtonState(); - public int X { get; private set; } - public int Y { get; private set; } - public int DeltaX { get; private set; } - public int DeltaY { get; private set; } + public int X { get; private set; } + public int Y { get; private set; } + public int DeltaX { get; private set; } + public int DeltaY { get; private set; } - public int Wheel { get; internal set; } + public int Wheel { get; internal set; } - private bool relativeMode; - public bool RelativeMode - { - get => relativeMode; - set - { - relativeMode = value; - SDL.SDL_SetRelativeMouseMode( - relativeMode ? - SDL.SDL_bool.SDL_TRUE : - SDL.SDL_bool.SDL_FALSE - ); - } - } + private bool relativeMode; + public bool RelativeMode + { + get => relativeMode; + set + { + relativeMode = value; + SDL.SDL_SetRelativeMouseMode( + relativeMode ? + SDL.SDL_bool.SDL_TRUE : + SDL.SDL_bool.SDL_FALSE + ); + } + } - internal void Update() - { - var buttonMask = SDL.SDL_GetMouseState(out var x, out var y); - var _ = SDL.SDL_GetRelativeMouseState(out var deltaX, out var deltaY); + internal void Update() + { + var buttonMask = SDL.SDL_GetMouseState(out var x, out var y); + var _ = SDL.SDL_GetRelativeMouseState(out var deltaX, out var deltaY); - X = x; - Y = y; - DeltaX = deltaX; - DeltaY = deltaY; + X = x; + Y = y; + DeltaX = deltaX; + DeltaY = deltaY; - LeftButton.Update(IsPressed(buttonMask, SDL.SDL_BUTTON_LMASK)); - MiddleButton.Update(IsPressed(buttonMask, SDL.SDL_BUTTON_MMASK)); - RightButton.Update(IsPressed(buttonMask, SDL.SDL_BUTTON_RMASK)); - } + LeftButton.Update(IsPressed(buttonMask, SDL.SDL_BUTTON_LMASK)); + MiddleButton.Update(IsPressed(buttonMask, SDL.SDL_BUTTON_MMASK)); + RightButton.Update(IsPressed(buttonMask, SDL.SDL_BUTTON_RMASK)); + } - private bool IsPressed(uint buttonMask, uint buttonFlag) - { - return (buttonMask & buttonFlag) != 0; - } - } + private bool IsPressed(uint buttonMask, uint buttonFlag) + { + return (buttonMask & buttonFlag) != 0; + } + } } diff --git a/src/Logger.cs b/src/Logger.cs index 37208063..1d0ce7ce 100644 --- a/src/Logger.cs +++ b/src/Logger.cs @@ -1,69 +1,69 @@ -using System; +using System; using RefreshCS; namespace MoonWorks { - public static class Logger - { - public static Action LogInfo; - public static Action LogWarn; - public static Action LogError; + public static class Logger + { + public static Action LogInfo; + public static Action LogWarn; + public static Action LogError; - private static RefreshCS.Refresh.Refresh_LogFunc LogInfoFunc = RefreshLogInfo; - private static RefreshCS.Refresh.Refresh_LogFunc LogWarnFunc = RefreshLogWarn; - private static RefreshCS.Refresh.Refresh_LogFunc LogErrorFunc = RefreshLogError; + private static RefreshCS.Refresh.Refresh_LogFunc LogInfoFunc = RefreshLogInfo; + private static RefreshCS.Refresh.Refresh_LogFunc LogWarnFunc = RefreshLogWarn; + private static RefreshCS.Refresh.Refresh_LogFunc LogErrorFunc = RefreshLogError; - internal static void Initialize() - { - if (Logger.LogInfo == null) - { - Logger.LogInfo = Console.WriteLine; - } - if (Logger.LogWarn == null) - { - Logger.LogWarn = Console.WriteLine; - } - if (Logger.LogError == null) - { - Logger.LogError = Console.WriteLine; - } + internal static void Initialize() + { + if (Logger.LogInfo == null) + { + Logger.LogInfo = Console.WriteLine; + } + if (Logger.LogWarn == null) + { + Logger.LogWarn = Console.WriteLine; + } + if (Logger.LogError == null) + { + Logger.LogError = Console.WriteLine; + } - Refresh.Refresh_HookLogFunctions( - LogInfoFunc, - LogWarnFunc, - LogErrorFunc - ); - } + Refresh.Refresh_HookLogFunctions( + LogInfoFunc, + LogWarnFunc, + LogErrorFunc + ); + } - private static void RefreshLogInfo(IntPtr msg) - { - LogInfo(UTF8_ToManaged(msg)); - } + private static void RefreshLogInfo(IntPtr msg) + { + LogInfo(UTF8_ToManaged(msg)); + } - private static void RefreshLogWarn(IntPtr msg) - { - LogWarn(UTF8_ToManaged(msg)); - } + private static void RefreshLogWarn(IntPtr msg) + { + LogWarn(UTF8_ToManaged(msg)); + } - private static void RefreshLogError(IntPtr msg) - { - LogError(UTF8_ToManaged(msg)); - } + private static void RefreshLogError(IntPtr msg) + { + LogError(UTF8_ToManaged(msg)); + } - private unsafe static string UTF8_ToManaged(IntPtr s) - { - byte* ptr = (byte*) s; - while (*ptr != 0) - { - ptr += 1; - } + private unsafe static string UTF8_ToManaged(IntPtr s) + { + byte* ptr = (byte*) s; + while (*ptr != 0) + { + ptr += 1; + } - string result = System.Text.Encoding.UTF8.GetString( - (byte*) s, - (int) (ptr - (byte*) s) - ); + string result = System.Text.Encoding.UTF8.GetString( + (byte*) s, + (int) (ptr - (byte*) s) + ); - return result; - } - } + return result; + } + } } diff --git a/src/Math/BoundingBox.cs b/src/Math/BoundingBox.cs index c55c51dc..13e7c172 100644 --- a/src/Math/BoundingBox.cs +++ b/src/Math/BoundingBox.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -91,23 +91,23 @@ namespace MoonWorks.Math public ContainmentType Contains(BoundingBox box) { // Test if all corner is in the same side of a face by just checking min and max - if ( box.Max.X < Min.X || + if (box.Max.X < Min.X || box.Min.X > Max.X || box.Max.Y < Min.Y || box.Min.Y > Max.Y || box.Max.Z < Min.Z || - box.Min.Z > Max.Z ) + box.Min.Z > Max.Z) { return ContainmentType.Disjoint; } - if ( box.Min.X >= Min.X && + if (box.Min.X >= Min.X && box.Max.X <= Max.X && box.Min.Y >= Min.Y && box.Max.Y <= Max.Y && box.Min.Z >= Min.Z && - box.Max.Z <= Max.Z ) + box.Max.Z <= Max.Z) { return ContainmentType.Contains; } @@ -172,12 +172,12 @@ namespace MoonWorks.Math public ContainmentType Contains(BoundingSphere sphere) { - if ( sphere.Center.X - Min.X >= sphere.Radius && + if (sphere.Center.X - Min.X >= sphere.Radius && sphere.Center.Y - Min.Y >= sphere.Radius && sphere.Center.Z - Min.Z >= sphere.Radius && Max.X - sphere.Center.X >= sphere.Radius && Max.Y - sphere.Center.Y >= sphere.Radius && - Max.Z - sphere.Center.Z >= sphere.Radius ) + Max.Z - sphere.Center.Z >= sphere.Radius) { return ContainmentType.Contains; } @@ -261,12 +261,12 @@ namespace MoonWorks.Math public void Contains(ref Vector3 point, out ContainmentType result) { // Determine if point is outside of this box. - if ( point.X < this.Min.X || + if (point.X < this.Min.X || point.X > this.Max.X || point.Y < this.Min.Y || point.Y > this.Max.Y || point.Z < this.Min.Z || - point.Z > this.Max.Z ) + point.Z > this.Max.Z) { result = ContainmentType.Disjoint; } @@ -380,12 +380,12 @@ namespace MoonWorks.Math public bool Intersects(BoundingSphere sphere) { - if ( sphere.Center.X - Min.X > sphere.Radius && + if (sphere.Center.X - Min.X > sphere.Radius && sphere.Center.Y - Min.Y > sphere.Radius && sphere.Center.Z - Min.Z > sphere.Radius && Max.X - sphere.Center.X > sphere.Radius && Max.Y - sphere.Center.Y > sphere.Radius && - Max.Z - sphere.Center.Z > sphere.Radius ) + Max.Z - sphere.Center.Z > sphere.Radius) { return true; } diff --git a/src/Math/BoundingFrustum.cs b/src/Math/BoundingFrustum.cs index 7e40b888..133a3eb3 100644 --- a/src/Math/BoundingFrustum.cs +++ b/src/Math/BoundingFrustum.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -230,12 +230,12 @@ namespace MoonWorks.Math box.Intersects(ref this.planes[i], out planeIntersectionType); switch (planeIntersectionType) { - case PlaneIntersectionType.Front: - result = ContainmentType.Disjoint; - return; - case PlaneIntersectionType.Intersecting: - intersects = true; - break; + case PlaneIntersectionType.Front: + result = ContainmentType.Disjoint; + return; + case PlaneIntersectionType.Intersecting: + intersects = true; + break; } } result = intersects ? ContainmentType.Intersects : ContainmentType.Contains; @@ -269,12 +269,12 @@ namespace MoonWorks.Math sphere.Intersects(ref this.planes[i], out planeIntersectionType); switch (planeIntersectionType) { - case PlaneIntersectionType.Front: - result = ContainmentType.Disjoint; - return; - case PlaneIntersectionType.Intersecting: - intersects = true; - break; + case PlaneIntersectionType.Front: + result = ContainmentType.Disjoint; + return; + case PlaneIntersectionType.Intersecting: + intersects = true; + break; } } result = intersects ? ContainmentType.Intersects : ContainmentType.Contains; @@ -597,7 +597,8 @@ namespace MoonWorks.Math ref Plane b, ref Plane c, out Vector3 result - ) { + ) + { /* Formula used * d1 ( N2 * N3 ) + d2 ( N3 * N1 ) + d3 ( N1 * N2 ) * P = ------------------------------------------------------------------- diff --git a/src/Math/BoundingSphere.cs b/src/Math/BoundingSphere.cs index d49db218..1b646d3c 100644 --- a/src/Math/BoundingSphere.cs +++ b/src/Math/BoundingSphere.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -297,8 +297,8 @@ namespace MoonWorks.Math /// true if the instances are equal; false otherwise. public bool Equals(BoundingSphere other) { - return ( Center == other.Center && - Radius == other.Radius ); + return (Center == other.Center && + Radius == other.Radius); } #endregion @@ -474,7 +474,8 @@ namespace MoonWorks.Math ref BoundingSphere original, ref BoundingSphere additional, out BoundingSphere result - ) { + ) + { Vector3 ocenterToaCenter = Vector3.Subtract(additional.Center, original.Center); float distance = ocenterToaCenter.Length(); diff --git a/src/Math/ContainmentType.cs b/src/Math/ContainmentType.cs index 081a4543..6a9b889b 100644 --- a/src/Math/ContainmentType.cs +++ b/src/Math/ContainmentType.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Math/MathHelper.cs b/src/Math/MathHelper.cs index a1414d0e..b98ef4c3 100644 --- a/src/Math/MathHelper.cs +++ b/src/Math/MathHelper.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -98,7 +98,8 @@ namespace MoonWorks.Math float value3, float amount1, float amount2 - ) { + ) + { return value1 + (value2 - value1) * amount1 + (value3 - value1) * amount2; } @@ -117,7 +118,8 @@ namespace MoonWorks.Math float value3, float value4, float amount - ) { + ) + { /* Using formula from http://www.mvps.org/directx/articles/catmull/ * Internally using doubles not to lose precision. */ @@ -184,7 +186,8 @@ namespace MoonWorks.Math float value2, float tangent2, float amount - ) { + ) + { /* All transformed to double not to lose precision * Otherwise, for high numbers of param:amount the result is NaN instead * of Infinity. diff --git a/src/Math/Matrix3x2.cs b/src/Math/Matrix3x2.cs index b7e082d9..a6344270 100644 --- a/src/Math/Matrix3x2.cs +++ b/src/Math/Matrix3x2.cs @@ -1,4 +1,4 @@ -/* MoonWorks - Game Development Framework +/* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley */ @@ -12,815 +12,815 @@ using System.Globalization; namespace MoonWorks.Math { - /// - /// A structure encapsulating a 3x2 matrix. - /// - public struct Matrix3x2 : IEquatable - { - #region Public Fields - /// - /// The first element of the first row - /// - public float M11; - /// - /// The second element of the first row - /// - public float M12; - /// - /// The first element of the second row - /// - public float M21; - /// - /// The second element of the second row - /// - public float M22; - /// - /// The first element of the third row - /// - public float M31; - /// - /// The second element of the third row - /// - public float M32; - #endregion Public Fields - - private static readonly Matrix3x2 _identity = new Matrix3x2 - ( - 1f, 0f, - 0f, 1f, - 0f, 0f - ); - - /// - /// Returns the multiplicative identity matrix. - /// - public static Matrix3x2 Identity - { - get { return _identity; } - } - - /// - /// Returns whether the matrix is the identity matrix. - /// - public bool IsIdentity - { - get - { - return M11 == 1f && M22 == 1f && // Check diagonal element first for early out. - M12 == 0f && - M21 == 0f && - M31 == 0f && M32 == 0f; - } - } - - /// - /// Gets or sets the translation component of this matrix. - /// - public Vector2 Translation - { - get - { - return new Vector2(M31, M32); - } - - set - { - M31 = value.X; - M32 = value.Y; - } - } - - /// - /// Constructs a Matrix3x2 from the given components. - /// - public Matrix3x2(float m11, float m12, - float m21, float m22, - float m31, float m32) - { - this.M11 = m11; - this.M12 = m12; - this.M21 = m21; - this.M22 = m22; - this.M31 = m31; - this.M32 = m32; - } - - /// - /// Creates a translation matrix from the given vector. - /// - /// The translation position. - /// A translation matrix. - public static Matrix3x2 CreateTranslation(Vector2 position) - { - Matrix3x2 result; - - result.M11 = 1.0f; - result.M12 = 0.0f; - result.M21 = 0.0f; - result.M22 = 1.0f; - - result.M31 = position.X; - result.M32 = position.Y; - - return result; - } - - /// - /// Creates a translation matrix from the given X and Y components. - /// - /// The X position. - /// The Y position. - /// A translation matrix. - public static Matrix3x2 CreateTranslation(float xPosition, float yPosition) - { - Matrix3x2 result; - - result.M11 = 1.0f; - result.M12 = 0.0f; - result.M21 = 0.0f; - result.M22 = 1.0f; - - result.M31 = xPosition; - result.M32 = yPosition; - - return result; - } - - /// - /// Creates a scale matrix from the given X and Y components. - /// - /// Value to scale by on the X-axis. - /// Value to scale by on the Y-axis. - /// A scaling matrix. - public static Matrix3x2 CreateScale(float xScale, float yScale) - { - Matrix3x2 result; - - result.M11 = xScale; - result.M12 = 0.0f; - result.M21 = 0.0f; - result.M22 = yScale; - result.M31 = 0.0f; - result.M32 = 0.0f; - - return result; - } - - /// - /// Creates a scale matrix that is offset by a given center point. - /// - /// Value to scale by on the X-axis. - /// Value to scale by on the Y-axis. - /// The center point. - /// A scaling matrix. - public static Matrix3x2 CreateScale(float xScale, float yScale, Vector2 centerPoint) - { - Matrix3x2 result; - - float tx = centerPoint.X * (1 - xScale); - float ty = centerPoint.Y * (1 - yScale); - - result.M11 = xScale; - result.M12 = 0.0f; - result.M21 = 0.0f; - result.M22 = yScale; - result.M31 = tx; - result.M32 = ty; - - return result; - } - - /// - /// Creates a scale matrix from the given vector scale. - /// - /// The scale to use. - /// A scaling matrix. - public static Matrix3x2 CreateScale(Vector2 scales) - { - Matrix3x2 result; - - result.M11 = scales.X; - result.M12 = 0.0f; - result.M21 = 0.0f; - result.M22 = scales.Y; - result.M31 = 0.0f; - result.M32 = 0.0f; - - return result; - } - - /// - /// Creates a scale matrix from the given vector scale with an offset from the given center point. - /// - /// The scale to use. - /// The center offset. - /// A scaling matrix. - public static Matrix3x2 CreateScale(Vector2 scales, Vector2 centerPoint) - { - Matrix3x2 result; - - float tx = centerPoint.X * (1 - scales.X); - float ty = centerPoint.Y * (1 - scales.Y); - - result.M11 = scales.X; - result.M12 = 0.0f; - result.M21 = 0.0f; - result.M22 = scales.Y; - result.M31 = tx; - result.M32 = ty; - - return result; - } - - /// - /// Creates a scale matrix that scales uniformly with the given scale. - /// - /// The uniform scale to use. - /// A scaling matrix. - public static Matrix3x2 CreateScale(float scale) - { - Matrix3x2 result; - - result.M11 = scale; - result.M12 = 0.0f; - result.M21 = 0.0f; - result.M22 = scale; - result.M31 = 0.0f; - result.M32 = 0.0f; - - return result; - } - - /// - /// Creates a scale matrix that scales uniformly with the given scale with an offset from the given center. - /// - /// The uniform scale to use. - /// The center offset. - /// A scaling matrix. - public static Matrix3x2 CreateScale(float scale, Vector2 centerPoint) - { - Matrix3x2 result; - - float tx = centerPoint.X * (1 - scale); - float ty = centerPoint.Y * (1 - scale); - - result.M11 = scale; - result.M12 = 0.0f; - result.M21 = 0.0f; - result.M22 = scale; - result.M31 = tx; - result.M32 = ty; - - return result; - } - - /// - /// Creates a skew matrix from the given angles in radians. - /// - /// The X angle, in radians. - /// The Y angle, in radians. - /// A skew matrix. - public static Matrix3x2 CreateSkew(float radiansX, float radiansY) - { - Matrix3x2 result; - - float xTan = (float)System.Math.Tan(radiansX); - float yTan = (float)System.Math.Tan(radiansY); - - result.M11 = 1.0f; - result.M12 = yTan; - result.M21 = xTan; - result.M22 = 1.0f; - result.M31 = 0.0f; - result.M32 = 0.0f; - - return result; - } - - /// - /// Creates a skew matrix from the given angles in radians and a center point. - /// - /// The X angle, in radians. - /// The Y angle, in radians. - /// The center point. - /// A skew matrix. - public static Matrix3x2 CreateSkew(float radiansX, float radiansY, Vector2 centerPoint) - { - Matrix3x2 result; - - float xTan = (float)System.Math.Tan(radiansX); - float yTan = (float)System.Math.Tan(radiansY); - - float tx = -centerPoint.Y * xTan; - float ty = -centerPoint.X * yTan; - - result.M11 = 1.0f; - result.M12 = yTan; - result.M21 = xTan; - result.M22 = 1.0f; - result.M31 = tx; - result.M32 = ty; - - return result; - } - - /// - /// Creates a rotation matrix using the given rotation in radians. - /// - /// The amount of rotation, in radians. - /// A rotation matrix. - public static Matrix3x2 CreateRotation(float radians) - { - Matrix3x2 result; - - radians = (float)System.Math.IEEERemainder(radians, System.Math.PI * 2); - - float c, s; - - const float epsilon = 0.001f * (float)System.Math.PI / 180f; // 0.1% of a degree - - if (radians > -epsilon && radians < epsilon) - { - // Exact case for zero rotation. - c = 1; - s = 0; - } - else if (radians > System.Math.PI / 2 - epsilon && radians < System.Math.PI / 2 + epsilon) - { - // Exact case for 90 degree rotation. - c = 0; - s = 1; - } - else if (radians < -System.Math.PI + epsilon || radians > System.Math.PI - epsilon) - { - // Exact case for 180 degree rotation. - c = -1; - s = 0; - } - else if (radians > -System.Math.PI / 2 - epsilon && radians < -System.Math.PI / 2 + epsilon) - { - // Exact case for 270 degree rotation. - c = 0; - s = -1; - } - else - { - // Arbitrary rotation. - c = (float)System.Math.Cos(radians); - s = (float)System.Math.Sin(radians); - } - - // [ c s ] - // [ -s c ] - // [ 0 0 ] - result.M11 = c; - result.M12 = s; - result.M21 = -s; - result.M22 = c; - result.M31 = 0.0f; - result.M32 = 0.0f; - - return result; - } - - /// - /// Creates a rotation matrix using the given rotation in radians and a center point. - /// - /// The amount of rotation, in radians. - /// The center point. - /// A rotation matrix. - public static Matrix3x2 CreateRotation(float radians, Vector2 centerPoint) - { - Matrix3x2 result; - - radians = (float)System.Math.IEEERemainder(radians, System.Math.PI * 2); - - float c, s; - - const float epsilon = 0.001f * (float)System.Math.PI / 180f; // 0.1% of a degree - - if (radians > -epsilon && radians < epsilon) - { - // Exact case for zero rotation. - c = 1; - s = 0; - } - else if (radians > System.Math.PI / 2 - epsilon && radians < System.Math.PI / 2 + epsilon) - { - // Exact case for 90 degree rotation. - c = 0; - s = 1; - } - else if (radians < -System.Math.PI + epsilon || radians > System.Math.PI - epsilon) - { - // Exact case for 180 degree rotation. - c = -1; - s = 0; - } - else if (radians > -System.Math.PI / 2 - epsilon && radians < -System.Math.PI / 2 + epsilon) - { - // Exact case for 270 degree rotation. - c = 0; - s = -1; - } - else - { - // Arbitrary rotation. - c = (float)System.Math.Cos(radians); - s = (float)System.Math.Sin(radians); - } - - float x = centerPoint.X * (1 - c) + centerPoint.Y * s; - float y = centerPoint.Y * (1 - c) - centerPoint.X * s; - - // [ c s ] - // [ -s c ] - // [ x y ] - result.M11 = c; - result.M12 = s; - result.M21 = -s; - result.M22 = c; - result.M31 = x; - result.M32 = y; - - return result; - } - - /// - /// Calculates the determinant for this matrix. - /// The determinant is calculated by expanding the matrix with a third column whose values are (0,0,1). - /// - /// The determinant. - public float GetDeterminant() - { - // There isn't actually any such thing as a determinant for a non-square matrix, - // but this 3x2 type is really just an optimization of a 3x3 where we happen to - // know the rightmost column is always (0, 0, 1). So we expand to 3x3 format: - // - // [ M11, M12, 0 ] - // [ M21, M22, 0 ] - // [ M31, M32, 1 ] - // - // Sum the diagonal products: - // (M11 * M22 * 1) + (M12 * 0 * M31) + (0 * M21 * M32) - // - // Subtract the opposite diagonal products: - // (M31 * M22 * 0) + (M32 * 0 * M11) + (1 * M21 * M12) - // - // Collapse out the constants and oh look, this is just a 2x2 determinant! - - return (M11 * M22) - (M21 * M12); - } - - /// - /// Attempts to invert the given matrix. If the operation succeeds, the inverted matrix is stored in the result parameter. - /// - /// The source matrix. - /// The output matrix. - /// True if the operation succeeded, False otherwise. - public static bool Invert(Matrix3x2 matrix, out Matrix3x2 result) - { - float det = (matrix.M11 * matrix.M22) - (matrix.M21 * matrix.M12); - - if (System.Math.Abs(det) < float.Epsilon) - { - result = new Matrix3x2(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN); - return false; - } - - float invDet = 1.0f / det; - - result.M11 = matrix.M22 * invDet; - result.M12 = -matrix.M12 * invDet; - result.M21 = -matrix.M21 * invDet; - result.M22 = matrix.M11 * invDet; - result.M31 = (matrix.M21 * matrix.M32 - matrix.M31 * matrix.M22) * invDet; - result.M32 = (matrix.M31 * matrix.M12 - matrix.M11 * matrix.M32) * invDet; - - return true; - } - - /// - /// Linearly interpolates from matrix1 to matrix2, based on the third parameter. - /// - /// The first source matrix. - /// The second source matrix. - /// The relative weighting of matrix2. - /// The interpolated matrix. - public static Matrix3x2 Lerp(Matrix3x2 matrix1, Matrix3x2 matrix2, float amount) - { - Matrix3x2 result; - - // First row - result.M11 = matrix1.M11 + (matrix2.M11 - matrix1.M11) * amount; - result.M12 = matrix1.M12 + (matrix2.M12 - matrix1.M12) * amount; - - // Second row - result.M21 = matrix1.M21 + (matrix2.M21 - matrix1.M21) * amount; - result.M22 = matrix1.M22 + (matrix2.M22 - matrix1.M22) * amount; - - // Third row - result.M31 = matrix1.M31 + (matrix2.M31 - matrix1.M31) * amount; - result.M32 = matrix1.M32 + (matrix2.M32 - matrix1.M32) * amount; - - return result; - } - - /// - /// Negates the given matrix by multiplying all values by -1. - /// - /// The source matrix. - /// The negated matrix. - public static Matrix3x2 Negate(Matrix3x2 value) - { - Matrix3x2 result; - - result.M11 = -value.M11; - result.M12 = -value.M12; - result.M21 = -value.M21; - result.M22 = -value.M22; - result.M31 = -value.M31; - result.M32 = -value.M32; - - return result; - } - - /// - /// Adds each matrix element in value1 with its corresponding element in value2. - /// - /// The first source matrix. - /// The second source matrix. - /// The matrix containing the summed values. - public static Matrix3x2 Add(Matrix3x2 value1, Matrix3x2 value2) - { - Matrix3x2 result; - - result.M11 = value1.M11 + value2.M11; - result.M12 = value1.M12 + value2.M12; - result.M21 = value1.M21 + value2.M21; - result.M22 = value1.M22 + value2.M22; - result.M31 = value1.M31 + value2.M31; - result.M32 = value1.M32 + value2.M32; - - return result; - } - - /// - /// Subtracts each matrix element in value2 from its corresponding element in value1. - /// - /// The first source matrix. - /// The second source matrix. - /// The matrix containing the resulting values. - public static Matrix3x2 Subtract(Matrix3x2 value1, Matrix3x2 value2) - { - Matrix3x2 result; - - result.M11 = value1.M11 - value2.M11; - result.M12 = value1.M12 - value2.M12; - result.M21 = value1.M21 - value2.M21; - result.M22 = value1.M22 - value2.M22; - result.M31 = value1.M31 - value2.M31; - result.M32 = value1.M32 - value2.M32; - - return result; - } - - /// - /// Multiplies two matrices together and returns the resulting matrix. - /// - /// The first source matrix. - /// The second source matrix. - /// The product matrix. - public static Matrix3x2 Multiply(Matrix3x2 value1, Matrix3x2 value2) - { - Matrix3x2 result; - - // First row - result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21; - result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22; - - // Second row - result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21; - result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22; - - // Third row - result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31; - result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32; - - return result; - } - - public Matrix4x4 ToMatrix4x4() - { - return new Matrix4x4( - M11, M12, 0, 0, - M21, M22, 0, 0, - 0, 0, 1, 0, - M31, M32, 0, 1 - ); - } - - /// - /// Scales all elements in a matrix by the given scalar factor. - /// - /// The source matrix. - /// The scaling value to use. - /// The resulting matrix. - public static Matrix3x2 Multiply(Matrix3x2 value1, float value2) - { - Matrix3x2 result; - - result.M11 = value1.M11 * value2; - result.M12 = value1.M12 * value2; - result.M21 = value1.M21 * value2; - result.M22 = value1.M22 * value2; - result.M31 = value1.M31 * value2; - result.M32 = value1.M32 * value2; - - return result; - } - - /// - /// Negates the given matrix by multiplying all values by -1. - /// - /// The source matrix. - /// The negated matrix. - public static Matrix3x2 operator -(Matrix3x2 value) - { - Matrix3x2 m; - - m.M11 = -value.M11; - m.M12 = -value.M12; - m.M21 = -value.M21; - m.M22 = -value.M22; - m.M31 = -value.M31; - m.M32 = -value.M32; - - return m; - } - - /// - /// Adds each matrix element in value1 with its corresponding element in value2. - /// - /// The first source matrix. - /// The second source matrix. - /// The matrix containing the summed values. - public static Matrix3x2 operator +(Matrix3x2 value1, Matrix3x2 value2) - { - Matrix3x2 m; - - m.M11 = value1.M11 + value2.M11; - m.M12 = value1.M12 + value2.M12; - m.M21 = value1.M21 + value2.M21; - m.M22 = value1.M22 + value2.M22; - m.M31 = value1.M31 + value2.M31; - m.M32 = value1.M32 + value2.M32; - - return m; - } - - /// - /// Subtracts each matrix element in value2 from its corresponding element in value1. - /// - /// The first source matrix. - /// The second source matrix. - /// The matrix containing the resulting values. - public static Matrix3x2 operator -(Matrix3x2 value1, Matrix3x2 value2) - { - Matrix3x2 m; - - m.M11 = value1.M11 - value2.M11; - m.M12 = value1.M12 - value2.M12; - m.M21 = value1.M21 - value2.M21; - m.M22 = value1.M22 - value2.M22; - m.M31 = value1.M31 - value2.M31; - m.M32 = value1.M32 - value2.M32; - - return m; - } - - /// - /// Multiplies two matrices together and returns the resulting matrix. - /// - /// The first source matrix. - /// The second source matrix. - /// The product matrix. - public static Matrix3x2 operator *(Matrix3x2 value1, Matrix3x2 value2) - { - Matrix3x2 m; - - // First row - m.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21; - m.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22; - - // Second row - m.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21; - m.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22; - - // Third row - m.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31; - m.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32; - - return m; - } - - /// - /// Scales all elements in a matrix by the given scalar factor. - /// - /// The source matrix. - /// The scaling value to use. - /// The resulting matrix. - public static Matrix3x2 operator *(Matrix3x2 value1, float value2) - { - Matrix3x2 m; - - m.M11 = value1.M11 * value2; - m.M12 = value1.M12 * value2; - m.M21 = value1.M21 * value2; - m.M22 = value1.M22 * value2; - m.M31 = value1.M31 * value2; - m.M32 = value1.M32 * value2; - - return m; - } - - /// - /// Returns a boolean indicating whether the given matrices are equal. - /// - /// The first source matrix. - /// The second source matrix. - /// True if the matrices are equal; False otherwise. - public static bool operator ==(Matrix3x2 value1, Matrix3x2 value2) - { - return (value1.M11 == value2.M11 && value1.M22 == value2.M22 && // Check diagonal element first for early out. - value1.M12 == value2.M12 && - value1.M21 == value2.M21 && - value1.M31 == value2.M31 && value1.M32 == value2.M32); - } - - /// - /// Returns a boolean indicating whether the given matrices are not equal. - /// - /// The first source matrix. - /// The second source matrix. - /// True if the matrices are not equal; False if they are equal. - public static bool operator !=(Matrix3x2 value1, Matrix3x2 value2) - { - return (value1.M11 != value2.M11 || value1.M12 != value2.M12 || - value1.M21 != value2.M21 || value1.M22 != value2.M22 || - value1.M31 != value2.M31 || value1.M32 != value2.M32); - } - - /// - /// Returns a boolean indicating whether the matrix is equal to the other given matrix. - /// - /// The other matrix to test equality against. - /// True if this matrix is equal to other; False otherwise. - public bool Equals(Matrix3x2 other) - { - return (M11 == other.M11 && M22 == other.M22 && // Check diagonal element first for early out. - M12 == other.M12 && - M21 == other.M21 && - M31 == other.M31 && M32 == other.M32); - } - - /// - /// Returns a boolean indicating whether the given Object is equal to this matrix instance. - /// - /// The Object to compare against. - /// True if the Object is equal to this matrix; False otherwise. - public override bool Equals(object obj) - { - if (obj is Matrix3x2) - { - return Equals((Matrix3x2)obj); - } - - return false; - } - - /// - /// Returns a String representing this matrix instance. - /// - /// The string representation. - public override string ToString() - { - CultureInfo ci = CultureInfo.CurrentCulture; - return String.Format(ci, "{{ {{M11:{0} M12:{1}}} {{M21:{2} M22:{3}}} {{M31:{4} M32:{5}}} }}", - M11.ToString(ci), M12.ToString(ci), - M21.ToString(ci), M22.ToString(ci), - M31.ToString(ci), M32.ToString(ci)); - } - - /// - /// Returns the hash code for this instance. - /// - /// The hash code. - public override int GetHashCode() - { - return M11.GetHashCode() + M12.GetHashCode() + - M21.GetHashCode() + M22.GetHashCode() + - M31.GetHashCode() + M32.GetHashCode(); - } - } + /// + /// A structure encapsulating a 3x2 matrix. + /// + public struct Matrix3x2 : IEquatable + { + #region Public Fields + /// + /// The first element of the first row + /// + public float M11; + /// + /// The second element of the first row + /// + public float M12; + /// + /// The first element of the second row + /// + public float M21; + /// + /// The second element of the second row + /// + public float M22; + /// + /// The first element of the third row + /// + public float M31; + /// + /// The second element of the third row + /// + public float M32; + #endregion Public Fields + + private static readonly Matrix3x2 _identity = new Matrix3x2 + ( + 1f, 0f, + 0f, 1f, + 0f, 0f + ); + + /// + /// Returns the multiplicative identity matrix. + /// + public static Matrix3x2 Identity + { + get { return _identity; } + } + + /// + /// Returns whether the matrix is the identity matrix. + /// + public bool IsIdentity + { + get + { + return M11 == 1f && M22 == 1f && // Check diagonal element first for early out. + M12 == 0f && + M21 == 0f && + M31 == 0f && M32 == 0f; + } + } + + /// + /// Gets or sets the translation component of this matrix. + /// + public Vector2 Translation + { + get + { + return new Vector2(M31, M32); + } + + set + { + M31 = value.X; + M32 = value.Y; + } + } + + /// + /// Constructs a Matrix3x2 from the given components. + /// + public Matrix3x2(float m11, float m12, + float m21, float m22, + float m31, float m32) + { + this.M11 = m11; + this.M12 = m12; + this.M21 = m21; + this.M22 = m22; + this.M31 = m31; + this.M32 = m32; + } + + /// + /// Creates a translation matrix from the given vector. + /// + /// The translation position. + /// A translation matrix. + public static Matrix3x2 CreateTranslation(Vector2 position) + { + Matrix3x2 result; + + result.M11 = 1.0f; + result.M12 = 0.0f; + result.M21 = 0.0f; + result.M22 = 1.0f; + + result.M31 = position.X; + result.M32 = position.Y; + + return result; + } + + /// + /// Creates a translation matrix from the given X and Y components. + /// + /// The X position. + /// The Y position. + /// A translation matrix. + public static Matrix3x2 CreateTranslation(float xPosition, float yPosition) + { + Matrix3x2 result; + + result.M11 = 1.0f; + result.M12 = 0.0f; + result.M21 = 0.0f; + result.M22 = 1.0f; + + result.M31 = xPosition; + result.M32 = yPosition; + + return result; + } + + /// + /// Creates a scale matrix from the given X and Y components. + /// + /// Value to scale by on the X-axis. + /// Value to scale by on the Y-axis. + /// A scaling matrix. + public static Matrix3x2 CreateScale(float xScale, float yScale) + { + Matrix3x2 result; + + result.M11 = xScale; + result.M12 = 0.0f; + result.M21 = 0.0f; + result.M22 = yScale; + result.M31 = 0.0f; + result.M32 = 0.0f; + + return result; + } + + /// + /// Creates a scale matrix that is offset by a given center point. + /// + /// Value to scale by on the X-axis. + /// Value to scale by on the Y-axis. + /// The center point. + /// A scaling matrix. + public static Matrix3x2 CreateScale(float xScale, float yScale, Vector2 centerPoint) + { + Matrix3x2 result; + + float tx = centerPoint.X * (1 - xScale); + float ty = centerPoint.Y * (1 - yScale); + + result.M11 = xScale; + result.M12 = 0.0f; + result.M21 = 0.0f; + result.M22 = yScale; + result.M31 = tx; + result.M32 = ty; + + return result; + } + + /// + /// Creates a scale matrix from the given vector scale. + /// + /// The scale to use. + /// A scaling matrix. + public static Matrix3x2 CreateScale(Vector2 scales) + { + Matrix3x2 result; + + result.M11 = scales.X; + result.M12 = 0.0f; + result.M21 = 0.0f; + result.M22 = scales.Y; + result.M31 = 0.0f; + result.M32 = 0.0f; + + return result; + } + + /// + /// Creates a scale matrix from the given vector scale with an offset from the given center point. + /// + /// The scale to use. + /// The center offset. + /// A scaling matrix. + public static Matrix3x2 CreateScale(Vector2 scales, Vector2 centerPoint) + { + Matrix3x2 result; + + float tx = centerPoint.X * (1 - scales.X); + float ty = centerPoint.Y * (1 - scales.Y); + + result.M11 = scales.X; + result.M12 = 0.0f; + result.M21 = 0.0f; + result.M22 = scales.Y; + result.M31 = tx; + result.M32 = ty; + + return result; + } + + /// + /// Creates a scale matrix that scales uniformly with the given scale. + /// + /// The uniform scale to use. + /// A scaling matrix. + public static Matrix3x2 CreateScale(float scale) + { + Matrix3x2 result; + + result.M11 = scale; + result.M12 = 0.0f; + result.M21 = 0.0f; + result.M22 = scale; + result.M31 = 0.0f; + result.M32 = 0.0f; + + return result; + } + + /// + /// Creates a scale matrix that scales uniformly with the given scale with an offset from the given center. + /// + /// The uniform scale to use. + /// The center offset. + /// A scaling matrix. + public static Matrix3x2 CreateScale(float scale, Vector2 centerPoint) + { + Matrix3x2 result; + + float tx = centerPoint.X * (1 - scale); + float ty = centerPoint.Y * (1 - scale); + + result.M11 = scale; + result.M12 = 0.0f; + result.M21 = 0.0f; + result.M22 = scale; + result.M31 = tx; + result.M32 = ty; + + return result; + } + + /// + /// Creates a skew matrix from the given angles in radians. + /// + /// The X angle, in radians. + /// The Y angle, in radians. + /// A skew matrix. + public static Matrix3x2 CreateSkew(float radiansX, float radiansY) + { + Matrix3x2 result; + + float xTan = (float) System.Math.Tan(radiansX); + float yTan = (float) System.Math.Tan(radiansY); + + result.M11 = 1.0f; + result.M12 = yTan; + result.M21 = xTan; + result.M22 = 1.0f; + result.M31 = 0.0f; + result.M32 = 0.0f; + + return result; + } + + /// + /// Creates a skew matrix from the given angles in radians and a center point. + /// + /// The X angle, in radians. + /// The Y angle, in radians. + /// The center point. + /// A skew matrix. + public static Matrix3x2 CreateSkew(float radiansX, float radiansY, Vector2 centerPoint) + { + Matrix3x2 result; + + float xTan = (float) System.Math.Tan(radiansX); + float yTan = (float) System.Math.Tan(radiansY); + + float tx = -centerPoint.Y * xTan; + float ty = -centerPoint.X * yTan; + + result.M11 = 1.0f; + result.M12 = yTan; + result.M21 = xTan; + result.M22 = 1.0f; + result.M31 = tx; + result.M32 = ty; + + return result; + } + + /// + /// Creates a rotation matrix using the given rotation in radians. + /// + /// The amount of rotation, in radians. + /// A rotation matrix. + public static Matrix3x2 CreateRotation(float radians) + { + Matrix3x2 result; + + radians = (float) System.Math.IEEERemainder(radians, System.Math.PI * 2); + + float c, s; + + const float epsilon = 0.001f * (float) System.Math.PI / 180f; // 0.1% of a degree + + if (radians > -epsilon && radians < epsilon) + { + // Exact case for zero rotation. + c = 1; + s = 0; + } + else if (radians > System.Math.PI / 2 - epsilon && radians < System.Math.PI / 2 + epsilon) + { + // Exact case for 90 degree rotation. + c = 0; + s = 1; + } + else if (radians < -System.Math.PI + epsilon || radians > System.Math.PI - epsilon) + { + // Exact case for 180 degree rotation. + c = -1; + s = 0; + } + else if (radians > -System.Math.PI / 2 - epsilon && radians < -System.Math.PI / 2 + epsilon) + { + // Exact case for 270 degree rotation. + c = 0; + s = -1; + } + else + { + // Arbitrary rotation. + c = (float) System.Math.Cos(radians); + s = (float) System.Math.Sin(radians); + } + + // [ c s ] + // [ -s c ] + // [ 0 0 ] + result.M11 = c; + result.M12 = s; + result.M21 = -s; + result.M22 = c; + result.M31 = 0.0f; + result.M32 = 0.0f; + + return result; + } + + /// + /// Creates a rotation matrix using the given rotation in radians and a center point. + /// + /// The amount of rotation, in radians. + /// The center point. + /// A rotation matrix. + public static Matrix3x2 CreateRotation(float radians, Vector2 centerPoint) + { + Matrix3x2 result; + + radians = (float) System.Math.IEEERemainder(radians, System.Math.PI * 2); + + float c, s; + + const float epsilon = 0.001f * (float) System.Math.PI / 180f; // 0.1% of a degree + + if (radians > -epsilon && radians < epsilon) + { + // Exact case for zero rotation. + c = 1; + s = 0; + } + else if (radians > System.Math.PI / 2 - epsilon && radians < System.Math.PI / 2 + epsilon) + { + // Exact case for 90 degree rotation. + c = 0; + s = 1; + } + else if (radians < -System.Math.PI + epsilon || radians > System.Math.PI - epsilon) + { + // Exact case for 180 degree rotation. + c = -1; + s = 0; + } + else if (radians > -System.Math.PI / 2 - epsilon && radians < -System.Math.PI / 2 + epsilon) + { + // Exact case for 270 degree rotation. + c = 0; + s = -1; + } + else + { + // Arbitrary rotation. + c = (float) System.Math.Cos(radians); + s = (float) System.Math.Sin(radians); + } + + float x = centerPoint.X * (1 - c) + centerPoint.Y * s; + float y = centerPoint.Y * (1 - c) - centerPoint.X * s; + + // [ c s ] + // [ -s c ] + // [ x y ] + result.M11 = c; + result.M12 = s; + result.M21 = -s; + result.M22 = c; + result.M31 = x; + result.M32 = y; + + return result; + } + + /// + /// Calculates the determinant for this matrix. + /// The determinant is calculated by expanding the matrix with a third column whose values are (0,0,1). + /// + /// The determinant. + public float GetDeterminant() + { + // There isn't actually any such thing as a determinant for a non-square matrix, + // but this 3x2 type is really just an optimization of a 3x3 where we happen to + // know the rightmost column is always (0, 0, 1). So we expand to 3x3 format: + // + // [ M11, M12, 0 ] + // [ M21, M22, 0 ] + // [ M31, M32, 1 ] + // + // Sum the diagonal products: + // (M11 * M22 * 1) + (M12 * 0 * M31) + (0 * M21 * M32) + // + // Subtract the opposite diagonal products: + // (M31 * M22 * 0) + (M32 * 0 * M11) + (1 * M21 * M12) + // + // Collapse out the constants and oh look, this is just a 2x2 determinant! + + return (M11 * M22) - (M21 * M12); + } + + /// + /// Attempts to invert the given matrix. If the operation succeeds, the inverted matrix is stored in the result parameter. + /// + /// The source matrix. + /// The output matrix. + /// True if the operation succeeded, False otherwise. + public static bool Invert(Matrix3x2 matrix, out Matrix3x2 result) + { + float det = (matrix.M11 * matrix.M22) - (matrix.M21 * matrix.M12); + + if (System.Math.Abs(det) < float.Epsilon) + { + result = new Matrix3x2(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN); + return false; + } + + float invDet = 1.0f / det; + + result.M11 = matrix.M22 * invDet; + result.M12 = -matrix.M12 * invDet; + result.M21 = -matrix.M21 * invDet; + result.M22 = matrix.M11 * invDet; + result.M31 = (matrix.M21 * matrix.M32 - matrix.M31 * matrix.M22) * invDet; + result.M32 = (matrix.M31 * matrix.M12 - matrix.M11 * matrix.M32) * invDet; + + return true; + } + + /// + /// Linearly interpolates from matrix1 to matrix2, based on the third parameter. + /// + /// The first source matrix. + /// The second source matrix. + /// The relative weighting of matrix2. + /// The interpolated matrix. + public static Matrix3x2 Lerp(Matrix3x2 matrix1, Matrix3x2 matrix2, float amount) + { + Matrix3x2 result; + + // First row + result.M11 = matrix1.M11 + (matrix2.M11 - matrix1.M11) * amount; + result.M12 = matrix1.M12 + (matrix2.M12 - matrix1.M12) * amount; + + // Second row + result.M21 = matrix1.M21 + (matrix2.M21 - matrix1.M21) * amount; + result.M22 = matrix1.M22 + (matrix2.M22 - matrix1.M22) * amount; + + // Third row + result.M31 = matrix1.M31 + (matrix2.M31 - matrix1.M31) * amount; + result.M32 = matrix1.M32 + (matrix2.M32 - matrix1.M32) * amount; + + return result; + } + + /// + /// Negates the given matrix by multiplying all values by -1. + /// + /// The source matrix. + /// The negated matrix. + public static Matrix3x2 Negate(Matrix3x2 value) + { + Matrix3x2 result; + + result.M11 = -value.M11; + result.M12 = -value.M12; + result.M21 = -value.M21; + result.M22 = -value.M22; + result.M31 = -value.M31; + result.M32 = -value.M32; + + return result; + } + + /// + /// Adds each matrix element in value1 with its corresponding element in value2. + /// + /// The first source matrix. + /// The second source matrix. + /// The matrix containing the summed values. + public static Matrix3x2 Add(Matrix3x2 value1, Matrix3x2 value2) + { + Matrix3x2 result; + + result.M11 = value1.M11 + value2.M11; + result.M12 = value1.M12 + value2.M12; + result.M21 = value1.M21 + value2.M21; + result.M22 = value1.M22 + value2.M22; + result.M31 = value1.M31 + value2.M31; + result.M32 = value1.M32 + value2.M32; + + return result; + } + + /// + /// Subtracts each matrix element in value2 from its corresponding element in value1. + /// + /// The first source matrix. + /// The second source matrix. + /// The matrix containing the resulting values. + public static Matrix3x2 Subtract(Matrix3x2 value1, Matrix3x2 value2) + { + Matrix3x2 result; + + result.M11 = value1.M11 - value2.M11; + result.M12 = value1.M12 - value2.M12; + result.M21 = value1.M21 - value2.M21; + result.M22 = value1.M22 - value2.M22; + result.M31 = value1.M31 - value2.M31; + result.M32 = value1.M32 - value2.M32; + + return result; + } + + /// + /// Multiplies two matrices together and returns the resulting matrix. + /// + /// The first source matrix. + /// The second source matrix. + /// The product matrix. + public static Matrix3x2 Multiply(Matrix3x2 value1, Matrix3x2 value2) + { + Matrix3x2 result; + + // First row + result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21; + result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22; + + // Second row + result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21; + result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22; + + // Third row + result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31; + result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32; + + return result; + } + + public Matrix4x4 ToMatrix4x4() + { + return new Matrix4x4( + M11, M12, 0, 0, + M21, M22, 0, 0, + 0, 0, 1, 0, + M31, M32, 0, 1 + ); + } + + /// + /// Scales all elements in a matrix by the given scalar factor. + /// + /// The source matrix. + /// The scaling value to use. + /// The resulting matrix. + public static Matrix3x2 Multiply(Matrix3x2 value1, float value2) + { + Matrix3x2 result; + + result.M11 = value1.M11 * value2; + result.M12 = value1.M12 * value2; + result.M21 = value1.M21 * value2; + result.M22 = value1.M22 * value2; + result.M31 = value1.M31 * value2; + result.M32 = value1.M32 * value2; + + return result; + } + + /// + /// Negates the given matrix by multiplying all values by -1. + /// + /// The source matrix. + /// The negated matrix. + public static Matrix3x2 operator -(Matrix3x2 value) + { + Matrix3x2 m; + + m.M11 = -value.M11; + m.M12 = -value.M12; + m.M21 = -value.M21; + m.M22 = -value.M22; + m.M31 = -value.M31; + m.M32 = -value.M32; + + return m; + } + + /// + /// Adds each matrix element in value1 with its corresponding element in value2. + /// + /// The first source matrix. + /// The second source matrix. + /// The matrix containing the summed values. + public static Matrix3x2 operator +(Matrix3x2 value1, Matrix3x2 value2) + { + Matrix3x2 m; + + m.M11 = value1.M11 + value2.M11; + m.M12 = value1.M12 + value2.M12; + m.M21 = value1.M21 + value2.M21; + m.M22 = value1.M22 + value2.M22; + m.M31 = value1.M31 + value2.M31; + m.M32 = value1.M32 + value2.M32; + + return m; + } + + /// + /// Subtracts each matrix element in value2 from its corresponding element in value1. + /// + /// The first source matrix. + /// The second source matrix. + /// The matrix containing the resulting values. + public static Matrix3x2 operator -(Matrix3x2 value1, Matrix3x2 value2) + { + Matrix3x2 m; + + m.M11 = value1.M11 - value2.M11; + m.M12 = value1.M12 - value2.M12; + m.M21 = value1.M21 - value2.M21; + m.M22 = value1.M22 - value2.M22; + m.M31 = value1.M31 - value2.M31; + m.M32 = value1.M32 - value2.M32; + + return m; + } + + /// + /// Multiplies two matrices together and returns the resulting matrix. + /// + /// The first source matrix. + /// The second source matrix. + /// The product matrix. + public static Matrix3x2 operator *(Matrix3x2 value1, Matrix3x2 value2) + { + Matrix3x2 m; + + // First row + m.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21; + m.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22; + + // Second row + m.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21; + m.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22; + + // Third row + m.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31; + m.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32; + + return m; + } + + /// + /// Scales all elements in a matrix by the given scalar factor. + /// + /// The source matrix. + /// The scaling value to use. + /// The resulting matrix. + public static Matrix3x2 operator *(Matrix3x2 value1, float value2) + { + Matrix3x2 m; + + m.M11 = value1.M11 * value2; + m.M12 = value1.M12 * value2; + m.M21 = value1.M21 * value2; + m.M22 = value1.M22 * value2; + m.M31 = value1.M31 * value2; + m.M32 = value1.M32 * value2; + + return m; + } + + /// + /// Returns a boolean indicating whether the given matrices are equal. + /// + /// The first source matrix. + /// The second source matrix. + /// True if the matrices are equal; False otherwise. + public static bool operator ==(Matrix3x2 value1, Matrix3x2 value2) + { + return (value1.M11 == value2.M11 && value1.M22 == value2.M22 && // Check diagonal element first for early out. + value1.M12 == value2.M12 && + value1.M21 == value2.M21 && + value1.M31 == value2.M31 && value1.M32 == value2.M32); + } + + /// + /// Returns a boolean indicating whether the given matrices are not equal. + /// + /// The first source matrix. + /// The second source matrix. + /// True if the matrices are not equal; False if they are equal. + public static bool operator !=(Matrix3x2 value1, Matrix3x2 value2) + { + return (value1.M11 != value2.M11 || value1.M12 != value2.M12 || + value1.M21 != value2.M21 || value1.M22 != value2.M22 || + value1.M31 != value2.M31 || value1.M32 != value2.M32); + } + + /// + /// Returns a boolean indicating whether the matrix is equal to the other given matrix. + /// + /// The other matrix to test equality against. + /// True if this matrix is equal to other; False otherwise. + public bool Equals(Matrix3x2 other) + { + return (M11 == other.M11 && M22 == other.M22 && // Check diagonal element first for early out. + M12 == other.M12 && + M21 == other.M21 && + M31 == other.M31 && M32 == other.M32); + } + + /// + /// Returns a boolean indicating whether the given Object is equal to this matrix instance. + /// + /// The Object to compare against. + /// True if the Object is equal to this matrix; False otherwise. + public override bool Equals(object obj) + { + if (obj is Matrix3x2) + { + return Equals((Matrix3x2) obj); + } + + return false; + } + + /// + /// Returns a String representing this matrix instance. + /// + /// The string representation. + public override string ToString() + { + CultureInfo ci = CultureInfo.CurrentCulture; + return String.Format(ci, "{{ {{M11:{0} M12:{1}}} {{M21:{2} M22:{3}}} {{M31:{4} M32:{5}}} }}", + M11.ToString(ci), M12.ToString(ci), + M21.ToString(ci), M22.ToString(ci), + M31.ToString(ci), M32.ToString(ci)); + } + + /// + /// Returns the hash code for this instance. + /// + /// The hash code. + public override int GetHashCode() + { + return M11.GetHashCode() + M12.GetHashCode() + + M21.GetHashCode() + M22.GetHashCode() + + M31.GetHashCode() + M32.GetHashCode(); + } + } } diff --git a/src/Math/Matrix4x4.cs b/src/Math/Matrix4x4.cs index 671882da..b2365207 100644 --- a/src/Math/Matrix4x4.cs +++ b/src/Math/Matrix4x4.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -316,7 +316,8 @@ namespace MoonWorks.Math float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44 - ) { + ) + { M11 = m11; M12 = m12; M13 = m13; @@ -350,7 +351,8 @@ namespace MoonWorks.Math out Vector3 scale, out Quaternion rotation, out Vector3 translation - ) { + ) + { translation.X = M41; translation.Y = M42; translation.Z = M43; @@ -363,9 +365,9 @@ namespace MoonWorks.Math scale.Y = ys * (float) System.Math.Sqrt(M21 * M21 + M22 * M22 + M23 * M23); scale.Z = zs * (float) System.Math.Sqrt(M31 * M31 + M32 * M32 + M33 * M33); - if ( MathHelper.WithinEpsilon(scale.X, 0.0f) || + if (MathHelper.WithinEpsilon(scale.X, 0.0f) || MathHelper.WithinEpsilon(scale.Y, 0.0f) || - MathHelper.WithinEpsilon(scale.Z, 0.0f) ) + MathHelper.WithinEpsilon(scale.Z, 0.0f)) { rotation = Quaternion.Identity; return false; @@ -413,7 +415,7 @@ namespace MoonWorks.Math /// true if the instances are equal; false otherwise. public bool Equals(Matrix4x4 other) { - return ( M11 == other.M11 && + return (M11 == other.M11 && M12 == other.M12 && M13 == other.M13 && M14 == other.M14 && @@ -428,7 +430,7 @@ namespace MoonWorks.Math M41 == other.M41 && M42 == other.M42 && M43 == other.M43 && - M44 == other.M44 ); + M44 == other.M44); } /// @@ -555,7 +557,8 @@ namespace MoonWorks.Math Vector3 cameraPosition, Vector3 cameraUpVector, Nullable cameraForwardVector - ) { + ) + { Matrix4x4 result; // Delegate to the other overload of the function to do the work @@ -584,7 +587,8 @@ namespace MoonWorks.Math ref Vector3 cameraUpVector, Vector3? cameraForwardVector, out Matrix4x4 result - ) { + ) + { Vector3 vector; Vector3 vector2; Vector3 vector3; @@ -642,7 +646,8 @@ namespace MoonWorks.Math Vector3 rotateAxis, Nullable cameraForwardVector, Nullable objectForwardVector - ) { + ) + { Matrix4x4 result; CreateConstrainedBillboard( ref objectPosition, @@ -671,7 +676,8 @@ namespace MoonWorks.Math Vector3? cameraForwardVector, Vector3? objectForwardVector, out Matrix4x4 result - ) { + ) + { float num; Vector3 vector; Vector3 vector2; @@ -777,7 +783,8 @@ namespace MoonWorks.Math ref Vector3 axis, float angle, out Matrix4x4 result - ) { + ) + { float x = axis.X; float y = axis.Y; float z = axis.Z; @@ -883,7 +890,8 @@ namespace MoonWorks.Math float pitch, float roll, out Matrix4x4 result - ) { + ) + { Quaternion quaternion; Quaternion.CreateFromYawPitchRoll(yaw, pitch, roll, out quaternion); CreateFromQuaternion(ref quaternion, out result); @@ -900,7 +908,8 @@ namespace MoonWorks.Math Vector3 cameraPosition, Vector3 cameraTarget, Vector3 cameraUpVector - ) { + ) + { Matrix4x4 matrix; CreateLookAt(ref cameraPosition, ref cameraTarget, ref cameraUpVector, out matrix); return matrix; @@ -918,7 +927,8 @@ namespace MoonWorks.Math ref Vector3 cameraTarget, ref Vector3 cameraUpVector, out Matrix4x4 result - ) { + ) + { Vector3 vectorA = Vector3.Normalize(cameraPosition - cameraTarget); Vector3 vectorB = Vector3.Normalize(Vector3.Cross(cameraUpVector, vectorA)); Vector3 vectorC = Vector3.Cross(vectorA, vectorB); @@ -953,7 +963,8 @@ namespace MoonWorks.Math float height, float zNearPlane, float zFarPlane - ) { + ) + { Matrix4x4 matrix; CreateOrthographic(width, height, zNearPlane, zFarPlane, out matrix); return matrix; @@ -973,7 +984,8 @@ namespace MoonWorks.Math float zNearPlane, float zFarPlane, out Matrix4x4 result - ) { + ) + { result.M11 = 2f / width; result.M12 = result.M13 = result.M14 = 0f; result.M22 = 2f / height; @@ -1002,7 +1014,8 @@ namespace MoonWorks.Math float top, float zNearPlane, float zFarPlane - ) { + ) + { Matrix4x4 matrix; CreateOrthographicOffCenter( left, @@ -1034,7 +1047,8 @@ namespace MoonWorks.Math float zNearPlane, float zFarPlane, out Matrix4x4 result - ) { + ) + { result.M11 = (float) (2.0 / ((double) right - (double) left)); result.M12 = 0.0f; result.M13 = 0.0f; @@ -1075,7 +1089,8 @@ namespace MoonWorks.Math float height, float nearPlaneDistance, float farPlaneDistance - ) { + ) + { Matrix4x4 matrix; CreatePerspective(width, height, nearPlaneDistance, farPlaneDistance, out matrix); return matrix; @@ -1095,7 +1110,8 @@ namespace MoonWorks.Math float nearPlaneDistance, float farPlaneDistance, out Matrix4x4 result - ) { + ) + { if (nearPlaneDistance <= 0f) { throw new ArgumentException("nearPlaneDistance <= 0"); @@ -1135,7 +1151,8 @@ namespace MoonWorks.Math float aspectRatio, float nearPlaneDistance, float farPlaneDistance - ) { + ) + { Matrix4x4 result; CreatePerspectiveFieldOfView( fieldOfView, @@ -1161,7 +1178,8 @@ namespace MoonWorks.Math float nearPlaneDistance, float farPlaneDistance, out Matrix4x4 result - ) { + ) + { if ((fieldOfView <= 0f) || (fieldOfView >= 3.141593f)) { throw new ArgumentException("fieldOfView <= 0 or >= PI"); @@ -1210,7 +1228,8 @@ namespace MoonWorks.Math float top, float nearPlaneDistance, float farPlaneDistance - ) { + ) + { Matrix4x4 result; CreatePerspectiveOffCenter( left, @@ -1242,7 +1261,8 @@ namespace MoonWorks.Math float nearPlaneDistance, float farPlaneDistance, out Matrix4x4 result - ) { + ) + { if (nearPlaneDistance <= 0f) { throw new ArgumentException("nearPlaneDistance <= 0"); @@ -1408,7 +1428,8 @@ namespace MoonWorks.Math float yScale, float zScale, out Matrix4x4 result - ) { + ) + { result.M11 = xScale; result.M12 = 0; result.M13 = 0; @@ -1527,7 +1548,8 @@ namespace MoonWorks.Math float xPosition, float yPosition, float zPosition - ) { + ) + { Matrix4x4 result; CreateTranslation(xPosition, yPosition, zPosition, out result); return result; @@ -1582,7 +1604,8 @@ namespace MoonWorks.Math float yPosition, float zPosition, out Matrix4x4 result - ) { + ) + { result.M11 = 1; result.M12 = 0; result.M13 = 0; @@ -1672,7 +1695,8 @@ namespace MoonWorks.Math ref Vector3 forward, ref Vector3 up, out Matrix4x4 result - ) { + ) + { Vector3 x, y, z; Vector3.Normalize(ref forward, out z); Vector3.Cross(ref forward, ref up, out x); @@ -2069,7 +2093,8 @@ namespace MoonWorks.Math ref Matrix4x4 matrix2, float amount, out Matrix4x4 result - ) { + ) + { result.M11 = matrix1.M11 + ((matrix2.M11 - matrix1.M11) * amount); result.M12 = matrix1.M12 + ((matrix2.M12 - matrix1.M12) * amount); result.M13 = matrix1.M13 + ((matrix2.M13 - matrix1.M13) * amount); @@ -2097,7 +2122,8 @@ namespace MoonWorks.Math public static Matrix4x4 Multiply( Matrix4x4 matrix1, Matrix4x4 matrix2 - ) { + ) + { float m11 = ( (matrix1.M11 * matrix2.M11) + (matrix1.M12 * matrix2.M21) + @@ -2548,7 +2574,8 @@ namespace MoonWorks.Math ref Matrix4x4 value, ref Quaternion rotation, out Matrix4x4 result - ) { + ) + { Matrix4x4 rotMatrix = CreateFromQuaternion(rotation); Multiply(ref value, ref rotMatrix, out result); } diff --git a/src/Math/Plane.cs b/src/Math/Plane.cs index c98eb7ce..5d2a40e9 100644 --- a/src/Math/Plane.cs +++ b/src/Math/Plane.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -233,7 +233,8 @@ namespace MoonWorks.Math ref Plane plane, ref Matrix4x4 matrix, out Plane result - ) { + ) + { /* See "Transforming Normals" in * http://www.glprogramming.com/red/appendixf.html * for an explanation of how this works. @@ -277,7 +278,8 @@ namespace MoonWorks.Math ref Plane plane, ref Quaternion rotation, out Plane result - ) { + ) + { Vector3.Transform( ref plane.Normal, ref rotation, diff --git a/src/Math/PlaneIntersectionType.cs b/src/Math/PlaneIntersectionType.cs index 2d6e0e18..9cd68eaa 100644 --- a/src/Math/PlaneIntersectionType.cs +++ b/src/Math/PlaneIntersectionType.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Math/Point.cs b/src/Math/Point.cs index 77618f95..e9f8aa28 100644 --- a/src/Math/Point.cs +++ b/src/Math/Point.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley diff --git a/src/Math/Quaternion.cs b/src/Math/Quaternion.cs index c795b756..db7597cf 100644 --- a/src/Math/Quaternion.cs +++ b/src/Math/Quaternion.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -157,10 +157,10 @@ namespace MoonWorks.Math /// true if the instances are equal; false otherwise. public bool Equals(Quaternion other) { - return ( X == other.X && + return (X == other.X && Y == other.Y && Z == other.Z && - W == other.W ); + W == other.W); } /// @@ -266,7 +266,8 @@ namespace MoonWorks.Math ref Quaternion quaternion1, ref Quaternion quaternion2, out Quaternion result - ) { + ) + { result.X = quaternion1.X + quaternion2.X; result.Y = quaternion1.Y + quaternion2.Y; result.Z = quaternion1.Z + quaternion2.Z; @@ -296,7 +297,8 @@ namespace MoonWorks.Math ref Quaternion value1, ref Quaternion value2, out Quaternion result - ) { + ) + { float x1 = value1.X; float y1 = value1.Y; float z1 = value1.Z; @@ -359,7 +361,8 @@ namespace MoonWorks.Math ref Vector3 axis, float angle, out Quaternion result - ) { + ) + { float half = angle * 0.5f; float sin = (float) System.Math.Sin((double) half); float cos = (float) System.Math.Cos((double) half); @@ -415,12 +418,12 @@ namespace MoonWorks.Math else if (matrix.M22 > matrix.M33) { sqrt = (float) System.Math.Sqrt(1.0f + matrix.M22 - matrix.M11 - matrix.M33); - half = 0.5f/sqrt; + half = 0.5f / sqrt; - result.X = (matrix.M21 + matrix.M12)*half; - result.Y = 0.5f*sqrt; - result.Z = (matrix.M32 + matrix.M23)*half; - result.W = (matrix.M31 - matrix.M13)*half; + result.X = (matrix.M21 + matrix.M12) * half; + result.Y = 0.5f * sqrt; + result.Z = (matrix.M32 + matrix.M23) * half; + result.W = (matrix.M31 - matrix.M13) * half; } else { @@ -499,7 +502,8 @@ namespace MoonWorks.Math ref Quaternion quaternion1, ref Quaternion quaternion2, out Quaternion result - ) { + ) + { float x = quaternion1.X; float y = quaternion1.Y; float z = quaternion1.Z; @@ -551,7 +555,8 @@ namespace MoonWorks.Math ref Quaternion quaternion1, ref Quaternion quaternion2, out float result - ) { + ) + { result = ( (quaternion1.X * quaternion2.X) + (quaternion1.Y * quaternion2.Y) + @@ -603,7 +608,8 @@ namespace MoonWorks.Math Quaternion quaternion1, Quaternion quaternion2, float amount - ) { + ) + { Quaternion quaternion; Lerp(ref quaternion1, ref quaternion2, amount, out quaternion); return quaternion; @@ -621,7 +627,8 @@ namespace MoonWorks.Math ref Quaternion quaternion2, float amount, out Quaternion result - ) { + ) + { float num = amount; float num2 = 1f - num; float num5 = ( @@ -668,7 +675,8 @@ namespace MoonWorks.Math Quaternion quaternion1, Quaternion quaternion2, float amount - ) { + ) + { Quaternion quaternion; Slerp(ref quaternion1, ref quaternion2, amount, out quaternion); return quaternion; @@ -686,7 +694,8 @@ namespace MoonWorks.Math ref Quaternion quaternion2, float amount, out Quaternion result - ) { + ) + { float num2; float num3; float num = amount; @@ -743,7 +752,8 @@ namespace MoonWorks.Math ref Quaternion quaternion1, ref Quaternion quaternion2, out Quaternion result - ) { + ) + { result.X = quaternion1.X - quaternion2.X; result.Y = quaternion1.Y - quaternion2.Y; result.Z = quaternion1.Z - quaternion2.Z; @@ -786,7 +796,8 @@ namespace MoonWorks.Math ref Quaternion quaternion1, ref Quaternion quaternion2, out Quaternion result - ) { + ) + { float x = quaternion1.X; float y = quaternion1.Y; float z = quaternion1.Z; @@ -815,7 +826,8 @@ namespace MoonWorks.Math ref Quaternion quaternion1, float scaleFactor, out Quaternion result - ) { + ) + { result.X = quaternion1.X * scaleFactor; result.Y = quaternion1.Y * scaleFactor; result.Z = quaternion1.Z * scaleFactor; @@ -881,15 +893,15 @@ namespace MoonWorks.Math result.W = quaternion.W * num; } - public static Quaternion LookAt(in Vector3 forward, in Vector3 up) - { - Matrix4x4 orientation = Matrix4x4.Identity; - orientation.Forward = forward; - orientation.Right = Vector3.Normalize(Vector3.Cross(forward, up)); - orientation.Up = Vector3.Cross(orientation.Right, forward); + public static Quaternion LookAt(in Vector3 forward, in Vector3 up) + { + Matrix4x4 orientation = Matrix4x4.Identity; + orientation.Forward = forward; + orientation.Right = Vector3.Normalize(Vector3.Cross(forward, up)); + orientation.Up = Vector3.Cross(orientation.Right, forward); - return Quaternion.CreateFromRotationMatrix(orientation); - } + return Quaternion.CreateFromRotationMatrix(orientation); + } #endregion diff --git a/src/Math/Ray.cs b/src/Math/Ray.cs index 9e613145..98f46a0d 100644 --- a/src/Math/Ray.cs +++ b/src/Math/Ray.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -70,8 +70,8 @@ namespace MoonWorks.Math public bool Equals(Ray other) { - return ( this.Position.Equals(other.Position) && - this.Direction.Equals(other.Direction) ); + return (this.Position.Equals(other.Position) && + this.Direction.Equals(other.Direction)); } @@ -124,8 +124,8 @@ namespace MoonWorks.Math tMaxY = temp; } - if ( (tMin.HasValue && tMin > tMaxY) || - (tMax.HasValue && tMinY > tMax) ) + if ((tMin.HasValue && tMin > tMaxY) || + (tMax.HasValue && tMinY > tMax)) { return null; } @@ -153,8 +153,8 @@ namespace MoonWorks.Math tMaxZ = temp; } - if ( (tMin.HasValue && tMin > tMaxZ) || - (tMax.HasValue && tMinZ > tMax) ) + if ((tMin.HasValue && tMin > tMaxZ) || + (tMax.HasValue && tMinZ > tMax)) { return null; } diff --git a/src/Math/Rectangle.cs b/src/Math/Rectangle.cs index 42f113a1..6bf9c39b 100644 --- a/src/Math/Rectangle.cs +++ b/src/Math/Rectangle.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -117,10 +117,10 @@ namespace MoonWorks.Math { get { - return ( (Width == 0) && + return ((Width == 0) && (Height == 0) && (X == 0) && - (Y == 0) ); + (Y == 0)); } } @@ -218,10 +218,10 @@ namespace MoonWorks.Math /// true if the provided coordinates lie inside this . false otherwise. public bool Contains(int x, int y) { - return ( (this.X <= x) && + return ((this.X <= x) && (x < (this.X + this.Width)) && (this.Y <= y) && - (y < (this.Y + this.Height)) ); + (y < (this.Y + this.Height))); } /// @@ -231,10 +231,10 @@ namespace MoonWorks.Math /// true if the provided lies inside this . false otherwise. public bool Contains(Point value) { - return ( (this.X <= value.X) && + return ((this.X <= value.X) && (value.X < (this.X + this.Width)) && (this.Y <= value.Y) && - (value.Y < (this.Y + this.Height)) ); + (value.Y < (this.Y + this.Height))); } /// @@ -244,26 +244,26 @@ namespace MoonWorks.Math /// true if the provided 's bounds lie entirely inside this . false otherwise. public bool Contains(Rectangle value) { - return ( (this.X <= value.X) && + return ((this.X <= value.X) && ((value.X + value.Width) <= (this.X + this.Width)) && (this.Y <= value.Y) && - ((value.Y + value.Height) <= (this.Y + this.Height)) ); + ((value.Y + value.Height) <= (this.Y + this.Height))); } public void Contains(ref Point value, out bool result) { - result = ( (this.X <= value.X) && + result = ((this.X <= value.X) && (value.X < (this.X + this.Width)) && (this.Y <= value.Y) && - (value.Y < (this.Y + this.Height)) ); + (value.Y < (this.Y + this.Height))); } public void Contains(ref Rectangle value, out bool result) { - result = ( (this.X <= value.X) && + result = ((this.X <= value.X) && ((value.X + value.Width) <= (this.X + this.Width)) && (this.Y <= value.Y) && - ((value.Y + value.Height) <= (this.Y + this.Height)) ); + ((value.Y + value.Height) <= (this.Y + this.Height))); } /// @@ -349,10 +349,10 @@ namespace MoonWorks.Math /// true if other intersects with this rectangle; false otherwise. public bool Intersects(Rectangle value) { - return ( value.Left < Right && + return (value.Left < Right && Left < value.Right && value.Top < Bottom && - Top < value.Bottom ); + Top < value.Bottom); } /// @@ -362,10 +362,10 @@ namespace MoonWorks.Math /// true if other intersects with this rectangle; false otherwise. As an output parameter. public void Intersects(ref Rectangle value, out bool result) { - result = ( value.Left < Right && + result = (value.Left < Right && Left < value.Right && value.Top < Bottom && - Top < value.Bottom ); + Top < value.Bottom); } #endregion @@ -374,10 +374,10 @@ namespace MoonWorks.Math public static bool operator ==(Rectangle a, Rectangle b) { - return ( (a.X == b.X) && + return ((a.X == b.X) && (a.Y == b.Y) && (a.Width == b.Width) && - (a.Height == b.Height) ); + (a.Height == b.Height)); } public static bool operator !=(Rectangle a, Rectangle b) @@ -396,7 +396,8 @@ namespace MoonWorks.Math ref Rectangle value1, ref Rectangle value2, out Rectangle result - ) { + ) + { if (value1.Intersects(value2)) { int right_side = System.Math.Min( diff --git a/src/Math/Vector2.cs b/src/Math/Vector2.cs index 4ac16bea..0749cad3 100644 --- a/src/Math/Vector2.cs +++ b/src/Math/Vector2.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -163,8 +163,8 @@ namespace MoonWorks.Math /// true if the instances are equal; false otherwise. public bool Equals(Vector2 other) { - return ( X == other.X && - Y == other.Y ); + return (X == other.X && + Y == other.Y); } /// @@ -264,7 +264,8 @@ namespace MoonWorks.Math Vector2 value3, float amount1, float amount2 - ) { + ) + { return new Vector2( MathHelper.Barycentric(value1.X, value2.X, value3.X, amount1, amount2), MathHelper.Barycentric(value1.Y, value2.Y, value3.Y, amount1, amount2) @@ -287,7 +288,8 @@ namespace MoonWorks.Math float amount1, float amount2, out Vector2 result - ) { + ) + { result.X = MathHelper.Barycentric(value1.X, value2.X, value3.X, amount1, amount2); result.Y = MathHelper.Barycentric(value1.Y, value2.Y, value3.Y, amount1, amount2); } @@ -307,7 +309,8 @@ namespace MoonWorks.Math Vector2 value3, Vector2 value4, float amount - ) { + ) + { return new Vector2( MathHelper.CatmullRom(value1.X, value2.X, value3.X, value4.X, amount), MathHelper.CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount) @@ -330,7 +333,8 @@ namespace MoonWorks.Math ref Vector2 value4, float amount, out Vector2 result - ) { + ) + { result.X = MathHelper.CatmullRom(value1.X, value2.X, value3.X, value4.X, amount); result.Y = MathHelper.CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount); } @@ -362,7 +366,8 @@ namespace MoonWorks.Math ref Vector2 min, ref Vector2 max, out Vector2 result - ) { + ) + { result.X = MathHelper.Clamp(value1.X, min.X, max.X); result.Y = MathHelper.Clamp(value1.Y, min.Y, max.Y); } @@ -413,7 +418,8 @@ namespace MoonWorks.Math ref Vector2 value1, ref Vector2 value2, out float result - ) { + ) + { float v1 = value1.X - value2.X, v2 = value1.Y - value2.Y; result = (v1 * v1) + (v2 * v2); } @@ -507,7 +513,8 @@ namespace MoonWorks.Math Vector2 value2, Vector2 tangent2, float amount - ) { + ) + { Vector2 result = new Vector2(); Hermite(ref value1, ref tangent1, ref value2, ref tangent2, amount, out result); return result; @@ -529,7 +536,8 @@ namespace MoonWorks.Math ref Vector2 tangent2, float amount, out Vector2 result - ) { + ) + { result.X = MathHelper.Hermite(value1.X, tangent1.X, value2.X, tangent2.X, amount); result.Y = MathHelper.Hermite(value1.Y, tangent1.Y, value2.Y, tangent2.Y, amount); } @@ -561,7 +569,8 @@ namespace MoonWorks.Math ref Vector2 value2, float amount, out Vector2 result - ) { + ) + { result.X = MathHelper.Lerp(value1.X, value2.X, amount); result.Y = MathHelper.Lerp(value1.Y, value2.Y, amount); } @@ -773,7 +782,8 @@ namespace MoonWorks.Math ref Vector2 value2, float amount, out Vector2 result - ) { + ) + { result.X = MathHelper.SmoothStep(value1.X, value2.X, amount); result.Y = MathHelper.SmoothStep(value1.Y, value2.Y, amount); } @@ -827,7 +837,8 @@ namespace MoonWorks.Math ref Vector2 position, ref Matrix4x4 matrix, out Vector2 result - ) { + ) + { float x = (position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M41; float y = (position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M42; result.X = x; @@ -856,7 +867,8 @@ namespace MoonWorks.Math ref Vector2 value, ref Quaternion rotation, out Vector2 result - ) { + ) + { float x = 2 * -(rotation.Z * value.Y); float y = 2 * (rotation.Z * value.X); float z = 2 * (rotation.X * value.Y - rotation.Y * value.X); @@ -875,7 +887,8 @@ namespace MoonWorks.Math Vector2[] sourceArray, ref Matrix4x4 matrix, Vector2[] destinationArray - ) { + ) + { Transform(sourceArray, 0, ref matrix, destinationArray, 0, sourceArray.Length); } @@ -895,7 +908,8 @@ namespace MoonWorks.Math Vector2[] destinationArray, int destinationIndex, int length - ) { + ) + { for (int x = 0; x < length; x += 1) { Vector2 position = sourceArray[sourceIndex + x]; @@ -918,7 +932,8 @@ namespace MoonWorks.Math Vector2[] sourceArray, ref Quaternion rotation, Vector2[] destinationArray - ) { + ) + { Transform( sourceArray, 0, @@ -945,7 +960,8 @@ namespace MoonWorks.Math Vector2[] destinationArray, int destinationIndex, int length - ) { + ) + { for (int i = 0; i < length; i += 1) { Vector2 position = sourceArray[sourceIndex + i]; @@ -979,7 +995,8 @@ namespace MoonWorks.Math ref Vector2 normal, ref Matrix4x4 matrix, out Vector2 result - ) { + ) + { float x = (normal.X * matrix.M11) + (normal.Y * matrix.M21); float y = (normal.X * matrix.M12) + (normal.Y * matrix.M22); result.X = x; @@ -996,7 +1013,8 @@ namespace MoonWorks.Math Vector2[] sourceArray, ref Matrix4x4 matrix, Vector2[] destinationArray - ) { + ) + { TransformNormal( sourceArray, 0, @@ -1023,7 +1041,8 @@ namespace MoonWorks.Math Vector2[] destinationArray, int destinationIndex, int length - ) { + ) + { for (int i = 0; i < length; i += 1) { Vector2 position = sourceArray[sourceIndex + i]; @@ -1058,8 +1077,8 @@ namespace MoonWorks.Math /// true if the instances are equal; false otherwise. public static bool operator ==(Vector2 value1, Vector2 value2) { - return ( value1.X == value2.X && - value1.Y == value2.Y ); + return (value1.X == value2.X && + value1.Y == value2.Y); } /// diff --git a/src/Math/Vector3.cs b/src/Math/Vector3.cs index 8e443376..7657da64 100644 --- a/src/Math/Vector3.cs +++ b/src/Math/Vector3.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -270,9 +270,9 @@ namespace MoonWorks.Math /// true if the instances are equal; false otherwise. public bool Equals(Vector3 other) { - return ( X == other.X && + return (X == other.X && Y == other.Y && - Z == other.Z ); + Z == other.Z); } /// @@ -383,7 +383,8 @@ namespace MoonWorks.Math Vector3 value3, float amount1, float amount2 - ) { + ) + { return new Vector3( MathHelper.Barycentric(value1.X, value2.X, value3.X, amount1, amount2), MathHelper.Barycentric(value1.Y, value2.Y, value3.Y, amount1, amount2), @@ -407,7 +408,8 @@ namespace MoonWorks.Math float amount1, float amount2, out Vector3 result - ) { + ) + { result.X = MathHelper.Barycentric(value1.X, value2.X, value3.X, amount1, amount2); result.Y = MathHelper.Barycentric(value1.Y, value2.Y, value3.Y, amount1, amount2); result.Z = MathHelper.Barycentric(value1.Z, value2.Z, value3.Z, amount1, amount2); @@ -428,7 +430,8 @@ namespace MoonWorks.Math Vector3 value3, Vector3 value4, float amount - ) { + ) + { return new Vector3( MathHelper.CatmullRom(value1.X, value2.X, value3.X, value4.X, amount), MathHelper.CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount), @@ -452,7 +455,8 @@ namespace MoonWorks.Math ref Vector3 value4, float amount, out Vector3 result - ) { + ) + { result.X = MathHelper.CatmullRom(value1.X, value2.X, value3.X, value4.X, amount); result.Y = MathHelper.CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount); result.Z = MathHelper.CatmullRom(value1.Z, value2.Z, value3.Z, value4.Z, amount); @@ -486,24 +490,26 @@ namespace MoonWorks.Math ref Vector3 min, ref Vector3 max, out Vector3 result - ) { + ) + { result.X = MathHelper.Clamp(value1.X, min.X, max.X); result.Y = MathHelper.Clamp(value1.Y, min.Y, max.Y); result.Z = MathHelper.Clamp(value1.Z, min.Z, max.Z); } /// - /// Clamps the magnitude of the specified vector. - /// - /// The vector to clamp. - /// The maximum length of the vector. - /// + /// Clamps the magnitude of the specified vector. + /// + /// The vector to clamp. + /// The maximum length of the vector. + /// public static Vector3 ClampMagnitude( Vector3 value, float maxLength - ) { - return (value.LengthSquared() > maxLength * maxLength) ? (Vector3.Normalize(value) * maxLength) : value; - } + ) + { + return (value.LengthSquared() > maxLength * maxLength) ? (Vector3.Normalize(value) * maxLength) : value; + } /// /// Computes the cross product of two vectors. @@ -583,7 +589,8 @@ namespace MoonWorks.Math ref Vector3 value1, ref Vector3 value2, out float result - ) { + ) + { result = ( (value1.X - value2.X) * (value1.X - value2.X) + (value1.Y - value2.Y) * (value1.Y - value2.Y) + @@ -688,7 +695,8 @@ namespace MoonWorks.Math Vector3 value2, Vector3 tangent2, float amount - ) { + ) + { Vector3 result = new Vector3(); Hermite(ref value1, ref tangent1, ref value2, ref tangent2, amount, out result); return result; @@ -710,7 +718,8 @@ namespace MoonWorks.Math ref Vector3 tangent2, float amount, out Vector3 result - ) { + ) + { result.X = MathHelper.Hermite(value1.X, tangent1.X, value2.X, tangent2.X, amount); result.Y = MathHelper.Hermite(value1.Y, tangent1.Y, value2.Y, tangent2.Y, amount); result.Z = MathHelper.Hermite(value1.Z, tangent1.Z, value2.Z, tangent2.Z, amount); @@ -744,7 +753,8 @@ namespace MoonWorks.Math ref Vector3 value2, float amount, out Vector3 result - ) { + ) + { result.X = MathHelper.Lerp(value1.X, value2.X, amount); result.Y = MathHelper.Lerp(value1.Y, value2.Y, amount); result.Z = MathHelper.Lerp(value1.Z, value2.Z, amount); @@ -992,7 +1002,8 @@ namespace MoonWorks.Math ref Vector3 value2, float amount, out Vector3 result - ) { + ) + { result.X = MathHelper.SmoothStep(value1.X, value2.X, amount); result.Y = MathHelper.SmoothStep(value1.Y, value2.Y, amount); result.Z = MathHelper.SmoothStep(value1.Z, value2.Z, amount); @@ -1047,7 +1058,8 @@ namespace MoonWorks.Math ref Vector3 position, ref Matrix4x4 matrix, out Vector3 result - ) { + ) + { float x = ( (position.X * matrix.M11) + (position.Y * matrix.M21) + @@ -1081,7 +1093,8 @@ namespace MoonWorks.Math Vector3[] sourceArray, ref Matrix4x4 matrix, Vector3[] destinationArray - ) { + ) + { Debug.Assert( destinationArray.Length >= sourceArray.Length, "The destination array is smaller than the source array." @@ -1121,7 +1134,8 @@ namespace MoonWorks.Math Vector3[] destinationArray, int destinationIndex, int length - ) { + ) + { Debug.Assert( sourceArray.Length - sourceIndex >= length, "The source array is too small for the given sourceIndex and length." @@ -1173,7 +1187,8 @@ namespace MoonWorks.Math ref Vector3 value, ref Quaternion rotation, out Vector3 result - ) { + ) + { float x = 2 * (rotation.Y * value.Z - rotation.Z * value.Y); float y = 2 * (rotation.Z * value.X - rotation.X * value.Z); float z = 2 * (rotation.X * value.Y - rotation.Y * value.X); @@ -1193,7 +1208,8 @@ namespace MoonWorks.Math Vector3[] sourceArray, ref Quaternion rotation, Vector3[] destinationArray - ) { + ) + { Debug.Assert( destinationArray.Length >= sourceArray.Length, "The destination array is smaller than the source array." @@ -1236,7 +1252,8 @@ namespace MoonWorks.Math Vector3[] destinationArray, int destinationIndex, int length - ) { + ) + { Debug.Assert( sourceArray.Length - sourceIndex >= length, "The source array is too small for the given sourceIndex and length." @@ -1289,7 +1306,8 @@ namespace MoonWorks.Math ref Vector3 normal, ref Matrix4x4 matrix, out Vector3 result - ) { + ) + { float x = (normal.X * matrix.M11) + (normal.Y * matrix.M21) + (normal.Z * matrix.M31); float y = (normal.X * matrix.M12) + (normal.Y * matrix.M22) + (normal.Z * matrix.M32); float z = (normal.X * matrix.M13) + (normal.Y * matrix.M23) + (normal.Z * matrix.M33); @@ -1308,7 +1326,8 @@ namespace MoonWorks.Math Vector3[] sourceArray, ref Matrix4x4 matrix, Vector3[] destinationArray - ) { + ) + { Debug.Assert( destinationArray.Length >= sourceArray.Length, "The destination array is smaller than the source array." @@ -1339,7 +1358,8 @@ namespace MoonWorks.Math Vector3[] destinationArray, int destinationIndex, int length - ) { + ) + { if (sourceArray == null) { throw new ArgumentNullException("sourceArray"); @@ -1396,9 +1416,9 @@ namespace MoonWorks.Math /// true if the instances are equal; false otherwise. public static bool operator ==(Vector3 value1, Vector3 value2) { - return ( value1.X == value2.X && + return (value1.X == value2.X && value1.Y == value2.Y && - value1.Z == value2.Z ); + value1.Z == value2.Z); } /// diff --git a/src/Math/Vector4.cs b/src/Math/Vector4.cs index 1332bee4..7a7c34d1 100644 --- a/src/Math/Vector4.cs +++ b/src/Math/Vector4.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -234,10 +234,10 @@ namespace MoonWorks.Math /// true if the instances are equal; false otherwise. public bool Equals(Vector4 other) { - return ( X == other.X && + return (X == other.X && Y == other.Y && Z == other.Z && - W == other.W ); + W == other.W); } /// @@ -344,7 +344,8 @@ namespace MoonWorks.Math Vector4 value3, float amount1, float amount2 - ) { + ) + { return new Vector4( MathHelper.Barycentric(value1.X, value2.X, value3.X, amount1, amount2), MathHelper.Barycentric(value1.Y, value2.Y, value3.Y, amount1, amount2), @@ -369,7 +370,8 @@ namespace MoonWorks.Math float amount1, float amount2, out Vector4 result - ) { + ) + { result.X = MathHelper.Barycentric(value1.X, value2.X, value3.X, amount1, amount2); result.Y = MathHelper.Barycentric(value1.Y, value2.Y, value3.Y, amount1, amount2); result.Z = MathHelper.Barycentric(value1.Z, value2.Z, value3.Z, amount1, amount2); @@ -391,7 +393,8 @@ namespace MoonWorks.Math Vector4 value3, Vector4 value4, float amount - ) { + ) + { return new Vector4( MathHelper.CatmullRom(value1.X, value2.X, value3.X, value4.X, amount), MathHelper.CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount), @@ -416,7 +419,8 @@ namespace MoonWorks.Math ref Vector4 value4, float amount, out Vector4 result - ) { + ) + { result.X = MathHelper.CatmullRom(value1.X, value2.X, value3.X, value4.X, amount); result.Y = MathHelper.CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount); result.Z = MathHelper.CatmullRom(value1.Z, value2.Z, value3.Z, value4.Z, amount); @@ -452,7 +456,8 @@ namespace MoonWorks.Math ref Vector4 min, ref Vector4 max, out Vector4 result - ) { + ) + { result.X = MathHelper.Clamp(value1.X, min.X, max.X); result.Y = MathHelper.Clamp(value1.Y, min.Y, max.Y); result.Z = MathHelper.Clamp(value1.Z, min.Z, max.Z); @@ -507,7 +512,8 @@ namespace MoonWorks.Math ref Vector4 value1, ref Vector4 value2, out float result - ) { + ) + { result = ( (value1.W - value2.W) * (value1.W - value2.W) + (value1.X - value2.X) * (value1.X - value2.X) + @@ -572,7 +578,8 @@ namespace MoonWorks.Math ref Vector4 value1, ref Vector4 value2, out Vector4 result - ) { + ) + { result.W = value1.W / value2.W; result.X = value1.X / value2.X; result.Y = value1.Y / value2.Y; @@ -626,7 +633,8 @@ namespace MoonWorks.Math Vector4 value2, Vector4 tangent2, float amount - ) { + ) + { return new Vector4( MathHelper.Hermite(value1.X, tangent1.X, value2.X, tangent2.X, amount), MathHelper.Hermite(value1.Y, tangent1.Y, value2.Y, tangent2.Y, amount), @@ -651,7 +659,8 @@ namespace MoonWorks.Math ref Vector4 tangent2, float amount, out Vector4 result - ) { + ) + { result.W = MathHelper.Hermite(value1.W, tangent1.W, value2.W, tangent2.W, amount); result.X = MathHelper.Hermite(value1.X, tangent1.X, value2.X, tangent2.X, amount); result.Y = MathHelper.Hermite(value1.Y, tangent1.Y, value2.Y, tangent2.Y, amount); @@ -687,7 +696,8 @@ namespace MoonWorks.Math ref Vector4 value2, float amount, out Vector4 result - ) { + ) + { result.X = MathHelper.Lerp(value1.X, value2.X, amount); result.Y = MathHelper.Lerp(value1.Y, value2.Y, amount); result.Z = MathHelper.Lerp(value1.Z, value2.Z, amount); @@ -905,7 +915,8 @@ namespace MoonWorks.Math ref Vector4 value2, float amount, out Vector4 result - ) { + ) + { result.X = MathHelper.SmoothStep(value1.X, value2.X, amount); result.Y = MathHelper.SmoothStep(value1.Y, value2.Y, amount); result.Z = MathHelper.SmoothStep(value1.Z, value2.Z, amount); @@ -1081,7 +1092,8 @@ namespace MoonWorks.Math Vector4[] sourceArray, ref Matrix4x4 matrix, Vector4[] destinationArray - ) { + ) + { if (sourceArray == null) { throw new ArgumentNullException("sourceArray"); @@ -1122,7 +1134,8 @@ namespace MoonWorks.Math Vector4[] destinationArray, int destinationIndex, int length - ) { + ) + { if (sourceArray == null) { throw new ArgumentNullException("sourceArray"); @@ -1202,7 +1215,8 @@ namespace MoonWorks.Math ref Vector2 value, ref Quaternion rotation, out Vector4 result - ) { + ) + { double xx = rotation.X + rotation.X; double yy = rotation.Y + rotation.Y; double zz = rotation.Z + rotation.Z; @@ -1240,7 +1254,8 @@ namespace MoonWorks.Math ref Vector3 value, ref Quaternion rotation, out Vector4 result - ) { + ) + { double xx = rotation.X + rotation.X; double yy = rotation.Y + rotation.Y; double zz = rotation.Z + rotation.Z; @@ -1281,7 +1296,8 @@ namespace MoonWorks.Math ref Vector4 value, ref Quaternion rotation, out Vector4 result - ) { + ) + { double xx = rotation.X + rotation.X; double yy = rotation.Y + rotation.Y; double zz = rotation.Z + rotation.Z; @@ -1322,7 +1338,8 @@ namespace MoonWorks.Math Vector4[] sourceArray, ref Quaternion rotation, Vector4[] destinationArray - ) { + ) + { if (sourceArray == null) { throw new ArgumentException("sourceArray"); @@ -1363,7 +1380,8 @@ namespace MoonWorks.Math Vector4[] destinationArray, int destinationIndex, int length - ) { + ) + { if (sourceArray == null) { throw new ArgumentException("sourceArray"); @@ -1405,10 +1423,10 @@ namespace MoonWorks.Math public static bool operator ==(Vector4 value1, Vector4 value2) { - return ( value1.X == value2.X && + return (value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z && - value1.W == value2.W ); + value1.W == value2.W); } public static bool operator !=(Vector4 value1, Vector4 value2) diff --git a/src/MoonWorksDllMap.cs b/src/MoonWorksDllMap.cs index c6eeea95..663cc58e 100644 --- a/src/MoonWorksDllMap.cs +++ b/src/MoonWorksDllMap.cs @@ -1,4 +1,4 @@ -#region License +#region License /* MoonWorks - Game Development Framework * Copyright 2021 Evan Hemsley @@ -42,7 +42,7 @@ namespace MoonWorks } else if (OperatingSystem.IsMacOS()) { - return "osx"; + return "osx"; } else if (OperatingSystem.IsLinux()) { @@ -67,7 +67,8 @@ namespace MoonWorks string libraryName, Assembly assembly, DllImportSearchPath? dllImportSearchPath - ) { + ) + { string mappedName; if (!mapDictionary.TryGetValue(libraryName, out mappedName)) { diff --git a/src/Window/OSWindow.cs b/src/Window/OSWindow.cs index 70381226..c6feda58 100644 --- a/src/Window/OSWindow.cs +++ b/src/Window/OSWindow.cs @@ -1,66 +1,66 @@ -using System; +using System; using SDL2; namespace MoonWorks.Window { - public class OSWindow : IDisposable - { + public class OSWindow : IDisposable + { internal IntPtr Handle { get; } - public ScreenMode ScreenMode { get; } + public ScreenMode ScreenMode { get; } private bool IsDisposed; - public OSWindow(WindowCreateInfo windowCreateInfo) - { - var windowFlags = SDL.SDL_WindowFlags.SDL_WINDOW_VULKAN; + public OSWindow(WindowCreateInfo windowCreateInfo) + { + var windowFlags = SDL.SDL_WindowFlags.SDL_WINDOW_VULKAN; - if (windowCreateInfo.ScreenMode == ScreenMode.Fullscreen) - { - windowFlags |= SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN; - } - else if (windowCreateInfo.ScreenMode == ScreenMode.BorderlessWindow) - { - windowFlags |= SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP; - } + if (windowCreateInfo.ScreenMode == ScreenMode.Fullscreen) + { + windowFlags |= SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN; + } + else if (windowCreateInfo.ScreenMode == ScreenMode.BorderlessWindow) + { + windowFlags |= SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP; + } - ScreenMode = windowCreateInfo.ScreenMode; + ScreenMode = windowCreateInfo.ScreenMode; - Handle = SDL.SDL_CreateWindow( - windowCreateInfo.WindowTitle, - SDL.SDL_WINDOWPOS_UNDEFINED, - SDL.SDL_WINDOWPOS_UNDEFINED, - (int)windowCreateInfo.WindowWidth, - (int)windowCreateInfo.WindowHeight, - windowFlags - ); - } + Handle = SDL.SDL_CreateWindow( + windowCreateInfo.WindowTitle, + SDL.SDL_WINDOWPOS_UNDEFINED, + SDL.SDL_WINDOWPOS_UNDEFINED, + (int) windowCreateInfo.WindowWidth, + (int) windowCreateInfo.WindowHeight, + windowFlags + ); + } - public void ChangeScreenMode(ScreenMode screenMode) - { - SDL.SDL_WindowFlags windowFlag = 0; + public void ChangeScreenMode(ScreenMode screenMode) + { + SDL.SDL_WindowFlags windowFlag = 0; - if (screenMode == ScreenMode.Fullscreen) - { - windowFlag = SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN; - } - else if (screenMode == ScreenMode.BorderlessWindow) - { - windowFlag = SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP; - } + if (screenMode == ScreenMode.Fullscreen) + { + windowFlag = SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN; + } + else if (screenMode == ScreenMode.BorderlessWindow) + { + windowFlag = SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP; + } - SDL.SDL_SetWindowFullscreen(Handle, (uint) windowFlag); - } + SDL.SDL_SetWindowFullscreen(Handle, (uint) windowFlag); + } - /// - /// Resizes the window. - /// Note that you are responsible for recreating any graphics resources that need to change as a result of the size change. - /// - /// - /// - public void SetWindowSize(uint width, uint height) - { - SDL.SDL_SetWindowSize(Handle, (int)width, (int)height); - } + /// + /// Resizes the window. + /// Note that you are responsible for recreating any graphics resources that need to change as a result of the size change. + /// + /// + /// + public void SetWindowSize(uint width, uint height) + { + SDL.SDL_SetWindowSize(Handle, (int) width, (int) height); + } protected virtual void Dispose(bool disposing) { @@ -79,8 +79,8 @@ namespace MoonWorks.Window ~OSWindow() { - // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method - Dispose(disposing: false); + // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method + Dispose(disposing: false); } public void Dispose() diff --git a/src/Window/ScreenMode.cs b/src/Window/ScreenMode.cs index 56c9d894..b42aaa01 100644 --- a/src/Window/ScreenMode.cs +++ b/src/Window/ScreenMode.cs @@ -1,9 +1,9 @@ -namespace MoonWorks.Window +namespace MoonWorks.Window { - public enum ScreenMode - { - Fullscreen, - BorderlessWindow, - Windowed - } + public enum ScreenMode + { + Fullscreen, + BorderlessWindow, + Windowed + } } diff --git a/src/Window/WindowCreateInfo.cs b/src/Window/WindowCreateInfo.cs index 54c3849a..2c88322f 100644 --- a/src/Window/WindowCreateInfo.cs +++ b/src/Window/WindowCreateInfo.cs @@ -1,10 +1,10 @@ -namespace MoonWorks.Window +namespace MoonWorks.Window { - public struct WindowCreateInfo - { - public string WindowTitle; - public uint WindowWidth; - public uint WindowHeight; - public ScreenMode ScreenMode; - } + public struct WindowCreateInfo + { + public string WindowTitle; + public uint WindowWidth; + public uint WindowHeight; + public ScreenMode ScreenMode; + } }