diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c94bd8d7763..b7986a8a35b 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -21,12 +21,27 @@ jobs: with: dotnet-version: '8.0.x' + - name: Add msbuild to PATH + if: runner.os == 'Windows' + uses: microsoft/setup-msbuild@v1.0.2 + + - name: Setup Premake5 + uses: abel0b/setup-premake@v2.4 + with: + version: "5.0.0-beta2" + - name: Setup Java uses: actions/setup-java@v4 with: distribution: 'microsoft' java-version: '17' + - name: Install Vulkan SDK + uses: humbletim/install-vulkan-sdk@v1.1.1 + with: + version: 1.3.283.0 + cache: true + - name: Disable annotations run: echo "::remove-matcher owner=csc::" diff --git a/.gitignore b/.gitignore index 7594fe9ed3a..d1d1b08a465 100644 --- a/.gitignore +++ b/.gitignore @@ -89,5 +89,9 @@ IDE/MonoDevelop/MonoDevelop.MonoGame/templates/Common/MonoGame.Framework.dll.con # CAKE .cake/** +# Xmake +.xmake +vsxmake2022 + # docfx _* diff --git a/.gitmodules b/.gitmodules index b9dd8b19463..3a5032ebfc6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -10,3 +10,15 @@ [submodule "ThirdParty/StbImageWriteSharp"] path = ThirdParty/StbImageWriteSharp url = https://github.com/StbSharp/StbImageWriteSharp.git +[submodule "src/monogame/external/sdl2"] + path = native/monogame/external/sdl2 + url = https://github.com/MonoGame/MonoGame.Library.SDL.git +[submodule "src/monogame/external/vulkan-headers"] + path = native/monogame/external/vulkan-headers + url = https://github.com/KhronosGroup/Vulkan-Headers.git +[submodule "src/monogame/external/volk"] + path = native/monogame/external/volk + url = https://github.com/zeux/volk.git +[submodule "src/monogame/external/vma"] + path = native/monogame/external/vma + url = https://github.com/LunarG/VulkanMemoryAllocator.git diff --git a/.vscode/launch.json b/.vscode/launch.json index e0521e1c38e..bf6c0271172 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,6 +4,17 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ + { + "name": "Generator: CTypes", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "generator-ctypes", + "program": "${workspaceFolder}/Tools/MonoGame.Generator.CTypes/bin/Debug/net8.0/MonoGame.Generator.CTypes", + "args": [], + "cwd": "${workspaceFolder}/Tools/MonoGame.Generator.CTypes/bin/Debug/net8.0", + "console": "internalConsole", + "stopAtEntry": false + }, { "name": "MGCB Editor (Mac)", "type": "coreclr", diff --git a/.vscode/tasks.json b/.vscode/tasks.json index ee1b2400981..2f929868902 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -24,6 +24,18 @@ "/consoleloggerparameters:NoSummary" ], "problemMatcher": "$msCompile" + }, + { + "label": "generator-ctypes", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/Tools/MonoGame.Generator.CTypes/MonoGame.Generator.CTypes.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" } ] } \ No newline at end of file diff --git a/MonoGame.Framework.Content.Pipeline/Graphics/DefaultTextureProfile.cs b/MonoGame.Framework.Content.Pipeline/Graphics/DefaultTextureProfile.cs index db220024518..26d47872c55 100644 --- a/MonoGame.Framework.Content.Pipeline/Graphics/DefaultTextureProfile.cs +++ b/MonoGame.Framework.Content.Pipeline/Graphics/DefaultTextureProfile.cs @@ -15,6 +15,7 @@ public override bool Supports(TargetPlatform platform) { return platform == TargetPlatform.Android || platform == TargetPlatform.DesktopGL || + platform == TargetPlatform.DesktopVK || platform == TargetPlatform.MacOSX || platform == TargetPlatform.NativeClient || platform == TargetPlatform.RaspberryPi || @@ -64,6 +65,7 @@ private static TextureProcessorOutputFormat GetTextureFormatForPlatform(TextureP } else if (platform == TargetPlatform.Windows || platform == TargetPlatform.DesktopGL || + platform == TargetPlatform.DesktopVK || platform == TargetPlatform.MacOSX || platform == TargetPlatform.NativeClient || platform == TargetPlatform.Web) diff --git a/MonoGame.Framework.Content.Pipeline/Processors/EffectProcessor.cs b/MonoGame.Framework.Content.Pipeline/Processors/EffectProcessor.cs index 19e4ed15b84..194b0f58674 100644 --- a/MonoGame.Framework.Content.Pipeline/Processors/EffectProcessor.cs +++ b/MonoGame.Framework.Content.Pipeline/Processors/EffectProcessor.cs @@ -95,6 +95,8 @@ private string GetProfileForPlatform(TargetPlatform platform) case TargetPlatform.RaspberryPi: case TargetPlatform.Web: return "OpenGL"; + case TargetPlatform.DesktopVK: + return "Vulkan"; } return platform.ToString(); diff --git a/MonoGame.Framework.Content.Pipeline/Serialization/Compiler/ContentWriter.cs b/MonoGame.Framework.Content.Pipeline/Serialization/Compiler/ContentWriter.cs index 1ed88b37e5b..d433a191f58 100644 --- a/MonoGame.Framework.Content.Pipeline/Serialization/Compiler/ContentWriter.cs +++ b/MonoGame.Framework.Content.Pipeline/Serialization/Compiler/ContentWriter.cs @@ -54,6 +54,7 @@ public sealed class ContentWriter : BinaryWriter 'O', // XboxOne 'S', // Nintendo Switch 'b', // WebAssembly and Bridge.NET + 'V', // DesktopVK (Vulkan) }; /// diff --git a/MonoGame.Framework.Content.Pipeline/TargetPlatform.cs b/MonoGame.Framework.Content.Pipeline/TargetPlatform.cs index 3af47f14a18..503dcf28144 100644 --- a/MonoGame.Framework.Content.Pipeline/TargetPlatform.cs +++ b/MonoGame.Framework.Content.Pipeline/TargetPlatform.cs @@ -85,7 +85,12 @@ public enum TargetPlatform /// /// WebAssembly and Bridge.NET /// - Web + Web, + + /// + /// All desktop versions using Vulkan. + /// + DesktopVK, } diff --git a/MonoGame.Framework.Native.sln b/MonoGame.Framework.Native.sln index f6dc6f70026..5267aa3ff91 100644 --- a/MonoGame.Framework.Native.sln +++ b/MonoGame.Framework.Native.sln @@ -3,20 +3,100 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonoGame.Framework.Native", "MonoGame.Framework\MonoGame.Framework.Native.csproj", "{56BA741D-6AF1-489B-AB00-338DE11B1D32}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MonoGame.Framework.Native", "MonoGame.Framework\MonoGame.Framework.Native.csproj", "{56BA741D-6AF1-489B-AB00-338DE11B1D32}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{65B3DC17-24BA-4C39-810F-E371AC48199A}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MonoGame.Generator.CTypes", "Tools\MonoGame.Generator.CTypes\MonoGame.Generator.CTypes.csproj", "{74F12E34-D96B-4EC1-A218-BAFC83DC6220}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MonoGame.Tests.WindowsVK", "Tests\MonoGame.Tests.WindowsVK.csproj", "{C670BF60-56F7-493F-B5DD-50F97DB80A04}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "desktopvk", "native\monogame\desktopvk.vcxproj", "{60D6243F-CC40-D9B5-157F-8A5B8128B70A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug_VK|Any CPU = Debug_VK|Any CPU + Debug_VK|x64 = Debug_VK|x64 Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Release_VK|Any CPU = Release_VK|Any CPU + Release_VK|x64 = Release_VK|x64 Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE + Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution + {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Debug_VK|Any CPU.ActiveCfg = Debug|Any CPU + {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Debug_VK|Any CPU.Build.0 = Debug|Any CPU + {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Debug_VK|x64.ActiveCfg = Debug|Any CPU + {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Debug_VK|x64.Build.0 = Debug|Any CPU {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Debug|Any CPU.Build.0 = Debug|Any CPU + {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Debug|x64.ActiveCfg = Debug|Any CPU + {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Debug|x64.Build.0 = Debug|Any CPU + {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Release_VK|Any CPU.ActiveCfg = Release|Any CPU + {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Release_VK|Any CPU.Build.0 = Release|Any CPU + {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Release_VK|x64.ActiveCfg = Release|Any CPU + {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Release_VK|x64.Build.0 = Release|Any CPU {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Release|Any CPU.ActiveCfg = Release|Any CPU {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Release|Any CPU.Build.0 = Release|Any CPU + {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Release|x64.ActiveCfg = Release|Any CPU + {56BA741D-6AF1-489B-AB00-338DE11B1D32}.Release|x64.Build.0 = Release|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Debug_VK|Any CPU.ActiveCfg = Debug|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Debug_VK|Any CPU.Build.0 = Debug|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Debug_VK|x64.ActiveCfg = Debug|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Debug_VK|x64.Build.0 = Debug|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Debug|Any CPU.Build.0 = Debug|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Debug|x64.ActiveCfg = Debug|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Debug|x64.Build.0 = Debug|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Release_VK|Any CPU.ActiveCfg = Release|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Release_VK|Any CPU.Build.0 = Release|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Release_VK|x64.ActiveCfg = Release|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Release_VK|x64.Build.0 = Release|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Release|Any CPU.ActiveCfg = Release|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Release|Any CPU.Build.0 = Release|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Release|x64.ActiveCfg = Release|Any CPU + {74F12E34-D96B-4EC1-A218-BAFC83DC6220}.Release|x64.Build.0 = Release|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Debug_VK|Any CPU.ActiveCfg = Debug|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Debug_VK|Any CPU.Build.0 = Debug|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Debug_VK|x64.ActiveCfg = Debug|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Debug_VK|x64.Build.0 = Debug|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Debug|x64.ActiveCfg = Debug|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Debug|x64.Build.0 = Debug|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Release_VK|Any CPU.ActiveCfg = Release|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Release_VK|Any CPU.Build.0 = Release|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Release_VK|x64.ActiveCfg = Release|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Release_VK|x64.Build.0 = Release|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Release|Any CPU.Build.0 = Release|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Release|x64.ActiveCfg = Release|Any CPU + {C670BF60-56F7-493F-B5DD-50F97DB80A04}.Release|x64.Build.0 = Release|Any CPU + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Debug_VK|Any CPU.ActiveCfg = Debug|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Debug_VK|Any CPU.Build.0 = Debug|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Debug_VK|x64.ActiveCfg = Debug|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Debug_VK|x64.Build.0 = Debug|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Debug|Any CPU.ActiveCfg = Debug|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Debug|Any CPU.Build.0 = Debug|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Debug|x64.ActiveCfg = Debug|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Debug|x64.Build.0 = Debug|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Release_VK|Any CPU.ActiveCfg = Release|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Release_VK|Any CPU.Build.0 = Release|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Release_VK|x64.ActiveCfg = Release|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Release_VK|x64.Build.0 = Release|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Release|Any CPU.ActiveCfg = Release|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Release|Any CPU.Build.0 = Release|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Release|x64.ActiveCfg = Release|x64 + {60D6243F-CC40-D9B5-157F-8A5B8128B70A}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {74F12E34-D96B-4EC1-A218-BAFC83DC6220} = {65B3DC17-24BA-4C39-810F-E371AC48199A} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {CDA9FB22-5A50-47C6-B732-CE09AC673DCA} EndGlobalSection EndGlobal diff --git a/MonoGame.Framework/Audio/SoundEffectInstance.cs b/MonoGame.Framework/Audio/SoundEffectInstance.cs index 2983daae51a..3985a154458 100644 --- a/MonoGame.Framework/Audio/SoundEffectInstance.cs +++ b/MonoGame.Framework/Audio/SoundEffectInstance.cs @@ -19,14 +19,15 @@ public partial class SoundEffectInstance : IDisposable internal SoundEffect _effect; private float _pan; private float _volume; - private float _pitch; + private float _pitch; + private bool _isLooped; /// Enables or Disables whether the SoundEffectInstance should repeat after playback. /// This value has no effect on an already playing sound. public virtual bool IsLooped - { - get { return PlatformGetIsLooped(); } - set { PlatformSetIsLooped(value); } + { + get { return _isLooped; } + set { _isLooped = value; } } /// Gets or sets the pan, or speaker balance.. @@ -94,13 +95,8 @@ internal SoundEffectInstance() { _pan = 0.0f; _volume = 1.0f; - _pitch = 0.0f; - } - - internal SoundEffectInstance(byte[] buffer, int sampleRate, int channels) - : this() - { - PlatformInitialize(buffer, sampleRate, channels); + _pitch = 0.0f; + _isLooped = false; } /// @@ -142,11 +138,13 @@ public virtual void Play() { if (_isDisposed) throw new ObjectDisposedException("SoundEffectInstance"); + + var state = State; - if (State == SoundState.Playing) + if (state == SoundState.Playing) return; - if (State == SoundState.Paused) + if (state == SoundState.Paused) { Resume(); return; @@ -154,7 +152,7 @@ public virtual void Play() // We don't need to check if we're at the instance play limit // if we're resuming from a paused state. - if (State != SoundState.Paused) + if (state != SoundState.Paused) { if (!SoundEffectInstancePool.SoundsAvailable) throw new InstancePlayLimitException(); diff --git a/MonoGame.Framework/Content/ContentManager.cs b/MonoGame.Framework/Content/ContentManager.cs index 422945888c0..41f5aaec1f9 100644 --- a/MonoGame.Framework/Content/ContentManager.cs +++ b/MonoGame.Framework/Content/ContentManager.cs @@ -49,6 +49,7 @@ public partial class ContentManager : IDisposable 'O', // XboxOne 'S', // Nintendo Switch 'b', // WebAssembly and Bridge.NET + 'V', // DesktopVK // NOTE: There are additional identifiers for consoles that // are not defined in this repository. Be sure to ask the diff --git a/MonoGame.Framework/Game.cs b/MonoGame.Framework/Game.cs index ff77b289709..0ccfd8dc2c4 100644 --- a/MonoGame.Framework/Game.cs +++ b/MonoGame.Framework/Game.cs @@ -672,7 +672,7 @@ protected virtual void UnloadContent() { } protected virtual void Initialize() { // TODO: This should be removed once all platforms use the new GraphicsDeviceManager -#if !(WINDOWS && DIRECTX) +#if !(WINDOWS && DIRECTX) && !NATIVE applyChanges(graphicsDeviceManager); #endif @@ -791,7 +791,7 @@ private void Platform_AsyncRunLoopEnded(object sender, EventArgs e) // break entirely the possibility that additional platforms could // be added by third parties without changing MonoGame itself. -#if !(WINDOWS && DIRECTX) +#if !(WINDOWS && DIRECTX) && !NATIVE internal void applyChanges(GraphicsDeviceManager manager) { Platform.BeginScreenDeviceChange(GraphicsDevice.PresentationParameters.IsFullScreen); diff --git a/MonoGame.Framework/GameWindow.cs b/MonoGame.Framework/GameWindow.cs index f48a934af1a..01ed723b38c 100644 --- a/MonoGame.Framework/GameWindow.cs +++ b/MonoGame.Framework/GameWindow.cs @@ -34,13 +34,13 @@ public abstract class GameWindow /// public virtual bool AllowAltF4 { get { return _allowAltF4; } set { _allowAltF4 = value; } } -#if WINDOWS || DESKTOPGL /// /// The location of this window on the desktop, eg: global coordinate space /// which stretches across all screens. + /// + /// May be zero on platforms where it is not supported. /// public abstract Point Position { get; set; } -#endif /// /// The display orientation on a mobile device. @@ -123,7 +123,7 @@ protected GameWindow() /// public event EventHandler ScreenDeviceNameChanged; -#if WINDOWS || DESKTOPGL|| ANGLE +#if WINDOWS || DESKTOPGL|| ANGLE || NATIVE /// /// Use this event to user text input. @@ -228,7 +228,8 @@ protected void OnScreenDeviceNameChanged () EventHelpers.Raise(this, ScreenDeviceNameChanged, EventArgs.Empty); } -#if WINDOWS || DESKTOPGL || ANGLE +#if WINDOWS || DESKTOPGL || ANGLE || NATIVE + /// /// Called when the window receives text input. Raises the event. /// diff --git a/MonoGame.Framework/Graphics/Effect/EffectResource.cs b/MonoGame.Framework/Graphics/Effect/EffectResource.cs index 7ba1d9f9d4d..15c70ce711a 100644 --- a/MonoGame.Framework/Graphics/Effect/EffectResource.cs +++ b/MonoGame.Framework/Graphics/Effect/EffectResource.cs @@ -39,19 +39,26 @@ public byte[] Bytecode if (_bytecode != null) return _bytecode; - var assembly = ReflectionHelpers.GetAssembly(typeof(EffectResource)); - - var stream = assembly.GetManifestResourceStream(_name); - using (var ms = new MemoryStream()) - { - stream.CopyTo(ms); - _bytecode = ms.ToArray(); - } + _bytecode = PlatformGetBytecode(_name); } } return _bytecode; } } + +#if !NATIVE + private static byte[] PlatformGetBytecode(string name) + { + var assembly = ReflectionHelpers.GetAssembly(typeof(EffectResource)); + + var stream = assembly.GetManifestResourceStream(name); + using (var ms = new MemoryStream()) + { + stream.CopyTo(ms); + return ms.ToArray(); + } + } +#endif } } diff --git a/MonoGame.Framework/Graphics/GraphicsDevice.cs b/MonoGame.Framework/Graphics/GraphicsDevice.cs index c90df5efdf6..f7f95cc37ab 100644 --- a/MonoGame.Framework/Graphics/GraphicsDevice.cs +++ b/MonoGame.Framework/Graphics/GraphicsDevice.cs @@ -1,1665 +1,1665 @@ -// MonoGame - Copyright (C) MonoGame Foundation, Inc -// This file is subject to the terms and conditions defined in -// file 'LICENSE.txt', which is part of this source code package. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using MonoGame.Framework.Utilities; -using System.Runtime.InteropServices; - - -namespace Microsoft.Xna.Framework.Graphics -{ - /// - /// Performs primitive-based rendering, creates resources, - /// handles system-level variables, adjusts gamma ramp levels, and creates shaders. - /// - public partial class GraphicsDevice : IDisposable - { - /// - /// Indicates if DX9 style pixel addressing or current standard - /// pixel addressing should be used. This flag is set to - /// false by default. If `UseHalfPixelOffset` is - /// `true` you have to add half-pixel offset to a Projection matrix. - /// See also . - /// - /// - /// XNA uses DirectX9 for its graphics. DirectX9 interprets UV - /// coordinates differently from other graphics API's. This is - /// typically referred to as the half-pixel offset. MonoGame - /// replicates XNA behavior if this flag is set to true. - /// - public bool UseHalfPixelOffset { get; private set; } - - private Viewport _viewport; - - private bool _isDisposed; - - // On Intel Integrated graphics, there is a fast hw unit for doing - // clears to colors where all components are either 0 or 255. - // Despite XNA4 using Purple here, we use black (in Release) to avoid - // performance warnings on Intel/Mesa -#if DEBUG - private static Color _discardColor = new Color(68, 34, 136, 255); -#else - private static Color _discardColor = new Color(0, 0, 0, 255); -#endif - - private Color _blendFactor = Color.White; - private bool _blendFactorDirty; - - private BlendState _blendState; - private BlendState _actualBlendState; - private bool _blendStateDirty; - - private BlendState _blendStateAdditive; - private BlendState _blendStateAlphaBlend; - private BlendState _blendStateNonPremultiplied; - private BlendState _blendStateOpaque; - - private DepthStencilState _depthStencilState; - private DepthStencilState _actualDepthStencilState; - private bool _depthStencilStateDirty; - - private DepthStencilState _depthStencilStateDefault; - private DepthStencilState _depthStencilStateDepthRead; - private DepthStencilState _depthStencilStateNone; - - private RasterizerState _rasterizerState; - private RasterizerState _actualRasterizerState; - private bool _rasterizerStateDirty; - - private RasterizerState _rasterizerStateCullClockwise; - private RasterizerState _rasterizerStateCullCounterClockwise; - private RasterizerState _rasterizerStateCullNone; - - private Rectangle _scissorRectangle; - private bool _scissorRectangleDirty; - - private VertexBufferBindings _vertexBuffers; - private bool _vertexBuffersDirty; - - private IndexBuffer _indexBuffer; - private bool _indexBufferDirty; - - private readonly RenderTargetBinding[] _currentRenderTargetBindings = new RenderTargetBinding[8]; - private int _currentRenderTargetCount; - private readonly RenderTargetBinding[] _tempRenderTargetBinding = new RenderTargetBinding[1]; - - internal GraphicsCapabilities GraphicsCapabilities { get; private set; } - - /// - /// Gets the collection of vertex textures that support texture lookup - /// in the vertex shader using the texldl statement. - /// The vertex engine contains four texture sampler stages. - /// - public TextureCollection VertexTextures { get; private set; } - - /// - /// Returns the collection of vertex sampler states. - /// - public SamplerStateCollection VertexSamplerStates { get; private set; } - - /// - /// Returns the collection of textures that have been assigned to the texture stages of the device. - /// - public TextureCollection Textures { get; private set; } - - /// - /// Retrieves a collection of objects for the current . - /// - public SamplerStateCollection SamplerStates { get; private set; } - - /// - /// Get or set the color a is cleared to when it is set. - /// - public static Color DiscardColor { - get { return _discardColor; } - set { _discardColor = value; } - } - - /// - /// The active vertex shader. - /// - private Shader _vertexShader; - private bool _vertexShaderDirty; - private bool VertexShaderDirty - { - get { return _vertexShaderDirty; } - } - - /// - /// The active pixel shader. - /// - private Shader _pixelShader; - private bool _pixelShaderDirty; - private bool PixelShaderDirty - { - get { return _pixelShaderDirty; } - } - - private readonly ConstantBufferCollection _vertexConstantBuffers = new ConstantBufferCollection(ShaderStage.Vertex, 16); - private readonly ConstantBufferCollection _pixelConstantBuffers = new ConstantBufferCollection(ShaderStage.Pixel, 16); - - /// - /// The cache of effects from unique byte streams. - /// - internal Dictionary EffectCache; - - // Resources may be added to and removed from the list from many threads. - private readonly object _resourcesLock = new object(); - - // Use WeakReference for the global resources list as we do not know when a resource - // may be disposed and collected. We do not want to prevent a resource from being - // collected by holding a strong reference to it in this list. - private readonly List _resources = new List(); - - // TODO Graphics Device events need implementing - /// - /// Occurs when a GraphicsDevice is about to be lost (for example, immediately before a reset). - /// - public event EventHandler DeviceLost; - - /// - /// Occurs after a GraphicsDevice is reset, allowing an application to recreate all resources. - /// - public event EventHandler DeviceReset; - - /// - /// Occurs when a GraphicsDevice is resetting, - /// allowing the application to cancel the default handling of the reset. - /// - public event EventHandler DeviceResetting; - - /// - /// Occurs when a resource is created. - /// - public event EventHandler ResourceCreated; - - /// - /// Occurs when a resource is destroyed. - /// - public event EventHandler ResourceDestroyed; - - /// - /// Occurs when is called - /// or when this object is finalized and collected by the garbage collector. - /// - public event EventHandler Disposing; - - internal event EventHandler PresentationChanged; - - private int _maxVertexBufferSlots; - internal int MaxTextureSlots; - internal int MaxVertexTextureSlots; - - /// - /// Gets a value that indicates whether the object is disposed. - /// - public bool IsDisposed - { - get - { - return _isDisposed; - } - } - - /// - /// Gets a value that indicates whether the associated content was lost. - /// - public bool IsContentLost { - get { - // We will just return IsDisposed for now - // as that is the only case I can see for now - return IsDisposed; - } - } - - internal bool IsRenderTargetBound - { - get - { - return _currentRenderTargetCount > 0; - } - } - - internal DepthFormat ActiveDepthFormat - { - get - { - return IsRenderTargetBound - ? _currentRenderTargetBindings[0].DepthFormat - : PresentationParameters.DepthStencilFormat; - } - } - - /// - /// Gets the graphics adapter. - /// - public GraphicsAdapter Adapter - { - get; - private set; - } - - internal GraphicsMetrics _graphicsMetrics; - - /// - /// The rendering information for debugging and profiling. - /// The metrics are reset every frame after draw within . - /// - public GraphicsMetrics Metrics { get { return _graphicsMetrics; } set { _graphicsMetrics = value; } } - - private GraphicsDebug _graphicsDebug; - - /// - /// Access debugging APIs for the graphics subsystem. - /// - public GraphicsDebug GraphicsDebug { get { return _graphicsDebug; } set { _graphicsDebug = value; } } - - internal GraphicsDevice() - { - PresentationParameters = new PresentationParameters(); - PresentationParameters.DepthStencilFormat = DepthFormat.Depth24; - Setup(); - GraphicsCapabilities = new GraphicsCapabilities(); - GraphicsCapabilities.Initialize(this); - Initialize(); - } - - /// - /// Initializes a new instance of the class. - /// - /// The graphics adapter. - /// The graphics profile. - /// The presentation options. - /// - /// is . - /// - public GraphicsDevice(GraphicsAdapter adapter, GraphicsProfile graphicsProfile, PresentationParameters presentationParameters) - { - if (adapter == null) - throw new ArgumentNullException("adapter"); - if (!adapter.IsProfileSupported(graphicsProfile)) - throw new NoSuitableGraphicsDeviceException(String.Format("Adapter '{0}' does not support the {1} profile.", adapter.Description, graphicsProfile)); - if (presentationParameters == null) - throw new ArgumentNullException("presentationParameters"); - Adapter = adapter; - PresentationParameters = presentationParameters; - _graphicsProfile = graphicsProfile; - Setup(); - GraphicsCapabilities = new GraphicsCapabilities(); - GraphicsCapabilities.Initialize(this); - - Initialize(); - } - - /// - /// Initializes a new instance of the class. - /// - /// The graphics adapter. - /// The graphics profile. - /// Indicates if DX9 style pixel addressing or current standard pixel addressing should be used. This value is passed to - /// The presentation options. - /// - /// is . - /// - public GraphicsDevice(GraphicsAdapter adapter, GraphicsProfile graphicsProfile, bool preferHalfPixelOffset, PresentationParameters presentationParameters) - { - if (adapter == null) - throw new ArgumentNullException("adapter"); - if (!adapter.IsProfileSupported(graphicsProfile)) - throw new NoSuitableGraphicsDeviceException(String.Format("Adapter '{0}' does not support the {1} profile.", adapter.Description, graphicsProfile)); - if (presentationParameters == null) - throw new ArgumentNullException("presentationParameters"); -#if DIRECTX - // TODO we need to figure out how to inject the half pixel offset into DX shaders - preferHalfPixelOffset = false; -#endif - Adapter = adapter; - _graphicsProfile = graphicsProfile; - UseHalfPixelOffset = preferHalfPixelOffset; - PresentationParameters = presentationParameters; - Setup(); - GraphicsCapabilities = new GraphicsCapabilities(); - GraphicsCapabilities.Initialize(this); - - Initialize(); - } - - private void Setup() - { -#if DEBUG - if (DisplayMode == null) - { - throw new Exception( - "Unable to determine the current display mode. This can indicate that the " + - "game is not configured to be HiDPI aware under Windows 10 or later. See " + - "https://github.com/MonoGame/MonoGame/issues/5040 for more information."); - } -#endif - - // Initialize the main viewport - _viewport = new Viewport (0, 0, DisplayMode.Width, DisplayMode.Height); - _viewport.MaxDepth = 1.0f; - - PlatformSetup(); - - VertexTextures = new TextureCollection(this, MaxVertexTextureSlots, true); - VertexSamplerStates = new SamplerStateCollection(this, MaxVertexTextureSlots, true); - - Textures = new TextureCollection(this, MaxTextureSlots, false); - SamplerStates = new SamplerStateCollection(this, MaxTextureSlots, false); - - _blendStateAdditive = BlendState.Additive.Clone(); - _blendStateAlphaBlend = BlendState.AlphaBlend.Clone(); - _blendStateNonPremultiplied = BlendState.NonPremultiplied.Clone(); - _blendStateOpaque = BlendState.Opaque.Clone(); - - BlendState = BlendState.Opaque; - - _depthStencilStateDefault = DepthStencilState.Default.Clone(); - _depthStencilStateDepthRead = DepthStencilState.DepthRead.Clone(); - _depthStencilStateNone = DepthStencilState.None.Clone(); - - DepthStencilState = DepthStencilState.Default; - - _rasterizerStateCullClockwise = RasterizerState.CullClockwise.Clone(); - _rasterizerStateCullCounterClockwise = RasterizerState.CullCounterClockwise.Clone(); - _rasterizerStateCullNone = RasterizerState.CullNone.Clone(); - - RasterizerState = RasterizerState.CullCounterClockwise; - - EffectCache = new Dictionary(); - } - - /// - ~GraphicsDevice() - { - Dispose(false); - } - - internal int GetClampedMultisampleCount(int multiSampleCount) - { - if (multiSampleCount > 1) - { - // Round down MultiSampleCount to the nearest power of two - // hack from http://stackoverflow.com/a/2681094 - // Note: this will return an incorrect, but large value - // for very large numbers. That doesn't matter because - // the number will get clamped below anyway in this case. - var msc = multiSampleCount; - msc = msc | (msc >> 1); - msc = msc | (msc >> 2); - msc = msc | (msc >> 4); - msc -= (msc >> 1); - // and clamp it to what the device can handle - if (msc > GraphicsCapabilities.MaxMultiSampleCount) - msc = GraphicsCapabilities.MaxMultiSampleCount; - - return msc; - } - else return 0; - } - - internal void Initialize() - { - PlatformInitialize(); - - // Force set the default render states. - _blendStateDirty = _depthStencilStateDirty = _rasterizerStateDirty = true; - BlendState = BlendState.Opaque; - DepthStencilState = DepthStencilState.Default; - RasterizerState = RasterizerState.CullCounterClockwise; - - // Clear the texture and sampler collections forcing - // the state to be reapplied. - VertexTextures.Clear(); - VertexSamplerStates.Clear(); - Textures.Clear(); - SamplerStates.Clear(); - - // Clear constant buffers - _vertexConstantBuffers.Clear(); - _pixelConstantBuffers.Clear(); - - // Force set the buffers and shaders on next ApplyState() call - _vertexBuffers = new VertexBufferBindings(_maxVertexBufferSlots); - _vertexBuffersDirty = true; - _indexBufferDirty = true; - _vertexShaderDirty = true; - _pixelShaderDirty = true; - - // Set the default scissor rect. - _scissorRectangleDirty = true; - ScissorRectangle = _viewport.Bounds; - - // Set the default render target. - ApplyRenderTargets(null); - } - - /// - /// Gets or sets rasterizer state. - /// The default value is . - /// - public RasterizerState RasterizerState - { - get - { - return _rasterizerState; - } - - set - { - if (value == null) - throw new ArgumentNullException("value"); - - // Don't set the same state twice! - if (_rasterizerState == value) - return; - - if (!value.DepthClipEnable && !GraphicsCapabilities.SupportsDepthClamp) - throw new InvalidOperationException("Cannot set RasterizerState.DepthClipEnable to false on this graphics device"); - - _rasterizerState = value; - - // Static state properties never actually get bound; - // instead we use our GraphicsDevice-specific version of them. - var newRasterizerState = _rasterizerState; - if (ReferenceEquals(_rasterizerState, RasterizerState.CullClockwise)) - newRasterizerState = _rasterizerStateCullClockwise; - else if (ReferenceEquals(_rasterizerState, RasterizerState.CullCounterClockwise)) - newRasterizerState = _rasterizerStateCullCounterClockwise; - else if (ReferenceEquals(_rasterizerState, RasterizerState.CullNone)) - newRasterizerState = _rasterizerStateCullNone; - - newRasterizerState.BindToGraphicsDevice(this); - - _actualRasterizerState = newRasterizerState; - - _rasterizerStateDirty = true; - } - } - - /// - /// The color used as blend factor when alpha blending. - /// - /// - /// When only changing BlendFactor, use this rather than to - /// only update BlendFactor so the whole BlendState does not have to be updated. - /// - public Color BlendFactor - { - get { return _blendFactor; } - set - { - if (_blendFactor == value) - return; - _blendFactor = value; - _blendFactorDirty = true; - } - } - - /// - /// Gets or sets a system-defined instance of a blend state object initialized for alpha blending. - /// The default value is . - /// - public BlendState BlendState - { - get { return _blendState; } - set - { - if (value == null) - throw new ArgumentNullException("value"); - - // Don't set the same state twice! - if (_blendState == value) - return; - - _blendState = value; - - // Static state properties never actually get bound; - // instead we use our GraphicsDevice-specific version of them. - var newBlendState = _blendState; - if (ReferenceEquals(_blendState, BlendState.Additive)) - newBlendState = _blendStateAdditive; - else if (ReferenceEquals(_blendState, BlendState.AlphaBlend)) - newBlendState = _blendStateAlphaBlend; - else if (ReferenceEquals(_blendState, BlendState.NonPremultiplied)) - newBlendState = _blendStateNonPremultiplied; - else if (ReferenceEquals(_blendState, BlendState.Opaque)) - newBlendState = _blendStateOpaque; - - if (newBlendState.IndependentBlendEnable && !GraphicsCapabilities.SupportsSeparateBlendStates) - throw new PlatformNotSupportedException("Independent blend states requires at least OpenGL 4.0 or GL_ARB_draw_buffers_blend. Try upgrading your graphics drivers."); - - // Blend state is now bound to a device... no one should - // be changing the state of the blend state object now! - newBlendState.BindToGraphicsDevice(this); - - _actualBlendState = newBlendState; - - BlendFactor = _actualBlendState.BlendFactor; - - _blendStateDirty = true; - } - } - - /// - /// Gets or sets a system-defined instance of a depth-stencil state object. - /// The default value is . - /// - public DepthStencilState DepthStencilState - { - get { return _depthStencilState; } - set - { - if (value == null) - throw new ArgumentNullException("value"); - - // Don't set the same state twice! - if (_depthStencilState == value) - return; - - _depthStencilState = value; - - // Static state properties never actually get bound; - // instead we use our GraphicsDevice-specific version of them. - var newDepthStencilState = _depthStencilState; - if (ReferenceEquals(_depthStencilState, DepthStencilState.Default)) - newDepthStencilState = _depthStencilStateDefault; - else if (ReferenceEquals(_depthStencilState, DepthStencilState.DepthRead)) - newDepthStencilState = _depthStencilStateDepthRead; - else if (ReferenceEquals(_depthStencilState, DepthStencilState.None)) - newDepthStencilState = _depthStencilStateNone; - - newDepthStencilState.BindToGraphicsDevice(this); - - _actualDepthStencilState = newDepthStencilState; - - _depthStencilStateDirty = true; - } - } - - internal void ApplyState(bool applyShaders) - { - PlatformBeginApplyState(); - - PlatformApplyBlend(); - - if (_depthStencilStateDirty) - { - _actualDepthStencilState.PlatformApplyState(this); - _depthStencilStateDirty = false; - } - - if (_rasterizerStateDirty) - { - _actualRasterizerState.PlatformApplyState(this); - _rasterizerStateDirty = false; - } - - PlatformApplyState(applyShaders); - } - - /// - /// Clears resource buffers. - /// - /// Set this color value in all buffers. - public void Clear(Color color) - { - var options = ClearOptions.Target; - options |= ClearOptions.DepthBuffer; - options |= ClearOptions.Stencil; - PlatformClear(options, color.ToVector4(), _viewport.MaxDepth, 0); - - unchecked - { - _graphicsMetrics._clearCount++; - } - } - - /// - /// Clears resource buffers. - /// - /// Options for clearing a buffer. - /// Set this color value in all buffers. - /// Set this depth value in the buffer. - /// Set this stencil value in the buffer. - public void Clear(ClearOptions options, Color color, float depth, int stencil) - { - PlatformClear(options, color.ToVector4(), depth, stencil); - - unchecked - { - _graphicsMetrics._clearCount++; - } - } - - /// - /// Clears resource buffers. - /// - /// Options for clearing a buffer. - /// Set this color value in all buffers. - /// Set this depth value in the buffer. - /// Set this stencil value in the buffer. - public void Clear(ClearOptions options, Vector4 color, float depth, int stencil) - { - PlatformClear(options, color, depth, stencil); - - unchecked - { - _graphicsMetrics._clearCount++; - } - } - - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - protected virtual void Dispose(bool disposing) - { - if (!_isDisposed) - { - if (disposing) - { - // Dispose of all remaining graphics resources before disposing of the graphics device - lock (_resourcesLock) - { - foreach (var resource in _resources.ToArray()) - { - var target = resource.Target as IDisposable; - if (target != null) - target.Dispose(); - } - _resources.Clear(); - } - - // Clear the effect cache. - EffectCache.Clear(); - - _blendState = null; - _actualBlendState = null; - _blendStateAdditive.Dispose(); - _blendStateAlphaBlend.Dispose(); - _blendStateNonPremultiplied.Dispose(); - _blendStateOpaque.Dispose(); - - _depthStencilState = null; - _actualDepthStencilState = null; - _depthStencilStateDefault.Dispose(); - _depthStencilStateDepthRead.Dispose(); - _depthStencilStateNone.Dispose(); - - _rasterizerState = null; - _actualRasterizerState = null; - _rasterizerStateCullClockwise.Dispose(); - _rasterizerStateCullCounterClockwise.Dispose(); - _rasterizerStateCullNone.Dispose(); - - PlatformDispose(); - } - - _isDisposed = true; - EventHelpers.Raise(this, Disposing, EventArgs.Empty); - } - } - - internal void AddResourceReference(WeakReference resourceReference) - { - lock (_resourcesLock) - { - _resources.Add(resourceReference); - } - } - - internal void RemoveResourceReference(WeakReference resourceReference) - { - lock (_resourcesLock) - { - _resources.Remove(resourceReference); - } - } - - /// - /// Presents the display with the contents of the next buffer - /// in the sequence of back buffers owned by the . - /// - /// A render target is active. - public void Present() - { - // We cannot present with a RT set on the device. - if (_currentRenderTargetCount != 0) - throw new InvalidOperationException("Cannot call Present when a render target is active."); - - _graphicsMetrics = new GraphicsMetrics(); - PlatformPresent(); - } - - /* - public void Present(Rectangle? sourceRectangle, Rectangle? destinationRectangle, IntPtr overrideWindowHandle) - { - throw new NotImplementedException(); - } - */ - - partial void PlatformReset(); - - /// - /// Resets the presentation parameters for the current . - /// - public void Reset() - { - PlatformReset(); - - EventHelpers.Raise(this, DeviceResetting, EventArgs.Empty); - - // Update the back buffer. - OnPresentationChanged(); - - EventHelpers.Raise(this, PresentationChanged, new PresentationEventArgs(PresentationParameters)); - EventHelpers.Raise(this, DeviceReset, EventArgs.Empty); - } - - /// - /// Resets the current with the specified . - /// - /// Presentation parameters to set. - /// - /// is - /// - public void Reset(PresentationParameters presentationParameters) - { - if (presentationParameters == null) - throw new ArgumentNullException("presentationParameters"); - - PresentationParameters = presentationParameters; - Reset(); - } - - /// - /// Trigger the DeviceResetting event - /// Currently internal to allow the various platforms to send the event at the appropriate time. - /// - internal void OnDeviceResetting() - { - EventHelpers.Raise(this, DeviceResetting, EventArgs.Empty); - - lock (_resourcesLock) - { - foreach (var resource in _resources) - { - var target = resource.Target as GraphicsResource; - if (target != null) - target.GraphicsDeviceResetting(); - } - - // Remove references to resources that have been garbage collected. - _resources.RemoveAll(wr => !wr.IsAlive); - } - } - - /// - /// Trigger the DeviceReset event to allow games to be notified of a device reset. - /// Currently internal to allow the various platforms to send the event at the appropriate time. - /// - internal void OnDeviceReset() - { - EventHelpers.Raise(this, DeviceReset, EventArgs.Empty); - } - - /// - /// Retrieves the display mode's spatial resolution, color resolution, and refresh frequency. - /// - public DisplayMode DisplayMode - { - get - { - return Adapter.CurrentDisplayMode; - } - } - - /// - /// Retrieves the status of the device. - /// - public GraphicsDeviceStatus GraphicsDeviceStatus - { - get - { - return GraphicsDeviceStatus.Normal; - } - } - - /// - /// Gets the presentation parameters associated with this graphics device. - /// - public PresentationParameters PresentationParameters - { - get; - private set; - } - - /// - /// Gets or sets a viewport identifying the portion of the render target to receive draw calls. - /// - public Viewport Viewport - { - get - { - return _viewport; - } - - set - { - _viewport = value; - PlatformSetViewport(ref value); - } - } - - private readonly GraphicsProfile _graphicsProfile; - /// - /// Gets the graphics profile. - /// The default value is . - /// - public GraphicsProfile GraphicsProfile - { - get { return _graphicsProfile; } - } - - /// - /// Gets or sets the rectangle used for scissor testing. By default, the size matches the render target size. - /// - public Rectangle ScissorRectangle - { - get - { - return _scissorRectangle; - } - - set - { - if (_scissorRectangle == value) - return; - - _scissorRectangle = value; - _scissorRectangleDirty = true; - } - } - - /// - /// Gets the amount of render targets bound to this device. - /// - public int RenderTargetCount - { - get - { - return _currentRenderTargetCount; - } - } - - /// - /// Sets a new render target for this . - /// - /// - /// A new render target for the device, or - /// to set the device render target to the back buffer of the device. - /// - public void SetRenderTarget(RenderTarget2D renderTarget) - { - if (renderTarget == null) - { - SetRenderTargets(null); - } - else - { - _tempRenderTargetBinding[0] = new RenderTargetBinding(renderTarget); - SetRenderTargets(_tempRenderTargetBinding); - } - } - - /// - /// Sets a new render target for this . - /// - /// - /// A new render target for the device, or - /// to set the device render target to the back buffer of the device. - /// - /// The cube map face type. - public void SetRenderTarget(RenderTargetCube renderTarget, CubeMapFace cubeMapFace) - { - if (renderTarget == null) - { - SetRenderTargets(null); - } - else - { - _tempRenderTargetBinding[0] = new RenderTargetBinding(renderTarget, cubeMapFace); - SetRenderTargets(_tempRenderTargetBinding); - } - } - - /// - /// Sets an array of render targets. - /// - /// An array of render targets. - public void SetRenderTargets(params RenderTargetBinding[] renderTargets) - { - // Avoid having to check for null and zero length. - var renderTargetCount = 0; - if (renderTargets != null) - { - renderTargetCount = renderTargets.Length; - if (renderTargetCount == 0) - { - renderTargets = null; - } - } - - // Try to early out if the current and new bindings are equal. - if (_currentRenderTargetCount == renderTargetCount) - { - var isEqual = true; - for (var i = 0; i < _currentRenderTargetCount; i++) - { - if (_currentRenderTargetBindings[i].RenderTarget != renderTargets[i].RenderTarget || - _currentRenderTargetBindings[i].ArraySlice != renderTargets[i].ArraySlice) - { - isEqual = false; - break; - } - } - - if (isEqual) - return; - } - - ApplyRenderTargets(renderTargets); - - if (renderTargetCount == 0) - { - unchecked - { - _graphicsMetrics._targetCount++; - } - } - else - { - unchecked - { - _graphicsMetrics._targetCount += renderTargetCount; - } - } - } - - internal void ApplyRenderTargets(RenderTargetBinding[] renderTargets) - { - var clearTarget = false; - - PlatformResolveRenderTargets(); - - // Clear the current bindings. - Array.Clear(_currentRenderTargetBindings, 0, _currentRenderTargetBindings.Length); - - int renderTargetWidth; - int renderTargetHeight; - if (renderTargets == null) - { - _currentRenderTargetCount = 0; - - PlatformApplyDefaultRenderTarget(); - clearTarget = PresentationParameters.RenderTargetUsage == RenderTargetUsage.DiscardContents; - - renderTargetWidth = PresentationParameters.BackBufferWidth; - renderTargetHeight = PresentationParameters.BackBufferHeight; - } - else - { - // Copy the new bindings. - Array.Copy(renderTargets, _currentRenderTargetBindings, renderTargets.Length); - _currentRenderTargetCount = renderTargets.Length; - - var renderTarget = PlatformApplyRenderTargets(); - - // We clear the render target if asked. - clearTarget = renderTarget.RenderTargetUsage == RenderTargetUsage.DiscardContents; - - renderTargetWidth = renderTarget.Width; - renderTargetHeight = renderTarget.Height; - } - - // Set the viewport to the size of the first render target. - Viewport = new Viewport(0, 0, renderTargetWidth, renderTargetHeight); - - // Set the scissor rectangle to the size of the first render target. - ScissorRectangle = new Rectangle(0, 0, renderTargetWidth, renderTargetHeight); - - // In XNA 4, because of hardware limitations on Xbox, when - // a render target doesn't have PreserveContents as its usage - // it is cleared before being rendered to. - if (clearTarget) - Clear(DiscardColor); - } - - /// - /// Gets render target surfaces. - /// - /// An array of bound render targets. - public RenderTargetBinding[] GetRenderTargets() - { - // Return a correctly sized copy our internal array. - var bindings = new RenderTargetBinding[_currentRenderTargetCount]; - Array.Copy(_currentRenderTargetBindings, bindings, _currentRenderTargetCount); - return bindings; - } - - /// - /// Gets render target surfaces. - /// - /// - /// When this method returns, contains an array of that description of bound render targets. - /// This parameter is treated as uninitialized. - /// - public void GetRenderTargets(RenderTargetBinding[] outTargets) - { - Debug.Assert(outTargets.Length == _currentRenderTargetCount, "Invalid outTargets array length!"); - Array.Copy(_currentRenderTargetBindings, outTargets, _currentRenderTargetCount); - } - - /// - /// Sets or binds a vertex buffer to a device. - /// - /// A vertex buffer. - public void SetVertexBuffer(VertexBuffer vertexBuffer) - { - _vertexBuffersDirty |= (vertexBuffer == null) - ? _vertexBuffers.Clear() - : _vertexBuffers.Set(vertexBuffer, 0); - } - - /// - /// Sets or binds a vertex buffer to a device. - /// - /// A vertex buffer. - /// The offset (in bytes) from the beginning of the buffer. - /// - /// is less than 0 - /// OR is greater than or equal to .VertexCount. - /// - public void SetVertexBuffer(VertexBuffer vertexBuffer, int vertexOffset) - { - // Validate vertexOffset. - if (vertexOffset < 0 - || vertexBuffer == null && vertexOffset != 0 - || vertexBuffer != null && vertexOffset >= vertexBuffer.VertexCount) - { - throw new ArgumentOutOfRangeException("vertexOffset"); - } - - _vertexBuffersDirty |= (vertexBuffer == null) - ? _vertexBuffers.Clear() - : _vertexBuffers.Set(vertexBuffer, vertexOffset); - } - - /// - /// Sets the vertex buffers. - /// - /// An array of vertex buffers. - /// - /// Length of is more than max allowed number of vertex buffers. - /// - public void SetVertexBuffers(params VertexBufferBinding[] vertexBuffers) - { - if (vertexBuffers == null || vertexBuffers.Length == 0) - { - _vertexBuffersDirty |= _vertexBuffers.Clear(); - } - else - { - if (vertexBuffers.Length > _maxVertexBufferSlots) - { - var message = string.Format(CultureInfo.InvariantCulture, "Max number of vertex buffers is {0}.", _maxVertexBufferSlots); - throw new ArgumentOutOfRangeException("vertexBuffers", message); - } - - _vertexBuffersDirty |= _vertexBuffers.Set(vertexBuffers); - } - } - - private void SetIndexBuffer(IndexBuffer indexBuffer) - { - if (_indexBuffer == indexBuffer) - return; - - _indexBuffer = indexBuffer; - _indexBufferDirty = true; - } - - /// - /// Gets or sets index data. The default value is . - /// - public IndexBuffer Indices { set { SetIndexBuffer(value); } get { return _indexBuffer; } } - - internal Shader VertexShader - { - get { return _vertexShader; } - - set - { - if (_vertexShader == value) - return; - - _vertexShader = value; - _vertexConstantBuffers.Clear(); - _vertexShaderDirty = true; - } - } - - internal Shader PixelShader - { - get { return _pixelShader; } - - set - { - if (_pixelShader == value) - return; - - _pixelShader = value; - _pixelConstantBuffers.Clear(); - _pixelShaderDirty = true; - } - } - - internal void SetConstantBuffer(ShaderStage stage, int slot, ConstantBuffer buffer) - { - if (stage == ShaderStage.Vertex) - _vertexConstantBuffers[slot] = buffer; - else - _pixelConstantBuffers[slot] = buffer; - } - - /// - /// Gets a value that indicates whether the resources were lost. - /// - public bool ResourcesLost { get; set; } - - /// - /// Draw geometry by indexing into the vertex buffer. - /// - /// The type of primitives in the index buffer. - /// Used to offset the vertex range indexed from the vertex buffer. - /// This is unused and remains here only for XNA API compatibility. - /// This is unused and remains here only for XNA API compatibility. - /// The index within the index buffer to start drawing from. - /// The number of primitives to render from the index buffer. - /// Note that minVertexIndex and numVertices are unused in MonoGame and will be ignored. - [Obsolete("Use DrawIndexedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount) instead. In future versions this method can be removed.")] - public void DrawIndexedPrimitives(PrimitiveType primitiveType, int baseVertex, int minVertexIndex, int numVertices, int startIndex, int primitiveCount) - { - DrawIndexedPrimitives(primitiveType, baseVertex, startIndex, primitiveCount); - } - - /// - /// Draw geometry by indexing into the vertex buffer. - /// - /// The type of primitives in the index buffer. - /// Used to offset the vertex range indexed from the vertex buffer. - /// The index within the index buffer to start drawing from. - /// The number of primitives to render from the index buffer. - public void DrawIndexedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount) - { - if (_vertexShader == null) - throw new InvalidOperationException("Vertex shader must be set before calling DrawIndexedPrimitives."); - - if (_vertexBuffers.Count == 0) - throw new InvalidOperationException("Vertex buffer must be set before calling DrawIndexedPrimitives."); - - if (_indexBuffer == null) - throw new InvalidOperationException("Index buffer must be set before calling DrawIndexedPrimitives."); - - if (primitiveCount <= 0) - throw new ArgumentOutOfRangeException("primitiveCount"); - - PlatformDrawIndexedPrimitives(primitiveType, baseVertex, startIndex, primitiveCount); - - unchecked - { - _graphicsMetrics._drawCount++; - _graphicsMetrics._primitiveCount += primitiveCount; - } - } - - /// - /// Draw primitives of the specified type from the data in an array of vertices without indexing. - /// - /// The type of the vertices. - /// The type of primitives to draw with the vertices. - /// An array of vertices to draw. - /// The index in the array of the first vertex that should be rendered. - /// The number of primitives to draw. - /// The will be found by getting - /// from an instance of and cached for subsequent calls. - public void DrawUserPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int primitiveCount) where T : struct, IVertexType - { - DrawUserPrimitives(primitiveType, vertexData, vertexOffset, primitiveCount, VertexDeclarationCache.VertexDeclaration); - } - - /// - /// Draw primitives of the specified type from the data in the given array of vertices without indexing. - /// - /// The type of the vertices. - /// The type of primitives to draw with the vertices. - /// An array of vertices to draw. - /// The index in the array of the first vertex that should be rendered. - /// The number of primitives to draw. - /// The layout of the vertices. - public void DrawUserPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct - { - if (vertexData == null) - throw new ArgumentNullException("vertexData"); - - if (vertexData.Length == 0) - throw new ArgumentOutOfRangeException("vertexData"); - - if (vertexOffset < 0 || vertexOffset >= vertexData.Length) - throw new ArgumentOutOfRangeException("vertexOffset"); - - if (primitiveCount <= 0) - throw new ArgumentOutOfRangeException("primitiveCount"); - - var vertexCount = GetElementCountArray(primitiveType, primitiveCount); - - if (vertexOffset + vertexCount > vertexData.Length) - throw new ArgumentOutOfRangeException("primitiveCount"); - - if (vertexDeclaration == null) - throw new ArgumentNullException("vertexDeclaration"); - - PlatformDrawUserPrimitives(primitiveType, vertexData, vertexOffset, vertexDeclaration, vertexCount); - - unchecked - { - _graphicsMetrics._drawCount++; - _graphicsMetrics._primitiveCount += primitiveCount; - } - } - - /// - /// Draw primitives of the specified type from the currently bound vertexbuffers without indexing. - /// - /// The type of primitives to draw. - /// Index of the vertex to start at. - /// The number of primitives to draw. - public void DrawPrimitives(PrimitiveType primitiveType, int vertexStart, int primitiveCount) - { - if (_vertexShader == null) - throw new InvalidOperationException("Vertex shader must be set before calling DrawPrimitives."); - - if (_vertexBuffers.Count == 0) - throw new InvalidOperationException("Vertex buffer must be set before calling DrawPrimitives."); - - if (primitiveCount <= 0) - throw new ArgumentOutOfRangeException("primitiveCount"); - - var vertexCount = GetElementCountArray(primitiveType, primitiveCount); - - PlatformDrawPrimitives(primitiveType, vertexStart, vertexCount); - - unchecked - { - _graphicsMetrics._drawCount++; - _graphicsMetrics._primitiveCount += primitiveCount; - } - } - - /// - /// Draw primitives of the specified type by indexing into the given array of vertices with 16-bit indices. - /// - /// The type of the vertices. - /// The type of primitives to draw with the vertices. - /// An array of vertices to draw. - /// The index in the array of the first vertex to draw. - /// The index in the array of indices of the first index to use - /// The number of primitives to draw. - /// The number of vertices to draw. - /// The index data. - /// The will be found by getting - /// from an instance of and cached for subsequent calls. - /// All indices in the vertex buffer are interpreted relative to the specified . - /// For example a value of zero in the array of indices points to the vertex at index - /// in the array of vertices. - public void DrawUserIndexedPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, short[] indexData, int indexOffset, int primitiveCount) where T : struct, IVertexType - { - DrawUserIndexedPrimitives(primitiveType, vertexData, vertexOffset, numVertices, indexData, indexOffset, primitiveCount, VertexDeclarationCache.VertexDeclaration); - } - - /// - /// Draw primitives of the specified type by indexing into the given array of vertices with 16-bit indices. - /// - /// The type of the vertices. - /// The type of primitives to draw with the vertices. - /// An array of vertices to draw. - /// The index in the array of the first vertex to draw. - /// The index in the array of indices of the first index to use - /// The number of primitives to draw. - /// The number of vertices to draw. - /// The index data. - /// The layout of the vertices. - /// All indices in the vertex buffer are interpreted relative to the specified . - /// For example a value of zero in the array of indices points to the vertex at index - /// in the array of vertices. - public void DrawUserIndexedPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, short[] indexData, int indexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct - { - // These parameter checks are a duplicate of the checks in the int[] overload of DrawUserIndexedPrimitives. - // Inlined here for efficiency. - - if (vertexData == null || vertexData.Length == 0) - throw new ArgumentNullException("vertexData"); - - if (vertexOffset < 0 || vertexOffset >= vertexData.Length) - throw new ArgumentOutOfRangeException("vertexOffset"); - - if (numVertices <= 0 || numVertices > vertexData.Length) - throw new ArgumentOutOfRangeException("numVertices"); - - if (vertexOffset + numVertices > vertexData.Length) - throw new ArgumentOutOfRangeException("numVertices"); - - if (indexData == null || indexData.Length == 0) - throw new ArgumentNullException("indexData"); - - if (indexOffset < 0 || indexOffset >= indexData.Length) - throw new ArgumentOutOfRangeException("indexOffset"); - - if (primitiveCount <= 0) - throw new ArgumentOutOfRangeException("primitiveCount"); - - if (indexOffset + GetElementCountArray(primitiveType, primitiveCount) > indexData.Length) - throw new ArgumentOutOfRangeException("primitiveCount"); - - if (vertexDeclaration == null) - throw new ArgumentNullException("vertexDeclaration"); - - if (vertexDeclaration.VertexStride < ReflectionHelpers.SizeOf.Get()) - throw new ArgumentOutOfRangeException("vertexDeclaration", "Vertex stride of vertexDeclaration should be at least as big as the stride of the actual vertices."); - - PlatformDrawUserIndexedPrimitives(primitiveType, vertexData, vertexOffset, numVertices, indexData, indexOffset, primitiveCount, vertexDeclaration); - - unchecked - { - _graphicsMetrics._drawCount++; - _graphicsMetrics._primitiveCount += primitiveCount; - } - } - - /// - /// Draw primitives of the specified type by indexing into the given array of vertices with 32-bit indices. - /// - /// The type of the vertices. - /// The type of primitives to draw with the vertices. - /// An array of vertices to draw. - /// The index in the array of the first vertex to draw. - /// The index in the array of indices of the first index to use - /// The number of primitives to draw. - /// The number of vertices to draw. - /// The index data. - /// The will be found by getting - /// from an instance of and cached for subsequent calls. - /// All indices in the vertex buffer are interpreted relative to the specified . - /// For example a value of zero in the array of indices points to the vertex at index - /// in the array of vertices. - public void DrawUserIndexedPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, int[] indexData, int indexOffset, int primitiveCount) where T : struct, IVertexType - { - DrawUserIndexedPrimitives(primitiveType, vertexData, vertexOffset, numVertices, indexData, indexOffset, primitiveCount, VertexDeclarationCache.VertexDeclaration); - } - - /// - /// Draw primitives of the specified type by indexing into the given array of vertices with 32-bit indices. - /// - /// The type of the vertices. - /// The type of primitives to draw with the vertices. - /// An array of vertices to draw. - /// The index in the array of the first vertex to draw. - /// The index in the array of indices of the first index to use - /// The number of primitives to draw. - /// The number of vertices to draw. - /// The index data. - /// The layout of the vertices. - /// All indices in the vertex buffer are interpreted relative to the specified . - /// For example value of zero in the array of indices points to the vertex at index - /// in the array of vertices. - public void DrawUserIndexedPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, int[] indexData, int indexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct - { - // These parameter checks are a duplicate of the checks in the short[] overload of DrawUserIndexedPrimitives. - // Inlined here for efficiency. - - if (vertexData == null || vertexData.Length == 0) - throw new ArgumentNullException("vertexData"); - - if (vertexOffset < 0 || vertexOffset >= vertexData.Length) - throw new ArgumentOutOfRangeException("vertexOffset"); - - if (numVertices <= 0 || numVertices > vertexData.Length) - throw new ArgumentOutOfRangeException("numVertices"); - - if (vertexOffset + numVertices > vertexData.Length) - throw new ArgumentOutOfRangeException("numVertices"); - - if (indexData == null || indexData.Length == 0) - throw new ArgumentNullException("indexData"); - - if (indexOffset < 0 || indexOffset >= indexData.Length) - throw new ArgumentOutOfRangeException("indexOffset"); - - if (primitiveCount <= 0) - throw new ArgumentOutOfRangeException("primitiveCount"); - - if (indexOffset + GetElementCountArray(primitiveType, primitiveCount) > indexData.Length) - throw new ArgumentOutOfRangeException("primitiveCount"); - - if (vertexDeclaration == null) - throw new ArgumentNullException("vertexDeclaration"); - - if (vertexDeclaration.VertexStride < ReflectionHelpers.SizeOf.Get()) - throw new ArgumentOutOfRangeException("vertexDeclaration", "Vertex stride of vertexDeclaration should be at least as big as the stride of the actual vertices."); - - PlatformDrawUserIndexedPrimitives(primitiveType, vertexData, vertexOffset, numVertices, indexData, indexOffset, primitiveCount, vertexDeclaration); - - unchecked - { - _graphicsMetrics._drawCount++; - _graphicsMetrics._primitiveCount += primitiveCount; - } - } - - /// - /// Draw instanced geometry from the bound vertex buffers and index buffer. - /// - /// The type of primitives in the index buffer. - /// Used to offset the vertex range indexed from the vertex buffer. - /// This is unused and remains here only for XNA API compatibility. - /// This is unused and remains here only for XNA API compatibility. - /// The index within the index buffer to start drawing from. - /// The number of primitives in a single instance. - /// The number of instances to render. - /// Note that minVertexIndex and numVertices are unused in MonoGame and will be ignored. - [Obsolete("Use DrawInstancedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount, int instanceCount) instead. In future versions this method can be removed.")] - public void DrawInstancedPrimitives(PrimitiveType primitiveType, int baseVertex, int minVertexIndex, - int numVertices, int startIndex, int primitiveCount, int instanceCount) - { - DrawInstancedPrimitives(primitiveType, baseVertex, startIndex, primitiveCount, 0, instanceCount); - } - - /// - /// Draw instanced geometry from the bound vertex buffers and index buffer. - /// - /// The type of primitives in the index buffer. - /// Used to offset the vertex range indexed from the vertex buffer. - /// The index within the index buffer to start drawing from. - /// The number of primitives in a single instance. - /// The number of instances to render. - /// Draw geometry with data from multiple bound vertex streams at different frequencies. - public void DrawInstancedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount, int instanceCount) - { - DrawInstancedPrimitives(primitiveType, baseVertex, startIndex, primitiveCount, 0, instanceCount); - } - - /// - /// Draw instanced geometry from the bound vertex buffers and index buffer. - /// - /// The type of primitives in the index buffer. - /// Used to offset the vertex range indexed from the vertex buffer. - /// The index within the index buffer to start drawing from. - /// The number of primitives in a single instance. - /// Used to offset the instance range indexed from the instance buffer. - /// The number of instances to render. - /// Draw geometry with data from multiple bound vertex streams at different frequencies. - public void DrawInstancedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount, int baseInstance, int instanceCount) - { - if (_vertexShader == null) - throw new InvalidOperationException("Vertex shader must be set before calling DrawInstancedPrimitives."); - - if (_vertexBuffers.Count == 0) - throw new InvalidOperationException("Vertex buffer must be set before calling DrawInstancedPrimitives."); - - if (_indexBuffer == null) - throw new InvalidOperationException("Index buffer must be set before calling DrawInstancedPrimitives."); - - if (primitiveCount <= 0) - throw new ArgumentOutOfRangeException("primitiveCount"); - - PlatformDrawInstancedPrimitives(primitiveType, baseVertex, startIndex, primitiveCount, baseInstance, instanceCount); - - unchecked - { - _graphicsMetrics._drawCount++; - _graphicsMetrics._primitiveCount += (primitiveCount * instanceCount); - } - } - - /// - /// Gets the Pixel data of what is currently drawn on screen. - /// The format is whatever the current format of the backbuffer is. - /// - /// A byte[] of size (ViewPort.Width * ViewPort.Height * 4) - /// Array of data. - public void GetBackBufferData(T[] data) where T : struct - { - if (data == null) - throw new ArgumentNullException("data"); - GetBackBufferData(null, data, 0, data.Length); - } - - /// - /// Gets the Pixel data of what is currently drawn on screen. - /// The format is whatever the current format of the backbuffer is. - /// - /// A byte[] of size (ViewPort.Width * ViewPort.Height * 4) - /// Array of data. - /// The first element to use. - /// The number of elements to use. - public void GetBackBufferData(T[] data, int startIndex, int elementCount) where T : struct - { - GetBackBufferData(null, data, startIndex, elementCount); - } - - /// - /// Gets the Pixel data of what is currently drawn on screen. - /// The format is whatever the current format of the backbuffer is. - /// - /// A byte[] of size (ViewPort.Width * ViewPort.Height * 4) - /// - /// The section of the back buffer to copy. - /// indicates the data will be copied from the entire back buffer. - /// - /// Array of data. - /// The first element to use. - /// The number of elements to use. - /// - /// is - /// - /// - public void GetBackBufferData(Rectangle? rect, T[] data, int startIndex, int elementCount) - where T : struct - { - if (data == null) - throw new ArgumentNullException("data"); - - int width, height; - if (rect.HasValue) - { - var rectangle = rect.Value; - width = rectangle.Width; - height = rectangle.Height; - - if (rectangle.X < 0 || rectangle.Y < 0 || rectangle.Width <= 0 || rectangle.Height <= 0 || - rectangle.Right > PresentationParameters.BackBufferWidth || rectangle.Top > PresentationParameters.BackBufferHeight) - throw new ArgumentException("Rectangle must fit in BackBuffer dimensions"); - } - else - { - width = PresentationParameters.BackBufferWidth; - height = PresentationParameters.BackBufferHeight; - } - - var tSize = ReflectionHelpers.SizeOf.Get(); - var fSize = PresentationParameters.BackBufferFormat.GetSize(); - if (tSize > fSize || fSize % tSize != 0) - throw new ArgumentException("Type T is of an invalid size for the format of this texture.", "T"); - if (startIndex < 0 || startIndex >= data.Length) - throw new ArgumentException("startIndex must be at least zero and smaller than data.Length.", "startIndex"); - if (data.Length < startIndex + elementCount) - throw new ArgumentException("The data array is too small."); - var dataByteSize = width * height * fSize; - - if (elementCount * tSize != dataByteSize) - throw new ArgumentException(string.Format("elementCount is not the right size, " + - "elementCount * sizeof(T) is {0}, but data size is {1} bytes.", - elementCount * tSize, dataByteSize), "elementCount"); - - PlatformGetBackBufferData(rect, data, startIndex, elementCount); - } - - private static int GetElementCountArray(PrimitiveType primitiveType, int primitiveCount) - { - switch (primitiveType) - { - case PrimitiveType.LineList: - return primitiveCount * 2; - case PrimitiveType.LineStrip: - return primitiveCount + 1; - case PrimitiveType.TriangleList: - return primitiveCount * 3; - case PrimitiveType.TriangleStrip: - return primitiveCount + 2; - case PrimitiveType.PointList: - return primitiveCount; - } - - throw new NotSupportedException(); - } - - // uniformly scales down the given rectangle by 10% - internal static Rectangle GetDefaultTitleSafeArea(int x, int y, int width, int height) - { - var marginX = (width + 19) / 20; - var marginY = (height + 19) / 20; - x += marginX; - y += marginY; - - width -= marginX * 2; - height -= marginY * 2; - return new Rectangle(x, y, width, height); - } - - internal static Rectangle GetTitleSafeArea(int x, int y, int width, int height) - { - return PlatformGetTitleSafeArea(x, y, width, height); - } - } -} +// MonoGame - Copyright (C) MonoGame Foundation, Inc +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using MonoGame.Framework.Utilities; +using System.Runtime.InteropServices; + + +namespace Microsoft.Xna.Framework.Graphics +{ + /// + /// Performs primitive-based rendering, creates resources, + /// handles system-level variables, adjusts gamma ramp levels, and creates shaders. + /// + public partial class GraphicsDevice : IDisposable + { + /// + /// Indicates if DX9 style pixel addressing or current standard + /// pixel addressing should be used. This flag is set to + /// false by default. If `UseHalfPixelOffset` is + /// `true` you have to add half-pixel offset to a Projection matrix. + /// See also . + /// + /// + /// XNA uses DirectX9 for its graphics. DirectX9 interprets UV + /// coordinates differently from other graphics API's. This is + /// typically referred to as the half-pixel offset. MonoGame + /// replicates XNA behavior if this flag is set to true. + /// + public bool UseHalfPixelOffset { get; private set; } + + private Viewport _viewport; + + private bool _isDisposed; + + // On Intel Integrated graphics, there is a fast hw unit for doing + // clears to colors where all components are either 0 or 255. + // Despite XNA4 using Purple here, we use black (in Release) to avoid + // performance warnings on Intel/Mesa +#if DEBUG + private static Color _discardColor = new Color(68, 34, 136, 255); +#else + private static Color _discardColor = new Color(0, 0, 0, 255); +#endif + + private Color _blendFactor = Color.White; + private bool _blendFactorDirty; + + private BlendState _blendState; + private BlendState _actualBlendState; + private bool _blendStateDirty; + + private BlendState _blendStateAdditive; + private BlendState _blendStateAlphaBlend; + private BlendState _blendStateNonPremultiplied; + private BlendState _blendStateOpaque; + + private DepthStencilState _depthStencilState; + private DepthStencilState _actualDepthStencilState; + private bool _depthStencilStateDirty; + + private DepthStencilState _depthStencilStateDefault; + private DepthStencilState _depthStencilStateDepthRead; + private DepthStencilState _depthStencilStateNone; + + private RasterizerState _rasterizerState; + private RasterizerState _actualRasterizerState; + private bool _rasterizerStateDirty; + + private RasterizerState _rasterizerStateCullClockwise; + private RasterizerState _rasterizerStateCullCounterClockwise; + private RasterizerState _rasterizerStateCullNone; + + private Rectangle _scissorRectangle; + private bool _scissorRectangleDirty; + + private VertexBufferBindings _vertexBuffers; + private bool _vertexBuffersDirty; + + private IndexBuffer _indexBuffer; + private bool _indexBufferDirty; + + private readonly RenderTargetBinding[] _currentRenderTargetBindings = new RenderTargetBinding[8]; + private int _currentRenderTargetCount; + private readonly RenderTargetBinding[] _tempRenderTargetBinding = new RenderTargetBinding[1]; + + internal GraphicsCapabilities GraphicsCapabilities { get; private set; } + + /// + /// Gets the collection of vertex textures that support texture lookup + /// in the vertex shader using the texldl statement. + /// The vertex engine contains four texture sampler stages. + /// + public TextureCollection VertexTextures { get; private set; } + + /// + /// Returns the collection of vertex sampler states. + /// + public SamplerStateCollection VertexSamplerStates { get; private set; } + + /// + /// Returns the collection of textures that have been assigned to the texture stages of the device. + /// + public TextureCollection Textures { get; private set; } + + /// + /// Retrieves a collection of objects for the current . + /// + public SamplerStateCollection SamplerStates { get; private set; } + + /// + /// Get or set the color a is cleared to when it is set. + /// + public static Color DiscardColor { + get { return _discardColor; } + set { _discardColor = value; } + } + + /// + /// The active vertex shader. + /// + private Shader _vertexShader; + private bool _vertexShaderDirty; + private bool VertexShaderDirty + { + get { return _vertexShaderDirty; } + } + + /// + /// The active pixel shader. + /// + private Shader _pixelShader; + private bool _pixelShaderDirty; + private bool PixelShaderDirty + { + get { return _pixelShaderDirty; } + } + + private readonly ConstantBufferCollection _vertexConstantBuffers = new ConstantBufferCollection(ShaderStage.Vertex, 16); + private readonly ConstantBufferCollection _pixelConstantBuffers = new ConstantBufferCollection(ShaderStage.Pixel, 16); + + /// + /// The cache of effects from unique byte streams. + /// + internal Dictionary EffectCache; + + // Resources may be added to and removed from the list from many threads. + private readonly object _resourcesLock = new object(); + + // Use WeakReference for the global resources list as we do not know when a resource + // may be disposed and collected. We do not want to prevent a resource from being + // collected by holding a strong reference to it in this list. + private readonly List _resources = new List(); + + // TODO Graphics Device events need implementing + /// + /// Occurs when a GraphicsDevice is about to be lost (for example, immediately before a reset). + /// + public event EventHandler DeviceLost; + + /// + /// Occurs after a GraphicsDevice is reset, allowing an application to recreate all resources. + /// + public event EventHandler DeviceReset; + + /// + /// Occurs when a GraphicsDevice is resetting, + /// allowing the application to cancel the default handling of the reset. + /// + public event EventHandler DeviceResetting; + + /// + /// Occurs when a resource is created. + /// + public event EventHandler ResourceCreated; + + /// + /// Occurs when a resource is destroyed. + /// + public event EventHandler ResourceDestroyed; + + /// + /// Occurs when is called + /// or when this object is finalized and collected by the garbage collector. + /// + public event EventHandler Disposing; + + internal event EventHandler PresentationChanged; + + private int _maxVertexBufferSlots; + internal int MaxTextureSlots; + internal int MaxVertexTextureSlots; + + /// + /// Gets a value that indicates whether the object is disposed. + /// + public bool IsDisposed + { + get + { + return _isDisposed; + } + } + + /// + /// Gets a value that indicates whether the associated content was lost. + /// + public bool IsContentLost { + get { + // We will just return IsDisposed for now + // as that is the only case I can see for now + return IsDisposed; + } + } + + internal bool IsRenderTargetBound + { + get + { + return _currentRenderTargetCount > 0; + } + } + + internal DepthFormat ActiveDepthFormat + { + get + { + return IsRenderTargetBound + ? _currentRenderTargetBindings[0].DepthFormat + : PresentationParameters.DepthStencilFormat; + } + } + + /// + /// Gets the graphics adapter. + /// + public GraphicsAdapter Adapter + { + get; + private set; + } + + internal GraphicsMetrics _graphicsMetrics; + + /// + /// The rendering information for debugging and profiling. + /// The metrics are reset every frame after draw within . + /// + public GraphicsMetrics Metrics { get { return _graphicsMetrics; } set { _graphicsMetrics = value; } } + + private GraphicsDebug _graphicsDebug; + + /// + /// Access debugging APIs for the graphics subsystem. + /// + public GraphicsDebug GraphicsDebug { get { return _graphicsDebug; } set { _graphicsDebug = value; } } + + internal GraphicsDevice() + { + PresentationParameters = new PresentationParameters(); + PresentationParameters.DepthStencilFormat = DepthFormat.Depth24; + Setup(); + GraphicsCapabilities = new GraphicsCapabilities(); + GraphicsCapabilities.Initialize(this); + Initialize(); + } + + /// + /// Initializes a new instance of the class. + /// + /// The graphics adapter. + /// The graphics profile. + /// The presentation options. + /// + /// is . + /// + public GraphicsDevice(GraphicsAdapter adapter, GraphicsProfile graphicsProfile, PresentationParameters presentationParameters) + { + if (adapter == null) + throw new ArgumentNullException("adapter"); + if (!adapter.IsProfileSupported(graphicsProfile)) + throw new NoSuitableGraphicsDeviceException(String.Format("Adapter '{0}' does not support the {1} profile.", adapter.Description, graphicsProfile)); + if (presentationParameters == null) + throw new ArgumentNullException("presentationParameters"); + Adapter = adapter; + PresentationParameters = presentationParameters; + _graphicsProfile = graphicsProfile; + Setup(); + GraphicsCapabilities = new GraphicsCapabilities(); + GraphicsCapabilities.Initialize(this); + + Initialize(); + } + + /// + /// Initializes a new instance of the class. + /// + /// The graphics adapter. + /// The graphics profile. + /// Indicates if DX9 style pixel addressing or current standard pixel addressing should be used. This value is passed to + /// The presentation options. + /// + /// is . + /// + public GraphicsDevice(GraphicsAdapter adapter, GraphicsProfile graphicsProfile, bool preferHalfPixelOffset, PresentationParameters presentationParameters) + { + if (adapter == null) + throw new ArgumentNullException("adapter"); + if (!adapter.IsProfileSupported(graphicsProfile)) + throw new NoSuitableGraphicsDeviceException(String.Format("Adapter '{0}' does not support the {1} profile.", adapter.Description, graphicsProfile)); + if (presentationParameters == null) + throw new ArgumentNullException("presentationParameters"); +#if DIRECTX + // TODO we need to figure out how to inject the half pixel offset into DX shaders + preferHalfPixelOffset = false; +#endif + Adapter = adapter; + _graphicsProfile = graphicsProfile; + UseHalfPixelOffset = preferHalfPixelOffset; + PresentationParameters = presentationParameters; + Setup(); + GraphicsCapabilities = new GraphicsCapabilities(); + GraphicsCapabilities.Initialize(this); + + Initialize(); + } + + private void Setup() + { +#if DEBUG + if (DisplayMode == null) + { + throw new Exception( + "Unable to determine the current display mode. This can indicate that the " + + "game is not configured to be HiDPI aware under Windows 10 or later. See " + + "https://github.com/MonoGame/MonoGame/issues/5040 for more information."); + } +#endif + + // Initialize the main viewport + _viewport = new Viewport (0, 0, DisplayMode.Width, DisplayMode.Height); + _viewport.MaxDepth = 1.0f; + + PlatformSetup(); + + VertexTextures = new TextureCollection(this, MaxVertexTextureSlots, ShaderStage.Vertex); + VertexSamplerStates = new SamplerStateCollection(this, MaxVertexTextureSlots, ShaderStage.Vertex); + + Textures = new TextureCollection(this, MaxTextureSlots, ShaderStage.Pixel); + SamplerStates = new SamplerStateCollection(this, MaxTextureSlots, ShaderStage.Pixel); + + _blendStateAdditive = BlendState.Additive.Clone(); + _blendStateAlphaBlend = BlendState.AlphaBlend.Clone(); + _blendStateNonPremultiplied = BlendState.NonPremultiplied.Clone(); + _blendStateOpaque = BlendState.Opaque.Clone(); + + BlendState = BlendState.Opaque; + + _depthStencilStateDefault = DepthStencilState.Default.Clone(); + _depthStencilStateDepthRead = DepthStencilState.DepthRead.Clone(); + _depthStencilStateNone = DepthStencilState.None.Clone(); + + DepthStencilState = DepthStencilState.Default; + + _rasterizerStateCullClockwise = RasterizerState.CullClockwise.Clone(); + _rasterizerStateCullCounterClockwise = RasterizerState.CullCounterClockwise.Clone(); + _rasterizerStateCullNone = RasterizerState.CullNone.Clone(); + + RasterizerState = RasterizerState.CullCounterClockwise; + + EffectCache = new Dictionary(); + } + + /// + ~GraphicsDevice() + { + Dispose(false); + } + + internal int GetClampedMultisampleCount(int multiSampleCount) + { + if (multiSampleCount > 1) + { + // Round down MultiSampleCount to the nearest power of two + // hack from http://stackoverflow.com/a/2681094 + // Note: this will return an incorrect, but large value + // for very large numbers. That doesn't matter because + // the number will get clamped below anyway in this case. + var msc = multiSampleCount; + msc = msc | (msc >> 1); + msc = msc | (msc >> 2); + msc = msc | (msc >> 4); + msc -= (msc >> 1); + // and clamp it to what the device can handle + if (msc > GraphicsCapabilities.MaxMultiSampleCount) + msc = GraphicsCapabilities.MaxMultiSampleCount; + + return msc; + } + else return 0; + } + + internal void Initialize() + { + PlatformInitialize(); + + // Force set the default render states. + _blendStateDirty = _depthStencilStateDirty = _rasterizerStateDirty = true; + BlendState = BlendState.Opaque; + DepthStencilState = DepthStencilState.Default; + RasterizerState = RasterizerState.CullCounterClockwise; + + // Clear the texture and sampler collections forcing + // the state to be reapplied. + VertexTextures.Clear(); + VertexSamplerStates.Clear(); + Textures.Clear(); + SamplerStates.Clear(); + + // Clear constant buffers + _vertexConstantBuffers.Clear(); + _pixelConstantBuffers.Clear(); + + // Force set the buffers and shaders on next ApplyState() call + _vertexBuffers = new VertexBufferBindings(_maxVertexBufferSlots); + _vertexBuffersDirty = true; + _indexBufferDirty = true; + _vertexShaderDirty = true; + _pixelShaderDirty = true; + + // Set the default scissor rect. + _scissorRectangleDirty = true; + ScissorRectangle = _viewport.Bounds; + + // Set the default render target. + ApplyRenderTargets(null); + } + + /// + /// Gets or sets rasterizer state. + /// The default value is . + /// + public RasterizerState RasterizerState + { + get + { + return _rasterizerState; + } + + set + { + if (value == null) + throw new ArgumentNullException("value"); + + // Don't set the same state twice! + if (_rasterizerState == value) + return; + + if (!value.DepthClipEnable && !GraphicsCapabilities.SupportsDepthClamp) + throw new InvalidOperationException("Cannot set RasterizerState.DepthClipEnable to false on this graphics device"); + + _rasterizerState = value; + + // Static state properties never actually get bound; + // instead we use our GraphicsDevice-specific version of them. + var newRasterizerState = _rasterizerState; + if (ReferenceEquals(_rasterizerState, RasterizerState.CullClockwise)) + newRasterizerState = _rasterizerStateCullClockwise; + else if (ReferenceEquals(_rasterizerState, RasterizerState.CullCounterClockwise)) + newRasterizerState = _rasterizerStateCullCounterClockwise; + else if (ReferenceEquals(_rasterizerState, RasterizerState.CullNone)) + newRasterizerState = _rasterizerStateCullNone; + + newRasterizerState.BindToGraphicsDevice(this); + + _actualRasterizerState = newRasterizerState; + + _rasterizerStateDirty = true; + } + } + + /// + /// The color used as blend factor when alpha blending. + /// + /// + /// When only changing BlendFactor, use this rather than to + /// only update BlendFactor so the whole BlendState does not have to be updated. + /// + public Color BlendFactor + { + get { return _blendFactor; } + set + { + if (_blendFactor == value) + return; + _blendFactor = value; + _blendFactorDirty = true; + } + } + + /// + /// Gets or sets a system-defined instance of a blend state object initialized for alpha blending. + /// The default value is . + /// + public BlendState BlendState + { + get { return _blendState; } + set + { + if (value == null) + throw new ArgumentNullException("value"); + + // Don't set the same state twice! + if (_blendState == value) + return; + + _blendState = value; + + // Static state properties never actually get bound; + // instead we use our GraphicsDevice-specific version of them. + var newBlendState = _blendState; + if (ReferenceEquals(_blendState, BlendState.Additive)) + newBlendState = _blendStateAdditive; + else if (ReferenceEquals(_blendState, BlendState.AlphaBlend)) + newBlendState = _blendStateAlphaBlend; + else if (ReferenceEquals(_blendState, BlendState.NonPremultiplied)) + newBlendState = _blendStateNonPremultiplied; + else if (ReferenceEquals(_blendState, BlendState.Opaque)) + newBlendState = _blendStateOpaque; + + if (newBlendState.IndependentBlendEnable && !GraphicsCapabilities.SupportsSeparateBlendStates) + throw new PlatformNotSupportedException("Independent blend states requires at least OpenGL 4.0 or GL_ARB_draw_buffers_blend. Try upgrading your graphics drivers."); + + // Blend state is now bound to a device... no one should + // be changing the state of the blend state object now! + newBlendState.BindToGraphicsDevice(this); + + _actualBlendState = newBlendState; + + BlendFactor = _actualBlendState.BlendFactor; + + _blendStateDirty = true; + } + } + + /// + /// Gets or sets a system-defined instance of a depth-stencil state object. + /// The default value is . + /// + public DepthStencilState DepthStencilState + { + get { return _depthStencilState; } + set + { + if (value == null) + throw new ArgumentNullException("value"); + + // Don't set the same state twice! + if (_depthStencilState == value) + return; + + _depthStencilState = value; + + // Static state properties never actually get bound; + // instead we use our GraphicsDevice-specific version of them. + var newDepthStencilState = _depthStencilState; + if (ReferenceEquals(_depthStencilState, DepthStencilState.Default)) + newDepthStencilState = _depthStencilStateDefault; + else if (ReferenceEquals(_depthStencilState, DepthStencilState.DepthRead)) + newDepthStencilState = _depthStencilStateDepthRead; + else if (ReferenceEquals(_depthStencilState, DepthStencilState.None)) + newDepthStencilState = _depthStencilStateNone; + + newDepthStencilState.BindToGraphicsDevice(this); + + _actualDepthStencilState = newDepthStencilState; + + _depthStencilStateDirty = true; + } + } + + internal void ApplyState(bool applyShaders) + { + PlatformBeginApplyState(); + + PlatformApplyBlend(); + + if (_depthStencilStateDirty) + { + _actualDepthStencilState.PlatformApplyState(this); + _depthStencilStateDirty = false; + } + + if (_rasterizerStateDirty) + { + _actualRasterizerState.PlatformApplyState(this); + _rasterizerStateDirty = false; + } + + PlatformApplyState(applyShaders); + } + + /// + /// Clears resource buffers. + /// + /// Set this color value in all buffers. + public void Clear(Color color) + { + var options = ClearOptions.Target; + options |= ClearOptions.DepthBuffer; + options |= ClearOptions.Stencil; + PlatformClear(options, color.ToVector4(), _viewport.MaxDepth, 0); + + unchecked + { + _graphicsMetrics._clearCount++; + } + } + + /// + /// Clears resource buffers. + /// + /// Options for clearing a buffer. + /// Set this color value in all buffers. + /// Set this depth value in the buffer. + /// Set this stencil value in the buffer. + public void Clear(ClearOptions options, Color color, float depth, int stencil) + { + PlatformClear(options, color.ToVector4(), depth, stencil); + + unchecked + { + _graphicsMetrics._clearCount++; + } + } + + /// + /// Clears resource buffers. + /// + /// Options for clearing a buffer. + /// Set this color value in all buffers. + /// Set this depth value in the buffer. + /// Set this stencil value in the buffer. + public void Clear(ClearOptions options, Vector4 color, float depth, int stencil) + { + PlatformClear(options, color, depth, stencil); + + unchecked + { + _graphicsMetrics._clearCount++; + } + } + + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + protected virtual void Dispose(bool disposing) + { + if (!_isDisposed) + { + if (disposing) + { + // Dispose of all remaining graphics resources before disposing of the graphics device + lock (_resourcesLock) + { + foreach (var resource in _resources.ToArray()) + { + var target = resource.Target as IDisposable; + if (target != null) + target.Dispose(); + } + _resources.Clear(); + } + + // Clear the effect cache. + EffectCache.Clear(); + + _blendState = null; + _actualBlendState = null; + _blendStateAdditive.Dispose(); + _blendStateAlphaBlend.Dispose(); + _blendStateNonPremultiplied.Dispose(); + _blendStateOpaque.Dispose(); + + _depthStencilState = null; + _actualDepthStencilState = null; + _depthStencilStateDefault.Dispose(); + _depthStencilStateDepthRead.Dispose(); + _depthStencilStateNone.Dispose(); + + _rasterizerState = null; + _actualRasterizerState = null; + _rasterizerStateCullClockwise.Dispose(); + _rasterizerStateCullCounterClockwise.Dispose(); + _rasterizerStateCullNone.Dispose(); + + PlatformDispose(); + } + + _isDisposed = true; + EventHelpers.Raise(this, Disposing, EventArgs.Empty); + } + } + + internal void AddResourceReference(WeakReference resourceReference) + { + lock (_resourcesLock) + { + _resources.Add(resourceReference); + } + } + + internal void RemoveResourceReference(WeakReference resourceReference) + { + lock (_resourcesLock) + { + _resources.Remove(resourceReference); + } + } + + /// + /// Presents the display with the contents of the next buffer + /// in the sequence of back buffers owned by the . + /// + /// A render target is active. + public void Present() + { + // We cannot present with a RT set on the device. + if (_currentRenderTargetCount != 0) + throw new InvalidOperationException("Cannot call Present when a render target is active."); + + _graphicsMetrics = new GraphicsMetrics(); + PlatformPresent(); + } + + /* + public void Present(Rectangle? sourceRectangle, Rectangle? destinationRectangle, IntPtr overrideWindowHandle) + { + throw new NotImplementedException(); + } + */ + + partial void PlatformReset(); + + /// + /// Resets the presentation parameters for the current . + /// + public void Reset() + { + PlatformReset(); + + EventHelpers.Raise(this, DeviceResetting, EventArgs.Empty); + + // Update the back buffer. + OnPresentationChanged(); + + EventHelpers.Raise(this, PresentationChanged, new PresentationEventArgs(PresentationParameters)); + EventHelpers.Raise(this, DeviceReset, EventArgs.Empty); + } + + /// + /// Resets the current with the specified . + /// + /// Presentation parameters to set. + /// + /// is + /// + public void Reset(PresentationParameters presentationParameters) + { + if (presentationParameters == null) + throw new ArgumentNullException("presentationParameters"); + + PresentationParameters = presentationParameters; + Reset(); + } + + /// + /// Trigger the DeviceResetting event + /// Currently internal to allow the various platforms to send the event at the appropriate time. + /// + internal void OnDeviceResetting() + { + EventHelpers.Raise(this, DeviceResetting, EventArgs.Empty); + + lock (_resourcesLock) + { + foreach (var resource in _resources) + { + var target = resource.Target as GraphicsResource; + if (target != null) + target.GraphicsDeviceResetting(); + } + + // Remove references to resources that have been garbage collected. + _resources.RemoveAll(wr => !wr.IsAlive); + } + } + + /// + /// Trigger the DeviceReset event to allow games to be notified of a device reset. + /// Currently internal to allow the various platforms to send the event at the appropriate time. + /// + internal void OnDeviceReset() + { + EventHelpers.Raise(this, DeviceReset, EventArgs.Empty); + } + + /// + /// Retrieves the display mode's spatial resolution, color resolution, and refresh frequency. + /// + public DisplayMode DisplayMode + { + get + { + return Adapter.CurrentDisplayMode; + } + } + + /// + /// Retrieves the status of the device. + /// + public GraphicsDeviceStatus GraphicsDeviceStatus + { + get + { + return GraphicsDeviceStatus.Normal; + } + } + + /// + /// Gets the presentation parameters associated with this graphics device. + /// + public PresentationParameters PresentationParameters + { + get; + private set; + } + + /// + /// Gets or sets a viewport identifying the portion of the render target to receive draw calls. + /// + public Viewport Viewport + { + get + { + return _viewport; + } + + set + { + _viewport = value; + PlatformSetViewport(ref value); + } + } + + private readonly GraphicsProfile _graphicsProfile; + /// + /// Gets the graphics profile. + /// The default value is . + /// + public GraphicsProfile GraphicsProfile + { + get { return _graphicsProfile; } + } + + /// + /// Gets or sets the rectangle used for scissor testing. By default, the size matches the render target size. + /// + public Rectangle ScissorRectangle + { + get + { + return _scissorRectangle; + } + + set + { + if (_scissorRectangle == value) + return; + + _scissorRectangle = value; + _scissorRectangleDirty = true; + } + } + + /// + /// Gets the amount of render targets bound to this device. + /// + public int RenderTargetCount + { + get + { + return _currentRenderTargetCount; + } + } + + /// + /// Sets a new render target for this . + /// + /// + /// A new render target for the device, or + /// to set the device render target to the back buffer of the device. + /// + public void SetRenderTarget(RenderTarget2D renderTarget) + { + if (renderTarget == null) + { + SetRenderTargets(null); + } + else + { + _tempRenderTargetBinding[0] = new RenderTargetBinding(renderTarget); + SetRenderTargets(_tempRenderTargetBinding); + } + } + + /// + /// Sets a new render target for this . + /// + /// + /// A new render target for the device, or + /// to set the device render target to the back buffer of the device. + /// + /// The cube map face type. + public void SetRenderTarget(RenderTargetCube renderTarget, CubeMapFace cubeMapFace) + { + if (renderTarget == null) + { + SetRenderTargets(null); + } + else + { + _tempRenderTargetBinding[0] = new RenderTargetBinding(renderTarget, cubeMapFace); + SetRenderTargets(_tempRenderTargetBinding); + } + } + + /// + /// Sets an array of render targets. + /// + /// An array of render targets. + public void SetRenderTargets(params RenderTargetBinding[] renderTargets) + { + // Avoid having to check for null and zero length. + var renderTargetCount = 0; + if (renderTargets != null) + { + renderTargetCount = renderTargets.Length; + if (renderTargetCount == 0) + { + renderTargets = null; + } + } + + // Try to early out if the current and new bindings are equal. + if (_currentRenderTargetCount == renderTargetCount) + { + var isEqual = true; + for (var i = 0; i < _currentRenderTargetCount; i++) + { + if (_currentRenderTargetBindings[i].RenderTarget != renderTargets[i].RenderTarget || + _currentRenderTargetBindings[i].ArraySlice != renderTargets[i].ArraySlice) + { + isEqual = false; + break; + } + } + + if (isEqual) + return; + } + + ApplyRenderTargets(renderTargets); + + if (renderTargetCount == 0) + { + unchecked + { + _graphicsMetrics._targetCount++; + } + } + else + { + unchecked + { + _graphicsMetrics._targetCount += renderTargetCount; + } + } + } + + internal void ApplyRenderTargets(RenderTargetBinding[] renderTargets) + { + var clearTarget = false; + + PlatformResolveRenderTargets(); + + // Clear the current bindings. + Array.Clear(_currentRenderTargetBindings, 0, _currentRenderTargetBindings.Length); + + int renderTargetWidth; + int renderTargetHeight; + if (renderTargets == null) + { + _currentRenderTargetCount = 0; + + PlatformApplyDefaultRenderTarget(); + clearTarget = PresentationParameters.RenderTargetUsage == RenderTargetUsage.DiscardContents; + + renderTargetWidth = PresentationParameters.BackBufferWidth; + renderTargetHeight = PresentationParameters.BackBufferHeight; + } + else + { + // Copy the new bindings. + Array.Copy(renderTargets, _currentRenderTargetBindings, renderTargets.Length); + _currentRenderTargetCount = renderTargets.Length; + + var renderTarget = PlatformApplyRenderTargets(); + + // We clear the render target if asked. + clearTarget = renderTarget.RenderTargetUsage == RenderTargetUsage.DiscardContents; + + renderTargetWidth = renderTarget.Width; + renderTargetHeight = renderTarget.Height; + } + + // Set the viewport to the size of the first render target. + Viewport = new Viewport(0, 0, renderTargetWidth, renderTargetHeight); + + // Set the scissor rectangle to the size of the first render target. + ScissorRectangle = new Rectangle(0, 0, renderTargetWidth, renderTargetHeight); + + // In XNA 4, because of hardware limitations on Xbox, when + // a render target doesn't have PreserveContents as its usage + // it is cleared before being rendered to. + if (clearTarget) + Clear(DiscardColor); + } + + /// + /// Gets render target surfaces. + /// + /// An array of bound render targets. + public RenderTargetBinding[] GetRenderTargets() + { + // Return a correctly sized copy our internal array. + var bindings = new RenderTargetBinding[_currentRenderTargetCount]; + Array.Copy(_currentRenderTargetBindings, bindings, _currentRenderTargetCount); + return bindings; + } + + /// + /// Gets render target surfaces. + /// + /// + /// When this method returns, contains an array of that description of bound render targets. + /// This parameter is treated as uninitialized. + /// + public void GetRenderTargets(RenderTargetBinding[] outTargets) + { + Debug.Assert(outTargets.Length == _currentRenderTargetCount, "Invalid outTargets array length!"); + Array.Copy(_currentRenderTargetBindings, outTargets, _currentRenderTargetCount); + } + + /// + /// Sets or binds a vertex buffer to a device. + /// + /// A vertex buffer. + public void SetVertexBuffer(VertexBuffer vertexBuffer) + { + _vertexBuffersDirty |= (vertexBuffer == null) + ? _vertexBuffers.Clear() + : _vertexBuffers.Set(vertexBuffer, 0); + } + + /// + /// Sets or binds a vertex buffer to a device. + /// + /// A vertex buffer. + /// The offset (in bytes) from the beginning of the buffer. + /// + /// is less than 0 + /// OR is greater than or equal to .VertexCount. + /// + public void SetVertexBuffer(VertexBuffer vertexBuffer, int vertexOffset) + { + // Validate vertexOffset. + if (vertexOffset < 0 + || vertexBuffer == null && vertexOffset != 0 + || vertexBuffer != null && vertexOffset >= vertexBuffer.VertexCount) + { + throw new ArgumentOutOfRangeException("vertexOffset"); + } + + _vertexBuffersDirty |= (vertexBuffer == null) + ? _vertexBuffers.Clear() + : _vertexBuffers.Set(vertexBuffer, vertexOffset); + } + + /// + /// Sets the vertex buffers. + /// + /// An array of vertex buffers. + /// + /// Length of is more than max allowed number of vertex buffers. + /// + public void SetVertexBuffers(params VertexBufferBinding[] vertexBuffers) + { + if (vertexBuffers == null || vertexBuffers.Length == 0) + { + _vertexBuffersDirty |= _vertexBuffers.Clear(); + } + else + { + if (vertexBuffers.Length > _maxVertexBufferSlots) + { + var message = string.Format(CultureInfo.InvariantCulture, "Max number of vertex buffers is {0}.", _maxVertexBufferSlots); + throw new ArgumentOutOfRangeException("vertexBuffers", message); + } + + _vertexBuffersDirty |= _vertexBuffers.Set(vertexBuffers); + } + } + + private void SetIndexBuffer(IndexBuffer indexBuffer) + { + if (_indexBuffer == indexBuffer) + return; + + _indexBuffer = indexBuffer; + _indexBufferDirty = true; + } + + /// + /// Gets or sets index data. The default value is . + /// + public IndexBuffer Indices { set { SetIndexBuffer(value); } get { return _indexBuffer; } } + + internal Shader VertexShader + { + get { return _vertexShader; } + + set + { + if (_vertexShader == value) + return; + + _vertexShader = value; + _vertexConstantBuffers.Clear(); + _vertexShaderDirty = true; + } + } + + internal Shader PixelShader + { + get { return _pixelShader; } + + set + { + if (_pixelShader == value) + return; + + _pixelShader = value; + _pixelConstantBuffers.Clear(); + _pixelShaderDirty = true; + } + } + + internal void SetConstantBuffer(ShaderStage stage, int slot, ConstantBuffer buffer) + { + if (stage == ShaderStage.Vertex) + _vertexConstantBuffers[slot] = buffer; + else + _pixelConstantBuffers[slot] = buffer; + } + + /// + /// Gets a value that indicates whether the resources were lost. + /// + public bool ResourcesLost { get; set; } + + /// + /// Draw geometry by indexing into the vertex buffer. + /// + /// The type of primitives in the index buffer. + /// Used to offset the vertex range indexed from the vertex buffer. + /// This is unused and remains here only for XNA API compatibility. + /// This is unused and remains here only for XNA API compatibility. + /// The index within the index buffer to start drawing from. + /// The number of primitives to render from the index buffer. + /// Note that minVertexIndex and numVertices are unused in MonoGame and will be ignored. + [Obsolete("Use DrawIndexedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount) instead. In future versions this method can be removed.")] + public void DrawIndexedPrimitives(PrimitiveType primitiveType, int baseVertex, int minVertexIndex, int numVertices, int startIndex, int primitiveCount) + { + DrawIndexedPrimitives(primitiveType, baseVertex, startIndex, primitiveCount); + } + + /// + /// Draw geometry by indexing into the vertex buffer. + /// + /// The type of primitives in the index buffer. + /// Used to offset the vertex range indexed from the vertex buffer. + /// The index within the index buffer to start drawing from. + /// The number of primitives to render from the index buffer. + public void DrawIndexedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount) + { + if (_vertexShader == null) + throw new InvalidOperationException("Vertex shader must be set before calling DrawIndexedPrimitives."); + + if (_vertexBuffers.Count == 0) + throw new InvalidOperationException("Vertex buffer must be set before calling DrawIndexedPrimitives."); + + if (_indexBuffer == null) + throw new InvalidOperationException("Index buffer must be set before calling DrawIndexedPrimitives."); + + if (primitiveCount <= 0) + throw new ArgumentOutOfRangeException("primitiveCount"); + + PlatformDrawIndexedPrimitives(primitiveType, baseVertex, startIndex, primitiveCount); + + unchecked + { + _graphicsMetrics._drawCount++; + _graphicsMetrics._primitiveCount += primitiveCount; + } + } + + /// + /// Draw primitives of the specified type from the data in an array of vertices without indexing. + /// + /// The type of the vertices. + /// The type of primitives to draw with the vertices. + /// An array of vertices to draw. + /// The index in the array of the first vertex that should be rendered. + /// The number of primitives to draw. + /// The will be found by getting + /// from an instance of and cached for subsequent calls. + public void DrawUserPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int primitiveCount) where T : struct, IVertexType + { + DrawUserPrimitives(primitiveType, vertexData, vertexOffset, primitiveCount, VertexDeclarationCache.VertexDeclaration); + } + + /// + /// Draw primitives of the specified type from the data in the given array of vertices without indexing. + /// + /// The type of the vertices. + /// The type of primitives to draw with the vertices. + /// An array of vertices to draw. + /// The index in the array of the first vertex that should be rendered. + /// The number of primitives to draw. + /// The layout of the vertices. + public void DrawUserPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct + { + if (vertexData == null) + throw new ArgumentNullException("vertexData"); + + if (vertexData.Length == 0) + throw new ArgumentOutOfRangeException("vertexData"); + + if (vertexOffset < 0 || vertexOffset >= vertexData.Length) + throw new ArgumentOutOfRangeException("vertexOffset"); + + if (primitiveCount <= 0) + throw new ArgumentOutOfRangeException("primitiveCount"); + + var vertexCount = GetElementCountArray(primitiveType, primitiveCount); + + if (vertexOffset + vertexCount > vertexData.Length) + throw new ArgumentOutOfRangeException("primitiveCount"); + + if (vertexDeclaration == null) + throw new ArgumentNullException("vertexDeclaration"); + + PlatformDrawUserPrimitives(primitiveType, vertexData, vertexOffset, vertexDeclaration, vertexCount); + + unchecked + { + _graphicsMetrics._drawCount++; + _graphicsMetrics._primitiveCount += primitiveCount; + } + } + + /// + /// Draw primitives of the specified type from the currently bound vertexbuffers without indexing. + /// + /// The type of primitives to draw. + /// Index of the vertex to start at. + /// The number of primitives to draw. + public void DrawPrimitives(PrimitiveType primitiveType, int vertexStart, int primitiveCount) + { + if (_vertexShader == null) + throw new InvalidOperationException("Vertex shader must be set before calling DrawPrimitives."); + + if (_vertexBuffers.Count == 0) + throw new InvalidOperationException("Vertex buffer must be set before calling DrawPrimitives."); + + if (primitiveCount <= 0) + throw new ArgumentOutOfRangeException("primitiveCount"); + + var vertexCount = GetElementCountArray(primitiveType, primitiveCount); + + PlatformDrawPrimitives(primitiveType, vertexStart, vertexCount); + + unchecked + { + _graphicsMetrics._drawCount++; + _graphicsMetrics._primitiveCount += primitiveCount; + } + } + + /// + /// Draw primitives of the specified type by indexing into the given array of vertices with 16-bit indices. + /// + /// The type of the vertices. + /// The type of primitives to draw with the vertices. + /// An array of vertices to draw. + /// The index in the array of the first vertex to draw. + /// The index in the array of indices of the first index to use + /// The number of primitives to draw. + /// The number of vertices to draw. + /// The index data. + /// The will be found by getting + /// from an instance of and cached for subsequent calls. + /// All indices in the vertex buffer are interpreted relative to the specified . + /// For example a value of zero in the array of indices points to the vertex at index + /// in the array of vertices. + public void DrawUserIndexedPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, short[] indexData, int indexOffset, int primitiveCount) where T : struct, IVertexType + { + DrawUserIndexedPrimitives(primitiveType, vertexData, vertexOffset, numVertices, indexData, indexOffset, primitiveCount, VertexDeclarationCache.VertexDeclaration); + } + + /// + /// Draw primitives of the specified type by indexing into the given array of vertices with 16-bit indices. + /// + /// The type of the vertices. + /// The type of primitives to draw with the vertices. + /// An array of vertices to draw. + /// The index in the array of the first vertex to draw. + /// The index in the array of indices of the first index to use + /// The number of primitives to draw. + /// The number of vertices to draw. + /// The index data. + /// The layout of the vertices. + /// All indices in the vertex buffer are interpreted relative to the specified . + /// For example a value of zero in the array of indices points to the vertex at index + /// in the array of vertices. + public void DrawUserIndexedPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, short[] indexData, int indexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct + { + // These parameter checks are a duplicate of the checks in the int[] overload of DrawUserIndexedPrimitives. + // Inlined here for efficiency. + + if (vertexData == null || vertexData.Length == 0) + throw new ArgumentNullException("vertexData"); + + if (vertexOffset < 0 || vertexOffset >= vertexData.Length) + throw new ArgumentOutOfRangeException("vertexOffset"); + + if (numVertices <= 0 || numVertices > vertexData.Length) + throw new ArgumentOutOfRangeException("numVertices"); + + if (vertexOffset + numVertices > vertexData.Length) + throw new ArgumentOutOfRangeException("numVertices"); + + if (indexData == null || indexData.Length == 0) + throw new ArgumentNullException("indexData"); + + if (indexOffset < 0 || indexOffset >= indexData.Length) + throw new ArgumentOutOfRangeException("indexOffset"); + + if (primitiveCount <= 0) + throw new ArgumentOutOfRangeException("primitiveCount"); + + if (indexOffset + GetElementCountArray(primitiveType, primitiveCount) > indexData.Length) + throw new ArgumentOutOfRangeException("primitiveCount"); + + if (vertexDeclaration == null) + throw new ArgumentNullException("vertexDeclaration"); + + if (vertexDeclaration.VertexStride < ReflectionHelpers.FastSizeOf()) + throw new ArgumentOutOfRangeException("vertexDeclaration", "Vertex stride of vertexDeclaration should be at least as big as the stride of the actual vertices."); + + PlatformDrawUserIndexedPrimitives(primitiveType, vertexData, vertexOffset, numVertices, indexData, indexOffset, primitiveCount, vertexDeclaration); + + unchecked + { + _graphicsMetrics._drawCount++; + _graphicsMetrics._primitiveCount += primitiveCount; + } + } + + /// + /// Draw primitives of the specified type by indexing into the given array of vertices with 32-bit indices. + /// + /// The type of the vertices. + /// The type of primitives to draw with the vertices. + /// An array of vertices to draw. + /// The index in the array of the first vertex to draw. + /// The index in the array of indices of the first index to use + /// The number of primitives to draw. + /// The number of vertices to draw. + /// The index data. + /// The will be found by getting + /// from an instance of and cached for subsequent calls. + /// All indices in the vertex buffer are interpreted relative to the specified . + /// For example a value of zero in the array of indices points to the vertex at index + /// in the array of vertices. + public void DrawUserIndexedPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, int[] indexData, int indexOffset, int primitiveCount) where T : struct, IVertexType + { + DrawUserIndexedPrimitives(primitiveType, vertexData, vertexOffset, numVertices, indexData, indexOffset, primitiveCount, VertexDeclarationCache.VertexDeclaration); + } + + /// + /// Draw primitives of the specified type by indexing into the given array of vertices with 32-bit indices. + /// + /// The type of the vertices. + /// The type of primitives to draw with the vertices. + /// An array of vertices to draw. + /// The index in the array of the first vertex to draw. + /// The index in the array of indices of the first index to use + /// The number of primitives to draw. + /// The number of vertices to draw. + /// The index data. + /// The layout of the vertices. + /// All indices in the vertex buffer are interpreted relative to the specified . + /// For example value of zero in the array of indices points to the vertex at index + /// in the array of vertices. + public void DrawUserIndexedPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, int[] indexData, int indexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct + { + // These parameter checks are a duplicate of the checks in the short[] overload of DrawUserIndexedPrimitives. + // Inlined here for efficiency. + + if (vertexData == null || vertexData.Length == 0) + throw new ArgumentNullException("vertexData"); + + if (vertexOffset < 0 || vertexOffset >= vertexData.Length) + throw new ArgumentOutOfRangeException("vertexOffset"); + + if (numVertices <= 0 || numVertices > vertexData.Length) + throw new ArgumentOutOfRangeException("numVertices"); + + if (vertexOffset + numVertices > vertexData.Length) + throw new ArgumentOutOfRangeException("numVertices"); + + if (indexData == null || indexData.Length == 0) + throw new ArgumentNullException("indexData"); + + if (indexOffset < 0 || indexOffset >= indexData.Length) + throw new ArgumentOutOfRangeException("indexOffset"); + + if (primitiveCount <= 0) + throw new ArgumentOutOfRangeException("primitiveCount"); + + if (indexOffset + GetElementCountArray(primitiveType, primitiveCount) > indexData.Length) + throw new ArgumentOutOfRangeException("primitiveCount"); + + if (vertexDeclaration == null) + throw new ArgumentNullException("vertexDeclaration"); + + if (vertexDeclaration.VertexStride < ReflectionHelpers.FastSizeOf()) + throw new ArgumentOutOfRangeException("vertexDeclaration", "Vertex stride of vertexDeclaration should be at least as big as the stride of the actual vertices."); + + PlatformDrawUserIndexedPrimitives(primitiveType, vertexData, vertexOffset, numVertices, indexData, indexOffset, primitiveCount, vertexDeclaration); + + unchecked + { + _graphicsMetrics._drawCount++; + _graphicsMetrics._primitiveCount += primitiveCount; + } + } + + /// + /// Draw instanced geometry from the bound vertex buffers and index buffer. + /// + /// The type of primitives in the index buffer. + /// Used to offset the vertex range indexed from the vertex buffer. + /// This is unused and remains here only for XNA API compatibility. + /// This is unused and remains here only for XNA API compatibility. + /// The index within the index buffer to start drawing from. + /// The number of primitives in a single instance. + /// The number of instances to render. + /// Note that minVertexIndex and numVertices are unused in MonoGame and will be ignored. + [Obsolete("Use DrawInstancedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount, int instanceCount) instead. In future versions this method can be removed.")] + public void DrawInstancedPrimitives(PrimitiveType primitiveType, int baseVertex, int minVertexIndex, + int numVertices, int startIndex, int primitiveCount, int instanceCount) + { + DrawInstancedPrimitives(primitiveType, baseVertex, startIndex, primitiveCount, 0, instanceCount); + } + + /// + /// Draw instanced geometry from the bound vertex buffers and index buffer. + /// + /// The type of primitives in the index buffer. + /// Used to offset the vertex range indexed from the vertex buffer. + /// The index within the index buffer to start drawing from. + /// The number of primitives in a single instance. + /// The number of instances to render. + /// Draw geometry with data from multiple bound vertex streams at different frequencies. + public void DrawInstancedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount, int instanceCount) + { + DrawInstancedPrimitives(primitiveType, baseVertex, startIndex, primitiveCount, 0, instanceCount); + } + + /// + /// Draw instanced geometry from the bound vertex buffers and index buffer. + /// + /// The type of primitives in the index buffer. + /// Used to offset the vertex range indexed from the vertex buffer. + /// The index within the index buffer to start drawing from. + /// The number of primitives in a single instance. + /// Used to offset the instance range indexed from the instance buffer. + /// The number of instances to render. + /// Draw geometry with data from multiple bound vertex streams at different frequencies. + public void DrawInstancedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount, int baseInstance, int instanceCount) + { + if (_vertexShader == null) + throw new InvalidOperationException("Vertex shader must be set before calling DrawInstancedPrimitives."); + + if (_vertexBuffers.Count == 0) + throw new InvalidOperationException("Vertex buffer must be set before calling DrawInstancedPrimitives."); + + if (_indexBuffer == null) + throw new InvalidOperationException("Index buffer must be set before calling DrawInstancedPrimitives."); + + if (primitiveCount <= 0) + throw new ArgumentOutOfRangeException("primitiveCount"); + + PlatformDrawInstancedPrimitives(primitiveType, baseVertex, startIndex, primitiveCount, baseInstance, instanceCount); + + unchecked + { + _graphicsMetrics._drawCount++; + _graphicsMetrics._primitiveCount += (primitiveCount * instanceCount); + } + } + + /// + /// Gets the Pixel data of what is currently drawn on screen. + /// The format is whatever the current format of the backbuffer is. + /// + /// A byte[] of size (ViewPort.Width * ViewPort.Height * 4) + /// Array of data. + public void GetBackBufferData(T[] data) where T : struct + { + if (data == null) + throw new ArgumentNullException("data"); + GetBackBufferData(null, data, 0, data.Length); + } + + /// + /// Gets the Pixel data of what is currently drawn on screen. + /// The format is whatever the current format of the backbuffer is. + /// + /// A byte[] of size (ViewPort.Width * ViewPort.Height * 4) + /// Array of data. + /// The first element to use. + /// The number of elements to use. + public void GetBackBufferData(T[] data, int startIndex, int elementCount) where T : struct + { + GetBackBufferData(null, data, startIndex, elementCount); + } + + /// + /// Gets the Pixel data of what is currently drawn on screen. + /// The format is whatever the current format of the backbuffer is. + /// + /// A byte[] of size (ViewPort.Width * ViewPort.Height * 4) + /// + /// The section of the back buffer to copy. + /// indicates the data will be copied from the entire back buffer. + /// + /// Array of data. + /// The first element to use. + /// The number of elements to use. + /// + /// is + /// + /// + public void GetBackBufferData(Rectangle? rect, T[] data, int startIndex, int elementCount) + where T : struct + { + if (data == null) + throw new ArgumentNullException("data"); + + int width, height; + if (rect.HasValue) + { + var rectangle = rect.Value; + width = rectangle.Width; + height = rectangle.Height; + + if (rectangle.X < 0 || rectangle.Y < 0 || rectangle.Width <= 0 || rectangle.Height <= 0 || + rectangle.Right > PresentationParameters.BackBufferWidth || rectangle.Top > PresentationParameters.BackBufferHeight) + throw new ArgumentException("Rectangle must fit in BackBuffer dimensions"); + } + else + { + width = PresentationParameters.BackBufferWidth; + height = PresentationParameters.BackBufferHeight; + } + + var tSize = ReflectionHelpers.FastSizeOf(); + var fSize = PresentationParameters.BackBufferFormat.GetSize(); + if (tSize > fSize || fSize % tSize != 0) + throw new ArgumentException("Type T is of an invalid size for the format of this texture.", "T"); + if (startIndex < 0 || startIndex >= data.Length) + throw new ArgumentException("startIndex must be at least zero and smaller than data.Length.", "startIndex"); + if (data.Length < startIndex + elementCount) + throw new ArgumentException("The data array is too small."); + var dataByteSize = width * height * fSize; + + if (elementCount * tSize != dataByteSize) + throw new ArgumentException(string.Format("elementCount is not the right size, " + + "elementCount * sizeof(T) is {0}, but data size is {1} bytes.", + elementCount * tSize, dataByteSize), "elementCount"); + + PlatformGetBackBufferData(rect, data, startIndex, elementCount); + } + + private static int GetElementCountArray(PrimitiveType primitiveType, int primitiveCount) + { + switch (primitiveType) + { + case PrimitiveType.LineList: + return primitiveCount * 2; + case PrimitiveType.LineStrip: + return primitiveCount + 1; + case PrimitiveType.TriangleList: + return primitiveCount * 3; + case PrimitiveType.TriangleStrip: + return primitiveCount + 2; + case PrimitiveType.PointList: + return primitiveCount; + } + + throw new NotSupportedException(); + } + + // uniformly scales down the given rectangle by 10% + internal static Rectangle GetDefaultTitleSafeArea(int x, int y, int width, int height) + { + var marginX = (width + 19) / 20; + var marginY = (height + 19) / 20; + x += marginX; + y += marginY; + + width -= marginX * 2; + height -= marginY * 2; + return new Rectangle(x, y, width, height); + } + + internal static Rectangle GetTitleSafeArea(int x, int y, int width, int height) + { + return PlatformGetTitleSafeArea(x, y, width, height); + } + } +} diff --git a/MonoGame.Framework/Graphics/SamplerStateCollection.cs b/MonoGame.Framework/Graphics/SamplerStateCollection.cs index 8cb05ea39b7..425fe8f29a3 100644 --- a/MonoGame.Framework/Graphics/SamplerStateCollection.cs +++ b/MonoGame.Framework/Graphics/SamplerStateCollection.cs @@ -22,9 +22,9 @@ public sealed partial class SamplerStateCollection private readonly SamplerState[] _samplers; private readonly SamplerState[] _actualSamplers; - private readonly bool _applyToVertexStage; + private readonly ShaderStage _stage; - internal SamplerStateCollection(GraphicsDevice device, int maxSamplers, bool applyToVertexStage) + internal SamplerStateCollection(GraphicsDevice device, int maxSamplers, ShaderStage stage) { _graphicsDevice = device; @@ -37,7 +37,7 @@ internal SamplerStateCollection(GraphicsDevice device, int maxSamplers, bool app _samplers = new SamplerState[maxSamplers]; _actualSamplers = new SamplerState[maxSamplers]; - _applyToVertexStage = applyToVertexStage; + _stage = stage; Clear(); } diff --git a/MonoGame.Framework/Graphics/Shader/Shader.cs b/MonoGame.Framework/Graphics/Shader/Shader.cs index 34fa04d4651..e06e2fd9e2b 100644 --- a/MonoGame.Framework/Graphics/Shader/Shader.cs +++ b/MonoGame.Framework/Graphics/Shader/Shader.cs @@ -34,9 +34,47 @@ internal struct SamplerInfo internal struct VertexAttribute { public VertexElementUsage usage; - public int index; + public int index; + + // These should be obsolete once we move away from + // the old C# graphics backends to the native ones. public string name; - public int location; + public int location; + + public string ToShaderSemantic() + { + switch (usage) + { + case VertexElementUsage.Position: + return $"POSITION{index}"; + case VertexElementUsage.Color: + return $"COLOR{index}"; + case VertexElementUsage.Normal: + return $"NORMAL{index}"; + case VertexElementUsage.TextureCoordinate: + return $"TEXCOORD{index}"; + case VertexElementUsage.BlendIndices: + return $"BLENDINDICES{index}"; + case VertexElementUsage.BlendWeight: + return $"BLENDWEIGHT{index}"; + case VertexElementUsage.Binormal: + return $"BINORMAL{index}"; + case VertexElementUsage.Tangent: + return $"TANGENT{index}"; + case VertexElementUsage.PointSize: + return $"PSIZE{index}"; + case VertexElementUsage.Depth: + return $"DEPTH{index}"; + case VertexElementUsage.Fog: + return $"FOG{index}"; + case VertexElementUsage.Sample: // Huh? What is this? + return $"SAMPLE{index}"; + case VertexElementUsage.TessellateFactor: + return $"TESSELLATEFACTOR{index}"; + default: + throw new NotSupportedException("Unknown vertex element usage!"); + } + } } internal partial class Shader : GraphicsResource diff --git a/MonoGame.Framework/Graphics/Shader/ShaderStage.cs b/MonoGame.Framework/Graphics/Shader/ShaderStage.cs index 75d8f582885..636bb526248 100644 --- a/MonoGame.Framework/Graphics/Shader/ShaderStage.cs +++ b/MonoGame.Framework/Graphics/Shader/ShaderStage.cs @@ -4,5 +4,7 @@ internal enum ShaderStage { Vertex, Pixel, + + Count, } } diff --git a/MonoGame.Framework/Graphics/Texture2D.cs b/MonoGame.Framework/Graphics/Texture2D.cs index 9b96688b4cc..7ccd54344eb 100644 --- a/MonoGame.Framework/Graphics/Texture2D.cs +++ b/MonoGame.Framework/Graphics/Texture2D.cs @@ -788,7 +788,7 @@ private void ValidateParams(int level, int arraySlice, Rectangle? rect, T[] d throw new ArgumentException("Rectangle must be inside the texture bounds", "rect"); if (data == null) throw new ArgumentNullException("data"); - var tSize = ReflectionHelpers.SizeOf.Get(); + var tSize = ReflectionHelpers.FastSizeOf(); var fSize = Format.GetSize(); if (tSize > fSize || fSize % tSize != 0) throw new ArgumentException("Type T is of an invalid size for the format of this texture.", "T"); diff --git a/MonoGame.Framework/Graphics/Texture3D.cs b/MonoGame.Framework/Graphics/Texture3D.cs index 519997ddce8..b4a27f0bf7a 100644 --- a/MonoGame.Framework/Graphics/Texture3D.cs +++ b/MonoGame.Framework/Graphics/Texture3D.cs @@ -247,11 +247,7 @@ public void SetData (int level, { ValidateParams(level, left, top, right, bottom, front, back, data, startIndex, elementCount); - var width = right - left; - var height = bottom - top; - var depth = back - front; - - PlatformSetData(level, left, top, right, bottom, front, back, data, startIndex, elementCount, width, height, depth); + PlatformSetData(level, left, top, right, bottom, front, back, data, startIndex, elementCount); } /// @@ -414,7 +410,7 @@ private void ValidateParams(int level, throw new ArgumentException("level must be smaller than the number of levels in this texture."); if (data == null) throw new ArgumentNullException("data"); - var tSize = ReflectionHelpers.SizeOf.Get(); + var tSize = ReflectionHelpers.FastSizeOf(); var fSize = Format.GetSize(); if (tSize > fSize || fSize % tSize != 0) throw new ArgumentException("Type T is of an invalid size for the format of this texture.", "T"); diff --git a/MonoGame.Framework/Graphics/TextureCollection.cs b/MonoGame.Framework/Graphics/TextureCollection.cs index 29971499902..cc77f8364c3 100644 --- a/MonoGame.Framework/Graphics/TextureCollection.cs +++ b/MonoGame.Framework/Graphics/TextureCollection.cs @@ -13,14 +13,14 @@ public sealed partial class TextureCollection { private readonly GraphicsDevice _graphicsDevice; private readonly Texture[] _textures; - private readonly bool _applyToVertexStage; + private ShaderStage _stage; private int _dirty; - internal TextureCollection(GraphicsDevice graphicsDevice, int maxTextures, bool applyToVertexStage) + internal TextureCollection(GraphicsDevice graphicsDevice, int maxTextures, ShaderStage stage) { _graphicsDevice = graphicsDevice; _textures = new Texture[maxTextures]; - _applyToVertexStage = applyToVertexStage; + _stage = stage; _dirty = int.MaxValue; PlatformInit(); } @@ -36,7 +36,7 @@ public Texture this[int index] } set { - if (_applyToVertexStage && !_graphicsDevice.GraphicsCapabilities.SupportsVertexTextures) + if (_stage == ShaderStage.Vertex && !_graphicsDevice.GraphicsCapabilities.SupportsVertexTextures) throw new NotSupportedException("Vertex textures are not supported on this device."); if (_textures[index] == value) @@ -66,8 +66,9 @@ internal void Dirty() internal void SetTextures(GraphicsDevice device) { - if (_applyToVertexStage && !device.GraphicsCapabilities.SupportsVertexTextures) + if (_stage == ShaderStage.Vertex && !device.GraphicsCapabilities.SupportsVertexTextures) return; + PlatformSetTextures(device); } } diff --git a/MonoGame.Framework/Graphics/TextureCube.cs b/MonoGame.Framework/Graphics/TextureCube.cs index e499e291301..11511a70b00 100644 --- a/MonoGame.Framework/Graphics/TextureCube.cs +++ b/MonoGame.Framework/Graphics/TextureCube.cs @@ -312,7 +312,7 @@ private void ValidateParams(int level, Rectangle? rect, T[] data, int startIn throw new ArgumentException("Rectangle must be inside the texture bounds", "rect"); if (data == null) throw new ArgumentNullException("data"); - var tSize = ReflectionHelpers.SizeOf.Get(); + var tSize = ReflectionHelpers.FastSizeOf(); var fSize = Format.GetSize(); if (tSize > fSize || fSize % tSize != 0) throw new ArgumentException("Type T is of an invalid size for the format of this texture.", "T"); diff --git a/MonoGame.Framework/Graphics/Vertices/DynamicVertexBuffer.cs b/MonoGame.Framework/Graphics/Vertices/DynamicVertexBuffer.cs index 05a31a0a8f2..97c6b51fe36 100644 --- a/MonoGame.Framework/Graphics/Vertices/DynamicVertexBuffer.cs +++ b/MonoGame.Framework/Graphics/Vertices/DynamicVertexBuffer.cs @@ -131,7 +131,7 @@ public void SetData(int offsetInBytes, T[] data, int startIndex, int elementC /// public void SetData(T[] data, int startIndex, int elementCount, SetDataOptions options) where T : struct { - var elementSizeInBytes = ReflectionHelpers.SizeOf.Get(); + var elementSizeInBytes = ReflectionHelpers.FastSizeOf(); base.SetDataInternal(0, data, startIndex, elementCount, elementSizeInBytes, options); } } diff --git a/MonoGame.Framework/Platform/Graphics/Vertices/ImmutableVertexInputLayout.cs b/MonoGame.Framework/Graphics/Vertices/ImmutableVertexInputLayout.cs similarity index 100% rename from MonoGame.Framework/Platform/Graphics/Vertices/ImmutableVertexInputLayout.cs rename to MonoGame.Framework/Graphics/Vertices/ImmutableVertexInputLayout.cs diff --git a/MonoGame.Framework/Graphics/Vertices/VertexBuffer.cs b/MonoGame.Framework/Graphics/Vertices/VertexBuffer.cs index ee50db8401f..2a8cfa0faad 100644 --- a/MonoGame.Framework/Graphics/Vertices/VertexBuffer.cs +++ b/MonoGame.Framework/Graphics/Vertices/VertexBuffer.cs @@ -119,7 +119,7 @@ internal protected override void GraphicsDeviceResetting() /// public void GetData (int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride = 0) where T : struct { - var elementSizeInBytes = ReflectionHelpers.SizeOf.Get(); + var elementSizeInBytes = ReflectionHelpers.FastSizeOf(); if (vertexStride == 0) vertexStride = elementSizeInBytes; @@ -148,7 +148,7 @@ public void GetData(T[] data, int startIndex, int elementCount) where T : str /// public void GetData(T[] data) where T : struct { - var elementSizeInByte = ReflectionHelpers.SizeOf.Get(); + var elementSizeInByte = ReflectionHelpers.FastSizeOf(); this.GetData(0, data, 0, data.Length, elementSizeInByte); } @@ -215,7 +215,7 @@ public void SetData(int offsetInBytes, T[] data, int startIndex, int elementC /// must be within the array bounds. public void SetData(T[] data, int startIndex, int elementCount) where T : struct { - var elementSizeInBytes = ReflectionHelpers.SizeOf.Get(); + var elementSizeInBytes = ReflectionHelpers.FastSizeOf(); SetDataInternal(0, data, startIndex, elementCount, elementSizeInBytes, SetDataOptions.None); } @@ -228,7 +228,7 @@ public void SetData(T[] data, int startIndex, int elementCount) where T : str /// Data array to be passed to the shader. public void SetData(T[] data) where T : struct { - var elementSizeInBytes = ReflectionHelpers.SizeOf.Get(); + var elementSizeInBytes = ReflectionHelpers.FastSizeOf(); SetDataInternal(0, data, 0, data.Length, elementSizeInBytes, SetDataOptions.None); } @@ -238,7 +238,7 @@ protected void SetDataInternal(int offsetInBytes, T[] data, int startIndex, i if (data == null) throw new ArgumentNullException("data"); - var elementSizeInBytes = ReflectionHelpers.SizeOf.Get(); + var elementSizeInBytes = ReflectionHelpers.FastSizeOf(); var bufferSize = VertexCount * VertexDeclaration.VertexStride; if (vertexStride == 0) diff --git a/MonoGame.Framework/Graphics/Vertices/VertexBufferBindings.cs b/MonoGame.Framework/Graphics/Vertices/VertexBufferBindings.cs index 5e6f8fc984d..ec36660b530 100644 --- a/MonoGame.Framework/Graphics/Vertices/VertexBufferBindings.cs +++ b/MonoGame.Framework/Graphics/Vertices/VertexBufferBindings.cs @@ -165,5 +165,23 @@ public VertexBufferBinding[] Get() return bindings; } + + /// + /// Creates an that can be used as a key in the + /// . + /// + /// The . + internal ImmutableVertexInputLayout ToImmutable() + { + int count = Count; + + var vertexDeclarations = new VertexDeclaration[count]; + Array.Copy(VertexDeclarations, vertexDeclarations, count); + + var instanceFrequencies = new int[count]; + Array.Copy(InstanceFrequencies, instanceFrequencies, count); + + return new ImmutableVertexInputLayout(vertexDeclarations, instanceFrequencies); + } } } diff --git a/MonoGame.Framework/Input/KeyboardState.cs b/MonoGame.Framework/Input/KeyboardState.cs index 35277979bea..85cc98dfb6c 100644 --- a/MonoGame.Framework/Input/KeyboardState.cs +++ b/MonoGame.Framework/Input/KeyboardState.cs @@ -2,6 +2,7 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using System; using System.Collections.Generic; namespace Microsoft.Xna.Framework.Input @@ -95,14 +96,6 @@ internal void InternalClearAllKeys() internal KeyboardState(List keys, bool capsLock = false, bool numLock = false) : this() { - _keys0 = 0; - _keys1 = 0; - _keys2 = 0; - _keys3 = 0; - _keys4 = 0; - _keys5 = 0; - _keys6 = 0; - _keys7 = 0; _modifiers = (byte)(0 | (capsLock ? CapsLockModifier : 0) | (numLock ? NumLockModifier : 0)); if (keys != null) @@ -118,14 +111,6 @@ internal KeyboardState(List keys, bool capsLock = false, bool numLock = fa /// Num Lock state. public KeyboardState(Keys[] keys, bool capsLock = false, bool numLock = false) : this() { - _keys0 = 0; - _keys1 = 0; - _keys2 = 0; - _keys3 = 0; - _keys4 = 0; - _keys5 = 0; - _keys6 = 0; - _keys7 = 0; _modifiers = (byte)(0 | (capsLock ? CapsLockModifier : 0) | (numLock ? NumLockModifier : 0)); if (keys != null) @@ -139,16 +124,6 @@ public KeyboardState(Keys[] keys, bool capsLock = false, bool numLock = false) : /// List of keys to be flagged as pressed on initialization. public KeyboardState(params Keys[] keys) : this() { - _keys0 = 0; - _keys1 = 0; - _keys2 = 0; - _keys3 = 0; - _keys4 = 0; - _keys5 = 0; - _keys6 = 0; - _keys7 = 0; - _modifiers = 0; - if (keys != null) foreach (Keys k in keys) InternalSetKey(k); diff --git a/MonoGame.Framework/Media/MediaQueue.cs b/MonoGame.Framework/Media/MediaQueue.cs index 11e7b9bdb21..4b7fc1b57fb 100644 --- a/MonoGame.Framework/Media/MediaQueue.cs +++ b/MonoGame.Framework/Media/MediaQueue.cs @@ -111,14 +111,14 @@ internal void Clear() for(; songs.Count > 0; ) { song = songs[0]; -#if !DIRECTX && !NATIVE +#if !DIRECTX song.Stop(); #endif songs.Remove(song); } } -#if !DIRECTX && !NATIVE +#if !DIRECTX internal void SetVolume(float volume) { int count = songs.Count; @@ -132,7 +132,7 @@ internal void Add(Song song) songs.Add(song); } -#if !DIRECTX && !NATIVE +#if !DIRECTX internal void Stop() { int count = songs.Count; diff --git a/MonoGame.Framework/Media/Song.cs b/MonoGame.Framework/Media/Song.cs index 60e30642b39..740ff708166 100644 --- a/MonoGame.Framework/Media/Song.cs +++ b/MonoGame.Framework/Media/Song.cs @@ -48,7 +48,7 @@ public bool IsDisposed get { return disposed; } } -#if ANDROID || OPENAL || WEB || IOS +#if ANDROID || OPENAL || WEB || IOS || NATIVE internal delegate void FinishedPlayingHandler(object sender, EventArgs args); #if !DESKTOPGL event FinishedPlayingHandler DonePlaying; diff --git a/MonoGame.Framework/Media/Video.cs b/MonoGame.Framework/Media/Video.cs index 3179bb6016d..998fdf8af85 100644 --- a/MonoGame.Framework/Media/Video.cs +++ b/MonoGame.Framework/Media/Video.cs @@ -83,7 +83,7 @@ void Dispose(bool disposing) { if (!_disposed) { - //PlatformDispose(disposing); + PlatformDispose(disposing); _disposed = true; } } diff --git a/MonoGame.Framework/MonoGame.Framework.Native.csproj b/MonoGame.Framework/MonoGame.Framework.Native.csproj index c040237d332..dd48f27cb4d 100644 --- a/MonoGame.Framework/MonoGame.Framework.Native.csproj +++ b/MonoGame.Framework/MonoGame.Framework.Native.csproj @@ -1,4 +1,4 @@ - + net8.0 @@ -9,6 +9,8 @@ MonoGame.Framework.Native False True + Debug;Release + AnyCPU @@ -18,11 +20,31 @@ + + + + + + + + + + + + + + + + + diff --git a/MonoGame.Framework/Platform/Android/AndroidGameWindow.cs b/MonoGame.Framework/Platform/Android/AndroidGameWindow.cs index 88b12475f57..334c0869650 100644 --- a/MonoGame.Framework/Platform/Android/AndroidGameWindow.cs +++ b/MonoGame.Framework/Platform/Android/AndroidGameWindow.cs @@ -24,6 +24,17 @@ public class AndroidGameWindow : GameWindow, IDisposable public override IntPtr Handle { get { return IntPtr.Zero; } } + public override Point Position + { + get + { + return Point.Zero; + } + + set + { + } + } public void SetResumer(IResumeManager resumer) { diff --git a/MonoGame.Framework/Platform/DirectX.targets b/MonoGame.Framework/Platform/DirectX.targets index 927afc66900..288fbab2938 100644 --- a/MonoGame.Framework/Platform/DirectX.targets +++ b/MonoGame.Framework/Platform/DirectX.targets @@ -27,11 +27,9 @@ - - diff --git a/MonoGame.Framework/Platform/Graphics/Effect/Resources/AlphaTestEffect.dx11.mgfxo b/MonoGame.Framework/Platform/Graphics/Effect/Resources/AlphaTestEffect.dx11.mgfxo index 6cc09e02bd4..330b893bb8a 100644 Binary files a/MonoGame.Framework/Platform/Graphics/Effect/Resources/AlphaTestEffect.dx11.mgfxo and b/MonoGame.Framework/Platform/Graphics/Effect/Resources/AlphaTestEffect.dx11.mgfxo differ diff --git a/MonoGame.Framework/Platform/Graphics/Effect/Resources/AlphaTestEffect.ogl.mgfxo b/MonoGame.Framework/Platform/Graphics/Effect/Resources/AlphaTestEffect.ogl.mgfxo index 8bd2be9fd1e..41781356ad7 100644 Binary files a/MonoGame.Framework/Platform/Graphics/Effect/Resources/AlphaTestEffect.ogl.mgfxo and b/MonoGame.Framework/Platform/Graphics/Effect/Resources/AlphaTestEffect.ogl.mgfxo differ diff --git a/MonoGame.Framework/Platform/Graphics/Effect/Resources/BasicEffect.dx11.mgfxo b/MonoGame.Framework/Platform/Graphics/Effect/Resources/BasicEffect.dx11.mgfxo index d4866a23458..9d056ad2055 100644 Binary files a/MonoGame.Framework/Platform/Graphics/Effect/Resources/BasicEffect.dx11.mgfxo and b/MonoGame.Framework/Platform/Graphics/Effect/Resources/BasicEffect.dx11.mgfxo differ diff --git a/MonoGame.Framework/Platform/Graphics/Effect/Resources/BasicEffect.ogl.mgfxo b/MonoGame.Framework/Platform/Graphics/Effect/Resources/BasicEffect.ogl.mgfxo index 9141ce442bb..792baf29203 100644 Binary files a/MonoGame.Framework/Platform/Graphics/Effect/Resources/BasicEffect.ogl.mgfxo and b/MonoGame.Framework/Platform/Graphics/Effect/Resources/BasicEffect.ogl.mgfxo differ diff --git a/MonoGame.Framework/Platform/Graphics/Effect/Resources/EnvironmentMapEffect.ogl.mgfxo b/MonoGame.Framework/Platform/Graphics/Effect/Resources/EnvironmentMapEffect.ogl.mgfxo index c981b9ab6d4..9c1bc470423 100644 Binary files a/MonoGame.Framework/Platform/Graphics/Effect/Resources/EnvironmentMapEffect.ogl.mgfxo and b/MonoGame.Framework/Platform/Graphics/Effect/Resources/EnvironmentMapEffect.ogl.mgfxo differ diff --git a/MonoGame.Framework/Platform/Graphics/Effect/Resources/Lighting.fxh b/MonoGame.Framework/Platform/Graphics/Effect/Resources/Lighting.fxh index 6b82db49dd1..46585545ce5 100644 --- a/MonoGame.Framework/Platform/Graphics/Effect/Resources/Lighting.fxh +++ b/MonoGame.Framework/Platform/Graphics/Effect/Resources/Lighting.fxh @@ -20,7 +20,7 @@ ColorPair ComputeLights(float3 eyeVector, float3 worldNormal, uniform int numLig float3x3 lightSpecular = 0; float3x3 halfVectors = 0; - [unroll] + UNROLL for (int i = 0; i < numLights; i++) { lightDirections[i] = float3x3(DirLight0Direction, DirLight1Direction, DirLight2Direction) [i]; diff --git a/MonoGame.Framework/Platform/Graphics/Effect/Resources/Macros.fxh b/MonoGame.Framework/Platform/Graphics/Effect/Resources/Macros.fxh index 7b1d31e05f6..e438b24acd7 100644 --- a/MonoGame.Framework/Platform/Graphics/Effect/Resources/Macros.fxh +++ b/MonoGame.Framework/Platform/Graphics/Effect/Resources/Macros.fxh @@ -5,7 +5,34 @@ // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- -#ifdef SM4 + +#if defined(SM6) || defined(VULKAN) + +#define TECHNIQUE(name, vsname, psname ) \ + technique name { pass { VertexShader = compile vs_6_0 vsname (); PixelShader = compile ps_6_0 psname(); } } + +#define BEGIN_CONSTANTS cbuffer _MG_Globals : register(b0) { +#define MATRIX_CONSTANTS +#define END_CONSTANTS }; + +#define _vs(r) +#define _ps(r) +#define _cb(r) + +#define DECLARE_TEXTURE(Name, index) \ + Texture2D Name : register(t##index); \ + sampler Name##Sampler : register(s##index) + +#define DECLARE_CUBEMAP(Name, index) \ + TextureCube Name : register(t##index); \ + sampler Name##Sampler : register(s##index) + +#define SAMPLE_TEXTURE(Name, texCoord) Name.Sample(Name##Sampler, texCoord) +#define SAMPLE_CUBEMAP(Name, texCoord) Name.Sample(Name##Sampler, texCoord) + +#define UNROLL [unroll] + +#elif defined(SM4) // Macros for targetting shader model 4.0 (DX11) @@ -31,6 +58,7 @@ #define SAMPLE_TEXTURE(Name, texCoord) Name.Sample(Name##Sampler, texCoord) #define SAMPLE_CUBEMAP(Name, texCoord) Name.Sample(Name##Sampler, texCoord) +#define UNROLL [unroll] #else @@ -57,5 +85,6 @@ #define SAMPLE_TEXTURE(Name, texCoord) tex2D(Name, texCoord) #define SAMPLE_CUBEMAP(Name, texCoord) texCUBE(Name, texCoord) +#define UNROLL [unroll] #endif diff --git a/MonoGame.Framework/Platform/Graphics/Effect/Resources/RebuildMGFX.bat b/MonoGame.Framework/Platform/Graphics/Effect/Resources/RebuildMGFX.bat index 8d34282f66f..a8b0f5c33aa 100644 --- a/MonoGame.Framework/Platform/Graphics/Effect/Resources/RebuildMGFX.bat +++ b/MonoGame.Framework/Platform/Graphics/Effect/Resources/RebuildMGFX.bat @@ -3,13 +3,30 @@ setlocal SET MGFXC="..\..\..\..\..\Artifacts\MonoGame.Effect.Compiler\Release\mgfxc.exe" +echo --------------------------------------------------------------- +echo OpenGL +echo --------------------------------------------------------------- +echo. @for /f %%f IN ('dir /b *.fx') do ( - call %MGFXC% %%~nf.fx %%~nf.ogl.mgfxo + echo %%~f + call %MGFXC% %%~f %%~nf.ogl.mgfxo + echo. - call %MGFXC% %%~nf.fx %%~nf.dx11.mgfxo /Profile:DirectX_11 +) +echo. + +echo --------------------------------------------------------------- +echo DirectX 11 +echo --------------------------------------------------------------- +echo. +@for /f %%f IN ('dir /b *.fx') do ( + echo %%~f + call %MGFXC% %%~f %%~nf.dx11.mgfxo /Profile:DirectX_11 + echo. ) +echo. endlocal pause diff --git a/MonoGame.Framework/Platform/Graphics/Effect/Resources/SkinnedEffect.dx11.mgfxo b/MonoGame.Framework/Platform/Graphics/Effect/Resources/SkinnedEffect.dx11.mgfxo index e5172fba872..d3f798a9419 100644 Binary files a/MonoGame.Framework/Platform/Graphics/Effect/Resources/SkinnedEffect.dx11.mgfxo and b/MonoGame.Framework/Platform/Graphics/Effect/Resources/SkinnedEffect.dx11.mgfxo differ diff --git a/MonoGame.Framework/Platform/Graphics/Effect/Resources/SkinnedEffect.fx b/MonoGame.Framework/Platform/Graphics/Effect/Resources/SkinnedEffect.fx index 951161c7d95..0df33bf39b6 100644 --- a/MonoGame.Framework/Platform/Graphics/Effect/Resources/SkinnedEffect.fx +++ b/MonoGame.Framework/Platform/Graphics/Effect/Resources/SkinnedEffect.fx @@ -58,7 +58,7 @@ void Skin(inout VSInputNmTxWeights vin, uniform int boneCount) { float4x3 skinning = 0; - [unroll] + UNROLL for (int i = 0; i < boneCount; i++) { skinning += Bones[vin.Indices[i]] * vin.Weights[i]; diff --git a/MonoGame.Framework/Platform/Graphics/Effect/Resources/SkinnedEffect.ogl.mgfxo b/MonoGame.Framework/Platform/Graphics/Effect/Resources/SkinnedEffect.ogl.mgfxo index 15a629118de..77059f48455 100644 Binary files a/MonoGame.Framework/Platform/Graphics/Effect/Resources/SkinnedEffect.ogl.mgfxo and b/MonoGame.Framework/Platform/Graphics/Effect/Resources/SkinnedEffect.ogl.mgfxo differ diff --git a/MonoGame.Framework/Platform/Graphics/Effect/Resources/Structures.fxh b/MonoGame.Framework/Platform/Graphics/Effect/Resources/Structures.fxh index ecf2ea37384..990f2cb2db3 100644 --- a/MonoGame.Framework/Platform/Graphics/Effect/Resources/Structures.fxh +++ b/MonoGame.Framework/Platform/Graphics/Effect/Resources/Structures.fxh @@ -80,7 +80,7 @@ struct VSInputNmTxWeights float4 Position : POSITION0; float3 Normal : NORMAL0; float2 TexCoord : TEXCOORD0; - uint4 Indices : BLENDINDICES0; + int4 Indices : BLENDINDICES0; float4 Weights : BLENDWEIGHT0; }; diff --git a/MonoGame.Framework/Platform/Graphics/SamplerStateCollection.DirectX.cs b/MonoGame.Framework/Platform/Graphics/SamplerStateCollection.DirectX.cs index c86cce66aaf..b750f935e70 100644 --- a/MonoGame.Framework/Platform/Graphics/SamplerStateCollection.DirectX.cs +++ b/MonoGame.Framework/Platform/Graphics/SamplerStateCollection.DirectX.cs @@ -27,7 +27,7 @@ private void PlatformDirty() internal void PlatformSetSamplers(GraphicsDevice device) { - if (_applyToVertexStage && !device.GraphicsCapabilities.SupportsVertexTextures) + if (_stage == ShaderStage.Vertex && !device.GraphicsCapabilities.SupportsVertexTextures) return; // Skip out if nothing has changed. @@ -37,7 +37,7 @@ internal void PlatformSetSamplers(GraphicsDevice device) // NOTE: We make the assumption here that the caller has // locked the d3dContext for us to use. SharpDX.Direct3D11.CommonShaderStage shaderStage; - if (_applyToVertexStage) + if (_stage == ShaderStage.Vertex) shaderStage = device._d3dContext.VertexShader; else shaderStage = device._d3dContext.PixelShader; diff --git a/MonoGame.Framework/Platform/Graphics/Texture3D.DirectX.cs b/MonoGame.Framework/Platform/Graphics/Texture3D.DirectX.cs index 53c3a09c4db..dc7f3d6aae4 100644 --- a/MonoGame.Framework/Platform/Graphics/Texture3D.DirectX.cs +++ b/MonoGame.Framework/Platform/Graphics/Texture3D.DirectX.cs @@ -62,8 +62,11 @@ internal override Resource CreateTexture() private void PlatformSetData(int level, int left, int top, int right, int bottom, int front, int back, - T[] data, int startIndex, int elementCount, int width, int height, int depth) + T[] data, int startIndex, int elementCount) { + var width = right - left; + var height = bottom - top; + var elementSizeInByte = ReflectionHelpers.SizeOf.Get(); var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); try diff --git a/MonoGame.Framework/Platform/Graphics/Texture3D.OpenGL.cs b/MonoGame.Framework/Platform/Graphics/Texture3D.OpenGL.cs index 4cb3ca8ada6..73141f73e4f 100644 --- a/MonoGame.Framework/Platform/Graphics/Texture3D.OpenGL.cs +++ b/MonoGame.Framework/Platform/Graphics/Texture3D.OpenGL.cs @@ -41,11 +41,15 @@ private void PlatformConstruct(GraphicsDevice graphicsDevice, int width, int hei private void PlatformSetData( int level, int left, int top, int right, int bottom, int front, int back, - T[] data, int startIndex, int elementCount, int width, int height, int depth) + T[] data, int startIndex, int elementCount) { #if GLES throw new NotSupportedException("OpenGL ES 2.0 doesn't support 3D textures."); #else + var width = right - left; + var height = bottom - top; + var depth = back - front; + Threading.BlockOnUIThread(() => { var elementSizeInByte = Marshal.SizeOf(); diff --git a/MonoGame.Framework/Platform/Graphics/Texture3D.Web.cs b/MonoGame.Framework/Platform/Graphics/Texture3D.Web.cs index 112e7114972..fc5741a4f2b 100644 --- a/MonoGame.Framework/Platform/Graphics/Texture3D.Web.cs +++ b/MonoGame.Framework/Platform/Graphics/Texture3D.Web.cs @@ -30,10 +30,7 @@ private void PlatformSetData( int back, T[] data, int startIndex, - int elementCount, - int width, - int height, - int depth) + int elementCount) { throw new NotImplementedException(); } diff --git a/MonoGame.Framework/Platform/Graphics/TextureCollection.DirectX.cs b/MonoGame.Framework/Platform/Graphics/TextureCollection.DirectX.cs index 1dffcacdd43..d6048d9d5f6 100644 --- a/MonoGame.Framework/Platform/Graphics/TextureCollection.DirectX.cs +++ b/MonoGame.Framework/Platform/Graphics/TextureCollection.DirectX.cs @@ -12,10 +12,10 @@ void PlatformInit() internal void ClearTargets(GraphicsDevice device, RenderTargetBinding[] targets) { - if (_applyToVertexStage && !device.GraphicsCapabilities.SupportsVertexTextures) + if (_stage == ShaderStage.Vertex && !device.GraphicsCapabilities.SupportsVertexTextures) return; - if (_applyToVertexStage) + if (_stage == ShaderStage.Vertex) ClearTargets(targets, device._d3dContext.VertexShader); else ClearTargets(targets, device._d3dContext.PixelShader); @@ -59,7 +59,7 @@ void PlatformSetTextures(GraphicsDevice device) // NOTE: We make the assumption here that the caller has // locked the d3dContext for us to use. SharpDX.Direct3D11.CommonShaderStage shaderStage; - if (_applyToVertexStage) + if (_stage == ShaderStage.Vertex) shaderStage = device._d3dContext.VertexShader; else shaderStage = device._d3dContext.PixelShader; diff --git a/MonoGame.Framework/Platform/Graphics/Vertices/VertexBufferBindings.DirectX.cs b/MonoGame.Framework/Platform/Graphics/Vertices/VertexBufferBindings.DirectX.cs deleted file mode 100644 index d3ea1536655..00000000000 --- a/MonoGame.Framework/Platform/Graphics/Vertices/VertexBufferBindings.DirectX.cs +++ /dev/null @@ -1,30 +0,0 @@ -// MonoGame - Copyright (C) MonoGame Foundation, Inc -// This file is subject to the terms and conditions defined in -// file 'LICENSE.txt', which is part of this source code package. - -using System; - - -namespace Microsoft.Xna.Framework.Graphics -{ - partial class VertexBufferBindings - { - /// - /// Creates an that can be used as a key in the - /// . - /// - /// The . - public ImmutableVertexInputLayout ToImmutable() - { - int count = Count; - - var vertexDeclarations = new VertexDeclaration[count]; - Array.Copy(VertexDeclarations, vertexDeclarations, count); - - var instanceFrequencies = new int[count]; - Array.Copy(InstanceFrequencies, instanceFrequencies, count); - - return new ImmutableVertexInputLayout(vertexDeclarations, instanceFrequencies); - } - } -} diff --git a/MonoGame.Framework/Platform/Native/Audio.Interop.cs b/MonoGame.Framework/Platform/Native/Audio.Interop.cs new file mode 100644 index 00000000000..f9fd08b2af4 --- /dev/null +++ b/MonoGame.Framework/Platform/Native/Audio.Interop.cs @@ -0,0 +1,196 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using System; +using System.Runtime.InteropServices; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Audio; +using MonoGame.Framework.Utilities; + + +namespace MonoGame.Interop; + +[MGHandle] +internal readonly struct MGA_System { } + +[MGHandle] +internal readonly struct MGA_Buffer { } + +[MGHandle] +internal readonly struct MGA_Voice { } + + +internal struct ReverbSettings +{ + public float ReflectionsDelayMs; + public float ReverbDelayMs; + public float PositionLeft; + public float PositionRight; + public float PositionLeftMatrix; + public float PositionRightMatrix; + public float EarlyDiffusion; + public float LateDiffusion; + public float LowEqGain; + public float LowEqCutoff; + public float HighEqGain; + public float HighEqCutoff; + public float RearDelayMs; + public float RoomFilterFrequencyHz; + public float RoomFilterMainDb; + public float RoomFilterHighFrequencyDb; + public float ReflectionsGainDb; + public float ReverbGainDb; + public float DecayTimeSec; + public float DensityPct; + public float RoomSizeFeet; + public float WetDryMixPct; +} + +internal struct Listener +{ + public Vector3 Position; + public Vector3 Forward; + public Vector3 Up; + public Vector3 Velocity; +}; + +internal struct Emitter +{ + public Vector3 Position; + public Vector3 Forward; + public Vector3 Up; + public Vector3 Velocity; + public float DopplerScale; +}; + + + +/// +/// MonoGame native calls for platform audio features. +/// +internal static unsafe partial class MGA +{ + #region System + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void NativeFinishedCallback(nint callbackData); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_System_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGA_System* System_Create(); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_System_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void System_Destroy(MGA_System* system); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_System_GetMaxInstances", StringMarshalling = StringMarshalling.Utf8)] + public static partial int System_GetMaxInstances(); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_System_SetReverbSettings", StringMarshalling = StringMarshalling.Utf8)] + public static partial void System_SetReverbSettings(MGA_System* system, in ReverbSettings settings); + + #endregion + + #region Buffer + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Buffer_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGA_Buffer* Buffer_Create(MGA_System* system); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Buffer_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Buffer_Destroy(MGA_Buffer* buffer); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Buffer_InitializeFormat", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Buffer_InitializeFormat( + MGA_Buffer* buffer, + byte[] waveHeader, + byte[] waveData, + int length, + int loopStart, + int loopLength); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Buffer_InitializePCM", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Buffer_InitializePCM( + MGA_Buffer* buffer, + byte[] waveData, + int offset, + int length, + int sampleBits, + int sampleRate, + int channels, + int loopStart, + int loopLength); + + // TODO: This should go away after we move to FAudio's Xact implementation. + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Buffer_InitializeXact", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Buffer_InitializeXact( + MGA_Buffer* buffer, + uint codec, + byte[] waveData, + int length, + int sampleRate, + int blockAlignment, + int channels, + int loopStart, + int loopLength); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Buffer_GetDuration", StringMarshalling = StringMarshalling.Utf8)] + public static partial ulong Buffer_GetDuration(MGA_Buffer* buffer); + + #endregion + + #region Voice + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGA_Voice* Voice_Create(MGA_System* system); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_Destroy(MGA_Voice* voice); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_GetBufferCount", StringMarshalling = StringMarshalling.Utf8)] + public static partial int Voice_GetBufferCount(MGA_Voice* voice); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_SetBuffer", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_SetBuffer(MGA_Voice* voice, MGA_Buffer* buffer); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_AppendBuffer", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_AppendBuffer(MGA_Voice* voice, byte[] buffer, int offset, int count, [MarshalAs(UnmanagedType.U1)] bool clear); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_Play", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_Play(MGA_Voice* voice, [MarshalAs(UnmanagedType.U1)] bool looped); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_Pause", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_Pause(MGA_Voice* voice); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_Resume", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_Resume(MGA_Voice* voice); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_Stop", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_Stop(MGA_Voice* voice, [MarshalAs(UnmanagedType.U1)] bool immediate); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_GetState", StringMarshalling = StringMarshalling.Utf8)] + public static partial SoundState Voice_GetState(MGA_Voice* voice); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_SetPan", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_SetPan(MGA_Voice* voice, float pan); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_SetPitch", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_SetPitch(MGA_Voice* voice, float pitch); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_SetVolume", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_SetVolume(MGA_Voice* voice, float volume); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_SetReverbMix", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_SetReverbMix(MGA_Voice* voice, float mix); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_SetFilterMode", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_SetFilterMode(MGA_Voice* voice, FilterMode mode, float filterQ, float frequency); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_ClearFilterMode", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_ClearFilterMode(MGA_Voice* voice); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGA_Voice_Apply3D", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Voice_Apply3D(MGA_Voice* voice, in Listener listener, in Emitter emitter, float distanceScale); + + #endregion +} + + diff --git a/MonoGame.Framework/Platform/Native/BlendState.Native.cs b/MonoGame.Framework/Platform/Native/BlendState.Native.cs new file mode 100644 index 00000000000..0b3330143b1 --- /dev/null +++ b/MonoGame.Framework/Platform/Native/BlendState.Native.cs @@ -0,0 +1,51 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using MonoGame.Interop; +namespace Microsoft.Xna.Framework.Graphics; + +public partial class BlendState +{ + internal unsafe MGG_BlendState* Handle; + + internal unsafe void PlatformApplyState(GraphicsDevice device) + { + if (Handle == null) + { + var info = new MGG_BlendState_Info[4]; + for (int i = 0; i < 4; i++) + { + var state = _targetBlendState[i]; + + info[i] = new MGG_BlendState_Info() + { + colorSourceBlend = state.ColorSourceBlend, + colorDestBlend = state.ColorDestinationBlend, + colorBlendFunc = state.ColorBlendFunction, + alphaSourceBlend = state.AlphaSourceBlend, + alphaDestBlend = state.AlphaDestinationBlend, + alphaBlendFunc = state.AlphaBlendFunction, + colorWriteChannels = state.ColorWriteChannels + }; + } + + fixed (MGG_BlendState_Info* ptr = info) + Handle = MGG.BlendState_Create(device.Handle, ptr); + } + + MGG.GraphicsDevice_SetBlendState(device.Handle, Handle, _blendFactor.R / 255.0f, _blendFactor.G / 255.0f, _blendFactor.B / 255.0f, _blendFactor.A / 255.0f); + } + + partial void PlatformDispose() + { + unsafe + { + if (Handle != null) + { + MGG.BlendState_Destroy(GraphicsDevice.Handle, Handle); + Handle = null; + } + } + } +} diff --git a/MonoGame.Framework/Platform/Native/ConstantBuffer.Native.cs b/MonoGame.Framework/Platform/Native/ConstantBuffer.Native.cs index 509b51b4522..136ebc53346 100644 --- a/MonoGame.Framework/Platform/Native/ConstantBuffer.Native.cs +++ b/MonoGame.Framework/Platform/Native/ConstantBuffer.Native.cs @@ -2,22 +2,52 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; +using System; +using System.Collections.Generic; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; + namespace Microsoft.Xna.Framework.Graphics; internal partial class ConstantBuffer { - private void PlatformInitialize() - { + internal unsafe MGG_Buffer* Handle; + private unsafe void PlatformInitialize() + { + Handle = MGG.Buffer_Create(GraphicsDevice.Handle, BufferType.Constant, _buffer.Length); } private void PlatformClear() { + // TODO: What is this for? + throw new NotImplementedException(); + } + + internal unsafe void PlatformApply(GraphicsDevice device, ShaderStage stage, int slot) + { + if (Handle == null) + PlatformInitialize(); + + if (_dirty) + { + fixed (byte* data = &_buffer[0]) + MGG.Buffer_SetData(GraphicsDevice.Handle, ref Handle, 0, data, _buffer.Length, true); + _dirty = false; + } + MGG.GraphicsDevice_SetConstantBuffer(GraphicsDevice.Handle, stage, slot, Handle); } - internal void PlatformApply(GraphicsDevice device, ShaderStage stage, int slot) + protected override unsafe void Dispose(bool disposing) { + if (Handle != null) + { + MGG.Buffer_Destroy(GraphicsDevice.Handle, Handle); + Handle = null; + } + base.Dispose(disposing); } } diff --git a/MonoGame.Framework/Platform/Native/DepthStencilState.Native.cs b/MonoGame.Framework/Platform/Native/DepthStencilState.Native.cs index b7618f0d876..21c1cc963e6 100644 --- a/MonoGame.Framework/Platform/Native/DepthStencilState.Native.cs +++ b/MonoGame.Framework/Platform/Native/DepthStencilState.Native.cs @@ -2,12 +2,45 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; namespace Microsoft.Xna.Framework.Graphics; public partial class DepthStencilState { - internal void PlatformApplyState(GraphicsDevice device) + internal unsafe MGG_DepthStencilState* Handle; + + internal unsafe void PlatformApplyState(GraphicsDevice device) { + if (Handle == null) + { + MGG_DepthStencilState_Info info; + info.depthBufferEnable = DepthBufferEnable; + info.depthBufferWriteEnable = DepthBufferWriteEnable; + info.depthBufferFunction = DepthBufferFunction; + info.referenceStencil = ReferenceStencil; + info.stencilEnable = StencilEnable; + info.stencilMask = StencilMask; + info.stencilWriteMask = StencilWriteMask; + info.stencilFunction = StencilFunction; + info.stencilDepthBufferFail = StencilDepthBufferFail; + info.stencilFail = StencilFail; + info.stencilPass = StencilPass; + + Handle = MGG.DepthStencilState_Create(device.Handle, &info); + } + MGG.GraphicsDevice_SetDepthStencilState(device.Handle, Handle); + } + + partial void PlatformDispose() + { + unsafe + { + if (Handle != null) + { + MGG.DepthStencilState_Destroy(GraphicsDevice.Handle, Handle); + Handle = null; + } + } } } diff --git a/MonoGame.Framework/Platform/Native/DynamicSoundEffectInstance.Native.cs b/MonoGame.Framework/Platform/Native/DynamicSoundEffectInstance.Native.cs index 30c5496cb69..2270927e7c1 100644 --- a/MonoGame.Framework/Platform/Native/DynamicSoundEffectInstance.Native.cs +++ b/MonoGame.Framework/Platform/Native/DynamicSoundEffectInstance.Native.cs @@ -2,44 +2,72 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; +using System; + namespace Microsoft.Xna.Framework.Audio; public sealed partial class DynamicSoundEffectInstance : SoundEffectInstance { - private void PlatformCreate() + private unsafe void PlatformCreate() { + Voice = MGA.Voice_Create(SoundEffect.System); } - private int PlatformGetPendingBufferCount() + private unsafe int PlatformGetPendingBufferCount() { + if (Voice != null) + return MGA.Voice_GetBufferCount(Voice); + return 0; } - private void PlatformPlay() + private unsafe void PlatformPlay() { + if (Voice != null) + MGA.Voice_Play(Voice, true); } - private void PlatformPause() + private unsafe void PlatformPause() { + if (Voice != null) + MGA.Voice_Pause(Voice); } - private void PlatformResume() + private unsafe void PlatformResume() { + if (Voice != null) + MGA.Voice_Resume(Voice); } - private void PlatformStop() + private unsafe void PlatformStop() { + if (Voice != null) + MGA.Voice_Stop(Voice, true); } - private void PlatformSubmitBuffer(byte[] buffer, int offset, int count) + private unsafe void PlatformSubmitBuffer(byte[] buffer, int offset, int count) { + if (Voice != null) + MGA.Voice_AppendBuffer(Voice, buffer, offset, count, false); } - private void PlatformDispose(bool disposing) + private unsafe void PlatformDispose(bool disposing) { + if (disposing) + { + if (Voice != null) + { + MGA.Voice_Destroy(Voice); + Voice = null; + } + } } private void PlatformUpdateQueue() { + // TODO: This really shouldn't be per-instance + // instead this should be handled internally by + // the native sound system. } } diff --git a/MonoGame.Framework/Platform/Native/EffectResource.Native.cs b/MonoGame.Framework/Platform/Native/EffectResource.Native.cs index d4f1ec39795..8ae36a1d356 100644 --- a/MonoGame.Framework/Platform/Native/EffectResource.Native.cs +++ b/MonoGame.Framework/Platform/Native/EffectResource.Native.cs @@ -2,15 +2,28 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; +using System.Runtime.InteropServices; + namespace Microsoft.Xna.Framework.Graphics; internal partial class EffectResource { - // TODO: These should be loaded from the native library and not from the C# embedded resources! - const string AlphaTestEffectName = "Microsoft.Xna.Framework.Platform.Graphics.Effect.Resources.AlphaTestEffect.ogl.mgfxo"; - const string BasicEffectName = "Microsoft.Xna.Framework.Platform.Graphics.Effect.Resources.BasicEffect.ogl.mgfxo"; - const string DualTextureEffectName = "Microsoft.Xna.Framework.Platform.Graphics.Effect.Resources.DualTextureEffect.ogl.mgfxo"; - const string EnvironmentMapEffectName = "Microsoft.Xna.Framework.Platform.Graphics.Effect.Resources.EnvironmentMapEffect.ogl.mgfxo"; - const string SkinnedEffectName = "Microsoft.Xna.Framework.Platform.Graphics.Effect.Resources.SkinnedEffect.ogl.mgfxo"; - const string SpriteEffectName = "Microsoft.Xna.Framework.Platform.Graphics.Effect.Resources.SpriteEffect.ogl.mgfxo"; + const string AlphaTestEffectName = "AlphaTestEffect"; + const string BasicEffectName = "BasicEffect"; + const string DualTextureEffectName = "DualTextureEffect"; + const string EnvironmentMapEffectName = "EnvironmentMapEffect"; + const string SkinnedEffectName = "SkinnedEffect"; + const string SpriteEffectName = "SpriteEffect"; + + private static unsafe byte[] PlatformGetBytecode(string name) + { + byte* data; + int size; + MGG.EffectResource_GetBytecode(name, out data, out size); + + var bytecode = new byte[size]; + Marshal.Copy((nint)data, bytecode, 0, size); + return bytecode; + } } diff --git a/MonoGame.Framework/Platform/Native/GamePad.Native.cs b/MonoGame.Framework/Platform/Native/GamePad.Native.cs index 28298bad659..5e2acfade28 100644 --- a/MonoGame.Framework/Platform/Native/GamePad.Native.cs +++ b/MonoGame.Framework/Platform/Native/GamePad.Native.cs @@ -2,22 +2,180 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; +using System; +using System.Collections; +using System.Collections.Generic; + namespace Microsoft.Xna.Framework.Input; static partial class GamePad { + static int MaxSupported = MGP.GamePad_GetMaxSupported(); + + class State + { + public int Identifier; + public int Index; + + public ulong Timestamp; + + public Buttons Buttons; + public Vector2 ThumbstickL; + public Vector2 ThumbstickR; + public float TriggerL; + public float TriggerR; + + public GamePadCapabilities Caps; + } + + private static readonly Dictionary _stateByIndex = new Dictionary(); + private static readonly Dictionary _stateById = new Dictionary(); + + internal static void Add(int identifier) + { + var state = new State(); + state.Identifier = identifier; + state.Caps.IsConnected = true; + + // TODO: Maybe the platform should supply + // the correct player index as some platforms + // could define this. + + for (int i = 0; i < MaxSupported; i++) + { + // Add it to the first empty player index. + if (!_stateByIndex.ContainsKey(i)) + { + state.Index = i; + _stateByIndex.Add(i, state); + _stateById.Add(identifier, state); + return; + } + } + } + + internal static void Remove(int identifier) + { + if (_stateById.TryGetValue(identifier, out var state)) + { + _stateByIndex.Remove(state.Index); + _stateById.Remove(identifier); + } + } + + private static Buttons InputToButton(ControllerInput input) + { + switch (input) + { + case ControllerInput.A: + return Buttons.A; + case ControllerInput.B: + return Buttons.B; + case ControllerInput.X: + return Buttons.X; + case ControllerInput.Y: + return Buttons.Y; + case ControllerInput.Back: + return Buttons.Back; + case ControllerInput.Guide: + return Buttons.BigButton; + case ControllerInput.Start: + return Buttons.Start; + case ControllerInput.LeftStick: + return Buttons.LeftStick; + case ControllerInput.RightStick: + return Buttons.RightStick; + case ControllerInput.LeftShoulder: + return Buttons.LeftShoulder; + case ControllerInput.RightShoulder: + return Buttons.RightShoulder; + case ControllerInput.DpadUp: + return Buttons.DPadUp; + case ControllerInput.DpadDown: + return Buttons.DPadDown; + case ControllerInput.DpadLeft: + return Buttons.DPadLeft; + case ControllerInput.DpadRight: + return Buttons.DPadRight; + } + + // Unsupported button input. + return Buttons.None; + } + + private static float FromAxisValue(short axis) + { + if (axis < 0) + return axis / 32768f; + return axis / 32767f; + } + + internal static void ChangeState(int identifier, ulong timestamp, ControllerInput input, short value) + { + if (!_stateById.TryGetValue(identifier, out var state)) + return; + + state.Timestamp = timestamp; + + if (input > ControllerInput.LAST_BUTTON) + { + switch (input) + { + case ControllerInput.LeftStickX: + state.ThumbstickL.X = FromAxisValue(value); + break; + case ControllerInput.LeftStickY: + state.ThumbstickL.Y = FromAxisValue(value); + break; + case ControllerInput.RightStickX: + state.ThumbstickR.X = FromAxisValue(value); + break; + case ControllerInput.RightStickY: + state.ThumbstickR.Y = FromAxisValue(value); + break; + case ControllerInput.LeftTrigger: + state.TriggerL = FromAxisValue(value); + break; + case ControllerInput.RightTrigger: + state.TriggerR = FromAxisValue(value); + break; + } + } + else + { + var button = InputToButton(input); + if (value == 0) + state.Buttons &= ~button; + else + state.Buttons |= button; + } + } + private static int PlatformGetMaxNumberOfGamePads() { - return 16; + return MaxSupported; } private static GamePadCapabilities PlatformGetCapabilities(int index) { + if (_stateByIndex.TryGetValue(index, out var state)) + return state.Caps; + return new GamePadCapabilities(); } private static GamePadState PlatformGetState(int index, GamePadDeadZone leftDeadZoneMode, GamePadDeadZone rightDeadZoneMode) { + if (_stateByIndex.TryGetValue(index, out var state)) + { + return new GamePadState( + new GamePadThumbSticks(state.ThumbstickL, state.ThumbstickR, leftDeadZoneMode, rightDeadZoneMode), + new GamePadTriggers(state.TriggerL, state.TriggerR), + new GamePadButtons(state.Buttons), + new GamePadDPad(state.Buttons)); + } + return new GamePadState(); } diff --git a/MonoGame.Framework/Platform/Native/GamePlatform.Native.cs b/MonoGame.Framework/Platform/Native/GamePlatform.Native.cs index ffedce44e26..696f7a64d5b 100644 --- a/MonoGame.Framework/Platform/Native/GamePlatform.Native.cs +++ b/MonoGame.Framework/Platform/Native/GamePlatform.Native.cs @@ -2,6 +2,14 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using System; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using MonoGame.Interop; +using System.Threading; + namespace Microsoft.Xna.Framework; partial class GamePlatform @@ -11,54 +19,330 @@ partial class GamePlatform class NativeGamePlatform : GamePlatform { - public NativeGamePlatform(Game game) : base(game) + internal unsafe MGP_Platform* Handle; + + private static unsafe MGG_GraphicsSystem* _system; + + private NativeGameWindow _window; + + private readonly List _dropList = new List(64); + + private int _isExiting; + + public unsafe NativeGamePlatform(Game game) : base(game) + { + Handle = MGP.Platform_Create(out GameRunBehavior behavior); + + DefaultRunBehavior = behavior; + + _window = new NativeGameWindow(this, true); + + Window = _window; + + Mouse.WindowHandle = _window.Handle; + MessageBox._window = _window._handle; + } + + internal static unsafe MGG_GraphicsSystem* GraphicsSystem { + get + { + if (_system == null) + _system = MGG.GraphicsSystem_Create(); + + return _system; + } } public override GameRunBehavior DefaultRunBehavior { get; } - public override void Exit() + public override unsafe void Exit() + { + Interlocked.Increment(ref _isExiting); + } + + public override unsafe void RunLoop() { + _window.Show(true); + + while (true) + { + PollEvents(); + + Game.Tick(); + + Threading.Run(); + if (_isExiting > 0 && ShouldExit()) + break; + else + _isExiting = 0; + } } - public override void RunLoop() + private unsafe void PollEvents() { + while (MGP.Platform_PollEvent(Handle, out MGP_Event event_)) + { + switch (event_.Type) + { + case EventType.Quit: + _isExiting++; + break; + + case EventType.WindowGainedFocus: + IsActive = true; + break; + + case EventType.WindowLostFocus: + IsActive = false; + break; + + case EventType.WindowResized: + { + var window = NativeGameWindow.FromHandle(event_.Window.Window); + if (window != null) + window.ClientResize(event_.Window.Data1, event_.Window.Data2); + break; + } + + case EventType.WindowClose: + { + var window = NativeGameWindow.FromHandle(event_.Window.Window); + if (Window == window) + _isExiting++; + break; + } + + case EventType.KeyDown: + { + var window = NativeGameWindow.FromHandle(event_.Key.Window); + var key = event_.Key.Key; + var character = (char)event_.Key.Character; + + if (!Keyboard.Keys.Contains(key)) + Keyboard.Keys.Add(key); + + if (window != null) + { + window.OnKeyDown(new InputKeyEventArgs(key)); + + if (window.IsTextInputHandled && char.IsControl(character)) + window.OnTextInput(new TextInputEventArgs(character, key)); + } + + break; + } + + case EventType.KeyUp: + { + var window = NativeGameWindow.FromHandle(event_.Key.Window); + var key = event_.Key.Key; + + Keyboard.Keys.Remove(key); + + if (window != null) + window.OnKeyUp(new InputKeyEventArgs(key)); + break; + } + + case EventType.TextInput: + { + var window = NativeGameWindow.FromHandle(event_.Key.Window); + if (window != null && window.IsTextInputHandled) + { + var key = event_.Key.Key; + var character = (char)event_.Key.Character; + window.OnTextInput(new TextInputEventArgs(character, key)); + } + break; + } + + case EventType.MouseMove: + { + var window = NativeGameWindow.FromHandle(event_.MouseMove.Window); + if (window != null) + { + window.MouseState.X = event_.MouseMove.X; + window.MouseState.Y = event_.MouseMove.Y; + } + break; + } + + case EventType.MouseWheel: + { + var window = NativeGameWindow.FromHandle(event_.MouseWheel.Window); + if (window != null) + { + window.MouseState.ScrollWheelValue = event_.MouseWheel.Scroll; + window.MouseState.HorizontalScrollWheelValue = event_.MouseWheel.ScrollH; + } + break; + } + + case EventType.MouseButtonUp: + case EventType.MouseButtonDown: + { + var window = NativeGameWindow.FromHandle(event_.MouseButton.Window); + if (window != null) + { + var state = event_.Type == EventType.MouseButtonDown ? ButtonState.Pressed : ButtonState.Released; + + switch (event_.MouseButton.Button) + { + case MouseButton.Left: + window.MouseState.LeftButton = state; + break; + case MouseButton.Right: + window.MouseState.RightButton = state; + break; + case MouseButton.Middle: + window.MouseState.MiddleButton = state; + break; + case MouseButton.X1: + window.MouseState.XButton1 = state; + break; + case MouseButton.X2: + window.MouseState.XButton2 = state; + break; + } + } + break; + } + + case EventType.ControllerAdded: + { + GamePad.Add(event_.Controller.Id); + break; + } + + case EventType.ControllerRemoved: + { + GamePad.Remove(event_.Controller.Id); + break; + } + + case EventType.ControllerStateChange: + { + GamePad.ChangeState(event_.Controller.Id, event_.Timestamp, event_.Controller.Input, event_.Controller.Value); + break; + } + + case EventType.DropFile: + { + var file = Marshal.PtrToStringUTF8(event_.Drop.File); + _dropList.Add(file); + break; + } + + case EventType.DropComplete: + { + var window = NativeGameWindow.FromHandle(event_.Drop.Window); + if (window != null ) + window.OnFileDrop(new FileDropEventArgs(_dropList.ToArray())); + _dropList.Clear(); + break; + } + } + } } - public override void StartRunLoop() + private bool ShouldExit() { + if ( Keyboard.Keys.Contains(Keys.F4) && + ( Keyboard.Keys.Contains(Keys.LeftAlt) || + Keyboard.Keys.Contains(Keys.RightAlt))) + { + return Window.AllowAltF4; + } + return true; } - public override bool BeforeUpdate(GameTime gameTime) + public override void Present() { - return false; + if (Game.GraphicsDevice != null) + Game.GraphicsDevice.Present(); } - public override bool BeforeDraw(GameTime gameTime) + public override unsafe void StartRunLoop() { - return false; + MGP.Platform_StartRunLoop(Handle); } - public override void EnterFullScreen() + public override unsafe void BeforeInitialize() { + var gdm = Game.graphicsDeviceManager; + if (gdm == null) + { + // TODO: ??? + } + else + { + var pp = Game.GraphicsDevice.PresentationParameters; + _window.OnPresentationChanged(pp); + } + + base.BeforeInitialize(); + } + public override unsafe bool BeforeRun() + { + return MGP.Platform_BeforeRun(Handle); } - public override void ExitFullScreen() + public override unsafe bool BeforeUpdate(GameTime gameTime) { + return MGP.Platform_BeforeUpdate(Handle); + } + public override unsafe bool BeforeDraw(GameTime gameTime) + { + return MGP.Platform_BeforeDraw(Handle); } - public override void BeginScreenDeviceChange(bool willBeFullScreen) + public override unsafe void EnterFullScreen() { + } + public override unsafe void ExitFullScreen() + { } + public override void BeginScreenDeviceChange(bool willBeFullScreen) + { + } public override void EndScreenDeviceChange(string screenDeviceName, int clientWidth, int clientHeight) { } + + internal override void OnPresentationChanged(PresentationParameters pp) + { + _window.OnPresentationChanged(pp); + } + + protected override unsafe void OnIsMouseVisibleChanged() + { + MGP.Mouse_SetVisible(Handle, Game.IsMouseVisible); + } + + protected unsafe override void Dispose(bool disposing) + { + if (_window != null) + { + _window.Destroy(); + _window = null; + Window = null; + } + + if (Handle != null) + { + MGP.Platform_Destroy(Handle); + Handle = null; + } + + base.Dispose(disposing); + } } diff --git a/MonoGame.Framework/Platform/Native/GameWindow.Native.cs b/MonoGame.Framework/Platform/Native/GameWindow.Native.cs index bd0ce5dbe97..3cb5daea4f7 100644 --- a/MonoGame.Framework/Platform/Native/GameWindow.Native.cs +++ b/MonoGame.Framework/Platform/Native/GameWindow.Native.cs @@ -2,35 +2,215 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using MonoGame.Framework.Utilities; +using MonoGame.Interop; using System; +using System.Collections.Generic; +using System.Drawing; namespace Microsoft.Xna.Framework; internal class NativeGameWindow : GameWindow { - public override bool AllowUserResizing { get; set; } - public override Rectangle ClientBounds { get; } + internal unsafe MGP_Window* _handle; + + private static readonly Dictionary _windows = new Dictionary(); + + private NativeGamePlatform _platform; + + private bool _primaryWindow; + + private int _width; + private int _height; + + public static NativeGameWindow FromHandle(nint handle) + { + if (_windows.TryGetValue(handle, out var window)) + return window; + + return null; + } + + public override unsafe bool AllowUserResizing + { + get + { + return MGP.Window_GetAllowUserResizing(_handle); + } + + set + { + MGP.Window_SetAllowUserResizing(_handle, value); + } + } + public override unsafe bool IsBorderless + { + get + { + return MGP.Window_GetIsBorderless(_handle); + } + + set + { + MGP.Window_SetIsBorderless(_handle, value); + } + } + + public bool IsFullScreen { get; private set; } + + public bool HardwareModeSwitch { get; private set; } + public override DisplayOrientation CurrentOrientation { get; } + public override IntPtr Handle { get; } + public override string ScreenDeviceName { get; } - public override void BeginScreenDeviceChange(bool willBeFullScreen) + public override unsafe Point Position { + get + { + int x = 0, y = 0; + if (!IsFullScreen) + MGP.Window_GetPosition(_handle, out x, out y); + + return new Point(x, y); + } + set + { + MGP.Window_SetPosition(_handle, value.X, value.Y); + } } - public override void EndScreenDeviceChange(string screenDeviceName, int clientWidth, int clientHeight) + public override Rectangle ClientBounds + { + get + { + var position = Position; + return new Rectangle(position.X, position.Y, _width, _height); + } + } + + public unsafe NativeGameWindow(NativeGamePlatform platform, bool primaryWindow) + { + _platform = platform; + _primaryWindow = primaryWindow; + + // Assume the backbuffer size as the default client size. + _width = GraphicsDeviceManager.DefaultBackBufferWidth; + _height = GraphicsDeviceManager.DefaultBackBufferHeight; + + var title = Title == null ? AssemblyHelper.GetDefaultWindowTitle() : Title; + + _handle = MGP.Window_Create( + platform.Handle, + _width, + _height, + title); + + _windows[(nint)_handle] = this; + + var icon = AssemblyHelper.GetDefaultWindowIcon(); + if (icon != null) + MGP.Window_SetIconBitmap(_handle, icon, icon.Length); + + Handle = MGP.Window_GetNativeHandle(_handle); + } + + internal unsafe void Destroy() + { + if (_handle != null) + { + _windows.Remove((nint)_handle); + MGP.Window_Destroy(_handle); + _handle = null; + } + } + + public override void BeginScreenDeviceChange(bool willBeFullScreen) { + } + public override void EndScreenDeviceChange(string screenDeviceName, int clientWidth, int clientHeight) + { } protected internal override void SetSupportedOrientations(DisplayOrientation orientations) { + } + + public unsafe void OnPresentationChanged(PresentationParameters pp) + { + if (pp.IsFullScreen && pp.HardwareModeSwitch && IsFullScreen && HardwareModeSwitch) + { + // Nothing changed... what do we do here? + } + else if (pp.IsFullScreen && (!IsFullScreen || pp.HardwareModeSwitch != HardwareModeSwitch)) + { + IsFullScreen = pp.IsFullScreen; + HardwareModeSwitch = pp.HardwareModeSwitch; + + MGP.Window_EnterFullScreen(_handle, HardwareModeSwitch); + } + else if (!pp.IsFullScreen && IsFullScreen) + { + IsFullScreen = pp.IsFullScreen; + MGP.Window_ExitFullScreen(_handle); + } + + ClientResize(pp.BackBufferWidth, pp.BackBufferHeight); } - protected override void SetTitle(string title) + public unsafe void ClientResize(int width, int height) { + if (_width == width && _height == height) + return; + + if (!IsFullScreen) + MGP.Window_SetClientSize(_handle, width, height); + UpdateBackBufferSize(width, height); + + OnClientSizeChanged(); + } + + private void UpdateBackBufferSize(int width, int height) + { + _width = width; + _height = height; + + // TODO: Implement sperate swap change logic for + // non-primary windows. + + // TODO: We should expose a feature to allow + // for either the swapchain to resize to match + // the window size or remain fixed size and stretch. + + // Only the primary window will resize the + // default back buffer. + if (!_primaryWindow) + return; + + var manager = _platform.Game.graphicsDeviceManager; + if (manager.GraphicsDevice == null) + return; + + manager.PreferredBackBufferWidth = _width; + manager.PreferredBackBufferHeight = _height; + manager.ApplyChanges(); + } + + protected override unsafe void SetTitle(string title) + { + MGP.Window_SetTitle(_handle, title); + } + + internal unsafe void Show(bool show) + { + MGP.Window_Show(_handle, show); } } diff --git a/MonoGame.Framework/Platform/Native/Graphics.Interop.cs b/MonoGame.Framework/Platform/Native/Graphics.Interop.cs new file mode 100644 index 00000000000..52ae55f2360 --- /dev/null +++ b/MonoGame.Framework/Platform/Native/Graphics.Interop.cs @@ -0,0 +1,429 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using System.Numerics; +using System.Runtime.InteropServices; + +namespace MonoGame.Interop; + +internal struct PtrTo +{ + public unsafe T* Ptr; +} + +[MGHandle] internal readonly struct MGG_GraphicsSystem { } +[MGHandle] internal readonly struct MGG_GraphicsAdapter { } +[MGHandle] internal readonly struct MGG_GraphicsDevice { } +[MGHandle] internal readonly struct MGG_BlendState { } +[MGHandle] internal readonly struct MGG_DepthStencilState { } +[MGHandle] internal readonly struct MGG_RasterizerState { } +[MGHandle] internal readonly struct MGG_Buffer { } +[MGHandle] internal readonly struct MGG_Texture { } +[MGHandle] internal readonly struct MGG_SamplerState { } +[MGHandle] internal readonly struct MGG_Shader { } +[MGHandle] internal readonly struct MGG_InputLayout { } +[MGHandle] internal readonly struct MGG_OcclusionQuery { } + + +[StructLayout(LayoutKind.Sequential)] +internal struct MGG_DisplayMode +{ + public SurfaceFormat format; + public int width; + public int height; +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MGG_GraphicsAdaptor_Info +{ + public nint DeviceName; + public nint Description; + public int DeviceId; + public int Revision; + public int VendorId; + public int SubSystemId; + public nint MonitorHandle; + + public unsafe MGG_DisplayMode* DisplayModes; + public int DisplayModeCount; + + public MGG_DisplayMode CurrentDisplayMode; +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MGG_GraphicsDevice_Caps +{ + public int MaxTextureSlots; + public int MaxVertexTextureSlots; + public int MaxVertexBufferSlots; + public int ShaderProfile; +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MGG_BlendState_Info +{ + public Blend colorSourceBlend; + public Blend colorDestBlend; + public BlendFunction colorBlendFunc; + public Blend alphaSourceBlend; + public Blend alphaDestBlend; + public BlendFunction alphaBlendFunc; + public ColorWriteChannels colorWriteChannels; +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MGG_DepthStencilState_Info +{ + public bool depthBufferEnable; + public bool depthBufferWriteEnable; + public CompareFunction depthBufferFunction; + public int referenceStencil; + public bool stencilEnable; + public int stencilMask; + public int stencilWriteMask; + public CompareFunction stencilFunction; + public StencilOperation stencilDepthBufferFail; + public StencilOperation stencilFail; + public StencilOperation stencilPass; +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MGG_RasterizerState_Info +{ + public FillMode fillMode; + public CullMode cullMode; + public bool scissorTestEnable; + public bool depthClipEnable; + public float depthBias; + public float slopeScaleDepthBias; + public bool multiSampleAntiAlias; +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MGG_SamplerState_Info +{ + public TextureAddressMode AddressU; + public TextureAddressMode AddressV; + public TextureAddressMode AddressW; + public uint BorderColor; + public TextureFilter Filter; + public TextureFilterMode FilterMode; + public int MaximumAnisotropy; + public int MaxMipLevel; + public float MipMapLevelOfDetailBias; + public CompareFunction ComparisonFunction; +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MGG_InputElement +{ + public uint VertexBufferSlot; + public VertexElementFormat Format; + public uint AlignedByteOffset; + public uint InstanceDataStepRate; +} + +internal enum TextureType +{ + _2D, + _3D, + Cube, +} + +internal enum BufferType +{ + Index, + Vertex, + Constant, +} + + +internal static unsafe partial class MGG +{ + #region Effect Resources + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_EffectResource_GetBytecode", StringMarshalling = StringMarshalling.Utf8)] + public static partial void EffectResource_GetBytecode(string name, out byte* bytecode, out int size); + + #endregion + + #region Graphics System + + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsSystem_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGG_GraphicsSystem* GraphicsSystem_Create(); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsSystem_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsSystem_Destroy(MGG_GraphicsSystem* system); + + #endregion + + #region Graphics Adapter + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsAdapter_Get", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGG_GraphicsAdapter* GraphicsAdapter_Get(MGG_GraphicsSystem* system, int index); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsAdapter_GetInfo", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsAdapter_GetInfo(MGG_GraphicsAdapter* adapter, out MGG_GraphicsAdaptor_Info info); + + #endregion + + #region Graphics Device + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGG_GraphicsDevice* GraphicsDevice_Create(MGG_GraphicsSystem* system, MGG_GraphicsAdapter* adapter); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_Destroy(MGG_GraphicsDevice* device); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_GetCaps", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_GetCaps(MGG_GraphicsDevice* device, out MGG_GraphicsDevice_Caps caps); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_ResizeSwapchain", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_ResizeSwapchain( + MGG_GraphicsDevice* device, + nint nativeWindowHandle, + int width, + int height, + SurfaceFormat color, + DepthFormat depth); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_BeginFrame", StringMarshalling = StringMarshalling.Utf8)] + public static partial int GraphicsDevice_BeginFrame(MGG_GraphicsDevice* device); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_Clear", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_Clear(MGG_GraphicsDevice* device, ClearOptions options, ref Microsoft.Xna.Framework.Vector4 color, float depth, int stencil); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_Present", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_Present(MGG_GraphicsDevice* device, int currentFrame, int syncInterval); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_SetBlendState", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_SetBlendState(MGG_GraphicsDevice* device, MGG_BlendState* state, float factorR, float factorG, float factorB, float factorA); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_SetDepthStencilState", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_SetDepthStencilState(MGG_GraphicsDevice* device, MGG_DepthStencilState* state); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_SetRasterizerState", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_SetRasterizerState(MGG_GraphicsDevice* device, MGG_RasterizerState* state); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_GetTitleSafeArea", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_GetTitleSafeArea( + ref int x, + ref int y, + ref int width, + ref int height); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_SetViewport", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_SetViewport( + MGG_GraphicsDevice* device, + int x, + int y, + int width, + int height, + float minDepth, + float maxDepth); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_SetScissorRectangle", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_SetScissorRectangle( + MGG_GraphicsDevice* device, + int x, + int y, + int width, + int height); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_SetRenderTargets", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_SetRenderTargets(MGG_GraphicsDevice* device, MGG_Texture** targets, int count); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_SetConstantBuffer", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_SetConstantBuffer(MGG_GraphicsDevice* device, ShaderStage stage, int slot, MGG_Buffer* buffer); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_SetTexture", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_SetTexture(MGG_GraphicsDevice* device, ShaderStage stage, int slot, MGG_Texture* texture); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_SetSamplerState", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_SetSamplerState(MGG_GraphicsDevice* device, ShaderStage stage, int slot, MGG_SamplerState* state); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_SetIndexBuffer", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_SetIndexBuffer(MGG_GraphicsDevice* device, IndexElementSize size, MGG_Buffer* buffer); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_SetVertexBuffer", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_SetVertexBuffer(MGG_GraphicsDevice* device, int slot, MGG_Buffer* buffer, int vertexOffset); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_SetShader", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_SetShader(MGG_GraphicsDevice* device, ShaderStage stage, MGG_Shader* shader); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_SetInputLayout", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_SetInputLayout(MGG_GraphicsDevice* device, MGG_InputLayout* layout); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_Draw", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_Draw(MGG_GraphicsDevice* device, PrimitiveType primitiveType, int vertexStart, int vertexCount); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_DrawIndexed", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_DrawIndexed(MGG_GraphicsDevice* device, PrimitiveType primitiveType, int primitiveCount, int indexStart, int vertexStart); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_GraphicsDevice_DrawIndexedInstanced", StringMarshalling = StringMarshalling.Utf8)] + public static partial void GraphicsDevice_DrawIndexedInstanced(MGG_GraphicsDevice* device, PrimitiveType primitiveType, int primitiveCount, int indexStart, int vertexStart, int instanceCount); + + #endregion + + #region State + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_BlendState_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGG_BlendState* BlendState_Create(MGG_GraphicsDevice* device, MGG_BlendState_Info* infos); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_BlendState_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void BlendState_Destroy(MGG_GraphicsDevice* device, MGG_BlendState* state); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_DepthStencilState_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGG_DepthStencilState* DepthStencilState_Create(MGG_GraphicsDevice* device, MGG_DepthStencilState_Info* info); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_DepthStencilState_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void DepthStencilState_Destroy(MGG_GraphicsDevice* device, MGG_DepthStencilState* state); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_RasterizerState_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGG_RasterizerState* RasterizerState_Create(MGG_GraphicsDevice* device, MGG_RasterizerState_Info* info); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_RasterizerState_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void RasterizerState_Destroy(MGG_GraphicsDevice* device, MGG_RasterizerState* state); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_SamplerState_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGG_SamplerState* SamplerState_Create(MGG_GraphicsDevice* device, MGG_SamplerState_Info* info); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_SamplerState_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void SamplerState_Destroy(MGG_GraphicsDevice* device, MGG_SamplerState* state); + + #endregion + + #region Buffer + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_Buffer_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGG_Buffer* Buffer_Create(MGG_GraphicsDevice* device, BufferType type, int sizeInBytes); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_Buffer_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Buffer_Destroy(MGG_GraphicsDevice* device, MGG_Buffer* buffer); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_Buffer_SetData", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Buffer_SetData( + MGG_GraphicsDevice* device, + ref MGG_Buffer* buffer, + int offset, + byte* data, + int length, + [MarshalAs(UnmanagedType.U1)] + bool discard); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_Buffer_GetData", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Buffer_GetData( + MGG_GraphicsDevice* device, + MGG_Buffer* buffer, + int offset, + byte* data, + int dataCount, + int dataBytes, + int dataStride); + + #endregion + + #region Texture + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_Texture_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGG_Texture* Texture_Create(MGG_GraphicsDevice* device, TextureType type, SurfaceFormat format, int width, int height, int depth, int mipmaps, int slices); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_RenderTarget_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGG_Texture* RenderTarget_Create( + MGG_GraphicsDevice* device, + TextureType type, + SurfaceFormat format, + int width, + int height, + int depth, + int mipmaps, + int slices, + DepthFormat depthFormat, + int multiSampleCount, + RenderTargetUsage usage); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_Texture_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Texture_Destroy(MGG_GraphicsDevice* device, MGG_Texture* texture); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_Texture_SetData", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Texture_SetData( + MGG_GraphicsDevice* device, + MGG_Texture* texture, + int level, + int slice, + int x, + int y, + int z, + int width, + int height, + int depth, + byte* data, + int dataBytes); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_Texture_GetData", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Texture_GetData( + MGG_GraphicsDevice* device, + MGG_Texture* texture, + int level, + int slice, + int x, + int y, + int z, + int width, + int height, + int depth, + byte* data, + int dataBytes); + + #endregion + + #region Input Layout + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_InputLayout_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGG_InputLayout* InputLayout_Create( + MGG_GraphicsDevice* device, + int[] strides, + int streamCount, + MGG_InputElement[] elements, + int elementCount + ); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_InputLayout_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void InputLayout_Destroy(MGG_GraphicsDevice* device, MGG_InputLayout* layout); + + #endregion + + #region Shader + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_Shader_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGG_Shader* Shader_Create(MGG_GraphicsDevice* device, ShaderStage stage, byte* bytecode, int sizeInBytes); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_Shader_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Shader_Destroy(MGG_GraphicsDevice* device, MGG_Shader* shader); + + #endregion + + #region Occlusion Query + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_OcclusionQuery_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGG_OcclusionQuery* OcclusionQuery_Create(MGG_GraphicsDevice* device); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_OcclusionQuery_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void OcclusionQuery_Destroy(MGG_GraphicsDevice* device, MGG_OcclusionQuery* query); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_OcclusionQuery_Begin", StringMarshalling = StringMarshalling.Utf8)] + public static partial void OcclusionQuery_Begin(MGG_GraphicsDevice* device, MGG_OcclusionQuery* query); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_OcclusionQuery_End", StringMarshalling = StringMarshalling.Utf8)] + public static partial void OcclusionQuery_End(MGG_GraphicsDevice* device, MGG_OcclusionQuery* query); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGG_OcclusionQuery_GetResult", StringMarshalling = StringMarshalling.Utf8)] + [return: MarshalAs(UnmanagedType.U1)] + public static partial bool OcclusionQuery_GetResult(MGG_GraphicsDevice* device, MGG_OcclusionQuery* query, out int pixelCount); + + #endregion +} diff --git a/MonoGame.Framework/Platform/Native/GraphicsAdapter.Native.cs b/MonoGame.Framework/Platform/Native/GraphicsAdapter.Native.cs index 406af5430df..953748904b0 100644 --- a/MonoGame.Framework/Platform/Native/GraphicsAdapter.Native.cs +++ b/MonoGame.Framework/Platform/Native/GraphicsAdapter.Native.cs @@ -2,19 +2,73 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; +using System; +using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Runtime.InteropServices; +using System.Threading; namespace Microsoft.Xna.Framework.Graphics; partial class GraphicsAdapter { - private static void PlatformInitializeAdapters(out ReadOnlyCollection adapters) + internal unsafe MGG_GraphicsAdapter* Handle; + + private static unsafe void PlatformInitializeAdapters(out ReadOnlyCollection adapters) { - adapters = new ReadOnlyCollection([]); + var found = new List(); + + while (true) + { + var handle = MGG.GraphicsAdapter_Get(NativeGamePlatform.GraphicsSystem, found.Count); + if (handle == null) + break; + + MGG_GraphicsAdaptor_Info info; + MGG.GraphicsAdapter_GetInfo(handle, out info); + + var adapter = new GraphicsAdapter(); + adapter.Handle = handle; + adapter.DeviceName = Marshal.PtrToStringUTF8(info.DeviceName); + adapter.Description = Marshal.PtrToStringUTF8(info.Description); + adapter.DeviceId = info.DeviceId; + adapter.Revision = info.Revision; + adapter.VendorId = info.VendorId; + adapter.SubSystemId = info.SubSystemId; + adapter.MonitorHandle = info.MonitorHandle; + + // Assume the first adapter is the default for now. + adapter.IsDefaultAdapter = found.Count == 0; + + adapter._currentDisplayMode = new DisplayMode( + info.CurrentDisplayMode.width, + info.CurrentDisplayMode.height, + info.CurrentDisplayMode.format); + + var modes = new List(); + + for (int i=0; i < info.DisplayModeCount; i++) + { + var mode = new DisplayMode( + info.DisplayModes[i].width, + info.DisplayModes[i].height, + info.DisplayModes[i].format); + + modes.Add(mode); + } + + adapter._supportedDisplayModes = new DisplayModeCollection(modes); + + found.Add(adapter); + } + + adapters = new ReadOnlyCollection(found); } private bool PlatformIsProfileSupported(GraphicsProfile graphicsProfile) { - return false; + // This isn't needed in 2024! + return true; } } diff --git a/MonoGame.Framework/Platform/Native/GraphicsCapabilities.Native.cs b/MonoGame.Framework/Platform/Native/GraphicsCapabilities.Native.cs index 30843102a30..9766be04cf2 100644 --- a/MonoGame.Framework/Platform/Native/GraphicsCapabilities.Native.cs +++ b/MonoGame.Framework/Platform/Native/GraphicsCapabilities.Native.cs @@ -8,7 +8,34 @@ internal partial class GraphicsCapabilities { private void PlatformInitialize(GraphicsDevice device) { + SupportsNonPowerOfTwo = device.GraphicsProfile == GraphicsProfile.HiDef; + SupportsTextureFilterAnisotropic = true; + SupportsDepth24 = true; + SupportsPackedDepthStencil = true; + SupportsDepthNonLinear = false; + SupportsTextureMaxLevel = true; + + // Texture compression + SupportsDxt1 = true; + SupportsS3tc = true; + + SupportsSRgb = true; + + SupportsTextureArrays = device.GraphicsProfile == GraphicsProfile.HiDef; + SupportsDepthClamp = device.GraphicsProfile == GraphicsProfile.HiDef; + SupportsVertexTextures = device.GraphicsProfile == GraphicsProfile.HiDef; + SupportsFloatTextures = true; + SupportsHalfFloatTextures = true; + SupportsNormalized = true; + + SupportsInstancing = true; + SupportsBaseIndexInstancing = true; + SupportsSeparateBlendStates = true; + + MaxTextureAnisotropy = (device.GraphicsProfile == GraphicsProfile.Reach) ? 2 : 16; + + _maxMultiSampleCount = 4;// GetMaxMultiSampleCount(device); } } diff --git a/MonoGame.Framework/Platform/Native/GraphicsDebug.Native.cs b/MonoGame.Framework/Platform/Native/GraphicsDebug.Native.cs index 24f3116a1ed..3f351bc1a35 100644 --- a/MonoGame.Framework/Platform/Native/GraphicsDebug.Native.cs +++ b/MonoGame.Framework/Platform/Native/GraphicsDebug.Native.cs @@ -4,6 +4,9 @@ namespace Microsoft.Xna.Framework.Graphics; +// TODO: We should review the API and decide how useful +// it is considering Vulkan, DirectX12, and consoles. + public partial class GraphicsDebug { private bool PlatformTryDequeueMessage(out GraphicsDebugMessage message) diff --git a/MonoGame.Framework/Platform/Native/GraphicsDevice.Native.cs b/MonoGame.Framework/Platform/Native/GraphicsDevice.Native.cs index 83fd2716981..5a36618c862 100644 --- a/MonoGame.Framework/Platform/Native/GraphicsDevice.Native.cs +++ b/MonoGame.Framework/Platform/Native/GraphicsDevice.Native.cs @@ -3,43 +3,168 @@ // file 'LICENSE.txt', which is part of this source code package. using System; +using System.Collections.Generic; +using MonoGame.Interop; +using MonoGame.Framework.Utilities; + namespace Microsoft.Xna.Framework.Graphics; + public partial class GraphicsDevice { - private void PlatformSetup() + internal unsafe MGG_GraphicsDevice* Handle; + + internal Texture2D DefaultTexture; + + private int _currentFrame = -1; + + private readonly Dictionary _userVertexBuffers = new Dictionary(); + private DynamicIndexBuffer _userIndexBuffer16; + private DynamicIndexBuffer _userIndexBuffer32; + + private unsafe readonly MGG_Texture*[] _curRenderTargets = new MGG_Texture*[4]; + + internal static int ShaderProfile + { + get; private set; + } + + private unsafe void PlatformSetup() { + // Creates the device, but no swap chain yet. + Handle = MGG.GraphicsDevice_Create(NativeGamePlatform.GraphicsSystem, Adapter.Handle); + + // Get the device caps. + MGG_GraphicsDevice_Caps caps; + MGG.GraphicsDevice_GetCaps(Handle, out caps); + MaxTextureSlots = caps.MaxTextureSlots; + MaxVertexTextureSlots = caps.MaxVertexTextureSlots; + _maxVertexBufferSlots = caps.MaxVertexBufferSlots; + ShaderProfile = caps.ShaderProfile; + UseHalfPixelOffset = false; } - private void PlatformInitialize() + private unsafe void PlatformInitialize() { + MGG.GraphicsDevice_ResizeSwapchain( + Handle, + PresentationParameters.DeviceWindowHandle, + PresentationParameters.BackBufferWidth, + PresentationParameters.BackBufferHeight, + PresentationParameters.BackBufferFormat, + PresentationParameters.DepthStencilFormat); + + // Setup the default texture. + DefaultTexture = new Texture2D(this, 2, 2); + DefaultTexture.SetData(new[] { Color.Black, Color.Black, Color.Black, Color.Black }); } - private void OnPresentationChanged() + private unsafe void OnPresentationChanged() { + // Finish any frame that is currently rendering. + if (_currentFrame > -1) + { + var syncInterval = PresentationParameters.PresentationInterval.GetSyncInterval(); + MGG.GraphicsDevice_Present(Handle, _currentFrame, syncInterval); + } + + // Now resize the back buffer. + MGG.GraphicsDevice_ResizeSwapchain( + Handle, + PresentationParameters.DeviceWindowHandle, + PresentationParameters.BackBufferWidth, + PresentationParameters.BackBufferHeight, + PresentationParameters.BackBufferFormat, + PresentationParameters.DepthStencilFormat); + + _viewport = new Viewport( + 0, + 0, + PresentationParameters.BackBufferWidth, + PresentationParameters.BackBufferHeight, + _viewport.MinDepth, + _viewport.MaxDepth); + + // Begin a new frame it if was previously rendering. + if (_currentFrame > -1) + { + _currentFrame = -1; + BeginFrame(); + } } - private void PlatformClear(ClearOptions options, Vector4 color, float depth, int stencil) + private unsafe void BeginFrame() { + if (_currentFrame > -1) + return; + + // Start the command buffer now. + _currentFrame = MGG.GraphicsDevice_BeginFrame(Handle); + // We must reapply all the state on a new command buffer. + _scissorRectangleDirty = true; + _blendFactorDirty = true; + _blendStateDirty = true; + _pixelShaderDirty = true; + _vertexShaderDirty = true; + _depthStencilStateDirty = true; + _indexBufferDirty = true; + _rasterizerStateDirty = true; + _vertexBuffersDirty = true; + Textures.Dirty(); + SamplerStates.Dirty(); + + PlatformApplyDefaultRenderTarget(); } - private void PlatformDispose() + private unsafe void PlatformClear(ClearOptions options, Vector4 color, float depth, int stencil) { + BeginFrame(); + + PlatformBeginApplyState(); + MGG.GraphicsDevice_Clear(Handle, options, ref color, depth, stencil); } - private void PlatformPresent() + private unsafe void PlatformDispose() { + if (Handle != null) + { + MGG.GraphicsDevice_Destroy(Handle); + Handle = null; + } } - private void PlatformSetViewport(ref Viewport value) + private unsafe void PlatformPresent() { + if (_currentFrame < 0) + return; + + var syncInterval = PresentationParameters.PresentationInterval.GetSyncInterval(); + MGG.GraphicsDevice_Present(Handle, _currentFrame, syncInterval); + _currentFrame = -1; } - private void PlatformApplyDefaultRenderTarget() + private unsafe void PlatformSetViewport(ref Viewport viewport) { + BeginFrame(); + + MGG.GraphicsDevice_SetViewport( + Handle, + viewport.X, + viewport.Y, + viewport.Width, + viewport.Height, + viewport.MinDepth, + viewport.MaxDepth); + } + + private unsafe void PlatformApplyDefaultRenderTarget() + { + BeginFrame(); + + MGG.GraphicsDevice_SetRenderTargets(Handle, null, 0); } private void PlatformResolveRenderTargets() @@ -47,45 +172,255 @@ private void PlatformResolveRenderTargets() // Resolving MSAA render targets should be done here. } - private IRenderTarget PlatformApplyRenderTargets() + private unsafe IRenderTarget PlatformApplyRenderTargets() { - return null; + BeginFrame(); + + Array.Clear(_curRenderTargets, 0, 4); + + RenderTarget2D first = null; + + for (var i = 0; i < _currentRenderTargetCount; i++) + { + var binding = _currentRenderTargetBindings[i]; + var target = binding.RenderTarget as RenderTarget2D; + _curRenderTargets[i] = target.Handle; + if (i == 0) + first = target; + } + + fixed (MGG_Texture** targets = _curRenderTargets) + MGG.GraphicsDevice_SetRenderTargets(Handle, targets, _currentRenderTargetCount); + + return first; } private void PlatformBeginApplyState() { + BeginFrame(); } private void PlatformApplyBlend() { + if (_blendStateDirty) + { + _actualBlendState.PlatformApplyState(this); + _blendStateDirty = false; + } + + if (_blendFactorDirty) + { + // TODO? + _blendFactorDirty = false; + } + } + + private unsafe void PlatformApplyState(bool applyShaders) + { + if (_scissorRectangleDirty) + { + MGG.GraphicsDevice_SetScissorRectangle( + Handle, + _scissorRectangle.X, + _scissorRectangle.Y, + _scissorRectangle.Width, + _scissorRectangle.Height); + + _scissorRectangleDirty = false; + } + + // If we're not applying shaders then early out now. + if (!applyShaders) + return; + + if (_vertexShader == null) + throw new InvalidOperationException("A vertex shader must be set!"); + if (_pixelShader == null) + throw new InvalidOperationException("A pixel shader must be set!"); + + if (_indexBufferDirty) + { + if (_indexBuffer != null) + MGG.GraphicsDevice_SetIndexBuffer(Handle, _indexBuffer.IndexElementSize, _indexBuffer.Handle); + _indexBufferDirty = false; + } + + if (_vertexBuffersDirty && _vertexBuffers.Count > 0) + { + var numBuffers = _vertexBuffers.Count; + for (var slot = 0; slot < numBuffers; slot++) + { + var vertexBufferBinding = _vertexBuffers.Get(slot); + var buffer = vertexBufferBinding.VertexBuffer; + + MGG.GraphicsDevice_SetVertexBuffer(Handle, slot, buffer.Handle, vertexBufferBinding.VertexOffset); + } + } + + if (_vertexShaderDirty) + { + MGG.GraphicsDevice_SetShader(Handle, ShaderStage.Vertex, _vertexShader.Handle); + unchecked { _graphicsMetrics._vertexShaderCount++; } + } + + if (_vertexShaderDirty || _vertexBuffersDirty) + { + var layout = _vertexShader.GetOrCreateLayout(_vertexBuffers); + MGG.GraphicsDevice_SetInputLayout(Handle, layout); + _vertexShaderDirty = _vertexBuffersDirty = false; + } + + if (_pixelShaderDirty) + { + MGG.GraphicsDevice_SetShader(Handle, ShaderStage.Pixel, _pixelShader.Handle); + _pixelShaderDirty = false; + unchecked { _graphicsMetrics._pixelShaderCount++; } + } + + _vertexConstantBuffers.SetConstantBuffers(this); + _pixelConstantBuffers.SetConstantBuffers(this); + + VertexTextures.SetTextures(this); + VertexSamplerStates.PlatformSetSamplers(this); + + Textures.SetTextures(this); + SamplerStates.PlatformSetSamplers(this); + } + + private int SetUserVertexBuffer(T[] vertexData, int vertexOffset, int vertexCount, VertexDeclaration vertexDecl) + where T : struct + { + DynamicVertexBuffer buffer; + + if (!_userVertexBuffers.TryGetValue(vertexDecl.GetHashCode(), out buffer) || buffer.VertexCount < vertexCount) + { + // Dispose the previous buffer if we have one. + if (buffer != null) + buffer.Dispose(); + + buffer = new DynamicVertexBuffer(this, vertexDecl, Math.Max(vertexCount, 2000), BufferUsage.WriteOnly); + _userVertexBuffers[vertexDecl.GetHashCode()] = buffer; + } + + var startVertex = buffer.UserOffset; + + if ((vertexCount + buffer.UserOffset) < buffer.VertexCount) + { + buffer.UserOffset += vertexCount; + buffer.SetData(startVertex * vertexDecl.VertexStride, vertexData, vertexOffset, vertexCount, vertexDecl.VertexStride, SetDataOptions.NoOverwrite); + } + else + { + buffer.UserOffset = vertexCount; + buffer.SetData(vertexData, vertexOffset, vertexCount, SetDataOptions.Discard); + startVertex = 0; + } + + SetVertexBuffer(buffer); + + return startVertex; } - private void PlatformApplyState(bool applyShaders) + private int SetUserIndexBuffer(T[] indexData, int indexOffset, int indexCount) + where T : struct { + DynamicIndexBuffer buffer; + + var indexSize = ReflectionHelpers.FastSizeOf(); + var indexElementSize = indexSize == 2 ? IndexElementSize.SixteenBits : IndexElementSize.ThirtyTwoBits; + + var requiredIndexCount = Math.Max(indexCount, 6000); + if (indexElementSize == IndexElementSize.SixteenBits) + { + if (_userIndexBuffer16 == null || _userIndexBuffer16.IndexCount < requiredIndexCount) + { + if (_userIndexBuffer16 != null) + _userIndexBuffer16.Dispose(); + + _userIndexBuffer16 = new DynamicIndexBuffer(this, indexElementSize, requiredIndexCount, BufferUsage.WriteOnly); + } + + buffer = _userIndexBuffer16; + } + else + { + if (_userIndexBuffer32 == null || _userIndexBuffer32.IndexCount < requiredIndexCount) + { + if (_userIndexBuffer32 != null) + _userIndexBuffer32.Dispose(); + + _userIndexBuffer32 = new DynamicIndexBuffer(this, indexElementSize, requiredIndexCount, BufferUsage.WriteOnly); + } + + buffer = _userIndexBuffer32; + } + + var startIndex = buffer.UserOffset; + + if ((indexCount + buffer.UserOffset) < buffer.IndexCount) + { + buffer.UserOffset += indexCount; + buffer.SetData(startIndex * indexSize, indexData, indexOffset, indexCount, SetDataOptions.NoOverwrite); + } + else + { + startIndex = 0; + buffer.UserOffset = indexCount; + buffer.SetData(indexData, indexOffset, indexCount, SetDataOptions.Discard); + } + + Indices = buffer; + + return startIndex; } - private void PlatformDrawIndexedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount) + private unsafe void PlatformDrawIndexedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount) { + ApplyState(true); + + MGG.GraphicsDevice_DrawIndexed(Handle, primitiveType, primitiveCount, startIndex, baseVertex); } - private void PlatformDrawUserPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, VertexDeclaration vertexDeclaration, int vertexCount) where T : struct + private unsafe void PlatformDrawUserPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, VertexDeclaration vertexDeclaration, int vertexCount) where T : struct { + var startVertex = SetUserVertexBuffer(vertexData, vertexOffset, vertexCount, vertexDeclaration); + ApplyState(true); + + MGG.GraphicsDevice_Draw(Handle, primitiveType, startVertex, vertexCount); } - private void PlatformDrawPrimitives(PrimitiveType primitiveType, int vertexStart, int vertexCount) + private unsafe void PlatformDrawPrimitives(PrimitiveType primitiveType, int vertexStart, int vertexCount) { + ApplyState(true); + + MGG.GraphicsDevice_Draw(Handle, primitiveType, vertexStart, vertexCount); } - private void PlatformDrawUserIndexedPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, short[] indexData, int indexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct + private unsafe void PlatformDrawUserIndexedPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, short[] indexData, int indexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct { + var indexCount = GetElementCountArray(primitiveType, primitiveCount); + var startVertex = SetUserVertexBuffer(vertexData, vertexOffset, numVertices, vertexDeclaration); + var startIndex = SetUserIndexBuffer(indexData, indexOffset, indexCount); + ApplyState(true); + + MGG.GraphicsDevice_DrawIndexed(Handle, primitiveType, primitiveCount, startIndex, startVertex); } - private void PlatformDrawUserIndexedPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, int[] indexData, int indexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct + private unsafe void PlatformDrawUserIndexedPrimitives(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, int[] indexData, int indexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct { + var indexCount = GetElementCountArray(primitiveType, primitiveCount); + var startVertex = SetUserVertexBuffer(vertexData, vertexOffset, numVertices, vertexDeclaration); + var startIndex = SetUserIndexBuffer(indexData, indexOffset, indexCount); + ApplyState(true); + + MGG.GraphicsDevice_DrawIndexed(Handle, primitiveType, primitiveCount, startIndex, startVertex); } - private void PlatformDrawInstancedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount, int baseInstance, int instanceCount) + private unsafe void PlatformDrawInstancedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount, int baseInstance, int instanceCount) { + ApplyState(true); + + MGG.GraphicsDevice_DrawIndexedInstanced(Handle, primitiveType, primitiveCount, startIndex, baseVertex, instanceCount); } private void PlatformGetBackBufferData(Rectangle? rect, T[] data, int startIndex, int count) where T : struct @@ -95,6 +430,8 @@ private void PlatformGetBackBufferData(Rectangle? rect, T[] data, int startIn private static Rectangle PlatformGetTitleSafeArea(int x, int y, int width, int height) { + MGG.GraphicsDevice_GetTitleSafeArea(ref x, ref y, ref width, ref height); + return new Rectangle(x, y, width, height); } } diff --git a/MonoGame.Framework/Platform/Native/Image.Interop.cs b/MonoGame.Framework/Platform/Native/Image.Interop.cs new file mode 100644 index 00000000000..0f1e2cacd2e --- /dev/null +++ b/MonoGame.Framework/Platform/Native/Image.Interop.cs @@ -0,0 +1,45 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using System.Runtime.InteropServices; + + +namespace MonoGame.Interop; + + +/// +/// MonoGame native calls for high performance reading and writing of images. +/// +internal static unsafe partial class MGI +{ + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGI_ReadRGBA", StringMarshalling = StringMarshalling.Utf8)] + public static partial void ReadRGBA( + byte* data, + int dataBytes, + [MarshalAs(UnmanagedType.U1)] bool zeroTransparentPixels, + out int width, + out int height, + out byte* rgba); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGI_WriteJpg", StringMarshalling = StringMarshalling.Utf8)] + public static partial void WriteJpg( + byte* data, + int dataBytes, + int width, + int height, + int quality, + out byte* jpg, + out int jpgBytes); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGI_WritePng", StringMarshalling = StringMarshalling.Utf8)] + public static partial void WritePng( + byte* data, + int dataBytes, + int width, + int height, + out byte* png, + out int pngBytes); +} + + diff --git a/MonoGame.Framework/Platform/Native/IndexBuffer.Native.cs b/MonoGame.Framework/Platform/Native/IndexBuffer.Native.cs index f530cf38eb6..825e2a724c4 100644 --- a/MonoGame.Framework/Platform/Native/IndexBuffer.Native.cs +++ b/MonoGame.Framework/Platform/Native/IndexBuffer.Native.cs @@ -2,27 +2,71 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using System; +using System.Runtime.InteropServices; +using MonoGame.Interop; +using MonoGame.Framework.Utilities; + + namespace Microsoft.Xna.Framework.Graphics; public partial class IndexBuffer { - private void PlatformConstruct(IndexElementSize indexElementSize, int indexCount) + internal unsafe MGG_Buffer* Handle; + + private unsafe void PlatformConstruct(IndexElementSize indexElementSize, int indexCount) { + var indexBytes = indexElementSize == IndexElementSize.SixteenBits ? 2 : 4; + Handle = MGG.Buffer_Create(GraphicsDevice.Handle, BufferType.Index, indexCount * indexBytes); } - private void PlatformGraphicsDeviceResetting() + private unsafe void PlatformGraphicsDeviceResetting() { + if (Handle != null) + { + MGG.Buffer_Destroy(GraphicsDevice.Handle, Handle); + Handle = null; + } + } + private unsafe void PlatformGetData(int offsetInBytes, T[] data, int startIndex, int elementCount) where T : struct + { + var elementSizeInBytes = ReflectionHelpers.FastSizeOf(); + var startBytes = startIndex * elementSizeInBytes; + var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); + var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); + var dataStride = IndexElementSize == IndexElementSize.SixteenBits ? 2 : 4; + + MGG.Buffer_GetData(GraphicsDevice.Handle, Handle, offsetInBytes, (byte*)dataPtr, elementCount, elementSizeInBytes, dataStride); + + dataHandle.Free(); } - private void PlatformGetData(int offsetInBytes, T[] data, int startIndex, int elementCount) where T : struct + private unsafe void PlatformSetData(int offsetInBytes, T[] data, int startIndex, int elementCount, SetDataOptions options) where T : struct { + var elementSizeInBytes = ReflectionHelpers.FastSizeOf(); + var startBytes = startIndex * elementSizeInBytes; + var dataBytes = elementCount * elementSizeInBytes; + var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); + var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); + + // TODO: We need to figure out the correct behavior + // for SetDataOptions.None on a dynamic buffer. + // + // For now we always discard as it is a pretty safe default. + // + var discard = _isDynamic && options != SetDataOptions.NoOverwrite; + + MGG.Buffer_SetData(GraphicsDevice.Handle, ref Handle, offsetInBytes, (byte*)dataPtr, dataBytes, discard); + dataHandle.Free(); } - private void PlatformSetData(int offsetInBytes, T[] data, int startIndex, int elementCount, SetDataOptions options) where T : struct + protected override void Dispose(bool disposing) { + PlatformGraphicsDeviceResetting(); + base.Dispose(disposing); } } diff --git a/MonoGame.Framework/Platform/Native/Keyboard.Native.cs b/MonoGame.Framework/Platform/Native/Keyboard.Native.cs index 57a0a4a12a2..a9e802b553a 100644 --- a/MonoGame.Framework/Platform/Native/Keyboard.Native.cs +++ b/MonoGame.Framework/Platform/Native/Keyboard.Native.cs @@ -2,12 +2,28 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; +using System; +using System.Collections.Generic; +using System.Numerics; + namespace Microsoft.Xna.Framework.Input; public static partial class Keyboard { - private static KeyboardState PlatformGetState() + // NOTE: Most keyboards can register 6 pressed keys at once + // and some gaming keyboards can do up to 10 or 25 keys. + // + // For this reason a List<> is best here as in most of the time + // it will perform faster than a HashSet or other collections. + // + internal static readonly List Keys = new List(32); + + private static unsafe KeyboardState PlatformGetState() { - return new KeyboardState(); + bool capsLock = Keys.Contains(Input.Keys.CapsLock); + bool numLock = Keys.Contains(Input.Keys.NumLock); + + return new KeyboardState(Keys, capsLock, numLock); } } diff --git a/MonoGame.Framework/Platform/Native/Media.Interop.cs b/MonoGame.Framework/Platform/Native/Media.Interop.cs new file mode 100644 index 00000000000..bda979ff72d --- /dev/null +++ b/MonoGame.Framework/Platform/Native/Media.Interop.cs @@ -0,0 +1,96 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using System; +using System.Runtime.InteropServices; +using Microsoft.Xna.Framework.Media; + +namespace MonoGame.Interop; + + +[MGHandle] +internal readonly struct MGM_Song { } + +[MGHandle] +internal readonly struct MGM_Video { } + + +internal static unsafe partial class MGM +{ + #region Song + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void NativeFinishedCallback(nint callbackData); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Song_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGM_Song* Song_Create(string mediaFilePath); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Song_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Song_Destroy(MGM_Song* song); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Song_GetDuration", StringMarshalling = StringMarshalling.Utf8)] + public static partial ulong Song_GetDuration(MGM_Song* song); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Song_GetPosition", StringMarshalling = StringMarshalling.Utf8)] + public static partial ulong Song_GetPosition(MGM_Song* song); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Song_GetVolume", StringMarshalling = StringMarshalling.Utf8)] + public static partial float Song_GetVolume(MGM_Song* song); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Song_SetVolume", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Song_SetVolume(MGM_Song* song, float volume); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Song_Play", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Song_Play(MGM_Song* song, ulong startPositionMs, [MarshalAs(UnmanagedType.FunctionPtr)] NativeFinishedCallback callback, nint callbackData); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Song_Pause", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Song_Pause(MGM_Song* song); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Song_Resume", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Song_Resume(MGM_Song* song); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Song_Stop", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Song_Stop(MGM_Song* song); + + #endregion + + + #region Video + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Video_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGM_Video* Video_Create(string mediaFilePath, int cachedFrameNum, out int width, out int height, out float fps, out ulong duration); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Video_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Video_Destroy(MGM_Video* video); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Video_GetState", StringMarshalling = StringMarshalling.Utf8)] + public static partial MediaState Video_GetState(MGM_Video* video); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Video_GetPosition", StringMarshalling = StringMarshalling.Utf8)] + public static partial ulong Video_GetPosition(MGM_Video* video); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Video_SetVolume", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Video_SetVolume(MGM_Video* video, float volume); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Video_SetLooped", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Video_SetLooped(MGM_Video* video, [MarshalAs(UnmanagedType.U1)] bool looped); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Video_Play", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Video_Play(MGM_Video* video); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Video_Pause", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Video_Pause(MGM_Video* video); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Video_Resume", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Video_Resume(MGM_Video* video); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Video_Stop", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Video_Stop(MGM_Video* video); + + [LibraryImport(MGP.MonoGameNativeDLL, EntryPoint = "MGM_Video_GetFrame", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Video_GetFrame(MGM_Video* video, out uint frame, out MGG_Texture* handle); + + + #endregion +} diff --git a/MonoGame.Framework/Platform/Native/MediaPlayer.Native.cs b/MonoGame.Framework/Platform/Native/MediaPlayer.Native.cs index caf2d63d8b2..d06460a5e0c 100644 --- a/MonoGame.Framework/Platform/Native/MediaPlayer.Native.cs +++ b/MonoGame.Framework/Platform/Native/MediaPlayer.Native.cs @@ -10,57 +10,70 @@ public static partial class MediaPlayer { private static void PlatformInitialize() { - } private static bool PlatformGetIsMuted() { - return false; + return _isMuted; } private static void PlatformSetIsMuted(bool muted) { + _isMuted = muted; + + if (_queue.Count == 0) + return; + var newVolume = _isMuted ? 0.0f : _volume; + _queue.SetVolume(newVolume); } private static bool PlatformGetIsRepeating() { - return false; + return _isRepeating; } private static void PlatformSetIsRepeating(bool repeating) { - + _isRepeating = repeating; } private static bool PlatformGetIsShuffled() { - return false; + return _isShuffled; } private static void PlatformSetIsShuffled(bool shuffled) { - + _isShuffled = shuffled; } private static TimeSpan PlatformGetPlayPosition() { - return TimeSpan.Zero; + if (_queue.ActiveSong == null) + return TimeSpan.Zero; + + return _queue.ActiveSong.Position; } private static MediaState PlatformGetState() { - return MediaState.Stopped; + return _state; } private static float PlatformGetVolume() { - return 0.0f; + return _volume; } private static void PlatformSetVolume(float volume) { + _volume = volume; + if (_queue.ActiveSong == null) + return; + + _queue.SetVolume(_isMuted ? 0.0f : _volume); } private static bool PlatformGetGameHasControl() @@ -70,21 +83,33 @@ private static bool PlatformGetGameHasControl() private static void PlatformPause() { + if (_queue.ActiveSong == null) + return; + _queue.ActiveSong.Pause(); } private static void PlatformPlaySong(Song song, TimeSpan? startPosition) { + if (_queue.ActiveSong == null) + return; + song.Volume = _isMuted ? 0.0f : _volume; + song.Play(startPosition, OnSongFinishedPlaying); } private static void PlatformResume() { + if (_queue.ActiveSong == null) + return; + _queue.ActiveSong.Resume(); } private static void PlatformStop() { - + // TOOD: What is this loop doing? + foreach (var song in Queue.Songs) + _queue.ActiveSong.Stop(); } } diff --git a/MonoGame.Framework/Platform/Native/MessageBox.Native.cs b/MonoGame.Framework/Platform/Native/MessageBox.Native.cs index b47160ebdcc..5f7e3f2e9d3 100644 --- a/MonoGame.Framework/Platform/Native/MessageBox.Native.cs +++ b/MonoGame.Framework/Platform/Native/MessageBox.Native.cs @@ -2,20 +2,25 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; using System.Collections.Generic; +using System.ComponentModel; using System.Threading.Tasks; namespace Microsoft.Xna.Framework.Input; public static partial class MessageBox { - private static Task PlatformShow(string title, string description, List buttons) + internal static unsafe MGP_Window* _window; + + private static unsafe Task PlatformShow(string title, string description, List buttons) { - return Task.FromResult(0); + var result = MGP.Window_ShowMessageBox(_window, title, description, buttons.ToArray(), buttons.Count); + return Task.FromResult(result); } private static void PlatformCancel(int? result) { - + // TODO: How should we do this? } } diff --git a/MonoGame.Framework/Platform/Native/Mouse.Native.cs b/MonoGame.Framework/Platform/Native/Mouse.Native.cs index ce4c60d82ef..ba2a1b260ae 100644 --- a/MonoGame.Framework/Platform/Native/Mouse.Native.cs +++ b/MonoGame.Framework/Platform/Native/Mouse.Native.cs @@ -2,6 +2,7 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; using System; namespace Microsoft.Xna.Framework.Input; @@ -10,27 +11,39 @@ public static partial class Mouse { private static IntPtr PlatformGetWindowHandle() { - return IntPtr.Zero; + // TODO: Multiple window support. + + return PrimaryWindow.Handle; } private static void PlatformSetWindowHandle(IntPtr windowHandle) { - + // TODO: Multiple window support. } - private static MouseState PlatformGetState(GameWindow window) + private static unsafe MouseState PlatformGetState(GameWindow window) { + // Mouse events keep this updated for each window. return window.MouseState; } - private static void PlatformSetPosition(int x, int y) + private static unsafe void PlatformSetPosition(int x, int y) { + // TODO: Multiple window support. + + PrimaryWindow.MouseState.X = x; + PrimaryWindow.MouseState.Y = y; + + var window = PrimaryWindow as NativeGameWindow; + MGP.Mouse_WarpPosition(window._handle, x, y); } - /// - public static void PlatformSetCursor(MouseCursor cursor) + private static unsafe void PlatformSetCursor(MouseCursor cursor) { + // TODO: Multiple window support? + var window = PrimaryWindow as NativeGameWindow; + MGP.Window_SetCursor(window._handle, (MGP_Cursor*)cursor.Handle); } } diff --git a/MonoGame.Framework/Platform/Native/MouseCursor.Native.cs b/MonoGame.Framework/Platform/Native/MouseCursor.Native.cs new file mode 100644 index 00000000000..9c99d633e94 --- /dev/null +++ b/MonoGame.Framework/Platform/Native/MouseCursor.Native.cs @@ -0,0 +1,52 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using System; +using Microsoft.Xna.Framework.Graphics; +using MonoGame.Interop; + +namespace Microsoft.Xna.Framework.Input; + +public partial class MouseCursor +{ + private unsafe MouseCursor(SystemCursor cursor) + { + Handle = (nint)MGP.Cursor_Create(cursor); + } + + private static void PlatformInitalize() + { + Arrow = new MouseCursor(SystemCursor.Arrow); + IBeam = new MouseCursor(SystemCursor.IBeam); + Wait = new MouseCursor(SystemCursor.Wait); + Crosshair = new MouseCursor(SystemCursor.Crosshair); + WaitArrow = new MouseCursor(SystemCursor.WaitArrow); + SizeNWSE = new MouseCursor(SystemCursor.SizeNWSE); + SizeNESW = new MouseCursor(SystemCursor.SizeNESW); + SizeWE = new MouseCursor(SystemCursor.SizeWE); + SizeNS = new MouseCursor(SystemCursor.SizeNS); + SizeAll = new MouseCursor(SystemCursor.SizeAll); + No = new MouseCursor(SystemCursor.No); + Hand = new MouseCursor(SystemCursor.Hand); + } + + private unsafe static MouseCursor PlatformFromTexture2D(Texture2D texture, int originx, int originy) + { + var bytes = new byte[texture.Width * texture.Height * 4]; + texture.GetData(bytes); + + var handle = MGP.Cursor_CreateCustom(bytes, texture.Width, texture.Height, originx, originy); + + return new MouseCursor((nint)handle); + } + + private unsafe void PlatformDispose() + { + if (Handle == IntPtr.Zero) + return; + + MGP.Cursor_Destroy((MGP_Cursor*)Handle); + Handle = IntPtr.Zero; + } +} diff --git a/MonoGame.Framework/Platform/Native/MouseCursor.Nativve.cs b/MonoGame.Framework/Platform/Native/MouseCursor.Nativve.cs deleted file mode 100644 index 15e01e57a8f..00000000000 --- a/MonoGame.Framework/Platform/Native/MouseCursor.Nativve.cs +++ /dev/null @@ -1,26 +0,0 @@ -// MonoGame - Copyright (C) The MonoGame Team -// This file is subject to the terms and conditions defined in -// file 'LICENSE.txt', which is part of this source code package. - -using System; -using Microsoft.Xna.Framework.Graphics; - -namespace Microsoft.Xna.Framework.Input; - -public partial class MouseCursor -{ - private static void PlatformInitalize() - { - - } - - private static MouseCursor PlatformFromTexture2D(Texture2D texture, int originx, int originy) - { - return new MouseCursor(IntPtr.Zero); - } - - private void PlatformDispose() - { - - } -} diff --git a/MonoGame.Framework/Platform/Native/OcclusionQuery.Native.cs b/MonoGame.Framework/Platform/Native/OcclusionQuery.Native.cs index f57a07f84fe..4959fc969e4 100644 --- a/MonoGame.Framework/Platform/Native/OcclusionQuery.Native.cs +++ b/MonoGame.Framework/Platform/Native/OcclusionQuery.Native.cs @@ -2,25 +2,45 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; + namespace Microsoft.Xna.Framework.Graphics; partial class OcclusionQuery { - private void PlatformConstruct() + internal unsafe MGG_OcclusionQuery* Handle; + + private unsafe void PlatformConstruct() + { + Handle = MGG.OcclusionQuery_Create(GraphicsDevice.Handle); + } + + private unsafe void PlatformBegin() { + MGG.OcclusionQuery_Begin(GraphicsDevice.Handle, Handle); } - private void PlatformBegin() + private unsafe void PlatformEnd() { + MGG.OcclusionQuery_End(GraphicsDevice.Handle, Handle); } - private void PlatformEnd() + private unsafe bool PlatformGetResult(out int pixelCount) { + return MGG.OcclusionQuery_GetResult(GraphicsDevice.Handle, Handle, out pixelCount); } - private bool PlatformGetResult(out int pixelCount) + protected unsafe override void Dispose(bool disposing) { - pixelCount = 0; - return false; + if (!IsDisposed) + { + if (disposing) + { + MGG.OcclusionQuery_Destroy(GraphicsDevice.Handle, Handle); + Handle = null; + } + } + + base.Dispose(disposing); } } diff --git a/MonoGame.Framework/Platform/Native/Platform.Interop.cs b/MonoGame.Framework/Platform/Native/Platform.Interop.cs new file mode 100644 index 00000000000..919d0f3e52b --- /dev/null +++ b/MonoGame.Framework/Platform/Native/Platform.Interop.cs @@ -0,0 +1,342 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Input; +using MonoGame.Framework.Utilities; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace MonoGame.Interop; + +internal class MGHandleAttribute : System.Attribute +{ +} + +internal enum EventType : uint +{ + Quit, + + WindowMoved, + WindowResized, + WindowGainedFocus, + WindowLostFocus, + WindowClose, + + KeyDown, + KeyUp, + TextInput, + + MouseMove, + MouseButtonDown, + MouseButtonUp, + MouseWheel, + + ControllerAdded, + ControllerRemoved, + ControllerStateChange, + + DropFile, + DropComplete, +} + + +[StructLayout(LayoutKind.Sequential)] +internal struct MGP_WindowEvent +{ + public nint Window; + public int Data1; + public int Data2; +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MGP_KeyEvent +{ + public nint Window; + public uint Character; + public Keys Key; +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MGP_MouseMoveEvent +{ + public nint Window; + public int X; + public int Y; +} + +internal enum MouseButton +{ + Left, + Middle, + Right, + X1, + X2 +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MGP_MouseButtonEvent +{ + public nint Window; + public MouseButton Button; +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MGP_MouseWheelEvent +{ + public nint Window; + public int Scroll; + public int ScrollH; +} + +internal enum SystemCursor : int +{ + Arrow, + IBeam, + Wait, + Crosshair, + WaitArrow, + SizeNWSE, + SizeNESW, + SizeWE, + SizeNS, + SizeAll, + No, + Hand +} + +[MGHandle] +internal readonly struct MGP_Cursor { } + +internal enum ControllerInput : int +{ + INVALID = -1, + + A, + B, + X, + Y, + Back, + Guide, + Start, + LeftStick, + RightStick, + LeftShoulder, + RightShoulder, + DpadUp, + DpadDown, + DpadLeft, + DpadRight, + Misc1, + Paddle1, + Paddle2, + Paddle3, + Paddle4, + Touchpad, + LAST_BUTTON = Touchpad, + + LeftStickX, + LeftStickY, + RightStickX, + RightStickY, + LeftTrigger, + RightTrigger, + LAST_TRIGGER = RightTrigger, +} + +[StructLayout(LayoutKind.Sequential)] +internal struct MGP_ControllerEvent +{ + public int Id; + + public ControllerInput Input; + + /// + /// For a axis input this can range from -32768 to 32767. + /// For a button input the value is 0 or 1. + /// + public short Value; +} + + +[StructLayout(LayoutKind.Sequential)] +internal struct MGP_DropEvent +{ + public nint Window; + public nint File; +} + + +[StructLayout(LayoutKind.Explicit)] +internal struct MGP_Event +{ + [FieldOffset(0)] + public EventType Type; + + [FieldOffset(4)] + public ulong Timestamp; + + [FieldOffset(12)] + public MGP_KeyEvent Key; + + [FieldOffset(12)] + public MGP_MouseMoveEvent MouseMove; + + [FieldOffset(12)] + public MGP_MouseButtonEvent MouseButton; + + [FieldOffset(12)] + public MGP_MouseWheelEvent MouseWheel; + + [FieldOffset(12)] + public MGP_DropEvent Drop; + + [FieldOffset(12)] + public MGP_WindowEvent Window; + + [FieldOffset(12)] + public MGP_ControllerEvent Controller; +} + +[MGHandle] +internal readonly struct MGP_Platform { } + +[MGHandle] +internal readonly struct MGP_Window { } + +internal static unsafe partial class MGP +{ + public const string MonoGameNativeDLL = "monogame.native"; + + #region Platform + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Platform_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGP_Platform* Platform_Create(out GameRunBehavior behavior); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Platform_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Platform_Destroy(MGP_Platform* platform); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Platform_BeforeInitialize", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Platform_BeforeInitialize(MGP_Platform* platform); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Platform_PollEvent", StringMarshalling = StringMarshalling.Utf8)] + [return: MarshalAs(UnmanagedType.U1)] + public static partial bool Platform_PollEvent(MGP_Platform* platform, out MGP_Event event_); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Platform_StartRunLoop", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Platform_StartRunLoop(MGP_Platform* platform); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Platform_BeforeRun", StringMarshalling = StringMarshalling.Utf8)] + [return: MarshalAs(UnmanagedType.U1)] + public static partial bool Platform_BeforeRun(MGP_Platform* platform); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Platform_BeforeUpdate", StringMarshalling = StringMarshalling.Utf8)] + [return: MarshalAs(UnmanagedType.U1)] + public static partial bool Platform_BeforeUpdate(MGP_Platform* platform); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Platform_BeforeDraw", StringMarshalling = StringMarshalling.Utf8)] + [return: MarshalAs(UnmanagedType.U1)] + public static partial bool Platform_BeforeDraw(MGP_Platform* platform); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Platform_MakePath", StringMarshalling = StringMarshalling.Utf8)] + public static partial string Platform_MakePath(string location, string path); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Platform_GetPlatform", StringMarshalling = StringMarshalling.Utf8)] + public static partial MonoGamePlatform Platform_GetPlatform(); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Platform_GetGraphicsBackend", StringMarshalling = StringMarshalling.Utf8)] + public static partial GraphicsBackend Platform_GetGraphicsBackend(); + + #endregion + + #region Window + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGP_Window* Window_Create( + MGP_Platform* platform, + int width, + int height, + string title); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Window_Destroy(MGP_Window* window); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_SetIconBitmap", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Window_SetIconBitmap(MGP_Window* window, byte[] icon, int length); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_GetNativeHandle", StringMarshalling = StringMarshalling.Utf8)] + public static partial nint Window_GetNativeHandle(MGP_Window* window); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_GetAllowUserResizing", StringMarshalling = StringMarshalling.Utf8)] + [return: MarshalAs(UnmanagedType.U1)] + public static partial bool Window_GetAllowUserResizing(MGP_Window* window); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_SetAllowUserResizing", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Window_SetAllowUserResizing(MGP_Window* window, [MarshalAs(UnmanagedType.U1)] bool allow); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_GetIsBoderless", StringMarshalling = StringMarshalling.Utf8)] + [return: MarshalAs(UnmanagedType.U1)] + public static partial bool Window_GetIsBorderless(MGP_Window* window); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_SetIsBoderless", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Window_SetIsBorderless(MGP_Window* window, [MarshalAs(UnmanagedType.U1)] bool borderless); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_SetTitle", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Window_SetTitle(MGP_Window* window, string title); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_Show", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Window_Show(MGP_Window* window, [MarshalAs(UnmanagedType.U1)] bool show); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_GetPosition", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Window_GetPosition(MGP_Window* window, out int x, out int y); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_SetPosition", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Window_SetPosition(MGP_Window* window, int x, int y); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_SetClientSize", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Window_SetClientSize(MGP_Window* window, int width, int height); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_SetCursor", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Window_SetCursor(MGP_Window* window, MGP_Cursor* cursor); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_ShowMessageBox", StringMarshalling = StringMarshalling.Utf8)] + public static partial int Window_ShowMessageBox( + MGP_Window* window, + string title, + string description, + string[] buttons, + int count); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_EnterFullScreen", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Window_EnterFullScreen(MGP_Window* window, [MarshalAs(UnmanagedType.U1)] bool useHardwareModeSwitch); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Window_ExitFullScreen", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Window_ExitFullScreen(MGP_Window* window); + + #endregion + + #region Mouse + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Mouse_SetVisible", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Mouse_SetVisible(MGP_Platform* platform, [MarshalAs(UnmanagedType.U1)] bool visible); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Mouse_WarpPosition", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Mouse_WarpPosition(MGP_Window* window, int x, int y); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Cursor_Create", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGP_Cursor* Cursor_Create(SystemCursor cursor); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Cursor_CreateCustom", StringMarshalling = StringMarshalling.Utf8)] + public static partial MGP_Cursor* Cursor_CreateCustom(byte[] rgba, int width, int height, int originx, int originy); + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_Cursor_Destroy", StringMarshalling = StringMarshalling.Utf8)] + public static partial void Cursor_Destroy(MGP_Cursor* cursor); + + #endregion + + + [LibraryImport(MonoGameNativeDLL, EntryPoint = "MGP_GamePad_GetMaxSupported", StringMarshalling = StringMarshalling.Utf8)] + public static partial int GamePad_GetMaxSupported(); + +} diff --git a/MonoGame.Framework/Platform/Native/PlatformInfo.Native.cs b/MonoGame.Framework/Platform/Native/PlatformInfo.Native.cs index e82b9c15dba..00744c8fbf5 100644 --- a/MonoGame.Framework/Platform/Native/PlatformInfo.Native.cs +++ b/MonoGame.Framework/Platform/Native/PlatformInfo.Native.cs @@ -2,17 +2,22 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; + namespace MonoGame.Framework.Utilities; public static partial class PlatformInfo { + static readonly MonoGamePlatform _platform = MGP.Platform_GetPlatform(); + static readonly GraphicsBackend _graphics = MGP.Platform_GetGraphicsBackend(); + private static MonoGamePlatform PlatformGetMonoGamePlatform() { - return MonoGamePlatform.DesktopGL; + return _platform; } private static GraphicsBackend PlatformGetGraphicsBackend() { - return GraphicsBackend.OpenGL; + return _graphics; } } diff --git a/MonoGame.Framework/Platform/Native/RasterizerState.Native.cs b/MonoGame.Framework/Platform/Native/RasterizerState.Native.cs index f1d4b5e2734..cdcffdc4e7b 100644 --- a/MonoGame.Framework/Platform/Native/RasterizerState.Native.cs +++ b/MonoGame.Framework/Platform/Native/RasterizerState.Native.cs @@ -2,12 +2,42 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; + namespace Microsoft.Xna.Framework.Graphics; public partial class RasterizerState { - internal void PlatformApplyState(GraphicsDevice device) + internal unsafe MGG_RasterizerState* Handle; + + internal unsafe void PlatformApplyState(GraphicsDevice device) { + if (Handle == null) + { + MGG_RasterizerState_Info info; + info.fillMode = FillMode; + info.cullMode = CullMode; + info.scissorTestEnable = ScissorTestEnable; + info.depthClipEnable = DepthClipEnable; + info.depthBias = DepthBias; + info.slopeScaleDepthBias = SlopeScaleDepthBias; + info.multiSampleAntiAlias = MultiSampleAntiAlias; + + Handle = MGG.RasterizerState_Create(device.Handle, &info); + } + MGG.GraphicsDevice_SetRasterizerState(device.Handle, Handle); + } + + partial void PlatformDispose() + { + unsafe + { + if (Handle != null) + { + MGG.RasterizerState_Destroy(GraphicsDevice.Handle, Handle); + Handle = null; + } + } } } diff --git a/MonoGame.Framework/Platform/Native/ReflectionHelper.Native.cs b/MonoGame.Framework/Platform/Native/ReflectionHelper.Native.cs deleted file mode 100644 index dfc12953fbf..00000000000 --- a/MonoGame.Framework/Platform/Native/ReflectionHelper.Native.cs +++ /dev/null @@ -1,31 +0,0 @@ -// MonoGame - Copyright (C) The MonoGame Team -// This file is subject to the terms and conditions defined in -// file 'LICENSE.txt', which is part of this source code package. - -using System; -using System.Runtime.InteropServices; - -namespace MonoGame.Framework.Utilities; - -internal static partial class ReflectionHelpers -{ - internal static class SizeOf - { - static int _sizeOf; - - static SizeOf() - { - _sizeOf = Marshal.SizeOf(); - } - - public static int Get() - { - return _sizeOf; - } - } - - internal static int ManagedSizeOf(Type type) - { - return Marshal.SizeOf(type); - } -} diff --git a/MonoGame.Framework/Platform/Native/RenderTarget2D.Native.cs b/MonoGame.Framework/Platform/Native/RenderTarget2D.Native.cs index 58ccdf165a5..f918fa2aa77 100644 --- a/MonoGame.Framework/Platform/Native/RenderTarget2D.Native.cs +++ b/MonoGame.Framework/Platform/Native/RenderTarget2D.Native.cs @@ -2,17 +2,33 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; namespace Microsoft.Xna.Framework.Graphics; public partial class RenderTarget2D { - private void PlatformConstruct(GraphicsDevice graphicsDevice, int width, int height, bool mipMap, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage, bool shared) + private unsafe void PlatformConstruct(GraphicsDevice graphicsDevice, int width, int height, bool mipMap, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage, bool shared) { - + Handle = MGG.RenderTarget_Create( + GraphicsDevice.Handle, + TextureType._2D, + _format, + width, + height, + 1, + _levelCount, + ArraySize, + preferredDepthFormat, + preferredMultiSampleCount, + usage); } - private void PlatformGraphicsDeviceResetting() + private unsafe void PlatformGraphicsDeviceResetting() { - + if (Handle != null && Owned) + { + MGG.Texture_Destroy(GraphicsDevice.Handle, Handle); + Handle = null; + } } } diff --git a/MonoGame.Framework/Platform/Native/RenderTarget3D.Native.cs b/MonoGame.Framework/Platform/Native/RenderTarget3D.Native.cs index d2c8389de90..15f0e2d729b 100644 --- a/MonoGame.Framework/Platform/Native/RenderTarget3D.Native.cs +++ b/MonoGame.Framework/Platform/Native/RenderTarget3D.Native.cs @@ -2,12 +2,25 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; + namespace Microsoft.Xna.Framework.Graphics; public partial class RenderTarget3D { - private void PlatformConstruct(GraphicsDevice graphicsDevice, int width, int height, bool mipMap, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage) + private unsafe void PlatformConstruct(GraphicsDevice graphicsDevice, int width, int height, bool mipMap, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage) { - + Handle = MGG.RenderTarget_Create( + GraphicsDevice.Handle, + TextureType._3D, + _format, + width, + height, + Depth, + _levelCount, + 1, + preferredDepthFormat, + preferredMultiSampleCount, + usage); } } diff --git a/MonoGame.Framework/Platform/Native/RenderTargetCube.Native.cs b/MonoGame.Framework/Platform/Native/RenderTargetCube.Native.cs index e64d10b0bcd..1acb980ab22 100644 --- a/MonoGame.Framework/Platform/Native/RenderTargetCube.Native.cs +++ b/MonoGame.Framework/Platform/Native/RenderTargetCube.Native.cs @@ -2,12 +2,25 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; + namespace Microsoft.Xna.Framework.Graphics; public partial class RenderTargetCube { - private void PlatformConstruct(GraphicsDevice graphicsDevice, bool mipMap, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage) + private unsafe void PlatformConstruct(GraphicsDevice graphicsDevice, bool mipMap, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage) { - + Handle = MGG.RenderTarget_Create( + GraphicsDevice.Handle, + TextureType.Cube, + _format, + Size, + Size, + 1, + _levelCount, + 6, + preferredDepthFormat, + preferredMultiSampleCount, + usage); } } diff --git a/MonoGame.Framework/Platform/Native/SamplerState.Native.cs b/MonoGame.Framework/Platform/Native/SamplerState.Native.cs new file mode 100644 index 00000000000..6f553b51dc5 --- /dev/null +++ b/MonoGame.Framework/Platform/Native/SamplerState.Native.cs @@ -0,0 +1,62 @@ +// MonoGame - Copyright (C) MonoGame Foundation, Inc +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using MonoGame.Interop; +using System; +using System.Diagnostics; + +namespace Microsoft.Xna.Framework.Graphics; + + +public partial class SamplerState +{ + private unsafe MGG_SamplerState* Handle; + + private unsafe void Destroy() + { + if (Handle != null) + { + MGG.SamplerState_Destroy(GraphicsDevice.Handle, Handle); + Handle = null; + } + } + + /// + protected unsafe internal override void GraphicsDeviceResetting() + { + Destroy(); + + base.GraphicsDeviceResetting(); + } + + internal unsafe MGG_SamplerState* GetHandle(GraphicsDevice device) + { + Debug.Assert(GraphicsDevice == device, "The state was created for a different device!"); + + if (Handle != null) + return Handle; + + var info = new MGG_SamplerState_Info(); + info.AddressU = AddressU; + info.AddressV = AddressV; + info.AddressW = AddressW; + info.BorderColor = BorderColor.PackedValue; + info.Filter = Filter; + info.FilterMode = FilterMode; + info.MaximumAnisotropy = Math.Min(MaxAnisotropy, device.GraphicsCapabilities.MaxTextureAnisotropy); + info.MaxMipLevel = MaxMipLevel; + info.MipMapLevelOfDetailBias = MipMapLevelOfDetailBias; + info.ComparisonFunction = ComparisonFunction; + + Handle = MGG.SamplerState_Create(device.Handle, &info); + + return Handle; + } + + partial void PlatformDispose() + { + Destroy(); + } +} + diff --git a/MonoGame.Framework/Platform/Native/SamplerStateCollection.Native.cs b/MonoGame.Framework/Platform/Native/SamplerStateCollection.Native.cs index b9b59b77701..0c149603f0c 100644 --- a/MonoGame.Framework/Platform/Native/SamplerStateCollection.Native.cs +++ b/MonoGame.Framework/Platform/Native/SamplerStateCollection.Native.cs @@ -2,24 +2,58 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; + namespace Microsoft.Xna.Framework.Graphics; public sealed partial class SamplerStateCollection { + private int _dirty; + private void PlatformSetSamplerState(int index) { + _dirty |= 1 << index; } private void PlatformClear() { + _dirty = int.MaxValue; } private void PlatformDirty() { + _dirty = int.MaxValue; } - private void PlatformSetSamplers(GraphicsDevice device) + internal unsafe void PlatformSetSamplers(GraphicsDevice device) { + if (_stage == ShaderStage.Vertex && !device.GraphicsCapabilities.SupportsVertexTextures) + return; + + // Skip out if nothing has changed. + if (_dirty == 0) + return; + + var handle = device.Handle; + + for (var i = 0; i < _actualSamplers.Length; i++) + { + var mask = 1 << i; + if ((_dirty & mask) == 0) + continue; + + var sampler = _actualSamplers[i]; + if (sampler != null) + { + var state = sampler.GetHandle(device); + MGG.GraphicsDevice_SetSamplerState(handle, _stage, i, state); + } + + _dirty &= ~mask; + if (_dirty == 0) + break; + } + _dirty = 0; } } diff --git a/MonoGame.Framework/Platform/Native/Shader.Native.cs b/MonoGame.Framework/Platform/Native/Shader.Native.cs index 1a6d03d5af2..5c259a1061a 100644 --- a/MonoGame.Framework/Platform/Native/Shader.Native.cs +++ b/MonoGame.Framework/Platform/Native/Shader.Native.cs @@ -2,22 +2,72 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; +using System.Collections.Generic; +using System.Runtime.InteropServices; + namespace Microsoft.Xna.Framework.Graphics; partial class Shader { + internal unsafe MGG_Shader* Handle; + + private byte[] _bytecode; + private readonly Dictionary> _cache = new Dictionary>(); + private static int PlatformProfile() { - return 0; + return GraphicsDevice.ShaderProfile; + } + + private unsafe void PlatformConstruct(ShaderStage stage, byte[] shaderBytecode) + { + fixed (byte* bytecode = shaderBytecode) + Handle = MGG.Shader_Create(GraphicsDevice.Handle, stage, bytecode, shaderBytecode.Length); + } + + internal unsafe MGG_InputLayout* GetOrCreateLayout(VertexBufferBindings vertexBuffers) + { + // First check the cache. + PtrTo inputLayout; + if (_cache.TryGetValue(vertexBuffers, out inputLayout)) + return inputLayout.Ptr; + + // Generate and cache a new layout based on the current + // vb bindings and this vertex shader. + + var vertexInputLayout = vertexBuffers.ToImmutable(); + vertexInputLayout.GenerateInputElements(Attributes, out var inputElements, out var streamStrides); + + inputLayout.Ptr = MGG.InputLayout_Create( + GraphicsDevice.Handle, + streamStrides, + streamStrides.Length, + inputElements, + inputElements.Length); + + _cache.Add(vertexInputLayout, inputLayout); + + return inputLayout.Ptr; } - private void PlatformConstruct(ShaderStage stage, byte[] shaderBytecode) + private unsafe void PlatformGraphicsDeviceResetting() { + foreach (var pair in _cache) + MGG.InputLayout_Destroy(GraphicsDevice.Handle, pair.Value.Ptr); + _cache.Clear(); + if (Handle != null) + { + MGG.Shader_Destroy(GraphicsDevice.Handle, Handle); + Handle = null; + } } - private void PlatformGraphicsDeviceResetting() + protected override void Dispose(bool disposing) { + PlatformGraphicsDeviceResetting(); + base.Dispose(disposing); } } diff --git a/MonoGame.Framework/Platform/Native/Song.Native.cs b/MonoGame.Framework/Platform/Native/Song.Native.cs index bedda5aa798..34bea91c54d 100644 --- a/MonoGame.Framework/Platform/Native/Song.Native.cs +++ b/MonoGame.Framework/Platform/Native/Song.Native.cs @@ -3,68 +3,192 @@ // file 'LICENSE.txt', which is part of this source code package. using System; +using System.Runtime.InteropServices; +using MonoGame.Interop; namespace Microsoft.Xna.Framework.Media; public sealed partial class Song : IEquatable, IDisposable { - private void PlatformInitialize(string fileName) + private unsafe MGM_Song* _song; + + private GCHandle _self; + + #region The playback API used by MediaPlayer + + private unsafe void PlatformInitialize(string fileName) + { + _song = MGM.Song_Create(fileName); + } + + private unsafe void PlatformDispose(bool disposing) + { + if (_self.IsAllocated) + _self.Free(); + + if (_song != null) + { + MGM.Song_Destroy(_song); + _song = null; + } + } + + private int PlatformGetPlayCount() + { + return _playCount; + } + + private unsafe TimeSpan PlatformGetDuration() + { + if (_song == null) + return TimeSpan.Zero; + + var milliseconds = MGM.Song_GetDuration(_song); + return TimeSpan.FromMilliseconds(milliseconds); + } + + internal unsafe float Volume + { + get + { + if (_song == null) + return 0.0f; + + return MGM.Song_GetVolume(_song); + } + + set + { + if (_song != null) + MGM.Song_SetVolume(_song, value); + } + } + + internal unsafe TimeSpan Position + { + get + { + if (_song == null) + return TimeSpan.Zero; + + var milliseconds = MGM.Song_GetPosition(_song); + return TimeSpan.FromMilliseconds(milliseconds); + } + } + + internal static void FinishedCallback(nint callbackData) + { + var self = GCHandle.FromIntPtr(callbackData); + var song = self.Target as Song; + + // This could happen if we were disposed. + if (song == null) + return; + + // This callback is likely coming from a platform + // specific native thread. So queue the event to + // the main game thread for processing on the + // next tick. + + Threading.OnUIThread(() => song.DonePlaying(song, EventArgs.Empty)); + } + + internal unsafe void Play(TimeSpan? startPosition, FinishedPlayingHandler handler) { + if (_song == null) + return; + ulong milliseconds = 0; + if (startPosition.HasValue) + milliseconds = (ulong)startPosition.Value.TotalMilliseconds; + + // Only setup the finished callback once. + if (DonePlaying == null) + DonePlaying += handler; + if (!_self.IsAllocated) + _self = GCHandle.Alloc(this, GCHandleType.Weak); + + MGM.Song_Play(_song, milliseconds, FinishedCallback, (nint)_self); + + _playCount++; + } + + internal unsafe void Pause() + { + if (_song == null) + return; + + MGM.Song_Pause(_song); } - private void PlatformDispose(bool disposing) + internal unsafe void Resume() { + if (_song == null) + return; + MGM.Song_Resume(_song); } + internal unsafe void Stop() + { + if (_song == null) + return; + + MGM.Song_Stop(_song); + } + + + #endregion + + #region Media Library Features Not Supported + private Album PlatformGetAlbum() { + // Not Supported. return null; } private Artist PlatformGetArtist() { + // Not Supported. return null; } private Genre PlatformGetGenre() { + // Not Supported. return null; } - private TimeSpan PlatformGetDuration() - { - return TimeSpan.Zero; - } - private bool PlatformIsProtected() { + // Not Supported. return false; } private bool PlatformIsRated() { + // Not Supported. return false; } - private string PlatformGetName() - { - return ""; - } - - private int PlatformGetPlayCount() + private int PlatformGetRating() { + // Not Supported. return 0; } - private int PlatformGetRating() + private int PlatformGetTrackNumber() { + // Not Supported. return 0; } - private int PlatformGetTrackNumber() + private string PlatformGetName() { - return 0; + // Not Supported. + return string.Empty; } + + #endregion } diff --git a/MonoGame.Framework/Platform/Native/SoundEffect.Native.cs b/MonoGame.Framework/Platform/Native/SoundEffect.Native.cs index dc021d124d7..36ebbe830b8 100644 --- a/MonoGame.Framework/Platform/Native/SoundEffect.Native.cs +++ b/MonoGame.Framework/Platform/Native/SoundEffect.Native.cs @@ -4,55 +4,156 @@ using System; using System.IO; +using MonoGame.Interop; + namespace Microsoft.Xna.Framework.Audio; public sealed partial class SoundEffect { - internal const int MAX_PLAYING_INSTANCES = int.MaxValue; + internal static readonly int MAX_PLAYING_INSTANCES = MGA.System_GetMaxInstances(); - private void PlatformLoadAudioStream(Stream s, out TimeSpan duration) + internal static unsafe MGA_System* System; + + internal unsafe MGA_Buffer* Buffer; + + private unsafe static void PlatformInitialize() { - duration = TimeSpan.Zero; + System = MGA.System_Create(); } - private void PlatformInitializePcm(byte[] buffer, int offset, int count, int sampleBits, int sampleRate, AudioChannels channels, int loopStart, int loopLength) + internal unsafe static void PlatformShutdown() { - + if (System != null) + { + MGA.System_Destroy(System); + System = null; + } } - private void PlatformInitializeFormat(byte[] header, byte[] buffer, int bufferSize, int loopStart, int loopLength) + private void PlatformLoadAudioStream(Stream s, out TimeSpan duration) { - + using (var reader = new BinaryReader(s)) + { + var riff = reader.ReadBytes(4); + reader.ReadBytes(8); + + byte[] waveData = null; + byte[] headerData = null; + byte[] dpdsData = null; + + // Read chunks. + for (;;) + { + var name = reader.ReadBytes(4); + var len = reader.ReadInt32(); + if (len == -1) + break; + + var isData = name[0] == 'd' && name[1] == 'a' && name[2] == 't' && name[3] == 'a'; + var isFormat = name[0] == 'f' && name[1] == 'm' && name[2] == 't' && name[3] == ' '; + var isDpDs = name[0] == 'd' && name[1] == 'p' && name[2] == 'd' && name[3] == 's'; + + if (isData) + waveData = reader.ReadBytes(len); + else if (isFormat) + headerData = reader.ReadBytes(len); + else if (isDpDs) + dpdsData = reader.ReadBytes(len); + else + reader.ReadBytes(len); + + if (waveData != null && headerData != null) + break; + } + + unsafe + { + Buffer = MGA.Buffer_Create(System); + MGA.Buffer_InitializeFormat(Buffer, headerData, waveData, waveData.Length, 0, 0); + + var milliseconds = MGA.Buffer_GetDuration(Buffer); + duration = TimeSpan.FromMilliseconds(milliseconds); + } + } } - private void PlatformInitializeXact(MiniFormatTag codec, byte[] buffer, int channels, int sampleRate, int blockAlignment, int loopStart, int loopLength, out TimeSpan duration) + private unsafe void PlatformInitializePcm(byte[] buffer, int offset, int count, int sampleBits, int sampleRate, AudioChannels channels, int loopStart, int loopLength) { - duration = TimeSpan.Zero; + Buffer = MGA.Buffer_Create(System); + MGA.Buffer_InitializePCM(Buffer, buffer, offset, count, sampleBits, sampleRate, (int)channels, loopStart, loopLength); } - private void PlatformSetupInstance(SoundEffectInstance instance) + private unsafe void PlatformInitializeFormat(byte[] header, byte[] buffer, int bufferSize, int loopStart, int loopLength) { - + Buffer = MGA.Buffer_Create(System); + MGA.Buffer_InitializeFormat(Buffer, header, buffer, bufferSize, loopStart, loopLength); } - private void PlatformDispose(bool disposing) + // TODO: This should go away after we move to FAudio's Xact implementation. + private unsafe void PlatformInitializeXact(MiniFormatTag codec, byte[] buffer, int channels, int sampleRate, int blockAlignment, int loopStart, int loopLength, out TimeSpan duration) { + // This is only the platform specific non-streaming + // Xact sound handling as PCM is already handled. + + Buffer = MGA.Buffer_Create(System); + MGA.Buffer_InitializeXact(Buffer, (uint)codec, buffer, buffer.Length, sampleRate, blockAlignment, channels, loopStart, loopLength); + var milliseconds = MGA.Buffer_GetDuration(Buffer); + duration = TimeSpan.FromMilliseconds(milliseconds); } - internal static void PlatformSetReverbSettings(ReverbSettings reverbSettings) + private unsafe void PlatformSetupInstance(SoundEffectInstance instance) { + // If the instance came from the pool then it could + // already have a valid voice assigned. + if (instance.Voice == null) + instance.Voice = MGA.Voice_Create(System); + + MGA.Voice_SetBuffer(instance.Voice, Buffer); } - private static void PlatformInitialize() + private unsafe void PlatformDispose(bool disposing) { - + if (disposing) + { + if (Buffer != null) + { + MGA.Buffer_Destroy(Buffer); + Buffer = null; + } + } } - internal static void PlatformShutdown() + internal unsafe static void PlatformSetReverbSettings(ReverbSettings reverbSettings) { - + var settings = new MonoGame.Interop.ReverbSettings + { + ReflectionsDelayMs = reverbSettings.ReflectionsDelayMs, + ReverbDelayMs = reverbSettings.ReverbDelayMs, + PositionLeft = reverbSettings.PositionLeft, + PositionRight = reverbSettings.PositionRight, + PositionLeftMatrix = reverbSettings.PositionLeftMatrix, + PositionRightMatrix = reverbSettings.PositionRightMatrix, + EarlyDiffusion = reverbSettings.EarlyDiffusion, + LateDiffusion = reverbSettings.LateDiffusion, + LowEqGain = reverbSettings.LowEqGain, + LowEqCutoff = reverbSettings.LowEqCutoff, + HighEqGain = reverbSettings.HighEqGain, + HighEqCutoff = reverbSettings.HighEqCutoff, + RearDelayMs = reverbSettings.RearDelayMs, + RoomFilterFrequencyHz = reverbSettings.RoomFilterFrequencyHz, + RoomFilterMainDb = reverbSettings.RoomFilterMainDb, + RoomFilterHighFrequencyDb = reverbSettings.RoomFilterHighFrequencyDb, + ReflectionsGainDb = reverbSettings.ReflectionsGainDb, + ReverbGainDb = reverbSettings.ReverbGainDb, + DecayTimeSec = reverbSettings.DecayTimeSec, + DensityPct = reverbSettings.DensityPct, + RoomSizeFeet = reverbSettings.RoomSizeFeet, + WetDryMixPct = reverbSettings.WetDryMixPct + }; + + MGA.System_SetReverbSettings(System, in settings); } } diff --git a/MonoGame.Framework/Platform/Native/SoundEffectInstance.Native.cs b/MonoGame.Framework/Platform/Native/SoundEffectInstance.Native.cs index 337f2033a22..731183c019e 100644 --- a/MonoGame.Framework/Platform/Native/SoundEffectInstance.Native.cs +++ b/MonoGame.Framework/Platform/Native/SoundEffectInstance.Native.cs @@ -3,88 +3,117 @@ // file 'LICENSE.txt', which is part of this source code package. using System; +using Microsoft.Xna.Framework.Graphics; +using MonoGame.Interop; + namespace Microsoft.Xna.Framework.Audio; public partial class SoundEffectInstance : IDisposable { - private void PlatformInitialize(byte[] buffer, int sampleRate, int channels) - { + internal unsafe MGA_Voice* Voice; - } - private void PlatformApply3D(AudioListener listener, AudioEmitter emitter) + private unsafe void PlatformApply3D(AudioListener listener, AudioEmitter emitter) { + var listener_ = new Listener() + { + Position = listener.Position, + Forward = listener.Forward, + Up = listener.Up, + Velocity = listener.Velocity, + }; - } - - private void PlatformPause() - { + var emitter_ = new Emitter() + { + Position = emitter.Position, + Forward = emitter.Forward, + Up = emitter.Up, + Velocity = emitter.Velocity, + DopplerScale = emitter.DopplerScale + }; + if (Voice != null) + MGA.Voice_Apply3D(Voice, in listener_, in emitter_, SoundEffect.DistanceScale); } - private void PlatformPlay() + private unsafe void PlatformPause() { - + if (Voice != null) + MGA.Voice_Pause(Voice); } - private void PlatformResume() + private unsafe void PlatformPlay() { - + if (Voice != null) + MGA.Voice_Play(Voice, _isLooped); } - private void PlatformStop(bool immediate) + private unsafe void PlatformResume() { - + if (Voice != null) + MGA.Voice_Resume(Voice); } - private void PlatformSetIsLooped(bool value) + private unsafe void PlatformStop(bool immediate) { - + if (Voice != null) + MGA.Voice_Stop(Voice, immediate); } - private bool PlatformGetIsLooped() + private unsafe void PlatformSetPan(float pan) { - return false; + if (Voice != null) + MGA.Voice_SetPan(Voice, pan); } - private void PlatformSetPan(float value) + private unsafe void PlatformSetPitch(float pitch) { - + if (Voice != null) + MGA.Voice_SetPitch(Voice, pitch); } - private void PlatformSetPitch(float value) + private unsafe SoundState PlatformGetState() { + if (Voice != null) + return MGA.Voice_GetState(Voice); - } - - private SoundState PlatformGetState() - { return SoundState.Stopped; } - private void PlatformSetVolume(float value) + private unsafe void PlatformSetVolume(float volume) { - + if (Voice != null) + MGA.Voice_SetVolume(Voice, volume); } - internal void PlatformSetReverbMix(float mix) + internal unsafe void PlatformSetReverbMix(float mix) { - + if (Voice != null) + MGA.Voice_SetReverbMix(Voice, mix); } - internal void PlatformSetFilter(FilterMode mode, float filterQ, float frequency) + internal unsafe void PlatformSetFilter(FilterMode mode, float filterQ, float frequency) { - + if (Voice != null) + MGA.Voice_SetFilterMode(Voice, mode, filterQ, frequency); } - internal void PlatformClearFilter() + internal unsafe void PlatformClearFilter() { - + if (Voice != null) + MGA.Voice_ClearFilterMode(Voice); } - private void PlatformDispose(bool disposing) + private unsafe void PlatformDispose(bool disposing) { - + if (disposing) + { + if (Voice != null) + { + MGA.Voice_Destroy(Voice); + Voice = null; + } + } } } diff --git a/MonoGame.Framework/Platform/Native/Texture.Native.cs b/MonoGame.Framework/Platform/Native/Texture.Native.cs index 8bbcdad4e26..cea969c23b0 100644 --- a/MonoGame.Framework/Platform/Native/Texture.Native.cs +++ b/MonoGame.Framework/Platform/Native/Texture.Native.cs @@ -2,12 +2,27 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; namespace Microsoft.Xna.Framework.Graphics; public abstract partial class Texture { - private void PlatformGraphicsDeviceResetting() + internal unsafe MGG_Texture* Handle; + internal bool Owned = true; + + private unsafe void PlatformGraphicsDeviceResetting() + { + if (Handle != null && Owned) + { + MGG.Texture_Destroy(GraphicsDevice.Handle, Handle); + Handle = null; + } + } + + protected unsafe override void Dispose(bool disposing) { + PlatformGraphicsDeviceResetting(); + base.Dispose(disposing); } } diff --git a/MonoGame.Framework/Platform/Native/Texture2D.Native.cs b/MonoGame.Framework/Platform/Native/Texture2D.Native.cs index 3ddeb1f0e69..c3af5adcee0 100644 --- a/MonoGame.Framework/Platform/Native/Texture2D.Native.cs +++ b/MonoGame.Framework/Platform/Native/Texture2D.Native.cs @@ -4,53 +4,269 @@ using System; using System.IO; +using System.Runtime.InteropServices; +using MonoGame.Interop; +using MonoGame.Framework.Utilities; + namespace Microsoft.Xna.Framework.Graphics; public partial class Texture2D : Texture { - private void PlatformConstruct(int width, int height, bool mipmap, SurfaceFormat format, SurfaceType type, bool shared) + /// + /// Wrap a texture handle without owning the native texture. + /// + internal unsafe Texture2D(GraphicsDevice graphicsDevice, MGG_Texture* handle, int width, int height, bool mipmap, SurfaceFormat format, SurfaceType type, int arraySize) + { + this.GraphicsDevice = graphicsDevice; + this.Handle = handle; + this.Owned = false; + this.width = width; + this.height = height; + this.TexelWidth = 1f / (float)width; + this.TexelHeight = 1f / (float)height; + this._format = format; + this._levelCount = mipmap ? CalculateMipLevels(width, height) : 1; + this.ArraySize = arraySize; + } + + private unsafe void PlatformConstruct(int width, int height, bool mipmap, SurfaceFormat format, SurfaceType type, bool shared) { + // Ignore creation calls for RenderTargets and Swapchains. + if (type != SurfaceType.Texture) + return; + Handle = MGG.Texture_Create(GraphicsDevice.Handle, TextureType._2D, format, width, height, 1, _levelCount, ArraySize); } private void PlatformSetData(int level, T[] data, int startIndex, int elementCount) where T : struct { + var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); + var elementSizeInByte = ReflectionHelpers.FastSizeOf(); + var startBytes = startIndex * elementSizeInByte; + var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); + unsafe + { + MGG.Texture_SetData( + GraphicsDevice.Handle, + Handle, + level, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + (byte*)dataPtr, + elementSizeInByte * elementCount); + } + + dataHandle.Free(); } private void PlatformSetData(int level, int arraySlice, Rectangle rect, T[] data, int startIndex, int elementCount) where T : struct { + var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); + var elementSizeInByte = ReflectionHelpers.FastSizeOf(); + var startBytes = startIndex * elementSizeInByte; + var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); + + unsafe + { + MGG.Texture_SetData( + GraphicsDevice.Handle, + Handle, + level, + arraySlice, + rect.X, + rect.Y, + 0, + rect.Width, + rect.Height, + 1, + (byte*)dataPtr, + elementSizeInByte * elementCount); + } + dataHandle.Free(); } - private void PlatformGetData(int level, int arraySlice, Rectangle rect, T[] data, int startIndex, int elementCount) where T : struct + private unsafe void PlatformGetData(int level, int arraySlice, Rectangle rect, T[] data, int startIndex, int elementCount) where T : struct { + var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); + var elementSizeInByte = ReflectionHelpers.FastSizeOf(); + var startBytes = startIndex * elementSizeInByte; + var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); - } + MGG.Texture_GetData( + GraphicsDevice.Handle, + Handle, + level, + arraySlice, + rect.X, + rect.Y, + 0, + rect.Width, + rect.Height, + 1, + (byte*)dataPtr, + elementSizeInByte * elementCount); - private static Texture2D PlatformFromStream(GraphicsDevice graphicsDevice, Stream stream) - { - return new Texture2D(graphicsDevice, 1, 1); + dataHandle.Free(); } - private static Texture2D PlatformFromStream(GraphicsDevice graphicsDevice, Stream stream, Action colorProcessor) + private static unsafe Texture2D PlatformFromStream(GraphicsDevice graphicsDevice, Stream stream, Action colorProcessor) { - return new Texture2D(graphicsDevice, 1, 1); + // HACK: Clear the default zero action as we do this natively. + if (colorProcessor == DefaultColorProcessors.ZeroTransparentPixels) + colorProcessor = null; + + // Simply read it all into memory as it will be fast + // for most cases and simplifies the native API. + + var dataLength = (int)stream.Length; + var streamTemp = new byte[dataLength]; + stream.Read(streamTemp, 0, dataLength); + + var handle = GCHandle.Alloc(streamTemp, GCHandleType.Pinned); + + byte* rgba; + int width, height; + + try + { + MGI.ReadRGBA( + (byte*)handle.AddrOfPinnedObject(), + dataLength, + colorProcessor == null ? true : false, + out width, + out height, + out rgba); + + if (rgba == null) + return null; + } + finally + { + handle.Free(); + } + + var texture = new Texture2D(graphicsDevice, width, height); + var rgbaBytes = width * height; + + if (colorProcessor == null) + { + // Without a color processor take the fast path. + + MGG.Texture_SetData( + graphicsDevice.Handle, + texture.Handle, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + rgba, + rgbaBytes); + + Marshal.FreeHGlobal((nint)rgba); + + return texture; + } + + // Since color processor takes a byte[] we need to copy the + // native memory to a managed array. + // + // Ideally we change this to use Span which avoids this. + var bytes = new byte[rgbaBytes]; + Marshal.Copy((nint)rgba, bytes, 0, rgbaBytes); + Marshal.FreeHGlobal((nint)rgba); + + // Do the processing. + colorProcessor(bytes); + + texture.SetData(bytes); + return texture; } - private void PlatformSaveAsJpeg(Stream stream, int width, int height) + private unsafe void PlatformSaveAsJpeg(Stream stream, int width, int height) { + Color[] data = GetColorData(); + + fixed (Color* ptr = &data[0]) + { + byte* jpg; + int jpgBytes; + + MGI.WriteJpg((byte*)ptr, data.Length, width, height, 90, out jpg, out jpgBytes); + stream.Write(new ReadOnlySpan(jpg, jpgBytes)); + } } - private void PlatformSaveAsPng(Stream stream, int width, int height) + private unsafe void PlatformSaveAsPng(Stream stream, int width, int height) { + Color[] data = GetColorData(); + fixed (Color* ptr = &data[0]) + { + byte* png; + int pngBytes; + + MGI.WritePng((byte*)ptr, data.Length, width, height, out png, out pngBytes); + + stream.Write(new ReadOnlySpan(png, pngBytes)); + } } - private void PlatformReload(Stream textureStream) + private unsafe void PlatformReload(Stream stream) { + var dataLength = (int)stream.Length; + var streamTemp = new byte[dataLength]; + stream.Read(streamTemp, 0, dataLength); + + var handle = GCHandle.Alloc(streamTemp, GCHandleType.Pinned); + + byte* rgba; + int width, height; + + try + { + MGI.ReadRGBA( + (byte*)handle.AddrOfPinnedObject(), + dataLength, + true, + out width, + out height, + out rgba); + + if (rgba == null) + return; + } + finally + { + handle.Free(); + } + + MGG.Texture_SetData( + GraphicsDevice.Handle, + Handle, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + rgba, + width * height); + Marshal.FreeHGlobal((nint)rgba); } } diff --git a/MonoGame.Framework/Platform/Native/Texture3D.Native.cs b/MonoGame.Framework/Platform/Native/Texture3D.Native.cs index d6b072ae57a..78a24358c06 100644 --- a/MonoGame.Framework/Platform/Native/Texture3D.Native.cs +++ b/MonoGame.Framework/Platform/Native/Texture3D.Native.cs @@ -2,22 +2,74 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using System; +using System.Runtime.InteropServices; +using MonoGame.Interop; +using MonoGame.Framework.Utilities; + + namespace Microsoft.Xna.Framework.Graphics; public partial class Texture3D : Texture { - private void PlatformConstruct(GraphicsDevice graphicsDevice, int width, int height, int depth, bool mipMap, SurfaceFormat format, bool renderTarget) + private unsafe void PlatformConstruct(GraphicsDevice graphicsDevice, int width, int height, int depth, bool mipMap, SurfaceFormat format, bool renderTarget) { - + Handle = MGG.Texture_Create(GraphicsDevice.Handle, TextureType._3D, format, width, height, depth, _levelCount, 1); } - private void PlatformSetData(int level, int left, int top, int right, int bottom, int front, int back, T[] data, int startIndex, int elementCount, int width, int height, int depth) + private unsafe void PlatformSetData(int level, int left, int top, int right, int bottom, int front, int back, T[] data, int startIndex, int elementCount) { + var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); + var elementSizeInByte = ReflectionHelpers.FastSizeOf(); + var startBytes = startIndex * elementSizeInByte; + var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); + + var width = right - left; + var height = bottom - top; + var depth = back - front; + MGG.Texture_SetData( + GraphicsDevice.Handle, + Handle, + level, + 0, + left, + top, + front, + width, + height, + depth, + (byte*)dataPtr, + elementSizeInByte * elementCount); + + dataHandle.Free(); } - private void PlatformGetData(int level, int left, int top, int right, int bottom, int front, int back, T[] data, int startIndex, int elementCount) where T : struct + private unsafe void PlatformGetData(int level, int left, int top, int right, int bottom, int front, int back, T[] data, int startIndex, int elementCount) where T : struct { + var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); + var elementSizeInByte = ReflectionHelpers.FastSizeOf(); + var startBytes = startIndex * elementSizeInByte; + var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); + + var width = right - left; + var height = bottom - top; + var depth = back - front; + + MGG.Texture_GetData( + GraphicsDevice.Handle, + Handle, + level, + 0, + left, + top, + front, + width, + height, + depth, + (byte*)dataPtr, + elementSizeInByte * elementCount); + dataHandle.Free(); } } diff --git a/MonoGame.Framework/Platform/Native/TextureCollection.Native.cs b/MonoGame.Framework/Platform/Native/TextureCollection.Native.cs index df2a7ca05c5..54ff7c6e01d 100644 --- a/MonoGame.Framework/Platform/Native/TextureCollection.Native.cs +++ b/MonoGame.Framework/Platform/Native/TextureCollection.Native.cs @@ -2,22 +2,50 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using MonoGame.Interop; + namespace Microsoft.Xna.Framework.Graphics; public sealed partial class TextureCollection { private void PlatformInit() { - } private void PlatformClear() { - } - private void PlatformSetTextures(GraphicsDevice device) + private unsafe void PlatformSetTextures(GraphicsDevice device) { + // Skip out if nothing has changed. + if (_dirty == 0) + return; + + for (var i = 0; i < _textures.Length; i++) + { + var mask = 1 << i; + if ((_dirty & mask) == 0) + continue; + + var tex = _textures[i]; + + if (_textures[i] == null || _textures[i].IsDisposed) + MGG.GraphicsDevice_SetTexture(device.Handle, _stage, i, null); + else + { + MGG.GraphicsDevice_SetTexture(device.Handle, _stage, i, tex.Handle); + unchecked + { + _graphicsDevice._graphicsMetrics._textureCount++; + } + } + + _dirty &= ~mask; + if (_dirty == 0) + break; + } + _dirty = 0; } } diff --git a/MonoGame.Framework/Platform/Native/TextureCube.Native.cs b/MonoGame.Framework/Platform/Native/TextureCube.Native.cs index 7db76ec874b..48297daa1ca 100644 --- a/MonoGame.Framework/Platform/Native/TextureCube.Native.cs +++ b/MonoGame.Framework/Platform/Native/TextureCube.Native.cs @@ -2,22 +2,75 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using System; +using System.Runtime.InteropServices; +using MonoGame.Interop; +using MonoGame.Framework.Utilities; + + namespace Microsoft.Xna.Framework.Graphics; public partial class TextureCube { - private void PlatformConstruct(GraphicsDevice graphicsDevice, int size, bool mipMap, SurfaceFormat format, bool renderTarget) + private unsafe void PlatformConstruct(GraphicsDevice graphicsDevice, int size, bool mipMap, SurfaceFormat format, bool renderTarget) { + if (renderTarget) + return; + Handle = MGG.Texture_Create(GraphicsDevice.Handle, TextureType.Cube, format, size, size, 1, _levelCount, 6); } - private void PlatformGetData(CubeMapFace cubeMapFace, int level, Rectangle rect, T[] data, int startIndex, int elementCount) where T : struct + private unsafe void PlatformSetData(CubeMapFace face, int level, Rectangle rect, T[] data, int startIndex, int elementCount) { + var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); + var elementSizeInByte = ReflectionHelpers.FastSizeOf(); + var startBytes = startIndex * elementSizeInByte; + var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); + + var width = rect.Right - rect.Left; + var height = rect.Bottom - rect.Top; + MGG.Texture_SetData( + GraphicsDevice.Handle, + Handle, + level, + 0, + rect.Left, + rect.Top, + (int)face, + width, + height, + 1, + (byte*)dataPtr, + elementSizeInByte * elementCount); + + dataHandle.Free(); } - private void PlatformSetData(CubeMapFace face, int level, Rectangle rect, T[] data, int startIndex, int elementCount) + private unsafe void PlatformGetData(CubeMapFace face, int level, Rectangle rect, T[] data, int startIndex, int elementCount) where T : struct { + var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); + var elementSizeInByte = ReflectionHelpers.FastSizeOf(); + var startBytes = startIndex * elementSizeInByte; + var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); + + var width = rect.Right - rect.Left; + var height = rect.Bottom - rect.Top; + + MGG.Texture_GetData( + GraphicsDevice.Handle, + Handle, + level, + 0, + rect.Left, + rect.Top, + (int)face, + width, + height, + 1, + (byte*)dataPtr, + elementSizeInByte * elementCount); + dataHandle.Free(); } } diff --git a/MonoGame.Framework/Platform/Native/TitleContainer.Native.cs b/MonoGame.Framework/Platform/Native/TitleContainer.Native.cs index e7edbaf8d4c..b885d1bc202 100644 --- a/MonoGame.Framework/Platform/Native/TitleContainer.Native.cs +++ b/MonoGame.Framework/Platform/Native/TitleContainer.Native.cs @@ -3,6 +3,8 @@ // file 'LICENSE.txt', which is part of this source code package. using System.IO; +using MonoGame.Interop; + namespace Microsoft.Xna.Framework; @@ -10,11 +12,12 @@ partial class TitleContainer { static partial void PlatformInit() { - } private static Stream PlatformOpenStream(string safeName) { - return Stream.Null; + var absolutePath = MGP.Platform_MakePath(Location, safeName); + + return File.OpenRead(absolutePath); } } diff --git a/MonoGame.Framework/Platform/Native/VertexBuffer.Native.cs b/MonoGame.Framework/Platform/Native/VertexBuffer.Native.cs index a7c0612a48e..0db0da22616 100644 --- a/MonoGame.Framework/Platform/Native/VertexBuffer.Native.cs +++ b/MonoGame.Framework/Platform/Native/VertexBuffer.Native.cs @@ -2,27 +2,67 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using System; +using System.Runtime.InteropServices; +using MonoGame.Interop; +using MonoGame.Framework.Utilities; + + namespace Microsoft.Xna.Framework.Graphics; public partial class VertexBuffer { - private void PlatformConstruct() - { + internal unsafe MGG_Buffer* Handle; + private unsafe void PlatformConstruct() + { + Handle = MGG.Buffer_Create(GraphicsDevice.Handle, BufferType.Vertex, VertexCount * VertexDeclaration.VertexStride); } - private void PlatformGetData(int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride) + private unsafe void PlatformGetData(int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride) { + var elementSizeInBytes = ReflectionHelpers.FastSizeOf(); + var startBytes = startIndex * elementSizeInBytes; + var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); + var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); + + MGG.Buffer_GetData(GraphicsDevice.Handle, Handle, offsetInBytes, (byte*)dataPtr, elementCount, elementSizeInBytes, vertexStride); + dataHandle.Free(); } - private void PlatformSetData(int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride, SetDataOptions options, int bufferSize, int elementSizeInBytes) + private unsafe void PlatformSetData(int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride, SetDataOptions options, int bufferSize, int elementSizeInBytes) { + var startBytes = startIndex * elementSizeInBytes; + var dataBytes = elementCount * elementSizeInBytes; + var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); + var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); + // TODO: We need to figure out the correct behavior + // for SetDataOptions.None on a dynamic buffer. + // + // For now we always discard as it is a pretty safe default. + // + var discard = _isDynamic && options != SetDataOptions.NoOverwrite; + + MGG.Buffer_SetData(GraphicsDevice.Handle, ref Handle, offsetInBytes, (byte*)dataPtr, dataBytes, discard); + + dataHandle.Free(); + } + + private unsafe void PlatformGraphicsDeviceResetting() + { + if (Handle != null) + { + MGG.Buffer_Destroy(GraphicsDevice.Handle, Handle); + Handle = null; + } } - private void PlatformGraphicsDeviceResetting() + protected override void Dispose(bool disposing) { + PlatformGraphicsDeviceResetting(); + base.Dispose(disposing); } } diff --git a/MonoGame.Framework/Platform/Native/VertexElement.Native.cs b/MonoGame.Framework/Platform/Native/VertexElement.Native.cs new file mode 100644 index 00000000000..9af55b44dcb --- /dev/null +++ b/MonoGame.Framework/Platform/Native/VertexElement.Native.cs @@ -0,0 +1,23 @@ +// MonoGame - Copyright (C) MonoGame Foundation, Inc +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using System; +using MonoGame.Interop; + +namespace Microsoft.Xna.Framework.Graphics; + +partial struct VertexElement +{ + internal MGG_InputElement AsInputElement(int vbSlot, int instanceFrequency) + { + var element = new MGG_InputElement(); + + element.VertexBufferSlot = (uint)vbSlot; + element.Format = _format; + element.AlignedByteOffset = (uint)_offset; + element.InstanceDataStepRate = (uint)instanceFrequency; + + return element; + } +} diff --git a/MonoGame.Framework/Platform/Native/VertexInputLayout.Native.cs b/MonoGame.Framework/Platform/Native/VertexInputLayout.Native.cs new file mode 100644 index 00000000000..ef346b96c1a --- /dev/null +++ b/MonoGame.Framework/Platform/Native/VertexInputLayout.Native.cs @@ -0,0 +1,78 @@ +// MonoGame - Copyright (C) MonoGame Foundation, Inc +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using System; +using System.Collections.Generic; +using System.Linq; +using MonoGame.Interop; + + +namespace Microsoft.Xna.Framework.Graphics; + +partial class VertexInputLayout +{ + public void GenerateInputElements(VertexAttribute[] inputs, out MGG_InputElement[] elements, out int[] strides) + { + elements = new MGG_InputElement[inputs.Length]; + strides = new int[Count]; + + var missingShaderInputs = false; + + // So we are looking for element matches between the REQUIRED vertex + // shader inputs and the provided vertex declarations for this draw. + // + // We don't concern ourselves with the same vertex elements bound + // to multiple shader inputs because that is useful behavior. + // + // We also don't worry about unused vertex declaration elements + // as we expect the shader is what drives the rendering. For example + // you may use the same model data for rendering shadows which just + // need a position and rendering lighting which need position and a normal. + + for (int i = 0; i < inputs.Length; i++) + { + var attr = inputs[i]; + + bool found = false; + + for (int j = 0; j < Count; j++) + { + var declaration = VertexDeclarations[j]; + var vertexElements = declaration.InternalVertexElements; + var instanceFrequencies = InstanceFrequencies[j]; + + foreach (var vertexElement in vertexElements) + { + if (vertexElement.VertexElementUsage == attr.usage && + vertexElement.UsageIndex == attr.index) + { + found = true; + elements[i] = vertexElement.AsInputElement(j, instanceFrequencies); + strides[j] = declaration.VertexStride; + break; + } + } + + if (found) + break; + } + + if (!found) + missingShaderInputs = true; + } + + if (missingShaderInputs) + { + // TODO: This should reference the documentation for more information on this issue. + + var message = "An error occurred while preparing to draw.\n\n" + + "The set VertexDeclaration does not provide all the elements " + + "required by the current vertex shader:\n\n\t" + + string.Join(", ", inputs.Select((x) => x.ToShaderSemantic())) + "\n\n" + + "To fix the error change your VertexDeclaration or your Effect."; + + throw new InvalidOperationException(message); + } + } +} diff --git a/MonoGame.Framework/Platform/Native/Video.Native.cs b/MonoGame.Framework/Platform/Native/Video.Native.cs index 05e19a7b850..139a4df7d38 100644 --- a/MonoGame.Framework/Platform/Native/Video.Native.cs +++ b/MonoGame.Framework/Platform/Native/Video.Native.cs @@ -3,13 +3,180 @@ // file 'LICENSE.txt', which is part of this source code package. using System; +using System.IO; +using MonoGame.Interop; +using Microsoft.Xna.Framework.Graphics; + namespace Microsoft.Xna.Framework.Media; public sealed partial class Video : IDisposable { - private void PlatformInitialize() + private unsafe MGM_Video* _video; + private Texture2D[] _frameCache; + private bool _muted = false; + private float _volume = 1.0f; + private bool _looped = false; + + private unsafe void PlatformInitialize() + { + var mediaFilePath = Path.Combine(TitleContainer.Location, FileName); + + // TODO: We should expose the back buffer count so that + // video playback and optimize the number of textures created + // for video frames. + int cachedFrameNum = 2; // Game.Instance.GraphicsDevice.BackBufferCount; + + // TODO: May be worth letting the video return texture + // format, so it can avoid CPU conversions when possible. + + _video = MGM.Video_Create(mediaFilePath, cachedFrameNum, out var width, out var height, out var fps, out var duration); + + Width = width; + Height = height; + Duration = TimeSpan.FromMilliseconds(duration); + FramesPerSecond = fps; + _frameCache = new Texture2D[cachedFrameNum]; + + // Unsupported + VideoSoundtrackType = VideoSoundtrackType.MusicAndDialog; + } + + private unsafe void PlatformDispose(bool disposing) + { + if (_video != null) + { + MGM.Video_Destroy(_video); + _video = null; + } + } + + internal unsafe Texture2D GetTexture() + { + if (_video == null) + return null; + + MGM.Video_GetFrame(_video, out uint frame, out MGG_Texture* handle); + + uint index = frame % (uint)_frameCache.Length; + var texture = _frameCache[index]; + + if (texture == null) + { + // The video player owns the texture handle here. + + _frameCache[index] = texture = new Texture2D( + Game.Instance.GraphicsDevice, + handle, + Width, + Height, + false, + SurfaceFormat.Color, + Texture2D.SurfaceType.Texture, + 1); + } + + return texture; + } + + internal unsafe MediaState State + { + get + { + if (_video == null) + return MediaState.Stopped; + + return MGM.Video_GetState(_video); + } + } + + internal unsafe TimeSpan Position { + get + { + if (_video == null) + return TimeSpan.Zero; + var position = MGM.Video_GetPosition(_video); + return TimeSpan.FromMilliseconds(position); + } + } + + internal unsafe bool IsLooped + { + set + { + _looped = value; + if (_video != null) + MGM.Video_SetLooped(_video, value); + } + + get + { + return _looped; + } + } + + internal unsafe bool IsMuted + { + set + { + if (value) + { + _muted = true; + if (_video != null) + MGM.Video_SetVolume(_video, 0.0f); + } + else + { + _muted = false; + if (_video != null) + MGM.Video_SetVolume(_video, _volume); + } + } + + get + { + return _muted; + } + } + + internal unsafe float Volume + { + set + { + _volume = value; + if (!_muted && _video != null) + MGM.Video_SetVolume(_video, _volume); + } + + get + { + return _volume; + } + } + + internal unsafe void Play() + { + if (_video != null) + MGM.Video_Play(_video); + } + + internal unsafe void Pause() + { + if (_video != null) + MGM.Video_Pause(_video); + } + + internal unsafe void Resume() + { + if (_video != null) + MGM.Video_Resume(_video); + } + + internal unsafe void Stop() + { + if (_video != null) + MGM.Video_Stop(_video); } } diff --git a/MonoGame.Framework/Platform/Native/VideoPlayer.Native.cs b/MonoGame.Framework/Platform/Native/VideoPlayer.Native.cs index dfdfbf82433..019eb5aeb95 100644 --- a/MonoGame.Framework/Platform/Native/VideoPlayer.Native.cs +++ b/MonoGame.Framework/Platform/Native/VideoPlayer.Native.cs @@ -11,56 +11,57 @@ public sealed partial class VideoPlayer : IDisposable { private void PlatformInitialize() { - + // Nothing to do... the Video does the work. } private Texture2D PlatformGetTexture() { - throw new NotImplementedException(); + return _currentVideo.GetTexture(); } private void PlatformGetState(ref MediaState result) { + result = _currentVideo.State; } private void PlatformPause() { - + _currentVideo.Pause(); } private void PlatformResume() { - + _currentVideo.Resume(); } private void PlatformPlay() { - + _currentVideo.Play(); } private void PlatformStop() { - + _currentVideo.Stop(); } private TimeSpan PlatformGetPlayPosition() { - return TimeSpan.Zero; + return _currentVideo.Position; } private void PlatformSetIsLooped() { - + _currentVideo.IsLooped = _isLooped; } private void PlatformSetIsMuted() { - + _currentVideo.IsMuted = _isMuted; } - private TimeSpan PlatformSetVolume() + private void PlatformSetVolume() { - return TimeSpan.Zero; + _currentVideo.Volume = _volume; } private void PlatformDispose(bool disposing) diff --git a/MonoGame.Framework/Platform/Native/WaveBank.Native.cs b/MonoGame.Framework/Platform/Native/WaveBank.Native.cs index 4506ba08761..73ecb181313 100644 --- a/MonoGame.Framework/Platform/Native/WaveBank.Native.cs +++ b/MonoGame.Framework/Platform/Native/WaveBank.Native.cs @@ -2,12 +2,14 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +using System; + namespace Microsoft.Xna.Framework.Audio; partial class WaveBank { private SoundEffectInstance PlatformCreateStream(StreamInfo stream) { - return new SoundEffectInstance(); + throw new NotSupportedException(); } } diff --git a/MonoGame.Framework/Platform/Threading.cs b/MonoGame.Framework/Platform/Threading.cs index 90f2182066d..c3985f51d2a 100644 --- a/MonoGame.Framework/Platform/Threading.cs +++ b/MonoGame.Framework/Platform/Threading.cs @@ -43,7 +43,9 @@ public static void Dequeue() { var item = Queue.Dequeue(); item.Action.Invoke(item.State); - item.ResetEvent.Set(); + + if (item.ResetEvent != null) + item.ResetEvent.Set(); } public struct QueuedAction @@ -149,6 +151,41 @@ internal static void BlockOnUIThread(Action action, TState state #endif } + /// + /// Queues the action to occur on the UI thread and returns immediately. + /// + /// The action to be run on the UI thread + internal static void OnUIThread(Action action) + { + if (action == null) + throw new ArgumentNullException("action"); + + OnUIThread(_metaAction, action); + } + + /// + /// Queues the action to occur on the UI thread and returns immediately. + /// + /// The action to be run on the UI thread + /// The data to pass to . + internal static void OnUIThread(Action action, TState state = default) + { + if (action == null) + throw new ArgumentNullException("action"); + + var queuedAction = new StateActionHelper.QueuedAction + { + Action = action, + State = state + }; + + lock (_queuedActions) + { + StateActionHelper.Queue.Enqueue(queuedAction); + _queuedActions.Add(StateActionHelper.DequeueAction); + } + } + static ManualResetEventSlim RentResetEvent() { lock (_resetEventPool) diff --git a/MonoGame.Framework/Platform/Utilities/AssemblyHelper.cs b/MonoGame.Framework/Platform/Utilities/AssemblyHelper.cs index 3af856364a8..7c6d2234017 100644 --- a/MonoGame.Framework/Platform/Utilities/AssemblyHelper.cs +++ b/MonoGame.Framework/Platform/Utilities/AssemblyHelper.cs @@ -3,6 +3,7 @@ // file 'LICENSE.txt', which is part of this source code package. using System; +using System.IO; using System.Reflection; namespace MonoGame.Framework.Utilities @@ -37,5 +38,29 @@ public static string GetDefaultWindowTitle() return windowTitle; } + + public static byte[] GetDefaultWindowIcon() + { + var entryAssembly = Assembly.GetEntryAssembly(); + + if (entryAssembly != null) + { + using ( + var stream = + entryAssembly.GetManifestResourceStream(entryAssembly.GetName().Name + ".Icon.bmp") ?? + entryAssembly.GetManifestResourceStream("Icon.bmp") ?? + typeof(AssemblyHelper).Assembly.GetManifestResourceStream("MonoGame.bmp")) + { + if (stream != null) + using (var br = new BinaryReader(stream)) + { + var bytes = br.ReadBytes((int)stream.Length); + return bytes; + } + } + } + + return null; + } } } diff --git a/MonoGame.Framework/Platform/Utilities/ReflectionHelpers.Default.cs b/MonoGame.Framework/Platform/Utilities/ReflectionHelpers.Default.cs index 1d383a148b5..0c7dfbe031c 100644 --- a/MonoGame.Framework/Platform/Utilities/ReflectionHelpers.Default.cs +++ b/MonoGame.Framework/Platform/Utilities/ReflectionHelpers.Default.cs @@ -7,9 +7,9 @@ namespace MonoGame.Framework.Utilities { internal static partial class ReflectionHelpers { - /// - /// Generics handler for Marshal.SizeOf - /// + // This helper caches the Marshal.SizeOf result + // as it generates an allocation on each call. + [Obsolete("This should be made private and use FastSizeOf() below instead!")] internal static class SizeOf { static int _sizeOf; @@ -24,13 +24,5 @@ static public int Get() return _sizeOf; } } - - /// - /// Fallback handler for Marshal.SizeOf(type) - /// - internal static int ManagedSizeOf(Type type) - { - return Marshal.SizeOf(type); - } } } diff --git a/MonoGame.Framework/Platform/Utilities/ReflectionHelpers.Legacy.cs b/MonoGame.Framework/Platform/Utilities/ReflectionHelpers.Legacy.cs index 2e6c5c63f75..f4755f7d6c6 100644 --- a/MonoGame.Framework/Platform/Utilities/ReflectionHelpers.Legacy.cs +++ b/MonoGame.Framework/Platform/Utilities/ReflectionHelpers.Legacy.cs @@ -7,9 +7,9 @@ namespace MonoGame.Framework.Utilities { internal static partial class ReflectionHelpers { - /// - /// Generics handler for Marshal.SizeOf - /// + // This helper caches the Marshal.SizeOf result + // as it generates an allocation on each call. + [Obsolete("This should be made private and use FastSizeOf() below instead!")] internal static class SizeOf { static int _sizeOf; @@ -25,13 +25,5 @@ static public int Get() return _sizeOf; } } - - /// - /// Fallback handler for Marshal.SizeOf(type) - /// - internal static int ManagedSizeOf(Type type) - { - return Marshal.SizeOf(type); - } } } diff --git a/MonoGame.Framework/Platform/iOS/iOSGameWindow.cs b/MonoGame.Framework/Platform/iOS/iOSGameWindow.cs index 1d856c47e50..bd204df7776 100644 --- a/MonoGame.Framework/Platform/iOS/iOSGameWindow.cs +++ b/MonoGame.Framework/Platform/iOS/iOSGameWindow.cs @@ -23,9 +23,21 @@ void HandleInterfaceOrientationChanged (object sender, EventArgs e) OnOrientationChanged(); } - #region GameWindow Members + #region GameWindow Members - public override bool AllowUserResizing { + public override Point Position + { + get + { + return Point.Zero; + } + + set + { + } + } + + public override bool AllowUserResizing { get { return false; } set { /* Do nothing. */ } } @@ -120,4 +132,4 @@ protected override void SetTitle (string title) #endregion GameWindow Members } -} \ No newline at end of file +} diff --git a/MonoGame.Framework/Utilities/MonoGamePlatform.cs b/MonoGame.Framework/Utilities/MonoGamePlatform.cs index 9a8038abbfa..1d5dc8d746f 100644 --- a/MonoGame.Framework/Utilities/MonoGamePlatform.cs +++ b/MonoGame.Framework/Utilities/MonoGamePlatform.cs @@ -57,6 +57,11 @@ public enum MonoGamePlatform /// /// MonoGame Nintendo Switch platform. /// - NintendoSwitch + NintendoSwitch, + + /// + /// All desktop versions using Vulkan. + /// + DesktopVK, } } diff --git a/MonoGame.Framework/Utilities/ReflectionHelpers.cs b/MonoGame.Framework/Utilities/ReflectionHelpers.cs index 89fcdd53853..a7bd2e84e4f 100644 --- a/MonoGame.Framework/Utilities/ReflectionHelpers.cs +++ b/MonoGame.Framework/Utilities/ReflectionHelpers.cs @@ -4,6 +4,7 @@ using System; using System.Reflection; +using System.Runtime.InteropServices; namespace MonoGame.Framework.Utilities { @@ -174,5 +175,20 @@ public static bool IsAssignableFromType(Type type, Type objectType) #endif return false; } + + // Returns the cached size of the unmanaged type in bytes. + public static int FastSizeOf() + { + return SizeOf.Get(); + } + + /// + /// Fallback handler for Marshal.SizeOf(type) + /// + internal static int ManagedSizeOf(Type type) + { + return Marshal.SizeOf(type); + } + } } diff --git a/Tests/Assets/Effects/Bevels.fx b/Tests/Assets/Effects/Bevels.fx index 30c0fa6e31b..763a69204d2 100644 --- a/Tests/Assets/Effects/Bevels.fx +++ b/Tests/Assets/Effects/Bevels.fx @@ -4,15 +4,16 @@ #include "include.fxh" -sampler s0; +DECLARE_TEXTURE(s, 0); float4 PixelShaderFunction( float4 inPosition : SV_Position, float4 inColor : COLOR0, - float2 coords : TEXCOORD0 ) : COLOR0 + float2 coords : TEXCOORD0) : SV_TARGET0 { - float4 color = tex2D(s0, coords); - color -= tex2D(s0, coords - 0.002) * 2.5f; - color += tex2D(s0, coords + 0.002) * 2.5f; + float4 color = SAMPLE_TEXTURE(s, coords); + + color -= SAMPLE_TEXTURE(s, coords - 0.002) * 2.5f; + color += SAMPLE_TEXTURE(s, coords + 0.002) * 2.5f; return color; } @@ -23,4 +24,4 @@ technique Technique1 { PixelShader = compile PS_PROFILE PixelShaderFunction(); } -} \ No newline at end of file +} diff --git a/Tests/Assets/Effects/BlackOut.fx b/Tests/Assets/Effects/BlackOut.fx index 13785454024..6486c60b766 100644 --- a/Tests/Assets/Effects/BlackOut.fx +++ b/Tests/Assets/Effects/BlackOut.fx @@ -4,13 +4,13 @@ #include "include.fxh" -sampler s0; +DECLARE_TEXTURE(s, 0); float4 PixelShaderFunction( float4 inPosition : SV_Position, float4 inColor : COLOR0, - float2 coords : TEXCOORD0 ) : COLOR0 + float2 coords : TEXCOORD0 ) : SV_TARGET0 { - float4 color = tex2D(s0, coords); + float4 color = SAMPLE_TEXTURE(s, coords); color.rgb = 0; return color; @@ -22,4 +22,4 @@ technique Technique1 { PixelShader = compile PS_PROFILE PixelShaderFunction(); } -} \ No newline at end of file +} diff --git a/Tests/Assets/Effects/ColorFlip.fx b/Tests/Assets/Effects/ColorFlip.fx index 1bb6acba032..9a1021a0f3d 100644 --- a/Tests/Assets/Effects/ColorFlip.fx +++ b/Tests/Assets/Effects/ColorFlip.fx @@ -4,13 +4,13 @@ #include "include.fxh" -sampler s0; +DECLARE_TEXTURE(s, 0); float4 PixelShaderFunction( float4 inPosition : SV_Position, float4 inColor : COLOR0, - float2 coords : TEXCOORD0 ) : COLOR0 + float2 coords : TEXCOORD0 ) : SV_TARGET0 { - float4 color = tex2D(s0, coords); + float4 color = SAMPLE_TEXTURE(s, coords); color.rgb = color.bgr; return color; @@ -22,4 +22,4 @@ technique Technique1 { PixelShader = compile PS_PROFILE PixelShaderFunction(); } -} \ No newline at end of file +} diff --git a/Tests/Assets/Effects/CustomSpriteBatchEffect.fx b/Tests/Assets/Effects/CustomSpriteBatchEffect.fx index f38d32a99cd..bbe85a2e9b3 100644 --- a/Tests/Assets/Effects/CustomSpriteBatchEffect.fx +++ b/Tests/Assets/Effects/CustomSpriteBatchEffect.fx @@ -4,22 +4,12 @@ #include "include.fxh" -Texture2D SourceTexture; -Texture2D OtherTexture; +DECLARE_TEXTURE(SourceTexture, 0); +DECLARE_TEXTURE(OtherTexture, 1); -sampler2D SourceSampler = sampler_state +float4 PS_Main(float2 uv : TEXCOORD0) : SV_TARGET0 { - Texture = (SourceTexture); -}; - -sampler2D OtherSampler = sampler_state -{ - Texture = (OtherTexture); -}; - -float4 PS_Main(float2 uv : TEXCOORD0) : COLOR0 -{ - return tex2D(SourceSampler, uv) + tex2D(OtherSampler, uv); + return SAMPLE_TEXTURE(SourceTexture, uv) + SAMPLE_TEXTURE(OtherTexture, uv); } technique @@ -28,4 +18,4 @@ technique { PixelShader = compile PS_PROFILE PS_Main(); } -} \ No newline at end of file +} diff --git a/Tests/Assets/Effects/CustomSpriteBatchEffectComparisonSampler.fx b/Tests/Assets/Effects/CustomSpriteBatchEffectComparisonSampler.fx index dd033f3427b..a3d9543c5dc 100644 --- a/Tests/Assets/Effects/CustomSpriteBatchEffectComparisonSampler.fx +++ b/Tests/Assets/Effects/CustomSpriteBatchEffectComparisonSampler.fx @@ -2,9 +2,11 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. -Texture2D SourceTexture; +#include "include.fxh" -SamplerComparisonState SourceSampler; +Texture2D SourceTexture : register(t0); + +SamplerComparisonState SourceSampler : register(s0); struct VSOutput { @@ -13,24 +15,16 @@ struct VSOutput float2 uv : TEXCOORD0; }; -float4 PS_Main(VSOutput input) : COLOR0 +float4 PS_Main(VSOutput input) : SV_TARGET0 { float comparisonResult = SourceTexture.SampleCmpLevelZero(SourceSampler, input.uv, 0.5f); return float4(comparisonResult, 0, 0, 1); } -#if SM4 -#define PS_PROFILE ps_4_0 -#define VS_PROFILE vs_4_0 -#else -#define PS_PROFILE ps_3_0 -#define VS_PROFILE vs_3_0 -#endif - technique { pass { PixelShader = compile PS_PROFILE PS_Main(); } -} \ No newline at end of file +} diff --git a/Tests/Assets/Effects/DefinesTest.fx b/Tests/Assets/Effects/DefinesTest.fx index 720e1cecf63..d292266eca4 100644 --- a/Tests/Assets/Effects/DefinesTest.fx +++ b/Tests/Assets/Effects/DefinesTest.fx @@ -9,7 +9,7 @@ float4 VS_Main(float4 position : POSITION0) : SV_Position0 return float4(1, 2, 3, 4); } -float4 PS_Main(float4 position : SV_Position) : COLOR0 +float4 PS_Main(float4 position : SV_Position) : SV_TARGET0 { return 1; } diff --git a/Tests/Assets/Effects/Grayscale.fx b/Tests/Assets/Effects/Grayscale.fx index e2e78161c1a..0a927604ce2 100644 --- a/Tests/Assets/Effects/Grayscale.fx +++ b/Tests/Assets/Effects/Grayscale.fx @@ -4,13 +4,14 @@ #include "include.fxh" -sampler s0; +DECLARE_TEXTURE(s, 0); float4 PixelShaderFunction( float4 inPosition : SV_Position, float4 inColor : COLOR0, - float2 coords : TEXCOORD0 ) : COLOR0 + float2 coords : TEXCOORD0 ) : SV_TARGET0 { - float4 color = tex2D(s0, coords); + float4 color = SAMPLE_TEXTURE(s, coords); + color.rgb = color.r; return color; @@ -22,4 +23,4 @@ technique Technique1 { PixelShader = compile PS_PROFILE PixelShaderFunction(); } -} \ No newline at end of file +} diff --git a/Tests/Assets/Effects/HighContrast.fx b/Tests/Assets/Effects/HighContrast.fx index c5b07981a7b..cadeab1baef 100644 --- a/Tests/Assets/Effects/HighContrast.fx +++ b/Tests/Assets/Effects/HighContrast.fx @@ -4,13 +4,13 @@ #include "include.fxh" -sampler s0; +DECLARE_TEXTURE(s, 0); float4 PixelShaderFunction( float4 inPosition : SV_Position, float4 inColor : COLOR0, - float2 coords : TEXCOORD0 ) : COLOR0 + float2 coords : TEXCOORD0 ) : SV_TARGET0 { - float4 color = tex2D(s0, coords); + float4 color = SAMPLE_TEXTURE(s, coords); if (color.r > .65) color.r = 1; else if (color.r < .35) color.r = 0; @@ -24,4 +24,4 @@ technique Technique1 { PixelShader = compile PS_PROFILE PixelShaderFunction(); } -} \ No newline at end of file +} diff --git a/Tests/Assets/Effects/Include.fxh b/Tests/Assets/Effects/Include.fxh index 7374c6742ff..6d88f64d698 100644 --- a/Tests/Assets/Effects/Include.fxh +++ b/Tests/Assets/Effects/Include.fxh @@ -2,14 +2,53 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. -#if SM4 +#if SM6 + +#define PS_PROFILE ps_6_0 +#define VS_PROFILE vs_6_0 +#define SV_TARGET0 SV_Target0 + +#define DECLARE_TEXTURE(Name, index) \ + Texture2D Name : register(t##index); \ + sampler Name##Sampler : register(s##index) + +#define DECLARE_CUBEMAP(Name, index) \ + TextureCube Name : register(t##index); \ + sampler Name##Sampler : register(s##index) + +#define SAMPLE_TEXTURE(Name, texCoord) Name.Sample(Name##Sampler, texCoord) +#define SAMPLE_CUBEMAP(Name, texCoord) Name.Sample(Name##Sampler, texCoord) + +#elif SM4 #define PS_PROFILE ps_4_0_level_9_1 #define VS_PROFILE vs_4_0_level_9_1 +#define SV_TARGET0 COLOR0 + +#define DECLARE_TEXTURE(Name, index) \ + Texture2D Name : register(t##index); \ + sampler Name##Sampler : register(s##index) + +#define DECLARE_CUBEMAP(Name, index) \ + TextureCube Name : register(t##index); \ + sampler Name##Sampler : register(s##index) + +#define SAMPLE_TEXTURE(Name, texCoord) Name.Sample(Name##Sampler, texCoord) +#define SAMPLE_CUBEMAP(Name, texCoord) Name.Sample(Name##Sampler, texCoord) #else #define PS_PROFILE ps_2_0 #define VS_PROFILE vs_2_0 +#define SV_TARGET0 COLOR0 + +#define DECLARE_TEXTURE(Name, index) \ + sampler2D Name : register(s##index); + +#define DECLARE_CUBEMAP(Name, index) \ + samplerCUBE Name : register(s##index); + +#define SAMPLE_TEXTURE(Name, texCoord) tex2D(Name, texCoord) +#define SAMPLE_CUBEMAP(Name, texCoord) texCUBE(Name, texCoord) -#endif \ No newline at end of file +#endif diff --git a/Tests/Assets/Effects/Instancing.fx b/Tests/Assets/Effects/Instancing.fx index 0a3cdde6ce7..03b7870d491 100644 --- a/Tests/Assets/Effects/Instancing.fx +++ b/Tests/Assets/Effects/Instancing.fx @@ -2,6 +2,8 @@ // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. +#include "include.fxh" + float4x4 View; float4x4 Projection; @@ -36,19 +38,11 @@ VSOutput VS(VSInput input, float4x4 worldTransposed : BLENDWEIGHT) return output; } -float4 PS(PSInput input) : COLOR0 +float4 PS(PSInput input) : SV_TARGET0 { return float4(input.TexCoord.xy, 0, 1); } -#if SM4 -#define PS_PROFILE ps_4_0 -#define VS_PROFILE vs_4_0 -#else -#define PS_PROFILE ps_3_0 -#define VS_PROFILE vs_3_0 -#endif - technique { pass diff --git a/Tests/Assets/Effects/Invert.fx b/Tests/Assets/Effects/Invert.fx index 00a6e58fa2f..f2a37b4e72e 100644 --- a/Tests/Assets/Effects/Invert.fx +++ b/Tests/Assets/Effects/Invert.fx @@ -4,13 +4,13 @@ #include "include.fxh" -sampler s0; +DECLARE_TEXTURE(s, 0); float4 PixelShaderFunction( float4 inPosition : SV_Position, float4 inColor : COLOR0, - float2 coords : TEXCOORD0 ) : COLOR0 + float2 coords : TEXCOORD0 ) : SV_TARGET0 { - float4 color = tex2D(s0, coords); + float4 color = SAMPLE_TEXTURE(s, coords); if (!any(color)) return color; @@ -25,4 +25,4 @@ technique Technique1 { PixelShader = compile PS_PROFILE PixelShaderFunction(); } -} \ No newline at end of file +} diff --git a/Tests/Assets/Effects/NoEffect.fx b/Tests/Assets/Effects/NoEffect.fx index 4df800b390f..7a7e7ec3ca4 100644 --- a/Tests/Assets/Effects/NoEffect.fx +++ b/Tests/Assets/Effects/NoEffect.fx @@ -4,13 +4,13 @@ #include "include.fxh" -sampler s0; +DECLARE_TEXTURE(s, 0); float4 PixelShaderFunction( float4 inPosition : SV_Position, float4 inColor : COLOR0, - float2 coords : TEXCOORD0 ) : COLOR0 + float2 coords : TEXCOORD0 ) : SV_TARGET0 { - float4 color = tex2D(s0, coords); + float4 color = SAMPLE_TEXTURE(s, coords); return color; } @@ -20,4 +20,4 @@ technique Technique1 { PixelShader = compile PS_PROFILE PixelShaderFunction(); } -} \ No newline at end of file +} diff --git a/Tests/Assets/Effects/ParserTest.fx b/Tests/Assets/Effects/ParserTest.fx index 3c29e348d1a..3a5dc94cf35 100644 --- a/Tests/Assets/Effects/ParserTest.fx +++ b/Tests/Assets/Effects/ParserTest.fx @@ -27,7 +27,7 @@ float4 VS_Main(float4 position : POSITION0) : SV_Position0 return float4(1, 2, 3, 4); } -float4 PS_Main(float4 position : SV_Position) : COLOR0 +float4 PS_Main(float4 position : SV_Position) : SV_TARGET0 { return 1; } diff --git a/Tests/Assets/Effects/PreprocessorTest.fx b/Tests/Assets/Effects/PreprocessorTest.fx index 312e479fb41..c1128c48845 100644 --- a/Tests/Assets/Effects/PreprocessorTest.fx +++ b/Tests/Assets/Effects/PreprocessorTest.fx @@ -33,7 +33,7 @@ float4 VS_Main(float4 position : POSITION0) : SV_Position0 return float4(1, 2, 3, 4); } -float4 PS_Main(float4 position : SV_Position) : COLOR0 +float4 PS_Main(float4 position : SV_Position) : SV_TARGET0 { return 1; } @@ -45,4 +45,4 @@ technique VertexShader = compile VS_PROFILE VS_Main(); PixelShader = compile PS_PROFILE PS_Main(); } -} \ No newline at end of file +} diff --git a/Tests/Assets/Effects/RainbowH.fx b/Tests/Assets/Effects/RainbowH.fx index 43511d77733..970e107d704 100644 --- a/Tests/Assets/Effects/RainbowH.fx +++ b/Tests/Assets/Effects/RainbowH.fx @@ -4,23 +4,23 @@ #include "include.fxh" -sampler s0; +DECLARE_TEXTURE(s, 0); -float4 red = float4(1,0,0,1); -float4 orange = float4(1,.5,0,1); -float4 yellow = float4(1,1,0,1); -float4 green = float4(0,1,0,1); -float4 blue = float4(0,0,1,1); -float4 indigo = float4(.3,0,.8,1); -float4 violet = float4(1,.8,1,1); +static float4 red = float4(1,0,0,1); +static float4 orange = float4(1, .5, 0, 1); +static float4 yellow = float4(1, 1, 0, 1); +static float4 green = float4(0, 1, 0, 1); +static float4 blue = float4(0, 0, 1, 1); +static float4 indigo = float4(.3, 0, .8, 1); +static float4 violet = float4(1, .8, 1, 1); -float step = 1.0/7; +static float step = 1.0 / 7; float4 PixelShaderFunction( float4 inPosition : SV_Position, float4 inColor : COLOR0, - float2 coords : TEXCOORD0 ) : COLOR0 + float2 coords : TEXCOORD0 ) : SV_TARGET0 { - float4 color = tex2D(s0, coords); + float4 color = SAMPLE_TEXTURE(s, coords); if (!any(color)) return color; @@ -41,4 +41,4 @@ technique Technique1 { PixelShader = compile PS_PROFILE PixelShaderFunction(); } -} \ No newline at end of file +} diff --git a/Tests/Assets/Effects/TextureArrayEffect.fx b/Tests/Assets/Effects/TextureArrayEffect.fx index 816e2f10b86..03da318acb6 100644 --- a/Tests/Assets/Effects/TextureArrayEffect.fx +++ b/Tests/Assets/Effects/TextureArrayEffect.fx @@ -27,7 +27,7 @@ VSOutput VS_Main(uint VertexID : SV_VertexID) return output; } -float4 PS_Main(PSInput input) : COLOR0 +float4 PS_Main(PSInput input) : SV_TARGET0 { return Texture.Sample(TextureSampler, float3(input.TexCoord, (uint) input.PositionSS.x % 4)); } @@ -39,4 +39,4 @@ technique VertexShader = compile vs_4_0 VS_Main(); PixelShader = compile ps_4_0 PS_Main(); } -} \ No newline at end of file +} diff --git a/Tests/Assets/Effects/VertexTextureEffect.fx b/Tests/Assets/Effects/VertexTextureEffect.fx index 28bcd13b3d7..72af9b64976 100644 --- a/Tests/Assets/Effects/VertexTextureEffect.fx +++ b/Tests/Assets/Effects/VertexTextureEffect.fx @@ -33,7 +33,7 @@ VSOutput VS_Main(float2 xy : POSITION) return output; } -float4 PS_Main(VSOutput input) : COLOR0 +float4 PS_Main(VSOutput input) : SV_TARGET0 { return input.Color; } @@ -57,4 +57,4 @@ technique VertexShader = compile VS_PROFILE VS_Main(); PixelShader = compile PS_PROFILE PS_Main(); } -} \ No newline at end of file +} diff --git a/Tests/Assets/Effects/Vulkan.mgcb b/Tests/Assets/Effects/Vulkan.mgcb new file mode 100644 index 00000000000..f6233fe9ff1 --- /dev/null +++ b/Tests/Assets/Effects/Vulkan.mgcb @@ -0,0 +1,94 @@ + +#----------------------------- Global Properties ----------------------------# + +/outputDir:Vulkan +/intermediateDir:obj +/platform:DesktopVK +/config: +/profile:Reach +/compress:False + +#-------------------------------- References --------------------------------# + + +#---------------------------------- Content ---------------------------------# + +#begin Bevels.fx +/importer:EffectImporter +/processor:EffectProcessor +/processorParam:DebugMode=Auto +/build:Bevels.fx + +#begin BlackOut.fx +/importer:EffectImporter +/processor:EffectProcessor +/processorParam:DebugMode=Auto +/build:BlackOut.fx + +#begin ColorFlip.fx +/importer:EffectImporter +/processor:EffectProcessor +/processorParam:DebugMode=Auto +/build:ColorFlip.fx + +#begin Grayscale.fx +/importer:EffectImporter +/processor:EffectProcessor +/processorParam:DebugMode=Auto +/build:Grayscale.fx + +#begin HighContrast.fx +/importer:EffectImporter +/processor:EffectProcessor +/processorParam:DebugMode=Auto +/build:HighContrast.fx + +#begin Invert.fx +/importer:EffectImporter +/processor:EffectProcessor +/processorParam:DebugMode=Auto +/build:Invert.fx + +#begin NoEffect.fx +/importer:EffectImporter +/processor:EffectProcessor +/processorParam:DebugMode=Auto +/build:NoEffect.fx + +#begin RainbowH.fx +/importer:EffectImporter +/processor:EffectProcessor +/processorParam:DebugMode=Auto +/build:RainbowH.fx + +#begin Instancing.fx +/importer:EffectImporter +/processor:EffectProcessor +/processorParam:DebugMode=Auto +/build:Instancing.fx + +#begin VertexTextureEffect.fx +/importer:EffectImporter +/processor:EffectProcessor +/processorParam:DebugMode=Auto +/build:VertexTextureEffect.fx + +#begin CustomSpriteBatchEffect.fx +/importer:EffectImporter +/processor:EffectProcessor +/processorParam:DebugMode=Auto +/build:CustomSpriteBatchEffect.fx + +#begin CustomSpriteBatchEffectComparisonSampler.fx +/importer:EffectImporter +/processor:EffectProcessor +/processorParam:DebugMode=Auto +/processorParam:Defines= +/build:CustomSpriteBatchEffectComparisonSampler.fx + +#begin TextureArrayEffect.fx +/importer:EffectImporter +/processor:EffectProcessor +/processorParam:DebugMode=Auto +/build:TextureArrayEffect.fx + diff --git a/Tests/Assets/Effects/Vulkan/Bevels.xnb b/Tests/Assets/Effects/Vulkan/Bevels.xnb new file mode 100644 index 00000000000..669f3c729f1 Binary files /dev/null and b/Tests/Assets/Effects/Vulkan/Bevels.xnb differ diff --git a/Tests/Assets/Effects/Vulkan/BlackOut.xnb b/Tests/Assets/Effects/Vulkan/BlackOut.xnb new file mode 100644 index 00000000000..5007ef01a73 Binary files /dev/null and b/Tests/Assets/Effects/Vulkan/BlackOut.xnb differ diff --git a/Tests/Assets/Effects/Vulkan/ColorFlip.xnb b/Tests/Assets/Effects/Vulkan/ColorFlip.xnb new file mode 100644 index 00000000000..ae60825f232 Binary files /dev/null and b/Tests/Assets/Effects/Vulkan/ColorFlip.xnb differ diff --git a/Tests/Assets/Effects/Vulkan/CustomSpriteBatchEffect.xnb b/Tests/Assets/Effects/Vulkan/CustomSpriteBatchEffect.xnb new file mode 100644 index 00000000000..e65131ad526 Binary files /dev/null and b/Tests/Assets/Effects/Vulkan/CustomSpriteBatchEffect.xnb differ diff --git a/Tests/Assets/Effects/Vulkan/Grayscale.xnb b/Tests/Assets/Effects/Vulkan/Grayscale.xnb new file mode 100644 index 00000000000..be3d0506bf3 Binary files /dev/null and b/Tests/Assets/Effects/Vulkan/Grayscale.xnb differ diff --git a/Tests/Assets/Effects/Vulkan/HighContrast.xnb b/Tests/Assets/Effects/Vulkan/HighContrast.xnb new file mode 100644 index 00000000000..903be4b396f Binary files /dev/null and b/Tests/Assets/Effects/Vulkan/HighContrast.xnb differ diff --git a/Tests/Assets/Effects/Vulkan/Invert.xnb b/Tests/Assets/Effects/Vulkan/Invert.xnb new file mode 100644 index 00000000000..5368b3861ff Binary files /dev/null and b/Tests/Assets/Effects/Vulkan/Invert.xnb differ diff --git a/Tests/Assets/Effects/Vulkan/NoEffect.xnb b/Tests/Assets/Effects/Vulkan/NoEffect.xnb new file mode 100644 index 00000000000..f2434fe6a98 Binary files /dev/null and b/Tests/Assets/Effects/Vulkan/NoEffect.xnb differ diff --git a/Tests/Assets/Effects/Vulkan/RainbowH.xnb b/Tests/Assets/Effects/Vulkan/RainbowH.xnb new file mode 100644 index 00000000000..149b998bb71 Binary files /dev/null and b/Tests/Assets/Effects/Vulkan/RainbowH.xnb differ diff --git a/Tests/Framework/Graphics/GraphicsDeviceTest.cs b/Tests/Framework/Graphics/GraphicsDeviceTest.cs index 5ad4b176e19..dc85ecb1806 100644 --- a/Tests/Framework/Graphics/GraphicsDeviceTest.cs +++ b/Tests/Framework/Graphics/GraphicsDeviceTest.cs @@ -635,6 +635,11 @@ public void VertexTexturesGetSet() #endif foreach (var format in Enum.GetValues(typeof(SurfaceFormat)).Cast()) { +#if !MOBILE + // Skip the mobile formats on non-mobile platforms. + if (format > SurfaceFormat.Dxt5SRgb) + continue; +#endif var texture = new Texture2D(gd, 4, 4, false, format); if (supportedVertexTextureFormats.Contains(format)) diff --git a/Tests/Framework/MockWindow.cs b/Tests/Framework/MockWindow.cs index 7c3a155adbd..463e093a25f 100644 --- a/Tests/Framework/MockWindow.cs +++ b/Tests/Framework/MockWindow.cs @@ -17,10 +17,7 @@ public override Rectangle ClientBounds get { throw new NotImplementedException(); } } - // TODO: Make this common so that all platforms have it! -#if WINDOWS || DESKTOPGL public override Point Position { get; set; } -#endif public override DisplayOrientation CurrentOrientation { diff --git a/Tests/MonoGame.Tests.WindowsVK.csproj b/Tests/MonoGame.Tests.WindowsVK.csproj new file mode 100644 index 00000000000..cc15189d6d1 --- /dev/null +++ b/Tests/MonoGame.Tests.WindowsVK.csproj @@ -0,0 +1,65 @@ + + + + Exe + net8.0-windows + Major + false + true + false + WINDOWS;VULKAN;DESKTOP + + + + + + + + + + + + + + + + + + + + + + + + Assets\Effects\Stock\%(Filename)%(Extension) + PreserveNewest + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + + + + + + + diff --git a/Tests/Properties/launchSettings.json b/Tests/Properties/launchSettings.json new file mode 100644 index 00000000000..3476ef87c00 --- /dev/null +++ b/Tests/Properties/launchSettings.json @@ -0,0 +1,8 @@ +{ + "profiles": { + "MonoGame.Tests.WindowsVK": { + "commandName": "Project", + "nativeDebugging": true + } + } +} \ No newline at end of file diff --git a/Tests/Runner/Utility.cs b/Tests/Runner/Utility.cs index f290fb0b22d..699988c273d 100644 --- a/Tests/Runner/Utility.cs +++ b/Tests/Runner/Utility.cs @@ -355,6 +355,8 @@ public static string CompiledEffect (params string [] pathParts) type = "DirectX"; #elif DESKTOPGL type = "OpenGL"; +#elif VULKAN + type = "Vulkan"; #else throw new Exception("Make sure the effect path is set up correctly for this platform!"); #endif diff --git a/Tools/MonoGame.Effect.Compiler/Effect/ConstantBufferData.Vulkan.cs b/Tools/MonoGame.Effect.Compiler/Effect/ConstantBufferData.Vulkan.cs new file mode 100644 index 00000000000..f0c1026e993 --- /dev/null +++ b/Tools/MonoGame.Effect.Compiler/Effect/ConstantBufferData.Vulkan.cs @@ -0,0 +1,121 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using System; +using System.Linq; + +namespace MonoGame.Effect +{ + internal partial class ConstantBufferData + { + static EffectObject.D3DXPARAMETER_TYPE ToParamType(string dataType) + { + switch(dataType) + { + case "float": + return EffectObject.D3DXPARAMETER_TYPE.FLOAT; + case "int": + return EffectObject.D3DXPARAMETER_TYPE.INT; + case "bool": + return EffectObject.D3DXPARAMETER_TYPE.BOOL; + default: + throw new Exception("Unknown data type: " + dataType); + }; + } + + public void AddParameter(string name, string dataType, int sizeOfArray, int byteOffset) + { + // Has this parameter already been added? + var found = Parameters.FirstOrDefault(p => p.name == name); + if (found != null) + return; + + // Create the new parameter. + var param = new EffectObject.d3dx_parameter(); + param.name = name; + param.semantic = string.Empty; + param.bufferOffset = byteOffset; + + if (dataType.StartsWith("%mat")) + { + param.columns = (uint)char.GetNumericValue(dataType[4]); + param.rows = (uint)char.GetNumericValue(dataType[6]); + param.type = ToParamType(dataType.Substring(7)); + } + else if (dataType.StartsWith("%v")) + { + param.rows = 1; + param.columns = (uint)char.GetNumericValue(dataType[2]); + param.type = ToParamType(dataType.Substring(3)); + } + else if (dataType.StartsWith("%_arr_")) + { + // TODO: Support arrays.... %_arr_mat4v3float_uint_72 + param.rows = 1; + param.columns = 1; + param.type = EffectObject.D3DXPARAMETER_TYPE.FLOAT; + } + else + { + param.rows = 1; + param.columns = 1; + param.type = ToParamType(dataType.Substring(1)); + } + + if (param.rows > 1) + param.class_ = EffectObject.D3DXPARAMETER_CLASS.MATRIX_COLUMNS; + else if (param.columns > 1) + param.class_ = EffectObject.D3DXPARAMETER_CLASS.VECTOR; + else + param.class_ = EffectObject.D3DXPARAMETER_CLASS.SCALAR; + + var byteSize = param.rows * param.columns * 4; + + if (sizeOfArray > 0) + { + param.element_count = (uint)sizeOfArray; + param.member_handles = new EffectObject.d3dx_parameter[param.element_count]; + for (var i = 0; i < param.element_count; i++) + { + var mparam = new EffectObject.d3dx_parameter(); + + mparam.name = string.Empty; + mparam.semantic = string.Empty; + mparam.type = param.type; + mparam.class_ = param.class_; + mparam.rows = param.rows; + mparam.columns = param.columns; + mparam.data = new byte[byteSize]; + + param.member_handles[i] = mparam; + } + } + + var data = new byte[byteSize]; + + // TODO: Default value? + + param.data = data; + + // Add the new parameter and resort by the + // offset for some consistent results. + Parameters.Add(param); + Parameters = Parameters.OrderBy(e => e.bufferOffset).ToList(); + + // Recreate the parameter offsets and calculate the size. + Size = 0; + ParameterOffset.Clear(); + foreach (var p in Parameters) + { + ParameterOffset.Add(p.bufferOffset); + + var esize = p.rows * p.columns * 4; + if (p.element_count > 0) + esize = (esize + (16 - (esize % 16))) * p.element_count; + + Size = p.bufferOffset + (int)esize; + } + } + } +} diff --git a/Tools/MonoGame.Effect.Compiler/Effect/ShaderProfile.Vulkan.cs b/Tools/MonoGame.Effect.Compiler/Effect/ShaderProfile.Vulkan.cs new file mode 100644 index 00000000000..6668a01ef44 --- /dev/null +++ b/Tools/MonoGame.Effect.Compiler/Effect/ShaderProfile.Vulkan.cs @@ -0,0 +1,636 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using Microsoft.Xna.Framework.Content.Pipeline; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using MonoGame.Effect.TPGParser; +using Microsoft.Xna.Framework.Graphics; + +namespace MonoGame.Effect +{ + class VulkanShaderProfile : ShaderProfile + { + public VulkanShaderProfile() + : base("Vulkan", 80) + { + } + + internal override void AddMacros(Dictionary macros) + { + macros.Add("SM6", "1"); + macros.Add("VULKAN", "1"); + } + + internal override void ValidateShaderModels(PassInfo pass) + { + if (!string.IsNullOrEmpty(pass.vsFunction)) + { + if (pass.vsModel != "vs_6_0") + throw new Exception(String.Format("Invalid Vulkan vertex profile '{0}'! Requires vs_6_0.", pass.vsModel)); + } + + if (!string.IsNullOrEmpty(pass.psFunction)) + { + if (pass.psModel != "ps_6_0") + throw new Exception(String.Format("Invalid Vulkan pixel profile '{0}'! Requires ps_6_0.", pass.psModel)); + } + } + + class VkStructMember + { + public string name; + public int offset; + public string type; + }; + + class VkStruct + { + public string name; + public readonly Dictionary members = new Dictionary(); + }; + + enum VkDescriptorType : uint + { + SAMPLER = 0, + COMBINED_IMAGE_SAMPLER = 1, + SAMPLED_IMAGE = 2, + STORAGE_IMAGE = 3, + UNIFORM_TEXEL_BUFFER = 4, + STORAGE_TEXEL_BUFFER = 5, + UNIFORM_BUFFER = 6, + STORAGE_BUFFER = 7, + UNIFORM_BUFFER_DYNAMIC = 8, + STORAGE_BUFFER_DYNAMIC = 9, + INPUT_ATTACHMENT = 10, + INLINE_UNIFORM_BLOCK = 1000138000, + ACCELERATION_STRUCTURE_KHR = 1000150000, + ACCELERATION_STRUCTURE_NV = 1000165000, + SAMPLE_WEIGHT_IMAGE_QCOM = 1000440000, + BLOCK_MATCH_IMAGE_QCOM = 1000440001, + MUTABLE_EXT = 1000351000, + INLINE_UNIFORM_BLOCK_EXT = INLINE_UNIFORM_BLOCK, + MUTABLE_VALVE = MUTABLE_EXT, + MAX_ENUM = 0x7FFFFFFF + }; + + [Flags] + enum VkShaderStageFlags : uint + { + VERTEX_BIT = 0x00000001, + TESSELLATION_CONTROL_BIT = 0x00000002, + TESSELLATION_EVALUATION_BIT = 0x00000004, + GEOMETRY_BIT = 0x00000008, + FRAGMENT_BIT = 0x00000010, + COMPUTE_BIT = 0x00000020, + ALL_GRAPHICS = 0x0000001F, + ALL = 0x7FFFFFFF, + RAYGEN_BIT_KHR = 0x00000100, + ANY_HIT_BIT_KHR = 0x00000200, + CLOSEST_HIT_BIT_KHR = 0x00000400, + MISS_BIT_KHR = 0x00000800, + INTERSECTION_BIT_KHR = 0x00001000, + CALLABLE_BIT_KHR = 0x00002000, + TASK_BIT_EXT = 0x00000040, + MESH_BIT_EXT = 0x00000080, + SUBPASS_SHADING_BIT_HUAWEI = 0x00004000, + CLUSTER_CULLING_BIT_HUAWEI = 0x00080000, + RAYGEN_BIT_NV = RAYGEN_BIT_KHR, + ANY_HIT_BIT_NV = ANY_HIT_BIT_KHR, + CLOSEST_HIT_BIT_NV = CLOSEST_HIT_BIT_KHR, + MISS_BIT_NV = MISS_BIT_KHR, + INTERSECTION_BIT_NV = INTERSECTION_BIT_KHR, + CALLABLE_BIT_NV = CALLABLE_BIT_KHR, + TASK_BIT_NV = TASK_BIT_EXT, + MESH_BIT_NV = MESH_BIT_EXT, + FLAG_BITS_MAX_ENUM = 0x7FFFFFFF + }; + + class VkDescriptor + { + public string name; + public VkDescriptorType type; + public int set; + public int binding; + }; + + class VkInput + { + public string name; + public string type; + public int location; + }; + + struct VkDescriptorSetLayoutBinding + { + public uint binding; + public VkDescriptorType descriptorType; + public uint descriptorCount; + public VkShaderStageFlags stageFlags; + public nint pImmutableSamplers; + }; + + internal override ShaderData CreateShader(ShaderResult shaderResult, string shaderFunction, string shaderProfile, bool isVertexShader, EffectObject effect, ref string errorsAndWarnings) + { + const int SlotOffset = 32; + + var outputPath = Path.GetDirectoryName(shaderResult.OutputFilePath); + var sourceFileName = Path.GetFileNameWithoutExtension(shaderResult.FilePath) + "." + shaderFunction; + + // TODO: We have no intermediate folder in 2MGFX for temp stuff + // that isn't content, but could be useful later. So just putting + // them into the output then cleaning it up after. + var intermediateDir = outputPath; + var hlslFile = Path.Combine(intermediateDir, sourceFileName + ".hlsl"); + var glslFile = Path.Combine(intermediateDir, sourceFileName + ".glsl"); + var binFile = Path.Combine(intermediateDir, sourceFileName + ".bin"); + var reflectFile = Path.Combine(intermediateDir, sourceFileName + ".reflect"); + + // Need to keep this for debugging to work. + var dbgFile = Path.Combine(outputPath, sourceFileName + ".dbg"); + + // Disable this if you want to keep these around for testing! + var cleanup = new List(); + cleanup.Add(hlslFile); + cleanup.Add(binFile); + cleanup.Add(dbgFile); + cleanup.Add(reflectFile); + + try + { + if (!Directory.Exists(intermediateDir)) + Directory.CreateDirectory(intermediateDir); + + // Replace the entrypoint name with "main" for simplicity at runtime. + var shaderContent = Regex.Replace(shaderResult.FileContent, @"(?<=\s+)" + shaderFunction + @"(?=\s*[(])", "main"); + + // Write preprocessed hlsl file. + File.WriteAllText(hlslFile, shaderContent); + + // Run HlslCrossCompiler.exe to convert temp.fx to a .glsl + string stdout; + string stderr; + string toolArgs; + int toolResult; + + toolArgs = ""; + toolArgs += "-nologo "; + toolArgs += "-spirv "; + toolArgs += "-fvk-use-dx-layout "; + if (isVertexShader) + { + toolArgs += "-fvk-invert-y "; + toolArgs += "-fvk-use-dx-position-w "; + } + else + { + // Move pixel shaders into the second descriptor + // to avoid overlapping bindings between the vertex + // and pixel stages. + toolArgs += "-auto-binding-space 1 "; + } + + // In SPIR-V the uniform and texture bindings cannot + // overlap. To solve this we shift them all forward by + // a fixed amount here and in the shader layout creation. + if (isVertexShader) + { + toolArgs += $"-fvk-t-shift {SlotOffset} 0 "; + toolArgs += $"-fvk-s-shift {SlotOffset} 0 "; + } + else + { + toolArgs += $"-fvk-t-shift {SlotOffset} 1 "; + toolArgs += $"-fvk-s-shift {SlotOffset} 1 "; + } + + //toolArgs += "-Qstrip_reflect "; + //toolArgs += "-fspv-reflect "; + toolArgs += "-T " + (isVertexShader ? "vs_" : "ps_") + "6_0 "; + toolArgs += "-E main "; + toolArgs += "-Fc \"" + reflectFile + "\" "; + toolArgs += "-Fo \"" + binFile + "\" "; + + if (shaderResult.Debug) + { + toolArgs += "-Zi "; + toolArgs += "-Fd \"" + dbgFile + "\" "; + } + toolArgs += "\"" + hlslFile + "\""; + + toolResult = ExternalTool.Run("dxc", toolArgs, out stdout, out stderr); + errorsAndWarnings += stderr; + + // jcf: this tool doesn't seem to use stderr for output + // but if the return code was not success=0 then treat stdout as stderr + if (toolResult != 0) + { + errorsAndWarnings += string.Format("DXC.exe returned error code '{0}'.\n", toolResult); + errorsAndWarnings += stdout; + throw new ShaderCompilerException(); + } + + // Load up the compiled shader. + var bytecode = File.ReadAllBytes(binFile); + + // First look to see if we already created this same shader. + foreach (var shader in effect.Shaders) + { + if (bytecode.SequenceEqual(shader.Bytecode)) + return shader; + } + + string reflectionData = File.ReadAllText(reflectFile); + + // Keep the debug file if we are creating a new shader + // and debug shaders are enabled. + if (shaderResult.Debug) + { + if (File.Exists(dbgFile)) + shaderResult.AdditionalOutputFiles.Add(dbgFile); + + cleanup.Remove(dbgFile); + } + + // Create a new shader. + var shaderData = new ShaderData(isVertexShader, effect.Shaders.Count, bytecode); + + // Gather all the vulkan reflection info. + var reader = new StringReader(reflectionData); + var names = new Dictionary(); + var structs = new Dictionary(); + var descriptors = new Dictionary(); + var inputs = new Dictionary(); + + while (true) + { + var line = reader.ReadLine(); + if (line == null) + break; + + var data = line.Trim().Split(' '); + + if (data[0] == "OpName") + { + var name = data[2].Trim(new[] { '\"' }); + var id = data[1]; + if (id.StartsWith("%in_var_")) + inputs.Add(id, new VkInput { name = id.Substring(8) }); + else + names.Add(id, name); + } + else if (data[0] == "OpMemberName") + { + var name = data[3].Trim(new[] { '\"' }); + var id = data[1]; + var index = int.Parse(data[2]); + + VkStruct s; + if (!structs.TryGetValue(id, out s)) + { + s = new VkStruct(); + s.name = names[id]; + structs.Add(id, s); + } + + var member = new VkStructMember(); + member.name = name; + s.members.Add(index, member); + } + else if (data[0] == "OpDecorate") + { + if (data[2] == "DescriptorSet") + { + VkDescriptor d; + if (!descriptors.TryGetValue(data[1], out d)) + { + d = new VkDescriptor(); + d.name = data[1]; + d.type = VkDescriptorType.UNIFORM_BUFFER; + descriptors.Add(d.name, d); + } + + d.set = int.Parse(data[3]); + } + else if (data[2] == "Binding") + { + VkDescriptor d; + if (!descriptors.TryGetValue(data[1], out d)) + { + d = new VkDescriptor(); + d.name = data[1]; + d.type = VkDescriptorType.UNIFORM_BUFFER; + descriptors.Add(d.name, d); + } + + d.binding = int.Parse(data[3]); + } + else if (data[1].StartsWith("%in_var_")) + { + inputs[data[1]].location = int.Parse(data[3]); + } + } + else if (data[0] == "OpMemberDecorate") + { + var id = data[1]; + var index = int.Parse(data[2]); + var s = structs[id]; + + if (data[3] == "Offset") + { + var offset = int.Parse(data[4]); + s.members[index].offset = offset; + } + } + else if (data[0].StartsWith("%in_var_")) + { + inputs[data[0]].type = data[3].Substring(12); + } + else if (data[0].StartsWith("%")) + { + if (data[2] == "OpTypeStruct") + { + var id = data[0]; + var s = structs[id]; + + for (int i=3; i < data.Length; i++) + s.members[i - 3].type = data[i]; + } + else if (data[2] == "OpVariable") + { + VkDescriptor d; + if (descriptors.TryGetValue(data[0], out d)) + { + if (data[3].EndsWith("_type_2d_image")) + d.type = VkDescriptorType.SAMPLED_IMAGE; + else if (data[3].EndsWith("_type_sampler")) + d.type = VkDescriptorType.SAMPLER; + } + } + } + } + + var cbuffer = new ConstantBufferData("global"); + + // TODO: Support multiple constant buffers one day! + + // First gather the uniforms. + VkStruct globals; + if (structs.TryGetValue("%type__MG_Globals", out globals)) + { + foreach (var member in globals.members.Values) + cbuffer.AddParameter(member.name, member.type, 0, member.offset); + } + + // Gather the input attributes. + var attributes = new List(); + if (isVertexShader) + { + // Sort by the location. + var sorted = inputs.Values.OrderBy(f=>f.location); + + int offset = 0; + + foreach (var input in sorted) + { + var a = new ShaderData.Attribute(); + + var m = Regex.Match(input.name, @"(\D+)(\d+)?"); + if (m.Groups[2].Success) + a.index = int.Parse(m.Groups[2].Value); + else + a.index = 0; + + if (m.Groups[1].Success) + { + switch (m.Groups[1].Value.ToUpper()) + { + default: + a.usage = VertexElementUsage.TextureCoordinate; + break; + case "POSITION": + a.usage = VertexElementUsage.Position; + break; + case "NORMAL": + a.usage = VertexElementUsage.Normal; + break; + case "TANGENT": + a.usage = VertexElementUsage.Tangent; + break; + case "BINORMAL": + a.usage = VertexElementUsage.Binormal; + break; + case "COLOR": + a.usage = VertexElementUsage.Color; + break; + case "BLENDINDICES": + a.usage = VertexElementUsage.BlendIndices; + break; + case "BLENDWEIGHT": + a.usage = VertexElementUsage.BlendWeight; + break; + case "DEPTH": + a.usage = VertexElementUsage.Depth; + break; + case "FOG": + a.usage = VertexElementUsage.Fog; + break; + case "POINTSIZE": + a.usage = VertexElementUsage.PointSize; + break; + case "TESSELLATEFACTOR": + a.usage = VertexElementUsage.TessellateFactor; + break; + } + } + + int size; + if (input.type.StartsWith("v")) + { + int len = (int)char.GetNumericValue(input.type[1]); + switch (input.type.Substring(2)) + { + case "int": + case "float": + size = len * 4; + break; + default: + errorsAndWarnings += string.Format("Unknown vertex shader input type '{0}'.", input.type); + throw new ShaderCompilerException(); + } + } + else + { + errorsAndWarnings += string.Format("Unknown vertex shader input type '{0}'.", input.type); + throw new ShaderCompilerException(); + } + + offset += size; + + // TODO: These are unused at runtime under the + // new native backends, we will remove them soon. + a.location = 0; + a.name = string.Empty; + + attributes.Add(a); + } + } + + // Now gather the samplers. + var samplers = new List(); + foreach (var d in descriptors.Values) + { + // TODO: This seems like it is maybe backwards + // and i should be looking for samplers for textures? + + if (d.type != VkDescriptorType.SAMPLER) + continue; + + var s = new ShaderData.Sampler(); + s.samplerSlot = d.binding; + s.samplerName = names[d.name]; + + s.type = MojoShader.MOJOSHADER_samplerType.MOJOSHADER_SAMPLER_2D; + //if (data[0] == "SAMPLER3D") + //s.type = MojoShader.MOJOSHADER_samplerType.MOJOSHADER_SAMPLER_VOLUME; + //else if (data[0] == "SAMPLERCUBE") + //s.type = MojoShader.MOJOSHADER_samplerType.MOJOSHADER_SAMPLER_CUBE; + + foreach (var td in descriptors.Values) + { + if (td.binding == s.samplerSlot) + { + s.textureSlot = td.binding - SlotOffset; + s.parameterName = names[td.name]; + break; + } + } + + s.samplerSlot -= SlotOffset; + + // Associate sampler state to the sampler. + SamplerStateInfo state; + if (shaderResult.ShaderInfo.SamplerStates.TryGetValue(s.samplerName, out state)) + { + s.parameterName = s.parameterName ?? state.TextureName; + s.state = state.State; + samplers.Add(s); + continue; + } + + s.parameterName = s.parameterName ?? s.samplerName; + s.state = state.State; + samplers.Add(s); + } + + shaderData._samplers = samplers.ToArray(); + + // Look for existing matching constant buffers. + var cbufferIndex = new List(); + if (cbuffer.Size > 0) + { + var match = effect.ConstantBuffers.FindIndex(e => e.SameAs(cbuffer)); + if (match == -1) + { + cbufferIndex.Add(effect.ConstantBuffers.Count); + effect.ConstantBuffers.Add(cbuffer); + } + else + cbufferIndex.Add(match); + } + shaderData._cbuffers = cbufferIndex.ToArray(); + + shaderData._attributes = attributes.ToArray(); + + // Generate the layout bindings from our cbuffers, samplers, and textures. + { + using (var stream = new MemoryStream()) + using (var writer = new BinaryWriter(stream)) + { + var bindings = new List(); + + VkDescriptorSetLayoutBinding binding; + binding.stageFlags = isVertexShader ? VkShaderStageFlags.VERTEX_BIT : VkShaderStageFlags.FRAGMENT_BIT; + binding.pImmutableSamplers = 0; + binding.descriptorCount = 1; + + // Write the number of uniform buffers + writer.Write(cbufferIndex.Count); + + uint uniformSlots = 0; + uint textureSlots = 0; + uint samplerSlots = 0; + + // We just have one cbuffer at 0 right now. + if (cbufferIndex.Count > 0) + { + uniformSlots |= 1 << 0; + binding.binding = 0; + binding.descriptorType = VkDescriptorType.UNIFORM_BUFFER_DYNAMIC; + bindings.Add(binding); + } + + foreach (var s in samplers) + { + if (s.textureSlot == s.samplerSlot) + { + textureSlots |= (uint)(1 << s.textureSlot); + samplerSlots |= (uint)(1 << s.textureSlot); + binding.binding = (uint)(s.textureSlot + SlotOffset); + binding.descriptorType = VkDescriptorType.COMBINED_IMAGE_SAMPLER; + bindings.Add(binding); + + continue; + } + + samplerSlots |= (uint)(1 << s.samplerSlot); + binding.binding = (uint)(s.samplerSlot + SlotOffset); + binding.descriptorType = VkDescriptorType.SAMPLER; + bindings.Add(binding); + + textureSlots |= (uint)(1 << s.textureSlot); + binding.binding = (uint)(s.textureSlot + SlotOffset); + binding.descriptorType = VkDescriptorType.SAMPLED_IMAGE; + bindings.Add(binding); + } + + // Write the slot bits. + writer.Write(uniformSlots); + writer.Write(textureSlots); + writer.Write(samplerSlots); + + // Write the bindings. + writer.Write((uint)bindings.Count); + foreach (var b in bindings) + { + writer.Write(b.binding); + writer.Write((uint)b.descriptorType); + writer.Write(b.descriptorCount); + writer.Write((uint)b.stageFlags); + writer.Write((UInt64)b.pImmutableSamplers); + } + + // Finally write the shader bytecode. + writer.Write(shaderData.Bytecode); + + // Store the combined binding layout info and shader code. + shaderData.ShaderCode = stream.ToArray(); + } + } + + effect.Shaders.Add(shaderData); + + return shaderData; + } + finally + { + foreach (var file in cleanup) + ExternalTool.DeleteFile(file); + } + } + } +} diff --git a/Tools/MonoGame.Effect.Compiler/Effect/ShaderProfile.cs b/Tools/MonoGame.Effect.Compiler/Effect/ShaderProfile.cs index 72e38e40b41..80d5e59068f 100644 --- a/Tools/MonoGame.Effect.Compiler/Effect/ShaderProfile.cs +++ b/Tools/MonoGame.Effect.Compiler/Effect/ShaderProfile.cs @@ -28,6 +28,8 @@ protected ShaderProfile(string name, byte formatId) public static readonly ShaderProfile DirectX_11 = FromName("DirectX_11"); + public static readonly ShaderProfile Vulkan = FromName("Vulkan"); + /// /// Returns all the loaded shader profiles. /// @@ -93,4 +95,4 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c } } } -} \ No newline at end of file +} diff --git a/Tools/MonoGame.Effect.Compiler/MonoGame.Effect.Compiler.csproj b/Tools/MonoGame.Effect.Compiler/MonoGame.Effect.Compiler.csproj index 69bc13922a1..00ccca6da08 100644 --- a/Tools/MonoGame.Effect.Compiler/MonoGame.Effect.Compiler.csproj +++ b/Tools/MonoGame.Effect.Compiler/MonoGame.Effect.Compiler.csproj @@ -69,6 +69,7 @@ + @@ -83,4 +84,12 @@ + + + + + + + + diff --git a/Tools/MonoGame.Generator.CTypes/EnumWritter.cs b/Tools/MonoGame.Generator.CTypes/EnumWritter.cs new file mode 100644 index 00000000000..5db1e702dcc --- /dev/null +++ b/Tools/MonoGame.Generator.CTypes/EnumWritter.cs @@ -0,0 +1,116 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using System; +using System.Text; + +namespace MonoGame.Generator.CTypes; + +class EnumWritter +{ + private readonly Dictionary _types; + private readonly StringBuilder _outputText; + + public EnumWritter() + { + _outputText = new StringBuilder($""" + // MonoGame - Copyright (C) The MonoGame Team + // This file is subject to the terms and conditions defined in + // file 'LICENSE.txt', which is part of this source code package. + + // This code is auto generated, don't modify it by hand. + // To regenerate it run: Tools/MonoGame.Generator.CTypes + + #pragma once + + #include "api_common.h" + + + """); + + _types = []; + } + + private static bool IsValid(Type type) + { + return type.IsEnum && !type.IsNested; + } + + public bool TryAppend(Type type) + { + if (type.IsByRef) + type = type.GetElementType(); + + if (type.IsPointer) + type = type.GetElementType(); + + if (!IsValid(type)) + return false; + + if (_types.ContainsKey(type.Name)) + return true; + + _types.Add(type.Name, type); + return true; + } + + private void Generate(Type type) + { + var enumNames = Enum.GetNames(type); + var enumValues = Enum.GetValues(type); + + var name = Util.GetCTypeOrEnum(type); + + // Write all values to output + _outputText.AppendLine($$""" + enum class {{name}} : {{Util.GetCType(Enum.GetUnderlyingType(type))}} + { + """); + for (int i = 0; i < enumNames.Length; i++) + { + var enumValue = (Enum)enumValues.GetValue(i); + _outputText.AppendLine($" {enumNames[i]} = {enumValue.ToString("d")},"); + } + _outputText.AppendLine(""" + }; + + """); + + // TODO: This causes issues with enums that have repeat + // values causing the `switch` to not work. + // + // We don't use this feature now anyway. + /* + _outputText.AppendLine($$""" + static const char* {{name}}_ToString({{name}} enumValue) + { + switch (enumValue) + { + """); + for (int i = 0; i < enumNames.Length; i++) + { + _outputText.AppendLine($" case {name}::{enumNames[i]}: return \"{enumNames[i]}\";"); + } + _outputText.AppendLine(""" + } + + return "Unknown Value"; + } + + """); + */ + } + + public void Flush(string dirPath) + { + foreach (var pair in _types) + Generate(pair.Value); + + var path = Path.Combine(dirPath, "api_enums.h"); + var text = _outputText.ToString().ReplaceLineEndings(); + + File.WriteAllText(path, text); + } + +} diff --git a/Tools/MonoGame.Generator.CTypes/MonoGame.Generator.CTypes.csproj b/Tools/MonoGame.Generator.CTypes/MonoGame.Generator.CTypes.csproj new file mode 100644 index 00000000000..6d6c4c59425 --- /dev/null +++ b/Tools/MonoGame.Generator.CTypes/MonoGame.Generator.CTypes.csproj @@ -0,0 +1,12 @@ + + + + Exe + net8.0 + enable + enable + Debug;Release + AnyCPU + + + diff --git a/Tools/MonoGame.Generator.CTypes/PInvokeWritter.cs b/Tools/MonoGame.Generator.CTypes/PInvokeWritter.cs new file mode 100644 index 00000000000..c2b06fd0d84 --- /dev/null +++ b/Tools/MonoGame.Generator.CTypes/PInvokeWritter.cs @@ -0,0 +1,142 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using System.ComponentModel; +using System.Reflection; +using System.Reflection.Metadata; +using System.Runtime.InteropServices; +using System.Text; +using System.Runtime.CompilerServices; + +namespace MonoGame.Generator.CTypes; + +class PinvokeWritter +{ + private readonly string _name; + + private readonly StringBuilder _outputText; + + private readonly Dictionary _handles; + + private readonly List _methods; + + private EnumWritter _enumWritter; + + private StructWritter _structWritter; + + public PinvokeWritter(Type type, StructWritter structWritter, EnumWritter enumWritter) + { + _name = type.Name; + _enumWritter = enumWritter; + _structWritter = structWritter; + + _outputText = new StringBuilder($""" + // MonoGame - Copyright (C) The MonoGame Team + // This file is subject to the terms and conditions defined in + // file 'LICENSE.txt', which is part of this source code package. + + // This code is auto generated, don't modify it by hand. + // To regenerate it run: Tools/MonoGame.Generator.CTypes + + #pragma once + + #include "api_common.h" + #include "api_enums.h" + #include "api_structs.h" + + + + """) + { + + }; + _handles = []; + _methods = []; + } + + private static bool IsHandle(Type type) + { + if (!type.IsPointer) + return false; + + type = type.GetElementType(); + + return type.IsMGHandle(); + } + + private bool TryAppendHandle(Type type) + { + if (!IsHandle(type)) + return false; + + if (_handles.ContainsKey(type.Name)) + return false; + + _handles.Add(type.Name, type); + + return true; + } + + public bool Append(MethodInfo method) + { + if (!method.IsStatic) + return false; + + var import = method.GetCustomAttribute(); + if (import == null) + return false; + + TryAppendHandle(method.ReturnType); + _enumWritter.TryAppend(method.ReturnType); + _structWritter.TryAppend(method.ReturnType); + + foreach (var arg in method.GetParameters()) + { + TryAppendHandle(arg.ParameterType); + _enumWritter.TryAppend(arg.ParameterType); + _structWritter.TryAppend(arg.ParameterType); + } + + _methods.Add(method); + return true; + } + + private void GenerateHandle(Type type) + { + type = type.GetElementType(); + _outputText.AppendLine($"struct {type.Name};"); + } + + private void GenerateMethod(MethodInfo method) + { + var import = method.GetCustomAttribute(); + + var rtype = Util.GetCTypeOrEnum(method.ReturnType); + var fname = import.EntryPoint ?? method.Name; + + var arguments = new List(); + foreach (var arg in method.GetParameters()) + arguments.Add(Util.GetCType(arg)); + + _outputText.AppendLine($"MG_EXPORT {rtype} {fname}({string.Join(", ", arguments)});"); + } + + public void Flush(string dirPath) + { + // Write the handles. + foreach (var pair in _handles) + GenerateHandle(pair.Value); + + _outputText.AppendLine(); + + // Write the pinvokes. + foreach (var method in _methods) + GenerateMethod(method); + + var path = Path.Combine(dirPath, $"api_{_name}.h"); + var text = _outputText.ToString().ReplaceLineEndings(); + + File.WriteAllText(path, text); + } +} diff --git a/Tools/MonoGame.Generator.CTypes/Program.cs b/Tools/MonoGame.Generator.CTypes/Program.cs new file mode 100644 index 00000000000..f71d4f9ce62 --- /dev/null +++ b/Tools/MonoGame.Generator.CTypes/Program.cs @@ -0,0 +1,36 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using System.Reflection; +using MonoGame.Generator.CTypes; + +var repoDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../../../"); +var monogamePlatformDir = Path.Combine(repoDirectory, "native/monogame/include"); +var monogameFrameworkPath = Path.Combine(repoDirectory, "Artifacts/MonoGame.Framework/Native/Debug/MonoGame.Framework.dll"); +var assembly = Assembly.LoadFile(monogameFrameworkPath); +var enumWritter = new EnumWritter(); +var structWritter = new StructWritter(enumWritter); + +if (!Directory.Exists(monogamePlatformDir)) + Directory.CreateDirectory(monogamePlatformDir); + +foreach (var type in assembly.GetTypes()) +{ + // Look for our interop types. + if (!type.FullName!.StartsWith("MonoGame.Interop.")) + continue; + + // All our interop pinvokes are static classes. + if (!type.IsClass || !type.IsAbstract || !type.IsSealed) + continue; + + var writter = new PinvokeWritter(type, structWritter, enumWritter); + foreach (var method in type.GetMethods()) + writter.Append(method); + + writter.Flush(monogamePlatformDir); +} + +enumWritter.Flush(monogamePlatformDir); +structWritter.Flush(monogamePlatformDir); diff --git a/Tools/MonoGame.Generator.CTypes/StructWritter.cs b/Tools/MonoGame.Generator.CTypes/StructWritter.cs new file mode 100644 index 00000000000..5777db129c7 --- /dev/null +++ b/Tools/MonoGame.Generator.CTypes/StructWritter.cs @@ -0,0 +1,152 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using System; +using System.ComponentModel; +using System.Reflection; +using System.Text; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace MonoGame.Generator.CTypes; + +class StructWritter +{ + private readonly Dictionary _types; + private readonly StringBuilder _outputText; + private readonly EnumWritter _enumWritter; + + public StructWritter(EnumWritter enumWritter) + { + _enumWritter = enumWritter; + + _outputText = new StringBuilder($""" + // MonoGame - Copyright (C) The MonoGame Team + // This file is subject to the terms and conditions defined in + // file 'LICENSE.txt', which is part of this source code package. + + // This code is auto generated, don't modify it by hand. + // To regenerate it run: Tools/MonoGame.Generator.CTypes + + #pragma once + + #include "api_common.h" + + + """); + + _types = []; + } + + private static bool IsValid(Type type) + { + if (!type.IsValueType) + return false; + + if (type.IsEnum) + return false; + + if (type.IsNested) + return false; + + if (type.FullName.StartsWith("System.")) + return false; + + return true; + } + + public bool TryAppend(Type type) + { + if (type.ToString().Contains("MGG_InputElement")) + type = type; + + if (type.IsArray) + type = type.GetElementType(); + + if (type.IsPointer || type.IsByRef) + { + type = type.GetElementType(); + + // Our handle types don't need to be exported. + if (type.IsMGHandle()) + return false; + } + + if (!IsValid(type)) + return false; + + if (_types.ContainsKey(type.Name)) + return true; + + foreach (var field in type.GetFields()) + { + TryAppend(field.FieldType); + _enumWritter.TryAppend(field.FieldType); + } + + _types.Add(type.Name, type); + return true; + } + + private void Generate(Type type) + { + var explicitLayout = type.IsExplicitLayout; + + if (explicitLayout) + _outputText.AppendLine("#pragma pack(push,1)"); + + _outputText.AppendLine($$""" + struct {{type.Name}} + { + """); + + int soffset = 0; + + if (explicitLayout) + _outputText.AppendLine("union {"); + + // We export all public and private fields skipping statics. + var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + foreach (var field in type.GetFields(flags)) + { + var ftype = Util.GetCTypeOrEnum(field.FieldType); + + if (explicitLayout) + { + var offset = field.GetFieldOffset(); + if (offset != 0) + _outputText.AppendLine($" MG_FIELD_OFFSET({offset}, {ftype}, {field.Name});"); + else + _outputText.AppendLine($" {ftype} {field.Name};"); + } + else + _outputText.AppendLine($" {ftype} {field.Name};"); + } + + if (explicitLayout) + _outputText.AppendLine("};"); + + _outputText.AppendLine($$""" + }; + """); + + if (explicitLayout) + _outputText.AppendLine("#pragma pack(pop)"); + + _outputText.AppendLine(); + } + + public void Flush(string dirPath) + { + foreach (var pair in _types) + Generate(pair.Value); + + var path = Path.Combine(dirPath, "api_structs.h"); + var text = _outputText.ToString().ReplaceLineEndings(); + + File.WriteAllText(path, text); + } + +} diff --git a/Tools/MonoGame.Generator.CTypes/Util.cs b/Tools/MonoGame.Generator.CTypes/Util.cs new file mode 100644 index 00000000000..835587970f4 --- /dev/null +++ b/Tools/MonoGame.Generator.CTypes/Util.cs @@ -0,0 +1,130 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.InteropServices; +using System.Text; + +namespace MonoGame.Generator.CTypes; + +static class Util +{ + public static string GetCType(Type cstype) => cstype.ToString() switch + { + "System.Byte" => "mgbyte", + "System.Int16" => "mgshort", + "System.UInt16" => "mgushort", + "System.Int32" => "mgint", + "System.UInt32" => "mguint", + "System.Int64" => "mglong", + "System.UInt64" => "mgulong", + "System.Void" => "void", + "System.Boolean" => "mgbool", + "System.Single" => "mgfloat", + "System.Double" => "mgdouble", + "System.IntPtr" => "void*", + "System.UIntPtr" => "void*", + "System.Char" => "mgchar", + "System.String" => "const char*", + _ => cstype.Name.ToString() + }; + + public static string GetCTypeOrEnum(Type type, string functionPointerName = null) + { + if (type.IsArray) + return GetCTypeOrEnum(type.GetElementType()) + "*"; + + if (type.IsByRef) + return GetCTypeOrEnum(type.GetElementType()) + "&"; + + if (type.IsPointer) + return GetCTypeOrEnum(type.GetElementType()) + "*"; + + if (type.IsEnum) + return $"MG{type.Name}"; + + return GetCType(type); + } + + public static string GetCType(ParameterInfo param) + { + var type = param.ParameterType; + + if (type.FullName.Contains("String[]")) + type = type; + + var result = new StringBuilder(); + + if (type.BaseType != null && type.BaseType.FullName == "System.MulticastDelegate") + { + var invokeMethod = type.GetMethod("Invoke"); + + result.Append("void (*"); + result.Append(param.Name); + result.Append(")("); + + var args = new List(); + foreach (var arg in invokeMethod.GetParameters()) + args.Add(GetCTypeOrEnum(arg.ParameterType)); + + result.Append(string.Join(",", args)); + result.Append(")"); + } + else if (type.IsFunctionPointer) + { + result.Append(GetCTypeOrEnum(type.GetFunctionPointerReturnType())); + result.Append(" (*"); + result.Append(param.Name); + result.Append(")("); + + var args = new List(); + foreach (var arg in type.GetFunctionPointerParameterTypes()) + args.Add(GetCTypeOrEnum(arg)); + + result.Append(string.Join(",", args)); + result.Append(")"); + } + else + { + result.Append(GetCTypeOrEnum(type)); + result.Append(" "); + result.Append(param.Name); + } + + return result.ToString(); + } + + + public static bool IsMGHandle(this Type type) + { + foreach (var obj in type.GetCustomAttributes(false)) + { + var atype = obj.GetType(); + if (atype.FullName == "MonoGame.Interop.MGHandleAttribute") + return true; + } + + return false; + } + + public static int GetFieldOffset(this FieldInfo field) + { + var att = field.GetCustomAttribute(); + return att.Value; + } + + public static int SizeOf(Type type) + { + // Inefficienct but works for our generator needs. + + var method = new DynamicMethod("SizeOfImpl", typeof(uint), new Type[0], typeof(Util), false); + ILGenerator gen = method.GetILGenerator(); + gen.Emit(OpCodes.Sizeof, type); + gen.Emit(OpCodes.Ret); + var func = (Func)method.CreateDelegate(typeof(Func)); + + return checked((int)func()); + } +} diff --git a/build/BuildFrameworksTasks/BuildConsoleCheckTask.cs b/build/BuildFrameworksTasks/BuildConsoleCheckTask.cs deleted file mode 100644 index c1eb05afe17..00000000000 --- a/build/BuildFrameworksTasks/BuildConsoleCheckTask.cs +++ /dev/null @@ -1,11 +0,0 @@ - -namespace BuildScripts; - -[TaskName("Build ConsoleCheck")] -public sealed class BuildConsoleCheckTask : FrostingTask -{ - public override bool ShouldRun(BuildContext context) => context.IsRunningOnWindows(); - - public override void Run(BuildContext context) - => context.DotNetBuild(context.GetProjectPath(ProjectType.Framework, "ConsoleCheck"), context.DotNetBuildSettings); -} diff --git a/build/BuildFrameworksTasks/BuildDesktopVKTask.cs b/build/BuildFrameworksTasks/BuildDesktopVKTask.cs new file mode 100644 index 00000000000..850367c7b45 --- /dev/null +++ b/build/BuildFrameworksTasks/BuildDesktopVKTask.cs @@ -0,0 +1,42 @@ + +namespace BuildScripts; + +[TaskName("Build DesktopVK")] +public sealed class BuildDesktopVKTask : FrostingTask +{ + // TEMP: Until OSX and Linux is setup to work. + public override bool ShouldRun(BuildContext context) => context.IsRunningOnWindows(); + + public override void Run(BuildContext context) + { + int exit; + + // TODO: This should be moved to its own separate + // build process so that it doesn't run on all MG builds. + { + var buildDir = "native/monogame/external/sdl2/sdl/build"; + context.CreateDirectory(buildDir); + + exit = context.StartProcess("cmake", new ProcessSettings { WorkingDirectory = buildDir, Arguments = "-A x64 -D CMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded ../" }); + if (exit != 0) + throw new Exception($"SDL2 Cmake failed! {exit}"); + + exit = context.StartProcess("msbuild", new ProcessSettings { WorkingDirectory = buildDir, Arguments = "SDL2.sln /p:Configuration=Release /p:Platform=x64" }); + if (exit != 0) + throw new Exception($"SDL2 build failed! {exit}"); + } + + // Generate the native projects. + exit = context.StartProcess("premake5", new ProcessSettings { WorkingDirectory = "native/monogame", Arguments = "clean" }); + if (exit != 0) + throw new Exception($"Premake clean failed! {exit}"); + exit = context.StartProcess("premake5", new ProcessSettings { WorkingDirectory = "native/monogame", Arguments = "--os=windows --verbose vs2022" }); + if (exit != 0) + throw new Exception($"Premake generation failed! {exit}"); + + // Build it. + exit = context.StartProcess("msbuild", new ProcessSettings { WorkingDirectory = "native/monogame", Arguments = "monogame.sln /p:Configuration=Release /p:Platform=x64" }); + if (exit != 0) + throw new Exception($"Native build failed! {exit}"); + } +} diff --git a/build/Tasks.cs b/build/Tasks.cs index 7fc3f294fbe..d9a4bd3af55 100644 --- a/build/Tasks.cs +++ b/build/Tasks.cs @@ -2,8 +2,8 @@ namespace BuildScripts; [TaskName("Build Frameworks")] -[IsDependentOn(typeof(BuildConsoleCheckTask))] [IsDependentOn(typeof(BuildNativeTask))] +[IsDependentOn(typeof(BuildDesktopVKTask))] [IsDependentOn(typeof(BuildDesktopGLTask))] [IsDependentOn(typeof(BuildWindowsDXTask))] [IsDependentOn(typeof(BuildAndroidTask))] diff --git a/native/monogame/common/MGI.cpp b/native/monogame/common/MGI.cpp new file mode 100644 index 00000000000..68fd89fa4b4 --- /dev/null +++ b/native/monogame/common/MGI.cpp @@ -0,0 +1,117 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +#include "api_MGI.h" + +#define STBI_NO_PSD +#define STBI_NO_BMP +#define STBI_NO_TGA +#define STBI_NO_HDR +#define STBI_NO_PIC +#define STBI_NO_PNM + +#if defined(_WIN32) +#define __STDC_LIB_EXT1__ +#endif + +#define STB_IMAGE_IMPLEMENTATION +#include "stb_image.h" + +#define STB_IMAGE_WRITE_IMPLEMENTATION +#include "stb_image_write.h" + + +void MGI_ReadRGBA(mgbyte* data, mgint dataBytes, mgbool zeroTransparentPixels, mgint& width, mgint& height, mgbyte*& rgba) +{ + width = 0; + height = 0; + rgba = nullptr; + + int c, w, h; + auto image = stbi_load_from_memory(data, dataBytes, &w, &h, &c, 4); + if (image == nullptr) + { + width = 0; + height = 0; + return; + } + + // If the original image before conversion had alpha... + if (zeroTransparentPixels && c == 4) + { + // XNA blacks out any pixels with an alpha of zero. + for (int i = 0; i < w * h; i += 4) + { + if (image[i + 3] == 0) + { + image[i + 0] = 0; + image[i + 1] = 0; + image[i + 2] = 0; + } + } + } + + rgba = image; + width = w; + height = h; +} + +struct mem_image +{ + static const size_t grow = 4096; + + mem_image() + { + dataBytes = grow; + data = (mgbyte*)malloc(grow); + offset = 0; + } + + mgbyte* data; + mgint dataBytes; + size_t offset; +}; + +static void mem_image_write(void* context, void* data, int size) +{ + mem_image* image = (mem_image*)context; + + size_t offset = image->offset + size; + + + if (offset > image->dataBytes) + { + // TODO: Need a better strategy for memory growth. + // TODO: Need to handle allocation failure gracefully. + image->dataBytes = (mgint)(offset + mem_image::grow); // Need a better algo! + image->data = (mgbyte*)realloc(image->data, image->dataBytes); + } + + memcpy(image->data + image->offset, data, size); + image->offset = offset; +} + +void MGI_WriteJpg(mgbyte* data, mgint dataBytes, mgint width, mgint height, mgint quality, mgbyte*& jpg, mgint& jpgBytes) +{ + jpg = nullptr; + jpgBytes = 0; + + mem_image image; + stbi_write_jpg_to_func(mem_image_write, &image, width, height, 4, data, quality); + + jpg = (mgbyte*)realloc(image.data, image.offset); + jpgBytes = image.dataBytes; +} + +void MGI_WritePng(mgbyte* data, mgint dataBytes, mgint width, mgint height, mgbyte*& png, mgint& pngBytes) +{ + png = nullptr; + pngBytes = 0; + + mem_image image; + stbi_write_png_to_func(mem_image_write, &image, width, height, 4, data, 4); + + png = (mgbyte*)realloc(image.data, image.offset); + pngBytes = image.dataBytes; +} diff --git a/native/monogame/common/MGM.cpp b/native/monogame/common/MGM.cpp new file mode 100644 index 00000000000..d17ad0184ee --- /dev/null +++ b/native/monogame/common/MGM.cpp @@ -0,0 +1,185 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +struct MGG_Texture; + +#include "api_MGM.h" + +#include "mg_common.h" + + +struct MGM_Song +{ + mgulong duration; + + void (*finishCallback)(void*); + void* finishData; +}; + +MGM_Song* MGM_Song_Create(const char* mediaFilePath) +{ + assert(mediaFilePath != nullptr); + + // TODO: This should detect the media format using + // standard native format decoder libraries that are + // portable to all our target platforms: + // + // libvorbis + // minimp3 + // wave ?? + // mp4 ?? + // FLAC ?? + // + // It should then spin up thread which decodes the + // audio and streams buffers to a native SoundEffect. + + auto song = new MGM_Song(); + song->duration = 0; + song->finishCallback = nullptr; + song->finishData = nullptr; + return song; +} + +mgulong MGM_Song_GetDuration(MGM_Song* song) +{ + assert(song != nullptr); + return song->duration; +} + +mgulong MGM_Song_GetPosition(MGM_Song* song) +{ + assert(song != nullptr); + return 0; +} + +mgfloat MGM_Song_GetVolume(MGM_Song* song) +{ + assert(song != nullptr); + return 0; +} + +void MGM_Song_SetVolume(MGM_Song* song, mgfloat volume) +{ + assert(song != nullptr); +} + +void MGM_Song_Pause(MGM_Song* song) +{ + assert(song != nullptr); +} + +void MGM_Song_Play(MGM_Song* song, mgulong startPositionMs, void (*callback)(void*), void* callbackData) +{ + assert(song != nullptr); + + song->finishCallback = callback; + song->finishData = callbackData; +} + +void MGM_Song_Resume(MGM_Song* song) +{ + assert(song != nullptr); +} + +void MGM_Song_Stop(MGM_Song* song) +{ + assert(song != nullptr); +} + +void MGM_Song_Destroy(MGM_Song* song) +{ + assert(song != nullptr); + delete song; +} + + +struct MGM_Video +{ + mguint width; + mguint height; + mgfloat fps; + mgulong duration; + mgint cachedFrames; +}; + +MGM_Video* MGM_Video_Create(const char* mediaFilePath, mgint cachedFrameNum, mgint& width, mgint& height, mgfloat& fps, mgulong& duration) +{ + assert(mediaFilePath != nullptr); + + // TODO: Like Song above we should detect the media + // format from a native decoder libraries that are + // portable to all our target platforms. + // + // It should then spin up thread which decodes the + // video/audio streams. + + // TOOD: Ideally we just support OpenH264+AAC which is pretty + // much industry standard now. Anything else is not + // importaint unless a new standard comes around. + + auto video = new MGM_Video(); + video->duration = duration = 0; + video->width = width = 0; + video->height = height = 0; + video->fps = fps = 0.0f; + video->cachedFrames = cachedFrameNum; + + return video; +} + +void MGM_Video_Destroy(MGM_Video* video) +{ + assert(video != nullptr); + delete video; +} + +MGMediaState MGM_Video_GetState(MGM_Video* video) +{ + assert(video != nullptr); + return MGMediaState::Stopped; +} + +mgulong MGM_Video_GetPosition(MGM_Video* video) +{ + assert(video != nullptr); + return 0; +} + +void MGM_Video_SetVolume(MGM_Video* video, mgfloat volume) +{ + assert(video != nullptr); +} + +void MGM_Video_SetLooped(MGM_Video* video, mgbool looped) +{ + assert(video != nullptr); +} + +void MGM_Video_Play(MGM_Video* video) +{ + assert(video != nullptr); +} + +void MGM_Video_Pause(MGM_Video* video) +{ + assert(video != nullptr); +} + +void MGM_Video_Resume(MGM_Video* video) +{ + assert(video != nullptr); +} + +void MGM_Video_Stop(MGM_Video* video) +{ + assert(video != nullptr); +} + +void MGM_Video_GetFrame(MGM_Video* video, mguint& frame, MGG_Texture*& handle) +{ + assert(video != nullptr); + frame = 0; + handle = nullptr; +} + diff --git a/native/monogame/common/mg_hash.cpp b/native/monogame/common/mg_hash.cpp new file mode 100644 index 00000000000..4c2791d037e --- /dev/null +++ b/native/monogame/common/mg_hash.cpp @@ -0,0 +1,44 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +#include "mg_common.h" + + +mguint MG_ComputeHash(const mgbyte* value, mgint length) +{ + // This is a 32-bit FNV-1a hash based on public domain code from: + // http://www.isthe.com/chongo/tech/comp/fnv + // + mguint result = (mguint)0x811c9dc5; + while (length-- > 0) + { + result ^= (mguint)*value; + result += + (result << 1) + + (result << 4) + + (result << 7) + + (result << 8) + + (result << 24); + ++value; + } + + return result; +} + +mguint MG_ComputeHash(mguint value, mguint result) +{ + // This is a 32-bit FNV-1a hash based on public domain code from: + // http://www.isthe.com/chongo/tech/comp/fnv + // + + result ^= value; + result += + (result << 1) + + (result << 4) + + (result << 7) + + (result << 8) + + (result << 24); + + return result; +} diff --git a/native/monogame/common/stb_image.h b/native/monogame/common/stb_image.h new file mode 100644 index 00000000000..b3d2c99180c --- /dev/null +++ b/native/monogame/common/stb_image.h @@ -0,0 +1,8099 @@ +/* stb_image - v2.29 - public domain image loader - http://nothings.org/stb + no warranty implied; use at your own risk + + Do this: + #define STB_IMAGE_IMPLEMENTATION + before you include this file in *one* C or C++ file to create the implementation. + + // i.e. it should look like this: + #include ... + #include ... + #include ... + #define STB_IMAGE_IMPLEMENTATION + #include "stb_image.h" + + You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. + And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free + + + QUICK NOTES: + Primarily of interest to game developers and other people who can + avoid problematic images and only need the trivial interface + + JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) + PNG 1/2/4/8/16-bit-per-channel + + TGA (not sure what subset, if a subset) + BMP non-1bpp, non-RLE + PSD (composited view only, no extra channels, 8/16 bit-per-channel) + + GIF (*comp always reports as 4-channel) + HDR (radiance rgbE format) + PIC (Softimage PIC) + PNM (PPM and PGM binary only) + + Animated GIF still needs a proper API, but here's one way to do it: + http://gist.github.com/urraka/685d9a6340b26b830d49 + + - decode from memory or through FILE (define STBI_NO_STDIO to remove code) + - decode from arbitrary I/O callbacks + - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) + + Full documentation under "DOCUMENTATION" below. + + +LICENSE + + See end of file for license information. + +RECENT REVISION HISTORY: + + 2.29 (2023-05-xx) optimizations + 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff + 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes + 2.26 (2020-07-13) many minor fixes + 2.25 (2020-02-02) fix warnings + 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically + 2.23 (2019-08-11) fix clang static analysis warning + 2.22 (2019-03-04) gif fixes, fix warnings + 2.21 (2019-02-25) fix typo in comment + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings + 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes + 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 + RGB-format JPEG; remove white matting in PSD; + allocate large structures on the stack; + correct channel count for PNG & BMP + 2.10 (2016-01-22) avoid warning introduced in 2.09 + 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED + + See end of file for full revision history. + + + ============================ Contributors ========================= + + Image formats Extensions, features + Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) + Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) + Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) + Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) + Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) + Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) + Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) + github:urraka (animated gif) Junggon Kim (PNM comments) + Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) + socks-the-fox (16-bit PNG) + Jeremy Sawicki (handle all ImageNet JPGs) + Optimizations & bugfixes Mikhail Morozov (1-bit BMP) + Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) + Arseny Kapoulkine Simon Breuss (16-bit PNM) + John-Mark Allen + Carmelo J Fdez-Aguera + + Bug & warning fixes + Marc LeBlanc David Woo Guillaume George Martins Mozeiko + Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski + Phil Jordan Dave Moore Roy Eltham + Hayaki Saito Nathan Reed Won Chun + Luke Graham Johan Duparc Nick Verigakis the Horde3D community + Thomas Ruf Ronny Chevalier github:rlyeh + Janez Zemva John Bartholomew Michal Cichon github:romigrou + Jonathan Blow Ken Hamada Tero Hanninen github:svdijk + Eugene Golushkov Laurent Gomila Cort Stratton github:snagar + Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex + Cass Everitt Ryamond Barbiero github:grim210 + Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw + Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus + Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo + Julian Raschke Gregory Mullen Christian Floisand github:darealshinji + Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 + Brad Weinberger Matvey Cherevko github:mosra + Luca Sas Alexander Veselov Zack Middleton [reserved] + Ryan C. Gordon [reserved] [reserved] + DO NOT ADD YOUR NAME HERE + + Jacko Dirks + + To add your name to the credits, pick a random blank space in the middle and fill it. + 80% of merge conflicts on stb PRs are due to people adding their name at the end + of the credits. +*/ + +#ifndef STBI_INCLUDE_STB_IMAGE_H +#define STBI_INCLUDE_STB_IMAGE_H + +// DOCUMENTATION +// +// Limitations: +// - no 12-bit-per-channel JPEG +// - no JPEGs with arithmetic coding +// - GIF always returns *comp=4 +// +// Basic usage (see HDR discussion below for HDR usage): +// int x,y,n; +// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); +// // ... process data if not NULL ... +// // ... x = width, y = height, n = # 8-bit components per pixel ... +// // ... replace '0' with '1'..'4' to force that many components per pixel +// // ... but 'n' will always be the number that it would have been if you said 0 +// stbi_image_free(data); +// +// Standard parameters: +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *channels_in_file -- outputs # of image components in image file +// int desired_channels -- if non-zero, # of image components requested in result +// +// The return value from an image loader is an 'unsigned char *' which points +// to the pixel data, or NULL on an allocation failure or if the image is +// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, +// with each pixel consisting of N interleaved 8-bit components; the first +// pixel pointed to is top-left-most in the image. There is no padding between +// image scanlines or between pixels, regardless of format. The number of +// components N is 'desired_channels' if desired_channels is non-zero, or +// *channels_in_file otherwise. If desired_channels is non-zero, +// *channels_in_file has the number of components that _would_ have been +// output otherwise. E.g. if you set desired_channels to 4, you will always +// get RGBA output, but you can check *channels_in_file to see if it's trivially +// opaque because e.g. there were only 3 channels in the source image. +// +// An output image with N components has the following components interleaved +// in this order in each pixel: +// +// N=#comp components +// 1 grey +// 2 grey, alpha +// 3 red, green, blue +// 4 red, green, blue, alpha +// +// If image loading fails for any reason, the return value will be NULL, +// and *x, *y, *channels_in_file will be unchanged. The function +// stbi_failure_reason() can be queried for an extremely brief, end-user +// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS +// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// more user-friendly ones. +// +// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. +// +// To query the width, height and component count of an image without having to +// decode the full file, you can use the stbi_info family of functions: +// +// int x,y,n,ok; +// ok = stbi_info(filename, &x, &y, &n); +// // returns ok=1 and sets x, y, n if image is a supported format, +// // 0 otherwise. +// +// Note that stb_image pervasively uses ints in its public API for sizes, +// including sizes of memory buffers. This is now part of the API and thus +// hard to change without causing breakage. As a result, the various image +// loaders all have certain limits on image size; these differ somewhat +// by format but generally boil down to either just under 2GB or just under +// 1GB. When the decoded image would be larger than this, stb_image decoding +// will fail. +// +// Additionally, stb_image will reject image files that have any of their +// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS, +// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit, +// the only way to have an image with such dimensions load correctly +// is for it to have a rather extreme aspect ratio. Either way, the +// assumption here is that such larger images are likely to be malformed +// or malicious. If you do need to load an image with individual dimensions +// larger than that, and it still fits in the overall size limit, you can +// #define STBI_MAX_DIMENSIONS on your own to be something larger. +// +// =========================================================================== +// +// UNICODE: +// +// If compiling for Windows and you wish to use Unicode filenames, compile +// with +// #define STBI_WINDOWS_UTF8 +// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert +// Windows wchar_t filenames to utf8. +// +// =========================================================================== +// +// Philosophy +// +// stb libraries are designed with the following priorities: +// +// 1. easy to use +// 2. easy to maintain +// 3. good performance +// +// Sometimes I let "good performance" creep up in priority over "easy to maintain", +// and for best performance I may provide less-easy-to-use APIs that give higher +// performance, in addition to the easy-to-use ones. Nevertheless, it's important +// to keep in mind that from the standpoint of you, a client of this library, +// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. +// +// Some secondary priorities arise directly from the first two, some of which +// provide more explicit reasons why performance can't be emphasized. +// +// - Portable ("ease of use") +// - Small source code footprint ("easy to maintain") +// - No dependencies ("ease of use") +// +// =========================================================================== +// +// I/O callbacks +// +// I/O callbacks allow you to read from arbitrary sources, like packaged +// files or some other source. Data read from callbacks are processed +// through a small internal buffer (currently 128 bytes) to try to reduce +// overhead. +// +// The three functions you must define are "read" (reads some bytes of data), +// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). +// +// =========================================================================== +// +// SIMD support +// +// The JPEG decoder will try to automatically use SIMD kernels on x86 when +// supported by the compiler. For ARM Neon support, you must explicitly +// request it. +// +// (The old do-it-yourself SIMD API is no longer supported in the current +// code.) +// +// On x86, SSE2 will automatically be used when available based on a run-time +// test; if not, the generic C versions are used as a fall-back. On ARM targets, +// the typical path is to have separate builds for NEON and non-NEON devices +// (at least this is true for iOS and Android). Therefore, the NEON support is +// toggled by a build flag: define STBI_NEON to get NEON loops. +// +// If for some reason you do not want to use any of SIMD code, or if +// you have issues compiling it, you can disable it entirely by +// defining STBI_NO_SIMD. +// +// =========================================================================== +// +// HDR image support (disable by defining STBI_NO_HDR) +// +// stb_image supports loading HDR images in general, and currently the Radiance +// .HDR file format specifically. You can still load any file through the existing +// interface; if you attempt to load an HDR file, it will be automatically remapped +// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// both of these constants can be reconfigured through this interface: +// +// stbi_hdr_to_ldr_gamma(2.2f); +// stbi_hdr_to_ldr_scale(1.0f); +// +// (note, do not use _inverse_ constants; stbi_image will invert them +// appropriately). +// +// Additionally, there is a new, parallel interface for loading files as +// (linear) floats to preserve the full dynamic range: +// +// float *data = stbi_loadf(filename, &x, &y, &n, 0); +// +// If you load LDR images through this interface, those images will +// be promoted to floating point values, run through the inverse of +// constants corresponding to the above: +// +// stbi_ldr_to_hdr_scale(1.0f); +// stbi_ldr_to_hdr_gamma(2.2f); +// +// Finally, given a filename (or an open file or memory block--see header +// file for details) containing image data, you can query for the "most +// appropriate" interface to use (that is, whether the image is HDR or +// not), using: +// +// stbi_is_hdr(char *filename); +// +// =========================================================================== +// +// iPhone PNG support: +// +// We optionally support converting iPhone-formatted PNGs (which store +// premultiplied BGRA) back to RGB, even though they're internally encoded +// differently. To enable this conversion, call +// stbi_convert_iphone_png_to_rgb(1). +// +// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per +// pixel to remove any premultiplied alpha *only* if the image file explicitly +// says there's premultiplied data (currently only happens in iPhone images, +// and only if iPhone convert-to-rgb processing is on). +// +// =========================================================================== +// +// ADDITIONAL CONFIGURATION +// +// - You can suppress implementation of any of the decoders to reduce +// your code footprint by #defining one or more of the following +// symbols before creating the implementation. +// +// STBI_NO_JPEG +// STBI_NO_PNG +// STBI_NO_BMP +// STBI_NO_PSD +// STBI_NO_TGA +// STBI_NO_GIF +// STBI_NO_HDR +// STBI_NO_PIC +// STBI_NO_PNM (.ppm and .pgm) +// +// - You can request *only* certain decoders and suppress all other ones +// (this will be more forward-compatible, as addition of new decoders +// doesn't require you to disable them explicitly): +// +// STBI_ONLY_JPEG +// STBI_ONLY_PNG +// STBI_ONLY_BMP +// STBI_ONLY_PSD +// STBI_ONLY_TGA +// STBI_ONLY_GIF +// STBI_ONLY_HDR +// STBI_ONLY_PIC +// STBI_ONLY_PNM (.ppm and .pgm) +// +// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still +// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB +// +// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater +// than that size (in either width or height) without further processing. +// This is to let programs in the wild set an upper bound to prevent +// denial-of-service attacks on untrusted data, as one could generate a +// valid image of gigantic dimensions and force stb_image to allocate a +// huge block of memory and spend disproportionate time decoding it. By +// default this is set to (1 << 24), which is 16777216, but that's still +// very big. + +#ifndef STBI_NO_STDIO +#include +#endif // STBI_NO_STDIO + +#define STBI_VERSION 1 + +enum +{ + STBI_default = 0, // only used for desired_channels + + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 +}; + +#include +typedef unsigned char stbi_uc; +typedef unsigned short stbi_us; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef STBIDEF +#ifdef STB_IMAGE_STATIC +#define STBIDEF static +#else +#define STBIDEF extern +#endif +#endif + + ////////////////////////////////////////////////////////////////////////////// + // + // PRIMARY API - works on images of any type + // + + // + // load image by filename, open file, or memory buffer + // + + typedef struct + { + int (*read) (void* user, char* data, int size); // fill 'data' with 'size' bytes. return number of bytes actually read + void (*skip) (void* user, int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + int (*eof) (void* user); // returns nonzero if we are at end of file/data + } stbi_io_callbacks; + + //////////////////////////////////// + // + // 8-bits-per-channel interface + // + + STBIDEF stbi_uc* stbi_load_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* channels_in_file, int desired_channels); + STBIDEF stbi_uc* stbi_load_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO + STBIDEF stbi_uc* stbi_load(char const* filename, int* x, int* y, int* channels_in_file, int desired_channels); + STBIDEF stbi_uc* stbi_load_from_file(FILE* f, int* x, int* y, int* channels_in_file, int desired_channels); + // for stbi_load_from_file, file pointer is left pointing immediately after image +#endif + +#ifndef STBI_NO_GIF + STBIDEF stbi_uc* stbi_load_gif_from_memory(stbi_uc const* buffer, int len, int** delays, int* x, int* y, int* z, int* comp, int req_comp); +#endif + +#ifdef STBI_WINDOWS_UTF8 + STBIDEF int stbi_convert_wchar_to_utf8(char* buffer, size_t bufferlen, const wchar_t* input); +#endif + + //////////////////////////////////// + // + // 16-bits-per-channel interface + // + + STBIDEF stbi_us* stbi_load_16_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* channels_in_file, int desired_channels); + STBIDEF stbi_us* stbi_load_16_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO + STBIDEF stbi_us* stbi_load_16(char const* filename, int* x, int* y, int* channels_in_file, int desired_channels); + STBIDEF stbi_us* stbi_load_from_file_16(FILE* f, int* x, int* y, int* channels_in_file, int desired_channels); +#endif + + //////////////////////////////////// + // + // float-per-channel interface + // +#ifndef STBI_NO_LINEAR + STBIDEF float* stbi_loadf_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* channels_in_file, int desired_channels); + STBIDEF float* stbi_loadf_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO + STBIDEF float* stbi_loadf(char const* filename, int* x, int* y, int* channels_in_file, int desired_channels); + STBIDEF float* stbi_loadf_from_file(FILE* f, int* x, int* y, int* channels_in_file, int desired_channels); +#endif +#endif + +#ifndef STBI_NO_HDR + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); + STBIDEF void stbi_hdr_to_ldr_scale(float scale); +#endif // STBI_NO_HDR + +#ifndef STBI_NO_LINEAR + STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); + STBIDEF void stbi_ldr_to_hdr_scale(float scale); +#endif // STBI_NO_LINEAR + + // stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR + STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const* clbk, void* user); + STBIDEF int stbi_is_hdr_from_memory(stbi_uc const* buffer, int len); +#ifndef STBI_NO_STDIO + STBIDEF int stbi_is_hdr(char const* filename); + STBIDEF int stbi_is_hdr_from_file(FILE* f); +#endif // STBI_NO_STDIO + + + // get a VERY brief reason for failure + // on most compilers (and ALL modern mainstream compilers) this is threadsafe + STBIDEF const char* stbi_failure_reason(void); + + // free the loaded image -- this is just free() + STBIDEF void stbi_image_free(void* retval_from_stbi_load); + + // get image dimensions & components without fully decoding + STBIDEF int stbi_info_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* comp); + STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* comp); + STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const* buffer, int len); + STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const* clbk, void* user); + +#ifndef STBI_NO_STDIO + STBIDEF int stbi_info(char const* filename, int* x, int* y, int* comp); + STBIDEF int stbi_info_from_file(FILE* f, int* x, int* y, int* comp); + STBIDEF int stbi_is_16_bit(char const* filename); + STBIDEF int stbi_is_16_bit_from_file(FILE* f); +#endif + + + + // for image formats that explicitly notate that they have premultiplied alpha, + // we just return the colors as stored in the file. set this flag to force + // unpremultiplication. results are undefined if the unpremultiply overflow. + STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); + + // indicate whether we should process iphone images back to canonical format, + // or just pass them through "as-is" + STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); + + // flip the image vertically, so the first pixel in the output array is the bottom left + STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); + + // as above, but only applies to images loaded on the thread that calls the function + // this function is only available if your compiler supports thread-local variables; + // calling it will fail to link if your compiler doesn't + STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); + STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); + STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); + + // ZLIB client - used by PNG, available for other purposes + + STBIDEF char* stbi_zlib_decode_malloc_guesssize(const char* buffer, int len, int initial_size, int* outlen); + STBIDEF char* stbi_zlib_decode_malloc_guesssize_headerflag(const char* buffer, int len, int initial_size, int* outlen, int parse_header); + STBIDEF char* stbi_zlib_decode_malloc(const char* buffer, int len, int* outlen); + STBIDEF int stbi_zlib_decode_buffer(char* obuffer, int olen, const char* ibuffer, int ilen); + + STBIDEF char* stbi_zlib_decode_noheader_malloc(const char* buffer, int len, int* outlen); + STBIDEF int stbi_zlib_decode_noheader_buffer(char* obuffer, int olen, const char* ibuffer, int ilen); + + +#ifdef __cplusplus +} +#endif + +// +// +//// end header file ///////////////////////////////////////////////////// +#endif // STBI_INCLUDE_STB_IMAGE_H + +#ifdef STB_IMAGE_IMPLEMENTATION + +#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ + || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ + || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ + || defined(STBI_ONLY_ZLIB) +#ifndef STBI_ONLY_JPEG +#define STBI_NO_JPEG +#endif +#ifndef STBI_ONLY_PNG +#define STBI_NO_PNG +#endif +#ifndef STBI_ONLY_BMP +#define STBI_NO_BMP +#endif +#ifndef STBI_ONLY_PSD +#define STBI_NO_PSD +#endif +#ifndef STBI_ONLY_TGA +#define STBI_NO_TGA +#endif +#ifndef STBI_ONLY_GIF +#define STBI_NO_GIF +#endif +#ifndef STBI_ONLY_HDR +#define STBI_NO_HDR +#endif +#ifndef STBI_ONLY_PIC +#define STBI_NO_PIC +#endif +#ifndef STBI_ONLY_PNM +#define STBI_NO_PNM +#endif +#endif + +#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) +#define STBI_NO_ZLIB +#endif + + +#include +#include // ptrdiff_t on osx +#include +#include +#include + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +#include // ldexp, pow +#endif + +#ifndef STBI_NO_STDIO +#include +#endif + +#ifndef STBI_ASSERT +#include +#define STBI_ASSERT(x) assert(x) +#endif + +#ifdef __cplusplus +#define STBI_EXTERN extern "C" +#else +#define STBI_EXTERN extern +#endif + + +#ifndef _MSC_VER +#ifdef __cplusplus +#define stbi_inline inline +#else +#define stbi_inline +#endif +#else +#define stbi_inline __forceinline +#endif + +#ifndef STBI_NO_THREAD_LOCALS +#if defined(__cplusplus) && __cplusplus >= 201103L +#define STBI_THREAD_LOCAL thread_local +#elif defined(__GNUC__) && __GNUC__ < 5 +#define STBI_THREAD_LOCAL __thread +#elif defined(_MSC_VER) +#define STBI_THREAD_LOCAL __declspec(thread) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) +#define STBI_THREAD_LOCAL _Thread_local +#endif + +#ifndef STBI_THREAD_LOCAL +#if defined(__GNUC__) +#define STBI_THREAD_LOCAL __thread +#endif +#endif +#endif + +#if defined(_MSC_VER) || defined(__SYMBIAN32__) +typedef unsigned short stbi__uint16; +typedef signed short stbi__int16; +typedef unsigned int stbi__uint32; +typedef signed int stbi__int32; +#else +#include +typedef uint16_t stbi__uint16; +typedef int16_t stbi__int16; +typedef uint32_t stbi__uint32; +typedef int32_t stbi__int32; +#endif + +// should produce compiler error if size is wrong +typedef unsigned char validate_uint32[sizeof(stbi__uint32) == 4 ? 1 : -1]; + +#ifdef _MSC_VER +#define STBI_NOTUSED(v) (void)(v) +#else +#define STBI_NOTUSED(v) (void)sizeof(v) +#endif + +#ifdef _MSC_VER +#define STBI_HAS_LROTL +#endif + +#ifdef STBI_HAS_LROTL +#define stbi_lrot(x,y) _lrotl(x,y) +#else +#define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31))) +#endif + +#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) +// ok +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." +#endif + +#ifndef STBI_MALLOC +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p,newsz) realloc(p,newsz) +#define STBI_FREE(p) free(p) +#endif + +#ifndef STBI_REALLOC_SIZED +#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) +#endif + +// x86/x64 detection +#if defined(__x86_64__) || defined(_M_X64) +#define STBI__X64_TARGET +#elif defined(__i386) || defined(_M_IX86) +#define STBI__X86_TARGET +#endif + +#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) +// gcc doesn't support sse2 intrinsics unless you compile with -msse2, +// which in turn means it gets to use SSE2 everywhere. This is unfortunate, +// but previous attempts to provide the SSE2 functions with runtime +// detection caused numerous issues. The way architecture extensions are +// exposed in GCC/Clang is, sadly, not really suited for one-file libs. +// New behavior: if compiled with -msse2, we use SSE2 without any +// detection; if not, we don't use it at all. +#define STBI_NO_SIMD +#endif + +#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) +// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET +// +// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the +// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. +// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not +// simultaneously enabling "-mstackrealign". +// +// See https://github.com/nothings/stb/issues/81 for more information. +// +// So default to no SSE2 on 32-bit MinGW. If you've read this far and added +// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. +#define STBI_NO_SIMD +#endif + +#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) +#define STBI_SSE2 +#include + +#ifdef _MSC_VER + +#if _MSC_VER >= 1400 // not VC6 +#include // __cpuid +static int stbi__cpuid3(void) +{ + int info[4]; + __cpuid(info, 1); + return info[3]; +} +#else +static int stbi__cpuid3(void) +{ + int res; + __asm { + mov eax, 1 + cpuid + mov res, edx + } + return res; +} +#endif + +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + int info3 = stbi__cpuid3(); + return ((info3 >> 26) & 1) != 0; +} +#endif + +#else // assume GCC-style if not VC++ +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + // If we're even attempting to compile this on GCC/Clang, that means + // -msse2 is on, which means the compiler is allowed to use SSE2 + // instructions at will, and so are we. + return 1; +} +#endif + +#endif +#endif + +// ARM NEON +#if defined(STBI_NO_SIMD) && defined(STBI_NEON) +#undef STBI_NEON +#endif + +#ifdef STBI_NEON +#include +#ifdef _MSC_VER +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name +#else +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) +#endif +#endif + +#ifndef STBI_SIMD_ALIGN +#define STBI_SIMD_ALIGN(type, name) type name +#endif + +#ifndef STBI_MAX_DIMENSIONS +#define STBI_MAX_DIMENSIONS (1 << 24) +#endif + +/////////////////////////////////////////////// +// +// stbi__context struct and start_xxx functions + +// stbi__context structure is our basic context used by all images, so it +// contains all the IO context, plus some basic image information +typedef struct +{ + stbi__uint32 img_x, img_y; + int img_n, img_out_n; + + stbi_io_callbacks io; + void* io_user_data; + + int read_from_callbacks; + int buflen; + stbi_uc buffer_start[128]; + int callback_already_read; + + stbi_uc* img_buffer, * img_buffer_end; + stbi_uc* img_buffer_original, * img_buffer_original_end; +} stbi__context; + + +static void stbi__refill_buffer(stbi__context* s); + +// initialize a memory-decode context +static void stbi__start_mem(stbi__context* s, stbi_uc const* buffer, int len) +{ + s->io.read = NULL; + s->read_from_callbacks = 0; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = (stbi_uc*)buffer; + s->img_buffer_end = s->img_buffer_original_end = (stbi_uc*)buffer + len; +} + +// initialize a callback-based context +static void stbi__start_callbacks(stbi__context* s, stbi_io_callbacks* c, void* user) +{ + s->io = *c; + s->io_user_data = user; + s->buflen = sizeof(s->buffer_start); + s->read_from_callbacks = 1; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = s->buffer_start; + stbi__refill_buffer(s); + s->img_buffer_original_end = s->img_buffer_end; +} + +#ifndef STBI_NO_STDIO + +static int stbi__stdio_read(void* user, char* data, int size) +{ + return (int)fread(data, 1, size, (FILE*)user); +} + +static void stbi__stdio_skip(void* user, int n) +{ + int ch; + fseek((FILE*)user, n, SEEK_CUR); + ch = fgetc((FILE*)user); /* have to read a byte to reset feof()'s flag */ + if (ch != EOF) { + ungetc(ch, (FILE*)user); /* push byte back onto stream if valid. */ + } +} + +static int stbi__stdio_eof(void* user) +{ + return feof((FILE*)user) || ferror((FILE*)user); +} + +static stbi_io_callbacks stbi__stdio_callbacks = +{ + stbi__stdio_read, + stbi__stdio_skip, + stbi__stdio_eof, +}; + +static void stbi__start_file(stbi__context* s, FILE* f) +{ + stbi__start_callbacks(s, &stbi__stdio_callbacks, (void*)f); +} + +//static void stop_file(stbi__context *s) { } + +#endif // !STBI_NO_STDIO + +static void stbi__rewind(stbi__context* s) +{ + // conceptually rewind SHOULD rewind to the beginning of the stream, + // but we just rewind to the beginning of the initial buffer, because + // we only use it after doing 'test', which only ever looks at at most 92 bytes + s->img_buffer = s->img_buffer_original; + s->img_buffer_end = s->img_buffer_original_end; +} + +enum +{ + STBI_ORDER_RGB, + STBI_ORDER_BGR +}; + +typedef struct +{ + int bits_per_channel; + int num_channels; + int channel_order; +} stbi__result_info; + +#ifndef STBI_NO_JPEG +static int stbi__jpeg_test(stbi__context* s); +static void* stbi__jpeg_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri); +static int stbi__jpeg_info(stbi__context* s, int* x, int* y, int* comp); +#endif + +#ifndef STBI_NO_PNG +static int stbi__png_test(stbi__context* s); +static void* stbi__png_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri); +static int stbi__png_info(stbi__context* s, int* x, int* y, int* comp); +static int stbi__png_is16(stbi__context* s); +#endif + +#ifndef STBI_NO_BMP +static int stbi__bmp_test(stbi__context* s); +static void* stbi__bmp_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri); +static int stbi__bmp_info(stbi__context* s, int* x, int* y, int* comp); +#endif + +#ifndef STBI_NO_TGA +static int stbi__tga_test(stbi__context* s); +static void* stbi__tga_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri); +static int stbi__tga_info(stbi__context* s, int* x, int* y, int* comp); +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context* s); +static void* stbi__psd_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri, int bpc); +static int stbi__psd_info(stbi__context* s, int* x, int* y, int* comp); +static int stbi__psd_is16(stbi__context* s); +#endif + +#ifndef STBI_NO_HDR +static int stbi__hdr_test(stbi__context* s); +static float* stbi__hdr_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri); +static int stbi__hdr_info(stbi__context* s, int* x, int* y, int* comp); +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_test(stbi__context* s); +static void* stbi__pic_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri); +static int stbi__pic_info(stbi__context* s, int* x, int* y, int* comp); +#endif + +#ifndef STBI_NO_GIF +static int stbi__gif_test(stbi__context* s); +static void* stbi__gif_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri); +static void* stbi__load_gif_main(stbi__context* s, int** delays, int* x, int* y, int* z, int* comp, int req_comp); +static int stbi__gif_info(stbi__context* s, int* x, int* y, int* comp); +#endif + +#ifndef STBI_NO_PNM +static int stbi__pnm_test(stbi__context* s); +static void* stbi__pnm_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri); +static int stbi__pnm_info(stbi__context* s, int* x, int* y, int* comp); +static int stbi__pnm_is16(stbi__context* s); +#endif + +static +#ifdef STBI_THREAD_LOCAL +STBI_THREAD_LOCAL +#endif +const char* stbi__g_failure_reason; + +STBIDEF const char* stbi_failure_reason(void) +{ + return stbi__g_failure_reason; +} + +#ifndef STBI_NO_FAILURE_STRINGS +static int stbi__err(const char* str) +{ + stbi__g_failure_reason = str; + return 0; +} +#endif + +static void* stbi__malloc(size_t size) +{ + return STBI_MALLOC(size); +} + +// stb_image uses ints pervasively, including for offset calculations. +// therefore the largest decoded image size we can support with the +// current code, even on 64-bit targets, is INT_MAX. this is not a +// significant limitation for the intended use case. +// +// we do, however, need to make sure our size calculations don't +// overflow. hence a few helper functions for size calculations that +// multiply integers together, making sure that they're non-negative +// and no overflow occurs. + +// return 1 if the sum is valid, 0 on overflow. +// negative terms are considered invalid. +static int stbi__addsizes_valid(int a, int b) +{ + if (b < 0) return 0; + // now 0 <= b <= INT_MAX, hence also + // 0 <= INT_MAX - b <= INTMAX. + // And "a + b <= INT_MAX" (which might overflow) is the + // same as a <= INT_MAX - b (no overflow) + return a <= INT_MAX - b; +} + +// returns 1 if the product is valid, 0 on overflow. +// negative factors are considered invalid. +static int stbi__mul2sizes_valid(int a, int b) +{ + if (a < 0 || b < 0) return 0; + if (b == 0) return 1; // mul-by-0 is always safe + // portable way to check for no overflows in a*b + return a <= INT_MAX / b; +} + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow +static int stbi__mad2sizes_valid(int a, int b, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a * b, add); +} +#endif + +// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow +static int stbi__mad3sizes_valid(int a, int b, int c, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a * b, c) && + stbi__addsizes_valid(a * b * c, add); +} + +// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a * b, c) && + stbi__mul2sizes_valid(a * b * c, d) && stbi__addsizes_valid(a * b * c * d, add); +} +#endif + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// mallocs with size overflow checking +static void* stbi__malloc_mad2(int a, int b, int add) +{ + if (!stbi__mad2sizes_valid(a, b, add)) return NULL; + return stbi__malloc(a * b + add); +} +#endif + +static void* stbi__malloc_mad3(int a, int b, int c, int add) +{ + if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; + return stbi__malloc(a * b * c + add); +} + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static void* stbi__malloc_mad4(int a, int b, int c, int d, int add) +{ + if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; + return stbi__malloc(a * b * c * d + add); +} +#endif + +// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow. +static int stbi__addints_valid(int a, int b) +{ + if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow + if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0. + return a <= INT_MAX - b; +} + +// returns 1 if the product of two ints fits in a signed short, 0 on overflow. +static int stbi__mul2shorts_valid(int a, int b) +{ + if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow + if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX / b; // product is positive, so similar to mul2sizes_valid + if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN + return a >= SHRT_MIN / b; +} + +// stbi__err - error +// stbi__errpf - error returning pointer to float +// stbi__errpuc - error returning pointer to unsigned char + +#ifdef STBI_NO_FAILURE_STRINGS +#define stbi__err(x,y) 0 +#elif defined(STBI_FAILURE_USERMSG) +#define stbi__err(x,y) stbi__err(y) +#else +#define stbi__err(x,y) stbi__err(x) +#endif + +#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) +#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) + +STBIDEF void stbi_image_free(void* retval_from_stbi_load) +{ + STBI_FREE(retval_from_stbi_load); +} + +#ifndef STBI_NO_LINEAR +static float* stbi__ldr_to_hdr(stbi_uc* data, int x, int y, int comp); +#endif + +#ifndef STBI_NO_HDR +static stbi_uc* stbi__hdr_to_ldr(float* data, int x, int y, int comp); +#endif + +static int stbi__vertically_flip_on_load_global = 0; + +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_global = flag_true_if_should_flip; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global +#else +static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; + +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_local = flag_true_if_should_flip; + stbi__vertically_flip_on_load_set = 1; +} + +#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ + ? stbi__vertically_flip_on_load_local \ + : stbi__vertically_flip_on_load_global) +#endif // STBI_THREAD_LOCAL + +static void* stbi__load_main(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri, int bpc) +{ + memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields + ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed + ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order + ri->num_channels = 0; + + // test the formats with a very explicit header first (at least a FOURCC + // or distinctive magic number first) +#ifndef STBI_NO_PNG + if (stbi__png_test(s)) return stbi__png_load(s, x, y, comp, req_comp, ri); +#endif +#ifndef STBI_NO_BMP + if (stbi__bmp_test(s)) return stbi__bmp_load(s, x, y, comp, req_comp, ri); +#endif +#ifndef STBI_NO_GIF + if (stbi__gif_test(s)) return stbi__gif_load(s, x, y, comp, req_comp, ri); +#endif +#ifndef STBI_NO_PSD + if (stbi__psd_test(s)) return stbi__psd_load(s, x, y, comp, req_comp, ri, bpc); +#else + STBI_NOTUSED(bpc); +#endif +#ifndef STBI_NO_PIC + if (stbi__pic_test(s)) return stbi__pic_load(s, x, y, comp, req_comp, ri); +#endif + + // then the formats that can end up attempting to load with just 1 or 2 + // bytes matching expectations; these are prone to false positives, so + // try them later +#ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s, x, y, comp, req_comp, ri); +#endif +#ifndef STBI_NO_PNM + if (stbi__pnm_test(s)) return stbi__pnm_load(s, x, y, comp, req_comp, ri); +#endif + +#ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float* hdr = stbi__hdr_load(s, x, y, comp, req_comp, ri); + return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); + } +#endif + +#ifndef STBI_NO_TGA + // test tga last because it's a crappy test! + if (stbi__tga_test(s)) + return stbi__tga_load(s, x, y, comp, req_comp, ri); +#endif + + return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); +} + +static stbi_uc* stbi__convert_16_to_8(stbi__uint16* orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi_uc* reduced; + + reduced = (stbi_uc*)stbi__malloc(img_len); + if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling + + STBI_FREE(orig); + return reduced; +} + +static stbi__uint16* stbi__convert_8_to_16(stbi_uc* orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi__uint16* enlarged; + + enlarged = (stbi__uint16*)stbi__malloc(img_len * 2); + if (enlarged == NULL) return (stbi__uint16*)stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff + + STBI_FREE(orig); + return enlarged; +} + +static void stbi__vertical_flip(void* image, int w, int h, int bytes_per_pixel) +{ + int row; + size_t bytes_per_row = (size_t)w * bytes_per_pixel; + stbi_uc temp[2048]; + stbi_uc* bytes = (stbi_uc*)image; + + for (row = 0; row < (h >> 1); row++) { + stbi_uc* row0 = bytes + row * bytes_per_row; + stbi_uc* row1 = bytes + (h - row - 1) * bytes_per_row; + // swap row0 with row1 + size_t bytes_left = bytes_per_row; + while (bytes_left) { + size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + memcpy(temp, row0, bytes_copy); + memcpy(row0, row1, bytes_copy); + memcpy(row1, temp, bytes_copy); + row0 += bytes_copy; + row1 += bytes_copy; + bytes_left -= bytes_copy; + } + } +} + +#ifndef STBI_NO_GIF +static void stbi__vertical_flip_slices(void* image, int w, int h, int z, int bytes_per_pixel) +{ + int slice; + int slice_size = w * h * bytes_per_pixel; + + stbi_uc* bytes = (stbi_uc*)image; + for (slice = 0; slice < z; ++slice) { + stbi__vertical_flip(bytes, w, h, bytes_per_pixel); + bytes += slice_size; + } +} +#endif + +static unsigned char* stbi__load_and_postprocess_8bit(stbi__context* s, int* x, int* y, int* comp, int req_comp) +{ + stbi__result_info ri; + void* result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 8) { + result = stbi__convert_16_to_8((stbi__uint16*)result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 8; + } + + // @TODO: move stbi__convert_format to here + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); + } + + return (unsigned char*)result; +} + +static stbi__uint16* stbi__load_and_postprocess_16bit(stbi__context* s, int* x, int* y, int* comp, int req_comp) +{ + stbi__result_info ri; + void* result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 16) { + result = stbi__convert_8_to_16((stbi_uc*)result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 16; + } + + // @TODO: move stbi__convert_format16 to here + // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); + } + + return (stbi__uint16*)result; +} + +#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) +static void stbi__float_postprocess(float* result, int* x, int* y, int* comp, int req_comp) +{ + if (stbi__vertically_flip_on_load && result != NULL) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); + } +} +#endif + +#ifndef STBI_NO_STDIO + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char* str, int cbmb, wchar_t* widestr, int cchwide); +STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t* widestr, int cchwide, char* str, int cbmb, const char* defchar, int* used_default); +#endif + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBIDEF int stbi_convert_wchar_to_utf8(char* buffer, size_t bufferlen, const wchar_t* input) +{ + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int)bufferlen, NULL, NULL); +} +#endif + +static FILE* stbi__fopen(char const* filename, char const* mode) +{ + FILE* f; +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) + wchar_t wMode[64]; + wchar_t wFilename[1024]; + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename) / sizeof(*wFilename))) + return 0; + + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode) / sizeof(*wMode))) + return 0; + +#if defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != _wfopen_s(&f, wFilename, wMode)) + f = 0; +#else + f = _wfopen(wFilename, wMode); +#endif + +#elif defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != fopen_s(&f, filename, mode)) + f = 0; +#else + f = fopen(filename, mode); +#endif + return f; +} + + +STBIDEF stbi_uc* stbi_load(char const* filename, int* x, int* y, int* comp, int req_comp) +{ + FILE* f = stbi__fopen(filename, "rb"); + unsigned char* result; + if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file(f, x, y, comp, req_comp); + fclose(f); + return result; +} + +STBIDEF stbi_uc* stbi_load_from_file(FILE* f, int* x, int* y, int* comp, int req_comp) +{ + unsigned char* result; + stbi__context s; + stbi__start_file(&s, f); + result = stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, -(int)(s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi__uint16* stbi_load_from_file_16(FILE* f, int* x, int* y, int* comp, int req_comp) +{ + stbi__uint16* result; + stbi__context s; + stbi__start_file(&s, f); + result = stbi__load_and_postprocess_16bit(&s, x, y, comp, req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, -(int)(s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi_us* stbi_load_16(char const* filename, int* x, int* y, int* comp, int req_comp) +{ + FILE* f = stbi__fopen(filename, "rb"); + stbi__uint16* result; + if (!f) return (stbi_us*)stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file_16(f, x, y, comp, req_comp); + fclose(f); + return result; +} + + +#endif //!STBI_NO_STDIO + +STBIDEF stbi_us* stbi_load_16_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, desired_channels); +} + +STBIDEF stbi_us* stbi_load_16_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks*)clbk, user); + return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, desired_channels); +} + +STBIDEF stbi_uc* stbi_load_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); +} + +STBIDEF stbi_uc* stbi_load_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks*)clbk, user); + return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); +} + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc* stbi_load_gif_from_memory(stbi_uc const* buffer, int len, int** delays, int* x, int* y, int* z, int* comp, int req_comp) +{ + unsigned char* result; + stbi__context s; + stbi__start_mem(&s, buffer, len); + + result = (unsigned char*)stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); + if (stbi__vertically_flip_on_load) { + stbi__vertical_flip_slices(result, *x, *y, *z, *comp); + } + + return result; +} +#endif + +#ifndef STBI_NO_LINEAR +static float* stbi__loadf_main(stbi__context* s, int* x, int* y, int* comp, int req_comp) +{ + unsigned char* data; +#ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + stbi__result_info ri; + float* hdr_data = stbi__hdr_load(s, x, y, comp, req_comp, &ri); + if (hdr_data) + stbi__float_postprocess(hdr_data, x, y, comp, req_comp); + return hdr_data; + } +#endif + data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); + if (data) + return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); +} + +STBIDEF float* stbi_loadf_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__loadf_main(&s, x, y, comp, req_comp); +} + +STBIDEF float* stbi_loadf_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks*)clbk, user); + return stbi__loadf_main(&s, x, y, comp, req_comp); +} + +#ifndef STBI_NO_STDIO +STBIDEF float* stbi_loadf(char const* filename, int* x, int* y, int* comp, int req_comp) +{ + float* result; + FILE* f = stbi__fopen(filename, "rb"); + if (!f) return stbi__errpf("can't fopen", "Unable to open file"); + result = stbi_loadf_from_file(f, x, y, comp, req_comp); + fclose(f); + return result; +} + +STBIDEF float* stbi_loadf_from_file(FILE* f, int* x, int* y, int* comp, int req_comp) +{ + stbi__context s; + stbi__start_file(&s, f); + return stbi__loadf_main(&s, x, y, comp, req_comp); +} +#endif // !STBI_NO_STDIO + +#endif // !STBI_NO_LINEAR + +// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is +// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always +// reports false! + +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const* buffer, int len) +{ +#ifndef STBI_NO_HDR + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__hdr_test(&s); +#else + STBI_NOTUSED(buffer); + STBI_NOTUSED(len); + return 0; +#endif +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr(char const* filename) +{ + FILE* f = stbi__fopen(filename, "rb"); + int result = 0; + if (f) { + result = stbi_is_hdr_from_file(f); + fclose(f); + } + return result; +} + +STBIDEF int stbi_is_hdr_from_file(FILE* f) +{ +#ifndef STBI_NO_HDR + long pos = ftell(f); + int res; + stbi__context s; + stbi__start_file(&s, f); + res = stbi__hdr_test(&s); + fseek(f, pos, SEEK_SET); + return res; +#else + STBI_NOTUSED(f); + return 0; +#endif +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const* clbk, void* user) +{ +#ifndef STBI_NO_HDR + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks*)clbk, user); + return stbi__hdr_test(&s); +#else + STBI_NOTUSED(clbk); + STBI_NOTUSED(user); + return 0; +#endif +} + +#ifndef STBI_NO_LINEAR +static float stbi__l2h_gamma = 2.2f, stbi__l2h_scale = 1.0f; + +STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } +STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } +#endif + +static float stbi__h2l_gamma_i = 1.0f / 2.2f, stbi__h2l_scale_i = 1.0f; + +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1 / gamma; } +STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1 / scale; } + + +////////////////////////////////////////////////////////////////////////////// +// +// Common code used by all image loaders +// + +enum +{ + STBI__SCAN_load = 0, + STBI__SCAN_type, + STBI__SCAN_header +}; + +static void stbi__refill_buffer(stbi__context* s) +{ + int n = (s->io.read)(s->io_user_data, (char*)s->buffer_start, s->buflen); + s->callback_already_read += (int)(s->img_buffer - s->img_buffer_original); + if (n == 0) { + // at end of file, treat same as if from memory, but need to handle case + // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file + s->read_from_callbacks = 0; + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + 1; + *s->img_buffer = 0; + } + else { + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + n; + } +} + +stbi_inline static stbi_uc stbi__get8(stbi__context* s) +{ + if (s->img_buffer < s->img_buffer_end) + return *s->img_buffer++; + if (s->read_from_callbacks) { + stbi__refill_buffer(s); + return *s->img_buffer++; + } + return 0; +} + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +stbi_inline static int stbi__at_eof(stbi__context* s) +{ + if (s->io.read) { + if (!(s->io.eof)(s->io_user_data)) return 0; + // if feof() is true, check if buffer = end + // special case: we've only got the special 0 character at the end + if (s->read_from_callbacks == 0) return 1; + } + + return s->img_buffer >= s->img_buffer_end; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) +// nothing +#else +static void stbi__skip(stbi__context* s, int n) +{ + if (n == 0) return; // already there! + if (n < 0) { + s->img_buffer = s->img_buffer_end; + return; + } + if (s->io.read) { + int blen = (int)(s->img_buffer_end - s->img_buffer); + if (blen < n) { + s->img_buffer = s->img_buffer_end; + (s->io.skip)(s->io_user_data, n - blen); + return; + } + } + s->img_buffer += n; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) +// nothing +#else +static int stbi__getn(stbi__context* s, stbi_uc* buffer, int n) +{ + if (s->io.read) { + int blen = (int)(s->img_buffer_end - s->img_buffer); + if (blen < n) { + int res, count; + + memcpy(buffer, s->img_buffer, blen); + + count = (s->io.read)(s->io_user_data, (char*)buffer + blen, n - blen); + res = (count == (n - blen)); + s->img_buffer = s->img_buffer_end; + return res; + } + } + + if (s->img_buffer + n <= s->img_buffer_end) { + memcpy(buffer, s->img_buffer, n); + s->img_buffer += n; + return 1; + } + else + return 0; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static int stbi__get16be(stbi__context* s) +{ + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static stbi__uint32 stbi__get32be(stbi__context* s) +{ + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); +} +#endif + +#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) +// nothing +#else +static int stbi__get16le(stbi__context* s) +{ + int z = stbi__get8(s); + return z + (stbi__get8(s) << 8); +} +#endif + +#ifndef STBI_NO_BMP +static stbi__uint32 stbi__get32le(stbi__context* s) +{ + stbi__uint32 z = stbi__get16le(s); + z += (stbi__uint32)stbi__get16le(s) << 16; + return z; +} +#endif + +#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +////////////////////////////////////////////////////////////////////////////// +// +// generic converter from built-in img_n to req_comp +// individual types do this automatically as much as possible (e.g. jpeg +// does all cases internally since it needs to colorspace convert anyway, +// and it never has alpha, so very few cases ). png can automatically +// interleave an alpha=255 channel, but falls back to this for other cases +// +// assume data buffer is malloced, so malloc a new one and free that one +// only failure mode is malloc failing + +static stbi_uc stbi__compute_y(int r, int g, int b) +{ + return (stbi_uc)(((r * 77) + (g * 150) + (29 * b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +static unsigned char* stbi__convert_format(unsigned char* data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i, j; + unsigned char* good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (unsigned char*)stbi__malloc_mad3(req_comp, x, y, 0); + if (good == NULL) { + STBI_FREE(data); + return stbi__errpuc("outofmem", "Out of memory"); + } + + for (j = 0; j < (int)y; ++j) { + unsigned char* src = data + j * x * img_n; + unsigned char* dest = good + j * x * req_comp; + +#define STBI__COMBO(a,b) ((a)*8+(b)) +#define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1, 2) { dest[0] = src[0]; dest[1] = 255; } break; + STBI__CASE(1, 3) { dest[0] = dest[1] = dest[2] = src[0]; } break; + STBI__CASE(1, 4) { dest[0] = dest[1] = dest[2] = src[0]; dest[3] = 255; } break; + STBI__CASE(2, 1) { dest[0] = src[0]; } break; + STBI__CASE(2, 3) { dest[0] = dest[1] = dest[2] = src[0]; } break; + STBI__CASE(2, 4) { dest[0] = dest[1] = dest[2] = src[0]; dest[3] = src[1]; } break; + STBI__CASE(3, 4) { dest[0] = src[0]; dest[1] = src[1]; dest[2] = src[2]; dest[3] = 255; } break; + STBI__CASE(3, 1) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); } break; + STBI__CASE(3, 2) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); dest[1] = 255; } break; + STBI__CASE(4, 1) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); } break; + STBI__CASE(4, 2) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); dest[1] = src[3]; } break; + STBI__CASE(4, 3) { dest[0] = src[0]; dest[1] = src[1]; dest[2] = src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); + } +#undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) +{ + return (stbi__uint16)(((r * 77) + (g * 150) + (29 * b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16* stbi__convert_format16(stbi__uint16* data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i, j; + stbi__uint16* good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (stbi__uint16*)stbi__malloc(req_comp * x * y * 2); + if (good == NULL) { + STBI_FREE(data); + return (stbi__uint16*)stbi__errpuc("outofmem", "Out of memory"); + } + + for (j = 0; j < (int)y; ++j) { + stbi__uint16* src = data + j * x * img_n; + stbi__uint16* dest = good + j * x * req_comp; + +#define STBI__COMBO(a,b) ((a)*8+(b)) +#define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1, 2) { dest[0] = src[0]; dest[1] = 0xffff; } break; + STBI__CASE(1, 3) { dest[0] = dest[1] = dest[2] = src[0]; } break; + STBI__CASE(1, 4) { dest[0] = dest[1] = dest[2] = src[0]; dest[3] = 0xffff; } break; + STBI__CASE(2, 1) { dest[0] = src[0]; } break; + STBI__CASE(2, 3) { dest[0] = dest[1] = dest[2] = src[0]; } break; + STBI__CASE(2, 4) { dest[0] = dest[1] = dest[2] = src[0]; dest[3] = src[1]; } break; + STBI__CASE(3, 4) { dest[0] = src[0]; dest[1] = src[1]; dest[2] = src[2]; dest[3] = 0xffff; } break; + STBI__CASE(3, 1) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); } break; + STBI__CASE(3, 2) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); dest[1] = 0xffff; } break; + STBI__CASE(4, 1) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); } break; + STBI__CASE(4, 2) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); dest[1] = src[3]; } break; + STBI__CASE(4, 3) { dest[0] = src[0]; dest[1] = src[1]; dest[2] = src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*)stbi__errpuc("unsupported", "Unsupported format conversion"); + } +#undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#ifndef STBI_NO_LINEAR +static float* stbi__ldr_to_hdr(stbi_uc* data, int x, int y, int comp) +{ + int i, k, n; + float* output; + if (!data) return NULL; + output = (float*)stbi__malloc_mad4(x, y, comp, sizeof(float), 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp - 1; + for (i = 0; i < x * y; ++i) { + for (k = 0; k < n; ++k) { + output[i * comp + k] = (float)(pow(data[i * comp + k] / 255.0f, stbi__l2h_gamma) * stbi__l2h_scale); + } + } + if (n < comp) { + for (i = 0; i < x * y; ++i) { + output[i * comp + n] = data[i * comp + n] / 255.0f; + } + } + STBI_FREE(data); + return output; +} +#endif + +#ifndef STBI_NO_HDR +#define stbi__float2int(x) ((int) (x)) +static stbi_uc* stbi__hdr_to_ldr(float* data, int x, int y, int comp) +{ + int i, k, n; + stbi_uc* output; + if (!data) return NULL; + output = (stbi_uc*)stbi__malloc_mad3(x, y, comp, 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp - 1; + for (i = 0; i < x * y; ++i) { + for (k = 0; k < n; ++k) { + float z = (float)pow(data[i * comp + k] * stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i * comp + k] = (stbi_uc)stbi__float2int(z); + } + if (k < comp) { + float z = data[i * comp + k] * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i * comp + k] = (stbi_uc)stbi__float2int(z); + } + } + STBI_FREE(data); + return output; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// "baseline" JPEG/JFIF decoder +// +// simple implementation +// - doesn't support delayed output of y-dimension +// - simple interface (only one output format: 8-bit interleaved RGB) +// - doesn't try to recover corrupt jpegs +// - doesn't allow partial loading, loading multiple at once +// - still fast on x86 (copying globals into locals doesn't help x86) +// - allocates lots of intermediate memory (full size of all components) +// - non-interleaved case requires this anyway +// - allows good upsampling (see next) +// high-quality +// - upsampled channels are bilinearly interpolated, even across blocks +// - quality integer IDCT derived from IJG's 'slow' +// performance +// - fast huffman; reasonable integer IDCT +// - some SIMD kernels for common paths on targets with SSE2/NEON +// - uses a lot of intermediate memory, could cache poorly + +#ifndef STBI_NO_JPEG + +// huffman decoding acceleration +#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache + +typedef struct +{ + stbi_uc fast[1 << FAST_BITS]; + // weirdly, repacking this into AoS is a 10% speed loss, instead of a win + stbi__uint16 code[256]; + stbi_uc values[256]; + stbi_uc size[257]; + unsigned int maxcode[18]; + int delta[17]; // old 'firstsymbol' - old 'firstcode' +} stbi__huffman; + +typedef struct +{ + stbi__context* s; + stbi__huffman huff_dc[4]; + stbi__huffman huff_ac[4]; + stbi__uint16 dequant[4][64]; + stbi__int16 fast_ac[4][1 << FAST_BITS]; + + // sizes for components, interleaved MCUs + int img_h_max, img_v_max; + int img_mcu_x, img_mcu_y; + int img_mcu_w, img_mcu_h; + + // definition of jpeg image component + struct + { + int id; + int h, v; + int tq; + int hd, ha; + int dc_pred; + + int x, y, w2, h2; + stbi_uc* data; + void* raw_data, * raw_coeff; + stbi_uc* linebuf; + short* coeff; // progressive only + int coeff_w, coeff_h; // number of 8x8 coefficient blocks + } img_comp[4]; + + stbi__uint32 code_buffer; // jpeg entropy-coded buffer + int code_bits; // number of valid bits + unsigned char marker; // marker seen while filling entropy buffer + int nomore; // flag if we saw a marker so must stop + + int progressive; + int spec_start; + int spec_end; + int succ_high; + int succ_low; + int eob_run; + int jfif; + int app14_color_transform; // Adobe APP14 tag + int rgb; + + int scan_n, order[4]; + int restart_interval, todo; + + // kernels + void (*idct_block_kernel)(stbi_uc* out, int out_stride, short data[64]); + void (*YCbCr_to_RGB_kernel)(stbi_uc* out, const stbi_uc* y, const stbi_uc* pcb, const stbi_uc* pcr, int count, int step); + stbi_uc* (*resample_row_hv_2_kernel)(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs); +} stbi__jpeg; + +static int stbi__build_huffman(stbi__huffman* h, int* count) +{ + int i, j, k = 0; + unsigned int code; + // build size list for each symbol (from JPEG spec) + for (i = 0; i < 16; ++i) { + for (j = 0; j < count[i]; ++j) { + h->size[k++] = (stbi_uc)(i + 1); + if (k >= 257) return stbi__err("bad size list", "Corrupt JPEG"); + } + } + h->size[k] = 0; + + // compute actual symbols (from jpeg spec) + code = 0; + k = 0; + for (j = 1; j <= 16; ++j) { + // compute delta to add to code to compute symbol id + h->delta[j] = k - code; + if (h->size[k] == j) { + while (h->size[k] == j) + h->code[k++] = (stbi__uint16)(code++); + if (code - 1 >= (1u << j)) return stbi__err("bad code lengths", "Corrupt JPEG"); + } + // compute largest code + 1 for this size, preshifted as needed later + h->maxcode[j] = code << (16 - j); + code <<= 1; + } + h->maxcode[j] = 0xffffffff; + + // build non-spec acceleration table; 255 is flag for not-accelerated + memset(h->fast, 255, 1 << FAST_BITS); + for (i = 0; i < k; ++i) { + int s = h->size[i]; + if (s <= FAST_BITS) { + int c = h->code[i] << (FAST_BITS - s); + int m = 1 << (FAST_BITS - s); + for (j = 0; j < m; ++j) { + h->fast[c + j] = (stbi_uc)i; + } + } + } + return 1; +} + +// build a table that decodes both magnitude and value of small ACs in +// one go. +static void stbi__build_fast_ac(stbi__int16* fast_ac, stbi__huffman* h) +{ + int i; + for (i = 0; i < (1 << FAST_BITS); ++i) { + stbi_uc fast = h->fast[i]; + fast_ac[i] = 0; + if (fast < 255) { + int rs = h->values[fast]; + int run = (rs >> 4) & 15; + int magbits = rs & 15; + int len = h->size[fast]; + + if (magbits && len + magbits <= FAST_BITS) { + // magnitude code followed by receive_extend code + int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); + int m = 1 << (magbits - 1); + if (k < m) k += (~0U << magbits) + 1; + // if the result is small enough, we can fit it in fast_ac table + if (k >= -128 && k <= 127) + fast_ac[i] = (stbi__int16)((k * 256) + (run * 16) + (len + magbits)); + } + } + } +} + +static void stbi__grow_buffer_unsafe(stbi__jpeg* j) +{ + do { + unsigned int b = j->nomore ? 0 : stbi__get8(j->s); + if (b == 0xff) { + int c = stbi__get8(j->s); + while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes + if (c != 0) { + j->marker = (unsigned char)c; + j->nomore = 1; + return; + } + } + j->code_buffer |= b << (24 - j->code_bits); + j->code_bits += 8; + } while (j->code_bits <= 24); +} + +// (1 << n) - 1 +static const stbi__uint32 stbi__bmask[17] = { 0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535 }; + +// decode a jpeg huffman value from the bitstream +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg* j, stbi__huffman* h) +{ + unsigned int temp; + int c, k; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + // look at the top FAST_BITS and determine what symbol ID it is, + // if the code is <= FAST_BITS + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1); + k = h->fast[c]; + if (k < 255) { + int s = h->size[k]; + if (s > j->code_bits) + return -1; + j->code_buffer <<= s; + j->code_bits -= s; + return h->values[k]; + } + + // naive test is to shift the code_buffer down so k bits are + // valid, then test against maxcode. To speed this up, we've + // preshifted maxcode left so that it has (16-k) 0s at the + // end; in other words, regardless of the number of bits, it + // wants to be compared against something shifted to have 16; + // that way we don't need to shift inside the loop. + temp = j->code_buffer >> 16; + for (k = FAST_BITS + 1; ; ++k) + if (temp < h->maxcode[k]) + break; + if (k == 17) { + // error! code not found + j->code_bits -= 16; + return -1; + } + + if (k > j->code_bits) + return -1; + + // convert the huffman code to the symbol id + c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + if (c < 0 || c >= 256) // symbol id out of bounds! + return -1; + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); + + // convert the id to a symbol + j->code_bits -= k; + j->code_buffer <<= k; + return h->values[c]; +} + +// bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing + + sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative) + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k + (stbi__jbias[n] & (sgn - 1)); +} + +// get some unsigned bits +stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg* j, int n) +{ + unsigned int k; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k; +} + +stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg* j) +{ + unsigned int k; + if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing + k = j->code_buffer; + j->code_buffer <<= 1; + --j->code_bits; + return k & 0x80000000; +} + +// given a value that's at position X in the zigzag stream, +// where does it appear in the 8x8 matrix coded as row-major? +static const stbi_uc stbi__jpeg_dezigzag[64 + 15] = +{ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + // let corrupt input sample past end + 63, 63, 63, 63, 63, 63, 63, 63, + 63, 63, 63, 63, 63, 63, 63 +}; + +// decode one 64-entry block-- +static int stbi__jpeg_decode_block(stbi__jpeg* j, short data[64], stbi__huffman* hdc, stbi__huffman* hac, stbi__int16* fac, int b, stbi__uint16* dequant) +{ + int diff, dc, k; + int t; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("bad huffman code", "Corrupt JPEG"); + + // 0 all the ac values now so we can do it 32-bits at a time + memset(data, 0, 64 * sizeof(data[0])); + + diff = t ? stbi__extend_receive(j, t) : 0; + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short)(dc * dequant[0]); + + // decode AC components, see JPEG spec + k = 1; + do { + unsigned int zig; + int c, r, s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short)((r >> 8) * dequant[zig]); + } + else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (rs != 0xf0) break; // end block + k += 16; + } + else { + k += r; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short)(stbi__extend_receive(j, s) * dequant[zig]); + } + } + } while (k < 64); + return 1; +} + +static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg* j, short data[64], stbi__huffman* hdc, int b) +{ + int diff, dc; + int t; + if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + if (j->succ_high == 0) { + // first scan for DC coefficient, must be first + memset(data, 0, 64 * sizeof(data[0])); // 0 all the ac values now + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + diff = t ? stbi__extend_receive(j, t) : 0; + + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short)(dc * (1 << j->succ_low)); + } + else { + // refinement scan for DC coefficient + if (stbi__jpeg_get_bit(j)) + data[0] += (short)(1 << j->succ_low); + } + return 1; +} + +// @OPTIMIZE: store non-zigzagged during the decode passes, +// and only de-zigzag when dequantizing +static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg* j, short data[64], stbi__huffman* hac, stbi__int16* fac) +{ + int k; + if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->succ_high == 0) { + int shift = j->succ_low; + + if (j->eob_run) { + --j->eob_run; + return 1; + } + + k = j->spec_start; + do { + unsigned int zig; + int c, r, s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short)((r >> 8) * (1 << shift)); + } + else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r); + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + --j->eob_run; + break; + } + k += 16; + } + else { + k += r; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short)(stbi__extend_receive(j, s) * (1 << shift)); + } + } + } while (k <= j->spec_end); + } + else { + // refinement scan for these AC coefficients + + short bit = (short)(1 << j->succ_low); + + if (j->eob_run) { + --j->eob_run; + for (k = j->spec_start; k <= j->spec_end; ++k) { + short* p = &data[stbi__jpeg_dezigzag[k]]; + if (*p != 0) + if (stbi__jpeg_get_bit(j)) + if ((*p & bit) == 0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } + } + else { + k = j->spec_start; + do { + int r, s; + int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh + if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r) - 1; + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + r = 64; // force end of block + } + else { + // r=15 s=0 should write 16 0s, so we just do + // a run of 15 0s and then write s (which is 0), + // so we don't have to do anything special here + } + } + else { + if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); + // sign bit + if (stbi__jpeg_get_bit(j)) + s = bit; + else + s = -bit; + } + + // advance by r + while (k <= j->spec_end) { + short* p = &data[stbi__jpeg_dezigzag[k++]]; + if (*p != 0) { + if (stbi__jpeg_get_bit(j)) + if ((*p & bit) == 0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } + else { + if (r == 0) { + *p = (short)s; + break; + } + --r; + } + } + } while (k <= j->spec_end); + } + } + return 1; +} + +// take a -128..127 value and stbi__clamp it and convert to 0..255 +stbi_inline static stbi_uc stbi__clamp(int x) +{ + // trick to use a single test to catch both cases + if ((unsigned int)x > 255) { + if (x < 0) return 0; + if (x > 255) return 255; + } + return (stbi_uc)x; +} + +#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) +#define stbi__fsh(x) ((x) * 4096) + +// derived from jidctint -- DCT_ISLOW +#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ + int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ + p2 = s2; \ + p3 = s6; \ + p1 = (p2+p3) * stbi__f2f(0.5411961f); \ + t2 = p1 + p3*stbi__f2f(-1.847759065f); \ + t3 = p1 + p2*stbi__f2f( 0.765366865f); \ + p2 = s0; \ + p3 = s4; \ + t0 = stbi__fsh(p2+p3); \ + t1 = stbi__fsh(p2-p3); \ + x0 = t0+t3; \ + x3 = t0-t3; \ + x1 = t1+t2; \ + x2 = t1-t2; \ + t0 = s7; \ + t1 = s5; \ + t2 = s3; \ + t3 = s1; \ + p3 = t0+t2; \ + p4 = t1+t3; \ + p1 = t0+t3; \ + p2 = t1+t2; \ + p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ + t0 = t0*stbi__f2f( 0.298631336f); \ + t1 = t1*stbi__f2f( 2.053119869f); \ + t2 = t2*stbi__f2f( 3.072711026f); \ + t3 = t3*stbi__f2f( 1.501321110f); \ + p1 = p5 + p1*stbi__f2f(-0.899976223f); \ + p2 = p5 + p2*stbi__f2f(-2.562915447f); \ + p3 = p3*stbi__f2f(-1.961570560f); \ + p4 = p4*stbi__f2f(-0.390180644f); \ + t3 += p1+p4; \ + t2 += p2+p3; \ + t1 += p2+p4; \ + t0 += p1+p3; + +static void stbi__idct_block(stbi_uc* out, int out_stride, short data[64]) +{ + int i, val[64], * v = val; + stbi_uc* o; + short* d = data; + + // columns + for (i = 0; i < 8; ++i, ++d, ++v) { + // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing + if (d[8] == 0 && d[16] == 0 && d[24] == 0 && d[32] == 0 + && d[40] == 0 && d[48] == 0 && d[56] == 0) { + // no shortcut 0 seconds + // (1|2|3|4|5|6|7)==0 0 seconds + // all separate -0.047 seconds + // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds + int dcterm = d[0] * 4; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; + } + else { + STBI__IDCT_1D(d[0], d[8], d[16], d[24], d[32], d[40], d[48], d[56]) + // constants scaled things up by 1<<12; let's bring them back + // down, but keep 2 extra bits of precision + x0 += 512; x1 += 512; x2 += 512; x3 += 512; + v[0] = (x0 + t3) >> 10; + v[56] = (x0 - t3) >> 10; + v[8] = (x1 + t2) >> 10; + v[48] = (x1 - t2) >> 10; + v[16] = (x2 + t1) >> 10; + v[40] = (x2 - t1) >> 10; + v[24] = (x3 + t0) >> 10; + v[32] = (x3 - t0) >> 10; + } + } + + for (i = 0, v = val, o = out; i < 8; ++i, v += 8, o += out_stride) { + // no fast case since the first 1D IDCT spread components out + STBI__IDCT_1D(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]) + // constants scaled things up by 1<<12, plus we had 1<<2 from first + // loop, plus horizontal and vertical each scale by sqrt(8) so together + // we've got an extra 1<<3, so 1<<17 total we need to remove. + // so we want to round that, which means adding 0.5 * 1<<17, + // aka 65536. Also, we'll end up with -128 to 127 that we want + // to encode as 0..255 by adding 128, so we'll add that before the shift + x0 += 65536 + (128 << 17); + x1 += 65536 + (128 << 17); + x2 += 65536 + (128 << 17); + x3 += 65536 + (128 << 17); + // tried computing the shifts into temps, or'ing the temps to see + // if any were out of range, but that was slower + o[0] = stbi__clamp((x0 + t3) >> 17); + o[7] = stbi__clamp((x0 - t3) >> 17); + o[1] = stbi__clamp((x1 + t2) >> 17); + o[6] = stbi__clamp((x1 - t2) >> 17); + o[2] = stbi__clamp((x2 + t1) >> 17); + o[5] = stbi__clamp((x2 - t1) >> 17); + o[3] = stbi__clamp((x3 + t0) >> 17); + o[4] = stbi__clamp((x3 - t0) >> 17); + } +} + +#ifdef STBI_SSE2 +// sse2 integer IDCT. not the fastest possible implementation but it +// produces bit-identical results to the generic C version so it's +// fully "transparent". +static void stbi__idct_simd(stbi_uc* out, int out_stride, short data[64]) +{ + // This is constructed to match our regular (generic) integer IDCT exactly. + __m128i row0, row1, row2, row3, row4, row5, row6, row7; + __m128i tmp; + + // dot product constant: even elems=x, odd elems=y +#define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) + +// out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) +// out(1) = c1[even]*x + c1[odd]*y +#define dct_rot(out0,out1, x,y,c0,c1) \ + __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ + __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ + __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ + __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ + __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ + __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) + + // out = in << 12 (in 16-bit, out 32-bit) +#define dct_widen(out, in) \ + __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ + __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) + + // wide add +#define dct_wadd(out, a, b) \ + __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_add_epi32(a##_h, b##_h) + + // wide sub +#define dct_wsub(out, a, b) \ + __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) + + // butterfly a/b, add bias, then shift by "s" and pack +#define dct_bfly32o(out0, out1, a,b,bias,s) \ + { \ + __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ + __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ + dct_wadd(sum, abiased, b); \ + dct_wsub(dif, abiased, b); \ + out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ + out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ + } + + // 8-bit interleave step (for transposes) +#define dct_interleave8(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi8(a, b); \ + b = _mm_unpackhi_epi8(tmp, b) + + // 16-bit interleave step (for transposes) +#define dct_interleave16(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi16(a, b); \ + b = _mm_unpackhi_epi16(tmp, b) + +#define dct_pass(bias,shift) \ + { \ + /* even part */ \ + dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ + __m128i sum04 = _mm_add_epi16(row0, row4); \ + __m128i dif04 = _mm_sub_epi16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ + dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ + __m128i sum17 = _mm_add_epi16(row1, row7); \ + __m128i sum35 = _mm_add_epi16(row3, row5); \ + dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ + dct_wadd(x4, y0o, y4o); \ + dct_wadd(x5, y1o, y5o); \ + dct_wadd(x6, y2o, y5o); \ + dct_wadd(x7, y3o, y4o); \ + dct_bfly32o(row0,row7, x0,x7,bias,shift); \ + dct_bfly32o(row1,row6, x1,x6,bias,shift); \ + dct_bfly32o(row2,row5, x2,x5,bias,shift); \ + dct_bfly32o(row3,row4, x3,x4,bias,shift); \ + } + + __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); + __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f(0.765366865f), stbi__f2f(0.5411961f)); + __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); + __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); + __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f(0.298631336f), stbi__f2f(-1.961570560f)); + __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f(3.072711026f)); + __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f(2.053119869f), stbi__f2f(-0.390180644f)); + __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f(1.501321110f)); + + // rounding biases in column/row passes, see stbi__idct_block for explanation. + __m128i bias_0 = _mm_set1_epi32(512); + __m128i bias_1 = _mm_set1_epi32(65536 + (128 << 17)); + + // load + row0 = _mm_load_si128((const __m128i*) (data + 0 * 8)); + row1 = _mm_load_si128((const __m128i*) (data + 1 * 8)); + row2 = _mm_load_si128((const __m128i*) (data + 2 * 8)); + row3 = _mm_load_si128((const __m128i*) (data + 3 * 8)); + row4 = _mm_load_si128((const __m128i*) (data + 4 * 8)); + row5 = _mm_load_si128((const __m128i*) (data + 5 * 8)); + row6 = _mm_load_si128((const __m128i*) (data + 6 * 8)); + row7 = _mm_load_si128((const __m128i*) (data + 7 * 8)); + + // column pass + dct_pass(bias_0, 10); + + { + // 16bit 8x8 transpose pass 1 + dct_interleave16(row0, row4); + dct_interleave16(row1, row5); + dct_interleave16(row2, row6); + dct_interleave16(row3, row7); + + // transpose pass 2 + dct_interleave16(row0, row2); + dct_interleave16(row1, row3); + dct_interleave16(row4, row6); + dct_interleave16(row5, row7); + + // transpose pass 3 + dct_interleave16(row0, row1); + dct_interleave16(row2, row3); + dct_interleave16(row4, row5); + dct_interleave16(row6, row7); + } + + // row pass + dct_pass(bias_1, 17); + + { + // pack + __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 + __m128i p1 = _mm_packus_epi16(row2, row3); + __m128i p2 = _mm_packus_epi16(row4, row5); + __m128i p3 = _mm_packus_epi16(row6, row7); + + // 8bit 8x8 transpose pass 1 + dct_interleave8(p0, p2); // a0e0a1e1... + dct_interleave8(p1, p3); // c0g0c1g1... + + // transpose pass 2 + dct_interleave8(p0, p1); // a0c0e0g0... + dct_interleave8(p2, p3); // b0d0f0h0... + + // transpose pass 3 + dct_interleave8(p0, p2); // a0b0c0d0... + dct_interleave8(p1, p3); // a4b4c4d4... + + // store + _mm_storel_epi64((__m128i*) out, p0); out += out_stride; + _mm_storel_epi64((__m128i*) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i*) out, p2); out += out_stride; + _mm_storel_epi64((__m128i*) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i*) out, p1); out += out_stride; + _mm_storel_epi64((__m128i*) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i*) out, p3); out += out_stride; + _mm_storel_epi64((__m128i*) out, _mm_shuffle_epi32(p3, 0x4e)); + } + +#undef dct_const +#undef dct_rot +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_interleave8 +#undef dct_interleave16 +#undef dct_pass +} + +#endif // STBI_SSE2 + +#ifdef STBI_NEON + +// NEON integer IDCT. should produce bit-identical +// results to the generic C version. +static void stbi__idct_simd(stbi_uc* out, int out_stride, short data[64]) +{ + int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; + + int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); + int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); + int16x4_t rot0_2 = vdup_n_s16(stbi__f2f(0.765366865f)); + int16x4_t rot1_0 = vdup_n_s16(stbi__f2f(1.175875602f)); + int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); + int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); + int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); + int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); + int16x4_t rot3_0 = vdup_n_s16(stbi__f2f(0.298631336f)); + int16x4_t rot3_1 = vdup_n_s16(stbi__f2f(2.053119869f)); + int16x4_t rot3_2 = vdup_n_s16(stbi__f2f(3.072711026f)); + int16x4_t rot3_3 = vdup_n_s16(stbi__f2f(1.501321110f)); + +#define dct_long_mul(out, inq, coeff) \ + int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) + +#define dct_long_mac(out, acc, inq, coeff) \ + int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) + +#define dct_widen(out, inq) \ + int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ + int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) + + // wide add +#define dct_wadd(out, a, b) \ + int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vaddq_s32(a##_h, b##_h) + +// wide sub +#define dct_wsub(out, a, b) \ + int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vsubq_s32(a##_h, b##_h) + +// butterfly a/b, then shift using "shiftop" by "s" and pack +#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ + { \ + dct_wadd(sum, a, b); \ + dct_wsub(dif, a, b); \ + out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ + out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ + } + +#define dct_pass(shiftop, shift) \ + { \ + /* even part */ \ + int16x8_t sum26 = vaddq_s16(row2, row6); \ + dct_long_mul(p1e, sum26, rot0_0); \ + dct_long_mac(t2e, p1e, row6, rot0_1); \ + dct_long_mac(t3e, p1e, row2, rot0_2); \ + int16x8_t sum04 = vaddq_s16(row0, row4); \ + int16x8_t dif04 = vsubq_s16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + int16x8_t sum15 = vaddq_s16(row1, row5); \ + int16x8_t sum17 = vaddq_s16(row1, row7); \ + int16x8_t sum35 = vaddq_s16(row3, row5); \ + int16x8_t sum37 = vaddq_s16(row3, row7); \ + int16x8_t sumodd = vaddq_s16(sum17, sum35); \ + dct_long_mul(p5o, sumodd, rot1_0); \ + dct_long_mac(p1o, p5o, sum17, rot1_1); \ + dct_long_mac(p2o, p5o, sum35, rot1_2); \ + dct_long_mul(p3o, sum37, rot2_0); \ + dct_long_mul(p4o, sum15, rot2_1); \ + dct_wadd(sump13o, p1o, p3o); \ + dct_wadd(sump24o, p2o, p4o); \ + dct_wadd(sump23o, p2o, p3o); \ + dct_wadd(sump14o, p1o, p4o); \ + dct_long_mac(x4, sump13o, row7, rot3_0); \ + dct_long_mac(x5, sump24o, row5, rot3_1); \ + dct_long_mac(x6, sump23o, row3, rot3_2); \ + dct_long_mac(x7, sump14o, row1, rot3_3); \ + dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ + dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ + dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ + dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ + } + + // load + row0 = vld1q_s16(data + 0 * 8); + row1 = vld1q_s16(data + 1 * 8); + row2 = vld1q_s16(data + 2 * 8); + row3 = vld1q_s16(data + 3 * 8); + row4 = vld1q_s16(data + 4 * 8); + row5 = vld1q_s16(data + 5 * 8); + row6 = vld1q_s16(data + 6 * 8); + row7 = vld1q_s16(data + 7 * 8); + + // add DC bias + row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); + + // column pass + dct_pass(vrshrn_n_s32, 10); + + // 16bit 8x8 transpose + { + // these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. + // whether compilers actually get this is another story, sadly. +#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } +#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } + + // pass 1 + dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 + dct_trn16(row2, row3); + dct_trn16(row4, row5); + dct_trn16(row6, row7); + + // pass 2 + dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 + dct_trn32(row1, row3); + dct_trn32(row4, row6); + dct_trn32(row5, row7); + + // pass 3 + dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 + dct_trn64(row1, row5); + dct_trn64(row2, row6); + dct_trn64(row3, row7); + +#undef dct_trn16 +#undef dct_trn32 +#undef dct_trn64 + } + + // row pass + // vrshrn_n_s32 only supports shifts up to 16, we need + // 17. so do a non-rounding shift of 16 first then follow + // up with a rounding shift by 1. + dct_pass(vshrn_n_s32, 16); + + { + // pack and round + uint8x8_t p0 = vqrshrun_n_s16(row0, 1); + uint8x8_t p1 = vqrshrun_n_s16(row1, 1); + uint8x8_t p2 = vqrshrun_n_s16(row2, 1); + uint8x8_t p3 = vqrshrun_n_s16(row3, 1); + uint8x8_t p4 = vqrshrun_n_s16(row4, 1); + uint8x8_t p5 = vqrshrun_n_s16(row5, 1); + uint8x8_t p6 = vqrshrun_n_s16(row6, 1); + uint8x8_t p7 = vqrshrun_n_s16(row7, 1); + + // again, these can translate into one instruction, but often don't. +#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } +#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } + + // sadly can't use interleaved stores here since we only write + // 8 bytes to each scan line! + + // 8x8 8-bit transpose pass 1 + dct_trn8_8(p0, p1); + dct_trn8_8(p2, p3); + dct_trn8_8(p4, p5); + dct_trn8_8(p6, p7); + + // pass 2 + dct_trn8_16(p0, p2); + dct_trn8_16(p1, p3); + dct_trn8_16(p4, p6); + dct_trn8_16(p5, p7); + + // pass 3 + dct_trn8_32(p0, p4); + dct_trn8_32(p1, p5); + dct_trn8_32(p2, p6); + dct_trn8_32(p3, p7); + + // store + vst1_u8(out, p0); out += out_stride; + vst1_u8(out, p1); out += out_stride; + vst1_u8(out, p2); out += out_stride; + vst1_u8(out, p3); out += out_stride; + vst1_u8(out, p4); out += out_stride; + vst1_u8(out, p5); out += out_stride; + vst1_u8(out, p6); out += out_stride; + vst1_u8(out, p7); + +#undef dct_trn8_8 +#undef dct_trn8_16 +#undef dct_trn8_32 + } + +#undef dct_long_mul +#undef dct_long_mac +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_pass +} + +#endif // STBI_NEON + +#define STBI__MARKER_none 0xff +// if there's a pending marker from the entropy stream, return that +// otherwise, fetch from the stream and get a marker. if there's no +// marker, return 0xff, which is never a valid marker value +static stbi_uc stbi__get_marker(stbi__jpeg* j) +{ + stbi_uc x; + if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } + x = stbi__get8(j->s); + if (x != 0xff) return STBI__MARKER_none; + while (x == 0xff) + x = stbi__get8(j->s); // consume repeated 0xff fill bytes + return x; +} + +// in each scan, we'll have scan_n components, and the order +// of the components is specified by order[] +#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) + +// after a restart interval, stbi__jpeg_reset the entropy decoder and +// the dc prediction +static void stbi__jpeg_reset(stbi__jpeg* j) +{ + j->code_bits = 0; + j->code_buffer = 0; + j->nomore = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; + j->marker = STBI__MARKER_none; + j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; + j->eob_run = 0; + // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, + // since we don't even allow 1<<30 pixels +} + +static int stbi__parse_entropy_coded_data(stbi__jpeg* z) +{ + stbi__jpeg_reset(z); + if (!z->progressive) { + if (z->scan_n == 1) { + int i, j; + STBI_SIMD_ALIGN(short, data[64]); + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x + 7) >> 3; + int h = (z->img_comp[n].y + 7) >> 3; + for (j = 0; j < h; ++j) { + for (i = 0; i < w; ++i) { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc + z->img_comp[n].hd, z->huff_ac + ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8, z->img_comp[n].w2, data); + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get corrupt data + // rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + else { // interleaved + int i, j, k, x, y; + STBI_SIMD_ALIGN(short, data[64]); + for (j = 0; j < z->img_mcu_y; ++j) { + for (i = 0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k = 0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y = 0; y < z->img_comp[n].v; ++y) { + for (x = 0; x < z->img_comp[n].h; ++x) { + int x2 = (i * z->img_comp[n].h + x) * 8; + int y2 = (j * z->img_comp[n].v + y) * 8; + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc + z->img_comp[n].hd, z->huff_ac + ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2 * y2 + x2, z->img_comp[n].w2, data); + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } + else { + if (z->scan_n == 1) { + int i, j; + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x + 7) >> 3; + int h = (z->img_comp[n].y + 7) >> 3; + for (j = 0; j < h; ++j) { + for (i = 0; i < w; ++i) { + short* data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + if (z->spec_start == 0) { + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } + else { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) + return 0; + } + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + else { // interleaved + int i, j, k, x, y; + for (j = 0; j < z->img_mcu_y; ++j) { + for (i = 0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k = 0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y = 0; y < z->img_comp[n].v; ++y) { + for (x = 0; x < z->img_comp[n].h; ++x) { + int x2 = (i * z->img_comp[n].h + x); + int y2 = (j * z->img_comp[n].v + y); + short* data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } +} + +static void stbi__jpeg_dequantize(short* data, stbi__uint16* dequant) +{ + int i; + for (i = 0; i < 64; ++i) + data[i] *= dequant[i]; +} + +static void stbi__jpeg_finish(stbi__jpeg* z) +{ + if (z->progressive) { + // dequantize and idct the data + int i, j, n; + for (n = 0; n < z->s->img_n; ++n) { + int w = (z->img_comp[n].x + 7) >> 3; + int h = (z->img_comp[n].y + 7) >> 3; + for (j = 0; j < h; ++j) { + for (i = 0; i < w; ++i) { + short* data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); + z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8, z->img_comp[n].w2, data); + } + } + } + } +} + +static int stbi__process_marker(stbi__jpeg* z, int m) +{ + int L; + switch (m) { + case STBI__MARKER_none: // no marker found + return stbi__err("expected marker", "Corrupt JPEG"); + + case 0xDD: // DRI - specify restart interval + if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len", "Corrupt JPEG"); + z->restart_interval = stbi__get16be(z->s); + return 1; + + case 0xDB: // DQT - define quantization table + L = stbi__get16be(z->s) - 2; + while (L > 0) { + int q = stbi__get8(z->s); + int p = q >> 4, sixteen = (p != 0); + int t = q & 15, i; + if (p != 0 && p != 1) return stbi__err("bad DQT type", "Corrupt JPEG"); + if (t > 3) return stbi__err("bad DQT table", "Corrupt JPEG"); + + for (i = 0; i < 64; ++i) + z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); + L -= (sixteen ? 129 : 65); + } + return L == 0; + + case 0xC4: // DHT - define huffman table + L = stbi__get16be(z->s) - 2; + while (L > 0) { + stbi_uc* v; + int sizes[16], i, n = 0; + int q = stbi__get8(z->s); + int tc = q >> 4; + int th = q & 15; + if (tc > 1 || th > 3) return stbi__err("bad DHT header", "Corrupt JPEG"); + for (i = 0; i < 16; ++i) { + sizes[i] = stbi__get8(z->s); + n += sizes[i]; + } + if (n > 256) return stbi__err("bad DHT header", "Corrupt JPEG"); // Loop over i < n would write past end of values! + L -= 17; + if (tc == 0) { + if (!stbi__build_huffman(z->huff_dc + th, sizes)) return 0; + v = z->huff_dc[th].values; + } + else { + if (!stbi__build_huffman(z->huff_ac + th, sizes)) return 0; + v = z->huff_ac[th].values; + } + for (i = 0; i < n; ++i) + v[i] = stbi__get8(z->s); + if (tc != 0) + stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); + L -= n; + } + return L == 0; + } + + // check for comment block or APP blocks + if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { + L = stbi__get16be(z->s); + if (L < 2) { + if (m == 0xFE) + return stbi__err("bad COM len", "Corrupt JPEG"); + else + return stbi__err("bad APP len", "Corrupt JPEG"); + } + L -= 2; + + if (m == 0xE0 && L >= 5) { // JFIF APP0 segment + static const unsigned char tag[5] = { 'J','F','I','F','\0' }; + int ok = 1; + int i; + for (i = 0; i < 5; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 5; + if (ok) + z->jfif = 1; + } + else if (m == 0xEE && L >= 12) { // Adobe APP14 segment + static const unsigned char tag[6] = { 'A','d','o','b','e','\0' }; + int ok = 1; + int i; + for (i = 0; i < 6; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 6; + if (ok) { + stbi__get8(z->s); // version + stbi__get16be(z->s); // flags0 + stbi__get16be(z->s); // flags1 + z->app14_color_transform = stbi__get8(z->s); // color transform + L -= 6; + } + } + + stbi__skip(z->s, L); + return 1; + } + + return stbi__err("unknown marker", "Corrupt JPEG"); +} + +// after we see SOS +static int stbi__process_scan_header(stbi__jpeg* z) +{ + int i; + int Ls = stbi__get16be(z->s); + z->scan_n = stbi__get8(z->s); + if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int)z->s->img_n) return stbi__err("bad SOS component count", "Corrupt JPEG"); + if (Ls != 6 + 2 * z->scan_n) return stbi__err("bad SOS len", "Corrupt JPEG"); + for (i = 0; i < z->scan_n; ++i) { + int id = stbi__get8(z->s), which; + int q = stbi__get8(z->s); + for (which = 0; which < z->s->img_n; ++which) + if (z->img_comp[which].id == id) + break; + if (which == z->s->img_n) return 0; // no match + z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff", "Corrupt JPEG"); + z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff", "Corrupt JPEG"); + z->order[i] = which; + } + + { + int aa; + z->spec_start = stbi__get8(z->s); + z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 + aa = stbi__get8(z->s); + z->succ_high = (aa >> 4); + z->succ_low = (aa & 15); + if (z->progressive) { + if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) + return stbi__err("bad SOS", "Corrupt JPEG"); + } + else { + if (z->spec_start != 0) return stbi__err("bad SOS", "Corrupt JPEG"); + if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS", "Corrupt JPEG"); + z->spec_end = 63; + } + } + + return 1; +} + +static int stbi__free_jpeg_components(stbi__jpeg* z, int ncomp, int why) +{ + int i; + for (i = 0; i < ncomp; ++i) { + if (z->img_comp[i].raw_data) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + z->img_comp[i].data = NULL; + } + if (z->img_comp[i].raw_coeff) { + STBI_FREE(z->img_comp[i].raw_coeff); + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].coeff = 0; + } + if (z->img_comp[i].linebuf) { + STBI_FREE(z->img_comp[i].linebuf); + z->img_comp[i].linebuf = NULL; + } + } + return why; +} + +static int stbi__process_frame_header(stbi__jpeg* z, int scan) +{ + stbi__context* s = z->s; + int Lf, p, i, q, h_max = 1, v_max = 1, c; + Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len", "Corrupt JPEG"); // JPEG + p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit", "JPEG format not supported: 8-bit only"); // JPEG baseline + s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG + s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width", "Corrupt JPEG"); // JPEG requires + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large", "Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large", "Very large image (corrupt?)"); + c = stbi__get8(s); + if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count", "Corrupt JPEG"); + s->img_n = c; + for (i = 0; i < c; ++i) { + z->img_comp[i].data = NULL; + z->img_comp[i].linebuf = NULL; + } + + if (Lf != 8 + 3 * s->img_n) return stbi__err("bad SOF len", "Corrupt JPEG"); + + z->rgb = 0; + for (i = 0; i < s->img_n; ++i) { + static const unsigned char rgb[3] = { 'R', 'G', 'B' }; + z->img_comp[i].id = stbi__get8(s); + if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) + ++z->rgb; + q = stbi__get8(s); + z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H", "Corrupt JPEG"); + z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V", "Corrupt JPEG"); + z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ", "Corrupt JPEG"); + } + + if (scan != STBI__SCAN_load) return 1; + + if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); + + for (i = 0; i < s->img_n; ++i) { + if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; + if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; + } + + // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios + // and I've never seen a non-corrupted JPEG file actually use them + for (i = 0; i < s->img_n; ++i) { + if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H", "Corrupt JPEG"); + if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V", "Corrupt JPEG"); + } + + // compute interleaved mcu info + z->img_h_max = h_max; + z->img_v_max = v_max; + z->img_mcu_w = h_max * 8; + z->img_mcu_h = v_max * 8; + // these sizes can't be more than 17 bits + z->img_mcu_x = (s->img_x + z->img_mcu_w - 1) / z->img_mcu_w; + z->img_mcu_y = (s->img_y + z->img_mcu_h - 1) / z->img_mcu_h; + + for (i = 0; i < s->img_n; ++i) { + // number of effective pixels (e.g. for non-interleaved MCU) + z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max - 1) / h_max; + z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max - 1) / v_max; + // to simplify generation, we'll allocate enough memory to decode + // the bogus oversized data from using interleaved MCUs and their + // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't + // discard the extra data until colorspace conversion + // + // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) + // so these muls can't overflow with 32-bit ints (which we require) + z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; + z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].linebuf = NULL; + z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + if (z->img_comp[i].raw_data == NULL) + return stbi__free_jpeg_components(z, i + 1, stbi__err("outofmem", "Out of memory")); + // align blocks for idct using mmx/sse + z->img_comp[i].data = (stbi_uc*)(((size_t)z->img_comp[i].raw_data + 15) & ~15); + if (z->progressive) { + // w2, h2 are multiples of 8 (see above) + z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; + z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; + z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + if (z->img_comp[i].raw_coeff == NULL) + return stbi__free_jpeg_components(z, i + 1, stbi__err("outofmem", "Out of memory")); + z->img_comp[i].coeff = (short*)(((size_t)z->img_comp[i].raw_coeff + 15) & ~15); + } + } + + return 1; +} + +// use comparisons since in some cases we handle more than one case (e.g. SOF) +#define stbi__DNL(x) ((x) == 0xdc) +#define stbi__SOI(x) ((x) == 0xd8) +#define stbi__EOI(x) ((x) == 0xd9) +#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) +#define stbi__SOS(x) ((x) == 0xda) + +#define stbi__SOF_progressive(x) ((x) == 0xc2) + +static int stbi__decode_jpeg_header(stbi__jpeg* z, int scan) +{ + int m; + z->jfif = 0; + z->app14_color_transform = -1; // valid values are 0,1,2 + z->marker = STBI__MARKER_none; // initialize cached marker to empty + m = stbi__get_marker(z); + if (!stbi__SOI(m)) return stbi__err("no SOI", "Corrupt JPEG"); + if (scan == STBI__SCAN_type) return 1; + m = stbi__get_marker(z); + while (!stbi__SOF(m)) { + if (!stbi__process_marker(z, m)) return 0; + m = stbi__get_marker(z); + while (m == STBI__MARKER_none) { + // some files have extra padding after their blocks, so ok, we'll scan + if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); + m = stbi__get_marker(z); + } + } + z->progressive = stbi__SOF_progressive(m); + if (!stbi__process_frame_header(z, scan)) return 0; + return 1; +} + +static stbi_uc stbi__skip_jpeg_junk_at_end(stbi__jpeg* j) +{ + // some JPEGs have junk at end, skip over it but if we find what looks + // like a valid marker, resume there + while (!stbi__at_eof(j->s)) { + stbi_uc x = stbi__get8(j->s); + while (x == 0xff) { // might be a marker + if (stbi__at_eof(j->s)) return STBI__MARKER_none; + x = stbi__get8(j->s); + if (x != 0x00 && x != 0xff) { + // not a stuffed zero or lead-in to another marker, looks + // like an actual marker, return it + return x; + } + // stuffed zero has x=0 now which ends the loop, meaning we go + // back to regular scan loop. + // repeated 0xff keeps trying to read the next byte of the marker. + } + } + return STBI__MARKER_none; +} + +// decode image to YCbCr format +static int stbi__decode_jpeg_image(stbi__jpeg* j) +{ + int m; + for (m = 0; m < 4; m++) { + j->img_comp[m].raw_data = NULL; + j->img_comp[m].raw_coeff = NULL; + } + j->restart_interval = 0; + if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; + m = stbi__get_marker(j); + while (!stbi__EOI(m)) { + if (stbi__SOS(m)) { + if (!stbi__process_scan_header(j)) return 0; + if (!stbi__parse_entropy_coded_data(j)) return 0; + if (j->marker == STBI__MARKER_none) { + j->marker = stbi__skip_jpeg_junk_at_end(j); + // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 + } + m = stbi__get_marker(j); + if (STBI__RESTART(m)) + m = stbi__get_marker(j); + } + else if (stbi__DNL(m)) { + int Ld = stbi__get16be(j->s); + stbi__uint32 NL = stbi__get16be(j->s); + if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); + m = stbi__get_marker(j); + } + else { + if (!stbi__process_marker(j, m)) return 1; + m = stbi__get_marker(j); + } + } + if (j->progressive) + stbi__jpeg_finish(j); + return 1; +} + +// static jfif-centered resampling (across block boundaries) + +typedef stbi_uc* (*resample_row_func)(stbi_uc* out, stbi_uc* in0, stbi_uc* in1, + int w, int hs); + +#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) + +static stbi_uc* resample_row_1(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs) +{ + STBI_NOTUSED(out); + STBI_NOTUSED(in_far); + STBI_NOTUSED(w); + STBI_NOTUSED(hs); + return in_near; +} + +static stbi_uc* stbi__resample_row_v_2(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs) +{ + // need to generate two samples vertically for every one in input + int i; + STBI_NOTUSED(hs); + for (i = 0; i < w; ++i) + out[i] = stbi__div4(3 * in_near[i] + in_far[i] + 2); + return out; +} + +static stbi_uc* stbi__resample_row_h_2(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs) +{ + // need to generate two samples horizontally for every one in input + int i; + stbi_uc* input = in_near; + + if (w == 1) { + // if only one sample, can't do any interpolation + out[0] = out[1] = input[0]; + return out; + } + + out[0] = input[0]; + out[1] = stbi__div4(input[0] * 3 + input[1] + 2); + for (i = 1; i < w - 1; ++i) { + int n = 3 * input[i] + 2; + out[i * 2 + 0] = stbi__div4(n + input[i - 1]); + out[i * 2 + 1] = stbi__div4(n + input[i + 1]); + } + out[i * 2 + 0] = stbi__div4(input[w - 2] * 3 + input[w - 1] + 2); + out[i * 2 + 1] = input[w - 1]; + + STBI_NOTUSED(in_far); + STBI_NOTUSED(hs); + + return out; +} + +#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) + +static stbi_uc* stbi__resample_row_hv_2(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i, t0, t1; + if (w == 1) { + out[0] = out[1] = stbi__div4(3 * in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3 * in_near[0] + in_far[0]; + out[0] = stbi__div4(t1 + 2); + for (i = 1; i < w; ++i) { + t0 = t1; + t1 = 3 * in_near[i] + in_far[i]; + out[i * 2 - 1] = stbi__div16(3 * t0 + t1 + 8); + out[i * 2] = stbi__div16(3 * t1 + t0 + 8); + } + out[w * 2 - 1] = stbi__div4(t1 + 2); + + STBI_NOTUSED(hs); + + return out; +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static stbi_uc* stbi__resample_row_hv_2_simd(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i = 0, t0, t1; + + if (w == 1) { + out[0] = out[1] = stbi__div4(3 * in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3 * in_near[0] + in_far[0]; + // process groups of 8 pixels for as long as we can. + // note we can't handle the last pixel in a row in this loop + // because we need to handle the filter boundary conditions. + for (; i < ((w - 1) & ~7); i += 8) { +#if defined(STBI_SSE2) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + __m128i zero = _mm_setzero_si128(); + __m128i farb = _mm_loadl_epi64((__m128i*) (in_far + i)); + __m128i nearb = _mm_loadl_epi64((__m128i*) (in_near + i)); + __m128i farw = _mm_unpacklo_epi8(farb, zero); + __m128i nearw = _mm_unpacklo_epi8(nearb, zero); + __m128i diff = _mm_sub_epi16(farw, nearw); + __m128i nears = _mm_slli_epi16(nearw, 2); + __m128i curr = _mm_add_epi16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + __m128i prv0 = _mm_slli_si128(curr, 2); + __m128i nxt0 = _mm_srli_si128(curr, 2); + __m128i prev = _mm_insert_epi16(prv0, t1, 0); + __m128i next = _mm_insert_epi16(nxt0, 3 * in_near[i + 8] + in_far[i + 8], 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + __m128i bias = _mm_set1_epi16(8); + __m128i curs = _mm_slli_epi16(curr, 2); + __m128i prvd = _mm_sub_epi16(prev, curr); + __m128i nxtd = _mm_sub_epi16(next, curr); + __m128i curb = _mm_add_epi16(curs, bias); + __m128i even = _mm_add_epi16(prvd, curb); + __m128i odd = _mm_add_epi16(nxtd, curb); + + // interleave even and odd pixels, then undo scaling. + __m128i int0 = _mm_unpacklo_epi16(even, odd); + __m128i int1 = _mm_unpackhi_epi16(even, odd); + __m128i de0 = _mm_srli_epi16(int0, 4); + __m128i de1 = _mm_srli_epi16(int1, 4); + + // pack and write output + __m128i outv = _mm_packus_epi16(de0, de1); + _mm_storeu_si128((__m128i*) (out + i * 2), outv); +#elif defined(STBI_NEON) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + uint8x8_t farb = vld1_u8(in_far + i); + uint8x8_t nearb = vld1_u8(in_near + i); + int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); + int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); + int16x8_t curr = vaddq_s16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + int16x8_t prv0 = vextq_s16(curr, curr, 7); + int16x8_t nxt0 = vextq_s16(curr, curr, 1); + int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); + int16x8_t next = vsetq_lane_s16(3 * in_near[i + 8] + in_far[i + 8], nxt0, 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + int16x8_t curs = vshlq_n_s16(curr, 2); + int16x8_t prvd = vsubq_s16(prev, curr); + int16x8_t nxtd = vsubq_s16(next, curr); + int16x8_t even = vaddq_s16(curs, prvd); + int16x8_t odd = vaddq_s16(curs, nxtd); + + // undo scaling and round, then store with even/odd phases interleaved + uint8x8x2_t o; + o.val[0] = vqrshrun_n_s16(even, 4); + o.val[1] = vqrshrun_n_s16(odd, 4); + vst2_u8(out + i * 2, o); +#endif + + // "previous" value for next iter + t1 = 3 * in_near[i + 7] + in_far[i + 7]; + } + + t0 = t1; + t1 = 3 * in_near[i] + in_far[i]; + out[i * 2] = stbi__div16(3 * t1 + t0 + 8); + + for (++i; i < w; ++i) { + t0 = t1; + t1 = 3 * in_near[i] + in_far[i]; + out[i * 2 - 1] = stbi__div16(3 * t0 + t1 + 8); + out[i * 2] = stbi__div16(3 * t1 + t0 + 8); + } + out[w * 2 - 1] = stbi__div4(t1 + 2); + + STBI_NOTUSED(hs); + + return out; +} +#endif + +static stbi_uc* stbi__resample_row_generic(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, int w, int hs) +{ + // resample with nearest-neighbor + int i, j; + STBI_NOTUSED(in_far); + for (i = 0; i < w; ++i) + for (j = 0; j < hs; ++j) + out[i * hs + j] = in_near[i]; + return out; +} + +// this is a reduced-precision calculation of YCbCr-to-RGB introduced +// to make sure the code produces the same results in both SIMD and scalar +#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) +static void stbi__YCbCr_to_RGB_row(stbi_uc* out, const stbi_uc* y, const stbi_uc* pcb, const stbi_uc* pcr, int count, int step) +{ + int i; + for (i = 0; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1 << 19); // rounding + int r, g, b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr * stbi__float2fixed(1.40200f); + g = y_fixed + (cr * -stbi__float2fixed(0.71414f)) + ((cb * -stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb * stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned)r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned)g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned)b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static void stbi__YCbCr_to_RGB_simd(stbi_uc* out, stbi_uc const* y, stbi_uc const* pcb, stbi_uc const* pcr, int count, int step) +{ + int i = 0; + +#ifdef STBI_SSE2 + // step == 3 is pretty ugly on the final interleave, and i'm not convinced + // it's useful in practice (you wouldn't use it for textures, for example). + // so just accelerate step == 4 case. + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + __m128i signflip = _mm_set1_epi8(-0x80); + __m128i cr_const0 = _mm_set1_epi16((short)(1.40200f * 4096.0f + 0.5f)); + __m128i cr_const1 = _mm_set1_epi16(-(short)(0.71414f * 4096.0f + 0.5f)); + __m128i cb_const0 = _mm_set1_epi16(-(short)(0.34414f * 4096.0f + 0.5f)); + __m128i cb_const1 = _mm_set1_epi16((short)(1.77200f * 4096.0f + 0.5f)); + __m128i y_bias = _mm_set1_epi8((char)(unsigned char)128); + __m128i xw = _mm_set1_epi16(255); // alpha channel + + for (; i + 7 < count; i += 8) { + // load + __m128i y_bytes = _mm_loadl_epi64((__m128i*) (y + i)); + __m128i cr_bytes = _mm_loadl_epi64((__m128i*) (pcr + i)); + __m128i cb_bytes = _mm_loadl_epi64((__m128i*) (pcb + i)); + __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 + __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 + + // unpack to short (and left-shift cr, cb by 8) + __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); + __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); + __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); + + // color transform + __m128i yws = _mm_srli_epi16(yw, 4); + __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); + __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); + __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); + __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); + __m128i rws = _mm_add_epi16(cr0, yws); + __m128i gwt = _mm_add_epi16(cb0, yws); + __m128i bws = _mm_add_epi16(yws, cb1); + __m128i gws = _mm_add_epi16(gwt, cr1); + + // descale + __m128i rw = _mm_srai_epi16(rws, 4); + __m128i bw = _mm_srai_epi16(bws, 4); + __m128i gw = _mm_srai_epi16(gws, 4); + + // back to byte, set up for transpose + __m128i brb = _mm_packus_epi16(rw, bw); + __m128i gxb = _mm_packus_epi16(gw, xw); + + // transpose to interleave channels + __m128i t0 = _mm_unpacklo_epi8(brb, gxb); + __m128i t1 = _mm_unpackhi_epi8(brb, gxb); + __m128i o0 = _mm_unpacklo_epi16(t0, t1); + __m128i o1 = _mm_unpackhi_epi16(t0, t1); + + // store + _mm_storeu_si128((__m128i*) (out + 0), o0); + _mm_storeu_si128((__m128i*) (out + 16), o1); + out += 32; + } + } +#endif + +#ifdef STBI_NEON + // in this version, step=3 support would be easy to add. but is there demand? + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + uint8x8_t signflip = vdup_n_u8(0x80); + int16x8_t cr_const0 = vdupq_n_s16((short)(1.40200f * 4096.0f + 0.5f)); + int16x8_t cr_const1 = vdupq_n_s16(-(short)(0.71414f * 4096.0f + 0.5f)); + int16x8_t cb_const0 = vdupq_n_s16(-(short)(0.34414f * 4096.0f + 0.5f)); + int16x8_t cb_const1 = vdupq_n_s16((short)(1.77200f * 4096.0f + 0.5f)); + + for (; i + 7 < count; i += 8) { + // load + uint8x8_t y_bytes = vld1_u8(y + i); + uint8x8_t cr_bytes = vld1_u8(pcr + i); + uint8x8_t cb_bytes = vld1_u8(pcb + i); + int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); + int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); + + // expand to s16 + int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); + int16x8_t crw = vshll_n_s8(cr_biased, 7); + int16x8_t cbw = vshll_n_s8(cb_biased, 7); + + // color transform + int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); + int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); + int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); + int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); + int16x8_t rws = vaddq_s16(yws, cr0); + int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); + int16x8_t bws = vaddq_s16(yws, cb1); + + // undo scaling, round, convert to byte + uint8x8x4_t o; + o.val[0] = vqrshrun_n_s16(rws, 4); + o.val[1] = vqrshrun_n_s16(gws, 4); + o.val[2] = vqrshrun_n_s16(bws, 4); + o.val[3] = vdup_n_u8(255); + + // store, interleaving r/g/b/a + vst4_u8(out, o); + out += 8 * 4; + } + } +#endif + + for (; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1 << 19); // rounding + int r, g, b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr * stbi__float2fixed(1.40200f); + g = y_fixed + cr * -stbi__float2fixed(0.71414f) + ((cb * -stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb * stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned)r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned)g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned)b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} +#endif + +// set up the kernels +static void stbi__setup_jpeg(stbi__jpeg* j) +{ + j->idct_block_kernel = stbi__idct_block; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; + +#ifdef STBI_SSE2 + if (stbi__sse2_available()) { + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; + } +#endif + +#ifdef STBI_NEON + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; +#endif +} + +// clean up the temporary component buffers +static void stbi__cleanup_jpeg(stbi__jpeg* j) +{ + stbi__free_jpeg_components(j, j->s->img_n, 0); +} + +typedef struct +{ + resample_row_func resample; + stbi_uc* line0, * line1; + int hs, vs; // expansion factor in each axis + int w_lores; // horizontal pixels pre-expansion + int ystep; // how far through vertical expansion we are + int ypos; // which pre-expansion row we're on +} stbi__resample; + +// fast 0..255 * 0..255 => 0..255 rounded multiplication +static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) +{ + unsigned int t = x * y + 128; + return (stbi_uc)((t + (t >> 8)) >> 8); +} + +static stbi_uc* load_jpeg_image(stbi__jpeg* z, int* out_x, int* out_y, int* comp, int req_comp) +{ + int n, decode_n, is_rgb; + z->s->img_n = 0; // make stbi__cleanup_jpeg safe + + // validate req_comp + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + + // load a jpeg image from whichever source, but leave in YCbCr format + if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } + + // determine actual number of components to generate + n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; + + is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + + if (z->s->img_n == 3 && n < 3 && !is_rgb) + decode_n = 1; + else + decode_n = z->s->img_n; + + // nothing to do if no components requested; check this now to avoid + // accessing uninitialized coutput[0] later + if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; } + + // resample and color-convert + { + int k; + unsigned int i, j; + stbi_uc* output; + stbi_uc* coutput[4] = { NULL, NULL, NULL, NULL }; + + stbi__resample res_comp[4]; + + for (k = 0; k < decode_n; ++k) { + stbi__resample* r = &res_comp[k]; + + // allocate line buffer big enough for upsampling off the edges + // with upsample factor of 4 + z->img_comp[k].linebuf = (stbi_uc*)stbi__malloc(z->s->img_x + 3); + if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + r->hs = z->img_h_max / z->img_comp[k].h; + r->vs = z->img_v_max / z->img_comp[k].v; + r->ystep = r->vs >> 1; + r->w_lores = (z->s->img_x + r->hs - 1) / r->hs; + r->ypos = 0; + r->line0 = r->line1 = z->img_comp[k].data; + + if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; + else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; + else r->resample = stbi__resample_row_generic; + } + + // can't error after this so, this is safe + output = (stbi_uc*)stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); + if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + // now go ahead and resample + for (j = 0; j < z->s->img_y; ++j) { + stbi_uc* out = output + n * z->s->img_x * j; + for (k = 0; k < decode_n; ++k) { + stbi__resample* r = &res_comp[k]; + int y_bot = r->ystep >= (r->vs >> 1); + coutput[k] = r->resample(z->img_comp[k].linebuf, + y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, + r->w_lores, r->hs); + if (++r->ystep >= r->vs) { + r->ystep = 0; + r->line0 = r->line1; + if (++r->ypos < z->img_comp[k].y) + r->line1 += z->img_comp[k].w2; + } + } + if (n >= 3) { + stbi_uc* y = coutput[0]; + if (z->s->img_n == 3) { + if (is_rgb) { + for (i = 0; i < z->s->img_x; ++i) { + out[0] = y[i]; + out[1] = coutput[1][i]; + out[2] = coutput[2][i]; + out[3] = 255; + out += n; + } + } + else { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } + else if (z->s->img_n == 4) { + if (z->app14_color_transform == 0) { // CMYK + for (i = 0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], m); + out[1] = stbi__blinn_8x8(coutput[1][i], m); + out[2] = stbi__blinn_8x8(coutput[2][i], m); + out[3] = 255; + out += n; + } + } + else if (z->app14_color_transform == 2) { // YCCK + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + for (i = 0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], m); + out[1] = stbi__blinn_8x8(255 - out[1], m); + out[2] = stbi__blinn_8x8(255 - out[2], m); + out += n; + } + } + else { // YCbCr + alpha? Ignore the fourth channel for now + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } + else + for (i = 0; i < z->s->img_x; ++i) { + out[0] = out[1] = out[2] = y[i]; + out[3] = 255; // not used if n==3 + out += n; + } + } + else { + if (is_rgb) { + if (n == 1) + for (i = 0; i < z->s->img_x; ++i) + *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + else { + for (i = 0; i < z->s->img_x; ++i, out += 2) { + out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + out[1] = 255; + } + } + } + else if (z->s->img_n == 4 && z->app14_color_transform == 0) { + for (i = 0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + out[0] = stbi__compute_y(r, g, b); + out[1] = 255; + out += n; + } + } + else if (z->s->img_n == 4 && z->app14_color_transform == 2) { + for (i = 0; i < z->s->img_x; ++i) { + out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); + out[1] = 255; + out += n; + } + } + else { + stbi_uc* y = coutput[0]; + if (n == 1) + for (i = 0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i = 0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } + } + } + } + stbi__cleanup_jpeg(z); + *out_x = z->s->img_x; + *out_y = z->s->img_y; + if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output + return output; + } +} + +static void* stbi__jpeg_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri) +{ + unsigned char* result; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__errpuc("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + STBI_NOTUSED(ri); + j->s = s; + stbi__setup_jpeg(j); + result = load_jpeg_image(j, x, y, comp, req_comp); + STBI_FREE(j); + return result; +} + +static int stbi__jpeg_test(stbi__context* s) +{ + int r; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + stbi__setup_jpeg(j); + r = stbi__decode_jpeg_header(j, STBI__SCAN_type); + stbi__rewind(s); + STBI_FREE(j); + return r; +} + +static int stbi__jpeg_info_raw(stbi__jpeg* j, int* x, int* y, int* comp) +{ + if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { + stbi__rewind(j->s); + return 0; + } + if (x) *x = j->s->img_x; + if (y) *y = j->s->img_y; + if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; + return 1; +} + +static int stbi__jpeg_info(stbi__context* s, int* x, int* y, int* comp) +{ + int result; + stbi__jpeg* j = (stbi__jpeg*)(stbi__malloc(sizeof(stbi__jpeg))); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + result = stbi__jpeg_info_raw(j, x, y, comp); + STBI_FREE(j); + return result; +} +#endif + +// public domain zlib decode v0.2 Sean Barrett 2006-11-18 +// simple implementation +// - all input must be provided in an upfront buffer +// - all output is written to a single output buffer (can malloc/realloc) +// performance +// - fast huffman + +#ifndef STBI_NO_ZLIB + +// fast-way is faster to check than jpeg huffman, but slow way is slower +#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables +#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) +#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet + +// zlib-style huffman encoding +// (jpegs packs from left, zlib from right, so can't share code) +typedef struct +{ + stbi__uint16 fast[1 << STBI__ZFAST_BITS]; + stbi__uint16 firstcode[16]; + int maxcode[17]; + stbi__uint16 firstsymbol[16]; + stbi_uc size[STBI__ZNSYMS]; + stbi__uint16 value[STBI__ZNSYMS]; +} stbi__zhuffman; + +stbi_inline static int stbi__bitreverse16(int n) +{ + n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); + n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); + n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); + n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); + return n; +} + +stbi_inline static int stbi__bit_reverse(int v, int bits) +{ + STBI_ASSERT(bits <= 16); + // to bit reverse n bits, reverse 16 and shift + // e.g. 11 bits, bit reverse and shift away 5 + return stbi__bitreverse16(v) >> (16 - bits); +} + +static int stbi__zbuild_huffman(stbi__zhuffman* z, const stbi_uc* sizelist, int num) +{ + int i, k = 0; + int code, next_code[16], sizes[17]; + + // DEFLATE spec for generating codes + memset(sizes, 0, sizeof(sizes)); + memset(z->fast, 0, sizeof(z->fast)); + for (i = 0; i < num; ++i) + ++sizes[sizelist[i]]; + sizes[0] = 0; + for (i = 1; i < 16; ++i) + if (sizes[i] > (1 << i)) + return stbi__err("bad sizes", "Corrupt PNG"); + code = 0; + for (i = 1; i < 16; ++i) { + next_code[i] = code; + z->firstcode[i] = (stbi__uint16)code; + z->firstsymbol[i] = (stbi__uint16)k; + code = (code + sizes[i]); + if (sizes[i]) + if (code - 1 >= (1 << i)) return stbi__err("bad codelengths", "Corrupt PNG"); + z->maxcode[i] = code << (16 - i); // preshift for inner loop + code <<= 1; + k += sizes[i]; + } + z->maxcode[16] = 0x10000; // sentinel + for (i = 0; i < num; ++i) { + int s = sizelist[i]; + if (s) { + int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + stbi__uint16 fastv = (stbi__uint16)((s << 9) | i); + z->size[c] = (stbi_uc)s; + z->value[c] = (stbi__uint16)i; + if (s <= STBI__ZFAST_BITS) { + int j = stbi__bit_reverse(next_code[s], s); + while (j < (1 << STBI__ZFAST_BITS)) { + z->fast[j] = fastv; + j += (1 << s); + } + } + ++next_code[s]; + } + } + return 1; +} + +// zlib-from-memory implementation for PNG reading +// because PNG allows splitting the zlib stream arbitrarily, +// and it's annoying structurally to have PNG call ZLIB call PNG, +// we require PNG read all the IDATs and combine them into a single +// memory buffer + +typedef struct +{ + stbi_uc* zbuffer, * zbuffer_end; + int num_bits; + int hit_zeof_once; + stbi__uint32 code_buffer; + + char* zout; + char* zout_start; + char* zout_end; + int z_expandable; + + stbi__zhuffman z_length, z_distance; +} stbi__zbuf; + +stbi_inline static int stbi__zeof(stbi__zbuf* z) +{ + return (z->zbuffer >= z->zbuffer_end); +} + +stbi_inline static stbi_uc stbi__zget8(stbi__zbuf* z) +{ + return stbi__zeof(z) ? 0 : *z->zbuffer++; +} + +static void stbi__fill_bits(stbi__zbuf* z) +{ + do { + if (z->code_buffer >= (1U << z->num_bits)) { + z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ + return; + } + z->code_buffer |= (unsigned int)stbi__zget8(z) << z->num_bits; + z->num_bits += 8; + } while (z->num_bits <= 24); +} + +stbi_inline static unsigned int stbi__zreceive(stbi__zbuf* z, int n) +{ + unsigned int k; + if (z->num_bits < n) stbi__fill_bits(z); + k = z->code_buffer & ((1 << n) - 1); + z->code_buffer >>= n; + z->num_bits -= n; + return k; +} + +static int stbi__zhuffman_decode_slowpath(stbi__zbuf* a, stbi__zhuffman* z) +{ + int b, s, k; + // not resolved by fast table, so compute it the slow way + // use jpeg approach, which requires MSbits at top + k = stbi__bit_reverse(a->code_buffer, 16); + for (s = STBI__ZFAST_BITS + 1; ; ++s) + if (k < z->maxcode[s]) + break; + if (s >= 16) return -1; // invalid code! + // code size is s, so: + b = (k >> (16 - s)) - z->firstcode[s] + z->firstsymbol[s]; + if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! + if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; +} + +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf* a, stbi__zhuffman* z) +{ + int b, s; + if (a->num_bits < 16) { + if (stbi__zeof(a)) { + if (!a->hit_zeof_once) { + // This is the first time we hit eof, insert 16 extra padding btis + // to allow us to keep going; if we actually consume any of them + // though, that is invalid data. This is caught later. + a->hit_zeof_once = 1; + a->num_bits += 16; // add 16 implicit zero bits + } + else { + // We already inserted our extra 16 padding bits and are again + // out, this stream is actually prematurely terminated. + return -1; + } + } + else { + stbi__fill_bits(a); + } + } + b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; + if (b) { + s = b >> 9; + a->code_buffer >>= s; + a->num_bits -= s; + return b & 511; + } + return stbi__zhuffman_decode_slowpath(a, z); +} + +static int stbi__zexpand(stbi__zbuf* z, char* zout, int n) // need to make room for n bytes +{ + char* q; + unsigned int cur, limit, old_limit; + z->zout = zout; + if (!z->z_expandable) return stbi__err("output buffer limit", "Corrupt PNG"); + cur = (unsigned int)(z->zout - z->zout_start); + limit = old_limit = (unsigned)(z->zout_end - z->zout_start); + if (UINT_MAX - cur < (unsigned)n) return stbi__err("outofmem", "Out of memory"); + while (cur + n > limit) { + if (limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); + limit *= 2; + } + q = (char*)STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); + if (q == NULL) return stbi__err("outofmem", "Out of memory"); + z->zout_start = q; + z->zout = q + cur; + z->zout_end = q + limit; + return 1; +} + +static const int stbi__zlength_base[31] = { + 3,4,5,6,7,8,9,10,11,13, + 15,17,19,23,27,31,35,43,51,59, + 67,83,99,115,131,163,195,227,258,0,0 }; + +static const int stbi__zlength_extra[31] = +{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + +static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, +257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0 }; + +static const int stbi__zdist_extra[32] = +{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 }; + +static int stbi__parse_huffman_block(stbi__zbuf* a) +{ + char* zout = a->zout; + for (;;) { + int z = stbi__zhuffman_decode(a, &a->z_length); + if (z < 256) { + if (z < 0) return stbi__err("bad huffman code", "Corrupt PNG"); // error in huffman codes + if (zout >= a->zout_end) { + if (!stbi__zexpand(a, zout, 1)) return 0; + zout = a->zout; + } + *zout++ = (char)z; + } + else { + stbi_uc* p; + int len, dist; + if (z == 256) { + a->zout = zout; + if (a->hit_zeof_once && a->num_bits < 16) { + // The first time we hit zeof, we inserted 16 extra zero bits into our bit + // buffer so the decoder can just do its speculative decoding. But if we + // actually consumed any of those bits (which is the case when num_bits < 16), + // the stream actually read past the end so it is malformed. + return stbi__err("unexpected end", "Corrupt PNG"); + } + return 1; + } + if (z >= 286) return stbi__err("bad huffman code", "Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data + z -= 257; + len = stbi__zlength_base[z]; + if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); + z = stbi__zhuffman_decode(a, &a->z_distance); + if (z < 0 || z >= 30) return stbi__err("bad huffman code", "Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data + dist = stbi__zdist_base[z]; + if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (zout - a->zout_start < dist) return stbi__err("bad dist", "Corrupt PNG"); + if (len > a->zout_end - zout) { + if (!stbi__zexpand(a, zout, len)) return 0; + zout = a->zout; + } + p = (stbi_uc*)(zout - dist); + if (dist == 1) { // run of one byte; common in images. + stbi_uc v = *p; + if (len) { do *zout++ = v; while (--len); } + } + else { + if (len) { do *zout++ = *p++; while (--len); } + } + } + } +} + +static int stbi__compute_huffman_codes(stbi__zbuf* a) +{ + static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + stbi__zhuffman z_codelength; + stbi_uc lencodes[286 + 32 + 137];//padding for maximum single op + stbi_uc codelength_sizes[19]; + int i, n; + + int hlit = stbi__zreceive(a, 5) + 257; + int hdist = stbi__zreceive(a, 5) + 1; + int hclen = stbi__zreceive(a, 4) + 4; + int ntot = hlit + hdist; + + memset(codelength_sizes, 0, sizeof(codelength_sizes)); + for (i = 0; i < hclen; ++i) { + int s = stbi__zreceive(a, 3); + codelength_sizes[length_dezigzag[i]] = (stbi_uc)s; + } + if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; + + n = 0; + while (n < ntot) { + int c = stbi__zhuffman_decode(a, &z_codelength); + if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); + if (c < 16) + lencodes[n++] = (stbi_uc)c; + else { + stbi_uc fill = 0; + if (c == 16) { + c = stbi__zreceive(a, 2) + 3; + if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); + fill = lencodes[n - 1]; + } + else if (c == 17) { + c = stbi__zreceive(a, 3) + 3; + } + else if (c == 18) { + c = stbi__zreceive(a, 7) + 11; + } + else { + return stbi__err("bad codelengths", "Corrupt PNG"); + } + if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); + memset(lencodes + n, fill, c); + n += c; + } + } + if (n != ntot) return stbi__err("bad codelengths", "Corrupt PNG"); + if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, lencodes + hlit, hdist)) return 0; + return 1; +} + +static int stbi__parse_uncompressed_block(stbi__zbuf* a) +{ + stbi_uc header[4]; + int len, nlen, k; + if (a->num_bits & 7) + stbi__zreceive(a, a->num_bits & 7); // discard + // drain the bit-packed data into header + k = 0; + while (a->num_bits > 0) { + header[k++] = (stbi_uc)(a->code_buffer & 255); // suppress MSVC run-time check + a->code_buffer >>= 8; + a->num_bits -= 8; + } + if (a->num_bits < 0) return stbi__err("zlib corrupt", "Corrupt PNG"); + // now fill header the normal way + while (k < 4) + header[k++] = stbi__zget8(a); + len = header[1] * 256 + header[0]; + nlen = header[3] * 256 + header[2]; + if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt", "Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer", "Corrupt PNG"); + if (a->zout + len > a->zout_end) + if (!stbi__zexpand(a, a->zout, len)) return 0; + memcpy(a->zout, a->zbuffer, len); + a->zbuffer += len; + a->zout += len; + return 1; +} + +static int stbi__parse_zlib_header(stbi__zbuf* a) +{ + int cmf = stbi__zget8(a); + int cm = cmf & 15; + /* int cinfo = cmf >> 4; */ + int flg = stbi__zget8(a); + if (stbi__zeof(a)) return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec + if ((cmf * 256 + flg) % 31 != 0) return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec + if (flg & 32) return stbi__err("no preset dict", "Corrupt PNG"); // preset dictionary not allowed in png + if (cm != 8) return stbi__err("bad compression", "Corrupt PNG"); // DEFLATE required for png + // window = 1 << (8 + cinfo)... but who cares, we fully buffer output + return 1; +} + +static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = +{ + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 +}; +static const stbi_uc stbi__zdefault_distance[32] = +{ + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 +}; +/* +Init algorithm: +{ + int i; // use <= to match clearly with spec + for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; + for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; + for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; + for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; + + for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; +} +*/ + +static int stbi__parse_zlib(stbi__zbuf* a, int parse_header) +{ + int final, type; + if (parse_header) + if (!stbi__parse_zlib_header(a)) return 0; + a->num_bits = 0; + a->code_buffer = 0; + a->hit_zeof_once = 0; + do { + final = stbi__zreceive(a, 1); + type = stbi__zreceive(a, 2); + if (type == 0) { + if (!stbi__parse_uncompressed_block(a)) return 0; + } + else if (type == 3) { + return 0; + } + else { + if (type == 1) { + // use fixed code lengths + if (!stbi__zbuild_huffman(&a->z_length, stbi__zdefault_length, STBI__ZNSYMS)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; + } + else { + if (!stbi__compute_huffman_codes(a)) return 0; + } + if (!stbi__parse_huffman_block(a)) return 0; + } + } while (!final); + return 1; +} + +static int stbi__do_zlib(stbi__zbuf* a, char* obuf, int olen, int exp, int parse_header) +{ + a->zout_start = obuf; + a->zout = obuf; + a->zout_end = obuf + olen; + a->z_expandable = exp; + + return stbi__parse_zlib(a, parse_header); +} + +STBIDEF char* stbi_zlib_decode_malloc_guesssize(const char* buffer, int len, int initial_size, int* outlen) +{ + stbi__zbuf a; + char* p = (char*)stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc*)buffer; + a.zbuffer_end = (stbi_uc*)buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { + if (outlen) *outlen = (int)(a.zout - a.zout_start); + return a.zout_start; + } + else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF char* stbi_zlib_decode_malloc(char const* buffer, int len, int* outlen) +{ + return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); +} + +STBIDEF char* stbi_zlib_decode_malloc_guesssize_headerflag(const char* buffer, int len, int initial_size, int* outlen, int parse_header) +{ + stbi__zbuf a; + char* p = (char*)stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc*)buffer; + a.zbuffer_end = (stbi_uc*)buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { + if (outlen) *outlen = (int)(a.zout - a.zout_start); + return a.zout_start; + } + else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_buffer(char* obuffer, int olen, char const* ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc*)ibuffer; + a.zbuffer_end = (stbi_uc*)ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) + return (int)(a.zout - a.zout_start); + else + return -1; +} + +STBIDEF char* stbi_zlib_decode_noheader_malloc(char const* buffer, int len, int* outlen) +{ + stbi__zbuf a; + char* p = (char*)stbi__malloc(16384); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc*)buffer; + a.zbuffer_end = (stbi_uc*)buffer + len; + if (stbi__do_zlib(&a, p, 16384, 1, 0)) { + if (outlen) *outlen = (int)(a.zout - a.zout_start); + return a.zout_start; + } + else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_noheader_buffer(char* obuffer, int olen, const char* ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc*)ibuffer; + a.zbuffer_end = (stbi_uc*)ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) + return (int)(a.zout - a.zout_start); + else + return -1; +} +#endif + +// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 +// simple implementation +// - only 8-bit samples +// - no CRC checking +// - allocates lots of intermediate memory +// - avoids problem of streaming data between subsystems +// - avoids explicit window management +// performance +// - uses stb_zlib, a PD zlib implementation with fast huffman decoding + +#ifndef STBI_NO_PNG +typedef struct +{ + stbi__uint32 length; + stbi__uint32 type; +} stbi__pngchunk; + +static stbi__pngchunk stbi__get_chunk_header(stbi__context* s) +{ + stbi__pngchunk c; + c.length = stbi__get32be(s); + c.type = stbi__get32be(s); + return c; +} + +static int stbi__check_png_header(stbi__context* s) +{ + static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + int i; + for (i = 0; i < 8; ++i) + if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig", "Not a PNG"); + return 1; +} + +typedef struct +{ + stbi__context* s; + stbi_uc* idata, * expanded, * out; + int depth; +} stbi__png; + + +enum { + STBI__F_none = 0, + STBI__F_sub = 1, + STBI__F_up = 2, + STBI__F_avg = 3, + STBI__F_paeth = 4, + // synthetic filter used for first scanline to avoid needing a dummy row of 0s + STBI__F_avg_first +}; + +static stbi_uc first_row_filter[5] = +{ + STBI__F_none, + STBI__F_sub, + STBI__F_none, + STBI__F_avg_first, + STBI__F_sub // Paeth with b=c=0 turns out to be equivalent to sub +}; + +static int stbi__paeth(int a, int b, int c) +{ + // This formulation looks very different from the reference in the PNG spec, but is + // actually equivalent and has favorable data dependencies and admits straightforward + // generation of branch-free code, which helps performance significantly. + int thresh = c * 3 - (a + b); + int lo = a < b ? a : b; + int hi = a < b ? b : a; + int t0 = (hi <= thresh) ? lo : c; + int t1 = (thresh <= lo) ? hi : t0; + return t1; +} + +static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; + +// adds an extra all-255 alpha channel +// dest == src is legal +// img_n must be 1 or 3 +static void stbi__create_png_alpha_expand8(stbi_uc* dest, stbi_uc* src, stbi__uint32 x, int img_n) +{ + int i; + // must process data backwards since we allow dest==src + if (img_n == 1) { + for (i = x - 1; i >= 0; --i) { + dest[i * 2 + 1] = 255; + dest[i * 2 + 0] = src[i]; + } + } + else { + STBI_ASSERT(img_n == 3); + for (i = x - 1; i >= 0; --i) { + dest[i * 4 + 3] = 255; + dest[i * 4 + 2] = src[i * 3 + 2]; + dest[i * 4 + 1] = src[i * 3 + 1]; + dest[i * 4 + 0] = src[i * 3 + 0]; + } + } +} + +// create the png data from post-deflated data +static int stbi__create_png_image_raw(stbi__png* a, stbi_uc* raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) +{ + int bytes = (depth == 16 ? 2 : 1); + stbi__context* s = a->s; + stbi__uint32 i, j, stride = x * out_n * bytes; + stbi__uint32 img_len, img_width_bytes; + stbi_uc* filter_buf; + int all_ok = 1; + int k; + int img_n = s->img_n; // copy it into a local for later + + int output_bytes = out_n * bytes; + int filter_bytes = img_n * bytes; + int width = x; + + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n + 1); + a->out = (stbi_uc*)stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into + if (!a->out) return stbi__err("outofmem", "Out of memory"); + + // note: error exits here don't need to clean up a->out individually, + // stbi__do_png always does on error. + if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); + img_width_bytes = (((img_n * x * depth) + 7) >> 3); + if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes)) return stbi__err("too large", "Corrupt PNG"); + img_len = (img_width_bytes + 1) * y; + + // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, + // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), + // so just check for raw_len < img_len always. + if (raw_len < img_len) return stbi__err("not enough pixels", "Corrupt PNG"); + + // Allocate two scan lines worth of filter workspace buffer. + filter_buf = (stbi_uc*)stbi__malloc_mad2(img_width_bytes, 2, 0); + if (!filter_buf) return stbi__err("outofmem", "Out of memory"); + + // Filtering for low-bit-depth images + if (depth < 8) { + filter_bytes = 1; + width = img_width_bytes; + } + + for (j = 0; j < y; ++j) { + // cur/prior filter buffers alternate + stbi_uc* cur = filter_buf + (j & 1) * img_width_bytes; + stbi_uc* prior = filter_buf + (~j & 1) * img_width_bytes; + stbi_uc* dest = a->out + stride * j; + int nk = width * filter_bytes; + int filter = *raw++; + + // check filter type + if (filter > 4) { + all_ok = stbi__err("invalid filter", "Corrupt PNG"); + break; + } + + // if first row, use special filter that doesn't sample previous row + if (j == 0) filter = first_row_filter[filter]; + + // perform actual filtering + switch (filter) { + case STBI__F_none: + memcpy(cur, raw, nk); + break; + case STBI__F_sub: + memcpy(cur, raw, filter_bytes); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + cur[k - filter_bytes]); + break; + case STBI__F_up: + for (k = 0; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + prior[k]); + break; + case STBI__F_avg: + for (k = 0; k < filter_bytes; ++k) + cur[k] = STBI__BYTECAST(raw[k] + (prior[k] >> 1)); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k - filter_bytes]) >> 1)); + break; + case STBI__F_paeth: + for (k = 0; k < filter_bytes; ++k) + cur[k] = STBI__BYTECAST(raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0) + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k - filter_bytes], prior[k], prior[k - filter_bytes])); + break; + case STBI__F_avg_first: + memcpy(cur, raw, filter_bytes); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + (cur[k - filter_bytes] >> 1)); + break; + } + + raw += nk; + + // expand decoded bits in cur to dest, also adding an extra alpha channel if desired + if (depth < 8) { + stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range + stbi_uc* in = cur; + stbi_uc* out = dest; + stbi_uc inb = 0; + stbi__uint32 nsmp = x * img_n; + + // expand bits to bytes first + if (depth == 4) { + for (i = 0; i < nsmp; ++i) { + if ((i & 1) == 0) inb = *in++; + *out++ = scale * (inb >> 4); + inb <<= 4; + } + } + else if (depth == 2) { + for (i = 0; i < nsmp; ++i) { + if ((i & 3) == 0) inb = *in++; + *out++ = scale * (inb >> 6); + inb <<= 2; + } + } + else { + STBI_ASSERT(depth == 1); + for (i = 0; i < nsmp; ++i) { + if ((i & 7) == 0) inb = *in++; + *out++ = scale * (inb >> 7); + inb <<= 1; + } + } + + // insert alpha=255 values if desired + if (img_n != out_n) + stbi__create_png_alpha_expand8(dest, dest, x, img_n); + } + else if (depth == 8) { + if (img_n == out_n) + memcpy(dest, cur, x * img_n); + else + stbi__create_png_alpha_expand8(dest, cur, x, img_n); + } + else if (depth == 16) { + // convert the image data from big-endian to platform-native + stbi__uint16* dest16 = (stbi__uint16*)dest; + stbi__uint32 nsmp = x * img_n; + + if (img_n == out_n) { + for (i = 0; i < nsmp; ++i, ++dest16, cur += 2) + *dest16 = (cur[0] << 8) | cur[1]; + } + else { + STBI_ASSERT(img_n + 1 == out_n); + if (img_n == 1) { + for (i = 0; i < x; ++i, dest16 += 2, cur += 2) { + dest16[0] = (cur[0] << 8) | cur[1]; + dest16[1] = 0xffff; + } + } + else { + STBI_ASSERT(img_n == 3); + for (i = 0; i < x; ++i, dest16 += 4, cur += 6) { + dest16[0] = (cur[0] << 8) | cur[1]; + dest16[1] = (cur[2] << 8) | cur[3]; + dest16[2] = (cur[4] << 8) | cur[5]; + dest16[3] = 0xffff; + } + } + } + } + } + + STBI_FREE(filter_buf); + if (!all_ok) return 0; + + return 1; +} + +static int stbi__create_png_image(stbi__png* a, stbi_uc* image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) +{ + int bytes = (depth == 16 ? 2 : 1); + int out_bytes = out_n * bytes; + stbi_uc* final; + int p; + if (!interlaced) + return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); + + // de-interlacing + final = (stbi_uc*)stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + if (!final) return stbi__err("outofmem", "Out of memory"); + for (p = 0; p < 7; ++p) { + int xorig[] = { 0,4,0,2,0,1,0 }; + int yorig[] = { 0,0,4,0,2,0,1 }; + int xspc[] = { 8,8,4,4,2,2,1 }; + int yspc[] = { 8,8,8,4,4,2,2 }; + int i, j, x, y; + // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 + x = (a->s->img_x - xorig[p] + xspc[p] - 1) / xspc[p]; + y = (a->s->img_y - yorig[p] + yspc[p] - 1) / yspc[p]; + if (x && y) { + stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { + STBI_FREE(final); + return 0; + } + for (j = 0; j < y; ++j) { + for (i = 0; i < x; ++i) { + int out_y = j * yspc[p] + yorig[p]; + int out_x = i * xspc[p] + xorig[p]; + memcpy(final + out_y * a->s->img_x * out_bytes + out_x * out_bytes, + a->out + (j * x + i) * out_bytes, out_bytes); + } + } + STBI_FREE(a->out); + image_data += img_len; + image_data_len -= img_len; + } + } + a->out = final; + + return 1; +} + +static int stbi__compute_transparency(stbi__png* z, stbi_uc tc[3], int out_n) +{ + stbi__context* s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc* p = z->out; + + // compute color-based transparency, assuming we've + // already got 255 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 255); + p += 2; + } + } + else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__compute_transparency16(stbi__png* z, stbi__uint16 tc[3], int out_n) +{ + stbi__context* s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi__uint16* p = (stbi__uint16*)z->out; + + // compute color-based transparency, assuming we've + // already got 65535 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 65535); + p += 2; + } + } + else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__expand_png_palette(stbi__png* a, stbi_uc* palette, int len, int pal_img_n) +{ + stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; + stbi_uc* p, * temp_out, * orig = a->out; + + p = (stbi_uc*)stbi__malloc_mad2(pixel_count, pal_img_n, 0); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); + + // between here and free(out) below, exitting would leak + temp_out = p; + + if (pal_img_n == 3) { + for (i = 0; i < pixel_count; ++i) { + int n = orig[i] * 4; + p[0] = palette[n]; + p[1] = palette[n + 1]; + p[2] = palette[n + 2]; + p += 3; + } + } + else { + for (i = 0; i < pixel_count; ++i) { + int n = orig[i] * 4; + p[0] = palette[n]; + p[1] = palette[n + 1]; + p[2] = palette[n + 2]; + p[3] = palette[n + 3]; + p += 4; + } + } + STBI_FREE(a->out); + a->out = temp_out; + + STBI_NOTUSED(len); + + return 1; +} + +static int stbi__unpremultiply_on_load_global = 0; +static int stbi__de_iphone_flag_global = 0; + +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_global = flag_true_if_should_convert; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global +#define stbi__de_iphone_flag stbi__de_iphone_flag_global +#else +static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set; +static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set; + +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; + stbi__unpremultiply_on_load_set = 1; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_local = flag_true_if_should_convert; + stbi__de_iphone_flag_set = 1; +} + +#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \ + ? stbi__unpremultiply_on_load_local \ + : stbi__unpremultiply_on_load_global) +#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \ + ? stbi__de_iphone_flag_local \ + : stbi__de_iphone_flag_global) +#endif // STBI_THREAD_LOCAL + +static void stbi__de_iphone(stbi__png* z) +{ + stbi__context* s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc* p = z->out; + + if (s->img_out_n == 3) { // convert bgr to rgb + for (i = 0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 3; + } + } + else { + STBI_ASSERT(s->img_out_n == 4); + if (stbi__unpremultiply_on_load) { + // convert bgr to rgb and unpremultiply + for (i = 0; i < pixel_count; ++i) { + stbi_uc a = p[3]; + stbi_uc t = p[0]; + if (a) { + stbi_uc half = a / 2; + p[0] = (p[2] * 255 + half) / a; + p[1] = (p[1] * 255 + half) / a; + p[2] = (t * 255 + half) / a; + } + else { + p[0] = p[2]; + p[2] = t; + } + p += 4; + } + } + else { + // convert bgr to rgb + for (i = 0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 4; + } + } + } +} + +#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) + +static int stbi__parse_png_file(stbi__png* z, int scan, int req_comp) +{ + stbi_uc palette[1024], pal_img_n = 0; + stbi_uc has_trans = 0, tc[3] = { 0 }; + stbi__uint16 tc16[3]; + stbi__uint32 ioff = 0, idata_limit = 0, i, pal_len = 0; + int first = 1, k, interlace = 0, color = 0, is_iphone = 0; + stbi__context* s = z->s; + + z->expanded = NULL; + z->idata = NULL; + z->out = NULL; + + if (!stbi__check_png_header(s)) return 0; + + if (scan == STBI__SCAN_type) return 1; + + for (;;) { + stbi__pngchunk c = stbi__get_chunk_header(s); + switch (c.type) { + case STBI__PNG_TYPE('C', 'g', 'B', 'I'): + is_iphone = 1; + stbi__skip(s, c.length); + break; + case STBI__PNG_TYPE('I', 'H', 'D', 'R'): { + int comp, filter; + if (!first) return stbi__err("multiple IHDR", "Corrupt PNG"); + first = 0; + if (c.length != 13) return stbi__err("bad IHDR len", "Corrupt PNG"); + s->img_x = stbi__get32be(s); + s->img_y = stbi__get32be(s); + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large", "Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large", "Very large image (corrupt?)"); + z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only", "PNG not supported: 1/2/4/8/16-bit only"); + color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype", "Corrupt PNG"); + if (color == 3 && z->depth == 16) return stbi__err("bad ctype", "Corrupt PNG"); + if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype", "Corrupt PNG"); + comp = stbi__get8(s); if (comp) return stbi__err("bad comp method", "Corrupt PNG"); + filter = stbi__get8(s); if (filter) return stbi__err("bad filter method", "Corrupt PNG"); + interlace = stbi__get8(s); if (interlace > 1) return stbi__err("bad interlace method", "Corrupt PNG"); + if (!s->img_x || !s->img_y) return stbi__err("0-pixel image", "Corrupt PNG"); + if (!pal_img_n) { + s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + } + else { + // if paletted, then pal_n is our final components, and + // img_n is # components to decompress/filter. + s->img_n = 1; + if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large", "Corrupt PNG"); + } + // even with SCAN_header, have to scan to see if we have a tRNS + break; + } + + case STBI__PNG_TYPE('P', 'L', 'T', 'E'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (c.length > 256 * 3) return stbi__err("invalid PLTE", "Corrupt PNG"); + pal_len = c.length / 3; + if (pal_len * 3 != c.length) return stbi__err("invalid PLTE", "Corrupt PNG"); + for (i = 0; i < pal_len; ++i) { + palette[i * 4 + 0] = stbi__get8(s); + palette[i * 4 + 1] = stbi__get8(s); + palette[i * 4 + 2] = stbi__get8(s); + palette[i * 4 + 3] = 255; + } + break; + } + + case STBI__PNG_TYPE('t', 'R', 'N', 'S'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (z->idata) return stbi__err("tRNS after IDAT", "Corrupt PNG"); + if (pal_img_n) { + if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } + if (pal_len == 0) return stbi__err("tRNS before PLTE", "Corrupt PNG"); + if (c.length > pal_len) return stbi__err("bad tRNS len", "Corrupt PNG"); + pal_img_n = 4; + for (i = 0; i < c.length; ++i) + palette[i * 4 + 3] = stbi__get8(s); + } + else { + if (!(s->img_n & 1)) return stbi__err("tRNS with alpha", "Corrupt PNG"); + if (c.length != (stbi__uint32)s->img_n * 2) return stbi__err("bad tRNS len", "Corrupt PNG"); + has_trans = 1; + // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now. + if (scan == STBI__SCAN_header) { ++s->img_n; return 1; } + if (z->depth == 16) { + for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is + } + else { + for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger + } + } + break; + } + + case STBI__PNG_TYPE('I', 'D', 'A', 'T'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (pal_img_n && !pal_len) return stbi__err("no PLTE", "Corrupt PNG"); + if (scan == STBI__SCAN_header) { + // header scan definitely stops at first IDAT + if (pal_img_n) + s->img_n = pal_img_n; + return 1; + } + if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes"); + if ((int)(ioff + c.length) < (int)ioff) return 0; + if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; + stbi_uc* p; + if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; + while (ioff + c.length > idata_limit) + idata_limit *= 2; + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc*)STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + z->idata = p; + } + if (!stbi__getn(s, z->idata + ioff, c.length)) return stbi__err("outofdata", "Corrupt PNG"); + ioff += c.length; + break; + } + + case STBI__PNG_TYPE('I', 'E', 'N', 'D'): { + stbi__uint32 raw_len, bpl; + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (scan != STBI__SCAN_load) return 1; + if (z->idata == NULL) return stbi__err("no IDAT", "Corrupt PNG"); + // initial guess for decoded data size to avoid unnecessary reallocs + bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component + raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; + z->expanded = (stbi_uc*)stbi_zlib_decode_malloc_guesssize_headerflag((char*)z->idata, ioff, raw_len, (int*)&raw_len, !is_iphone); + if (z->expanded == NULL) return 0; // zlib should set error + STBI_FREE(z->idata); z->idata = NULL; + if ((req_comp == s->img_n + 1 && req_comp != 3 && !pal_img_n) || has_trans) + s->img_out_n = s->img_n + 1; + else + s->img_out_n = s->img_n; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; + if (has_trans) { + if (z->depth == 16) { + if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; + } + else { + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + } + } + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) + stbi__de_iphone(z); + if (pal_img_n) { + // pal_img_n == 3 or 4 + s->img_n = pal_img_n; // record the actual colors we had + s->img_out_n = pal_img_n; + if (req_comp >= 3) s->img_out_n = req_comp; + if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) + return 0; + } + else if (has_trans) { + // non-paletted image with tRNS -> source image has (constant) alpha + ++s->img_n; + } + STBI_FREE(z->expanded); z->expanded = NULL; + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + return 1; + } + + default: + // if critical, fail + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if ((c.type & (1 << 29)) == 0) { +#ifndef STBI_NO_FAILURE_STRINGS + // not threadsafe + static char invalid_chunk[] = "XXXX PNG chunk not known"; + invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); + invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); + invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); + invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); +#endif + return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); + } + stbi__skip(s, c.length); + break; + } + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + } +} + +static void* stbi__do_png(stbi__png* p, int* x, int* y, int* n, int req_comp, stbi__result_info* ri) +{ + void* result = NULL; + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + if (p->depth <= 8) + ri->bits_per_channel = 8; + else if (p->depth == 16) + ri->bits_per_channel = 16; + else + return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); + result = p->out; + p->out = NULL; + if (req_comp && req_comp != p->s->img_out_n) { + if (ri->bits_per_channel == 8) + result = stbi__convert_format((unsigned char*)result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + else + result = stbi__convert_format16((stbi__uint16*)result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + p->s->img_out_n = req_comp; + if (result == NULL) return result; + } + *x = p->s->img_x; + *y = p->s->img_y; + if (n) *n = p->s->img_n; + } + STBI_FREE(p->out); p->out = NULL; + STBI_FREE(p->expanded); p->expanded = NULL; + STBI_FREE(p->idata); p->idata = NULL; + + return result; +} + +static void* stbi__png_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri) +{ + stbi__png p; + p.s = s; + return stbi__do_png(&p, x, y, comp, req_comp, ri); +} + +static int stbi__png_test(stbi__context* s) +{ + int r; + r = stbi__check_png_header(s); + stbi__rewind(s); + return r; +} + +static int stbi__png_info_raw(stbi__png* p, int* x, int* y, int* comp) +{ + if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { + stbi__rewind(p->s); + return 0; + } + if (x) *x = p->s->img_x; + if (y) *y = p->s->img_y; + if (comp) *comp = p->s->img_n; + return 1; +} + +static int stbi__png_info(stbi__context* s, int* x, int* y, int* comp) +{ + stbi__png p; + p.s = s; + return stbi__png_info_raw(&p, x, y, comp); +} + +static int stbi__png_is16(stbi__context* s) +{ + stbi__png p; + p.s = s; + if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) + return 0; + if (p.depth != 16) { + stbi__rewind(p.s); + return 0; + } + return 1; +} +#endif + +// Microsoft/Windows BMP image + +#ifndef STBI_NO_BMP +static int stbi__bmp_test_raw(stbi__context* s) +{ + int r; + int sz; + if (stbi__get8(s) != 'B') return 0; + if (stbi__get8(s) != 'M') return 0; + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + stbi__get32le(s); // discard data offset + sz = stbi__get32le(s); + r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); + return r; +} + +static int stbi__bmp_test(stbi__context* s) +{ + int r = stbi__bmp_test_raw(s); + stbi__rewind(s); + return r; +} + + +// returns 0..31 for the highest set bit +static int stbi__high_bit(unsigned int z) +{ + int n = 0; + if (z == 0) return -1; + if (z >= 0x10000) { n += 16; z >>= 16; } + if (z >= 0x00100) { n += 8; z >>= 8; } + if (z >= 0x00010) { n += 4; z >>= 4; } + if (z >= 0x00004) { n += 2; z >>= 2; } + if (z >= 0x00002) { n += 1;/* >>= 1;*/ } + return n; +} + +static int stbi__bitcount(unsigned int a) +{ + a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 + a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits + a = (a + (a >> 8)); // max 16 per 8 bits + a = (a + (a >> 16)); // max 32 per 8 bits + return a & 0xff; +} + +// extract an arbitrarily-aligned N-bit value (N=bits) +// from v, and then make it 8-bits long and fractionally +// extend it to full full range. +static int stbi__shiftsigned(unsigned int v, int shift, int bits) +{ + static unsigned int mul_table[9] = { + 0, + 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, + 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, + }; + static unsigned int shift_table[9] = { + 0, 0,0,1,0,2,4,6,0, + }; + if (shift < 0) + v <<= -shift; + else + v >>= shift; + STBI_ASSERT(v < 256); + v >>= (8 - bits); + STBI_ASSERT(bits >= 0 && bits <= 8); + return (int)((unsigned)v * mul_table[bits]) >> shift_table[bits]; +} + +typedef struct +{ + int bpp, offset, hsz; + unsigned int mr, mg, mb, ma, all_a; + int extra_read; +} stbi__bmp_data; + +static int stbi__bmp_set_mask_defaults(stbi__bmp_data* info, int compress) +{ + // BI_BITFIELDS specifies masks explicitly, don't override + if (compress == 3) + return 1; + + if (compress == 0) { + if (info->bpp == 16) { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } + else if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 + } + else { + // otherwise, use defaults, which is all-0 + info->mr = info->mg = info->mb = info->ma = 0; + } + return 1; + } + return 0; // error +} + +static void* stbi__bmp_parse_header(stbi__context* s, stbi__bmp_data* info) +{ + int hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + info->mr = info->mg = info->mb = info->ma = 0; + info->extra_read = 14; + + if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); + + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); + if (hsz == 12) { + s->img_x = stbi__get16le(s); + s->img_y = stbi__get16le(s); + } + else { + s->img_x = stbi__get32le(s); + s->img_y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); + info->bpp = stbi__get16le(s); + if (hsz != 12) { + int compress = stbi__get32le(s); + if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes + if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel + stbi__get32le(s); // discard sizeof + stbi__get32le(s); // discard hres + stbi__get32le(s); // discard vres + stbi__get32le(s); // discard colorsused + stbi__get32le(s); // discard max important + if (hsz == 40 || hsz == 56) { + if (hsz == 56) { + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + } + if (info->bpp == 16 || info->bpp == 32) { + if (compress == 0) { + stbi__bmp_set_mask_defaults(info, compress); + } + else if (compress == 3) { + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->extra_read += 12; + // not documented, but generated by photoshop and handled by mspaint + if (info->mr == info->mg && info->mg == info->mb) { + // ?!?!? + return stbi__errpuc("bad BMP", "bad BMP"); + } + } + else + return stbi__errpuc("bad BMP", "bad BMP"); + } + } + else { + // V4/V5 header + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs + stbi__bmp_set_mask_defaults(info, compress); + stbi__get32le(s); // discard color space + for (i = 0; i < 12; ++i) + stbi__get32le(s); // discard color space parameters + if (hsz == 124) { + stbi__get32le(s); // discard rendering intent + stbi__get32le(s); // discard offset of profile data + stbi__get32le(s); // discard size of profile data + stbi__get32le(s); // discard reserved + } + } + } + return (void*)1; +} + + +static void* stbi__bmp_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri) +{ + stbi_uc* out; + unsigned int mr = 0, mg = 0, mb = 0, ma = 0, all_a; + stbi_uc pal[256][4]; + int psize = 0, i, j, width; + int flip_vertically, pad, target; + stbi__bmp_data info; + STBI_NOTUSED(ri); + + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set + + flip_vertically = ((int)s->img_y) > 0; + s->img_y = abs((int)s->img_y); + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large", "Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large", "Very large image (corrupt?)"); + + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; + + if (info.hsz == 12) { + if (info.bpp < 24) + psize = (info.offset - info.extra_read - 24) / 3; + } + else { + if (info.bpp < 16) + psize = (info.offset - info.extra_read - info.hsz) >> 2; + } + if (psize == 0) { + // accept some number of extra bytes after the header, but if the offset points either to before + // the header ends or implies a large amount of extra data, reject the file as malformed + int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original); + int header_limit = 1024; // max we actually read is below 256 bytes currently. + int extra_data_limit = 256 * 4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size. + if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) { + return stbi__errpuc("bad header", "Corrupt BMP"); + } + // we established that bytes_read_so_far is positive and sensible. + // the first half of this test rejects offsets that are either too small positives, or + // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn + // ensures the number computed in the second half of the test can't overflow. + if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) { + return stbi__errpuc("bad offset", "Corrupt BMP"); + } + else { + stbi__skip(s, info.offset - bytes_read_so_far); + } + } + + if (info.bpp == 24 && ma == 0xff000000) + s->img_n = 3; + else + s->img_n = ma ? 4 : 3; + if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 + target = req_comp; + else + target = s->img_n; // if they want monochrome, we'll post-convert + + // sanity-check size + if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "Corrupt BMP"); + + out = (stbi_uc*)stbi__malloc_mad3(target, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (info.bpp < 16) { + int z = 0; + if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } + for (i = 0; i < psize; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); + pal[i][3] = 255; + } + stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 1) width = (s->img_x + 7) >> 3; + else if (info.bpp == 4) width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) width = s->img_x; + else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } + pad = (-width) & 3; + if (info.bpp == 1) { + for (j = 0; j < (int)s->img_y; ++j) { + int bit_offset = 7, v = stbi__get8(s); + for (i = 0; i < (int)s->img_x; ++i) { + int color = (v >> bit_offset) & 0x1; + out[z++] = pal[color][0]; + out[z++] = pal[color][1]; + out[z++] = pal[color][2]; + if (target == 4) out[z++] = 255; + if (i + 1 == (int)s->img_x) break; + if ((--bit_offset) < 0) { + bit_offset = 7; + v = stbi__get8(s); + } + } + stbi__skip(s, pad); + } + } + else { + for (j = 0; j < (int)s->img_y; ++j) { + for (i = 0; i < (int)s->img_x; i += 2) { + int v = stbi__get8(s), v2 = 0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i + 1 == (int)s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); + } + } + } + else { + int rshift = 0, gshift = 0, bshift = 0, ashift = 0, rcount = 0, gcount = 0, bcount = 0, acount = 0; + int z = 0; + int easy = 0; + stbi__skip(s, info.offset - info.extra_read - info.hsz); + if (info.bpp == 24) width = 3 * s->img_x; + else if (info.bpp == 16) width = 2 * s->img_x; + else /* bpp = 32 and pad = 0 */ width = 0; + pad = (-width) & 3; + if (info.bpp == 24) { + easy = 1; + } + else if (info.bpp == 32) { + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) + easy = 2; + } + if (!easy) { + if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + // right shift amt to put high bit in position #7 + rshift = stbi__high_bit(mr) - 7; rcount = stbi__bitcount(mr); + gshift = stbi__high_bit(mg) - 7; gcount = stbi__bitcount(mg); + bshift = stbi__high_bit(mb) - 7; bcount = stbi__bitcount(mb); + ashift = stbi__high_bit(ma) - 7; acount = stbi__bitcount(ma); + if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + } + for (j = 0; j < (int)s->img_y; ++j) { + if (easy) { + for (i = 0; i < (int)s->img_x; ++i) { + unsigned char a; + out[z + 2] = stbi__get8(s); + out[z + 1] = stbi__get8(s); + out[z + 0] = stbi__get8(s); + z += 3; + a = (easy == 2 ? stbi__get8(s) : 255); + all_a |= a; + if (target == 4) out[z++] = a; + } + } + else { + int bpp = info.bpp; + for (i = 0; i < (int)s->img_x; ++i) { + stbi__uint32 v = (bpp == 16 ? (stbi__uint32)stbi__get16le(s) : stbi__get32le(s)); + unsigned int a; + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); + a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); + all_a |= a; + if (target == 4) out[z++] = STBI__BYTECAST(a); + } + } + stbi__skip(s, pad); + } + } + + // if alpha channel is all 0s, replace with all 255s + if (target == 4 && all_a == 0) + for (i = 4 * s->img_x * s->img_y - 1; i >= 0; i -= 4) + out[i] = 255; + + if (flip_vertically) { + stbi_uc t; + for (j = 0; j < (int)s->img_y >> 1; ++j) { + stbi_uc* p1 = out + j * s->img_x * target; + stbi_uc* p2 = out + (s->img_y - 1 - j) * s->img_x * target; + for (i = 0; i < (int)s->img_x * target; ++i) { + t = p1[i]; p1[i] = p2[i]; p2[i] = t; + } + } + } + + if (req_comp && req_comp != target) { + out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + return out; +} +#endif + +// Targa Truevision - TGA +// by Jonathan Dummer +#ifndef STBI_NO_TGA +// returns STBI_rgb or whatever, 0 on error +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) +{ + // only RGB or RGBA (incl. 16bit) or grey allowed + if (is_rgb16) *is_rgb16 = 0; + switch (bits_per_pixel) { + case 8: return STBI_grey; + case 16: if (is_grey) return STBI_grey_alpha; + // fallthrough + case 15: if (is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fallthrough + case 32: return bits_per_pixel / 8; + default: return 0; + } +} + +static int stbi__tga_info(stbi__context* s, int* x, int* y, int* comp) +{ + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; + int sz, tga_colormap_type; + stbi__get8(s); // discard Offset + tga_colormap_type = stbi__get8(s); // colormap type + if (tga_colormap_type > 1) { + stbi__rewind(s); + return 0; // only RGB or indexed allowed + } + tga_image_type = stbi__get8(s); // image type + if (tga_colormap_type == 1) { // colormapped (paletted) image + if (tga_image_type != 1 && tga_image_type != 9) { + stbi__rewind(s); + return 0; + } + stbi__skip(s, 4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) { + stbi__rewind(s); + return 0; + } + stbi__skip(s, 4); // skip image x and y origin + tga_colormap_bpp = sz; + } + else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ((tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11)) { + stbi__rewind(s); + return 0; // only RGB or grey allowed, +/- RLE + } + stbi__skip(s, 9); // skip colormap specification and image x/y origin + tga_colormap_bpp = 0; + } + tga_w = stbi__get16le(s); + if (tga_w < 1) { + stbi__rewind(s); + return 0; // test width + } + tga_h = stbi__get16le(s); + if (tga_h < 1) { + stbi__rewind(s); + return 0; // test height + } + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits + if (tga_colormap_bpp != 0) { + if ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the indexes + // I don't think anything but 8 or 16bit indexes makes sense + stbi__rewind(s); + return 0; + } + tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); + } + else { + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + } + if (!tga_comp) { + stbi__rewind(s); + return 0; + } + if (x) *x = tga_w; + if (y) *y = tga_h; + if (comp) *comp = tga_comp; + return 1; // seems to have passed everything +} + +static int stbi__tga_test(stbi__context* s) +{ + int res = 0; + int sz, tga_color_type; + stbi__get8(s); // discard Offset + tga_color_type = stbi__get8(s); // color type + if (tga_color_type > 1) goto errorEnd; // only RGB or indexed allowed + sz = stbi__get8(s); // image type + if (tga_color_type == 1) { // colormapped (paletted) image + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s, 4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) goto errorEnd; + stbi__skip(s, 4); // skip image x and y origin + } + else { // "normal" image w/o colormap + if ((sz != 2) && (sz != 3) && (sz != 10) && (sz != 11)) goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s, 9); // skip colormap specification and image x/y origin + } + if (stbi__get16le(s) < 1) goto errorEnd; // test width + if (stbi__get16le(s) < 1) goto errorEnd; // test height + sz = stbi__get8(s); // bits per pixel + if ((tga_color_type == 1) && (sz != 8) && (sz != 16)) goto errorEnd; // for colormapped images, bpp is size of an index + if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) goto errorEnd; + + res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + +errorEnd: + stbi__rewind(s); + return res; +} + +// read 16bit value and convert to 24bit RGB +static void stbi__tga_read_rgb16(stbi__context* s, stbi_uc* out) +{ + stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later + out[0] = (stbi_uc)((r * 255) / 31); + out[1] = (stbi_uc)((g * 255) / 31); + out[2] = (stbi_uc)((b * 255) / 31); + + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. +} + +static void* stbi__tga_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri) +{ + // read in the TGA header stuff + int tga_offset = stbi__get8(s); + int tga_indexed = stbi__get8(s); + int tga_image_type = stbi__get8(s); + int tga_is_RLE = 0; + int tga_palette_start = stbi__get16le(s); + int tga_palette_len = stbi__get16le(s); + int tga_palette_bits = stbi__get8(s); + int tga_x_origin = stbi__get16le(s); + int tga_y_origin = stbi__get16le(s); + int tga_width = stbi__get16le(s); + int tga_height = stbi__get16le(s); + int tga_bits_per_pixel = stbi__get8(s); + int tga_comp, tga_rgb16 = 0; + int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) + // image data + unsigned char* tga_data; + unsigned char* tga_palette = NULL; + int i, j; + unsigned char raw_data[4] = { 0 }; + int RLE_count = 0; + int RLE_repeating = 0; + int read_next_pixel = 1; + STBI_NOTUSED(ri); + STBI_NOTUSED(tga_x_origin); // @TODO + STBI_NOTUSED(tga_y_origin); // @TODO + + if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large", "Very large image (corrupt?)"); + if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large", "Very large image (corrupt?)"); + + // do a tiny bit of precessing + if (tga_image_type >= 8) + { + tga_image_type -= 8; + tga_is_RLE = 1; + } + tga_inverted = 1 - ((tga_inverted >> 5) & 1); + + // If I'm paletted, then I'll use the number of bits from the palette + if (tga_indexed) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + + if (!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); + + // tga info + *x = tga_width; + *y = tga_height; + if (comp) *comp = tga_comp; + + if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) + return stbi__errpuc("too large", "Corrupt TGA"); + + tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); + if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); + + // skip to the data's starting position (offset usually = 0) + stbi__skip(s, tga_offset); + + if (!tga_indexed && !tga_is_RLE && !tga_rgb16) { + for (i = 0; i < tga_height; ++i) { + int row = tga_inverted ? tga_height - i - 1 : i; + stbi_uc* tga_row = tga_data + row * tga_width * tga_comp; + stbi__getn(s, tga_row, tga_width * tga_comp); + } + } + else { + // do I need to load a palette? + if (tga_indexed) + { + if (tga_palette_len == 0) { /* you have to have at least one entry! */ + STBI_FREE(tga_data); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + + // any data to skip? (offset usually = 0) + stbi__skip(s, tga_palette_start); + // load the palette + tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); + if (!tga_palette) { + STBI_FREE(tga_data); + return stbi__errpuc("outofmem", "Out of memory"); + } + if (tga_rgb16) { + stbi_uc* pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i = 0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } + else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + } + // load the data + for (i = 0; i < tga_width * tga_height; ++i) + { + // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? + if (tga_is_RLE) + { + if (RLE_count == 0) + { + // yep, get the next byte as a RLE command + int RLE_cmd = stbi__get8(s); + RLE_count = 1 + (RLE_cmd & 127); + RLE_repeating = RLE_cmd >> 7; + read_next_pixel = 1; + } + else if (!RLE_repeating) + { + read_next_pixel = 1; + } + } + else + { + read_next_pixel = 1; + } + // OK, if I need to read a pixel, do it now + if (read_next_pixel) + { + // load however much data we did have + if (tga_indexed) + { + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); + if (pal_idx >= tga_palette_len) { + // invalid index + pal_idx = 0; + } + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = tga_palette[pal_idx + j]; + } + } + else if (tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } + else { + // read in the data raw + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = stbi__get8(s); + } + } + // clear the reading flag for the next pixel + read_next_pixel = 0; + } // end of reading a pixel + + // copy data + for (j = 0; j < tga_comp; ++j) + tga_data[i * tga_comp + j] = raw_data[j]; + + // in case we're in RLE mode, keep counting down + --RLE_count; + } + // do I need to invert the image? + if (tga_inverted) + { + for (j = 0; j * 2 < tga_height; ++j) + { + int index1 = j * tga_width * tga_comp; + int index2 = (tga_height - 1 - j) * tga_width * tga_comp; + for (i = tga_width * tga_comp; i > 0; --i) + { + unsigned char temp = tga_data[index1]; + tga_data[index1] = tga_data[index2]; + tga_data[index2] = temp; + ++index1; + ++index2; + } + } + } + // clear my palette, if I had one + if (tga_palette != NULL) + { + STBI_FREE(tga_palette); + } + } + + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) + { + unsigned char* tga_pixel = tga_data; + for (i = 0; i < tga_width * tga_height; ++i) + { + unsigned char temp = tga_pixel[0]; + tga_pixel[0] = tga_pixel[2]; + tga_pixel[2] = temp; + tga_pixel += tga_comp; + } + } + + // convert to target component count + if (req_comp && req_comp != tga_comp) + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); + + // the things I do to get rid of an error message, and yet keep + // Microsoft's C compilers happy... [8^( + tga_palette_start = tga_palette_len = tga_palette_bits = + tga_x_origin = tga_y_origin = 0; + STBI_NOTUSED(tga_palette_start); + // OK, done + return tga_data; +} +#endif + +// ************************************************************************************************* +// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context* s) +{ + int r = (stbi__get32be(s) == 0x38425053); + stbi__rewind(s); + return r; +} + +static int stbi__psd_decode_rle(stbi__context* s, stbi_uc* p, int pixelCount) +{ + int count, nleft, len; + + count = 0; + while ((nleft = pixelCount - count) > 0) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } + else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + if (len > nleft) return 0; // corrupt data + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } + else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len = 257 - len; + if (len > nleft) return 0; // corrupt data + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + + return 1; +} + +static void* stbi__psd_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri, int bpc) +{ + int pixelCount; + int channelCount, compression; + int channel, i; + int bitdepth; + int w, h; + stbi_uc* out; + STBI_NOTUSED(ri); + + // Check identifier + if (stbi__get32be(s) != 0x38425053) // "8BPS" + return stbi__errpuc("not PSD", "Corrupt PSD image"); + + // Check file type version. + if (stbi__get16be(s) != 1) + return stbi__errpuc("wrong version", "Unsupported version of PSD image"); + + // Skip 6 reserved bytes. + stbi__skip(s, 6); + + // Read the number of channels (R, G, B, A, etc). + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) + return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); + + // Read the rows and columns of the image. + h = stbi__get32be(s); + w = stbi__get32be(s); + + if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large", "Very large image (corrupt?)"); + if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large", "Very large image (corrupt?)"); + + // Make sure the depth is 8 bits. + bitdepth = stbi__get16be(s); + if (bitdepth != 8 && bitdepth != 16) + return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); + + // Make sure the color mode is RGB. + // Valid options are: + // 0: Bitmap + // 1: Grayscale + // 2: Indexed color + // 3: RGB color + // 4: CMYK color + // 7: Multichannel + // 8: Duotone + // 9: Lab color + if (stbi__get16be(s) != 3) + return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); + + // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) + stbi__skip(s, stbi__get32be(s)); + + // Skip the image resources. (resolution, pen tool paths, etc) + stbi__skip(s, stbi__get32be(s)); + + // Skip the reserved data. + stbi__skip(s, stbi__get32be(s)); + + // Find out if the data is compressed. + // Known values: + // 0: no compression + // 1: RLE compressed + compression = stbi__get16be(s); + if (compression > 1) + return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + + // Check size + if (!stbi__mad3sizes_valid(4, w, h, 0)) + return stbi__errpuc("too large", "Corrupt PSD"); + + // Create the destination image. + + if (!compression && bitdepth == 16 && bpc == 16) { + out = (stbi_uc*)stbi__malloc_mad3(8, w, h, 0); + ri->bits_per_channel = 16; + } + else + out = (stbi_uc*)stbi__malloc(4 * w * h); + + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + pixelCount = w * h; + + // Initialize the data to zero. + //memset( out, 0, pixelCount * 4 ); + + // Finally, the image data. + if (compression) { + // RLE as used by .PSD and .TIFF + // Loop until you get the number of unpacked bytes you are expecting: + // Read the next source byte into n. + // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. + // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. + // Else if n is 128, noop. + // Endloop + + // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, + // which we're going to just skip. + stbi__skip(s, h * channelCount * 2); + + // Read the RLE data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc* p; + + p = out + channel; + if (channel >= channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++, p += 4) + *p = (channel == 3 ? 255 : 0); + } + else { + // Read the RLE data. + if (!stbi__psd_decode_rle(s, p, pixelCount)) { + STBI_FREE(out); + return stbi__errpuc("corrupt", "bad RLE data"); + } + } + } + + } + else { + // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) + // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. + + // Read the data by channel. + for (channel = 0; channel < 4; channel++) { + if (channel >= channelCount) { + // Fill this channel with default data. + if (bitdepth == 16 && bpc == 16) { + stbi__uint16* q = ((stbi__uint16*)out) + channel; + stbi__uint16 val = channel == 3 ? 65535 : 0; + for (i = 0; i < pixelCount; i++, q += 4) + *q = val; + } + else { + stbi_uc* p = out + channel; + stbi_uc val = channel == 3 ? 255 : 0; + for (i = 0; i < pixelCount; i++, p += 4) + *p = val; + } + } + else { + if (ri->bits_per_channel == 16) { // output bpc + stbi__uint16* q = ((stbi__uint16*)out) + channel; + for (i = 0; i < pixelCount; i++, q += 4) + *q = (stbi__uint16)stbi__get16be(s); + } + else { + stbi_uc* p = out + channel; + if (bitdepth == 16) { // input bpc + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc)(stbi__get16be(s) >> 8); + } + else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } + } + } + } + } + + // remove weird white matte from PSD + if (channelCount >= 4) { + if (ri->bits_per_channel == 16) { + for (i = 0; i < w * h; ++i) { + stbi__uint16* pixel = (stbi__uint16*)out + 4 * i; + if (pixel[3] != 0 && pixel[3] != 65535) { + float a = pixel[3] / 65535.0f; + float ra = 1.0f / a; + float inv_a = 65535.0f * (1 - ra); + pixel[0] = (stbi__uint16)(pixel[0] * ra + inv_a); + pixel[1] = (stbi__uint16)(pixel[1] * ra + inv_a); + pixel[2] = (stbi__uint16)(pixel[2] * ra + inv_a); + } + } + } + else { + for (i = 0; i < w * h; ++i) { + unsigned char* pixel = out + 4 * i; + if (pixel[3] != 0 && pixel[3] != 255) { + float a = pixel[3] / 255.0f; + float ra = 1.0f / a; + float inv_a = 255.0f * (1 - ra); + pixel[0] = (unsigned char)(pixel[0] * ra + inv_a); + pixel[1] = (unsigned char)(pixel[1] * ra + inv_a); + pixel[2] = (unsigned char)(pixel[2] * ra + inv_a); + } + } + } + } + + // convert to desired output format + if (req_comp && req_comp != 4) { + if (ri->bits_per_channel == 16) + out = (stbi_uc*)stbi__convert_format16((stbi__uint16*)out, 4, req_comp, w, h); + else + out = stbi__convert_format(out, 4, req_comp, w, h); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + if (comp) *comp = 4; + *y = h; + *x = w; + + return out; +} +#endif + +// ************************************************************************************************* +// Softimage PIC loader +// by Tom Seddon +// +// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format +// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ + +#ifndef STBI_NO_PIC +static int stbi__pic_is4(stbi__context* s, const char* str) +{ + int i; + for (i = 0; i < 4; ++i) + if (stbi__get8(s) != (stbi_uc)str[i]) + return 0; + + return 1; +} + +static int stbi__pic_test_core(stbi__context* s) +{ + int i; + + if (!stbi__pic_is4(s, "\x53\x80\xF6\x34")) + return 0; + + for (i = 0; i < 84; ++i) + stbi__get8(s); + + if (!stbi__pic_is4(s, "PICT")) + return 0; + + return 1; +} + +typedef struct +{ + stbi_uc size, type, channel; +} stbi__pic_packet; + +static stbi_uc* stbi__readval(stbi__context* s, int channel, stbi_uc* dest) +{ + int mask = 0x80, i; + + for (i = 0; i < 4; ++i, mask >>= 1) { + if (channel & mask) { + if (stbi__at_eof(s)) return stbi__errpuc("bad file", "PIC file too short"); + dest[i] = stbi__get8(s); + } + } + + return dest; +} + +static void stbi__copyval(int channel, stbi_uc* dest, const stbi_uc* src) +{ + int mask = 0x80, i; + + for (i = 0; i < 4; ++i, mask >>= 1) + if (channel & mask) + dest[i] = src[i]; +} + +static stbi_uc* stbi__pic_load_core(stbi__context* s, int width, int height, int* comp, stbi_uc* result) +{ + int act_comp = 0, num_packets = 0, y, chained; + stbi__pic_packet packets[10]; + + // this will (should...) cater for even some bizarre stuff like having data + // for the same channel in multiple packets. + do { + stbi__pic_packet* packet; + + if (num_packets == sizeof(packets) / sizeof(packets[0])) + return stbi__errpuc("bad format", "too many packets"); + + packet = &packets[num_packets++]; + + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + + act_comp |= packet->channel; + + if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (reading packets)"); + if (packet->size != 8) return stbi__errpuc("bad format", "packet isn't 8bpp"); + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? + + for (y = 0; y < height; ++y) { + int packet_idx; + + for (packet_idx = 0; packet_idx < num_packets; ++packet_idx) { + stbi__pic_packet* packet = &packets[packet_idx]; + stbi_uc* dest = result + y * width * 4; + + switch (packet->type) { + default: + return stbi__errpuc("bad format", "packet has bad compression type"); + + case 0: {//uncompressed + int x; + + for (x = 0; x < width; ++x, dest += 4) + if (!stbi__readval(s, packet->channel, dest)) + return 0; + break; + } + + case 1://Pure RLE + { + int left = width, i; + + while (left > 0) { + stbi_uc count, value[4]; + + count = stbi__get8(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (pure read count)"); + + if (count > left) + count = (stbi_uc)left; + + if (!stbi__readval(s, packet->channel, value)) return 0; + + for (i = 0; i < count; ++i, dest += 4) + stbi__copyval(packet->channel, dest, value); + left -= count; + } + } + break; + + case 2: {//Mixed RLE + int left = width; + while (left > 0) { + int count = stbi__get8(s), i; + if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (mixed read count)"); + + if (count >= 128) { // Repeated + stbi_uc value[4]; + + if (count == 128) + count = stbi__get16be(s); + else + count -= 127; + if (count > left) + return stbi__errpuc("bad file", "scanline overrun"); + + if (!stbi__readval(s, packet->channel, value)) + return 0; + + for (i = 0; i < count; ++i, dest += 4) + stbi__copyval(packet->channel, dest, value); + } + else { // Raw + ++count; + if (count > left) return stbi__errpuc("bad file", "scanline overrun"); + + for (i = 0; i < count; ++i, dest += 4) + if (!stbi__readval(s, packet->channel, dest)) + return 0; + } + left -= count; + } + break; + } + } + } + } + + return result; +} + +static void* stbi__pic_load(stbi__context* s, int* px, int* py, int* comp, int req_comp, stbi__result_info* ri) +{ + stbi_uc* result; + int i, x, y, internal_comp; + STBI_NOTUSED(ri); + + if (!comp) comp = &internal_comp; + + for (i = 0; i < 92; ++i) + stbi__get8(s); + + x = stbi__get16be(s); + y = stbi__get16be(s); + + if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large", "Very large image (corrupt?)"); + if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large", "Very large image (corrupt?)"); + + if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (pic header)"); + if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); + + stbi__get32be(s); //skip `ratio' + stbi__get16be(s); //skip `fields' + stbi__get16be(s); //skip `pad' + + // intermediate buffer is RGBA + result = (stbi_uc*)stbi__malloc_mad3(x, y, 4, 0); + if (!result) return stbi__errpuc("outofmem", "Out of memory"); + memset(result, 0xff, x * y * 4); + + if (!stbi__pic_load_core(s, x, y, comp, result)) { + STBI_FREE(result); + result = 0; + } + *px = x; + *py = y; + if (req_comp == 0) req_comp = *comp; + result = stbi__convert_format(result, 4, req_comp, x, y); + + return result; +} + +static int stbi__pic_test(stbi__context* s) +{ + int r = stbi__pic_test_core(s); + stbi__rewind(s); + return r; +} +#endif + +// ************************************************************************************************* +// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb + +#ifndef STBI_NO_GIF +typedef struct +{ + stbi__int16 prefix; + stbi_uc first; + stbi_uc suffix; +} stbi__gif_lzw; + +typedef struct +{ + int w, h; + stbi_uc* out; // output buffer (always 4 components) + stbi_uc* background; // The current "background" as far as a gif is concerned + stbi_uc* history; + int flags, bgindex, ratio, transparent, eflags; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[8192]; + stbi_uc* color_table; + int parse, step; + int lflags; + int start_x, start_y; + int max_x, max_y; + int cur_x, cur_y; + int line_size; + int delay; +} stbi__gif; + +static int stbi__gif_test_raw(stbi__context* s) +{ + int sz; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; + sz = stbi__get8(s); + if (sz != '9' && sz != '7') return 0; + if (stbi__get8(s) != 'a') return 0; + return 1; +} + +static int stbi__gif_test(stbi__context* s) +{ + int r = stbi__gif_test_raw(s); + stbi__rewind(s); + return r; +} + +static void stbi__gif_parse_colortable(stbi__context* s, stbi_uc pal[256][4], int num_entries, int transp) +{ + int i; + for (i = 0; i < num_entries; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + pal[i][3] = transp == i ? 0 : 255; + } +} + +static int stbi__gif_header(stbi__context* s, stbi__gif* g, int* comp, int is_info) +{ + stbi_uc version; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') + return stbi__err("not GIF", "Corrupt GIF"); + + version = stbi__get8(s); + if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); + if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); + + stbi__g_failure_reason = ""; + g->w = stbi__get16le(s); + g->h = stbi__get16le(s); + g->flags = stbi__get8(s); + g->bgindex = stbi__get8(s); + g->ratio = stbi__get8(s); + g->transparent = -1; + + if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large", "Very large image (corrupt?)"); + if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large", "Very large image (corrupt?)"); + + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + + if (is_info) return 1; + + if (g->flags & 0x80) + stbi__gif_parse_colortable(s, g->pal, 2 << (g->flags & 7), -1); + + return 1; +} + +static int stbi__gif_info_raw(stbi__context* s, int* x, int* y, int* comp) +{ + stbi__gif* g = (stbi__gif*)stbi__malloc(sizeof(stbi__gif)); + if (!g) return stbi__err("outofmem", "Out of memory"); + if (!stbi__gif_header(s, g, comp, 1)) { + STBI_FREE(g); + stbi__rewind(s); + return 0; + } + if (x) *x = g->w; + if (y) *y = g->h; + STBI_FREE(g); + return 1; +} + +static void stbi__out_gif_code(stbi__gif* g, stbi__uint16 code) +{ + stbi_uc* p, * c; + int idx; + + // recurse to decode the prefixes, since the linked-list is backwards, + // and working backwards through an interleaved image would be nasty + if (g->codes[code].prefix >= 0) + stbi__out_gif_code(g, g->codes[code].prefix); + + if (g->cur_y >= g->max_y) return; + + idx = g->cur_x + g->cur_y; + p = &g->out[idx]; + g->history[idx / 4] = 1; + + c = &g->color_table[g->codes[code].suffix * 4]; + if (c[3] > 128) { // don't render transparent pixels; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } + g->cur_x += 4; + + if (g->cur_x >= g->max_x) { + g->cur_x = g->start_x; + g->cur_y += g->step; + + while (g->cur_y >= g->max_y && g->parse > 0) { + g->step = (1 << g->parse) * g->line_size; + g->cur_y = g->start_y + (g->step >> 1); + --g->parse; + } + } +} + +static stbi_uc* stbi__process_gif_raster(stbi__context* s, stbi__gif* g) +{ + stbi_uc lzw_cs; + stbi__int32 len, init_code; + stbi__uint32 first; + stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; + stbi__gif_lzw* p; + + lzw_cs = stbi__get8(s); + if (lzw_cs > 12) return NULL; + clear = 1 << lzw_cs; + first = 1; + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + bits = 0; + valid_bits = 0; + for (init_code = 0; init_code < clear; init_code++) { + g->codes[init_code].prefix = -1; + g->codes[init_code].first = (stbi_uc)init_code; + g->codes[init_code].suffix = (stbi_uc)init_code; + } + + // support no starting clear code + avail = clear + 2; + oldcode = -1; + + len = 0; + for (;;) { + if (valid_bits < codesize) { + if (len == 0) { + len = stbi__get8(s); // start new block + if (len == 0) + return g->out; + } + --len; + bits |= (stbi__int32)stbi__get8(s) << valid_bits; + valid_bits += 8; + } + else { + stbi__int32 code = bits & codemask; + bits >>= codesize; + valid_bits -= codesize; + // @OPTIMIZE: is there some way we can accelerate the non-clear path? + if (code == clear) { // clear code + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + avail = clear + 2; + oldcode = -1; + first = 0; + } + else if (code == clear + 1) { // end of stream code + stbi__skip(s, len); + while ((len = stbi__get8(s)) > 0) + stbi__skip(s, len); + return g->out; + } + else if (code <= avail) { + if (first) { + return stbi__errpuc("no clear code", "Corrupt GIF"); + } + + if (oldcode >= 0) { + p = &g->codes[avail++]; + if (avail > 8192) { + return stbi__errpuc("too many codes", "Corrupt GIF"); + } + + p->prefix = (stbi__int16)oldcode; + p->first = g->codes[oldcode].first; + p->suffix = (code == avail) ? p->first : g->codes[code].first; + } + else if (code == avail) + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + + stbi__out_gif_code(g, (stbi__uint16)code); + + if ((avail & codemask) == 0 && avail <= 0x0FFF) { + codesize++; + codemask = (1 << codesize) - 1; + } + + oldcode = code; + } + else { + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + } + } + } +} + +// this function is designed to support animated gifs, although stb_image doesn't support it +// two back is the image from two frames ago, used for a very specific disposal format +static stbi_uc* stbi__gif_load_next(stbi__context* s, stbi__gif* g, int* comp, int req_comp, stbi_uc* two_back) +{ + int dispose; + int first_frame; + int pi; + int pcount; + STBI_NOTUSED(req_comp); + + // on first frame, any non-written pixels get the background colour (non-transparent) + first_frame = 0; + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp, 0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) + return stbi__errpuc("too large", "GIF image is too large"); + pcount = g->w * g->h; + g->out = (stbi_uc*)stbi__malloc(4 * pcount); + g->background = (stbi_uc*)stbi__malloc(4 * pcount); + g->history = (stbi_uc*)stbi__malloc(pcount); + if (!g->out || !g->background || !g->history) + return stbi__errpuc("outofmem", "Out of memory"); + + // image is treated as "transparent" at the start - ie, nothing overwrites the current background; + // background colour is only used for pixels that are not rendered first frame, after that "background" + // color refers to the color that was there the previous frame. + memset(g->out, 0x00, 4 * pcount); + memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) + memset(g->history, 0x00, pcount); // pixels that were affected previous frame + first_frame = 1; + } + else { + // second frame - how do we dispose of the previous one? + dispose = (g->eflags & 0x1C) >> 2; + pcount = g->w * g->h; + + if ((dispose == 3) && (two_back == 0)) { + dispose = 2; // if I don't have an image to revert back to, default to the old background + } + + if (dispose == 3) { // use previous graphic + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy(&g->out[pi * 4], &two_back[pi * 4], 4); + } + } + } + else if (dispose == 2) { + // restore what was changed last frame to background before that frame; + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy(&g->out[pi * 4], &g->background[pi * 4], 4); + } + } + } + else { + // This is a non-disposal case eithe way, so just + // leave the pixels as is, and they will become the new background + // 1: do not dispose + // 0: not specified. + } + + // background is what out is after the undoing of the previou frame; + memcpy(g->background, g->out, 4 * g->w * g->h); + } + + // clear my history; + memset(g->history, 0x00, g->w * g->h); // pixels that were affected previous frame + + for (;;) { + int tag = stbi__get8(s); + switch (tag) { + case 0x2C: /* Image Descriptor */ + { + stbi__int32 x, y, w, h; + stbi_uc* o; + + x = stbi__get16le(s); + y = stbi__get16le(s); + w = stbi__get16le(s); + h = stbi__get16le(s); + if (((x + w) > (g->w)) || ((y + h) > (g->h))) + return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); + + g->line_size = g->w * 4; + g->start_x = x * 4; + g->start_y = y * g->line_size; + g->max_x = g->start_x + w * 4; + g->max_y = g->start_y + h * g->line_size; + g->cur_x = g->start_x; + g->cur_y = g->start_y; + + // if the width of the specified rectangle is 0, that means + // we may not see *any* pixels or the image is malformed; + // to make sure this is caught, move the current y down to + // max_y (which is what out_gif_code checks). + if (w == 0) + g->cur_y = g->max_y; + + g->lflags = stbi__get8(s); + + if (g->lflags & 0x40) { + g->step = 8 * g->line_size; // first interlaced spacing + g->parse = 3; + } + else { + g->step = g->line_size; + g->parse = 0; + } + + if (g->lflags & 0x80) { + stbi__gif_parse_colortable(s, g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); + g->color_table = (stbi_uc*)g->lpal; + } + else if (g->flags & 0x80) { + g->color_table = (stbi_uc*)g->pal; + } + else + return stbi__errpuc("missing color table", "Corrupt GIF"); + + o = stbi__process_gif_raster(s, g); + if (!o) return NULL; + + // if this was the first frame, + pcount = g->w * g->h; + if (first_frame && (g->bgindex > 0)) { + // if first frame, any pixel not drawn to gets the background color + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi] == 0) { + g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; + memcpy(&g->out[pi * 4], &g->pal[g->bgindex], 4); + } + } + } + + return o; + } + + case 0x21: // Comment Extension. + { + int len; + int ext = stbi__get8(s); + if (ext == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. + + // unset old transparent + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 255; + } + if (g->eflags & 0x01) { + g->transparent = stbi__get8(s); + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 0; + } + } + else { + // don't need transparent + stbi__skip(s, 1); + g->transparent = -1; + } + } + else { + stbi__skip(s, len); + break; + } + } + while ((len = stbi__get8(s)) != 0) { + stbi__skip(s, len); + } + break; + } + + case 0x3B: // gif stream termination code + return (stbi_uc*)s; // using '1' causes warning on some compilers + + default: + return stbi__errpuc("unknown code", "Corrupt GIF"); + } + } +} + +static void* stbi__load_gif_main_outofmem(stbi__gif* g, stbi_uc* out, int** delays) +{ + STBI_FREE(g->out); + STBI_FREE(g->history); + STBI_FREE(g->background); + + if (out) STBI_FREE(out); + if (delays && *delays) STBI_FREE(*delays); + return stbi__errpuc("outofmem", "Out of memory"); +} + +static void* stbi__load_gif_main(stbi__context* s, int** delays, int* x, int* y, int* z, int* comp, int req_comp) +{ + if (stbi__gif_test(s)) { + int layers = 0; + stbi_uc* u = 0; + stbi_uc* out = 0; + stbi_uc* two_back = 0; + stbi__gif g; + int stride; + int out_size = 0; + int delays_size = 0; + + STBI_NOTUSED(out_size); + STBI_NOTUSED(delays_size); + + memset(&g, 0, sizeof(g)); + if (delays) { + *delays = 0; + } + + do { + u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); + if (u == (stbi_uc*)s) u = 0; // end of animated gif marker + + if (u) { + *x = g.w; + *y = g.h; + ++layers; + stride = g.w * g.h * 4; + + if (out) { + void* tmp = (stbi_uc*)STBI_REALLOC_SIZED(out, out_size, layers * stride); + if (!tmp) + return stbi__load_gif_main_outofmem(&g, out, delays); + else { + out = (stbi_uc*)tmp; + out_size = layers * stride; + } + + if (delays) { + int* new_delays = (int*)STBI_REALLOC_SIZED(*delays, delays_size, sizeof(int) * layers); + if (!new_delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + *delays = new_delays; + delays_size = layers * sizeof(int); + } + } + else { + out = (stbi_uc*)stbi__malloc(layers * stride); + if (!out) + return stbi__load_gif_main_outofmem(&g, out, delays); + out_size = layers * stride; + if (delays) { + *delays = (int*)stbi__malloc(layers * sizeof(int)); + if (!*delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + delays_size = layers * sizeof(int); + } + } + memcpy(out + ((layers - 1) * stride), u, stride); + if (layers >= 2) { + two_back = out - 2 * stride; + } + + if (delays) { + (*delays)[layers - 1U] = g.delay; + } + } + } while (u != 0); + + // free temp buffer; + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + + // do the final conversion after loading everything; + if (req_comp && req_comp != 4) + out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); + + *z = layers; + return out; + } + else { + return stbi__errpuc("not GIF", "Image was not as a gif type."); + } +} + +static void* stbi__gif_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri) +{ + stbi_uc* u = 0; + stbi__gif g; + memset(&g, 0, sizeof(g)); + STBI_NOTUSED(ri); + + u = stbi__gif_load_next(s, &g, comp, req_comp, 0); + if (u == (stbi_uc*)s) u = 0; // end of animated gif marker + if (u) { + *x = g.w; + *y = g.h; + + // moved conversion to after successful load so that the same + // can be done for multiple frames. + if (req_comp && req_comp != 4) + u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + } + else if (g.out) { + // if there was an error and we allocated an image buffer, free it! + STBI_FREE(g.out); + } + + // free buffers needed for multiple frame loading; + STBI_FREE(g.history); + STBI_FREE(g.background); + + return u; +} + +static int stbi__gif_info(stbi__context* s, int* x, int* y, int* comp) +{ + return stbi__gif_info_raw(s, x, y, comp); +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR loader +// originally by Nicolas Schulz +#ifndef STBI_NO_HDR +static int stbi__hdr_test_core(stbi__context* s, const char* signature) +{ + int i; + for (i = 0; signature[i]; ++i) + if (stbi__get8(s) != signature[i]) + return 0; + stbi__rewind(s); + return 1; +} + +static int stbi__hdr_test(stbi__context* s) +{ + int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); + stbi__rewind(s); + if (!r) { + r = stbi__hdr_test_core(s, "#?RGBE\n"); + stbi__rewind(s); + } + return r; +} + +#define STBI__HDR_BUFLEN 1024 +static char* stbi__hdr_gettoken(stbi__context* z, char* buffer) +{ + int len = 0; + char c = '\0'; + + c = (char)stbi__get8(z); + + while (!stbi__at_eof(z) && c != '\n') { + buffer[len++] = c; + if (len == STBI__HDR_BUFLEN - 1) { + // flush to end of line + while (!stbi__at_eof(z) && stbi__get8(z) != '\n') + ; + break; + } + c = (char)stbi__get8(z); + } + + buffer[len] = 0; + return buffer; +} + +static void stbi__hdr_convert(float* output, stbi_uc* input, int req_comp) +{ + if (input[3] != 0) { + float f1; + // Exponent + f1 = (float)ldexp(1.0f, input[3] - (int)(128 + 8)); + if (req_comp <= 2) + output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + else { + output[0] = input[0] * f1; + output[1] = input[1] * f1; + output[2] = input[2] * f1; + } + if (req_comp == 2) output[1] = 1; + if (req_comp == 4) output[3] = 1; + } + else { + switch (req_comp) { + case 4: output[3] = 1; /* fallthrough */ + case 3: output[0] = output[1] = output[2] = 0; + break; + case 2: output[1] = 1; /* fallthrough */ + case 1: output[0] = 0; + break; + } + } +} + +static float* stbi__hdr_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri) +{ + char buffer[STBI__HDR_BUFLEN]; + char* token; + int valid = 0; + int width, height; + stbi_uc* scanline; + float* hdr_data; + int len; + unsigned char count, value; + int i, j, k, c1, c2, z; + const char* headerToken; + STBI_NOTUSED(ri); + + // Check identifier + headerToken = stbi__hdr_gettoken(s, buffer); + if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) + return stbi__errpf("not HDR", "Corrupt HDR image"); + + // Parse header + for (;;) { + token = stbi__hdr_gettoken(s, buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); + + // Parse width and height + // can't use sscanf() if we're not using stdio! + token = stbi__hdr_gettoken(s, buffer); + if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + height = (int)strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + width = (int)strtol(token, NULL, 10); + + if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large", "Very large image (corrupt?)"); + if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large", "Very large image (corrupt?)"); + + *x = width; + *y = height; + + if (comp) *comp = 3; + if (req_comp == 0) req_comp = 3; + + if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) + return stbi__errpf("too large", "HDR image is too large"); + + // Read data + hdr_data = (float*)stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); + if (!hdr_data) + return stbi__errpf("outofmem", "Out of memory"); + + // Load image data + // image data is stored as some number of sca + if (width < 8 || width >= 32768) { + // Read flat data + for (j = 0; j < height; ++j) { + for (i = 0; i < width; ++i) { + stbi_uc rgbe[4]; + main_decode_loop: + stbi__getn(s, rgbe, 4); + stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); + } + } + } + else { + // Read RLE-encoded data + scanline = NULL; + + for (j = 0; j < height; ++j) { + c1 = stbi__get8(s); + c2 = stbi__get8(s); + len = stbi__get8(s); + if (c1 != 2 || c2 != 2 || (len & 0x80)) { + // not run-length encoded, so we have to actually use THIS data as a decoded + // pixel (note this can't be a valid pixel--one of RGB must be >= 128) + stbi_uc rgbe[4]; + rgbe[0] = (stbi_uc)c1; + rgbe[1] = (stbi_uc)c2; + rgbe[2] = (stbi_uc)len; + rgbe[3] = (stbi_uc)stbi__get8(s); + stbi__hdr_convert(hdr_data, rgbe, req_comp); + i = 1; + j = 0; + STBI_FREE(scanline); + goto main_decode_loop; // yes, this makes no sense + } + len <<= 8; + len |= stbi__get8(s); + if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } + if (scanline == NULL) { + scanline = (stbi_uc*)stbi__malloc_mad2(width, 4, 0); + if (!scanline) { + STBI_FREE(hdr_data); + return stbi__errpf("outofmem", "Out of memory"); + } + } + + for (k = 0; k < 4; ++k) { + int nleft; + i = 0; + while ((nleft = width - i) > 0) { + count = stbi__get8(s); + if (count > 128) { + // Run + value = stbi__get8(s); + count -= 128; + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = value; + } + else { + // Dump + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = stbi__get8(s); + } + } + } + for (i = 0; i < width; ++i) + stbi__hdr_convert(hdr_data + (j * width + i) * req_comp, scanline + i * 4, req_comp); + } + if (scanline) + STBI_FREE(scanline); + } + + return hdr_data; +} + +static int stbi__hdr_info(stbi__context* s, int* x, int* y, int* comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char* token; + int valid = 0; + int dummy; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (stbi__hdr_test(s) == 0) { + stbi__rewind(s); + return 0; + } + + for (;;) { + token = stbi__hdr_gettoken(s, buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) { + stbi__rewind(s); + return 0; + } + token = stbi__hdr_gettoken(s, buffer); + if (strncmp(token, "-Y ", 3)) { + stbi__rewind(s); + return 0; + } + token += 3; + *y = (int)strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) { + stbi__rewind(s); + return 0; + } + token += 3; + *x = (int)strtol(token, NULL, 10); + *comp = 3; + return 1; +} +#endif // STBI_NO_HDR + +#ifndef STBI_NO_BMP +static int stbi__bmp_info(stbi__context* s, int* x, int* y, int* comp) +{ + void* p; + stbi__bmp_data info; + + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + if (p == NULL) { + stbi__rewind(s); + return 0; + } + if (x) *x = s->img_x; + if (y) *y = s->img_y; + if (comp) { + if (info.bpp == 24 && info.ma == 0xff000000) + *comp = 3; + else + *comp = info.ma ? 4 : 3; + } + return 1; +} +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_info(stbi__context* s, int* x, int* y, int* comp) +{ + int channelCount, dummy, depth; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind(s); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind(s); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind(s); + return 0; + } + *y = stbi__get32be(s); + *x = stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 8 && depth != 16) { + stbi__rewind(s); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind(s); + return 0; + } + *comp = 4; + return 1; +} + +static int stbi__psd_is16(stbi__context* s) +{ + int channelCount, depth; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind(s); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind(s); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind(s); + return 0; + } + STBI_NOTUSED(stbi__get32be(s)); + STBI_NOTUSED(stbi__get32be(s)); + depth = stbi__get16be(s); + if (depth != 16) { + stbi__rewind(s); + return 0; + } + return 1; +} +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_info(stbi__context* s, int* x, int* y, int* comp) +{ + int act_comp = 0, num_packets = 0, chained, dummy; + stbi__pic_packet packets[10]; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (!stbi__pic_is4(s, "\x53\x80\xF6\x34")) { + stbi__rewind(s); + return 0; + } + + stbi__skip(s, 88); + + *x = stbi__get16be(s); + *y = stbi__get16be(s); + if (stbi__at_eof(s)) { + stbi__rewind(s); + return 0; + } + if ((*x) != 0 && (1 << 28) / (*x) < (*y)) { + stbi__rewind(s); + return 0; + } + + stbi__skip(s, 8); + + do { + stbi__pic_packet* packet; + + if (num_packets == sizeof(packets) / sizeof(packets[0])) + return 0; + + packet = &packets[num_packets++]; + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + act_comp |= packet->channel; + + if (stbi__at_eof(s)) { + stbi__rewind(s); + return 0; + } + if (packet->size != 8) { + stbi__rewind(s); + return 0; + } + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); + + return 1; +} +#endif + +// ************************************************************************************************* +// Portable Gray Map and Portable Pixel Map loader +// by Ken Miller +// +// PGM: http://netpbm.sourceforge.net/doc/pgm.html +// PPM: http://netpbm.sourceforge.net/doc/ppm.html +// +// Known limitations: +// Does not support comments in the header section +// Does not support ASCII image data (formats P2 and P3) + +#ifndef STBI_NO_PNM + +static int stbi__pnm_test(stbi__context* s) +{ + char p, t; + p = (char)stbi__get8(s); + t = (char)stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + return 1; +} + +static void* stbi__pnm_load(stbi__context* s, int* x, int* y, int* comp, int req_comp, stbi__result_info* ri) +{ + stbi_uc* out; + STBI_NOTUSED(ri); + + ri->bits_per_channel = stbi__pnm_info(s, (int*)&s->img_x, (int*)&s->img_y, (int*)&s->img_n); + if (ri->bits_per_channel == 0) + return 0; + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large", "Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large", "Very large image (corrupt?)"); + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + + if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) + return stbi__errpuc("too large", "PNM too large"); + + out = (stbi_uc*)stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { + STBI_FREE(out); + return stbi__errpuc("bad PNM", "PNM file truncated"); + } + + if (req_comp && req_comp != s->img_n) { + if (ri->bits_per_channel == 16) { + out = (stbi_uc*)stbi__convert_format16((stbi__uint16*)out, s->img_n, req_comp, s->img_x, s->img_y); + } + else { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + } + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + return out; +} + +static int stbi__pnm_isspace(char c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; +} + +static void stbi__pnm_skip_whitespace(stbi__context* s, char* c) +{ + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char)stbi__get8(s); + + if (stbi__at_eof(s) || *c != '#') + break; + + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r') + *c = (char)stbi__get8(s); + } +} + +static int stbi__pnm_isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static int stbi__pnm_getinteger(stbi__context* s, char* c) +{ + int value = 0; + + while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { + value = value * 10 + (*c - '0'); + *c = (char)stbi__get8(s); + if ((value > 214748364) || (value == 214748364 && *c > '7')) + return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int"); + } + + return value; +} + +static int stbi__pnm_info(stbi__context* s, int* x, int* y, int* comp) +{ + int maxv, dummy; + char c, p, t; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + stbi__rewind(s); + + // Get identifier + p = (char)stbi__get8(s); + t = (char)stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + + *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm + + c = (char)stbi__get8(s); + stbi__pnm_skip_whitespace(s, &c); + + *x = stbi__pnm_getinteger(s, &c); // read width + if (*x == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + *y = stbi__pnm_getinteger(s, &c); // read height + if (*y == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + maxv = stbi__pnm_getinteger(s, &c); // read max value + if (maxv > 65535) + return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images"); + else if (maxv > 255) + return 16; + else + return 8; +} + +static int stbi__pnm_is16(stbi__context* s) +{ + if (stbi__pnm_info(s, NULL, NULL, NULL) == 16) + return 1; + return 0; +} +#endif + +static int stbi__info_main(stbi__context* s, int* x, int* y, int* comp) +{ +#ifndef STBI_NO_JPEG + if (stbi__jpeg_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_PNG + if (stbi__png_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_GIF + if (stbi__gif_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_BMP + if (stbi__bmp_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_PSD + if (stbi__psd_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_PIC + if (stbi__pic_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_PNM + if (stbi__pnm_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_HDR + if (stbi__hdr_info(s, x, y, comp)) return 1; +#endif + + // test tga last because it's a crappy test! +#ifndef STBI_NO_TGA + if (stbi__tga_info(s, x, y, comp)) + return 1; +#endif + return stbi__err("unknown image type", "Image not of any known type, or corrupt"); +} + +static int stbi__is_16_main(stbi__context* s) +{ +#ifndef STBI_NO_PNG + if (stbi__png_is16(s)) return 1; +#endif + +#ifndef STBI_NO_PSD + if (stbi__psd_is16(s)) return 1; +#endif + +#ifndef STBI_NO_PNM + if (stbi__pnm_is16(s)) return 1; +#endif + return 0; +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info(char const* filename, int* x, int* y, int* comp) +{ + FILE* f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_info_from_file(f, x, y, comp); + fclose(f); + return result; +} + +STBIDEF int stbi_info_from_file(FILE* f, int* x, int* y, int* comp) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__info_main(&s, x, y, comp); + fseek(f, pos, SEEK_SET); + return r; +} + +STBIDEF int stbi_is_16_bit(char const* filename) +{ + FILE* f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_is_16_bit_from_file(f); + fclose(f); + return result; +} + +STBIDEF int stbi_is_16_bit_from_file(FILE* f) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__is_16_main(&s); + fseek(f, pos, SEEK_SET); + return r; +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_info_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* comp) +{ + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__info_main(&s, x, y, comp); +} + +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const* c, void* user, int* x, int* y, int* comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks*)c, user); + return stbi__info_main(&s, x, y, comp); +} + +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const* buffer, int len) +{ + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__is_16_main(&s); +} + +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const* c, void* user) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks*)c, user); + return stbi__is_16_main(&s); +} + +#endif // STB_IMAGE_IMPLEMENTATION + +/* + revision history: + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug + 1-bit BMP + *_is_16_bit api + avoid warnings + 2.16 (2017-07-23) all functions have 16-bit variants; + STBI_NO_STDIO works again; + compilation fixes; + fix rounding in unpremultiply; + optimize vertical flip; + disable raw_len validation; + documentation fixes + 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; + warning fixes; disable run-time SSE detection on gcc; + uniform handling of optional "return" values; + thread-safe initialization of zlib tables + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) allocate large structures on the stack + remove white matting for transparent PSD + fix reported channel count for PNG & BMP + re-enable SSE2 in non-gcc 64-bit + support RGB-formatted JPEG + read 16-bit PNGs (only as 8-bit) + 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED + 2.09 (2016-01-16) allow comments in PNM files + 16-bit-per-pixel TGA (not bit-per-component) + info() for TGA could break due to .hdr handling + info() for BMP to shares code instead of sloppy parse + can use STBI_REALLOC_SIZED if allocator doesn't support realloc + code cleanup + 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA + 2.07 (2015-09-13) fix compiler warnings + partial animated GIF support + limited 16-bpc PSD support + #ifdef unused functions + bug with < 92 byte PIC,PNM,HDR,TGA + 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value + 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning + 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit + 2.03 (2015-04-12) extra corruption checking (mmozeiko) + stbi_set_flip_vertically_on_load (nguillemot) + fix NEON support; fix mingw support + 2.02 (2015-01-19) fix incorrect assert, fix warning + 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 + 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG + 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) + progressive JPEG (stb) + PGM/PPM support (Ken Miller) + STBI_MALLOC,STBI_REALLOC,STBI_FREE + GIF bugfix -- seemingly never worked + STBI_NO_*, STBI_ONLY_* + 1.48 (2014-12-14) fix incorrectly-named assert() + 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) + optimize PNG (ryg) + fix bug in interlaced PNG with user-specified channel count (stb) + 1.46 (2014-08-26) + fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG + 1.45 (2014-08-16) + fix MSVC-ARM internal compiler error by wrapping malloc + 1.44 (2014-08-07) + various warning fixes from Ronny Chevalier + 1.43 (2014-07-15) + fix MSVC-only compiler problem in code changed in 1.42 + 1.42 (2014-07-09) + don't define _CRT_SECURE_NO_WARNINGS (affects user code) + fixes to stbi__cleanup_jpeg path + added STBI_ASSERT to avoid requiring assert.h + 1.41 (2014-06-25) + fix search&replace from 1.36 that messed up comments/error messages + 1.40 (2014-06-22) + fix gcc struct-initialization warning + 1.39 (2014-06-15) + fix to TGA optimization when req_comp != number of components in TGA; + fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) + add support for BMP version 5 (more ignored fields) + 1.38 (2014-06-06) + suppress MSVC warnings on integer casts truncating values + fix accidental rename of 'skip' field of I/O + 1.37 (2014-06-04) + remove duplicate typedef + 1.36 (2014-06-03) + convert to header file single-file library + if de-iphone isn't set, load iphone images color-swapped instead of returning NULL + 1.35 (2014-05-27) + various warnings + fix broken STBI_SIMD path + fix bug where stbi_load_from_file no longer left file pointer in correct place + fix broken non-easy path for 32-bit BMP (possibly never used) + TGA optimization by Arseny Kapoulkine + 1.34 (unknown) + use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case + 1.33 (2011-07-14) + make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements + 1.32 (2011-07-13) + support for "info" function for all supported filetypes (SpartanJ) + 1.31 (2011-06-20) + a few more leak fixes, bug in PNG handling (SpartanJ) + 1.30 (2011-06-11) + added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) + removed deprecated format-specific test/load functions + removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway + error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) + fix inefficiency in decoding 32-bit BMP (David Woo) + 1.29 (2010-08-16) + various warning fixes from Aurelien Pocheville + 1.28 (2010-08-01) + fix bug in GIF palette transparency (SpartanJ) + 1.27 (2010-08-01) + cast-to-stbi_uc to fix warnings + 1.26 (2010-07-24) + fix bug in file buffering for PNG reported by SpartanJ + 1.25 (2010-07-17) + refix trans_data warning (Won Chun) + 1.24 (2010-07-12) + perf improvements reading from files on platforms with lock-heavy fgetc() + minor perf improvements for jpeg + deprecated type-specific functions so we'll get feedback if they're needed + attempt to fix trans_data warning (Won Chun) + 1.23 fixed bug in iPhone support + 1.22 (2010-07-10) + removed image *writing* support + stbi_info support from Jetro Lauha + GIF support from Jean-Marc Lienher + iPhone PNG-extensions from James Brown + warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) + 1.21 fix use of 'stbi_uc' in header (reported by jon blow) + 1.20 added support for Softimage PIC, by Tom Seddon + 1.19 bug in interlaced PNG corruption check (found by ryg) + 1.18 (2008-08-02) + fix a threading bug (local mutable static) + 1.17 support interlaced PNG + 1.16 major bugfix - stbi__convert_format converted one too many pixels + 1.15 initialize some fields for thread safety + 1.14 fix threadsafe conversion bug + header-file-only version (#define STBI_HEADER_FILE_ONLY before including) + 1.13 threadsafe + 1.12 const qualifiers in the API + 1.11 Support installable IDCT, colorspace conversion routines + 1.10 Fixes for 64-bit (don't use "unsigned long") + optimized upsampling by Fabian "ryg" Giesen + 1.09 Fix format-conversion for PSD code (bad global variables!) + 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz + 1.07 attempt to fix C++ warning/errors again + 1.06 attempt to fix C++ warning/errors again + 1.05 fix TGA loading to return correct *comp and use good luminance calc + 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free + 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR + 1.02 support for (subset of) HDR files, float interface for preferred access to them + 1.01 fix bug: possible bug in handling right-side up bmps... not sure + fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all + 1.00 interface to zlib that skips zlib header + 0.99 correct handling of alpha in palette + 0.98 TGA loader by lonesock; dynamically add loaders (untested) + 0.97 jpeg errors on too large a file; also catch another malloc failure + 0.96 fix detection of invalid v value - particleman@mollyrocket forum + 0.95 during header scan, seek to markers in case of padding + 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same + 0.93 handle jpegtran output; verbose errors + 0.92 read 4,8,16,24,32-bit BMP files of several formats + 0.91 output 24-bit Windows 3.0 BMP files + 0.90 fix a few more warnings; bump version number to approach 1.0 + 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd + 0.60 fix compiling as c++ + 0.59 fix warnings: merge Dave Moore's -Wall fixes + 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian + 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available + 0.56 fix bug: zlib uncompressed mode len vs. nlen + 0.55 fix bug: restart_interval not initialized to 0 + 0.54 allow NULL for 'int *comp' + 0.53 fix bug in png 3->4; speedup png decoding + 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments + 0.51 obey req_comp requests, 1-component jpegs return as 1-component, + on 'test' only check type, not whether we support this variant + 0.50 (2006-11-19) + first released version +*/ + + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/native/monogame/common/stb_image_write.h b/native/monogame/common/stb_image_write.h new file mode 100644 index 00000000000..e4b32ed1bc3 --- /dev/null +++ b/native/monogame/common/stb_image_write.h @@ -0,0 +1,1724 @@ +/* stb_image_write - v1.16 - public domain - http://nothings.org/stb + writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015 + no warranty implied; use at your own risk + + Before #including, + + #define STB_IMAGE_WRITE_IMPLEMENTATION + + in the file that you want to have the implementation. + + Will probably not work correctly with strict-aliasing optimizations. + +ABOUT: + + This header file is a library for writing images to C stdio or a callback. + + The PNG output is not optimal; it is 20-50% larger than the file + written by a decent optimizing implementation; though providing a custom + zlib compress function (see STBIW_ZLIB_COMPRESS) can mitigate that. + This library is designed for source code compactness and simplicity, + not optimal image file size or run-time performance. + +BUILDING: + + You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h. + You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace + malloc,realloc,free. + You can #define STBIW_MEMMOVE() to replace memmove() + You can #define STBIW_ZLIB_COMPRESS to use a custom zlib-style compress function + for PNG compression (instead of the builtin one), it must have the following signature: + unsigned char * my_compress(unsigned char *data, int data_len, int *out_len, int quality); + The returned data will be freed with STBIW_FREE() (free() by default), + so it must be heap allocated with STBIW_MALLOC() (malloc() by default), + +UNICODE: + + If compiling for Windows and you wish to use Unicode filenames, compile + with + #define STBIW_WINDOWS_UTF8 + and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert + Windows wchar_t filenames to utf8. + +USAGE: + + There are five functions, one for each image file format: + + int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); + int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); + int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); + int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality); + int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); + + void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically + + There are also five equivalent functions that use an arbitrary write function. You are + expected to open/close your file-equivalent before and after calling these: + + int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); + int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); + int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); + int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); + int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); + + where the callback is: + void stbi_write_func(void *context, void *data, int size); + + You can configure it with these global variables: + int stbi_write_tga_with_rle; // defaults to true; set to 0 to disable RLE + int stbi_write_png_compression_level; // defaults to 8; set to higher for more compression + int stbi_write_force_png_filter; // defaults to -1; set to 0..5 to force a filter mode + + + You can define STBI_WRITE_NO_STDIO to disable the file variant of these + functions, so the library will not use stdio.h at all. However, this will + also disable HDR writing, because it requires stdio for formatted output. + + Each function returns 0 on failure and non-0 on success. + + The functions create an image file defined by the parameters. The image + is a rectangle of pixels stored from left-to-right, top-to-bottom. + Each pixel contains 'comp' channels of data stored interleaved with 8-bits + per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is + monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall. + The *data pointer points to the first byte of the top-left-most pixel. + For PNG, "stride_in_bytes" is the distance in bytes from the first byte of + a row of pixels to the first byte of the next row of pixels. + + PNG creates output files with the same number of components as the input. + The BMP format expands Y to RGB in the file format and does not + output alpha. + + PNG supports writing rectangles of data even when the bytes storing rows of + data are not consecutive in memory (e.g. sub-rectangles of a larger image), + by supplying the stride between the beginning of adjacent rows. The other + formats do not. (Thus you cannot write a native-format BMP through the BMP + writer, both because it is in BGR order and because it may have padding + at the end of the line.) + + PNG allows you to set the deflate compression level by setting the global + variable 'stbi_write_png_compression_level' (it defaults to 8). + + HDR expects linear float data. Since the format is always 32-bit rgb(e) + data, alpha (if provided) is discarded, and for monochrome data it is + replicated across all three channels. + + TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed + data, set the global variable 'stbi_write_tga_with_rle' to 0. + + JPEG does ignore alpha channels in input data; quality is between 1 and 100. + Higher quality looks better but results in a bigger image. + JPEG baseline (no JPEG progressive). + +CREDITS: + + + Sean Barrett - PNG/BMP/TGA + Baldur Karlsson - HDR + Jean-Sebastien Guay - TGA monochrome + Tim Kelsey - misc enhancements + Alan Hickman - TGA RLE + Emmanuel Julien - initial file IO callback implementation + Jon Olick - original jo_jpeg.cpp code + Daniel Gibson - integrate JPEG, allow external zlib + Aarni Koskela - allow choosing PNG filter + + bugfixes: + github:Chribba + Guillaume Chereau + github:jry2 + github:romigrou + Sergio Gonzalez + Jonas Karlsson + Filip Wasil + Thatcher Ulrich + github:poppolopoppo + Patrick Boettcher + github:xeekworx + Cap Petschulat + Simon Rodriguez + Ivan Tikhonov + github:ignotion + Adam Schackart + Andrew Kensler + +LICENSE + + See end of file for license information. + +*/ + +#ifndef INCLUDE_STB_IMAGE_WRITE_H +#define INCLUDE_STB_IMAGE_WRITE_H + +#include + +// if STB_IMAGE_WRITE_STATIC causes problems, try defining STBIWDEF to 'inline' or 'static inline' +#ifndef STBIWDEF +#ifdef STB_IMAGE_WRITE_STATIC +#define STBIWDEF static +#else +#ifdef __cplusplus +#define STBIWDEF extern "C" +#else +#define STBIWDEF extern +#endif +#endif +#endif + +#ifndef STB_IMAGE_WRITE_STATIC // C++ forbids static forward declarations +STBIWDEF int stbi_write_tga_with_rle; +STBIWDEF int stbi_write_png_compression_level; +STBIWDEF int stbi_write_force_png_filter; +#endif + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); +STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); +STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality); + +#ifdef STBIW_WINDOWS_UTF8 +STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); +#endif +#endif + +typedef void stbi_write_func(void *context, void *data, int size); + +STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); +STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); +STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); +STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); + +STBIWDEF void stbi_flip_vertically_on_write(int flip_boolean); + +#endif//INCLUDE_STB_IMAGE_WRITE_H + +#ifdef STB_IMAGE_WRITE_IMPLEMENTATION + +#ifdef _WIN32 + #ifndef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS + #endif + #ifndef _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_NONSTDC_NO_DEPRECATE + #endif +#endif + +#ifndef STBI_WRITE_NO_STDIO +#include +#endif // STBI_WRITE_NO_STDIO + +#include +#include +#include +#include + +#if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED)) +// ok +#elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)." +#endif + +#ifndef STBIW_MALLOC +#define STBIW_MALLOC(sz) malloc(sz) +#define STBIW_REALLOC(p,newsz) realloc(p,newsz) +#define STBIW_FREE(p) free(p) +#endif + +#ifndef STBIW_REALLOC_SIZED +#define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz) +#endif + + +#ifndef STBIW_MEMMOVE +#define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz) +#endif + + +#ifndef STBIW_ASSERT +#include +#define STBIW_ASSERT(x) assert(x) +#endif + +#define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff) + +#ifdef STB_IMAGE_WRITE_STATIC +static int stbi_write_png_compression_level = 8; +static int stbi_write_tga_with_rle = 1; +static int stbi_write_force_png_filter = -1; +#else +int stbi_write_png_compression_level = 8; +int stbi_write_tga_with_rle = 1; +int stbi_write_force_png_filter = -1; +#endif + +static int stbi__flip_vertically_on_write = 0; + +STBIWDEF void stbi_flip_vertically_on_write(int flag) +{ + stbi__flip_vertically_on_write = flag; +} + +typedef struct +{ + stbi_write_func *func; + void *context; + unsigned char buffer[64]; + int buf_used; +} stbi__write_context; + +// initialize a callback-based context +static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context) +{ + s->func = c; + s->context = context; +} + +#ifndef STBI_WRITE_NO_STDIO + +static void stbi__stdio_write(void *context, void *data, int size) +{ + fwrite(data,1,size,(FILE*) context); +} + +#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) +#ifdef __cplusplus +#define STBIW_EXTERN extern "C" +#else +#define STBIW_EXTERN extern +#endif +STBIW_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); +STBIW_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); + +STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) +{ + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); +} +#endif + +static FILE *stbiw__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) + wchar_t wMode[64]; + wchar_t wFilename[1024]; + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) + return 0; + + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) + return 0; + +#if defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != _wfopen_s(&f, wFilename, wMode)) + f = 0; +#else + f = _wfopen(wFilename, wMode); +#endif + +#elif defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != fopen_s(&f, filename, mode)) + f=0; +#else + f = fopen(filename, mode); +#endif + return f; +} + +static int stbi__start_write_file(stbi__write_context *s, const char *filename) +{ + FILE *f = stbiw__fopen(filename, "wb"); + stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); + return f != NULL; +} + +static void stbi__end_write_file(stbi__write_context *s) +{ + fclose((FILE *)s->context); +} + +#endif // !STBI_WRITE_NO_STDIO + +typedef unsigned int stbiw_uint32; +typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1]; + +static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) +{ + while (*fmt) { + switch (*fmt++) { + case ' ': break; + case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int)); + s->func(s->context,&x,1); + break; } + case '2': { int x = va_arg(v,int); + unsigned char b[2]; + b[0] = STBIW_UCHAR(x); + b[1] = STBIW_UCHAR(x>>8); + s->func(s->context,b,2); + break; } + case '4': { stbiw_uint32 x = va_arg(v,int); + unsigned char b[4]; + b[0]=STBIW_UCHAR(x); + b[1]=STBIW_UCHAR(x>>8); + b[2]=STBIW_UCHAR(x>>16); + b[3]=STBIW_UCHAR(x>>24); + s->func(s->context,b,4); + break; } + default: + STBIW_ASSERT(0); + return; + } + } +} + +static void stbiw__writef(stbi__write_context *s, const char *fmt, ...) +{ + va_list v; + va_start(v, fmt); + stbiw__writefv(s, fmt, v); + va_end(v); +} + +static void stbiw__write_flush(stbi__write_context *s) +{ + if (s->buf_used) { + s->func(s->context, &s->buffer, s->buf_used); + s->buf_used = 0; + } +} + +static void stbiw__putc(stbi__write_context *s, unsigned char c) +{ + s->func(s->context, &c, 1); +} + +static void stbiw__write1(stbi__write_context *s, unsigned char a) +{ + if ((size_t)s->buf_used + 1 > sizeof(s->buffer)) + stbiw__write_flush(s); + s->buffer[s->buf_used++] = a; +} + +static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c) +{ + int n; + if ((size_t)s->buf_used + 3 > sizeof(s->buffer)) + stbiw__write_flush(s); + n = s->buf_used; + s->buf_used = n+3; + s->buffer[n+0] = a; + s->buffer[n+1] = b; + s->buffer[n+2] = c; +} + +static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d) +{ + unsigned char bg[3] = { 255, 0, 255}, px[3]; + int k; + + if (write_alpha < 0) + stbiw__write1(s, d[comp - 1]); + + switch (comp) { + case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as 1-channel case + case 1: + if (expand_mono) + stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp + else + stbiw__write1(s, d[0]); // monochrome TGA + break; + case 4: + if (!write_alpha) { + // composite against pink background + for (k = 0; k < 3; ++k) + px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255; + stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]); + break; + } + /* FALLTHROUGH */ + case 3: + stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]); + break; + } + if (write_alpha > 0) + stbiw__write1(s, d[comp - 1]); +} + +static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono) +{ + stbiw_uint32 zero = 0; + int i,j, j_end; + + if (y <= 0) + return; + + if (stbi__flip_vertically_on_write) + vdir *= -1; + + if (vdir < 0) { + j_end = -1; j = y-1; + } else { + j_end = y; j = 0; + } + + for (; j != j_end; j += vdir) { + for (i=0; i < x; ++i) { + unsigned char *d = (unsigned char *) data + (j*x+i)*comp; + stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d); + } + stbiw__write_flush(s); + s->func(s->context, &zero, scanline_pad); + } +} + +static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...) +{ + if (y < 0 || x < 0) { + return 0; + } else { + va_list v; + va_start(v, fmt); + stbiw__writefv(s, fmt, v); + va_end(v); + stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono); + return 1; + } +} + +static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data) +{ + if (comp != 4) { + // write RGB bitmap + int pad = (-x*3) & 3; + return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad, + "11 4 22 4" "4 44 22 444444", + 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header + 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header + } else { + // RGBA bitmaps need a v4 header + // use BI_BITFIELDS mode with 32bpp and alpha mask + // (straight BI_RGB with alpha mask doesn't work in most readers) + return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *)data,1,0, + "11 4 22 4" "4 44 22 444444 4444 4 444 444 444 444", + 'B', 'M', 14+108+x*y*4, 0, 0, 14+108, // file header + 108, x,y, 1,32, 3,0,0,0,0,0, 0xff0000,0xff00,0xff,0xff000000u, 0, 0,0,0, 0,0,0, 0,0,0, 0,0,0); // bitmap V4 header + } +} + +STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) +{ + stbi__write_context s = { 0 }; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_bmp_core(&s, x, y, comp, data); +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data) +{ + stbi__write_context s = { 0 }; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_bmp_core(&s, x, y, comp, data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif //!STBI_WRITE_NO_STDIO + +static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data) +{ + int has_alpha = (comp == 2 || comp == 4); + int colorbytes = has_alpha ? comp-1 : comp; + int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 + + if (y < 0 || x < 0) + return 0; + + if (!stbi_write_tga_with_rle) { + return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0, + "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8); + } else { + int i,j,k; + int jend, jdir; + + stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8); + + if (stbi__flip_vertically_on_write) { + j = 0; + jend = y; + jdir = 1; + } else { + j = y-1; + jend = -1; + jdir = -1; + } + for (; j != jend; j += jdir) { + unsigned char *row = (unsigned char *) data + j * x * comp; + int len; + + for (i = 0; i < x; i += len) { + unsigned char *begin = row + i * comp; + int diff = 1; + len = 1; + + if (i < x - 1) { + ++len; + diff = memcmp(begin, row + (i + 1) * comp, comp); + if (diff) { + const unsigned char *prev = begin; + for (k = i + 2; k < x && len < 128; ++k) { + if (memcmp(prev, row + k * comp, comp)) { + prev += comp; + ++len; + } else { + --len; + break; + } + } + } else { + for (k = i + 2; k < x && len < 128; ++k) { + if (!memcmp(begin, row + k * comp, comp)) { + ++len; + } else { + break; + } + } + } + } + + if (diff) { + unsigned char header = STBIW_UCHAR(len - 1); + stbiw__write1(s, header); + for (k = 0; k < len; ++k) { + stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp); + } + } else { + unsigned char header = STBIW_UCHAR(len - 129); + stbiw__write1(s, header); + stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin); + } + } + } + stbiw__write_flush(s); + } + return 1; +} + +STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) +{ + stbi__write_context s = { 0 }; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_tga_core(&s, x, y, comp, (void *) data); +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data) +{ + stbi__write_context s = { 0 }; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR writer +// by Baldur Karlsson + +#define stbiw__max(a, b) ((a) > (b) ? (a) : (b)) + +#ifndef STBI_WRITE_NO_STDIO + +static void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) +{ + int exponent; + float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); + + if (maxcomp < 1e-32f) { + rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; + } else { + float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; + + rgbe[0] = (unsigned char)(linear[0] * normalize); + rgbe[1] = (unsigned char)(linear[1] * normalize); + rgbe[2] = (unsigned char)(linear[2] * normalize); + rgbe[3] = (unsigned char)(exponent + 128); + } +} + +static void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte) +{ + unsigned char lengthbyte = STBIW_UCHAR(length+128); + STBIW_ASSERT(length+128 <= 255); + s->func(s->context, &lengthbyte, 1); + s->func(s->context, &databyte, 1); +} + +static void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data) +{ + unsigned char lengthbyte = STBIW_UCHAR(length); + STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code + s->func(s->context, &lengthbyte, 1); + s->func(s->context, data, length); +} + +static void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline) +{ + unsigned char scanlineheader[4] = { 2, 2, 0, 0 }; + unsigned char rgbe[4]; + float linear[3]; + int x; + + scanlineheader[2] = (width&0xff00)>>8; + scanlineheader[3] = (width&0x00ff); + + /* skip RLE for images too small or large */ + if (width < 8 || width >= 32768) { + for (x=0; x < width; x++) { + switch (ncomp) { + case 4: /* fallthrough */ + case 3: linear[2] = scanline[x*ncomp + 2]; + linear[1] = scanline[x*ncomp + 1]; + linear[0] = scanline[x*ncomp + 0]; + break; + default: + linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; + break; + } + stbiw__linear_to_rgbe(rgbe, linear); + s->func(s->context, rgbe, 4); + } + } else { + int c,r; + /* encode into scratch buffer */ + for (x=0; x < width; x++) { + switch(ncomp) { + case 4: /* fallthrough */ + case 3: linear[2] = scanline[x*ncomp + 2]; + linear[1] = scanline[x*ncomp + 1]; + linear[0] = scanline[x*ncomp + 0]; + break; + default: + linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; + break; + } + stbiw__linear_to_rgbe(rgbe, linear); + scratch[x + width*0] = rgbe[0]; + scratch[x + width*1] = rgbe[1]; + scratch[x + width*2] = rgbe[2]; + scratch[x + width*3] = rgbe[3]; + } + + s->func(s->context, scanlineheader, 4); + + /* RLE each component separately */ + for (c=0; c < 4; c++) { + unsigned char *comp = &scratch[width*c]; + + x = 0; + while (x < width) { + // find first run + r = x; + while (r+2 < width) { + if (comp[r] == comp[r+1] && comp[r] == comp[r+2]) + break; + ++r; + } + if (r+2 >= width) + r = width; + // dump up to first run + while (x < r) { + int len = r-x; + if (len > 128) len = 128; + stbiw__write_dump_data(s, len, &comp[x]); + x += len; + } + // if there's a run, output it + if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd + // find next byte after run + while (r < width && comp[r] == comp[x]) + ++r; + // output run up to r + while (x < r) { + int len = r-x; + if (len > 127) len = 127; + stbiw__write_run_data(s, len, comp[x]); + x += len; + } + } + } + } + } +} + +static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data) +{ + if (y <= 0 || x <= 0 || data == NULL) + return 0; + else { + // Each component is stored separately. Allocate scratch space for full output scanline. + unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4); + int i, len; + char buffer[128]; + char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n"; + s->func(s->context, header, sizeof(header)-1); + +#ifdef __STDC_LIB_EXT1__ + len = sprintf_s(buffer, sizeof(buffer), "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); +#else + len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); +#endif + s->func(s->context, buffer, len); + + for(i=0; i < y; i++) + stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*x*(stbi__flip_vertically_on_write ? y-1-i : i)); + STBIW_FREE(scratch); + return 1; + } +} + +STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data) +{ + stbi__write_context s = { 0 }; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_hdr_core(&s, x, y, comp, (float *) data); +} + +STBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data) +{ + stbi__write_context s = { 0 }; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif // STBI_WRITE_NO_STDIO + + +////////////////////////////////////////////////////////////////////////////// +// +// PNG writer +// + +#ifndef STBIW_ZLIB_COMPRESS +// stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size() +#define stbiw__sbraw(a) ((int *) (void *) (a) - 2) +#define stbiw__sbm(a) stbiw__sbraw(a)[0] +#define stbiw__sbn(a) stbiw__sbraw(a)[1] + +#define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a)) +#define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0) +#define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a))) + +#define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v)) +#define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0) +#define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0) + +static void *stbiw__sbgrowf(void **arr, int increment, int itemsize) +{ + int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; + void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2); + STBIW_ASSERT(p); + if (p) { + if (!*arr) ((int *) p)[1] = 0; + *arr = (void *) ((int *) p + 2); + stbiw__sbm(*arr) = m; + } + return *arr; +} + +static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount) +{ + while (*bitcount >= 8) { + stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer)); + *bitbuffer >>= 8; + *bitcount -= 8; + } + return data; +} + +static int stbiw__zlib_bitrev(int code, int codebits) +{ + int res=0; + while (codebits--) { + res = (res << 1) | (code & 1); + code >>= 1; + } + return res; +} + +static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit) +{ + int i; + for (i=0; i < limit && i < 258; ++i) + if (a[i] != b[i]) break; + return i; +} + +static unsigned int stbiw__zhash(unsigned char *data) +{ + stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16); + hash ^= hash << 3; + hash += hash >> 5; + hash ^= hash << 4; + hash += hash >> 17; + hash ^= hash << 25; + hash += hash >> 6; + return hash; +} + +#define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount)) +#define stbiw__zlib_add(code,codebits) \ + (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush()) +#define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c) +// default huffman tables +#define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8) +#define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9) +#define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7) +#define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8) +#define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n)) +#define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n)) + +#define stbiw__ZHASH 16384 + +#endif // STBIW_ZLIB_COMPRESS + +STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality) +{ +#ifdef STBIW_ZLIB_COMPRESS + // user provided a zlib compress implementation, use that + return STBIW_ZLIB_COMPRESS(data, data_len, out_len, quality); +#else // use builtin + static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 }; + static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; + static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 }; + static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 }; + unsigned int bitbuf=0; + int i,j, bitcount=0; + unsigned char *out = NULL; + unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(unsigned char**)); + if (hash_table == NULL) + return NULL; + if (quality < 5) quality = 5; + + stbiw__sbpush(out, 0x78); // DEFLATE 32K window + stbiw__sbpush(out, 0x5e); // FLEVEL = 1 + stbiw__zlib_add(1,1); // BFINAL = 1 + stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman + + for (i=0; i < stbiw__ZHASH; ++i) + hash_table[i] = NULL; + + i=0; + while (i < data_len-3) { + // hash next 3 bytes of data to be compressed + int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3; + unsigned char *bestloc = 0; + unsigned char **hlist = hash_table[h]; + int n = stbiw__sbcount(hlist); + for (j=0; j < n; ++j) { + if (hlist[j]-data > i-32768) { // if entry lies within window + int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i); + if (d >= best) { best=d; bestloc=hlist[j]; } + } + } + // when hash table entry is too long, delete half the entries + if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) { + STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality); + stbiw__sbn(hash_table[h]) = quality; + } + stbiw__sbpush(hash_table[h],data+i); + + if (bestloc) { + // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal + h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1); + hlist = hash_table[h]; + n = stbiw__sbcount(hlist); + for (j=0; j < n; ++j) { + if (hlist[j]-data > i-32767) { + int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1); + if (e > best) { // if next match is better, bail on current match + bestloc = NULL; + break; + } + } + } + } + + if (bestloc) { + int d = (int) (data+i - bestloc); // distance back + STBIW_ASSERT(d <= 32767 && best <= 258); + for (j=0; best > lengthc[j+1]-1; ++j); + stbiw__zlib_huff(j+257); + if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]); + for (j=0; d > distc[j+1]-1; ++j); + stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5); + if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]); + i += best; + } else { + stbiw__zlib_huffb(data[i]); + ++i; + } + } + // write out final bytes + for (;i < data_len; ++i) + stbiw__zlib_huffb(data[i]); + stbiw__zlib_huff(256); // end of block + // pad with 0 bits to byte boundary + while (bitcount) + stbiw__zlib_add(0,1); + + for (i=0; i < stbiw__ZHASH; ++i) + (void) stbiw__sbfree(hash_table[i]); + STBIW_FREE(hash_table); + + // store uncompressed instead if compression was worse + if (stbiw__sbn(out) > data_len + 2 + ((data_len+32766)/32767)*5) { + stbiw__sbn(out) = 2; // truncate to DEFLATE 32K window and FLEVEL = 1 + for (j = 0; j < data_len;) { + int blocklen = data_len - j; + if (blocklen > 32767) blocklen = 32767; + stbiw__sbpush(out, data_len - j == blocklen); // BFINAL = ?, BTYPE = 0 -- no compression + stbiw__sbpush(out, STBIW_UCHAR(blocklen)); // LEN + stbiw__sbpush(out, STBIW_UCHAR(blocklen >> 8)); + stbiw__sbpush(out, STBIW_UCHAR(~blocklen)); // NLEN + stbiw__sbpush(out, STBIW_UCHAR(~blocklen >> 8)); + memcpy(out+stbiw__sbn(out), data+j, blocklen); + stbiw__sbn(out) += blocklen; + j += blocklen; + } + } + + { + // compute adler32 on input + unsigned int s1=1, s2=0; + int blocklen = (int) (data_len % 5552); + j=0; + while (j < data_len) { + for (i=0; i < blocklen; ++i) { s1 += data[j+i]; s2 += s1; } + s1 %= 65521; s2 %= 65521; + j += blocklen; + blocklen = 5552; + } + stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8)); + stbiw__sbpush(out, STBIW_UCHAR(s2)); + stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8)); + stbiw__sbpush(out, STBIW_UCHAR(s1)); + } + *out_len = stbiw__sbn(out); + // make returned pointer freeable + STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len); + return (unsigned char *) stbiw__sbraw(out); +#endif // STBIW_ZLIB_COMPRESS +} + +static unsigned int stbiw__crc32(unsigned char *buffer, int len) +{ +#ifdef STBIW_CRC32 + return STBIW_CRC32(buffer, len); +#else + static unsigned int crc_table[256] = + { + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, + 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, + 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, + 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, + 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, + 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, + 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, + 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, + 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, + 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, + 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, + 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, + 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, + 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, + 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D + }; + + unsigned int crc = ~0u; + int i; + for (i=0; i < len; ++i) + crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)]; + return ~crc; +#endif +} + +#define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4) +#define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v)); +#define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3]) + +static void stbiw__wpcrc(unsigned char **data, int len) +{ + unsigned int crc = stbiw__crc32(*data - len - 4, len+4); + stbiw__wp32(*data, crc); +} + +static unsigned char stbiw__paeth(int a, int b, int c) +{ + int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c); + if (pa <= pb && pa <= pc) return STBIW_UCHAR(a); + if (pb <= pc) return STBIW_UCHAR(b); + return STBIW_UCHAR(c); +} + +// @OPTIMIZE: provide an option that always forces left-predict or paeth predict +static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int width, int height, int y, int n, int filter_type, signed char *line_buffer) +{ + static int mapping[] = { 0,1,2,3,4 }; + static int firstmap[] = { 0,1,0,5,6 }; + int *mymap = (y != 0) ? mapping : firstmap; + int i; + int type = mymap[filter_type]; + unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y); + int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes; + + if (type==0) { + memcpy(line_buffer, z, width*n); + return; + } + + // first loop isn't optimized since it's just one pixel + for (i = 0; i < n; ++i) { + switch (type) { + case 1: line_buffer[i] = z[i]; break; + case 2: line_buffer[i] = z[i] - z[i-signed_stride]; break; + case 3: line_buffer[i] = z[i] - (z[i-signed_stride]>>1); break; + case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-signed_stride],0)); break; + case 5: line_buffer[i] = z[i]; break; + case 6: line_buffer[i] = z[i]; break; + } + } + switch (type) { + case 1: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-n]; break; + case 2: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-signed_stride]; break; + case 3: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - ((z[i-n] + z[i-signed_stride])>>1); break; + case 4: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-signed_stride], z[i-signed_stride-n]); break; + case 5: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - (z[i-n]>>1); break; + case 6: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break; + } +} + +STBIWDEF unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len) +{ + int force_filter = stbi_write_force_png_filter; + int ctype[5] = { -1, 0, 4, 2, 6 }; + unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; + unsigned char *out,*o, *filt, *zlib; + signed char *line_buffer; + int j,zlen; + + if (stride_bytes == 0) + stride_bytes = x * n; + + if (force_filter >= 5) { + force_filter = -1; + } + + filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0; + line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; } + for (j=0; j < y; ++j) { + int filter_type; + if (force_filter > -1) { + filter_type = force_filter; + stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, force_filter, line_buffer); + } else { // Estimate the best filter by running through all of them: + int best_filter = 0, best_filter_val = 0x7fffffff, est, i; + for (filter_type = 0; filter_type < 5; filter_type++) { + stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, filter_type, line_buffer); + + // Estimate the entropy of the line using this filter; the less, the better. + est = 0; + for (i = 0; i < x*n; ++i) { + est += abs((signed char) line_buffer[i]); + } + if (est < best_filter_val) { + best_filter_val = est; + best_filter = filter_type; + } + } + if (filter_type != best_filter) { // If the last iteration already got us the best filter, don't redo it + stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, best_filter, line_buffer); + filter_type = best_filter; + } + } + // when we get here, filter_type contains the filter type, and line_buffer contains the data + filt[j*(x*n+1)] = (unsigned char) filter_type; + STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n); + } + STBIW_FREE(line_buffer); + zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, stbi_write_png_compression_level); + STBIW_FREE(filt); + if (!zlib) return 0; + + // each tag requires 12 bytes of overhead + out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12); + if (!out) return 0; + *out_len = 8 + 12+13 + 12+zlen + 12; + + o=out; + STBIW_MEMMOVE(o,sig,8); o+= 8; + stbiw__wp32(o, 13); // header length + stbiw__wptag(o, "IHDR"); + stbiw__wp32(o, x); + stbiw__wp32(o, y); + *o++ = 8; + *o++ = STBIW_UCHAR(ctype[n]); + *o++ = 0; + *o++ = 0; + *o++ = 0; + stbiw__wpcrc(&o,13); + + stbiw__wp32(o, zlen); + stbiw__wptag(o, "IDAT"); + STBIW_MEMMOVE(o, zlib, zlen); + o += zlen; + STBIW_FREE(zlib); + stbiw__wpcrc(&o, zlen); + + stbiw__wp32(o,0); + stbiw__wptag(o, "IEND"); + stbiw__wpcrc(&o,0); + + STBIW_ASSERT(o == out + *out_len); + + return out; +} + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes) +{ + FILE *f; + int len; + unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); + if (png == NULL) return 0; + + f = stbiw__fopen(filename, "wb"); + if (!f) { STBIW_FREE(png); return 0; } + fwrite(png, 1, len, f); + fclose(f); + STBIW_FREE(png); + return 1; +} +#endif + +STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes) +{ + int len; + unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); + if (png == NULL) return 0; + func(context, png, len); + STBIW_FREE(png); + return 1; +} + + +/* *************************************************************************** + * + * JPEG writer + * + * This is based on Jon Olick's jo_jpeg.cpp: + * public domain Simple, Minimalistic JPEG writer - http://www.jonolick.com/code.html + */ + +static const unsigned char stbiw__jpg_ZigZag[] = { 0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18, + 24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63 }; + +static void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP, int *bitCntP, const unsigned short *bs) { + int bitBuf = *bitBufP, bitCnt = *bitCntP; + bitCnt += bs[1]; + bitBuf |= bs[0] << (24 - bitCnt); + while(bitCnt >= 8) { + unsigned char c = (bitBuf >> 16) & 255; + stbiw__putc(s, c); + if(c == 255) { + stbiw__putc(s, 0); + } + bitBuf <<= 8; + bitCnt -= 8; + } + *bitBufP = bitBuf; + *bitCntP = bitCnt; +} + +static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) { + float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p; + float z1, z2, z3, z4, z5, z11, z13; + + float tmp0 = d0 + d7; + float tmp7 = d0 - d7; + float tmp1 = d1 + d6; + float tmp6 = d1 - d6; + float tmp2 = d2 + d5; + float tmp5 = d2 - d5; + float tmp3 = d3 + d4; + float tmp4 = d3 - d4; + + // Even part + float tmp10 = tmp0 + tmp3; // phase 2 + float tmp13 = tmp0 - tmp3; + float tmp11 = tmp1 + tmp2; + float tmp12 = tmp1 - tmp2; + + d0 = tmp10 + tmp11; // phase 3 + d4 = tmp10 - tmp11; + + z1 = (tmp12 + tmp13) * 0.707106781f; // c4 + d2 = tmp13 + z1; // phase 5 + d6 = tmp13 - z1; + + // Odd part + tmp10 = tmp4 + tmp5; // phase 2 + tmp11 = tmp5 + tmp6; + tmp12 = tmp6 + tmp7; + + // The rotator is modified from fig 4-8 to avoid extra negations. + z5 = (tmp10 - tmp12) * 0.382683433f; // c6 + z2 = tmp10 * 0.541196100f + z5; // c2-c6 + z4 = tmp12 * 1.306562965f + z5; // c2+c6 + z3 = tmp11 * 0.707106781f; // c4 + + z11 = tmp7 + z3; // phase 5 + z13 = tmp7 - z3; + + *d5p = z13 + z2; // phase 6 + *d3p = z13 - z2; + *d1p = z11 + z4; + *d7p = z11 - z4; + + *d0p = d0; *d2p = d2; *d4p = d4; *d6p = d6; +} + +static void stbiw__jpg_calcBits(int val, unsigned short bits[2]) { + int tmp1 = val < 0 ? -val : val; + val = val < 0 ? val-1 : val; + bits[1] = 1; + while(tmp1 >>= 1) { + ++bits[1]; + } + bits[0] = val & ((1<0)&&(DU[end0pos]==0); --end0pos) { + } + // end0pos = first element in reverse order !=0 + if(end0pos == 0) { + stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); + return DU[0]; + } + for(i = 1; i <= end0pos; ++i) { + int startpos = i; + int nrzeroes; + unsigned short bits[2]; + for (; DU[i]==0 && i<=end0pos; ++i) { + } + nrzeroes = i-startpos; + if ( nrzeroes >= 16 ) { + int lng = nrzeroes>>4; + int nrmarker; + for (nrmarker=1; nrmarker <= lng; ++nrmarker) + stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes); + nrzeroes &= 15; + } + stbiw__jpg_calcBits(DU[i], bits); + stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes<<4)+bits[1]]); + stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); + } + if(end0pos != 63) { + stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); + } + return DU[0]; +} + +static int stbi_write_jpg_core(stbi__write_context *s, int width, int height, int comp, const void* data, int quality) { + // Constants that don't pollute global namespace + static const unsigned char std_dc_luminance_nrcodes[] = {0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0}; + static const unsigned char std_dc_luminance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; + static const unsigned char std_ac_luminance_nrcodes[] = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d}; + static const unsigned char std_ac_luminance_values[] = { + 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, + 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, + 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, + 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, + 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, + 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, + 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa + }; + static const unsigned char std_dc_chrominance_nrcodes[] = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0}; + static const unsigned char std_dc_chrominance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; + static const unsigned char std_ac_chrominance_nrcodes[] = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77}; + static const unsigned char std_ac_chrominance_values[] = { + 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, + 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, + 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, + 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, + 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, + 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, + 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa + }; + // Huffman tables + static const unsigned short YDC_HT[256][2] = { {0,2},{2,3},{3,3},{4,3},{5,3},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9}}; + static const unsigned short UVDC_HT[256][2] = { {0,2},{1,2},{2,2},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9},{1022,10},{2046,11}}; + static const unsigned short YAC_HT[256][2] = { + {10,4},{0,2},{1,2},{4,3},{11,4},{26,5},{120,7},{248,8},{1014,10},{65410,16},{65411,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {12,4},{27,5},{121,7},{502,9},{2038,11},{65412,16},{65413,16},{65414,16},{65415,16},{65416,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {28,5},{249,8},{1015,10},{4084,12},{65417,16},{65418,16},{65419,16},{65420,16},{65421,16},{65422,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {58,6},{503,9},{4085,12},{65423,16},{65424,16},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {59,6},{1016,10},{65430,16},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {122,7},{2039,11},{65438,16},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {123,7},{4086,12},{65446,16},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {250,8},{4087,12},{65454,16},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {504,9},{32704,15},{65462,16},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {505,9},{65470,16},{65471,16},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {506,9},{65479,16},{65480,16},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {1017,10},{65488,16},{65489,16},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {1018,10},{65497,16},{65498,16},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {2040,11},{65506,16},{65507,16},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {65515,16},{65516,16},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{0,0},{0,0},{0,0},{0,0},{0,0}, + {2041,11},{65525,16},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} + }; + static const unsigned short UVAC_HT[256][2] = { + {0,2},{1,2},{4,3},{10,4},{24,5},{25,5},{56,6},{120,7},{500,9},{1014,10},{4084,12},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {11,4},{57,6},{246,8},{501,9},{2038,11},{4085,12},{65416,16},{65417,16},{65418,16},{65419,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {26,5},{247,8},{1015,10},{4086,12},{32706,15},{65420,16},{65421,16},{65422,16},{65423,16},{65424,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {27,5},{248,8},{1016,10},{4087,12},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{65430,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {58,6},{502,9},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{65438,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {59,6},{1017,10},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{65446,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {121,7},{2039,11},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{65454,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {122,7},{2040,11},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{65462,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {249,8},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{65470,16},{65471,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {503,9},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{65479,16},{65480,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {504,9},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{65488,16},{65489,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {505,9},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{65497,16},{65498,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {506,9},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{65506,16},{65507,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {2041,11},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{65515,16},{65516,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, + {16352,14},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{65525,16},{0,0},{0,0},{0,0},{0,0},{0,0}, + {1018,10},{32707,15},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} + }; + static const int YQT[] = {16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22, + 37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99}; + static const int UVQT[] = {17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99, + 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99}; + static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f, + 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f }; + + int row, col, i, k, subsample; + float fdtbl_Y[64], fdtbl_UV[64]; + unsigned char YTable[64], UVTable[64]; + + if(!data || !width || !height || comp > 4 || comp < 1) { + return 0; + } + + quality = quality ? quality : 90; + subsample = quality <= 90 ? 1 : 0; + quality = quality < 1 ? 1 : quality > 100 ? 100 : quality; + quality = quality < 50 ? 5000 / quality : 200 - quality * 2; + + for(i = 0; i < 64; ++i) { + int uvti, yti = (YQT[i]*quality+50)/100; + YTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (yti < 1 ? 1 : yti > 255 ? 255 : yti); + uvti = (UVQT[i]*quality+50)/100; + UVTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (uvti < 1 ? 1 : uvti > 255 ? 255 : uvti); + } + + for(row = 0, k = 0; row < 8; ++row) { + for(col = 0; col < 8; ++col, ++k) { + fdtbl_Y[k] = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); + fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); + } + } + + // Write Headers + { + static const unsigned char head0[] = { 0xFF,0xD8,0xFF,0xE0,0,0x10,'J','F','I','F',0,1,1,0,0,1,0,1,0,0,0xFF,0xDB,0,0x84,0 }; + static const unsigned char head2[] = { 0xFF,0xDA,0,0xC,3,1,0,2,0x11,3,0x11,0,0x3F,0 }; + const unsigned char head1[] = { 0xFF,0xC0,0,0x11,8,(unsigned char)(height>>8),STBIW_UCHAR(height),(unsigned char)(width>>8),STBIW_UCHAR(width), + 3,1,(unsigned char)(subsample?0x22:0x11),0,2,0x11,1,3,0x11,1,0xFF,0xC4,0x01,0xA2,0 }; + s->func(s->context, (void*)head0, sizeof(head0)); + s->func(s->context, (void*)YTable, sizeof(YTable)); + stbiw__putc(s, 1); + s->func(s->context, UVTable, sizeof(UVTable)); + s->func(s->context, (void*)head1, sizeof(head1)); + s->func(s->context, (void*)(std_dc_luminance_nrcodes+1), sizeof(std_dc_luminance_nrcodes)-1); + s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values)); + stbiw__putc(s, 0x10); // HTYACinfo + s->func(s->context, (void*)(std_ac_luminance_nrcodes+1), sizeof(std_ac_luminance_nrcodes)-1); + s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values)); + stbiw__putc(s, 1); // HTUDCinfo + s->func(s->context, (void*)(std_dc_chrominance_nrcodes+1), sizeof(std_dc_chrominance_nrcodes)-1); + s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values)); + stbiw__putc(s, 0x11); // HTUACinfo + s->func(s->context, (void*)(std_ac_chrominance_nrcodes+1), sizeof(std_ac_chrominance_nrcodes)-1); + s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values)); + s->func(s->context, (void*)head2, sizeof(head2)); + } + + // Encode 8x8 macroblocks + { + static const unsigned short fillBits[] = {0x7F, 7}; + int DCY=0, DCU=0, DCV=0; + int bitBuf=0, bitCnt=0; + // comp == 2 is grey+alpha (alpha is ignored) + int ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0; + const unsigned char *dataR = (const unsigned char *)data; + const unsigned char *dataG = dataR + ofsG; + const unsigned char *dataB = dataR + ofsB; + int x, y, pos; + if(subsample) { + for(y = 0; y < height; y += 16) { + for(x = 0; x < width; x += 16) { + float Y[256], U[256], V[256]; + for(row = y, pos = 0; row < y+16; ++row) { + // row >= height => use last input row + int clamped_row = (row < height) ? row : height - 1; + int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; + for(col = x; col < x+16; ++col, ++pos) { + // if col >= width => use pixel from last input column + int p = base_p + ((col < width) ? col : (width-1))*comp; + float r = dataR[p], g = dataG[p], b = dataB[p]; + Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; + U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; + V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; + } + } + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+0, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+8, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+128, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+136, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); + + // subsample U,V + { + float subU[64], subV[64]; + int yy, xx; + for(yy = 0, pos = 0; yy < 8; ++yy) { + for(xx = 0; xx < 8; ++xx, ++pos) { + int j = yy*32+xx*2; + subU[pos] = (U[j+0] + U[j+1] + U[j+16] + U[j+17]) * 0.25f; + subV[pos] = (V[j+0] + V[j+1] + V[j+16] + V[j+17]) * 0.25f; + } + } + DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subU, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); + DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subV, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); + } + } + } + } else { + for(y = 0; y < height; y += 8) { + for(x = 0; x < width; x += 8) { + float Y[64], U[64], V[64]; + for(row = y, pos = 0; row < y+8; ++row) { + // row >= height => use last input row + int clamped_row = (row < height) ? row : height - 1; + int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; + for(col = x; col < x+8; ++col, ++pos) { + // if col >= width => use pixel from last input column + int p = base_p + ((col < width) ? col : (width-1))*comp; + float r = dataR[p], g = dataG[p], b = dataB[p]; + Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; + U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; + V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; + } + } + + DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y, 8, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, U, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); + DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, V, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); + } + } + } + + // Do the bit alignment of the EOI marker + stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits); + } + + // EOI + stbiw__putc(s, 0xFF); + stbiw__putc(s, 0xD9); + + return 1; +} + +STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality) +{ + stbi__write_context s = { 0 }; + stbi__start_write_callbacks(&s, func, context); + return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality); +} + + +#ifndef STBI_WRITE_NO_STDIO +STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality) +{ + stbi__write_context s = { 0 }; + if (stbi__start_write_file(&s,filename)) { + int r = stbi_write_jpg_core(&s, x, y, comp, data, quality); + stbi__end_write_file(&s); + return r; + } else + return 0; +} +#endif + +#endif // STB_IMAGE_WRITE_IMPLEMENTATION + +/* Revision history + 1.16 (2021-07-11) + make Deflate code emit uncompressed blocks when it would otherwise expand + support writing BMPs with alpha channel + 1.15 (2020-07-13) unknown + 1.14 (2020-02-02) updated JPEG writer to downsample chroma channels + 1.13 + 1.12 + 1.11 (2019-08-11) + + 1.10 (2019-02-07) + support utf8 filenames in Windows; fix warnings and platform ifdefs + 1.09 (2018-02-11) + fix typo in zlib quality API, improve STB_I_W_STATIC in C++ + 1.08 (2018-01-29) + add stbi__flip_vertically_on_write, external zlib, zlib quality, choose PNG filter + 1.07 (2017-07-24) + doc fix + 1.06 (2017-07-23) + writing JPEG (using Jon Olick's code) + 1.05 ??? + 1.04 (2017-03-03) + monochrome BMP expansion + 1.03 ??? + 1.02 (2016-04-02) + avoid allocating large structures on the stack + 1.01 (2016-01-16) + STBIW_REALLOC_SIZED: support allocators with no realloc support + avoid race-condition in crc initialization + minor compile issues + 1.00 (2015-09-14) + installable file IO function + 0.99 (2015-09-13) + warning fixes; TGA rle support + 0.98 (2015-04-08) + added STBIW_MALLOC, STBIW_ASSERT etc + 0.97 (2015-01-18) + fixed HDR asserts, rewrote HDR rle logic + 0.96 (2015-01-17) + add HDR output + fix monochrome BMP + 0.95 (2014-08-17) + add monochrome TGA output + 0.94 (2014-05-31) + rename private functions to avoid conflicts with stb_image.h + 0.93 (2014-05-27) + warning fixes + 0.92 (2010-08-01) + casts to unsigned char to fix warnings + 0.91 (2010-07-17) + first public release + 0.90 first internal release +*/ + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/native/monogame/external/sdl2 b/native/monogame/external/sdl2 new file mode 160000 index 00000000000..2eefe1b7ed2 --- /dev/null +++ b/native/monogame/external/sdl2 @@ -0,0 +1 @@ +Subproject commit 2eefe1b7ed2989ceef6a10d48d0f656f10ee5efa diff --git a/native/monogame/external/vma b/native/monogame/external/vma new file mode 160000 index 00000000000..0e89587db3e --- /dev/null +++ b/native/monogame/external/vma @@ -0,0 +1 @@ +Subproject commit 0e89587db3ebee4d463f191bd296374c5fafc8ea diff --git a/native/monogame/external/volk b/native/monogame/external/volk new file mode 160000 index 00000000000..3a8068a5741 --- /dev/null +++ b/native/monogame/external/volk @@ -0,0 +1 @@ +Subproject commit 3a8068a57417940cf2bf9d837a7bb60d015ca2f1 diff --git a/native/monogame/external/vulkan-headers b/native/monogame/external/vulkan-headers new file mode 160000 index 00000000000..eaa319dade9 --- /dev/null +++ b/native/monogame/external/vulkan-headers @@ -0,0 +1 @@ +Subproject commit eaa319dade959cb61ed2229c8ea42e307cc8f8b3 diff --git a/native/monogame/faudio/MGA_faudio.cpp b/native/monogame/faudio/MGA_faudio.cpp new file mode 100644 index 00000000000..00d3783a58f --- /dev/null +++ b/native/monogame/faudio/MGA_faudio.cpp @@ -0,0 +1,204 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +#include "api_MGA.h" + +#include "mg_common.h" + + +// TODO: Implement against the C++ API for FAudio. + +struct MGA_System +{ +}; + +struct MGA_Buffer +{ +}; + +struct MGA_Voice +{ +}; + + +MGA_System* MGA_System_Create() +{ + auto system = new MGA_System(); + return system; +} + +void MGA_System_Destroy(MGA_System* system) +{ + assert(system != nullptr); + + // TODO: We're assuming here the C# side is cleaning up + // buffers/voices, but if we want this to be a good C++ + // API as well, we likely should cleanup ourselves too. + + delete system; +} + +mgint MGA_System_GetMaxInstances() +{ + return INT_MAX; +} + +void MGA_System_SetReverbSettings(MGA_System* system, ReverbSettings& settings) +{ + assert(system != nullptr); +} + +MGA_Buffer* MGA_Buffer_Create(MGA_System* system) +{ + assert(system != nullptr); + auto buffer = new MGA_Buffer(); + return buffer; +} + +void MGA_Buffer_Destroy(MGA_Buffer* buffer) +{ + assert(buffer != nullptr); + delete buffer; +} + +void MGA_Buffer_InitializeFormat(MGA_Buffer* buffer, mgbyte* waveHeader, mgbyte* waveData, mgint length, mgint loopStart, mgint loopLength) +{ + assert(buffer != nullptr); + assert(waveHeader != nullptr); + assert(waveData != nullptr); + assert(length > 0); +} + +void MGA_Buffer_InitializePCM(MGA_Buffer* buffer, mgbyte* waveData, mgint offset, mgint length, mgint sampleBits, mgint sampleRate, mgint channels, mgint loopStart, mgint loopLength) +{ + assert(buffer != nullptr); + assert(waveData != nullptr); + assert(offset >=0); + assert(length > 0); +} + +void MGA_Buffer_InitializeXact(MGA_Buffer* buffer, mguint codec, mgbyte* waveData, mgint length, mgint sampleRate, mgint blockAlignment, mgint channels, mgint loopStart, mgint loopLength) +{ + assert(buffer != nullptr); + assert(waveData != nullptr); + assert(length > 0); +} + +mgulong MGA_Buffer_GetDuration(MGA_Buffer* buffer) +{ + assert(buffer != nullptr); + return 0; +} + +MGA_Voice* MGA_Voice_Create(MGA_System* system) +{ + assert(system != nullptr); + auto voice = new MGA_Voice(); + return voice; +} + +void MGA_Voice_Destroy(MGA_Voice* voice) +{ + assert(voice != nullptr); + delete voice; +} + +mgint MGA_Voice_GetBufferCount(MGA_Voice* voice) +{ + assert(voice != nullptr); + return 0; +} + +void MGA_Voice_SetBuffer(MGA_Voice* voice, MGA_Buffer* buffer) +{ + assert(voice != nullptr); + + // Stop and remove any pending buffers first. + + // Append a buffer if we got one. + if (buffer) + { + + } +} + +void MGA_Voice_AppendBuffer(MGA_Voice* voice, mgbyte* buffer, mgint offset, mgint count, mgbool clear) +{ + assert(voice != nullptr); + assert(buffer != nullptr); + + if (clear) + { + // Stop and remove any pending buffers first. + } + + // The idea here is that for streaming cases and dynamic buffers + // we internally allocate a big chunk of memory for it and + // break it up into smaller buffers for submission. + + // Allocate a dynamic buffer that can be reused later. + // Append the buffer. +} + +void MGA_Voice_Play(MGA_Voice* voice, mgbool looped) +{ + assert(voice != nullptr); +} + +void MGA_Voice_Pause(MGA_Voice* voice) +{ + assert(voice != nullptr); +} + +void MGA_Voice_Resume(MGA_Voice* voice) +{ + assert(voice != nullptr); +} + +void MGA_Voice_Stop(MGA_Voice* voice, mgbool immediate) +{ + assert(voice != nullptr); +} + +MGSoundState MGA_Voice_GetState(MGA_Voice* voice) +{ + assert(voice != nullptr); + return MGSoundState::Stopped; +} + +void MGA_Voice_SetPan(MGA_Voice* voice, mgfloat pan) +{ + assert(voice != nullptr); +} + +void MGA_Voice_SetPitch(MGA_Voice* voice, mgfloat pitch) +{ + assert(voice != nullptr); +} + +void MGA_Voice_SetVolume(MGA_Voice* voice, mgfloat volume) +{ + assert(voice != nullptr); +} + +void MGA_Voice_SetReverbMix(MGA_Voice* voice, mgfloat mix) +{ + assert(voice != nullptr); +} + +void MGA_Voice_SetFilterMode(MGA_Voice* voice, MGFilterMode mode, mgfloat filterQ, mgfloat frequency) +{ + assert(voice != nullptr); +} + +void MGA_Voice_ClearFilterMode(MGA_Voice* voice) +{ + assert(voice != nullptr); +} + +void MGA_Voice_Apply3D(MGA_Voice* voice, Listener& listener, Emitter& emitter, mgfloat distanceScale) +{ + assert(voice != nullptr); +} + diff --git a/native/monogame/include/api_MGA.h b/native/monogame/include/api_MGA.h new file mode 100644 index 00000000000..3870c4573b7 --- /dev/null +++ b/native/monogame/include/api_MGA.h @@ -0,0 +1,45 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +// This code is auto generated, don't modify it by hand. +// To regenerate it run: Tools/MonoGame.Generator.CTypes + +#pragma once + +#include "api_common.h" +#include "api_enums.h" +#include "api_structs.h" + + +struct MGA_System; +struct MGA_Buffer; +struct MGA_Voice; + +MG_EXPORT MGA_System* MGA_System_Create(); +MG_EXPORT void MGA_System_Destroy(MGA_System* system); +MG_EXPORT mgint MGA_System_GetMaxInstances(); +MG_EXPORT void MGA_System_SetReverbSettings(MGA_System* system, ReverbSettings& settings); +MG_EXPORT MGA_Buffer* MGA_Buffer_Create(MGA_System* system); +MG_EXPORT void MGA_Buffer_Destroy(MGA_Buffer* buffer); +MG_EXPORT void MGA_Buffer_InitializeFormat(MGA_Buffer* buffer, mgbyte* waveHeader, mgbyte* waveData, mgint length, mgint loopStart, mgint loopLength); +MG_EXPORT void MGA_Buffer_InitializePCM(MGA_Buffer* buffer, mgbyte* waveData, mgint offset, mgint length, mgint sampleBits, mgint sampleRate, mgint channels, mgint loopStart, mgint loopLength); +MG_EXPORT void MGA_Buffer_InitializeXact(MGA_Buffer* buffer, mguint codec, mgbyte* waveData, mgint length, mgint sampleRate, mgint blockAlignment, mgint channels, mgint loopStart, mgint loopLength); +MG_EXPORT mgulong MGA_Buffer_GetDuration(MGA_Buffer* buffer); +MG_EXPORT MGA_Voice* MGA_Voice_Create(MGA_System* system); +MG_EXPORT void MGA_Voice_Destroy(MGA_Voice* voice); +MG_EXPORT mgint MGA_Voice_GetBufferCount(MGA_Voice* voice); +MG_EXPORT void MGA_Voice_SetBuffer(MGA_Voice* voice, MGA_Buffer* buffer); +MG_EXPORT void MGA_Voice_AppendBuffer(MGA_Voice* voice, mgbyte* buffer, mgint offset, mgint count, mgbool clear); +MG_EXPORT void MGA_Voice_Play(MGA_Voice* voice, mgbool looped); +MG_EXPORT void MGA_Voice_Pause(MGA_Voice* voice); +MG_EXPORT void MGA_Voice_Resume(MGA_Voice* voice); +MG_EXPORT void MGA_Voice_Stop(MGA_Voice* voice, mgbool immediate); +MG_EXPORT MGSoundState MGA_Voice_GetState(MGA_Voice* voice); +MG_EXPORT void MGA_Voice_SetPan(MGA_Voice* voice, mgfloat pan); +MG_EXPORT void MGA_Voice_SetPitch(MGA_Voice* voice, mgfloat pitch); +MG_EXPORT void MGA_Voice_SetVolume(MGA_Voice* voice, mgfloat volume); +MG_EXPORT void MGA_Voice_SetReverbMix(MGA_Voice* voice, mgfloat mix); +MG_EXPORT void MGA_Voice_SetFilterMode(MGA_Voice* voice, MGFilterMode mode, mgfloat filterQ, mgfloat frequency); +MG_EXPORT void MGA_Voice_ClearFilterMode(MGA_Voice* voice); +MG_EXPORT void MGA_Voice_Apply3D(MGA_Voice* voice, Listener& listener, Emitter& emitter, mgfloat distanceScale); diff --git a/native/monogame/include/api_MGG.h b/native/monogame/include/api_MGG.h new file mode 100644 index 00000000000..63c809b7922 --- /dev/null +++ b/native/monogame/include/api_MGG.h @@ -0,0 +1,82 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +// This code is auto generated, don't modify it by hand. +// To regenerate it run: Tools/MonoGame.Generator.CTypes + +#pragma once + +#include "api_common.h" +#include "api_enums.h" +#include "api_structs.h" + + +struct MGG_GraphicsSystem; +struct MGG_GraphicsAdapter; +struct MGG_GraphicsDevice; +struct MGG_BlendState; +struct MGG_DepthStencilState; +struct MGG_RasterizerState; +struct MGG_Buffer; +struct MGG_Texture; +struct MGG_SamplerState; +struct MGG_Shader; +struct MGG_InputLayout; +struct MGG_OcclusionQuery; + +MG_EXPORT void MGG_EffectResource_GetBytecode(const char* name, mgbyte*& bytecode, mgint& size); +MG_EXPORT MGG_GraphicsSystem* MGG_GraphicsSystem_Create(); +MG_EXPORT void MGG_GraphicsSystem_Destroy(MGG_GraphicsSystem* system); +MG_EXPORT MGG_GraphicsAdapter* MGG_GraphicsAdapter_Get(MGG_GraphicsSystem* system, mgint index); +MG_EXPORT void MGG_GraphicsAdapter_GetInfo(MGG_GraphicsAdapter* adapter, MGG_GraphicsAdaptor_Info& info); +MG_EXPORT MGG_GraphicsDevice* MGG_GraphicsDevice_Create(MGG_GraphicsSystem* system, MGG_GraphicsAdapter* adapter); +MG_EXPORT void MGG_GraphicsDevice_Destroy(MGG_GraphicsDevice* device); +MG_EXPORT void MGG_GraphicsDevice_GetCaps(MGG_GraphicsDevice* device, MGG_GraphicsDevice_Caps& caps); +MG_EXPORT void MGG_GraphicsDevice_ResizeSwapchain(MGG_GraphicsDevice* device, void* nativeWindowHandle, mgint width, mgint height, MGSurfaceFormat color, MGDepthFormat depth); +MG_EXPORT mgint MGG_GraphicsDevice_BeginFrame(MGG_GraphicsDevice* device); +MG_EXPORT void MGG_GraphicsDevice_Clear(MGG_GraphicsDevice* device, MGClearOptions options, Vector4& color, mgfloat depth, mgint stencil); +MG_EXPORT void MGG_GraphicsDevice_Present(MGG_GraphicsDevice* device, mgint currentFrame, mgint syncInterval); +MG_EXPORT void MGG_GraphicsDevice_SetBlendState(MGG_GraphicsDevice* device, MGG_BlendState* state, mgfloat factorR, mgfloat factorG, mgfloat factorB, mgfloat factorA); +MG_EXPORT void MGG_GraphicsDevice_SetDepthStencilState(MGG_GraphicsDevice* device, MGG_DepthStencilState* state); +MG_EXPORT void MGG_GraphicsDevice_SetRasterizerState(MGG_GraphicsDevice* device, MGG_RasterizerState* state); +MG_EXPORT void MGG_GraphicsDevice_GetTitleSafeArea(mgint& x, mgint& y, mgint& width, mgint& height); +MG_EXPORT void MGG_GraphicsDevice_SetViewport(MGG_GraphicsDevice* device, mgint x, mgint y, mgint width, mgint height, mgfloat minDepth, mgfloat maxDepth); +MG_EXPORT void MGG_GraphicsDevice_SetScissorRectangle(MGG_GraphicsDevice* device, mgint x, mgint y, mgint width, mgint height); +MG_EXPORT void MGG_GraphicsDevice_SetRenderTargets(MGG_GraphicsDevice* device, MGG_Texture** targets, mgint count); +MG_EXPORT void MGG_GraphicsDevice_SetConstantBuffer(MGG_GraphicsDevice* device, MGShaderStage stage, mgint slot, MGG_Buffer* buffer); +MG_EXPORT void MGG_GraphicsDevice_SetTexture(MGG_GraphicsDevice* device, MGShaderStage stage, mgint slot, MGG_Texture* texture); +MG_EXPORT void MGG_GraphicsDevice_SetSamplerState(MGG_GraphicsDevice* device, MGShaderStage stage, mgint slot, MGG_SamplerState* state); +MG_EXPORT void MGG_GraphicsDevice_SetIndexBuffer(MGG_GraphicsDevice* device, MGIndexElementSize size, MGG_Buffer* buffer); +MG_EXPORT void MGG_GraphicsDevice_SetVertexBuffer(MGG_GraphicsDevice* device, mgint slot, MGG_Buffer* buffer, mgint vertexOffset); +MG_EXPORT void MGG_GraphicsDevice_SetShader(MGG_GraphicsDevice* device, MGShaderStage stage, MGG_Shader* shader); +MG_EXPORT void MGG_GraphicsDevice_SetInputLayout(MGG_GraphicsDevice* device, MGG_InputLayout* layout); +MG_EXPORT void MGG_GraphicsDevice_Draw(MGG_GraphicsDevice* device, MGPrimitiveType primitiveType, mgint vertexStart, mgint vertexCount); +MG_EXPORT void MGG_GraphicsDevice_DrawIndexed(MGG_GraphicsDevice* device, MGPrimitiveType primitiveType, mgint primitiveCount, mgint indexStart, mgint vertexStart); +MG_EXPORT void MGG_GraphicsDevice_DrawIndexedInstanced(MGG_GraphicsDevice* device, MGPrimitiveType primitiveType, mgint primitiveCount, mgint indexStart, mgint vertexStart, mgint instanceCount); +MG_EXPORT MGG_BlendState* MGG_BlendState_Create(MGG_GraphicsDevice* device, MGG_BlendState_Info* infos); +MG_EXPORT void MGG_BlendState_Destroy(MGG_GraphicsDevice* device, MGG_BlendState* state); +MG_EXPORT MGG_DepthStencilState* MGG_DepthStencilState_Create(MGG_GraphicsDevice* device, MGG_DepthStencilState_Info* info); +MG_EXPORT void MGG_DepthStencilState_Destroy(MGG_GraphicsDevice* device, MGG_DepthStencilState* state); +MG_EXPORT MGG_RasterizerState* MGG_RasterizerState_Create(MGG_GraphicsDevice* device, MGG_RasterizerState_Info* info); +MG_EXPORT void MGG_RasterizerState_Destroy(MGG_GraphicsDevice* device, MGG_RasterizerState* state); +MG_EXPORT MGG_SamplerState* MGG_SamplerState_Create(MGG_GraphicsDevice* device, MGG_SamplerState_Info* info); +MG_EXPORT void MGG_SamplerState_Destroy(MGG_GraphicsDevice* device, MGG_SamplerState* state); +MG_EXPORT MGG_Buffer* MGG_Buffer_Create(MGG_GraphicsDevice* device, MGBufferType type, mgint sizeInBytes); +MG_EXPORT void MGG_Buffer_Destroy(MGG_GraphicsDevice* device, MGG_Buffer* buffer); +MG_EXPORT void MGG_Buffer_SetData(MGG_GraphicsDevice* device, MGG_Buffer*& buffer, mgint offset, mgbyte* data, mgint length, mgbool discard); +MG_EXPORT void MGG_Buffer_GetData(MGG_GraphicsDevice* device, MGG_Buffer* buffer, mgint offset, mgbyte* data, mgint dataCount, mgint dataBytes, mgint dataStride); +MG_EXPORT MGG_Texture* MGG_Texture_Create(MGG_GraphicsDevice* device, MGTextureType type, MGSurfaceFormat format, mgint width, mgint height, mgint depth, mgint mipmaps, mgint slices); +MG_EXPORT MGG_Texture* MGG_RenderTarget_Create(MGG_GraphicsDevice* device, MGTextureType type, MGSurfaceFormat format, mgint width, mgint height, mgint depth, mgint mipmaps, mgint slices, MGDepthFormat depthFormat, mgint multiSampleCount, MGRenderTargetUsage usage); +MG_EXPORT void MGG_Texture_Destroy(MGG_GraphicsDevice* device, MGG_Texture* texture); +MG_EXPORT void MGG_Texture_SetData(MGG_GraphicsDevice* device, MGG_Texture* texture, mgint level, mgint slice, mgint x, mgint y, mgint z, mgint width, mgint height, mgint depth, mgbyte* data, mgint dataBytes); +MG_EXPORT void MGG_Texture_GetData(MGG_GraphicsDevice* device, MGG_Texture* texture, mgint level, mgint slice, mgint x, mgint y, mgint z, mgint width, mgint height, mgint depth, mgbyte* data, mgint dataBytes); +MG_EXPORT MGG_InputLayout* MGG_InputLayout_Create(MGG_GraphicsDevice* device, mgint* strides, mgint streamCount, MGG_InputElement* elements, mgint elementCount); +MG_EXPORT void MGG_InputLayout_Destroy(MGG_GraphicsDevice* device, MGG_InputLayout* layout); +MG_EXPORT MGG_Shader* MGG_Shader_Create(MGG_GraphicsDevice* device, MGShaderStage stage, mgbyte* bytecode, mgint sizeInBytes); +MG_EXPORT void MGG_Shader_Destroy(MGG_GraphicsDevice* device, MGG_Shader* shader); +MG_EXPORT MGG_OcclusionQuery* MGG_OcclusionQuery_Create(MGG_GraphicsDevice* device); +MG_EXPORT void MGG_OcclusionQuery_Destroy(MGG_GraphicsDevice* device, MGG_OcclusionQuery* query); +MG_EXPORT void MGG_OcclusionQuery_Begin(MGG_GraphicsDevice* device, MGG_OcclusionQuery* query); +MG_EXPORT void MGG_OcclusionQuery_End(MGG_GraphicsDevice* device, MGG_OcclusionQuery* query); +MG_EXPORT mgbool MGG_OcclusionQuery_GetResult(MGG_GraphicsDevice* device, MGG_OcclusionQuery* query, mgint& pixelCount); diff --git a/native/monogame/include/api_MGI.h b/native/monogame/include/api_MGI.h new file mode 100644 index 00000000000..e95613b19f0 --- /dev/null +++ b/native/monogame/include/api_MGI.h @@ -0,0 +1,18 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +// This code is auto generated, don't modify it by hand. +// To regenerate it run: Tools/MonoGame.Generator.CTypes + +#pragma once + +#include "api_common.h" +#include "api_enums.h" +#include "api_structs.h" + + + +MG_EXPORT void MGI_ReadRGBA(mgbyte* data, mgint dataBytes, mgbool zeroTransparentPixels, mgint& width, mgint& height, mgbyte*& rgba); +MG_EXPORT void MGI_WriteJpg(mgbyte* data, mgint dataBytes, mgint width, mgint height, mgint quality, mgbyte*& jpg, mgint& jpgBytes); +MG_EXPORT void MGI_WritePng(mgbyte* data, mgint dataBytes, mgint width, mgint height, mgbyte*& png, mgint& pngBytes); diff --git a/native/monogame/include/api_MGM.h b/native/monogame/include/api_MGM.h new file mode 100644 index 00000000000..a35b6c294b2 --- /dev/null +++ b/native/monogame/include/api_MGM.h @@ -0,0 +1,38 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +// This code is auto generated, don't modify it by hand. +// To regenerate it run: Tools/MonoGame.Generator.CTypes + +#pragma once + +#include "api_common.h" +#include "api_enums.h" +#include "api_structs.h" + + +struct MGM_Song; +struct MGM_Video; + +MG_EXPORT MGM_Song* MGM_Song_Create(const char* mediaFilePath); +MG_EXPORT void MGM_Song_Destroy(MGM_Song* song); +MG_EXPORT mgulong MGM_Song_GetDuration(MGM_Song* song); +MG_EXPORT mgulong MGM_Song_GetPosition(MGM_Song* song); +MG_EXPORT mgfloat MGM_Song_GetVolume(MGM_Song* song); +MG_EXPORT void MGM_Song_SetVolume(MGM_Song* song, mgfloat volume); +MG_EXPORT void MGM_Song_Play(MGM_Song* song, mgulong startPositionMs, void (*callback)(void*), void* callbackData); +MG_EXPORT void MGM_Song_Pause(MGM_Song* song); +MG_EXPORT void MGM_Song_Resume(MGM_Song* song); +MG_EXPORT void MGM_Song_Stop(MGM_Song* song); +MG_EXPORT MGM_Video* MGM_Video_Create(const char* mediaFilePath, mgint cachedFrameNum, mgint& width, mgint& height, mgfloat& fps, mgulong& duration); +MG_EXPORT void MGM_Video_Destroy(MGM_Video* video); +MG_EXPORT MGMediaState MGM_Video_GetState(MGM_Video* video); +MG_EXPORT mgulong MGM_Video_GetPosition(MGM_Video* video); +MG_EXPORT void MGM_Video_SetVolume(MGM_Video* video, mgfloat volume); +MG_EXPORT void MGM_Video_SetLooped(MGM_Video* video, mgbool looped); +MG_EXPORT void MGM_Video_Play(MGM_Video* video); +MG_EXPORT void MGM_Video_Pause(MGM_Video* video); +MG_EXPORT void MGM_Video_Resume(MGM_Video* video); +MG_EXPORT void MGM_Video_Stop(MGM_Video* video); +MG_EXPORT void MGM_Video_GetFrame(MGM_Video* video, mguint& frame, MGG_Texture*& handle); diff --git a/native/monogame/include/api_MGP.h b/native/monogame/include/api_MGP.h new file mode 100644 index 00000000000..712ca7354ed --- /dev/null +++ b/native/monogame/include/api_MGP.h @@ -0,0 +1,52 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +// This code is auto generated, don't modify it by hand. +// To regenerate it run: Tools/MonoGame.Generator.CTypes + +#pragma once + +#include "api_common.h" +#include "api_enums.h" +#include "api_structs.h" + + +struct MGP_Platform; +struct MGP_Window; +struct MGP_Cursor; + +MG_EXPORT MGP_Platform* MGP_Platform_Create(MGGameRunBehavior& behavior); +MG_EXPORT void MGP_Platform_Destroy(MGP_Platform* platform); +MG_EXPORT void MGP_Platform_BeforeInitialize(MGP_Platform* platform); +MG_EXPORT mgbool MGP_Platform_PollEvent(MGP_Platform* platform, MGP_Event& event_); +MG_EXPORT void MGP_Platform_StartRunLoop(MGP_Platform* platform); +MG_EXPORT mgbool MGP_Platform_BeforeRun(MGP_Platform* platform); +MG_EXPORT mgbool MGP_Platform_BeforeUpdate(MGP_Platform* platform); +MG_EXPORT mgbool MGP_Platform_BeforeDraw(MGP_Platform* platform); +MG_EXPORT const char* MGP_Platform_MakePath(const char* location, const char* path); +MG_EXPORT MGMonoGamePlatform MGP_Platform_GetPlatform(); +MG_EXPORT MGGraphicsBackend MGP_Platform_GetGraphicsBackend(); +MG_EXPORT MGP_Window* MGP_Window_Create(MGP_Platform* platform, mgint width, mgint height, const char* title); +MG_EXPORT void MGP_Window_Destroy(MGP_Window* window); +MG_EXPORT void MGP_Window_SetIconBitmap(MGP_Window* window, mgbyte* icon, mgint length); +MG_EXPORT void* MGP_Window_GetNativeHandle(MGP_Window* window); +MG_EXPORT mgbool MGP_Window_GetAllowUserResizing(MGP_Window* window); +MG_EXPORT void MGP_Window_SetAllowUserResizing(MGP_Window* window, mgbool allow); +MG_EXPORT mgbool MGP_Window_GetIsBoderless(MGP_Window* window); +MG_EXPORT void MGP_Window_SetIsBoderless(MGP_Window* window, mgbool borderless); +MG_EXPORT void MGP_Window_SetTitle(MGP_Window* window, const char* title); +MG_EXPORT void MGP_Window_Show(MGP_Window* window, mgbool show); +MG_EXPORT void MGP_Window_GetPosition(MGP_Window* window, mgint& x, mgint& y); +MG_EXPORT void MGP_Window_SetPosition(MGP_Window* window, mgint x, mgint y); +MG_EXPORT void MGP_Window_SetClientSize(MGP_Window* window, mgint width, mgint height); +MG_EXPORT void MGP_Window_SetCursor(MGP_Window* window, MGP_Cursor* cursor); +MG_EXPORT mgint MGP_Window_ShowMessageBox(MGP_Window* window, const char* title, const char* description, const char** buttons, mgint count); +MG_EXPORT void MGP_Window_EnterFullScreen(MGP_Window* window, mgbool useHardwareModeSwitch); +MG_EXPORT void MGP_Window_ExitFullScreen(MGP_Window* window); +MG_EXPORT void MGP_Mouse_SetVisible(MGP_Platform* platform, mgbool visible); +MG_EXPORT void MGP_Mouse_WarpPosition(MGP_Window* window, mgint x, mgint y); +MG_EXPORT MGP_Cursor* MGP_Cursor_Create(MGSystemCursor cursor); +MG_EXPORT MGP_Cursor* MGP_Cursor_CreateCustom(mgbyte* rgba, mgint width, mgint height, mgint originx, mgint originy); +MG_EXPORT void MGP_Cursor_Destroy(MGP_Cursor* cursor); +MG_EXPORT mgint MGP_GamePad_GetMaxSupported(); diff --git a/native/monogame/include/api_common.h b/native/monogame/include/api_common.h new file mode 100644 index 00000000000..79de751614b --- /dev/null +++ b/native/monogame/include/api_common.h @@ -0,0 +1,26 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +#pragma once + +typedef unsigned short mgchar; +typedef unsigned char mgbyte; +typedef short mgshort; +typedef unsigned short mgushort; +typedef int mgint; +typedef unsigned int mguint; +typedef long long mglong; +typedef unsigned long long mgulong; +typedef bool mgbool; +typedef float mgfloat; +typedef double mgdouble; + + +#define MG_FIELD_OFFSET(off, type, name) struct { char _pad_##name[off]; type name; } + +#ifdef DLL_EXPORT +#define MG_EXPORT extern "C" __declspec(dllexport) +#else +#define MG_EXPORT extern "C" +#endif diff --git a/native/monogame/include/api_enums.h b/native/monogame/include/api_enums.h new file mode 100644 index 00000000000..a878ece5a2d --- /dev/null +++ b/native/monogame/include/api_enums.h @@ -0,0 +1,527 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +// This code is auto generated, don't modify it by hand. +// To regenerate it run: Tools/MonoGame.Generator.CTypes + +#pragma once + +#include "api_common.h" + +enum class MGSoundState : mgint +{ + Playing = 0, + Paused = 1, + Stopped = 2, +}; + +enum class MGFilterMode : mgint +{ + LowPass = 0, + BandPass = 1, + HighPass = 2, +}; + +enum class MGSurfaceFormat : mgint +{ + Color = 0, + Bgr565 = 1, + Bgra5551 = 2, + Bgra4444 = 3, + Dxt1 = 4, + Dxt3 = 5, + Dxt5 = 6, + NormalizedByte2 = 7, + NormalizedByte4 = 8, + Rgba1010102 = 9, + Rg32 = 10, + Rgba64 = 11, + Alpha8 = 12, + Single = 13, + Vector2 = 14, + Vector4 = 15, + HalfSingle = 16, + HalfVector2 = 17, + HalfVector4 = 18, + HdrBlendable = 19, + Bgr32 = 20, + Bgra32 = 21, + ColorSRgb = 30, + Bgr32SRgb = 31, + Bgra32SRgb = 32, + Dxt1SRgb = 33, + Dxt3SRgb = 34, + Dxt5SRgb = 35, + RgbPvrtc2Bpp = 50, + RgbPvrtc4Bpp = 51, + RgbaPvrtc2Bpp = 52, + RgbaPvrtc4Bpp = 53, + RgbEtc1 = 60, + Dxt1a = 70, + RgbaAtcExplicitAlpha = 80, + RgbaAtcInterpolatedAlpha = 81, + Rgb8Etc2 = 90, + Srgb8Etc2 = 91, + Rgb8A1Etc2 = 92, + Srgb8A1Etc2 = 93, + Rgba8Etc2 = 94, + SRgb8A8Etc2 = 95, + Astc4X4Rgba = 96, +}; + +enum class MGDepthFormat : mgint +{ + None = 0, + Depth16 = 1, + Depth24 = 2, + Depth24Stencil8 = 3, +}; + +enum class MGClearOptions : mgint +{ + Target = 1, + DepthBuffer = 2, + Stencil = 4, +}; + +enum class MGShaderStage : mgint +{ + Vertex = 0, + Pixel = 1, + Count = 2, +}; + +enum class MGIndexElementSize : mgint +{ + SixteenBits = 0, + ThirtyTwoBits = 1, +}; + +enum class MGPrimitiveType : mgint +{ + TriangleList = 0, + TriangleStrip = 1, + LineList = 2, + LineStrip = 3, + PointList = 4, +}; + +enum class MGBlend : mgint +{ + One = 0, + Zero = 1, + SourceColor = 2, + InverseSourceColor = 3, + SourceAlpha = 4, + InverseSourceAlpha = 5, + DestinationColor = 6, + InverseDestinationColor = 7, + DestinationAlpha = 8, + InverseDestinationAlpha = 9, + BlendFactor = 10, + InverseBlendFactor = 11, + SourceAlphaSaturation = 12, +}; + +enum class MGBlendFunction : mgint +{ + Add = 0, + Subtract = 1, + ReverseSubtract = 2, + Min = 3, + Max = 4, +}; + +enum class MGColorWriteChannels : mgint +{ + None = 0, + Red = 1, + Green = 2, + Blue = 4, + Alpha = 8, + All = 15, +}; + +enum class MGCompareFunction : mgint +{ + Always = 0, + Never = 1, + Less = 2, + LessEqual = 3, + Equal = 4, + GreaterEqual = 5, + Greater = 6, + NotEqual = 7, +}; + +enum class MGStencilOperation : mgint +{ + Keep = 0, + Zero = 1, + Replace = 2, + Increment = 3, + Decrement = 4, + IncrementSaturation = 5, + DecrementSaturation = 6, + Invert = 7, +}; + +enum class MGFillMode : mgint +{ + Solid = 0, + WireFrame = 1, +}; + +enum class MGCullMode : mgint +{ + None = 0, + CullClockwiseFace = 1, + CullCounterClockwiseFace = 2, +}; + +enum class MGTextureAddressMode : mgint +{ + Wrap = 0, + Clamp = 1, + Mirror = 2, + Border = 3, +}; + +enum class MGTextureFilter : mgint +{ + Linear = 0, + Point = 1, + Anisotropic = 2, + LinearMipPoint = 3, + PointMipLinear = 4, + MinLinearMagPointMipLinear = 5, + MinLinearMagPointMipPoint = 6, + MinPointMagLinearMipLinear = 7, + MinPointMagLinearMipPoint = 8, +}; + +enum class MGTextureFilterMode : mgint +{ + Default = 0, + Comparison = 1, +}; + +enum class MGBufferType : mgint +{ + Index = 0, + Vertex = 1, + Constant = 2, +}; + +enum class MGTextureType : mgint +{ + _2D = 0, + _3D = 1, + Cube = 2, +}; + +enum class MGRenderTargetUsage : mgint +{ + DiscardContents = 0, + PreserveContents = 1, + PlatformContents = 2, +}; + +enum class MGVertexElementFormat : mgint +{ + Single = 0, + Vector2 = 1, + Vector3 = 2, + Vector4 = 3, + Color = 4, + Byte4 = 5, + Short2 = 6, + Short4 = 7, + NormalizedShort2 = 8, + NormalizedShort4 = 9, + HalfVector2 = 10, + HalfVector4 = 11, +}; + +enum class MGMediaState : mgint +{ + Stopped = 0, + Playing = 1, + Paused = 2, +}; + +enum class MGGameRunBehavior : mgint +{ + Asynchronous = 0, + Synchronous = 1, +}; + +enum class MGEventType : mguint +{ + Quit = 0, + WindowMoved = 1, + WindowResized = 2, + WindowGainedFocus = 3, + WindowLostFocus = 4, + WindowClose = 5, + KeyDown = 6, + KeyUp = 7, + TextInput = 8, + MouseMove = 9, + MouseButtonDown = 10, + MouseButtonUp = 11, + MouseWheel = 12, + ControllerAdded = 13, + ControllerRemoved = 14, + ControllerStateChange = 15, + DropFile = 16, + DropComplete = 17, +}; + +enum class MGKeys : mgint +{ + None = 0, + Back = 8, + Tab = 9, + Enter = 13, + Pause = 19, + CapsLock = 20, + Kana = 21, + Kanji = 25, + Escape = 27, + ImeConvert = 28, + ImeNoConvert = 29, + Space = 32, + PageUp = 33, + PageDown = 34, + End = 35, + Home = 36, + Left = 37, + Up = 38, + Right = 39, + Down = 40, + Select = 41, + Print = 42, + Execute = 43, + PrintScreen = 44, + Insert = 45, + Delete = 46, + Help = 47, + D0 = 48, + D1 = 49, + D2 = 50, + D3 = 51, + D4 = 52, + D5 = 53, + D6 = 54, + D7 = 55, + D8 = 56, + D9 = 57, + A = 65, + B = 66, + C = 67, + D = 68, + E = 69, + F = 70, + G = 71, + H = 72, + I = 73, + J = 74, + K = 75, + L = 76, + M = 77, + N = 78, + O = 79, + P = 80, + Q = 81, + R = 82, + S = 83, + T = 84, + U = 85, + V = 86, + W = 87, + X = 88, + Y = 89, + Z = 90, + LeftWindows = 91, + RightWindows = 92, + Apps = 93, + Sleep = 95, + NumPad0 = 96, + NumPad1 = 97, + NumPad2 = 98, + NumPad3 = 99, + NumPad4 = 100, + NumPad5 = 101, + NumPad6 = 102, + NumPad7 = 103, + NumPad8 = 104, + NumPad9 = 105, + Multiply = 106, + Add = 107, + Separator = 108, + Subtract = 109, + Decimal = 110, + Divide = 111, + F1 = 112, + F2 = 113, + F3 = 114, + F4 = 115, + F5 = 116, + F6 = 117, + F7 = 118, + F8 = 119, + F9 = 120, + F10 = 121, + F11 = 122, + F12 = 123, + F13 = 124, + F14 = 125, + F15 = 126, + F16 = 127, + F17 = 128, + F18 = 129, + F19 = 130, + F20 = 131, + F21 = 132, + F22 = 133, + F23 = 134, + F24 = 135, + NumLock = 144, + Scroll = 145, + LeftShift = 160, + RightShift = 161, + LeftControl = 162, + RightControl = 163, + LeftAlt = 164, + RightAlt = 165, + BrowserBack = 166, + BrowserForward = 167, + BrowserRefresh = 168, + BrowserStop = 169, + BrowserSearch = 170, + BrowserFavorites = 171, + BrowserHome = 172, + VolumeMute = 173, + VolumeDown = 174, + VolumeUp = 175, + MediaNextTrack = 176, + MediaPreviousTrack = 177, + MediaStop = 178, + MediaPlayPause = 179, + LaunchMail = 180, + SelectMedia = 181, + LaunchApplication1 = 182, + LaunchApplication2 = 183, + OemSemicolon = 186, + OemPlus = 187, + OemComma = 188, + OemMinus = 189, + OemPeriod = 190, + OemQuestion = 191, + OemTilde = 192, + ChatPadGreen = 202, + ChatPadOrange = 203, + OemOpenBrackets = 219, + OemPipe = 220, + OemCloseBrackets = 221, + OemQuotes = 222, + Oem8 = 223, + OemBackslash = 226, + ProcessKey = 229, + OemCopy = 242, + OemAuto = 243, + OemEnlW = 244, + Attn = 246, + Crsel = 247, + Exsel = 248, + EraseEof = 249, + Play = 250, + Zoom = 251, + Pa1 = 253, + OemClear = 254, +}; + +enum class MGMouseButton : mgint +{ + Left = 0, + Middle = 1, + Right = 2, + X1 = 3, + X2 = 4, +}; + +enum class MGControllerInput : mgint +{ + A = 0, + B = 1, + X = 2, + Y = 3, + Back = 4, + Guide = 5, + Start = 6, + LeftStick = 7, + RightStick = 8, + LeftShoulder = 9, + RightShoulder = 10, + DpadUp = 11, + DpadDown = 12, + DpadLeft = 13, + DpadRight = 14, + Misc1 = 15, + Paddle1 = 16, + Paddle2 = 17, + Paddle3 = 18, + Paddle4 = 19, + Touchpad = 20, + LAST_BUTTON = 20, + LeftStickX = 21, + LeftStickY = 22, + RightStickX = 23, + RightStickY = 24, + LeftTrigger = 25, + LAST_TRIGGER = 26, + RightTrigger = 26, + INVALID = -1, +}; + +enum class MGMonoGamePlatform : mgint +{ + Android = 0, + iOS = 1, + tvOS = 2, + DesktopGL = 3, + Windows = 4, + WebGL = 5, + XboxOne = 6, + PlayStation4 = 7, + PlayStation5 = 8, + NintendoSwitch = 9, + DesktopVK = 10, +}; + +enum class MGGraphicsBackend : mgint +{ + DirectX = 0, + OpenGL = 1, + Vulkan = 2, + Metal = 3, +}; + +enum class MGSystemCursor : mgint +{ + Arrow = 0, + IBeam = 1, + Wait = 2, + Crosshair = 3, + WaitArrow = 4, + SizeNWSE = 5, + SizeNESW = 6, + SizeWE = 7, + SizeNS = 8, + SizeAll = 9, + No = 10, + Hand = 11, +}; + diff --git a/native/monogame/include/api_structs.h b/native/monogame/include/api_structs.h new file mode 100644 index 00000000000..6745b5ce01c --- /dev/null +++ b/native/monogame/include/api_structs.h @@ -0,0 +1,221 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +// This code is auto generated, don't modify it by hand. +// To regenerate it run: Tools/MonoGame.Generator.CTypes + +#pragma once + +#include "api_common.h" + +struct ReverbSettings +{ + mgfloat ReflectionsDelayMs; + mgfloat ReverbDelayMs; + mgfloat PositionLeft; + mgfloat PositionRight; + mgfloat PositionLeftMatrix; + mgfloat PositionRightMatrix; + mgfloat EarlyDiffusion; + mgfloat LateDiffusion; + mgfloat LowEqGain; + mgfloat LowEqCutoff; + mgfloat HighEqGain; + mgfloat HighEqCutoff; + mgfloat RearDelayMs; + mgfloat RoomFilterFrequencyHz; + mgfloat RoomFilterMainDb; + mgfloat RoomFilterHighFrequencyDb; + mgfloat ReflectionsGainDb; + mgfloat ReverbGainDb; + mgfloat DecayTimeSec; + mgfloat DensityPct; + mgfloat RoomSizeFeet; + mgfloat WetDryMixPct; +}; + +struct Vector3 +{ + mgfloat X; + mgfloat Y; + mgfloat Z; +}; + +struct Listener +{ + Vector3 Position; + Vector3 Forward; + Vector3 Up; + Vector3 Velocity; +}; + +struct Emitter +{ + Vector3 Position; + Vector3 Forward; + Vector3 Up; + Vector3 Velocity; + mgfloat DopplerScale; +}; + +struct MGG_DisplayMode +{ + MGSurfaceFormat format; + mgint width; + mgint height; +}; + +struct MGG_GraphicsAdaptor_Info +{ + void* DeviceName; + void* Description; + mgint DeviceId; + mgint Revision; + mgint VendorId; + mgint SubSystemId; + void* MonitorHandle; + MGG_DisplayMode* DisplayModes; + mgint DisplayModeCount; + MGG_DisplayMode CurrentDisplayMode; +}; + +struct MGG_GraphicsDevice_Caps +{ + mgint MaxTextureSlots; + mgint MaxVertexTextureSlots; + mgint MaxVertexBufferSlots; + mgint ShaderProfile; +}; + +struct Vector4 +{ + mgfloat X; + mgfloat Y; + mgfloat Z; + mgfloat W; +}; + +struct MGG_BlendState_Info +{ + MGBlend colorSourceBlend; + MGBlend colorDestBlend; + MGBlendFunction colorBlendFunc; + MGBlend alphaSourceBlend; + MGBlend alphaDestBlend; + MGBlendFunction alphaBlendFunc; + MGColorWriteChannels colorWriteChannels; +}; + +struct MGG_DepthStencilState_Info +{ + mgbool depthBufferEnable; + mgbool depthBufferWriteEnable; + MGCompareFunction depthBufferFunction; + mgint referenceStencil; + mgbool stencilEnable; + mgint stencilMask; + mgint stencilWriteMask; + MGCompareFunction stencilFunction; + MGStencilOperation stencilDepthBufferFail; + MGStencilOperation stencilFail; + MGStencilOperation stencilPass; +}; + +struct MGG_RasterizerState_Info +{ + MGFillMode fillMode; + MGCullMode cullMode; + mgbool scissorTestEnable; + mgbool depthClipEnable; + mgfloat depthBias; + mgfloat slopeScaleDepthBias; + mgbool multiSampleAntiAlias; +}; + +struct MGG_SamplerState_Info +{ + MGTextureAddressMode AddressU; + MGTextureAddressMode AddressV; + MGTextureAddressMode AddressW; + mguint BorderColor; + MGTextureFilter Filter; + MGTextureFilterMode FilterMode; + mgint MaximumAnisotropy; + mgint MaxMipLevel; + mgfloat MipMapLevelOfDetailBias; + MGCompareFunction ComparisonFunction; +}; + +struct MGG_InputElement +{ + mguint VertexBufferSlot; + MGVertexElementFormat Format; + mguint AlignedByteOffset; + mguint InstanceDataStepRate; +}; + +struct MGP_KeyEvent +{ + void* Window; + mguint Character; + MGKeys Key; +}; + +struct MGP_MouseMoveEvent +{ + void* Window; + mgint X; + mgint Y; +}; + +struct MGP_MouseButtonEvent +{ + void* Window; + MGMouseButton Button; +}; + +struct MGP_MouseWheelEvent +{ + void* Window; + mgint Scroll; + mgint ScrollH; +}; + +struct MGP_DropEvent +{ + void* Window; + void* File; +}; + +struct MGP_WindowEvent +{ + void* Window; + mgint Data1; + mgint Data2; +}; + +struct MGP_ControllerEvent +{ + mgint Id; + MGControllerInput Input; + mgshort Value; +}; + +#pragma pack(push,1) +struct MGP_Event +{ +union { + MGEventType Type; + MG_FIELD_OFFSET(4, mgulong, Timestamp); + MG_FIELD_OFFSET(12, MGP_KeyEvent, Key); + MG_FIELD_OFFSET(12, MGP_MouseMoveEvent, MouseMove); + MG_FIELD_OFFSET(12, MGP_MouseButtonEvent, MouseButton); + MG_FIELD_OFFSET(12, MGP_MouseWheelEvent, MouseWheel); + MG_FIELD_OFFSET(12, MGP_DropEvent, Drop); + MG_FIELD_OFFSET(12, MGP_WindowEvent, Window); + MG_FIELD_OFFSET(12, MGP_ControllerEvent, Controller); +}; +}; +#pragma pack(pop) + diff --git a/native/monogame/include/mg_common.h b/native/monogame/include/mg_common.h new file mode 100644 index 00000000000..0352a4229c6 --- /dev/null +++ b/native/monogame/include/mg_common.h @@ -0,0 +1,72 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +#pragma once + +#include "api_common.h" + +#include +#include + +#include +#include +#include +#include +#include + + +#if defined(_WIN32) +#define MG_GENERATE_TRAP() __debugbreak() +#else +#define MG_GENERATE_TRAP() __builtin_trap() +#endif + +#if defined(_WIN32) +#define MG_PATH_SEPARATOR "\\" +#else +#define MG_PATH_SEPARATOR "/" +#endif + +inline void MG_Print_StdError(const char* file, int line, const char* message) +{ + fflush(stdout); + fprintf(stderr, "%s(%d): %s\n", file, line, message); + fflush(stderr); +} + +inline void MG_Print_StdOut(const char* file, int line, const char* message) +{ + fprintf(stdout, "%s(%d): %s\n", file, line, message); + fflush(stdout); +} + +#define MG_PRINT(msg) \ + MG_Print_StdOut(__FILE__, __LINE__, msg) + +#define MG_ERROR_PRINT(msg) \ + MG_Print_StdError(__FILE__, __LINE__, msg) + +#define MG_NOT_IMPLEMEMTED MG_ERROR_PRINT("NOT IMPLEMENTED!"); MG_GENERATE_TRAP() + + +mguint MG_ComputeHash(const mgbyte* value, mgint length); +mguint MG_ComputeHash(mguint value, mguint result = 0x811c9dc5); + +template +void mg_remove(std::vector& vector, const T& element) +{ + auto new_end = std::remove(vector.begin(), vector.end(), element); + assert(new_end != vector.end()); + vector.erase(new_end, vector.end()); +} + +template +bool mg_contains(std::vector& vector, const T& element) +{ + auto found = std::find(vector.begin(), vector.end(), element); + return found != vector.end(); +} + + + diff --git a/native/monogame/make_windows_solution.bat b/native/monogame/make_windows_solution.bat new file mode 100644 index 00000000000..a861b6cc4c1 --- /dev/null +++ b/native/monogame/make_windows_solution.bat @@ -0,0 +1,4 @@ +@echo off +premake5 vs2022 + + diff --git a/native/monogame/premake5.lua b/native/monogame/premake5.lua new file mode 100644 index 00000000000..4d914128cbf --- /dev/null +++ b/native/monogame/premake5.lua @@ -0,0 +1,124 @@ +-- MonoGame - Copyright (C) MonoGame Foundation, Inc +-- This file is subject to the terms and conditions defined in +-- file 'LICENSE.txt', which is part of this source code package. + +function common(project_name) + + platform_target_path = "../../Artifacts/monogame.native/%{cfg.system}/" .. project_name .. "/%{cfg.buildcfg}" + + kind "SharedLib" + language "C++" + architecture "x64" + defines { "DLL_EXPORT" } + targetdir( platform_target_path ) + targetname "monogame.native" + + files + { + "include/**.h", + "common/**.h", + "common/**.cpp", + } + includedirs + { + "include", + } + +end + +-- SDL is supported on all desktop platforms. +function sdl2() + + defines { "MG_SDL2" } + + files + { + "sdl/**.h", + "sdl/**.cpp", + } + + includedirs + { + "external/sdl2/sdl/include", + } + + filter { "system:windows" } + links + { + "external/sdl2/sdl/build/Release/SDL2-static.lib", + "winmm", + "imm32", + "user32", + "gdi32", + "advapi32", + "setupapi", + "ole32", + "oleaut32", + "version", + "shell32" + } + +end + +-- Vulkan is supported for all desktop platforms. +function vulkan() + + defines { "MG_VULKAN" } + + files + { + "vulkan/**.h", + "vulkan/**.cpp", + } + + filter "system:windows" + files { "vulkan/**.rc", } + + includedirs + { + "external/vulkan-headers/include", + "external/volk", + "external/vma/include", + } + +end + + +-- FAudio is supported for all desktop platforms. +function faudio() + + defines { "MG_FAUDIO" } + + files + { + "faudio/**.h", + "faudio/**.cpp", + } + +end + +function configs() + + filter "configurations:Debug" + defines { "DEBUG" } + symbols "On" + + filter "configurations:Release" + defines { "NDEBUG" } + optimize "On" + +end + +workspace "monogame" + configurations { "Debug", "Release" } + +project "desktopvk" + common("desktopvk") + sdl2() + vulkan() + faudio() + configs() + + +project "windowsdx" + common("windowsdx") diff --git a/native/monogame/sdl/MGP_sdl.cpp b/native/monogame/sdl/MGP_sdl.cpp new file mode 100644 index 00000000000..1a03891d1f1 --- /dev/null +++ b/native/monogame/sdl/MGP_sdl.cpp @@ -0,0 +1,892 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +#include "api_MGP.h" + +#include "mg_common.h" + +#include + +#if _WIN32 +#include +#endif + + +struct MGP_Platform +{ + std::vector windows; + std::queue queued_events; +}; + +static std::map s_keymap +{ + { 8, MGKeys::Back }, + { 9, MGKeys::Tab }, + { 13, MGKeys::Enter }, + { 27, MGKeys::Escape }, + { 32, MGKeys::Space }, + { 39, MGKeys::OemQuotes }, + { 43, MGKeys::Add }, + { 44, MGKeys::OemComma }, + { 45, MGKeys::OemMinus }, + { 46, MGKeys::OemPeriod }, + { 47, MGKeys::OemQuestion }, + { 48, MGKeys::D0 }, + { 49, MGKeys::D1 }, + { 50, MGKeys::D2 }, + { 51, MGKeys::D3 }, + { 52, MGKeys::D4 }, + { 53, MGKeys::D5 }, + { 54, MGKeys::D6 }, + { 55, MGKeys::D7 }, + { 56, MGKeys::D8 }, + { 57, MGKeys::D9 }, + { 59, MGKeys::OemSemicolon }, + { 60, MGKeys::OemBackslash }, + { 61, MGKeys::OemPlus }, + { 91, MGKeys::OemOpenBrackets }, + { 92, MGKeys::OemPipe }, + { 93, MGKeys::OemCloseBrackets }, + { 96, MGKeys::OemTilde }, + { 97, MGKeys::A }, + { 98, MGKeys::B }, + { 99, MGKeys::C }, + { 100, MGKeys::D }, + { 101, MGKeys::E }, + { 102, MGKeys::F }, + { 103, MGKeys::G }, + { 104, MGKeys::H }, + { 105, MGKeys::I }, + { 106, MGKeys::J }, + { 107, MGKeys::K }, + { 108, MGKeys::L }, + { 109, MGKeys::M }, + { 110, MGKeys::N }, + { 111, MGKeys::O }, + { 112, MGKeys::P }, + { 113, MGKeys::Q }, + { 114, MGKeys::R }, + { 115, MGKeys::S }, + { 116, MGKeys::T }, + { 117, MGKeys::U }, + { 118, MGKeys::V }, + { 119, MGKeys::W }, + { 120, MGKeys::X }, + { 121, MGKeys::Y }, + { 122, MGKeys::Z }, + { 127, MGKeys::Delete }, + { 1073741881, MGKeys::CapsLock }, + { 1073741882, MGKeys::F1 }, + { 1073741883, MGKeys::F2 }, + { 1073741884, MGKeys::F3 }, + { 1073741885, MGKeys::F4 }, + { 1073741886, MGKeys::F5 }, + { 1073741887, MGKeys::F6 }, + { 1073741888, MGKeys::F7 }, + { 1073741889, MGKeys::F8 }, + { 1073741890, MGKeys::F9 }, + { 1073741891, MGKeys::F10 }, + { 1073741892, MGKeys::F11 }, + { 1073741893, MGKeys::F12 }, + { 1073741894, MGKeys::PrintScreen }, + { 1073741895, MGKeys::Scroll }, + { 1073741896, MGKeys::Pause }, + { 1073741897, MGKeys::Insert }, + { 1073741898, MGKeys::Home }, + { 1073741899, MGKeys::PageUp }, + { 1073741901, MGKeys::End }, + { 1073741902, MGKeys::PageDown }, + { 1073741903, MGKeys::Right }, + { 1073741904, MGKeys::Left }, + { 1073741905, MGKeys::Down }, + { 1073741906, MGKeys::Up }, + { 1073741907, MGKeys::NumLock }, + { 1073741908, MGKeys::Divide }, + { 1073741909, MGKeys::Multiply }, + { 1073741910, MGKeys::Subtract }, + { 1073741911, MGKeys::Add }, + { 1073741912, MGKeys::Enter }, + { 1073741913, MGKeys::NumPad1 }, + { 1073741914, MGKeys::NumPad2 }, + { 1073741915, MGKeys::NumPad3 }, + { 1073741916, MGKeys::NumPad4 }, + { 1073741917, MGKeys::NumPad5 }, + { 1073741918, MGKeys::NumPad6 }, + { 1073741919, MGKeys::NumPad7 }, + { 1073741920, MGKeys::NumPad8 }, + { 1073741921, MGKeys::NumPad9 }, + { 1073741922, MGKeys::NumPad0 }, + { 1073741923, MGKeys::Decimal }, + { 1073741925, MGKeys::Apps }, + { 1073741928, MGKeys::F13 }, + { 1073741929, MGKeys::F14 }, + { 1073741930, MGKeys::F15 }, + { 1073741931, MGKeys::F16 }, + { 1073741932, MGKeys::F17 }, + { 1073741933, MGKeys::F18 }, + { 1073741934, MGKeys::F19 }, + { 1073741935, MGKeys::F20 }, + { 1073741936, MGKeys::F21 }, + { 1073741937, MGKeys::F22 }, + { 1073741938, MGKeys::F23 }, + { 1073741939, MGKeys::F24 }, + { 1073741951, MGKeys::VolumeMute }, + { 1073741952, MGKeys::VolumeUp }, + { 1073741953, MGKeys::VolumeDown }, + { 1073742040, MGKeys::OemClear }, + { 1073742044, MGKeys::Decimal }, + { 1073742048, MGKeys::LeftControl }, + { 1073742049, MGKeys::LeftShift }, + { 1073742050, MGKeys::LeftAlt }, + { 1073742051, MGKeys::LeftWindows }, + { 1073742052, MGKeys::RightControl }, + { 1073742053, MGKeys::RightShift }, + { 1073742054, MGKeys::RightAlt }, + { 1073742055, MGKeys::RightWindows }, + { 1073742082, MGKeys::MediaNextTrack }, + { 1073742083, MGKeys::MediaPreviousTrack }, + { 1073742084, MGKeys::MediaStop }, + { 1073742085, MGKeys::MediaPlayPause }, + { 1073742086, MGKeys::VolumeMute }, + { 1073742087, MGKeys::SelectMedia }, + { 1073742089, MGKeys::LaunchMail }, + { 1073742092, MGKeys::BrowserSearch }, + { 1073742093, MGKeys::BrowserHome }, + { 1073742094, MGKeys::BrowserBack }, + { 1073742095, MGKeys::BrowserForward }, + { 1073742096, MGKeys::BrowserStop }, + { 1073742097, MGKeys::BrowserRefresh }, + { 1073742098, MGKeys::BrowserFavorites }, + { 1073742106, MGKeys::Sleep }, +}; + +inline MGKeys ToXNA(SDL_Keycode key) +{ + auto pair = s_keymap.find((int)key); + if (pair == s_keymap.end()) + return MGKeys::None; + + return pair->second; +} + +struct MGP_Window +{ + MGP_Platform* platform = nullptr; + + Uint32 windowId = 0; + + std::string identifier; + + SDL_Window* window = nullptr; +}; + +struct MGP_Cursor +{ + SDL_Cursor* cursor; +}; + + +MGP_Platform* MGP_Platform_Create(MGGameRunBehavior& behavior) +{ + SDL_Init( + SDL_INIT_VIDEO | + SDL_INIT_JOYSTICK | + SDL_INIT_GAMECONTROLLER | + SDL_INIT_HAPTIC); + + SDL_DisableScreenSaver(); + + SDL_SetHint("SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS", "0"); + SDL_SetHint("SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS", "1"); + + behavior = MGGameRunBehavior::Synchronous; + + auto platform = new MGP_Platform(); + return platform; +} + +void MGP_Platform_Destroy(MGP_Platform* platform) +{ + assert(platform != nullptr); + + // Destroy any active windows that may have been leaked. + for (auto window : platform->windows) + MGP_Window_Destroy(window); + + delete platform; +} + +const char* MGP_Platform_MakePath(const char* location, const char* path) +{ + assert(location != nullptr); + assert(path != nullptr); + + size_t length = strlen(path) + 1; + if (location[0]) + length += strlen(location) + 1; + +#if _WIN32 + // Windows requires marshaled strings to be allocated like this. + char* fpath = (char*)CoTaskMemAlloc(length); +#else + char* fpath = (char*)malloc(length); +#endif + + if (location[0]) + { + strcpy_s(fpath, length, location); + strcat_s(fpath, length, MG_PATH_SEPARATOR); + strcat_s(fpath, length, path); + } + else + { + strcpy_s(fpath, length, path); + } + + return fpath; +} + +void MGP_Platform_BeforeInitialize(MGP_Platform* platform) +{ + assert(platform != nullptr); +} + +MGMonoGamePlatform MGP_Platform_GetPlatform() +{ +#if MG_VULKAN + return MGMonoGamePlatform::DesktopVK; +#else + assert(false); + return (MGMonoGamePlatform)-1; +#endif +} + +MGGraphicsBackend MGP_Platform_GetGraphicsBackend() +{ +#if MG_VULKAN + return MGGraphicsBackend::Vulkan; +#else + assert(false); + return (MGGraphicsBackend)-1; +#endif + +} + +static MGP_Window* MGP_WindowFromId(MGP_Platform* platform, Uint32 windowId) +{ + assert(platform != nullptr); + + for (auto window : platform->windows) + { + if (window->windowId == windowId) + return window; + } + + return nullptr; +} + +static int UTF8ToUnicode(int utf8) +{ + int byte4 = utf8 & 0xFF, + byte3 = (utf8 >> 8) & 0xFF, + byte2 = (utf8 >> 16) & 0xFF, + byte1 = (utf8 >> 24) & 0xFF; + + if (byte1 < 0x80) + return byte1; + else if (byte1 < 0xC0) + return -1; + else if (byte1 < 0xE0 && byte2 >= 0x80 && byte2 < 0xC0) + return (byte1 % 0x20) * 0x40 + (byte2 % 0x40); + else if (byte1 < 0xF0 && byte2 >= 0x80 && byte2 < 0xC0 && byte3 >= 0x80 && byte3 < 0xC0) + return (byte1 % 0x10) * 0x40 * 0x40 + (byte2 % 0x40) * 0x40 + (byte3 % 0x40); + else if (byte1 < 0xF8 && byte2 >= 0x80 && byte2 < 0xC0 && byte3 >= 0x80 && byte3 < 0xC0 && byte4 >= 0x80 && byte4 < 0xC0) + return (byte1 % 0x8) * 0x40 * 0x40 * 0x40 + (byte2 % 0x40) * 0x40 * 0x40 + (byte3 % 0x40) * 0x40 + (byte4 % 0x40); + else + return -1; +} + +static MGControllerInput FromSDLButton(Uint8 button) +{ + switch (button) + { + default: + return MGControllerInput::INVALID; + case SDL_CONTROLLER_BUTTON_A: + return MGControllerInput::A; + case SDL_CONTROLLER_BUTTON_B: + return MGControllerInput::B; + case SDL_CONTROLLER_BUTTON_X: + return MGControllerInput::X; + case SDL_CONTROLLER_BUTTON_Y: + return MGControllerInput::Y; + case SDL_CONTROLLER_BUTTON_BACK: + return MGControllerInput::Back; + case SDL_CONTROLLER_BUTTON_GUIDE: + return MGControllerInput::Guide; + case SDL_CONTROLLER_BUTTON_START: + return MGControllerInput::Start; + case SDL_CONTROLLER_BUTTON_LEFTSTICK: + return MGControllerInput::LeftStick; + case SDL_CONTROLLER_BUTTON_RIGHTSTICK: + return MGControllerInput::RightStick; + case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: + return MGControllerInput::LeftShoulder; + case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: + return MGControllerInput::RightShoulder; + case SDL_CONTROLLER_BUTTON_DPAD_UP: + return MGControllerInput::DpadUp; + case SDL_CONTROLLER_BUTTON_DPAD_DOWN: + return MGControllerInput::DpadDown; + case SDL_CONTROLLER_BUTTON_DPAD_LEFT: + return MGControllerInput::DpadLeft; + case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: + return MGControllerInput::DpadRight; + case SDL_CONTROLLER_BUTTON_MISC1: + return MGControllerInput::Misc1; + case SDL_CONTROLLER_BUTTON_PADDLE1: + return MGControllerInput::Paddle1; + case SDL_CONTROLLER_BUTTON_PADDLE2: + return MGControllerInput::Paddle2; + case SDL_CONTROLLER_BUTTON_PADDLE3: + return MGControllerInput::Paddle3; + case SDL_CONTROLLER_BUTTON_PADDLE4: + return MGControllerInput::Paddle4; + case SDL_CONTROLLER_BUTTON_TOUCHPAD: + return MGControllerInput::Touchpad; + } +} + + +static MGControllerInput FromSDLAxis(Uint8 axis) +{ + switch (axis) + { + default: + return MGControllerInput::INVALID; + case SDL_CONTROLLER_AXIS_LEFTX: + return MGControllerInput::LeftStickX; + case SDL_CONTROLLER_AXIS_LEFTY: + return MGControllerInput::LeftStickY; + case SDL_CONTROLLER_AXIS_RIGHTX: + return MGControllerInput::RightStickX; + case SDL_CONTROLLER_AXIS_RIGHTY: + return MGControllerInput::RightStickY; + case SDL_CONTROLLER_AXIS_TRIGGERLEFT: + return MGControllerInput::LeftTrigger; + case SDL_CONTROLLER_AXIS_TRIGGERRIGHT: + return MGControllerInput::RightTrigger; + } +} + +mgbool MGP_Platform_PollEvent(MGP_Platform* platform, MGP_Event& event_) +{ + assert(platform != nullptr); + + SDL_Event ev; + + const int MOUSE_WHEEL_DELTA = 120; + + // If we had previous queued events then return those. + if (platform->queued_events.size() > 0) + { + event_ = platform->queued_events.front(); + platform->queued_events.pop(); + return true; + } + + while (SDL_PollEvent(&ev) == 1) + { + // TODO: We cannot call SDL_GetTicks64 as it is different from + // SDL_GetTicks() and controller and keyboard events return SDL_GetTicks(). + event_.Timestamp = SDL_GetTicks(); + + switch (ev.type) + { + case SDL_QUIT: + event_.Type = MGEventType::Quit; + return true; + + case SDL_EventType::SDL_JOYDEVICEADDED: + break; + case SDL_EventType::SDL_JOYDEVICEREMOVED: + break; + + case SDL_EventType::SDL_CONTROLLERDEVICEADDED: + SDL_GameControllerOpen(ev.cdevice.which); + event_.Type = MGEventType::ControllerAdded; + event_.Timestamp = ev.cdevice.timestamp; + event_.Controller.Id = SDL_JoystickGetDeviceInstanceID(ev.cdevice.which); + event_.Controller.Input = MGControllerInput::INVALID; + event_.Controller.Value = 0; + return true; + case SDL_EventType::SDL_CONTROLLERDEVICEREMOVED: + event_.Type = MGEventType::ControllerRemoved; + event_.Timestamp = ev.cdevice.timestamp; + event_.Controller.Id = ev.cdevice.which; + event_.Controller.Input = MGControllerInput::INVALID; + event_.Controller.Value = 0; + return true; + case SDL_EventType::SDL_CONTROLLERBUTTONUP: + event_.Type = MGEventType::ControllerStateChange; + event_.Timestamp = ev.cbutton.timestamp; + event_.Controller.Id = ev.cbutton.which; + event_.Controller.Input = FromSDLButton(ev.cbutton.button); + event_.Controller.Value = 0; + return true; + case SDL_EventType::SDL_CONTROLLERBUTTONDOWN: + event_.Type = MGEventType::ControllerStateChange; + event_.Timestamp = ev.cbutton.timestamp; + event_.Controller.Id = ev.cbutton.which; + event_.Controller.Input = FromSDLButton(ev.cbutton.button); + event_.Controller.Value = 1; + return true; + case SDL_EventType::SDL_CONTROLLERAXISMOTION: + event_.Type = MGEventType::ControllerStateChange; + event_.Timestamp = ev.caxis.timestamp; + event_.Controller.Id = ev.caxis.which; + event_.Controller.Input = FromSDLAxis(ev.caxis.axis); + event_.Controller.Value = ev.caxis.value; + return true; + break; + + case SDL_EventType::SDL_MOUSEMOTION: + event_.Type = MGEventType::MouseMove; + event_.MouseMove.Window = MGP_WindowFromId(platform, ev.motion.windowID); + event_.MouseMove.X = ev.motion.x; + event_.MouseMove.Y = ev.motion.y; + return true; + + case SDL_EventType::SDL_MOUSEWHEEL: + event_.Type = MGEventType::MouseWheel; + event_.MouseWheel.Window = MGP_WindowFromId(platform, ev.wheel.windowID); + event_.MouseWheel.Scroll = ev.wheel.y * MOUSE_WHEEL_DELTA; + event_.MouseWheel.ScrollH = ev.wheel.x * MOUSE_WHEEL_DELTA; + return true; + + case SDL_EventType::SDL_MOUSEBUTTONUP: + case SDL_EventType::SDL_MOUSEBUTTONDOWN: + event_.Type = ev.type == SDL_EventType::SDL_MOUSEBUTTONDOWN ? MGEventType::MouseButtonDown : MGEventType::MouseButtonUp; + event_.MouseButton.Window = MGP_WindowFromId(platform, ev.button.windowID); + switch (ev.button.button) + { + default: + case SDL_BUTTON_LEFT: + event_.MouseButton.Button = MGMouseButton::Left; + break; + case SDL_BUTTON_RIGHT: + event_.MouseButton.Button = MGMouseButton::Right; + break; + case SDL_BUTTON_MIDDLE: + event_.MouseButton.Button = MGMouseButton::Middle; + break; + case SDL_BUTTON_X1: + event_.MouseButton.Button = MGMouseButton::X1; + break; + case SDL_BUTTON_X2: + event_.MouseButton.Button = MGMouseButton::X2; + break; + } + return true; + + case SDL_EventType::SDL_KEYDOWN: + { + event_.Type = MGEventType::KeyDown; + + event_.Key.Window = MGP_WindowFromId(platform, ev.key.windowID); + event_.Key.Character = ev.key.keysym.sym; + event_.Key.Key = ToXNA(ev.key.keysym.sym); + + return true; + } + case SDL_EventType::SDL_KEYUP: + { + event_.Type = MGEventType::KeyUp; + + event_.Key.Window = MGP_WindowFromId(platform, ev.key.windowID); + event_.Key.Character = ev.key.keysym.sym; + event_.Key.Key = ToXNA(ev.key.keysym.sym); + + return true; + } + + case SDL_TEXTINPUT: + { + event_.Type = MGEventType::TextInput; + event_.Key.Window = MGP_WindowFromId(platform, ev.text.windowID); + + int len = 0; + int utf8character = 0; // using an int to encode multibyte characters longer than 2 bytes + mgbyte currentByte = 0; + int charByteSize = 0; // UTF8 char length to decode + int remainingShift = 0; + while ((currentByte = ev.text.text[len]) != 0) + { + // we're reading the first UTF8 byte, we need to check if it's multibyte + if (charByteSize == 0) + { + if (currentByte < 192) + charByteSize = 1; + else if (currentByte < 224) + charByteSize = 2; + else if (currentByte < 240) + charByteSize = 3; + else + charByteSize = 4; + + utf8character = 0; + remainingShift = 4; + } + + // assembling the character + utf8character <<= 8; + utf8character |= currentByte; + + charByteSize--; + remainingShift--; + + if (charByteSize == 0) // finished decoding the current character + { + utf8character <<= remainingShift * 8; // shifting it to full UTF8 scope + + // SDL returns UTF8-encoded characters while C# char type is UTF16-encoded (and limited to the 0-FFFF range / does not support surrogate pairs) + // so we need to convert it to Unicode codepoint and check if it's within the supported range + int codepoint = UTF8ToUnicode(utf8character); + if (codepoint >= 0 && codepoint < 0xFFFF) + { + event_.Key.Character = codepoint; + event_.Key.Key = ToXNA(codepoint); + + platform->queued_events.push(event_); + + // UTF16 characters beyond 0xFFFF are not supported (and would require a surrogate encoding that is not supported by the char type) + } + } + + len++; + } + + if (platform->queued_events.size() > 0) + { + event_ = platform->queued_events.front(); + platform->queued_events.pop(); + return true; + } + + break; + } + + case SDL_WINDOWEVENT: + { + event_.Window.Window = MGP_WindowFromId(platform, ev.window.windowID); + + switch (ev.window.event) + { + case SDL_WINDOWEVENT_RESIZED: + case SDL_WINDOWEVENT_SIZE_CHANGED: + event_.Type = MGEventType::WindowResized; + event_.Window.Data1 = ev.window.data1; + event_.Window.Data2 = ev.window.data2; + return true; + break; + case SDL_WINDOWEVENT_FOCUS_GAINED: + event_.Type = MGEventType::WindowGainedFocus; + return true; + case SDL_WINDOWEVENT_FOCUS_LOST: + event_.Type = MGEventType::WindowLostFocus; + return true; + case SDL_WINDOWEVENT_MOVED: + event_.Type = MGEventType::WindowMoved; + event_.Window.Data1 = ev.window.data1; + event_.Window.Data2 = ev.window.data2; + return true; + case SDL_WINDOWEVENT_CLOSE: + event_.Type = MGEventType::WindowClose; + return true; + } + + break; + } + + case SDL_DROPFILE: + { + event_.Type = MGEventType::DropFile; + event_.Drop.Window = MGP_WindowFromId(platform, ev.drop.windowID); + + static char TempPath[_MAX_PATH]; + strcpy_s(TempPath, _MAX_PATH, ev.drop.file); + SDL_free(ev.drop.file); + + event_.Drop.File = TempPath; + return true; + } + + case SDL_DROPCOMPLETE: + event_.Type = MGEventType::DropComplete; + event_.Drop.Window = MGP_WindowFromId(platform, ev.drop.windowID); + event_.Drop.File = nullptr; + return true; + } + } + + return false; +} + +mgbool MGP_Platform_BeforeRun(MGP_Platform* platform) +{ + assert(platform != nullptr); + return true; +} + +mgbool MGP_Platform_BeforeUpdate(MGP_Platform* platform) +{ + assert(platform != nullptr); + return true; +} + +mgbool MGP_Platform_BeforeDraw(MGP_Platform* platform) +{ + assert(platform != nullptr); + return true; +} + +MGP_Window* MGP_Window_Create( + MGP_Platform* platform, + mgint width, + mgint height, + const char* title) +{ + assert(platform != nullptr); + assert(width > 0); + assert(height > 0); + + auto window = new MGP_Window(); + window->platform = platform; + + // TODO: Why did this start with SDL_WINDOW_FULLSCREEN_DESKTOP in the old C# SDL? + // We should write coments to document odd behaviors like this. + + Uint32 flags = SDL_WINDOW_HIDDEN;// | SDL_WINDOW_FULLSCREEN_DESKTOP; + +#if MG_VULKAN + flags |= SDL_WINDOW_VULKAN; +#else + #error Not implemented +#endif + + title = title ? title : ""; + + window->window = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); + window->windowId = SDL_GetWindowID(window->window); + + platform->windows.push_back(window); + + return window; +} + +void MGP_Window_Destroy(MGP_Window* window) +{ + assert(window != nullptr); + assert(window->platform != nullptr); + + assert(window->window != nullptr); + SDL_DestroyWindow(window->window); + + mg_remove(window->platform->windows, window); + delete window; +} + +void MGP_Window_SetIconBitmap(MGP_Window* window, mgbyte* icon, mgint length) +{ + assert(window != nullptr); + + auto src = SDL_RWFromConstMem(icon, length); + auto surface = SDL_LoadBMP_RW(src, 1); + + SDL_SetWindowIcon(window->window, surface); +} + +void* MGP_Window_GetNativeHandle(MGP_Window* window) +{ + assert(window != nullptr); + assert(window->window != nullptr); + return window->window; +} + +mgbool MGP_Window_GetAllowUserResizing(MGP_Window* window) +{ + assert(window != nullptr); + assert(window->window != nullptr); + + auto flags = SDL_GetWindowFlags(window->window); + + if ((flags & SDL_WINDOW_RESIZABLE) != 0) + return true; + + return false; +} + +void MGP_Window_SetAllowUserResizing(MGP_Window* window, mgbool allow) +{ + assert(window != nullptr); + assert(window->window != nullptr); + + SDL_SetWindowResizable(window->window, allow ? SDL_TRUE : SDL_FALSE); +} + +mgbool MGP_Window_GetIsBoderless(MGP_Window* window) +{ + assert(window != nullptr); + + auto flags = SDL_GetWindowFlags(window->window); + + if ((flags & SDL_WINDOW_BORDERLESS) != 0) + return true; + + return false; +} + +void MGP_Window_SetIsBoderless(MGP_Window* window, mgbool borderless) +{ + assert(window != nullptr); + + SDL_SetWindowBordered(window->window, borderless ? SDL_FALSE : SDL_TRUE); +} + +void MGP_Window_SetTitle(MGP_Window* window, const char* title) +{ + assert(window != nullptr); + + title = title ? title : ""; + SDL_SetWindowTitle(window->window, title); +} + +void MGP_Window_Show(MGP_Window* window, mgbool show) +{ + assert(window != nullptr); + + if (show) + SDL_ShowWindow(window->window); + else + SDL_HideWindow(window->window); +} + +void MGP_Window_GetPosition(MGP_Window* window, mgint& x, mgint& y) +{ + assert(window != nullptr); + SDL_GetWindowPosition(window->window, &x, &y); +} + +void MGP_Window_SetPosition(MGP_Window* window, mgint x, mgint y) +{ + assert(window != nullptr); + SDL_SetWindowPosition(window->window, x, y); +} + +void MGP_Window_SetClientSize(MGP_Window* window, mgint width, mgint height) +{ + assert(window != nullptr); + SDL_SetWindowSize(window->window, width, height); +} + +void MGP_Window_SetCursor(MGP_Window* window, MGP_Cursor* cursor) +{ + assert(window != nullptr); + assert(cursor != nullptr); + + SDL_SetCursor(cursor->cursor); +} + +void MGP_Window_EnterFullScreen(MGP_Window* window, mgbool useHardwareModeSwitch) +{ + assert(window != nullptr); + + Uint32 flags; + if (useHardwareModeSwitch) + flags = SDL_WINDOW_FULLSCREEN; + else + flags = SDL_WINDOW_FULLSCREEN_DESKTOP; + + SDL_SetWindowFullscreen(window->window, flags); +} + +void MGP_Window_ExitFullScreen(MGP_Window* window) +{ + assert(window != nullptr); + SDL_SetWindowFullscreen(window->window, 0); +} + +void MGP_Mouse_SetVisible(MGP_Platform* platform, mgbool visible) +{ + assert(platform != nullptr); + SDL_ShowCursor(visible ? SDL_ENABLE : SDL_DISABLE); +} + +void MGP_Mouse_WarpPosition(MGP_Window* window, mgint x, mgint y) +{ + assert(window != nullptr); + SDL_WarpMouseInWindow(window->window, x, y); +} + +MGP_Cursor* MGP_Cursor_Create(MGSystemCursor cursor_) +{ + auto cursor = new MGP_Cursor(); + cursor->cursor = SDL_CreateSystemCursor((SDL_SystemCursor)cursor_); + return cursor; +} + +MGP_Cursor* MGP_Cursor_CreateCustom(mgbyte* rgba, mgint width, mgint height, mgint originx, mgint originy) +{ + assert(rgba != nullptr); + + auto cursor = new MGP_Cursor(); + + auto surface = SDL_CreateRGBSurfaceFrom(rgba, width, height, 32, width * 4, 0x000000ff, 0x0000FF00, 0x00FF0000, 0xFF000000); + cursor->cursor = SDL_CreateColorCursor(surface, originx, originy); + + return cursor; +} + +void MGP_Cursor_Destroy(MGP_Cursor* cursor) +{ + assert(cursor != nullptr); + SDL_FreeCursor(cursor->cursor); + delete cursor; +} + +mgint MGP_GamePad_GetMaxSupported() +{ + return 16; +} + +mgint MGP_Window_ShowMessageBox(MGP_Window* window, const char* title, const char* description, const char** buttons, mgint count) +{ + SDL_MessageBoxData data; + data.window = window->window; + data.title = title; + data.message = description; + data.colorScheme = nullptr; + data.flags = SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT; + + auto bdata = new SDL_MessageBoxButtonData[count]; + for (int i = 0; i < count; i++) + { + bdata[i].buttonid = i; + bdata[i].text = buttons[i]; + bdata[i].flags = 0; + } + + data.numbuttons = count; + data.buttons = bdata; + + int hit = -1; + int error = SDL_ShowMessageBox(&data, &hit); + + delete [] bdata; + + if (error == 0) + return hit; + + return -1; +} diff --git a/native/monogame/vulkan/AlphaTestEffect.vk.mgfxo b/native/monogame/vulkan/AlphaTestEffect.vk.mgfxo new file mode 100644 index 00000000000..f51d482f8c7 Binary files /dev/null and b/native/monogame/vulkan/AlphaTestEffect.vk.mgfxo differ diff --git a/native/monogame/vulkan/BasicEffect.vk.mgfxo b/native/monogame/vulkan/BasicEffect.vk.mgfxo new file mode 100644 index 00000000000..79fbdeafae7 Binary files /dev/null and b/native/monogame/vulkan/BasicEffect.vk.mgfxo differ diff --git a/native/monogame/vulkan/DualTextureEffect.vk.mgfxo b/native/monogame/vulkan/DualTextureEffect.vk.mgfxo new file mode 100644 index 00000000000..3946b22a958 Binary files /dev/null and b/native/monogame/vulkan/DualTextureEffect.vk.mgfxo differ diff --git a/native/monogame/vulkan/EnvironmentMapEffect.vk.mgfxo b/native/monogame/vulkan/EnvironmentMapEffect.vk.mgfxo new file mode 100644 index 00000000000..e42e3c84568 Binary files /dev/null and b/native/monogame/vulkan/EnvironmentMapEffect.vk.mgfxo differ diff --git a/native/monogame/vulkan/MGG_Vulkan.cpp b/native/monogame/vulkan/MGG_Vulkan.cpp new file mode 100644 index 00000000000..1c91bc619c0 --- /dev/null +++ b/native/monogame/vulkan/MGG_Vulkan.cpp @@ -0,0 +1,4017 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + +#include "api_MGG.h" + +#include "mg_common.h" + + +#define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1 +#define VULKAN_HPP_NO_EXCEPTIONS +#define VULKAN_HPP_TYPESAFE_CONVERSION 1 +#define VK_NO_PROTOTYPES +#include + +#define VOLK_IMPLEMENTATION +#include + +#define VMA_IMPLEMENTATION +#define VMA_STATIC_VULKAN_FUNCTIONS 1 +#include + +#if defined(MG_SDL2) +#include +#endif + +#ifdef _WIN32 +#include +#include +#include "vulkan.resources.h" +#endif + +#define VK_CHECK_RESULT(vkr) \ +{ \ + VkResult _vkr = vkr; \ + if (_vkr < VK_SUCCESS) \ + { \ + fprintf(stderr, "Fatal : VkResult is %x in %s:%d", _vkr, __FILE__, __LINE__); \ + assert(_vkr == VK_SUCCESS); \ + } \ +} + +template +T MG_AlignUp(T value, const T alignment) +{ + return (value + alignment - 1) & ~(alignment - 1); +} + +struct MGVK_Program; + +typedef uint32_t FrameCounter; + +const FrameCounter kFreeFrames = 2; +const FrameCounter kConcurrentFrameCount = 2; + + +struct MGVK_CmdBuffer +{ + VkSemaphore imageAcquiredSemaphore; + VkSemaphore renderCompleteSemaphore; + VkCommandBuffer buffer; + VkFence completedFence; +}; + +struct MGVK_TargetSet +{ + MGG_Texture* targets[4] = { 0 }; + int numTargets = 0; +}; + +struct MGVK_TargetSetCache +{ + MGVK_TargetSet set; + + int width = 0; + int height = 0; + VkFramebuffer framebuffer = VK_NULL_HANDLE; + VkRenderPass renderPass = VK_NULL_HANDLE; +}; + +struct MGVK_PipelineState +{ + VkPrimitiveTopology topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; + + MGVK_Program* program = nullptr; + MGG_InputLayout* layout = nullptr; + + MGVK_TargetSetCache* targets = nullptr; + + MGG_BlendState* blendState = nullptr; + MGG_RasterizerState* rasterizerState = nullptr; + MGG_DepthStencilState* depthStencilState = nullptr; +}; + +struct MGVK_PipelineCache +{ + MGVK_PipelineState state; + VkPipeline cache = VK_NULL_HANDLE; +}; + +struct MGVK_Program +{ + MGG_Shader* vertex; + MGG_Shader* pixel; + + //std::vector bindings; + + VkPipelineLayout layout; +}; + +struct MGVK_FrameState +{ + bool is_recording = false; + + MGG_Texture* swapchainTexture = nullptr; + MGVK_CmdBuffer commandBuffer; + + uint32_t uniformOffset = 0; + MGG_Buffer* uniforms = nullptr; +}; + + +struct MGG_GraphicsAdapter +{ + VkInstance instance = nullptr; + VkPhysicalDevice device = nullptr; + VkPhysicalDeviceProperties properties = { 0 }; + VkPhysicalDeviceFeatures features = { 0 }; + VkPhysicalDeviceMemoryProperties memory = { 0 }; + + MGG_DisplayMode current = { MGSurfaceFormat::Color, 0, 0 }; + + std::vector modes; +}; + +const int MAX_TEXTURE_SLOTS = 16; + +struct MGG_GraphicsDevice +{ + VkInstance instance = VK_NULL_HANDLE; + + VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; + VkPhysicalDeviceProperties deviceProperties; + VkPhysicalDeviceFeatures deviceFeatures; + VkPhysicalDeviceMemoryProperties deviceMemoryProperties; + + VkDevice device = VK_NULL_HANDLE; + VkQueue queue = VK_NULL_HANDLE; + VkCommandPool cmdPool = VK_NULL_HANDLE; + + VmaAllocator allocator = VK_NULL_HANDLE; + + MGVK_FrameState* frames = nullptr; + FrameCounter frame = 0; + + uint32_t swapchainWidth = 0; + uint32_t swapchainHeight = 0; + VkFormat colorFormat = VK_FORMAT_UNDEFINED; + VkFormat depthFormat = VK_FORMAT_UNDEFINED; + + bool inRenderPass = false; + bool renderTargetDirty = false; + + VkViewport viewport = { 0 }; + VkRect2D scissor = { 0 }; + bool scissorDirty = false; + +#if defined(MG_SDL2) + SDL_Window* window = nullptr; +#else +#error Not Implemented +#endif + VkSurfaceKHR surface = VK_NULL_HANDLE; + VkSwapchainKHR swapchain = VK_NULL_HANDLE; + uint32_t swapchain_image_index = 0; + + uint64_t vertexBuffersDirty = 0; + MGG_Buffer* vertexBuffers[8] = { 0 }; + uint32_t vertexOffsets[8] = { 0 }; + + MGG_Buffer* indexBuffer = nullptr; + MGIndexElementSize indexBufferSize = MGIndexElementSize::SixteenBits; + + uint64_t currentTextureId = 1; + uint64_t currentSamplerId = 1; + MGG_Texture* textures[MAX_TEXTURE_SLOTS] = { 0 }; + MGG_SamplerState* samplers[MAX_TEXTURE_SLOTS] = { 0 }; + uint32_t textureSamplerDirty = 0; + + bool blendFactorDirty = false; + float blendFactor[4] = { 0 }; + + uint32_t currentShaderId = 0; + MGG_Shader* shaders[(mgint)MGShaderStage::Count] = { 0 }; + bool shaderDirty = false; + std::map shader_programs; + std::vector all_shaders; + + VkPipelineCache pipelineCache = VK_NULL_HANDLE; + std::map pipelines; + + std::map blendStates; + std::map rasterizerStates; + std::map depthStencilStates; + + MGVK_TargetSet targets; + std::map targetCache; + + + // + bool pipelineStateDirty = false; + MGVK_PipelineState pipelineState; + + MGG_Buffer* uniforms[2] = { nullptr, nullptr }; + uint32_t uniformsDirty = 0; + + VkDescriptorSet descriptorSets[2] = { 0 }; + uint32_t dynamicOffsets[2] = { 0 }; + + // Some needed limits. + VkDeviceSize minUniformBufferOffsetAlignment = 0; + + std::queue destroyBuffers; + std::queue destroyTextures; + std::queue destroyBlendStates; + std::queue destroyRasterizerStates; + std::queue destroyDepthStencilStates; + + MGG_Buffer* discarded = nullptr; + MGG_Buffer* pending = nullptr; + MGG_Buffer* free = nullptr; + + std::vector all_buffers; + std::vector all_textures; +}; + +struct MGG_Buffer +{ + FrameCounter frame = 0; + + MGG_Buffer* next = nullptr; + + MGBufferType type = MGBufferType::Vertex; + + int dataSize = 0; + int actualSize = 0; + bool dirty = false; + + uint8_t* push = nullptr; + + VkBuffer buffer = VK_NULL_HANDLE; + VmaAllocation allocation = VK_NULL_HANDLE; + + uint8_t* mapped = nullptr; +}; + +struct MGG_Texture +{ + FrameCounter frame; + + MGTextureType type; + MGSurfaceFormat format; + + MGRenderTargetUsage usage = MGRenderTargetUsage::PlatformContents; + + mgbool isTarget = false; + mgbool isSwapchain = false; + + mgint multiSampleCount = 0; + + uint64_t id; + VkImageCreateInfo info; + VkImage image; + + VkImageLayout layout = VK_IMAGE_LAYOUT_GENERAL; + VkImageLayout optimal_layout = VK_IMAGE_LAYOUT_GENERAL; + + VmaAllocation allocation; + + void* mappedAddr; + + VkImageView view = VK_NULL_HANDLE; + VkImageView target_view = VK_NULL_HANDLE; + + MGDepthFormat depthFormat = MGDepthFormat::None; + MGG_Texture* depthTexture; +}; + +struct MGG_InputLayout +{ + VkVertexInputAttributeDescription* attributes = nullptr; + VkVertexInputBindingDescription* bindings = nullptr; + mgint streamCount = 0; + mgint attributeCount = 0; +}; + +struct MGVK_DescriptorInfo +{ + FrameCounter frame; + VkDescriptorSet set; +}; + + +struct MGG_Shader +{ + uint32_t id; + + MGShaderStage stage; + + VkShaderModule module; + VkDescriptorSetLayout setLayout; + + std::vector bindings; + + VkWriteDescriptorSet* writes; + + mguint uniformSlots; + mguint textureSlots; + mguint samplerSlots; + + VkDescriptorPoolCreateInfo* poolInfo; + VkDescriptorPool pool; + + std::queue freeSets; + std::map usedSets; +}; + +struct MGVK_BindingInfo +{ + VkDescriptorType type; + mguint slot; + mguint binding; + MGG_Shader* shader; +}; + +struct MGG_BlendState +{ + FrameCounter frame; + mguint hash; + mgint refs; + VkPipelineColorBlendStateCreateInfo info; + VkPipelineColorBlendAttachmentState attachments[4]; +}; + +struct MGG_DepthStencilState +{ + FrameCounter frame; + mguint hash; + mgint refs; + VkPipelineDepthStencilStateCreateInfo info; +}; + +struct MGG_RasterizerState +{ + FrameCounter frame; + mguint hash; + mgint refs; + VkPipelineRasterizationStateCreateInfo info; + mgbool scissorTestEnable; + mgbool multiSampleAntiAlias; +}; + +struct MGG_SamplerState +{ + uint64_t id; + VkSampler sampler; + MGG_SamplerState_Info info; +}; + +struct MGG_OcclusionQuery +{ + // TODO! +}; + +struct MGG_GraphicsSystem +{ + VkInstance instance; + + std::vector adapters; +}; + + +static void MGVK_BufferCopyAndFlush(MGG_GraphicsDevice* device, MGG_Buffer* buffer, int destOffset, mgbyte* data, int dataBytes); +static MGG_Buffer* MGVK_Buffer_Create(MGG_GraphicsDevice* device, MGBufferType type, mgint sizeInBytes, bool no_push); +static void MGVK_DestroyFrameResources(MGG_GraphicsDevice* device, mgint currentFrame, mgbool free_all); +static void MGVK_UpdateRenderPass(MGG_GraphicsDevice* device, FrameCounter currentFrame, MGVK_CmdBuffer& cmd); +static void MGVK_TransitionImageLayout(MGG_GraphicsDevice* device, MGG_Texture* texture, int32_t level, VkImageLayout newLayout); + + +static VkFormat ToVkFormat(MGSurfaceFormat format) +{ + switch (format) + { + case MGSurfaceFormat::Color: + return VK_FORMAT_R8G8B8A8_UNORM; + case MGSurfaceFormat::Bgr565: + return VK_FORMAT_B5G6R5_UNORM_PACK16; + case MGSurfaceFormat::Bgra5551: + return VK_FORMAT_B5G5R5A1_UNORM_PACK16; + case MGSurfaceFormat::Bgra4444: + return VK_FORMAT_B4G4R4A4_UNORM_PACK16; + case MGSurfaceFormat::Dxt1: + return VK_FORMAT_BC1_RGB_UNORM_BLOCK; + case MGSurfaceFormat::Dxt3: + return VK_FORMAT_BC2_UNORM_BLOCK; + case MGSurfaceFormat::Dxt5: + return VK_FORMAT_BC3_UNORM_BLOCK; + case MGSurfaceFormat::NormalizedByte2: + return VK_FORMAT_R8G8_UNORM; + case MGSurfaceFormat::NormalizedByte4: + return VK_FORMAT_R8G8B8A8_UNORM; + case MGSurfaceFormat::Rgba1010102: + return VK_FORMAT_A2R10G10B10_UNORM_PACK32; + case MGSurfaceFormat::Rg32: + return VK_FORMAT_R16G16_UNORM; + case MGSurfaceFormat::Rgba64: + return VK_FORMAT_R16G16B16A16_UNORM; + case MGSurfaceFormat::Alpha8: + return VK_FORMAT_R8_UNORM; + case MGSurfaceFormat::Single: + return VK_FORMAT_R32_SFLOAT; + case MGSurfaceFormat::Vector2: + return VK_FORMAT_R32G32_SFLOAT; + case MGSurfaceFormat::Vector4: + return VK_FORMAT_R32G32B32A32_SFLOAT; + case MGSurfaceFormat::HalfSingle: + return VK_FORMAT_R32G32B32A32_SFLOAT; + case MGSurfaceFormat::HalfVector2: + return VK_FORMAT_R16G16_SFLOAT; + case MGSurfaceFormat::HalfVector4: + return VK_FORMAT_R16G16B16A16_SFLOAT; + case MGSurfaceFormat::HdrBlendable: + return VK_FORMAT_R16G16B16A16_SFLOAT; + case MGSurfaceFormat::Bgr32: + return VK_FORMAT_B8G8R8A8_UNORM; + case MGSurfaceFormat::Bgra32: + return VK_FORMAT_B8G8R8A8_UNORM; + case MGSurfaceFormat::ColorSRgb: + return VK_FORMAT_R8G8B8A8_SRGB; + case MGSurfaceFormat::Bgr32SRgb: + return VK_FORMAT_B8G8R8A8_SRGB; + case MGSurfaceFormat::Bgra32SRgb: + return VK_FORMAT_B8G8R8A8_SRGB; + case MGSurfaceFormat::Dxt1SRgb: + return VK_FORMAT_BC1_RGB_SRGB_BLOCK; + case MGSurfaceFormat::Dxt3SRgb: + return VK_FORMAT_BC2_SRGB_BLOCK; + case MGSurfaceFormat::Dxt5SRgb: + return VK_FORMAT_BC3_SRGB_BLOCK; + case MGSurfaceFormat::Dxt1a: + return VK_FORMAT_BC1_RGBA_UNORM_BLOCK; + default: + assert(0); + } +} + +static VkFormat ToVkFormat(MGDepthFormat format) +{ + switch (format) + { + case MGDepthFormat::Depth16: + return VkFormat::VK_FORMAT_D16_UNORM; + case MGDepthFormat::Depth24: + case MGDepthFormat::Depth24Stencil8: + return VkFormat::VK_FORMAT_D24_UNORM_S8_UINT; + default: + return VkFormat::VK_FORMAT_UNDEFINED; + } +} + +static VkFormat ToVkFormat(MGVertexElementFormat format) +{ + switch (format) + { + case MGVertexElementFormat::Single: + return VK_FORMAT_R32_SFLOAT; + case MGVertexElementFormat::Vector2: + return VK_FORMAT_R32G32_SFLOAT; + case MGVertexElementFormat::Vector3: + return VK_FORMAT_R32G32B32_SFLOAT; + case MGVertexElementFormat::Vector4: + return VK_FORMAT_R32G32B32A32_SFLOAT; + case MGVertexElementFormat::Color: + return VK_FORMAT_R8G8B8A8_UNORM; + case MGVertexElementFormat::Byte4: + return VK_FORMAT_R8G8B8A8_UINT; + case MGVertexElementFormat::Short2: + return VK_FORMAT_R16G16_SINT; + case MGVertexElementFormat::Short4: + return VK_FORMAT_R16G16B16A16_SINT; + case MGVertexElementFormat::NormalizedShort2: + return VK_FORMAT_R16G16_SSCALED; + case MGVertexElementFormat::NormalizedShort4: + return VK_FORMAT_R16G16B16A16_SSCALED; + case MGVertexElementFormat::HalfVector2: + return VK_FORMAT_R16G16_SFLOAT; + case MGVertexElementFormat::HalfVector4: + return VK_FORMAT_R16G16B16A16_SFLOAT; + default: + assert(0); + } +} + +static VkPrimitiveTopology ToVkPrimitiveTopology(MGPrimitiveType type) +{ + switch (type) + { + case MGPrimitiveType::TriangleList: + return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + case MGPrimitiveType::TriangleStrip: + return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; + case MGPrimitiveType::LineList: + return VK_PRIMITIVE_TOPOLOGY_LINE_LIST; + case MGPrimitiveType::LineStrip: + return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP; + default: + assert(0); + } +} + +static VkImageAspectFlags DetermineAspectMask(VkFormat format) +{ + VkImageAspectFlags result = (VkImageAspectFlags)0; + switch (format) { + // Depth + case VK_FORMAT_D16_UNORM: + case VK_FORMAT_X8_D24_UNORM_PACK32: + case VK_FORMAT_D32_SFLOAT: + result = VK_IMAGE_ASPECT_DEPTH_BIT; + break; + // Stencil + case VK_FORMAT_S8_UINT: + result = VK_IMAGE_ASPECT_STENCIL_BIT; + break; + // Depth/Stencil + case VK_FORMAT_D16_UNORM_S8_UINT: + case VK_FORMAT_D24_UNORM_S8_UINT: + case VK_FORMAT_D32_SFLOAT_S8_UINT: + result = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + break; + // Undefined + case VK_FORMAT_UNDEFINED: + break; + // Assume everything else is Color + default: + result = VK_IMAGE_ASPECT_COLOR_BIT; + break; + } + return result; +} + +void MGG_EffectResource_GetBytecode(const char* name, mgbyte*& bytecode, mgint& size) +{ + bytecode = nullptr; + size = 0; + + // Get the handle of this DLL. + HMODULE module; + ::GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCSTR)&MGG_EffectResource_GetBytecode, &module); + + LPCSTR id = ""; + + if (strcmp(name, "AlphaTestEffect") == 0) + id = MAKEINTRESOURCEA(C_AlphaTestEffect); + else if (strcmp(name, "BasicEffect") == 0) + id = MAKEINTRESOURCEA(C_BasicEffect); + else if (strcmp(name, "DualTextureEffect") == 0) + id = MAKEINTRESOURCEA(C_DualTextureEffect); + else if (strcmp(name, "EnvironmentMapEffect") == 0) + id = MAKEINTRESOURCEA(C_EnvironmentMapEffect); + else if (strcmp(name, "SkinnedEffect") == 0) + id = MAKEINTRESOURCEA(C_SkinnedEffect); + else if (strcmp(name, "SpriteEffect") == 0) + id = MAKEINTRESOURCEA(C_SpriteEffect); + + auto handle = ::FindResourceA(module, id, "BIN"); + if (handle == nullptr) + return; + + size = ::SizeofResource(module, handle); + if (size == 0) + return; + + HGLOBAL global = ::LoadResource(module, handle); + if (global == nullptr) + return; + + bytecode = (mgbyte*)LockResource(global); +} + +uint64_t CheckValidationLayerSupport(const std::vector& validationLayers) +{ + uint32_t layerCount; + vkEnumerateInstanceLayerProperties(&layerCount, nullptr); + + std::vector availableLayers(layerCount); + vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); + + uint64_t found = 0; + + for (int i = 0; i < validationLayers.size(); i++) + { + const char* layerName = validationLayers[i]; + + for (const auto& layerProperties : availableLayers) + { + if (strcmp(layerName, layerProperties.layerName) == 0) + { + found |= ((uint64_t)1) << i; + break; + } + } + } + + return found; +} +MGG_GraphicsSystem* MGG_GraphicsSystem_Create() +{ + auto err = volkInitialize(); + if (err != VK_SUCCESS) + { + printf("Failed to initialize volk!"); + return nullptr; + } + + VkApplicationInfo app_info = { VK_STRUCTURE_TYPE_APPLICATION_INFO }; + app_info.pNext = nullptr; + app_info.apiVersion = VK_API_VERSION_1_0; + + // TODO: pass these thru from C# is more flexible! + app_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0); + app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0); + app_info.pApplicationName = "Unknown"; + app_info.pEngineName = "MonoGame"; + + std::vector instanceExtensions; +#if defined(MG_SDL2) + { + uint32_t count; + SDL_Vulkan_GetInstanceExtensions(nullptr, &count, nullptr); + instanceExtensions.resize(count); + + SDL_Vulkan_GetInstanceExtensions(nullptr, &count, instanceExtensions.data()); + } +#else +#error Not Implemented! +#endif + instanceExtensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); + + std::vector enabledLayers; + enabledLayers.push_back("VK_LAYER_KHRONOS_validation"); + //enabledLayers.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); + CheckValidationLayerSupport(enabledLayers); + + VkInstanceCreateInfo instance_create_info = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO }; + instance_create_info.pApplicationInfo = &app_info; + instance_create_info.enabledExtensionCount = instanceExtensions.size(); + instance_create_info.ppEnabledExtensionNames = instanceExtensions.data(); + instance_create_info.enabledLayerCount = enabledLayers.size(); + instance_create_info.ppEnabledLayerNames = enabledLayers.data(); + instance_create_info.pNext = nullptr; + + VkInstance instance = VK_NULL_HANDLE; + + err = vkCreateInstance(&instance_create_info, nullptr, &instance); + if (err != VK_SUCCESS) + { + printf("Failed to create Vulkan instance!"); + return nullptr; + } + + volkLoadInstance(instance); + + auto system = new MGG_GraphicsSystem(); + system->instance = instance; + + // Gather the physical devices. + { + uint32_t count = 0; + VkResult res = vkEnumeratePhysicalDevices(system->instance, &count, NULL); + if (res == VK_SUCCESS) + { + VkPhysicalDevice* gpus = (VkPhysicalDevice*)calloc(count, sizeof(*gpus)); + + res = vkEnumeratePhysicalDevices(system->instance, &count, gpus); + if (res == VK_SUCCESS) + { + for (uint32_t i = 0; i < count; ++i) + { + auto adapter = new MGG_GraphicsAdapter(); + adapter->device = gpus[i]; + + vkGetPhysicalDeviceProperties(adapter->device, &adapter->properties); + vkGetPhysicalDeviceFeatures(adapter->device, &adapter->features); + vkGetPhysicalDeviceMemoryProperties(adapter->device, &adapter->memory); + + system->adapters.push_back(adapter); + } + } + + free((void*)gpus); + } + } + + return system; +} + +void MGG_GraphicsSystem_Destroy(MGG_GraphicsSystem* system) +{ + assert(system != nullptr); + + MG_NOT_IMPLEMEMTED; +} + +MGG_GraphicsAdapter* MGG_GraphicsAdapter_Get(MGG_GraphicsSystem* system, mgint index) +{ + if (index < 0 || index >= system->adapters.size()) + return nullptr; + + return system->adapters[index]; +} + +void MGG_GraphicsAdapter_GetInfo(MGG_GraphicsAdapter* adapter, MGG_GraphicsAdaptor_Info& info) +{ + assert(adapter != nullptr); + + info.DeviceName = adapter->properties.deviceName; + info.DeviceId = adapter->properties.deviceID; + info.Revision = adapter->properties.driverVersion; + info.VendorId = adapter->properties.vendorID; + + // TODO: Should we be generating a description? + // Is there a description somewhere for us to get? + static const char* description = ""; + info.Description = (void*)description; + + info.SubSystemId = 0; + info.MonitorHandle = 0; + +#ifdef _WIN32 + + HMONITOR primaryMonitor = MonitorFromPoint(POINT{ 0, 0 }, MONITOR_DEFAULTTOPRIMARY); + info.MonitorHandle = primaryMonitor; + + MONITORINFOEX monitorInfo; + monitorInfo.cbSize = sizeof(MONITORINFOEX); + GetMonitorInfo(primaryMonitor, &monitorInfo); + + if (adapter->modes.size() == 0) + { + // TODO: There is probably a better way to do all this + // but this works for our current case. + // + // Like shouldn't this be per-graphics device/adapter? + // + // What about the color format? Does it matter in 2024? + // + + DEVMODE devMode; + devMode.dmSize = sizeof(DEVMODE); + + int count = 0; + + while (EnumDisplaySettings(monitorInfo.szDevice, count, &devMode)) + { + MGG_DisplayMode mode; + mode.width = devMode.dmPelsWidth; + mode.height = devMode.dmPelsHeight; + mode.format = MGSurfaceFormat::Color; + + bool found = false; + for (auto m : adapter->modes) + { + if (m.width == mode.width && + m.height == mode.height) + { + found = true; + break; + } + } + + if (!found) + adapter->modes.push_back(mode); + + count++; + } + } + + info.DisplayModeCount = adapter->modes.size(); + info.DisplayModes = adapter->modes.data(); + + info.CurrentDisplayMode.width = monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left; + info.CurrentDisplayMode.height = monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top; + info.CurrentDisplayMode.format = MGSurfaceFormat::Color; + +#else +#error NOT IMPLEMENTED! +#endif +} + +static void mggCreateImage(MGG_GraphicsDevice* device, VkImageCreateInfo* info, MGG_Texture* texture) +{ + VmaAllocationCreateInfo allocInfo = {}; + allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; + VkResult res = vmaCreateImage(device->allocator, info, &allocInfo, &texture->image, &texture->allocation, nullptr); + VK_CHECK_RESULT(res); +} + +static MGG_Texture* CreateDepthTexture(MGG_GraphicsDevice* device, VkFormat format, uint32_t width, uint32_t height) +{ + // TODO: Could convert this into a + // general image creation method. + + MGG_Texture* texture = new MGG_Texture; + memset(texture, 0, sizeof(MGG_Texture)); + + VkImageCreateInfo& create_info = texture->info; + create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + create_info.imageType = VK_IMAGE_TYPE_2D; + create_info.format = format; + create_info.extent = { width, height, 1 }; + create_info.mipLevels = 1; + create_info.arrayLayers = 1; + create_info.samples = VK_SAMPLE_COUNT_1_BIT; + create_info.tiling = VK_IMAGE_TILING_OPTIMAL; + create_info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; + create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + + texture->layout = VK_IMAGE_LAYOUT_UNDEFINED; + texture->optimal_layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + + mggCreateImage(device, &create_info, texture); + + MGVK_TransitionImageLayout(device, texture, 0, texture->optimal_layout); + + return texture; +} + +static VkImageView CreateImageView(MGG_GraphicsDevice* device, MGG_Texture* texture, uint32_t level_count) +{ + VkFormat format = texture->info.format; + uint32_t layer_count = texture->info.arrayLayers; + + VkImageAspectFlags aspect_mask = DetermineAspectMask(format); + + VkImageViewCreateInfo image_view_create_info = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO }; + image_view_create_info.image = texture->image; + image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + image_view_create_info.format = format; + image_view_create_info.subresourceRange.aspectMask = aspect_mask; + image_view_create_info.subresourceRange.baseMipLevel = 0; + image_view_create_info.subresourceRange.levelCount = level_count; + image_view_create_info.subresourceRange.baseArrayLayer = 0; + image_view_create_info.subresourceRange.layerCount = layer_count; + + VkImageView view; + VkResult res = vkCreateImageView(device->device, &image_view_create_info, NULL, &view); + VK_CHECK_RESULT(res); + + return view; +} + +static void MGVK_BufferCreate(MGG_GraphicsDevice* device, int sizeInBytes, VkBufferUsageFlags usage, VmaMemoryUsage flags, MGG_Buffer* buffer) +{ + VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; + bufferInfo.size = sizeInBytes; + bufferInfo.usage = usage; + bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + VmaAllocationCreateInfo allocInfo = {}; + allocInfo.usage = flags; + + VkResult res = vmaCreateBuffer(device->allocator, &bufferInfo, &allocInfo, &buffer->buffer, &buffer->allocation, nullptr); + VK_CHECK_RESULT(res); +} + +static VkBufferUsageFlags ToUsage(MGBufferType type) +{ + VkBufferUsageFlags usage; + switch (type) + { + case MGBufferType::Index: + return VK_BUFFER_USAGE_INDEX_BUFFER_BIT; + break; + case MGBufferType::Vertex: + return VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; + break; + case MGBufferType::Constant: + return VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; + break; + default: + assert(0); + } +} + +static VkCommandBuffer MGVK_BeginNewCommandBuffer(MGG_GraphicsDevice* device) +{ + VkCommandBufferAllocateInfo allocInfo = {}; + allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + allocInfo.commandPool = device->cmdPool; + allocInfo.commandBufferCount = 1; + + VkCommandBuffer commandBuffer; + vkAllocateCommandBuffers(device->device, &allocInfo, &commandBuffer); + + VkCommandBufferBeginInfo beginInfo = {}; + beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + + vkBeginCommandBuffer(commandBuffer, &beginInfo); + + return commandBuffer; +} + +static void MGVK_ExecuteAndFreeCommandBuffer(MGG_GraphicsDevice* device, VkCommandBuffer commandBuffer) +{ + vkEndCommandBuffer(commandBuffer); + + VkFence renderFence; + { + VkFenceCreateInfo fenceCreateInfo = {}; + fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + fenceCreateInfo.flags = 0; + vkCreateFence(device->device, &fenceCreateInfo, nullptr, &renderFence); + } + + VkSubmitInfo submitInfo = {}; + submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submitInfo.commandBufferCount = 1; + submitInfo.pCommandBuffers = &commandBuffer; + + vkQueueSubmit(device->queue, 1, &submitInfo, renderFence); + //vkQueueWaitIdle(device->queue); + + vkWaitForFences(device->device, 1, &renderFence, VK_TRUE, UINT64_MAX); + + vkDestroyFence(device->device, renderFence, nullptr); + + vkFreeCommandBuffers(device->device, device->cmdPool, 1, &commandBuffer); +} + +static void MGVK_CopyBufferToImage(MGG_GraphicsDevice* device, VkBuffer buffer, VkImage image, int32_t x, int32_t y, int32_t level, uint32_t width, uint32_t height) +{ + VkCommandBuffer cmds = MGVK_BeginNewCommandBuffer(device); + + VkBufferImageCopy region = {}; + region.bufferOffset = 0; + region.bufferRowLength = 0; + region.bufferImageHeight = 0; + + region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + region.imageSubresource.mipLevel = level; + region.imageSubresource.baseArrayLayer = 0; + region.imageSubresource.layerCount = 1; + + region.imageOffset = { x, y, 0 }; + region.imageExtent = { width, height, 1 }; + + vkCmdCopyBufferToImage(cmds, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion); + + MGVK_ExecuteAndFreeCommandBuffer(device, cmds); +} + +static void MGVK_CopyImageToBuffer(MGG_GraphicsDevice* device, VkImage image, VkBuffer buffer, int32_t x, int32_t y, int32_t level, uint32_t width, uint32_t height) +{ + VkCommandBuffer cmds = MGVK_BeginNewCommandBuffer(device); + + VkBufferImageCopy region = {}; + region.bufferOffset = 0; + region.bufferRowLength = 0; + region.bufferImageHeight = 0; + + region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + region.imageSubresource.mipLevel = level; + region.imageSubresource.baseArrayLayer = 0; + region.imageSubresource.layerCount = 1; + + region.imageOffset = { x, y, level }; + region.imageExtent = { width, height, 1 }; + + vkCmdCopyImageToBuffer(cmds, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buffer, 1, ®ion); + + MGVK_ExecuteAndFreeCommandBuffer(device, cmds); +} + +MGG_GraphicsDevice* MGG_GraphicsDevice_Create(MGG_GraphicsSystem* system, MGG_GraphicsAdapter* adapter) +{ + assert(system != nullptr); + assert(adapter != nullptr); + + auto device = new MGG_GraphicsDevice(); + + device->instance = system->instance; + device->physicalDevice = adapter->device; + + // Capture some needed limits. + device->minUniformBufferOffsetAlignment = adapter->properties.limits.minUniformBufferOffsetAlignment; + + uint32_t queueFamilyCount; + vkGetPhysicalDeviceQueueFamilyProperties(device->physicalDevice, &queueFamilyCount, nullptr); + assert(queueFamilyCount > 0); + + VkQueueFamilyProperties* queueFamilyProps = new VkQueueFamilyProperties[queueFamilyCount]; + uint32_t queueFamilyIndex = 0; + { + vkGetPhysicalDeviceQueueFamilyProperties(device->physicalDevice, &queueFamilyCount, queueFamilyProps); + + for (int i = 0; i < queueFamilyCount; i++) + { + if ((queueFamilyProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) + { + queueFamilyIndex = i; + break; + } + } + } + + int queueCreateInfoCount = 0; + VkDeviceQueueCreateInfo* queueCreateInfos = new VkDeviceQueueCreateInfo[queueFamilyCount]; + memset(queueCreateInfos, 0, sizeof(VkDeviceQueueCreateInfo) * queueFamilyCount); + + for (int i = 0; i < queueFamilyCount; i++) + { + const VkQueueFamilyProperties* properties = queueFamilyProps + i; + float* queuePriorities = new float[properties->queueCount]; + + for (int j = 0; j < properties->queueCount; ++j) + queuePriorities[j] = 1.0f; + + queueCreateInfos[i].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + queueCreateInfos[i].queueFamilyIndex = i; + queueCreateInfos[i].queueCount = 1; + queueCreateInfos[i].pQueuePriorities = queuePriorities; + ++queueCreateInfoCount; + } + assert(queueFamilyCount == queueCreateInfoCount); + + std::vector extensions; + extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); + extensions.push_back(VK_EXT_CUSTOM_BORDER_COLOR_EXTENSION_NAME); + + VkPhysicalDeviceCustomBorderColorFeaturesEXT customBorderColorFeatures = {}; + customBorderColorFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT; + customBorderColorFeatures.customBorderColors = VK_TRUE; + customBorderColorFeatures.customBorderColorWithoutFormat = VK_TRUE; + + VkPhysicalDeviceFeatures2 deviceFeatures2 = {}; + deviceFeatures2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; + deviceFeatures2.pNext = &customBorderColorFeatures; + deviceFeatures2.features = device->deviceFeatures; + + VkDeviceCreateInfo deviceCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO }; + deviceCreateInfo.queueCreateInfoCount = queueCreateInfoCount; + deviceCreateInfo.pQueueCreateInfos = queueCreateInfos; + deviceCreateInfo.enabledExtensionCount = extensions.size(); + deviceCreateInfo.ppEnabledExtensionNames = extensions.data(); + deviceCreateInfo.pEnabledFeatures = nullptr; + deviceCreateInfo.pNext = &deviceFeatures2; + + auto res = vkCreateDevice(device->physicalDevice, &deviceCreateInfo, NULL, &device->device); + VK_CHECK_RESULT(res); + + VmaAllocatorCreateInfo allocatorInfo = {}; + allocatorInfo.instance = system->instance; + allocatorInfo.physicalDevice = device->physicalDevice; + allocatorInfo.device = device->device; + vmaCreateAllocator(&allocatorInfo, &device->allocator); + + vkGetDeviceQueue(device->device, queueFamilyIndex, 0, &device->queue); + + VkCommandPoolCreateInfo cmdPoolInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO }; + cmdPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + cmdPoolInfo.queueFamilyIndex = queueFamilyIndex; + res = vkCreateCommandPool(device->device, &cmdPoolInfo, nullptr, &device->cmdPool); + VK_CHECK_RESULT(res); + + VkCommandBufferAllocateInfo comBufferInfo = + { + VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, + NULL, + device->cmdPool, + VK_COMMAND_BUFFER_LEVEL_PRIMARY, + 1 + }; + + device->frames = new MGVK_FrameState[kConcurrentFrameCount]; + memset(device->frames, 0, sizeof(MGVK_FrameState) * kConcurrentFrameCount); + + for (int i = 0; i < kConcurrentFrameCount; i++) + { + MGVK_CmdBuffer& cmd = device->frames[i].commandBuffer; + + res = vkAllocateCommandBuffers(device->device, &comBufferInfo, &cmd.buffer); + VK_CHECK_RESULT(res); + + VkSemaphoreCreateInfo semaphore_create_info = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO }; + res = vkCreateSemaphore(device->device, &semaphore_create_info, NULL, &cmd.imageAcquiredSemaphore); + VK_CHECK_RESULT(res); + res = vkCreateSemaphore(device->device, &semaphore_create_info, NULL, &cmd.renderCompleteSemaphore); + VK_CHECK_RESULT(res); + + VkFenceCreateInfo fence_create_info = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO }; + fence_create_info.flags = VK_FENCE_CREATE_SIGNALED_BIT; + res = vkCreateFence(device->device, &fence_create_info, NULL, &cmd.completedFence); + VK_CHECK_RESULT(res); + } + + // Create the pipeline cache which is used at runtime + // to speed up pipeline creation. + VkPipelineCacheCreateInfo pipelineCache{ VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO }; + pipelineCache.pNext = NULL; + pipelineCache.initialDataSize = 0; + pipelineCache.pInitialData = NULL; + pipelineCache.flags = 0; + res = vkCreatePipelineCache(device->device, &pipelineCache, nullptr, &device->pipelineCache); + VK_CHECK_RESULT(res); + + //res = vkDeviceWaitIdle(device->device); + //VK_CHECK_RESULT(res); + // + // Initialize all the device state. + device->scissorDirty = true; + device->uniformsDirty = 0xFFFFFFFF; + device->textureSamplerDirty = 0xFFFFFFFF; + device->vertexBuffersDirty = 0xFFFFFFFF; + device->pipelineStateDirty = true; + device->currentTextureId = 1; + device->currentSamplerId = 1; + device->blendFactorDirty = true; + device->renderTargetDirty = true; + device->inRenderPass = false; + device->blendFactor[0] = device->blendFactor[1] = device->blendFactor[2] = device->blendFactor[3] = 1; + memset(device->descriptorSets, 0, sizeof(device->descriptorSets)); + memset(device->dynamicOffsets, 0, sizeof(device->dynamicOffsets)); + memset(device->vertexBuffers, 0, sizeof(device->vertexBuffers)); + memset(device->vertexOffsets, 0, sizeof(device->vertexOffsets)); + memset(device->uniforms, 0, sizeof(device->uniforms)); + memset(device->textures, 0, sizeof(device->textures)); + memset(device->samplers, 0, sizeof(device->samplers)); + + return device; +} + +static void cleanupSwapChain(MGG_GraphicsDevice* device) +{ + vkQueueWaitIdle(device->queue); + + // Destroy all the frame resources. + + + // Destroy all frame buffers. + for (auto pair : device->targetCache) + { + vkDestroyRenderPass(device->device, pair.second->renderPass, nullptr); + vkDestroyFramebuffer(device->device, pair.second->framebuffer, nullptr); + delete pair.second; + } + device->targetCache.clear(); + + // Cleanup the swap chain images. + for (size_t i = 0; i < kConcurrentFrameCount; i++) + { + auto chain = device->frames[i].swapchainTexture; + if (chain == nullptr) + continue; + + vkDestroyImageView(device->device, chain->target_view, nullptr); + //vkDestroyImage(device->device, chain->image, nullptr); + //vmaFreeMemory(device->allocator, chain->allocation); + + chain->target_view = VK_NULL_HANDLE; + chain->image = VK_NULL_HANDLE; + chain->allocation = nullptr; + + if (chain->depthTexture != nullptr) + { + vkDestroyImageView(device->device, chain->depthTexture->target_view, nullptr); + vmaDestroyImage(device->allocator, chain->depthTexture->image, chain->depthTexture->allocation); + delete chain->depthTexture; + + chain->depthTexture = nullptr; + } + + delete chain; + device->frames[i].swapchainTexture = nullptr; + } + + if (device->swapchain != VK_NULL_HANDLE) + { + vkDestroySwapchainKHR(device->device, device->swapchain, nullptr); + device->swapchain = VK_NULL_HANDLE; + } +} + +void MGG_GraphicsDevice_Destroy(MGG_GraphicsDevice* device) +{ + assert(device != nullptr); + + cleanupSwapChain(device); + + for (auto pair : device->shader_programs) + { + vkDestroyPipelineLayout(device->device, pair.second->layout, nullptr); + delete pair.second; + } + device->shader_programs.clear(); + + vkDestroyPipelineCache(device->device, device->pipelineCache, nullptr); + + while (device->all_buffers.size() > 0) + MGG_Buffer_Destroy(device, device->all_buffers[0]); + + for (size_t i = 0; i < kConcurrentFrameCount; i++) + { + auto cmd = device->frames[i].commandBuffer; + + vkDestroySemaphore(device->device, cmd.imageAcquiredSemaphore, nullptr); + vkDestroySemaphore(device->device, cmd.renderCompleteSemaphore, nullptr); + vkDestroyFence(device->device, cmd.completedFence, nullptr); + } + + vkDestroyCommandPool(device->device, device->cmdPool, nullptr); + + for (size_t i = 0; i < kConcurrentFrameCount; i++) + MGVK_DestroyFrameResources(device, i, true); + + vmaDestroyAllocator(device->allocator); + + vkDestroyDevice(device->device, nullptr); + + delete device; +} + +void MGG_GraphicsDevice_GetCaps(MGG_GraphicsDevice* device, MGG_GraphicsDevice_Caps& caps) +{ + assert(device != nullptr); + + // TODO: Get actual stats from the device! + + caps.MaxTextureSlots = 16; + caps.MaxVertexBufferSlots = 8; + caps.MaxVertexTextureSlots = 8; + + // Vulkan shader profile from pipeline. + caps.ShaderProfile = 80; +} + +void MGVK_RecreateSwapChain( + MGG_GraphicsDevice* device, + void* nativeWindowHandle, + mgint width, + mgint height, + VkFormat vkColor, + VkFormat vkDepth) +{ + assert(device != nullptr); + assert(nativeWindowHandle != nullptr); + + // Be sure we're done drawing. + vkDeviceWaitIdle(device->device); + + VkResult res; + + // Create the surface. +#if defined(MG_SDL2) + auto sdl_window = (SDL_Window*)nativeWindowHandle; + if (sdl_window != device->window) + { + cleanupSwapChain(device); + + if (device->surface != nullptr) + vkDestroySurfaceKHR(device->instance, device->surface, nullptr); + + SDL_Vulkan_CreateSurface(sdl_window, device->instance, &device->surface); + + device->window = sdl_window; + } +#else +#error Not Implemented +#endif + + if (width == device->swapchainWidth && + height == device->swapchainHeight && + vkColor == device->colorFormat && + vkDepth == device->depthFormat && + device->swapchain != VK_NULL_HANDLE) + return; + + cleanupSwapChain(device); + + device->swapchainWidth = width; + device->swapchainHeight = height; + device->colorFormat = vkColor; + device->depthFormat = vkDepth; + + { + VkSurfaceCapabilitiesKHR surface_capabilities; + res = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device->physicalDevice, device->surface, &surface_capabilities); + VK_CHECK_RESULT(res); + + VkFormat surface_format = VK_FORMAT_UNDEFINED; + uint32_t format_count = 0; + res = vkGetPhysicalDeviceSurfaceFormatsKHR(device->physicalDevice, device->surface, &format_count, nullptr); + VK_CHECK_RESULT(res); + + VkSurfaceFormatKHR* surfFormats = new VkSurfaceFormatKHR[format_count]; + res = vkGetPhysicalDeviceSurfaceFormatsKHR(device->physicalDevice, device->surface, &format_count, surfFormats); + VK_CHECK_RESULT(res); + + surface_format = surfFormats[0].format; + if ((1 == format_count) && (VK_FORMAT_UNDEFINED == surfFormats[0].format)) + surface_format = VK_FORMAT_B8G8R8A8_UNORM; + + VkSurfaceCapabilitiesKHR surface_caps; + res = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device->physicalDevice, device->surface, &surface_caps); + VK_CHECK_RESULT(res); + + device->colorFormat = surface_format; + + delete[] surfFormats; + } + + // Requested swapchain extent will be clamped based on the surface's min/max extent. + // In most cases these will match the current extent, as specified at window/surface creation time. + VkExtent2D extent; + extent.width = device->swapchainWidth; + extent.height = device->swapchainHeight; + + /* + VkSwapchainPresentScalingCreateInfoEXT scalingCreateInfo = {}; + scalingCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_SCALING_CREATE_INFO_EXT; + scalingCreateInfo.scalingBehavior = VK_PRESENT_SCALING_ASPECT_RATIO_STRETCH_BIT_EXT | VK_PRESENT_SCALING_STRETCH_BIT_EXT; + scalingCreateInfo.presentGravityX = VK_PRESENT_GRAVITY_CENTERED_BIT_EXT; + scalingCreateInfo.presentGravityY = VK_PRESENT_GRAVITY_CENTERED_BIT_EXT; + */ + + VkSwapchainCreateInfoKHR create_info = { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR }; + create_info.surface = device->surface; + create_info.minImageCount = kConcurrentFrameCount; + create_info.imageFormat = device->colorFormat; + create_info.imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; + create_info.imageExtent = extent; + create_info.imageArrayLayers = 1; + create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; + create_info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + create_info.presentMode = VK_PRESENT_MODE_MAILBOX_KHR; + create_info.clipped = true; + //create_info.pNext = &scalingCreateInfo; + res = vkCreateSwapchainKHR(device->device, &create_info, nullptr, &device->swapchain); + VK_CHECK_RESULT(res); + + uint32_t swapchainCount = 0; + res = vkGetSwapchainImagesKHR(device->device, device->swapchain, &swapchainCount, NULL); + VK_CHECK_RESULT(res); + + VkImage* swapchainImages = new VkImage[swapchainCount]; + res = vkGetSwapchainImagesKHR(device->device, device->swapchain, &swapchainCount, swapchainImages); + VK_CHECK_RESULT(res); + + for (uint32_t i = 0; i < swapchainCount; ++i) + { + VkImageCreateInfo image_create_info = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; + image_create_info.imageType = VK_IMAGE_TYPE_2D; + image_create_info.format = device->colorFormat; + image_create_info.extent = { device->swapchainWidth, device->swapchainHeight, 1 }; + image_create_info.mipLevels = 1; + image_create_info.arrayLayers = 1; + image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_create_info.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_create_info.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + MGG_Texture* texture = new MGG_Texture; + memset(texture, 0, sizeof(MGG_Texture)); + + VkMemoryRequirements memory_requirements = { 0 }; + vkGetImageMemoryRequirements(device->device, swapchainImages[i], &memory_requirements); + + texture->info = image_create_info; + texture->image = swapchainImages[i]; + texture->isSwapchain = texture->isTarget = true; + + texture->target_view = CreateImageView(device, texture, 1); + + if (device->depthFormat != VK_FORMAT_UNDEFINED) + { + texture->depthTexture = CreateDepthTexture(device, device->depthFormat, texture->info.extent.width, texture->info.extent.height); + texture->depthTexture->target_view = CreateImageView(device, texture->depthTexture, 1); + } + + device->frames[i].swapchainTexture = texture; + } + + delete[] swapchainImages; +} + +void MGVK_RecreateSwapChain(MGG_GraphicsDevice* device) +{ + cleanupSwapChain(device); + + MGVK_RecreateSwapChain( + device, + device->window, + device->swapchainWidth, + device->swapchainHeight, + device->colorFormat, + device->depthFormat); + + MGG_GraphicsDevice_SetRenderTargets(device, nullptr, 0); +} + +void MGG_GraphicsDevice_ResizeSwapchain( + MGG_GraphicsDevice* device, + void* nativeWindowHandle, + mgint width, + mgint height, + MGSurfaceFormat color, + MGDepthFormat depth) +{ + auto vkColor = ToVkFormat(color); + auto vkDepth = ToVkFormat(depth); + + MGVK_RecreateSwapChain(device, nativeWindowHandle, width, height, vkColor, vkDepth); +} + + +static void MGVK_ProcessDescriptorCaches(MGG_GraphicsDevice* device, FrameCounter currentFrame) +{ + // Here we go thru the shaders and move any + // descriptors that haven't been used in a few + // frames to the correct free list. + + // TODO: This could be a ton of iteration. + // Maybe keep a list of recently used shaders + // or descriptors and only process those? + + auto shader = device->all_shaders.begin(); + for (; shader != device->all_shaders.end(); shader++) + { + auto& usedSets = (*shader)->usedSets; + auto& freeSets = (*shader)->freeSets; + + auto pair = usedSets.begin(); + for (; pair != usedSets.end();) + { + auto diff = currentFrame - pair->second->frame; + if (diff < kFreeFrames || (0xFFFF - diff) < kFreeFrames) + { + pair++; + continue; + } + + freeSets.push(pair->second); + pair = usedSets.erase(pair); + } + } +} + +void MGVK_BeginFrame(MGVK_CmdBuffer& cmd) +{ + VkCommandBufferBeginInfo beginInfo = + { + VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, + NULL, + VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT, + NULL + }; + + auto res = vkResetCommandBuffer(cmd.buffer, VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT); + VK_CHECK_RESULT(res); + res = vkBeginCommandBuffer(cmd.buffer, &beginInfo); + VK_CHECK_RESULT(res); + + //vkCmdSetDepthClampEnableEXT(cmd.buffer, VK_TRUE); +} + +mgint MGG_GraphicsDevice_BeginFrame(MGG_GraphicsDevice* device) +{ + assert(device != nullptr); + + VkResult res; + + const FrameCounter currentFrame = device->frame; + const FrameCounter frameIndex = currentFrame % kConcurrentFrameCount; + MGVK_FrameState& frame = device->frames[frameIndex]; + MGVK_CmdBuffer& cmd = frame.commandBuffer; + + MGVK_ProcessDescriptorCaches(device, currentFrame); + + res = vkWaitForFences(device->device, 1, &cmd.completedFence, VK_TRUE, UINT64_MAX); + VK_CHECK_RESULT(res); + res = vkResetFences(device->device, 1, &cmd.completedFence); + VK_CHECK_RESULT(res); + + device->swapchain_image_index = 0; + res = vkAcquireNextImageKHR(device->device, device->swapchain, UINT64_MAX, + cmd.imageAcquiredSemaphore, VK_NULL_HANDLE, &device->swapchain_image_index); + VK_CHECK_RESULT(res); + + frame.uniformOffset = 0; + if (frame.uniforms == NULL) + frame.uniforms = MGVK_Buffer_Create(device, MGBufferType::Constant, 4 * 1024 * 1024, true); + + MGVK_BeginFrame(cmd); + + //device->dynamicOffsets[0] = 0; + //device->dynamicOffsets[1] = 0; + + frame.is_recording = true; + + return frameIndex; +} + +void MGG_GraphicsDevice_Clear(MGG_GraphicsDevice* device, MGClearOptions options, Vector4& color, mgfloat depth, mgint stencil) +{ + assert(device != nullptr); + + // Make sure something was set to be cleared. + if ((mgint)options == 0) + return; + + auto currentFrame = device->frame; + auto frameIndex = currentFrame % kConcurrentFrameCount; + auto& frame = device->frames[frameIndex]; + auto& cmd = frame.commandBuffer; + assert(frame.is_recording); + + MGVK_UpdateRenderPass(device, currentFrame, cmd); + + int num_attachments = 0; + + VkClearAttachment attachments[5]; + memset(attachments, 0, sizeof(attachments)); + + auto targets = device->pipelineState.targets; + + if (((int)options & (int)MGClearOptions::Target) != 0) + { + for (int i = 0; i < targets->set.numTargets; i++) + { + VkClearAttachment* attachment = &attachments[num_attachments]; + attachment->aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + attachment->colorAttachment = num_attachments; + attachment->clearValue.color.float32[0] = color.X; + attachment->clearValue.color.float32[1] = color.Y; + attachment->clearValue.color.float32[2] = color.Z; + attachment->clearValue.color.float32[3] = color.W; + num_attachments++; + } + } + + bool clearDepth = ((int)options & (int)MGClearOptions::DepthBuffer) != 0; + bool clearStencil = ((int)options & (int)MGClearOptions::Stencil) != 0; + if (clearDepth || clearStencil) + { + VkClearAttachment* attachment = &attachments[num_attachments++]; + + if (clearDepth) + attachment->aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT; + if (clearStencil) + attachment->aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT; + + attachment->clearValue.depthStencil.depth = depth; + attachment->clearValue.depthStencil.stencil = stencil; + } + + VkClearRect rect; + rect.rect.offset.x = 0; + rect.rect.offset.y = 0; + rect.baseArrayLayer = 0; + rect.layerCount = 1; + + // Clear always clears the entire target. + rect.rect.extent.width = targets->width; + rect.rect.extent.height = targets->height; + + vkCmdClearAttachments(cmd.buffer, num_attachments, attachments, 1, &rect); +} + +static void MGVK_DestroyTargetSets(MGG_GraphicsDevice* device, std::function compare) +{ + auto& cache = device->targetCache; + auto itr = cache.cbegin(); + + while (itr != cache.cend()) + { + if (!compare(itr->second)) + itr++; + else + { + vkDestroyFramebuffer(device->device, itr->second->framebuffer, nullptr); + vkDestroyRenderPass(device->device, itr->second->renderPass, nullptr); + delete itr->second; + cache.erase(itr++); + } + } +} + +static void MGVK_DestroyPipelines(MGG_GraphicsDevice* device, std::function compare) +{ + auto& pipelines = device->pipelines; + auto itr = pipelines.cbegin(); + + while (itr != pipelines.cend()) + { + if (!compare(itr->second.state)) + itr++; + else + { + vkDestroyPipeline(device->device, itr->second.cache, nullptr); + pipelines.erase(itr++); + } + } +} + +static void MGVK_DestroyFrameResources(MGG_GraphicsDevice* device, mgint currentFrame, mgbool free_all) +{ + assert(device != nullptr); + assert(currentFrame >= 0); + + auto frameIndex = currentFrame % kConcurrentFrameCount; + auto& frame = device->frames[frameIndex]; + + // Delete resources that haven't been used in a few frames + { + while (device->destroyBuffers.size() > 0) + { + auto buffer = device->destroyBuffers.front(); + auto diff = currentFrame - buffer->frame; + if (!free_all && diff < kFreeFrames || (0xFFFF - diff) < kFreeFrames) + break; + + device->destroyBuffers.pop(); + vmaDestroyBuffer(device->allocator, buffer->buffer, buffer->allocation); + delete buffer; + } + + while (device->destroyTextures.size() > 0) + { + auto texture = device->destroyTextures.front(); + auto diff = currentFrame - texture->frame; + if (!free_all && diff < kFreeFrames || (0xFFFF - diff) < kFreeFrames) + break; + + device->destroyTextures.pop(); + + if (texture->isTarget) + { + MGVK_DestroyPipelines(device, [texture](const MGVK_PipelineState& s) + { + return s.targets->set.targets[0] == texture || + s.targets->set.targets[1] == texture || + s.targets->set.targets[2] == texture || + s.targets->set.targets[3] == texture; + }); + + MGVK_DestroyTargetSets(device, [texture](const MGVK_TargetSetCache* s) + { + return s->set.targets[0] == texture || + s->set.targets[1] == texture || + s->set.targets[2] == texture || + s->set.targets[3] == texture; + }); + } + + if (texture->target_view != VK_NULL_HANDLE) + vkDestroyImageView(device->device, texture->target_view, nullptr); + if (texture->view != VK_NULL_HANDLE) + vkDestroyImageView(device->device, texture->view, nullptr); + + vmaDestroyImage(device->allocator, texture->image, texture->allocation); + delete texture; + } + + while (device->destroyBlendStates.size() > 0) + { + auto state = device->destroyBlendStates.front(); + auto diff = currentFrame - state->frame; + if (!free_all && diff < kFreeFrames || (0xFFFF - diff) < kFreeFrames) + break; + + device->destroyBlendStates.pop(); + + MGVK_DestroyPipelines(device, [state](const MGVK_PipelineState& s) { return s.blendState == state; }); + delete state; + } + + while (device->destroyRasterizerStates.size() > 0) + { + auto state = device->destroyRasterizerStates.front(); + auto diff = currentFrame - state->frame; + if (!free_all && diff < kFreeFrames || (0xFFFF - diff) < kFreeFrames) + break; + + device->destroyRasterizerStates.pop(); + + MGVK_DestroyPipelines(device, [state](const MGVK_PipelineState& s) { return s.rasterizerState == state; }); + delete state; + } + + while (device->destroyDepthStencilStates.size() > 0) + { + auto state = device->destroyDepthStencilStates.front(); + auto diff = currentFrame - state->frame; + if (!free_all && diff < kFreeFrames || (0xFFFF - diff) < kFreeFrames) + break; + + device->destroyDepthStencilStates.pop(); + + MGVK_DestroyPipelines(device, [state](const MGVK_PipelineState& s) { return s.depthStencilState == state; }); + delete state; + } + } +} + +void MGG_GraphicsDevice_Present(MGG_GraphicsDevice* device, mgint currentFrame, mgint syncInterval) +{ + assert(device != nullptr); + assert(syncInterval >= 0); + assert(currentFrame >= 0); + assert((device->frame % kConcurrentFrameCount) == currentFrame); + + auto frameIndex = currentFrame % kConcurrentFrameCount; + auto& frame = device->frames[frameIndex]; + assert(frame.is_recording); + + auto& cmd = frame.commandBuffer; + + if (device->inRenderPass) + { + vkCmdEndRenderPass(cmd.buffer); + device->inRenderPass = false; + } + + VkResult res = vkEndCommandBuffer(cmd.buffer); + VK_CHECK_RESULT(res); + + VkPipelineStageFlags wait_dst_stage_mask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO }; + submitInfo.waitSemaphoreCount = 1; + submitInfo.pWaitSemaphores = &cmd.imageAcquiredSemaphore; + submitInfo.pWaitDstStageMask = &wait_dst_stage_mask; + submitInfo.commandBufferCount = 1; + submitInfo.pCommandBuffers = &cmd.buffer; + submitInfo.signalSemaphoreCount = 1; + submitInfo.pSignalSemaphores = &cmd.renderCompleteSemaphore; + + res = vkQueueSubmit(device->queue, 1, &submitInfo, cmd.completedFence); + VK_CHECK_RESULT(res); + + VkPresentInfoKHR presentInfo = { VK_STRUCTURE_TYPE_PRESENT_INFO_KHR }; + presentInfo.waitSemaphoreCount = 1; + presentInfo.pWaitSemaphores = &cmd.renderCompleteSemaphore; + presentInfo.swapchainCount = 1; + presentInfo.pSwapchains = &device->swapchain; + presentInfo.pImageIndices = &device->swapchain_image_index; + + res = vkQueuePresentKHR(device->queue, &presentInfo); + if (res == VK_ERROR_OUT_OF_DATE_KHR) + MGVK_RecreateSwapChain(device); + else + { + VK_CHECK_RESULT(res); + } + + ++device->frame; + + // Move the pending buffers to the free list + // for reuse on the next frame. + if (device->pending != nullptr) + { + auto last = device->pending; + while (true) + { + if (last->next == nullptr) + break; + last = last->next; + } + + last->next = device->free; + device->free = device->pending; + device->pending = nullptr; + } + + // Buffers discarded this frame can be moved + // into the pending list for a future frame. + device->pending = device->discarded; + device->discarded = nullptr; + + // Cleanup resources for the next frame. + MGVK_DestroyFrameResources(device, currentFrame, false); +} + +void MGG_GraphicsDevice_SetBlendState(MGG_GraphicsDevice* device, MGG_BlendState* state, mgfloat factorR, mgfloat factorG, mgfloat factorB, mgfloat factorA) +{ + assert(device != nullptr); + assert(state != nullptr); + + if (device->pipelineState.blendState != state) + { + device->pipelineStateDirty = true; + device->pipelineState.blendState = state; + } + + if (device->blendFactor[0] != factorR || + device->blendFactor[1] != factorG || + device->blendFactor[2] != factorB || + device->blendFactor[3] != factorA) + { + device->blendFactor[0] = factorR; + device->blendFactor[1] = factorG; + device->blendFactor[2] = factorB; + device->blendFactor[3] = factorA; + device->blendFactorDirty = true; + } +} + +void MGG_GraphicsDevice_SetDepthStencilState(MGG_GraphicsDevice* device, MGG_DepthStencilState* state) +{ + assert(device != nullptr); + assert(state != nullptr); + + if (device->pipelineState.depthStencilState != state) + { + device->pipelineStateDirty = true; + device->pipelineState.depthStencilState = state; + } +} + +void MGG_GraphicsDevice_SetRasterizerState(MGG_GraphicsDevice* device, MGG_RasterizerState* state) +{ + assert(device != nullptr); + assert(state != nullptr); + + if (device->pipelineState.rasterizerState != state) + { + device->pipelineStateDirty = true; + device->pipelineState.rasterizerState = state; + } +} + +void MGG_GraphicsDevice_GetTitleSafeArea(mgint& x, mgint& y, mgint& width, mgint& height) +{ + // Nothing for PC here unless we want to support + // things like Steam TV modes and we need platform + // specific calls for that. +} + +void MGG_GraphicsDevice_SetViewport(MGG_GraphicsDevice* device, mgint x, mgint y, mgint width, mgint height, mgfloat minDepth, mgfloat maxDepth) +{ + assert(device != nullptr); + + VkViewport& viewport = device->viewport; + viewport.x = x; + viewport.y = y; + viewport.width = width; + viewport.height = height; + viewport.minDepth = minDepth; + viewport.maxDepth = maxDepth; + + auto frameIndex = device->frame % kConcurrentFrameCount; + auto& frame = device->frames[frameIndex]; + assert(frame.is_recording); + + vkCmdSetViewport(frame.commandBuffer.buffer, 0, 1, &viewport); +} + +void MGG_GraphicsDevice_SetScissorRectangle(MGG_GraphicsDevice* device, mgint x, mgint y, mgint width, mgint height) +{ + assert(device != nullptr); + + VkRect2D& scissor = device->scissor; + scissor.offset.x = x; + scissor.offset.y = y; + scissor.extent.width = width; + scissor.extent.height = height; + device->scissorDirty = true; +} + +void MGG_GraphicsDevice_SetRenderTargets(MGG_GraphicsDevice* device, MGG_Texture** targets, mgint count) +{ + assert(device != nullptr); + + if (targets == nullptr || count == 0) + { + auto currentFrame = device->frame; + auto frameIndex = currentFrame % kConcurrentFrameCount; + auto& frame = device->frames[frameIndex]; + + device->targets.targets[0] = frame.swapchainTexture; + memset(device->targets.targets + 1, 0, 3 * sizeof(MGG_Texture*)); + device->targets.numTargets = 1; + } + else + { + memcpy(device->targets.targets, targets, count * sizeof(MGG_Texture*)); + memset(device->targets.targets + count, 0, (4 - count) * sizeof(MGG_Texture*)); + device->targets.numTargets = count; + } + + device->pipelineStateDirty = true; + device->renderTargetDirty = true; +} + +void MGG_GraphicsDevice_SetConstantBuffer(MGG_GraphicsDevice* device, MGShaderStage stage, mgint slot, MGG_Buffer* buffer) +{ + assert(device != nullptr); + assert(buffer != nullptr); + + // TODO: slot ?? + + MGG_Buffer** uniforms = device->uniforms; + + if (uniforms[(int)stage] != buffer) + { + uniforms[(int)stage] = buffer; + device->uniformsDirty |= 1 << (int)stage; + } + else + { + if (buffer->dirty) + device->uniformsDirty |= 1 << (int)stage; + } +} + +void MGG_GraphicsDevice_SetTexture(MGG_GraphicsDevice* device, MGShaderStage stage, mgint slot, MGG_Texture* texture) +{ + assert(device != nullptr); + assert(slot >= 0); + assert(slot < MAX_TEXTURE_SLOTS); + + device->textures[slot] = texture; + device->textureSamplerDirty |= 1 << slot; +} + +void MGG_GraphicsDevice_SetSamplerState(MGG_GraphicsDevice* device, MGShaderStage stage, mgint slot, MGG_SamplerState* state) +{ + assert(device != nullptr); + assert(slot >= 0); + assert(slot < MAX_TEXTURE_SLOTS); + + device->samplers[slot] = state; + device->textureSamplerDirty |= 1 << slot; +} + +void MGG_GraphicsDevice_SetIndexBuffer(MGG_GraphicsDevice* device, MGIndexElementSize size, MGG_Buffer* buffer) +{ + assert(device != nullptr); + assert(buffer != nullptr); + + device->indexBuffer = buffer; + device->indexBufferSize = size; +} + +void MGG_GraphicsDevice_SetVertexBuffer(MGG_GraphicsDevice* device, mgint slot, MGG_Buffer* buffer, mgint vertexOffset) +{ + assert(device != nullptr); + assert(buffer != nullptr); + + // TODO: Support multiple VB streams! + assert(slot == 0); + assert(vertexOffset == 0); + + device->vertexBuffers[slot] = buffer; + device->vertexOffsets[slot] = vertexOffset; + device->vertexBuffersDirty |= 1 << slot; +} + +void MGG_GraphicsDevice_SetShader(MGG_GraphicsDevice* device, MGShaderStage stage, MGG_Shader* shader) +{ + assert(device != nullptr); + assert(shader != nullptr); + assert(shader->stage == stage); + + device->shaders[(mgint)stage] = shader; + device->shaderDirty = true; +} + +void MGG_GraphicsDevice_SetInputLayout(MGG_GraphicsDevice* device, MGG_InputLayout* layout) +{ + assert(device != nullptr); + assert(layout != nullptr); + + if (layout != device->pipelineState.layout) + { + device->pipelineStateDirty = true; + device->pipelineState.layout = layout; + } +} + +static void MGVK_UpdateRenderPass(MGG_GraphicsDevice* device, FrameCounter currentFrame, MGVK_CmdBuffer& cmd) +{ + if (!device->renderTargetDirty) + return; + + if (device->inRenderPass) + { + vkCmdEndRenderPass(cmd.buffer); + device->inRenderPass = false; + } + + // Lookup the texture set in the cache. + uint32_t hash = MG_ComputeHash((mgbyte*)&device->targets, sizeof(MGVK_TargetSet)); + MGVK_TargetSetCache* cached = device->targetCache[hash]; + if (!cached) + { + cached = new MGVK_TargetSetCache(); + cached->set = device->targets; + + auto first = cached->set.targets[0]; + assert(first); + cached->width = first->info.extent.width; + cached->height = first->info.extent.height; + + VkImageView attachments[5]; + VkAttachmentReference color_attachments[5]; + VkAttachmentReference depth_stencil_attachment; + VkAttachmentDescription attachment_descs[5]; + memset(attachment_descs, 0, sizeof(attachment_descs)); + int num_attachments = 0; + int num_color_attachments = 0; + + for (int i = 0; i < cached->set.numTargets; i++) + { + auto target = cached->set.targets[i]; + assert(target); + + attachments[num_attachments] = target->target_view; + + color_attachments[num_attachments].attachment = num_attachments; + color_attachments[num_attachments].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + attachment_descs[num_attachments].format = target->info.format; + attachment_descs[num_attachments].samples = VK_SAMPLE_COUNT_1_BIT; + attachment_descs[num_attachments].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment_descs[num_attachments].storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachment_descs[num_attachments].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment_descs[num_attachments].stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE; + attachment_descs[num_attachments].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachment_descs[num_attachments].finalLayout = target->isSwapchain ? VK_IMAGE_LAYOUT_PRESENT_SRC_KHR : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + num_attachments++; + num_color_attachments++; + } + + auto depth = cached->set.targets[0]->depthTexture; + if (depth) + { + depth_stencil_attachment.attachment = num_attachments; + depth_stencil_attachment.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + + attachments[num_attachments] = depth->target_view; + + attachment_descs[num_attachments].format = depth->info.format; + attachment_descs[num_attachments].samples = VK_SAMPLE_COUNT_1_BIT; + attachment_descs[num_attachments].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment_descs[num_attachments].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachment_descs[num_attachments].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment_descs[num_attachments].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachment_descs[num_attachments].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachment_descs[num_attachments].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + num_attachments++; + } + + { + VkSubpassDescription subpass_desc = {}; + subpass_desc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass_desc.colorAttachmentCount = num_color_attachments; + subpass_desc.pColorAttachments = color_attachments; + if (depth) + subpass_desc.pDepthStencilAttachment = &depth_stencil_attachment; + + VkRenderPassCreateInfo create_info = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO }; + create_info.attachmentCount = num_attachments; + create_info.pAttachments = attachment_descs; + create_info.subpassCount = 1; + create_info.pSubpasses = &subpass_desc; + + VkResult res = vkCreateRenderPass(device->device, &create_info, nullptr, &cached->renderPass); + VK_CHECK_RESULT(res); + } + + { + VkFramebufferCreateInfo create_info = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; + create_info.renderPass = cached->renderPass; + create_info.attachmentCount = num_attachments; + create_info.pAttachments = attachments; + create_info.width = cached->width; + create_info.height = cached->height; + create_info.layers = 1; + + VkResult res = vkCreateFramebuffer(device->device, &create_info, nullptr, &cached->framebuffer); + VK_CHECK_RESULT(res); + } + + device->targetCache[hash] = cached; + } + + // Set the cache for the changed pipeline state. + device->pipelineState.targets = cached; + + // Set default viewport and scissor. + MGG_GraphicsDevice_SetViewport(device, 0, 0, cached->width, cached->height, 0, 1); + MGG_GraphicsDevice_SetScissorRectangle(device, 0, 0, cached->width, cached->height); + + // Setup the render pass and pipeline. + VkRect2D render_area; + render_area.offset.x = 0; + render_area.offset.y = 0; + render_area.extent.width = cached->width; + render_area.extent.height = cached->height; + + VkRenderPassBeginInfo render_pass_begin_info = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO }; + render_pass_begin_info.renderPass = cached->renderPass; + render_pass_begin_info.framebuffer = cached->framebuffer; + render_pass_begin_info.renderArea = render_area; + render_pass_begin_info.clearValueCount = 0; + render_pass_begin_info.pClearValues = NULL; + vkCmdBeginRenderPass(cmd.buffer, &render_pass_begin_info, VK_SUBPASS_CONTENTS_INLINE); + + device->inRenderPass = true; + device->renderTargetDirty = false; + device->pipelineStateDirty = true; +} + +static void MGVK_UpdateDescriptors(MGG_GraphicsDevice* device, FrameCounter currentFrame, MGG_Shader* shader, VkDescriptorSet* current, uint32_t* dynamicOffset) +{ + // If nothing is dirty then skip the update. + if ((device->uniformsDirty & shader->uniformSlots) == 0 && + (device->textureSamplerDirty & shader->textureSlots) == 0 && + (device->textureSamplerDirty & shader->samplerSlots) == 0) + return; + + // If we got here we must have some sort of bindings! + assert(!shader->bindings.empty()); + + // Apply the bindings to the new descriptor set. + const FrameCounter frameIndex = currentFrame % kConcurrentFrameCount; + auto& offset = device->frames[frameIndex].uniformOffset; + auto buffer = device->frames[frameIndex].uniforms; + + // We have some dirty state... so the descriptor + // needs to be updated before we draw. + + MGVK_DescriptorInfo* info; + + // First generate a hash of the new state. + uint32_t hash = MG_ComputeHash(shader->uniformSlots); + hash = MG_ComputeHash(shader->textureSlots, hash); + uint32_t dirty = shader->textureSlots; + for (int i = 0; i < 16; i++) + { + uint32_t mask = 1 << i; + if ((dirty & mask) == 0) + continue; + + device->textures[i]->frame = currentFrame; + + hash = MG_ComputeHash(device->textures[i]->id, hash); + hash = MG_ComputeHash(device->samplers[i]->id, hash); + + // Early out if there are no more used slots. + dirty &= ~mask; + if (!dirty) + break; + } + //hash = MG_ComputeHash(frame_index); + + // Do we have this same descriptor cached? + info = shader->usedSets[hash]; + if (!info) + { + // The descriptor wasn't cached... so we need to + // create a new one from the free sets. + if (shader->freeSets.size() > 0) + { + info = shader->freeSets.front(); + shader->freeSets.pop(); + } + else + { + // TODO: We're out of free sets... allocate more? + assert(0); + } + + // Cache the new or recycled set for later use. + shader->usedSets[hash] = info; + + for (int i = 0; i < shader->bindings.size(); i++) + { + auto& w = shader->writes[i]; + w.dstSet = info->set; + + if (w.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) + { + auto src = device->uniforms[(int)shader->stage + w.dstBinding]; + ((VkDescriptorBufferInfo*)w.pBufferInfo)->buffer = buffer->buffer; + ((VkDescriptorBufferInfo*)w.pBufferInfo)->range = src->dataSize; + } + else if (w.descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) + { + int slot = w.dstBinding - 32; + ((VkDescriptorImageInfo*)w.pImageInfo)->imageView = device->textures[slot]->view; + ((VkDescriptorImageInfo*)w.pImageInfo)->sampler = device->samplers[slot]->sampler; + } + else + { + // This should never happen! + assert(0); + } + } + + vkUpdateDescriptorSets(device->device, shader->bindings.size(), shader->writes, 0, nullptr); + } + + // Update the uniform data into the buffer. + if (shader->uniformSlots) + { + for (int i = 0; i < shader->bindings.size(); i++) + { + auto& w = shader->writes[i]; + if (w.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) + { + auto src = device->uniforms[(int)shader->stage + w.dstBinding]; + + *dynamicOffset = offset; + + if ((offset + src->dataSize) < buffer->dataSize) + MGVK_BufferCopyAndFlush(device, buffer, offset, src->push, src->dataSize); + else + { + // TODO: Discard or wrap around? + assert(0); + } + + // Must meet the alignment limit for the device. + auto alignedSize = MG_AlignUp(src->dataSize, (int)device->minUniformBufferOffsetAlignment); + offset += alignedSize; + } + } + } + + // Mark when we used this set last so we + // can move it back the free list later. + info->frame = currentFrame; + *current = info->set; +} + +static MGVK_Program* MGVK_ProgramGetOrCreate(MGG_GraphicsDevice* device, MGG_Shader* vertexShaderData, MGG_Shader* pixelShaderData) +{ + assert(device); + assert(vertexShaderData); + assert(pixelShaderData); + + uint64_t programId = ((uint64_t)vertexShaderData->id) | (((uint64_t)pixelShaderData->id) << 32); + MGVK_Program* program = device->shader_programs[programId]; + if (program != nullptr) + return program; + + program = new MGVK_Program(); + program->vertex = vertexShaderData; + program->pixel = pixelShaderData; + + VkResult res; + + int count = 0; + VkDescriptorSetLayout layouts[2]; + if (program->vertex->setLayout) + layouts[count++] = program->vertex->setLayout; + if (program->pixel->setLayout) + layouts[count++] = program->pixel->setLayout; + + VkPipelineLayoutCreateInfo pipelineLayoutInfo; + memset(&pipelineLayoutInfo, 0, sizeof(pipelineLayoutInfo)); + pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipelineLayoutInfo.setLayoutCount = count; + pipelineLayoutInfo.pSetLayouts = layouts; + pipelineLayoutInfo.pushConstantRangeCount = 0; + pipelineLayoutInfo.pPushConstantRanges = nullptr; + res = vkCreatePipelineLayout(device->device, &pipelineLayoutInfo, nullptr, &program->layout); + VK_CHECK_RESULT(res); + + device->shader_programs[programId] = program; + + return program; +} + +static VkPipeline MGVK_CreatePipeline(MGG_GraphicsDevice* device) +{ + // TODO: We could hit hash collisions here, so we + // eventually need to implement some fast hash + // collision detection and resolution. + + // First see if we've cached this state before. + uint32_t hash = MG_ComputeHash((mgbyte*)&device->pipelineState, sizeof(MGVK_PipelineState)); + auto itr = device->pipelines.find(hash); + if (itr != device->pipelines.end()) + return itr->second.cache; + + VkGraphicsPipelineCreateInfo pipelineInfo; + memset(&pipelineInfo, 0, sizeof(pipelineInfo)); + pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + + // We set the viewport and scissor dynamically. + static const VkDynamicState dynamicStates[] = { + VK_DYNAMIC_STATE_VIEWPORT, + VK_DYNAMIC_STATE_SCISSOR, + VK_DYNAMIC_STATE_BLEND_CONSTANTS, + //VK_DYNAMIC_STATE_DEPTH_BIAS, + //VK_DYNAMIC_STATE_DEPTH_BOUNDS, + }; + VkPipelineDynamicStateCreateInfo dynamicState; + memset(&dynamicState, 0, sizeof(dynamicState)); + dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dynamicState.dynamicStateCount = 3; + dynamicState.pDynamicStates = dynamicStates; + pipelineInfo.pDynamicState = &dynamicState; + + + const auto& pstate = device->pipelineState; + + // NOTE: These don't matter as we set them dynamically. + VkPipelineViewportStateCreateInfo viewport; + memset(&viewport, 0, sizeof(viewport)); + viewport.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + viewport.viewportCount = 1; + viewport.pViewports = &device->viewport; + viewport.scissorCount = 1; + viewport.pScissors = &device->scissor; + pipelineInfo.pViewportState = &viewport; + + VkPipelineShaderStageCreateInfo stages[2]; + memset(stages, 0, sizeof(stages)); + stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + stages[0].module = pstate.program->vertex->module; + stages[0].pName = "main"; + stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + stages[1].module = pstate.program->pixel->module; + stages[1].pName = "main"; + pipelineInfo.stageCount = 2; + pipelineInfo.pStages = stages; + pipelineInfo.layout = pstate.program->layout; + + VkPipelineVertexInputStateCreateInfo vertexInputInfo; + memset(&vertexInputInfo, 0, sizeof(vertexInputInfo)); + vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertexInputInfo.vertexBindingDescriptionCount = pstate.layout->streamCount; + vertexInputInfo.pVertexBindingDescriptions = pstate.layout->bindings; + vertexInputInfo.vertexAttributeDescriptionCount = pstate.layout->attributeCount; + vertexInputInfo.pVertexAttributeDescriptions = pstate.layout->attributes; + pipelineInfo.pVertexInputState = &vertexInputInfo; + + + VkPipelineInputAssemblyStateCreateInfo inputAssembly; + memset(&inputAssembly, 0, sizeof(inputAssembly)); + inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + inputAssembly.topology = pstate.topology; + pipelineInfo.pInputAssemblyState = &inputAssembly; + + // Setup the blend, rasterizer, and depth/stencil states. + VkPipelineColorBlendStateCreateInfo colorBlending = pstate.blendState->info; + colorBlending.attachmentCount = pstate.targets->set.numTargets; + pipelineInfo.pColorBlendState = &colorBlending; + pipelineInfo.pRasterizationState = &pstate.rasterizerState->info; + pipelineInfo.pDepthStencilState = &pstate.depthStencilState->info; + + // TODO: What state is this part of? + VkPipelineMultisampleStateCreateInfo multisampling; + memset(&multisampling, 0, sizeof(multisampling)); + multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + multisampling.sampleShadingEnable = VK_FALSE; + multisampling.rasterizationSamples = pstate.rasterizerState->multiSampleAntiAlias ? VK_SAMPLE_COUNT_1_BIT : VK_SAMPLE_COUNT_1_BIT; + multisampling.minSampleShading = 1.0f; // Optional + multisampling.pSampleMask = nullptr; // Optional + multisampling.alphaToCoverageEnable = VK_FALSE; // Optional + multisampling.alphaToOneEnable = VK_FALSE; // Optional + pipelineInfo.pMultisampleState = &multisampling; + pipelineInfo.renderPass = pstate.targets->renderPass; + + pipelineInfo.subpass = 0; + + MGVK_PipelineCache pipeline; + pipeline.state = device->pipelineState; + + VkResult res = vkCreateGraphicsPipelines(device->device, device->pipelineCache, 1, &pipelineInfo, nullptr, &pipeline.cache); + VK_CHECK_RESULT(res); + + device->pipelines[hash] = pipeline; + + return pipeline.cache; +} + +static void MGVK_UpdatePipeline(MGG_GraphicsDevice* device, MGVK_CmdBuffer& cmd, FrameCounter currentFrame) +{ + assert(device); + + // Make sure we know when we last used these states. + device->pipelineState.blendState->frame = currentFrame; + device->pipelineState.depthStencilState->frame = currentFrame; + device->pipelineState.rasterizerState->frame = currentFrame; + + // Update the shader program. + if (device->shaderDirty) + { + auto vertexShader = device->shaders[(mgint)MGShaderStage::Vertex]; + auto pixelShader = device->shaders[(mgint)MGShaderStage::Pixel]; + assert(vertexShader != nullptr); + assert(pixelShader != nullptr); + + auto program = MGVK_ProgramGetOrCreate(device, vertexShader, pixelShader); + + if (program != device->pipelineState.program) + { + device->pipelineState.program = program; + device->pipelineStateDirty = true; + } + + device->shaderDirty = false; + } + + // First update the pipeline if we need to. + if (device->pipelineStateDirty) + { + device->pipelineStateDirty = false; + + auto pipeline = MGVK_CreatePipeline(device); + vkCmdBindPipeline(cmd.buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + + // Since the pipeline changed we need to update other states. + device->scissorDirty = true; + device->uniformsDirty = 0xFFFFFFFF; + device->textureSamplerDirty = 0xFFFFFFFF; + device->descriptorSets[0] = nullptr; + device->descriptorSets[1] = nullptr; + device->dynamicOffsets[0] = 0; + device->dynamicOffsets[1] = 0; + device->vertexBuffersDirty = 0xFFFFFFFF; + device->blendFactorDirty = true; + + // We need to re-apply the viewport too. + vkCmdSetViewport(cmd.buffer, 0, 1, &device->viewport); + } + + if (device->scissorDirty) + { + device->scissorDirty = false; + + // If the scissor state is enabled then set the scissor rectable. + auto rasterizerState = device->pipelineState.rasterizerState; + if (rasterizerState->scissorTestEnable) + vkCmdSetScissor(cmd.buffer, 0, 1, &device->scissor); + else + { + VkRect2D scissor; + scissor.offset.x = 0; + scissor.offset.y = 0; + + // When the scissor test is disabled we need to set the + // scissor rectangle to the full size of the current target. + auto targets = device->pipelineState.targets; + scissor.extent.width = targets->width; + scissor.extent.height = targets->height; + + vkCmdSetScissor(cmd.buffer, 0, 1, &scissor); + } + } + + if (device->blendFactorDirty) + { + vkCmdSetBlendConstants(cmd.buffer, device->blendFactor); + device->blendFactorDirty = false; + } + + // Do we need to update the descriptors? + if (device->uniformsDirty || device->textureSamplerDirty) + { + auto program = device->pipelineState.program; + + // Update the shader bindings. + int setsCount = 0; + int offsetCount = 0; + if (program->vertex->setLayout) + { + uint32_t* dynamicOffset = nullptr; + if (program->vertex->uniformSlots) + dynamicOffset = &device->dynamicOffsets[offsetCount++]; + + MGVK_UpdateDescriptors(device, currentFrame, program->vertex, &device->descriptorSets[setsCount++], dynamicOffset); + } + if (program->pixel->setLayout) + { + uint32_t* dynamicOffset = nullptr; + if (program->pixel->uniformSlots) + dynamicOffset = &device->dynamicOffsets[offsetCount++]; + + MGVK_UpdateDescriptors(device, currentFrame, program->pixel, &device->descriptorSets[setsCount++], dynamicOffset); + } + + // Bind the new descriptor sets. + vkCmdBindDescriptorSets(cmd.buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + program->layout, 0, + setsCount, device->descriptorSets, + offsetCount, device->dynamicOffsets); + + // Clear all the dirty flags. + device->uniformsDirty = 0; + device->textureSamplerDirty = 0; + } + + if (device->vertexBuffersDirty) + { + // TODO: Fix multiple vertex streams! + + int count = 0; + VkDeviceSize offsets[8]; + VkBuffer buffers[8]; + for (int i = 0; i < 8; i++) + { + offsets[i] = device->vertexOffsets[i]; + buffers[i] = nullptr; + + auto buffer = device->vertexBuffers[i]; + if (buffer) + { + buffer->frame = currentFrame; + buffers[i] = buffer->buffer; + count++; + } + } + + vkCmdBindVertexBuffers(cmd.buffer, 0, count, buffers, offsets); + + device->vertexBuffersDirty = 0; + } +} + +static int MGVK_GetIndexCount(MGPrimitiveType primitiveType, mgint primitiveCount) +{ + switch (primitiveType) + { + case MGPrimitiveType::LineList: + return primitiveCount * 2; + case MGPrimitiveType::LineStrip: + return primitiveCount + 1; + case MGPrimitiveType::TriangleList: + return primitiveCount * 3; + case MGPrimitiveType::TriangleStrip: + return primitiveCount + 2; + default: + case MGPrimitiveType::PointList: + return primitiveCount; + } +} + +void MGG_GraphicsDevice_Draw(MGG_GraphicsDevice* device, MGPrimitiveType primitiveType, mgint vertexStart, mgint vertexCount) +{ + assert(device != nullptr); + assert(vertexStart >= 0); + + if (vertexCount <= 0) + return; + + auto currentFrame = device->frame; + auto frameIndex = currentFrame % kConcurrentFrameCount; + auto& frame = device->frames[frameIndex]; + assert(frame.is_recording); + + MGVK_UpdateRenderPass(device, currentFrame, frame.commandBuffer); + + auto topology = ToVkPrimitiveTopology(primitiveType); + if (device->pipelineState.topology != topology) + { + device->pipelineStateDirty = true; + device->pipelineState.topology = topology; + } + + MGVK_UpdatePipeline(device, frame.commandBuffer, currentFrame); + + vkCmdDraw(frame.commandBuffer.buffer, vertexCount, 1, vertexStart, 0); +} + +void MGG_GraphicsDevice_DrawIndexed(MGG_GraphicsDevice* device, MGPrimitiveType primitiveType, mgint primitiveCount, mgint indexStart, mgint vertexStart) +{ + assert(device != nullptr); + assert(primitiveCount >= 0); + assert(indexStart >= 0); + assert(vertexStart >= 0); + + if (primitiveCount <= 0) + return; + + auto currentFrame = device->frame; + auto frameIndex = currentFrame % kConcurrentFrameCount; + auto& frame = device->frames[frameIndex]; + assert(frame.is_recording); + + MGVK_UpdateRenderPass(device, currentFrame, frame.commandBuffer); + + auto topology = ToVkPrimitiveTopology(primitiveType); + if (device->pipelineState.topology != topology) + { + device->pipelineStateDirty = true; + device->pipelineState.topology = topology; + } + + MGVK_UpdatePipeline(device, frame.commandBuffer, currentFrame); + + auto indexBuffer = device->indexBuffer; + assert(indexBuffer != nullptr); + + // TODO: Detect if we need to rebind the same index buffer? + vkCmdBindIndexBuffer(frame.commandBuffer.buffer, indexBuffer->buffer, 0, device->indexBufferSize == MGIndexElementSize::SixteenBits ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32); + + auto indexCount = MGVK_GetIndexCount(primitiveType, primitiveCount); + + vkCmdDrawIndexed(frame.commandBuffer.buffer, indexCount, 1, indexStart, vertexStart, 0); +} + +void MGG_GraphicsDevice_DrawIndexedInstanced(MGG_GraphicsDevice* device, MGPrimitiveType primitiveType, mgint primitiveCount, mgint indexStart, mgint vertexStart, mgint instanceCount) +{ + assert(device != nullptr); + assert(primitiveCount >= 0); + assert(indexStart >= 0); + assert(vertexStart >= 0); + assert(instanceCount >= 0); + + if (primitiveCount <= 0) + return; + if (instanceCount <= 0) + return; + + MG_NOT_IMPLEMEMTED; +} + + +static VkBlendFactor ToVkBlendFactor(MGBlend mode) +{ + switch (mode) + { + case MGBlend::One: + return VK_BLEND_FACTOR_ONE; + case MGBlend::Zero: + return VK_BLEND_FACTOR_ZERO; + case MGBlend::SourceColor: + return VK_BLEND_FACTOR_SRC_COLOR; + case MGBlend::InverseSourceColor: + return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR; + case MGBlend::SourceAlpha: + return VK_BLEND_FACTOR_SRC_ALPHA; + case MGBlend::InverseSourceAlpha: + return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + case MGBlend::DestinationColor: + return VK_BLEND_FACTOR_DST_COLOR; + case MGBlend::InverseDestinationColor: + return VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR; + case MGBlend::DestinationAlpha: + return VK_BLEND_FACTOR_DST_ALPHA; + case MGBlend::InverseDestinationAlpha: + return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA; + case MGBlend::BlendFactor: + return VK_BLEND_FACTOR_CONSTANT_COLOR; + case MGBlend::InverseBlendFactor: + return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR; + case MGBlend::SourceAlphaSaturation: + return VK_BLEND_FACTOR_SRC_ALPHA_SATURATE; + default: + assert(0); + } +} + +static VkBlendOp ToVkBlendOp(MGBlendFunction func) +{ + switch (func) + { + case MGBlendFunction::Add: + return VK_BLEND_OP_ADD; + case MGBlendFunction::Subtract: + return VK_BLEND_OP_SUBTRACT; + case MGBlendFunction::ReverseSubtract: + return VK_BLEND_OP_REVERSE_SUBTRACT; + case MGBlendFunction::Min: + return VK_BLEND_OP_MIN; + case MGBlendFunction::Max: + return VK_BLEND_OP_MAX; + default: + assert(0); + } +} + +static void MGVK_SetBlendState(MGG_BlendState_Info* info, VkPipelineColorBlendAttachmentState* blend) +{ + if ((int)info->colorWriteChannels & (int)MGColorWriteChannels::Red) + blend->colorWriteMask |= VK_COLOR_COMPONENT_R_BIT; + if ((int)info->colorWriteChannels & (int)MGColorWriteChannels::Green) + blend->colorWriteMask |= VK_COLOR_COMPONENT_G_BIT; + if ((int)info->colorWriteChannels & (int)MGColorWriteChannels::Blue) + blend->colorWriteMask |= VK_COLOR_COMPONENT_B_BIT; + if ((int)info->colorWriteChannels & (int)MGColorWriteChannels::Alpha) + blend->colorWriteMask |= VK_COLOR_COMPONENT_A_BIT; + + blend->blendEnable = !(info->colorSourceBlend == MGBlend::One && + info->colorDestBlend == MGBlend::Zero && + info->alphaSourceBlend == MGBlend::One && + info->alphaDestBlend == MGBlend::Zero); + + blend->srcColorBlendFactor = ToVkBlendFactor(info->colorSourceBlend); + blend->dstColorBlendFactor = ToVkBlendFactor(info->colorDestBlend); + blend->colorBlendOp = ToVkBlendOp(info->colorBlendFunc); + blend->srcAlphaBlendFactor = ToVkBlendFactor(info->alphaSourceBlend); + blend->dstAlphaBlendFactor = ToVkBlendFactor(info->alphaDestBlend); + blend->alphaBlendOp = ToVkBlendOp(info->alphaBlendFunc); +} + +MGG_BlendState* MGG_BlendState_Create(MGG_GraphicsDevice* device, MGG_BlendState_Info* infos) +{ + assert(device != nullptr); + assert(infos != nullptr); + + // First check the cache. + uint32_t hash = MG_ComputeHash((mgbyte*)infos, sizeof(MGG_BlendState_Info) * 4); + MGG_BlendState* cached = device->blendStates[hash]; + if (cached) + { + cached->refs++; + return cached; + } + + auto state = new MGG_BlendState(); + memset(state, 0, sizeof(MGG_BlendState)); + + auto attachments = state->attachments; + MGVK_SetBlendState(infos + 0, attachments + 0); + MGVK_SetBlendState(infos + 1, attachments + 1); + MGVK_SetBlendState(infos + 2, attachments + 2); + MGVK_SetBlendState(infos + 3, attachments + 3); + + auto& blend = state->info; + blend.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + blend.logicOpEnable = VK_FALSE; + blend.logicOp = VK_LOGIC_OP_COPY; + blend.flags = 0; // Reserved for future use. + blend.pAttachments = state->attachments; + blend.attachmentCount = 4; + + state->refs = 1; + state->hash = hash; + + device->blendStates[hash] = state; + + return state; + +} + +void MGG_BlendState_Destroy(MGG_GraphicsDevice* device, MGG_BlendState* state) +{ + assert(device != nullptr); + assert(state != nullptr); + + if (!state) + return; + + // Release the reference. + state->refs--; + if (state->refs > 0) + return; + + // Queue the state for later destruction. + device->destroyBlendStates.push(state); + device->blendStates.erase(state->hash); +} + +static VkCompareOp ToVkCompareOp(MGCompareFunction func) +{ + switch (func) + { + case MGCompareFunction::Always: + return VK_COMPARE_OP_ALWAYS; + case MGCompareFunction::Never: + return VK_COMPARE_OP_NEVER; + case MGCompareFunction::Less: + return VK_COMPARE_OP_LESS; + case MGCompareFunction::LessEqual: + return VK_COMPARE_OP_LESS_OR_EQUAL; + case MGCompareFunction::Equal: + return VK_COMPARE_OP_EQUAL; + case MGCompareFunction::GreaterEqual: + return VK_COMPARE_OP_GREATER_OR_EQUAL; + case MGCompareFunction::Greater: + return VK_COMPARE_OP_GREATER; + case MGCompareFunction::NotEqual: + return VK_COMPARE_OP_NOT_EQUAL; + default: + assert(0); + } +} + +static VkStencilOp ToVkStencilOp(MGStencilOperation op) +{ + switch (op) + { + case MGStencilOperation::Keep: + return VK_STENCIL_OP_KEEP; + case MGStencilOperation::Zero: + return VK_STENCIL_OP_ZERO; + case MGStencilOperation::Replace: + return VK_STENCIL_OP_REPLACE; + case MGStencilOperation::Increment: + return VK_STENCIL_OP_INCREMENT_AND_WRAP; + case MGStencilOperation::Decrement: + return VK_STENCIL_OP_DECREMENT_AND_WRAP; + case MGStencilOperation::IncrementSaturation: + return VK_STENCIL_OP_INCREMENT_AND_CLAMP; + case MGStencilOperation::DecrementSaturation: + return VK_STENCIL_OP_DECREMENT_AND_CLAMP; + case MGStencilOperation::Invert: + return VK_STENCIL_OP_INVERT; + default: + assert(0); + } +} + +MGG_DepthStencilState* MGG_DepthStencilState_Create(MGG_GraphicsDevice* device, MGG_DepthStencilState_Info* info) +{ + assert(device != nullptr); + assert(info != nullptr); + + // First check the cache. + uint32_t hash = MG_ComputeHash((mgbyte*)info, sizeof(MGG_DepthStencilState_Info)); + MGG_DepthStencilState* cached = device->depthStencilStates[hash]; + if (cached) + { + cached->refs++; + return cached; + } + + auto state = new MGG_DepthStencilState(); + memset(state, 0, sizeof(MGG_DepthStencilState)); + + auto& depth = state->info; + depth.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + depth.flags = 0; // Reserved for future use. + depth.depthTestEnable = info->depthBufferEnable; + depth.depthWriteEnable = info->depthBufferWriteEnable; + depth.depthCompareOp = ToVkCompareOp(info->depthBufferFunction); + depth.depthBoundsTestEnable = VK_FALSE; // VK_TRUE; + depth.stencilTestEnable = info->stencilEnable; + depth.front.failOp = ToVkStencilOp(info->stencilFail); + depth.front.passOp = ToVkStencilOp(info->stencilPass); + depth.front.depthFailOp = ToVkStencilOp(info->stencilDepthBufferFail); + depth.front.compareOp = ToVkCompareOp(info->stencilFunction); + depth.front.compareMask = info->stencilMask; + depth.front.writeMask = info->stencilWriteMask; + depth.front.reference = info->referenceStencil; + depth.back = depth.front; + depth.minDepthBounds = 0.0f; + depth.maxDepthBounds = 1.0f; + + state->refs = 1; + state->hash = hash; + device->depthStencilStates[hash] = state; + + return state; +} + +void MGG_DepthStencilState_Destroy(MGG_GraphicsDevice* device, MGG_DepthStencilState* state) +{ + assert(device != nullptr); + assert(state != nullptr); + + if (!state) + return; + + // Release the reference. + state->refs--; + if (state->refs > 0) + return; + + // Queue the state for later destruction. + device->destroyDepthStencilStates.push(state); + device->depthStencilStates.erase(state->hash); +} + +static VkPolygonMode ToVkPolygonMode(MGFillMode mode) +{ + switch (mode) + { + case MGFillMode::Solid: + return VK_POLYGON_MODE_FILL; + case MGFillMode::WireFrame: + return VK_POLYGON_MODE_LINE; + default: + assert(0); + } +} + +static VkCullModeFlags ToVkCullModeFlags(MGCullMode mode) +{ + switch (mode) + { + case MGCullMode::None: + return VK_CULL_MODE_NONE; + case MGCullMode::CullClockwiseFace: + return VK_CULL_MODE_FRONT_BIT; + case MGCullMode::CullCounterClockwiseFace: + return VK_CULL_MODE_BACK_BIT; + default: + assert(0); + } +} + + +MGG_RasterizerState* MGG_RasterizerState_Create(MGG_GraphicsDevice* device, MGG_RasterizerState_Info* info) +{ + assert(device != nullptr); + assert(info != nullptr); + + // First check the cache. + uint32_t hash = MG_ComputeHash((mgbyte*)info, sizeof(MGG_RasterizerState_Info)); + MGG_RasterizerState* cached = device->rasterizerStates[hash]; + if (cached) + { + cached->refs++; + return cached; + } + + auto state = new MGG_RasterizerState(); + memset(state, 0, sizeof(MGG_RasterizerState)); + + auto& rasterizer = state->info; + rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rasterizer.flags = 0; // Reserved for future use. + rasterizer.depthClampEnable = VK_FALSE; // info->depthClipEnable; + rasterizer.rasterizerDiscardEnable = VK_FALSE; + rasterizer.polygonMode = ToVkPolygonMode(info->fillMode); + rasterizer.cullMode = ToVkCullModeFlags(info->cullMode); + rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE; + rasterizer.depthBiasEnable = info->depthBias != 0; + rasterizer.depthBiasConstantFactor = info->depthBias; + rasterizer.depthBiasClamp = 0.0f; + rasterizer.depthBiasSlopeFactor = info->slopeScaleDepthBias; + rasterizer.lineWidth = 1.0f; + + // These don't fit this structure, so we + // need to hold them for later. + state->scissorTestEnable = info->scissorTestEnable; + state->multiSampleAntiAlias = info->multiSampleAntiAlias; + + state->refs = 1; + state->hash = hash; + device->rasterizerStates[hash] = state; + + return state; +} + +void MGG_RasterizerState_Destroy(MGG_GraphicsDevice* device, MGG_RasterizerState* state) +{ + assert(device != nullptr); + assert(state != nullptr); + + if (!state) + return; + + // Release the reference. + state->refs--; + if (state->refs > 0) + return; + + // Queue the state for later destruction. + device->destroyRasterizerStates.push(state); + device->rasterizerStates.erase(state->hash); +} + +static VkSamplerAddressMode ToVkSamplerAddressMode(MGTextureAddressMode mode) +{ + switch (mode) + { + case MGTextureAddressMode::Wrap: + return VK_SAMPLER_ADDRESS_MODE_REPEAT; + case MGTextureAddressMode::Clamp: + return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + case MGTextureAddressMode::Mirror: + return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; + case MGTextureAddressMode::Border: + return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; + default: + assert(0); + } +} + +MGG_SamplerState* MGG_SamplerState_Create(MGG_GraphicsDevice* device, MGG_SamplerState_Info* info) +{ + assert(device != nullptr); + assert(info != nullptr); + + // TODO: Why isn't this reference counted? + + auto state = new MGG_SamplerState(); + state->info = *info; // For debugging + + VkSamplerCreateInfo samplerInfo = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; + samplerInfo.addressModeU = ToVkSamplerAddressMode(info->AddressU); + samplerInfo.addressModeV = ToVkSamplerAddressMode(info->AddressV); + samplerInfo.addressModeW = ToVkSamplerAddressMode(info->AddressW); + samplerInfo.anisotropyEnable = info->Filter == MGTextureFilter::Anisotropic; + samplerInfo.maxAnisotropy = info->MaximumAnisotropy; + samplerInfo.unnormalizedCoordinates = VK_FALSE; + samplerInfo.compareEnable = VK_FALSE; + samplerInfo.compareOp = VK_COMPARE_OP_NEVER; + samplerInfo.mipLodBias = 0.0f; // ?? info->MipMapLevelOfDetailBias + samplerInfo.minLod = 0; // ??? info->MaxMipLevel + samplerInfo.maxLod = VK_LOD_CLAMP_NONE; + + VkSamplerCustomBorderColorCreateInfoEXT bcolor = {}; + + // TODO: What about the FLOAT color cases? + if (info->BorderColor == 0x00000000) + samplerInfo.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; + else if (info->BorderColor == 0xFF000000) + samplerInfo.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; + else if (info->BorderColor == 0xFFFFFFFF) + samplerInfo.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; + else + { + samplerInfo.borderColor = VK_BORDER_COLOR_FLOAT_CUSTOM_EXT; + bcolor.sType = VK_STRUCTURE_TYPE_SAMPLER_CUSTOM_BORDER_COLOR_CREATE_INFO_EXT; + + // RGBA + bcolor.format = VK_FORMAT_UNDEFINED; + bcolor.customBorderColor.float32[0] = ((info->BorderColor >> 0) & 0xFF) / 255.0f; + bcolor.customBorderColor.float32[1] = ((info->BorderColor >> 8) & 0xFF) / 255.0f; + bcolor.customBorderColor.float32[2] = ((info->BorderColor >> 16) & 0xFF) / 255.0f; + bcolor.customBorderColor.float32[3] = ((info->BorderColor >> 24) & 0xFF) / 255.0f; + + samplerInfo.pNext = &bcolor; + } + + switch (info->Filter) + { + case MGTextureFilter::Anisotropic: + case MGTextureFilter::Linear: + samplerInfo.minFilter = VK_FILTER_LINEAR; + samplerInfo.magFilter = VK_FILTER_LINEAR; + samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + break; + case MGTextureFilter::LinearMipPoint: + samplerInfo.minFilter = VK_FILTER_LINEAR; + samplerInfo.magFilter = VK_FILTER_LINEAR; + samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + break; + case MGTextureFilter::Point: + samplerInfo.minFilter = VK_FILTER_NEAREST; + samplerInfo.magFilter = VK_FILTER_NEAREST; + samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + break; + case MGTextureFilter::PointMipLinear: + samplerInfo.minFilter = VK_FILTER_NEAREST; + samplerInfo.magFilter = VK_FILTER_NEAREST; + samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + break; + case MGTextureFilter::MinLinearMagPointMipLinear: + samplerInfo.minFilter = VK_FILTER_LINEAR; + samplerInfo.magFilter = VK_FILTER_NEAREST; + samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + break; + case MGTextureFilter::MinLinearMagPointMipPoint: + samplerInfo.minFilter = VK_FILTER_LINEAR; + samplerInfo.magFilter = VK_FILTER_NEAREST; + samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + break; + case MGTextureFilter::MinPointMagLinearMipLinear: + samplerInfo.minFilter = VK_FILTER_NEAREST; + samplerInfo.magFilter = VK_FILTER_LINEAR; + samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + break; + case MGTextureFilter::MinPointMagLinearMipPoint: + samplerInfo.minFilter = VK_FILTER_NEAREST; + samplerInfo.magFilter = VK_FILTER_LINEAR; + samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + break; + default: + assert(0); + } + + VkResult res = vkCreateSampler(device->device, &samplerInfo, nullptr, &state->sampler); + VK_CHECK_RESULT(res); + + state->id = ++device->currentSamplerId; + + return state; +} + +void MGG_SamplerState_Destroy(MGG_GraphicsDevice* device, MGG_SamplerState* state) +{ + assert(device != nullptr); + assert(state != nullptr); + + if (!state) + return; + + vkDestroySampler(device->device, state->sampler, nullptr); + + delete state; +} + +static MGG_Buffer* MGVK_BufferDiscard(MGG_GraphicsDevice* device, MGG_Buffer* buffer) +{ + // Get the info we need to find/allocate a new buffer. + auto dataSize = buffer->dataSize; + auto type = buffer->type; + + // Discard the current buffer. + assert(buffer->next == nullptr); + buffer->next = device->discarded; + device->discarded = buffer; + buffer = nullptr; + + // Search for the best fit from the free list. + MGG_Buffer** curr = &device->free; + MGG_Buffer** best = nullptr; + while (*curr != nullptr) + { + if ((*curr)->type == type) + { + auto currSize = (*curr)->actualSize; + + if (currSize >= dataSize) + { + if (best == nullptr || (*best)->actualSize > currSize) + { + best = curr; + if (currSize == dataSize) + break; + } + } + } + + curr = &(*curr)->next; + } + + // Did we find a match? + if (best != nullptr) + { + buffer = *best; + *best = buffer->next; + buffer->next = nullptr; + buffer->dataSize = dataSize; + //buffer->dirtyMin = 0; + //buffer->dirtyMax = 0; + return buffer; + } + + // We didn't find a match, so allocate a new one. + buffer = MGG_Buffer_Create(device, type, dataSize); + + return buffer; +} + +static MGG_Buffer* MGVK_Buffer_Create(MGG_GraphicsDevice* device, MGBufferType type, mgint sizeInBytes, bool no_push) +{ + assert(device != nullptr); + + auto buffer = new MGG_Buffer(); + memset(buffer, 0, sizeof(MGG_Buffer)); + + buffer->actualSize = buffer->dataSize = sizeInBytes; + buffer->type = type; + + if (type == MGBufferType::Constant && !no_push) + { + // Uniform buffers never use real buffers. We just + // keep the data in system memory until it is time to render. + buffer->push = new mgbyte[sizeInBytes]; + } + else + { + VkBufferUsageFlags usage; + switch (type) + { + case MGBufferType::Index: + usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT; + break; + case MGBufferType::Vertex: + usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; + break; + case MGBufferType::Constant: + usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; + break; + default: + assert(0); + } + + MGVK_BufferCreate(device, sizeInBytes, usage, VMA_MEMORY_USAGE_CPU_TO_GPU, buffer); + + // TODO: We could lazy map on first write/read... then + // unmap it if we haven't accessed it in a while. This + // should reduce the CPU memory we have in use for + // generally static buffers. Maybe the dynamic buffer + // hint would be useful for this? + + // Mapping buffers takes a good amount of time, so + // just keep the buffer mapped the whole time and + // use flush/invalidate to syncronize as needed. + auto res = vmaMapMemory(device->allocator, buffer->allocation, (void**)&buffer->mapped); + VK_CHECK_RESULT(res); + } + + device->all_buffers.push_back(buffer); + + return buffer; +} + +MGG_Buffer* MGG_Buffer_Create(MGG_GraphicsDevice* device, MGBufferType type, mgint sizeInBytes) +{ + return MGVK_Buffer_Create(device, type, sizeInBytes, false); +} + +static void MGVK_BufferCopyAndFlush(MGG_GraphicsDevice* device, MGG_Buffer* buffer, int destOffset, mgbyte* data, int dataBytes) +{ + assert(device); + assert(buffer); + assert(destOffset < buffer->dataSize); + assert(destOffset + dataBytes <= buffer->dataSize); + + memcpy(buffer->mapped + destOffset, data, dataBytes); + + buffer->dirty = false; + + /* + // TODO: Store ranges and all buffers used in a frame + // so we can flush them before vkSubmit. + auto nonCoherentAtomSize = device->deviceProperties.limits.nonCoherentAtomSize; + + uint32_t alignedOffset = destOffset; + if ((alignedOffset % nonCoherentAtomSize) != 0) + alignedOffset -= alignedOffset % nonCoherentAtomSize; + + uint32_t alignedEnd = destOffset + dataBytes; + if ((alignedEnd % nonCoherentAtomSize) != 0) + { + alignedEnd += nonCoherentAtomSize - (alignedEnd % nonCoherentAtomSize); + if (alignedEnd >= buffer->dataSize) + alignedEnd = buffer->dataSize; + } + + assert(alignedOffset < buffer->dataSize); + assert(alignedEnd <= buffer->dataSize); + + uint32_t alignedSize = alignedEnd - alignedOffset; + + VkMappedMemoryRange range = { VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE }; + range.memory = buffer->memory; + range.offset = alignedOffset; + range.size = alignedSize; + VkResult res = vkFlushMappedMemoryRanges(device->device, 1, &range); + VK_CHECK_RESULT(res); + */ +} + +void MGG_Buffer_Destroy(MGG_GraphicsDevice* device, MGG_Buffer* buffer) +{ + assert(device != nullptr); + assert(buffer != nullptr); + + if (!buffer) + return; + + mg_remove(device->all_buffers, buffer); + + // Push buffers can be freed immediately. + if (buffer->push) + { + delete[] buffer->push; + delete buffer; + return; + } + + // Safe to unmap it now. + if (buffer->mapped) + vmaUnmapMemory(device->allocator, buffer->allocation); + + // Queue the buffer for later destruction. + device->destroyBuffers.push(buffer); +} + +void MGG_Buffer_SetData(MGG_GraphicsDevice* device, MGG_Buffer*& buffer, mgint offset, mgbyte* data, mgint length, mgbool discard) +{ + assert(device != nullptr); + assert(buffer != nullptr); + assert(data != nullptr); + + buffer->dirty = true; + + // If this is a push buffer we don't need to + // do anything other than copy over the content. + // We can safely ignore the discard. + if (buffer->push) + { + memcpy(buffer->push + offset, data, length); + return; + } + + // TODO: Force discard here if we find we're + // copying over data still in use. See NX. + + if (discard) + { + auto last = buffer; + + buffer = MGVK_BufferDiscard(device, buffer); + + // Fix any active mapping of the buffer that + // was just discarded for another. + + switch (buffer->type) + { + case MGBufferType::Constant: + for (int i=0; i < (int)MGShaderStage::Count; i++) + { + if (device->uniforms[i] == last) + { + device->uniforms[i] = buffer; + device->uniformsDirty |= 1 << (int)i; + } + } + break; + + case MGBufferType::Vertex: + for (int i = 0; i < 8; i++) + { + if (device->vertexBuffers[i] == last) + { + device->vertexBuffers[i] = buffer; + device->vertexBuffersDirty |= 1 << i; + } + } + break; + + case MGBufferType::Index: + if (device->indexBuffer == last) + device->indexBuffer = buffer; + break; + } + } + + // Do the copy and flush. + MGVK_BufferCopyAndFlush(device, buffer, offset, data, length); +} + +void MGG_Buffer_GetData(MGG_GraphicsDevice* device, MGG_Buffer* buffer, mgint offset, mgbyte* data, mgint dataCount, mgint dataBytes, mgint dataStride) +{ + assert(device != nullptr); + assert(buffer != nullptr); + assert(data != nullptr); + + //assert(offset > 0 && offset < buffer->length); + + assert(dataCount > 0); + assert(dataBytes > 0); + assert(dataStride > 0); + + if (buffer->push) + memcpy(data, buffer->push + offset, dataCount * dataBytes); + else + memcpy(data, buffer->mapped + offset, dataCount * dataBytes); +} + +MGG_Texture* MGG_Texture_Create( + MGG_GraphicsDevice* device, + MGTextureType type, + MGSurfaceFormat format, + mgint width, + mgint height, + mgint depth, + mgint mipmaps, + mgint slices) +{ + assert(device != nullptr); + + assert(width > 0); + assert(height > 0); + assert(depth > 0); + assert(mipmaps > 0); + assert(slices > 0); + assert(type != MGTextureType::Cube || (slices % 6) == 0); + + auto texture = new MGG_Texture(); + texture->type = type; + texture->format = format; + + VkImageCreateInfo& create_info = texture->info; + create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + create_info.imageType = VK_IMAGE_TYPE_2D; // TODO: 3D textures + create_info.format = ToVkFormat(format); + create_info.extent.width = width; + create_info.extent.height = height; + create_info.extent.depth = depth; + create_info.mipLevels = mipmaps; + create_info.arrayLayers = slices; + create_info.samples = VK_SAMPLE_COUNT_1_BIT; + create_info.tiling = VK_IMAGE_TILING_OPTIMAL; + create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + + texture->layout = VK_IMAGE_LAYOUT_UNDEFINED; + texture->optimal_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + + mggCreateImage(device, &create_info, texture); + + texture->view = CreateImageView(device, texture, mipmaps); + + texture->id = ++device->currentTextureId; + + return texture; +} + +MGG_Texture* MGG_RenderTarget_Create( + MGG_GraphicsDevice* device, + MGTextureType type, + MGSurfaceFormat format, + mgint width, + mgint height, + mgint depth, + mgint mipmaps, + mgint slices, + MGDepthFormat depthFormat, + mgint multiSampleCount, + MGRenderTargetUsage usage) +{ + assert(device != nullptr); + + assert(width > 0); + assert(height > 0); + assert(depth > 0); + assert(mipmaps > 0); + assert(slices > 0); + assert(type != MGTextureType::Cube || (slices % 6) == 0); + + auto texture = new MGG_Texture(); + texture->isTarget = true; + texture->type = type; + texture->format = format; + + texture->depthFormat = depthFormat; + texture->multiSampleCount = multiSampleCount; + texture->usage = usage; + + { + VkImageCreateInfo& create_info = texture->info; + create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + create_info.imageType = VK_IMAGE_TYPE_2D; // TODO: Fix type! + create_info.format = ToVkFormat(format); + create_info.extent.width = width; + create_info.extent.height = height; + create_info.extent.depth = depth; + create_info.mipLevels = mipmaps; + create_info.arrayLayers = slices; + create_info.samples = VK_SAMPLE_COUNT_1_BIT; + create_info.tiling = VK_IMAGE_TILING_OPTIMAL; + create_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + + texture->layout = VK_IMAGE_LAYOUT_UNDEFINED; + texture->optimal_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + + mggCreateImage(device, &create_info, texture); + + texture->view = CreateImageView(device, texture, mipmaps); + texture->target_view = CreateImageView(device, texture, 1); + + MGVK_TransitionImageLayout(device, texture, 0, texture->optimal_layout); + } + + if (depthFormat != MGDepthFormat::None) + { + texture->depthTexture = CreateDepthTexture(device, ToVkFormat(depthFormat), width, height); + texture->depthTexture->target_view = CreateImageView(device, texture->depthTexture, 1); + } + + texture->id = ++device->currentTextureId; + + //device->all_textures.push_back(texture); + + return texture; +} + +void MGG_Texture_Destroy(MGG_GraphicsDevice* device, MGG_Texture* texture) +{ + assert(device != nullptr); + assert(texture != nullptr); + + if (!texture) + return; + + if (texture->depthTexture) + MGG_Texture_Destroy(device, texture->depthTexture); + + // Queue the texture for later destruction. + device->destroyTextures.push(texture); + + //remove_by_value(device->all_textures, texture); + //delete texture; +} + +static void MGVK_TransitionImageLayout(MGG_GraphicsDevice* device, MGG_Texture* texture, int32_t level, VkImageLayout newLayout) +{ + VkCommandBuffer cmd = MGVK_BeginNewCommandBuffer(device); + + VkImageLayout oldLayout = texture->layout; + + VkImageMemoryBarrier barrier = {}; + barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + barrier.oldLayout = oldLayout; + barrier.newLayout = newLayout; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = texture->image; + barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; // Fetch this from MGG_Texture! + barrier.subresourceRange.baseMipLevel = level; + barrier.subresourceRange.levelCount = 1; + barrier.subresourceRange.baseArrayLayer = 0; + barrier.subresourceRange.layerCount = 1; + + VkPipelineStageFlags sourceStage; + VkPipelineStageFlags destinationStage; + + if (newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) + { + barrier.srcAccessMask = 0; + barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + + sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT; + } + else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) + { + barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + + sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT; + destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; + } + else if (newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) + { + barrier.srcAccessMask = 0; + barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + + sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT; + } + else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) + { + barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + + sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT; + destinationStage = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; + + if (newLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) + barrier.dstAccessMask |= VK_ACCESS_SHADER_WRITE_BIT; + } + else if (newLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) + { + barrier.srcAccessMask = 0; + barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + + sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + destinationStage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + } + else if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) + { + barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + + barrier.srcAccessMask = 0; + barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + + sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; + destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; + } + else + { + // unsupported layout transition! + assert(0); + } + + vkCmdPipelineBarrier( + cmd, + sourceStage, destinationStage, + 0, + 0, nullptr, + 0, nullptr, + 1, &barrier + ); + + MGVK_ExecuteAndFreeCommandBuffer(device, cmd); + + texture->layout = barrier.newLayout; +} + +void MGG_Texture_SetData(MGG_GraphicsDevice* device, MGG_Texture* texture, mgint level, mgint slice, mgint x, mgint y, mgint z, mgint width, mgint height, mgint depth, mgbyte* data, mgint dataBytes) +{ + assert(device != nullptr); + assert(texture != nullptr); + + if (x == 0 && y == 0 && width == 0 && height == 0) + { + width = texture->info.extent.width; + height = texture->info.extent.height; + } + + assert(level >= 0 && level < texture->info.mipLevels); + assert(slice >= 0 && slice < texture->info.arrayLayers); + assert(x >= 0 && x < texture->info.extent.width); + assert(y >= 0 && y < texture->info.extent.height); + assert(z >= 0 && z < texture->info.extent.depth); + assert(x + width <= texture->info.extent.width); + assert(y + height <= texture->info.extent.height); + assert(z + depth <= texture->info.extent.depth); + + assert(data != nullptr); + assert(dataBytes > 0); + + // TODO: Pool staging buffers maybe? + + MGG_Buffer buffer; + MGVK_BufferCreate(device, dataBytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_ONLY, &buffer); + + void* dest; + vmaMapMemory(device->allocator, buffer.allocation, &dest); + memcpy(dest, data, dataBytes); + vmaUnmapMemory(device->allocator, buffer.allocation); + + MGVK_TransitionImageLayout(device, texture, level, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + + MGVK_CopyBufferToImage(device, buffer.buffer, texture->image, x, y, level, width, height); + + MGVK_TransitionImageLayout(device, texture, level, texture->optimal_layout); + + vmaDestroyBuffer(device->allocator, buffer.buffer, buffer.allocation); +} + +void MGG_Texture_GetData(MGG_GraphicsDevice* device, MGG_Texture* texture, mgint level, mgint slice, mgint x, mgint y, mgint z, mgint width, mgint height, mgint depth, mgbyte* data, mgint dataBytes) +{ + assert(device != nullptr); + assert(texture != nullptr); + + assert(level >= 0 && level < texture->info.mipLevels); + assert(slice >= 0 && slice < texture->info.arrayLayers); + assert(x >= 0 && x < texture->info.extent.width); + assert(y >= 0 && y < texture->info.extent.height); + assert(z >= 0 && z < texture->info.extent.depth); + assert(x + width <= texture->info.extent.width); + assert(y + height <= texture->info.extent.height); + assert(z + depth <= texture->info.extent.depth); + + assert(data != nullptr); + assert(dataBytes > 0); + + bool restart_frame = false; + + const FrameCounter currentFrame = device->frame; + const FrameCounter frameIndex = currentFrame % kConcurrentFrameCount; + MGVK_FrameState& frame = device->frames[frameIndex]; + MGVK_CmdBuffer& cmd = frame.commandBuffer; + + if (texture->isTarget) + { + if (texture->frame == device->frame) + { + if (device->inRenderPass) + { + vkCmdEndRenderPass(cmd.buffer); + device->inRenderPass = false; + } + + VkResult res = vkEndCommandBuffer(cmd.buffer); + VK_CHECK_RESULT(res); + + VkFence renderFence; + { + VkFenceCreateInfo fenceCreateInfo = {}; + fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + fenceCreateInfo.flags = 0; + vkCreateFence(device->device, &fenceCreateInfo, nullptr, &renderFence); + } + + VkSubmitInfo submitInfo = {}; + submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submitInfo.commandBufferCount = 1; + submitInfo.pCommandBuffers = &cmd.buffer; + + vkQueueSubmit(device->queue, 1, &submitInfo, renderFence); + + vkWaitForFences(device->device, 1, &renderFence, VK_TRUE, UINT64_MAX); + + vkDestroyFence(device->device, renderFence, nullptr); + + restart_frame = true; + } + } + + MGG_Buffer buffer; + MGVK_BufferCreate(device, dataBytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_CPU_ONLY, &buffer); + MGVK_TransitionImageLayout(device, texture, level, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + + MGVK_CopyImageToBuffer(device, texture->image, buffer.buffer, x, y, level, width, height); + + MGVK_TransitionImageLayout(device, texture, level, texture->layout); + + void* src; + vmaMapMemory(device->allocator, buffer.allocation, &src); + memcpy(data, src, dataBytes); + vmaUnmapMemory(device->allocator, buffer.allocation); + + vmaDestroyBuffer(device->allocator, buffer.buffer, buffer.allocation); + + if (restart_frame) + MGVK_BeginFrame(cmd); +} + +MGG_InputLayout* MGG_InputLayout_Create( + MGG_GraphicsDevice* device, + mgint* strides, + mgint streamCount, + MGG_InputElement* elements, + mgint elementCount + ) +{ + assert(device != nullptr); + assert(streamCount >= 0); + assert(strides != nullptr); + assert(elements != nullptr); + assert(elementCount >= 0); + + auto layout = new MGG_InputLayout(); + + layout->streamCount = streamCount; + auto bindings = layout->bindings = new VkVertexInputBindingDescription[streamCount]; + for (int i = 0; i < streamCount; i++) + { + bindings[i].binding = i; + bindings[i].stride = strides[i]; + bindings[i].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; // Support instance rates. + } + + layout->attributeCount = elementCount; + auto attrs = layout->attributes = new VkVertexInputAttributeDescription[elementCount]; + for (int i = 0; i < elementCount; i++) + { + attrs[i].location = i; + attrs[i].binding = elements[i].VertexBufferSlot; + attrs[i].format = ToVkFormat(elements[i].Format); + attrs[i].offset = elements[i].AlignedByteOffset; + } + + return layout; +} + +void MGG_InputLayout_Destroy(MGG_GraphicsDevice* device, MGG_InputLayout* layout) +{ + assert(device != nullptr); + assert(layout != nullptr); + + if (layout == nullptr) + return; + + //remove_by_value(device->layouts, layout); + + delete [] layout->bindings; + delete [] layout->attributes; + delete layout; +} + +static const int DefaultPoolSize = 1024; + +MGG_Shader* MGG_Shader_Create(MGG_GraphicsDevice* device, MGShaderStage stage, mgbyte* bytecode, mgint sizeInBytes) +{ + assert(device != nullptr); + assert(bytecode != nullptr); + assert(sizeInBytes > 0); + + auto shader = new MGG_Shader(); + shader->stage = stage; + + // We store the pre-generated bindings info at the top of the shader bytecode data. + int uniformCount = 0; + auto& layoutBindings = shader->bindings; + { + uniformCount = *(mgint*)bytecode; bytecode += sizeof(mgint); sizeInBytes -= sizeof(mgint); + shader->uniformSlots = *(mguint*)bytecode; bytecode += sizeof(mguint); sizeInBytes -= sizeof(mguint); + shader->textureSlots = *(mguint*)bytecode; bytecode += sizeof(mguint); sizeInBytes -= sizeof(mguint); + shader->samplerSlots = *(mguint*)bytecode; bytecode += sizeof(mguint); sizeInBytes -= sizeof(mguint); + + int count = *(mgint*)bytecode; bytecode += sizeof(mgint); sizeInBytes -= sizeof(mgint); + layoutBindings.resize(count); + memcpy(layoutBindings.data(), bytecode, sizeof(VkDescriptorSetLayoutBinding) * count); + + // The shader bytecode follows. + bytecode += sizeof(VkDescriptorSetLayoutBinding) * count; + sizeInBytes -= sizeof(VkDescriptorSetLayoutBinding) * count; + } + + VkShaderModuleCreateInfo create_info = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO }; + create_info.codeSize = sizeInBytes; + create_info.pCode = (uint32_t*)bytecode; + VkResult res = vkCreateShaderModule(device->device, &create_info, NULL, &shader->module); + VK_CHECK_RESULT(res); + + shader->id = ++device->currentShaderId; + + device->all_shaders.push_back(shader); + + // If the shader has no bindings... then skip all the layout + // and descriptor setup. + if (layoutBindings.empty()) + { + shader->setLayout = nullptr; + shader->poolInfo = nullptr; + shader->pool = nullptr; + shader->writes = nullptr; + return shader; + } + + VkDescriptorSetLayoutCreateInfo layoutInfo; + memset(&layoutInfo, 0, sizeof(layoutInfo)); + layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + layoutInfo.bindingCount = layoutBindings.size(); + layoutInfo.pBindings = layoutBindings.data(); + layoutInfo.flags = 0; + + res = vkCreateDescriptorSetLayout(device->device, &layoutInfo, nullptr, &shader->setLayout); + VK_CHECK_RESULT(res); + + // Prepare the initial descriptor pool. + { + VkDescriptorPoolSize* pool_sizes = new VkDescriptorPoolSize[layoutBindings.size()]; + + for (int i = 0; i < layoutBindings.size(); i++) + { + auto& b = layoutBindings[i]; + pool_sizes[i].type = b.descriptorType; + pool_sizes[i].descriptorCount = DefaultPoolSize; + } + + shader->poolInfo = new VkDescriptorPoolCreateInfo(); + shader->poolInfo->sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + shader->poolInfo->flags = 0; + shader->poolInfo->maxSets = DefaultPoolSize; + shader->poolInfo->poolSizeCount = layoutBindings.size(); + shader->poolInfo->pPoolSizes = pool_sizes; + + res = vkCreateDescriptorPool(device->device, shader->poolInfo, nullptr, &shader->pool); + VK_CHECK_RESULT(res); + } + + // Pre-fill the free descriptor sets now. + VkDescriptorSetAllocateInfo alloc_info = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO }; + alloc_info.descriptorPool = shader->pool; + alloc_info.descriptorSetCount = 1; + alloc_info.pSetLayouts = &shader->setLayout; + for (int i = 0; i < DefaultPoolSize; i++) + { + MGVK_DescriptorInfo* info = new MGVK_DescriptorInfo; + info->frame = 0; + shader->freeSets.push(info); + + res = vkAllocateDescriptorSets(device->device, &alloc_info, &info->set); + VK_CHECK_RESULT(res); + } + + // Prepare the write descriptor set for updates at runtime. + VkWriteDescriptorSet* write = shader->writes = new VkWriteDescriptorSet[layoutBindings.size()]; + VkDescriptorBufferInfo* bufferInfo = new VkDescriptorBufferInfo[uniformCount]; + VkDescriptorImageInfo* imageInfo = new VkDescriptorImageInfo[layoutBindings.size() - uniformCount]; + for (int i = 0; i < layoutBindings.size(); i++) + { + auto& b = layoutBindings[i]; + + if (b.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) + { + bufferInfo->buffer = NULL; + bufferInfo->offset = 0; + bufferInfo->range = VK_WHOLE_SIZE; + + write->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + write->pNext = nullptr; + write->dstSet = nullptr; + write->dstBinding = b.binding; + write->dstArrayElement = 0; + write->descriptorType = b.descriptorType; + write->descriptorCount = 1; + write->pImageInfo = nullptr; + write->pBufferInfo = bufferInfo++; + write->pTexelBufferView = nullptr; + + write++; + } + else if (b.descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) + { + imageInfo->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + imageInfo->imageView = nullptr; + imageInfo->sampler = nullptr; + + write->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + write->pNext = nullptr; + write->dstSet = nullptr; + write->dstBinding = b.binding; + write->dstArrayElement = 0; + write->descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + write->descriptorCount = 1; + write->pImageInfo = imageInfo++; + write->pBufferInfo = nullptr; + write->pTexelBufferView = nullptr; + + write++; + } + else + { + assert(0); + } + } + + return shader; +} + +void MGG_Shader_Destroy(MGG_GraphicsDevice* device, MGG_Shader* shader) +{ + assert(device != nullptr); + assert(shader != nullptr); + + if (!shader) + return; + + for (auto pair : shader->usedSets) + { + //vkFreeDescriptorSets(device->device, shader->pool, 1, &pair.second->set); + delete pair.second; + } + + while (shader->freeSets.size() > 0) + { + auto free = shader->freeSets.front(); + shader->freeSets.pop(); + + //vkFreeDescriptorSets(device->device, shader->pool, 1, &free->set); + delete free; + } + + vkDestroyDescriptorSetLayout(device->device, shader->setLayout, nullptr); + + vkDestroyDescriptorPool(device->device, shader->pool, nullptr); + delete shader->poolInfo; + + vkDestroyShaderModule(device->device, shader->module, nullptr); + + mg_remove(device->all_shaders, shader); + delete shader; +} + +MGG_OcclusionQuery* MGG_OcclusionQuery_Create(MGG_GraphicsDevice* device) +{ + assert(device != nullptr); + + auto query = new MGG_OcclusionQuery(); + + // TODO: Implement! + + return query; +} + +void MGG_OcclusionQuery_Destroy(MGG_GraphicsDevice* device, MGG_OcclusionQuery* query) +{ + assert(device != nullptr); + assert(query != nullptr); + + if (!query) + return; + + // TODO: Implement! + + delete query; +} + +void MGG_OcclusionQuery_Begin(MGG_GraphicsDevice* device, MGG_OcclusionQuery* query) +{ + assert(device != nullptr); + assert(query != nullptr); + + // TODO: Implement! +} + +void MGG_OcclusionQuery_End(MGG_GraphicsDevice* device, MGG_OcclusionQuery* query) +{ + assert(device != nullptr); + assert(query != nullptr); + + // TODO: Implement! +} + +mgbool MGG_OcclusionQuery_GetResult(MGG_GraphicsDevice* device, MGG_OcclusionQuery* query, mgint& pixelCount) +{ + assert(device != nullptr); + assert(query != nullptr); + + // TODO: Implement! + + pixelCount = 0; + return true; +} diff --git a/native/monogame/vulkan/RebuildMGFX.bat b/native/monogame/vulkan/RebuildMGFX.bat new file mode 100644 index 00000000000..b3afe2934f6 --- /dev/null +++ b/native/monogame/vulkan/RebuildMGFX.bat @@ -0,0 +1,19 @@ +@echo off +setlocal + +SET MGFXC="..\..\..\Artifacts\MonoGame.Effect.Compiler\Release\mgfxc.exe" + +echo --------------------------------------------------------------- +echo Vulkan +echo --------------------------------------------------------------- +echo. +@for /f %%f IN ('dir /b ..\..\..\MonoGame.Framework\Platform\Graphics\Effect\Resources\*.fx') do ( + + echo %%~f + call %MGFXC% "..\..\..\MonoGame.Framework\Platform\Graphics\Effect\Resources\%%~f" %%~nf.vk.mgfxo /Profile:Vulkan + echo. +) +echo. + +endlocal +pause diff --git a/native/monogame/vulkan/SkinnedEffect.vk.mgfxo b/native/monogame/vulkan/SkinnedEffect.vk.mgfxo new file mode 100644 index 00000000000..534251a64a1 Binary files /dev/null and b/native/monogame/vulkan/SkinnedEffect.vk.mgfxo differ diff --git a/native/monogame/vulkan/SpriteEffect.vk.mgfxo b/native/monogame/vulkan/SpriteEffect.vk.mgfxo new file mode 100644 index 00000000000..2383a818181 Binary files /dev/null and b/native/monogame/vulkan/SpriteEffect.vk.mgfxo differ diff --git a/native/monogame/vulkan/vk_mem_alloc.natvis b/native/monogame/vulkan/vk_mem_alloc.natvis new file mode 100644 index 00000000000..85c75335f80 --- /dev/null +++ b/native/monogame/vulkan/vk_mem_alloc.natvis @@ -0,0 +1,40 @@ + + + + {{ Count={m_Count} }} + + m_Count + + m_Count + m_pFront + pNext + Value + + + + + + {{ Count={m_RawList.m_Count} }} + + m_RawList.m_Count + + m_RawList.m_Count + m_RawList.m_pFront + pNext + Value + + + + + + {{ Count={m_Count} }} + + m_Count + m_Capacity + + m_Count + m_pArray + + + + \ No newline at end of file diff --git a/native/monogame/vulkan/vulkan.rc b/native/monogame/vulkan/vulkan.rc new file mode 100644 index 00000000000..5327f4840d5 Binary files /dev/null and b/native/monogame/vulkan/vulkan.rc differ diff --git a/native/monogame/vulkan/vulkan.resources.h b/native/monogame/vulkan/vulkan.resources.h new file mode 100644 index 00000000000..20d35c03704 --- /dev/null +++ b/native/monogame/vulkan/vulkan.resources.h @@ -0,0 +1,11 @@ +// MonoGame - Copyright (C) The MonoGame Team +// This file is subject to the terms and conditions defined in +// file 'LICENSE.txt', which is part of this source code package. + + +#define C_AlphaTestEffect 7001 +#define C_BasicEffect 7002 +#define C_DualTextureEffect 7003 +#define C_EnvironmentMapEffect 7004 +#define C_SkinnedEffect 7005 +#define C_SpriteEffect 7006