diff --git a/.gitignore b/.gitignore index 65dc397..874e8a3 100644 --- a/.gitignore +++ b/.gitignore @@ -136,6 +136,8 @@ UpgradeLog*.htm App_Data/*.mdf App_Data/*.ldf +.vs/ + ############# ## Windows detritus ############# @@ -166,4 +168,5 @@ Temp_Lightmap.dds imgui.ini # Sublime -*.sublime-workspace \ No newline at end of file +*.sublime-workspace +*.args.json \ No newline at end of file diff --git a/BindlessDeferred/AppConfig.h b/BindlessDeferred/AppConfig.h index 1669a28..28a6edb 100644 --- a/BindlessDeferred/AppConfig.h +++ b/BindlessDeferred/AppConfig.h @@ -1,12 +1,13 @@ -//================================================================================================= -// -// Bindless Deferred Texturing Sample -// by MJP -// http://mynameismjp.wordpress.com/ -// -// All code and content licensed under the MIT license -// -//================================================================================================= - -#define EnableSkyModel_ (1) -#define EnableEmbree_ (0) \ No newline at end of file +//================================================================================================= +// +// Bindless Deferred Texturing Sample +// by MJP +// http://mynameismjp.wordpress.com/ +// +// All code and content licensed under the MIT license +// +//================================================================================================= + +#define EnableSkyModel_ (1) +#define EnableEmbree_ (0) +#define EnableShaderModel6_ (1) \ No newline at end of file diff --git a/BindlessDeferred/AppSettings.cpp b/BindlessDeferred/AppSettings.cpp index b15fe65..e3d64ff 100644 --- a/BindlessDeferred/AppSettings.cpp +++ b/BindlessDeferred/AppSettings.cpp @@ -1,242 +1,252 @@ -#include -#include "AppSettings.h" - -using namespace SampleFramework12; - -static const char* MSAAModesLabels[] = -{ - "None", - "2x", - "4x", -}; - -static const char* ScenesLabels[] = -{ - "Sponza", -}; - -static const char* RenderModesLabels[] = -{ - "Clustered Forward", - "Deferred Texturing", -}; - -static const char* ClusterRasterizationModesLabels[] = -{ - "Normal", - "MSAA4x", - "MSAA8x", - "Conservative", -}; - -namespace AppSettings -{ - static SettingsContainer Settings; - - BoolSetting EnableSun; - BoolSetting SunAreaLightApproximation; - FloatSetting SunSize; - DirectionSetting SunDirection; - FloatSetting Turbidity; - ColorSetting GroundAlbedo; - MSAAModesSetting MSAAMode; - ScenesSetting CurrentScene; - BoolSetting RenderLights; - BoolSetting RenderDecals; - Button ClearDecals; - BoolSetting EnableDecalPicker; - RenderModesSetting RenderMode; - BoolSetting DepthPrepass; - BoolSetting SortByDepth; - IntSetting MaxLightClamp; - ClusterRasterizationModesSetting ClusterRasterizationMode; - BoolSetting UseZGradientsForMSAAMask; - BoolSetting ComputeUVGradients; - FloatSetting Exposure; - FloatSetting BloomExposure; - FloatSetting BloomMagnitude; - FloatSetting BloomBlurSigma; - BoolSetting EnableVSync; - BoolSetting EnableAlbedoMaps; - BoolSetting EnableNormalMaps; - BoolSetting EnableSpecular; - BoolSetting ShowLightCounts; - BoolSetting ShowDecalCounts; - BoolSetting ShowClusterVisualizer; - BoolSetting ShowMSAAMask; - BoolSetting ShowUVGradients; - - ConstantBuffer CBuffer; - const uint32 CBufferRegister = 12; - - void Initialize() - { - - Settings.Initialize(6); - - Settings.AddGroup("Sun And Sky", true); - - Settings.AddGroup("Anti Aliasing", true); - - Settings.AddGroup("Scene", true); - - Settings.AddGroup("Rendering", true); - - Settings.AddGroup("Post Processing", false); - - Settings.AddGroup("Debug", true); - - EnableSun.Initialize("EnableSun", "Sun And Sky", "Enable Sun", "Enables the sun light", true); - Settings.AddSetting(&EnableSun); - - SunAreaLightApproximation.Initialize("SunAreaLightApproximation", "Sun And Sky", "Sun Area Light Approximation", "Controls whether the sun is treated as a disc area light in the real-time shader", true); - Settings.AddSetting(&SunAreaLightApproximation); - - SunSize.Initialize("SunSize", "Sun And Sky", "Sun Size", "Angular radius of the sun in degrees", 1.0000f, 0.0100f, 340282300000000000000000000000000000000.0000f, 0.0100f, ConversionMode::None, 1.0000f); - Settings.AddSetting(&SunSize); - - SunDirection.Initialize("SunDirection", "Sun And Sky", "Sun Direction", "Direction of the sun", Float3(0.2600f, 0.9870f, -0.1600f), true); - Settings.AddSetting(&SunDirection); - - Turbidity.Initialize("Turbidity", "Sun And Sky", "Turbidity", "Atmospheric turbidity (thickness) uses for procedural sun and sky model", 2.0000f, 1.0000f, 10.0000f, 0.0100f, ConversionMode::None, 1.0000f); - Settings.AddSetting(&Turbidity); - - GroundAlbedo.Initialize("GroundAlbedo", "Sun And Sky", "Ground Albedo", "Ground albedo color used for procedural sun and sky model", Float3(0.2500f, 0.2500f, 0.2500f), false, -340282300000000000000000000000000000000.0000f, 340282300000000000000000000000000000000.0000f, 0.0100f, ColorUnit::None); - Settings.AddSetting(&GroundAlbedo); - - MSAAMode.Initialize("MSAAMode", "Anti Aliasing", "MSAAMode", "MSAA mode to use for rendering", MSAAModes::MSAANone, 3, MSAAModesLabels); - Settings.AddSetting(&MSAAMode); - - CurrentScene.Initialize("CurrentScene", "Scene", "Current Scene", "", Scenes::Sponza, 1, ScenesLabels); - Settings.AddSetting(&CurrentScene); - - RenderLights.Initialize("RenderLights", "Scene", "Render Lights", "Enable or disable deferred light rendering", true); - Settings.AddSetting(&RenderLights); - - RenderDecals.Initialize("RenderDecals", "Scene", "Render Decals", "Enable or disable applying decals in the main pass", true); - Settings.AddSetting(&RenderDecals); - - ClearDecals.Initialize("ClearDecals", "Scene", "Clear Decals", ""); - Settings.AddSetting(&ClearDecals); - - EnableDecalPicker.Initialize("EnableDecalPicker", "Scene", "Enable Decal Picker", "Enables or disables placing new decals with the mouse", true); - Settings.AddSetting(&EnableDecalPicker); - - RenderMode.Initialize("RenderMode", "Rendering", "Render Mode", "The rendering technique to use", RenderModes::DeferredTexturing, 2, RenderModesLabels); - Settings.AddSetting(&RenderMode); - - DepthPrepass.Initialize("DepthPrepass", "Rendering", "Depth Prepass", "Renders a depth prepass before the main pass or G-Buffer pass", false); - Settings.AddSetting(&DepthPrepass); - - SortByDepth.Initialize("SortByDepth", "Rendering", "Sort By Depth", "Enables sorting meshes by their depth in front-to-back order", true); - Settings.AddSetting(&SortByDepth); - - MaxLightClamp.Initialize("MaxLightClamp", "Rendering", "Max Lights", "Limits the number of lights in the scene", 32, 0, 32); - Settings.AddSetting(&MaxLightClamp); - - ClusterRasterizationMode.Initialize("ClusterRasterizationMode", "Rendering", "Cluster Rasterization Mode", "Conservative rasterization mode to use for light binning", ClusterRasterizationModes::Conservative, 4, ClusterRasterizationModesLabels); - Settings.AddSetting(&ClusterRasterizationMode); - - UseZGradientsForMSAAMask.Initialize("UseZGradientsForMSAAMask", "Rendering", "Use Z DX/DY For MSAA Mask", "Use Z gradients to detect edges during MSAA mask generation", false); - Settings.AddSetting(&UseZGradientsForMSAAMask); - - ComputeUVGradients.Initialize("ComputeUVGradients", "Rendering", "Compute UV Gradients", "Choose whether to compute UV gradients for deferred rendering, or explicitly store them in the G-Buffer", false); - Settings.AddSetting(&ComputeUVGradients); - - Exposure.Initialize("Exposure", "Post Processing", "Exposure", "Simple exposure value applied to the scene before tone mapping (uses log2 scale)", -14.0000f, -24.0000f, 24.0000f, 0.1000f, ConversionMode::None, 1.0000f); - Settings.AddSetting(&Exposure); - - BloomExposure.Initialize("BloomExposure", "Post Processing", "Bloom Exposure Offset", "Exposure offset applied to generate the input of the bloom pass", -4.0000f, -10.0000f, 0.0000f, 0.0100f, ConversionMode::None, 1.0000f); - Settings.AddSetting(&BloomExposure); - - BloomMagnitude.Initialize("BloomMagnitude", "Post Processing", "Bloom Magnitude", "Scale factor applied to the bloom results when combined with tone-mapped result", 1.0000f, 0.0000f, 2.0000f, 0.0100f, ConversionMode::None, 1.0000f); - Settings.AddSetting(&BloomMagnitude); - - BloomBlurSigma.Initialize("BloomBlurSigma", "Post Processing", "Bloom Blur Sigma", "Sigma parameter of the Gaussian filter used in the bloom pass", 2.5000f, 0.5000f, 2.5000f, 0.0100f, ConversionMode::None, 1.0000f); - Settings.AddSetting(&BloomBlurSigma); - - EnableVSync.Initialize("EnableVSync", "Debug", "Enable VSync", "Enables or disables vertical sync during Present", true); - Settings.AddSetting(&EnableVSync); - - EnableAlbedoMaps.Initialize("EnableAlbedoMaps", "Debug", "Enable Albedo Maps", "Enables albedo maps", true); - Settings.AddSetting(&EnableAlbedoMaps); - - EnableNormalMaps.Initialize("EnableNormalMaps", "Debug", "Enable Normal Maps", "Enables normal maps", true); - Settings.AddSetting(&EnableNormalMaps); - - EnableSpecular.Initialize("EnableSpecular", "Debug", "Enable Specular", "Enables specular reflections", true); - Settings.AddSetting(&EnableSpecular); - - ShowLightCounts.Initialize("ShowLightCounts", "Debug", "Show Light Counts", "Visualizes the light count for a pixel", false); - Settings.AddSetting(&ShowLightCounts); - - ShowDecalCounts.Initialize("ShowDecalCounts", "Debug", "Show Decal Counts", "Visualizes the decal count for a pixel", false); - Settings.AddSetting(&ShowDecalCounts); - - ShowClusterVisualizer.Initialize("ShowClusterVisualizer", "Debug", "Show Cluster Visualizer", "Shows an overhead perspective of the view frustum with a visualization of the light/decal counts", false); - Settings.AddSetting(&ShowClusterVisualizer); - - ShowMSAAMask.Initialize("ShowMSAAMask", "Debug", "Show MSAA Mask", "Visualizes the pixels where per-sample shading is applied", false); - Settings.AddSetting(&ShowMSAAMask); - - ShowUVGradients.Initialize("ShowUVGradients", "Debug", "Show UV Gradients", "Visualize the UV gradients used for mip selection", false); - Settings.AddSetting(&ShowUVGradients); - - CBuffer.Initialize(BufferLifetime::Temporary); - } - - void Update(uint32 displayWidth, uint32 displayHeight, const Float4x4& viewMatrix) - { - Settings.Update(displayWidth, displayHeight, viewMatrix); - - } - - void UpdateCBuffer() - { - CBuffer.Data.EnableSun = EnableSun; - CBuffer.Data.SunAreaLightApproximation = SunAreaLightApproximation; - CBuffer.Data.SunSize = SunSize; - CBuffer.Data.SunDirection = SunDirection; - CBuffer.Data.MSAAMode = MSAAMode; - CBuffer.Data.RenderLights = RenderLights; - CBuffer.Data.RenderDecals = RenderDecals; - CBuffer.Data.RenderMode = RenderMode; - CBuffer.Data.Exposure = Exposure; - CBuffer.Data.BloomExposure = BloomExposure; - CBuffer.Data.BloomMagnitude = BloomMagnitude; - CBuffer.Data.BloomBlurSigma = BloomBlurSigma; - CBuffer.Data.EnableAlbedoMaps = EnableAlbedoMaps; - CBuffer.Data.EnableNormalMaps = EnableNormalMaps; - CBuffer.Data.EnableSpecular = EnableSpecular; - CBuffer.Data.ShowLightCounts = ShowLightCounts; - CBuffer.Data.ShowDecalCounts = ShowDecalCounts; - CBuffer.Data.ShowMSAAMask = ShowMSAAMask; - CBuffer.Data.ShowUVGradients = ShowUVGradients; - - CBuffer.Upload(); - } - void BindCBufferGfx(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter) - { - CBuffer.SetAsGfxRootParameter(cmdList, rootParameter); - } - void BindCBufferCompute(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter) - { - CBuffer.SetAsComputeRootParameter(cmdList, rootParameter); - } - void Shutdown() - { - CBuffer.Shutdown(); - } -} - -// ================================================================================================ - -namespace AppSettings -{ - uint64 NumXTiles = 0; - uint64 NumYTiles = 0; - - void UpdateUI() - { - } +#include +#include "AppSettings.h" + +using namespace SampleFramework12; + +static const char* MSAAModesLabels[] = +{ + "None", + "2x", + "4x", +}; + +static const char* ScenesLabels[] = +{ + "Sponza", +}; + +static const char* RenderModesLabels[] = +{ + "Clustered Forward", + "Deferred Texturing", +}; + +static const char* ClusterRasterizationModesLabels[] = +{ + "Normal", + "MSAA4x", + "MSAA8x", + "Conservative", +}; + +namespace AppSettings +{ + static SettingsContainer Settings; + + BoolSetting EnableSun; + BoolSetting SunAreaLightApproximation; + FloatSetting SunSize; + DirectionSetting SunDirection; + FloatSetting Turbidity; + ColorSetting GroundAlbedo; + MSAAModesSetting MSAAMode; + ScenesSetting CurrentScene; + BoolSetting RenderLights; + BoolSetting RenderDecals; + Button ClearDecals; + BoolSetting EnableDecalPicker; + RenderModesSetting RenderMode; + BoolSetting DepthPrepass; + BoolSetting SortByDepth; + IntSetting MaxLightClamp; + ClusterRasterizationModesSetting ClusterRasterizationMode; + BoolSetting UseZGradientsForMSAAMask; + BoolSetting ComputeUVGradients; + FloatSetting Exposure; + FloatSetting BloomExposure; + FloatSetting BloomMagnitude; + FloatSetting BloomBlurSigma; + BoolSetting EnableVSync; + BoolSetting EnableAlbedoMaps; + BoolSetting EnableNormalMaps; + BoolSetting EnableSpecular; + BoolSetting ShowLightCounts; + BoolSetting ShowDecalCounts; + BoolSetting ShowClusterVisualizer; + BoolSetting ShowMSAAMask; + BoolSetting ShowUVGradients; + BoolSetting AnimateLightIntensity; + + ConstantBuffer CBuffer; + const uint32 CBufferRegister = 12; + + void Initialize() + { + + Settings.Initialize(6); + + Settings.AddGroup("Sun And Sky", true); + + Settings.AddGroup("Anti Aliasing", true); + + Settings.AddGroup("Scene", true); + + Settings.AddGroup("Rendering", true); + + Settings.AddGroup("Post Processing", false); + + Settings.AddGroup("Debug", true); + + EnableSun.Initialize("EnableSun", "Sun And Sky", "Enable Sun", "Enables the sun light", true); + Settings.AddSetting(&EnableSun); + + SunAreaLightApproximation.Initialize("SunAreaLightApproximation", "Sun And Sky", "Sun Area Light Approximation", "Controls whether the sun is treated as a disc area light in the real-time shader", true); + Settings.AddSetting(&SunAreaLightApproximation); + + SunSize.Initialize("SunSize", "Sun And Sky", "Sun Size", "Angular radius of the sun in degrees", 1.0000f, 0.0100f, 340282300000000000000000000000000000000.0000f, 0.0100f, ConversionMode::None, 1.0000f); + Settings.AddSetting(&SunSize); + + SunDirection.Initialize("SunDirection", "Sun And Sky", "Sun Direction", "Direction of the sun", Float3(0.2600f, 0.9870f, -0.1600f), true); + Settings.AddSetting(&SunDirection); + + Turbidity.Initialize("Turbidity", "Sun And Sky", "Turbidity", "Atmospheric turbidity (thickness) uses for procedural sun and sky model", 2.0000f, 1.0000f, 10.0000f, 0.0100f, ConversionMode::None, 1.0000f); + Settings.AddSetting(&Turbidity); + + GroundAlbedo.Initialize("GroundAlbedo", "Sun And Sky", "Ground Albedo", "Ground albedo color used for procedural sun and sky model", Float3(0.2500f, 0.2500f, 0.2500f), false, -340282300000000000000000000000000000000.0000f, 340282300000000000000000000000000000000.0000f, 0.0100f, ColorUnit::None); + Settings.AddSetting(&GroundAlbedo); + + MSAAMode.Initialize("MSAAMode", "Anti Aliasing", "MSAA Mode", "MSAA mode to use for rendering", MSAAModes::MSAANone, 3, MSAAModesLabels); + Settings.AddSetting(&MSAAMode); + + CurrentScene.Initialize("CurrentScene", "Scene", "Current Scene", "", Scenes::Sponza, 1, ScenesLabels); + Settings.AddSetting(&CurrentScene); + + RenderLights.Initialize("RenderLights", "Scene", "Render Lights", "Enable or disable deferred light rendering", true); + Settings.AddSetting(&RenderLights); + + RenderDecals.Initialize("RenderDecals", "Scene", "Render Decals", "Enable or disable applying decals in the main pass", true); + Settings.AddSetting(&RenderDecals); + + ClearDecals.Initialize("ClearDecals", "Scene", "Clear Decals", ""); + Settings.AddSetting(&ClearDecals); + + EnableDecalPicker.Initialize("EnableDecalPicker", "Scene", "Enable Decal Picker", "Enables or disables placing new decals with the mouse", true); + Settings.AddSetting(&EnableDecalPicker); + + RenderMode.Initialize("RenderMode", "Rendering", "Render Mode", "The rendering technique to use", RenderModes::DeferredTexturing, 2, RenderModesLabels); + Settings.AddSetting(&RenderMode); + + DepthPrepass.Initialize("DepthPrepass", "Rendering", "Depth Prepass", "Renders a depth prepass before the main pass or G-Buffer pass", false); + Settings.AddSetting(&DepthPrepass); + + SortByDepth.Initialize("SortByDepth", "Rendering", "Sort By Depth", "Enables sorting meshes by their depth in front-to-back order", true); + Settings.AddSetting(&SortByDepth); + + MaxLightClamp.Initialize("MaxLightClamp", "Rendering", "Max Lights", "Limits the number of lights in the scene", 32, 0, 32); + Settings.AddSetting(&MaxLightClamp); + + ClusterRasterizationMode.Initialize("ClusterRasterizationMode", "Rendering", "Cluster Rasterization Mode", "Conservative rasterization mode to use for light binning", ClusterRasterizationModes::Conservative, 4, ClusterRasterizationModesLabels); + Settings.AddSetting(&ClusterRasterizationMode); + + UseZGradientsForMSAAMask.Initialize("UseZGradientsForMSAAMask", "Rendering", "Use Z DX/DY For MSAA Mask", "Use Z gradients to detect edges during MSAA mask generation", false); + Settings.AddSetting(&UseZGradientsForMSAAMask); + + ComputeUVGradients.Initialize("ComputeUVGradients", "Rendering", "Compute UV Gradients", "Choose whether to compute UV gradients for deferred rendering, or explicitly store them in the G-Buffer", false); + Settings.AddSetting(&ComputeUVGradients); + + Exposure.Initialize("Exposure", "Post Processing", "Exposure", "Simple exposure value applied to the scene before tone mapping (uses log2 scale)", -14.0000f, -24.0000f, 24.0000f, 0.1000f, ConversionMode::None, 1.0000f); + Settings.AddSetting(&Exposure); + + BloomExposure.Initialize("BloomExposure", "Post Processing", "Bloom Exposure Offset", "Exposure offset applied to generate the input of the bloom pass", -4.0000f, -10.0000f, 0.0000f, 0.0100f, ConversionMode::None, 1.0000f); + Settings.AddSetting(&BloomExposure); + + BloomMagnitude.Initialize("BloomMagnitude", "Post Processing", "Bloom Magnitude", "Scale factor applied to the bloom results when combined with tone-mapped result", 1.0000f, 0.0000f, 2.0000f, 0.0100f, ConversionMode::None, 1.0000f); + Settings.AddSetting(&BloomMagnitude); + + BloomBlurSigma.Initialize("BloomBlurSigma", "Post Processing", "Bloom Blur Sigma", "Sigma parameter of the Gaussian filter used in the bloom pass", 2.5000f, 0.5000f, 2.5000f, 0.0100f, ConversionMode::None, 1.0000f); + Settings.AddSetting(&BloomBlurSigma); + + EnableVSync.Initialize("EnableVSync", "Debug", "Enable VSync", "Enables or disables vertical sync during Present", true); + Settings.AddSetting(&EnableVSync); + + EnableAlbedoMaps.Initialize("EnableAlbedoMaps", "Debug", "Enable Albedo Maps", "Enables albedo maps", true); + Settings.AddSetting(&EnableAlbedoMaps); + + EnableNormalMaps.Initialize("EnableNormalMaps", "Debug", "Enable Normal Maps", "Enables normal maps", true); + Settings.AddSetting(&EnableNormalMaps); + + EnableSpecular.Initialize("EnableSpecular", "Debug", "Enable Specular", "Enables specular reflections", true); + Settings.AddSetting(&EnableSpecular); + + ShowLightCounts.Initialize("ShowLightCounts", "Debug", "Show Light Counts", "Visualizes the light count for a pixel", false); + Settings.AddSetting(&ShowLightCounts); + + ShowDecalCounts.Initialize("ShowDecalCounts", "Debug", "Show Decal Counts", "Visualizes the decal count for a pixel", false); + Settings.AddSetting(&ShowDecalCounts); + + ShowClusterVisualizer.Initialize("ShowClusterVisualizer", "Debug", "Show Cluster Visualizer", "Shows an overhead perspective of the view frustum with a visualization of the light/decal counts", false); + Settings.AddSetting(&ShowClusterVisualizer); + + ShowMSAAMask.Initialize("ShowMSAAMask", "Debug", "Show MSAA Mask", "Visualizes the pixels where per-sample shading is applied", false); + Settings.AddSetting(&ShowMSAAMask); + + ShowUVGradients.Initialize("ShowUVGradients", "Debug", "Show UV Gradients", "Visualize the UV gradients used for mip selection", false); + Settings.AddSetting(&ShowUVGradients); + + AnimateLightIntensity.Initialize("AnimateLightIntensity", "Debug", "Animate Light Intensity", "Modulates the light intensity to test buffer uploads", false); + Settings.AddSetting(&AnimateLightIntensity); + + ConstantBufferInit cbInit; + cbInit.Size = sizeof(AppSettingsCBuffer); + cbInit.Dynamic = true; + cbInit.Name = L"AppSettings Constant Buffer"; + CBuffer.Initialize(cbInit); + } + + void Update(uint32 displayWidth, uint32 displayHeight, const Float4x4& viewMatrix) + { + Settings.Update(displayWidth, displayHeight, viewMatrix); + + } + + void UpdateCBuffer() + { + AppSettingsCBuffer cbData; + cbData.EnableSun = EnableSun; + cbData.SunAreaLightApproximation = SunAreaLightApproximation; + cbData.SunSize = SunSize; + cbData.SunDirection = SunDirection; + cbData.MSAAMode = MSAAMode; + cbData.RenderLights = RenderLights; + cbData.RenderDecals = RenderDecals; + cbData.RenderMode = RenderMode; + cbData.Exposure = Exposure; + cbData.BloomExposure = BloomExposure; + cbData.BloomMagnitude = BloomMagnitude; + cbData.BloomBlurSigma = BloomBlurSigma; + cbData.EnableAlbedoMaps = EnableAlbedoMaps; + cbData.EnableNormalMaps = EnableNormalMaps; + cbData.EnableSpecular = EnableSpecular; + cbData.ShowLightCounts = ShowLightCounts; + cbData.ShowDecalCounts = ShowDecalCounts; + cbData.ShowMSAAMask = ShowMSAAMask; + cbData.ShowUVGradients = ShowUVGradients; + cbData.AnimateLightIntensity = AnimateLightIntensity; + + CBuffer.MapAndSetData(cbData); + } + void BindCBufferGfx(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter) + { + CBuffer.SetAsGfxRootParameter(cmdList, rootParameter); + } + void BindCBufferCompute(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter) + { + CBuffer.SetAsComputeRootParameter(cmdList, rootParameter); + } + void Shutdown() + { + CBuffer.Shutdown(); + } +} + +// ================================================================================================ + +namespace AppSettings +{ + uint64 NumXTiles = 0; + uint64 NumYTiles = 0; + + void UpdateUI() + { + } } \ No newline at end of file diff --git a/BindlessDeferred/AppSettings.cs b/BindlessDeferred/AppSettings.cs index f934dbe..587d84b 100644 --- a/BindlessDeferred/AppSettings.cs +++ b/BindlessDeferred/AppSettings.cs @@ -1,215 +1,221 @@ -enum Scenes -{ - Sponza = 0, -} - -enum MSAAModes -{ - [EnumLabel("None")] - MSAANone = 0, - - [EnumLabel("2x")] - MSAA2x, - - [EnumLabel("4x")] - MSAA4x, -} - -enum RenderModes -{ - [EnumLabel("Clustered Forward")] - ClusteredForward = 0, - - [EnumLabel("Deferred Texturing")] - DeferredTexturing, -} - -enum ClusterRasterizationModes -{ - Normal, - MSAA4x, - MSAA8x, - Conservative -} - -public class Settings -{ - [ExpandGroup(true)] - public class SunAndSky - { - [HelpText("Enables the sun light")] - bool EnableSun = true; - - [HelpText("Controls whether the sun is treated as a disc area light in the real-time shader")] - bool SunAreaLightApproximation = true; - - [HelpText("Angular radius of the sun in degrees")] - [MinValue(0.01f)] - [StepSize(0.01f)] - float SunSize = 1.0f; - - [HelpText("Direction of the sun")] - [DisplayInViewSpaceAttribute(true)] - Direction SunDirection = new Direction(0.26f, 0.987f, -0.16f); - - [MinValue(1.0f)] - [MaxValue(10.0f)] - [UseAsShaderConstant(false)] - [HelpText("Atmospheric turbidity (thickness) uses for procedural sun and sky model")] - float Turbidity = 2.0f; - - [HDR(false)] - [UseAsShaderConstant(false)] - [HelpText("Ground albedo color used for procedural sun and sky model")] - Color GroundAlbedo = new Color(0.25f, 0.25f, 0.25f); - } - - [ExpandGroup(true)] - public class AntiAliasing - { - [HelpText("MSAA mode to use for rendering")] - MSAAModes MSAAMode = MSAAModes.MSAANone; - } - - [ExpandGroup(true)] - public class Scene - { - [UseAsShaderConstant(false)] - Scenes CurrentScene = Scenes.Sponza; - - [HelpText("Enable or disable deferred light rendering")] - bool RenderLights = true; - - [HelpText("Enable or disable applying decals in the main pass")] - bool RenderDecals = true; - - Button ClearDecals; - - [HelpText("Enables or disables placing new decals with the mouse")] - [UseAsShaderConstant(false)] - bool EnableDecalPicker = true; - } - - const uint ClusterTileSize = 16; - const uint NumZTiles = 16; - - const uint NumDecalTypes = 8; - const uint NumTexturesPerDecal = 2; - const uint NumDecalTextures = NumDecalTypes * NumTexturesPerDecal; - const uint MaxDecals = 64; - const uint DecalElementsPerCluster = MaxDecals / 32; - - const uint MaxSpotLights = 32; - const uint SpotLightElementsPerCluster = MaxSpotLights / 32; - const float SpotLightRange = 7.5f; - - const uint DeferredTileSize = 8; - const uint DeferredTileMaskSize = (DeferredTileSize * DeferredTileSize) / 32; - - const float DeferredUVScale = 2.0f; - - [ExpandGroup(true)] - public class Rendering - { - [HelpText("The rendering technique to use")] - RenderModes RenderMode = RenderModes.DeferredTexturing; - - [UseAsShaderConstant(false)] - [HelpText("Renders a depth prepass before the main pass or G-Buffer pass")] - bool DepthPrepass = false; - - [UseAsShaderConstant(false)] - [HelpText("Enables sorting meshes by their depth in front-to-back order")] - bool SortByDepth = true; - - [UseAsShaderConstant(false)] - [MinValue(0)] - [MaxValue((int)MaxSpotLights)] - [DisplayName("Max Lights")] - [HelpText("Limits the number of lights in the scene")] - int MaxLightClamp = (int)MaxSpotLights; - - [UseAsShaderConstant(false)] - [HelpText("Conservative rasterization mode to use for light binning")] - ClusterRasterizationModes ClusterRasterizationMode = ClusterRasterizationModes.Conservative; - - [DisplayName("Use Z DX/DY For MSAA Mask")] - [UseAsShaderConstant(false)] - [HelpText("Use Z gradients to detect edges during MSAA mask generation")] - bool UseZGradientsForMSAAMask = false; - - [DisplayName("Compute UV Gradients")] - [UseAsShaderConstant(false)] - [HelpText("Choose whether to compute UV gradients for deferred rendering, or explicitly store them in the G-Buffer")] - bool ComputeUVGradients = false; - } - - [ExpandGroup(false)] - public class PostProcessing - { - [MinValue(-24.0f)] - [MaxValue(24.0f)] - [StepSize(0.1f)] - [HelpText("Simple exposure value applied to the scene before tone mapping (uses log2 scale)")] - float Exposure = -14.0f; - - [DisplayName("Bloom Exposure Offset")] - [MinValue(-10.0f)] - [MaxValue(0.0f)] - [StepSize(0.01f)] - [HelpText("Exposure offset applied to generate the input of the bloom pass")] - float BloomExposure = -4.0f; - - [DisplayName("Bloom Magnitude")] - [MinValue(0.0f)] - [MaxValue(2.0f)] - [StepSize(0.01f)] - [HelpText("Scale factor applied to the bloom results when combined with tone-mapped result")] - float BloomMagnitude = 1.0f; - - [DisplayName("Bloom Blur Sigma")] - [MinValue(0.5f)] - [MaxValue(2.5f)] - [StepSize(0.01f)] - [HelpText("Sigma parameter of the Gaussian filter used in the bloom pass")] - float BloomBlurSigma = 2.5f; - } - - [ExpandGroup(true)] - public class Debug - { - [UseAsShaderConstant(false)] - [DisplayName("Enable VSync")] - [HelpText("Enables or disables vertical sync during Present")] - bool EnableVSync = true; - - [DisplayName("Enable Albedo Maps")] - [HelpText("Enables albedo maps")] - bool EnableAlbedoMaps = true; - - [DisplayName("Enable Normal Maps")] - [HelpText("Enables normal maps")] - bool EnableNormalMaps = true; - - [HelpText("Enables specular reflections")] - bool EnableSpecular = true; - - [HelpText("Visualizes the light count for a pixel")] - bool ShowLightCounts = false; - - [HelpText("Visualizes the decal count for a pixel")] - bool ShowDecalCounts = false; - - [HelpText("Shows an overhead perspective of the view frustum with a visualization of the light/decal counts")] - [UseAsShaderConstant(false)] - bool ShowClusterVisualizer = false; - - [HelpText("Visualizes the pixels where per-sample shading is applied")] - [DisplayName("Show MSAA Mask")] - bool ShowMSAAMask = false; - - [HelpText("Visualize the UV gradients used for mip selection")] - [DisplayName("Show UV Gradients")] - bool ShowUVGradients = false; - } +enum Scenes +{ + Sponza = 0, +} + +enum MSAAModes +{ + [EnumLabel("None")] + MSAANone = 0, + + [EnumLabel("2x")] + MSAA2x, + + [EnumLabel("4x")] + MSAA4x, +} + +enum RenderModes +{ + [EnumLabel("Clustered Forward")] + ClusteredForward = 0, + + [EnumLabel("Deferred Texturing")] + DeferredTexturing, +} + +enum ClusterRasterizationModes +{ + Normal, + MSAA4x, + MSAA8x, + Conservative +} + +public class Settings +{ + [ExpandGroup(true)] + public class SunAndSky + { + [HelpText("Enables the sun light")] + bool EnableSun = true; + + [HelpText("Controls whether the sun is treated as a disc area light in the real-time shader")] + bool SunAreaLightApproximation = true; + + [HelpText("Angular radius of the sun in degrees")] + [MinValue(0.01f)] + [StepSize(0.01f)] + float SunSize = 1.0f; + + [HelpText("Direction of the sun")] + [DisplayInViewSpaceAttribute(true)] + Direction SunDirection = new Direction(0.26f, 0.987f, -0.16f); + + [MinValue(1.0f)] + [MaxValue(10.0f)] + [UseAsShaderConstant(false)] + [HelpText("Atmospheric turbidity (thickness) uses for procedural sun and sky model")] + float Turbidity = 2.0f; + + [HDR(false)] + [UseAsShaderConstant(false)] + [HelpText("Ground albedo color used for procedural sun and sky model")] + Color GroundAlbedo = new Color(0.25f, 0.25f, 0.25f); + } + + [ExpandGroup(true)] + public class AntiAliasing + { + [HelpText("MSAA mode to use for rendering")] + [DisplayName("MSAA Mode")] + MSAAModes MSAAMode = MSAAModes.MSAANone; + } + + [ExpandGroup(true)] + public class Scene + { + [UseAsShaderConstant(false)] + Scenes CurrentScene = Scenes.Sponza; + + [HelpText("Enable or disable deferred light rendering")] + bool RenderLights = true; + + [HelpText("Enable or disable applying decals in the main pass")] + bool RenderDecals = true; + + Button ClearDecals; + + [HelpText("Enables or disables placing new decals with the mouse")] + [UseAsShaderConstant(false)] + bool EnableDecalPicker = true; + } + + const uint ClusterTileSize = 16; + const uint NumZTiles = 16; + + const uint NumDecalTypes = 8; + const uint NumTexturesPerDecal = 2; + const uint NumDecalTextures = NumDecalTypes * NumTexturesPerDecal; + const uint MaxDecals = 64; + const uint DecalElementsPerCluster = MaxDecals / 32; + + const uint MaxSpotLights = 32; + const uint SpotLightElementsPerCluster = MaxSpotLights / 32; + const float SpotLightRange = 7.5f; + const float SpotShadowNearClip = 0.1f; + + const uint DeferredTileSize = 8; + const uint DeferredTileMaskSize = (DeferredTileSize * DeferredTileSize) / 32; + + const float DeferredUVScale = 2.0f; + + [ExpandGroup(true)] + public class Rendering + { + [HelpText("The rendering technique to use")] + RenderModes RenderMode = RenderModes.DeferredTexturing; + + [UseAsShaderConstant(false)] + [HelpText("Renders a depth prepass before the main pass or G-Buffer pass")] + bool DepthPrepass = false; + + [UseAsShaderConstant(false)] + [HelpText("Enables sorting meshes by their depth in front-to-back order")] + bool SortByDepth = true; + + [UseAsShaderConstant(false)] + [MinValue(0)] + [MaxValue((int)MaxSpotLights)] + [DisplayName("Max Lights")] + [HelpText("Limits the number of lights in the scene")] + int MaxLightClamp = (int)MaxSpotLights; + + [UseAsShaderConstant(false)] + [HelpText("Conservative rasterization mode to use for light binning")] + ClusterRasterizationModes ClusterRasterizationMode = ClusterRasterizationModes.Conservative; + + [DisplayName("Use Z DX/DY For MSAA Mask")] + [UseAsShaderConstant(false)] + [HelpText("Use Z gradients to detect edges during MSAA mask generation")] + bool UseZGradientsForMSAAMask = false; + + [DisplayName("Compute UV Gradients")] + [UseAsShaderConstant(false)] + [HelpText("Choose whether to compute UV gradients for deferred rendering, or explicitly store them in the G-Buffer")] + bool ComputeUVGradients = false; + } + + [ExpandGroup(false)] + public class PostProcessing + { + [MinValue(-24.0f)] + [MaxValue(24.0f)] + [StepSize(0.1f)] + [HelpText("Simple exposure value applied to the scene before tone mapping (uses log2 scale)")] + float Exposure = -14.0f; + + [DisplayName("Bloom Exposure Offset")] + [MinValue(-10.0f)] + [MaxValue(0.0f)] + [StepSize(0.01f)] + [HelpText("Exposure offset applied to generate the input of the bloom pass")] + float BloomExposure = -4.0f; + + [DisplayName("Bloom Magnitude")] + [MinValue(0.0f)] + [MaxValue(2.0f)] + [StepSize(0.01f)] + [HelpText("Scale factor applied to the bloom results when combined with tone-mapped result")] + float BloomMagnitude = 1.0f; + + [DisplayName("Bloom Blur Sigma")] + [MinValue(0.5f)] + [MaxValue(2.5f)] + [StepSize(0.01f)] + [HelpText("Sigma parameter of the Gaussian filter used in the bloom pass")] + float BloomBlurSigma = 2.5f; + } + + [ExpandGroup(true)] + public class Debug + { + [UseAsShaderConstant(false)] + [DisplayName("Enable VSync")] + [HelpText("Enables or disables vertical sync during Present")] + bool EnableVSync = true; + + [DisplayName("Enable Albedo Maps")] + [HelpText("Enables albedo maps")] + bool EnableAlbedoMaps = true; + + [DisplayName("Enable Normal Maps")] + [HelpText("Enables normal maps")] + bool EnableNormalMaps = true; + + [HelpText("Enables specular reflections")] + bool EnableSpecular = true; + + [HelpText("Visualizes the light count for a pixel")] + bool ShowLightCounts = false; + + [HelpText("Visualizes the decal count for a pixel")] + bool ShowDecalCounts = false; + + [HelpText("Shows an overhead perspective of the view frustum with a visualization of the light/decal counts")] + [UseAsShaderConstant(false)] + bool ShowClusterVisualizer = false; + + [HelpText("Visualizes the pixels where per-sample shading is applied")] + [DisplayName("Show MSAA Mask")] + bool ShowMSAAMask = false; + + [HelpText("Visualize the UV gradients used for mip selection")] + [DisplayName("Show UV Gradients")] + bool ShowUVGradients = false; + + [HelpText("Modulates the light intensity to test buffer uploads")] + [DisplayName("Animate Light Intensity")] + bool AnimateLightIntensity = false; + } } \ No newline at end of file diff --git a/BindlessDeferred/AppSettings.h b/BindlessDeferred/AppSettings.h index 83317fc..4ded3af 100644 --- a/BindlessDeferred/AppSettings.h +++ b/BindlessDeferred/AppSettings.h @@ -1,156 +1,159 @@ -#pragma once - -#include -#include -#include - -using namespace SampleFramework12; - -enum class MSAAModes -{ - MSAANone = 0, - MSAA2x = 1, - MSAA4x = 2, - - NumValues -}; - -typedef EnumSettingT MSAAModesSetting; - -enum class Scenes -{ - Sponza = 0, - - NumValues -}; - -typedef EnumSettingT ScenesSetting; - -enum class RenderModes -{ - ClusteredForward = 0, - DeferredTexturing = 1, - - NumValues -}; - -typedef EnumSettingT RenderModesSetting; - -enum class ClusterRasterizationModes -{ - Normal = 0, - MSAA4x = 1, - MSAA8x = 2, - Conservative = 3, - - NumValues -}; - -typedef EnumSettingT ClusterRasterizationModesSetting; - -namespace AppSettings -{ - static const uint64 ClusterTileSize = 16; - static const uint64 NumZTiles = 16; - static const uint64 NumDecalTypes = 8; - static const uint64 NumTexturesPerDecal = 2; - static const uint64 NumDecalTextures = 16; - static const uint64 MaxDecals = 64; - static const uint64 DecalElementsPerCluster = 2; - static const uint64 MaxSpotLights = 32; - static const uint64 SpotLightElementsPerCluster = 1; - static const float SpotLightRange = 7.5000f; - static const uint64 DeferredTileSize = 8; - static const uint64 DeferredTileMaskSize = 2; - static const float DeferredUVScale = 2.0000f; - - extern BoolSetting EnableSun; - extern BoolSetting SunAreaLightApproximation; - extern FloatSetting SunSize; - extern DirectionSetting SunDirection; - extern FloatSetting Turbidity; - extern ColorSetting GroundAlbedo; - extern MSAAModesSetting MSAAMode; - extern ScenesSetting CurrentScene; - extern BoolSetting RenderLights; - extern BoolSetting RenderDecals; - extern Button ClearDecals; - extern BoolSetting EnableDecalPicker; - extern RenderModesSetting RenderMode; - extern BoolSetting DepthPrepass; - extern BoolSetting SortByDepth; - extern IntSetting MaxLightClamp; - extern ClusterRasterizationModesSetting ClusterRasterizationMode; - extern BoolSetting UseZGradientsForMSAAMask; - extern BoolSetting ComputeUVGradients; - extern FloatSetting Exposure; - extern FloatSetting BloomExposure; - extern FloatSetting BloomMagnitude; - extern FloatSetting BloomBlurSigma; - extern BoolSetting EnableVSync; - extern BoolSetting EnableAlbedoMaps; - extern BoolSetting EnableNormalMaps; - extern BoolSetting EnableSpecular; - extern BoolSetting ShowLightCounts; - extern BoolSetting ShowDecalCounts; - extern BoolSetting ShowClusterVisualizer; - extern BoolSetting ShowMSAAMask; - extern BoolSetting ShowUVGradients; - - struct AppSettingsCBuffer - { - bool32 EnableSun; - bool32 SunAreaLightApproximation; - float SunSize; - Float4Align Float3 SunDirection; - int32 MSAAMode; - bool32 RenderLights; - bool32 RenderDecals; - int32 RenderMode; - float Exposure; - float BloomExposure; - float BloomMagnitude; - float BloomBlurSigma; - bool32 EnableAlbedoMaps; - bool32 EnableNormalMaps; - bool32 EnableSpecular; - bool32 ShowLightCounts; - bool32 ShowDecalCounts; - bool32 ShowMSAAMask; - bool32 ShowUVGradients; - }; - - extern ConstantBuffer CBuffer; - const extern uint32 CBufferRegister; - - void Initialize(); - void Shutdown(); - void Update(uint32 displayWidth, uint32 displayHeight, const Float4x4& viewMatrix); - void UpdateCBuffer(); - void BindCBufferGfx(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter); - void BindCBufferCompute(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter); -}; - -// ================================================================================================ - -const uint64 NumMSAAModes = uint64(MSAAModes::NumValues); - -namespace AppSettings -{ - extern uint64 NumXTiles; - extern uint64 NumYTiles; - - inline uint32 NumMSAASamples(MSAAModes mode) - { - static const uint32 NumSamples[] = { 1, 2, 4 }; - StaticAssert_(ArraySize_(NumSamples) >= uint64(MSAAModes::NumValues)); - return NumSamples[uint32(mode)]; - } - - inline uint32 NumMSAASamples() - { - return NumMSAASamples(MSAAMode); - } - - void UpdateUI(); +#pragma once + +#include +#include +#include + +using namespace SampleFramework12; + +enum class MSAAModes +{ + MSAANone = 0, + MSAA2x = 1, + MSAA4x = 2, + + NumValues +}; + +typedef EnumSettingT MSAAModesSetting; + +enum class Scenes +{ + Sponza = 0, + + NumValues +}; + +typedef EnumSettingT ScenesSetting; + +enum class RenderModes +{ + ClusteredForward = 0, + DeferredTexturing = 1, + + NumValues +}; + +typedef EnumSettingT RenderModesSetting; + +enum class ClusterRasterizationModes +{ + Normal = 0, + MSAA4x = 1, + MSAA8x = 2, + Conservative = 3, + + NumValues +}; + +typedef EnumSettingT ClusterRasterizationModesSetting; + +namespace AppSettings +{ + static const uint64 ClusterTileSize = 16; + static const uint64 NumZTiles = 16; + static const uint64 NumDecalTypes = 8; + static const uint64 NumTexturesPerDecal = 2; + static const uint64 NumDecalTextures = 16; + static const uint64 MaxDecals = 64; + static const uint64 DecalElementsPerCluster = 2; + static const uint64 MaxSpotLights = 32; + static const uint64 SpotLightElementsPerCluster = 1; + static const float SpotLightRange = 7.5000f; + static const float SpotShadowNearClip = 0.1000f; + static const uint64 DeferredTileSize = 8; + static const uint64 DeferredTileMaskSize = 2; + static const float DeferredUVScale = 2.0000f; + + extern BoolSetting EnableSun; + extern BoolSetting SunAreaLightApproximation; + extern FloatSetting SunSize; + extern DirectionSetting SunDirection; + extern FloatSetting Turbidity; + extern ColorSetting GroundAlbedo; + extern MSAAModesSetting MSAAMode; + extern ScenesSetting CurrentScene; + extern BoolSetting RenderLights; + extern BoolSetting RenderDecals; + extern Button ClearDecals; + extern BoolSetting EnableDecalPicker; + extern RenderModesSetting RenderMode; + extern BoolSetting DepthPrepass; + extern BoolSetting SortByDepth; + extern IntSetting MaxLightClamp; + extern ClusterRasterizationModesSetting ClusterRasterizationMode; + extern BoolSetting UseZGradientsForMSAAMask; + extern BoolSetting ComputeUVGradients; + extern FloatSetting Exposure; + extern FloatSetting BloomExposure; + extern FloatSetting BloomMagnitude; + extern FloatSetting BloomBlurSigma; + extern BoolSetting EnableVSync; + extern BoolSetting EnableAlbedoMaps; + extern BoolSetting EnableNormalMaps; + extern BoolSetting EnableSpecular; + extern BoolSetting ShowLightCounts; + extern BoolSetting ShowDecalCounts; + extern BoolSetting ShowClusterVisualizer; + extern BoolSetting ShowMSAAMask; + extern BoolSetting ShowUVGradients; + extern BoolSetting AnimateLightIntensity; + + struct AppSettingsCBuffer + { + bool32 EnableSun; + bool32 SunAreaLightApproximation; + float SunSize; + Float4Align Float3 SunDirection; + int32 MSAAMode; + bool32 RenderLights; + bool32 RenderDecals; + int32 RenderMode; + float Exposure; + float BloomExposure; + float BloomMagnitude; + float BloomBlurSigma; + bool32 EnableAlbedoMaps; + bool32 EnableNormalMaps; + bool32 EnableSpecular; + bool32 ShowLightCounts; + bool32 ShowDecalCounts; + bool32 ShowMSAAMask; + bool32 ShowUVGradients; + bool32 AnimateLightIntensity; + }; + + extern ConstantBuffer CBuffer; + const extern uint32 CBufferRegister; + + void Initialize(); + void Shutdown(); + void Update(uint32 displayWidth, uint32 displayHeight, const Float4x4& viewMatrix); + void UpdateCBuffer(); + void BindCBufferGfx(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter); + void BindCBufferCompute(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter); +}; + +// ================================================================================================ + +const uint64 NumMSAAModes = uint64(MSAAModes::NumValues); + +namespace AppSettings +{ + extern uint64 NumXTiles; + extern uint64 NumYTiles; + + inline uint32 NumMSAASamples(MSAAModes mode) + { + static const uint32 NumSamples[] = { 1, 2, 4 }; + StaticAssert_(ArraySize_(NumSamples) >= uint64(MSAAModes::NumValues)); + return NumSamples[uint32(mode)]; + } + + inline uint32 NumMSAASamples() + { + return NumMSAASamples(MSAAMode); + } + + void UpdateUI(); } \ No newline at end of file diff --git a/BindlessDeferred/AppSettings.hlsl b/BindlessDeferred/AppSettings.hlsl index f9e5925..667a7a1 100644 --- a/BindlessDeferred/AppSettings.hlsl +++ b/BindlessDeferred/AppSettings.hlsl @@ -1,52 +1,54 @@ -struct AppSettings_Layout -{ - bool EnableSun; - bool SunAreaLightApproximation; - float SunSize; - float3 SunDirection; - int MSAAMode; - bool RenderLights; - bool RenderDecals; - int RenderMode; - float Exposure; - float BloomExposure; - float BloomMagnitude; - float BloomBlurSigma; - bool EnableAlbedoMaps; - bool EnableNormalMaps; - bool EnableSpecular; - bool ShowLightCounts; - bool ShowDecalCounts; - bool ShowMSAAMask; - bool ShowUVGradients; -}; - -ConstantBuffer AppSettings : register(b12); - -static const int MSAAModes_MSAANone = 0; -static const int MSAAModes_MSAA2x = 1; -static const int MSAAModes_MSAA4x = 2; - -static const int Scenes_Sponza = 0; - -static const int RenderModes_ClusteredForward = 0; -static const int RenderModes_DeferredTexturing = 1; - -static const int ClusterRasterizationModes_Normal = 0; -static const int ClusterRasterizationModes_MSAA4x = 1; -static const int ClusterRasterizationModes_MSAA8x = 2; -static const int ClusterRasterizationModes_Conservative = 3; - -static const uint ClusterTileSize = 16; -static const uint NumZTiles = 16; -static const uint NumDecalTypes = 8; -static const uint NumTexturesPerDecal = 2; -static const uint NumDecalTextures = 16; -static const uint MaxDecals = 64; -static const uint DecalElementsPerCluster = 2; -static const uint MaxSpotLights = 32; -static const uint SpotLightElementsPerCluster = 1; -static const float SpotLightRange = 7.5000f; -static const uint DeferredTileSize = 8; -static const uint DeferredTileMaskSize = 2; -static const float DeferredUVScale = 2.0000f; +struct AppSettings_Layout +{ + bool EnableSun; + bool SunAreaLightApproximation; + float SunSize; + float3 SunDirection; + int MSAAMode; + bool RenderLights; + bool RenderDecals; + int RenderMode; + float Exposure; + float BloomExposure; + float BloomMagnitude; + float BloomBlurSigma; + bool EnableAlbedoMaps; + bool EnableNormalMaps; + bool EnableSpecular; + bool ShowLightCounts; + bool ShowDecalCounts; + bool ShowMSAAMask; + bool ShowUVGradients; + bool AnimateLightIntensity; +}; + +ConstantBuffer AppSettings : register(b12); + +static const int MSAAModes_MSAANone = 0; +static const int MSAAModes_MSAA2x = 1; +static const int MSAAModes_MSAA4x = 2; + +static const int Scenes_Sponza = 0; + +static const int RenderModes_ClusteredForward = 0; +static const int RenderModes_DeferredTexturing = 1; + +static const int ClusterRasterizationModes_Normal = 0; +static const int ClusterRasterizationModes_MSAA4x = 1; +static const int ClusterRasterizationModes_MSAA8x = 2; +static const int ClusterRasterizationModes_Conservative = 3; + +static const uint ClusterTileSize = 16; +static const uint NumZTiles = 16; +static const uint NumDecalTypes = 8; +static const uint NumTexturesPerDecal = 2; +static const uint NumDecalTextures = 16; +static const uint MaxDecals = 64; +static const uint DecalElementsPerCluster = 2; +static const uint MaxSpotLights = 32; +static const uint SpotLightElementsPerCluster = 1; +static const float SpotLightRange = 7.5000f; +static const float SpotShadowNearClip = 0.1000f; +static const uint DeferredTileSize = 8; +static const uint DeferredTileMaskSize = 2; +static const float DeferredUVScale = 2.0000f; diff --git a/BindlessDeferred/BindlessDeferred.cpp b/BindlessDeferred/BindlessDeferred.cpp index 51c1a7d..9af04f9 100644 --- a/BindlessDeferred/BindlessDeferred.cpp +++ b/BindlessDeferred/BindlessDeferred.cpp @@ -1,2258 +1,2424 @@ -//================================================================================================= -// -// Bindless Deferred Texturing Sample -// by MJP -// http://mynameismjp.wordpress.com/ -// -// All code and content licensed under the MIT license -// -//================================================================================================= - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "BindlessDeferred.h" -#include "SharedTypes.h" -#include "EnkiTS/TaskScheduler_c.h" - -using namespace SampleFramework12; -using std::wstring; - -// Model filenames -static const wchar* ScenePaths[] = -{ - L"..\\Content\\Models\\Sponza\\Sponza.fbx", -}; - -static const float SceneScales[] = { 0.01f }; -static const Float3 SceneCameraPositions[] = { Float3(-11.5f, 1.85f, -0.45f) }; -static const Float2 SceneCameraRotations[] = { Float2(0.0f, 1.544f) }; - -StaticAssert_(ArraySize_(ScenePaths) == uint64(Scenes::NumValues)); -StaticAssert_(ArraySize_(SceneScales) == uint64(Scenes::NumValues)); -StaticAssert_(ArraySize_(SceneCameraPositions) == uint64(Scenes::NumValues)); -StaticAssert_(ArraySize_(SceneCameraRotations) == uint64(Scenes::NumValues)); - -static const uint64 NumConeSides = 16; - -static enkiTaskScheduler* taskScheduler = nullptr; -static enkiTaskSet* taskSet = nullptr; - -struct PickingData -{ - Float3 Position; - Float3 Normal; -}; - -enum DeferredRootParams -{ - Deferred_DeferredCBuffer, - Deferred_PSCBuffer, - Deferred_ShadowCBuffer, - Deferred_LightCBuffer, - Deferred_AppSettings, - Deferred_Descriptors, - Deferred_DecalDescriptors, - - NumDeferredRootParams -}; - -// Returns true if a sphere intersects a capped cone defined by a direction, height, and angle -static bool SphereConeIntersection(const Float3& coneTip, const Float3& coneDir, float coneHeight, - float coneAngle, const Float3& sphereCenter, float sphereRadius) -{ - if(Float3::Dot(sphereCenter - coneTip, coneDir) > coneHeight + sphereRadius) - return false; - - float cosHalfAngle = std::cos(coneAngle * 0.5f); - float sinHalfAngle = std::sin(coneAngle * 0.5f); - - Float3 v = sphereCenter - coneTip; - float a = Float3::Dot(v, coneDir); - float b = a * sinHalfAngle / cosHalfAngle; - float c = std::sqrt(Float3::Dot(v, v) - a * a); - float d = c - b; - float e = d * cosHalfAngle; - - return e < sphereRadius; -} - -BindlessDeferred::BindlessDeferred() : App(L"Bindless Deferred Texturing") -{ - minFeatureLevel = D3D_FEATURE_LEVEL_11_1; - globalHelpText = "Bindless Deferred Texturing\n\n" - "Controls:\n\n" - "Use W/S/A/D/Q/E to move the camera, and hold right-click while dragging the mouse to rotate."; -} - -void BindlessDeferred::BeforeReset() -{ -} - -void BindlessDeferred::AfterReset() -{ - float aspect = float(swapChain.Width()) / swapChain.Height(); - camera.SetAspectRatio(aspect); - - CreateRenderTargets(); -} - -void BindlessDeferred::Initialize() -{ - // Check if the device supports conservative rasterization - D3D12_FEATURE_DATA_D3D12_OPTIONS features = { }; - DX12::Device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &features, sizeof(features)); - if(features.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_2) - throw Exception("This demo requires a GPU that supports FEATURE_LEVEL_11_1 with D3D12_RESOURCE_BINDING_TIER_2"); - - if(features.ConservativeRasterizationTier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) - { - AppSettings::ClusterRasterizationMode.SetValue(ClusterRasterizationModes::MSAA8x); - AppSettings::ClusterRasterizationMode.ClampNumValues(uint32(ClusterRasterizationModes::NumValues) - 1); - } - - // Load the scenes - for(uint64 i = 0; i < uint64(Scenes::NumValues); ++i) - { - ModelLoadSettings settings; - settings.FilePath = ScenePaths[i]; - settings.ForceSRGB = true; - settings.SceneScale = SceneScales[i]; - settings.MergeMeshes = false; - sceneModels[i].CreateWithAssimp(settings); - } - - float aspect = float(swapChain.Width()) / swapChain.Height(); - camera.Initialize(aspect, Pi_4, 0.1f, 35.0f); - - InitializeScene(); - - skybox.Initialize(); - - postProcessor.Initialize(); - - // Load the decal textures - for(uint64 i = 0; i < AppSettings::NumDecalTypes; ++i) - { - LoadTexture(decalTextures[i * 2 + 0], MakeString(L"..\\Content\\Textures\\Decals\\Decal_%02u_Albedo.tga", uint32(i)).c_str(), true); - LoadTexture(decalTextures[i * 2 + 1], MakeString(L"..\\Content\\Textures\\Decals\\Decal_%02u_Normal.png", uint32(i)).c_str(), false); - } - - decals.Init(AppSettings::MaxDecals); - - { - // Decal buffer - StructuredBufferInit sbInit; - sbInit.Stride = sizeof(Decal); - sbInit.NumElements = AppSettings::MaxDecals; - sbInit.Dynamic = false; - sbInit.Lifetime = BufferLifetime::Persistent; - sbInit.InitialState = D3D12_RESOURCE_STATE_COPY_DEST; - decalBuffer.Initialize(sbInit); - decalBuffer.Resource()->SetName(L"Decal Buffer"); - } - - { - // Decal bounds and instance buffers - StructuredBufferInit sbInit; - sbInit.Stride = sizeof(ClusterBounds); - sbInit.NumElements = AppSettings::MaxDecals; - sbInit.Dynamic = true; - sbInit.Lifetime = BufferLifetime::Temporary; - decalBoundsBuffer.Initialize(sbInit); - - sbInit.Stride = sizeof(uint32); - decalInstanceBuffer.Initialize(sbInit); - } - - { - // Spot light bounds and instance buffers - StructuredBufferInit sbInit; - sbInit.Stride = sizeof(ClusterBounds); - sbInit.NumElements = AppSettings::MaxSpotLights; - sbInit.Dynamic = true; - sbInit.Lifetime = BufferLifetime::Temporary; - spotLightBoundsBuffer.Initialize(sbInit); - - sbInit.Stride = sizeof(uint32); - spotLightInstanceBuffer.Initialize(sbInit); - } - - { - // Spot light and shadow bounds buffer (actually used as a constant buffer) - StructuredBufferInit sbInit; - sbInit.Stride = sizeof(LightConstants); - sbInit.NumElements = 1; - sbInit.Dynamic = false; - sbInit.Lifetime = BufferLifetime::Persistent; - sbInit.InitialState = D3D12_RESOURCE_STATE_COPY_DEST; - - spotLightBuffer.Initialize(sbInit); - spotLightBuffer.Resource()->SetName(L"Spot Light Buffer"); - } - - { - // Indirect args buffers for deferred rendering - StructuredBufferInit sbInit; - sbInit.NumElements = 1; - sbInit.Stride = sizeof(D3D12_DISPATCH_ARGUMENTS); - - uint32 initData[3] = { 0, 1, 1 }; - sbInit.InitData = initData; - sbInit.InitialState = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; - - nonMsaaArgsBuffer.Initialize(sbInit); - msaaArgsBuffer.Initialize(sbInit); - - nonMsaaArgsBuffer.Resource()->SetName(L"Non-MSAA Args Buffer"); - msaaArgsBuffer.Resource()->SetName(L"MSAA Args Buffer"); - } - - { - CompileOptions opts; - opts.Add("FrontFace_", 1); - opts.Add("BackFace_", 0); - opts.Add("Intersecting_", 0); - - // Clustering shaders - clusterVS = CompileFromFile(L"Clusters.hlsl", "ClusterVS", ShaderType::Vertex, ShaderProfile::SM51, opts); - clusterFrontFacePS = CompileFromFile(L"Clusters.hlsl", "ClusterPS", ShaderType::Pixel, ShaderProfile::SM51, opts); - - opts.Reset(); - opts.Add("FrontFace_", 0); - opts.Add("BackFace_", 1); - opts.Add("Intersecting_", 0); - clusterBackFacePS = CompileFromFile(L"Clusters.hlsl", "ClusterPS", ShaderType::Pixel, ShaderProfile::SM51, opts); - - opts.Reset(); - opts.Add("FrontFace_", 0); - opts.Add("BackFace_", 0); - opts.Add("Intersecting_", 1); - clusterIntersectingPS = CompileFromFile(L"Clusters.hlsl", "ClusterPS", ShaderType::Pixel, ShaderProfile::SM51, opts); - } - - MakeBoxGeometry(decalClusterVtxBuffer, decalClusterIdxBuffer, 2.0f); // resulting box is [-1, 1] - MakeConeGeometry(NumConeSides, spotLightClusterVtxBuffer, spotLightClusterIdxBuffer, coneVertices); - - { - // Picking buffer - StructuredBufferInit sbInit; - sbInit.Stride = sizeof(PickingData); - sbInit.NumElements = 1; - sbInit.CreateUAV = 1; - pickingBuffer.Initialize(sbInit); - } - - for(uint64 i = 0; i < DX12::RenderLatency; ++i) - { - pickingReadbackBuffers[i].Initialize(sizeof(PickingData)); - pickingReadbackBuffers[i].Resource->SetName(L"Picking Readback Buffer"); - } - - { - // Compile picking shaders - CompileOptions opts; - opts.Add("MSAA_", 0); - pickingCS[0] = CompileFromFile(L"Picking.hlsl", "PickingCS", ShaderType::Compute, ShaderProfile::SM51, opts); - - opts.Reset(); - opts.Add("MSAA_", 1); - pickingCS[1] = CompileFromFile(L"Picking.hlsl", "PickingCS", ShaderType::Compute, ShaderProfile::SM51, opts); - } - - // Compile MSAA mask generation shaders - for(uint64 msaaMode = 1; msaaMode < NumMSAAModes; ++msaaMode) - { - CompileOptions opts; - opts.Add("MSAASamples_", AppSettings::NumMSAASamples(MSAAModes(msaaMode))); - opts.Add("UseZGradients_", 0); - msaaMaskCS[msaaMode][0] = CompileFromFile(L"MSAAMask.hlsl", "MSAAMaskCS", ShaderType::Compute, ShaderProfile::SM51, opts); - - opts.Reset(); - opts.Add("MSAASamples_", AppSettings::NumMSAASamples(MSAAModes(msaaMode))); - opts.Add("UseZGradients_", 1); - msaaMaskCS[msaaMode][1] = CompileFromFile(L"MSAAMask.hlsl", "MSAAMaskCS", ShaderType::Compute, ShaderProfile::SM51, opts); - } - - // Compile resolve shaders - for(uint64 msaaMode = 1; msaaMode < NumMSAAModes; ++msaaMode) - { - for(uint64 deferred = 0; deferred < 2; ++deferred) - { - CompileOptions opts; - opts.Add("MSAASamples_", AppSettings::NumMSAASamples(MSAAModes(msaaMode))); - opts.Add("Deferred_", uint32(deferred)); - resolvePS[msaaMode][deferred] = CompileFromFile(L"Resolve.hlsl", "ResolvePS", ShaderType::Pixel, ShaderProfile::SM51, opts); - } - } - - // Compile cluster visualization shaders - clusterVisPS = CompileFromFile(L"ClusterVisualizer.hlsl", "ClusterVisualizerPS", ShaderType::Pixel, ShaderProfile::SM51); - - std::wstring fullScreenTriPath = SampleFrameworkDir() + L"Shaders\\FullScreenTriangle.hlsl"; - fullScreenTriVS = CompileFromFile(fullScreenTriPath.c_str(), "FullScreenTriangleVS", ShaderType::Vertex, ShaderProfile::SM51); - - // Create constant buffers - clusterConstants.Initialize(BufferLifetime::Temporary); - msaaMaskConstants.Initialize(BufferLifetime::Temporary); - deferredConstants.Initialize(BufferLifetime::Temporary); - shadingConstants.Initialize(BufferLifetime::Temporary); - pickingConstants.Initialize(BufferLifetime::Temporary); - clusterVisConstants.Initialize(BufferLifetime::Temporary); - - { - // Clustering root signature - D3D12_DESCRIPTOR_RANGE1 srvRanges[1] = {}; - srvRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - srvRanges[0].NumDescriptors = 3; - srvRanges[0].BaseShaderRegister = 0; - srvRanges[0].RegisterSpace = 0; - srvRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - D3D12_DESCRIPTOR_RANGE1 uavRanges[1] = {}; - uavRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; - uavRanges[0].NumDescriptors = 1; - uavRanges[0].BaseShaderRegister = 0; - uavRanges[0].RegisterSpace = 0; - uavRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - D3D12_ROOT_PARAMETER1 rootParameters[4] = {}; - - // CBuffer - rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[0].Descriptor.RegisterSpace = 0; - rootParameters[0].Descriptor.ShaderRegister = 0; - - // AppSettings - rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[1].Descriptor.RegisterSpace = 0; - rootParameters[1].Descriptor.ShaderRegister = AppSettings::CBufferRegister; - - // VS SRV descriptors - rootParameters[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; - rootParameters[2].DescriptorTable.pDescriptorRanges = srvRanges; - rootParameters[2].DescriptorTable.NumDescriptorRanges = ArraySize_(srvRanges); - - // PS SRV descriptors - rootParameters[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[3].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[3].DescriptorTable.pDescriptorRanges = uavRanges; - rootParameters[3].DescriptorTable.NumDescriptorRanges = ArraySize_(uavRanges); - - D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; - rootSignatureDesc.NumParameters = ArraySize_(rootParameters); - rootSignatureDesc.pParameters = rootParameters; - rootSignatureDesc.NumStaticSamplers = 0; - rootSignatureDesc.pStaticSamplers = nullptr; - rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; - - DX12::CreateRootSignature(&clusterRS, rootSignatureDesc); - } - - { - // Picking root signature - D3D12_DESCRIPTOR_RANGE1 descriptorRanges[2] = {}; - descriptorRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - descriptorRanges[0].NumDescriptors = 2; - descriptorRanges[0].BaseShaderRegister = 0; - descriptorRanges[0].RegisterSpace = 0; - descriptorRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - descriptorRanges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; - descriptorRanges[1].NumDescriptors = 1; - descriptorRanges[1].BaseShaderRegister = 0; - descriptorRanges[1].RegisterSpace = 0; - descriptorRanges[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - D3D12_ROOT_PARAMETER1 rootParameters[2] = {}; - rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[0].Descriptor.RegisterSpace = 0; - rootParameters[0].Descriptor.ShaderRegister = 0; - - rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[1].DescriptorTable.pDescriptorRanges = descriptorRanges; - rootParameters[1].DescriptorTable.NumDescriptorRanges = ArraySize_(descriptorRanges); - - D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; - rootSignatureDesc.NumParameters = ArraySize_(rootParameters); - rootSignatureDesc.pParameters = rootParameters; - rootSignatureDesc.NumStaticSamplers = 0; - rootSignatureDesc.pStaticSamplers = nullptr; - rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; - - DX12::CreateRootSignature(&pickingRS, rootSignatureDesc); - } - - { - // MSAA mask root signature - D3D12_DESCRIPTOR_RANGE1 descriptorRanges[2] = {}; - descriptorRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - descriptorRanges[0].NumDescriptors = 2; - descriptorRanges[0].BaseShaderRegister = 0; - descriptorRanges[0].RegisterSpace = 0; - descriptorRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - descriptorRanges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; - descriptorRanges[1].NumDescriptors = 3; - descriptorRanges[1].BaseShaderRegister = 0; - descriptorRanges[1].RegisterSpace = 0; - descriptorRanges[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - D3D12_ROOT_PARAMETER1 rootParameters[3] = {}; - - // MSAAMaskCBuffer - rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[0].Descriptor.RegisterSpace = 0; - rootParameters[0].Descriptor.ShaderRegister = 0; - - // AppSettings - rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[1].Descriptor.RegisterSpace = 0; - rootParameters[1].Descriptor.ShaderRegister = AppSettings::CBufferRegister; - - // SRV descriptors - rootParameters[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[2].DescriptorTable.pDescriptorRanges = descriptorRanges; - rootParameters[2].DescriptorTable.NumDescriptorRanges = ArraySize_(descriptorRanges); - - D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; - rootSignatureDesc.NumParameters = ArraySize_(rootParameters); - rootSignatureDesc.pParameters = rootParameters; - rootSignatureDesc.NumStaticSamplers = 0; - rootSignatureDesc.pStaticSamplers = nullptr; - rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; - - DX12::CreateRootSignature(&msaaMaskRootSignature, rootSignatureDesc); - } - - { - // Resolve root signature - D3D12_DESCRIPTOR_RANGE1 srvRanges[1] = {}; - srvRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - srvRanges[0].NumDescriptors = 1; - srvRanges[0].BaseShaderRegister = 0; - srvRanges[0].RegisterSpace = 0; - srvRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - D3D12_ROOT_PARAMETER1 rootParameters[3] = {}; - - // ResolveCBuffer - rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[0].Constants.Num32BitValues = 2; - rootParameters[0].Constants.RegisterSpace = 0; - rootParameters[0].Constants.ShaderRegister = 0; - - // AppSettings - rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[1].Descriptor.RegisterSpace = 0; - rootParameters[1].Descriptor.ShaderRegister = AppSettings::CBufferRegister; - - // SRV descriptors - rootParameters[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[2].DescriptorTable.pDescriptorRanges = srvRanges; - rootParameters[2].DescriptorTable.NumDescriptorRanges = ArraySize_(srvRanges); - - D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; - rootSignatureDesc.NumParameters = ArraySize_(rootParameters); - rootSignatureDesc.pParameters = rootParameters; - rootSignatureDesc.NumStaticSamplers = 0; - rootSignatureDesc.pStaticSamplers = nullptr; - rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; - - DX12::CreateRootSignature(&resolveRootSignature, rootSignatureDesc); - } - - { - // Cluster visualization root signature - D3D12_DESCRIPTOR_RANGE1 srvRanges[1] = {}; - srvRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - srvRanges[0].NumDescriptors = 2; - srvRanges[0].BaseShaderRegister = 0; - srvRanges[0].RegisterSpace = 0; - srvRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - D3D12_ROOT_PARAMETER1 rootParameters[3] = {}; - - // CBuffer - rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[0].Descriptor.RegisterSpace = 0; - rootParameters[0].Descriptor.ShaderRegister = 0; - - // AppSettings - rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[1].Descriptor.RegisterSpace = 0; - rootParameters[1].Descriptor.ShaderRegister = AppSettings::CBufferRegister; - - // SRV descriptors - rootParameters[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[2].DescriptorTable.pDescriptorRanges = srvRanges; - rootParameters[2].DescriptorTable.NumDescriptorRanges = ArraySize_(srvRanges); - - D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; - rootSignatureDesc.NumParameters = ArraySize_(rootParameters); - rootSignatureDesc.pParameters = rootParameters; - rootSignatureDesc.NumStaticSamplers = 0; - rootSignatureDesc.pStaticSamplers = nullptr; - rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; - - DX12::CreateRootSignature(&clusterVisRootSignature, rootSignatureDesc); - } - - { - // Command signature for MSAA deferred indirect dispatch - D3D12_INDIRECT_ARGUMENT_DESC argsDescs[1] = { }; - argsDescs[0].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; - - D3D12_COMMAND_SIGNATURE_DESC cmdSignatureDesc = { }; - cmdSignatureDesc.ByteStride = sizeof(D3D12_DISPATCH_ARGUMENTS); - cmdSignatureDesc.NodeMask = 0; - cmdSignatureDesc.NumArgumentDescs = ArraySize_(argsDescs); - cmdSignatureDesc.pArgumentDescs = argsDescs; - DXCall(DX12::Device->CreateCommandSignature(&cmdSignatureDesc, nullptr, IID_PPV_ARGS(&deferredCmdSignature))); - } -} - -void BindlessDeferred::Shutdown() -{ - for(uint64 i = 0; i < ArraySize_(sceneModels); ++i) - sceneModels[i].Shutdown(); - meshRenderer.Shutdown(); - skybox.Shutdown(); - skyCache.Shutdown(); - postProcessor.Shutdown(); - - decalBuffer.Shutdown(); - decalBoundsBuffer.Shutdown(); - decalClusterBuffer.Shutdown(); - decalInstanceBuffer.Shutdown(); - for(uint64 i = 0; i < ArraySize_(decalTextures); ++i) - decalTextures[i].Shutdown(); - - spotLightBuffer.Shutdown(); - spotLightBoundsBuffer.Shutdown(); - spotLightClusterBuffer.Shutdown(); - spotLightInstanceBuffer.Shutdown(); - - DX12::Release(clusterRS); - clusterMSAATarget.Shutdown(); - - decalClusterVtxBuffer.Shutdown(); - decalClusterIdxBuffer.Shutdown(); - - spotLightClusterVtxBuffer.Shutdown(); - spotLightClusterIdxBuffer.Shutdown(); - - DX12::Release(deferredRootSignature); - DX12::Release(deferredCmdSignature); - - deferredConstants.Shutdown(); - msaaMaskConstants.Shutdown(); - shadingConstants.Shutdown(); - DX12::Release(msaaMaskRootSignature); - nonMsaaTileBuffer.Shutdown(); - msaaTileBuffer.Shutdown(); - nonMsaaArgsBuffer.Shutdown(); - msaaArgsBuffer.Shutdown(); - msaaMaskBuffer.Shutdown(); - - pickingBuffer.Shutdown(); - DX12::Release(pickingRS); - pickingConstants.Shutdown(); - for(uint64 i = 0; i < ArraySize_(pickingReadbackBuffers); ++i) - pickingReadbackBuffers[i].Shutdown(); - - clusterVisConstants.Shutdown(); - DX12::Release(clusterVisRootSignature); - - mainTarget.Shutdown(); - tangentFrameTarget.Shutdown(); - resolveTarget.Shutdown(); - depthBuffer.Shutdown(); - uvTarget.Shutdown(); - uvGradientsTarget.Shutdown(); - materialIDTarget.Shutdown(); - deferredMSAATarget.Shutdown(); - - DX12::Release(resolveRootSignature); -} - -void BindlessDeferred::CreatePSOs() -{ - DXGI_FORMAT gBufferFormats[] = { tangentFrameTarget.Format(), uvTarget.Format(), materialIDTarget.Format(), uvGradientsTarget.Format() }; - uint64 numGBuffers = AppSettings::ComputeUVGradients ? ArraySize_(gBufferFormats) - 1 : ArraySize_(gBufferFormats); - meshRenderer.CreatePSOs(mainTarget.Texture.Format, depthBuffer.DSVFormat, gBufferFormats, numGBuffers, mainTarget.MSAASamples); - skybox.CreatePSOs(mainTarget.Texture.Format, depthBuffer.DSVFormat, mainTarget.MSAASamples); - postProcessor.CreatePSOs(); - - { - // Clustering PSO - D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; - psoDesc.pRootSignature = clusterRS; - psoDesc.BlendState = DX12::GetBlendState(BlendState::Disabled); - psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::Disabled); - psoDesc.SampleMask = UINT_MAX; - psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - psoDesc.NumRenderTargets = 0; - psoDesc.VS = clusterVS.ByteCode(); - - ClusterRasterizationModes rastMode = AppSettings::ClusterRasterizationMode; - if(rastMode == ClusterRasterizationModes::MSAA4x || rastMode == ClusterRasterizationModes::MSAA8x) - { - psoDesc.SampleDesc.Count = clusterMSAATarget.MSAASamples; - psoDesc.SampleDesc.Quality = DX12::StandardMSAAPattern; - psoDesc.NumRenderTargets = 1; - psoDesc.RTVFormats[0] = clusterMSAATarget.Format(); - } - else - psoDesc.SampleDesc.Count = 1; - - D3D12_CONSERVATIVE_RASTERIZATION_MODE crMode = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; - if(rastMode == ClusterRasterizationModes::Conservative) - crMode = D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON; - - psoDesc.PS = clusterFrontFacePS.ByteCode(); - psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::BackFaceCull); - psoDesc.RasterizerState.ConservativeRaster = crMode; - DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&clusterFrontFacePSO))); - - psoDesc.PS = clusterBackFacePS.ByteCode(); - psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::FrontFaceCull); - psoDesc.RasterizerState.ConservativeRaster = crMode; - DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&clusterBackFacePSO))); - - psoDesc.PS = clusterIntersectingPS.ByteCode(); - psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::FrontFaceCull); - psoDesc.RasterizerState.ConservativeRaster = crMode; - DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&clusterIntersectingPSO))); - } - - const bool msaaEnabled = AppSettings::MSAAMode != MSAAModes::MSAANone; - const uint64 msaaModeIdx = uint64(AppSettings::MSAAMode); - - if(msaaEnabled) - { - // MSAA mask PSO's - D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = { }; - psoDesc.CS = msaaMaskCS[uint64(AppSettings::MSAAMode)][0].ByteCode(); - psoDesc.pRootSignature = msaaMaskRootSignature; - DXCall(DX12::Device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&msaaMaskPSOs[0]))); - - psoDesc.CS = msaaMaskCS[uint64(AppSettings::MSAAMode)][1].ByteCode(); - DXCall(DX12::Device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&msaaMaskPSOs[1]))); - } - - if(taskSet == nullptr) - { - // Deferred rendering PSO - const uint64 uvGradIdx = AppSettings::ComputeUVGradients ? 1 : 0; - D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = { }; - psoDesc.CS = deferredCS[msaaModeIdx][uvGradIdx][0].ByteCode(); - psoDesc.pRootSignature = deferredRootSignature; - DXCall(DX12::Device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&deferredPSOs[0]))); - - if(AppSettings::MSAAMode != MSAAModes::MSAANone) - { - psoDesc.CS = deferredCS[msaaModeIdx][uvGradIdx][1].ByteCode(); - DXCall(DX12::Device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&deferredPSOs[1]))); - } - } - - if(msaaEnabled) - { - // Resolve PSO - D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; - psoDesc.pRootSignature = resolveRootSignature; - psoDesc.VS = fullScreenTriVS.ByteCode(); - psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::NoCull); - psoDesc.BlendState = DX12::GetBlendState(BlendState::Disabled); - psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::Disabled); - psoDesc.SampleMask = UINT_MAX; - psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - psoDesc.NumRenderTargets = 1; - psoDesc.RTVFormats[0] = mainTarget.Format(); - psoDesc.SampleDesc.Count = 1; - - psoDesc.PS = resolvePS[msaaModeIdx][0].ByteCode(); - DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&resolvePSOs[0]))); - - psoDesc.PS = resolvePS[msaaModeIdx][1].ByteCode(); - DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&resolvePSOs[1]))); - } - - { - // Cluster visualizer PSO - D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; - psoDesc.pRootSignature = clusterVisRootSignature; - psoDesc.VS = fullScreenTriVS.ByteCode(); - psoDesc.PS = clusterVisPS.ByteCode(); - psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::NoCull); - psoDesc.BlendState = DX12::GetBlendState(BlendState::AlphaBlend); - psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::Disabled); - psoDesc.SampleMask = UINT_MAX; - psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - psoDesc.NumRenderTargets = 1; - psoDesc.RTVFormats[0] = swapChain.Format(); - psoDesc.SampleDesc.Count = 1; - DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&clusterVisPSO))); - } - - { - // Picking PSO - D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = { }; - psoDesc.CS = pickingCS[0].ByteCode(); - psoDesc.pRootSignature = pickingRS; - DXCall(DX12::Device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&pickingPSOs[0]))); - - psoDesc.CS = pickingCS[1].ByteCode(); - DXCall(DX12::Device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&pickingPSOs[1]))); - } -} - -void BindlessDeferred::DestroyPSOs() -{ - meshRenderer.DestroyPSOs(); - skybox.DestroyPSOs(); - postProcessor.DestroyPSOs(); - DX12::DeferredRelease(clusterFrontFacePSO); - DX12::DeferredRelease(clusterBackFacePSO); - DX12::DeferredRelease(clusterIntersectingPSO); - DX12::DeferredRelease(pickingPSOs[0]); - DX12::DeferredRelease(pickingPSOs[1]); - DX12::DeferredRelease(clusterVisPSO); - for(uint64 i = 0; i < ArraySize_(msaaMaskPSOs); ++i) - DX12::DeferredRelease(msaaMaskPSOs[i]); - for(uint64 i = 0; i < ArraySize_(deferredPSOs); ++i) - DX12::DeferredRelease(deferredPSOs[i]); - for(uint64 i = 0; i < ArraySize_(resolvePSOs); ++i) - DX12::DeferredRelease(resolvePSOs[i]); -} - -// Creates all required render targets -void BindlessDeferred::CreateRenderTargets() -{ - uint32 width = swapChain.Width(); - uint32 height = swapChain.Height(); - const uint32 NumSamples = AppSettings::NumMSAASamples(); - - mainTarget.Initialize(width, height, DXGI_FORMAT_R16G16B16A16_FLOAT, NumSamples, 1, NumSamples == 1); - mainTarget.Resource()->SetName(L"Main Target"); - - tangentFrameTarget.Initialize(width, height, DXGI_FORMAT_R10G10B10A2_UNORM, NumSamples, 1, false, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - uvTarget.Initialize(width, height, DXGI_FORMAT_R16G16B16A16_SNORM, NumSamples, 1, false, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - uvGradientsTarget.Initialize(width, height, DXGI_FORMAT_R16G16B16A16_SNORM, NumSamples, 1, false, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - materialIDTarget.Initialize(width, height, DXGI_FORMAT_R8_UINT, NumSamples, 1, false, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - - tangentFrameTarget.Resource()->SetName(L"Tangent Frame Target"); - uvTarget.Resource()->SetName(L"UV Target"); - uvGradientsTarget.Resource()->SetName(L"UV Gradient Target"); - materialIDTarget.Resource()->SetName(L"Material ID Target"); - - if(NumSamples > 1) - { - resolveTarget.Initialize(width, height, DXGI_FORMAT_R16G16B16A16_FLOAT, 1, 1, false); - - uint32 deferredWidth = width * 2; - uint32 deferredHeight = NumSamples == 4 ? height * 2 : height; - deferredMSAATarget.Initialize(deferredWidth, deferredHeight, DXGI_FORMAT_R16G16B16A16_FLOAT, 1, 1, true); - deferredMSAATarget.Resource()->SetName(L"Deferred MSAA Target"); - } - - depthBuffer.Initialize(width, height, DXGI_FORMAT_D32_FLOAT, NumSamples, 1, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_DEPTH_READ); - depthBuffer.Resource()->SetName(L"Main Depth Buffer"); - - AppSettings::NumXTiles = (width + (AppSettings::ClusterTileSize - 1)) / AppSettings::ClusterTileSize; - AppSettings::NumYTiles = (height + (AppSettings::ClusterTileSize - 1)) / AppSettings::ClusterTileSize; - const uint64 numXYZTiles = AppSettings::NumXTiles * AppSettings::NumYTiles * AppSettings::NumZTiles; - - // Render target for forcing MSAA during cluster rasterization. Ideally we would use ForcedSampleCount for this, - // but it's currently causing the Nvidia driver to crash. :( - ClusterRasterizationModes rastMode = AppSettings::ClusterRasterizationMode; - if(rastMode == ClusterRasterizationModes::MSAA4x) - clusterMSAATarget.Initialize(AppSettings::NumXTiles, AppSettings::NumYTiles, DXGI_FORMAT_R8_UNORM, 4, 1, false); - else if(rastMode == ClusterRasterizationModes::MSAA8x) - clusterMSAATarget.Initialize(AppSettings::NumXTiles, AppSettings::NumYTiles, DXGI_FORMAT_R8_UNORM, 8, 1, false); - else - clusterMSAATarget.Shutdown(); - - { - // Decal cluster bitmask buffer - RawBufferInit rbInit; - rbInit.NumElements = numXYZTiles * AppSettings::DecalElementsPerCluster; - rbInit.CreateUAV = true; - decalClusterBuffer.Initialize(rbInit); - decalClusterBuffer.InternalBuffer.Resource->SetName(L"Decal Cluster Buffer"); - } - - { - // Spotlight cluster bitmask buffer - RawBufferInit rbInit; - rbInit.NumElements = numXYZTiles * AppSettings::SpotLightElementsPerCluster; - rbInit.CreateUAV = true; - spotLightClusterBuffer.Initialize(rbInit); - spotLightClusterBuffer.InternalBuffer.Resource->SetName(L"Spot Light Cluster Buffer"); - } - - { - const uint64 numComputeTilesX = AlignTo(mainTarget.Width(), AppSettings::DeferredTileSize) / AppSettings::DeferredTileSize; - const uint64 numComputeTilesY = AlignTo(mainTarget.Height(), AppSettings::DeferredTileSize) / AppSettings::DeferredTileSize; - - // AppendBuffer for storing coordinates of tiles with "edge" pixels for MSAA sampling - StructuredBufferInit sbInit; - sbInit.NumElements = numComputeTilesX * numComputeTilesY; - sbInit.Stride = sizeof(uint32); - sbInit.CreateUAV = true; - sbInit.UseCounter = true; - sbInit.InitialState = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - msaaTileBuffer.Initialize(sbInit); - msaaTileBuffer.InternalBuffer.Resource->SetName(L"MSAA Tile Buffer"); - - // AppendBuffer for storing coordinates of tiles with non-edge pixels for MSAA sampling - nonMsaaTileBuffer.Initialize(sbInit); - nonMsaaTileBuffer.InternalBuffer.Resource->SetName(L"Non-MSAA Tile Buffer"); - - // Buffer storing 1 bit per pixel indicating MSAA edge pixels - sbInit.Stride = AppSettings::DeferredTileMaskSize * sizeof(uint32); - sbInit.UseCounter = false; - msaaMaskBuffer.Initialize(sbInit); - msaaMaskBuffer.InternalBuffer.Resource->SetName(L"MSAA Mask Buffer"); - } -} - -void BindlessDeferred::CompileShadersTask(uint32 start, uint32 end, uint32 threadNum, void* args) -{ - BindlessDeferred* app = (BindlessDeferred*)args; - const uint64 numMaterialTextures = app->currentModel->MaterialTextures().Count(); - - for(uint32 i = start; i < end; ++i) - { - uint32 msaaMode = i / 4; - uint32 computeUVGradients = (i / 2) % 2; - uint32 perSample = i % 2; - - uint32 numMSAASamples = AppSettings::NumMSAASamples(MSAAModes(msaaMode)); - uint32 msaa = msaaMode > 0; - if(msaa == 0 && perSample == 1) - continue; - - CompileOptions opts; - opts.Add("MSAA_", msaa); - opts.Add("NumMSAASamples_", numMSAASamples); - opts.Add("ShadePerSample_", perSample); - opts.Add("NumMaterialTextures_", uint32(numMaterialTextures)); - opts.Add("ComputeUVGradients_", computeUVGradients); - app->deferredCS[msaaMode][computeUVGradients][perSample] = CompileFromFile(L"Deferred.hlsl", "DeferredCS", ShaderType::Compute, ShaderProfile::SM51, opts); - } -} - -void BindlessDeferred::InitializeScene() -{ - currentModel = &sceneModels[uint64(AppSettings::CurrentScene)]; - meshRenderer.Shutdown(); - DX12::FlushGPU(); - meshRenderer.Initialize(currentModel); - - const uint64 numMaterialTextures = currentModel->MaterialTextures().Count(); - - camera.SetPosition(SceneCameraPositions[uint64(AppSettings::CurrentScene)]); - camera.SetXRotation(SceneCameraRotations[uint64(AppSettings::CurrentScene)].x); - camera.SetYRotation(SceneCameraRotations[uint64(AppSettings::CurrentScene)].y); - - if(taskSet != nullptr) - { - enkiWaitForTaskSet(taskScheduler, taskSet); - } - else - { - taskScheduler = enkiCreateTaskScheduler(); - taskSet = enkiCreateTaskSet(taskScheduler, CompileShadersTask); - } - - // Kick off tasks to compile the deferred compute shaders - enkiAddTaskSetToPipe(taskScheduler, taskSet, this, uint32(MSAAModes::NumValues) * 2 * 2); - - { - // Initialize the spotlight data used for rendering - const uint64 numSpotLights = Min(currentModel->SpotLights().Size(), AppSettings::MaxSpotLights); - spotLights.Init(numSpotLights); - - for(uint64 i = 0; i < numSpotLights; ++i) - { - const ModelSpotLight& srcLight = currentModel->SpotLights()[i]; - - SpotLight& spotLight = spotLights[i]; - spotLight.Position = srcLight.Position; - spotLight.Direction = -srcLight.Direction; - spotLight.Intensity = srcLight.Intensity * 25.0f; - spotLight.AngularAttenuationX = std::cos(srcLight.AngularAttenuation.x * 0.5f); - spotLight.AngularAttenuationY = std::cos(srcLight.AngularAttenuation.y * 0.5f); - spotLight.Range = AppSettings::SpotLightRange; - } - - AppSettings::MaxLightClamp.SetValue(int32(numSpotLights)); - } - - { - DX12::DeferredRelease(deferredRootSignature); - - // Deferred root signature - D3D12_DESCRIPTOR_RANGE1 descriptorRanges[2] = {}; - descriptorRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; - descriptorRanges[0].NumDescriptors = 1; - descriptorRanges[0].BaseShaderRegister = 0; - descriptorRanges[0].RegisterSpace = 0; - descriptorRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - descriptorRanges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - descriptorRanges[1].NumDescriptors = 15 + uint32(numMaterialTextures); - descriptorRanges[1].BaseShaderRegister = 0; - descriptorRanges[1].RegisterSpace = 0; - descriptorRanges[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - D3D12_DESCRIPTOR_RANGE1 decalTextureRanges[1] = {}; - decalTextureRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - decalTextureRanges[0].NumDescriptors = AppSettings::NumDecalTextures; - decalTextureRanges[0].BaseShaderRegister = 0; - decalTextureRanges[0].RegisterSpace = 1; - decalTextureRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - D3D12_ROOT_PARAMETER1 rootParameters[NumDeferredRootParams] = {}; - - // DeferredCBuffer - rootParameters[Deferred_DeferredCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[Deferred_DeferredCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[Deferred_DeferredCBuffer].Descriptor.RegisterSpace = 0; - rootParameters[Deferred_DeferredCBuffer].Descriptor.ShaderRegister = 2; - - // PSCBuffer - rootParameters[Deferred_PSCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[Deferred_PSCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[Deferred_PSCBuffer].Descriptor.RegisterSpace = 0; - rootParameters[Deferred_PSCBuffer].Descriptor.ShaderRegister = 0; - - // ShadowCBuffer - rootParameters[Deferred_ShadowCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[Deferred_ShadowCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[Deferred_ShadowCBuffer].Descriptor.RegisterSpace = 0; - rootParameters[Deferred_ShadowCBuffer].Descriptor.ShaderRegister = 1; - - // LightCBuffer - rootParameters[Deferred_LightCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[Deferred_LightCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[Deferred_LightCBuffer].Descriptor.RegisterSpace = 0; - rootParameters[Deferred_LightCBuffer].Descriptor.ShaderRegister = 3; - - // AppSettings - rootParameters[Deferred_AppSettings].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[Deferred_AppSettings].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[Deferred_AppSettings].Descriptor.RegisterSpace = 0; - rootParameters[Deferred_AppSettings].Descriptor.ShaderRegister = AppSettings::CBufferRegister; - - // Descriptors - rootParameters[Deferred_Descriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[Deferred_Descriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[Deferred_Descriptors].DescriptorTable.pDescriptorRanges = descriptorRanges; - rootParameters[Deferred_Descriptors].DescriptorTable.NumDescriptorRanges = ArraySize_(descriptorRanges); - - // Decal texture descriptors - rootParameters[Deferred_DecalDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[Deferred_DecalDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[Deferred_DecalDescriptors].DescriptorTable.pDescriptorRanges = decalTextureRanges; - rootParameters[Deferred_DecalDescriptors].DescriptorTable.NumDescriptorRanges = 1; - - D3D12_STATIC_SAMPLER_DESC staticSamplers[2] = {}; - staticSamplers[0] = DX12::GetStaticSamplerState(SamplerState::Anisotropic, 0, 0, D3D12_SHADER_VISIBILITY_ALL); - staticSamplers[1] = DX12::GetStaticSamplerState(SamplerState::ShadowMapPCF, 1, 0, D3D12_SHADER_VISIBILITY_ALL); - - D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; - rootSignatureDesc.NumParameters = ArraySize_(rootParameters); - rootSignatureDesc.pParameters = rootParameters; - rootSignatureDesc.NumStaticSamplers = ArraySize_(staticSamplers); - rootSignatureDesc.pStaticSamplers = staticSamplers; - rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; - - DX12::CreateRootSignature(&deferredRootSignature, rootSignatureDesc); - } - - numDecals = 0; -} - -void BindlessDeferred::Update(const Timer& timer) -{ - CPUProfileBlock profileBlock("Update"); - - AppSettings::UpdateUI(); - - MouseState mouseState = MouseState::GetMouseState(window); - KeyboardState kbState = KeyboardState::GetKeyboardState(window); - - currMouseState = mouseState; - - if(kbState.IsKeyDown(KeyboardState::Escape)) - window.Destroy(); - - float CamMoveSpeed = 5.0f * timer.DeltaSecondsF(); - const float CamRotSpeed = 0.180f * timer.DeltaSecondsF(); - - // Move the camera with keyboard input - if(kbState.IsKeyDown(KeyboardState::LeftShift)) - CamMoveSpeed *= 0.25f; - - Float3 camPos = camera.Position(); - if(kbState.IsKeyDown(KeyboardState::W)) - camPos += camera.Forward() * CamMoveSpeed; - else if (kbState.IsKeyDown(KeyboardState::S)) - camPos += camera.Back() * CamMoveSpeed; - if(kbState.IsKeyDown(KeyboardState::A)) - camPos += camera.Left() * CamMoveSpeed; - else if (kbState.IsKeyDown(KeyboardState::D)) - camPos += camera.Right() * CamMoveSpeed; - if(kbState.IsKeyDown(KeyboardState::Q)) - camPos += camera.Up() * CamMoveSpeed; - else if (kbState.IsKeyDown(KeyboardState::E)) - camPos += camera.Down() * CamMoveSpeed; - camera.SetPosition(camPos); - - // Rotate the camera with the mouse - if(mouseState.RButton.Pressed && mouseState.IsOverWindow) - { - float xRot = camera.XRotation(); - float yRot = camera.YRotation(); - xRot += mouseState.DY * CamRotSpeed; - yRot += mouseState.DX * CamRotSpeed; - camera.SetXRotation(xRot); - camera.SetYRotation(yRot); - } - - UpdateDecals(timer); - UpdateLights(); - - appViewMatrix = camera.ViewMatrix(); - - // Toggle VSYNC - swapChain.SetVSYNCEnabled(AppSettings::EnableVSync ? true : false); - - skyCache.Init(AppSettings::SunDirection, AppSettings::SunSize, AppSettings::GroundAlbedo, AppSettings::Turbidity, true); - - if(AppSettings::MSAAMode.Changed() || AppSettings::ClusterRasterizationMode.Changed()) - { - DestroyPSOs(); - CreateRenderTargets(); - CreatePSOs(); - } - - if(AppSettings::CurrentScene.Changed()) - { - currentModel = &sceneModels[uint64(AppSettings::CurrentScene)]; - DestroyPSOs(); - InitializeScene(); - CreatePSOs(); - } - - if(AppSettings::ComputeUVGradients.Changed()) - { - DestroyPSOs(); - CreatePSOs(); - } - - if(taskSet != nullptr && enkiIsTaskSetComplete(taskScheduler, taskSet)) - { - enkiDeleteTaskSet(taskSet); - enkiDeleteTaskScheduler(taskScheduler); - taskSet = nullptr; - taskScheduler = nullptr; - - DestroyPSOs(); - CreatePSOs(); - } -} - -void BindlessDeferred::Render(const Timer& timer) -{ - ID3D12GraphicsCommandList* cmdList = DX12::CmdList; - - CPUProfileBlock cpuProfileBlock("Render"); - ProfileBlock gpuProfileBlock(cmdList, "Render Total"); - - if(taskSet != nullptr) - { - // We're still waiting for shaders to compile, so print a message to the screen and skip the render loop - D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[1] = { swapChain.BackBuffer().RTV.CPUHandle }; - cmdList->OMSetRenderTargets(1, rtvHandles, false, nullptr); - - const float clearColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; - cmdList->ClearRenderTargetView(rtvHandles[0], clearColor, 0, nullptr); - - DX12::SetViewport(cmdList, swapChain.Width(), swapChain.Height()); - - Float2 viewportSize; - viewportSize.x = float(swapChain.Width()); - viewportSize.y = float(swapChain.Height()); - spriteRenderer.Begin(cmdList, viewportSize, SpriteFilterMode::Point, SpriteBlendMode::AlphaBlend); - - wchar text[32] = L"Compiling Shaders..."; - uint32 numDots = uint32(Frac(timer.ElapsedSecondsF()) * 4.0f); - text[17 + numDots] = 0; - Float2 textSize = font.MeasureText(text); - - Float2 textPos = (viewportSize * 0.5f) - (textSize * 0.5f); - spriteRenderer.RenderText(cmdList, font, text, textPos, Float4(1.0f, 1.0f, 1.0f, 1.0f)); - - spriteRenderer.End(); - - return; - } - - RenderClusters(); - - if(AppSettings::EnableSun) - meshRenderer.RenderSunShadowMap(cmdList, camera); - - if(AppSettings::RenderLights) - meshRenderer.RenderSpotLightShadowMap(cmdList, camera); - - // Update the light constant buffer - spotLightBuffer.InternalBuffer.UpdateData(spotLights.Data(), spotLights.MemorySize(), 0); - spotLightBuffer.InternalBuffer.UpdateData(meshRenderer.SpotLightShadowMatrices(), spotLights.Size() * sizeof(Float4x4), - sizeof(SpotLight) * AppSettings::MaxSpotLights); - spotLightBuffer.Transition(DX12::CmdList, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); - - if(AppSettings::RenderMode == RenderModes::ClusteredForward) - RenderForward(); - else - RenderDeferred(); - - RenderPicking(); - RenderResolve(); - - RenderTexture& finalRT = mainTarget.MSAASamples > 1 ? resolveTarget : mainTarget; - - { - ProfileBlock ppProfileBlock(cmdList, "Post Processing"); - postProcessor.Render(cmdList, finalRT, swapChain.BackBuffer()); - } - - D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[1] = { swapChain.BackBuffer().RTV.CPUHandle }; - cmdList->OMSetRenderTargets(1, rtvHandles, false, nullptr); - - RenderClusterVisualizer(); - - DX12::SetViewport(cmdList, swapChain.Width(), swapChain.Height()); - - RenderHUD(timer); - - // Transition updatable resources back to copy dest state - decalBuffer.Transition(DX12::CmdList, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_COPY_DEST); - spotLightBuffer.Transition(DX12::CmdList, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, D3D12_RESOURCE_STATE_COPY_DEST); -} - -void BindlessDeferred::UpdateDecals(const Timer& timer) -{ - if(AppSettings::ClearDecals.Pressed()) - numDecals = 0; - - // Update picking and placing new decals - cursorDecal = Decal(); - cursorDecal.Type = uint32(-1); - cursorDecalIntensity = 0.0f; - if(currMouseState.IsOverWindow && AppSettings::EnableDecalPicker) - { - // Update the decal cursor - const uint64 texIdx = currDecalType * AppSettings::NumTexturesPerDecal; - Assert_(texIdx < ArraySize_(decalTextures)); - - Float2 textureSize; - textureSize.x = float(decalTextures[texIdx].Width); - textureSize.y = float(decalTextures[texIdx].Height); - const float sizeScale = 1 / 1024.0f; - - const PickingData* pickingData = pickingReadbackBuffers[DX12::CurrFrameIdx].Map(); - if(pickingData->Normal != Float3(0.0f, 0.0f, 0.0f)) - { - const float decalThickness = 0.125f; - - cursorDecal.Position = pickingData->Position; - cursorDecal.Size = Float3(textureSize.x * sizeScale, textureSize.y * sizeScale, decalThickness); - cursorDecal.Type = uint32(currDecalType); - cursorDecalIntensity = float(std::cos(timer.ElapsedSecondsD() * Pi2)) * 0.25f + 0.5f; - - Float3 forward = -pickingData->Normal; - Float3 up = std::abs(Float3::Dot(forward, Float3(0.0f, 1.0f, 0.0f))) < 0.99f ? Float3(0.0f, 1.0f, 0.0f) : Float3(0.0f, 0.0f, 1.0f); - Float3 right = Float3::Normalize(Float3::Cross(up, forward)); - up = Float3::Cross(forward, right); - Float3x3 orientation = Float3x3(right, up, forward); - - cursorDecal.Orientation = Quaternion(orientation); - - if(currMouseState.MButton.RisingEdge) - { - // Place a new decal, and fill the buffer - const uint64 decalIdx = (numDecals++) % AppSettings::MaxDecals; - decals[decalIdx] = cursorDecal; - - currDecalType = (currDecalType + 1) % uint64(AppSettings::NumDecalTypes); - } - } - - pickingReadbackBuffers[DX12::CurrFrameIdx].Unmap(); - } - - // Update the Z bounds, and fill the buffers - const Float4x4 viewMatrix = camera.ViewMatrix(); - const float nearClip = camera.NearClip(); - const float farClip = camera.FarClip(); - const float zRange = farClip - nearClip; - const Float3 cameraPos = camera.Position(); - const float3 boxVerts[8] = { float3(-1, 1, -1), float3(1, 1, -1), float3(-1, 1, 1), float3(1, 1, 1), - float3(-1, -1, -1), float3(1, -1, -1), float3(-1, -1, 1), float3(1, -1, 1) }; - - // Come up with an oriented bounding box that surrounds the near clipping plane. We'll test this box - // for intersection with the decal's bounding box, and use that to estimate if the bounding - // geometry will end up getting clipped by the camera's near clipping plane - Float3 nearClipCenter = cameraPos + nearClip * camera.Forward(); - Float4x4 invProjection = Float4x4::Invert(camera.ProjectionMatrix()); - Float3 nearTopRight = Float3::Transform(Float3(1.0f, 1.0f, 0.0f), invProjection); - Float3 nearClipExtents = Float3(nearTopRight.x, nearTopRight.y, 0.01f); - DirectX::BoundingOrientedBox nearClipBox(nearClipCenter.ToXMFLOAT3(), nearClipExtents.ToXMFLOAT3(), camera.Orientation().ToXMFLOAT4()); - - ClusterBounds* boundsData = decalBoundsBuffer.Map(); - bool intersectsCamera[AppSettings::MaxDecals] = { }; - - const uint64 numDecalsToUpdate = Min(numDecals, AppSettings::MaxDecals); - for(uint64 decalIdx = 0; decalIdx < numDecalsToUpdate; ++decalIdx) - { - const Decal& decal = decals[decalIdx]; - - // Compute conservative Z bounds for the decal based on vertices of the bounding geometry - float minZ = FloatMax; - float maxZ = -FloatMax; - for(uint64 i = 0; i < 8; ++i) - { - Float3 boxVert = boxVerts[i] * decal.Size; - boxVert = Float3::Transform(boxVert, decal.Orientation); - boxVert += decal.Position; - - float vertZ = Float3::Transform(boxVert, viewMatrix).z; - minZ = Min(minZ, vertZ); - maxZ = Max(maxZ, vertZ); - } - - minZ = Saturate((minZ - nearClip) / zRange); - maxZ = Saturate((maxZ - nearClip) / zRange); - - uint64 minZTile = uint64(minZ * AppSettings::NumZTiles); - uint64 maxZTile = Min(uint64(maxZ * AppSettings::NumZTiles), AppSettings::NumZTiles - 1); - - ClusterBounds bounds; - bounds.Position = decal.Position; - bounds.Orientation = decal.Orientation; - bounds.Scale = decal.Size; - bounds.ZBounds = Uint2(uint32(minZTile), uint32(maxZTile)); - boundsData[decalIdx] = bounds; - - // Estimate if this decal's bounding geometry intersects with the camera's near clip plane - DirectX::BoundingOrientedBox box = DirectX::BoundingOrientedBox(decal.Position.ToXMFLOAT3(), decal.Size.ToXMFLOAT3(), decal.Orientation.ToXMFLOAT4()); - intersectsCamera[decalIdx] = box.Intersects(nearClipBox); - } - - decalBuffer.UpdateData(decals.Data(), decals.Size(), 0); - decalBuffer.Transition(DX12::CmdList, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_GENERIC_READ); - - numIntersectingDecals = 0; - uint32* instanceData = decalInstanceBuffer.Map(); - - for(uint64 decalIdx = 0; decalIdx < numDecalsToUpdate; ++decalIdx) - if(intersectsCamera[decalIdx]) - instanceData[numIntersectingDecals++] = uint32(decalIdx); - - uint64 offset = numIntersectingDecals; - for(uint64 decalIdx = 0; decalIdx < numDecalsToUpdate; ++decalIdx) - if(intersectsCamera[decalIdx] == false) - instanceData[offset++] = uint32(decalIdx); -} - -void BindlessDeferred::UpdateLights() -{ - const uint64 numSpotLights = Min(spotLights.Size(), AppSettings::MaxLightClamp); - - // This is an additional scale factor that's needed to make sure that our polygonal bounding cone - // fully encloses the actual cone representing the light's area of influence - const float inRadius = std::cos(Pi / NumConeSides); - const float scaleCorrection = 1.0f / inRadius; - - const Float4x4 viewMatrix = camera.ViewMatrix(); - const float nearClip = camera.NearClip(); - const float farClip = camera.FarClip(); - const float zRange = farClip - nearClip; - const Float3 cameraPos = camera.Position(); - const uint64 numConeVerts = coneVertices.Size(); - - // Come up with a bounding sphere that surrounds the near clipping plane. We'll test this sphere - // for intersection with the spot light's bounding cone, and use that to over-estimate if the bounding - // geometry will end up getting clipped by the camera's near clipping plane - Float3 nearClipCenter = cameraPos + nearClip * camera.Forward(); - Float4x4 invViewProjection = Float4x4::Invert(camera.ViewProjectionMatrix()); - Float3 nearTopRight = Float3::Transform(Float3(1.0f, 1.0f, 0.0f), invViewProjection); - float nearClipRadius = Float3::Length(nearTopRight - nearClipCenter); - - ClusterBounds* boundsData = spotLightBoundsBuffer.Map(); - bool intersectsCamera[AppSettings::MaxDecals] = { }; - - // Update the light bounds buffer - for(uint64 spotLightIdx = 0; spotLightIdx < numSpotLights; ++spotLightIdx) - { - const SpotLight& spotLight = spotLights[spotLightIdx]; - const ModelSpotLight& srcSpotLight = currentModel->SpotLights()[spotLightIdx]; - ClusterBounds bounds; - bounds.Position = spotLight.Position; - bounds.Orientation = srcSpotLight.Orientation; - bounds.Scale.x = bounds.Scale.y = std::tan(srcSpotLight.AngularAttenuation.y / 2.0f) * spotLight.Range * scaleCorrection; - bounds.Scale.z = spotLight.Range; - - // Compute conservative Z bounds for the light based on vertices of the bounding geometry - float minZ = FloatMax; - float maxZ = -FloatMax; - for(uint64 i = 0; i < numConeVerts; ++i) - { - Float3 coneVert = coneVertices[i] * bounds.Scale; - coneVert = Float3::Transform(coneVert, bounds.Orientation); - coneVert += bounds.Position; - - float vertZ = Float3::Transform(coneVert, viewMatrix).z; - minZ = Min(minZ, vertZ); - maxZ = Max(maxZ, vertZ); - } - - minZ = Saturate((minZ - nearClip) / zRange); - maxZ = Saturate((maxZ - nearClip) / zRange); - - bounds.ZBounds.x = uint32(minZ * AppSettings::NumZTiles); - bounds.ZBounds.y = Min(uint32(maxZ * AppSettings::NumZTiles), uint32(AppSettings::NumZTiles - 1)); - - // Estimate if the light's bounding geometry intersects with the camera's near clip plane - boundsData[spotLightIdx] = bounds; - intersectsCamera[spotLightIdx] = SphereConeIntersection(spotLight.Position, srcSpotLight.Direction, spotLight.Range, - srcSpotLight.AngularAttenuation.y, nearClipCenter, nearClipRadius); - } - - numIntersectingSpotLights = 0; - uint32* instanceData = spotLightInstanceBuffer.Map(); - - for(uint64 spotLightIdx = 0; spotLightIdx < numSpotLights; ++spotLightIdx) - if(intersectsCamera[spotLightIdx]) - instanceData[numIntersectingSpotLights++] = uint32(spotLightIdx); - - uint64 offset = numIntersectingSpotLights; - for(uint64 spotLightIdx = 0; spotLightIdx < numSpotLights; ++spotLightIdx) - if(intersectsCamera[spotLightIdx] == false) - instanceData[offset++] = uint32(spotLightIdx); -} - -void BindlessDeferred::RenderClusters() -{ - ID3D12GraphicsCommandList* cmdList = DX12::CmdList; - - PIXMarker marker(cmdList, "Cluster Update"); - ProfileBlock profileBlock(cmdList, "Cluster Update"); - - decalClusterBuffer.MakeWritable(cmdList); - spotLightClusterBuffer.MakeWritable(cmdList); - - if(AppSettings::RenderDecals) - { - // Clear decal clusters - D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptors[1] = { decalClusterBuffer.UAV() }; - DescriptorHandle gpuHandle = DX12::MakeDescriptorTable(ArraySize_(cpuDescriptors), cpuDescriptors); - - uint32 values[4] = { }; - cmdList->ClearUnorderedAccessViewUint(gpuHandle.GPUHandle, cpuDescriptors[0], decalClusterBuffer.InternalBuffer.Resource, values, 0, nullptr); - } - - if(AppSettings::RenderLights) - { - // Clear spot light clusters - D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptors[1] = { spotLightClusterBuffer.UAV() }; - DescriptorHandle gpuHandle = DX12::MakeDescriptorTable(ArraySize_(cpuDescriptors), cpuDescriptors); - - uint32 values[4] = { }; - cmdList->ClearUnorderedAccessViewUint(gpuHandle.GPUHandle, cpuDescriptors[0], spotLightClusterBuffer.InternalBuffer.Resource, values, 0, nullptr); - } - - clusterConstants.Data.ViewProjection = camera.ViewProjectionMatrix(); - clusterConstants.Data.InvProjection = Float4x4::Invert(camera.ProjectionMatrix()); - clusterConstants.Data.NearClip = camera.NearClip(); - clusterConstants.Data.FarClip = camera.FarClip(); - clusterConstants.Data.InvClipRange = 1.0f / (camera.FarClip() - camera.NearClip()); - clusterConstants.Data.NumXTiles = uint32(AppSettings::NumXTiles); - clusterConstants.Data.NumYTiles = uint32(AppSettings::NumYTiles); - clusterConstants.Data.NumXYTiles = uint32(AppSettings::NumXTiles * AppSettings::NumYTiles); - clusterConstants.Data.InstanceOffset = 0; - clusterConstants.Data.NumLights = Min(uint32(spotLights.Size()), AppSettings::MaxLightClamp); - clusterConstants.Data.NumDecals = uint32(Min(numDecals, AppSettings::MaxDecals)); - - D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[1] = { clusterMSAATarget.RTV.CPUHandle }; - ClusterRasterizationModes rastMode = AppSettings::ClusterRasterizationMode; - if(rastMode == ClusterRasterizationModes::MSAA4x || rastMode == ClusterRasterizationModes::MSAA8x) - cmdList->OMSetRenderTargets(1, rtvHandles, false, nullptr); - else - cmdList->OMSetRenderTargets(0, nullptr, false, nullptr); - - DX12::SetViewport(cmdList, AppSettings::NumXTiles, AppSettings::NumYTiles); - cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - - cmdList->SetGraphicsRootSignature(clusterRS); - - if(AppSettings::RenderDecals) - { - // Update decal clusters - decalClusterBuffer.UAVBarrier(cmdList); - - D3D12_INDEX_BUFFER_VIEW ibView = decalClusterIdxBuffer.IBView(); - cmdList->IASetIndexBuffer(&ibView); - - clusterConstants.Data.ElementsPerCluster = uint32(AppSettings::DecalElementsPerCluster); - clusterConstants.Data.InstanceOffset = 0; - clusterConstants.Upload(); - clusterConstants.SetAsGfxRootParameter(cmdList, 0); - - AppSettings::BindCBufferGfx(cmdList, 1); - - D3D12_CPU_DESCRIPTOR_HANDLE srvDescriptors[] = { decalBoundsBuffer.SRV(), decalClusterVtxBuffer.SRV(), decalInstanceBuffer.SRV() }; - DX12::BindShaderResources(cmdList, 2, ArraySize_(srvDescriptors), srvDescriptors); - - D3D12_CPU_DESCRIPTOR_HANDLE uavDescriptors[] = { decalClusterBuffer.UAV() }; - DX12::BindShaderResources(cmdList, 3, ArraySize_(uavDescriptors), uavDescriptors); - - const uint64 numDecalsToRender = Min(numDecals, AppSettings::MaxDecals); - Assert_(numIntersectingDecals <= numDecalsToRender); - const uint64 numNonIntersecting = numDecalsToRender - numIntersectingDecals; - - // Render back faces for decals that intersect with the camera - cmdList->SetPipelineState(clusterIntersectingPSO); - - cmdList->DrawIndexedInstanced(uint32(decalClusterIdxBuffer.NumElements), uint32(numIntersectingDecals), 0, 0, 0); - - // Now for all other decals, render the back faces followed by the front faces - cmdList->SetPipelineState(clusterBackFacePSO); - - clusterConstants.Data.InstanceOffset = uint32(numIntersectingDecals); - clusterConstants.Upload(); - clusterConstants.SetAsGfxRootParameter(cmdList, 0); - - cmdList->DrawIndexedInstanced(uint32(decalClusterIdxBuffer.NumElements), uint32(numNonIntersecting), 0, 0, 0); - - decalClusterBuffer.UAVBarrier(cmdList); - - cmdList->SetPipelineState(clusterFrontFacePSO); - - cmdList->DrawIndexedInstanced(uint32(decalClusterIdxBuffer.NumElements), uint32(numNonIntersecting), 0, 0, 0); - } - - if(AppSettings::RenderLights) - { - // Update decal clusters - spotLightClusterBuffer.UAVBarrier(cmdList); - - D3D12_INDEX_BUFFER_VIEW ibView = spotLightClusterIdxBuffer.IBView(); - cmdList->IASetIndexBuffer(&ibView); - - clusterConstants.Data.ElementsPerCluster = uint32(AppSettings::SpotLightElementsPerCluster); - clusterConstants.Data.InstanceOffset = 0; - clusterConstants.Upload(); - - clusterConstants.SetAsGfxRootParameter(cmdList, 0); - - AppSettings::BindCBufferGfx(cmdList, 1); - - D3D12_CPU_DESCRIPTOR_HANDLE srvDescriptors[] = { spotLightBoundsBuffer.SRV(), spotLightClusterVtxBuffer.SRV(), spotLightInstanceBuffer.SRV() }; - DX12::BindShaderResources(cmdList, 2, ArraySize_(srvDescriptors), srvDescriptors); - - D3D12_CPU_DESCRIPTOR_HANDLE uavDescriptors[] = { spotLightClusterBuffer.UAV() }; - DX12::BindShaderResources(cmdList, 3, ArraySize_(uavDescriptors), uavDescriptors); - - const uint64 numLightsToRender = Min(spotLights.Size(), AppSettings::MaxLightClamp); - Assert_(numIntersectingSpotLights <= numLightsToRender); - const uint64 numNonIntersecting = numLightsToRender - numIntersectingSpotLights; - - // Render back faces for decals that intersect with the camera - cmdList->SetPipelineState(clusterIntersectingPSO); - - cmdList->DrawIndexedInstanced(uint32(spotLightClusterIdxBuffer.NumElements), uint32(numIntersectingSpotLights), 0, 0, 0); - - // Now for all other lights, render the back faces followed by the front faces - cmdList->SetPipelineState(clusterBackFacePSO); - - clusterConstants.Data.InstanceOffset = uint32(numIntersectingSpotLights); - clusterConstants.Upload(); - clusterConstants.SetAsGfxRootParameter(cmdList, 0); - - cmdList->DrawIndexedInstanced(uint32(spotLightClusterIdxBuffer.NumElements), uint32(numNonIntersecting), 0, 0, 0); - - spotLightClusterBuffer.UAVBarrier(cmdList); - - cmdList->SetPipelineState(clusterFrontFacePSO); - - cmdList->DrawIndexedInstanced(uint32(spotLightClusterIdxBuffer.NumElements), uint32(numNonIntersecting), 0, 0, 0); - } - - // Sync - decalClusterBuffer.MakeReadable(cmdList); - spotLightClusterBuffer.MakeReadable(cmdList); -} - -void BindlessDeferred::RenderForward() -{ - ID3D12GraphicsCommandList* cmdList = DX12::CmdList; - - PIXMarker marker(cmdList, "Forward rendering"); - - { - // Transition render targets and depth buffers back to a writable state, and sync on the shadow maps - D3D12_RESOURCE_BARRIER barriers[5] = {}; - barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[0].Transition.pResource = mainTarget.Resource(); - barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; - barriers[0].Transition.Subresource = 0; - - barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[1].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[1].Transition.pResource = tangentFrameTarget.Resource(); - barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; - barriers[1].Transition.Subresource = 0; - - barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[2].Transition.pResource = depthBuffer.Resource(); - barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_DEPTH_READ; - barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barriers[2].Transition.Subresource = 0; - - barriers[3].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[3].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[3].Transition.pResource = meshRenderer.SunShadowMap().Resource(); - barriers[3].Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barriers[3].Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - barriers[3].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - - barriers[4].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[4].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[4].Transition.pResource = meshRenderer.SpotLightShadowMap().Resource(); - barriers[4].Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barriers[4].Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - barriers[4].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - - cmdList->ResourceBarrier(ArraySize_(barriers), barriers); - } - - D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[2] = { mainTarget.RTV.CPUHandle, tangentFrameTarget.RTV.CPUHandle }; - cmdList->OMSetRenderTargets(2, rtvHandles, false, &depthBuffer.DSV.CPUHandle); - - const float clearColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; - cmdList->ClearRenderTargetView(rtvHandles[0], clearColor, 0, nullptr); - cmdList->ClearRenderTargetView(rtvHandles[1], clearColor, 0, nullptr); - cmdList->ClearDepthStencilView(depthBuffer.DSV.CPUHandle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr); - - DX12::SetViewport(cmdList, mainTarget.Width(), mainTarget.Height()); - - if(AppSettings::DepthPrepass) - meshRenderer.RenderDepthPrepass(cmdList, camera); - - { - ProfileBlock profileBlock(cmdList, "Forward Rendering Pass"); - - // Render the main forward pass - MainPassData mainPassData; - mainPassData.SkyCache = &skyCache; - mainPassData.DecalTextures = decalTextures; - mainPassData.DecalBuffer = &decalBuffer; - mainPassData.CursorDecal = cursorDecal; - mainPassData.CursorDecalIntensity = cursorDecalIntensity; - mainPassData.DecalClusterBuffer = &decalClusterBuffer; - mainPassData.SpotLightBuffer = &spotLightBuffer; - mainPassData.SpotLightClusterBuffer = &spotLightClusterBuffer; - meshRenderer.RenderMainPass(cmdList, camera, mainPassData); - - cmdList->OMSetRenderTargets(1, rtvHandles, false, &depthBuffer.DSV.CPUHandle); - - // Render the sky - skybox.RenderSky(cmdList, camera.ViewMatrix(), camera.ProjectionMatrix(), skyCache, true); - - { - // Make our targets readable again, which will force a sync point. Also transition - // the shadow maps back to their writable state - D3D12_RESOURCE_BARRIER barriers[5] = {}; - barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[0].Transition.pResource = mainTarget.Resource(); - barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; - barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - barriers[0].Transition.Subresource = 0; - - barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[1].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[1].Transition.pResource = tangentFrameTarget.Resource(); - barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; - barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[1].Transition.Subresource = 0; - - barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[2].Transition.pResource = depthBuffer.Resource(); - barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_DEPTH_READ; - barriers[2].Transition.Subresource = 0; - - barriers[3].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[3].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[3].Transition.pResource = meshRenderer.SunShadowMap().Resource(); - barriers[3].Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - barriers[3].Transition.StateAfter = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barriers[3].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - - barriers[4].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[4].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[4].Transition.pResource = meshRenderer.SpotLightShadowMap().Resource(); - barriers[4].Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - barriers[4].Transition.StateAfter = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barriers[4].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - - cmdList->ResourceBarrier(ArraySize_(barriers), barriers); - } - } -} - -void BindlessDeferred::RenderDeferred() -{ - ID3D12GraphicsCommandList* cmdList = DX12::CmdList; - - PIXMarker marker(cmdList, "Render Deferred"); - - { - // Transition our G-Buffer targets to a writable state, and sync on shadow map rendering - D3D12_RESOURCE_BARRIER barriers[7] = {}; - barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[0].Transition.pResource = depthBuffer.Resource(); - barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_DEPTH_READ; - barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barriers[0].Transition.Subresource = 0; - - barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[1].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[1].Transition.pResource = tangentFrameTarget.Resource(); - barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; - barriers[1].Transition.Subresource = 0; - - barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[2].Transition.pResource = uvTarget.Resource(); - barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; - barriers[2].Transition.Subresource = 0; - - barriers[3].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[3].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[3].Transition.pResource = materialIDTarget.Resource(); - barriers[3].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[3].Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; - barriers[3].Transition.Subresource = 0; - - barriers[4].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[4].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[4].Transition.pResource = meshRenderer.SunShadowMap().Resource(); - barriers[4].Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barriers[4].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[4].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - - barriers[5].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[5].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[5].Transition.pResource = meshRenderer.SpotLightShadowMap().Resource(); - barriers[5].Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barriers[5].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[5].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - - barriers[6].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[6].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[6].Transition.pResource = uvGradientsTarget.Resource(); - barriers[6].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[6].Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; - barriers[6].Transition.Subresource = 0; - - const uint32 numBarriers = AppSettings::ComputeUVGradients ? ArraySize_(barriers) - 1 : ArraySize_(barriers); - cmdList->ResourceBarrier(numBarriers, barriers); - } - - { - // Set the G-Buffer render targets and clear them - D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[] = { tangentFrameTarget.RTV.CPUHandle, uvTarget.RTV.CPUHandle, - materialIDTarget.RTV.CPUHandle, uvGradientsTarget.RTV.CPUHandle }; - const uint32 numTargets = AppSettings::ComputeUVGradients ? ArraySize_(rtvHandles) - 1 : ArraySize_(rtvHandles); - cmdList->OMSetRenderTargets(numTargets, rtvHandles, false, &depthBuffer.DSV.CPUHandle); - - const float clearColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; - for(uint64 i = 0; i < numTargets; ++i) - cmdList->ClearRenderTargetView(rtvHandles[i], clearColor, 0, nullptr); - cmdList->ClearDepthStencilView(depthBuffer.DSV.CPUHandle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr); - } - - DX12::SetViewport(cmdList, mainTarget.Width(), mainTarget.Height()); - - /*if(AppSettings::DepthPrepass) - meshRenderer.RenderDepthPrepass(cmdList, camera);*/ - - const uint64 msaaMode = uint64(AppSettings::MSAAMode); - const bool msaaEnabled = AppSettings::MSAAMode != MSAAModes::MSAANone; - - { - // Render the G-Buffer, and sync - ProfileBlock profileBlock(cmdList, "G-Buffer Rendering"); - - meshRenderer.RenderGBuffer(cmdList, camera); - - D3D12_RESOURCE_BARRIER barriers[5] = {}; - barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[0].Transition.pResource = depthBuffer.Resource(); - barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_DEPTH_READ; - barriers[0].Transition.Subresource = 0; - - barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[1].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[1].Transition.pResource = tangentFrameTarget.Resource(); - barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; - barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[1].Transition.Subresource = 0; - - barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[2].Transition.pResource = uvTarget.Resource(); - barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; - barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[2].Transition.Subresource = 0; - - barriers[3].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[3].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[3].Transition.pResource = materialIDTarget.Resource(); - barriers[3].Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; - barriers[3].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[3].Transition.Subresource = 0; - - barriers[4].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[4].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[4].Transition.pResource = uvGradientsTarget.Resource(); - barriers[4].Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; - barriers[4].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[4].Transition.Subresource = 0; - - const uint32 numBarriers = AppSettings::ComputeUVGradients ? ArraySize_(barriers) - 1 : ArraySize_(barriers); - cmdList->ResourceBarrier(numBarriers, barriers); - } - - const uint32 numComputeTilesX = uint32(AlignTo(mainTarget.Width(), AppSettings::DeferredTileSize) / AppSettings::DeferredTileSize); - const uint32 numComputeTilesY = uint32(AlignTo(mainTarget.Height(), AppSettings::DeferredTileSize) / AppSettings::DeferredTileSize); - - if(msaaEnabled) - { - // Generate dispatch lists for for per-sample shading - PIXMarker maskMarker(cmdList, "MSAA Mask"); - ProfileBlock profileBlock(cmdList, "MSAA Mask"); - - // Clear the structure counts - { - D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptors[1] = { nonMsaaTileBuffer.CounterUAV.CPUHandle }; - DescriptorHandle gpuHandle = DX12::MakeDescriptorTable(ArraySize_(cpuDescriptors), cpuDescriptors); - - uint32 values[4] = {}; - cmdList->ClearUnorderedAccessViewUint(gpuHandle.GPUHandle, cpuDescriptors[0], nonMsaaTileBuffer.CounterResource, values, 0, nullptr); - } - - { - D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptors[1] = { msaaTileBuffer.CounterUAV.CPUHandle }; - DescriptorHandle gpuHandle = DX12::MakeDescriptorTable(ArraySize_(cpuDescriptors), cpuDescriptors); - - uint32 values[4] = {}; - cmdList->ClearUnorderedAccessViewUint(gpuHandle.GPUHandle, cpuDescriptors[0], msaaTileBuffer.CounterResource, values, 0, nullptr); - } - - { - // Issue barriers - D3D12_RESOURCE_BARRIER barriers[5] = {}; - barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; - barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[0].UAV.pResource = nonMsaaTileBuffer.CounterResource; - - barriers[1] = barriers[0]; - barriers[1].UAV.pResource = msaaTileBuffer.CounterResource; - - barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[2].Transition.pResource = nonMsaaTileBuffer.Resource(); - barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; - barriers[2].Transition.Subresource = 0; - - barriers[3] = barriers[2]; - barriers[3].Transition.pResource = msaaTileBuffer.Resource(); - - barriers[4] = barriers[2]; - barriers[4].Transition.pResource = msaaMaskBuffer.Resource(); - - cmdList->ResourceBarrier(ArraySize_(barriers), barriers); - } - - // Generate the edge mask, and fill the buffers containing edge/non-edge tiles - cmdList->SetComputeRootSignature(msaaMaskRootSignature); - cmdList->SetPipelineState(AppSettings::UseZGradientsForMSAAMask ? msaaMaskPSOs[1] : msaaMaskPSOs[0]); - - msaaMaskConstants.Data.NumXTiles = numComputeTilesX; - msaaMaskConstants.Upload(); - msaaMaskConstants.SetAsComputeRootParameter(cmdList, 0); - - AppSettings::BindCBufferCompute(cmdList, 1); - - D3D12_CPU_DESCRIPTOR_HANDLE descriptors[] = - { - materialIDTarget.SRV(), - uvTarget.SRV(), - nonMsaaTileBuffer.UAV(), - msaaTileBuffer.UAV(), - msaaMaskBuffer.UAV(), - }; - - DX12::BindShaderResources(cmdList, 2, ArraySize_(descriptors), descriptors, CmdListMode::Compute); - - cmdList->Dispatch(numComputeTilesX, numComputeTilesY, 1); - - { - // Sync on our buffers - D3D12_RESOURCE_BARRIER barriers[4] = {}; - barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[0].Transition.pResource = nonMsaaTileBuffer.CounterResource; - barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; - barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; - barriers[0].Transition.Subresource = 0; - - barriers[1] = barriers[0]; - barriers[1].Transition.pResource = msaaTileBuffer.CounterResource; - - barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[2].Transition.pResource = nonMsaaArgsBuffer.Resource(); - barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; - barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; - barriers[2].Transition.Subresource = 0; - - barriers[3] = barriers[2]; - barriers[3].Transition.pResource = msaaArgsBuffer.Resource(); - - cmdList->ResourceBarrier(ArraySize_(barriers), barriers); - } - - // Copy off the structure counts to our indirect args buffers - cmdList->CopyBufferRegion(nonMsaaArgsBuffer.Resource(), 0, nonMsaaTileBuffer.CounterResource, 0, sizeof(uint32)); - cmdList->CopyBufferRegion(msaaArgsBuffer.Resource(), 0, msaaTileBuffer.CounterResource, 0, sizeof(uint32)); - - { - // Issue remaining barriers - D3D12_RESOURCE_BARRIER barriers[7] = {}; - barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[0].Transition.pResource = nonMsaaTileBuffer.CounterResource; - barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; - barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; - barriers[0].Transition.Subresource = 0; - - barriers[1] = barriers[0]; - barriers[1].Transition.pResource = msaaTileBuffer.CounterResource; - - barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[2].Transition.pResource = nonMsaaArgsBuffer.Resource(); - barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; - barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; - barriers[2].Transition.Subresource = 0; - - barriers[3] = barriers[2]; - barriers[3].Transition.pResource = msaaArgsBuffer.Resource(); - - barriers[4].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[4].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[4].Transition.pResource = nonMsaaTileBuffer.Resource(); - barriers[4].Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; - barriers[4].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[4].Transition.Subresource = 0; - - barriers[5] = barriers[4]; - barriers[5].Transition.pResource = msaaTileBuffer.Resource(); - - barriers[6] = barriers[4]; - barriers[6].Transition.pResource = msaaMaskBuffer.Resource(); - - cmdList->ResourceBarrier(ArraySize_(barriers), barriers); - } - } - - if(msaaEnabled) - { - // Render the sky in the empty areas - mainTarget.Transition(cmdList, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); - - D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[1] = { mainTarget.RTV.CPUHandle }; - cmdList->OMSetRenderTargets(1, rtvHandles, false, &depthBuffer.DSV.CPUHandle); - - skybox.RenderSky(cmdList, camera.ViewMatrix(), camera.ProjectionMatrix(), skyCache, true); - - mainTarget.Transition(cmdList, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - } - - { - // Render the full-screen deferred pass - PIXMarker deferredMarker(cmdList, "Deferred Rendering"); - ProfileBlock profileBlock(cmdList, "Deferred Rendering"); - - RenderTexture& deferredTarget = msaaEnabled ? deferredMSAATarget : mainTarget; - deferredTarget.Transition(cmdList, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - - cmdList->SetComputeRootSignature(deferredRootSignature); - cmdList->SetPipelineState(deferredPSOs[0]); - - // Set constant buffers - deferredConstants.Data.InvViewProj = Float4x4::Invert(camera.ViewProjectionMatrix()); - deferredConstants.Data.Projection = camera.ProjectionMatrix(); - deferredConstants.Data.RTSize = Float2(float(mainTarget.Width()), float(mainTarget.Height())); - deferredConstants.Data.NumComputeTilesX = numComputeTilesX; - deferredConstants.Upload(); - deferredConstants.SetAsComputeRootParameter(cmdList, Deferred_DeferredCBuffer); - - shadingConstants.Data.SunDirectionWS = AppSettings::SunDirection; - shadingConstants.Data.SunIrradiance = skyCache.SunIrradiance; - shadingConstants.Data.CosSunAngularRadius = std::cos(DegToRad(AppSettings::SunSize)); - shadingConstants.Data.SinSunAngularRadius = std::sin(DegToRad(AppSettings::SunSize)); - shadingConstants.Data.CameraPosWS = camera.Position(); - - shadingConstants.Data.CursorDecalPos = cursorDecal.Position; - shadingConstants.Data.CursorDecalIntensity = cursorDecalIntensity; - shadingConstants.Data.CursorDecalOrientation = cursorDecal.Orientation; - shadingConstants.Data.CursorDecalSize = cursorDecal.Size; - shadingConstants.Data.CursorDecalType = cursorDecal.Type; - shadingConstants.Data.NumXTiles = uint32(AppSettings::NumXTiles); - shadingConstants.Data.NumXYTiles = uint32(AppSettings::NumXTiles * AppSettings::NumYTiles); - shadingConstants.Data.NearClip = camera.NearClip(); - shadingConstants.Data.FarClip = camera.FarClip(); - - shadingConstants.Data.SkySH = skyCache.SH; - shadingConstants.Upload(); - shadingConstants.SetAsComputeRootParameter(cmdList, Deferred_PSCBuffer); - - ConstantBuffer& sunShadowConstants = meshRenderer.SunShadowConstantBuffer(); - sunShadowConstants.Upload(); - sunShadowConstants.SetAsComputeRootParameter(cmdList, Deferred_ShadowCBuffer); - - cmdList->SetComputeRootConstantBufferView(Deferred_LightCBuffer, spotLightBuffer.InternalBuffer.GPUAddress); - - AppSettings::BindCBufferCompute(cmdList, Deferred_AppSettings); - - D3D12_CPU_DESCRIPTOR_HANDLE skyTargetSRV = DX12::NullTexture2DSRV.CPUHandle; - if(msaaEnabled) - skyTargetSRV = mainTarget.SRV(); - - D3D12_CPU_DESCRIPTOR_HANDLE descriptors[] = - { - deferredTarget.UAV.CPUHandle, - meshRenderer.SunShadowMap().SRV(), - meshRenderer.SpotLightShadowMap().SRV(), - meshRenderer.MaterialTextureIndicesBuffer().SRV(), - decalBuffer.SRV(), - decalClusterBuffer.SRV(), - spotLightClusterBuffer.SRV(), - nonMsaaTileBuffer.SRV(), - msaaTileBuffer.SRV(), - tangentFrameTarget.SRV(), - uvTarget.SRV(), - uvGradientsTarget.SRV(), - materialIDTarget.SRV(), - depthBuffer.SRV(), - skyTargetSRV, - msaaMaskBuffer.SRV(), - }; - - // We need to get everything into a contiguous shader-visible descriptor table - const uint64 numMaterialTextures = currentModel->MaterialTextures().Count(); - LinearDescriptorHeap& descriptorHeap = DX12::SRVDescriptorHeapGPU[DX12::CurrFrameIdx]; - DescriptorHandle tableStart = descriptorHeap.Allocate(ArraySize_(descriptors) + numMaterialTextures); - - // First the non-material descriptors - for(uint64 i = 0; i < ArraySize_(descriptors); ++i) - { - D3D12_CPU_DESCRIPTOR_HANDLE dstDescriptor = tableStart.CPUHandle; - dstDescriptor.ptr += i * DX12::SRVDescriptorSize; - DX12::Device->CopyDescriptorsSimple(1, dstDescriptor, descriptors[i], D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - } - - // And now the material textures - D3D12_CPU_DESCRIPTOR_HANDLE srcMaterialTextures = currentModel->MaterialTextureDescriptors(); - D3D12_CPU_DESCRIPTOR_HANDLE dstMaterialTextures = tableStart.CPUHandle; - dstMaterialTextures.ptr += ArraySize_(descriptors) * DX12::SRVDescriptorSize; - DX12::Device->CopyDescriptorsSimple(uint32(numMaterialTextures), dstMaterialTextures, srcMaterialTextures, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - - cmdList->SetComputeRootDescriptorTable(Deferred_Descriptors, tableStart.GPUHandle); - - // Bind the decal textures - D3D12_CPU_DESCRIPTOR_HANDLE decalDescriptors[AppSettings::NumDecalTextures] = { }; - for(uint64 i = 0; i < AppSettings::NumDecalTextures; ++i) - decalDescriptors[i] = decalTextures[i].SRV.CPUHandle; - - DX12::BindShaderResources(cmdList, Deferred_DecalDescriptors, AppSettings::NumDecalTextures, decalDescriptors, CmdListMode::Compute); - - if(msaaEnabled) - cmdList->ExecuteIndirect(deferredCmdSignature, 1, nonMsaaArgsBuffer.Resource(), 0, nullptr, 0); - else - cmdList->Dispatch(numComputeTilesX, numComputeTilesY, 1); - - if(msaaEnabled) - { - // No need to sync here, both passes write to different tiles - cmdList->SetPipelineState(deferredPSOs[1]); - - cmdList->ExecuteIndirect(deferredCmdSignature, 1, msaaArgsBuffer.Resource(), 0, nullptr, 0); - - // Sync on the results - D3D12_RESOURCE_BARRIER barriers[2] = {}; - barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[0].Transition.pResource = deferredMSAATarget.Resource(); - barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; - barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - barriers[0].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - - barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[1].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[1].Transition.pResource = mainTarget.Resource(); - barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - barriers[1].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - - cmdList->ResourceBarrier(ArraySize_(barriers), barriers); - } - else - { - // Render the sky in the empty areas - mainTarget.Transition(cmdList, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_RENDER_TARGET); - - D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[1] = { mainTarget.RTV.CPUHandle }; - cmdList->OMSetRenderTargets(1, rtvHandles, false, &depthBuffer.DSV.CPUHandle); - - skybox.RenderSky(cmdList, camera.ViewMatrix(), camera.ProjectionMatrix(), skyCache, true); - - mainTarget.Transition(cmdList, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); - } - } - - { - // Transition the shadow maps back into their writable state - D3D12_RESOURCE_BARRIER barriers[2] = {}; - - barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[0].Transition.pResource = meshRenderer.SunShadowMap().Resource(); - barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barriers[0].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - - barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barriers[1].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barriers[1].Transition.pResource = meshRenderer.SpotLightShadowMap().Resource(); - barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barriers[1].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - - cmdList->ResourceBarrier(ArraySize_(barriers), barriers); - } -} - -// Performs MSAA resolve with a full-screen pixel shader -void BindlessDeferred::RenderResolve() -{ - if(AppSettings::MSAAMode == MSAAModes::MSAANone) - return; - - ID3D12GraphicsCommandList* cmdList = DX12::CmdList; - - PIXMarker pixMarker(cmdList, "MSAA Resolve"); - ProfileBlock profileBlock(cmdList, "MSAA Resolve"); - - resolveTarget.MakeWritable(cmdList); - - D3D12_CPU_DESCRIPTOR_HANDLE rtvs[1] = { resolveTarget.RTV.CPUHandle }; - cmdList->OMSetRenderTargets(ArraySize_(rtvs), rtvs, false, nullptr); - DX12::SetViewport(cmdList, resolveTarget.Width(), resolveTarget.Height()); - - const uint64 deferred = AppSettings::RenderMode == RenderModes::DeferredTexturing ? 1 : 0; - ID3D12PipelineState* pso = resolvePSOs[deferred]; - - cmdList->SetGraphicsRootSignature(resolveRootSignature); - cmdList->SetPipelineState(pso); - - cmdList->SetGraphicsRoot32BitConstant(0, uint32(mainTarget.Width()), 0); - cmdList->SetGraphicsRoot32BitConstant(0, uint32(mainTarget.Height()), 1); - - AppSettings::BindCBufferGfx(cmdList, 1); - - D3D12_CPU_DESCRIPTOR_HANDLE srvs[1] = { deferred ? deferredMSAATarget.SRV() : mainTarget.SRV() }; - DX12::BindShaderResources(cmdList, 2, ArraySize_(srvs), srvs); - - cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - cmdList->IASetIndexBuffer(nullptr); - cmdList->IASetVertexBuffers(0, 0, nullptr); - - cmdList->DrawInstanced(3, 1, 0, 0); - - resolveTarget.MakeReadable(cmdList); -} - -// Runs a simple compute shader that reads depth + tangent from for a particular pixel, and copies -// the results to a readback buffer that's used to generate the "cursor" decal -void BindlessDeferred::RenderPicking() -{ - if(currMouseState.IsOverWindow == false || AppSettings::EnableDecalPicker == false) - return; - - ID3D12GraphicsCommandList* cmdList = DX12::CmdList; - - PIXMarker pixMarker(cmdList, "Picking"); - - cmdList->SetPipelineState(AppSettings::MSAAMode != MSAAModes::MSAANone ? pickingPSOs[1] : pickingPSOs[0]); - cmdList->SetComputeRootSignature(pickingRS); - - pickingConstants.Data.InverseViewProjection = Float4x4::Invert(camera.ViewProjectionMatrix()); - pickingConstants.Data.PixelPos = Uint2(currMouseState.X, currMouseState.Y); - pickingConstants.Data.RTSize.x = float(mainTarget.Width()); - pickingConstants.Data.RTSize.y = float(mainTarget.Height()); - pickingConstants.Upload(); - pickingConstants.SetAsComputeRootParameter(cmdList, 0); - - pickingBuffer.MakeWritable(cmdList); - - D3D12_CPU_DESCRIPTOR_HANDLE descriptors[3] = { tangentFrameTarget.SRV(), depthBuffer.SRV(), pickingBuffer.UAV() }; - DX12::BindShaderResources(cmdList, 1, ArraySize_(descriptors), descriptors, CmdListMode::Compute); - - cmdList->Dispatch(1, 1, 1); - - pickingBuffer.MakeReadable(cmdList); - - cmdList->CopyResource(pickingReadbackBuffers[DX12::CurrFrameIdx].Resource, pickingBuffer.InternalBuffer.Resource); -} - -// Renders the 2D "overhead" visualizer that shows per-cluster light/decal counts -void BindlessDeferred::RenderClusterVisualizer() -{ - if(AppSettings::ShowClusterVisualizer == false) - return; - - ID3D12GraphicsCommandList* cmdList = DX12::CmdList; - - PIXMarker pixMarker(cmdList, "Cluster Visualizer"); - - Float2 displaySize = Float2(float(swapChain.Width()), float(swapChain.Height())); - Float2 drawSize = displaySize * 0.375f; - Float2 drawPos = displaySize * (0.5f + (0.5f - 0.375f) / 2.0f); - - D3D12_VIEWPORT viewport = { }; - viewport.Width = drawSize.x; - viewport.Height = drawSize.y; - viewport.MinDepth = 0.0f; - viewport.MaxDepth = 1.0f; - viewport.TopLeftX = drawPos.x; - viewport.TopLeftY = drawPos.y; - - D3D12_RECT scissorRect = { }; - scissorRect.left = 0; - scissorRect.top = 0; - scissorRect.right = uint32(swapChain.Width()); - scissorRect.bottom = uint32(swapChain.Height()); - - cmdList->RSSetViewports(1, &viewport); - cmdList->RSSetScissorRects(1, &scissorRect); - - cmdList->SetGraphicsRootSignature(clusterVisRootSignature); - cmdList->SetPipelineState(clusterVisPSO); - - Float4x4 invProjection = Float4x4::Invert(camera.ProjectionMatrix()); - Float3 farTopRight = Float3::Transform(Float3(1.0f, 1.0f, 1.0f), invProjection); - Float3 farBottomLeft = Float3::Transform(Float3(-1.0f, -1.0f, 1.0f), invProjection); - - clusterVisConstants.Data.Projection = camera.ProjectionMatrix(); - clusterVisConstants.Data.ViewMin = Float3(farBottomLeft.x, farBottomLeft.y, camera.NearClip()); - clusterVisConstants.Data.NearClip = camera.NearClip(); - clusterVisConstants.Data.ViewMax = Float3(farTopRight.x, farTopRight.y, camera.FarClip()); - clusterVisConstants.Data.InvClipRange = 1.0f / (camera.FarClip() - camera.NearClip()); - clusterVisConstants.Data.DisplaySize = displaySize; - clusterVisConstants.Data.NumXTiles = uint32(AppSettings::NumXTiles); - clusterVisConstants.Data.NumXYTiles = uint32(AppSettings::NumXTiles * AppSettings::NumYTiles); - clusterVisConstants.Upload(); - clusterVisConstants.SetAsGfxRootParameter(cmdList, 0); - - AppSettings::BindCBufferGfx(cmdList, 1); - - D3D12_CPU_DESCRIPTOR_HANDLE srvs[] = { decalClusterBuffer.SRV(), spotLightClusterBuffer.SRV() }; - DX12::BindShaderResources(cmdList, 2, ArraySize_(srvs), srvs); - - cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - cmdList->IASetIndexBuffer(nullptr); - cmdList->IASetVertexBuffers(0, 0, nullptr); - - cmdList->DrawInstanced(3, 1, 0, 0); -} - -void BindlessDeferred::RenderHUD(const Timer& timer) -{ - ID3D12GraphicsCommandList* cmdList = DX12::CmdList; - PIXMarker pixMarker(cmdList, "HUD Pass"); - - Float2 viewportSize; - viewportSize.x = float(swapChain.Width()); - viewportSize.y = float(swapChain.Height()); - spriteRenderer.Begin(cmdList, viewportSize, SpriteFilterMode::Point, SpriteBlendMode::AlphaBlend); - - Float2 textPos = Float2(25.0f, 25.0f); - wstring fpsText = MakeString(L"Frame Time: %.2fms (%u FPS)", 1000.0f / fps, fps); - spriteRenderer.RenderText(cmdList, font, fpsText.c_str(), textPos, Float4(1.0f, 1.0f, 0.0f, 1.0f)); - - spriteRenderer.End(); -} - -int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) -{ - BindlessDeferred app; - app.Run(); -} +//================================================================================================= +// +// Bindless Deferred Texturing Sample +// by MJP +// http://mynameismjp.wordpress.com/ +// +// All code and content licensed under the MIT license +// +//================================================================================================= + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "BindlessDeferred.h" +#include "SharedTypes.h" + +using namespace SampleFramework12; +using std::wstring; + +// Model filenames +static const wchar* ScenePaths[] = +{ + L"..\\Content\\Models\\Sponza\\Sponza.fbx", +}; + +static const float SceneScales[] = { 0.01f }; +static const Float3 SceneCameraPositions[] = { Float3(-11.5f, 1.85f, -0.45f) }; +static const Float2 SceneCameraRotations[] = { Float2(0.0f, 1.544f) }; + +StaticAssert_(ArraySize_(ScenePaths) == uint64(Scenes::NumValues)); +StaticAssert_(ArraySize_(SceneScales) == uint64(Scenes::NumValues)); +StaticAssert_(ArraySize_(SceneCameraPositions) == uint64(Scenes::NumValues)); +StaticAssert_(ArraySize_(SceneCameraRotations) == uint64(Scenes::NumValues)); + +static const uint64 NumConeSides = 16; + +static const float SpotLightIntensityFactor = 25.0f; + +static enkiTaskScheduler* taskScheduler = nullptr; +static enkiTaskSet* taskSet = nullptr; +static const bool EnableMultithreadedCompilation = true; + +struct PickingData +{ + Float3 Position; + Float3 Normal; +}; + +struct LightConstants +{ + SpotLight Lights[AppSettings::MaxSpotLights]; + Float4x4 ShadowMatrices[AppSettings::MaxSpotLights]; +}; + +struct ClusterConstants +{ + Float4x4 ViewProjection; + Float4x4 InvProjection; + float NearClip = 0.0f; + float FarClip = 0.0f; + float InvClipRange = 0.0f; + uint32 NumXTiles = 0; + uint32 NumYTiles = 0; + uint32 NumXYTiles = 0; + uint32 ElementsPerCluster = 0; + uint32 InstanceOffset = 0; + uint32 NumLights = 0; + uint32 NumDecals = 0; + + uint32 BoundsBufferIdx = uint32(-1); + uint32 VertexBufferIdx = uint32(-1); + uint32 InstanceBufferIdx = uint32(-1); +}; + +struct MSAAMaskConstants +{ + uint32 NumXTiles = 0; + uint32 MaterialIDMapIdx = uint32(-1); + uint32 UVMapIdx = uint32(-1); +}; + +struct DeferredConstants +{ + Float4x4 InvViewProj; + Float4x4 Projection; + Float2 RTSize; + uint32 NumComputeTilesX = 0; +}; + +struct PickingConstants +{ + Float4x4 InverseViewProjection; + Uint2 PixelPos; + Float2 RTSize; + uint32 TangentMapIdx = uint32(-1); + uint32 DepthMapIdx = uint32(-1); +}; + +struct ClusterVisConstants +{ + Float4x4 Projection; + Float3 ViewMin; + float NearClip = 0.0f; + Float3 ViewMax; + float InvClipRange = 0.0f; + Float2 DisplaySize; + uint32 NumXTiles = 0; + uint32 NumXYTiles = 0; + + uint32 DecalClusterBufferIdx = uint32(-1); + uint32 SpotLightClusterBufferIdx = uint32(-1); +}; + +enum ClusterRootParams : uint32 +{ + ClusterParams_StandardDescriptors, + ClusterParams_UAVDescriptors, + ClusterParams_CBuffer, + ClusterParams_AppSettings, + + NumClusterRootParams, +}; + +enum MSAAMaskRootParams : uint32 +{ + MSAAMaskParams_StandardDescriptors, + MSAAMaskParams_UAVDescriptors, + MSAAMaskParams_CBuffer, + MSAAMaskParams_AppSettings, + + NumMSAAMaskRootParams +}; + +enum DeferredRootParams : uint32 +{ + DeferredParams_StandardDescriptors, + DeferredParams_PSCBuffer, + DeferredParams_ShadowCBuffer, + DeferredParams_DeferredCBuffer, + DeferredParams_LightCBuffer, + DeferredParams_SRVIndices, + DeferredParams_UAVDescriptors, + DeferredParams_AppSettings, + + NumDeferredRootParams +}; + +enum PickingRootParams : uint32 +{ + PickingParams_StandardDescriptors, + PickingParams_UAVDescriptors, + PickingParams_CBuffer, + + NumPickingRootParams +}; + +enum ClusterVisRootParams : uint32 +{ + ClusterVisParams_StandardDescriptors, + ClusterVisParams_CBuffer, + ClusterVisParams_AppSettings, + + NumClusterVisRootParams, +}; + +enum ResolveRootParams : uint32 +{ + ResolveParams_StandardDescriptors, + ResolveParams_Constants, + ResolveParams_AppSettings, + + NumResolveRootParams +}; + +// Returns true if a sphere intersects a capped cone defined by a direction, height, and angle +static bool SphereConeIntersection(const Float3& coneTip, const Float3& coneDir, float coneHeight, + float coneAngle, const Float3& sphereCenter, float sphereRadius) +{ + if(Float3::Dot(sphereCenter - coneTip, coneDir) > coneHeight + sphereRadius) + return false; + + float cosHalfAngle = std::cos(coneAngle * 0.5f); + float sinHalfAngle = std::sin(coneAngle * 0.5f); + + Float3 v = sphereCenter - coneTip; + float a = Float3::Dot(v, coneDir); + float b = a * sinHalfAngle / cosHalfAngle; + float c = std::sqrt(Float3::Dot(v, v) - a * a); + float d = c - b; + float e = d * cosHalfAngle; + + return e < sphereRadius; +} + +BindlessDeferred::BindlessDeferred(const wchar* cmdLine) : App(L"Bindless Deferred Texturing", cmdLine) +{ + minFeatureLevel = D3D_FEATURE_LEVEL_11_1; + globalHelpText = "Bindless Deferred Texturing\n\n" + "Controls:\n\n" + "Use W/S/A/D/Q/E to move the camera, and hold right-click while dragging the mouse to rotate."; +} + +void BindlessDeferred::BeforeReset() +{ +} + +void BindlessDeferred::AfterReset() +{ + float aspect = float(swapChain.Width()) / swapChain.Height(); + camera.SetAspectRatio(aspect); + + CreateRenderTargets(); +} + +void BindlessDeferred::Initialize() +{ + // Check if the device supports conservative rasterization + D3D12_FEATURE_DATA_D3D12_OPTIONS features = { }; + DX12::Device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &features, sizeof(features)); + if(features.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_2) + throw Exception("This demo requires a GPU that supports FEATURE_LEVEL_11_1 with D3D12_RESOURCE_BINDING_TIER_2"); + + if(features.ConservativeRasterizationTier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) + { + AppSettings::ClusterRasterizationMode.SetValue(ClusterRasterizationModes::MSAA8x); + AppSettings::ClusterRasterizationMode.ClampNumValues(uint32(ClusterRasterizationModes::NumValues) - 1); + } + + ShadowHelper::Initialize(ShadowMapMode::DepthMap, ShadowMSAAMode::MSAA1x); + + // Load the scenes + for(uint64 i = 0; i < uint64(Scenes::NumValues); ++i) + { + ModelLoadSettings settings; + settings.FilePath = ScenePaths[i]; + settings.ForceSRGB = true; + settings.SceneScale = SceneScales[i]; + settings.MergeMeshes = false; + sceneModels[i].CreateWithAssimp(settings); + } + + float aspect = float(swapChain.Width()) / swapChain.Height(); + camera.Initialize(aspect, Pi_4, 0.1f, 35.0f); + + InitializeScene(); + + skybox.Initialize(); + + postProcessor.Initialize(); + + // Load the decal textures + for(uint64 i = 0; i < AppSettings::NumDecalTypes; ++i) + { + LoadTexture(decalTextures[i * 2 + 0], MakeString(L"..\\Content\\Textures\\Decals\\Decal_%02u_Albedo.tga", uint32(i)).c_str(), true); + LoadTexture(decalTextures[i * 2 + 1], MakeString(L"..\\Content\\Textures\\Decals\\Decal_%02u_Normal.png", uint32(i)).c_str(), false); + } + + decals.Init(AppSettings::MaxDecals); + + { + // Decal buffer + StructuredBufferInit sbInit; + sbInit.Stride = sizeof(Decal); + sbInit.NumElements = AppSettings::MaxDecals; + sbInit.Dynamic = true; + sbInit.CPUAccessible = false; + decalBuffer.Initialize(sbInit); + decalBuffer.Resource()->SetName(L"Decal Buffer"); + } + + { + // Decal bounds and instance buffers + StructuredBufferInit sbInit; + sbInit.Stride = sizeof(ClusterBounds); + sbInit.NumElements = AppSettings::MaxDecals; + sbInit.Dynamic = true; + sbInit.CPUAccessible = true; + decalBoundsBuffer.Initialize(sbInit); + + sbInit.Stride = sizeof(uint32); + decalInstanceBuffer.Initialize(sbInit); + } + + { + // Spot light bounds and instance buffers + StructuredBufferInit sbInit; + sbInit.Stride = sizeof(ClusterBounds); + sbInit.NumElements = AppSettings::MaxSpotLights; + sbInit.Dynamic = true; + sbInit.CPUAccessible = true; + spotLightBoundsBuffer.Initialize(sbInit); + + sbInit.Stride = sizeof(uint32); + spotLightInstanceBuffer.Initialize(sbInit); + } + + { + // Spot light and shadow bounds buffer + ConstantBufferInit cbInit; + cbInit.Size = sizeof(LightConstants); + cbInit.Dynamic = true; + cbInit.CPUAccessible = false; + cbInit.Name = L"Spot Light Buffer"; + + spotLightBuffer.Initialize(cbInit); + } + + { + // Indirect args buffers for deferred rendering + StructuredBufferInit sbInit; + sbInit.NumElements = 1; + sbInit.Stride = sizeof(D3D12_DISPATCH_ARGUMENTS); + + uint32 initData[3] = { 0, 1, 1 }; + sbInit.InitData = initData; + + nonMsaaArgsBuffer.Initialize(sbInit); + msaaArgsBuffer.Initialize(sbInit); + + nonMsaaArgsBuffer.Resource()->SetName(L"Non-MSAA Args Buffer"); + msaaArgsBuffer.Resource()->SetName(L"MSAA Args Buffer"); + } + + { + CompileOptions opts; + opts.Add("FrontFace_", 1); + opts.Add("BackFace_", 0); + opts.Add("Intersecting_", 0); + + // Clustering shaders + clusterVS = CompileFromFile(L"Clusters.hlsl", "ClusterVS", ShaderType::Vertex, opts); + clusterFrontFacePS = CompileFromFile(L"Clusters.hlsl", "ClusterPS", ShaderType::Pixel, opts); + + opts.Reset(); + opts.Add("FrontFace_", 0); + opts.Add("BackFace_", 1); + opts.Add("Intersecting_", 0); + clusterBackFacePS = CompileFromFile(L"Clusters.hlsl", "ClusterPS", ShaderType::Pixel, opts); + + opts.Reset(); + opts.Add("FrontFace_", 0); + opts.Add("BackFace_", 0); + opts.Add("Intersecting_", 1); + clusterIntersectingPS = CompileFromFile(L"Clusters.hlsl", "ClusterPS", ShaderType::Pixel, opts); + } + + MakeBoxGeometry(decalClusterVtxBuffer, decalClusterIdxBuffer, 2.0f); // resulting box is [-1, 1] + MakeConeGeometry(NumConeSides, spotLightClusterVtxBuffer, spotLightClusterIdxBuffer, coneVertices); + + { + // Picking buffer + StructuredBufferInit sbInit; + sbInit.Stride = sizeof(PickingData); + sbInit.NumElements = 1; + sbInit.CreateUAV = 1; + pickingBuffer.Initialize(sbInit); + } + + for(uint64 i = 0; i < DX12::RenderLatency; ++i) + { + pickingReadbackBuffers[i].Initialize(sizeof(PickingData)); + pickingReadbackBuffers[i].Resource->SetName(L"Picking Readback Buffer"); + } + + { + // Compile picking shaders + CompileOptions opts; + opts.Add("MSAA_", 0); + pickingCS[0] = CompileFromFile(L"Picking.hlsl", "PickingCS", ShaderType::Compute, opts); + + opts.Reset(); + opts.Add("MSAA_", 1); + pickingCS[1] = CompileFromFile(L"Picking.hlsl", "PickingCS", ShaderType::Compute, opts); + } + + // Compile MSAA mask generation shaders + for(uint64 msaaMode = 1; msaaMode < NumMSAAModes; ++msaaMode) + { + CompileOptions opts; + opts.Add("MSAASamples_", AppSettings::NumMSAASamples(MSAAModes(msaaMode))); + opts.Add("UseZGradients_", 0); + msaaMaskCS[msaaMode][0] = CompileFromFile(L"MSAAMask.hlsl", "MSAAMaskCS", ShaderType::Compute, opts); + + opts.Reset(); + opts.Add("MSAASamples_", AppSettings::NumMSAASamples(MSAAModes(msaaMode))); + opts.Add("UseZGradients_", 1); + msaaMaskCS[msaaMode][1] = CompileFromFile(L"MSAAMask.hlsl", "MSAAMaskCS", ShaderType::Compute, opts); + } + + // Compile resolve shaders + for(uint64 msaaMode = 1; msaaMode < NumMSAAModes; ++msaaMode) + { + for(uint64 deferred = 0; deferred < 2; ++deferred) + { + CompileOptions opts; + opts.Add("MSAASamples_", AppSettings::NumMSAASamples(MSAAModes(msaaMode))); + opts.Add("Deferred_", uint32(deferred)); + resolvePS[msaaMode][deferred] = CompileFromFile(L"Resolve.hlsl", "ResolvePS", ShaderType::Pixel, opts); + } + } + + // Compile cluster visualization shaders + clusterVisPS = CompileFromFile(L"ClusterVisualizer.hlsl", "ClusterVisualizerPS", ShaderType::Pixel); + + std::wstring fullScreenTriPath = SampleFrameworkDir() + L"Shaders\\FullScreenTriangle.hlsl"; + fullScreenTriVS = CompileFromFile(fullScreenTriPath.c_str(), "FullScreenTriangleVS", ShaderType::Vertex); + + { + // Clustering root signature + D3D12_DESCRIPTOR_RANGE1 uavRanges[1] = {}; + uavRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; + uavRanges[0].NumDescriptors = 1; + uavRanges[0].BaseShaderRegister = 0; + uavRanges[0].RegisterSpace = 0; + uavRanges[0].OffsetInDescriptorsFromTableStart = 0; + + D3D12_ROOT_PARAMETER1 rootParameters[NumClusterRootParams] = {}; + + // Standard SRV descriptors + rootParameters[ClusterParams_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[ClusterParams_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; + rootParameters[ClusterParams_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[ClusterParams_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + // PS UAV descriptors + rootParameters[ClusterParams_UAVDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[ClusterParams_UAVDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[ClusterParams_UAVDescriptors].DescriptorTable.pDescriptorRanges = uavRanges; + rootParameters[ClusterParams_UAVDescriptors].DescriptorTable.NumDescriptorRanges = ArraySize_(uavRanges); + + // CBuffer + rootParameters[ClusterParams_CBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[ClusterParams_CBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[ClusterParams_CBuffer].Descriptor.RegisterSpace = 0; + rootParameters[ClusterParams_CBuffer].Descriptor.ShaderRegister = 0; + rootParameters[ClusterParams_CBuffer].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + // AppSettings + rootParameters[ClusterParams_AppSettings].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[ClusterParams_AppSettings].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[ClusterParams_AppSettings].Descriptor.RegisterSpace = 0; + rootParameters[ClusterParams_AppSettings].Descriptor.ShaderRegister = AppSettings::CBufferRegister; + rootParameters[ClusterParams_AppSettings].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; + rootSignatureDesc.NumParameters = ArraySize_(rootParameters); + rootSignatureDesc.pParameters = rootParameters; + rootSignatureDesc.NumStaticSamplers = 0; + rootSignatureDesc.pStaticSamplers = nullptr; + rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + + DX12::CreateRootSignature(&clusterRS, rootSignatureDesc); + } + + { + // Picking root signature + D3D12_DESCRIPTOR_RANGE1 descriptorRanges[1] = {}; + descriptorRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; + descriptorRanges[0].NumDescriptors = 1; + descriptorRanges[0].BaseShaderRegister = 0; + descriptorRanges[0].RegisterSpace = 0; + descriptorRanges[0].OffsetInDescriptorsFromTableStart = 0; + + D3D12_ROOT_PARAMETER1 rootParameters[NumPickingRootParams] = {}; + + rootParameters[PickingParams_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[PickingParams_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[PickingParams_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[PickingParams_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + rootParameters[PickingParams_UAVDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[PickingParams_UAVDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[PickingParams_UAVDescriptors].DescriptorTable.pDescriptorRanges = descriptorRanges; + rootParameters[PickingParams_UAVDescriptors].DescriptorTable.NumDescriptorRanges = ArraySize_(descriptorRanges); + + rootParameters[PickingParams_CBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[PickingParams_CBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[PickingParams_CBuffer].Descriptor.RegisterSpace = 0; + rootParameters[PickingParams_CBuffer].Descriptor.ShaderRegister = 0; + rootParameters[PickingParams_CBuffer].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; + rootSignatureDesc.NumParameters = ArraySize_(rootParameters); + rootSignatureDesc.pParameters = rootParameters; + rootSignatureDesc.NumStaticSamplers = 0; + rootSignatureDesc.pStaticSamplers = nullptr; + rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + + DX12::CreateRootSignature(&pickingRS, rootSignatureDesc); + } + + { + // MSAA mask root signature + D3D12_DESCRIPTOR_RANGE1 descriptorRanges[1] = {}; + descriptorRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; + descriptorRanges[0].NumDescriptors = 3; + descriptorRanges[0].BaseShaderRegister = 0; + descriptorRanges[0].RegisterSpace = 0; + descriptorRanges[0].OffsetInDescriptorsFromTableStart = 0; + + D3D12_ROOT_PARAMETER1 rootParameters[NumMSAAMaskRootParams] = {}; + rootParameters[MSAAMaskParams_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[MSAAMaskParams_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[MSAAMaskParams_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[MSAAMaskParams_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + rootParameters[MSAAMaskParams_UAVDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[MSAAMaskParams_UAVDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[MSAAMaskParams_UAVDescriptors].DescriptorTable.pDescriptorRanges = descriptorRanges; + rootParameters[MSAAMaskParams_UAVDescriptors].DescriptorTable.NumDescriptorRanges = ArraySize_(descriptorRanges); + + rootParameters[MSAAMaskParams_CBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[MSAAMaskParams_CBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[MSAAMaskParams_CBuffer].Descriptor.RegisterSpace = 0; + rootParameters[MSAAMaskParams_CBuffer].Descriptor.ShaderRegister = 0; + rootParameters[MSAAMaskParams_CBuffer].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + rootParameters[MSAAMaskParams_AppSettings].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[MSAAMaskParams_AppSettings].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[MSAAMaskParams_AppSettings].Descriptor.RegisterSpace = 0; + rootParameters[MSAAMaskParams_AppSettings].Descriptor.ShaderRegister = AppSettings::CBufferRegister; + rootParameters[MSAAMaskParams_AppSettings].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; + rootSignatureDesc.NumParameters = ArraySize_(rootParameters); + rootSignatureDesc.pParameters = rootParameters; + rootSignatureDesc.NumStaticSamplers = 0; + rootSignatureDesc.pStaticSamplers = nullptr; + rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + + DX12::CreateRootSignature(&msaaMaskRootSignature, rootSignatureDesc); + } + + { + // Resolve root signature + D3D12_ROOT_PARAMETER1 rootParameters[NumResolveRootParams] = {}; + + // Standard SRV descriptors + rootParameters[ResolveParams_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[ResolveParams_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[ResolveParams_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[ResolveParams_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + // CBuffer + rootParameters[ResolveParams_Constants].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + rootParameters[ResolveParams_Constants].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[ResolveParams_Constants].Constants.Num32BitValues = 3; + rootParameters[ResolveParams_Constants].Constants.RegisterSpace = 0; + rootParameters[ResolveParams_Constants].Constants.ShaderRegister = 0; + + // AppSettings + rootParameters[ResolveParams_AppSettings].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[ResolveParams_AppSettings].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[ResolveParams_AppSettings].Descriptor.RegisterSpace = 0; + rootParameters[ResolveParams_AppSettings].Descriptor.ShaderRegister = AppSettings::CBufferRegister; + rootParameters[ResolveParams_AppSettings].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; + rootSignatureDesc.NumParameters = ArraySize_(rootParameters); + rootSignatureDesc.pParameters = rootParameters; + rootSignatureDesc.NumStaticSamplers = 0; + rootSignatureDesc.pStaticSamplers = nullptr; + rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + + DX12::CreateRootSignature(&resolveRootSignature, rootSignatureDesc); + } + + { + // Cluster visualization root signature + D3D12_ROOT_PARAMETER1 rootParameters[NumClusterVisRootParams] = {}; + + // Standard SRV descriptors + rootParameters[ClusterVisParams_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[ClusterVisParams_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[ClusterVisParams_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[ClusterVisParams_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + // CBuffer + rootParameters[ClusterVisParams_CBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[ClusterVisParams_CBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[ClusterVisParams_CBuffer].Descriptor.RegisterSpace = 0; + rootParameters[ClusterVisParams_CBuffer].Descriptor.ShaderRegister = 0; + rootParameters[ClusterVisParams_CBuffer].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + // AppSettings + rootParameters[ClusterVisParams_AppSettings].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[ClusterVisParams_AppSettings].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[ClusterVisParams_AppSettings].Descriptor.RegisterSpace = 0; + rootParameters[ClusterVisParams_AppSettings].Descriptor.ShaderRegister = AppSettings::CBufferRegister; + rootParameters[ClusterVisParams_AppSettings].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; + rootSignatureDesc.NumParameters = ArraySize_(rootParameters); + rootSignatureDesc.pParameters = rootParameters; + rootSignatureDesc.NumStaticSamplers = 0; + rootSignatureDesc.pStaticSamplers = nullptr; + rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + + DX12::CreateRootSignature(&clusterVisRootSignature, rootSignatureDesc); + } + + { + // Command signature for MSAA deferred indirect dispatch + D3D12_INDIRECT_ARGUMENT_DESC argsDescs[1] = { }; + argsDescs[0].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; + + D3D12_COMMAND_SIGNATURE_DESC cmdSignatureDesc = { }; + cmdSignatureDesc.ByteStride = sizeof(D3D12_DISPATCH_ARGUMENTS); + cmdSignatureDesc.NodeMask = 0; + cmdSignatureDesc.NumArgumentDescs = ArraySize_(argsDescs); + cmdSignatureDesc.pArgumentDescs = argsDescs; + DXCall(DX12::Device->CreateCommandSignature(&cmdSignatureDesc, nullptr, IID_PPV_ARGS(&deferredCmdSignature))); + } +} + +void BindlessDeferred::Shutdown() +{ + ShadowHelper::Shutdown(); + + for(uint64 i = 0; i < ArraySize_(sceneModels); ++i) + sceneModels[i].Shutdown(); + meshRenderer.Shutdown(); + skybox.Shutdown(); + skyCache.Shutdown(); + postProcessor.Shutdown(); + + decalBuffer.Shutdown(); + decalBoundsBuffer.Shutdown(); + decalClusterBuffer.Shutdown(); + decalInstanceBuffer.Shutdown(); + for(uint64 i = 0; i < ArraySize_(decalTextures); ++i) + decalTextures[i].Shutdown(); + + spotLightBuffer.Shutdown(); + spotLightBoundsBuffer.Shutdown(); + spotLightClusterBuffer.Shutdown(); + spotLightInstanceBuffer.Shutdown(); + + DX12::Release(clusterRS); + clusterMSAATarget.Shutdown(); + + decalClusterVtxBuffer.Shutdown(); + decalClusterIdxBuffer.Shutdown(); + + spotLightClusterVtxBuffer.Shutdown(); + spotLightClusterIdxBuffer.Shutdown(); + + DX12::Release(deferredRootSignature); + DX12::Release(deferredCmdSignature); + + DX12::Release(msaaMaskRootSignature); + nonMsaaTileBuffer.Shutdown(); + msaaTileBuffer.Shutdown(); + nonMsaaArgsBuffer.Shutdown(); + msaaArgsBuffer.Shutdown(); + msaaMaskBuffer.Shutdown(); + + pickingBuffer.Shutdown(); + DX12::Release(pickingRS); + for(uint64 i = 0; i < ArraySize_(pickingReadbackBuffers); ++i) + pickingReadbackBuffers[i].Shutdown(); + + DX12::Release(clusterVisRootSignature); + + mainTarget.Shutdown(); + tangentFrameTarget.Shutdown(); + resolveTarget.Shutdown(); + depthBuffer.Shutdown(); + uvTarget.Shutdown(); + uvGradientsTarget.Shutdown(); + materialIDTarget.Shutdown(); + deferredMSAATarget.Shutdown(); + + DX12::Release(resolveRootSignature); +} + +void BindlessDeferred::CreatePSOs() +{ + DXGI_FORMAT gBufferFormats[] = { tangentFrameTarget.Format(), uvTarget.Format(), materialIDTarget.Format(), uvGradientsTarget.Format() }; + uint64 numGBuffers = AppSettings::ComputeUVGradients ? ArraySize_(gBufferFormats) - 1 : ArraySize_(gBufferFormats); + meshRenderer.CreatePSOs(mainTarget.Texture.Format, depthBuffer.DSVFormat, gBufferFormats, numGBuffers, mainTarget.MSAASamples); + skybox.CreatePSOs(mainTarget.Texture.Format, depthBuffer.DSVFormat, mainTarget.MSAASamples); + postProcessor.CreatePSOs(); + + { + // Clustering PSO + D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; + psoDesc.pRootSignature = clusterRS; + psoDesc.BlendState = DX12::GetBlendState(BlendState::Disabled); + psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::Disabled); + psoDesc.SampleMask = UINT_MAX; + psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + psoDesc.NumRenderTargets = 0; + psoDesc.VS = clusterVS.ByteCode(); + + ClusterRasterizationModes rastMode = AppSettings::ClusterRasterizationMode; + if(rastMode == ClusterRasterizationModes::MSAA4x || rastMode == ClusterRasterizationModes::MSAA8x) + { + psoDesc.SampleDesc.Count = clusterMSAATarget.MSAASamples; + psoDesc.SampleDesc.Quality = DX12::StandardMSAAPattern; + psoDesc.NumRenderTargets = 1; + psoDesc.RTVFormats[0] = clusterMSAATarget.Format(); + } + else + psoDesc.SampleDesc.Count = 1; + + D3D12_CONSERVATIVE_RASTERIZATION_MODE crMode = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; + if(rastMode == ClusterRasterizationModes::Conservative) + crMode = D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON; + + psoDesc.PS = clusterFrontFacePS.ByteCode(); + psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::BackFaceCull); + psoDesc.RasterizerState.ConservativeRaster = crMode; + DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&clusterFrontFacePSO))); + + psoDesc.PS = clusterBackFacePS.ByteCode(); + psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::FrontFaceCull); + psoDesc.RasterizerState.ConservativeRaster = crMode; + DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&clusterBackFacePSO))); + + psoDesc.PS = clusterIntersectingPS.ByteCode(); + psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::FrontFaceCull); + psoDesc.RasterizerState.ConservativeRaster = crMode; + DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&clusterIntersectingPSO))); + + clusterFrontFacePSO->SetName(L"Cluster Front-Face PSO"); + clusterBackFacePSO->SetName(L"Cluster Back-Face PSO"); + clusterIntersectingPSO->SetName(L"Cluster Intersecting PSO"); + } + + const bool msaaEnabled = AppSettings::MSAAMode != MSAAModes::MSAANone; + const uint64 msaaModeIdx = uint64(AppSettings::MSAAMode); + + if(msaaEnabled) + { + // MSAA mask PSO's + D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = { }; + psoDesc.CS = msaaMaskCS[uint64(AppSettings::MSAAMode)][0].ByteCode(); + psoDesc.pRootSignature = msaaMaskRootSignature; + DXCall(DX12::Device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&msaaMaskPSOs[0]))); + + psoDesc.CS = msaaMaskCS[uint64(AppSettings::MSAAMode)][1].ByteCode(); + DXCall(DX12::Device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&msaaMaskPSOs[1]))); + } + + if(taskSet == nullptr || EnableMultithreadedCompilation == false) + { + // Deferred rendering PSO + const uint64 uvGradIdx = AppSettings::ComputeUVGradients ? 1 : 0; + D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = { }; + psoDesc.CS = deferredCS[msaaModeIdx][uvGradIdx][0].ByteCode(); + psoDesc.pRootSignature = deferredRootSignature; + DXCall(DX12::Device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&deferredPSOs[0]))); + + if(AppSettings::MSAAMode != MSAAModes::MSAANone) + { + psoDesc.CS = deferredCS[msaaModeIdx][uvGradIdx][1].ByteCode(); + DXCall(DX12::Device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&deferredPSOs[1]))); + } + } + + if(msaaEnabled) + { + // Resolve PSO + D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; + psoDesc.pRootSignature = resolveRootSignature; + psoDesc.VS = fullScreenTriVS.ByteCode(); + psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::NoCull); + psoDesc.BlendState = DX12::GetBlendState(BlendState::Disabled); + psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::Disabled); + psoDesc.SampleMask = UINT_MAX; + psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + psoDesc.NumRenderTargets = 1; + psoDesc.RTVFormats[0] = mainTarget.Format(); + psoDesc.SampleDesc.Count = 1; + + psoDesc.PS = resolvePS[msaaModeIdx][0].ByteCode(); + DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&resolvePSOs[0]))); + + psoDesc.PS = resolvePS[msaaModeIdx][1].ByteCode(); + DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&resolvePSOs[1]))); + } + + { + // Cluster visualizer PSO + D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; + psoDesc.pRootSignature = clusterVisRootSignature; + psoDesc.VS = fullScreenTriVS.ByteCode(); + psoDesc.PS = clusterVisPS.ByteCode(); + psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::NoCull); + psoDesc.BlendState = DX12::GetBlendState(BlendState::AlphaBlend); + psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::Disabled); + psoDesc.SampleMask = UINT_MAX; + psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + psoDesc.NumRenderTargets = 1; + psoDesc.RTVFormats[0] = swapChain.Format(); + psoDesc.SampleDesc.Count = 1; + DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&clusterVisPSO))); + } + + { + // Picking PSO + D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = { }; + psoDesc.CS = pickingCS[0].ByteCode(); + psoDesc.pRootSignature = pickingRS; + DXCall(DX12::Device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&pickingPSOs[0]))); + + psoDesc.CS = pickingCS[1].ByteCode(); + DXCall(DX12::Device->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&pickingPSOs[1]))); + } +} + +void BindlessDeferred::DestroyPSOs() +{ + meshRenderer.DestroyPSOs(); + skybox.DestroyPSOs(); + postProcessor.DestroyPSOs(); + DX12::DeferredRelease(clusterFrontFacePSO); + DX12::DeferredRelease(clusterBackFacePSO); + DX12::DeferredRelease(clusterIntersectingPSO); + DX12::DeferredRelease(pickingPSOs[0]); + DX12::DeferredRelease(pickingPSOs[1]); + DX12::DeferredRelease(clusterVisPSO); + for(uint64 i = 0; i < ArraySize_(msaaMaskPSOs); ++i) + DX12::DeferredRelease(msaaMaskPSOs[i]); + for(uint64 i = 0; i < ArraySize_(deferredPSOs); ++i) + DX12::DeferredRelease(deferredPSOs[i]); + for(uint64 i = 0; i < ArraySize_(resolvePSOs); ++i) + DX12::DeferredRelease(resolvePSOs[i]); +} + +// Creates all required render targets +void BindlessDeferred::CreateRenderTargets() +{ + uint32 width = swapChain.Width(); + uint32 height = swapChain.Height(); + const uint32 NumSamples = AppSettings::NumMSAASamples(); + + { + RenderTextureInit rtInit; + rtInit.Width = width; + rtInit.Height = height; + rtInit.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + rtInit.MSAASamples = NumSamples; + rtInit.ArraySize = 1; + rtInit.CreateUAV = NumSamples == 1; + rtInit.InitialState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + rtInit.Name = L"Main Target"; + mainTarget.Initialize(rtInit); + } + + { + RenderTextureInit rtInit; + rtInit.Width = width; + rtInit.Height = height; + rtInit.Format = DXGI_FORMAT_R10G10B10A2_UNORM; + rtInit.MSAASamples = NumSamples; + rtInit.ArraySize = 1; + rtInit.CreateUAV = false; + rtInit.InitialState = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + rtInit.Name = L"Tangent Frame Target"; + tangentFrameTarget.Initialize(rtInit); + } + + { + RenderTextureInit rtInit; + rtInit.Width = width; + rtInit.Height = height; + rtInit.Format = DXGI_FORMAT_R16G16B16A16_SNORM; + rtInit.MSAASamples = NumSamples; + rtInit.ArraySize = 1; + rtInit.CreateUAV = false; + rtInit.InitialState = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + rtInit.Name = L"UV Target"; + uvTarget.Initialize(rtInit); + } + + { + RenderTextureInit rtInit; + rtInit.Width = width; + rtInit.Height = height; + rtInit.Format = DXGI_FORMAT_R16G16B16A16_SNORM; + rtInit.MSAASamples = NumSamples; + rtInit.ArraySize = 1; + rtInit.CreateUAV = false; + rtInit.InitialState = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + rtInit.Name = L"UV Gradient Target"; + uvGradientsTarget.Initialize(rtInit); + } + + { + RenderTextureInit rtInit; + rtInit.Width = width; + rtInit.Height = height; + rtInit.Format = DXGI_FORMAT_R8_UINT; + rtInit.MSAASamples = NumSamples; + rtInit.ArraySize = 1; + rtInit.CreateUAV = false; + rtInit.InitialState = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + rtInit.Name = L"Material ID Target"; + materialIDTarget.Initialize(rtInit); + } + + if(NumSamples > 1) + { + { + RenderTextureInit rtInit; + rtInit.Width = width; + rtInit.Height = height; + rtInit.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + rtInit.MSAASamples = 1; + rtInit.ArraySize = 1; + rtInit.CreateUAV = false; + rtInit.InitialState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + rtInit.Name = L"Resolve Target"; + resolveTarget.Initialize(rtInit); + } + + { + RenderTextureInit rtInit; + rtInit.Width = width * 2; + rtInit.Height = NumSamples == 4 ? height * 2 : height; + rtInit.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + rtInit.MSAASamples = 1; + rtInit.ArraySize = 1; + rtInit.CreateUAV = true; + rtInit.InitialState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + rtInit.Name = L"Deferred MSAA Target"; + deferredMSAATarget.Initialize(rtInit); + } + } + + { + DepthBufferInit dbInit; + dbInit.Width = width; + dbInit.Height = height; + dbInit.Format = DXGI_FORMAT_D32_FLOAT; + dbInit.MSAASamples = NumSamples; + dbInit.InitialState = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_DEPTH_READ; + dbInit.Name = L"Main Depth Buffer"; + depthBuffer.Initialize(dbInit); + } + + AppSettings::NumXTiles = (width + (AppSettings::ClusterTileSize - 1)) / AppSettings::ClusterTileSize; + AppSettings::NumYTiles = (height + (AppSettings::ClusterTileSize - 1)) / AppSettings::ClusterTileSize; + const uint64 numXYZTiles = AppSettings::NumXTiles * AppSettings::NumYTiles * AppSettings::NumZTiles; + + { + // Render target for forcing MSAA during cluster rasterization. Ideally we would use ForcedSampleCount for this, + // but it's currently causing the Nvidia driver to crash. :( + RenderTextureInit rtInit; + rtInit.Width = AppSettings::NumXTiles; + rtInit.Height = AppSettings::NumYTiles; + rtInit.Format = DXGI_FORMAT_R8_UNORM; + rtInit.MSAASamples = 1; + rtInit.ArraySize = 1; + rtInit.CreateUAV = false; + rtInit.Name = L"Deferred MSAA Target"; + + ClusterRasterizationModes rastMode = AppSettings::ClusterRasterizationMode; + if(rastMode == ClusterRasterizationModes::MSAA4x) + { + rtInit.MSAASamples = 4; + clusterMSAATarget.Initialize(rtInit); + } + else if(rastMode == ClusterRasterizationModes::MSAA8x) + { + rtInit.MSAASamples = 8; + clusterMSAATarget.Initialize(rtInit); + } + else + clusterMSAATarget.Shutdown(); + } + + { + // Decal cluster bitmask buffer + RawBufferInit rbInit; + rbInit.NumElements = numXYZTiles * AppSettings::DecalElementsPerCluster; + rbInit.CreateUAV = true; + decalClusterBuffer.Initialize(rbInit); + decalClusterBuffer.InternalBuffer.Resource->SetName(L"Decal Cluster Buffer"); + } + + { + // Spotlight cluster bitmask buffer + RawBufferInit rbInit; + rbInit.NumElements = numXYZTiles * AppSettings::SpotLightElementsPerCluster; + rbInit.CreateUAV = true; + spotLightClusterBuffer.Initialize(rbInit); + spotLightClusterBuffer.InternalBuffer.Resource->SetName(L"Spot Light Cluster Buffer"); + } + + { + const uint64 numComputeTilesX = AlignTo(mainTarget.Width(), AppSettings::DeferredTileSize) / AppSettings::DeferredTileSize; + const uint64 numComputeTilesY = AlignTo(mainTarget.Height(), AppSettings::DeferredTileSize) / AppSettings::DeferredTileSize; + + // AppendBuffer for storing coordinates of tiles with "edge" pixels for MSAA sampling + StructuredBufferInit sbInit; + sbInit.NumElements = numComputeTilesX * numComputeTilesY; + sbInit.Stride = sizeof(uint32); + sbInit.CreateUAV = true; + sbInit.UseCounter = true; + msaaTileBuffer.Initialize(sbInit); + msaaTileBuffer.InternalBuffer.Resource->SetName(L"MSAA Tile Buffer"); + + // AppendBuffer for storing coordinates of tiles with non-edge pixels for MSAA sampling + nonMsaaTileBuffer.Initialize(sbInit); + nonMsaaTileBuffer.InternalBuffer.Resource->SetName(L"Non-MSAA Tile Buffer"); + + // Buffer storing 1 bit per pixel indicating MSAA edge pixels + sbInit.Stride = AppSettings::DeferredTileMaskSize * sizeof(uint32); + sbInit.UseCounter = false; + msaaMaskBuffer.Initialize(sbInit); + msaaMaskBuffer.InternalBuffer.Resource->SetName(L"MSAA Mask Buffer"); + } +} + +void BindlessDeferred::CompileShadersTask(uint32 start, uint32 end, uint32 threadNum, void* args) +{ + BindlessDeferred* app = (BindlessDeferred*)args; + + for(uint32 i = start; i < end; ++i) + { + uint32 msaaMode = i / 4; + uint32 computeUVGradients = (i / 2) % 2; + uint32 perSample = i % 2; + + uint32 numMSAASamples = AppSettings::NumMSAASamples(MSAAModes(msaaMode)); + uint32 msaa = msaaMode > 0; + if(msaa == 0 && perSample == 1) + continue; + + CompileOptions opts; + opts.Add("MSAA_", msaa); + opts.Add("NumMSAASamples_", numMSAASamples); + opts.Add("ShadePerSample_", perSample); + opts.Add("ComputeUVGradients_", computeUVGradients); + app->deferredCS[msaaMode][computeUVGradients][perSample] = CompileFromFile(L"Deferred.hlsl", "DeferredCS", ShaderType::Compute, opts); + } +} + +void BindlessDeferred::InitializeScene() +{ + currentModel = &sceneModels[uint64(AppSettings::CurrentScene)]; + meshRenderer.Shutdown(); + DX12::FlushGPU(); + meshRenderer.Initialize(currentModel); + + camera.SetPosition(SceneCameraPositions[uint64(AppSettings::CurrentScene)]); + camera.SetXRotation(SceneCameraRotations[uint64(AppSettings::CurrentScene)].x); + camera.SetYRotation(SceneCameraRotations[uint64(AppSettings::CurrentScene)].y); + + if(EnableMultithreadedCompilation) + { + if(taskSet != nullptr) + { + enkiWaitForTaskSet(taskScheduler, taskSet); + } + else + { + taskScheduler = enkiCreateTaskScheduler(); + taskSet = enkiCreateTaskSet(taskScheduler, CompileShadersTask); + } + + // Kick off tasks to compile the deferred compute shaders + enkiAddTaskSetToPipe(taskScheduler, taskSet, this, uint32(MSAAModes::NumValues) * 2 * 2); + } + else + { + CompileShadersTask(0, uint32(MSAAModes::NumValues) * 2 * 2, 0, this); + } + + { + // Initialize the spotlight data used for rendering + const uint64 numSpotLights = Min(currentModel->SpotLights().Size(), AppSettings::MaxSpotLights); + spotLights.Init(numSpotLights); + + for(uint64 i = 0; i < numSpotLights; ++i) + { + const ModelSpotLight& srcLight = currentModel->SpotLights()[i]; + + SpotLight& spotLight = spotLights[i]; + spotLight.Position = srcLight.Position; + spotLight.Direction = -srcLight.Direction; + spotLight.Intensity = srcLight.Intensity * SpotLightIntensityFactor; + spotLight.AngularAttenuationX = std::cos(srcLight.AngularAttenuation.x * 0.5f); + spotLight.AngularAttenuationY = std::cos(srcLight.AngularAttenuation.y * 0.5f); + spotLight.Range = AppSettings::SpotLightRange; + } + + AppSettings::MaxLightClamp.SetValue(int32(numSpotLights)); + } + + { + DX12::DeferredRelease(deferredRootSignature); + + // Deferred root signature + D3D12_DESCRIPTOR_RANGE1 descriptorRanges[1] = {}; + descriptorRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; + descriptorRanges[0].NumDescriptors = 1; + descriptorRanges[0].BaseShaderRegister = 0; + descriptorRanges[0].RegisterSpace = 0; + descriptorRanges[0].OffsetInDescriptorsFromTableStart = 0; + + D3D12_ROOT_PARAMETER1 rootParameters[NumDeferredRootParams] = {}; + + rootParameters[DeferredParams_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[DeferredParams_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[DeferredParams_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[DeferredParams_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + // PSCBuffer + rootParameters[DeferredParams_PSCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[DeferredParams_PSCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[DeferredParams_PSCBuffer].Descriptor.RegisterSpace = 0; + rootParameters[DeferredParams_PSCBuffer].Descriptor.ShaderRegister = 0; + rootParameters[DeferredParams_PSCBuffer].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + // ShadowCBuffer + rootParameters[DeferredParams_ShadowCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[DeferredParams_ShadowCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[DeferredParams_ShadowCBuffer].Descriptor.RegisterSpace = 0; + rootParameters[DeferredParams_ShadowCBuffer].Descriptor.ShaderRegister = 1; + rootParameters[DeferredParams_ShadowCBuffer].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + // DeferredCBuffer + rootParameters[DeferredParams_DeferredCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[DeferredParams_DeferredCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[DeferredParams_DeferredCBuffer].Descriptor.RegisterSpace = 0; + rootParameters[DeferredParams_DeferredCBuffer].Descriptor.ShaderRegister = 2; + rootParameters[DeferredParams_DeferredCBuffer].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + // LightCBuffer + rootParameters[DeferredParams_LightCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[DeferredParams_LightCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[DeferredParams_LightCBuffer].Descriptor.RegisterSpace = 0; + rootParameters[DeferredParams_LightCBuffer].Descriptor.ShaderRegister = 3; + rootParameters[DeferredParams_LightCBuffer].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE; + + // SRV Indices + rootParameters[DeferredParams_SRVIndices].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[DeferredParams_SRVIndices].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[DeferredParams_SRVIndices].Descriptor.RegisterSpace = 0; + rootParameters[DeferredParams_SRVIndices].Descriptor.ShaderRegister = 4; + rootParameters[DeferredParams_SRVIndices].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + // UAV's + rootParameters[DeferredParams_UAVDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[DeferredParams_UAVDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[DeferredParams_UAVDescriptors].DescriptorTable.pDescriptorRanges = descriptorRanges; + rootParameters[DeferredParams_UAVDescriptors].DescriptorTable.NumDescriptorRanges = ArraySize_(descriptorRanges); + + // AppSettings + rootParameters[DeferredParams_AppSettings].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[DeferredParams_AppSettings].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[DeferredParams_AppSettings].Descriptor.RegisterSpace = 0; + rootParameters[DeferredParams_AppSettings].Descriptor.ShaderRegister = AppSettings::CBufferRegister; + + D3D12_STATIC_SAMPLER_DESC staticSamplers[2] = {}; + staticSamplers[0] = DX12::GetStaticSamplerState(SamplerState::Anisotropic, 0, 0, D3D12_SHADER_VISIBILITY_ALL); + staticSamplers[1] = DX12::GetStaticSamplerState(SamplerState::ShadowMapPCF, 1, 0, D3D12_SHADER_VISIBILITY_ALL); + + D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; + rootSignatureDesc.NumParameters = ArraySize_(rootParameters); + rootSignatureDesc.pParameters = rootParameters; + rootSignatureDesc.NumStaticSamplers = ArraySize_(staticSamplers); + rootSignatureDesc.pStaticSamplers = staticSamplers; + rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + + DX12::CreateRootSignature(&deferredRootSignature, rootSignatureDesc); + } + + numDecals = 0; +} + +void BindlessDeferred::Update(const Timer& timer) +{ + CPUProfileBlock profileBlock("Update"); + + AppSettings::UpdateUI(); + + MouseState mouseState = MouseState::GetMouseState(window); + KeyboardState kbState = KeyboardState::GetKeyboardState(window); + + currMouseState = mouseState; + + if(kbState.IsKeyDown(KeyboardState::Escape)) + window.Destroy(); + + float CamMoveSpeed = 5.0f * timer.DeltaSecondsF(); + const float CamRotSpeed = 0.180f * timer.DeltaSecondsF(); + + // Move the camera with keyboard input + if(kbState.IsKeyDown(KeyboardState::LeftShift)) + CamMoveSpeed *= 0.25f; + + Float3 camPos = camera.Position(); + if(kbState.IsKeyDown(KeyboardState::W)) + camPos += camera.Forward() * CamMoveSpeed; + else if (kbState.IsKeyDown(KeyboardState::S)) + camPos += camera.Back() * CamMoveSpeed; + if(kbState.IsKeyDown(KeyboardState::A)) + camPos += camera.Left() * CamMoveSpeed; + else if (kbState.IsKeyDown(KeyboardState::D)) + camPos += camera.Right() * CamMoveSpeed; + if(kbState.IsKeyDown(KeyboardState::Q)) + camPos += camera.Up() * CamMoveSpeed; + else if (kbState.IsKeyDown(KeyboardState::E)) + camPos += camera.Down() * CamMoveSpeed; + camera.SetPosition(camPos); + + // Rotate the camera with the mouse + if(mouseState.RButton.Pressed && mouseState.IsOverWindow) + { + float xRot = camera.XRotation(); + float yRot = camera.YRotation(); + xRot += mouseState.DY * CamRotSpeed; + yRot += mouseState.DX * CamRotSpeed; + camera.SetXRotation(xRot); + camera.SetYRotation(yRot); + } + + UpdateDecals(timer); + UpdateLights(); + + appViewMatrix = camera.ViewMatrix(); + + // Toggle VSYNC + swapChain.SetVSYNCEnabled(AppSettings::EnableVSync ? true : false); + + skyCache.Init(AppSettings::SunDirection, AppSettings::SunSize, AppSettings::GroundAlbedo, AppSettings::Turbidity, true); + + if(AppSettings::MSAAMode.Changed() || AppSettings::ClusterRasterizationMode.Changed()) + { + DestroyPSOs(); + CreateRenderTargets(); + CreatePSOs(); + } + + if(AppSettings::CurrentScene.Changed()) + { + currentModel = &sceneModels[uint64(AppSettings::CurrentScene)]; + DestroyPSOs(); + InitializeScene(); + CreatePSOs(); + } + + if(AppSettings::ComputeUVGradients.Changed()) + { + DestroyPSOs(); + CreatePSOs(); + } + + if(EnableMultithreadedCompilation && taskSet != nullptr && enkiIsTaskSetComplete(taskScheduler, taskSet)) + { + enkiDeleteTaskSet(taskSet); + enkiDeleteTaskScheduler(taskScheduler); + taskSet = nullptr; + taskScheduler = nullptr; + + DestroyPSOs(); + CreatePSOs(); + } +} + +void BindlessDeferred::Render(const Timer& timer) +{ + ID3D12GraphicsCommandList* cmdList = DX12::CmdList; + + CPUProfileBlock cpuProfileBlock("Render"); + ProfileBlock gpuProfileBlock(cmdList, "Render Total"); + + if(taskSet != nullptr) + { + // We're still waiting for shaders to compile, so print a message to the screen and skip the render loop + D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[1] = { swapChain.BackBuffer().RTV }; + cmdList->OMSetRenderTargets(1, rtvHandles, false, nullptr); + + const float clearColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; + cmdList->ClearRenderTargetView(rtvHandles[0], clearColor, 0, nullptr); + + DX12::SetViewport(cmdList, swapChain.Width(), swapChain.Height()); + + Float2 viewportSize; + viewportSize.x = float(swapChain.Width()); + viewportSize.y = float(swapChain.Height()); + spriteRenderer.Begin(cmdList, viewportSize, SpriteFilterMode::Point, SpriteBlendMode::AlphaBlend); + + wchar text[32] = L"Compiling Shaders..."; + uint32 numDots = uint32(Frac(timer.ElapsedSecondsF()) * 4.0f); + text[17 + numDots] = 0; + Float2 textSize = font.MeasureText(text); + + Float2 textPos = (viewportSize * 0.5f) - (textSize * 0.5f); + spriteRenderer.RenderText(cmdList, font, text, textPos, Float4(1.0f, 1.0f, 1.0f, 1.0f)); + + spriteRenderer.End(); + + return; + } + + RenderClusters(); + + if(AppSettings::EnableSun) + meshRenderer.RenderSunShadowMap(cmdList, camera); + + if(AppSettings::RenderLights) + meshRenderer.RenderSpotLightShadowMap(cmdList, camera); + + { + // Update the light constant buffer + const void* srcData[2] = { spotLights.Data(), meshRenderer.SpotLightShadowMatrices() }; + uint64 sizes[2] = { spotLights.MemorySize(), spotLights.Size() * sizeof(Float4x4) }; + uint64 offsets[2] = { 0, sizeof(SpotLight) * AppSettings::MaxSpotLights }; + spotLightBuffer.MultiUpdateData(srcData, sizes, offsets, ArraySize_(srcData)); + } + + if(AppSettings::RenderMode == RenderModes::ClusteredForward) + RenderForward(); + else + RenderDeferred(); + + RenderPicking(); + RenderResolve(); + + RenderTexture& finalRT = mainTarget.MSAASamples > 1 ? resolveTarget : mainTarget; + + { + ProfileBlock ppProfileBlock(cmdList, "Post Processing"); + postProcessor.Render(cmdList, finalRT, swapChain.BackBuffer()); + } + + D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[1] = { swapChain.BackBuffer().RTV }; + cmdList->OMSetRenderTargets(1, rtvHandles, false, nullptr); + + RenderClusterVisualizer(); + + DX12::SetViewport(cmdList, swapChain.Width(), swapChain.Height()); + + RenderHUD(timer); +} + +void BindlessDeferred::UpdateDecals(const Timer& timer) +{ + if(AppSettings::ClearDecals.Pressed()) + numDecals = 0; + + // Update picking and placing new decals + cursorDecal = Decal(); + cursorDecal.AlbedoTexIdx = uint32(-1); + cursorDecal.NormalTexIdx = uint32(-1); + cursorDecalIntensity = 0.0f; + if(currMouseState.IsOverWindow && AppSettings::EnableDecalPicker) + { + // Update the decal cursor + const uint64 albedoTexIdx = currDecalType * AppSettings::NumTexturesPerDecal; + const uint64 normalTexIdx = albedoTexIdx + 1; + Assert_(albedoTexIdx < ArraySize_(decalTextures)); + + Float2 textureSize; + textureSize.x = float(decalTextures[albedoTexIdx].Width); + textureSize.y = float(decalTextures[albedoTexIdx].Height); + const float sizeScale = 1 / 1024.0f; + + const PickingData* pickingData = pickingReadbackBuffers[DX12::CurrFrameIdx].Map(); + if(pickingData->Normal != Float3(0.0f, 0.0f, 0.0f)) + { + const float decalThickness = 0.125f; + + cursorDecal.Position = pickingData->Position; + cursorDecal.Size = Float3(textureSize.x * sizeScale, textureSize.y * sizeScale, decalThickness); + cursorDecal.AlbedoTexIdx = decalTextures[albedoTexIdx].SRV; + cursorDecal.NormalTexIdx = decalTextures[normalTexIdx].SRV; + cursorDecalIntensity = float(std::cos(timer.ElapsedSecondsD() * Pi2)) * 0.25f + 0.5f; + + Float3 forward = -pickingData->Normal; + Float3 up = std::abs(Float3::Dot(forward, Float3(0.0f, 1.0f, 0.0f))) < 0.99f ? Float3(0.0f, 1.0f, 0.0f) : Float3(0.0f, 0.0f, 1.0f); + Float3 right = Float3::Normalize(Float3::Cross(up, forward)); + up = Float3::Cross(forward, right); + Float3x3 orientation = Float3x3(right, up, forward); + + cursorDecal.Orientation = Quaternion(orientation); + + if(currMouseState.MButton.RisingEdge) + { + // Place a new decal, and fill the buffer + const uint64 decalIdx = (numDecals++) % AppSettings::MaxDecals; + decals[decalIdx] = cursorDecal; + + currDecalType = (currDecalType + 1) % uint64(AppSettings::NumDecalTypes); + } + } + + pickingReadbackBuffers[DX12::CurrFrameIdx].Unmap(); + } + + // Update the Z bounds, and fill the buffers + const Float4x4 viewMatrix = camera.ViewMatrix(); + const float nearClip = camera.NearClip(); + const float farClip = camera.FarClip(); + const float zRange = farClip - nearClip; + const Float3 cameraPos = camera.Position(); + const float3 boxVerts[8] = { float3(-1, 1, -1), float3(1, 1, -1), float3(-1, 1, 1), float3(1, 1, 1), + float3(-1, -1, -1), float3(1, -1, -1), float3(-1, -1, 1), float3(1, -1, 1) }; + + // Come up with an oriented bounding box that surrounds the near clipping plane. We'll test this box + // for intersection with the decal's bounding box, and use that to estimate if the bounding + // geometry will end up getting clipped by the camera's near clipping plane + Float3 nearClipCenter = cameraPos + nearClip * camera.Forward(); + Float4x4 invProjection = Float4x4::Invert(camera.ProjectionMatrix()); + Float3 nearTopRight = Float3::Transform(Float3(1.0f, 1.0f, 0.0f), invProjection); + Float3 nearClipExtents = Float3(nearTopRight.x, nearTopRight.y, 0.01f); + DirectX::BoundingOrientedBox nearClipBox(nearClipCenter.ToXMFLOAT3(), nearClipExtents.ToXMFLOAT3(), camera.Orientation().ToXMFLOAT4()); + + ClusterBounds* boundsData = decalBoundsBuffer.Map(); + bool intersectsCamera[AppSettings::MaxDecals] = { }; + + const uint64 numDecalsToUpdate = Min(numDecals, AppSettings::MaxDecals); + for(uint64 decalIdx = 0; decalIdx < numDecalsToUpdate; ++decalIdx) + { + const Decal& decal = decals[decalIdx]; + + // Compute conservative Z bounds for the decal based on vertices of the bounding geometry + float minZ = FloatMax; + float maxZ = -FloatMax; + for(uint64 i = 0; i < 8; ++i) + { + Float3 boxVert = boxVerts[i] * decal.Size; + boxVert = Float3::Transform(boxVert, decal.Orientation); + boxVert += decal.Position; + + float vertZ = Float3::Transform(boxVert, viewMatrix).z; + minZ = Min(minZ, vertZ); + maxZ = Max(maxZ, vertZ); + } + + minZ = Saturate((minZ - nearClip) / zRange); + maxZ = Saturate((maxZ - nearClip) / zRange); + + uint64 minZTile = uint64(minZ * AppSettings::NumZTiles); + uint64 maxZTile = Min(uint64(maxZ * AppSettings::NumZTiles), AppSettings::NumZTiles - 1); + + ClusterBounds bounds; + bounds.Position = decal.Position; + bounds.Orientation = decal.Orientation; + bounds.Scale = decal.Size; + bounds.ZBounds = Uint2(uint32(minZTile), uint32(maxZTile)); + boundsData[decalIdx] = bounds; + + // Estimate if this decal's bounding geometry intersects with the camera's near clip plane + DirectX::BoundingOrientedBox box = DirectX::BoundingOrientedBox(decal.Position.ToXMFLOAT3(), decal.Size.ToXMFLOAT3(), decal.Orientation.ToXMFLOAT4()); + intersectsCamera[decalIdx] = box.Intersects(nearClipBox); + } + + decalBuffer.UpdateData(decals.Data(), decals.Size(), 0); + + numIntersectingDecals = 0; + uint32* instanceData = decalInstanceBuffer.Map(); + + for(uint64 decalIdx = 0; decalIdx < numDecalsToUpdate; ++decalIdx) + if(intersectsCamera[decalIdx]) + instanceData[numIntersectingDecals++] = uint32(decalIdx); + + uint64 offset = numIntersectingDecals; + for(uint64 decalIdx = 0; decalIdx < numDecalsToUpdate; ++decalIdx) + if(intersectsCamera[decalIdx] == false) + instanceData[offset++] = uint32(decalIdx); +} + +void BindlessDeferred::UpdateLights() +{ + const uint64 numSpotLights = Min(spotLights.Size(), AppSettings::MaxLightClamp); + + // This is an additional scale factor that's needed to make sure that our polygonal bounding cone + // fully encloses the actual cone representing the light's area of influence + const float inRadius = std::cos(Pi / NumConeSides); + const float scaleCorrection = 1.0f / inRadius; + + const Float4x4 viewMatrix = camera.ViewMatrix(); + const float nearClip = camera.NearClip(); + const float farClip = camera.FarClip(); + const float zRange = farClip - nearClip; + const Float3 cameraPos = camera.Position(); + const uint64 numConeVerts = coneVertices.Size(); + + // Come up with a bounding sphere that surrounds the near clipping plane. We'll test this sphere + // for intersection with the spot light's bounding cone, and use that to over-estimate if the bounding + // geometry will end up getting clipped by the camera's near clipping plane + Float3 nearClipCenter = cameraPos + nearClip * camera.Forward(); + Float4x4 invViewProjection = Float4x4::Invert(camera.ViewProjectionMatrix()); + Float3 nearTopRight = Float3::Transform(Float3(1.0f, 1.0f, 0.0f), invViewProjection); + float nearClipRadius = Float3::Length(nearTopRight - nearClipCenter); + + ClusterBounds* boundsData = spotLightBoundsBuffer.Map(); + bool intersectsCamera[AppSettings::MaxDecals] = { }; + + // Update the light bounds buffer + for(uint64 spotLightIdx = 0; spotLightIdx < numSpotLights; ++spotLightIdx) + { + const SpotLight& spotLight = spotLights[spotLightIdx]; + const ModelSpotLight& srcSpotLight = currentModel->SpotLights()[spotLightIdx]; + ClusterBounds bounds; + bounds.Position = spotLight.Position; + bounds.Orientation = srcSpotLight.Orientation; + bounds.Scale.x = bounds.Scale.y = std::tan(srcSpotLight.AngularAttenuation.y / 2.0f) * spotLight.Range * scaleCorrection; + bounds.Scale.z = spotLight.Range; + + // Compute conservative Z bounds for the light based on vertices of the bounding geometry + float minZ = FloatMax; + float maxZ = -FloatMax; + for(uint64 i = 0; i < numConeVerts; ++i) + { + Float3 coneVert = coneVertices[i] * bounds.Scale; + coneVert = Float3::Transform(coneVert, bounds.Orientation); + coneVert += bounds.Position; + + float vertZ = Float3::Transform(coneVert, viewMatrix).z; + minZ = Min(minZ, vertZ); + maxZ = Max(maxZ, vertZ); + } + + minZ = Saturate((minZ - nearClip) / zRange); + maxZ = Saturate((maxZ - nearClip) / zRange); + + bounds.ZBounds.x = uint32(minZ * AppSettings::NumZTiles); + bounds.ZBounds.y = Min(uint32(maxZ * AppSettings::NumZTiles), uint32(AppSettings::NumZTiles - 1)); + + // Estimate if the light's bounding geometry intersects with the camera's near clip plane + boundsData[spotLightIdx] = bounds; + intersectsCamera[spotLightIdx] = SphereConeIntersection(spotLight.Position, srcSpotLight.Direction, spotLight.Range, + srcSpotLight.AngularAttenuation.y, nearClipCenter, nearClipRadius); + + if(AppSettings::AnimateLightIntensity) + { + float intensityFactor = std::cos(appTimer.ElapsedSecondsF() * Pi + spotLightIdx * 0.1f); + intensityFactor = intensityFactor * 0.5f + 1.0f; + spotLights[spotLightIdx].Intensity = srcSpotLight.Intensity * intensityFactor * SpotLightIntensityFactor; + } + else + spotLights[spotLightIdx].Intensity = srcSpotLight.Intensity * SpotLightIntensityFactor; + } + + numIntersectingSpotLights = 0; + uint32* instanceData = spotLightInstanceBuffer.Map(); + + for(uint64 spotLightIdx = 0; spotLightIdx < numSpotLights; ++spotLightIdx) + if(intersectsCamera[spotLightIdx]) + instanceData[numIntersectingSpotLights++] = uint32(spotLightIdx); + + uint64 offset = numIntersectingSpotLights; + for(uint64 spotLightIdx = 0; spotLightIdx < numSpotLights; ++spotLightIdx) + if(intersectsCamera[spotLightIdx] == false) + instanceData[offset++] = uint32(spotLightIdx); +} + +void BindlessDeferred::RenderClusters() +{ + ID3D12GraphicsCommandList* cmdList = DX12::CmdList; + + PIXMarker marker(cmdList, "Cluster Update"); + ProfileBlock profileBlock(cmdList, "Cluster Update"); + + decalClusterBuffer.MakeWritable(cmdList); + spotLightClusterBuffer.MakeWritable(cmdList); + + { + // Clear decal clusters + D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptors[1] = { decalClusterBuffer.UAV }; + D3D12_GPU_DESCRIPTOR_HANDLE gpuHandle = DX12::TempDescriptorTable(cpuDescriptors, ArraySize_(cpuDescriptors)); + + uint32 values[4] = { }; + cmdList->ClearUnorderedAccessViewUint(gpuHandle, cpuDescriptors[0], decalClusterBuffer.InternalBuffer.Resource, values, 0, nullptr); + } + + { + // Clear spot light clusters + D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptors[1] = { spotLightClusterBuffer.UAV }; + D3D12_GPU_DESCRIPTOR_HANDLE gpuHandle = DX12::TempDescriptorTable(cpuDescriptors, ArraySize_(cpuDescriptors)); + + uint32 values[4] = { }; + cmdList->ClearUnorderedAccessViewUint(gpuHandle, cpuDescriptors[0], spotLightClusterBuffer.InternalBuffer.Resource, values, 0, nullptr); + } + + ClusterConstants clusterConstants; + clusterConstants.ViewProjection = camera.ViewProjectionMatrix(); + clusterConstants.InvProjection = Float4x4::Invert(camera.ProjectionMatrix()); + clusterConstants.NearClip = camera.NearClip(); + clusterConstants.FarClip = camera.FarClip(); + clusterConstants.InvClipRange = 1.0f / (camera.FarClip() - camera.NearClip()); + clusterConstants.NumXTiles = uint32(AppSettings::NumXTiles); + clusterConstants.NumYTiles = uint32(AppSettings::NumYTiles); + clusterConstants.NumXYTiles = uint32(AppSettings::NumXTiles * AppSettings::NumYTiles); + clusterConstants.InstanceOffset = 0; + clusterConstants.NumLights = Min(uint32(spotLights.Size()), AppSettings::MaxLightClamp); + clusterConstants.NumDecals = uint32(Min(numDecals, AppSettings::MaxDecals)); + + D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[1] = { clusterMSAATarget.RTV }; + ClusterRasterizationModes rastMode = AppSettings::ClusterRasterizationMode; + if(rastMode == ClusterRasterizationModes::MSAA4x || rastMode == ClusterRasterizationModes::MSAA8x) + cmdList->OMSetRenderTargets(1, rtvHandles, false, nullptr); + else + cmdList->OMSetRenderTargets(0, nullptr, false, nullptr); + + DX12::SetViewport(cmdList, AppSettings::NumXTiles, AppSettings::NumYTiles); + cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + + cmdList->SetGraphicsRootSignature(clusterRS); + + DX12::BindStandardDescriptorTable(cmdList, ClusterParams_StandardDescriptors, CmdListMode::Graphics); + + if(AppSettings::RenderDecals) + { + // Update decal clusters + decalClusterBuffer.UAVBarrier(cmdList); + + D3D12_INDEX_BUFFER_VIEW ibView = decalClusterIdxBuffer.IBView(); + cmdList->IASetIndexBuffer(&ibView); + + clusterConstants.ElementsPerCluster = uint32(AppSettings::DecalElementsPerCluster); + clusterConstants.InstanceOffset = 0; + clusterConstants.BoundsBufferIdx = decalBoundsBuffer.SRV; + clusterConstants.VertexBufferIdx = decalClusterVtxBuffer.SRV; + clusterConstants.InstanceBufferIdx = decalInstanceBuffer.SRV; + DX12::BindTempConstantBuffer(cmdList, clusterConstants, ClusterParams_CBuffer, CmdListMode::Graphics); + + AppSettings::BindCBufferGfx(cmdList, ClusterParams_AppSettings); + + D3D12_CPU_DESCRIPTOR_HANDLE uavs[] = { decalClusterBuffer.UAV }; + DX12::BindTempDescriptorTable(cmdList, uavs, ArraySize_(uavs), ClusterParams_UAVDescriptors, CmdListMode::Graphics); + + const uint64 numDecalsToRender = Min(numDecals, AppSettings::MaxDecals); + Assert_(numIntersectingDecals <= numDecalsToRender); + const uint64 numNonIntersecting = numDecalsToRender - numIntersectingDecals; + + // Render back faces for decals that intersect with the camera + cmdList->SetPipelineState(clusterIntersectingPSO); + + cmdList->DrawIndexedInstanced(uint32(decalClusterIdxBuffer.NumElements), uint32(numIntersectingDecals), 0, 0, 0); + + // Now for all other decals, render the back faces followed by the front faces + cmdList->SetPipelineState(clusterBackFacePSO); + + clusterConstants.InstanceOffset = uint32(numIntersectingDecals); + DX12::BindTempConstantBuffer(cmdList, clusterConstants, ClusterParams_CBuffer, CmdListMode::Graphics); + + cmdList->DrawIndexedInstanced(uint32(decalClusterIdxBuffer.NumElements), uint32(numNonIntersecting), 0, 0, 0); + + decalClusterBuffer.UAVBarrier(cmdList); + + cmdList->SetPipelineState(clusterFrontFacePSO); + + cmdList->DrawIndexedInstanced(uint32(decalClusterIdxBuffer.NumElements), uint32(numNonIntersecting), 0, 0, 0); + } + + if(AppSettings::RenderLights) + { + // Update decal clusters + spotLightClusterBuffer.UAVBarrier(cmdList); + + D3D12_INDEX_BUFFER_VIEW ibView = spotLightClusterIdxBuffer.IBView(); + cmdList->IASetIndexBuffer(&ibView); + + clusterConstants.ElementsPerCluster = uint32(AppSettings::SpotLightElementsPerCluster); + clusterConstants.InstanceOffset = 0; + clusterConstants.BoundsBufferIdx = spotLightBoundsBuffer.SRV; + clusterConstants.VertexBufferIdx = spotLightClusterVtxBuffer.SRV; + clusterConstants.InstanceBufferIdx = spotLightInstanceBuffer.SRV; + DX12::BindTempConstantBuffer(cmdList, clusterConstants, ClusterParams_CBuffer, CmdListMode::Graphics); + + AppSettings::BindCBufferGfx(cmdList, ClusterParams_AppSettings); + + D3D12_CPU_DESCRIPTOR_HANDLE uavs[] = { spotLightClusterBuffer.UAV }; + DX12::BindTempDescriptorTable(cmdList, uavs, ArraySize_(uavs), ClusterParams_UAVDescriptors, CmdListMode::Graphics); + + const uint64 numLightsToRender = Min(spotLights.Size(), AppSettings::MaxLightClamp); + Assert_(numIntersectingSpotLights <= numLightsToRender); + const uint64 numNonIntersecting = numLightsToRender - numIntersectingSpotLights; + + // Render back faces for decals that intersect with the camera + cmdList->SetPipelineState(clusterIntersectingPSO); + + cmdList->DrawIndexedInstanced(uint32(spotLightClusterIdxBuffer.NumElements), uint32(numIntersectingSpotLights), 0, 0, 0); + + // Now for all other lights, render the back faces followed by the front faces + cmdList->SetPipelineState(clusterBackFacePSO); + + clusterConstants.InstanceOffset = uint32(numIntersectingSpotLights); + DX12::BindTempConstantBuffer(cmdList, clusterConstants, ClusterParams_CBuffer, CmdListMode::Graphics); + + cmdList->DrawIndexedInstanced(uint32(spotLightClusterIdxBuffer.NumElements), uint32(numNonIntersecting), 0, 0, 0); + + spotLightClusterBuffer.UAVBarrier(cmdList); + + cmdList->SetPipelineState(clusterFrontFacePSO); + + cmdList->DrawIndexedInstanced(uint32(spotLightClusterIdxBuffer.NumElements), uint32(numNonIntersecting), 0, 0, 0); + } + + // Sync + decalClusterBuffer.MakeReadable(cmdList); + spotLightClusterBuffer.MakeReadable(cmdList); +} + +void BindlessDeferred::RenderForward() +{ + ID3D12GraphicsCommandList* cmdList = DX12::CmdList; + + PIXMarker marker(cmdList, "Forward rendering"); + + { + // Transition render targets and depth buffers back to a writable state, and sync on the shadow maps + D3D12_RESOURCE_BARRIER barriers[5] = {}; + barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[0].Transition.pResource = mainTarget.Resource(); + barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; + barriers[0].Transition.Subresource = 0; + + barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[1].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[1].Transition.pResource = tangentFrameTarget.Resource(); + barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; + barriers[1].Transition.Subresource = 0; + + barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[2].Transition.pResource = depthBuffer.Resource(); + barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_DEPTH_READ; + barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_DEPTH_WRITE; + barriers[2].Transition.Subresource = 0; + + barriers[3].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[3].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[3].Transition.pResource = meshRenderer.SunShadowMap().Resource(); + barriers[3].Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; + barriers[3].Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + barriers[3].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + barriers[4].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[4].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[4].Transition.pResource = meshRenderer.SpotLightShadowMap().Resource(); + barriers[4].Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; + barriers[4].Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + barriers[4].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + cmdList->ResourceBarrier(ArraySize_(barriers), barriers); + } + + D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[2] = { mainTarget.RTV, tangentFrameTarget.RTV }; + cmdList->OMSetRenderTargets(2, rtvHandles, false, &depthBuffer.DSV); + + const float clearColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; + cmdList->ClearRenderTargetView(rtvHandles[0], clearColor, 0, nullptr); + cmdList->ClearRenderTargetView(rtvHandles[1], clearColor, 0, nullptr); + cmdList->ClearDepthStencilView(depthBuffer.DSV, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr); + + DX12::SetViewport(cmdList, mainTarget.Width(), mainTarget.Height()); + + if(AppSettings::DepthPrepass) + meshRenderer.RenderDepthPrepass(cmdList, camera); + + { + ProfileBlock profileBlock(cmdList, "Forward Rendering Pass"); + + // Render the main forward pass + MainPassData mainPassData; + mainPassData.SkyCache = &skyCache; + mainPassData.DecalTextures = decalTextures; + mainPassData.DecalBuffer = &decalBuffer; + mainPassData.CursorDecal = cursorDecal; + mainPassData.CursorDecalIntensity = cursorDecalIntensity; + mainPassData.DecalClusterBuffer = &decalClusterBuffer; + mainPassData.SpotLightBuffer = &spotLightBuffer; + mainPassData.SpotLightClusterBuffer = &spotLightClusterBuffer; + meshRenderer.RenderMainPass(cmdList, camera, mainPassData); + + cmdList->OMSetRenderTargets(1, rtvHandles, false, &depthBuffer.DSV); + + // Render the sky + skybox.RenderSky(cmdList, camera.ViewMatrix(), camera.ProjectionMatrix(), skyCache, true); + + { + // Make our targets readable again, which will force a sync point. Also transition + // the shadow maps back to their writable state + D3D12_RESOURCE_BARRIER barriers[5] = {}; + barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[0].Transition.pResource = mainTarget.Resource(); + barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; + barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + barriers[0].Transition.Subresource = 0; + + barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[1].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[1].Transition.pResource = tangentFrameTarget.Resource(); + barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; + barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[1].Transition.Subresource = 0; + + barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[2].Transition.pResource = depthBuffer.Resource(); + barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; + barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_DEPTH_READ; + barriers[2].Transition.Subresource = 0; + + barriers[3].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[3].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[3].Transition.pResource = meshRenderer.SunShadowMap().Resource(); + barriers[3].Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + barriers[3].Transition.StateAfter = D3D12_RESOURCE_STATE_DEPTH_WRITE; + barriers[3].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + barriers[4].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[4].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[4].Transition.pResource = meshRenderer.SpotLightShadowMap().Resource(); + barriers[4].Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + barriers[4].Transition.StateAfter = D3D12_RESOURCE_STATE_DEPTH_WRITE; + barriers[4].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + cmdList->ResourceBarrier(ArraySize_(barriers), barriers); + } + } +} + +void BindlessDeferred::RenderDeferred() +{ + ID3D12GraphicsCommandList* cmdList = DX12::CmdList; + + PIXMarker marker(cmdList, "Render Deferred"); + + { + // Transition our G-Buffer targets to a writable state, and sync on shadow map rendering + D3D12_RESOURCE_BARRIER barriers[7] = {}; + barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[0].Transition.pResource = depthBuffer.Resource(); + barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_DEPTH_READ; + barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_DEPTH_WRITE; + barriers[0].Transition.Subresource = 0; + + barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[1].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[1].Transition.pResource = tangentFrameTarget.Resource(); + barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; + barriers[1].Transition.Subresource = 0; + + barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[2].Transition.pResource = uvTarget.Resource(); + barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; + barriers[2].Transition.Subresource = 0; + + barriers[3].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[3].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[3].Transition.pResource = materialIDTarget.Resource(); + barriers[3].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[3].Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; + barriers[3].Transition.Subresource = 0; + + barriers[4].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[4].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[4].Transition.pResource = meshRenderer.SunShadowMap().Resource(); + barriers[4].Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; + barriers[4].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[4].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + barriers[5].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[5].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[5].Transition.pResource = meshRenderer.SpotLightShadowMap().Resource(); + barriers[5].Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; + barriers[5].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[5].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + barriers[6].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[6].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[6].Transition.pResource = uvGradientsTarget.Resource(); + barriers[6].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[6].Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; + barriers[6].Transition.Subresource = 0; + + const uint32 numBarriers = AppSettings::ComputeUVGradients ? ArraySize_(barriers) - 1 : ArraySize_(barriers); + cmdList->ResourceBarrier(numBarriers, barriers); + } + + { + // Set the G-Buffer render targets and clear them + D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[] = { tangentFrameTarget.RTV, uvTarget.RTV, + materialIDTarget.RTV, uvGradientsTarget.RTV }; + const uint32 numTargets = AppSettings::ComputeUVGradients ? ArraySize_(rtvHandles) - 1 : ArraySize_(rtvHandles); + cmdList->OMSetRenderTargets(numTargets, rtvHandles, false, &depthBuffer.DSV); + + const float clearColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; + for(uint64 i = 0; i < numTargets; ++i) + cmdList->ClearRenderTargetView(rtvHandles[i], clearColor, 0, nullptr); + cmdList->ClearDepthStencilView(depthBuffer.DSV, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr); + } + + DX12::SetViewport(cmdList, mainTarget.Width(), mainTarget.Height()); + + /*if(AppSettings::DepthPrepass) + meshRenderer.RenderDepthPrepass(cmdList, camera);*/ + + const bool msaaEnabled = AppSettings::MSAAMode != MSAAModes::MSAANone; + + { + // Render the G-Buffer, and sync + ProfileBlock profileBlock(cmdList, "G-Buffer Rendering"); + + meshRenderer.RenderGBuffer(cmdList, camera); + + D3D12_RESOURCE_BARRIER barriers[5] = {}; + barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[0].Transition.pResource = depthBuffer.Resource(); + barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; + barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_DEPTH_READ; + barriers[0].Transition.Subresource = 0; + + barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[1].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[1].Transition.pResource = tangentFrameTarget.Resource(); + barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; + barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[1].Transition.Subresource = 0; + + barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[2].Transition.pResource = uvTarget.Resource(); + barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; + barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[2].Transition.Subresource = 0; + + barriers[3].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[3].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[3].Transition.pResource = materialIDTarget.Resource(); + barriers[3].Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; + barriers[3].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[3].Transition.Subresource = 0; + + barriers[4].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[4].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[4].Transition.pResource = uvGradientsTarget.Resource(); + barriers[4].Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; + barriers[4].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[4].Transition.Subresource = 0; + + const uint32 numBarriers = AppSettings::ComputeUVGradients ? ArraySize_(barriers) - 1 : ArraySize_(barriers); + cmdList->ResourceBarrier(numBarriers, barriers); + } + + const uint32 numComputeTilesX = uint32(AlignTo(mainTarget.Width(), AppSettings::DeferredTileSize) / AppSettings::DeferredTileSize); + const uint32 numComputeTilesY = uint32(AlignTo(mainTarget.Height(), AppSettings::DeferredTileSize) / AppSettings::DeferredTileSize); + + if(msaaEnabled) + { + // Generate dispatch lists for for per-sample shading + PIXMarker maskMarker(cmdList, "MSAA Mask"); + ProfileBlock profileBlock(cmdList, "MSAA Mask"); + + // Clear the structure counts + { + D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptors[1] = { nonMsaaTileBuffer.CounterUAV }; + D3D12_GPU_DESCRIPTOR_HANDLE gpuHandle = DX12::TempDescriptorTable(cpuDescriptors, ArraySize_(cpuDescriptors)); + + uint32 values[4] = {}; + cmdList->ClearUnorderedAccessViewUint(gpuHandle, cpuDescriptors[0], nonMsaaTileBuffer.CounterResource, values, 0, nullptr); + } + + { + D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptors[1] = { msaaTileBuffer.CounterUAV }; + D3D12_GPU_DESCRIPTOR_HANDLE gpuHandle = DX12::TempDescriptorTable(cpuDescriptors, ArraySize_(cpuDescriptors)); + + uint32 values[4] = {}; + cmdList->ClearUnorderedAccessViewUint(gpuHandle, cpuDescriptors[0], msaaTileBuffer.CounterResource, values, 0, nullptr); + } + + { + // Issue barriers + D3D12_RESOURCE_BARRIER barriers[5] = {}; + barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[0].UAV.pResource = nonMsaaTileBuffer.CounterResource; + + barriers[1] = barriers[0]; + barriers[1].UAV.pResource = msaaTileBuffer.CounterResource; + + barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[2].Transition.pResource = nonMsaaTileBuffer.Resource(); + barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + barriers[2].Transition.Subresource = 0; + + barriers[3] = barriers[2]; + barriers[3].Transition.pResource = msaaTileBuffer.Resource(); + + barriers[4] = barriers[2]; + barriers[4].Transition.pResource = msaaMaskBuffer.Resource(); + + cmdList->ResourceBarrier(ArraySize_(barriers), barriers); + } + + // Generate the edge mask, and fill the buffers containing edge/non-edge tiles + cmdList->SetComputeRootSignature(msaaMaskRootSignature); + cmdList->SetPipelineState(AppSettings::UseZGradientsForMSAAMask ? msaaMaskPSOs[1] : msaaMaskPSOs[0]); + + DX12::BindStandardDescriptorTable(cmdList, MSAAMaskParams_StandardDescriptors, CmdListMode::Compute); + + MSAAMaskConstants msaaMaskConstants; + msaaMaskConstants.NumXTiles = numComputeTilesX; + msaaMaskConstants.MaterialIDMapIdx = materialIDTarget.SRV(); + msaaMaskConstants.UVMapIdx = uvTarget.SRV(); + DX12::BindTempConstantBuffer(cmdList, msaaMaskConstants, MSAAMaskParams_CBuffer, CmdListMode::Compute); + + D3D12_CPU_DESCRIPTOR_HANDLE uavs[] = { nonMsaaTileBuffer.UAV, msaaTileBuffer.UAV, msaaMaskBuffer.UAV }; + DX12::BindTempDescriptorTable(cmdList, uavs, ArraySize_(uavs), MSAAMaskParams_UAVDescriptors, CmdListMode::Compute); + + AppSettings::BindCBufferCompute(cmdList, MSAAMaskParams_AppSettings); + + cmdList->Dispatch(numComputeTilesX, numComputeTilesY, 1); + + { + // Sync on our buffers + D3D12_RESOURCE_BARRIER barriers[4] = {}; + barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[0].Transition.pResource = nonMsaaTileBuffer.CounterResource; + barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + barriers[0].Transition.Subresource = 0; + + barriers[1] = barriers[0]; + barriers[1].Transition.pResource = msaaTileBuffer.CounterResource; + + barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[2].Transition.pResource = nonMsaaArgsBuffer.Resource(); + barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; + barriers[2].Transition.Subresource = 0; + + barriers[3] = barriers[2]; + barriers[3].Transition.pResource = msaaArgsBuffer.Resource(); + + cmdList->ResourceBarrier(ArraySize_(barriers), barriers); + } + + // Copy off the structure counts to our indirect args buffers + cmdList->CopyBufferRegion(nonMsaaArgsBuffer.Resource(), 0, nonMsaaTileBuffer.CounterResource, 0, sizeof(uint32)); + cmdList->CopyBufferRegion(msaaArgsBuffer.Resource(), 0, msaaTileBuffer.CounterResource, 0, sizeof(uint32)); + + { + // Issue remaining barriers + D3D12_RESOURCE_BARRIER barriers[7] = {}; + barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[0].Transition.pResource = nonMsaaTileBuffer.CounterResource; + barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + barriers[0].Transition.Subresource = 0; + + barriers[1] = barriers[0]; + barriers[1].Transition.pResource = msaaTileBuffer.CounterResource; + + barriers[2].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[2].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[2].Transition.pResource = nonMsaaArgsBuffer.Resource(); + barriers[2].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; + barriers[2].Transition.StateAfter = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + barriers[2].Transition.Subresource = 0; + + barriers[3] = barriers[2]; + barriers[3].Transition.pResource = msaaArgsBuffer.Resource(); + + barriers[4].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[4].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[4].Transition.pResource = nonMsaaTileBuffer.Resource(); + barriers[4].Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + barriers[4].Transition.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[4].Transition.Subresource = 0; + + barriers[5] = barriers[4]; + barriers[5].Transition.pResource = msaaTileBuffer.Resource(); + + barriers[6] = barriers[4]; + barriers[6].Transition.pResource = msaaMaskBuffer.Resource(); + + cmdList->ResourceBarrier(ArraySize_(barriers), barriers); + } + } + + if(msaaEnabled) + { + // Render the sky in the empty areas + mainTarget.Transition(cmdList, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + + D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[1] = { mainTarget.RTV }; + cmdList->OMSetRenderTargets(1, rtvHandles, false, &depthBuffer.DSV); + + skybox.RenderSky(cmdList, camera.ViewMatrix(), camera.ProjectionMatrix(), skyCache, true); + + mainTarget.Transition(cmdList, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + } + + { + // Render the full-screen deferred pass + PIXMarker deferredMarker(cmdList, "Deferred Rendering"); + ProfileBlock profileBlock(cmdList, "Deferred Rendering"); + + RenderTexture& deferredTarget = msaaEnabled ? deferredMSAATarget : mainTarget; + deferredTarget.Transition(cmdList, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + + cmdList->SetComputeRootSignature(deferredRootSignature); + cmdList->SetPipelineState(deferredPSOs[0]); + + DX12::BindStandardDescriptorTable(cmdList, DeferredParams_StandardDescriptors, CmdListMode::Compute); + + // Set constant buffers + DeferredConstants deferredConstants; + deferredConstants.InvViewProj = Float4x4::Invert(camera.ViewProjectionMatrix()); + deferredConstants.Projection = camera.ProjectionMatrix(); + deferredConstants.RTSize = Float2(float(mainTarget.Width()), float(mainTarget.Height())); + deferredConstants.NumComputeTilesX = numComputeTilesX; + DX12::BindTempConstantBuffer(cmdList, deferredConstants, DeferredParams_DeferredCBuffer, CmdListMode::Compute); + + ShadingConstants shadingConstants; + shadingConstants.SunDirectionWS = AppSettings::SunDirection; + shadingConstants.SunIrradiance = skyCache.SunIrradiance; + shadingConstants.CosSunAngularRadius = std::cos(DegToRad(AppSettings::SunSize)); + shadingConstants.SinSunAngularRadius = std::sin(DegToRad(AppSettings::SunSize)); + shadingConstants.CameraPosWS = camera.Position(); + + shadingConstants.CursorDecalPos = cursorDecal.Position; + shadingConstants.CursorDecalIntensity = cursorDecalIntensity; + shadingConstants.CursorDecalOrientation = cursorDecal.Orientation; + shadingConstants.CursorDecalSize = cursorDecal.Size; + shadingConstants.CursorDecalTexIdx = cursorDecal.AlbedoTexIdx; + shadingConstants.NumXTiles = uint32(AppSettings::NumXTiles); + shadingConstants.NumXYTiles = uint32(AppSettings::NumXTiles * AppSettings::NumYTiles); + shadingConstants.NearClip = camera.NearClip(); + shadingConstants.FarClip = camera.FarClip(); + shadingConstants.SkySH = skyCache.SH; + + DX12::BindTempConstantBuffer(cmdList, shadingConstants, DeferredParams_PSCBuffer, CmdListMode::Compute); + + const SunShadowConstantsDepthMap& sunShadowConstants = meshRenderer.SunShadowConstantData(); + DX12::BindTempConstantBuffer(cmdList, sunShadowConstants, DeferredParams_ShadowCBuffer, CmdListMode::Compute); + + spotLightBuffer.SetAsComputeRootParameter(cmdList, DeferredParams_LightCBuffer); + + AppSettings::BindCBufferCompute(cmdList, DeferredParams_AppSettings); + + uint32 skyTargetSRV = DX12::NullTexture2DSRV; + if(msaaEnabled) + skyTargetSRV = mainTarget.SRV(); + + uint32 srvIndices[] = + { + meshRenderer.SunShadowMap().SRV(), + meshRenderer.SpotLightShadowMap().SRV(), + meshRenderer.MaterialTextureIndicesBuffer().SRV, + decalBuffer.SRV, + decalClusterBuffer.SRV, + spotLightClusterBuffer.SRV, + nonMsaaTileBuffer.SRV, + msaaTileBuffer.SRV, + tangentFrameTarget.SRV(), + uvTarget.SRV(), + uvGradientsTarget.SRV(), + materialIDTarget.SRV(), + depthBuffer.SRV(), + skyTargetSRV, + msaaMaskBuffer.SRV, + }; + + DX12::BindTempConstantBuffer(cmdList, srvIndices, DeferredParams_SRVIndices, CmdListMode::Compute); + + D3D12_CPU_DESCRIPTOR_HANDLE uavs[] = { deferredTarget.UAV }; + DX12::BindTempDescriptorTable(cmdList, uavs, ArraySize_(uavs), DeferredParams_UAVDescriptors, CmdListMode::Compute); + + if(msaaEnabled) + cmdList->ExecuteIndirect(deferredCmdSignature, 1, nonMsaaArgsBuffer.Resource(), 0, nullptr, 0); + else + cmdList->Dispatch(numComputeTilesX, numComputeTilesY, 1); + + if(msaaEnabled) + { + // No need to sync here, both passes write to different tiles + cmdList->SetPipelineState(deferredPSOs[1]); + + cmdList->ExecuteIndirect(deferredCmdSignature, 1, msaaArgsBuffer.Resource(), 0, nullptr, 0); + + // Sync on the results + D3D12_RESOURCE_BARRIER barriers[2] = {}; + barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[0].Transition.pResource = deferredMSAATarget.Resource(); + barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + barriers[0].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[1].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[1].Transition.pResource = mainTarget.Resource(); + barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + barriers[1].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + cmdList->ResourceBarrier(ArraySize_(barriers), barriers); + } + else + { + // Render the sky in the empty areas + mainTarget.Transition(cmdList, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_RENDER_TARGET); + + D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[1] = { mainTarget.RTV }; + cmdList->OMSetRenderTargets(1, rtvHandles, false, &depthBuffer.DSV); + + skybox.RenderSky(cmdList, camera.ViewMatrix(), camera.ProjectionMatrix(), skyCache, true); + + mainTarget.Transition(cmdList, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + } + } + + { + // Transition the shadow maps back into their writable state + D3D12_RESOURCE_BARRIER barriers[2] = {}; + + barriers[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[0].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[0].Transition.pResource = meshRenderer.SunShadowMap().Resource(); + barriers[0].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[0].Transition.StateAfter = D3D12_RESOURCE_STATE_DEPTH_WRITE; + barriers[0].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + barriers[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barriers[1].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barriers[1].Transition.pResource = meshRenderer.SpotLightShadowMap().Resource(); + barriers[1].Transition.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + barriers[1].Transition.StateAfter = D3D12_RESOURCE_STATE_DEPTH_WRITE; + barriers[1].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + cmdList->ResourceBarrier(ArraySize_(barriers), barriers); + } +} + +// Performs MSAA resolve with a full-screen pixel shader +void BindlessDeferred::RenderResolve() +{ + if(AppSettings::MSAAMode == MSAAModes::MSAANone) + return; + + ID3D12GraphicsCommandList* cmdList = DX12::CmdList; + + PIXMarker pixMarker(cmdList, "MSAA Resolve"); + ProfileBlock profileBlock(cmdList, "MSAA Resolve"); + + resolveTarget.MakeWritable(cmdList); + + D3D12_CPU_DESCRIPTOR_HANDLE rtvs[1] = { resolveTarget.RTV }; + cmdList->OMSetRenderTargets(ArraySize_(rtvs), rtvs, false, nullptr); + DX12::SetViewport(cmdList, resolveTarget.Width(), resolveTarget.Height()); + + const uint64 deferred = AppSettings::RenderMode == RenderModes::DeferredTexturing ? 1 : 0; + ID3D12PipelineState* pso = resolvePSOs[deferred]; + + cmdList->SetGraphicsRootSignature(resolveRootSignature); + cmdList->SetPipelineState(pso); + + DX12::BindStandardDescriptorTable(cmdList, ResolveParams_StandardDescriptors, CmdListMode::Graphics); + + cmdList->SetGraphicsRoot32BitConstant(ResolveParams_Constants, uint32(mainTarget.Width()), 0); + cmdList->SetGraphicsRoot32BitConstant(ResolveParams_Constants, uint32(mainTarget.Height()), 1); + cmdList->SetGraphicsRoot32BitConstant(ResolveParams_Constants, deferred ? deferredMSAATarget.SRV() : mainTarget.SRV(), 2); + + AppSettings::BindCBufferGfx(cmdList, ResolveParams_AppSettings); + + cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + cmdList->IASetIndexBuffer(nullptr); + cmdList->IASetVertexBuffers(0, 0, nullptr); + + cmdList->DrawInstanced(3, 1, 0, 0); + + resolveTarget.MakeReadable(cmdList); +} + +// Runs a simple compute shader that reads depth + tangent from for a particular pixel, and copies +// the results to a readback buffer that's used to generate the "cursor" decal +void BindlessDeferred::RenderPicking() +{ + if(currMouseState.IsOverWindow == false || AppSettings::EnableDecalPicker == false) + return; + + ID3D12GraphicsCommandList* cmdList = DX12::CmdList; + + PIXMarker pixMarker(cmdList, "Picking"); + + cmdList->SetPipelineState(AppSettings::MSAAMode != MSAAModes::MSAANone ? pickingPSOs[1] : pickingPSOs[0]); + cmdList->SetComputeRootSignature(pickingRS); + + DX12::BindStandardDescriptorTable(cmdList, PickingParams_StandardDescriptors, CmdListMode::Compute); + + PickingConstants pickingConstants; + pickingConstants.InverseViewProjection = Float4x4::Invert(camera.ViewProjectionMatrix()); + pickingConstants.PixelPos = Uint2(currMouseState.X, currMouseState.Y); + pickingConstants.RTSize.x = float(mainTarget.Width()); + pickingConstants.RTSize.y = float(mainTarget.Height()); + pickingConstants.TangentMapIdx = tangentFrameTarget.SRV(); + pickingConstants.DepthMapIdx = depthBuffer.SRV(); + DX12::BindTempConstantBuffer(cmdList, pickingConstants, PickingParams_CBuffer, CmdListMode::Compute); + + pickingBuffer.MakeWritable(cmdList); + + D3D12_CPU_DESCRIPTOR_HANDLE uavs[] = { pickingBuffer.UAV }; + DX12::BindTempDescriptorTable(cmdList, uavs, ArraySize_(uavs), PickingParams_UAVDescriptors, CmdListMode::Compute); + + cmdList->Dispatch(1, 1, 1); + + pickingBuffer.MakeReadable(cmdList); + + cmdList->CopyResource(pickingReadbackBuffers[DX12::CurrFrameIdx].Resource, pickingBuffer.InternalBuffer.Resource); +} + +// Renders the 2D "overhead" visualizer that shows per-cluster light/decal counts +void BindlessDeferred::RenderClusterVisualizer() +{ + if(AppSettings::ShowClusterVisualizer == false) + return; + + ID3D12GraphicsCommandList* cmdList = DX12::CmdList; + + PIXMarker pixMarker(cmdList, "Cluster Visualizer"); + + Float2 displaySize = Float2(float(swapChain.Width()), float(swapChain.Height())); + Float2 drawSize = displaySize * 0.375f; + Float2 drawPos = displaySize * (0.5f + (0.5f - 0.375f) / 2.0f); + + D3D12_VIEWPORT viewport = { }; + viewport.Width = drawSize.x; + viewport.Height = drawSize.y; + viewport.MinDepth = 0.0f; + viewport.MaxDepth = 1.0f; + viewport.TopLeftX = drawPos.x; + viewport.TopLeftY = drawPos.y; + + D3D12_RECT scissorRect = { }; + scissorRect.left = 0; + scissorRect.top = 0; + scissorRect.right = uint32(swapChain.Width()); + scissorRect.bottom = uint32(swapChain.Height()); + + cmdList->RSSetViewports(1, &viewport); + cmdList->RSSetScissorRects(1, &scissorRect); + + cmdList->SetGraphicsRootSignature(clusterVisRootSignature); + cmdList->SetPipelineState(clusterVisPSO); + + DX12::BindStandardDescriptorTable(cmdList, ClusterVisParams_StandardDescriptors, CmdListMode::Graphics); + + Float4x4 invProjection = Float4x4::Invert(camera.ProjectionMatrix()); + Float3 farTopRight = Float3::Transform(Float3(1.0f, 1.0f, 1.0f), invProjection); + Float3 farBottomLeft = Float3::Transform(Float3(-1.0f, -1.0f, 1.0f), invProjection); + + ClusterVisConstants clusterVisConstants; + clusterVisConstants.Projection = camera.ProjectionMatrix(); + clusterVisConstants.ViewMin = Float3(farBottomLeft.x, farBottomLeft.y, camera.NearClip()); + clusterVisConstants.NearClip = camera.NearClip(); + clusterVisConstants.ViewMax = Float3(farTopRight.x, farTopRight.y, camera.FarClip()); + clusterVisConstants.InvClipRange = 1.0f / (camera.FarClip() - camera.NearClip()); + clusterVisConstants.DisplaySize = displaySize; + clusterVisConstants.NumXTiles = uint32(AppSettings::NumXTiles); + clusterVisConstants.NumXYTiles = uint32(AppSettings::NumXTiles * AppSettings::NumYTiles); + clusterVisConstants.DecalClusterBufferIdx = decalClusterBuffer.SRV; + clusterVisConstants.SpotLightClusterBufferIdx = spotLightClusterBuffer.SRV; + DX12::BindTempConstantBuffer(cmdList, clusterVisConstants, ClusterVisParams_CBuffer, CmdListMode::Graphics); + + AppSettings::BindCBufferGfx(cmdList, ClusterVisParams_AppSettings); + + cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + cmdList->IASetIndexBuffer(nullptr); + cmdList->IASetVertexBuffers(0, 0, nullptr); + + cmdList->DrawInstanced(3, 1, 0, 0); +} + +void BindlessDeferred::RenderHUD(const Timer& timer) +{ + ID3D12GraphicsCommandList* cmdList = DX12::CmdList; + PIXMarker pixMarker(cmdList, "HUD Pass"); + + Float2 viewportSize; + viewportSize.x = float(swapChain.Width()); + viewportSize.y = float(swapChain.Height()); + spriteRenderer.Begin(cmdList, viewportSize, SpriteFilterMode::Point, SpriteBlendMode::AlphaBlend); + + Float2 textPos = Float2(25.0f, 25.0f); + wstring fpsText = MakeString(L"Frame Time: %.2fms (%u FPS)", 1000.0f / fps, fps); + spriteRenderer.RenderText(cmdList, font, fpsText.c_str(), textPos, Float4(1.0f, 1.0f, 0.0f, 1.0f)); + + spriteRenderer.End(); +} + +int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) +{ + BindlessDeferred app(lpCmdLine); + app.Run(); +} diff --git a/BindlessDeferred/BindlessDeferred.h b/BindlessDeferred/BindlessDeferred.h index 2c45bfd..70e7015 100644 --- a/BindlessDeferred/BindlessDeferred.h +++ b/BindlessDeferred/BindlessDeferred.h @@ -1,212 +1,151 @@ -//================================================================================================= -// -// Bindless Deferred Texturing Sample -// by MJP -// http://mynameismjp.wordpress.com/ -// -// All code and content licensed under the MIT license -// -//================================================================================================= - -#pragma once - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "PostProcessor.h" -#include "MeshRenderer.h" - -using namespace SampleFramework12; - -class BindlessDeferred : public App -{ - -protected: - - FirstPersonCamera camera; - - Skybox skybox; - SkyCache skyCache; - - PostProcessor postProcessor; - - // Model - Model sceneModels[uint64(Scenes::NumValues)]; - const Model* currentModel = nullptr; - MeshRenderer meshRenderer; - - RenderTexture mainTarget; - RenderTexture tangentFrameTarget; - RenderTexture uvTarget; - RenderTexture uvGradientsTarget; - RenderTexture materialIDTarget; - RenderTexture resolveTarget; - RenderTexture deferredMSAATarget; - DepthBuffer depthBuffer; - - Texture decalTextures[AppSettings::NumDecalTextures]; - StructuredBuffer decalBuffer; - StructuredBuffer decalBoundsBuffer; - StructuredBuffer decalInstanceBuffer; - RawBuffer decalClusterBuffer; - Array decals; - uint64 numDecals = 0; - uint64 numIntersectingDecals = 0; - - Array spotLights; - StructuredBuffer spotLightBuffer; - StructuredBuffer spotLightBoundsBuffer; - StructuredBuffer spotLightInstanceBuffer; - RawBuffer spotLightClusterBuffer; - uint64 numIntersectingSpotLights = 0; - - ID3D12RootSignature* clusterRS = nullptr; - CompiledShaderPtr clusterVS; - CompiledShaderPtr clusterFrontFacePS; - CompiledShaderPtr clusterBackFacePS; - CompiledShaderPtr clusterIntersectingPS; - ID3D12PipelineState* clusterFrontFacePSO = nullptr; - ID3D12PipelineState* clusterBackFacePSO = nullptr; - ID3D12PipelineState* clusterIntersectingPSO = nullptr; - RenderTexture clusterMSAATarget; - - StructuredBuffer decalClusterVtxBuffer; - FormattedBuffer decalClusterIdxBuffer; - - StructuredBuffer spotLightClusterVtxBuffer; - FormattedBuffer spotLightClusterIdxBuffer; - Array coneVertices; - - StructuredBuffer pickingBuffer; - ReadbackBuffer pickingReadbackBuffers[DX12::RenderLatency]; - ID3D12RootSignature* pickingRS = nullptr; - ID3D12PipelineState* pickingPSOs[2] = { }; - CompiledShaderPtr pickingCS[2]; - MouseState currMouseState; - Decal cursorDecal; - float cursorDecalIntensity = 0.0f; - uint64 currDecalType = 0; - - CompiledShaderPtr deferredCS[NumMSAAModes][2][2]; - ID3D12RootSignature* deferredRootSignature = nullptr; - ID3D12PipelineState* deferredPSOs[2] = { }; - ID3D12CommandSignature* deferredCmdSignature = nullptr; - - CompiledShaderPtr msaaMaskCS[NumMSAAModes][2]; - ID3D12RootSignature* msaaMaskRootSignature = nullptr; - ID3D12PipelineState* msaaMaskPSOs[2] = { }; - StructuredBuffer nonMsaaTileBuffer; - StructuredBuffer msaaTileBuffer; - StructuredBuffer nonMsaaArgsBuffer; - StructuredBuffer msaaArgsBuffer; - StructuredBuffer msaaMaskBuffer; - - CompiledShaderPtr fullScreenTriVS; - CompiledShaderPtr resolvePS[NumMSAAModes][2]; - ID3D12RootSignature* resolveRootSignature = nullptr; - ID3D12PipelineState* resolvePSOs[2] = { }; - - CompiledShaderPtr clusterVisPS; - ID3D12RootSignature* clusterVisRootSignature = nullptr; - ID3D12PipelineState* clusterVisPSO = nullptr; - - struct ClusterConstants - { - Float4x4 ViewProjection; - Float4x4 InvProjection; - float NearClip; - float FarClip; - float InvClipRange; - uint32 NumXTiles; - uint32 NumYTiles; - uint32 NumXYTiles; - uint32 ElementsPerCluster; - uint32 InstanceOffset; - uint32 NumLights; - uint32 NumDecals; - }; - - struct MSAAMaskConstants - { - uint32 NumXTiles; - }; - - struct DeferredConstants - { - Float4x4 InvViewProj; - Float4x4 Projection; - Float2 RTSize; - uint32 NumComputeTilesX; - }; - - struct PickingConstants - { - Float4x4 InverseViewProjection; - Uint2 PixelPos; - Float2 RTSize; - }; - - struct ClusterVisConstants - { - Float4x4 Projection; - Float3 ViewMin; - float NearClip; - Float3 ViewMax; - float InvClipRange; - Float2 DisplaySize; - uint32 NumXTiles; - uint32 NumXYTiles; - }; - - struct LightConstants - { - SpotLight Lights[AppSettings::MaxSpotLights]; - Float4x4 ShadowMatrices[AppSettings::MaxSpotLights]; - }; - - ConstantBuffer clusterConstants; - ConstantBuffer msaaMaskConstants; - ConstantBuffer deferredConstants; - ConstantBuffer shadingConstants; - ConstantBuffer pickingConstants; - ConstantBuffer clusterVisConstants; - - virtual void Initialize() override; - virtual void Shutdown() override; - - virtual void Render(const Timer& timer) override; - virtual void Update(const Timer& timer) override; - - virtual void BeforeReset() override; - virtual void AfterReset() override; - - virtual void CreatePSOs() override; - virtual void DestroyPSOs() override; - - void CreateRenderTargets(); - void InitializeScene(); - - void UpdateDecals(const Timer& timer); - void UpdateLights(); - - void RenderClusters(); - void RenderForward(); - void RenderDeferred(); - void RenderResolve(); - void RenderPicking(); - void RenderClusterVisualizer(); - void RenderHUD(const Timer& timer); - - static void CompileShadersTask(uint32 start, uint32 end, uint32 threadNum, void* args); - -public: - - BindlessDeferred(); -}; +//================================================================================================= +// +// Bindless Deferred Texturing Sample +// by MJP +// http://mynameismjp.wordpress.com/ +// +// All code and content licensed under the MIT license +// +//================================================================================================= + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "PostProcessor.h" +#include "MeshRenderer.h" + +using namespace SampleFramework12; + +class BindlessDeferred : public App +{ + +protected: + + FirstPersonCamera camera; + + Skybox skybox; + SkyCache skyCache; + + PostProcessor postProcessor; + + // Model + Model sceneModels[uint64(Scenes::NumValues)]; + const Model* currentModel = nullptr; + MeshRenderer meshRenderer; + + RenderTexture mainTarget; + RenderTexture tangentFrameTarget; + RenderTexture uvTarget; + RenderTexture uvGradientsTarget; + RenderTexture materialIDTarget; + RenderTexture resolveTarget; + RenderTexture deferredMSAATarget; + DepthBuffer depthBuffer; + + Texture decalTextures[AppSettings::NumDecalTextures]; + StructuredBuffer decalBuffer; + StructuredBuffer decalBoundsBuffer; + StructuredBuffer decalInstanceBuffer; + RawBuffer decalClusterBuffer; + Array decals; + uint64 numDecals = 0; + uint64 numIntersectingDecals = 0; + + Array spotLights; + ConstantBuffer spotLightBuffer; + StructuredBuffer spotLightBoundsBuffer; + StructuredBuffer spotLightInstanceBuffer; + RawBuffer spotLightClusterBuffer; + uint64 numIntersectingSpotLights = 0; + + ID3D12RootSignature* clusterRS = nullptr; + CompiledShaderPtr clusterVS; + CompiledShaderPtr clusterFrontFacePS; + CompiledShaderPtr clusterBackFacePS; + CompiledShaderPtr clusterIntersectingPS; + ID3D12PipelineState* clusterFrontFacePSO = nullptr; + ID3D12PipelineState* clusterBackFacePSO = nullptr; + ID3D12PipelineState* clusterIntersectingPSO = nullptr; + RenderTexture clusterMSAATarget; + + StructuredBuffer decalClusterVtxBuffer; + FormattedBuffer decalClusterIdxBuffer; + + StructuredBuffer spotLightClusterVtxBuffer; + FormattedBuffer spotLightClusterIdxBuffer; + Array coneVertices; + + StructuredBuffer pickingBuffer; + ReadbackBuffer pickingReadbackBuffers[DX12::RenderLatency]; + ID3D12RootSignature* pickingRS = nullptr; + ID3D12PipelineState* pickingPSOs[2] = { }; + CompiledShaderPtr pickingCS[2]; + MouseState currMouseState; + Decal cursorDecal; + float cursorDecalIntensity = 0.0f; + uint64 currDecalType = 0; + + CompiledShaderPtr deferredCS[NumMSAAModes][2][2]; + ID3D12RootSignature* deferredRootSignature = nullptr; + ID3D12PipelineState* deferredPSOs[2] = { }; + ID3D12CommandSignature* deferredCmdSignature = nullptr; + + CompiledShaderPtr msaaMaskCS[NumMSAAModes][2]; + ID3D12RootSignature* msaaMaskRootSignature = nullptr; + ID3D12PipelineState* msaaMaskPSOs[2] = { }; + StructuredBuffer nonMsaaTileBuffer; + StructuredBuffer msaaTileBuffer; + StructuredBuffer nonMsaaArgsBuffer; + StructuredBuffer msaaArgsBuffer; + StructuredBuffer msaaMaskBuffer; + + CompiledShaderPtr fullScreenTriVS; + CompiledShaderPtr resolvePS[NumMSAAModes][2]; + ID3D12RootSignature* resolveRootSignature = nullptr; + ID3D12PipelineState* resolvePSOs[2] = { }; + + CompiledShaderPtr clusterVisPS; + ID3D12RootSignature* clusterVisRootSignature = nullptr; + ID3D12PipelineState* clusterVisPSO = nullptr; + + virtual void Initialize() override; + virtual void Shutdown() override; + + virtual void Render(const Timer& timer) override; + virtual void Update(const Timer& timer) override; + + virtual void BeforeReset() override; + virtual void AfterReset() override; + + virtual void CreatePSOs() override; + virtual void DestroyPSOs() override; + + void CreateRenderTargets(); + void InitializeScene(); + + void UpdateDecals(const Timer& timer); + void UpdateLights(); + + void RenderClusters(); + void RenderForward(); + void RenderDeferred(); + void RenderResolve(); + void RenderPicking(); + void RenderClusterVisualizer(); + void RenderHUD(const Timer& timer); + + static void CompileShadersTask(uint32 start, uint32 end, uint32 threadNum, void* args); + +public: + + BindlessDeferred(const wchar* cmdLine); +}; diff --git a/BindlessDeferred/BindlessDeferred.sln b/BindlessDeferred/BindlessDeferred.sln index 08fa6ef..5922ecd 100644 --- a/BindlessDeferred/BindlessDeferred.sln +++ b/BindlessDeferred/BindlessDeferred.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.23107.0 +# Visual Studio 15 +VisualStudioVersion = 15.0.26403.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BindlessDeferred", "BindlessDeferred.vcxproj", "{FA705507-9C58-4413-8878-8795F3B9897D}" EndProject diff --git a/BindlessDeferred/BindlessDeferred.vcxproj b/BindlessDeferred/BindlessDeferred.vcxproj index 9f862e6..0d7b31e 100644 --- a/BindlessDeferred/BindlessDeferred.vcxproj +++ b/BindlessDeferred/BindlessDeferred.vcxproj @@ -1,5 +1,5 @@  - + Debug @@ -14,19 +14,19 @@ {FA705507-9C58-4413-8878-8795F3B9897D} Win32Proj BindlessDeferred - 10.0.14393.0 + 10.0 Application true - v140 + v141 Unicode Application false - v140 + v141 true Unicode @@ -37,11 +37,11 @@ - + - + @@ -85,110 +85,121 @@ - + Use Use - + Use Use - + + + Use Use - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + Use Use - + Use Use - + Create Create - + Use Use - - - - - + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - @@ -210,13 +221,25 @@ - + Document + + + Document + + + + + Document + copy "%(FullPath)" $(OutDir)%(Filename)%(Extension) + copy "%(FullPath)" $(OutDir)%(Filename)%(Extension) + + diff --git a/BindlessDeferred/BindlessDeferred.vcxproj.filters b/BindlessDeferred/BindlessDeferred.vcxproj.filters index 902f614..abdd52d 100644 --- a/BindlessDeferred/BindlessDeferred.vcxproj.filters +++ b/BindlessDeferred/BindlessDeferred.vcxproj.filters @@ -5,107 +5,119 @@ - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12 - - SampleFramework12 - - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - - EnkiTS + + SampleFramework12\EnkiTS + + + SampleFramework12\EnkiTS + + + SampleFramework12\ImGui - - EnkiTS + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12 + + + SampleFramework12\HosekSky @@ -113,130 +125,151 @@ - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12 - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - - SampleFramework12 - - + SampleFramework12 - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - + SampleFramework12\Graphics - - EnkiTS + + SampleFramework12\EnkiTS + + + SampleFramework12\EnkiTS + + + SampleFramework12\EnkiTS + + + SampleFramework12\ImGui - - EnkiTS + + SampleFramework12\ImGui - - EnkiTS + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12 + + + SampleFramework12\HosekSky @@ -249,8 +282,14 @@ {075a1545-c637-4509-b8ec-701cdbf9fef9} - - {8267240b-3934-47c0-bb9f-46a9a7847f61} + + {f6b57266-b3a1-4989-a6da-bb809c7a43b0} + + + {d02e01ba-7d18-49be-9c34-b0f749072bbb} + + + {04851386-edd7-402e-bacf-16bf98648c22} @@ -261,9 +300,15 @@ SampleFramework12\External DLLs + + SampleFramework12\External DLLs + + + SampleFramework12\External DLLs + - + SampleFramework12 diff --git a/BindlessDeferred/BindlessDeferred_2019.sln b/BindlessDeferred/BindlessDeferred_2019.sln new file mode 100644 index 0000000..5127723 --- /dev/null +++ b/BindlessDeferred/BindlessDeferred_2019.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28922.388 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BindlessDeferred_2019", "BindlessDeferred_2019.vcxproj", "{FA705507-9C58-4413-8878-8795F3B9897D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FA705507-9C58-4413-8878-8795F3B9897D}.Debug|x64.ActiveCfg = Debug|x64 + {FA705507-9C58-4413-8878-8795F3B9897D}.Debug|x64.Build.0 = Debug|x64 + {FA705507-9C58-4413-8878-8795F3B9897D}.Release|x64.ActiveCfg = Release|x64 + {FA705507-9C58-4413-8878-8795F3B9897D}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/BindlessDeferred/BindlessDeferred_2019.vcxproj b/BindlessDeferred/BindlessDeferred_2019.vcxproj new file mode 100644 index 0000000..d8ed463 --- /dev/null +++ b/BindlessDeferred/BindlessDeferred_2019.vcxproj @@ -0,0 +1,248 @@ + + + + + Debug + x64 + + + Release + x64 + + + + {FA705507-9C58-4413-8878-8795F3B9897D} + Win32Proj + BindlessDeferred + 10.0 + + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + + + + + + + + + + + + + + + true + + + false + + + + Use + Level4 + Disabled + Debug_=1;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + true + false + stdcpp17 + + + Windows + true + + + + + Level3 + Use + MaxSpeed + true + true + NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + true + false + stdcpp17 + + + Windows + true + true + true + + + + + Use + Use + + + Use + Use + + + + + Use + Use + + + + + + + + + + + + + + + + + + + + + + + + + + + Use + Use + + + Use + Use + + + Create + Create + + + Use + Use + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Document + + + + + $(SampleFrameworkDir)SettingsCompiler.exe %(FullPath) + Compiling settings and generating C++ code + $(ProjectDir)\%(Filename).deps + $(SampleFrameworkDir)SettingsCompiler.exe %(FullPath) + Compiling settings and generating C++ code + $(ProjectDir)\%(Filename).deps + + + + + + + + Document + + + + + Document + + + + + Document + copy "%(FullPath)" $(OutDir)%(Filename)%(Extension) + copy "%(FullPath)" $(OutDir)%(Filename)%(Extension) + + + + + + \ No newline at end of file diff --git a/BindlessDeferred/BindlessDeferred_2019.vcxproj.filters b/BindlessDeferred/BindlessDeferred_2019.vcxproj.filters new file mode 100644 index 0000000..abdd52d --- /dev/null +++ b/BindlessDeferred/BindlessDeferred_2019.vcxproj.filters @@ -0,0 +1,315 @@ + + + + + + + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12 + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\EnkiTS + + + SampleFramework12\EnkiTS + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12 + + + SampleFramework12\HosekSky + + + + + + + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12 + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + + SampleFramework12\Graphics + + + + SampleFramework12\EnkiTS + + + SampleFramework12\EnkiTS + + + SampleFramework12\EnkiTS + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12 + + + SampleFramework12\HosekSky + + + + + {f3f7f78e-3efa-49dc-b296-8ee1e9ac5ce3} + + + {75a60a2c-5900-4bd1-82c7-81e3237b116f} + + + {075a1545-c637-4509-b8ec-701cdbf9fef9} + + + {f6b57266-b3a1-4989-a6da-bb809c7a43b0} + + + {d02e01ba-7d18-49be-9c34-b0f749072bbb} + + + {04851386-edd7-402e-bacf-16bf98648c22} + + + + + SampleFramework12\External DLLs + + + + SampleFramework12\External DLLs + + + SampleFramework12\External DLLs + + + SampleFramework12\External DLLs + + + + + SampleFramework12 + + + \ No newline at end of file diff --git a/BindlessDeferred/BindlessDeferred_2022.sln b/BindlessDeferred/BindlessDeferred_2022.sln new file mode 100644 index 0000000..806e053 --- /dev/null +++ b/BindlessDeferred/BindlessDeferred_2022.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.32014.148 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BindlessDeferred_2022", "BindlessDeferred_2022.vcxproj", "{FA705507-9C58-4413-8878-8795F3B9897D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FA705507-9C58-4413-8878-8795F3B9897D}.Debug|x64.ActiveCfg = Debug|x64 + {FA705507-9C58-4413-8878-8795F3B9897D}.Debug|x64.Build.0 = Debug|x64 + {FA705507-9C58-4413-8878-8795F3B9897D}.Release|x64.ActiveCfg = Release|x64 + {FA705507-9C58-4413-8878-8795F3B9897D}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/BindlessDeferred/BindlessDeferred_2022.vcxproj b/BindlessDeferred/BindlessDeferred_2022.vcxproj new file mode 100644 index 0000000..2f951de --- /dev/null +++ b/BindlessDeferred/BindlessDeferred_2022.vcxproj @@ -0,0 +1,248 @@ + + + + + Debug + x64 + + + Release + x64 + + + + {FA705507-9C58-4413-8878-8795F3B9897D} + Win32Proj + BindlessDeferred + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + true + + + false + + + + Use + Level4 + Disabled + Debug_=1;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + true + false + stdcpp17 + + + Windows + true + + + + + Level3 + Use + MaxSpeed + true + true + NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + true + true + false + stdcpp17 + + + Windows + true + true + true + + + + + Use + Use + + + Use + Use + + + + + Use + Use + + + + + + + + + + + + + + + + + + + + + + + + + + + Use + Use + + + Use + Use + + + Create + Create + + + Use + Use + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Document + + + + + $(SampleFrameworkDir)SettingsCompiler.exe %(FullPath) + Compiling settings and generating C++ code + $(ProjectDir)\%(Filename).deps + $(SampleFrameworkDir)SettingsCompiler.exe %(FullPath) + Compiling settings and generating C++ code + $(ProjectDir)\%(Filename).deps + + + + + + + + Document + + + + + Document + + + + + Document + copy "%(FullPath)" $(OutDir)%(Filename)%(Extension) + copy "%(FullPath)" $(OutDir)%(Filename)%(Extension) + + + + + + \ No newline at end of file diff --git a/BindlessDeferred/BindlessDeferred_2022.vcxproj.filters b/BindlessDeferred/BindlessDeferred_2022.vcxproj.filters new file mode 100644 index 0000000..abdd52d --- /dev/null +++ b/BindlessDeferred/BindlessDeferred_2022.vcxproj.filters @@ -0,0 +1,315 @@ + + + + + + + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12 + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\EnkiTS + + + SampleFramework12\EnkiTS + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12 + + + SampleFramework12\HosekSky + + + + + + + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12 + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12 + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + SampleFramework12\Graphics + + + + SampleFramework12\Graphics + + + + SampleFramework12\EnkiTS + + + SampleFramework12\EnkiTS + + + SampleFramework12\EnkiTS + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12\ImGui + + + SampleFramework12 + + + SampleFramework12\HosekSky + + + + + {f3f7f78e-3efa-49dc-b296-8ee1e9ac5ce3} + + + {75a60a2c-5900-4bd1-82c7-81e3237b116f} + + + {075a1545-c637-4509-b8ec-701cdbf9fef9} + + + {f6b57266-b3a1-4989-a6da-bb809c7a43b0} + + + {d02e01ba-7d18-49be-9c34-b0f749072bbb} + + + {04851386-edd7-402e-bacf-16bf98648c22} + + + + + SampleFramework12\External DLLs + + + + SampleFramework12\External DLLs + + + SampleFramework12\External DLLs + + + SampleFramework12\External DLLs + + + + + SampleFramework12 + + + \ No newline at end of file diff --git a/BindlessDeferred/ClusterVisualizer.hlsl b/BindlessDeferred/ClusterVisualizer.hlsl index 7164ad7..431f2e9 100644 --- a/BindlessDeferred/ClusterVisualizer.hlsl +++ b/BindlessDeferred/ClusterVisualizer.hlsl @@ -12,6 +12,7 @@ // Includes //================================================================================================= #include +#include #include "AppSettings.hlsl" //================================================================================================= @@ -27,18 +28,21 @@ struct ClusterVisConstants float2 DisplaySize; uint NumXTiles; uint NumXYTiles; + + uint DecalClusterBufferIdx; + uint SpotLightClusterBufferIdx; }; ConstantBuffer CBuffer : register(b0); -ByteAddressBuffer DecalClusterBuffer : register(t0); -ByteAddressBuffer SpotLightClusterBuffer : register(t1); - // ================================================================================================ // Pixel shader for visualizing decal/light counts from an overhead view of the frustum // ================================================================================================ float4 ClusterVisualizerPS(in float4 PositionSS : SV_Position, in float2 TexCoord : TEXCOORD) : SV_Target0 { + ByteAddressBuffer decalClusterBuffer = RawBufferTable[CBuffer.DecalClusterBufferIdx]; + ByteAddressBuffer spotLightClusterBuffer = RawBufferTable[CBuffer.SpotLightClusterBufferIdx]; + float3 viewPos = lerp(CBuffer.ViewMin, CBuffer.ViewMax, float3(TexCoord.x, 0.5f, 1.0f - TexCoord.y)); float4 projectedPos = mul(float4(viewPos, 1.0f), CBuffer.Projection); projectedPos.xyz /= projectedPos.w; @@ -62,7 +66,7 @@ float4 ClusterVisualizerPS(in float4 PositionSS : SV_Position, in float2 TexCoor [unroll] for(uint elemIdx = 0; elemIdx < SpotLightElementsPerCluster; ++elemIdx) { - uint clusterElemMask = SpotLightClusterBuffer.Load((clusterOffset + elemIdx) * 4); + uint clusterElemMask = spotLightClusterBuffer.Load((clusterOffset + elemIdx) * 4); numLights += countbits(clusterElemMask); } @@ -76,7 +80,7 @@ float4 ClusterVisualizerPS(in float4 PositionSS : SV_Position, in float2 TexCoor [unroll] for(uint elemIdx = 0; elemIdx < DecalElementsPerCluster; ++elemIdx) { - uint clusterElemMask = DecalClusterBuffer.Load((clusterOffset + elemIdx) * 4); + uint clusterElemMask = decalClusterBuffer.Load((clusterOffset + elemIdx) * 4); numDecals += countbits(clusterElemMask); } diff --git a/BindlessDeferred/Clusters.hlsl b/BindlessDeferred/Clusters.hlsl index 3b340ea..854367b 100644 --- a/BindlessDeferred/Clusters.hlsl +++ b/BindlessDeferred/Clusters.hlsl @@ -32,6 +32,10 @@ struct ClusterConstants uint InstanceOffset; uint NumLights; uint NumDecals; + + uint BoundsBufferIdx; + uint VertexBufferIdx; + uint InstanceBufferIdx; }; ConstantBuffer CBuffer : register(b0); @@ -39,9 +43,9 @@ ConstantBuffer CBuffer : register(b0); //================================================================================================= // Resources //================================================================================================= -StructuredBuffer BoundsBuffer : register(t0); -StructuredBuffer VertexBuffer : register(t1); -StructuredBuffer InstanceBuffer : register(t2); +StructuredBuffer BoundsBuffers[] : register(t0, space100); +StructuredBuffer VertexBuffers[] : register(t0, space101); +StructuredBuffer InstanceBuffers[] : register(t0, space102); RWByteAddressBuffer ClusterBuffer : register(u0); @@ -54,10 +58,14 @@ struct VSOutput VSOutput ClusterVS(in uint VertexIdx : SV_VertexID, in uint InstanceIdx : SV_InstanceID) { - uint idx = InstanceBuffer[InstanceIdx + CBuffer.InstanceOffset]; - ClusterBounds bounds = BoundsBuffer[idx]; + StructuredBuffer boundsBuffer = BoundsBuffers[CBuffer.BoundsBufferIdx]; + StructuredBuffer vertexBuffer = VertexBuffers[CBuffer.VertexBufferIdx]; + StructuredBuffer instanceBuffer = InstanceBuffers[CBuffer.InstanceBufferIdx]; + + uint idx = instanceBuffer[InstanceIdx + CBuffer.InstanceOffset]; + ClusterBounds bounds = boundsBuffer[idx]; - float3 vtxPos = VertexBuffer[VertexIdx] * bounds.Scale; + float3 vtxPos = vertexBuffer[VertexIdx] * bounds.Scale; vtxPos = QuatRotate(vtxPos, bounds.Orientation); vtxPos += bounds.Position; @@ -73,7 +81,7 @@ void ClusterPS(in VSOutput input) { uint2 tilePosXY = uint2(input.Position.xy); uint elemIdx = input.Index / 32; - uint mask = 1 << (input.Index % 32); + uint mask = 1u << (input.Index % 32); // Estimate the minimum and maximum Z tile intersected by the current triangle, treating the triangle as a plane. // This estimate will be wrong if we end up extrapolating off of the triangle. diff --git a/BindlessDeferred/Deferred.hlsl b/BindlessDeferred/Deferred.hlsl index cdbcb9f..271edbc 100644 --- a/BindlessDeferred/Deferred.hlsl +++ b/BindlessDeferred/Deferred.hlsl @@ -1,332 +1,360 @@ -//================================================================================================= -// -// Bindless Deferred Texturing Sample -// by MJP -// http://mynameismjp.wordpress.com/ -// -// All code and content licensed under the MIT license -// -//================================================================================================= - -#define UseImplicitShadowDerivatives_ 0 - -//================================================================================================= -// Includes -//================================================================================================= -#include "Shading.hlsl" - -//================================================================================================= -// Constant buffers -//================================================================================================= -struct DeferredConstants -{ - row_major float4x4 InvViewProj; - row_major float4x4 Projection; - float2 RTSize; - uint NumComputeTilesX; -}; - -ConstantBuffer PSCBuffer : register(b0); -ConstantBuffer ShadowCBuffer : register(b1); -ConstantBuffer DeferredCBuffer : register(b2); -ConstantBuffer LightCBuffer : register(b3); - -static const uint ThreadGroupSize = DeferredTileSize * DeferredTileSize; - -//================================================================================================= -// Resources -//================================================================================================= -RWTexture2D OutputTexture : register(u0); - -struct TileMSAAMask -{ - uint Masks[DeferredTileMaskSize]; -}; - -Texture2DArray SunShadowMap : register(t0); -Texture2DArray SpotLightShadowMap : register(t1); -StructuredBuffer MaterialIndicesBuffer : register(t2); -StructuredBuffer DecalBuffer : register(t3); -ByteAddressBuffer DecalClusterBuffer : register(t4); -ByteAddressBuffer SpotLightClusterBuffer : register(t5); -StructuredBuffer NonMSAATiles : register(t6); -StructuredBuffer MSAATiles : register(t7); -#if MSAA_ - Texture2DMS TangentFrameMap : register(t8); - Texture2DMS UVMap : register(t9); - Texture2DMS UVGradientMap : register(t10); - Texture2DMS MaterialIDMap : register(t11); - Texture2DMS DepthMap : register(t12); - Texture2DMS SkyMap : register(t13); - StructuredBuffer MSAAMaskBuffer : register(t14); -#else - Texture2D TangentFrameMap : register(t8); - Texture2D UVMap : register(t9); - Texture2D UVGradientMap : register(t10); - Texture2D MaterialIDMap : register(t11); - Texture2D DepthMap : register(t12); -#endif - -Texture2D MaterialTextures[NumMaterialTextures_] : register(t15); - -SamplerState AnisoSampler : register(s0); -SamplerComparisonState ShadowSampler : register(s1); - -// MSAA subsample locations -#if NumMSAASamples_ == 4 - static const float2 SubSampleOffsets[4] = { - float2(-0.125f, -0.375f), - float2( 0.375f, -0.125f), - float2(-0.375f, 0.125f), - float2( 0.125f, 0.375f), - }; -#elif NumMSAASamples_ == 2 - static const float2 SubSampleOffsets[2] = { - float2( 0.25f, 0.25f), - float2(-0.25f, -0.25f), - }; -#else - static const float2 SubSampleOffsets[1] = { - float2(0.0f, 0.0f), - }; -#endif - -#if MSAA_ && ShadePerSample_ - // List of pixels needing per-sample shading - groupshared uint TileMSAAPixels[ThreadGroupSize]; - groupshared uint NumMSAAPixels; -#endif - -#if MSAA_ - #define MSAALoad_(tex, pos, idx) tex.Load(pos, idx) -#else - #define MSAALoad_(tex, pos, idx) tex[pos] -#endif - -// Computes world-space position from post-projection depth -float3 PositionFromDepth(in float zw, in float2 uv) -{ - float linearDepth = DeferredCBuffer.Projection._43 / (zw - DeferredCBuffer.Projection._33); - float4 positionCS = float4(uv * 2.0f - 1.0f, zw, 1.0f); - positionCS.y *= -1.0f; - float4 positionWS = mul(positionCS, DeferredCBuffer.InvViewProj); - return positionWS.xyz / positionWS.w; -} - -// Shades a single sample point, given a pixel position and an MSAA subsample index -void ShadeSample(in uint2 pixelPos, in uint sampleIdx, in uint numMSAASamples) -{ - Quaternion tangentFrame = UnpackQuaternion(MSAALoad_(TangentFrameMap, pixelPos, sampleIdx)); - float2 uv = MSAALoad_(UVMap, pixelPos, sampleIdx).xy * DeferredUVScale; - uint packedMaterialID = MSAALoad_(MaterialIDMap, pixelPos, sampleIdx); - float zw = MSAALoad_(DepthMap, pixelPos, sampleIdx); - - // Recover the tangent frame handedness from the material ID, and then reconstruct the w component - float handedness = packedMaterialID & 0x80 ? -1.0f : 1.0f; - float3x3 tangentFrameMatrix = QuatTo3x3(tangentFrame); - tangentFrameMatrix._m10_m11_m12 *= handedness; - - float2 zwGradients = MSAALoad_(UVMap, pixelPos, sampleIdx).zw; - - #if ComputeUVGradients_ - // Compute gradients, trying not to walk off the edge of the triangle that isn't coplanar - float4 zwGradUp = MSAALoad_(UVMap, int2(pixelPos) + int2(0, -1), sampleIdx); - float4 zwGradDown = MSAALoad_(UVMap, int2(pixelPos) + int2(0, 1), sampleIdx); - float4 zwGradLeft = MSAALoad_(UVMap, int2(pixelPos) + int2(-1, 0), sampleIdx); - float4 zwGradRight = MSAALoad_(UVMap, int2(pixelPos) + int2(1, 0), sampleIdx); - - uint matIDUp = MSAALoad_(MaterialIDMap, int2(pixelPos) + int2(0, -1), sampleIdx); - uint matIDDown = MSAALoad_(MaterialIDMap, int2(pixelPos) + int2(0, 1), sampleIdx); - uint matIDLeft = MSAALoad_(MaterialIDMap, int2(pixelPos) + int2(-1, 0), sampleIdx); - uint matIDRight = MSAALoad_(MaterialIDMap, int2(pixelPos) + int2(1, 0), sampleIdx); - - const float zwGradThreshold = 0.0025f; - bool up = all(abs(zwGradUp.zw - zwGradients) <= zwGradThreshold) && (matIDUp == packedMaterialID); - bool down = all(abs(zwGradDown.zw - zwGradients) <= zwGradThreshold) && (matIDDown == packedMaterialID); - bool left = all(abs(zwGradLeft.zw - zwGradients) <= zwGradThreshold) && (matIDLeft == packedMaterialID); - bool right = all(abs(zwGradRight.zw - zwGradients) <= zwGradThreshold) && (matIDRight == packedMaterialID); - - float2 uvDX = 0.0f; - float2 uvDY = 0.0f; - - if(up) - uvDY = uv - zwGradUp.xy * DeferredUVScale; - else if(down) - uvDY = zwGradDown.xy * DeferredUVScale - uv; - - if(left) - uvDX = uv - zwGradLeft.xy * DeferredUVScale; - else if(right) - uvDX = zwGradRight.xy * DeferredUVScale - uv; - - // Check for wrapping around due to frac(), and correct for it. - if(uvDX.x > 1.0f) - uvDX.x -= 2.0f; - else if(uvDX.x < -1.0f) - uvDX.x += 2.0f; - if(uvDX.y > 1.0f) - uvDX.y -= 2.0f; - else if(uvDX.y < -1.0f) - uvDX.y += 2.0f; - - if(uvDY.x > 1.0f) - uvDY.x -= 2.0f; - else if(uvDY.x < -1.0f) - uvDY.x += 2.0f; - if(uvDY.y > 1.0f) - uvDY.y -= 2.0f; - else if(uvDY.y < -1.0f) - uvDY.y += 2.0f; - #else - // Read the UV gradients from the G-Buffer - float4 uvGradients = MSAALoad_(UVGradientMap, pixelPos, sampleIdx); - float2 uvDX = uvGradients.xy; - float2 uvDY = uvGradients.zw; - #endif - - float2 invRTSize = 1.0f / DeferredCBuffer.RTSize; - - // Reconstruct the surface position from the depth buffer - float linearDepth = DeferredCBuffer.Projection._43 / (zw - DeferredCBuffer.Projection._33); - float2 screenUV = (pixelPos + 0.5f + SubSampleOffsets[sampleIdx]) * invRTSize; - float3 positionWS = PositionFromDepth(zw, screenUV); - - // Compute the position derivatives using the stored Z derivatives - zwGradients = sign(zwGradients) * pow(abs(zwGradients), 2.0f); - float2 zwNeighbors = saturate(zw.xx + zwGradients); - float3 positionDX = PositionFromDepth(zwNeighbors.x, screenUV + (int2(1, 0) * invRTSize)) - positionWS; - float3 positionDY = PositionFromDepth(zwNeighbors.y, screenUV + (int2(0, 1) * invRTSize)) - positionWS; - - uint materialID = packedMaterialID & 0x7F; - - MaterialTextureIndices matIndices = MaterialIndicesBuffer[NonUniformResourceIndex(materialID)]; - Texture2D AlbedoMap = MaterialTextures[NonUniformResourceIndex(matIndices.Albedo)]; - Texture2D NormalMap = MaterialTextures[NonUniformResourceIndex(matIndices.Normal)]; - Texture2D RoughnessMap = MaterialTextures[NonUniformResourceIndex(matIndices.Roughness)]; - Texture2D MetallicMap = MaterialTextures[NonUniformResourceIndex(matIndices.Metallic)]; - - ShadingInput shadingInput; - shadingInput.PositionSS = pixelPos; - shadingInput.PositionWS = positionWS; - shadingInput.PositionWS_DX = positionDX; - shadingInput.PositionWS_DY = positionDY; - shadingInput.DepthVS = linearDepth; - shadingInput.TangentFrame = tangentFrameMatrix; - - shadingInput.AlbedoMap = AlbedoMap.SampleGrad(AnisoSampler, uv, uvDX, uvDY); - shadingInput.NormalMap = NormalMap.SampleGrad(AnisoSampler, uv, uvDX, uvDY).xy; - shadingInput.RoughnessMap = RoughnessMap.SampleGrad(AnisoSampler, uv, uvDX, uvDY).x; - shadingInput.MetallicMap = MetallicMap.SampleGrad(AnisoSampler, uv, uvDX, uvDY).x; - - shadingInput.DecalBuffer = DecalBuffer; - shadingInput.DecalClusterBuffer = DecalClusterBuffer; - shadingInput.SpotLightClusterBuffer = SpotLightClusterBuffer; - - shadingInput.AnisoSampler = AnisoSampler; - - shadingInput.ShadingCBuffer = PSCBuffer; - shadingInput.ShadowCBuffer = ShadowCBuffer; - shadingInput.LightCBuffer = LightCBuffer; - - float3 shadingResult = ShadePixel(shadingInput, SunShadowMap, SpotLightShadowMap, ShadowSampler); - - #if MSAA_ - if(zw >= 1.0f) - shadingResult = MSAALoad_(SkyMap, pixelPos, sampleIdx).xyz; - #endif - - #if ShadePerSample_ - if(AppSettings.ShowMSAAMask) - shadingResult = lerp(shadingResult, float3(0, 0.0f, 5.0f), 0.5f);; - #endif - - if(AppSettings.ShowUVGradients) - shadingResult = abs(float3(uvDX, uvDY.x)) * 64.0f; - - uint2 outputPos = pixelPos; - #if ShadePerSample_ - // When MSAA is enabled, the output target is 2x the width/height since D3D doesn't - // support writing to MSAA textures trough a UAV - uint2 offset = uint2(sampleIdx % 2, sampleIdx / 2); - offset *= uint2(DeferredCBuffer.RTSize); - outputPos += offset; - #endif - - OutputTexture[outputPos] = float4(shadingResult, float(numMSAASamples)); -} - -//================================================================================================= -// Compute shader for deferred texturing -//================================================================================================= -[numthreads(DeferredTileSize, DeferredTileSize, 1)] -void DeferredCS(in uint3 DispatchID : SV_DispatchThreadID, in uint GroupIndex : SV_GroupIndex, - in uint3 GroupID : SV_GroupID, in uint3 GroupThreadID : SV_GroupThreadID) -{ - #if MSAA_ - // When MSAA is enabled, we have list of Edge and non-Edge tiles in a buffer and we use - // ExecuteIndirect to dispatch the appropriate number of thread groups for each case - #if ShadePerSample_ - const uint packedTilePos = MSAATiles[GroupID.x]; - #else - const uint packedTilePos = NonMSAATiles[GroupID.x]; - #endif - const uint2 tilePos = uint2(packedTilePos & 0xFFFF, packedTilePos >> 16); - const uint2 pixelPos = tilePos * DeferredTileSize + GroupThreadID.xy; - - #if ShadePerSample_ - // See if the pixel we're working on is an edge pixel - const uint tileIdx = tilePos.y * DeferredCBuffer.NumComputeTilesX + tilePos.x; - TileMSAAMask tileMask = MSAAMaskBuffer[tileIdx]; - const uint msaaEdge = tileMask.Masks[GroupIndex / 32] & (1 << (GroupIndex % 32)); - const uint numMSAASamples = msaaEdge ? NumMSAASamples_ : 1; - #else - const uint numMSAASamples = 1; - #endif - #else - const uint2 pixelPos = DispatchID.xy; - const uint numMSAASamples = 1; - #endif - - ShadeSample(pixelPos, 0, numMSAASamples); - - #if ShadePerSample_ - if(GroupIndex == 0) - NumMSAAPixels = 0; - - GroupMemoryBarrierWithGroupSync(); - - if(msaaEdge) - { - // If this is an edge pixel, we need to shade the rest of the subsamples. To do this, - // we build a list in thread group shared memory containing all of the edge pixels - // and then loop over the list in batches of contiguous thread. - uint listIndex; - InterlockedAdd(NumMSAAPixels, 1, listIndex); - TileMSAAPixels[listIndex] = (pixelPos.y << 16) | (pixelPos.x & 0xFFFF); - } - - GroupMemoryBarrierWithGroupSync(); - - const uint extraSamples = (NumMSAASamples_ - 1); - const uint numSamples = NumMSAAPixels * extraSamples; - - // Shade the rest of the samples for edge pixels - // NOTE: this loop is unrolled to work around an issue with the shader compiler where - // optimization fails to converge - [unroll(extraSamples)] - for(uint msaaPixelIdx = GroupIndex; msaaPixelIdx < numSamples; msaaPixelIdx += ThreadGroupSize) - { - uint listIdx = msaaPixelIdx / extraSamples; - uint sampleIdx = (msaaPixelIdx % extraSamples) + 1; - - uint2 samplePixelPos; - samplePixelPos.x = TileMSAAPixels[listIdx] & 0xFFFF; - samplePixelPos.y = TileMSAAPixels[listIdx] >> 16; - - ShadeSample(samplePixelPos, sampleIdx, NumMSAASamples_); - } - - if(AppSettings.ShowMSAAMask && msaaEdge) - OutputTexture[pixelPos] = float4(0.0f, 0.0f, 100.0f, 1.0f); - #endif +//================================================================================================= +// +// Bindless Deferred Texturing Sample +// by MJP +// http://mynameismjp.wordpress.com/ +// +// All code and content licensed under the MIT license +// +//================================================================================================= + +#define UseImplicitShadowDerivatives_ 0 + +//================================================================================================= +// Includes +//================================================================================================= +#include "Shading.hlsl" + +//================================================================================================= +// Constant buffers +//================================================================================================= +struct DeferredConstants +{ + row_major float4x4 InvViewProj; + row_major float4x4 Projection; + float2 RTSize; + uint NumComputeTilesX; +}; + +struct SRVIndexConstants +{ + uint SunShadowMapIdx; + uint SpotLightShadowMapIdx; + uint MaterialIndicesBufferIdx; + uint DecalBufferIdx; + uint DecalClusterBufferIdx; + uint SpotLightClusterBufferIdx; + uint NonMSAATilesIdx; + uint MSAATilesIdx; + uint TangentFrameMapIdx; + uint UVMapIdx; + uint UVGradientMapIdx; + uint MaterialIDMapIdx; + uint DepthMapIdx; + uint SkyMapIdx; + uint MSAAMaskBufferIdx; +}; + +ConstantBuffer PSCBuffer : register(b0); +ConstantBuffer ShadowCBuffer : register(b1); +ConstantBuffer DeferredCBuffer : register(b2); +ConstantBuffer LightCBuffer : register(b3); +ConstantBuffer SRVIndices : register(b4); + +static const uint ThreadGroupSize = DeferredTileSize * DeferredTileSize; + +//================================================================================================= +// Resources +//================================================================================================= +RWTexture2D OutputTexture : register(u0); + +struct TileMSAAMask +{ + uint Masks[DeferredTileMaskSize]; +}; + +StructuredBuffer MaterialIndexBuffers[] : register(t0, space100); +StructuredBuffer DecalBuffers[] : register(t0, space101); +StructuredBuffer NonMSAATileBuffers[] : register(t0, space102); +StructuredBuffer MSAATileBuffers[] : register(t0, space103); + +#if MSAA_ + Texture2DMS MaterialIDMaps[] : register(t0, space104); + StructuredBuffer MSAAMaskBuffers[] : register(t0, space105); +#else + Texture2D MaterialIDMaps[] : register(t0, space104); +#endif + +SamplerState AnisoSampler : register(s0); +SamplerComparisonState ShadowMapSampler : register(s1); + +// MSAA subsample locations +#if NumMSAASamples_ == 4 + static const float2 SubSampleOffsets[4] = { + float2(-0.125f, -0.375f), + float2( 0.375f, -0.125f), + float2(-0.375f, 0.125f), + float2( 0.125f, 0.375f), + }; +#elif NumMSAASamples_ == 2 + static const float2 SubSampleOffsets[2] = { + float2( 0.25f, 0.25f), + float2(-0.25f, -0.25f), + }; +#else + static const float2 SubSampleOffsets[1] = { + float2(0.0f, 0.0f), + }; +#endif + +#if MSAA_ && ShadePerSample_ + // List of pixels needing per-sample shading + groupshared uint TileMSAAPixels[ThreadGroupSize]; + groupshared uint NumMSAAPixels; +#endif + +#if MSAA_ + #define MSAALoad_(tex, pos, idx) tex.Load(pos, idx) +#else + #define MSAALoad_(tex, pos, idx) tex[pos] +#endif + +// Computes world-space position from post-projection depth +float3 PositionFromDepth(in float zw, in float2 uv) +{ + float linearDepth = DeferredCBuffer.Projection._43 / (zw - DeferredCBuffer.Projection._33); + float4 positionCS = float4(uv * 2.0f - 1.0f, zw, 1.0f); + positionCS.y *= -1.0f; + float4 positionWS = mul(positionCS, DeferredCBuffer.InvViewProj); + return positionWS.xyz / positionWS.w; +} + +// Shades a single sample point, given a pixel position and an MSAA subsample index +void ShadeSample(in uint2 pixelPos, in uint sampleIdx, in uint numMSAASamples) +{ + Texture2DArray sunShadowMap = Tex2DArrayTable[SRVIndices.SunShadowMapIdx]; + Texture2DArray spotLightShadowMap = Tex2DArrayTable[SRVIndices.SpotLightShadowMapIdx]; + StructuredBuffer materialIndicesBuffer = MaterialIndexBuffers[SRVIndices.MaterialIndicesBufferIdx]; + StructuredBuffer decalBuffer = DecalBuffers[SRVIndices.DecalBufferIdx]; + ByteAddressBuffer decalClusterBuffer = RawBufferTable[SRVIndices.DecalClusterBufferIdx]; + ByteAddressBuffer spotLightClusterBuffer = RawBufferTable[SRVIndices.SpotLightClusterBufferIdx]; + #if MSAA_ + Texture2DMS tangentFrameMap = Tex2DMSTable[SRVIndices.TangentFrameMapIdx]; + Texture2DMS uvMap = Tex2DMSTable[SRVIndices.UVMapIdx]; + Texture2DMS uvGradientMap = Tex2DMSTable[SRVIndices.UVGradientMapIdx]; + Texture2DMS materialIDMap = MaterialIDMaps[SRVIndices.MaterialIDMapIdx]; + Texture2DMS depthMap = Tex2DMSTable[SRVIndices.DepthMapIdx]; + Texture2DMS skyMap = Tex2DMSTable[SRVIndices.SkyMapIdx]; + #else + Texture2D tangentFrameMap = Tex2DTable[SRVIndices.TangentFrameMapIdx]; + Texture2D uvMap = Tex2DTable[SRVIndices.UVMapIdx]; + Texture2D uvGradientMap = Tex2DTable[SRVIndices.UVGradientMapIdx]; + Texture2D materialIDMap = MaterialIDMaps[SRVIndices.MaterialIDMapIdx]; + Texture2D depthMap = Tex2DTable[SRVIndices.DepthMapIdx]; + #endif + + Quaternion tangentFrame = UnpackQuaternion(MSAALoad_(tangentFrameMap, pixelPos, sampleIdx)); + float2 uv = MSAALoad_(uvMap, pixelPos, sampleIdx).xy * DeferredUVScale; + uint packedMaterialID = MSAALoad_(materialIDMap, pixelPos, sampleIdx); + float zw = MSAALoad_(depthMap, pixelPos, sampleIdx).x; + + // Recover the tangent frame handedness from the material ID, and then reconstruct the w component + float handedness = packedMaterialID & 0x80 ? -1.0f : 1.0f; + float3x3 tangentFrameMatrix = QuatTo3x3(tangentFrame); + tangentFrameMatrix._m10_m11_m12 *= handedness; + + float2 zwGradients = MSAALoad_(uvMap, pixelPos, sampleIdx).zw; + + #if ComputeUVGradients_ + // Compute gradients, trying not to walk off the edge of the triangle that isn't coplanar + float4 zwGradUp = MSAALoad_(uvMap, int2(pixelPos) + int2(0, -1), sampleIdx); + float4 zwGradDown = MSAALoad_(uvMap, int2(pixelPos) + int2(0, 1), sampleIdx); + float4 zwGradLeft = MSAALoad_(uvMap, int2(pixelPos) + int2(-1, 0), sampleIdx); + float4 zwGradRight = MSAALoad_(uvMap, int2(pixelPos) + int2(1, 0), sampleIdx); + + uint matIDUp = MSAALoad_(materialIDMap, int2(pixelPos) + int2(0, -1), sampleIdx); + uint matIDDown = MSAALoad_(materialIDMap, int2(pixelPos) + int2(0, 1), sampleIdx); + uint matIDLeft = MSAALoad_(materialIDMap, int2(pixelPos) + int2(-1, 0), sampleIdx); + uint matIDRight = MSAALoad_(materialIDMap, int2(pixelPos) + int2(1, 0), sampleIdx); + + const float zwGradThreshold = 0.0025f; + bool up = all(abs(zwGradUp.zw - zwGradients) <= zwGradThreshold) && (matIDUp == packedMaterialID); + bool down = all(abs(zwGradDown.zw - zwGradients) <= zwGradThreshold) && (matIDDown == packedMaterialID); + bool left = all(abs(zwGradLeft.zw - zwGradients) <= zwGradThreshold) && (matIDLeft == packedMaterialID); + bool right = all(abs(zwGradRight.zw - zwGradients) <= zwGradThreshold) && (matIDRight == packedMaterialID); + + float2 uvDX = 0.0f; + float2 uvDY = 0.0f; + + if(up) + uvDY = uv - zwGradUp.xy * DeferredUVScale; + else if(down) + uvDY = zwGradDown.xy * DeferredUVScale - uv; + + if(left) + uvDX = uv - zwGradLeft.xy * DeferredUVScale; + else if(right) + uvDX = zwGradRight.xy * DeferredUVScale - uv; + + // Check for wrapping around due to frac(), and correct for it. + if(uvDX.x > 1.0f) + uvDX.x -= 2.0f; + else if(uvDX.x < -1.0f) + uvDX.x += 2.0f; + if(uvDX.y > 1.0f) + uvDX.y -= 2.0f; + else if(uvDX.y < -1.0f) + uvDX.y += 2.0f; + + if(uvDY.x > 1.0f) + uvDY.x -= 2.0f; + else if(uvDY.x < -1.0f) + uvDY.x += 2.0f; + if(uvDY.y > 1.0f) + uvDY.y -= 2.0f; + else if(uvDY.y < -1.0f) + uvDY.y += 2.0f; + #else + // Read the UV gradients from the G-Buffer + float4 uvGradients = MSAALoad_(uvGradientMap, pixelPos, sampleIdx); + float2 uvDX = uvGradients.xy; + float2 uvDY = uvGradients.zw; + #endif + + float2 invRTSize = 1.0f / DeferredCBuffer.RTSize; + + // Reconstruct the surface position from the depth buffer + float linearDepth = DeferredCBuffer.Projection._43 / (zw - DeferredCBuffer.Projection._33); + float2 screenUV = (pixelPos + 0.5f + SubSampleOffsets[sampleIdx]) * invRTSize; + float3 positionWS = PositionFromDepth(zw, screenUV); + + // Compute the position derivatives using the stored Z derivatives + zwGradients = sign(zwGradients) * pow(abs(zwGradients), 2.0f); + float2 zwNeighbors = saturate(zw.xx + zwGradients); + float3 positionDX = PositionFromDepth(zwNeighbors.x, screenUV + (int2(1, 0) * invRTSize)) - positionWS; + float3 positionDY = PositionFromDepth(zwNeighbors.y, screenUV + (int2(0, 1) * invRTSize)) - positionWS; + + uint materialID = packedMaterialID & 0x7F; + + MaterialTextureIndices matIndices = materialIndicesBuffer[materialID]; + Texture2D AlbedoMap = Tex2DTable[NonUniformResourceIndex(matIndices.Albedo)]; + Texture2D NormalMap = Tex2DTable[NonUniformResourceIndex(matIndices.Normal)]; + Texture2D RoughnessMap = Tex2DTable[NonUniformResourceIndex(matIndices.Roughness)]; + Texture2D MetallicMap = Tex2DTable[NonUniformResourceIndex(matIndices.Metallic)]; + + ShadingInput shadingInput; + shadingInput.PositionSS = pixelPos; + shadingInput.PositionWS = positionWS; + shadingInput.PositionWS_DX = positionDX; + shadingInput.PositionWS_DY = positionDY; + shadingInput.DepthVS = linearDepth; + shadingInput.TangentFrame = tangentFrameMatrix; + + shadingInput.AlbedoMap = AlbedoMap.SampleGrad(AnisoSampler, uv, uvDX, uvDY); + shadingInput.NormalMap = NormalMap.SampleGrad(AnisoSampler, uv, uvDX, uvDY).xy; + shadingInput.RoughnessMap = RoughnessMap.SampleGrad(AnisoSampler, uv, uvDX, uvDY).x; + shadingInput.MetallicMap = MetallicMap.SampleGrad(AnisoSampler, uv, uvDX, uvDY).x; + + shadingInput.DecalBuffer = decalBuffer; + shadingInput.DecalClusterBuffer = decalClusterBuffer; + shadingInput.SpotLightClusterBuffer = spotLightClusterBuffer; + + shadingInput.AnisoSampler = AnisoSampler; + + shadingInput.ShadingCBuffer = PSCBuffer; + shadingInput.ShadowCBuffer = ShadowCBuffer; + shadingInput.LightCBuffer = LightCBuffer; + + float3 shadingResult = ShadePixel(shadingInput, sunShadowMap, spotLightShadowMap, ShadowMapSampler); + + #if MSAA_ + if(zw >= 1.0f) + shadingResult = MSAALoad_(skyMap, pixelPos, sampleIdx).xyz; + #endif + + #if ShadePerSample_ + if(AppSettings.ShowMSAAMask) + shadingResult = lerp(shadingResult, float3(0, 0.0f, 5.0f), 0.5f);; + #endif + + if(AppSettings.ShowUVGradients) + shadingResult = abs(float3(uvDX, uvDY.x)) * 64.0f; + + uint2 outputPos = pixelPos; + #if ShadePerSample_ + // When MSAA is enabled, the output target is 2x the width/height since D3D doesn't + // support writing to MSAA textures trough a UAV + uint2 offset = uint2(sampleIdx % 2, sampleIdx / 2); + offset *= uint2(DeferredCBuffer.RTSize); + outputPos += offset; + #endif + + OutputTexture[outputPos] = float4(shadingResult, float(numMSAASamples)); +} + +//================================================================================================= +// Compute shader for deferred texturing +//================================================================================================= +[numthreads(DeferredTileSize, DeferredTileSize, 1)] +void DeferredCS(in uint3 DispatchID : SV_DispatchThreadID, in uint GroupIndex : SV_GroupIndex, + in uint3 GroupID : SV_GroupID, in uint3 GroupThreadID : SV_GroupThreadID) +{ + #if MSAA_ + StructuredBuffer msaaTiles = MSAATileBuffers[SRVIndices.MSAATilesIdx]; + StructuredBuffer nonMSAATiles = NonMSAATileBuffers[SRVIndices.NonMSAATilesIdx]; + StructuredBuffer msaaMaskBuffer = MSAAMaskBuffers[SRVIndices.MSAAMaskBufferIdx]; + + // When MSAA is enabled, we have list of Edge and non-Edge tiles in a buffer and we use + // ExecuteIndirect to dispatch the appropriate number of thread groups for each case + #if ShadePerSample_ + const uint packedTilePos = msaaTiles[GroupID.x]; + #else + const uint packedTilePos = nonMSAATiles[GroupID.x]; + #endif + const uint2 tilePos = uint2(packedTilePos & 0xFFFF, packedTilePos >> 16); + const uint2 pixelPos = tilePos * DeferredTileSize + GroupThreadID.xy; + + #if ShadePerSample_ + // See if the pixel we're working on is an edge pixel + const uint tileIdx = tilePos.y * DeferredCBuffer.NumComputeTilesX + tilePos.x; + TileMSAAMask tileMask = msaaMaskBuffer[tileIdx]; + const uint msaaEdge = tileMask.Masks[GroupIndex / 32] & (1u << (GroupIndex % 32)); + const uint numMSAASamples = msaaEdge ? NumMSAASamples_ : 1; + #else + const uint numMSAASamples = 1; + #endif + #else + const uint2 pixelPos = DispatchID.xy; + const uint numMSAASamples = 1; + #endif + + ShadeSample(pixelPos, 0, numMSAASamples); + + #if ShadePerSample_ + if(GroupIndex == 0) + NumMSAAPixels = 0; + + GroupMemoryBarrierWithGroupSync(); + + if(msaaEdge) + { + // If this is an edge pixel, we need to shade the rest of the subsamples. To do this, + // we build a list in thread group shared memory containing all of the edge pixels + // and then loop over the list in batches of contiguous thread. + uint listIndex; + InterlockedAdd(NumMSAAPixels, 1, listIndex); + TileMSAAPixels[listIndex] = (pixelPos.y << 16) | (pixelPos.x & 0xFFFF); + } + + GroupMemoryBarrierWithGroupSync(); + + const uint extraSamples = (NumMSAASamples_ - 1); + const uint numSamples = NumMSAAPixels * extraSamples; + + // Shade the rest of the samples for edge pixels + for(uint msaaPixelIdx = GroupIndex; msaaPixelIdx < numSamples; msaaPixelIdx += ThreadGroupSize) + { + uint listIdx = msaaPixelIdx / extraSamples; + uint sampleIdx = (msaaPixelIdx % extraSamples) + 1; + + uint2 samplePixelPos; + samplePixelPos.x = TileMSAAPixels[listIdx] & 0xFFFF; + samplePixelPos.y = TileMSAAPixels[listIdx] >> 16; + + ShadeSample(samplePixelPos, sampleIdx, NumMSAASamples_); + } + + if(AppSettings.ShowMSAAMask && msaaEdge) + OutputTexture[pixelPos] = float4(0.0f, 0.0f, 100.0f, 1.0f); + #endif } \ No newline at end of file diff --git a/BindlessDeferred/DepthOnly.hlsl b/BindlessDeferred/DepthOnly.hlsl index 05f4827..ebc8445 100644 --- a/BindlessDeferred/DepthOnly.hlsl +++ b/BindlessDeferred/DepthOnly.hlsl @@ -8,15 +8,35 @@ // //================================================================================================= +#include +#include +#include "SharedTypes.h" + // ================================================================================================ // Constant buffers // ================================================================================================ -cbuffer VSConstants : register(b0) +struct VSConstants { - float4x4 World; - float4x4 View; - float4x4 WorldViewProjection; -} + row_major float4x4 World; + row_major float4x4 View; + row_major float4x4 WorldViewProjection; +}; + +struct MatIndexConstants +{ + uint MaterialTextureIndicesIdx; + uint MatIndex; +}; + +ConstantBuffer VSCBuffer : register(b0); +ConstantBuffer MatIndexCBuffer : register(b1); + +//================================================================================================= +// Resources +//================================================================================================= +StructuredBuffer MaterialIndicesBuffers[] : register(t0, space100); + +SamplerState AnisoSampler : register(s0); // ================================================================================================ // Input/Output structs @@ -24,11 +44,13 @@ cbuffer VSConstants : register(b0) struct VSInput { float4 PositionOS : POSITION; + float2 UV : UV; }; struct VSOutput { float4 PositionCS : SV_Position; + float2 UV : UV; }; // ================================================================================================ @@ -39,7 +61,8 @@ VSOutput VS(in VSInput input) VSOutput output; // Calc the clip-space position - output.PositionCS = mul(input.PositionOS, WorldViewProjection); + output.PositionCS = mul(input.PositionOS, VSCBuffer.WorldViewProjection); + output.UV = input.UV; return output; } @@ -47,7 +70,12 @@ VSOutput VS(in VSInput input) // ================================================================================================ // Pixel Shader // ================================================================================================ -float4 PS() : SV_Target +void PS(in VSOutput input) { - return float4(0.0f, 0.0f, 0.0f, 1.0f); + StructuredBuffer matIndicesBuffer = MaterialIndicesBuffers[MatIndexCBuffer.MaterialTextureIndicesIdx]; + MaterialTextureIndices matIndices = matIndicesBuffer[MatIndexCBuffer.MatIndex]; + Texture2D AlbedoMap = Tex2DTable[matIndices.Albedo]; + const float alpha = AlbedoMap.Sample(AnisoSampler, input.UV).w; + if(alpha < 0.5f) + discard; } \ No newline at end of file diff --git a/BindlessDeferred/MSAAMask.hlsl b/BindlessDeferred/MSAAMask.hlsl index ca98573..77432de 100644 --- a/BindlessDeferred/MSAAMask.hlsl +++ b/BindlessDeferred/MSAAMask.hlsl @@ -12,6 +12,7 @@ // Includes //================================================================================================= #include +#include #include "AppSettings.hlsl" struct TileMSAAMask @@ -25,15 +26,18 @@ struct TileMSAAMask struct MSAAMaskConstants { uint NumXTiles; + uint MaterialIDMapIdx; + uint UVMapIdx; }; -ConstantBuffer MSAAMaskCBuffer : register(b0); +ConstantBuffer CBuffer : register(b0); //================================================================================================= // Resources //================================================================================================= -Texture2DMS MaterialIDMap : register(t0); +Texture2DMS MaterialIDMaps[] : register(t0, space100); Texture2DMS UVMap : register(t1); + AppendStructuredBuffer NonMSAATiles : register(u0); AppendStructuredBuffer MSAATiles : register(u1); RWStructuredBuffer MSAAMask : register(u2); @@ -48,14 +52,17 @@ void MSAAMaskCS(in uint3 DispatchID : SV_DispatchThreadID, in uint GroupIndex : { uint2 pixelPos = DispatchID.xy; - uint materialID = MaterialIDMap.Load(pixelPos, 0) & 0x7F; - float2 zGradients = UVMap.Load(pixelPos, 0).zw; + Texture2DMS uvMap = Tex2DMSTable[CBuffer.UVMapIdx]; + Texture2DMS materialIDMap = MaterialIDMaps[CBuffer.UVMapIdx]; + + uint materialID = materialIDMap.Load(pixelPos, 0) & 0x7F; + float2 zGradients = uvMap.Load(pixelPos, 0).zw; uint edge = 0; [unroll] for(uint i = 1; i < MSAASamples_; ++i) { - edge += (MaterialIDMap.Load(pixelPos, i) & 0x7F) != materialID; + edge += (materialIDMap.Load(pixelPos, i) & 0x7F) != materialID; #if UseZGradients_ edge += any(abs(UVMap.Load(pixelPos, i).zw - zGradients) > 0.0025f); #endif @@ -69,7 +76,7 @@ void MSAAMaskCS(in uint3 DispatchID : SV_DispatchThreadID, in uint GroupIndex : GroupMemoryBarrierWithGroupSync(); if(perSample) - InterlockedOr(GroupMask.Masks[GroupIndex / 32], 1 << (GroupIndex % 32)); + InterlockedOr(GroupMask.Masks[GroupIndex / 32], 1u << (GroupIndex % 32)); GroupMemoryBarrierWithGroupSync(); @@ -87,7 +94,7 @@ void MSAAMaskCS(in uint3 DispatchID : SV_DispatchThreadID, in uint GroupIndex : else NonMSAATiles.Append(packedTilePos); - uint tileIdx = GroupID.y * MSAAMaskCBuffer.NumXTiles + GroupID.x; + uint tileIdx = GroupID.y * CBuffer.NumXTiles + GroupID.x; MSAAMask[tileIdx] = GroupMask; } } \ No newline at end of file diff --git a/BindlessDeferred/Manifest.txt b/BindlessDeferred/Manifest.txt new file mode 100644 index 0000000..84293bd --- /dev/null +++ b/BindlessDeferred/Manifest.txt @@ -0,0 +1,16 @@ +[References] +SampleFramework12\v1.01 + +[Local] + +SharedTypes.h + +[Content] + +Models\Sponza\Sponza.fbx +Models\Sponza\*.png +Textures\Decals\*.tga +Textures\Decals\*.png + +[Externals] + diff --git a/BindlessDeferred/Mesh.hlsl b/BindlessDeferred/Mesh.hlsl index 0623e21..cfad676 100644 --- a/BindlessDeferred/Mesh.hlsl +++ b/BindlessDeferred/Mesh.hlsl @@ -1,227 +1,255 @@ -//================================================================================================= -// -// Bindless Deferred Texturing Sample -// by MJP -// http://mynameismjp.wordpress.com/ -// -// All code and content licensed under the MIT license -// -//================================================================================================= - -#define UseImplicitShadowDerivatives_ 1 - -//================================================================================================= -// Includes -//================================================================================================= -#include "Shading.hlsl" - -//================================================================================================= -// Constant buffers -//================================================================================================= -struct VSConstants -{ - row_major float4x4 World; - row_major float4x4 View; - row_major float4x4 WorldViewProjection; - float NearClip; - float FarClip; -}; - -struct MatIndexConstants -{ - uint MatIndex; -}; - -ConstantBuffer VSCBuffer : register(b0); -ConstantBuffer PSCBuffer : register(b0); -ConstantBuffer ShadowCBuffer : register(b1); -ConstantBuffer MatIndexCBuffer : register(b2); -ConstantBuffer LightCBuffer : register(b3); - -//================================================================================================= -// Resources -//================================================================================================= -Texture2DArray SunShadowMap : register(t0); -Texture2DArray SpotLightShadowMap : register(t1); -StructuredBuffer MaterialIndicesBuffer : register(t2); -StructuredBuffer DecalBuffer : register(t3); -ByteAddressBuffer DecalClusterBuffer : register(t4); -ByteAddressBuffer SpotLightClusterBuffer : register(t5); - -Texture2D MaterialTextures[NumMaterialTextures_] : register(t6); - -SamplerState AnisoSampler : register(s0); -SamplerComparisonState ShadowSampler : register(s1); - -//================================================================================================= -// Input/Output structs -//================================================================================================= -struct VSInput -{ - float3 PositionOS : POSITION; - float3 NormalOS : NORMAL; - float2 UV : UV; - float3 TangentOS : TANGENT; - float3 BitangentOS : BITANGENT; -}; - -struct VSOutput -{ - float4 PositionCS : SV_Position; - - float3 NormalWS : NORMALWS; - float3 PositionWS : POSITIONWS; - float DepthVS : DEPTHVS; - float3 TangentWS : TANGENTWS; - float3 BitangentWS : BITANGENTWS; - float2 UV : UV; -}; - -struct PSInput -{ - float4 PositionSS : SV_Position; - - float3 NormalWS : NORMALWS; - float3 PositionWS : POSITIONWS; - float DepthVS : DEPTHVS; - float3 TangentWS : TANGENTWS; - float3 BitangentWS : BITANGENTWS; - float2 UV : UV; -}; - -struct PSOutputForward -{ - float4 Color : SV_Target0; - float4 TangentFrame : SV_Target1; -}; - -struct PSOutputGBuffer -{ - float4 TangentFrame : SV_Target0; - float4 UV : SV_Target1; - uint MaterialID : SV_Target2; - #if OutputUVGradients_ - float4 UVGradients : SV_Target3; - #endif -}; - -//================================================================================================= -// Vertex Shader -//================================================================================================= -VSOutput VS(in VSInput input, in uint VertexID : SV_VertexID) -{ - VSOutput output; - - float3 positionOS = input.PositionOS; - - // Calc the world-space position - output.PositionWS = mul(float4(positionOS, 1.0f), VSCBuffer.World).xyz; - - // Calc the clip-space position - output.PositionCS = mul(float4(positionOS, 1.0f), VSCBuffer.WorldViewProjection); - output.DepthVS = output.PositionCS.w; - - // Rotate the normal into world space - output.NormalWS = normalize(mul(float4(input.NormalOS, 0.0f), VSCBuffer.World)).xyz; - - // Rotate the rest of the tangent frame into world space - output.TangentWS = normalize(mul(float4(input.TangentOS, 0.0f), VSCBuffer.World)).xyz; - output.BitangentWS = normalize(mul(float4(input.BitangentOS, 0.0f), VSCBuffer.World)).xyz; - - // Pass along the texture coordinates - output.UV = input.UV; - - return output; -} - -//================================================================================================= -// Pixel Shader for clustered forward rendering -//================================================================================================= -PSOutputForward PSForward(in PSInput input) -{ - float3 vtxNormalWS = normalize(input.NormalWS); - float3 positionWS = input.PositionWS; - - float3 tangentWS = normalize(input.TangentWS); - float3 bitangentWS = normalize(input.BitangentWS); - float3x3 tangentFrame = float3x3(tangentWS, bitangentWS, vtxNormalWS); - - MaterialTextureIndices matIndices = MaterialIndicesBuffer[MatIndexCBuffer.MatIndex]; - Texture2D AlbedoMap = MaterialTextures[matIndices.Albedo]; - Texture2D NormalMap = MaterialTextures[matIndices.Normal]; - Texture2D RoughnessMap = MaterialTextures[matIndices.Roughness]; - Texture2D MetallicMap = MaterialTextures[matIndices.Metallic]; - - ShadingInput shadingInput; - shadingInput.PositionSS = uint2(input.PositionSS.xy); - shadingInput.PositionWS = input.PositionWS; - shadingInput.PositionWS_DX = ddx_fine(input.PositionWS); - shadingInput.PositionWS_DY = ddy_fine(input.PositionWS); - shadingInput.DepthVS = input.DepthVS; - shadingInput.TangentFrame = tangentFrame; - - shadingInput.AlbedoMap = AlbedoMap.Sample(AnisoSampler, input.UV); - shadingInput.NormalMap = NormalMap.Sample(AnisoSampler, input.UV).xy; - shadingInput.RoughnessMap = RoughnessMap.Sample(AnisoSampler, input.UV).x; - shadingInput.MetallicMap = MetallicMap.Sample(AnisoSampler, input.UV).x; - - shadingInput.DecalBuffer = DecalBuffer; - shadingInput.DecalClusterBuffer = DecalClusterBuffer; - shadingInput.SpotLightClusterBuffer = SpotLightClusterBuffer; - - shadingInput.AnisoSampler = AnisoSampler; - - shadingInput.ShadingCBuffer = PSCBuffer; - shadingInput.ShadowCBuffer = ShadowCBuffer; - shadingInput.LightCBuffer = LightCBuffer; - - float3 shadingResult = ShadePixel(shadingInput, SunShadowMap, SpotLightShadowMap, ShadowSampler); - - if(AppSettings.ShowUVGradients) - shadingResult = abs(float3(ddx(input.UV), ddy(input.UV).x)) * 64.0f; - - // The tangent frame can have arbitrary handedness, so we force it to be left-handed. - // We don't pack the handedness bit for forward rendering, since the decal picking only - // cares about the normal direction. - float handedness = dot(bitangentWS, cross(vtxNormalWS, tangentWS)) > 0.0f ? 1.0f : -1.0f; - bitangentWS *= handedness; - Quaternion tangentFrameQ = QuatFrom3x3(float3x3(tangentWS, bitangentWS, vtxNormalWS)); - - PSOutputForward output; - output.Color = float4(shadingResult, 1.0f); - output.TangentFrame = PackQuaternion(tangentFrameQ); - - return output; -} - -//================================================================================================= -// Pixel Shader for G-Buffer rendering using deferred texturing -//================================================================================================= -PSOutputGBuffer PSGBuffer(in PSInput input) -{ - float3 normalWS = normalize(input.NormalWS); - float3 tangentWS = normalize(input.TangentWS); - float3 bitangentWS = normalize(input.BitangentWS); - - // The tangent frame can have arbitrary handedness, so we force it to be left-handed and then - // pack the handedness into the material ID - float handedness = dot(bitangentWS, cross(normalWS, tangentWS)) > 0.0f ? 1.0f : -1.0f; - bitangentWS *= handedness; - - Quaternion tangentFrame = QuatFrom3x3(float3x3(tangentWS, bitangentWS, normalWS)); - - PSOutputGBuffer output; - output.TangentFrame = PackQuaternion(tangentFrame); - output.UV.xy = frac(input.UV / DeferredUVScale); - output.UV.zw = float2(ddx_fine(input.PositionSS.z), ddy_fine(input.PositionSS.z)); - output.UV.zw = sign(output.UV.zw) * pow(abs(output.UV.zw), 1 / 2.0f); - output.MaterialID = MatIndexCBuffer.MatIndex & 0x7F; - if(handedness == -1.0f) - output.MaterialID |= 0x80; - - #if OutputUVGradients_ - output.UVGradients = float4(ddx_fine(input.UV), ddy_fine(input.UV)); - #endif - - return output; -} +//================================================================================================= +// +// Bindless Deferred Texturing Sample +// by MJP +// http://mynameismjp.wordpress.com/ +// +// All code and content licensed under the MIT license +// +//================================================================================================= + +#define UseImplicitShadowDerivatives_ 1 + +//================================================================================================= +// Includes +//================================================================================================= +#include "Shading.hlsl" + +//================================================================================================= +// Constant buffers +//================================================================================================= +struct VSConstants +{ + row_major float4x4 World; + row_major float4x4 View; + row_major float4x4 WorldViewProjection; + float NearClip; + float FarClip; +}; + +struct MatIndexConstants +{ + uint MaterialTextureIndicesIdx; + uint MatIndex; +}; + +struct SRVIndexConstants +{ + uint SunShadowMapIdx; + uint SpotLightShadowMapIdx; + uint DecalBufferIdx; + uint DecalClusterBufferIdx; + uint SpotLightClusterBufferIdx; +}; + +ConstantBuffer VSCBuffer : register(b0); +ConstantBuffer PSCBuffer : register(b0); +ConstantBuffer ShadowCBuffer : register(b1); +ConstantBuffer MatIndexCBuffer : register(b2); +ConstantBuffer LightCBuffer : register(b3); +ConstantBuffer SRVIndices : register(b4); + +//================================================================================================= +// Resources +//================================================================================================= +StructuredBuffer MaterialIndicesBuffers[] : register(t0, space100); +StructuredBuffer DecalBuffers[] : register(t0, space101); +StructuredBuffer MatIndicesBufferForGBuffer : register(t0); + +SamplerState AnisoSampler : register(s0); +SamplerComparisonState ShadowMapSampler : register(s1); + +//================================================================================================= +// Input/Output structs +//================================================================================================= +struct VSInput +{ + float3 PositionOS : POSITION; + float3 NormalOS : NORMAL; + float2 UV : UV; + float3 TangentOS : TANGENT; + float3 BitangentOS : BITANGENT; +}; + +struct VSOutput +{ + float4 PositionCS : SV_Position; + + float3 NormalWS : NORMALWS; + float3 PositionWS : POSITIONWS; + float DepthVS : DEPTHVS; + float3 TangentWS : TANGENTWS; + float3 BitangentWS : BITANGENTWS; + float2 UV : UV; +}; + +struct PSInput +{ + float4 PositionSS : SV_Position; + + float3 NormalWS : NORMALWS; + float3 PositionWS : POSITIONWS; + float DepthVS : DEPTHVS; + float3 TangentWS : TANGENTWS; + float3 BitangentWS : BITANGENTWS; + float2 UV : UV; +}; + +struct PSOutputForward +{ + float4 Color : SV_Target0; + float4 TangentFrame : SV_Target1; +}; + +struct PSOutputGBuffer +{ + float4 TangentFrame : SV_Target0; + float4 UV : SV_Target1; + uint MaterialID : SV_Target2; + #if OutputUVGradients_ + float4 UVGradients : SV_Target3; + #endif +}; + +//================================================================================================= +// Vertex Shader +//================================================================================================= +VSOutput VS(in VSInput input, in uint VertexID : SV_VertexID) +{ + VSOutput output; + + float3 positionOS = input.PositionOS; + + // Calc the world-space position + output.PositionWS = mul(float4(positionOS, 1.0f), VSCBuffer.World).xyz; + + // Calc the clip-space position + output.PositionCS = mul(float4(positionOS, 1.0f), VSCBuffer.WorldViewProjection); + output.DepthVS = output.PositionCS.w; + + // Rotate the normal into world space + output.NormalWS = normalize(mul(float4(input.NormalOS, 0.0f), VSCBuffer.World)).xyz; + + // Rotate the rest of the tangent frame into world space + output.TangentWS = normalize(mul(float4(input.TangentOS, 0.0f), VSCBuffer.World)).xyz; + output.BitangentWS = normalize(mul(float4(input.BitangentOS, 0.0f), VSCBuffer.World)).xyz; + + // Pass along the texture coordinates + output.UV = input.UV; + + return output; +} + +//================================================================================================= +// Pixel Shader for clustered forward rendering +//================================================================================================= +PSOutputForward PSForward(in PSInput input) +{ + float3 vtxNormalWS = normalize(input.NormalWS); + float3 positionWS = input.PositionWS; + + float3 tangentWS = normalize(input.TangentWS); + float3 bitangentWS = normalize(input.BitangentWS); + float3x3 tangentFrame = float3x3(tangentWS, bitangentWS, vtxNormalWS); + + StructuredBuffer matIndicesBuffer = MaterialIndicesBuffers[MatIndexCBuffer.MaterialTextureIndicesIdx]; + MaterialTextureIndices matIndices = matIndicesBuffer[MatIndexCBuffer.MatIndex]; + Texture2D AlbedoMap = Tex2DTable[matIndices.Albedo]; + Texture2D NormalMap = Tex2DTable[matIndices.Normal]; + Texture2D RoughnessMap = Tex2DTable[matIndices.Roughness]; + Texture2D MetallicMap = Tex2DTable[matIndices.Metallic]; + + #if AlphaTest_ + const float alpha = AlbedoMap.Sample(AnisoSampler, input.UV).w; + if(alpha < 0.5f) + discard; + #endif + + ShadingInput shadingInput; + shadingInput.PositionSS = uint2(input.PositionSS.xy); + shadingInput.PositionWS = input.PositionWS; + shadingInput.PositionWS_DX = ddx_fine(input.PositionWS); + shadingInput.PositionWS_DY = ddy_fine(input.PositionWS); + shadingInput.DepthVS = input.DepthVS; + shadingInput.TangentFrame = tangentFrame; + + shadingInput.AlbedoMap = AlbedoMap.Sample(AnisoSampler, input.UV); + shadingInput.NormalMap = NormalMap.Sample(AnisoSampler, input.UV).xy; + shadingInput.RoughnessMap = RoughnessMap.Sample(AnisoSampler, input.UV).x; + shadingInput.MetallicMap = MetallicMap.Sample(AnisoSampler, input.UV).x; + + shadingInput.DecalBuffer = DecalBuffers[SRVIndices.DecalBufferIdx]; + shadingInput.DecalClusterBuffer = RawBufferTable[SRVIndices.DecalClusterBufferIdx]; + shadingInput.SpotLightClusterBuffer = RawBufferTable[SRVIndices.SpotLightClusterBufferIdx]; + + shadingInput.AnisoSampler = AnisoSampler; + + shadingInput.ShadingCBuffer = PSCBuffer; + shadingInput.ShadowCBuffer = ShadowCBuffer; + shadingInput.LightCBuffer = LightCBuffer; + + // The DXIL validator is complaining if we do this after the wave operations inside of ShadePixel + float3 gradients = abs(float3(ddx(input.UV), ddy(input.UV).x)) * 64.0f; + + Texture2DArray sunShadowMap = Tex2DArrayTable[SRVIndices.SunShadowMapIdx]; + Texture2DArray spotLightShadowMap = Tex2DArrayTable[SRVIndices.SpotLightShadowMapIdx]; + + float3 shadingResult = ShadePixel(shadingInput, sunShadowMap, spotLightShadowMap, ShadowMapSampler); + + if(AppSettings.ShowUVGradients) + shadingResult = gradients; + + // The tangent frame can have arbitrary handedness, so we force it to be left-handed. + // We don't pack the handedness bit for forward rendering, since the decal picking only + // cares about the normal direction. + float handedness = dot(bitangentWS, cross(vtxNormalWS, tangentWS)) > 0.0f ? 1.0f : -1.0f; + bitangentWS *= handedness; + Quaternion tangentFrameQ = QuatFrom3x3(float3x3(tangentWS, bitangentWS, vtxNormalWS)); + + PSOutputForward output; + output.Color = float4(shadingResult, 1.0f); + output.TangentFrame = PackQuaternion(tangentFrameQ); + + return output; +} + +//================================================================================================= +// Pixel Shader for G-Buffer rendering using deferred texturing +//================================================================================================= +PSOutputGBuffer PSGBuffer(in PSInput input) +{ + float3 normalWS = normalize(input.NormalWS); + float3 tangentWS = normalize(input.TangentWS); + float3 bitangentWS = normalize(input.BitangentWS); + + // The tangent frame can have arbitrary handedness, so we force it to be left-handed and then + // pack the handedness into the material ID + float handedness = dot(bitangentWS, cross(normalWS, tangentWS)) > 0.0f ? 1.0f : -1.0f; + bitangentWS *= handedness; + + Quaternion tangentFrame = QuatFrom3x3(float3x3(tangentWS, bitangentWS, normalWS)); + + PSOutputGBuffer output; + output.TangentFrame = PackQuaternion(tangentFrame); + output.UV.xy = frac(input.UV / DeferredUVScale); + output.UV.zw = float2(ddx_fine(input.PositionSS.z), ddy_fine(input.PositionSS.z)); + output.UV.zw = sign(output.UV.zw) * pow(abs(output.UV.zw), 1 / 2.0f); + output.MaterialID = MatIndexCBuffer.MatIndex & 0x7F; + if(handedness == -1.0f) + output.MaterialID |= 0x80; + + #if OutputUVGradients_ + output.UVGradients = float4(ddx_fine(input.UV), ddy_fine(input.UV)); + #endif + + #if AlphaTest_ + StructuredBuffer matIndicesBuffer = MaterialIndicesBuffers[MatIndexCBuffer.MaterialTextureIndicesIdx]; + MaterialTextureIndices matIndices = matIndicesBuffer[MatIndexCBuffer.MatIndex]; + Texture2D AlbedoMap = Tex2DTable[matIndices.Albedo]; + const float alpha = AlbedoMap.Sample(AnisoSampler, input.UV).w; + if(alpha < 0.5f) + discard; + #endif + + return output; +} diff --git a/BindlessDeferred/MeshRenderer.cpp b/BindlessDeferred/MeshRenderer.cpp index 13a8e21..bf87df7 100644 --- a/BindlessDeferred/MeshRenderer.cpp +++ b/BindlessDeferred/MeshRenderer.cpp @@ -1,739 +1,847 @@ -//================================================================================================= -// -// Bindless Deferred Texturing Sample -// by MJP -// http://mynameismjp.wordpress.com/ -// -// All code and content licensed under the MIT license -// -//================================================================================================= - -#include - -#include "MeshRenderer.h" - -#include -#include -#include -#include -#include - -#include "AppSettings.h" - -// Constants -static const uint64 SunShadowMapSize = 2048; -static const uint64 SpotLightShadowMapSize = 1024; - -enum MainPassRootParams -{ - MainPass_MatIndexCBuffer, - MainPass_PSCBuffer, - MainPass_ShadowCBuffer, - MainPass_LightCBuffer, - MainPass_AppSettings, - MainPass_SRV, - MainPass_Decals, - MainPass_VSCBuffer, - - NumMainPassRootParams, -}; - -// Used to sort by depth -struct ZSortComparer -{ - const Array& MeshDepths; - ZSortComparer(const Array& meshDepths) : MeshDepths(meshDepths) { } - - bool operator()(uint32 a, uint32 b) - { - return MeshDepths[a] < MeshDepths[b]; - } -}; - -// Frustum culls meshes, and produces a buffer of visible mesh indices -static uint64 CullMeshes(const Camera& camera, const Array& boundingBoxes, Array& drawIndices) -{ - DirectX::BoundingFrustum frustum(camera.ProjectionMatrix().ToSIMD()); - frustum.Transform(frustum, 1.0f, camera.Orientation().ToSIMD(), camera.Position().ToSIMD()); - - uint64 numVisible = 0; - const uint64 numMeshes = boundingBoxes.Size(); - for(uint64 i = 0; i < numMeshes; ++i) - { - if(frustum.Intersects(boundingBoxes[i])) - drawIndices[numVisible++] = uint32(i); - } - - return numVisible; -} - -// Frustum culls meshes, and produces a buffer of visible mesh indices. Also sorts the indices by depth. -static uint64 CullMeshesAndSort(const Camera& camera, const Array& boundingBoxes, - Array& meshDepths, Array& drawIndices) -{ - DirectX::BoundingFrustum frustum(camera.ProjectionMatrix().ToSIMD()); - frustum.Transform(frustum, 1.0f, camera.Orientation().ToSIMD(), camera.Position().ToSIMD()); - - Float4x4 viewMatrix = camera.ViewMatrix(); - - uint64 numVisible = 0; - const uint64 numMeshes = boundingBoxes.Size(); - for(uint64 i = 0; i < numMeshes; ++i) - { - if(frustum.Intersects(boundingBoxes[i])) - { - meshDepths[i] = Float3::Transform(Float3(boundingBoxes[i].Center), viewMatrix).z; - drawIndices[numVisible++] = uint32(i); - } - } - - if(numVisible > 0) - { - ZSortComparer comparer(meshDepths); - std::sort(drawIndices.Data(), drawIndices.Data() + numVisible, comparer); - } - - return numVisible; -} - -// Frustum culls meshes for an orthographic projection, and produces a buffer of visible mesh indices -static uint64 CullMeshesOrthographic(const OrthographicCamera& camera, bool ignoreNearZ, const Array& boundingBoxes, Array& drawIndices) -{ - Float3 mins = Float3(camera.MinX(), camera.MinY(), camera.NearClip()); - Float3 maxes = Float3(camera.MaxX(), camera.MaxY(), camera.FarClip()); - if(ignoreNearZ) - mins.z = -10000.0f; - - Float3 extents = (maxes - mins) / 2.0f; - Float3 center = mins + extents; - center = Float3::Transform(center, camera.Orientation()); - center += camera.Position(); - - DirectX::BoundingOrientedBox obb; - obb.Extents = extents.ToXMFLOAT3(); - obb.Center = center.ToXMFLOAT3(); - obb.Orientation = camera.Orientation().ToXMFLOAT4(); - - uint64 numVisible = 0; - const uint64 numMeshes = boundingBoxes.Size(); - for(uint64 i = 0; i < numMeshes; ++i) - { - if(obb.Intersects(boundingBoxes[i])) - drawIndices[numVisible++] = uint32(i); - } - - return numVisible; -} - -MeshRenderer::MeshRenderer() -{ -} - -void MeshRenderer::LoadShaders() -{ - // Load the mesh shaders - meshDepthVS = CompileFromFile(L"DepthOnly.hlsl", "VS", ShaderType::Vertex, ShaderProfile::SM51); - - CompileOptions opts; - opts.Add("NumMaterialTextures_", uint32(model->MaterialTextures().Count())); - opts.Add("OutputUVGradients_", 1); - meshVS = CompileFromFile(L"Mesh.hlsl", "VS", ShaderType::Vertex, ShaderProfile::SM51, opts); - meshPSForward = CompileFromFile(L"Mesh.hlsl", "PSForward", ShaderType::Pixel, ShaderProfile::SM51, opts); - meshPSGBuffer[0] = CompileFromFile(L"Mesh.hlsl", "PSGBuffer", ShaderType::Pixel, ShaderProfile::SM51, opts); - - opts.Reset(); - opts.Add("NumMaterialTextures_", uint32(model->MaterialTextures().Count())); - opts.Add("OutputUVGradients_", 0); - meshPSGBuffer[1] = CompileFromFile(L"Mesh.hlsl", "PSGBuffer", ShaderType::Pixel, ShaderProfile::SM51, opts); -} - -// Loads resources -void MeshRenderer::Initialize(const Model* model_) -{ - model = model_; - - const uint64 numMeshes = model->Meshes().Size(); - meshBoundingBoxes.Init(numMeshes); - meshDrawIndices.Init(numMeshes, uint32(-1)); - meshZDepths.Init(numMeshes, FloatMax); - for(uint64 i = 0; i < numMeshes; ++i) - { - const Mesh& mesh = model->Meshes()[i]; - DirectX::BoundingBox& boundingBox = meshBoundingBoxes[i]; - Float3 extents = (mesh.AABBMax() - mesh.AABBMin()) / 2.0f; - Float3 center = mesh.AABBMin() + extents; - boundingBox.Center = center.ToXMFLOAT3(); - boundingBox.Extents = extents.ToXMFLOAT3(); - } - - meshVSConstants.Initialize(BufferLifetime::Temporary); - meshPSConstants.Initialize(BufferLifetime::Temporary); - sunShadowConstants.Initialize(BufferLifetime::Temporary); - - LoadShaders(); - - sunShadowMap.Initialize(SunShadowMapSize, SunShadowMapSize, DXGI_FORMAT_D32_FLOAT, 1, NumCascades, D3D12_RESOURCE_STATE_DEPTH_WRITE); - sunShadowMap.Resource()->SetName(L"Sun Shadow Map"); - - const uint64 numSpotLights = model->SpotLights().Size(); - spotLightShadowMap.Initialize(SpotLightShadowMapSize, SpotLightShadowMapSize, DXGI_FORMAT_D24_UNORM_S8_UINT, 1, numSpotLights, D3D12_RESOURCE_STATE_DEPTH_WRITE); - spotLightShadowMap.Resource()->SetName(L"Sun Shadow Map"); - - const uint64 numMaterialTextures = model->MaterialTextures().Count(); - - { - // Create a structured buffer containing texture indices per-material - const Array& materials = model->Materials(); - const uint64 numMaterials = materials.Size(); - Array textureIndices(numMaterials); - for(uint64 i = 0; i < numMaterials; ++i) - { - MaterialTextureIndices& matIndices = textureIndices[i]; - const MeshMaterial& material = materials[i]; - - matIndices.Albedo = material.TextureIndices[uint64(MaterialTextures::Albedo)]; - matIndices.Normal = material.TextureIndices[uint64(MaterialTextures::Normal)]; - matIndices.Roughness = material.TextureIndices[uint64(MaterialTextures::Roughness)]; - matIndices.Metallic = material.TextureIndices[uint64(MaterialTextures::Metallic)]; - } - - StructuredBufferInit sbInit; - sbInit.Stride = sizeof(MaterialTextureIndices); - sbInit.NumElements = numMaterials; - sbInit.Dynamic = false; - sbInit.Lifetime = BufferLifetime::Persistent; - sbInit.InitData = textureIndices.Data(); - materialTextureIndices.Initialize(sbInit); - materialTextureIndices.Resource()->SetName(L"Material Texture Indices"); - } - - { - // Main pass root signature - D3D12_DESCRIPTOR_RANGE1 srvRanges[1] = {}; - srvRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - srvRanges[0].NumDescriptors = uint32(6 + numMaterialTextures); - srvRanges[0].BaseShaderRegister = 0; - srvRanges[0].RegisterSpace = 0; - srvRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - D3D12_DESCRIPTOR_RANGE1 decalTextureRanges[1] = {}; - decalTextureRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - decalTextureRanges[0].NumDescriptors = AppSettings::NumDecalTextures; - decalTextureRanges[0].BaseShaderRegister = 0; - decalTextureRanges[0].RegisterSpace = 1; - decalTextureRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - D3D12_ROOT_PARAMETER1 rootParameters[NumMainPassRootParams] = {}; - - // VSCBuffer - rootParameters[MainPass_VSCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[MainPass_VSCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; - rootParameters[MainPass_VSCBuffer].Descriptor.RegisterSpace = 0; - rootParameters[MainPass_VSCBuffer].Descriptor.ShaderRegister = 0; - - // PSCBuffer - rootParameters[MainPass_PSCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[MainPass_PSCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[MainPass_PSCBuffer].Descriptor.RegisterSpace = 0; - rootParameters[MainPass_PSCBuffer].Descriptor.ShaderRegister = 0; - - // ShadowCBuffer - rootParameters[MainPass_ShadowCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[MainPass_ShadowCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[MainPass_ShadowCBuffer].Descriptor.RegisterSpace = 0; - rootParameters[MainPass_ShadowCBuffer].Descriptor.ShaderRegister = 1; - - // LightCBuffer - rootParameters[MainPass_LightCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[MainPass_LightCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[MainPass_LightCBuffer].Descriptor.RegisterSpace = 0; - rootParameters[MainPass_LightCBuffer].Descriptor.ShaderRegister = 3; - - // AppSettings - rootParameters[MainPass_AppSettings].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[MainPass_AppSettings].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[MainPass_AppSettings].Descriptor.RegisterSpace = 0; - rootParameters[MainPass_AppSettings].Descriptor.ShaderRegister = AppSettings::CBufferRegister; - - // MatIndexCBuffer - rootParameters[MainPass_MatIndexCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - rootParameters[MainPass_MatIndexCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[MainPass_MatIndexCBuffer].Constants.Num32BitValues = 1; - rootParameters[MainPass_MatIndexCBuffer].Constants.RegisterSpace = 0; - rootParameters[MainPass_MatIndexCBuffer].Constants.ShaderRegister = 2; - - // SRV descriptors - rootParameters[MainPass_SRV].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[MainPass_SRV].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[MainPass_SRV].DescriptorTable.pDescriptorRanges = srvRanges; - rootParameters[MainPass_SRV].DescriptorTable.NumDescriptorRanges = 1; - - // Decal texture descriptors - rootParameters[MainPass_Decals].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[MainPass_Decals].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[MainPass_Decals].DescriptorTable.pDescriptorRanges = decalTextureRanges; - rootParameters[MainPass_Decals].DescriptorTable.NumDescriptorRanges = 1; - - D3D12_STATIC_SAMPLER_DESC staticSamplers[2] = {}; - staticSamplers[0] = DX12::GetStaticSamplerState(SamplerState::Anisotropic, 0); - staticSamplers[1] = DX12::GetStaticSamplerState(SamplerState::ShadowMapPCF, 1); - - D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; - rootSignatureDesc.NumParameters = ArraySize_(rootParameters); - rootSignatureDesc.pParameters = rootParameters; - rootSignatureDesc.NumStaticSamplers = ArraySize_(staticSamplers); - rootSignatureDesc.pStaticSamplers = staticSamplers; - rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; - - DX12::CreateRootSignature(&mainPassRootSignature, rootSignatureDesc); - } - - { - // G-Buffer root signature - D3D12_ROOT_PARAMETER1 rootParameters[2] = {}; - - // VSCBuffer - rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[0].Descriptor.RegisterSpace = 0; - rootParameters[0].Descriptor.ShaderRegister = 0; - - // MatIndexCBuffer - rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[1].Constants.Num32BitValues = 1; - rootParameters[1].Constants.RegisterSpace = 0; - rootParameters[1].Constants.ShaderRegister = 2; - - D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; - rootSignatureDesc.NumParameters = ArraySize_(rootParameters); - rootSignatureDesc.pParameters = rootParameters; - rootSignatureDesc.NumStaticSamplers = 0; - rootSignatureDesc.pStaticSamplers = nullptr; - rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; - - DX12::CreateRootSignature(&gBufferRootSignature, rootSignatureDesc); - } - - { - // Depth only root signature - D3D12_ROOT_PARAMETER1 rootParameters[1] = {}; - - // VSCBuffer - rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; - rootParameters[0].Descriptor.RegisterSpace = 0; - rootParameters[0].Descriptor.ShaderRegister = 0; - - D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; - rootSignatureDesc.NumParameters = ArraySize_(rootParameters); - rootSignatureDesc.pParameters = rootParameters; - rootSignatureDesc.NumStaticSamplers = 0; - rootSignatureDesc.pStaticSamplers = nullptr; - rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; - - DX12::CreateRootSignature(&depthRootSignature, rootSignatureDesc); - } -} - -void MeshRenderer::Shutdown() -{ - DestroyPSOs(); - sunShadowMap.Shutdown(); - spotLightShadowMap.Shutdown(); - materialTextureIndices.Shutdown(); - DX12::Release(mainPassRootSignature); - DX12::Release(gBufferRootSignature); - DX12::Release(depthRootSignature); -} - -void MeshRenderer::CreatePSOs(DXGI_FORMAT mainRTFormat, DXGI_FORMAT depthFormat, const DXGI_FORMAT* gBufferFormats, - uint64 numGBuffers, uint32 numMSAASamples) -{ - if(model == nullptr) - return; - - - ID3D12Device* device = DX12::Device; - - { - // Main pass PSO - D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; - psoDesc.pRootSignature = mainPassRootSignature; - psoDesc.VS = meshVS.ByteCode(); - psoDesc.PS = meshPSForward.ByteCode(); - psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::BackFaceCull); - psoDesc.BlendState = DX12::GetBlendState(BlendState::Disabled); - psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::WritesEnabled); - psoDesc.SampleMask = UINT_MAX; - psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - psoDesc.NumRenderTargets = 2; - psoDesc.RTVFormats[0] = mainRTFormat; - psoDesc.RTVFormats[1] = gBufferFormats[0]; - psoDesc.DSVFormat = depthFormat; - psoDesc.SampleDesc.Count = numMSAASamples; - psoDesc.SampleDesc.Quality = numMSAASamples > 1 ? DX12::StandardMSAAPattern : 0; - psoDesc.InputLayout.NumElements = uint32(Model::NumInputElements()); - psoDesc.InputLayout.pInputElementDescs = Model::InputElements(); - DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&mainPassPSO))); - } - - { - // G-Buffer PSO - D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; - psoDesc.pRootSignature = gBufferRootSignature; - psoDesc.VS = meshVS.ByteCode(); - psoDesc.PS = meshPSGBuffer[AppSettings::ComputeUVGradients ? 1 : 0].ByteCode(); - psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::BackFaceCull); - psoDesc.BlendState = DX12::GetBlendState(BlendState::Disabled); - psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::WritesEnabled); - psoDesc.SampleMask = UINT_MAX; - psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - psoDesc.NumRenderTargets = uint32(numGBuffers); - for(uint64 i = 0; i < numGBuffers; ++i) - psoDesc.RTVFormats[i] = gBufferFormats[i]; - psoDesc.DSVFormat = depthFormat; - psoDesc.SampleDesc.Count = numMSAASamples; - psoDesc.SampleDesc.Quality = numMSAASamples > 1 ? DX12::StandardMSAAPattern : 0; - psoDesc.InputLayout.NumElements = uint32(Model::NumInputElements()); - psoDesc.InputLayout.pInputElementDescs = Model::InputElements(); - DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&gBufferPSO))); - } - - { - // Depth-only PSO - D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; - psoDesc.pRootSignature = depthRootSignature; - psoDesc.VS = meshVS.ByteCode(); - psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::BackFaceCull); - psoDesc.BlendState = DX12::GetBlendState(BlendState::Disabled); - psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::WritesEnabled); - psoDesc.SampleMask = UINT_MAX; - psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - psoDesc.NumRenderTargets = 0; - psoDesc.DSVFormat = depthFormat; - psoDesc.SampleDesc.Count = numMSAASamples; - psoDesc.SampleDesc.Quality = numMSAASamples > 1 ? DX12::StandardMSAAPattern : 0; - psoDesc.InputLayout.NumElements = uint32(Model::NumInputElements()); - psoDesc.InputLayout.pInputElementDescs = Model::InputElements(); - DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&depthPSO))); - - // Spotlight shadow depth PSO - psoDesc.DSVFormat = spotLightShadowMap.DSVFormat; - psoDesc.SampleDesc.Count = spotLightShadowMap.MSAASamples; - psoDesc.SampleDesc.Quality = spotLightShadowMap.MSAASamples > 1 ? DX12::StandardMSAAPattern : 0; - psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::BackFaceCull); - DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&spotLightShadowPSO))); - - // Sun shadow depth PSO - psoDesc.DSVFormat = sunShadowMap.DSVFormat; - psoDesc.SampleDesc.Count = sunShadowMap.MSAASamples; - psoDesc.SampleDesc.Quality = sunShadowMap.MSAASamples > 1 ? DX12::StandardMSAAPattern : 0; - psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::BackFaceCullNoZClip); - DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&sunShadowPSO))); - } -} - -void MeshRenderer::DestroyPSOs() -{ - DX12::DeferredRelease(mainPassPSO); - DX12::DeferredRelease(gBufferPSO); - DX12::DeferredRelease(depthPSO); - DX12::DeferredRelease(spotLightShadowPSO); - DX12::DeferredRelease(sunShadowPSO); -} - -// Renders all meshes in the model, with shadows -void MeshRenderer::RenderMainPass(ID3D12GraphicsCommandList* cmdList, const Camera& camera, const MainPassData& mainPassData) -{ - PIXMarker marker(cmdList, "Mesh Rendering"); - - uint64 numVisible = 0; - if(AppSettings::SortByDepth) - numVisible = CullMeshesAndSort(camera, meshBoundingBoxes, meshZDepths, meshDrawIndices); - else - numVisible = CullMeshes(camera, meshBoundingBoxes, meshDrawIndices); - - cmdList->SetGraphicsRootSignature(mainPassRootSignature); - cmdList->SetPipelineState(mainPassPSO); - cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - - Float4x4 world; - - // Set constant buffers - meshVSConstants.Data.World = world; - meshVSConstants.Data.View = camera.ViewMatrix(); - meshVSConstants.Data.WorldViewProjection = world * camera.ViewProjectionMatrix(); - meshVSConstants.Upload(); - meshVSConstants.SetAsGfxRootParameter(cmdList, MainPass_VSCBuffer); - - meshPSConstants.Data.SunDirectionWS = AppSettings::SunDirection; - meshPSConstants.Data.SunIrradiance = mainPassData.SkyCache->SunIrradiance; - meshPSConstants.Data.CosSunAngularRadius = std::cos(DegToRad(AppSettings::SunSize)); - meshPSConstants.Data.SinSunAngularRadius = std::sin(DegToRad(AppSettings::SunSize)); - meshPSConstants.Data.CameraPosWS = camera.Position(); - - meshPSConstants.Data.CursorDecalPos = mainPassData.CursorDecal.Position; - meshPSConstants.Data.CursorDecalIntensity = mainPassData.CursorDecalIntensity; - meshPSConstants.Data.CursorDecalOrientation = mainPassData.CursorDecal.Orientation; - meshPSConstants.Data.CursorDecalSize = mainPassData.CursorDecal.Size; - meshPSConstants.Data.CursorDecalType = mainPassData.CursorDecal.Type; - meshPSConstants.Data.NumXTiles = uint32(AppSettings::NumXTiles); - meshPSConstants.Data.NumXYTiles = uint32(AppSettings::NumXTiles * AppSettings::NumYTiles); - meshPSConstants.Data.NearClip = camera.NearClip(); - meshPSConstants.Data.FarClip = camera.FarClip(); - - meshPSConstants.Data.SkySH = mainPassData.SkyCache->SH; - meshPSConstants.Upload(); - meshPSConstants.SetAsGfxRootParameter(cmdList, MainPass_PSCBuffer); - - sunShadowConstants.Upload(); - sunShadowConstants.SetAsGfxRootParameter(cmdList, MainPass_ShadowCBuffer); - - cmdList->SetGraphicsRootConstantBufferView(MainPass_LightCBuffer, mainPassData.SpotLightBuffer->InternalBuffer.GPUAddress); - - AppSettings::BindCBufferGfx(cmdList, MainPass_AppSettings); - - D3D12_CPU_DESCRIPTOR_HANDLE psSRVs[] = - { - sunShadowMap.SRV(), - spotLightShadowMap.SRV(), - materialTextureIndices.SRV(), - mainPassData.DecalBuffer->SRV(), - mainPassData.DecalClusterBuffer->SRV(), - mainPassData.SpotLightClusterBuffer->SRV(), - }; - - // We need to get everything into a contiguous shader-visible descriptor table - const uint64 numMaterialTextures = model->MaterialTextures().Count(); - LinearDescriptorHeap& descriptorHeap = DX12::SRVDescriptorHeapGPU[DX12::CurrFrameIdx]; - DescriptorHandle tableStart = descriptorHeap.Allocate(ArraySize_(psSRVs) + numMaterialTextures); - - // First the non-material SRVs - for(uint64 i = 0; i < ArraySize_(psSRVs); ++i) - { - D3D12_CPU_DESCRIPTOR_HANDLE dstDescriptor = tableStart.CPUHandle; - dstDescriptor.ptr += i * DX12::SRVDescriptorSize; - DX12::Device->CopyDescriptorsSimple(1, dstDescriptor, psSRVs[i], D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - } - - // And now the material textures - D3D12_CPU_DESCRIPTOR_HANDLE srcMaterialTextures = model->MaterialTextureDescriptors(); - D3D12_CPU_DESCRIPTOR_HANDLE dstMaterialTextures = tableStart.CPUHandle; - dstMaterialTextures.ptr += ArraySize_(psSRVs) * DX12::SRVDescriptorSize; - DX12::Device->CopyDescriptorsSimple(uint32(numMaterialTextures), dstMaterialTextures, srcMaterialTextures, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - - cmdList->SetGraphicsRootDescriptorTable(MainPass_SRV, tableStart.GPUHandle); - - // Bind the decal textures - D3D12_CPU_DESCRIPTOR_HANDLE decalDescriptors[AppSettings::NumDecalTextures] = { }; - for(uint64 i = 0; i < AppSettings::NumDecalTextures; ++i) - decalDescriptors[i] = mainPassData.DecalTextures[i].SRV.CPUHandle; - - DX12::BindShaderResources(cmdList, MainPass_Decals, AppSettings::NumDecalTextures, decalDescriptors); - - // Bind vertices and indices - D3D12_VERTEX_BUFFER_VIEW vbView = model->VertexBuffer().VBView(); - D3D12_INDEX_BUFFER_VIEW ibView = model->IndexBuffer().IBView(); - cmdList->IASetVertexBuffers(0, 1, &vbView); - cmdList->IASetIndexBuffer(&ibView); - - // Draw all visible meshes - uint32 currMaterial = uint32(-1); - for(uint64 i = 0; i < numVisible; ++i) - { - uint64 meshIdx = meshDrawIndices[i]; - const Mesh& mesh = model->Meshes()[meshIdx]; - - // Draw all parts - for(uint64 partIdx = 0; partIdx < mesh.NumMeshParts(); ++partIdx) - { - const MeshPart& part = mesh.MeshParts()[partIdx]; - if(part.MaterialIdx != currMaterial) - { - cmdList->SetGraphicsRoot32BitConstant(MainPass_MatIndexCBuffer, part.MaterialIdx, 0); - currMaterial = part.MaterialIdx; - } - cmdList->DrawIndexedInstanced(part.IndexCount, 1, mesh.IndexOffset() + part.IndexStart, mesh.VertexOffset(), 0); - } - } -} - -// Renders all meshes to the G-Buffer -void MeshRenderer::RenderGBuffer(ID3D12GraphicsCommandList* cmdList, const Camera& camera) -{ - PIXMarker marker(cmdList, L"Render G-Buffer"); - CPUProfileBlock cpuProfileBlock("Render G-Buffer"); - - uint64 numVisible = 0; - if(AppSettings::SortByDepth) - numVisible = CullMeshesAndSort(camera, meshBoundingBoxes, meshZDepths, meshDrawIndices); - else - numVisible = CullMeshes(camera, meshBoundingBoxes, meshDrawIndices); - - cmdList->SetGraphicsRootSignature(gBufferRootSignature); - cmdList->SetPipelineState(gBufferPSO); - cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - - Float4x4 world; - - // Set constant buffers - meshVSConstants.Data.World = world; - meshVSConstants.Data.View = camera.ViewMatrix(); - meshVSConstants.Data.WorldViewProjection = world * camera.ViewProjectionMatrix(); - meshVSConstants.Data.NearClip = camera.NearClip(); - meshVSConstants.Data.FarClip = camera.FarClip(); - meshVSConstants.Upload(); - meshVSConstants.SetAsGfxRootParameter(cmdList, 0); - - // Bind vertices and indices - D3D12_VERTEX_BUFFER_VIEW vbView = model->VertexBuffer().VBView(); - D3D12_INDEX_BUFFER_VIEW ibView = model->IndexBuffer().IBView(); - cmdList->IASetVertexBuffers(0, 1, &vbView); - cmdList->IASetIndexBuffer(&ibView); - - // Draw all visible meshes - uint32 currMaterial = uint32(-1); - for(uint64 i = 0; i < numVisible; ++i) - { - uint64 meshIdx = meshDrawIndices[i]; - const Mesh& mesh = model->Meshes()[meshIdx]; - - // Draw all parts - for(uint64 partIdx = 0; partIdx < mesh.NumMeshParts(); ++partIdx) - { - const MeshPart& part = mesh.MeshParts()[partIdx]; - if(part.MaterialIdx != currMaterial) - { - cmdList->SetGraphicsRoot32BitConstant(1, part.MaterialIdx, 0); - currMaterial = part.MaterialIdx; - } - cmdList->DrawIndexedInstanced(part.IndexCount, 1, mesh.IndexOffset() + part.IndexStart, mesh.VertexOffset(), 0); - } - } -} - -// Renders all meshes using depth-only rendering -void MeshRenderer::RenderDepth(ID3D12GraphicsCommandList* cmdList, const Camera& camera, ID3D12PipelineState* pso, uint64 numVisible) -{ - cmdList->SetGraphicsRootSignature(depthRootSignature); - cmdList->SetPipelineState(pso); - cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - - Float4x4 world; - - // Set constant buffers - meshVSConstants.Data.World = world; - meshVSConstants.Data.View = camera.ViewMatrix(); - meshVSConstants.Data.WorldViewProjection = world * camera.ViewProjectionMatrix(); - meshVSConstants.Upload(); - meshVSConstants.SetAsGfxRootParameter(cmdList, 0); - - // Bind vertices and indices - D3D12_VERTEX_BUFFER_VIEW vbView = model->VertexBuffer().VBView(); - D3D12_INDEX_BUFFER_VIEW ibView = model->IndexBuffer().IBView(); - cmdList->IASetVertexBuffers(0, 1, &vbView); - cmdList->IASetIndexBuffer(&ibView); - - // Draw all meshes - for(uint64 i = 0; i < numVisible; ++i) - { - uint64 meshIdx = meshDrawIndices[i]; - const Mesh& mesh = model->Meshes()[meshIdx]; - - // Draw the whole mesh - cmdList->DrawIndexedInstanced(mesh.NumIndices(), 1, mesh.IndexOffset(), mesh.VertexOffset(), 0); - } -} - -// Renders all meshes using depth-only rendering for a sun shadow map -void MeshRenderer::RenderDepthPrepass(ID3D12GraphicsCommandList* cmdList, const Camera& camera) -{ - PIXMarker marker(cmdList, L"Depth Prepass"); - CPUProfileBlock cpuProfileBlock("Depth Prepass"); - ProfileBlock profileBlock(cmdList, "Depth Prepass"); - - uint64 numVisible = 0; - if(AppSettings::SortByDepth) - numVisible = CullMeshesAndSort(camera, meshBoundingBoxes, meshZDepths, meshDrawIndices); - else - numVisible = CullMeshes(camera, meshBoundingBoxes, meshDrawIndices); - - RenderDepth(cmdList, camera, depthPSO, numVisible); -} - -// Renders all meshes using depth-only rendering for a sun shadow map -void MeshRenderer::RenderSunShadowDepth(ID3D12GraphicsCommandList* cmdList, const OrthographicCamera& camera) -{ - const uint64 numVisible = CullMeshesOrthographic(camera, true, meshBoundingBoxes, meshDrawIndices); - RenderDepth(cmdList, camera, sunShadowPSO, numVisible); -} - -void MeshRenderer::RenderSpotLightShadowDepth(ID3D12GraphicsCommandList* cmdList, const Camera& camera) -{ - const uint64 numVisible = CullMeshes(camera, meshBoundingBoxes, meshDrawIndices); - RenderDepth(cmdList, camera, spotLightShadowPSO, numVisible); -} - -// Renders meshes using cascaded shadow mapping -void MeshRenderer::RenderSunShadowMap(ID3D12GraphicsCommandList* cmdList, const Camera& camera) -{ - PIXMarker marker(cmdList, L"Sun Shadow Map Rendering"); - CPUProfileBlock cpuProfileBlock("Sun Shadow Map Rendering"); - ProfileBlock profileBlock(cmdList, "Sun Shadow Map Rendering"); - - OrthographicCamera cascadeCameras[NumCascades]; - PrepareShadowCascades(AppSettings::SunDirection, SunShadowMapSize, true, camera, sunShadowConstants.Data, cascadeCameras); - - // Render the meshes to each cascade - for(uint64 cascadeIdx = 0; cascadeIdx < NumCascades; ++cascadeIdx) - { - PIXMarker cascadeMarker(cmdList, MakeString(L"Rendering Shadow Map Cascade %u", cascadeIdx).c_str()); - - // Set the viewport - DX12::SetViewport(cmdList, SunShadowMapSize, SunShadowMapSize); - - // Set the shadow map as the depth target - D3D12_CPU_DESCRIPTOR_HANDLE dsv = sunShadowMap.ArrayDSVs[cascadeIdx].CPUHandle; - cmdList->OMSetRenderTargets(0, nullptr, false, &dsv); - cmdList->ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr); - - // Draw the mesh with depth only, using the new shadow camera - RenderSunShadowDepth(cmdList, cascadeCameras[cascadeIdx]); - } -} - -// Render shadows for all spot lights -void MeshRenderer::RenderSpotLightShadowMap(ID3D12GraphicsCommandList* cmdList, const Camera& camera) -{ - PIXMarker marker(cmdList, L"Spot Light Shadow Map Rendering"); - CPUProfileBlock cpuProfileBlock("Spot Light Shadow Map Rendering"); - ProfileBlock profileBlock(cmdList, "Spot Light Shadow Map Rendering"); - - const Array& spotLights = model->SpotLights(); - const uint64 numSpotLights = Min(spotLights.Size(), AppSettings::MaxLightClamp); - for(uint64 i = 0; i < numSpotLights; ++i) - { - PIXMarker lightMarker(cmdList, MakeString(L"Rendering Spot Light Shadow %u", i).c_str()); - - // Set the viewport - DX12::SetViewport(cmdList, SpotLightShadowMapSize, SpotLightShadowMapSize); - - // Set the shadow map as the depth target - D3D12_CPU_DESCRIPTOR_HANDLE dsv = spotLightShadowMap.ArrayDSVs[i].CPUHandle; - cmdList->OMSetRenderTargets(0, nullptr, false, &dsv); - cmdList->ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr); - - const ModelSpotLight& light = spotLights[i]; - - // Draw the mesh with depth only, using the new shadow camera - PerspectiveCamera shadowCamera; - shadowCamera.Initialize(1.0f, light.AngularAttenuation.y, 0.1f, AppSettings::SpotLightRange); - shadowCamera.SetPosition(light.Position); - shadowCamera.SetOrientation(light.Orientation); - RenderSpotLightShadowDepth(cmdList, shadowCamera); - - Float4x4 shadowMatrix = shadowCamera.ViewProjectionMatrix() * ShadowScaleOffsetMatrix; - spotLightShadowMatrices[i] = Float4x4::Transpose(shadowMatrix); - } +//================================================================================================= +// +// Bindless Deferred Texturing Sample +// by MJP +// http://mynameismjp.wordpress.com/ +// +// All code and content licensed under the MIT license +// +//================================================================================================= + +#include + +#include "MeshRenderer.h" + +#include +#include +#include +#include +#include + +#include "AppSettings.h" + +// Constants +static const uint64 SunShadowMapSize = 2048; +static const uint64 SpotLightShadowMapSize = 1024; + +enum MainPassRootParams +{ + MainPass_StandardDescriptors, + MainPass_VSCBuffer, + MainPass_PSCBuffer, + MainPass_ShadowCBuffer, + MainPass_MatIndexCBuffer, + MainPass_LightCBuffer, + MainPass_SRVIndices, + MainPass_AppSettings, + + NumMainPassRootParams, +}; + +struct MeshVSConstants +{ + Float4Align Float4x4 World; + Float4Align Float4x4 View; + Float4Align Float4x4 WorldViewProjection; + float NearClip = 0.0f; + float FarClip = 0.0f; +}; + +// Used to sort by depth +struct ZSortComparer +{ + const Array& MeshDepths; + ZSortComparer(const Array& meshDepths) : MeshDepths(meshDepths) { } + + bool operator()(uint32 a, uint32 b) + { + return MeshDepths[a] < MeshDepths[b]; + } +}; + +// Frustum culls meshes, and produces a buffer of visible mesh indices +static uint64 CullMeshes(const Camera& camera, const Array& boundingBoxes, Array& drawIndices) +{ + DirectX::BoundingFrustum frustum(camera.ProjectionMatrix().ToSIMD()); + frustum.Transform(frustum, 1.0f, camera.Orientation().ToSIMD(), camera.Position().ToSIMD()); + + uint64 numVisible = 0; + const uint64 numMeshes = boundingBoxes.Size(); + for(uint64 i = 0; i < numMeshes; ++i) + { + if(frustum.Intersects(boundingBoxes[i])) + drawIndices[numVisible++] = uint32(i); + } + + return numVisible; +} + +// Frustum culls meshes, and produces a buffer of visible mesh indices. Also sorts the indices by depth. +static uint64 CullMeshesAndSort(const Camera& camera, const Array& boundingBoxes, + Array& meshDepths, Array& drawIndices) +{ + DirectX::BoundingFrustum frustum(camera.ProjectionMatrix().ToSIMD()); + frustum.Transform(frustum, 1.0f, camera.Orientation().ToSIMD(), camera.Position().ToSIMD()); + + Float4x4 viewMatrix = camera.ViewMatrix(); + + uint64 numVisible = 0; + const uint64 numMeshes = boundingBoxes.Size(); + for(uint64 i = 0; i < numMeshes; ++i) + { + if(frustum.Intersects(boundingBoxes[i])) + { + meshDepths[i] = Float3::Transform(Float3(boundingBoxes[i].Center), viewMatrix).z; + drawIndices[numVisible++] = uint32(i); + } + } + + if(numVisible > 0) + { + ZSortComparer comparer(meshDepths); + std::sort(drawIndices.Data(), drawIndices.Data() + numVisible, comparer); + } + + return numVisible; +} + +// Frustum culls meshes for an orthographic projection, and produces a buffer of visible mesh indices +static uint64 CullMeshesOrthographic(const OrthographicCamera& camera, bool ignoreNearZ, const Array& boundingBoxes, Array& drawIndices) +{ + Float3 mins = Float3(camera.MinX(), camera.MinY(), camera.NearClip()); + Float3 maxes = Float3(camera.MaxX(), camera.MaxY(), camera.FarClip()); + if(ignoreNearZ) + mins.z = -10000.0f; + + Float3 extents = (maxes - mins) / 2.0f; + Float3 center = mins + extents; + center = Float3::Transform(center, camera.Orientation()); + center += camera.Position(); + + DirectX::BoundingOrientedBox obb; + obb.Extents = extents.ToXMFLOAT3(); + obb.Center = center.ToXMFLOAT3(); + obb.Orientation = camera.Orientation().ToXMFLOAT4(); + + uint64 numVisible = 0; + const uint64 numMeshes = boundingBoxes.Size(); + for(uint64 i = 0; i < numMeshes; ++i) + { + if(obb.Intersects(boundingBoxes[i])) + drawIndices[numVisible++] = uint32(i); + } + + return numVisible; +} + +MeshRenderer::MeshRenderer() +{ +} + +void MeshRenderer::LoadShaders() +{ + // Load the mesh shaders + meshDepthVS = CompileFromFile(L"DepthOnly.hlsl", "VS", ShaderType::Vertex); + meshDepthAlphaTestPS = CompileFromFile(L"DepthOnly.hlsl", "PS", ShaderType::Pixel); + + CompileOptions opts; + opts.Add("OutputUVGradients_", 1); + opts.Add("AlphaTest_", 0); + meshVS = CompileFromFile(L"Mesh.hlsl", "VS", ShaderType::Vertex, opts); + meshPSForward = CompileFromFile(L"Mesh.hlsl", "PSForward", ShaderType::Pixel, opts); + meshPSGBuffer[0] = CompileFromFile(L"Mesh.hlsl", "PSGBuffer", ShaderType::Pixel, opts); + + opts.Reset(); + opts.Add("OutputUVGradients_", 0); + opts.Add("AlphaTest_", 0); + meshPSGBuffer[1] = CompileFromFile(L"Mesh.hlsl", "PSGBuffer", ShaderType::Pixel, opts); + + opts.Reset(); + opts.Add("OutputUVGradients_", 1); + opts.Add("AlphaTest_", 1); + meshPSForwardAlphaTest = CompileFromFile(L"Mesh.hlsl", "PSForward", ShaderType::Pixel, opts); + meshPSGBufferAlphaTest[0] = CompileFromFile(L"Mesh.hlsl", "PSGBuffer", ShaderType::Pixel, opts); + + opts.Reset(); + opts.Add("OutputUVGradients_", 0); + opts.Add("AlphaTest_", 1); + meshPSGBufferAlphaTest[1] = CompileFromFile(L"Mesh.hlsl", "PSGBuffer", ShaderType::Pixel, opts); +} + +// Loads resources +void MeshRenderer::Initialize(const Model* model_) +{ + model = model_; + + const uint64 numMeshes = model->Meshes().Size(); + meshBoundingBoxes.Init(numMeshes); + meshDrawIndices.Init(numMeshes, uint32(-1)); + meshZDepths.Init(numMeshes, FloatMax); + for(uint64 i = 0; i < numMeshes; ++i) + { + const Mesh& mesh = model->Meshes()[i]; + DirectX::BoundingBox& boundingBox = meshBoundingBoxes[i]; + Float3 extents = (mesh.AABBMax() - mesh.AABBMin()) / 2.0f; + Float3 center = mesh.AABBMin() + extents; + boundingBox.Center = center.ToXMFLOAT3(); + boundingBox.Extents = extents.ToXMFLOAT3(); + } + + LoadShaders(); + + { + DepthBufferInit dbInit; + dbInit.Width = SunShadowMapSize; + dbInit.Height = SunShadowMapSize; + dbInit.Format = DXGI_FORMAT_D32_FLOAT; + dbInit.MSAASamples = 1; + dbInit.ArraySize = NumCascades; + dbInit.InitialState = D3D12_RESOURCE_STATE_DEPTH_WRITE; + dbInit.Name = L"Sun Shadow Map"; + sunShadowMap.Initialize(dbInit); + } + + { + DepthBufferInit dbInit; + dbInit.Width = SpotLightShadowMapSize; + dbInit.Height = SpotLightShadowMapSize; + dbInit.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; + dbInit.MSAASamples = 1; + dbInit.ArraySize = model->SpotLights().Size(); + dbInit.InitialState = D3D12_RESOURCE_STATE_DEPTH_WRITE; + dbInit.Name = L"Spot Light Shadow Map"; + spotLightShadowMap.Initialize(dbInit); + } + + { + // Create a structured buffer containing texture indices per-material + const Array& materials = model->Materials(); + const uint64 numMaterials = materials.Size(); + Array textureIndices(numMaterials); + materialHasAlphaTest.Init(numMaterials, false); + for(uint64 i = 0; i < numMaterials; ++i) + { + MaterialTextureIndices& matIndices = textureIndices[i]; + const MeshMaterial& material = materials[i]; + + matIndices.Albedo = material.Textures[uint64(MaterialTextures::Albedo)]->SRV; + matIndices.Normal = material.Textures[uint64(MaterialTextures::Normal)]->SRV; + matIndices.Roughness = material.Textures[uint64(MaterialTextures::Roughness)]->SRV; + matIndices.Metallic = material.Textures[uint64(MaterialTextures::Metallic)]->SRV; + + const std::wstring& albedoTexName = material.TextureNames[uint32(MaterialTextures::Albedo)]; + if(albedoTexName == L"Sponza_Thorn_diffuse.png" || albedoTexName == L"VasePlant_diffuse.png") + materialHasAlphaTest[i] = true; + else + materialHasAlphaTest[i] = false; + } + + StructuredBufferInit sbInit; + sbInit.Stride = sizeof(MaterialTextureIndices); + sbInit.NumElements = numMaterials; + sbInit.Dynamic = false; + sbInit.InitData = textureIndices.Data(); + materialTextureIndices.Initialize(sbInit); + materialTextureIndices.Resource()->SetName(L"Material Texture Indices"); + } + + { + // Main pass root signature + D3D12_ROOT_PARAMETER1 rootParameters[NumMainPassRootParams] = {}; + + // "Standard" descriptor table + rootParameters[MainPass_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[MainPass_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[MainPass_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[MainPass_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + // VSCBuffer + rootParameters[MainPass_VSCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[MainPass_VSCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; + rootParameters[MainPass_VSCBuffer].Descriptor.RegisterSpace = 0; + rootParameters[MainPass_VSCBuffer].Descriptor.ShaderRegister = 0; + rootParameters[MainPass_VSCBuffer].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + // PSCBuffer + rootParameters[MainPass_PSCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[MainPass_PSCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[MainPass_PSCBuffer].Descriptor.RegisterSpace = 0; + rootParameters[MainPass_PSCBuffer].Descriptor.ShaderRegister = 0; + rootParameters[MainPass_PSCBuffer].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + // ShadowCBuffer + rootParameters[MainPass_ShadowCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[MainPass_ShadowCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[MainPass_ShadowCBuffer].Descriptor.RegisterSpace = 0; + rootParameters[MainPass_ShadowCBuffer].Descriptor.ShaderRegister = 1; + rootParameters[MainPass_ShadowCBuffer].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + // MatIndexCBuffer + rootParameters[MainPass_MatIndexCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + rootParameters[MainPass_MatIndexCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[MainPass_MatIndexCBuffer].Constants.Num32BitValues = 2; + rootParameters[MainPass_MatIndexCBuffer].Constants.RegisterSpace = 0; + rootParameters[MainPass_MatIndexCBuffer].Constants.ShaderRegister = 2; + + // LightCBuffer + rootParameters[MainPass_LightCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[MainPass_LightCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[MainPass_LightCBuffer].Descriptor.RegisterSpace = 0; + rootParameters[MainPass_LightCBuffer].Descriptor.ShaderRegister = 3; + rootParameters[MainPass_LightCBuffer].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE; + + // SRV descriptor indices + rootParameters[MainPass_SRVIndices].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[MainPass_SRVIndices].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[MainPass_SRVIndices].Descriptor.RegisterSpace = 0; + rootParameters[MainPass_SRVIndices].Descriptor.ShaderRegister = 4; + rootParameters[MainPass_SRVIndices].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + // AppSettings + rootParameters[MainPass_AppSettings].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[MainPass_AppSettings].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[MainPass_AppSettings].Descriptor.RegisterSpace = 0; + rootParameters[MainPass_AppSettings].Descriptor.ShaderRegister = AppSettings::CBufferRegister; + rootParameters[MainPass_AppSettings].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC; + + D3D12_STATIC_SAMPLER_DESC staticSamplers[2] = {}; + staticSamplers[0] = DX12::GetStaticSamplerState(SamplerState::Anisotropic, 0); + staticSamplers[1] = DX12::GetStaticSamplerState(SamplerState::ShadowMapPCF, 1); + + D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; + rootSignatureDesc.NumParameters = ArraySize_(rootParameters); + rootSignatureDesc.pParameters = rootParameters; + rootSignatureDesc.NumStaticSamplers = ArraySize_(staticSamplers); + rootSignatureDesc.pStaticSamplers = staticSamplers; + rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; + + DX12::CreateRootSignature(&mainPassRootSignature, rootSignatureDesc); + } + + { + // G-Buffer root signature + D3D12_ROOT_PARAMETER1 rootParameters[3] = {}; + + // VSCBuffer + rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[0].Descriptor.RegisterSpace = 0; + rootParameters[0].Descriptor.ShaderRegister = 0; + + // MatIndexCBuffer + rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[1].Constants.Num32BitValues = 2; + rootParameters[1].Constants.RegisterSpace = 0; + rootParameters[1].Constants.ShaderRegister = 2; + + // "Standard" descriptor table + rootParameters[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[2].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[2].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + D3D12_STATIC_SAMPLER_DESC staticSamplers[1] = {}; + staticSamplers[0] = DX12::GetStaticSamplerState(SamplerState::Anisotropic, 0); + + D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; + rootSignatureDesc.NumParameters = ArraySize_(rootParameters); + rootSignatureDesc.pParameters = rootParameters; + rootSignatureDesc.NumStaticSamplers = ArraySize_(staticSamplers); + rootSignatureDesc.pStaticSamplers = staticSamplers; + rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; + + DX12::CreateRootSignature(&gBufferRootSignature, rootSignatureDesc); + } + + { + // Depth only root signature + D3D12_ROOT_PARAMETER1 rootParameters[3] = {}; + + // VSCBuffer + rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; + rootParameters[0].Descriptor.RegisterSpace = 0; + rootParameters[0].Descriptor.ShaderRegister = 0; + + // MatIndexCBuffer + rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[1].Constants.Num32BitValues = 2; + rootParameters[1].Constants.RegisterSpace = 0; + rootParameters[1].Constants.ShaderRegister = 1; + + // "Standard" descriptor table + rootParameters[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[2].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[2].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + D3D12_STATIC_SAMPLER_DESC staticSamplers[1] = {}; + staticSamplers[0] = DX12::GetStaticSamplerState(SamplerState::Anisotropic, 0); + + D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; + rootSignatureDesc.NumParameters = ArraySize_(rootParameters); + rootSignatureDesc.pParameters = rootParameters; + rootSignatureDesc.NumStaticSamplers = ArraySize_(staticSamplers); + rootSignatureDesc.pStaticSamplers = staticSamplers; + rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; + + DX12::CreateRootSignature(&depthRootSignature, rootSignatureDesc); + } +} + +void MeshRenderer::Shutdown() +{ + DestroyPSOs(); + sunShadowMap.Shutdown(); + spotLightShadowMap.Shutdown(); + materialTextureIndices.Shutdown(); + DX12::Release(mainPassRootSignature); + DX12::Release(gBufferRootSignature); + DX12::Release(depthRootSignature); +} + +void MeshRenderer::CreatePSOs(DXGI_FORMAT mainRTFormat, DXGI_FORMAT depthFormat, const DXGI_FORMAT* gBufferFormats, + uint64 numGBuffers, uint32 numMSAASamples) +{ + if(model == nullptr) + return; + + + ID3D12Device* device = DX12::Device; + + { + // Main pass PSO + D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; + psoDesc.pRootSignature = mainPassRootSignature; + psoDesc.VS = meshVS.ByteCode(); + psoDesc.PS = meshPSForward.ByteCode(); + psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::BackFaceCull); + psoDesc.BlendState = DX12::GetBlendState(BlendState::Disabled); + psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::WritesEnabled); + psoDesc.SampleMask = UINT_MAX; + psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + psoDesc.NumRenderTargets = 2; + psoDesc.RTVFormats[0] = mainRTFormat; + psoDesc.RTVFormats[1] = gBufferFormats[0]; + psoDesc.DSVFormat = depthFormat; + psoDesc.SampleDesc.Count = numMSAASamples; + psoDesc.SampleDesc.Quality = numMSAASamples > 1 ? DX12::StandardMSAAPattern : 0; + psoDesc.InputLayout.NumElements = uint32(Model::NumInputElements()); + psoDesc.InputLayout.pInputElementDescs = Model::InputElements(); + DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&mainPassPSO))); + + psoDesc.PS = meshPSForwardAlphaTest.ByteCode(); + DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&mainPassAlphaTestPSO))); + + psoDesc.PS = meshPSForward.ByteCode(); + psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::Enabled); + psoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_EQUAL; + DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&mainPassDepthPrepassPSO))); + } + + { + // G-Buffer PSO + D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; + psoDesc.pRootSignature = gBufferRootSignature; + psoDesc.VS = meshVS.ByteCode(); + psoDesc.PS = meshPSGBuffer[AppSettings::ComputeUVGradients ? 1 : 0].ByteCode(); + psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::BackFaceCull); + psoDesc.BlendState = DX12::GetBlendState(BlendState::Disabled); + psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::WritesEnabled); + psoDesc.SampleMask = UINT_MAX; + psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + psoDesc.NumRenderTargets = uint32(numGBuffers); + for(uint64 i = 0; i < numGBuffers; ++i) + psoDesc.RTVFormats[i] = gBufferFormats[i]; + psoDesc.DSVFormat = depthFormat; + psoDesc.SampleDesc.Count = numMSAASamples; + psoDesc.SampleDesc.Quality = numMSAASamples > 1 ? DX12::StandardMSAAPattern : 0; + psoDesc.InputLayout.NumElements = uint32(Model::NumInputElements()); + psoDesc.InputLayout.pInputElementDescs = Model::InputElements(); + DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&gBufferPSO))); + + psoDesc.PS = meshPSGBufferAlphaTest[AppSettings::ComputeUVGradients ? 1 : 0].ByteCode(); + DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&gBufferAlphaTestPSO))); + } + + { + // Depth-only PSO + D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; + psoDesc.pRootSignature = depthRootSignature; + psoDesc.VS = meshDepthVS.ByteCode(); + psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::BackFaceCull); + psoDesc.BlendState = DX12::GetBlendState(BlendState::Disabled); + psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::WritesEnabled); + psoDesc.SampleMask = UINT_MAX; + psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + psoDesc.NumRenderTargets = 0; + psoDesc.DSVFormat = depthFormat; + psoDesc.SampleDesc.Count = numMSAASamples; + psoDesc.SampleDesc.Quality = numMSAASamples > 1 ? DX12::StandardMSAAPattern : 0; + psoDesc.InputLayout.NumElements = uint32(Model::NumInputElements()); + psoDesc.InputLayout.pInputElementDescs = Model::InputElements(); + DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&depthPSO))); + + psoDesc.PS = meshDepthAlphaTestPS.ByteCode(); + DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&depthAlphaTestPSO))); + psoDesc.PS = { }; + + // Spotlight shadow depth PSO + psoDesc.DSVFormat = spotLightShadowMap.DSVFormat; + psoDesc.SampleDesc.Count = spotLightShadowMap.MSAASamples; + psoDesc.SampleDesc.Quality = spotLightShadowMap.MSAASamples > 1 ? DX12::StandardMSAAPattern : 0; + psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::BackFaceCull); + DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&spotLightShadowPSO))); + + psoDesc.PS = meshDepthAlphaTestPS.ByteCode(); + DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&spotLightShadowAlphaTestPSO))); + psoDesc.PS = { }; + + // Sun shadow depth PSO + psoDesc.DSVFormat = sunShadowMap.DSVFormat; + psoDesc.SampleDesc.Count = sunShadowMap.MSAASamples; + psoDesc.SampleDesc.Quality = sunShadowMap.MSAASamples > 1 ? DX12::StandardMSAAPattern : 0; + psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::BackFaceCullNoZClip); + DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&sunShadowPSO))); + + psoDesc.PS = meshDepthAlphaTestPS.ByteCode(); + DXCall(device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&sunShadowAlphaTestPSO))); + psoDesc.PS = { }; + } +} + +void MeshRenderer::DestroyPSOs() +{ + DX12::DeferredRelease(mainPassPSO); + DX12::DeferredRelease(mainPassAlphaTestPSO); + DX12::DeferredRelease(mainPassDepthPrepassPSO); + DX12::DeferredRelease(gBufferPSO); + DX12::DeferredRelease(gBufferAlphaTestPSO); + DX12::DeferredRelease(depthPSO); + DX12::DeferredRelease(depthAlphaTestPSO); + DX12::DeferredRelease(spotLightShadowPSO); + DX12::DeferredRelease(spotLightShadowAlphaTestPSO); + DX12::DeferredRelease(sunShadowPSO); + DX12::DeferredRelease(sunShadowAlphaTestPSO); +} + +// Renders all meshes in the model, with shadows +void MeshRenderer::RenderMainPass(ID3D12GraphicsCommandList* cmdList, const Camera& camera, const MainPassData& mainPassData) +{ + PIXMarker marker(cmdList, "Mesh Rendering"); + + uint64 numVisible = 0; + if(AppSettings::SortByDepth) + numVisible = CullMeshesAndSort(camera, meshBoundingBoxes, meshZDepths, meshDrawIndices); + else + numVisible = CullMeshes(camera, meshBoundingBoxes, meshDrawIndices); + + ID3D12PipelineState* basePSO = AppSettings::DepthPrepass ? mainPassDepthPrepassPSO : mainPassPSO; + ID3D12PipelineState* alphaTestPSO = AppSettings::DepthPrepass ? mainPassDepthPrepassPSO : mainPassAlphaTestPSO; // Alpha test was already done during the depth prepass + + cmdList->SetGraphicsRootSignature(mainPassRootSignature); + cmdList->SetPipelineState(basePSO); + cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + + ID3D12PipelineState* currPSO = basePSO; + + DX12::BindStandardDescriptorTable(cmdList, MainPass_StandardDescriptors, CmdListMode::Graphics); + + Float4x4 world; + + // Set constant buffers + MeshVSConstants vsConstants; + vsConstants.World = world; + vsConstants.View = camera.ViewMatrix(); + vsConstants.WorldViewProjection = world * camera.ViewProjectionMatrix(); + DX12::BindTempConstantBuffer(cmdList, vsConstants, MainPass_VSCBuffer, CmdListMode::Graphics); + + ShadingConstants psConstants; + psConstants.SunDirectionWS = AppSettings::SunDirection; + psConstants.SunIrradiance = mainPassData.SkyCache->SunIrradiance; + psConstants.CosSunAngularRadius = std::cos(DegToRad(AppSettings::SunSize)); + psConstants.SinSunAngularRadius = std::sin(DegToRad(AppSettings::SunSize)); + psConstants.CameraPosWS = camera.Position(); + + psConstants.CursorDecalPos = mainPassData.CursorDecal.Position; + psConstants.CursorDecalIntensity = mainPassData.CursorDecalIntensity; + psConstants.CursorDecalOrientation = mainPassData.CursorDecal.Orientation; + psConstants.CursorDecalSize = mainPassData.CursorDecal.Size; + psConstants.CursorDecalTexIdx = mainPassData.CursorDecal.AlbedoTexIdx; + psConstants.NumXTiles = uint32(AppSettings::NumXTiles); + psConstants.NumXYTiles = uint32(AppSettings::NumXTiles * AppSettings::NumYTiles); + psConstants.NearClip = camera.NearClip(); + psConstants.FarClip = camera.FarClip(); + + psConstants.SkySH = mainPassData.SkyCache->SH; + DX12::BindTempConstantBuffer(cmdList, psConstants, MainPass_PSCBuffer, CmdListMode::Graphics); + + DX12::BindTempConstantBuffer(cmdList, sunShadowConstants, MainPass_ShadowCBuffer, CmdListMode::Graphics); + + mainPassData.SpotLightBuffer->SetAsGfxRootParameter(cmdList, MainPass_LightCBuffer); + + AppSettings::BindCBufferGfx(cmdList, MainPass_AppSettings); + + uint32 psSRVs[] = + { + sunShadowMap.SRV(), + spotLightShadowMap.SRV(), + mainPassData.DecalBuffer->SRV, + mainPassData.DecalClusterBuffer->SRV, + mainPassData.SpotLightClusterBuffer->SRV, + }; + + DX12::BindTempConstantBuffer(cmdList, psSRVs, MainPass_SRVIndices, CmdListMode::Graphics); + + cmdList->SetGraphicsRoot32BitConstant(MainPass_MatIndexCBuffer, materialTextureIndices.SRV, 0); + + // Bind vertices and indices + D3D12_VERTEX_BUFFER_VIEW vbView = model->VertexBuffer().VBView(); + D3D12_INDEX_BUFFER_VIEW ibView = model->IndexBuffer().IBView(); + cmdList->IASetVertexBuffers(0, 1, &vbView); + cmdList->IASetIndexBuffer(&ibView); + + // Draw all visible meshes + uint32 currMaterial = uint32(-1); + for(uint64 i = 0; i < numVisible; ++i) + { + uint64 meshIdx = meshDrawIndices[i]; + const Mesh& mesh = model->Meshes()[meshIdx]; + + // Draw all parts + for(uint64 partIdx = 0; partIdx < mesh.NumMeshParts(); ++partIdx) + { + const MeshPart& part = mesh.MeshParts()[partIdx]; + if(part.MaterialIdx != currMaterial) + { + cmdList->SetGraphicsRoot32BitConstant(MainPass_MatIndexCBuffer, part.MaterialIdx, 1); + currMaterial = part.MaterialIdx; + + ID3D12PipelineState* psoToUse = materialHasAlphaTest[part.MaterialIdx] ? alphaTestPSO : basePSO; + if(psoToUse != currPSO) + { + cmdList->SetPipelineState(psoToUse); + currPSO = psoToUse; + } + } + cmdList->DrawIndexedInstanced(part.IndexCount, 1, mesh.IndexOffset() + part.IndexStart, mesh.VertexOffset(), 0); + } + } +} + +// Renders all meshes to the G-Buffer +void MeshRenderer::RenderGBuffer(ID3D12GraphicsCommandList* cmdList, const Camera& camera) +{ + PIXMarker marker(cmdList, L"Render G-Buffer"); + CPUProfileBlock cpuProfileBlock("Render G-Buffer"); + + uint64 numVisible = 0; + if(AppSettings::SortByDepth) + numVisible = CullMeshesAndSort(camera, meshBoundingBoxes, meshZDepths, meshDrawIndices); + else + numVisible = CullMeshes(camera, meshBoundingBoxes, meshDrawIndices); + + cmdList->SetGraphicsRootSignature(gBufferRootSignature); + cmdList->SetPipelineState(gBufferPSO); + cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + + DX12::BindStandardDescriptorTable(cmdList, 2, CmdListMode::Graphics); + + ID3D12PipelineState* currPSO = gBufferPSO; + + Float4x4 world; + + // Set constant buffers + MeshVSConstants vsConstants; + vsConstants.World = world; + vsConstants.View = camera.ViewMatrix(); + vsConstants.WorldViewProjection = world * camera.ViewProjectionMatrix(); + vsConstants.NearClip = camera.NearClip(); + vsConstants.FarClip = camera.FarClip(); + DX12::BindTempConstantBuffer(cmdList, vsConstants, 0, CmdListMode::Graphics); + + cmdList->SetGraphicsRoot32BitConstant(1, materialTextureIndices.SRV, 0); + + // Bind vertices and indices + D3D12_VERTEX_BUFFER_VIEW vbView = model->VertexBuffer().VBView(); + D3D12_INDEX_BUFFER_VIEW ibView = model->IndexBuffer().IBView(); + cmdList->IASetVertexBuffers(0, 1, &vbView); + cmdList->IASetIndexBuffer(&ibView); + + // Draw all visible meshes + uint32 currMaterial = uint32(-1); + for(uint64 i = 0; i < numVisible; ++i) + { + uint64 meshIdx = meshDrawIndices[i]; + const Mesh& mesh = model->Meshes()[meshIdx]; + + // Draw all parts + for(uint64 partIdx = 0; partIdx < mesh.NumMeshParts(); ++partIdx) + { + const MeshPart& part = mesh.MeshParts()[partIdx]; + if(part.MaterialIdx != currMaterial) + { + cmdList->SetGraphicsRoot32BitConstant(1, part.MaterialIdx, 1); + currMaterial = part.MaterialIdx; + + ID3D12PipelineState* psoToUse = materialHasAlphaTest[part.MaterialIdx] ? gBufferAlphaTestPSO : gBufferPSO; + if(psoToUse != currPSO) + { + cmdList->SetPipelineState(psoToUse); + currPSO = psoToUse; + } + } + cmdList->DrawIndexedInstanced(part.IndexCount, 1, mesh.IndexOffset() + part.IndexStart, mesh.VertexOffset(), 0); + } + } +} + +// Renders all meshes using depth-only rendering +void MeshRenderer::RenderDepth(ID3D12GraphicsCommandList* cmdList, const Camera& camera, ID3D12PipelineState* pso, ID3D12PipelineState* alphaTestPSO, uint64 numVisible) +{ + cmdList->SetGraphicsRootSignature(depthRootSignature); + cmdList->SetPipelineState(pso); + cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + + ID3D12PipelineState* currPSO = gBufferPSO; + + DX12::BindStandardDescriptorTable(cmdList, 2, CmdListMode::Graphics); + + Float4x4 world; + + // Set constant buffers + MeshVSConstants vsConstants; + vsConstants.World = world; + vsConstants.View = camera.ViewMatrix(); + vsConstants.WorldViewProjection = world * camera.ViewProjectionMatrix(); + DX12::BindTempConstantBuffer(cmdList, vsConstants, 0, CmdListMode::Graphics); + + cmdList->SetGraphicsRoot32BitConstant(1, materialTextureIndices.SRV, 0); + + // Bind vertices and indices + D3D12_VERTEX_BUFFER_VIEW vbView = model->VertexBuffer().VBView(); + D3D12_INDEX_BUFFER_VIEW ibView = model->IndexBuffer().IBView(); + cmdList->IASetVertexBuffers(0, 1, &vbView); + cmdList->IASetIndexBuffer(&ibView); + + // Draw all visible meshes + uint32 currMaterial = uint32(-1); + for(uint64 i = 0; i < numVisible; ++i) + { + uint64 meshIdx = meshDrawIndices[i]; + const Mesh& mesh = model->Meshes()[meshIdx]; + + // Draw all parts + for(uint64 partIdx = 0; partIdx < mesh.NumMeshParts(); ++partIdx) + { + const MeshPart& part = mesh.MeshParts()[partIdx]; + if(part.MaterialIdx != currMaterial) + { + cmdList->SetGraphicsRoot32BitConstant(1, part.MaterialIdx, 1); + currMaterial = part.MaterialIdx; + + ID3D12PipelineState* psoToUse = materialHasAlphaTest[part.MaterialIdx] ? alphaTestPSO : pso; + if(psoToUse != currPSO) + { + cmdList->SetPipelineState(psoToUse); + currPSO = psoToUse; + } + } + cmdList->DrawIndexedInstanced(part.IndexCount, 1, mesh.IndexOffset() + part.IndexStart, mesh.VertexOffset(), 0); + } + } +} + +// Renders all meshes using depth-only rendering for a sun shadow map +void MeshRenderer::RenderDepthPrepass(ID3D12GraphicsCommandList* cmdList, const Camera& camera) +{ + PIXMarker marker(cmdList, L"Depth Prepass"); + CPUProfileBlock cpuProfileBlock("Depth Prepass"); + ProfileBlock profileBlock(cmdList, "Depth Prepass"); + + uint64 numVisible = 0; + if(AppSettings::SortByDepth) + numVisible = CullMeshesAndSort(camera, meshBoundingBoxes, meshZDepths, meshDrawIndices); + else + numVisible = CullMeshes(camera, meshBoundingBoxes, meshDrawIndices); + + RenderDepth(cmdList, camera, depthPSO, depthAlphaTestPSO, numVisible); +} + +// Renders all meshes using depth-only rendering for a sun shadow map +void MeshRenderer::RenderSunShadowDepth(ID3D12GraphicsCommandList* cmdList, const OrthographicCamera& camera) +{ + const uint64 numVisible = CullMeshesOrthographic(camera, true, meshBoundingBoxes, meshDrawIndices); + RenderDepth(cmdList, camera, sunShadowPSO, sunShadowAlphaTestPSO, numVisible); +} + +void MeshRenderer::RenderSpotLightShadowDepth(ID3D12GraphicsCommandList* cmdList, const Camera& camera) +{ + const uint64 numVisible = CullMeshes(camera, meshBoundingBoxes, meshDrawIndices); + RenderDepth(cmdList, camera, spotLightShadowPSO, spotLightShadowAlphaTestPSO, numVisible); +} + +// Renders meshes using cascaded shadow mapping +void MeshRenderer::RenderSunShadowMap(ID3D12GraphicsCommandList* cmdList, const Camera& camera) +{ + PIXMarker marker(cmdList, L"Sun Shadow Map Rendering"); + CPUProfileBlock cpuProfileBlock("Sun Shadow Map Rendering"); + ProfileBlock profileBlock(cmdList, "Sun Shadow Map Rendering"); + + OrthographicCamera cascadeCameras[NumCascades]; + ShadowHelper::PrepareCascades(AppSettings::SunDirection, SunShadowMapSize, true, camera, sunShadowConstants.Base, cascadeCameras); + + // Render the meshes to each cascade + for(uint64 cascadeIdx = 0; cascadeIdx < NumCascades; ++cascadeIdx) + { + PIXMarker cascadeMarker(cmdList, MakeString(L"Rendering Shadow Map Cascade %u", cascadeIdx).c_str()); + + // Set the viewport + DX12::SetViewport(cmdList, SunShadowMapSize, SunShadowMapSize); + + // Set the shadow map as the depth target + D3D12_CPU_DESCRIPTOR_HANDLE dsv = sunShadowMap.ArrayDSVs[cascadeIdx]; + cmdList->OMSetRenderTargets(0, nullptr, false, &dsv); + cmdList->ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr); + + // Draw the mesh with depth only, using the new shadow camera + RenderSunShadowDepth(cmdList, cascadeCameras[cascadeIdx]); + } +} + +// Render shadows for all spot lights +void MeshRenderer::RenderSpotLightShadowMap(ID3D12GraphicsCommandList* cmdList, const Camera& camera) +{ + PIXMarker marker(cmdList, L"Spot Light Shadow Map Rendering"); + CPUProfileBlock cpuProfileBlock("Spot Light Shadow Map Rendering"); + ProfileBlock profileBlock(cmdList, "Spot Light Shadow Map Rendering"); + + const Array& spotLights = model->SpotLights(); + const uint64 numSpotLights = Min(spotLights.Size(), AppSettings::MaxLightClamp); + for(uint64 i = 0; i < numSpotLights; ++i) + { + PIXMarker lightMarker(cmdList, MakeString(L"Rendering Spot Light Shadow %u", i).c_str()); + + // Set the viewport + DX12::SetViewport(cmdList, SpotLightShadowMapSize, SpotLightShadowMapSize); + + // Set the shadow map as the depth target + D3D12_CPU_DESCRIPTOR_HANDLE dsv = spotLightShadowMap.ArrayDSVs[i]; + cmdList->OMSetRenderTargets(0, nullptr, false, &dsv); + cmdList->ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr); + + const ModelSpotLight& light = spotLights[i]; + + // Draw the mesh with depth only, using the new shadow camera + PerspectiveCamera shadowCamera; + shadowCamera.Initialize(1.0f, light.AngularAttenuation.y, AppSettings::SpotShadowNearClip, AppSettings::SpotLightRange); + shadowCamera.SetPosition(light.Position); + shadowCamera.SetOrientation(light.Orientation); + RenderSpotLightShadowDepth(cmdList, shadowCamera); + + Float4x4 shadowMatrix = shadowCamera.ViewProjectionMatrix() * ShadowHelper::ShadowScaleOffsetMatrix; + spotLightShadowMatrices[i] = Float4x4::Transpose(shadowMatrix); + } } \ No newline at end of file diff --git a/BindlessDeferred/MeshRenderer.h b/BindlessDeferred/MeshRenderer.h index fe0ca8e..47475fd 100644 --- a/BindlessDeferred/MeshRenderer.h +++ b/BindlessDeferred/MeshRenderer.h @@ -1,141 +1,138 @@ -//================================================================================================= -// -// Bindless Deferred Texturing Sample -// by MJP -// http://mynameismjp.wordpress.com/ -// -// All code and content licensed under the MIT license -// -//================================================================================================= - -#pragma once - -#include - -#include -#include -#include -#include -#include -#include - -#include "AppSettings.h" -#include "SharedTypes.h" - -using namespace SampleFramework12; - -namespace SampleFramework12 -{ - struct SkyCache; -} - -struct MainPassData -{ - const SkyCache* SkyCache = nullptr; - const Texture* DecalTextures = nullptr; - const StructuredBuffer* DecalBuffer = nullptr; - Decal CursorDecal; - float CursorDecalIntensity = 0.0f; - const RawBuffer* DecalClusterBuffer = nullptr; - const StructuredBuffer* SpotLightBuffer = nullptr; - const RawBuffer* SpotLightClusterBuffer = nullptr; -}; - -struct ShadingConstants -{ - Float4Align Float3 SunDirectionWS; - float CosSunAngularRadius; - Float4Align Float3 SunIrradiance; - float SinSunAngularRadius; - Float4Align Float3 CameraPosWS; - - Float4Align Float3 CursorDecalPos; - float CursorDecalIntensity; - Float4Align Quaternion CursorDecalOrientation; - Float4Align Float3 CursorDecalSize; - uint32 CursorDecalType; - uint32 NumXTiles; - uint32 NumXYTiles; - float NearClip; - float FarClip; - - Float4Align ShaderSH9Color SkySH; -}; - -class MeshRenderer -{ - - -public: - - MeshRenderer(); - - void Initialize(const Model* sceneModel); - void Shutdown(); - - void CreatePSOs(DXGI_FORMAT mainRTFormat, DXGI_FORMAT depthFormat, const DXGI_FORMAT* gBufferFormats, - uint64 numGBuffers, uint32 numMSAASamples); - void DestroyPSOs(); - - void RenderMainPass(ID3D12GraphicsCommandList* cmdList, const Camera& camera, const MainPassData& mainPassData); - void RenderGBuffer(ID3D12GraphicsCommandList* cmdList, const Camera& camera); - - void RenderDepthPrepass(ID3D12GraphicsCommandList* cmdList, const Camera& camera); - void RenderSunShadowDepth(ID3D12GraphicsCommandList* cmdList, const OrthographicCamera& camera); - void RenderSpotLightShadowDepth(ID3D12GraphicsCommandList* cmdList, const Camera& camera); - - void RenderSunShadowMap(ID3D12GraphicsCommandList* cmdList, const Camera& camera); - void RenderSpotLightShadowMap(ID3D12GraphicsCommandList* cmdList, const Camera& camera); - - const DepthBuffer& SunShadowMap() const { return sunShadowMap; } - const DepthBuffer& SpotLightShadowMap() const { return spotLightShadowMap; } - const Float4x4* SpotLightShadowMatrices() const { return spotLightShadowMatrices; } - const StructuredBuffer& MaterialTextureIndicesBuffer() const { return materialTextureIndices; } - ConstantBuffer& SunShadowConstantBuffer() { return sunShadowConstants; } - -protected: - - void LoadShaders(); - void RenderDepth(ID3D12GraphicsCommandList* cmdList, const Camera& camera, ID3D12PipelineState* pso, uint64 numVisible); - - const Model* model = nullptr; - - DepthBuffer sunShadowMap; - DepthBuffer spotLightShadowMap; - Float4x4 spotLightShadowMatrices[AppSettings::MaxSpotLights]; - - StructuredBuffer materialTextureIndices; - - CompiledShaderPtr meshVS; - CompiledShaderPtr meshPSForward; - CompiledShaderPtr meshPSGBuffer[2]; - ID3D12PipelineState* mainPassPSO = nullptr; - ID3D12RootSignature* mainPassRootSignature = nullptr; - ID3D12PipelineState* gBufferPSO = nullptr; - ID3D12RootSignature* gBufferRootSignature = nullptr; - - CompiledShaderPtr meshDepthVS; - ID3D12PipelineState* depthPSO = nullptr; - ID3D12PipelineState* sunShadowPSO = nullptr; - ID3D12PipelineState* spotLightShadowPSO = nullptr; - ID3D12RootSignature* depthRootSignature = nullptr; - - Array meshBoundingBoxes; - Array meshDrawIndices; - Array meshZDepths; - - // Constant buffers - struct MeshVSConstants - { - Float4Align Float4x4 World; - Float4Align Float4x4 View; - Float4Align Float4x4 WorldViewProjection; - float NearClip; - float FarClip; - }; - - ConstantBuffer meshVSConstants; - ConstantBuffer meshPSConstants; - ConstantBuffer sunShadowConstants; - +//================================================================================================= +// +// Bindless Deferred Texturing Sample +// by MJP +// http://mynameismjp.wordpress.com/ +// +// All code and content licensed under the MIT license +// +//================================================================================================= + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +#include "AppSettings.h" +#include "SharedTypes.h" + +using namespace SampleFramework12; + +namespace SampleFramework12 +{ + struct SkyCache; +} + +struct MainPassData +{ + const SkyCache* SkyCache = nullptr; + const Texture* DecalTextures = nullptr; + const StructuredBuffer* DecalBuffer = nullptr; + Decal CursorDecal; + float CursorDecalIntensity = 0.0f; + const RawBuffer* DecalClusterBuffer = nullptr; + const ConstantBuffer* SpotLightBuffer = nullptr; + const RawBuffer* SpotLightClusterBuffer = nullptr; +}; + +struct ShadingConstants +{ + Float4Align Float3 SunDirectionWS; + float CosSunAngularRadius = 0.0f; + Float4Align Float3 SunIrradiance; + float SinSunAngularRadius = 0.0f; + Float4Align Float3 CameraPosWS; + + Float4Align Float3 CursorDecalPos; + float CursorDecalIntensity = 0.0f; + Float4Align Quaternion CursorDecalOrientation; + Float4Align Float3 CursorDecalSize; + uint32 CursorDecalTexIdx = uint32(-1); + uint32 NumXTiles = 0; + uint32 NumXYTiles = 0; + float NearClip = 0.0f; + float FarClip = 0.0f; + + Float4Align ShaderSH9Color SkySH; +}; + +class MeshRenderer +{ + + +public: + + MeshRenderer(); + + void Initialize(const Model* sceneModel); + void Shutdown(); + + void CreatePSOs(DXGI_FORMAT mainRTFormat, DXGI_FORMAT depthFormat, const DXGI_FORMAT* gBufferFormats, + uint64 numGBuffers, uint32 numMSAASamples); + void DestroyPSOs(); + + void RenderMainPass(ID3D12GraphicsCommandList* cmdList, const Camera& camera, const MainPassData& mainPassData); + void RenderGBuffer(ID3D12GraphicsCommandList* cmdList, const Camera& camera); + + void RenderDepthPrepass(ID3D12GraphicsCommandList* cmdList, const Camera& camera); + void RenderSunShadowDepth(ID3D12GraphicsCommandList* cmdList, const OrthographicCamera& camera); + void RenderSpotLightShadowDepth(ID3D12GraphicsCommandList* cmdList, const Camera& camera); + + void RenderSunShadowMap(ID3D12GraphicsCommandList* cmdList, const Camera& camera); + void RenderSpotLightShadowMap(ID3D12GraphicsCommandList* cmdList, const Camera& camera); + + const DepthBuffer& SunShadowMap() const { return sunShadowMap; } + const DepthBuffer& SpotLightShadowMap() const { return spotLightShadowMap; } + const Float4x4* SpotLightShadowMatrices() const { return spotLightShadowMatrices; } + const StructuredBuffer& MaterialTextureIndicesBuffer() const { return materialTextureIndices; } + const SunShadowConstantsDepthMap& SunShadowConstantData() { return sunShadowConstants; } + +protected: + + void LoadShaders(); + void RenderDepth(ID3D12GraphicsCommandList* cmdList, const Camera& camera, ID3D12PipelineState* pso, ID3D12PipelineState* alphaTestPSO, uint64 numVisible); + + const Model* model = nullptr; + + DepthBuffer sunShadowMap; + DepthBuffer spotLightShadowMap; + Float4x4 spotLightShadowMatrices[AppSettings::MaxSpotLights]; + + StructuredBuffer materialTextureIndices; + Array materialHasAlphaTest; + + CompiledShaderPtr meshVS; + CompiledShaderPtr meshPSForward; + CompiledShaderPtr meshPSForwardAlphaTest; + CompiledShaderPtr meshPSGBuffer[2]; + CompiledShaderPtr meshPSGBufferAlphaTest[2]; + ID3D12PipelineState* mainPassPSO = nullptr; + ID3D12PipelineState* mainPassAlphaTestPSO = nullptr; + ID3D12PipelineState* mainPassDepthPrepassPSO = nullptr; + ID3D12RootSignature* mainPassRootSignature = nullptr; + ID3D12PipelineState* gBufferPSO = nullptr; + ID3D12PipelineState* gBufferAlphaTestPSO = nullptr; + ID3D12RootSignature* gBufferRootSignature = nullptr; + + CompiledShaderPtr meshDepthVS; + CompiledShaderPtr meshDepthAlphaTestPS; + ID3D12PipelineState* depthPSO = nullptr; + ID3D12PipelineState* depthAlphaTestPSO = nullptr; + ID3D12PipelineState* sunShadowPSO = nullptr; + ID3D12PipelineState* sunShadowAlphaTestPSO = nullptr; + ID3D12PipelineState* spotLightShadowPSO = nullptr; + ID3D12PipelineState* spotLightShadowAlphaTestPSO = nullptr; + ID3D12RootSignature* depthRootSignature = nullptr; + + Array meshBoundingBoxes; + Array meshDrawIndices; + Array meshZDepths; + + SunShadowConstantsDepthMap sunShadowConstants; }; \ No newline at end of file diff --git a/BindlessDeferred/Picking.hlsl b/BindlessDeferred/Picking.hlsl index eaba50b..8d9ae1f 100644 --- a/BindlessDeferred/Picking.hlsl +++ b/BindlessDeferred/Picking.hlsl @@ -8,6 +8,7 @@ // //================================================================================================= +#include #include struct PickingConstants @@ -15,6 +16,8 @@ struct PickingConstants row_major float4x4 InverseViewProjection; uint2 PixelPos; float2 RTSize; + uint TangentMapIdx; + uint DepthMapIdx; }; ConstantBuffer CBuffer : register(b0); @@ -25,25 +28,23 @@ struct PickingData float3 Normal; }; -#if MSAA_ - Texture2DMS TangentMap : register(t0); - Texture2DMS DepthMap : register(t1); -#else - Texture2D TangentMap : register(t0); - Texture2D DepthMap : register(t1); -#endif - RWStructuredBuffer PickingBuffer : register(u0); [numthreads(1, 1, 1)] void PickingCS() { #if MSAA_ - float zw = DepthMap.Load(CBuffer.PixelPos, 0); - Quaternion tangentFrame = UnpackQuaternion(TangentMap.Load(CBuffer.PixelPos, 0)); + Texture2DMS tangentMap = Tex2DMSTable[CBuffer.TangentMapIdx]; + Texture2DMS depthMap = Tex2DMSTable[CBuffer.DepthMapIdx]; + + float zw = depthMap.Load(CBuffer.PixelPos, 0).x; + Quaternion tangentFrame = UnpackQuaternion(tangentMap.Load(CBuffer.PixelPos, 0)); #else - float zw = DepthMap[CBuffer.PixelPos]; - Quaternion tangentFrame = UnpackQuaternion(TangentMap[CBuffer.PixelPos]); + Texture2D tangentMap = Tex2DTable[CBuffer.TangentMapIdx]; + Texture2D depthMap = Tex2DTable[CBuffer.DepthMapIdx]; + + float zw = depthMap[CBuffer.PixelPos].x; + Quaternion tangentFrame = UnpackQuaternion(tangentMap[CBuffer.PixelPos]); #endif float2 uv = (CBuffer.PixelPos + 0.5f) / CBuffer.RTSize; diff --git a/BindlessDeferred/PostProcessing.hlsl b/BindlessDeferred/PostProcessing.hlsl index 2513469..a78282e 100644 --- a/BindlessDeferred/PostProcessing.hlsl +++ b/BindlessDeferred/PostProcessing.hlsl @@ -7,7 +7,7 @@ // All code and content licensed under the MIT license // //================================================================================================= - +#include #include #include #include "AppSettings.hlsl" @@ -26,8 +26,10 @@ float CalcGaussianWeight(int sampleDist, float sigma) // Performs a gaussian blur in one direction float4 Blur(in PSInput input, float2 texScale, float sigma, bool nrmlize) { + Texture2D inputTexture = Tex2DTable[SRVIndices.Idx0]; + float2 inputSize = 0.0f; - InputTexture0.GetDimensions(inputSize.x, inputSize.y); + inputTexture.GetDimensions(inputSize.x, inputSize.y); float4 color = 0; float weightSum = 0.0f; @@ -35,10 +37,13 @@ float4 Blur(in PSInput input, float2 texScale, float sigma, bool nrmlize) { float weight = CalcGaussianWeight(i, sigma); weightSum += weight; + float2 texCoord = input.TexCoord; texCoord += (i / inputSize) * texScale; - float4 sample = InputTexture0.Sample(PointSampler, texCoord); - color += sample * weight; + + float4 texSample = inputTexture.Sample(PointSampler, texCoord); + + color += texSample * weight; } if(nrmlize) @@ -62,9 +67,11 @@ float3 ToneMapFilmicALU(in float3 color) // Initial pass for bloom float4 Bloom(in PSInput input) : SV_Target { - float4 reds = InputTexture0.GatherRed(LinearSampler, input.TexCoord); - float4 greens = InputTexture0.GatherGreen(LinearSampler, input.TexCoord); - float4 blues = InputTexture0.GatherBlue(LinearSampler, input.TexCoord); + Texture2D inputTexture = Tex2DTable[SRVIndices.Idx0]; + + float4 reds = inputTexture.GatherRed(LinearSampler, input.TexCoord); + float4 greens = inputTexture.GatherGreen(LinearSampler, input.TexCoord); + float4 blues = inputTexture.GatherBlue(LinearSampler, input.TexCoord); float3 result = 0.0f; @@ -84,7 +91,8 @@ float4 Bloom(in PSInput input) : SV_Target // Uses hw bilinear filtering for upscaling or downscaling float4 Scale(in PSInput input) : SV_Target { - return InputTexture0.Sample(LinearSampler, input.TexCoord); + Texture2D inputTexture = Tex2DTable[SRVIndices.Idx0]; + return inputTexture.Sample(LinearSampler, input.TexCoord); } // Horizontal gaussian blur @@ -102,10 +110,13 @@ float4 BlurV(in PSInput input) : SV_Target // Applies exposure and tone mapping to the input float4 ToneMap(in PSInput input) : SV_Target0 { - float3 color = InputTexture0.Sample(PointSampler, input.TexCoord).xyz; + Texture2D inputTexture0 = Tex2DTable[SRVIndices.Idx0]; + Texture2D inputTexture1 = Tex2DTable[SRVIndices.Idx1]; + + float3 color = inputTexture0.Sample(PointSampler, input.TexCoord).xyz; - // Add bloomg - color += InputTexture1.Sample(LinearSampler, input.TexCoord).xyz * AppSettings.BloomMagnitude * exp2(AppSettings.BloomExposure); + // Add bloom + color += inputTexture1.Sample(LinearSampler, input.TexCoord).xyz * AppSettings.BloomMagnitude * exp2(AppSettings.BloomExposure); // Apply exposure (accounting for the FP16 scale used for lighting and emissive sources) color *= exp2(AppSettings.Exposure) / FP16Scale; diff --git a/BindlessDeferred/PostProcessor.cpp b/BindlessDeferred/PostProcessor.cpp index de83576..8986a0c 100644 --- a/BindlessDeferred/PostProcessor.cpp +++ b/BindlessDeferred/PostProcessor.cpp @@ -19,11 +19,11 @@ void PostProcessor::Initialize() helper.Initialize(); // Load the shaders - toneMap = CompileFromFile(L"PostProcessing.hlsl", "ToneMap", ShaderType::Pixel, ShaderProfile::SM51); - scale = CompileFromFile(L"PostProcessing.hlsl", "Scale", ShaderType::Pixel, ShaderProfile::SM51); - blurH = CompileFromFile(L"PostProcessing.hlsl", "BlurH", ShaderType::Pixel, ShaderProfile::SM51); - blurV = CompileFromFile(L"PostProcessing.hlsl", "BlurV", ShaderType::Pixel, ShaderProfile::SM51); - bloom = CompileFromFile(L"PostProcessing.hlsl", "Bloom", ShaderType::Pixel, ShaderProfile::SM51); + toneMap = CompileFromFile(L"PostProcessing.hlsl", "ToneMap", ShaderType::Pixel); + scale = CompileFromFile(L"PostProcessing.hlsl", "Scale", ShaderType::Pixel); + blurH = CompileFromFile(L"PostProcessing.hlsl", "BlurH", ShaderType::Pixel); + blurV = CompileFromFile(L"PostProcessing.hlsl", "BlurV", ShaderType::Pixel); + bloom = CompileFromFile(L"PostProcessing.hlsl", "Bloom", ShaderType::Pixel); } void PostProcessor::Shutdown() @@ -47,7 +47,7 @@ void PostProcessor::Render(ID3D12GraphicsCommandList* cmdList, const RenderTextu TempRenderTarget* bloomTarget = Bloom(cmdList, input); // Apply tone mapping - D3D12_CPU_DESCRIPTOR_HANDLE inputs[2] = { input.SRV(), bloomTarget->RT.SRV() }; + uint32 inputs[2] = { input.SRV(), bloomTarget->RT.SRV() }; const RenderTexture* outputs[1] = { &output }; helper.PostProcess(toneMap, "Tone Mapping", inputs, ArraySize_(inputs), outputs, ArraySize_(outputs)); diff --git a/BindlessDeferred/Resolve.hlsl b/BindlessDeferred/Resolve.hlsl index 6715002..0085d6c 100644 --- a/BindlessDeferred/Resolve.hlsl +++ b/BindlessDeferred/Resolve.hlsl @@ -11,24 +11,20 @@ //================================================================================================= // Includes //================================================================================================= +#include #include #include "AppSettings.hlsl" //================================================================================================= // Resources //================================================================================================= -#if Deferred_ - Texture2D InputTexture : register(t0); -#else - Texture2DMS InputTexture : register(t0); -#endif - struct ResolveConstants { uint2 OutputSize; + uint InputTextureIdx; }; -ConstantBuffer ResolveCBuffer : register(b0); +ConstantBuffer CBuffer : register(b0); float Luminance(in float3 clr) { @@ -37,11 +33,17 @@ float Luminance(in float3 clr) float4 ResolvePS(in float4 Position : SV_Position) : SV_Target0 { + #if Deferred_ + Texture2D inputTexture = Tex2DTable[CBuffer.InputTextureIdx]; + #else + Texture2DMS inputTexture = Tex2DMSTable[CBuffer.InputTextureIdx]; + #endif + uint2 pixelPos = uint2(Position.xy); #if Deferred_ - if(InputTexture[pixelPos].w <= 1.0f) - return float4(InputTexture[pixelPos].xyz, 1.0f); + if(inputTexture[pixelPos].w <= 1.0f) + return float4(inputTexture[pixelPos].xyz, 1.0f); #endif const float ExposureFilterOffset = 2.0f; @@ -57,19 +59,19 @@ float4 ResolvePS(in float4 Position : SV_Position) : SV_Target0 // For the deferred path, the output target is 2x the width/height since // D3D doesn't support writing to MSAA textures trough a UAV uint2 offset = uint2(subSampleIdx % 2, subSampleIdx / 2); - offset *= ResolveCBuffer.OutputSize; - float3 sample = InputTexture[pixelPos + offset].xyz; + offset *= CBuffer.OutputSize; + float3 texSample = inputTexture[pixelPos + offset].xyz; #else - float3 sample = InputTexture.Load(pixelPos, subSampleIdx).xyz; + float3 texSample = inputTexture.Load(pixelPos, subSampleIdx).xyz; #endif - sample = max(sample, 0.0f); + texSample = max(texSample, 0.0f); - float sampleLum = Luminance(sample); + float sampleLum = Luminance(texSample); sampleLum *= exposure; float weight = 1.0f / (1.0f + sampleLum); - sum += sample * weight; + sum += texSample * weight; totalWeight += weight; } diff --git a/BindlessDeferred/Shading.hlsl b/BindlessDeferred/Shading.hlsl index dde5df3..9fd4391 100644 --- a/BindlessDeferred/Shading.hlsl +++ b/BindlessDeferred/Shading.hlsl @@ -1,337 +1,363 @@ -//================================================================================================= -// -// Bindless Deferred Texturing Sample -// by MJP -// http://mynameismjp.wordpress.com/ -// -// All code and content licensed under the MIT license -// -//================================================================================================= - -// Options -#ifndef UseImplicitShadowDerivatives_ - #define UseImplicitShadowDerivatives_ 0 -#endif - -#define UseReceiverPlaneBias_ 1 - -// Set this to zero to make compile times quicker -#define UseGatherPCF_ 1 - -#include -#include -#include -#include -#include "AppSettings.hlsl" -#include "SharedTypes.h" - -struct ShadingConstants -{ - float3 SunDirectionWS; - float CosSunAngularRadius; - float3 SunIrradiance; - float SinSunAngularRadius; - float3 CameraPosWS; - - float3 CursorDecalPos; - float CursorDecalIntensity; - Quaternion CursorDecalOrientation; - float3 CursorDecalSize; - uint CursorDecalType; - uint NumXTiles; - uint NumXYTiles; - float NearClip; - float FarClip; - - SH9Color SkySH; -}; - -struct LightConstants -{ - SpotLight Lights[MaxSpotLights]; - float4x4 ShadowMatrices[MaxSpotLights]; -}; - -struct ShadingInput -{ - uint2 PositionSS; - float3 PositionWS; - float3 PositionWS_DX; - float3 PositionWS_DY; - float DepthVS; - float3x3 TangentFrame; - - float4 AlbedoMap; - float2 NormalMap; - float RoughnessMap; - float MetallicMap; - - StructuredBuffer DecalBuffer; - ByteAddressBuffer DecalClusterBuffer; - ByteAddressBuffer SpotLightClusterBuffer; - - SamplerState AnisoSampler; - - ShadingConstants ShadingCBuffer; - ShadowConstants ShadowCBuffer; - LightConstants LightCBuffer; -}; - -Texture2D DecalTextures[NumDecalTextures] : register(t0, space1); - -//------------------------------------------------------------------------------------------------- -// Calculates the lighting result for an analytical light source -//------------------------------------------------------------------------------------------------- -float3 CalcLighting(in float3 normal, in float3 lightDir, in float3 peakIrradiance, - in float3 diffuseAlbedo, in float3 specularAlbedo, in float roughness, - in float3 positionWS, in float3 cameraPosWS) -{ - float3 lighting = diffuseAlbedo * (1.0f / 3.14159f); - - float3 view = normalize(cameraPosWS - positionWS); - const float nDotL = saturate(dot(normal, lightDir)); - if(nDotL > 0.0f) - { - const float nDotV = saturate(dot(normal, view)); - float3 h = normalize(view + lightDir); - - float3 fresnel = Fresnel(specularAlbedo, h, lightDir); - - float specular = GGX_Specular(roughness, normal, h, view, lightDir); - lighting += specular * fresnel; - } - - return lighting * nDotL * peakIrradiance; -} - -//------------------------------------------------------------------------------------------------- -// Calculates the full shading result for a single pixel. Note: some of the input textures -// are passed directly to this function instead of through the ShadingInput struct in order to -// work around incorrect behavior from the shader compiler -//------------------------------------------------------------------------------------------------- -float3 ShadePixel(in ShadingInput input, in Texture2DArray SunShadowMap, - in Texture2DArray SpotLightShadowMap, in SamplerComparisonState ShadowSampler) -{ - float3 vtxNormalWS = input.TangentFrame._m20_m21_m22; - float3 normalWS = vtxNormalWS; - float3 positionWS = input.PositionWS; - - const ShadingConstants CBuffer = input.ShadingCBuffer; - const ShadowConstants ShadowCBuffer = input.ShadowCBuffer; - - float3 viewWS = normalize(CBuffer.CameraPosWS - positionWS); - - if(AppSettings.EnableNormalMaps) - { - // Sample the normal map, and convert the normal to world space - float3 normalTS; - normalTS.xy = input.NormalMap * 2.0f - 1.0f; - normalTS.z = sqrt(1.0f - saturate(normalTS.x * normalTS.x + normalTS.y * normalTS.y)); - normalWS = normalize(mul(normalTS, input.TangentFrame)); - } - - float4 albedoMap = 1.0f; - if(AppSettings.EnableAlbedoMaps) - albedoMap = input.AlbedoMap; - - float metallic = saturate(input.MetallicMap); - float3 diffuseAlbedo = lerp(albedoMap.xyz, 0.0f, metallic); - float3 specularAlbedo = lerp(0.03f, albedoMap.xyz, metallic) * (AppSettings.EnableSpecular ? 1.0f : 0.0f); - - float roughnessMap = input.RoughnessMap; - float roughness = roughnessMap * roughnessMap; - - float depthVS = input.DepthVS; - - // Compute shared cluster lookup data - uint2 pixelPos = uint2(input.PositionSS); - float zRange = CBuffer.FarClip - CBuffer.NearClip; - float normalizedZ = saturate((depthVS - CBuffer.NearClip) / zRange); - uint zTile = normalizedZ * NumZTiles; - - uint3 tileCoords = uint3(pixelPos / ClusterTileSize, zTile); - uint clusterIdx = (tileCoords.z * CBuffer.NumXYTiles) + (tileCoords.y * CBuffer.NumXTiles) + tileCoords.x; - - float3 positionNeighborX = input.PositionWS + input.PositionWS_DX; - float3 positionNeighborY = input.PositionWS + input.PositionWS_DY; - - // Apply decals - uint numDecals = 0; - if(AppSettings.RenderDecals) - { - uint clusterOffset = clusterIdx * DecalElementsPerCluster; - - // Loop over the number of 4-byte elements needed for each cluster - [unroll] - for(uint elemIdx = 0; elemIdx < DecalElementsPerCluster; ++elemIdx) - { - // Loop until we've processed every raised bit - uint clusterElemMask = input.DecalClusterBuffer.Load((clusterOffset + elemIdx) * 4); - while(clusterElemMask) - { - uint bitIdx = firstbitlow(clusterElemMask); - clusterElemMask &= ~(1 << bitIdx); - uint decalIdx = bitIdx + (elemIdx * 32); - Decal decal = input.DecalBuffer[decalIdx]; - float3x3 decalRot = QuatTo3x3(decal.Orientation); - - // Apply the decal projection, and branch over the decal if we're outside of its bounding box - float3 localPos = positionWS - decal.Position; - localPos = mul(localPos, transpose(decalRot)); - float3 decalUVW = localPos / decal.Size; - decalUVW.y *= -1; - if(decalUVW.x >= -1.0f && decalUVW.x <= 1.0f && - decalUVW.y >= -1.0f && decalUVW.y <= 1.0f && - decalUVW.z >= -1.0f && decalUVW.z <= 1.0f) - { - // Pull out the right textures from the descriptor array - float2 decalUV = saturate(decalUVW.xy * 0.5f + 0.5f); - const uint baseTextureIdx = decal.Type * NumTexturesPerDecal; - Texture2D decalAlbedoMap = DecalTextures[NonUniformResourceIndex(baseTextureIdx + 0)]; - Texture2D decalNormalMap = DecalTextures[NonUniformResourceIndex(baseTextureIdx + 1)]; - - // Calculate decal UV gradients - float3 decalPosNeighborX = positionNeighborX - decal.Position; - decalPosNeighborX = mul(decalPosNeighborX, transpose(decalRot)); - decalPosNeighborX = decalPosNeighborX / decal.Size; - decalPosNeighborX.y *= -1; - float2 uvDX = saturate(decalPosNeighborX.xy * 0.5f + 0.5f) - decalUV; - - float3 decalPosNeighborY = positionNeighborY - decal.Position; - decalPosNeighborY = mul(decalPosNeighborY, transpose(decalRot)); - decalPosNeighborY = decalPosNeighborY / decal.Size; - decalPosNeighborY.y *= -1; - float2 uvDY = saturate(decalPosNeighborY.xy * 0.5f + 0.5f) - decalUV; - - float4 decalAlbedo = decalAlbedoMap.SampleGrad(input.AnisoSampler, decalUV, uvDX, uvDY); - float3 decalNormalTS = decalNormalMap.SampleGrad(input.AnisoSampler, decalUV, uvDX, uvDY).xyz; - - float decalBlend = decalAlbedo.w; - // decalBlend *= saturate(dot(decalRot._m20_m21_m22, -vtxNormalWS) * 100.0f - 99.0f); - - decalNormalTS = decalNormalTS * 2.0f - 1.0f; - decalNormalTS.z *= -1.0f; - float3 decalNormalWS = mul(decalNormalTS, decalRot); - - // Blend the decal properties with the material properties - diffuseAlbedo = lerp(diffuseAlbedo, decalAlbedo.xyz, decalBlend); - normalWS = lerp(normalWS, decalNormalWS, decalBlend); - } - - ++numDecals; - } - } - } - - // Apply the decal "cursor", indicating where a new decal will be placed - if(CBuffer.CursorDecalIntensity > 0.0f && CBuffer.CursorDecalType != uint(-1)) - { - float3x3 decalRot = QuatTo3x3(CBuffer.CursorDecalOrientation); - float3 localPos = positionWS - CBuffer.CursorDecalPos; - localPos = mul(localPos, transpose(decalRot)); - float3 decalUVW = localPos / CBuffer.CursorDecalSize; - decalUVW.y *= -1.0f; - if(decalUVW.x >= -1.0f && decalUVW.x <= 1.0f && - decalUVW.y >= -1.0f && decalUVW.y <= 1.0f && - decalUVW.z >= -1.0f && decalUVW.z <= 1.0f) - { - float2 decalUV = saturate(decalUVW.xy * 0.5f + 0.5f); - Texture2D decalAlbedoMap = DecalTextures[CBuffer.CursorDecalType * NumTexturesPerDecal + 0]; - float4 decalAlbedo = decalAlbedoMap.SampleLevel(input.AnisoSampler, decalUV, 0.0f); - - float decalBlend = decalAlbedo.w; - // decalBlend *= saturate(dot(decalRot._m20_m21_m22, -vtxNormalWS) * 100.0f - 99.0f); - - diffuseAlbedo = lerp(diffuseAlbedo, decalAlbedo.xyz, decalBlend * CBuffer.CursorDecalIntensity); - } - } - - // Add in the primary directional light - float3 output = 0.0f; - - if(AppSettings.EnableSun) - { - #if UseImplicitShadowDerivatives_ - // Forward path - float sunShadowVisibility = SunShadowVisibility(positionWS, depthVS, SunShadowMap, ShadowSampler, ShadowCBuffer); - #else - // Deferred path - float sunShadowVisibility = SunShadowVisibility(positionWS, positionNeighborX, positionNeighborY, - depthVS, SunShadowMap, ShadowSampler, ShadowCBuffer); - #endif - - float3 sunDirection = CBuffer.SunDirectionWS; - if(AppSettings.SunAreaLightApproximation) - { - float3 D = CBuffer.SunDirectionWS; - float3 R = reflect(-viewWS, normalWS); - float r = CBuffer.SinSunAngularRadius; - float d = CBuffer.CosSunAngularRadius; - float3 DDotR = dot(D, R); - float3 S = R - DDotR * D; - sunDirection = DDotR < d ? normalize(d * D + normalize(S) * r) : R; - } - output += CalcLighting(normalWS, sunDirection, CBuffer.SunIrradiance, diffuseAlbedo, specularAlbedo, - roughness, positionWS, CBuffer.CameraPosWS) * sunShadowVisibility; - } - - // Apply the spot lights - uint numLights = 0; - if(AppSettings.RenderLights) - { - uint clusterOffset = clusterIdx * SpotLightElementsPerCluster; - - // Loop over the number of 4-byte elements needed for each cluster - [unroll] - for(uint elemIdx = 0; elemIdx < SpotLightElementsPerCluster; ++elemIdx) - { - // Loop until we've processed every raised bit - uint clusterElemMask = input.SpotLightClusterBuffer.Load((clusterOffset + elemIdx) * 4); - while(clusterElemMask) - { - uint bitIdx = firstbitlow(clusterElemMask); - clusterElemMask &= ~(1 << bitIdx); - uint spotLightIdx = bitIdx + (elemIdx * 32); - SpotLight spotLight = input.LightCBuffer.Lights[spotLightIdx]; - - float3 surfaceToLight = spotLight.Position - positionWS; - float distanceToLight = length(surfaceToLight); - surfaceToLight /= distanceToLight; - float angleFactor = saturate(dot(surfaceToLight, spotLight.Direction)); - float angularAttenuation = smoothstep(spotLight.AngularAttenuationY, spotLight.AngularAttenuationX, angleFactor); - - if(angularAttenuation > 0.0f) - { - float d = distanceToLight / spotLight.Range; - float falloff = saturate(1.0f - (d * d * d * d)); - falloff = (falloff * falloff) / (distanceToLight * distanceToLight + 1.0f); - float3 intensity = spotLight.Intensity * angularAttenuation * falloff; - - // We have to use explicit gradients for spotlight shadows, since the looping/branching is non-uniform - float spotLightVisibility = SpotLightShadowVisibility(positionWS, positionNeighborX, positionNeighborY, - input.LightCBuffer.ShadowMatrices[spotLightIdx], - spotLightIdx, SpotLightShadowMap, ShadowSampler); - - output += CalcLighting(normalWS, surfaceToLight, intensity, diffuseAlbedo, specularAlbedo, - roughness, positionWS, CBuffer.CameraPosWS) * spotLightVisibility; - } - - ++numLights; - } - } - } - - float3 ambient = EvalSH9Irradiance(normalWS, CBuffer.SkySH) * InvPi; - ambient *= 0.1f; // Darken the ambient since we don't have any sky occlusion - output += ambient * diffuseAlbedo; - - if(AppSettings.ShowLightCounts) - output = lerp(output, float3(2.5f, 0.0f, 0.0f), numLights / 10.0f); - - if(AppSettings.ShowDecalCounts) - output = lerp(output, float3(0.0f, 2.5f, 0.0f), numDecals / 10.0f); - - output = clamp(output, 0.0f, FP16Max); - - return output; +//================================================================================================= +// +// Bindless Deferred Texturing Sample +// by MJP +// http://mynameismjp.wordpress.com/ +// +// All code and content licensed under the MIT license +// +//================================================================================================= + +// Options +#ifndef UseImplicitShadowDerivatives_ + #define UseImplicitShadowDerivatives_ 0 +#endif + +#define ShadowMapMode_ 0 +#define UseGatherPCF_ 0 + +#include +#include +#include +#include +#include +#include "AppSettings.hlsl" +#include "SharedTypes.h" + +struct ShadingConstants +{ + float3 SunDirectionWS; + float CosSunAngularRadius; + float3 SunIrradiance; + float SinSunAngularRadius; + float3 CameraPosWS; + + float3 CursorDecalPos; + float CursorDecalIntensity; + Quaternion CursorDecalOrientation; + float3 CursorDecalSize; + uint CursorDecalTexIdx; + uint NumXTiles; + uint NumXYTiles; + float NearClip; + float FarClip; + + SH9Color SkySH; +}; + +struct LightConstants +{ + SpotLight Lights[MaxSpotLights]; + float4x4 ShadowMatrices[MaxSpotLights]; +}; + +struct ShadingInput +{ + uint2 PositionSS; + float3 PositionWS; + float3 PositionWS_DX; + float3 PositionWS_DY; + float DepthVS; + float3x3 TangentFrame; + + float4 AlbedoMap; + float2 NormalMap; + float RoughnessMap; + float MetallicMap; + + StructuredBuffer DecalBuffer; + ByteAddressBuffer DecalClusterBuffer; + ByteAddressBuffer SpotLightClusterBuffer; + + SamplerState AnisoSampler; + + ShadingConstants ShadingCBuffer; + SunShadowConstants ShadowCBuffer; + LightConstants LightCBuffer; +}; + +//------------------------------------------------------------------------------------------------- +// Calculates the lighting result for an analytical light source +//------------------------------------------------------------------------------------------------- +float3 CalcLighting(in float3 normal, in float3 lightDir, in float3 peakIrradiance, + in float3 diffuseAlbedo, in float3 specularAlbedo, in float roughness, + in float3 positionWS, in float3 cameraPosWS) +{ + float3 lighting = diffuseAlbedo * (1.0f / 3.14159f); + + float3 view = normalize(cameraPosWS - positionWS); + const float nDotL = saturate(dot(normal, lightDir)); + if(nDotL > 0.0f) + { + const float nDotV = saturate(dot(normal, view)); + float3 h = normalize(view + lightDir); + + float3 fresnel = Fresnel(specularAlbedo, h, lightDir); + + float specular = GGX_Specular(roughness, normal, h, view, lightDir); + lighting += specular * fresnel; + } + + return lighting * nDotL * peakIrradiance; +} + +//------------------------------------------------------------------------------------------------- +// Calculates the full shading result for a single pixel. Note: some of the input textures +// are passed directly to this function instead of through the ShadingInput struct in order to +// work around incorrect behavior from the shader compiler +//------------------------------------------------------------------------------------------------- +float3 ShadePixel(in ShadingInput input, in Texture2DArray sunShadowMap, + in Texture2DArray spotLightShadowMap, in SamplerComparisonState shadowSampler) +{ + float3 vtxNormalWS = input.TangentFrame._m20_m21_m22; + float3 normalWS = vtxNormalWS; + float3 positionWS = input.PositionWS; + + const ShadingConstants CBuffer = input.ShadingCBuffer; + const SunShadowConstants ShadowCBuffer = input.ShadowCBuffer; + + float3 viewWS = normalize(CBuffer.CameraPosWS - positionWS); + + if(AppSettings.EnableNormalMaps) + { + // Sample the normal map, and convert the normal to world space + float3 normalTS; + normalTS.xy = input.NormalMap * 2.0f - 1.0f; + normalTS.z = sqrt(1.0f - saturate(normalTS.x * normalTS.x + normalTS.y * normalTS.y)); + normalWS = normalize(mul(normalTS, input.TangentFrame)); + } + + float4 albedoMap = 1.0f; + if(AppSettings.EnableAlbedoMaps) + albedoMap = input.AlbedoMap; + + float metallic = saturate(input.MetallicMap); + float3 diffuseAlbedo = lerp(albedoMap.xyz, 0.0f, metallic); + float3 specularAlbedo = lerp(0.03f, albedoMap.xyz, metallic) * (AppSettings.EnableSpecular ? 1.0f : 0.0f); + + float roughnessMap = input.RoughnessMap; + float roughness = roughnessMap * roughnessMap; + + float depthVS = input.DepthVS; + + // Compute shared cluster lookup data + uint2 pixelPos = uint2(input.PositionSS); + float zRange = CBuffer.FarClip - CBuffer.NearClip; + float normalizedZ = saturate((depthVS - CBuffer.NearClip) / zRange); + uint zTile = normalizedZ * NumZTiles; + + uint3 tileCoords = uint3(pixelPos / ClusterTileSize, zTile); + uint clusterIdx = (tileCoords.z * CBuffer.NumXYTiles) + (tileCoords.y * CBuffer.NumXTiles) + tileCoords.x; + + float3 positionNeighborX = input.PositionWS + input.PositionWS_DX; + float3 positionNeighborY = input.PositionWS + input.PositionWS_DY; + + // Apply decals + uint numDecals = 0; + if(AppSettings.RenderDecals) + { + uint clusterOffset = clusterIdx * DecalElementsPerCluster; + + // Loop over the number of 4-byte elements needed for each cluster + [unroll] + for(uint elemIdx = 0; elemIdx < DecalElementsPerCluster; ++elemIdx) + { + // Loop until we've processed every raised bit + uint clusterElemMask = input.DecalClusterBuffer.Load((clusterOffset + elemIdx) * 4); + + #if DXC_ + // OR the cluster bitmask across the entire wave to force it to be wave-uniform. + // This can allow AMD hardware to use scalar loads and registers for data from the decal buffer. + clusterElemMask = WaveActiveBitOr(clusterElemMask); + clusterElemMask = WaveReadLaneFirst(clusterElemMask); + #endif + + while(clusterElemMask) + { + uint bitIdx = firstbitlow(clusterElemMask); + clusterElemMask &= ~(1u << bitIdx); + uint decalIdx = bitIdx + (elemIdx * 32); + Decal decal = input.DecalBuffer[decalIdx]; + float3x3 decalRot = QuatTo3x3(decal.Orientation); + + // Apply the decal projection, and branch over the decal if we're outside of its bounding box + float3 localPos = positionWS - decal.Position; + localPos = mul(localPos, transpose(decalRot)); + float3 decalUVW = localPos / decal.Size; + decalUVW.y *= -1; + if(decalUVW.x >= -1.0f && decalUVW.x <= 1.0f && + decalUVW.y >= -1.0f && decalUVW.y <= 1.0f && + decalUVW.z >= -1.0f && decalUVW.z <= 1.0f) + { + // Pull out the right textures from the descriptor array + float2 decalUV = saturate(decalUVW.xy * 0.5f + 0.5f); + Texture2D decalAlbedoMap = Tex2DTable[NonUniformResourceIndex(decal.AlbedoTexIdx)]; + Texture2D decalNormalMap = Tex2DTable[NonUniformResourceIndex(decal.NormalTexIdx)]; + + // Calculate decal UV gradients + float3 decalPosNeighborX = positionNeighborX - decal.Position; + decalPosNeighborX = mul(decalPosNeighborX, transpose(decalRot)); + decalPosNeighborX = decalPosNeighborX / decal.Size; + decalPosNeighborX.y *= -1; + float2 uvDX = saturate(decalPosNeighborX.xy * 0.5f + 0.5f) - decalUV; + + float3 decalPosNeighborY = positionNeighborY - decal.Position; + decalPosNeighborY = mul(decalPosNeighborY, transpose(decalRot)); + decalPosNeighborY = decalPosNeighborY / decal.Size; + decalPosNeighborY.y *= -1; + float2 uvDY = saturate(decalPosNeighborY.xy * 0.5f + 0.5f) - decalUV; + + float4 decalAlbedo = decalAlbedoMap.SampleGrad(input.AnisoSampler, decalUV, uvDX, uvDY); + float3 decalNormalTS = decalNormalMap.SampleGrad(input.AnisoSampler, decalUV, uvDX, uvDY).xyz; + + float decalBlend = decalAlbedo.w; + // decalBlend *= saturate(dot(decalRot._m20_m21_m22, -vtxNormalWS) * 100.0f - 99.0f); + + decalNormalTS = decalNormalTS * 2.0f - 1.0f; + decalNormalTS.z *= -1.0f; + float3 decalNormalWS = mul(decalNormalTS, decalRot); + + // Blend the decal properties with the material properties + diffuseAlbedo = lerp(diffuseAlbedo, decalAlbedo.xyz, decalBlend); + normalWS = lerp(normalWS, decalNormalWS, decalBlend); + } + + ++numDecals; + } + } + } + + // Apply the decal "cursor", indicating where a new decal will be placed + if(CBuffer.CursorDecalIntensity > 0.0f && CBuffer.CursorDecalTexIdx != uint(-1)) + { + float3x3 decalRot = QuatTo3x3(CBuffer.CursorDecalOrientation); + float3 localPos = positionWS - CBuffer.CursorDecalPos; + localPos = mul(localPos, transpose(decalRot)); + float3 decalUVW = localPos / CBuffer.CursorDecalSize; + decalUVW.y *= -1.0f; + if(decalUVW.x >= -1.0f && decalUVW.x <= 1.0f && + decalUVW.y >= -1.0f && decalUVW.y <= 1.0f && + decalUVW.z >= -1.0f && decalUVW.z <= 1.0f) + { + float2 decalUV = saturate(decalUVW.xy * 0.5f + 0.5f); + Texture2D decalAlbedoMap = Tex2DTable[CBuffer.CursorDecalTexIdx]; + float4 decalAlbedo = decalAlbedoMap.SampleLevel(input.AnisoSampler, decalUV, 0.0f); + + float decalBlend = decalAlbedo.w; + // decalBlend *= saturate(dot(decalRot._m20_m21_m22, -vtxNormalWS) * 100.0f - 99.0f); + + diffuseAlbedo = lerp(diffuseAlbedo, decalAlbedo.xyz, decalBlend * CBuffer.CursorDecalIntensity); + } + } + + // Add in the primary directional light + float3 output = 0.0f; + + if(AppSettings.EnableSun) + { + float3 sunDirection = CBuffer.SunDirectionWS; + + float2 shadowMapSize; + float numSlices; + sunShadowMap.GetDimensions(shadowMapSize.x, shadowMapSize.y, numSlices); + + const float3 shadowPosOffset = GetShadowPosOffset(saturate(dot(vtxNormalWS, sunDirection)), vtxNormalWS, shadowMapSize.x); + + #if UseImplicitShadowDerivatives_ + // Forward path + float sunShadowVisibility = SunShadowVisibility(positionWS, depthVS, shadowPosOffset, 0.0f, sunShadowMap, shadowSampler, ShadowCBuffer); + #else + // Deferred path + float sunShadowVisibility = SunShadowVisibility(positionWS, positionNeighborX, positionNeighborY, + depthVS, shadowPosOffset, 0.0f, sunShadowMap, shadowSampler, ShadowCBuffer); + #endif + + if(AppSettings.SunAreaLightApproximation) + { + float3 D = CBuffer.SunDirectionWS; + float3 R = reflect(-viewWS, normalWS); + float r = CBuffer.SinSunAngularRadius; + float d = CBuffer.CosSunAngularRadius; + float3 DDotR = dot(D, R); + float3 S = R - DDotR * D; + sunDirection = DDotR < d ? normalize(d * D + normalize(S) * r) : R; + } + output += CalcLighting(normalWS, sunDirection, CBuffer.SunIrradiance, diffuseAlbedo, specularAlbedo, + roughness, positionWS, CBuffer.CameraPosWS) * sunShadowVisibility; + } + + // Apply the spot lights + uint numLights = 0; + if(AppSettings.RenderLights) + { + float2 shadowMapSize; + float numSlices; + spotLightShadowMap.GetDimensions(shadowMapSize.x, shadowMapSize.y, numSlices); + + uint clusterOffset = clusterIdx * SpotLightElementsPerCluster; + + // Loop over the number of 4-byte elements needed for each cluster + [unroll] + for(uint elemIdx = 0; elemIdx < SpotLightElementsPerCluster; ++elemIdx) + { + // Loop until we've processed every raised bit + uint clusterElemMask = input.SpotLightClusterBuffer.Load((clusterOffset + elemIdx) * 4); + + #if DXC_ + // OR the cluster bitmask across the entire wave to force it to be wave-uniform. + // This can allow AMD hardware to use scalar loads and registers for data from the light buffer. + clusterElemMask = WaveActiveBitOr(clusterElemMask); + clusterElemMask = WaveReadLaneFirst(clusterElemMask); + #endif + + while(clusterElemMask) + { + uint bitIdx = firstbitlow(clusterElemMask); + clusterElemMask &= ~(1u << bitIdx); + uint spotLightIdx = bitIdx + (elemIdx * 32); + SpotLight spotLight = input.LightCBuffer.Lights[spotLightIdx]; + + float3 surfaceToLight = spotLight.Position - positionWS; + float distanceToLight = length(surfaceToLight); + surfaceToLight /= distanceToLight; + float angleFactor = saturate(dot(surfaceToLight, spotLight.Direction)); + float angularAttenuation = smoothstep(spotLight.AngularAttenuationY, spotLight.AngularAttenuationX, angleFactor); + + if(angularAttenuation > 0.0f) + { + float d = distanceToLight / spotLight.Range; + float falloff = saturate(1.0f - (d * d * d * d)); + falloff = (falloff * falloff) / (distanceToLight * distanceToLight + 1.0f); + float3 intensity = spotLight.Intensity * angularAttenuation * falloff; + + const float3 shadowPosOffset = GetShadowPosOffset(saturate(dot(vtxNormalWS, surfaceToLight)), vtxNormalWS, shadowMapSize.x); + + // We have to use explicit gradients for spotlight shadows, since the looping/branching is non-uniform + float spotLightVisibility = SpotLightShadowVisibility(positionWS, positionNeighborX, positionNeighborY, + input.LightCBuffer.ShadowMatrices[spotLightIdx], + spotLightIdx, shadowPosOffset, spotLightShadowMap, shadowSampler, + float2(SpotShadowNearClip, spotLight.Range), ShadowCBuffer.Extra); + + output += CalcLighting(normalWS, surfaceToLight, intensity, diffuseAlbedo, specularAlbedo, + roughness, positionWS, CBuffer.CameraPosWS) * spotLightVisibility; + } + + ++numLights; + } + } + } + + float3 ambient = EvalSH9Irradiance(normalWS, CBuffer.SkySH) * InvPi; + ambient *= 0.1f; // Darken the ambient since we don't have any sky occlusion + output += ambient * diffuseAlbedo; + + if(AppSettings.ShowLightCounts) + output = lerp(output, float3(2.5f, 0.0f, 0.0f), numLights / 10.0f); + + if(AppSettings.ShowDecalCounts) + output = lerp(output, float3(0.0f, 2.5f, 0.0f), numDecals / 10.0f); + + output = clamp(output, 0.0f, FP16Max); + + return output; } \ No newline at end of file diff --git a/BindlessDeferred/SharedTypes.h b/BindlessDeferred/SharedTypes.h index fc77242..9cf1055 100644 --- a/BindlessDeferred/SharedTypes.h +++ b/BindlessDeferred/SharedTypes.h @@ -40,10 +40,11 @@ struct Decal Quaternion Orientation; float3 Size; float3 Position; - uint Type; + uint AlbedoTexIdx; + uint NormalTexIdx; #if _WINDOWS - Decal() : Type(uint32(-1)) { } + Decal() : AlbedoTexIdx(uint32(-1)), NormalTexIdx(uint32(-1)) { } #endif }; diff --git a/BindlessDeferred/project.sublime-project b/BindlessDeferred/project.sublime-project index d393afa..fd44a6d 100644 --- a/BindlessDeferred/project.sublime-project +++ b/BindlessDeferred/project.sublime-project @@ -1,29 +1,29 @@ -{ - "folders": - [ - { - "path": "/", - "name": "Local", - "file_exclude_patterns": ["*.sln", "*.vcxproj", "*.filters", "*.rc", "*.props", "*.user", "*.opensdf", "*.ico"], - "folder_exclude_patterns": ["Debug", "Release", "bin", "obj", "Properties", "ipch", "x64", "ShaderCache"] - }, - { - "path": "../SampleFramework12/v1.00/", - "name": "SampleFramework", - "file_exclude_patterns": ["*.sln", "*.vcxproj", "*.filters", "*.rc", "*.props", "*.user", "*.opensdf", "*.ico"], - "folder_exclude_patterns": ["Debug", "Release", "bin", "obj", "Properties", "ipch", "x64", ".vs"] - }, - { - "path": "../Externals/", - "name": "Externals", - "file_exclude_patterns": ["*.sln", "*.vcxproj", "*.filters", "*.rc", "*.props", "*.user", "*.opensdf", "*.ico", "*.lib", "*.dll", "*.pdb"], - "folder_exclude_patterns": ["Debug", "Release", "x64", "obj", "Properties", "ipch", "x64", "Lib*", "bin"] - } - ], - "settings": - { - "tab_size": 4, - "translate_tabs_to_spaces": true, - "trim_trailing_white_space_on_save": true - } +{ + "folders": + [ + { + "path": ".", + "name": "Local", + "file_exclude_patterns": ["*.sln", "*.vcxproj", "*.filters", "*.rc", "*.props", "*.user", "*.opensdf", "*.ico"], + "folder_exclude_patterns": ["Debug", "Release", "bin", "obj", "Properties", "ipch", "x64", "ShaderCache", ".vs"] + }, + { + "path": "../SampleFramework12/v1.01/", + "name": "SampleFramework", + "file_exclude_patterns": ["*.sln", "*.vcxproj", "*.filters", "*.rc", "*.props", "*.user", "*.opensdf", "*.ico"], + "folder_exclude_patterns": ["Debug", "Release", "bin", "obj", "Properties", "ipch", "x64", ".vs"] + }, + { + "path": "../Externals/", + "name": "Externals", + "file_exclude_patterns": ["*.sln", "*.vcxproj", "*.filters", "*.rc", "*.props", "*.user", "*.opensdf", "*.ico", "*.lib", "*.dll", "*.pdb"], + "folder_exclude_patterns": ["Debug", "Release", "x64", "obj", "Properties", "ipch", "x64", "Lib*", "bin"] + } + ], + "settings": + { + "tab_size": 4, + "translate_tabs_to_spaces": true, + "trim_trailing_white_space_on_save": true + } } \ No newline at end of file diff --git a/Externals/.gitignore b/Externals/.gitignore index f764d74..9becf9b 100644 --- a/Externals/.gitignore +++ b/Externals/.gitignore @@ -20,3 +20,5 @@ sun/source/x64/ *.opensdf *.suo *.vcproj.user + +DXCompiler/bin/dxcompiler.pdb diff --git a/Externals/DXCompiler/Bin/dxcompiler.dll b/Externals/DXCompiler/Bin/dxcompiler.dll new file mode 100644 index 0000000..52ed352 Binary files /dev/null and b/Externals/DXCompiler/Bin/dxcompiler.dll differ diff --git a/Externals/DXCompiler/Bin/dxil.dll b/Externals/DXCompiler/Bin/dxil.dll new file mode 100644 index 0000000..0fa690a Binary files /dev/null and b/Externals/DXCompiler/Bin/dxil.dll differ diff --git a/Externals/DXCompiler/Include/d3d12shader.h b/Externals/DXCompiler/Include/d3d12shader.h new file mode 100644 index 0000000..4101676 --- /dev/null +++ b/Externals/DXCompiler/Include/d3d12shader.h @@ -0,0 +1,474 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +// +// File: D3D12Shader.h +// Content: D3D12 Shader Types and APIs +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef __D3D12SHADER_H__ +#define __D3D12SHADER_H__ + +#include "d3dcommon.h" + +typedef enum D3D12_SHADER_VERSION_TYPE +{ + D3D12_SHVER_PIXEL_SHADER = 0, + D3D12_SHVER_VERTEX_SHADER = 1, + D3D12_SHVER_GEOMETRY_SHADER = 2, + + // D3D11 Shaders + D3D12_SHVER_HULL_SHADER = 3, + D3D12_SHVER_DOMAIN_SHADER = 4, + D3D12_SHVER_COMPUTE_SHADER = 5, + + D3D12_SHVER_RESERVED0 = 0xFFF0, +} D3D12_SHADER_VERSION_TYPE; + +#define D3D12_SHVER_GET_TYPE(_Version) \ + (((_Version) >> 16) & 0xffff) +#define D3D12_SHVER_GET_MAJOR(_Version) \ + (((_Version) >> 4) & 0xf) +#define D3D12_SHVER_GET_MINOR(_Version) \ + (((_Version) >> 0) & 0xf) + +// Slot ID for library function return +#define D3D_RETURN_PARAMETER_INDEX (-1) + +typedef D3D_RESOURCE_RETURN_TYPE D3D12_RESOURCE_RETURN_TYPE; + +typedef D3D_CBUFFER_TYPE D3D12_CBUFFER_TYPE; + + +typedef struct _D3D12_SIGNATURE_PARAMETER_DESC +{ + LPCSTR SemanticName; // Name of the semantic + UINT SemanticIndex; // Index of the semantic + UINT Register; // Number of member variables + D3D_NAME SystemValueType;// A predefined system value, or D3D_NAME_UNDEFINED if not applicable + D3D_REGISTER_COMPONENT_TYPE ComponentType; // Scalar type (e.g. uint, float, etc.) + BYTE Mask; // Mask to indicate which components of the register + // are used (combination of D3D10_COMPONENT_MASK values) + BYTE ReadWriteMask; // Mask to indicate whether a given component is + // never written (if this is an output signature) or + // always read (if this is an input signature). + // (combination of D3D_MASK_* values) + UINT Stream; // Stream index + D3D_MIN_PRECISION MinPrecision; // Minimum desired interpolation precision +} D3D12_SIGNATURE_PARAMETER_DESC; + +typedef struct _D3D12_SHADER_BUFFER_DESC +{ + LPCSTR Name; // Name of the constant buffer + D3D_CBUFFER_TYPE Type; // Indicates type of buffer content + UINT Variables; // Number of member variables + UINT Size; // Size of CB (in bytes) + UINT uFlags; // Buffer description flags +} D3D12_SHADER_BUFFER_DESC; + +typedef struct _D3D12_SHADER_VARIABLE_DESC +{ + LPCSTR Name; // Name of the variable + UINT StartOffset; // Offset in constant buffer's backing store + UINT Size; // Size of variable (in bytes) + UINT uFlags; // Variable flags + LPVOID DefaultValue; // Raw pointer to default value + UINT StartTexture; // First texture index (or -1 if no textures used) + UINT TextureSize; // Number of texture slots possibly used. + UINT StartSampler; // First sampler index (or -1 if no textures used) + UINT SamplerSize; // Number of sampler slots possibly used. +} D3D12_SHADER_VARIABLE_DESC; + +typedef struct _D3D12_SHADER_TYPE_DESC +{ + D3D_SHADER_VARIABLE_CLASS Class; // Variable class (e.g. object, matrix, etc.) + D3D_SHADER_VARIABLE_TYPE Type; // Variable type (e.g. float, sampler, etc.) + UINT Rows; // Number of rows (for matrices, 1 for other numeric, 0 if not applicable) + UINT Columns; // Number of columns (for vectors & matrices, 1 for other numeric, 0 if not applicable) + UINT Elements; // Number of elements (0 if not an array) + UINT Members; // Number of members (0 if not a structure) + UINT Offset; // Offset from the start of structure (0 if not a structure member) + LPCSTR Name; // Name of type, can be NULL +} D3D12_SHADER_TYPE_DESC; + +typedef D3D_TESSELLATOR_DOMAIN D3D12_TESSELLATOR_DOMAIN; + +typedef D3D_TESSELLATOR_PARTITIONING D3D12_TESSELLATOR_PARTITIONING; + +typedef D3D_TESSELLATOR_OUTPUT_PRIMITIVE D3D12_TESSELLATOR_OUTPUT_PRIMITIVE; + +typedef struct _D3D12_SHADER_DESC +{ + UINT Version; // Shader version + LPCSTR Creator; // Creator string + UINT Flags; // Shader compilation/parse flags + + UINT ConstantBuffers; // Number of constant buffers + UINT BoundResources; // Number of bound resources + UINT InputParameters; // Number of parameters in the input signature + UINT OutputParameters; // Number of parameters in the output signature + + UINT InstructionCount; // Number of emitted instructions + UINT TempRegisterCount; // Number of temporary registers used + UINT TempArrayCount; // Number of temporary arrays used + UINT DefCount; // Number of constant defines + UINT DclCount; // Number of declarations (input + output) + UINT TextureNormalInstructions; // Number of non-categorized texture instructions + UINT TextureLoadInstructions; // Number of texture load instructions + UINT TextureCompInstructions; // Number of texture comparison instructions + UINT TextureBiasInstructions; // Number of texture bias instructions + UINT TextureGradientInstructions; // Number of texture gradient instructions + UINT FloatInstructionCount; // Number of floating point arithmetic instructions used + UINT IntInstructionCount; // Number of signed integer arithmetic instructions used + UINT UintInstructionCount; // Number of unsigned integer arithmetic instructions used + UINT StaticFlowControlCount; // Number of static flow control instructions used + UINT DynamicFlowControlCount; // Number of dynamic flow control instructions used + UINT MacroInstructionCount; // Number of macro instructions used + UINT ArrayInstructionCount; // Number of array instructions used + UINT CutInstructionCount; // Number of cut instructions used + UINT EmitInstructionCount; // Number of emit instructions used + D3D_PRIMITIVE_TOPOLOGY GSOutputTopology; // Geometry shader output topology + UINT GSMaxOutputVertexCount; // Geometry shader maximum output vertex count + D3D_PRIMITIVE InputPrimitive; // GS/HS input primitive + UINT PatchConstantParameters; // Number of parameters in the patch constant signature + UINT cGSInstanceCount; // Number of Geometry shader instances + UINT cControlPoints; // Number of control points in the HS->DS stage + D3D_TESSELLATOR_OUTPUT_PRIMITIVE HSOutputPrimitive; // Primitive output by the tessellator + D3D_TESSELLATOR_PARTITIONING HSPartitioning; // Partitioning mode of the tessellator + D3D_TESSELLATOR_DOMAIN TessellatorDomain; // Domain of the tessellator (quad, tri, isoline) + // instruction counts + UINT cBarrierInstructions; // Number of barrier instructions in a compute shader + UINT cInterlockedInstructions; // Number of interlocked instructions + UINT cTextureStoreInstructions; // Number of texture writes +} D3D12_SHADER_DESC; + +typedef struct _D3D12_SHADER_INPUT_BIND_DESC +{ + LPCSTR Name; // Name of the resource + D3D_SHADER_INPUT_TYPE Type; // Type of resource (e.g. texture, cbuffer, etc.) + UINT BindPoint; // Starting bind point + UINT BindCount; // Number of contiguous bind points (for arrays) + + UINT uFlags; // Input binding flags + D3D_RESOURCE_RETURN_TYPE ReturnType; // Return type (if texture) + D3D_SRV_DIMENSION Dimension; // Dimension (if texture) + UINT NumSamples; // Number of samples (0 if not MS texture) + UINT Space; // Register space + UINT uID; // Range ID in the bytecode +} D3D12_SHADER_INPUT_BIND_DESC; + +#define D3D_SHADER_REQUIRES_DOUBLES 0x00000001 +#define D3D_SHADER_REQUIRES_EARLY_DEPTH_STENCIL 0x00000002 +#define D3D_SHADER_REQUIRES_UAVS_AT_EVERY_STAGE 0x00000004 +#define D3D_SHADER_REQUIRES_64_UAVS 0x00000008 +#define D3D_SHADER_REQUIRES_MINIMUM_PRECISION 0x00000010 +#define D3D_SHADER_REQUIRES_11_1_DOUBLE_EXTENSIONS 0x00000020 +#define D3D_SHADER_REQUIRES_11_1_SHADER_EXTENSIONS 0x00000040 +#define D3D_SHADER_REQUIRES_LEVEL_9_COMPARISON_FILTERING 0x00000080 +#define D3D_SHADER_REQUIRES_TILED_RESOURCES 0x00000100 +#define D3D_SHADER_REQUIRES_STENCIL_REF 0x00000200 +#define D3D_SHADER_REQUIRES_INNER_COVERAGE 0x00000400 +#define D3D_SHADER_REQUIRES_TYPED_UAV_LOAD_ADDITIONAL_FORMATS 0x00000800 +#define D3D_SHADER_REQUIRES_ROVS 0x00001000 +#define D3D_SHADER_REQUIRES_VIEWPORT_AND_RT_ARRAY_INDEX_FROM_ANY_SHADER_FEEDING_RASTERIZER 0x00002000 +#define D3D_SHADER_REQUIRES_WAVE_OPS 0x00004000 +#define D3D_SHADER_REQUIRES_INT64_OPS 0x00008000 +#define D3D_SHADER_REQUIRES_VIEW_ID 0x00010000 +#define D3D_SHADER_REQUIRES_BARYCENTRICS 0x00020000 +#define D3D_SHADER_REQUIRES_NATIVE_16BIT_OPS 0x00040000 +#define D3D_SHADER_REQUIRES_SHADING_RATE 0x00080000 +#define D3D_SHADER_REQUIRES_RAYTRACING_TIER_1_1 0x00100000 +#define D3D_SHADER_REQUIRES_SAMPLER_FEEDBACK 0x00200000 +#define D3D_SHADER_REQUIRES_ATOMIC_INT64_ON_TYPED_RESOURCE 0x00400000 +#define D3D_SHADER_REQUIRES_ATOMIC_INT64_ON_GROUP_SHARED 0x00800000 +#define D3D_SHADER_REQUIRES_DERIVATIVES_IN_MESH_AND_AMPLIFICATION_SHADERS 0x01000000 +#define D3D_SHADER_REQUIRES_RESOURCE_DESCRIPTOR_HEAP_INDEXING 0x02000000 +#define D3D_SHADER_REQUIRES_SAMPLER_DESCRIPTOR_HEAP_INDEXING 0x04000000 +#define D3D_SHADER_REQUIRES_WAVE_MMA 0x08000000 +#define D3D_SHADER_REQUIRES_ATOMIC_INT64_ON_DESCRIPTOR_HEAP_RESOURCE 0x10000000 + +typedef struct _D3D12_LIBRARY_DESC +{ + LPCSTR Creator; // The name of the originator of the library. + UINT Flags; // Compilation flags. + UINT FunctionCount; // Number of functions exported from the library. +} D3D12_LIBRARY_DESC; + +typedef struct _D3D12_FUNCTION_DESC +{ + UINT Version; // Shader version + LPCSTR Creator; // Creator string + UINT Flags; // Shader compilation/parse flags + + UINT ConstantBuffers; // Number of constant buffers + UINT BoundResources; // Number of bound resources + + UINT InstructionCount; // Number of emitted instructions + UINT TempRegisterCount; // Number of temporary registers used + UINT TempArrayCount; // Number of temporary arrays used + UINT DefCount; // Number of constant defines + UINT DclCount; // Number of declarations (input + output) + UINT TextureNormalInstructions; // Number of non-categorized texture instructions + UINT TextureLoadInstructions; // Number of texture load instructions + UINT TextureCompInstructions; // Number of texture comparison instructions + UINT TextureBiasInstructions; // Number of texture bias instructions + UINT TextureGradientInstructions; // Number of texture gradient instructions + UINT FloatInstructionCount; // Number of floating point arithmetic instructions used + UINT IntInstructionCount; // Number of signed integer arithmetic instructions used + UINT UintInstructionCount; // Number of unsigned integer arithmetic instructions used + UINT StaticFlowControlCount; // Number of static flow control instructions used + UINT DynamicFlowControlCount; // Number of dynamic flow control instructions used + UINT MacroInstructionCount; // Number of macro instructions used + UINT ArrayInstructionCount; // Number of array instructions used + UINT MovInstructionCount; // Number of mov instructions used + UINT MovcInstructionCount; // Number of movc instructions used + UINT ConversionInstructionCount; // Number of type conversion instructions used + UINT BitwiseInstructionCount; // Number of bitwise arithmetic instructions used + D3D_FEATURE_LEVEL MinFeatureLevel; // Min target of the function byte code + UINT64 RequiredFeatureFlags; // Required feature flags + + LPCSTR Name; // Function name + INT FunctionParameterCount; // Number of logical parameters in the function signature (not including return) + BOOL HasReturn; // TRUE, if function returns a value, false - it is a subroutine + BOOL Has10Level9VertexShader; // TRUE, if there is a 10L9 VS blob + BOOL Has10Level9PixelShader; // TRUE, if there is a 10L9 PS blob +} D3D12_FUNCTION_DESC; + +typedef struct _D3D12_PARAMETER_DESC +{ + LPCSTR Name; // Parameter name. + LPCSTR SemanticName; // Parameter semantic name (+index). + D3D_SHADER_VARIABLE_TYPE Type; // Element type. + D3D_SHADER_VARIABLE_CLASS Class; // Scalar/Vector/Matrix. + UINT Rows; // Rows are for matrix parameters. + UINT Columns; // Components or Columns in matrix. + D3D_INTERPOLATION_MODE InterpolationMode; // Interpolation mode. + D3D_PARAMETER_FLAGS Flags; // Parameter modifiers. + + UINT FirstInRegister; // The first input register for this parameter. + UINT FirstInComponent; // The first input register component for this parameter. + UINT FirstOutRegister; // The first output register for this parameter. + UINT FirstOutComponent; // The first output register component for this parameter. +} D3D12_PARAMETER_DESC; + + +////////////////////////////////////////////////////////////////////////////// +// Interfaces //////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3D12ShaderReflectionType ID3D12ShaderReflectionType; +typedef interface ID3D12ShaderReflectionType *LPD3D12SHADERREFLECTIONTYPE; + +typedef interface ID3D12ShaderReflectionVariable ID3D12ShaderReflectionVariable; +typedef interface ID3D12ShaderReflectionVariable *LPD3D12SHADERREFLECTIONVARIABLE; + +typedef interface ID3D12ShaderReflectionConstantBuffer ID3D12ShaderReflectionConstantBuffer; +typedef interface ID3D12ShaderReflectionConstantBuffer *LPD3D12SHADERREFLECTIONCONSTANTBUFFER; + +typedef interface ID3D12ShaderReflection ID3D12ShaderReflection; +typedef interface ID3D12ShaderReflection *LPD3D12SHADERREFLECTION; + +typedef interface ID3D12LibraryReflection ID3D12LibraryReflection; +typedef interface ID3D12LibraryReflection *LPD3D12LIBRARYREFLECTION; + +typedef interface ID3D12FunctionReflection ID3D12FunctionReflection; +typedef interface ID3D12FunctionReflection *LPD3D12FUNCTIONREFLECTION; + +typedef interface ID3D12FunctionParameterReflection ID3D12FunctionParameterReflection; +typedef interface ID3D12FunctionParameterReflection *LPD3D12FUNCTIONPARAMETERREFLECTION; + + +// {E913C351-783D-48CA-A1D1-4F306284AD56} +interface DECLSPEC_UUID("E913C351-783D-48CA-A1D1-4F306284AD56") ID3D12ShaderReflectionType; +DEFINE_GUID(IID_ID3D12ShaderReflectionType, +0xe913c351, 0x783d, 0x48ca, 0xa1, 0xd1, 0x4f, 0x30, 0x62, 0x84, 0xad, 0x56); + +#undef INTERFACE +#define INTERFACE ID3D12ShaderReflectionType + +DECLARE_INTERFACE(ID3D12ShaderReflectionType) +{ + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_SHADER_TYPE_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByIndex)(THIS_ _In_ UINT Index) PURE; + STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByName)(THIS_ _In_ LPCSTR Name) PURE; + STDMETHOD_(LPCSTR, GetMemberTypeName)(THIS_ _In_ UINT Index) PURE; + + STDMETHOD(IsEqual)(THIS_ _In_ ID3D12ShaderReflectionType* pType) PURE; + STDMETHOD_(ID3D12ShaderReflectionType*, GetSubType)(THIS) PURE; + STDMETHOD_(ID3D12ShaderReflectionType*, GetBaseClass)(THIS) PURE; + STDMETHOD_(UINT, GetNumInterfaces)(THIS) PURE; + STDMETHOD_(ID3D12ShaderReflectionType*, GetInterfaceByIndex)(THIS_ _In_ UINT uIndex) PURE; + STDMETHOD(IsOfType)(THIS_ _In_ ID3D12ShaderReflectionType* pType) PURE; + STDMETHOD(ImplementsInterface)(THIS_ _In_ ID3D12ShaderReflectionType* pBase) PURE; +}; + +// {8337A8A6-A216-444A-B2F4-314733A73AEA} +interface DECLSPEC_UUID("8337A8A6-A216-444A-B2F4-314733A73AEA") ID3D12ShaderReflectionVariable; +DEFINE_GUID(IID_ID3D12ShaderReflectionVariable, +0x8337a8a6, 0xa216, 0x444a, 0xb2, 0xf4, 0x31, 0x47, 0x33, 0xa7, 0x3a, 0xea); + +#undef INTERFACE +#define INTERFACE ID3D12ShaderReflectionVariable + +DECLARE_INTERFACE(ID3D12ShaderReflectionVariable) +{ + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_SHADER_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionType*, GetType)(THIS) PURE; + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer*, GetBuffer)(THIS) PURE; + + STDMETHOD_(UINT, GetInterfaceSlot)(THIS_ _In_ UINT uArrayIndex) PURE; +}; + +// {C59598B4-48B3-4869-B9B1-B1618B14A8B7} +interface DECLSPEC_UUID("C59598B4-48B3-4869-B9B1-B1618B14A8B7") ID3D12ShaderReflectionConstantBuffer; +DEFINE_GUID(IID_ID3D12ShaderReflectionConstantBuffer, +0xc59598b4, 0x48b3, 0x4869, 0xb9, 0xb1, 0xb1, 0x61, 0x8b, 0x14, 0xa8, 0xb7); + +#undef INTERFACE +#define INTERFACE ID3D12ShaderReflectionConstantBuffer + +DECLARE_INTERFACE(ID3D12ShaderReflectionConstantBuffer) +{ + STDMETHOD(GetDesc)(THIS_ D3D12_SHADER_BUFFER_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByIndex)(THIS_ _In_ UINT Index) PURE; + STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByName)(THIS_ _In_ LPCSTR Name) PURE; +}; + +// The ID3D12ShaderReflection IID may change from SDK version to SDK version +// if the reflection API changes. This prevents new code with the new API +// from working with an old binary. Recompiling with the new header +// will pick up the new IID. + +// {5A58797D-A72C-478D-8BA2-EFC6B0EFE88E} +interface DECLSPEC_UUID("5A58797D-A72C-478D-8BA2-EFC6B0EFE88E") ID3D12ShaderReflection; +DEFINE_GUID(IID_ID3D12ShaderReflection, +0x5a58797d, 0xa72c, 0x478d, 0x8b, 0xa2, 0xef, 0xc6, 0xb0, 0xef, 0xe8, 0x8e); + +#undef INTERFACE +#define INTERFACE ID3D12ShaderReflection + +DECLARE_INTERFACE_(ID3D12ShaderReflection, IUnknown) +{ + STDMETHOD(QueryInterface)(THIS_ _In_ REFIID iid, + _Out_ LPVOID *ppv) PURE; + STDMETHOD_(ULONG, AddRef)(THIS) PURE; + STDMETHOD_(ULONG, Release)(THIS) PURE; + + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_SHADER_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer*, GetConstantBufferByIndex)(THIS_ _In_ UINT Index) PURE; + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer*, GetConstantBufferByName)(THIS_ _In_ LPCSTR Name) PURE; + + STDMETHOD(GetResourceBindingDesc)(THIS_ _In_ UINT ResourceIndex, + _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc) PURE; + + STDMETHOD(GetInputParameterDesc)(THIS_ _In_ UINT ParameterIndex, + _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc) PURE; + STDMETHOD(GetOutputParameterDesc)(THIS_ _In_ UINT ParameterIndex, + _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc) PURE; + STDMETHOD(GetPatchConstantParameterDesc)(THIS_ _In_ UINT ParameterIndex, + _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByName)(THIS_ _In_ LPCSTR Name) PURE; + + STDMETHOD(GetResourceBindingDescByName)(THIS_ _In_ LPCSTR Name, + _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc) PURE; + + STDMETHOD_(UINT, GetMovInstructionCount)(THIS) PURE; + STDMETHOD_(UINT, GetMovcInstructionCount)(THIS) PURE; + STDMETHOD_(UINT, GetConversionInstructionCount)(THIS) PURE; + STDMETHOD_(UINT, GetBitwiseInstructionCount)(THIS) PURE; + + STDMETHOD_(D3D_PRIMITIVE, GetGSInputPrimitive)(THIS) PURE; + STDMETHOD_(BOOL, IsSampleFrequencyShader)(THIS) PURE; + + STDMETHOD_(UINT, GetNumInterfaceSlots)(THIS) PURE; + STDMETHOD(GetMinFeatureLevel)(THIS_ _Out_ enum D3D_FEATURE_LEVEL* pLevel) PURE; + + STDMETHOD_(UINT, GetThreadGroupSize)(THIS_ + _Out_opt_ UINT* pSizeX, + _Out_opt_ UINT* pSizeY, + _Out_opt_ UINT* pSizeZ) PURE; + + STDMETHOD_(UINT64, GetRequiresFlags)(THIS) PURE; +}; + +// {8E349D19-54DB-4A56-9DC9-119D87BDB804} +interface DECLSPEC_UUID("8E349D19-54DB-4A56-9DC9-119D87BDB804") ID3D12LibraryReflection; +DEFINE_GUID(IID_ID3D12LibraryReflection, +0x8e349d19, 0x54db, 0x4a56, 0x9d, 0xc9, 0x11, 0x9d, 0x87, 0xbd, 0xb8, 0x4); + +#undef INTERFACE +#define INTERFACE ID3D12LibraryReflection + +DECLARE_INTERFACE_(ID3D12LibraryReflection, IUnknown) +{ + STDMETHOD(QueryInterface)(THIS_ _In_ REFIID iid, _Out_ LPVOID * ppv) PURE; + STDMETHOD_(ULONG, AddRef)(THIS) PURE; + STDMETHOD_(ULONG, Release)(THIS) PURE; + + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_LIBRARY_DESC * pDesc) PURE; + + STDMETHOD_(ID3D12FunctionReflection *, GetFunctionByIndex)(THIS_ _In_ INT FunctionIndex) PURE; +}; + +// {1108795C-2772-4BA9-B2A8-D464DC7E2799} +interface DECLSPEC_UUID("1108795C-2772-4BA9-B2A8-D464DC7E2799") ID3D12FunctionReflection; +DEFINE_GUID(IID_ID3D12FunctionReflection, +0x1108795c, 0x2772, 0x4ba9, 0xb2, 0xa8, 0xd4, 0x64, 0xdc, 0x7e, 0x27, 0x99); + +#undef INTERFACE +#define INTERFACE ID3D12FunctionReflection + +DECLARE_INTERFACE(ID3D12FunctionReflection) +{ + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_FUNCTION_DESC * pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByIndex)(THIS_ _In_ UINT BufferIndex) PURE; + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByName)(THIS_ _In_ LPCSTR Name) PURE; + + STDMETHOD(GetResourceBindingDesc)(THIS_ _In_ UINT ResourceIndex, + _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionVariable *, GetVariableByName)(THIS_ _In_ LPCSTR Name) PURE; + + STDMETHOD(GetResourceBindingDescByName)(THIS_ _In_ LPCSTR Name, + _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc) PURE; + + // Use D3D_RETURN_PARAMETER_INDEX to get description of the return value. + STDMETHOD_(ID3D12FunctionParameterReflection *, GetFunctionParameter)(THIS_ _In_ INT ParameterIndex) PURE; +}; + +// {EC25F42D-7006-4F2B-B33E-02CC3375733F} +interface DECLSPEC_UUID("EC25F42D-7006-4F2B-B33E-02CC3375733F") ID3D12FunctionParameterReflection; +DEFINE_GUID(IID_ID3D12FunctionParameterReflection, +0xec25f42d, 0x7006, 0x4f2b, 0xb3, 0x3e, 0x2, 0xcc, 0x33, 0x75, 0x73, 0x3f); + +#undef INTERFACE +#define INTERFACE ID3D12FunctionParameterReflection + +DECLARE_INTERFACE(ID3D12FunctionParameterReflection) +{ + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_PARAMETER_DESC * pDesc) PURE; +}; + + +////////////////////////////////////////////////////////////////////////////// +// APIs ////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + +#ifdef __cplusplus +} +#endif //__cplusplus + +#endif //__D3D12SHADER_H__ + diff --git a/Externals/DXCompiler/Include/dxcapi.h b/Externals/DXCompiler/Include/dxcapi.h new file mode 100644 index 0000000..e8158ac --- /dev/null +++ b/Externals/DXCompiler/Include/dxcapi.h @@ -0,0 +1,725 @@ + +/////////////////////////////////////////////////////////////////////////////// +// // +// dxcapi.h // +// Copyright (C) Microsoft Corporation. All rights reserved. // +// This file is distributed under the University of Illinois Open Source // +// License. See LICENSE.TXT for details. // +// // +// Provides declarations for the DirectX Compiler API entry point. // +// // +/////////////////////////////////////////////////////////////////////////////// + +#ifndef __DXC_API__ +#define __DXC_API__ + +#ifdef _WIN32 +#ifndef DXC_API_IMPORT +#define DXC_API_IMPORT __declspec(dllimport) +#endif +#else +#ifndef DXC_API_IMPORT +#define DXC_API_IMPORT __attribute__ ((visibility ("default"))) +#endif +#endif + +#ifdef _WIN32 + +#ifndef CROSS_PLATFORM_UUIDOF +// Warning: This macro exists in WinAdapter.h as well +#define CROSS_PLATFORM_UUIDOF(interface, spec) \ + struct __declspec(uuid(spec)) interface; +#endif + +#else + +#include +#include "dxc/Support/WinAdapter.h" +#endif + +struct IMalloc; + +struct IDxcIncludeHandler; + +typedef HRESULT (__stdcall *DxcCreateInstanceProc)( + _In_ REFCLSID rclsid, + _In_ REFIID riid, + _Out_ LPVOID* ppv +); + +typedef HRESULT(__stdcall *DxcCreateInstance2Proc)( + _In_ IMalloc *pMalloc, + _In_ REFCLSID rclsid, + _In_ REFIID riid, + _Out_ LPVOID* ppv + ); + +/// +/// Creates a single uninitialized object of the class associated with a specified CLSID. +/// +/// +/// The CLSID associated with the data and code that will be used to create the object. +/// +/// +/// A reference to the identifier of the interface to be used to communicate +/// with the object. +/// +/// +/// Address of pointer variable that receives the interface pointer requested +/// in riid. Upon successful return, *ppv contains the requested interface +/// pointer. Upon failure, *ppv contains NULL. +/// +/// While this function is similar to CoCreateInstance, there is no COM involvement. +/// + +extern "C" +DXC_API_IMPORT HRESULT __stdcall DxcCreateInstance( + _In_ REFCLSID rclsid, + _In_ REFIID riid, + _Out_ LPVOID* ppv + ); + +extern "C" +DXC_API_IMPORT HRESULT __stdcall DxcCreateInstance2( + _In_ IMalloc *pMalloc, + _In_ REFCLSID rclsid, + _In_ REFIID riid, + _Out_ LPVOID* ppv +); + +// For convenience, equivalent definitions to CP_UTF8 and CP_UTF16. +#define DXC_CP_UTF8 65001 +#define DXC_CP_UTF16 1200 +// Use DXC_CP_ACP for: Binary; ANSI Text; Autodetect UTF with BOM +#define DXC_CP_ACP 0 + +// This flag indicates that the shader hash was computed taking into account source information (-Zss) +#define DXC_HASHFLAG_INCLUDES_SOURCE 1 + +// Hash digest type for ShaderHash +typedef struct DxcShaderHash { + UINT32 Flags; // DXC_HASHFLAG_* + BYTE HashDigest[16]; +} DxcShaderHash; + +#define DXC_FOURCC(ch0, ch1, ch2, ch3) ( \ + (UINT32)(UINT8)(ch0) | (UINT32)(UINT8)(ch1) << 8 | \ + (UINT32)(UINT8)(ch2) << 16 | (UINT32)(UINT8)(ch3) << 24 \ + ) +#define DXC_PART_PDB DXC_FOURCC('I', 'L', 'D', 'B') +#define DXC_PART_PDB_NAME DXC_FOURCC('I', 'L', 'D', 'N') +#define DXC_PART_PRIVATE_DATA DXC_FOURCC('P', 'R', 'I', 'V') +#define DXC_PART_ROOT_SIGNATURE DXC_FOURCC('R', 'T', 'S', '0') +#define DXC_PART_DXIL DXC_FOURCC('D', 'X', 'I', 'L') +#define DXC_PART_REFLECTION_DATA DXC_FOURCC('S', 'T', 'A', 'T') +#define DXC_PART_SHADER_HASH DXC_FOURCC('H', 'A', 'S', 'H') +#define DXC_PART_INPUT_SIGNATURE DXC_FOURCC('I', 'S', 'G', '1') +#define DXC_PART_OUTPUT_SIGNATURE DXC_FOURCC('O', 'S', 'G', '1') +#define DXC_PART_PATCH_CONSTANT_SIGNATURE DXC_FOURCC('P', 'S', 'G', '1') + +// Some option arguments are defined here for continuity with D3DCompile interface +#define DXC_ARG_DEBUG L"-Zi" +#define DXC_ARG_SKIP_VALIDATION L"-Vd" +#define DXC_ARG_SKIP_OPTIMIZATIONS L"-Od" +#define DXC_ARG_PACK_MATRIX_ROW_MAJOR L"-Zpr" +#define DXC_ARG_PACK_MATRIX_COLUMN_MAJOR L"-Zpc" +#define DXC_ARG_AVOID_FLOW_CONTROL L"-Gfa" +#define DXC_ARG_PREFER_FLOW_CONTROL L"-Gfp" +#define DXC_ARG_ENABLE_STRICTNESS L"-Ges" +#define DXC_ARG_ENABLE_BACKWARDS_COMPATIBILITY L"-Gec" +#define DXC_ARG_IEEE_STRICTNESS L"-Gis" +#define DXC_ARG_OPTIMIZATION_LEVEL0 L"-O0" +#define DXC_ARG_OPTIMIZATION_LEVEL1 L"-O1" +#define DXC_ARG_OPTIMIZATION_LEVEL2 L"-O2" +#define DXC_ARG_OPTIMIZATION_LEVEL3 L"-O3" +#define DXC_ARG_WARNINGS_ARE_ERRORS L"-WX" +#define DXC_ARG_RESOURCES_MAY_ALIAS L"-res_may_alias" +#define DXC_ARG_ALL_RESOURCES_BOUND L"-all_resources_bound" +#define DXC_ARG_DEBUG_NAME_FOR_SOURCE L"-Zss" +#define DXC_ARG_DEBUG_NAME_FOR_BINARY L"-Zsb" + +// IDxcBlob is an alias of ID3D10Blob and ID3DBlob +CROSS_PLATFORM_UUIDOF(IDxcBlob, "8BA5FB08-5195-40e2-AC58-0D989C3A0102") +struct IDxcBlob : public IUnknown { +public: + virtual LPVOID STDMETHODCALLTYPE GetBufferPointer(void) = 0; + virtual SIZE_T STDMETHODCALLTYPE GetBufferSize(void) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcBlobEncoding, "7241d424-2646-4191-97c0-98e96e42fc68") +struct IDxcBlobEncoding : public IDxcBlob { +public: + virtual HRESULT STDMETHODCALLTYPE GetEncoding(_Out_ BOOL *pKnown, + _Out_ UINT32 *pCodePage) = 0; +}; + +// Notes on IDxcBlobUtf16 and IDxcBlobUtf8 +// These guarantee null-terminated text and the stated encoding. +// GetBufferSize() will return the size in bytes, including null-terminator +// GetStringLength() will return the length in characters, excluding the null-terminator +// Name strings will use IDxcBlobUtf16, while other string output blobs, +// such as errors/warnings, preprocessed HLSL, or other text will be based +// on the -encoding option. + +// The API will use this interface for output name strings +CROSS_PLATFORM_UUIDOF(IDxcBlobUtf16, "A3F84EAB-0FAA-497E-A39C-EE6ED60B2D84") +struct IDxcBlobUtf16 : public IDxcBlobEncoding { +public: + virtual LPCWSTR STDMETHODCALLTYPE GetStringPointer(void) = 0; + virtual SIZE_T STDMETHODCALLTYPE GetStringLength(void) = 0; +}; +CROSS_PLATFORM_UUIDOF(IDxcBlobUtf8, "3DA636C9-BA71-4024-A301-30CBF125305B") +struct IDxcBlobUtf8 : public IDxcBlobEncoding { +public: + virtual LPCSTR STDMETHODCALLTYPE GetStringPointer(void) = 0; + virtual SIZE_T STDMETHODCALLTYPE GetStringLength(void) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcIncludeHandler, "7f61fc7d-950d-467f-b3e3-3c02fb49187c") +struct IDxcIncludeHandler : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE LoadSource( + _In_z_ LPCWSTR pFilename, // Candidate filename. + _COM_Outptr_result_maybenull_ IDxcBlob **ppIncludeSource // Resultant source object for included file, nullptr if not found. + ) = 0; +}; + +// Structure for supplying bytes or text input to Dxc APIs. +// Use Encoding = 0 for non-text bytes, ANSI text, or unknown with BOM. +typedef struct DxcBuffer { + LPCVOID Ptr; + SIZE_T Size; + UINT Encoding; +} DxcText; + +struct DxcDefine { + LPCWSTR Name; + _Maybenull_ LPCWSTR Value; +}; + +CROSS_PLATFORM_UUIDOF(IDxcCompilerArgs, "73EFFE2A-70DC-45F8-9690-EFF64C02429D") +struct IDxcCompilerArgs : public IUnknown { + // Pass GetArguments() and GetCount() to Compile + virtual LPCWSTR* STDMETHODCALLTYPE GetArguments() = 0; + virtual UINT32 STDMETHODCALLTYPE GetCount() = 0; + + // Add additional arguments or defines here, if desired. + virtual HRESULT STDMETHODCALLTYPE AddArguments( + _In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments to add + _In_ UINT32 argCount // Number of arguments to add + ) = 0; + virtual HRESULT STDMETHODCALLTYPE AddArgumentsUTF8( + _In_opt_count_(argCount)LPCSTR *pArguments, // Array of pointers to UTF-8 arguments to add + _In_ UINT32 argCount // Number of arguments to add + ) = 0; + virtual HRESULT STDMETHODCALLTYPE AddDefines( + _In_count_(defineCount) const DxcDefine *pDefines, // Array of defines + _In_ UINT32 defineCount // Number of defines + ) = 0; +}; + +////////////////////////// +// Legacy Interfaces +///////////////////////// + +// NOTE: IDxcUtils replaces IDxcLibrary +CROSS_PLATFORM_UUIDOF(IDxcLibrary, "e5204dc7-d18c-4c3c-bdfb-851673980fe7") +struct IDxcLibrary : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE SetMalloc(_In_opt_ IMalloc *pMalloc) = 0; + virtual HRESULT STDMETHODCALLTYPE CreateBlobFromBlob( + _In_ IDxcBlob *pBlob, UINT32 offset, UINT32 length, _COM_Outptr_ IDxcBlob **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE CreateBlobFromFile( + _In_z_ LPCWSTR pFileName, _In_opt_ UINT32* codePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingFromPinned( + _In_bytecount_(size) LPCVOID pText, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingOnHeapCopy( + _In_bytecount_(size) LPCVOID pText, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingOnMalloc( + _In_bytecount_(size) LPCVOID pText, IMalloc *pIMalloc, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + virtual HRESULT STDMETHODCALLTYPE CreateIncludeHandler( + _COM_Outptr_ IDxcIncludeHandler **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE CreateStreamFromBlobReadOnly( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IStream **ppStream) = 0; + virtual HRESULT STDMETHODCALLTYPE GetBlobAsUtf8( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + virtual HRESULT STDMETHODCALLTYPE GetBlobAsUtf16( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; +}; + +// NOTE: IDxcResult replaces IDxcOperationResult +CROSS_PLATFORM_UUIDOF(IDxcOperationResult, "CEDB484A-D4E9-445A-B991-CA21CA157DC2") +struct IDxcOperationResult : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE GetStatus(_Out_ HRESULT *pStatus) = 0; + + // GetResult returns the main result of the operation. + // This corresponds to: + // DXC_OUT_OBJECT - Compile() with shader or library target + // DXC_OUT_DISASSEMBLY - Disassemble() + // DXC_OUT_HLSL - Compile() with -P + // DXC_OUT_ROOT_SIGNATURE - Compile() with rootsig_* target + virtual HRESULT STDMETHODCALLTYPE GetResult(_COM_Outptr_result_maybenull_ IDxcBlob **ppResult) = 0; + + // GetErrorBuffer Corresponds to DXC_OUT_ERRORS. + virtual HRESULT STDMETHODCALLTYPE GetErrorBuffer(_COM_Outptr_result_maybenull_ IDxcBlobEncoding **ppErrors) = 0; +}; + +// NOTE: IDxcCompiler3 replaces IDxcCompiler and IDxcCompiler2 +CROSS_PLATFORM_UUIDOF(IDxcCompiler, "8c210bf3-011f-4422-8d70-6f9acb8db617") +struct IDxcCompiler : public IUnknown { + // Compile a single entry point to the target shader model + virtual HRESULT STDMETHODCALLTYPE Compile( + _In_ IDxcBlob *pSource, // Source text to compile + _In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and include handlers. + _In_opt_z_ LPCWSTR pEntryPoint, // entry point name + _In_z_ LPCWSTR pTargetProfile, // shader profile to compile + _In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments + _In_ UINT32 argCount, // Number of arguments + _In_count_(defineCount) + const DxcDefine *pDefines, // Array of defines + _In_ UINT32 defineCount, // Number of defines + _In_opt_ IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle #include directives (optional) + _COM_Outptr_ IDxcOperationResult **ppResult // Compiler output status, buffer, and errors + ) = 0; + + // Preprocess source text + virtual HRESULT STDMETHODCALLTYPE Preprocess( + _In_ IDxcBlob *pSource, // Source text to preprocess + _In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and include handlers. + _In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments + _In_ UINT32 argCount, // Number of arguments + _In_count_(defineCount) + const DxcDefine *pDefines, // Array of defines + _In_ UINT32 defineCount, // Number of defines + _In_opt_ IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle #include directives (optional) + _COM_Outptr_ IDxcOperationResult **ppResult // Preprocessor output status, buffer, and errors + ) = 0; + + // Disassemble a program. + virtual HRESULT STDMETHODCALLTYPE Disassemble( + _In_ IDxcBlob *pSource, // Program to disassemble. + _COM_Outptr_ IDxcBlobEncoding **ppDisassembly // Disassembly text. + ) = 0; +}; + +// NOTE: IDxcCompiler3 replaces IDxcCompiler and IDxcCompiler2 +CROSS_PLATFORM_UUIDOF(IDxcCompiler2, "A005A9D9-B8BB-4594-B5C9-0E633BEC4D37") +struct IDxcCompiler2 : public IDxcCompiler { + // Compile a single entry point to the target shader model with debug information. + virtual HRESULT STDMETHODCALLTYPE CompileWithDebug( + _In_ IDxcBlob *pSource, // Source text to compile + _In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and include handlers. + _In_opt_z_ LPCWSTR pEntryPoint, // Entry point name + _In_z_ LPCWSTR pTargetProfile, // Shader profile to compile + _In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments + _In_ UINT32 argCount, // Number of arguments + _In_count_(defineCount) + const DxcDefine *pDefines, // Array of defines + _In_ UINT32 defineCount, // Number of defines + _In_opt_ IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle #include directives (optional) + _COM_Outptr_ IDxcOperationResult **ppResult, // Compiler output status, buffer, and errors + _Outptr_opt_result_z_ LPWSTR *ppDebugBlobName,// Suggested file name for debug blob. (Must be CoTaskMemFree()'d!) + _COM_Outptr_opt_ IDxcBlob **ppDebugBlob // Debug blob + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcLinker, "F1B5BE2A-62DD-4327-A1C2-42AC1E1E78E6") +struct IDxcLinker : public IUnknown { +public: + // Register a library with name to ref it later. + virtual HRESULT RegisterLibrary( + _In_opt_ LPCWSTR pLibName, // Name of the library. + _In_ IDxcBlob *pLib // Library blob. + ) = 0; + + // Links the shader and produces a shader blob that the Direct3D runtime can + // use. + virtual HRESULT STDMETHODCALLTYPE Link( + _In_opt_ LPCWSTR pEntryName, // Entry point name + _In_ LPCWSTR pTargetProfile, // shader profile to link + _In_count_(libCount) + const LPCWSTR *pLibNames, // Array of library names to link + _In_ UINT32 libCount, // Number of libraries to link + _In_opt_count_(argCount) const LPCWSTR *pArguments, // Array of pointers to arguments + _In_ UINT32 argCount, // Number of arguments + _COM_Outptr_ + IDxcOperationResult **ppResult // Linker output status, buffer, and errors + ) = 0; +}; + +///////////////////////// +// Latest interfaces. Please use these +//////////////////////// + +// NOTE: IDxcUtils replaces IDxcLibrary +CROSS_PLATFORM_UUIDOF(IDxcUtils, "4605C4CB-2019-492A-ADA4-65F20BB7D67F") +struct IDxcUtils : public IUnknown { + // Create a sub-blob that holds a reference to the outer blob and points to its memory. + virtual HRESULT STDMETHODCALLTYPE CreateBlobFromBlob( + _In_ IDxcBlob *pBlob, UINT32 offset, UINT32 length, _COM_Outptr_ IDxcBlob **ppResult) = 0; + + // For codePage, use 0 (or DXC_CP_ACP) for raw binary or ANSI code page + + // Creates a blob referencing existing memory, with no copy. + // User must manage the memory lifetime separately. + // (was: CreateBlobWithEncodingFromPinned) + virtual HRESULT STDMETHODCALLTYPE CreateBlobFromPinned( + _In_bytecount_(size) LPCVOID pData, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + // Create blob, taking ownership of memory allocated with supplied allocator. + // (was: CreateBlobWithEncodingOnMalloc) + virtual HRESULT STDMETHODCALLTYPE MoveToBlob( + _In_bytecount_(size) LPCVOID pData, IMalloc *pIMalloc, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + //// + // New blobs and copied contents are allocated with the current allocator + + // Copy blob contents to memory owned by the new blob. + // (was: CreateBlobWithEncodingOnHeapCopy) + virtual HRESULT STDMETHODCALLTYPE CreateBlob( + _In_bytecount_(size) LPCVOID pData, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + // (was: CreateBlobFromFile) + virtual HRESULT STDMETHODCALLTYPE LoadFile( + _In_z_ LPCWSTR pFileName, _In_opt_ UINT32* pCodePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + virtual HRESULT STDMETHODCALLTYPE CreateReadOnlyStreamFromBlob( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IStream **ppStream) = 0; + + // Create default file-based include handler + virtual HRESULT STDMETHODCALLTYPE CreateDefaultIncludeHandler( + _COM_Outptr_ IDxcIncludeHandler **ppResult) = 0; + + // Convert or return matching encoded text blobs + virtual HRESULT STDMETHODCALLTYPE GetBlobAsUtf8( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobUtf8 **pBlobEncoding) = 0; + virtual HRESULT STDMETHODCALLTYPE GetBlobAsUtf16( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobUtf16 **pBlobEncoding) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetDxilContainerPart( + _In_ const DxcBuffer *pShader, + _In_ UINT32 DxcPart, + _Outptr_result_nullonfailure_ void **ppPartData, + _Out_ UINT32 *pPartSizeInBytes) = 0; + + // Create reflection interface from serialized Dxil container, or DXC_PART_REFLECTION_DATA. + // TBD: Require part header for RDAT? (leaning towards yes) + virtual HRESULT STDMETHODCALLTYPE CreateReflection( + _In_ const DxcBuffer *pData, REFIID iid, void **ppvReflection) = 0; + + virtual HRESULT STDMETHODCALLTYPE BuildArguments( + _In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in errors and include handlers. + _In_opt_z_ LPCWSTR pEntryPoint, // Entry point name. (-E) + _In_z_ LPCWSTR pTargetProfile, // Shader profile to compile. (-T) + _In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments + _In_ UINT32 argCount, // Number of arguments + _In_count_(defineCount) + const DxcDefine *pDefines, // Array of defines + _In_ UINT32 defineCount, // Number of defines + _COM_Outptr_ IDxcCompilerArgs **ppArgs // Arguments you can use with Compile() method + ) = 0; + + // Takes the shader PDB and returns the hash and the container inside it + virtual HRESULT STDMETHODCALLTYPE GetPDBContents( + _In_ IDxcBlob *pPDBBlob, _COM_Outptr_ IDxcBlob **ppHash, _COM_Outptr_ IDxcBlob **ppContainer) = 0; +}; + +// For use with IDxcResult::[Has|Get]Output dxcOutKind argument +// Note: text outputs returned from version 2 APIs are UTF-8 or UTF-16 based on -encoding option +typedef enum DXC_OUT_KIND { + DXC_OUT_NONE = 0, + DXC_OUT_OBJECT = 1, // IDxcBlob - Shader or library object + DXC_OUT_ERRORS = 2, // IDxcBlobUtf8 or IDxcBlobUtf16 + DXC_OUT_PDB = 3, // IDxcBlob + DXC_OUT_SHADER_HASH = 4, // IDxcBlob - DxcShaderHash of shader or shader with source info (-Zsb/-Zss) + DXC_OUT_DISASSEMBLY = 5, // IDxcBlobUtf8 or IDxcBlobUtf16 - from Disassemble + DXC_OUT_HLSL = 6, // IDxcBlobUtf8 or IDxcBlobUtf16 - from Preprocessor or Rewriter + DXC_OUT_TEXT = 7, // IDxcBlobUtf8 or IDxcBlobUtf16 - other text, such as -ast-dump or -Odump + DXC_OUT_REFLECTION = 8, // IDxcBlob - RDAT part with reflection data + DXC_OUT_ROOT_SIGNATURE = 9, // IDxcBlob - Serialized root signature output + DXC_OUT_EXTRA_OUTPUTS = 10,// IDxcExtraResults - Extra outputs + + DXC_OUT_FORCE_DWORD = 0xFFFFFFFF +} DXC_OUT_KIND; + +CROSS_PLATFORM_UUIDOF(IDxcResult, "58346CDA-DDE7-4497-9461-6F87AF5E0659") +struct IDxcResult : public IDxcOperationResult { + virtual BOOL STDMETHODCALLTYPE HasOutput(_In_ DXC_OUT_KIND dxcOutKind) = 0; + virtual HRESULT STDMETHODCALLTYPE GetOutput(_In_ DXC_OUT_KIND dxcOutKind, + _In_ REFIID iid, _COM_Outptr_opt_result_maybenull_ void **ppvObject, + _COM_Outptr_ IDxcBlobUtf16 **ppOutputName) = 0; + + virtual UINT32 GetNumOutputs() = 0; + virtual DXC_OUT_KIND GetOutputByIndex(UINT32 Index) = 0; + virtual DXC_OUT_KIND PrimaryOutput() = 0; +}; + +// Special names for extra output that should get written to specific streams +#define DXC_EXTRA_OUTPUT_NAME_STDOUT L"*stdout*" +#define DXC_EXTRA_OUTPUT_NAME_STDERR L"*stderr*" + +CROSS_PLATFORM_UUIDOF(IDxcExtraOutputs, "319b37a2-a5c2-494a-a5de-4801b2faf989") +struct IDxcExtraOutputs : public IUnknown { + + virtual UINT32 STDMETHODCALLTYPE GetOutputCount() = 0; + virtual HRESULT STDMETHODCALLTYPE GetOutput(_In_ UINT32 uIndex, + _In_ REFIID iid, _COM_Outptr_opt_result_maybenull_ void **ppvObject, + _COM_Outptr_opt_result_maybenull_ IDxcBlobUtf16 **ppOutputType, + _COM_Outptr_opt_result_maybenull_ IDxcBlobUtf16 **ppOutputName) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcCompiler3, "228B4687-5A6A-4730-900C-9702B2203F54") +struct IDxcCompiler3 : public IUnknown { + // Compile a single entry point to the target shader model, + // Compile a library to a library target (-T lib_*), + // Compile a root signature (-T rootsig_*), or + // Preprocess HLSL source (-P) + virtual HRESULT STDMETHODCALLTYPE Compile( + _In_ const DxcBuffer *pSource, // Source text to compile + _In_opt_count_(argCount) LPCWSTR *pArguments, // Array of pointers to arguments + _In_ UINT32 argCount, // Number of arguments + _In_opt_ IDxcIncludeHandler *pIncludeHandler, // user-provided interface to handle #include directives (optional) + _In_ REFIID riid, _Out_ LPVOID *ppResult // IDxcResult: status, buffer, and errors + ) = 0; + + // Disassemble a program. + virtual HRESULT STDMETHODCALLTYPE Disassemble( + _In_ const DxcBuffer *pObject, // Program to disassemble: dxil container or bitcode. + _In_ REFIID riid, _Out_ LPVOID *ppResult // IDxcResult: status, disassembly text, and errors + ) = 0; +}; + +static const UINT32 DxcValidatorFlags_Default = 0; +static const UINT32 DxcValidatorFlags_InPlaceEdit = 1; // Validator is allowed to update shader blob in-place. +static const UINT32 DxcValidatorFlags_RootSignatureOnly = 2; +static const UINT32 DxcValidatorFlags_ModuleOnly = 4; +static const UINT32 DxcValidatorFlags_ValidMask = 0x7; + +CROSS_PLATFORM_UUIDOF(IDxcValidator, "A6E82BD2-1FD7-4826-9811-2857E797F49A") +struct IDxcValidator : public IUnknown { + // Validate a shader. + virtual HRESULT STDMETHODCALLTYPE Validate( + _In_ IDxcBlob *pShader, // Shader to validate. + _In_ UINT32 Flags, // Validation flags. + _COM_Outptr_ IDxcOperationResult **ppResult // Validation output status, buffer, and errors + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcValidator2, "458e1fd1-b1b2-4750-a6e1-9c10f03bed92") +struct IDxcValidator2 : public IDxcValidator { + // Validate a shader. + virtual HRESULT STDMETHODCALLTYPE ValidateWithDebug( + _In_ IDxcBlob *pShader, // Shader to validate. + _In_ UINT32 Flags, // Validation flags. + _In_opt_ DxcBuffer *pOptDebugBitcode, // Optional debug module bitcode to provide line numbers + _COM_Outptr_ IDxcOperationResult **ppResult // Validation output status, buffer, and errors + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcContainerBuilder, "334b1f50-2292-4b35-99a1-25588d8c17fe") +struct IDxcContainerBuilder : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pDxilContainerHeader) = 0; // Loads DxilContainer to the builder + virtual HRESULT STDMETHODCALLTYPE AddPart(_In_ UINT32 fourCC, _In_ IDxcBlob *pSource) = 0; // Part to add to the container + virtual HRESULT STDMETHODCALLTYPE RemovePart(_In_ UINT32 fourCC) = 0; // Remove the part with fourCC + virtual HRESULT STDMETHODCALLTYPE SerializeContainer(_Out_ IDxcOperationResult **ppResult) = 0; // Builds a container of the given container builder state +}; + +CROSS_PLATFORM_UUIDOF(IDxcAssembler, "091f7a26-1c1f-4948-904b-e6e3a8a771d5") +struct IDxcAssembler : public IUnknown { + // Assemble dxil in ll or llvm bitcode to DXIL container. + virtual HRESULT STDMETHODCALLTYPE AssembleToContainer( + _In_ IDxcBlob *pShader, // Shader to assemble. + _COM_Outptr_ IDxcOperationResult **ppResult // Assembly output status, buffer, and errors + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcContainerReflection, "d2c21b26-8350-4bdc-976a-331ce6f4c54c") +struct IDxcContainerReflection : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pContainer) = 0; // Container to load. + virtual HRESULT STDMETHODCALLTYPE GetPartCount(_Out_ UINT32 *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetPartKind(UINT32 idx, _Out_ UINT32 *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetPartContent(UINT32 idx, _COM_Outptr_ IDxcBlob **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE FindFirstPartKind(UINT32 kind, _Out_ UINT32 *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetPartReflection(UINT32 idx, REFIID iid, void **ppvObject) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcOptimizerPass, "AE2CD79F-CC22-453F-9B6B-B124E7A5204C") +struct IDxcOptimizerPass : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE GetOptionName(_COM_Outptr_ LPWSTR *ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetDescription(_COM_Outptr_ LPWSTR *ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetOptionArgCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE GetOptionArgName(UINT32 argIndex, _COM_Outptr_ LPWSTR *ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetOptionArgDescription(UINT32 argIndex, _COM_Outptr_ LPWSTR *ppResult) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcOptimizer, "25740E2E-9CBA-401B-9119-4FB42F39F270") +struct IDxcOptimizer : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE GetAvailablePassCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE GetAvailablePass(UINT32 index, _COM_Outptr_ IDxcOptimizerPass** ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE RunOptimizer(IDxcBlob *pBlob, + _In_count_(optionCount) LPCWSTR *ppOptions, UINT32 optionCount, + _COM_Outptr_ IDxcBlob **pOutputModule, + _COM_Outptr_opt_ IDxcBlobEncoding **ppOutputText) = 0; +}; + +static const UINT32 DxcVersionInfoFlags_None = 0; +static const UINT32 DxcVersionInfoFlags_Debug = 1; // Matches VS_FF_DEBUG +static const UINT32 DxcVersionInfoFlags_Internal = 2; // Internal Validator (non-signing) + +CROSS_PLATFORM_UUIDOF(IDxcVersionInfo, "b04f5b50-2059-4f12-a8ff-a1e0cde1cc7e") +struct IDxcVersionInfo : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE GetVersion(_Out_ UINT32 *pMajor, _Out_ UINT32 *pMinor) = 0; + virtual HRESULT STDMETHODCALLTYPE GetFlags(_Out_ UINT32 *pFlags) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcVersionInfo2, "fb6904c4-42f0-4b62-9c46-983af7da7c83") +struct IDxcVersionInfo2 : public IDxcVersionInfo { + virtual HRESULT STDMETHODCALLTYPE GetCommitInfo( + _Out_ UINT32 *pCommitCount, // The total number commits. + _Outptr_result_z_ char **pCommitHash // The SHA of the latest commit. (Must be CoTaskMemFree()'d!) + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcVersionInfo3, "5e13e843-9d25-473c-9ad2-03b2d0b44b1e") +struct IDxcVersionInfo3 : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE GetCustomVersionString( + _Outptr_result_z_ char **pVersionString // Custom version string for compiler. (Must be CoTaskMemFree()'d!) + ) = 0; +}; + +struct DxcArgPair { + const WCHAR *pName; + const WCHAR *pValue; +}; + +CROSS_PLATFORM_UUIDOF(IDxcPdbUtils, "E6C9647E-9D6A-4C3B-B94C-524B5A6C343D") +struct IDxcPdbUtils : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pPdbOrDxil) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetSourceCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE GetSource(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobEncoding **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetSourceName(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetFlagCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE GetFlag(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetArgCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE GetArg(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetArgPairCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE GetArgPair(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pName, _Outptr_result_z_ BSTR *pValue) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetDefineCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE GetDefine(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetTargetProfile(_Outptr_result_z_ BSTR *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetEntryPoint(_Outptr_result_z_ BSTR *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetMainFileName(_Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetHash(_COM_Outptr_ IDxcBlob **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetName(_Outptr_result_z_ BSTR *pResult) = 0; + + virtual BOOL STDMETHODCALLTYPE IsFullPDB() = 0; + virtual HRESULT STDMETHODCALLTYPE GetFullPDB(_COM_Outptr_ IDxcBlob **ppFullPDB) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetVersionInfo(_COM_Outptr_ IDxcVersionInfo **ppVersionInfo) = 0; + + virtual HRESULT STDMETHODCALLTYPE SetCompiler(_In_ IDxcCompiler3 *pCompiler) = 0; + virtual HRESULT STDMETHODCALLTYPE CompileForFullPDB(_COM_Outptr_ IDxcResult **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE OverrideArgs(_In_ DxcArgPair *pArgPairs, UINT32 uNumArgPairs) = 0; + virtual HRESULT STDMETHODCALLTYPE OverrideRootSignature(_In_ const WCHAR *pRootSignature) = 0; +}; + +// Note: __declspec(selectany) requires 'extern' +// On Linux __declspec(selectany) is removed and using 'extern' results in link error. +#ifdef _MSC_VER +#define CLSID_SCOPE __declspec(selectany) extern +#else +#define CLSID_SCOPE +#endif + +CLSID_SCOPE const CLSID CLSID_DxcCompiler = { + 0x73e22d93, + 0xe6ce, + 0x47f3, + {0xb5, 0xbf, 0xf0, 0x66, 0x4f, 0x39, 0xc1, 0xb0}}; + +// {EF6A8087-B0EA-4D56-9E45-D07E1A8B7806} +CLSID_SCOPE const GUID CLSID_DxcLinker = { + 0xef6a8087, + 0xb0ea, + 0x4d56, + {0x9e, 0x45, 0xd0, 0x7e, 0x1a, 0x8b, 0x78, 0x6}}; + +// {CD1F6B73-2AB0-484D-8EDC-EBE7A43CA09F} +CLSID_SCOPE const CLSID CLSID_DxcDiaDataSource = { + 0xcd1f6b73, + 0x2ab0, + 0x484d, + {0x8e, 0xdc, 0xeb, 0xe7, 0xa4, 0x3c, 0xa0, 0x9f}}; + +// {3E56AE82-224D-470F-A1A1-FE3016EE9F9D} +CLSID_SCOPE const CLSID CLSID_DxcCompilerArgs = { + 0x3e56ae82, + 0x224d, + 0x470f, + {0xa1, 0xa1, 0xfe, 0x30, 0x16, 0xee, 0x9f, 0x9d}}; + +// {6245D6AF-66E0-48FD-80B4-4D271796748C} +CLSID_SCOPE const GUID CLSID_DxcLibrary = { + 0x6245d6af, + 0x66e0, + 0x48fd, + {0x80, 0xb4, 0x4d, 0x27, 0x17, 0x96, 0x74, 0x8c}}; + +CLSID_SCOPE const GUID CLSID_DxcUtils = CLSID_DxcLibrary; + +// {8CA3E215-F728-4CF3-8CDD-88AF917587A1} +CLSID_SCOPE const GUID CLSID_DxcValidator = { + 0x8ca3e215, + 0xf728, + 0x4cf3, + {0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1}}; + +// {D728DB68-F903-4F80-94CD-DCCF76EC7151} +CLSID_SCOPE const GUID CLSID_DxcAssembler = { + 0xd728db68, + 0xf903, + 0x4f80, + {0x94, 0xcd, 0xdc, 0xcf, 0x76, 0xec, 0x71, 0x51}}; + +// {b9f54489-55b8-400c-ba3a-1675e4728b91} +CLSID_SCOPE const GUID CLSID_DxcContainerReflection = { + 0xb9f54489, + 0x55b8, + 0x400c, + {0xba, 0x3a, 0x16, 0x75, 0xe4, 0x72, 0x8b, 0x91}}; + +// {AE2CD79F-CC22-453F-9B6B-B124E7A5204C} +CLSID_SCOPE const GUID CLSID_DxcOptimizer = { + 0xae2cd79f, + 0xcc22, + 0x453f, + {0x9b, 0x6b, 0xb1, 0x24, 0xe7, 0xa5, 0x20, 0x4c}}; + +// {94134294-411f-4574-b4d0-8741e25240d2} +CLSID_SCOPE const GUID CLSID_DxcContainerBuilder = { + 0x94134294, + 0x411f, + 0x4574, + {0xb4, 0xd0, 0x87, 0x41, 0xe2, 0x52, 0x40, 0xd2}}; + +// {54621dfb-f2ce-457e-ae8c-ec355faeec7c} +CLSID_SCOPE const GUID CLSID_DxcPdbUtils = { + 0x54621dfb, + 0xf2ce, + 0x457e, + {0xae, 0x8c, 0xec, 0x35, 0x5f, 0xae, 0xec, 0x7c}}; + +#endif diff --git a/Externals/DXCompiler/Lib/dxcompiler.lib b/Externals/DXCompiler/Lib/dxcompiler.lib new file mode 100644 index 0000000..6ba052c Binary files /dev/null and b/Externals/DXCompiler/Lib/dxcompiler.lib differ diff --git a/Externals/DirectXTex Aug 2015/Include/BC.h b/Externals/DirectXTex Aug 2015/Include/BC.h deleted file mode 100644 index ef8928c..0000000 --- a/Externals/DirectXTex Aug 2015/Include/BC.h +++ /dev/null @@ -1,891 +0,0 @@ -//------------------------------------------------------------------------------------- -// BC.h -// -// Block-compression (BC) functionality -// -// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -// PARTICULAR PURPOSE. -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// http://go.microsoft.com/fwlink/?LinkId=248926 -//------------------------------------------------------------------------------------- - -#pragma once - -#include -#include -#include - -namespace DirectX -{ - -//------------------------------------------------------------------------------------- -// Constants -//------------------------------------------------------------------------------------- - -const uint16_t F16S_MASK = 0x8000; // f16 sign mask -const uint16_t F16EM_MASK = 0x7fff; // f16 exp & mantissa mask -const uint16_t F16MAX = 0x7bff; // MAXFLT bit pattern for XMHALF - -#define SIGN_EXTEND(x,nb) ((((x)&(1<<((nb)-1)))?((~0)<<(nb)):0)|(x)) - -// Because these are used in SAL annotations, they need to remain macros rather than const values -#define NUM_PIXELS_PER_BLOCK 16 -#define BC6H_MAX_REGIONS 2 -#define BC6H_MAX_INDICES 16 -#define BC7_MAX_REGIONS 3 -#define BC7_MAX_INDICES 16 - -const size_t BC6H_NUM_CHANNELS = 3; -const size_t BC6H_MAX_SHAPES = 32; - -const size_t BC7_NUM_CHANNELS = 4; -const size_t BC7_MAX_SHAPES = 64; - -const int32_t BC67_WEIGHT_MAX = 64; -const uint32_t BC67_WEIGHT_SHIFT = 6; -const int32_t BC67_WEIGHT_ROUND = 32; - -extern const int g_aWeights2[4]; -extern const int g_aWeights3[8]; -extern const int g_aWeights4[16]; - -enum BC_FLAGS -{ - BC_FLAGS_NONE = 0x0, - BC_FLAGS_DITHER_RGB = 0x10000, // Enables dithering for RGB colors for BC1-3 - BC_FLAGS_DITHER_A = 0x20000, // Enables dithering for Alpha channel for BC1-3 - BC_FLAGS_UNIFORM = 0x40000, // By default, uses perceptual weighting for BC1-3; this flag makes it a uniform weighting - BC_FLAGS_USE_3SUBSETS = 0x80000,// By default, BC7 skips mode 0 & 2; this flag adds those modes back -}; - -//------------------------------------------------------------------------------------- -// Structures -//------------------------------------------------------------------------------------- -class HDRColorA; - -class LDRColorA -{ -public: - uint8_t r, g, b, a; - - LDRColorA() DIRECTX_CTOR_DEFAULT - LDRColorA(uint8_t _r, uint8_t _g, uint8_t _b, uint8_t _a) : r(_r), g(_g), b(_b), a(_a) {} - - const uint8_t& operator [] (_In_range_(0,3) size_t uElement) const - { - switch(uElement) - { - case 0: return r; - case 1: return g; - case 2: return b; - case 3: return a; - default: assert(false); return r; - } - } - - uint8_t& operator [] (_In_range_(0,3) size_t uElement) - { - switch(uElement) - { - case 0: return r; - case 1: return g; - case 2: return b; - case 3: return a; - default: assert(false); return r; - } - } - - LDRColorA operator = (_In_ const HDRColorA& c); - - static void InterpolateRGB(_In_ const LDRColorA& c0, _In_ const LDRColorA& c1, _In_ size_t wc, _In_ _In_range_(2, 4) size_t wcprec, _Out_ LDRColorA& out) - { - const int* aWeights = nullptr; - switch(wcprec) - { - case 2: aWeights = g_aWeights2; assert( wc < 4 ); _Analysis_assume_( wc < 4 ); break; - case 3: aWeights = g_aWeights3; assert( wc < 8 ); _Analysis_assume_( wc < 8 ); break; - case 4: aWeights = g_aWeights4; assert( wc < 16 ); _Analysis_assume_( wc < 16 ); break; - default: assert(false); out.r = out.g = out.b = 0; return; - } - out.r = uint8_t((uint32_t(c0.r) * uint32_t(BC67_WEIGHT_MAX - aWeights[wc]) + uint32_t(c1.r) * uint32_t(aWeights[wc]) + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT); - out.g = uint8_t((uint32_t(c0.g) * uint32_t(BC67_WEIGHT_MAX - aWeights[wc]) + uint32_t(c1.g) * uint32_t(aWeights[wc]) + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT); - out.b = uint8_t((uint32_t(c0.b) * uint32_t(BC67_WEIGHT_MAX - aWeights[wc]) + uint32_t(c1.b) * uint32_t(aWeights[wc]) + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT); - } - - static void InterpolateA(_In_ const LDRColorA& c0, _In_ const LDRColorA& c1, _In_ size_t wa, _In_range_(2, 4) _In_ size_t waprec, _Out_ LDRColorA& out) - { - const int* aWeights = nullptr; - switch(waprec) - { - case 2: aWeights = g_aWeights2; assert( wa < 4 ); _Analysis_assume_( wa < 4 ); break; - case 3: aWeights = g_aWeights3; assert( wa < 8 ); _Analysis_assume_( wa < 8 ); break; - case 4: aWeights = g_aWeights4; assert( wa < 16 ); _Analysis_assume_( wa < 16 ); break; - default: assert(false); out.a = 0; return; - } - out.a = uint8_t((uint32_t(c0.a) * uint32_t(BC67_WEIGHT_MAX - aWeights[wa]) + uint32_t(c1.a) * uint32_t(aWeights[wa]) + BC67_WEIGHT_ROUND) >> BC67_WEIGHT_SHIFT); - } - - static void Interpolate(_In_ const LDRColorA& c0, _In_ const LDRColorA& c1, _In_ size_t wc, _In_ size_t wa, _In_ _In_range_(2, 4) size_t wcprec, _In_ _In_range_(2, 4) size_t waprec, _Out_ LDRColorA& out) - { - InterpolateRGB(c0, c1, wc, wcprec, out); - InterpolateA(c0, c1, wa, waprec, out); - } -}; - -static_assert( sizeof(LDRColorA) == 4, "Unexpected packing"); - -class HDRColorA -{ -public: - float r, g, b, a; - -public: - HDRColorA() DIRECTX_CTOR_DEFAULT - HDRColorA(float _r, float _g, float _b, float _a) : r(_r), g(_g), b(_b), a(_a) {} - HDRColorA(const HDRColorA& c) : r(c.r), g(c.g), b(c.b), a(c.a) {} - HDRColorA(const LDRColorA& c) - { - r = float(c.r) * (1.0f/255.0f); - g = float(c.g) * (1.0f/255.0f); - b = float(c.b) * (1.0f/255.0f); - a = float(c.a) * (1.0f/255.0f); - } - - // binary operators - HDRColorA operator + ( _In_ const HDRColorA& c ) const - { - return HDRColorA(r + c.r, g + c.g, b + c.b, a + c.a); - } - - HDRColorA operator - ( _In_ const HDRColorA& c ) const - { - return HDRColorA(r - c.r, g - c.g, b - c.b, a - c.a); - } - - HDRColorA operator * ( _In_ float f ) const - { - return HDRColorA(r * f, g * f, b * f, a * f); - } - - HDRColorA operator / ( _In_ float f ) const - { - float fInv = 1.0f / f; - return HDRColorA(r * fInv, g * fInv, b * fInv, a * fInv); - } - - float operator * ( _In_ const HDRColorA& c ) const - { - return r * c.r + g * c.g + b * c.b + a * c.a; - } - - // assignment operators - HDRColorA& operator += ( _In_ const HDRColorA& c ) - { - r += c.r; - g += c.g; - b += c.b; - a += c.a; - return *this; - } - - HDRColorA& operator -= ( _In_ const HDRColorA& c ) - { - r -= c.r; - g -= c.g; - b -= c.b; - a -= c.a; - return *this; - } - - HDRColorA& operator *= ( _In_ float f ) - { - r *= f; - g *= f; - b *= f; - a *= f; - return *this; - } - - HDRColorA& operator /= ( _In_ float f ) - { - float fInv = 1.0f / f; - r *= fInv; - g *= fInv; - b *= fInv; - a *= fInv; - return *this; - } - - HDRColorA& operator = (_In_ const LDRColorA& c) - { - r = (float) c.r; - g = (float) c.g; - b = (float) c.b; - a = (float) c.a; - return *this; - } - - HDRColorA& Clamp(_In_ float fMin, _In_ float fMax) - { - r = std::min(fMax, std::max(fMin, r)); - g = std::min(fMax, std::max(fMin, g)); - b = std::min(fMax, std::max(fMin, b)); - a = std::min(fMax, std::max(fMin, a)); - return *this; - } - - LDRColorA ToLDRColorA() const - { - return LDRColorA((uint8_t) (r + 0.01f), (uint8_t) (g + 0.01f), (uint8_t) (b + 0.01f), (uint8_t) (a + 0.01f)); - } -}; - -inline LDRColorA LDRColorA::operator = (_In_ const HDRColorA& c) -{ - LDRColorA ret; - HDRColorA tmp(c); - tmp = tmp.Clamp(0.0f, 1.0f) * 255.0f; - ret.r = uint8_t(tmp.r + 0.001f); - ret.g = uint8_t(tmp.g + 0.001f); - ret.b = uint8_t(tmp.b + 0.001f); - ret.a = uint8_t(tmp.a + 0.001f); - return ret; -} - -struct LDREndPntPair -{ - LDRColorA A; - LDRColorA B; -}; - -struct HDREndPntPair -{ - HDRColorA A; - HDRColorA B; -}; - -inline HDRColorA* HDRColorALerp(_Out_ HDRColorA *pOut, _In_ const HDRColorA *pC1, _In_ const HDRColorA *pC2, _In_ float s) -{ - pOut->r = pC1->r + s * (pC2->r - pC1->r); - pOut->g = pC1->g + s * (pC2->g - pC1->g); - pOut->b = pC1->b + s * (pC2->b - pC1->b); - pOut->a = pC1->a + s * (pC2->a - pC1->a); - return pOut; -} - -#pragma pack(push,1) -// BC1/DXT1 compression (4 bits per texel) -struct D3DX_BC1 -{ - uint16_t rgb[2]; // 565 colors - uint32_t bitmap; // 2bpp rgb bitmap -}; - -// BC2/DXT2/3 compression (8 bits per texel) -struct D3DX_BC2 -{ - uint32_t bitmap[2]; // 4bpp alpha bitmap - D3DX_BC1 bc1; // BC1 rgb data -}; - -// BC3/DXT4/5 compression (8 bits per texel) -struct D3DX_BC3 -{ - uint8_t alpha[2]; // alpha values - uint8_t bitmap[6]; // 3bpp alpha bitmap - D3DX_BC1 bc1; // BC1 rgb data -}; -#pragma pack(pop) - -class INTColor -{ -public: - int r, g, b; - int pad; - -public: - INTColor() DIRECTX_CTOR_DEFAULT - INTColor(int nr, int ng, int nb) {r = nr; g = ng; b = nb;} - INTColor(const INTColor& c) {r = c.r; g = c.g; b = c.b;} - - INTColor operator - ( _In_ const INTColor& c ) const - { - return INTColor(r - c.r, g - c.g, b - c.b); - } - - INTColor& operator += ( _In_ const INTColor& c ) - { - r += c.r; - g += c.g; - b += c.b; - return *this; - } - - INTColor& operator -= ( _In_ const INTColor& c ) - { - r -= c.r; - g -= c.g; - b -= c.b; - return *this; - } - - INTColor& operator &= ( _In_ const INTColor& c ) - { - r &= c.r; - g &= c.g; - b &= c.b; - return *this; - } - - int& operator [] ( _In_ uint8_t i ) - { - assert(i < sizeof(INTColor) / sizeof(int)); - _Analysis_assume_(i < sizeof(INTColor) / sizeof(int)); - return ((int*) this)[i]; - } - - void Set(_In_ const HDRColorA& c, _In_ bool bSigned) - { - PackedVector::XMHALF4 aF16; - - XMVECTOR v = XMLoadFloat4( (const XMFLOAT4*)& c ); - XMStoreHalf4( &aF16, v ); - - r = F16ToINT(aF16.x, bSigned); - g = F16ToINT(aF16.y, bSigned); - b = F16ToINT(aF16.z, bSigned); - } - - INTColor& Clamp(_In_ int iMin, _In_ int iMax) - { - r = std::min(iMax, std::max(iMin, r)); - g = std::min(iMax, std::max(iMin, g)); - b = std::min(iMax, std::max(iMin, b)); - return *this; - } - - INTColor& SignExtend(_In_ const LDRColorA& Prec) - { - r = SIGN_EXTEND(r, Prec.r); - g = SIGN_EXTEND(g, Prec.g); - b = SIGN_EXTEND(b, Prec.b); - return *this; - } - - void ToF16(_Out_writes_(3) PackedVector::HALF aF16[3], _In_ bool bSigned) const - { - aF16[0] = INT2F16(r, bSigned); - aF16[1] = INT2F16(g, bSigned); - aF16[2] = INT2F16(b, bSigned); - } - -private: - static int F16ToINT(_In_ const PackedVector::HALF& f, _In_ bool bSigned) - { - uint16_t input = *((const uint16_t*) &f); - int out, s; - if(bSigned) - { - s = input & F16S_MASK; - input &= F16EM_MASK; - if(input > F16MAX) out = F16MAX; - else out = input; - out = s ? -out : out; - } - else - { - if(input & F16S_MASK) out = 0; - else out = input; - } - return out; - } - - static PackedVector::HALF INT2F16(_In_ int input, _In_ bool bSigned) - { - PackedVector::HALF h; - uint16_t out; - if(bSigned) - { - int s = 0; - if(input < 0) - { - s = F16S_MASK; - input = -input; - } - out = uint16_t(s | input); - } - else - { - assert(input >= 0 && input <= F16MAX); - out = (uint16_t) input; - } - - *((uint16_t*) &h) = out; - return h; - } -}; - -static_assert( sizeof(INTColor) == 16, "Unexpected packing"); - -struct INTEndPntPair -{ - INTColor A; - INTColor B; -}; - -template< size_t SizeInBytes > -class CBits -{ -public: - uint8_t GetBit(_Inout_ size_t& uStartBit) const - { - assert(uStartBit < 128); - _Analysis_assume_(uStartBit < 128); - size_t uIndex = uStartBit >> 3; - uint8_t ret = (m_uBits[uIndex] >> (uStartBit - (uIndex << 3))) & 0x01; - uStartBit++; - return ret; - } - - uint8_t GetBits(_Inout_ size_t& uStartBit, _In_ size_t uNumBits) const - { - if(uNumBits == 0) return 0; - assert(uStartBit + uNumBits <= 128 && uNumBits <= 8); - _Analysis_assume_(uStartBit + uNumBits <= 128 && uNumBits <= 8); - uint8_t ret; - size_t uIndex = uStartBit >> 3; - size_t uBase = uStartBit - (uIndex << 3); - if(uBase + uNumBits > 8) - { - size_t uFirstIndexBits = 8 - uBase; - size_t uNextIndexBits = uNumBits - uFirstIndexBits; - ret = (m_uBits[uIndex] >> uBase) | ((m_uBits[uIndex+1] & ((1 << uNextIndexBits) - 1)) << uFirstIndexBits); - } - else - { - ret = (m_uBits[uIndex] >> uBase) & ((1 << uNumBits) - 1); - } - assert(ret < (1 << uNumBits)); - uStartBit += uNumBits; - return ret; - } - - void SetBit(_Inout_ size_t& uStartBit, _In_ uint8_t uValue) - { - assert(uStartBit < 128 && uValue < 2); - _Analysis_assume_(uStartBit < 128 && uValue < 2); - size_t uIndex = uStartBit >> 3; - size_t uBase = uStartBit - (uIndex << 3); - m_uBits[uIndex] &= ~(1 << uBase); - m_uBits[uIndex] |= uValue << uBase; - uStartBit++; - } - - void SetBits(_Inout_ size_t& uStartBit, _In_ size_t uNumBits, _In_ uint8_t uValue) - { - if(uNumBits == 0) - return; - assert(uStartBit + uNumBits <= 128 && uNumBits <= 8); - _Analysis_assume_(uStartBit + uNumBits <= 128 && uNumBits <= 8); - assert(uValue < (1 << uNumBits)); - size_t uIndex = uStartBit >> 3; - size_t uBase = uStartBit - (uIndex << 3); - if(uBase + uNumBits > 8) - { - size_t uFirstIndexBits = 8 - uBase; - size_t uNextIndexBits = uNumBits - uFirstIndexBits; - m_uBits[uIndex] &= ~(((1 << uFirstIndexBits) - 1) << uBase); - m_uBits[uIndex] |= uValue << uBase; - m_uBits[uIndex+1] &= ~((1 << uNextIndexBits) - 1); - m_uBits[uIndex+1] |= uValue >> uFirstIndexBits; - } - else - { - m_uBits[uIndex] &= ~(((1 << uNumBits) - 1) << uBase); - m_uBits[uIndex] |= uValue << uBase; - } - uStartBit += uNumBits; - } - -private: - uint8_t m_uBits[ SizeInBytes ]; -}; - -// BC6H compression (16 bits per texel) -class D3DX_BC6H : private CBits< 16 > -{ -public: - void Decode(_In_ bool bSigned, _Out_writes_(NUM_PIXELS_PER_BLOCK) HDRColorA* pOut) const; - void Encode(_In_ bool bSigned, _In_reads_(NUM_PIXELS_PER_BLOCK) const HDRColorA* const pIn); - -private: -#pragma warning(push) -#pragma warning(disable : 4480) - enum EField : uint8_t - { - NA, // N/A - M, // Mode - D, // Shape - RW, - RX, - RY, - RZ, - GW, - GX, - GY, - GZ, - BW, - BX, - BY, - BZ, - }; -#pragma warning(pop) - - struct ModeDescriptor - { - EField m_eField; - uint8_t m_uBit; - }; - - struct ModeInfo - { - uint8_t uMode; - uint8_t uPartitions; - bool bTransformed; - uint8_t uIndexPrec; - LDRColorA RGBAPrec[BC6H_MAX_REGIONS][2]; - }; - -#pragma warning(push) -#pragma warning(disable : 4512) - struct EncodeParams - { - float fBestErr; - const bool bSigned; - uint8_t uMode; - uint8_t uShape; - const HDRColorA* const aHDRPixels; - INTEndPntPair aUnqEndPts[BC6H_MAX_SHAPES][BC6H_MAX_REGIONS]; - INTColor aIPixels[NUM_PIXELS_PER_BLOCK]; - - EncodeParams(const HDRColorA* const aOriginal, bool bSignedFormat) : - aHDRPixels(aOriginal), fBestErr(FLT_MAX), bSigned(bSignedFormat) - { - for(size_t i = 0; i < NUM_PIXELS_PER_BLOCK; ++i) - { - aIPixels[i].Set(aOriginal[i], bSigned); - } - } - }; -#pragma warning(pop) - - static int Quantize(_In_ int iValue, _In_ int prec, _In_ bool bSigned); - static int Unquantize(_In_ int comp, _In_ uint8_t uBitsPerComp, _In_ bool bSigned); - static int FinishUnquantize(_In_ int comp, _In_ bool bSigned); - - static bool EndPointsFit(_In_ const EncodeParams* pEP, _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aEndPts[]); - - void GeneratePaletteQuantized(_In_ const EncodeParams* pEP, _In_ const INTEndPntPair& endPts, - _Out_writes_(BC6H_MAX_INDICES) INTColor aPalette[]) const; - float MapColorsQuantized(_In_ const EncodeParams* pEP, _In_reads_(np) const INTColor aColors[], _In_ size_t np, _In_ const INTEndPntPair &endPts) const; - float PerturbOne(_In_ const EncodeParams* pEP, _In_reads_(np) const INTColor aColors[], _In_ size_t np, _In_ uint8_t ch, - _In_ const INTEndPntPair& oldEndPts, _Out_ INTEndPntPair& newEndPts, _In_ float fOldErr, _In_ int do_b) const; - void OptimizeOne(_In_ const EncodeParams* pEP, _In_reads_(np) const INTColor aColors[], _In_ size_t np, _In_ float aOrgErr, - _In_ const INTEndPntPair &aOrgEndPts, _Out_ INTEndPntPair &aOptEndPts) const; - void OptimizeEndPoints(_In_ const EncodeParams* pEP, _In_reads_(BC6H_MAX_REGIONS) const float aOrgErr[], - _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aOrgEndPts[], - _Out_writes_all_(BC6H_MAX_REGIONS) INTEndPntPair aOptEndPts[]) const; - static void SwapIndices(_In_ const EncodeParams* pEP, _Inout_updates_all_(BC6H_MAX_REGIONS) INTEndPntPair aEndPts[], - _In_reads_(NUM_PIXELS_PER_BLOCK) size_t aIndices[]); - void AssignIndices(_In_ const EncodeParams* pEP, _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aEndPts[], - _Out_writes_(NUM_PIXELS_PER_BLOCK) size_t aIndices[], - _Out_writes_(BC6H_MAX_REGIONS) float aTotErr[]) const; - void QuantizeEndPts(_In_ const EncodeParams* pEP, _Out_writes_(BC6H_MAX_REGIONS) INTEndPntPair* qQntEndPts) const; - void EmitBlock(_In_ const EncodeParams* pEP, _In_reads_(BC6H_MAX_REGIONS) const INTEndPntPair aEndPts[], - _In_reads_(NUM_PIXELS_PER_BLOCK) const size_t aIndices[]); - void Refine(_Inout_ EncodeParams* pEP); - - static void GeneratePaletteUnquantized(_In_ const EncodeParams* pEP, _In_ size_t uRegion, _Out_writes_(BC6H_MAX_INDICES) INTColor aPalette[]); - float MapColors(_In_ const EncodeParams* pEP, _In_ size_t uRegion, _In_ size_t np, _In_reads_(np) const size_t* auIndex) const; - float RoughMSE(_Inout_ EncodeParams* pEP) const; - -private: - const static ModeDescriptor ms_aDesc[][82]; - const static ModeInfo ms_aInfo[]; - const static int ms_aModeToInfo[]; -}; - -// BC67 compression (16b bits per texel) -class D3DX_BC7 : private CBits< 16 > -{ -public: - void Decode(_Out_writes_(NUM_PIXELS_PER_BLOCK) HDRColorA* pOut) const; - void Encode(bool skip3subsets, _In_reads_(NUM_PIXELS_PER_BLOCK) const HDRColorA* const pIn); - -private: - struct ModeInfo - { - uint8_t uPartitions; - uint8_t uPartitionBits; - uint8_t uPBits; - uint8_t uRotationBits; - uint8_t uIndexModeBits; - uint8_t uIndexPrec; - uint8_t uIndexPrec2; - LDRColorA RGBAPrec; - LDRColorA RGBAPrecWithP; - }; - -#pragma warning(push) -#pragma warning(disable : 4512) - struct EncodeParams - { - uint8_t uMode; - LDREndPntPair aEndPts[BC7_MAX_SHAPES][BC7_MAX_REGIONS]; - LDRColorA aLDRPixels[NUM_PIXELS_PER_BLOCK]; - const HDRColorA* const aHDRPixels; - - EncodeParams(const HDRColorA* const aOriginal) : aHDRPixels(aOriginal) {} - }; -#pragma warning(pop) - - static uint8_t Quantize(_In_ uint8_t comp, _In_ uint8_t uPrec) - { - assert(0 < uPrec && uPrec <= 8); - uint8_t rnd = (uint8_t) std::min(255, uint16_t(comp) + (1 << (7 - uPrec))); - return rnd >> (8 - uPrec); - } - - static LDRColorA Quantize(_In_ const LDRColorA& c, _In_ const LDRColorA& RGBAPrec) - { - LDRColorA q; - q.r = Quantize(c.r, RGBAPrec.r); - q.g = Quantize(c.g, RGBAPrec.g); - q.b = Quantize(c.b, RGBAPrec.b); - if(RGBAPrec.a) - q.a = Quantize(c.a, RGBAPrec.a); - else - q.a = 255; - return q; - } - - static uint8_t Unquantize(_In_ uint8_t comp, _In_ size_t uPrec) - { - assert(0 < uPrec && uPrec <= 8); - comp = comp << (8 - uPrec); - return comp | (comp >> uPrec); - } - - static LDRColorA Unquantize(_In_ const LDRColorA& c, _In_ const LDRColorA& RGBAPrec) - { - LDRColorA q; - q.r = Unquantize(c.r, RGBAPrec.r); - q.g = Unquantize(c.g, RGBAPrec.g); - q.b = Unquantize(c.b, RGBAPrec.b); - q.a = RGBAPrec.a > 0 ? Unquantize(c.a, RGBAPrec.a) : 255; - return q; - } - - void GeneratePaletteQuantized(_In_ const EncodeParams* pEP, _In_ size_t uIndexMode, _In_ const LDREndPntPair& endpts, - _Out_writes_(BC7_MAX_INDICES) LDRColorA aPalette[]) const; - float PerturbOne(_In_ const EncodeParams* pEP, _In_reads_(np) const LDRColorA colors[], _In_ size_t np, _In_ size_t uIndexMode, - _In_ size_t ch, _In_ const LDREndPntPair &old_endpts, - _Out_ LDREndPntPair &new_endpts, _In_ float old_err, _In_ uint8_t do_b) const; - void Exhaustive(_In_ const EncodeParams* pEP, _In_reads_(np) const LDRColorA aColors[], _In_ size_t np, _In_ size_t uIndexMode, - _In_ size_t ch, _Inout_ float& fOrgErr, _Inout_ LDREndPntPair& optEndPt) const; - void OptimizeOne(_In_ const EncodeParams* pEP, _In_reads_(np) const LDRColorA colors[], _In_ size_t np, _In_ size_t uIndexMode, - _In_ float orig_err, _In_ const LDREndPntPair &orig_endpts, _Out_ LDREndPntPair &opt_endpts) const; - void OptimizeEndPoints(_In_ const EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uIndexMode, - _In_reads_(BC7_MAX_REGIONS) const float orig_err[], - _In_reads_(BC7_MAX_REGIONS) const LDREndPntPair orig_endpts[], - _Out_writes_(BC7_MAX_REGIONS) LDREndPntPair opt_endpts[]) const; - void AssignIndices(_In_ const EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uIndexMode, - _In_reads_(BC7_MAX_REGIONS) LDREndPntPair endpts[], - _Out_writes_(NUM_PIXELS_PER_BLOCK) size_t aIndices[], _Out_writes_(NUM_PIXELS_PER_BLOCK) size_t aIndices2[], - _Out_writes_(BC7_MAX_REGIONS) float afTotErr[]) const; - void EmitBlock(_In_ const EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uRotation, _In_ size_t uIndexMode, - _In_reads_(BC7_MAX_REGIONS) const LDREndPntPair aEndPts[], - _In_reads_(NUM_PIXELS_PER_BLOCK) const size_t aIndex[], - _In_reads_(NUM_PIXELS_PER_BLOCK) const size_t aIndex2[]); - float Refine(_In_ const EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uRotation, _In_ size_t uIndexMode); - - float MapColors(_In_ const EncodeParams* pEP, _In_reads_(np) const LDRColorA aColors[], _In_ size_t np, _In_ size_t uIndexMode, - _In_ const LDREndPntPair& endPts, _In_ float fMinErr) const; - static float RoughMSE(_Inout_ EncodeParams* pEP, _In_ size_t uShape, _In_ size_t uIndexMode); - -private: - const static ModeInfo ms_aInfo[]; -}; - -//------------------------------------------------------------------------------------- -#pragma warning(push) -#pragma warning(disable : 4127) -template void OptimizeAlpha(float *pX, float *pY, const float *pPoints, size_t cSteps) -{ - static const float pC6[] = { 5.0f/5.0f, 4.0f/5.0f, 3.0f/5.0f, 2.0f/5.0f, 1.0f/5.0f, 0.0f/5.0f }; - static const float pD6[] = { 0.0f/5.0f, 1.0f/5.0f, 2.0f/5.0f, 3.0f/5.0f, 4.0f/5.0f, 5.0f/5.0f }; - static const float pC8[] = { 7.0f/7.0f, 6.0f/7.0f, 5.0f/7.0f, 4.0f/7.0f, 3.0f/7.0f, 2.0f/7.0f, 1.0f/7.0f, 0.0f/7.0f }; - static const float pD8[] = { 0.0f/7.0f, 1.0f/7.0f, 2.0f/7.0f, 3.0f/7.0f, 4.0f/7.0f, 5.0f/7.0f, 6.0f/7.0f, 7.0f/7.0f }; - - const float *pC = (6 == cSteps) ? pC6 : pC8; - const float *pD = (6 == cSteps) ? pD6 : pD8; - - float MAX_VALUE = 1.0f; - float MIN_VALUE; - if (bRange) - { - MIN_VALUE = -1.0f; - } - else - { - MIN_VALUE = 0.0f; - } - - // Find Min and Max points, as starting point - float fX = MAX_VALUE; - float fY = MIN_VALUE; - - if(8 == cSteps) - { - for(size_t iPoint = 0; iPoint < NUM_PIXELS_PER_BLOCK; iPoint++) - { - if(pPoints[iPoint] < fX) - fX = pPoints[iPoint]; - - if(pPoints[iPoint] > fY) - fY = pPoints[iPoint]; - } - } - else - { - for(size_t iPoint = 0; iPoint < NUM_PIXELS_PER_BLOCK; iPoint++) - { - if(pPoints[iPoint] < fX && pPoints[iPoint] > MIN_VALUE) - fX = pPoints[iPoint]; - - if(pPoints[iPoint] > fY && pPoints[iPoint] < MAX_VALUE) - fY = pPoints[iPoint]; - } - - if (fX == fY) - { - fY = MAX_VALUE; - } - } - - // Use Newton's Method to find local minima of sum-of-squares error. - float fSteps = (float) (cSteps - 1); - - for(size_t iIteration = 0; iIteration < 8; iIteration++) - { - float fScale; - - if((fY - fX) < (1.0f / 256.0f)) - break; - - fScale = fSteps / (fY - fX); - - // Calculate new steps - float pSteps[8]; - - for(size_t iStep = 0; iStep < cSteps; iStep++) - pSteps[iStep] = pC[iStep] * fX + pD[iStep] * fY; - - if(6 == cSteps) - { - pSteps[6] = MIN_VALUE; - pSteps[7] = MAX_VALUE; - } - - // Evaluate function, and derivatives - float dX = 0.0f; - float dY = 0.0f; - float d2X = 0.0f; - float d2Y = 0.0f; - - for(size_t iPoint = 0; iPoint < NUM_PIXELS_PER_BLOCK; iPoint++) - { - float fDot = (pPoints[iPoint] - fX) * fScale; - - size_t iStep; - - if(fDot <= 0.0f) - iStep = ((6 == cSteps) && (pPoints[iPoint] <= fX * 0.5f)) ? 6 : 0; - else if(fDot >= fSteps) - iStep = ((6 == cSteps) && (pPoints[iPoint] >= (fY + 1.0f) * 0.5f)) ? 7 : (cSteps - 1); - else - iStep = static_cast(fDot + 0.5f); - - - if(iStep < cSteps) - { - // D3DX had this computation backwards (pPoints[iPoint] - pSteps[iStep]) - // this fix improves RMS of the alpha component - float fDiff = pSteps[iStep] - pPoints[iPoint]; - - dX += pC[iStep] * fDiff; - d2X += pC[iStep] * pC[iStep]; - - dY += pD[iStep] * fDiff; - d2Y += pD[iStep] * pD[iStep]; - } - } - - // Move endpoints - if(d2X > 0.0f) - fX -= dX / d2X; - - if(d2Y > 0.0f) - fY -= dY / d2Y; - - if(fX > fY) - { - float f = fX; fX = fY; fY = f; - } - - if((dX * dX < (1.0f / 64.0f)) && (dY * dY < (1.0f / 64.0f))) - break; - } - - *pX = (fX < MIN_VALUE) ? MIN_VALUE : (fX > MAX_VALUE) ? MAX_VALUE : fX; - *pY = (fY < MIN_VALUE) ? MIN_VALUE : (fY > MAX_VALUE) ? MAX_VALUE : fY; -} -#pragma warning(pop) - - -//------------------------------------------------------------------------------------- -// Functions -//------------------------------------------------------------------------------------- - -typedef void (*BC_DECODE)(XMVECTOR *pColor, const uint8_t *pBC); -typedef void (*BC_ENCODE)(uint8_t *pDXT, const XMVECTOR *pColor, DWORD flags); - -void D3DXDecodeBC1(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(8) const uint8_t *pBC); -void D3DXDecodeBC2(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC); -void D3DXDecodeBC3(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC); -void D3DXDecodeBC4U(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(8) const uint8_t *pBC); -void D3DXDecodeBC4S(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(8) const uint8_t *pBC); -void D3DXDecodeBC5U(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC); -void D3DXDecodeBC5S(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC); -void D3DXDecodeBC6HU(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC); -void D3DXDecodeBC6HS(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC); -void D3DXDecodeBC7(_Out_writes_(NUM_PIXELS_PER_BLOCK) XMVECTOR *pColor, _In_reads_(16) const uint8_t *pBC); - -void D3DXEncodeBC1(_Out_writes_(8) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ float alphaRef, _In_ DWORD flags); - // BC1 requires one additional parameter, so it doesn't match signature of BC_ENCODE above - -void D3DXEncodeBC2(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags); -void D3DXEncodeBC3(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags); -void D3DXEncodeBC4U(_Out_writes_(8) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags); -void D3DXEncodeBC4S(_Out_writes_(8) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags); -void D3DXEncodeBC5U(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags); -void D3DXEncodeBC5S(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags); -void D3DXEncodeBC6HU(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags); -void D3DXEncodeBC6HS(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags); -void D3DXEncodeBC7(_Out_writes_(16) uint8_t *pBC, _In_reads_(NUM_PIXELS_PER_BLOCK) const XMVECTOR *pColor, _In_ DWORD flags); - -}; // namespace diff --git a/Externals/DirectXTex Aug 2015/Include/BCDirectCompute.h b/Externals/DirectXTex Aug 2015/Include/BCDirectCompute.h deleted file mode 100644 index 8bbfa75..0000000 --- a/Externals/DirectXTex Aug 2015/Include/BCDirectCompute.h +++ /dev/null @@ -1,67 +0,0 @@ -//------------------------------------------------------------------------------------- -// BCDirectCompute.h -// -// Direct3D 11 Compute Shader BC Compressor -// -// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -// PARTICULAR PURPOSE. -// -// Copyright (c) Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------------- - -#pragma once - -namespace DirectX -{ - -class GPUCompressBC -{ -public: - GPUCompressBC(); - - HRESULT Initialize( _In_ ID3D11Device* pDevice ); - - HRESULT Prepare( _In_ size_t width, _In_ size_t height, _In_ DXGI_FORMAT format, _In_ float alphaWeight = 1.f, _In_ bool skip3subsets = true ); - - HRESULT Compress( _In_ const Image& srcImage, _In_ const Image& destImage ); - - DXGI_FORMAT GetSourceFormat() const { return m_srcformat; } - -private: - DXGI_FORMAT m_bcformat; - DXGI_FORMAT m_srcformat; - float m_alphaWeight; - bool m_skip3Subsets; - size_t m_width; - size_t m_height; - - Microsoft::WRL::ComPtr m_device; - Microsoft::WRL::ComPtr m_context; - - Microsoft::WRL::ComPtr m_err1; - Microsoft::WRL::ComPtr m_err1UAV; - Microsoft::WRL::ComPtr m_err1SRV; - - Microsoft::WRL::ComPtr m_err2; - Microsoft::WRL::ComPtr m_err2UAV; - Microsoft::WRL::ComPtr m_err2SRV; - - Microsoft::WRL::ComPtr m_output; - Microsoft::WRL::ComPtr m_outputCPU; - Microsoft::WRL::ComPtr m_outputUAV; - Microsoft::WRL::ComPtr m_constBuffer; - - // Compute shader library - Microsoft::WRL::ComPtr m_BC6H_tryModeG10CS; - Microsoft::WRL::ComPtr m_BC6H_tryModeLE10CS; - Microsoft::WRL::ComPtr m_BC6H_encodeBlockCS; - - Microsoft::WRL::ComPtr m_BC7_tryMode456CS; - Microsoft::WRL::ComPtr m_BC7_tryMode137CS; - Microsoft::WRL::ComPtr m_BC7_tryMode02CS; - Microsoft::WRL::ComPtr m_BC7_encodeBlockCS; -}; - -}; // namespace \ No newline at end of file diff --git a/Externals/DirectXTex Aug 2015/Include/DDS.h b/Externals/DirectXTex Aug 2015/Include/DDS.h deleted file mode 100644 index 4d74620..0000000 --- a/Externals/DirectXTex Aug 2015/Include/DDS.h +++ /dev/null @@ -1,237 +0,0 @@ -//-------------------------------------------------------------------------------------- -// dds.h -// -// This header defines constants and structures that are useful when parsing -// DDS files. DDS files were originally designed to use several structures -// and constants that are native to DirectDraw and are defined in ddraw.h, -// such as DDSURFACEDESC2 and DDSCAPS2. This file defines similar -// (compatible) constants and structures so that one can use DDS files -// without needing to include ddraw.h. -// -// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -// PARTICULAR PURPOSE. -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// http://go.microsoft.com/fwlink/?LinkId=248926 -//-------------------------------------------------------------------------------------- - -#pragma once - -#if defined(_XBOX_ONE) && defined(_TITLE) -#include -#else -#include -#endif - -// VS 2010's stdint.h conflicts with intsafe.h -#pragma warning(push) -#pragma warning(disable : 4005) -#include -#pragma warning(pop) - -namespace DirectX -{ - -#pragma pack(push,1) - -const uint32_t DDS_MAGIC = 0x20534444; // "DDS " - -struct DDS_PIXELFORMAT -{ - uint32_t dwSize; - uint32_t dwFlags; - uint32_t dwFourCC; - uint32_t dwRGBBitCount; - uint32_t dwRBitMask; - uint32_t dwGBitMask; - uint32_t dwBBitMask; - uint32_t dwABitMask; -}; - -#define DDS_FOURCC 0x00000004 // DDPF_FOURCC -#define DDS_RGB 0x00000040 // DDPF_RGB -#define DDS_RGBA 0x00000041 // DDPF_RGB | DDPF_ALPHAPIXELS -#define DDS_LUMINANCE 0x00020000 // DDPF_LUMINANCE -#define DDS_LUMINANCEA 0x00020001 // DDPF_LUMINANCE | DDPF_ALPHAPIXELS -#define DDS_ALPHA 0x00000002 // DDPF_ALPHA -#define DDS_PAL8 0x00000020 // DDPF_PALETTEINDEXED8 - -#ifndef MAKEFOURCC - #define MAKEFOURCC(ch0, ch1, ch2, ch3) \ - ((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) | \ - ((uint32_t)(uint8_t)(ch2) << 16) | ((uint32_t)(uint8_t)(ch3) << 24 )) -#endif /* defined(MAKEFOURCC) */ - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT1 = - { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','1'), 0, 0, 0, 0, 0 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT2 = - { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','2'), 0, 0, 0, 0, 0 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT3 = - { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','3'), 0, 0, 0, 0, 0 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT4 = - { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','4'), 0, 0, 0, 0, 0 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT5 = - { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','5'), 0, 0, 0, 0, 0 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_UNORM = - { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','U'), 0, 0, 0, 0, 0 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_SNORM = - { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','S'), 0, 0, 0, 0, 0 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_UNORM = - { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','U'), 0, 0, 0, 0, 0 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_SNORM = - { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','S'), 0, 0, 0, 0, 0 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8_B8G8 = - { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('R','G','B','G'), 0, 0, 0, 0, 0 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G8R8_G8B8 = - { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('G','R','G','B'), 0, 0, 0, 0, 0 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_YUY2 = - { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('Y','U','Y','2'), 0, 0, 0, 0, 0 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8R8G8B8 = - { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8R8G8B8 = - { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8B8G8R8 = - { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8B8G8R8 = - { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G16R16 = - { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x0000ffff, 0xffff0000, 0x00000000, 0x00000000 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R5G6B5 = - { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0x0000f800, 0x000007e0, 0x0000001f, 0x00000000 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A1R5G5B5 = - { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00007c00, 0x000003e0, 0x0000001f, 0x00008000 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A4R4G4B4 = - { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00000f00, 0x000000f0, 0x0000000f, 0x0000f000 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8B8 = - { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 24, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L8 = - { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 8, 0xff, 0x00, 0x00, 0x00 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L16 = - { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 16, 0xffff, 0x0000, 0x0000, 0x0000 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8L8 = - { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 16, 0x00ff, 0x0000, 0x0000, 0xff00 }; - -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8 = - { sizeof(DDS_PIXELFORMAT), DDS_ALPHA, 0, 8, 0x00, 0x00, 0x00, 0xff }; - -// D3DFMT_A2R10G10B10/D3DFMT_A2B10G10R10 should be written using DX10 extension to avoid D3DX 10:10:10:2 reversal issue - -// This indicates the DDS_HEADER_DXT10 extension is present (the format is in dxgiFormat) -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DX10 = - { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','1','0'), 0, 0, 0, 0, 0 }; - -#define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT -#define DDS_HEADER_FLAGS_MIPMAP 0x00020000 // DDSD_MIPMAPCOUNT -#define DDS_HEADER_FLAGS_VOLUME 0x00800000 // DDSD_DEPTH -#define DDS_HEADER_FLAGS_PITCH 0x00000008 // DDSD_PITCH -#define DDS_HEADER_FLAGS_LINEARSIZE 0x00080000 // DDSD_LINEARSIZE - -#define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT -#define DDS_WIDTH 0x00000004 // DDSD_WIDTH - -#define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE -#define DDS_SURFACE_FLAGS_MIPMAP 0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP -#define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX - -#define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX -#define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX -#define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY -#define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY -#define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ -#define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ - -#define DDS_CUBEMAP_ALLFACES ( DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\ - DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\ - DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ ) - -#define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP - -#define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME - -// Subset here matches D3D10_RESOURCE_DIMENSION and D3D11_RESOURCE_DIMENSION -enum DDS_RESOURCE_DIMENSION -{ - DDS_DIMENSION_TEXTURE1D = 2, - DDS_DIMENSION_TEXTURE2D = 3, - DDS_DIMENSION_TEXTURE3D = 4, -}; - -// Subset here matches D3D10_RESOURCE_MISC_FLAG and D3D11_RESOURCE_MISC_FLAG -enum DDS_RESOURCE_MISC_FLAG -{ - DDS_RESOURCE_MISC_TEXTURECUBE = 0x4L, -}; - -enum DDS_MISC_FLAGS2 -{ - DDS_MISC_FLAGS2_ALPHA_MODE_MASK = 0x7L, -}; - -enum DDS_ALPHA_MODE -{ - DDS_ALPHA_MODE_UNKNOWN = 0, - DDS_ALPHA_MODE_STRAIGHT = 1, - DDS_ALPHA_MODE_PREMULTIPLIED = 2, - DDS_ALPHA_MODE_OPAQUE = 3, - DDS_ALPHA_MODE_CUSTOM = 4, -}; - -struct DDS_HEADER -{ - uint32_t dwSize; - uint32_t dwFlags; - uint32_t dwHeight; - uint32_t dwWidth; - uint32_t dwPitchOrLinearSize; - uint32_t dwDepth; // only if DDS_HEADER_FLAGS_VOLUME is set in dwFlags - uint32_t dwMipMapCount; - uint32_t dwReserved1[11]; - DDS_PIXELFORMAT ddspf; - uint32_t dwCaps; - uint32_t dwCaps2; - uint32_t dwCaps3; - uint32_t dwCaps4; - uint32_t dwReserved2; -}; - -struct DDS_HEADER_DXT10 -{ - DXGI_FORMAT dxgiFormat; - uint32_t resourceDimension; - uint32_t miscFlag; // see DDS_RESOURCE_MISC_FLAG - uint32_t arraySize; - uint32_t miscFlags2; // see DDS_MISC_FLAGS2 -}; - -#pragma pack(pop) - -static_assert( sizeof(DDS_HEADER) == 124, "DDS Header size mismatch" ); -static_assert( sizeof(DDS_HEADER_DXT10) == 20, "DDS DX10 Extended Header size mismatch"); - -}; // namespace diff --git a/Externals/DirectXTex Aug 2015/Include/DirectXTexP.h b/Externals/DirectXTex Aug 2015/Include/DirectXTexP.h deleted file mode 100644 index ac2244f..0000000 --- a/Externals/DirectXTex Aug 2015/Include/DirectXTexP.h +++ /dev/null @@ -1,231 +0,0 @@ -//------------------------------------------------------------------------------------- -// DirectXTexp.h -// -// DirectX Texture Library - Private header -// -// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -// PARTICULAR PURPOSE. -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// http://go.microsoft.com/fwlink/?LinkId=248926 -//------------------------------------------------------------------------------------- - -#pragma once - -#if !defined(WIN32_LEAN_AND_MEAN) -#define WIN32_LEAN_AND_MEAN -#endif - -#if !defined(NOMINMAX) -#define NOMINMAX -#endif - -#ifndef _WIN32_WINNT_WIN10 -#define _WIN32_WINNT_WIN10 0x0A00 -#endif - -#include -#include -#include -#include - -#include -#include - -#include - -#include -#include - -#include - -#include "directxtex.h" - -// VS 2010's stdint.h conflicts with intsafe.h -#pragma warning(push) -#pragma warning(disable : 4005) -#include -#include -#pragma warning(pop) - -#include - -#include "scoped.h" - -#define TEX_FILTER_MASK 0xF00000 - -#define XBOX_DXGI_FORMAT_R10G10B10_7E3_A2_FLOAT DXGI_FORMAT(116) -#define XBOX_DXGI_FORMAT_R10G10B10_6E4_A2_FLOAT DXGI_FORMAT(117) -#define XBOX_DXGI_FORMAT_D16_UNORM_S8_UINT DXGI_FORMAT(118) -#define XBOX_DXGI_FORMAT_R16_UNORM_X8_TYPELESS DXGI_FORMAT(119) -#define XBOX_DXGI_FORMAT_X16_TYPELESS_G8_UINT DXGI_FORMAT(120) - -#define WIN10_DXGI_FORMAT_P208 DXGI_FORMAT(130) -#define WIN10_DXGI_FORMAT_V208 DXGI_FORMAT(131) -#define WIN10_DXGI_FORMAT_V408 DXGI_FORMAT(132) - -#ifndef XBOX_DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM -#define XBOX_DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM DXGI_FORMAT(189) -#endif - -#define XBOX_DXGI_FORMAT_R4G4_UNORM DXGI_FORMAT(190) - - -namespace DirectX -{ - //--------------------------------------------------------------------------------- - // WIC helper functions - DXGI_FORMAT __cdecl _WICToDXGI( _In_ const GUID& guid ); - bool __cdecl _DXGIToWIC( _In_ DXGI_FORMAT format, _Out_ GUID& guid, _In_ bool ignoreRGBvsBGR = false ); - - DWORD __cdecl _CheckWICColorSpace( _In_ const GUID& sourceGUID, _In_ const GUID& targetGUID ); - - inline WICBitmapDitherType __cdecl _GetWICDither( _In_ DWORD flags ) - { - static_assert( TEX_FILTER_DITHER == 0x10000, "TEX_FILTER_DITHER* flag values don't match mask" ); - - static_assert( TEX_FILTER_DITHER == WIC_FLAGS_DITHER, "TEX_FILTER_DITHER* should match WIC_FLAGS_DITHER*" ); - static_assert( TEX_FILTER_DITHER_DIFFUSION == WIC_FLAGS_DITHER_DIFFUSION, "TEX_FILTER_DITHER* should match WIC_FLAGS_DITHER*" ); - - switch( flags & 0xF0000 ) - { - case TEX_FILTER_DITHER: - return WICBitmapDitherTypeOrdered4x4; - - case TEX_FILTER_DITHER_DIFFUSION: - return WICBitmapDitherTypeErrorDiffusion; - - default: - return WICBitmapDitherTypeNone; - } - } - - inline WICBitmapInterpolationMode __cdecl _GetWICInterp( _In_ DWORD flags ) - { - static_assert( TEX_FILTER_POINT == 0x100000, "TEX_FILTER_ flag values don't match TEX_FILTER_MASK" ); - - static_assert( TEX_FILTER_POINT == WIC_FLAGS_FILTER_POINT, "TEX_FILTER_* flags should match WIC_FLAGS_FILTER_*" ); - static_assert( TEX_FILTER_LINEAR == WIC_FLAGS_FILTER_LINEAR, "TEX_FILTER_* flags should match WIC_FLAGS_FILTER_*" ); - static_assert( TEX_FILTER_CUBIC == WIC_FLAGS_FILTER_CUBIC, "TEX_FILTER_* flags should match WIC_FLAGS_FILTER_*" ); - static_assert( TEX_FILTER_FANT == WIC_FLAGS_FILTER_FANT, "TEX_FILTER_* flags should match WIC_FLAGS_FILTER_*" ); - - switch( flags & TEX_FILTER_MASK ) - { - case TEX_FILTER_POINT: - return WICBitmapInterpolationModeNearestNeighbor; - - case TEX_FILTER_LINEAR: - return WICBitmapInterpolationModeLinear; - - case TEX_FILTER_CUBIC: - return WICBitmapInterpolationModeCubic; - - case TEX_FILTER_FANT: - default: - return WICBitmapInterpolationModeFant; - } - } - - //--------------------------------------------------------------------------------- - // Image helper functions - void __cdecl _DetermineImageArray( _In_ const TexMetadata& metadata, _In_ DWORD cpFlags, - _Out_ size_t& nImages, _Out_ size_t& pixelSize ); - - _Success_(return != false) - bool __cdecl _SetupImageArray( _In_reads_bytes_(pixelSize) uint8_t *pMemory, _In_ size_t pixelSize, - _In_ const TexMetadata& metadata, _In_ DWORD cpFlags, - _Out_writes_(nImages) Image* images, _In_ size_t nImages ); - - //--------------------------------------------------------------------------------- - // Conversion helper functions - - enum TEXP_SCANLINE_FLAGS - { - TEXP_SCANLINE_NONE = 0, - TEXP_SCANLINE_SETALPHA = 0x1, // Set alpha channel to known opaque value - TEXP_SCANLINE_LEGACY = 0x2, // Enables specific legacy format conversion cases - }; - - enum CONVERT_FLAGS - { - CONVF_FLOAT = 0x1, - CONVF_UNORM = 0x2, - CONVF_UINT = 0x4, - CONVF_SNORM = 0x8, - CONVF_SINT = 0x10, - CONVF_DEPTH = 0x20, - CONVF_STENCIL = 0x40, - CONVF_SHAREDEXP = 0x80, - CONVF_BGR = 0x100, - CONVF_XR = 0x200, - CONVF_PACKED = 0x400, - CONVF_BC = 0x800, - CONVF_YUV = 0x1000, - CONVF_R = 0x10000, - CONVF_G = 0x20000, - CONVF_B = 0x40000, - CONVF_A = 0x80000, - CONVF_RGB_MASK = 0x70000, - CONVF_RGBA_MASK = 0xF0000, - }; - - DWORD __cdecl _GetConvertFlags( _In_ DXGI_FORMAT format ); - - void __cdecl _CopyScanline( _When_(pDestination == pSource, _Inout_updates_bytes_(outSize)) - _When_(pDestination != pSource, _Out_writes_bytes_(outSize)) - LPVOID pDestination, _In_ size_t outSize, - _In_reads_bytes_(inSize) LPCVOID pSource, _In_ size_t inSize, - _In_ DXGI_FORMAT format, _In_ DWORD flags ); - - void __cdecl _SwizzleScanline( _When_(pDestination == pSource, _In_) - _When_(pDestination != pSource, _Out_writes_bytes_(outSize)) - LPVOID pDestination, _In_ size_t outSize, - _In_reads_bytes_(inSize) LPCVOID pSource, _In_ size_t inSize, - _In_ DXGI_FORMAT format, _In_ DWORD flags ); - - _Success_(return != false) - bool __cdecl _ExpandScanline( _Out_writes_bytes_(outSize) LPVOID pDestination, _In_ size_t outSize, - _In_ DXGI_FORMAT outFormat, - _In_reads_bytes_(inSize) LPCVOID pSource, _In_ size_t inSize, - _In_ DXGI_FORMAT inFormat, _In_ DWORD flags ); - - _Success_(return != false) - bool __cdecl _LoadScanline( _Out_writes_(count) XMVECTOR* pDestination, _In_ size_t count, - _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, _In_ DXGI_FORMAT format ); - - _Success_(return != false) - bool __cdecl _LoadScanlineLinear( _Out_writes_(count) XMVECTOR* pDestination, _In_ size_t count, - _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, _In_ DXGI_FORMAT format, _In_ DWORD flags ); - - _Success_(return != false) - bool __cdecl _StoreScanline( LPVOID pDestination, _In_ size_t size, _In_ DXGI_FORMAT format, - _In_reads_(count) const XMVECTOR* pSource, _In_ size_t count, _In_ float threshold = 0 ); - - _Success_(return != false) - bool __cdecl _StoreScanlineLinear( LPVOID pDestination, _In_ size_t size, _In_ DXGI_FORMAT format, - _Inout_updates_all_(count) XMVECTOR* pSource, _In_ size_t count, _In_ DWORD flags, _In_ float threshold = 0 ); - - _Success_(return != false) - bool __cdecl _StoreScanlineDither( LPVOID pDestination, _In_ size_t size, _In_ DXGI_FORMAT format, - _Inout_updates_all_(count) XMVECTOR* pSource, _In_ size_t count, _In_ float threshold, size_t y, size_t z, - _Inout_updates_all_opt_(count+2) XMVECTOR* pDiffusionErrors ); - - HRESULT __cdecl _ConvertToR32G32B32A32( _In_ const Image& srcImage, _Inout_ ScratchImage& image ); - - HRESULT __cdecl _ConvertFromR32G32B32A32( _In_ const Image& srcImage, _In_ const Image& destImage ); - HRESULT __cdecl _ConvertFromR32G32B32A32( _In_ const Image& srcImage, _In_ DXGI_FORMAT format, _Inout_ ScratchImage& image ); - HRESULT __cdecl _ConvertFromR32G32B32A32( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata, - _In_ DXGI_FORMAT format, _Out_ ScratchImage& result ); - - void __cdecl _ConvertScanline( _Inout_updates_all_(count) XMVECTOR* pBuffer, _In_ size_t count, - _In_ DXGI_FORMAT outFormat, _In_ DXGI_FORMAT inFormat, _In_ DWORD flags ); - - //--------------------------------------------------------------------------------- - // DDS helper functions - HRESULT __cdecl _EncodeDDSHeader( _In_ const TexMetadata& metadata, DWORD flags, - _Out_writes_bytes_to_opt_(maxsize, required) LPVOID pDestination, _In_ size_t maxsize, _Out_ size_t& required ); - -}; // namespace diff --git a/Externals/DirectXTex Aug 2015/Include/Filters.h b/Externals/DirectXTex Aug 2015/Include/Filters.h deleted file mode 100644 index c65eb77..0000000 --- a/Externals/DirectXTex Aug 2015/Include/Filters.h +++ /dev/null @@ -1,422 +0,0 @@ -//------------------------------------------------------------------------------------- -// filters.h -// -// Utility header with helpers for implementing image filters -// -// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -// PARTICULAR PURPOSE. -// -// Copyright (c) Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------------- - -#pragma once - -#include -#include - -#include - -#include "scoped.h" - -namespace DirectX -{ - -//------------------------------------------------------------------------------------- -// Box filtering helpers -//------------------------------------------------------------------------------------- - -XMGLOBALCONST XMVECTORF32 g_boxScale = { 0.25f, 0.25f, 0.25f, 0.25f }; -XMGLOBALCONST XMVECTORF32 g_boxScale3D = { 0.125f, 0.125f, 0.125f, 0.125f }; - -#define AVERAGE4( res, p0, p1, p2, p3 ) \ -{ \ - XMVECTOR v = XMVectorAdd( (p0), (p1) ); \ - v = XMVectorAdd( v, (p2) ); \ - v = XMVectorAdd( v, (p3) ); \ - res = XMVectorMultiply( v, g_boxScale ); \ -} - -#define AVERAGE8( res, p0, p1, p2, p3, p4, p5, p6, p7) \ -{ \ - XMVECTOR v = XMVectorAdd( (p0), (p1) ); \ - v = XMVectorAdd( v, (p2) ); \ - v = XMVectorAdd( v, (p3) ); \ - v = XMVectorAdd( v, (p4) ); \ - v = XMVectorAdd( v, (p5) ); \ - v = XMVectorAdd( v, (p6) ); \ - v = XMVectorAdd( v, (p7) ); \ - res = XMVectorMultiply( v, g_boxScale3D ); \ -} - - -//------------------------------------------------------------------------------------- -// Linear filtering helpers -//------------------------------------------------------------------------------------- - -struct LinearFilter -{ - size_t u0; - float weight0; - size_t u1; - float weight1; -}; - -inline void _CreateLinearFilter( _In_ size_t source, _In_ size_t dest, _In_ bool wrap, _Out_writes_(dest) LinearFilter* lf ) -{ - assert( source > 0 ); - assert( dest > 0 ); - assert( lf != 0 ); - - float scale = float(source) / float(dest); - - // Mirror is the same case as clamp for linear - - for( size_t u = 0; u < dest; ++u ) - { - float srcB = ( float(u) + 0.5f ) * scale + 0.5f; - - ptrdiff_t isrcB = ptrdiff_t(srcB); - ptrdiff_t isrcA = isrcB - 1; - - if ( isrcA < 0 ) - { - isrcA = ( wrap ) ? ( source - 1) : 0; - } - - if ( size_t(isrcB) >= source ) - { - isrcB = ( wrap ) ? 0 : ( source - 1); - } - - float weight = 1.0f + float(isrcB) - srcB; - - auto& entry = lf[ u ]; - entry.u0 = size_t(isrcA); - entry.weight0 = weight; - - entry.u1 = size_t(isrcB); - entry.weight1 = 1.0f - weight; - } -} - -#define BILINEAR_INTERPOLATE( res, x, y, r0, r1 ) \ - res = ( y.weight0 * ( (r0)[ x.u0 ] * x.weight0 + (r0)[ x.u1 ] * x.weight1 ) ) \ - + ( y.weight1 * ( (r1)[ x.u0 ] * x.weight0 + (r1)[ x.u1 ] * x.weight1 ) ) - -#define TRILINEAR_INTERPOLATE( res, x, y, z, r0, r1, r2, r3 ) \ - res = ( z.weight0 * ( ( y.weight0 * ( (r0)[ x.u0 ] * x.weight0 + (r0)[ x.u1 ] * x.weight1 ) ) \ - + ( y.weight1 * ( (r1)[ x.u0 ] * x.weight0 + (r1)[ x.u1 ] * x.weight1 ) ) ) ) \ - + ( z.weight1 * ( ( y.weight0 * ( (r2)[ x.u0 ] * x.weight0 + (r2)[ x.u1 ] * x.weight1 ) ) \ - + ( y.weight1 * ( (r3)[ x.u0 ] * x.weight0 + (r3)[ x.u1 ] * x.weight1 ) ) ) ) - - -//------------------------------------------------------------------------------------- -// Cubic filtering helpers -//------------------------------------------------------------------------------------- - -XMGLOBALCONST XMVECTORF32 g_cubicThird = { 1.f/3.f, 1.f/3.f, 1.f/3.f, 1.f/3.f }; -XMGLOBALCONST XMVECTORF32 g_cubicSixth = { 1.f/6.f, 1.f/6.f, 1.f/6.f, 1.f/6.f }; -XMGLOBALCONST XMVECTORF32 g_cubicHalf = { 1.f/2.f, 1.f/2.f, 1.f/2.f, 1.f/2.f }; - -inline ptrdiff_t bounduvw( ptrdiff_t u, ptrdiff_t maxu, bool wrap, bool mirror ) -{ - if ( wrap ) - { - if ( u < 0 ) - { - u = maxu + u + 1; - } - else if ( u > maxu ) - { - u = u - maxu - 1; - } - } - else if ( mirror ) - { - if ( u < 0 ) - { - u = ( -u ) - 1; - } - else if ( u > maxu ) - { - u = maxu - (u - maxu - 1); - } - } - - // Handles clamp, but also a safety factor for degenerate images for wrap/mirror - u = std::min( u, maxu ); - u = std::max( u, 0 ); - - return u; -} - -struct CubicFilter -{ - size_t u0; - size_t u1; - size_t u2; - size_t u3; - float x; -}; - -inline void _CreateCubicFilter( _In_ size_t source, _In_ size_t dest, _In_ bool wrap, _In_ bool mirror, _Out_writes_(dest) CubicFilter* cf ) -{ - assert( source > 0 ); - assert( dest > 0 ); - assert( cf != 0 ); - - float scale = float(source) / float(dest); - - for( size_t u = 0; u < dest; ++u ) - { - float srcB = ( float(u) + 0.5f ) * scale - 0.5f; - - ptrdiff_t isrcB = bounduvw( ptrdiff_t(srcB), source - 1, wrap, mirror ); - ptrdiff_t isrcA = bounduvw( isrcB - 1, source - 1, wrap, mirror ); - ptrdiff_t isrcC = bounduvw( isrcB + 1, source - 1, wrap, mirror ); - ptrdiff_t isrcD = bounduvw( isrcB + 2, source - 1, wrap, mirror ); - - auto& entry = cf[ u ]; - entry.u0 = size_t(isrcA); - entry.u1 = size_t(isrcB); - entry.u2 = size_t(isrcC); - entry.u3 = size_t(isrcD); - - float x = srcB - float(isrcB); - entry.x = x; - } -} - -#define CUBIC_INTERPOLATE( res, dx, p0, p1, p2, p3 ) \ -{ \ - XMVECTOR a0 = (p1); \ - XMVECTOR d0 = (p0) - a0; \ - XMVECTOR d2 = (p2) - a0; \ - XMVECTOR d3 = (p3) - a0; \ - XMVECTOR a1 = d2 - g_cubicThird*d0 - g_cubicSixth*d3; \ - XMVECTOR a2 = g_cubicHalf*d0 + g_cubicHalf*d2; \ - XMVECTOR a3 = g_cubicSixth*d3 - g_cubicSixth*d0 - g_cubicHalf*d2; \ - XMVECTOR vdx = XMVectorReplicate( dx ); \ - XMVECTOR vdx2 = vdx * vdx; \ - XMVECTOR vdx3 = vdx2 * vdx; \ - res = a0 + a1*vdx + a2*vdx2 + a3*vdx3; \ -} - - -//------------------------------------------------------------------------------------- -// Triangle filtering helpers -//------------------------------------------------------------------------------------- - -namespace TriangleFilter -{ - struct FilterTo - { - size_t u; - float weight; - }; - - struct FilterFrom - { - size_t count; - size_t sizeInBytes; - FilterTo to[1]; // variable-sized array - }; - - struct Filter - { - size_t sizeInBytes; - size_t totalSize; - FilterFrom from[1]; // variable-sized array - }; - - struct TriangleRow - { - size_t remaining; - TriangleRow* next; - ScopedAlignedArrayXMVECTOR scanline; - - TriangleRow() : remaining(0), next(nullptr) {} - }; - - static const size_t TF_FILTER_SIZE = sizeof(Filter) - sizeof(FilterFrom); - static const size_t TF_FROM_SIZE = sizeof(FilterFrom) - sizeof(FilterTo); - static const size_t TF_TO_SIZE = sizeof(FilterTo); - - static const float TF_EPSILON = 0.00001f; - - inline HRESULT _Create( _In_ size_t source, _In_ size_t dest, _In_ bool wrap, _Inout_ std::unique_ptr& tf ) - { - assert( source > 0 ); - assert( dest > 0 ); - - float scale = float(dest) / float(source); - float scaleInv = 0.5f / scale; - - // Determine storage required for filter and allocate memory if needed - size_t totalSize = TF_FILTER_SIZE + TF_FROM_SIZE + TF_TO_SIZE; - float repeat = (wrap) ? 1.f : 0.f; - - for( size_t u = 0; u < source; ++u ) - { - float src = float(u) - 0.5f; - float destMin = src * scale; - float destMax = destMin + scale; - - totalSize += TF_FROM_SIZE + TF_TO_SIZE + size_t( destMax - destMin + repeat + 1.f ) * TF_TO_SIZE * 2; - } - - uint8_t* pFilter = nullptr; - - if ( tf ) - { - // See if existing filter memory block is large enough to reuse - if ( tf->totalSize >= totalSize ) - { - pFilter = reinterpret_cast( tf.get() ); - } - else - { - // Need to reallocate filter memory block - tf.reset( nullptr ); - } - } - - if ( !tf ) - { - // Allocate filter memory block - pFilter = new (std::nothrow) uint8_t[ totalSize ]; - if ( !pFilter ) - return E_OUTOFMEMORY; - - tf.reset( reinterpret_cast( pFilter ) ); - tf->totalSize = totalSize; - } - - assert( pFilter != 0 ); - - // Filter setup - size_t sizeInBytes = TF_FILTER_SIZE; - size_t accumU = 0; - float accumWeight = 0.f; - - for( size_t u = 0; u < source; ++u ) - { - // Setup from entry - size_t sizeFrom = sizeInBytes; - auto pFrom = reinterpret_cast( pFilter + sizeInBytes ); - sizeInBytes += TF_FROM_SIZE; - - if ( sizeInBytes > totalSize ) - return E_FAIL; - - size_t toCount = 0; - - // Perform two passes to capture the influences from both sides - for( size_t j = 0; j < 2; ++j ) - { - float src = float( u + j ) - 0.5f; - - float destMin = src * scale; - float destMax = destMin + scale; - - if ( !wrap ) - { - // Clamp - if ( destMin < 0.f ) - destMin = 0.f; - if ( destMax > float(dest) ) - destMax = float(dest); - } - - for( auto k = static_cast( floorf( destMin ) ); float(k) < destMax; ++k ) - { - float d0 = float(k); - float d1 = d0 + 1.f; - - size_t u0; - if ( k < 0 ) - { - // Handle wrap - u0 = size_t( k + ptrdiff_t(dest) ); - } - else if ( k >= ptrdiff_t(dest) ) - { - // Handle wrap - u0 = size_t( k - ptrdiff_t(dest) ); - } - else - { - u0 = size_t( k ); - } - - // Save previous accumulated weight (if any) - if ( u0 != accumU ) - { - if ( accumWeight > TF_EPSILON ) - { - auto pTo = reinterpret_cast( pFilter + sizeInBytes ); - sizeInBytes += TF_TO_SIZE; - ++toCount; - - if ( sizeInBytes > totalSize ) - return E_FAIL; - - pTo->u = accumU; - pTo->weight = accumWeight; - } - - accumWeight = 0.f; - accumU = u0; - } - - // Clip destination - if ( d0 < destMin ) - d0 = destMin; - if ( d1 > destMax ) - d1 = destMax; - - // Calculate average weight over destination pixel - - float weight; - if ( !wrap && src < 0.f ) - weight = 1.f; - else if ( !wrap && ( ( src + 1.f ) >= float(source) ) ) - weight = 0.f; - else - weight = (d0 + d1) * scaleInv - src; - - accumWeight += (d1 - d0) * ( j ? (1.f - weight) : weight ); - } - } - - // Store accumulated weight - if ( accumWeight > TF_EPSILON ) - { - auto pTo = reinterpret_cast( pFilter + sizeInBytes ); - sizeInBytes += TF_TO_SIZE; - ++toCount; - - if ( sizeInBytes > totalSize ) - return E_FAIL; - - pTo->u = accumU; - pTo->weight = accumWeight; - } - - accumWeight = 0.f; - - // Finalize from entry - pFrom->count = toCount; - pFrom->sizeInBytes = sizeInBytes - sizeFrom; - } - - tf->sizeInBytes = sizeInBytes; - - return S_OK; - } - -}; // namespace - -}; // namespace \ No newline at end of file diff --git a/Externals/DirectXTex Aug 2015/Include/scoped.h b/Externals/DirectXTex Aug 2015/Include/scoped.h deleted file mode 100644 index d6329b1..0000000 --- a/Externals/DirectXTex Aug 2015/Include/scoped.h +++ /dev/null @@ -1,32 +0,0 @@ -//------------------------------------------------------------------------------------- -// scoped.h -// -// Utility header with helper classes for exception-safe handling of resources -// -// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -// PARTICULAR PURPOSE. -// -// Copyright (c) Microsoft Corporation. All rights reserved. -//------------------------------------------------------------------------------------- - -#pragma once - -#include -#include -#include - -//--------------------------------------------------------------------------------- -struct aligned_deleter { void operator()(void* p) { _aligned_free(p); } }; - -typedef std::unique_ptr ScopedAlignedArrayFloat; - -typedef std::unique_ptr ScopedAlignedArrayXMVECTOR; - -//--------------------------------------------------------------------------------- -struct handle_closer { void operator()(HANDLE h) { assert(h != INVALID_HANDLE_VALUE); if (h) CloseHandle(h); } }; - -typedef public std::unique_ptr ScopedHandle; - -inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? 0 : h; } diff --git a/Externals/DirectXTex Aug 2015/Lib 2015/Debug/DirectXTex.lib b/Externals/DirectXTex Aug 2015/Lib 2015/Debug/DirectXTex.lib deleted file mode 100644 index 8f48c52..0000000 Binary files a/Externals/DirectXTex Aug 2015/Lib 2015/Debug/DirectXTex.lib and /dev/null differ diff --git a/Externals/DirectXTex Aug 2015/Lib 2015/Debug/DirectXTex.pdb b/Externals/DirectXTex Aug 2015/Lib 2015/Debug/DirectXTex.pdb deleted file mode 100644 index 2079327..0000000 Binary files a/Externals/DirectXTex Aug 2015/Lib 2015/Debug/DirectXTex.pdb and /dev/null differ diff --git a/Externals/DirectXTex Aug 2015/Lib 2015/Release/DirectXTex.lib b/Externals/DirectXTex Aug 2015/Lib 2015/Release/DirectXTex.lib deleted file mode 100644 index e8d6767..0000000 Binary files a/Externals/DirectXTex Aug 2015/Lib 2015/Release/DirectXTex.lib and /dev/null differ diff --git a/Externals/DirectXTex Aug 2015/Lib 2015/Release/DirectXTex.pdb b/Externals/DirectXTex Aug 2015/Lib 2015/Release/DirectXTex.pdb deleted file mode 100644 index a9a3731..0000000 Binary files a/Externals/DirectXTex Aug 2015/Lib 2015/Release/DirectXTex.pdb and /dev/null differ diff --git a/Externals/DirectXTex Aug 2015/Include/DirectXTex.h b/Externals/DirectXTex July 2017/Include/DirectXTex.h similarity index 75% rename from Externals/DirectXTex Aug 2015/Include/DirectXTex.h rename to Externals/DirectXTex July 2017/Include/DirectXTex.h index 73bf67d..f4a55d5 100644 --- a/Externals/DirectXTex Aug 2015/Include/DirectXTex.h +++ b/Externals/DirectXTex July 2017/Include/DirectXTex.h @@ -15,51 +15,29 @@ #pragma once -#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) && (_WIN32_WINNT <= _WIN32_WINNT_WIN8) -#error WIC is not supported on Windows Phone 8.0 -#endif - -// VS 2010's stdint.h conflicts with intsafe.h -#pragma warning(push) -#pragma warning(disable : 4005) #include -#pragma warning(pop) #include #include +#include +#if !defined(__d3d11_h__) && !defined(__d3d11_x_h__) && !defined(__d3d12_h__) && !defined(__d3d12_x_h__) #if defined(_XBOX_ONE) && defined(_TITLE) #include #define DCOMMON_H_INCLUDED #else #include #endif - -#include - -// VS 2010 doesn't support explicit calling convention for std::function -#ifndef DIRECTX_STD_CALLCONV -#if defined(_MSC_VER) && (_MSC_VER < 1700) -#define DIRECTX_STD_CALLCONV -#else -#define DIRECTX_STD_CALLCONV __cdecl -#endif #endif -// VS 2010/2012 do not support =default =delete -#ifndef DIRECTX_CTOR_DEFAULT -#if defined(_MSC_VER) && (_MSC_VER < 1800) -#define DIRECTX_CTOR_DEFAULT {} -#define DIRECTX_CTOR_DELETE ; -#else -#define DIRECTX_CTOR_DEFAULT =default; -#define DIRECTX_CTOR_DELETE =delete; -#endif -#endif +#include -#define DIRECTX_TEX_VERSION 133 +#include + +#define DIRECTX_TEX_VERSION 151 struct IWICImagingFactory; +struct IWICMetadataQueryReader; namespace DirectX @@ -91,6 +69,7 @@ namespace DirectX CP_FLAGS_YMM = 0x4, // Assume pitch is 32-byte aligned instead of BYTE aligned CP_FLAGS_ZMM = 0x8, // Assume pitch is 64-byte aligned instead of BYTE aligned CP_FLAGS_PAGE4K = 0x200, // Assume pitch is 4096-byte aligned instead of BYTE aligned + CP_FLAGS_BAD_DXTN_TAILS = 0x1000, // BC formats with malformed mipchain blocks smaller than 4x4 CP_FLAGS_24BPP = 0x10000, // Override with a legacy 24 bits-per-pixel format size CP_FLAGS_16BPP = 0x20000, // Override with a legacy 16 bits-per-pixel format size CP_FLAGS_8BPP = 0x40000, // Override with a legacy 8 bits-per-pixel format size @@ -157,6 +136,7 @@ namespace DirectX bool __cdecl IsPMAlpha() const { return ((miscFlags2 & TEX_MISC2_ALPHA_MODE_MASK) == TEX_ALPHA_MODE_PREMULTIPLIED) != 0; } void __cdecl SetAlphaMode( TEX_ALPHA_MODE mode ) { miscFlags2 = (miscFlags2 & ~TEX_MISC2_ALPHA_MODE_MASK) | static_cast(mode); } + TEX_ALPHA_MODE __cdecl GetAlphaMode() const { return static_cast(miscFlags2 & TEX_MISC2_ALPHA_MODE_MASK); } // Helpers for miscFlags2 bool __cdecl IsVolumemap() const { return (dimension == TEX_DIMENSION_TEXTURE3D); } @@ -185,6 +165,9 @@ namespace DirectX DDS_FLAGS_EXPAND_LUMINANCE = 0x20, // When loading legacy luminance formats expand replicating the color channels rather than leaving them packed (L8, L16, A8L8) + DDS_FLAGS_BAD_DXTN_TAILS = 0x40, + // Some older DXTn DDS files incorrectly handle mipchain tails for blocks smaller than 4x4 + DDS_FLAGS_FORCE_DX10_EXT = 0x10000, // Always use the 'DX10' header extension for DDS writer (i.e. don't try to write DX9 compatible DDS files) @@ -227,21 +210,29 @@ namespace DirectX // Filtering mode to use for any required image resizing (only needed when loading arrays of differently sized images; defaults to Fant) }; - HRESULT __cdecl GetMetadataFromDDSMemory( _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, _In_ DWORD flags, + HRESULT __cdecl GetMetadataFromDDSMemory( _In_reads_bytes_(size) const void* pSource, _In_ size_t size, _In_ DWORD flags, _Out_ TexMetadata& metadata ); - HRESULT __cdecl GetMetadataFromDDSFile( _In_z_ LPCWSTR szFile, _In_ DWORD flags, + HRESULT __cdecl GetMetadataFromDDSFile( _In_z_ const wchar_t* szFile, _In_ DWORD flags, _Out_ TexMetadata& metadata ); - HRESULT __cdecl GetMetadataFromTGAMemory( _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, + HRESULT __cdecl GetMetadataFromHDRMemory( _In_reads_bytes_(size) const void* pSource, _In_ size_t size, _Out_ TexMetadata& metadata ); - HRESULT __cdecl GetMetadataFromTGAFile( _In_z_ LPCWSTR szFile, + HRESULT __cdecl GetMetadataFromHDRFile( _In_z_ const wchar_t* szFile, _Out_ TexMetadata& metadata ); - HRESULT __cdecl GetMetadataFromWICMemory( _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, _In_ DWORD flags, + HRESULT __cdecl GetMetadataFromTGAMemory( _In_reads_bytes_(size) const void* pSource, _In_ size_t size, _Out_ TexMetadata& metadata ); - HRESULT __cdecl GetMetadataFromWICFile( _In_z_ LPCWSTR szFile, _In_ DWORD flags, + HRESULT __cdecl GetMetadataFromTGAFile( _In_z_ const wchar_t* szFile, _Out_ TexMetadata& metadata ); + HRESULT __cdecl GetMetadataFromWICMemory( _In_reads_bytes_(size) const void* pSource, _In_ size_t size, _In_ DWORD flags, + _Out_ TexMetadata& metadata, + _In_opt_ std::function getMQR = nullptr); + + HRESULT __cdecl GetMetadataFromWICFile( _In_z_ const wchar_t* szFile, _In_ DWORD flags, + _Out_ TexMetadata& metadata, + _In_opt_ std::function getMQR = nullptr); + //--------------------------------------------------------------------------------- // Bitmap image container struct Image @@ -258,13 +249,16 @@ namespace DirectX { public: ScratchImage() - : _nimages(0), _size(0), _image(nullptr), _memory(nullptr) {} + : m_nimages(0), m_size(0), m_metadata{}, m_image(nullptr), m_memory(nullptr) {} ScratchImage(ScratchImage&& moveFrom) - : _nimages(0), _size(0), _image(nullptr), _memory(nullptr) { *this = std::move(moveFrom); } + : m_nimages(0), m_size(0), m_metadata{}, m_image(nullptr), m_memory(nullptr) { *this = std::move(moveFrom); } ~ScratchImage() { Release(); } ScratchImage& __cdecl operator= (ScratchImage&& moveFrom); + ScratchImage(const ScratchImage&) = delete; + ScratchImage& operator=(const ScratchImage&) = delete; + HRESULT __cdecl Initialize( _In_ const TexMetadata& mdata, _In_ DWORD flags = CP_FLAGS_NONE ); HRESULT __cdecl Initialize1D( _In_ DXGI_FORMAT fmt, _In_ size_t length, _In_ size_t arraySize, _In_ size_t mipLevels, _In_ DWORD flags = CP_FLAGS_NONE ); @@ -281,27 +275,23 @@ namespace DirectX bool __cdecl OverrideFormat( _In_ DXGI_FORMAT f ); - const TexMetadata& __cdecl GetMetadata() const { return _metadata; } + const TexMetadata& __cdecl GetMetadata() const { return m_metadata; } const Image* __cdecl GetImage(_In_ size_t mip, _In_ size_t item, _In_ size_t slice) const; - const Image* __cdecl GetImages() const { return _image; } - size_t __cdecl GetImageCount() const { return _nimages; } + const Image* __cdecl GetImages() const { return m_image; } + size_t __cdecl GetImageCount() const { return m_nimages; } - uint8_t* __cdecl GetPixels() const { return _memory; } - size_t __cdecl GetPixelsSize() const { return _size; } + uint8_t* __cdecl GetPixels() const { return m_memory; } + size_t __cdecl GetPixelsSize() const { return m_size; } bool __cdecl IsAlphaAllOpaque() const; private: - size_t _nimages; - size_t _size; - TexMetadata _metadata; - Image* _image; - uint8_t* _memory; - - // Hide copy constructor and assignment operator - ScratchImage( const ScratchImage& ); - ScratchImage& operator=( const ScratchImage& ); + size_t m_nimages; + size_t m_size; + TexMetadata m_metadata; + Image* m_image; + uint8_t* m_memory; }; //--------------------------------------------------------------------------------- @@ -309,35 +299,36 @@ namespace DirectX class Blob { public: - Blob() : _buffer(nullptr), _size(0) {} - Blob(Blob&& moveFrom) : _buffer(nullptr), _size(0) { *this = std::move(moveFrom); } + Blob() : m_buffer(nullptr), m_size(0) {} + Blob(Blob&& moveFrom) : m_buffer(nullptr), m_size(0) { *this = std::move(moveFrom); } ~Blob() { Release(); } Blob& __cdecl operator= (Blob&& moveFrom); + Blob(const Blob&) = delete; + Blob& operator=(const Blob&) = delete; + HRESULT __cdecl Initialize( _In_ size_t size ); void __cdecl Release(); - void *__cdecl GetBufferPointer() const { return _buffer; } - size_t __cdecl GetBufferSize() const { return _size; } + void *__cdecl GetBufferPointer() const { return m_buffer; } + size_t __cdecl GetBufferSize() const { return m_size; } - private: - void* _buffer; - size_t _size; + HRESULT __cdecl Trim(size_t size); - // Hide copy constructor and assignment operator - Blob( const Blob& ); - Blob& operator=( const Blob& ); + private: + void* m_buffer; + size_t m_size; }; //--------------------------------------------------------------------------------- // Image I/O // DDS operations - HRESULT __cdecl LoadFromDDSMemory( _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, _In_ DWORD flags, + HRESULT __cdecl LoadFromDDSMemory( _In_reads_bytes_(size) const void* pSource, _In_ size_t size, _In_ DWORD flags, _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image ); - HRESULT __cdecl LoadFromDDSFile( _In_z_ LPCWSTR szFile, _In_ DWORD flags, + HRESULT __cdecl LoadFromDDSFile( _In_z_ const wchar_t* szFile, _In_ DWORD flags, _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image ); HRESULT __cdecl SaveToDDSMemory( _In_ const Image& image, _In_ DWORD flags, @@ -345,37 +336,48 @@ namespace DirectX HRESULT __cdecl SaveToDDSMemory( _In_reads_(nimages) const Image* images, _In_ size_t nimages, _In_ const TexMetadata& metadata, _In_ DWORD flags, _Out_ Blob& blob ); - HRESULT __cdecl SaveToDDSFile( _In_ const Image& image, _In_ DWORD flags, _In_z_ LPCWSTR szFile ); - HRESULT __cdecl SaveToDDSFile( _In_reads_(nimages) const Image* images, _In_ size_t nimages, _In_ const TexMetadata& metadata, _In_ DWORD flags, _In_z_ LPCWSTR szFile ); + HRESULT __cdecl SaveToDDSFile( _In_ const Image& image, _In_ DWORD flags, _In_z_ const wchar_t* szFile ); + HRESULT __cdecl SaveToDDSFile( _In_reads_(nimages) const Image* images, _In_ size_t nimages, _In_ const TexMetadata& metadata, _In_ DWORD flags, _In_z_ const wchar_t* szFile ); + + // HDR operations + HRESULT __cdecl LoadFromHDRMemory( _In_reads_bytes_(size) const void* pSource, _In_ size_t size, + _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image ); + HRESULT __cdecl LoadFromHDRFile( _In_z_ const wchar_t* szFile, + _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image ); + + HRESULT __cdecl SaveToHDRMemory( _In_ const Image& image, _Out_ Blob& blob ); + HRESULT __cdecl SaveToHDRFile( _In_ const Image& image, _In_z_ const wchar_t* szFile ); // TGA operations - HRESULT __cdecl LoadFromTGAMemory( _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, + HRESULT __cdecl LoadFromTGAMemory( _In_reads_bytes_(size) const void* pSource, _In_ size_t size, _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image ); - HRESULT __cdecl LoadFromTGAFile( _In_z_ LPCWSTR szFile, + HRESULT __cdecl LoadFromTGAFile( _In_z_ const wchar_t* szFile, _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image ); HRESULT __cdecl SaveToTGAMemory( _In_ const Image& image, _Out_ Blob& blob ); - HRESULT __cdecl SaveToTGAFile( _In_ const Image& image, _In_z_ LPCWSTR szFile ); + HRESULT __cdecl SaveToTGAFile( _In_ const Image& image, _In_z_ const wchar_t* szFile ); // WIC operations - HRESULT __cdecl LoadFromWICMemory( _In_reads_bytes_(size) LPCVOID pSource, _In_ size_t size, _In_ DWORD flags, - _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image ); - HRESULT __cdecl LoadFromWICFile( _In_z_ LPCWSTR szFile, _In_ DWORD flags, - _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image ); + HRESULT __cdecl LoadFromWICMemory( _In_reads_bytes_(size) const void* pSource, _In_ size_t size, _In_ DWORD flags, + _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image, + _In_opt_ std::function getMQR = nullptr); + HRESULT __cdecl LoadFromWICFile( _In_z_ const wchar_t* szFile, _In_ DWORD flags, + _Out_opt_ TexMetadata* metadata, _Out_ ScratchImage& image, + _In_opt_ std::function getMQR = nullptr); HRESULT __cdecl SaveToWICMemory( _In_ const Image& image, _In_ DWORD flags, _In_ REFGUID guidContainerFormat, _Out_ Blob& blob, _In_opt_ const GUID* targetFormat = nullptr, - _In_opt_ std::function setCustomProps = nullptr ); + _In_opt_ std::function setCustomProps = nullptr ); HRESULT __cdecl SaveToWICMemory( _In_count_(nimages) const Image* images, _In_ size_t nimages, _In_ DWORD flags, _In_ REFGUID guidContainerFormat, _Out_ Blob& blob, _In_opt_ const GUID* targetFormat = nullptr, - _In_opt_ std::function setCustomProps = nullptr ); + _In_opt_ std::function setCustomProps = nullptr ); HRESULT __cdecl SaveToWICFile( _In_ const Image& image, _In_ DWORD flags, _In_ REFGUID guidContainerFormat, - _In_z_ LPCWSTR szFile, _In_opt_ const GUID* targetFormat = nullptr, - _In_opt_ std::function setCustomProps = nullptr ); + _In_z_ const wchar_t* szFile, _In_opt_ const GUID* targetFormat = nullptr, + _In_opt_ std::function setCustomProps = nullptr ); HRESULT __cdecl SaveToWICFile( _In_count_(nimages) const Image* images, _In_ size_t nimages, _In_ DWORD flags, _In_ REFGUID guidContainerFormat, - _In_z_ LPCWSTR szFile, _In_opt_ const GUID* targetFormat = nullptr, - _In_opt_ std::function setCustomProps = nullptr ); + _In_z_ const wchar_t* szFile, _In_opt_ const GUID* targetFormat = nullptr, + _In_opt_ std::function setCustomProps = nullptr ); //--------------------------------------------------------------------------------- // Texture conversion, resizing, mipmap generation, and block compression @@ -412,6 +414,9 @@ namespace DirectX TEX_FILTER_SEPARATE_ALPHA = 0x100, // Resize color and alpha channel independently + TEX_FILTER_FLOAT_X2BIAS = 0x200, + // Enable *2 - 1 conversion cases for unorm<->float and positive-only float formats + TEX_FILTER_RGB_COPY_RED = 0x1000, TEX_FILTER_RGB_COPY_GREEN = 0x2000, TEX_FILTER_RGB_COPY_BLUE = 0x4000, @@ -452,6 +457,9 @@ namespace DirectX // Resize the image to width x height. Defaults to Fant filtering. // Note for a complex resize, the result will always have mipLevels == 1 + const float TEX_THRESHOLD_DEFAULT = 0.5f; + // Default value for alpha threshold used when converting to 1-bit alpha + HRESULT __cdecl Convert( _In_ const Image& srcImage, _In_ DXGI_FORMAT format, _In_ DWORD filter, _In_ float threshold, _Out_ ScratchImage& image ); HRESULT __cdecl Convert( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata, @@ -484,6 +492,9 @@ namespace DirectX TEX_PMALPHA_IGNORE_SRGB = 0x1, // ignores sRGB colorspace conversions + TEX_PMALPHA_REVERSE = 0x2, + // converts from premultiplied alpha back to straight alpha + TEX_PMALPHA_SRGB_IN = 0x1000000, TEX_PMALPHA_SRGB_OUT = 0x2000000, TEX_PMALPHA_SRGB = ( TEX_PMALPHA_SRGB_IN | TEX_PMALPHA_SRGB_OUT ), @@ -492,49 +503,55 @@ namespace DirectX }; HRESULT __cdecl PremultiplyAlpha( _In_ const Image& srcImage, _In_ DWORD flags, _Out_ ScratchImage& image ); - HRESULT __cdecl PremultiplyAlpha( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata, _In_ DWORD flags, _Out_ ScratchImage& result ); - // Converts to a premultiplied alpha version of the texture + HRESULT __cdecl PremultiplyAlpha( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata, + _In_ DWORD flags, _Out_ ScratchImage& result ); + // Converts to/from a premultiplied alpha version of the texture enum TEX_COMPRESS_FLAGS { - TEX_COMPRESS_DEFAULT = 0, + TEX_COMPRESS_DEFAULT = 0, - TEX_COMPRESS_RGB_DITHER = 0x10000, + TEX_COMPRESS_RGB_DITHER = 0x10000, // Enables dithering RGB colors for BC1-3 compression - TEX_COMPRESS_A_DITHER = 0x20000, + TEX_COMPRESS_A_DITHER = 0x20000, // Enables dithering alpha for BC1-3 compression - TEX_COMPRESS_DITHER = 0x30000, + TEX_COMPRESS_DITHER = 0x30000, // Enables both RGB and alpha dithering for BC1-3 compression - TEX_COMPRESS_UNIFORM = 0x40000, + TEX_COMPRESS_UNIFORM = 0x40000, // Uniform color weighting for BC1-3 compression; by default uses perceptual weighting - TEX_COMPRESS_BC7_USE_3SUBSETS = 0x80000, + TEX_COMPRESS_BC7_USE_3SUBSETS = 0x80000, // Enables exhaustive search for BC7 compress for mode 0 and 2; by default skips trying these modes - TEX_COMPRESS_SRGB_IN = 0x1000000, - TEX_COMPRESS_SRGB_OUT = 0x2000000, - TEX_COMPRESS_SRGB = ( TEX_COMPRESS_SRGB_IN | TEX_COMPRESS_SRGB_OUT ), + TEX_COMPRESS_BC7_QUICK = 0x100000, + // Minimal modes (usually mode 6) for BC7 compression + + TEX_COMPRESS_SRGB_IN = 0x1000000, + TEX_COMPRESS_SRGB_OUT = 0x2000000, + TEX_COMPRESS_SRGB = ( TEX_COMPRESS_SRGB_IN | TEX_COMPRESS_SRGB_OUT ), // if the input format type is IsSRGB(), then SRGB_IN is on by default // if the output format type is IsSRGB(), then SRGB_OUT is on by default - TEX_COMPRESS_PARALLEL = 0x10000000, + TEX_COMPRESS_PARALLEL = 0x10000000, // Compress is free to use multithreading to improve performance (by default it does not use multithreading) }; - HRESULT __cdecl Compress( _In_ const Image& srcImage, _In_ DXGI_FORMAT format, _In_ DWORD compress, _In_ float alphaRef, + HRESULT __cdecl Compress( _In_ const Image& srcImage, _In_ DXGI_FORMAT format, _In_ DWORD compress, _In_ float threshold, _Out_ ScratchImage& cImage ); HRESULT __cdecl Compress( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata, - _In_ DXGI_FORMAT format, _In_ DWORD compress, _In_ float alphaRef, _Out_ ScratchImage& cImages ); - // Note that alphaRef is only used by BC1. 0.5f is a typical value to use + _In_ DXGI_FORMAT format, _In_ DWORD compress, _In_ float threshold, _Out_ ScratchImage& cImages ); + // Note that threshold is only used by BC1. TEX_THRESHOLD_DEFAULT is a typical value to use +#if defined(__d3d11_h__) || defined(__d3d11_x_h__) HRESULT __cdecl Compress( _In_ ID3D11Device* pDevice, _In_ const Image& srcImage, _In_ DXGI_FORMAT format, _In_ DWORD compress, _In_ float alphaWeight, _Out_ ScratchImage& image ); HRESULT __cdecl Compress( _In_ ID3D11Device* pDevice, _In_ const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata, _In_ DXGI_FORMAT format, _In_ DWORD compress, _In_ float alphaWeight, _Out_ ScratchImage& cImages ); // DirectCompute-based compression (alphaWeight is only used by BC7. 1.0 is the typical value to use) +#endif HRESULT __cdecl Decompress( _In_ const Image& cImage, _In_ DXGI_FORMAT format, _Out_ ScratchImage& image ); HRESULT __cdecl Decompress( _In_reads_(nimages) const Image* cImages, _In_ size_t nimages, _In_ const TexMetadata& metadata, @@ -582,7 +599,7 @@ namespace DirectX size_t w; size_t h; - Rect() DIRECTX_CTOR_DEFAULT + Rect() = default; Rect( size_t _x, size_t _y, size_t _w, size_t _h ) : x(_x), y(_y), w(_w), h(_h) {} }; @@ -610,6 +627,20 @@ namespace DirectX HRESULT __cdecl ComputeMSE( _In_ const Image& image1, _In_ const Image& image2, _Out_ float& mse, _Out_writes_opt_(4) float* mseV, _In_ DWORD flags = 0 ); + HRESULT __cdecl EvaluateImage( _In_ const Image& image, + _In_ std::function pixelFunc ); + HRESULT __cdecl EvaluateImage( _In_reads_(nimages) const Image* images, _In_ size_t nimages, _In_ const TexMetadata& metadata, + _In_ std::function pixelFunc ); + + HRESULT __cdecl TransformImage( _In_ const Image& image, + _In_ std::function pixelFunc, + ScratchImage& result ); + HRESULT __cdecl TransformImage( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata, + _In_ std::function pixelFunc, + ScratchImage& result ); + //--------------------------------------------------------------------------------- // WIC utility code @@ -631,6 +662,7 @@ namespace DirectX //--------------------------------------------------------------------------------- // Direct3D 11 functions +#if defined(__d3d11_h__) || defined(__d3d11_x_h__) bool __cdecl IsSupportedTexture( _In_ ID3D11Device* pDevice, _In_ const TexMetadata& metadata ); HRESULT __cdecl CreateTexture( _In_ ID3D11Device* pDevice, _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata, @@ -648,6 +680,29 @@ namespace DirectX _Outptr_ ID3D11ShaderResourceView** ppSRV ); HRESULT __cdecl CaptureTexture( _In_ ID3D11Device* pDevice, _In_ ID3D11DeviceContext* pContext, _In_ ID3D11Resource* pSource, _Out_ ScratchImage& result ); +#endif + + //--------------------------------------------------------------------------------- + // Direct3D 12 functions +#if defined(__d3d12_h__) || defined(__d3d12_x_h__) + bool __cdecl IsSupportedTexture( _In_ ID3D12Device* pDevice, _In_ const TexMetadata& metadata ); + + HRESULT __cdecl CreateTexture( _In_ ID3D12Device* pDevice, _In_ const TexMetadata& metadata, + _Outptr_ ID3D12Resource** ppResource ); + + HRESULT __cdecl CreateTextureEx( _In_ ID3D12Device* pDevice, _In_ const TexMetadata& metadata, + _In_ D3D12_RESOURCE_FLAGS resFlags, _In_ bool forceSRGB, + _Outptr_ ID3D12Resource** ppResource ); + + HRESULT __cdecl PrepareUpload( _In_ ID3D12Device* pDevice, + _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata, + std::vector& subresources ); + + HRESULT __cdecl CaptureTexture( _In_ ID3D12CommandQueue* pCommandQueue, _In_ ID3D12Resource* pSource, _In_ bool isCubeMap, + _Out_ ScratchImage& result, + _In_ D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_RENDER_TARGET, + _In_ D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_RENDER_TARGET ); +#endif #include "DirectXTex.inl" diff --git a/Externals/DirectXTex Aug 2015/Include/DirectXTex.inl b/Externals/DirectXTex July 2017/Include/DirectXTex.inl similarity index 95% rename from Externals/DirectXTex Aug 2015/Include/DirectXTex.inl rename to Externals/DirectXTex July 2017/Include/DirectXTex.inl index 605c2c8..5173869 100644 --- a/Externals/DirectXTex Aug 2015/Include/DirectXTex.inl +++ b/Externals/DirectXTex July 2017/Include/DirectXTex.inl @@ -100,8 +100,7 @@ inline bool __cdecl IsSRGB(DXGI_FORMAT fmt) _Use_decl_annotations_ inline HRESULT __cdecl SaveToDDSMemory(const Image& image, DWORD flags, Blob& blob) { - TexMetadata mdata; - memset( &mdata, 0, sizeof(mdata) ); + TexMetadata mdata = {}; mdata.width = image.width; mdata.height = image.height; mdata.depth = 1; @@ -114,10 +113,9 @@ inline HRESULT __cdecl SaveToDDSMemory(const Image& image, DWORD flags, Blob& bl } _Use_decl_annotations_ -inline HRESULT __cdecl SaveToDDSFile(const Image& image, DWORD flags, LPCWSTR szFile) +inline HRESULT __cdecl SaveToDDSFile(const Image& image, DWORD flags, const wchar_t* szFile) { - TexMetadata mdata; - memset( &mdata, 0, sizeof(mdata) ); + TexMetadata mdata = {}; mdata.width = image.width; mdata.height = image.height; mdata.depth = 1; diff --git a/Externals/DirectXTex July 2017/Lib 2017/Debug/DirectXTex.lib b/Externals/DirectXTex July 2017/Lib 2017/Debug/DirectXTex.lib new file mode 100644 index 0000000..82e2311 Binary files /dev/null and b/Externals/DirectXTex July 2017/Lib 2017/Debug/DirectXTex.lib differ diff --git a/Externals/DirectXTex July 2017/Lib 2017/Debug/DirectXTex.pdb b/Externals/DirectXTex July 2017/Lib 2017/Debug/DirectXTex.pdb new file mode 100644 index 0000000..5f334f8 Binary files /dev/null and b/Externals/DirectXTex July 2017/Lib 2017/Debug/DirectXTex.pdb differ diff --git a/Externals/DirectXTex July 2017/Lib 2017/Release/DirectXTex.lib b/Externals/DirectXTex July 2017/Lib 2017/Release/DirectXTex.lib new file mode 100644 index 0000000..c7cf4db Binary files /dev/null and b/Externals/DirectXTex July 2017/Lib 2017/Release/DirectXTex.lib differ diff --git a/Externals/DirectXTex July 2017/Lib 2017/Release/DirectXTex.pdb b/Externals/DirectXTex July 2017/Lib 2017/Release/DirectXTex.pdb new file mode 100644 index 0000000..59e670c Binary files /dev/null and b/Externals/DirectXTex July 2017/Lib 2017/Release/DirectXTex.pdb differ diff --git a/Externals/HosekSky/Lib 2013/HosekSky.lib b/Externals/HosekSky/Lib 2013/HosekSky.lib deleted file mode 100644 index a0b595d..0000000 Binary files a/Externals/HosekSky/Lib 2013/HosekSky.lib and /dev/null differ diff --git a/Externals/HosekSky/Lib 2013/HosekSky_Dbg.lib b/Externals/HosekSky/Lib 2013/HosekSky_Dbg.lib deleted file mode 100644 index abe1237..0000000 Binary files a/Externals/HosekSky/Lib 2013/HosekSky_Dbg.lib and /dev/null differ diff --git a/Externals/HosekSky/Lib 2013/hoseksky.pdb b/Externals/HosekSky/Lib 2013/hoseksky.pdb deleted file mode 100644 index a769faf..0000000 Binary files a/Externals/HosekSky/Lib 2013/hoseksky.pdb and /dev/null differ diff --git a/Externals/HosekSky/Lib 2013/hoseksky_dbg.pdb b/Externals/HosekSky/Lib 2013/hoseksky_dbg.pdb deleted file mode 100644 index b2903a7..0000000 Binary files a/Externals/HosekSky/Lib 2013/hoseksky_dbg.pdb and /dev/null differ diff --git a/Externals/HosekSky/Lib 2015/HosekSky.lib b/Externals/HosekSky/Lib 2015/HosekSky.lib deleted file mode 100644 index e9def45..0000000 Binary files a/Externals/HosekSky/Lib 2015/HosekSky.lib and /dev/null differ diff --git a/Externals/HosekSky/Lib 2015/HosekSky.pdb b/Externals/HosekSky/Lib 2015/HosekSky.pdb deleted file mode 100644 index c652247..0000000 Binary files a/Externals/HosekSky/Lib 2015/HosekSky.pdb and /dev/null differ diff --git a/Externals/HosekSky/Lib 2015/HosekSky_Dbg.lib b/Externals/HosekSky/Lib 2015/HosekSky_Dbg.lib deleted file mode 100644 index da52007..0000000 Binary files a/Externals/HosekSky/Lib 2015/HosekSky_Dbg.lib and /dev/null differ diff --git a/Externals/HosekSky/Lib 2015/HosekSky_Dbg.pdb b/Externals/HosekSky/Lib 2015/HosekSky_Dbg.pdb deleted file mode 100644 index f368388..0000000 Binary files a/Externals/HosekSky/Lib 2015/HosekSky_Dbg.pdb and /dev/null differ diff --git a/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/PIXEventsCommon.h b/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/PIXEventsCommon.h index 3021db2..84f3f69 100644 --- a/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/PIXEventsCommon.h +++ b/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/PIXEventsCommon.h @@ -1,9 +1,3 @@ -// -// This file was copied from //depot/rs_xbox_dev_flight/xbox/drivers/Graphics/Pix3/PixEvt/inc/PIXEventsCommon.h#6 -// -// To refresh: run 'UpdateFromXbox -latest' -// - /*==========================================================================; * * Copyright (C) Microsoft Corporation. All Rights Reserved. diff --git a/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/PIXEventsGenerated.h b/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/PIXEventsGenerated.h index 86f742a..e9fab2b 100644 --- a/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/PIXEventsGenerated.h +++ b/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/PIXEventsGenerated.h @@ -1,9 +1,3 @@ -// -// This file was copied from //depot/rs_xbox_dev_flight/xbox/drivers/Graphics/Pix3/PixEvt/inc/PIXEventsGenerated.h#6 -// -// To refresh: run 'UpdateFromXbox -latest' -// - //This is a generated file. #pragma once diff --git a/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/pix3.h b/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/pix3.h index 7668702..5bd819c 100644 --- a/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/pix3.h +++ b/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/pix3.h @@ -1,9 +1,3 @@ -// -// This file was copied from //depot/rs_xbox_dev_flight/xbox/drivers/Graphics/Pix3/PixEvt/inc/pix3.h#4 -// -// To refresh: run 'UpdateFromXbox -latest' -// - /*==========================================================================; * * Copyright (C) Microsoft Corporation. All Rights Reserved. diff --git a/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/pix3_win.h b/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/pix3_win.h index 4e7915b..8acc1ae 100644 --- a/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/pix3_win.h +++ b/Externals/WinPixEventRuntime/Include/WinPixEventRuntime/pix3_win.h @@ -1,9 +1,3 @@ -// -// This file was copied from //depot/rs_xbox_dev_flight/xbox/drivers/Graphics/Pix3/PixEvt/inc/pix3_win.h#4 -// -// To refresh: run 'UpdateFromXbox -latest' -// - /*==========================================================================; * * Copyright (C) Microsoft Corporation. All Rights Reserved. diff --git a/Externals/WinPixEventRuntime/bin/WinPixEventRuntime.dll b/Externals/WinPixEventRuntime/bin/WinPixEventRuntime.dll index 5b54dd3..9d9ce8f 100644 Binary files a/Externals/WinPixEventRuntime/bin/WinPixEventRuntime.dll and b/Externals/WinPixEventRuntime/bin/WinPixEventRuntime.dll differ diff --git a/Externals/WinPixEventRuntime/bin/WinPixEventRuntime.lib b/Externals/WinPixEventRuntime/bin/WinPixEventRuntime.lib index eb346ca..5e4c236 100644 Binary files a/Externals/WinPixEventRuntime/bin/WinPixEventRuntime.lib and b/Externals/WinPixEventRuntime/bin/WinPixEventRuntime.lib differ diff --git a/Externals/cxxopts/LICENSE b/Externals/cxxopts/LICENSE new file mode 100644 index 0000000..324a203 --- /dev/null +++ b/Externals/cxxopts/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Jarryd Beck + +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. diff --git a/Externals/cxxopts/include/cxxopts.hpp b/Externals/cxxopts/include/cxxopts.hpp new file mode 100644 index 0000000..c33c06a --- /dev/null +++ b/Externals/cxxopts/include/cxxopts.hpp @@ -0,0 +1,1421 @@ +/* + +Copyright (c) 2014, 2015, 2016 Jarryd Beck + +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. + +*/ + +#ifndef CXX_OPTS_HPP +#define CXX_OPTS_HPP + +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnon-virtual-dtor" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +//when we ask cxxopts to use Unicode, help strings are processed using ICU, +//which results in the correct lengths being computed for strings when they +//are formatted for the help output +//it is necessary to make sure that can be found by the +//compiler, and that icu-uc is linked in to the binary. + +#ifdef CXXOPTS_USE_UNICODE +#include + +namespace cxxopts +{ + typedef icu::UnicodeString String; + + inline + String + toLocalString(std::string s) + { + return icu::UnicodeString::fromUTF8(s); + } + + class UnicodeStringIterator : public + std::iterator + { + public: + + UnicodeStringIterator(const icu::UnicodeString* s, int32_t pos) + : s(s) + , i(pos) + { + } + + value_type + operator*() const + { + return s->char32At(i); + } + + bool + operator==(const UnicodeStringIterator& rhs) const + { + return s == rhs.s && i == rhs.i; + } + + bool + operator!=(const UnicodeStringIterator& rhs) const + { + return !(*this == rhs); + } + + UnicodeStringIterator& + operator++() + { + ++i; + return *this; + } + + UnicodeStringIterator + operator+(int32_t v) + { + return UnicodeStringIterator(s, i + v); + } + + private: + const icu::UnicodeString* s; + int32_t i; + }; + + inline + String& + stringAppend(String&s, String a) + { + return s.append(std::move(a)); + } + + inline + String& + stringAppend(String& s, int n, UChar32 c) + { + for (int i = 0; i != n; ++i) + { + s.append(c); + } + + return s; + } + + template + String& + stringAppend(String& s, Iterator begin, Iterator end) + { + while (begin != end) + { + s.append(*begin); + ++begin; + } + + return s; + } + + inline + size_t + stringLength(const String& s) + { + return s.length(); + } + + inline + std::string + toUTF8String(const String& s) + { + std::string result; + s.toUTF8String(result); + + return result; + } + + inline + bool + empty(const String& s) + { + return s.isEmpty(); + } +} + +namespace std +{ + cxxopts::UnicodeStringIterator + begin(const icu::UnicodeString& s) + { + return cxxopts::UnicodeStringIterator(&s, 0); + } + + cxxopts::UnicodeStringIterator + end(const icu::UnicodeString& s) + { + return cxxopts::UnicodeStringIterator(&s, s.length()); + } +} + +//ifdef CXXOPTS_USE_UNICODE +#else + +namespace cxxopts +{ + typedef std::string String; + + template + T + toLocalString(T&& t) + { + return t; + } + + inline + size_t + stringLength(const String& s) + { + return s.length(); + } + + inline + String& + stringAppend(String&s, String a) + { + return s.append(std::move(a)); + } + + inline + String& + stringAppend(String& s, size_t n, char c) + { + return s.append(n, c); + } + + template + String& + stringAppend(String& s, Iterator begin, Iterator end) + { + return s.append(begin, end); + } + + template + std::string + toUTF8String(T&& t) + { + return std::forward(t); + } + + inline + bool + empty(const std::string& s) + { + return s.empty(); + } +} + +//ifdef CXXOPTS_USE_UNICODE +#endif + +namespace cxxopts +{ + class Value : public std::enable_shared_from_this + { + public: + + virtual void + parse(const std::string& text) const = 0; + + virtual void + parse() const = 0; + + virtual bool + has_arg() const = 0; + + virtual bool + has_default() const = 0; + + virtual bool + is_container() const = 0; + + virtual bool + has_implicit() const = 0; + + virtual std::string + get_default_value() const = 0; + + virtual std::string + get_implicit_value() const = 0; + + virtual std::shared_ptr + default_value(const std::string& value) = 0; + + virtual std::shared_ptr + implicit_value(const std::string& value) = 0; + }; + + class OptionException : public std::exception + { + public: + OptionException(const std::string& message) + : m_message(message) + { + } + + virtual const char* + what() const noexcept + { + return m_message.c_str(); + } + + private: + std::string m_message; + }; + + class OptionSpecException : public OptionException + { + public: + + OptionSpecException(const std::string& message) + : OptionException(message) + { + } + }; + + class OptionParseException : public OptionException + { + public: + OptionParseException(const std::string& message) + : OptionException(message) + { + } + }; + + class option_exists_error : public OptionSpecException + { + public: + option_exists_error(const std::string& option) + : OptionSpecException(u8"Option ‘" + option + u8"’ already exists") + { + } + }; + + class invalid_option_format_error : public OptionSpecException + { + public: + invalid_option_format_error(const std::string& format) + : OptionSpecException(u8"Invalid option format ‘" + format + u8"’") + { + } + }; + + class option_not_exists_exception : public OptionParseException + { + public: + option_not_exists_exception(const std::string& option) + : OptionParseException(u8"Option ‘" + option + u8"’ does not exist") + { + } + }; + + class missing_argument_exception : public OptionParseException + { + public: + missing_argument_exception(const std::string& option) + : OptionParseException(u8"Option ‘" + option + u8"’ is missing an argument") + { + } + }; + + class option_requires_argument_exception : public OptionParseException + { + public: + option_requires_argument_exception(const std::string& option) + : OptionParseException(u8"Option ‘" + option + u8"’ requires an argument") + { + } + }; + + class option_not_has_argument_exception : public OptionParseException + { + public: + option_not_has_argument_exception + ( + const std::string& option, + const std::string& arg + ) + : OptionParseException( + u8"Option ‘" + option + u8"’ does not take an argument, but argument‘" + + arg + "’ given") + { + } + }; + + class option_not_present_exception : public OptionParseException + { + public: + option_not_present_exception(const std::string& option) + : OptionParseException(u8"Option ‘" + option + u8"’ not present") + { + } + }; + + class argument_incorrect_type : public OptionParseException + { + public: + argument_incorrect_type + ( + const std::string& arg + ) + : OptionParseException( + u8"Argument ‘" + arg + u8"’ failed to parse" + ) + { + } + }; + + namespace values + { + template + void + parse_value(const std::string& text, T& value) + { + std::istringstream is(text); + if (!(is >> value)) + { + throw argument_incorrect_type(text); + } + + if (is.rdbuf()->in_avail() != 0) + { + throw argument_incorrect_type(text); + } + } + + inline + void + parse_value(const std::string& /*text*/, bool& value) + { + //TODO recognise on, off, yes, no, enable, disable + //so that we can write --long=yes explicitly + value = true; + } + + inline + void + parse_value(const std::string& text, std::string& value) + { + value = text; + } + + template + void + parse_value(const std::string& text, std::vector& value) + { + T v; + parse_value(text, v); + value.push_back(v); + } + + template + struct value_has_arg + { + static constexpr bool value = true; + }; + + template <> + struct value_has_arg + { + static constexpr bool value = false; + }; + + template + struct type_is_container + { + static constexpr bool value = false; + }; + + template + struct type_is_container> + { + static constexpr bool value = true; + }; + + template + class standard_value : public Value + { + public: + standard_value() + : m_result(std::make_shared()) + , m_store(m_result.get()) + { + } + + standard_value(T* t) + : m_store(t) + { + } + + void + parse(const std::string& text) const + { + if (m_implicit && text.empty()) + { + parse_value(m_implicit_value, *m_store); + } + else + { + parse_value(text, *m_store); + } + } + + bool + is_container() const + { + return type_is_container::value; + } + + void + parse() const + { + parse_value(m_default_value, *m_store); + } + + bool + has_arg() const + { + return value_has_arg::value; + } + + bool + has_default() const + { + return m_default; + } + + bool + has_implicit() const + { + return m_implicit; + } + + virtual std::shared_ptr + default_value(const std::string& value){ + m_default = true; + m_default_value = value; + return shared_from_this(); + } + + virtual std::shared_ptr + implicit_value(const std::string& value){ + m_implicit = true; + m_implicit_value = value; + return shared_from_this(); + } + + std::string + get_default_value() const + { + return m_default_value; + } + + std::string + get_implicit_value() const + { + return m_implicit_value; + } + + const T& + get() const + { + if (m_store == nullptr) + { + return *m_result; + } + else + { + return *m_store; + } + } + + protected: + std::shared_ptr m_result; + T* m_store; + bool m_default = false; + std::string m_default_value; + bool m_implicit = false; + std::string m_implicit_value; + }; + } + + template + std::shared_ptr + value() + { + return std::make_shared>(); + } + + template + std::shared_ptr + value(T& t) + { + return std::make_shared>(&t); + } + + class OptionAdder; + + class OptionDetails + { + public: + OptionDetails + ( + const String& description, + std::shared_ptr value + ) + : m_desc(description) + , m_value(value) + , m_count(0) + { + } + + const String& + description() const + { + return m_desc; + } + + bool + has_arg() const + { + return m_value->has_arg(); + } + + void + parse(const std::string& text) + { + m_value->parse(text); + ++m_count; + } + + void + parse_default() + { + m_value->parse(); + } + + int + count() const + { + return m_count; + } + + const Value& value() const { + return *m_value; + } + + template + const T& + as() const + { +#ifdef CXXOPTS_NO_RTTI + return static_cast&>(*m_value).get(); +#else + return dynamic_cast&>(*m_value).get(); +#endif + } + + private: + String m_desc; + std::shared_ptr m_value; + int m_count; + }; + + struct HelpOptionDetails + { + std::string s; + std::string l; + String desc; + bool has_arg; + bool has_default; + std::string default_value; + bool has_implicit; + std::string implicit_value; + std::string arg_help; + bool is_container; + }; + + struct HelpGroupDetails + { + std::string name; + std::string description; + std::vector options; + }; + + class Options + { + public: + + Options(std::string program, std::string help_string = "") + : m_program(std::move(program)) + , m_help_string(toLocalString(std::move(help_string))) + , m_next_positional(m_positional.end()) + { + } + + inline + void + parse(int& argc, char**& argv); + + inline + OptionAdder + add_options(std::string group = ""); + + inline + void + add_option + ( + const std::string& group, + const std::string& s, + const std::string& l, + std::string desc, + std::shared_ptr value, + std::string arg_help + ); + + int + count(const std::string& o) const + { + auto iter = m_options.find(o); + if (iter == m_options.end()) + { + return 0; + } + + return iter->second->count(); + } + + const OptionDetails& + operator[](const std::string& option) const + { + auto iter = m_options.find(option); + + if (iter == m_options.end()) + { + throw option_not_present_exception(option); + } + + return *iter->second; + } + + //parse positional arguments into the given option + inline + void + parse_positional(std::string option); + + inline + void + parse_positional(std::vector options); + + inline + std::string + help(const std::vector& groups = {""}) const; + + inline + const std::vector + groups() const; + + inline + const HelpGroupDetails& + group_help(const std::string& group) const; + + private: + + inline + void + add_one_option + ( + const std::string& option, + std::shared_ptr details + ); + + inline + bool + consume_positional(std::string a); + + inline + void + add_to_option(const std::string& option, const std::string& arg); + + inline + void + parse_option + ( + std::shared_ptr value, + const std::string& name, + const std::string& arg = "" + ); + + inline + void + checked_parse_arg + ( + int argc, + char* argv[], + int& current, + std::shared_ptr value, + const std::string& name + ); + + inline + String + help_one_group(const std::string& group) const; + + std::string m_program; + String m_help_string; + + std::map> m_options; + std::vector m_positional; + std::vector::iterator m_next_positional; + std::unordered_set m_positional_set; + + //mapping from groups to help options + std::map m_help; + }; + + class OptionAdder + { + public: + + OptionAdder(Options& options, std::string group) + : m_options(options), m_group(std::move(group)) + { + } + + inline + OptionAdder& + operator() + ( + const std::string& opts, + const std::string& desc, + std::shared_ptr value + = ::cxxopts::value(), + std::string arg_help = "" + ); + + private: + Options& m_options; + std::string m_group; + }; + +} + +namespace cxxopts +{ + + namespace + { + + constexpr int OPTION_LONGEST = 30; + constexpr int OPTION_DESC_GAP = 2; + + std::basic_regex option_matcher + ("--([[:alnum:]][-_[:alnum:]]+)(=(.*))?|-([[:alnum:]]+)"); + + std::basic_regex option_specifier + ("(([[:alnum:]]),)?([[:alnum:]][-_[:alnum:]]+)"); + + String + format_option + ( + const HelpOptionDetails& o + ) + { + auto& s = o.s; + auto& l = o.l; + + String result = " "; + + if (s.size() > 0) + { + result += "-" + toLocalString(s) + ","; + } + else + { + result += " "; + } + + if (l.size() > 0) + { + result += " --" + toLocalString(l); + } + + if (o.has_arg) + { + auto arg = o.arg_help.size() > 0 ? toLocalString(o.arg_help) : "arg"; + + if (o.has_implicit) + { + result += " [=" + arg + "(=" + toLocalString(o.implicit_value) + ")]"; + } + else + { + result += " " + arg; + } + } + + return result; + } + + String + format_description + ( + const HelpOptionDetails& o, + size_t start, + size_t width + ) + { + auto desc = o.desc; + + if (o.has_default) + { + desc += toLocalString(" (default: " + o.default_value + ")"); + } + + String result; + + auto current = std::begin(desc); + auto startLine = current; + auto lastSpace = current; + + auto size = size_t{}; + + while (current != std::end(desc)) + { + if (*current == ' ') + { + lastSpace = current; + } + + if (size > width) + { + if (lastSpace == startLine) + { + stringAppend(result, startLine, current + 1); + stringAppend(result, "\n"); + stringAppend(result, start, ' '); + startLine = current + 1; + lastSpace = startLine; + } + else + { + stringAppend(result, startLine, lastSpace); + stringAppend(result, "\n"); + stringAppend(result, start, ' '); + startLine = lastSpace + 1; + } + size = 0; + } + else + { + ++size; + } + + ++current; + } + + //append whatever is left + stringAppend(result, startLine, current); + + return result; + } + } + +OptionAdder +Options::add_options(std::string group) +{ + return OptionAdder(*this, std::move(group)); +} + +OptionAdder& +OptionAdder::operator() +( + const std::string& opts, + const std::string& desc, + std::shared_ptr value, + std::string arg_help +) +{ + std::match_results result; + std::regex_match(opts.c_str(), result, option_specifier); + + if (result.empty()) + { + throw invalid_option_format_error(opts); + } + + const auto& s = result[2]; + const auto& l = result[3]; + + m_options.add_option(m_group, s.str(), l.str(), desc, value, + std::move(arg_help)); + + return *this; +} + +void +Options::parse_option +( + std::shared_ptr value, + const std::string& /*name*/, + const std::string& arg +) +{ + value->parse(arg); +} + +void +Options::checked_parse_arg +( + int argc, + char* argv[], + int& current, + std::shared_ptr value, + const std::string& name +) +{ + if (current + 1 >= argc) + { + if (value->value().has_implicit()) + { + parse_option(value, name, ""); + } + else + { + throw missing_argument_exception(name); + } + } + else + { + if (argv[current + 1][0] == '-' && value->value().has_implicit()) + { + parse_option(value, name, ""); + } + else + { + parse_option(value, name, argv[current + 1]); + ++current; + } + } +} + +void +Options::add_to_option(const std::string& option, const std::string& arg) +{ + auto iter = m_options.find(option); + + if (iter == m_options.end()) + { + throw option_not_exists_exception(option); + } + + parse_option(iter->second, option, arg); +} + +bool +Options::consume_positional(std::string a) +{ + while (m_next_positional != m_positional.end()) + { + auto iter = m_options.find(*m_next_positional); + if (iter != m_options.end()) + { + if (!iter->second->value().is_container()) + { + if (iter->second->count() == 0) + { + add_to_option(*m_next_positional, a); + ++m_next_positional; + return true; + } + else + { + ++m_next_positional; + continue; + } + } + else + { + add_to_option(*m_next_positional, a); + return true; + } + } + ++m_next_positional; + } + + return false; +} + +void +Options::parse_positional(std::string option) +{ + parse_positional(std::vector{option}); +} + +void +Options::parse_positional(std::vector options) +{ + m_positional = std::move(options); + m_next_positional = m_positional.begin(); + + m_positional_set.insert(m_positional.begin(), m_positional.end()); +} + +void +Options::parse(int& argc, char**& argv) +{ + int current = 1; + + int nextKeep = 1; + + bool consume_remaining = false; + + while (current != argc) + { + if (strcmp(argv[current], "--") == 0) + { + consume_remaining = true; + ++current; + break; + } + + std::match_results result; + std::regex_match(argv[current], result, option_matcher); + + if (result.empty()) + { + //not a flag + + //if true is returned here then it was consumed, otherwise it is + //ignored + if (consume_positional(argv[current])) + { + } + else + { + argv[nextKeep] = argv[current]; + ++nextKeep; + } + //if we return from here then it was parsed successfully, so continue + } + else + { + //short or long option? + if (result[4].length() != 0) + { + const std::string& s = result[4]; + + for (std::size_t i = 0; i != s.size(); ++i) + { + std::string name(1, s[i]); + auto iter = m_options.find(name); + + if (iter == m_options.end()) + { + throw option_not_exists_exception(name); + } + + auto value = iter->second; + + //if no argument then just add it + if (!value->has_arg()) + { + parse_option(value, name); + } + else + { + //it must be the last argument + if (i + 1 == s.size()) + { + checked_parse_arg(argc, argv, current, value, name); + } + else if (value->value().has_implicit()) + { + parse_option(value, name, ""); + } + else + { + //error + throw option_requires_argument_exception(name); + } + } + } + } + else if (result[1].length() != 0) + { + const std::string& name = result[1]; + + auto iter = m_options.find(name); + + if (iter == m_options.end()) + { + throw option_not_exists_exception(name); + } + + auto opt = iter->second; + + //equals provided for long option? + if (result[3].length() != 0) + { + //parse the option given + + //but if it doesn't take an argument, this is an error + if (!opt->has_arg()) + { + throw option_not_has_argument_exception(name, result[3]); + } + + parse_option(opt, name, result[3]); + } + else + { + if (opt->has_arg()) + { + //parse the next argument + checked_parse_arg(argc, argv, current, opt, name); + } + else + { + //parse with empty argument + parse_option(opt, name); + } + } + } + + } + + ++current; + } + + for (auto& opt : m_options) + { + auto& detail = opt.second; + auto& value = detail->value(); + + if(!detail->count() && value.has_default()){ + detail->parse_default(); + } + } + + if (consume_remaining) + { + while (current < argc) + { + consume_positional(argv[current]); + ++current; + } + } + + argc = nextKeep; + +} + +void +Options::add_option +( + const std::string& group, + const std::string& s, + const std::string& l, + std::string desc, + std::shared_ptr value, + std::string arg_help +) +{ + auto stringDesc = toLocalString(std::move(desc)); + auto option = std::make_shared(stringDesc, value); + + if (s.size() > 0) + { + add_one_option(s, option); + } + + if (l.size() > 0) + { + add_one_option(l, option); + } + + //add the help details + auto& options = m_help[group]; + + options.options.emplace_back(HelpOptionDetails{s, l, stringDesc, + value->has_arg(), + value->has_default(), value->get_default_value(), + value->has_implicit(), value->get_implicit_value(), + std::move(arg_help), + value->is_container()}); +} + +void +Options::add_one_option +( + const std::string& option, + std::shared_ptr details +) +{ + auto in = m_options.emplace(option, details); + + if (!in.second) + { + throw option_exists_error(option); + } +} + +String +Options::help_one_group(const std::string& g) const +{ + typedef std::vector> OptionHelp; + + auto group = m_help.find(g); + if (group == m_help.end()) + { + return ""; + } + + OptionHelp format; + + size_t longest = 0; + + String result; + + if (!g.empty()) + { + result += toLocalString(" " + g + " options:\n"); + } + + for (const auto& o : group->second.options) + { + if (o.is_container && m_positional_set.find(o.l) != m_positional_set.end()) + { + continue; + } + + auto s = format_option(o); + longest = std::max(longest, stringLength(s)); + format.push_back(std::make_pair(s, String())); + } + + longest = std::min(longest, static_cast(OPTION_LONGEST)); + + //widest allowed description + auto allowed = size_t{76} - longest - OPTION_DESC_GAP; + + auto fiter = format.begin(); + for (const auto& o : group->second.options) + { + if (o.is_container && m_positional_set.find(o.l) != m_positional_set.end()) + { + continue; + } + + auto d = format_description(o, longest + OPTION_DESC_GAP, allowed); + + result += fiter->first; + if (stringLength(fiter->first) > longest) + { + result += '\n'; + result += toLocalString(std::string(longest + OPTION_DESC_GAP, ' ')); + } + else + { + result += toLocalString(std::string(longest + OPTION_DESC_GAP - + stringLength(fiter->first), + ' ')); + } + result += d; + result += '\n'; + + ++fiter; + } + + return result; +} + +std::string +Options::help(const std::vector& groups) const +{ + String result = m_help_string + "\nUsage:\n " + + toLocalString(m_program) + " [OPTION...]"; + + if (m_positional.size() > 0) { + result += " positional parameters"; + } + + result += "\n\n"; + + for (std::size_t i = 0; i < groups.size(); ++i) + { + String const& group_help = help_one_group(groups[i]); + if (empty(group_help)) continue; + result += group_help; + if (i < groups.size() - 1) + { + result += '\n'; + } + } + + return toUTF8String(result); +} + +const std::vector +Options::groups() const +{ + std::vector g; + + std::transform( + m_help.begin(), + m_help.end(), + std::back_inserter(g), + [] (const std::map::value_type& pair) + { + return pair.first; + } + ); + + return g; +} + +const HelpGroupDetails& +Options::group_help(const std::string& group) const +{ + return m_help.at(group); +} + +} + +#if defined(__GNU__) +#pragma GCC diagnostic pop +#endif + +#endif //CXX_OPTS_HPP diff --git a/Externals/imgui-1.46/Lib/Debug/imgui.lib b/Externals/imgui-1.46/Lib/Debug/imgui.lib deleted file mode 100644 index f2cc5d8..0000000 Binary files a/Externals/imgui-1.46/Lib/Debug/imgui.lib and /dev/null differ diff --git a/Externals/imgui-1.46/Lib/Debug/imgui.pdb b/Externals/imgui-1.46/Lib/Debug/imgui.pdb deleted file mode 100644 index 373a609..0000000 Binary files a/Externals/imgui-1.46/Lib/Debug/imgui.pdb and /dev/null differ diff --git a/Externals/imgui-1.46/Lib/Release/imgui.lib b/Externals/imgui-1.46/Lib/Release/imgui.lib deleted file mode 100644 index 602c876..0000000 Binary files a/Externals/imgui-1.46/Lib/Release/imgui.lib and /dev/null differ diff --git a/Externals/imgui-1.46/Lib/Release/imgui.pdb b/Externals/imgui-1.46/Lib/Release/imgui.pdb deleted file mode 100644 index 02050a3..0000000 Binary files a/Externals/imgui-1.46/Lib/Release/imgui.pdb and /dev/null differ diff --git a/README.md b/README.md index b4ec2ed..eab7172 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,17 @@ This project is a D3D12 rendering sample that implements a deferred renderer using bindless deferred texturing. Deferred texturing is similar to normal deferred rendering, except that textures are not sampled in the geometry pass. Instead, the interpolated UV's are written into the G-Buffer so that the material textures can be sampled during the deferred pass. To enable sampling of textures from arbitrary materials, the demo makes use of dynamic indexing of texture descriptors. The demo also implements a deferred decal system using a clustering technique that's compatible with both deferred texturing as well as clustered forward rendering (which is also implemented in the demo as a baseline for comparison). -See the full blog post for more info: [https://mynameismjp.wordpress.com/2016/03/25/bindless-texturing-for-deferred-rendering-and-decals/](https://mynameismjp.wordpress.com/2016/03/25/bindless-texturing-for-deferred-rendering-and-decals/) +See the full blog post for more info: [https://therealmjp.github.io/posts/bindless-texturing-for-deferred-rendering-and-decals/](https://therealmjp.github.io/posts/bindless-texturing-for-deferred-rendering-and-decals/) # Build Instructions The repository contains a Visual Studio 2015 project and solution file that's ready to build on Windows. All external dependencies are included in the repository, so there's no need to download additional libraries. Running the demo requires Windows 10, as well as a GPU that supports Feature Level 11_1. -# Using the Demo App +# Using The Demo App + +To move the camera, press the W/S/A/D/Q/E keys. The camera can also be rotated by right-clicking on the window and dragging the mouse. To place new decals, click the middle mouse button. Everything else is controlled through the in-app settings UI. + +# Using the new DirectX Shader Compiler + +This project supports using the new [open-source HLSL compiler](https://github.com/Microsoft/DirectXShaderCompiler) (also known as DXC), with support for Shader Model 6.0+. Usage of the new compiler is controlled by the "EnableShaderModel6_" macro that's defined in AppConfig.h. If you enable this flag, you'll want to make sure that you're on Windows 10 version 1803 or later to enable retail support for loading DXIL. If you're on an earlier Win10 version or an older driver, you may need to enable experimental feature support for D3D12ExperimentalShaderModels (see DX12.cpp for some code you can enable to do this). -To move the camera, press the W/S/A/D/Q/E keys. The camera can also be rotated by right-clicking on the window and dragging the mouse. To place new decals, click the middle mouse button. Everything else is controlled through the in-app settings UI. \ No newline at end of file diff --git a/SampleFramework12/.gitignore b/SampleFramework12/.gitignore new file mode 100644 index 0000000..0dceebf --- /dev/null +++ b/SampleFramework12/.gitignore @@ -0,0 +1,5 @@ +## Exclusions for SampleFramework12 + +!SettingsCompiler.exe +!SettingsCompilerAttributes.dll +!Packager.exe \ No newline at end of file diff --git a/SampleFramework12/v1.00/Graphics/GraphicsTypes.cpp b/SampleFramework12/v1.00/Graphics/GraphicsTypes.cpp deleted file mode 100644 index 6e3023e..0000000 --- a/SampleFramework12/v1.00/Graphics/GraphicsTypes.cpp +++ /dev/null @@ -1,1287 +0,0 @@ -//================================================================================================= -// -// MJP's DX12 Sample Framework -// http://mynameismjp.wordpress.com/ -// -// All code licensed under the MIT license -// -//================================================================================================= - -#include "PCH.h" - -#include "GraphicsTypes.h" -#include "..\\Exceptions.h" -#include "..\\Utility.h" -#include "..\\Serialization.h" -#include "..\\FileIO.h" - -namespace SampleFramework12 -{ - -// == DescriptorHeap ============================================================================== - -DescriptorHeap::~DescriptorHeap() -{ - Assert_(Heap == nullptr); -} - -void DescriptorHeap::Init(ID3D12Device* device, uint64 numDescriptors, D3D12_DESCRIPTOR_HEAP_TYPE heapType, bool shaderVisible) -{ - Shutdown(); - Assert_(numDescriptors > 0); - - NumDescriptors = numDescriptors; - HeapType = heapType; - ShaderVisible = shaderVisible; - if(heapType == D3D12_DESCRIPTOR_HEAP_TYPE_RTV || heapType == D3D12_DESCRIPTOR_HEAP_TYPE_DSV) - ShaderVisible = false; - - DeadList.Init(numDescriptors); - for(uint64 i = 0; i < numDescriptors; ++i) - DeadList[i] = uint32(i); - - D3D12_DESCRIPTOR_HEAP_DESC heapDesc = { }; - heapDesc.NumDescriptors = uint32(numDescriptors); - heapDesc.Type = heapType; - heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; - if(ShaderVisible) - heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; - - DXCall(device->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&Heap))); - - CPUStart = Heap->GetCPUDescriptorHandleForHeapStart(); - if(ShaderVisible) - GPUStart = Heap->GetGPUDescriptorHandleForHeapStart(); - - DescriptorSize = device->GetDescriptorHandleIncrementSize(heapType); -} - -void DescriptorHeap::Shutdown() -{ - Assert_(Allocated == 0); - DX12::Release(Heap); -} - -DescriptorHandle DescriptorHeap::Allocate() -{ - Assert_(Heap != nullptr); - Assert_(Allocated < NumDescriptors); - uint64 idx = DeadList[Allocated]; - ++Allocated; - - DescriptorHandle handle; - handle.CPUHandle = CPUStart; - handle.CPUHandle.ptr += idx * DescriptorSize; - if(ShaderVisible) - { - handle.GPUHandle = GPUStart; - handle.GPUHandle.ptr += idx * DescriptorSize; - } - - #if UseAsserts_ - handle.ParentHeap = reinterpret_cast(this); - #endif - - return handle; -} - -void DescriptorHeap::Free(DescriptorHandle& handle) -{ - if(handle.IsValid() == false) - return; - - #if UseAsserts_ - Assert_(reinterpret_cast(this) == handle.ParentHeap); - #endif - - Assert_(Heap != nullptr); - Assert_(Allocated > 0); - Assert_(handle.CPUHandle.ptr >= CPUStart.ptr); - uint64 heapIdx = (handle.CPUHandle.ptr - CPUStart.ptr) / DescriptorSize; - Assert_(heapIdx < NumDescriptors); - - DeadList[Allocated - 1] = uint32(heapIdx); - --Allocated; - - handle = DescriptorHandle(); -} - -// == LinearDescriptorHeap ======================================================================== - -LinearDescriptorHeap::~LinearDescriptorHeap() -{ - Assert_(Heap == nullptr); -} - -void LinearDescriptorHeap::Init(ID3D12Device* device, uint64 numDescriptors, D3D12_DESCRIPTOR_HEAP_TYPE heapType, bool shaderVisible) -{ - Shutdown(); - - Assert_(numDescriptors > 0); - - Allocated = 0; - NumDescriptors = numDescriptors; - HeapType = heapType; - ShaderVisible = shaderVisible; - if (heapType == D3D12_DESCRIPTOR_HEAP_TYPE_RTV || heapType == D3D12_DESCRIPTOR_HEAP_TYPE_DSV) - ShaderVisible = false; - - D3D12_DESCRIPTOR_HEAP_DESC heapDesc = { }; - heapDesc.NumDescriptors = uint32(numDescriptors); - heapDesc.Type = heapType; - heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; - if(ShaderVisible) - heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; - - DXCall(device->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&Heap))); - - CPUStart = Heap->GetCPUDescriptorHandleForHeapStart(); - if(ShaderVisible) - GPUStart = Heap->GetGPUDescriptorHandleForHeapStart(); - - DescriptorSize = device->GetDescriptorHandleIncrementSize(heapType); -} - -void LinearDescriptorHeap::Shutdown() -{ - DX12::Release(Heap); -} - -DescriptorHandle LinearDescriptorHeap::Allocate(uint64 count) -{ - Assert_(Heap != nullptr); - Assert_(count > 0); - Assert_(Allocated + count <= NumDescriptors); - - uint64 idx = Allocated; - - DescriptorHandle handle; - handle.CPUHandle = CPUStart; - handle.CPUHandle.ptr += idx * DescriptorSize; - if(ShaderVisible) - { - handle.GPUHandle = GPUStart; - handle.GPUHandle.ptr += idx * DescriptorSize; - } - - Allocated += count; - - return handle; -} - -void LinearDescriptorHeap::Reset() -{ - Allocated = 0; -} - -// == Buffer ====================================================================================== - -Buffer::Buffer() -{ -} - -Buffer::~Buffer() -{ - Assert_(Resource == nullptr); -} - -void Buffer::Initialize(uint64 size, uint64 alignment, bool32 dynamic, BufferLifetime lifetime, bool32 allowUAV, const void* initData, D3D12_RESOURCE_STATES initialState) -{ - Assert_(size > 0); - Assert_(alignment > 0); - - Size = AlignTo(size, alignment); - Alignment = alignment; - Lifetime = lifetime; - Dynamic = dynamic; - CurrBuffer = 0; - CPUAddress = nullptr; - GPUAddress = 0; - - Assert_(Lifetime == BufferLifetime::Persistent || dynamic); - Assert_(allowUAV == false || dynamic == false); - - if(Lifetime == BufferLifetime::Persistent) - { - D3D12_RESOURCE_DESC resourceDesc = { }; - resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - resourceDesc.Width = uint32(dynamic ? Size * DX12::RenderLatency : Size); - resourceDesc.Height = 1; - resourceDesc.DepthOrArraySize = 1; - resourceDesc.MipLevels = 1; - resourceDesc.Format = DXGI_FORMAT_UNKNOWN; - resourceDesc.Flags = allowUAV ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE; - resourceDesc.SampleDesc.Count = 1; - resourceDesc.SampleDesc.Quality = 0; - resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - resourceDesc.Alignment = 0; - - const D3D12_HEAP_PROPERTIES* heapProps = dynamic ? DX12::GetUploadHeapProps() : DX12::GetDefaultHeapProps(); - D3D12_RESOURCE_STATES resourceState = initialState; - if(initData && dynamic == false) - resourceState = D3D12_RESOURCE_STATE_COPY_DEST; - - DXCall(DX12::Device->CreateCommittedResource(heapProps, D3D12_HEAP_FLAG_NONE, &resourceDesc, - resourceState, nullptr, IID_PPV_ARGS(&Resource))); - - GPUAddress = Resource->GetGPUVirtualAddress(); - - if(dynamic) - { - D3D12_RANGE readRange = { }; - DXCall(Resource->Map(0, &readRange, reinterpret_cast(&CPUAddress))); - } - - if(initData && dynamic) - { - for(uint64 i = 0; i < DX12::RenderLatency; ++i) - { - uint8* dstMem = CPUAddress + Size * i; - memcpy(dstMem, initData, size); - } - - } - else if(initData) - { - UploadContext uploadContext = DX12::ResourceUploadBegin(resourceDesc.Width); - - memcpy(uploadContext.CPUAddress, initData, size); - - uploadContext.CmdList->CopyBufferRegion(Resource, 0, uploadContext.Resource, uploadContext.ResourceOffset, size); - - DX12::ResourceUploadEnd(uploadContext); - } - } -} - -void Buffer::Shutdown() -{ - DX12::DeferredRelease(Resource); -} - -MapResult Buffer::Map() -{ - Assert_(Initialized()); - Assert_(Dynamic); - - if(Lifetime == BufferLifetime::Persistent) - { - #if UseAsserts_ - // Make sure that we onlt do this at most once per frame - Assert_(UploadFrame != DX12::CurrentCPUFrame); - UploadFrame = DX12::CurrentCPUFrame; - #endif - CurrBuffer = (CurrBuffer + 1) % DX12::RenderLatency; - - MapResult result; - result.ResourceOffset = CurrBuffer * Size; - result.CPUAddress = CPUAddress + CurrBuffer * Size; - result.GPUAddress = GPUAddress + CurrBuffer * Size; - result.Resource = Resource; - return result; - } - else - { - Assert_(Lifetime == BufferLifetime::Temporary); - - #if UseAsserts_ - UploadFrame = DX12::CurrentCPUFrame; - #endif - - return DX12::AcquireTempBufferMem(Size, Alignment); - } -} - -MapResult Buffer::MapAndSetData(const void* data, uint64 dataSize) -{ - Assert_(dataSize <= Size); - MapResult result = Map(); - memcpy(result.CPUAddress, data, dataSize); - return result; -} - -void Buffer::UpdateData(const void* srcData, uint64 srcSize, uint64 dstOffset) -{ - Assert_(Dynamic == false); - Assert_(dstOffset + srcSize <= Size); - - UploadContext uploadContext = DX12::ResourceUploadBegin(srcSize); - - memcpy(uploadContext.CPUAddress, srcData, srcSize); - - uploadContext.CmdList->CopyBufferRegion(Resource, dstOffset, uploadContext.Resource, uploadContext.ResourceOffset, srcSize); - - DX12::ResourceUploadEnd(uploadContext); -} - -void Buffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const -{ - Assert_(Resource != nullptr); - DX12::TransitionResource(cmdList, Resource, before, after); -} - -void Buffer::MakeReadable(ID3D12GraphicsCommandList* cmdList) const -{ - Assert_(Resource != nullptr); - DX12::TransitionResource(cmdList, Resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_GENERIC_READ); -} - -void Buffer::MakeWritable(ID3D12GraphicsCommandList* cmdList) const -{ - Assert_(Resource != nullptr); - DX12::TransitionResource(cmdList, Resource, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); -} - -void Buffer::UAVBarrier(ID3D12GraphicsCommandList* cmdList) const -{ - Assert_(Resource != nullptr); - D3D12_RESOURCE_BARRIER barrier = { }; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; - barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barrier.UAV.pResource = Resource; - cmdList->ResourceBarrier(1, &barrier); -} - -#if UseAsserts_ - -bool Buffer::ReadyForBinding() const -{ - if(Dynamic && Lifetime == BufferLifetime::Temporary) - return UploadFrame == DX12::CurrentCPUFrame; - else - return Initialized(); -} - -#endif - -// == StructuredBuffer ============================================================================ - -StructuredBuffer::StructuredBuffer() -{ - -} - -StructuredBuffer::~StructuredBuffer() -{ - Assert_(NumElements == 0); - Shutdown(); -} - -void StructuredBuffer::Initialize(const StructuredBufferInit& init) -{ - Shutdown(); - - Assert_(init.Stride > 0); - Assert_(init.NumElements > 0); - Stride = init.Stride; - NumElements = init.NumElements; - - InternalBuffer.Initialize(Stride * NumElements, Stride, init.Dynamic, init.Lifetime, init.CreateUAV, init.InitData, init.InitialState); - GPUAddress = InternalBuffer.GPUAddress; - - if(init.Lifetime == BufferLifetime::Persistent) - { - const uint64 numSRVs = init.Dynamic ? DX12::RenderLatency : 1; - for(uint64 i = 0; i < numSRVs; ++i) - { - SRVHandles[i] = DX12::SRVDescriptorHeap.Allocate(); - - D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; - srvDesc.Format = DXGI_FORMAT_UNKNOWN; - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srvDesc.Buffer.FirstElement = uint32(NumElements * i); - srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; - srvDesc.Buffer.NumElements = uint32(NumElements); - srvDesc.Buffer.StructureByteStride = uint32(Stride); - DX12::Device->CreateShaderResourceView(InternalBuffer.Resource, &srvDesc, SRVHandles[i].CPUHandle); - } - } - else if(init.Lifetime == BufferLifetime::Temporary) - { - SRVHandles[0] = DX12::SRVDescriptorHeap.Allocate(); - } - - if(init.CreateUAV) - { - Assert_(init.Dynamic == false); - - ID3D12Resource* counterRes = nullptr; - if(init.UseCounter) - { - D3D12_RESOURCE_DESC resourceDesc = { }; - resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - resourceDesc.Width = sizeof(uint32); - resourceDesc.Height = 1; - resourceDesc.DepthOrArraySize = 1; - resourceDesc.MipLevels = 1; - resourceDesc.Format = DXGI_FORMAT_UNKNOWN; - resourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - resourceDesc.SampleDesc.Count = 1; - resourceDesc.SampleDesc.Quality = 0; - resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - resourceDesc.Alignment = 0; - DXCall(DX12::Device->CreateCommittedResource(DX12::GetDefaultHeapProps(), D3D12_HEAP_FLAG_NONE, &resourceDesc, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&CounterResource))); - - counterRes = CounterResource; - - CounterUAV = DX12::SRVDescriptorHeap.Allocate(); - - D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {}; - uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; - uavDesc.Format = DXGI_FORMAT_UNKNOWN; - uavDesc.Buffer.CounterOffsetInBytes = 0; - uavDesc.Buffer.FirstElement = 0; - uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; - uavDesc.Buffer.NumElements = 1; - uavDesc.Buffer.StructureByteStride = sizeof(uint32); - - DX12::Device->CreateUnorderedAccessView(counterRes, nullptr, &uavDesc, CounterUAV.CPUHandle); - } - - UAVHandle = DX12::SRVDescriptorHeap.Allocate(); - - D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = { }; - uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; - uavDesc.Format = DXGI_FORMAT_UNKNOWN; - uavDesc.Buffer.CounterOffsetInBytes = 0; - uavDesc.Buffer.FirstElement = 0; - uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; - uavDesc.Buffer.NumElements = uint32(NumElements); - uavDesc.Buffer.StructureByteStride = uint32(Stride); - - DX12::Device->CreateUnorderedAccessView(InternalBuffer.Resource, counterRes, &uavDesc, UAVHandle.CPUHandle); - } -} - -void StructuredBuffer::Shutdown() -{ - for(uint64 i = 0; i < ArraySize_(SRVHandles); ++i) - DX12::SRVDescriptorHeap.Free(SRVHandles[i]); - DX12::SRVDescriptorHeap.Free(UAVHandle); - DX12::SRVDescriptorHeap.Free(CounterUAV); - InternalBuffer.Shutdown(); - DX12::DeferredRelease(CounterResource); - Stride = 0; - NumElements = 0; -} - -D3D12_CPU_DESCRIPTOR_HANDLE StructuredBuffer::SRV() const -{ - Assert_(InternalBuffer.ReadyForBinding()); - Assert_(SRVHandles[InternalBuffer.CurrBuffer].IsValid()); - return SRVHandles[InternalBuffer.CurrBuffer].CPUHandle; -} - -D3D12_CPU_DESCRIPTOR_HANDLE StructuredBuffer::UAV() const -{ - Assert_(UAVHandle.IsValid()); - return UAVHandle.CPUHandle; -} - -D3D12_VERTEX_BUFFER_VIEW StructuredBuffer::VBView() const -{ - Assert_(InternalBuffer.ReadyForBinding()); - D3D12_VERTEX_BUFFER_VIEW vbView = { }; - vbView.BufferLocation = GPUAddress; - vbView.StrideInBytes = uint32(Stride); - vbView.SizeInBytes = uint32(InternalBuffer.Size); - return vbView; -} - -void* StructuredBuffer::Map() -{ - MapResult mapResult = InternalBuffer.Map(); - if(InternalBuffer.Lifetime == BufferLifetime::Temporary) - { - Assert_(SRVHandles[0].IsValid()); - Assert_(mapResult.ResourceOffset % Stride == 0); - - D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { }; - srvDesc.Format = DXGI_FORMAT_UNKNOWN; - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srvDesc.Buffer.FirstElement = uint32(mapResult.ResourceOffset / Stride); - srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; - srvDesc.Buffer.NumElements = uint32(NumElements); - srvDesc.Buffer.StructureByteStride = uint32(Stride); - DX12::Device->CreateShaderResourceView(mapResult.Resource, &srvDesc, SRVHandles[0].CPUHandle); - } - - GPUAddress = mapResult.GPUAddress; - - return mapResult.CPUAddress; -} - -void StructuredBuffer::MapAndSetData(const void* data, uint64 numElements) -{ - Assert_(numElements <= NumElements); - void* cpuAddr = Map(); - memcpy(cpuAddr, data, numElements * Stride); -} - -void StructuredBuffer::UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset) -{ - InternalBuffer.UpdateData(srcData, srcNumElements * Stride, dstElemOffset * Stride); -} - -void StructuredBuffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const -{ - InternalBuffer.Transition(cmdList, before, after); -} - -void StructuredBuffer::MakeReadable(ID3D12GraphicsCommandList* cmdList) const -{ - InternalBuffer.MakeReadable(cmdList); -} - -void StructuredBuffer::MakeWritable(ID3D12GraphicsCommandList* cmdList) const -{ - InternalBuffer.MakeWritable(cmdList); -} - -void StructuredBuffer::UAVBarrier(ID3D12GraphicsCommandList* cmdList) const -{ - InternalBuffer.UAVBarrier(cmdList); -} - -// == FormattedBuffer ============================================================================ - -FormattedBuffer::FormattedBuffer() -{ -} - -FormattedBuffer::~FormattedBuffer() -{ - Assert_(NumElements == 0); - Shutdown(); -} - -void FormattedBuffer::Initialize(const FormattedBufferInit& init) -{ - Shutdown(); - - Assert_(init.Format != DXGI_FORMAT_UNKNOWN); - Assert_(init.NumElements > 0); - Stride = DirectX::BitsPerPixel(init.Format) / 8; - NumElements = init.NumElements; - Format = init.Format; - - InternalBuffer.Initialize(Stride * NumElements, Stride, init.Dynamic, init.Lifetime, init.CreateUAV, init.InitData, init.InitialState); - GPUAddress = InternalBuffer.GPUAddress; - - if(init.Lifetime == BufferLifetime::Persistent) - { - const uint64 numSRVs = init.Dynamic ? DX12::RenderLatency : 1; - for(uint64 i = 0; i < numSRVs; ++i) - { - SRVHandles[i] = DX12::SRVDescriptorHeap.Allocate(); - - D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { }; - srvDesc.Format = Format; - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srvDesc.Buffer.FirstElement = uint32(NumElements * i); - srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; - srvDesc.Buffer.NumElements = uint32(NumElements); - DX12::Device->CreateShaderResourceView(InternalBuffer.Resource, &srvDesc, SRVHandles[i].CPUHandle); - } - } - else if(init.Lifetime == BufferLifetime::Temporary) - { - SRVHandles[0] = DX12::SRVDescriptorHeap.Allocate(); - } - - if(init.CreateUAV) - { - Assert_(init.Dynamic == false); - - UAVHandle = DX12::SRVDescriptorHeap.Allocate(); - - D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = { }; - uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; - uavDesc.Format = Format; - uavDesc.Buffer.CounterOffsetInBytes = 0; - uavDesc.Buffer.FirstElement = 0; - uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; - uavDesc.Buffer.NumElements = uint32(NumElements); - - DX12::Device->CreateUnorderedAccessView(InternalBuffer.Resource, nullptr, &uavDesc, UAVHandle.CPUHandle); - } -} - -void FormattedBuffer::Shutdown() -{ - for(uint64 i = 0; i < ArraySize_(SRVHandles); ++i) - DX12::SRVDescriptorHeap.Free(SRVHandles[i]); - DX12::SRVDescriptorHeap.Free(UAVHandle); - InternalBuffer.Shutdown(); - Stride = 0; - NumElements = 0; -} - -D3D12_CPU_DESCRIPTOR_HANDLE FormattedBuffer::SRV() const -{ - Assert_(InternalBuffer.ReadyForBinding()); - Assert_(SRVHandles[InternalBuffer.CurrBuffer].IsValid()); - return SRVHandles[InternalBuffer.CurrBuffer].CPUHandle; -} - -D3D12_CPU_DESCRIPTOR_HANDLE FormattedBuffer::UAV() const -{ - Assert_(UAVHandle.IsValid()); - return UAVHandle.CPUHandle; -} - -D3D12_INDEX_BUFFER_VIEW FormattedBuffer::IBView() const -{ - Assert_(Format == DXGI_FORMAT_R16_UINT || Format == DXGI_FORMAT_R32_UINT); - D3D12_INDEX_BUFFER_VIEW ibView = { }; - ibView.BufferLocation = GPUAddress; - ibView.Format = Format; - ibView.SizeInBytes = uint32(InternalBuffer.Size); - return ibView; -} - -void* FormattedBuffer::Map() -{ - MapResult mapResult = InternalBuffer.Map(); - if(InternalBuffer.Lifetime == BufferLifetime::Temporary) - { - Assert_(SRVHandles[0].IsValid()); - Assert_(mapResult.ResourceOffset % Stride == 0); - - D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { }; - srvDesc.Format = Format; - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srvDesc.Buffer.FirstElement = uint32(mapResult.ResourceOffset / Stride); - srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; - srvDesc.Buffer.NumElements = uint32(NumElements); - DX12::Device->CreateShaderResourceView(mapResult.Resource, &srvDesc, SRVHandles[0].CPUHandle); - } - - GPUAddress = mapResult.GPUAddress; - return mapResult.CPUAddress; -} - -void FormattedBuffer::MapAndSetData(const void* data, uint64 numElements) -{ - Assert_(numElements <= NumElements); - void* cpuAddr = Map(); - memcpy(cpuAddr, data, numElements * Stride); -} - -void FormattedBuffer::UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset) -{ - InternalBuffer.UpdateData(srcData, srcNumElements * Stride, dstElemOffset * Stride); -} - -void FormattedBuffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const -{ - InternalBuffer.Transition(cmdList, before, after); -} - -void FormattedBuffer::MakeReadable(ID3D12GraphicsCommandList* cmdList) const -{ - InternalBuffer.MakeReadable(cmdList); -} - -void FormattedBuffer::MakeWritable(ID3D12GraphicsCommandList* cmdList) const -{ - InternalBuffer.MakeWritable(cmdList); -} - -void FormattedBuffer::UAVBarrier(ID3D12GraphicsCommandList* cmdList) const -{ - InternalBuffer.UAVBarrier(cmdList); -} - -// == RawBuffer ============================================================================ - -RawBuffer::RawBuffer() -{ -} - -RawBuffer::~RawBuffer() -{ - Assert_(NumElements == 0); - Shutdown(); -} - -void RawBuffer::Initialize(const RawBufferInit& init) -{ - Shutdown(); - - Assert_(init.NumElements > 0); - NumElements = init.NumElements; - - InternalBuffer.Initialize(Stride * NumElements, Stride, init.Dynamic, init.Lifetime, init.CreateUAV, init.InitData, init.InitialState); - GPUAddress = InternalBuffer.GPUAddress; - - if(init.Lifetime == BufferLifetime::Persistent) - { - const uint64 numSRVs = init.Dynamic ? DX12::RenderLatency : 1; - for(uint64 i = 0; i < numSRVs; ++i) - { - SRVHandles[i] = DX12::SRVDescriptorHeap.Allocate(); - - D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { }; - srvDesc.Format = DXGI_FORMAT_R32_TYPELESS; - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srvDesc.Buffer.FirstElement = uint32(NumElements * i); - srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; - srvDesc.Buffer.NumElements = uint32(NumElements); - DX12::Device->CreateShaderResourceView(InternalBuffer.Resource, &srvDesc, SRVHandles[i].CPUHandle); - } - } - else if(init.Lifetime == BufferLifetime::Temporary) - { - SRVHandles[0] = DX12::SRVDescriptorHeap.Allocate(); - } - - if(init.CreateUAV) - { - Assert_(init.Dynamic == false); - - UAVHandle = DX12::SRVDescriptorHeap.Allocate(); - - D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = { }; - uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; - uavDesc.Format = DXGI_FORMAT_R32_TYPELESS; - uavDesc.Buffer.CounterOffsetInBytes = 0; - uavDesc.Buffer.FirstElement = 0; - uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; - uavDesc.Buffer.NumElements = uint32(NumElements); - - DX12::Device->CreateUnorderedAccessView(InternalBuffer.Resource, nullptr, &uavDesc, UAVHandle.CPUHandle); - } -} - -void RawBuffer::Shutdown() -{ - for(uint64 i = 0; i < ArraySize_(SRVHandles); ++i) - DX12::SRVDescriptorHeap.Free(SRVHandles[i]); - DX12::SRVDescriptorHeap.Free(UAVHandle); - InternalBuffer.Shutdown(); - NumElements = 0; -} - -D3D12_CPU_DESCRIPTOR_HANDLE RawBuffer::SRV() const -{ - Assert_(InternalBuffer.ReadyForBinding()); - Assert_(SRVHandles[InternalBuffer.CurrBuffer].IsValid()); - return SRVHandles[InternalBuffer.CurrBuffer].CPUHandle; -} - -D3D12_CPU_DESCRIPTOR_HANDLE RawBuffer::UAV() const -{ - Assert_(UAVHandle.IsValid()); - return UAVHandle.CPUHandle; -} - -void* RawBuffer::Map() -{ - MapResult mapResult = InternalBuffer.Map(); - if(InternalBuffer.Lifetime == BufferLifetime::Temporary) - { - Assert_(SRVHandles[0].IsValid()); - Assert_(mapResult.ResourceOffset % Stride == 0); - - D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { }; - srvDesc.Format = DXGI_FORMAT_R32_TYPELESS; - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srvDesc.Buffer.FirstElement = uint32(mapResult.ResourceOffset / Stride); - srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; - srvDesc.Buffer.NumElements = uint32(NumElements); - DX12::Device->CreateShaderResourceView(mapResult.Resource, &srvDesc, SRVHandles[0].CPUHandle); - } - - GPUAddress = mapResult.GPUAddress; - return mapResult.CPUAddress; -} - -void RawBuffer::MapAndSetData(const void* data, uint64 numElements) -{ - Assert_(numElements <= NumElements); - void* cpuAddr = Map(); - memcpy(cpuAddr, data, numElements * Stride); -} - -void RawBuffer::UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset) -{ - InternalBuffer.UpdateData(srcData, srcNumElements * Stride, dstElemOffset * Stride); -} - -void RawBuffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const -{ - InternalBuffer.Transition(cmdList, before, after); -} - -void RawBuffer::MakeReadable(ID3D12GraphicsCommandList* cmdList) const -{ - InternalBuffer.MakeReadable(cmdList); -} - -void RawBuffer::MakeWritable(ID3D12GraphicsCommandList* cmdList) const -{ - InternalBuffer.MakeWritable(cmdList); -} - -void RawBuffer::UAVBarrier(ID3D12GraphicsCommandList* cmdList) const -{ - InternalBuffer.UAVBarrier(cmdList); -} - -// == ReadbackBuffer ============================================================================== - -ReadbackBuffer::ReadbackBuffer() -{ -} - -ReadbackBuffer::~ReadbackBuffer() -{ - Assert_(Resource == nullptr); -} - -void ReadbackBuffer::Initialize(uint64 size) -{ - Assert_(size > 0); - Size = size; - - D3D12_RESOURCE_DESC resourceDesc = {}; - resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - resourceDesc.Width = uint32(size); - resourceDesc.Height = 1; - resourceDesc.DepthOrArraySize = 1; - resourceDesc.MipLevels = 1; - resourceDesc.Format = DXGI_FORMAT_UNKNOWN; - resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE; - resourceDesc.SampleDesc.Count = 1; - resourceDesc.SampleDesc.Quality = 0; - resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - resourceDesc.Alignment = 0; - - DXCall(DX12::Device->CreateCommittedResource(DX12::GetReadbackHeapProps(), D3D12_HEAP_FLAG_NONE, &resourceDesc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&Resource))); -} - -void ReadbackBuffer::Shutdown() -{ - DX12::DeferredRelease(Resource); - Size = 0; -} - -void* ReadbackBuffer::Map() -{ - Assert_(Resource != nullptr); - void* data = nullptr; - Resource->Map(0, nullptr, &data); - return data; -} - -void ReadbackBuffer::Unmap() -{ - Assert_(Resource != nullptr); - Resource->Unmap(0, nullptr); -} - -// == Fence ======================================================================================= - -Fence::~Fence() -{ - Assert_(D3DFence == nullptr); - Shutdown(); -} - -void Fence::Init(uint64 initialValue) -{ - DXCall(DX12::Device->CreateFence(initialValue, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&D3DFence))); - FenceEvent = CreateEventEx(nullptr, FALSE, FALSE, EVENT_ALL_ACCESS); - Win32Call(FenceEvent != 0); -} - -void Fence::Shutdown() -{ - DX12::DeferredRelease(D3DFence); -} - -void Fence::Signal(ID3D12CommandQueue* queue, uint64 fenceValue) -{ - Assert_(D3DFence != nullptr); - DXCall(queue->Signal(D3DFence, fenceValue)); -} - -void Fence::Wait(uint64 fenceValue) -{ - Assert_(D3DFence != nullptr); - if(D3DFence->GetCompletedValue() < fenceValue) - { - DXCall(D3DFence->SetEventOnCompletion(fenceValue, FenceEvent)); - WaitForSingleObject(FenceEvent, INFINITE); - } -} - - -bool Fence::Signaled(uint64 fenceValue) -{ - Assert_(D3DFence != nullptr); - return D3DFence->GetCompletedValue() >= fenceValue; -} - -void Fence::Clear(uint64 fenceValue) -{ - Assert_(D3DFence != nullptr); - D3DFence->Signal(fenceValue); -} - -// == Texture ==================================================================================== - -Texture::Texture() -{ -} - -Texture::~Texture() -{ - Assert_(Resource == nullptr); -} - -void Texture::Shutdown() -{ - DX12::SRVDescriptorHeap.Free(SRV); - DX12::DeferredRelease(Resource); -} - -// == RenderTexture =============================================================================== - -RenderTexture::RenderTexture() -{ -} - -RenderTexture::~RenderTexture() -{ - Assert_(RTV.IsValid() == false); -} - -void RenderTexture::Initialize(uint64 width, uint64 height, DXGI_FORMAT format, uint64 msaaSamples, uint64 arraySize, bool32 createUAV, D3D12_RESOURCE_STATES initialState) -{ - Shutdown(); - - Assert_(width > 0); - Assert_(height > 0); - Assert_(msaaSamples > 0); - - D3D12_RESOURCE_DESC textureDesc = { }; - textureDesc.MipLevels = 1; - textureDesc.Format = format; - textureDesc.Width = uint32(width); - textureDesc.Height = uint32(height); - textureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - if(createUAV) - textureDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - textureDesc.DepthOrArraySize = uint16(arraySize); - textureDesc.SampleDesc.Count = uint32(msaaSamples); - textureDesc.SampleDesc.Quality = msaaSamples > 1 ? DX12::StandardMSAAPattern : 0; - textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - textureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; - textureDesc.Alignment = 0; - - D3D12_CLEAR_VALUE clearValue = { }; - clearValue.Format = format; - DXCall(DX12::Device->CreateCommittedResource(DX12::GetDefaultHeapProps(), D3D12_HEAP_FLAG_NONE, &textureDesc, - initialState, &clearValue, IID_PPV_ARGS(&Texture.Resource))); - - Texture.SRV = DX12::SRVDescriptorHeap.Allocate(); - DX12::Device->CreateShaderResourceView(Texture.Resource, nullptr, Texture.SRV.CPUHandle); - - Texture.Width = uint32(width); - Texture.Height = uint32(height); - Texture.Depth = 1; - Texture.NumMips = 1; - Texture.ArraySize = uint32(arraySize); - Texture.Format = format; - Texture.Cubemap = false; - MSAASamples = uint32(msaaSamples); - - RTV = DX12::RTVDescriptorHeap.Allocate(); - DX12::Device->CreateRenderTargetView(Texture.Resource, nullptr, RTV.CPUHandle); - - if(arraySize > 1) - { - ArrayRTVs.Init(arraySize); - - D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = { }; - rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; - rtvDesc.Format = format; - if(msaaSamples > 1) - rtvDesc.Texture2DMSArray.ArraySize = 1; - else - rtvDesc.Texture2DArray.ArraySize = 1; - - for(uint64 i = 0; i < arraySize; ++i) - { - if(msaaSamples > 1) - rtvDesc.Texture2DMSArray.FirstArraySlice = uint32(i); - else - rtvDesc.Texture2DArray.FirstArraySlice = uint32(i); - - ArrayRTVs[i] = DX12::RTVDescriptorHeap.Allocate(); - DX12::Device->CreateRenderTargetView(Texture.Resource, &rtvDesc, ArrayRTVs[i].CPUHandle); - } - } - - if(createUAV) - { - UAV = DX12::SRVDescriptorHeap.Allocate(); - DX12::Device->CreateUnorderedAccessView(Texture.Resource, nullptr, nullptr, UAV.CPUHandle); - } -} - -void RenderTexture::Shutdown() -{ - DX12::RTVDescriptorHeap.Free(RTV); - DX12::SRVDescriptorHeap.Free(UAV); - for(uint64 i = 0; i < ArrayRTVs.Size(); ++i) - DX12::RTVDescriptorHeap.Free(ArrayRTVs[i]); - ArrayRTVs.Shutdown(); - Texture.Shutdown(); -} - -void RenderTexture::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after, uint64 mipLevel, uint64 arraySlice) const -{ - uint32 subResourceIdx = mipLevel == uint64(-1) || arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES - : uint32(SubResourceIndex(mipLevel, arraySlice)); - Assert_(Texture.Resource != nullptr); - DX12::TransitionResource(cmdList, Texture.Resource, before, after, subResourceIdx); -} - -void RenderTexture::MakeReadable(ID3D12GraphicsCommandList* cmdList, uint64 mipLevel, uint64 arraySlice) const -{ - uint32 subResourceIdx = mipLevel == uint64(-1) || arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES - : uint32(SubResourceIndex(mipLevel, arraySlice)); - Assert_(Texture.Resource != nullptr); - DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, subResourceIdx); -} - -void RenderTexture::MakeWritable(ID3D12GraphicsCommandList* cmdList, uint64 mipLevel, uint64 arraySlice) const -{ - uint32 subResourceIdx = mipLevel == uint64(-1) || arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES - : uint32(SubResourceIndex(mipLevel, arraySlice)); - Assert_(Texture.Resource != nullptr); - DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET, subResourceIdx); -} - -// == DepthBuffer =============================================================================== - -DepthBuffer::DepthBuffer() -{ -} - -DepthBuffer::~DepthBuffer() -{ - Assert_(DSVFormat == DXGI_FORMAT_UNKNOWN); - Shutdown(); -} - -void DepthBuffer::Initialize(uint64 width, uint64 height, DXGI_FORMAT format, uint64 msaaSamples, uint64 arraySize, D3D12_RESOURCE_STATES initialState) -{ - Shutdown(); - - Assert_(width > 0); - Assert_(height > 0); - Assert_(msaaSamples > 0); - - DXGI_FORMAT texFormat = format; - DXGI_FORMAT srvFormat = format; - if(format == DXGI_FORMAT_D16_UNORM) - { - texFormat = DXGI_FORMAT_R16_TYPELESS; - srvFormat = DXGI_FORMAT_R16_UNORM; - } - else if(format == DXGI_FORMAT_D24_UNORM_S8_UINT) - { - texFormat = DXGI_FORMAT_R24G8_TYPELESS; - srvFormat = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; - } - else if(format == DXGI_FORMAT_D32_FLOAT) - { - texFormat = DXGI_FORMAT_R32_TYPELESS; - srvFormat = DXGI_FORMAT_R32_FLOAT; - } - else if(format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT) - { - texFormat = DXGI_FORMAT_R32G8X24_TYPELESS; - srvFormat = DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; - } - else - { - AssertFail_("Invalid depth buffer format!"); - } - - D3D12_RESOURCE_DESC textureDesc = { }; - textureDesc.MipLevels = 1; - textureDesc.Format = texFormat; - textureDesc.Width = uint32(width); - textureDesc.Height = uint32(height); - textureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; - textureDesc.DepthOrArraySize = uint16(arraySize); - textureDesc.SampleDesc.Count = uint32(msaaSamples); - textureDesc.SampleDesc.Quality = msaaSamples > 1 ? DX12::StandardMSAAPattern : 0; - textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - textureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; - textureDesc.Alignment = 0; - - D3D12_CLEAR_VALUE clearValue = { }; - clearValue.DepthStencil.Depth = 1.0f; - clearValue.DepthStencil.Stencil = 0; - clearValue.Format = format; - - DXCall(DX12::Device->CreateCommittedResource(DX12::GetDefaultHeapProps(), D3D12_HEAP_FLAG_NONE, &textureDesc, - initialState, &clearValue, IID_PPV_ARGS(&Texture.Resource))); - - Texture.SRV = DX12::SRVDescriptorHeap.Allocate(); - - D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { }; - srvDesc.Format = srvFormat; - srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - if(msaaSamples == 1 && arraySize == 1) - { - srvDesc.Texture2D.MipLevels = 1; - srvDesc.Texture2D.MostDetailedMip = 0; - srvDesc.Texture2D.PlaneSlice = 0; - srvDesc.Texture2D.ResourceMinLODClamp = 0.0f; - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - } - else if(msaaSamples == 1 && arraySize > 1) - { - srvDesc.Texture2DArray.ArraySize = uint32(arraySize); - srvDesc.Texture2DArray.FirstArraySlice = 0; - srvDesc.Texture2DArray.MipLevels = 1; - srvDesc.Texture2DArray.MostDetailedMip = 0; - srvDesc.Texture2DArray.PlaneSlice = 0; - srvDesc.Texture2DArray.ResourceMinLODClamp = 0.0f; - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; - } - else if(msaaSamples > 1 && arraySize == 1) - { - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS; - } - else if(msaaSamples > 1 && arraySize > 1) - { - srvDesc.Texture2DMSArray.FirstArraySlice = 0; - srvDesc.Texture2DMSArray.ArraySize = uint32(arraySize); - srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; - } - DX12::Device->CreateShaderResourceView(Texture.Resource, &srvDesc, Texture.SRV.CPUHandle); - - Texture.Width = uint32(width); - Texture.Height = uint32(height); - Texture.Depth = 1; - Texture.NumMips = 1; - Texture.ArraySize = uint32(arraySize); - Texture.Format = srvFormat; - Texture.Cubemap = false; - MSAASamples = uint32(msaaSamples); - - DSV = DX12::DSVDescriptorHeap.Allocate(); - - D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = { }; - dsvDesc.Flags = D3D12_DSV_FLAG_NONE; - dsvDesc.Format = format; - - if(msaaSamples == 1 && arraySize == 1) - { - dsvDesc.Texture2D.MipSlice = 0; - dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; - } - else if(msaaSamples == 1 && arraySize > 1) - { - dsvDesc.Texture2DArray.ArraySize = uint32(arraySize); - dsvDesc.Texture2DArray.FirstArraySlice = 0; - dsvDesc.Texture2DArray.MipSlice = 0; - dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY; - } - else if(msaaSamples > 1 && arraySize == 1) - { - dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMS; - } - else if(msaaSamples > 1 && arraySize > 1) - { - dsvDesc.Texture2DMSArray.ArraySize = uint32(arraySize); - dsvDesc.Texture2DMSArray.FirstArraySlice = 0; - dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY; - } - - DX12::Device->CreateDepthStencilView(Texture.Resource, &dsvDesc, DSV.CPUHandle); - - bool hasStencil = format == DXGI_FORMAT_D24_UNORM_S8_UINT || format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT; - - ReadOnlyDSV = DX12::DSVDescriptorHeap.Allocate(); - dsvDesc.Flags = D3D12_DSV_FLAG_READ_ONLY_DEPTH; - if(hasStencil) - dsvDesc.Flags |= D3D12_DSV_FLAG_READ_ONLY_STENCIL; - DX12::Device->CreateDepthStencilView(Texture.Resource, &dsvDesc, ReadOnlyDSV.CPUHandle); - - if(arraySize > 1) - { - ArrayDSVs.Init(arraySize); - - dsvDesc.Flags = D3D12_DSV_FLAG_NONE; - if(msaaSamples > 1) - dsvDesc.Texture2DMSArray.ArraySize = 1; - else - dsvDesc.Texture2DArray.ArraySize = 1; - - for(uint64 i = 0; i < arraySize; ++i) - { - if(msaaSamples > 1) - dsvDesc.Texture2DMSArray.FirstArraySlice = uint32(i); - else - dsvDesc.Texture2DArray.FirstArraySlice = uint32(i); - - ArrayDSVs[i] = DX12::DSVDescriptorHeap.Allocate(); - DX12::Device->CreateDepthStencilView(Texture.Resource, &dsvDesc, ArrayDSVs[i].CPUHandle); - } - } - - DSVFormat = format; -} - -void DepthBuffer::Shutdown() -{ - DX12::DSVDescriptorHeap.Free(DSV); - DX12::DSVDescriptorHeap.Free(ReadOnlyDSV); - for(uint64 i = 0; i < ArrayDSVs.Size(); ++i) - DX12::DSVDescriptorHeap.Free(ArrayDSVs[i]); - ArrayDSVs.Shutdown(); - Texture.Shutdown(); - DSVFormat = DXGI_FORMAT_UNKNOWN; -} - -void DepthBuffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after, uint64 arraySlice) const -{ - uint32 subResourceIdx = arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES : uint32(arraySlice); - Assert_(Texture.Resource != nullptr); - DX12::TransitionResource(cmdList, Texture.Resource, before, after, subResourceIdx); -} - -void DepthBuffer::MakeReadable(ID3D12GraphicsCommandList* cmdList, uint64 arraySlice) const -{ - uint32 subResourceIdx = arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES : uint32(arraySlice); - Assert_(Texture.Resource != nullptr); - DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_DEPTH_WRITE, - D3D12_RESOURCE_STATE_DEPTH_READ | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, subResourceIdx); -} - -void DepthBuffer::MakeWritable(ID3D12GraphicsCommandList* cmdList, uint64 arraySlice) const -{ - uint32 subResourceIdx = arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES : uint32(arraySlice); - Assert_(Texture.Resource != nullptr); - DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_DEPTH_READ | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, - D3D12_RESOURCE_STATE_DEPTH_WRITE, subResourceIdx); -} - -} \ No newline at end of file diff --git a/SampleFramework12/v1.00/Graphics/ShadowHelper.cpp b/SampleFramework12/v1.00/Graphics/ShadowHelper.cpp deleted file mode 100644 index cc7b0b0..0000000 --- a/SampleFramework12/v1.00/Graphics/ShadowHelper.cpp +++ /dev/null @@ -1,216 +0,0 @@ -//================================================================================================= -// -// MJP's DX12 Sample Framework -// http://mynameismjp.wordpress.com/ -// -// All code licensed under the MIT license -// -//================================================================================================= - -#pragma once - -#include "PCH.h" -#include "ShadowHelper.h" -#include "Camera.h" - -namespace SampleFramework12 -{ - -// Transforms from [-1,1] post-projection space to [0,1] UV space -Float4x4 ShadowScaleOffsetMatrix = Float4x4(Float4(0.5f, 0.0f, 0.0f, 0.0f), - Float4(0.0f, -0.5f, 0.0f, 0.0f), - Float4(0.0f, 0.0f, 1.0f, 0.0f), - Float4(0.5f, 0.5f, 0.0f, 1.0f)); - -void PrepareShadowCascades(const Float3& lightDir, uint64 shadowMapSize, bool stabilize, const Camera& camera, - SunShadowConstants& constants, OrthographicCamera* cascadeCameras) -{ - const float MinDistance = 0.0f; - const float MaxDistance = 1.0f; - - // Compute the split distances based on the partitioning mode - float cascadeSplits[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; - - { - float lambda = 0.5f; - - float nearClip = camera.NearClip(); - float farClip = camera.FarClip(); - float clipRange = farClip - nearClip; - - float minZ = nearClip + MinDistance * clipRange; - float maxZ = nearClip + MaxDistance * clipRange; - - float range = maxZ - minZ; - float ratio = maxZ / minZ; - - for(uint32 i = 0; i < NumCascades; ++i) - { - float p = (i + 1) / static_cast(NumCascades); - float log = minZ * std::pow(ratio, p); - float uniform = minZ + range * p; - float d = lambda * (log - uniform) + uniform; - cascadeSplits[i] = (d - nearClip) / clipRange; - } - } - - Float3 c0Extents; - Float4x4 c0Matrix; - - // Prepare the projections ofr each cascade - for(uint64 cascadeIdx = 0; cascadeIdx < NumCascades; ++cascadeIdx) - { - // Get the 8 points of the view frustum in world space - Float3 frustumCornersWS[8] = - { - Float3(-1.0f, 1.0f, 0.0f), - Float3( 1.0f, 1.0f, 0.0f), - Float3( 1.0f, -1.0f, 0.0f), - Float3(-1.0f, -1.0f, 0.0f), - Float3(-1.0f, 1.0f, 1.0f), - Float3( 1.0f, 1.0f, 1.0f), - Float3( 1.0f, -1.0f, 1.0f), - Float3(-1.0f, -1.0f, 1.0f), - }; - - float prevSplitDist = cascadeIdx == 0 ? MinDistance : cascadeSplits[cascadeIdx - 1]; - float splitDist = cascadeSplits[cascadeIdx]; - - Float4x4 invViewProj = Float4x4::Invert(camera.ViewProjectionMatrix()); - for(uint64 i = 0; i < 8; ++i) - frustumCornersWS[i] = Float3::Transform(frustumCornersWS[i], invViewProj); - - // Get the corners of the current cascade slice of the view frustum - for(uint64 i = 0; i < 4; ++i) - { - Float3 cornerRay = frustumCornersWS[i + 4] - frustumCornersWS[i]; - Float3 nearCornerRay = cornerRay * prevSplitDist; - Float3 farCornerRay = cornerRay * splitDist; - frustumCornersWS[i + 4] = frustumCornersWS[i] + farCornerRay; - frustumCornersWS[i] = frustumCornersWS[i] + nearCornerRay; - } - - // Calculate the centroid of the view frustum slice - Float3 frustumCenter = Float3(0.0f); - for(uint64 i = 0; i < 8; ++i) - frustumCenter += frustumCornersWS[i]; - frustumCenter *= (1.0f / 8.0f); - - // Pick the up vector to use for the light camera - Float3 upDir = camera.Right(); - - Float3 minExtents; - Float3 maxExtents; - - if(stabilize) - { - // This needs to be constant for it to be stable - upDir = Float3(0.0f, 1.0f, 0.0f); - - // Calculate the radius of a bounding sphere surrounding the frustum corners - float sphereRadius = 0.0f; - for(uint64 i = 0; i < 8; ++i) - { - float dist = Float3::Length(Float3(frustumCornersWS[i]) - frustumCenter); - sphereRadius = Max(sphereRadius, dist); - } - - sphereRadius = std::ceil(sphereRadius * 16.0f) / 16.0f; - - maxExtents = Float3(sphereRadius, sphereRadius, sphereRadius); - minExtents = -maxExtents; - } - else - { - // Create a temporary view matrix for the light - Float3 lightCameraPos = frustumCenter; - Float3 lookAt = frustumCenter - lightDir; - DirectX::XMMATRIX lightView = DirectX::XMMatrixLookAtLH(lightCameraPos.ToSIMD(), lookAt.ToSIMD(), upDir.ToSIMD()); - - // Calculate an AABB around the frustum corners - DirectX::XMVECTOR mins = DirectX::XMVectorSet(FloatMax, FloatMax, FloatMax, FloatMax); - DirectX::XMVECTOR maxes = DirectX::XMVectorSet(-FloatMax, -FloatMax, -FloatMax, -FloatMax); - for(uint32 i = 0; i < 8; ++i) - { - DirectX::XMVECTOR corner = DirectX::XMVector3TransformCoord(frustumCornersWS[i].ToSIMD(), lightView); - mins = DirectX::XMVectorMin(mins, corner); - maxes = DirectX::XMVectorMax(maxes, corner); - } - - minExtents = Float3(mins); - maxExtents = Float3(maxes); - } - - // Adjust the min/max to accommodate the filtering size - float scale = (shadowMapSize + 7.0f) / shadowMapSize; - minExtents.x *= scale; - minExtents.y *= scale; - maxExtents.x *= scale; - maxExtents.x *= scale; - - Float3 cascadeExtents = maxExtents - minExtents; - - // Get position of the shadow camera - Float3 shadowCameraPos = frustumCenter + lightDir * -minExtents.z; - - // Come up with a new orthographic camera for the shadow caster - OrthographicCamera& shadowCamera = cascadeCameras[cascadeIdx]; - shadowCamera.Initialize(minExtents.x, minExtents.y, maxExtents.x, maxExtents.y, 0.0f, cascadeExtents.z); - shadowCamera.SetLookAt(shadowCameraPos, frustumCenter, upDir); - - if(stabilize) - { - // Create the rounding matrix, by projecting the world-space origin and determining - // the fractional offset in texel space - DirectX::XMMATRIX shadowMatrix = shadowCamera.ViewProjectionMatrix().ToSIMD(); - DirectX::XMVECTOR shadowOrigin = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f); - shadowOrigin = DirectX::XMVector4Transform(shadowOrigin, shadowMatrix); - shadowOrigin = DirectX::XMVectorScale(shadowOrigin, shadowMapSize / 2.0f); - - DirectX::XMVECTOR roundedOrigin = DirectX::XMVectorRound(shadowOrigin); - DirectX::XMVECTOR roundOffset = DirectX::XMVectorSubtract(roundedOrigin, shadowOrigin); - roundOffset = DirectX::XMVectorScale(roundOffset, 2.0f / shadowMapSize); - roundOffset = DirectX::XMVectorSetZ(roundOffset, 0.0f); - roundOffset = DirectX::XMVectorSetW(roundOffset, 0.0f); - - DirectX::XMMATRIX shadowProj = shadowCamera.ProjectionMatrix().ToSIMD(); - shadowProj.r[3] = DirectX::XMVectorAdd(shadowProj.r[3], roundOffset); - shadowCamera.SetProjection(Float4x4(shadowProj)); - } - - Float4x4 shadowMatrix = shadowCamera.ViewProjectionMatrix(); - shadowMatrix = shadowMatrix * ShadowScaleOffsetMatrix; - - // Store the split distance in terms of view space depth - const float clipDist = camera.FarClip() - camera.NearClip(); - constants.CascadeSplits[cascadeIdx] = camera.NearClip() + splitDist * clipDist; - - if(cascadeIdx == 0) - { - c0Extents = cascadeExtents; - c0Matrix = shadowMatrix; - constants.ShadowMatrix = shadowMatrix; - constants.CascadeOffsets[0] = Float4(0.0f, 0.0f, 0.0f, 0.0f); - constants.CascadeScales[0] = Float4(1.0f, 1.0f, 1.0f, 1.0f); - } - else - { - // Calculate the position of the lower corner of the cascade partition, in the UV space - // of the first cascade partition - Float4x4 invCascadeMat = Float4x4::Invert(shadowMatrix); - Float3 cascadeCorner = Float3::Transform(Float3(0.0f, 0.0f, 0.0f), invCascadeMat); - cascadeCorner = Float3::Transform(cascadeCorner, c0Matrix); - - // Do the same for the upper corner - Float3 otherCorner = Float3::Transform(Float3(1.0f, 1.0f, 1.0f), invCascadeMat); - otherCorner = Float3::Transform(otherCorner, c0Matrix); - - // Calculate the scale and offset - Float3 cascadeScale = Float3(1.0f, 1.0f, 1.f) / (otherCorner - cascadeCorner); - constants.CascadeOffsets[cascadeIdx] = Float4(-cascadeCorner, 0.0f); - constants.CascadeScales[cascadeIdx] = Float4(cascadeScale, 1.0f); - } - } -} - -} diff --git a/SampleFramework12/v1.00/Graphics/ShadowHelper.h b/SampleFramework12/v1.00/Graphics/ShadowHelper.h deleted file mode 100644 index 6966aef..0000000 --- a/SampleFramework12/v1.00/Graphics/ShadowHelper.h +++ /dev/null @@ -1,37 +0,0 @@ -//================================================================================================= -// -// MJP's DX12 Sample Framework -// http://mynameismjp.wordpress.com/ -// -// All code licensed under the MIT license -// -//================================================================================================= - -#pragma once - -#include -#include "..\\SF12_Math.h" - -namespace SampleFramework12 -{ - -class Camera; -class OrthographicCamera; -class PerspectiveCamera; -struct ModelSpotLight; - -const uint64 NumCascades = 4; - -struct SunShadowConstants -{ - Float4x4 ShadowMatrix; - float CascadeSplits[NumCascades]; - Float4 CascadeOffsets[NumCascades]; - Float4 CascadeScales[NumCascades]; -}; - -extern Float4x4 ShadowScaleOffsetMatrix; -void PrepareShadowCascades(const Float3& lightDir, uint64 shadowMapSize, bool stabilize, const Camera& camera, - SunShadowConstants& constants, OrthographicCamera* cascadeCameras); - -} diff --git a/SampleFramework12/v1.00/Shaders/D3DX_DXGIFormatConvert.inl b/SampleFramework12/v1.00/Shaders/D3DX_DXGIFormatConvert.inl deleted file mode 100644 index 1cfba72..0000000 --- a/SampleFramework12/v1.00/Shaders/D3DX_DXGIFormatConvert.inl +++ /dev/null @@ -1,800 +0,0 @@ -//============================================================================= -// D3D11 HLSL Routines for Manual Pack/Unpack of 32-bit DXGI_FORMAT_* -//============================================================================= -// -// This file contains format conversion routines for use in the -// Compute Shader or Pixel Shader on D3D11 Hardware. -// -// Skip to the end of this comment to see a summary of the routines -// provided. The rest of the text below explains why they are needed -// and how to use them. -// -// The scenario where these can be useful is if your application -// needs to simultaneously both read and write texture - i.e. in-place -// image editing. -// -// D3D11's Unordered Access View (UAV) of a Texture1D/2D/3D resource -// allows random access reads and writes to memory from a Compute Shader -// or Pixel Shader. However, the only texture format that supports this -// is DXGI_FORMAT_R32_UINT. e.g. Other more interesting formats like -// DXGI_FORMAT_R8G8B8A8_UNORM do not support simultaneous read and -// write. You can use such formats for random access writing only -// using a UAV, or reading only using a Shader Resource View (SRV). -// But for simultaneous read+write, the format conversion hardware is -// not available. -// -// There is a workaround to this limitation, involving casting the texture -// to R32_UINT when creating a UAV, as long as the original format of the -// resource supports it (most 32 bit per element formats). This allows -// simultaneous read+write as long as the shader does manual format -// unpacking on read and packing on write. -// -// The benefit is that later on, other views such as RenderTarget Views -// or ShaderResource Views on the same texture can be used with the -// proper format (e.g. DXGI_FORMAT_R16G16_FLOAT) so the hardware can -// do the usual automatic format unpack/pack and do texture filtering etc. -// where there are no hardware limitations. -// -// The sequence of actions for an application is the following: -// -// Suppose you want to make a texture than you can use a Pixel Shader -// or Compute Shader to perform in-place editing, and that the format -// you want the data to be stored in happens to be a descendent -// of of one of these formats: -// -// DXGI_FORMAT_R10G10B10A2_TYPELESS -// DXGI_FORMAT_R8G8B8A8_TYPELESS -// DXGI_FORMAT_B8G8R8A8_TYPELESS -// DXGI_FORMAT_B8G8R8X8_TYPELESS -// DXGI_FORMAT_R16G16_TYPELESS -// -// e.g. DXGI_FORMAT_R10G10B10A2_UNORM is a descendent of -// DXGI_FORMAT_R10G10B10A2_TYPELESS, so it supports the -// usage pattern described here. -// -// (Formats descending from DXGI_FORMAT_R32_TYPELESS, such as -// DXGI_FORMAT_R32_FLOAT, are trivially supported without -// needing any of the format conversion help provided here.) -// -// Steps: -// -// (1) Create a texture with the appropriate _TYPELESS format above -// along with the needed bind flags, such as -// D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE. -// -// (2) For in-place image editing, create a UAV with the format -// DXGI_FORMAT_R32_UINT. D3D normally doesn't allow casting -// between different format "families", but the API makes -// an exception here. -// -// (3) In the Compute Shader or Pixel Shader, use the appropriate -// format pack/unpack routines provided in this file. -// For example if the DXGI_FORMAT_R32_UINT UAV really holds -// DXGI_FORMAT_R10G10B10A2_UNORM data, then, after reading a -// uint from the UAV into the shader, unpack by calling: -// -// XMFLOAT4 D3DX_R10G10B10A2_UNORM_to_FLOAT4(UINT packedInput) -// -// Then to write to the UAV in the same shader, call the following -// to pack shader data into a uint that can be written out: -// -// UINT D3DX_FLOAT4_to_R10G10B10A2_UNORM(hlsl_precise XMFLOAT4 unpackedInput) -// -// (4) Other views, such as SRVs, can be created with the desired format; -// e.g. DXGI_FORMAT_R10G10B10A2_UNORM if the resource was created as -// DXGI_FORMAT_R10G10B10A2_TYPELESS. When that view is accessed by a -// shader, the hardware can do automatic type conversion as usual. -// -// Note, again, that if the shader only needs to write to a UAV, or read -// as an SRV, then none of this is needed - fully typed UAV or SRVs can -// be used. Only if simultaneous reading and writing to a UAV of a texture -// is needed are the format conversion routines provided here potentially -// useful. -// -// The following is the list of format conversion routines included in this -// file, categorized by the DXGI_FORMAT they unpack/pack. Each of the -// formats supported descends from one of the TYPELESS formats listed -// above, and supports casting to DXGI_FORMAT_R32_UINT as a UAV. -// -// DXGI_FORMAT_R10G10B10A2_UNORM: -// -// XMFLOAT4 D3DX_R10G10B10A2_UNORM_to_FLOAT4(UINT packedInput) -// UINT D3DX_FLOAT4_to_R10G10B10A2_UNORM(hlsl_precise XMFLOAT4 unpackedInput) -// -// DXGI_FORMAT_R10G10B10A2_UINT: -// -// XMUINT4 D3DX_R10G10B10A2_UINT_to_UINT4(UINT packedInput) -// UINT D3DX_UINT4_to_R10G10B10A2_UINT(XMUINT4 unpackedInput) -// -// DXGI_FORMAT_R8G8B8A8_UNORM: -// -// XMFLOAT4 D3DX_R8G8B8A8_UNORM_to_FLOAT4(UINT packedInput) -// UINT D3DX_FLOAT4_to_R8G8B8A8_UNORM(hlsl_precise XMFLOAT4 unpackedInput) -// -// DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: -// -// XMFLOAT4 D3DX_R8G8B8A8_UNORM_SRGB_to_FLOAT4_inexact(UINT packedInput) * -// XMFLOAT4 D3DX_R8G8B8A8_UNORM_SRGB_to_FLOAT4(UINT packedInput) -// UINT D3DX_FLOAT4_to_R8G8B8A8_UNORM_SRGB(hlsl_precise XMFLOAT4 unpackedInput) -// -// * The "_inexact" function above uses shader instructions that don't -// have high enough precision to give the exact answer, albeit close. -// The alternative function uses a lookup table stored in the shader -// to give an exact SRGB->float conversion. -// -// DXGI_FORMAT_R8G8B8A8_UINT: -// -// XMUINT4 D3DX_R8G8B8A8_UINT_to_UINT4(UINT packedInput) -// XMUINT D3DX_UINT4_to_R8G8B8A8_UINT(XMUINT4 unpackedInput) -// -// DXGI_FORMAT_R8G8B8A8_SNORM: -// -// XMFLOAT4 D3DX_R8G8B8A8_SNORM_to_FLOAT4(UINT packedInput) -// UINT D3DX_FLOAT4_to_R8G8B8A8_SNORM(hlsl_precise XMFLOAT4 unpackedInput) -// -// DXGI_FORMAT_R8G8B8A8_SINT: -// -// XMINT4 D3DX_R8G8B8A8_SINT_to_INT4(UINT packedInput) -// UINT D3DX_INT4_to_R8G8B8A8_SINT(XMINT4 unpackedInput) -// -// DXGI_FORMAT_B8G8R8A8_UNORM: -// -// XMFLOAT4 D3DX_B8G8R8A8_UNORM_to_FLOAT4(UINT packedInput) -// UINT D3DX_FLOAT4_to_B8G8R8A8_UNORM(hlsl_precise XMFLOAT4 unpackedInput) -// -// DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: -// -// XMFLOAT4 D3DX_B8G8R8A8_UNORM_SRGB_to_FLOAT4_inexact(UINT packedInput) * -// XMFLOAT4 D3DX_B8G8R8A8_UNORM_SRGB_to_FLOAT4(UINT packedInput) -// UINT D3DX_FLOAT4_to_R8G8B8A8_UNORM_SRGB(hlsl_precise XMFLOAT4 unpackedInput) -// -// * The "_inexact" function above uses shader instructions that don't -// have high enough precision to give the exact answer, albeit close. -// The alternative function uses a lookup table stored in the shader -// to give an exact SRGB->float conversion. -// -// DXGI_FORMAT_B8G8R8X8_UNORM: -// -// XMFLOAT3 D3DX_B8G8R8X8_UNORM_to_FLOAT3(UINT packedInput) -// UINT D3DX_FLOAT3_to_B8G8R8X8_UNORM(hlsl_precise XMFLOAT3 unpackedInput) -// -// DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: -// -// XMFLOAT3 D3DX_B8G8R8X8_UNORM_SRGB_to_FLOAT3_inexact(UINT packedInput) * -// XMFLOAT3 D3DX_B8G8R8X8_UNORM_SRGB_to_FLOAT3(UINT packedInput) -// UINT D3DX_FLOAT3_to_B8G8R8X8_UNORM_SRGB(hlsl_precise XMFLOAT3 unpackedInput) -// -// * The "_inexact" function above uses shader instructions that don't -// have high enough precision to give the exact answer, albeit close. -// The alternative function uses a lookup table stored in the shader -// to give an exact SRGB->float conversion. -// -// DXGI_FORMAT_R16G16_FLOAT: -// -// XMFLOAT2 D3DX_R16G16_FLOAT_to_FLOAT2(UINT packedInput) -// UINT D3DX_FLOAT2_to_R16G16_FLOAT(hlsl_precise XMFLOAT2 unpackedInput) -// -// DXGI_FORMAT_R16G16_UNORM: -// -// XMFLOAT2 D3DX_R16G16_UNORM_to_FLOAT2(UINT packedInput) -// UINT D3DX_FLOAT2_to_R16G16_UNORM(hlsl_precise FLOAT2 unpackedInput) -// -// DXGI_FORMAT_R16G16_UINT: -// -// XMUINT2 D3DX_R16G16_UINT_to_UINT2(UINT packedInput) -// UINT D3DX_UINT2_to_R16G16_UINT(XMUINT2 unpackedInput) -// -// DXGI_FORMAT_R16G16_SNORM: -// -// XMFLOAT2 D3DX_R16G16_SNORM_to_FLOAT2(UINT packedInput) -// UINT D3DX_FLOAT2_to_R16G16_SNORM(hlsl_precise XMFLOAT2 unpackedInput) -// -// DXGI_FORMAT_R16G16_SINT: -// -// XMINT2 D3DX_R16G16_SINT_to_INT2(UINT packedInput) -// UINT D3DX_INT2_to_R16G16_SINT(XMINT2 unpackedInput) -// -//============================================================================= - -#ifndef __D3DX_DXGI_FORMAT_CONVERT_INL___ -#define __D3DX_DXGI_FORMAT_CONVERT_INL___ - -#if HLSL_VERSION > 0 - -#define D3DX11INLINE - -typedef int INT; -typedef uint UINT; - -typedef float2 XMFLOAT2; -typedef float3 XMFLOAT3; -typedef float4 XMFLOAT4; -typedef int2 XMINT2; -typedef int4 XMINT4; -typedef uint2 XMUINT2; -typedef uint4 XMUINT4; - -#define hlsl_precise precise - -#define D3DX_Saturate_FLOAT(_V) saturate(_V) -#define D3DX_IsNan(_V) isnan(_V) -#define D3DX_Truncate_FLOAT(_V) trunc(_V) - -#else // HLSL_VERSION > 0 - -#ifndef __cplusplus -#error C++ compilation required -#endif - -#include -#include - -#define hlsl_precise - -D3DX11INLINE FLOAT D3DX_Saturate_FLOAT(FLOAT _V) -{ - return min(max(_V, 0), 1); -} -D3DX11INLINE bool D3DX_IsNan(FLOAT _V) -{ - return _V != _V; -} -D3DX11INLINE FLOAT D3DX_Truncate_FLOAT(FLOAT _V) -{ - return _V >= 0 ? floor(_V) : ceil(_V); -} - -// 2D Vector; 32 bit signed integer components -typedef struct _XMINT2 -{ - INT x; - INT y; -} XMINT2; - -// 2D Vector; 32 bit unsigned integer components -typedef struct _XMUINT2 -{ - UINT x; - UINT y; -} XMUINT2; - -// 4D Vector; 32 bit signed integer components -typedef struct _XMINT4 -{ - INT x; - INT y; - INT z; - INT w; -} XMINT4; - -// 4D Vector; 32 bit unsigned integer components -typedef struct _XMUINT4 -{ - UINT x; - UINT y; - UINT z; - UINT w; -} XMUINT4; - -#endif // HLSL_VERSION > 0 - -//============================================================================= -// SRGB Helper Functions Called By Conversions Further Below. -//============================================================================= -// SRGB_to_FLOAT_inexact is imprecise due to precision of pow implementations. -// If exact SRGB->float conversion is needed, a table lookup is provided -// further below. -D3DX11INLINE FLOAT D3DX_SRGB_to_FLOAT_inexact(hlsl_precise FLOAT val) -{ - if( val < 0.04045f ) - val /= 12.92f; - else - val = pow((val + 0.055f)/1.055f,2.4f); - return val; -} - -static const UINT D3DX_SRGBTable[] = -{ - 0x00000000,0x399f22b4,0x3a1f22b4,0x3a6eb40e,0x3a9f22b4,0x3ac6eb61,0x3aeeb40e,0x3b0b3e5d, - 0x3b1f22b4,0x3b33070b,0x3b46eb61,0x3b5b518d,0x3b70f18d,0x3b83e1c6,0x3b8fe616,0x3b9c87fd, - 0x3ba9c9b7,0x3bb7ad6f,0x3bc63549,0x3bd56361,0x3be539c1,0x3bf5ba70,0x3c0373b5,0x3c0c6152, - 0x3c15a703,0x3c1f45be,0x3c293e6b,0x3c3391f7,0x3c3e4149,0x3c494d43,0x3c54b6c7,0x3c607eb1, - 0x3c6ca5df,0x3c792d22,0x3c830aa8,0x3c89af9f,0x3c9085db,0x3c978dc5,0x3c9ec7c2,0x3ca63433, - 0x3cadd37d,0x3cb5a601,0x3cbdac20,0x3cc5e639,0x3cce54ab,0x3cd6f7d5,0x3cdfd010,0x3ce8ddb9, - 0x3cf2212c,0x3cfb9ac1,0x3d02a569,0x3d0798dc,0x3d0ca7e6,0x3d11d2af,0x3d171963,0x3d1c7c2e, - 0x3d21fb3c,0x3d2796b2,0x3d2d4ebb,0x3d332380,0x3d39152b,0x3d3f23e3,0x3d454fd1,0x3d4b991c, - 0x3d51ffef,0x3d58846a,0x3d5f26b7,0x3d65e6fe,0x3d6cc564,0x3d73c20f,0x3d7add29,0x3d810b67, - 0x3d84b795,0x3d887330,0x3d8c3e4a,0x3d9018f6,0x3d940345,0x3d97fd4a,0x3d9c0716,0x3da020bb, - 0x3da44a4b,0x3da883d7,0x3daccd70,0x3db12728,0x3db59112,0x3dba0b3b,0x3dbe95b5,0x3dc33092, - 0x3dc7dbe2,0x3dcc97b6,0x3dd1641f,0x3dd6412c,0x3ddb2eef,0x3de02d77,0x3de53cd5,0x3dea5d19, - 0x3def8e52,0x3df4d091,0x3dfa23e8,0x3dff8861,0x3e027f07,0x3e054280,0x3e080ea3,0x3e0ae378, - 0x3e0dc105,0x3e10a754,0x3e13966b,0x3e168e52,0x3e198f10,0x3e1c98ad,0x3e1fab30,0x3e22c6a3, - 0x3e25eb09,0x3e29186c,0x3e2c4ed0,0x3e2f8e41,0x3e32d6c4,0x3e362861,0x3e39831e,0x3e3ce703, - 0x3e405416,0x3e43ca5f,0x3e4749e4,0x3e4ad2ae,0x3e4e64c2,0x3e520027,0x3e55a4e6,0x3e595303, - 0x3e5d0a8b,0x3e60cb7c,0x3e6495e0,0x3e6869bf,0x3e6c4720,0x3e702e0c,0x3e741e84,0x3e781890, - 0x3e7c1c38,0x3e8014c2,0x3e82203c,0x3e84308d,0x3e8645ba,0x3e885fc5,0x3e8a7eb2,0x3e8ca283, - 0x3e8ecb3d,0x3e90f8e1,0x3e932b74,0x3e9562f8,0x3e979f71,0x3e99e0e2,0x3e9c274e,0x3e9e72b7, - 0x3ea0c322,0x3ea31892,0x3ea57308,0x3ea7d289,0x3eaa3718,0x3eaca0b7,0x3eaf0f69,0x3eb18333, - 0x3eb3fc18,0x3eb67a18,0x3eb8fd37,0x3ebb8579,0x3ebe12e1,0x3ec0a571,0x3ec33d2d,0x3ec5da17, - 0x3ec87c33,0x3ecb2383,0x3ecdd00b,0x3ed081cd,0x3ed338cc,0x3ed5f50b,0x3ed8b68d,0x3edb7d54, - 0x3ede4965,0x3ee11ac1,0x3ee3f16b,0x3ee6cd67,0x3ee9aeb6,0x3eec955d,0x3eef815d,0x3ef272ba, - 0x3ef56976,0x3ef86594,0x3efb6717,0x3efe6e02,0x3f00bd2d,0x3f02460e,0x3f03d1a7,0x3f055ff9, - 0x3f06f106,0x3f0884cf,0x3f0a1b56,0x3f0bb49b,0x3f0d50a0,0x3f0eef67,0x3f1090f1,0x3f12353e, - 0x3f13dc51,0x3f15862b,0x3f1732cd,0x3f18e239,0x3f1a946f,0x3f1c4971,0x3f1e0141,0x3f1fbbdf, - 0x3f21794e,0x3f23398e,0x3f24fca0,0x3f26c286,0x3f288b41,0x3f2a56d3,0x3f2c253d,0x3f2df680, - 0x3f2fca9e,0x3f31a197,0x3f337b6c,0x3f355820,0x3f3737b3,0x3f391a26,0x3f3aff7c,0x3f3ce7b5, - 0x3f3ed2d2,0x3f40c0d4,0x3f42b1be,0x3f44a590,0x3f469c4b,0x3f4895f1,0x3f4a9282,0x3f4c9201, - 0x3f4e946e,0x3f5099cb,0x3f52a218,0x3f54ad57,0x3f56bb8a,0x3f58ccb0,0x3f5ae0cd,0x3f5cf7e0, - 0x3f5f11ec,0x3f612eee,0x3f634eef,0x3f6571e9,0x3f6797e3,0x3f69c0d6,0x3f6beccd,0x3f6e1bbf, - 0x3f704db8,0x3f7282af,0x3f74baae,0x3f76f5ae,0x3f7933b9,0x3f7b74c6,0x3f7db8e0,0x3f800000 -}; - -D3DX11INLINE FLOAT D3DX_SRGB_to_FLOAT(UINT val) -{ -#if HLSL_VERSION > 0 - return asfloat(D3DX_SRGBTable[val]); -#else - return *(FLOAT*)&D3DX_SRGBTable[val]; -#endif -} - -D3DX11INLINE FLOAT D3DX_FLOAT_to_SRGB(hlsl_precise FLOAT val) -{ - if( val < 0.0031308f ) - val *= 12.92f; - else - val = 1.055f * pow(val,1.0f/2.4f) - 0.055f; - return val; -} - -D3DX11INLINE FLOAT D3DX_SaturateSigned_FLOAT(FLOAT _V) -{ - if (D3DX_IsNan(_V)) - { - return 0; - } - - return min(max(_V, -1), 1); -} - -D3DX11INLINE UINT D3DX_FLOAT_to_UINT(FLOAT _V, - FLOAT _Scale) -{ - return (UINT)floor(_V * _Scale + 0.5f); -} - -D3DX11INLINE FLOAT D3DX_INT_to_FLOAT(INT _V, - FLOAT _Scale) -{ - FLOAT Scaled = (FLOAT)_V / _Scale; - // The integer is a two's-complement signed - // number so the negative range is slightly - // larger than the positive range, meaning - // the scaled value can be slight less than -1. - // Clamp to keep the float range [-1, 1]. - return max(Scaled, -1.0f); -} - -D3DX11INLINE INT D3DX_FLOAT_to_INT(FLOAT _V, - FLOAT _Scale) -{ - return (INT)D3DX_Truncate_FLOAT(_V * _Scale + (_V >= 0 ? 0.5f : -0.5f)); -} - -//============================================================================= -// Conversion routines -//============================================================================= -//----------------------------------------------------------------------------- -// R10B10G10A2_UNORM <-> FLOAT4 -//----------------------------------------------------------------------------- -D3DX11INLINE XMFLOAT4 D3DX_R10G10B10A2_UNORM_to_FLOAT4(UINT packedInput) -{ - hlsl_precise XMFLOAT4 unpackedOutput; - unpackedOutput.x = (FLOAT) (packedInput & 0x000003ff) / 1023; - unpackedOutput.y = (FLOAT)(((packedInput>>10) & 0x000003ff)) / 1023; - unpackedOutput.z = (FLOAT)(((packedInput>>20) & 0x000003ff)) / 1023; - unpackedOutput.w = (FLOAT)(((packedInput>>30) & 0x00000003)) / 3; - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_FLOAT4_to_R10G10B10A2_UNORM(hlsl_precise XMFLOAT4 unpackedInput) -{ - UINT packedOutput; - packedOutput = ( (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.x), 1023)) | - (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.y), 1023)<<10) | - (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.z), 1023)<<20) | - (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.w), 3)<<30) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// R10B10G10A2_UINT <-> UINT4 -//----------------------------------------------------------------------------- -D3DX11INLINE XMUINT4 D3DX_R10G10B10A2_UINT_to_UINT4(UINT packedInput) -{ - XMUINT4 unpackedOutput; - unpackedOutput.x = packedInput & 0x000003ff; - unpackedOutput.y = (packedInput>>10) & 0x000003ff; - unpackedOutput.z = (packedInput>>20) & 0x000003ff; - unpackedOutput.w = (packedInput>>30) & 0x00000003; - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_UINT4_to_R10G10B10A2_UINT(XMUINT4 unpackedInput) -{ - UINT packedOutput; - unpackedInput.x = min(unpackedInput.x, 0x000003ff); - unpackedInput.y = min(unpackedInput.y, 0x000003ff); - unpackedInput.z = min(unpackedInput.z, 0x000003ff); - unpackedInput.w = min(unpackedInput.w, 0x00000003); - packedOutput = ( (unpackedInput.x) | - ((unpackedInput.y)<<10) | - ((unpackedInput.z)<<20) | - ((unpackedInput.w)<<30) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// R8G8B8A8_UNORM <-> FLOAT4 -//----------------------------------------------------------------------------- -D3DX11INLINE XMFLOAT4 D3DX_R8G8B8A8_UNORM_to_FLOAT4(UINT packedInput) -{ - hlsl_precise XMFLOAT4 unpackedOutput; - unpackedOutput.x = (FLOAT) (packedInput & 0x000000ff) / 255; - unpackedOutput.y = (FLOAT)(((packedInput>> 8) & 0x000000ff)) / 255; - unpackedOutput.z = (FLOAT)(((packedInput>>16) & 0x000000ff)) / 255; - unpackedOutput.w = (FLOAT) (packedInput>>24) / 255; - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_FLOAT4_to_R8G8B8A8_UNORM(hlsl_precise XMFLOAT4 unpackedInput) -{ - UINT packedOutput; - packedOutput = ( (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.x), 255)) | - (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.y), 255)<< 8) | - (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.z), 255)<<16) | - (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.w), 255)<<24) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// R8G8B8A8_UNORM_SRGB <-> FLOAT4 -//----------------------------------------------------------------------------- -D3DX11INLINE XMFLOAT4 D3DX_R8G8B8A8_UNORM_SRGB_to_FLOAT4_inexact(UINT packedInput) -{ - hlsl_precise XMFLOAT4 unpackedOutput; - unpackedOutput.x = D3DX_SRGB_to_FLOAT_inexact(((FLOAT) (packedInput & 0x000000ff) )/255); - unpackedOutput.y = D3DX_SRGB_to_FLOAT_inexact(((FLOAT)(((packedInput>> 8) & 0x000000ff)))/255); - unpackedOutput.z = D3DX_SRGB_to_FLOAT_inexact(((FLOAT)(((packedInput>>16) & 0x000000ff)))/255); - unpackedOutput.w = (FLOAT)(packedInput>>24) / 255; - return unpackedOutput; -} - -D3DX11INLINE XMFLOAT4 D3DX_R8G8B8A8_UNORM_SRGB_to_FLOAT4(UINT packedInput) -{ - hlsl_precise XMFLOAT4 unpackedOutput; - unpackedOutput.x = D3DX_SRGB_to_FLOAT( (packedInput & 0x000000ff) ); - unpackedOutput.y = D3DX_SRGB_to_FLOAT((((packedInput>> 8) & 0x000000ff))); - unpackedOutput.z = D3DX_SRGB_to_FLOAT((((packedInput>>16) & 0x000000ff))); - unpackedOutput.w = (FLOAT)(packedInput>>24) / 255; - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_FLOAT4_to_R8G8B8A8_UNORM_SRGB(hlsl_precise XMFLOAT4 unpackedInput) -{ - UINT packedOutput; - unpackedInput.x = D3DX_FLOAT_to_SRGB(D3DX_Saturate_FLOAT(unpackedInput.x)); - unpackedInput.y = D3DX_FLOAT_to_SRGB(D3DX_Saturate_FLOAT(unpackedInput.y)); - unpackedInput.z = D3DX_FLOAT_to_SRGB(D3DX_Saturate_FLOAT(unpackedInput.z)); - unpackedInput.w = D3DX_Saturate_FLOAT(unpackedInput.w); - packedOutput = ( (D3DX_FLOAT_to_UINT(unpackedInput.x, 255)) | - (D3DX_FLOAT_to_UINT(unpackedInput.y, 255)<< 8) | - (D3DX_FLOAT_to_UINT(unpackedInput.z, 255)<<16) | - (D3DX_FLOAT_to_UINT(unpackedInput.w, 255)<<24) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// R8G8B8A8_UINT <-> UINT4 -//----------------------------------------------------------------------------- -D3DX11INLINE XMUINT4 D3DX_R8G8B8A8_UINT_to_UINT4(UINT packedInput) -{ - XMUINT4 unpackedOutput; - unpackedOutput.x = packedInput & 0x000000ff; - unpackedOutput.y = (packedInput>> 8) & 0x000000ff; - unpackedOutput.z = (packedInput>>16) & 0x000000ff; - unpackedOutput.w = packedInput>>24; - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_UINT4_to_R8G8B8A8_UINT(XMUINT4 unpackedInput) -{ - UINT packedOutput; - unpackedInput.x = min(unpackedInput.x, 0x000000ff); - unpackedInput.y = min(unpackedInput.y, 0x000000ff); - unpackedInput.z = min(unpackedInput.z, 0x000000ff); - unpackedInput.w = min(unpackedInput.w, 0x000000ff); - packedOutput = ( unpackedInput.x | - (unpackedInput.y<< 8) | - (unpackedInput.z<<16) | - (unpackedInput.w<<24) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// R8G8B8A8_SNORM <-> FLOAT4 -//----------------------------------------------------------------------------- -D3DX11INLINE XMFLOAT4 D3DX_R8G8B8A8_SNORM_to_FLOAT4(UINT packedInput) -{ - hlsl_precise XMFLOAT4 unpackedOutput; - XMINT4 signExtendedBits; - signExtendedBits.x = (INT)(packedInput << 24) >> 24; - signExtendedBits.y = (INT)((packedInput << 16) & 0xff000000) >> 24; - signExtendedBits.z = (INT)((packedInput << 8) & 0xff000000) >> 24; - signExtendedBits.w = (INT)(packedInput & 0xff000000) >> 24; - unpackedOutput.x = D3DX_INT_to_FLOAT(signExtendedBits.x, 127); - unpackedOutput.y = D3DX_INT_to_FLOAT(signExtendedBits.y, 127); - unpackedOutput.z = D3DX_INT_to_FLOAT(signExtendedBits.z, 127); - unpackedOutput.w = D3DX_INT_to_FLOAT(signExtendedBits.w, 127); - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_FLOAT4_to_R8G8B8A8_SNORM(hlsl_precise XMFLOAT4 unpackedInput) -{ - UINT packedOutput; - packedOutput = ( (D3DX_FLOAT_to_INT(D3DX_SaturateSigned_FLOAT(unpackedInput.x), 127) & 0x000000ff) | - ((D3DX_FLOAT_to_INT(D3DX_SaturateSigned_FLOAT(unpackedInput.y), 127) & 0x000000ff)<< 8) | - ((D3DX_FLOAT_to_INT(D3DX_SaturateSigned_FLOAT(unpackedInput.z), 127) & 0x000000ff)<<16) | - ((D3DX_FLOAT_to_INT(D3DX_SaturateSigned_FLOAT(unpackedInput.w), 127)) <<24) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// R8G8B8A8_SINT <-> INT4 -//----------------------------------------------------------------------------- -D3DX11INLINE XMINT4 D3DX_R8G8B8A8_SINT_to_INT4(UINT packedInput) -{ - XMINT4 unpackedOutput; - unpackedOutput.x = (INT)(packedInput << 24) >> 24; - unpackedOutput.y = (INT)((packedInput << 16) & 0xff000000) >> 24; - unpackedOutput.z = (INT)((packedInput << 8) & 0xff000000) >> 24; - unpackedOutput.w = (INT)(packedInput & 0xff000000) >> 24; - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_INT4_to_R8G8B8A8_SINT(XMINT4 unpackedInput) -{ - UINT packedOutput; - unpackedInput.x = max(min(unpackedInput.x,127),-128); - unpackedInput.y = max(min(unpackedInput.y,127),-128); - unpackedInput.z = max(min(unpackedInput.z,127),-128); - unpackedInput.w = max(min(unpackedInput.w,127),-128); - packedOutput = ( (unpackedInput.x & 0x000000ff) | - ((unpackedInput.y & 0x000000ff)<< 8) | - ((unpackedInput.z & 0x000000ff)<<16) | - (unpackedInput.w <<24) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// B8G8R8A8_UNORM <-> FLOAT4 -//----------------------------------------------------------------------------- -D3DX11INLINE XMFLOAT4 D3DX_B8G8R8A8_UNORM_to_FLOAT4(UINT packedInput) -{ - hlsl_precise XMFLOAT4 unpackedOutput; - unpackedOutput.z = (FLOAT) (packedInput & 0x000000ff) / 255; - unpackedOutput.y = (FLOAT)(((packedInput>> 8) & 0x000000ff)) / 255; - unpackedOutput.x = (FLOAT)(((packedInput>>16) & 0x000000ff)) / 255; - unpackedOutput.w = (FLOAT) (packedInput>>24) / 255; - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_FLOAT4_to_B8G8R8A8_UNORM(hlsl_precise XMFLOAT4 unpackedInput) -{ - UINT packedOutput; - packedOutput = ( (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.z), 255)) | - (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.y), 255)<< 8) | - (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.x), 255)<<16) | - (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.w), 255)<<24) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// B8G8R8A8_UNORM_SRGB <-> FLOAT4 -//----------------------------------------------------------------------------- -D3DX11INLINE XMFLOAT4 D3DX_B8G8R8A8_UNORM_SRGB_to_FLOAT4_inexact(UINT packedInput) -{ - hlsl_precise XMFLOAT4 unpackedOutput; - unpackedOutput.z = D3DX_SRGB_to_FLOAT_inexact(((FLOAT) (packedInput & 0x000000ff) )/255); - unpackedOutput.y = D3DX_SRGB_to_FLOAT_inexact(((FLOAT)(((packedInput>> 8) & 0x000000ff)))/255); - unpackedOutput.x = D3DX_SRGB_to_FLOAT_inexact(((FLOAT)(((packedInput>>16) & 0x000000ff)))/255); - unpackedOutput.w = (FLOAT)(packedInput>>24) / 255; - return unpackedOutput; -} - -D3DX11INLINE XMFLOAT4 D3DX_B8G8R8A8_UNORM_SRGB_to_FLOAT4(UINT packedInput) -{ - hlsl_precise XMFLOAT4 unpackedOutput; - unpackedOutput.z = D3DX_SRGB_to_FLOAT( (packedInput & 0x000000ff) ); - unpackedOutput.y = D3DX_SRGB_to_FLOAT((((packedInput>> 8) & 0x000000ff))); - unpackedOutput.x = D3DX_SRGB_to_FLOAT((((packedInput>>16) & 0x000000ff))); - unpackedOutput.w = (FLOAT)(packedInput>>24) / 255; - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_FLOAT4_to_B8G8R8A8_UNORM_SRGB(hlsl_precise XMFLOAT4 unpackedInput) -{ - UINT packedOutput; - unpackedInput.z = D3DX_FLOAT_to_SRGB(D3DX_Saturate_FLOAT(unpackedInput.z)); - unpackedInput.y = D3DX_FLOAT_to_SRGB(D3DX_Saturate_FLOAT(unpackedInput.y)); - unpackedInput.x = D3DX_FLOAT_to_SRGB(D3DX_Saturate_FLOAT(unpackedInput.x)); - unpackedInput.w = D3DX_Saturate_FLOAT(unpackedInput.w); - packedOutput = ( (D3DX_FLOAT_to_UINT(unpackedInput.z, 255)) | - (D3DX_FLOAT_to_UINT(unpackedInput.y, 255)<< 8) | - (D3DX_FLOAT_to_UINT(unpackedInput.x, 255)<<16) | - (D3DX_FLOAT_to_UINT(unpackedInput.w, 255)<<24) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// B8G8R8X8_UNORM <-> FLOAT3 -//----------------------------------------------------------------------------- -D3DX11INLINE XMFLOAT3 D3DX_B8G8R8X8_UNORM_to_FLOAT3(UINT packedInput) -{ - hlsl_precise XMFLOAT3 unpackedOutput; - unpackedOutput.z = (FLOAT) (packedInput & 0x000000ff) / 255; - unpackedOutput.y = (FLOAT)(((packedInput>> 8) & 0x000000ff)) / 255; - unpackedOutput.x = (FLOAT)(((packedInput>>16) & 0x000000ff)) / 255; - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_FLOAT3_to_B8G8R8X8_UNORM(hlsl_precise XMFLOAT3 unpackedInput) -{ - UINT packedOutput; - packedOutput = ( (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.z), 255)) | - (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.y), 255)<< 8) | - (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.x), 255)<<16) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// B8G8R8X8_UNORM_SRGB <-> FLOAT3 -//----------------------------------------------------------------------------- -D3DX11INLINE XMFLOAT3 D3DX_B8G8R8X8_UNORM_SRGB_to_FLOAT3_inexact(UINT packedInput) -{ - hlsl_precise XMFLOAT3 unpackedOutput; - unpackedOutput.z = D3DX_SRGB_to_FLOAT_inexact(((FLOAT) (packedInput & 0x000000ff) )/255); - unpackedOutput.y = D3DX_SRGB_to_FLOAT_inexact(((FLOAT)(((packedInput>> 8) & 0x000000ff)))/255); - unpackedOutput.x = D3DX_SRGB_to_FLOAT_inexact(((FLOAT)(((packedInput>>16) & 0x000000ff)))/255); - return unpackedOutput; -} - -D3DX11INLINE XMFLOAT3 D3DX_B8G8R8X8_UNORM_SRGB_to_FLOAT3(UINT packedInput) -{ - hlsl_precise XMFLOAT3 unpackedOutput; - unpackedOutput.z = D3DX_SRGB_to_FLOAT( (packedInput & 0x000000ff) ); - unpackedOutput.y = D3DX_SRGB_to_FLOAT((((packedInput>> 8) & 0x000000ff))); - unpackedOutput.x = D3DX_SRGB_to_FLOAT((((packedInput>>16) & 0x000000ff))); - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_FLOAT3_to_B8G8R8X8_UNORM_SRGB(hlsl_precise XMFLOAT3 unpackedInput) -{ - UINT packedOutput; - unpackedInput.z = D3DX_FLOAT_to_SRGB(D3DX_Saturate_FLOAT(unpackedInput.z)); - unpackedInput.y = D3DX_FLOAT_to_SRGB(D3DX_Saturate_FLOAT(unpackedInput.y)); - unpackedInput.x = D3DX_FLOAT_to_SRGB(D3DX_Saturate_FLOAT(unpackedInput.x)); - packedOutput = ( (D3DX_FLOAT_to_UINT(unpackedInput.z, 255)) | - (D3DX_FLOAT_to_UINT(unpackedInput.y, 255)<< 8) | - (D3DX_FLOAT_to_UINT(unpackedInput.x, 255)<<16) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// R16G16_FLOAT <-> FLOAT2 -//----------------------------------------------------------------------------- - -#if HLSL_VERSION > 0 - -D3DX11INLINE XMFLOAT2 D3DX_R16G16_FLOAT_to_FLOAT2(UINT packedInput) -{ - hlsl_precise XMFLOAT2 unpackedOutput; - unpackedOutput.x = f16tof32(packedInput&0x0000ffff); - unpackedOutput.y = f16tof32(packedInput>>16); - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_FLOAT2_to_R16G16_FLOAT(hlsl_precise XMFLOAT2 unpackedInput) -{ - UINT packedOutput; - packedOutput = asuint(f32tof16(unpackedInput.x)) | - (asuint(f32tof16(unpackedInput.y)) << 16); - return packedOutput; -} - -#endif // HLSL_VERSION > 0 - -//----------------------------------------------------------------------------- -// R16G16_UNORM <-> FLOAT2 -//----------------------------------------------------------------------------- -D3DX11INLINE XMFLOAT2 D3DX_R16G16_UNORM_to_FLOAT2(UINT packedInput) -{ - hlsl_precise XMFLOAT2 unpackedOutput; - unpackedOutput.x = (FLOAT) (packedInput & 0x0000ffff) / 65535; - unpackedOutput.y = (FLOAT) (packedInput>>16) / 65535; - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_FLOAT2_to_R16G16_UNORM(hlsl_precise XMFLOAT2 unpackedInput) -{ - UINT packedOutput; - packedOutput = ( (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.x), 65535)) | - (D3DX_FLOAT_to_UINT(D3DX_Saturate_FLOAT(unpackedInput.y), 65535)<< 16) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// R16G16_UINT <-> UINT2 -//----------------------------------------------------------------------------- -D3DX11INLINE XMUINT2 D3DX_R16G16_UINT_to_UINT2(UINT packedInput) -{ - XMUINT2 unpackedOutput; - unpackedOutput.x = packedInput & 0x0000ffff; - unpackedOutput.y = packedInput>>16; - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_UINT2_to_R16G16_UINT(XMUINT2 unpackedInput) -{ - UINT packedOutput; - unpackedInput.x = min(unpackedInput.x,0x0000ffff); - unpackedInput.y = min(unpackedInput.y,0x0000ffff); - packedOutput = ( unpackedInput.x | - (unpackedInput.y<<16) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// R16G16_SNORM <-> FLOAT2 -//----------------------------------------------------------------------------- -D3DX11INLINE XMFLOAT2 D3DX_R16G16_SNORM_to_FLOAT2(UINT packedInput) -{ - hlsl_precise XMFLOAT2 unpackedOutput; - XMINT2 signExtendedBits; - signExtendedBits.x = (INT)(packedInput << 16) >> 16; - signExtendedBits.y = (INT)(packedInput & 0xffff0000) >> 16; - unpackedOutput.x = D3DX_INT_to_FLOAT(signExtendedBits.x, 32767); - unpackedOutput.y = D3DX_INT_to_FLOAT(signExtendedBits.y, 32767); - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_FLOAT2_to_R16G16_SNORM(hlsl_precise XMFLOAT2 unpackedInput) -{ - UINT packedOutput; - packedOutput = ( (D3DX_FLOAT_to_INT(D3DX_SaturateSigned_FLOAT(unpackedInput.x), 32767) & 0x0000ffff) | - (D3DX_FLOAT_to_INT(D3DX_SaturateSigned_FLOAT(unpackedInput.y), 32767) <<16) ); - return packedOutput; -} - -//----------------------------------------------------------------------------- -// R16G16_SINT <-> INT2 -//----------------------------------------------------------------------------- -D3DX11INLINE XMINT2 D3DX_R16G16_SINT_to_INT2(UINT packedInput) -{ - XMINT2 unpackedOutput; - unpackedOutput.x = (INT)(packedInput << 16) >> 16; - unpackedOutput.y = (INT)(packedInput & 0xffff0000) >> 16; - return unpackedOutput; -} - -D3DX11INLINE UINT D3DX_INT2_to_R16G16_SINT(XMINT2 unpackedInput) -{ - UINT packedOutput; - unpackedInput.x = max(min(unpackedInput.x,32767),-32768); - unpackedInput.y = max(min(unpackedInput.y,32767),-32768); - packedOutput = ( (unpackedInput.x & 0x0000ffff) | - (unpackedInput.y <<16) ); - return packedOutput; -} - -#endif // __D3DX_DXGI_FORMAT_CONVERT_INL___ diff --git a/SampleFramework12/v1.00/Shaders/EVSMConvert.hlsl b/SampleFramework12/v1.00/Shaders/EVSMConvert.hlsl deleted file mode 100644 index 50f5d4a..0000000 --- a/SampleFramework12/v1.00/Shaders/EVSMConvert.hlsl +++ /dev/null @@ -1,136 +0,0 @@ -//================================================================================================= -// -// MJP's DX12 Sample Framework -// http://mynameismjp.wordpress.com/ -// -// All code licensed under the MIT license -// -//================================================================================================= - -//================================================================================================= -// Includes -//================================================================================================= -#include - -//================================================================================================= -// Constants -//================================================================================================= -#ifndef MSAASamples_ - #define MSAASamples_ 1 -#endif - -#ifndef SampleRadius_ - #define SampleRadius_ 0 -#endif - -//================================================================================================= -// Resources -//================================================================================================= -#if MSAASamples_ > 1 - Texture2DMS ShadowMap : register(t0); -#else - Texture2D ShadowMap : register(t0); -#endif - -#if Vertical_ - Texture2D EVSMMap : register(t0); -#else - Texture2DArray EVSMMap : register(t0); -#endif - -cbuffer EVSMConstants : register(b0) -{ - float3 CascadeScale; - float PositiveExponent; - float NegativeExponent; - float FilterSize; - float2 ShadowMapSize; -} - -struct VSOutput -{ - float4 Position : SV_Position; - float2 TexCoord : TEXCOORD; -}; - -VSOutput FullScreenVS(in uint VertexID : SV_VertexID) -{ - VSOutput output; - - if(VertexID == 0) - { - output.Position = float4(-1.0f, 1.0f, 1.0f, 1.0f); - output.TexCoord = float2(0.0f, 0.0f); - } - else if(VertexID == 1) - { - output.Position = float4(3.0f, 1.0f, 1.0f, 1.0f); - output.TexCoord = float2(2.0f, 0.0f); - } - else - { - output.Position = float4(-1.0f, -3.0f, 1.0f, 1.0f); - output.TexCoord = float2(0.0f, 2.0f); - } - - return output; -} - -float4 ConvertToEVSM(in VSOutput input) : SV_Target0 -{ - float sampleWeight = 1.0f / float(MSAASamples_); - uint2 coords = uint2(input.Position.xy); - - float2 exponents = GetEVSMExponents(PositiveExponent, NegativeExponent, CascadeScale); - - float4 average = float4(0.0f, 0.0f, 0.0f, 0.0f); - - // Sample indices to Load() must be literal, so force unroll - [unroll] - for(uint i = 0; i < MSAASamples_; ++i) - { - // Convert to EVSM representation - #if MSAASamples_ > 1 - float depth = ShadowMap.Load(coords, i); - #else - float depth = ShadowMap[coords]; - #endif - - float2 warpedDepth = WarpDepth(depth, exponents); - average += sampleWeight * float4(warpedDepth.xy, warpedDepth.xy * warpedDepth.xy); - } - - return average; -} - -float4 BlurSample(in float2 screenPos, in float offset, in float2 mapSize) -{ - #if Vertical_ - float2 samplePos = screenPos; - samplePos.y = clamp(screenPos.y + offset, 0, mapSize.y); - return EVSMMap[uint2(samplePos)]; - #else - float2 samplePos = screenPos; - samplePos.x = clamp(screenPos.x + offset, 0, mapSize.x); - return EVSMMap[uint3(samplePos, 0)]; - #endif -} - -float4 BlurEVSM(in VSOutput input) : SV_Target0 -{ - const float Radius = FilterSize / 2.0f; - - float4 sum = 0.0f; - - [unroll] - for(int i = -SampleRadius_; i <= SampleRadius_; ++i) - { - float4 sample = BlurSample(input.Position.xy, i, ShadowMapSize); - - sample *= saturate((Radius + 0.5f) - abs(i)); - - sum += sample; - } - - return sum / FilterSize; -} \ No newline at end of file diff --git a/SampleFramework12/v1.00/Shaders/Shadows.hlsl b/SampleFramework12/v1.00/Shaders/Shadows.hlsl deleted file mode 100644 index 4af3ae2..0000000 --- a/SampleFramework12/v1.00/Shaders/Shadows.hlsl +++ /dev/null @@ -1,424 +0,0 @@ -//================================================================================================= -// -// MJP's DX12 Sample Framework -// http://mynameismjp.wordpress.com/ -// -// All code licensed under the MIT license -// -//================================================================================================= - -#include - -// Options -#ifndef UseGatherPCF_ - #define UseGatherPCF_ 1 -#endif - -#ifndef UseReceiverPlaneBias_ - #define UseReceiverPlaneBias_ 1 -#endif - -//================================================================================================= -// Constants -//================================================================================================= -static const uint NumCascades = 4; - -struct ShadowConstantsEVSM -{ - row_major float4x4 ShadowMatrix; - float4 CascadeSplits; - float4 CascadeOffsets[NumCascades]; - float4 CascadeScales[NumCascades]; - - float PositiveExponent; - float NegativeExponent; - float LightBleedingReduction; -}; - -struct ShadowConstants -{ - row_major float4x4 ShadowMatrix; - float4 CascadeSplits; - float4 CascadeOffsets[NumCascades]; - float4 CascadeScales[NumCascades]; -}; - -//------------------------------------------------------------------------------------------------- -// Samples the EVSM shadow map -//------------------------------------------------------------------------------------------------- -float SampleShadowMapEVSM(in float3 shadowPos, in float3 shadowPosDX, - in float3 shadowPosDY, in uint cascadeIdx, - in Texture2DArray sunShadowMap, in SamplerState evsmSampler, - in ShadowConstantsEVSM shadowConstants) -{ - float2 exponents = GetEVSMExponents(shadowConstants.PositiveExponent, shadowConstants.NegativeExponent, - shadowConstants.CascadeScales[cascadeIdx].xyz); - float2 warpedDepth = WarpDepth(shadowPos.z, exponents); - - float4 occluder = sunShadowMap.SampleGrad(evsmSampler, float3(shadowPos.xy, cascadeIdx), - shadowPosDX.xy, shadowPosDY.xy); - - // Derivative of warping at depth - float2 depthScale = 0.0001f * exponents * warpedDepth; - float2 minVariance = depthScale * depthScale; - - float posContrib = ChebyshevUpperBound(occluder.xz, warpedDepth.x, minVariance.x, shadowConstants.LightBleedingReduction); - float negContrib = ChebyshevUpperBound(occluder.yw, warpedDepth.y, minVariance.y, shadowConstants.LightBleedingReduction); - float shadowContrib = posContrib; - shadowContrib = min(shadowContrib, negContrib); - - return shadowContrib; -} - -//------------------------------------------------------------------------------------------------- -// Samples the appropriate shadow map cascade -//------------------------------------------------------------------------------------------------- -float3 SampleShadowCascadeEVSM(in float3 shadowPosition, in float3 shadowPosDX, - in float3 shadowPosDY, in uint cascadeIdx, - in Texture2DArray sunShadowMap, in SamplerState evsmSampler, - in ShadowConstantsEVSM shadowConstants) -{ - shadowPosition += shadowConstants.CascadeOffsets[cascadeIdx].xyz; - shadowPosition *= shadowConstants.CascadeScales[cascadeIdx].xyz; - - shadowPosDX *= shadowConstants.CascadeScales[cascadeIdx].xyz; - shadowPosDY *= shadowConstants.CascadeScales[cascadeIdx].xyz; - - float3 cascadeColor = 1.0f; - - float shadow = SampleShadowMapEVSM(shadowPosition, shadowPosDX, shadowPosDY, cascadeIdx, sunShadowMap, evsmSampler, shadowConstants); - - return shadow * cascadeColor; -} - -//-------------------------------------------------------------------------------------- -// Computes the sun visibility term by performing the shadow test -//-------------------------------------------------------------------------------------- -float3 SunShadowVisibilityEVSM(in float3 positionWS, in float depthVS, - in Texture2DArray sunShadowMap, in SamplerState evsmSampler, - in ShadowConstantsEVSM shadowConstants) -{ - float3 shadowVisibility = 1.0f; - uint cascadeIdx = 0; - - // Project into shadow space - float3 samplePos = positionWS; - float3 shadowPosition = mul(float4(samplePos, 1.0f), shadowConstants.ShadowMatrix).xyz; - float3 shadowPosDX = ddx(shadowPosition); - float3 shadowPosDY = ddy(shadowPosition); - - // Figure out which cascade to sample from - [unroll] - for(uint i = 0; i < NumCascades - 1; ++i) - { - [flatten] - if(depthVS > shadowConstants.CascadeSplits[i]) - cascadeIdx = i + 1; - } - - shadowVisibility = SampleShadowCascadeEVSM(shadowPosition, shadowPosDX, shadowPosDY, - cascadeIdx, sunShadowMap, evsmSampler, shadowConstants); - - return shadowVisibility; -} - -//------------------------------------------------------------------------------------------------- -// Computes the factor used to bias the depth comparison value based on the derivatives of the -// shadow-space position with respect to screen-space X and Y. -//------------------------------------------------------------------------------------------------- -float2 ComputeReceiverPlaneDepthBias(in float3 uvDX, in float3 uvDY) -{ - float2 biasUV; - biasUV.x = uvDY.y * uvDX.z - uvDX.y * uvDY.z; - biasUV.y = uvDX.x * uvDY.z - uvDY.x * uvDX.z; - biasUV *= 1.0f / ((uvDX.x * uvDY.y) - (uvDX.y * uvDY.x)); - return biasUV; -} - -#if UseGatherPCF_ - -// 7x7 disc kernel -static const uint ShadowFilterSize = 7; -static const float W[ShadowFilterSize][ShadowFilterSize] = -{ - { 0.0f, 0.0f, 0.5f, 1.0f, 0.5f, 0.0f, 0.0f }, - { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f }, - { 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f }, - { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }, - { 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f }, - { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f }, - { 0.0f, 0.0f, 0.5f, 1.0f, 0.5f, 0.0f, 0.0f } -}; - -//------------------------------------------------------------------------------------------------- -// Samples the shadow map with a fixed-size PCF kernel optimized with GatherCmp. Uses code -// from "Fast Conventional Shadow Filtering" by Holger Gruen, in GPU Pro. -//------------------------------------------------------------------------------------------------- -float SampleShadowMapGatherPCF(in float3 shadowPos, in float2 planeBias, in uint shadowMapIdx, - in Texture2DArray shadowMap, in SamplerComparisonState shadowSampler) { - float2 shadowMapSize; - float numSlices; - shadowMap.GetDimensions(shadowMapSize.x, shadowMapSize.y, numSlices); - float2 texelSize = 1.0f / shadowMapSize; - - float lightDepth = shadowPos.z; - - // Static depth biasing to make up for incorrect fractional sampling on the shadow map grid - float fractionalError = dot(float2(1.0f, 1.0f) * texelSize, abs(planeBias)); - lightDepth -= min(fractionalError, 0.01f); - - const int FS_2 = int(ShadowFilterSize) / 2; - - float2 tc = shadowPos.xy; - - float4 s = 0.0f; - float2 stc = (shadowMapSize * tc.xy) + float2(0.5f, 0.5f); - float2 tcs = floor(stc); - float2 fc = 0.0f; - float w = 0.0f; - float4 v1[FS_2 + 1]; - float2 v0[FS_2 + 1]; - - fc.xy = stc - tcs; - tc.xy = tcs / shadowMapSize; - - for(uint y = 0; y < ShadowFilterSize; ++y) - for(uint x = 0; x < ShadowFilterSize; ++x) - w += W[y][x]; - - // -- loop over the rows - [unroll] - for(int row = -FS_2; row <= FS_2; row += 2) - { - [unroll] - for(int col = -FS_2; col <= FS_2; col += 2) - { - float value = W[row + FS_2][col + FS_2]; - - if(col > -FS_2) - value += W[row + FS_2][col + FS_2 - 1]; - - if(col < FS_2) - value += W[row + FS_2][col + FS_2 + 1]; - - if(row > -FS_2) { - value += W[row + FS_2 - 1][col + FS_2]; - - if(col < FS_2) - value += W[row + FS_2 - 1][col + FS_2 + 1]; - - if(col > -FS_2) - value += W[row + FS_2 - 1][col + FS_2 - 1]; - } - - if(value != 0.0f) - { - float sampleDepth = lightDepth; - - // Compute offset and apply planar depth bias - float2 offset = float2(col, row) * texelSize; - sampleDepth -= saturate(-dot(offset, planeBias)); - - v1[(col + FS_2) / 2] = shadowMap.GatherCmp(shadowSampler, float3(tc.xy, shadowMapIdx), sampleDepth, int2(col, row)); - } - else - v1[(col + FS_2) / 2] = 0.0f; - - if(col == -FS_2) - { - s.x += (1.0f - fc.y) * (v1[0].w * (W[row + FS_2][col + FS_2] - W[row + FS_2][col + FS_2] * fc.x) + v1[0].z * (fc.x * (W[row + FS_2][col + FS_2] - - W[row + FS_2][col + FS_2 + 1.0f]) + W[row + FS_2][col + FS_2 + 1])); - s.y += fc.y * (v1[0].x * (W[row + FS_2][col + FS_2] - W[row + FS_2][col + FS_2] * fc.x) - + v1[0].y * (fc.x * (W[row + FS_2][col + FS_2] - W[row + FS_2][col + FS_2 + 1]) - + W[row + FS_2][col + FS_2 + 1])); - if(row > -FS_2) - { - s.z += (1.0f - fc.y) * (v0[0].x * (W[row + FS_2 - 1][col + FS_2] - W[row + FS_2 - 1][col + FS_2] * fc.x) - + v0[0].y * (fc.x * (W[row + FS_2 - 1][col + FS_2] - W[row + FS_2 - 1][col + FS_2 + 1]) - + W[row + FS_2 - 1][col + FS_2 + 1])); - s.w += fc.y * (v1[0].w * (W[row + FS_2 - 1][col + FS_2] - W[row + FS_2 - 1][col + FS_2] * fc.x) - + v1[0].z * (fc.x * (W[row + FS_2 - 1][col + FS_2] - W[row + FS_2 - 1][col + FS_2 + 1]) - + W[row + FS_2 - 1][col + FS_2 + 1])); - } - } - else if(col == FS_2) - { - s.x += (1 - fc.y) * (v1[FS_2].w * (fc.x * (W[row + FS_2][col + FS_2 - 1] - W[row + FS_2][col + FS_2]) + W[row + FS_2][col + FS_2]) - + v1[FS_2].z * fc.x * W[row + FS_2][col + FS_2]); - s.y += fc.y * (v1[FS_2].x * (fc.x * (W[row + FS_2][col + FS_2 - 1] - W[row + FS_2][col + FS_2] ) + W[row + FS_2][col + FS_2]) - + v1[FS_2].y * fc.x * W[row + FS_2][col + FS_2]); - if(row > -FS_2) { - s.z += (1 - fc.y) * (v0[FS_2].x * (fc.x * (W[row + FS_2 - 1][col + FS_2 - 1] - W[row + FS_2 - 1][col + FS_2]) - + W[row + FS_2 - 1][col + FS_2]) + v0[FS_2].y * fc.x * W[row + FS_2 - 1][col + FS_2]); - s.w += fc.y * (v1[FS_2].w * (fc.x * (W[row + FS_2 - 1][col + FS_2 - 1] - W[row + FS_2 - 1][col + FS_2]) - + W[row + FS_2 - 1][col + FS_2]) + v1[FS_2].z * fc.x * W[row + FS_2 - 1][col + FS_2]); - } - } - else - { - s.x += (1 - fc.y) * (v1[(col + FS_2) / 2].w * (fc.x * (W[row + FS_2][col + FS_2 - 1] - W[row + FS_2][col + FS_2 + 0] ) + W[row + FS_2][col + FS_2 + 0]) - + v1[(col + FS_2) / 2].z * (fc.x * (W[row + FS_2][col + FS_2 - 0] - W[row + FS_2][col + FS_2 + 1]) + W[row + FS_2][col + FS_2 + 1])); - s.y += fc.y * (v1[(col + FS_2) / 2].x * (fc.x * (W[row + FS_2][col + FS_2-1] - W[row + FS_2][col + FS_2 + 0]) + W[row + FS_2][col + FS_2 + 0]) - + v1[(col + FS_2) / 2].y * (fc.x * (W[row + FS_2][col + FS_2 - 0] - W[row + FS_2][col + FS_2 + 1]) + W[row + FS_2][col + FS_2 + 1])); - if(row > -FS_2) { - s.z += (1 - fc.y) * (v0[(col + FS_2) / 2].x * (fc.x * (W[row + FS_2 - 1][col + FS_2 - 1] - W[row + FS_2 - 1][col + FS_2 + 0]) + W[row + FS_2 - 1][col + FS_2 + 0]) - + v0[(col + FS_2) / 2].y * (fc.x * (W[row + FS_2 - 1][col + FS_2 - 0] - W[row + FS_2 - 1][col + FS_2 + 1]) + W[row + FS_2 - 1][col + FS_2 + 1])); - s.w += fc.y * (v1[(col + FS_2) / 2].w * (fc.x * (W[row + FS_2 - 1][col + FS_2 - 1] - W[row + FS_2 - 1][col + FS_2 + 0]) + W[row + FS_2 - 1][col + FS_2 + 0]) - + v1[(col + FS_2) / 2].z * (fc.x * (W[row + FS_2 - 1][col + FS_2 - 0] - W[row + FS_2 - 1][col + FS_2 + 1]) + W[row + FS_2 - 1][col + FS_2 + 1])); - } - } - - if(row != FS_2) - v0[(col + FS_2) / 2] = v1[(col + FS_2) / 2].xy; - } - } - - return dot(s, 1.0f) / w; -} - -#endif - -//------------------------------------------------------------------------------------------------- -// Samples the shadow map with a 2x2 hardware PCF kernel -//------------------------------------------------------------------------------------------------- -float SampleShadowMapSimplePCF(in float3 shadowPos, in float2 planeBias, in uint shadowMapIdx, - in Texture2DArray shadowMap, in SamplerComparisonState shadowSampler) { - float2 shadowMapSize; - float numSlices; - shadowMap.GetDimensions(shadowMapSize.x, shadowMapSize.y, numSlices); - float2 texelSize = 1.0f / shadowMapSize; - - float lightDepth = shadowPos.z; - - // Static depth biasing to make up for incorrect fractional sampling on the shadow map grid - float fractionalError = dot(float2(1.0f, 1.0f) * texelSize, abs(planeBias)); - lightDepth -= min(fractionalError, 0.01f); - - return shadowMap.SampleCmpLevelZero(shadowSampler, float3(shadowPos.xy, shadowMapIdx), lightDepth); -} - -//-------------------------------------------------------------------------------------- -// Computes the visibility for a directional light using implicit derivatives -//-------------------------------------------------------------------------------------- -float SunShadows(in float3 shadowPos, in float3 shadowPosDX, in float3 shadowPosDY, in float depthVS, - in Texture2DArray sunShadowMap, in SamplerComparisonState shadowSampler, - in ShadowConstants shadowConstants) -{ - // Figure out which cascade to sample from - uint cascadeIdx = 0; - - [unroll] - for(uint i = 0; i < NumCascades - 1; ++i) - { - [flatten] - if(depthVS > shadowConstants.CascadeSplits[i]) - cascadeIdx = i + 1; - } - - shadowPos += shadowConstants.CascadeOffsets[cascadeIdx].xyz; - shadowPos *= shadowConstants.CascadeScales[cascadeIdx].xyz; - - shadowPosDX *= shadowConstants.CascadeScales[cascadeIdx].xyz; - shadowPosDY *= shadowConstants.CascadeScales[cascadeIdx].xyz; - - #if UseReceiverPlaneBias_ - float2 planeBias = ComputeReceiverPlaneDepthBias(shadowPosDX, shadowPosDY); - #else - shadowPos.z -= 0.01f; - float2 planeBias = 0.0f; - #endif - - #if UseGatherPCF_ - return SampleShadowMapGatherPCF(shadowPos, planeBias, cascadeIdx, sunShadowMap, shadowSampler); - #else - return SampleShadowMapSimplePCF(shadowPos, planeBias, cascadeIdx, sunShadowMap, shadowSampler); - #endif -} - - -//-------------------------------------------------------------------------------------- -// Computes the visibility for a directional light using implicit derivatives -//-------------------------------------------------------------------------------------- -float SunShadowVisibility(in float3 positionWS, in float depthVS, - in Texture2DArray sunShadowMap, in SamplerComparisonState shadowSampler, - in ShadowConstants shadowConstants) -{ - // Project into shadow space - float3 shadowPos = mul(float4(positionWS, 1.0f), shadowConstants.ShadowMatrix).xyz; - float3 shadowPosDX = ddx(shadowPos); - float3 shadowPosDY = ddy(shadowPos); - - return SunShadows(shadowPos, shadowPosDX, shadowPosDY, depthVS, sunShadowMap, shadowSampler, shadowConstants); -} - -//-------------------------------------------------------------------------------------- -// Computes the visibility for a directional light using explicit position derivatives -//-------------------------------------------------------------------------------------- -float SunShadowVisibility(in float3 positionWS, in float3 positionNeighborX, in float3 positionNeighborY, in float depthVS, - in Texture2DArray sunShadowMap, in SamplerComparisonState shadowSampler, - in ShadowConstants shadowConstants) -{ - // Project into shadow space - float3 shadowPos = mul(float4(positionWS, 1.0f), shadowConstants.ShadowMatrix).xyz; - float3 shadowPosDX = mul(float4(positionNeighborX, 1.0f), shadowConstants.ShadowMatrix).xyz - shadowPos; - float3 shadowPosDY = mul(float4(positionNeighborY, 1.0f), shadowConstants.ShadowMatrix).xyz - shadowPos; - - return SunShadows(shadowPos, shadowPosDX, shadowPosDY, depthVS, sunShadowMap, shadowSampler, shadowConstants); -} - -//-------------------------------------------------------------------------------------- -// Computes the visibility for a spot light using explicit position derivatives -//-------------------------------------------------------------------------------------- -float SpotLightShadows(in float3 shadowPos, in float3 shadowPosDX, in float3 shadowPosDY, - in float4x4 shadowMatrix, in uint shadowMapIdx, - in Texture2DArray shadowMap, in SamplerComparisonState shadowSampler) -{ - #if UseReceiverPlaneBias_ - shadowPos.z -= 0.00001f; - float2 planeBias = ComputeReceiverPlaneDepthBias(shadowPosDX, shadowPosDY); - #else - shadowPos.z -= 0.001f; - float2 planeBias = 0.0f; - #endif - - #if UseGatherPCF_ - return SampleShadowMapGatherPCF(shadowPos, planeBias, shadowMapIdx, shadowMap, shadowSampler); - #else - return SampleShadowMapSimplePCF(shadowPos, planeBias, shadowMapIdx, shadowMap, shadowSampler); - #endif -} - -//-------------------------------------------------------------------------------------- -// Computes the visibility for a spot light using implicit derivatives -//-------------------------------------------------------------------------------------- -float SpotLightShadowVisibility(in float3 positionWS, in float4x4 shadowMatrix, in uint shadowMapIdx, - in Texture2DArray shadowMap, in SamplerComparisonState shadowSampler) -{ - // Project into shadow space - float4 shadowPos = mul(float4(positionWS, 1.0f), shadowMatrix); - shadowPos.xyz /= shadowPos.w; - - return SpotLightShadows(shadowPos.xyz, ddx(shadowPos.xyz), ddy(shadowPos.xyz), shadowMatrix, shadowMapIdx, shadowMap, shadowSampler); -} - -//-------------------------------------------------------------------------------------- -// Computes the visibility for a spot light using explicit position derivatives -//-------------------------------------------------------------------------------------- -float SpotLightShadowVisibility(in float3 positionWS, in float3 positionNeighborX, in float3 positionNeighborY, - in float4x4 shadowMatrix, in uint shadowMapIdx, - in Texture2DArray shadowMap, in SamplerComparisonState shadowSampler) -{ - // Project into shadow space - float4 shadowPos = mul(float4(positionWS, 1.0f), shadowMatrix); - shadowPos.xyz /= shadowPos.w; - - float4 shadowPosDX = mul(float4(positionNeighborX, 1.0f), shadowMatrix); - shadowPosDX.xyz /= shadowPosDX.w; - shadowPosDX.xyz -= shadowPos.xyz; - - float4 shadowPosDY = mul(float4(positionNeighborY, 1.0f), shadowMatrix); - shadowPosDY.xyz /= shadowPosDY.w; - shadowPosDY.xyz -= shadowPos.xyz; - - return SpotLightShadows(shadowPos.xyz, shadowPosDX.xyz, shadowPosDY.xyz, shadowMatrix, shadowMapIdx, shadowMap, shadowSampler); -} \ No newline at end of file diff --git a/SampleFramework12/v1.00/.gitignore b/SampleFramework12/v1.01/.gitignore similarity index 100% rename from SampleFramework12/v1.00/.gitignore rename to SampleFramework12/v1.01/.gitignore diff --git a/SampleFramework12/v1.00/App.cpp b/SampleFramework12/v1.01/App.cpp similarity index 82% rename from SampleFramework12/v1.00/App.cpp rename to SampleFramework12/v1.01/App.cpp index 4ad02fe..ecd58bd 100644 --- a/SampleFramework12/v1.00/App.cpp +++ b/SampleFramework12/v1.01/App.cpp @@ -17,6 +17,7 @@ #include "FileIO.h" #include "Settings.h" #include "ImGuiHelper.h" +#include "ImGui/imgui.h" // AppSettings framework namespace AppSettings @@ -32,8 +33,8 @@ namespace SampleFramework12 App* GlobalApp = nullptr; -App::App(const wchar* appName, const wchar* iconResource) : window(NULL, appName, WS_OVERLAPPEDWINDOW, - WS_EX_APPWINDOW, 1280, 720, iconResource, iconResource), +App::App(const wchar* appName, const wchar* cmdLine) : window(nullptr, appName, WS_OVERLAPPEDWINDOW, + WS_EX_APPWINDOW, 1280, 720), applicationName(appName) { @@ -42,6 +43,8 @@ App::App(const wchar* appName, const wchar* iconResource) : window(NULL, appNa timeDeltaBuffer[i] = 0.0f; SampledSpectrum::Init(); + + ParseCommandLine(cmdLine); } App::~App() @@ -130,9 +133,50 @@ void App::Exit() window.Destroy(); } +void App::BeforeFlush() +{ +} + +void App::ParseCommandLine(const wchar* cmdLine) +{ + if(cmdLine == nullptr) + return; + + std::string cmdLineA = WStringToAnsi(cmdLine); + std::vector parts; + Split(cmdLineA, parts, " "); + + uint64 numParts = parts.size(); + if(numParts == 0) + return; + + Array partStrings(numParts + 1); + partStrings[0] = "App"; + for(uint64 i = 0; i < numParts; ++i) + partStrings[i + 1] = &parts[i].front(); + + int32 argc = int32(numParts + 1); + char** argv = partStrings.Data(); + + cxxopts::Options options("App", ""); + options.add_options() + ("a,adapter", "GPU adapter index", cxxopts::value()); + + try + { + options.parse(argc, argv); + } + catch(cxxopts::missing_argument_exception&) + { + } + + if(options.count("adapter")) + adapterIdx = options["adapter"].as(); +} + void App::Initialize_Internal() { - DX12::Initialize(minFeatureLevel); + DX12::Initialize(minFeatureLevel, adapterIdx); window.SetClientArea(swapChain.Width(), swapChain.Height()); swapChain.Initialize(window); @@ -158,6 +202,7 @@ void App::Initialize_Internal() void App::Shutdown_Internal() { + BeforeFlush(); DX12::FlushGPU(); DestroyPSOs(); ImGuiHelper::Shutdown(); @@ -210,7 +255,7 @@ void App::Render_Internal() DrawLog(); - ImGuiHelper::EndFrame(DX12::CmdList, swapChain.BackBuffer().RTV.CPUHandle, displayWidth, displayHeight); + ImGuiHelper::EndFrame(DX12::CmdList, swapChain.BackBuffer().RTV, displayWidth, displayHeight); swapChain.EndFrame(); @@ -219,6 +264,8 @@ void App::Render_Internal() void App::BeforeReset_Internal() { + BeforeFlush(); + // Need this in order to resize the swap chain DX12::FlushGPU(); @@ -298,8 +345,9 @@ void App::DrawLog() return; } - const uint64 start = numLogMessages > MaxLogMessages ? numLogMessages - MaxLogMessages : 0; - for(uint64 i = start; i < numLogMessages; ++i) + const uint64 numMessages = numLogMessages; + const uint64 start = numMessages > MaxLogMessages ? numMessages - MaxLogMessages : 0; + for(uint64 i = start; i < numMessages; ++i) ImGui::TextUnformatted(logMessages[i % MaxLogMessages].c_str()); if(newLogMessage) @@ -315,9 +363,8 @@ void App::AddToLog(const char* msg) if(msg == nullptr) return; - const uint64 idx = numLogMessages % MaxLogMessages; + const uint64 idx = uint64(InterlockedIncrement64(&numLogMessages) - 1) % MaxLogMessages; logMessages[idx] = msg; - ++numLogMessages; newLogMessage = true; } diff --git a/SampleFramework12/v1.00/App.h b/SampleFramework12/v1.01/App.h similarity index 92% rename from SampleFramework12/v1.00/App.h rename to SampleFramework12/v1.01/App.h index a7c1779..4034b7e 100644 --- a/SampleFramework12/v1.00/App.h +++ b/SampleFramework12/v1.01/App.h @@ -25,7 +25,7 @@ class App public: - App(const wchar* appName, const wchar* iconResource = nullptr); + App(const wchar* appName, const wchar* cmdLine); virtual ~App(); int32 Run(); @@ -44,6 +44,8 @@ class App virtual void CreatePSOs() = 0; virtual void DestroyPSOs() = 0; + virtual void BeforeFlush(); + void Exit(); void ToggleFullScreen(bool fullScreen); void CalculateFPS(); @@ -68,17 +70,20 @@ class App bool showWindow = true; int32 returnCode = 0; D3D_FEATURE_LEVEL minFeatureLevel = D3D_FEATURE_LEVEL_11_0; + uint32 adapterIdx = 0; Float4x4 appViewMatrix; static const uint64 MaxLogMessages = 1024; std::string logMessages[MaxLogMessages]; - uint64 numLogMessages = 0; + volatile int64 numLogMessages = 0; bool showLog = false; bool newLogMessage = false; private: + void ParseCommandLine(const wchar* cmdLine); + void Initialize_Internal(); void Shutdown_Internal(); diff --git a/SampleFramework12/v1.00/Assert.cpp b/SampleFramework12/v1.01/Assert.cpp similarity index 100% rename from SampleFramework12/v1.00/Assert.cpp rename to SampleFramework12/v1.01/Assert.cpp diff --git a/SampleFramework12/v1.00/Assert.h b/SampleFramework12/v1.01/Assert.h similarity index 100% rename from SampleFramework12/v1.00/Assert.h rename to SampleFramework12/v1.01/Assert.h diff --git a/SampleFramework12/v1.00/Containers.h b/SampleFramework12/v1.01/Containers.h similarity index 100% rename from SampleFramework12/v1.00/Containers.h rename to SampleFramework12/v1.01/Containers.h diff --git a/BindlessDeferred/EnkiTS/License.txt b/SampleFramework12/v1.01/EnkiTS/License.txt similarity index 100% rename from BindlessDeferred/EnkiTS/License.txt rename to SampleFramework12/v1.01/EnkiTS/License.txt diff --git a/BindlessDeferred/EnkiTS/LockLessMultiReadPipe.h b/SampleFramework12/v1.01/EnkiTS/LockLessMultiReadPipe.h similarity index 100% rename from BindlessDeferred/EnkiTS/LockLessMultiReadPipe.h rename to SampleFramework12/v1.01/EnkiTS/LockLessMultiReadPipe.h diff --git a/BindlessDeferred/EnkiTS/TaskScheduler.cpp b/SampleFramework12/v1.01/EnkiTS/TaskScheduler.cpp similarity index 100% rename from BindlessDeferred/EnkiTS/TaskScheduler.cpp rename to SampleFramework12/v1.01/EnkiTS/TaskScheduler.cpp diff --git a/BindlessDeferred/EnkiTS/TaskScheduler.h b/SampleFramework12/v1.01/EnkiTS/TaskScheduler.h similarity index 100% rename from BindlessDeferred/EnkiTS/TaskScheduler.h rename to SampleFramework12/v1.01/EnkiTS/TaskScheduler.h diff --git a/BindlessDeferred/EnkiTS/TaskScheduler_c.cpp b/SampleFramework12/v1.01/EnkiTS/TaskScheduler_c.cpp similarity index 100% rename from BindlessDeferred/EnkiTS/TaskScheduler_c.cpp rename to SampleFramework12/v1.01/EnkiTS/TaskScheduler_c.cpp diff --git a/BindlessDeferred/EnkiTS/TaskScheduler_c.h b/SampleFramework12/v1.01/EnkiTS/TaskScheduler_c.h similarity index 100% rename from BindlessDeferred/EnkiTS/TaskScheduler_c.h rename to SampleFramework12/v1.01/EnkiTS/TaskScheduler_c.h diff --git a/SampleFramework12/v1.00/Exceptions.h b/SampleFramework12/v1.01/Exceptions.h similarity index 100% rename from SampleFramework12/v1.00/Exceptions.h rename to SampleFramework12/v1.01/Exceptions.h diff --git a/SampleFramework12/v1.00/FileIO.cpp b/SampleFramework12/v1.01/FileIO.cpp similarity index 100% rename from SampleFramework12/v1.00/FileIO.cpp rename to SampleFramework12/v1.01/FileIO.cpp diff --git a/SampleFramework12/v1.00/FileIO.h b/SampleFramework12/v1.01/FileIO.h similarity index 96% rename from SampleFramework12/v1.00/FileIO.h rename to SampleFramework12/v1.01/FileIO.h index d919ea0..928037e 100644 --- a/SampleFramework12/v1.00/FileIO.h +++ b/SampleFramework12/v1.01/FileIO.h @@ -83,14 +83,14 @@ template void File::Write(const T& data) const // Reads a POD type from a file template void ReadFromFile(const wchar* fileName, T& val) { - File file(fileName, File::OpenRead); + File file(fileName, FileOpenMode::Read); file.Read(val); } // Writes a POD type to a file template void WriteToFile(const wchar* fileName, const T& val) { - File file(fileName, File::OpenWrite); + File file(fileName, FileOpenMode::Write); file.Write(val); } diff --git a/SampleFramework12/v1.00/Graphics/BRDF.h b/SampleFramework12/v1.01/Graphics/BRDF.h similarity index 100% rename from SampleFramework12/v1.00/Graphics/BRDF.h rename to SampleFramework12/v1.01/Graphics/BRDF.h diff --git a/SampleFramework12/v1.00/Graphics/Camera.cpp b/SampleFramework12/v1.01/Graphics/Camera.cpp similarity index 100% rename from SampleFramework12/v1.00/Graphics/Camera.cpp rename to SampleFramework12/v1.01/Graphics/Camera.cpp diff --git a/SampleFramework12/v1.00/Graphics/Camera.h b/SampleFramework12/v1.01/Graphics/Camera.h similarity index 94% rename from SampleFramework12/v1.00/Graphics/Camera.h rename to SampleFramework12/v1.01/Graphics/Camera.h index b0416a7..1276fdb 100644 --- a/SampleFramework12/v1.00/Graphics/Camera.h +++ b/SampleFramework12/v1.01/Graphics/Camera.h @@ -45,8 +45,9 @@ class Camera const Float4x4& WorldMatrix() const { return world; }; const Float3& Position() const { return position; }; const Quaternion& Orientation() const { return orientation; }; - const float& NearClip() const { return nearZ; }; - const float& FarClip() const { return farZ; }; + float NearClip() const { return nearZ; }; + float FarClip() const { return farZ; }; + Float3 Forward() const; Float3 Back() const; @@ -62,6 +63,8 @@ class Camera void SetNearClip(float newNearClip); void SetFarClip(float newFarClip); void SetProjection(const Float4x4& newProjection); + + virtual bool IsOrthographic() const { return false; } }; // Camera with an orthographic projection @@ -90,6 +93,8 @@ class OrthographicCamera : public Camera void SetMinY(float minY); void SetMaxX(float maxX); void SetMaxY(float maxY); + + bool IsOrthographic() const override { return true; } }; // Camera with a perspective projection diff --git a/SampleFramework12/v1.00/Graphics/DX12.cpp b/SampleFramework12/v1.01/Graphics/DX12.cpp similarity index 71% rename from SampleFramework12/v1.00/Graphics/DX12.cpp rename to SampleFramework12/v1.01/Graphics/DX12.cpp index e2afa5d..12081c0 100644 --- a/SampleFramework12/v1.00/Graphics/DX12.cpp +++ b/SampleFramework12/v1.01/Graphics/DX12.cpp @@ -1,273 +1,340 @@ -//================================================================================================= -// -// MJP's DX12 Sample Framework -// http://mynameismjp.wordpress.com/ -// -// All code licensed under the MIT license -// -//================================================================================================= - -#include "PCH.h" -#include "DX12.h" -#include "DX12_Upload.h" -#include "DX12_Helpers.h" -#include "GraphicsTypes.h" - -#if Debug_ - #define UseDebugDevice_ 1 - #define BreakOnDXError_ (UseDebugDevice_ && 1) -#else - #define UseDebugDevice_ 0 - #define BreakOnDXError_ 0 -#endif - -namespace SampleFramework12 -{ - -namespace DX12 -{ - -ID3D12Device* Device = nullptr; -ID3D12GraphicsCommandList* CmdList = nullptr; -ID3D12CommandQueue* GfxQueue = nullptr; -D3D_FEATURE_LEVEL FeatureLevel = D3D_FEATURE_LEVEL_11_0; -IDXGIFactory4* Factory = nullptr; -IDXGIAdapter1* Adapter = nullptr; - -uint64 CurrentCPUFrame = 0; -uint64 CurrentGPUFrame = 0; -uint64 CurrFrameIdx = 0; - -static const uint64 NumCmdAllocators = RenderLatency; - -static ID3D12CommandAllocator* CmdAllocators[NumCmdAllocators] = { }; -static Fence FrameFence; - -static GrowableList DeferredReleases[RenderLatency]; -static bool ShuttingDown = false; - -static void ProcessDeferredReleases(uint64 idx) -{ - for(uint64 i = 0; i < DeferredReleases[idx].Count(); ++i) - DeferredReleases[idx][i]->Release(); - DeferredReleases[idx].RemoveAll(nullptr); -} - -void Initialize(D3D_FEATURE_LEVEL minFeatureLevel) -{ - ShuttingDown = false; - - HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(&Factory)); - if(FAILED(hr)) - throw Exception(L"Unable to create a DXGI 1.4 device.\n " - L"Make sure that your OS and driver support DirectX 12"); - - // Just use the first adapter for now - uint32 adapterIdx = 0; - LARGE_INTEGER umdVersion = { }; - Factory->EnumAdapters1(adapterIdx, &Adapter); - - if(Adapter == nullptr) - throw Exception(L"Unable to locate a DXGI 1.4 adapter that supports a D3D12 device.\n" - L"Make sure that your OS and driver support DirectX 12"); - - #if UseDebugDevice_ - ID3D12DebugPtr d3d12debug; - DXCall(D3D12GetDebugInterface(IID_PPV_ARGS(&d3d12debug))); - d3d12debug->EnableDebugLayer(); - #endif - - DXCall(D3D12CreateDevice(Adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&Device))); - - // Check the maximum feature level, and make sure it's above our minimum - D3D_FEATURE_LEVEL featureLevelsArray[4]; - featureLevelsArray[0] = D3D_FEATURE_LEVEL_11_0; - featureLevelsArray[1] = D3D_FEATURE_LEVEL_11_1; - featureLevelsArray[2] = D3D_FEATURE_LEVEL_12_0; - featureLevelsArray[3] = D3D_FEATURE_LEVEL_12_1; - D3D12_FEATURE_DATA_FEATURE_LEVELS featureLevels = { }; - featureLevels.NumFeatureLevels = ArraySize_(featureLevelsArray); - featureLevels.pFeatureLevelsRequested = featureLevelsArray; - DXCall(Device->CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS, &featureLevels, sizeof(featureLevels))); - FeatureLevel = featureLevels.MaxSupportedFeatureLevel; - - if(FeatureLevel < minFeatureLevel) - { - std::wstring majorLevel = ToString(minFeatureLevel >> 12); - std::wstring minorLevel = ToString((minFeatureLevel >> 8) & 0xF); - throw Exception(L"The device doesn't support the minimum feature level required to run this sample (DX" + majorLevel + L"." + minorLevel + L")"); - } - - #if UseDebugDevice_ - ID3D12InfoQueuePtr infoQueue; - DXCall(Device->QueryInterface(IID_PPV_ARGS(&infoQueue))); - - D3D12_MESSAGE_ID disabledMessages[] = - { - D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE, - - // These happen when capturing with VS diagnostics - D3D12_MESSAGE_ID_MAP_INVALID_NULLRANGE, - D3D12_MESSAGE_ID_UNMAP_INVALID_NULLRANGE, - }; - - D3D12_INFO_QUEUE_FILTER filter = { }; - filter.DenyList.NumIDs = ArraySize_(disabledMessages); - filter.DenyList.pIDList = disabledMessages; - infoQueue->AddStorageFilterEntries(&filter); - #endif - - #if BreakOnDXError_ - infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, TRUE); - infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, TRUE); - #endif - - for(uint64 i = 0; i < NumCmdAllocators; ++i) - DXCall(Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&CmdAllocators[i]))); - - DXCall(Device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, CmdAllocators[0], nullptr, IID_PPV_ARGS(&CmdList))); - DXCall(CmdList->Close()); - - D3D12_COMMAND_QUEUE_DESC queueDesc = {}; - queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; - queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; - DXCall(Device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&GfxQueue))); - - CurrFrameIdx = CurrentCPUFrame % NumCmdAllocators; - DXCall(CmdAllocators[CurrFrameIdx]->Reset()); - DXCall(CmdList->Reset(CmdAllocators[CurrFrameIdx], nullptr)); - - FrameFence.Init(0); - - Initialize_Upload(); - Initialize_Helpers(); -} - -void Shutdown() -{ - Assert_(CurrentCPUFrame == CurrentGPUFrame); - ShuttingDown = true; - - for(uint64 i = 0; i < ArraySize_(DeferredReleases); ++i) - ProcessDeferredReleases(i); - - FrameFence.Shutdown(); - - for(uint64 i = 0; i < RenderLatency; ++i) - Release(CmdAllocators[i]); - - Release(CmdList); - Release(GfxQueue); - Release(Factory); - Release(Adapter); - - Shutdown_Upload(); - Shutdown_Helpers(); - - #if BreakOnDXError_ - if(Device != nullptr) - { - ID3D12InfoQueuePtr infoQueue; - DXCall(Device->QueryInterface(IID_PPV_ARGS(&infoQueue))); - infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, FALSE); - infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, FALSE); - } - #endif - - #if UseDebugDevice_ && 0 - if(Device != nullptr) - { - ID3D12DebugDevicePtr debugDevice; - DXCall(Device->QueryInterface(IID_PPV_ARGS(&debugDevice))); - debugDevice->ReportLiveDeviceObjects(D3D12_RLDO_DETAIL); - } - #endif - - Release(Device); -} - -void BeginFrame() -{ - Assert_(Device); - - SetDescriptorHeaps(CmdList); -} - -void EndFrame(IDXGISwapChain4* swapChain, uint32 syncIntervals) -{ - Assert_(Device); - - DXCall(CmdList->Close()); - - EndFrame_Upload(); - - ID3D12CommandList* commandLists[] = { CmdList }; - GfxQueue->ExecuteCommandLists(ArraySize_(commandLists), commandLists); - - // Present the frame. - if(swapChain) - DXCall(swapChain->Present(syncIntervals, syncIntervals == 0 ? DXGI_PRESENT_ALLOW_TEARING : 0)); - - ++CurrentCPUFrame; - - // Signal the fence with the current frame number, so that we can check back on it - FrameFence.Signal(GfxQueue, CurrentCPUFrame); - - // Wait for the GPU to catch up before we stomp an executing command buffer - const uint64 gpuLag = DX12::CurrentCPUFrame - DX12::CurrentGPUFrame; - Assert_(gpuLag <= DX12::RenderLatency); - if(gpuLag >= DX12::RenderLatency) - { - // Make sure that the previous frame is finished - FrameFence.Wait(DX12::CurrentGPUFrame + 1); - ++DX12::CurrentGPUFrame; - } - - CurrFrameIdx = DX12::CurrentCPUFrame % NumCmdAllocators; - - // Prepare the command buffers to be used for the next frame - DXCall(CmdAllocators[CurrFrameIdx]->Reset()); - DXCall(CmdList->Reset(CmdAllocators[CurrFrameIdx], nullptr)); - - EndFrame_Helpers(); - - // See if we have any deferred releases to process - ProcessDeferredReleases(CurrFrameIdx); -} - -void FlushGPU() -{ - Assert_(Device); - - // Wait for the GPU to fully catch up with the CPU - Assert_(CurrentCPUFrame >= CurrentGPUFrame); - if(CurrentCPUFrame > CurrentGPUFrame) - { - FrameFence.Wait(CurrentCPUFrame); - CurrentGPUFrame = CurrentCPUFrame; - } - - // Clean up what we can now - for(uint64 i = 1; i < RenderLatency; ++i) - ProcessDeferredReleases((i + CurrFrameIdx) % RenderLatency); -} - -void DeferredRelease_(IUnknown* resource) -{ - if(resource == nullptr) - return; - - if(ShuttingDown || Device == nullptr) - { - // Free-for-all! - resource->Release(); - return; - } - - DeferredReleases[CurrFrameIdx].Add(resource); -} - -} // namespace SampleFramework12 - -} // namespace SampleFramework12 - +//================================================================================================= +// +// MJP's DX12 Sample Framework +// http://mynameismjp.wordpress.com/ +// +// All code licensed under the MIT license +// +//================================================================================================= + +#include "PCH.h" +#include "DX12.h" +#include "DX12_Upload.h" +#include "DX12_Helpers.h" +#include "GraphicsTypes.h" + +#if Debug_ + #define UseDebugDevice_ 1 + #define BreakOnDXError_ (UseDebugDevice_ && 1) + #define UseGPUValidation_ 0 +#else + #define UseDebugDevice_ 0 + #define BreakOnDXError_ 0 + #define UseGPUValidation_ 0 +#endif + +namespace SampleFramework12 +{ + +namespace DX12 +{ + +ID3D12Device2* Device = nullptr; +ID3D12GraphicsCommandList1* CmdList = nullptr; +ID3D12CommandQueue* GfxQueue = nullptr; +D3D_FEATURE_LEVEL FeatureLevel = D3D_FEATURE_LEVEL_11_0; +IDXGIFactory4* Factory = nullptr; +IDXGIAdapter1* Adapter = nullptr; + +uint64 CurrentCPUFrame = 0; +uint64 CurrentGPUFrame = 0; +uint64 CurrFrameIdx = 0; + +static const uint64 NumCmdAllocators = RenderLatency; + +static ID3D12CommandAllocator* CmdAllocators[NumCmdAllocators] = { }; +static Fence FrameFence; + +static GrowableList DeferredReleases[RenderLatency]; +static bool ShuttingDown = false; + +struct DeferredSRVCreate +{ + ID3D12Resource* Resource = nullptr; + D3D12_SHADER_RESOURCE_VIEW_DESC Desc = { }; + uint32 DescriptorIdx = uint32(-1); +}; + +static Array DeferredSRVCreates[RenderLatency]; +static volatile uint64 DeferredSRVCreateCount[RenderLatency] = { }; + +static void ProcessDeferredReleases(uint64 frameIdx) +{ + for(uint64 i = 0; i < DeferredReleases[frameIdx].Count(); ++i) + DeferredReleases[frameIdx][i]->Release(); + DeferredReleases[frameIdx].RemoveAll(nullptr); +} + +static void ProcessDeferredSRVCreates(uint64 frameIdx) +{ + uint64 createCount = DeferredSRVCreateCount[frameIdx]; + for(uint64 i = 0; i < createCount; ++i) + { + DeferredSRVCreate& create = DeferredSRVCreates[frameIdx][i]; + Assert_(create.Resource != nullptr); + + D3D12_CPU_DESCRIPTOR_HANDLE handle = SRVDescriptorHeap.CPUHandleFromIndex(create.DescriptorIdx, frameIdx); + Device->CreateShaderResourceView(create.Resource, &create.Desc, handle); + + create.Resource = nullptr; + create.DescriptorIdx = uint32(-1); + } + + DeferredSRVCreateCount[frameIdx] = 0; +} + +void Initialize(D3D_FEATURE_LEVEL minFeatureLevel, uint32 adapterIdx) +{ + ShuttingDown = false; + + HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(&Factory)); + if(FAILED(hr)) + throw Exception(L"Unable to create a DXGI 1.4 device.\n " + L"Make sure that your OS and driver support DirectX 12"); + + LARGE_INTEGER umdVersion = { }; + Factory->EnumAdapters1(adapterIdx, &Adapter); + + if(Adapter == nullptr) + throw Exception(L"Unable to locate a DXGI 1.4 adapter that supports a D3D12 device.\n" + L"Make sure that your OS and driver support DirectX 12"); + + DXGI_ADAPTER_DESC1 desc = { }; + Adapter->GetDesc1(&desc); + WriteLog("Creating DX12 device on adapter '%ls'", desc.Description); + + #if UseDebugDevice_ + ID3D12DebugPtr d3d12debug; + DXCall(D3D12GetDebugInterface(IID_PPV_ARGS(&d3d12debug))); + d3d12debug->EnableDebugLayer(); + + #if UseGPUValidation_ + ID3D12Debug1Ptr debug1; + d3d12debug->QueryInterface(IID_PPV_ARGS(&debug1)); + debug1->SetEnableGPUBasedValidation(true); + #endif + #endif + + #if EnableShaderModel6_ && 0 + // Enable experimental shader models + DXCall(D3D12EnableExperimentalFeatures(1, &D3D12ExperimentalShaderModels, nullptr, nullptr)); + #endif + + DXCall(D3D12CreateDevice(Adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&Device))); + + // Check the maximum feature level, and make sure it's above our minimum + D3D_FEATURE_LEVEL featureLevelsArray[4]; + featureLevelsArray[0] = D3D_FEATURE_LEVEL_11_0; + featureLevelsArray[1] = D3D_FEATURE_LEVEL_11_1; + featureLevelsArray[2] = D3D_FEATURE_LEVEL_12_0; + featureLevelsArray[3] = D3D_FEATURE_LEVEL_12_1; + D3D12_FEATURE_DATA_FEATURE_LEVELS featureLevels = { }; + featureLevels.NumFeatureLevels = ArraySize_(featureLevelsArray); + featureLevels.pFeatureLevelsRequested = featureLevelsArray; + DXCall(Device->CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS, &featureLevels, sizeof(featureLevels))); + FeatureLevel = featureLevels.MaxSupportedFeatureLevel; + + if(FeatureLevel < minFeatureLevel) + { + std::wstring majorLevel = ToString(minFeatureLevel >> 12); + std::wstring minorLevel = ToString((minFeatureLevel >> 8) & 0xF); + throw Exception(L"The device doesn't support the minimum feature level required to run this sample (DX" + majorLevel + L"." + minorLevel + L")"); + } + + #if UseDebugDevice_ + ID3D12InfoQueuePtr infoQueue; + DXCall(Device->QueryInterface(IID_PPV_ARGS(&infoQueue))); + + D3D12_MESSAGE_ID disabledMessages[] = + { + D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE, + + // These happen when capturing with VS diagnostics + D3D12_MESSAGE_ID_MAP_INVALID_NULLRANGE, + D3D12_MESSAGE_ID_UNMAP_INVALID_NULLRANGE, + }; + + D3D12_INFO_QUEUE_FILTER filter = { }; + filter.DenyList.NumIDs = ArraySize_(disabledMessages); + filter.DenyList.pIDList = disabledMessages; + infoQueue->AddStorageFilterEntries(&filter); + #endif + + #if BreakOnDXError_ + infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, TRUE); + infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, TRUE); + #endif + + for(uint64 i = 0; i < NumCmdAllocators; ++i) + DXCall(Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&CmdAllocators[i]))); + + DXCall(Device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, CmdAllocators[0], nullptr, IID_PPV_ARGS(&CmdList))); + DXCall(CmdList->Close()); + CmdList->SetName(L"Primary Graphics Command List"); + + D3D12_COMMAND_QUEUE_DESC queueDesc = {}; + queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; + queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + DXCall(Device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&GfxQueue))); + GfxQueue->SetName(L"Main Gfx Queue"); + + CurrFrameIdx = CurrentCPUFrame % NumCmdAllocators; + DXCall(CmdAllocators[CurrFrameIdx]->Reset()); + DXCall(CmdList->Reset(CmdAllocators[CurrFrameIdx], nullptr)); + + FrameFence.Init(0); + + for(uint64 i = 0; i < ArraySize_(DeferredSRVCreates); ++i) + DeferredSRVCreates[i].Init(1024); + + Initialize_Helpers(); + Initialize_Upload(); +} + +void Shutdown() +{ + Assert_(CurrentCPUFrame == CurrentGPUFrame); + ShuttingDown = true; + + for(uint64 i = 0; i < ArraySize_(DeferredReleases); ++i) + ProcessDeferredReleases(i); + + FrameFence.Shutdown(); + + for(uint64 i = 0; i < RenderLatency; ++i) + Release(CmdAllocators[i]); + + Release(CmdList); + Release(GfxQueue); + Release(Factory); + Release(Adapter); + + Shutdown_Helpers(); + Shutdown_Upload(); + + #if BreakOnDXError_ + if(Device != nullptr) + { + ID3D12InfoQueuePtr infoQueue; + DXCall(Device->QueryInterface(IID_PPV_ARGS(&infoQueue))); + infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, FALSE); + infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, FALSE); + } + #endif + + #if UseDebugDevice_ && 0 + if(Device != nullptr) + { + ID3D12DebugDevicePtr debugDevice; + DXCall(Device->QueryInterface(IID_PPV_ARGS(&debugDevice))); + debugDevice->ReportLiveDeviceObjects(D3D12_RLDO_DETAIL); + } + #endif + + Release(Device); +} + +void BeginFrame() +{ + Assert_(Device); + + SetDescriptorHeaps(CmdList); +} + +void EndFrame(IDXGISwapChain4* swapChain, uint32 syncIntervals) +{ + Assert_(Device); + + DXCall(CmdList->Close()); + + EndFrame_Upload(); + + ID3D12CommandList* commandLists[] = { CmdList }; + GfxQueue->ExecuteCommandLists(ArraySize_(commandLists), commandLists); + + // Present the frame. + if(swapChain) + DXCall(swapChain->Present(syncIntervals, syncIntervals == 0 ? DXGI_PRESENT_ALLOW_TEARING : 0)); + + ++CurrentCPUFrame; + + // Signal the fence with the current frame number, so that we can check back on it + FrameFence.Signal(GfxQueue, CurrentCPUFrame); + + // Wait for the GPU to catch up before we stomp an executing command buffer + const uint64 gpuLag = DX12::CurrentCPUFrame - DX12::CurrentGPUFrame; + Assert_(gpuLag <= DX12::RenderLatency); + if(gpuLag >= DX12::RenderLatency) + { + // Make sure that the previous frame is finished + FrameFence.Wait(DX12::CurrentGPUFrame + 1); + ++DX12::CurrentGPUFrame; + } + + CurrFrameIdx = DX12::CurrentCPUFrame % NumCmdAllocators; + + // Prepare the command buffers to be used for the next frame + DXCall(CmdAllocators[CurrFrameIdx]->Reset()); + DXCall(CmdList->Reset(CmdAllocators[CurrFrameIdx], nullptr)); + + EndFrame_Helpers(); + + // See if we have any deferred releases to process + ProcessDeferredReleases(CurrFrameIdx); + + ProcessDeferredSRVCreates(CurrFrameIdx); +} + +void FlushGPU() +{ + Assert_(Device); + + // Wait for the GPU to fully catch up with the CPU + Assert_(CurrentCPUFrame >= CurrentGPUFrame); + if(CurrentCPUFrame > CurrentGPUFrame) + { + FrameFence.Wait(CurrentCPUFrame); + CurrentGPUFrame = CurrentCPUFrame; + } + + // Clean up what we can now + for(uint64 i = 1; i < RenderLatency; ++i) + { + uint64 frameIdx = (i + CurrFrameIdx) % RenderLatency; + ProcessDeferredReleases(frameIdx); + ProcessDeferredSRVCreates(frameIdx); + } +} + +void DeferredRelease_(IUnknown* resource) +{ + if(resource == nullptr) + return; + + if(ShuttingDown || Device == nullptr) + { + // Free-for-all! + resource->Release(); + return; + } + + DeferredReleases[CurrFrameIdx].Add(resource); +} + +void DeferredCreateSRV(ID3D12Resource* resource, const D3D12_SHADER_RESOURCE_VIEW_DESC& desc, uint32 descriptorIdx) +{ + for(uint64 i = 1; i < RenderLatency; ++i) + { + uint64 frameIdx = (CurrentCPUFrame + i) % RenderLatency; + uint64 writeIdx = InterlockedIncrement(&DeferredSRVCreateCount[frameIdx]) - 1; + DeferredSRVCreate& create = DeferredSRVCreates[frameIdx][writeIdx]; + create.Resource = resource; + create.Desc = desc; + create.DescriptorIdx = descriptorIdx; + } +} + +} // namespace SampleFramework12 + +} // namespace SampleFramework12 + diff --git a/SampleFramework12/v1.00/Graphics/DX12.h b/SampleFramework12/v1.01/Graphics/DX12.h similarity index 81% rename from SampleFramework12/v1.00/Graphics/DX12.h rename to SampleFramework12/v1.01/Graphics/DX12.h index ca4608a..371acdf 100644 --- a/SampleFramework12/v1.00/Graphics/DX12.h +++ b/SampleFramework12/v1.01/Graphics/DX12.h @@ -1,65 +1,67 @@ -//================================================================================================= -// -// MJP's DX12 Sample Framework -// http://mynameismjp.wordpress.com/ -// -// All code licensed under the MIT license -// -//================================================================================================= - -#pragma once - -#include "..\\PCH.h" - -namespace SampleFramework12 -{ - -namespace DX12 -{ - -// Constants -const uint64 RenderLatency = 2; - -// Externals -extern ID3D12Device* Device; -extern ID3D12GraphicsCommandList* CmdList; -extern ID3D12CommandQueue* GfxQueue; -extern D3D_FEATURE_LEVEL FeatureLevel; -extern IDXGIFactory4* Factory; -extern IDXGIAdapter1* Adapter; - -extern uint64 CurrentCPUFrame; // Total number of CPU frames completed (completed means all command buffers submitted to the GPU) -extern uint64 CurrentGPUFrame; // Total number of GPU frames completed (completed means that the GPU signals the fence) -extern uint64 CurrFrameIdx; // CurrentCPUFrame % RenderLatency - -// Lifetime -void Initialize(D3D_FEATURE_LEVEL minFeatureLevel = D3D_FEATURE_LEVEL_12_0); -void Shutdown(); - -// Frame submission synchronization -void BeginFrame(); -void EndFrame(IDXGISwapChain4* swapChain, uint32 syncIntervals); -void FlushGPU(); - -void DeferredRelease_(IUnknown* resource); - -template void DeferredRelease(T*& resource) -{ - IUnknown* base = resource; - DeferredRelease_(base); - resource = nullptr; -} - -template void Release(T*& resource) -{ - if(resource != nullptr) { - resource->Release(); - resource = nullptr; - } -} - -} // namespace DX12 - -} // namespace SampleFramework12 - - +//================================================================================================= +// +// MJP's DX12 Sample Framework +// http://mynameismjp.wordpress.com/ +// +// All code licensed under the MIT license +// +//================================================================================================= + +#pragma once + +#include "..\\PCH.h" + +namespace SampleFramework12 +{ + +namespace DX12 +{ + +// Constants +const uint64 RenderLatency = 2; + +// Externals +extern ID3D12Device2* Device; +extern ID3D12GraphicsCommandList1* CmdList; +extern ID3D12CommandQueue* GfxQueue; +extern D3D_FEATURE_LEVEL FeatureLevel; +extern IDXGIFactory4* Factory; +extern IDXGIAdapter1* Adapter; + +extern uint64 CurrentCPUFrame; // Total number of CPU frames completed (completed means all command buffers submitted to the GPU) +extern uint64 CurrentGPUFrame; // Total number of GPU frames completed (completed means that the GPU signals the fence) +extern uint64 CurrFrameIdx; // CurrentCPUFrame % RenderLatency + +// Lifetime +void Initialize(D3D_FEATURE_LEVEL minFeatureLevel, uint32 adapterIdx); +void Shutdown(); + +// Frame submission synchronization +void BeginFrame(); +void EndFrame(IDXGISwapChain4* swapChain, uint32 syncIntervals); +void FlushGPU(); + +void DeferredRelease_(IUnknown* resource); + +template void DeferredRelease(T*& resource) +{ + IUnknown* base = resource; + DeferredRelease_(base); + resource = nullptr; +} + +template void Release(T*& resource) +{ + if(resource != nullptr) { + resource->Release(); + resource = nullptr; + } +} + +void DeferredCreateSRV(ID3D12Resource* resource, const D3D12_SHADER_RESOURCE_VIEW_DESC& desc, uint32 descriptorIdx); + +} // namespace DX12 + +} // namespace SampleFramework12 + + diff --git a/SampleFramework12/v1.00/Graphics/DX12_Helpers.cpp b/SampleFramework12/v1.01/Graphics/DX12_Helpers.cpp similarity index 72% rename from SampleFramework12/v1.00/Graphics/DX12_Helpers.cpp rename to SampleFramework12/v1.01/Graphics/DX12_Helpers.cpp index 7eaa5fb..908ea4b 100644 --- a/SampleFramework12/v1.00/Graphics/DX12_Helpers.cpp +++ b/SampleFramework12/v1.01/Graphics/DX12_Helpers.cpp @@ -11,6 +11,7 @@ #include "DX12_Helpers.h" #include "DX12.h" +#include "DX12_Upload.h" #include "GraphicsTypes.h" namespace SampleFramework12 @@ -24,17 +25,13 @@ uint32 SRVDescriptorSize = 0; uint32 UAVDescriptorSize = 0; uint32 CBVDescriptorSize = 0; uint32 DSVDescriptorSize = 0; -uint32 SamplerDescriptorSize = 0; DescriptorHeap RTVDescriptorHeap; DescriptorHeap SRVDescriptorHeap; DescriptorHeap DSVDescriptorHeap; -DescriptorHeap SamplerDescriptorHeap; +DescriptorHeap UAVDescriptorHeap; -LinearDescriptorHeap SRVDescriptorHeapGPU[RenderLatency]; -LinearDescriptorHeap SamplerDescriptorHeapGPU[RenderLatency]; - -DescriptorHandle NullTexture2DSRV; +uint32 NullTexture2DSRV = uint32(-1); static const uint64 NumBlendStates = uint64(BlendState::NumValues); static const uint64 NumRasterizerStates = uint64(RasterizerState::NumValues); @@ -46,23 +43,21 @@ static D3D12_RASTERIZER_DESC RasterizerStateDescs[NumRasterizerStates] = { }; static D3D12_DEPTH_STENCIL_DESC DepthStateDescs[NumBlendStates] = { }; static D3D12_SAMPLER_DESC SamplerStateDescs[NumSamplerStates] = { }; +static D3D12_DESCRIPTOR_RANGE1 StandardDescriptorRangeDescs[NumStandardDescriptorRanges] = { }; + void Initialize_Helpers() { - RTVDescriptorHeap.Init(Device, 256, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, false); - SRVDescriptorHeap.Init(Device, 1024, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, false); - DSVDescriptorHeap.Init(Device, 256, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, false); - SamplerDescriptorHeap.Init(Device, 256, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, false); - - for(uint64 i = 0; i < RenderLatency; ++i) - { - SRVDescriptorHeapGPU[i].Init(Device, 1024, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, true); - SamplerDescriptorHeapGPU[i].Init(Device, 256, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, true); - } + RTVDescriptorHeap.Init(256, 0, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, false); + SRVDescriptorHeap.Init(1024, 1024, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, true); + DSVDescriptorHeap.Init(256, 0, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, false); + UAVDescriptorHeap.Init(256, 0, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, false); RTVDescriptorSize = RTVDescriptorHeap.DescriptorSize; SRVDescriptorSize = UAVDescriptorSize = CBVDescriptorSize = SRVDescriptorHeap.DescriptorSize; DSVDescriptorSize = DSVDescriptorHeap.DescriptorSize; - SamplerDescriptorSize = SamplerDescriptorHeap.DescriptorSize; + + // Standard descriptor ranges for binding to the arrays in DescriptorTables.hlsl + InsertStandardDescriptorRanges(StandardDescriptorRangeDescs); // Blend state initialization { @@ -368,31 +363,29 @@ void Initialize_Helpers() srvDesc.Texture2D.PlaneSlice = 0; srvDesc.Texture2D.ResourceMinLODClamp = 0.0f; - NullTexture2DSRV = SRVDescriptorHeap.Allocate(); - Device->CreateShaderResourceView(nullptr, &srvDesc, NullTexture2DSRV.CPUHandle); + PersistentDescriptorAlloc srvAlloc = SRVDescriptorHeap.AllocatePersistent(); + for(uint32 i = 0; i < SRVDescriptorHeap.NumHeaps; ++i) + Device->CreateShaderResourceView(nullptr, &srvDesc, srvAlloc.Handles[i]); + NullTexture2DSRV = srvAlloc.Index; } } void Shutdown_Helpers() { - SRVDescriptorHeap.Free(NullTexture2DSRV); + SRVDescriptorHeap.FreePersistent(NullTexture2DSRV); RTVDescriptorHeap.Shutdown(); SRVDescriptorHeap.Shutdown(); DSVDescriptorHeap.Shutdown(); - SamplerDescriptorHeap.Shutdown(); - - for(uint64 i = 0; i < RenderLatency; ++i) - { - SRVDescriptorHeapGPU[i].Shutdown(); - SamplerDescriptorHeapGPU[i].Shutdown(); - } + UAVDescriptorHeap.Shutdown(); } void EndFrame_Helpers() { - SRVDescriptorHeapGPU[CurrFrameIdx].Reset(); - SamplerDescriptorHeapGPU[CurrFrameIdx].Reset(); + RTVDescriptorHeap.EndFrame(); + SRVDescriptorHeap.EndFrame(); + DSVDescriptorHeap.EndFrame(); + UAVDescriptorHeap.EndFrame(); } void TransitionResource(ID3D12GraphicsCommandList* cmdList, ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after, uint32 subResource) @@ -579,57 +572,201 @@ void SetDescriptorHeaps(ID3D12GraphicsCommandList* cmdList) { ID3D12DescriptorHeap* heaps[] = { - SRVDescriptorHeapGPU[CurrFrameIdx].Heap, - SamplerDescriptorHeapGPU[CurrFrameIdx].Heap, + SRVDescriptorHeap.CurrentHeap(), }; cmdList->SetDescriptorHeaps(ArraySize_(heaps), heaps); } -DescriptorHandle MakeDescriptorTable(uint64 count, const D3D12_CPU_DESCRIPTOR_HANDLE* handles, ShaderResourceType srType) +D3D12_GPU_DESCRIPTOR_HANDLE TempDescriptorTable(const D3D12_CPU_DESCRIPTOR_HANDLE* handles, uint64 count) { Assert_(count <= MaxBindCount); Assert_(count > 0); - LinearDescriptorHeap& heap = srType == ShaderResourceType::SRV_UAV_CBV ? SRVDescriptorHeapGPU[CurrFrameIdx] - : SamplerDescriptorHeapGPU[CurrFrameIdx]; - - DescriptorHandle tableStart = heap.Allocate(count); + TempDescriptorAlloc tempAlloc = SRVDescriptorHeap.AllocateTemporary(uint32(count)); uint32 destRanges[1] = { uint32(count) }; - Device->CopyDescriptors(1, &tableStart.CPUHandle, destRanges, uint32(count), handles, DescriptorCopyRanges, heap.HeapType); + Device->CopyDescriptors(1, &tempAlloc.StartCPUHandle, destRanges, uint32(count), handles, DescriptorCopyRanges, SRVDescriptorHeap.HeapType); - return tableStart; + return tempAlloc.StartGPUHandle; } -void BindShaderResources(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter, uint64 count, - const D3D12_CPU_DESCRIPTOR_HANDLE* handles, CmdListMode cmdListMode, ShaderResourceType srType) +void BindTempDescriptorTable(ID3D12GraphicsCommandList* cmdList, const D3D12_CPU_DESCRIPTOR_HANDLE* handles, + uint64 count, uint32 rootParameter, CmdListMode cmdListMode) { - Assert_(count <= MaxBindCount); - Assert_(count > 0); + D3D12_GPU_DESCRIPTOR_HANDLE tempTable = TempDescriptorTable(handles, count); + + if(cmdListMode == CmdListMode::Graphics) + cmdList->SetGraphicsRootDescriptorTable(rootParameter, tempTable); + else + cmdList->SetComputeRootDescriptorTable(rootParameter, tempTable); +} + +TempBuffer TempConstantBuffer(uint64 cbSize, bool makeDescriptor) +{ + Assert_(cbSize > 0); + MapResult tempMem = DX12::AcquireTempBufferMem(cbSize, ConstantBufferAlignment); + TempBuffer tempBuffer; + tempBuffer.CPUAddress = tempMem.CPUAddress; + tempBuffer.GPUAddress = tempMem.GPUAddress; + if(makeDescriptor) + { + TempDescriptorAlloc cbvAlloc = SRVDescriptorHeap.AllocateTemporary(1); + D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc = { }; + cbvDesc.BufferLocation = tempMem.GPUAddress; + cbvDesc.SizeInBytes = uint32(AlignTo(cbSize, ConstantBufferAlignment)); + DX12::Device->CreateConstantBufferView(&cbvDesc, cbvAlloc.StartCPUHandle); + tempBuffer.DescriptorIndex = cbvAlloc.StartIndex; + } - DescriptorHandle tableStart = MakeDescriptorTable(count, handles, srType); + return tempBuffer; +} + +void BindTempConstantBuffer(ID3D12GraphicsCommandList* cmdList, const void* cbData, uint64 cbSize, uint32 rootParameter, CmdListMode cmdListMode) +{ + TempBuffer tempBuffer = TempConstantBuffer(cbSize, false); + memcpy(tempBuffer.CPUAddress, cbData, cbSize); if(cmdListMode == CmdListMode::Graphics) - cmdList->SetGraphicsRootDescriptorTable(rootParameter, tableStart.GPUHandle); + cmdList->SetGraphicsRootConstantBufferView(rootParameter, tempBuffer.GPUAddress); else - cmdList->SetComputeRootDescriptorTable(rootParameter, tableStart.GPUHandle); + cmdList->SetComputeRootConstantBufferView(rootParameter, tempBuffer.GPUAddress); } -void BindShaderResources(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter, uint64 count, - const DescriptorHandle* handles, CmdListMode cmdListMode, ShaderResourceType srType) +TempBuffer TempStructuredBuffer(uint64 numElements, uint64 stride, bool makeDescriptor) { - Assert_(count <= MaxBindCount); - Assert_(count > 0); - D3D12_CPU_DESCRIPTOR_HANDLE d3dHandles[MaxBindCount]; - for(uint64 i = 0; i < count; ++i) + Assert_(numElements > 0); + Assert_(stride > 0); + Assert_(stride % 4 == 0); + + MapResult tempMem = DX12::AcquireTempBufferMem(numElements * stride, stride); + Assert_(tempMem.ResourceOffset % stride == 0); + + TempBuffer result; + result.CPUAddress = tempMem.CPUAddress; + result.GPUAddress = tempMem.GPUAddress; + + if(makeDescriptor) { - Assert_(handles[i].IsValid()); - Assert_(handles[i].ShaderVisible() == false); - d3dHandles[i] = handles[i].CPUHandle; + TempDescriptorAlloc srvAlloc = SRVDescriptorHeap.AllocateTemporary(1); + + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; + srvDesc.Format = DXGI_FORMAT_UNKNOWN; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srvDesc.Buffer.FirstElement = uint32(tempMem.ResourceOffset / stride); + srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; + srvDesc.Buffer.NumElements = uint32(numElements); + srvDesc.Buffer.StructureByteStride = uint32(stride); + DX12::Device->CreateShaderResourceView(tempMem.Resource, &srvDesc, srvAlloc.StartCPUHandle); + + result.DescriptorIndex = srvAlloc.StartIndex; } - BindShaderResources(cmdList, rootParameter, count, d3dHandles, cmdListMode, srType); + return result; +} + +TempBuffer TempFormattedBuffer(uint64 numElements, DXGI_FORMAT format, bool makeDescriptor) +{ + Assert_(format != DXGI_FORMAT_UNKNOWN); + Assert_(numElements > 0); + uint64 stride = DirectX::BitsPerPixel(format) / 8; + + MapResult tempMem = DX12::AcquireTempBufferMem(numElements * stride, stride); + Assert_(tempMem.ResourceOffset % stride == 0); + + TempBuffer result; + result.CPUAddress = tempMem.CPUAddress; + result.GPUAddress = tempMem.GPUAddress; + + if(makeDescriptor) + { + TempDescriptorAlloc srvAlloc = SRVDescriptorHeap.AllocateTemporary(1); + + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { }; + srvDesc.Format = format; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srvDesc.Buffer.FirstElement = uint32(tempMem.ResourceOffset / stride); + srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; + srvDesc.Buffer.NumElements = uint32(numElements); + DX12::Device->CreateShaderResourceView(tempMem.Resource, &srvDesc, srvAlloc.StartCPUHandle); + + result.DescriptorIndex = srvAlloc.StartIndex; + } + + return result; +} + +TempBuffer TempRawBuffer(uint64 numElements, bool makeDescriptor) +{ + Assert_(numElements > 0); + const uint64 stride = 4; + + MapResult tempMem = DX12::AcquireTempBufferMem(numElements * stride, stride); + Assert_(tempMem.ResourceOffset % stride == 0); + + TempBuffer result; + result.CPUAddress = tempMem.CPUAddress; + + if(makeDescriptor) + { + TempDescriptorAlloc srvAlloc = SRVDescriptorHeap.AllocateTemporary(1); + + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { }; + srvDesc.Format = DXGI_FORMAT_R32_TYPELESS; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srvDesc.Buffer.FirstElement = uint32(tempMem.ResourceOffset / stride); + srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + srvDesc.Buffer.NumElements = uint32(numElements); + DX12::Device->CreateShaderResourceView(tempMem.Resource, &srvDesc, srvAlloc.StartCPUHandle); + + result.DescriptorIndex = srvAlloc.StartIndex; + } + + return result; +} + +const D3D12_DESCRIPTOR_RANGE1* StandardDescriptorRanges() +{ + Assert_(SRVDescriptorSize != 0); + return StandardDescriptorRangeDescs; +} + +void InsertStandardDescriptorRanges(D3D12_DESCRIPTOR_RANGE1* ranges) +{ + uint32 userStart = NumStandardDescriptorRanges - NumUserDescriptorRanges; + for(uint32 i = 0; i < NumStandardDescriptorRanges; ++i) + { + StandardDescriptorRangeDescs[i].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + StandardDescriptorRangeDescs[i].NumDescriptors = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + StandardDescriptorRangeDescs[i].BaseShaderRegister = 0; + StandardDescriptorRangeDescs[i].RegisterSpace = i; + StandardDescriptorRangeDescs[i].OffsetInDescriptorsFromTableStart = 0; + StandardDescriptorRangeDescs[i].Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE; + if(i >= userStart) + StandardDescriptorRangeDescs[i].RegisterSpace = (i - userStart) + 100; + } +} + +void BindAsDescriptorTable(ID3D12GraphicsCommandList* cmdList, uint32 descriptorIdx, uint32 rootParameter, CmdListMode cmdListMode) +{ + Assert_(descriptorIdx != uint32(-1)); + D3D12_GPU_DESCRIPTOR_HANDLE handle = SRVDescriptorHeap.GPUHandleFromIndex(descriptorIdx); + if(cmdListMode == CmdListMode::Compute) + cmdList->SetComputeRootDescriptorTable(rootParameter, handle); + else + cmdList->SetGraphicsRootDescriptorTable(rootParameter, handle); +} + +void BindStandardDescriptorTable(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter, CmdListMode cmdListMode) +{ + D3D12_GPU_DESCRIPTOR_HANDLE handle = SRVDescriptorHeap.GPUStart[SRVDescriptorHeap.HeapIndex]; + if(cmdListMode == CmdListMode::Compute) + cmdList->SetComputeRootDescriptorTable(rootParameter, handle); + else + cmdList->SetGraphicsRootDescriptorTable(rootParameter, handle); } } // namespace DX12 diff --git a/SampleFramework12/v1.00/Graphics/DX12_Helpers.h b/SampleFramework12/v1.01/Graphics/DX12_Helpers.h similarity index 63% rename from SampleFramework12/v1.00/Graphics/DX12_Helpers.h rename to SampleFramework12/v1.01/Graphics/DX12_Helpers.h index 4ccadd5..4de8c52 100644 --- a/SampleFramework12/v1.00/Graphics/DX12_Helpers.h +++ b/SampleFramework12/v1.01/Graphics/DX12_Helpers.h @@ -74,13 +74,19 @@ enum class CmdListMode : uint64 { Graphics = 0, Compute, - Copy, }; -enum class ShaderResourceType : uint64 +struct TempDescriptorTable { - SRV_UAV_CBV = 0, - Sampler, + D3D12_CPU_DESCRIPTOR_HANDLE CPUStart; + D3D12_GPU_DESCRIPTOR_HANDLE GPUStart; +}; + +struct TempBuffer +{ + void* CPUAddress = nullptr; + uint64 GPUAddress = 0; + uint32 DescriptorIndex = uint32(-1); }; namespace DX12 @@ -98,17 +104,16 @@ extern uint32 SRVDescriptorSize; extern uint32 UAVDescriptorSize; extern uint32 CBVDescriptorSize; extern uint32 DSVDescriptorSize; -extern uint32 SamplerDescriptorSize; extern DescriptorHeap RTVDescriptorHeap; extern DescriptorHeap SRVDescriptorHeap; extern DescriptorHeap DSVDescriptorHeap; -extern DescriptorHeap SamplerDescriptorHeap; +extern DescriptorHeap UAVDescriptorHeap; -extern LinearDescriptorHeap SRVDescriptorHeapGPU[RenderLatency]; -extern LinearDescriptorHeap SamplerDescriptorHeapGPU[RenderLatency]; +extern uint32 NullTexture2DSRV; -extern DescriptorHandle NullTexture2DSRV; +const uint32 NumUserDescriptorRanges = 16; +const uint32 NumStandardDescriptorRanges = 7 + NumUserDescriptorRanges; // Lifetime void Initialize_Helpers(); @@ -146,14 +151,33 @@ uint32 DispatchSize(uint64 numElements, uint64 groupSize); // Resource binding void SetDescriptorHeaps(ID3D12GraphicsCommandList* cmdList); -DescriptorHandle MakeDescriptorTable(uint64 count, const D3D12_CPU_DESCRIPTOR_HANDLE* handles, - ShaderResourceType srType = ShaderResourceType::SRV_UAV_CBV); -void BindShaderResources(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter, uint64 count, - const D3D12_CPU_DESCRIPTOR_HANDLE* handles, CmdListMode cmdListMode = CmdListMode::Graphics, - ShaderResourceType srType = ShaderResourceType::SRV_UAV_CBV); -void BindShaderResources(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter, uint64 count, - const DescriptorHandle* handles, CmdListMode cmdListMode = CmdListMode::Graphics, - ShaderResourceType srType = ShaderResourceType::SRV_UAV_CBV); +D3D12_GPU_DESCRIPTOR_HANDLE TempDescriptorTable(const D3D12_CPU_DESCRIPTOR_HANDLE* handles, uint64 count); +void BindTempDescriptorTable(ID3D12GraphicsCommandList* cmdList, const D3D12_CPU_DESCRIPTOR_HANDLE* handles, + uint64 count, uint32 rootParameter, CmdListMode cmdListMode); + +// Helpers for buffer types that use temporary buffer memory from the upload helper +TempBuffer TempConstantBuffer(uint64 cbSize, bool makeDescriptor = false); +void BindTempConstantBuffer(ID3D12GraphicsCommandList* cmdList, const void* cbData, uint64 cbSize, uint32 rootParameter, CmdListMode cmdListMode); + +template void BindTempConstantBuffer(ID3D12GraphicsCommandList* cmdList, const T& cbData, uint32 rootParameter, CmdListMode cmdListMode) +{ + BindTempConstantBuffer(cmdList, &cbData, sizeof(T), rootParameter, cmdListMode); +} + +template void BindTempConstantBuffer(ID3D12GraphicsCommandList* cmdList, const uint32 (&cbData)[N], uint32 rootParameter, CmdListMode cmdListMode) +{ + BindTempConstantBuffer(cmdList, cbData, N * sizeof(uint32), rootParameter, cmdListMode); +} + +TempBuffer TempStructuredBuffer(uint64 numElements, uint64 stride, bool makeDescriptor = true); +TempBuffer TempFormattedBuffer(uint64 numElements, DXGI_FORMAT format, bool makeDescriptor = true); +TempBuffer TempRawBuffer(uint64 numElements, bool makeDescriptor = true); + +const D3D12_DESCRIPTOR_RANGE1* StandardDescriptorRanges(); +void InsertStandardDescriptorRanges(D3D12_DESCRIPTOR_RANGE1* ranges); + +void BindAsDescriptorTable(ID3D12GraphicsCommandList* cmdList, uint32 descriptorIdx, uint32 rootParameter, CmdListMode cmdListMode); +void BindStandardDescriptorTable(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter, CmdListMode cmdListMode); } // namespace DX12 diff --git a/SampleFramework12/v1.00/Graphics/DX12_Upload.cpp b/SampleFramework12/v1.01/Graphics/DX12_Upload.cpp similarity index 66% rename from SampleFramework12/v1.00/Graphics/DX12_Upload.cpp rename to SampleFramework12/v1.01/Graphics/DX12_Upload.cpp index ce58b06..6d0f23a 100644 --- a/SampleFramework12/v1.00/Graphics/DX12_Upload.cpp +++ b/SampleFramework12/v1.01/Graphics/DX12_Upload.cpp @@ -20,7 +20,34 @@ namespace SampleFramework12 namespace DX12 { -static ID3D12GraphicsCommandList* convertCmdList = nullptr; +enum ConvertRootParams : uint32 +{ + ConvertParams_StandardDescriptors = 0, + ConvertParams_UAV, + ConvertParams_SRVIndex, + + NumConvertRootParams +}; + +struct UploadSubmission +{ + ID3D12CommandAllocator* CmdAllocator = nullptr; + ID3D12GraphicsCommandList1* CmdList = nullptr; + uint64 Offset = 0; + uint64 Size = 0; + uint64 FenceValue = 0; + uint64 Padding = 0; + + void Reset() + { + Offset = 0; + Size = 0; + FenceValue = 0; + Padding = 0; + } +}; + +static ID3D12GraphicsCommandList1* convertCmdList = nullptr; static ID3D12CommandQueue* convertCmdQueue = nullptr; static ID3D12CommandAllocator* convertCmdAllocator = nullptr; static ID3D12RootSignature* convertRootSignature = nullptr; @@ -31,38 +58,25 @@ static CompiledShaderPtr convertArrayCS; static uint32 convertTGSize = 16; static Fence convertFence; -static ID3D12GraphicsCommandList* readbackCmdList = nullptr; +static ID3D12GraphicsCommandList1* readbackCmdList = nullptr; static ID3D12CommandAllocator* readbackCmdAllocator = nullptr; static Fence readbackFence; static const uint64 UploadBufferSize = 32 * 1024 * 1024; static const uint64 MaxUploadSubmissions = 16; -static ID3D12GraphicsCommandList* UploadCmdList = nullptr; -static ID3D12CommandQueue* UploadCmdQueue = nullptr; static ID3D12Resource* UploadBuffer = nullptr; static uint8* UploadBufferCPUAddr = nullptr; -static uint64 UploadBufferStart = 0; -static uint64 UploadBufferUsed = 0; +static SRWLOCK UploadSubmissionLock = SRWLOCK_INIT; +static SRWLOCK UploadQueueLock = SRWLOCK_INIT; + +// These are protected by UploadQueueLock +static ID3D12CommandQueue* UploadCmdQueue = nullptr; static Fence UploadFence; static uint64 UploadFenceValue = 0; -struct UploadSubmission -{ - ID3D12CommandAllocator* CmdAllocator = nullptr; - uint64 Offset = 0; - uint64 Size = 0; - uint64 FenceValue = uint64(-1); - uint64 Padding = 0; - - void Reset() - { - Offset = 0; - Size = 0; - FenceValue = uint64(-1); - Padding = 0; - } -}; - +// These are protected by UploadSubmissionLock +static uint64 UploadBufferStart = 0; +static uint64 UploadBufferUsed = 0; static UploadSubmission UploadSubmissions[MaxUploadSubmissions]; static uint64 UploadSubmissionStart = 0; static uint64 UploadSubmissionUsed = 0; @@ -71,7 +85,7 @@ static const uint64 TempBufferSize = 2 * 1024 * 1024; static ID3D12Resource* TempFrameBuffers[RenderLatency] = { }; static uint8* TempFrameCPUMem[RenderLatency] = { }; static uint64 TempFrameGPUMem[RenderLatency] = { }; -static uint64 TempFrameUsed = 0; +static volatile int64 TempFrameUsed = 0; static void ClearFinishedUploads(uint64 flushCount) { @@ -82,9 +96,12 @@ static void ClearFinishedUploads(uint64 flushCount) const uint64 idx = (start + i) % MaxUploadSubmissions; UploadSubmission& submission = UploadSubmissions[idx]; Assert_(submission.Size > 0); - Assert_(submission.FenceValue != uint64(-1)); Assert_(UploadBufferUsed >= submission.Size); + // If the submission hasn't been sent to the GPU yet we can't wait for it + if(submission.FenceValue == uint64(-1)) + return; + if(i < flushCount) UploadFence.Wait(submission.FenceValue); @@ -102,21 +119,25 @@ static void ClearFinishedUploads(uint64 flushCount) if(UploadBufferUsed == 0) UploadBufferStart = 0; } + else + { + return; + } } } -static bool AllocUploadSubmission(uint64 size) +static UploadSubmission* AllocUploadSubmission(uint64 size) { Assert_(UploadSubmissionUsed <= MaxUploadSubmissions); if(UploadSubmissionUsed == MaxUploadSubmissions) - return false; + return nullptr; const uint64 submissionIdx = (UploadSubmissionStart + UploadSubmissionUsed) % MaxUploadSubmissions; Assert_(UploadSubmissions[submissionIdx].Size == 0); Assert_(UploadBufferUsed <= UploadBufferSize); if(size > (UploadBufferSize - UploadBufferUsed)) - return false; + return nullptr; const uint64 start = UploadBufferStart; const uint64 end = UploadBufferStart + UploadBufferUsed; @@ -145,33 +166,34 @@ static bool AllocUploadSubmission(uint64 size) } if(allocOffset == uint64(-1)) - return false; + return nullptr; UploadSubmissionUsed += 1; UploadBufferUsed += size; - ++UploadFenceValue; + UploadSubmission* submission = &UploadSubmissions[submissionIdx]; + submission->Offset = allocOffset; + submission->Size = size; + submission->FenceValue = uint64(-1); + submission->Padding = padding; - UploadSubmissions[submissionIdx].Offset = allocOffset; - UploadSubmissions[submissionIdx].Size = size; - UploadSubmissions[submissionIdx].FenceValue = UploadFenceValue; - UploadSubmissions[submissionIdx].Padding = padding; - - return true; + return submission; } void Initialize_Upload() { - for(uint64 i = 0; i < MaxUploadSubmissions; ++i) - DXCall(Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY, IID_PPV_ARGS(&UploadSubmissions[i].CmdAllocator))); - - DXCall(Device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, UploadSubmissions[0].CmdAllocator, nullptr, IID_PPV_ARGS(&UploadCmdList))); - DXCall(UploadCmdList->Close()); + for(uint64 i = 0; i < MaxUploadSubmissions; ++i) { + UploadSubmission& submission = UploadSubmissions[i]; + DXCall(Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY, IID_PPV_ARGS(&submission.CmdAllocator))); + DXCall(Device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, submission.CmdAllocator, nullptr, IID_PPV_ARGS(&submission.CmdList))); + DXCall(submission.CmdList->Close()); + } D3D12_COMMAND_QUEUE_DESC queueDesc = { }; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_COPY; DXCall(Device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&UploadCmdQueue))); + UploadCmdQueue->SetName(L"Upload Copy Queue"); UploadFence.Init(0); @@ -220,28 +242,33 @@ void Initialize_Upload() CompileOptions opts; opts.Add("TGSize_", convertTGSize); const std::wstring shaderPath = SampleFrameworkDir() + L"Shaders\\DecodeTextureCS.hlsl"; - convertCS = CompileFromFile(shaderPath.c_str(), "DecodeTextureCS", ShaderType::Compute, ShaderProfile::SM51, opts); - convertArrayCS = CompileFromFile(shaderPath.c_str(), "DecodeTextureArrayCS", ShaderType::Compute, ShaderProfile::SM51, opts); + convertCS = CompileFromFile(shaderPath.c_str(), "DecodeTextureCS", ShaderType::Compute, opts); + convertArrayCS = CompileFromFile(shaderPath.c_str(), "DecodeTextureArrayCS", ShaderType::Compute, opts); { - D3D12_DESCRIPTOR_RANGE1 ranges[2] = {}; - ranges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - ranges[0].NumDescriptors = 1; - ranges[0].BaseShaderRegister = 0; - ranges[0].RegisterSpace = 0; - ranges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - ranges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; - ranges[1].NumDescriptors = 1; - ranges[1].BaseShaderRegister = 0; - ranges[1].RegisterSpace = 0; - ranges[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - D3D12_ROOT_PARAMETER1 rootParameters[1] = {}; - rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[0].DescriptorTable.pDescriptorRanges = ranges; - rootParameters[0].DescriptorTable.NumDescriptorRanges = ArraySize_(ranges); + D3D12_DESCRIPTOR_RANGE1 uavRanges[1] = {}; + uavRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; + uavRanges[0].NumDescriptors = 1; + uavRanges[0].BaseShaderRegister = 0; + uavRanges[0].RegisterSpace = 0; + uavRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + + D3D12_ROOT_PARAMETER1 rootParameters[NumConvertRootParams] = {}; + rootParameters[ConvertParams_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[ConvertParams_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[ConvertParams_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[ConvertParams_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + rootParameters[ConvertParams_UAV].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[ConvertParams_UAV].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[ConvertParams_UAV].DescriptorTable.pDescriptorRanges = uavRanges; + rootParameters[ConvertParams_UAV].DescriptorTable.NumDescriptorRanges = ArraySize_(uavRanges); + + rootParameters[ConvertParams_SRVIndex].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + rootParameters[ConvertParams_SRVIndex].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[ConvertParams_SRVIndex].Constants.Num32BitValues = 1; + rootParameters[ConvertParams_SRVIndex].Constants.RegisterSpace = 0; + rootParameters[ConvertParams_SRVIndex].Constants.ShaderRegister = 0; D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; rootSignatureDesc.NumParameters = ArraySize_(rootParameters); @@ -278,12 +305,13 @@ void Shutdown_Upload() for(uint64 i = 0; i < ArraySize_(TempFrameBuffers); ++i) Release(TempFrameBuffers[i]); - Release(UploadCmdList); Release(UploadBuffer); Release(UploadCmdQueue); UploadFence.Shutdown(); - for(uint64 i = 0; i < MaxUploadSubmissions; ++i) + for(uint64 i = 0; i < MaxUploadSubmissions; ++i) { Release(UploadSubmissions[i].CmdAllocator); + Release(UploadSubmissions[i].CmdList); + } Release(convertCmdAllocator); Release(convertCmdList); @@ -300,9 +328,23 @@ void Shutdown_Upload() void EndFrame_Upload() { - // Make sure to sync on any pending uploads - ClearFinishedUploads(0); - GfxQueue->Wait(UploadFence.D3DFence, UploadFenceValue); + // If we can grab the lock, try to clear out any completed submissions + if(TryAcquireSRWLockExclusive(&UploadSubmissionLock)) + { + ClearFinishedUploads(0); + + ReleaseSRWLockExclusive(&UploadSubmissionLock); + } + + { + AcquireSRWLockExclusive(&UploadQueueLock); + + // Make sure to sync on any pending uploads + ClearFinishedUploads(0); + GfxQueue->Wait(UploadFence.D3DFence, UploadFenceValue); + + ReleaseSRWLockExclusive(&UploadQueueLock); + } TempFrameUsed = 0; } @@ -315,23 +357,32 @@ UploadContext ResourceUploadBegin(uint64 size) Assert_(size <= UploadBufferSize); Assert_(size > 0); - ClearFinishedUploads(0); - while(AllocUploadSubmission(size) == false) - ClearFinishedUploads(1); + UploadSubmission* submission = nullptr; + + { + AcquireSRWLockExclusive(&UploadSubmissionLock); - Assert_(UploadSubmissionUsed > 0); - const uint64 submissionIdx = (UploadSubmissionStart + (UploadSubmissionUsed - 1)) % MaxUploadSubmissions; - UploadSubmission& submission = UploadSubmissions[submissionIdx]; - Assert_(submission.Size == size); + ClearFinishedUploads(0); - DXCall(submission.CmdAllocator->Reset()); - DXCall(UploadCmdList->Reset(submission.CmdAllocator, nullptr)); + submission = AllocUploadSubmission(size); + while(submission == nullptr) + { + ClearFinishedUploads(1); + submission = AllocUploadSubmission(size); + } + + ReleaseSRWLockExclusive(&UploadSubmissionLock); + } + + DXCall(submission->CmdAllocator->Reset()); + DXCall(submission->CmdList->Reset(submission->CmdAllocator, nullptr)); UploadContext context; - context.CmdList = UploadCmdList; + context.CmdList = submission->CmdList; context.Resource = UploadBuffer; - context.CPUAddress = UploadBufferCPUAddr + submission.Offset; - context.ResourceOffset = submission.Offset; + context.CPUAddress = UploadBufferCPUAddr + submission->Offset; + context.ResourceOffset = submission->Offset; + context.Submission = submission; return context; } @@ -339,34 +390,41 @@ UploadContext ResourceUploadBegin(uint64 size) void ResourceUploadEnd(UploadContext& context) { Assert_(context.CmdList != nullptr); + Assert_(context.Submission != nullptr); + UploadSubmission* submission = reinterpret_cast(context.Submission); + + { + AcquireSRWLockExclusive(&UploadQueueLock); + + // Finish off and execute the command list + DXCall(submission->CmdList->Close()); + ID3D12CommandList* cmdLists[1] = { submission->CmdList }; + UploadCmdQueue->ExecuteCommandLists(1, cmdLists); - // Finish off and execute the command list - DXCall(UploadCmdList->Close()); - ID3D12CommandList* cmdLists[1] = { UploadCmdList }; - UploadCmdQueue->ExecuteCommandLists(1, cmdLists); + ++UploadFenceValue; + UploadFence.Signal(UploadCmdQueue, UploadFenceValue); + submission->FenceValue = UploadFenceValue; - Assert_(UploadSubmissionUsed > 0); - const uint64 submissionIdx = (UploadSubmissionStart + (UploadSubmissionUsed - 1)) % MaxUploadSubmissions; - UploadSubmission& submission = UploadSubmissions[submissionIdx]; - Assert_(submission.Size != 0); - UploadFence.Signal(UploadCmdQueue, submission.FenceValue); + ReleaseSRWLockExclusive(&UploadQueueLock); + } context = UploadContext(); } MapResult AcquireTempBufferMem(uint64 size, uint64 alignment) { - TempFrameUsed = AlignTo(TempFrameUsed, alignment); - Assert_(TempFrameUsed + size <= TempBufferSize); + uint64 allocSize = size + alignment; + uint64 offset = InterlockedAdd64(&TempFrameUsed, allocSize) - allocSize; + if(alignment > 0) + offset = AlignTo(offset, alignment); + Assert_(offset + size <= TempBufferSize); MapResult result; - result.CPUAddress = TempFrameCPUMem[CurrFrameIdx] + TempFrameUsed; - result.GPUAddress = TempFrameGPUMem[CurrFrameIdx] + TempFrameUsed; - result.ResourceOffset = TempFrameUsed; + result.CPUAddress = TempFrameCPUMem[CurrFrameIdx] + offset; + result.GPUAddress = TempFrameGPUMem[CurrFrameIdx] + offset; + result.ResourceOffset = offset; result.Resource = TempFrameBuffers[CurrFrameIdx]; - TempFrameUsed += size; - return result; } @@ -381,7 +439,6 @@ void ConvertAndReadbackTexture(const Texture& texture, DXGI_FORMAT outputFormat, init.Format = outputFormat; init.NumElements = texture.Width * texture.Height * texture.ArraySize; init.CreateUAV = true; - init.InitialState = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; FormattedBuffer convertBuffer; convertBuffer.Initialize(init); @@ -391,8 +448,12 @@ void ConvertAndReadbackTexture(const Texture& texture, DXGI_FORMAT outputFormat, convertCmdList->SetComputeRootSignature(convertRootSignature); convertCmdList->SetPipelineState(texture.ArraySize > 1 ? convertArrayPSO : convertPSO); - D3D12_CPU_DESCRIPTOR_HANDLE descriptors[2] = { texture.SRV.CPUHandle, convertBuffer.UAV() }; - BindShaderResources(convertCmdList, 0, ArraySize_(descriptors), descriptors, CmdListMode::Compute, ShaderResourceType::SRV_UAV_CBV); + BindStandardDescriptorTable(convertCmdList, ConvertParams_StandardDescriptors, CmdListMode::Compute); + + D3D12_CPU_DESCRIPTOR_HANDLE uavs[] = { convertBuffer.UAV }; + BindTempDescriptorTable(convertCmdList, uavs, ArraySize_(uavs), ConvertParams_UAV, CmdListMode::Compute); + + convertCmdList->SetComputeRoot32BitConstant(ConvertParams_SRVIndex, texture.SRV, 0); uint32 dispatchX = DispatchSize(texture.Width, convertTGSize); uint32 dispatchY = DispatchSize(texture.Height, convertTGSize); @@ -441,4 +502,4 @@ void ConvertAndReadbackTexture(const Texture& texture, DXGI_FORMAT outputFormat, } // namespace DX12 -} // namespace SampleFramework12 \ No newline at end of file +} // namespace SampleFramework12 diff --git a/SampleFramework12/v1.00/Graphics/DX12_Upload.h b/SampleFramework12/v1.01/Graphics/DX12_Upload.h similarity index 97% rename from SampleFramework12/v1.00/Graphics/DX12_Upload.h rename to SampleFramework12/v1.01/Graphics/DX12_Upload.h index d1b6bc9..2ce6b26 100644 --- a/SampleFramework12/v1.00/Graphics/DX12_Upload.h +++ b/SampleFramework12/v1.01/Graphics/DX12_Upload.h @@ -28,6 +28,7 @@ struct UploadContext void* CPUAddress = nullptr; uint64 ResourceOffset = 0; ID3D12Resource* Resource = nullptr; + void* Submission = nullptr; }; struct ReadbackBuffer; diff --git a/SampleFramework12/v1.00/Graphics/DXErr.cpp b/SampleFramework12/v1.01/Graphics/DXErr.cpp similarity index 100% rename from SampleFramework12/v1.00/Graphics/DXErr.cpp rename to SampleFramework12/v1.01/Graphics/DXErr.cpp diff --git a/SampleFramework12/v1.00/Graphics/DXErr.h b/SampleFramework12/v1.01/Graphics/DXErr.h similarity index 100% rename from SampleFramework12/v1.00/Graphics/DXErr.h rename to SampleFramework12/v1.01/Graphics/DXErr.h diff --git a/SampleFramework12/v1.00/Graphics/Filtering.h b/SampleFramework12/v1.01/Graphics/Filtering.h similarity index 100% rename from SampleFramework12/v1.00/Graphics/Filtering.h rename to SampleFramework12/v1.01/Graphics/Filtering.h diff --git a/SampleFramework12/v1.01/Graphics/GraphicsTypes.cpp b/SampleFramework12/v1.01/Graphics/GraphicsTypes.cpp new file mode 100644 index 0000000..7451335 --- /dev/null +++ b/SampleFramework12/v1.01/Graphics/GraphicsTypes.cpp @@ -0,0 +1,1528 @@ +//================================================================================================= +// +// MJP's DX12 Sample Framework +// http://mynameismjp.wordpress.com/ +// +// All code licensed under the MIT license +// +//================================================================================================= + +#include "PCH.h" + +#include "GraphicsTypes.h" +#include "..\\Exceptions.h" +#include "..\\Utility.h" +#include "..\\Serialization.h" +#include "..\\FileIO.h" + +namespace SampleFramework12 +{ + +// == DescriptorHeap ============================================================================== + +DescriptorHeap::~DescriptorHeap() +{ + Assert_(Heaps[0] == nullptr); +} + +void DescriptorHeap::Init(uint32 numPersistent, uint32 numTemporary, D3D12_DESCRIPTOR_HEAP_TYPE heapType, bool shaderVisible) +{ + Shutdown(); + + uint32 totalNumDescriptors = numPersistent + numTemporary; + Assert_(totalNumDescriptors > 0); + + NumPersistent = numPersistent; + NumTemporary = numTemporary; + HeapType = heapType; + ShaderVisible = shaderVisible; + if(heapType == D3D12_DESCRIPTOR_HEAP_TYPE_RTV || heapType == D3D12_DESCRIPTOR_HEAP_TYPE_DSV) + ShaderVisible = false; + + NumHeaps = ShaderVisible ? 2 : 1; + + DeadList.Init(numPersistent); + for(uint32 i = 0; i < numPersistent; ++i) + DeadList[i] = uint32(i); + + D3D12_DESCRIPTOR_HEAP_DESC heapDesc = { }; + heapDesc.NumDescriptors = uint32(totalNumDescriptors); + heapDesc.Type = heapType; + heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; + if(ShaderVisible) + heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; + + for(uint32 i = 0; i < NumHeaps; ++i) + { + DXCall(DX12::Device->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&Heaps[i]))); + CPUStart[i] = Heaps[i]->GetCPUDescriptorHandleForHeapStart(); + if(ShaderVisible) + GPUStart[i] = Heaps[i]->GetGPUDescriptorHandleForHeapStart(); + } + + DescriptorSize = DX12::Device->GetDescriptorHandleIncrementSize(heapType); +} + +void DescriptorHeap::Shutdown() +{ + Assert_(PersistentAllocated == 0); + for(uint64 i = 0; i < ArraySize_(Heaps); ++i) + DX12::Release(Heaps[i]); +} + +PersistentDescriptorAlloc DescriptorHeap::AllocatePersistent() +{ + Assert_(Heaps[0] != nullptr); + + AcquireSRWLockExclusive(&Lock); + + Assert_(PersistentAllocated < NumPersistent); + uint32 idx = DeadList[PersistentAllocated]; + ++PersistentAllocated; + + ReleaseSRWLockExclusive(&Lock); + + PersistentDescriptorAlloc alloc; + alloc.Index = idx; + for(uint32 i = 0; i < NumHeaps; ++i) + { + alloc.Handles[i] = CPUStart[i]; + alloc.Handles[i].ptr += idx * DescriptorSize; + } + + return alloc; +} + +void DescriptorHeap::FreePersistent(uint32& idx) +{ + if(idx == uint32(-1)) + return; + + Assert_(idx < NumPersistent); + Assert_(Heaps[0] != nullptr); + + AcquireSRWLockExclusive(&Lock); + + Assert_(PersistentAllocated > 0); + DeadList[PersistentAllocated - 1] = idx; + --PersistentAllocated; + + ReleaseSRWLockExclusive(&Lock); + + idx = uint32(-1); +} + +void DescriptorHeap::FreePersistent(D3D12_CPU_DESCRIPTOR_HANDLE& handle) +{ + Assert_(NumHeaps == 1); + if(handle.ptr != 0) + { + uint32 idx = IndexFromHandle(handle); + FreePersistent(idx); + handle = { }; + } +} + +void DescriptorHeap::FreePersistent(D3D12_GPU_DESCRIPTOR_HANDLE& handle) +{ + Assert_(NumHeaps == 1); + if(handle.ptr != 0) + { + uint32 idx = IndexFromHandle(handle); + FreePersistent(idx); + handle = { }; + } +} + +TempDescriptorAlloc DescriptorHeap::AllocateTemporary(uint32 count) +{ + Assert_(Heaps[0] != nullptr); + Assert_(count > 0); + + uint32 tempIdx = uint32(InterlockedAdd64(&TemporaryAllocated, count)) - count; + Assert_(tempIdx < NumTemporary); + + uint32 finalIdx = tempIdx + NumPersistent; + + TempDescriptorAlloc alloc; + alloc.StartCPUHandle = CPUStart[HeapIndex]; + alloc.StartCPUHandle.ptr += finalIdx * DescriptorSize; + alloc.StartGPUHandle = GPUStart[HeapIndex]; + alloc.StartGPUHandle.ptr += finalIdx * DescriptorSize; + alloc.StartIndex = finalIdx; + + return alloc; +} + +void DescriptorHeap::EndFrame() +{ + Assert_(Heaps[0] != nullptr); + TemporaryAllocated = 0; + HeapIndex = (HeapIndex + 1) % NumHeaps; +} + +D3D12_CPU_DESCRIPTOR_HANDLE DescriptorHeap::CPUHandleFromIndex(uint32 descriptorIdx) const +{ + return CPUHandleFromIndex(descriptorIdx, HeapIndex); +} + +D3D12_GPU_DESCRIPTOR_HANDLE DescriptorHeap::GPUHandleFromIndex(uint32 descriptorIdx) const +{ + return GPUHandleFromIndex(descriptorIdx, HeapIndex); +} + +D3D12_CPU_DESCRIPTOR_HANDLE DescriptorHeap::CPUHandleFromIndex(uint32 descriptorIdx, uint64 heapIdx) const +{ + Assert_(Heaps[0] != nullptr); + Assert_(heapIdx < NumHeaps); + Assert_(descriptorIdx < TotalNumDescriptors()); + D3D12_CPU_DESCRIPTOR_HANDLE handle = CPUStart[heapIdx]; + handle.ptr += descriptorIdx * DescriptorSize; + return handle; +} + +D3D12_GPU_DESCRIPTOR_HANDLE DescriptorHeap::GPUHandleFromIndex(uint32 descriptorIdx, uint64 heapIdx) const +{ + Assert_(Heaps[0] != nullptr); + Assert_(heapIdx < NumHeaps); + Assert_(descriptorIdx < TotalNumDescriptors()); + Assert_(ShaderVisible); + D3D12_GPU_DESCRIPTOR_HANDLE handle = GPUStart[heapIdx]; + handle.ptr += descriptorIdx * DescriptorSize; + return handle; +} + +uint32 DescriptorHeap::IndexFromHandle(D3D12_CPU_DESCRIPTOR_HANDLE handle) +{ + Assert_(Heaps[0] != nullptr); + Assert_(handle.ptr >= CPUStart[HeapIndex].ptr); + Assert_(handle.ptr < CPUStart[HeapIndex].ptr + DescriptorSize * TotalNumDescriptors()); + Assert_((handle.ptr - CPUStart[HeapIndex].ptr) % DescriptorSize == 0); + return uint32(handle.ptr - CPUStart[HeapIndex].ptr) / DescriptorSize; +} + +uint32 DescriptorHeap::IndexFromHandle(D3D12_GPU_DESCRIPTOR_HANDLE handle) +{ + Assert_(Heaps[0] != nullptr); + Assert_(handle.ptr >= GPUStart[HeapIndex].ptr); + Assert_(handle.ptr < GPUStart[HeapIndex].ptr + DescriptorSize * TotalNumDescriptors()); + Assert_((handle.ptr - GPUStart[HeapIndex].ptr) % DescriptorSize == 0); + return uint32(handle.ptr - GPUStart[HeapIndex].ptr) / DescriptorSize; +} + +ID3D12DescriptorHeap* DescriptorHeap::CurrentHeap() const +{ + Assert_(Heaps[0] != nullptr); + return Heaps[HeapIndex]; +} + +// == Buffer ====================================================================================== + +Buffer::Buffer() +{ +} + +Buffer::~Buffer() +{ + Assert_(Resource == nullptr); +} + +void Buffer::Initialize(uint64 size, uint64 alignment, bool32 dynamic, bool32 cpuAccessible, + bool32 allowUAV, const void* initData, ID3D12Heap* heap, uint64 heapOffset, + const wchar* name) +{ + Assert_(size > 0); + Assert_(alignment > 0); + + Size = AlignTo(size, alignment); + Alignment = alignment; + Dynamic = dynamic; + CPUAccessible = cpuAccessible; + CurrBuffer = 0; + CPUAddress = nullptr; + GPUAddress = 0; + Heap = nullptr; + HeapOffset = 0; + + Assert_(allowUAV == false || dynamic == false); + Assert_(dynamic || cpuAccessible == false); + + D3D12_RESOURCE_DESC resourceDesc = { }; + resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + resourceDesc.Width = dynamic ? Size * DX12::RenderLatency : Size; + resourceDesc.Height = 1; + resourceDesc.DepthOrArraySize = 1; + resourceDesc.MipLevels = 1; + resourceDesc.Format = DXGI_FORMAT_UNKNOWN; + resourceDesc.Flags = allowUAV ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE; + resourceDesc.SampleDesc.Count = 1; + resourceDesc.SampleDesc.Quality = 0; + resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + resourceDesc.Alignment = 0; + + const D3D12_HEAP_PROPERTIES* heapProps = cpuAccessible ? DX12::GetUploadHeapProps() : DX12::GetDefaultHeapProps(); + + D3D12_RESOURCE_STATES resourceState = D3D12_RESOURCE_STATE_COMMON; + if (cpuAccessible) + resourceState = D3D12_RESOURCE_STATE_GENERIC_READ; + + if(heap) + { + Heap = heap; + HeapOffset = heapOffset; + DXCall(DX12::Device->CreatePlacedResource(heap, heapOffset, &resourceDesc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&Resource))); + } + else + { + DXCall(DX12::Device->CreateCommittedResource(heapProps, D3D12_HEAP_FLAG_NONE, &resourceDesc, + resourceState, nullptr, IID_PPV_ARGS(&Resource))); + } + + if(name) + Resource->SetName(name); + + GPUAddress = Resource->GetGPUVirtualAddress(); + + if(cpuAccessible) + { + D3D12_RANGE readRange = { }; + DXCall(Resource->Map(0, &readRange, reinterpret_cast(&CPUAddress))); + } + + if(initData && cpuAccessible) + { + for(uint64 i = 0; i < DX12::RenderLatency; ++i) + { + uint8* dstMem = CPUAddress + Size * i; + memcpy(dstMem, initData, size); + } + + } + else if(initData) + { + UploadContext uploadContext = DX12::ResourceUploadBegin(resourceDesc.Width); + + memcpy(uploadContext.CPUAddress, initData, size); + if(dynamic) + memcpy((uint8*)uploadContext.CPUAddress + size, initData, size); + + uploadContext.CmdList->CopyBufferRegion(Resource, 0, uploadContext.Resource, uploadContext.ResourceOffset, size); + + DX12::ResourceUploadEnd(uploadContext); + } +} + +void Buffer::Shutdown() +{ + DX12::DeferredRelease(Resource); +} + +MapResult Buffer::Map() +{ + Assert_(Initialized()); + Assert_(Dynamic); + Assert_(CPUAccessible); + + // Make sure that we do this at most once per-frame + Assert_(UploadFrame != DX12::CurrentCPUFrame); + UploadFrame = DX12::CurrentCPUFrame; + + // Cycle to the next buffer + CurrBuffer = (DX12::CurrentCPUFrame + 1) % DX12::RenderLatency; + + MapResult result; + result.ResourceOffset = CurrBuffer * Size; + result.CPUAddress = CPUAddress + CurrBuffer * Size; + result.GPUAddress = GPUAddress + CurrBuffer * Size; + result.Resource = Resource; + return result; +} + +MapResult Buffer::MapAndSetData(const void* data, uint64 dataSize) +{ + Assert_(dataSize <= Size); + MapResult result = Map(); + memcpy(result.CPUAddress, data, dataSize); + return result; +} + +uint64 Buffer::UpdateData(const void* srcData, uint64 srcSize, uint64 dstOffset) +{ + return MultiUpdateData(&srcData, &srcSize, &dstOffset, 1); +} + +uint64 Buffer::MultiUpdateData(const void* srcData[], uint64 srcSize[], uint64 dstOffset[], uint64 numUpdates) +{ + Assert_(Dynamic); + Assert_(CPUAccessible == false); + Assert_(numUpdates > 0); + + // Make sure that we do this at most once per-frame + Assert_(UploadFrame != DX12::CurrentCPUFrame); + UploadFrame = DX12::CurrentCPUFrame; + + // Cycle to the next buffer + CurrBuffer = (DX12::CurrentCPUFrame + 1) % DX12::RenderLatency; + + uint64 currOffset = CurrBuffer * Size; + + uint64 totalUpdateSize = 0; + for(uint64 i = 0; i < numUpdates; ++i) + totalUpdateSize += srcSize[i]; + + UploadContext uploadContext = DX12::ResourceUploadBegin(totalUpdateSize); + + uint64 uploadOffset = 0; + for(uint64 i = 0; i < numUpdates; ++i) + { + Assert_(dstOffset[i] + srcSize[i] <= Size); + Assert_(uploadOffset + srcSize[i] <= totalUpdateSize); + memcpy(reinterpret_cast(uploadContext.CPUAddress) + uploadOffset, srcData[i], srcSize[i]); + uploadContext.CmdList->CopyBufferRegion(Resource, currOffset + dstOffset[i], uploadContext.Resource, uploadContext.ResourceOffset + uploadOffset, srcSize[i]); + + uploadOffset += srcSize[i]; + } + + DX12::ResourceUploadEnd(uploadContext); + + return GPUAddress + currOffset; +} + +void Buffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const +{ + Assert_(Resource != nullptr); + DX12::TransitionResource(cmdList, Resource, before, after); +} + +void Buffer::MakeReadable(ID3D12GraphicsCommandList* cmdList) const +{ + Assert_(Resource != nullptr); + DX12::TransitionResource(cmdList, Resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_GENERIC_READ); +} + +void Buffer::MakeWritable(ID3D12GraphicsCommandList* cmdList) const +{ + Assert_(Resource != nullptr); + DX12::TransitionResource(cmdList, Resource, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); +} + +void Buffer::UAVBarrier(ID3D12GraphicsCommandList* cmdList) const +{ + Assert_(Resource != nullptr); + D3D12_RESOURCE_BARRIER barrier = { }; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barrier.UAV.pResource = Resource; + cmdList->ResourceBarrier(1, &barrier); +} + +#if UseAsserts_ + +bool Buffer::ReadyForBinding() const +{ + return Initialized(); +} + +#endif + +// == ConstantBuffer ============================================================================== + +ConstantBuffer::ConstantBuffer() +{ +} + +ConstantBuffer::~ConstantBuffer() +{ +} + +void ConstantBuffer::Initialize(const ConstantBufferInit& init) +{ + InternalBuffer.Initialize(init.Size, DX12::ConstantBufferAlignment, init.Dynamic, init.CPUAccessible, + false, init.InitData, init.Heap, init.HeapOffset, init.Name); +} + +void ConstantBuffer::Shutdown() +{ + InternalBuffer.Shutdown(); +} + +void ConstantBuffer::SetAsGfxRootParameter(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter) const +{ + Assert_(InternalBuffer.ReadyForBinding()); + cmdList->SetGraphicsRootConstantBufferView(rootParameter, CurrentGPUAddress); +} + +void ConstantBuffer::SetAsComputeRootParameter(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter) const +{ + Assert_(InternalBuffer.ReadyForBinding()); + cmdList->SetComputeRootConstantBufferView(rootParameter, CurrentGPUAddress); +} + +void* ConstantBuffer::Map() +{ + MapResult mapResult = InternalBuffer.Map(); + CurrentGPUAddress = mapResult.GPUAddress; + return mapResult.CPUAddress; +} + +void ConstantBuffer::MapAndSetData(const void* data, uint64 dataSize) +{ + Assert_(dataSize <= InternalBuffer.Size); + void* cpuAddr = Map(); + memcpy(cpuAddr, data, dataSize); +} + +void ConstantBuffer::UpdateData(const void* srcData, uint64 srcSize, uint64 dstOffset) +{ + CurrentGPUAddress = InternalBuffer.UpdateData(srcData, srcSize, dstOffset); +} + +void ConstantBuffer::MultiUpdateData(const void* srcData[], uint64 srcSize[], uint64 dstOffset[], uint64 numUpdates) +{ + CurrentGPUAddress = InternalBuffer.MultiUpdateData(srcData, srcSize, dstOffset, numUpdates); +} + +// == StructuredBuffer ============================================================================ + +StructuredBuffer::StructuredBuffer() +{ + +} + +StructuredBuffer::~StructuredBuffer() +{ + Assert_(NumElements == 0); +} + +void StructuredBuffer::Initialize(const StructuredBufferInit& init) +{ + Shutdown(); + + Assert_(init.Stride > 0); + Assert_(init.NumElements > 0); + Stride = init.Stride; + NumElements = init.NumElements; + + InternalBuffer.Initialize(Stride * NumElements, Stride, init.Dynamic, init.CPUAccessible, init.CreateUAV, + init.InitData, init.Heap, init.HeapOffset, init.Name); + GPUAddress = InternalBuffer.GPUAddress; + + PersistentDescriptorAlloc srvAlloc = DX12::SRVDescriptorHeap.AllocatePersistent(); + SRV = srvAlloc.Index; + + // Start off all SRV's pointing to the first buffer + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = SRVDesc(0); + for(uint32 i = 0; i < ArraySize_(srvAlloc.Handles); ++i) + DX12::Device->CreateShaderResourceView(InternalBuffer.Resource, &srvDesc, srvAlloc.Handles[i]); + + if(init.CreateUAV) + { + Assert_(init.Dynamic == false); + + ID3D12Resource* counterRes = nullptr; + if(init.UseCounter) + { + D3D12_RESOURCE_DESC resourceDesc = { }; + resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + resourceDesc.Width = sizeof(uint32); + resourceDesc.Height = 1; + resourceDesc.DepthOrArraySize = 1; + resourceDesc.MipLevels = 1; + resourceDesc.Format = DXGI_FORMAT_UNKNOWN; + resourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + resourceDesc.SampleDesc.Count = 1; + resourceDesc.SampleDesc.Quality = 0; + resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + resourceDesc.Alignment = 0; + DXCall(DX12::Device->CreateCommittedResource(DX12::GetDefaultHeapProps(), D3D12_HEAP_FLAG_NONE, &resourceDesc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&CounterResource))); + + counterRes = CounterResource; + + CounterUAV = DX12::UAVDescriptorHeap.AllocatePersistent().Handles[0]; + + D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = { }; + uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uavDesc.Format = DXGI_FORMAT_R32_UINT; + uavDesc.Buffer.CounterOffsetInBytes = 0; + uavDesc.Buffer.FirstElement = 0; + uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; + uavDesc.Buffer.NumElements = 1; + DX12::Device->CreateUnorderedAccessView(counterRes, nullptr, &uavDesc, CounterUAV); + } + + UAV = DX12::UAVDescriptorHeap.AllocatePersistent().Handles[0]; + + D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = { }; + uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uavDesc.Format = DXGI_FORMAT_UNKNOWN; + uavDesc.Buffer.CounterOffsetInBytes = 0; + uavDesc.Buffer.FirstElement = 0; + uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; + uavDesc.Buffer.NumElements = uint32(NumElements); + uavDesc.Buffer.StructureByteStride = uint32(Stride); + DX12::Device->CreateUnorderedAccessView(InternalBuffer.Resource, counterRes, &uavDesc, UAV); + } +} + +void StructuredBuffer::Shutdown() +{ + DX12::SRVDescriptorHeap.FreePersistent(SRV); + DX12::UAVDescriptorHeap.FreePersistent(UAV); + DX12::UAVDescriptorHeap.FreePersistent(CounterUAV); + InternalBuffer.Shutdown(); + DX12::DeferredRelease(CounterResource); + Stride = 0; + NumElements = 0; +} + +D3D12_VERTEX_BUFFER_VIEW StructuredBuffer::VBView() const +{ + Assert_(InternalBuffer.ReadyForBinding()); + D3D12_VERTEX_BUFFER_VIEW vbView = { }; + vbView.BufferLocation = GPUAddress; + vbView.StrideInBytes = uint32(Stride); + vbView.SizeInBytes = uint32(InternalBuffer.Size); + return vbView; +} + +void* StructuredBuffer::Map() +{ + MapResult mapResult = InternalBuffer.Map(); + GPUAddress = mapResult.GPUAddress; + + UpdateDynamicSRV(); + + return mapResult.CPUAddress; +} + +void StructuredBuffer::MapAndSetData(const void* data, uint64 numElements) +{ + Assert_(numElements <= NumElements); + void* cpuAddr = Map(); + memcpy(cpuAddr, data, numElements * Stride); +} + +void StructuredBuffer::UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset) +{ + GPUAddress = InternalBuffer.UpdateData(srcData, srcNumElements * Stride, dstElemOffset * Stride); + + UpdateDynamicSRV(); +} + +void StructuredBuffer::MultiUpdateData(const void* srcData[], uint64 srcNumElements[], uint64 dstElemOffset[], uint64 numUpdates) +{ + uint64 srcSizes[16]; + uint64 dstOffsets[16]; + Assert_(numUpdates <= ArraySize_(srcSizes)); + for(uint64 i = 0; i < numUpdates; ++i) + { + srcSizes[i] = srcNumElements[i] * Stride; + dstOffsets[i] = dstElemOffset[i] * Stride; + } + + GPUAddress = InternalBuffer.MultiUpdateData(srcData, srcSizes, dstOffsets, numUpdates); + + UpdateDynamicSRV(); +} + +void StructuredBuffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const +{ + InternalBuffer.Transition(cmdList, before, after); +} + +void StructuredBuffer::MakeReadable(ID3D12GraphicsCommandList* cmdList) const +{ + InternalBuffer.MakeReadable(cmdList); +} + +void StructuredBuffer::MakeWritable(ID3D12GraphicsCommandList* cmdList) const +{ + InternalBuffer.MakeWritable(cmdList); +} + +void StructuredBuffer::UAVBarrier(ID3D12GraphicsCommandList* cmdList) const +{ + InternalBuffer.UAVBarrier(cmdList); +} + +D3D12_SHADER_RESOURCE_VIEW_DESC StructuredBuffer::SRVDesc(uint64 bufferIdx) const +{ + Assert_(bufferIdx == 0 || InternalBuffer.Dynamic); + Assert_(bufferIdx < DX12::RenderLatency); + + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; + srvDesc.Format = DXGI_FORMAT_UNKNOWN; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srvDesc.Buffer.FirstElement = uint32(NumElements * bufferIdx); + srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; + srvDesc.Buffer.NumElements = uint32(NumElements); + srvDesc.Buffer.StructureByteStride = uint32(Stride); + return srvDesc; +} + +void StructuredBuffer::UpdateDynamicSRV() const +{ + Assert_(InternalBuffer.Dynamic); + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = SRVDesc(InternalBuffer.CurrBuffer); + + D3D12_CPU_DESCRIPTOR_HANDLE handle = DX12::SRVDescriptorHeap.CPUHandleFromIndex(SRV, DX12::CurrFrameIdx); + DX12::Device->CreateShaderResourceView(InternalBuffer.Resource, &srvDesc, handle); + + DX12::DeferredCreateSRV(InternalBuffer.Resource, srvDesc, SRV); +} + +// == FormattedBuffer ============================================================================ + +FormattedBuffer::FormattedBuffer() +{ +} + +FormattedBuffer::~FormattedBuffer() +{ + Assert_(NumElements == 0); + Shutdown(); +} + +void FormattedBuffer::Initialize(const FormattedBufferInit& init) +{ + Shutdown(); + + Assert_(init.Format != DXGI_FORMAT_UNKNOWN); + Assert_(init.NumElements > 0); + Stride = DirectX::BitsPerPixel(init.Format) / 8; + NumElements = init.NumElements; + Format = init.Format; + + InternalBuffer.Initialize(Stride * NumElements, Stride, init.Dynamic, init.CPUAccessible, init.CreateUAV, + init.InitData, init.Heap, init.HeapOffset, init.Name); + GPUAddress = InternalBuffer.GPUAddress; + + PersistentDescriptorAlloc srvAlloc = DX12::SRVDescriptorHeap.AllocatePersistent(); + SRV = srvAlloc.Index; + +// Start off all SRV's pointing to the first buffer + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = SRVDesc(0); + for(uint32 i = 0; i < ArraySize_(srvAlloc.Handles); ++i) + DX12::Device->CreateShaderResourceView(InternalBuffer.Resource, &srvDesc, srvAlloc.Handles[i]); + + if(init.CreateUAV) + { + Assert_(init.Dynamic == false); + + UAV = DX12::UAVDescriptorHeap.AllocatePersistent().Handles[0]; + + D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = { }; + uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uavDesc.Format = Format; + uavDesc.Buffer.CounterOffsetInBytes = 0; + uavDesc.Buffer.FirstElement = 0; + uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; + uavDesc.Buffer.NumElements = uint32(NumElements); + + DX12::Device->CreateUnorderedAccessView(InternalBuffer.Resource, nullptr, &uavDesc, UAV); + } +} + +void FormattedBuffer::Shutdown() +{ + DX12::SRVDescriptorHeap.FreePersistent(SRV); + DX12::UAVDescriptorHeap.FreePersistent(UAV); + InternalBuffer.Shutdown(); + Stride = 0; + NumElements = 0; +} + +D3D12_INDEX_BUFFER_VIEW FormattedBuffer::IBView() const +{ + Assert_(Format == DXGI_FORMAT_R16_UINT || Format == DXGI_FORMAT_R32_UINT); + D3D12_INDEX_BUFFER_VIEW ibView = { }; + ibView.BufferLocation = GPUAddress; + ibView.Format = Format; + ibView.SizeInBytes = uint32(InternalBuffer.Size); + return ibView; +} + +void* FormattedBuffer::Map() +{ + MapResult mapResult = InternalBuffer.Map(); + + GPUAddress = mapResult.GPUAddress; + + UpdateDynamicSRV(); + + return mapResult.CPUAddress; +} + +void FormattedBuffer::MapAndSetData(const void* data, uint64 numElements) +{ + Assert_(numElements <= NumElements); + void* cpuAddr = Map(); + memcpy(cpuAddr, data, numElements * Stride); +} + +void FormattedBuffer::UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset) +{ + GPUAddress = InternalBuffer.UpdateData(srcData, srcNumElements * Stride, dstElemOffset * Stride); + + UpdateDynamicSRV(); +} + +void FormattedBuffer::MultiUpdateData(const void* srcData[], uint64 srcNumElements[], uint64 dstElemOffset[], uint64 numUpdates) +{ + uint64 srcSizes[16]; + uint64 dstOffsets[16]; + Assert_(numUpdates <= ArraySize_(srcSizes)); + for(uint64 i = 0; i < numUpdates; ++i) + { + srcSizes[i] = srcNumElements[i] * Stride; + dstOffsets[i] = dstElemOffset[i] * Stride; + } + + GPUAddress = InternalBuffer.MultiUpdateData(srcData, srcSizes, dstOffsets, numUpdates); + + UpdateDynamicSRV(); +} + +void FormattedBuffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const +{ + InternalBuffer.Transition(cmdList, before, after); +} + +void FormattedBuffer::MakeReadable(ID3D12GraphicsCommandList* cmdList) const +{ + InternalBuffer.MakeReadable(cmdList); +} + +void FormattedBuffer::MakeWritable(ID3D12GraphicsCommandList* cmdList) const +{ + InternalBuffer.MakeWritable(cmdList); +} + +void FormattedBuffer::UAVBarrier(ID3D12GraphicsCommandList* cmdList) const +{ + InternalBuffer.UAVBarrier(cmdList); +} + +D3D12_SHADER_RESOURCE_VIEW_DESC FormattedBuffer::SRVDesc(uint64 bufferIdx) const +{ + Assert_(bufferIdx == 0 || InternalBuffer.Dynamic); + Assert_(bufferIdx < DX12::RenderLatency); + + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; + srvDesc.Format = Format; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srvDesc.Buffer.FirstElement = uint32(NumElements * bufferIdx); + srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; + srvDesc.Buffer.NumElements = uint32(NumElements); + return srvDesc; +} + +void FormattedBuffer::UpdateDynamicSRV() const +{ + Assert_(InternalBuffer.Dynamic); + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = SRVDesc(InternalBuffer.CurrBuffer); + + D3D12_CPU_DESCRIPTOR_HANDLE handle = DX12::SRVDescriptorHeap.CPUHandleFromIndex(SRV, DX12::CurrFrameIdx); + DX12::Device->CreateShaderResourceView(InternalBuffer.Resource, &srvDesc, handle); + + DX12::DeferredCreateSRV(InternalBuffer.Resource, srvDesc, SRV); +} + +// == RawBuffer ============================================================================ + +RawBuffer::RawBuffer() +{ +} + +RawBuffer::~RawBuffer() +{ + Assert_(NumElements == 0); + Shutdown(); +} + +void RawBuffer::Initialize(const RawBufferInit& init) +{ + Shutdown(); + + Assert_(init.NumElements > 0); + NumElements = init.NumElements; + + InternalBuffer.Initialize(Stride * NumElements, Stride, init.Dynamic, init.CPUAccessible, init.CreateUAV, init.InitData, + init.Heap, init.HeapOffset, init.Name); + GPUAddress = InternalBuffer.GPUAddress; + + PersistentDescriptorAlloc srvAlloc = DX12::SRVDescriptorHeap.AllocatePersistent(); + SRV = srvAlloc.Index; + + // Start off all SRV's pointing to the first buffer + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = SRVDesc(0); + for(uint32 i = 0; i < ArraySize_(srvAlloc.Handles); ++i) + DX12::Device->CreateShaderResourceView(InternalBuffer.Resource, &srvDesc, srvAlloc.Handles[i]); + + if(init.CreateUAV) + { + Assert_(init.Dynamic == false); + + UAV = DX12::UAVDescriptorHeap.AllocatePersistent().Handles[0]; + + D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = { }; + uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uavDesc.Format = DXGI_FORMAT_R32_TYPELESS; + uavDesc.Buffer.CounterOffsetInBytes = 0; + uavDesc.Buffer.FirstElement = 0; + uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + uavDesc.Buffer.NumElements = uint32(NumElements); + DX12::Device->CreateUnorderedAccessView(InternalBuffer.Resource, nullptr, &uavDesc, UAV); + } +} + +void RawBuffer::Shutdown() +{ + DX12::SRVDescriptorHeap.FreePersistent(SRV); + DX12::UAVDescriptorHeap.FreePersistent(UAV); + InternalBuffer.Shutdown(); + NumElements = 0; +} + +void* RawBuffer::Map() +{ + MapResult mapResult = InternalBuffer.Map(); + GPUAddress = mapResult.GPUAddress; + + UpdateDynamicSRV(); + + return mapResult.CPUAddress; +} + +void RawBuffer::MapAndSetData(const void* data, uint64 numElements) +{ + Assert_(numElements <= NumElements); + void* cpuAddr = Map(); + memcpy(cpuAddr, data, numElements * Stride); +} + +void RawBuffer::UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset) +{ + GPUAddress = InternalBuffer.UpdateData(srcData, srcNumElements * Stride, dstElemOffset * Stride); + + UpdateDynamicSRV(); +} + +void RawBuffer::MultiUpdateData(const void* srcData[], uint64 srcNumElements[], uint64 dstElemOffset[], uint64 numUpdates) +{ + uint64 srcSizes[16]; + uint64 dstOffsets[16]; + Assert_(numUpdates <= ArraySize_(srcSizes)); + for(uint64 i = 0; i < numUpdates; ++i) + { + srcSizes[i] = srcNumElements[i] * Stride; + dstOffsets[i] = dstElemOffset[i] * Stride; + } + + GPUAddress = InternalBuffer.MultiUpdateData(srcData, srcSizes, dstOffsets, numUpdates); + + UpdateDynamicSRV(); +} + +void RawBuffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const +{ + InternalBuffer.Transition(cmdList, before, after); +} + +void RawBuffer::MakeReadable(ID3D12GraphicsCommandList* cmdList) const +{ + InternalBuffer.MakeReadable(cmdList); +} + +void RawBuffer::MakeWritable(ID3D12GraphicsCommandList* cmdList) const +{ + InternalBuffer.MakeWritable(cmdList); +} + +void RawBuffer::UAVBarrier(ID3D12GraphicsCommandList* cmdList) const +{ + InternalBuffer.UAVBarrier(cmdList); +} + +D3D12_SHADER_RESOURCE_VIEW_DESC RawBuffer::SRVDesc(uint64 bufferIdx) const +{ + Assert_(bufferIdx == 0 || InternalBuffer.Dynamic); + Assert_(bufferIdx < DX12::RenderLatency); + + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; + srvDesc.Format = DXGI_FORMAT_R32_TYPELESS; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srvDesc.Buffer.FirstElement = uint32(NumElements * bufferIdx); + srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + srvDesc.Buffer.NumElements = uint32(NumElements); + return srvDesc; +} + +void RawBuffer::UpdateDynamicSRV() const +{ + Assert_(InternalBuffer.Dynamic); + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = SRVDesc(InternalBuffer.CurrBuffer); + + D3D12_CPU_DESCRIPTOR_HANDLE handle = DX12::SRVDescriptorHeap.CPUHandleFromIndex(SRV, DX12::CurrFrameIdx); + DX12::Device->CreateShaderResourceView(InternalBuffer.Resource, &srvDesc, handle); + + DX12::DeferredCreateSRV(InternalBuffer.Resource, srvDesc, SRV); +} + +// == ReadbackBuffer ============================================================================== + +ReadbackBuffer::ReadbackBuffer() +{ +} + +ReadbackBuffer::~ReadbackBuffer() +{ + Assert_(Resource == nullptr); +} + +void ReadbackBuffer::Initialize(uint64 size) +{ + Assert_(size > 0); + Size = size; + + D3D12_RESOURCE_DESC resourceDesc = {}; + resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + resourceDesc.Width = uint32(size); + resourceDesc.Height = 1; + resourceDesc.DepthOrArraySize = 1; + resourceDesc.MipLevels = 1; + resourceDesc.Format = DXGI_FORMAT_UNKNOWN; + resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE; + resourceDesc.SampleDesc.Count = 1; + resourceDesc.SampleDesc.Quality = 0; + resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + resourceDesc.Alignment = 0; + + DXCall(DX12::Device->CreateCommittedResource(DX12::GetReadbackHeapProps(), D3D12_HEAP_FLAG_NONE, &resourceDesc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&Resource))); +} + +void ReadbackBuffer::Shutdown() +{ + DX12::DeferredRelease(Resource); + Size = 0; +} + +void* ReadbackBuffer::Map() +{ + Assert_(Resource != nullptr); + void* data = nullptr; + Resource->Map(0, nullptr, &data); + return data; +} + +void ReadbackBuffer::Unmap() +{ + Assert_(Resource != nullptr); + Resource->Unmap(0, nullptr); +} + +// == Fence ======================================================================================= + +Fence::~Fence() +{ + Assert_(D3DFence == nullptr); + Shutdown(); +} + +void Fence::Init(uint64 initialValue) +{ + DXCall(DX12::Device->CreateFence(initialValue, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&D3DFence))); + FenceEvent = CreateEventEx(nullptr, FALSE, FALSE, EVENT_ALL_ACCESS); + Win32Call(FenceEvent != 0); +} + +void Fence::Shutdown() +{ + DX12::DeferredRelease(D3DFence); +} + +void Fence::Signal(ID3D12CommandQueue* queue, uint64 fenceValue) +{ + Assert_(D3DFence != nullptr); + DXCall(queue->Signal(D3DFence, fenceValue)); +} + +void Fence::Wait(uint64 fenceValue) +{ + Assert_(D3DFence != nullptr); + if(D3DFence->GetCompletedValue() < fenceValue) + { + DXCall(D3DFence->SetEventOnCompletion(fenceValue, FenceEvent)); + WaitForSingleObject(FenceEvent, INFINITE); + } +} + + +bool Fence::Signaled(uint64 fenceValue) +{ + Assert_(D3DFence != nullptr); + return D3DFence->GetCompletedValue() >= fenceValue; +} + +void Fence::Clear(uint64 fenceValue) +{ + Assert_(D3DFence != nullptr); + D3DFence->Signal(fenceValue); +} + +// == Texture ==================================================================================== + +Texture::Texture() +{ +} + +Texture::~Texture() +{ + Assert_(Resource == nullptr); +} + +void Texture::Shutdown() +{ + DX12::SRVDescriptorHeap.FreePersistent(SRV); + DX12::DeferredRelease(Resource); +} + +// == RenderTexture =============================================================================== + +RenderTexture::RenderTexture() +{ +} + +RenderTexture::~RenderTexture() +{ + Assert_(RTV.ptr == 0); +} + +void RenderTexture::Initialize(const RenderTextureInit& init) +{ + Shutdown(); + + Assert_(init.Width > 0); + Assert_(init.Height > 0); + Assert_(init.MSAASamples > 0); + + D3D12_RESOURCE_DESC textureDesc = { }; + textureDesc.MipLevels = 1; + textureDesc.Format = init.Format; + textureDesc.Width = uint32(init.Width); + textureDesc.Height = uint32(init.Height); + textureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + if(init.CreateUAV) + textureDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + textureDesc.DepthOrArraySize = uint16(init.ArraySize); + textureDesc.SampleDesc.Count = uint32(init.MSAASamples); + textureDesc.SampleDesc.Quality = init.MSAASamples > 1 ? DX12::StandardMSAAPattern : 0; + textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + textureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + textureDesc.Alignment = 0; + + D3D12_CLEAR_VALUE clearValue = { }; + clearValue.Format = init.Format; + DXCall(DX12::Device->CreateCommittedResource(DX12::GetDefaultHeapProps(), D3D12_HEAP_FLAG_NONE, &textureDesc, + init.InitialState, &clearValue, IID_PPV_ARGS(&Texture.Resource))); + + if(init.Name != nullptr) + Texture.Resource->SetName(init.Name); + + PersistentDescriptorAlloc srvAlloc = DX12::SRVDescriptorHeap.AllocatePersistent(); + Texture.SRV = srvAlloc.Index; + for(uint32 i = 0; i < DX12::SRVDescriptorHeap.NumHeaps; ++i) + DX12::Device->CreateShaderResourceView(Texture.Resource, nullptr, srvAlloc.Handles[i]); + + Texture.Width = uint32(init.Width); + Texture.Height = uint32(init.Height); + Texture.Depth = 1; + Texture.NumMips = 1; + Texture.ArraySize = uint32(init.ArraySize); + Texture.Format = init.Format; + Texture.Cubemap = false; + MSAASamples = uint32(init.MSAASamples); + MSAAQuality = uint32(textureDesc.SampleDesc.Quality); + + RTV = DX12::RTVDescriptorHeap.AllocatePersistent().Handles[0]; + DX12::Device->CreateRenderTargetView(Texture.Resource, nullptr, RTV); + + if(init.ArraySize > 1) + { + ArrayRTVs.Init(init.ArraySize); + + D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = { }; + rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; + rtvDesc.Format = init.Format; + if(init.MSAASamples > 1) + rtvDesc.Texture2DMSArray.ArraySize = 1; + else + rtvDesc.Texture2DArray.ArraySize = 1; + + for(uint64 i = 0; i < init.ArraySize; ++i) + { + if(init.MSAASamples > 1) + rtvDesc.Texture2DMSArray.FirstArraySlice = uint32(i); + else + rtvDesc.Texture2DArray.FirstArraySlice = uint32(i); + + ArrayRTVs[i] = DX12::RTVDescriptorHeap.AllocatePersistent().Handles[0]; + DX12::Device->CreateRenderTargetView(Texture.Resource, &rtvDesc, ArrayRTVs[i]); + } + } + + if(init.CreateUAV) + { + UAV = DX12::UAVDescriptorHeap.AllocatePersistent().Handles[0]; + DX12::Device->CreateUnorderedAccessView(Texture.Resource, nullptr, nullptr, UAV); + } +} + +void RenderTexture::Shutdown() +{ + DX12::RTVDescriptorHeap.FreePersistent(RTV); + DX12::UAVDescriptorHeap.FreePersistent(UAV); + for(uint64 i = 0; i < ArrayRTVs.Size(); ++i) + DX12::RTVDescriptorHeap.FreePersistent(ArrayRTVs[i]); + ArrayRTVs.Shutdown(); + Texture.Shutdown(); +} + +void RenderTexture::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after, uint64 mipLevel, uint64 arraySlice) const +{ + uint32 subResourceIdx = mipLevel == uint64(-1) || arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES + : uint32(SubResourceIndex(mipLevel, arraySlice)); + Assert_(Texture.Resource != nullptr); + DX12::TransitionResource(cmdList, Texture.Resource, before, after, subResourceIdx); +} + +void RenderTexture::MakeReadable(ID3D12GraphicsCommandList* cmdList, uint64 mipLevel, uint64 arraySlice) const +{ + uint32 subResourceIdx = mipLevel == uint64(-1) || arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES + : uint32(SubResourceIndex(mipLevel, arraySlice)); + Assert_(Texture.Resource != nullptr); + DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, subResourceIdx); +} + +void RenderTexture::MakeWritable(ID3D12GraphicsCommandList* cmdList, uint64 mipLevel, uint64 arraySlice) const +{ + uint32 subResourceIdx = mipLevel == uint64(-1) || arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES + : uint32(SubResourceIndex(mipLevel, arraySlice)); + Assert_(Texture.Resource != nullptr); + DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET, subResourceIdx); +} + +void RenderTexture::UAVBarrier(ID3D12GraphicsCommandList* cmdList) const +{ + Assert_(Texture.Resource != nullptr); + + D3D12_RESOURCE_BARRIER barrier = { }; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barrier.UAV.pResource = Texture.Resource; + cmdList->ResourceBarrier(1, &barrier); +} + +// == VolumeTexture =============================================================================== + +VolumeTexture::VolumeTexture() +{ +} + +VolumeTexture::~VolumeTexture() +{ + Assert_(UAV.ptr == 0); +} + +void VolumeTexture::Initialize(const VolumeTextureInit& init) +{ + Shutdown(); + + Assert_(init.Width > 0); + Assert_(init.Height > 0); + Assert_(init.Depth > 0); + + D3D12_RESOURCE_DESC textureDesc = { }; + textureDesc.MipLevels = 1; + textureDesc.Format = init.Format; + textureDesc.Width = uint32(init.Width); + textureDesc.Height = uint32(init.Height); + textureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + textureDesc.DepthOrArraySize = uint16(init.Depth); + textureDesc.SampleDesc.Count = 1; + textureDesc.SampleDesc.Quality = 0; + textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + textureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + textureDesc.Alignment = 0; + + DXCall(DX12::Device->CreateCommittedResource(DX12::GetDefaultHeapProps(), D3D12_HEAP_FLAG_NONE, &textureDesc, + init.InitialState, nullptr, IID_PPV_ARGS(&Texture.Resource))); + + if(init.Name != nullptr) + Texture.Resource->SetName(init.Name); + + PersistentDescriptorAlloc srvAlloc = DX12::SRVDescriptorHeap.AllocatePersistent(); + Texture.SRV = srvAlloc.Index; + for(uint32 i = 0; i < DX12::SRVDescriptorHeap.NumHeaps; ++i) + DX12::Device->CreateShaderResourceView(Texture.Resource, nullptr, srvAlloc.Handles[i]); + + Texture.Width = uint32(init.Width); + Texture.Height = uint32(init.Height); + Texture.Depth = uint32(init.Depth); + Texture.NumMips = 1; + Texture.ArraySize = 1; + Texture.Format = init.Format; + Texture.Cubemap = false; + + UAV = DX12::UAVDescriptorHeap.AllocatePersistent().Handles[0]; + DX12::Device->CreateUnorderedAccessView(Texture.Resource, nullptr, nullptr, UAV); +} + +void VolumeTexture::Shutdown() +{ + DX12::UAVDescriptorHeap.FreePersistent(UAV); + Texture.Shutdown(); +} + +void VolumeTexture::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const +{ + Assert_(Texture.Resource != nullptr); + DX12::TransitionResource(cmdList, Texture.Resource, before, after, 0); +} + +void VolumeTexture::MakeReadable(ID3D12GraphicsCommandList* cmdList) const +{ + Assert_(Texture.Resource != nullptr); + DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, 0); +} + +void VolumeTexture::MakeWritable(ID3D12GraphicsCommandList* cmdList) const +{ + Assert_(Texture.Resource != nullptr); + DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, 0); +} + +// == DepthBuffer =============================================================================== + +DepthBuffer::DepthBuffer() +{ +} + +DepthBuffer::~DepthBuffer() +{ + Assert_(DSVFormat == DXGI_FORMAT_UNKNOWN); + Shutdown(); +} + +void DepthBuffer::Initialize(const DepthBufferInit& init) +{ + Shutdown(); + + Assert_(init.Width > 0); + Assert_(init.Height > 0); + Assert_(init.MSAASamples > 0); + + DXGI_FORMAT texFormat = init.Format; + DXGI_FORMAT srvFormat = init.Format; + if(init.Format == DXGI_FORMAT_D16_UNORM) + { + texFormat = DXGI_FORMAT_R16_TYPELESS; + srvFormat = DXGI_FORMAT_R16_UNORM; + } + else if(init.Format == DXGI_FORMAT_D24_UNORM_S8_UINT) + { + texFormat = DXGI_FORMAT_R24G8_TYPELESS; + srvFormat = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; + } + else if(init.Format == DXGI_FORMAT_D32_FLOAT) + { + texFormat = DXGI_FORMAT_R32_TYPELESS; + srvFormat = DXGI_FORMAT_R32_FLOAT; + } + else if(init.Format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT) + { + texFormat = DXGI_FORMAT_R32G8X24_TYPELESS; + srvFormat = DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; + } + else + { + AssertFail_("Invalid depth buffer format!"); + } + + D3D12_RESOURCE_DESC textureDesc = { }; + textureDesc.MipLevels = 1; + textureDesc.Format = texFormat; + textureDesc.Width = uint32(init.Width); + textureDesc.Height = uint32(init.Height); + textureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + textureDesc.DepthOrArraySize = uint16(init.ArraySize); + textureDesc.SampleDesc.Count = uint32(init.MSAASamples); + textureDesc.SampleDesc.Quality = init.MSAASamples> 1 ? DX12::StandardMSAAPattern : 0; + textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + textureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + textureDesc.Alignment = 0; + + D3D12_CLEAR_VALUE clearValue = { }; + clearValue.DepthStencil.Depth = 1.0f; + clearValue.DepthStencil.Stencil = 0; + clearValue.Format = init.Format; + + DXCall(DX12::Device->CreateCommittedResource(DX12::GetDefaultHeapProps(), D3D12_HEAP_FLAG_NONE, &textureDesc, + init.InitialState, &clearValue, IID_PPV_ARGS(&Texture.Resource))); + + if(init.Name != nullptr) + Texture.Resource->SetName(init.Name); + + PersistentDescriptorAlloc srvAlloc = DX12::SRVDescriptorHeap.AllocatePersistent(); + Texture.SRV = srvAlloc.Index; + + D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { }; + srvDesc.Format = srvFormat; + srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if(init.MSAASamples == 1 && init.ArraySize == 1) + { + srvDesc.Texture2D.MipLevels = 1; + srvDesc.Texture2D.MostDetailedMip = 0; + srvDesc.Texture2D.PlaneSlice = 0; + srvDesc.Texture2D.ResourceMinLODClamp = 0.0f; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + } + else if(init.MSAASamples == 1 && init.ArraySize > 1) + { + srvDesc.Texture2DArray.ArraySize = uint32(init.ArraySize); + srvDesc.Texture2DArray.FirstArraySlice = 0; + srvDesc.Texture2DArray.MipLevels = 1; + srvDesc.Texture2DArray.MostDetailedMip = 0; + srvDesc.Texture2DArray.PlaneSlice = 0; + srvDesc.Texture2DArray.ResourceMinLODClamp = 0.0f; + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + } + else if(init.MSAASamples > 1 && init.ArraySize == 1) + { + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS; + } + else if(init.MSAASamples > 1 && init.ArraySize > 1) + { + srvDesc.Texture2DMSArray.FirstArraySlice = 0; + srvDesc.Texture2DMSArray.ArraySize = uint32(init.ArraySize); + srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; + } + + for(uint32 i = 0; i < DX12::SRVDescriptorHeap.NumHeaps; ++i) + DX12::Device->CreateShaderResourceView(Texture.Resource, &srvDesc, srvAlloc.Handles[i]); + + Texture.Width = uint32(init.Width); + Texture.Height = uint32(init.Height); + Texture.Depth = 1; + Texture.NumMips = 1; + Texture.ArraySize = uint32(init.ArraySize); + Texture.Format = srvFormat; + Texture.Cubemap = false; + MSAASamples = uint32(init.MSAASamples); + MSAAQuality = uint32(textureDesc.SampleDesc.Quality); + + DSV = DX12::DSVDescriptorHeap.AllocatePersistent().Handles[0]; + + D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = { }; + dsvDesc.Flags = D3D12_DSV_FLAG_NONE; + dsvDesc.Format = init.Format; + + if(init.MSAASamples == 1 && init.ArraySize == 1) + { + dsvDesc.Texture2D.MipSlice = 0; + dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + } + else if(init.MSAASamples == 1 && init.ArraySize > 1) + { + dsvDesc.Texture2DArray.ArraySize = uint32(init.ArraySize); + dsvDesc.Texture2DArray.FirstArraySlice = 0; + dsvDesc.Texture2DArray.MipSlice = 0; + dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY; + } + else if(init.MSAASamples > 1 && init.ArraySize == 1) + { + dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMS; + } + else if(init.MSAASamples > 1 && init.ArraySize > 1) + { + dsvDesc.Texture2DMSArray.ArraySize = uint32(init.ArraySize); + dsvDesc.Texture2DMSArray.FirstArraySlice = 0; + dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY; + } + + DX12::Device->CreateDepthStencilView(Texture.Resource, &dsvDesc, DSV); + + bool hasStencil = init.Format == DXGI_FORMAT_D24_UNORM_S8_UINT || init.Format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + + ReadOnlyDSV = DX12::DSVDescriptorHeap.AllocatePersistent().Handles[0]; + dsvDesc.Flags = D3D12_DSV_FLAG_READ_ONLY_DEPTH; + if(hasStencil) + dsvDesc.Flags |= D3D12_DSV_FLAG_READ_ONLY_STENCIL; + DX12::Device->CreateDepthStencilView(Texture.Resource, &dsvDesc, ReadOnlyDSV); + + if(init.ArraySize > 1) + { + ArrayDSVs.Init(init.ArraySize); + + dsvDesc.Flags = D3D12_DSV_FLAG_NONE; + if(init.MSAASamples > 1) + dsvDesc.Texture2DMSArray.ArraySize = 1; + else + dsvDesc.Texture2DArray.ArraySize = 1; + + for(uint64 i = 0; i < init.ArraySize; ++i) + { + if(init.MSAASamples > 1) + dsvDesc.Texture2DMSArray.FirstArraySlice = uint32(i); + else + dsvDesc.Texture2DArray.FirstArraySlice = uint32(i); + + ArrayDSVs[i] = DX12::DSVDescriptorHeap.AllocatePersistent().Handles[0]; + DX12::Device->CreateDepthStencilView(Texture.Resource, &dsvDesc, ArrayDSVs[i]); + } + } + + DSVFormat = init.Format; +} + +void DepthBuffer::Shutdown() +{ + DX12::DSVDescriptorHeap.FreePersistent(DSV); + DX12::DSVDescriptorHeap.FreePersistent(ReadOnlyDSV); + for(uint64 i = 0; i < ArrayDSVs.Size(); ++i) + DX12::DSVDescriptorHeap.FreePersistent(ArrayDSVs[i]); + ArrayDSVs.Shutdown(); + Texture.Shutdown(); + DSVFormat = DXGI_FORMAT_UNKNOWN; +} + +void DepthBuffer::Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after, uint64 arraySlice) const +{ + uint32 subResourceIdx = arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES : uint32(arraySlice); + Assert_(Texture.Resource != nullptr); + DX12::TransitionResource(cmdList, Texture.Resource, before, after, subResourceIdx); +} + +void DepthBuffer::MakeReadable(ID3D12GraphicsCommandList* cmdList, uint64 arraySlice) const +{ + uint32 subResourceIdx = arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES : uint32(arraySlice); + Assert_(Texture.Resource != nullptr); + DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_DEPTH_READ | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, subResourceIdx); +} + +void DepthBuffer::MakeWritable(ID3D12GraphicsCommandList* cmdList, uint64 arraySlice) const +{ + uint32 subResourceIdx = arraySlice == uint64(-1) ? D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES : uint32(arraySlice); + Assert_(Texture.Resource != nullptr); + DX12::TransitionResource(cmdList, Texture.Resource, D3D12_RESOURCE_STATE_DEPTH_READ | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_DEPTH_WRITE, subResourceIdx); +} + +} \ No newline at end of file diff --git a/SampleFramework12/v1.00/Graphics/GraphicsTypes.h b/SampleFramework12/v1.01/Graphics/GraphicsTypes.h similarity index 55% rename from SampleFramework12/v1.00/Graphics/GraphicsTypes.h rename to SampleFramework12/v1.01/Graphics/GraphicsTypes.h index 005d17f..e60a5f2 100644 --- a/SampleFramework12/v1.00/Graphics/GraphicsTypes.h +++ b/SampleFramework12/v1.01/Graphics/GraphicsTypes.h @@ -1,470 +1,519 @@ -//================================================================================================= -// -// MJP's DX12 Sample Framework -// http://mynameismjp.wordpress.com/ -// -// All code licensed under the MIT license -// -//================================================================================================= - -#pragma once - -#include "..\\PCH.h" - -#include "..\\InterfacePointers.h" -#include "..\\Utility.h" -#include "..\\Containers.h" -#include "DX12.h" -#include "DX12_Upload.h" -#include "DX12_Helpers.h" - -namespace SampleFramework12 -{ - -struct DescriptorHandle -{ - D3D12_CPU_DESCRIPTOR_HANDLE CPUHandle = { }; - D3D12_GPU_DESCRIPTOR_HANDLE GPUHandle = { }; - - #if UseAsserts_ - const void* ParentHeap = nullptr; - #endif - - bool IsValid() const - { - return CPUHandle.ptr != 0; - } - - bool ShaderVisible() const - { - return GPUHandle.ptr != 0; - } -}; - -// Wrapper for D3D12 a descriptor heap -struct DescriptorHeap -{ - ID3D12DescriptorHeap* Heap = nullptr; - uint64 NumDescriptors = 0; - uint64 Allocated = 0; - Array DeadList; - uint32 DescriptorSize = 0; - bool32 ShaderVisible = false; - D3D12_DESCRIPTOR_HEAP_TYPE HeapType = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; - D3D12_CPU_DESCRIPTOR_HANDLE CPUStart = { }; - D3D12_GPU_DESCRIPTOR_HANDLE GPUStart = { }; - - ~DescriptorHeap(); - - void Init(ID3D12Device* device, uint64 numDescriptors, D3D12_DESCRIPTOR_HEAP_TYPE heapType, bool shaderVisible); - void Shutdown(); - - DescriptorHandle Allocate(); - void Free(DescriptorHandle& handle); -}; - -struct LinearDescriptorHeap -{ - ID3D12DescriptorHeap* Heap = nullptr; - uint64 NumDescriptors = 0; - uint64 Allocated = 0; - uint32 DescriptorSize = 0; - bool32 ShaderVisible = false; - D3D12_DESCRIPTOR_HEAP_TYPE HeapType = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; - D3D12_CPU_DESCRIPTOR_HANDLE CPUStart = {}; - D3D12_GPU_DESCRIPTOR_HANDLE GPUStart = {}; - - ~LinearDescriptorHeap(); - - void Init(ID3D12Device* device, uint64 numDescriptors, D3D12_DESCRIPTOR_HEAP_TYPE heapType, bool shaderVisible); - void Shutdown(); - - DescriptorHandle Allocate(uint64 count); - void Reset(); -}; - -enum class BufferLifetime -{ - Persistent = 0, - Temporary -}; - -struct Buffer -{ - ID3D12Resource* Resource = nullptr; - uint64 CurrBuffer = 0; - uint8* CPUAddress = 0; - uint64 GPUAddress = 0; - uint64 Alignment = 0; - uint64 Size = 0; - bool32 Dynamic = false; - BufferLifetime Lifetime = BufferLifetime::Persistent; - - #if UseAsserts_ - uint64 UploadFrame = uint64(-1); - #endif - - Buffer(); - ~Buffer(); - - void Initialize(uint64 size, uint64 alignment, bool32 dynamic, BufferLifetime lifetime, bool32 allowUAV, const void* initData, D3D12_RESOURCE_STATES initialState); - void Shutdown(); - - MapResult Map(); - MapResult MapAndSetData(const void* data, uint64 dataSize); - template MapResult MapAndSetData(const T& data) { return MapAndSetData(&data, sizeof(T)); } - void UpdateData(const void* srcData, uint64 srcSize, uint64 dstOffset); - - void Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const; - void MakeReadable(ID3D12GraphicsCommandList* cmdList) const; - void MakeWritable(ID3D12GraphicsCommandList* cmdList) const; - void UAVBarrier(ID3D12GraphicsCommandList* cmdList) const; - - bool Initialized() const { return Size > 0; } - - #if UseAsserts_ - bool ReadyForBinding() const; - #endif - -private: - - Buffer(const Buffer& other) { } -}; - -// For aligning to float4 boundaries -#define Float4Align __declspec(align(16)) -#define Float4Align_ __declspec(align(16)) - -template struct ConstantBuffer -{ - T Data; - Buffer InternalBuffer; - uint64 CurrentGPUAddress = 0; - - ConstantBuffer() - { - } - - ~ConstantBuffer() - { - Shutdown(); - } - - void Initialize(BufferLifetime lifetime) - { - InternalBuffer.Initialize(sizeof(T), DX12::ConstantBufferAlignment, true, lifetime, false, nullptr, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); - } - - void Shutdown() - { - InternalBuffer.Shutdown(); - } - - void Upload() - { - MapResult result = InternalBuffer.MapAndSetData(Data); - CurrentGPUAddress = result.GPUAddress; - } - - void SetAsGfxRootParameter(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter) const - { - Assert_(InternalBuffer.ReadyForBinding()); - cmdList->SetGraphicsRootConstantBufferView(rootParameter, CurrentGPUAddress); - } - - void SetAsComputeRootParameter(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter) const - { - Assert_(InternalBuffer.ReadyForBinding()); - cmdList->SetComputeRootConstantBufferView(rootParameter, CurrentGPUAddress); - } -}; - -struct StructuredBufferInit -{ - uint64 Stride = 0; - uint64 NumElements = 0; - bool32 CreateUAV = false; - bool32 UseCounter = false; - bool32 Dynamic = false; - BufferLifetime Lifetime = BufferLifetime::Persistent; - const void* InitData = nullptr; - D3D12_RESOURCE_STATES InitialState = D3D12_RESOURCE_STATE_GENERIC_READ; -}; - -struct StructuredBuffer -{ - Buffer InternalBuffer; - uint64 Stride = 0; - uint64 NumElements = 0; - DescriptorHandle SRVHandles[DX12::RenderLatency]; - DescriptorHandle UAVHandle; - ID3D12Resource* CounterResource = nullptr; - DescriptorHandle CounterUAV; - uint64 GPUAddress = 0; - - StructuredBuffer(); - ~StructuredBuffer(); - - void Initialize(const StructuredBufferInit& init); - void Shutdown(); - - D3D12_CPU_DESCRIPTOR_HANDLE SRV() const; - D3D12_CPU_DESCRIPTOR_HANDLE UAV() const; - D3D12_VERTEX_BUFFER_VIEW VBView() const; - ID3D12Resource* Resource() const { return InternalBuffer.Resource; } - - void* Map(); - template T* Map() { return reinterpret_cast(Map()); }; - void MapAndSetData(const void* data, uint64 numElements); - void UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset); - - void Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const; - void MakeReadable(ID3D12GraphicsCommandList* cmdList) const; - void MakeWritable(ID3D12GraphicsCommandList* cmdList) const; - void UAVBarrier(ID3D12GraphicsCommandList* cmdList) const; - -private: - - StructuredBuffer(const StructuredBuffer& other) { } - -}; - -struct FormattedBufferInit -{ - DXGI_FORMAT Format = DXGI_FORMAT_UNKNOWN; - uint64 NumElements = 0; - bool32 CreateUAV = false; - bool32 Dynamic = false; - BufferLifetime Lifetime = BufferLifetime::Persistent; - const void* InitData = nullptr; - D3D12_RESOURCE_STATES InitialState = D3D12_RESOURCE_STATE_GENERIC_READ; -}; - -struct FormattedBuffer -{ - Buffer InternalBuffer; - uint64 Stride = 0; - uint64 NumElements = 0; - DXGI_FORMAT Format = DXGI_FORMAT_UNKNOWN; - DescriptorHandle SRVHandles[DX12::RenderLatency]; - DescriptorHandle UAVHandle; - uint64 GPUAddress = 0; - - FormattedBuffer(); - ~FormattedBuffer(); - - void Initialize(const FormattedBufferInit& init); - void Shutdown(); - - D3D12_CPU_DESCRIPTOR_HANDLE SRV() const; - D3D12_CPU_DESCRIPTOR_HANDLE UAV() const; - D3D12_INDEX_BUFFER_VIEW IBView() const; - ID3D12Resource* Resource() const { return InternalBuffer.Resource; } - - void* Map(); - template T* Map() { return reinterpret_cast(Map()); }; - void MapAndSetData(const void* data, uint64 numElements); - void UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset); - - void Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const; - void MakeReadable(ID3D12GraphicsCommandList* cmdList) const; - void MakeWritable(ID3D12GraphicsCommandList* cmdList) const; - void UAVBarrier(ID3D12GraphicsCommandList* cmdList) const; - -private: - - FormattedBuffer(const FormattedBuffer& other) { } - -}; - -struct RawBufferInit -{ - uint64 NumElements = 0; - bool32 CreateUAV = false; - bool32 Dynamic = false; - BufferLifetime Lifetime = BufferLifetime::Persistent; - const void* InitData = nullptr; - D3D12_RESOURCE_STATES InitialState = D3D12_RESOURCE_STATE_GENERIC_READ; -}; - -struct RawBuffer -{ - Buffer InternalBuffer; - uint64 NumElements = 0; - DescriptorHandle SRVHandles[DX12::RenderLatency]; - DescriptorHandle UAVHandle; - uint64 GPUAddress = 0; - - const uint64 Stride = 4; - - RawBuffer(); - ~RawBuffer(); - - void Initialize(const RawBufferInit& init); - void Shutdown(); - - D3D12_CPU_DESCRIPTOR_HANDLE SRV() const; - D3D12_CPU_DESCRIPTOR_HANDLE UAV() const; - ID3D12Resource* Resource() const { return InternalBuffer.Resource; } - - void* Map(); - template T* Map() { return reinterpret_cast(Map()); }; - void MapAndSetData(const void* data, uint64 numElements); - void UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset); - - void Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const; - void MakeReadable(ID3D12GraphicsCommandList* cmdList) const; - void MakeWritable(ID3D12GraphicsCommandList* cmdList) const; - void UAVBarrier(ID3D12GraphicsCommandList* cmdList) const; - -private: - - RawBuffer(const RawBuffer& other) { } - -}; - -struct ReadbackBuffer -{ - ID3D12Resource* Resource = nullptr; - uint64 Size = 0; - - ReadbackBuffer(); - ~ReadbackBuffer(); - - void Initialize(uint64 size); - void Shutdown(); - - void* Map(); - template T* Map() { return reinterpret_cast(Map()); }; - void Unmap(); - -private: - - ReadbackBuffer(const ReadbackBuffer& other) { } -}; - -struct Fence -{ - ID3D12Fence* D3DFence = nullptr; - HANDLE FenceEvent = INVALID_HANDLE_VALUE; - - ~Fence(); - - void Init(uint64 initialValue = 0); - void Shutdown(); - - void Signal(ID3D12CommandQueue* queue, uint64 fenceValue); - void Wait(uint64 fenceValue); - bool Signaled(uint64 fenceValue); - void Clear(uint64 fenceValue); -}; - -struct Texture -{ - DescriptorHandle SRV; - ID3D12Resource* Resource = nullptr; - uint32 Width = 0; - uint32 Height = 0; - uint32 Depth = 0; - uint32 NumMips = 0; - uint32 ArraySize = 0; - DXGI_FORMAT Format = DXGI_FORMAT_UNKNOWN; - bool32 Cubemap = false; - - Texture(); - ~Texture(); - - bool Valid() const - { - return Resource != nullptr; - } - - void Shutdown(); - -private: - - Texture(const Texture& other) { } -}; - -struct RenderTexture -{ - Texture Texture; - DescriptorHandle RTV; - DescriptorHandle UAV; - Array ArrayRTVs; - uint32 MSAASamples = 0; - - RenderTexture(); - ~RenderTexture(); - - void Initialize(uint64 width, uint64 height, DXGI_FORMAT format, uint64 msaaSamples = 1, uint64 arraySize = 1, - bool32 createUAV = false, D3D12_RESOURCE_STATES initialState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); - void Shutdown(); - - void Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after, uint64 mipLevel = uint64(-1), uint64 arraySlice = uint64(-1)) const; - void MakeReadable(ID3D12GraphicsCommandList* cmdList, uint64 mipLevel = uint64(-1), uint64 arraySlice = uint64(-1)) const; - void MakeWritable(ID3D12GraphicsCommandList* cmdList, uint64 mipLevel = uint64(-1), uint64 arraySlice = uint64(-1)) const; - - D3D12_CPU_DESCRIPTOR_HANDLE SRV() const { return Texture.SRV.CPUHandle; } - uint64 Width() const { return Texture.Width; } - uint64 Height() const { return Texture.Height; } - DXGI_FORMAT Format() const { return Texture.Format; } - ID3D12Resource* Resource() const { return Texture.Resource; } - uint64 SubResourceIndex(uint64 mipLevel, uint64 arraySlice) const { return arraySlice * Texture.NumMips + mipLevel; } - -private: - - RenderTexture(const RenderTexture& other) { } -}; - -struct DepthBuffer -{ - Texture Texture; - DescriptorHandle DSV; - DescriptorHandle ReadOnlyDSV; - Array ArrayDSVs; - uint32 MSAASamples = 0; - DXGI_FORMAT DSVFormat = DXGI_FORMAT_UNKNOWN; - - DepthBuffer(); - ~DepthBuffer(); - - void Initialize(uint64 width, uint64 height, DXGI_FORMAT format, uint64 msaaSamples = 1, uint64 arraySize = 1, - D3D12_RESOURCE_STATES initialState = D3D12_RESOURCE_STATE_DEPTH_WRITE); - void Shutdown(); - - void Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after, uint64 arraySlice = uint64(-1)) const; - void MakeReadable(ID3D12GraphicsCommandList* cmdList, uint64 arraySlice = uint64(-1)) const; - void MakeWritable(ID3D12GraphicsCommandList* cmdList, uint64 arraySlice = uint64(-1)) const; - - D3D12_CPU_DESCRIPTOR_HANDLE SRV() const { return Texture.SRV.CPUHandle; } - uint64 Width() const { return Texture.Width; } - uint64 Height() const { return Texture.Height; } - ID3D12Resource* Resource() const { return Texture.Resource; } - -private: - - DepthBuffer(const DepthBuffer& other) { } -}; - -struct PIXMarker -{ - ID3D12GraphicsCommandList* CmdList = nullptr; - - PIXMarker(ID3D12GraphicsCommandList* cmdList, const wchar* msg) : CmdList(cmdList) - { - PIXBeginEvent(cmdList, 0, msg); - } - - PIXMarker(ID3D12GraphicsCommandList* cmdList, const char* msg) : CmdList(cmdList) - { - PIXBeginEvent(cmdList, 0, msg); - } - - ~PIXMarker() - { - PIXEndEvent(CmdList); - } -}; - +//================================================================================================= +// +// MJP's DX12 Sample Framework +// http://mynameismjp.wordpress.com/ +// +// All code licensed under the MIT license +// +//================================================================================================= + +#pragma once + +#include "..\\PCH.h" + +#include "..\\InterfacePointers.h" +#include "..\\Utility.h" +#include "..\\Containers.h" +#include "DX12.h" +#include "DX12_Upload.h" +#include "DX12_Helpers.h" + +namespace SampleFramework12 +{ + +struct PersistentDescriptorAlloc +{ + D3D12_CPU_DESCRIPTOR_HANDLE Handles[DX12::RenderLatency] = { }; + uint32 Index = uint32(-1); +}; + +struct TempDescriptorAlloc +{ + D3D12_CPU_DESCRIPTOR_HANDLE StartCPUHandle = { }; + D3D12_GPU_DESCRIPTOR_HANDLE StartGPUHandle = { }; + uint32 StartIndex = uint32(-1); +}; + +// Wrapper for D3D12 descriptor heaps that supports persistent and temporary allocations +struct DescriptorHeap +{ + ID3D12DescriptorHeap* Heaps[DX12::RenderLatency] = { }; + uint32 NumPersistent = 0; + uint32 PersistentAllocated = 0; + Array DeadList; + uint32 NumTemporary = 0; + volatile int64 TemporaryAllocated = 0; + uint32 HeapIndex = 0; + uint32 NumHeaps = 0; + uint32 DescriptorSize = 0; + bool32 ShaderVisible = false; + D3D12_DESCRIPTOR_HEAP_TYPE HeapType = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + D3D12_CPU_DESCRIPTOR_HANDLE CPUStart[DX12::RenderLatency] = { }; + D3D12_GPU_DESCRIPTOR_HANDLE GPUStart[DX12::RenderLatency] = { }; + SRWLOCK Lock = SRWLOCK_INIT; + + ~DescriptorHeap(); + + void Init(uint32 numPersistent, uint32 numTemporary, D3D12_DESCRIPTOR_HEAP_TYPE heapType, bool shaderVisible); + void Shutdown(); + + PersistentDescriptorAlloc AllocatePersistent(); + void FreePersistent(uint32& idx); + void FreePersistent(D3D12_CPU_DESCRIPTOR_HANDLE& handle); + void FreePersistent(D3D12_GPU_DESCRIPTOR_HANDLE& handle); + + TempDescriptorAlloc AllocateTemporary(uint32 count); + void EndFrame(); + + D3D12_CPU_DESCRIPTOR_HANDLE CPUHandleFromIndex(uint32 descriptorIdx) const; + D3D12_GPU_DESCRIPTOR_HANDLE GPUHandleFromIndex(uint32 descriptorIdx) const; + + D3D12_CPU_DESCRIPTOR_HANDLE CPUHandleFromIndex(uint32 descriptorIdx, uint64 heapIdx) const; + D3D12_GPU_DESCRIPTOR_HANDLE GPUHandleFromIndex(uint32 descriptorIdx, uint64 heapIdx) const; + + uint32 IndexFromHandle(D3D12_CPU_DESCRIPTOR_HANDLE handle); + uint32 IndexFromHandle(D3D12_GPU_DESCRIPTOR_HANDLE handle); + + ID3D12DescriptorHeap* CurrentHeap() const; + uint32 TotalNumDescriptors() const { return NumPersistent + NumTemporary; } +}; + +struct Buffer +{ + ID3D12Resource* Resource = nullptr; + uint64 CurrBuffer = 0; + uint8* CPUAddress = 0; + uint64 GPUAddress = 0; + uint64 Alignment = 0; + uint64 Size = 0; + bool32 Dynamic = false; + bool32 CPUAccessible = false; + ID3D12Heap* Heap = nullptr; + uint64 HeapOffset = 0; + uint64 UploadFrame = uint64(-1); + + Buffer(); + ~Buffer(); + + void Initialize(uint64 size, uint64 alignment, bool32 dynamic, bool32 cpuAccessible, + bool32 allowUAV, const void* initData, ID3D12Heap* heap, uint64 heapOffset, const wchar* name); + void Shutdown(); + + MapResult Map(); + MapResult MapAndSetData(const void* data, uint64 dataSize); + template MapResult MapAndSetData(const T& data) { return MapAndSetData(&data, sizeof(T)); } + uint64 UpdateData(const void* srcData, uint64 srcSize, uint64 dstOffset); + uint64 MultiUpdateData(const void* srcData[], uint64 srcSize[], uint64 dstOffset[], uint64 numUpdates); + + void Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const; + void MakeReadable(ID3D12GraphicsCommandList* cmdList) const; + void MakeWritable(ID3D12GraphicsCommandList* cmdList) const; + void UAVBarrier(ID3D12GraphicsCommandList* cmdList) const; + + bool Initialized() const { return Size > 0; } + + #if UseAsserts_ + bool ReadyForBinding() const; + #endif + +private: + + Buffer(const Buffer& other) { } +}; + +// For aligning to float4 boundaries +#define Float4Align __declspec(align(16)) +#define Float4Align_ __declspec(align(16)) + +struct ConstantBufferInit +{ + uint64 Size = 0; + bool32 Dynamic = true; + bool32 CPUAccessible = true; + const void* InitData = nullptr; + ID3D12Heap* Heap = nullptr; + uint64 HeapOffset = 0; + const wchar* Name = nullptr; +}; + +struct ConstantBuffer +{ + Buffer InternalBuffer; + uint64 CurrentGPUAddress = 0; + + ConstantBuffer(); + ~ConstantBuffer(); + + void Initialize(const ConstantBufferInit& init); + void Shutdown(); + + void SetAsGfxRootParameter(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter) const; + void SetAsComputeRootParameter(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter) const; + + void* Map(); + template T* Map() { return reinterpret_cast(Map()); } + void MapAndSetData(const void* data, uint64 dataSize); + template void MapAndSetData(const T& data) { MapAndSetData(&data, sizeof(T)); } + void UpdateData(const void* srcData, uint64 srcSize, uint64 dstOffset); + void MultiUpdateData(const void* srcData[], uint64 srcSize[], uint64 dstOffset[], uint64 numUpdates); +}; + +struct StructuredBufferInit +{ + uint64 Stride = 0; + uint64 NumElements = 0; + bool32 CreateUAV = false; + bool32 UseCounter = false; + bool32 Dynamic = false; + bool32 CPUAccessible = false; + const void* InitData = nullptr; + ID3D12Heap* Heap = nullptr; + uint64 HeapOffset = 0; + const wchar* Name = nullptr; +}; + +struct StructuredBuffer +{ + Buffer InternalBuffer; + uint64 Stride = 0; + uint64 NumElements = 0; + uint32 SRV = uint32(-1); + D3D12_CPU_DESCRIPTOR_HANDLE UAV = { }; + ID3D12Resource* CounterResource = nullptr; + D3D12_CPU_DESCRIPTOR_HANDLE CounterUAV = { }; + uint64 GPUAddress = 0; + + StructuredBuffer(); + ~StructuredBuffer(); + + void Initialize(const StructuredBufferInit& init); + void Shutdown(); + + D3D12_VERTEX_BUFFER_VIEW VBView() const; + ID3D12Resource* Resource() const { return InternalBuffer.Resource; } + + void* Map(); + template T* Map() { return reinterpret_cast(Map()); } + void MapAndSetData(const void* data, uint64 numElements); + void UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset); + void MultiUpdateData(const void* srcData[], uint64 srcNumElements[], uint64 dstElemOffset[], uint64 numUpdates); + + void Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const; + void MakeReadable(ID3D12GraphicsCommandList* cmdList) const; + void MakeWritable(ID3D12GraphicsCommandList* cmdList) const; + void UAVBarrier(ID3D12GraphicsCommandList* cmdList) const; + +private: + + StructuredBuffer(const StructuredBuffer& other) { } + + D3D12_SHADER_RESOURCE_VIEW_DESC SRVDesc(uint64 bufferIdx) const; + void UpdateDynamicSRV() const; +}; + +struct FormattedBufferInit +{ + DXGI_FORMAT Format = DXGI_FORMAT_UNKNOWN; + uint64 NumElements = 0; + bool32 CreateUAV = false; + bool32 Dynamic = false; + bool32 CPUAccessible = false; + const void* InitData = nullptr; + ID3D12Heap* Heap = nullptr; + uint64 HeapOffset = 0; + const wchar* Name = nullptr; +}; + +struct FormattedBuffer +{ + Buffer InternalBuffer; + uint64 Stride = 0; + uint64 NumElements = 0; + DXGI_FORMAT Format = DXGI_FORMAT_UNKNOWN; + uint32 SRV = uint32(-1); + D3D12_CPU_DESCRIPTOR_HANDLE UAV = { }; + uint64 GPUAddress = 0; + + FormattedBuffer(); + ~FormattedBuffer(); + + void Initialize(const FormattedBufferInit& init); + void Shutdown(); + + D3D12_INDEX_BUFFER_VIEW IBView() const; + ID3D12Resource* Resource() const { return InternalBuffer.Resource; } + + void* Map(); + template T* Map() { return reinterpret_cast(Map()); }; + void MapAndSetData(const void* data, uint64 numElements); + void UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset); + void MultiUpdateData(const void* srcData[], uint64 srcNumElements[], uint64 dstElemOffset[], uint64 numUpdates); + + void Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const; + void MakeReadable(ID3D12GraphicsCommandList* cmdList) const; + void MakeWritable(ID3D12GraphicsCommandList* cmdList) const; + void UAVBarrier(ID3D12GraphicsCommandList* cmdList) const; + +private: + + FormattedBuffer(const FormattedBuffer& other) { } + + D3D12_SHADER_RESOURCE_VIEW_DESC SRVDesc(uint64 bufferIdx) const; + void UpdateDynamicSRV() const; +}; + +struct RawBufferInit +{ + uint64 NumElements = 0; + bool32 CreateUAV = false; + bool32 Dynamic = false; + bool32 CPUAccessible = false; + const void* InitData = nullptr; + ID3D12Heap* Heap = nullptr; + uint64 HeapOffset = 0; + const wchar* Name = nullptr; +}; + +struct RawBuffer +{ + Buffer InternalBuffer; + uint64 NumElements = 0; + uint32 SRV = uint32(-1); + D3D12_CPU_DESCRIPTOR_HANDLE UAV = { }; + uint64 GPUAddress = 0; + + const uint64 Stride = 4; + + RawBuffer(); + ~RawBuffer(); + + void Initialize(const RawBufferInit& init); + void Shutdown(); + + ID3D12Resource* Resource() const { return InternalBuffer.Resource; } + + void* Map(); + template T* Map() { return reinterpret_cast(Map()); }; + void MapAndSetData(const void* data, uint64 numElements); + void UpdateData(const void* srcData, uint64 srcNumElements, uint64 dstElemOffset); + void MultiUpdateData(const void* srcData[], uint64 srcNumElements[], uint64 dstElemOffset[], uint64 numUpdates); + + void Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const; + void MakeReadable(ID3D12GraphicsCommandList* cmdList) const; + void MakeWritable(ID3D12GraphicsCommandList* cmdList) const; + void UAVBarrier(ID3D12GraphicsCommandList* cmdList) const; + +private: + + RawBuffer(const RawBuffer& other) { } + + D3D12_SHADER_RESOURCE_VIEW_DESC SRVDesc(uint64 bufferIdx) const; + void UpdateDynamicSRV() const; +}; + +struct ReadbackBuffer +{ + ID3D12Resource* Resource = nullptr; + uint64 Size = 0; + + ReadbackBuffer(); + ~ReadbackBuffer(); + + void Initialize(uint64 size); + void Shutdown(); + + void* Map(); + template T* Map() { return reinterpret_cast(Map()); }; + void Unmap(); + +private: + + ReadbackBuffer(const ReadbackBuffer& other) { } +}; + +struct Fence +{ + ID3D12Fence* D3DFence = nullptr; + HANDLE FenceEvent = INVALID_HANDLE_VALUE; + + ~Fence(); + + void Init(uint64 initialValue = 0); + void Shutdown(); + + void Signal(ID3D12CommandQueue* queue, uint64 fenceValue); + void Wait(uint64 fenceValue); + bool Signaled(uint64 fenceValue); + void Clear(uint64 fenceValue); +}; + +struct Texture +{ + uint32 SRV = uint32(-1); + ID3D12Resource* Resource = nullptr; + uint32 Width = 0; + uint32 Height = 0; + uint32 Depth = 0; + uint32 NumMips = 0; + uint32 ArraySize = 0; + DXGI_FORMAT Format = DXGI_FORMAT_UNKNOWN; + bool32 Cubemap = false; + + Texture(); + ~Texture(); + + bool Valid() const + { + return Resource != nullptr; + } + + void Shutdown(); + +private: + + Texture(const Texture& other) { } +}; + +struct RenderTextureInit +{ + uint64 Width = 0; + uint64 Height = 0; + DXGI_FORMAT Format = DXGI_FORMAT_UNKNOWN; + uint64 MSAASamples = 1; + uint64 ArraySize = 1; + bool32 CreateUAV = false; + D3D12_RESOURCE_STATES InitialState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + const wchar* Name = nullptr; +}; + +struct RenderTexture +{ + Texture Texture; + D3D12_CPU_DESCRIPTOR_HANDLE RTV = { }; + D3D12_CPU_DESCRIPTOR_HANDLE UAV = { }; + Array ArrayRTVs; + uint32 MSAASamples = 0; + uint32 MSAAQuality = 0; + + RenderTexture(); + ~RenderTexture(); + + void Initialize(const RenderTextureInit& init); + void Shutdown(); + + void Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after, uint64 mipLevel = uint64(-1), uint64 arraySlice = uint64(-1)) const; + void MakeReadable(ID3D12GraphicsCommandList* cmdList, uint64 mipLevel = uint64(-1), uint64 arraySlice = uint64(-1)) const; + void MakeWritable(ID3D12GraphicsCommandList* cmdList, uint64 mipLevel = uint64(-1), uint64 arraySlice = uint64(-1)) const; + void UAVBarrier(ID3D12GraphicsCommandList* cmdList) const; + + uint32 SRV() const { return Texture.SRV; } + uint64 Width() const { return Texture.Width; } + uint64 Height() const { return Texture.Height; } + DXGI_FORMAT Format() const { return Texture.Format; } + ID3D12Resource* Resource() const { return Texture.Resource; } + uint64 SubResourceIndex(uint64 mipLevel, uint64 arraySlice) const { return arraySlice * Texture.NumMips + mipLevel; } + +private: + + RenderTexture(const RenderTexture& other) { } +}; + +struct VolumeTextureInit +{ + uint64 Width = 0; + uint64 Height = 0; + uint64 Depth = 0; + DXGI_FORMAT Format = DXGI_FORMAT_UNKNOWN; + D3D12_RESOURCE_STATES InitialState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + const wchar* Name = nullptr; +}; + +struct VolumeTexture +{ + Texture Texture; + D3D12_CPU_DESCRIPTOR_HANDLE UAV = { }; + + VolumeTexture(); + ~VolumeTexture(); + + void Initialize(const VolumeTextureInit& init); + void Shutdown(); + + void Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const; + void MakeReadable(ID3D12GraphicsCommandList* cmdList) const; + void MakeWritable(ID3D12GraphicsCommandList* cmdList) const; + + uint32 SRV() const { return Texture.SRV; } + uint64 Width() const { return Texture.Width; } + uint64 Height() const { return Texture.Height; } + uint64 Depth() const { return Texture.Depth; } + DXGI_FORMAT Format() const { return Texture.Format; } + ID3D12Resource* Resource() const { return Texture.Resource; } + +private: + + VolumeTexture(const RenderTexture& other) { } +}; + +struct DepthBufferInit +{ + uint64 Width = 0; + uint64 Height = 0; + DXGI_FORMAT Format = DXGI_FORMAT_UNKNOWN; + uint64 MSAASamples = 1; + uint64 ArraySize = 1; + D3D12_RESOURCE_STATES InitialState = D3D12_RESOURCE_STATE_DEPTH_WRITE; + const wchar* Name = nullptr; +}; + +struct DepthBuffer +{ + Texture Texture; + D3D12_CPU_DESCRIPTOR_HANDLE DSV = { }; + D3D12_CPU_DESCRIPTOR_HANDLE ReadOnlyDSV = { }; + Array ArrayDSVs; + uint32 MSAASamples = 0; + uint32 MSAAQuality = 0; + DXGI_FORMAT DSVFormat = DXGI_FORMAT_UNKNOWN; + + DepthBuffer(); + ~DepthBuffer(); + + void Initialize(const DepthBufferInit& init); + void Shutdown(); + + void Transition(ID3D12GraphicsCommandList* cmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after, uint64 arraySlice = uint64(-1)) const; + void MakeReadable(ID3D12GraphicsCommandList* cmdList, uint64 arraySlice = uint64(-1)) const; + void MakeWritable(ID3D12GraphicsCommandList* cmdList, uint64 arraySlice = uint64(-1)) const; + + uint32 SRV() const { return Texture.SRV; } + uint64 Width() const { return Texture.Width; } + uint64 Height() const { return Texture.Height; } + ID3D12Resource* Resource() const { return Texture.Resource; } + +private: + + DepthBuffer(const DepthBuffer& other) { } +}; + +struct PIXMarker +{ + ID3D12GraphicsCommandList* CmdList = nullptr; + + PIXMarker(ID3D12GraphicsCommandList* cmdList, const wchar* msg) : CmdList(cmdList) + { + PIXBeginEvent(cmdList, 0, msg); + } + + PIXMarker(ID3D12GraphicsCommandList* cmdList, const char* msg) : CmdList(cmdList) + { + PIXBeginEvent(cmdList, 0, msg); + } + + ~PIXMarker() + { + PIXEndEvent(CmdList); + } +}; + } \ No newline at end of file diff --git a/SampleFramework12/v1.00/Graphics/Model.cpp b/SampleFramework12/v1.01/Graphics/Model.cpp similarity index 96% rename from SampleFramework12/v1.00/Graphics/Model.cpp rename to SampleFramework12/v1.01/Graphics/Model.cpp index 400b25d..d3711e2 100644 --- a/SampleFramework12/v1.00/Graphics/Model.cpp +++ b/SampleFramework12/v1.01/Graphics/Model.cpp @@ -74,7 +74,7 @@ static Float4x4 ConvertMatrix(const aiMatrix4x4& mat) } void LoadMaterialResources(Array& materials, const wstring& directory, bool32 forceSRGB, - GrowableList& materialTextures, LinearDescriptorHeap& descriptorHeap) + GrowableList& materialTextures) { const uint64 numMaterials = materials.Size(); for(uint64 matIdx = 0; matIdx < numMaterials; ++matIdx) @@ -112,17 +112,6 @@ void LoadMaterialResources(Array& materials, const wstring& direct } } } - - const uint64 numTextures = materialTextures.Count(); - descriptorHeap.Init(DX12::Device, numTextures, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, false); - DescriptorHandle handle = descriptorHeap.Allocate(numTextures); - - for(uint64 i = 0; i < numTextures; ++i) - { - D3D12_CPU_DESCRIPTOR_HANDLE dstHandle = handle.CPUHandle; - dstHandle.ptr += i * DX12::SRVDescriptorSize; - DX12::Device->CopyDescriptorsSimple(1, dstHandle, materialTextures[i]->Texture.SRV.CPUHandle, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - } } void Mesh::InitFromAssimpMesh(const aiMesh& assimpMesh, float sceneScale, MeshVertex* dstVertices, uint16* dstIndices) @@ -191,7 +180,7 @@ void Mesh::InitFromAssimpMesh(const aiMesh& assimpMesh, float sceneScale, MeshVe } const uint64 numSubsets = 1; - meshParts.Init(1); + meshParts.Init(numSubsets); MeshPart& part = meshParts[0]; part.IndexStart = 0; part.IndexCount = numIndices; @@ -299,7 +288,6 @@ void Mesh::InitBox(const Float3& dimensions, const Float3& position, dstIndices[iIdx++] = 20 + 3; dstIndices[iIdx++] = 20 + 0; - const uint32 indexSize = 2; indexType = IndexType::Index16Bit; numVertices = uint32(NumBoxVerts); @@ -339,7 +327,6 @@ void Mesh::InitPlane(const Float2& dimensions, const Float3& position, const Qua dstIndices[iIdx++] = 3; dstIndices[iIdx++] = 0; - const uint32 indexSize = 2; indexType = IndexType::Index16Bit; numVertices = uint32(NumPlaneVerts); @@ -401,6 +388,35 @@ const char* Mesh::InputElementTypeString(InputElementType elemType) // == Model ======================================================================================= +// For some reason the roughness maps aren't coming through in the SHININESS channel after Assimp import. :( +static const wchar_t* SponzaRoughnessMaps[] = { + L"Sponza_Thorn_roughness.png", + L"VasePlant_roughness.png", + L"VaseRound_roughness.png", + L"Background_Roughness.png", + L"Sponza_Bricks_a_Roughness.png", + L"Sponza_Arch_roughness.png", + L"Sponza_Ceiling_roughness.png", + L"Sponza_Column_a_roughness.png", + L"Sponza_Floor_roughness.png", + L"Sponza_Column_c_roughness.png", + L"Sponza_Details_roughness.png", + L"Sponza_Column_b_roughness.png", + nullptr, + L"Sponza_FlagPole_roughness.png", + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + L"ChainTexture_Roughness.png", + L"VaseHanging_roughness.png", + L"Vase_roughness.png", + L"Lion_Roughness.png", + L"Sponza_Roof_roughness.png" +}; + void Model::CreateWithAssimp(const ModelLoadSettings& settings) { const wchar* filePath = settings.FilePath; @@ -507,14 +523,18 @@ void Model::CreateWithAssimp(const ModelLoadSettings& settings) || mat.GetTexture(aiTextureType_HEIGHT, 0, &normalMapPath) == aiReturn_SUCCESS) material.TextureNames[uint64(MaterialTextures::Normal)] = GetFileName(AnsiToWString(normalMapPath.C_Str()).c_str()); - if(mat.GetTexture(aiTextureType_SHININESS, 0, &roughnessMapPath) == aiReturn_SUCCESS) - material.TextureNames[uint64(MaterialTextures::Roughness)] = GetFileName(AnsiToWString(roughnessMapPath.C_Str()).c_str()); + /*if(mat.GetTexture(aiTextureType_SHININESS, 0, &roughnessMapPath) == aiReturn_SUCCESS) + material.TextureNames[uint64(MaterialTextures::Roughness)] = GetFileName(AnsiToWString(roughnessMapPath.C_Str()).c_str());*/ + + // For some reason the roughness maps aren't coming through in the SHININESS channel after Assimp import. :( + if(SponzaRoughnessMaps[i] != nullptr) + material.TextureNames[uint64(MaterialTextures::Roughness)] = GetFileName(SponzaRoughnessMaps[i]); if(mat.GetTexture(aiTextureType_AMBIENT, 0, &metallicMapPath) == aiReturn_SUCCESS) material.TextureNames[uint64(MaterialTextures::Metallic)] = GetFileName(AnsiToWString(metallicMapPath.C_Str()).c_str()); } - LoadMaterialResources(meshMaterials, fileDirectory, settings.ForceSRGB, materialTextures, descriptorHeap); + LoadMaterialResources(meshMaterials, fileDirectory, settings.ForceSRGB, materialTextures); aabbMin = FloatMax; aabbMax = -FloatMax; @@ -570,7 +590,7 @@ void Model::CreateFromMeshData(const wchar* filePath) CreateBuffers(); - LoadMaterialResources(meshMaterials, fileDirectory, forceSRGB, materialTextures, descriptorHeap); + LoadMaterialResources(meshMaterials, fileDirectory, forceSRGB, materialTextures); } void Model::GenerateBoxScene(const Float3& dimensions, const Float3& position, @@ -582,7 +602,7 @@ void Model::GenerateBoxScene(const Float3& dimensions, const Float3& position, material.TextureNames[uint64(MaterialTextures::Albedo)] = colorMap; material.TextureNames[uint64(MaterialTextures::Normal)] = normalMap; fileDirectory = L"..\\Content\\Textures\\"; - LoadMaterialResources(meshMaterials, L"..\\Content\\Textures\\", false, materialTextures, descriptorHeap); + LoadMaterialResources(meshMaterials, L"..\\Content\\Textures\\", false, materialTextures); vertices.Init(NumBoxVerts); indices.Init(NumBoxIndices); @@ -600,7 +620,7 @@ void Model::GenerateBoxTestScene() material.TextureNames[uint64(MaterialTextures::Albedo)] = L"White.png"; material.TextureNames[uint64(MaterialTextures::Normal)] = L"Hex.png"; fileDirectory = L"..\\Content\\Textures\\"; - LoadMaterialResources(meshMaterials, L"..\\Content\\Textures\\", false, materialTextures, descriptorHeap); + LoadMaterialResources(meshMaterials, L"..\\Content\\Textures\\", false, materialTextures); vertices.Init(NumBoxVerts * 2); indices.Init(NumBoxIndices * 2); @@ -621,7 +641,7 @@ void Model::GeneratePlaneScene(const Float2& dimensions, const Float3& position, material.TextureNames[uint64(MaterialTextures::Albedo)] = colorMap; material.TextureNames[uint64(MaterialTextures::Normal)] = normalMap; fileDirectory = L"..\\Content\\Textures\\"; - LoadMaterialResources(meshMaterials, L"..\\Content\\Textures\\", false, materialTextures, descriptorHeap); + LoadMaterialResources(meshMaterials, L"..\\Content\\Textures\\", false, materialTextures); vertices.Init(NumPlaneVerts); indices.Init(NumPlaneIndices); @@ -645,7 +665,6 @@ void Model::Shutdown() materialTextures[i] = nullptr; } materialTextures.Shutdown(); - descriptorHeap.Shutdown(); fileDirectory = L""; forceSRGB = false; diff --git a/SampleFramework12/v1.00/Graphics/Model.h b/SampleFramework12/v1.01/Graphics/Model.h similarity index 97% rename from SampleFramework12/v1.00/Graphics/Model.h rename to SampleFramework12/v1.01/Graphics/Model.h index 09ff174..217f568 100644 --- a/SampleFramework12/v1.00/Graphics/Model.h +++ b/SampleFramework12/v1.01/Graphics/Model.h @@ -80,11 +80,11 @@ struct MeshMaterial const Texture* Textures[uint64(MaterialTextures::Count)] = { }; uint32 TextureIndices[uint64(MaterialTextures::Count)] = { }; - D3D12_CPU_DESCRIPTOR_HANDLE Texture(MaterialTextures texType) const + uint32 Texture(MaterialTextures texType) const { Assert_(uint64(texType) < uint64(MaterialTextures::Count)); Assert_(Textures[uint64(texType)] != nullptr); - return Textures[uint64(texType)]->SRV.CPUHandle; + return Textures[uint64(texType)]->SRV; } template void Serialize(TSerializer& serializer) @@ -279,7 +279,6 @@ class Model const Array& Materials() const { return meshMaterials; } const GrowableList& MaterialTextures() const { return materialTextures; } - D3D12_CPU_DESCRIPTOR_HANDLE MaterialTextureDescriptors() const { return descriptorHeap.CPUStart; } const Array& SpotLights() const { return spotLights; } const Array& PointLights() const { return pointLights; } @@ -287,6 +286,8 @@ class Model const StructuredBuffer& VertexBuffer() const { return vertexBuffer; } const FormattedBuffer& IndexBuffer() const { return indexBuffer; } + const std::wstring& FileDirectory() const { return fileDirectory; } + static const D3D12_INPUT_ELEMENT_DESC* InputElements(); static const InputElementType* InputElementTypes(); static uint64 NumInputElements(); @@ -325,7 +326,6 @@ class Model Array indices; GrowableList materialTextures; - LinearDescriptorHeap descriptorHeap; }; void MakeSphereGeometry(uint64 uDivisions, uint64 vDivisions, StructuredBuffer& vtxBuffer, FormattedBuffer& idxBuffer); diff --git a/SampleFramework12/v1.00/Graphics/PostProcessHelper.cpp b/SampleFramework12/v1.01/Graphics/PostProcessHelper.cpp similarity index 73% rename from SampleFramework12/v1.00/Graphics/PostProcessHelper.cpp rename to SampleFramework12/v1.01/Graphics/PostProcessHelper.cpp index 2e55f6e..b99f472 100644 --- a/SampleFramework12/v1.00/Graphics/PostProcessHelper.cpp +++ b/SampleFramework12/v1.01/Graphics/PostProcessHelper.cpp @@ -1,265 +1,279 @@ -//================================================================================================= -// -// MJP's DX12 Sample Framework -// http://mynameismjp.wordpress.com/ -// -// All code licensed under the MIT license -// -//================================================================================================= - -#include "PCH.h" - -#include "PostProcessHelper.h" - -#include "..\\Utility.h" -#include "ShaderCompilation.h" -#include "DX12.h" - -namespace AppSettings -{ - const extern uint32 CBufferRegister; - void BindCBufferGfx(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter); -} - -namespace SampleFramework12 -{ - -static const uint32 MaxInputs = 8; - -PostProcessHelper::PostProcessHelper() -{ -} - -PostProcessHelper::~PostProcessHelper() -{ - Assert_(tempRenderTargets.Count() == 0); - Assert_(pipelineStates.Count() == 0); -} - -void PostProcessHelper::Initialize() -{ - // Load the shaders - std::wstring fullScreenTriPath = SampleFrameworkDir() + L"Shaders\\FullScreenTriangle.hlsl"; - fullScreenTriVS = CompileFromFile(fullScreenTriPath.c_str(), "FullScreenTriangleVS", ShaderType::Vertex, ShaderProfile::SM51); - - { - D3D12_DESCRIPTOR_RANGE1 srvRanges[1] = {}; - srvRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - srvRanges[0].NumDescriptors = MaxInputs; - srvRanges[0].BaseShaderRegister = 0; - srvRanges[0].RegisterSpace = 0; - srvRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - D3D12_ROOT_PARAMETER1 rootParameters[2] = {}; - - // AppSettings - rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[0].Descriptor.RegisterSpace = 0; - rootParameters[0].Descriptor.ShaderRegister = AppSettings::CBufferRegister; - - // SRV descriptors - rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[1].DescriptorTable.pDescriptorRanges = srvRanges; - rootParameters[1].DescriptorTable.NumDescriptorRanges = 1; - - D3D12_STATIC_SAMPLER_DESC staticSamplers[4] = {}; - staticSamplers[0] = DX12::GetStaticSamplerState(SamplerState::Point, 0); - staticSamplers[1] = DX12::GetStaticSamplerState(SamplerState::LinearClamp, 1); - staticSamplers[2] = DX12::GetStaticSamplerState(SamplerState::Linear, 2); - staticSamplers[3] = DX12::GetStaticSamplerState(SamplerState::LinearBorder, 3); - - D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; - rootSignatureDesc.NumParameters = ArraySize_(rootParameters); - rootSignatureDesc.pParameters = rootParameters; - rootSignatureDesc.NumStaticSamplers = ArraySize_(staticSamplers); - rootSignatureDesc.pStaticSamplers = staticSamplers; - rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; - - DX12::CreateRootSignature(&rootSignature, rootSignatureDesc); - rootSignature->SetName(L"PostProcessHelper"); - } -} - -void PostProcessHelper::Shutdown() -{ - ClearCache(); - - DX12::Release(rootSignature); -} - -void PostProcessHelper::ClearCache() -{ - for(uint64 i = 0; i < tempRenderTargets.Count(); ++i) - { - TempRenderTarget* tempRT = tempRenderTargets[i]; - tempRT->RT.Shutdown(); - delete tempRT; - } - - tempRenderTargets.RemoveAll(nullptr); - - for(uint64 i = 0; i < pipelineStates.Count(); ++i) - DX12::DeferredRelease(pipelineStates[i].PSO); - - pipelineStates.RemoveAll(CachedPSO()); -} - -TempRenderTarget* PostProcessHelper::GetTempRenderTarget(uint64 width, uint64 height, DXGI_FORMAT format, bool useAsUAV) -{ - for(uint64 i = 0; i < tempRenderTargets.Count(); ++i) - { - TempRenderTarget* tempRT = tempRenderTargets[i]; - if(tempRT->InUse) - continue; - - const RenderTexture& rt = tempRT->RT; - if(rt.Texture.Width == width && rt.Texture.Height == height && rt.Texture.Format == format && useAsUAV == rt.UAV.IsValid()) { - tempRT->InUse = true; - return tempRT; - } - } - - TempRenderTarget* tempRT = new TempRenderTarget(); - tempRT->RT.Initialize(width, height, format, 1, 1, useAsUAV); - tempRT->RT.Texture.Resource->SetName(L"PP Temp Render Target"); - tempRT->InUse = true; - tempRenderTargets.Add(tempRT); - - return tempRT; -} - -void PostProcessHelper::Begin(ID3D12GraphicsCommandList* cmdList_) -{ - Assert_(cmdList == nullptr); - cmdList = cmdList_; -} - -void PostProcessHelper::End() -{ - Assert_(cmdList != nullptr); - cmdList = nullptr; - - for(uint64 i = 0; i < tempRenderTargets.Count(); ++i) - Assert_(tempRenderTargets[i]->InUse == false); -} - -void PostProcessHelper::PostProcess(CompiledShaderPtr pixelShader, const char* name, const RenderTexture& input, const RenderTexture& output) -{ - D3D12_CPU_DESCRIPTOR_HANDLE inputs[1] = { input.SRV() }; - const RenderTexture* outputs[1] = { &output }; - PostProcess(pixelShader, name, inputs, 1, outputs, 1); -} - -void PostProcessHelper::PostProcess(CompiledShaderPtr pixelShader, const char* name, const RenderTexture& input, const TempRenderTarget* output) -{ - D3D12_CPU_DESCRIPTOR_HANDLE inputs[1] = { input.SRV() }; - const RenderTexture* outputs[1] = { &output->RT }; - PostProcess(pixelShader, name, inputs, 1, outputs, 1); -} - -void PostProcessHelper::PostProcess(CompiledShaderPtr pixelShader, const char* name, const TempRenderTarget* input, const RenderTexture& output) -{ - D3D12_CPU_DESCRIPTOR_HANDLE inputs[1] = { input->RT.SRV() }; - const RenderTexture* outputs[1] = { &output }; - PostProcess(pixelShader, name, inputs, 1, outputs, 1); -} - -void PostProcessHelper::PostProcess(CompiledShaderPtr pixelShader, const char* name, const TempRenderTarget* input, const TempRenderTarget* output) -{ - D3D12_CPU_DESCRIPTOR_HANDLE inputs[1] = { input->RT.SRV() }; - const RenderTexture* outputs[1] = { &output->RT }; - PostProcess(pixelShader, name, inputs, 1, outputs, 1); -} - -struct HashSource -{ - DXGI_FORMAT OutputFormats[8] = { }; - uint64 MSAASamples = 0; -}; - -void PostProcessHelper::PostProcess(CompiledShaderPtr pixelShader, const char* name, const D3D12_CPU_DESCRIPTOR_HANDLE* inputs, uint64 numInputs, - const RenderTexture*const* outputs, uint64 numOutputs) -{ - Assert_(cmdList != nullptr); - Assert_(numOutputs > 0); - Assert_(outputs != nullptr); - Assert_(numInputs == 0 || inputs != nullptr); - Assert_(numInputs <= MaxInputs); - - PIXMarker marker(cmdList, name); - - HashSource hashSource; - for(uint64 i = 0; i < numOutputs; ++i) - { - hashSource.OutputFormats[i] = outputs[i]->Texture.Format; - hashSource.MSAASamples = outputs[i]->MSAASamples; - } - - Hash psoHash = GenerateHash(&hashSource, sizeof(HashSource)); - psoHash = CombineHashes(psoHash, pixelShader->ByteCodeHash); - - ID3D12PipelineState* pso = nullptr; - - // The most linear of searches! - const uint64 numPSOs = pipelineStates.Count(); - for(uint64 i = 0; i < numPSOs; ++i) - { - if(pipelineStates[i].Hash == psoHash) - { - pso = pipelineStates[i].PSO; - break; - } - } - - if(pso == nullptr) - { - D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; - psoDesc.pRootSignature = rootSignature; - psoDesc.VS = fullScreenTriVS.ByteCode(); - psoDesc.PS = pixelShader.ByteCode(); - psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::NoCull); - psoDesc.BlendState = DX12::GetBlendState(BlendState::Disabled); - psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::Disabled); - psoDesc.SampleMask = UINT_MAX; - psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - psoDesc.NumRenderTargets = uint32(numOutputs); - for(uint64 i = 0; i < numOutputs; ++i) - psoDesc.RTVFormats[i] = hashSource.OutputFormats[i]; - psoDesc.DSVFormat = DXGI_FORMAT_UNKNOWN; - psoDesc.SampleDesc.Count = uint32(hashSource.MSAASamples); - DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&pso))); - - CachedPSO cachedPSO; - cachedPSO.Hash = psoHash; - cachedPSO.PSO = pso; - pipelineStates.Add(cachedPSO); - } - - D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[8] = { }; - for(uint64 i = 0; i < numOutputs; ++i) - rtvHandles[i] = outputs[i]->RTV.CPUHandle; - cmdList->OMSetRenderTargets(uint32(numOutputs), rtvHandles, false, nullptr); - - cmdList->SetGraphicsRootSignature(rootSignature); - cmdList->SetPipelineState(pso); - - AppSettings::BindCBufferGfx(cmdList, 0); - - D3D12_CPU_DESCRIPTOR_HANDLE srvHandles[MaxInputs] = { }; - for(uint64 i = 0; i < numInputs; ++i) - srvHandles[i] = inputs[i]; - for(uint64 i = numInputs; i < MaxInputs; ++i) - srvHandles[i] = DX12::NullTexture2DSRV.CPUHandle; - - DX12::BindShaderResources(cmdList, 1, MaxInputs, srvHandles); - - DX12::SetViewport(cmdList, outputs[0]->Texture.Width, outputs[0]->Texture.Height); - - cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - cmdList->DrawInstanced(3, 1, 0, 0); - -} - +//================================================================================================= +// +// MJP's DX12 Sample Framework +// http://mynameismjp.wordpress.com/ +// +// All code licensed under the MIT license +// +//================================================================================================= + +#include "PCH.h" + +#include "PostProcessHelper.h" + +#include "..\\Utility.h" +#include "ShaderCompilation.h" +#include "DX12.h" + +namespace AppSettings +{ + const extern uint32 CBufferRegister; + void BindCBufferGfx(ID3D12GraphicsCommandList* cmdList, uint32 rootParameter); +} + +namespace SampleFramework12 +{ + +static const uint32 MaxInputs = 8; + +enum RootParams : uint32 +{ + RootParam_StandardDescriptors, + RootParam_SRVIndices, + RootParam_AppSettings, + + NumRootParams, +}; + +PostProcessHelper::PostProcessHelper() +{ +} + +PostProcessHelper::~PostProcessHelper() +{ + Assert_(tempRenderTargets.Count() == 0); + Assert_(pipelineStates.Count() == 0); +} + +void PostProcessHelper::Initialize() +{ + // Load the shaders + std::wstring fullScreenTriPath = SampleFrameworkDir() + L"Shaders\\FullScreenTriangle.hlsl"; + fullScreenTriVS = CompileFromFile(fullScreenTriPath.c_str(), "FullScreenTriangleVS", ShaderType::Vertex); + + { + D3D12_ROOT_PARAMETER1 rootParameters[NumRootParams] = {}; + + rootParameters[RootParam_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[RootParam_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[RootParam_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[RootParam_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + rootParameters[RootParam_SRVIndices].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[RootParam_SRVIndices].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[RootParam_SRVIndices].Descriptor.RegisterSpace = 0; + rootParameters[RootParam_SRVIndices].Descriptor.ShaderRegister = 0; + + rootParameters[RootParam_AppSettings].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[RootParam_AppSettings].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[RootParam_AppSettings].Descriptor.RegisterSpace = 0; + rootParameters[RootParam_AppSettings].Descriptor.ShaderRegister = AppSettings::CBufferRegister; + + D3D12_STATIC_SAMPLER_DESC staticSamplers[4] = {}; + staticSamplers[0] = DX12::GetStaticSamplerState(SamplerState::Point, 0); + staticSamplers[1] = DX12::GetStaticSamplerState(SamplerState::LinearClamp, 1); + staticSamplers[2] = DX12::GetStaticSamplerState(SamplerState::Linear, 2); + staticSamplers[3] = DX12::GetStaticSamplerState(SamplerState::LinearBorder, 3); + + D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; + rootSignatureDesc.NumParameters = ArraySize_(rootParameters); + rootSignatureDesc.pParameters = rootParameters; + rootSignatureDesc.NumStaticSamplers = ArraySize_(staticSamplers); + rootSignatureDesc.pStaticSamplers = staticSamplers; + rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + + DX12::CreateRootSignature(&rootSignature, rootSignatureDesc); + rootSignature->SetName(L"PostProcessHelper"); + } +} + +void PostProcessHelper::Shutdown() +{ + ClearCache(); + + DX12::Release(rootSignature); +} + +void PostProcessHelper::ClearCache() +{ + for(uint64 i = 0; i < tempRenderTargets.Count(); ++i) + { + TempRenderTarget* tempRT = tempRenderTargets[i]; + tempRT->RT.Shutdown(); + delete tempRT; + } + + tempRenderTargets.RemoveAll(nullptr); + + for(uint64 i = 0; i < pipelineStates.Count(); ++i) + DX12::DeferredRelease(pipelineStates[i].PSO); + + pipelineStates.RemoveAll(CachedPSO()); +} + +TempRenderTarget* PostProcessHelper::GetTempRenderTarget(uint64 width, uint64 height, DXGI_FORMAT format, bool useAsUAV) +{ + for(uint64 i = 0; i < tempRenderTargets.Count(); ++i) + { + TempRenderTarget* tempRT = tempRenderTargets[i]; + if(tempRT->InUse) + continue; + + const RenderTexture& rt = tempRT->RT; + if(rt.Texture.Width == width && rt.Texture.Height == height && rt.Texture.Format == format && useAsUAV == (rt.UAV.ptr != 0)) { + tempRT->InUse = true; + return tempRT; + } + } + + RenderTextureInit rtInit; + rtInit.Width = width; + rtInit.Height = height; + rtInit.Format = format; + rtInit.CreateUAV = useAsUAV; + rtInit.InitialState = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + + TempRenderTarget* tempRT = new TempRenderTarget(); + tempRT->RT.Initialize(rtInit); + tempRT->RT.Texture.Resource->SetName(L"PP Temp Render Target"); + tempRT->InUse = true; + tempRenderTargets.Add(tempRT); + + return tempRT; +} + +void PostProcessHelper::Begin(ID3D12GraphicsCommandList* cmdList_) +{ + Assert_(cmdList == nullptr); + cmdList = cmdList_; +} + +void PostProcessHelper::End() +{ + Assert_(cmdList != nullptr); + cmdList = nullptr; + + for(uint64 i = 0; i < tempRenderTargets.Count(); ++i) + Assert_(tempRenderTargets[i]->InUse == false); +} + +void PostProcessHelper::PostProcess(CompiledShaderPtr pixelShader, const char* name, const RenderTexture& input, const RenderTexture& output) +{ + uint32 inputs[1] = { input.SRV() }; + const RenderTexture* outputs[1] = { &output }; + PostProcess(pixelShader, name, inputs, 1, outputs, 1); +} + +void PostProcessHelper::PostProcess(CompiledShaderPtr pixelShader, const char* name, const RenderTexture& input, const TempRenderTarget* output) +{ + uint32 inputs[1] = { input.SRV() }; + const RenderTexture* outputs[1] = { &output->RT }; + PostProcess(pixelShader, name, inputs, 1, outputs, 1); +} + +void PostProcessHelper::PostProcess(CompiledShaderPtr pixelShader, const char* name, const TempRenderTarget* input, const RenderTexture& output) +{ + uint32 inputs[1] = { input->RT.SRV() }; + const RenderTexture* outputs[1] = { &output }; + PostProcess(pixelShader, name, inputs, 1, outputs, 1); +} + +void PostProcessHelper::PostProcess(CompiledShaderPtr pixelShader, const char* name, const TempRenderTarget* input, const TempRenderTarget* output) +{ + uint32 inputs[1] = { input->RT.SRV() }; + const RenderTexture* outputs[1] = { &output->RT }; + PostProcess(pixelShader, name, inputs, 1, outputs, 1); +} + +struct HashSource +{ + DXGI_FORMAT OutputFormats[8] = { }; + uint64 MSAASamples = 0; +}; + +void PostProcessHelper::PostProcess(CompiledShaderPtr pixelShader, const char* name, const uint32* inputs, uint64 numInputs, + const RenderTexture*const* outputs, uint64 numOutputs) +{ + Assert_(cmdList != nullptr); + Assert_(numOutputs > 0); + Assert_(outputs != nullptr); + Assert_(numInputs == 0 || inputs != nullptr); + Assert_(numInputs <= MaxInputs); + + PIXMarker marker(cmdList, name); + + HashSource hashSource; + for(uint64 i = 0; i < numOutputs; ++i) + { + hashSource.OutputFormats[i] = outputs[i]->Texture.Format; + hashSource.MSAASamples = outputs[i]->MSAASamples; + } + + Hash psoHash = GenerateHash(&hashSource, sizeof(HashSource)); + psoHash = CombineHashes(psoHash, pixelShader->ByteCodeHash); + + ID3D12PipelineState* pso = nullptr; + + // The most linear of searches! + const uint64 numPSOs = pipelineStates.Count(); + for(uint64 i = 0; i < numPSOs; ++i) + { + if(pipelineStates[i].Hash == psoHash) + { + pso = pipelineStates[i].PSO; + break; + } + } + + if(pso == nullptr) + { + D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; + psoDesc.pRootSignature = rootSignature; + psoDesc.VS = fullScreenTriVS.ByteCode(); + psoDesc.PS = pixelShader.ByteCode(); + psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::NoCull); + psoDesc.BlendState = DX12::GetBlendState(BlendState::Disabled); + psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::Disabled); + psoDesc.SampleMask = UINT_MAX; + psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + psoDesc.NumRenderTargets = uint32(numOutputs); + for(uint64 i = 0; i < numOutputs; ++i) + psoDesc.RTVFormats[i] = hashSource.OutputFormats[i]; + psoDesc.DSVFormat = DXGI_FORMAT_UNKNOWN; + psoDesc.SampleDesc.Count = uint32(hashSource.MSAASamples); + DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&pso))); + + CachedPSO cachedPSO; + cachedPSO.Hash = psoHash; + cachedPSO.PSO = pso; + pipelineStates.Add(cachedPSO); + } + + D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[8] = { }; + for(uint64 i = 0; i < numOutputs; ++i) + rtvHandles[i] = outputs[i]->RTV; + cmdList->OMSetRenderTargets(uint32(numOutputs), rtvHandles, false, nullptr); + + cmdList->SetGraphicsRootSignature(rootSignature); + cmdList->SetPipelineState(pso); + + DX12::BindStandardDescriptorTable(cmdList, RootParam_StandardDescriptors, CmdListMode::Graphics); + + AppSettings::BindCBufferGfx(cmdList, RootParam_AppSettings); + + uint32 srvIndices[MaxInputs] = { }; + for(uint64 i = 0; i < numInputs; ++i) + srvIndices[i] = inputs[i]; + for(uint64 i = numInputs; i < MaxInputs; ++i) + srvIndices[i] = DX12::NullTexture2DSRV; + + DX12::BindTempConstantBuffer(cmdList, srvIndices, RootParam_SRVIndices, CmdListMode::Graphics); + + DX12::SetViewport(cmdList, outputs[0]->Texture.Width, outputs[0]->Texture.Height); + + cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + cmdList->DrawInstanced(3, 1, 0, 0); + +} + } \ No newline at end of file diff --git a/SampleFramework12/v1.00/Graphics/PostProcessHelper.h b/SampleFramework12/v1.01/Graphics/PostProcessHelper.h similarity index 96% rename from SampleFramework12/v1.00/Graphics/PostProcessHelper.h rename to SampleFramework12/v1.01/Graphics/PostProcessHelper.h index b6d78a1..3f3aee3 100644 --- a/SampleFramework12/v1.00/Graphics/PostProcessHelper.h +++ b/SampleFramework12/v1.01/Graphics/PostProcessHelper.h @@ -50,7 +50,7 @@ class PostProcessHelper void PostProcess(CompiledShaderPtr pixelShader, const char* name, const RenderTexture& input, const TempRenderTarget* output); void PostProcess(CompiledShaderPtr pixelShader, const char* name, const TempRenderTarget* input, const RenderTexture& output); void PostProcess(CompiledShaderPtr pixelShader, const char* name, const TempRenderTarget* input, const TempRenderTarget* output); - void PostProcess(CompiledShaderPtr pixelShader, const char* name, const D3D12_CPU_DESCRIPTOR_HANDLE* inputs, uint64 numInputs, + void PostProcess(CompiledShaderPtr pixelShader, const char* name, const uint32* inputs, uint64 numInputs, const RenderTexture*const* outputs, uint64 numOutputs); protected: diff --git a/SampleFramework12/v1.00/Graphics/Profiler.cpp b/SampleFramework12/v1.01/Graphics/Profiler.cpp similarity index 96% rename from SampleFramework12/v1.00/Graphics/Profiler.cpp rename to SampleFramework12/v1.01/Graphics/Profiler.cpp index ba64f5e..3b2edb1 100644 --- a/SampleFramework12/v1.00/Graphics/Profiler.cpp +++ b/SampleFramework12/v1.01/Graphics/Profiler.cpp @@ -11,6 +11,7 @@ #include "Profiler.h" #include "DX12.h" #include "..\\Utility.h" +#include "..\\ImGui\ImGui.h" using std::wstring; using std::map; @@ -192,7 +193,7 @@ static void UpdateProfile(ProfileData& profile, uint64 profileIdx, bool drawText { time = double(profile.EndTime - profile.StartTime) / 1000.0; } - else + else if(frameQueryData) { Assert_(frameQueryData != nullptr); @@ -200,9 +201,12 @@ static void UpdateProfile(ProfileData& profile, uint64 profileIdx, bool drawText uint64 startTime = frameQueryData[profileIdx * 2 + 0]; uint64 endTime = frameQueryData[profileIdx * 2 + 1]; - uint64 delta = endTime - startTime; - double frequency = double(gpuFrequency); - time = (delta / frequency) * 1000.0; + if(endTime > startTime) + { + uint64 delta = endTime - startTime; + double frequency = double(gpuFrequency); + time = (delta / frequency) * 1000.0; + } } profile.TimeSamples[profile.CurrSample] = time; @@ -301,6 +305,8 @@ void Profiler::EndFrame(uint32 displayWidth, uint32 displayHeight) if(enableGPUProfiling) readbackBuffer.Unmap(); + + enableGPUProfiling = showUI; } // == ProfileBlock ================================================================================ diff --git a/SampleFramework12/v1.00/Graphics/Profiler.h b/SampleFramework12/v1.01/Graphics/Profiler.h similarity index 100% rename from SampleFramework12/v1.00/Graphics/Profiler.h rename to SampleFramework12/v1.01/Graphics/Profiler.h diff --git a/SampleFramework12/v1.00/Graphics/SH.cpp b/SampleFramework12/v1.01/Graphics/SH.cpp similarity index 100% rename from SampleFramework12/v1.00/Graphics/SH.cpp rename to SampleFramework12/v1.01/Graphics/SH.cpp diff --git a/SampleFramework12/v1.00/Graphics/SH.h b/SampleFramework12/v1.01/Graphics/SH.h similarity index 100% rename from SampleFramework12/v1.00/Graphics/SH.h rename to SampleFramework12/v1.01/Graphics/SH.h diff --git a/SampleFramework12/v1.00/Graphics/Sampling.cpp b/SampleFramework12/v1.01/Graphics/Sampling.cpp similarity index 87% rename from SampleFramework12/v1.00/Graphics/Sampling.cpp rename to SampleFramework12/v1.01/Graphics/Sampling.cpp index 515b394..e8ff4de 100644 --- a/SampleFramework12/v1.00/Graphics/Sampling.cpp +++ b/SampleFramework12/v1.01/Graphics/Sampling.cpp @@ -278,6 +278,7 @@ Float3 SampleDirectionCosineHemisphere(float u1, float u2) return dir; } +// Returns a random direction from within a cone with angle == theta Float3 SampleDirectionCone(float u1, float u2, float cosThetaMax) { float cosTheta = (1.0f - u1) + u1 * cosThetaMax; @@ -286,6 +287,32 @@ Float3 SampleDirectionCone(float u1, float u2, float cosThetaMax) return Float3(std::cos(phi) * sinTheta, std::sin(phi) * sinTheta, cosTheta); } +// Returns a direction that samples a rectangular area light +Float3 SampleDirectionRectangularLight(float u1, float u2, const Float3& sourcePos, + const Float2& lightSize, const Float3& lightPos, + const Quaternion lightOrientation, float& distanceToLight) +{ + float x = u1 - 0.5f; + float y = u2 - 0.5f; + + Float3x3 lightBasis = lightOrientation.ToFloat3x3(); + Float3 lightBasisX = lightBasis.Right(); + Float3 lightBasisY = lightBasis.Up(); + Float3 lightBasisZ = lightBasis.Forward(); + + // Pick random sample point + Float3 samplePos = lightPos + + lightBasisX * x * lightSize.x + + lightBasisY * y * lightSize.y; + + Float3 sampleDir = samplePos - sourcePos; + distanceToLight = Float3::Length(sampleDir); + if(distanceToLight > 0.0f) + sampleDir /= distanceToLight; + + return sampleDir; +} + // Returns the PDF for a particular GGX sample float SampleDirectionGGX_PDF(const Float3& n, const Float3& h, const Float3& v, float roughness) { @@ -297,21 +324,45 @@ float SampleDirectionGGX_PDF(const Float3& n, const Float3& h, const Float3& v, return pM / (4 * hDotV); } +// Returns the (constant) PDF of sampling uniform directions on the unit sphere float SampleDirectionSphere_PDF() { return 1.0f / (Pi * 4.0f); } +// Returns the (constant) PDF of sampling uniform directions on a unit hemisphere float SampleDirectionHemisphere_PDF() { return 1.0f / (Pi * 2.0f); } +// Returns the PDF of of a single sample on a cosine-weighted hemisphere +float SampleDirectionCosineHemisphere_PDF(float cosTheta) +{ + return cosTheta / Pi; +} + +// Returns the PDF of of a single sample on a cosine-weighted hemisphere +float SampleDirectionCosineHemisphere_PDF(const Float3& normal, const Float3& sampleDir) +{ + return Saturate(Float3::Dot(normal, sampleDir)) / Pi; +} + +// Returns the PDF of of a single uniform sample within a cone float SampleDirectionCone_PDF(float cosThetaMax) { return 1.0f / (2.0f * Pi * (1.0f - cosThetaMax)); } +// Returns the PDF of of a single sample on a rectangular area light +float SampleDirectionRectangularLight_PDF(const Float2& lightSize, const Float3& sampleDir, + const Quaternion lightOrientation, float distanceToLight) +{ + Float3 lightBasisZ = Float3::Transform(Float3(0.0f, 0.0f, -1.0f), lightOrientation); + float areaNDotL = Saturate(Float3::Dot(sampleDir, lightBasisZ)); + return (distanceToLight * distanceToLight) / (areaNDotL * lightSize.x * lightSize.y); +} + // Computes a radical inverse with base 2 using crazy bit-twiddling from "Hacker's Delight" float RadicalInverseBase2(uint32 bits) { diff --git a/SampleFramework12/v1.00/Graphics/Sampling.h b/SampleFramework12/v1.01/Graphics/Sampling.h similarity index 78% rename from SampleFramework12/v1.00/Graphics/Sampling.h rename to SampleFramework12/v1.01/Graphics/Sampling.h index fb2e96b..2a2e767 100644 --- a/SampleFramework12/v1.00/Graphics/Sampling.h +++ b/SampleFramework12/v1.01/Graphics/Sampling.h @@ -22,12 +22,19 @@ Float3 SampleDirectionSphere(float u1, float u2); Float3 SampleDirectionHemisphere(float u1, float u2); Float3 SampleDirectionCosineHemisphere(float u1, float u2); Float3 SampleDirectionCone(float u1, float u2, float cosThetaMax); +Float3 SampleDirectionRectangularLight(float u1, float u2, const Float3& sourcePos, + const Float2& lightSize, const Float3& lightPos, + const Quaternion lightOrientation, float& distanceToLight); // PDF functions float SampleDirectionGGX_PDF(const Float3& n, const Float3& h, const Float3& v, float roughness); float SampleDirectionSphere_PDF(); float SampleDirectionHemisphere_PDF(); +float SampleDirectionCosineHemisphere_PDF(float cosTheta); +float SampleDirectionCosineHemisphere_PDF(const Float3& normal, const Float3& sampleDir); float SampleDirectionCone_PDF(float cosThetaMax); +float SampleDirectionRectangularLight_PDF(const Float2& lightSize, const Float3& sampleDir, + const Quaternion lightOrientation, float distanceToLight); // Random sample generation Float2 Hammersley2D(uint64 sampleIdx, uint64 numSamples); diff --git a/SampleFramework12/v1.00/Graphics/ShaderCompilation.cpp b/SampleFramework12/v1.01/Graphics/ShaderCompilation.cpp similarity index 65% rename from SampleFramework12/v1.00/Graphics/ShaderCompilation.cpp rename to SampleFramework12/v1.01/Graphics/ShaderCompilation.cpp index dde3a17..86208f8 100644 --- a/SampleFramework12/v1.00/Graphics/ShaderCompilation.cpp +++ b/SampleFramework12/v1.01/Graphics/ShaderCompilation.cpp @@ -10,6 +10,7 @@ #include "PCH.h" #include "ShaderCompilation.h" +#include "DX12.h" #include "..\\Utility.h" #include "..\\Exceptions.h" @@ -26,17 +27,45 @@ using std::map; namespace SampleFramework12 { +static const uint64 CacheVersion = 0; + static const char* TypeStrings[] = { "vertex", "hull", "domain", "geometry", "pixel", "compute" }; StaticAssert_(ArraySize_(TypeStrings) == uint64(ShaderType::NumTypes)); -static const uint64 TotalNumProfiles = uint64(ShaderType::NumTypes) * uint64(ShaderProfile::NumProfiles); static const char* ProfileStrings[] = { - "vs_5_0", "hs_5_0", "ds_5_0", "gs_5_0", "ps_5_0", "cs_5_0", - "vs_5_1", "hs_5_1", "ds_5_1", "gs_5_1", "ps_5_1", "cs_5_1", + #if EnableShaderModel6_ + "vs_6_0", "hs_6_0", "ds_6_0", "gs_6_0", "ps_6_0", "cs_6_0", + #else + "vs_5_1", "hs_5_1", "ds_5_1", "gs_5_1", "ps_5_1", "cs_5_1", + #endif }; -StaticAssert_(ArraySize_(ProfileStrings) == TotalNumProfiles); +StaticAssert_(ArraySize_(ProfileStrings) == uint64(ShaderType::NumTypes)); + +static Hash MakeCompilerHash() +{ + #if EnableShaderModel6_ + HMODULE module = LoadLibrary(L"dxcompiler.dll"); + #else + HMODULE module = LoadLibrary(L"d3dcompiler_47.dll"); + #endif + + if(module == nullptr) + throw Exception(L"Failed to load compiler DLL"); + + wchar dllPath[1024] = { }; + GetModuleFileName(module, dllPath, ArraySize_(dllPath)); + + File dllFile(dllPath, FileOpenMode::Read); + uint64 fileSize = dllFile.Size(); + Array fileData(fileSize); + dllFile.Read(fileSize, fileData.Data()); + + return GenerateHash(fileData.Data(), int32(fileSize)); +} + +static Hash CompilerHash = MakeCompilerHash(); static string GetExpandedShaderCode(const wchar* path, GrowableList& filePaths) { @@ -48,6 +77,10 @@ static string GetExpandedShaderCode(const wchar* path, GrowableList& fi string fileContents = ReadFileAsString(path); + wstring fileDirectory = GetDirectoryFromFilePath(path); + if(fileDirectory.length() > 0) + fileDirectory += L"\\"; + // Look for includes size_t lineStart = 0; while(true) @@ -68,7 +101,7 @@ static string GetExpandedShaderCode(const wchar* path, GrowableList& fi { size_t endQuote = line.find('\"', startQuote + 1); string includePath = line.substr(startQuote + 1, endQuote - startQuote - 1); - fullIncludePath = AnsiToWString(includePath.c_str()); + fullIncludePath = fileDirectory + AnsiToWString(includePath.c_str()); } else { @@ -135,7 +168,10 @@ static wstring MakeShaderCacheName(const std::string& shaderCode, const char* fu hashString += MakeDefinesString(defines); + hashString += ToAnsiString(CacheVersion); + Hash codeHash = GenerateHash(hashString.data(), int(hashString.length()), 0); + codeHash = CombineHashes(codeHash, CompilerHash); return cacheDir + codeHash.ToString() + L".cache"; } @@ -169,8 +205,135 @@ class FrameworkInclude : public ID3DInclude } }; -static ID3DBlob* CompileShader(const wchar* path, const char* functionName, ShaderType type, ShaderProfile profile, - const D3D_SHADER_MACRO* defines, bool forceOptimization, GrowableList& filePaths) +#if EnableShaderModel6_ + +struct Blob : public ID3DBlob +{ + Array Data; + uint32 RefCount = 1; + + void* GetBufferPointer() override + { + return Data.Data(); + } + + size_t GetBufferSize() override + { + return Data.MemorySize(); + } + + ULONG AddRef() override + { + return ++RefCount; + } + + ULONG Release() override + { + if(RefCount == 1) + { + delete this; + return 0; + } + else if(RefCount > 1) + { + return --RefCount; + } + else + { + Assert_(false); + return 0; + } + } + + HRESULT QueryInterface(REFIID riid, void** ppvObject) override + { + return E_FAIL; + } +}; + +static HRESULT CompileShaderDXC(const wchar* path, const D3D_SHADER_MACRO* defines, const char* functionName, + const char* profileString, ID3DBlob** compiledShader, ID3DBlob** errorMessages) +{ + IDxcLibrary* library = nullptr; + DXCall(DxcCreateInstance(CLSID_DxcLibrary, IID_PPV_ARGS(&library))); + + IDxcBlobEncoding* sourceCode = nullptr; + DXCall(library->CreateBlobFromFile(path, nullptr, &sourceCode)); + + IDxcCompiler* compiler = nullptr; + DXCall(DxcCreateInstance(CLSID_DxcCompiler, IID_PPV_ARGS(&compiler))); + + // Convert the defines to wide strings + uint64 numDefines = 0; + while(defines && defines[numDefines].Name) + ++numDefines; + + const uint64 extraDefines = 2; + uint64 totalNumDefines = numDefines + extraDefines; + + Array dxcDefines(totalNumDefines); + Array defineStrings(numDefines * 2); + for(uint64 i = 0; i < numDefines; ++i) + { + defineStrings[i * 2 + 0] = AnsiToWString(defines[i].Name); + defineStrings[i * 2 + 1] = AnsiToWString(defines[i].Definition); + dxcDefines[i].Name = defineStrings[i * 2 + 0].c_str(); + dxcDefines[i].Value = defineStrings[i * 2 + 1].c_str(); + } + + dxcDefines[numDefines + 0].Name = L"DXC_"; + dxcDefines[numDefines + 0].Value = L"1"; + dxcDefines[numDefines + 1].Name = L"SM60_"; + dxcDefines[numDefines + 1].Value = L"1"; + + wstring frameworkShaderDir = SampleFrameworkDir() + L"Shaders"; + wchar expandedFrameworkShaderDir[1024] = { }; + GetFullPathName(frameworkShaderDir.c_str(), ArraySize_(expandedFrameworkShaderDir), expandedFrameworkShaderDir, nullptr); + + const wchar* arguments[] = + { + L"/O3", + L"-all_resources_bound", + L"-WX", + L"-I", + expandedFrameworkShaderDir, + + #if Debug_ + L"/Zi", + L"/Qembed_debug", + #endif + }; + + IDxcIncludeHandler* includeHandler = nullptr; + DXCall(library->CreateIncludeHandler(&includeHandler)); + + IDxcOperationResult* operationResult = nullptr; + DXCall(compiler->Compile(sourceCode, path, AnsiToWString(functionName).c_str(), + AnsiToWString(profileString).c_str(), arguments, + ArraySize_(arguments), dxcDefines.Data(), uint32(dxcDefines.Size()), + includeHandler, &operationResult)); + + HRESULT hr = S_OK; + operationResult->GetStatus(&hr); + if(SUCCEEDED(hr)) + DXCall(operationResult->GetResult(reinterpret_cast(compiledShader))); + + operationResult->GetErrorBuffer(reinterpret_cast(errorMessages)); + + DX12::Release(operationResult); + DX12::Release(includeHandler); + DX12::Release(compiler); + DX12::Release(sourceCode); + DX12::Release(library); + + return hr; +} + +#endif // EnableShaderModel6_ + +static ID3DBlob* CompileShader(const wchar* path, const char* functionName, ShaderType type, + const D3D_SHADER_MACRO* defines, bool forceOptimization, + GrowableList& filePaths) { if(FileExists(path) == false) { @@ -178,8 +341,8 @@ static ID3DBlob* CompileShader(const wchar* path, const char* functionName, Shad throw Exception(L"Shader file " + std::wstring(path) + L" does not exist"); } - uint64 profileIdx = uint64(profile) * uint64(ShaderType::NumTypes) + uint64(type); - Assert_(profileIdx < TotalNumProfiles); + uint64 profileIdx = uint64(type); + Assert_(profileIdx < ArraySize_(ProfileStrings)); const char* profileString = ProfileStrings[profileIdx]; // Make a hash off the expanded shader code @@ -189,18 +352,25 @@ static ID3DBlob* CompileShader(const wchar* path, const char* functionName, Shad if(FileExists(cacheName.c_str())) { File cacheFile(cacheName.c_str(), FileOpenMode::Read); - const uint64 shaderSize = cacheFile.Size(); - Array compressedShader; - compressedShader.Init(shaderSize); - cacheFile.Read(shaderSize, compressedShader.Data()); - - ID3DBlob* decompressedShader[1] = { nullptr }; - uint32 indices[1] = { 0 }; - DXCall(D3DDecompressShaders(compressedShader.Data(), shaderSize, 1, 0, - indices, 0, decompressedShader, nullptr)); - return decompressedShader[0]; + #if EnableShaderModel6_ + Blob* shaderBlob = new Blob(); + shaderBlob->Data.Init(shaderSize); + cacheFile.Read(shaderSize, shaderBlob->Data.Data()); + return shaderBlob; + #else + Array compressedShader; + compressedShader.Init(shaderSize); + cacheFile.Read(shaderSize, compressedShader.Data()); + + ID3DBlob* decompressedShader[1] = { nullptr }; + uint32 indices[1] = { 0 }; + DXCall(D3DDecompressShaders(compressedShader.Data(), shaderSize, 1, 0, + indices, 0, decompressedShader, nullptr)); + + return decompressedShader[0]; + #endif } WriteLog("Compiling %s shader %s_%s %s\n", TypeStrings[uint64(type)], @@ -210,25 +380,32 @@ static ID3DBlob* CompileShader(const wchar* path, const char* functionName, Shad // Loop until we succeed, or an exception is thrown while(true) { - UINT flags = D3DCOMPILE_WARNINGS_ARE_ERRORS; - #ifdef _DEBUG - flags |= D3DCOMPILE_DEBUG; - // This is causing some shader bugs - /*if(forceOptimization == false) - flags |= D3DCOMPILE_SKIP_OPTIMIZATION;*/ - #endif - - ID3DBlob* compiledShader; + ID3DBlob* compiledShader = nullptr; ID3DBlobPtr errorMessages; - FrameworkInclude include; - HRESULT hr = D3DCompileFromFile(path, defines, &include, functionName, - profileString, flags, 0, &compiledShader, &errorMessages); + + #if EnableShaderModel6_ + HRESULT hr = CompileShaderDXC(path, defines, functionName, profileString, &compiledShader, &errorMessages); + #else + UINT flags = D3DCOMPILE_WARNINGS_ARE_ERRORS; + flags |= D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES; + flags |= D3DCOMPILE_ALL_RESOURCES_BOUND; + #ifdef _DEBUG + flags |= D3DCOMPILE_DEBUG; + // This is causing some shader bugs + /*if(forceOptimization == false) + flags |= D3DCOMPILE_SKIP_OPTIMIZATION;*/ + #endif + + FrameworkInclude include; + HRESULT hr = D3DCompileFromFile(path, defines, &include, functionName, + profileString, flags, 0, &compiledShader, &errorMessages); + #endif if(FAILED(hr)) { if(errorMessages) { - wchar message[1024] = { 0 }; + wchar message[1024 * 4] = { 0 }; char* blobdata = reinterpret_cast(errorMessages->GetBufferPointer()); MultiByteToWideChar(CP_ACP, 0, blobdata, static_cast(errorMessages->GetBufferSize()), message, 1024); @@ -250,12 +427,21 @@ static ID3DBlob* CompileShader(const wchar* path, const char* functionName, Shad } else { - // Compress the shader - D3D_SHADER_DATA shaderData; - shaderData.pBytecode = compiledShader->GetBufferPointer(); - shaderData.BytecodeLength = compiledShader->GetBufferSize(); + // Write out warnings + if(errorMessages != nullptr && errorMessages->GetBufferSize() > 0) + WriteLog("Warning from shader '%ls' (%s): %s", path, functionName, errorMessages->GetBufferPointer()); + ID3DBlobPtr compressedShader; - DXCall(D3DCompressShaders(1, &shaderData, D3D_COMPRESS_SHADER_KEEP_ALL_PARTS, &compressedShader)); + + #if EnableShaderModel6_ + compressedShader = compiledShader; + #else + // Compress the shader + D3D_SHADER_DATA shaderData; + shaderData.pBytecode = compiledShader->GetBufferPointer(); + shaderData.BytecodeLength = compiledShader->GetBufferSize(); + DXCall(D3DCompressShaders(1, &shaderData, D3D_COMPRESS_SHADER_KEEP_ALL_PARTS, &compressedShader)); + #endif // Create the cache directory if it doesn't exist if(DirectoryExists(baseCacheDir.c_str()) == false) @@ -299,8 +485,7 @@ static void CompileShader(CompiledShader* shader) D3D_SHADER_MACRO defines[CompileOptions::MaxDefines + 1]; shader->CompileOpts.MakeDefines(defines); shader->ByteCode = CompileShader(shader->FilePath.c_str(), shader->FunctionName.c_str(), - shader->Type, shader->Profile, defines, - shader->ForceOptimization, filePaths); + shader->Type, defines, shader->ForceOptimization, filePaths); shader->ByteCodeHash = GenerateHash(shader->ByteCode->GetBufferPointer(), int(shader->ByteCode->GetBufferSize())); for(uint64 fileIdx = 0; fileIdx < filePaths.Count(); ++ fileIdx) @@ -345,11 +530,10 @@ static void CompileShader(CompiledShader* shader) CompiledShaderPtr CompileFromFile(const wchar* path, const char* functionName, ShaderType type, - ShaderProfile profile, const CompileOptions& compileOpts, bool forceOptimization) { - CompiledShader* compiledShader = new CompiledShader(path, functionName, profile, compileOpts, forceOptimization, type); + CompiledShader* compiledShader = new CompiledShader(path, functionName, compileOpts, forceOptimization, type); CompileShader(compiledShader); AcquireSRWLockExclusive(&CompiledShadersLock); @@ -363,56 +547,50 @@ CompiledShaderPtr CompileFromFile(const wchar* path, VertexShaderPtr CompileVSFromFile(const wchar* path, const char* functionName, - ShaderProfile profile, const CompileOptions& compileOptions, bool forceOptimization) { - return CompileFromFile(path, functionName, ShaderType::Vertex, profile, compileOptions, forceOptimization); + return CompileFromFile(path, functionName, ShaderType::Vertex, compileOptions, forceOptimization); } PixelShaderPtr CompilePSFromFile(const wchar* path, const char* functionName, - ShaderProfile profile, const CompileOptions& compileOptions, bool forceOptimization) { - return CompileFromFile(path, functionName, ShaderType::Pixel, profile, compileOptions, forceOptimization); + return CompileFromFile(path, functionName, ShaderType::Pixel, compileOptions, forceOptimization); } GeometryShaderPtr CompileGSFromFile(const wchar* path, const char* functionName, - ShaderProfile profile, const CompileOptions& compileOptions, bool forceOptimization) { - return CompileFromFile(path, functionName, ShaderType::Geometry, profile, compileOptions, forceOptimization); + return CompileFromFile(path, functionName, ShaderType::Geometry, compileOptions, forceOptimization); } HullShaderPtr CompileHSFromFile(const wchar* path, const char* functionName, - ShaderProfile profile, const CompileOptions& compileOptions, bool forceOptimization) { - return CompileFromFile(path, functionName, ShaderType::Hull, profile, compileOptions, forceOptimization); + return CompileFromFile(path, functionName, ShaderType::Hull, compileOptions, forceOptimization); } DomainShaderPtr CompileDSFromFile(const wchar* path, const char* functionName, - ShaderProfile profile, const CompileOptions& compileOptions, bool forceOptimization) { - return CompileFromFile(path, functionName, ShaderType::Domain, profile, compileOptions, forceOptimization); + return CompileFromFile(path, functionName, ShaderType::Domain, compileOptions, forceOptimization); } ComputeShaderPtr CompileCSFromFile(const wchar* path, const char* functionName, - ShaderProfile profile, const CompileOptions& compileOptions, bool forceOptimization) { - return CompileFromFile(path, functionName, ShaderType::Compute, profile, compileOptions, forceOptimization); + return CompileFromFile(path, functionName, ShaderType::Compute, compileOptions, forceOptimization); } bool UpdateShaders() diff --git a/SampleFramework12/v1.00/Graphics/ShaderCompilation.h b/SampleFramework12/v1.01/Graphics/ShaderCompilation.h similarity index 81% rename from SampleFramework12/v1.00/Graphics/ShaderCompilation.h rename to SampleFramework12/v1.01/Graphics/ShaderCompilation.h index 6d8f1a3..e8077df 100644 --- a/SampleFramework12/v1.00/Graphics/ShaderCompilation.h +++ b/SampleFramework12/v1.01/Graphics/ShaderCompilation.h @@ -69,7 +69,6 @@ class CompiledShader std::wstring FilePath; std::string FunctionName; - ShaderProfile Profile; CompileOptions CompileOpts; bool ForceOptimization; ID3DBlobPtr ByteCode; @@ -77,10 +76,9 @@ class CompiledShader Hash ByteCodeHash; CompiledShader(const wchar* filePath, const char* functionName, - ShaderProfile profile, const CompileOptions& compileOptions, + const CompileOptions& compileOptions, bool forceOptimization, ShaderType type) : FilePath(filePath), FunctionName(functionName), - Profile(profile), CompileOpts(compileOptions), ForceOptimization(forceOptimization), Type(type) @@ -126,14 +124,6 @@ class CompiledShaderPtr return byteCode; } - // Compatability hack, remove this - operator ID3D11VertexShader*() const { return nullptr; } - operator ID3D11HullShader*() const { return nullptr; } - operator ID3D11DomainShader*() const { return nullptr; } - operator ID3D11GeometryShader*() const { return nullptr; } - operator ID3D11PixelShader*() const { return nullptr; } - operator ID3D11ComputeShader*() const { return nullptr; } - private: const CompiledShader* ptr; @@ -151,43 +141,36 @@ typedef ComputeShaderPtr ShaderPtr; CompiledShaderPtr CompileFromFile(const wchar* path, const char* functionName, ShaderType type, - ShaderProfile profile = ShaderProfile::SM51, const CompileOptions& compileOpts = CompileOptions(), bool forceOptimization = false); VertexShaderPtr CompileVSFromFile(const wchar* path, const char* functionName = "VS", - ShaderProfile profile = ShaderProfile::SM51, const CompileOptions& compileOpts = CompileOptions(), bool forceOptimization = false); PixelShaderPtr CompilePSFromFile(const wchar* path, const char* functionName = "PS", - ShaderProfile profile = ShaderProfile::SM51, const CompileOptions& compileOpts = CompileOptions(), bool forceOptimization = false); GeometryShaderPtr CompileGSFromFile(const wchar* path, const char* functionName = "GS", - ShaderProfile profile = ShaderProfile::SM51, const CompileOptions& compileOpts = CompileOptions(), bool forceOptimization = false); HullShaderPtr CompileHSFromFile(const wchar* path, const char* functionName = "HS", - ShaderProfile profile = ShaderProfile::SM51, const CompileOptions& compileOpts = CompileOptions(), bool forceOptimization = false); DomainShaderPtr CompileDSFromFile(const wchar* path, const char* functionName = "DS", - ShaderProfile profile = ShaderProfile::SM51, const CompileOptions& compileOpts = CompileOptions(), bool forceOptimization = false); ComputeShaderPtr CompileCSFromFile(const wchar* path, const char* functionName = "CS", - ShaderProfile profile = ShaderProfile::SM51, const CompileOptions& compileOpts = CompileOptions(), bool forceOptimization = false); diff --git a/SampleFramework12/v1.01/Graphics/ShadowHelper.cpp b/SampleFramework12/v1.01/Graphics/ShadowHelper.cpp new file mode 100644 index 0000000..6b2f0b0 --- /dev/null +++ b/SampleFramework12/v1.01/Graphics/ShadowHelper.cpp @@ -0,0 +1,631 @@ +//================================================================================================= +// +// MJP's DX12 Sample Framework +// http://mynameismjp.wordpress.com/ +// +// All code licensed under the MIT license +// +//================================================================================================= + +#pragma once + +#include "PCH.h" +#include "ShadowHelper.h" +#include "Camera.h" + +#include +#include +#include +#include + +namespace SampleFramework12 +{ + +namespace ShadowHelper +{ + +static const uint32 MaxFilterRadius = 4; + +// Transforms from [-1,1] post-projection space to [0,1] UV space +Float4x4 ShadowScaleOffsetMatrix = Float4x4(Float4(0.5f, 0.0f, 0.0f, 0.0f), + Float4(0.0f, -0.5f, 0.0f, 0.0f), + Float4(0.0f, 0.0f, 1.0f, 0.0f), + Float4(0.5f, 0.5f, 0.0f, 1.0f)); + +static CompiledShaderPtr fullScreenTriVS; +static CompiledShaderPtr smConvertPS; +static CompiledShaderPtr filterSMHorizontalPS[MaxFilterRadius + 1]; +static CompiledShaderPtr filterSMVerticalPS[MaxFilterRadius + 1]; +static CompiledShaderPtr filter3x3PS; +static CompiledShaderPtr filter5x5PS; +static CompiledShaderPtr smConvertAndFilterCS[MaxFilterRadius + 1]; + +static ID3D12PipelineState* smConvertPSO = nullptr; +static ID3D12PipelineState* filterSMHorizontalPSO[MaxFilterRadius + 1] = { }; +static ID3D12PipelineState* filterSMVerticalPSO[MaxFilterRadius + 1] = { }; +static ID3D12PipelineState* filter3x3PSO = nullptr; +static ID3D12PipelineState* filter5x5PSO = nullptr; +static ID3D12RootSignature* rootSignature = nullptr; + +static ID3D12PipelineState* smConvertAndFilterPSO[MaxFilterRadius + 1] = { }; +static ID3D12RootSignature* rootSignatureCS = nullptr; + +static ShadowMapMode currSMMode = ShadowMapMode::NumValues; +static ShadowMSAAMode currMSAAMode = ShadowMSAAMode::NumValues; +static bool initialized = false; + +enum RootParams : uint32 +{ + RootParam_StandardDescriptors, + RootParam_CBuffer, + + NumRootParams +}; + +enum RootParamsCS : uint32 +{ + CSRootParam_StandardDescriptors, + CSRootParam_CBuffer, + CSRootParam_UAV, + + NumComputeRootParams +}; + +struct ConvertConstants +{ + Float2 ShadowMapSize; + float PositiveExponent = 0.0f; + float NegativeExponent = 0.0f; + float FilterSizeU = 0.0f; + float FilterSizeV = 0.0f; + bool32 LinearizeDepth = 0; + float NearClip = 0.0f; + float InvClipRange = 0.0f; + float Proj33 = 0.0f; + float Proj43 = 0.0f; + uint32 InputMapIdx = uint32(-1); + uint32 ArraySliceIdx = 0; +}; + +void Initialize(ShadowMapMode smMode, ShadowMSAAMode msaaMode) +{ + Assert_(initialized == false); + currSMMode = smMode; + currMSAAMode = msaaMode; + + if(smMode == ShadowMapMode::EVSM || smMode == ShadowMapMode::MSM) + { + std::wstring fullScreenTriPath = SampleFrameworkDir() + L"Shaders\\FullScreenTriangle.hlsl"; + std::wstring smConvertPath = SampleFrameworkDir() + L"Shaders\\SMConvert.hlsl"; + fullScreenTriVS = CompileFromFile(fullScreenTriPath.c_str(), "FullScreenTriangleVS", ShaderType::Vertex); + for(uint32 i = 0; i <= MaxFilterRadius; ++i) + { + CompileOptions opts; + opts.Add("SampleRadius_", i); + opts.Add("Vertical_", 0); + filterSMHorizontalPS[i] = CompileFromFile(smConvertPath.c_str(), "FilterSM", ShaderType::Pixel, opts); + + opts.Reset(); + opts.Add("SampleRadius_", i); + opts.Add("Vertical_", 1); + filterSMVerticalPS[i] = CompileFromFile(smConvertPath.c_str(), "FilterSM", ShaderType::Pixel, opts); + } + + filter3x3PS = CompileFromFile(smConvertPath.c_str(), "FilterSM3x3", ShaderType::Pixel); + filter5x5PS = CompileFromFile(smConvertPath.c_str(), "FilterSM5x5", ShaderType::Pixel); + + { + CompileOptions opts; + opts.Add("EVSM_", smMode == ShadowMapMode::EVSM ? 1 : 0); + opts.Add("MSM_", smMode == ShadowMapMode::MSM ? 1 : 0); + opts.Add("MSAASamples_", NumMSAASamples()); + smConvertPS = CompileFromFile(smConvertPath.c_str(), "SMConvert", ShaderType::Pixel, opts); + } + + for(uint32 i = 0; i <= MaxFilterRadius; ++i) + { + CompileOptions opts; + opts.Add("SampleRadius_", i); + opts.Add("EVSM_", smMode == ShadowMapMode::EVSM ? 1 : 0); + opts.Add("MSM_", smMode == ShadowMapMode::MSM ? 1 : 0); + opts.Add("MSAASamples_", NumMSAASamples()); + opts.Add("CS_", 1); + smConvertAndFilterCS[i] = CompileFromFile(smConvertPath.c_str(), "SMConvertAndFilter", ShaderType::Compute, opts); + } + + { + D3D12_ROOT_PARAMETER1 rootParameters[NumRootParams] = { }; + rootParameters[RootParam_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[RootParam_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[RootParam_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[RootParam_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + rootParameters[RootParam_CBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[RootParam_CBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[RootParam_CBuffer].Descriptor.RegisterSpace = 0; + rootParameters[RootParam_CBuffer].Descriptor.ShaderRegister = 0; + + D3D12_STATIC_SAMPLER_DESC staticSamplers[1] = {}; + staticSamplers[0] = DX12::GetStaticSamplerState(SamplerState::LinearClamp, 0); + + D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; + rootSignatureDesc.NumParameters = ArraySize_(rootParameters); + rootSignatureDesc.pParameters = rootParameters; + rootSignatureDesc.NumStaticSamplers = ArraySize_(staticSamplers); + rootSignatureDesc.pStaticSamplers = staticSamplers; + rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + + DX12::CreateRootSignature(&rootSignature, rootSignatureDesc); + } + + { + D3D12_DESCRIPTOR_RANGE1 uavRanges[1] = {}; + uavRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; + uavRanges[0].NumDescriptors = 1; + uavRanges[0].BaseShaderRegister = 0; + uavRanges[0].RegisterSpace = 0; + uavRanges[0].OffsetInDescriptorsFromTableStart = 0; + + D3D12_ROOT_PARAMETER1 rootParameters[NumComputeRootParams] = { }; + rootParameters[CSRootParam_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[CSRootParam_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[CSRootParam_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[CSRootParam_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + rootParameters[CSRootParam_CBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[CSRootParam_CBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[CSRootParam_CBuffer].Descriptor.RegisterSpace = 0; + rootParameters[CSRootParam_CBuffer].Descriptor.ShaderRegister = 0; + + // UAV descriptor + rootParameters[CSRootParam_UAV].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[CSRootParam_UAV].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[CSRootParam_UAV].DescriptorTable.pDescriptorRanges = uavRanges; + rootParameters[CSRootParam_UAV].DescriptorTable.NumDescriptorRanges = ArraySize_(uavRanges); + + D3D12_ROOT_SIGNATURE_DESC1 rootSignatureDesc = {}; + rootSignatureDesc.NumParameters = ArraySize_(rootParameters); + rootSignatureDesc.pParameters = rootParameters; + rootSignatureDesc.NumStaticSamplers = 0; + rootSignatureDesc.pStaticSamplers = nullptr; + rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + + DX12::CreateRootSignature(&rootSignatureCS, rootSignatureDesc); + } + } + + initialized = true; +} + +void Shutdown() +{ + Assert_(initialized); + + DX12::DeferredRelease(rootSignature); + DX12::DeferredRelease(rootSignatureCS); + + currSMMode = ShadowMapMode::NumValues; + currMSAAMode = ShadowMSAAMode::NumValues; + initialized = false; +} + +void CreatePSOs() +{ + if(initialized == false) + return; + + D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = { }; + psoDesc.pRootSignature = rootSignature; + psoDesc.VS = fullScreenTriVS.ByteCode(); + psoDesc.PS = smConvertPS.ByteCode(); + psoDesc.RasterizerState = DX12::GetRasterizerState(RasterizerState::NoCull); + psoDesc.BlendState = DX12::GetBlendState(BlendState::Disabled); + psoDesc.DepthStencilState = DX12::GetDepthState(DepthState::Disabled); + psoDesc.SampleMask = UINT_MAX; + psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + psoDesc.NumRenderTargets = 1; + psoDesc.RTVFormats[0] = SMFormat(); + psoDesc.SampleDesc.Count = 1; + DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&smConvertPSO))); + + for(uint32 i = 0; i <= MaxFilterRadius; ++i) + { + psoDesc.PS = filterSMHorizontalPS[i].ByteCode(); + DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&filterSMHorizontalPSO[i]))); + + psoDesc.PS = filterSMVerticalPS[i].ByteCode(); + DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&filterSMVerticalPSO[i]))); + } + + psoDesc.PS = filter3x3PS.ByteCode(); + DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&filter3x3PSO))); + + psoDesc.PS = filter5x5PS.ByteCode(); + DXCall(DX12::Device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&filter5x5PSO))); + + D3D12_COMPUTE_PIPELINE_STATE_DESC psoDescCS = { }; + psoDescCS.pRootSignature = rootSignatureCS; + + for(uint32 i = 0; i <= MaxFilterRadius; ++i) + { + psoDescCS.CS = smConvertAndFilterCS[i].ByteCode(); + DXCall(DX12::Device->CreateComputePipelineState(&psoDescCS, IID_PPV_ARGS(&smConvertAndFilterPSO[i]))); + } +} + +void DestroyPSOs() +{ + if(initialized == false) + return; + + DX12::DeferredRelease(smConvertPSO); + DX12::DeferredRelease(filter3x3PSO); + DX12::DeferredRelease(filter5x5PSO); + for(uint32 i = 0; i <= MaxFilterRadius; ++i) + { + DX12::DeferredRelease(filterSMHorizontalPSO[i]); + DX12::DeferredRelease(filterSMVerticalPSO[i]); + DX12::DeferredRelease(smConvertAndFilterPSO[i]); + } +} + +uint32 NumMSAASamples() +{ + Assert_(currMSAAMode != ShadowMSAAMode::NumValues); + + static const uint32 numMSAASamples[] = { 1, 2, 4 }; + StaticAssert_(ArraySize_(numMSAASamples) == uint32(ShadowMSAAMode::NumValues)); + return numMSAASamples[uint32(currMSAAMode)]; +} + +DXGI_FORMAT SMFormat() +{ + Assert_(currSMMode != ShadowMapMode::NumValues); + + if(currSMMode == ShadowMapMode::EVSM) + return DXGI_FORMAT_R32G32B32A32_FLOAT; + else if(currSMMode == ShadowMapMode::MSM) + return DXGI_FORMAT_R16G16B16A16_UNORM; + + Assert_(false); + return DXGI_FORMAT_UNKNOWN; +} + +void ConvertShadowMap(ID3D12GraphicsCommandList* cmdList, const DepthBuffer& depthMap, RenderTexture& smTarget, + uint32 arraySlice, RenderTexture& tempTarget, float filterSizeU, float filterSizeV, + bool32 linearizeDepth, float nearClip, float farClip, const Float4x4& projection, + bool32 useCSConversion, bool32 use3x3Filter, float positiveExponent, float negativeExponent) +{ + Assert_(initialized); + Assert_(currSMMode == ShadowMapMode::MSM || currSMMode == ShadowMapMode::EVSM); + Assert_(NumMSAASamples() == depthMap.MSAASamples); + Assert_(depthMap.Width() == smTarget.Width() && depthMap.Height() == smTarget.Height()); + + PIXMarker event(cmdList, "Shadow Map Conversion"); + + filterSizeU = Clamp(filterSizeU, 1.0f, MaxShadowFilterSize); + filterSizeV = Clamp(filterSizeV, 1.0f, MaxShadowFilterSize); + + const uint32 sampleRadiusU = uint32((filterSizeU / 2) + 0.499f); + const uint32 sampleRadiusV = uint32((filterSizeV / 2) + 0.499f); + + ConvertConstants constants; + constants.ShadowMapSize.x = float(depthMap.Width()); + constants.ShadowMapSize.y = float(depthMap.Height()); + constants.PositiveExponent = positiveExponent; + constants.NegativeExponent = negativeExponent; + constants.FilterSizeU = filterSizeU; + constants.FilterSizeV = filterSizeV; + constants.LinearizeDepth = linearizeDepth ? 1 : 0; + constants.NearClip = nearClip; + constants.InvClipRange = 1.0f / (farClip - nearClip); + constants.Proj33 = projection._33; + constants.Proj43 = projection._43; + constants.InputMapIdx = depthMap.SRV(); + constants.ArraySliceIdx = arraySlice; + + if(useCSConversion) + { + uint32 sampleRadius = uint32((Max(filterSizeU, filterSizeV) / 2.0f) + 0.499f); + + cmdList->SetComputeRootSignature(rootSignatureCS); + cmdList->SetPipelineState(smConvertAndFilterPSO[sampleRadius]); + + DX12::BindStandardDescriptorTable(cmdList, CSRootParam_StandardDescriptors, CmdListMode::Compute); + + DX12::BindTempConstantBuffer(cmdList, constants, CSRootParam_CBuffer, CmdListMode::Compute); + + D3D12_CPU_DESCRIPTOR_HANDLE uavs[] = { smTarget.UAV }; + DX12::BindTempDescriptorTable(cmdList, uavs, ArraySize_(uavs), CSRootParam_UAV, CmdListMode::Compute); + + const uint32 BaseThreadGroupWidth = 8; + cmdList->Dispatch(DX12::DispatchSize(smTarget.Width(), BaseThreadGroupWidth), DX12::DispatchSize(smTarget.Height(), BaseThreadGroupWidth), 1); + + smTarget.UAVBarrier(cmdList); + } + else if(use3x3Filter && ((sampleRadiusU == 1 && sampleRadiusV == 1) || (sampleRadiusU == 2 && sampleRadiusV == 2))) + { + // Do a conversion pass, then do 3x3 filtering in single pass + tempTarget.MakeWritable(cmdList, 0, 0); + + D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[1] = { tempTarget.RTV }; + cmdList->OMSetRenderTargets(1, rtvHandles, false, nullptr); + + cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + DX12::SetViewport(cmdList, tempTarget.Width(), tempTarget.Height()); + + cmdList->SetGraphicsRootSignature(rootSignature); + cmdList->SetPipelineState(smConvertPSO); + + DX12::BindStandardDescriptorTable(cmdList, RootParam_StandardDescriptors, CmdListMode::Graphics); + + DX12::BindTempConstantBuffer(cmdList, constants, RootParam_CBuffer, CmdListMode::Graphics); + + cmdList->DrawInstanced(3, 1, 0, 0); + + tempTarget.MakeReadable(cmdList); + + rtvHandles[0] = arraySlice == 0 ? smTarget.RTV : smTarget.ArrayRTVs[arraySlice]; + cmdList->OMSetRenderTargets(1, rtvHandles, false, nullptr); + + constants.InputMapIdx = tempTarget.SRV(); + DX12::BindTempConstantBuffer(cmdList, constants, RootParam_CBuffer, CmdListMode::Graphics); + + cmdList->SetPipelineState(sampleRadiusU == 2 ? filter5x5PSO : filter3x3PSO); + + cmdList->DrawInstanced(3, 1, 0, 0); + } + else + { + // Standard pixel shader conversion/filtering path + D3D12_CPU_DESCRIPTOR_HANDLE smTargetRTV = arraySlice == 0 ? smTarget.RTV : smTarget.ArrayRTVs[arraySlice]; + D3D12_CPU_DESCRIPTOR_HANDLE rtvHandles[1] = { smTargetRTV }; + cmdList->OMSetRenderTargets(1, rtvHandles, false, nullptr); + + cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + DX12::SetViewport(cmdList, smTarget.Width(), smTarget.Height()); + + cmdList->SetGraphicsRootSignature(rootSignature); + cmdList->SetPipelineState(smConvertPSO); + + DX12::BindStandardDescriptorTable(cmdList, RootParam_StandardDescriptors, CmdListMode::Graphics); + + DX12::BindTempConstantBuffer(cmdList, constants, RootParam_CBuffer, CmdListMode::Graphics); + + cmdList->DrawInstanced(3, 1, 0, 0); + + if(filterSizeU > 1.0f || filterSizeV > 1.0f) + { + smTarget.MakeReadable(cmdList, 0, arraySlice); + + // Horizontal pass + rtvHandles[0] = tempTarget.RTV; + cmdList->OMSetRenderTargets(1, rtvHandles, false, nullptr); + + tempTarget.MakeWritable(cmdList, 0, 0); + + constants.InputMapIdx = smTarget.SRV(); + DX12::BindTempConstantBuffer(cmdList, constants, RootParam_CBuffer, CmdListMode::Graphics); + + cmdList->SetPipelineState(filterSMHorizontalPSO[sampleRadiusU]); + + cmdList->DrawInstanced(3, 1, 0, 0); + + tempTarget.MakeReadable(cmdList, 0, 0); + + // Vertical pass + smTarget.MakeWritable(cmdList, 0, arraySlice); + + rtvHandles[0] = smTargetRTV; + cmdList->OMSetRenderTargets(1, rtvHandles, false, nullptr); + + constants.InputMapIdx = tempTarget.SRV(); + DX12::BindTempConstantBuffer(cmdList, constants, RootParam_CBuffer, CmdListMode::Graphics); + + cmdList->SetPipelineState(filterSMVerticalPSO[sampleRadiusV]); + + cmdList->DrawInstanced(3, 1, 0, 0); + + // smTarget.MakeReadable(cmdList, 0, arraySlice); + } + } +} + +void PrepareCascades(const Float3& lightDir, uint64 shadowMapSize, bool stabilize, const Camera& camera, + SunShadowConstantsBase& constants, OrthographicCamera* cascadeCameras) +{ + const float MinDistance = 0.0f; + const float MaxDistance = 1.0f; + + // Compute the split distances based on the partitioning mode + float cascadeSplits[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + + if(camera.IsOrthographic()) + { + for(uint32 i = 0; i < NumCascades; ++i) + cascadeSplits[i] = Lerp(MinDistance, MaxDistance, (i + 1.0f) / NumCascades); + } + else + { + float lambda = 0.5f; + + float nearClip = camera.NearClip(); + float farClip = camera.FarClip(); + float clipRange = farClip - nearClip; + + float minZ = nearClip + MinDistance * clipRange; + float maxZ = nearClip + MaxDistance * clipRange; + + float range = maxZ - minZ; + float ratio = maxZ / minZ; + + for(uint32 i = 0; i < NumCascades; ++i) + { + float p = (i + 1) / static_cast(NumCascades); + float log = minZ * std::pow(ratio, p); + float uniform = minZ + range * p; + float d = lambda * (log - uniform) + uniform; + cascadeSplits[i] = (d - nearClip) / clipRange; + } + } + + Float4x4 c0Matrix; + + // Prepare the projections ofr each cascade + for(uint64 cascadeIdx = 0; cascadeIdx < NumCascades; ++cascadeIdx) + { + // Get the 8 points of the view frustum in world space + Float3 frustumCornersWS[8] = + { + Float3(-1.0f, 1.0f, 0.0f), + Float3( 1.0f, 1.0f, 0.0f), + Float3( 1.0f, -1.0f, 0.0f), + Float3(-1.0f, -1.0f, 0.0f), + Float3(-1.0f, 1.0f, 1.0f), + Float3( 1.0f, 1.0f, 1.0f), + Float3( 1.0f, -1.0f, 1.0f), + Float3(-1.0f, -1.0f, 1.0f), + }; + + float prevSplitDist = cascadeIdx == 0 ? MinDistance : cascadeSplits[cascadeIdx - 1]; + float splitDist = cascadeSplits[cascadeIdx]; + + Float4x4 invViewProj = Float4x4::Invert(camera.ViewProjectionMatrix()); + for(uint64 i = 0; i < 8; ++i) + frustumCornersWS[i] = Float3::Transform(frustumCornersWS[i], invViewProj); + + // Get the corners of the current cascade slice of the view frustum + for(uint64 i = 0; i < 4; ++i) + { + Float3 cornerRay = frustumCornersWS[i + 4] - frustumCornersWS[i]; + Float3 nearCornerRay = cornerRay * prevSplitDist; + Float3 farCornerRay = cornerRay * splitDist; + frustumCornersWS[i + 4] = frustumCornersWS[i] + farCornerRay; + frustumCornersWS[i] = frustumCornersWS[i] + nearCornerRay; + } + + // Calculate the centroid of the view frustum slice + Float3 frustumCenter = Float3(0.0f); + for(uint64 i = 0; i < 8; ++i) + frustumCenter += frustumCornersWS[i]; + frustumCenter *= (1.0f / 8.0f); + + // Pick the up vector to use for the light camera + Float3 upDir = camera.Right(); + + Float3 minExtents; + Float3 maxExtents; + + if(stabilize) + { + // This needs to be constant for it to be stable + upDir = Float3(0.0f, 1.0f, 0.0f); + + // Calculate the radius of a bounding sphere surrounding the frustum corners + float sphereRadius = 0.0f; + for(uint64 i = 0; i < 8; ++i) + { + float dist = Float3::Length(Float3(frustumCornersWS[i]) - frustumCenter); + sphereRadius = Max(sphereRadius, dist); + } + + sphereRadius = std::ceil(sphereRadius * 16.0f) / 16.0f; + + maxExtents = Float3(sphereRadius, sphereRadius, sphereRadius); + minExtents = -maxExtents; + } + else + { + // Create a temporary view matrix for the light + Float3 lightCameraPos = frustumCenter; + Float3 lookAt = frustumCenter - lightDir; + DirectX::XMMATRIX lightView = DirectX::XMMatrixLookAtLH(lightCameraPos.ToSIMD(), lookAt.ToSIMD(), upDir.ToSIMD()); + + // Calculate an AABB around the frustum corners + DirectX::XMVECTOR mins = DirectX::XMVectorSet(FloatMax, FloatMax, FloatMax, FloatMax); + DirectX::XMVECTOR maxes = DirectX::XMVectorSet(-FloatMax, -FloatMax, -FloatMax, -FloatMax); + for(uint32 i = 0; i < 8; ++i) + { + DirectX::XMVECTOR corner = DirectX::XMVector3TransformCoord(frustumCornersWS[i].ToSIMD(), lightView); + mins = DirectX::XMVectorMin(mins, corner); + maxes = DirectX::XMVectorMax(maxes, corner); + } + + minExtents = Float3(mins); + maxExtents = Float3(maxes); + } + + // Adjust the min/max to accommodate the filtering size + float scale = (shadowMapSize + 7.0f) / shadowMapSize; + minExtents.x *= scale; + minExtents.y *= scale; + maxExtents.x *= scale; + maxExtents.y *= scale; + + Float3 cascadeExtents = maxExtents - minExtents; + + // Get position of the shadow camera + Float3 shadowCameraPos = frustumCenter + lightDir * -minExtents.z; + + // Come up with a new orthographic camera for the shadow caster + OrthographicCamera& shadowCamera = cascadeCameras[cascadeIdx]; + shadowCamera.Initialize(minExtents.x, minExtents.y, maxExtents.x, maxExtents.y, 0.0f, cascadeExtents.z); + shadowCamera.SetLookAt(shadowCameraPos, frustumCenter, upDir); + + if(stabilize) + { + // Create the rounding matrix, by projecting the world-space origin and determining + // the fractional offset in texel space + DirectX::XMMATRIX shadowMatrix = shadowCamera.ViewProjectionMatrix().ToSIMD(); + DirectX::XMVECTOR shadowOrigin = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f); + shadowOrigin = DirectX::XMVector4Transform(shadowOrigin, shadowMatrix); + shadowOrigin = DirectX::XMVectorScale(shadowOrigin, shadowMapSize / 2.0f); + + DirectX::XMVECTOR roundedOrigin = DirectX::XMVectorRound(shadowOrigin); + DirectX::XMVECTOR roundOffset = DirectX::XMVectorSubtract(roundedOrigin, shadowOrigin); + roundOffset = DirectX::XMVectorScale(roundOffset, 2.0f / shadowMapSize); + roundOffset = DirectX::XMVectorSetZ(roundOffset, 0.0f); + roundOffset = DirectX::XMVectorSetW(roundOffset, 0.0f); + + DirectX::XMMATRIX shadowProj = shadowCamera.ProjectionMatrix().ToSIMD(); + shadowProj.r[3] = DirectX::XMVectorAdd(shadowProj.r[3], roundOffset); + shadowCamera.SetProjection(Float4x4(shadowProj)); + } + + Float4x4 shadowMatrix = shadowCamera.ViewProjectionMatrix(); + shadowMatrix = shadowMatrix * ShadowScaleOffsetMatrix; + + // Store the split distance in terms of view space depth + const float clipDist = camera.FarClip() - camera.NearClip(); + constants.CascadeSplits[cascadeIdx] = camera.NearClip() + splitDist * clipDist; + + if(cascadeIdx == 0) + { + c0Matrix = shadowMatrix; + constants.ShadowMatrix = shadowMatrix; + constants.CascadeOffsets[0] = Float4(0.0f, 0.0f, 0.0f, 0.0f); + constants.CascadeScales[0] = Float4(1.0f, 1.0f, 1.0f, 1.0f); + } + else + { + // Calculate the position of the lower corner of the cascade partition, in the UV space + // of the first cascade partition + Float4x4 invCascadeMat = Float4x4::Invert(shadowMatrix); + Float3 cascadeCorner = Float3::Transform(Float3(0.0f, 0.0f, 0.0f), invCascadeMat); + cascadeCorner = Float3::Transform(cascadeCorner, c0Matrix); + + // Do the same for the upper corner + Float3 otherCorner = Float3::Transform(Float3(1.0f, 1.0f, 1.0f), invCascadeMat); + otherCorner = Float3::Transform(otherCorner, c0Matrix); + + // Calculate the scale and offset + Float3 cascadeScale = Float3(1.0f, 1.0f, 1.f) / (otherCorner - cascadeCorner); + constants.CascadeOffsets[cascadeIdx] = Float4(-cascadeCorner, 0.0f); + constants.CascadeScales[cascadeIdx] = Float4(cascadeScale, 1.0f); + } + } +} + +} + +} diff --git a/SampleFramework12/v1.01/Graphics/ShadowHelper.h b/SampleFramework12/v1.01/Graphics/ShadowHelper.h new file mode 100644 index 0000000..d9ec30e --- /dev/null +++ b/SampleFramework12/v1.01/Graphics/ShadowHelper.h @@ -0,0 +1,113 @@ +//================================================================================================= +// +// MJP's DX12 Sample Framework +// http://mynameismjp.wordpress.com/ +// +// All code licensed under the MIT license +// +//================================================================================================= + +#pragma once + +#include +#include "..\\SF12_Math.h" + +namespace SampleFramework12 +{ + +class Camera; +class OrthographicCamera; +class PerspectiveCamera; +struct ModelSpotLight; +struct DepthBuffer; +struct RenderTexture; + +const uint64 NumCascades = 4; +const float MaxShadowFilterSize = 9.0f; + +struct SunShadowConstantsBase +{ + Float4x4 ShadowMatrix; + float CascadeSplits[NumCascades] = { }; + Float4 CascadeOffsets[NumCascades]; + Float4 CascadeScales[NumCascades]; +}; + +struct EVSMConstants +{ + float PositiveExponent = 0.0f; + float NegativeExponent = 0.0f; + float LightBleedingReduction = 0.25f; + uint32 Padding = 0; +}; + +struct MSMConstants +{ + float DepthBias = 0.0f; + float MomentBias = 0.0003f; + float LightBleedingReduction = 0.25f; + uint32 Padding = 0; +}; + +struct SunShadowConstantsDepthMap +{ + SunShadowConstantsBase Base; + uint32 Dummy[4] = { }; +}; + +struct SunShadowConstantsEVSM +{ + SunShadowConstantsBase Base; + EVSMConstants EVSM; +}; + +struct SunShadowConstantsMSM +{ + SunShadowConstantsBase Base; + MSMConstants MSM; +}; + +enum class ShadowMapMode : uint32 +{ + DepthMap, + EVSM, + MSM, + + NumValues, +}; + +enum class ShadowMSAAMode : uint32 +{ + MSAA1x, + MSAA2x, + MSAA4x, + + NumValues, +}; + +namespace ShadowHelper +{ + +extern Float4x4 ShadowScaleOffsetMatrix; + +void Initialize(ShadowMapMode smMode, ShadowMSAAMode msaaMode); +void Shutdown(); + +void CreatePSOs(); +void DestroyPSOs(); + +uint32 NumMSAASamples(); +DXGI_FORMAT SMFormat(); + +void ConvertShadowMap(ID3D12GraphicsCommandList* cmdList, const DepthBuffer& depthMap, RenderTexture& smTarget, + uint32 arraySlice, RenderTexture& tempTarget, float filterSizeU, float filterSizeV, + bool32 linearizeDepth, float nearClip, float farClip, const Float4x4& projection, + bool32 useCSConversion = false, bool32 use3x3Filter = true, float positiveExponent = 0.0f, float negativeExponent = 0.0f); + +extern Float4x4 ScaleOffsetMatrix; +void PrepareCascades(const Float3& lightDir, uint64 shadowMapSize, bool stabilize, const Camera& camera, + SunShadowConstantsBase& constants, OrthographicCamera* cascadeCameras); + +}; + +} diff --git a/SampleFramework12/v1.00/Graphics/Skybox.cpp b/SampleFramework12/v1.01/Graphics/Skybox.cpp similarity index 79% rename from SampleFramework12/v1.00/Graphics/Skybox.cpp rename to SampleFramework12/v1.01/Graphics/Skybox.cpp index 4a9c980..41f36d9 100644 --- a/SampleFramework12/v1.00/Graphics/Skybox.cpp +++ b/SampleFramework12/v1.01/Graphics/Skybox.cpp @@ -13,6 +13,7 @@ #include "../Utility.h" #include "../SF12_Math.h" +#include "../HosekSky/ArHosekSkyModel.h" #include "ShaderCompilation.h" #include "Textures.h" #include "Spectrum.h" @@ -249,6 +250,15 @@ Float3 SkyCache::Sample(Float3 sampleDir) const // == Skybox ====================================================================================== +enum RootParams : uint32 +{ + RootParam_StandardDescriptors = 0, + RootParam_VSCBuffer, + RootParam_PSCBuffer, + + NumRootParams +}; + Skybox::Skybox() { } @@ -261,33 +271,26 @@ void Skybox::Initialize() { // Load the shaders const std::wstring shaderPath = SampleFrameworkDir() + L"Shaders\\Skybox.hlsl"; - vertexShader = CompileFromFile(shaderPath.c_str(), "SkyboxVS", ShaderType::Vertex, ShaderProfile::SM51); - pixelShader = CompileFromFile(shaderPath.c_str(), "SkyboxPS", ShaderType::Pixel, ShaderProfile::SM51); + vertexShader = CompileFromFile(shaderPath.c_str(), "SkyboxVS", ShaderType::Vertex); + pixelShader = CompileFromFile(shaderPath.c_str(), "SkyboxPS", ShaderType::Pixel); { // Make a root signature - D3D12_DESCRIPTOR_RANGE1 srvRanges[1] = { }; - srvRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - srvRanges[0].NumDescriptors = 1; - srvRanges[0].BaseShaderRegister = 0; - srvRanges[0].RegisterSpace = 0; - srvRanges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - D3D12_ROOT_PARAMETER1 rootParameters[3] = { }; - rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[0].DescriptorTable.pDescriptorRanges = srvRanges; - rootParameters[0].DescriptorTable.NumDescriptorRanges = 1; - - rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; - rootParameters[1].Descriptor.RegisterSpace = 0; - rootParameters[1].Descriptor.ShaderRegister = 0; - - rootParameters[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[2].Descriptor.RegisterSpace = 0; - rootParameters[2].Descriptor.ShaderRegister = 0; + D3D12_ROOT_PARAMETER1 rootParameters[NumRootParams] = { }; + rootParameters[RootParam_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[RootParam_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[RootParam_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[RootParam_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + rootParameters[RootParam_VSCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[RootParam_VSCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; + rootParameters[RootParam_VSCBuffer].Descriptor.RegisterSpace = 0; + rootParameters[RootParam_VSCBuffer].Descriptor.ShaderRegister = 0; + + rootParameters[RootParam_PSCBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[RootParam_PSCBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[RootParam_PSCBuffer].Descriptor.RegisterSpace = 0; + rootParameters[RootParam_PSCBuffer].Descriptor.ShaderRegister = 0; D3D12_STATIC_SAMPLER_DESC staticSamplers[1] = { }; staticSamplers[0] = DX12::GetStaticSamplerState(SamplerState::LinearClamp); @@ -315,9 +318,12 @@ void Skybox::Initialize() Float3(1.0f, -1.0f, -1.0f), }; - vertexBuffer.Initialize(sizeof(verts), DX12::VertexBufferAlignment, - false, BufferLifetime::Persistent, false, verts, - D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); + StructuredBufferInit vbInit; + vbInit.Stride = sizeof(Float3); + vbInit.NumElements = uint32(NumVertices); + vbInit.InitData = verts; + vbInit.Name = L"Skybox Vertex Buffer"; + vertexBuffer.Initialize(vbInit); uint16 indices[NumIndices] = { @@ -329,23 +335,18 @@ void Skybox::Initialize() 3, 2, 7, 7, 6, 3 // Bottom }; - indexBuffer.Initialize(sizeof(indices), DX12::IndexBufferAlignment, - false, BufferLifetime::Persistent, false, indices, - D3D12_RESOURCE_STATE_INDEX_BUFFER); - - // Create the VS constant buffer - vsConstantBuffer.Initialize(BufferLifetime::Temporary); - - // Create the PS constant buffer - psConstantBuffer.Initialize(BufferLifetime::Temporary); + FormattedBufferInit ibInit; + ibInit.Format = DXGI_FORMAT_R16_UINT; + ibInit.NumElements = uint32(NumIndices); + ibInit.InitData = indices; + ibInit.Name = L"SpriteRenderer Index Buffer"; + indexBuffer.Initialize(ibInit); } void Skybox::Shutdown() { DestroyPSOs(); - vsConstantBuffer.Shutdown(); - psConstantBuffer.Shutdown(); vertexBuffer.Shutdown(); indexBuffer.Shutdown(); DX12::Release(rootSignature); @@ -385,37 +386,27 @@ void Skybox::DestroyPSOs() void Skybox::RenderCommon(ID3D12GraphicsCommandList* cmdList, const Texture* environmentMap, const Float4x4& view, const Float4x4& projection, Float3 scale) { - // Set the constants - vsConstantBuffer.Data.View = view; - vsConstantBuffer.Data.Projection = projection; - vsConstantBuffer.Upload(); - - psConstantBuffer.Data.Scale = scale; - psConstantBuffer.Upload(); - // Set pipeline state cmdList->SetPipelineState(pipelineState); cmdList->SetGraphicsRootSignature(rootSignature); cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - // Bind descriptors and constant buffers - D3D12_CPU_DESCRIPTOR_HANDLE psResources[1] = { environmentMap->SRV.CPUHandle }; + DX12::BindStandardDescriptorTable(cmdList, RootParam_StandardDescriptors, CmdListMode::Graphics); + + // Bind the constant buffers + vsConstants.View = view; + vsConstants.Projection = projection; + DX12::BindTempConstantBuffer(cmdList, vsConstants, RootParam_VSCBuffer, CmdListMode::Graphics); - DX12::BindShaderResources(cmdList, 0, ArraySize_(psResources), psResources, CmdListMode::Graphics, ShaderResourceType::SRV_UAV_CBV); - vsConstantBuffer.SetAsGfxRootParameter(cmdList, 1); - psConstantBuffer.SetAsGfxRootParameter(cmdList, 2); + psConstants.Scale = scale; + psConstants.EnvMapIdx = environmentMap->SRV; + DX12::BindTempConstantBuffer(cmdList, psConstants, RootParam_PSCBuffer, CmdListMode::Graphics); // Set vertex/index buffers - D3D12_VERTEX_BUFFER_VIEW vbView = { }; - vbView.BufferLocation = vertexBuffer.GPUAddress; - vbView.SizeInBytes = uint32(vertexBuffer.Size); - vbView.StrideInBytes = sizeof(Float3); + D3D12_VERTEX_BUFFER_VIEW vbView = vertexBuffer.VBView(); cmdList->IASetVertexBuffers(0, 1, &vbView); - D3D12_INDEX_BUFFER_VIEW ibView = { }; - ibView.BufferLocation = indexBuffer.GPUAddress; - ibView.SizeInBytes = uint32(indexBuffer.Size); - ibView.Format = DXGI_FORMAT_R16_UINT; + D3D12_INDEX_BUFFER_VIEW ibView = indexBuffer.IBView(); cmdList->IASetIndexBuffer(&ibView); // Draw @@ -427,7 +418,7 @@ void Skybox::RenderEnvironmentMap(ID3D12GraphicsCommandList* cmdList, const Flo { PIXMarker pixEvent(cmdList, "Skybox Render Environment Map"); - psConstantBuffer.Data.CosSunAngularRadius = 0.0f; + psConstants.CosSunAngularRadius = 0.0f; RenderCommon(cmdList, environmentMap, view, projection, scale); } @@ -442,21 +433,21 @@ void Skybox::RenderSky(ID3D12GraphicsCommandList* cmdList, const Float4x4& view, Assert_(skyCache.Initialized()); // Set the pixel shader constants - psConstantBuffer.Data.SunDirection = skyCache.SunDirection; - psConstantBuffer.Data.Scale = scale; + psConstants.SunDirection = skyCache.SunDirection; + psConstants.Scale = scale; if(enableSun) { Float3 sunColor = skyCache.SunRadiance; float maxComponent = Max(sunColor.x, Max(sunColor.y, sunColor.z)); if(maxComponent > FP16Max) sunColor *= (FP16Max / maxComponent); - psConstantBuffer.Data.SunColor = Float3::Clamp(sunColor, 0.0f, FP16Max); - psConstantBuffer.Data.CosSunAngularRadius = std::cos(DegToRad(skyCache.SunSize)); + psConstants.SunColor = Float3::Clamp(sunColor, 0.0f, FP16Max); + psConstants.CosSunAngularRadius = std::cos(DegToRad(skyCache.SunSize)); } else { - psConstantBuffer.Data.SunColor = 0.0f; - psConstantBuffer.Data.CosSunAngularRadius = 0.0f; + psConstants.SunColor = 0.0f; + psConstants.CosSunAngularRadius = 0.0f; } RenderCommon(cmdList, &skyCache.CubeMap, view, projection, scale); diff --git a/SampleFramework12/v1.00/Graphics/Skybox.h b/SampleFramework12/v1.01/Graphics/Skybox.h similarity index 94% rename from SampleFramework12/v1.00/Graphics/Skybox.h rename to SampleFramework12/v1.01/Graphics/Skybox.h index a293ca7..d63138c 100644 --- a/SampleFramework12/v1.00/Graphics/Skybox.h +++ b/SampleFramework12/v1.01/Graphics/Skybox.h @@ -104,14 +104,15 @@ class Skybox Float3 SunColor = 1.0f; uint32 Padding = 0; Float3 Scale = 1.0f; + uint32 EnvMapIdx = uint32(-1); }; CompiledShaderPtr vertexShader; CompiledShaderPtr pixelShader; - Buffer vertexBuffer; - Buffer indexBuffer; - ConstantBuffer vsConstantBuffer; - ConstantBuffer psConstantBuffer; + StructuredBuffer vertexBuffer; + FormattedBuffer indexBuffer; + VSConstants vsConstants; + PSConstants psConstants; ID3D12RootSignature* rootSignature; ID3D12PipelineState* pipelineState; }; diff --git a/SampleFramework12/v1.00/Graphics/Spectrum.cpp b/SampleFramework12/v1.01/Graphics/Spectrum.cpp similarity index 100% rename from SampleFramework12/v1.00/Graphics/Spectrum.cpp rename to SampleFramework12/v1.01/Graphics/Spectrum.cpp diff --git a/SampleFramework12/v1.00/Graphics/Spectrum.h b/SampleFramework12/v1.01/Graphics/Spectrum.h similarity index 100% rename from SampleFramework12/v1.00/Graphics/Spectrum.h rename to SampleFramework12/v1.01/Graphics/Spectrum.h diff --git a/SampleFramework12/v1.00/Graphics/SpriteFont.cpp b/SampleFramework12/v1.01/Graphics/SpriteFont.cpp similarity index 100% rename from SampleFramework12/v1.00/Graphics/SpriteFont.cpp rename to SampleFramework12/v1.01/Graphics/SpriteFont.cpp diff --git a/SampleFramework12/v1.00/Graphics/SpriteFont.h b/SampleFramework12/v1.01/Graphics/SpriteFont.h similarity index 100% rename from SampleFramework12/v1.00/Graphics/SpriteFont.h rename to SampleFramework12/v1.01/Graphics/SpriteFont.h diff --git a/SampleFramework12/v1.00/Graphics/SpriteRenderer.cpp b/SampleFramework12/v1.01/Graphics/SpriteRenderer.cpp similarity index 69% rename from SampleFramework12/v1.00/Graphics/SpriteRenderer.cpp rename to SampleFramework12/v1.01/Graphics/SpriteRenderer.cpp index 0aec7d4..9b1d79b 100644 --- a/SampleFramework12/v1.00/Graphics/SpriteRenderer.cpp +++ b/SampleFramework12/v1.01/Graphics/SpriteRenderer.cpp @@ -17,11 +17,11 @@ namespace SampleFramework12 { -enum RootParams +enum RootParams : uint32 { - SRVParam_VS, - SRVParam_PS, - CBVParam, + RootParam_StandardDescriptors, + RootParam_PerBatchCB, + RootParam_SRVIndicesCB, NumRootParams }; @@ -43,53 +43,34 @@ void SpriteRenderer::Initialize() vertexShader = CompileFromFile(shaderPath.c_str(), "SpriteVS", ShaderType::Vertex); pixelShader = CompileFromFile(shaderPath.c_str(), "SpritePS", ShaderType::Pixel); - // Create the instance data buffer - StructuredBufferInit sbInit; - sbInit.Dynamic = true; - sbInit.Lifetime = BufferLifetime::Temporary; - sbInit.NumElements = MaxBatchSize; - sbInit.Stride = sizeof(SpriteDrawData); - instanceDataBuffer.Initialize(sbInit); - // Create the index buffer uint16 indices[] = { 0, 1, 2, 3, 0, 2 }; - indexBuffer.Initialize(sizeof(indices), 4, false, BufferLifetime::Persistent, false, indices, D3D12_RESOURCE_STATE_INDEX_BUFFER); - - // Create our constant buffers - perBatchCB.Initialize(BufferLifetime::Temporary); + FormattedBufferInit ibInit; + ibInit.Format = DXGI_FORMAT_R16_UINT; + ibInit.NumElements = ArraySize_(indices); + ibInit.InitData = indices; + ibInit.Name = L"SpriteRenderer Index Buffer"; + indexBuffer.Initialize(ibInit); LoadTexture(defaultTexture, L"..\\Content\\Textures\\Default.dds"); { // Make the root signature - D3D12_DESCRIPTOR_RANGE1 ranges[2] = { }; - ranges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - ranges[0].NumDescriptors = 1; - ranges[0].BaseShaderRegister = 0; - ranges[0].RegisterSpace = 0; - ranges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - - ranges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - ranges[1].NumDescriptors = 1; - ranges[1].BaseShaderRegister = 1; - ranges[1].RegisterSpace = 0; - ranges[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; - D3D12_ROOT_PARAMETER1 rootParameters[NumRootParams] = { }; - rootParameters[SRVParam_VS].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[SRVParam_VS].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; - rootParameters[SRVParam_VS].DescriptorTable.pDescriptorRanges = &ranges[0]; - rootParameters[SRVParam_VS].DescriptorTable.NumDescriptorRanges = 1; + rootParameters[RootParam_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[RootParam_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[RootParam_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[RootParam_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; - rootParameters[SRVParam_PS].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[SRVParam_PS].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[SRVParam_PS].DescriptorTable.pDescriptorRanges = &ranges[1]; - rootParameters[SRVParam_PS].DescriptorTable.NumDescriptorRanges = 1; + rootParameters[RootParam_PerBatchCB].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[RootParam_PerBatchCB].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[RootParam_PerBatchCB].Descriptor.RegisterSpace = 0; + rootParameters[RootParam_PerBatchCB].Descriptor.ShaderRegister = 0; - rootParameters[CBVParam].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[CBVParam].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - rootParameters[CBVParam].Descriptor.RegisterSpace = 0; - rootParameters[CBVParam].Descriptor.ShaderRegister = 0; + rootParameters[RootParam_SRVIndicesCB].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[RootParam_SRVIndicesCB].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[RootParam_SRVIndicesCB].Descriptor.RegisterSpace = 0; + rootParameters[RootParam_SRVIndicesCB].Descriptor.ShaderRegister = 1; D3D12_STATIC_SAMPLER_DESC staticSamplers[2] = { }; staticSamplers[0] = DX12::GetStaticSamplerState(SamplerState::Point, 0); @@ -111,7 +92,6 @@ void SpriteRenderer::Shutdown() DestroyPSOs(); indexBuffer.Shutdown(); - instanceDataBuffer.Shutdown(); defaultTexture.Shutdown(); DX12::Release(rootSignature); } @@ -151,16 +131,15 @@ void SpriteRenderer::Begin(ID3D12GraphicsCommandList* cmdList, Float2 viewportSi cmdList->SetPipelineState(pipelineStates[uint64(blendMode)]); cmdList->SetGraphicsRootSignature(rootSignature); - perBatchCB.Data.LinearSampling = filterMode == SpriteFilterMode::Linear ? 1 : 0; - perBatchCB.Data.ViewportSize = viewportSize; + perBatchData.LinearSampling = filterMode == SpriteFilterMode::Linear ? 1 : 0; + perBatchData.ViewportSize = viewportSize; cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - D3D12_INDEX_BUFFER_VIEW ibView = { }; - ibView.BufferLocation = indexBuffer.GPUAddress; - ibView.SizeInBytes = uint32(indexBuffer.Size); - ibView.Format = DXGI_FORMAT_R16_UINT; + D3D12_INDEX_BUFFER_VIEW ibView = indexBuffer.IBView(); cmdList->IASetIndexBuffer(&ibView); + + DX12::BindStandardDescriptorTable(cmdList, RootParam_StandardDescriptors, CmdListMode::Graphics); } void SpriteRenderer::Render(ID3D12GraphicsCommandList* cmdList, const Texture* texture, const SpriteTransform& transform, @@ -189,9 +168,8 @@ void SpriteRenderer::RenderBatch(ID3D12GraphicsCommandList* cmdList, const Textu if(texture == nullptr) texture = &defaultTexture; - perBatchCB.Data.TextureSize = Float2(float(texture->Width), float(texture->Height)); - perBatchCB.Upload(); - perBatchCB.SetAsGfxRootParameter(cmdList, CBVParam); + perBatchData.TextureSize = Float2(float(texture->Width), float(texture->Height)); + DX12::BindTempConstantBuffer(cmdList, perBatchData, RootParam_PerBatchCB, CmdListMode::Graphics); #if Debug_ // Make sure the draw rects are all valid @@ -211,14 +189,11 @@ void SpriteRenderer::RenderBatch(ID3D12GraphicsCommandList* cmdList, const Textu const uint64 spritesToDraw = Min(MaxBatchSize, numSpritesLeft); // Fill up the instance buffer - instanceDataBuffer.MapAndSetData(drawData + offset, spritesToDraw); - - // Bind the resources - D3D12_CPU_DESCRIPTOR_HANDLE vsDescriptors[] = { instanceDataBuffer.SRV() }; - DX12::BindShaderResources(cmdList, SRVParam_VS, ArraySize_(vsDescriptors), vsDescriptors); + TempBuffer instanceBuffer = DX12::TempStructuredBuffer(spritesToDraw, sizeof(SpriteDrawData)); + memcpy(instanceBuffer.CPUAddress, drawData + offset, spritesToDraw * sizeof(SpriteDrawData)); - D3D12_CPU_DESCRIPTOR_HANDLE psDescriptors[] = { texture->SRV.CPUHandle }; - DX12::BindShaderResources(cmdList, SRVParam_PS, ArraySize_(psDescriptors), psDescriptors); + uint32 srvIndices[] = { instanceBuffer.DescriptorIndex, texture->SRV }; + DX12::BindTempConstantBuffer(cmdList, srvIndices, RootParam_SRVIndicesCB, CmdListMode::Graphics); // Draw cmdList->DrawIndexedInstanced(6, uint32(spritesToDraw), 0, 0, 0); diff --git a/SampleFramework12/v1.00/Graphics/SpriteRenderer.h b/SampleFramework12/v1.01/Graphics/SpriteRenderer.h similarity index 96% rename from SampleFramework12/v1.00/Graphics/SpriteRenderer.h rename to SampleFramework12/v1.01/Graphics/SpriteRenderer.h index a9784f4..c5a7110 100644 --- a/SampleFramework12/v1.00/Graphics/SpriteRenderer.h +++ b/SampleFramework12/v1.01/Graphics/SpriteRenderer.h @@ -108,21 +108,19 @@ class SpriteRenderer ShaderPtr vertexShaderInstanced; ShaderPtr pixelShader; ShaderPtr pixelShaderOpaque; - Buffer indexBuffer; + FormattedBuffer indexBuffer; StructuredBuffer instanceDataBuffer; SpriteDrawData textDrawData[MaxBatchSize]; ID3D12PipelineState* pipelineStates[uint64(SpriteBlendMode::NumValues)] = { }; ID3D12RootSignature* rootSignature = nullptr; Texture defaultTexture; - struct PerBatchCB + struct PerBatchConstants { Float2 TextureSize; Float2 ViewportSize; bool32 LinearSampling = false; - }; - - ConstantBuffer perBatchCB; + } perBatchData; }; } \ No newline at end of file diff --git a/SampleFramework12/v1.00/Graphics/SwapChain.cpp b/SampleFramework12/v1.01/Graphics/SwapChain.cpp similarity index 89% rename from SampleFramework12/v1.00/Graphics/SwapChain.cpp rename to SampleFramework12/v1.01/Graphics/SwapChain.cpp index b56d1fa..733c21e 100644 --- a/SampleFramework12/v1.00/Graphics/SwapChain.cpp +++ b/SampleFramework12/v1.01/Graphics/SwapChain.cpp @@ -58,7 +58,7 @@ void SwapChain::Initialize(HWND outputWindow) Shutdown(); // We'll just use the first output for fullscreen - DXCall(DX12::Adapter->EnumOutputs(0, &output)); + DX12::Adapter->EnumOutputs(0, &output); if(format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) noSRGBFormat = DXGI_FORMAT_R8G8B8A8_UNORM; @@ -77,7 +77,9 @@ void SwapChain::Initialize(HWND outputWindow) swapChainDesc.OutputWindow = outputWindow; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.Windowed = TRUE; - swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH | DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING; + swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH | + DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING | + DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; IDXGISwapChain* tempSwapChain = nullptr; DXCall(DX12::Factory->CreateSwapChain(DX12::GfxQueue, &swapChainDesc, &tempSwapChain)); @@ -85,6 +87,7 @@ void SwapChain::Initialize(HWND outputWindow) DX12::Release(tempSwapChain); backBufferIdx = swapChain->GetCurrentBackBufferIndex(); + waitableObject = swapChain->GetFrameLatencyWaitableObject(); AfterReset(); } @@ -94,7 +97,7 @@ void SwapChain::Shutdown() for(uint64 i = 0; i < NumBackBuffers; ++i) { DX12::Release(backBuffers[i].Texture.Resource); - DX12::RTVDescriptorHeap.Free(backBuffers[i].RTV); + DX12::RTVDescriptorHeap.FreePersistent(backBuffers[i].RTV); } DX12::Release(swapChain); @@ -106,7 +109,7 @@ void SwapChain::AfterReset() // Re-create an RTV for each back buffer for(uint64 i = 0; i < NumBackBuffers; i++) { - backBuffers[i].RTV = DX12::RTVDescriptorHeap.Allocate(); + backBuffers[i].RTV = DX12::RTVDescriptorHeap.AllocatePersistent().Handles[0]; DXCall(swapChain->GetBuffer(uint32(i), IID_PPV_ARGS(&backBuffers[i].Texture.Resource))); D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = { }; @@ -114,7 +117,7 @@ void SwapChain::AfterReset() rtvDesc.Format = format; rtvDesc.Texture2D.MipSlice = 0; rtvDesc.Texture2D.PlaneSlice = 0; - DX12::Device->CreateRenderTargetView(backBuffers[i].Texture.Resource, &rtvDesc, backBuffers[i].RTV.CPUHandle); + DX12::Device->CreateRenderTargetView(backBuffers[i].Texture.Resource, &rtvDesc, backBuffers[i].RTV); backBuffers[i].Texture.Resource->SetName(MakeString(L"Back Buffer %llu", i).c_str()); @@ -159,12 +162,14 @@ void SwapChain::PrepareFullScreenSettings() void SwapChain::Reset() { Assert_(swapChain); + if(output == nullptr) + fullScreen = false; // Release all references for(uint64 i = 0; i < NumBackBuffers; ++i) { DX12::Release(backBuffers[i].Texture.Resource); - DX12::RTVDescriptorHeap.Free(backBuffers[i].RTV); + DX12::RTVDescriptorHeap.FreePersistent(backBuffers[i].RTV); } if(format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) @@ -184,8 +189,10 @@ void SwapChain::Reset() DXCall(swapChain->SetFullscreenState(fullScreen, NULL)); - DXCall(swapChain->ResizeBuffers(NumBackBuffers, width, height, noSRGBFormat, - DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH | DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING)); + DXCall(swapChain->ResizeBuffers(NumBackBuffers, width, height, noSRGBFormat, + DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH | + DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING | + DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT)); if(fullScreen) { diff --git a/SampleFramework12/v1.00/Graphics/SwapChain.h b/SampleFramework12/v1.01/Graphics/SwapChain.h similarity index 95% rename from SampleFramework12/v1.00/Graphics/SwapChain.h rename to SampleFramework12/v1.01/Graphics/SwapChain.h index 83a2748..7927b48 100644 --- a/SampleFramework12/v1.00/Graphics/SwapChain.h +++ b/SampleFramework12/v1.01/Graphics/SwapChain.h @@ -42,6 +42,7 @@ class SwapChain bool FullScreen() const { return fullScreen; }; bool VSYNCEnabled() const { return vsync; }; uint32 NumVSYNCIntervals() const { return vsync ? numVSYNCIntervals : 0; }; + HANDLE WaitableObject() const { return waitableObject; } // Setters void SetFormat(DXGI_FORMAT format_) { format = format_; }; @@ -62,6 +63,7 @@ class SwapChain IDXGISwapChain4* swapChain = nullptr; uint32 backBufferIdx = 0; RenderTexture backBuffers[NumBackBuffers]; + HANDLE waitableObject = INVALID_HANDLE_VALUE; IDXGIOutput* output = nullptr; diff --git a/SampleFramework12/v1.00/Graphics/Textures.cpp b/SampleFramework12/v1.01/Graphics/Textures.cpp similarity index 90% rename from SampleFramework12/v1.00/Graphics/Textures.cpp rename to SampleFramework12/v1.01/Graphics/Textures.cpp index be986d9..d46f3a4 100644 --- a/SampleFramework12/v1.00/Graphics/Textures.cpp +++ b/SampleFramework12/v1.01/Graphics/Textures.cpp @@ -21,11 +21,6 @@ namespace SampleFramework12 { -static const uint64 MaxSubResources = 1024; -static D3D12_PLACED_SUBRESOURCE_FOOTPRINT Layouts[MaxSubResources] = { }; -static uint32 NumRows[MaxSubResources] = { 0 }; -static uint64 RowSizes[MaxSubResources] = { 0 }; - // Returns the number of mip levels given a texture size static uint64 NumMipLevels(uint64 width, uint64 height, uint64 depth = 1) { @@ -88,9 +83,12 @@ void LoadTexture(Texture& texture, const wchar* filePath, bool forceSRGB) ID3D12Device* device = DX12::Device; DXCall(device->CreateCommittedResource(DX12::GetDefaultHeapProps(), D3D12_HEAP_FLAG_NONE, &textureDesc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&texture.Resource))); + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&texture.Resource))); + texture.Resource->SetName(filePath); + + PersistentDescriptorAlloc srvAlloc = DX12::SRVDescriptorHeap.AllocatePersistent(); + texture.SRV = srvAlloc.Index; - texture.SRV = DX12::SRVDescriptorHeap.Allocate(); const D3D12_SHADER_RESOURCE_VIEW_DESC* srvDescPtr = nullptr; D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { }; if(metaData.IsCubemap()) @@ -104,12 +102,16 @@ void LoadTexture(Texture& texture, const wchar* filePath, bool forceSRGB) srvDescPtr = &srvDesc; } - device->CreateShaderResourceView(texture.Resource, srvDescPtr, texture.SRV.CPUHandle); + for(uint32 i = 0; i < DX12::SRVDescriptorHeap.NumHeaps; ++i) + device->CreateShaderResourceView(texture.Resource, srvDescPtr, srvAlloc.Handles[i]); const uint64 numSubResources = metaData.mipLevels * metaData.arraySize; - Assert_(numSubResources <= MaxSubResources); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT* layouts = (D3D12_PLACED_SUBRESOURCE_FOOTPRINT*)_alloca(sizeof(D3D12_PLACED_SUBRESOURCE_FOOTPRINT) * numSubResources); + uint32* numRows = (uint32*)_alloca(sizeof(uint32) * numSubResources); + uint64* rowSizes = (uint64*)_alloca(sizeof(uint64) * numSubResources); + uint64 textureMemSize = 0; - device->GetCopyableFootprints(&textureDesc, 0, uint32(numSubResources), 0, Layouts, NumRows, RowSizes, &textureMemSize); + device->GetCopyableFootprints(&textureDesc, 0, uint32(numSubResources), 0, layouts, numRows, rowSizes, &textureMemSize); // Get a GPU upload buffer UploadContext uploadContext = DX12::ResourceUploadBegin(textureMemSize); @@ -122,8 +124,8 @@ void LoadTexture(Texture& texture, const wchar* filePath, bool forceSRGB) { const uint64 subResourceIdx = mipIdx + (arrayIdx * metaData.mipLevels); - const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& subResourceLayout = Layouts[subResourceIdx]; - const uint64 subResourceHeight = NumRows[subResourceIdx]; + const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& subResourceLayout = layouts[subResourceIdx]; + const uint64 subResourceHeight = numRows[subResourceIdx]; const uint64 subResourcePitch = subResourceLayout.Footprint.RowPitch; const uint64 subResourceDepth = subResourceLayout.Footprint.Depth; uint8* dstSubResourceMem = reinterpret_cast(uploadMem) + subResourceLayout.Offset; @@ -153,7 +155,7 @@ void LoadTexture(Texture& texture, const wchar* filePath, bool forceSRGB) D3D12_TEXTURE_COPY_LOCATION src = { }; src.pResource = uploadContext.Resource; src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - src.PlacedFootprint = Layouts[subResourceIdx]; + src.PlacedFootprint = layouts[subResourceIdx]; src.PlacedFootprint.Offset += uploadContext.ResourceOffset; uploadContext.CmdList->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); } @@ -201,10 +203,11 @@ void Create2DTexture(Texture& texture, uint64 width, uint64 height, uint64 numMi ID3D12Device* device = DX12::Device; DXCall(device->CreateCommittedResource(DX12::GetDefaultHeapProps(), D3D12_HEAP_FLAG_NONE, &textureDesc, - initData ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + initData ? D3D12_RESOURCE_STATE_COMMON : D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, nullptr, IID_PPV_ARGS(&texture.Resource))); - texture.SRV = DX12::SRVDescriptorHeap.Allocate(); + PersistentDescriptorAlloc srvAlloc = DX12::SRVDescriptorHeap.AllocatePersistent(); + texture.SRV = srvAlloc.Index; D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { }; srvDesc.Format = format; @@ -245,7 +248,8 @@ void Create2DTexture(Texture& texture, uint64 width, uint64 height, uint64 numMi srvDesc.TextureCubeArray.NumCubes = uint32(srvArraySize); } - device->CreateShaderResourceView(texture.Resource, &srvDesc, texture.SRV.CPUHandle); + for(uint32 i = 0; i < DX12::SRVDescriptorHeap.NumHeaps; ++i) + device->CreateShaderResourceView(texture.Resource, &srvDesc, srvAlloc.Handles[i]); texture.Width = uint32(width); texture.Height = uint32(height); @@ -286,10 +290,11 @@ void Create3DTexture(Texture& texture, uint64 width, uint64 height, uint64 depth ID3D12Device* device = DX12::Device; DXCall(device->CreateCommittedResource(DX12::GetDefaultHeapProps(), D3D12_HEAP_FLAG_NONE, &textureDesc, - initData ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + initData ? D3D12_RESOURCE_STATE_COMMON : D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, nullptr, IID_PPV_ARGS(&texture.Resource))); - texture.SRV = DX12::SRVDescriptorHeap.Allocate(); + PersistentDescriptorAlloc srvAlloc = DX12::SRVDescriptorHeap.AllocatePersistent(); + texture.SRV = srvAlloc.Index; D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = { }; srvDesc.Format = format; @@ -299,7 +304,8 @@ void Create3DTexture(Texture& texture, uint64 width, uint64 height, uint64 depth srvDesc.Texture3D.MostDetailedMip = 0; srvDesc.Texture3D.ResourceMinLODClamp = 0.0f; - device->CreateShaderResourceView(texture.Resource, &srvDesc, texture.SRV.CPUHandle); + for(uint32 i = 0; i < DX12::SRVDescriptorHeap.NumHeaps; ++i) + device->CreateShaderResourceView(texture.Resource, &srvDesc, srvAlloc.Handles[i]); texture.Width = uint32(width); texture.Height = uint32(height); @@ -339,9 +345,12 @@ void UploadTextureData(const Texture& texture, const void* initData, ID3D12Graph const uint64 arraySize = texture.Cubemap ? texture.ArraySize * 6 : texture.ArraySize; const uint64 numSubResources = texture.NumMips * arraySize; - Assert_(numSubResources <= MaxSubResources); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT* layouts = (D3D12_PLACED_SUBRESOURCE_FOOTPRINT*)_alloca(sizeof(D3D12_PLACED_SUBRESOURCE_FOOTPRINT) * numSubResources); + uint32* numRows = (uint32*)_alloca(sizeof(uint32) * numSubResources); + uint64* rowSizes = (uint64*)_alloca(sizeof(uint64) * numSubResources); + uint64 textureMemSize = 0; - device->GetCopyableFootprints(&textureDesc, 0, uint32(numSubResources), 0, Layouts, NumRows, RowSizes, &textureMemSize); + device->GetCopyableFootprints(&textureDesc, 0, uint32(numSubResources), 0, layouts, numRows, rowSizes, &textureMemSize); // Get a GPU upload buffer uint8* uploadMem = reinterpret_cast(uploadCPUMem); @@ -356,8 +365,8 @@ void UploadTextureData(const Texture& texture, const void* initData, ID3D12Graph { const uint64 subResourceIdx = mipIdx + (arrayIdx * texture.NumMips); - const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& subResourceLayout = Layouts[subResourceIdx]; - const uint64 subResourceHeight = NumRows[subResourceIdx]; + const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& subResourceLayout = layouts[subResourceIdx]; + const uint64 subResourceHeight = numRows[subResourceIdx]; const uint64 subResourcePitch = subResourceLayout.Footprint.RowPitch; const uint64 subResourceDepth = subResourceLayout.Footprint.Depth; const uint64 srcPitch = mipWidth * srcTexelSize; @@ -386,7 +395,7 @@ void UploadTextureData(const Texture& texture, const void* initData, ID3D12Graph D3D12_TEXTURE_COPY_LOCATION src = {}; src.pResource = uploadResource; src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - src.PlacedFootprint = Layouts[subResourceIdx]; + src.PlacedFootprint = layouts[subResourceIdx]; src.PlacedFootprint.Offset += resourceOffset; cmdList->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); } diff --git a/SampleFramework12/v1.00/Graphics/Textures.h b/SampleFramework12/v1.01/Graphics/Textures.h similarity index 100% rename from SampleFramework12/v1.00/Graphics/Textures.h rename to SampleFramework12/v1.01/Graphics/Textures.h diff --git a/Externals/HosekSky/Include/ArHosekSkyModel.c b/SampleFramework12/v1.01/HosekSky/ArHosekSkyModel.cpp similarity index 99% rename from Externals/HosekSky/Include/ArHosekSkyModel.c rename to SampleFramework12/v1.01/HosekSky/ArHosekSkyModel.cpp index 17c8880..6161b7f 100644 --- a/Externals/HosekSky/Include/ArHosekSkyModel.c +++ b/SampleFramework12/v1.01/HosekSky/ArHosekSkyModel.cpp @@ -97,6 +97,8 @@ All instructions on how to use this code are in the accompanying header file. */ +#include "PCH.h" + #include "ArHosekSkyModel.h" #include "ArHosekSkyModelData_Spectral.h" #include "ArHosekSkyModelData_CIEXYZ.h" @@ -523,7 +525,7 @@ double arhosekskymodel_radiance( double wavelength ) { - int low_wl = (wavelength - 320.0 ) / 40.0; + int low_wl = int((wavelength - 320.0 ) / 40.0); if ( low_wl < 0 || low_wl >= 11 ) return 0.0f; diff --git a/Externals/HosekSky/Include/ArHosekSkyModel.h b/SampleFramework12/v1.01/HosekSky/ArHosekSkyModel.h similarity index 100% rename from Externals/HosekSky/Include/ArHosekSkyModel.h rename to SampleFramework12/v1.01/HosekSky/ArHosekSkyModel.h diff --git a/Externals/HosekSky/Include/ArHosekSkyModelData_CIEXYZ.h b/SampleFramework12/v1.01/HosekSky/ArHosekSkyModelData_CIEXYZ.h similarity index 100% rename from Externals/HosekSky/Include/ArHosekSkyModelData_CIEXYZ.h rename to SampleFramework12/v1.01/HosekSky/ArHosekSkyModelData_CIEXYZ.h diff --git a/Externals/HosekSky/Include/ArHosekSkyModelData_RGB.h b/SampleFramework12/v1.01/HosekSky/ArHosekSkyModelData_RGB.h similarity index 100% rename from Externals/HosekSky/Include/ArHosekSkyModelData_RGB.h rename to SampleFramework12/v1.01/HosekSky/ArHosekSkyModelData_RGB.h diff --git a/Externals/HosekSky/Include/ArHosekSkyModelData_Spectral.h b/SampleFramework12/v1.01/HosekSky/ArHosekSkyModelData_Spectral.h similarity index 100% rename from Externals/HosekSky/Include/ArHosekSkyModelData_Spectral.h rename to SampleFramework12/v1.01/HosekSky/ArHosekSkyModelData_Spectral.h diff --git a/Externals/HosekSky/Include/README.txt b/SampleFramework12/v1.01/HosekSky/README.txt similarity index 100% rename from Externals/HosekSky/Include/README.txt rename to SampleFramework12/v1.01/HosekSky/README.txt diff --git a/SampleFramework12/v1.01/ImGui/LICENSE b/SampleFramework12/v1.01/ImGui/LICENSE new file mode 100644 index 0000000..b28ef22 --- /dev/null +++ b/SampleFramework12/v1.01/ImGui/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2015 Omar Cornut and ImGui contributors + +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. diff --git a/Externals/imgui-1.46/Include/imconfig.h b/SampleFramework12/v1.01/ImGui/imconfig.h similarity index 74% rename from Externals/imgui-1.46/Include/imconfig.h rename to SampleFramework12/v1.01/ImGui/imconfig.h index 20f58b2..1daa254 100644 --- a/Externals/imgui-1.46/Include/imconfig.h +++ b/SampleFramework12/v1.01/ImGui/imconfig.h @@ -13,9 +13,6 @@ //#define IMGUI_API __declspec( dllexport ) //#define IMGUI_API __declspec( dllimport ) -//---- Include imgui_user.inl at the end of imgui.cpp so you can include code that extends ImGui using its private data/functions. -//#define IMGUI_INCLUDE_IMGUI_USER_INL - //---- Include imgui_user.h at the end of imgui.h //#define IMGUI_INCLUDE_IMGUI_USER_H @@ -29,6 +26,9 @@ //---- Don't define obsolete functions names //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS +//---- Pack colors to BGRA instead of RGBA (remove need to post process vertex buffer in back ends) +//#define IMGUI_USE_BGRA_PACKED_COLOR + //---- Implement STB libraries in a namespace to avoid conflicts //#define IMGUI_STB_NAMESPACE ImGuiStb @@ -43,14 +43,15 @@ operator MyVec4() const { return MyVec4(x,y,z,w); } */ -//---- Freely implement extra functions within the ImGui:: namespace. -//---- Declare helpers or widgets implemented in imgui_user.inl or elsewhere, so end-user doesn't need to include multiple files. -//---- e.g. you can create variants of the ImGui::Value() helper for your low-level math types, or your own widgets/helpers. +//---- Use 32-bit vertex indices (instead of default: 16-bit) to allow meshes with more than 64K vertices +//#define ImDrawIdx unsigned int + +//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. +//---- e.g. create variants of the ImGui::Value() helper for your low-level math types, or your own widgets/helpers. /* namespace ImGui { - void Value(const char* prefix, const MyVec2& v, const char* float_format = NULL); - void Value(const char* prefix, const MyVec4& v, const char* float_format = NULL); + void Value(const char* prefix, const MyMatrix44& v, const char* float_format = NULL); } */ diff --git a/SampleFramework12/v1.01/ImGui/imgui.cpp b/SampleFramework12/v1.01/ImGui/imgui.cpp new file mode 100644 index 0000000..c4c5684 --- /dev/null +++ b/SampleFramework12/v1.01/ImGui/imgui.cpp @@ -0,0 +1,9863 @@ +// dear imgui, v1.50 +// (main code and documentation) + +// See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code. +// Newcomers, read 'Programmer guide' below for notes on how to setup ImGui in your codebase. +// Get latest version at https://github.com/ocornut/imgui +// Releases change-log at https://github.com/ocornut/imgui/releases +// Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/772 +// Developed by Omar Cornut and every direct or indirect contributors to the GitHub. +// This library is free but I need your support to sustain development and maintenance. +// If you work for a company, please consider financial support, e.g: https://www.patreon.com/imgui + +/* + + Index + - MISSION STATEMENT + - END-USER GUIDE + - PROGRAMMER GUIDE (read me!) + - API BREAKING CHANGES (read me when you update!) + - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS + - How can I help? + - How do I update to a newer version of ImGui? + - What is ImTextureID and how do I display an image? + - I integrated ImGui in my engine and the text or lines are blurry.. + - I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around.. + - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs. + - How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? + - How can I load a different font than the default? + - How can I easily use icons in my application? + - How can I load multiple fonts? + - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic? + - How can I use the drawing facilities without an ImGui window? (using ImDrawList API) + - ISSUES & TODO-LIST + - CODE + + + MISSION STATEMENT + ================= + + - easy to use to create code-driven and data-driven tools + - easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools + - easy to hack and improve + - minimize screen real-estate usage + - minimize setup and maintenance + - minimize state storage on user side + - portable, minimize dependencies, run on target (consoles, phones, etc.) + - efficient runtime (NB- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything) + - read about immediate-mode gui principles @ http://mollyrocket.com/861, http://mollyrocket.com/forums/index.html + + Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes: + - doesn't look fancy, doesn't animate + - limited layout features, intricate layouts are typically crafted in code + - occasionally uses statically sized buffers for string manipulations - won't crash, but some very long pieces of text may be clipped. functions like ImGui::TextUnformatted() don't have such restriction. + + + END-USER GUIDE + ============== + + - double-click title bar to collapse window + - click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin() + - click and drag on lower right corner to resize window + - click and drag on any empty space to move window + - double-click/double-tap on lower right corner grip to auto-fit to content + - TAB/SHIFT+TAB to cycle through keyboard editable fields + - use mouse wheel to scroll + - use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true) + - CTRL+Click on a slider or drag box to input value as text + - text editor: + - Hold SHIFT or use mouse to select text. + - CTRL+Left/Right to word jump + - CTRL+Shift+Left/Right to select words + - CTRL+A our Double-Click to select all + - CTRL+X,CTRL+C,CTRL+V to use OS clipboard + - CTRL+Z,CTRL+Y to undo/redo + - ESCAPE to revert text to its original value + - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!) + + + PROGRAMMER GUIDE + ================ + + - read the FAQ below this section! + - your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention on your side, no state duplication, less sync, less bugs. + - call and read ImGui::ShowTestWindow() for demo code demonstrating most features. + - see examples/ folder for standalone sample applications. Prefer reading examples/opengl2_example/ first as it is the simplest. + you may be able to grab and copy a ready made imgui_impl_*** file from the examples/. + - customization: PushStyleColor()/PushStyleVar() or the style editor to tweak the look of the interface (e.g. if you want a more compact UI or a different color scheme). + + - getting started: + - init: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the fields marked 'Settings'. + - init: call io.Fonts->GetTexDataAsRGBA32(...) and load the font texture pixels into graphics memory. + - every frame: + 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the fields marked 'Input' + 2/ call ImGui::NewFrame() as early as you can! + 3/ use any ImGui function you want between NewFrame() and Render() + 4/ call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your RenderDrawListFn handler that you set in the IO structure. + (if you don't need to render, you still need to call Render() and ignore the callback, or call EndFrame() instead. if you call neither some aspects of windows focusing/moving will appear broken.) + - all rendering information are stored into command-lists until ImGui::Render() is called. + - ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide. + - effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases of your own application. + - refer to the examples applications in the examples/ folder for instruction on how to setup your code. + - a typical application skeleton may be: + + // Application init + ImGuiIO& io = ImGui::GetIO(); + io.DisplaySize.x = 1920.0f; + io.DisplaySize.y = 1280.0f; + io.IniFilename = "imgui.ini"; + io.RenderDrawListsFn = my_render_function; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access the render data. + // TODO: Fill others settings of the io structure + + // Load texture atlas + // There is a default font so you don't need to care about choosing a font yet + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height); + // TODO: At this points you've got a texture pointed to by 'pixels' and you need to upload that your your graphic system + // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID' + + // Application main loop + while (true) + { + // 1) get low-level inputs (e.g. on Win32, GetKeyboardState(), or poll your events, etc.) + // TODO: fill all fields of IO structure and call NewFrame + ImGuiIO& io = ImGui::GetIO(); + io.DeltaTime = 1.0f/60.0f; + io.MousePos = mouse_pos; + io.MouseDown[0] = mouse_button_0; + io.MouseDown[1] = mouse_button_1; + io.KeysDown[i] = ... + + // 2) call NewFrame(), after this point you can use ImGui::* functions anytime + ImGui::NewFrame(); + + // 3) most of your application code here + MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); + MyGameRender(); // may use any ImGui functions + + // 4) render & swap video buffers + ImGui::Render(); + SwapBuffers(); + } + + - You can read back 'io.WantCaptureMouse', 'io.WantCaptureKeybord' etc. flags from the IO structure to tell how ImGui intends to use your + inputs and to know if you should share them or hide them from the rest of your application. Read the FAQ below for more information. + + + API BREAKING CHANGES + ==================== + + Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix. + Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code. + Also read releases logs https://github.com/ocornut/imgui/releases for more details. + + - 2017/05/26 (1.50) - Removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset. + - 2017/05/01 (1.50) - Renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity. + - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild(). + - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it. + - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc. + - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal. + - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore. + If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you. + However if your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar. + This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color. + ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) + { + float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; + return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); + } + If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color. + - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext(). + - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection. + - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen). + - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDraw::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer. + - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337). + - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337) + - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete). + - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert. + - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you. + - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis. + - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete. + - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position. + GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side. + GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out! + - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize + - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project. + - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason + - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure. + you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text. + - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost. + this necessary change will break your rendering function! the fix should be very easy. sorry for that :( + - if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest. + - the signature of the io.RenderDrawListsFn handler has changed! + ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) + became: + ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data). + argument 'cmd_lists' -> 'draw_data->CmdLists' + argument 'cmd_lists_count' -> 'draw_data->CmdListsCount' + ImDrawList 'commands' -> 'CmdBuffer' + ImDrawList 'vtx_buffer' -> 'VtxBuffer' + ImDrawList n/a -> 'IdxBuffer' (new) + ImDrawCmd 'vtx_count' -> 'ElemCount' + ImDrawCmd 'clip_rect' -> 'ClipRect' + ImDrawCmd 'user_callback' -> 'UserCallback' + ImDrawCmd 'texture_id' -> 'TextureId' + - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer. + - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering! + - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade! + - 2015/07/10 (1.43) - changed SameLine() parameters from int to float. + - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete). + - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount. + - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence + - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry! + - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete). + - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete). + - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons. + - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened. + - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same). + - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50. + - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API + - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive. + - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead. + - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50. + - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing + - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50. + - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing) + - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50. + - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once. + - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now. + - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior + - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing() + - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused) + - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions. + - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader. + (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels. + this sequence: + const void* png_data; + unsigned int png_size; + ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); + // + became: + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + // + io.Fonts->TexID = (your_texture_identifier); + you now have much more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. + it is now recommended that you sample the font texture with bilinear interpolation. + (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID. + (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix) + (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets + - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver) + - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph) + - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility + - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered() + - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly) + - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) + - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale() + - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn + - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically) + - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite + - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes + + + FREQUENTLY ASKED QUESTIONS (FAQ), TIPS + ====================================== + + Q: How can I help? + A: - If you are experienced enough with ImGui and with C/C++, look at the todo list and see how you want/can help! + - Become a Patron/donate. Convince your company to become a Patron or provide serious funding for development time. + + Q: How do I update to a newer version of ImGui? + A: Overwrite the following files: + imgui.cpp + imgui.h + imgui_demo.cpp + imgui_draw.cpp + imgui_internal.h + stb_rect_pack.h + stb_textedit.h + stb_truetype.h + Don't overwrite imconfig.h if you have made modification to your copy. + If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it. + Check the "API BREAKING CHANGES" sections for a list of occasional API breaking changes. + Please report any issue to the GitHub page! + + Q: What is ImTextureID and how do I display an image? + A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function. + ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry! + It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc. + At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render. + Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing. + (c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!) + To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions. + ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use. + It is your responsibility to get textures uploaded to your GPU. + + Q: I integrated ImGui in my engine and the text or lines are blurry.. + A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f). + Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension. + + Q: I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around.. + A: Most likely you are mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height). + + Q: Can I have multiple widgets with the same label? Can I have widget without a label? (Yes) + A: Yes. A primer on the use of labels/IDs in ImGui.. + + - Elements that are not clickable, such as Text() items don't need an ID. + + - Interactive widgets require state to be carried over multiple frames (most typically ImGui often needs to remember what is the "active" widget). + to do so they need a unique ID. unique ID are typically derived from a string label, an integer index or a pointer. + + Button("OK"); // Label = "OK", ID = hash of "OK" + Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel" + + - ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK" in two different windows + or in two different locations of a tree. + + - If you have a same ID twice in the same location, you'll have a conflict: + + Button("OK"); + Button("OK"); // ID collision! Both buttons will be treated as the same. + + Fear not! this is easy to solve and there are many ways to solve it! + + - When passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases. + use "##" to pass a complement to the ID that won't be visible to the end-user: + + Button("Play"); // Label = "Play", ID = hash of "Play" + Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above) + Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above) + + - If you want to completely hide the label, but still need an ID: + + Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!) + + - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels. + For example you may want to include varying information in a window title bar (and windows are uniquely identified by their ID.. obviously) + Use "###" to pass a label that isn't part of ID: + + Button("Hello###ID"; // Label = "Hello", ID = hash of "ID" + Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above) + + sprintf(buf, "My game (%f FPS)###MyGame"); + Begin(buf); // Variable label, ID = hash of "MyGame" + + - Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window. + This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements. + You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of everything in the ID stack! + + for (int i = 0; i < 100; i++) + { + PushID(i); + Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique) + PopID(); + } + + for (int i = 0; i < 100; i++) + { + MyObject* obj = Objects[i]; + PushID(obj); + Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique) + PopID(); + } + + for (int i = 0; i < 100; i++) + { + MyObject* obj = Objects[i]; + PushID(obj->Name); + Button("Click"); // Label = "Click", ID = hash of string + "label" (unique) + PopID(); + } + + - More example showing that you can stack multiple prefixes into the ID stack: + + Button("Click"); // Label = "Click", ID = hash of "Click" + PushID("node"); + Button("Click"); // Label = "Click", ID = hash of "node" + "Click" + PushID(my_ptr); + Button("Click"); // Label = "Click", ID = hash of "node" + ptr + "Click" + PopID(); + PopID(); + + - Tree nodes implicitly creates a scope for you by calling PushID(). + + Button("Click"); // Label = "Click", ID = hash of "Click" + if (TreeNode("node")) + { + Button("Click"); // Label = "Click", ID = hash of "node" + "Click" + TreePop(); + } + + - When working with trees, ID are used to preserve the open/close state of each tree node. + Depending on your use cases you may want to use strings, indices or pointers as ID. + e.g. when displaying a single object that may change over time (1-1 relationship), using a static string as ID will preserve your node open/closed state when the targeted object change. + e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently. experiment and see what makes more sense! + + Q: How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? + A: You can read the 'io.WantCaptureXXX' flags in the ImGuiIO structure. Preferably read them after calling ImGui::NewFrame() to avoid those flags lagging by one frame, but either should be fine. + When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application. + When 'io.WantInputsCharacters' is set to may want to notify your OS to popup an on-screen keyboard, if available. + ImGui is tracking dragging and widget activity that may occur outside the boundary of a window, so 'io.WantCaptureMouse' is a more accurate and complete than testing for ImGui::IsMouseHoveringAnyWindow(). + (Advanced note: text input releases focus on Return 'KeyDown', so the following Return 'KeyUp' event that your application receive will typically have 'io.WantcaptureKeyboard=false'. + Depending on your application logic it may or not be inconvenient. You might want to track which key-downs were for ImGui (e.g. with an array of bool) and filter out the corresponding key-ups.) + + Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13) + A: Use the font atlas to load the TTF file you want: + + ImGuiIO& io = ImGui::GetIO(); + io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + + Q: How can I easily use icons in my application? + A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you main font. Then you can refer to icons within your strings. + Read 'How can I load multiple fonts?' and the file 'extra_fonts/README.txt' for instructions. + + Q: How can I load multiple fonts? + A: Use the font atlas to pack them into a single texture: + (Read extra_fonts/README.txt and the code in ImFontAtlas for more details.) + + ImGuiIO& io = ImGui::GetIO(); + ImFont* font0 = io.Fonts->AddFontDefault(); + ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); + ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + // the first loaded font gets used by default + // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime + + // Options + ImFontConfig config; + config.OversampleH = 3; + config.OversampleV = 1; + config.GlyphExtraSpacing.x = 1.0f; + io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config); + + // Combine multiple fonts into one (e.g. for icon fonts) + ImWchar ranges[] = { 0xf000, 0xf3ff, 0 }; + ImFontConfig config; + config.MergeMode = true; + io.Fonts->AddFontDefault(); + io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font + io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs + + Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? + A: When loading a font, pass custom Unicode ranges to specify the glyphs to load. + All your strings needs to use UTF-8 encoding. Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will not work. + In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8. + You can also try to remap your local codepage characters to their Unicode codepoint using font->AddRemapChar(), but international users may have problems reading/editing your source code. + + io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application + + As for text input, depends on you passing the right character code to io.AddInputCharacter(). The example applications do that. + + Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API) + A: The easiest way is to create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag, zero background alpha, + then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. + + - tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will run the block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code. + - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug" + - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. this is also useful to set yourself in the context of another window (to get/set other settings) + - tip: you can call Render() multiple times (e.g for VR renders). + - tip: call and read the ShowTestWindow() code in imgui_demo.cpp for more example of how to use ImGui! + + + ISSUES & TODO-LIST + ================== + Issue numbers (#) refer to github issues listed at https://github.com/ocornut/imgui/issues + The list below consist mostly of ideas noted down before they are requested/discussed by users (at which point it usually moves to the github) + + - doc: add a proper documentation+regression testing system (#435) + - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass. + - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis) (#690) + - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify. + - window: allow resizing of child windows (possibly given min/max for each axis?) + - window: background options for child windows, border option (disable rounding) + - window: add a way to clear an existing window instead of appending (e.g. for tooltip override using a consistent api rather than the deferred tooltip) + - window: resizing from any sides? + mouse cursor directives for app. +!- window: begin with *p_open == false should return false. + - window: get size/pos helpers given names (see discussion in #249) + - window: a collapsed window can be stuck behind the main menu bar? + - window: when window is small, prioritize resize button over close button. + - window: detect extra End() call that pop the "Debug" window out and assert at call site instead of later. + - window/tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic. + - window: increase minimum size of a window with menus or fix the menu rendering so that it doesn't look odd. + - draw-list: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command). +!- scrolling: allow immediately effective change of scroll if we haven't appended items yet + - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319) + - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc. + - widgets: clean up widgets internal toward exposing everything. + - widgets: add disabled and read-only modes (#211) + - main: considering adding an Init() function? some constructs are awkward in the implementation because of the lack of them. +!- main: make it so that a frame with no window registered won't refocus every window on subsequent frames (~bump LastFrameActive of all windows). + - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes + - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode? + - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. + - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) + - input text: expose CursorPos in char filter event (#816) + - input text: flag to disable live update of the user buffer (also applies to float/int text input) + - input text: resize behavior - field could stretch when being edited? hover tooltip shows more text? + - input text: add ImGuiInputTextFlags_EnterToApply? (off #218) + - input text: add discard flag (e.g. ImGuiInputTextFlags_DiscardActiveBuffer) or make it easier to clear active focus for text replacement during edition (#725) + - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc). + - input text multi-line: way to dynamically grow the buffer without forcing the user to initially allocate for worse case (follow up on #200) + - input text multi-line: line numbers? status bar? (follow up on #200) + - input text multi-line: behave better when user changes input buffer while editing is active (even though it is illegal behavior). namely, the change of buffer can create a scrollbar glitch (#725) + - input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position. + - input number: optional range min/max for Input*() functions + - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled) + - input number: use mouse wheel to step up/down + - input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack. + - button: provide a button that looks framed. + - text: proper alignment options + - image/image button: misalignment on padded/bordered button? + - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that? + - layout: horizontal layout helper (#97) + - layout: horizontal flow until no space left (#404) + - layout: more generic alignment state (left/right/centered) for single items? + - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding. + - layout: BeginGroup() needs a border option. + - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) (#513, #125) + - columns: add a conditional parameter to SetColumnOffset() (#513, #125) + - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (#125) + - columns: columns header to act as button (~sort op) and allow resize/reorder (#513, #125) + - columns: user specify columns size (#513, #125) + - columns: flag to add horizontal separator above/below? + - columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets) + - combo: sparse combo boxes (via function call?) / iterators + - combo: contents should extends to fit label if combo widget is small + - combo/listbox: keyboard control. need InputText-like non-active focus + key handling. considering keyboard for custom listbox (pr #203) + - listbox: multiple selection + - listbox: user may want to initial scroll to focus on the one selected value? + - listbox: keyboard navigation. + - listbox: scrolling should track modified selection. +!- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402) + - popups: add variant using global identifier similar to Begin/End (#402) + - popups: border options. richer api like BeginChild() perhaps? (#197) + - tooltip: tooltip that doesn't fit in entire screen seems to lose their "last preferred button" and may teleport when moving mouse + - menus: local shortcuts, global shortcuts (#456, #126) + - menus: icons + - menus: menubars: some sort of priority / effect of main menu-bar on desktop size? + - menus: calling BeginMenu() twice with a same name doesn't seem to append nicely + - statusbar: add a per-window status bar helper similar to what menubar does. + - tabs (#261, #351) + - separator: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y) +!- color: the color helpers/typing is a mess and needs sorting out. + - color: add a better color picker (#346) + - node/graph editor (#306) + - pie menus patterns (#434) + - drag'n drop, dragging helpers (carry dragging info, visualize drag source before clicking, drop target, etc.) (#143, #479) + - plot: PlotLines() should use the polygon-stroke facilities (currently issues with averaging normals) + - plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots) + - plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value) + - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID) + - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() + - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar). + - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate. + - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign) + - slider & drag: int data passing through a float + - drag float: up/down axis + - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits) + - tree node / optimization: avoid formatting when clipped. + - tree node: tree-node/header right-most side doesn't take account of horizontal scrolling. + - tree node: add treenode/treepush int variants? not there because (void*) cast from int warns on some platforms/settings? + - tree node: try to apply scrolling at time of TreePop() if node was just opened and end of node is past scrolling limits? + - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer) + - tree node: tweak color scheme to distinguish headers from selected tree node (#581) + - textwrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249) + - settings: write more decent code to allow saving/loading new fields + - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file + - style: add window shadows. + - style/optimization: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding. + - style: color-box not always square? + - style: a concept of "compact style" that the end-user can easily rely on (e.g. PushStyleCompact()?) that maps to other settings? avoid implementing duplicate helpers such as SmallCheckbox(), etc. + - style: try to make PushStyleVar() more robust to incorrect parameters (to be more friendly to edit & continues situation). + - style: global scale setting. + - style: WindowPadding needs to be EVEN needs the 0.5 multiplier probably have a subtle effect on clip rectangle + - text: simple markup language for color change? + - font: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier. + - font: small opt: for monospace font (like the defalt one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance + - font: add support for kerning, probably optional. perhaps default to (32..128)^2 matrix ~ 36KB then hash fallback. + - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize) + - font: fix AddRemapChar() to work before font has been built. + - log: LogButtons() options for specifying depth and/or hiding depth slider + - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope) + - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard) + - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs. + - filters: set a current filter that tree node can automatically query to hide themselves + - filters: handle wildcards (with implicit leading/trailing *), regexps + - shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus) +!- keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing + - keyboard: full keyboard navigation and focus. (#323) + - focus: preserve ActiveId/focus stack state, e.g. when opening a menu and close it, previously selected InputText() focus gets restored (#622) + - focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame) + - input: rework IO system to be able to pass actual ordered/timestamped events. (~#335, #71) + - input: allow to decide and pass explicit double-clicks (e.g. for windows by the CS_DBLCLKS style). + - input: support track pad style scrolling & slider edit. + - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL) + - misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon? + - misc: provide HoveredTime and ActivatedTime to ease the creation of animations. + - style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? (#438) + - style editor: color child window height expressed in multiple of line height. + - remote: make a system like RemoteImGui first-class citizen/project (#75) + - drawlist: move Font, FontSize, FontTexUvWhitePixel inside ImDrawList and make it self-contained (apart from drawing settings?) + - drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack. + - examples: directx9: save/restore device state more thoroughly. + - examples: window minimize, maximize (#583) + - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335) + - optimization: use another hash function than crc32, e.g. FNV1a + - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)? + - optimization: turn some the various stack vectors into statically-sized arrays + - optimization: better clipping for multi-component widgets +*/ + +#include "PCH.h" + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#define IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_PLACEMENT_NEW +#include "imgui_internal.h" + +#include // toupper, isprint +#include // NULL, malloc, free, qsort, atoi +#include // vsnprintf, sscanf, printf +#include // INT_MIN, INT_MAX +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include // intptr_t +#else +#include // intptr_t +#endif + +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#endif + +// Clang warnings with -Weverything +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' // +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*' +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers +#endif + +//------------------------------------------------------------------------- +// Forward Declarations +//------------------------------------------------------------------------- + +static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL); + +static void PushMultiItemsWidths(int components, float w_full = 0.0f); +static float GetDraggedColumnOffset(int column_index); + +static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true); + +static ImFont* GetDefaultFont(); +static void SetCurrentFont(ImFont* font); +static void SetCurrentWindow(ImGuiWindow* window); +static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y); +static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond); +static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond); +static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond); +static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs); +static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags); +static inline bool IsWindowContentHoverable(ImGuiWindow* window); +static void ClearSetNextWindowData(); +static void CheckStacksSize(ImGuiWindow* window, bool write); +static void Scrollbar(ImGuiWindow* window, bool horizontal); + +static void AddDrawListToRenderList(ImVector& out_render_list, ImDrawList* draw_list); +static void AddWindowToRenderList(ImVector& out_render_list, ImGuiWindow* window); +static void AddWindowToSortedBuffer(ImVector& out_sorted_windows, ImGuiWindow* window); + +static ImGuiIniData* FindWindowSettings(const char* name); +static ImGuiIniData* AddWindowSettings(const char* name); +static void LoadIniSettingsFromDisk(const char* ini_filename); +static void SaveIniSettingsToDisk(const char* ini_filename); +static void MarkIniSettingsDirty(); + +static void PushColumnClipRect(int column_index = -1); +static ImRect GetVisibleRect(); + +static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags); +static void CloseInactivePopups(); +static void ClosePopupToLevel(int remaining); +static void ClosePopup(ImGuiID id); +static bool IsPopupOpen(ImGuiID id); +static ImGuiWindow* GetFrontMostModalRootWindow(); +static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& rect_to_avoid); + +static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data); +static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end); +static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false); + +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size); +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size); +static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2); +static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format); + +//----------------------------------------------------------------------------- +// Platform dependent default implementations +//----------------------------------------------------------------------------- + +static const char* GetClipboardTextFn_DefaultImpl(void* user_data); +static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text); +static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y); + +//----------------------------------------------------------------------------- +// Context +//----------------------------------------------------------------------------- + +// Default font atlas storage . +// New contexts always point by default to this font atlas. It can be changed by reassigning the GetIO().Fonts variable. +static ImFontAtlas GImDefaultFontAtlas; + +// Default context storage + current context pointer. +// Implicitely used by all ImGui functions. Always assumed to be != NULL. Change to a different context by calling ImGui::SetCurrentContext() +// ImGui is currently not thread-safe because of this variable. If you want thread-safety to allow N threads to access N different contexts, you might work around it by: +// - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts) +// - or: Changing this variable to be TLS. You may #define GImGui in imconfig.h for further custom hackery. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586 +#ifndef GImGui +static ImGuiContext GImDefaultContext; +ImGuiContext* GImGui = &GImDefaultContext; +#endif + +//----------------------------------------------------------------------------- +// User facing structures +//----------------------------------------------------------------------------- + +ImGuiStyle::ImGuiStyle() +{ + Alpha = 1.0f; // Global alpha applies to everything in ImGui + WindowPadding = ImVec2(8,8); // Padding within a window + WindowMinSize = ImVec2(32,32); // Minimum window size + WindowRounding = 9.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows + WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text + ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows + FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets) + FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets). + ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines + ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) + TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). + ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns + ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar + ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar + GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar + GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. + DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows. + DisplaySafeAreaPadding = ImVec2(4,4); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. + AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU. + AntiAliasedShapes = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) + CurveTessellationTol = 1.25f; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + + Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); + Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f); + Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + Colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f); + Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 0.65f); + Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input + Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f); + Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f); + Colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f); + Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); + Colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f); + Colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f); + Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f); + Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); + Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); + Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f); + Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f); + Colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f); + Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); + Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); + Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f); + Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f); + Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); + Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); + Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); + Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f); + Colors[ImGuiCol_Column] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); + Colors[ImGuiCol_ColumnHovered] = ImVec4(0.70f, 0.60f, 0.60f, 1.00f); + Colors[ImGuiCol_ColumnActive] = ImVec4(0.90f, 0.70f, 0.70f, 1.00f); + Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); + Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f); + Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f); + Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f); + Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f); + Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f); + Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); + Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); +} + +ImGuiIO::ImGuiIO() +{ + // Most fields are initialized with zero + memset(this, 0, sizeof(*this)); + + DisplaySize = ImVec2(-1.0f, -1.0f); + DeltaTime = 1.0f/60.0f; + IniSavingRate = 5.0f; + IniFilename = "imgui.ini"; + LogFilename = "imgui_log.txt"; + Fonts = &GImDefaultFontAtlas; + FontGlobalScale = 1.0f; + FontDefault = NULL; + DisplayFramebufferScale = ImVec2(1.0f, 1.0f); + MousePos = ImVec2(-1,-1); + MousePosPrev = ImVec2(-1,-1); + MouseDoubleClickTime = 0.30f; + MouseDoubleClickMaxDist = 6.0f; + MouseDragThreshold = 6.0f; + for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) + MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f; + for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) + KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f; + for (int i = 0; i < ImGuiKey_COUNT; i++) + KeyMap[i] = -1; + KeyRepeatDelay = 0.250f; + KeyRepeatRate = 0.050f; + UserData = NULL; + + // User functions + RenderDrawListsFn = NULL; + MemAllocFn = malloc; + MemFreeFn = free; + GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations + SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; + ClipboardUserData = NULL; + ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl; + + // Set OS X style defaults based on __APPLE__ compile time flag +#ifdef __APPLE__ + OSXBehaviors = true; +#endif +} + +// Pass in translated ASCII characters for text input. +// - with glfw you can get those from the callback set in glfwSetCharCallback() +// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message +void ImGuiIO::AddInputCharacter(ImWchar c) +{ + const int n = ImStrlenW(InputCharacters); + if (n + 1 < IM_ARRAYSIZE(InputCharacters)) + { + InputCharacters[n] = c; + InputCharacters[n+1] = '\0'; + } +} + +void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) +{ + // We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more + const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar); + ImWchar wchars[wchars_buf_len]; + ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL); + for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++) + AddInputCharacter(wchars[i]); +} + +//----------------------------------------------------------------------------- +// HELPERS +//----------------------------------------------------------------------------- + +#define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose +#define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255 + +// Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n. +#define IM_NEWLINE "\n" + +bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c) +{ + bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f; + bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f; + bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f; + return ((b1 == b2) && (b2 == b3)); +} + +int ImStricmp(const char* str1, const char* str2) +{ + int d; + while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } + return d; +} + +int ImStrnicmp(const char* str1, const char* str2, int count) +{ + int d = 0; + while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } + return d; +} + +void ImStrncpy(char* dst, const char* src, int count) +{ + if (count < 1) return; + strncpy(dst, src, (size_t)count); + dst[count-1] = 0; +} + +char* ImStrdup(const char *str) +{ + size_t len = strlen(str) + 1; + void* buff = ImGui::MemAlloc(len); + return (char*)memcpy(buff, (const void*)str, len); +} + +int ImStrlenW(const ImWchar* str) +{ + int n = 0; + while (*str++) n++; + return n; +} + +const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line +{ + while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n') + buf_mid_line--; + return buf_mid_line; +} + +const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end) +{ + if (!needle_end) + needle_end = needle + strlen(needle); + + const char un0 = (char)toupper(*needle); + while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end)) + { + if (toupper(*haystack) == un0) + { + const char* b = needle + 1; + for (const char* a = haystack + 1; b < needle_end; a++, b++) + if (toupper(*a) != toupper(*b)) + break; + if (b == needle_end) + return haystack; + } + haystack++; + } + return NULL; +} + + +// MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size). +// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm. +int ImFormatString(char* buf, int buf_size, const char* fmt, ...) +{ + IM_ASSERT(buf_size > 0); + va_list args; + va_start(args, fmt); + int w = vsnprintf(buf, buf_size, fmt, args); + va_end(args); + if (w == -1 || w >= buf_size) + w = buf_size - 1; + buf[w] = 0; + return w; +} + +int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args) +{ + IM_ASSERT(buf_size > 0); + int w = vsnprintf(buf, buf_size, fmt, args); + if (w == -1 || w >= buf_size) + w = buf_size - 1; + buf[w] = 0; + return w; +} + +// Pass data_size==0 for zero-terminated strings +// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. +ImU32 ImHash(const void* data, int data_size, ImU32 seed) +{ + static ImU32 crc32_lut[256] = { 0 }; + if (!crc32_lut[1]) + { + const ImU32 polynomial = 0xEDB88320; + for (ImU32 i = 0; i < 256; i++) + { + ImU32 crc = i; + for (ImU32 j = 0; j < 8; j++) + crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial); + crc32_lut[i] = crc; + } + } + + seed = ~seed; + ImU32 crc = seed; + const unsigned char* current = (const unsigned char*)data; + + if (data_size > 0) + { + // Known size + while (data_size--) + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++]; + } + else + { + // Zero-terminated string + while (unsigned char c = *current++) + { + // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed. + // Because this syntax is rarely used we are optimizing for the common case. + // - If we reach ### in the string we discard the hash so far and reset to the seed. + // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller. + if (c == '#' && current[0] == '#' && current[1] == '#') + crc = seed; + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; + } + } + return ~crc; +} + +//----------------------------------------------------------------------------- +// ImText* helpers +//----------------------------------------------------------------------------- + +// Convert UTF-8 to 32-bits character, process single character input. +// Based on stb_from_utf8() from github.com/nothings/stb/ +// We handle UTF-8 decoding error by skipping forward. +int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) +{ + unsigned int c = (unsigned int)-1; + const unsigned char* str = (const unsigned char*)in_text; + if (!(*str & 0x80)) + { + c = (unsigned int)(*str++); + *out_char = c; + return 1; + } + if ((*str & 0xe0) == 0xc0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 2) return 1; + if (*str < 0xc2) return 2; + c = (unsigned int)((*str++ & 0x1f) << 6); + if ((*str & 0xc0) != 0x80) return 2; + c += (*str++ & 0x3f); + *out_char = c; + return 2; + } + if ((*str & 0xf0) == 0xe0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 3) return 1; + if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3; + if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x0f) << 12); + if ((*str & 0xc0) != 0x80) return 3; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return 3; + c += (*str++ & 0x3f); + *out_char = c; + return 3; + } + if ((*str & 0xf8) == 0xf0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 4) return 1; + if (*str > 0xf4) return 4; + if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4; + if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x07) << 18); + if ((*str & 0xc0) != 0x80) return 4; + c += (unsigned int)((*str++ & 0x3f) << 12); + if ((*str & 0xc0) != 0x80) return 4; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return 4; + c += (*str++ & 0x3f); + // utf-8 encodings of values used in surrogate pairs are invalid + if ((c & 0xFFFFF800) == 0xD800) return 4; + *out_char = c; + return 4; + } + *out_char = 0; + return 0; +} + +int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) +{ + ImWchar* buf_out = buf; + ImWchar* buf_end = buf + buf_size; + while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c == 0) + break; + if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes + *buf_out++ = (ImWchar)c; + } + *buf_out = 0; + if (in_text_remaining) + *in_text_remaining = in_text; + return (int)(buf_out - buf); +} + +int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) +{ + int char_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c == 0) + break; + if (c < 0x10000) + char_count++; + } + return char_count; +} + +// Based on stb_to_utf8() from github.com/nothings/stb/ +static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) +{ + if (c < 0x80) + { + buf[0] = (char)c; + return 1; + } + if (c < 0x800) + { + if (buf_size < 2) return 0; + buf[0] = (char)(0xc0 + (c >> 6)); + buf[1] = (char)(0x80 + (c & 0x3f)); + return 2; + } + if (c >= 0xdc00 && c < 0xe000) + { + return 0; + } + if (c >= 0xd800 && c < 0xdc00) + { + if (buf_size < 4) return 0; + buf[0] = (char)(0xf0 + (c >> 18)); + buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); + buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); + buf[3] = (char)(0x80 + ((c ) & 0x3f)); + return 4; + } + //else if (c < 0x10000) + { + if (buf_size < 3) return 0; + buf[0] = (char)(0xe0 + (c >> 12)); + buf[1] = (char)(0x80 + ((c>> 6) & 0x3f)); + buf[2] = (char)(0x80 + ((c ) & 0x3f)); + return 3; + } +} + +static inline int ImTextCountUtf8BytesFromChar(unsigned int c) +{ + if (c < 0x80) return 1; + if (c < 0x800) return 2; + if (c >= 0xdc00 && c < 0xe000) return 0; + if (c >= 0xd800 && c < 0xdc00) return 4; + return 3; +} + +int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end) +{ + char* buf_out = buf; + const char* buf_end = buf + buf_size; + while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + *buf_out++ = (char)c; + else + buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c); + } + *buf_out = 0; + return (int)(buf_out - buf); +} + +int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) +{ + int bytes_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + bytes_count++; + else + bytes_count += ImTextCountUtf8BytesFromChar(c); + } + return bytes_count; +} + +ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) +{ + float s = 1.0f/255.0f; + return ImVec4( + ((in >> IM_COL32_R_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_G_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_B_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_A_SHIFT) & 0xFF) * s); +} + +ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in) +{ + ImU32 out; + out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT; + return out; +} + +ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul) +{ + ImVec4 c = GImGui->Style.Colors[idx]; + c.w *= GImGui->Style.Alpha * alpha_mul; + return ColorConvertFloat4ToU32(c); +} + +ImU32 ImGui::GetColorU32(const ImVec4& col) +{ + ImVec4 c = col; + c.w *= GImGui->Style.Alpha; + return ColorConvertFloat4ToU32(c); +} + +// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 +// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv +void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v) +{ + float K = 0.f; + if (g < b) + { + const float tmp = g; g = b; b = tmp; + K = -1.f; + } + if (r < g) + { + const float tmp = r; r = g; g = tmp; + K = -2.f / 6.f - K; + } + + const float chroma = r - (g < b ? g : b); + out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f)); + out_s = chroma / (r + 1e-20f); + out_v = r; +} + +// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 +// also http://en.wikipedia.org/wiki/HSL_and_HSV +void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) +{ + if (s == 0.0f) + { + // gray + out_r = out_g = out_b = v; + return; + } + + h = fmodf(h, 1.0f) / (60.0f/360.0f); + int i = (int)h; + float f = h - (float)i; + float p = v * (1.0f - s); + float q = v * (1.0f - s * f); + float t = v * (1.0f - s * (1.0f - f)); + + switch (i) + { + case 0: out_r = v; out_g = t; out_b = p; break; + case 1: out_r = q; out_g = v; out_b = p; break; + case 2: out_r = p; out_g = v; out_b = t; break; + case 3: out_r = p; out_g = q; out_b = v; break; + case 4: out_r = t; out_g = p; out_b = v; break; + case 5: default: out_r = v; out_g = p; out_b = q; break; + } +} + +FILE* ImFileOpen(const char* filename, const char* mode) +{ +#if defined(_WIN32) && !defined(__CYGWIN__) + // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can) + const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1; + const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1; + ImVector buf; + buf.resize(filename_wsize + mode_wsize); + ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL); + ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL); + return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]); +#else + return fopen(filename, mode); +#endif +} + +// Load file content into memory +// Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree() +void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes) +{ + IM_ASSERT(filename && file_open_mode); + if (out_file_size) + *out_file_size = 0; + + FILE* f; + if ((f = ImFileOpen(filename, file_open_mode)) == NULL) + return NULL; + + long file_size_signed; + if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) + { + fclose(f); + return NULL; + } + + int file_size = (int)file_size_signed; + void* file_data = ImGui::MemAlloc(file_size + padding_bytes); + if (file_data == NULL) + { + fclose(f); + return NULL; + } + if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size) + { + fclose(f); + ImGui::MemFree(file_data); + return NULL; + } + if (padding_bytes > 0) + memset((void *)(((char*)file_data) + file_size), 0, padding_bytes); + + fclose(f); + if (out_file_size) + *out_file_size = file_size; + + return file_data; +} + +//----------------------------------------------------------------------------- +// ImGuiStorage +//----------------------------------------------------------------------------- + +// Helper: Key->value storage +void ImGuiStorage::Clear() +{ + Data.clear(); +} + +// std::lower_bound but without the bullshit +static ImVector::iterator LowerBound(ImVector& data, ImGuiID key) +{ + ImVector::iterator first = data.begin(); + ImVector::iterator last = data.end(); + int count = (int)(last - first); + while (count > 0) + { + int count2 = count / 2; + ImVector::iterator mid = first + count2; + if (mid->key < key) + { + first = ++mid; + count -= count2 + 1; + } + else + { + count = count2; + } + } + return first; +} + +int ImGuiStorage::GetInt(ImGuiID key, int default_val) const +{ + ImVector::iterator it = LowerBound(const_cast&>(Data), key); + if (it == Data.end() || it->key != key) + return default_val; + return it->val_i; +} + +bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const +{ + return GetInt(key, default_val ? 1 : 0) != 0; +} + +float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const +{ + ImVector::iterator it = LowerBound(const_cast&>(Data), key); + if (it == Data.end() || it->key != key) + return default_val; + return it->val_f; +} + +void* ImGuiStorage::GetVoidPtr(ImGuiID key) const +{ + ImVector::iterator it = LowerBound(const_cast&>(Data), key); + if (it == Data.end() || it->key != key) + return NULL; + return it->val_p; +} + +// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. +int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + it = Data.insert(it, Pair(key, default_val)); + return &it->val_i; +} + +bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) +{ + return (bool*)GetIntRef(key, default_val ? 1 : 0); +} + +float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + it = Data.insert(it, Pair(key, default_val)); + return &it->val_f; +} + +void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + it = Data.insert(it, Pair(key, default_val)); + return &it->val_p; +} + +// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) +void ImGuiStorage::SetInt(ImGuiID key, int val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + { + Data.insert(it, Pair(key, val)); + return; + } + it->val_i = val; +} + +void ImGuiStorage::SetBool(ImGuiID key, bool val) +{ + SetInt(key, val ? 1 : 0); +} + +void ImGuiStorage::SetFloat(ImGuiID key, float val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + { + Data.insert(it, Pair(key, val)); + return; + } + it->val_f = val; +} + +void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + { + Data.insert(it, Pair(key, val)); + return; + } + it->val_p = val; +} + +void ImGuiStorage::SetAllInt(int v) +{ + for (int i = 0; i < Data.Size; i++) + Data[i].val_i = v; +} + +//----------------------------------------------------------------------------- +// ImGuiTextFilter +//----------------------------------------------------------------------------- + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) +{ + if (default_filter) + { + ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf)); + Build(); + } + else + { + InputBuf[0] = 0; + CountGrep = 0; + } +} + +bool ImGuiTextFilter::Draw(const char* label, float width) +{ + if (width != 0.0f) + ImGui::PushItemWidth(width); + bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); + if (width != 0.0f) + ImGui::PopItemWidth(); + if (value_changed) + Build(); + return value_changed; +} + +void ImGuiTextFilter::TextRange::split(char separator, ImVector& out) +{ + out.resize(0); + const char* wb = b; + const char* we = wb; + while (we < e) + { + if (*we == separator) + { + out.push_back(TextRange(wb, we)); + wb = we + 1; + } + we++; + } + if (wb != we) + out.push_back(TextRange(wb, we)); +} + +void ImGuiTextFilter::Build() +{ + Filters.resize(0); + TextRange input_range(InputBuf, InputBuf+strlen(InputBuf)); + input_range.split(',', Filters); + + CountGrep = 0; + for (int i = 0; i != Filters.Size; i++) + { + Filters[i].trim_blanks(); + if (Filters[i].empty()) + continue; + if (Filters[i].front() != '-') + CountGrep += 1; + } +} + +bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const +{ + if (Filters.empty()) + return true; + + if (text == NULL) + text = ""; + + for (int i = 0; i != Filters.Size; i++) + { + const TextRange& f = Filters[i]; + if (f.empty()) + continue; + if (f.front() == '-') + { + // Subtract + if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL) + return false; + } + else + { + // Grep + if (ImStristr(text, text_end, f.begin(), f.end()) != NULL) + return true; + } + } + + // Implicit * grep + if (CountGrep == 0) + return true; + + return false; +} + +//----------------------------------------------------------------------------- +// ImGuiTextBuffer +//----------------------------------------------------------------------------- + +// On some platform vsnprintf() takes va_list by reference and modifies it. +// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it. +#ifndef va_copy +#define va_copy(dest, src) (dest = src) +#endif + +// Helper: Text buffer for logging/accumulating text +void ImGuiTextBuffer::appendv(const char* fmt, va_list args) +{ + va_list args_copy; + va_copy(args_copy, args); + + int len = vsnprintf(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass. + if (len <= 0) + return; + + const int write_off = Buf.Size; + const int needed_sz = write_off + len; + if (write_off + len >= Buf.Capacity) + { + int double_capacity = Buf.Capacity * 2; + Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity); + } + + Buf.resize(needed_sz); + ImFormatStringV(&Buf[write_off] - 1, len+1, fmt, args_copy); +} + +void ImGuiTextBuffer::append(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + appendv(fmt, args); + va_end(args); +} + +//----------------------------------------------------------------------------- +// ImGuiSimpleColumns +//----------------------------------------------------------------------------- + +ImGuiSimpleColumns::ImGuiSimpleColumns() +{ + Count = 0; + Spacing = Width = NextWidth = 0.0f; + memset(Pos, 0, sizeof(Pos)); + memset(NextWidths, 0, sizeof(NextWidths)); +} + +void ImGuiSimpleColumns::Update(int count, float spacing, bool clear) +{ + IM_ASSERT(Count <= IM_ARRAYSIZE(Pos)); + Count = count; + Width = NextWidth = 0.0f; + Spacing = spacing; + if (clear) memset(NextWidths, 0, sizeof(NextWidths)); + for (int i = 0; i < Count; i++) + { + if (i > 0 && NextWidths[i] > 0.0f) + Width += Spacing; + Pos[i] = (float)(int)Width; + Width += NextWidths[i]; + NextWidths[i] = 0.0f; + } +} + +float ImGuiSimpleColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double +{ + NextWidth = 0.0f; + NextWidths[0] = ImMax(NextWidths[0], w0); + NextWidths[1] = ImMax(NextWidths[1], w1); + NextWidths[2] = ImMax(NextWidths[2], w2); + for (int i = 0; i < 3; i++) + NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f); + return ImMax(Width, NextWidth); +} + +float ImGuiSimpleColumns::CalcExtraSpace(float avail_w) +{ + return ImMax(0.0f, avail_w - Width); +} + +//----------------------------------------------------------------------------- +// ImGuiListClipper +//----------------------------------------------------------------------------- + +static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) +{ + // Set cursor position and a few other things so that SetScrollHere() and Columns() can work when seeking cursor. + // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. Consider moving within SetCursorXXX functions? + ImGui::SetCursorPosY(pos_y); + ImGuiWindow* window = ImGui::GetCurrentWindow(); + window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHere() can properly function after the end of our clipper usage. + window->DC.PrevLineHeight = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. + if (window->DC.ColumnsCount > 1) + window->DC.ColumnsCellMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly +} + +// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1 +// Use case B: Begin() called from constructor with items_height>0 +// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. +void ImGuiListClipper::Begin(int count, float items_height) +{ + StartPosY = ImGui::GetCursorPosY(); + ItemsHeight = items_height; + ItemsCount = count; + StepNo = 0; + DisplayEnd = DisplayStart = -1; + if (ItemsHeight > 0.0f) + { + ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display + if (DisplayStart > 0) + SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor + StepNo = 2; + } +} + +void ImGuiListClipper::End() +{ + if (ItemsCount < 0) + return; + // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. + if (ItemsCount < INT_MAX) + SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor + ItemsCount = -1; + StepNo = 3; +} + +bool ImGuiListClipper::Step() +{ + if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems) + { + ItemsCount = -1; + return false; + } + if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height. + { + DisplayStart = 0; + DisplayEnd = 1; + StartPosY = ImGui::GetCursorPosY(); + StepNo = 1; + return true; + } + if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. + { + if (ItemsCount == 1) { ItemsCount = -1; return false; } + float items_height = ImGui::GetCursorPosY() - StartPosY; + IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically + Begin(ItemsCount-1, items_height); + DisplayStart++; + DisplayEnd++; + StepNo = 3; + return true; + } + if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. + { + IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0); + StepNo = 3; + return true; + } + if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. + End(); + return false; +} + +//----------------------------------------------------------------------------- +// ImGuiWindow +//----------------------------------------------------------------------------- + +ImGuiWindow::ImGuiWindow(const char* name) +{ + Name = ImStrdup(name); + ID = ImHash(name, 0); + IDStack.push_back(ID); + MoveId = GetID("#MOVE"); + + Flags = 0; + IndexWithinParent = 0; + PosFloat = Pos = ImVec2(0.0f, 0.0f); + Size = SizeFull = ImVec2(0.0f, 0.0f); + SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f); + WindowPadding = ImVec2(0.0f, 0.0f); + Scroll = ImVec2(0.0f, 0.0f); + ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); + ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); + ScrollbarX = ScrollbarY = false; + ScrollbarSizes = ImVec2(0.0f, 0.0f); + BorderSize = 0.0f; + Active = WasActive = false; + Accessed = false; + Collapsed = false; + SkipItems = false; + BeginCount = 0; + PopupId = 0; + AutoFitFramesX = AutoFitFramesY = -1; + AutoFitOnlyGrows = false; + AutoPosLastDirection = -1; + HiddenFrames = 0; + SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiSetCond_Always | ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing; + SetWindowPosCenterWanted = false; + + LastFrameActive = -1; + ItemWidthDefault = 0.0f; + FontWindowScale = 1.0f; + + DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList)); + IM_PLACEMENT_NEW(DrawList) ImDrawList(); + DrawList->_OwnerName = Name; + RootWindow = NULL; + RootNonPopupWindow = NULL; + ParentWindow = NULL; + + FocusIdxAllCounter = FocusIdxTabCounter = -1; + FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX; + FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX; +} + +ImGuiWindow::~ImGuiWindow() +{ + DrawList->~ImDrawList(); + ImGui::MemFree(DrawList); + DrawList = NULL; + ImGui::MemFree(Name); + Name = NULL; +} + +ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) +{ + ImGuiID seed = IDStack.back(); + ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed); + ImGui::KeepAliveID(id); + return id; +} + +ImGuiID ImGuiWindow::GetID(const void* ptr) +{ + ImGuiID seed = IDStack.back(); + ImGuiID id = ImHash(&ptr, sizeof(void*), seed); + ImGui::KeepAliveID(id); + return id; +} + +ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end) +{ + ImGuiID seed = IDStack.back(); + return ImHash(str, str_end ? (int)(str_end - str) : 0, seed); +} + +//----------------------------------------------------------------------------- +// Internal API exposed in imgui_internal.h +//----------------------------------------------------------------------------- + +static void SetCurrentWindow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + g.CurrentWindow = window; + if (window) + g.FontSize = window->CalcFontSize(); +} + +ImGuiWindow* ImGui::GetParentWindow() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.CurrentWindowStack.Size >= 2); + return g.CurrentWindowStack[(unsigned int)g.CurrentWindowStack.Size - 2]; +} + +void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + g.ActiveId = id; + g.ActiveIdAllowOverlap = false; + g.ActiveIdIsJustActivated = true; + if (id) + g.ActiveIdIsAlive = true; + g.ActiveIdWindow = window; +} + +void ImGui::ClearActiveID() +{ + SetActiveID(0, NULL); +} + +void ImGui::SetHoveredID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + g.HoveredId = id; + g.HoveredIdAllowOverlap = false; +} + +void ImGui::KeepAliveID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId == id) + g.ActiveIdIsAlive = true; +} + +// Advance cursor given item size for layout. +void ImGui::ItemSize(const ImVec2& size, float text_offset_y) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + // Always align ourselves on pixel boundaries + ImGuiContext& g = *GImGui; + const float line_height = ImMax(window->DC.CurrentLineHeight, size.y); + const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y); + window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y); + window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y)); + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); + + //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // Debug + + window->DC.PrevLineHeight = line_height; + window->DC.PrevLineTextBaseOffset = text_base_offset; + window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f; +} + +void ImGui::ItemSize(const ImRect& bb, float text_offset_y) +{ + ItemSize(bb.GetSize(), text_offset_y); +} + +// Declare item bounding box for clipping and interaction. +// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface +// declares their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd(). +bool ImGui::ItemAdd(const ImRect& bb, const ImGuiID* id) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.LastItemId = id ? *id : 0; + window->DC.LastItemRect = bb; + window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false; + if (IsClippedEx(bb, id, false)) + return false; + + // This is a sensible default, but widgets are free to override it after calling ItemAdd() + ImGuiContext& g = *GImGui; + if (IsMouseHoveringRect(bb.Min, bb.Max)) + { + // Matching the behavior of IsHovered() but allow if ActiveId==window->MoveID (we clicked on the window background) + // So that clicking on items with no active id such as Text() still returns true with IsItemHovered() + window->DC.LastItemHoveredRect = true; + if (g.HoveredRootWindow == window->RootWindow) + if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdAllowOverlap || (g.ActiveId == window->MoveId)) + if (IsWindowContentHoverable(window)) + window->DC.LastItemHoveredAndUsable = true; + } + + return true; +} + +bool ImGui::IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); + + if (!bb.Overlaps(window->ClipRect)) + if (!id || *id != GImGui->ActiveId) + if (clip_even_when_logged || !g.LogEnabled) + return true; + return false; +} + +// NB: This is an internal helper. The user-facing IsItemHovered() is using data emitted from ItemAdd(), with a slightly different logic. +bool ImGui::IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs) +{ + ImGuiContext& g = *GImGui; + if (g.HoveredId == 0 || g.HoveredId == id || g.HoveredIdAllowOverlap) + { + ImGuiWindow* window = GetCurrentWindowRead(); + if (g.HoveredWindow == window || (flatten_childs && g.HoveredRootWindow == window->RootWindow)) + if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdAllowOverlap) && IsMouseHoveringRect(bb.Min, bb.Max)) + if (IsWindowContentHoverable(g.HoveredRootWindow)) + return true; + } + return false; +} + +bool ImGui::FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop) +{ + ImGuiContext& g = *GImGui; + + const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus; + window->FocusIdxAllCounter++; + if (allow_keyboard_focus) + window->FocusIdxTabCounter++; + + // Process keyboard input at this point: TAB, Shift-TAB switch focus + // We can always TAB out of a widget that doesn't allow tabbing in. + if (tab_stop && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab)) + { + // Modulo on index will be applied at the end of frame once we've got the total counter of items. + window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); + } + + if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent) + return true; + + if (allow_keyboard_focus) + if (window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent) + return true; + + return false; +} + +void ImGui::FocusableItemUnregister(ImGuiWindow* window) +{ + window->FocusIdxAllCounter--; + window->FocusIdxTabCounter--; +} + +ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y) +{ + ImGuiContext& g = *GImGui; + ImVec2 content_max; + if (size.x < 0.0f || size.y < 0.0f) + content_max = g.CurrentWindow->Pos + GetContentRegionMax(); + if (size.x <= 0.0f) + size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x; + if (size.y <= 0.0f) + size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y; + return size; +} + +float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) +{ + if (wrap_pos_x < 0.0f) + return 0.0f; + + ImGuiWindow* window = GetCurrentWindowRead(); + if (wrap_pos_x == 0.0f) + wrap_pos_x = GetContentRegionMax().x + window->Pos.x; + else if (wrap_pos_x > 0.0f) + wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space + + return ImMax(wrap_pos_x - pos.x, 1.0f); +} + +//----------------------------------------------------------------------------- + +void* ImGui::MemAlloc(size_t sz) +{ + GImGui->IO.MetricsAllocs++; + return GImGui->IO.MemAllocFn(sz); +} + +void ImGui::MemFree(void* ptr) +{ + if (ptr) GImGui->IO.MetricsAllocs--; + return GImGui->IO.MemFreeFn(ptr); +} + +const char* ImGui::GetClipboardText() +{ + return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : ""; +} + +void ImGui::SetClipboardText(const char* text) +{ + if (GImGui->IO.SetClipboardTextFn) + GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text); +} + +const char* ImGui::GetVersion() +{ + return IMGUI_VERSION; +} + +// Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself +// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module +ImGuiContext* ImGui::GetCurrentContext() +{ + return GImGui; +} + +void ImGui::SetCurrentContext(ImGuiContext* ctx) +{ +#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC + IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this. +#else + GImGui = ctx; +#endif +} + +ImGuiContext* ImGui::CreateContext(void* (*malloc_fn)(size_t), void (*free_fn)(void*)) +{ + if (!malloc_fn) malloc_fn = malloc; + ImGuiContext* ctx = (ImGuiContext*)malloc_fn(sizeof(ImGuiContext)); + IM_PLACEMENT_NEW(ctx) ImGuiContext(); + ctx->IO.MemAllocFn = malloc_fn; + ctx->IO.MemFreeFn = free_fn ? free_fn : free; + return ctx; +} + +void ImGui::DestroyContext(ImGuiContext* ctx) +{ + void (*free_fn)(void*) = ctx->IO.MemFreeFn; + ctx->~ImGuiContext(); + free_fn(ctx); + if (GImGui == ctx) + SetCurrentContext(NULL); +} + +ImGuiIO& ImGui::GetIO() +{ + return GImGui->IO; +} + +ImGuiStyle& ImGui::GetStyle() +{ + return GImGui->Style; +} + +// Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame() +ImDrawData* ImGui::GetDrawData() +{ + return GImGui->RenderDrawData.Valid ? &GImGui->RenderDrawData : NULL; +} + +float ImGui::GetTime() +{ + return GImGui->Time; +} + +int ImGui::GetFrameCount() +{ + return GImGui->FrameCount; +} + +void ImGui::NewFrame() +{ + ImGuiContext& g = *GImGui; + + // Check user data + IM_ASSERT(g.IO.DeltaTime >= 0.0f); // Need a positive DeltaTime (zero is tolerated but will cause some timing issues) + IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f); + IM_ASSERT(g.IO.Fonts->Fonts.Size > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(g.Style.CurveTessellationTol > 0.0f); // Invalid style setting + + if (!g.Initialized) + { + // Initialize on first frame + g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer)); + IM_PLACEMENT_NEW(g.LogClipboard) ImGuiTextBuffer(); + + IM_ASSERT(g.Settings.empty()); + LoadIniSettingsFromDisk(g.IO.IniFilename); + g.Initialized = true; + } + + SetCurrentFont(GetDefaultFont()); + IM_ASSERT(g.Font->IsLoaded()); + + g.Time += g.IO.DeltaTime; + g.FrameCount += 1; + g.Tooltip[0] = '\0'; + g.OverlayDrawList.Clear(); + g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID); + g.OverlayDrawList.PushClipRectFullScreen(); + + // Mark rendering data as invalid to prevent user who may have a handle on it to use it + g.RenderDrawData.Valid = false; + g.RenderDrawData.CmdLists = NULL; + g.RenderDrawData.CmdListsCount = g.RenderDrawData.TotalVtxCount = g.RenderDrawData.TotalIdxCount = 0; + + // Update inputs state + if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) + g.IO.MousePos = ImVec2(-9999.0f, -9999.0f); + if ((g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) || (g.IO.MousePosPrev.x < 0 && g.IO.MousePosPrev.y < 0)) // if mouse just appeared or disappeared (negative coordinate) we cancel out movement in MouseDelta + g.IO.MouseDelta = ImVec2(0.0f, 0.0f); + else + g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; + g.IO.MousePosPrev = g.IO.MousePos; + for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) + { + g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f; + g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f; + g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i]; + g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f; + g.IO.MouseDoubleClicked[i] = false; + if (g.IO.MouseClicked[i]) + { + if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime) + { + if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist) + g.IO.MouseDoubleClicked[i] = true; + g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click + } + else + { + g.IO.MouseClickedTime[i] = g.Time; + } + g.IO.MouseClickedPos[i] = g.IO.MousePos; + g.IO.MouseDragMaxDistanceSqr[i] = 0.0f; + } + else if (g.IO.MouseDown[i]) + { + g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i])); + } + } + memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration)); + for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) + g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f; + + // Calculate frame-rate for the user, as a purely luxurious feature + g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; + g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime; + g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame); + g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame)); + + // Clear reference to active widget if the widget isn't alive anymore + g.HoveredIdPreviousFrame = g.HoveredId; + g.HoveredId = 0; + g.HoveredIdAllowOverlap = false; + if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) + ClearActiveID(); + g.ActiveIdPreviousFrame = g.ActiveId; + g.ActiveIdIsAlive = false; + g.ActiveIdIsJustActivated = false; + + // Handle user moving window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows. + if (g.MovedWindowMoveId && g.MovedWindowMoveId == g.ActiveId) + { + KeepAliveID(g.MovedWindowMoveId); + IM_ASSERT(g.MovedWindow && g.MovedWindow->RootWindow); + IM_ASSERT(g.MovedWindow->RootWindow->MoveId == g.MovedWindowMoveId); + if (g.IO.MouseDown[0]) + { + if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoMove)) + { + g.MovedWindow->PosFloat += g.IO.MouseDelta; + if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoSavedSettings) && (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)) + MarkIniSettingsDirty(); + } + FocusWindow(g.MovedWindow); + } + else + { + ClearActiveID(); + g.MovedWindow = NULL; + g.MovedWindowMoveId = 0; + } + } + else + { + g.MovedWindow = NULL; + g.MovedWindowMoveId = 0; + } + + // Delay saving settings so we don't spam disk too much + if (g.SettingsDirtyTimer > 0.0f) + { + g.SettingsDirtyTimer -= g.IO.DeltaTime; + if (g.SettingsDirtyTimer <= 0.0f) + SaveIniSettingsToDisk(g.IO.IniFilename); + } + + // Find the window we are hovering. Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow + g.HoveredWindow = g.MovedWindow ? g.MovedWindow : FindHoveredWindow(g.IO.MousePos, false); + if (g.HoveredWindow && (g.HoveredWindow->Flags & ImGuiWindowFlags_ChildWindow)) + g.HoveredRootWindow = g.HoveredWindow->RootWindow; + else + g.HoveredRootWindow = g.MovedWindow ? g.MovedWindow->RootWindow : FindHoveredWindow(g.IO.MousePos, true); + + if (ImGuiWindow* modal_window = GetFrontMostModalRootWindow()) + { + g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f); + ImGuiWindow* window = g.HoveredRootWindow; + while (window && window != modal_window) + window = window->ParentWindow; + if (!window) + g.HoveredRootWindow = g.HoveredWindow = NULL; + } + else + { + g.ModalWindowDarkeningRatio = 0.0f; + } + + // Are we using inputs? Tell user so they can capture/discard the inputs away from the rest of their application. + // When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership. + int mouse_earliest_button_down = -1; + bool mouse_any_down = false; + for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) + { + if (g.IO.MouseClicked[i]) + g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty()); + mouse_any_down |= g.IO.MouseDown[i]; + if (g.IO.MouseDown[i]) + if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[mouse_earliest_button_down] > g.IO.MouseClickedTime[i]) + mouse_earliest_button_down = i; + } + bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down]; + if (g.CaptureMouseNextFrame != -1) + g.IO.WantCaptureMouse = (g.CaptureMouseNextFrame != 0); + else + g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.ActiveId != 0) || (!g.OpenPopupStack.empty()); + g.IO.WantCaptureKeyboard = (g.CaptureKeyboardNextFrame != -1) ? (g.CaptureKeyboardNextFrame != 0) : (g.ActiveId != 0); + g.IO.WantTextInput = (g.ActiveId != 0 && g.InputTextState.Id == g.ActiveId); + g.MouseCursor = ImGuiMouseCursor_Arrow; + g.CaptureMouseNextFrame = g.CaptureKeyboardNextFrame = -1; + g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default + + // If mouse was first clicked outside of ImGui bounds we also cancel out hovering. + if (!mouse_avail_to_imgui) + g.HoveredWindow = g.HoveredRootWindow = NULL; + + // Scale & Scrolling + if (g.HoveredWindow && g.IO.MouseWheel != 0.0f && !g.HoveredWindow->Collapsed) + { + ImGuiWindow* window = g.HoveredWindow; + if (g.IO.KeyCtrl) + { + if (g.IO.FontAllowUserScaling) + { + // Zoom / Scale window + float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); + float scale = new_font_scale / window->FontWindowScale; + window->FontWindowScale = new_font_scale; + + const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; + window->Pos += offset; + window->PosFloat += offset; + window->Size *= scale; + window->SizeFull *= scale; + } + } + else if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse)) + { + // Scroll + const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5; + SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * window->CalcFontSize() * scroll_lines); + } + } + + // Pressing TAB activate widget focus + // NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus. + if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false)) + g.FocusedWindow->FocusIdxTabRequestNext = 0; + + // Mark all windows as not visible + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + window->WasActive = window->Active; + window->Active = false; + window->Accessed = false; + } + + // Closing the focused window restore focus to the first active root window in descending z-order + if (g.FocusedWindow && !g.FocusedWindow->WasActive) + for (int i = g.Windows.Size-1; i >= 0; i--) + if (g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow)) + { + FocusWindow(g.Windows[i]); + break; + } + + // No window should be open at the beginning of the frame. + // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. + g.CurrentWindowStack.resize(0); + g.CurrentPopupStack.resize(0); + CloseInactivePopups(); + + // Create implicit window - we will only render it if the user has added something to it. + ImGui::SetNextWindowSize(ImVec2(400,400), ImGuiSetCond_FirstUseEver); + ImGui::Begin("Debug"); +} + +// NB: behavior of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations. +void ImGui::Shutdown() +{ + ImGuiContext& g = *GImGui; + + // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) + if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky. + g.IO.Fonts->Clear(); + + // Cleanup of other data are conditional on actually having used ImGui. + if (!g.Initialized) + return; + + SaveIniSettingsToDisk(g.IO.IniFilename); + + for (int i = 0; i < g.Windows.Size; i++) + { + g.Windows[i]->~ImGuiWindow(); + ImGui::MemFree(g.Windows[i]); + } + g.Windows.clear(); + g.WindowsSortBuffer.clear(); + g.CurrentWindow = NULL; + g.CurrentWindowStack.clear(); + g.FocusedWindow = NULL; + g.HoveredWindow = NULL; + g.HoveredRootWindow = NULL; + g.ActiveIdWindow = NULL; + g.MovedWindow = NULL; + for (int i = 0; i < g.Settings.Size; i++) + ImGui::MemFree(g.Settings[i].Name); + g.Settings.clear(); + g.ColorModifiers.clear(); + g.StyleModifiers.clear(); + g.FontStack.clear(); + g.OpenPopupStack.clear(); + g.CurrentPopupStack.clear(); + g.SetNextWindowSizeConstraintCallback = NULL; + g.SetNextWindowSizeConstraintCallbackUserData = NULL; + for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + g.RenderDrawLists[i].clear(); + g.OverlayDrawList.ClearFreeMemory(); + g.ColorEditModeStorage.Clear(); + if (g.PrivateClipboard) + { + ImGui::MemFree(g.PrivateClipboard); + g.PrivateClipboard = NULL; + } + g.InputTextState.Text.clear(); + g.InputTextState.InitialText.clear(); + g.InputTextState.TempTextBuffer.clear(); + + if (g.LogFile && g.LogFile != stdout) + { + fclose(g.LogFile); + g.LogFile = NULL; + } + if (g.LogClipboard) + { + g.LogClipboard->~ImGuiTextBuffer(); + ImGui::MemFree(g.LogClipboard); + } + + g.Initialized = false; +} + +static ImGuiIniData* FindWindowSettings(const char* name) +{ + ImGuiContext& g = *GImGui; + ImGuiID id = ImHash(name, 0); + for (int i = 0; i != g.Settings.Size; i++) + { + ImGuiIniData* ini = &g.Settings[i]; + if (ini->Id == id) + return ini; + } + return NULL; +} + +static ImGuiIniData* AddWindowSettings(const char* name) +{ + GImGui->Settings.resize(GImGui->Settings.Size + 1); + ImGuiIniData* ini = &GImGui->Settings.back(); + ini->Name = ImStrdup(name); + ini->Id = ImHash(name, 0); + ini->Collapsed = false; + ini->Pos = ImVec2(FLT_MAX,FLT_MAX); + ini->Size = ImVec2(0,0); + return ini; +} + +// Zero-tolerance, poor-man .ini parsing +// FIXME: Write something less rubbish +static void LoadIniSettingsFromDisk(const char* ini_filename) +{ + ImGuiContext& g = *GImGui; + if (!ini_filename) + return; + + int file_size; + char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_size, 1); + if (!file_data) + return; + + ImGuiIniData* settings = NULL; + const char* buf_end = file_data + file_size; + for (const char* line_start = file_data; line_start < buf_end; ) + { + const char* line_end = line_start; + while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') + line_end++; + + if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']') + { + char name[64]; + ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", (int)(line_end-line_start-2), line_start+1); + settings = FindWindowSettings(name); + if (!settings) + settings = AddWindowSettings(name); + } + else if (settings) + { + float x, y; + int i; + if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2) + settings->Pos = ImVec2(x, y); + else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2) + settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); + else if (sscanf(line_start, "Collapsed=%d", &i) == 1) + settings->Collapsed = (i != 0); + } + + line_start = line_end+1; + } + + ImGui::MemFree(file_data); +} + +static void SaveIniSettingsToDisk(const char* ini_filename) +{ + ImGuiContext& g = *GImGui; + g.SettingsDirtyTimer = 0.0f; + if (!ini_filename) + return; + + // Gather data from windows that were active during this session + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Flags & ImGuiWindowFlags_NoSavedSettings) + continue; + ImGuiIniData* settings = FindWindowSettings(window->Name); + settings->Pos = window->Pos; + settings->Size = window->SizeFull; + settings->Collapsed = window->Collapsed; + } + + // Write .ini file + // If a window wasn't opened in this session we preserve its settings + FILE* f = ImFileOpen(ini_filename, "wt"); + if (!f) + return; + for (int i = 0; i != g.Settings.Size; i++) + { + const ImGuiIniData* settings = &g.Settings[i]; + if (settings->Pos.x == FLT_MAX) + continue; + const char* name = settings->Name; + if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() + name = p; + fprintf(f, "[%s]\n", name); + fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); + fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); + fprintf(f, "Collapsed=%d\n", settings->Collapsed); + fprintf(f, "\n"); + } + + fclose(f); +} + +static void MarkIniSettingsDirty() +{ + ImGuiContext& g = *GImGui; + if (g.SettingsDirtyTimer <= 0.0f) + g.SettingsDirtyTimer = g.IO.IniSavingRate; +} + +// FIXME: Add a more explicit sort order in the window structure. +static int ChildWindowComparer(const void* lhs, const void* rhs) +{ + const ImGuiWindow* a = *(const ImGuiWindow**)lhs; + const ImGuiWindow* b = *(const ImGuiWindow**)rhs; + if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup)) + return d; + if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) + return d; + if (int d = (a->Flags & ImGuiWindowFlags_ComboBox) - (b->Flags & ImGuiWindowFlags_ComboBox)) + return d; + return (a->IndexWithinParent - b->IndexWithinParent); +} + +static void AddWindowToSortedBuffer(ImVector& out_sorted_windows, ImGuiWindow* window) +{ + out_sorted_windows.push_back(window); + if (window->Active) + { + int count = window->DC.ChildWindows.Size; + if (count > 1) + qsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer); + for (int i = 0; i < count; i++) + { + ImGuiWindow* child = window->DC.ChildWindows[i]; + if (child->Active) + AddWindowToSortedBuffer(out_sorted_windows, child); + } + } +} + +static void AddDrawListToRenderList(ImVector& out_render_list, ImDrawList* draw_list) +{ + if (draw_list->CmdBuffer.empty()) + return; + + // Remove trailing command if unused + ImDrawCmd& last_cmd = draw_list->CmdBuffer.back(); + if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL) + { + draw_list->CmdBuffer.pop_back(); + if (draw_list->CmdBuffer.empty()) + return; + } + + // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. + IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); + IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); + IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); + + // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = 2 bytes = 64K vertices) + // If this assert triggers because you are drawing lots of stuff manually, A) workaround by calling BeginChild()/EndChild() to put your draw commands in multiple draw lists, B) #define ImDrawIdx to a 'unsigned int' in imconfig.h and render accordingly. + IM_ASSERT((int64_t)draw_list->_VtxCurrentIdx <= ((int64_t)1L << (sizeof(ImDrawIdx)*8))); // Too many vertices in same ImDrawList. See comment above. + + out_render_list.push_back(draw_list); + GImGui->IO.MetricsRenderVertices += draw_list->VtxBuffer.Size; + GImGui->IO.MetricsRenderIndices += draw_list->IdxBuffer.Size; +} + +static void AddWindowToRenderList(ImVector& out_render_list, ImGuiWindow* window) +{ + AddDrawListToRenderList(out_render_list, window->DrawList); + for (int i = 0; i < window->DC.ChildWindows.Size; i++) + { + ImGuiWindow* child = window->DC.ChildWindows[i]; + if (!child->Active) // clipped children may have been marked not active + continue; + if ((child->Flags & ImGuiWindowFlags_Popup) && child->HiddenFrames > 0) + continue; + AddWindowToRenderList(out_render_list, child); + } +} + +// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. +void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); + window->ClipRect = window->DrawList->_ClipRectStack.back(); +} + +void ImGui::PopClipRect() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->PopClipRect(); + window->ClipRect = window->DrawList->_ClipRectStack.back(); +} + +// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. +void ImGui::EndFrame() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() + IM_ASSERT(g.FrameCountEnded != g.FrameCount); // ImGui::EndFrame() called multiple times, or forgot to call ImGui::NewFrame() again + + // Render tooltip + if (g.Tooltip[0]) + { + ImGui::BeginTooltip(); + ImGui::TextUnformatted(g.Tooltip); + ImGui::EndTooltip(); + } + + // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) + if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f) + { + g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y); + g.OsImePosSet = g.OsImePosRequest; + } + + // Hide implicit "Debug" window if it hasn't been used + IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls + if (g.CurrentWindow && !g.CurrentWindow->Accessed) + g.CurrentWindow->Active = false; + ImGui::End(); + + // Click to focus window and start moving (after we're done with all our widgets) + if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0]) + { + if (!(g.FocusedWindow && !g.FocusedWindow->WasActive && g.FocusedWindow->Active)) // Unless we just made a popup appear + { + if (g.HoveredRootWindow != NULL) + { + FocusWindow(g.HoveredWindow); + if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove)) + { + g.MovedWindow = g.HoveredWindow; + g.MovedWindowMoveId = g.HoveredRootWindow->MoveId; + SetActiveID(g.MovedWindowMoveId, g.HoveredRootWindow); + } + } + else if (g.FocusedWindow != NULL && GetFrontMostModalRootWindow() == NULL) + { + // Clicking on void disable focus + FocusWindow(NULL); + } + } + } + + // Sort the window list so that all child windows are after their parent + // We cannot do that on FocusWindow() because childs may not exist yet + g.WindowsSortBuffer.resize(0); + g.WindowsSortBuffer.reserve(g.Windows.Size); + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it + continue; + AddWindowToSortedBuffer(g.WindowsSortBuffer, window); + } + IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong + g.Windows.swap(g.WindowsSortBuffer); + + // Clear Input data for next frame + g.IO.MouseWheel = 0.0f; + memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); + + g.FrameCountEnded = g.FrameCount; +} + +void ImGui::Render() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() + + if (g.FrameCountEnded != g.FrameCount) + ImGui::EndFrame(); + g.FrameCountRendered = g.FrameCount; + + // Skip render altogether if alpha is 0.0 + // Note that vertex buffers have been created and are wasted, so it is best practice that you don't create windows in the first place, or consistently respond to Begin() returning false. + if (g.Style.Alpha > 0.0f) + { + // Gather windows to render + g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0; + for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + g.RenderDrawLists[i].resize(0); + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0) + { + // FIXME: Generalize this with a proper layering system so e.g. user can draw in specific layers, below text, .. + g.IO.MetricsActiveWindows++; + if (window->Flags & ImGuiWindowFlags_Popup) + AddWindowToRenderList(g.RenderDrawLists[1], window); + else if (window->Flags & ImGuiWindowFlags_Tooltip) + AddWindowToRenderList(g.RenderDrawLists[2], window); + else + AddWindowToRenderList(g.RenderDrawLists[0], window); + } + } + + // Flatten layers + int n = g.RenderDrawLists[0].Size; + int flattened_size = n; + for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + flattened_size += g.RenderDrawLists[i].Size; + g.RenderDrawLists[0].resize(flattened_size); + for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + { + ImVector& layer = g.RenderDrawLists[i]; + if (layer.empty()) + continue; + memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.Size * sizeof(ImDrawList*)); + n += layer.Size; + } + + // Draw software mouse cursor if requested + if (g.IO.MouseDrawCursor) + { + const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor]; + const ImVec2 pos = g.IO.MousePos - cursor_data.HotOffset; + const ImVec2 size = cursor_data.Size; + const ImTextureID tex_id = g.IO.Fonts->TexID; + g.OverlayDrawList.PushTextureID(tex_id); + g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow + g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow + g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,255)); // Black border + g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], IM_COL32(255,255,255,255)); // White fill + g.OverlayDrawList.PopTextureID(); + } + if (!g.OverlayDrawList.VtxBuffer.empty()) + AddDrawListToRenderList(g.RenderDrawLists[0], &g.OverlayDrawList); + + // Setup draw data + g.RenderDrawData.Valid = true; + g.RenderDrawData.CmdLists = (g.RenderDrawLists[0].Size > 0) ? &g.RenderDrawLists[0][0] : NULL; + g.RenderDrawData.CmdListsCount = g.RenderDrawLists[0].Size; + g.RenderDrawData.TotalVtxCount = g.IO.MetricsRenderVertices; + g.RenderDrawData.TotalIdxCount = g.IO.MetricsRenderIndices; + + // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData() + if (g.RenderDrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL) + g.IO.RenderDrawListsFn(&g.RenderDrawData); + } +} + +const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end) +{ + const char* text_display_end = text; + if (!text_end) + text_end = (const char*)-1; + + while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) + text_display_end++; + return text_display_end; +} + +// Pass text data straight to log (without being displayed) +void ImGui::LogText(const char* fmt, ...) +{ + ImGuiContext& g = *GImGui; + if (!g.LogEnabled) + return; + + va_list args; + va_start(args, fmt); + if (g.LogFile) + { + vfprintf(g.LogFile, fmt, args); + } + else + { + g.LogClipboard->appendv(fmt, args); + } + va_end(args); +} + +// Internal version that takes a position to decide on newline placement and pad items according to their depth. +// We split text into individual lines to add current tree level padding +static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = ImGui::GetCurrentWindowRead(); + + if (!text_end) + text_end = ImGui::FindRenderedTextEnd(text, text_end); + + const bool log_new_line = ref_pos.y > window->DC.LogLinePosY+1; + window->DC.LogLinePosY = ref_pos.y; + + const char* text_remaining = text; + if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth + g.LogStartDepth = window->DC.TreeDepth; + const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth); + for (;;) + { + // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. + const char* line_end = text_remaining; + while (line_end < text_end) + if (*line_end == '\n') + break; + else + line_end++; + if (line_end >= text_end) + line_end = NULL; + + const bool is_first_line = (text == text_remaining); + bool is_last_line = false; + if (line_end == NULL) + { + is_last_line = true; + line_end = text_end; + } + if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0)) + { + const int char_count = (int)(line_end - text_remaining); + if (log_new_line || !is_first_line) + ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining); + else + ImGui::LogText(" %.*s", char_count, text_remaining); + } + + if (is_last_line) + break; + text_remaining = line_end + 1; + } +} + +// Internal ImGui functions to render text +// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() +void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + // Hide anything after a '##' string + const char* text_display_end; + if (hide_text_after_hash) + { + text_display_end = FindRenderedTextEnd(text, text_end); + } + else + { + if (!text_end) + text_end = text + strlen(text); // FIXME-OPT + text_display_end = text_end; + } + + const int text_len = (int)(text_display_end - text); + if (text_len > 0) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); + if (g.LogEnabled) + LogRenderedText(pos, text, text_display_end); + } +} + +void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + if (!text_end) + text_end = text + strlen(text); // FIXME-OPT + + const int text_len = (int)(text_end - text); + if (text_len > 0) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); + if (g.LogEnabled) + LogRenderedText(pos, text, text_end); + } +} + +// Default clip_rect uses (pos_min,pos_max) +// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges) +void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) +{ + // Hide anything after a '##' string + const char* text_display_end = FindRenderedTextEnd(text, text_end); + const int text_len = (int)(text_display_end - text); + if (text_len == 0) + return; + + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + // Perform CPU side clipping for single clipped element to avoid using scissor state + ImVec2 pos = pos_min; + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f); + + const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min; + const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max; + bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y); + if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min + need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); + + // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. + if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); + if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); + + // Render + if (need_clipping) + { + ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); + } + else + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL); + } + if (g.LogEnabled) + LogRenderedText(pos, text, text_display_end); +} + +// Render a rectangle shaped with optional rounding and borders +void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) +{ + ImGuiWindow* window = GetCurrentWindow(); + + window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); + if (border && (window->Flags & ImGuiWindowFlags_ShowBorders)) + { + window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding); + window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding); + } +} + +// Render a triangle to denote expanded/collapsed state +void ImGui::RenderCollapseTriangle(ImVec2 p_min, bool is_open, float scale) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + const float h = g.FontSize * 1.00f; + const float r = h * 0.40f * scale; + ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale); + + ImVec2 a, b, c; + if (is_open) + { + center.y -= r*0.25f; + a = center + ImVec2(0,1)*r; + b = center + ImVec2(-0.866f,-0.5f)*r; + c = center + ImVec2(0.866f,-0.5f)*r; + } + else + { + a = center + ImVec2(1,0)*r; + b = center + ImVec2(-0.500f,0.866f)*r; + c = center + ImVec2(-0.500f,-0.866f)*r; + } + + window->DrawList->AddTriangleFilled(a, b, c, GetColorU32(ImGuiCol_Text)); +} + +void ImGui::RenderBullet(ImVec2 pos) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8); +} + +void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + ImVec2 a, b, c; + float start_x = (float)(int)(g.FontSize * 0.307f + 0.5f); + float rem_third = (float)(int)((g.FontSize - start_x) / 3.0f); + a.x = pos.x + 0.5f + start_x; + b.x = a.x + rem_third; + c.x = a.x + rem_third * 3.0f; + b.y = pos.y - 1.0f + (float)(int)(g.Font->Ascent * (g.FontSize / g.Font->FontSize) + 0.5f) + (float)(int)(g.Font->DisplayOffset.y); + a.y = b.y - rem_third; + c.y = b.y - rem_third * 2.0f; + + window->DrawList->PathLineTo(a); + window->DrawList->PathLineTo(b); + window->DrawList->PathLineTo(c); + window->DrawList->PathStroke(col, false); +} + +// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. +// CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize) +ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) +{ + ImGuiContext& g = *GImGui; + + const char* text_display_end; + if (hide_text_after_double_hash) + text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string + else + text_display_end = text_end; + + ImFont* font = g.Font; + const float font_size = g.FontSize; + if (text == text_display_end) + return ImVec2(0.0f, font_size); + ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); + + // Cancel out character spacing for the last character of a line (it is baked into glyph->XAdvance field) + const float font_scale = font_size / font->FontSize; + const float character_spacing_x = 1.0f * font_scale; + if (text_size.x > 0.0f) + text_size.x -= character_spacing_x; + text_size.x = (float)(int)(text_size.x + 0.95f); + + return text_size; +} + +// Helper to calculate coarse clipping of large list of evenly sized items. +// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern. +// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX +void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); + if (g.LogEnabled) + { + // If logging is active, do not perform any clipping + *out_items_display_start = 0; + *out_items_display_end = items_count; + return; + } + if (window->SkipItems) + { + *out_items_display_start = *out_items_display_end = 0; + return; + } + + const ImVec2 pos = window->DC.CursorPos; + int start = (int)((window->ClipRect.Min.y - pos.y) / items_height); + int end = (int)((window->ClipRect.Max.y - pos.y) / items_height); + start = ImClamp(start, 0, items_count); + end = ImClamp(end + 1, start, items_count); + *out_items_display_start = start; + *out_items_display_end = end; +} + +// Find window given position, search front-to-back +// FIXME: Note that we have a lag here because WindowRectClipped is updated in Begin() so windows moved by user via SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is called, aka before the next Begin(). Moving window thankfully isn't affected. +static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs) +{ + ImGuiContext& g = *GImGui; + for (int i = g.Windows.Size-1; i >= 0; i--) + { + ImGuiWindow* window = g.Windows[i]; + if (!window->Active) + continue; + if (window->Flags & ImGuiWindowFlags_NoInputs) + continue; + if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0) + continue; + + // Using the clipped AABB so a child window will typically be clipped by its parent. + ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding); + if (bb.Contains(pos)) + return window; + } + return NULL; +} + +// Test if mouse cursor is hovering given rectangle +// NB- Rectangle is clipped by our current clip setting +// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) +bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); + + // Clip + ImRect rect_clipped(r_min, r_max); + if (clip) + rect_clipped.Clip(window->ClipRect); + + // Expand for touch input + const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding); + return rect_for_touch.Contains(g.IO.MousePos); +} + +bool ImGui::IsMouseHoveringWindow() +{ + ImGuiContext& g = *GImGui; + return g.HoveredWindow == g.CurrentWindow; +} + +bool ImGui::IsMouseHoveringAnyWindow() +{ + ImGuiContext& g = *GImGui; + return g.HoveredWindow != NULL; +} + +bool ImGui::IsPosHoveringAnyWindow(const ImVec2& pos) +{ + return FindHoveredWindow(pos, false) != NULL; +} + +static bool IsKeyPressedMap(ImGuiKey key, bool repeat) +{ + const int key_index = GImGui->IO.KeyMap[key]; + return ImGui::IsKeyPressed(key_index, repeat); +} + +int ImGui::GetKeyIndex(ImGuiKey imgui_key) +{ + IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT); + return GImGui->IO.KeyMap[imgui_key]; +} + +// Note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your backend/engine stored them into KeyDown[]! +bool ImGui::IsKeyDown(int user_key_index) +{ + if (user_key_index < 0) return false; + IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown)); + return GImGui->IO.KeysDown[user_key_index]; +} + +bool ImGui::IsKeyPressed(int user_key_index, bool repeat) +{ + ImGuiContext& g = *GImGui; + if (user_key_index < 0) return false; + IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); + const float t = g.IO.KeysDownDuration[user_key_index]; + if (t == 0.0f) + return true; + + if (repeat && t > g.IO.KeyRepeatDelay) + { + float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; + if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) + return true; + } + return false; +} + +bool ImGui::IsKeyReleased(int user_key_index) +{ + ImGuiContext& g = *GImGui; + if (user_key_index < 0) return false; + IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); + if (g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index]) + return true; + return false; +} + +bool ImGui::IsMouseDown(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseDown[button]; +} + +bool ImGui::IsMouseClicked(int button, bool repeat) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + const float t = g.IO.MouseDownDuration[button]; + if (t == 0.0f) + return true; + + if (repeat && t > g.IO.KeyRepeatDelay) + { + float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; + if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) + return true; + } + + return false; +} + +bool ImGui::IsMouseReleased(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseReleased[button]; +} + +bool ImGui::IsMouseDoubleClicked(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseDoubleClicked[button]; +} + +bool ImGui::IsMouseDragging(int button, float lock_threshold) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + if (!g.IO.MouseDown[button]) + return false; + if (lock_threshold < 0.0f) + lock_threshold = g.IO.MouseDragThreshold; + return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; +} + +ImVec2 ImGui::GetMousePos() +{ + return GImGui->IO.MousePos; +} + +// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! +ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() +{ + ImGuiContext& g = *GImGui; + if (g.CurrentPopupStack.Size > 0) + return g.OpenPopupStack[g.CurrentPopupStack.Size-1].MousePosOnOpen; + return g.IO.MousePos; +} + +ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + if (lock_threshold < 0.0f) + lock_threshold = g.IO.MouseDragThreshold; + if (g.IO.MouseDown[button]) + if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold) + return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment). + return ImVec2(0.0f, 0.0f); +} + +void ImGui::ResetMouseDragDelta(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr + g.IO.MouseClickedPos[button] = g.IO.MousePos; +} + +ImGuiMouseCursor ImGui::GetMouseCursor() +{ + return GImGui->MouseCursor; +} + +void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) +{ + GImGui->MouseCursor = cursor_type; +} + +void ImGui::CaptureKeyboardFromApp(bool capture) +{ + GImGui->CaptureKeyboardNextFrame = capture ? 1 : 0; +} + +void ImGui::CaptureMouseFromApp(bool capture) +{ + GImGui->CaptureMouseNextFrame = capture ? 1 : 0; +} + +bool ImGui::IsItemHovered() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.LastItemHoveredAndUsable; +} + +bool ImGui::IsItemHoveredRect() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.LastItemHoveredRect; +} + +bool ImGui::IsItemActive() +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId) + { + ImGuiWindow* window = GetCurrentWindowRead(); + return g.ActiveId == window->DC.LastItemId; + } + return false; +} + +bool ImGui::IsItemClicked(int mouse_button) +{ + return IsMouseClicked(mouse_button) && IsItemHovered(); +} + +bool ImGui::IsAnyItemHovered() +{ + return GImGui->HoveredId != 0 || GImGui->HoveredIdPreviousFrame != 0; +} + +bool ImGui::IsAnyItemActive() +{ + return GImGui->ActiveId != 0; +} + +bool ImGui::IsItemVisible() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImRect r(window->ClipRect); + return r.Overlaps(window->DC.LastItemRect); +} + +// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority. +void ImGui::SetItemAllowOverlap() +{ + ImGuiContext& g = *GImGui; + if (g.HoveredId == g.CurrentWindow->DC.LastItemId) + g.HoveredIdAllowOverlap = true; + if (g.ActiveId == g.CurrentWindow->DC.LastItemId) + g.ActiveIdAllowOverlap = true; +} + +ImVec2 ImGui::GetItemRectMin() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.LastItemRect.Min; +} + +ImVec2 ImGui::GetItemRectMax() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.LastItemRect.Max; +} + +ImVec2 ImGui::GetItemRectSize() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.LastItemRect.GetSize(); +} + +ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImRect rect = window->DC.LastItemRect; + rect.Expand(outward); + return rect.GetClosestPoint(pos, on_edge); +} + +// Tooltip is stored and turned into a BeginTooltip()/EndTooltip() sequence at the end of the frame. Each call override previous value. +void ImGui::SetTooltipV(const char* fmt, va_list args) +{ + ImGuiContext& g = *GImGui; + ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args); +} + +void ImGui::SetTooltip(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + SetTooltipV(fmt, args); + va_end(args); +} + +static ImRect GetVisibleRect() +{ + ImGuiContext& g = *GImGui; + if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y) + return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax); + return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); +} + +void ImGui::BeginTooltip() +{ + ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; + ImGui::Begin("##Tooltip", NULL, flags); +} + +void ImGui::EndTooltip() +{ + IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls + ImGui::End(); +} + +static bool IsPopupOpen(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id; +} + +// Mark popup as open (toggle toward open state). +// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. +// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). +// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) +void ImGui::OpenPopupEx(const char* str_id, bool reopen_existing) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiID id = window->GetID(str_id); + int current_stack_size = g.CurrentPopupStack.Size; + ImGuiPopupRef popup_ref = ImGuiPopupRef(id, window, window->GetID("##menus"), g.IO.MousePos); // Tagged as new ref because constructor sets Window to NULL (we are passing the ParentWindow info here) + if (g.OpenPopupStack.Size < current_stack_size + 1) + g.OpenPopupStack.push_back(popup_ref); + else if (reopen_existing || g.OpenPopupStack[current_stack_size].PopupId != id) + { + g.OpenPopupStack.resize(current_stack_size+1); + g.OpenPopupStack[current_stack_size] = popup_ref; + } +} + +void ImGui::OpenPopup(const char* str_id) +{ + ImGui::OpenPopupEx(str_id, false); +} + +static void CloseInactivePopups() +{ + ImGuiContext& g = *GImGui; + if (g.OpenPopupStack.empty()) + return; + + // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. + // Don't close our own child popup windows + int n = 0; + if (g.FocusedWindow) + { + for (n = 0; n < g.OpenPopupStack.Size; n++) + { + ImGuiPopupRef& popup = g.OpenPopupStack[n]; + if (!popup.Window) + continue; + IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0); + if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow) + continue; + + bool has_focus = false; + for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++) + has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == g.FocusedWindow->RootWindow); + if (!has_focus) + break; + } + } + if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a useful breakpoint on the line below + g.OpenPopupStack.resize(n); +} + +static ImGuiWindow* GetFrontMostModalRootWindow() +{ + ImGuiContext& g = *GImGui; + for (int n = g.OpenPopupStack.Size-1; n >= 0; n--) + if (ImGuiWindow* front_most_popup = g.OpenPopupStack.Data[n].Window) + if (front_most_popup->Flags & ImGuiWindowFlags_Modal) + return front_most_popup; + return NULL; +} + +static void ClosePopupToLevel(int remaining) +{ + ImGuiContext& g = *GImGui; + if (remaining > 0) + ImGui::FocusWindow(g.OpenPopupStack[remaining-1].Window); + else + ImGui::FocusWindow(g.OpenPopupStack[0].ParentWindow); + g.OpenPopupStack.resize(remaining); +} + +static void ClosePopup(ImGuiID id) +{ + if (!IsPopupOpen(id)) + return; + ImGuiContext& g = *GImGui; + ClosePopupToLevel(g.OpenPopupStack.Size - 1); +} + +// Close the popup we have begin-ed into. +void ImGui::CloseCurrentPopup() +{ + ImGuiContext& g = *GImGui; + int popup_idx = g.CurrentPopupStack.Size - 1; + if (popup_idx < 0 || popup_idx > g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId) + return; + while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu)) + popup_idx--; + ClosePopupToLevel(popup_idx); +} + +static inline void ClearSetNextWindowData() +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = 0; + g.SetNextWindowSizeConstraint = g.SetNextWindowFocus = false; +} + +static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiID id = window->GetID(str_id); + if (!IsPopupOpen(id)) + { + ClearSetNextWindowData(); // We behave like Begin() and need to consume those values + return false; + } + + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; + + char name[20]; + if (flags & ImGuiWindowFlags_ChildMenu) + ImFormatString(name, IM_ARRAYSIZE(name), "##menu_%d", g.CurrentPopupStack.Size); // Recycle windows based on depth + else + ImFormatString(name, IM_ARRAYSIZE(name), "##popup_%08x", id); // Not recycling, so we can close/open during the same frame + + bool is_open = ImGui::Begin(name, NULL, flags); + if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) + g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders; + if (!is_open) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + ImGui::EndPopup(); + + return is_open; +} + +bool ImGui::BeginPopup(const char* str_id) +{ + if (GImGui->OpenPopupStack.Size <= GImGui->CurrentPopupStack.Size) // Early out for performance + { + ClearSetNextWindowData(); // We behave like Begin() and need to consume those values + return false; + } + return BeginPopupEx(str_id, ImGuiWindowFlags_ShowBorders); +} + +bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags extra_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiID id = window->GetID(name); + if (!IsPopupOpen(id)) + { + ClearSetNextWindowData(); // We behave like Begin() and need to consume those values + return false; + } + + ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_Modal|ImGuiWindowFlags_NoCollapse|ImGuiWindowFlags_NoSavedSettings; + bool is_open = ImGui::Begin(name, p_open, flags); + if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + { + ImGui::EndPopup(); + if (is_open) + ClosePopup(id); + return false; + } + + return is_open; +} + +void ImGui::EndPopup() +{ + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls + IM_ASSERT(GImGui->CurrentPopupStack.Size > 0); + ImGui::End(); + if (!(window->Flags & ImGuiWindowFlags_Modal)) + ImGui::PopStyleVar(); +} + +// This is a helper to handle the most simple case of associating one named popup to one given widget. +// 1. If you have many possible popups (for different "instances" of a same widget, or for wholly different widgets), you may be better off handling +// this yourself so you can store data relative to the widget that opened the popup instead of choosing different popup identifiers. +// 2. If you want right-clicking on the same item to reopen the popup at new location, use the same code replacing IsItemHovered() with IsItemHoveredRect() +// and passing true to the OpenPopupEx(). +// Because: hovering an item in a window below the popup won't normally trigger is hovering behavior/coloring. The pattern of ignoring the fact that +// the item isn't interactable (because it is blocked by the active popup) may useful in some situation when e.g. large canvas as one item, content of menu +// driven by click position. +bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button) +{ + if (IsItemHovered() && IsMouseClicked(mouse_button)) + OpenPopupEx(str_id, false); + return BeginPopup(str_id); +} + +bool ImGui::BeginPopupContextWindow(bool also_over_items, const char* str_id, int mouse_button) +{ + if (!str_id) str_id = "window_context_menu"; + if (IsMouseHoveringWindow() && IsMouseClicked(mouse_button)) + if (also_over_items || !IsAnyItemHovered()) + OpenPopupEx(str_id, true); + return BeginPopup(str_id); +} + +bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button) +{ + if (!str_id) str_id = "void_context_menu"; + if (!IsMouseHoveringAnyWindow() && IsMouseClicked(mouse_button)) + OpenPopupEx(str_id, true); + return BeginPopup(str_id); +} + +static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) +{ + ImGuiWindow* window = ImGui::GetCurrentWindow(); + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; + + const ImVec2 content_avail = ImGui::GetContentRegionAvail(); + ImVec2 size = ImFloor(size_arg); + if (size.x <= 0.0f) + { + if (size.x == 0.0f) + flags |= ImGuiWindowFlags_ChildWindowAutoFitX; + size.x = ImMax(content_avail.x, 4.0f) - fabsf(size.x); // Arbitrary minimum zero-ish child size of 4.0f (0.0f causing too much issues) + } + if (size.y <= 0.0f) + { + if (size.y == 0.0f) + flags |= ImGuiWindowFlags_ChildWindowAutoFitY; + size.y = ImMax(content_avail.y, 4.0f) - fabsf(size.y); + } + if (border) + flags |= ImGuiWindowFlags_ShowBorders; + flags |= extra_flags; + + char title[256]; + if (name) + ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s.%08X", window->Name, name, id); + else + ImFormatString(title, IM_ARRAYSIZE(title), "%s.%08X", window->Name, id); + + bool ret = ImGui::Begin(title, NULL, size, -1.0f, flags); + + if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) + ImGui::GetCurrentWindow()->Flags &= ~ImGuiWindowFlags_ShowBorders; + + return ret; +} + +bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags); +} + +bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) +{ + return BeginChildEx(NULL, id, size_arg, border, extra_flags); +} + +void ImGui::EndChild() +{ + ImGuiWindow* window = GetCurrentWindow(); + + IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss + if ((window->Flags & ImGuiWindowFlags_ComboBox) || window->BeginCount > 1) + { + ImGui::End(); + } + else + { + // When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting. + ImVec2 sz = GetWindowSize(); + if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f + sz.x = ImMax(4.0f, sz.x); + if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitY) + sz.y = ImMax(4.0f, sz.y); + + ImGui::End(); + + window = GetCurrentWindow(); + ImRect bb(window->DC.CursorPos, window->DC.CursorPos + sz); + ItemSize(sz); + ItemAdd(bb, NULL); + } +} + +// Helper to create a child window / scrolling region that looks like a normal widget frame. +bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, style.Colors[ImGuiCol_FrameBg]); + ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, style.FrameRounding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); + return ImGui::BeginChild(id, size, (g.CurrentWindow->Flags & ImGuiWindowFlags_ShowBorders) ? true : false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags); +} + +void ImGui::EndChildFrame() +{ + ImGui::EndChild(); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); +} + +// Save and compare stack sizes on Begin()/End() to detect usage errors +static void CheckStacksSize(ImGuiWindow* window, bool write) +{ + // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) + ImGuiContext& g = *GImGui; + int* p_backup = &window->DC.StackSizesBackup[0]; + { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop() + { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup() + { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup() + { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor() + { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar() + { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont() + IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup)); +} + +static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& r_inner) +{ + const ImGuiStyle& style = GImGui->Style; + + // Clamp into visible area while not overlapping the cursor. Safety padding is optional if our popup size won't fit without it. + ImVec2 safe_padding = style.DisplaySafeAreaPadding; + ImRect r_outer(GetVisibleRect()); + r_outer.Reduce(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? safe_padding.y : 0.0f)); + ImVec2 base_pos_clamped = ImClamp(base_pos, r_outer.Min, r_outer.Max - size); + + for (int n = (*last_dir != -1) ? -1 : 0; n < 4; n++) // Last, Right, down, up, left. (Favor last used direction). + { + const int dir = (n == -1) ? *last_dir : n; + ImRect rect(dir == 0 ? r_inner.Max.x : r_outer.Min.x, dir == 1 ? r_inner.Max.y : r_outer.Min.y, dir == 3 ? r_inner.Min.x : r_outer.Max.x, dir == 2 ? r_inner.Min.y : r_outer.Max.y); + if (rect.GetWidth() < size.x || rect.GetHeight() < size.y) + continue; + *last_dir = dir; + return ImVec2(dir == 0 ? r_inner.Max.x : dir == 3 ? r_inner.Min.x - size.x : base_pos_clamped.x, dir == 1 ? r_inner.Max.y : dir == 2 ? r_inner.Min.y - size.y : base_pos_clamped.y); + } + + // Fallback, try to keep within display + *last_dir = -1; + ImVec2 pos = base_pos; + pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x); + pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y); + return pos; +} + +ImGuiWindow* ImGui::FindWindowByName(const char* name) +{ + // FIXME-OPT: Store sorted hashes -> pointers so we can do a bissection in a contiguous block + ImGuiContext& g = *GImGui; + ImGuiID id = ImHash(name, 0); + for (int i = 0; i < g.Windows.Size; i++) + if (g.Windows[i]->ID == id) + return g.Windows[i]; + return NULL; +} + +static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; + + // Create window the first time + ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow)); + IM_PLACEMENT_NEW(window) ImGuiWindow(name); + window->Flags = flags; + + if (flags & ImGuiWindowFlags_NoSavedSettings) + { + // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. + window->Size = window->SizeFull = size; + } + else + { + // Retrieve settings from .ini file + // Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window. + window->PosFloat = ImVec2(60, 60); + window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); + + ImGuiIniData* settings = FindWindowSettings(name); + if (!settings) + { + settings = AddWindowSettings(name); + } + else + { + window->SetWindowPosAllowFlags &= ~ImGuiSetCond_FirstUseEver; + window->SetWindowSizeAllowFlags &= ~ImGuiSetCond_FirstUseEver; + window->SetWindowCollapsedAllowFlags &= ~ImGuiSetCond_FirstUseEver; + } + + if (settings->Pos.x != FLT_MAX) + { + window->PosFloat = settings->Pos; + window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); + window->Collapsed = settings->Collapsed; + } + + if (ImLengthSqr(settings->Size) > 0.00001f && !(flags & ImGuiWindowFlags_NoResize)) + size = settings->Size; + window->Size = window->SizeFull = size; + } + + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) + { + window->AutoFitFramesX = window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = false; + } + else + { + if (window->Size.x <= 0.0f) + window->AutoFitFramesX = 2; + if (window->Size.y <= 0.0f) + window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0); + } + + if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus) + g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once + else + g.Windows.push_back(window); + return window; +} + +static void ApplySizeFullWithConstraint(ImGuiWindow* window, ImVec2 new_size) +{ + ImGuiContext& g = *GImGui; + if (g.SetNextWindowSizeConstraint) + { + // Using -1,-1 on either X/Y axis to preserve the current size. + ImRect cr = g.SetNextWindowSizeConstraintRect; + new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x; + new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y; + if (g.SetNextWindowSizeConstraintCallback) + { + ImGuiSizeConstraintCallbackData data; + data.UserData = g.SetNextWindowSizeConstraintCallbackUserData; + data.Pos = window->Pos; + data.CurrentSize = window->SizeFull; + data.DesiredSize = new_size; + g.SetNextWindowSizeConstraintCallback(&data); + new_size = data.DesiredSize; + } + } + if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize))) + new_size = ImMax(new_size, g.Style.WindowMinSize); + window->SizeFull = new_size; +} + +// Push a new ImGui window to add widgets to. +// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. +// - Begin/End can be called multiple times during the frame with the same window name to append content. +// - 'size_on_first_use' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation. +// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). +// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. +// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned. +// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. +// - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiSetCond_FirstUseEver) prior to calling Begin(). +bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) +{ + return ImGui::Begin(name, p_open, ImVec2(0.f, 0.f), -1.0f, flags); +} + +bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + IM_ASSERT(name != NULL); // Window name required + IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() + IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet + + if (flags & ImGuiWindowFlags_NoInputs) + flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize; + + // Find or create + bool window_is_new = false; + ImGuiWindow* window = FindWindowByName(name); + if (!window) + { + window = CreateNewWindow(name, size_on_first_use, flags); + window_is_new = true; + } + + const int current_frame = ImGui::GetFrameCount(); + const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); + if (first_begin_of_the_frame) + window->Flags = (ImGuiWindowFlags)flags; + else + flags = window->Flags; + + // Add to stack + ImGuiWindow* parent_window = !g.CurrentWindowStack.empty() ? g.CurrentWindowStack.back() : NULL; + g.CurrentWindowStack.push_back(window); + SetCurrentWindow(window); + CheckStacksSize(window, true); + IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); + + bool window_was_active = (window->LastFrameActive == current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on + if (flags & ImGuiWindowFlags_Popup) + { + ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size]; + window_was_active &= (window->PopupId == popup_ref.PopupId); + window_was_active &= (window == popup_ref.Window); + popup_ref.Window = window; + g.CurrentPopupStack.push_back(popup_ref); + window->PopupId = popup_ref.PopupId; + } + + const bool window_appearing_after_being_hidden = (window->HiddenFrames == 1); + + // Process SetNextWindow***() calls + bool window_pos_set_by_api = false, window_size_set_by_api = false; + if (g.SetNextWindowPosCond) + { + const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this saving/restore anymore :( need to look into that. + if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowPosAllowFlags |= ImGuiSetCond_Appearing; + window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) != 0; + if (window_pos_set_by_api && ImLengthSqr(g.SetNextWindowPosVal - ImVec2(-FLT_MAX,-FLT_MAX)) < 0.001f) + { + window->SetWindowPosCenterWanted = true; // May be processed on the next frame if this is our first frame and we are measuring size + window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); + } + else + { + SetWindowPos(window, g.SetNextWindowPosVal, g.SetNextWindowPosCond); + } + window->DC.CursorPos = backup_cursor_pos; + g.SetNextWindowPosCond = 0; + } + if (g.SetNextWindowSizeCond) + { + if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowSizeAllowFlags |= ImGuiSetCond_Appearing; + window_size_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0; + SetWindowSize(window, g.SetNextWindowSizeVal, g.SetNextWindowSizeCond); + g.SetNextWindowSizeCond = 0; + } + if (g.SetNextWindowContentSizeCond) + { + window->SizeContentsExplicit = g.SetNextWindowContentSizeVal; + g.SetNextWindowContentSizeCond = 0; + } + else if (first_begin_of_the_frame) + { + window->SizeContentsExplicit = ImVec2(0.0f, 0.0f); + } + if (g.SetNextWindowCollapsedCond) + { + if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowCollapsedAllowFlags |= ImGuiSetCond_Appearing; + SetWindowCollapsed(window, g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond); + g.SetNextWindowCollapsedCond = 0; + } + if (g.SetNextWindowFocus) + { + ImGui::SetWindowFocus(); + g.SetNextWindowFocus = false; + } + + // Update known root window (if we are a child window, otherwise window == window->RootWindow) + int root_idx, root_non_popup_idx; + for (root_idx = g.CurrentWindowStack.Size - 1; root_idx > 0; root_idx--) + if (!(g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow)) + break; + for (root_non_popup_idx = root_idx; root_non_popup_idx > 0; root_non_popup_idx--) + if (!(g.CurrentWindowStack[root_non_popup_idx]->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) + break; + window->ParentWindow = parent_window; + window->RootWindow = g.CurrentWindowStack[root_idx]; + window->RootNonPopupWindow = g.CurrentWindowStack[root_non_popup_idx]; // This is merely for displaying the TitleBgActive color. + + // When reusing window again multiple times a frame, just append content (don't need to setup again) + if (first_begin_of_the_frame) + { + window->Active = true; + window->IndexWithinParent = 0; + window->BeginCount = 0; + window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); + window->LastFrameActive = current_frame; + window->IDStack.resize(1); + + // Clear draw list, setup texture, outer clipping rectangle + window->DrawList->Clear(); + window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); + ImRect fullscreen_rect(GetVisibleRect()); + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_ComboBox|ImGuiWindowFlags_Popup))) + PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true); + else + PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true); + + if (!window_was_active) + { + // Popup first latch mouse position, will position itself when it appears next frame + window->AutoPosLastDirection = -1; + if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) + window->PosFloat = g.IO.MousePos; + } + + // Collapse window by double-clicking on title bar + // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing + if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse)) + { + ImRect title_bar_rect = window->TitleBarRect(); + if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0]) + { + window->Collapsed = !window->Collapsed; + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + MarkIniSettingsDirty(); + FocusWindow(window); + } + } + else + { + window->Collapsed = false; + } + + // SIZE + + // Save contents size from last frame for auto-fitting (unless explicitly specified) + window->SizeContents.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.x - window->Pos.x) + window->Scroll.x)); + window->SizeContents.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.y - window->Pos.y) + window->Scroll.y)); + + // Hide popup/tooltip window when first appearing while we measure size (because we recycle them) + if (window->HiddenFrames > 0) + window->HiddenFrames--; + if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && !window_was_active) + { + window->HiddenFrames = 1; + if (flags & ImGuiWindowFlags_AlwaysAutoResize) + { + if (!window_size_set_by_api) + window->Size = window->SizeFull = ImVec2(0.f, 0.f); + window->SizeContents = ImVec2(0.f, 0.f); + } + } + + // Lock window padding so that altering the ShowBorders flag for children doesn't have side-effects. + window->WindowPadding = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_ComboBox | ImGuiWindowFlags_Popup))) ? ImVec2(0,0) : style.WindowPadding; + + // Calculate auto-fit size + ImVec2 size_auto_fit; + if ((flags & ImGuiWindowFlags_Tooltip) != 0) + { + // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose. + size_auto_fit = window->SizeContents + window->WindowPadding - ImVec2(0.0f, style.ItemSpacing.y); + } + else + { + size_auto_fit = ImClamp(window->SizeContents + window->WindowPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding)); + + // Handling case of auto fit window not fitting in screen on one axis, we are growing auto fit size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding. + if (size_auto_fit.x < window->SizeContents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)) + size_auto_fit.y += style.ScrollbarSize; + if (size_auto_fit.y < window->SizeContents.y && !(flags & ImGuiWindowFlags_NoScrollbar)) + size_auto_fit.x += style.ScrollbarSize; + size_auto_fit.y = ImMax(size_auto_fit.y - style.ItemSpacing.y, 0.0f); + } + + // Handle automatic resize + if (window->Collapsed) + { + // We still process initial auto-fit on collapsed windows to get a window width, + // But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. + if (window->AutoFitFramesX > 0) + window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + if (window->AutoFitFramesY > 0) + window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; + } + else + { + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window_size_set_by_api) + { + window->SizeFull = size_auto_fit; + } + else if ((window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) && !window_size_set_by_api) + { + // Auto-fit only grows during the first few frames + if (window->AutoFitFramesX > 0) + window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + if (window->AutoFitFramesY > 0) + window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + MarkIniSettingsDirty(); + } + } + + // Apply minimum/maximum window size constraints and final size + ApplySizeFullWithConstraint(window, window->SizeFull); + window->Size = window->Collapsed ? window->TitleBarRect().GetSize() : window->SizeFull; + + // POSITION + + // Position child window + if (flags & ImGuiWindowFlags_ChildWindow) + { + window->IndexWithinParent = parent_window->DC.ChildWindows.Size; + parent_window->DC.ChildWindows.push_back(window); + } + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) + { + window->Pos = window->PosFloat = parent_window->DC.CursorPos; + window->Size = window->SizeFull = size_on_first_use; // NB: argument name 'size_on_first_use' misleading here, it's really just 'size' as provided by user passed via BeginChild()->Begin(). + } + + bool window_pos_center = false; + window_pos_center |= (window->SetWindowPosCenterWanted && window->HiddenFrames == 0); + window_pos_center |= ((flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api && window_appearing_after_being_hidden); + if (window_pos_center) + { + // Center (any sort of window) + SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, fullscreen_rect.GetCenter() - window->SizeFull * 0.5f), 0); + } + else if (flags & ImGuiWindowFlags_ChildMenu) + { + // Child menus typically request _any_ position within the parent menu item, and then our FindBestPopupWindowPos() function will move the new menu outside the parent bounds. + // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu. + IM_ASSERT(window_pos_set_by_api); + float horizontal_overlap = style.ItemSpacing.x; // We want some overlap to convey the relative depth of each popup (currently the amount of overlap it is hard-coded to style.ItemSpacing.x, may need to introduce another style value). + ImRect rect_to_avoid; + if (parent_window->DC.MenuBarAppending) + rect_to_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight()); + else + rect_to_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX); + window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); + } + else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_appearing_after_being_hidden) + { + ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1); + window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); + } + + // Position tooltip (always follows mouse) + if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api) + { + ImRect rect_to_avoid(g.IO.MousePos.x - 16, g.IO.MousePos.y - 8, g.IO.MousePos.x + 24, g.IO.MousePos.y + 24); // FIXME: Completely hard-coded. Perhaps center on cursor hit-point instead? + window->PosFloat = FindBestPopupWindowPos(g.IO.MousePos, window->Size, &window->AutoPosLastDirection, rect_to_avoid); + if (window->AutoPosLastDirection == -1) + window->PosFloat = g.IO.MousePos + ImVec2(2,2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. + } + + // Clamp position so it stays visible + if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) + { + if (!window_pos_set_by_api && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. + { + ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); + window->PosFloat = ImMax(window->PosFloat + window->Size, padding) - window->Size; + window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding); + } + } + window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); + + // Default item width. Make it proportional to window size if window manually resizes + if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) + window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); + else + window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f); + + // Prepare for focus requests + window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1); + window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1); + window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1; + window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX; + + // Apply scrolling + if (window->ScrollTarget.x < FLT_MAX) + { + window->Scroll.x = window->ScrollTarget.x; + window->ScrollTarget.x = FLT_MAX; + } + if (window->ScrollTarget.y < FLT_MAX) + { + float center_ratio = window->ScrollTargetCenterRatio.y; + window->Scroll.y = window->ScrollTarget.y - ((1.0f - center_ratio) * (window->TitleBarHeight() + window->MenuBarHeight())) - (center_ratio * window->SizeFull.y); + window->ScrollTarget.y = FLT_MAX; + } + window->Scroll = ImMax(window->Scroll, ImVec2(0.0f, 0.0f)); + if (!window->Collapsed && !window->SkipItems) + window->Scroll = ImMin(window->Scroll, ImMax(ImVec2(0.0f, 0.0f), window->SizeContents - window->SizeFull + window->ScrollbarSizes)); + + // Modal window darkens what is behind them + if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow()) + window->DrawList->AddRectFilled(fullscreen_rect.Min, fullscreen_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio)); + + // Draw window + handle manual resize + ImRect title_bar_rect = window->TitleBarRect(); + const float window_rounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding; + if (window->Collapsed) + { + // Draw title bar only + RenderFrame(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding); + } + else + { + ImU32 resize_col = 0; + const float resize_corner_size = ImMax(g.FontSize * 1.35f, window_rounding + 1.0f + g.FontSize * 0.2f); + if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && !(flags & ImGuiWindowFlags_NoResize)) + { + // Manual resize + const ImVec2 br = window->Rect().GetBR(); + const ImRect resize_rect(br - ImVec2(resize_corner_size * 0.75f, resize_corner_size * 0.75f), br); + const ImGuiID resize_id = window->GetID("#RESIZE"); + bool hovered, held; + ButtonBehavior(resize_rect, resize_id, &hovered, &held, ImGuiButtonFlags_FlattenChilds); + resize_col = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); + + if (hovered || held) + g.MouseCursor = ImGuiMouseCursor_ResizeNWSE; + + if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0]) + { + // Manual auto-fit when double-clicking + ApplySizeFullWithConstraint(window, size_auto_fit); + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + MarkIniSettingsDirty(); + ClearActiveID(); + } + else if (held) + { + // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position + ApplySizeFullWithConstraint(window, (g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize()) - window->Pos); + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + MarkIniSettingsDirty(); + } + + window->Size = window->SizeFull; + title_bar_rect = window->TitleBarRect(); + } + + // Scrollbars + window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > window->Size.y + style.ItemSpacing.y) && !(flags & ImGuiWindowFlags_NoScrollbar)); + window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > window->Size.x - (window->ScrollbarY ? style.ScrollbarSize : 0.0f) - window->WindowPadding.x) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); + window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); + window->BorderSize = (flags & ImGuiWindowFlags_ShowBorders) ? 1.0f : 0.0f; + + // Window background, Default Alpha + ImGuiCol bg_color_idx = ImGuiCol_WindowBg; + if ((flags & ImGuiWindowFlags_ComboBox) != 0) + bg_color_idx = ImGuiCol_ComboBg; + else if ((flags & ImGuiWindowFlags_Tooltip) != 0 || (flags & ImGuiWindowFlags_Popup) != 0) + bg_color_idx = ImGuiCol_PopupBg; + else if ((flags & ImGuiWindowFlags_ChildWindow) != 0) + bg_color_idx = ImGuiCol_ChildWindowBg; + ImVec4 bg_color = style.Colors[bg_color_idx]; + if (bg_alpha >= 0.0f) + bg_color.w = bg_alpha; + bg_color.w *= style.Alpha; + if (bg_color.w > 0.0f) + window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, ColorConvertFloat4ToU32(bg_color), window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImGuiCorner_All : ImGuiCorner_BottomLeft|ImGuiCorner_BottomRight); + + // Title bar + if (!(flags & ImGuiWindowFlags_NoTitleBar)) + window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32((g.FocusedWindow && window->RootNonPopupWindow == g.FocusedWindow->RootNonPopupWindow) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, ImGuiCorner_TopLeft|ImGuiCorner_TopRight); + + // Menu bar + if (flags & ImGuiWindowFlags_MenuBar) + { + ImRect menu_bar_rect = window->MenuBarRect(); + if (flags & ImGuiWindowFlags_ShowBorders) + window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border)); + window->DrawList->AddRectFilled(menu_bar_rect.GetTL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImGuiCorner_TopLeft|ImGuiCorner_TopRight); + } + + // Scrollbars + if (window->ScrollbarX) + Scrollbar(window, true); + if (window->ScrollbarY) + Scrollbar(window, false); + + // Render resize grip + // (after the input handling so we don't have a frame of latency) + if (!(flags & ImGuiWindowFlags_NoResize)) + { + const ImVec2 br = window->Rect().GetBR(); + window->DrawList->PathLineTo(br + ImVec2(-resize_corner_size, -window->BorderSize)); + window->DrawList->PathLineTo(br + ImVec2(-window->BorderSize, -resize_corner_size)); + window->DrawList->PathArcToFast(ImVec2(br.x - window_rounding - window->BorderSize, br.y - window_rounding - window->BorderSize), window_rounding, 0, 3); + window->DrawList->PathFillConvex(resize_col); + } + + // Borders + if (flags & ImGuiWindowFlags_ShowBorders) + { + window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), window_rounding); + window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding); + if (!(flags & ImGuiWindowFlags_NoTitleBar)) + window->DrawList->AddLine(title_bar_rect.GetBL()+ImVec2(1,0), title_bar_rect.GetBR()-ImVec2(1,0), GetColorU32(ImGuiCol_Border)); + } + } + + // Update ContentsRegionMax. All the variable it depends on are set above in this function. + window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x; + window->ContentsRegionRect.Min.y = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); + window->ContentsRegionRect.Max.x = -window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x)); + window->ContentsRegionRect.Max.y = -window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y)); + + // Setup drawing context + window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x; + window->DC.GroupOffsetX = 0.0f; + window->DC.ColumnsOffsetX = 0.0f; + window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y); + window->DC.CursorPos = window->DC.CursorStartPos; + window->DC.CursorPosPrevLine = window->DC.CursorPos; + window->DC.CursorMaxPos = window->DC.CursorStartPos; + window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f; + window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; + window->DC.MenuBarAppending = false; + window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x); + window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; + window->DC.ChildWindows.resize(0); + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.ItemWidth = window->ItemWidthDefault; + window->DC.TextWrapPos = -1.0f; // disabled + window->DC.AllowKeyboardFocus = true; + window->DC.ButtonRepeat = false; + window->DC.ItemWidthStack.resize(0); + window->DC.AllowKeyboardFocusStack.resize(0); + window->DC.ButtonRepeatStack.resize(0); + window->DC.TextWrapPosStack.resize(0); + window->DC.ColumnsCurrent = 0; + window->DC.ColumnsCount = 1; + window->DC.ColumnsStartPosY = window->DC.CursorPos.y; + window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPosY; + window->DC.TreeDepth = 0; + window->DC.StateStorage = &window->StateStorage; + window->DC.GroupStack.resize(0); + window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect; + window->MenuColumns.Update(3, style.ItemSpacing.x, !window_was_active); + + if (window->AutoFitFramesX > 0) + window->AutoFitFramesX--; + if (window->AutoFitFramesY > 0) + window->AutoFitFramesY--; + + // New windows appears in front (we need to do that AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) + if (!window_was_active && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) + if (!(flags & (ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup)) + FocusWindow(window); + + // Title bar + if (!(flags & ImGuiWindowFlags_NoTitleBar)) + { + if (p_open != NULL) + { + const float pad = 2.0f; + const float rad = (window->TitleBarHeight() - pad*2.0f) * 0.5f; + if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad)) + *p_open = false; + } + + const ImVec2 text_size = CalcTextSize(name, NULL, true); + if (!(flags & ImGuiWindowFlags_NoCollapse)) + RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f); + + ImVec2 text_min = window->Pos; + ImVec2 text_max = window->Pos + ImVec2(window->Size.x, style.FramePadding.y*2 + text_size.y); + ImRect clip_rect; + clip_rect.Max = ImVec2(window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x), text_max.y); // Match the size of CloseWindowButton() + float pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0 ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x; + float pad_right = (p_open != NULL) ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x; + if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x); + text_min.x += pad_left; + text_max.x -= pad_right; + clip_rect.Min = ImVec2(text_min.x, window->Pos.y); + RenderTextClipped(text_min, text_max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect); + } + + // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() + window->WindowRectClipped = window->Rect(); + window->WindowRectClipped.Clip(window->ClipRect); + + // Pressing CTRL+C while holding on a window copy its content to the clipboard + // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. + // Maybe we can support CTRL+C on every element? + /* + if (g.ActiveId == move_id) + if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C)) + ImGui::LogToClipboard(); + */ + } + + // Inner clipping rectangle + // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame + // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior. + const ImRect title_bar_rect = window->TitleBarRect(); + const float border_size = window->BorderSize; + ImRect clip_rect; // Force round to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + clip_rect.Min.x = ImFloor(0.5f + title_bar_rect.Min.x + ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f))); + clip_rect.Min.y = ImFloor(0.5f + title_bar_rect.Max.y + window->MenuBarHeight() + border_size); + clip_rect.Max.x = ImFloor(0.5f + window->Pos.x + window->Size.x - window->ScrollbarSizes.x - ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f))); + clip_rect.Max.y = ImFloor(0.5f + window->Pos.y + window->Size.y - window->ScrollbarSizes.y - border_size); + PushClipRect(clip_rect.Min, clip_rect.Max, true); + + // Clear 'accessed' flag last thing + if (first_begin_of_the_frame) + window->Accessed = false; + window->BeginCount++; + g.SetNextWindowSizeConstraint = false; + + // Child window can be out of sight and have "negative" clip windows. + // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar). + if (flags & ImGuiWindowFlags_ChildWindow) + { + IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); + window->Collapsed = parent_window && parent_window->Collapsed; + + if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) + window->Collapsed |= (window->WindowRectClipped.Min.x >= window->WindowRectClipped.Max.x || window->WindowRectClipped.Min.y >= window->WindowRectClipped.Max.y); + + // We also hide the window from rendering because we've already added its border to the command list. + // (we could perform the check earlier in the function but it is simpler at this point) + if (window->Collapsed) + window->Active = false; + } + if (style.Alpha <= 0.0f) + window->Active = false; + + // Return false if we don't intend to display anything to allow user to perform an early out optimization + window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0; + return !window->SkipItems; +} + +void ImGui::End() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + if (window->DC.ColumnsCount != 1) // close columns set if any is open + Columns(1, "#CLOSECOLUMNS"); + PopClipRect(); // inner window clip rectangle + + // Stop logging + if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging + LogFinish(); + + // Pop + // NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin(). + g.CurrentWindowStack.pop_back(); + if (window->Flags & ImGuiWindowFlags_Popup) + g.CurrentPopupStack.pop_back(); + CheckStacksSize(window, false); + SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back()); +} + +// Vertical scrollbar +// The entire piece of code below is rather confusing because: +// - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) +// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar +// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal. +static void Scrollbar(ImGuiWindow* window, bool horizontal) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY"); + + // Render background + bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX); + float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f; + const ImRect window_rect = window->Rect(); + const float border_size = window->BorderSize; + ImRect bb = horizontal + ? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size) + : ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size); + if (!horizontal) + bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f); + if (bb.GetWidth() <= 0.0f || bb.GetHeight() <= 0.0f) + return; + + float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding; + int window_rounding_corners; + if (horizontal) + window_rounding_corners = ImGuiCorner_BottomLeft | (other_scrollbar ? 0 : ImGuiCorner_BottomRight); + else + window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImGuiCorner_TopRight : 0) | (other_scrollbar ? 0 : ImGuiCorner_BottomRight); + window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_ScrollbarBg), window_rounding, window_rounding_corners); + bb.Reduce(ImVec2(ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f))); + + // V denote the main axis of the scrollbar + float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight(); + float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y; + float win_size_avail_v = (horizontal ? window->Size.x : window->Size.y) - other_scrollbar_size_w; + float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y; + + // The grabable box size generally represent the amount visible (vs the total scrollable amount) + // But we maintain a minimum size in pixel to allow for the user to still aim inside. + const float grab_h_pixels = ImMin(ImMax(scrollbar_size_v * ImSaturate(win_size_avail_v / ImMax(win_size_contents_v, win_size_avail_v)), style.GrabMinSize), scrollbar_size_v); + const float grab_h_norm = grab_h_pixels / scrollbar_size_v; + + // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). + bool held = false; + bool hovered = false; + const bool previously_held = (g.ActiveId == id); + ImGui::ButtonBehavior(bb, id, &hovered, &held); + + float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v); + float scroll_ratio = ImSaturate(scroll_v / scroll_max); + float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; + if (held && grab_h_norm < 1.0f) + { + float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y; + float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; + float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y; + + // Click position in scrollbar normalized space (0.0f->1.0f) + const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v); + ImGui::SetHoveredID(id); + + bool seek_absolute = false; + if (!previously_held) + { + // On initial click calculate the distance between mouse and the center of the grab + if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm) + { + *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; + } + else + { + seek_absolute = true; + *click_delta_to_grab_center_v = 0.0f; + } + } + + // Apply scroll + // It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position + const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm)); + scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v)); + if (horizontal) + window->Scroll.x = scroll_v; + else + window->Scroll.y = scroll_v; + + // Update values for rendering + scroll_ratio = ImSaturate(scroll_v / scroll_max); + grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; + + // Update distance to grab now that we have seeked and saturated + if (seek_absolute) + *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; + } + + // Render + const ImU32 grab_col = ImGui::GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); + if (horizontal) + window->DrawList->AddRectFilled(ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y), ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y), grab_col, style.ScrollbarRounding); + else + window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels), grab_col, style.ScrollbarRounding); +} + +// Moving window to front of display (which happens to be back of our sorted list) +void ImGui::FocusWindow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + + // Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing. + g.FocusedWindow = window; + + // Passing NULL allow to disable keyboard focus + if (!window) + return; + + // And move its root window to the top of the pile + if (window->RootWindow) + window = window->RootWindow; + + // Steal focus on active widgets + if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it.. + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window) + ClearActiveID(); + + // Bring to front + if ((window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) || g.Windows.back() == window) + return; + for (int i = 0; i < g.Windows.Size; i++) + if (g.Windows[i] == window) + { + g.Windows.erase(g.Windows.begin() + i); + break; + } + g.Windows.push_back(window); +} + +void ImGui::PushItemWidth(float item_width) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); + window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); +} + +static void PushMultiItemsWidths(int components, float w_full) +{ + ImGuiWindow* window = ImGui::GetCurrentWindow(); + const ImGuiStyle& style = GImGui->Style; + if (w_full <= 0.0f) + w_full = ImGui::CalcItemWidth(); + const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); + window->DC.ItemWidthStack.push_back(w_item_last); + for (int i = 0; i < components-1; i++) + window->DC.ItemWidthStack.push_back(w_item_one); + window->DC.ItemWidth = window->DC.ItemWidthStack.back(); +} + +void ImGui::PopItemWidth() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ItemWidthStack.pop_back(); + window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back(); +} + +float ImGui::CalcItemWidth() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + float w = window->DC.ItemWidth; + if (w < 0.0f) + { + // Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well. + float width_to_right_edge = GetContentRegionAvail().x; + w = ImMax(1.0f, width_to_right_edge + w); + } + w = (float)(int)w; + return w; +} + +static ImFont* GetDefaultFont() +{ + ImGuiContext& g = *GImGui; + return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; +} + +static void SetCurrentFont(ImFont* font) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(font->Scale > 0.0f); + g.Font = font; + g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale; + g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; + g.FontTexUvWhitePixel = g.Font->ContainerAtlas->TexUvWhitePixel; +} + +void ImGui::PushFont(ImFont* font) +{ + ImGuiContext& g = *GImGui; + if (!font) + font = GetDefaultFont(); + SetCurrentFont(font); + g.FontStack.push_back(font); + g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID); +} + +void ImGui::PopFont() +{ + ImGuiContext& g = *GImGui; + g.CurrentWindow->DrawList->PopTextureID(); + g.FontStack.pop_back(); + SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back()); +} + +void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.AllowKeyboardFocus = allow_keyboard_focus; + window->DC.AllowKeyboardFocusStack.push_back(allow_keyboard_focus); +} + +void ImGui::PopAllowKeyboardFocus() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.AllowKeyboardFocusStack.pop_back(); + window->DC.AllowKeyboardFocus = window->DC.AllowKeyboardFocusStack.empty() ? true : window->DC.AllowKeyboardFocusStack.back(); +} + +void ImGui::PushButtonRepeat(bool repeat) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ButtonRepeat = repeat; + window->DC.ButtonRepeatStack.push_back(repeat); +} + +void ImGui::PopButtonRepeat() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ButtonRepeatStack.pop_back(); + window->DC.ButtonRepeat = window->DC.ButtonRepeatStack.empty() ? false : window->DC.ButtonRepeatStack.back(); +} + +void ImGui::PushTextWrapPos(float wrap_pos_x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.TextWrapPos = wrap_pos_x; + window->DC.TextWrapPosStack.push_back(wrap_pos_x); +} + +void ImGui::PopTextWrapPos() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.TextWrapPosStack.pop_back(); + window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back(); +} + +void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) +{ + ImGuiContext& g = *GImGui; + ImGuiColMod backup; + backup.Col = idx; + backup.BackupValue = g.Style.Colors[idx]; + g.ColorModifiers.push_back(backup); + g.Style.Colors[idx] = col; +} + +void ImGui::PopStyleColor(int count) +{ + ImGuiContext& g = *GImGui; + while (count > 0) + { + ImGuiColMod& backup = g.ColorModifiers.back(); + g.Style.Colors[backup.Col] = backup.BackupValue; + g.ColorModifiers.pop_back(); + count--; + } +} + +struct ImGuiStyleVarInfo +{ + ImGuiDataType Type; + ImU32 Offset; + void* GetVarPtr() const { return (void*)((unsigned char*)&GImGui->Style + Offset); } +}; + +static const ImGuiStyleVarInfo GStyleVarInfo[ImGuiStyleVar_Count_] = +{ + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildWindowRounding) }, + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, +}; + +static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx) +{ + IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_Count_); + return &GStyleVarInfo[idx]; +} + +void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) +{ + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float) + { + float* pvar = (float*)var_info->GetVarPtr(); + GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0); // Called function with wrong-type? Variable is not a float. +} + +void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) +{ + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float2) + { + ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(); + GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2. +} + +void ImGui::PopStyleVar(int count) +{ + ImGuiContext& g = *GImGui; + while (count > 0) + { + ImGuiStyleMod& backup = g.StyleModifiers.back(); + const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx); + if (info->Type == ImGuiDataType_Float) (*(float*)info->GetVarPtr()) = backup.BackupFloat[0]; + else if (info->Type == ImGuiDataType_Float2) (*(ImVec2*)info->GetVarPtr()) = ImVec2(backup.BackupFloat[0], backup.BackupFloat[1]); + else if (info->Type == ImGuiDataType_Int) (*(int*)info->GetVarPtr()) = backup.BackupInt[0]; + g.StyleModifiers.pop_back(); + count--; + } +} + +const char* ImGui::GetStyleColName(ImGuiCol idx) +{ + // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1"; + switch (idx) + { + case ImGuiCol_Text: return "Text"; + case ImGuiCol_TextDisabled: return "TextDisabled"; + case ImGuiCol_WindowBg: return "WindowBg"; + case ImGuiCol_ChildWindowBg: return "ChildWindowBg"; + case ImGuiCol_PopupBg: return "PopupBg"; + case ImGuiCol_Border: return "Border"; + case ImGuiCol_BorderShadow: return "BorderShadow"; + case ImGuiCol_FrameBg: return "FrameBg"; + case ImGuiCol_FrameBgHovered: return "FrameBgHovered"; + case ImGuiCol_FrameBgActive: return "FrameBgActive"; + case ImGuiCol_TitleBg: return "TitleBg"; + case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed"; + case ImGuiCol_TitleBgActive: return "TitleBgActive"; + case ImGuiCol_MenuBarBg: return "MenuBarBg"; + case ImGuiCol_ScrollbarBg: return "ScrollbarBg"; + case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab"; + case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered"; + case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive"; + case ImGuiCol_ComboBg: return "ComboBg"; + case ImGuiCol_CheckMark: return "CheckMark"; + case ImGuiCol_SliderGrab: return "SliderGrab"; + case ImGuiCol_SliderGrabActive: return "SliderGrabActive"; + case ImGuiCol_Button: return "Button"; + case ImGuiCol_ButtonHovered: return "ButtonHovered"; + case ImGuiCol_ButtonActive: return "ButtonActive"; + case ImGuiCol_Header: return "Header"; + case ImGuiCol_HeaderHovered: return "HeaderHovered"; + case ImGuiCol_HeaderActive: return "HeaderActive"; + case ImGuiCol_Column: return "Column"; + case ImGuiCol_ColumnHovered: return "ColumnHovered"; + case ImGuiCol_ColumnActive: return "ColumnActive"; + case ImGuiCol_ResizeGrip: return "ResizeGrip"; + case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; + case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; + case ImGuiCol_CloseButton: return "CloseButton"; + case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered"; + case ImGuiCol_CloseButtonActive: return "CloseButtonActive"; + case ImGuiCol_PlotLines: return "PlotLines"; + case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; + case ImGuiCol_PlotHistogram: return "PlotHistogram"; + case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; + case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; + case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening"; + } + IM_ASSERT(0); + return "Unknown"; +} + +bool ImGui::IsWindowHovered() +{ + ImGuiContext& g = *GImGui; + return g.HoveredWindow == g.CurrentWindow && IsWindowContentHoverable(g.HoveredRootWindow); +} + +bool ImGui::IsWindowFocused() +{ + ImGuiContext& g = *GImGui; + return g.FocusedWindow == g.CurrentWindow; +} + +bool ImGui::IsRootWindowFocused() +{ + ImGuiContext& g = *GImGui; + return g.FocusedWindow == g.CurrentWindow->RootWindow; +} + +bool ImGui::IsRootWindowOrAnyChildFocused() +{ + ImGuiContext& g = *GImGui; + return g.FocusedWindow && g.FocusedWindow->RootWindow == g.CurrentWindow->RootWindow; +} + +bool ImGui::IsRootWindowOrAnyChildHovered() +{ + ImGuiContext& g = *GImGui; + return g.HoveredRootWindow && (g.HoveredRootWindow == g.CurrentWindow->RootWindow) && IsWindowContentHoverable(g.HoveredRootWindow); +} + +float ImGui::GetWindowWidth() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Size.x; +} + +float ImGui::GetWindowHeight() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Size.y; +} + +ImVec2 ImGui::GetWindowPos() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + return window->Pos; +} + +static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y) +{ + window->DC.CursorMaxPos.y += window->Scroll.y; + window->Scroll.y = new_scroll_y; + window->DC.CursorMaxPos.y -= window->Scroll.y; +} + +static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowPosAllowFlags & cond) == 0) + return; + window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); + window->SetWindowPosCenterWanted = false; + + // Set + const ImVec2 old_pos = window->Pos; + window->PosFloat = pos; + window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); + window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor + window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected. +} + +void ImGui::SetWindowPos(const ImVec2& pos, ImGuiSetCond cond) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + SetWindowPos(window, pos, cond); +} + +void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond) +{ + if (ImGuiWindow* window = FindWindowByName(name)) + SetWindowPos(window, pos, cond); +} + +ImVec2 ImGui::GetWindowSize() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->Size; +} + +static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowSizeAllowFlags & cond) == 0) + return; + window->SetWindowSizeAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); + + // Set + if (size.x > 0.0f) + { + window->AutoFitFramesX = 0; + window->SizeFull.x = size.x; + } + else + { + window->AutoFitFramesX = 2; + window->AutoFitOnlyGrows = false; + } + if (size.y > 0.0f) + { + window->AutoFitFramesY = 0; + window->SizeFull.y = size.y; + } + else + { + window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = false; + } +} + +void ImGui::SetWindowSize(const ImVec2& size, ImGuiSetCond cond) +{ + SetWindowSize(GImGui->CurrentWindow, size, cond); +} + +void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond) +{ + ImGuiWindow* window = FindWindowByName(name); + if (window) + SetWindowSize(window, size, cond); +} + +static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0) + return; + window->SetWindowCollapsedAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); + + // Set + window->Collapsed = collapsed; +} + +void ImGui::SetWindowCollapsed(bool collapsed, ImGuiSetCond cond) +{ + SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); +} + +bool ImGui::IsWindowCollapsed() +{ + return GImGui->CurrentWindow->Collapsed; +} + +void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond) +{ + ImGuiWindow* window = FindWindowByName(name); + if (window) + SetWindowCollapsed(window, collapsed, cond); +} + +void ImGui::SetWindowFocus() +{ + FocusWindow(GImGui->CurrentWindow); +} + +void ImGui::SetWindowFocus(const char* name) +{ + if (name) + { + if (ImGuiWindow* window = FindWindowByName(name)) + FocusWindow(window); + } + else + { + FocusWindow(NULL); + } +} + +void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowPosVal = pos; + g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowPosCenter(ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowPosVal = ImVec2(-FLT_MAX, -FLT_MAX); + g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowSizeVal = size; + g.SetNextWindowSizeCond = cond ? cond : ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback, void* custom_callback_user_data) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowSizeConstraint = true; + g.SetNextWindowSizeConstraintRect = ImRect(size_min, size_max); + g.SetNextWindowSizeConstraintCallback = custom_callback; + g.SetNextWindowSizeConstraintCallbackUserData = custom_callback_user_data; +} + +void ImGui::SetNextWindowContentSize(const ImVec2& size) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowContentSizeVal = size; + g.SetNextWindowContentSizeCond = ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowContentWidth(float width) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowContentSizeVal = ImVec2(width, g.SetNextWindowContentSizeCond ? g.SetNextWindowContentSizeVal.y : 0.0f); + g.SetNextWindowContentSizeCond = ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowCollapsedVal = collapsed; + g.SetNextWindowCollapsedCond = cond ? cond : ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowFocus() +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowFocus = true; +} + +// In window space (not screen space!) +ImVec2 ImGui::GetContentRegionMax() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImVec2 mx = window->ContentsRegionRect.Max; + if (window->DC.ColumnsCount != 1) + mx.x = GetColumnOffset(window->DC.ColumnsCurrent + 1) - window->WindowPadding.x; + return mx; +} + +ImVec2 ImGui::GetContentRegionAvail() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return GetContentRegionMax() - (window->DC.CursorPos - window->Pos); +} + +float ImGui::GetContentRegionAvailWidth() +{ + return GetContentRegionAvail().x; +} + +// In window space (not screen space!) +ImVec2 ImGui::GetWindowContentRegionMin() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Min; +} + +ImVec2 ImGui::GetWindowContentRegionMax() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Max; +} + +float ImGui::GetWindowContentRegionWidth() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Max.x - window->ContentsRegionRect.Min.x; +} + +float ImGui::GetTextLineHeight() +{ + ImGuiContext& g = *GImGui; + return g.FontSize; +} + +float ImGui::GetTextLineHeightWithSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + g.Style.ItemSpacing.y; +} + +float ImGui::GetItemsLineHeightWithSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y; +} + +ImDrawList* ImGui::GetWindowDrawList() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DrawList; +} + +ImFont* ImGui::GetFont() +{ + return GImGui->Font; +} + +float ImGui::GetFontSize() +{ + return GImGui->FontSize; +} + +ImVec2 ImGui::GetFontTexUvWhitePixel() +{ + return GImGui->FontTexUvWhitePixel; +} + +void ImGui::SetWindowFontScale(float scale) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->FontWindowScale = scale; + g.FontSize = window->CalcFontSize(); +} + +// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. +// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. +ImVec2 ImGui::GetCursorPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos - window->Pos + window->Scroll; +} + +float ImGui::GetCursorPosX() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; +} + +float ImGui::GetCursorPosY() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; +} + +void ImGui::SetCursorPos(const ImVec2& local_pos) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos = window->Pos - window->Scroll + local_pos; + window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); +} + +void ImGui::SetCursorPosX(float x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x; + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x); +} + +void ImGui::SetCursorPosY(float y) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y; + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); +} + +ImVec2 ImGui::GetCursorStartPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorStartPos - window->Pos; +} + +ImVec2 ImGui::GetCursorScreenPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos; +} + +void ImGui::SetCursorScreenPos(const ImVec2& screen_pos) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos = screen_pos; + window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); +} + +float ImGui::GetScrollX() +{ + return GImGui->CurrentWindow->Scroll.x; +} + +float ImGui::GetScrollY() +{ + return GImGui->CurrentWindow->Scroll.y; +} + +float ImGui::GetScrollMaxX() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->SizeContents.x - window->SizeFull.x - window->ScrollbarSizes.x; +} + +float ImGui::GetScrollMaxY() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->SizeContents.y - window->SizeFull.y - window->ScrollbarSizes.y; +} + +void ImGui::SetScrollX(float scroll_x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->ScrollTarget.x = scroll_x; + window->ScrollTargetCenterRatio.x = 0.0f; +} + +void ImGui::SetScrollY(float scroll_y) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY + window->ScrollTargetCenterRatio.y = 0.0f; +} + +void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio) +{ + // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); + window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y); + if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y) // Minor hack to make "scroll to top" take account of WindowPadding, else it would scroll to (WindowPadding.y - ItemSpacing.y) + window->ScrollTarget.y = 0.0f; + window->ScrollTargetCenterRatio.y = center_y_ratio; +} + +// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. +void ImGui::SetScrollHere(float center_y_ratio) +{ + ImGuiWindow* window = GetCurrentWindow(); + float target_y = window->DC.CursorPosPrevLine.y + (window->DC.PrevLineHeight * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. + SetScrollFromPosY(target_y - window->Pos.y, center_y_ratio); +} + +void ImGui::SetKeyboardFocusHere(int offset) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset; + window->FocusIdxTabRequestNext = INT_MAX; +} + +void ImGui::SetStateStorage(ImGuiStorage* tree) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.StateStorage = tree ? tree : &window->StateStorage; +} + +ImGuiStorage* ImGui::GetStateStorage() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.StateStorage; +} + +void ImGui::TextV(const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + TextUnformatted(g.TempBuffer, text_end); +} + +void ImGui::Text(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextV(fmt, args); + va_end(args); +} + +void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) +{ + PushStyleColor(ImGuiCol_Text, col); + TextV(fmt, args); + PopStyleColor(); +} + +void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextColoredV(col, fmt, args); + va_end(args); +} + +void ImGui::TextDisabledV(const char* fmt, va_list args) +{ + PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]); + TextV(fmt, args); + PopStyleColor(); +} + +void ImGui::TextDisabled(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextDisabledV(fmt, args); + va_end(args); +} + +void ImGui::TextWrappedV(const char* fmt, va_list args) +{ + bool need_wrap = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position is one ia already set + if (need_wrap) PushTextWrapPos(0.0f); + TextV(fmt, args); + if (need_wrap) PopTextWrapPos(); +} + +void ImGui::TextWrapped(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextWrappedV(fmt, args); + va_end(args); +} + +void ImGui::TextUnformatted(const char* text, const char* text_end) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + IM_ASSERT(text != NULL); + const char* text_begin = text; + if (text_end == NULL) + text_end = text + strlen(text); // FIXME-OPT + + const float wrap_pos_x = window->DC.TextWrapPos; + const bool wrap_enabled = wrap_pos_x >= 0.0f; + if (text_end - text > 2000 && !wrap_enabled) + { + // Long text! + // Perform manual coarse clipping to optimize for long multi-line text + // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. + // We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. + const char* line = text; + const float line_height = GetTextLineHeight(); + const ImVec2 text_pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrentLineTextBaseOffset); + const ImRect clip_rect = window->ClipRect; + ImVec2 text_size(0,0); + + if (text_pos.y <= clip_rect.Max.y) + { + ImVec2 pos = text_pos; + + // Lines to skip (can't skip when logging text) + if (!g.LogEnabled) + { + int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height); + if (lines_skippable > 0) + { + int lines_skipped = 0; + while (line < text_end && lines_skipped < lines_skippable) + { + const char* line_end = strchr(line, '\n'); + if (!line_end) + line_end = text_end; + line = line_end + 1; + lines_skipped++; + } + pos.y += lines_skipped * line_height; + } + } + + // Lines to render + if (line < text_end) + { + ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height)); + while (line < text_end) + { + const char* line_end = strchr(line, '\n'); + if (IsClippedEx(line_rect, NULL, false)) + break; + + const ImVec2 line_size = CalcTextSize(line, line_end, false); + text_size.x = ImMax(text_size.x, line_size.x); + RenderText(pos, line, line_end, false); + if (!line_end) + line_end = text_end; + line = line_end + 1; + line_rect.Min.y += line_height; + line_rect.Max.y += line_height; + pos.y += line_height; + } + + // Count remaining lines + int lines_skipped = 0; + while (line < text_end) + { + const char* line_end = strchr(line, '\n'); + if (!line_end) + line_end = text_end; + line = line_end + 1; + lines_skipped++; + } + pos.y += lines_skipped * line_height; + } + + text_size.y += (pos - text_pos).y; + } + + ImRect bb(text_pos, text_pos + text_size); + ItemSize(bb); + ItemAdd(bb, NULL); + } + else + { + const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; + const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); + + // Account of baseline offset + ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset); + ImRect bb(text_pos, text_pos + text_size); + ItemSize(text_size); + if (!ItemAdd(bb, NULL)) + return; + + // Render (we don't hide text after ## in this end-user function) + RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width); + } +} + +void ImGui::AlignFirstTextHeightToWidgets() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + // Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height. + ImGuiContext& g = *GImGui; + ItemSize(ImVec2(0, g.FontSize + g.Style.FramePadding.y*2), g.Style.FramePadding.y); + SameLine(0, 0); +} + +// Add a label+text combo aligned to other label+value widgets +void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float w = CalcItemWidth(); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2)); + const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, NULL)) + return; + + // Render + const char* value_text_begin = &g.TempBuffer[0]; + const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f)); + if (label_size.x > 0.0f) + RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); +} + +void ImGui::LabelText(const char* label, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + LabelTextV(label, fmt, args); + va_end(args); +} + +static inline bool IsWindowContentHoverable(ImGuiWindow* window) +{ + // An active popup disable hovering on other windows (apart from its own children) + ImGuiContext& g = *GImGui; + if (ImGuiWindow* focused_window = g.FocusedWindow) + if (ImGuiWindow* focused_root_window = focused_window->RootWindow) + if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_root_window->WasActive && focused_root_window != window->RootWindow) + return false; + + return true; +} + +bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + if (flags & ImGuiButtonFlags_Disabled) + { + if (out_hovered) *out_hovered = false; + if (out_held) *out_held = false; + if (g.ActiveId == id) ClearActiveID(); + return false; + } + + if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0) + flags |= ImGuiButtonFlags_PressedOnClickRelease; + + bool pressed = false; + bool hovered = IsHovered(bb, id, (flags & ImGuiButtonFlags_FlattenChilds) != 0); + if (hovered) + { + SetHoveredID(id); + if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) + { + // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat + // PressedOnClickRelease | * | .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds + // PressedOnClick | | .. + // PressedOnRelease | | .. (NOT on release) + // PressedOnDoubleClick | | .. + if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0]) + { + SetActiveID(id, window); // Hold on ID + FocusWindow(window); + g.ActiveIdClickOffset = g.IO.MousePos - bb.Min; + } + if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0])) + { + pressed = true; + ClearActiveID(); + FocusWindow(window); + } + if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0]) + { + if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps + pressed = true; + ClearActiveID(); + } + + // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above). + // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings. + if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true)) + pressed = true; + } + } + + bool held = false; + if (g.ActiveId == id) + { + if (g.IO.MouseDown[0]) + { + held = true; + } + else + { + if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease)) + if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps + pressed = true; + ClearActiveID(); + } + } + + // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one. + if (hovered && (flags & ImGuiButtonFlags_AllowOverlapMode) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0)) + hovered = pressed = held = false; + + if (out_hovered) *out_hovered = hovered; + if (out_held) *out_held = held; + + return pressed; +} + +bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + ImVec2 pos = window->DC.CursorPos; + if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) + pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y; + ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); + + const ImRect bb(pos, pos + size); + ItemSize(bb, style.FramePadding.y); + if (!ItemAdd(bb, &id)) + return false; + + if (window->DC.ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); + + // Render + const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); + RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); + + // Automatically close popups + //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + // CloseCurrentPopup(); + + return pressed; +} + +bool ImGui::Button(const char* label, const ImVec2& size_arg) +{ + return ButtonEx(label, size_arg, 0); +} + +// Small buttons fits within text without additional vertical spacing. +bool ImGui::SmallButton(const char* label) +{ + ImGuiContext& g = *GImGui; + float backup_padding_y = g.Style.FramePadding.y; + g.Style.FramePadding.y = 0.0f; + bool pressed = ButtonEx(label, ImVec2(0,0), ImGuiButtonFlags_AlignTextBaseLine); + g.Style.FramePadding.y = backup_padding_y; + return pressed; +} + +// Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. +// Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) +bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiID id = window->GetID(str_id); + ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(bb); + if (!ItemAdd(bb, &id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + + return pressed; +} + +// Upper-right button to close a window. +bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius) +{ + ImGuiWindow* window = GetCurrentWindow(); + + const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius)); + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + + // Render + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton); + const ImVec2 center = bb.GetCenter(); + window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), col, 12); + + const float cross_extent = (radius * 0.7071f) - 1.0f; + if (hovered) + { + window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), GetColorU32(ImGuiCol_Text)); + window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), GetColorU32(ImGuiCol_Text)); + } + + return pressed; +} + +void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + if (border_col.w > 0.0f) + bb.Max += ImVec2(2,2); + ItemSize(bb); + if (!ItemAdd(bb, NULL)) + return; + + if (border_col.w > 0.0f) + { + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f); + window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, GetColorU32(tint_col)); + } + else + { + window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col)); + } +} + +// frame_padding < 0: uses FramePadding from style (default) +// frame_padding = 0: no framing +// frame_padding > 0: set framing size +// The color used are the button colors. +bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + // Default to using texture ID as ID. User can still push string/integer prefixes. + // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV. + PushID((void *)user_texture_id); + const ImGuiID id = window->GetID("#image"); + PopID(); + + const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding; + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding*2); + const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size); + ItemSize(bb); + if (!ItemAdd(bb, &id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + + // Render + const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding)); + if (bg_col.w > 0.0f) + window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col)); + window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col)); + + return pressed; +} + +// Start logging ImGui output to TTY +void ImGui::LogToTTY(int max_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + ImGuiWindow* window = GetCurrentWindowRead(); + + g.LogEnabled = true; + g.LogFile = stdout; + g.LogStartDepth = window->DC.TreeDepth; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; +} + +// Start logging ImGui output to given file +void ImGui::LogToFile(int max_depth, const char* filename) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + ImGuiWindow* window = GetCurrentWindowRead(); + + if (!filename) + { + filename = g.IO.LogFilename; + if (!filename) + return; + } + + g.LogFile = ImFileOpen(filename, "ab"); + if (!g.LogFile) + { + IM_ASSERT(g.LogFile != NULL); // Consider this an error + return; + } + g.LogEnabled = true; + g.LogStartDepth = window->DC.TreeDepth; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; +} + +// Start logging ImGui output to clipboard +void ImGui::LogToClipboard(int max_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + ImGuiWindow* window = GetCurrentWindowRead(); + + g.LogEnabled = true; + g.LogFile = NULL; + g.LogStartDepth = window->DC.TreeDepth; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; +} + +void ImGui::LogFinish() +{ + ImGuiContext& g = *GImGui; + if (!g.LogEnabled) + return; + + LogText(IM_NEWLINE); + g.LogEnabled = false; + if (g.LogFile != NULL) + { + if (g.LogFile == stdout) + fflush(g.LogFile); + else + fclose(g.LogFile); + g.LogFile = NULL; + } + if (g.LogClipboard->size() > 1) + { + SetClipboardText(g.LogClipboard->begin()); + g.LogClipboard->clear(); + } +} + +// Helper to display logging buttons +void ImGui::LogButtons() +{ + ImGuiContext& g = *GImGui; + + PushID("LogButtons"); + const bool log_to_tty = Button("Log To TTY"); SameLine(); + const bool log_to_file = Button("Log To File"); SameLine(); + const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); + PushItemWidth(80.0f); + PushAllowKeyboardFocus(false); + SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL); + PopAllowKeyboardFocus(); + PopItemWidth(); + PopID(); + + // Start logging at the end of the function so that the buttons don't appear in the log + if (log_to_tty) + LogToTTY(g.LogAutoExpandMaxDepth); + if (log_to_file) + LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename); + if (log_to_clipboard) + LogToClipboard(g.LogAutoExpandMaxDepth); +} + +bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) +{ + if (flags & ImGuiTreeNodeFlags_Leaf) + return true; + + // We only write to the tree storage if the user clicks (or explicitely use SetNextTreeNode*** functions) + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiStorage* storage = window->DC.StateStorage; + + bool is_open; + if (g.SetNextTreeNodeOpenCond != 0) + { + if (g.SetNextTreeNodeOpenCond & ImGuiSetCond_Always) + { + is_open = g.SetNextTreeNodeOpenVal; + storage->SetInt(id, is_open); + } + else + { + // We treat ImGuiSetCondition_Once and ImGuiSetCondition_FirstUseEver the same because tree node state are not saved persistently. + const int stored_value = storage->GetInt(id, -1); + if (stored_value == -1) + { + is_open = g.SetNextTreeNodeOpenVal; + storage->SetInt(id, is_open); + } + else + { + is_open = stored_value != 0; + } + } + g.SetNextTreeNodeOpenCond = 0; + } + else + { + is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; + } + + // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). + // NB- If we are above max depth we still allow manually opened nodes to be logged. + if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth) + is_open = true; + + return is_open; +} + +bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0; + const ImVec2 padding = display_frame ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f); + + if (!label_end) + label_end = FindRenderedTextEnd(label); + const ImVec2 label_size = CalcTextSize(label, label_end, false); + + // We vertically grow up to current line height up the typical widget height. + const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset - padding.y); // Latch before ItemSize changes it + const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); + ImRect bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height)); + if (display_frame) + { + // Framed header expand a little outside the default padding + bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1; + bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1; + } + + const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing + const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser + ItemSize(ImVec2(text_width, frame_height), text_base_offset_y); + + // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing + // (Ideally we'd want to add a flag for the user to specify we want want the hit test to be done up to the right side of the content or not) + const ImRect interact_bb = display_frame ? bb : ImRect(bb.Min.x, bb.Min.y, bb.Min.x + text_width + style.ItemSpacing.x*2, bb.Max.y); + bool is_open = TreeNodeBehaviorIsOpen(id, flags); + if (!ItemAdd(interact_bb, &id)) + { + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushRawID(id); + return is_open; + } + + // Flags that affects opening behavior: + // - 0(default) ..................... single-click anywhere to open + // - OpenOnDoubleClick .............. double-click anywhere to open + // - OpenOnArrow .................... single-click on arrow to open + // - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open + ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowOverlapMode) ? ImGuiButtonFlags_AllowOverlapMode : 0); + if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) + button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0); + bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); + if (pressed && !(flags & ImGuiTreeNodeFlags_Leaf)) + { + bool toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)); + if (flags & ImGuiTreeNodeFlags_OpenOnArrow) + toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)); + if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) + toggled |= g.IO.MouseDoubleClicked[0]; + if (toggled) + { + is_open = !is_open; + window->DC.StateStorage->SetInt(id, is_open); + } + } + if (flags & ImGuiTreeNodeFlags_AllowOverlapMode) + SetItemAllowOverlap(); + + // Render + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + const ImVec2 text_pos = bb.Min + ImVec2(text_offset_x, padding.y + text_base_offset_y); + if (display_frame) + { + // Framed type + RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); + RenderCollapseTriangle(bb.Min + padding + ImVec2(0.0f, text_base_offset_y), is_open, 1.0f); + if (g.LogEnabled) + { + // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here. + const char log_prefix[] = "\n##"; + const char log_suffix[] = "##"; + LogRenderedText(text_pos, log_prefix, log_prefix+3); + RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size); + LogRenderedText(text_pos, log_suffix+1, log_suffix+3); + } + else + { + RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size); + } + } + else + { + // Unframed typed for tree nodes + if (hovered || (flags & ImGuiTreeNodeFlags_Selected)) + RenderFrame(bb.Min, bb.Max, col, false); + + if (flags & ImGuiTreeNodeFlags_Bullet) + RenderBullet(bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y)); + else if (!(flags & ImGuiTreeNodeFlags_Leaf)) + RenderCollapseTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open, 0.70f); + if (g.LogEnabled) + LogRenderedText(text_pos, ">"); + RenderText(text_pos, label, label_end, false); + } + + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushRawID(id); + return is_open; +} + +// CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag). +// This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). +bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen, label); +} + +bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + if (p_open && !*p_open) + return false; + + ImGuiID id = window->GetID(label); + bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowOverlapMode : 0), label); + if (p_open) + { + // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. + ImGuiContext& g = *GImGui; + float button_sz = g.FontSize * 0.5f; + if (CloseButton(window->GetID((void*)(intptr_t)(id+1)), ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_sz, window->DC.LastItemRect.Min.y + g.Style.FramePadding.y + button_sz), button_sz)) + *p_open = false; + } + + return is_open; +} + +bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + return TreeNodeBehavior(window->GetID(label), flags, label, NULL); +} + +bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end); +} + +bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end); +} + +bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) +{ + return TreeNodeExV(str_id, 0, fmt, args); +} + +bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) +{ + return TreeNodeExV(ptr_id, 0, fmt, args); +} + +bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(str_id, flags, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(ptr_id, flags, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(str_id, 0, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(ptr_id, 0, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const char* label) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + return TreeNodeBehavior(window->GetID(label), 0, label, NULL); +} + +void ImGui::TreeAdvanceToLabelPos() +{ + ImGuiContext& g = *GImGui; + g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing(); +} + +// Horizontal distance preceding label when using TreeNode() or Bullet() +float ImGui::GetTreeNodeToLabelSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + (g.Style.FramePadding.x * 2.0f); +} + +void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextTreeNodeOpenVal = is_open; + g.SetNextTreeNodeOpenCond = cond ? cond : ImGuiSetCond_Always; +} + +void ImGui::PushID(const char* str_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.push_back(window->GetID(str_id)); +} + +void ImGui::PushID(const char* str_id_begin, const char* str_id_end) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.push_back(window->GetID(str_id_begin, str_id_end)); +} + +void ImGui::PushID(const void* ptr_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.push_back(window->GetID(ptr_id)); +} + +void ImGui::PushID(int int_id) +{ + const void* ptr_id = (void*)(intptr_t)int_id; + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.push_back(window->GetID(ptr_id)); +} + +void ImGui::PopID() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.pop_back(); +} + +ImGuiID ImGui::GetID(const char* str_id) +{ + return GImGui->CurrentWindow->GetID(str_id); +} + +ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end) +{ + return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end); +} + +ImGuiID ImGui::GetID(const void* ptr_id) +{ + return GImGui->CurrentWindow->GetID(ptr_id); +} + +void ImGui::Bullet() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height)); + ItemSize(bb); + if (!ItemAdd(bb, NULL)) + { + SameLine(0, style.FramePadding.x*2); + return; + } + + // Render and stay on same line + RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); + SameLine(0, style.FramePadding.x*2); +} + +// Text with a little bullet aligned to the typical tree node. +void ImGui::BulletTextV(const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + const char* text_begin = g.TempBuffer; + const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + const ImVec2 label_size = CalcTextSize(text_begin, text_end, false); + const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it + const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding + ItemSize(bb); + if (!ItemAdd(bb, NULL)) + return; + + // Render + RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); + RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false); +} + +void ImGui::BulletText(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + BulletTextV(fmt, args); + va_end(args); +} + +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size) +{ + if (data_type == ImGuiDataType_Int) + ImFormatString(buf, buf_size, display_format, *(int*)data_ptr); + else if (data_type == ImGuiDataType_Float) + ImFormatString(buf, buf_size, display_format, *(float*)data_ptr); +} + +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size) +{ + if (data_type == ImGuiDataType_Int) + { + if (decimal_precision < 0) + ImFormatString(buf, buf_size, "%d", *(int*)data_ptr); + else + ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr); + } + else if (data_type == ImGuiDataType_Float) + { + if (decimal_precision < 0) + ImFormatString(buf, buf_size, "%f", *(float*)data_ptr); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits? + else + ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr); + } +} + +static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1 +{ + if (data_type == ImGuiDataType_Int) + { + if (op == '+') + *(int*)value1 = *(int*)value1 + *(const int*)value2; + else if (op == '-') + *(int*)value1 = *(int*)value1 - *(const int*)value2; + } + else if (data_type == ImGuiDataType_Float) + { + if (op == '+') + *(float*)value1 = *(float*)value1 + *(const float*)value2; + else if (op == '-') + *(float*)value1 = *(float*)value1 - *(const float*)value2; + } +} + +// User can input math operators (e.g. +100) to edit a numerical values. +static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format) +{ + while (ImCharIsSpace(*buf)) + buf++; + + // We don't support '-' op because it would conflict with inputing negative value. + // Instead you can use +-100 to subtract from an existing value + char op = buf[0]; + if (op == '+' || op == '*' || op == '/') + { + buf++; + while (ImCharIsSpace(*buf)) + buf++; + } + else + { + op = 0; + } + if (!buf[0]) + return false; + + if (data_type == ImGuiDataType_Int) + { + if (!scalar_format) + scalar_format = "%d"; + int* v = (int*)data_ptr; + const int old_v = *v; + int arg0 = *v; + if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1) + return false; + + // Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision + float arg1 = 0.0f; + if (op == '+') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 + arg1); } // Add (use "+-" to subtract) + else if (op == '*') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 * arg1); } // Multiply + else if (op == '/') { if (sscanf(buf, "%f", &arg1) == 1 && arg1 != 0.0f) *v = (int)(arg0 / arg1); }// Divide + else { if (sscanf(buf, scalar_format, &arg0) == 1) *v = arg0; } // Assign constant + return (old_v != *v); + } + else if (data_type == ImGuiDataType_Float) + { + // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in + scalar_format = "%f"; + float* v = (float*)data_ptr; + const float old_v = *v; + float arg0 = *v; + if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1) + return false; + + float arg1 = 0.0f; + if (sscanf(buf, scalar_format, &arg1) < 1) + return false; + if (op == '+') { *v = arg0 + arg1; } // Add (use "+-" to subtract) + else if (op == '*') { *v = arg0 * arg1; } // Multiply + else if (op == '/') { if (arg1 != 0.0f) *v = arg0 / arg1; } // Divide + else { *v = arg1; } // Assign constant + return (old_v != *v); + } + + return false; +} + +// Create text input in place of a slider (when CTRL+Clicking on slider) +bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen) + SetActiveID(g.ScalarAsInputTextId, window); + SetHoveredID(0); + FocusableItemUnregister(window); + + char buf[32]; + DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf)); + bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll); + if (g.ScalarAsInputTextId == 0) + { + // First frame + IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible) + g.ScalarAsInputTextId = g.ActiveId; + SetHoveredID(id); + } + else if (g.ActiveId != g.ScalarAsInputTextId) + { + // Release + g.ScalarAsInputTextId = 0; + } + if (text_value_changed) + return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL); + return false; +} + +// Parse display precision back from the display format string +int ImGui::ParseFormatPrecision(const char* fmt, int default_precision) +{ + int precision = default_precision; + while ((fmt = strchr(fmt, '%')) != NULL) + { + fmt++; + if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%" + while (*fmt >= '0' && *fmt <= '9') + fmt++; + if (*fmt == '.') + { + precision = atoi(fmt + 1); + if (precision < 0 || precision > 10) + precision = default_precision; + } + break; + } + return precision; +} + +float ImGui::RoundScalar(float value, int decimal_precision) +{ + // Round past decimal precision + // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0 + // FIXME: Investigate better rounding methods + static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f }; + float min_step = (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision); + bool negative = value < 0.0f; + value = fabsf(value); + float remainder = fmodf(value, min_step); + if (remainder <= min_step*0.5f) + value -= remainder; + else + value += (min_step - remainder); + return negative ? -value : value; +} + +static inline float SliderBehaviorCalcRatioFromValue(float v, float v_min, float v_max, float power, float linear_zero_pos) +{ + if (v_min == v_max) + return 0.0f; + + const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f); + const float v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); + if (is_non_linear) + { + if (v_clamped < 0.0f) + { + const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min); + return (1.0f - powf(f, 1.0f/power)) * linear_zero_pos; + } + else + { + const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min)); + return linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos); + } + } + + // Linear slider + return (v_clamped - v_min) / (v_max - v_min); +} + +bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + const ImGuiStyle& style = g.Style; + + // Draw frame + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + + const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f); + const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0; + + const float grab_padding = 2.0f; + const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f); + float grab_sz; + if (decimal_precision > 0) + grab_sz = ImMin(style.GrabMinSize, slider_sz); + else + grab_sz = ImMin(ImMax(1.0f * (slider_sz / ((v_min < v_max ? v_max - v_min : v_min - v_max) + 1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit + const float slider_usable_sz = slider_sz - grab_sz; + const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f; + const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f; + + // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f + float linear_zero_pos = 0.0f; // 0.0->1.0f + if (v_min * v_max < 0.0f) + { + // Different sign + const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power); + const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power); + linear_zero_pos = linear_dist_min_to_0 / (linear_dist_min_to_0+linear_dist_max_to_0); + } + else + { + // Same sign + linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f; + } + + // Process clicking on the slider + bool value_changed = false; + if (g.ActiveId == id) + { + if (g.IO.MouseDown[0]) + { + const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; + float clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f; + if (!is_horizontal) + clicked_t = 1.0f - clicked_t; + + float new_value; + if (is_non_linear) + { + // Account for logarithmic scale on both sides of the zero + if (clicked_t < linear_zero_pos) + { + // Negative: rescale to the negative range before powering + float a = 1.0f - (clicked_t / linear_zero_pos); + a = powf(a, power); + new_value = ImLerp(ImMin(v_max,0.0f), v_min, a); + } + else + { + // Positive: rescale to the positive range before powering + float a; + if (fabsf(linear_zero_pos - 1.0f) > 1.e-6f) + a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos); + else + a = clicked_t; + a = powf(a, power); + new_value = ImLerp(ImMax(v_min,0.0f), v_max, a); + } + } + else + { + // Linear slider + new_value = ImLerp(v_min, v_max, clicked_t); + } + + // Round past decimal precision + new_value = RoundScalar(new_value, decimal_precision); + if (*v != new_value) + { + *v = new_value; + value_changed = true; + } + } + else + { + ClearActiveID(); + } + } + + // Calculate slider grab positioning + float grab_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos); + + // Draw + if (!is_horizontal) + grab_t = 1.0f - grab_t; + const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); + ImRect grab_bb; + if (is_horizontal) + grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + grab_padding), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - grab_padding)); + else + grab_bb = ImRect(ImVec2(frame_bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f)); + window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); + + return value_changed; +} + +// Use power!=1.0 for logarithmic sliders. +// Adjust display_format to decorate the value with a prefix or a suffix. +// "%.3f" 1.234 +// "%5.2f secs" 01.23 secs +// "Gold: %.0f" Gold: 1 +bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w = CalcItemWidth(); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + // NB- we don't call ItemSize() yet because we may turn into a text edit box below + if (!ItemAdd(total_bb, &id)) + { + ItemSize(total_bb, style.FramePadding.y); + return false; + } + + const bool hovered = IsHovered(frame_bb, id); + if (hovered) + SetHoveredID(id); + + if (!display_format) + display_format = "%.3f"; + int decimal_precision = ParseFormatPrecision(display_format, 3); + + // Tabbing or CTRL-clicking on Slider turns it into an input box + bool start_text_input = false; + const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id); + if (tab_focus_requested || (hovered && g.IO.MouseClicked[0])) + { + SetActiveID(id, window); + FocusWindow(window); + + if (tab_focus_requested || g.IO.KeyCtrl) + { + start_text_input = true; + g.ScalarAsInputTextId = 0; + } + } + if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) + return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); + + ItemSize(total_bb, style.FramePadding.y); + + // Actual slider behavior + render grab + const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + char value_buf[64]; + const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + return value_changed; +} + +bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); + const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + ItemSize(bb, style.FramePadding.y); + if (!ItemAdd(frame_bb, &id)) + return false; + + const bool hovered = IsHovered(frame_bb, id); + if (hovered) + SetHoveredID(id); + + if (!display_format) + display_format = "%.3f"; + int decimal_precision = ParseFormatPrecision(display_format, 3); + + if (hovered && g.IO.MouseClicked[0]) + { + SetActiveID(id, window); + FocusWindow(window); + } + + // Actual slider behavior + render grab + bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + // For the vertical slider we allow centered text to overlap the frame padding + char value_buf[64]; + char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f)); + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + return value_changed; +} + +bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max) +{ + float v_deg = (*v_rad) * 360.0f / (2*IM_PI); + bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f); + *v_rad = v_deg * (2*IM_PI) / 360.0f; + return value_changed; +} + +bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format) +{ + if (!display_format) + display_format = "%.0f"; + float v_f = (float)*v; + bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); + *v = (int)v_f; + return value_changed; +} + +bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format) +{ + if (!display_format) + display_format = "%.0f"; + float v_f = (float)*v; + bool value_changed = VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); + *v = (int)v_f; + return value_changed; +} + +// Add multiple sliders on 1 line for compact edition of multiple components +bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= SliderFloat("##v", &v[i], v_min, v_max, display_format, power); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power) +{ + return SliderFloatN(label, v, 2, v_min, v_max, display_format, power); +} + +bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power) +{ + return SliderFloatN(label, v, 3, v_min, v_max, display_format, power); +} + +bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power) +{ + return SliderFloatN(label, v, 4, v_min, v_max, display_format, power); +} + +bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= SliderInt("##v", &v[i], v_min, v_max, display_format); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format) +{ + return SliderIntN(label, v, 2, v_min, v_max, display_format); +} + +bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format) +{ + return SliderIntN(label, v, 3, v_min, v_max, display_format); +} + +bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format) +{ + return SliderIntN(label, v, 4, v_min, v_max, display_format); +} + +bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + // Draw frame + const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); + + bool value_changed = false; + + // Process clicking on the drag + if (g.ActiveId == id) + { + if (g.IO.MouseDown[0]) + { + if (g.ActiveIdIsJustActivated) + { + // Lock current value on click + g.DragCurrentValue = *v; + g.DragLastMouseDelta = ImVec2(0.f, 0.f); + } + + float v_cur = g.DragCurrentValue; + const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f); + if (fabsf(mouse_drag_delta.x - g.DragLastMouseDelta.x) > 0.0f) + { + float speed = v_speed; + if (speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX) + speed = (v_max - v_min) * g.DragSpeedDefaultRatio; + if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f) + speed = speed * g.DragSpeedScaleFast; + if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f) + speed = speed * g.DragSpeedScaleSlow; + + float delta = (mouse_drag_delta.x - g.DragLastMouseDelta.x) * speed; + if (fabsf(power - 1.0f) > 0.001f) + { + // Logarithmic curve on both side of 0.0 + float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur; + float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f; + float v1 = powf(v0_abs, 1.0f / power) + (delta * v0_sign); + float v1_abs = v1 >= 0.0f ? v1 : -v1; + float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line + v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign + } + else + { + v_cur += delta; + } + g.DragLastMouseDelta.x = mouse_drag_delta.x; + + // Clamp + if (v_min < v_max) + v_cur = ImClamp(v_cur, v_min, v_max); + g.DragCurrentValue = v_cur; + } + + // Round to user desired precision, then apply + v_cur = RoundScalar(v_cur, decimal_precision); + if (*v != v_cur) + { + *v = v_cur; + value_changed = true; + } + } + else + { + ClearActiveID(); + } + } + + return value_changed; +} + +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w = CalcItemWidth(); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + // NB- we don't call ItemSize() yet because we may turn into a text edit box below + if (!ItemAdd(total_bb, &id)) + { + ItemSize(total_bb, style.FramePadding.y); + return false; + } + + const bool hovered = IsHovered(frame_bb, id); + if (hovered) + SetHoveredID(id); + + if (!display_format) + display_format = "%.3f"; + int decimal_precision = ParseFormatPrecision(display_format, 3); + + // Tabbing or CTRL-clicking on Drag turns it into an input box + bool start_text_input = false; + const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id); + if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] | g.IO.MouseDoubleClicked[0]))) + { + SetActiveID(id, window); + FocusWindow(window); + + if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0]) + { + start_text_input = true; + g.ScalarAsInputTextId = 0; + } + } + if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) + return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); + + // Actual drag behavior + ItemSize(total_bb, style.FramePadding.y); + const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + char value_buf[64]; + const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); + + return value_changed; +} + +bool ImGui::DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power); +} + +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power); +} + +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_format, power); +} + +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* display_format, const char* display_format_max, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2); + + bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format, power); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, display_format_max ? display_format_max : display_format, power); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); + + return value_changed; +} + +// NB: v_speed is float to allow adjusting the drag speed with more precision +bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* display_format) +{ + if (!display_format) + display_format = "%.0f"; + float v_f = (float)*v; + bool value_changed = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format); + *v = (int)v_f; + return value_changed; +} + +bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= DragInt("##v", &v[i], v_speed, v_min, v_max, display_format); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format) +{ + return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format); +} + +bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format) +{ + return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format); +} + +bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format) +{ + return DragIntN(label, v, 4, v_speed, v_min, v_max, display_format); +} + +bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* display_format, const char* display_format_max) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2); + + bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, display_format_max ? display_format_max : display_format); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); + + return value_changed; +} + +void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + if (graph_size.x == 0.0f) + graph_size.x = CalcItemWidth(); + if (graph_size.y == 0.0f) + graph_size.y = label_size.y + (style.FramePadding.y * 2); + + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y)); + const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, NULL)) + return; + + // Determine scale from values if not specified + if (scale_min == FLT_MAX || scale_max == FLT_MAX) + { + float v_min = FLT_MAX; + float v_max = -FLT_MAX; + for (int i = 0; i < values_count; i++) + { + const float v = values_getter(data, i); + v_min = ImMin(v_min, v); + v_max = ImMax(v_max, v); + } + if (scale_min == FLT_MAX) + scale_min = v_min; + if (scale_max == FLT_MAX) + scale_max = v_max; + } + + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + + if (values_count > 0) + { + int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + + // Tooltip on hover + int v_hovered = -1; + if (IsHovered(inner_bb, 0)) + { + const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f); + const int v_idx = (int)(t * item_count); + IM_ASSERT(v_idx >= 0 && v_idx < values_count); + + const float v0 = values_getter(data, (v_idx + values_offset) % values_count); + const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); + if (plot_type == ImGuiPlotType_Lines) + SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); + else if (plot_type == ImGuiPlotType_Histogram) + SetTooltip("%d: %8.4g", v_idx, v0); + v_hovered = v_idx; + } + + const float t_step = 1.0f / (float)res_w; + + float v0 = values_getter(data, (0 + values_offset) % values_count); + float t0 = 0.0f; + ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle + + const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); + const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); + + for (int n = 0; n < res_w; n++) + { + const float t1 = t0 + t_step; + const int v1_idx = (int)(t0 * item_count + 0.5f); + IM_ASSERT(v1_idx >= 0 && v1_idx < values_count); + const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count); + const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) ); + + // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. + ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0); + ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, 1.0f)); + if (plot_type == ImGuiPlotType_Lines) + { + window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); + } + else if (plot_type == ImGuiPlotType_Histogram) + { + if (pos1.x >= pos0.x + 2.0f) + pos1.x -= 1.0f; + window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); + } + + t0 = t1; + tp0 = tp1; + } + } + + // Text overlay + if (overlay_text) + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); +} + +struct ImGuiPlotArrayGetterData +{ + const float* Values; + int Stride; + + ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; } +}; + +static float Plot_ArrayGetter(void* data, int idx) +{ + ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data; + const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride); + return v; +} + +void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) +{ + ImGuiPlotArrayGetterData data(values, stride); + PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) +{ + ImGuiPlotArrayGetterData data(values, stride); + PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +// size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size +void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f)); + ItemSize(bb, style.FramePadding.y); + if (!ItemAdd(bb, NULL)) + return; + + // Render + fraction = ImSaturate(fraction); + RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + bb.Reduce(ImVec2(window->BorderSize, window->BorderSize)); + const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y); + RenderFrame(bb.Min, fill_br, GetColorU32(ImGuiCol_PlotHistogram), false, style.FrameRounding); + + // Default displaying the fraction as percentage string, but user can override it + char overlay_buf[32]; + if (!overlay) + { + ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f); + overlay = overlay_buf; + } + + ImVec2 overlay_size = CalcTextSize(overlay, NULL); + if (overlay_size.x > 0.0f) + RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb); +} + +bool ImGui::Checkbox(const char* label, bool* v) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2, label_size.y + style.FramePadding.y*2)); + ItemSize(check_bb, style.FramePadding.y); + + ImRect total_bb = check_bb; + if (label_size.x > 0) + SameLine(0, style.ItemInnerSpacing.x); + const ImRect text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + label_size); + if (label_size.x > 0) + { + ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); + total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max)); + } + + if (!ItemAdd(total_bb, &id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); + if (pressed) + *v = !(*v); + + RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); + if (*v) + { + const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); + const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); + window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), style.FrameRounding); + } + + if (g.LogEnabled) + LogRenderedText(text_bb.GetTL(), *v ? "[x]" : "[ ]"); + if (label_size.x > 0.0f) + RenderText(text_bb.GetTL(), label); + + return pressed; +} + +bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) +{ + bool v = ((*flags & flags_value) == flags_value); + bool pressed = Checkbox(label, &v); + if (pressed) + { + if (v) + *flags |= flags_value; + else + *flags &= ~flags_value; + } + + return pressed; +} + +bool ImGui::RadioButton(const char* label, bool active) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2-1, label_size.y + style.FramePadding.y*2-1)); + ItemSize(check_bb, style.FramePadding.y); + + ImRect total_bb = check_bb; + if (label_size.x > 0) + SameLine(0, style.ItemInnerSpacing.x); + const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size); + if (label_size.x > 0) + { + ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); + total_bb.Add(text_bb); + } + + if (!ItemAdd(total_bb, &id)) + return false; + + ImVec2 center = check_bb.GetCenter(); + center.x = (float)(int)center.x + 0.5f; + center.y = (float)(int)center.y + 0.5f; + const float radius = check_bb.GetHeight() * 0.5f; + + bool hovered, held; + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); + + window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); + if (active) + { + const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); + const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); + window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16); + } + + if (window->Flags & ImGuiWindowFlags_ShowBorders) + { + window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16); + window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16); + } + + if (g.LogEnabled) + LogRenderedText(text_bb.GetTL(), active ? "(x)" : "( )"); + if (label_size.x > 0.0f) + RenderText(text_bb.GetTL(), label); + + return pressed; +} + +bool ImGui::RadioButton(const char* label, int* v, int v_button) +{ + const bool pressed = RadioButton(label, *v == v_button); + if (pressed) + { + *v = v_button; + } + return pressed; +} + +static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) +{ + int line_count = 0; + const char* s = text_begin; + while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding + if (c == '\n') + line_count++; + s--; + if (s[0] != '\n' && s[0] != '\r') + line_count++; + *out_text_end = s; + return line_count; +} + +static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line) +{ + ImFont* font = GImGui->Font; + const float line_height = GImGui->FontSize; + const float scale = line_height / font->FontSize; + + ImVec2 text_size = ImVec2(0,0); + float line_width = 0.0f; + + const ImWchar* s = text_begin; + while (s < text_end) + { + unsigned int c = (unsigned int)(*s++); + if (c == '\n') + { + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + if (stop_on_new_line) + break; + continue; + } + if (c == '\r') + continue; + + const float char_width = font->GetCharAdvance((unsigned short)c) * scale; + line_width += char_width; + } + + if (text_size.x < line_width) + text_size.x = line_width; + + if (out_offset) + *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n + + if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n + text_size.y += line_height; + + if (remaining) + *remaining = s; + + return text_size; +} + +// Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) +namespace ImGuiStb +{ + +static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; } +static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; } +static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->Text[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); } +static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; } +static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; +static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx) +{ + const ImWchar* text = obj->Text.Data; + const ImWchar* text_remaining = NULL; + const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true); + r->x0 = 0.0f; + r->x1 = size.x; + r->baseline_y_delta = size.y; + r->ymin = 0.0f; + r->ymax = size.y; + r->num_chars = (int)(text_remaining - (text + line_start_idx)); +} + +static bool is_separator(unsigned int c) { return ImCharIsSpace(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } +static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->Text[idx-1] ) && !is_separator( obj->Text[idx] ) ) : 1; } +static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; } +#ifdef __APPLE__ // FIXME: Move setting to IO structure +static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->Text[idx-1] ) && is_separator( obj->Text[idx] ) ) : 1; } +static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; } +#else +static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; } +#endif +#define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h +#define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL + +static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n) +{ + ImWchar* dst = obj->Text.Data + pos; + + // We maintain our buffer length in both UTF-8 and wchar formats + obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n); + obj->CurLenW -= n; + + // Offset remaining text + const ImWchar* src = obj->Text.Data + pos + n; + while (ImWchar c = *src++) + *dst++ = c; + *dst = '\0'; +} + +static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len) +{ + const int text_len = obj->CurLenW; + IM_ASSERT(pos <= text_len); + if (new_text_len + text_len + 1 > obj->Text.Size) + return false; + + const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len); + if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA) + return false; + + ImWchar* text = obj->Text.Data; + if (pos != text_len) + memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar)); + memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); + + obj->CurLenW += new_text_len; + obj->CurLenA += new_text_len_utf8; + obj->Text[obj->CurLenW] = '\0'; + + return true; +} + +// We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols) +#define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left +#define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right +#define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up +#define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down +#define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line +#define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line +#define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text +#define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text +#define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor +#define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor +#define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo +#define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo +#define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word +#define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word +#define STB_TEXTEDIT_K_SHIFT 0x20000 + +#define STB_TEXTEDIT_IMPLEMENTATION +#include "stb_textedit.h" + +} + +void ImGuiTextEditState::OnKeyPressed(int key) +{ + stb_textedit_key(this, &StbState, key); + CursorFollow = true; + CursorAnimReset(); +} + +// Public API to manipulate UTF-8 text +// We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar) +// FIXME: The existence of this rarely exercised code path is a bit of a nuisance. +void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count) +{ + IM_ASSERT(pos + bytes_count <= BufTextLen); + char* dst = Buf + pos; + const char* src = Buf + pos + bytes_count; + while (char c = *src++) + *dst++ = c; + *dst = '\0'; + + if (CursorPos + bytes_count >= pos) + CursorPos -= bytes_count; + else if (CursorPos >= pos) + CursorPos = pos; + SelectionStart = SelectionEnd = CursorPos; + BufDirty = true; + BufTextLen -= bytes_count; +} + +void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) +{ + const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text); + if (new_text_len + BufTextLen + 1 >= BufSize) + return; + + if (BufTextLen != pos) + memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos)); + memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char)); + Buf[BufTextLen + new_text_len] = '\0'; + + if (CursorPos >= pos) + CursorPos += new_text_len; + SelectionStart = SelectionEnd = CursorPos; + BufDirty = true; + BufTextLen += new_text_len; +} + +// Return false to discard a character. +static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +{ + unsigned int c = *p_char; + + if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF))) + { + bool pass = false; + pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline)); + pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput)); + if (!pass) + return false; + } + + if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys. + return false; + + if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank)) + { + if (flags & ImGuiInputTextFlags_CharsDecimal) + if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/')) + return false; + + if (flags & ImGuiInputTextFlags_CharsHexadecimal) + if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) + return false; + + if (flags & ImGuiInputTextFlags_CharsUppercase) + if (c >= 'a' && c <= 'z') + *p_char = (c += (unsigned int)('A'-'a')); + + if (flags & ImGuiInputTextFlags_CharsNoBlank) + if (ImCharIsSpace(c)) + return false; + } + + if (flags & ImGuiInputTextFlags_CallbackCharFilter) + { + ImGuiTextEditCallbackData callback_data; + memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); + callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; + callback_data.EventChar = (ImWchar)c; + callback_data.Flags = flags; + callback_data.UserData = user_data; + if (callback(&callback_data) != 0) + return false; + *p_char = callback_data.EventChar; + if (!callback_data.EventChar) + return false; + } + + return true; +} + +// Edit a string of text +// NB: when active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while active has no effect. +// FIXME: Rather messy function partly because we are doing UTF8 > u16 > UTF8 conversions on the go to more easily handle stb_textedit calls. Ideally we should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188 +bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) + + ImGuiContext& g = *GImGui; + const ImGuiIO& io = g.IO; + const ImGuiStyle& style = g.Style; + + const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; + const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0; + const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; + + if (is_multiline) // Open group before calling GetID() because groups tracks id created during their spawn + BeginGroup(); + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f)); + + ImGuiWindow* draw_window = window; + if (is_multiline) + { + if (!BeginChildFrame(id, frame_bb.GetSize())) + { + EndChildFrame(); + EndGroup(); + return false; + } + draw_window = GetCurrentWindow(); + size.x -= draw_window->ScrollbarSizes.x; + } + else + { + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, &id)) + return false; + } + + // Password pushes a temporary font with only a fallback glyph + if (is_password) + { + const ImFont::Glyph* glyph = g.Font->FindGlyph('*'); + ImFont* password_font = &g.InputTextPasswordFont; + password_font->FontSize = g.Font->FontSize; + password_font->Scale = g.Font->Scale; + password_font->DisplayOffset = g.Font->DisplayOffset; + password_font->Ascent = g.Font->Ascent; + password_font->Descent = g.Font->Descent; + password_font->ContainerAtlas = g.Font->ContainerAtlas; + password_font->FallbackGlyph = glyph; + password_font->FallbackXAdvance = glyph->XAdvance; + IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexXAdvance.empty() && password_font->IndexLookup.empty()); + PushFont(password_font); + } + + // NB: we are only allowed to access 'edit_state' if we are the active widget. + ImGuiTextEditState& edit_state = g.InputTextState; + + const bool focus_requested = FocusableItemRegister(window, g.ActiveId == id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing + const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent); + const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; + + const bool hovered = IsHovered(frame_bb, id); + if (hovered) + { + SetHoveredID(id); + g.MouseCursor = ImGuiMouseCursor_TextInput; + } + const bool user_clicked = hovered && io.MouseClicked[0]; + const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY"); + + bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0; + if (focus_requested || user_clicked || user_scrolled) + { + if (g.ActiveId != id) + { + // Start edition + // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) + // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) + const int prev_len_w = edit_state.CurLenW; + edit_state.Text.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash. + edit_state.InitialText.resize(buf_size+1); // UTF-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash. + ImStrncpy(edit_state.InitialText.Data, buf, edit_state.InitialText.Size); + const char* buf_end = NULL; + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end); + edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. + edit_state.CursorAnimReset(); + + // Preserve cursor position and undo/redo stack if we come back to same widget + // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar). + const bool recycle_state = (edit_state.Id == id) && (prev_len_w == edit_state.CurLenW); + if (recycle_state) + { + // Recycle existing cursor/selection/undo stack but clamp position + // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. + edit_state.CursorClamp(); + } + else + { + edit_state.Id = id; + edit_state.ScrollX = 0.0f; + stb_textedit_initialize_state(&edit_state.StbState, !is_multiline); + if (!is_multiline && focus_requested_by_code) + select_all = true; + } + if (flags & ImGuiInputTextFlags_AlwaysInsertMode) + edit_state.StbState.insert_mode = true; + if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl))) + select_all = true; + } + SetActiveID(id, window); + FocusWindow(window); + } + else if (io.MouseClicked[0]) + { + // Release focus when we click outside + if (g.ActiveId == id) + ClearActiveID(); + } + + bool value_changed = false; + bool enter_pressed = false; + + if (g.ActiveId == id) + { + if (!is_editable && !g.ActiveIdIsJustActivated) + { + // When read-only we always use the live data passed to the function + edit_state.Text.resize(buf_size+1); + const char* buf_end = NULL; + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end); + edit_state.CurLenA = (int)(buf_end - buf); + edit_state.CursorClamp(); + } + + edit_state.BufSizeA = buf_size; + + // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. + // Down the line we should have a cleaner library-wide concept of Selected vs Active. + g.ActiveIdAllowOverlap = !io.MouseDown[0]; + + // Edit in progress + const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX; + const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f)); + + const bool osx_double_click_selects_words = io.OSXBehaviors; // OS X style: Double click selects by word instead of selecting whole text + if (select_all || (hovered && !osx_double_click_selects_words && io.MouseDoubleClicked[0])) + { + edit_state.SelectAll(); + edit_state.SelectedAllMouseLock = true; + } + else if (hovered && osx_double_click_selects_words && io.MouseDoubleClicked[0]) + { + // Select a word only, OS X style (by simulating keystrokes) + edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT); + edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); + } + else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock) + { + stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y); + edit_state.CursorAnimReset(); + } + else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) + { + stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y); + edit_state.CursorAnimReset(); + edit_state.CursorFollow = true; + } + if (edit_state.SelectedAllMouseLock && !io.MouseDown[0]) + edit_state.SelectedAllMouseLock = false; + + if (io.InputCharacters[0]) + { + // Process text input (before we check for Return because using some IME will effectively send a Return?) + // We ignore CTRL inputs, but need to allow CTRL+ALT as some keyboards (e.g. German) use AltGR - which is Alt+Ctrl - to input certain characters. + if (!(io.KeyCtrl && !io.KeyAlt) && is_editable) + { + for (int n = 0; n < IM_ARRAYSIZE(io.InputCharacters) && io.InputCharacters[n]; n++) + if (unsigned int c = (unsigned int)io.InputCharacters[n]) + { + // Insert character if they pass filtering + if (!InputTextFilterCharacter(&c, flags, callback, user_data)) + continue; + edit_state.OnKeyPressed((int)c); + } + } + + // Consume characters + memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); + } + + // Handle various key-presses + bool cancel_edit = false; + const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); + const bool is_shortcut_key_only = (io.OSXBehaviors ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl + const bool is_wordmove_key_down = io.OSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl + const bool is_startend_key_down = io.OSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End + + if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable) + { + if (!edit_state.HasSelection()) + { + if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT); + else if (io.OSXBehaviors && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT); + } + edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); + } + else if (IsKeyPressedMap(ImGuiKey_Enter)) + { + bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; + if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl)) + { + ClearActiveID(); + enter_pressed = true; + } + else if (is_editable) + { + unsigned int c = '\n'; // Insert new line + if (InputTextFilterCharacter(&c, flags, callback, user_data)) + edit_state.OnKeyPressed((int)c); + } + } + else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable) + { + unsigned int c = '\t'; // Insert TAB + if (InputTextFilterCharacter(&c, flags, callback, user_data)) + edit_state.OnKeyPressed((int)c); + } + else if (IsKeyPressedMap(ImGuiKey_Escape)) { ClearActiveID(); cancel_edit = true; } + else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); } + else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); } + else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; } + else if (is_shortcut_key_only && !is_password && ((IsKeyPressedMap(ImGuiKey_X) && is_editable) || IsKeyPressedMap(ImGuiKey_C)) && (!is_multiline || edit_state.HasSelection())) + { + // Cut, Copy + const bool cut = IsKeyPressedMap(ImGuiKey_X); + if (cut && !edit_state.HasSelection()) + edit_state.SelectAll(); + + if (io.SetClipboardTextFn) + { + const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0; + const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW; + edit_state.TempTextBuffer.resize((ie-ib) * 4 + 1); + ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data+ib, edit_state.Text.Data+ie); + SetClipboardText(edit_state.TempTextBuffer.Data); + } + + if (cut) + { + edit_state.CursorFollow = true; + stb_textedit_cut(&edit_state, &edit_state.StbState); + } + } + else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V) && is_editable) + { + // Paste + if (const char* clipboard = GetClipboardText()) + { + // Filter pasted buffer + const int clipboard_len = (int)strlen(clipboard); + ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar)); + int clipboard_filtered_len = 0; + for (const char* s = clipboard; *s; ) + { + unsigned int c; + s += ImTextCharFromUtf8(&c, s, NULL); + if (c == 0) + break; + if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, user_data)) + continue; + clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c; + } + clipboard_filtered[clipboard_filtered_len] = 0; + if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation + { + stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len); + edit_state.CursorFollow = true; + } + ImGui::MemFree(clipboard_filtered); + } + } + + if (cancel_edit) + { + // Restore initial value + if (is_editable) + { + ImStrncpy(buf, edit_state.InitialText.Data, buf_size); + value_changed = true; + } + } + else + { + // Apply new value immediately - copy modified buffer back + // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer + // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect. + // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. + if (is_editable) + { + edit_state.TempTextBuffer.resize(edit_state.Text.Size * 4); + ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data, NULL); + } + + // User callback + if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0) + { + IM_ASSERT(callback != NULL); + + // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. + ImGuiInputTextFlags event_flag = 0; + ImGuiKey event_key = ImGuiKey_COUNT; + if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab)) + { + event_flag = ImGuiInputTextFlags_CallbackCompletion; + event_key = ImGuiKey_Tab; + } + else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow)) + { + event_flag = ImGuiInputTextFlags_CallbackHistory; + event_key = ImGuiKey_UpArrow; + } + else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow)) + { + event_flag = ImGuiInputTextFlags_CallbackHistory; + event_key = ImGuiKey_DownArrow; + } + else if (flags & ImGuiInputTextFlags_CallbackAlways) + event_flag = ImGuiInputTextFlags_CallbackAlways; + + if (event_flag) + { + ImGuiTextEditCallbackData callback_data; + memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); + callback_data.EventFlag = event_flag; + callback_data.Flags = flags; + callback_data.UserData = user_data; + callback_data.ReadOnly = !is_editable; + + callback_data.EventKey = event_key; + callback_data.Buf = edit_state.TempTextBuffer.Data; + callback_data.BufTextLen = edit_state.CurLenA; + callback_data.BufSize = edit_state.BufSizeA; + callback_data.BufDirty = false; + + // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188) + ImWchar* text = edit_state.Text.Data; + const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor); + const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start); + const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end); + + // Call user code + callback(&callback_data); + + // Read back what user may have modified + IM_ASSERT(callback_data.Buf == edit_state.TempTextBuffer.Data); // Invalid to modify those fields + IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA); + IM_ASSERT(callback_data.Flags == flags); + if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); + if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); + if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); + if (callback_data.BufDirty) + { + IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, callback_data.Buf, NULL); + edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen() + edit_state.CursorAnimReset(); + } + } + } + + // Copy back to user buffer + if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0) + { + ImStrncpy(buf, edit_state.TempTextBuffer.Data, buf_size); + value_changed = true; + } + } + } + + // Render + // Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on. + const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempTextBuffer.Data : buf; buf = NULL; + + if (!is_multiline) + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + + const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size + ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; + ImVec2 text_size(0.f, 0.f); + const bool is_currently_scrolling = (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetIDNoKeepAlive("#SCROLLY")); + if (g.ActiveId == id || is_currently_scrolling) + { + edit_state.CursorAnim += io.DeltaTime; + + // This is going to be messy. We need to: + // - Display the text (this alone can be more easily clipped) + // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) + // - Measure text height (for scrollbar) + // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) + // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. + const ImWchar* text_begin = edit_state.Text.Data; + ImVec2 cursor_offset, select_start_offset; + + { + // Count lines + find lines numbers straddling 'cursor' and 'select_start' position. + const ImWchar* searches_input_ptr[2]; + searches_input_ptr[0] = text_begin + edit_state.StbState.cursor; + searches_input_ptr[1] = NULL; + int searches_remaining = 1; + int searches_result_line_number[2] = { -1, -999 }; + if (edit_state.StbState.select_start != edit_state.StbState.select_end) + { + searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); + searches_result_line_number[1] = -1; + searches_remaining++; + } + + // Iterate all lines to find our line numbers + // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter. + searches_remaining += is_multiline ? 1 : 0; + int line_count = 0; + for (const ImWchar* s = text_begin; *s != 0; s++) + if (*s == '\n') + { + line_count++; + if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; } + if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; } + } + line_count++; + if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count; + if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count; + + // Calculate 2d position by finding the beginning of the line and measuring distance + cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x; + cursor_offset.y = searches_result_line_number[0] * g.FontSize; + if (searches_result_line_number[1] >= 0) + { + select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x; + select_start_offset.y = searches_result_line_number[1] * g.FontSize; + } + + // Calculate text height + if (is_multiline) + text_size = ImVec2(size.x, line_count * g.FontSize); + } + + // Scroll + if (edit_state.CursorFollow) + { + // Horizontal scroll in chunks of quarter width + if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll)) + { + const float scroll_increment_x = size.x * 0.25f; + if (cursor_offset.x < edit_state.ScrollX) + edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x); + else if (cursor_offset.x - size.x >= edit_state.ScrollX) + edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x); + } + else + { + edit_state.ScrollX = 0.0f; + } + + // Vertical scroll + if (is_multiline) + { + float scroll_y = draw_window->Scroll.y; + if (cursor_offset.y - g.FontSize < scroll_y) + scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); + else if (cursor_offset.y - size.y >= scroll_y) + scroll_y = cursor_offset.y - size.y; + draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag + draw_window->Scroll.y = scroll_y; + render_pos.y = draw_window->DC.CursorPos.y; + } + } + edit_state.CursorFollow = false; + const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f); + + // Draw selection + if (edit_state.StbState.select_start != edit_state.StbState.select_end) + { + const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); + const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end); + + float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. + float bg_offy_dn = is_multiline ? 0.0f : 2.0f; + ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg); + ImVec2 rect_pos = render_pos + select_start_offset - render_scroll; + for (const ImWchar* p = text_selected_begin; p < text_selected_end; ) + { + if (rect_pos.y > clip_rect.w + g.FontSize) + break; + if (rect_pos.y < clip_rect.y) + { + while (p < text_selected_end) + if (*p++ == '\n') + break; + } + else + { + ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true); + if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((unsigned short)' ') * 0.50f); // So we can see selected empty lines + ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn)); + rect.Clip(clip_rect); + if (rect.Overlaps(clip_rect)) + draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); + } + rect_pos.x = render_pos.x - render_scroll.x; + rect_pos.y += g.FontSize; + } + } + + draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect); + + // Draw blinking cursor + bool cursor_is_visible = (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f; + ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll; + ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y-g.FontSize+0.5f, cursor_screen_pos.x+1.0f, cursor_screen_pos.y-1.5f); + if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) + draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); + + // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) + if (is_editable) + g.OsImePosRequest = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize); + } + else + { + // Render text only + const char* buf_end = NULL; + if (is_multiline) + text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width + draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect); + } + + if (is_multiline) + { + Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line + EndChildFrame(); + EndGroup(); + } + + if (is_password) + PopFont(); + + // Log as text + if (g.LogEnabled && !is_password) + LogRenderedText(render_pos, buf_display, NULL); + + if (label_size.x > 0) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0) + return enter_pressed; + else + return value_changed; +} + +bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +{ + IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() + return InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data); +} + +bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +{ + return InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data); +} + +// NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument) +bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + BeginGroup(); + PushID(label); + const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding*2.0f; + if (step_ptr) + PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2)); + + char buf[64]; + DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf)); + + bool value_changed = false; + if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal)) + extra_flags |= ImGuiInputTextFlags_CharsDecimal; + extra_flags |= ImGuiInputTextFlags_AutoSelectAll; + if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags)) // PushId(label) + "" gives us the expected ID from outside point of view + value_changed = DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format); + + // Step buttons + if (step_ptr) + { + PopItemWidth(); + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) + { + DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr); + value_changed = true; + } + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) + { + DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr); + value_changed = true; + } + } + PopID(); + + if (label_size.x > 0) + { + SameLine(0, style.ItemInnerSpacing.x); + RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label); + ItemSize(label_size, style.FramePadding.y); + } + EndGroup(); + + return value_changed; +} + +bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + char display_format[16]; + if (decimal_precision < 0) + strcpy(display_format, "%f"); // Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1 + else + ImFormatString(display_format, IM_ARRAYSIZE(display_format), "%%.%df", decimal_precision); + return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags); +} + +bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags) +{ + // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. + const char* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d"; + return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), scalar_format, extra_flags); +} + +bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + return InputFloatN(label, v, 2, decimal_precision, extra_flags); +} + +bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + return InputFloatN(label, v, 3, decimal_precision, extra_flags); +} + +bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + return InputFloatN(label, v, 4, decimal_precision, extra_flags); +} + +bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= InputInt("##v", &v[i], 0, 0, extra_flags); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags) +{ + return InputIntN(label, v, 2, extra_flags); +} + +bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags) +{ + return InputIntN(label, v, 3, extra_flags); +} + +bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags) +{ + return InputIntN(label, v, 4, extra_flags); +} + +static bool Items_ArrayGetter(void* data, int idx, const char** out_text) +{ + const char* const* items = (const char* const*)data; + if (out_text) + *out_text = items[idx]; + return true; +} + +static bool Items_SingleStringGetter(void* data, int idx, const char** out_text) +{ + // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited. + const char* items_separated_by_zeros = (const char*)data; + int items_count = 0; + const char* p = items_separated_by_zeros; + while (*p) + { + if (idx == items_count) + break; + p += strlen(p) + 1; + items_count++; + } + if (!*p) + return false; + if (out_text) + *out_text = p; + return true; +} + +// Combo box helper allowing to pass an array of strings. +bool ImGui::Combo(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items) +{ + const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items); + return value_changed; +} + +// Combo box helper allowing to pass all items in a single string. +bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items) +{ + int items_count = 0; + const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open + while (*p) + { + p += strlen(p) + 1; + items_count++; + } + bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); + return value_changed; +} + +// Combo box function. +bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w = CalcItemWidth(); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, &id)) + return false; + + const float arrow_size = (g.FontSize + style.FramePadding.x * 2.0f); + const bool hovered = IsHovered(frame_bb, id); + bool popup_open = IsPopupOpen(id); + bool popup_opened_now = false; + + const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f)); + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(popup_open || hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING + RenderCollapseTriangle(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y) + style.FramePadding, true); + + if (*current_item >= 0 && *current_item < items_count) + { + const char* item_text; + if (items_getter(data, *current_item, &item_text)) + RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, item_text, NULL, NULL, ImVec2(0.0f,0.0f)); + } + + if (label_size.x > 0) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + if (hovered) + { + SetHoveredID(id); + if (g.IO.MouseClicked[0]) + { + ClearActiveID(); + if (IsPopupOpen(id)) + { + ClosePopup(id); + } + else + { + FocusWindow(window); + OpenPopup(label); + popup_open = popup_opened_now = true; + } + } + } + + bool value_changed = false; + if (IsPopupOpen(id)) + { + // Size default to hold ~7 items + if (height_in_items < 0) + height_in_items = 7; + + float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3); + float popup_y1 = frame_bb.Max.y; + float popup_y2 = ImClamp(popup_y1 + popup_height, popup_y1, g.IO.DisplaySize.y - style.DisplaySafeAreaPadding.y); + if ((popup_y2 - popup_y1) < ImMin(popup_height, frame_bb.Min.y - style.DisplaySafeAreaPadding.y)) + { + // Position our combo ABOVE because there's more space to fit! (FIXME: Handle in Begin() or use a shared helper. We have similar code in Begin() for popup placement) + popup_y1 = ImClamp(frame_bb.Min.y - popup_height, style.DisplaySafeAreaPadding.y, frame_bb.Min.y); + popup_y2 = frame_bb.Min.y; + } + ImRect popup_rect(ImVec2(frame_bb.Min.x, popup_y1), ImVec2(frame_bb.Max.x, popup_y2)); + SetNextWindowPos(popup_rect.Min); + SetNextWindowSize(popup_rect.GetSize()); + PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); + + const ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0); + if (BeginPopupEx(label, flags)) + { + // Display items + Spacing(); + for (int i = 0; i < items_count; i++) + { + PushID((void*)(intptr_t)i); + const bool item_selected = (i == *current_item); + const char* item_text; + if (!items_getter(data, i, &item_text)) + item_text = "*Unknown item*"; + if (Selectable(item_text, item_selected)) + { + ClearActiveID(); + value_changed = true; + *current_item = i; + } + if (item_selected && popup_opened_now) + SetScrollHere(); + PopID(); + } + EndPopup(); + } + PopStyleVar(); + } + return value_changed; +} + +// Tip: pass an empty label (e.g. "##dummy") then you can use the space to draw other text or image. +// But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID. +bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) + PopClipRect(); + + ImGuiID id = window->GetID(label); + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); + ImVec2 pos = window->DC.CursorPos; + pos.y += window->DC.CurrentLineTextBaseOffset; + ImRect bb(pos, pos + size); + ItemSize(bb); + + // Fill horizontal space. + ImVec2 window_padding = window->WindowPadding; + float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x; + float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x); + ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y); + ImRect bb_with_spacing(pos, pos + size_draw); + if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth)) + bb_with_spacing.Max.x += window_padding.x; + + // Selectables are tightly packed together, we extend the box to cover spacing between selectable. + float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f); + float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f); + float spacing_R = style.ItemSpacing.x - spacing_L; + float spacing_D = style.ItemSpacing.y - spacing_U; + bb_with_spacing.Min.x -= spacing_L; + bb_with_spacing.Min.y -= spacing_U; + bb_with_spacing.Max.x += spacing_R; + bb_with_spacing.Max.y += spacing_D; + if (!ItemAdd(bb_with_spacing, &id)) + { + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) + PushColumnClipRect(); + return false; + } + + ImGuiButtonFlags button_flags = 0; + if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick; + if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnClick|ImGuiButtonFlags_PressedOnRelease; + if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled; + if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; + bool hovered, held; + bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags); + if (flags & ImGuiSelectableFlags_Disabled) + selected = false; + + // Render + if (hovered || selected) + { + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f); + } + + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) + { + PushColumnClipRect(); + bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x); + } + + if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size, ImVec2(0.0f,0.0f)); + if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor(); + + // Automatically close popups + if (pressed && !(flags & ImGuiSelectableFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + CloseCurrentPopup(); + return pressed; +} + +bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) +{ + if (Selectable(label, *p_selected, flags, size_arg)) + { + *p_selected = !*p_selected; + return true; + } + return false; +} + +// Helper to calculate the size of a listbox and display a label on the right. +// Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an empty label "##empty" +bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = GetStyle(); + const ImGuiID id = GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); + ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); + ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); + ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + window->DC.LastItemRect = bb; + + BeginGroup(); + if (label_size.x > 0) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + BeginChildFrame(id, frame_bb.GetSize()); + return true; +} + +bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items) +{ + // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. + // However we don't add +0.40f if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size. + // I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution. + if (height_in_items < 0) + height_in_items = ImMin(items_count, 7); + float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (height_in_items + 0.00f); + + // We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild(). + ImVec2 size; + size.x = 0.0f; + size.y = GetTextLineHeightWithSpacing() * height_in_items_f + GetStyle().ItemSpacing.y; + return ListBoxHeader(label, size); +} + +void ImGui::ListBoxFooter() +{ + ImGuiWindow* parent_window = GetParentWindow(); + const ImRect bb = parent_window->DC.LastItemRect; + const ImGuiStyle& style = GetStyle(); + + EndChildFrame(); + + // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect) + // We call SameLine() to restore DC.CurrentLine* data + SameLine(); + parent_window->DC.CursorPos = bb.Min; + ItemSize(bb, style.FramePadding.y); + EndGroup(); +} + +bool ImGui::ListBox(const char* label, int* current_item, const char* const* items, int items_count, int height_items) +{ + const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items); + return value_changed; +} + +bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) +{ + if (!ListBoxHeader(label, items_count, height_in_items)) + return false; + + // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper. + bool value_changed = false; + ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + { + const bool item_selected = (i == *current_item); + const char* item_text; + if (!items_getter(data, i, &item_text)) + item_text = "*Unknown item*"; + + PushID(i); + if (Selectable(item_text, item_selected)) + { + *current_item = i; + value_changed = true; + } + PopID(); + } + ListBoxFooter(); + return value_changed; +} + +bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + ImVec2 pos = window->DC.CursorPos; + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f); + float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame + float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); + + bool pressed = Selectable(label, false, ImGuiSelectableFlags_MenuItem | ImGuiSelectableFlags_DrawFillAvailWidth | (enabled ? 0 : ImGuiSelectableFlags_Disabled), ImVec2(w, 0.0f)); + if (shortcut_size.x > 0.0f) + { + PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false); + PopStyleColor(); + } + + if (selected) + RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled)); + + return pressed; +} + +bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled) +{ + if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled)) + { + if (p_selected) + *p_selected = !*p_selected; + return true; + } + return false; +} + +bool ImGui::BeginMainMenuBar() +{ + ImGuiContext& g = *GImGui; + SetNextWindowPos(ImVec2(0.0f, 0.0f)); + SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f)); + PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0)); + if (!Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_MenuBar) + || !BeginMenuBar()) + { + End(); + PopStyleVar(2); + return false; + } + g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x; + return true; +} + +void ImGui::EndMainMenuBar() +{ + EndMenuBar(); + End(); + PopStyleVar(2); +} + +bool ImGui::BeginMenuBar() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + if (!(window->Flags & ImGuiWindowFlags_MenuBar)) + return false; + + IM_ASSERT(!window->DC.MenuBarAppending); + BeginGroup(); // Save position + PushID("##menubar"); + ImRect rect = window->MenuBarRect(); + PushClipRect(ImVec2(ImFloor(rect.Min.x+0.5f), ImFloor(rect.Min.y + window->BorderSize + 0.5f)), ImVec2(ImFloor(rect.Max.x+0.5f), ImFloor(rect.Max.y+0.5f)), false); + window->DC.CursorPos = ImVec2(rect.Min.x + window->DC.MenuBarOffsetX, rect.Min.y);// + g.Style.FramePadding.y); + window->DC.LayoutType = ImGuiLayoutType_Horizontal; + window->DC.MenuBarAppending = true; + AlignFirstTextHeightToWidgets(); + return true; +} + +void ImGui::EndMenuBar() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar); + IM_ASSERT(window->DC.MenuBarAppending); + PopClipRect(); + PopID(); + window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x; + window->DC.GroupStack.back().AdvanceCursor = false; + EndGroup(); + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.MenuBarAppending = false; +} + +bool ImGui::BeginMenu(const char* label, bool enabled) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImGuiWindow* backed_focused_window = g.FocusedWindow; + + bool pressed; + bool menu_is_open = IsPopupOpen(id); + bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentMenuSet == window->GetID("##menus")); + if (menuset_is_open) + g.FocusedWindow = window; + + // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu (using FindBestPopupWindowPos). + ImVec2 popup_pos, pos = window->DC.CursorPos; + if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) + { + popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight()); + window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); + PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f); + float w = label_size.x; + pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); + PopStyleVar(); + SameLine(); + window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); + } + else + { + popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y); + float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame + float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); + pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); + if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderCollapseTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), false); + if (!enabled) PopStyleColor(); + } + + bool hovered = enabled && IsHovered(window->DC.LastItemRect, id); + if (menuset_is_open) + g.FocusedWindow = backed_focused_window; + + bool want_open = false, want_close = false; + if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) + { + // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. + bool moving_within_opened_triangle = false; + if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window) + { + if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window) + { + ImRect next_window_rect = next_window->Rect(); + ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta; + ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR(); + ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR(); + float extra = ImClamp(fabsf(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack. + ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues + tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale? + tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f); + moving_within_opened_triangle = ImIsPointInTriangle(g.IO.MousePos, ta, tb, tc); + //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug + } + } + + want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle); + want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed); + } + else if (menu_is_open && pressed && menuset_is_open) // menu-bar: click open menu to close + { + want_close = true; + want_open = menu_is_open = false; + } + else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // menu-bar: first click to open, then hover to open others + want_open = true; + if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' + want_close = true; + if (want_close && IsPopupOpen(id)) + ClosePopupToLevel(GImGui->CurrentPopupStack.Size); + + if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.Size) + { + // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame. + OpenPopup(label); + return false; + } + + menu_is_open |= want_open; + if (want_open) + OpenPopup(label); + + if (menu_is_open) + { + SetNextWindowPos(popup_pos, ImGuiSetCond_Always); + ImGuiWindowFlags flags = ImGuiWindowFlags_ShowBorders | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu); + menu_is_open = BeginPopupEx(label, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + } + + return menu_is_open; +} + +void ImGui::EndMenu() +{ + EndPopup(); +} + +// A little colored square. Return true when clicked. +// FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. +bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID("#colorbutton"); + const float square_size = g.FontSize; + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.y*2, square_size + (small_height ? 0 : style.FramePadding.y*2))); + ItemSize(bb, small_height ? 0.0f : style.FramePadding.y); + if (!ItemAdd(bb, &id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + RenderFrame(bb.Min, bb.Max, GetColorU32(col), outline_border, style.FrameRounding); + + if (hovered) + SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, IM_F32_TO_INT8_SAT(col.x), IM_F32_TO_INT8_SAT(col.y), IM_F32_TO_INT8_SAT(col.z), IM_F32_TO_INT8_SAT(col.w)); + + return pressed; +} + +bool ImGui::ColorEdit3(const char* label, float col[3]) +{ + float col4[4]; + col4[0] = col[0]; + col4[1] = col[1]; + col4[2] = col[2]; + col4[3] = 1.0f; + const bool value_changed = ColorEdit4(label, col4, false); + col[0] = col4[0]; + col[1] = col4[1]; + col[2] = col4[2]; + return value_changed; +} + +// Edit colors components (each component in 0.0f..1.0f range +// Use CTRL-Click to input value and TAB to go to next item. +bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w_full = CalcItemWidth(); + const float square_sz = (g.FontSize + style.FramePadding.y * 2.0f); + + ImGuiColorEditMode edit_mode = window->DC.ColorEditMode; + if (edit_mode == ImGuiColorEditMode_UserSelect || edit_mode == ImGuiColorEditMode_UserSelectShowButton) + edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3; + + float f[4] = { col[0], col[1], col[2], col[3] }; + if (edit_mode == ImGuiColorEditMode_HSV) + ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); + + int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) }; + + int components = alpha ? 4 : 3; + bool value_changed = false; + + BeginGroup(); + PushID(label); + + const bool hsv = (edit_mode == 1); + switch (edit_mode) + { + case ImGuiColorEditMode_RGB: + case ImGuiColorEditMode_HSV: + { + // RGB/HSV 0..255 Sliders + const float w_items_all = w_full - (square_sz + style.ItemInnerSpacing.x); + const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); + + const bool hide_prefix = (w_item_one <= CalcTextSize("M:999").x); + const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; + const char* fmt_table[3][4] = + { + { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, + { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" }, + { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } + }; + const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[1]; + + PushItemWidth(w_item_one); + for (int n = 0; n < components; n++) + { + if (n > 0) + SameLine(0, style.ItemInnerSpacing.x); + if (n + 1 == components) + PushItemWidth(w_item_last); + value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, 255, fmt[n]); + } + PopItemWidth(); + PopItemWidth(); + } + break; + case ImGuiColorEditMode_HEX: + { + // RGB Hexadecimal Input + const float w_slider_all = w_full - square_sz; + char buf[64]; + if (alpha) + ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", i[0], i[1], i[2], i[3]); + else + ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", i[0], i[1], i[2]); + PushItemWidth(w_slider_all - style.ItemInnerSpacing.x); + if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) + { + value_changed |= true; + char* p = buf; + while (*p == '#' || ImCharIsSpace(*p)) + p++; + i[0] = i[1] = i[2] = i[3] = 0; + if (alpha) + sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned) + else + sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); + } + PopItemWidth(); + } + break; + } + + SameLine(0, style.ItemInnerSpacing.x); + + const ImVec4 col_display(col[0], col[1], col[2], 1.0f); + if (ColorButton(col_display)) + g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! + + // Recreate our own tooltip over's ColorButton() one because we want to display correct alpha here + if (IsItemHovered()) + SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col[0], col[1], col[2], col[3], IM_F32_TO_INT8_SAT(col[0]), IM_F32_TO_INT8_SAT(col[1]), IM_F32_TO_INT8_SAT(col[2]), IM_F32_TO_INT8_SAT(col[3])); + + if (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) + { + SameLine(0, style.ItemInnerSpacing.x); + const char* button_titles[3] = { "RGB", "HSV", "HEX" }; + if (ButtonEx(button_titles[edit_mode], ImVec2(0,0), ImGuiButtonFlags_DontClosePopups)) + g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! + } + + const char* label_display_end = FindRenderedTextEnd(label); + if (label != label_display_end) + { + SameLine(0, (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) ? -1.0f : style.ItemInnerSpacing.x); + TextUnformatted(label, label_display_end); + } + + // Convert back + for (int n = 0; n < 4; n++) + f[n] = i[n] / 255.0f; + if (edit_mode == 1) + ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); + + if (value_changed) + { + col[0] = f[0]; + col[1] = f[1]; + col[2] = f[2]; + if (alpha) + col[3] = f[3]; + } + + PopID(); + EndGroup(); + + return value_changed; +} + +void ImGui::ColorEditMode(ImGuiColorEditMode mode) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ColorEditMode = mode; +} + +// Horizontal separating line. +void ImGui::Separator() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + if (window->DC.ColumnsCount > 1) + PopClipRect(); + + float x1 = window->Pos.x; + float x2 = window->Pos.x + window->Size.x; + if (!window->DC.GroupStack.empty()) + x1 += window->DC.IndentX; + + const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f)); + ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout. + if (!ItemAdd(bb, NULL)) + { + if (window->DC.ColumnsCount > 1) + PushColumnClipRect(); + return; + } + + window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Border)); + + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + LogText(IM_NEWLINE "--------------------------------"); + + if (window->DC.ColumnsCount > 1) + { + PushColumnClipRect(); + window->DC.ColumnsCellMinY = window->DC.CursorPos.y; + } +} + +void ImGui::Spacing() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + ItemSize(ImVec2(0,0)); +} + +void ImGui::Dummy(const ImVec2& size) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(bb); + ItemAdd(bb, NULL); +} + +bool ImGui::IsRectVisible(const ImVec2& size) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size)); +} + +bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); +} + +// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) +void ImGui::BeginGroup() +{ + ImGuiWindow* window = GetCurrentWindow(); + + window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1); + ImGuiGroupData& group_data = window->DC.GroupStack.back(); + group_data.BackupCursorPos = window->DC.CursorPos; + group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; + group_data.BackupIndentX = window->DC.IndentX; + group_data.BackupGroupOffsetX = window->DC.GroupOffsetX; + group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight; + group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset; + group_data.BackupLogLinePosY = window->DC.LogLinePosY; + group_data.BackupActiveIdIsAlive = GImGui->ActiveIdIsAlive; + group_data.AdvanceCursor = true; + + window->DC.GroupOffsetX = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffsetX; + window->DC.IndentX = window->DC.GroupOffsetX; + window->DC.CursorMaxPos = window->DC.CursorPos; + window->DC.CurrentLineHeight = 0.0f; + window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; +} + +void ImGui::EndGroup() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls + + ImGuiGroupData& group_data = window->DC.GroupStack.back(); + + ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos); + group_bb.Max.y -= g.Style.ItemSpacing.y; // Cancel out last vertical spacing because we are adding one ourselves. + group_bb.Max = ImMax(group_bb.Min, group_bb.Max); + + window->DC.CursorPos = group_data.BackupCursorPos; + window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); + window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight; + window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset; + window->DC.IndentX = group_data.BackupIndentX; + window->DC.GroupOffsetX = group_data.BackupGroupOffsetX; + window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; + + if (group_data.AdvanceCursor) + { + window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. + ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset); + ItemAdd(group_bb, NULL); + } + + // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive() will function on the entire group. + // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but if you search for LastItemId you'll notice it is only used in that context. + const bool active_id_within_group = (!group_data.BackupActiveIdIsAlive && g.ActiveIdIsAlive && g.ActiveId && g.ActiveIdWindow->RootWindow == window->RootWindow); + if (active_id_within_group) + window->DC.LastItemId = g.ActiveId; + if (active_id_within_group && g.HoveredId == g.ActiveId) + window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = true; + + window->DC.GroupStack.pop_back(); + + //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // Debug +} + +// Gets back to previous line and continue with horizontal layout +// pos_x == 0 : follow right after previous item +// pos_x != 0 : align to specified x position (relative to window/group left) +// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0 +// spacing_w >= 0 : enforce spacing amount +void ImGui::SameLine(float pos_x, float spacing_w) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + if (pos_x != 0.0f) + { + if (spacing_w < 0.0f) spacing_w = 0.0f; + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffsetX + window->DC.ColumnsOffsetX; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; + } + else + { + if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x; + window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; + } + window->DC.CurrentLineHeight = window->DC.PrevLineHeight; + window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; +} + +void ImGui::NewLine() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + if (window->DC.CurrentLineHeight > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. + ItemSize(ImVec2(0,0)); + else + ItemSize(ImVec2(0.0f, GImGui->FontSize)); +} + +void ImGui::NextColumn() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems || window->DC.ColumnsCount <= 1) + return; + + ImGuiContext& g = *GImGui; + PopItemWidth(); + PopClipRect(); + + window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); + if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount) + { + // Columns 1+ cancel out IndentX + window->DC.ColumnsOffsetX = GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.IndentX + g.Style.ItemSpacing.x; + window->DrawList->ChannelsSetCurrent(window->DC.ColumnsCurrent); + } + else + { + window->DC.ColumnsCurrent = 0; + window->DC.ColumnsOffsetX = 0.0f; + window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY; + window->DrawList->ChannelsSetCurrent(0); + } + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); + window->DC.CursorPos.y = window->DC.ColumnsCellMinY; + window->DC.CurrentLineHeight = 0.0f; + window->DC.CurrentLineTextBaseOffset = 0.0f; + + PushColumnClipRect(); + PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup +} + +int ImGui::GetColumnIndex() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.ColumnsCurrent; +} + +int ImGui::GetColumnsCount() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.ColumnsCount; +} + +static float GetDraggedColumnOffset(int column_index) +{ + // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing + // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. + ImGuiContext& g = *GImGui; + ImGuiWindow* window = ImGui::GetCurrentWindowRead(); + IM_ASSERT(column_index > 0); // We cannot drag column 0. If you get this assert you may have a conflict between the ID of your columns and another widgets. + IM_ASSERT(g.ActiveId == window->DC.ColumnsSetId + ImGuiID(column_index)); + + float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x - window->Pos.x; + x = ImClamp(x, ImGui::GetColumnOffset(column_index-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(column_index+1)-g.Style.ColumnsMinSpacing); + + return (float)(int)x; +} + +float ImGui::GetColumnOffset(int column_index) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); + if (column_index < 0) + column_index = window->DC.ColumnsCurrent; + + if (g.ActiveId) + { + const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); + if (g.ActiveId == column_id) + return GetDraggedColumnOffset(column_index); + } + + IM_ASSERT(column_index < window->DC.ColumnsData.Size); + const float t = window->DC.ColumnsData[column_index].OffsetNorm; + const float x_offset = window->DC.ColumnsMinX + t * (window->DC.ColumnsMaxX - window->DC.ColumnsMinX); + return (float)(int)x_offset; +} + +void ImGui::SetColumnOffset(int column_index, float offset) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (column_index < 0) + column_index = window->DC.ColumnsCurrent; + + IM_ASSERT(column_index < window->DC.ColumnsData.Size); + const float t = (offset - window->DC.ColumnsMinX) / (window->DC.ColumnsMaxX - window->DC.ColumnsMinX); + window->DC.ColumnsData[column_index].OffsetNorm = t; + + const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); + window->DC.StateStorage->SetFloat(column_id, t); +} + +float ImGui::GetColumnWidth(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + if (column_index < 0) + column_index = window->DC.ColumnsCurrent; + + float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index); + return w; +} + +static void PushColumnClipRect(int column_index) +{ + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (column_index < 0) + column_index = window->DC.ColumnsCurrent; + + float x1 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index) - 1.0f); + float x2 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1.0f); + ImGui::PushClipRect(ImVec2(x1,-FLT_MAX), ImVec2(x2,+FLT_MAX), true); +} + +void ImGui::Columns(int columns_count, const char* id, bool border) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(columns_count >= 1); + + if (window->DC.ColumnsCount != 1) + { + if (window->DC.ColumnsCurrent != 0) + ItemSize(ImVec2(0,0)); // Advance to column 0 + PopItemWidth(); + PopClipRect(); + window->DrawList->ChannelsMerge(); + + window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); + window->DC.CursorPos.y = window->DC.ColumnsCellMaxY; + } + + // Draw columns borders and handle resize at the time of "closing" a columns set + if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1 && window->DC.ColumnsShowBorders && !window->SkipItems) + { + const float y1 = window->DC.ColumnsStartPosY; + const float y2 = window->DC.CursorPos.y; + for (int i = 1; i < window->DC.ColumnsCount; i++) + { + float x = window->Pos.x + GetColumnOffset(i); + const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(i); + const ImRect column_rect(ImVec2(x-4,y1),ImVec2(x+4,y2)); + if (IsClippedEx(column_rect, &column_id, false)) + continue; + + bool hovered, held; + ButtonBehavior(column_rect, column_id, &hovered, &held); + if (hovered || held) + g.MouseCursor = ImGuiMouseCursor_ResizeEW; + + // Draw before resize so our items positioning are in sync with the line being drawn + const ImU32 col = GetColorU32(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column); + const float xi = (float)(int)x; + window->DrawList->AddLine(ImVec2(xi, y1+1.0f), ImVec2(xi, y2), col); + + if (held) + { + if (g.ActiveIdIsJustActivated) + g.ActiveIdClickOffset.x -= 4; // Store from center of column line (we used a 8 wide rect for columns clicking) + x = GetDraggedColumnOffset(i); + SetColumnOffset(i, x); + } + } + } + + // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. + // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. + PushID(0x11223347 + (id ? 0 : columns_count)); + window->DC.ColumnsSetId = window->GetID(id ? id : "columns"); + PopID(); + + // Set state for first column + window->DC.ColumnsCurrent = 0; + window->DC.ColumnsCount = columns_count; + window->DC.ColumnsShowBorders = border; + + const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : window->Size.x; + window->DC.ColumnsMinX = window->DC.IndentX; // Lock our horizontal range + window->DC.ColumnsMaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x; + window->DC.ColumnsStartPosY = window->DC.CursorPos.y; + window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y; + window->DC.ColumnsOffsetX = 0.0f; + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); + + if (window->DC.ColumnsCount != 1) + { + // Cache column offsets + window->DC.ColumnsData.resize(columns_count + 1); + for (int column_index = 0; column_index < columns_count + 1; column_index++) + { + const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); + KeepAliveID(column_id); + const float default_t = column_index / (float)window->DC.ColumnsCount; + const float t = window->DC.StateStorage->GetFloat(column_id, default_t); // Cheaply store our floating point value inside the integer (could store a union into the map?) + window->DC.ColumnsData[column_index].OffsetNorm = t; + } + window->DrawList->ChannelsSplit(window->DC.ColumnsCount); + PushColumnClipRect(); + PushItemWidth(GetColumnWidth() * 0.65f); + } + else + { + window->DC.ColumnsData.resize(0); + } +} + +void ImGui::Indent(float indent_w) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->DC.IndentX += (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX; +} + +void ImGui::Unindent(float indent_w) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->DC.IndentX -= (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX; +} + +void ImGui::TreePush(const char* str_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + PushID(str_id ? str_id : "#TreePush"); +} + +void ImGui::TreePush(const void* ptr_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + PushID(ptr_id ? ptr_id : (const void*)"#TreePush"); +} + +void ImGui::TreePushRawID(ImGuiID id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + window->IDStack.push_back(id); +} + +void ImGui::TreePop() +{ + ImGuiWindow* window = GetCurrentWindow(); + Unindent(); + window->DC.TreeDepth--; + PopID(); +} + +void ImGui::Value(const char* prefix, bool b) +{ + Text("%s: %s", prefix, (b ? "true" : "false")); +} + +void ImGui::Value(const char* prefix, int v) +{ + Text("%s: %d", prefix, v); +} + +void ImGui::Value(const char* prefix, unsigned int v) +{ + Text("%s: %d", prefix, v); +} + +void ImGui::Value(const char* prefix, float v, const char* float_format) +{ + if (float_format) + { + char fmt[64]; + ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format); + Text(fmt, prefix, v); + } + else + { + Text("%s: %.3f", prefix, v); + } +} + +// FIXME: May want to remove those helpers? +void ImGui::ValueColor(const char* prefix, const ImVec4& v) +{ + Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w); + SameLine(); + ColorButton(v, true); +} + +void ImGui::ValueColor(const char* prefix, ImU32 v) +{ + Text("%s: %08X", prefix, v); + SameLine(); + ColorButton(ColorConvertU32ToFloat4(v), true); +} + +//----------------------------------------------------------------------------- +// PLATFORM DEPENDENT HELPERS +//----------------------------------------------------------------------------- + +#if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS)) +#undef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#include +#endif + +// Win32 API clipboard implementation +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) + +#ifdef _MSC_VER +#pragma comment(lib, "user32") +#endif + +static const char* GetClipboardTextFn_DefaultImpl(void*) +{ + static ImVector buf_local; + buf_local.clear(); + if (!OpenClipboard(NULL)) + return NULL; + HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT); + if (wbuf_handle == NULL) + return NULL; + if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle)) + { + int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1; + buf_local.resize(buf_len); + ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL); + } + GlobalUnlock(wbuf_handle); + CloseClipboard(); + return buf_local.Data; +} + +static void SetClipboardTextFn_DefaultImpl(void*, const char* text) +{ + if (!OpenClipboard(NULL)) + return; + const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1; + HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); + if (wbuf_handle == NULL) + return; + ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle); + ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL); + GlobalUnlock(wbuf_handle); + EmptyClipboard(); + SetClipboardData(CF_UNICODETEXT, wbuf_handle); + CloseClipboard(); +} + +#else + +// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers +static const char* GetClipboardTextFn_DefaultImpl(void*) +{ + return GImGui->PrivateClipboard; +} + +// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers +static void SetClipboardTextFn_DefaultImpl(void*, const char* text) +{ + ImGuiContext& g = *GImGui; + if (g.PrivateClipboard) + { + ImGui::MemFree(g.PrivateClipboard); + g.PrivateClipboard = NULL; + } + const char* text_end = text + strlen(text); + g.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1); + memcpy(g.PrivateClipboard, text, (size_t)(text_end - text)); + g.PrivateClipboard[(int)(text_end - text)] = 0; +} + +#endif + +// Win32 API IME support (for Asian languages, etc.) +#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS) + +#include +#ifdef _MSC_VER +#pragma comment(lib, "imm32") +#endif + +static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) +{ + // Notify OS Input Method Editor of text input position + if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle) + if (HIMC himc = ImmGetContext(hwnd)) + { + COMPOSITIONFORM cf; + cf.ptCurrentPos.x = x; + cf.ptCurrentPos.y = y; + cf.dwStyle = CFS_FORCE_POSITION; + ImmSetCompositionWindow(himc, &cf); + } +} + +#else + +static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} + +#endif + +//----------------------------------------------------------------------------- +// HELP +//----------------------------------------------------------------------------- + +void ImGui::ShowMetricsWindow(bool* p_open) +{ + if (ImGui::Begin("ImGui Metrics", p_open)) + { + ImGui::Text("ImGui %s", ImGui::GetVersion()); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3); + ImGui::Text("%d allocations", ImGui::GetIO().MetricsAllocs); + static bool show_clip_rects = true; + ImGui::Checkbox("Show clipping rectangles when hovering a ImDrawCmd", &show_clip_rects); + ImGui::Separator(); + + struct Funcs + { + static void NodeDrawList(ImDrawList* draw_list, const char* label) + { + bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); + if (draw_list == ImGui::GetWindowDrawList()) + { + ImGui::SameLine(); + ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) + if (node_open) ImGui::TreePop(); + return; + } + if (!node_open) + return; + + ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list + overlay_draw_list->PushClipRectFullScreen(); + int elem_offset = 0; + for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++) + { + if (pcmd->UserCallback) + { + ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); + continue; + } + ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; + bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %-4d %s vtx, tex = %p, clip_rect = (%.0f,%.0f)..(%.0f,%.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); + if (show_clip_rects && ImGui::IsItemHovered()) + { + ImRect clip_rect = pcmd->ClipRect; + ImRect vtxs_rect; + for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++) + vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos); + clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255)); + vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255)); + } + if (!pcmd_node_open) + continue; + ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. + while (clipper.Step()) + for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++) + { + char buf[300], *buf_p = buf; + ImVec2 triangles_pos[3]; + for (int n = 0; n < 3; n++, vtx_i++) + { + ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i]; + triangles_pos[n] = v.pos; + buf_p += sprintf(buf_p, "%s %04d { pos = (%8.2f,%8.2f), uv = (%.6f,%.6f), col = %08X }\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); + } + ImGui::Selectable(buf, false); + if (ImGui::IsItemHovered()) + overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f, false); // Add triangle without AA, more readable for large-thin triangle + } + ImGui::TreePop(); + } + overlay_draw_list->PopClipRect(); + ImGui::TreePop(); + } + + static void NodeWindows(ImVector& windows, const char* label) + { + if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) + return; + for (int i = 0; i < windows.Size; i++) + Funcs::NodeWindow(windows[i], "Window"); + ImGui::TreePop(); + } + + static void NodeWindow(ImGuiWindow* window, const char* label) + { + if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window)) + return; + NodeDrawList(window->DrawList, "DrawList"); + ImGui::BulletText("Pos: (%.1f,%.1f)", window->Pos.x, window->Pos.y); + ImGui::BulletText("Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y); + ImGui::BulletText("Scroll: (%.2f,%.2f)", window->Scroll.x, window->Scroll.y); + if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow"); + if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows"); + ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair)); + ImGui::TreePop(); + } + }; + + ImGuiContext& g = *GImGui; // Access private state + Funcs::NodeWindows(g.Windows, "Windows"); + if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.RenderDrawLists[0].Size)) + { + for (int i = 0; i < g.RenderDrawLists[0].Size; i++) + Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList"); + ImGui::TreePop(); + } + if (ImGui::TreeNode("Popups", "Open Popups Stack (%d)", g.OpenPopupStack.Size)) + { + for (int i = 0; i < g.OpenPopupStack.Size; i++) + { + ImGuiWindow* window = g.OpenPopupStack[i].Window; + ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : ""); + } + ImGui::TreePop(); + } + if (ImGui::TreeNode("Basic state")) + { + ImGui::Text("FocusedWindow: '%s'", g.FocusedWindow ? g.FocusedWindow->Name : "NULL"); + ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); + ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); + ImGui::Text("HoveredID: 0x%08X/0x%08X", g.HoveredId, g.HoveredIdPreviousFrame); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not + ImGui::Text("ActiveID: 0x%08X/0x%08X", g.ActiveId, g.ActiveIdPreviousFrame); + ImGui::TreePop(); + } + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- + +// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. +// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github. +#ifdef IMGUI_INCLUDE_IMGUI_USER_INL +#include "imgui_user.inl" +#endif + +//----------------------------------------------------------------------------- diff --git a/Externals/imgui-1.46/Include/imgui.h b/SampleFramework12/v1.01/ImGui/imgui.h similarity index 67% rename from Externals/imgui-1.46/Include/imgui.h rename to SampleFramework12/v1.01/ImGui/imgui.h index 28e460e..8bca83f 100644 --- a/Externals/imgui-1.46/Include/imgui.h +++ b/SampleFramework12/v1.01/ImGui/imgui.h @@ -1,5 +1,5 @@ -// ImGui library v1.46 -// Headers +// dear imgui, v1.50 +// (headers) // See imgui.cpp file for documentation. // See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code. @@ -14,10 +14,14 @@ #include // FLT_MAX #include // va_list #include // ptrdiff_t, NULL -#include // NULL, malloc, free, qsort, atoi #include // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp -#define IMGUI_VERSION "1.46" +#define IMGUI_VERSION "1.50" + +// Define attributes of all API symbols declarations, e.g. for DLL under Windows. +#ifndef IMGUI_API +#define IMGUI_API +#endif // Define assertion handler. #ifndef IM_ASSERT @@ -25,50 +29,66 @@ #define IM_ASSERT(_EXPR) assert(_EXPR) #endif -// Define attributes of all API symbols declarations, e.g. for DLL under Windows. -#ifndef IMGUI_API -#define IMGUI_API -#endif - +// Some compilers support applying printf-style warnings to user functions. #if defined(__clang__) || defined(__GNUC__) #define IM_PRINTFARGS(FMT) __attribute__((format(printf, FMT, (FMT+1)))) #else #define IM_PRINTFARGS(FMT) #endif +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" +#endif + // Forward declarations -struct ImDrawCmd; -struct ImDrawList; -struct ImDrawData; -struct ImFont; -struct ImFontAtlas; -struct ImGuiIO; -struct ImGuiStorage; -struct ImGuiStyle; - -typedef unsigned int ImU32; +struct ImDrawChannel; // Temporary storage for outputting drawing commands out of order, used by ImDrawList::ChannelsSplit() +struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call) +struct ImDrawData; // All draw command lists required to render the frame +struct ImDrawList; // A single draw command list (generally one per window) +struct ImDrawVert; // A single vertex (20 bytes by default, override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) +struct ImFont; // Runtime data for a single font within a parent ImFontAtlas +struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF font loader +struct ImFontConfig; // Configuration data when adding a font or merging fonts +struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 +struct ImGuiIO; // Main configuration and I/O between your application and ImGui +struct ImGuiOnceUponAFrame; // Simple helper for running a block of code not more than once a frame, used by IMGUI_ONCE_UPON_A_FRAME macro +struct ImGuiStorage; // Simple custom key value storage +struct ImGuiStyle; // Runtime data for styling/colors +struct ImGuiTextFilter; // Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +struct ImGuiTextBuffer; // Text buffer for logging/accumulating text +struct ImGuiTextEditCallbackData; // Shared state of ImGui::InputText() when using custom ImGuiTextEditCallback (rare/advanced use) +struct ImGuiSizeConstraintCallbackData;// Structure used to constraint window size in custom ways when using custom ImGuiSizeConstraintCallback (rare/advanced use) +struct ImGuiListClipper; // Helper to manually clip large list of items +struct ImGuiContext; // ImGui context (opaque) + +// Typedefs and Enumerations (declared as int for compatibility and to not pollute the top of this file) +typedef unsigned int ImU32; // 32-bit unsigned integer (typically used to store packed colors) +typedef unsigned int ImGuiID; // unique ID used by widgets (typically hashed from a stack of string) typedef unsigned short ImWchar; // character for keyboard input/display -typedef void* ImTextureID; // user data to refer to a texture (e.g. store your texture handle/id) -typedef ImU32 ImGuiID; // unique ID used by widgets (typically hashed from a stack of string) -typedef int ImGuiCol; // enum ImGuiCol_ -typedef int ImGuiStyleVar; // enum ImGuiStyleVar_ -typedef int ImGuiKey; // enum ImGuiKey_ -typedef int ImGuiAlign; // enum ImGuiAlign_ -typedef int ImGuiColorEditMode; // enum ImGuiColorEditMode_ -typedef int ImGuiMouseCursor; // enum ImGuiMouseCursor_ -typedef int ImGuiWindowFlags; // enum ImGuiWindowFlags_ -typedef int ImGuiSetCond; // enum ImGuiSetCond_ -typedef int ImGuiInputTextFlags; // enum ImGuiInputTextFlags_ -typedef int ImGuiSelectableFlags; // enum ImGuiSelectableFlags_ -struct ImGuiTextEditCallbackData; // for advanced uses of InputText() +typedef void* ImTextureID; // user data to identify a texture (this is whatever to you want it to be! read the FAQ about ImTextureID in imgui.cpp) +typedef int ImGuiCol; // a color identifier for styling // enum ImGuiCol_ +typedef int ImGuiStyleVar; // a variable identifier for styling // enum ImGuiStyleVar_ +typedef int ImGuiKey; // a key identifier (ImGui-side enum) // enum ImGuiKey_ +typedef int ImGuiColorEditMode; // color edit mode for ColorEdit*() // enum ImGuiColorEditMode_ +typedef int ImGuiMouseCursor; // a mouse cursor identifier // enum ImGuiMouseCursor_ +typedef int ImGuiWindowFlags; // window flags for Begin*() // enum ImGuiWindowFlags_ +typedef int ImGuiSetCond; // condition flags for Set*() // enum ImGuiSetCond_ +typedef int ImGuiInputTextFlags; // flags for InputText*() // enum ImGuiInputTextFlags_ +typedef int ImGuiSelectableFlags; // flags for Selectable() // enum ImGuiSelectableFlags_ +typedef int ImGuiTreeNodeFlags; // flags for TreeNode*(), Collapsing*() // enum ImGuiTreeNodeFlags_ typedef int (*ImGuiTextEditCallback)(ImGuiTextEditCallbackData *data); +typedef void (*ImGuiSizeConstraintCallback)(ImGuiSizeConstraintCallbackData* data); + +// Others helpers at bottom of the file: +// class ImVector<> // Lightweight std::vector like class. +// IMGUI_ONCE_UPON_A_FRAME // Execute a block of code once per frame only (convenient for creating UI within deep-nested code that runs multiple times) struct ImVec2 { float x, y; ImVec2() { x = y = 0.0f; } ImVec2(float _x, float _y) { x = _x; y = _y; } - #ifdef IM_VEC2_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec2. IM_VEC2_CLASS_EXTRA #endif @@ -79,25 +99,11 @@ struct ImVec4 float x, y, z, w; ImVec4() { x = y = z = w = 0.0f; } ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } - #ifdef IM_VEC4_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec4. IM_VEC4_CLASS_EXTRA #endif }; -// Helpers at bottom of the file: -// - class ImVector<> // Lightweight std::vector like class. -// - IMGUI_ONCE_UPON_A_FRAME // Execute a block of code once per frame only (convenient for creating UI within deep-nested code that runs multiple times) -// - struct ImGuiTextFilter // Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" -// - struct ImGuiTextBuffer // Text buffer for logging/accumulating text -// - struct ImGuiStorage // Custom key value storage (if you need to alter open/close states manually) -// - struct ImGuiTextEditCallbackData // Shared state of ImGui::InputText() when using custom callbacks -// - struct ImGuiListClipper // Helper to manually clip large list of items. -// - struct ImColor // Helper functions to created packed 32-bit RGBA color values -// - struct ImDrawList // Draw command list -// - struct ImFontAtlas // Bake multiple fonts into a single texture, TTF font loader, bake glyphs into bitmap -// - struct ImFont // Single font - // ImGui end-user API // In a namespace so that user can add extra functions in a separate file (e.g. Value() helpers for your vector or common types) namespace ImGui @@ -105,51 +111,50 @@ namespace ImGui // Main IMGUI_API ImGuiIO& GetIO(); IMGUI_API ImGuiStyle& GetStyle(); - IMGUI_API ImDrawData* GetDrawData(); // same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame() - IMGUI_API void NewFrame(); - IMGUI_API void Render(); + IMGUI_API ImDrawData* GetDrawData(); // same value as passed to your io.RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame() + IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until NewFrame()/Render(). + IMGUI_API void Render(); // ends the ImGui frame, finalize rendering data, then call your io.RenderDrawListsFn() function if set. IMGUI_API void Shutdown(); IMGUI_API void ShowUserGuide(); // help block - IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // style editor block - IMGUI_API void ShowTestWindow(bool* opened = NULL); // test window, demonstrate ImGui features - IMGUI_API void ShowMetricsWindow(bool* opened = NULL); // metrics window for debugging imgui + IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // style editor block. you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) + IMGUI_API void ShowTestWindow(bool* p_open = NULL); // test window demonstrating ImGui features + IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // metrics window for debugging ImGui (browse draw commands, individual vertices, window list, etc.) // Window - IMGUI_API bool Begin(const char* name, bool* p_opened = NULL, ImGuiWindowFlags flags = 0); // see .cpp for details. return false when window is collapsed, so you can early out in your code. 'bool* p_opened' creates a widget on the upper-right to close the window (which sets your bool to false). - IMGUI_API bool Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags = 0); // this is the older/longer API. the extra parameters aren't very relevant. call SetNextWindowSize() instead if you want to set a window size. For regular windows, 'size_on_first_use' only applies to the first time EVER the window is created and probably not what you want! maybe obsolete this API eventually. - IMGUI_API void End(); - IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // begin a scrolling region. size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed size. each axis can use a different mode, e.g. ImVec2(0,400). - IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // " + IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // push window to the stack and start appending to it. see .cpp for details. return false when window is collapsed, so you can early out in your code. 'bool* p_open' creates a widget on the upper-right to close the window (which sets your bool to false). + IMGUI_API bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags = 0); // OBSOLETE. this is the older/longer API. the extra parameters aren't very relevant. call SetNextWindowSize() instead if you want to set a window size. For regular windows, 'size_on_first_use' only applies to the first time EVER the window is created and probably not what you want! might obsolete this API eventually. + IMGUI_API void End(); // finish appending to current window, pop it off the window stack. + IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // begin a scrolling region. size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed size. each axis can use a different mode, e.g. ImVec2(0,400). + IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // " IMGUI_API void EndChild(); IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() IMGUI_API float GetContentRegionAvailWidth(); // IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates - IMGUI_API float GetWindowContentRegionWidth(); // + IMGUI_API float GetWindowContentRegionWidth(); // IMGUI_API ImDrawList* GetWindowDrawList(); // get rendering command-list if you want to append your own draw primitives - IMGUI_API ImFont* GetWindowFont(); - IMGUI_API float GetWindowFontSize(); // size (also height in pixels) of current font with current scale applied - IMGUI_API void SetWindowFontScale(float scale); // per-window font scale. Adjust IO.FontGlobalScale if you want to scale all windows IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList api) IMGUI_API ImVec2 GetWindowSize(); // get current window size IMGUI_API float GetWindowWidth(); IMGUI_API float GetWindowHeight(); IMGUI_API bool IsWindowCollapsed(); + IMGUI_API void SetWindowFontScale(float scale); // per-window font scale. Adjust IO.FontGlobalScale if you want to scale all windows IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // set next window position. call before Begin() IMGUI_API void SetNextWindowPosCenter(ImGuiSetCond cond = 0); // set next window position to be centered on screen. call before Begin() IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() + IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply non-trivial programmatic constraints. IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (enforce the range of scrollbars). set axis to 0.0f to leave it automatic. call before Begin() - IMGUI_API void SetNextWindowContentWidth(float width); // set next window content width (enforce the range of horizontal scrollbar). call before Begin() + IMGUI_API void SetNextWindowContentWidth(float width); // set next window content width (enforce the range of horizontal scrollbar). call before Begin() IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // set next window collapsed state. call before Begin() IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin() - IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // set current window position - call within Begin()/End(). may incur tearing - IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // set current window size. set to ImVec2(0,0) to force an auto-fit. may incur tearing - IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // set current window collapsed state - IMGUI_API void SetWindowFocus(); // set current window to be focused / front-most - IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond = 0); // set named window position - call within Begin()/End(). may incur tearing - IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. may incur tearing + IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. + IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. + IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). + IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / front-most. prefer using SetNextWindowFocus(). + IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond = 0); // set named window position. + IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond = 0); // set named window collapsed state IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus. @@ -161,7 +166,7 @@ namespace ImGui IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()] IMGUI_API void SetScrollHere(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. IMGUI_API void SetScrollFromPosY(float pos_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position valid. use GetCursorPos() or GetCursorStartPos()+offset to get valid positions. - IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget + IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use negative 'offset' to access previous widgets. IMGUI_API void SetStateStorage(ImGuiStorage* tree); // replace tree state storage with our own (if you want to manipulate it yourself, typically clear subsection of it) IMGUI_API ImGuiStorage* GetStateStorage(); @@ -173,6 +178,11 @@ namespace ImGui IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); IMGUI_API void PopStyleVar(int count = 1); + IMGUI_API ImFont* GetFont(); // get current font + IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied + IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API + IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier + IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied // Parameters stacks (current window) IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side) @@ -186,21 +196,15 @@ namespace ImGui IMGUI_API void PopButtonRepeat(); // Cursor / Layout - IMGUI_API void BeginGroup(); // lock horizontal starting position. once closing a group it is seen as a single item (so you can use IsItemHovered() on a group, SameLine() between groups, etc. - IMGUI_API void EndGroup(); IMGUI_API void Separator(); // horizontal line - IMGUI_API void SameLine(float local_pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally - IMGUI_API void Spacing(); // add spacing + IMGUI_API void SameLine(float pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally + IMGUI_API void NewLine(); // undo a SameLine() + IMGUI_API void Spacing(); // add vertical spacing IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size - IMGUI_API void Indent(); // move content position toward the right by style.IndentSpacing pixels - IMGUI_API void Unindent(); // move content position back to the left (cancel Indent) - IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border=true); // setup number of columns. use an identifier to distinguish multiple column sets. close with Columns(1). - IMGUI_API void NextColumn(); // next column - IMGUI_API int GetColumnIndex(); // get current column index - IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetcolumnsCount() inclusive. column 0 is usually 0.0f and not resizable unless you call this - IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column - IMGUI_API float GetColumnWidth(int column_index = -1); // column width (== GetColumnOffset(GetColumnIndex()+1) - GetColumnOffset(GetColumnOffset()) - IMGUI_API int GetColumnsCount(); // number of columns (what was passed to Columns()) + IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if >0 + IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if >0 + IMGUI_API void BeginGroup(); // lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) + IMGUI_API void EndGroup(); IMGUI_API ImVec2 GetCursorPos(); // cursor position is relative to window position IMGUI_API float GetCursorPosX(); // " IMGUI_API float GetCursorPosY(); // " @@ -208,16 +212,26 @@ namespace ImGui IMGUI_API void SetCursorPosX(float x); // " IMGUI_API void SetCursorPosY(float y); // " IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position - IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] + IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API) IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize] IMGUI_API void AlignFirstTextHeightToWidgets(); // call once if the first item on the line is a Text() item and you want to vertically lower it to match subsequent (bigger) widgets IMGUI_API float GetTextLineHeight(); // height of font == GetWindowFontSize() IMGUI_API float GetTextLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of text == GetWindowFontSize() + GetStyle().ItemSpacing.y IMGUI_API float GetItemsLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of standard height widgets == GetWindowFontSize() + GetStyle().FramePadding.y*2 + GetStyle().ItemSpacing.y + // Columns + // You can also use SameLine(pos_x) for simplified columning. The columns API is still work-in-progress and rather lacking. + IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); // setup number of columns. use an identifier to distinguish multiple column sets. close with Columns(1). + IMGUI_API void NextColumn(); // next column + IMGUI_API int GetColumnIndex(); // get current column index + IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetcolumnsCount() inclusive. column 0 is usually 0.0f and not resizable unless you call this + IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column + IMGUI_API float GetColumnWidth(int column_index = -1); // column width (== GetColumnOffset(GetColumnIndex()+1) - GetColumnOffset(GetColumnOffset()) + IMGUI_API int GetColumnsCount(); // number of columns (what was passed to Columns()) + // ID scopes // If you are creating widgets in a loop you most likely want to push a unique identifier so ImGui can differentiate them. - // You can also use "##extra" within your widget name to distinguish them from each others. Read the FAQ for more details. + // You can also use the "##foobar" syntax within widget label to distinguish them from each others. Read "A primer on the use of labels/IDs" in the FAQ for more details. IMGUI_API void PushID(const char* str_id); // push identifier into the ID stack. IDs are hash of the *entire* stack! IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); IMGUI_API void PushID(const void* ptr_id); @@ -239,32 +253,33 @@ namespace ImGui IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // doesn't require null terminated string if 'text_end' is specified. no copy done to any bounded stack buffer, recommended for long chunks of text IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_PRINTFARGS(2); // display text+label aligned the same way as value+label widgets IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args); - IMGUI_API void Bullet(); - IMGUI_API void BulletText(const char* fmt, ...) IM_PRINTFARGS(1); + IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses + IMGUI_API void BulletText(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for Bullet()+Text() IMGUI_API void BulletTextV(const char* fmt, va_list args); - IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); - IMGUI_API bool SmallButton(const char* label); + IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button + IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding - IMGUI_API bool CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false); IMGUI_API bool Checkbox(const char* label, bool* v); IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); IMGUI_API bool RadioButton(const char* label, bool active); IMGUI_API bool RadioButton(const char* label, int* v, int v_button); - IMGUI_API bool Combo(const char* label, int* current_item, const char** items, int items_count, int height_in_items = -1); + IMGUI_API bool Combo(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items = -1); IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items = -1); // separate items with \0, end item-list with \0\0 IMGUI_API bool Combo(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); IMGUI_API bool ColorButton(const ImVec4& col, bool small_height = false, bool outline_border = true); - IMGUI_API bool ColorEdit3(const char* label, float col[3]); - IMGUI_API bool ColorEdit4(const char* label, float col[4], bool show_alpha = true); - IMGUI_API void ColorEditMode(ImGuiColorEditMode mode); + IMGUI_API bool ColorEdit3(const char* label, float col[3]); // Hint: 'float col[3]' function argument is same as 'float* col'. You can pass address of first element out of a contiguous set, e.g. &myvector.x + IMGUI_API bool ColorEdit4(const char* label, float col[4], bool show_alpha = true); // " + IMGUI_API void ColorEditMode(ImGuiColorEditMode mode); // FIXME-OBSOLETE: This is inconsistent with most of the API and will be obsoleted/replaced. IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float)); IMGUI_API void PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float)); IMGUI_API void PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); + IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL); - // Widgets: Drags (tip: ctrl+click on a drag box to input text) + // Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can go off-bounds) + // For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, remember than a 'float v[3]' function argument is the same as 'float* v'. You can pass address of your first element out of a contiguous set, e.g. &myvector.x IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); @@ -276,7 +291,7 @@ namespace ImGui IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f", const char* display_format_max = NULL); - // Widgets: Input + // Widgets: Input with Keyboard IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); @@ -288,7 +303,7 @@ namespace ImGui IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags = 0); - // Widgets: Sliders (tip: ctrl+click on a slider to input text) + // Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can go off-bounds) IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); // adjust display_format to decorate the value with a prefix or a suffix. Use power!=1.0 for logarithmic sliders IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); @@ -302,20 +317,29 @@ namespace ImGui IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format = "%.0f"); // Widgets: Trees - IMGUI_API bool TreeNode(const char* str_label_id); // if returning 'true' the node is open and the user is responsible for calling TreePop() - IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_PRINTFARGS(2); // " + IMGUI_API bool TreeNode(const char* label); // if returning 'true' the node is open and the tree id is pushed into the id stack. user is responsible for calling TreePop(). + IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_PRINTFARGS(2); // read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_PRINTFARGS(2); // " IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args); // " IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args); // " - IMGUI_API void TreePush(const char* str_id = NULL); // already called by TreeNode(), but you can call Push/Pop yourself for layouting purpose + IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); + IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3); + IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3); + IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args); + IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args); + IMGUI_API void TreePush(const char* str_id = NULL); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Push/Pop yourself for layout purpose IMGUI_API void TreePush(const void* ptr_id = NULL); // " - IMGUI_API void TreePop(); - IMGUI_API void SetNextTreeNodeOpened(bool opened, ImGuiSetCond cond = 0); // set next tree node to be opened. + IMGUI_API void TreePop(); // ~ Unindent()+PopId() + IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing() + IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode + IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond = 0); // set next TreeNode/CollapsingHeader open state. + IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). + IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header // Widgets: Selectable / Lists IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); - IMGUI_API bool ListBox(const char* label, int* current_item, const char** items, int items_count, int height_in_items = -1); + IMGUI_API bool ListBox(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items = -1); IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. make sure to call ListBoxFooter() afterwards. IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // " @@ -326,10 +350,10 @@ namespace ImGui IMGUI_API void Value(const char* prefix, int v); IMGUI_API void Value(const char* prefix, unsigned int v); IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); - IMGUI_API void Color(const char* prefix, const ImVec4& v); - IMGUI_API void Color(const char* prefix, unsigned int v); + IMGUI_API void ValueColor(const char* prefix, const ImVec4& v); + IMGUI_API void ValueColor(const char* prefix, ImU32 v); - // Tooltip + // Tooltips IMGUI_API void SetTooltip(const char* fmt, ...) IM_PRINTFARGS(1); // set tooltip under mouse-cursor, typically use with ImGui::IsHovered(). last call wins IMGUI_API void SetTooltipV(const char* fmt, va_list args); IMGUI_API void BeginTooltip(); // use to create full-featured tooltip windows that aren't just text @@ -345,17 +369,17 @@ namespace ImGui IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL - // Popup - IMGUI_API void OpenPopup(const char* str_id); // mark popup as open. popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). close childs popups if any. will close popup when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. - IMGUI_API bool BeginPopup(const char* str_id); // return true if popup if opened and start outputting to it. only call EndPopup() if BeginPopup() returned true! - IMGUI_API bool BeginPopupModal(const char* name, bool* p_opened = NULL, ImGuiWindowFlags extra_flags = 0); // modal dialog (can't close them by clicking outside) - IMGUI_API bool BeginPopupContextItem(const char* str_id, int mouse_button = 1); // helper to open and begin popup when clicked on last item - IMGUI_API bool BeginPopupContextWindow(bool also_over_items = true, const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked on current window - IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked in void (no window) + // Popups + IMGUI_API void OpenPopup(const char* str_id); // mark popup as open. popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). + IMGUI_API bool BeginPopup(const char* str_id); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returned true! + IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags extra_flags = 0); // modal dialog (block interactions behind the modal window, can't close the modal window by clicking outside) + IMGUI_API bool BeginPopupContextItem(const char* str_id, int mouse_button = 1); // helper to open and begin popup when clicked on last item. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(bool also_over_items = true, const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked in void (no window). IMGUI_API void EndPopup(); IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. - // Logging: all text output from interface is redirected to tty/file/clipboard. Tree nodes are automatically opened. + // Logging: all text output from interface is redirected to tty/file/clipboard. By default, tree nodes are automatically opened during logging. IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file IMGUI_API void LogToClipboard(int max_depth = -1); // start logging to OS clipboard @@ -363,21 +387,29 @@ namespace ImGui IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard IMGUI_API void LogText(const char* fmt, ...) IM_PRINTFARGS(1); // pass text data straight to log (without being displayed) + // Clipping + IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); + IMGUI_API void PopClipRect(); + // Utilities IMGUI_API bool IsItemHovered(); // was the last item hovered by mouse? - IMGUI_API bool IsItemHoveredRect(); // was the last item hovered by mouse? even if another item is active while we are hovering this + IMGUI_API bool IsItemHoveredRect(); // was the last item hovered by mouse? even if another item is active or window is blocked by popup while we are hovering this IMGUI_API bool IsItemActive(); // was the last item active? (e.g. button being held, text field being edited- items that don't interact will always return false) + IMGUI_API bool IsItemClicked(int mouse_button = 0); // was the last item clicked? (e.g. button/node just clicked on) IMGUI_API bool IsItemVisible(); // was the last item visible? (aka not out of sight due to clipping/scrolling.) IMGUI_API bool IsAnyItemHovered(); IMGUI_API bool IsAnyItemActive(); IMGUI_API ImVec2 GetItemRectMin(); // get bounding rect of last item in screen space IMGUI_API ImVec2 GetItemRectMax(); // " IMGUI_API ImVec2 GetItemRectSize(); // " + IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area. IMGUI_API bool IsWindowHovered(); // is current window hovered and hoverable (not blocked by a popup) (differentiate child windows from each others) IMGUI_API bool IsWindowFocused(); // is current window focused - IMGUI_API bool IsRootWindowFocused(); // is current root window focused (top parent window in case of child windows) + IMGUI_API bool IsRootWindowFocused(); // is current root window focused (root = top-most parent of a child, otherwise self) IMGUI_API bool IsRootWindowOrAnyChildFocused(); // is current root window or any of its child (including current window) focused - IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle of given size starting from cursor pos is visible (not clipped). to perform coarse clipping on user's side (as an optimization) + IMGUI_API bool IsRootWindowOrAnyChildHovered(); // is current root window or any of its child (including current window) hovered and hoverable (not blocked by a popup) + IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped. + IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. IMGUI_API bool IsPosHoveringAnyWindow(const ImVec2& pos); // is given position hovering any active imgui window IMGUI_API float GetTime(); IMGUI_API int GetFrameCount(); @@ -395,17 +427,17 @@ namespace ImGui IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); // Inputs - IMGUI_API int GetKeyIndex(ImGuiKey key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key] - IMGUI_API bool IsKeyDown(int key_index); // key_index into the keys_down[] array, imgui doesn't know the semantic of each entry, uses your own indices! - IMGUI_API bool IsKeyPressed(int key_index, bool repeat = true); // uses user's key indices as stored in the keys_down[] array. if repeat=true. uses io.KeyRepeatDelay / KeyRepeatRate - IMGUI_API bool IsKeyReleased(int key_index); // " + IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key] + IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index]. note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your backend/engine stored them into KeyDown[]! + IMGUI_API bool IsKeyPressed(int user_key_index, bool repeat = true); // was key pressed (went from !Down to Down). if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate + IMGUI_API bool IsKeyReleased(int user_key_index); // was key released (went from Down to !Down).. IMGUI_API bool IsMouseDown(int button); // is mouse button held IMGUI_API bool IsMouseClicked(int button, bool repeat = false); // did mouse button clicked (went from !Down to Down) IMGUI_API bool IsMouseDoubleClicked(int button); // did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime. IMGUI_API bool IsMouseReleased(int button); // did mouse button released (went from Down to !Down) IMGUI_API bool IsMouseHoveringWindow(); // is mouse hovering current window ("window" in API names always refer to current window). disregarding of any consideration of being blocked by a popup. (unlike IsWindowHovered() this will return true even if the window is blocked because of a popup) IMGUI_API bool IsMouseHoveringAnyWindow(); // is mouse hovering any visible window - IMGUI_API bool IsMouseHoveringRect(const ImVec2& pos_min, const ImVec2& pos_max, bool clip = true); // is mouse hovering given bounding rect (in screen space). clipped by current clipping settings. disregarding of consideration of focus/window ordering/blocked by a popup. + IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true); // is mouse hovering given bounding rect (in screen space). clipped by current clipping settings. disregarding of consideration of focus/window ordering/blocked by a popup. IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse positioning at the time of opening popup we have BeginPopup() into @@ -413,8 +445,8 @@ namespace ImGui IMGUI_API void ResetMouseDragDelta(int button = 0); // IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type - IMGUI_API void CaptureKeyboardFromApp(); // manually enforce imgui setting the io.WantCaptureKeyboard flag next frame (your application needs to handle it). e.g. capture keyboard when your widget is being hovered. - IMGUI_API void CaptureMouseFromApp(); // manually enforce imgui setting the io.WantCaptureMouse flag next frame (your application needs to handle it). + IMGUI_API void CaptureKeyboardFromApp(bool capture = true); // manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application handle). e.g. force capture keyboard when your widget is being hovered. + IMGUI_API void CaptureMouseFromApp(bool capture = true); // manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application handle). // Helpers functions to access functions pointers in ImGui::GetIO() IMGUI_API void* MemAlloc(size_t sz); @@ -422,23 +454,22 @@ namespace ImGui IMGUI_API const char* GetClipboardText(); IMGUI_API void SetClipboardText(const char* text); - // Internal state/context access - if you want to use multiple ImGui context, or share context between modules (e.g. DLL), or allocate the memory yourself + // Internal context access - if you want to use multiple context, share context between modules (e.g. DLL). There is a default context created and active by default. + // All contexts share a same ImFontAtlas by default. If you want different font atlas, you can new() them and overwrite the GetIO().Fonts variable of an ImGui context. IMGUI_API const char* GetVersion(); - IMGUI_API void* GetInternalState(); - IMGUI_API size_t GetInternalStateSize(); - IMGUI_API void SetInternalState(void* state, bool construct = false); + IMGUI_API ImGuiContext* CreateContext(void* (*malloc_fn)(size_t) = NULL, void (*free_fn)(void*) = NULL); + IMGUI_API void DestroyContext(ImGuiContext* ctx); + IMGUI_API ImGuiContext* GetCurrentContext(); + IMGUI_API void SetCurrentContext(ImGuiContext* ctx); // Obsolete (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - static inline void OpenNextNode(bool open) { ImGui::SetNextTreeNodeOpened(open, 0); } // OBSOLETE 1.34+ - static inline bool GetWindowIsFocused() { return ImGui::IsWindowFocused(); } // OBSOLETE 1.36+ + static inline bool CollapsingHeader(const char* label, const char* str_id, bool framed = true, bool default_open = false) { (void)str_id; (void)framed; ImGuiTreeNodeFlags default_open_flags = 1<<5; return CollapsingHeader(label, (default_open ? default_open_flags : 0)); } // OBSOLETE 1.49+ + static inline ImFont* GetWindowFont() { return GetFont(); } // OBSOLETE 1.48+ + static inline float GetWindowFontSize() { return GetFontSize(); } // OBSOLETE 1.48+ + static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETE 1.42+ static inline bool GetWindowCollapsed() { return ImGui::IsWindowCollapsed(); } // OBSOLETE 1.39+ - static inline ImVec2 GetItemBoxMin() { return GetItemRectMin(); } // OBSOLETE 1.36+ - static inline ImVec2 GetItemBoxMax() { return GetItemRectMax(); } // OBSOLETE 1.36+ - static inline bool IsClipped(const ImVec2& size) { return !IsRectVisible(size); } // OBSOLETE 1.38+ static inline bool IsRectClipped(const ImVec2& size) { return !IsRectVisible(size); } // OBSOLETE 1.39+ - static inline bool IsMouseHoveringBox(const ImVec2& rect_min, const ImVec2& rect_max) { return IsMouseHoveringRect(rect_min, rect_max); } // OBSOLETE 1.36+ - static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETE 1.42+ #endif } // namespace ImGui @@ -450,17 +481,20 @@ enum ImGuiWindowFlags_ ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window - ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbar (window can still scroll with mouse or programatically) - ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user scrolling with mouse wheel + ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programatically) + ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame ImGuiWindowFlags_ShowBorders = 1 << 7, // Show borders around windows and items ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file ImGuiWindowFlags_NoInputs = 1 << 9, // Disable catching mouse or keyboard inputs ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar - ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Enable horizontal scrollbar (off by default). You need to use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. + ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programatically giving it focus) + ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) + ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) + ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient) // [Internal] ImGuiWindowFlags_ChildWindow = 1 << 20, // Don't use! For internal use by BeginChild() ImGuiWindowFlags_ChildWindowAutoFitX = 1 << 21, // Don't use! For internal use by BeginChild() @@ -484,23 +518,43 @@ enum ImGuiInputTextFlags_ ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to when the value was modified) ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Call user function on pressing TAB (for completion handling) ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Call user function on pressing Up/Down arrows (for history handling) - ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Call user function every time + ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Call user function every time. User code may query cursor position, modify text buffer. ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Call user function to filter character. Modify data->EventChar to replace/filter input, or return 1 to discard character. ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field - ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, allow exiting edition by pressing Enter. Ctrl+Enter to add new line (by default adds new lines with Enter). + ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter). ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally ImGuiInputTextFlags_AlwaysInsertMode = 1 << 13, // Insert mode ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode + ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*' // [Internal] ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline() }; +// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() +enum ImGuiTreeNodeFlags_ +{ + ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected + ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader) + ImGuiTreeNodeFlags_AllowOverlapMode = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one + ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack + ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) + ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open + ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node + ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open. + ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). + ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow + //ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 10, // FIXME: TODO: Extend hit box horizontally even if not framed + //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 11, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible + ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoAutoOpenOnLog +}; + // Flags for ImGui::Selectable() enum ImGuiSelectableFlags_ { // Default: 0 ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window - ImGuiSelectableFlags_SpanAllColumns = 1 << 1 // Selectable frame can span all columns (text will still fit in current column) + ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column) + ImGuiSelectableFlags_AllowDoubleClick = 1 << 2 // Generate press events on double clicks too }; // User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array @@ -533,8 +587,9 @@ enum ImGuiCol_ { ImGuiCol_Text, ImGuiCol_TextDisabled, - ImGuiCol_WindowBg, - ImGuiCol_ChildWindowBg, + ImGuiCol_WindowBg, // Background of normal windows + ImGuiCol_ChildWindowBg, // Background of child windows + ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows ImGuiCol_Border, ImGuiCol_BorderShadow, ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input @@ -572,7 +627,6 @@ enum ImGuiCol_ ImGuiCol_PlotHistogram, ImGuiCol_PlotHistogramHovered, ImGuiCol_TextSelectedBg, - ImGuiCol_TooltipBg, ImGuiCol_ModalWindowDarkening, // darken entire screen when a modal window is active ImGuiCol_COUNT }; @@ -591,20 +645,13 @@ enum ImGuiStyleVar_ ImGuiStyleVar_ItemSpacing, // ImVec2 ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ImGuiStyleVar_IndentSpacing, // float - ImGuiStyleVar_GrabMinSize // float -}; - -enum ImGuiAlign_ -{ - ImGuiAlign_Left = 1 << 0, - ImGuiAlign_Center = 1 << 1, - ImGuiAlign_Right = 1 << 2, - ImGuiAlign_Top = 1 << 3, - ImGuiAlign_VCenter = 1 << 4, - ImGuiAlign_Default = ImGuiAlign_Left | ImGuiAlign_Top + ImGuiStyleVar_GrabMinSize, // float + ImGuiStyleVar_ButtonTextAlign, // flags ImGuiAlign_* + ImGuiStyleVar_Count_ }; // Enumeration for ColorEditMode() +// FIXME-OBSOLETE: Will be replaced by future color/picker api enum ImGuiColorEditMode_ { ImGuiColorEditMode_UserSelect = -2, @@ -617,6 +664,7 @@ enum ImGuiColorEditMode_ // Enumeration for GetMouseCursor() enum ImGuiMouseCursor_ { + ImGuiMouseCursor_None = -1, ImGuiMouseCursor_Arrow = 0, ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. ImGuiMouseCursor_Move, // Unused @@ -632,9 +680,9 @@ enum ImGuiMouseCursor_ enum ImGuiSetCond_ { ImGuiSetCond_Always = 1 << 0, // Set the variable - ImGuiSetCond_Once = 1 << 1, // Only set the variable on the first call per runtime session - ImGuiSetCond_FirstUseEver = 1 << 2, // Only set the variable if the window doesn't exist in the .ini file - ImGuiSetCond_Appearing = 1 << 3 // Only set the variable if the window is appearing after being inactive (or the first time) + ImGuiSetCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed) + ImGuiSetCond_FirstUseEver = 1 << 2, // Set the variable if the window has no saved data (if doesn't exist in the .ini file) + ImGuiSetCond_Appearing = 1 << 3 // Set the variable if the window is appearing after being hidden/inactive (or the first time) }; struct ImGuiStyle @@ -643,20 +691,20 @@ struct ImGuiStyle ImVec2 WindowPadding; // Padding within a window ImVec2 WindowMinSize; // Minimum window size float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows - ImGuiAlign WindowTitleAlign; // Alignment for title bar text + ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. float ChildWindowRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets) float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! - float WindowFillAlphaDefault; // Default alpha of window background, if not specified in ImGui::Begin() - float IndentSpacing; // Horizontal indentation when e.g. entering a tree node + float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). float ColumnsMinSpacing; // Minimum horizontal spacing between two columns float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar float ScrollbarRounding; // Radius of grab corners for scrollbar - float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar + float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f,0.5f) for horizontally+vertically centered. ImVec2 DisplayWindowPadding; // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows. ImVec2 DisplaySafeAreaPadding; // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. @@ -684,30 +732,35 @@ struct ImGuiIO float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging int KeyMap[ImGuiKey_COUNT]; // // Map of indices into the KeysDown[512] entries array - float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds. (for actions where 'repeat' is active) + float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). float KeyRepeatRate; // = 0.020f // When holding a key/button, rate at which it repeats, in seconds. void* UserData; // = NULL // Store your own data for retrieval by callbacks. ImFontAtlas* Fonts; // // Load and assemble one or more fonts into a single tightly packed texture. Output to Fonts array. float FontGlobalScale; // = 1.0f // Global scale all fonts bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. + ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. ImVec2 DisplayVisibleMin; // (0.0f,0.0f) // If you use DisplaySize as a virtual space larger than your screen, set DisplayVisibleMin/Max to the visible area. ImVec2 DisplayVisibleMax; // (0.0f,0.0f) // If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize + // Advanced/subtle behaviors + bool OSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl + //------------------------------------------------------------------ // User Functions //------------------------------------------------------------------ - // Rendering function, will be called in Render(). + // Rendering function, will be called in Render(). // Alternatively you can keep this to NULL and call GetDrawData() after Render() to get the same pointer. // See example applications if you are unsure of how to implement this. void (*RenderDrawListsFn)(ImDrawData* data); // Optional: access OS clipboard // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) - const char* (*GetClipboardTextFn)(); - void (*SetClipboardTextFn)(const char* text); + const char* (*GetClipboardTextFn)(void* user_data); + void (*SetClipboardTextFn)(void* user_data, const char* text); + void* ClipboardUserData; // Optional: override memory allocations. MemFreeFn() may be called with a NULL pointer. // (default to posix malloc/free) @@ -730,32 +783,34 @@ struct ImGuiIO bool KeyCtrl; // Keyboard modifier pressed: Control bool KeyShift; // Keyboard modifier pressed: Shift bool KeyAlt; // Keyboard modifier pressed: Alt + bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows bool KeysDown[512]; // Keyboard keys that are pressed (in whatever storage order you naturally have access to keyboard data) ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper. // Functions - IMGUI_API void AddInputCharacter(ImWchar c); // Helper to add a new character into InputCharacters[] - IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Helper to add new characters into InputCharacters[] from an UTF-8 string + IMGUI_API void AddInputCharacter(ImWchar c); // Add new character into InputCharacters[] + IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Add new characters into InputCharacters[] from an UTF-8 string + inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Clear the text input buffer manually //------------------------------------------------------------------ - // Output - Retrieve after calling NewFrame(), you can use them to discard inputs or hide them from the rest of your application + // Output - Retrieve after calling NewFrame() //------------------------------------------------------------------ - bool WantCaptureMouse; // Mouse is hovering a window or widget is active (= ImGui will use your mouse input) - bool WantCaptureKeyboard; // Widget is active (= ImGui will use your keyboard input) - bool WantTextInput; // Some text input widget is active, which will read input characters from the InputCharacters array. - float Framerate; // Framerate estimation, in frame per second. Rolling average estimation based on IO.DeltaTime over 120 frames + bool WantCaptureMouse; // Mouse is hovering a window or widget is active (= ImGui will use your mouse input). Use to hide mouse from the rest of your application + bool WantCaptureKeyboard; // Widget is active (= ImGui will use your keyboard input). Use to hide keyboard from the rest of your application + bool WantTextInput; // Some text input widget is active, which will read input characters from the InputCharacters array. Use to activate on screen keyboard if your system needs one + float Framerate; // Application framerate estimation, in frame per second. Solely for convenience. Rolling average estimation based on IO.DeltaTime over 120 frames int MetricsAllocs; // Number of active memory allocations int MetricsRenderVertices; // Vertices output during last call to Render() int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3 - int MetricsActiveWindows; // Number of visible windows (exclude child windows) + int MetricsActiveWindows; // Number of visible root windows (exclude child windows) + ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are negative, so a disappearing/reappearing mouse won't have a huge delta for one frame. //------------------------------------------------------------------ - // [Internal] ImGui will maintain those fields for you + // [Private] ImGui will maintain those fields. Forward compatibility not guaranteed! //------------------------------------------------------------------ - ImVec2 MousePosPrev; // Previous mouse position - ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are negative to allow mouse enabling/disabling. + ImVec2 MousePosPrev; // Previous mouse position temporary storage (nb: not for public use, set to MousePos in NewFrame()) bool MouseClicked[5]; // Mouse button went from !Down to Down ImVec2 MouseClickedPos[5]; // Position at time of clicking float MouseClickedTime[5]; // Time of last click (used to figure out double-click) @@ -817,7 +872,8 @@ class ImVector { if (new_capacity <= Capacity) return; T* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(value_type)); - memcpy(new_data, Data, (size_t)Size * sizeof(value_type)); + if (Data) + memcpy(new_data, Data, (size_t)Size * sizeof(value_type)); ImGui::MemFree(Data); Data = new_data; Capacity = new_capacity; @@ -826,11 +882,11 @@ class ImVector inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size+1)); Data[Size++] = v; } inline void pop_back() { IM_ASSERT(Size > 0); Size--; } - inline iterator erase(const_iterator it) { IM_ASSERT(it >= begin() && it < end()); const ptrdiff_t off = it - begin(); memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; } - inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= begin() && it <= end()); const ptrdiff_t off = it - begin(); if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; return Data + off; } + inline iterator erase(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; } + inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; return Data + off; } }; -// Helper: execute a block of code once a frame only +// Helper: execute a block of code at maximum once a frame // Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame. // Usage: // IMGUI_ONCE_UPON_A_FRAME @@ -860,8 +916,8 @@ struct ImGuiTextFilter const char* end() const { return e; } bool empty() const { return b == e; } char front() const { return *b; } - static bool isblank(char c) { return c == ' ' || c == '\t'; } - void trim_blanks() { while (b < e && isblank(*b)) b++; while (e > b && isblank(*(e-1))) e--; } + static bool is_blank(char c) { return c == ' ' || c == '\t'; } + void trim_blanks() { while (b < e && is_blank(*b)) b++; while (e > b && is_blank(*(e-1))) e--; } IMGUI_API void split(char separator, ImVector& out); }; @@ -870,6 +926,7 @@ struct ImGuiTextFilter int CountGrep; ImGuiTextFilter(const char* default_filter = ""); + ~ImGuiTextFilter() {} void Clear() { InputBuf[0] = 0; Build(); } bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build bool PassFilter(const char* text, const char* text_end = NULL) const; @@ -887,21 +944,21 @@ struct ImGuiTextBuffer const char* begin() const { return &Buf.front(); } const char* end() const { return &Buf.back(); } // Buf is zero-terminated, so end() will point on the zero-terminator int size() const { return Buf.Size - 1; } - bool empty() { return Buf.Size >= 2; } + bool empty() { return Buf.Size <= 1; } void clear() { Buf.clear(); Buf.push_back(0); } const char* c_str() const { return Buf.Data; } IMGUI_API void append(const char* fmt, ...) IM_PRINTFARGS(2); IMGUI_API void appendv(const char* fmt, va_list args); }; -// Helper: Key->value storage -// - Store collapse state for a tree (Int 0/1) -// - Store color edit options (Int using values in ImGuiColorEditMode enum). -// - Custom user storage for temporary values. +// Helper: Simple Key->value storage // Typically you don't have to worry about this since a storage is held within each Window. +// We use it to e.g. store collapse state for a tree (Int 0/1), store color edit options. +// You can use it as custom user storage for temporary values. // Declare your own storage if: // - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). // - You want to store custom debug data easily without adding or editing structures in your code. +// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. struct ImGuiStorage { struct Pair @@ -912,33 +969,35 @@ struct ImGuiStorage Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } }; - ImVector Data; + ImVector Data; // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) // - Set***() functions find pair, insertion on demand if missing. - // - Sorted insertion is costly but should amortize. A typical frame shouldn't need to insert any new pair. - IMGUI_API void Clear(); - IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; - IMGUI_API void SetInt(ImGuiID key, int val); - IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; - IMGUI_API void SetFloat(ImGuiID key, float val); - IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL - IMGUI_API void SetVoidPtr(ImGuiID key, void* val); + // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair. + IMGUI_API void Clear(); + IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; + IMGUI_API void SetInt(ImGuiID key, int val); + IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const; + IMGUI_API void SetBool(ImGuiID key, bool val); + IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; + IMGUI_API void SetFloat(ImGuiID key, float val); + IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL + IMGUI_API void SetVoidPtr(ImGuiID key, void* val); // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. - // - A typical use case where this is convenient: + // - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct) // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; - // - You can also use this to quickly create temporary editable values during a session of using Edit&Continue, without restarting your application. - IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); - IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0); - IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); + IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); + IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false); + IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f); + IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); // Use on your own storage if you know only integer are being stored (open/close all tree nodes) - IMGUI_API void SetAllInt(int val); + IMGUI_API void SetAllInt(int val); }; -// Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used. +// Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used and the corresponding callback is triggered. struct ImGuiTextEditCallbackData { ImGuiInputTextFlags EventFlag; // One of ImGuiInputTextFlags_Callback* // Read-only @@ -950,67 +1009,100 @@ struct ImGuiTextEditCallbackData ImWchar EventChar; // Character input // Read-write (replace character or set to zero) // Completion,History,Always events: + // If you modify the buffer contents make sure you update 'BufTextLen' and set 'BufDirty' to true. ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only - char* Buf; // Current text // Read-write (pointed data only) - int BufSize; // // Read-only - bool BufDirty; // Must set if you modify Buf directly // Write + char* Buf; // Current text buffer // Read-write (pointed data only, can't replace the actual pointer) + int BufTextLen; // Current text length in bytes // Read-write + int BufSize; // Maximum text length in bytes // Read-only + bool BufDirty; // Set if you modify Buf/BufTextLen!! // Write int CursorPos; // // Read-write int SelectionStart; // // Read-write (== to SelectionEnd when no selection) int SelectionEnd; // // Read-write - // NB: calling those function loses selection. - void DeleteChars(int pos, int bytes_count); - void InsertChars(int pos, const char* text, const char* text_end = NULL); + // NB: Helper functions for text manipulation. Calling those function loses selection. + IMGUI_API void DeleteChars(int pos, int bytes_count); + IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL); bool HasSelection() const { return SelectionStart != SelectionEnd; } }; -// ImColor() is just a helper that implicity converts to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float) -// None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. +// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). +// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough. +struct ImGuiSizeConstraintCallbackData +{ + void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints() + ImVec2 Pos; // Read-only. Window position, for reference. + ImVec2 CurrentSize; // Read-only. Current window size. + ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. +}; + +// Helpers macros to generate 32-bits encoded colors +#ifdef IMGUI_USE_BGRA_PACKED_COLOR +#define IM_COL32_R_SHIFT 16 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 0 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#else +#define IM_COL32_R_SHIFT 0 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 16 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#endif +#define IM_COL32(R,G,B,A) (((ImU32)(A)<>8)&0xFF) * sc; Value.z = (float)((rgba>>16)&0xFF) * sc; Value.w = (float)(rgba >> 24) * sc; } + ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)((rgba>>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; } ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; } ImColor(const ImVec4& col) { Value = col; } - operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } - operator ImVec4() const { return Value; } + inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } + inline operator ImVec4() const { return Value; } + + inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); } }; // Helper: Manually clip large list of items. -// If you are displaying thousands of even spaced items and you have a random access to the list, you can perform clipping yourself to save on CPU. +// If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse clipping based on visibility to save yourself from processing those items at all. +// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. +// ImGui already clip items based on their bounds but it needs to measure text size to do so. Coarse clipping before submission makes this cost and your own data fetching/submission cost null. // Usage: -// ImGuiListClipper clipper(count, ImGui::GetTextLineHeightWithSpacing()); -// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) // display only visible items -// ImGui::Text("line number %d", i); -// clipper.End(); -// NB: 'count' is only used to clamp the result, if you don't know your count you can use INT_MAX +// ImGuiListClipper clipper(1000); // we have 1000 elements, evenly spaced. +// while (clipper.Step()) +// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) +// ImGui::Text("line number %d", i); +// - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor). +// - Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. +// - (Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.) +// - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. struct ImGuiListClipper { + float StartPosY; float ItemsHeight; - int ItemsCount, DisplayStart, DisplayEnd; + int ItemsCount, StepNo, DisplayStart, DisplayEnd; - ImGuiListClipper() { ItemsHeight = 0.0f; ItemsCount = DisplayStart = DisplayEnd = -1; } - ImGuiListClipper(int count, float height) { ItemsCount = -1; Begin(count, height); } - ~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // user forgot to call End() + // items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step). + // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetItemsLineHeightWithSpacing(). + // If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step(). + ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want). + ~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false. - void Begin(int count, float height) // items_height: generally pass GetTextLineHeightWithSpacing() or GetItemsLineHeightWithSpacing() - { - IM_ASSERT(ItemsCount == -1); - ItemsCount = count; - ItemsHeight = height; - ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display - ImGui::SetCursorPosY(ImGui::GetCursorPosY() + DisplayStart * ItemsHeight); // advance cursor - } - void End() - { - IM_ASSERT(ItemsCount >= 0); - ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (ItemsCount - DisplayEnd) * ItemsHeight); // advance cursor - ItemsCount = -1; - } + IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. + IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1. + IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. }; //----------------------------------------------------------------------------- @@ -1020,13 +1112,8 @@ struct ImGuiListClipper // Draw callbacks for advanced uses. // NB- You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering (you can poke into the draw list for that) -// Draw callback are useful for example if you want to render a complex 3D scene inside a UI element. -// The expected behavior from your rendering loop is: -// if (cmd.UserCallback != NULL) -// cmd.UserCallback(parent_list, cmd); -// else -// RenderTriangles() -// It is up to you to decide if your rendering loop or the callback should be responsible for backup/restoring rendering state. +// Draw callback may be useful for example, A) Change your GPU render state, B) render a complex 3D scene inside a UI element (without an intermediate texture/render target), etc. +// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) cmd.UserCallback(parent_list, cmd); else RenderTriangles()' typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); // Typically, 1 command = 1 gpu draw call (unless command is a callback) @@ -1041,7 +1128,7 @@ struct ImDrawCmd ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = -8192.0f; ClipRect.z = ClipRect.w = +8192.0f; TextureId = NULL; UserCallback = NULL; UserCallbackData = NULL; } }; -// Vertex index (override with, e.g. '#define ImDrawIdx unsigned int' in ImConfig) +// Vertex index (override with '#define ImDrawIdx unsigned int' inside in imconfig.h) #ifndef ImDrawIdx typedef unsigned short ImDrawIdx; #endif @@ -1055,9 +1142,9 @@ struct ImDrawVert ImU32 col; }; #else -// You can change the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h +// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h // The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. -// The type has to be described by the #define (you can either declare the struct or use a typedef) +// The type has to be described within the macro (you can either declare the struct or use a typedef) IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; #endif @@ -1075,7 +1162,6 @@ struct ImDrawChannel // If you want to add custom rendering within a window, you can use ImGui::GetWindowDrawList() to access the current draw list and add your own primitives. // You can interleave normal ImGui:: calls and adding primitives to the current draw list. // All positions are in screen coordinates (0,0=top-left, 1 pixel per unit). Primitives are always added to the list and not culled (culling is done at render time and at a higher-level by ImGui:: functions). -// Note that this only gives you access to rendering polygons. If your intent is to create custom widgets and the publicly exposed functions/data aren't sufficient, you can add code in imgui_user.inl struct ImDrawList { // This is what you have to render @@ -1084,7 +1170,7 @@ struct ImDrawList ImVector VtxBuffer; // Vertex buffer. // [Internal, used while building lists] - const char* _OwnerName; // Pointer to owner window's name (if any) for debugging + const char* _OwnerName; // Pointer to owner window's name for debugging unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) @@ -1095,11 +1181,9 @@ struct ImDrawList int _ChannelsCount; // [Internal] number of active channels (1+) ImVector _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size) - ImDrawList() { _OwnerName = NULL; Clear(); } + ImDrawList() { _OwnerName = NULL; Clear(); } ~ImDrawList() { ClearFreeMemory(); } - IMGUI_API void Clear(); - IMGUI_API void ClearFreeMemory(); - IMGUI_API void PushClipRect(const ImVec4& clip_rect); // Scissoring. The values are x1, y1, x2, y2. + IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) IMGUI_API void PushClipRectFullScreen(); IMGUI_API void PopClipRect(); IMGUI_API void PushTextureID(const ImTextureID& texture_id); @@ -1107,15 +1191,19 @@ struct ImDrawList // Primitives IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); - IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners = 0x0F); - IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners = 0x0F); + IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ~0, float thickness = 1.0f); // a: upper-left, b: lower-right, rounding_corners_flags: 4-bits corresponding to which corner to round + IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ~0); // a: upper-left, b: lower-right IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); + IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col); + IMGUI_API void AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness = 1.0f); IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col); - IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); + IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f); IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); - IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), ImU32 col = 0xFFFFFFFF); + IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = 0xFFFFFFFF); + IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = 0xFFFFFFFF); IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness, bool anti_aliased); IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col, bool anti_aliased); IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0); @@ -1123,13 +1211,13 @@ struct ImDrawList // Stateful path API, add points then finish with PathFill() or PathStroke() inline void PathClear() { _Path.resize(0); } inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } - inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || _Path[_Path.Size-1].x != pos.x || _Path[_Path.Size-1].y != pos.y) _Path.push_back(pos); } - inline void PathFill(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, true); PathClear(); } + inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); } + inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, true); PathClear(); } inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness, true); PathClear(); } IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10); - IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle + IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0); - IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners = 0x0F); + IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners_flags = ~0); // rounding_corners_flags: 4-bits corresponding to which corner to round // Channels // - Use to simulate layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives) @@ -1144,12 +1232,15 @@ struct ImDrawList // Internal helpers // NB: all primitives needs to be reserved via PrimReserve() beforehand! + IMGUI_API void Clear(); + IMGUI_API void ClearFreeMemory(); IMGUI_API void PrimReserve(int idx_count, int vtx_count); - IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); + IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); - inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } + IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } + inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } IMGUI_API void UpdateClipRect(); IMGUI_API void UpdateTextureID(); }; @@ -1177,11 +1268,11 @@ struct ImFontConfig int FontNo; // 0 // Index of font within TTF file float SizePixels; // // Size in pixels for rasterizer int OversampleH, OversampleV; // 3, 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. - bool PixelSnapH; // false // Align every character to pixel boundary (if enabled, set OversampleH/V to 1) + bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs - const ImWchar* GlyphRanges; // // List of Unicode range (2 value per range, values are inclusive, zero-terminated list) - bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). - bool MergeGlyphCenterV; // false // When merging (multiple ImFontInput for one ImFont), vertically center new glyphs instead of aligning their baseline + ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input + const ImWchar* GlyphRanges; // // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. + bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. // [Internal] char Name[32]; // Name (strictly for debugging) @@ -1198,6 +1289,7 @@ struct ImFontConfig // 3. Upload the pixels data into a texture within your graphics system. // 4. Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture. This value will be passed back to you during rendering to identify the texture. // 5. Call ClearTexData() to free textures memory on the heap. +// NB: If you use a 'glyph_ranges' array you need to make sure that your array persist up until the ImFont is cleared. We only copy the pointer, not the data. struct ImFontAtlas { IMGUI_API ImFontAtlas(); @@ -1220,26 +1312,27 @@ struct ImFontAtlas // Pitch = Width * BytesPerPixels IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel - void SetTexID(void* id) { TexID = id; } + void SetTexID(ImTextureID id) { TexID = id; } // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) - // (Those functions could be static but aren't so most users don't have to refer to the ImFontAtlas:: name ever if in their code; just using io.Fonts->) + // NB: Make sure that your string are UTF-8 and NOT in your local code page. See FAQ for details. IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs IMGUI_API const ImWchar* GetGlyphRangesChinese(); // Japanese + full set of about 21000 CJK Unified Ideographs IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters + IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters // Members // (Access texture data via GetTexData*() calls which will setup a default font for you.) - void* TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It ia passed back to you during rendering. + ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 int TexWidth; // Texture width calculated during Build(). int TexHeight; // Texture height calculated during Build(). int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. - ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel (part of the TexExtraData block) - ImVector Fonts; + ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel + ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. // Private ImVector ConfigData; // Internal data @@ -1251,15 +1344,6 @@ struct ImFontAtlas // ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). struct ImFont { - // Members: Settings - float FontSize; // // Height of characters, set during loading (don't change after loading) - float Scale; // = 1.0f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale() - ImVec2 DisplayOffset; // = (0.0f,1.0f) // Offset font rendering by xx pixels - ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() - ImFontConfig* ConfigData; // // Pointer within ImFontAtlas->ConfigData - int ConfigDataCount; // - - // Members: Runtime data struct Glyph { ImWchar Codepoint; @@ -1267,34 +1351,52 @@ struct ImFont float X0, Y0, X1, Y1; float U0, V0, U1, V1; // Texture coordinates }; - float Ascent, Descent; // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] - ImFontAtlas* ContainerAtlas; // What we has been loaded into - ImVector Glyphs; + + // Members: Hot ~62/78 bytes + float FontSize; // // Height of characters, set during loading (don't change after loading) + float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale() + ImVec2 DisplayOffset; // = (0.f,1.f) // Offset font rendering by xx pixels + ImVector Glyphs; // // All glyphs. + ImVector IndexXAdvance; // // Sparse. Glyphs->XAdvance in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI). + ImVector IndexLookup; // // Sparse. Index glyphs by Unicode code-point. const Glyph* FallbackGlyph; // == FindGlyph(FontFallbackChar) - float FallbackXAdvance; // - ImVector IndexXAdvance; // Sparse. Glyphs->XAdvance directly indexable (more cache-friendly that reading from Glyphs, for CalcTextSize functions which are often bottleneck in large UI) - ImVector IndexLookup; // Sparse. Index glyphs by Unicode code-point. + float FallbackXAdvance; // == FallbackGlyph->XAdvance + ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() + + // Members: Cold ~18/26 bytes + short ConfigDataCount; // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. + ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData + ImFontAtlas* ContainerAtlas; // // What we has been loaded into + float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] + int MetricsTotalSurface;// // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) // Methods IMGUI_API ImFont(); IMGUI_API ~ImFont(); IMGUI_API void Clear(); IMGUI_API void BuildLookupTable(); - IMGUI_API const Glyph* FindGlyph(unsigned short c) const; + IMGUI_API const Glyph* FindGlyph(ImWchar c) const; IMGUI_API void SetFallbackChar(ImWchar c); - float GetCharAdvance(unsigned short c) const { return ((int)c < IndexXAdvance.Size) ? IndexXAdvance[(int)c] : FallbackXAdvance; } - bool IsLoaded() const { return ContainerAtlas != NULL; } + float GetCharAdvance(ImWchar c) const { return ((int)c < IndexXAdvance.Size) ? IndexXAdvance[(int)c] : FallbackXAdvance; } + bool IsLoaded() const { return ContainerAtlas != NULL; } // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8 IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const; - IMGUI_API void RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, ImDrawList* draw_list, float wrap_width = 0.0f, bool cpu_fine_clip = false) const; + IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const; + IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const; + + // Private + IMGUI_API void GrowIndex(int new_size); + IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. }; -//---- Include imgui_user.h at the end of imgui.h -//---- So you can include code that extends ImGui using any of the types declared above. -//---- (also convenient for user to only explicitly include vanilla imgui.h) +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +// Include imgui_user.h at the end of imgui.h (convenient for user to only explicitly include vanilla imgui.h) #ifdef IMGUI_INCLUDE_IMGUI_USER_H #include "imgui_user.h" #endif diff --git a/SampleFramework12/v1.01/ImGui/imgui_demo.cpp b/SampleFramework12/v1.01/ImGui/imgui_demo.cpp new file mode 100644 index 0000000..e53ff58 --- /dev/null +++ b/SampleFramework12/v1.01/ImGui/imgui_demo.cpp @@ -0,0 +1,2643 @@ +// dear imgui, v1.50 +// (demo code) + +// Message to the person tempted to delete this file when integrating ImGui into their code base: +// Do NOT remove this file from your project! It is useful reference code that you and other users will want to refer to. +// Everything in this file will be stripped out by the linker if you don't call ImGui::ShowTestWindow(). +// During development, you can call ImGui::ShowTestWindow() in your code to learn about various features of ImGui. +// Removing this file from your project is hindering your access to documentation, likely leading you to poorer usage of the library. + +#include "PCH.h" + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#include // toupper, isprint +#include // sqrtf, powf, cosf, sinf, floorf, ceilf +#include // vsnprintf, sscanf, printf +#include // NULL, malloc, free, qsort, atoi +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include // intptr_t +#else +#include // intptr_t +#endif + +#ifdef _MSC_VER +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#define snprintf _snprintf +#endif +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning : 'xx' is deprecated: The POSIX name for this item.. // for strdup used in demo code (so user can copy & paste the code) +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' +#pragma clang diagnostic ignored "-Wformat-security" // warning : warning: format string is not a string literal +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#if __has_warning("-Wreserved-id-macro") +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // +#endif +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat-security" // warning : format string is not a string literal (potentially insecure) +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#if (__GNUC__ >= 6) +#pragma GCC diagnostic ignored "-Wmisleading-indentation" // warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on github. +#endif +#endif + +// Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n. +#ifdef _WIN32 +#define IM_NEWLINE "\r\n" +#else +#define IM_NEWLINE "\n" +#endif + +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) +#define IM_MAX(_A,_B) (((_A) >= (_B)) ? (_A) : (_B)) + +//----------------------------------------------------------------------------- +// DEMO CODE +//----------------------------------------------------------------------------- + +#ifndef IMGUI_DISABLE_TEST_WINDOWS + +static void ShowExampleAppConsole(bool* p_open); +static void ShowExampleAppLog(bool* p_open); +static void ShowExampleAppLayout(bool* p_open); +static void ShowExampleAppPropertyEditor(bool* p_open); +static void ShowExampleAppLongText(bool* p_open); +static void ShowExampleAppAutoResize(bool* p_open); +static void ShowExampleAppConstrainedResize(bool* p_open); +static void ShowExampleAppFixedOverlay(bool* p_open); +static void ShowExampleAppManipulatingWindowTitle(bool* p_open); +static void ShowExampleAppCustomRendering(bool* p_open); +static void ShowExampleAppMainMenuBar(); +static void ShowExampleMenuFile(); + +static void ShowHelpMarker(const char* desc) +{ + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::PushTextWrapPos(450.0f); + ImGui::TextUnformatted(desc); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} + +void ImGui::ShowUserGuide() +{ + ImGui::BulletText("Double-click on title bar to collapse window."); + ImGui::BulletText("Click and drag on lower right corner to resize window."); + ImGui::BulletText("Click and drag on any empty space to move window."); + ImGui::BulletText("Mouse Wheel to scroll."); + if (ImGui::GetIO().FontAllowUserScaling) + ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); + ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); + ImGui::BulletText("CTRL+Click on a slider or drag box to input text."); + ImGui::BulletText( + "While editing text:\n" + "- Hold SHIFT or use mouse to select text\n" + "- CTRL+Left/Right to word jump\n" + "- CTRL+A or double-click to select all\n" + "- CTRL+X,CTRL+C,CTRL+V clipboard\n" + "- CTRL+Z,CTRL+Y undo/redo\n" + "- ESCAPE to revert\n" + "- You can apply arithmetic operators +,*,/ on numerical values.\n" + " Use +- to subtract.\n"); +} + +// Demonstrate most ImGui features (big function!) +void ImGui::ShowTestWindow(bool* p_open) +{ + // Examples apps + static bool show_app_main_menu_bar = false; + static bool show_app_console = false; + static bool show_app_log = false; + static bool show_app_layout = false; + static bool show_app_property_editor = false; + static bool show_app_long_text = false; + static bool show_app_auto_resize = false; + static bool show_app_constrained_resize = false; + static bool show_app_fixed_overlay = false; + static bool show_app_manipulating_window_title = false; + static bool show_app_custom_rendering = false; + static bool show_app_style_editor = false; + + static bool show_app_metrics = false; + static bool show_app_about = false; + + if (show_app_main_menu_bar) ShowExampleAppMainMenuBar(); + if (show_app_console) ShowExampleAppConsole(&show_app_console); + if (show_app_log) ShowExampleAppLog(&show_app_log); + if (show_app_layout) ShowExampleAppLayout(&show_app_layout); + if (show_app_property_editor) ShowExampleAppPropertyEditor(&show_app_property_editor); + if (show_app_long_text) ShowExampleAppLongText(&show_app_long_text); + if (show_app_auto_resize) ShowExampleAppAutoResize(&show_app_auto_resize); + if (show_app_constrained_resize) ShowExampleAppConstrainedResize(&show_app_constrained_resize); + if (show_app_fixed_overlay) ShowExampleAppFixedOverlay(&show_app_fixed_overlay); + if (show_app_manipulating_window_title) ShowExampleAppManipulatingWindowTitle(&show_app_manipulating_window_title); + if (show_app_custom_rendering) ShowExampleAppCustomRendering(&show_app_custom_rendering); + + if (show_app_metrics) ImGui::ShowMetricsWindow(&show_app_metrics); + if (show_app_style_editor) { ImGui::Begin("Style Editor", &show_app_style_editor); ImGui::ShowStyleEditor(); ImGui::End(); } + if (show_app_about) + { + ImGui::Begin("About ImGui", &show_app_about, ImGuiWindowFlags_AlwaysAutoResize); + ImGui::Text("dear imgui, %s", ImGui::GetVersion()); + ImGui::Separator(); + ImGui::Text("By Omar Cornut and all github contributors."); + ImGui::Text("ImGui is licensed under the MIT License, see LICENSE for more information."); + ImGui::End(); + } + + static bool no_titlebar = false; + static bool no_border = true; + static bool no_resize = false; + static bool no_move = false; + static bool no_scrollbar = false; + static bool no_collapse = false; + static bool no_menu = false; + + // Demonstrate the various window flags. Typically you would just use the default. + ImGuiWindowFlags window_flags = 0; + if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar; + if (!no_border) window_flags |= ImGuiWindowFlags_ShowBorders; + if (no_resize) window_flags |= ImGuiWindowFlags_NoResize; + if (no_move) window_flags |= ImGuiWindowFlags_NoMove; + if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar; + if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse; + if (!no_menu) window_flags |= ImGuiWindowFlags_MenuBar; + ImGui::SetNextWindowSize(ImVec2(550,680), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("ImGui Demo", p_open, window_flags)) + { + // Early out if the window is collapsed, as an optimization. + ImGui::End(); + return; + } + + //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // 2/3 of the space for widget and 1/3 for labels + ImGui::PushItemWidth(-140); // Right align, keep 140 pixels for labels + + ImGui::Text("Dear ImGui says hello."); + + // Menu + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("Menu")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Examples")) + { + ImGui::MenuItem("Main menu bar", NULL, &show_app_main_menu_bar); + ImGui::MenuItem("Console", NULL, &show_app_console); + ImGui::MenuItem("Log", NULL, &show_app_log); + ImGui::MenuItem("Simple layout", NULL, &show_app_layout); + ImGui::MenuItem("Property editor", NULL, &show_app_property_editor); + ImGui::MenuItem("Long text display", NULL, &show_app_long_text); + ImGui::MenuItem("Auto-resizing window", NULL, &show_app_auto_resize); + ImGui::MenuItem("Constrained-resizing window", NULL, &show_app_constrained_resize); + ImGui::MenuItem("Simple overlay", NULL, &show_app_fixed_overlay); + ImGui::MenuItem("Manipulating window title", NULL, &show_app_manipulating_window_title); + ImGui::MenuItem("Custom rendering", NULL, &show_app_custom_rendering); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Help")) + { + ImGui::MenuItem("Metrics", NULL, &show_app_metrics); + ImGui::MenuItem("Style Editor", NULL, &show_app_style_editor); + ImGui::MenuItem("About ImGui", NULL, &show_app_about); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + ImGui::Spacing(); + if (ImGui::CollapsingHeader("Help")) + { + ImGui::TextWrapped("This window is being created by the ShowTestWindow() function. Please refer to the code for programming reference.\n\nUser Guide:"); + ImGui::ShowUserGuide(); + } + + if (ImGui::CollapsingHeader("Window options")) + { + ImGui::Checkbox("No titlebar", &no_titlebar); ImGui::SameLine(150); + ImGui::Checkbox("No border", &no_border); ImGui::SameLine(300); + ImGui::Checkbox("No resize", &no_resize); + ImGui::Checkbox("No move", &no_move); ImGui::SameLine(150); + ImGui::Checkbox("No scrollbar", &no_scrollbar); ImGui::SameLine(300); + ImGui::Checkbox("No collapse", &no_collapse); + ImGui::Checkbox("No menu", &no_menu); + + if (ImGui::TreeNode("Style")) + { + ImGui::ShowStyleEditor(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Logging")) + { + ImGui::TextWrapped("The logging API redirects all text output so you can easily capture the content of a window or a block. Tree nodes can be automatically expanded. You can also call ImGui::LogText() to output directly to the log without a visual output."); + ImGui::LogButtons(); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Widgets")) + { + if (ImGui::TreeNode("Trees")) + { + if (ImGui::TreeNode("Basic trees")) + { + for (int i = 0; i < 5; i++) + if (ImGui::TreeNode((void*)(intptr_t)i, "Child %d", i)) + { + ImGui::Text("blah blah"); + ImGui::SameLine(); + if (ImGui::SmallButton("print")) printf("Child %d pressed", i); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Advanced, with Selectable nodes")) + { + ShowHelpMarker("This is a more standard looking tree with selectable nodes.\nClick to select, CTRL+Click to toggle, click on arrows or double-click to open."); + static bool align_label_with_current_x_position = false; + ImGui::Checkbox("Align label with current X position)", &align_label_with_current_x_position); + ImGui::Text("Hello!"); + if (align_label_with_current_x_position) + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + + static int selection_mask = (1 << 2); // Dumb representation of what may be user-side selection state. You may carry selection state inside or outside your objects in whatever format you see fit. + int node_clicked = -1; // Temporary storage of what node we have clicked to process selection at the end of the loop. May be a pointer to your own node type, etc. + ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize()*3); // Increase spacing to differentiate leaves from expanded contents. + for (int i = 0; i < 6; i++) + { + // Disable the default open on single-click behavior and pass in Selected flag according to our selection state. + ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ((selection_mask & (1 << i)) ? ImGuiTreeNodeFlags_Selected : 0); + if (i < 3) + { + // Node + bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i); + if (ImGui::IsItemClicked()) + node_clicked = i; + if (node_open) + { + ImGui::Text("Blah blah\nBlah Blah"); + ImGui::TreePop(); + } + } + else + { + // Leaf: The only reason we have a TreeNode at all is to allow selection of the leaf. Otherwise we can use BulletText() or TreeAdvanceToLabelPos()+Text(). + ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "Selectable Leaf %d", i); + if (ImGui::IsItemClicked()) + node_clicked = i; + } + } + if (node_clicked != -1) + { + // Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame. + if (ImGui::GetIO().KeyCtrl) + selection_mask ^= (1 << node_clicked); // CTRL+click to toggle + else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, this commented bit preserve selection when clicking on item that is part of the selection + selection_mask = (1 << node_clicked); // Click to single-select + } + ImGui::PopStyleVar(); + if (align_label_with_current_x_position) + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Collapsing Headers")) + { + static bool closable_group = true; + if (ImGui::CollapsingHeader("Header")) + { + ImGui::Checkbox("Enable extra group", &closable_group); + for (int i = 0; i < 5; i++) + ImGui::Text("Some content %d", i); + } + if (ImGui::CollapsingHeader("Header with a close button", &closable_group)) + { + for (int i = 0; i < 5; i++) + ImGui::Text("More content %d", i); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Bullets")) + { + ImGui::BulletText("Bullet point 1"); + ImGui::BulletText("Bullet point 2\nOn multiple lines"); + ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)"); + ImGui::Bullet(); ImGui::SmallButton("Button"); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Colored Text")) + { + // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. + ImGui::TextColored(ImVec4(1.0f,0.0f,1.0f,1.0f), "Pink"); + ImGui::TextColored(ImVec4(1.0f,1.0f,0.0f,1.0f), "Yellow"); + ImGui::TextDisabled("Disabled"); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Word Wrapping")) + { + // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. + ImGui::TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules suitable for English and possibly other languages."); + ImGui::Spacing(); + + static float wrap_width = 200.0f; + ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); + + ImGui::Text("Test paragraph 1:"); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255,0,255,255)); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + ImGui::Text("The lazy dog is a good dog. This paragraph is made to fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width); + ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255,255,0,255)); + ImGui::PopTextWrapPos(); + + ImGui::Text("Test paragraph 2:"); + pos = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255,0,255,255)); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh"); + ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255,255,0,255)); + ImGui::PopTextWrapPos(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("UTF-8 Text")) + { + // UTF-8 test with Japanese characters + // (needs a suitable font, try Arial Unicode or M+ fonts http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html) + // Most compiler appears to support UTF-8 in source code (with Visual Studio you need to save your file as 'UTF-8 without signature') + // However for the sake for maximum portability here we are *not* including raw UTF-8 character in this source file, instead we encode the string with hexadecimal constants. + // In your own application be reasonable and use UTF-8 in source or retrieve the data from file system! + // Note that characters values are preserved even if the font cannot be displayed, so you can safely copy & paste garbled characters into another application. + ImGui::TextWrapped("CJK text will only appears if the font was loaded with the appropriate CJK character ranges. Call io.Font->LoadFromFileTTF() manually to load extra character ranges."); + ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); + ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); + static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; + ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf)); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Images")) + { + ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!"); + ImVec2 tex_screen_pos = ImGui::GetCursorScreenPos(); + float tex_w = (float)ImGui::GetIO().Fonts->TexWidth; + float tex_h = (float)ImGui::GetIO().Fonts->TexHeight; + ImTextureID tex_id = ImGui::GetIO().Fonts->TexID; + ImGui::Text("%.0fx%.0f", tex_w, tex_h); + ImGui::Image(tex_id, ImVec2(tex_w, tex_h), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128)); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + float focus_sz = 32.0f; + float focus_x = ImGui::GetMousePos().x - tex_screen_pos.x - focus_sz * 0.5f; if (focus_x < 0.0f) focus_x = 0.0f; else if (focus_x > tex_w - focus_sz) focus_x = tex_w - focus_sz; + float focus_y = ImGui::GetMousePos().y - tex_screen_pos.y - focus_sz * 0.5f; if (focus_y < 0.0f) focus_y = 0.0f; else if (focus_y > tex_h - focus_sz) focus_y = tex_h - focus_sz; + ImGui::Text("Min: (%.2f, %.2f)", focus_x, focus_y); + ImGui::Text("Max: (%.2f, %.2f)", focus_x + focus_sz, focus_y + focus_sz); + ImVec2 uv0 = ImVec2((focus_x) / tex_w, (focus_y) / tex_h); + ImVec2 uv1 = ImVec2((focus_x + focus_sz) / tex_w, (focus_y + focus_sz) / tex_h); + ImGui::Image(tex_id, ImVec2(128,128), uv0, uv1, ImColor(255,255,255,255), ImColor(255,255,255,128)); + ImGui::EndTooltip(); + } + ImGui::TextWrapped("And now some textured buttons.."); + static int pressed_count = 0; + for (int i = 0; i < 8; i++) + { + ImGui::PushID(i); + int frame_padding = -1 + i; // -1 = uses default padding + if (ImGui::ImageButton(tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/tex_w,32/tex_h), frame_padding, ImColor(0,0,0,255))) + pressed_count += 1; + ImGui::PopID(); + ImGui::SameLine(); + } + ImGui::NewLine(); + ImGui::Text("Pressed %d times.", pressed_count); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Selectables")) + { + if (ImGui::TreeNode("Basic")) + { + static bool selected[4] = { false, true, false, false }; + ImGui::Selectable("1. I am selectable", &selected[0]); + ImGui::Selectable("2. I am selectable", &selected[1]); + ImGui::Text("3. I am not selectable"); + ImGui::Selectable("4. I am selectable", &selected[2]); + if (ImGui::Selectable("5. I am double clickable", selected[3], ImGuiSelectableFlags_AllowDoubleClick)) + if (ImGui::IsMouseDoubleClicked(0)) + selected[3] = !selected[3]; + ImGui::TreePop(); + } + if (ImGui::TreeNode("Rendering more text into the same block")) + { + static bool selected[3] = { false, false, false }; + ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); + ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(300); ImGui::Text("12,345 bytes"); + ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); + ImGui::TreePop(); + } + if (ImGui::TreeNode("In columns")) + { + ImGui::Columns(3, NULL, false); + static bool selected[16] = { 0 }; + for (int i = 0; i < 16; i++) + { + char label[32]; sprintf(label, "Item %d", i); + if (ImGui::Selectable(label, &selected[i])) {} + ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::TreePop(); + } + if (ImGui::TreeNode("Grid")) + { + static bool selected[16] = { true, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true }; + for (int i = 0; i < 16; i++) + { + ImGui::PushID(i); + if (ImGui::Selectable("Sailor", &selected[i], 0, ImVec2(50,50))) + { + int x = i % 4, y = i / 4; + if (x > 0) selected[i - 1] ^= 1; + if (x < 3) selected[i + 1] ^= 1; + if (y > 0) selected[i - 4] ^= 1; + if (y < 3) selected[i + 4] ^= 1; + } + if ((i % 4) < 3) ImGui::SameLine(); + ImGui::PopID(); + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Filtered Text Input")) + { + static char buf1[64] = ""; ImGui::InputText("default", buf1, 64); + static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal); + static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); + static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); + static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); + struct TextFilters { static int FilterImGuiLetters(ImGuiTextEditCallbackData* data) { if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) return 0; return 1; } }; + static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); + + ImGui::Text("Password input"); + static char bufpass[64] = "password123"; + ImGui::InputText("password", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank); + ImGui::SameLine(); ShowHelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); + ImGui::InputText("password (clear)", bufpass, 64, ImGuiInputTextFlags_CharsNoBlank); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Multi-line Text Input")) + { + static bool read_only = false; + static char text[1024*16] = + "/*\n" + " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n" + " the hexadecimal encoding of one offending instruction,\n" + " more formally, the invalid operand with locked CMPXCHG8B\n" + " instruction bug, is a design flaw in the majority of\n" + " Intel Pentium, Pentium MMX, and Pentium OverDrive\n" + " processors (all in the P5 microarchitecture).\n" + "*/\n\n" + "label:\n" + "\tlock cmpxchg8b eax\n"; + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); + ImGui::Checkbox("Read-only", &read_only); + ImGui::PopStyleVar(); + ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16), ImGuiInputTextFlags_AllowTabInput | (read_only ? ImGuiInputTextFlags_ReadOnly : 0)); + ImGui::TreePop(); + } + + static bool a=false; + if (ImGui::Button("Button")) { printf("Clicked\n"); a ^= 1; } + if (a) + { + ImGui::SameLine(); + ImGui::Text("Thanks for clicking me!"); + } + + static bool check = true; + ImGui::Checkbox("checkbox", &check); + + static int e = 0; + ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine(); + ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); + ImGui::RadioButton("radio c", &e, 2); + + // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. + for (int i = 0; i < 7; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(i/7.0f, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(i/7.0f, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(i/7.0f, 0.8f, 0.8f)); + ImGui::Button("Click"); + ImGui::PopStyleColor(3); + ImGui::PopID(); + } + + ImGui::Text("Hover over me"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("I am a tooltip"); + + ImGui::SameLine(); + ImGui::Text("- or me"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("I am a fancy tooltip"); + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr)); + ImGui::EndTooltip(); + } + + // Testing IMGUI_ONCE_UPON_A_FRAME macro + //for (int i = 0; i < 5; i++) + //{ + // IMGUI_ONCE_UPON_A_FRAME + // { + // ImGui::Text("This will be displayed only once."); + // } + //} + + ImGui::Separator(); + + ImGui::LabelText("label", "Value"); + + static int item = 1; + ImGui::Combo("combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); // Combo using values packed in a single constant string (for really quick combo) + + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK" }; + static int item2 = -1; + ImGui::Combo("combo scroll", &item2, items, IM_ARRAYSIZE(items)); // Combo using proper array. You can also pass a callback to retrieve array value, no need to create/copy an array just for that. + + { + static char str0[128] = "Hello, world!"; + static int i0=123; + static float f0=0.001f; + ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); + ImGui::SameLine(); ShowHelpMarker("Hold SHIFT or use mouse to select text.\n" "CTRL+Left/Right to word jump.\n" "CTRL+A or double-click to select all.\n" "CTRL+X,CTRL+C,CTRL+V clipboard.\n" "CTRL+Z,CTRL+Y undo/redo.\n" "ESCAPE to revert.\n"); + + ImGui::InputInt("input int", &i0); + ImGui::SameLine(); ShowHelpMarker("You can apply arithmetic operators +,*,/ on numerical values.\n e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\nUse +- to subtract.\n"); + + ImGui::InputFloat("input float", &f0, 0.01f, 1.0f); + + static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + ImGui::InputFloat3("input float3", vec4a); + } + + { + static int i1=50, i2=42; + ImGui::DragInt("drag int", &i1, 1); + ImGui::SameLine(); ShowHelpMarker("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input value."); + + ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%.0f%%"); + + static float f1=1.00f, f2=0.0067f; + ImGui::DragFloat("drag float", &f1, 0.005f); + ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); + } + + { + static int i1=0; + ImGui::SliderInt("slider int", &i1, -1, 3); + ImGui::SameLine(); ShowHelpMarker("CTRL+click to input value."); + + static float f1=0.123f, f2=0.0f; + ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); + ImGui::SliderFloat("slider log float", &f2, -10.0f, 10.0f, "%.4f", 3.0f); + static float angle = 0.0f; + ImGui::SliderAngle("slider angle", &angle); + } + + static float col1[3] = { 1.0f,0.0f,0.2f }; + static float col2[4] = { 0.4f,0.7f,0.0f,0.5f }; + ImGui::ColorEdit3("color 1", col1); + ImGui::SameLine(); ShowHelpMarker("Click on the colored square to change edit mode.\nCTRL+click on individual component to input value.\n"); + + ImGui::ColorEdit4("color 2", col2); + + const char* listbox_items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; + static int listbox_item_current = 1; + ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4); + + //static int listbox_item_current2 = 2; + //ImGui::PushItemWidth(-1); + //ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4); + //ImGui::PopItemWidth(); + + if (ImGui::TreeNode("Range Widgets")) + { + ImGui::Unindent(); + + static float begin = 10, end = 90; + static int begin_i = 100, end_i = 1000; + ImGui::DragFloatRange2("range", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%"); + ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %.0f units", "Max: %.0f units"); + + ImGui::Indent(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Multi-component Widgets")) + { + ImGui::Unindent(); + + static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + static int vec4i[4] = { 1, 5, 100, 255 }; + + ImGui::InputFloat2("input float2", vec4f); + ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f); + ImGui::DragInt2("drag int2", vec4i, 1, 0, 255); + ImGui::InputInt2("input int2", vec4i); + ImGui::SliderInt2("slider int2", vec4i, 0, 255); + ImGui::Spacing(); + + ImGui::InputFloat3("input float3", vec4f); + ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f); + ImGui::DragInt3("drag int3", vec4i, 1, 0, 255); + ImGui::InputInt3("input int3", vec4i); + ImGui::SliderInt3("slider int3", vec4i, 0, 255); + ImGui::Spacing(); + + ImGui::InputFloat4("input float4", vec4f); + ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f); + ImGui::InputInt4("input int4", vec4i); + ImGui::DragInt4("drag int4", vec4i, 1, 0, 255); + ImGui::SliderInt4("slider int4", vec4i, 0, 255); + + ImGui::Indent(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Vertical Sliders")) + { + ImGui::Unindent(); + const float spacing = 4; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); + + static int int_value = 0; + ImGui::VSliderInt("##int", ImVec2(18,160), &int_value, 0, 5); + ImGui::SameLine(); + + static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; + ImGui::PushID("set1"); + for (int i = 0; i < 7; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_FrameBg, ImColor::HSV(i/7.0f, 0.5f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImColor::HSV(i/7.0f, 0.6f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImColor::HSV(i/7.0f, 0.7f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, ImColor::HSV(i/7.0f, 0.9f, 0.9f)); + ImGui::VSliderFloat("##v", ImVec2(18,160), &values[i], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values[i]); + ImGui::PopStyleColor(4); + ImGui::PopID(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set2"); + static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f }; + const int rows = 3; + const ImVec2 small_slider_size(18, (160.0f-(rows-1)*spacing)/rows); + for (int nx = 0; nx < 4; nx++) + { + if (nx > 0) ImGui::SameLine(); + ImGui::BeginGroup(); + for (int ny = 0; ny < rows; ny++) + { + ImGui::PushID(nx*rows+ny); + ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values2[nx]); + ImGui::PopID(); + } + ImGui::EndGroup(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set3"); + for (int i = 0; i < 4; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); + ImGui::VSliderFloat("##v", ImVec2(40,160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); + ImGui::PopStyleVar(); + ImGui::PopID(); + } + ImGui::PopID(); + ImGui::PopStyleVar(); + + ImGui::Indent(); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Graphs widgets")) + { + static bool animate = true; + ImGui::Checkbox("Animate", &animate); + + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); + + // Create a dummy array of contiguous float values to plot + // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float and the sizeof() of your structure in the Stride parameter. + static float values[90] = { 0 }; + static int values_offset = 0; + if (animate) + { + static float refresh_time = ImGui::GetTime(); // Create dummy data at fixed 60 hz rate for the demo + for (; ImGui::GetTime() > refresh_time + 1.0f/60.0f; refresh_time += 1.0f/60.0f) + { + static float phase = 0.0f; + values[values_offset] = cosf(phase); + values_offset = (values_offset+1) % IM_ARRAYSIZE(values); + phase += 0.10f*values_offset; + } + } + ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,80)); + ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80)); + + // Use functions to generate output + // FIXME: This is rather awkward because current plot API only pass in indices. We probably want an API passing floats and user provide sample rate/count. + struct Funcs + { + static float Sin(void*, int i) { return sinf(i * 0.1f); } + static float Saw(void*, int i) { return (i & 1) ? 1.0f : 0.0f; } + }; + static int func_type = 0, display_count = 70; + ImGui::Separator(); + ImGui::PushItemWidth(100); ImGui::Combo("func", &func_type, "Sin\0Saw\0"); ImGui::PopItemWidth(); + ImGui::SameLine(); + ImGui::SliderInt("Sample count", &display_count, 1, 400); + float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; + ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80)); + ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80)); + ImGui::Separator(); + + // Animate a simple progress bar + static float progress = 0.0f, progress_dir = 1.0f; + if (animate) + { + progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime; + if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; } + if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; } + } + + // Typically we would use ImVec2(-1.0f,0.0f) to use all available width, or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth. + ImGui::ProgressBar(progress, ImVec2(0.0f,0.0f)); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::Text("Progress Bar"); + + float progress_saturated = (progress < 0.0f) ? 0.0f : (progress > 1.0f) ? 1.0f : progress; + char buf[32]; + sprintf(buf, "%d/%d", (int)(progress_saturated*1753), 1753); + ImGui::ProgressBar(progress, ImVec2(0.f,0.f), buf); + } + + if (ImGui::CollapsingHeader("Layout")) + { + if (ImGui::TreeNode("Child regions")) + { + ImGui::Text("Without border"); + static int line = 50; + bool goto_line = ImGui::Button("Goto"); + ImGui::SameLine(); + ImGui::PushItemWidth(100); + goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue); + ImGui::PopItemWidth(); + ImGui::BeginChild("Sub1", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f,300), false, ImGuiWindowFlags_HorizontalScrollbar); + for (int i = 0; i < 100; i++) + { + ImGui::Text("%04d: scrollable region", i); + if (goto_line && line == i) + ImGui::SetScrollHere(); + } + if (goto_line && line >= 100) + ImGui::SetScrollHere(); + ImGui::EndChild(); + + ImGui::SameLine(); + + ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, 5.0f); + ImGui::BeginChild("Sub2", ImVec2(0,300), true); + ImGui::Text("With border"); + ImGui::Columns(2); + for (int i = 0; i < 100; i++) + { + if (i == 50) + ImGui::NextColumn(); + char buf[32]; + sprintf(buf, "%08x", i*5731); + ImGui::Button(buf, ImVec2(-1.0f, 0.0f)); + } + ImGui::EndChild(); + ImGui::PopStyleVar(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Widgets Width")) + { + static float f = 0.0f; + ImGui::Text("PushItemWidth(100)"); + ImGui::SameLine(); ShowHelpMarker("Fixed width."); + ImGui::PushItemWidth(100); + ImGui::DragFloat("float##1", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(GetWindowWidth() * 0.5f)"); + ImGui::SameLine(); ShowHelpMarker("Half of window width."); + ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); + ImGui::DragFloat("float##2", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(GetContentRegionAvailWidth() * 0.5f)"); + ImGui::SameLine(); ShowHelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)"); + ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f); + ImGui::DragFloat("float##3", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(-100)"); + ImGui::SameLine(); ShowHelpMarker("Align to right edge minus 100"); + ImGui::PushItemWidth(-100); + ImGui::DragFloat("float##4", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(-1)"); + ImGui::SameLine(); ShowHelpMarker("Align to right edge"); + ImGui::PushItemWidth(-1); + ImGui::DragFloat("float##5", &f); + ImGui::PopItemWidth(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Basic Horizontal Layout")) + { + ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceding item)"); + + // Text + ImGui::Text("Two items: Hello"); ImGui::SameLine(); + ImGui::TextColored(ImVec4(1,1,0,1), "Sailor"); + + // Adjust spacing + ImGui::Text("More spacing: Hello"); ImGui::SameLine(0, 20); + ImGui::TextColored(ImVec4(1,1,0,1), "Sailor"); + + // Button + ImGui::AlignFirstTextHeightToWidgets(); + ImGui::Text("Normal buttons"); ImGui::SameLine(); + ImGui::Button("Banana"); ImGui::SameLine(); + ImGui::Button("Apple"); ImGui::SameLine(); + ImGui::Button("Corniflower"); + + // Button + ImGui::Text("Small buttons"); ImGui::SameLine(); + ImGui::SmallButton("Like this one"); ImGui::SameLine(); + ImGui::Text("can fit within a text block."); + + // Aligned to arbitrary position. Easy/cheap column. + ImGui::Text("Aligned"); + ImGui::SameLine(150); ImGui::Text("x=150"); + ImGui::SameLine(300); ImGui::Text("x=300"); + ImGui::Text("Aligned"); + ImGui::SameLine(150); ImGui::SmallButton("x=150"); + ImGui::SameLine(300); ImGui::SmallButton("x=300"); + + // Checkbox + static bool c1=false,c2=false,c3=false,c4=false; + ImGui::Checkbox("My", &c1); ImGui::SameLine(); + ImGui::Checkbox("Tailor", &c2); ImGui::SameLine(); + ImGui::Checkbox("Is", &c3); ImGui::SameLine(); + ImGui::Checkbox("Rich", &c4); + + // Various + static float f0=1.0f, f1=2.0f, f2=3.0f; + ImGui::PushItemWidth(80); + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" }; + static int item = -1; + ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine(); + ImGui::SliderFloat("X", &f0, 0.0f,5.0f); ImGui::SameLine(); + ImGui::SliderFloat("Y", &f1, 0.0f,5.0f); ImGui::SameLine(); + ImGui::SliderFloat("Z", &f2, 0.0f,5.0f); + ImGui::PopItemWidth(); + + ImGui::PushItemWidth(80); + ImGui::Text("Lists:"); + static int selection[4] = { 0, 1, 2, 3 }; + for (int i = 0; i < 4; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::ListBox("", &selection[i], items, IM_ARRAYSIZE(items)); + ImGui::PopID(); + //if (ImGui::IsItemHovered()) ImGui::SetTooltip("ListBox %d hovered", i); + } + ImGui::PopItemWidth(); + + // Dummy + ImVec2 sz(30,30); + ImGui::Button("A", sz); ImGui::SameLine(); + ImGui::Dummy(sz); ImGui::SameLine(); + ImGui::Button("B", sz); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Groups")) + { + ImGui::TextWrapped("(Using ImGui::BeginGroup()/EndGroup() to layout items. BeginGroup() basically locks the horizontal position. EndGroup() bundles the whole group so that you can use functions such as IsItemHovered() on it.)"); + ImGui::BeginGroup(); + { + ImGui::BeginGroup(); + ImGui::Button("AAA"); + ImGui::SameLine(); + ImGui::Button("BBB"); + ImGui::SameLine(); + ImGui::BeginGroup(); + ImGui::Button("CCC"); + ImGui::Button("DDD"); + ImGui::EndGroup(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Group hovered"); + ImGui::SameLine(); + ImGui::Button("EEE"); + ImGui::EndGroup(); + } + // Capture the group size and create widgets using the same size + ImVec2 size = ImGui::GetItemRectSize(); + const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f }; + ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size); + + ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); + ImGui::SameLine(); + ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); + ImGui::EndGroup(); + ImGui::SameLine(); + + ImGui::Button("LEVERAGE\nBUZZWORD", size); + ImGui::SameLine(); + + ImGui::ListBoxHeader("List", size); + ImGui::Selectable("Selected", true); + ImGui::Selectable("Not Selected", false); + ImGui::ListBoxFooter(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Text Baseline Alignment")) + { + ImGui::TextWrapped("(This is testing the vertical alignment that occurs on text to keep it at the same baseline as widgets. Lines only composed of text or \"small\" widgets fit in less vertical spaces than lines with normal widgets)"); + + ImGui::Text("One\nTwo\nThree"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Text("Banana"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("One\nTwo\nThree"); + + ImGui::Button("HOP##1"); ImGui::SameLine(); + ImGui::Text("Banana"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Button("HOP##2"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Button("TEST##1"); ImGui::SameLine(); + ImGui::Text("TEST"); ImGui::SameLine(); + ImGui::SmallButton("TEST##2"); + + ImGui::AlignFirstTextHeightToWidgets(); // If your line starts with text, call this to align it to upcoming widgets. + ImGui::Text("Text aligned to Widget"); ImGui::SameLine(); + ImGui::Button("Widget##1"); ImGui::SameLine(); + ImGui::Text("Widget"); ImGui::SameLine(); + ImGui::SmallButton("Widget##2"); + + // Tree + const float spacing = ImGui::GetStyle().ItemInnerSpacing.x; + ImGui::Button("Button##1"); + ImGui::SameLine(0.0f, spacing); + if (ImGui::TreeNode("Node##1")) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data + + ImGui::AlignFirstTextHeightToWidgets(); // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. Otherwise you can use SmallButton (smaller fit). + bool node_open = ImGui::TreeNode("Node##2"); // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add child content. + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2"); + if (node_open) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data + + // Bullet + ImGui::Button("Button##3"); + ImGui::SameLine(0.0f, spacing); + ImGui::BulletText("Bullet text"); + + ImGui::AlignFirstTextHeightToWidgets(); + ImGui::BulletText("Node"); + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##4"); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Scrolling")) + { + ImGui::TextWrapped("(Use SetScrollHere() or SetScrollFromPosY() to scroll to a given position.)"); + static bool track = true; + static int track_line = 50, scroll_to_px = 200; + ImGui::Checkbox("Track", &track); + ImGui::PushItemWidth(100); + ImGui::SameLine(130); track |= ImGui::DragInt("##line", &track_line, 0.25f, 0, 99, "Line %.0f"); + bool scroll_to = ImGui::Button("Scroll To"); + ImGui::SameLine(130); scroll_to |= ImGui::DragInt("##pos_y", &scroll_to_px, 1.00f, 0, 9999, "y = %.0f px"); + ImGui::PopItemWidth(); + if (scroll_to) track = false; + + for (int i = 0; i < 5; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::BeginGroup(); + ImGui::Text("%s", i == 0 ? "Top" : i == 1 ? "25%" : i == 2 ? "Center" : i == 3 ? "75%" : "Bottom"); + ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(ImGui::GetWindowWidth() * 0.17f, 200.0f), true); + if (scroll_to) + ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_px, i * 0.25f); + for (int line = 0; line < 100; line++) + { + if (track && line == track_line) + { + ImGui::TextColored(ImColor(255,255,0), "Line %d", line); + ImGui::SetScrollHere(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom + } + else + { + ImGui::Text("Line %d", line); + } + } + ImGui::EndChild(); + ImGui::EndGroup(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Horizontal Scrolling")) + { + ImGui::Bullet(); ImGui::TextWrapped("Horizontal scrolling for a window has to be enabled explicitly via the ImGuiWindowFlags_HorizontalScrollbar flag."); + ImGui::Bullet(); ImGui::TextWrapped("You may want to explicitly specify content width by calling SetNextWindowContentWidth() before Begin()."); + static int lines = 7; + ImGui::SliderInt("Lines", &lines, 1, 15); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f)); + ImGui::BeginChild("scrolling", ImVec2(0, ImGui::GetItemsLineHeightWithSpacing()*7 + 30), true, ImGuiWindowFlags_HorizontalScrollbar); + for (int line = 0; line < lines; line++) + { + // Display random stuff (for the sake of this trivial demo we are using basic Button+SameLine. If you want to create your own time line for a real application you may be better off + // manipulating the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets yourself. You may also want to use the lower-level ImDrawList API) + int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3); + for (int n = 0; n < num_buttons; n++) + { + if (n > 0) ImGui::SameLine(); + ImGui::PushID(n + line * 1000); + char num_buf[16]; + const char* label = (!(n%15)) ? "FizzBuzz" : (!(n%3)) ? "Fizz" : (!(n%5)) ? "Buzz" : (sprintf(num_buf, "%d", n), num_buf); + float hue = n*0.05f; + ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(hue, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(hue, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(hue, 0.8f, 0.8f)); + ImGui::Button(label, ImVec2(40.0f + sinf((float)(line + n)) * 20.0f, 0.0f)); + ImGui::PopStyleColor(3); + ImGui::PopID(); + } + } + ImGui::EndChild(); + ImGui::PopStyleVar(2); + float scroll_x_delta = 0.0f; + ImGui::SmallButton("<<"); if (ImGui::IsItemActive()) scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f; + ImGui::SameLine(); ImGui::Text("Scroll from code"); ImGui::SameLine(); + ImGui::SmallButton(">>"); if (ImGui::IsItemActive()) scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f; + if (scroll_x_delta != 0.0f) + { + ImGui::BeginChild("scrolling"); // Demonstrate a trick: you can use Begin to set yourself in the context of another window (here we are already out of your child window) + ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta); + ImGui::End(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Clipping")) + { + static ImVec2 size(100, 100), offset(50, 20); + ImGui::TextWrapped("On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. The system is designed to try minimizing both execution and CPU/GPU rendering cost."); + ImGui::DragFloat2("size", (float*)&size, 0.5f, 0.0f, 200.0f, "%.0f"); + ImGui::TextWrapped("(Click and drag)"); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec4 clip_rect(pos.x, pos.y, pos.x+size.x, pos.y+size.y); + ImGui::InvisibleButton("##dummy", size); + if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) { offset.x += ImGui::GetIO().MouseDelta.x; offset.y += ImGui::GetIO().MouseDelta.y; } + ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x+size.x,pos.y+size.y), ImColor(90,90,120,255)); + ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x+offset.x,pos.y+offset.y), ImColor(255,255,255,255), "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Popups & Modal windows")) + { + if (ImGui::TreeNode("Popups")) + { + ImGui::TextWrapped("When a popup is active, it inhibits interacting with windows that are behind the popup. Clicking outside the popup closes it."); + + static int selected_fish = -1; + const char* names[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" }; + static bool toggles[] = { true, false, false, false, false }; + + // Simple selection popup + // (If you want to show the current selection inside the Button itself, you may want to build a string using the "###" operator to preserve a constant ID with a variable label) + if (ImGui::Button("Select..")) + ImGui::OpenPopup("select"); + ImGui::SameLine(); + ImGui::Text(selected_fish == -1 ? "" : names[selected_fish]); + if (ImGui::BeginPopup("select")) + { + ImGui::Text("Aquarium"); + ImGui::Separator(); + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + if (ImGui::Selectable(names[i])) + selected_fish = i; + ImGui::EndPopup(); + } + + // Showing a menu with toggles + if (ImGui::Button("Toggle..")) + ImGui::OpenPopup("toggle"); + if (ImGui::BeginPopup("toggle")) + { + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + ImGui::MenuItem(names[i], "", &toggles[i]); + if (ImGui::BeginMenu("Sub-menu")) + { + ImGui::MenuItem("Click me"); + ImGui::EndMenu(); + } + + ImGui::Separator(); + ImGui::Text("Tooltip here"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("I am a tooltip over a popup"); + + if (ImGui::Button("Stacked Popup")) + ImGui::OpenPopup("another popup"); + if (ImGui::BeginPopup("another popup")) + { + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + ImGui::MenuItem(names[i], "", &toggles[i]); + if (ImGui::BeginMenu("Sub-menu")) + { + ImGui::MenuItem("Click me"); + ImGui::EndMenu(); + } + ImGui::EndPopup(); + } + ImGui::EndPopup(); + } + + if (ImGui::Button("Popup Menu..")) + ImGui::OpenPopup("FilePopup"); + if (ImGui::BeginPopup("FilePopup")) + { + ShowExampleMenuFile(); + ImGui::EndPopup(); + } + + ImGui::Spacing(); + ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!"); + ImGui::Separator(); + // NB: As a quirk in this very specific example, we want to differentiate the parent of this menu from the parent of the various popup menus above. + // To do so we are encloding the items in a PushID()/PopID() block to make them two different menusets. If we don't, opening any popup above and hovering our menu here + // would open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it, which is the desired behavior for regular menus. + ImGui::PushID("foo"); + ImGui::MenuItem("Menu item", "CTRL+M"); + if (ImGui::BeginMenu("Menu inside a regular window")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::PopID(); + ImGui::Separator(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Context menus")) + { + static float value = 0.5f; + ImGui::Text("Value = %.3f (<-- right-click here)", value); + if (ImGui::BeginPopupContextItem("item context menu")) + { + if (ImGui::Selectable("Set to zero")) value = 0.0f; + if (ImGui::Selectable("Set to PI")) value = 3.1415f; + ImGui::EndPopup(); + } + + static ImVec4 color = ImColor(0.8f, 0.5f, 1.0f, 1.0f); + ImGui::ColorButton(color); + if (ImGui::BeginPopupContextItem("color context menu")) + { + ImGui::Text("Edit color"); + ImGui::ColorEdit3("##edit", (float*)&color); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + ImGui::SameLine(); ImGui::Text("(<-- right-click here)"); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Modals")) + { + ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside the window."); + + if (ImGui::Button("Delete..")) + ImGui::OpenPopup("Delete?"); + if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n"); + ImGui::Separator(); + + //static int dummy_i = 0; + //ImGui::Combo("Combo", &dummy_i, "Delete\0Delete harder\0"); + + static bool dont_ask_me_next_time = false; + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); + ImGui::Checkbox("Don't ask me next time", &dont_ask_me_next_time); + ImGui::PopStyleVar(); + + if (ImGui::Button("OK", ImVec2(120,0))) { ImGui::CloseCurrentPopup(); } + ImGui::SameLine(); + if (ImGui::Button("Cancel", ImVec2(120,0))) { ImGui::CloseCurrentPopup(); } + ImGui::EndPopup(); + } + + if (ImGui::Button("Stacked modals..")) + ImGui::OpenPopup("Stacked 1"); + if (ImGui::BeginPopupModal("Stacked 1")) + { + ImGui::Text("Hello from Stacked The First"); + + if (ImGui::Button("Another one..")) + ImGui::OpenPopup("Stacked 2"); + if (ImGui::BeginPopupModal("Stacked 2")) + { + ImGui::Text("Hello from Stacked The Second"); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Columns")) + { + // Basic columns + if (ImGui::TreeNode("Basic")) + { + ImGui::Text("Without border:"); + ImGui::Columns(3, "mycolumns3", false); // 3-ways, no border + ImGui::Separator(); + for (int n = 0; n < 14; n++) + { + char label[32]; + sprintf(label, "Item %d", n); + if (ImGui::Selectable(label)) {} + //if (ImGui::Button(label, ImVec2(-1,0))) {} + ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::Separator(); + + ImGui::Text("With border:"); + ImGui::Columns(4, "mycolumns"); // 4-ways, with border + ImGui::Separator(); + ImGui::Text("ID"); ImGui::NextColumn(); + ImGui::Text("Name"); ImGui::NextColumn(); + ImGui::Text("Path"); ImGui::NextColumn(); + ImGui::Text("Flags"); ImGui::NextColumn(); + ImGui::Separator(); + const char* names[3] = { "One", "Two", "Three" }; + const char* paths[3] = { "/path/one", "/path/two", "/path/three" }; + static int selected = -1; + for (int i = 0; i < 3; i++) + { + char label[32]; + sprintf(label, "%04d", i); + if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns)) + selected = i; + ImGui::NextColumn(); + ImGui::Text(names[i]); ImGui::NextColumn(); + ImGui::Text(paths[i]); ImGui::NextColumn(); + ImGui::Text("...."); ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + // Scrolling columns + /* + if (ImGui::TreeNode("Scrolling")) + { + ImGui::BeginChild("##header", ImVec2(0, ImGui::GetTextLineHeightWithSpacing()+ImGui::GetStyle().ItemSpacing.y)); + ImGui::Columns(3); + ImGui::Text("ID"); ImGui::NextColumn(); + ImGui::Text("Name"); ImGui::NextColumn(); + ImGui::Text("Path"); ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::EndChild(); + ImGui::BeginChild("##scrollingregion", ImVec2(0, 60)); + ImGui::Columns(3); + for (int i = 0; i < 10; i++) + { + ImGui::Text("%04d", i); ImGui::NextColumn(); + ImGui::Text("Foobar"); ImGui::NextColumn(); + ImGui::Text("/path/foobar/%04d/", i); ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::EndChild(); + ImGui::TreePop(); + } + */ + + // Create multiple items in a same cell before switching to next column + if (ImGui::TreeNode("Mixed items")) + { + ImGui::Columns(3, "mixed"); + ImGui::Separator(); + + ImGui::Text("Hello"); + ImGui::Button("Banana"); + ImGui::NextColumn(); + + ImGui::Text("ImGui"); + ImGui::Button("Apple"); + static float foo = 1.0f; + ImGui::InputFloat("red", &foo, 0.05f, 0, 3); + ImGui::Text("An extra line here."); + ImGui::NextColumn(); + + ImGui::Text("Sailor"); + ImGui::Button("Corniflower"); + static float bar = 1.0f; + ImGui::InputFloat("blue", &bar, 0.05f, 0, 3); + ImGui::NextColumn(); + + if (ImGui::CollapsingHeader("Category A")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category B")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category C")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + // Word wrapping + if (ImGui::TreeNode("Word-wrapping")) + { + ImGui::Columns(2, "word-wrapping"); + ImGui::Separator(); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::TextWrapped("Hello Left"); + ImGui::NextColumn(); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::TextWrapped("Hello Right"); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Borders")) + { + static bool h_borders = true; + static bool v_borders = true; + ImGui::Checkbox("horizontal", &h_borders); + ImGui::SameLine(); + ImGui::Checkbox("vertical", &v_borders); + ImGui::Columns(4, NULL, v_borders); + if (h_borders) ImGui::Separator(); + for (int i = 0; i < 8; i++) + { + ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i); + ImGui::NextColumn(); + } + ImGui::Columns(1); + if (h_borders) ImGui::Separator(); + ImGui::TreePop(); + } + + bool node_open = ImGui::TreeNode("Tree within single cell"); + ImGui::SameLine(); ShowHelpMarker("NB: Tree node must be poped before ending the cell.\nThere's no storage of state per-cell."); + if (node_open) + { + ImGui::Columns(2, "tree items"); + ImGui::Separator(); + if (ImGui::TreeNode("Hello")) { ImGui::BulletText("Sailor"); ImGui::TreePop(); } ImGui::NextColumn(); + if (ImGui::TreeNode("Bonjour")) { ImGui::BulletText("Marin"); ImGui::TreePop(); } ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Filtering")) + { + static ImGuiTextFilter filter; + ImGui::Text("Filter usage:\n" + " \"\" display all lines\n" + " \"xxx\" display lines containing \"xxx\"\n" + " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" + " \"-xxx\" hide lines containing \"xxx\""); + filter.Draw(); + const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; + for (int i = 0; i < IM_ARRAYSIZE(lines); i++) + if (filter.PassFilter(lines[i])) + ImGui::BulletText("%s", lines[i]); + } + + if (ImGui::CollapsingHeader("Keyboard, Mouse & Focus")) + { + if (ImGui::TreeNode("Tabbing")) + { + ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields."); + static char buf[32] = "dummy"; + ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); + ImGui::PushAllowKeyboardFocus(false); + ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf)); + //ImGui::SameLine(); ShowHelperMarker("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets."); + ImGui::PopAllowKeyboardFocus(); + ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Focus from code")) + { + bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine(); + bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine(); + bool focus_3 = ImGui::Button("Focus on 3"); + int has_focus = 0; + static char buf[128] = "click on a button to set focus"; + + if (focus_1) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 1; + + if (focus_2) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 2; + + ImGui::PushAllowKeyboardFocus(false); + if (focus_3) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 3; + ImGui::PopAllowKeyboardFocus(); + if (has_focus) + ImGui::Text("Item with focus: %d", has_focus); + else + ImGui::Text("Item with focus: "); + ImGui::TextWrapped("Cursor & selection are preserved when refocusing last used item in code."); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Dragging")) + { + ImGui::TextWrapped("You can use ImGui::GetMouseDragDelta(0) to query for the dragged amount on any widget."); + ImGui::Button("Drag Me"); + if (ImGui::IsItemActive()) + { + // Draw a line between the button and the mouse cursor + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + draw_list->PushClipRectFullScreen(); + draw_list->AddLine(ImGui::CalcItemRectClosestPoint(ImGui::GetIO().MousePos, true, -2.0f), ImGui::GetIO().MousePos, ImColor(ImGui::GetStyle().Colors[ImGuiCol_Button]), 4.0f); + draw_list->PopClipRect(); + ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f); + ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0); + ImVec2 mouse_delta = ImGui::GetIO().MouseDelta; + ImGui::SameLine(); ImGui::Text("Raw (%.1f, %.1f), WithLockThresold (%.1f, %.1f), MouseDelta (%.1f, %.1f)", value_raw.x, value_raw.y, value_with_lock_threshold.x, value_with_lock_threshold.y, mouse_delta.x, mouse_delta.y); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Keyboard & Mouse State")) + { + ImGuiIO& io = ImGui::GetIO(); + + ImGui::Text("MousePos: (%g, %g)", io.MousePos.x, io.MousePos.y); + ImGui::Text("Mouse down:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } + ImGui::Text("Mouse clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse dbl-clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse released:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseReleased(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("MouseWheel: %.1f", io.MouseWheel); + + ImGui::Text("Keys down:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (io.KeysDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("%d (%.02f secs)", i, io.KeysDownDuration[i]); } + ImGui::Text("Keys pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i)) { ImGui::SameLine(); ImGui::Text("%d", i); } + ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d", i); } + ImGui::Text("KeyMods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : ""); + + ImGui::Text("WantCaptureMouse: %s", io.WantCaptureMouse ? "true" : "false"); + ImGui::Text("WantCaptureKeyboard: %s", io.WantCaptureKeyboard ? "true" : "false"); + ImGui::Text("WantTextInput: %s", io.WantTextInput ? "true" : "false"); + + ImGui::Button("Hovering me sets the\nkeyboard capture flag"); + if (ImGui::IsItemHovered()) + ImGui::CaptureKeyboardFromApp(true); + ImGui::SameLine(); + ImGui::Button("Holding me clears the\nthe keyboard capture flag"); + if (ImGui::IsItemActive()) + ImGui::CaptureKeyboardFromApp(false); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Mouse cursors")) + { + ImGui::TextWrapped("Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. You can also set io.MouseDrawCursor to ask ImGui to render the cursor for you in software."); + ImGui::Checkbox("io.MouseDrawCursor", &ImGui::GetIO().MouseDrawCursor); + ImGui::Text("Hover to see mouse cursors:"); + for (int i = 0; i < ImGuiMouseCursor_Count_; i++) + { + char label[32]; + sprintf(label, "Mouse cursor %d", i); + ImGui::Bullet(); ImGui::Selectable(label, false); + if (ImGui::IsItemHovered()) + ImGui::SetMouseCursor(i); + } + ImGui::TreePop(); + } + } + + ImGui::End(); +} + +void ImGui::ShowStyleEditor(ImGuiStyle* ref) +{ + ImGuiStyle& style = ImGui::GetStyle(); + + // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to the default style) + const ImGuiStyle default_style; // Default style + if (ImGui::Button("Revert Style")) + style = ref ? *ref : default_style; + + if (ref) + { + ImGui::SameLine(); + if (ImGui::Button("Save Style")) + *ref = style; + } + + ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.55f); + + if (ImGui::TreeNode("Rendering")) + { + ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); + ImGui::Checkbox("Anti-aliased shapes", &style.AntiAliasedShapes); + ImGui::PushItemWidth(100); + ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, FLT_MAX, NULL, 2.0f); + if (style.CurveTessellationTol < 0.0f) style.CurveTessellationTol = 0.10f; + ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. + ImGui::PopItemWidth(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Settings")) + { + ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat("ChildWindowRounding", &style.ChildWindowRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); + ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f"); + ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 16.0f, "%.0f"); + ImGui::Text("Alignment"); + ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); + ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); ShowHelpMarker("Alignment applies when a button is larger than its text content."); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Colors")) + { + static int output_dest = 0; + static bool output_only_modified = false; + if (ImGui::Button("Copy Colors")) + { + if (output_dest == 0) + ImGui::LogToClipboard(); + else + ImGui::LogToTTY(); + ImGui::LogText("ImGuiStyle& style = ImGui::GetStyle();" IM_NEWLINE); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const ImVec4& col = style.Colors[i]; + const char* name = ImGui::GetStyleColName(i); + if (!output_only_modified || memcmp(&col, (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0) + ImGui::LogText("style.Colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, name, 22 - (int)strlen(name), "", col.x, col.y, col.z, col.w); + } + ImGui::LogFinish(); + } + ImGui::SameLine(); ImGui::PushItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); ImGui::PopItemWidth(); + ImGui::SameLine(); ImGui::Checkbox("Only Modified Fields", &output_only_modified); + + static ImGuiColorEditMode edit_mode = ImGuiColorEditMode_RGB; + ImGui::RadioButton("RGB", &edit_mode, ImGuiColorEditMode_RGB); + ImGui::SameLine(); + ImGui::RadioButton("HSV", &edit_mode, ImGuiColorEditMode_HSV); + ImGui::SameLine(); + ImGui::RadioButton("HEX", &edit_mode, ImGuiColorEditMode_HEX); + //ImGui::Text("Tip: Click on colored square to change edit mode."); + + static ImGuiTextFilter filter; + filter.Draw("Filter colors", 200); + + ImGui::BeginChild("#colors", ImVec2(0, 300), true, ImGuiWindowFlags_AlwaysVerticalScrollbar); + ImGui::PushItemWidth(-160); + ImGui::ColorEditMode(edit_mode); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const char* name = ImGui::GetStyleColName(i); + if (!filter.PassFilter(name)) + continue; + ImGui::PushID(i); + ImGui::ColorEdit4(name, (float*)&style.Colors[i], true); + if (memcmp(&style.Colors[i], (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0) + { + ImGui::SameLine(); if (ImGui::Button("Revert")) style.Colors[i] = ref ? ref->Colors[i] : default_style.Colors[i]; + if (ref) { ImGui::SameLine(); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i]; } + } + ImGui::PopID(); + } + ImGui::PopItemWidth(); + ImGui::EndChild(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Fonts", "Fonts (%d)", ImGui::GetIO().Fonts->Fonts.Size)) + { + ImGui::SameLine(); ShowHelpMarker("Tip: Load fonts with io.Fonts->AddFontFromFileTTF()\nbefore calling io.Fonts->GetTex* functions."); + ImFontAtlas* atlas = ImGui::GetIO().Fonts; + if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) + { + ImGui::Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128)); + ImGui::TreePop(); + } + ImGui::PushItemWidth(100); + for (int i = 0; i < atlas->Fonts.Size; i++) + { + ImFont* font = atlas->Fonts[i]; + ImGui::BulletText("Font %d: \'%s\', %.2f px, %d glyphs", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size); + ImGui::TreePush((void*)(intptr_t)i); + ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) ImGui::GetIO().FontDefault = font; + ImGui::PushFont(font); + ImGui::Text("The quick brown fox jumps over the lazy dog"); + ImGui::PopFont(); + if (ImGui::TreeNode("Details")) + { + ImGui::DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); // Scale only this font + ImGui::SameLine(); ShowHelpMarker("Note than the default embedded font is NOT meant to be scaled.\n\nFont are currently rendered into bitmaps at a given size at the time of building the atlas. You may oversample them to get some flexibility with scaling. You can also render at multiple sizes and select which one to use at runtime.\n\n(Glimmer of hope: the atlas system should hopefully be rewritten in the future to make scaling more natural and automatic.)"); + ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent); + ImGui::Text("Fallback character: '%c' (%d)", font->FallbackChar, font->FallbackChar); + ImGui::Text("Texture surface: %d pixels (approx) ~ %dx%d", font->MetricsTotalSurface, (int)sqrtf((float)font->MetricsTotalSurface), (int)sqrtf((float)font->MetricsTotalSurface)); + for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) + { + ImFontConfig* cfg = &font->ConfigData[config_i]; + ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d", config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH); + } + if (ImGui::TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) + { + // Display all glyphs of the fonts in separate pages of 256 characters + const ImFont::Glyph* glyph_fallback = font->FallbackGlyph; // Forcefully/dodgily make FindGlyph() return NULL on fallback, which isn't the default behavior. + font->FallbackGlyph = NULL; + for (int base = 0; base < 0x10000; base += 256) + { + int count = 0; + for (int n = 0; n < 256; n++) + count += font->FindGlyph((ImWchar)(base + n)) ? 1 : 0; + if (count > 0 && ImGui::TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base+255, count, count > 1 ? "glyphs" : "glyph")) + { + float cell_spacing = style.ItemSpacing.y; + ImVec2 cell_size(font->FontSize * 1, font->FontSize * 1); + ImVec2 base_pos = ImGui::GetCursorScreenPos(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + for (int n = 0; n < 256; n++) + { + ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size.x + cell_spacing), base_pos.y + (n / 16) * (cell_size.y + cell_spacing)); + ImVec2 cell_p2(cell_p1.x + cell_size.x, cell_p1.y + cell_size.y); + const ImFont::Glyph* glyph = font->FindGlyph((ImWchar)(base+n));; + draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255,255,255,100) : IM_COL32(255,255,255,50)); + font->RenderChar(draw_list, cell_size.x, cell_p1, ImGui::GetColorU32(ImGuiCol_Text), (ImWchar)(base+n)); // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions available to generate a string. + if (glyph && ImGui::IsMouseHoveringRect(cell_p1, cell_p2)) + { + ImGui::BeginTooltip(); + ImGui::Text("Codepoint: U+%04X", base+n); + ImGui::Separator(); + ImGui::Text("XAdvance+1: %.1f", glyph->XAdvance); + ImGui::Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); + ImGui::Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); + ImGui::EndTooltip(); + } + } + ImGui::Dummy(ImVec2((cell_size.x + cell_spacing) * 16, (cell_size.y + cell_spacing) * 16)); + ImGui::TreePop(); + } + } + font->FallbackGlyph = glyph_fallback; + ImGui::TreePop(); + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } + static float window_scale = 1.0f; + ImGui::DragFloat("this window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale only this window + ImGui::DragFloat("global scale", &ImGui::GetIO().FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale everything + ImGui::PopItemWidth(); + ImGui::SetWindowFontScale(window_scale); + ImGui::TreePop(); + } + + ImGui::PopItemWidth(); +} + +// Demonstrate creating a fullscreen menu bar and populating it. +static void ShowExampleAppMainMenuBar() +{ + if (ImGui::BeginMainMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Edit")) + { + if (ImGui::MenuItem("Undo", "CTRL+Z")) {} + if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item + ImGui::Separator(); + if (ImGui::MenuItem("Cut", "CTRL+X")) {} + if (ImGui::MenuItem("Copy", "CTRL+C")) {} + if (ImGui::MenuItem("Paste", "CTRL+V")) {} + ImGui::EndMenu(); + } + ImGui::EndMainMenuBar(); + } +} + +static void ShowExampleMenuFile() +{ + ImGui::MenuItem("(dummy menu)", NULL, false, false); + if (ImGui::MenuItem("New")) {} + if (ImGui::MenuItem("Open", "Ctrl+O")) {} + if (ImGui::BeginMenu("Open Recent")) + { + ImGui::MenuItem("fish_hat.c"); + ImGui::MenuItem("fish_hat.inl"); + ImGui::MenuItem("fish_hat.h"); + if (ImGui::BeginMenu("More..")) + { + ImGui::MenuItem("Hello"); + ImGui::MenuItem("Sailor"); + if (ImGui::BeginMenu("Recurse..")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::EndMenu(); + } + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Save", "Ctrl+S")) {} + if (ImGui::MenuItem("Save As..")) {} + ImGui::Separator(); + if (ImGui::BeginMenu("Options")) + { + static bool enabled = true; + ImGui::MenuItem("Enabled", "", &enabled); + ImGui::BeginChild("child", ImVec2(0, 60), true); + for (int i = 0; i < 10; i++) + ImGui::Text("Scrolling Text %d", i); + ImGui::EndChild(); + static float f = 0.5f; + static int n = 0; + ImGui::SliderFloat("Value", &f, 0.0f, 1.0f); + ImGui::InputFloat("Input", &f, 0.1f); + ImGui::Combo("Combo", &n, "Yes\0No\0Maybe\0\0"); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Colors")) + { + for (int i = 0; i < ImGuiCol_COUNT; i++) + ImGui::MenuItem(ImGui::GetStyleColName((ImGuiCol)i)); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Disabled", false)) // Disabled + { + IM_ASSERT(0); + } + if (ImGui::MenuItem("Checked", NULL, true)) {} + if (ImGui::MenuItem("Quit", "Alt+F4")) {} +} + +// Demonstrate creating a window which gets auto-resized according to its content. +static void ShowExampleAppAutoResize(bool* p_open) +{ + if (!ImGui::Begin("Example: Auto-resizing window", p_open, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::End(); + return; + } + + static int lines = 10; + ImGui::Text("Window will resize every-frame to the size of its content.\nNote that you probably don't want to query the window size to\noutput your content because that would create a feedback loop."); + ImGui::SliderInt("Number of lines", &lines, 1, 20); + for (int i = 0; i < lines; i++) + ImGui::Text("%*sThis is line %d", i*4, "", i); // Pad with space to extend size horizontally + ImGui::End(); +} + +// Demonstrate creating a window with custom resize constraints. +static void ShowExampleAppConstrainedResize(bool* p_open) +{ + struct CustomConstraints // Helper functions to demonstrate programmatic constraints + { + static void Square(ImGuiSizeConstraintCallbackData* data) { data->DesiredSize = ImVec2(IM_MAX(data->DesiredSize.x, data->DesiredSize.y), IM_MAX(data->DesiredSize.x, data->DesiredSize.y)); } + static void Step(ImGuiSizeConstraintCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); } + }; + + static int type = 0; + if (type == 0) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)); // Vertical only + if (type == 1) ImGui::SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)); // Horizontal only + if (type == 2) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)); // Width > 100, Height > 100 + if (type == 3) ImGui::SetNextWindowSizeConstraints(ImVec2(300, 0), ImVec2(400, FLT_MAX)); // Width 300-400 + if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square + if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)100);// Fixed Step + + if (ImGui::Begin("Example: Constrained Resize", p_open)) + { + const char* desc[] = + { + "Resize vertical only", + "Resize horizontal only", + "Width > 100, Height > 100", + "Width 300-400", + "Custom: Always Square", + "Custom: Fixed Steps (100)", + }; + ImGui::Combo("Constraint", &type, desc, IM_ARRAYSIZE(desc)); + if (ImGui::Button("200x200")) ImGui::SetWindowSize(ImVec2(200,200)); ImGui::SameLine(); + if (ImGui::Button("500x500")) ImGui::SetWindowSize(ImVec2(500,500)); ImGui::SameLine(); + if (ImGui::Button("800x200")) ImGui::SetWindowSize(ImVec2(800,200)); + for (int i = 0; i < 10; i++) + ImGui::Text("Hello, sailor! Making this line long enough for the example."); + } + ImGui::End(); +} + +// Demonstrate creating a simple static window with no decoration. +static void ShowExampleAppFixedOverlay(bool* p_open) +{ + ImGui::SetNextWindowPos(ImVec2(10,10)); + if (!ImGui::Begin("Example: Fixed Overlay", p_open, ImVec2(0,0), 0.3f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings)) + { + ImGui::End(); + return; + } + ImGui::Text("Simple overlay\non the top-left side of the screen."); + ImGui::Separator(); + ImGui::Text("Mouse Position: (%.1f,%.1f)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y); + ImGui::End(); +} + +// Demonstrate using "##" and "###" in identifiers to manipulate ID generation. +// Read section "How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs." about ID. +static void ShowExampleAppManipulatingWindowTitle(bool*) +{ + // By default, Windows are uniquely identified by their title. + // You can use the "##" and "###" markers to manipulate the display/ID. + + // Using "##" to display same title but have unique identifier. + ImGui::SetNextWindowPos(ImVec2(100,100), ImGuiSetCond_FirstUseEver); + ImGui::Begin("Same title as another window##1"); + ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique."); + ImGui::End(); + + ImGui::SetNextWindowPos(ImVec2(100,200), ImGuiSetCond_FirstUseEver); + ImGui::Begin("Same title as another window##2"); + ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique."); + ImGui::End(); + + // Using "###" to display a changing title but keep a static identifier "AnimatedTitle" + char buf[128]; + sprintf(buf, "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime()/0.25f)&3], rand()); + ImGui::SetNextWindowPos(ImVec2(100,300), ImGuiSetCond_FirstUseEver); + ImGui::Begin(buf); + ImGui::Text("This window has a changing title."); + ImGui::End(); +} + +// Demonstrate using the low-level ImDrawList to draw custom shapes. +static void ShowExampleAppCustomRendering(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(350,560), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("Example: Custom rendering", p_open)) + { + ImGui::End(); + return; + } + + // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of overloaded operators, etc. + // Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your types and ImVec2/ImVec4. + // ImGui defines overloaded operators but they are internal to imgui.cpp and not exposed outside (to avoid messing with your types) + // In this example we are not using the maths operators! + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + + // Primitives + ImGui::Text("Primitives"); + static float sz = 36.0f; + static ImVec4 col = ImVec4(1.0f,1.0f,0.4f,1.0f); + ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 72.0f, "%.0f"); + ImGui::ColorEdit3("Color", &col.x); + { + const ImVec2 p = ImGui::GetCursorScreenPos(); + const ImU32 col32 = ImColor(col); + float x = p.x + 4.0f, y = p.y + 4.0f, spacing = 8.0f; + for (int n = 0; n < 2; n++) + { + float thickness = (n == 0) ? 1.0f : 4.0f; + draw_list->AddCircle(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 20, thickness); x += sz+spacing; + draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 0.0f, ~0, thickness); x += sz+spacing; + draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ~0, thickness); x += sz+spacing; + draw_list->AddTriangle(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32, thickness); x += sz+spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y ), col32, thickness); x += sz+spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, thickness); x += sz+spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x, y+sz), col32, thickness); x += spacing; + draw_list->AddBezierCurve(ImVec2(x, y), ImVec2(x+sz*1.3f,y+sz*0.3f), ImVec2(x+sz-sz*1.3f,y+sz-sz*0.3f), ImVec2(x+sz, y+sz), col32, thickness); + x = p.x + 4; + y += sz+spacing; + } + draw_list->AddCircleFilled(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 32); x += sz+spacing; + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32); x += sz+spacing; + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f); x += sz+spacing; + draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32); x += sz+spacing; + draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x+sz, y+sz), ImColor(0,0,0), ImColor(255,0,0), ImColor(255,255,0), ImColor(0,255,0)); + ImGui::Dummy(ImVec2((sz+spacing)*8, (sz+spacing)*3)); + } + ImGui::Separator(); + { + static ImVector points; + static bool adding_line = false; + ImGui::Text("Canvas example"); + if (ImGui::Button("Clear")) points.clear(); + if (points.Size >= 2) { ImGui::SameLine(); if (ImGui::Button("Undo")) { points.pop_back(); points.pop_back(); } } + ImGui::Text("Left-click and drag to add lines,\nRight-click to undo"); + + // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered() + // However you can draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos(). + // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max). + ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! + ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available + if (canvas_size.x < 50.0f) canvas_size.x = 50.0f; + if (canvas_size.y < 50.0f) canvas_size.y = 50.0f; + draw_list->AddRectFilledMultiColor(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(50,50,50), ImColor(50,50,60), ImColor(60,60,70), ImColor(50,50,60)); + draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(255,255,255)); + + bool adding_preview = false; + ImGui::InvisibleButton("canvas", canvas_size); + ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); + if (adding_line) + { + adding_preview = true; + points.push_back(mouse_pos_in_canvas); + if (!ImGui::GetIO().MouseDown[0]) + adding_line = adding_preview = false; + } + if (ImGui::IsItemHovered()) + { + if (!adding_line && ImGui::IsMouseClicked(0)) + { + points.push_back(mouse_pos_in_canvas); + adding_line = true; + } + if (ImGui::IsMouseClicked(1) && !points.empty()) + { + adding_line = adding_preview = false; + points.pop_back(); + points.pop_back(); + } + } + draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x+canvas_size.x, canvas_pos.y+canvas_size.y)); // clip lines within the canvas (if we resize it, etc.) + for (int i = 0; i < points.Size - 1; i += 2) + draw_list->AddLine(ImVec2(canvas_pos.x + points[i].x, canvas_pos.y + points[i].y), ImVec2(canvas_pos.x + points[i+1].x, canvas_pos.y + points[i+1].y), IM_COL32(255,255,0,255), 2.0f); + draw_list->PopClipRect(); + if (adding_preview) + points.pop_back(); + } + ImGui::End(); +} + +// Demonstrating creating a simple console window, with scrolling, filtering, completion and history. +// For the console example, here we are using a more C++ like approach of declaring a class to hold the data and the functions. +struct ExampleAppConsole +{ + char InputBuf[256]; + ImVector Items; + bool ScrollToBottom; + ImVector History; + int HistoryPos; // -1: new line, 0..History.Size-1 browsing history. + ImVector Commands; + + ExampleAppConsole() + { + ClearLog(); + memset(InputBuf, 0, sizeof(InputBuf)); + HistoryPos = -1; + Commands.push_back("HELP"); + Commands.push_back("HISTORY"); + Commands.push_back("CLEAR"); + Commands.push_back("CLASSIFY"); // "classify" is here to provide an example of "C"+[tab] completing to "CL" and displaying matches. + AddLog("Welcome to ImGui!"); + } + ~ExampleAppConsole() + { + ClearLog(); + for (int i = 0; i < History.Size; i++) + free(History[i]); + } + + // Portable helpers + static int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } + static int Strnicmp(const char* str1, const char* str2, int n) { int d = 0; while (n > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; n--; } return d; } + static char* Strdup(const char *str) { size_t len = strlen(str) + 1; void* buff = malloc(len); return (char*)memcpy(buff, (const void*)str, len); } + + void ClearLog() + { + for (int i = 0; i < Items.Size; i++) + free(Items[i]); + Items.clear(); + ScrollToBottom = true; + } + + void AddLog(const char* fmt, ...) IM_PRINTFARGS(2) + { + char buf[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args); + buf[IM_ARRAYSIZE(buf)-1] = 0; + va_end(args); + Items.push_back(Strdup(buf)); + ScrollToBottom = true; + } + + void Draw(const char* title, bool* p_open) + { + ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin(title, p_open)) + { + ImGui::End(); + return; + } + + ImGui::TextWrapped("This example implements a console with basic coloring, completion and history. A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc."); + ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion."); + + // TODO: display items starting from the bottom + + if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); + if (ImGui::SmallButton("Add Dummy Error")) AddLog("[error] something went wrong"); ImGui::SameLine(); + if (ImGui::SmallButton("Clear")) ClearLog(); ImGui::SameLine(); + if (ImGui::SmallButton("Scroll to bottom")) ScrollToBottom = true; + //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } + + ImGui::Separator(); + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); + static ImGuiTextFilter filter; + filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); + ImGui::PopStyleVar(); + ImGui::Separator(); + + ImGui::BeginChild("ScrollingRegion", ImVec2(0,-ImGui::GetItemsLineHeightWithSpacing()), false, ImGuiWindowFlags_HorizontalScrollbar); + if (ImGui::BeginPopupContextWindow()) + { + if (ImGui::Selectable("Clear")) ClearLog(); + ImGui::EndPopup(); + } + + // Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); + // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping to only process visible items. + // You can seek and display only the lines that are visible using the ImGuiListClipper helper, if your elements are evenly spaced and you have cheap random access to the elements. + // To use the clipper we could replace the 'for (int i = 0; i < Items.Size; i++)' loop with: + // ImGuiListClipper clipper(Items.Size); + // while (clipper.Step()) + // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + // However take note that you can not use this code as is if a filter is active because it breaks the 'cheap random-access' property. We would need random-access on the post-filtered list. + // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices that passed the filtering test, recomputing this array when user changes the filter, + // and appending newly elements as they are inserted. This is left as a task to the user until we can manage to improve this example code! + // If your items are of variable size you may want to implement code similar to what ImGuiListClipper does. Or split your data into fixed height items to allow random-seeking into your list. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing + for (int i = 0; i < Items.Size; i++) + { + const char* item = Items[i]; + if (!filter.PassFilter(item)) + continue; + ImVec4 col = ImVec4(1.0f,1.0f,1.0f,1.0f); // A better implementation may store a type per-item. For the sample let's just parse the text. + if (strstr(item, "[error]")) col = ImColor(1.0f,0.4f,0.4f,1.0f); + else if (strncmp(item, "# ", 2) == 0) col = ImColor(1.0f,0.78f,0.58f,1.0f); + ImGui::PushStyleColor(ImGuiCol_Text, col); + ImGui::TextUnformatted(item); + ImGui::PopStyleColor(); + } + if (ScrollToBottom) + ImGui::SetScrollHere(); + ScrollToBottom = false; + ImGui::PopStyleVar(); + ImGui::EndChild(); + ImGui::Separator(); + + // Command-line + if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this)) + { + char* input_end = InputBuf+strlen(InputBuf); + while (input_end > InputBuf && input_end[-1] == ' ') input_end--; *input_end = 0; + if (InputBuf[0]) + ExecCommand(InputBuf); + strcpy(InputBuf, ""); + } + + // Demonstrate keeping auto focus on the input box + if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) + ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget + + ImGui::End(); + } + + void ExecCommand(const char* command_line) + { + AddLog("# %s\n", command_line); + + // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal. + HistoryPos = -1; + for (int i = History.Size-1; i >= 0; i--) + if (Stricmp(History[i], command_line) == 0) + { + free(History[i]); + History.erase(History.begin() + i); + break; + } + History.push_back(Strdup(command_line)); + + // Process command + if (Stricmp(command_line, "CLEAR") == 0) + { + ClearLog(); + } + else if (Stricmp(command_line, "HELP") == 0) + { + AddLog("Commands:"); + for (int i = 0; i < Commands.Size; i++) + AddLog("- %s", Commands[i]); + } + else if (Stricmp(command_line, "HISTORY") == 0) + { + for (int i = History.Size >= 10 ? History.Size - 10 : 0; i < History.Size; i++) + AddLog("%3d: %s\n", i, History[i]); + } + else + { + AddLog("Unknown command: '%s'\n", command_line); + } + } + + static int TextEditCallbackStub(ImGuiTextEditCallbackData* data) // In C++11 you are better off using lambdas for this sort of forwarding callbacks + { + ExampleAppConsole* console = (ExampleAppConsole*)data->UserData; + return console->TextEditCallback(data); + } + + int TextEditCallback(ImGuiTextEditCallbackData* data) + { + //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd); + switch (data->EventFlag) + { + case ImGuiInputTextFlags_CallbackCompletion: + { + // Example of TEXT COMPLETION + + // Locate beginning of current word + const char* word_end = data->Buf + data->CursorPos; + const char* word_start = word_end; + while (word_start > data->Buf) + { + const char c = word_start[-1]; + if (c == ' ' || c == '\t' || c == ',' || c == ';') + break; + word_start--; + } + + // Build a list of candidates + ImVector candidates; + for (int i = 0; i < Commands.Size; i++) + if (Strnicmp(Commands[i], word_start, (int)(word_end-word_start)) == 0) + candidates.push_back(Commands[i]); + + if (candidates.Size == 0) + { + // No match + AddLog("No match for \"%.*s\"!\n", (int)(word_end-word_start), word_start); + } + else if (candidates.Size == 1) + { + // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing + data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start)); + data->InsertChars(data->CursorPos, candidates[0]); + data->InsertChars(data->CursorPos, " "); + } + else + { + // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" + int match_len = (int)(word_end - word_start); + for (;;) + { + int c = 0; + bool all_candidates_matches = true; + for (int i = 0; i < candidates.Size && all_candidates_matches; i++) + if (i == 0) + c = toupper(candidates[i][match_len]); + else if (c == 0 || c != toupper(candidates[i][match_len])) + all_candidates_matches = false; + if (!all_candidates_matches) + break; + match_len++; + } + + if (match_len > 0) + { + data->DeleteChars((int)(word_start - data->Buf), (int)(word_end-word_start)); + data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); + } + + // List matches + AddLog("Possible matches:\n"); + for (int i = 0; i < candidates.Size; i++) + AddLog("- %s\n", candidates[i]); + } + + break; + } + case ImGuiInputTextFlags_CallbackHistory: + { + // Example of HISTORY + const int prev_history_pos = HistoryPos; + if (data->EventKey == ImGuiKey_UpArrow) + { + if (HistoryPos == -1) + HistoryPos = History.Size - 1; + else if (HistoryPos > 0) + HistoryPos--; + } + else if (data->EventKey == ImGuiKey_DownArrow) + { + if (HistoryPos != -1) + if (++HistoryPos >= History.Size) + HistoryPos = -1; + } + + // A better implementation would preserve the data on the current input line along with cursor position. + if (prev_history_pos != HistoryPos) + { + data->CursorPos = data->SelectionStart = data->SelectionEnd = data->BufTextLen = (int)snprintf(data->Buf, (size_t)data->BufSize, "%s", (HistoryPos >= 0) ? History[HistoryPos] : ""); + data->BufDirty = true; + } + } + } + return 0; + } +}; + +static void ShowExampleAppConsole(bool* p_open) +{ + static ExampleAppConsole console; + console.Draw("Example: Console", p_open); +} + +// Usage: +// static ExampleAppLog my_log; +// my_log.AddLog("Hello %d world\n", 123); +// my_log.Draw("title"); +struct ExampleAppLog +{ + ImGuiTextBuffer Buf; + ImGuiTextFilter Filter; + ImVector LineOffsets; // Index to lines offset + bool ScrollToBottom; + + void Clear() { Buf.clear(); LineOffsets.clear(); } + + void AddLog(const char* fmt, ...) IM_PRINTFARGS(2) + { + int old_size = Buf.size(); + va_list args; + va_start(args, fmt); + Buf.appendv(fmt, args); + va_end(args); + for (int new_size = Buf.size(); old_size < new_size; old_size++) + if (Buf[old_size] == '\n') + LineOffsets.push_back(old_size); + ScrollToBottom = true; + } + + void Draw(const char* title, bool* p_open = NULL) + { + ImGui::SetNextWindowSize(ImVec2(500,400), ImGuiSetCond_FirstUseEver); + ImGui::Begin(title, p_open); + if (ImGui::Button("Clear")) Clear(); + ImGui::SameLine(); + bool copy = ImGui::Button("Copy"); + ImGui::SameLine(); + Filter.Draw("Filter", -100.0f); + ImGui::Separator(); + ImGui::BeginChild("scrolling", ImVec2(0,0), false, ImGuiWindowFlags_HorizontalScrollbar); + if (copy) ImGui::LogToClipboard(); + + if (Filter.IsActive()) + { + const char* buf_begin = Buf.begin(); + const char* line = buf_begin; + for (int line_no = 0; line != NULL; line_no++) + { + const char* line_end = (line_no < LineOffsets.Size) ? buf_begin + LineOffsets[line_no] : NULL; + if (Filter.PassFilter(line, line_end)) + ImGui::TextUnformatted(line, line_end); + line = line_end && line_end[1] ? line_end + 1 : NULL; + } + } + else + { + ImGui::TextUnformatted(Buf.begin()); + } + + if (ScrollToBottom) + ImGui::SetScrollHere(1.0f); + ScrollToBottom = false; + ImGui::EndChild(); + ImGui::End(); + } +}; + +// Demonstrate creating a simple log window with basic filtering. +static void ShowExampleAppLog(bool* p_open) +{ + static ExampleAppLog log; + + // Demo fill + static float last_time = -1.0f; + float time = ImGui::GetTime(); + if (time - last_time >= 0.3f) + { + const char* random_words[] = { "system", "info", "warning", "error", "fatal", "notice", "log" }; + log.AddLog("[%s] Hello, time is %.1f, rand() %d\n", random_words[rand() % IM_ARRAYSIZE(random_words)], time, (int)rand()); + last_time = time; + } + + log.Draw("Example: Log", p_open); +} + +// Demonstrate create a window with multiple child windows. +static void ShowExampleAppLayout(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiSetCond_FirstUseEver); + if (ImGui::Begin("Example: Layout", p_open, ImGuiWindowFlags_MenuBar)) + { + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Close")) *p_open = false; + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + // left + static int selected = 0; + ImGui::BeginChild("left pane", ImVec2(150, 0), true); + for (int i = 0; i < 100; i++) + { + char label[128]; + sprintf(label, "MyObject %d", i); + if (ImGui::Selectable(label, selected == i)) + selected = i; + } + ImGui::EndChild(); + ImGui::SameLine(); + + // right + ImGui::BeginGroup(); + ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetItemsLineHeightWithSpacing())); // Leave room for 1 line below us + ImGui::Text("MyObject: %d", selected); + ImGui::Separator(); + ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "); + ImGui::EndChild(); + ImGui::BeginChild("buttons"); + if (ImGui::Button("Revert")) {} + ImGui::SameLine(); + if (ImGui::Button("Save")) {} + ImGui::EndChild(); + ImGui::EndGroup(); + } + ImGui::End(); +} + +// Demonstrate create a simple property editor. +static void ShowExampleAppPropertyEditor(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(430,450), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("Example: Property editor", p_open)) + { + ImGui::End(); + return; + } + + ShowHelpMarker("This example shows how you may implement a property editor using two columns.\nAll objects/fields data are dummies here.\nRemember that in many simple cases, you can use ImGui::SameLine(xxx) to position\nyour cursor horizontally instead of using the Columns() API."); + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2,2)); + ImGui::Columns(2); + ImGui::Separator(); + + struct funcs + { + static void ShowDummyObject(const char* prefix, int uid) + { + ImGui::PushID(uid); // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. + ImGui::AlignFirstTextHeightToWidgets(); // Text and Tree nodes are less high than regular widgets, here we add vertical spacing to make the tree lines equal high. + bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid); + ImGui::NextColumn(); + ImGui::AlignFirstTextHeightToWidgets(); + ImGui::Text("my sailor is rich"); + ImGui::NextColumn(); + if (node_open) + { + static float dummy_members[8] = { 0.0f,0.0f,1.0f,3.1416f,100.0f,999.0f }; + for (int i = 0; i < 8; i++) + { + ImGui::PushID(i); // Use field index as identifier. + if (i < 2) + { + ShowDummyObject("Child", 424242); + } + else + { + ImGui::AlignFirstTextHeightToWidgets(); + // Here we use a Selectable (instead of Text) to highlight on hover + //ImGui::Text("Field_%d", i); + char label[32]; + sprintf(label, "Field_%d", i); + ImGui::Bullet(); + ImGui::Selectable(label); + ImGui::NextColumn(); + ImGui::PushItemWidth(-1); + if (i >= 5) + ImGui::InputFloat("##value", &dummy_members[i], 1.0f); + else + ImGui::DragFloat("##value", &dummy_members[i], 0.01f); + ImGui::PopItemWidth(); + ImGui::NextColumn(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + ImGui::PopID(); + } + }; + + // Iterate dummy objects with dummy members (all the same data) + for (int obj_i = 0; obj_i < 3; obj_i++) + funcs::ShowDummyObject("Object", obj_i); + + ImGui::Columns(1); + ImGui::Separator(); + ImGui::PopStyleVar(); + ImGui::End(); +} + +// Demonstrate/test rendering huge amount of text, and the incidence of clipping. +static void ShowExampleAppLongText(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("Example: Long text display", p_open)) + { + ImGui::End(); + return; + } + + static int test_type = 0; + static ImGuiTextBuffer log; + static int lines = 0; + ImGui::Text("Printing unusually long amount of text."); + ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped manually\0Multiple calls to Text(), not clipped\0"); + ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size()); + if (ImGui::Button("Clear")) { log.clear(); lines = 0; } + ImGui::SameLine(); + if (ImGui::Button("Add 1000 lines")) + { + for (int i = 0; i < 1000; i++) + log.append("%i The quick brown fox jumps over the lazy dog\n", lines+i); + lines += 1000; + } + ImGui::BeginChild("Log"); + switch (test_type) + { + case 0: + // Single call to TextUnformatted() with a big buffer + ImGui::TextUnformatted(log.begin(), log.end()); + break; + case 1: + { + // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + ImGuiListClipper clipper(lines); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); + ImGui::PopStyleVar(); + break; + } + case 2: + // Multiple calls to Text(), not clipped (slow) + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + for (int i = 0; i < lines; i++) + ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); + ImGui::PopStyleVar(); + break; + } + ImGui::EndChild(); + ImGui::End(); +} + +// End of Demo code +#else + +void ImGui::ShowTestWindow(bool*) {} +void ImGui::ShowUserGuide() {} +void ImGui::ShowStyleEditor(ImGuiStyle*) {} + +#endif diff --git a/SampleFramework12/v1.01/ImGui/imgui_draw.cpp b/SampleFramework12/v1.01/ImGui/imgui_draw.cpp new file mode 100644 index 0000000..c73e9b6 --- /dev/null +++ b/SampleFramework12/v1.01/ImGui/imgui_draw.cpp @@ -0,0 +1,2420 @@ +// dear imgui, v1.50 +// (drawing and font code) + +// Contains implementation for +// - ImDrawList +// - ImDrawData +// - ImFontAtlas +// - ImFont +// - Default font data + +#include "PCH.h" + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#define IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_PLACEMENT_NEW +#include "imgui_internal.h" + +#include // vsnprintf, sscanf, printf +#if !defined(alloca) +#ifdef _WIN32 +#include // alloca +#elif (defined(__FreeBSD__) || defined(FreeBSD_kernel) || defined(__DragonFly__)) && !defined(__GLIBC__) +#include // alloca. FreeBSD uses stdlib.h unless GLIBC +#else +#include // alloca +#endif +#endif + +#ifdef _MSC_VER +#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#define snprintf _snprintf +#endif + +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#if __has_warning("-Wreserved-id-macro") +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // +#endif +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers +#endif + +//------------------------------------------------------------------------- +// STB libraries implementation +//------------------------------------------------------------------------- + +//#define IMGUI_STB_NAMESPACE ImGuiStb +//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION +//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION + +#ifdef IMGUI_STB_NAMESPACE +namespace IMGUI_STB_NAMESPACE +{ +#endif + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 4456) // declaration of 'xx' hides previous local declaration +#endif + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wunused-function" +#pragma clang diagnostic ignored "-Wmissing-prototypes" +#endif + +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wtype-limits" // warning: comparison is always true due to limited range of data type [-Wtype-limits] +#endif + +#define STBRP_ASSERT(x) IM_ASSERT(x) +#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION +#define STBRP_STATIC +#define STB_RECT_PACK_IMPLEMENTATION +#endif +#include "stb_rect_pack.h" + +#define STBTT_malloc(x,u) ((void)(u), ImGui::MemAlloc(x)) +#define STBTT_free(x,u) ((void)(u), ImGui::MemFree(x)) +#define STBTT_assert(x) IM_ASSERT(x) +#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +#define STBTT_STATIC +#define STB_TRUETYPE_IMPLEMENTATION +#else +#define STBTT_DEF extern +#endif +#include "stb_truetype.h" + +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +#ifdef IMGUI_STB_NAMESPACE +} // namespace ImGuiStb +using namespace IMGUI_STB_NAMESPACE; +#endif + +//----------------------------------------------------------------------------- +// ImDrawList +//----------------------------------------------------------------------------- + +static const ImVec4 GNullClipRect(-8192.0f, -8192.0f, +8192.0f, +8192.0f); // Large values that are easy to encode in a few bits+shift + +void ImDrawList::Clear() +{ + CmdBuffer.resize(0); + IdxBuffer.resize(0); + VtxBuffer.resize(0); + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.resize(0); + _TextureIdStack.resize(0); + _Path.resize(0); + _ChannelsCurrent = 0; + _ChannelsCount = 1; + // NB: Do not clear channels so our allocations are re-used after the first frame. +} + +void ImDrawList::ClearFreeMemory() +{ + CmdBuffer.clear(); + IdxBuffer.clear(); + VtxBuffer.clear(); + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.clear(); + _TextureIdStack.clear(); + _Path.clear(); + _ChannelsCurrent = 0; + _ChannelsCount = 1; + for (int i = 0; i < _Channels.Size; i++) + { + if (i == 0) memset(&_Channels[0], 0, sizeof(_Channels[0])); // channel 0 is a copy of CmdBuffer/IdxBuffer, don't destruct again + _Channels[i].CmdBuffer.clear(); + _Channels[i].IdxBuffer.clear(); + } + _Channels.clear(); +} + +// Use macros because C++ is a terrible language, we want guaranteed inline, no code in header, and no overhead in Debug mode +#define GetCurrentClipRect() (_ClipRectStack.Size ? _ClipRectStack.Data[_ClipRectStack.Size-1] : GNullClipRect) +#define GetCurrentTextureId() (_TextureIdStack.Size ? _TextureIdStack.Data[_TextureIdStack.Size-1] : NULL) + +void ImDrawList::AddDrawCmd() +{ + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = GetCurrentClipRect(); + draw_cmd.TextureId = GetCurrentTextureId(); + + IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w); + CmdBuffer.push_back(draw_cmd); +} + +void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) +{ + ImDrawCmd* current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; + if (!current_cmd || current_cmd->ElemCount != 0 || current_cmd->UserCallback != NULL) + { + AddDrawCmd(); + current_cmd = &CmdBuffer.back(); + } + current_cmd->UserCallback = callback; + current_cmd->UserCallbackData = callback_data; + + AddDrawCmd(); // Force a new command after us (see comment below) +} + +// Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. +// The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. +void ImDrawList::UpdateClipRect() +{ + // If current command is used with different settings we need to add a new command + const ImVec4 curr_clip_rect = GetCurrentClipRect(); + ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size-1] : NULL; + if (!curr_cmd || (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) + { + AddDrawCmd(); + return; + } + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; + if (curr_cmd->ElemCount == 0 && prev_cmd && memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL) + CmdBuffer.pop_back(); + else + curr_cmd->ClipRect = curr_clip_rect; +} + +void ImDrawList::UpdateTextureID() +{ + // If current command is used with different settings we need to add a new command + const ImTextureID curr_texture_id = GetCurrentTextureId(); + ImDrawCmd* curr_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; + if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) + { + AddDrawCmd(); + return; + } + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; + if (prev_cmd && prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->UserCallback == NULL) + CmdBuffer.pop_back(); + else + curr_cmd->TextureId = curr_texture_id; +} + +#undef GetCurrentClipRect +#undef GetCurrentTextureId + +// Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) +void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect) +{ + ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y); + if (intersect_with_current_clip_rect && _ClipRectStack.Size) + { + ImVec4 current = _ClipRectStack.Data[_ClipRectStack.Size-1]; + if (cr.x < current.x) cr.x = current.x; + if (cr.y < current.y) cr.y = current.y; + if (cr.z > current.z) cr.z = current.z; + if (cr.w > current.w) cr.w = current.w; + } + cr.z = ImMax(cr.x, cr.z); + cr.w = ImMax(cr.y, cr.w); + + _ClipRectStack.push_back(cr); + UpdateClipRect(); +} + +void ImDrawList::PushClipRectFullScreen() +{ + PushClipRect(ImVec2(GNullClipRect.x, GNullClipRect.y), ImVec2(GNullClipRect.z, GNullClipRect.w)); + //PushClipRect(GetVisibleRect()); // FIXME-OPT: This would be more correct but we're not supposed to access ImGuiContext from here? +} + +void ImDrawList::PopClipRect() +{ + IM_ASSERT(_ClipRectStack.Size > 0); + _ClipRectStack.pop_back(); + UpdateClipRect(); +} + +void ImDrawList::PushTextureID(const ImTextureID& texture_id) +{ + _TextureIdStack.push_back(texture_id); + UpdateTextureID(); +} + +void ImDrawList::PopTextureID() +{ + IM_ASSERT(_TextureIdStack.Size > 0); + _TextureIdStack.pop_back(); + UpdateTextureID(); +} + +void ImDrawList::ChannelsSplit(int channels_count) +{ + IM_ASSERT(_ChannelsCurrent == 0 && _ChannelsCount == 1); + int old_channels_count = _Channels.Size; + if (old_channels_count < channels_count) + _Channels.resize(channels_count); + _ChannelsCount = channels_count; + + // _Channels[] (24 bytes each) hold storage that we'll swap with this->_CmdBuffer/_IdxBuffer + // The content of _Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. + // When we switch to the next channel, we'll copy _CmdBuffer/_IdxBuffer into _Channels[0] and then _Channels[1] into _CmdBuffer/_IdxBuffer + memset(&_Channels[0], 0, sizeof(ImDrawChannel)); + for (int i = 1; i < channels_count; i++) + { + if (i >= old_channels_count) + { + IM_PLACEMENT_NEW(&_Channels[i]) ImDrawChannel(); + } + else + { + _Channels[i].CmdBuffer.resize(0); + _Channels[i].IdxBuffer.resize(0); + } + if (_Channels[i].CmdBuffer.Size == 0) + { + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = _ClipRectStack.back(); + draw_cmd.TextureId = _TextureIdStack.back(); + _Channels[i].CmdBuffer.push_back(draw_cmd); + } + } +} + +void ImDrawList::ChannelsMerge() +{ + // Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. + if (_ChannelsCount <= 1) + return; + + ChannelsSetCurrent(0); + if (CmdBuffer.Size && CmdBuffer.back().ElemCount == 0) + CmdBuffer.pop_back(); + + int new_cmd_buffer_count = 0, new_idx_buffer_count = 0; + for (int i = 1; i < _ChannelsCount; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (ch.CmdBuffer.Size && ch.CmdBuffer.back().ElemCount == 0) + ch.CmdBuffer.pop_back(); + new_cmd_buffer_count += ch.CmdBuffer.Size; + new_idx_buffer_count += ch.IdxBuffer.Size; + } + CmdBuffer.resize(CmdBuffer.Size + new_cmd_buffer_count); + IdxBuffer.resize(IdxBuffer.Size + new_idx_buffer_count); + + ImDrawCmd* cmd_write = CmdBuffer.Data + CmdBuffer.Size - new_cmd_buffer_count; + _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size - new_idx_buffer_count; + for (int i = 1; i < _ChannelsCount; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (int sz = ch.CmdBuffer.Size) { memcpy(cmd_write, ch.CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } + if (int sz = ch.IdxBuffer.Size) { memcpy(_IdxWritePtr, ch.IdxBuffer.Data, sz * sizeof(ImDrawIdx)); _IdxWritePtr += sz; } + } + AddDrawCmd(); + _ChannelsCount = 1; +} + +void ImDrawList::ChannelsSetCurrent(int idx) +{ + IM_ASSERT(idx < _ChannelsCount); + if (_ChannelsCurrent == idx) return; + memcpy(&_Channels.Data[_ChannelsCurrent].CmdBuffer, &CmdBuffer, sizeof(CmdBuffer)); // copy 12 bytes, four times + memcpy(&_Channels.Data[_ChannelsCurrent].IdxBuffer, &IdxBuffer, sizeof(IdxBuffer)); + _ChannelsCurrent = idx; + memcpy(&CmdBuffer, &_Channels.Data[_ChannelsCurrent].CmdBuffer, sizeof(CmdBuffer)); + memcpy(&IdxBuffer, &_Channels.Data[_ChannelsCurrent].IdxBuffer, sizeof(IdxBuffer)); + _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size; +} + +// NB: this can be called with negative count for removing primitives (as long as the result does not underflow) +void ImDrawList::PrimReserve(int idx_count, int vtx_count) +{ + ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size-1]; + draw_cmd.ElemCount += idx_count; + + int vtx_buffer_size = VtxBuffer.Size; + VtxBuffer.resize(vtx_buffer_size + vtx_count); + _VtxWritePtr = VtxBuffer.Data + vtx_buffer_size; + + int idx_buffer_size = IdxBuffer.Size; + IdxBuffer.resize(idx_buffer_size + idx_count); + _IdxWritePtr = IdxBuffer.Data + idx_buffer_size; +} + +// Fully unrolled with inline call to keep our debug builds decently fast. +void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv(GImGui->FontTexUvWhitePixel); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a, const ImVec2& uv_c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv_b(uv_c.x, uv_a.y), uv_d(uv_a.x, uv_c.y); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) +{ + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +// TODO: Thickness anti-aliased lines cap are missing their AA fringe. +void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, bool closed, float thickness, bool anti_aliased) +{ + if (points_count < 2) + return; + + const ImVec2 uv = GImGui->FontTexUvWhitePixel; + anti_aliased &= GImGui->Style.AntiAliasedLines; + //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug + + int count = points_count; + if (!closed) + count = points_count-1; + + const bool thick_line = thickness > 1.0f; + if (anti_aliased) + { + // Anti-aliased stroke + const float AA_SIZE = 1.0f; + const ImU32 col_trans = col & IM_COL32(255,255,255,0); + + const int idx_count = thick_line ? count*18 : count*12; + const int vtx_count = thick_line ? points_count*4 : points_count*3; + PrimReserve(idx_count, vtx_count); + + // Temporary buffer + ImVec2* temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); + ImVec2* temp_points = temp_normals + points_count; + + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + ImVec2 diff = points[i2] - points[i1]; + diff *= ImInvLength(diff, 1.0f); + temp_normals[i1].x = diff.y; + temp_normals[i1].y = -diff.x; + } + if (!closed) + temp_normals[points_count-1] = temp_normals[points_count-2]; + + if (!thick_line) + { + if (!closed) + { + temp_points[0] = points[0] + temp_normals[0] * AA_SIZE; + temp_points[1] = points[0] - temp_normals[0] * AA_SIZE; + temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * AA_SIZE; + temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * AA_SIZE; + } + + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+3; + + // Average normals + ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + dm *= AA_SIZE; + temp_points[i2*2+0] = points[i2] + dm; + temp_points[i2*2+1] = points[i2] - dm; + + // Add indexes + _IdxWritePtr[0] = (ImDrawIdx)(idx2+0); _IdxWritePtr[1] = (ImDrawIdx)(idx1+0); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+0); + _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10]= (ImDrawIdx)(idx2+0); _IdxWritePtr[11]= (ImDrawIdx)(idx2+1); + _IdxWritePtr += 12; + + idx1 = idx2; + } + + // Add vertexes + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; + _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col_trans; + _VtxWritePtr += 3; + } + } + else + { + const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; + if (!closed) + { + temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness); + temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness); + temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[(points_count-1)*4+0] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); + temp_points[(points_count-1)*4+1] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness); + temp_points[(points_count-1)*4+2] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness); + temp_points[(points_count-1)*4+3] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); + } + + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+4; + + // Average normals + ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + ImVec2 dm_out = dm * (half_inner_thickness + AA_SIZE); + ImVec2 dm_in = dm * half_inner_thickness; + temp_points[i2*4+0] = points[i2] + dm_out; + temp_points[i2*4+1] = points[i2] + dm_in; + temp_points[i2*4+2] = points[i2] - dm_in; + temp_points[i2*4+3] = points[i2] - dm_out; + + // Add indexes + _IdxWritePtr[0] = (ImDrawIdx)(idx2+1); _IdxWritePtr[1] = (ImDrawIdx)(idx1+1); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+1); + _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10] = (ImDrawIdx)(idx2+0); _IdxWritePtr[11] = (ImDrawIdx)(idx2+1); + _IdxWritePtr[12] = (ImDrawIdx)(idx2+2); _IdxWritePtr[13] = (ImDrawIdx)(idx1+2); _IdxWritePtr[14] = (ImDrawIdx)(idx1+3); + _IdxWritePtr[15] = (ImDrawIdx)(idx1+3); _IdxWritePtr[16] = (ImDrawIdx)(idx2+3); _IdxWritePtr[17] = (ImDrawIdx)(idx2+2); + _IdxWritePtr += 18; + + idx1 = idx2; + } + + // Add vertexes + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = temp_points[i*4+0]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col_trans; + _VtxWritePtr[1].pos = temp_points[i*4+1]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = temp_points[i*4+2]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = temp_points[i*4+3]; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col_trans; + _VtxWritePtr += 4; + } + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // Non Anti-aliased Stroke + const int idx_count = count*6; + const int vtx_count = count*4; // FIXME-OPT: Not sharing edges + PrimReserve(idx_count, vtx_count); + + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + const ImVec2& p1 = points[i1]; + const ImVec2& p2 = points[i2]; + ImVec2 diff = p2 - p1; + diff *= ImInvLength(diff, 1.0f); + + const float dx = diff.x * (thickness * 0.5f); + const float dy = diff.y * (thickness * 0.5f); + _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+2); + _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx+3); + _IdxWritePtr += 6; + _VtxCurrentIdx += 4; + } + } +} + +void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col, bool anti_aliased) +{ + const ImVec2 uv = GImGui->FontTexUvWhitePixel; + anti_aliased &= GImGui->Style.AntiAliasedShapes; + //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug + + if (anti_aliased) + { + // Anti-aliased Fill + const float AA_SIZE = 1.0f; + const ImU32 col_trans = col & IM_COL32(255,255,255,0); + const int idx_count = (points_count-2)*3 + points_count*6; + const int vtx_count = (points_count*2); + PrimReserve(idx_count, vtx_count); + + // Add indexes for fill + unsigned int vtx_inner_idx = _VtxCurrentIdx; + unsigned int vtx_outer_idx = _VtxCurrentIdx+1; + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+((i-1)<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx+(i<<1)); + _IdxWritePtr += 3; + } + + // Compute normals + ImVec2* temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); + for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + { + const ImVec2& p0 = points[i0]; + const ImVec2& p1 = points[i1]; + ImVec2 diff = p1 - p0; + diff *= ImInvLength(diff, 1.0f); + temp_normals[i0].x = diff.y; + temp_normals[i0].y = -diff.x; + } + + for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + { + // Average normals + const ImVec2& n0 = temp_normals[i0]; + const ImVec2& n1 = temp_normals[i1]; + ImVec2 dm = (n0 + n1) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + dm *= AA_SIZE * 0.5f; + + // Add vertices + _VtxWritePtr[0].pos = (points[i1] - dm); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; // Inner + _VtxWritePtr[1].pos = (points[i1] + dm); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; // Outer + _VtxWritePtr += 2; + + // Add indexes for fringes + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+(i0<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); + _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx+(i1<<1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); + _IdxWritePtr += 6; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // Non Anti-aliased Fill + const int idx_count = (points_count-2)*3; + const int vtx_count = points_count; + PrimReserve(idx_count, vtx_count); + for (int i = 0; i < vtx_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr++; + } + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+i-1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+i); + _IdxWritePtr += 3; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } +} + +void ImDrawList::PathArcToFast(const ImVec2& centre, float radius, int amin, int amax) +{ + static ImVec2 circle_vtx[12]; + static bool circle_vtx_builds = false; + const int circle_vtx_count = IM_ARRAYSIZE(circle_vtx); + if (!circle_vtx_builds) + { + for (int i = 0; i < circle_vtx_count; i++) + { + const float a = ((float)i / (float)circle_vtx_count) * 2*IM_PI; + circle_vtx[i].x = cosf(a); + circle_vtx[i].y = sinf(a); + } + circle_vtx_builds = true; + } + + if (amin > amax) return; + if (radius == 0.0f) + { + _Path.push_back(centre); + } + else + { + _Path.reserve(_Path.Size + (amax - amin + 1)); + for (int a = amin; a <= amax; a++) + { + const ImVec2& c = circle_vtx[a % circle_vtx_count]; + _Path.push_back(ImVec2(centre.x + c.x * radius, centre.y + c.y * radius)); + } + } +} + +void ImDrawList::PathArcTo(const ImVec2& centre, float radius, float amin, float amax, int num_segments) +{ + if (radius == 0.0f) + _Path.push_back(centre); + _Path.reserve(_Path.Size + (num_segments + 1)); + for (int i = 0; i <= num_segments; i++) + { + const float a = amin + ((float)i / (float)num_segments) * (amax - amin); + _Path.push_back(ImVec2(centre.x + cosf(a) * radius, centre.y + sinf(a) * radius)); + } +} + +static void PathBezierToCasteljau(ImVector* path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level) +{ + float dx = x4 - x1; + float dy = y4 - y1; + float d2 = ((x2 - x4) * dy - (y2 - y4) * dx); + float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); + d2 = (d2 >= 0) ? d2 : -d2; + d3 = (d3 >= 0) ? d3 : -d3; + if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy)) + { + path->push_back(ImVec2(x4, y4)); + } + else if (level < 10) + { + float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f; + float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f; + float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f; + float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f; + float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f; + float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f; + + PathBezierToCasteljau(path, x1,y1, x12,y12, x123,y123, x1234,y1234, tess_tol, level+1); + PathBezierToCasteljau(path, x1234,y1234, x234,y234, x34,y34, x4,y4, tess_tol, level+1); + } +} + +void ImDrawList::PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments) +{ + ImVec2 p1 = _Path.back(); + if (num_segments == 0) + { + // Auto-tessellated + PathBezierToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, GImGui->Style.CurveTessellationTol, 0); + } + else + { + float t_step = 1.0f / (float)num_segments; + for (int i_step = 1; i_step <= num_segments; i_step++) + { + float t = t_step * i_step; + float u = 1.0f - t; + float w1 = u*u*u; + float w2 = 3*u*u*t; + float w3 = 3*u*t*t; + float w4 = t*t*t; + _Path.push_back(ImVec2(w1*p1.x + w2*p2.x + w3*p3.x + w4*p4.x, w1*p1.y + w2*p2.y + w3*p3.y + w4*p4.y)); + } + } +} + +void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, int rounding_corners) +{ + float r = rounding; + r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f ) - 1.0f); + r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f ) - 1.0f); + + if (r <= 0.0f || rounding_corners == 0) + { + PathLineTo(a); + PathLineTo(ImVec2(b.x,a.y)); + PathLineTo(b); + PathLineTo(ImVec2(a.x,b.y)); + } + else + { + const float r0 = (rounding_corners & 1) ? r : 0.0f; + const float r1 = (rounding_corners & 2) ? r : 0.0f; + const float r2 = (rounding_corners & 4) ? r : 0.0f; + const float r3 = (rounding_corners & 8) ? r : 0.0f; + PathArcToFast(ImVec2(a.x+r0,a.y+r0), r0, 6, 9); + PathArcToFast(ImVec2(b.x-r1,a.y+r1), r1, 9, 12); + PathArcToFast(ImVec2(b.x-r2,b.y-r2), r2, 0, 3); + PathArcToFast(ImVec2(a.x+r3,b.y-r3), r3, 3, 6); + } +} + +void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + PathLineTo(a + ImVec2(0.5f,0.5f)); + PathLineTo(b + ImVec2(0.5f,0.5f)); + PathStroke(col, false, thickness); +} + +// a: upper-left, b: lower-right. we don't render 1 px sized rectangles properly. +void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners_flags, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.5f,0.5f), rounding, rounding_corners_flags); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners_flags) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + if (rounding > 0.0f) + { + PathRect(a, b, rounding, rounding_corners_flags); + PathFillConvex(col); + } + else + { + PrimReserve(6, 4); + PrimRect(a, b, col); + } +} + +void ImDrawList::AddRectFilledMultiColor(const ImVec2& a, const ImVec2& c, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left) +{ + if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) & IM_COL32_A_MASK) == 0) + return; + + const ImVec2 uv = GImGui->FontTexUvWhitePixel; + PrimReserve(6, 4); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+3)); + PrimWriteVtx(a, uv, col_upr_left); + PrimWriteVtx(ImVec2(c.x, a.y), uv, col_upr_right); + PrimWriteVtx(c, uv, col_bot_right); + PrimWriteVtx(ImVec2(a.x, c.y), uv, col_bot_left); +} + +void ImDrawList::AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathLineTo(d); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathLineTo(d); + PathFillConvex(col); +} + +void ImDrawList::AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathFillConvex(col); +} + +void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(centre, radius-0.5f, 0.0f, a_max, num_segments); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(centre, radius, 0.0f, a_max, num_segments); + PathFillConvex(col); +} + +void ImDrawList::AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(pos0); + PathBezierCurveTo(cp0, cp1, pos1, num_segments); + PathStroke(col, false, thickness); +} + +void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + if (text_end == NULL) + text_end = text_begin + strlen(text_begin); + if (text_begin == text_end) + return; + + // Note: This is one of the few instance of breaking the encapsulation of ImDrawList, as we pull this from ImGui state, but it is just SO useful. + // Might just move Font/FontSize to ImDrawList? + if (font == NULL) + font = GImGui->Font; + if (font_size == 0.0f) + font_size = GImGui->FontSize; + + IM_ASSERT(font->ContainerAtlas->TexID == _TextureIdStack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. + + ImVec4 clip_rect = _ClipRectStack.back(); + if (cpu_fine_clip_rect) + { + clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x); + clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect->y); + clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z); + clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w); + } + font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip_rect != NULL); +} + +void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end) +{ + AddText(GImGui->Font, GImGui->FontSize, pos, col, text_begin, text_end); +} + +void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + // FIXME-OPT: This is wasting draw calls. + const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); + if (push_texture_id) + PushTextureID(user_texture_id); + + PrimReserve(6, 4); + PrimRectUV(a, b, uv_a, uv_b, col); + + if (push_texture_id) + PopTextureID(); +} + +void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); + if (push_texture_id) + PushTextureID(user_texture_id); + + PrimReserve(6, 4); + PrimQuadUV(a, b, c, d, uv_a, uv_b, uv_c, uv_d, col); + + if (push_texture_id) + PopTextureID(); +} + +//----------------------------------------------------------------------------- +// ImDrawData +//----------------------------------------------------------------------------- + +// For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! +void ImDrawData::DeIndexAllBuffers() +{ + ImVector new_vtx_buffer; + TotalVtxCount = TotalIdxCount = 0; + for (int i = 0; i < CmdListsCount; i++) + { + ImDrawList* cmd_list = CmdLists[i]; + if (cmd_list->IdxBuffer.empty()) + continue; + new_vtx_buffer.resize(cmd_list->IdxBuffer.Size); + for (int j = 0; j < cmd_list->IdxBuffer.Size; j++) + new_vtx_buffer[j] = cmd_list->VtxBuffer[cmd_list->IdxBuffer[j]]; + cmd_list->VtxBuffer.swap(new_vtx_buffer); + cmd_list->IdxBuffer.resize(0); + TotalVtxCount += cmd_list->VtxBuffer.Size; + } +} + +// Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. +void ImDrawData::ScaleClipRects(const ImVec2& scale) +{ + for (int i = 0; i < CmdListsCount; i++) + { + ImDrawList* cmd_list = CmdLists[i]; + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + ImDrawCmd* cmd = &cmd_list->CmdBuffer[cmd_i]; + cmd->ClipRect = ImVec4(cmd->ClipRect.x * scale.x, cmd->ClipRect.y * scale.y, cmd->ClipRect.z * scale.x, cmd->ClipRect.w * scale.y); + } + } +} + +//----------------------------------------------------------------------------- +// ImFontAtlas +//----------------------------------------------------------------------------- + +ImFontConfig::ImFontConfig() +{ + FontData = NULL; + FontDataSize = 0; + FontDataOwnedByAtlas = true; + FontNo = 0; + SizePixels = 0.0f; + OversampleH = 3; + OversampleV = 1; + PixelSnapH = false; + GlyphExtraSpacing = ImVec2(0.0f, 0.0f); + GlyphOffset = ImVec2(0.0f, 0.0f); + GlyphRanges = NULL; + MergeMode = false; + DstFont = NULL; + memset(Name, 0, sizeof(Name)); +} + +ImFontAtlas::ImFontAtlas() +{ + TexID = NULL; + TexPixelsAlpha8 = NULL; + TexPixelsRGBA32 = NULL; + TexWidth = TexHeight = TexDesiredWidth = 0; + TexUvWhitePixel = ImVec2(0, 0); +} + +ImFontAtlas::~ImFontAtlas() +{ + Clear(); +} + +void ImFontAtlas::ClearInputData() +{ + for (int i = 0; i < ConfigData.Size; i++) + if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas) + { + ImGui::MemFree(ConfigData[i].FontData); + ConfigData[i].FontData = NULL; + } + + // When clearing this we lose access to the font name and other information used to build the font. + for (int i = 0; i < Fonts.Size; i++) + if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size) + { + Fonts[i]->ConfigData = NULL; + Fonts[i]->ConfigDataCount = 0; + } + ConfigData.clear(); +} + +void ImFontAtlas::ClearTexData() +{ + if (TexPixelsAlpha8) + ImGui::MemFree(TexPixelsAlpha8); + if (TexPixelsRGBA32) + ImGui::MemFree(TexPixelsRGBA32); + TexPixelsAlpha8 = NULL; + TexPixelsRGBA32 = NULL; +} + +void ImFontAtlas::ClearFonts() +{ + for (int i = 0; i < Fonts.Size; i++) + { + Fonts[i]->~ImFont(); + ImGui::MemFree(Fonts[i]); + } + Fonts.clear(); +} + +void ImFontAtlas::Clear() +{ + ClearInputData(); + ClearTexData(); + ClearFonts(); +} + +void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + // Build atlas on demand + if (TexPixelsAlpha8 == NULL) + { + if (ConfigData.empty()) + AddFontDefault(); + Build(); + } + + *out_pixels = TexPixelsAlpha8; + if (out_width) *out_width = TexWidth; + if (out_height) *out_height = TexHeight; + if (out_bytes_per_pixel) *out_bytes_per_pixel = 1; +} + +void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + // Convert to RGBA32 format on demand + // Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp + if (!TexPixelsRGBA32) + { + unsigned char* pixels; + GetTexDataAsAlpha8(&pixels, NULL, NULL); + TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)(TexWidth * TexHeight * 4)); + const unsigned char* src = pixels; + unsigned int* dst = TexPixelsRGBA32; + for (int n = TexWidth * TexHeight; n > 0; n--) + *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++)); + } + + *out_pixels = (unsigned char*)TexPixelsRGBA32; + if (out_width) *out_width = TexWidth; + if (out_height) *out_height = TexHeight; + if (out_bytes_per_pixel) *out_bytes_per_pixel = 4; +} + +ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) +{ + IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0); + IM_ASSERT(font_cfg->SizePixels > 0.0f); + + // Create new font + if (!font_cfg->MergeMode) + { + ImFont* font = (ImFont*)ImGui::MemAlloc(sizeof(ImFont)); + IM_PLACEMENT_NEW(font) ImFont(); + Fonts.push_back(font); + } + else + { + IM_ASSERT(!Fonts.empty()); // When using MergeMode make sure that a font has already been added before. You can use ImGui::AddFontDefault() to add the default imgui font. + } + + ConfigData.push_back(*font_cfg); + ImFontConfig& new_font_cfg = ConfigData.back(); + if (!new_font_cfg.DstFont) + new_font_cfg.DstFont = Fonts.back(); + if (!new_font_cfg.FontDataOwnedByAtlas) + { + new_font_cfg.FontData = ImGui::MemAlloc(new_font_cfg.FontDataSize); + new_font_cfg.FontDataOwnedByAtlas = true; + memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); + } + + // Invalidate texture + ClearTexData(); + return new_font_cfg.DstFont; +} + +// Default font TTF is compressed with stb_compress then base85 encoded (see extra_fonts/binary_to_compressed_c.cpp for encoder) +static unsigned int stb_decompress_length(unsigned char *input); +static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length); +static const char* GetDefaultCompressedFontDataTTFBase85(); +static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; } +static void Decode85(const unsigned char* src, unsigned char* dst) +{ + while (*src) + { + unsigned int tmp = Decode85Byte(src[0]) + 85*(Decode85Byte(src[1]) + 85*(Decode85Byte(src[2]) + 85*(Decode85Byte(src[3]) + 85*Decode85Byte(src[4])))); + dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianness. + src += 5; + dst += 4; + } +} + +// Load embedded ProggyClean.ttf at size 13, disable oversampling +ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) +{ + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (!font_cfg_template) + { + font_cfg.OversampleH = font_cfg.OversampleV = 1; + font_cfg.PixelSnapH = true; + } + if (font_cfg.Name[0] == '\0') strcpy(font_cfg.Name, "ProggyClean.ttf, 13px"); + + const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85(); + ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, 13.0f, &font_cfg, GetGlyphRangesDefault()); + return font; +} + +ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + int data_size = 0; + void* data = ImFileLoadToMemory(filename, "rb", &data_size, 0); + if (!data) + { + IM_ASSERT(0); // Could not load file. + return NULL; + } + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (font_cfg.Name[0] == '\0') + { + // Store a short copy of filename into into the font name for convenience + const char* p; + for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {} + snprintf(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s, %.0fpx", p, size_pixels); + } + return AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg, glyph_ranges); +} + +// NBM Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build(). +ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + font_cfg.FontData = ttf_data; + font_cfg.FontDataSize = ttf_size; + font_cfg.SizePixels = size_pixels; + if (glyph_ranges) + font_cfg.GlyphRanges = glyph_ranges; + return AddFont(&font_cfg); +} + +ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + const unsigned int buf_decompressed_size = stb_decompress_length((unsigned char*)compressed_ttf_data); + unsigned char* buf_decompressed_data = (unsigned char *)ImGui::MemAlloc(buf_decompressed_size); + stb_decompress(buf_decompressed_data, (unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size); + + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + font_cfg.FontDataOwnedByAtlas = true; + return AddFontFromMemoryTTF(buf_decompressed_data, (int)buf_decompressed_size, size_pixels, &font_cfg, glyph_ranges); +} + +ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) +{ + int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; + void* compressed_ttf = ImGui::MemAlloc((size_t)compressed_ttf_size); + Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf); + ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); + ImGui::MemFree(compressed_ttf); + return font; +} + +bool ImFontAtlas::Build() +{ + IM_ASSERT(ConfigData.Size > 0); + + TexID = NULL; + TexWidth = TexHeight = 0; + TexUvWhitePixel = ImVec2(0, 0); + ClearTexData(); + + struct ImFontTempBuildData + { + stbtt_fontinfo FontInfo; + stbrp_rect* Rects; + stbtt_pack_range* Ranges; + int RangesCount; + }; + ImFontTempBuildData* tmp_array = (ImFontTempBuildData*)ImGui::MemAlloc((size_t)ConfigData.Size * sizeof(ImFontTempBuildData)); + + // Initialize font information early (so we can error without any cleanup) + count glyphs + int total_glyph_count = 0; + int total_glyph_range_count = 0; + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + + IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == this)); + const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo); + IM_ASSERT(font_offset >= 0); + if (!stbtt_InitFont(&tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset)) + return false; + + // Count glyphs + if (!cfg.GlyphRanges) + cfg.GlyphRanges = GetGlyphRangesDefault(); + for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) + { + total_glyph_count += (in_range[1] - in_range[0]) + 1; + total_glyph_range_count++; + } + } + + // Start packing. We need a known width for the skyline algorithm. Using a cheap heuristic here to decide of width. User can override TexDesiredWidth if they wish. + // After packing is done, width shouldn't matter much, but some API/GPU have texture size limitations and increasing width can decrease height. + TexWidth = (TexDesiredWidth > 0) ? TexDesiredWidth : (total_glyph_count > 4000) ? 4096 : (total_glyph_count > 2000) ? 2048 : (total_glyph_count > 1000) ? 1024 : 512; + TexHeight = 0; + const int max_tex_height = 1024*32; + stbtt_pack_context spc; + stbtt_PackBegin(&spc, NULL, TexWidth, max_tex_height, 0, 1, NULL); + + // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). + ImVector extra_rects; + RenderCustomTexData(0, &extra_rects); + stbtt_PackSetOversampling(&spc, 1, 1); + stbrp_pack_rects((stbrp_context*)spc.pack_info, &extra_rects[0], extra_rects.Size); + for (int i = 0; i < extra_rects.Size; i++) + if (extra_rects[i].was_packed) + TexHeight = ImMax(TexHeight, extra_rects[i].y + extra_rects[i].h); + + // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) + int buf_packedchars_n = 0, buf_rects_n = 0, buf_ranges_n = 0; + stbtt_packedchar* buf_packedchars = (stbtt_packedchar*)ImGui::MemAlloc(total_glyph_count * sizeof(stbtt_packedchar)); + stbrp_rect* buf_rects = (stbrp_rect*)ImGui::MemAlloc(total_glyph_count * sizeof(stbrp_rect)); + stbtt_pack_range* buf_ranges = (stbtt_pack_range*)ImGui::MemAlloc(total_glyph_range_count * sizeof(stbtt_pack_range)); + memset(buf_packedchars, 0, total_glyph_count * sizeof(stbtt_packedchar)); + memset(buf_rects, 0, total_glyph_count * sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity. + memset(buf_ranges, 0, total_glyph_range_count * sizeof(stbtt_pack_range)); + + // First font pass: pack all glyphs (no rendering at this point, we are working with rectangles in an infinitely tall texture at this point) + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + + // Setup ranges + int glyph_count = 0; + int glyph_ranges_count = 0; + for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) + { + glyph_count += (in_range[1] - in_range[0]) + 1; + glyph_ranges_count++; + } + tmp.Ranges = buf_ranges + buf_ranges_n; + tmp.RangesCount = glyph_ranges_count; + buf_ranges_n += glyph_ranges_count; + for (int i = 0; i < glyph_ranges_count; i++) + { + const ImWchar* in_range = &cfg.GlyphRanges[i * 2]; + stbtt_pack_range& range = tmp.Ranges[i]; + range.font_size = cfg.SizePixels; + range.first_unicode_codepoint_in_range = in_range[0]; + range.num_chars = (in_range[1] - in_range[0]) + 1; + range.chardata_for_range = buf_packedchars + buf_packedchars_n; + buf_packedchars_n += range.num_chars; + } + + // Pack + tmp.Rects = buf_rects + buf_rects_n; + buf_rects_n += glyph_count; + stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV); + int n = stbtt_PackFontRangesGatherRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects); + stbrp_pack_rects((stbrp_context*)spc.pack_info, tmp.Rects, n); + + // Extend texture height + for (int i = 0; i < n; i++) + if (tmp.Rects[i].was_packed) + TexHeight = ImMax(TexHeight, tmp.Rects[i].y + tmp.Rects[i].h); + } + IM_ASSERT(buf_rects_n == total_glyph_count); + IM_ASSERT(buf_packedchars_n == total_glyph_count); + IM_ASSERT(buf_ranges_n == total_glyph_range_count); + + // Create texture + TexHeight = ImUpperPowerOfTwo(TexHeight); + TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(TexWidth * TexHeight); + memset(TexPixelsAlpha8, 0, TexWidth * TexHeight); + spc.pixels = TexPixelsAlpha8; + spc.height = TexHeight; + + // Second pass: render characters + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV); + stbtt_PackFontRangesRenderIntoRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects); + tmp.Rects = NULL; + } + + // End packing + stbtt_PackEnd(&spc); + ImGui::MemFree(buf_rects); + buf_rects = NULL; + + // Third pass: setup ImFont and glyphs for runtime + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + ImFont* dst_font = cfg.DstFont; // We can have multiple input fonts writing into a same destination font (when using MergeMode=true) + + float font_scale = stbtt_ScaleForPixelHeight(&tmp.FontInfo, cfg.SizePixels); + int unscaled_ascent, unscaled_descent, unscaled_line_gap; + stbtt_GetFontVMetrics(&tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); + + float ascent = unscaled_ascent * font_scale; + float descent = unscaled_descent * font_scale; + if (!cfg.MergeMode) + { + dst_font->ContainerAtlas = this; + dst_font->ConfigData = &cfg; + dst_font->ConfigDataCount = 0; + dst_font->FontSize = cfg.SizePixels; + dst_font->Ascent = ascent; + dst_font->Descent = descent; + dst_font->Glyphs.resize(0); + dst_font->MetricsTotalSurface = 0; + } + dst_font->ConfigDataCount++; + float off_x = cfg.GlyphOffset.x; + float off_y = cfg.GlyphOffset.y; + + dst_font->FallbackGlyph = NULL; // Always clear fallback so FindGlyph can return NULL. It will be set again in BuildLookupTable() + for (int i = 0; i < tmp.RangesCount; i++) + { + stbtt_pack_range& range = tmp.Ranges[i]; + for (int char_idx = 0; char_idx < range.num_chars; char_idx += 1) + { + const stbtt_packedchar& pc = range.chardata_for_range[char_idx]; + if (!pc.x0 && !pc.x1 && !pc.y0 && !pc.y1) + continue; + + const int codepoint = range.first_unicode_codepoint_in_range + char_idx; + if (cfg.MergeMode && dst_font->FindGlyph((unsigned short)codepoint)) + continue; + + stbtt_aligned_quad q; + float dummy_x = 0.0f, dummy_y = 0.0f; + stbtt_GetPackedQuad(range.chardata_for_range, TexWidth, TexHeight, char_idx, &dummy_x, &dummy_y, &q, 0); + + dst_font->Glyphs.resize(dst_font->Glyphs.Size + 1); + ImFont::Glyph& glyph = dst_font->Glyphs.back(); + glyph.Codepoint = (ImWchar)codepoint; + glyph.X0 = q.x0 + off_x; glyph.Y0 = q.y0 + off_y; glyph.X1 = q.x1 + off_x; glyph.Y1 = q.y1 + off_y; + glyph.U0 = q.s0; glyph.V0 = q.t0; glyph.U1 = q.s1; glyph.V1 = q.t1; + glyph.Y0 += (float)(int)(dst_font->Ascent + 0.5f); + glyph.Y1 += (float)(int)(dst_font->Ascent + 0.5f); + glyph.XAdvance = (pc.xadvance + cfg.GlyphExtraSpacing.x); // Bake spacing into XAdvance + if (cfg.PixelSnapH) + glyph.XAdvance = (float)(int)(glyph.XAdvance + 0.5f); + dst_font->MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * TexWidth + 1.99f) * (int)((glyph.V1 - glyph.V0) * TexHeight + 1.99f); // +1 to account for average padding, +0.99 to round + } + } + cfg.DstFont->BuildLookupTable(); + } + + // Cleanup temporaries + ImGui::MemFree(buf_packedchars); + ImGui::MemFree(buf_ranges); + ImGui::MemFree(tmp_array); + + // Render into our custom data block + RenderCustomTexData(1, &extra_rects); + + return true; +} + +void ImFontAtlas::RenderCustomTexData(int pass, void* p_rects) +{ + // A work of art lies ahead! (. = white layer, X = black layer, others are blank) + // The white texels on the top left are the ones we'll use everywhere in ImGui to render filled shapes. + const int TEX_DATA_W = 90; + const int TEX_DATA_H = 27; + const char texture_data[TEX_DATA_W*TEX_DATA_H+1] = + { + "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX" + "..- -X.....X- X.X - X.X -X.....X - X.....X" + "--- -XXX.XXX- X...X - X...X -X....X - X....X" + "X - X.X - X.....X - X.....X -X...X - X...X" + "XX - X.X -X.......X- X.......X -X..X.X - X.X..X" + "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X" + "X..X - X.X - X.X - X.X -XX X.X - X.X XX" + "X...X - X.X - X.X - XX X.X XX - X.X - X.X " + "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X " + "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X " + "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X " + "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X " + "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X " + "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X " + "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X " + "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X " + "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX " + "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------" + "X.X X..X - -X.......X- X.......X - XX XX - " + "XX X..X - - X.....X - X.....X - X.X X.X - " + " X..X - X...X - X...X - X..X X..X - " + " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - " + "------------ - X - X -X.....................X- " + " ----------------------------------- X...XXXXXXXXXXXXX...X - " + " - X..X X..X - " + " - X.X X.X - " + " - XX XX - " + }; + + ImVector& rects = *(ImVector*)p_rects; + if (pass == 0) + { + // Request rectangles + stbrp_rect r; + memset(&r, 0, sizeof(r)); + r.w = (TEX_DATA_W*2)+1; + r.h = TEX_DATA_H+1; + rects.push_back(r); + } + else if (pass == 1) + { + // Render/copy pixels + const stbrp_rect& r = rects[0]; + for (int y = 0, n = 0; y < TEX_DATA_H; y++) + for (int x = 0; x < TEX_DATA_W; x++, n++) + { + const int offset0 = (int)(r.x + x) + (int)(r.y + y) * TexWidth; + const int offset1 = offset0 + 1 + TEX_DATA_W; + TexPixelsAlpha8[offset0] = texture_data[n] == '.' ? 0xFF : 0x00; + TexPixelsAlpha8[offset1] = texture_data[n] == 'X' ? 0xFF : 0x00; + } + const ImVec2 tex_uv_scale(1.0f / TexWidth, 1.0f / TexHeight); + TexUvWhitePixel = ImVec2((r.x + 0.5f) * tex_uv_scale.x, (r.y + 0.5f) * tex_uv_scale.y); + + // Setup mouse cursors + const ImVec2 cursor_datas[ImGuiMouseCursor_Count_][3] = + { + // Pos ........ Size ......... Offset ...... + { ImVec2(0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow + { ImVec2(13,0), ImVec2(7,16), ImVec2( 4, 8) }, // ImGuiMouseCursor_TextInput + { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_Move + { ImVec2(21,0), ImVec2( 9,23), ImVec2( 5,11) }, // ImGuiMouseCursor_ResizeNS + { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 5) }, // ImGuiMouseCursor_ResizeEW + { ImVec2(73,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNESW + { ImVec2(55,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNWSE + }; + + for (int type = 0; type < ImGuiMouseCursor_Count_; type++) + { + ImGuiMouseCursorData& cursor_data = GImGui->MouseCursorData[type]; + ImVec2 pos = cursor_datas[type][0] + ImVec2((float)r.x, (float)r.y); + const ImVec2 size = cursor_datas[type][1]; + cursor_data.Type = type; + cursor_data.Size = size; + cursor_data.HotOffset = cursor_datas[type][2]; + cursor_data.TexUvMin[0] = (pos) * tex_uv_scale; + cursor_data.TexUvMax[0] = (pos + size) * tex_uv_scale; + pos.x += TEX_DATA_W+1; + cursor_data.TexUvMin[1] = (pos) * tex_uv_scale; + cursor_data.TexUvMax[1] = (pos + size) * tex_uv_scale; + } + } +} + +// Retrieve list of range (2 int per range, values are inclusive) +const ImWchar* ImFontAtlas::GetGlyphRangesDefault() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesKorean() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3131, 0x3163, // Korean alphabets + 0xAC00, 0xD79D, // Korean characters + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesChinese() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + 0x4e00, 0x9FAF, // CJK Ideograms + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesJapanese() +{ + // Store the 1946 ideograms code points as successive offsets from the initial unicode codepoint 0x4E00. Each offset has an implicit +1. + // This encoding helps us reduce the source code size. + static const short offsets_from_0x4E00[] = + { + -1,0,1,3,0,0,0,0,1,0,5,1,1,0,7,4,6,10,0,1,9,9,7,1,3,19,1,10,7,1,0,1,0,5,1,0,6,4,2,6,0,0,12,6,8,0,3,5,0,1,0,9,0,0,8,1,1,3,4,5,13,0,0,8,2,17, + 4,3,1,1,9,6,0,0,0,2,1,3,2,22,1,9,11,1,13,1,3,12,0,5,9,2,0,6,12,5,3,12,4,1,2,16,1,1,4,6,5,3,0,6,13,15,5,12,8,14,0,0,6,15,3,6,0,18,8,1,6,14,1, + 5,4,12,24,3,13,12,10,24,0,0,0,1,0,1,1,2,9,10,2,2,0,0,3,3,1,0,3,8,0,3,2,4,4,1,6,11,10,14,6,15,3,4,15,1,0,0,5,2,2,0,0,1,6,5,5,6,0,3,6,5,0,0,1,0, + 11,2,2,8,4,7,0,10,0,1,2,17,19,3,0,2,5,0,6,2,4,4,6,1,1,11,2,0,3,1,2,1,2,10,7,6,3,16,0,8,24,0,0,3,1,1,3,0,1,6,0,0,0,2,0,1,5,15,0,1,0,0,2,11,19, + 1,4,19,7,6,5,1,0,0,0,0,5,1,0,1,9,0,0,5,0,2,0,1,0,3,0,11,3,0,2,0,0,0,0,0,9,3,6,4,12,0,14,0,0,29,10,8,0,14,37,13,0,31,16,19,0,8,30,1,20,8,3,48, + 21,1,0,12,0,10,44,34,42,54,11,18,82,0,2,1,2,12,1,0,6,2,17,2,12,7,0,7,17,4,2,6,24,23,8,23,39,2,16,23,1,0,5,1,2,15,14,5,6,2,11,0,8,6,2,2,2,14, + 20,4,15,3,4,11,10,10,2,5,2,1,30,2,1,0,0,22,5,5,0,3,1,5,4,1,0,0,2,2,21,1,5,1,2,16,2,1,3,4,0,8,4,0,0,5,14,11,2,16,1,13,1,7,0,22,15,3,1,22,7,14, + 22,19,11,24,18,46,10,20,64,45,3,2,0,4,5,0,1,4,25,1,0,0,2,10,0,0,0,1,0,1,2,0,0,9,1,2,0,0,0,2,5,2,1,1,5,5,8,1,1,1,5,1,4,9,1,3,0,1,0,1,1,2,0,0, + 2,0,1,8,22,8,1,0,0,0,0,4,2,1,0,9,8,5,0,9,1,30,24,2,6,4,39,0,14,5,16,6,26,179,0,2,1,1,0,0,0,5,2,9,6,0,2,5,16,7,5,1,1,0,2,4,4,7,15,13,14,0,0, + 3,0,1,0,0,0,2,1,6,4,5,1,4,9,0,3,1,8,0,0,10,5,0,43,0,2,6,8,4,0,2,0,0,9,6,0,9,3,1,6,20,14,6,1,4,0,7,2,3,0,2,0,5,0,3,1,0,3,9,7,0,3,4,0,4,9,1,6,0, + 9,0,0,2,3,10,9,28,3,6,2,4,1,2,32,4,1,18,2,0,3,1,5,30,10,0,2,2,2,0,7,9,8,11,10,11,7,2,13,7,5,10,0,3,40,2,0,1,6,12,0,4,5,1,5,11,11,21,4,8,3,7, + 8,8,33,5,23,0,0,19,8,8,2,3,0,6,1,1,1,5,1,27,4,2,5,0,3,5,6,3,1,0,3,1,12,5,3,3,2,0,7,7,2,1,0,4,0,1,1,2,0,10,10,6,2,5,9,7,5,15,15,21,6,11,5,20, + 4,3,5,5,2,5,0,2,1,0,1,7,28,0,9,0,5,12,5,5,18,30,0,12,3,3,21,16,25,32,9,3,14,11,24,5,66,9,1,2,0,5,9,1,5,1,8,0,8,3,3,0,1,15,1,4,8,1,2,7,0,7,2, + 8,3,7,5,3,7,10,2,1,0,0,2,25,0,6,4,0,10,0,4,2,4,1,12,5,38,4,0,4,1,10,5,9,4,0,14,4,2,5,18,20,21,1,3,0,5,0,7,0,3,7,1,3,1,1,8,1,0,0,0,3,2,5,2,11, + 6,0,13,1,3,9,1,12,0,16,6,2,1,0,2,1,12,6,13,11,2,0,28,1,7,8,14,13,8,13,0,2,0,5,4,8,10,2,37,42,19,6,6,7,4,14,11,18,14,80,7,6,0,4,72,12,36,27, + 7,7,0,14,17,19,164,27,0,5,10,7,3,13,6,14,0,2,2,5,3,0,6,13,0,0,10,29,0,4,0,3,13,0,3,1,6,51,1,5,28,2,0,8,0,20,2,4,0,25,2,10,13,10,0,16,4,0,1,0, + 2,1,7,0,1,8,11,0,0,1,2,7,2,23,11,6,6,4,16,2,2,2,0,22,9,3,3,5,2,0,15,16,21,2,9,20,15,15,5,3,9,1,0,0,1,7,7,5,4,2,2,2,38,24,14,0,0,15,5,6,24,14, + 5,5,11,0,21,12,0,3,8,4,11,1,8,0,11,27,7,2,4,9,21,59,0,1,39,3,60,62,3,0,12,11,0,3,30,11,0,13,88,4,15,5,28,13,1,4,48,17,17,4,28,32,46,0,16,0, + 18,11,1,8,6,38,11,2,6,11,38,2,0,45,3,11,2,7,8,4,30,14,17,2,1,1,65,18,12,16,4,2,45,123,12,56,33,1,4,3,4,7,0,0,0,3,2,0,16,4,2,4,2,0,7,4,5,2,26, + 2,25,6,11,6,1,16,2,6,17,77,15,3,35,0,1,0,5,1,0,38,16,6,3,12,3,3,3,0,9,3,1,3,5,2,9,0,18,0,25,1,3,32,1,72,46,6,2,7,1,3,14,17,0,28,1,40,13,0,20, + 15,40,6,38,24,12,43,1,1,9,0,12,6,0,6,2,4,19,3,7,1,48,0,9,5,0,5,6,9,6,10,15,2,11,19,3,9,2,0,1,10,1,27,8,1,3,6,1,14,0,26,0,27,16,3,4,9,6,2,23, + 9,10,5,25,2,1,6,1,1,48,15,9,15,14,3,4,26,60,29,13,37,21,1,6,4,0,2,11,22,23,16,16,2,2,1,3,0,5,1,6,4,0,0,4,0,0,8,3,0,2,5,0,7,1,7,3,13,2,4,10, + 3,0,2,31,0,18,3,0,12,10,4,1,0,7,5,7,0,5,4,12,2,22,10,4,2,15,2,8,9,0,23,2,197,51,3,1,1,4,13,4,3,21,4,19,3,10,5,40,0,4,1,1,10,4,1,27,34,7,21, + 2,17,2,9,6,4,2,3,0,4,2,7,8,2,5,1,15,21,3,4,4,2,2,17,22,1,5,22,4,26,7,0,32,1,11,42,15,4,1,2,5,0,19,3,1,8,6,0,10,1,9,2,13,30,8,2,24,17,19,1,4, + 4,25,13,0,10,16,11,39,18,8,5,30,82,1,6,8,18,77,11,13,20,75,11,112,78,33,3,0,0,60,17,84,9,1,1,12,30,10,49,5,32,158,178,5,5,6,3,3,1,3,1,4,7,6, + 19,31,21,0,2,9,5,6,27,4,9,8,1,76,18,12,1,4,0,3,3,6,3,12,2,8,30,16,2,25,1,5,5,4,3,0,6,10,2,3,1,0,5,1,19,3,0,8,1,5,2,6,0,0,0,19,1,2,0,5,1,2,5, + 1,3,7,0,4,12,7,3,10,22,0,9,5,1,0,2,20,1,1,3,23,30,3,9,9,1,4,191,14,3,15,6,8,50,0,1,0,0,4,0,0,1,0,2,4,2,0,2,3,0,2,0,2,2,8,7,0,1,1,1,3,3,17,11, + 91,1,9,3,2,13,4,24,15,41,3,13,3,1,20,4,125,29,30,1,0,4,12,2,21,4,5,5,19,11,0,13,11,86,2,18,0,7,1,8,8,2,2,22,1,2,6,5,2,0,1,2,8,0,2,0,5,2,1,0, + 2,10,2,0,5,9,2,1,2,0,1,0,4,0,0,10,2,5,3,0,6,1,0,1,4,4,33,3,13,17,3,18,6,4,7,1,5,78,0,4,1,13,7,1,8,1,0,35,27,15,3,0,0,0,1,11,5,41,38,15,22,6, + 14,14,2,1,11,6,20,63,5,8,27,7,11,2,2,40,58,23,50,54,56,293,8,8,1,5,1,14,0,1,12,37,89,8,8,8,2,10,6,0,0,0,4,5,2,1,0,1,1,2,7,0,3,3,0,4,6,0,3,2, + 19,3,8,0,0,0,4,4,16,0,4,1,5,1,3,0,3,4,6,2,17,10,10,31,6,4,3,6,10,126,7,3,2,2,0,9,0,0,5,20,13,0,15,0,6,0,2,5,8,64,50,3,2,12,2,9,0,0,11,8,20, + 109,2,18,23,0,0,9,61,3,0,28,41,77,27,19,17,81,5,2,14,5,83,57,252,14,154,263,14,20,8,13,6,57,39,38, + }; + static ImWchar base_ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + }; + static bool full_ranges_unpacked = false; + static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(offsets_from_0x4E00)*2 + 1]; + if (!full_ranges_unpacked) + { + // Unpack + int codepoint = 0x4e00; + memcpy(full_ranges, base_ranges, sizeof(base_ranges)); + ImWchar* dst = full_ranges + IM_ARRAYSIZE(base_ranges);; + for (int n = 0; n < IM_ARRAYSIZE(offsets_from_0x4E00); n++, dst += 2) + dst[0] = dst[1] = (ImWchar)(codepoint += (offsets_from_0x4E00[n] + 1)); + dst[0] = 0; + full_ranges_unpacked = true; + } + return &full_ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesCyrillic() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x0400, 0x052F, // Cyrillic + Cyrillic Supplement + 0x2DE0, 0x2DFF, // Cyrillic Extended-A + 0xA640, 0xA69F, // Cyrillic Extended-B + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesThai() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + 0x0E00, 0x0E7F, // Thai + 0, + }; + return &ranges[0]; +} + +//----------------------------------------------------------------------------- +// ImFont +//----------------------------------------------------------------------------- + +ImFont::ImFont() +{ + Scale = 1.0f; + FallbackChar = (ImWchar)'?'; + Clear(); +} + +ImFont::~ImFont() +{ + // Invalidate active font so that the user gets a clear crash instead of a dangling pointer. + // If you want to delete fonts you need to do it between Render() and NewFrame(). + // FIXME-CLEANUP + /* + ImGuiContext& g = *GImGui; + if (g.Font == this) + g.Font = NULL; + */ + Clear(); +} + +void ImFont::Clear() +{ + FontSize = 0.0f; + DisplayOffset = ImVec2(0.0f, 1.0f); + Glyphs.clear(); + IndexXAdvance.clear(); + IndexLookup.clear(); + FallbackGlyph = NULL; + FallbackXAdvance = 0.0f; + ConfigDataCount = 0; + ConfigData = NULL; + ContainerAtlas = NULL; + Ascent = Descent = 0.0f; + MetricsTotalSurface = 0; +} + +void ImFont::BuildLookupTable() +{ + int max_codepoint = 0; + for (int i = 0; i != Glyphs.Size; i++) + max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); + + IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved + IndexXAdvance.clear(); + IndexLookup.clear(); + GrowIndex(max_codepoint + 1); + for (int i = 0; i < Glyphs.Size; i++) + { + int codepoint = (int)Glyphs[i].Codepoint; + IndexXAdvance[codepoint] = Glyphs[i].XAdvance; + IndexLookup[codepoint] = (unsigned short)i; + } + + // Create a glyph to handle TAB + // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) + if (FindGlyph((unsigned short)' ')) + { + if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times + Glyphs.resize(Glyphs.Size + 1); + ImFont::Glyph& tab_glyph = Glyphs.back(); + tab_glyph = *FindGlyph((unsigned short)' '); + tab_glyph.Codepoint = '\t'; + tab_glyph.XAdvance *= 4; + IndexXAdvance[(int)tab_glyph.Codepoint] = (float)tab_glyph.XAdvance; + IndexLookup[(int)tab_glyph.Codepoint] = (unsigned short)(Glyphs.Size-1); + } + + FallbackGlyph = NULL; + FallbackGlyph = FindGlyph(FallbackChar); + FallbackXAdvance = FallbackGlyph ? FallbackGlyph->XAdvance : 0.0f; + for (int i = 0; i < max_codepoint + 1; i++) + if (IndexXAdvance[i] < 0.0f) + IndexXAdvance[i] = FallbackXAdvance; +} + +void ImFont::SetFallbackChar(ImWchar c) +{ + FallbackChar = c; + BuildLookupTable(); +} + +void ImFont::GrowIndex(int new_size) +{ + IM_ASSERT(IndexXAdvance.Size == IndexLookup.Size); + int old_size = IndexLookup.Size; + if (new_size <= old_size) + return; + IndexXAdvance.resize(new_size); + IndexLookup.resize(new_size); + for (int i = old_size; i < new_size; i++) + { + IndexXAdvance[i] = -1.0f; + IndexLookup[i] = (unsigned short)-1; + } +} + +void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) +{ + IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function. + int index_size = IndexLookup.Size; + + if (dst < index_size && IndexLookup.Data[dst] == (unsigned short)-1 && !overwrite_dst) // 'dst' already exists + return; + if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op + return; + + GrowIndex(dst + 1); + IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (unsigned short)-1; + IndexXAdvance[dst] = (src < index_size) ? IndexXAdvance.Data[src] : 1.0f; +} + +const ImFont::Glyph* ImFont::FindGlyph(unsigned short c) const +{ + if (c < IndexLookup.Size) + { + const unsigned short i = IndexLookup[c]; + if (i != (unsigned short)-1) + return &Glyphs.Data[i]; + } + return FallbackGlyph; +} + +const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const +{ + // Simple word-wrapping for English, not full-featured. Please submit failing cases! + // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) + + // For references, possible wrap point marked with ^ + // "aaa bbb, ccc,ddd. eee fff. ggg!" + // ^ ^ ^ ^ ^__ ^ ^ + + // List of hardcoded separators: .,;!?'" + + // Skip extra blanks after a line returns (that includes not counting them in width computation) + // e.g. "Hello world" --> "Hello" "World" + + // Cut words that cannot possibly fit within one line. + // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" + + float line_width = 0.0f; + float word_width = 0.0f; + float blank_width = 0.0f; + + const char* word_end = text; + const char* prev_word_end = NULL; + bool inside_word = true; + + const char* s = text; + while (s < text_end) + { + unsigned int c = (unsigned int)*s; + const char* next_s; + if (c < 0x80) + next_s = s + 1; + else + next_s = s + ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) + break; + + if (c < 32) + { + if (c == '\n') + { + line_width = word_width = blank_width = 0.0f; + inside_word = true; + s = next_s; + continue; + } + if (c == '\r') + { + s = next_s; + continue; + } + } + + const float char_width = ((int)c < IndexXAdvance.Size ? IndexXAdvance[(int)c] : FallbackXAdvance) * scale; + if (ImCharIsSpace(c)) + { + if (inside_word) + { + line_width += blank_width; + blank_width = 0.0f; + word_end = s; + } + blank_width += char_width; + inside_word = false; + } + else + { + word_width += char_width; + if (inside_word) + { + word_end = next_s; + } + else + { + prev_word_end = word_end; + line_width += word_width + blank_width; + word_width = blank_width = 0.0f; + } + + // Allow wrapping after punctuation. + inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"'); + } + + // We ignore blank width at the end of the line (they can be skipped) + if (line_width + word_width >= wrap_width) + { + // Words that cannot possibly fit within an entire line will be cut anywhere. + if (word_width < wrap_width) + s = prev_word_end ? prev_word_end : word_end; + break; + } + + s = next_s; + } + + return s; +} + +ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this. + + const float line_height = size; + const float scale = size / FontSize; + + ImVec2 text_size = ImVec2(0,0); + float line_width = 0.0f; + + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char* word_wrap_eol = NULL; + + const char* s = text_begin; + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + if (text_size.x < line_width) + text_size.x = line_width; + text_size.y += line_height; + line_width = 0.0f; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } + } + continue; + } + } + + // Decode and advance source + const char* prev_s = s; + unsigned int c = (unsigned int)*s; + if (c < 0x80) + { + s += 1; + } + else + { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) // Malformed UTF-8? + break; + } + + if (c < 32) + { + if (c == '\n') + { + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + continue; + } + if (c == '\r') + continue; + } + + const float char_width = ((int)c < IndexXAdvance.Size ? IndexXAdvance[(int)c] : FallbackXAdvance) * scale; + if (line_width + char_width >= max_width) + { + s = prev_s; + break; + } + + line_width += char_width; + } + + if (text_size.x < line_width) + text_size.x = line_width; + + if (line_width > 0 || text_size.y == 0.0f) + text_size.y += line_height; + + if (remaining) + *remaining = s; + + return text_size; +} + +void ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const +{ + if (c == ' ' || c == '\t' || c == '\n' || c == '\r') // Match behavior of RenderText(), those 4 codepoints are hard-coded. + return; + if (const Glyph* glyph = FindGlyph(c)) + { + float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; + pos.x = (float)(int)pos.x + DisplayOffset.x; + pos.y = (float)(int)pos.y + DisplayOffset.y; + ImVec2 pos_tl(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale); + ImVec2 pos_br(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale); + draw_list->PrimReserve(6, 4); + draw_list->PrimRectUV(pos_tl, pos_br, ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col); + } +} + +void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); // ImGui functions generally already provides a valid text_end, so this is merely to handle direct calls. + + // Align to be pixel perfect + pos.x = (float)(int)pos.x + DisplayOffset.x; + pos.y = (float)(int)pos.y + DisplayOffset.y; + float x = pos.x; + float y = pos.y; + if (y > clip_rect.w) + return; + + const float scale = size / FontSize; + const float line_height = FontSize * scale; + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char* word_wrap_eol = NULL; + + // Skip non-visible lines + const char* s = text_begin; + if (!word_wrap_enabled && y + line_height < clip_rect.y) + while (s < text_end && *s != '\n') // Fast-forward to next line + s++; + + // Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) + const int vtx_count_max = (int)(text_end - s) * 4; + const int idx_count_max = (int)(text_end - s) * 6; + const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max; + draw_list->PrimReserve(idx_count_max, vtx_count_max); + + ImDrawVert* vtx_write = draw_list->_VtxWritePtr; + ImDrawIdx* idx_write = draw_list->_IdxWritePtr; + unsigned int vtx_current_idx = draw_list->_VtxCurrentIdx; + + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - pos.x)); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + x = pos.x; + y += line_height; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } + } + continue; + } + } + + // Decode and advance source + unsigned int c = (unsigned int)*s; + if (c < 0x80) + { + s += 1; + } + else + { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) // Malformed UTF-8? + break; + } + + if (c < 32) + { + if (c == '\n') + { + x = pos.x; + y += line_height; + + if (y > clip_rect.w) + break; + if (!word_wrap_enabled && y + line_height < clip_rect.y) + while (s < text_end && *s != '\n') // Fast-forward to next line + s++; + continue; + } + if (c == '\r') + continue; + } + + float char_width = 0.0f; + if (const Glyph* glyph = FindGlyph((unsigned short)c)) + { + char_width = glyph->XAdvance * scale; + + // Arbitrarily assume that both space and tabs are empty glyphs as an optimization + if (c != ' ' && c != '\t') + { + // We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w + float x1 = x + glyph->X0 * scale; + float x2 = x + glyph->X1 * scale; + float y1 = y + glyph->Y0 * scale; + float y2 = y + glyph->Y1 * scale; + if (x1 <= clip_rect.z && x2 >= clip_rect.x) + { + // Render a character + float u1 = glyph->U0; + float v1 = glyph->V0; + float u2 = glyph->U1; + float v2 = glyph->V1; + + // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. + if (cpu_fine_clip) + { + if (x1 < clip_rect.x) + { + u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1); + x1 = clip_rect.x; + } + if (y1 < clip_rect.y) + { + v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1); + y1 = clip_rect.y; + } + if (x2 > clip_rect.z) + { + u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1); + x2 = clip_rect.z; + } + if (y2 > clip_rect.w) + { + v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1); + y2 = clip_rect.w; + } + if (y1 >= y2) + { + x += char_width; + continue; + } + } + + // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug build. + // Inlined here: + { + idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx+1); idx_write[2] = (ImDrawIdx)(vtx_current_idx+2); + idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx+2); idx_write[5] = (ImDrawIdx)(vtx_current_idx+3); + vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[0].col = col; vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v1; + vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[1].col = col; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v1; + vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[2].col = col; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v2; + vtx_write[3].pos.x = x1; vtx_write[3].pos.y = y2; vtx_write[3].col = col; vtx_write[3].uv.x = u1; vtx_write[3].uv.y = v2; + vtx_write += 4; + vtx_current_idx += 4; + idx_write += 6; + } + } + } + } + + x += char_width; + } + + // Give back unused vertices + draw_list->VtxBuffer.resize((int)(vtx_write - draw_list->VtxBuffer.Data)); + draw_list->IdxBuffer.resize((int)(idx_write - draw_list->IdxBuffer.Data)); + draw_list->CmdBuffer[draw_list->CmdBuffer.Size-1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); + draw_list->_VtxWritePtr = vtx_write; + draw_list->_IdxWritePtr = idx_write; + draw_list->_VtxCurrentIdx = (unsigned int)draw_list->VtxBuffer.Size; +} + +//----------------------------------------------------------------------------- +// DEFAULT FONT DATA +//----------------------------------------------------------------------------- +// Compressed with stb_compress() then converted to a C array. +// Use the program in extra_fonts/binary_to_compressed_c.cpp to create the array from a TTF file. +// Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h +//----------------------------------------------------------------------------- + +static unsigned int stb_decompress_length(unsigned char *input) +{ + return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]; +} + +static unsigned char *stb__barrier, *stb__barrier2, *stb__barrier3, *stb__barrier4; +static unsigned char *stb__dout; +static void stb__match(unsigned char *data, unsigned int length) +{ + // INVERSE of memmove... write each byte before copying the next... + IM_ASSERT (stb__dout + length <= stb__barrier); + if (stb__dout + length > stb__barrier) { stb__dout += length; return; } + if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; } + while (length--) *stb__dout++ = *data++; +} + +static void stb__lit(unsigned char *data, unsigned int length) +{ + IM_ASSERT (stb__dout + length <= stb__barrier); + if (stb__dout + length > stb__barrier) { stb__dout += length; return; } + if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; } + memcpy(stb__dout, data, length); + stb__dout += length; +} + +#define stb__in2(x) ((i[x] << 8) + i[(x)+1]) +#define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1)) +#define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1)) + +static unsigned char *stb_decompress_token(unsigned char *i) +{ + if (*i >= 0x20) { // use fewer if's for cases that expand small + if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2; + else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3; + else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); + } else { // more ifs for cases that expand large, since overhead is amortized + if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4; + else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5; + else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1); + else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1); + else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5; + else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6; + } + return i; +} + +static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) +{ + const unsigned long ADLER_MOD = 65521; + unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; + unsigned long blocklen, i; + + blocklen = buflen % 5552; + while (buflen) { + for (i=0; i + 7 < blocklen; i += 8) { + s1 += buffer[0], s2 += s1; + s1 += buffer[1], s2 += s1; + s1 += buffer[2], s2 += s1; + s1 += buffer[3], s2 += s1; + s1 += buffer[4], s2 += s1; + s1 += buffer[5], s2 += s1; + s1 += buffer[6], s2 += s1; + s1 += buffer[7], s2 += s1; + + buffer += 8; + } + + for (; i < blocklen; ++i) + s1 += *buffer++, s2 += s1; + + s1 %= ADLER_MOD, s2 %= ADLER_MOD; + buflen -= blocklen; + blocklen = 5552; + } + return (unsigned int)(s2 << 16) + (unsigned int)s1; +} + +static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length) +{ + unsigned int olen; + if (stb__in4(0) != 0x57bC0000) return 0; + if (stb__in4(4) != 0) return 0; // error! stream is > 4GB + olen = stb_decompress_length(i); + stb__barrier2 = i; + stb__barrier3 = i+length; + stb__barrier = output + olen; + stb__barrier4 = output; + i += 16; + + stb__dout = output; + for (;;) { + unsigned char *old_i = i; + i = stb_decompress_token(i); + if (i == old_i) { + if (*i == 0x05 && i[1] == 0xfa) { + IM_ASSERT(stb__dout == output + olen); + if (stb__dout != output + olen) return 0; + if (stb_adler32(1, output, olen) != (unsigned int) stb__in4(2)) + return 0; + return olen; + } else { + IM_ASSERT(0); /* NOTREACHED */ + return 0; + } + } + IM_ASSERT(stb__dout <= output + olen); + if (stb__dout > output + olen) + return 0; + } +} + +//----------------------------------------------------------------------------- +// ProggyClean.ttf +// Copyright (c) 2004, 2005 Tristan Grimmer +// MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) +// Download and more information at http://upperbounds.net +//----------------------------------------------------------------------------- +// File: 'ProggyClean.ttf' (41208 bytes) +// Exported using binary_to_compressed_c.cpp +//----------------------------------------------------------------------------- +static const char proggy_clean_ttf_compressed_data_base85[11980+1] = + "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/" + "2*>]b(MC;$jPfY.;h^`IWM9Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1=Ke$$'5F%)]0^#0X@U.a$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;--VsM.M0rJfLH2eTM`*oJMHRC`N" + "kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`�j@'DbG&#^$PG.Ll+DNa&VZ>1i%h1S9u5o@YaaW$e+bROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc." + "x]Ip.PH^'/aqUO/$1WxLoW0[iLAw=4h(9.`G" + "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?Ggv:[7MI2k).'2($5FNP&EQ(,)" + "U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#" + "'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM" + "_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu" + "Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/" + "/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[Ket`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO" + "j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%" + "LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$MhLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]" + "%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et" + "Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:" + "a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VBpqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<-+k?'(^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M" + "D?@f&1'BW-)Ju#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX(" + "P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs" + "bIu)'Z,*[>br5fX^:FPAWr-m2KgLQ_nN6'8uTGT5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q" + "h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aege0jT6'N#(q%.O=?2S]u*(m<-" + "V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i" + "sZ88+dKQ)W6>J%CL`.d*(B`-n8D9oK-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P r+$%CE=68>K8r0=dSC%%(@p7" + ".m7jilQ02'0-VWAgTlGW'b)Tq7VT9q^*^$$.:&N@@" + "$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*" + "hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u" + "@-W$U%VEQ/,,>>#)D#%8cY#YZ?=,`Wdxu/ae&#" + "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$so8lKN%5/$(vdfq7+ebA#" + "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoFDoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8" + "6e%B/:=>)N4xeW.*wft-;$'58-ESqr#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#" + "b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjLV#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#SfD07&6D@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5" + "_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%" + "hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;" + "^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmLq9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:" + "+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3$U4O]GKx'm9)b@p7YsvK3w^YR-" + "CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*" + "hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdFTi1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IXSsDiWP,##P`%/L-" + "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdFl*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj" + "M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#$(>.Z-I&J(Q0Hd5Q%7Co-b`-cP)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8WlA2);Sa" + ">gXm8YB`1d@K#n]76-a$U,mF%Ul:#/'xoFM9QX-$.QN'>" + "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I" + "wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-uW%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)" + "i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo" + "1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P" + "iDDG)g,r%+?,$@?uou5tSe2aN_AQU*'IAO" + "URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#" + ";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T" + "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4" + "A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#" + "/QHC#3^ZC#7jmC#;v)D#?,)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP" + "GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp" + "O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#"; + +static const char* GetDefaultCompressedFontDataTTFBase85() +{ + return proggy_clean_ttf_compressed_data_base85; +} diff --git a/Externals/imgui-1.46/Include/imgui_internal.h b/SampleFramework12/v1.01/ImGui/imgui_internal.h similarity index 69% rename from Externals/imgui-1.46/Include/imgui_internal.h rename to SampleFramework12/v1.01/ImGui/imgui_internal.h index 811ad3e..200eda9 100644 --- a/Externals/imgui-1.46/Include/imgui_internal.h +++ b/SampleFramework12/v1.01/ImGui/imgui_internal.h @@ -1,7 +1,7 @@ -// ImGui library v1.46 -// Internals -// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! +// dear imgui, v1.50 +// (internals) +// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! // Implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators) // #define IMGUI_DEFINE_MATH_OPERATORS @@ -12,13 +12,20 @@ #endif #include // FILE* -#include // sqrtf() +#include // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport) #endif +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wold-style-cast" +#endif + //----------------------------------------------------------------------------- // Forward Declarations //----------------------------------------------------------------------------- @@ -33,12 +40,12 @@ struct ImGuiTextEditState; struct ImGuiIniData; struct ImGuiMouseCursorData; struct ImGuiPopupRef; -struct ImGuiState; struct ImGuiWindow; typedef int ImGuiLayoutType; // enum ImGuiLayoutType_ typedef int ImGuiButtonFlags; // enum ImGuiButtonFlags_ typedef int ImGuiTreeNodeFlags; // enum ImGuiTreeNodeFlags_ +typedef int ImGuiSliderFlags; // enum ImGuiSliderFlags_ //------------------------------------------------------------------------- // STB libraries @@ -47,12 +54,6 @@ typedef int ImGuiTreeNodeFlags; // enum ImGuiTreeNodeFlags_ namespace ImGuiStb { -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wmissing-prototypes" -#endif - #undef STB_TEXTEDIT_STRING #undef STB_TEXTEDIT_CHARTYPE #define STB_TEXTEDIT_STRING ImGuiTextEditState @@ -60,17 +61,15 @@ namespace ImGuiStb #define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f #include "stb_textedit.h" -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - } // namespace ImGuiStb //----------------------------------------------------------------------------- // Context //----------------------------------------------------------------------------- -extern IMGUI_API ImGuiState* GImGui; +#ifndef GImGui +extern IMGUI_API ImGuiContext* GImGui; // Current implicit ImGui context pointer +#endif //----------------------------------------------------------------------------- // Helpers @@ -78,6 +77,7 @@ extern IMGUI_API ImGuiState* GImGui; #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) #define IM_PI 3.14159265358979323846f +#define IM_OFFSETOF(_TYPE,_ELM) ((size_t)&(((_TYPE*)0)->_ELM)) // Helpers: UTF-8 <> wchar IMGUI_API int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count @@ -88,7 +88,8 @@ IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, cons // Helpers: Misc IMGUI_API ImU32 ImHash(const void* data, int data_size, ImU32 seed = 0); // Pass data_size==0 for zero-terminated strings -IMGUI_API void* ImLoadFileToMemory(const char* filename, const char* file_open_mode, int* out_file_size = NULL, int padding_bytes = 0); +IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size = NULL, int padding_bytes = 0); +IMGUI_API FILE* ImFileOpen(const char* filename, const char* file_open_mode); IMGUI_API bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c); static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; } static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } @@ -116,7 +117,7 @@ static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } -static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-lhs.w); } +static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-rhs.w); } #endif static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; } @@ -134,7 +135,17 @@ static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; } static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; } static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / sqrtf(d); return fail_value; } -static inline ImVec2 ImRound(ImVec2 v) { return ImVec2((float)(int)v.x, (float)(int)v.y); } +static inline float ImFloor(float f) { return (float)(int)f; } +static inline ImVec2 ImFloor(ImVec2 v) { return ImVec2((float)(int)v.x, (float)(int)v.y); } + +// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. +// Defining a custom placement new() with a dummy parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. +#ifdef IMGUI_DEFINE_PLACEMENT_NEW +struct ImPlacementNewDummy {}; +inline void* operator new(size_t, ImPlacementNewDummy, void* ptr) { return ptr; } +inline void operator delete(void*, ImPlacementNewDummy, void*) {} +#define IM_PLACEMENT_NEW(_PTR) new(ImPlacementNewDummy(), _PTR) +#endif //----------------------------------------------------------------------------- // Types @@ -142,28 +153,31 @@ static inline ImVec2 ImRound(ImVec2 v) enum ImGuiButtonFlags_ { - ImGuiButtonFlags_Repeat = 1 << 0, - ImGuiButtonFlags_PressedOnClick = 1 << 1, // return pressed on click only (default requires click+release) - ImGuiButtonFlags_PressedOnRelease = 1 << 2, // return pressed on release only (default requires click+release) - ImGuiButtonFlags_FlattenChilds = 1 << 3, - ImGuiButtonFlags_DontClosePopups = 1 << 4, - ImGuiButtonFlags_Disabled = 1 << 5, - ImGuiButtonFlags_AlignTextBaseLine = 1 << 6 + ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat + ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // (default) return pressed on click+release on same item (default if no PressedOn** flag is set) + ImGuiButtonFlags_PressedOnClick = 1 << 2, // return pressed on click (default requires click+release) + ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return pressed on release (default requires click+release) + ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return pressed on double-click (default requires click+release) + ImGuiButtonFlags_FlattenChilds = 1 << 5, // allow interaction even if a child window is overlapping + ImGuiButtonFlags_DontClosePopups = 1 << 6, // disable automatically closing parent popup on press + ImGuiButtonFlags_Disabled = 1 << 7, // disable interaction + ImGuiButtonFlags_AlignTextBaseLine = 1 << 8, // vertically align button to match text baseline - ButtonEx() only + ImGuiButtonFlags_NoKeyModifiers = 1 << 9, // disable interaction if a key modifier is held + ImGuiButtonFlags_AllowOverlapMode = 1 << 10 // require previous frame HoveredId to either match id or be null before being usable }; -enum ImGuiTreeNodeFlags_ +enum ImGuiSliderFlags_ { - ImGuiTreeNodeFlags_DefaultOpen = 1 << 0, - ImGuiTreeNodeFlags_NoAutoExpandOnLog = 1 << 1 + ImGuiSliderFlags_Vertical = 1 << 0 }; enum ImGuiSelectableFlagsPrivate_ { // NB: need to be in sync with last value of ImGuiSelectableFlags_ - ImGuiSelectableFlags_Menu = 1 << 2, - ImGuiSelectableFlags_MenuItem = 1 << 3, - ImGuiSelectableFlags_Disabled = 1 << 4, - ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 5 + ImGuiSelectableFlags_Menu = 1 << 3, + ImGuiSelectableFlags_MenuItem = 1 << 4, + ImGuiSelectableFlags_Disabled = 1 << 5, + ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 6 }; // FIXME: this is in development, not exposed/functional as a generic feature yet. @@ -182,40 +196,50 @@ enum ImGuiPlotType enum ImGuiDataType { ImGuiDataType_Int, - ImGuiDataType_Float + ImGuiDataType_Float, + ImGuiDataType_Float2, +}; + +enum ImGuiCorner +{ + ImGuiCorner_TopLeft = 1 << 0, // 1 + ImGuiCorner_TopRight = 1 << 1, // 2 + ImGuiCorner_BottomRight = 1 << 2, // 4 + ImGuiCorner_BottomLeft = 1 << 3, // 8 + ImGuiCorner_All = 0x0F }; // 2D axis aligned bounding-box // NB: we can't rely on ImVec2 math operators being available here struct IMGUI_API ImRect { - ImVec2 Min; // Upper-left - ImVec2 Max; // Lower-right + ImVec2 Min; // Upper-left + ImVec2 Max; // Lower-right ImRect() : Min(FLT_MAX,FLT_MAX), Max(-FLT_MAX,-FLT_MAX) {} ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {} ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {} ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {} - ImVec2 GetCenter() const { return ImVec2((Min.x+Max.x)*0.5f, (Min.y+Max.y)*0.5f); } - ImVec2 GetSize() const { return ImVec2(Max.x-Min.x, Max.y-Min.y); } - float GetWidth() const { return Max.x-Min.x; } - float GetHeight() const { return Max.y-Min.y; } - ImVec2 GetTL() const { return Min; } - ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } - ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } - ImVec2 GetBR() const { return Max; } - bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } - bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x < Max.x && r.Max.y < Max.y; } - bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } - void Add(const ImVec2& rhs) { if (Min.x > rhs.x) Min.x = rhs.x; if (Min.y > rhs.y) Min.y = rhs.y; if (Max.x < rhs.x) Max.x = rhs.x; if (Max.y < rhs.y) Max.y = rhs.y; } - void Add(const ImRect& rhs) { if (Min.x > rhs.Min.x) Min.x = rhs.Min.x; if (Min.y > rhs.Min.y) Min.y = rhs.Min.y; if (Max.x < rhs.Max.x) Max.x = rhs.Max.x; if (Max.y < rhs.Max.y) Max.y = rhs.Max.y; } - void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } - void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } - void Reduce(const ImVec2& amount) { Min.x += amount.x; Min.y += amount.y; Max.x -= amount.x; Max.y -= amount.y; } - void Clip(const ImRect& clip) { if (Min.x < clip.Min.x) Min.x = clip.Min.x; if (Min.y < clip.Min.y) Min.y = clip.Min.y; if (Max.x > clip.Max.x) Max.x = clip.Max.x; if (Max.y > clip.Max.y) Max.y = clip.Max.y; } - void Round() { Min.x = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; } - ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const + ImVec2 GetCenter() const { return ImVec2((Min.x+Max.x)*0.5f, (Min.y+Max.y)*0.5f); } + ImVec2 GetSize() const { return ImVec2(Max.x-Min.x, Max.y-Min.y); } + float GetWidth() const { return Max.x-Min.x; } + float GetHeight() const { return Max.y-Min.y; } + ImVec2 GetTL() const { return Min; } // Top-left + ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right + ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left + ImVec2 GetBR() const { return Max; } // Bottom-right + bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } + bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x < Max.x && r.Max.y < Max.y; } + bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } + void Add(const ImVec2& rhs) { if (Min.x > rhs.x) Min.x = rhs.x; if (Min.y > rhs.y) Min.y = rhs.y; if (Max.x < rhs.x) Max.x = rhs.x; if (Max.y < rhs.y) Max.y = rhs.y; } + void Add(const ImRect& rhs) { if (Min.x > rhs.Min.x) Min.x = rhs.Min.x; if (Min.y > rhs.Min.y) Min.y = rhs.Min.y; if (Max.x < rhs.Max.x) Max.x = rhs.Max.x; if (Max.y < rhs.Max.y) Max.y = rhs.Max.y; } + void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } + void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } + void Reduce(const ImVec2& amount) { Min.x += amount.x; Min.y += amount.y; Max.x -= amount.x; Max.y -= amount.y; } + void Clip(const ImRect& clip) { if (Min.x < clip.Min.x) Min.x = clip.Min.x; if (Min.y < clip.Min.y) Min.y = clip.Min.y; if (Max.x > clip.Max.x) Max.x = clip.Max.x; if (Max.y > clip.Max.y) Max.y = clip.Max.y; } + void Floor() { Min.x = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; } + ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const { if (!on_edge && Contains(p)) return p; @@ -230,41 +254,53 @@ struct IMGUI_API ImRect // Stacked color modifier, backup of modified data so we can restore it struct ImGuiColMod { - ImGuiCol Col; - ImVec4 PreviousValue; + ImGuiCol Col; + ImVec4 BackupValue; }; -// Stacked style modifier, backup of modified data so we can restore it +// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. struct ImGuiStyleMod { - ImGuiStyleVar Var; - ImVec2 PreviousValue; + ImGuiStyleVar VarIdx; + union { int BackupInt[2]; float BackupFloat[2]; }; + ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; } + ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; } + ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; } }; // Stacked data for BeginGroup()/EndGroup() struct ImGuiGroupData { - ImVec2 BackupCursorPos; - ImVec2 BackupCursorMaxPos; - float BackupColumnsStartX; - float BackupCurrentLineHeight; - float BackupCurrentLineTextBaseOffset; - float BackupLogLinePosY; - bool AdvanceCursor; + ImVec2 BackupCursorPos; + ImVec2 BackupCursorMaxPos; + float BackupIndentX; + float BackupGroupOffsetX; + float BackupCurrentLineHeight; + float BackupCurrentLineTextBaseOffset; + float BackupLogLinePosY; + bool BackupActiveIdIsAlive; + bool AdvanceCursor; }; -// Simple column measurement currently used for MenuItem() only. This is very short-sighted for now and not a generic helper. +// Per column data for Columns() +struct ImGuiColumnData +{ + float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) + //float IndentX; +}; + +// Simple column measurement currently used for MenuItem() only. This is very short-sighted/throw-away code and NOT a generic helper. struct IMGUI_API ImGuiSimpleColumns { - int Count; - float Spacing; - float Width, NextWidth; - float Pos[8], NextWidths[8]; + int Count; + float Spacing; + float Width, NextWidth; + float Pos[8], NextWidths[8]; ImGuiSimpleColumns(); - void Update(int count, float spacing, bool clear); - float DeclColumns(float w0, float w1, float w2); - float CalcExtraSpace(float avail_w); + void Update(int count, float spacing, bool clear); + float DeclColumns(float w0, float w1, float w2); + float CalcExtraSpace(float avail_w); }; // Internal state of the currently focused/edited text input box @@ -280,7 +316,6 @@ struct IMGUI_API ImGuiTextEditState ImGuiStb::STB_TexteditState StbState; float CursorAnim; bool CursorFollow; - ImVec2 InputCursorScreenPos; // Cursor position in screen space to be used by IME callback. bool SelectedAllMouseLock; ImGuiTextEditState() { memset(this, 0, sizeof(*this)); } @@ -295,11 +330,11 @@ struct IMGUI_API ImGuiTextEditState // Data saved in imgui.ini file struct ImGuiIniData { - char* Name; - ImGuiID ID; - ImVec2 Pos; - ImVec2 Size; - bool Collapsed; + char* Name; + ImGuiID Id; + ImVec2 Pos; + ImVec2 Size; + bool Collapsed; }; // Mouse cursor data (used when io.MouseDrawCursor is set) @@ -315,17 +350,17 @@ struct ImGuiMouseCursorData // Storage for current popup stack struct ImGuiPopupRef { - ImGuiID PopupID; // Set on OpenPopup() - ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() - ImGuiWindow* ParentWindow; // Set on OpenPopup() - ImGuiID ParentMenuSet; // Set on OpenPopup() - ImVec2 MousePosOnOpen; // Copy of mouse position at the time of opening popup + ImGuiID PopupId; // Set on OpenPopup() + ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() + ImGuiWindow* ParentWindow; // Set on OpenPopup() + ImGuiID ParentMenuSet; // Set on OpenPopup() + ImVec2 MousePosOnOpen; // Copy of mouse position at the time of opening popup - ImGuiPopupRef(ImGuiID id, ImGuiWindow* parent_window, ImGuiID parent_menu_set, const ImVec2& mouse_pos) { PopupID = id; Window = NULL; ParentWindow = parent_window; ParentMenuSet = parent_menu_set; MousePosOnOpen = mouse_pos; } + ImGuiPopupRef(ImGuiID id, ImGuiWindow* parent_window, ImGuiID parent_menu_set, const ImVec2& mouse_pos) { PopupId = id; Window = NULL; ParentWindow = parent_window; ParentMenuSet = parent_menu_set; MousePosOnOpen = mouse_pos; } }; // Main state for ImGui -struct ImGuiState +struct ImGuiContext { bool Initialized; ImGuiIO IO; @@ -333,7 +368,7 @@ struct ImGuiState ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize() float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Size of characters. - ImVec2 FontTexUvWhitePixel; // (Shortcut) == Font->TexUvForWhite + ImVec2 FontTexUvWhitePixel; // (Shortcut) == Font->TexUvWhitePixel float Time; int FrameCount; @@ -347,22 +382,23 @@ struct ImGuiState ImGuiWindow* HoveredWindow; // Will catch mouse inputs ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) ImGuiID HoveredId; // Hovered widget - bool HoveredIdAllowHoveringOthers; + bool HoveredIdAllowOverlap; ImGuiID HoveredIdPreviousFrame; ImGuiID ActiveId; // Active widget ImGuiID ActiveIdPreviousFrame; bool ActiveIdIsAlive; bool ActiveIdIsJustActivated; // Set at the time of activation for one frame - bool ActiveIdAllowHoveringOthers; // Set only by active widget + bool ActiveIdAllowOverlap; // Set only by active widget + ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) ImGuiWindow* ActiveIdWindow; - ImGuiWindow* MovedWindow; // Track the child window we clicked on to move a window. Pointer is only valid if ActiveID is the "#MOVE" identifier of a window. + ImGuiWindow* MovedWindow; // Track the child window we clicked on to move a window. + ImGuiID MovedWindowMoveId; // == MovedWindow->RootWindow->MoveId ImVector Settings; // .ini Settings - float SettingsDirtyTimer; // Save .ini settinngs on disk when time reaches zero - int DisableHideTextAfterDoubleHash; + float SettingsDirtyTimer; // Save .ini Settings on disk when time reaches zero ImVector ColorModifiers; // Stack for PushStyleColor()/PopStyleColor() ImVector StyleModifiers; // Stack for PushStyleVar()/PopStyleVar() ImVector FontStack; // Stack for PushFont()/PopFont() - ImVector OpenedPopupStack; // Which popups are open (persistent) + ImVector OpenPopupStack; // Which popups are open (persistent) ImVector CurrentPopupStack; // Which level of BeginPopup() we are in (reset every frame) // Storage for SetNexWindow** and SetNextTreeNode*** functions @@ -374,9 +410,13 @@ struct ImGuiState ImGuiSetCond SetNextWindowSizeCond; ImGuiSetCond SetNextWindowContentSizeCond; ImGuiSetCond SetNextWindowCollapsedCond; + ImRect SetNextWindowSizeConstraintRect; // Valid if 'SetNextWindowSizeConstraint' is true + ImGuiSizeConstraintCallback SetNextWindowSizeConstraintCallback; + void* SetNextWindowSizeConstraintCallbackUserData; + bool SetNextWindowSizeConstraint; bool SetNextWindowFocus; - bool SetNextTreeNodeOpenedVal; - ImGuiSetCond SetNextTreeNodeOpenedCond; + bool SetNextTreeNodeOpenVal; + ImGuiSetCond SetNextTreeNodeOpenCond; // Render ImDrawData RenderDrawData; // Main ImDrawData instance to pass render information to the user @@ -388,17 +428,18 @@ struct ImGuiState // Widget state ImGuiTextEditState InputTextState; + ImFont InputTextPasswordFont; ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc. ImGuiStorage ColorEditModeStorage; // Store user selection of color edit mode - ImVec2 ActiveClickDeltaToCenter; float DragCurrentValue; // Currently dragged value, always float, not rounded by end-user precision settings ImVec2 DragLastMouseDelta; float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio float DragSpeedScaleSlow; float DragSpeedScaleFast; - ImVec2 ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage? + ImVec2 ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage? char Tooltip[1024]; char* PrivateClipboard; // If no custom clipboard handler is defined + ImVec2 OsImePosRequest, OsImePosSet; // Cursor position request & last passed to the OS Input Method Editor // Logging bool LogEnabled; @@ -411,11 +452,11 @@ struct ImGuiState float FramerateSecPerFrame[120]; // calculate estimate of framerate for user int FramerateSecPerFrameIdx; float FramerateSecPerFrameAccum; - bool CaptureMouseNextFrame; // explicit capture via CaptureInputs() sets those flags - bool CaptureKeyboardNextFrame; + int CaptureMouseNextFrame; // explicit capture via CaptureInputs() sets those flags + int CaptureKeyboardNextFrame; char TempBuffer[1024*3+1]; // temporary text buffer - ImGuiState() + ImGuiContext() { Initialized = false; Font = NULL; @@ -430,42 +471,49 @@ struct ImGuiState HoveredWindow = NULL; HoveredRootWindow = NULL; HoveredId = 0; - HoveredIdAllowHoveringOthers = false; + HoveredIdAllowOverlap = false; HoveredIdPreviousFrame = 0; ActiveId = 0; ActiveIdPreviousFrame = 0; ActiveIdIsAlive = false; ActiveIdIsJustActivated = false; - ActiveIdAllowHoveringOthers = false; + ActiveIdAllowOverlap = false; + ActiveIdClickOffset = ImVec2(-1,-1); ActiveIdWindow = NULL; MovedWindow = NULL; + MovedWindowMoveId = 0; SettingsDirtyTimer = 0.0f; - DisableHideTextAfterDoubleHash = 0; SetNextWindowPosVal = ImVec2(0.0f, 0.0f); SetNextWindowSizeVal = ImVec2(0.0f, 0.0f); SetNextWindowCollapsedVal = false; SetNextWindowPosCond = 0; SetNextWindowSizeCond = 0; + SetNextWindowContentSizeCond = 0; SetNextWindowCollapsedCond = 0; + SetNextWindowSizeConstraintRect = ImRect(); + SetNextWindowSizeConstraintCallback = NULL; + SetNextWindowSizeConstraintCallbackUserData = NULL; + SetNextWindowSizeConstraint = false; SetNextWindowFocus = false; - SetNextTreeNodeOpenedVal = false; - SetNextTreeNodeOpenedCond = 0; + SetNextTreeNodeOpenVal = false; + SetNextTreeNodeOpenCond = 0; ScalarAsInputTextId = 0; - ActiveClickDeltaToCenter = ImVec2(0.0f, 0.0f); DragCurrentValue = 0.0f; DragLastMouseDelta = ImVec2(0.0f, 0.0f); - DragSpeedDefaultRatio = 0.01f; + DragSpeedDefaultRatio = 1.0f / 100.0f; DragSpeedScaleSlow = 0.01f; DragSpeedScaleFast = 10.0f; ScrollbarClickDeltaToGrabCenter = ImVec2(0.0f, 0.0f); memset(Tooltip, 0, sizeof(Tooltip)); PrivateClipboard = NULL; + OsImePosRequest = OsImePosSet = ImVec2(-1.0f, -1.0f); ModalWindowDarkeningRatio = 0.0f; OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging MouseCursor = ImGuiMouseCursor_Arrow; + memset(MouseCursorData, 0, sizeof(MouseCursorData)); LogEnabled = false; LogFile = NULL; @@ -476,7 +524,8 @@ struct ImGuiState memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); FramerateSecPerFrameIdx = 0; FramerateSecPerFrameAccum = 0.0f; - CaptureMouseNextFrame = CaptureKeyboardNextFrame = false; + CaptureMouseNextFrame = CaptureKeyboardNextFrame = -1; + memset(TempBuffer, 0, sizeof(TempBuffer)); } }; @@ -494,10 +543,10 @@ struct IMGUI_API ImGuiDrawContext float PrevLineTextBaseOffset; float LogLinePosY; int TreeDepth; - ImGuiID LastItemID; + ImGuiID LastItemId; ImRect LastItemRect; - bool LastItemHoveredAndUsable; - bool LastItemHoveredRect; + bool LastItemHoveredAndUsable; // Item rectangle is hovered, and its window is currently interactable with (not blocked by a popup preventing access to the window) + bool LastItemHoveredRect; // Item rectangle is hovered, but its window may or not be currently interactable with (might be blocked by a popup preventing access to the window) bool MenuBarAppending; float MenuBarOffsetX; ImVector ChildWindows; @@ -517,16 +566,19 @@ struct IMGUI_API ImGuiDrawContext ImGuiColorEditMode ColorEditMode; int StackSizesBackup[6]; // Store size of various stacks for asserting - float ColumnsStartX; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) + float IndentX; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) + float GroupOffsetX; float ColumnsOffsetX; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API. int ColumnsCurrent; int ColumnsCount; - ImVec2 ColumnsStartPos; + float ColumnsMinX; + float ColumnsMaxX; + float ColumnsStartPosY; float ColumnsCellMinY; float ColumnsCellMaxY; bool ColumnsShowBorders; - ImGuiID ColumnsSetID; - ImVector ColumnsOffsetsT; // Columns offset normalized 0.0 (far left) -> 1.0 (far right) + ImGuiID ColumnsSetId; + ImVector ColumnsData; ImGuiDrawContext() { @@ -535,7 +587,7 @@ struct IMGUI_API ImGuiDrawContext CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; LogLinePosY = -1.0f; TreeDepth = 0; - LastItemID = 0; + LastItemId = 0; LastItemRect = ImRect(0.0f,0.0f,0.0f,0.0f); LastItemHoveredAndUsable = LastItemHoveredRect = false; MenuBarAppending = false; @@ -549,14 +601,16 @@ struct IMGUI_API ImGuiDrawContext ColorEditMode = ImGuiColorEditMode_RGB; memset(StackSizesBackup, 0, sizeof(StackSizesBackup)); - ColumnsStartX = 0.0f; + IndentX = 0.0f; + GroupOffsetX = 0.0f; ColumnsOffsetX = 0.0f; ColumnsCurrent = 0; ColumnsCount = 1; - ColumnsStartPos = ImVec2(0.0f, 0.0f); + ColumnsMinX = ColumnsMaxX = 0.0f; + ColumnsStartPosY = 0.0f; ColumnsCellMinY = ColumnsCellMaxY = 0.0f; ColumnsShowBorders = true; - ColumnsSetID = 0; + ColumnsSetId = 0; } }; @@ -564,28 +618,31 @@ struct IMGUI_API ImGuiDrawContext struct IMGUI_API ImGuiWindow { char* Name; - ImGuiID ID; - ImGuiWindowFlags Flags; + ImGuiID ID; // == ImHash(Name) + ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_ + int IndexWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0. ImVec2 PosFloat; ImVec2 Pos; // Position rounded-up to nearest pixel ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) ImVec2 SizeFull; // Size when non collapsed ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame ImVec2 SizeContentsExplicit; // Size of contents explicitly set by the user via SetNextWindowContentSize() + ImRect ContentsRegionRect; // Maximum visible content position in window coordinates. ~~ (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis ImVec2 WindowPadding; // Window padding at the time of begin. We need to lock it, in particular manipulation of the ShowBorder would have an effect - ImGuiID MoveID; // == window->GetID("#MOVE") + ImGuiID MoveId; // == window->GetID("#MOVE") ImVec2 Scroll; ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change) ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered bool ScrollbarX, ScrollbarY; - ImVec2 ScrollbarSizes; // + ImVec2 ScrollbarSizes; + float BorderSize; bool Active; // Set to true on Begin() bool WasActive; bool Accessed; // Set to true when any widget access the current window bool Collapsed; // Set when collapsing window to become only title-bar bool SkipItems; // == Visible && !Collapsed int BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) - ImGuiID PopupID; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling) + ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling) int AutoFitFramesX, AutoFitFramesY; bool AutoFitOnlyGrows; int AutoPosLastDirection; @@ -598,17 +655,18 @@ struct IMGUI_API ImGuiWindow ImGuiDrawContext DC; // Temporary per-window data, reset at the beginning of the frame ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack ImRect ClipRect; // = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2. - ImRect ClippedWindowRect; // = ClipRect just after setup in Begin() + ImRect WindowRectClipped; // = WindowRect just after setup in Begin(). == window->Rect() for root window. int LastFrameActive; float ItemWidthDefault; ImGuiSimpleColumns MenuColumns; // Simplified columns storage for menu items ImGuiStorage StateStorage; float FontWindowScale; // Scale multiplier per-window ImDrawList* DrawList; - ImGuiWindow* RootWindow; - ImGuiWindow* RootNonPopupWindow; + ImGuiWindow* RootWindow; // If we are a child window, this is pointing to the first non-child parent window. Else point to ourself. + ImGuiWindow* RootNonPopupWindow; // If we are a child window, this is pointing to the first non-child non-popup parent window. Else point to ourself. + ImGuiWindow* ParentWindow; // If we are a child window, this is pointing to our parent window. Else point to NULL. - // Focus + // Navigation / Focus int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister() int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through) int FocusIdxAllRequestCurrent; // Item being requested for focus @@ -622,6 +680,7 @@ struct IMGUI_API ImGuiWindow ImGuiID GetID(const char* str, const char* str_end = NULL); ImGuiID GetID(const void* ptr); + ImGuiID GetIDNoKeepAlive(const char* str, const char* str_end = NULL); ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); } float CalcFontSize() const { return GImGui->FontBaseSize * FontWindowScale; } @@ -629,8 +688,6 @@ struct IMGUI_API ImGuiWindow ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); } float MenuBarHeight() const { return (Flags & ImGuiWindowFlags_MenuBar) ? CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f : 0.0f; } ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); } - ImU32 Color(ImGuiCol idx, float a=1.f) const { ImVec4 c = GImGui->Style.Colors[idx]; c.w *= GImGui->Style.Alpha * a; return ImGui::ColorConvertFloat4ToU32(c); } - ImU32 Color(const ImVec4& col) const { ImVec4 c = col; c.w *= GImGui->Style.Alpha; return ImGui::ColorConvertFloat4ToU32(c); } }; //----------------------------------------------------------------------------- @@ -644,17 +701,19 @@ namespace ImGui // If this ever crash because g.CurrentWindow is NULL it means that either // - ImGui::NewFrame() has never been called, which is illegal. // - You are calling ImGui functions after ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal. - inline ImGuiWindow* GetCurrentWindowRead() { ImGuiState& g = *GImGui; return g.CurrentWindow; } - inline ImGuiWindow* GetCurrentWindow() { ImGuiState& g = *GImGui; g.CurrentWindow->Accessed = true; return g.CurrentWindow; } + inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; } + inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->Accessed = true; return g.CurrentWindow; } IMGUI_API ImGuiWindow* GetParentWindow(); + IMGUI_API ImGuiWindow* FindWindowByName(const char* name); IMGUI_API void FocusWindow(ImGuiWindow* window); + IMGUI_API void EndFrame(); // Ends the ImGui frame. Automatically called by Render()! you most likely don't need to ever call that yourself directly. If you don't need to render you can call EndFrame() but you'll have wasted CPU already. If you don't need to render, don't create any windows instead! + IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window); + IMGUI_API void ClearActiveID(); IMGUI_API void SetHoveredID(ImGuiID id); IMGUI_API void KeepAliveID(ImGuiID id); - IMGUI_API void EndFrame(); // This automatically called by Render() - IMGUI_API void ItemSize(const ImVec2& size, float text_offset_y = 0.0f); IMGUI_API void ItemSize(const ImRect& bb, float text_offset_y = 0.0f); IMGUI_API bool ItemAdd(const ImRect& bb, const ImGuiID* id); @@ -665,18 +724,25 @@ namespace ImGui IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_x, float default_y); IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); + IMGUI_API void OpenPopupEx(const char* str_id, bool reopen_existing); + // NB: All position are in absolute pixels coordinates (not window coordinates) + // FIXME: All those functions are a mess and needs to be refactored into something decent. AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. + // We need: a sort of symbol library, preferably baked into font atlas when possible + decent text rendering helpers. IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); - IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, ImGuiAlign align = ImGuiAlign_Default, const ImVec2* clip_min = NULL, const ImVec2* clip_max = NULL); + IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0,0), const ImRect* clip_rect = NULL); IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); - IMGUI_API void RenderCollapseTriangle(ImVec2 p_min, bool opened, float scale = 1.0f, bool shadow = false); + IMGUI_API void RenderCollapseTriangle(ImVec2 pos, bool is_open, float scale = 1.0f); + IMGUI_API void RenderBullet(ImVec2 pos); IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col); + IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text. - IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, bool allow_key_modifiers, ImGuiButtonFlags flags = 0); + IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0,0), ImGuiButtonFlags flags = 0); + IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos, float radius); - IMGUI_API bool SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, bool horizontal); + IMGUI_API bool SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags = 0); IMGUI_API bool SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power); IMGUI_API bool SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format); @@ -690,14 +756,20 @@ namespace ImGui IMGUI_API bool InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags); IMGUI_API bool InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision); - IMGUI_API bool TreeNodeBehaviorIsOpened(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextTreeNodeOpened() data, if any. May return true when logging + IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); + IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextTreeNodeOpened() data, if any. May return true when logging + IMGUI_API void TreePushRawID(ImGuiID id); IMGUI_API void PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size); IMGUI_API int ParseFormatPrecision(const char* fmt, int default_value); IMGUI_API float RoundScalar(float value, int decimal_precision); -} // namespace ImGuiP +} // namespace ImGui + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif #ifdef _MSC_VER #pragma warning (pop) diff --git a/Externals/imgui-1.46/Include/stb_rect_pack.h b/SampleFramework12/v1.01/ImGui/stb_rect_pack.h similarity index 89% rename from Externals/imgui-1.46/Include/stb_rect_pack.h rename to SampleFramework12/v1.01/ImGui/stb_rect_pack.h index eb0ef2f..c75527d 100644 --- a/Externals/imgui-1.46/Include/stb_rect_pack.h +++ b/SampleFramework12/v1.01/ImGui/stb_rect_pack.h @@ -1,4 +1,4 @@ -// stb_rect_pack.h - v0.05 - public domain - rectangle packing +// stb_rect_pack.h - v0.10 - public domain - rectangle packing // Sean Barrett 2014 // // Useful for e.g. packing rectangular textures into an atlas. @@ -13,6 +13,7 @@ // More docs to come. // // No memory allocations; uses qsort() and assert() from stdlib. +// Can override those by defining STBRP_SORT and STBRP_ASSERT. // // This library currently uses the Skyline Bottom-Left algorithm. // @@ -20,11 +21,31 @@ // implement them to the same API, but with a different init // function. // +// Credits +// +// Library +// Sean Barrett +// Minor features +// Martins Mozeiko +// Bugfixes / warning fixes +// Jeremy Jaussaud +// // Version history: // +// 0.10 (2016-10-25) remove cast-away-const to avoid warnings +// 0.09 (2016-08-27) fix compiler warnings +// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) +// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) +// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort // 0.05: added STBRP_ASSERT to allow replacing assert // 0.04: fixed minor bug in STBRP_LARGE_RECTS support // 0.01: initial release +// +// LICENSE +// +// This software is dual-licensed to the public domain and under the following +// license: you are granted a perpetual, irrevocable license to copy, modify, +// publish, and distribute this file as you see fit. ////////////////////////////////////////////////////////////////////////////// // @@ -169,13 +190,22 @@ struct stbrp_context // #ifdef STB_RECT_PACK_IMPLEMENTATION +#ifndef STBRP_SORT #include +#define STBRP_SORT qsort +#endif #ifndef STBRP_ASSERT #include #define STBRP_ASSERT assert #endif +#ifdef _MSC_VER +#define STBRP__NOTUSED(v) (void)(v) +#else +#define STBRP__NOTUSED(v) (void)sizeof(v) +#endif + enum { STBRP__INIT_skyline = 1 @@ -248,10 +278,12 @@ STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, // find minimum y position if it starts at x1 static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste) { - (void)c; stbrp_node *node = first; int x1 = x0 + width; int min_y, visited_width, waste_area; + + STBRP__NOTUSED(c); + STBRP_ASSERT(first->x <= x0); #if 0 @@ -479,8 +511,8 @@ static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, i static int rect_height_compare(const void *a, const void *b) { - stbrp_rect *p = (stbrp_rect *) a; - stbrp_rect *q = (stbrp_rect *) b; + const stbrp_rect *p = (const stbrp_rect *) a; + const stbrp_rect *q = (const stbrp_rect *) b; if (p->h > q->h) return -1; if (p->h < q->h) @@ -490,8 +522,8 @@ static int rect_height_compare(const void *a, const void *b) static int rect_width_compare(const void *a, const void *b) { - stbrp_rect *p = (stbrp_rect *) a; - stbrp_rect *q = (stbrp_rect *) b; + const stbrp_rect *p = (const stbrp_rect *) a; + const stbrp_rect *q = (const stbrp_rect *) b; if (p->w > q->w) return -1; if (p->w < q->w) @@ -501,8 +533,8 @@ static int rect_width_compare(const void *a, const void *b) static int rect_original_order(const void *a, const void *b) { - stbrp_rect *p = (stbrp_rect *) a; - stbrp_rect *q = (stbrp_rect *) b; + const stbrp_rect *p = (const stbrp_rect *) a; + const stbrp_rect *q = (const stbrp_rect *) b; return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); } @@ -525,20 +557,24 @@ STBRP_DEF void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int n } // sort according to heuristic - qsort(rects, num_rects, sizeof(rects[0]), rect_height_compare); + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare); for (i=0; i < num_rects; ++i) { - stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); - if (fr.prev_link) { - rects[i].x = (stbrp_coord) fr.x; - rects[i].y = (stbrp_coord) fr.y; + if (rects[i].w == 0 || rects[i].h == 0) { + rects[i].x = rects[i].y = 0; // empty rect needs no space } else { - rects[i].x = rects[i].y = STBRP__MAXVAL; + stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); + if (fr.prev_link) { + rects[i].x = (stbrp_coord) fr.x; + rects[i].y = (stbrp_coord) fr.y; + } else { + rects[i].x = rects[i].y = STBRP__MAXVAL; + } } } // unsort - qsort(rects, num_rects, sizeof(rects[0]), rect_original_order); + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order); // set was_packed flags for (i=0; i < num_rects; ++i) diff --git a/Externals/imgui-1.46/Include/stb_textedit.h b/SampleFramework12/v1.01/ImGui/stb_textedit.h similarity index 87% rename from Externals/imgui-1.46/Include/stb_textedit.h rename to SampleFramework12/v1.01/ImGui/stb_textedit.h index 3972c0f..4b731a0 100644 --- a/Externals/imgui-1.46/Include/stb_textedit.h +++ b/SampleFramework12/v1.01/ImGui/stb_textedit.h @@ -1,7 +1,10 @@ -// [ImGui] this is a slightly modified version of stb_truetype.h 1.4 -// [ImGui] we made a fix for using the END key on multi-line text edit, see https://github.com/ocornut/imgui/issues/275 +// [ImGui] this is a slightly modified version of stb_truetype.h 1.9. Those changes would need to be pushed into nothings/sb +// [ImGui] - fixed linestart handler when over last character of multi-line buffer + simplified existing code (#588, #815) +// [ImGui] - fixed a state corruption/crash bug in stb_text_redo and stb_textedit_discard_redo (#715) +// [ImGui] - fixed a crash bug in stb_textedit_discard_redo (#681) +// [ImGui] - fixed some minor warnings -// stb_textedit.h - v1.4 - public domain - Sean Barrett +// stb_textedit.h - v1.9 - public domain - Sean Barrett // Development of this library was sponsored by RAD Game Tools // // This C header file implements the guts of a multi-line text-editing @@ -20,19 +23,25 @@ // // LICENSE // -// This software has been placed in the public domain by its author. -// Where that dedication is not recognized, you are granted a perpetual, -// irrevocable license to copy and modify this file as you see fit. +// This software is dual-licensed to the public domain and under the following +// license: you are granted a perpetual, irrevocable license to copy, modify, +// publish, and distribute this file as you see fit. // // // DEPENDENCIES // -// Uses the C runtime function 'memmove'. Uses no other functions. -// Performs no runtime allocations. +// Uses the C runtime function 'memmove', which you can override +// by defining STB_TEXTEDIT_memmove before the implementation. +// Uses no other functions. Performs no runtime allocations. // // // VERSION HISTORY // +// 1.9 (2016-08-27) customizable move-by-word +// 1.8 (2016-04-02) better keyboard handling when mouse button is down +// 1.7 (2015-09-13) change y range handling in case baseline is non-0 +// 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove +// 1.5 (2014-09-10) add support for secondary keys for OS X // 1.4 (2014-08-17) fix signed/unsigned warnings // 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary // 1.2 (2014-05-27) fix some RAD types that had crept into the new code @@ -45,7 +54,13 @@ // ADDITIONAL CONTRIBUTORS // // Ulf Winklemann: move-by-word in 1.1 -// Scott Graham: mouse selection bugfix in 1.3 +// Fabian Giesen: secondary key inputs in 1.5 +// Martins Mozeiko: STB_TEXTEDIT_memmove +// +// Bugfixes: +// Scott Graham +// Daniel Keller +// Omar Cornut // // USAGE // @@ -140,11 +155,17 @@ // STB_TEXTEDIT_K_REDO keyboard input to perform redo // // Optional: -// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode -// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), -// required for WORDLEFT/WORDRIGHT -// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT -// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT +// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode +// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), +// required for default WORDLEFT/WORDRIGHT handlers +// STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to +// STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to +// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT +// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT +// STB_TEXTEDIT_K_LINESTART2 secondary keyboard input to move cursor to start of line +// STB_TEXTEDIT_K_LINEEND2 secondary keyboard input to move cursor to end of line +// STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text +// STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text // // Todo: // STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page @@ -355,7 +376,10 @@ typedef struct // included just the "header" portion #ifdef STB_TEXTEDIT_IMPLEMENTATION -#include // memmove +#ifndef STB_TEXTEDIT_memmove +#include +#define STB_TEXTEDIT_memmove memmove +#endif ///////////////////////////////////////////////////////////////////////////// @@ -371,9 +395,6 @@ static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) float base_y = 0, prev_x; int i=0, k; - if (y < 0) - return 0; - r.x0 = r.x1 = 0; r.ymin = r.ymax = 0; r.num_chars = 0; @@ -384,6 +405,9 @@ static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) if (r.num_chars <= 0) return n; + if (i==0 && y < base_y + r.ymin) + return 0; + if (y < base_y + r.ymax) break; @@ -402,10 +426,9 @@ static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) // check if it's before the end of the line if (x < r.x1) { // search characters in row for one that straddles 'x' - k = i; prev_x = r.x0; - for (i=0; i < r.num_chars; ++i) { - float w = STB_TEXTEDIT_GETWIDTH(str, k, i); + for (k=0; k < r.num_chars; ++k) { + float w = STB_TEXTEDIT_GETWIDTH(str, i, k); if (x < prev_x+w) { if (x < prev_x+w/2) return k+i; @@ -437,6 +460,8 @@ static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *stat static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) { int p = stb_text_locate_coord(str, x, y); + if (state->select_start == state->select_end) + state->select_start = state->cursor; state->cursor = state->select_end = p; } @@ -593,15 +618,16 @@ static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditStat } #ifdef STB_TEXTEDIT_IS_SPACE -static int is_word_boundary( STB_TEXTEDIT_STRING *_str, int _idx ) +static int is_word_boundary( STB_TEXTEDIT_STRING *str, int idx ) { - return _idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(_str,_idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(_str, _idx) ) ) : 1; + return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1; } -static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *_str, STB_TexteditState *_state ) +#ifndef STB_TEXTEDIT_MOVEWORDLEFT +static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *str, int c ) { - int c = _state->cursor - 1; - while( c >= 0 && !is_word_boundary( _str, c ) ) + --c; // always move at least one character + while( c >= 0 && !is_word_boundary( str, c ) ) --c; if( c < 0 ) @@ -609,12 +635,15 @@ static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *_str, STB_Te return c; } +#define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous +#endif -static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *_str, STB_TexteditState *_state ) +#ifndef STB_TEXTEDIT_MOVEWORDRIGHT +static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *str, int c ) { - const int len = STB_TEXTEDIT_STRINGLEN(_str); - int c = _state->cursor+1; - while( c < len && !is_word_boundary( _str, c ) ) + const int len = STB_TEXTEDIT_STRINGLEN(str); + ++c; // always move at least one character + while( c < len && !is_word_boundary( str, c ) ) ++c; if( c > len ) @@ -622,6 +651,9 @@ static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *_str, STB_Texted return c; } +#define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next +#endif + #endif // update selection and cursor to match each other @@ -743,21 +775,12 @@ static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, state->has_preferred_x = 0; break; -#ifdef STB_TEXTEDIT_IS_SPACE +#ifdef STB_TEXTEDIT_MOVEWORDLEFT case STB_TEXTEDIT_K_WORDLEFT: if (STB_TEXT_HAS_SELECTION(state)) stb_textedit_move_to_first(state); else { - state->cursor = stb_textedit_move_to_word_previous(str, state); - stb_textedit_clamp( str, state ); - } - break; - - case STB_TEXTEDIT_K_WORDRIGHT: - if (STB_TEXT_HAS_SELECTION(state)) - stb_textedit_move_to_last(str, state); - else { - state->cursor = stb_textedit_move_to_word_next(str, state); + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); stb_textedit_clamp( str, state ); } break; @@ -766,17 +789,28 @@ static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, if( !STB_TEXT_HAS_SELECTION( state ) ) stb_textedit_prep_selection_at_cursor(state); - state->cursor = stb_textedit_move_to_word_previous(str, state); + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); state->select_end = state->cursor; stb_textedit_clamp( str, state ); break; +#endif + +#ifdef STB_TEXTEDIT_MOVEWORDRIGHT + case STB_TEXTEDIT_K_WORDRIGHT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else { + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); + stb_textedit_clamp( str, state ); + } + break; case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT: if( !STB_TEXT_HAS_SELECTION( state ) ) stb_textedit_prep_selection_at_cursor(state); - state->cursor = stb_textedit_move_to_word_next(str, state); + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); state->select_end = state->cursor; stb_textedit_clamp( str, state ); @@ -920,23 +954,35 @@ static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, state->has_preferred_x = 0; break; +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2: +#endif case STB_TEXTEDIT_K_TEXTSTART: state->cursor = state->select_start = state->select_end = 0; state->has_preferred_x = 0; break; +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2: +#endif case STB_TEXTEDIT_K_TEXTEND: state->cursor = STB_TEXTEDIT_STRINGLEN(str); state->select_start = state->select_end = 0; state->has_preferred_x = 0; break; +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT: +#endif case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT: stb_textedit_prep_selection_at_cursor(state); state->cursor = state->select_end = 0; state->has_preferred_x = 0; break; +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT: +#endif case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT: stb_textedit_prep_selection_at_cursor(state); state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str); @@ -944,46 +990,60 @@ static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, break; - case STB_TEXTEDIT_K_LINESTART: { - StbFindState find; +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2: +#endif + case STB_TEXTEDIT_K_LINESTART: stb_textedit_clamp(str, state); stb_textedit_move_to_first(state); - stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); - state->cursor = find.first_char; + if (state->single_line) + state->cursor = 0; + else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) + --state->cursor; state->has_preferred_x = 0; break; - } +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2: +#endif case STB_TEXTEDIT_K_LINEEND: { - StbFindState find; + int n = STB_TEXTEDIT_STRINGLEN(str); stb_textedit_clamp(str, state); stb_textedit_move_to_first(state); - stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); - state->cursor = find.first_char + find.length; - if (find.length > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) == STB_TEXTEDIT_NEWLINE) - state->cursor--; + if (state->single_line) + state->cursor = n; + else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) + ++state->cursor; state->has_preferred_x = 0; break; } - case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: { - StbFindState find; +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: stb_textedit_clamp(str, state); stb_textedit_prep_selection_at_cursor(state); - stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); - state->cursor = state->select_end = find.first_char; + if (state->single_line) + state->cursor = 0; + else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) + --state->cursor; + state->select_end = state->cursor; state->has_preferred_x = 0; break; - } +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT: +#endif case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: { - StbFindState find; + int n = STB_TEXTEDIT_STRINGLEN(str); stb_textedit_clamp(str, state); stb_textedit_prep_selection_at_cursor(state); - stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); - state->cursor = state->select_end = find.first_char + find.length; - if (find.length > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) == STB_TEXTEDIT_NEWLINE) - state->cursor = state->select_end = state->cursor - 1; + if (state->single_line) + state->cursor = n; + else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) + ++state->cursor; + state->select_end = state->cursor; state->has_preferred_x = 0; break; } @@ -1015,13 +1075,13 @@ static void stb_textedit_discard_undo(StbUndoState *state) int n = state->undo_rec[0].insert_length, i; // delete n characters from all other records state->undo_char_point = state->undo_char_point - (short) n; // vsnet05 - memmove(state->undo_char, state->undo_char + n, (size_t) ((size_t)state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE))); + STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) ((size_t)state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE))); for (i=0; i < state->undo_point; ++i) if (state->undo_rec[i].char_storage >= 0) state->undo_rec[i].char_storage = state->undo_rec[i].char_storage - (short) n; // vsnet05 // @OPTIMIZE: get rid of char_storage and infer it } --state->undo_point; - memmove(state->undo_rec, state->undo_rec+1, (size_t) ((size_t)state->undo_point*sizeof(state->undo_rec[0]))); + STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) ((size_t)state->undo_point*sizeof(state->undo_rec[0]))); } } @@ -1039,13 +1099,13 @@ static void stb_textedit_discard_redo(StbUndoState *state) int n = state->undo_rec[k].insert_length, i; // delete n characters from all other records state->redo_char_point = state->redo_char_point + (short) n; // vsnet05 - memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE))); + STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((size_t)(STB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE))); for (i=state->redo_point; i < k; ++i) if (state->undo_rec[i].char_storage >= 0) state->undo_rec[i].char_storage = state->undo_rec[i].char_storage + (short) n; // vsnet05 } + STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point, state->undo_rec + state->redo_point-1, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0]))); ++state->redo_point; - memmove(state->undo_rec + state->redo_point-1, state->undo_rec + state->redo_point, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0]))); } } @@ -1203,6 +1263,7 @@ static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) if (r.insert_length) { // easy case: need to insert n characters STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length); + s->redo_char_point += r.insert_length; } state->cursor = r.where + r.insert_length; diff --git a/Externals/imgui-1.46/Include/stb_truetype.h b/SampleFramework12/v1.01/ImGui/stb_truetype.h similarity index 78% rename from Externals/imgui-1.46/Include/stb_truetype.h rename to SampleFramework12/v1.01/ImGui/stb_truetype.h index 3eba786..92b9a87 100644 --- a/Externals/imgui-1.46/Include/stb_truetype.h +++ b/SampleFramework12/v1.01/ImGui/stb_truetype.h @@ -1,5 +1,5 @@ -// stb_truetype.h - v1.07 - public domain -// authored from 2009-2015 by Sean Barrett / RAD Game Tools +// stb_truetype.h - v1.14 - public domain +// authored from 2009-2016 by Sean Barrett / RAD Game Tools // // This library processes TrueType files: // parse files @@ -20,6 +20,12 @@ // // Mikko Mononen: compound shape support, more cmap formats // Tor Andersson: kerning, subpixel rendering +// Dougall Johnson: OpenType / Type 2 font handling +// +// Misc other: +// Ryan Gordon +// Simon Glass +// github:IntellectualKitty // // Bug/warning reports/fixes: // "Zer" on mollyrocket (with fix) @@ -39,32 +45,33 @@ // Omar Cornut // github:aloucks // Peter LaValle +// Sergey Popov // Giumo X. Clanjor -// -// Misc other: -// Ryan Gordon +// Higor Euripedes +// Thomas Fields +// Derek Vinyard // // VERSION HISTORY // +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts, num-fonts-in-TTC function +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; // variant PackFontRanges to pack and render in separate phases; // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); // fixed an assert() bug in the new rasterizer // replace assert() with STBTT_assert() in new rasterizer -// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) -// also more precise AA rasterizer, except if shapes overlap -// remove need for STBTT_sort -// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC -// 1.04 (2015-04-15) typo in example -// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes // // Full history can be found at the end of this file. // // LICENSE // -// This software is in the public domain. Where that dedication is not -// recognized, you are granted a perpetual, irrevocable license to copy, -// distribute, and modify this file as you see fit. +// This software is dual-licensed to the public domain and under the following +// license: you are granted a perpetual, irrevocable license to copy, modify, +// publish, and distribute this file as you see fit. // // USAGE // @@ -91,7 +98,8 @@ // // "Load" a font file from a memory buffer (you have to keep the buffer loaded) // stbtt_InitFont() -// stbtt_GetFontOffsetForIndex() -- use for TTC font collections +// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections +// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections // // Render a unicode codepoint to a bitmap // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap @@ -400,6 +408,11 @@ int main(int arg, char **argv) #define STBTT_sqrt(x) sqrt(x) #endif + #ifndef STBTT_fabs + #include + #define STBTT_fabs(x) fabs(x) + #endif + // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h #ifndef STBTT_malloc #include @@ -444,6 +457,14 @@ int main(int arg, char **argv) extern "C" { #endif +// private structure +typedef struct +{ + unsigned char *data; + int cursor; + int size; +} stbtt__buf; + ////////////////////////////////////////////////////////////////////////////// // // TEXTURE BAKING API @@ -513,7 +534,7 @@ typedef struct stbrp_rect stbrp_rect; STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); // Initializes a packing context stored in the passed-in stbtt_pack_context. // Future calls using this context will pack characters into the bitmap passed -// in here: a 1-channel bitmap that is weight x height. stride_in_bytes is +// in here: a 1-channel bitmap that is width * height. stride_in_bytes is // the distance from one row to the next (or 0 to mean they are packed tightly // together). "padding" is the amount of padding to leave between each // character (normally you want '1' for bitmaps you'll use as textures with @@ -579,9 +600,9 @@ STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, stbtt_aligned_quad *q, // output: quad to draw int align_to_integer); -STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); -STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); // Calling these functions in sequence is roughly equivalent to calling // stbtt_PackFontRanges(). If you more control over the packing of multiple // fonts, or if you want to pack custom data into a font texture, take a look @@ -612,18 +633,23 @@ struct stbtt_pack_context { // // +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); +// This function will determine the number of fonts in a font file. TrueType +// collection (.ttc) files may contain multiple fonts, while TrueType font +// (.ttf) files only contain one font. The number of fonts can be used for +// indexing with the previous function where the index is between zero and one +// less than the total fonts. If an error occurs, -1 is returned. + STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); // Each .ttf/.ttc file may have more than one font. Each font has a sequential // index number starting from 0. Call this function to get the font offset for // a given index; it returns -1 if the index is out of range. A regular .ttf // file will only define one font and it always be at offset 0, so it will -// return '0' for index 0, and -1 for all other indices. You can just skip -// this step if you know it's that kind of font. - +// return '0' for index 0, and -1 for all other indices. // The following structure is defined publically so you can declare one on // the stack or as a global or etc, but you should treat it as opaque. -typedef struct stbtt_fontinfo +struct stbtt_fontinfo { void * userdata; unsigned char * data; // pointer to .ttf file @@ -634,7 +660,14 @@ typedef struct stbtt_fontinfo int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf int index_map; // a cmap mapping for our chosen character encoding int indexToLocFormat; // format needed to map from glyph index to glyph -} stbtt_fontinfo; + + stbtt__buf cff; // cff font data + stbtt__buf charstrings; // the charstring index + stbtt__buf gsubrs; // global charstring subroutines index + stbtt__buf subrs; // private charstring subroutines index + stbtt__buf fontdicts; // array of font dicts + stbtt__buf fdselect; // map from glyph to fontdict +}; STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); // Given an offset into the file that defines a font, this function builds @@ -711,7 +744,8 @@ STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, in enum { STBTT_vmove=1, STBTT_vline, - STBTT_vcurve + STBTT_vcurve, + STBTT_vcubic }; #endif @@ -720,7 +754,7 @@ STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, in #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file typedef struct { - stbtt_vertex_type x,y,cx,cy; + stbtt_vertex_type x,y,cx,cy,cx1,cy1; unsigned char type,padding; } stbtt_vertex; #endif @@ -802,7 +836,16 @@ typedef struct unsigned char *pixels; } stbtt__bitmap; -STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata); +// rasterize a shape with quadratic beziers into a bitmap +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into + float flatness_in_pixels, // allowable error of curve in pixels + stbtt_vertex *vertices, // array of vertices defining shape + int num_verts, // number of vertices in above array + float scale_x, float scale_y, // scale applied to input vertices + float shift_x, float shift_y, // translation applied to input vertices + int x_off, int y_off, // another translation applied to input + int invert, // if non-zero, vertically flip shape + void *userdata); // context for to STBTT_MALLOC ////////////////////////////////////////////////////////////////////////////// // @@ -927,6 +970,158 @@ typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERS #define STBTT_RASTERIZER_VERSION 2 #endif +#ifdef _MSC_VER +#define STBTT__NOTUSED(v) (void)(v) +#else +#define STBTT__NOTUSED(v) (void)sizeof(v) +#endif + +////////////////////////////////////////////////////////////////////////// +// +// stbtt__buf helpers to parse data from file +// + +static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor++]; +} + +static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor]; +} + +static void stbtt__buf_seek(stbtt__buf *b, int o) +{ + STBTT_assert(!(o > b->size || o < 0)); + b->cursor = (o > b->size || o < 0) ? b->size : o; +} + +static void stbtt__buf_skip(stbtt__buf *b, int o) +{ + stbtt__buf_seek(b, b->cursor + o); +} + +static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) +{ + stbtt_uint32 v = 0; + int i; + STBTT_assert(n >= 1 && n <= 4); + for (i = 0; i < n; i++) + v = (v << 8) | stbtt__buf_get8(b); + return v; +} + +static stbtt__buf stbtt__new_buf(const void *p, size_t size) +{ + stbtt__buf r; + STBTT_assert(size < 0x40000000); + r.data = (stbtt_uint8*) p; + r.size = (int) size; + r.cursor = 0; + return r; +} + +#define stbtt__buf_get16(b) stbtt__buf_get((b), 2) +#define stbtt__buf_get32(b) stbtt__buf_get((b), 4) + +static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) +{ + stbtt__buf r = stbtt__new_buf(NULL, 0); + if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; + r.data = b->data + o; + r.size = s; + return r; +} + +static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) +{ + int count, start, offsize; + start = b->cursor; + count = stbtt__buf_get16(b); + if (count) { + offsize = stbtt__buf_get8(b); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(b, offsize * count); + stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); + } + return stbtt__buf_range(b, start, b->cursor - start); +} + +static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) +{ + int b0 = stbtt__buf_get8(b); + if (b0 >= 32 && b0 <= 246) return b0 - 139; + else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; + else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; + else if (b0 == 28) return stbtt__buf_get16(b); + else if (b0 == 29) return stbtt__buf_get32(b); + STBTT_assert(0); + return 0; +} + +static void stbtt__cff_skip_operand(stbtt__buf *b) { + int v, b0 = stbtt__buf_peek8(b); + STBTT_assert(b0 >= 28); + if (b0 == 30) { + stbtt__buf_skip(b, 1); + while (b->cursor < b->size) { + v = stbtt__buf_get8(b); + if ((v & 0xF) == 0xF || (v >> 4) == 0xF) + break; + } + } else { + stbtt__cff_int(b); + } +} + +static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) +{ + stbtt__buf_seek(b, 0); + while (b->cursor < b->size) { + int start = b->cursor, end, op; + while (stbtt__buf_peek8(b) >= 28) + stbtt__cff_skip_operand(b); + end = b->cursor; + op = stbtt__buf_get8(b); + if (op == 12) op = stbtt__buf_get8(b) | 0x100; + if (op == key) return stbtt__buf_range(b, start, end-start); + } + return stbtt__buf_range(b, 0, 0); +} + +static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) +{ + int i; + stbtt__buf operands = stbtt__dict_get(b, key); + for (i = 0; i < outcount && operands.cursor < operands.size; i++) + out[i] = stbtt__cff_int(&operands); +} + +static int stbtt__cff_index_count(stbtt__buf *b) +{ + stbtt__buf_seek(b, 0); + return stbtt__buf_get16(b); +} + +static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) +{ + int count, offsize, start, end; + stbtt__buf_seek(&b, 0); + count = stbtt__buf_get16(&b); + offsize = stbtt__buf_get8(&b); + STBTT_assert(i >= 0 && i < count); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(&b, i*offsize); + start = stbtt__buf_get(&b, offsize); + end = stbtt__buf_get(&b, offsize); + return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); +} + ////////////////////////////////////////////////////////////////////////// // // accessors to parse data from file @@ -939,32 +1134,22 @@ typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERS #define ttCHAR(p) (* (stbtt_int8 *) (p)) #define ttFixed(p) ttLONG(p) -#if defined(STB_TRUETYPE_BIGENDIAN) && !defined(ALLOW_UNALIGNED_TRUETYPE) - - #define ttUSHORT(p) (* (stbtt_uint16 *) (p)) - #define ttSHORT(p) (* (stbtt_int16 *) (p)) - #define ttULONG(p) (* (stbtt_uint32 *) (p)) - #define ttLONG(p) (* (stbtt_int32 *) (p)) - -#else - - static stbtt_uint16 ttUSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; } - static stbtt_int16 ttSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; } - static stbtt_uint32 ttULONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } - static stbtt_int32 ttLONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } - -#endif +static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } +static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) #define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) -static int stbtt__isfont(const stbtt_uint8 *font) +static int stbtt__isfont(stbtt_uint8 *font) { // check the version number if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 + if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts return 0; } @@ -982,7 +1167,7 @@ static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, return 0; } -STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *font_collection, int index) +static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) { // if it's just a font, there's only one valid index if (stbtt__isfont(font_collection)) @@ -1001,14 +1186,43 @@ STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *font_collection, return -1; } -STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data2, int fontstart) +static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) +{ + // if it's just a font, there's only one valid font + if (stbtt__isfont(font_collection)) + return 1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + return ttLONG(font_collection+8); + } + } + return 0; +} + +static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) +{ + stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; + stbtt__buf pdict; + stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); + if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); + pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); + stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); + if (!subrsoff) return stbtt__new_buf(NULL, 0); + stbtt__buf_seek(&cff, private_loc[1]+subrsoff); + return stbtt__cff_get_index(&cff); +} + +static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) { - stbtt_uint8 *data = (stbtt_uint8 *) data2; stbtt_uint32 cmap, t; stbtt_int32 i,numTables; info->data = data; info->fontstart = fontstart; + info->cff = stbtt__new_buf(NULL, 0); cmap = stbtt__find_table(data, fontstart, "cmap"); // required info->loca = stbtt__find_table(data, fontstart, "loca"); // required @@ -1017,8 +1231,61 @@ STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data2, i info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required info->kern = stbtt__find_table(data, fontstart, "kern"); // not required - if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx) + + if (!cmap || !info->head || !info->hhea || !info->hmtx) return 0; + if (info->glyf) { + // required for truetype + if (!info->loca) return 0; + } else { + // initialization for CFF / Type2 fonts (OTF) + stbtt__buf b, topdict, topdictidx; + stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; + stbtt_uint32 cff; + + cff = stbtt__find_table(data, fontstart, "CFF "); + if (!cff) return 0; + + info->fontdicts = stbtt__new_buf(NULL, 0); + info->fdselect = stbtt__new_buf(NULL, 0); + + // @TODO this should use size from table (not 512MB) + info->cff = stbtt__new_buf(data+cff, 512*1024*1024); + b = info->cff; + + // read the header + stbtt__buf_skip(&b, 2); + stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize + + // @TODO the name INDEX could list multiple fonts, + // but we just use the first one. + stbtt__cff_get_index(&b); // name INDEX + topdictidx = stbtt__cff_get_index(&b); + topdict = stbtt__cff_index_get(topdictidx, 0); + stbtt__cff_get_index(&b); // string INDEX + info->gsubrs = stbtt__cff_get_index(&b); + + stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); + stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); + stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); + stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); + info->subrs = stbtt__get_subrs(b, topdict); + + // we only support Type 2 charstrings + if (cstype != 2) return 0; + if (charstrings == 0) return 0; + + if (fdarrayoff) { + // looks like a CID font + if (!fdselectoff) return 0; + stbtt__buf_seek(&b, fdarrayoff); + info->fontdicts = stbtt__cff_get_index(&b); + info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); + } + + stbtt__buf_seek(&b, charstrings); + info->charstrings = stbtt__cff_get_index(&b); + } t = stbtt__find_table(data, fontstart, "maxp"); if (t) @@ -1169,6 +1436,8 @@ static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) { int g1,g2; + STBTT_assert(!info->cff.size); + if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format @@ -1183,15 +1452,21 @@ static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) return g1==g2 ? -1 : g1; // if length is 0, return -1 } +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); + STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { - int g = stbtt__GetGlyfOffset(info, glyph_index); - if (g < 0) return 0; + if (info->cff.size) { + stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); + } else { + int g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 0; - if (x0) *x0 = ttSHORT(info->data + g + 2); - if (y0) *y0 = ttSHORT(info->data + g + 4); - if (x1) *x1 = ttSHORT(info->data + g + 6); - if (y1) *y1 = ttSHORT(info->data + g + 8); + if (x0) *x0 = ttSHORT(info->data + g + 2); + if (y0) *y0 = ttSHORT(info->data + g + 4); + if (x1) *x1 = ttSHORT(info->data + g + 6); + if (y1) *y1 = ttSHORT(info->data + g + 8); + } return 1; } @@ -1203,7 +1478,10 @@ STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, i STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) { stbtt_int16 numberOfContours; - int g = stbtt__GetGlyfOffset(info, glyph_index); + int g; + if (info->cff.size) + return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; + g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 1; numberOfContours = ttSHORT(info->data + g); return numberOfContours == 0; @@ -1225,7 +1503,7 @@ static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_ return num_vertices; } -STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { stbtt_int16 numberOfContours; stbtt_uint8 *endPtsOfContours; @@ -1451,6 +1729,416 @@ STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, s return num_vertices; } +typedef struct +{ + int bounds; + int started; + float first_x, first_y; + float x, y; + stbtt_int32 min_x, max_x, min_y, max_y; + + stbtt_vertex *pvertices; + int num_vertices; +} stbtt__csctx; + +#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} + +static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) +{ + if (x > c->max_x || !c->started) c->max_x = x; + if (y > c->max_y || !c->started) c->max_y = y; + if (x < c->min_x || !c->started) c->min_x = x; + if (y < c->min_y || !c->started) c->min_y = y; + c->started = 1; +} + +static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) +{ + if (c->bounds) { + stbtt__track_vertex(c, x, y); + if (type == STBTT_vcubic) { + stbtt__track_vertex(c, cx, cy); + stbtt__track_vertex(c, cx1, cy1); + } + } else { + stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); + c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; + c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; + } + c->num_vertices++; +} + +static void stbtt__csctx_close_shape(stbtt__csctx *ctx) +{ + if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) +{ + stbtt__csctx_close_shape(ctx); + ctx->first_x = ctx->x = ctx->x + dx; + ctx->first_y = ctx->y = ctx->y + dy; + stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) +{ + ctx->x += dx; + ctx->y += dy; + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) +{ + float cx1 = ctx->x + dx1; + float cy1 = ctx->y + dy1; + float cx2 = cx1 + dx2; + float cy2 = cy1 + dy2; + ctx->x = cx2 + dx3; + ctx->y = cy2 + dy3; + stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); +} + +static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) +{ + int count = stbtt__cff_index_count(&idx); + int bias = 107; + if (count >= 33900) + bias = 32768; + else if (count >= 1240) + bias = 1131; + n += bias; + if (n < 0 || n >= count) + return stbtt__new_buf(NULL, 0); + return stbtt__cff_index_get(idx, n); +} + +static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt__buf fdselect = info->fdselect; + int nranges, start, end, v, fmt, fdselector = -1, i; + + stbtt__buf_seek(&fdselect, 0); + fmt = stbtt__buf_get8(&fdselect); + if (fmt == 0) { + // untested + stbtt__buf_skip(&fdselect, glyph_index); + fdselector = stbtt__buf_get8(&fdselect); + } else if (fmt == 3) { + nranges = stbtt__buf_get16(&fdselect); + start = stbtt__buf_get16(&fdselect); + for (i = 0; i < nranges; i++) { + v = stbtt__buf_get8(&fdselect); + end = stbtt__buf_get16(&fdselect); + if (glyph_index >= start && glyph_index < end) { + fdselector = v; + break; + } + start = end; + } + } + if (fdselector == -1) stbtt__new_buf(NULL, 0); + return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); +} + +static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) +{ + int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; + int has_subrs = 0, clear_stack; + float s[48]; + stbtt__buf subr_stack[10], subrs = info->subrs, b; + float f; + +#define STBTT__CSERR(s) (0) + + // this currently ignores the initial width value, which isn't needed if we have hmtx + b = stbtt__cff_index_get(info->charstrings, glyph_index); + while (b.cursor < b.size) { + i = 0; + clear_stack = 1; + b0 = stbtt__buf_get8(&b); + switch (b0) { + // @TODO implement hinting + case 0x13: // hintmask + case 0x14: // cntrmask + if (in_header) + maskbits += (sp / 2); // implicit "vstem" + in_header = 0; + stbtt__buf_skip(&b, (maskbits + 7) / 8); + break; + + case 0x01: // hstem + case 0x03: // vstem + case 0x12: // hstemhm + case 0x17: // vstemhm + maskbits += (sp / 2); + break; + + case 0x15: // rmoveto + in_header = 0; + if (sp < 2) return STBTT__CSERR("rmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); + break; + case 0x04: // vmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("vmoveto stack"); + stbtt__csctx_rmove_to(c, 0, s[sp-1]); + break; + case 0x16: // hmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("hmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-1], 0); + break; + + case 0x05: // rlineto + if (sp < 2) return STBTT__CSERR("rlineto stack"); + for (; i + 1 < sp; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical + // starting from a different place. + + case 0x07: // vlineto + if (sp < 1) return STBTT__CSERR("vlineto stack"); + goto vlineto; + case 0x06: // hlineto + if (sp < 1) return STBTT__CSERR("hlineto stack"); + for (;;) { + if (i >= sp) break; + stbtt__csctx_rline_to(c, s[i], 0); + i++; + vlineto: + if (i >= sp) break; + stbtt__csctx_rline_to(c, 0, s[i]); + i++; + } + break; + + case 0x1F: // hvcurveto + if (sp < 4) return STBTT__CSERR("hvcurveto stack"); + goto hvcurveto; + case 0x1E: // vhcurveto + if (sp < 4) return STBTT__CSERR("vhcurveto stack"); + for (;;) { + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); + i += 4; + hvcurveto: + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); + i += 4; + } + break; + + case 0x08: // rrcurveto + if (sp < 6) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x18: // rcurveline + if (sp < 8) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp - 2; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + case 0x19: // rlinecurve + if (sp < 8) return STBTT__CSERR("rlinecurve stack"); + for (; i + 1 < sp - 6; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x1A: // vvcurveto + case 0x1B: // hhcurveto + if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); + f = 0.0; + if (sp & 1) { f = s[i]; i++; } + for (; i + 3 < sp; i += 4) { + if (b0 == 0x1B) + stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); + else + stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); + f = 0.0; + } + break; + + case 0x0A: // callsubr + if (!has_subrs) { + if (info->fdselect.size) + subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); + has_subrs = 1; + } + // fallthrough + case 0x1D: // callgsubr + if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); + v = (int) s[--sp]; + if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); + subr_stack[subr_stack_height++] = b; + b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); + if (b.size == 0) return STBTT__CSERR("subr not found"); + b.cursor = 0; + clear_stack = 0; + break; + + case 0x0B: // return + if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); + b = subr_stack[--subr_stack_height]; + clear_stack = 0; + break; + + case 0x0E: // endchar + stbtt__csctx_close_shape(c); + return 1; + + case 0x0C: { // two-byte escape + float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; + float dx, dy; + int b1 = stbtt__buf_get8(&b); + switch (b1) { + // @TODO These "flex" implementations ignore the flex-depth and resolution, + // and always draw beziers. + case 0x22: // hflex + if (sp < 7) return STBTT__CSERR("hflex stack"); + dx1 = s[0]; + dx2 = s[1]; + dy2 = s[2]; + dx3 = s[3]; + dx4 = s[4]; + dx5 = s[5]; + dx6 = s[6]; + stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); + break; + + case 0x23: // flex + if (sp < 13) return STBTT__CSERR("flex stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = s[10]; + dy6 = s[11]; + //fd is s[12] + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + case 0x24: // hflex1 + if (sp < 9) return STBTT__CSERR("hflex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dx4 = s[5]; + dx5 = s[6]; + dy5 = s[7]; + dx6 = s[8]; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); + break; + + case 0x25: // flex1 + if (sp < 11) return STBTT__CSERR("flex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = dy6 = s[10]; + dx = dx1+dx2+dx3+dx4+dx5; + dy = dy1+dy2+dy3+dy4+dy5; + if (STBTT_fabs(dx) > STBTT_fabs(dy)) + dy6 = -dy; + else + dx6 = -dx; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + default: + return STBTT__CSERR("unimplemented"); + } + } break; + + default: + if (b0 != 255 && b0 != 28 && (b0 < 32 || b0 > 254)) + return STBTT__CSERR("reserved operator"); + + // push immediate + if (b0 == 255) { + f = (float)stbtt__buf_get32(&b) / 0x10000; + } else { + stbtt__buf_skip(&b, -1); + f = (float)(stbtt_int16)stbtt__cff_int(&b); + } + if (sp >= 48) return STBTT__CSERR("push stack overflow"); + s[sp++] = f; + clear_stack = 0; + break; + } + if (clear_stack) sp = 0; + } + return STBTT__CSERR("no endchar"); + +#undef STBTT__CSERR +} + +static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + // runs the charstring twice, once to count and once to output (to avoid realloc) + stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); + stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); + if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { + *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); + output_ctx.pvertices = *pvertices; + if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { + STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); + return output_ctx.num_vertices; + } + } + *pvertices = NULL; + return 0; +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + stbtt__csctx c = STBTT__CSCTX_INIT(1); + int r = stbtt__run_charstring(info, glyph_index, &c); + if (x0) { + *x0 = r ? c.min_x : 0; + *y0 = r ? c.min_y : 0; + *x1 = r ? c.max_x : 0; + *y1 = r ? c.max_y : 0; + } + return r ? c.num_vertices : 0; +} + +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + if (!info->cff.size) + return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); + else + return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); +} + STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) { stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); @@ -1544,7 +2232,7 @@ STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) { - int x0,y0,x1,y1; + int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { // e.g. space character if (ix0) *ix0 = 0; @@ -1660,6 +2348,7 @@ static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, i { stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); if (!z) return z; // round dx down to avoid overshooting @@ -1681,10 +2370,11 @@ static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, i { stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); //STBTT_assert(e->y0 <= start_point); if (!z) return z; z->fdx = dxdy; - z->fdy = (1/dxdy); + z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; z->fx = e->x0 + dxdy * (start_point - e->y0); z->fx -= off_x; z->direction = e->invert ? 1.0f : -1.0f; @@ -1745,7 +2435,7 @@ static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__ac static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) { - stbtt__hheap hh = { 0 }; + stbtt__hheap hh = { 0, 0, 0 }; stbtt__active_edge *active = NULL; int y,j=0; int max_weight = (255 / vsubsample); // weight per vertical scanline @@ -1805,21 +2495,23 @@ static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, while (e->y0 <= scan_y) { if (e->y1 > scan_y) { stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); - // find insertion point - if (active == NULL) - active = z; - else if (z->x < active->x) { - // insert at front - z->next = active; - active = z; - } else { - // find thing to insert AFTER - stbtt__active_edge *p = active; - while (p->next && p->next->x < z->x) - p = p->next; - // at this point, p->next->x is NOT < z->x - z->next = p->next; - p->next = z; + if (z != NULL) { + // find insertion point + if (active == NULL) + active = z; + else if (z->x < active->x) { + // insert at front + z->next = active; + active = z; + } else { + // find thing to insert AFTER + stbtt__active_edge *p = active; + while (p->next && p->next->x < z->x) + p = p->next; + // at this point, p->next->x is NOT < z->x + z->next = p->next; + p->next = z; + } } } ++e; @@ -1907,7 +2599,7 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, float dx = e->fdx; float xb = x0 + dx; float x_top, x_bottom; - float y0,y1; + float sy0,sy1; float dy = e->fdy; STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); @@ -1916,17 +2608,17 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, // line with y_top, but that may be off the line segment. if (e->sy > y_top) { x_top = x0 + dx * (e->sy - y_top); - y0 = e->sy; + sy0 = e->sy; } else { x_top = x0; - y0 = y_top; + sy0 = y_top; } if (e->ey < y_bottom) { x_bottom = x0 + dx * (e->ey - y_top); - y1 = e->ey; + sy1 = e->ey; } else { x_bottom = xb; - y1 = y_bottom; + sy1 = y_bottom; } if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { @@ -1936,7 +2628,7 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, float height; // simple case, only spans one pixel int x = (int) x_top; - height = y1 - y0; + height = sy1 - sy0; STBTT_assert(x >= 0 && x < len); scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2) * height; scanline_fill[x] += e->direction * height; // everything right of this pixel is filled @@ -1947,9 +2639,9 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, if (x_top > x_bottom) { // flip scanline vertically; signed area is the same float t; - y0 = y_bottom - (y0 - y_top); - y1 = y_bottom - (y1 - y_top); - t = y0, y0 = y1, y1 = t; + sy0 = y_bottom - (sy0 - y_top); + sy1 = y_bottom - (sy1 - y_top); + t = sy0, sy0 = sy1, sy1 = t; t = x_bottom, x_bottom = x_top, x_top = t; dx = -dx; dy = -dy; @@ -1963,7 +2655,7 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, sign = e->direction; // area of the rectangle covered from y0..y_crossing - area = sign * (y_crossing-y0); + area = sign * (y_crossing-sy0); // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing) scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2); @@ -1974,11 +2666,11 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, } y_crossing += dy * (x2 - (x1+1)); - STBTT_assert(fabs(area) <= 1.01f); + STBTT_assert(STBTT_fabs(area) <= 1.01f); - scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (y1-y_crossing); + scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing); - scanline_fill[x2] += sign * (y1-y0); + scanline_fill[x2] += sign * (sy1-sy0); } } else { // if edge goes outside of box we're drawing, we require @@ -2047,12 +2739,13 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, // directly AA rasterize edges w/o supersampling static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) { - (void)vsubsample; - stbtt__hheap hh = { 0 }; + stbtt__hheap hh = { 0, 0, 0 }; stbtt__active_edge *active = NULL; int y,j=0, i; float scanline_data[129], *scanline, *scanline2; + STBTT__NOTUSED(vsubsample); + if (result->w > 64) scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); else @@ -2088,11 +2781,15 @@ static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, // insert all edges that start before the bottom of this scanline while (e->y0 <= scan_y_bottom) { - stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); - STBTT_assert(z->ey >= scan_y_top); - // insert at front - z->next = active; - active = z; + if (e->y0 != e->y1) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); + if (z != NULL) { + STBTT_assert(z->ey >= scan_y_top); + // insert at front + z->next = active; + active = z; + } + } ++e; } @@ -2107,7 +2804,7 @@ static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int m; sum += scanline2[i]; k = scanline[i] + sum; - k = (float) fabs(k)*255 + 0.5f; + k = (float) STBTT_fabs(k)*255 + 0.5f; m = (int) k; if (m > 255) m = 255; result->pixels[j*result->stride + i] = (unsigned char) m; @@ -2312,6 +3009,48 @@ static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x return 1; } +static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) +{ + // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough + float dx0 = x1-x0; + float dy0 = y1-y0; + float dx1 = x2-x1; + float dy1 = y2-y1; + float dx2 = x3-x2; + float dy2 = y3-y2; + float dx = x3-x0; + float dy = y3-y0; + float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); + float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); + float flatness_squared = longlen*longlen-shortlen*shortlen; + + if (n > 16) // 65536 segments on one curve better be enough! + return; + + if (flatness_squared > objspace_flatness_squared) { + float x01 = (x0+x1)/2; + float y01 = (y0+y1)/2; + float x12 = (x1+x2)/2; + float y12 = (y1+y2)/2; + float x23 = (x2+x3)/2; + float y23 = (y2+y3)/2; + + float xa = (x01+x12)/2; + float ya = (y01+y12)/2; + float xb = (x12+x23)/2; + float yb = (y12+y23)/2; + + float mx = (xa+xb)/2; + float my = (ya+yb)/2; + + stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x3,y3); + *num_points = *num_points+1; + } +} + // returns number of contours static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) { @@ -2368,6 +3107,14 @@ static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, objspace_flatness_squared, 0); x = vertices[i].x, y = vertices[i].y; break; + case STBTT_vcubic: + stbtt__tesselate_cubic(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].cx1, vertices[i].cy1, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; } } (*contour_lengths)[n] = num_points - start; @@ -2408,7 +3155,10 @@ STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info if (scale_x == 0) scale_x = scale_y; if (scale_y == 0) { - if (scale_x == 0) return NULL; + if (scale_x == 0) { + STBTT_free(vertices, info->userdata); + return NULL; + } scale_y = scale_x; } @@ -2491,7 +3241,7 @@ STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned ch // // This is SUPER-CRAPPY packing to keep source code small -STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) +static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) float pixel_height, // height of font in pixels unsigned char *pixels, int pw, int ph, // bitmap to be filled in int first_char, int num_chars, // characters to bake @@ -2500,6 +3250,7 @@ STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // fo float scale; int x,y,bottom_y, i; stbtt_fontinfo f; + f.userdata = NULL; if (!stbtt_InitFont(&f, data, offset)) return -1; STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels @@ -2563,11 +3314,6 @@ STBTT_DEF void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int // #ifndef STB_RECT_PACK_VERSION -#ifdef _MSC_VER -#define STBTT__NOTUSED(v) (void)(v) -#else -#define STBTT__NOTUSED(v) (void)sizeof(v) -#endif typedef int stbrp_coord; @@ -2693,6 +3439,7 @@ static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_i unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_w = w - kernel_width; int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < h; ++j) { int i; unsigned int total; @@ -2754,6 +3501,7 @@ static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_i unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_h = h - kernel_width; int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < w; ++j) { int i; unsigned int total; @@ -2823,7 +3571,7 @@ static float stbtt__oversample_shift(int oversample) } // rects array must be big enough to accommodate all characters in the given ranges -STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { int i,j,k; @@ -2835,7 +3583,7 @@ STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fon ranges[i].v_oversample = (unsigned char) spc->v_oversample; for (j=0; j < ranges[i].num_chars; ++j) { int x0,y0,x1,y1; - int codepoint = ranges[i].first_unicode_codepoint_in_range ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; int glyph = stbtt_FindGlyphIndex(info, codepoint); stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, scale * spc->h_oversample, @@ -2852,7 +3600,7 @@ STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fon } // rects array must be big enough to accommodate all characters in the given ranges -STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { int i,j,k, return_value = 1; @@ -2876,7 +3624,7 @@ STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt if (r->was_packed) { stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; int advance, lsb, x0,y0,x1,y1; - int codepoint = ranges[i].first_unicode_codepoint_in_range ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; int glyph = stbtt_FindGlyphIndex(info, codepoint); stbrp_coord pad = (stbrp_coord) spc->padding; @@ -2962,6 +3710,7 @@ STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontd if (rects == NULL) return 0; + info.userdata = spc->user_allocator_context; stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); @@ -3020,7 +3769,7 @@ STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, i // // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string -static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(const stbtt_uint8 *s1, stbtt_int32 len1, const stbtt_uint8 *s2, stbtt_int32 len2) +static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) { stbtt_int32 i=0; @@ -3059,9 +3808,9 @@ static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(const stbtt_uint8 return i; } -STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) +static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) { - return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((const stbtt_uint8*) s1, len1, (const stbtt_uint8*) s2, len2); + return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); } // returns results in whatever encoding you request... but note that 2-byte encodings @@ -3117,7 +3866,7 @@ static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, return 1; } else if (matchlen < nlen && name[matchlen] == ' ') { ++matchlen; - if (stbtt_CompareUTF8toUTF16_bigendian((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) + if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) return 1; } } else { @@ -3163,7 +3912,7 @@ static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *nam return 0; } -STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *font_collection, const char *name_utf8, stbtt_int32 flags) +static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) { stbtt_int32 i; for (i=0;;++i) { @@ -3174,11 +3923,59 @@ STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *font_collection, const } } +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, + float pixel_height, unsigned char *pixels, int pw, int ph, + int first_char, int num_chars, stbtt_bakedchar *chardata) +{ + return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); +} + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) +{ + return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); +} + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) +{ + return stbtt_GetNumberOfFonts_internal((unsigned char *) data); +} + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) +{ + return stbtt_InitFont_internal(info, (unsigned char *) data, offset); +} + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) +{ + return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); +} + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) +{ + return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + #endif // STB_TRUETYPE_IMPLEMENTATION // FULL VERSION HISTORY // +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) allow user-defined fabs() replacement +// fix memory leak if fontsize=0.0 +// fix warning from duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; // allow PackFontRanges to pack and render in separate phases; // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); diff --git a/SampleFramework12/v1.00/ImGuiHelper.cpp b/SampleFramework12/v1.01/ImGuiHelper.cpp similarity index 79% rename from SampleFramework12/v1.00/ImGuiHelper.cpp rename to SampleFramework12/v1.01/ImGuiHelper.cpp index 46e5d9d..3d7432e 100644 --- a/SampleFramework12/v1.00/ImGuiHelper.cpp +++ b/SampleFramework12/v1.01/ImGuiHelper.cpp @@ -14,6 +14,7 @@ #include "Graphics/GraphicsTypes.h" #include "Graphics/ShaderCompilation.h" #include "Graphics/Textures.h" +#include "ImGui/imgui.h" namespace SampleFramework12 { @@ -21,6 +22,15 @@ namespace SampleFramework12 namespace ImGuiHelper { +enum RootParams : uint32 +{ + RootParam_StandardDescriptors, + RootParam_CBuffer, + RootParam_SRVIndices, + + NumRootParams +}; + struct ImGuiConstants { Float4x4 ProjectionMatrix; @@ -30,7 +40,6 @@ static CompiledShaderPtr VS; static CompiledShaderPtr PS; static ID3D12PipelineState* PSO = nullptr; static ID3D12RootSignature* RootSignature = nullptr; -static ConstantBuffer CBuffer; static Texture FontTexture; #if UseAsserts_ @@ -112,10 +121,8 @@ void Initialize(Window& window) io.ImeWindowHandle = window.GetHwnd(); const std::wstring shaderPath = SampleFrameworkDir() + L"Shaders\\ImGui.hlsl"; - VS = CompileFromFile(shaderPath.c_str(), "ImGuiVS", ShaderType::Vertex, ShaderProfile::SM51); - PS = CompileFromFile(shaderPath.c_str(), "ImGuiPS", ShaderType::Pixel, ShaderProfile::SM51); - - CBuffer.Initialize(BufferLifetime::Temporary); + VS = CompileFromFile(shaderPath.c_str(), "ImGuiVS", ShaderType::Vertex); + PS = CompileFromFile(shaderPath.c_str(), "ImGuiPS", ShaderType::Pixel); unsigned char* pixels = nullptr; int32 texWidth = 0; @@ -126,23 +133,22 @@ void Initialize(Window& window) io.Fonts->TexID = &FontTexture; { - D3D12_DESCRIPTOR_RANGE1 ranges[1] = {}; - ranges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - ranges[0].NumDescriptors = 1; - ranges[0].BaseShaderRegister = 0; - ranges[0].RegisterSpace = 0; - ranges[0].OffsetInDescriptorsFromTableStart = 0; - - D3D12_ROOT_PARAMETER1 rootParameters[2] = {}; - rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - rootParameters[0].DescriptorTable.pDescriptorRanges = ranges; - rootParameters[0].DescriptorTable.NumDescriptorRanges = 1; - - rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; - rootParameters[1].Descriptor.RegisterSpace = 0; - rootParameters[1].Descriptor.ShaderRegister = 0; + D3D12_ROOT_PARAMETER1 rootParameters[NumRootParams] = { }; + rootParameters[RootParam_StandardDescriptors].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParameters[RootParam_StandardDescriptors].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + rootParameters[RootParam_StandardDescriptors].DescriptorTable.pDescriptorRanges = DX12::StandardDescriptorRanges(); + rootParameters[RootParam_StandardDescriptors].DescriptorTable.NumDescriptorRanges = DX12::NumStandardDescriptorRanges; + + rootParameters[RootParam_CBuffer].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParameters[RootParam_CBuffer].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; + rootParameters[RootParam_CBuffer].Descriptor.RegisterSpace = 0; + rootParameters[RootParam_CBuffer].Descriptor.ShaderRegister = 0; + + rootParameters[RootParam_SRVIndices].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + rootParameters[RootParam_SRVIndices].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + rootParameters[RootParam_SRVIndices].Constants.Num32BitValues = 1; + rootParameters[RootParam_SRVIndices].Constants.RegisterSpace = 0; + rootParameters[RootParam_SRVIndices].Constants.ShaderRegister = 1; D3D12_STATIC_SAMPLER_DESC staticSamplers[1] = {}; staticSamplers[0] = DX12::GetStaticSamplerState(SamplerState::LinearClamp); @@ -162,7 +168,6 @@ void Shutdown() { ImGui::Shutdown(); - CBuffer.Shutdown(); FontTexture.Shutdown(); DX12::Release(RootSignature); @@ -250,18 +255,18 @@ void EndFrame(ID3D12GraphicsCommandList* cmdList, D3D12_CPU_DESCRIPTOR_HANDLE rt } // Setup orthographic projection matrix into our constant buffer + ImGuiConstants constants; + { const float L = 0.0f; const float R = float(displayWidth); const float B = float(displayHeight); const float T = 0.0f; - CBuffer.Data.ProjectionMatrix = Float4x4(Float4(2.0f/(R-L), 0.0f, 0.0f, 0.0f), - Float4(0.0f, 2.0f/(T-B), 0.0f, 0.0f), - Float4(0.0f, 0.0f, 0.5f, 0.0f), - Float4((R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f)); - - CBuffer.Upload(); + constants.ProjectionMatrix = Float4x4(Float4(2.0f/(R-L), 0.0f, 0.0f, 0.0f), + Float4(0.0f, 2.0f/(T-B), 0.0f, 0.0f), + Float4(0.0f, 0.0f, 0.5f, 0.0f), + Float4((R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f)); } // Setup viewport @@ -273,7 +278,9 @@ void EndFrame(ID3D12GraphicsCommandList* cmdList, D3D12_CPU_DESCRIPTOR_HANDLE rt cmdList->SetPipelineState(PSO); cmdList->SetGraphicsRootSignature(RootSignature); cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - CBuffer.SetAsGfxRootParameter(cmdList, 1); + + DX12::BindStandardDescriptorTable(cmdList, RootParam_StandardDescriptors, CmdListMode::Graphics); + DX12::BindTempConstantBuffer(cmdList, constants, RootParam_CBuffer, CmdListMode::Graphics); D3D12_VERTEX_BUFFER_VIEW vbView = { }; vbView.BufferLocation = vertexMem.GPUAddress; @@ -302,14 +309,17 @@ void EndFrame(ID3D12GraphicsCommandList* cmdList, D3D12_CPU_DESCRIPTOR_HANDLE rt } else { - Texture* texture = reinterpret_cast(drawCmd->TextureId); - D3D12_CPU_DESCRIPTOR_HANDLE psResources[1] = { texture->SRV.CPUHandle }; - DX12::BindShaderResources(cmdList, 0, ArraySize_(psResources), psResources, CmdListMode::Graphics, ShaderResourceType::SRV_UAV_CBV); - const D3D12_RECT r = { int32(drawCmd->ClipRect.x), int32(drawCmd->ClipRect.y), int32(drawCmd->ClipRect.z), int32(drawCmd->ClipRect.w) }; - cmdList->RSSetScissorRects(1, &r); - cmdList->DrawIndexedInstanced(drawCmd->ElemCount, 1, idxOffset, vtxOffset, 0); + if(r.left < r.right && r.top < r.bottom) + { + Texture* texture = reinterpret_cast(drawCmd->TextureId); + cmdList->SetGraphicsRoot32BitConstant(RootParam_SRVIndices, texture->SRV, 0); + + cmdList->RSSetScissorRects(1, &r); + + cmdList->DrawIndexedInstanced(drawCmd->ElemCount, 1, idxOffset, vtxOffset, 0); + } } idxOffset += drawCmd->ElemCount; } diff --git a/SampleFramework12/v1.00/ImGuiHelper.h b/SampleFramework12/v1.01/ImGuiHelper.h similarity index 97% rename from SampleFramework12/v1.00/ImGuiHelper.h rename to SampleFramework12/v1.01/ImGuiHelper.h index 907a0b2..84d6084 100644 --- a/SampleFramework12/v1.00/ImGuiHelper.h +++ b/SampleFramework12/v1.01/ImGuiHelper.h @@ -11,6 +11,7 @@ #include "PCH.h" #include "SF12_Math.h" +#include "ImGui/imgui.h" namespace SampleFramework12 { diff --git a/SampleFramework12/v1.00/Input.cpp b/SampleFramework12/v1.01/Input.cpp similarity index 100% rename from SampleFramework12/v1.00/Input.cpp rename to SampleFramework12/v1.01/Input.cpp diff --git a/SampleFramework12/v1.00/Input.h b/SampleFramework12/v1.01/Input.h similarity index 100% rename from SampleFramework12/v1.00/Input.h rename to SampleFramework12/v1.01/Input.h diff --git a/SampleFramework12/v1.00/InterfacePointers.h b/SampleFramework12/v1.01/InterfacePointers.h similarity index 98% rename from SampleFramework12/v1.00/InterfacePointers.h rename to SampleFramework12/v1.01/InterfacePointers.h index aa53005..1fc0a45 100644 --- a/SampleFramework12/v1.00/InterfacePointers.h +++ b/SampleFramework12/v1.01/InterfacePointers.h @@ -62,6 +62,7 @@ typedef Microsoft::WRL::ComPtr ID3D12ShaderReflectio typedef Microsoft::WRL::ComPtr ID3D12ShaderReflectionVariablePtr; typedef Microsoft::WRL::ComPtr ID3D12DebugPtr; +typedef Microsoft::WRL::ComPtr ID3D12Debug1Ptr; typedef Microsoft::WRL::ComPtr ID3D12DebugDevicePtr; typedef Microsoft::WRL::ComPtr ID3D12DebugCommandListPtr; typedef Microsoft::WRL::ComPtr ID3D12DebugCommandQueuePtr; diff --git a/SampleFramework12/v1.01/Manifest.txt b/SampleFramework12/v1.01/Manifest.txt new file mode 100644 index 0000000..233327f --- /dev/null +++ b/SampleFramework12/v1.01/Manifest.txt @@ -0,0 +1,30 @@ +[Code] +Graphics\ +EnkiTS\ +SettingsCompiler\ +|SettingsCompiler\bin\ +|SettingsCompiler\obj\ +SettingsCompilerAttributes\ +|SettingsCompilerAttributes\bin\ +|SettingsCompilerAttributes\obj\ + +[Local] +Shaders\ +SettingsCompiler.exe +SettingsCompilerAttributes.dll + +[Content] + +Textures\Default.dds +Textures\DefaultNormalMap.dds +Textures\DefaultRoughness.dds +Textures\DefaultBlack.dds + +[Externals] + +imgui-1.46\ +Assimp-3.1.1\ +DirectXTex Aug 2015\ +HosekSky\ +WinPixEventRuntime\ +cxxopts\ \ No newline at end of file diff --git a/SampleFramework12/v1.00/MurmurHash.cpp b/SampleFramework12/v1.01/MurmurHash.cpp similarity index 100% rename from SampleFramework12/v1.00/MurmurHash.cpp rename to SampleFramework12/v1.01/MurmurHash.cpp diff --git a/SampleFramework12/v1.00/MurmurHash.h b/SampleFramework12/v1.01/MurmurHash.h similarity index 91% rename from SampleFramework12/v1.00/MurmurHash.h rename to SampleFramework12/v1.01/MurmurHash.h index 3829a87..29da483 100644 --- a/SampleFramework12/v1.00/MurmurHash.h +++ b/SampleFramework12/v1.01/MurmurHash.h @@ -30,7 +30,7 @@ struct Hash } }; -Hash GenerateHash(const void* key, int len, uint32 seed = 0); +Hash GenerateHash(const void* key, int32 len, uint32 seed = 0); Hash CombineHashes(Hash a, Hash b); } \ No newline at end of file diff --git a/SampleFramework12/v1.00/PCH.cpp b/SampleFramework12/v1.01/PCH.cpp similarity index 100% rename from SampleFramework12/v1.00/PCH.cpp rename to SampleFramework12/v1.01/PCH.cpp diff --git a/SampleFramework12/v1.00/PCH.h b/SampleFramework12/v1.01/PCH.h similarity index 84% rename from SampleFramework12/v1.00/PCH.h rename to SampleFramework12/v1.01/PCH.h index a383bf1..cc129e0 100644 --- a/SampleFramework12/v1.00/PCH.h +++ b/SampleFramework12/v1.01/PCH.h @@ -89,8 +89,8 @@ typedef uint32_t bool32; #include #include -#include #include +#include // DirectX Math #include @@ -98,11 +98,11 @@ typedef uint32_t bool32; #include // DirectX Tex -#include "..\\..\\Externals\\DirectXTex Aug 2015\\Include\\DirectXTex.h" +#include "..\\..\\Externals\\DirectXTex July 2017\\Include\\DirectXTex.h" #ifdef _DEBUG - #pragma comment(lib, "..\\Externals\\DirectXTex Aug 2015\\Lib 2015\\Debug\\DirectXTex.lib") + #pragma comment(lib, "..\\Externals\\DirectXTex July 2017\\Lib 2017\\Debug\\DirectXTex.lib") #else - #pragma comment(lib, "..\\Externals\\DirectXTex Aug 2015\\Lib 2015\\Release\\DirectXTex.lib") + #pragma comment(lib, "..\\Externals\\DirectXTex July 2017\\Lib 2017\\Release\\DirectXTex.lib") #endif // Pix for Windows @@ -158,24 +158,6 @@ typedef uint32_t bool32; #include "..\\..\\Externals\\Assimp-3.1.1\\include\\postprocess.h" #pragma comment(lib, "..\\Externals\\Assimp-3.1.1\\lib\\assimp.lib") -#if EnableSkyModel_ - // HosekSky lib - #include "..\\..\\Externals\\HosekSky\\Include\\ArHosekSkyModel.h" - #ifdef _DEBUG - #pragma comment(lib, "..\\Externals\\HosekSky\\Lib 2015\\HosekSky_Dbg.lib") - #else - #pragma comment(lib, "..\\Externals\\HosekSky\\Lib 2015\\HosekSky.lib") - #endif -#endif - -// Imgui -#include "..\\..\\Externals\\imgui-1.46\\Include\imgui.h" -#ifdef _DEBUG - #pragma comment(lib, "..\\Externals\\imgui-1.46\\Lib\\Debug\\imgui.lib") -#else - #pragma comment(lib, "..\\Externals\\imgui-1.46\\Lib\\Release\\imgui.lib") -#endif - // Embree #if EnableEmbree_ #include "..\\..\\Externals\\Embree-2.8\\include\\embree2\\rtcore.h" @@ -183,15 +165,24 @@ typedef uint32_t bool32; #pragma comment(lib, "..\\Externals\\Embree-2.8\\lib\\embree.lib") #endif +// cxxopts +#include "..\\..\\Externals\\cxxopts\\include\\\cxxopts.hpp" + // Windows SDK imports #pragma comment(lib, "dxguid.lib") #pragma comment(lib, "DXGI.lib") #pragma comment(lib, "comctl32.lib") #pragma comment(lib, "psapi.lib") -#pragma comment(lib, "d3dcompiler.lib") #pragma comment(lib, "gdiplus.lib") #pragma comment(lib, "D3D12.lib") +#if EnableShaderModel6_ + #include "..\\..\\Externals\\DXCompiler\\Include\\dxcapi.h" + #pragma comment(lib, "..\\Externals\\DXCompiler\\Lib\\dxcompiler.lib") +#else + #pragma comment(lib, "d3dcompiler.lib") +#endif + #ifdef _DEBUG #pragma comment(lib, "comsuppwd.lib") #else diff --git a/SampleFramework12/v1.00/SF12.props b/SampleFramework12/v1.01/SF12.props similarity index 91% rename from SampleFramework12/v1.00/SF12.props rename to SampleFramework12/v1.01/SF12.props index 1c9972e..80a1bbd 100644 --- a/SampleFramework12/v1.00/SF12.props +++ b/SampleFramework12/v1.01/SF12.props @@ -2,14 +2,14 @@ - ..\SampleFramework12\v1.00\ + ..\SampleFramework12\v1.01\ $(ProjectDir);$(SampleFrameworkDir);$(IncludePath) - %(PreprocessorDefinitions);SampleFrameworkDir_=L"..\\SampleFramework12\\v1.00\\" + %(PreprocessorDefinitions);SampleFrameworkDir_=L"..\\SampleFramework12\\v1.01\\" Create PCH.h true diff --git a/SampleFramework12/v1.00/SF12_Math.cpp b/SampleFramework12/v1.01/SF12_Math.cpp similarity index 100% rename from SampleFramework12/v1.00/SF12_Math.cpp rename to SampleFramework12/v1.01/SF12_Math.cpp diff --git a/SampleFramework12/v1.00/SF12_Math.h b/SampleFramework12/v1.01/SF12_Math.h similarity index 100% rename from SampleFramework12/v1.00/SF12_Math.h rename to SampleFramework12/v1.01/SF12_Math.h diff --git a/SampleFramework12/v1.01/Scripts/CopyDXC.bat b/SampleFramework12/v1.01/Scripts/CopyDXC.bat new file mode 100644 index 0000000..18d5db7 --- /dev/null +++ b/SampleFramework12/v1.01/Scripts/CopyDXC.bat @@ -0,0 +1,13 @@ +@echo off + +setlocal + +set BUILD_TYPE=Release + +if "%1"=="-Debug" ( + set BUILD_TYPE=Debug +) + +xcopy %HLSL_SRC_DIR%\Include\dxc\dxcapi.h %~dp0..\..\..\Externals\DXCompiler\Include\ /y +xcopy %HLSL_BLD_DIR%\%BUILD_TYPE%\lib\dxcompiler.lib %~dp0..\..\..\Externals\DXCompiler\Lib\ /y +xcopy %HLSL_BLD_DIR%\%BUILD_TYPE%\bin\dxcompiler.* %~dp0..\..\..\Externals\DXCompiler\Bin\ /y diff --git a/SampleFramework12/v1.01/Scripts/CopyDXCToOutputDir.bat b/SampleFramework12/v1.01/Scripts/CopyDXCToOutputDir.bat new file mode 100644 index 0000000..ffe8d0a --- /dev/null +++ b/SampleFramework12/v1.01/Scripts/CopyDXCToOutputDir.bat @@ -0,0 +1,9 @@ +@echo off + +IF EXIST %1\..\Externals\DXCompiler\Bin\dxcompiler.dll ( + copy %1\..\Externals\DXCompiler\Bin\dxcompiler.dll %2\dxcompiler.dll +) ELSE ( + copy %3\dxcompiler.dll %2\dxcompiler.dll +) + +copy %3\dxil.dll %2\dxil.dll \ No newline at end of file diff --git a/SampleFramework12/v1.01/Scripts/SoftCopy.bat b/SampleFramework12/v1.01/Scripts/SoftCopy.bat new file mode 100644 index 0000000..5d5ee43 --- /dev/null +++ b/SampleFramework12/v1.01/Scripts/SoftCopy.bat @@ -0,0 +1 @@ +IF EXIST %1 (copy %1 %2) \ No newline at end of file diff --git a/SampleFramework12/v1.00/Serialization.h b/SampleFramework12/v1.01/Serialization.h similarity index 100% rename from SampleFramework12/v1.00/Serialization.h rename to SampleFramework12/v1.01/Serialization.h diff --git a/SampleFramework12/v1.00/Settings.cpp b/SampleFramework12/v1.01/Settings.cpp similarity index 99% rename from SampleFramework12/v1.00/Settings.cpp rename to SampleFramework12/v1.01/Settings.cpp index 5192111..c1fef22 100644 --- a/SampleFramework12/v1.00/Settings.cpp +++ b/SampleFramework12/v1.01/Settings.cpp @@ -13,6 +13,7 @@ #include "Utility.h" #include "App.h" #include "ImGuiHelper.h" +#include "ImGui/imgui.h" namespace SampleFramework12 { diff --git a/SampleFramework12/v1.00/Settings.h b/SampleFramework12/v1.01/Settings.h similarity index 99% rename from SampleFramework12/v1.00/Settings.h rename to SampleFramework12/v1.01/Settings.h index 8be9953..cb5ac58 100644 --- a/SampleFramework12/v1.00/Settings.h +++ b/SampleFramework12/v1.01/Settings.h @@ -476,6 +476,8 @@ class SettingsContainer // Add new settings void AddSetting(Setting* setting); + + void SetWindowOpened(bool windowOpened) { opened = windowOpened; } }; } \ No newline at end of file diff --git a/SampleFramework12/v1.00/SettingsCompiler.exe b/SampleFramework12/v1.01/SettingsCompiler.exe similarity index 62% rename from SampleFramework12/v1.00/SettingsCompiler.exe rename to SampleFramework12/v1.01/SettingsCompiler.exe index f9dbe04..5a6a8f6 100644 Binary files a/SampleFramework12/v1.00/SettingsCompiler.exe and b/SampleFramework12/v1.01/SettingsCompiler.exe differ diff --git a/SampleFramework12/v1.00/SettingsCompiler.sln b/SampleFramework12/v1.01/SettingsCompiler.sln similarity index 100% rename from SampleFramework12/v1.00/SettingsCompiler.sln rename to SampleFramework12/v1.01/SettingsCompiler.sln diff --git a/SampleFramework12/v1.00/SettingsCompiler/App.config b/SampleFramework12/v1.01/SettingsCompiler/App.config similarity index 100% rename from SampleFramework12/v1.00/SettingsCompiler/App.config rename to SampleFramework12/v1.01/SettingsCompiler/App.config diff --git a/SampleFramework12/v1.00/SettingsCompiler/Properties/AssemblyInfo.cs b/SampleFramework12/v1.01/SettingsCompiler/Properties/AssemblyInfo.cs similarity index 100% rename from SampleFramework12/v1.00/SettingsCompiler/Properties/AssemblyInfo.cs rename to SampleFramework12/v1.01/SettingsCompiler/Properties/AssemblyInfo.cs diff --git a/SampleFramework12/v1.00/SettingsCompiler/SettingTypes.cs b/SampleFramework12/v1.01/SettingsCompiler/SettingTypes.cs similarity index 99% rename from SampleFramework12/v1.00/SettingsCompiler/SettingTypes.cs rename to SampleFramework12/v1.01/SettingsCompiler/SettingTypes.cs index 838d9b1..2b93b6c 100644 --- a/SampleFramework12/v1.00/SettingsCompiler/SettingTypes.cs +++ b/SampleFramework12/v1.01/SettingsCompiler/SettingTypes.cs @@ -187,7 +187,7 @@ public void WriteCBufferUpdate(List lines) if(Type == SettingType.Button) return; - lines.Add(string.Format(" CBuffer.Data." + Name + " = {0};", Name)); + lines.Add(string.Format(" cbData." + Name + " = {0};", Name)); } public static string FloatString(float num) diff --git a/SampleFramework12/v1.00/SettingsCompiler/SettingsCompiler.cs b/SampleFramework12/v1.01/SettingsCompiler/SettingsCompiler.cs similarity index 96% rename from SampleFramework12/v1.00/SettingsCompiler/SettingsCompiler.cs rename to SampleFramework12/v1.01/SettingsCompiler/SettingsCompiler.cs index 85b4e2c..ef3dfe5 100644 --- a/SampleFramework12/v1.00/SettingsCompiler/SettingsCompiler.cs +++ b/SampleFramework12/v1.01/SettingsCompiler/SettingsCompiler.cs @@ -262,12 +262,12 @@ static void GenerateHeader(List settings, string outputName, string out } else { - lines.Add(" uint Dummy;"); + lines.Add(" uint32 Dummy;"); } lines.Add(" };"); lines.Add(""); - lines.Add(string.Format(" extern ConstantBuffer<{0}CBuffer> CBuffer;", outputName)); + lines.Add(" extern ConstantBuffer CBuffer;"); lines.Add(" const extern uint32 CBufferRegister;"); lines.Add(""); @@ -306,7 +306,7 @@ static void GenerateCPP(List settings, string outputName, string output setting.WriteDefinition(lines); lines.Add(""); - lines.Add(string.Format(" ConstantBuffer<{0}CBuffer> CBuffer;", outputName)); + lines.Add(" ConstantBuffer CBuffer;"); lines.Add(string.Format(" const uint32 CBufferRegister = {0};", CBufferRegister)); lines.Add(""); @@ -329,7 +329,11 @@ static void GenerateCPP(List settings, string outputName, string output setting.WritePostInitialization(lines); } - lines.Add(" CBuffer.Initialize(BufferLifetime::Temporary);"); + lines.Add(" ConstantBufferInit cbInit;"); + lines.Add(" cbInit.Size = sizeof(AppSettingsCBuffer);"); + lines.Add(" cbInit.Dynamic = true;"); + lines.Add(" cbInit.Name = L\"AppSettings Constant Buffer\";"); + lines.Add(" CBuffer.Initialize(cbInit);"); lines.Add(" }"); @@ -348,13 +352,14 @@ static void GenerateCPP(List settings, string outputName, string output lines.Add(""); lines.Add(" void UpdateCBuffer()"); lines.Add(" {"); + lines.Add(" AppSettingsCBuffer cbData;"); foreach(Setting setting in settings) setting.WriteCBufferUpdate(lines); lines.Add(""); - lines.Add(" CBuffer.Upload();"); + lines.Add(" CBuffer.MapAndSetData(cbData);"); lines.Add(" }"); diff --git a/SampleFramework12/v1.00/SettingsCompiler/SettingsCompiler.csproj b/SampleFramework12/v1.01/SettingsCompiler/SettingsCompiler.csproj similarity index 100% rename from SampleFramework12/v1.00/SettingsCompiler/SettingsCompiler.csproj rename to SampleFramework12/v1.01/SettingsCompiler/SettingsCompiler.csproj diff --git a/SampleFramework12/v1.00/SettingsCompilerAttributes.dll b/SampleFramework12/v1.01/SettingsCompilerAttributes.dll similarity index 95% rename from SampleFramework12/v1.00/SettingsCompilerAttributes.dll rename to SampleFramework12/v1.01/SettingsCompilerAttributes.dll index 0744a39..5a5b3c2 100644 Binary files a/SampleFramework12/v1.00/SettingsCompilerAttributes.dll and b/SampleFramework12/v1.01/SettingsCompilerAttributes.dll differ diff --git a/SampleFramework12/v1.00/SettingsCompilerAttributes/Attributes.cs b/SampleFramework12/v1.01/SettingsCompilerAttributes/Attributes.cs similarity index 100% rename from SampleFramework12/v1.00/SettingsCompilerAttributes/Attributes.cs rename to SampleFramework12/v1.01/SettingsCompilerAttributes/Attributes.cs diff --git a/SampleFramework12/v1.00/SettingsCompilerAttributes/Properties/AssemblyInfo.cs b/SampleFramework12/v1.01/SettingsCompilerAttributes/Properties/AssemblyInfo.cs similarity index 100% rename from SampleFramework12/v1.00/SettingsCompilerAttributes/Properties/AssemblyInfo.cs rename to SampleFramework12/v1.01/SettingsCompilerAttributes/Properties/AssemblyInfo.cs diff --git a/SampleFramework12/v1.00/SettingsCompilerAttributes/SettingsCompilerAttributes.csproj b/SampleFramework12/v1.01/SettingsCompilerAttributes/SettingsCompilerAttributes.csproj similarity index 100% rename from SampleFramework12/v1.00/SettingsCompilerAttributes/SettingsCompilerAttributes.csproj rename to SampleFramework12/v1.01/SettingsCompilerAttributes/SettingsCompilerAttributes.csproj diff --git a/SampleFramework12/v1.00/Shaders/BRDF.hlsl b/SampleFramework12/v1.01/Shaders/BRDF.hlsl similarity index 100% rename from SampleFramework12/v1.00/Shaders/BRDF.hlsl rename to SampleFramework12/v1.01/Shaders/BRDF.hlsl diff --git a/SampleFramework12/v1.00/Shaders/Constants.hlsl b/SampleFramework12/v1.01/Shaders/Constants.hlsl similarity index 100% rename from SampleFramework12/v1.00/Shaders/Constants.hlsl rename to SampleFramework12/v1.01/Shaders/Constants.hlsl diff --git a/SampleFramework12/v1.00/Shaders/Conversion.hlsl b/SampleFramework12/v1.01/Shaders/Conversion.hlsl similarity index 100% rename from SampleFramework12/v1.00/Shaders/Conversion.hlsl rename to SampleFramework12/v1.01/Shaders/Conversion.hlsl diff --git a/SampleFramework12/v1.00/Shaders/DecodeTextureCS.hlsl b/SampleFramework12/v1.01/Shaders/DecodeTextureCS.hlsl similarity index 72% rename from SampleFramework12/v1.00/Shaders/DecodeTextureCS.hlsl rename to SampleFramework12/v1.01/Shaders/DecodeTextureCS.hlsl index 0fb19e5..6e04d00 100644 --- a/SampleFramework12/v1.00/Shaders/DecodeTextureCS.hlsl +++ b/SampleFramework12/v1.01/Shaders/DecodeTextureCS.hlsl @@ -1,19 +1,26 @@ //================================================================================================= // -// MJP's DX11 Sample Framework +// MJP's DX12 Sample Framework // http://mynameismjp.wordpress.com/ // // All code licensed under the MIT license // //================================================================================================= +#include + //================================================================================================= // Resources //================================================================================================= // Inputs -Texture2D InputTexture : register(t0); -Texture2DArray InputTextureArray : register(t0); +struct SRVIndicesLayout +{ + uint InputTexture; +}; + +ConstantBuffer SRVIndices : register(b0); + // Outputs RWBuffer OutputBuffer : register(u0); @@ -24,20 +31,24 @@ RWBuffer OutputBuffer : register(u0); [numthreads(TGSize_, TGSize_, 1)] void DecodeTextureCS(in uint3 GroupID : SV_GroupID, in uint3 GroupThreadID : SV_GroupThreadID) { + Texture2D inputTexture = Tex2DTable[SRVIndices.InputTexture]; + uint2 textureSize = 0; - InputTexture.GetDimensions(textureSize.x, textureSize.y); + inputTexture.GetDimensions(textureSize.x, textureSize.y); const uint2 texelIdx = GroupID.xy * uint2(TGSize_, TGSize_) + GroupThreadID.xy; const uint bufferIdx = texelIdx.y * textureSize.x + texelIdx.x; - OutputBuffer[bufferIdx] = InputTexture[texelIdx]; + OutputBuffer[bufferIdx] = inputTexture[texelIdx]; } [numthreads(TGSize_, TGSize_, 1)] void DecodeTextureArrayCS(in uint3 GroupID : SV_GroupID, in uint3 GroupThreadID : SV_GroupThreadID) { + Texture2DArray inputTexture = Tex2DArrayTable[SRVIndices.InputTexture]; + uint2 textureSize = 0; uint numSlices = 0; - InputTextureArray.GetDimensions(textureSize.x, textureSize.y, numSlices); + inputTexture.GetDimensions(textureSize.x, textureSize.y, numSlices); const uint3 texelIdx = uint3(GroupID.xy * uint2(TGSize_, TGSize_) + GroupThreadID.xy, GroupID.z); const uint bufferIdx = texelIdx.z * (textureSize.x * textureSize.y) + (texelIdx.y * textureSize.x) + texelIdx.x; - OutputBuffer[bufferIdx] = InputTextureArray[texelIdx]; + OutputBuffer[bufferIdx] = inputTexture[texelIdx]; } \ No newline at end of file diff --git a/SampleFramework12/v1.01/Shaders/DescriptorTables.hlsl b/SampleFramework12/v1.01/Shaders/DescriptorTables.hlsl new file mode 100644 index 0000000..a2092b9 --- /dev/null +++ b/SampleFramework12/v1.01/Shaders/DescriptorTables.hlsl @@ -0,0 +1,18 @@ +//================================================================================================= +// +// MJP's DX12 Sample Framework +// http://mynameismjp.wordpress.com/ +// +// All code licensed under the MIT license +// +//================================================================================================= + +// This is the standard set of descriptor tables that shaders use for accessing the SRV's that they need. +// These must match "NumStandardDescriptorRanges" and "StandardDescriptorRanges()" from DX12_Helpers.h +Texture2D Tex2DTable[] : register(t0, space0); +Texture2DArray Tex2DArrayTable[] : register(t0, space1); +TextureCube TexCubeTable[] : register(t0, space2); +Texture3D Tex3DTable[] : register(t0, space3); +Texture2DMS Tex2DMSTable[] : register(t0, space4); +ByteAddressBuffer RawBufferTable[] : register(t0, space5); +Buffer BufferUintTable[] : register(t0, space6); \ No newline at end of file diff --git a/SampleFramework12/v1.00/Shaders/EVSM.hlsl b/SampleFramework12/v1.01/Shaders/EVSM.hlsl similarity index 77% rename from SampleFramework12/v1.00/Shaders/EVSM.hlsl rename to SampleFramework12/v1.01/Shaders/EVSM.hlsl index eeaa80a..8b1e84f 100644 --- a/SampleFramework12/v1.00/Shaders/EVSM.hlsl +++ b/SampleFramework12/v1.01/Shaders/EVSM.hlsl @@ -1,61 +1,59 @@ -//================================================================================================= -// -// MJP's DX12 Sample Framework -// http://mynameismjp.wordpress.com/ -// -// All code licensed under the MIT license -// -//================================================================================================= - -float2 GetEVSMExponents(in float positiveExponent, in float negativeExponent, - in float3 cascadeScale) -{ - - const float maxExponent = 42.0f; - - float2 lightSpaceExponents = float2(positiveExponent, negativeExponent); - - // Make sure exponents say consistent in light space regardless of partition - // scaling. This prevents the exponentials from ever getting too rediculous - // and maintains consistency across partitions. - // Clamp to maximum range of fp32/fp16 to prevent overflow/underflow - return min(lightSpaceExponents / cascadeScale.z, maxExponent); -} - -// Input depth should be in [0, 1] -float2 WarpDepth(float depth, float2 exponents) -{ - // Rescale depth into [-1, 1] - depth = 2.0f * depth - 1.0f; - float pos = exp( exponents.x * depth); - float neg = -exp(-exponents.y * depth); - return float2(pos, neg); -} - -float Linstep(float a, float b, float v) -{ - return saturate((v - a) / (b - a)); -} - -float ReduceLightBleeding(float pMax, float amount) -{ - // Remove the [0, amount] tail and linearly rescale (amount, 1]. - return Linstep(amount, 1.0f, pMax); -} - -float ChebyshevUpperBound(float2 moments, float mean, float minVariance, - float lightBleedingReduction) -{ - // Compute variance - float variance = moments.y - (moments.x * moments.x); - variance = max(variance, minVariance); - - // Compute probabilistic upper bound - float d = mean - moments.x; - float pMax = variance / (variance + (d * d)); - - pMax = ReduceLightBleeding(pMax, lightBleedingReduction); - - // One-tailed Chebyshev - return (mean <= moments.x ? 1.0f : pMax); +//================================================================================================= +// +// MJP's DX12 Sample Framework +// http://mynameismjp.wordpress.com/ +// +// All code licensed under the MIT license +// +//================================================================================================= + +float2 GetEVSMExponents(in float positiveExponent, in float negativeExponent, + in float3 cascadeScale) +{ + + const float maxExponent = 42.0f; + + float2 lightSpaceExponents = float2(positiveExponent, negativeExponent); + + // Make sure exponents say consistent in light space regardless of partition + // scaling. This prevents the exponentials from ever getting too rediculous + // and maintains consistency across partitions. + // Clamp to maximum range of fp32/fp16 to prevent overflow/underflow + return min(lightSpaceExponents / cascadeScale.z, maxExponent); +} + +// Input depth should be in [0, 1] +float2 WarpDepth(float depth, float2 exponents) +{ + // Rescale depth into [-1, 1] + depth = 2.0f * depth - 1.0f; + float pos = exp( exponents.x * depth); + float neg = -exp(-exponents.y * depth); + return float2(pos, neg); +} + +//------------------------------------------------------------------------------------------------- +// Reduces EVSM/MSM light bleeding by clipping and rescaling +//------------------------------------------------------------------------------------------------- +float ReduceLightBleeding(float shadowAmt, float clipAmt) +{ + // Remove the [0, clipAmt] tail and linearly rescale (clipAmt, 1]. + return saturate((shadowAmt - clipAmt) / (1.0f - clipAmt)); +} + +float ChebyshevUpperBound(float2 moments, float mean, float minVariance, + float lightBleedingReduction) +{ + // Compute variance + float variance = moments.y - (moments.x * moments.x); + variance = max(variance, minVariance); + + // Compute probabilistic upper bound + float d = mean - moments.x; + float pMax = variance / (variance + (d * d)); + + pMax = ReduceLightBleeding(pMax, lightBleedingReduction); + + // One-tailed Chebyshev + return (mean <= moments.x ? 1.0f : pMax); } \ No newline at end of file diff --git a/SampleFramework12/v1.00/Shaders/FullScreenTriangle.hlsl b/SampleFramework12/v1.01/Shaders/FullScreenTriangle.hlsl similarity index 100% rename from SampleFramework12/v1.00/Shaders/FullScreenTriangle.hlsl rename to SampleFramework12/v1.01/Shaders/FullScreenTriangle.hlsl diff --git a/SampleFramework12/v1.00/Shaders/ImGui.hlsl b/SampleFramework12/v1.01/Shaders/ImGui.hlsl similarity index 78% rename from SampleFramework12/v1.00/Shaders/ImGui.hlsl rename to SampleFramework12/v1.01/Shaders/ImGui.hlsl index 68af022..5380dc7 100644 --- a/SampleFramework12/v1.00/Shaders/ImGui.hlsl +++ b/SampleFramework12/v1.01/Shaders/ImGui.hlsl @@ -7,6 +7,8 @@ // //================================================================================================= +#include + struct VSInput { float2 Position : POSITION; @@ -26,9 +28,14 @@ struct ImGuiConstants row_major float4x4 ProjectionMatrix; }; -Texture2D ImGuiTexture : register(t0); +struct SRVIndicesLayout +{ + uint TextureIdx; +}; + SamplerState LinearSampler : register(s0); ConstantBuffer ImGuiCB : register(b0); +ConstantBuffer SRVIndices : register(b1); VSOutput ImGuiVS(in VSInput input) { @@ -42,5 +49,6 @@ VSOutput ImGuiVS(in VSInput input) float4 ImGuiPS(in VSOutput input) : SV_Target0 { - return ImGuiTexture.Sample(LinearSampler, input.UV) * input.Color; + Texture2D imGuiTexture = Tex2DTable[SRVIndices.TextureIdx]; + return imGuiTexture.Sample(LinearSampler, input.UV) * input.Color; } \ No newline at end of file diff --git a/SampleFramework12/v1.01/Shaders/MSM.hlsl b/SampleFramework12/v1.01/Shaders/MSM.hlsl new file mode 100644 index 0000000..5eb2991 --- /dev/null +++ b/SampleFramework12/v1.01/Shaders/MSM.hlsl @@ -0,0 +1,140 @@ +//================================================================================================= +// +// MJP's DX12 Sample Framework +// http://mynameismjp.wordpress.com/ +// +// All code licensed under the MIT license +// +//================================================================================================= + +float4 GetOptimizedMoments(in float depth) +{ + float square = depth * depth; + float4 moments = float4(depth, square, square * depth, square * square); + float4 optimized = mul(moments, float4x4(-2.07224649f, 13.7948857237f, 0.105877704f, 9.7924062118f, + 32.23703778f, -59.4683975703f, -1.9077466311f, -33.7652110555f, + -68.571074599f, 82.0359750338f, 9.3496555107f, 47.9456096605f, + 39.3703274134f,-35.364903257f, -6.6543490743f, -23.9728048165f)); + optimized[0] += 0.035955884801f; + return optimized; +} + +float4 ConvertOptimizedMoments(in float4 optimizedMoments) +{ + optimizedMoments[0] -= 0.035955884801f; + return mul(optimizedMoments, float4x4(0.2227744146f, 0.1549679261f, 0.1451988946f, 0.163127443f, + 0.0771972861f, 0.1394629426f, 0.2120202157f, 0.2591432266f, + 0.7926986636f, 0.7963415838f, 0.7258694464f, 0.6539092497f, + 0.0319417555f,-0.1722823173f,-0.2758014811f,-0.3376131734f)); +} + +float ComputeMSMHamburger(in float4 moments, in float fragmentDepth, in float depthBias, in float momentBias) +{ + // Bias input data to avoid artifacts + float4 b = lerp(moments, float4(0.5f, 0.5f, 0.5f, 0.5f), momentBias); + float3 z; + z[0] = fragmentDepth - depthBias; + + // Compute a Cholesky factorization of the Hankel matrix B storing only non- + // trivial entries or related products + float L32D22 = mad(-b[0], b[1], b[2]); + float D22 = mad(-b[0], b[0], b[1]); + float squaredDepthVariance = mad(-b[1], b[1], b[3]); + float D33D22 = dot(float2(squaredDepthVariance, -L32D22), float2(D22, L32D22)); + float InvD22 = 1.0f / D22; + float L32 = L32D22 * InvD22; + + // Obtain a scaled inverse image of bz = (1,z[0],z[0]*z[0])^T + float3 c = float3(1.0f, z[0], z[0] * z[0]); + + // Forward substitution to solve L*c1=bz + c[1] -= b.x; + c[2] -= b.y + L32 * c[1]; + + // Scaling to solve D*c2=c1 + c[1] *= InvD22; + c[2] *= D22 / D33D22; + + // Backward substitution to solve L^T*c3=c2 + c[1] -= L32 * c[2]; + c[0] -= dot(c.yz, b.xy); + + // Solve the quadratic equation c[0]+c[1]*z+c[2]*z^2 to obtain solutions + // z[1] and z[2] + float p = c[1] / c[2]; + float q = c[0] / c[2]; + float D = (p * p * 0.25f) - q; + float r = sqrt(D); + z[1] =- p * 0.5f - r; + z[2] =- p * 0.5f + r; + + // Compute the shadow intensity by summing the appropriate weights + float4 switchVal = (z[2] < z[0]) ? float4(z[1], z[0], 1.0f, 1.0f) : + ((z[1] < z[0]) ? float4(z[0], z[1], 0.0f, 1.0f) : + float4(0.0f,0.0f,0.0f,0.0f)); + float quotient = (switchVal[0] * z[2] - b[0] * (switchVal[0] + z[2]) + b[1])/((z[2] - switchVal[1]) * (z[0] - z[1])); + float shadowIntensity = switchVal[2] + switchVal[3] * quotient; + return 1.0f - saturate(shadowIntensity); +} + +float ComputeMSMHausdorff(in float4 moments, in float fragmentDepth, in float depthBias, in float momentBias) +{ + // Bias input data to avoid artifacts + float4 b = lerp(moments, float4(0.5f, 0.5f, 0.5f, 0.5f), momentBias); + float3 z; + z[0] = fragmentDepth - depthBias; + + // Compute a Cholesky factorization of the Hankel matrix B storing only non- + // trivial entries or related products + float L32D22 = mad(-b[0], b[1], b[2]); + float D22 = mad(-b[0], b[0], b[1]); + float squaredDepthVariance = mad(-b[1], b[1], b[3]); + float D33D22 = dot(float2(squaredDepthVariance, -L32D22), float2(D22, L32D22)); + float InvD22 = 1.0f / D22; + float L32 = L32D22 * InvD22; + + // Obtain a scaled inverse image of bz=(1,z[0],z[0]*z[0])^T + float3 c = float3(1.0f, z[0], z[0] * z[0]); + + // Forward substitution to solve L*c1=bz + c[1] -= b.x; + c[2] -= b.y + L32 * c[1]; + + // Scaling to solve D*c2=c1 + c[1] *= InvD22; + c[2] *= D22 / D33D22; + + // Backward substitution to solve L^T*c3=c2 + c[1] -= L32 * c[2]; + c[0] -= dot(c.yz, b.xy); + + // Solve the quadratic equation c[0]+c[1]*z+c[2]*z^2 to obtain solutions z[1] + // and z[2] + float p = c[1] / c[2]; + float q = c[0] / c[2]; + float D = ((p * p) / 4.0f) - q; + float r = sqrt(D); + z[1] =- (p / 2.0f) - r; + z[2] =- (p / 2.0f) + r; + + float shadowIntensity = 1.0f; + + // Use a solution made of four deltas if the solution with three deltas is invalid + if(z[1] < 0.0f || z[2] > 1.0f) + { + float zFree = ((b[2] - b[1]) * z[0] + b[2] - b[3]) / ((b[1] - b[0]) * z[0] + b[1] - b[2]); + float w1Factor = (z[0] > zFree) ? 1.0f : 0.0f; + shadowIntensity = (b[1] - b[0] + (b[2] - b[0] - (zFree + 1.0f) * (b[1] - b[0])) * (zFree - w1Factor - z[0]) + /(z[0] * (z[0] - zFree))) / (zFree - w1Factor) + 1.0f - b[0]; + } + // Use the solution with three deltas + else{ + float4 switchVal = (z[2] < z[0]) ? float4(z[1], z[0], 1.0f, 1.0f) : + ((z[1] < z[0]) ? float4(z[0], z[1], 0.0f, 1.0f) : + float4(0.0f, 0.0f, 0.0f, 0.0f)); + float quotient = (switchVal[0] * z[2] - b[0] * (switchVal[0] + z[2]) + b[1]) / ((z[2] - switchVal[1]) * (z[0] - z[1])); + shadowIntensity = switchVal[2] + switchVal[3] * quotient; + } + + return 1.0f - saturate(shadowIntensity); +} \ No newline at end of file diff --git a/SampleFramework12/v1.00/Shaders/PPCommon.hlsl b/SampleFramework12/v1.01/Shaders/PPCommon.hlsl similarity index 64% rename from SampleFramework12/v1.00/Shaders/PPCommon.hlsl rename to SampleFramework12/v1.01/Shaders/PPCommon.hlsl index a28de25..898e353 100644 --- a/SampleFramework12/v1.00/Shaders/PPCommon.hlsl +++ b/SampleFramework12/v1.01/Shaders/PPCommon.hlsl @@ -12,14 +12,19 @@ SamplerState LinearSampler : register(s1); SamplerState LinearWrapSampler : register(s2); SamplerState LinearBorderSampler : register(s3); -Texture2D InputTexture0 : register(t0); -Texture2D InputTexture1 : register(t1); -Texture2D InputTexture2 : register(t2); -Texture2D InputTexture3 : register(t3); -Texture2D InputTexture4 : register(t4); -Texture2D InputTexture5 : register(t5); -Texture2D InputTexture6 : register(t6); -Texture2D InputTexture7 : register(t7); +struct SRVIndicesLayout +{ + uint Idx0; + uint Idx1; + uint Idx2; + uint Idx3; + uint Idx4; + uint Idx5; + uint Idx6; + uint Idx7; +}; + +ConstantBuffer SRVIndices : register(b0); struct PSInput { diff --git a/SampleFramework12/v1.00/Shaders/Quaternion.hlsl b/SampleFramework12/v1.01/Shaders/Quaternion.hlsl similarity index 100% rename from SampleFramework12/v1.00/Shaders/Quaternion.hlsl rename to SampleFramework12/v1.01/Shaders/Quaternion.hlsl diff --git a/SampleFramework12/v1.00/Shaders/SH.hlsl b/SampleFramework12/v1.01/Shaders/SH.hlsl similarity index 100% rename from SampleFramework12/v1.00/Shaders/SH.hlsl rename to SampleFramework12/v1.01/Shaders/SH.hlsl diff --git a/SampleFramework12/v1.01/Shaders/SMConvert.hlsl b/SampleFramework12/v1.01/Shaders/SMConvert.hlsl new file mode 100644 index 0000000..ea05c3d --- /dev/null +++ b/SampleFramework12/v1.01/Shaders/SMConvert.hlsl @@ -0,0 +1,507 @@ +//================================================================================================= +// +// MJP's DX12 Sample Framework +// http://mynameismjp.wordpress.com/ +// +// All code licensed under the MIT license +// +//================================================================================================= + +//================================================================================================= +// Includes +//================================================================================================= +#include +#include +#include + +//================================================================================================= +// Constants +//================================================================================================= +#ifndef MSAASamples_ + #define MSAASamples_ 1 +#endif + +#ifndef SampleRadius_ + #define SampleRadius_ 0 +#endif + +//================================================================================================= +// Resources +//================================================================================================= +struct ConvertConstants +{ + float2 ShadowMapSize; + float PositiveExponent; + float NegativeExponent; + float FilterSizeU; + float FilterSizeV; + bool LinearizeDepth; + float NearClip; + float InvClipRange; + float Proj33; + float Proj43; + uint InputMapIdx; + uint ArraySliceIdx; +}; + +ConstantBuffer CBuffer : register(b0); + +SamplerState LinearSampler : register (s0); + +float4 SMConvert(in float4 Position : SV_Position) : SV_Target0 +{ + float sampleWeight = 1.0f / float(MSAASamples_); + uint2 coords = uint2(Position.xy); + + float2 exponents = GetEVSMExponents(CBuffer.PositiveExponent, CBuffer.NegativeExponent, 1.0f); + + float4 average = float4(0.0f, 0.0f, 0.0f, 0.0f); + + // Sample indices to Load() must be literal, so force unroll + [unroll] + for(uint i = 0; i < MSAASamples_; ++i) + { + // Convert to EVSM representation + #if MSAASamples_ > 1 + Texture2DMS shadowMap = Tex2DMSTable[CBuffer.InputMapIdx]; + float depth = shadowMap.Load(coords, i).x; + #else + Texture2D shadowMap = Tex2DTable[CBuffer.InputMapIdx]; + float depth = shadowMap[coords].x; + #endif + + if(CBuffer.LinearizeDepth) + { + depth = CBuffer.Proj43 / (depth - CBuffer.Proj33); + depth = (depth - CBuffer.NearClip) * CBuffer.InvClipRange; + } + + #if MSM_ + float4 msmDepth = GetOptimizedMoments(depth); + average += sampleWeight * msmDepth; + #elif EVSM_ + float2 vsmDepth = WarpDepth(depth, exponents); + average += sampleWeight * float4(vsmDepth.xy, vsmDepth.xy * vsmDepth.xy); + #endif + } + + return average; +} + +float4 FilterSample(in float2 texelPos, in float offset, in float2 mapSize) +{ + float2 samplePos = texelPos; + + #if Vertical_ + samplePos.y = clamp(texelPos.y + offset, 0, mapSize.y - 1.0f); + Texture2D shadowMap = Tex2DTable[CBuffer.InputMapIdx]; + return shadowMap[uint2(samplePos)]; + #else + samplePos.x = clamp(texelPos.x + offset, 0, mapSize.x - 1.0f); + Texture2DArray shadowMap = Tex2DArrayTable[CBuffer.InputMapIdx]; + return shadowMap[uint3(samplePos, CBuffer.ArraySliceIdx)]; + #endif +} + +float4 FilterSM(in float4 Position : SV_Position) : SV_Target0 +{ + #if Vertical_ + const float filterSize = CBuffer.FilterSizeU; + const float texelSize = rcp(CBuffer.ShadowMapSize.y); + Texture2D shadowMap = Tex2DTable[CBuffer.InputMapIdx]; + #else + const float filterSize = CBuffer.FilterSizeV; + const float texelSize = rcp(CBuffer.ShadowMapSize.x); + Texture2DArray shadowMap = Tex2DArrayTable[CBuffer.InputMapIdx]; + #endif + + const float Radius = filterSize / 2.0f; + + float4 sum = 0.0f; + + #if 1 && SampleRadius_ > 0 + const float2 uv = Position.xy * rcp(CBuffer.ShadowMapSize); + float edgeFraction = Radius - (SampleRadius_ - 0.5f); + + float weightSum = 0.0f; + + [unroll] + for(float x = -SampleRadius_ + 0.5f; x <= SampleRadius_ + 0.5f; x += 2.0f) + { + float offset = x; + float sampleWeight = 2.0f; + if(x == -SampleRadius_ + 0.5f) + { + offset += (1.0f - edgeFraction) * 0.5f; + sampleWeight = 1.0f + edgeFraction; + } + else if(x == SampleRadius_ + 0.5f) + { + offset -= 0.5f; + sampleWeight = edgeFraction; + } + + #if Vertical_ + const float2 sampleUV = uv + float2(0.0f, offset) * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * sampleWeight; + #else + const float2 sampleUV = uv + float2(offset, 0.0f) * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, float3(sampleUV, CBuffer.ArraySliceIdx), 0.0f) * sampleWeight; + #endif + + weightSum += sampleWeight; + } + + return sum / filterSize; + #else + [unroll] + for(int i = -SampleRadius_; i <= SampleRadius_; ++i) + { + float4 smSample = FilterSample(Position.xy, i, CBuffer.ShadowMapSize); + + smSample *= saturate((Radius + 0.5f) - abs(i)); + + sum += smSample; + } + + return sum / filterSize; + #endif +} + +float4 FilterSM3x3(in float4 Position : SV_Position) : SV_Target0 +{ + const float2 texelSize = rcp(CBuffer.ShadowMapSize); + + const float2 uv = Position.xy * texelSize; + + const float2 radius = float2(CBuffer.FilterSizeU, CBuffer.FilterSizeV) / 2.0f; + float2 edgeFraction = radius - 0.5f; + + Texture2D shadowMap = Tex2DTable[CBuffer.InputMapIdx]; + + float4 sum = 0.0f; + + // +---+---+---+ + // | | | + // | | | + // | | | + // + 0 + 1 + + // | | | + // | | | + // | | | + // +---+---+---+ + // | | | + // | 2 | 3 | + // | | | + // +---+---+---+ + + { + // Top left 2x2 + float2 offset = float2(-0.5f, -0.5f) + ((1.0f - edgeFraction) * float2(0.5f, 0.5f)); + float2 weights = 1.0f + edgeFraction; + + const float2 sampleUV = uv + offset * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * weights.x * weights.y; + } + + { + // Top right 1x2 + float2 offset = float2(1.0f, -0.5f) + float2(0.0f, (1.0f - edgeFraction.y) * 0.5f); + float2 weights = float2(0.0f, 1.0f) + edgeFraction; + + const float2 sampleUV = uv + offset * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * weights.x * weights.y; + } + + { + // Bottom left 2x1 + float2 offset = float2(-0.5f, 1.0f) + float2((1.0f - edgeFraction.x) * 0.5f, 0.0f); + float2 weights = float2(1.0f, 0.0f) + edgeFraction; + + const float2 sampleUV = uv + offset * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * weights.x * weights.y; + } + + { + // Bottom right 1x1 + float2 offset = float2(1.0f, 1.0f); + float2 weights = edgeFraction; + + const float2 sampleUV = uv + offset * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * weights.x * weights.y; + } + + return sum / (CBuffer.FilterSizeU * CBuffer.FilterSizeV); +} + +float4 FilterSM5x5(in float4 Position : SV_Position) : SV_Target0 +{ + const float2 texelSize = rcp(CBuffer.ShadowMapSize); + + const float2 uv = Position.xy * texelSize; + + const float2 radius = float2(CBuffer.FilterSizeU, CBuffer.FilterSizeV) / 2.0f; + float2 edgeFraction = radius - 1.5f; + + Texture2D shadowMap = Tex2DTable[CBuffer.InputMapIdx]; + + float4 sum = 0.0f; + + // +---+---+---+---+---+ + // | | | | + // | | | | + // | | | | + // + 0 + 1 + 2 + + // | | | | + // | | | | + // | | | | + // +---+---+---+---+---+ + // | | | | + // | | | | + // | | | | + // + 3 + 4 + 5 + + // | | | | + // | | | | + // | | | | + // +---+---+---+---+---+ + // | | | | + // | 6 | 7 | 8 | + // | | | | + // +---+---+---+---+---+ + + { + // Top left 2x2 + float2 offset = float2(-1.5f, -1.5f) + ((1.0f - edgeFraction) * float2(0.5f, 0.5f)); + float2 weights = 1.0f + edgeFraction; + + const float2 sampleUV = uv + offset * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * weights.x * weights.y; + } + + { + // Middle top 2x2 + float2 offset = float2(0.5f, -1.5f) + float2(0.0f, (1.0f - edgeFraction.y) * 0.5f); + float2 weights = float2(2.0f, 1.0f + edgeFraction.y); + + const float2 sampleUV = uv + offset * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * weights.x * weights.y; + } + + { + // Top right 1x2 + float2 offset = float2(2.0f, -1.5f) + float2(0.0f, (1.0f - edgeFraction.y) * 0.5f); + float2 weights = float2(0.0f, 1.0f) + edgeFraction; + + const float2 sampleUV = uv + offset * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * weights.x * weights.y; + } + + { + // Left middle 2x2 + float2 offset = float2(-1.5f, 0.5f) + float2((1.0f - edgeFraction.x) * 0.5f, 0.0f); + float2 weights = float2(1.0f + edgeFraction.x, 2.0f); + + const float2 sampleUV = uv + offset * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * weights.x * weights.y; + } + + { + // Middle 2x2 + float2 offset = float2(0.5f, 0.5f); + float2 weights = float2(2.0f, 2.0f); + + const float2 sampleUV = uv + offset * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * weights.x * weights.y; + } + + { + // Middle right 1x2 + float2 offset = float2(2.0f, 0.5f); + float2 weights = float2(edgeFraction.x, 2.0f); + + const float2 sampleUV = uv + offset * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * weights.x * weights.y; + } + + { + // Bottom left 2x1 + float2 offset = float2(-1.5f, 2.0f) + float2((1.0f - edgeFraction.x) * 0.5f, 0.0f); + float2 weights = float2(1.0f, 0.0f) + edgeFraction; + + const float2 sampleUV = uv + offset * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * weights.x * weights.y; + } + + { + // Bottom middle 2x1 + float2 offset = float2(0.5f, 2.0f); + float2 weights = float2(2.0f, edgeFraction.y); + + const float2 sampleUV = uv + offset * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * weights.x * weights.y; + } + + { + // Bottom right 1x1 + float2 offset = float2(2.0f, 2.0f); + float2 weights = edgeFraction; + + const float2 sampleUV = uv + offset * texelSize; + sum += shadowMap.SampleLevel(LinearSampler, sampleUV, 0.0f) * weights.x * weights.y; + } + + return sum / (CBuffer.FilterSizeU * CBuffer.FilterSizeV); +} + +#if CS_ + +static const uint BaseThreadGroupWidth = 8; +static const uint GuardBandSize = SampleRadius_; +static const uint ThreadGroupWidth = BaseThreadGroupWidth + GuardBandSize * 2; + +#define UsePackedSharedMem_ 0 + +#if SampleRadius_ > 0 + #if UsePackedSharedMem_ + groupshared uint2 SharedMem[ThreadGroupWidth][ThreadGroupWidth]; + #else + groupshared float4 SharedMem[ThreadGroupWidth][ThreadGroupWidth]; + #endif +#endif + +#if UsePackedSharedMem_ + +uint2 PackToSharedMem(in float4 unpacked) +{ + uint2 packed = 0; + packed.x = uint(unpacked.x * float(0xFFFF)); + packed.x |= uint(unpacked.y * float(0xFFFF)) << 16; + packed.y = uint(unpacked.z * float(0xFFFF)); + packed.y |= uint(unpacked.w * float(0xFFFF)) << 16; + + return packed; +} + +float4 UnpackFromSharedMem(in uint2 packed) +{ + float4 unpacked; + unpacked.x = (packed.x & 0xFFFF) / float(0xFFFF); + unpacked.y = ((packed.x >> 16) & 0xFFFF) / float(0xFFFF); + unpacked.z = (packed.y & 0xFFFF) / float(0xFFFF); + unpacked.w = ((packed.y >> 16) & 0xFFFF) / float(0xFFFF); + + return unpacked; +} + +#else + +float4 PackToSharedMem(in float4 unpacked) { return unpacked; } +float4 UnpackFromSharedMem(in float4 packed) { return packed; } + +#endif + + +RWTexture2DArray OutputTexture : register(u0); + +[numthreads(ThreadGroupWidth, ThreadGroupWidth, 1)] +void SMConvertAndFilter(in uint3 GroupID : SV_GroupID, in uint3 GroupThreadID : SV_GroupThreadID, in uint GroupIndex : SV_GroupIndex) +{ + const float2 MaxTexelIdx = CBuffer.ShadowMapSize - 1.0f; + const float2 UnclampedTexelIdx = (GroupID.xy * BaseThreadGroupWidth + GroupThreadID.xy) - float(GuardBandSize); + const float2 TexelIdx = clamp(UnclampedTexelIdx, 0.0f, MaxTexelIdx); + + { + float sampleWeight = 1.0f / float(MSAASamples_); + + float2 exponents = GetEVSMExponents(CBuffer.PositiveExponent, CBuffer.NegativeExponent, 1.0f); + + float4 converted = float4(0.0f, 0.0f, 0.0f, 0.0f); + + // Sample indices to Load() must be literal, so force unroll + [unroll] + for(uint i = 0; i < MSAASamples_; ++i) + { + // Convert to EVSM representation + #if MSAASamples_ > 1 + Texture2DMS shadowMap = Tex2DMSTable[CBuffer.InputMapIdx]; + float depth = shadowMap.Load(TexelIdx, i).x; + #else + Texture2D shadowMap = Tex2DTable[CBuffer.InputMapIdx]; + float depth = shadowMap[TexelIdx].x; + #endif + + if(CBuffer.LinearizeDepth) + { + depth = CBuffer.Proj43 / (depth - CBuffer.Proj33); + depth = (depth - CBuffer.NearClip) * CBuffer.InvClipRange; + } + + #if MSM_ + float4 msmDepth = GetOptimizedMoments(depth); + converted += sampleWeight * msmDepth; + #elif EVSM_ + float2 vsmDepth = WarpDepth(depth, exponents); + converted += sampleWeight * float4(vsmDepth.xy, vsmDepth.xy * vsmDepth.xy); + #endif + } + + #if SampleRadius_ > 0 + SharedMem[GroupThreadID.y][GroupThreadID.x] = PackToSharedMem(converted); + #else + OutputTexture[uint3(GroupID.xy * ThreadGroupWidth + GroupThreadID.xy, CBuffer.ArraySliceIdx)] = converted; + #endif + } + + #if SampleRadius_ > 0 + GroupMemoryBarrierWithGroupSync(); + + { + const float radiusU = CBuffer.FilterSizeU / 2.0f; + + float4 filteredU = 0.0f; + + [unroll] + for(int i = -SampleRadius_; i <= SampleRadius_; ++i) + { + float4 smSample = UnpackFromSharedMem(SharedMem[GroupThreadID.y][int(GroupThreadID.x) + i]); + + smSample *= saturate((radiusU + 0.5f) - abs(i)); + + filteredU += smSample; + } + + filteredU /= CBuffer.FilterSizeU; + + GroupMemoryBarrierWithGroupSync(); + + SharedMem[GroupThreadID.y][GroupThreadID.x] = PackToSharedMem(filteredU); + } + + GroupMemoryBarrierWithGroupSync(); + + if(GroupIndex < BaseThreadGroupWidth * BaseThreadGroupWidth) + { + const uint2 localIdx = uint2(GroupIndex / BaseThreadGroupWidth, GroupIndex % BaseThreadGroupWidth); + + const float radiusV = CBuffer.FilterSizeV / 2.0f; + + float4 filtered = 0.0f; + + [unroll] + for(int i = -SampleRadius_; i <= SampleRadius_; ++i) + { + float4 smSample = UnpackFromSharedMem(SharedMem[int(localIdx.y + GuardBandSize) + i][localIdx.x + GuardBandSize]); + + smSample *= saturate((radiusV + 0.5f) - abs(i)); + + filtered += smSample; + } + + filtered /= CBuffer.FilterSizeV; + + OutputTexture[uint3(GroupID.xy * BaseThreadGroupWidth + localIdx, CBuffer.ArraySliceIdx)] = filtered; + } + #endif +} + +#endif // CS_ \ No newline at end of file diff --git a/SampleFramework12/v1.01/Shaders/Shadows.hlsl b/SampleFramework12/v1.01/Shaders/Shadows.hlsl new file mode 100644 index 0000000..c787856 --- /dev/null +++ b/SampleFramework12/v1.01/Shaders/Shadows.hlsl @@ -0,0 +1,595 @@ +//================================================================================================= +// +// MJP's DX12 Sample Framework +// http://mynameismjp.wordpress.com/ +// +// All code licensed under the MIT license +// +//================================================================================================= + +#include +#include + +#define ShadowMapMode_DepthMap_ 0 +#define ShadowMapMode_EVSM_ 1 +#define ShadowMapMode_MSM_ 2 + +// Options +#ifndef ShadowMapMode_ + #define ShadowMapMode_ ShadowMapMode_DepthMap_ +#endif + +#ifndef UseGatherPCF_ + #define UseGatherPCF_ 0 +#endif + +//================================================================================================= +// Constants +//================================================================================================= +static const uint NumCascades = 4; + +struct SunShadowConstantsBase +{ + row_major float4x4 ShadowMatrix; + float4 CascadeSplits; + float4 CascadeOffsets[NumCascades]; + float4 CascadeScales[NumCascades]; +}; + +struct EVSMConstants +{ + float PositiveExponent; + float NegativeExponent; + float LightBleedingReduction; + uint Padding; +}; + +struct MSMConstants +{ + float DepthBias; + float MomentBias; + float LightBleedingReduction; + uint Padding; +}; + +struct SunShadowConstantsDepthMap +{ + SunShadowConstantsBase Base; + uint4 Extra; +}; + +struct SunShadowConstantsEVSM +{ + SunShadowConstantsBase Base; + EVSMConstants Extra; +}; + +struct SunShadowConstantsMSM +{ + SunShadowConstantsBase Base; + MSMConstants Extra; +}; + +#if ShadowMapMode_ == ShadowMapMode_DepthMap_ + #define SunShadowConstants SunShadowConstantsDepthMap + typedef uint4 ExtraShadowConstants; + typedef SamplerComparisonState ShadowSampler; +#elif ShadowMapMode_ == ShadowMapMode_EVSM_ + #define SunShadowConstants SunShadowConstantsEVSM + typedef EVSMConstants ExtraShadowConstants; + typedef SamplerState ShadowSampler; +#elif ShadowMapMode_ == ShadowMapMode_MSM_ + #define SunShadowConstants SunShadowConstantsMSM + typedef MSMConstants ExtraShadowConstants; + typedef SamplerState ShadowSampler; +#endif + +//------------------------------------------------------------------------------------------------- +// Samples the EVSM shadow map with explicit gradients +//------------------------------------------------------------------------------------------------- +float SampleShadowMapEVSM(in float3 shadowPos, in float3 shadowPosDX, in float3 shadowPosDY, in uint arrayIdx, + in Texture2DArray shadowMap, in SamplerState evsmSampler, in EVSMConstants evsmConstants, in float3 cascadeScale) +{ + float2 exponents = GetEVSMExponents(evsmConstants.PositiveExponent, evsmConstants.NegativeExponent, cascadeScale); + float2 warpedDepth = WarpDepth(shadowPos.z, exponents); + + float4 occluder = shadowMap.SampleGrad(evsmSampler, float3(shadowPos.xy, arrayIdx), shadowPosDX.xy, shadowPosDY.xy); + + // Derivative of warping at depth + float2 depthScale = 0.0001f * exponents * warpedDepth; + float2 minVariance = depthScale * depthScale; + + float posContrib = ChebyshevUpperBound(occluder.xz, warpedDepth.x, minVariance.x, evsmConstants.LightBleedingReduction); + float negContrib = ChebyshevUpperBound(occluder.yw, warpedDepth.y, minVariance.y, evsmConstants.LightBleedingReduction); + float shadowContrib = posContrib; + shadowContrib = min(shadowContrib, negContrib); + + return shadowContrib; +} + +//------------------------------------------------------------------------------------------------- +// Samples the EVSM shadow map with implicit gradients +//------------------------------------------------------------------------------------------------- +float SampleShadowMapEVSM(in float3 shadowPos, in uint arrayIdx, in Texture2DArray shadowMap, in SamplerState evsmSampler, + in EVSMConstants evsmConstants, in float3 cascadeScale) +{ + float2 exponents = GetEVSMExponents(evsmConstants.PositiveExponent, evsmConstants.NegativeExponent, cascadeScale); + float2 warpedDepth = WarpDepth(shadowPos.z, exponents); + + float4 occluder = shadowMap.Sample(evsmSampler, float3(shadowPos.xy, arrayIdx)); + + // Derivative of warping at depth + float2 depthScale = 0.0001f * exponents * warpedDepth; + float2 minVariance = depthScale * depthScale; + + float posContrib = ChebyshevUpperBound(occluder.xz, warpedDepth.x, minVariance.x, evsmConstants.LightBleedingReduction); + float negContrib = ChebyshevUpperBound(occluder.yw, warpedDepth.y, minVariance.y, evsmConstants.LightBleedingReduction); + float shadowContrib = posContrib; + shadowContrib = min(shadowContrib, negContrib); + + return shadowContrib; +} + +//------------------------------------------------------------------------------------------------- +// Samples the MSM shadow map with explicit gradients +//------------------------------------------------------------------------------------------------- +float SampleShadowMapMSM(in float3 shadowPos, in float3 shadowPosDX, in float3 shadowPosDY, in uint arrayIdx, + in Texture2DArray shadowMap, in SamplerState evsmSampler, in MSMConstants msmConstants) +{ + float4 moments = shadowMap.SampleGrad(evsmSampler, float3(shadowPos.xy, arrayIdx), shadowPosDX.xy, shadowPosDY.xy); + moments = ConvertOptimizedMoments(moments); + float result = ComputeMSMHamburger(moments, shadowPos.z, msmConstants.DepthBias, msmConstants.MomentBias); + + return ReduceLightBleeding(result, msmConstants.LightBleedingReduction); +} + +//------------------------------------------------------------------------------------------------- +// Samples the MSM shadow map with implicit gradients +//------------------------------------------------------------------------------------------------- +float SampleShadowMapMSM(in float3 shadowPos, in uint arrayIdx, in Texture2DArray shadowMap, + in SamplerState evsmSampler, in MSMConstants msmConstants) +{ + float4 moments = shadowMap.Sample(evsmSampler, float3(shadowPos.xy, arrayIdx)); + moments = ConvertOptimizedMoments(moments); + float result = ComputeMSMHamburger(moments, shadowPos.z, msmConstants.DepthBias, msmConstants.MomentBias); + + return ReduceLightBleeding(result, msmConstants.LightBleedingReduction); +} + +#if UseGatherPCF_ + +// 7x7 disc kernel +static const uint ShadowFilterSize = 7; +static const float W[ShadowFilterSize][ShadowFilterSize] = +{ + { 0.0f, 0.0f, 0.5f, 1.0f, 0.5f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f }, + { 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f }, + { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }, + { 0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f }, + { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f }, + { 0.0f, 0.0f, 0.5f, 1.0f, 0.5f, 0.0f, 0.0f } +}; + +//------------------------------------------------------------------------------------------------- +// Samples the shadow map with a fixed-size PCF kernel optimized with GatherCmp. Uses code +// from "Fast Conventional Shadow Filtering" by Holger Gruen, in GPU Pro. +//------------------------------------------------------------------------------------------------- +float SampleShadowMapPCF(in float3 shadowPos, in uint arrayIdx, in Texture2DArray shadowMap, + in SamplerComparisonState shadowSampler) { + float2 shadowMapSize; + float numSlices; + shadowMap.GetDimensions(shadowMapSize.x, shadowMapSize.y, numSlices); + float2 texelSize = 1.0f / shadowMapSize; + + float lightDepth = shadowPos.z - 0.001f; + + const int FS_2 = int(ShadowFilterSize) / 2; + + float2 tc = shadowPos.xy; + + float4 s = 0.0f; + float2 stc = (shadowMapSize * tc.xy) + float2(0.5f, 0.5f); + float2 tcs = floor(stc); + float2 fc = 0.0f; + float w = 0.0f; + float4 v1[FS_2 + 1]; + float2 v0[FS_2 + 1]; + + fc.xy = stc - tcs; + tc.xy = tcs / shadowMapSize; + + for(uint y = 0; y < ShadowFilterSize; ++y) + for(uint x = 0; x < ShadowFilterSize; ++x) + w += W[y][x]; + + // -- loop over the rows + [unroll] + for(int row = -FS_2; row <= FS_2; row += 2) + { + [unroll] + for(int col = -FS_2; col <= FS_2; col += 2) + { + float value = W[row + FS_2][col + FS_2]; + + if(col > -FS_2) + value += W[row + FS_2][col + FS_2 - 1]; + + if(col < FS_2) + value += W[row + FS_2][col + FS_2 + 1]; + + if(row > -FS_2) { + value += W[row + FS_2 - 1][col + FS_2]; + + if(col < FS_2) + value += W[row + FS_2 - 1][col + FS_2 + 1]; + + if(col > -FS_2) + value += W[row + FS_2 - 1][col + FS_2 - 1]; + } + + if(value != 0.0f) + v1[(col + FS_2) / 2] = shadowMap.GatherCmp(shadowSampler, float3(tc.xy, arrayIdx), lightDepth, int2(col, row)); + else + v1[(col + FS_2) / 2] = 0.0f; + + if(col == -FS_2) + { + s.x += (1.0f - fc.y) * (v1[0].w * (W[row + FS_2][col + FS_2] - W[row + FS_2][col + FS_2] * fc.x) + v1[0].z * (fc.x * (W[row + FS_2][col + FS_2] + - W[row + FS_2][col + FS_2 + 1.0f]) + W[row + FS_2][col + FS_2 + 1])); + s.y += fc.y * (v1[0].x * (W[row + FS_2][col + FS_2] - W[row + FS_2][col + FS_2] * fc.x) + + v1[0].y * (fc.x * (W[row + FS_2][col + FS_2] - W[row + FS_2][col + FS_2 + 1]) + + W[row + FS_2][col + FS_2 + 1])); + if(row > -FS_2) + { + s.z += (1.0f - fc.y) * (v0[0].x * (W[row + FS_2 - 1][col + FS_2] - W[row + FS_2 - 1][col + FS_2] * fc.x) + + v0[0].y * (fc.x * (W[row + FS_2 - 1][col + FS_2] - W[row + FS_2 - 1][col + FS_2 + 1]) + + W[row + FS_2 - 1][col + FS_2 + 1])); + s.w += fc.y * (v1[0].w * (W[row + FS_2 - 1][col + FS_2] - W[row + FS_2 - 1][col + FS_2] * fc.x) + + v1[0].z * (fc.x * (W[row + FS_2 - 1][col + FS_2] - W[row + FS_2 - 1][col + FS_2 + 1]) + + W[row + FS_2 - 1][col + FS_2 + 1])); + } + } + else if(col == FS_2) + { + s.x += (1 - fc.y) * (v1[FS_2].w * (fc.x * (W[row + FS_2][col + FS_2 - 1] - W[row + FS_2][col + FS_2]) + W[row + FS_2][col + FS_2]) + + v1[FS_2].z * fc.x * W[row + FS_2][col + FS_2]); + s.y += fc.y * (v1[FS_2].x * (fc.x * (W[row + FS_2][col + FS_2 - 1] - W[row + FS_2][col + FS_2] ) + W[row + FS_2][col + FS_2]) + + v1[FS_2].y * fc.x * W[row + FS_2][col + FS_2]); + if(row > -FS_2) { + s.z += (1 - fc.y) * (v0[FS_2].x * (fc.x * (W[row + FS_2 - 1][col + FS_2 - 1] - W[row + FS_2 - 1][col + FS_2]) + + W[row + FS_2 - 1][col + FS_2]) + v0[FS_2].y * fc.x * W[row + FS_2 - 1][col + FS_2]); + s.w += fc.y * (v1[FS_2].w * (fc.x * (W[row + FS_2 - 1][col + FS_2 - 1] - W[row + FS_2 - 1][col + FS_2]) + + W[row + FS_2 - 1][col + FS_2]) + v1[FS_2].z * fc.x * W[row + FS_2 - 1][col + FS_2]); + } + } + else + { + s.x += (1 - fc.y) * (v1[(col + FS_2) / 2].w * (fc.x * (W[row + FS_2][col + FS_2 - 1] - W[row + FS_2][col + FS_2 + 0] ) + W[row + FS_2][col + FS_2 + 0]) + + v1[(col + FS_2) / 2].z * (fc.x * (W[row + FS_2][col + FS_2 - 0] - W[row + FS_2][col + FS_2 + 1]) + W[row + FS_2][col + FS_2 + 1])); + s.y += fc.y * (v1[(col + FS_2) / 2].x * (fc.x * (W[row + FS_2][col + FS_2-1] - W[row + FS_2][col + FS_2 + 0]) + W[row + FS_2][col + FS_2 + 0]) + + v1[(col + FS_2) / 2].y * (fc.x * (W[row + FS_2][col + FS_2 - 0] - W[row + FS_2][col + FS_2 + 1]) + W[row + FS_2][col + FS_2 + 1])); + if(row > -FS_2) { + s.z += (1 - fc.y) * (v0[(col + FS_2) / 2].x * (fc.x * (W[row + FS_2 - 1][col + FS_2 - 1] - W[row + FS_2 - 1][col + FS_2 + 0]) + W[row + FS_2 - 1][col + FS_2 + 0]) + + v0[(col + FS_2) / 2].y * (fc.x * (W[row + FS_2 - 1][col + FS_2 - 0] - W[row + FS_2 - 1][col + FS_2 + 1]) + W[row + FS_2 - 1][col + FS_2 + 1])); + s.w += fc.y * (v1[(col + FS_2) / 2].w * (fc.x * (W[row + FS_2 - 1][col + FS_2 - 1] - W[row + FS_2 - 1][col + FS_2 + 0]) + W[row + FS_2 - 1][col + FS_2 + 0]) + + v1[(col + FS_2) / 2].z * (fc.x * (W[row + FS_2 - 1][col + FS_2 - 0] - W[row + FS_2 - 1][col + FS_2 + 1]) + W[row + FS_2 - 1][col + FS_2 + 1])); + } + } + + if(row != FS_2) + v0[(col + FS_2) / 2] = v1[(col + FS_2) / 2].xy; + } + } + + return dot(s, 1.0f) / w; +} + +#else + +//------------------------------------------------------------------------------------------------- +// Helper function for SampleShadowMapPCF +//------------------------------------------------------------------------------------------------- +float SampleShadowMap(in float2 baseUV, in float u, in float v, in float2 shadowMapSizeInv, + in uint arrayIdx, in float depth, in Texture2DArray shadowMap, + in SamplerComparisonState pcfSampler) +{ + float2 uv = baseUV + float2(u, v) * shadowMapSizeInv; + return shadowMap.SampleCmpLevelZero(pcfSampler, float3(uv, arrayIdx), depth); +} + +//------------------------------------------------------------------------------------------------- +// Samples a shadow depth map with optimized PCF filtering +//------------------------------------------------------------------------------------------------- +float SampleShadowMapPCF(in float3 shadowPos, in uint arrayIdx, in Texture2DArray shadowMap, + in SamplerComparisonState pcfSampler) +{ + float2 shadowMapSize; + float numSlices; + shadowMap.GetDimensions(shadowMapSize.x, shadowMapSize.y, numSlices); + + float lightDepth = shadowPos.z - 0.001f; + + float2 uv = shadowPos.xy * shadowMapSize; // 1 unit - 1 texel + + float2 shadowMapSizeInv = 1.0 / shadowMapSize; + + float2 baseuv = floor(uv + 0.5f); + + float s = (uv.x + 0.5 - baseuv.x); + float t = (uv.y + 0.5 - baseuv.y); + + baseuv -= float2(0.5, 0.5); + baseuv *= shadowMapSizeInv; + + float sum = 0; + + #define FilterSize_ 7 + + #if FilterSize_ == 2 + return shadowMap.SampleCmpLevelZero(pcfSampler, float3(shadowPos.xy, arrayIdx), lightDepth); + #elif FilterSize_ == 3 + + float uw0 = (3 - 2 * s); + float uw1 = (1 + 2 * s); + + float u0 = (2 - s) / uw0 - 1; + float u1 = s / uw1 + 1; + + float vw0 = (3 - 2 * t); + float vw1 = (1 + 2 * t); + + float v0 = (2 - t) / vw0 - 1; + float v1 = t / vw1 + 1; + + sum += uw0 * vw0 * SampleShadowMap(baseuv, u0, v0, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw1 * vw0 * SampleShadowMap(baseuv, u1, v0, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw0 * vw1 * SampleShadowMap(baseuv, u0, v1, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw1 * vw1 * SampleShadowMap(baseuv, u1, v1, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + + return sum * 1.0f / 16; + + #elif FilterSize_ == 5 + + float uw0 = (4 - 3 * s); + float uw1 = 7; + float uw2 = (1 + 3 * s); + + float u0 = (3 - 2 * s) / uw0 - 2; + float u1 = (3 + s) / uw1; + float u2 = s / uw2 + 2; + + float vw0 = (4 - 3 * t); + float vw1 = 7; + float vw2 = (1 + 3 * t); + + float v0 = (3 - 2 * t) / vw0 - 2; + float v1 = (3 + t) / vw1; + float v2 = t / vw2 + 2; + + sum += uw0 * vw0 * SampleShadowMap(baseuv, u0, v0, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw1 * vw0 * SampleShadowMap(baseuv, u1, v0, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw2 * vw0 * SampleShadowMap(baseuv, u2, v0, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + + sum += uw0 * vw1 * SampleShadowMap(baseuv, u0, v1, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw1 * vw1 * SampleShadowMap(baseuv, u1, v1, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw2 * vw1 * SampleShadowMap(baseuv, u2, v1, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + + sum += uw0 * vw2 * SampleShadowMap(baseuv, u0, v2, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw1 * vw2 * SampleShadowMap(baseuv, u1, v2, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw2 * vw2 * SampleShadowMap(baseuv, u2, v2, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + + return sum * 1.0f / 144; + + #else // FilterSize_ == 7 + + float uw0 = (5 * s - 6); + float uw1 = (11 * s - 28); + float uw2 = -(11 * s + 17); + float uw3 = -(5 * s + 1); + + float u0 = (4 * s - 5) / uw0 - 3; + float u1 = (4 * s - 16) / uw1 - 1; + float u2 = -(7 * s + 5) / uw2 + 1; + float u3 = -s / uw3 + 3; + + float vw0 = (5 * t - 6); + float vw1 = (11 * t - 28); + float vw2 = -(11 * t + 17); + float vw3 = -(5 * t + 1); + + float v0 = (4 * t - 5) / vw0 - 3; + float v1 = (4 * t - 16) / vw1 - 1; + float v2 = -(7 * t + 5) / vw2 + 1; + float v3 = -t / vw3 + 3; + + sum += uw0 * vw0 * SampleShadowMap(baseuv, u0, v0, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw1 * vw0 * SampleShadowMap(baseuv, u1, v0, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw2 * vw0 * SampleShadowMap(baseuv, u2, v0, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw3 * vw0 * SampleShadowMap(baseuv, u3, v0, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + + sum += uw0 * vw1 * SampleShadowMap(baseuv, u0, v1, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw1 * vw1 * SampleShadowMap(baseuv, u1, v1, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw2 * vw1 * SampleShadowMap(baseuv, u2, v1, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw3 * vw1 * SampleShadowMap(baseuv, u3, v1, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + + sum += uw0 * vw2 * SampleShadowMap(baseuv, u0, v2, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw1 * vw2 * SampleShadowMap(baseuv, u1, v2, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw2 * vw2 * SampleShadowMap(baseuv, u2, v2, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw3 * vw2 * SampleShadowMap(baseuv, u3, v2, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + + sum += uw0 * vw3 * SampleShadowMap(baseuv, u0, v3, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw1 * vw3 * SampleShadowMap(baseuv, u1, v3, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw2 * vw3 * SampleShadowMap(baseuv, u2, v3, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + sum += uw3 * vw3 * SampleShadowMap(baseuv, u3, v3, shadowMapSizeInv, arrayIdx, lightDepth, shadowMap, pcfSampler); + + return sum * 1.0f / 2704; + + #endif +} + + +#endif + +//------------------------------------------------------------------------------------------------- +// Calculates the offset to use for sampling the shadow map, based on the surface normal +//------------------------------------------------------------------------------------------------- +float3 GetShadowPosOffset(in float nDotL, in float3 normal, in float shadowMapSize) +{ + const float offsetScale = 4.0f; + float texelSize = 2.0f / shadowMapSize; + float nmlOffsetScale = saturate(1.0f - nDotL); + return texelSize * offsetScale * nmlOffsetScale * normal; +} + +//-------------------------------------------------------------------------------------- +// Computes the visibility for a directional light using explicit position derivatives +//-------------------------------------------------------------------------------------- +float SunShadowVisibility(in float3 positionWS, in float3 positionNeighborX, in float3 positionNeighborY, + in float depthVS, in float3 shadowPosOffset, in float2 uvOffset, + in Texture2DArray sunShadowMap, in ShadowSampler shadowSampler, + in SunShadowConstants sunConstants) +{ + + // Figure out which cascade to sample from + uint cascadeIdx = 0; + + [unroll] + for(uint i = 0; i < NumCascades - 1; ++i) + { + [flatten] + if(depthVS > sunConstants.Base.CascadeSplits[i]) + cascadeIdx = i + 1; + } + + // Project into shadow space + float3 finalOffset = shadowPosOffset / abs(sunConstants.Base.CascadeScales[cascadeIdx].z); + float3 shadowPos = mul(float4(positionWS + finalOffset, 1.0f), sunConstants.Base.ShadowMatrix).xyz; + float3 shadowPosDX = mul(float4(positionNeighborX + finalOffset, 1.0f), sunConstants.Base.ShadowMatrix).xyz - shadowPos; + float3 shadowPosDY = mul(float4(positionNeighborY + finalOffset, 1.0f), sunConstants.Base.ShadowMatrix).xyz - shadowPos; + + shadowPos += sunConstants.Base.CascadeOffsets[cascadeIdx].xyz; + shadowPos *= sunConstants.Base.CascadeScales[cascadeIdx].xyz; + + shadowPosDX *= sunConstants.Base.CascadeScales[cascadeIdx].xyz; + shadowPosDY *= sunConstants.Base.CascadeScales[cascadeIdx].xyz; + + shadowPos.xy += uvOffset; + + #if ShadowMapMode_ == ShadowMapMode_DepthMap_ + return SampleShadowMapPCF(shadowPos, cascadeIdx, sunShadowMap, shadowSampler); + #elif ShadowMapMode_ == ShadowMapMode_EVSM_ + return SampleShadowMapEVSM(shadowPos, shadowPosDX, shadowPosDY, cascadeIdx, sunShadowMap, + shadowSampler, sunConstants.Extra, sunConstants.Base.CascadeScales[cascadeIdx].xyz); + #elif ShadowMapMode_ == ShadowMapMode_MSM_ + return SampleShadowMapMSM(shadowPos, shadowPosDX, shadowPosDY, cascadeIdx, sunShadowMap, + shadowSampler, sunConstants.Extra); + #endif +} + +//-------------------------------------------------------------------------------------- +// Computes the visibility for a directional light using implicit derivatives +//-------------------------------------------------------------------------------------- +float SunShadowVisibility(in float3 positionWS, in float depthVS, in float3 shadowPosOffset, in float2 uvOffset, + in Texture2DArray sunShadowMap, in ShadowSampler shadowSampler, + in SunShadowConstants sunConstants) +{ + // Figure out which cascade to sample from + uint cascadeIdx = 0; + + [unroll] + for(uint i = 0; i < NumCascades - 1; ++i) + { + [flatten] + if(depthVS > sunConstants.Base.CascadeSplits[i]) + cascadeIdx = i + 1; + } + + // Project into shadow space + float3 finalOffset = shadowPosOffset / abs(sunConstants.Base.CascadeScales[cascadeIdx].z); + float3 shadowPos = mul(float4(positionWS + finalOffset, 1.0f), sunConstants.Base.ShadowMatrix).xyz; + + shadowPos += sunConstants.Base.CascadeOffsets[cascadeIdx].xyz; + shadowPos *= sunConstants.Base.CascadeScales[cascadeIdx].xyz; + + shadowPos.xy += uvOffset; + + #if ShadowMapMode_ == ShadowMapMode_DepthMap_ + return SampleShadowMapPCF(shadowPos, cascadeIdx, sunShadowMap, shadowSampler); + #elif ShadowMapMode_ == ShadowMapMode_EVSM_ + return SampleShadowMapEVSM(shadowPos, cascadeIdx, sunShadowMap, shadowSampler, sunConstants.Extra, + sunConstants.Base.CascadeScales[cascadeIdx].xyz); + #elif ShadowMapMode_ == ShadowMapMode_MSM_ + return SampleShadowMapMSM(shadowPos, cascadeIdx, sunShadowMap, shadowSampler, sunConstants.Extra); + #endif +} + +//-------------------------------------------------------------------------------------- +// Computes the visibility for a spot light using implicit derivatives +//-------------------------------------------------------------------------------------- +float SpotLightShadowVisibility(in float3 positionWS, in float4x4 shadowMatrix, in uint shadowMapIdx, + in float3 shadowPosOffset, in Texture2DArray shadowMap, + in ShadowSampler shadowSampler, in float2 clipPlanes, + in ExtraShadowConstants extraConstants) +{ + #if ShadowMapMode_ == ShadowMapMode_DepthMap_ + const float3 posOffset = shadowPosOffset; + #else + const float3 posOffset = 0.0f; + #endif + + // Project into shadow space + float4 shadowPos = mul(float4(positionWS + posOffset, 1.0f), shadowMatrix); + shadowPos.xyz /= shadowPos.w; + + #if ShadowMapMode_ == ShadowMapMode_EVSM_ || ShadowMapMode_ == ShadowMapMode_MSM_ + shadowPos.z = (shadowPos.w - clipPlanes.x) / (clipPlanes.y - clipPlanes.x); + #endif + + #if ShadowMapMode_ == ShadowMapMode_DepthMap_ + return SampleShadowMapPCF(shadowPos.xyz, shadowMapIdx, shadowMap, shadowSampler); + #elif ShadowMapMode_ == ShadowMapMode_EVSM_ + return SampleShadowMapEVSM(shadowPos.xyz, shadowMapIdx, shadowMap, shadowSampler, extraConstants, 1.0f); + #elif ShadowMapMode_ == ShadowMapMode_MSM_ + return SampleShadowMapMSM(shadowPos.xyz, shadowMapIdx, shadowMap, shadowSampler, extraConstants); + #endif +} + +//-------------------------------------------------------------------------------------- +// Computes the visibility for a spot light using explicit position derivatives +//-------------------------------------------------------------------------------------- +float SpotLightShadowVisibility(in float3 positionWS, in float3 positionNeighborX, in float3 positionNeighborY, + in float4x4 shadowMatrix, in uint shadowMapIdx, in float3 shadowPosOffset, + in Texture2DArray shadowMap, in ShadowSampler shadowSampler, in float2 clipPlanes, + in ExtraShadowConstants extraConstants) +{ + #if ShadowMapMode_ == ShadowMapMode_DepthMap_ + const float3 posOffset = shadowPosOffset; + #else + const float3 posOffset = 0.0f; + #endif + + // Project into shadow space + float4 shadowPos = mul(float4(positionWS + posOffset, 1.0f), shadowMatrix); + shadowPos.xyz /= shadowPos.w; + + float4 shadowPosDX = mul(float4(positionNeighborX, 1.0f), shadowMatrix); + shadowPosDX.xyz /= shadowPosDX.w; + shadowPosDX.xyz -= shadowPos.xyz; + + float4 shadowPosDY = mul(float4(positionNeighborY, 1.0f), shadowMatrix); + shadowPosDY.xyz /= shadowPosDY.w; + shadowPosDY.xyz -= shadowPos.xyz; + + #if ShadowMapMode_ == ShadowMapMode_EVSM_ || ShadowMapMode_ == ShadowMapMode_MSM_ + shadowPos.z = (shadowPos.w - clipPlanes.x) / (clipPlanes.y - clipPlanes.x); + #endif + + #if ShadowMapMode_ == ShadowMapMode_DepthMap_ + return SampleShadowMapPCF(shadowPos.xyz, shadowMapIdx, shadowMap, shadowSampler); + #elif ShadowMapMode_ == ShadowMapMode_EVSM_ + return SampleShadowMapEVSM(shadowPos.xyz, shadowPosDX.xyz, shadowPosDY.xyz, shadowMapIdx, shadowMap, shadowSampler, extraConstants, 1.0f); + #elif ShadowMapMode_ == ShadowMapMode_MSM_ + return SampleShadowMapMSM(shadowPos.xyz, shadowPosDX.xyz, shadowPosDY.xyz, shadowMapIdx, shadowMap, shadowSampler, extraConstants); + #endif +} \ No newline at end of file diff --git a/SampleFramework12/v1.00/Shaders/Skybox.hlsl b/SampleFramework12/v1.01/Shaders/Skybox.hlsl similarity index 93% rename from SampleFramework12/v1.00/Shaders/Skybox.hlsl rename to SampleFramework12/v1.01/Shaders/Skybox.hlsl index b46e8d6..51828d1 100644 --- a/SampleFramework12/v1.00/Shaders/Skybox.hlsl +++ b/SampleFramework12/v1.01/Shaders/Skybox.hlsl @@ -8,6 +8,7 @@ //================================================================================================= #include +#include //================================================================================================= // Constant buffers @@ -25,6 +26,7 @@ struct PSConstants float CosSunAngularRadius; float3 SunColor; float3 Scale; + uint EnvMapIdx; }; ConstantBuffer VSCBuffer : register(b0); @@ -33,7 +35,6 @@ ConstantBuffer PSCBuffer : register(b0); //================================================================================================= // Samplers //================================================================================================= -TextureCube EnvironmentMap : register(t0); SamplerState LinearSampler : register(s0); //================================================================================================= @@ -77,7 +78,8 @@ VSOutput SkyboxVS(in VSInput input) float4 SkyboxPS(in VSOutput input) : SV_Target { // Sample the environment map - float3 color = EnvironmentMap.Sample(LinearSampler, normalize(input.TexCoord)).xyz; + TextureCube envMap = TexCubeTable[PSCBuffer.EnvMapIdx]; + float3 color = envMap.Sample(LinearSampler, normalize(input.TexCoord)).xyz; // Draw a circle for the sun float3 dir = normalize(input.TexCoord); diff --git a/SampleFramework12/v1.00/Shaders/Sprite.hlsl b/SampleFramework12/v1.01/Shaders/Sprite.hlsl similarity index 86% rename from SampleFramework12/v1.00/Shaders/Sprite.hlsl rename to SampleFramework12/v1.01/Shaders/Sprite.hlsl index 3455517..eb84ccb 100644 --- a/SampleFramework12/v1.00/Shaders/Sprite.hlsl +++ b/SampleFramework12/v1.01/Shaders/Sprite.hlsl @@ -7,6 +7,8 @@ // //================================================================================================= +#include + //================================================================================================= // Constant buffers //================================================================================================= @@ -17,6 +19,12 @@ cbuffer PerBatchCB : register(b0) bool LinearSampling; } +cbuffer SRVIndicesCB : register(b1) +{ + uint SpriteBufferIdx; + uint SpriteTextureIdx; +} + struct SpriteDrawData { float2 Position; @@ -29,8 +37,7 @@ struct SpriteDrawData //================================================================================================= // Resources //================================================================================================= -StructuredBuffer SpriteBuffer : register(t0); -Texture2D SpriteTexture : register(t1); +StructuredBuffer SpriteBuffers[] : register(t0, space100); SamplerState PointSampler : register(s0); SamplerState LinearSampler : register(s1); @@ -58,7 +65,8 @@ VSOutput SpriteVS(in uint VertexIdx : SV_VertexID, in uint InstanceIdx : SV_Inst else if(VertexIdx == 3) vtxPosition = float2(0.0f, 1.0f); - SpriteDrawData instanceData = SpriteBuffer[InstanceIdx]; + StructuredBuffer spriteBuffer = SpriteBuffers[SpriteBufferIdx]; + SpriteDrawData instanceData = spriteBuffer[InstanceIdx]; // Scale the quad so that it's texture-sized float2 positionSS = vtxPosition * instanceData.SourceRect.zw; @@ -94,11 +102,13 @@ VSOutput SpriteVS(in uint VertexIdx : SV_VertexID, in uint InstanceIdx : SV_Inst //================================================================================================= float4 SpritePS(in VSOutput input) : SV_Target { + Texture2D spriteTexture = Tex2DTable[SpriteTextureIdx]; + float4 texColor = 0.0f; if(LinearSampling) - texColor = SpriteTexture.Sample(LinearSampler, input.TexCoord); + texColor = spriteTexture.Sample(LinearSampler, input.TexCoord); else - texColor = SpriteTexture.Sample(PointSampler, input.TexCoord); + texColor = spriteTexture.Sample(PointSampler, input.TexCoord); texColor = texColor * input.Color; return texColor; } diff --git a/SampleFramework12/v1.00/Timer.cpp b/SampleFramework12/v1.01/Timer.cpp similarity index 100% rename from SampleFramework12/v1.00/Timer.cpp rename to SampleFramework12/v1.01/Timer.cpp diff --git a/SampleFramework12/v1.00/Timer.h b/SampleFramework12/v1.01/Timer.h similarity index 100% rename from SampleFramework12/v1.00/Timer.h rename to SampleFramework12/v1.01/Timer.h diff --git a/SampleFramework12/v1.00/TinyEXR.cpp b/SampleFramework12/v1.01/TinyEXR.cpp similarity index 100% rename from SampleFramework12/v1.00/TinyEXR.cpp rename to SampleFramework12/v1.01/TinyEXR.cpp diff --git a/SampleFramework12/v1.00/TinyEXR.h b/SampleFramework12/v1.01/TinyEXR.h similarity index 100% rename from SampleFramework12/v1.00/TinyEXR.h rename to SampleFramework12/v1.01/TinyEXR.h diff --git a/SampleFramework12/v1.01/Tools/Packager.exe b/SampleFramework12/v1.01/Tools/Packager.exe new file mode 100644 index 0000000..9bee4a9 Binary files /dev/null and b/SampleFramework12/v1.01/Tools/Packager.exe differ diff --git a/SampleFramework12/v1.01/Tools/Packager/App.config b/SampleFramework12/v1.01/Tools/Packager/App.config new file mode 100644 index 0000000..fbec4f3 --- /dev/null +++ b/SampleFramework12/v1.01/Tools/Packager/App.config @@ -0,0 +1,24 @@ + + + + +
+ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SampleFramework12/v1.01/Tools/Packager/MainFrm.Designer.cs b/SampleFramework12/v1.01/Tools/Packager/MainFrm.Designer.cs new file mode 100644 index 0000000..e2d9c82 --- /dev/null +++ b/SampleFramework12/v1.01/Tools/Packager/MainFrm.Designer.cs @@ -0,0 +1,287 @@ +namespace Packager +{ + partial class MainFrm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if(disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.packageButton = new System.Windows.Forms.Button(); + this.sourceTextBox = new System.Windows.Forms.TextBox(); + this.browseProjectButton = new System.Windows.Forms.Button(); + this.includeExeCB = new System.Windows.Forms.CheckBox(); + this.includeCodeCB = new System.Windows.Forms.CheckBox(); + this.includeShaderCacheCB = new System.Windows.Forms.CheckBox(); + this.outputTextBox = new System.Windows.Forms.TextBox(); + this.browseOutputButton = new System.Windows.Forms.Button(); + this.projectLabel = new System.Windows.Forms.Label(); + this.outputLabel = new System.Windows.Forms.Label(); + this.logListBox = new System.Windows.Forms.ListBox(); + this.createZipCB = new System.Windows.Forms.CheckBox(); + this.zipPathTextBox = new System.Windows.Forms.TextBox(); + this.browseZipButton = new System.Windows.Forms.Button(); + this.zipLabel = new System.Windows.Forms.Label(); + this.deleteOutputDirCB = new System.Windows.Forms.CheckBox(); + this.copyGitIgnoreCB = new System.Windows.Forms.CheckBox(); + this.SuspendLayout(); + // + // packageButton + // + this.packageButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.packageButton.Location = new System.Drawing.Point(406, 465); + this.packageButton.Name = "packageButton"; + this.packageButton.Size = new System.Drawing.Size(101, 31); + this.packageButton.TabIndex = 0; + this.packageButton.Text = "Package"; + this.packageButton.UseVisualStyleBackColor = true; + this.packageButton.Click += new System.EventHandler(this.packageButton_Click); + // + // sourceTextBox + // + this.sourceTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.sourceTextBox.Location = new System.Drawing.Point(59, 13); + this.sourceTextBox.Name = "sourceTextBox"; + this.sourceTextBox.Size = new System.Drawing.Size(403, 20); + this.sourceTextBox.TabIndex = 1; + // + // browseProjectButton + // + this.browseProjectButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.browseProjectButton.Location = new System.Drawing.Point(468, 11); + this.browseProjectButton.Name = "browseProjectButton"; + this.browseProjectButton.Size = new System.Drawing.Size(39, 23); + this.browseProjectButton.TabIndex = 2; + this.browseProjectButton.Text = "..."; + this.browseProjectButton.UseVisualStyleBackColor = true; + this.browseProjectButton.Click += new System.EventHandler(this.browseProjectButton_Click); + // + // includeExeCB + // + this.includeExeCB.AutoSize = true; + this.includeExeCB.Checked = true; + this.includeExeCB.CheckState = System.Windows.Forms.CheckState.Checked; + this.includeExeCB.Location = new System.Drawing.Point(12, 91); + this.includeExeCB.Name = "includeExeCB"; + this.includeExeCB.Size = new System.Drawing.Size(85, 17); + this.includeExeCB.TabIndex = 4; + this.includeExeCB.Text = "Include EXE"; + this.includeExeCB.UseVisualStyleBackColor = true; + // + // includeCodeCB + // + this.includeCodeCB.AutoSize = true; + this.includeCodeCB.Checked = true; + this.includeCodeCB.CheckState = System.Windows.Forms.CheckState.Checked; + this.includeCodeCB.Location = new System.Drawing.Point(13, 114); + this.includeCodeCB.Name = "includeCodeCB"; + this.includeCodeCB.Size = new System.Drawing.Size(89, 17); + this.includeCodeCB.TabIndex = 5; + this.includeCodeCB.Text = "Include Code"; + this.includeCodeCB.UseVisualStyleBackColor = true; + this.includeCodeCB.CheckedChanged += new System.EventHandler(this.includeCodeCB_CheckedChanged); + // + // includeShaderCacheCB + // + this.includeShaderCacheCB.AutoSize = true; + this.includeShaderCacheCB.Checked = true; + this.includeShaderCacheCB.CheckState = System.Windows.Forms.CheckState.Checked; + this.includeShaderCacheCB.Location = new System.Drawing.Point(103, 91); + this.includeShaderCacheCB.Name = "includeShaderCacheCB"; + this.includeShaderCacheCB.Size = new System.Drawing.Size(132, 17); + this.includeShaderCacheCB.TabIndex = 6; + this.includeShaderCacheCB.Text = "Include Shader Cache"; + this.includeShaderCacheCB.UseVisualStyleBackColor = true; + // + // outputTextBox + // + this.outputTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.outputTextBox.Location = new System.Drawing.Point(59, 39); + this.outputTextBox.Name = "outputTextBox"; + this.outputTextBox.Size = new System.Drawing.Size(403, 20); + this.outputTextBox.TabIndex = 7; + // + // browseOutputButton + // + this.browseOutputButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.browseOutputButton.Location = new System.Drawing.Point(468, 37); + this.browseOutputButton.Name = "browseOutputButton"; + this.browseOutputButton.Size = new System.Drawing.Size(39, 23); + this.browseOutputButton.TabIndex = 8; + this.browseOutputButton.Text = "..."; + this.browseOutputButton.UseVisualStyleBackColor = true; + this.browseOutputButton.Click += new System.EventHandler(this.browseOutputButton_Click); + // + // projectLabel + // + this.projectLabel.AutoSize = true; + this.projectLabel.Location = new System.Drawing.Point(13, 16); + this.projectLabel.Name = "projectLabel"; + this.projectLabel.Size = new System.Drawing.Size(40, 13); + this.projectLabel.TabIndex = 9; + this.projectLabel.Text = "Project"; + // + // outputLabel + // + this.outputLabel.AutoSize = true; + this.outputLabel.Location = new System.Drawing.Point(14, 42); + this.outputLabel.Name = "outputLabel"; + this.outputLabel.Size = new System.Drawing.Size(39, 13); + this.outputLabel.TabIndex = 10; + this.outputLabel.Text = "Output"; + // + // logListBox + // + this.logListBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.logListBox.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.logListBox.FormattingEnabled = true; + this.logListBox.ItemHeight = 14; + this.logListBox.Location = new System.Drawing.Point(12, 137); + this.logListBox.Name = "logListBox"; + this.logListBox.Size = new System.Drawing.Size(494, 312); + this.logListBox.TabIndex = 11; + // + // createZipCB + // + this.createZipCB.AutoSize = true; + this.createZipCB.Checked = true; + this.createZipCB.CheckState = System.Windows.Forms.CheckState.Checked; + this.createZipCB.Location = new System.Drawing.Point(103, 114); + this.createZipCB.Name = "createZipCB"; + this.createZipCB.Size = new System.Drawing.Size(96, 17); + this.createZipCB.TabIndex = 12; + this.createZipCB.Text = "Create ZIP File"; + this.createZipCB.UseVisualStyleBackColor = true; + this.createZipCB.CheckedChanged += new System.EventHandler(this.createZipCB_CheckedChanged); + // + // zipPathTextBox + // + this.zipPathTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.zipPathTextBox.Location = new System.Drawing.Point(59, 65); + this.zipPathTextBox.Name = "zipPathTextBox"; + this.zipPathTextBox.Size = new System.Drawing.Size(403, 20); + this.zipPathTextBox.TabIndex = 13; + // + // browseZipButton + // + this.browseZipButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.browseZipButton.Location = new System.Drawing.Point(468, 63); + this.browseZipButton.Name = "browseZipButton"; + this.browseZipButton.Size = new System.Drawing.Size(39, 23); + this.browseZipButton.TabIndex = 14; + this.browseZipButton.Text = "..."; + this.browseZipButton.UseVisualStyleBackColor = true; + this.browseZipButton.Click += new System.EventHandler(this.browseZipButton_Click); + // + // zipLabel + // + this.zipLabel.AutoSize = true; + this.zipLabel.Location = new System.Drawing.Point(25, 67); + this.zipLabel.Name = "zipLabel"; + this.zipLabel.Size = new System.Drawing.Size(24, 13); + this.zipLabel.TabIndex = 15; + this.zipLabel.Text = "ZIP"; + // + // deleteOutputDirCB + // + this.deleteOutputDirCB.AutoSize = true; + this.deleteOutputDirCB.Checked = true; + this.deleteOutputDirCB.CheckState = System.Windows.Forms.CheckState.Checked; + this.deleteOutputDirCB.Location = new System.Drawing.Point(241, 91); + this.deleteOutputDirCB.Name = "deleteOutputDirCB"; + this.deleteOutputDirCB.Size = new System.Drawing.Size(137, 17); + this.deleteOutputDirCB.TabIndex = 16; + this.deleteOutputDirCB.Text = "Delete Output Directory"; + this.deleteOutputDirCB.UseVisualStyleBackColor = true; + // + // copyGitIgnoreCB + // + this.copyGitIgnoreCB.AutoSize = true; + this.copyGitIgnoreCB.Checked = true; + this.copyGitIgnoreCB.CheckState = System.Windows.Forms.CheckState.Checked; + this.copyGitIgnoreCB.Location = new System.Drawing.Point(241, 114); + this.copyGitIgnoreCB.Name = "copyGitIgnoreCB"; + this.copyGitIgnoreCB.Size = new System.Drawing.Size(120, 17); + this.copyGitIgnoreCB.TabIndex = 17; + this.copyGitIgnoreCB.Text = "Copy .gitignore Files"; + this.copyGitIgnoreCB.UseVisualStyleBackColor = true; + // + // MainFrm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(519, 508); + this.Controls.Add(this.copyGitIgnoreCB); + this.Controls.Add(this.deleteOutputDirCB); + this.Controls.Add(this.zipLabel); + this.Controls.Add(this.browseZipButton); + this.Controls.Add(this.zipPathTextBox); + this.Controls.Add(this.createZipCB); + this.Controls.Add(this.logListBox); + this.Controls.Add(this.outputLabel); + this.Controls.Add(this.projectLabel); + this.Controls.Add(this.browseOutputButton); + this.Controls.Add(this.outputTextBox); + this.Controls.Add(this.includeShaderCacheCB); + this.Controls.Add(this.includeCodeCB); + this.Controls.Add(this.includeExeCB); + this.Controls.Add(this.browseProjectButton); + this.Controls.Add(this.sourceTextBox); + this.Controls.Add(this.packageButton); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "MainFrm"; + this.Text = "Packager"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button packageButton; + private System.Windows.Forms.TextBox sourceTextBox; + private System.Windows.Forms.Button browseProjectButton; + private System.Windows.Forms.CheckBox includeExeCB; + private System.Windows.Forms.CheckBox includeCodeCB; + private System.Windows.Forms.CheckBox includeShaderCacheCB; + private System.Windows.Forms.TextBox outputTextBox; + private System.Windows.Forms.Button browseOutputButton; + private System.Windows.Forms.Label projectLabel; + private System.Windows.Forms.Label outputLabel; + private System.Windows.Forms.ListBox logListBox; + private System.Windows.Forms.CheckBox createZipCB; + private System.Windows.Forms.TextBox zipPathTextBox; + private System.Windows.Forms.Button browseZipButton; + private System.Windows.Forms.Label zipLabel; + private System.Windows.Forms.CheckBox deleteOutputDirCB; + private System.Windows.Forms.CheckBox copyGitIgnoreCB; + } +} + diff --git a/SampleFramework12/v1.01/Tools/Packager/MainFrm.cs b/SampleFramework12/v1.01/Tools/Packager/MainFrm.cs new file mode 100644 index 0000000..511c045 --- /dev/null +++ b/SampleFramework12/v1.01/Tools/Packager/MainFrm.cs @@ -0,0 +1,594 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.IO; +using System.IO.Compression; +using System.Diagnostics; + +namespace Packager +{ + public partial class MainFrm : Form + { + private class Manifest + { + public List References = new List(); + public List Local = new List(); + public List External = new List(); + public List Content = new List(); + public List Code = new List(); + } + + private struct CopyItem : IEquatable + { + public string Source; + public string Destination; + + public bool Equals(CopyItem otherItem) + { + return Source == otherItem.Source && Destination == otherItem.Destination; + } + } + + enum ManifestCategory + { + Local, + Externals, + Content, + References, + Code, + + None + } + + public MainFrm() + { + InitializeComponent(); + + sourceTextBox.Text = Properties.Settings.Default.CurrentProject; + outputTextBox.Text = Properties.Settings.Default.CurrentOutput; + zipPathTextBox.Text = Properties.Settings.Default.CurrentZIP; + } + + private void SaveSettings() + { + Properties.Settings.Default.CurrentProject = sourceTextBox.Text; + Properties.Settings.Default.CurrentOutput = outputTextBox.Text; + Properties.Settings.Default.CurrentZIP = zipPathTextBox.Text; + Properties.Settings.Default.Save(); + } + + private void ClearLog() + { + logListBox.Items.Clear(); + } + + private void WriteLog(string log) + { + logListBox.Items.Add(log); + logListBox.Refresh(); + } + + private Manifest ParseManifestFile(string filePath) + { + Manifest manifest = new Manifest(); + string[] lines = File.ReadAllLines(filePath); + ManifestCategory category = ManifestCategory.None; + for(int lineNum = 1; lineNum <= lines.Length; ++lineNum) + { + string line = lines[lineNum - 1]; + + if(line.Length == 0) + continue; + + if(line.StartsWith("#")) + continue; + + if(line.StartsWith("[Content]")) + { + category = ManifestCategory.Content; + continue; + } + + if(line.StartsWith("[Externals]")) + { + category = ManifestCategory.Externals; + continue; + } + + if(line.StartsWith("[Local]")) + { + category = ManifestCategory.Local; + continue; + } + + if(line.StartsWith("[References]")) + { + category = ManifestCategory.References; + continue; + } + + if(line.StartsWith("[Code]")) + { + category = ManifestCategory.Code; + continue; + } + + if(line.StartsWith("[")) + { + WriteLog(string.Format("Unrecognized tag '{0}' on line {1}", line, lineNum)); + continue; + } + + if(category == ManifestCategory.Local) + manifest.Local.Add(line); + else if(category == ManifestCategory.Content) + manifest.Content.Add(line); + else if(category == ManifestCategory.Externals) + manifest.External.Add(line); + else if(category == ManifestCategory.References) + manifest.References.Add(line); + else if(category == ManifestCategory.Code) + manifest.Code.Add(line); + } + + return manifest; + } + + private void GenerateCopyItems(string sourceDir, string sourceRootDir, string outputRootDir, + string filter, List copyItems) + { + Debug.Assert(sourceDir.StartsWith(sourceRootDir)); + int rootDirLen = sourceRootDir.Length; + string outputDir = outputRootDir; + if(sourceDir.Length > rootDirLen) + { + Debug.Assert(sourceDir.ToCharArray()[rootDirLen] == '\\'); + string relativeDir = sourceDir.Substring(rootDirLen + 1); + outputDir = Path.Combine(outputRootDir, relativeDir); + } + + string[] filePaths = Directory.GetFiles(sourceDir, filter, SearchOption.TopDirectoryOnly); + foreach(string filePath in filePaths) + { + CopyItem copyItem = new CopyItem(); + copyItem.Source = filePath; + copyItem.Destination = Path.Combine(outputDir, Path.GetFileName(filePath)); + if(copyItems.Contains(copyItem) == false) + copyItems.Add(copyItem); + } + } + + private void RemoveCopyItems(string sourceDir, string filter, List copyItems) + { + string[] filePaths = Directory.GetFiles(sourceDir, filter, SearchOption.TopDirectoryOnly); + foreach(string filePath in filePaths) + { + int numItems = copyItems.Count; + for(int i = numItems - 1; i >= 0; --i) + { + if(copyItems[i].Source == filePath) + copyItems.RemoveAt(i); + } + } + } + + private void ExecuteCopyItems(List copyItems) + { + foreach(CopyItem copyItem in copyItems) + { + string destinationDir = Path.GetDirectoryName(copyItem.Destination); + if(Directory.Exists(destinationDir) == false) + Directory.CreateDirectory(destinationDir); + File.Copy(copyItem.Source, copyItem.Destination); + } + } + + private void ProcessManifestItem(string sourceDir, string sourceRootDir, string outputRootDir, + string manifestItem, List copyItems) + { + bool include = true; + if(manifestItem.StartsWith("|")) + { + manifestItem = manifestItem.TrimStart("|".ToCharArray()); + include = false; + } + + if(manifestItem.EndsWith("\\")) + { + // It's a directory, recursively process all of its files and nested directories + string manifestDir = manifestItem.TrimEnd("\\".ToCharArray()); + manifestDir = Path.Combine(sourceDir, manifestDir); + if(include) + GenerateCopyItems(manifestDir, sourceRootDir, outputRootDir, "*.*", copyItems); + else + RemoveCopyItems(manifestDir, "*.*", copyItems); + + string[] subDirs = Directory.GetDirectories(manifestDir, "*", SearchOption.AllDirectories); + foreach(string subDir in subDirs) + { + if(include) + GenerateCopyItems(subDir, sourceRootDir, outputRootDir, "*.*", copyItems); + else + RemoveCopyItems(subDir, "*.*", copyItems); + } + } + else + { + // It's a file or file filter pattern + string manifestPath = Path.Combine(sourceDir, manifestItem); + string manifestDir = Path.GetDirectoryName(manifestPath); + string manifestFilter = Path.GetFileName(manifestPath); + + if(include) + GenerateCopyItems(manifestDir, sourceRootDir, outputRootDir, manifestFilter, copyItems); + else + RemoveCopyItems(manifestDir, manifestFilter, copyItems); + } + } + + private void ProcessProjectManifest(string sourceRootDir, string outputRootDir, string projectName, bool referenced, List copyItems) + { + string sourceProjectDir = Path.Combine(sourceRootDir, projectName); + string sourceContentDir = Path.Combine(sourceRootDir, "Content"); + string sourceExternalsDir = Path.Combine(sourceRootDir, "Externals"); + string sourceFrameworkDir = Path.Combine(sourceRootDir, "SampleFramework12"); + + string outputProjectDir = Path.Combine(outputRootDir, projectName); + string outputContentDir = Path.Combine(outputRootDir, "Content"); + string outputExternalsDir = Path.Combine(outputRootDir, "Externals"); + string outputFrameworkDir = Path.Combine(outputRootDir, "SampleFramework12"); + + string projectManifestPath = Path.Combine(sourceProjectDir, "Manifest.txt"); + if(File.Exists(projectManifestPath) == false) + { + WriteLog("No manifest file found in source directory, aborting"); + return; + } + + WriteLog("Parsing project manifest file"); + Manifest projectManifest = ParseManifestFile(projectManifestPath); + + List codeFiles = new List() { "*.h", "*.cpp", "*.cs", "*.vcxproj", "*.vcxproj.filters", + "*.sln", "*.ico", "*.rc", "*.sublime-project", "*.csproj", + "*.resx", "*.props", "*.config", "*.natvis" }; + + List shaderFiles = new List() { "*.hlsl" }; + + if(includeCodeCB.Checked) + { + WriteLog("Gathering code files"); + + if(copyGitIgnoreCB.Checked) + codeFiles.Add(".gitignore"); + + foreach(string filter in codeFiles) + GenerateCopyItems(sourceProjectDir, sourceRootDir, outputRootDir, filter, copyItems); + + foreach(string manifestItem in projectManifest.Code) + ProcessManifestItem(sourceProjectDir, sourceRootDir, outputRootDir, manifestItem, copyItems); + + if(copyGitIgnoreCB.Checked && referenced == false) + { + CopyItem gitIgnoreItem = new CopyItem(); + gitIgnoreItem.Source = Path.Combine(sourceProjectDir, @"..\.gitignore"); + gitIgnoreItem.Destination = Path.Combine(outputRootDir, @".gitignore"); + copyItems.Add(gitIgnoreItem); + } + + WriteLog("Gathering external files"); + + foreach(string manifestItem in projectManifest.External) + ProcessManifestItem(sourceExternalsDir, sourceRootDir, outputRootDir, manifestItem, copyItems); + } + + WriteLog("Gathering shader files"); + + foreach(string filter in shaderFiles) + GenerateCopyItems(sourceProjectDir, sourceRootDir, outputRootDir, filter, copyItems); + + if(includeExeCB.Checked && referenced == false) + { + string exeDir = Path.Combine(sourceProjectDir, "x64", "Release"); + string exeName = projectName + ".exe"; + string exePath = Path.Combine(exeDir, exeName); + if(File.Exists(exePath)) + { + WriteLog("Gathering executable files"); + + CopyItem exeItem = new CopyItem(); + exeItem.Source = exePath; + exeItem.Destination = Path.Combine(outputProjectDir, exeName); + copyItems.Add(exeItem); + + // Also copy external DLL;s + string[] dllPaths = Directory.GetFiles(exeDir, "*.dll", SearchOption.TopDirectoryOnly); + foreach(string dllPath in dllPaths) + { + string dllName = Path.GetFileName(dllPath); + + CopyItem dllItem = new CopyItem(); + dllItem.Source = dllPath; + dllItem.Destination = Path.Combine(outputProjectDir, dllName); + copyItems.Add(dllItem); + } + + GenerateCopyItems(sourceProjectDir, sourceRootDir, outputRootDir, "*.dll", copyItems); + } + else + { + WriteLog("No executable detected! Skipping."); + } + } + + if(includeShaderCacheCB.Checked && referenced == false) + { + string cacheDir = Path.Combine(sourceProjectDir, "ShaderCache", "Release"); + if(Directory.Exists(cacheDir)) + { + WriteLog("Gathering shader cache files"); + GenerateCopyItems(cacheDir, sourceRootDir, outputRootDir, "*.cache", copyItems); + } + else + { + WriteLog("No shader cache directory found, skipping."); + } + } + + foreach(string manifestItem in projectManifest.Local) + ProcessManifestItem(sourceProjectDir, sourceRootDir, outputRootDir, manifestItem, copyItems); + + WriteLog("Gathering content files"); + + foreach(string manifestItem in projectManifest.Content) + ProcessManifestItem(sourceContentDir, sourceRootDir, outputRootDir, manifestItem, copyItems); + + if(copyGitIgnoreCB.Checked && includeCodeCB.Checked && referenced == false) + { + CopyItem contentIgnore; + contentIgnore.Source = Path.Combine(sourceContentDir, @".gitignore"); + contentIgnore.Destination = Path.Combine(outputContentDir, @".gitignore"); + copyItems.Add(contentIgnore); + + CopyItem externalsIgnore; + externalsIgnore.Source = Path.Combine(sourceExternalsDir, @".gitignore"); + externalsIgnore.Destination = Path.Combine(outputExternalsDir, @".gitignore"); + copyItems.Add(externalsIgnore); + } + + foreach(string reference in projectManifest.References) + { + WriteLog(string.Format("Processing referenced project '{0}'", reference)); + string referenceDir = Path.Combine(sourceRootDir, reference); + if(Directory.Exists(referenceDir) == false) + { + WriteLog(string.Format("Referenced project directory '{0}' doesn't exist, or isn't a directory. Skipping.", referenceDir)); + continue; + } + + ProcessProjectManifest(sourceRootDir, outputRootDir, reference, true, copyItems); + } + } + + private void Package() + { + ClearLog(); + + if(includeCodeCB.Checked == false && includeExeCB.Checked == false) + { + WriteLog("Need to include either code and/or the executable in order to package, aborting."); + return; + } + + string invalidChars = new string(Path.GetInvalidPathChars()); + + string sourceProjectDir = sourceTextBox.Text; + if(sourceProjectDir.Contains(invalidChars)) + { + WriteLog("Invalid path characters in the specified source project path"); + return; + } + + while(sourceProjectDir.EndsWith("\\") || sourceProjectDir.EndsWith("/")) + sourceProjectDir = sourceProjectDir.Substring(0, sourceProjectDir.Length - 1); + + if(File.Exists(sourceProjectDir) || Path.HasExtension(sourceProjectDir)) + { + WriteLog("The source project path must be a directory, not a file"); + return; + } + + if(Directory.Exists(sourceProjectDir) == false) + { + WriteLog(string.Format("Source project directory '{0}' does not exist! Aborting.", sourceProjectDir)); + return; + } + + if(outputTextBox.Text.Length == 0) + { + WriteLog("No output directory specified! Aborting."); + return; + } + + string sourceRootDir = Path.GetDirectoryName(sourceProjectDir); + string sourceContentDir = Path.Combine(sourceRootDir, "Content"); + string sourceExternalsDir = Path.Combine(sourceRootDir, "Externals"); + string sourceFrameworkDir = Path.Combine(sourceRootDir, "SampleFramework12"); + if(Directory.Exists(sourceContentDir) == false) + { + WriteLog("Source content directory not found! Aborting."); + return; + } + + if(Directory.Exists(sourceExternalsDir) == false) + { + WriteLog("Source externals directory not found! Aborting."); + return; + } + + if(Directory.Exists(sourceFrameworkDir) == false) + { + WriteLog("Source framework directory not found! Aborting."); + return; + } + + string projectName = sourceProjectDir.Substring(sourceRootDir.Length + 1); + + string outputRootDir = outputTextBox.Text; + if(outputRootDir.Contains(invalidChars)) + { + WriteLog("Invalid path characters in the specified output path"); + return; + } + + while(outputRootDir.EndsWith("\\") || outputRootDir.EndsWith("/")) + outputRootDir = outputRootDir.Substring(0, outputRootDir.Length - 1); + + if(File.Exists(outputRootDir) || Path.HasExtension(outputRootDir)) + { + WriteLog("The output path must be a directory, not a file"); + return; + } + + if(createZipCB.Checked) + { + string outputZipPath = zipPathTextBox.Text; + if(outputZipPath.Length == 0) + { + WriteLog("No output zip file path specified! Aborting."); + return; + } + + if(File.Exists(outputZipPath)) + { + string msg = string.Format("Output ZIP file '{0}' already exists! Overwrite?", outputZipPath); + if(MessageBox.Show(this, msg, "Packager", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) + { + WriteLog("Packaging Canceled."); + return; + } + } + } + + if(Directory.Exists(outputRootDir)) + { + int numFiles = Directory.GetFiles(outputRootDir).Length; + int numDirs = Directory.GetDirectories(outputRootDir).Length; + if(numFiles > 0 || numDirs > 0) + { + string msg = string.Format("Output directory '{0}' already exists, continuing will delete all of its contents. Continue?", outputRootDir); + if(MessageBox.Show(this, msg, "Packager", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) + { + WriteLog("Packaging canceled."); + return; + } + + WriteLog(string.Format("Deleting output directory '{0}'", outputRootDir)); + Directory.Delete(outputRootDir, true); + } + } + + if(Directory.Exists(outputRootDir) == false) + { + WriteLog(string.Format("Creating output directory '{0}'", outputRootDir)); + Directory.CreateDirectory(outputRootDir); + } + + List copyItems = new List(); + ProcessProjectManifest(sourceRootDir, outputRootDir, projectName, false, copyItems); + + WriteLog("Copying files"); + + ExecuteCopyItems(copyItems); + + if(createZipCB.Checked) + { + string outputZipPath = zipPathTextBox.Text; + if(File.Exists(outputZipPath)) + File.Delete(outputZipPath); + + WriteLog("Creating ZIP archive"); + ZipFile.CreateFromDirectory(outputRootDir, outputZipPath, CompressionLevel.Optimal, false); + + if(deleteOutputDirCB.Checked) + { + WriteLog("Deleting output directory"); + Directory.Delete(outputRootDir, true); + } + } + + WriteLog("Packaging complete!"); + } + + private void browseProjectButton_Click(object sender, EventArgs e) + { + FolderBrowserDialog dlg = new FolderBrowserDialog(); + dlg.Description = "Choose Source Project Folder"; + dlg.SelectedPath = sourceTextBox.Text; + dlg.ShowNewFolderButton = false; + if(dlg.ShowDialog(this) == DialogResult.OK) + { + sourceTextBox.Text = dlg.SelectedPath; + SaveSettings(); + } + } + + private void browseOutputButton_Click(object sender, EventArgs e) + { + FolderBrowserDialog dlg = new FolderBrowserDialog(); + dlg.Description = "Choose Output Folder"; + dlg.SelectedPath = outputTextBox.Text; + dlg.ShowNewFolderButton = true; + if(dlg.ShowDialog(this) == DialogResult.OK) + { + outputTextBox.Text = dlg.SelectedPath; + SaveSettings(); + } + } + + private void browseZipButton_Click(object sender, EventArgs e) + { + SaveFileDialog dlg = new SaveFileDialog(); + dlg.AddExtension = true; + dlg.AutoUpgradeEnabled = true; + dlg.DefaultExt = "zip"; + dlg.Filter = "Zip files (*.zip)|*.zip|All files (*.*)|*.*"; + dlg.FilterIndex = 1; + if(zipPathTextBox.Text.Length > 0) + dlg.InitialDirectory = Path.GetDirectoryName(zipPathTextBox.Text); + dlg.OverwritePrompt = true; + dlg.SupportMultiDottedExtensions = true; + dlg.Title = "Choose ZIP File Location..."; + if(dlg.ShowDialog(this) == DialogResult.OK) + { + zipPathTextBox.Text = dlg.FileName; + SaveSettings(); + } + } + + private void packageButton_Click(object sender, EventArgs e) + { + SaveSettings(); + Package(); + } + + private void createZipCB_CheckedChanged(object sender, EventArgs e) + { + bool enabled = createZipCB.Checked; + deleteOutputDirCB.Enabled = enabled; + browseZipButton.Enabled = enabled; + zipPathTextBox.Enabled = enabled; + } + + private void includeCodeCB_CheckedChanged(object sender, EventArgs e) + { + bool enabled = includeCodeCB.Checked; + copyGitIgnoreCB.Enabled = enabled; + } + } +} diff --git a/SampleFramework12/v1.01/Tools/Packager/MainFrm.resx b/SampleFramework12/v1.01/Tools/Packager/MainFrm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SampleFramework12/v1.01/Tools/Packager/MainFrm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SampleFramework12/v1.01/Tools/Packager/Packager.csproj b/SampleFramework12/v1.01/Tools/Packager/Packager.csproj new file mode 100644 index 0000000..cf18dd3 --- /dev/null +++ b/SampleFramework12/v1.01/Tools/Packager/Packager.csproj @@ -0,0 +1,89 @@ + + + + + Debug + AnyCPU + {C90AF2A3-8AD5-4057-93E9-44810F6470B4} + WinExe + Properties + Packager + Packager + v4.5 + 512 + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Form + + + MainFrm.cs + + + + + MainFrm.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + \ No newline at end of file diff --git a/SampleFramework12/v1.01/Tools/Packager/Packager.sln b/SampleFramework12/v1.01/Tools/Packager/Packager.sln new file mode 100644 index 0000000..54edeb9 --- /dev/null +++ b/SampleFramework12/v1.01/Tools/Packager/Packager.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.31101.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Packager", "Packager.csproj", "{C90AF2A3-8AD5-4057-93E9-44810F6470B4}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C90AF2A3-8AD5-4057-93E9-44810F6470B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C90AF2A3-8AD5-4057-93E9-44810F6470B4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C90AF2A3-8AD5-4057-93E9-44810F6470B4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C90AF2A3-8AD5-4057-93E9-44810F6470B4}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/SampleFramework12/v1.01/Tools/Packager/Program.cs b/SampleFramework12/v1.01/Tools/Packager/Program.cs new file mode 100644 index 0000000..59b1712 --- /dev/null +++ b/SampleFramework12/v1.01/Tools/Packager/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Packager +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MainFrm()); + } + } +} diff --git a/SampleFramework12/v1.01/Tools/Packager/Properties/AssemblyInfo.cs b/SampleFramework12/v1.01/Tools/Packager/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..59991c6 --- /dev/null +++ b/SampleFramework12/v1.01/Tools/Packager/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Packager")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Packager")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("19f9cd55-7425-4706-899d-ce34c4592123")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SampleFramework12/v1.01/Tools/Packager/Properties/Resources.Designer.cs b/SampleFramework12/v1.01/Tools/Packager/Properties/Resources.Designer.cs new file mode 100644 index 0000000..a9b6de6 --- /dev/null +++ b/SampleFramework12/v1.01/Tools/Packager/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.18444 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Packager.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Packager.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/SampleFramework12/v1.01/Tools/Packager/Properties/Resources.resx b/SampleFramework12/v1.01/Tools/Packager/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/SampleFramework12/v1.01/Tools/Packager/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SampleFramework12/v1.01/Tools/Packager/Properties/Settings.Designer.cs b/SampleFramework12/v1.01/Tools/Packager/Properties/Settings.Designer.cs new file mode 100644 index 0000000..c7a6e96 --- /dev/null +++ b/SampleFramework12/v1.01/Tools/Packager/Properties/Settings.Designer.cs @@ -0,0 +1,62 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.18444 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Packager.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string CurrentProject { + get { + return ((string)(this["CurrentProject"])); + } + set { + this["CurrentProject"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string CurrentOutput { + get { + return ((string)(this["CurrentOutput"])); + } + set { + this["CurrentOutput"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string CurrentZIP { + get { + return ((string)(this["CurrentZIP"])); + } + set { + this["CurrentZIP"] = value; + } + } + } +} diff --git a/SampleFramework12/v1.01/Tools/Packager/Properties/Settings.settings b/SampleFramework12/v1.01/Tools/Packager/Properties/Settings.settings new file mode 100644 index 0000000..bb81669 --- /dev/null +++ b/SampleFramework12/v1.01/Tools/Packager/Properties/Settings.settings @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SampleFramework12/v1.00/Utility.cpp b/SampleFramework12/v1.01/Utility.cpp similarity index 96% rename from SampleFramework12/v1.00/Utility.cpp rename to SampleFramework12/v1.01/Utility.cpp index 21040da..29fbe75 100644 --- a/SampleFramework12/v1.00/Utility.cpp +++ b/SampleFramework12/v1.01/Utility.cpp @@ -26,6 +26,7 @@ void WriteLog(const wchar* format, ...) GlobalApp->AddToLog(WStringToAnsi(buffer).c_str()); OutputDebugStringW(buffer); + OutputDebugStringW(L"\n"); } void WriteLog(const char* format, ...) @@ -38,6 +39,7 @@ void WriteLog(const char* format, ...) GlobalApp->AddToLog(buffer); OutputDebugStringA(buffer); + OutputDebugStringA("\n"); } std::wstring MakeString(const wchar* format, ...) diff --git a/SampleFramework12/v1.00/Utility.h b/SampleFramework12/v1.01/Utility.h similarity index 77% rename from SampleFramework12/v1.00/Utility.h rename to SampleFramework12/v1.01/Utility.h index b38df04..d6160b5 100644 --- a/SampleFramework12/v1.00/Utility.h +++ b/SampleFramework12/v1.01/Utility.h @@ -43,7 +43,7 @@ inline void Split(const std::wstring& str, std::vector& parts, con // Find first "non-delimiter" std::wstring::size_type pos = str.find_first_of(delimiters, lastPos); - while (std::wstring::npos != pos || std::wstring::npos != lastPos) + while(std::wstring::npos != pos || std::wstring::npos != lastPos) { // Found a token, add it to the vector parts.push_back(str.substr(lastPos, pos - lastPos)); @@ -64,6 +64,36 @@ inline std::vector Split(const std::wstring& str, const std::wstri return parts; } +// Splits up a string using a delimiter +inline void Split(const std::string& str, std::vector& parts, const std::string& delimiters = " ") +{ + // Skip delimiters at beginning + std::string::size_type lastPos = str.find_first_not_of(delimiters, 0); + + // Find first "non-delimiter" + std::string::size_type pos = str.find_first_of(delimiters, lastPos); + + while(std::string::npos != pos || std::string::npos != lastPos) + { + // Found a token, add it to the vector + parts.push_back(str.substr(lastPos, pos - lastPos)); + + // Skip delimiters. Note the "not_of" + lastPos = str.find_first_not_of(delimiters, pos); + + // Find next "non-delimiter" + pos = str.find_first_of(delimiters, lastPos); + } +} + +// Splits up a string using a delimiter +inline std::vector Split(const std::string& str, const std::string& delimiters = " ") +{ + std::vector parts; + Split(str, parts, delimiters); + return parts; +} + // Parses a string into a number template inline T Parse(const std::wstring& str) { diff --git a/SampleFramework12/v1.00/Window.cpp b/SampleFramework12/v1.01/Window.cpp similarity index 100% rename from SampleFramework12/v1.00/Window.cpp rename to SampleFramework12/v1.01/Window.cpp diff --git a/SampleFramework12/v1.00/Window.h b/SampleFramework12/v1.01/Window.h similarity index 100% rename from SampleFramework12/v1.00/Window.h rename to SampleFramework12/v1.01/Window.h diff --git a/SampleFramework12/v1.00/sf12.natvis b/SampleFramework12/v1.01/sf12.natvis similarity index 100% rename from SampleFramework12/v1.00/sf12.natvis rename to SampleFramework12/v1.01/sf12.natvis