Prepare initial release
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..d01ec3a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+build/

+docs/html/

diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..65a9473
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,3 @@
+# 1.0.0</b> (2019-07-23)

+

+First published version.

diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000..abf6d9e
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,19 @@
+Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.
+
+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/NOTICES.txt b/NOTICES.txt
new file mode 100644
index 0000000..7b28535
--- /dev/null
+++ b/NOTICES.txt
@@ -0,0 +1,82 @@
+Notices and licenses file

+_________________________

+

+AMD copyrighted code (MIT) 

+Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved. 

+

+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.

+

+

+Dependecnies on microsoft-directx-graphics-samples v-u (MIT) 

+

+Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved. 

+Copyright (c) Microsoft. All rights reserved.

+

+This code is licensed under the MIT License (MIT).

+THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF

+ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY

+IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR

+PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

+

+

+gpuopen-librariesandsdks-vulkanmemoryallocator v-u (MIT) 

+Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved. 

+

+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.

+

+

+premake-premake-core v-u (BSD3) 

+Copyright (c) 2003-2016 Jason Perkins and individual contributors.

+All rights reserved.

+

+Redistribution and use in source and binary forms, with or without modification,

+are permitted provided that the following conditions are met:

+

+  1. Redistributions of source code must retain the above copyright notice,

+     this list of conditions and the following disclaimer.

+

+  2. Redistributions in binary form must reproduce the above copyright notice,

+     this list of conditions and the following disclaimer in the documentation

+     and/or other materials provided with the distribution.

+

+  3. Neither the name of Premake nor the names of its contributors may be

+     used to endorse or promote products derived from this software without

+     specific prior written permission.

+

+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND

+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED

+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE

+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE

+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL

+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR

+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER

+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,

+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE

+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/README.md b/README.md
index e5fabb4..0d4f810 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,106 @@
-# Direct3D 12 Memory Allocator
+# D3D12 Memory Allocator
 
-Easy to integrate Direct3D 12 memory allocation library
\ No newline at end of file
+Easy to integrate memory allocation library for Direct3D 12.
+
+**License:** MIT. See [LICENSE.txt](LICENSE.txt)
+
+**Changelog:** See [CHANGELOG.md](CHANGELOG.md)
+
+**Product page:** [Vulkan Memory Allocator on GPUOpen](https://gpuopen.com/gaming-product/D3D12MemoryAllocator/) (TODO)
+
+**Build status:**
+
+TODO
+
+# Problem
+
+Memory allocation and resource (buffer and texture) creation in new, explicit graphics APIs (Vulkan and Direct3D 12) is difficult comparing to older graphics APIs like Direct3D 11 or OpenGL because it is recommended to allocate bigger blocks of memory and assign parts of them to resources. [Vulkan Memory Allocator](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator/) is a library that implements this functionality for Vulkan. It is available online since 2017 and it is successfully used in many software projects, including some AAA game studios. This is an equivalent library for D3D12.
+
+# Features
+
+This library can help developers to manage memory allocations and resource creation by offering function `Allocator::CreateResource` similar to the standard `ID3D12Device::CreateCommittedResource`. It internally:
+
+- Allocates and keeps track of bigger memory heaps, used and unused ranges inside them, finds best matching unused ranges to create new resources there as placed resources.
+- Automatically respects aligment requirements for created resources.
+- Automatically handles resource heap tier - whether it's `D3D12_RESOURCE_HEAP_TIER_1` that requires to keep certain classes of resources separate or `D3D12_RESOURCE_HEAP_TIER_2` that allows to keep them all together.
+
+Additional features:
+
+- Well-documented - description of all classes and functions provided, along with chapters that contain general description and example code.
+- Thread-safety: Library is designed to be used in multithreaded code.
+- Configuration: Fill optional members of `ALLOCATOR_DESC` structure to provide custom CPU memory allocator and other parameters.
+- Customization: Predefine appropriate macros to provide your own implementation of external facilities used by the library, like assert, mutex, and atomic.
+
+# Prequisites
+
+- Self-contained C++ library in single pair of H + CPP files. No external dependencies other than standard C, C++ library and Windows SDK. STL containers, C++ exceptions, and RTTI are not used.
+- Object-oriented interface in a convention similar to D3D12.
+- Error handling implemented by returning `HRESULT` error codes - same way as in D3D12.
+- Interface documented using Doxygen-style comments.
+
+# Example
+
+Basic usage of this library is very simple. Advanced features are optional. After you created global `Allocator` object, a complete code needed to create a texture may look like this:
+
+```cpp
+D3D12_RESOURCE_DESC resourceDesc = {};
+resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
+resourceDesc.Alignment = 0;
+resourceDesc.Width = 1024;
+resourceDesc.Height = 1024;
+resourceDesc.DepthOrArraySize = 1;
+resourceDesc.MipLevels = 1;
+resourceDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+resourceDesc.SampleDesc.Count = 1;
+resourceDesc.SampleDesc.Quality = 0;
+resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
+resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
+
+D3D12MA::ALLOCATION_DESC allocationDesc = {};
+allocDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;
+
+D3D12Resource* resource;
+D3D12MA::Allocation* allocation;
+HRESULT hr = allocator->CreateResource(
+    &allocationDesc,
+    &resourceDesc,
+    D3D12_RESOURCE_STATE_COPY_DEST,
+    NULL,
+    &allocation,
+    IID_PPV_ARGS(&resource));
+```
+
+With this one function call:
+
+1. `ID3D12Heap` memory block is allocated if needed.
+2. An unused region of the memory block assigned.
+3. `ID3D12Resource` is created as placed resource, bound to this region.
+
+`Allocation` is an object that represents memory assigned to this texture. It can be queried for parameters like offset and size.
+
+# Documentation
+
+Documentation is provided together with the library in form of Doxygen-style comments inside the code, in file "src/D3D12MemAlloc.h". They can be read directly or turned into HTML and other convenient to read formats. Unfortunately we can't provide pregenerated version browseable online. You can generate it on your own by following these steps:
+
+1. Install [Doxygen](http://www.doxygen.nl/).
+2. Open command line and enter "src" directory.
+3. Type command: `doxygen`
+4. Open following file in a web browser: "docs/html/index.html".
+
+# Copyright notice
+
+This software package uses third party software:
+
+- Parts of the code of [Vulkan Memory Allocator](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator/) by AMD, license: MIT
+- Parts of the code of [DirectX-Graphics-Samples](https://github.com/microsoft/DirectX-Graphics-Samples) by Microsoft, license: MIT
+- [Premake 5](https://premake.github.io/) binary, license: BSD
+
+For more information see [NOTICES.txt](NOTICES.txt).
+
+# Software using this library
+
+Place for the link to your project :)
+
+# See also
+
+- **[Vulkan Memory Allocator](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator/)** - equivalent library for Vulkan. License: MIT.
diff --git a/bin/D3D12Sample_Release_vs2019.exe b/bin/D3D12Sample_Release_vs2019.exe
new file mode 100644
index 0000000..e063ec6
--- /dev/null
+++ b/bin/D3D12Sample_Release_vs2019.exe
Binary files differ
diff --git a/premake/LICENSE.txt b/premake/LICENSE.txt
new file mode 100644
index 0000000..e7611e6
--- /dev/null
+++ b/premake/LICENSE.txt
@@ -0,0 +1,27 @@
+Copyright (c) 2003-2016 Jason Perkins and individual contributors.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+  1. Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+
+  2. Redistributions in binary form must reproduce the above copyright notice,
+     this list of conditions and the following disclaimer in the documentation
+     and/or other materials provided with the distribution.
+
+  3. Neither the name of Premake nor the names of its contributors may be
+     used to endorse or promote products derived from this software without
+     specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/premake/premake5.exe b/premake/premake5.exe
new file mode 100644
index 0000000..9048d51
--- /dev/null
+++ b/premake/premake5.exe
Binary files differ
diff --git a/premake/premake5.lua b/premake/premake5.lua
new file mode 100644
index 0000000..04bfb26
--- /dev/null
+++ b/premake/premake5.lua
@@ -0,0 +1,50 @@
+-- _ACTION is a premake global variable and for our usage will be vs2012, vs2013, etc.

+-- Strip "vs" from this string to make a suffix for solution and project files.

+_SUFFIX = _ACTION

+

+workspace "D3D12Sample"

+configurations { "Debug", "Release" }

+platforms { "x64" }

+location "../build"

+filename ("D3D12Sample_" .. _SUFFIX)

+startproject "D3D12Sample"

+

+filter "platforms:x64"

+system "Windows"

+architecture "x64"

+includedirs { }

+libdirs { }

+

+

+project "D3D12Sample"

+kind "ConsoleApp"

+language "C++"

+location "../build"

+filename ("D3D12Sample_" .. _SUFFIX)

+targetdir "../bin"

+objdir "../build/Desktop_%{_SUFFIX}/%{cfg.platform}/%{cfg.buildcfg}"

+floatingpoint "Fast"

+files { "../src/*.h", "../src/*.cpp" }

+flags { "NoPCH", "FatalWarnings" }

+characterset "Unicode"

+

+filter "configurations:Debug"

+defines { "_DEBUG", "DEBUG" }

+flags { }

+targetsuffix ("_Debug_" .. _SUFFIX)

+

+filter "configurations:Release"

+defines { "NDEBUG" }

+optimize "On"

+flags { "LinkTimeOptimization" }

+targetsuffix ("_Release_" .. _SUFFIX)

+

+filter { "platforms:x64" }

+defines { "WIN32", "_CONSOLE", "PROFILE", "_WINDOWS", "_WIN32_WINNT=0x0601" }

+links { "d3d12.lib", "dxgi.lib" }

+

+filter { "configurations:Debug", "platforms:x64" }

+buildoptions { "/MDd" }

+

+filter { "configurations:Release", "platforms:Windows-x64" }

+buildoptions { "/MD" }

diff --git a/src/Common.cpp b/src/Common.cpp
new file mode 100644
index 0000000..b5530d1
--- /dev/null
+++ b/src/Common.cpp
@@ -0,0 +1,176 @@
+//

+// Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.

+//

+// 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.

+//

+

+#include "Common.h"

+

+void ReadFile(std::vector<char>& out, const wchar_t* fileName)

+{

+    std::ifstream file(fileName, std::ios::ate | std::ios::binary);

+    assert(file.is_open());

+    size_t fileSize = (size_t)file.tellg();

+    if(fileSize > 0)

+    {

+        out.resize(fileSize);

+        file.seekg(0);

+        file.read(out.data(), fileSize);

+    }

+    else

+        out.clear();

+}

+

+void SaveFile(const wchar_t* filePath, const void* data, size_t dataSize)

+{

+    FILE* f = nullptr;

+    _wfopen_s(&f, filePath, L"wb");

+    if(f)

+    {

+        fwrite(data, 1, dataSize, f);

+        fclose(f);

+    }

+    else

+        assert(0);

+}

+

+void SetConsoleColor(CONSOLE_COLOR color)

+{

+    WORD attr = 0;

+    switch(color)

+    {

+    case CONSOLE_COLOR::INFO:

+        attr = FOREGROUND_INTENSITY;;

+        break;

+    case CONSOLE_COLOR::NORMAL:

+        attr = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;

+        break;

+    case CONSOLE_COLOR::WARNING:

+        attr = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY;

+        break;

+    case CONSOLE_COLOR::ERROR_:

+        attr = FOREGROUND_RED | FOREGROUND_INTENSITY;

+        break;

+    default:

+        assert(0);

+    }

+

+    HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);

+    SetConsoleTextAttribute(out, attr);

+}

+

+void PrintMessage(CONSOLE_COLOR color, const char* msg)

+{

+    if(color != CONSOLE_COLOR::NORMAL)

+        SetConsoleColor(color);

+    

+    printf("%s\n", msg);

+    

+    if (color != CONSOLE_COLOR::NORMAL)

+        SetConsoleColor(CONSOLE_COLOR::NORMAL);

+}

+

+void PrintMessage(CONSOLE_COLOR color, const wchar_t* msg)

+{

+    if(color != CONSOLE_COLOR::NORMAL)

+        SetConsoleColor(color);

+    

+    wprintf(L"%s\n", msg);

+    

+    if (color != CONSOLE_COLOR::NORMAL)

+        SetConsoleColor(CONSOLE_COLOR::NORMAL);

+}

+

+static const size_t CONSOLE_SMALL_BUF_SIZE = 256;

+

+void PrintMessageV(CONSOLE_COLOR color, const char* format, va_list argList)

+{

+	size_t dstLen = (size_t)::_vscprintf(format, argList);

+	if(dstLen)

+	{

+		bool useSmallBuf = dstLen < CONSOLE_SMALL_BUF_SIZE;

+		char smallBuf[CONSOLE_SMALL_BUF_SIZE];

+		std::vector<char> bigBuf(useSmallBuf ? 0 : dstLen + 1);

+		char* bufPtr = useSmallBuf ? smallBuf : bigBuf.data();

+		::vsprintf_s(bufPtr, dstLen + 1, format, argList);

+		PrintMessage(color, bufPtr);

+	}

+}

+

+void PrintMessageV(CONSOLE_COLOR color, const wchar_t* format, va_list argList)

+{

+	size_t dstLen = (size_t)::_vcwprintf(format, argList);

+	if(dstLen)

+	{

+		bool useSmallBuf = dstLen < CONSOLE_SMALL_BUF_SIZE;

+		wchar_t smallBuf[CONSOLE_SMALL_BUF_SIZE];

+		std::vector<wchar_t> bigBuf(useSmallBuf ? 0 : dstLen + 1);

+		wchar_t* bufPtr = useSmallBuf ? smallBuf : bigBuf.data();

+		::vswprintf_s(bufPtr, dstLen + 1, format, argList);

+		PrintMessage(color, bufPtr);

+	}

+}

+

+void PrintMessageF(CONSOLE_COLOR color, const char* format, ...)

+{

+	va_list argList;

+	va_start(argList, format);

+	PrintMessageV(color, format, argList);

+	va_end(argList);

+}

+

+void PrintMessageF(CONSOLE_COLOR color, const wchar_t* format, ...)

+{

+	va_list argList;

+	va_start(argList, format);

+	PrintMessageV(color, format, argList);

+	va_end(argList);

+}

+

+void PrintWarningF(const char* format, ...)

+{

+	va_list argList;

+	va_start(argList, format);

+	PrintMessageV(CONSOLE_COLOR::WARNING, format, argList);

+	va_end(argList);

+}

+

+void PrintWarningF(const wchar_t* format, ...)

+{

+	va_list argList;

+	va_start(argList, format);

+	PrintMessageV(CONSOLE_COLOR::WARNING, format, argList);

+	va_end(argList);

+}

+

+void PrintErrorF(const char* format, ...)

+{

+	va_list argList;

+	va_start(argList, format);

+	PrintMessageV(CONSOLE_COLOR::WARNING, format, argList);

+	va_end(argList);

+}

+

+void PrintErrorF(const wchar_t* format, ...)

+{

+	va_list argList;

+	va_start(argList, format);

+	PrintMessageV(CONSOLE_COLOR::WARNING, format, argList);

+	va_end(argList);

+}

diff --git a/src/Common.h b/src/Common.h
new file mode 100644
index 0000000..3495357
--- /dev/null
+++ b/src/Common.h
@@ -0,0 +1,380 @@
+//

+// Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.

+//

+// 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.

+//

+

+#pragma once

+

+#include <dxgi1_4.h>

+#include <d3d12.h>

+

+#define WIN32_LEAN_AND_MEAN

+#define NOMINMAX

+#include <Windows.h>

+#include <atlbase.h> // For CComPtr

+

+#include <iostream>

+#include <fstream>

+#include <vector>

+#include <memory>

+#include <algorithm>

+#include <numeric>

+#include <array>

+#include <type_traits>

+#include <utility>

+#include <chrono>

+#include <string>

+#include <exception>

+

+#include <cassert>

+#include <cstdlib>

+#include <cstdio>

+#include <cstdarg>

+

+typedef std::chrono::high_resolution_clock::time_point time_point;

+typedef std::chrono::high_resolution_clock::duration duration;

+

+#define STRINGIZE(x) STRINGIZE2(x)

+#define STRINGIZE2(x) #x

+#define LINE_STRING STRINGIZE(__LINE__)

+#define FAIL(msg) do { \

+        assert(0 && msg); \

+        throw std::runtime_error(msg); \

+    } while(false)

+

+#define CHECK_BOOL(expr)  do { if(!(expr)) FAIL(__FILE__ "(" LINE_STRING "): !( " #expr " )"); } while(false)

+#define CHECK_HR(expr)  do { if(FAILED(expr)) FAIL(__FILE__ "(" LINE_STRING "): FAILED( " #expr " )"); } while(false)

+

+template <typename T>

+inline constexpr T CeilDiv(T x, T y)

+{

+    return (x+y-1) / y;

+}

+template <typename T>

+inline constexpr T RoundDiv(T x, T y)

+{

+    return (x+y/(T)2) / y;

+}

+

+template <typename T>

+inline constexpr T AlignUp(T val, T align)

+{

+    return (val + align - 1) / align * align;

+}

+

+static const float PI = 3.14159265358979323846264338327950288419716939937510582f;

+

+struct vec2

+{

+    float x, y;

+

+    vec2() { }

+    vec2(float x, float y) : x(x), y(y) { }

+

+    float& operator[](uint32_t index) { return *(&x + index); }

+    const float& operator[](uint32_t index) const { return *(&x + index); }

+

+    vec2 operator+(const vec2& rhs) const { return vec2(x + rhs.x, y + rhs.y); }

+    vec2 operator-(const vec2& rhs) const { return vec2(x - rhs.x, y - rhs.y); }

+    vec2 operator*(float s) const { return vec2(x * s, y * s); }

+

+    vec2 Normalized() const

+    {

+        return (*this) * (1.f / sqrt(x * x + y * y));

+    }

+};

+

+struct vec3

+{

+    float x, y, z;

+

+    vec3() { }

+    vec3(float x, float y, float z) : x(x), y(y), z(z) { }

+

+    float& operator[](uint32_t index) { return *(&x + index); }

+    const float& operator[](uint32_t index) const { return *(&x + index); }

+

+    vec3 operator+(const vec3& rhs) const { return vec3(x + rhs.x, y + rhs.y, z + rhs.z); }

+    vec3 operator-(const vec3& rhs) const { return vec3(x - rhs.x, y - rhs.y, z - rhs.z); }

+    vec3 operator*(float s) const { return vec3(x * s, y * s, z * s); }

+

+    vec3 Normalized() const

+    {

+        return (*this) * (1.f / sqrt(x * x + y * y + z * z));

+    }

+};

+

+inline float Dot(const vec3& lhs, const vec3& rhs)

+{

+    return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z;

+}

+inline vec3 Cross(const vec3& lhs, const vec3& rhs)

+{

+    return vec3(

+        lhs.y * rhs.z - lhs.z * rhs.y,

+	    lhs.z * rhs.x - lhs.x * rhs.z,

+	    lhs.x * rhs.y - lhs.y * rhs.x);

+}

+

+struct vec4

+{

+    float x, y, z, w;

+

+    vec4() { }

+    vec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) { }

+    vec4(const vec3& v, float w) : x(v.x), y(v.y), z(v.z), w(w) { }

+

+    float& operator[](uint32_t index) { return *(&x + index); }

+    const float& operator[](uint32_t index) const { return *(&x + index); }

+

+    vec4 operator+(const vec4& rhs) const { return vec4(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w); }

+    vec4 operator-(const vec4& rhs) const { return vec4(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w); }

+    vec4 operator*(float s) const { return vec4(x * s, y * s, z * s, w * s); }

+};

+

+struct mat4

+{

+    union

+    {

+        struct

+        {

+            float _11, _12, _13, _14;

+            float _21, _22, _23, _24;

+            float _31, _32, _33, _34;

+            float _41, _42, _43, _44;

+        };

+        float m[4][4]; // [row][column]

+    };

+

+    mat4() { }

+

+    mat4(

+        float _11, float _12, float _13, float _14,

+        float _21, float _22, float _23, float _24,

+        float _31, float _32, float _33, float _34,

+        float _41, float _42, float _43, float _44) :

+        _11(_11), _12(_12), _13(_13), _14(_14),

+        _21(_21), _22(_22), _23(_23), _24(_24),

+        _31(_31), _32(_32), _33(_33), _34(_34),

+        _41(_41), _42(_42), _43(_43), _44(_44)

+    {

+    }

+

+    mat4(

+        const vec4& row1,

+        const vec4& row2,

+        const vec4& row3,

+        const vec4& row4) :

+        _11(row1.x), _12(row1.y), _13(row1.z), _14(row1.w),

+        _21(row2.x), _22(row2.y), _23(row2.z), _24(row2.w),

+        _31(row3.x), _32(row3.y), _33(row3.z), _34(row3.w),

+        _41(row4.x), _42(row4.y), _43(row4.z), _44(row4.w)

+    {

+    }

+

+    mat4(const float* data) :

+        _11(data[ 0]), _12(data[ 1]), _13(data[ 2]), _14(data[ 3]),

+        _21(data[ 4]), _22(data[ 5]), _23(data[ 6]), _24(data[ 7]),

+        _31(data[ 8]), _32(data[ 9]), _33(data[10]), _34(data[11]),

+        _41(data[12]), _42(data[13]), _43(data[14]), _44(data[15])

+    {

+    }

+

+    mat4 operator*(const mat4 &rhs) const

+    {

+        return mat4(

+            _11 * rhs._11 + _12 * rhs._21 + _13 * rhs._31 + _14 * rhs._41,

+            _11 * rhs._12 + _12 * rhs._22 + _13 * rhs._32 + _14 * rhs._42,

+            _11 * rhs._13 + _12 * rhs._23 + _13 * rhs._33 + _14 * rhs._43,

+            _11 * rhs._14 + _12 * rhs._24 + _13 * rhs._34 + _14 * rhs._44,

+

+            _21 * rhs._11 + _22 * rhs._21 + _23 * rhs._31 + _24 * rhs._41,

+            _21 * rhs._12 + _22 * rhs._22 + _23 * rhs._32 + _24 * rhs._42,

+            _21 * rhs._13 + _22 * rhs._23 + _23 * rhs._33 + _24 * rhs._43,

+            _21 * rhs._14 + _22 * rhs._24 + _23 * rhs._34 + _24 * rhs._44,

+

+            _31 * rhs._11 + _32 * rhs._21 + _33 * rhs._31 + _34 * rhs._41,

+            _31 * rhs._12 + _32 * rhs._22 + _33 * rhs._32 + _34 * rhs._42,

+            _31 * rhs._13 + _32 * rhs._23 + _33 * rhs._33 + _34 * rhs._43,

+            _31 * rhs._14 + _32 * rhs._24 + _33 * rhs._34 + _34 * rhs._44,

+

+            _41 * rhs._11 + _42 * rhs._21 + _43 * rhs._31 + _44 * rhs._41,

+            _41 * rhs._12 + _42 * rhs._22 + _43 * rhs._32 + _44 * rhs._42,

+            _41 * rhs._13 + _42 * rhs._23 + _43 * rhs._33 + _44 * rhs._43,

+            _41 * rhs._14 + _42 * rhs._24 + _43 * rhs._34 + _44 * rhs._44);

+    }

+

+    static mat4 Identity()

+    {

+        return mat4(

+            1.f, 0.f, 0.f, 0.f,

+            0.f, 1.f, 0.f, 0.f,

+            0.f, 0.f, 1.f, 0.f,

+            0.f, 0.f, 0.f, 1.f);

+    }

+

+    static mat4 Translation(const vec3& v)

+    {

+        return mat4(

+            1.f, 0.f, 0.f, 0.f,

+            0.f, 1.f, 0.f, 0.f,

+            0.f, 0.f, 1.f, 0.f,

+            v.x, v.y, v.z, 1.f);

+    }

+

+    static mat4 Scaling(float s)

+    {

+        return mat4(

+            s,   0.f, 0.f, 0.f,

+            0.f, s,   0.f, 0.f,

+            0.f, 0.f, s,   0.f,

+            0.f, 0.f, 0.f, 1.f);

+    }

+

+    static mat4 Scaling(const vec3& s)

+    {

+        return mat4(

+            s.x, 0.f, 0.f, 0.f,

+            0.f, s.y, 0.f, 0.f,

+            0.f, 0.f, s.z, 0.f,

+            0.f, 0.f, 0.f, 1.f);

+    }

+

+    static mat4 RotationX(float angle)

+    {

+        const float s = sin(angle), c = cos(angle);

+        return mat4(

+            1.f, 0.f, 0.f, 0.f,

+            0.f, c,   s,   0.f,

+            0.f, -s,  c,   0.f,

+            0.f, 0.f, 0.f, 1.f);

+    }

+

+    static mat4 RotationY(float angle)

+    {

+        const float s = sin(angle), c = cos(angle);

+        return mat4(

+            c,   s,  0.f,  0.f,

+            -s,  c,  0.f,  0.f,

+            0.f, 0.f, 1.f, 0.f,

+            0.f, 0.f, 0.f, 1.f);

+    }

+

+    static mat4 RotationZ(float angle)

+    {

+        const float s = sin(angle), c = cos(angle);

+        return mat4(

+            c,   0.f, -s,  0.f,

+            0.f, 1.f, 0.f, 0.f,

+            s,   0.f, c,   0.f,

+            0.f, 0.f, 0.f, 1.f);

+    }

+

+    static mat4 Perspective(float fovY, float aspectRatio, float zNear, float zFar)

+    {

+        float yScale = 1.0f / tan(fovY * 0.5f);

+        float xScale = yScale / aspectRatio;

+        return mat4(

+            xScale, 0.0f, 0.0f, 0.0f,

+            0.0f, yScale, 0.0f, 0.0f,

+            0.0f, 0.0f, zFar / (zFar - zNear), 1.0f,

+            0.0f, 0.0f, -zNear * zFar / (zFar - zNear), 0.0f);

+    }

+

+    static mat4 LookAt(vec3 at, vec3 eye, vec3 up)

+    {

+        vec3 zAxis = (at - eye).Normalized();

+        vec3 xAxis = Cross(up, zAxis).Normalized();

+        vec3 yAxis = Cross(zAxis, xAxis);

+        return mat4(

+            xAxis.x, yAxis.x, zAxis.x, 0.0f,

+            xAxis.y, yAxis.y, zAxis.y, 0.0f,

+            xAxis.z, yAxis.z, zAxis.z, 0.0f,

+            -Dot(xAxis, eye), -Dot(yAxis, eye), -Dot(zAxis, eye), 1.0f);

+    }

+

+    mat4 Transposed() const

+    {

+        return mat4(

+            _11, _21, _31, _41,

+            _12, _22, _32, _42,

+            _13, _23, _33, _43,

+            _14, _24, _34, _44);

+    }

+};

+

+class RandomNumberGenerator

+{

+public:

+    RandomNumberGenerator() : m_Value{GetTickCount()} {}

+    RandomNumberGenerator(uint32_t seed) : m_Value{seed} { }

+    void Seed(uint32_t seed) { m_Value = seed; }

+    uint32_t Generate() { return GenerateFast() ^ (GenerateFast() >> 7); }

+    bool GenerateBool() { return (GenerateFast() & 0x4) != 0; }

+

+private:

+    uint32_t m_Value;

+    uint32_t GenerateFast() { return m_Value = (m_Value * 196314165 + 907633515); }

+};

+

+// Wrapper for RandomNumberGenerator compatible with STL "UniformRandomNumberGenerator" idea.

+struct MyUniformRandomNumberGenerator

+{

+    typedef uint32_t result_type;

+    MyUniformRandomNumberGenerator(RandomNumberGenerator& gen) : m_Gen(gen) { }

+    uint32_t operator()() { return m_Gen.Generate(); }

+

+private:

+    RandomNumberGenerator& m_Gen;

+};

+

+void ReadFile(std::vector<char>& out, const wchar_t* fileName);

+void SaveFile(const wchar_t* filePath, const void* data, size_t dataSize);

+

+enum class CONSOLE_COLOR

+{

+    INFO,

+    NORMAL,

+    WARNING,

+    ERROR_,

+    COUNT

+};

+

+void SetConsoleColor(CONSOLE_COLOR color);

+

+void PrintMessage(CONSOLE_COLOR color, const char* msg);

+void PrintMessage(CONSOLE_COLOR color, const wchar_t* msg);

+

+inline void Print(const char* msg) { PrintMessage(CONSOLE_COLOR::NORMAL, msg); }

+inline void Print(const wchar_t* msg) { PrintMessage(CONSOLE_COLOR::NORMAL, msg); }

+inline void PrintWarning(const char* msg) { PrintMessage(CONSOLE_COLOR::WARNING, msg); }

+inline void PrintWarning(const wchar_t* msg) { PrintMessage(CONSOLE_COLOR::WARNING, msg); }

+inline void PrintError(const char* msg) { PrintMessage(CONSOLE_COLOR::ERROR_, msg); }

+inline void PrintError(const wchar_t* msg) { PrintMessage(CONSOLE_COLOR::ERROR_, msg); }

+

+void PrintMessageV(CONSOLE_COLOR color, const char* format, va_list argList);

+void PrintMessageV(CONSOLE_COLOR color, const wchar_t* format, va_list argList);

+void PrintMessageF(CONSOLE_COLOR color, const char* format, ...);

+void PrintMessageF(CONSOLE_COLOR color, const wchar_t* format, ...);

+void PrintWarningF(const char* format, ...);

+void PrintWarningF(const wchar_t* format, ...);

+void PrintErrorF(const char* format, ...);

+void PrintErrorF(const wchar_t* format, ...);

+

diff --git a/src/D3D12MemAlloc.cpp b/src/D3D12MemAlloc.cpp
new file mode 100644
index 0000000..874ee39
--- /dev/null
+++ b/src/D3D12MemAlloc.cpp
@@ -0,0 +1,3122 @@
+//

+// Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.

+//

+// 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.

+//

+

+#include "D3D12MemAlloc.h"

+

+#include <mutex>

+#include <atomic>

+#include <algorithm>

+#include <cstdlib>

+#include <malloc.h> // for _aligned_malloc, _aligned_free

+

+////////////////////////////////////////////////////////////////////////////////

+////////////////////////////////////////////////////////////////////////////////

+//

+// Configuration Begin

+//

+////////////////////////////////////////////////////////////////////////////////

+////////////////////////////////////////////////////////////////////////////////

+

+#ifndef D3D12MA_ASSERT

+    #include <cassert>

+    #define D3D12MA_ASSERT(cond) assert(cond)

+#endif

+

+// Assert that will be called very often, like inside data structures e.g. operator[].

+// Making it non-empty can make program slow.

+#ifndef D3D12MA_HEAVY_ASSERT

+    #ifdef _DEBUG

+        #define D3D12MA_HEAVY_ASSERT(expr)   //D3D12MA_ASSERT(expr)

+    #else

+        #define D3D12MA_HEAVY_ASSERT(expr)

+    #endif

+#endif

+

+#ifndef D3D12MA_DEBUG_ALWAYS_COMMITTED

+    /*

+    Every allocation will have its own memory block.

+    Define to 1 for debugging purposes only.

+    */

+    #define D3D12MA_DEBUG_ALWAYS_COMMITTED (0)

+#endif

+

+#ifndef D3D12MA_DEBUG_ALIGNMENT

+    /*

+    Minimum alignment of all allocations, in bytes.

+    Set to more than 1 for debugging purposes only. Must be power of two.

+    */

+    #define D3D12MA_DEBUG_ALIGNMENT (1)

+#endif

+

+#ifndef D3D12MA_DEBUG_MARGIN

+    // Minimum margin before and after every allocation, in bytes.

+    // Set nonzero for debugging purposes only.

+    #define D3D12MA_DEBUG_MARGIN (0)

+#endif

+

+#ifndef D3D12MA_DEBUG_GLOBAL_MUTEX

+    /*

+    Set this to 1 for debugging purposes only, to enable single mutex protecting all

+    entry calls to the library. Can be useful for debugging multithreading issues.

+    */

+    #define D3D12MA_DEBUG_GLOBAL_MUTEX (0)

+#endif

+

+#ifndef D3D12MA_DEFAULT_BLOCK_SIZE

+   /// Default size of a block allocated as single ID3D12Heap.

+   #define D3D12MA_DEFAULT_BLOCK_SIZE (256ull * 1024 * 1024)

+#endif

+

+////////////////////////////////////////////////////////////////////////////////

+////////////////////////////////////////////////////////////////////////////////

+//

+// Configuration End

+//

+////////////////////////////////////////////////////////////////////////////////

+////////////////////////////////////////////////////////////////////////////////

+

+

+namespace D3D12MA

+{

+

+////////////////////////////////////////////////////////////////////////////////

+// Private globals - CPU memory allocation

+

+static void* DefaultAllocate(size_t Size, size_t Alignment, void* /*pUserData*/)

+{

+    return _aligned_malloc(Size, Alignment);

+}

+static void DefaultFree(void* pMemory, void* /*pUserData*/)

+{

+    return _aligned_free(pMemory);

+}

+

+static void* Malloc(const ALLOCATION_CALLBACKS& allocs, size_t size, size_t alignment)

+{

+    return (*allocs.pAllocate)(size, alignment, allocs.pUserData);

+}

+static void Free(const ALLOCATION_CALLBACKS& allocs, void* memory)

+{

+    (*allocs.pFree)(memory, allocs.pUserData);

+}

+

+template<typename T>

+static T* Allocate(const ALLOCATION_CALLBACKS& allocs)

+{

+    return (T*)Malloc(allocs, sizeof(T), __alignof(T));

+}

+template<typename T>

+static T* AllocateArray(const ALLOCATION_CALLBACKS& allocs, size_t count)

+{

+    return (T*)Malloc(allocs, sizeof(T) * count, __alignof(T));

+}

+

+#define D3D12MA_NEW(allocs, type) new(D3D12MA::Allocate<type>(allocs))(type)

+#define D3D12MA_NEW_ARRAY(allocs, type, count) new(D3D12MA::AllocateArray<type>((allocs), (count)))(type)

+

+template<typename T>

+static void D3D12MA_DELETE(const ALLOCATION_CALLBACKS& allocs, T* memory)

+{

+    if(memory)

+    {

+        memory->~T();

+        Free(allocs, memory);

+    }

+}

+template<typename T>

+static void D3D12MA_DELETE_ARRAY(const ALLOCATION_CALLBACKS& allocs, T* memory, size_t count)

+{

+    if(memory)

+    {

+        for(size_t i = count; i--; )

+        {

+            memory[i].~T();

+        }

+        Free(allocs, memory);

+    }

+}

+

+static void SetupAllocationCallbacks(ALLOCATION_CALLBACKS& outAllocs, const ALLOCATOR_DESC& allocatorDesc)

+{

+    if(allocatorDesc.pAllocationCallbacks)

+    {

+        outAllocs = *allocatorDesc.pAllocationCallbacks;

+        D3D12MA_ASSERT(outAllocs.pAllocate != NULL && outAllocs.pFree != NULL);

+    }

+    else

+    {

+        outAllocs.pAllocate = &DefaultAllocate;

+        outAllocs.pFree = &DefaultFree;

+        outAllocs.pUserData = NULL;

+    }

+}

+

+////////////////////////////////////////////////////////////////////////////////

+// Private globals - basic facilities

+

+#define D3D12MA_VALIDATE(cond) do { if(!(cond)) { \

+        D3D12MA_ASSERT(0 && "Validation failed: " #cond); \

+        return false; \

+    } } while(false)

+

+template<typename T>

+static inline T D3D12MA_MIN(const T& a, const T& b)

+{

+    return a <= b ? a : b;

+}

+template<typename T>

+static inline T D3D12MA_MAX(const T& a, const T& b)

+{

+    return a <= b ? b : a;

+}

+

+template<typename T>

+static inline void D3D12MA_SWAP(T& a, T& b)

+{

+    T tmp = a; a = b; b = tmp;

+}

+

+#ifndef D3D12MA_MUTEX

+    class Mutex

+    {

+    public:

+        void Lock() { m_Mutex.lock(); }

+        void Unlock() { m_Mutex.unlock(); }

+    private:

+        std::mutex m_Mutex;

+    };

+    #define D3D12MA_MUTEX Mutex

+#endif

+

+#if !defined(_WIN32) || !defined(WINVER) || WINVER < 0x0600

+    #error Required at least WinAPI version supporting: client = Windows Vista, server = Windows Server 2008.

+#endif

+

+#ifndef D3D12MA_RW_MUTEX

+    class RWMutex

+    {

+    public:

+        RWMutex() { InitializeSRWLock(&m_Lock); }

+        void LockRead() { AcquireSRWLockShared(&m_Lock); }

+        void UnlockRead() { ReleaseSRWLockShared(&m_Lock); }

+        void LockWrite() { AcquireSRWLockExclusive(&m_Lock); }

+        void UnlockWrite() { ReleaseSRWLockExclusive(&m_Lock); }

+    private:

+        SRWLOCK m_Lock;

+    };

+    #define D3D12MA_RW_MUTEX RWMutex

+#endif

+

+/*

+If providing your own implementation, you need to implement a subset of std::atomic:

+

+- Constructor(UINT desired)

+- UINT load() const

+- void store(UINT desired)

+- bool compare_exchange_weak(UINT& expected, UINT desired)

+*/

+#ifndef D3D12MA_ATOMIC_UINT32

+    #define D3D12MA_ATOMIC_UINT32 std::atomic<UINT>

+#endif

+

+// Aligns given value up to nearest multiply of align value. For example: AlignUp(11, 8) = 16.

+// Use types like UINT, uint64_t as T.

+template <typename T>

+static inline T AlignUp(T val, T align)

+{

+	return (val + align - 1) / align * align;

+}

+// Aligns given value down to nearest multiply of align value. For example: AlignUp(11, 8) = 8.

+// Use types like UINT, uint64_t as T.

+template <typename T>

+static inline T AlignDown(T val, T align)

+{

+    return val / align * align;

+}

+

+// Division with mathematical rounding to nearest number.

+template <typename T>

+static inline T RoundDiv(T x, T y)

+{

+	return (x + (y / (T)2)) / y;

+}

+

+/*

+Returns true if given number is a power of two.

+T must be unsigned integer number or signed integer but always nonnegative.

+For 0 returns true.

+*/

+template <typename T>

+inline bool IsPow2(T x)

+{

+    return (x & (x-1)) == 0;

+}

+

+// Returns smallest power of 2 greater or equal to v.

+static inline UINT NextPow2(UINT v)

+{

+	v--;

+    v |= v >> 1;

+    v |= v >> 2;

+    v |= v >> 4;

+    v |= v >> 8;

+    v |= v >> 16;

+    v++;

+    return v;

+}

+static inline uint64_t NextPow2(uint64_t v)

+{

+	v--;

+    v |= v >> 1;

+    v |= v >> 2;

+    v |= v >> 4;

+    v |= v >> 8;

+    v |= v >> 16;

+    v |= v >> 32;

+    v++;

+    return v;

+}

+

+// Returns largest power of 2 less or equal to v.

+static inline UINT PrevPow2(UINT v)

+{

+    v |= v >> 1;

+    v |= v >> 2;

+    v |= v >> 4;

+    v |= v >> 8;

+    v |= v >> 16;

+    v = v ^ (v >> 1);

+    return v;

+}

+static inline uint64_t PrevPow2(uint64_t v)

+{

+    v |= v >> 1;

+    v |= v >> 2;

+    v |= v >> 4;

+    v |= v >> 8;

+    v |= v >> 16;

+    v |= v >> 32;

+    v = v ^ (v >> 1);

+    return v;

+}

+

+static inline bool StrIsEmpty(const char* pStr)

+{

+    return pStr == NULL || *pStr == '\0';

+}

+

+// Helper RAII class to lock a mutex in constructor and unlock it in destructor (at the end of scope).

+struct MutexLock

+{

+public:

+    MutexLock(D3D12MA_MUTEX& mutex, bool useMutex = true) :

+        m_pMutex(useMutex ? &mutex : NULL)

+    {

+        if(m_pMutex)

+        {

+            m_pMutex->Lock();

+        }

+    }

+    ~MutexLock()

+    {

+        if(m_pMutex)

+        {

+            m_pMutex->Unlock();

+        }

+    }

+private:

+    D3D12MA_MUTEX* m_pMutex;

+

+    D3D12MA_CLASS_NO_COPY(MutexLock)

+};

+

+// Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for reading.

+struct MutexLockRead

+{

+public:

+    MutexLockRead(D3D12MA_RW_MUTEX& mutex, bool useMutex) :

+        m_pMutex(useMutex ? &mutex : NULL)

+    {

+        if(m_pMutex)

+        {

+            m_pMutex->LockRead();

+        }

+    }

+    ~MutexLockRead()

+    {

+        if(m_pMutex)

+        {

+            m_pMutex->UnlockRead();

+        }

+    }

+private:

+    D3D12MA_RW_MUTEX* m_pMutex;

+

+    D3D12MA_CLASS_NO_COPY(MutexLockRead)

+};

+

+// Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for writing.

+struct MutexLockWrite

+{

+public:

+    MutexLockWrite(D3D12MA_RW_MUTEX& mutex, bool useMutex) :

+        m_pMutex(useMutex ? &mutex : NULL)

+    {

+        if(m_pMutex)

+        {

+            m_pMutex->LockWrite();

+        }

+    }

+    ~MutexLockWrite()

+    {

+        if(m_pMutex)

+        {

+            m_pMutex->UnlockWrite();

+        }

+    }

+private:

+    D3D12MA_RW_MUTEX* m_pMutex;

+

+    D3D12MA_CLASS_NO_COPY(MutexLockWrite)

+};

+

+#if D3D12MA_DEBUG_GLOBAL_MUTEX

+    static D3D12MA_MUTEX g_DebugGlobalMutex;

+    #define D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK MutexLock debugGlobalMutexLock(g_DebugGlobalMutex, true);

+#else

+    #define D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK

+#endif

+

+// Minimum size of a free suballocation to register it in the free suballocation collection.

+static const UINT64 MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER = 16;

+

+/*

+Performs binary search and returns iterator to first element that is greater or

+equal to `key`, according to comparison `cmp`.

+

+Cmp should return true if first argument is less than second argument.

+

+Returned value is the found element, if present in the collection or place where

+new element with value (key) should be inserted.

+*/

+template <typename CmpLess, typename IterT, typename KeyT>

+static IterT BinaryFindFirstNotLess(IterT beg, IterT end, const KeyT &key, const CmpLess& cmp)

+{

+    size_t down = 0, up = (end - beg);

+    while(down < up)

+    {

+        const size_t mid = (down + up) / 2;

+        if(cmp(*(beg+mid), key))

+        {

+            down = mid + 1;

+        }

+        else

+        {

+            up = mid;

+        }

+    }

+    return beg + down;

+}

+

+/*

+Performs binary search and returns iterator to an element that is equal to `key`,

+according to comparison `cmp`.

+

+Cmp should return true if first argument is less than second argument.

+

+Returned value is the found element, if present in the collection or end if not

+found.

+*/

+template<typename CmpLess, typename IterT, typename KeyT>

+IterT BinaryFindSorted(const IterT& beg, const IterT& end, const KeyT& value, const CmpLess& cmp)

+{

+    IterT it = BinaryFindFirstNotLess<CmpLess, IterT, KeyT>(beg, end, value, cmp);

+    if(it == end ||

+        (!cmp(*it, value) && !cmp(value, *it)))

+    {

+        return it;

+    }

+    return end;

+}

+

+struct PointerLess

+{

+    bool operator()(const void* lhs, const void* rhs) const

+    {

+        return lhs < rhs;

+    }

+};

+

+static const UINT HEAP_TYPE_COUNT = 3;

+

+static UINT HeapTypeToIndex(D3D12_HEAP_TYPE type)

+{

+    switch(type)

+    {

+    case D3D12_HEAP_TYPE_DEFAULT:  return 0;

+    case D3D12_HEAP_TYPE_UPLOAD:   return 1;

+    case D3D12_HEAP_TYPE_READBACK: return 2;

+    default: D3D12MA_ASSERT(0); return UINT_MAX;

+    }

+}

+

+////////////////////////////////////////////////////////////////////////////////

+// Private class Vector

+

+/*

+Dynamically resizing continuous array. Class with interface similar to std::vector.

+T must be POD because constructors and destructors are not called and memcpy is

+used for these objects.

+*/

+template<typename T>

+class Vector

+{

+public:

+    typedef T value_type;

+

+    // allocationCallbacks externally owned, must outlive this object.

+    Vector(const ALLOCATION_CALLBACKS& allocationCallbacks) :

+        m_AllocationCallbacks(allocationCallbacks),

+        m_pArray(NULL),

+        m_Count(0),

+        m_Capacity(0)

+    {

+    }

+

+    Vector(size_t count, const ALLOCATION_CALLBACKS& allocationCallbacks) :

+        m_AllocationCallbacks(allocationCallbacks),

+        m_pArray(count ? AllocateArray<T>(allocationCallbacks, count) : NULL),

+        m_Count(count),

+        m_Capacity(count)

+    {

+    }

+

+    Vector(const Vector<T>& src) :

+        m_AllocationCallbacks(src.m_AllocationCallbacks),

+        m_pArray(src.m_Count ? AllocateArray<T>(src.m_AllocationCallbacks, src.m_Count) : NULL),

+        m_Count(src.m_Count),

+        m_Capacity(src.m_Count)

+    {

+        if(m_Count > 0)

+        {

+            memcpy(m_pArray, src.m_pArray, m_Count * sizeof(T));

+        }

+    }

+

+    ~Vector()

+    {

+        Free(m_AllocationCallbacks, m_pArray);

+    }

+

+    Vector& operator=(const Vector<T>& rhs)

+    {

+        if(&rhs != this)

+        {

+            resize(rhs.m_Count);

+            if(m_Count != 0)

+            {

+                memcpy(m_pArray, rhs.m_pArray, m_Count * sizeof(T));

+            }

+        }

+        return *this;

+    }

+

+    bool empty() const { return m_Count == 0; }

+    size_t size() const { return m_Count; }

+    T* data() { return m_pArray; }

+    const T* data() const { return m_pArray; }

+

+    T& operator[](size_t index)

+    {

+        D3D12MA_HEAVY_ASSERT(index < m_Count);

+        return m_pArray[index];

+    }

+    const T& operator[](size_t index) const

+    {

+        D3D12MA_HEAVY_ASSERT(index < m_Count);

+        return m_pArray[index];

+    }

+

+    T& front()

+    {

+        D3D12MA_HEAVY_ASSERT(m_Count > 0);

+        return m_pArray[0];

+    }

+    const T& front() const

+    {

+        D3D12MA_HEAVY_ASSERT(m_Count > 0);

+        return m_pArray[0];

+    }

+    T& back()

+    {

+        D3D12MA_HEAVY_ASSERT(m_Count > 0);

+        return m_pArray[m_Count - 1];

+    }

+    const T& back() const

+    {

+        D3D12MA_HEAVY_ASSERT(m_Count > 0);

+        return m_pArray[m_Count - 1];

+    }

+

+    void reserve(size_t newCapacity, bool freeMemory = false)

+    {

+        newCapacity = D3D12MA_MAX(newCapacity, m_Count);

+

+        if((newCapacity < m_Capacity) && !freeMemory)

+        {

+            newCapacity = m_Capacity;

+        }

+

+        if(newCapacity != m_Capacity)

+        {

+            T* const newArray = newCapacity ? AllocateArray<T>(m_AllocationCallbacks, newCapacity) : NULL;

+            if(m_Count != 0)

+            {

+                memcpy(newArray, m_pArray, m_Count * sizeof(T));

+            }

+            Free(m_Allocator.m_pCallbacks, m_pArray);

+            m_Capacity = newCapacity;

+            m_pArray = newArray;

+        }

+    }

+

+    void resize(size_t newCount, bool freeMemory = false)

+    {

+        size_t newCapacity = m_Capacity;

+        if(newCount > m_Capacity)

+        {

+            newCapacity = D3D12MA_MAX(newCount, D3D12MA_MAX(m_Capacity * 3 / 2, (size_t)8));

+        }

+        else if(freeMemory)

+        {

+            newCapacity = newCount;

+        }

+

+        if(newCapacity != m_Capacity)

+        {

+            T* const newArray = newCapacity ? AllocateArray<T>(m_AllocationCallbacks, newCapacity) : NULL;

+            const size_t elementsToCopy = D3D12MA_MIN(m_Count, newCount);

+            if(elementsToCopy != 0)

+            {

+                memcpy(newArray, m_pArray, elementsToCopy * sizeof(T));

+            }

+            Free(m_AllocationCallbacks, m_pArray);

+            m_Capacity = newCapacity;

+            m_pArray = newArray;

+        }

+

+        m_Count = newCount;

+    }

+

+    void clear(bool freeMemory = false)

+    {

+        resize(0, freeMemory);

+    }

+

+    void insert(size_t index, const T& src)

+    {

+        D3D12MA_HEAVY_ASSERT(index <= m_Count);

+        const size_t oldCount = size();

+        resize(oldCount + 1);

+        if(index < oldCount)

+        {

+            memmove(m_pArray + (index + 1), m_pArray + index, (oldCount - index) * sizeof(T));

+        }

+        m_pArray[index] = src;

+    }

+

+    void remove(size_t index)

+    {

+        D3D12MA_HEAVY_ASSERT(index < m_Count);

+        const size_t oldCount = size();

+        if(index < oldCount - 1)

+        {

+            memmove(m_pArray + index, m_pArray + (index + 1), (oldCount - index - 1) * sizeof(T));

+        }

+        resize(oldCount - 1);

+    }

+

+    void push_back(const T& src)

+    {

+        const size_t newIndex = size();

+        resize(newIndex + 1);

+        m_pArray[newIndex] = src;

+    }

+

+    void pop_back()

+    {

+        D3D12MA_HEAVY_ASSERT(m_Count > 0);

+        resize(size() - 1);

+    }

+

+    void push_front(const T& src)

+    {

+        insert(0, src);

+    }

+

+    void pop_front()

+    {

+        D3D12MA_HEAVY_ASSERT(m_Count > 0);

+        remove(0);

+    }

+

+    typedef T* iterator;

+

+    iterator begin() { return m_pArray; }

+    iterator end() { return m_pArray + m_Count; }

+

+    template<typename CmpLess>

+    size_t InsertSorted(const T& value, const CmpLess& cmp)

+    {

+        const size_t indexToInsert = BinaryFindFirstNotLess<CmpLess, iterator, T>(

+            m_pArray,

+            m_pArray + m_Count,

+            value,

+            cmp) - m_pArray;

+        insert(indexToInsert, value);

+        return indexToInsert;

+    }

+

+    template<typename CmpLess>

+    bool RemoveSorted(const T& value, const CmpLess& cmp)

+    {

+        const iterator it = BinaryFindFirstNotLess(

+            m_pArray,

+            m_pArray + m_Count,

+            value,

+            cmp);

+        if((it != end()) && !cmp(*it, value) && !cmp(value, *it))

+        {

+            size_t indexToRemove = it - begin();

+            remove(indexToRemove);

+            return true;

+        }

+        return false;

+    }

+

+private:

+    const ALLOCATION_CALLBACKS& m_AllocationCallbacks;

+    T* m_pArray;

+    size_t m_Count;

+    size_t m_Capacity;

+};

+

+////////////////////////////////////////////////////////////////////////////////

+// Private class PoolAllocator

+

+/*

+Allocator for objects of type T using a list of arrays (pools) to speed up

+allocation. Number of elements that can be allocated is not bounded because

+allocator can create multiple blocks.

+T should be POD because constructor and destructor is not called in Alloc or

+Free.

+*/

+template<typename T>

+class PoolAllocator

+{

+    D3D12MA_CLASS_NO_COPY(PoolAllocator)

+public:

+    // allocationCallbacks externally owned, must outlive this object.

+    PoolAllocator(const ALLOCATION_CALLBACKS& allocationCallbacks, UINT firstBlockCapacity);

+    ~PoolAllocator() { Clear(); }

+    void Clear();

+    T* Alloc();

+    void Free(T* ptr);

+

+private:

+    union Item

+    {

+        UINT NextFreeIndex; // UINT32_MAX means end of list.

+        T Value;

+    };

+

+    struct ItemBlock

+    {

+        Item* pItems;

+        UINT Capacity;

+        UINT FirstFreeIndex;

+    };

+

+    const ALLOCATION_CALLBACKS& m_AllocationCallbacks;

+    const UINT m_FirstBlockCapacity;

+    Vector<ItemBlock> m_ItemBlocks;

+

+    ItemBlock& CreateNewBlock();

+};

+

+template<typename T>

+PoolAllocator<T>::PoolAllocator(const ALLOCATION_CALLBACKS& allocationCallbacks, UINT firstBlockCapacity) :

+    m_AllocationCallbacks(allocationCallbacks),

+    m_FirstBlockCapacity(firstBlockCapacity),

+    m_ItemBlocks(allocationCallbacks)

+{

+    D3D12MA_ASSERT(m_FirstBlockCapacity > 1);

+}

+

+template<typename T>

+void PoolAllocator<T>::Clear()

+{

+    for(size_t i = m_ItemBlocks.size(); i--; )

+    {

+        D3D12MA_DELETE_ARRAY(m_AllocationCallbacks, m_ItemBlocks[i].pItems, m_ItemBlocks[i].Capacity);

+    }

+    m_ItemBlocks.clear(true);

+}

+

+template<typename T>

+T* PoolAllocator<T>::Alloc()

+{

+    for(size_t i = m_ItemBlocks.size(); i--; )

+    {

+        ItemBlock& block = m_ItemBlocks[i];

+        // This block has some free items: Use first one.

+        if(block.FirstFreeIndex != UINT32_MAX)

+        {

+            Item* const pItem = &block.pItems[block.FirstFreeIndex];

+            block.FirstFreeIndex = pItem->NextFreeIndex;

+            return &pItem->Value;

+        }

+    }

+

+    // No block has free item: Create new one and use it.

+    ItemBlock& newBlock = CreateNewBlock();

+    Item* const pItem = &newBlock.pItems[0];

+    newBlock.FirstFreeIndex = pItem->NextFreeIndex;

+    return &pItem->Value;

+}

+

+template<typename T>

+void PoolAllocator<T>::Free(T* ptr)

+{

+    // Search all memory blocks to find ptr.

+    for(size_t i = m_ItemBlocks.size(); i--; )

+    {

+        ItemBlock& block = m_ItemBlocks[i];

+

+        Item* pItemPtr;

+        memcpy(&pItemPtr, &ptr, sizeof(pItemPtr));

+

+        // Check if pItemPtr is in address range of this block.

+        if((pItemPtr >= block.pItems) && (pItemPtr < block.pItems + block.Capacity))

+        {

+            const UINT index = static_cast<UINT>(pItemPtr - block.pItems);

+            pItemPtr->NextFreeIndex = block.FirstFreeIndex;

+            block.FirstFreeIndex = index;

+            return;

+        }

+    }

+    D3D12MA_ASSERT(0 && "Pointer doesn't belong to this memory pool.");

+}

+

+template<typename T>

+typename PoolAllocator<T>::ItemBlock& PoolAllocator<T>::CreateNewBlock()

+{

+    const UINT newBlockCapacity = m_ItemBlocks.empty() ?

+        m_FirstBlockCapacity : m_ItemBlocks.back().Capacity * 3 / 2;

+

+    const ItemBlock newBlock = {

+        D3D12MA_NEW_ARRAY(m_AllocationCallbacks, Item, newBlockCapacity),

+        newBlockCapacity,

+        0 };

+

+    m_ItemBlocks.push_back(newBlock);

+

+    // Setup singly-linked list of all free items in this block.

+    for(UINT i = 0; i < newBlockCapacity - 1; ++i)

+    {

+        newBlock.pItems[i].NextFreeIndex = i + 1;

+    }

+    newBlock.pItems[newBlockCapacity - 1].NextFreeIndex = UINT32_MAX;

+    return m_ItemBlocks.back();

+}

+

+////////////////////////////////////////////////////////////////////////////////

+// Private class List

+

+/*

+Doubly linked list, with elements allocated out of PoolAllocator.

+Has custom interface, as well as STL-style interface, including iterator and

+const_iterator.

+*/

+template<typename T>

+class List

+{

+    D3D12MA_CLASS_NO_COPY(List)

+public:

+    struct Item

+    {

+        Item* pPrev;

+        Item* pNext;

+        T Value;

+    };

+

+    // allocationCallbacks externally owned, must outlive this object.

+    List(const ALLOCATION_CALLBACKS& allocationCallbacks);

+    ~List();

+    void Clear();

+

+    size_t GetCount() const { return m_Count; }

+    bool IsEmpty() const { return m_Count == 0; }

+

+    Item* Front() { return m_pFront; }

+    const Item* Front() const { return m_pFront; }

+    Item* Back() { return m_pBack; }

+    const Item* Back() const { return m_pBack; }

+

+    Item* PushBack();

+    Item* PushFront();

+    Item* PushBack(const T& value);

+    Item* PushFront(const T& value);

+    void PopBack();

+    void PopFront();

+

+    // Item can be null - it means PushBack.

+    Item* InsertBefore(Item* pItem);

+    // Item can be null - it means PushFront.

+    Item* InsertAfter(Item* pItem);

+

+    Item* InsertBefore(Item* pItem, const T& value);

+    Item* InsertAfter(Item* pItem, const T& value);

+

+    void Remove(Item* pItem);

+

+    class iterator

+    {

+    public:

+        iterator() :

+            m_pList(NULL),

+            m_pItem(NULL)

+        {

+        }

+

+        T& operator*() const

+        {

+            D3D12MA_HEAVY_ASSERT(m_pItem != NULL);

+            return m_pItem->Value;

+        }

+        T* operator->() const

+        {

+            D3D12MA_HEAVY_ASSERT(m_pItem != NULL);

+            return &m_pItem->Value;

+        }

+

+        iterator& operator++()

+        {

+            D3D12MA_HEAVY_ASSERT(m_pItem != NULL);

+            m_pItem = m_pItem->pNext;

+            return *this;

+        }

+        iterator& operator--()

+        {

+            if(m_pItem != NULL)

+            {

+                m_pItem = m_pItem->pPrev;

+            }

+            else

+            {

+                D3D12MA_HEAVY_ASSERT(!m_pList->IsEmpty());

+                m_pItem = m_pList->Back();

+            }

+            return *this;

+        }

+

+        iterator operator++(int)

+        {

+            iterator result = *this;

+            ++*this;

+            return result;

+        }

+        iterator operator--(int)

+        {

+            iterator result = *this;

+            --*this;

+            return result;

+        }

+

+        bool operator==(const iterator& rhs) const

+        {

+            D3D12MA_HEAVY_ASSERT(m_pList == rhs.m_pList);

+            return m_pItem == rhs.m_pItem;

+        }

+        bool operator!=(const iterator& rhs) const

+        {

+            D3D12MA_HEAVY_ASSERT(m_pList == rhs.m_pList);

+            return m_pItem != rhs.m_pItem;

+        }

+

+    private:

+        List<T>* m_pList;

+        List<T>::Item* m_pItem;

+

+        iterator(List<T>* pList, List<T>::Item* pItem) :

+            m_pList(pList),

+            m_pItem(pItem)

+        {

+        }

+

+        friend class List<T>;

+    };

+

+    class const_iterator

+    {

+    public:

+        const_iterator() :

+            m_pList(NULL),

+            m_pItem(NULL)

+        {

+        }

+

+        const_iterator(const iterator& src) :

+            m_pList(src.m_pList),

+            m_pItem(src.m_pItem)

+        {

+        }

+

+        const T& operator*() const

+        {

+            D3D12MA_HEAVY_ASSERT(m_pItem != NULL);

+            return m_pItem->Value;

+        }

+        const T* operator->() const

+        {

+            D3D12MA_HEAVY_ASSERT(m_pItem != NULL);

+            return &m_pItem->Value;

+        }

+

+        const_iterator& operator++()

+        {

+            D3D12MA_HEAVY_ASSERT(m_pItem != NULL);

+            m_pItem = m_pItem->pNext;

+            return *this;

+        }

+        const_iterator& operator--()

+        {

+            if(m_pItem != NULL)

+            {

+                m_pItem = m_pItem->pPrev;

+            }

+            else

+            {

+                D3D12MA_HEAVY_ASSERT(!m_pList->IsEmpty());

+                m_pItem = m_pList->Back();

+            }

+            return *this;

+        }

+

+        const_iterator operator++(int)

+        {

+            const_iterator result = *this;

+            ++*this;

+            return result;

+        }

+        const_iterator operator--(int)

+        {

+            const_iterator result = *this;

+            --*this;

+            return result;

+        }

+

+        bool operator==(const const_iterator& rhs) const

+        {

+            D3D12MA_HEAVY_ASSERT(m_pList == rhs.m_pList);

+            return m_pItem == rhs.m_pItem;

+        }

+        bool operator!=(const const_iterator& rhs) const

+        {

+            D3D12MA_HEAVY_ASSERT(m_pList == rhs.m_pList);

+            return m_pItem != rhs.m_pItem;

+        }

+

+    private:

+        const_iterator(const List<T>* pList, const List<T>::Item* pItem) :

+            m_pList(pList),

+            m_pItem(pItem)

+        {

+        }

+

+        const List<T>* m_pList;

+        const List<T>::Item* m_pItem;

+

+        friend class List<T>;

+    };

+

+    bool empty() const { return IsEmpty(); }

+    size_t size() const { return GetCount(); }

+

+    iterator begin() { return iterator(this, Front()); }

+    iterator end() { return iterator(this, NULL); }

+

+    const_iterator cbegin() const { return const_iterator(this, Front()); }

+    const_iterator cend() const { return const_iterator(this, NULL); }

+

+    void clear() { Clear(); }

+    void push_back(const T& value) { PushBack(value); }

+    void erase(iterator it) { Remove(it.m_pItem); }

+    iterator insert(iterator it, const T& value) { return iterator(this, InsertBefore(it.m_pItem, value)); }

+

+private:

+    const ALLOCATION_CALLBACKS& m_AllocationCallbacks;

+    PoolAllocator<Item> m_ItemAllocator;

+    Item* m_pFront;

+    Item* m_pBack;

+    size_t m_Count;

+};

+

+template<typename T>

+List<T>::List(const ALLOCATION_CALLBACKS& allocationCallbacks) :

+    m_AllocationCallbacks(allocationCallbacks),

+    m_ItemAllocator(allocationCallbacks, 128),

+    m_pFront(NULL),

+    m_pBack(NULL),

+    m_Count(0)

+{

+}

+

+template<typename T>

+List<T>::~List()

+{

+    // Intentionally not calling Clear, because that would be unnecessary

+    // computations to return all items to m_ItemAllocator as free.

+}

+

+template<typename T>

+void List<T>::Clear()

+{

+    if(!IsEmpty())

+    {

+        Item* pItem = m_pBack;

+        while(pItem != NULL)

+        {

+            Item* const pPrevItem = pItem->pPrev;

+            m_ItemAllocator.Free(pItem);

+            pItem = pPrevItem;

+        }

+        m_pFront = NULL;

+        m_pBack = NULL;

+        m_Count = 0;

+    }

+}

+

+template<typename T>

+typename List<T>::Item* List<T>::PushBack()

+{

+    Item* const pNewItem = m_ItemAllocator.Alloc();

+    pNewItem->pNext = NULL;

+    if(IsEmpty())

+    {

+        pNewItem->pPrev = NULL;

+        m_pFront = pNewItem;

+        m_pBack = pNewItem;

+        m_Count = 1;

+    }

+    else

+    {

+        pNewItem->pPrev = m_pBack;

+        m_pBack->pNext = pNewItem;

+        m_pBack = pNewItem;

+        ++m_Count;

+    }

+    return pNewItem;

+}

+

+template<typename T>

+typename List<T>::Item* List<T>::PushFront()

+{

+    Item* const pNewItem = m_ItemAllocator.Alloc();

+    pNewItem->pPrev = NULL;

+    if(IsEmpty())

+    {

+        pNewItem->pNext = NULL;

+        m_pFront = pNewItem;

+        m_pBack = pNewItem;

+        m_Count = 1;

+    }

+    else

+    {

+        pNewItem->pNext = m_pFront;

+        m_pFront->pPrev = pNewItem;

+        m_pFront = pNewItem;

+        ++m_Count;

+    }

+    return pNewItem;

+}

+

+template<typename T>

+typename List<T>::Item* List<T>::PushBack(const T& value)

+{

+    Item* const pNewItem = PushBack();

+    pNewItem->Value = value;

+    return pNewItem;

+}

+

+template<typename T>

+typename List<T>::Item* List<T>::PushFront(const T& value)

+{

+    Item* const pNewItem = PushFront();

+    pNewItem->Value = value;

+    return pNewItem;

+}

+

+template<typename T>

+void List<T>::PopBack()

+{

+    D3D12MA_HEAVY_ASSERT(m_Count > 0);

+    Item* const pBackItem = m_pBack;

+    Item* const pPrevItem = pBackItem->pPrev;

+    if(pPrevItem != NULL)

+    {

+        pPrevItem->pNext = NULL;

+    }

+    m_pBack = pPrevItem;

+    m_ItemAllocator.Free(pBackItem);

+    --m_Count;

+}

+

+template<typename T>

+void List<T>::PopFront()

+{

+    D3D12MA_HEAVY_ASSERT(m_Count > 0);

+    Item* const pFrontItem = m_pFront;

+    Item* const pNextItem = pFrontItem->pNext;

+    if(pNextItem != NULL)

+    {

+        pNextItem->pPrev = NULL;

+    }

+    m_pFront = pNextItem;

+    m_ItemAllocator.Free(pFrontItem);

+    --m_Count;

+}

+

+template<typename T>

+void List<T>::Remove(Item* pItem)

+{

+    D3D12MA_HEAVY_ASSERT(pItem != NULL);

+    D3D12MA_HEAVY_ASSERT(m_Count > 0);

+

+    if(pItem->pPrev != NULL)

+    {

+        pItem->pPrev->pNext = pItem->pNext;

+    }

+    else

+    {

+        D3D12MA_HEAVY_ASSERT(m_pFront == pItem);

+        m_pFront = pItem->pNext;

+    }

+

+    if(pItem->pNext != NULL)

+    {

+        pItem->pNext->pPrev = pItem->pPrev;

+    }

+    else

+    {

+        D3D12MA_HEAVY_ASSERT(m_pBack == pItem);

+        m_pBack = pItem->pPrev;

+    }

+

+    m_ItemAllocator.Free(pItem);

+    --m_Count;

+}

+

+template<typename T>

+typename List<T>::Item* List<T>::InsertBefore(Item* pItem)

+{

+    if(pItem != NULL)

+    {

+        Item* const prevItem = pItem->pPrev;

+        Item* const newItem = m_ItemAllocator.Alloc();

+        newItem->pPrev = prevItem;

+        newItem->pNext = pItem;

+        pItem->pPrev = newItem;

+        if(prevItem != NULL)

+        {

+            prevItem->pNext = newItem;

+        }

+        else

+        {

+            D3D12MA_HEAVY_ASSERT(m_pFront == pItem);

+            m_pFront = newItem;

+        }

+        ++m_Count;

+        return newItem;

+    }

+    else

+    {

+        return PushBack();

+    }

+}

+

+template<typename T>

+typename List<T>::Item* List<T>::InsertAfter(Item* pItem)

+{

+    if(pItem != NULL)

+    {

+        Item* const nextItem = pItem->pNext;

+        Item* const newItem = m_ItemAllocator.Alloc();

+        newItem->pNext = nextItem;

+        newItem->pPrev = pItem;

+        pItem->pNext = newItem;

+        if(nextItem != NULL)

+        {

+            nextItem->pPrev = newItem;

+        }

+        else

+        {

+            D3D12MA_HEAVY_ASSERT(m_pBack == pItem);

+            m_pBack = newItem;

+        }

+        ++m_Count;

+        return newItem;

+    }

+    else

+        return PushFront();

+}

+

+template<typename T>

+typename List<T>::Item* List<T>::InsertBefore(List<T>::Item* pItem, const T& value)

+{

+    Item* const newItem = InsertBefore(pItem);

+    newItem->Value = value;

+    return newItem;

+}

+

+template<typename T>

+typename List<T>::Item* List<T>::InsertAfter(List<T>::Item* pItem, const T& value)

+{

+    Item* const newItem = InsertAfter(pItem);

+    newItem->Value = value;

+    return newItem;

+}

+

+////////////////////////////////////////////////////////////////////////////////

+// Private class BlockMetadata and derived classes - declarations

+

+enum SuballocationType

+{

+    SUBALLOCATION_TYPE_FREE = 0,

+    SUBALLOCATION_TYPE_ALLOCATION = 1,

+};

+

+/*

+Represents a region of DeviceMemoryBlock that is either assigned and returned as

+allocated memory block or free.

+*/

+struct Suballocation

+{

+    UINT64 offset;

+    UINT64 size;

+    Allocation* allocation;

+    SuballocationType type;

+};

+

+// Comparator for offsets.

+struct SuballocationOffsetLess

+{

+    bool operator()(const Suballocation& lhs, const Suballocation& rhs) const

+    {

+        return lhs.offset < rhs.offset;

+    }

+};

+struct SuballocationOffsetGreater

+{

+    bool operator()(const Suballocation& lhs, const Suballocation& rhs) const

+    {

+        return lhs.offset > rhs.offset;

+    }

+};

+

+typedef List<Suballocation> SuballocationList;

+

+struct SuballocationItemSizeLess

+{

+    bool operator()(const SuballocationList::iterator lhs, const SuballocationList::iterator rhs) const

+    {

+        return lhs->size < rhs->size;

+    }

+    bool operator()(const SuballocationList::iterator lhs, UINT64 rhsSize) const

+    {

+        return lhs->size < rhsSize;

+    }

+};

+

+/*

+Parameters of planned allocation inside a DeviceMemoryBlock.

+*/

+struct AllocationRequest

+{

+    UINT64 offset;

+    UINT64 sumFreeSize; // Sum size of free items that overlap with proposed allocation.

+    UINT64 sumItemSize; // Sum size of items to make lost that overlap with proposed allocation.

+    SuballocationList::iterator item;

+};

+

+/*

+Data structure used for bookkeeping of allocations and unused ranges of memory

+in a single ID3D12Heap memory block.

+*/

+class BlockMetadata

+{

+public:

+    BlockMetadata(const ALLOCATION_CALLBACKS* allocationCallbacks);

+    virtual ~BlockMetadata() { }

+    virtual void Init(UINT64 size) { m_Size = size; }

+

+    // Validates all data structures inside this object. If not valid, returns false.

+    virtual bool Validate() const = 0;

+    UINT64 GetSize() const { return m_Size; }

+    virtual size_t GetAllocationCount() const = 0;

+    virtual UINT64 GetSumFreeSize() const = 0;

+    virtual UINT64 GetUnusedRangeSizeMax() const = 0;

+    // Returns true if this block is empty - contains only single free suballocation.

+    virtual bool IsEmpty() const = 0;

+

+    // Tries to find a place for suballocation with given parameters inside this block.

+    // If succeeded, fills pAllocationRequest and returns true.

+    // If failed, returns false.

+    virtual bool CreateAllocationRequest(

+        UINT64 allocSize,

+        UINT64 allocAlignment,

+        AllocationRequest* pAllocationRequest) = 0;

+

+    // Makes actual allocation based on request. Request must already be checked and valid.

+    virtual void Alloc(

+        const AllocationRequest& request,

+        UINT64 allocSize,

+        Allocation* Allocation) = 0;

+

+    // Frees suballocation assigned to given memory region.

+    virtual void Free(const Allocation* allocation) = 0;

+    virtual void FreeAtOffset(UINT64 offset) = 0;

+

+protected:

+    const ALLOCATION_CALLBACKS* GetAllocs() const { return m_pAllocationCallbacks; }

+

+private:

+    UINT64 m_Size;

+    const ALLOCATION_CALLBACKS* m_pAllocationCallbacks;

+

+    D3D12MA_CLASS_NO_COPY(BlockMetadata);

+};

+

+class BlockMetadata_Generic : public BlockMetadata

+{

+public:

+    BlockMetadata_Generic(const ALLOCATION_CALLBACKS* allocationCallbacks);

+    virtual ~BlockMetadata_Generic();

+    virtual void Init(UINT64 size);

+

+    virtual bool Validate() const;

+    virtual size_t GetAllocationCount() const { return m_Suballocations.size() - m_FreeCount; }

+    virtual UINT64 GetSumFreeSize() const { return m_SumFreeSize; }

+    virtual UINT64 GetUnusedRangeSizeMax() const;

+    virtual bool IsEmpty() const;

+

+    virtual bool CreateAllocationRequest(

+        UINT64 allocSize,

+        UINT64 allocAlignment,

+        AllocationRequest* pAllocationRequest);

+

+    virtual void Alloc(

+        const AllocationRequest& request,

+        UINT64 allocSize,

+        Allocation* hAllocation);

+

+    virtual void Free(const Allocation* allocation);

+    virtual void FreeAtOffset(UINT64 offset);

+

+private:

+    UINT m_FreeCount;

+    UINT64 m_SumFreeSize;

+    SuballocationList m_Suballocations;

+    // Suballocations that are free and have size greater than certain threshold.

+    // Sorted by size, ascending.

+    Vector<SuballocationList::iterator> m_FreeSuballocationsBySize;

+

+    bool ValidateFreeSuballocationList() const;

+

+    // Checks if requested suballocation with given parameters can be placed in given pFreeSuballocItem.

+    // If yes, fills pOffset and returns true. If no, returns false.

+    bool CheckAllocation(

+        UINT64 allocSize,

+        UINT64 allocAlignment,

+        SuballocationList::const_iterator suballocItem,

+        UINT64* pOffset,

+        UINT64* pSumFreeSize,

+        UINT64* pSumItemSize) const;

+    // Given free suballocation, it merges it with following one, which must also be free.

+    void MergeFreeWithNext(SuballocationList::iterator item);

+    // Releases given suballocation, making it free.

+    // Merges it with adjacent free suballocations if applicable.

+    // Returns iterator to new free suballocation at this place.

+    SuballocationList::iterator FreeSuballocation(SuballocationList::iterator suballocItem);

+    // Given free suballocation, it inserts it into sorted list of

+    // m_FreeSuballocationsBySize if it's suitable.

+    void RegisterFreeSuballocation(SuballocationList::iterator item);

+    // Given free suballocation, it removes it from sorted list of

+    // m_FreeSuballocationsBySize if it's suitable.

+    void UnregisterFreeSuballocation(SuballocationList::iterator item);

+

+    D3D12MA_CLASS_NO_COPY(BlockMetadata_Generic)

+};

+

+////////////////////////////////////////////////////////////////////////////////

+// Private class DeviceMemoryBlock definition

+

+/*

+Represents a single block of device memory (heap) with all the data about its

+regions (aka suballocations, #Allocation), assigned and free.

+

+Thread-safety: This class must be externally synchronized.

+*/

+class DeviceMemoryBlock

+{

+public:

+    BlockMetadata* m_pMetadata;

+

+    DeviceMemoryBlock();

+

+    ~DeviceMemoryBlock()

+    {

+        D3D12MA_ASSERT(m_Heap == NULL);

+    }

+

+    // Always call after construction.

+    void Init(

+        AllocatorPimpl* allocator,

+        BlockVector* blockVector,

+        D3D12_HEAP_TYPE newHeapType,

+        ID3D12Heap* newHeap,

+        UINT64 newSize,

+        UINT id);

+    // Always call before destruction.

+    void Destroy(AllocatorPimpl* allocator);

+

+    BlockVector* GetBlockVector() const { return m_BlockVector; }

+    ID3D12Heap* GetHeap() const { return m_Heap; }

+    D3D12_HEAP_TYPE GetHeapType() const { return m_HeapType; }

+    UINT GetId() const { return m_Id; }

+

+    // Validates all data structures inside this object. If not valid, returns false.

+    bool Validate() const;

+

+private:

+    BlockVector* m_BlockVector;

+    D3D12_HEAP_TYPE m_HeapType;

+    UINT m_Id;

+    ID3D12Heap* m_Heap;

+

+    D3D12MA_CLASS_NO_COPY(DeviceMemoryBlock)

+};

+

+////////////////////////////////////////////////////////////////////////////////

+// Private class BlockVector definition

+

+/*

+Sequence of DeviceMemoryBlock. Represents memory blocks allocated for a specific

+heap type and possibly resource type (if only Tier 1 is supported).

+

+Synchronized internally with a mutex.

+*/

+class BlockVector

+{

+    D3D12MA_CLASS_NO_COPY(BlockVector)

+public:

+    BlockVector(

+        AllocatorPimpl* hAllocator,

+        D3D12_HEAP_TYPE heapType,

+        D3D12_HEAP_FLAGS heapFlags,

+        UINT64 preferredBlockSize,

+        size_t minBlockCount,

+        size_t maxBlockCount,

+        bool explicitBlockSize);

+    ~BlockVector();

+

+    HRESULT CreateMinBlocks();

+

+    UINT GetHeapType() const { return m_HeapType; }

+    UINT64 GetPreferredBlockSize() const { return m_PreferredBlockSize; }

+

+    bool IsEmpty() const { return m_Blocks.empty(); }

+

+    HRESULT Allocate(

+        UINT64 size,

+        UINT64 alignment,

+        const ALLOCATION_DESC& createInfo,

+        size_t allocationCount,

+        Allocation** pAllocations);

+

+    void Free(

+        Allocation* hAllocation);

+

+private:

+    static UINT64 HeapFlagsToAlignment(D3D12_HEAP_FLAGS flags);

+

+    AllocatorPimpl* const m_hAllocator;

+    const D3D12_HEAP_TYPE m_HeapType;

+    const D3D12_HEAP_FLAGS m_HeapFlags;

+    const UINT64 m_PreferredBlockSize;

+    const size_t m_MinBlockCount;

+    const size_t m_MaxBlockCount;

+    const bool m_ExplicitBlockSize;

+    /* There can be at most one allocation that is completely empty - a

+    hysteresis to avoid pessimistic case of alternating creation and destruction

+    of a VkDeviceMemory. */

+    bool m_HasEmptyBlock;

+    D3D12MA_RW_MUTEX m_Mutex;

+    // Incrementally sorted by sumFreeSize, ascending.

+    Vector<DeviceMemoryBlock*> m_Blocks;

+    UINT m_NextBlockId;

+

+    UINT64 CalcMaxBlockSize() const;

+

+    // Finds and removes given block from vector.

+    void Remove(DeviceMemoryBlock* pBlock);

+

+    // Performs single step in sorting m_Blocks. They may not be fully sorted

+    // after this call.

+    void IncrementallySortBlocks();

+

+    HRESULT AllocatePage(

+        UINT64 size,

+        UINT64 alignment,

+        const ALLOCATION_DESC& createInfo,

+        Allocation** pAllocation);

+

+    HRESULT AllocateFromBlock(

+        DeviceMemoryBlock* pBlock,

+        UINT64 size,

+        UINT64 alignment,

+        ALLOCATION_FLAGS allocFlags,

+        Allocation** pAllocation);

+

+    HRESULT CreateBlock(UINT64 blockSize, size_t* pNewBlockIndex);

+    HRESULT CreateD3d12Heap(ID3D12Heap*& outHeap, UINT64 size) const;

+};

+

+////////////////////////////////////////////////////////////////////////////////

+// Private class AllocatorPimpl definition

+

+static const UINT DEFAULT_POOL_MAX_COUNT = 9;

+

+class AllocatorPimpl

+{

+public:

+    AllocatorPimpl(const ALLOCATION_CALLBACKS& allocationCallbacks, const ALLOCATOR_DESC& desc);

+    HRESULT Init();

+    ~AllocatorPimpl();

+

+    ID3D12Device* GetDevice() const { return m_Device; }

+    // Shortcut for "Allocation Callbacks", because this function is called so often.

+    const ALLOCATION_CALLBACKS& GetAllocs() const { return m_AllocationCallbacks; }

+    const D3D12_FEATURE_DATA_D3D12_OPTIONS& GetD3D12Options() const { return m_D3D12Options; }

+    bool SupportsResourceHeapTier2() const { return m_D3D12Options.ResourceHeapTier >= D3D12_RESOURCE_HEAP_TIER_2; }

+    bool UseMutex() const { return m_UseMutex; }

+

+    HRESULT CreateResource(

+        const ALLOCATION_DESC* pAllocDesc,

+        const D3D12_RESOURCE_DESC* pResourceDesc,

+        D3D12_RESOURCE_STATES InitialResourceState,

+        const D3D12_CLEAR_VALUE *pOptimizedClearValue,

+        Allocation** ppAllocation,

+        REFIID riidResource,

+        void** ppvResource);

+

+    // Unregisters allocation from the collection of dedicated allocations.

+    // Allocation object must be deleted externally afterwards.

+    void FreeCommittedMemory(Allocation* allocation);

+    // Unregisters allocation from the collection of placed allocations.

+    // Allocation object must be deleted externally afterwards.

+    void FreePlacedMemory(Allocation* allocation);

+

+private:

+    friend class Allocator;

+

+    /*

+    Heuristics that decides whether a resource should better be placed in its own,

+    dedicated allocation (committed resource rather than placed resource).

+    */

+    static bool PrefersCommittedAllocation(const D3D12_RESOURCE_DESC& resourceDesc);

+

+    bool m_UseMutex;

+    ID3D12Device* m_Device;

+    UINT64 m_PreferredBlockSize;

+    ALLOCATION_CALLBACKS m_AllocationCallbacks;

+

+    D3D12_FEATURE_DATA_D3D12_OPTIONS m_D3D12Options;

+

+    typedef Vector<Allocation*> AllocationVectorType;

+    AllocationVectorType* m_pCommittedAllocations[HEAP_TYPE_COUNT];

+    D3D12MA_RW_MUTEX m_CommittedAllocationsMutex[HEAP_TYPE_COUNT];

+

+    // Default pools.

+    BlockVector* m_BlockVectors[DEFAULT_POOL_MAX_COUNT];

+

+    // Allocates and registers new committed resource with implicit heap, as dedicated allocation.

+    // Creates and returns Allocation objects.

+    HRESULT AllocateCommittedMemory(

+        const ALLOCATION_DESC* pAllocDesc,

+        const D3D12_RESOURCE_DESC* pResourceDesc,

+        const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo,

+        D3D12_RESOURCE_STATES InitialResourceState,

+        const D3D12_CLEAR_VALUE *pOptimizedClearValue,

+        Allocation** ppAllocation,

+        REFIID riidResource,

+        void** ppvResource);

+

+    /*

+    If SupportsResourceHeapTier2():

+        0: D3D12_HEAP_TYPE_DEFAULT

+        1: D3D12_HEAP_TYPE_UPLOAD

+        2: D3D12_HEAP_TYPE_READBACK

+    else:

+        0: D3D12_HEAP_TYPE_DEFAULT + buffer

+        1: D3D12_HEAP_TYPE_DEFAULT + texture

+        2: D3D12_HEAP_TYPE_DEFAULT + texture RT or DS

+        3: D3D12_HEAP_TYPE_UPLOAD + buffer

+        4: D3D12_HEAP_TYPE_UPLOAD + texture

+        5: D3D12_HEAP_TYPE_UPLOAD + texture RT or DS

+        6: D3D12_HEAP_TYPE_READBACK + buffer

+        7: D3D12_HEAP_TYPE_READBACK + texture

+        8: D3D12_HEAP_TYPE_READBACK + texture RT or DS

+    */

+    UINT CalcDefaultPoolCount() const;

+    UINT CalcDefaultPoolIndex(const ALLOCATION_DESC& allocDesc, const D3D12_RESOURCE_DESC& resourceDesc) const;

+    void CalcDefaultPoolParams(D3D12_HEAP_TYPE& outHeapType, D3D12_HEAP_FLAGS& outHeapFlags, UINT index) const;

+};

+

+////////////////////////////////////////////////////////////////////////////////

+// Private class BlockMetadata implementation

+

+BlockMetadata::BlockMetadata(const ALLOCATION_CALLBACKS* allocationCallbacks) :

+    m_Size(0),

+    m_pAllocationCallbacks(allocationCallbacks)

+{

+    D3D12MA_ASSERT(allocationCallbacks);

+}

+

+////////////////////////////////////////////////////////////////////////////////

+// Private class BlockMetadata_Generic implementation

+

+BlockMetadata_Generic::BlockMetadata_Generic(const ALLOCATION_CALLBACKS* allocationCallbacks) :

+    BlockMetadata(allocationCallbacks),

+    m_FreeCount(0),

+    m_SumFreeSize(0),

+    m_Suballocations(*allocationCallbacks),

+    m_FreeSuballocationsBySize(*allocationCallbacks)

+{

+    D3D12MA_ASSERT(allocationCallbacks);

+}

+

+BlockMetadata_Generic::~BlockMetadata_Generic()

+{

+}

+

+void BlockMetadata_Generic::Init(UINT64 size)

+{

+    BlockMetadata::Init(size);

+

+    m_FreeCount = 1;

+    m_SumFreeSize = size;

+

+    Suballocation suballoc = {};

+    suballoc.offset = 0;

+    suballoc.size = size;

+    suballoc.type = SUBALLOCATION_TYPE_FREE;

+    suballoc.allocation = NULL;

+

+    D3D12MA_ASSERT(size > MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER);

+    m_Suballocations.push_back(suballoc);

+    SuballocationList::iterator suballocItem = m_Suballocations.end();

+    --suballocItem;

+    m_FreeSuballocationsBySize.push_back(suballocItem);

+}

+

+bool BlockMetadata_Generic::Validate() const

+{

+    D3D12MA_VALIDATE(!m_Suballocations.empty());

+

+    // Expected offset of new suballocation as calculated from previous ones.

+    UINT64 calculatedOffset = 0;

+    // Expected number of free suballocations as calculated from traversing their list.

+    UINT calculatedFreeCount = 0;

+    // Expected sum size of free suballocations as calculated from traversing their list.

+    UINT64 calculatedSumFreeSize = 0;

+    // Expected number of free suballocations that should be registered in

+    // m_FreeSuballocationsBySize calculated from traversing their list.

+    size_t freeSuballocationsToRegister = 0;

+    // True if previous visited suballocation was free.

+    bool prevFree = false;

+

+    for(SuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();

+        suballocItem != m_Suballocations.cend();

+        ++suballocItem)

+    {

+        const Suballocation& subAlloc = *suballocItem;

+

+        // Actual offset of this suballocation doesn't match expected one.

+        D3D12MA_VALIDATE(subAlloc.offset == calculatedOffset);

+

+        const bool currFree = (subAlloc.type == SUBALLOCATION_TYPE_FREE);

+        // Two adjacent free suballocations are invalid. They should be merged.

+        D3D12MA_VALIDATE(!prevFree || !currFree);

+

+        D3D12MA_VALIDATE(currFree == (subAlloc.allocation == NULL));

+

+        if(currFree)

+        {

+            calculatedSumFreeSize += subAlloc.size;

+            ++calculatedFreeCount;

+            if(subAlloc.size >= MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)

+            {

+                ++freeSuballocationsToRegister;

+            }

+

+            // Margin required between allocations - every free space must be at least that large.

+            D3D12MA_VALIDATE(subAlloc.size >= D3D12MA_DEBUG_MARGIN);

+        }

+        else

+        {

+            D3D12MA_VALIDATE(subAlloc.allocation->GetOffset() == subAlloc.offset);

+            D3D12MA_VALIDATE(subAlloc.allocation->GetSize() == subAlloc.size);

+

+            // Margin required between allocations - previous allocation must be free.

+            D3D12MA_VALIDATE(D3D12MA_DEBUG_MARGIN == 0 || prevFree);

+        }

+

+        calculatedOffset += subAlloc.size;

+        prevFree = currFree;

+    }

+

+    // Number of free suballocations registered in m_FreeSuballocationsBySize doesn't

+    // match expected one.

+    D3D12MA_VALIDATE(m_FreeSuballocationsBySize.size() == freeSuballocationsToRegister);

+

+    UINT64 lastSize = 0;

+    for(size_t i = 0; i < m_FreeSuballocationsBySize.size(); ++i)

+    {

+        SuballocationList::iterator suballocItem = m_FreeSuballocationsBySize[i];

+

+        // Only free suballocations can be registered in m_FreeSuballocationsBySize.

+        D3D12MA_VALIDATE(suballocItem->type == SUBALLOCATION_TYPE_FREE);

+        // They must be sorted by size ascending.

+        D3D12MA_VALIDATE(suballocItem->size >= lastSize);

+

+        lastSize = suballocItem->size;

+    }

+

+    // Check if totals match calculacted values.

+    D3D12MA_VALIDATE(ValidateFreeSuballocationList());

+    D3D12MA_VALIDATE(calculatedOffset == GetSize());

+    D3D12MA_VALIDATE(calculatedSumFreeSize == m_SumFreeSize);

+    D3D12MA_VALIDATE(calculatedFreeCount == m_FreeCount);

+

+    return true;

+}

+

+UINT64 BlockMetadata_Generic::GetUnusedRangeSizeMax() const

+{

+    if(!m_FreeSuballocationsBySize.empty())

+    {

+        return m_FreeSuballocationsBySize.back()->size;

+    }

+    else

+    {

+        return 0;

+    }

+}

+

+bool BlockMetadata_Generic::IsEmpty() const

+{

+    return (m_Suballocations.size() == 1) && (m_FreeCount == 1);

+}

+

+bool BlockMetadata_Generic::CreateAllocationRequest(

+    UINT64 allocSize,

+    UINT64 allocAlignment,

+    AllocationRequest* pAllocationRequest)

+{

+    D3D12MA_ASSERT(allocSize > 0);

+    D3D12MA_ASSERT(pAllocationRequest != NULL);

+    D3D12MA_HEAVY_ASSERT(Validate());

+

+    // There is not enough total free space in this block to fullfill the request: Early return.

+    if(m_SumFreeSize < allocSize + 2 * D3D12MA_DEBUG_MARGIN)

+    {

+        return false;

+    }

+

+    // New algorithm, efficiently searching freeSuballocationsBySize.

+    const size_t freeSuballocCount = m_FreeSuballocationsBySize.size();

+    if(freeSuballocCount > 0)

+    {

+        // Find first free suballocation with size not less than allocSize + 2 * D3D12MA_DEBUG_MARGIN.

+        SuballocationList::iterator* const it = BinaryFindFirstNotLess(

+            m_FreeSuballocationsBySize.data(),

+            m_FreeSuballocationsBySize.data() + freeSuballocCount,

+            allocSize + 2 * D3D12MA_DEBUG_MARGIN,

+            SuballocationItemSizeLess());

+        size_t index = it - m_FreeSuballocationsBySize.data();

+        for(; index < freeSuballocCount; ++index)

+        {

+            if(CheckAllocation(

+                allocSize,

+                allocAlignment,

+                m_FreeSuballocationsBySize[index],

+                &pAllocationRequest->offset,

+                &pAllocationRequest->sumFreeSize,

+                &pAllocationRequest->sumItemSize))

+            {

+                pAllocationRequest->item = m_FreeSuballocationsBySize[index];

+                return true;

+            }

+        }

+    }

+

+    return false;

+}

+

+void BlockMetadata_Generic::Alloc(

+    const AllocationRequest& request,

+    UINT64 allocSize,

+    Allocation* allocation)

+{

+    D3D12MA_ASSERT(request.item != m_Suballocations.end());

+    Suballocation& suballoc = *request.item;

+    // Given suballocation is a free block.

+    D3D12MA_ASSERT(suballoc.type == SUBALLOCATION_TYPE_FREE);

+    // Given offset is inside this suballocation.

+    D3D12MA_ASSERT(request.offset >= suballoc.offset);

+    const UINT64 paddingBegin = request.offset - suballoc.offset;

+    D3D12MA_ASSERT(suballoc.size >= paddingBegin + allocSize);

+    const UINT64 paddingEnd = suballoc.size - paddingBegin - allocSize;

+

+    // Unregister this free suballocation from m_FreeSuballocationsBySize and update

+    // it to become used.

+    UnregisterFreeSuballocation(request.item);

+

+    suballoc.offset = request.offset;

+    suballoc.size = allocSize;

+    suballoc.type = SUBALLOCATION_TYPE_ALLOCATION;

+    suballoc.allocation = allocation;

+

+    // If there are any free bytes remaining at the end, insert new free suballocation after current one.

+    if(paddingEnd)

+    {

+        Suballocation paddingSuballoc = {};

+        paddingSuballoc.offset = request.offset + allocSize;

+        paddingSuballoc.size = paddingEnd;

+        paddingSuballoc.type = SUBALLOCATION_TYPE_FREE;

+        SuballocationList::iterator next = request.item;

+        ++next;

+        const SuballocationList::iterator paddingEndItem =

+            m_Suballocations.insert(next, paddingSuballoc);

+        RegisterFreeSuballocation(paddingEndItem);

+    }

+

+    // If there are any free bytes remaining at the beginning, insert new free suballocation before current one.

+    if(paddingBegin)

+    {

+        Suballocation paddingSuballoc = {};

+        paddingSuballoc.offset = request.offset - paddingBegin;

+        paddingSuballoc.size = paddingBegin;

+        paddingSuballoc.type = SUBALLOCATION_TYPE_FREE;

+        const SuballocationList::iterator paddingBeginItem =

+            m_Suballocations.insert(request.item, paddingSuballoc);

+        RegisterFreeSuballocation(paddingBeginItem);

+    }

+

+    // Update totals.

+    m_FreeCount = m_FreeCount - 1;

+    if(paddingBegin > 0)

+    {

+        ++m_FreeCount;

+    }

+    if(paddingEnd > 0)

+    {

+        ++m_FreeCount;

+    }

+    m_SumFreeSize -= allocSize;

+}

+

+void BlockMetadata_Generic::Free(const Allocation* allocation)

+{

+    for(SuballocationList::iterator suballocItem = m_Suballocations.begin();

+        suballocItem != m_Suballocations.end();

+        ++suballocItem)

+    {

+        Suballocation& suballoc = *suballocItem;

+        if(suballoc.allocation == allocation)

+        {

+            FreeSuballocation(suballocItem);

+            D3D12MA_HEAVY_ASSERT(Validate());

+            return;

+        }

+    }

+    D3D12MA_ASSERT(0 && "Not found!");

+}

+

+void BlockMetadata_Generic::FreeAtOffset(UINT64 offset)

+{

+    for(SuballocationList::iterator suballocItem = m_Suballocations.begin();

+        suballocItem != m_Suballocations.end();

+        ++suballocItem)

+    {

+        Suballocation& suballoc = *suballocItem;

+        if(suballoc.offset == offset)

+        {

+            FreeSuballocation(suballocItem);

+            return;

+        }

+    }

+    D3D12MA_ASSERT(0 && "Not found!");

+}

+

+bool BlockMetadata_Generic::ValidateFreeSuballocationList() const

+{

+    UINT64 lastSize = 0;

+    for(size_t i = 0, count = m_FreeSuballocationsBySize.size(); i < count; ++i)

+    {

+        const SuballocationList::iterator it = m_FreeSuballocationsBySize[i];

+

+        D3D12MA_VALIDATE(it->type == SUBALLOCATION_TYPE_FREE);

+        D3D12MA_VALIDATE(it->size >= MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER);

+        D3D12MA_VALIDATE(it->size >= lastSize);

+        lastSize = it->size;

+    }

+    return true;

+}

+

+bool BlockMetadata_Generic::CheckAllocation(

+    UINT64 allocSize,

+    UINT64 allocAlignment,

+    SuballocationList::const_iterator suballocItem,

+    UINT64* pOffset,

+    UINT64* pSumFreeSize,

+    UINT64* pSumItemSize) const

+{

+    D3D12MA_ASSERT(allocSize > 0);

+    D3D12MA_ASSERT(suballocItem != m_Suballocations.cend());

+    D3D12MA_ASSERT(pOffset != NULL);

+

+    *pSumFreeSize = 0;

+    *pSumItemSize = 0;

+

+    const Suballocation& suballoc = *suballocItem;

+    D3D12MA_ASSERT(suballoc.type == SUBALLOCATION_TYPE_FREE);

+

+    *pSumFreeSize = suballoc.size;

+

+    // Size of this suballocation is too small for this request: Early return.

+    if(suballoc.size < allocSize)

+    {

+        return false;

+    }

+

+    // Start from offset equal to beginning of this suballocation.

+    *pOffset = suballoc.offset;

+

+    // Apply D3D12MA_DEBUG_MARGIN at the beginning.

+    if(D3D12MA_DEBUG_MARGIN > 0)

+    {

+        *pOffset += D3D12MA_DEBUG_MARGIN;

+    }

+

+    // Apply alignment.

+    *pOffset = AlignUp(*pOffset, allocAlignment);

+

+    // Calculate padding at the beginning based on current offset.

+    const UINT64 paddingBegin = *pOffset - suballoc.offset;

+

+    // Calculate required margin at the end.

+    const UINT64 requiredEndMargin = D3D12MA_DEBUG_MARGIN;

+

+    // Fail if requested size plus margin before and after is bigger than size of this suballocation.

+    if(paddingBegin + allocSize + requiredEndMargin > suballoc.size)

+    {

+        return false;

+    }

+

+    // All tests passed: Success. pOffset is already filled.

+    return true;

+}

+

+void BlockMetadata_Generic::MergeFreeWithNext(SuballocationList::iterator item)

+{

+    D3D12MA_ASSERT(item != m_Suballocations.end());

+    D3D12MA_ASSERT(item->type == SUBALLOCATION_TYPE_FREE);

+

+    SuballocationList::iterator nextItem = item;

+    ++nextItem;

+    D3D12MA_ASSERT(nextItem != m_Suballocations.end());

+    D3D12MA_ASSERT(nextItem->type == SUBALLOCATION_TYPE_FREE);

+

+    item->size += nextItem->size;

+    --m_FreeCount;

+    m_Suballocations.erase(nextItem);

+}

+

+SuballocationList::iterator BlockMetadata_Generic::FreeSuballocation(SuballocationList::iterator suballocItem)

+{

+    // Change this suballocation to be marked as free.

+    Suballocation& suballoc = *suballocItem;

+    suballoc.type = SUBALLOCATION_TYPE_FREE;

+    suballoc.allocation = NULL;

+

+    // Update totals.

+    ++m_FreeCount;

+    m_SumFreeSize += suballoc.size;

+

+    // Merge with previous and/or next suballocation if it's also free.

+    bool mergeWithNext = false;

+    bool mergeWithPrev = false;

+

+    SuballocationList::iterator nextItem = suballocItem;

+    ++nextItem;

+    if((nextItem != m_Suballocations.end()) && (nextItem->type == SUBALLOCATION_TYPE_FREE))

+    {

+        mergeWithNext = true;

+    }

+

+    SuballocationList::iterator prevItem = suballocItem;

+    if(suballocItem != m_Suballocations.begin())

+    {

+        --prevItem;

+        if(prevItem->type == SUBALLOCATION_TYPE_FREE)

+        {

+            mergeWithPrev = true;

+        }

+    }

+

+    if(mergeWithNext)

+    {

+        UnregisterFreeSuballocation(nextItem);

+        MergeFreeWithNext(suballocItem);

+    }

+

+    if(mergeWithPrev)

+    {

+        UnregisterFreeSuballocation(prevItem);

+        MergeFreeWithNext(prevItem);

+        RegisterFreeSuballocation(prevItem);

+        return prevItem;

+    }

+    else

+    {

+        RegisterFreeSuballocation(suballocItem);

+        return suballocItem;

+    }

+}

+

+void BlockMetadata_Generic::RegisterFreeSuballocation(SuballocationList::iterator item)

+{

+    D3D12MA_ASSERT(item->type == SUBALLOCATION_TYPE_FREE);

+    D3D12MA_ASSERT(item->size > 0);

+

+    // You may want to enable this validation at the beginning or at the end of

+    // this function, depending on what do you want to check.

+    D3D12MA_HEAVY_ASSERT(ValidateFreeSuballocationList());

+

+    if(item->size >= MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)

+    {

+        if(m_FreeSuballocationsBySize.empty())

+        {

+            m_FreeSuballocationsBySize.push_back(item);

+        }

+        else

+        {

+            m_FreeSuballocationsBySize.InsertSorted(item, SuballocationItemSizeLess());

+        }

+    }

+

+    //D3D12MA_HEAVY_ASSERT(ValidateFreeSuballocationList());

+}

+

+

+void BlockMetadata_Generic::UnregisterFreeSuballocation(SuballocationList::iterator item)

+{

+    D3D12MA_ASSERT(item->type == SUBALLOCATION_TYPE_FREE);

+    D3D12MA_ASSERT(item->size > 0);

+

+    // You may want to enable this validation at the beginning or at the end of

+    // this function, depending on what do you want to check.

+    D3D12MA_HEAVY_ASSERT(ValidateFreeSuballocationList());

+

+    if(item->size >= MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)

+    {

+        SuballocationList::iterator* const it = BinaryFindFirstNotLess(

+            m_FreeSuballocationsBySize.data(),

+            m_FreeSuballocationsBySize.data() + m_FreeSuballocationsBySize.size(),

+            item,

+            SuballocationItemSizeLess());

+        for(size_t index = it - m_FreeSuballocationsBySize.data();

+            index < m_FreeSuballocationsBySize.size();

+            ++index)

+        {

+            if(m_FreeSuballocationsBySize[index] == item)

+            {

+                m_FreeSuballocationsBySize.remove(index);

+                return;

+            }

+            D3D12MA_ASSERT((m_FreeSuballocationsBySize[index]->size == item->size) && "Not found.");

+        }

+        D3D12MA_ASSERT(0 && "Not found.");

+    }

+

+    //D3D12MA_HEAVY_ASSERT(ValidateFreeSuballocationList());

+}

+

+////////////////////////////////////////////////////////////////////////////////

+// Private class DeviceMemoryBlock implementation

+

+DeviceMemoryBlock::DeviceMemoryBlock() :

+    m_pMetadata(NULL),

+    m_BlockVector(NULL),

+    m_HeapType(D3D12_HEAP_TYPE_CUSTOM),

+    m_Id(0),

+    m_Heap(NULL)

+{

+}

+

+void DeviceMemoryBlock::Init(

+    AllocatorPimpl* allocator,

+    BlockVector* blockVector,

+    D3D12_HEAP_TYPE newHeapType,

+    ID3D12Heap* newHeap,

+    UINT64 newSize,

+    UINT id)

+{

+    D3D12MA_ASSERT(m_Heap == NULL);

+

+    m_BlockVector = blockVector;

+    m_HeapType = newHeapType;

+    m_Id = id;

+    m_Heap = newHeap;

+

+    const ALLOCATION_CALLBACKS& allocs = allocator->GetAllocs();

+

+    m_pMetadata = D3D12MA_NEW(allocs, BlockMetadata_Generic)(&allocs);

+    m_pMetadata->Init(newSize);

+}

+

+void DeviceMemoryBlock::Destroy(AllocatorPimpl* allocator)

+{

+    // THIS IS THE MOST IMPORTANT ASSERT IN THE ENTIRE LIBRARY!

+    // Hitting it means you have some memory leak - unreleased Allocation objects.

+    D3D12MA_ASSERT(m_pMetadata->IsEmpty() && "Some allocations were not freed before destruction of this memory block!");

+

+    D3D12MA_ASSERT(m_Heap != NULL);

+    m_Heap->Release();

+    m_Heap = NULL;

+

+    D3D12MA_DELETE(allocator->GetAllocs(), m_pMetadata);

+    m_pMetadata = NULL;

+}

+

+bool DeviceMemoryBlock::Validate() const

+{

+    D3D12MA_VALIDATE(m_Heap && m_pMetadata && m_pMetadata->GetSize() != 0);

+    return m_pMetadata->Validate();

+}

+

+////////////////////////////////////////////////////////////////////////////////

+// Private class BlockVector implementation

+

+BlockVector::BlockVector(

+    AllocatorPimpl* hAllocator,

+    D3D12_HEAP_TYPE heapType,

+    D3D12_HEAP_FLAGS heapFlags,

+    UINT64 preferredBlockSize,

+    size_t minBlockCount,

+    size_t maxBlockCount,

+    bool explicitBlockSize) :

+    m_hAllocator(hAllocator),

+    m_HeapType(heapType),

+    m_HeapFlags(heapFlags),

+    m_PreferredBlockSize(preferredBlockSize),

+    m_MinBlockCount(minBlockCount),

+    m_MaxBlockCount(maxBlockCount),

+    m_ExplicitBlockSize(explicitBlockSize),

+    m_HasEmptyBlock(false),

+    m_Blocks(hAllocator->GetAllocs()),

+    m_NextBlockId(0)

+{

+}

+

+BlockVector::~BlockVector()

+{

+    for(size_t i = m_Blocks.size(); i--; )

+    {

+        m_Blocks[i]->Destroy(m_hAllocator);

+        D3D12MA_DELETE(m_hAllocator->GetAllocs(), m_Blocks[i]);

+    }

+}

+

+HRESULT BlockVector::CreateMinBlocks()

+{

+    for(size_t i = 0; i < m_MinBlockCount; ++i)

+    {

+        HRESULT hr = CreateBlock(m_PreferredBlockSize, NULL);

+        if(FAILED(hr))

+        {

+            return hr;

+        }

+    }

+    return S_OK;

+}

+

+HRESULT BlockVector::Allocate(

+    UINT64 size,

+    UINT64 alignment,

+    const ALLOCATION_DESC& createInfo,

+    size_t allocationCount,

+    Allocation** pAllocations)

+{

+    size_t allocIndex;

+    HRESULT hr = S_OK;

+

+    {

+        MutexLockWrite lock(m_Mutex, m_hAllocator->UseMutex());

+        for(allocIndex = 0; allocIndex < allocationCount; ++allocIndex)

+        {

+            hr = AllocatePage(

+                size,

+                alignment,

+                createInfo,

+                pAllocations + allocIndex);

+            if(FAILED(hr))

+            {

+                break;

+            }

+        }

+    }

+

+    if(FAILED(hr))

+    {

+        // Free all already created allocations.

+        while(allocIndex--)

+        {

+            Free(pAllocations[allocIndex]);

+        }

+        memset(pAllocations, 0, sizeof(Allocation*) * allocationCount);

+    }

+

+    return hr;

+}

+

+HRESULT BlockVector::AllocatePage(

+    UINT64 size,

+    UINT64 alignment,

+    const ALLOCATION_DESC& createInfo,

+    Allocation** pAllocation)

+{

+    // Early reject: requested allocation size is larger that maximum block size for this block vector.

+    if(size + 2 * D3D12MA_DEBUG_MARGIN > m_PreferredBlockSize)

+    {

+        return E_OUTOFMEMORY;

+    }

+

+    const bool canCreateNewBlock =

+        ((createInfo.Flags & ALLOCATION_FLAG_NEVER_ALLOCATE) == 0) &&

+        (m_Blocks.size() < m_MaxBlockCount);

+

+    if(canCreateNewBlock)

+    {

+        // 1. Search existing allocations. Try to allocate without making other allocations lost.

+        ALLOCATION_FLAGS allocFlagsCopy = createInfo.Flags;

+

+        {

+            {

+                // Forward order in m_Blocks - prefer blocks with smallest amount of free space.

+                for(size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex )

+                {

+                    DeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];

+                    D3D12MA_ASSERT(pCurrBlock);

+                    HRESULT hr = AllocateFromBlock(

+                        pCurrBlock,

+                        size,

+                        alignment,

+                        allocFlagsCopy,

+                        pAllocation);

+                    if(SUCCEEDED(hr))

+                    {

+                        return hr;

+                    }

+                }

+            }

+        }

+

+        // 2. Try to create new block.

+        if(canCreateNewBlock)

+        {

+            // Calculate optimal size for new block.

+            UINT64 newBlockSize = m_PreferredBlockSize;

+            UINT newBlockSizeShift = 0;

+            const UINT NEW_BLOCK_SIZE_SHIFT_MAX = 3;

+

+            if(!m_ExplicitBlockSize)

+            {

+                // Allocate 1/8, 1/4, 1/2 as first blocks.

+                const UINT64 maxExistingBlockSize = CalcMaxBlockSize();

+                for(UINT i = 0; i < NEW_BLOCK_SIZE_SHIFT_MAX; ++i)

+                {

+                    const UINT64 smallerNewBlockSize = newBlockSize / 2;

+                    if(smallerNewBlockSize > maxExistingBlockSize && smallerNewBlockSize >= size * 2)

+                    {

+                        newBlockSize = smallerNewBlockSize;

+                        ++newBlockSizeShift;

+                    }

+                    else

+                    {

+                        break;

+                    }

+                }

+            }

+

+            size_t newBlockIndex = 0;

+            HRESULT hr = CreateBlock(newBlockSize, &newBlockIndex);

+            // Allocation of this size failed? Try 1/2, 1/4, 1/8 of m_PreferredBlockSize.

+            if(!m_ExplicitBlockSize)

+            {

+                while(FAILED(hr) && newBlockSizeShift < NEW_BLOCK_SIZE_SHIFT_MAX)

+                {

+                    const UINT64 smallerNewBlockSize = newBlockSize / 2;

+                    if(smallerNewBlockSize >= size)

+                    {

+                        newBlockSize = smallerNewBlockSize;

+                        ++newBlockSizeShift;

+                        hr = CreateBlock(newBlockSize, &newBlockIndex);

+                    }

+                    else

+                    {

+                        break;

+                    }

+                }

+            }

+

+            if(SUCCEEDED(hr))

+            {

+                DeviceMemoryBlock* const pBlock = m_Blocks[newBlockIndex];

+                D3D12MA_ASSERT(pBlock->m_pMetadata->GetSize() >= size);

+

+                hr = AllocateFromBlock(

+                    pBlock,

+                    size,

+                    alignment,

+                    allocFlagsCopy,

+                    pAllocation);

+                if(SUCCEEDED(hr))

+                {

+                    return hr;

+                }

+                else

+                {

+                    // Allocation from new block failed, possibly due to D3D12MA_DEBUG_MARGIN or alignment.

+                    return E_OUTOFMEMORY;

+                }

+            }

+        }

+    }

+

+    return E_OUTOFMEMORY;

+}

+

+void BlockVector::Free(Allocation* hAllocation)

+{

+    DeviceMemoryBlock* pBlockToDelete = NULL;

+

+    // Scope for lock.

+    {

+        MutexLockWrite lock(m_Mutex, m_hAllocator->UseMutex());

+

+        DeviceMemoryBlock* pBlock = hAllocation->GetBlock();

+

+        pBlock->m_pMetadata->Free(hAllocation);

+        D3D12MA_HEAVY_ASSERT(pBlock->Validate());

+

+        // pBlock became empty after this deallocation.

+        if(pBlock->m_pMetadata->IsEmpty())

+        {

+            // Already has empty Allocation. We don't want to have two, so delete this one.

+            if(m_HasEmptyBlock && m_Blocks.size() > m_MinBlockCount)

+            {

+                pBlockToDelete = pBlock;

+                Remove(pBlock);

+            }

+            // We now have first empty block.

+            else

+            {

+                m_HasEmptyBlock = true;

+            }

+        }

+        // pBlock didn't become empty, but we have another empty block - find and free that one.

+        // (This is optional, heuristics.)

+        else if(m_HasEmptyBlock)

+        {

+            DeviceMemoryBlock* pLastBlock = m_Blocks.back();

+            if(pLastBlock->m_pMetadata->IsEmpty() && m_Blocks.size() > m_MinBlockCount)

+            {

+                pBlockToDelete = pLastBlock;

+                m_Blocks.pop_back();

+                m_HasEmptyBlock = false;

+            }

+        }

+

+        IncrementallySortBlocks();

+    }

+

+    // Destruction of a free Allocation. Deferred until this point, outside of mutex

+    // lock, for performance reason.

+    if(pBlockToDelete != NULL)

+    {

+        pBlockToDelete->Destroy(m_hAllocator);

+        D3D12MA_DELETE(m_hAllocator->GetAllocs(), pBlockToDelete);

+    }

+}

+

+UINT64 BlockVector::HeapFlagsToAlignment(D3D12_HEAP_FLAGS flags)

+{

+    /*

+    Documentation of D3D12_HEAP_DESC structure says:

+

+    - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT   defined as 64KB.

+    - D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT   defined as 4MB. An

+      application must decide whether the heap will contain multi-sample

+      anti-aliasing (MSAA), in which case, the application must choose [this flag].

+

+    https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/ns-d3d12-d3d12_heap_desc

+    */

+

+    const D3D12_HEAP_FLAGS denyAllTexturesFlags =

+        D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES;

+    const bool canContainAnyTextures =

+        (flags & denyAllTexturesFlags) != denyAllTexturesFlags;

+    return canContainAnyTextures ?

+        D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;

+}

+

+UINT64 BlockVector::CalcMaxBlockSize() const

+{

+    UINT64 result = 0;

+    for(size_t i = m_Blocks.size(); i--; )

+    {

+        result = D3D12MA_MAX(result, m_Blocks[i]->m_pMetadata->GetSize());

+        if(result >= m_PreferredBlockSize)

+        {

+            break;

+        }

+    }

+    return result;

+}

+

+void BlockVector::Remove(DeviceMemoryBlock* pBlock)

+{

+    for(UINT blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)

+    {

+        if(m_Blocks[blockIndex] == pBlock)

+        {

+            m_Blocks.remove(blockIndex);

+            return;

+        }

+    }

+    D3D12MA_ASSERT(0);

+}

+

+void BlockVector::IncrementallySortBlocks()

+{

+    // Bubble sort only until first swap.

+    for(size_t i = 1; i < m_Blocks.size(); ++i)

+    {

+        if(m_Blocks[i - 1]->m_pMetadata->GetSumFreeSize() > m_Blocks[i]->m_pMetadata->GetSumFreeSize())

+        {

+            D3D12MA_SWAP(m_Blocks[i - 1], m_Blocks[i]);

+            return;

+        }

+    }

+}

+

+HRESULT BlockVector::AllocateFromBlock(

+    DeviceMemoryBlock* pBlock,

+    UINT64 size,

+    UINT64 alignment,

+    ALLOCATION_FLAGS allocFlags,

+    Allocation** pAllocation)

+{

+    AllocationRequest currRequest = {};

+    if(pBlock->m_pMetadata->CreateAllocationRequest(

+        size,

+        alignment,

+        &currRequest))

+    {

+        // We no longer have an empty Allocation.

+        if(pBlock->m_pMetadata->IsEmpty())

+        {

+            m_HasEmptyBlock = false;

+        }

+

+        *pAllocation = D3D12MA_NEW(m_hAllocator->GetAllocs(), Allocation)();

+        pBlock->m_pMetadata->Alloc(currRequest, size, *pAllocation);

+        (*pAllocation)->InitPlaced(

+            m_hAllocator,

+            size,

+            currRequest.offset,

+            alignment,

+            pBlock);

+        D3D12MA_HEAVY_ASSERT(pBlock->Validate());

+        return S_OK;

+    }

+    return E_OUTOFMEMORY;

+}

+

+HRESULT BlockVector::CreateBlock(UINT64 blockSize, size_t* pNewBlockIndex)

+{

+    ID3D12Heap* heap = NULL;

+    HRESULT hr = CreateD3d12Heap(heap, blockSize);

+    if(FAILED(hr))

+    {

+        return hr;

+    }

+

+    DeviceMemoryBlock* const pBlock = D3D12MA_NEW(m_hAllocator->GetAllocs(), DeviceMemoryBlock)();

+    pBlock->Init(

+        m_hAllocator,

+        this,

+        m_HeapType,

+        heap,

+        blockSize,

+        m_NextBlockId++);

+

+    m_Blocks.push_back(pBlock);

+    if(pNewBlockIndex != NULL)

+    {

+        *pNewBlockIndex = m_Blocks.size() - 1;

+    }

+

+    return hr;

+}

+

+HRESULT BlockVector::CreateD3d12Heap(ID3D12Heap*& outHeap, UINT64 size) const

+{

+    D3D12_HEAP_DESC heapDesc = {};

+    heapDesc.SizeInBytes = size;

+    heapDesc.Properties.Type = m_HeapType;

+    heapDesc.Alignment = HeapFlagsToAlignment(m_HeapFlags);

+    heapDesc.Flags = m_HeapFlags;

+

+    ID3D12Heap* heap = NULL;

+    return m_hAllocator->GetDevice()->CreateHeap(&heapDesc, IID_PPV_ARGS(&outHeap));

+}

+

+////////////////////////////////////////////////////////////////////////////////

+// Private class AllocatorPimpl implementation

+

+AllocatorPimpl::AllocatorPimpl(const ALLOCATION_CALLBACKS& allocationCallbacks, const ALLOCATOR_DESC& desc) :

+    m_UseMutex((desc.Flags & ALLOCATOR_FLAG_SINGLETHREADED) == 0),

+    m_Device(desc.pDevice),

+    m_PreferredBlockSize(desc.PreferredBlockSize != 0 ? desc.PreferredBlockSize : D3D12MA_DEFAULT_BLOCK_SIZE),

+    m_AllocationCallbacks(allocationCallbacks)

+{

+    // desc.pAllocationCallbacks intentionally ignored here, preprocessed by CreateAllocator.

+    ZeroMemory(&m_D3D12Options, sizeof(m_D3D12Options));

+

+    ZeroMemory(m_pCommittedAllocations, sizeof(m_pCommittedAllocations));

+    ZeroMemory(m_BlockVectors, sizeof(m_BlockVectors));

+

+    for(UINT heapTypeIndex = 0; heapTypeIndex < HEAP_TYPE_COUNT; ++heapTypeIndex)

+    {

+        m_pCommittedAllocations[heapTypeIndex] = D3D12MA_NEW(GetAllocs(), AllocationVectorType)(GetAllocs());

+    }

+}

+

+HRESULT AllocatorPimpl::Init()

+{

+    HRESULT hr = m_Device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &m_D3D12Options, sizeof(m_D3D12Options));

+    if(FAILED(hr))

+    {

+        return hr;

+    }

+

+    const UINT defaultPoolCount = CalcDefaultPoolCount();

+    for(UINT i = 0; i < defaultPoolCount; ++i)

+    {

+        D3D12_HEAP_TYPE heapType;

+        D3D12_HEAP_FLAGS heapFlags;

+        CalcDefaultPoolParams(heapType, heapFlags, i);

+

+        m_BlockVectors[i] = D3D12MA_NEW(GetAllocs(), BlockVector)(

+            this, // hAllocator

+            heapType, // heapType

+            heapFlags, // heapFlags

+            m_PreferredBlockSize,

+            0, // minBlockCount

+            SIZE_MAX, // maxBlockCount

+            false); // explicitBlockSize

+        // No need to call m_pBlockVectors[i]->CreateMinBlocks here, becase minBlockCount is 0.

+    }

+

+    return S_OK;

+}

+

+AllocatorPimpl::~AllocatorPimpl()

+{

+    for(UINT i = DEFAULT_POOL_MAX_COUNT; i--; )

+    {

+        D3D12MA_DELETE(GetAllocs(), m_BlockVectors[i]);

+    }

+

+    for(UINT i = HEAP_TYPE_COUNT; i--; )

+    {

+        if(m_pCommittedAllocations[i] && !m_pCommittedAllocations[i]->empty())

+        {

+            D3D12MA_ASSERT(0 && "Unfreed committed allocations found.");

+        }

+

+        D3D12MA_DELETE(GetAllocs(), m_pCommittedAllocations[i]);

+    }

+}

+

+HRESULT AllocatorPimpl::CreateResource(

+    const ALLOCATION_DESC* pAllocDesc,

+    const D3D12_RESOURCE_DESC* pResourceDesc,

+    D3D12_RESOURCE_STATES InitialResourceState,

+    const D3D12_CLEAR_VALUE *pOptimizedClearValue,

+    Allocation** ppAllocation,

+    REFIID riidResource,

+    void** ppvResource)

+{

+    if(pAllocDesc->HeapType != D3D12_HEAP_TYPE_DEFAULT &&

+        pAllocDesc->HeapType != D3D12_HEAP_TYPE_UPLOAD &&

+        pAllocDesc->HeapType != D3D12_HEAP_TYPE_READBACK)

+    {

+        return E_INVALIDARG;

+    }

+

+    ALLOCATION_DESC finalAllocDesc = *pAllocDesc;

+

+    *ppvResource = NULL;

+

+    D3D12_RESOURCE_ALLOCATION_INFO resAllocInfo = m_Device->GetResourceAllocationInfo(0, 1, pResourceDesc);

+    resAllocInfo.Alignment = D3D12MA_MAX<UINT64>(resAllocInfo.Alignment, D3D12MA_DEBUG_ALIGNMENT);

+    D3D12MA_ASSERT(IsPow2(resAllocInfo.Alignment));

+    D3D12MA_ASSERT(resAllocInfo.SizeInBytes > 0);

+

+    const UINT defaultPoolIndex = CalcDefaultPoolIndex(*pAllocDesc, *pResourceDesc);

+    BlockVector* blockVector = m_BlockVectors[defaultPoolIndex];

+    D3D12MA_ASSERT(blockVector);

+

+    const UINT64 preferredBlockSize = blockVector->GetPreferredBlockSize();

+    bool preferCommittedMemory =

+        D3D12MA_DEBUG_ALWAYS_COMMITTED ||

+        PrefersCommittedAllocation(*pResourceDesc) ||

+        // Heuristics: Allocate committed memory if requested size if greater than half of preferred block size.

+        resAllocInfo.SizeInBytes > preferredBlockSize / 2;

+    if(preferCommittedMemory &&

+        (finalAllocDesc.Flags & ALLOCATION_FLAG_NEVER_ALLOCATE) == 0)

+    {

+        finalAllocDesc.Flags |= ALLOCATION_FLAG_COMMITTED;

+    }

+

+    if((finalAllocDesc.Flags & ALLOCATION_FLAG_COMMITTED) != 0)

+    {

+        return AllocateCommittedMemory(

+            &finalAllocDesc,

+            pResourceDesc,

+            resAllocInfo,

+            InitialResourceState,

+            pOptimizedClearValue,

+            ppAllocation,

+            riidResource,

+            ppvResource);

+    }

+    else

+    {

+        HRESULT hr = blockVector->Allocate(

+            resAllocInfo.SizeInBytes,

+            resAllocInfo.Alignment,

+            finalAllocDesc,

+            1,

+            (Allocation**)ppAllocation);

+        if(SUCCEEDED(hr))

+        {

+            hr = m_Device->CreatePlacedResource(

+                (*ppAllocation)->GetBlock()->GetHeap(),

+                (*ppAllocation)->GetOffset(),

+                pResourceDesc,

+                InitialResourceState,

+                pOptimizedClearValue,

+                riidResource,

+                ppvResource);

+            if(SUCCEEDED(hr))

+            {

+                return hr;

+            }

+            else

+            {

+                (*ppAllocation)->Release();

+                return hr;

+            }

+        }

+

+        return AllocateCommittedMemory(

+            &finalAllocDesc,

+            pResourceDesc,

+            resAllocInfo,

+            InitialResourceState,

+            pOptimizedClearValue,

+            ppAllocation,

+            riidResource,

+            ppvResource);

+    }

+}

+

+bool AllocatorPimpl::PrefersCommittedAllocation(const D3D12_RESOURCE_DESC& resourceDesc)

+{

+    // Intentional. It may change in the future.

+    return false;

+}

+

+HRESULT AllocatorPimpl::AllocateCommittedMemory(

+    const ALLOCATION_DESC* pAllocDesc,

+    const D3D12_RESOURCE_DESC* pResourceDesc,

+    const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo,

+    D3D12_RESOURCE_STATES InitialResourceState,

+    const D3D12_CLEAR_VALUE *pOptimizedClearValue,

+    Allocation** ppAllocation,

+    REFIID riidResource,

+    void** ppvResource)

+{

+    if((pAllocDesc->Flags & ALLOCATION_FLAG_NEVER_ALLOCATE) != 0)

+    {

+        return E_OUTOFMEMORY;

+    }

+

+    D3D12_HEAP_PROPERTIES heapProps = {};

+    heapProps.Type = pAllocDesc->HeapType;

+    HRESULT hr = m_Device->CreateCommittedResource(

+        &heapProps, D3D12_HEAP_FLAG_NONE, pResourceDesc, InitialResourceState,

+        pOptimizedClearValue, riidResource, ppvResource);

+    if(SUCCEEDED(hr))

+    {

+        Allocation* alloc = D3D12MA_NEW(m_AllocationCallbacks, Allocation)();

+        alloc->InitCommitted(this, resAllocInfo.SizeInBytes, pAllocDesc->HeapType);

+        *ppAllocation = alloc;

+

+        const UINT heapTypeIndex = HeapTypeToIndex(pAllocDesc->HeapType);

+

+        {

+            MutexLockWrite lock(m_CommittedAllocationsMutex[heapTypeIndex], m_UseMutex);

+            AllocationVectorType* const committedAllocations = m_pCommittedAllocations[heapTypeIndex];

+            D3D12MA_ASSERT(committedAllocations);

+            committedAllocations->InsertSorted(alloc, PointerLess());

+        }

+    }

+    return hr;

+}

+

+UINT AllocatorPimpl::CalcDefaultPoolCount() const

+{

+    if(SupportsResourceHeapTier2())

+    {

+        return 3;

+    }

+    else

+    {

+        return 9;

+    }

+}

+

+UINT AllocatorPimpl::CalcDefaultPoolIndex(const ALLOCATION_DESC& allocDesc, const D3D12_RESOURCE_DESC& resourceDesc) const

+{

+    UINT poolIndex = UINT_MAX;

+    switch(allocDesc.HeapType)

+    {

+    case D3D12_HEAP_TYPE_DEFAULT:  poolIndex = 0; break;

+    case D3D12_HEAP_TYPE_UPLOAD:   poolIndex = 1; break;

+    case D3D12_HEAP_TYPE_READBACK: poolIndex = 2; break;

+    default: D3D12MA_ASSERT(0);

+    }

+

+    if(!SupportsResourceHeapTier2())

+    {

+        poolIndex *= 3;

+        if(resourceDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER)

+        {

+            ++poolIndex;

+            const bool isRenderTargetOrDepthStencil =

+                (resourceDesc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0;

+            if(isRenderTargetOrDepthStencil)

+            {

+                ++poolIndex;

+            }

+        }

+    }

+

+    return poolIndex;

+}

+

+void AllocatorPimpl::CalcDefaultPoolParams(D3D12_HEAP_TYPE& outHeapType, D3D12_HEAP_FLAGS& outHeapFlags, UINT index) const

+{

+    outHeapType = D3D12_HEAP_TYPE_DEFAULT;

+    outHeapFlags = D3D12_HEAP_FLAG_NONE;

+

+    if(!SupportsResourceHeapTier2())

+    {

+        switch(index % 3)

+        {

+        case 0:

+            outHeapFlags = D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES;

+            break;

+        case 1:

+            outHeapFlags = D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES;

+            break;

+        case 2:

+            outHeapFlags = D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES;

+            break;

+        }

+

+        index /= 3;

+    }

+

+    switch(index)

+    {

+    case 0:

+        outHeapType = D3D12_HEAP_TYPE_DEFAULT;

+        break;

+    case 1:

+        outHeapType = D3D12_HEAP_TYPE_UPLOAD;

+        break;

+    case 2:

+        outHeapType = D3D12_HEAP_TYPE_READBACK;

+        break;

+    default:

+        D3D12MA_ASSERT(0);

+    }

+}

+

+void AllocatorPimpl::FreeCommittedMemory(Allocation* allocation)

+{

+    D3D12MA_ASSERT(allocation && allocation->m_Type == Allocation::TYPE_COMMITTED);

+    const UINT heapTypeIndex = HeapTypeToIndex(allocation->m_Committed.heapType);

+

+    {

+        MutexLockWrite lock(m_CommittedAllocationsMutex[heapTypeIndex], m_UseMutex);

+        AllocationVectorType* const committedAllocations = m_pCommittedAllocations[heapTypeIndex];

+        D3D12MA_ASSERT(committedAllocations);

+        bool success = committedAllocations->RemoveSorted(allocation, PointerLess());

+        D3D12MA_ASSERT(success);

+    }

+}

+

+void AllocatorPimpl::FreePlacedMemory(Allocation* allocation)

+{

+    D3D12MA_ASSERT(allocation && allocation->m_Type == Allocation::TYPE_PLACED);

+    

+    DeviceMemoryBlock* const block = allocation->GetBlock();

+    D3D12MA_ASSERT(block);

+    BlockVector* const blockVector = block->GetBlockVector();

+    D3D12MA_ASSERT(blockVector);

+    blockVector->Free(allocation);

+}

+

+

+////////////////////////////////////////////////////////////////////////////////

+// Public class Allocation implementation

+

+void Allocation::Release()

+{

+    if(this == NULL)

+    {

+        return;

+    }

+

+    D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK

+

+    switch(m_Type)

+    {

+    case TYPE_COMMITTED:

+        m_Allocator->FreeCommittedMemory(this);

+        break;

+    case TYPE_PLACED:

+        m_Allocator->FreePlacedMemory(this);

+        break;

+    }

+

+    FreeName();

+

+    D3D12MA_DELETE(m_Allocator->GetAllocs(), this);

+}

+

+UINT64 Allocation::GetOffset() const

+{

+    switch(m_Type)

+    {

+    case TYPE_COMMITTED:

+        return 0;

+    case TYPE_PLACED:

+        return m_Placed.offset;

+    default:

+        D3D12MA_ASSERT(0);

+        return 0;

+    }

+}

+

+ID3D12Heap* Allocation::GetHeap() const

+{

+    switch(m_Type)

+    {

+    case TYPE_COMMITTED:

+        return NULL;

+    case TYPE_PLACED:

+        return m_Placed.block->GetHeap();

+    default:

+        D3D12MA_ASSERT(0);

+        return 0;

+    }

+}

+

+void Allocation::SetName(LPCWSTR Name)

+{

+    FreeName();

+

+    if(Name)

+    {

+        const size_t nameCharCount = wcslen(Name) + 1;

+        m_Name = D3D12MA_NEW_ARRAY(m_Allocator->GetAllocs(), wchar_t, nameCharCount);

+        memcpy(m_Name, Name, nameCharCount * sizeof(wchar_t));

+    }

+}

+

+Allocation::Allocation()

+{

+    // Must be empty because Allocation objects will be allocated out of PoolAllocator

+    // and may not call constructor and destructor at the right time.

+    // Use Init* methods instead.

+}

+

+Allocation::~Allocation()

+{

+    // Must be empty because Allocation objects will be allocated out of PoolAllocator

+    // and may not call constructor and destructor at the right time.

+    // Use Release method instead.

+}

+

+void Allocation::InitCommitted(AllocatorPimpl* allocator, UINT64 size, D3D12_HEAP_TYPE heapType)

+{

+    m_Allocator = allocator;

+    m_Type = TYPE_COMMITTED;

+    m_Size = size;

+    m_Name = NULL;

+    m_Committed.heapType = heapType;

+}

+

+void Allocation::InitPlaced(AllocatorPimpl* allocator, UINT64 size, UINT64 offset, UINT64 alignment, DeviceMemoryBlock* block)

+{

+    m_Allocator = allocator;

+    m_Type = TYPE_PLACED;

+    m_Size = size;

+    m_Name = NULL;

+    m_Placed.offset = offset;

+    m_Placed.block = block;

+}

+

+DeviceMemoryBlock* Allocation::GetBlock()

+{

+    D3D12MA_ASSERT(m_Type == TYPE_PLACED);

+    return m_Placed.block;

+}

+

+void Allocation::FreeName()

+{

+    if(m_Name)

+    {

+        const size_t nameCharCount = wcslen(m_Name) + 1;

+        D3D12MA_DELETE_ARRAY(m_Allocator->GetAllocs(), m_Name, nameCharCount);

+        m_Name = NULL;

+    }

+}

+

+////////////////////////////////////////////////////////////////////////////////

+// Public class Allocator implementation

+

+Allocator::Allocator(const ALLOCATION_CALLBACKS& allocationCallbacks, const ALLOCATOR_DESC& desc) :

+    m_Pimpl(D3D12MA_NEW(allocationCallbacks, AllocatorPimpl)(allocationCallbacks, desc))

+{

+}

+

+Allocator::~Allocator()

+{

+    D3D12MA_DELETE(m_Pimpl->GetAllocs(), m_Pimpl);

+}

+

+void Allocator::Release()

+{

+    D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK

+

+    // Copy is needed because otherwise we would call destructor and invalidate the structure with callbacks before using it to free memory.

+    const ALLOCATION_CALLBACKS allocationCallbacksCopy = m_Pimpl->GetAllocs();

+    D3D12MA_DELETE(allocationCallbacksCopy, this);

+}

+

+

+

+const D3D12_FEATURE_DATA_D3D12_OPTIONS& Allocator::GetD3D12Options() const

+{

+    return m_Pimpl->GetD3D12Options();

+}

+

+HRESULT Allocator::CreateResource(

+    const ALLOCATION_DESC* pAllocDesc,

+    const D3D12_RESOURCE_DESC* pResourceDesc,

+    D3D12_RESOURCE_STATES InitialResourceState,

+    const D3D12_CLEAR_VALUE *pOptimizedClearValue,

+    Allocation** ppAllocation,

+    REFIID riidResource,

+    void** ppvResource)

+{

+    D3D12MA_ASSERT(pAllocDesc && pResourceDesc && ppAllocation && riidResource != IID_NULL && ppvResource);

+    D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK

+    return m_Pimpl->CreateResource(pAllocDesc, pResourceDesc, InitialResourceState, pOptimizedClearValue, ppAllocation, riidResource, ppvResource);

+}

+

+////////////////////////////////////////////////////////////////////////////////

+// Public global functions

+

+HRESULT CreateAllocator(const ALLOCATOR_DESC* pDesc, Allocator** ppAllocator)

+{

+    D3D12MA_ASSERT(pDesc && ppAllocator);

+    D3D12MA_ASSERT(pDesc->pDevice);

+    D3D12MA_ASSERT(pDesc->PreferredBlockSize == 0 || (pDesc->PreferredBlockSize >= 16 && pDesc->PreferredBlockSize < 0x10000000000ull));

+

+    D3D12MA_DEBUG_GLOBAL_MUTEX_LOCK

+

+    ALLOCATION_CALLBACKS allocationCallbacks;

+    SetupAllocationCallbacks(allocationCallbacks, *pDesc);

+

+    *ppAllocator = D3D12MA_NEW(allocationCallbacks, Allocator)(allocationCallbacks, *pDesc);

+    HRESULT hr = (*ppAllocator)->m_Pimpl->Init();

+    if(FAILED(hr))

+    {

+        D3D12MA_DELETE(allocationCallbacks, *ppAllocator);

+        *ppAllocator = NULL;

+    }

+    return hr;

+}

+

+} // namespace D3D12MA

diff --git a/src/D3D12MemAlloc.h b/src/D3D12MemAlloc.h
new file mode 100644
index 0000000..ec4abdc
--- /dev/null
+++ b/src/D3D12MemAlloc.h
@@ -0,0 +1,603 @@
+//

+// Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.

+//

+// 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.

+//

+

+#pragma once

+

+/** \mainpage D3D12 Memory Allocator

+

+<b>Version 1.0.0</b> (2019-07-23)

+

+Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved. \n

+License: MIT

+

+Documentation of all members: D3D12MemAlloc.h

+

+\section main_table_of_contents Table of contents

+

+- <b>User guide</b>

+    - \subpage quick_start

+        - [Project setup](@ref quick_start_project_setup)

+        - [Creating resources](@ref quick_start_creating_resources)

+        - [Mapping memory](@ref quick_start_mapping_memory)

+- \subpage configuration

+  - [Custom CPU memory allocator](@ref custom_memory_allocator)

+- \subpage general_considerations

+  - [Thread safety](@ref general_considerations_thread_safety)

+  - [Future plans](@ref general_considerations_future_plans)

+  - [Features not supported](@ref general_considerations_features_not_supported)

+		

+\section main_see_also See also

+

+- [Product page on GPUOpen](https://gpuopen.com/gaming-product/D3D12MemoryAllocator/) (TODO)

+- [Source repository on GitHub](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator)

+

+

+\page quick_start Quick start

+

+\section quick_start_project_setup Project setup and initialization

+

+This is a small, standalone C++ library. It consists of a pair of 2 files:

+"%D3D12MemAlloc.h" header file with public interface and "D3D12MemAlloc.cpp" with

+internal implementation. The only external dependencies are WinAPI, Direct3D 12,

+and parts of C/C++ standard library (but STL containers, exceptions, or RTTI are

+not used).

+

+The library is developed and tested using Microsoft Visual Studio 2019, but it

+should work with other compilers as well. It is designed for 64-bit code.

+

+To use the library in your project:

+

+(1.) Copy files `D3D12MemAlloc.cpp`, `%D3D12MemAlloc.h` to your project.

+

+(2.) Make `D3D12MemAlloc.cpp` compiling as part of the project, as C++ code.

+

+(3.) Include library header in each CPP file that needs to use the library.

+

+\code

+#include "D3D12MemAlloc.h"

+\endcode

+

+(4.) Right after you created `ID3D12Device`, fill D3D12MA::ALLOCATOR_DESC

+structure and call function D3D12MA::CreateAllocator to create the main

+D3D12MA::Allocator object.

+

+Please note that all symbols of the library are declared inside #D3D12MA namespace.

+

+\code

+ID3D12Device* device = (...)

+

+D3D12MA::ALLOCATOR_DESC allocatorDesc = {};

+allocatorDesc.pDevice = device;

+

+D3D12MA::Allocator* allocator;

+HRESULT hr = D3D12MA::CreateAllocator(&allocatorDesc, &allocator);

+\endcode

+

+(5.) Right before destroying the D3D12 device, destroy the allocator object.

+

+Please note that objects of this library must be destroyed by calling `Release`

+method (despite they are not COM interfaces and no reference counting is involved).

+

+\code

+allocator->Release();

+device->Release();

+\endcode

+

+

+\section quick_start_creating_resources Creating resources

+

+To use the library for creating resources (textures and buffers), call method

+D3D12MA::Allocator::CreateResource in the place where you would previously call

+`ID3D12Device::CreateCommittedResource`.

+

+The function has similar syntax, but it expects structure D3D12MA::ALLOCATION_DESC

+to be passed along with `D3D12_RESOURCE_DESC` and other parameters for created

+resource. This structure describes parameters of the desired memory allocation,

+including choice of `D3D12_HEAP_TYPE`.

+

+The function also returns a new object of type D3D12MA::Allocation, created along

+with usual `ID3D12Resource`. It represents allocated memory and can be queried

+for size, offset, and `ID3D12Heap` if needed.

+

+\code

+D3D12_RESOURCE_DESC resourceDesc = {};

+resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;

+resourceDesc.Alignment = 0;

+resourceDesc.Width = 1024;

+resourceDesc.Height = 1024;

+resourceDesc.DepthOrArraySize = 1;

+resourceDesc.MipLevels = 1;

+resourceDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

+resourceDesc.SampleDesc.Count = 1;

+resourceDesc.SampleDesc.Quality = 0;

+resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;

+resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

+

+D3D12MA::ALLOCATION_DESC allocationDesc = {};

+allocDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;

+

+D3D12Resource* resource;

+D3D12MA::Allocation* allocation;

+HRESULT hr = allocator->CreateResource(

+    &allocationDesc,

+    &resourceDesc,

+    D3D12_RESOURCE_STATE_COPY_DEST,

+    NULL,

+    &allocation,

+    IID_PPV_ARGS(&resource));

+\endcode

+

+You need to remember both resource and allocation objects and destroy them

+separately when no longer needed.

+

+\code

+allocation->Release();

+resource->Release();

+\endcode

+

+The advantage of using the allocator instead of creating committed resource, and

+the main purpose of this library, is that it can decide to allocate bigger memory

+heap internally using `ID3D12Device::CreateHeap` and place multiple resources in

+it, at different offsets, using `ID3D12Device::CreatePlacedResource`. The library

+manages its own collection of allocated memory blocks (heaps) and remembers which

+parts of them are occupied and which parts are free to be used for new resources.

+

+The library also automatically handles resource heap tier.

+When `D3D12_FEATURE_DATA_D3D12_OPTIONS::ResourceHeapTier` equals `D3D12_RESOURCE_HEAP_TIER_1`,

+resources of 3 types: buffers, textures that are render targets or depth-stencil,

+and other textures must be kept in separate heaps. When `D3D12_RESOURCE_HEAP_TIER_2`,

+they can be kept together. By using this library, you don't need to handle this

+manually.

+

+

+\section quick_start_mapping_memory Mapping memory

+

+The process of getting regular CPU-side pointer to the memory of a resource in

+Direct3D is called "mapping". There are rules and restrictions to this process,

+as described in D3D12 documentation of [ID3D12Resource::Map method](https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/nf-d3d12-id3d12resource-map).

+

+Mapping happens on the level of particular resources, not entire memory heaps,

+and so it is out of scope of this library. Just as the linked documentation says:

+

+- Returned pointer refers to data of particular subresource, not entire memory heap.

+- You can map same resource multiple times. It is ref-counted internally.

+- Mapping is thread-safe.

+- Unmapping is not required before resource destruction.

+- Unmapping may not be required before using written data - some heap types on

+  some platforms support resources persistently mapped.

+

+When using this library, you can map and use your resources normally without

+considering whether they are created as committed resources or placed resources in one large heap.

+

+Example for buffer created and filled in `UPLOAD` heap type:

+

+\code

+const UINT64 bufSize = 65536;

+const float* bufData = (...);

+

+D3D12_RESOURCE_DESC resourceDesc = {};

+resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;

+resourceDesc.Alignment = 0;

+resourceDesc.Width = bufSize;

+resourceDesc.Height = 1;

+resourceDesc.DepthOrArraySize = 1;

+resourceDesc.MipLevels = 1;

+resourceDesc.Format = DXGI_FORMAT_UNKNOWN;

+resourceDesc.SampleDesc.Count = 1;

+resourceDesc.SampleDesc.Quality = 0;

+resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;

+resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

+

+D3D12MA::ALLOCATION_DESC allocationDesc = {};

+allocationDesc.HeapType = D3D12_HEAP_TYPE_UPLOAD;

+

+D3D12Resource* resource;

+D3D12MA::Allocation* allocation;

+HRESULT hr = allocator->CreateResource(

+    &allocationDesc,

+    &resourceDesc,

+    D3D12_RESOURCE_STATE_GENERIC_READ,

+    NULL,

+    &allocation,

+    IID_PPV_ARGS(&resource));

+

+void* mappedPtr;

+hr = resource->Map(0, NULL, &mappedPtr);

+

+memcpy(mappedPtr, bufData, bufSize);

+

+resource->Unmap(0, NULL);

+\endcode

+

+

+\page configuration Configuration

+

+Please check file `D3D12MemAlloc.cpp` lines between "Configuration Begin" and

+"Configuration End" to find macros that you can define to change the behavior of

+the library, primarily for debugging purposes.

+

+\section custom_memory_allocator Custom CPU memory allocator

+

+If you use custom allocator for CPU memory rather than default C++ operator `new`

+and `delete` or `malloc` and `free` functions, you can make this library using

+your allocator as well by filling structure D3D12MA::ALLOCATION_CALLBACKS and

+passing it as optional member D3D12MA::ALLOCATOR_DESC::pAllocationCallbacks.

+Functions pointed there will be used by the library to make any CPU-side

+allocations. Example:

+

+\code

+#include <malloc.h>

+

+void* CustomAllocate(size_t Size, size_t Alignment, void* pUserData)

+{

+    void* memory = _aligned_malloc(Size, Alignment);

+    // Your extra bookkeeping here...

+    return memory;

+}

+

+void CustomFree(void* pMemory, void* pUserData)

+{

+    // Your extra bookkeeping here...

+    _aligned_free(pMemory);

+}

+

+(...)

+

+D3D12MA::ALLOCATION_CALLBACKS allocationCallbacks = {};

+allocationCallbacks.pAllocate = &CustomAllocate;

+allocationCallbacks.pFree = &CustomFree;

+

+D3D12MA::ALLOCATOR_DESC allocatorDesc = {};

+allocatorDesc.pDevice = device;

+allocatorDesc.pAllocationCallbacks = &allocationCallbacks;

+

+D3D12MA::Allocator* allocator;

+HRESULT hr = D3D12MA::CreateAllocator(&allocatorDesc, &allocator);

+\endcode

+

+

+\page general_considerations General considerations

+

+\section general_considerations_thread_safety Thread safety

+

+- The library has no global state, so separate D3D12MA::Allocator objects can be used independently.

+  In typical applications there should be no need to create multiple such objects though - one per `ID3D12Device` is enough.

+- All calls to methods of D3D12MA::Allocator class are safe to be made from multiple

+  threads simultaneously because they are synchronized internally when needed.

+- When the allocator is created with D3D12MA::ALLOCATOR_FLAG_SINGLETHREADED,

+  calls to methods of D3D12MA::Allocator class must be made from a single thread or synchronized by the user.

+  Using this flag may improve performance.

+

+\section general_considerations_future_plans Future plans

+

+Features planned for future releases:

+

+Near future: feature parity with [Vulkan Memory Allocator](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator/), including:

+

+- Custom memory pools

+- Alternative allocation algorithms: linear allocator, buddy allocator

+- Statistics about memory usage, number of allocations, allocated blocks etc.,

+  along with JSON dump that can be visualized on a picture

+- Support for priorities using `ID3D12Device1::SetResidencyPriority`

+- Support for "lost" allocations

+

+Later:

+

+- Memory defragmentation

+- Query for memory budget using `IDXGIAdapter3::QueryVideoMemoryInfo` and

+  sticking to this budget with allocations

+- Support for resource aliasing (overlap)

+- Support for multi-GPU (multi-adapter)

+

+\section general_considerations_features_not_supported Features not supported

+

+Features deliberately excluded from the scope of this library:

+

+- Descriptor allocation. Although also called "heaps", objects that represent

+  descriptors are separate part of the D3D12 API from buffers and textures.

+- Support for `D3D12_HEAP_TYPE_CUSTOM`. Only the default heap types are supported:

+  `D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_DEFAULT`, `D3D12_HEAP_TYPE_READBACK`.

+- Support for reserved (tiled) resources. We don't recommend using them.

+- Support for `ID3D12Device::Evict` and `MakeResident`. We don't recommend using them.

+

+*/

+

+#include <d3d12.h>

+

+/// \cond INTERNAL

+

+#define D3D12MA_CLASS_NO_COPY(className) \

+    private: \

+        className(const className&) = delete; \

+        className(className&&) = delete; \

+        className& operator=(const className&) = delete; \

+        className& operator=(className&&) = delete;

+

+// To be used with MAKE_HRESULT to define custom error codes.

+#define FACILITY_D3D12MA 3542

+

+/// \endcond

+

+namespace D3D12MA

+{

+

+/// \cond INTERNAL

+class AllocatorPimpl;

+class DeviceMemoryBlock;

+class BlockVector;

+/// \endcond

+

+/// Pointer to custom callback function that allocates CPU memory.

+typedef void* (*ALLOCATE_FUNC_PTR)(size_t Size, size_t Alignment, void* pUserData);

+/**

+\brief Pointer to custom callback function that deallocates CPU memory.

+

+`pMemory = null` should be accepted and ignored.

+*/

+typedef void (*FREE_FUNC_PTR)(void* pMemory, void* pUserData);

+

+/// Custom callbacks to CPU memory allocation functions.

+struct ALLOCATION_CALLBACKS

+{

+    /// %Allocation function.

+    ALLOCATE_FUNC_PTR pAllocate;

+    /// Dellocation function.

+    FREE_FUNC_PTR pFree;

+    /// Custom data that will be passed to allocation and deallocation functions as `pUserData` parameter.

+    void* pUserData;

+};

+

+/// \brief Bit flags to be used with ALLOCATION_DESC::Flags.

+typedef enum ALLOCATION_FLAGS

+{

+    /// Zero

+    ALLOCATION_FLAG_NONE = 0,

+

+    /**

+    Set this flag if the allocation should have its own dedicated memory allocation (committed resource with implicit heap).

+    

+    Use it for special, big resources, like fullscreen textures used as render targets.

+    */

+    ALLOCATION_FLAG_COMMITTED = 0x1,

+

+    /**

+    Set this flag to only try to allocate from existing memory heaps and never create new such heap.

+

+    If new allocation cannot be placed in any of the existing heaps, allocation

+    fails with `E_OUTOFMEMORY` error.

+

+    You should not use #ALLOCATION_FLAG_COMMITTED and

+    #ALLOCATION_FLAG_NEVER_ALLOCATE at the same time. It makes no sense.

+    */

+    ALLOCATION_FLAG_NEVER_ALLOCATE = 0x2,

+} ALLOCATION_FLAGS;

+

+/// \brief Parameters of created Allocation object. To be used with Allocator::CreateResource.

+struct ALLOCATION_DESC

+{

+    /// Flags.

+    ALLOCATION_FLAGS Flags;

+    /** \brief The type of memory heap where the new allocation should be placed.

+

+    It must be one of: `D3D12_HEAP_TYPE_DEFAULT`, `D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`.

+    */

+    D3D12_HEAP_TYPE HeapType;

+};

+

+/** \brief Represents single memory allocation.

+

+It may be either implicit memory heap dedicated to a single resource or a

+specific region of a bigger heap plus unique offset.

+

+To create such object, fill structure D3D12MA::ALLOCATION_DESC and call function

+Allocator::CreateResource.

+

+The object remembers size and some other information.

+To retrieve this information, use methods of this class.

+*/

+class Allocation

+{

+public:

+    /** \brief Deletes this object.

+

+    This function must be used instead of destructor, which is private.

+    There is no reference counting involved.

+    */

+    void Release();

+

+    /** \brief Returns offset in bytes from the start of memory heap.

+

+    If the Allocation represents committed resource with implicit heap, returns 0.

+    */

+    UINT64 GetOffset() const;

+

+    /** \brief Returns size in bytes of the resource.

+

+    Works also with committed resources.

+    */

+    UINT64 GetSize() const { return m_Size; }

+

+    /** \brief Returns memory heap that the resource is created in.

+

+    If the Allocation represents committed resource with implicit heap, returns NULL.

+    */

+    ID3D12Heap* GetHeap() const;

+

+    /** \brief Associates a name with the allocation object. This name is for use in debug diagnostics and tools.

+

+    Internal copy of the string is made, so the memory pointed by the argument can be

+    changed of freed immediately after this call.

+

+    `Name` can be null.

+    */

+    void SetName(LPCWSTR Name);

+

+    /** \brief Returns the name associated with the allocation object.

+

+    Returned string points to an internal copy.

+

+    If no name was associated with the allocation, returns null.

+    */

+    LPCWSTR GetName() const { return m_Name; }

+

+private:

+    friend class AllocatorPimpl;

+    friend class BlockVector;

+    template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);

+

+    AllocatorPimpl* m_Allocator;

+    enum Type

+    {

+        TYPE_COMMITTED,

+        TYPE_PLACED,

+        TYPE_COUNT

+    } m_Type;

+    UINT64 m_Size;

+    wchar_t* m_Name;

+

+    union

+    {

+        struct

+        {

+            D3D12_HEAP_TYPE heapType;

+        } m_Committed;

+

+        struct

+        {

+            UINT64 offset;

+            DeviceMemoryBlock* block;

+        } m_Placed;

+    };

+

+    Allocation();

+    ~Allocation();

+    void InitCommitted(AllocatorPimpl* allocator, UINT64 size, D3D12_HEAP_TYPE heapType);

+    void InitPlaced(AllocatorPimpl* allocator, UINT64 size, UINT64 offset, UINT64 alignment, DeviceMemoryBlock* block);

+    DeviceMemoryBlock* GetBlock();

+    void FreeName();

+

+    D3D12MA_CLASS_NO_COPY(Allocation)

+};

+

+/// \brief Bit flags to be used with ALLOCATOR_DESC::Flags.

+typedef enum ALLOCATOR_FLAGS

+{

+    /// Zero

+    ALLOCATOR_FLAG_NONE = 0,

+

+    /**

+    Allocator and all objects created from it will not be synchronized internally,

+    so you must guarantee they are used from only one thread at a time or

+    synchronized by you.

+

+    Using this flag may increase performance because internal mutexes are not used.

+    */

+    ALLOCATOR_FLAG_SINGLETHREADED = 0x1,

+} ALLOCATOR_FLAGS;

+

+/// \brief Parameters of created Allocator object. To be used with CreateAllocator().

+struct ALLOCATOR_DESC

+{

+    /// Flags.

+    ALLOCATOR_FLAGS Flags;

+    

+    /// Direct3D device object that the allocator should be attached to.

+    ID3D12Device* pDevice;

+    

+    /** \brief Preferred size of a single `ID3D12Heap` block to be allocated.

+    

+    Set to 0 to use default, which is currently 256 MiB.

+    */

+    UINT64 PreferredBlockSize;

+    

+    /** \brief Custom CPU memory allocation callbacks. Optional.

+

+    Optional, can be null. When specified, will be used for all CPU-side memory allocations.

+    */

+    const ALLOCATION_CALLBACKS* pAllocationCallbacks;

+};

+

+/**

+\brief Represents main object of this library initialized for particular `ID3D12Device`.

+

+Fill structure D3D12MA::ALLOCATOR_DESC and call function CreateAllocator() to create it.

+Call method Allocator::Release to destroy it.

+

+It is recommended to create just one object of this type per `ID3D12Device` object,

+right after Direct3D 12 is initialized and keep it alive until before Direct3D device is destroyed.

+*/

+class Allocator

+{

+public:

+    /** \brief Deletes this object.

+    

+    This function must be used instead of destructor, which is private.

+    There is no reference counting involved.

+    */

+    void Release();

+    

+    /// Returns cached options retrieved from D3D12 device.

+    const D3D12_FEATURE_DATA_D3D12_OPTIONS& GetD3D12Options() const;

+

+    /** \brief Allocates memory and creates a D3D12 resource (buffer or texture). This is the main allocation function.

+

+    The function is similar to `ID3D12Device::CreateCommittedResource`, but it may

+    really call `ID3D12Device::CreatePlacedResource` to assign part of a larger,

+    existing memory heap to the new resource, which is the main purpose of this

+    whole library.

+

+    Two objects are created and returned: allocation and resource. You need to

+    destroy them both.

+    */

+    HRESULT CreateResource(

+        const ALLOCATION_DESC* pAllocDesc,

+        const D3D12_RESOURCE_DESC* pResourceDesc,

+        D3D12_RESOURCE_STATES InitialResourceState,

+        const D3D12_CLEAR_VALUE *pOptimizedClearValue,

+        Allocation** ppAllocation,

+        REFIID riidResource,

+        void** ppvResource);

+

+private:

+    friend HRESULT CreateAllocator(const ALLOCATOR_DESC*, Allocator**);

+    template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);

+

+    Allocator(const ALLOCATION_CALLBACKS& allocationCallbacks, const ALLOCATOR_DESC& desc);

+    ~Allocator();

+    

+    AllocatorPimpl* m_Pimpl;

+    

+    D3D12MA_CLASS_NO_COPY(Allocator)

+};

+

+/** \brief Creates new main Allocator object and returns it through `ppAllocator`.

+

+You normally only need to call it once and keep a single Allocator object for your `ID3D12Device`.

+*/

+HRESULT CreateAllocator(const ALLOCATOR_DESC* pDesc, Allocator** ppAllocator);

+

+} // namespace D3D12MA

+

+/// \cond INTERNAL

+DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::ALLOCATION_FLAGS);

+DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::ALLOCATOR_FLAGS);

+/// \endcond

diff --git a/src/D3D12MemAlloc.natvis b/src/D3D12MemAlloc.natvis
new file mode 100644
index 0000000..0dadaa0
--- /dev/null
+++ b/src/D3D12MemAlloc.natvis
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?> 

+<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">

+  <Type Name="D3D12MA::Vector&lt;*&gt;">

+    <DisplayString>{{ Count={m_Count} }}</DisplayString>

+    <Expand>

+      <Item Name="[Count]">m_Count</Item>

+      <Item Name="[Capacity]">m_Capacity</Item>

+      <ArrayItems>

+        <Size>m_Count</Size>

+        <ValuePointer>m_pArray</ValuePointer>

+      </ArrayItems>

+    </Expand>

+  </Type>

+

+  <Type Name="D3D12MA::List&lt;*&gt;">

+    <DisplayString>{{ Count={m_Count} }}</DisplayString>

+    <Expand>

+      <Item Name="[Count]">m_Count</Item>

+      <LinkedListItems>

+        <Size>m_Count</Size>

+        <HeadPointer>m_pFront</HeadPointer>

+        <NextPointer>pNext</NextPointer>

+        <ValueNode>Value</ValueNode>

+      </LinkedListItems>

+    </Expand>

+  </Type>

+</AutoVisualizer>
\ No newline at end of file
diff --git a/src/D3D12Sample.cpp b/src/D3D12Sample.cpp
new file mode 100644
index 0000000..5348827
--- /dev/null
+++ b/src/D3D12Sample.cpp
@@ -0,0 +1,1501 @@
+//

+// Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.

+//

+// 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.

+//

+

+#include "D3D12MemAlloc.h"

+#include "Common.h"

+#include "Tests.h"

+#include <atomic>

+

+namespace VS

+{

+    #include "Shaders\VS_Compiled.h"

+}

+namespace PS

+{

+    #include "Shaders\PS_Compiled.h"

+}

+

+static const wchar_t * const CLASS_NAME = L"D3D12MemAllocSample";

+static const wchar_t * const WINDOW_TITLE = L"D3D12 Memory Allocator Sample";

+static const int SIZE_X = 1024;

+static const int SIZE_Y = 576; 

+static const bool FULLSCREEN = false;

+static const UINT PRESENT_SYNC_INTERVAL = 1;

+static const DXGI_FORMAT RENDER_TARGET_FORMAT = DXGI_FORMAT_R8G8B8A8_UNORM;

+static const DXGI_FORMAT DEPTH_STENCIL_FORMAT = DXGI_FORMAT_D32_FLOAT;

+static const size_t FRAME_BUFFER_COUNT = 3; // number of buffers we want, 2 for double buffering, 3 for tripple buffering

+static const D3D_FEATURE_LEVEL MY_D3D_FEATURE_LEVEL = D3D_FEATURE_LEVEL_12_0;

+

+static const bool ENABLE_DEBUG_LAYER = true;

+static const bool ENABLE_CPU_ALLOCATION_CALLBACKS = true;

+static const bool ENABLE_CPU_ALLOCATION_CALLBACKS_PRINT = false;

+

+static HINSTANCE g_Instance;

+static HWND g_Wnd;

+

+static UINT64 g_TimeOffset; // In ms.

+static UINT64 g_TimeValue; // Time since g_TimeOffset, in ms.

+static float g_Time; // g_TimeValue converted to float, in seconds.

+static float g_TimeDelta;

+

+static CComPtr<ID3D12Device> g_Device;

+static D3D12MA::Allocator* g_Allocator;

+

+static CComPtr<IDXGISwapChain3> g_SwapChain; // swapchain used to switch between render targets

+static CComPtr<ID3D12CommandQueue> g_CommandQueue; // container for command lists

+static CComPtr<ID3D12DescriptorHeap> g_RtvDescriptorHeap; // a descriptor heap to hold resources like the render targets

+static CComPtr<ID3D12Resource> g_RenderTargets[FRAME_BUFFER_COUNT]; // number of render targets equal to buffer count

+static CComPtr<ID3D12CommandAllocator> g_CommandAllocators[FRAME_BUFFER_COUNT]; // we want enough allocators for each buffer * number of threads (we only have one thread)

+static CComPtr<ID3D12GraphicsCommandList> g_CommandList; // a command list we can record commands into, then execute them to render the frame

+static CComPtr<ID3D12Fence> g_Fences[FRAME_BUFFER_COUNT];    // an object that is locked while our command list is being executed by the gpu. We need as many 

+                                                      //as we have allocators (more if we want to know when the gpu is finished with an asset)

+static HANDLE g_FenceEvent; // a handle to an event when our g_Fences is unlocked by the gpu

+static UINT64 g_FenceValues[FRAME_BUFFER_COUNT]; // this value is incremented each frame. each g_Fences will have its own value

+static UINT g_FrameIndex; // current rtv we are on

+static UINT g_RtvDescriptorSize; // size of the rtv descriptor on the g_Device (all front and back buffers will be the same size)

+

+static CComPtr<ID3D12PipelineState> g_PipelineStateObject;

+static CComPtr<ID3D12RootSignature> g_RootSignature;

+static CComPtr<ID3D12Resource> g_VertexBuffer;

+static D3D12MA::Allocation* g_VertexBufferAllocation;

+static CComPtr<ID3D12Resource> g_IndexBuffer;

+static D3D12MA::Allocation* g_IndexBufferAllocation;

+static D3D12_VERTEX_BUFFER_VIEW g_VertexBufferView;

+static D3D12_INDEX_BUFFER_VIEW g_IndexBufferView;

+static CComPtr<ID3D12Resource> g_DepthStencilBuffer;

+static D3D12MA::Allocation* g_DepthStencilAllocation;

+static CComPtr<ID3D12DescriptorHeap> g_DepthStencilDescriptorHeap;

+

+struct Vertex {

+    vec3 pos;

+    vec2 texCoord;

+

+    Vertex() { }

+    Vertex(float x, float y, float z, float tx, float ty) :

+        pos(x, y, z),

+        texCoord(tx, ty)

+    {

+    }

+};

+

+struct ConstantBuffer0_PS

+{

+    vec4 Color;

+};

+struct ConstantBuffer1_VS

+{

+    mat4 WorldViewProj;

+};

+

+static const size_t ConstantBufferPerObjectAlignedSize = AlignUp<size_t>(sizeof(ConstantBuffer1_VS), 256);

+static D3D12MA::Allocation* g_CbPerObjectUploadHeapAllocations[FRAME_BUFFER_COUNT];

+static CComPtr<ID3D12Resource> g_CbPerObjectUploadHeaps[FRAME_BUFFER_COUNT];

+static void* g_CbPerObjectAddress[FRAME_BUFFER_COUNT];

+static uint32_t g_CubeIndexCount;

+

+static CComPtr<ID3D12DescriptorHeap> g_MainDescriptorHeap[FRAME_BUFFER_COUNT];

+static CComPtr<ID3D12Resource> g_ConstantBufferUploadHeap[FRAME_BUFFER_COUNT];

+static D3D12MA::Allocation* g_ConstantBufferUploadAllocation[FRAME_BUFFER_COUNT];

+static void* g_ConstantBufferAddress[FRAME_BUFFER_COUNT];

+

+static CComPtr<ID3D12Resource> g_Texture;

+static D3D12MA::Allocation* g_TextureAllocation;

+

+static void* const CUSTOM_ALLOCATION_USER_DATA = (void*)(uintptr_t)0xDEADC0DE;

+

+static std::atomic<size_t> g_CpuAllocationCount{0};

+

+static void* CustomAllocate(size_t Size, size_t Alignment, void* pUserData)

+{

+    assert(pUserData == CUSTOM_ALLOCATION_USER_DATA);

+    void* memory = _aligned_malloc(Size, Alignment);

+    if(ENABLE_CPU_ALLOCATION_CALLBACKS_PRINT)

+    {

+        wprintf(L"Allocate Size=%llu Alignment=%llu -> %p\n", Size, Alignment, memory);

+    }

+    ++g_CpuAllocationCount;

+    return memory;

+}

+

+static void CustomFree(void* pMemory, void* pUserData)

+{

+    assert(pUserData == CUSTOM_ALLOCATION_USER_DATA);

+    if(pMemory)

+    {

+        --g_CpuAllocationCount;

+        if(ENABLE_CPU_ALLOCATION_CALLBACKS_PRINT)

+        {

+            wprintf(L"Free %p\n", pMemory);

+        }

+        _aligned_free(pMemory);

+    }

+}

+

+static void SetDefaultRasterizerDesc(D3D12_RASTERIZER_DESC& outDesc)

+{

+    outDesc.FillMode = D3D12_FILL_MODE_SOLID;

+    outDesc.CullMode = D3D12_CULL_MODE_BACK;

+    outDesc.FrontCounterClockwise = FALSE;

+    outDesc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;

+    outDesc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;

+    outDesc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;

+    outDesc.DepthClipEnable = TRUE;

+    outDesc.MultisampleEnable = FALSE;

+    outDesc.AntialiasedLineEnable = FALSE;

+    outDesc.ForcedSampleCount = 0;

+    outDesc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;

+}

+

+static void SetDefaultBlendDesc(D3D12_BLEND_DESC& outDesc)

+{

+    outDesc.AlphaToCoverageEnable = FALSE;

+    outDesc.IndependentBlendEnable = FALSE;

+    const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc = {

+        FALSE,FALSE,

+        D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,

+        D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,

+        D3D12_LOGIC_OP_NOOP,

+        D3D12_COLOR_WRITE_ENABLE_ALL };

+    for (UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)

+        outDesc.RenderTarget[i] = defaultRenderTargetBlendDesc;

+}

+

+static void SetDefaultDepthStencilDesc(D3D12_DEPTH_STENCIL_DESC& outDesc)

+{

+    outDesc.DepthEnable = TRUE;

+    outDesc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;

+    outDesc.DepthFunc = D3D12_COMPARISON_FUNC_LESS;

+    outDesc.StencilEnable = FALSE;

+    outDesc.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK;

+    outDesc.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK;

+    const D3D12_DEPTH_STENCILOP_DESC defaultStencilOp = {

+        D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS };

+    outDesc.FrontFace = defaultStencilOp;

+    outDesc.BackFace = defaultStencilOp;

+}

+

+void WaitForFrame(size_t frameIndex) // wait until gpu is finished with command list

+{

+    // if the current g_Fences value is still less than "g_FenceValues", then we know the GPU has not finished executing

+    // the command queue since it has not reached the "g_CommandQueue->Signal(g_Fences, g_FenceValues)" command

+    if (g_Fences[frameIndex]->GetCompletedValue() < g_FenceValues[frameIndex])

+    {

+        // we have the g_Fences create an event which is signaled once the g_Fences's current value is "g_FenceValues"

+        CHECK_HR( g_Fences[frameIndex]->SetEventOnCompletion(g_FenceValues[frameIndex], g_FenceEvent) );

+

+        // We will wait until the g_Fences has triggered the event that it's current value has reached "g_FenceValues". once it's value

+        // has reached "g_FenceValues", we know the command queue has finished executing

+        WaitForSingleObject(g_FenceEvent, INFINITE);

+    }

+}

+

+void WaitGPUIdle(size_t frameIndex)

+{

+    g_FenceValues[frameIndex]++;

+    CHECK_HR( g_CommandQueue->Signal(g_Fences[frameIndex], g_FenceValues[frameIndex]) );

+    WaitForFrame(frameIndex);

+}

+

+//*********************************************************

+//

+// Copyright (c) Microsoft. All rights reserved.

+// This code is licensed under the MIT License (MIT).

+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF

+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY

+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR

+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

+//

+//*********************************************************

+// Row-by-row memcpy

+inline void MemcpySubresource(

+    _In_ const D3D12_MEMCPY_DEST* pDest,

+    _In_ const D3D12_SUBRESOURCE_DATA* pSrc,

+    SIZE_T RowSizeInBytes,

+    UINT NumRows,

+    UINT NumSlices)

+{

+    for (UINT z = 0; z < NumSlices; ++z)

+    {

+        BYTE* pDestSlice = reinterpret_cast<BYTE*>(pDest->pData) + pDest->SlicePitch * z;

+        const BYTE* pSrcSlice = reinterpret_cast<const BYTE*>(pSrc->pData) + pSrc->SlicePitch * z;

+        for (UINT y = 0; y < NumRows; ++y)

+        {

+            memcpy(pDestSlice + pDest->RowPitch * y,

+                pSrcSlice + pSrc->RowPitch * y,

+                RowSizeInBytes);

+        }

+    }

+}

+

+//*********************************************************

+//

+// Copyright (c) Microsoft. All rights reserved.

+// This code is licensed under the MIT License (MIT).

+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF

+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY

+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR

+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

+//

+//*********************************************************

+inline UINT64 UpdateSubresources(

+    _In_ ID3D12GraphicsCommandList* pCmdList,

+    _In_ ID3D12Resource* pDestinationResource,

+    _In_ ID3D12Resource* pIntermediate,

+    _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource,

+    _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources,

+    UINT64 RequiredSize,

+    _In_reads_(NumSubresources) const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts,

+    _In_reads_(NumSubresources) const UINT* pNumRows,

+    _In_reads_(NumSubresources) const UINT64* pRowSizesInBytes,

+    _In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData)

+{

+    // Minor validation

+    D3D12_RESOURCE_DESC IntermediateDesc = pIntermediate->GetDesc();

+    D3D12_RESOURCE_DESC DestinationDesc = pDestinationResource->GetDesc();

+    if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || 

+        IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset || 

+        RequiredSize > (SIZE_T)-1 || 

+        (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && 

+        (FirstSubresource != 0 || NumSubresources != 1)))

+    {

+        return 0;

+    }

+

+    BYTE* pData;

+    HRESULT hr = pIntermediate->Map(0, NULL, reinterpret_cast<void**>(&pData));

+    if (FAILED(hr))

+    {

+        return 0;

+    }

+

+    for (UINT i = 0; i < NumSubresources; ++i)

+    {

+        if (pRowSizesInBytes[i] > (SIZE_T)-1) return 0;

+        D3D12_MEMCPY_DEST DestData = { pData + pLayouts[i].Offset, pLayouts[i].Footprint.RowPitch, pLayouts[i].Footprint.RowPitch * pNumRows[i] };

+        MemcpySubresource(&DestData, &pSrcData[i], (SIZE_T)pRowSizesInBytes[i], pNumRows[i], pLayouts[i].Footprint.Depth);

+    }

+    pIntermediate->Unmap(0, NULL);

+

+    if (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER)

+    {

+        D3D12_BOX SrcBox = {

+            UINT( pLayouts[0].Offset ), 0, 0,

+            UINT( pLayouts[0].Offset + pLayouts[0].Footprint.Width ), 0, 0 };

+        pCmdList->CopyBufferRegion(

+            pDestinationResource, 0, pIntermediate, pLayouts[0].Offset, pLayouts[0].Footprint.Width);

+    }

+    else

+    {

+        for (UINT i = 0; i < NumSubresources; ++i)

+        {

+            D3D12_TEXTURE_COPY_LOCATION Dst = {};

+            Dst.pResource = pDestinationResource;

+            Dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;

+            Dst.SubresourceIndex = i + FirstSubresource;

+            D3D12_TEXTURE_COPY_LOCATION Src = {};

+            Src.pResource = pIntermediate;

+            Src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;

+            Src.PlacedFootprint = pLayouts[i];

+            pCmdList->CopyTextureRegion(&Dst, 0, 0, 0, &Src, nullptr);

+        }

+    }

+    return RequiredSize;

+}

+

+//*********************************************************

+//

+// Copyright (c) Microsoft. All rights reserved.

+// This code is licensed under the MIT License (MIT).

+// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF

+// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY

+// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR

+// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

+//

+//*********************************************************

+inline UINT64 UpdateSubresources(

+    _In_ ID3D12GraphicsCommandList* pCmdList,

+    _In_ ID3D12Resource* pDestinationResource,

+    _In_ ID3D12Resource* pIntermediate,

+    UINT64 IntermediateOffset,

+    _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource,

+    _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources,

+    _In_reads_(NumSubresources) D3D12_SUBRESOURCE_DATA* pSrcData)

+{

+    UINT64 RequiredSize = 0;

+    UINT64 MemToAlloc = static_cast<UINT64>(sizeof(D3D12_PLACED_SUBRESOURCE_FOOTPRINT) + sizeof(UINT) + sizeof(UINT64)) * NumSubresources;

+    if (MemToAlloc > SIZE_MAX)

+    {

+        return 0;

+    }

+    void* pMem = HeapAlloc(GetProcessHeap(), 0, static_cast<SIZE_T>(MemToAlloc));

+    if (pMem == NULL)

+    {

+        return 0;

+    }

+    D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts = reinterpret_cast<D3D12_PLACED_SUBRESOURCE_FOOTPRINT*>(pMem);

+    UINT64* pRowSizesInBytes = reinterpret_cast<UINT64*>(pLayouts + NumSubresources);

+    UINT* pNumRows = reinterpret_cast<UINT*>(pRowSizesInBytes + NumSubresources);

+

+    D3D12_RESOURCE_DESC Desc = pDestinationResource->GetDesc();

+    ID3D12Device* pDevice;

+    pDestinationResource->GetDevice(__uuidof(*pDevice), reinterpret_cast<void**>(&pDevice));

+    pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize);

+    pDevice->Release();

+

+    UINT64 Result = UpdateSubresources(pCmdList, pDestinationResource, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, pLayouts, pNumRows, pRowSizesInBytes, pSrcData);

+    HeapFree(GetProcessHeap(), 0, pMem);

+    return Result;

+}

+

+void InitD3D() // initializes direct3d 12

+{

+    IDXGIFactory4* dxgiFactory;

+    CHECK_HR( CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)) );

+

+    IDXGIAdapter1* adapter = nullptr; // adapters are the graphics card (this includes the embedded graphics on the motherboard)

+

+    int adapterIndex = 0; // we'll start looking for directx 12  compatible graphics devices starting at index 0

+

+    bool adapterFound = false; // set this to true when a good one was found

+

+                               // find first hardware gpu that supports d3d 12

+    while (dxgiFactory->EnumAdapters1(adapterIndex, &adapter) != DXGI_ERROR_NOT_FOUND)

+    {

+        DXGI_ADAPTER_DESC1 desc;

+        adapter->GetDesc1(&desc);

+

+        if ((desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) == 0)

+        {

+            HRESULT hr = D3D12CreateDevice(adapter, MY_D3D_FEATURE_LEVEL, _uuidof(ID3D12Device), nullptr);

+            if (SUCCEEDED(hr))

+            {

+                adapterFound = true;

+                break;

+            }

+        }

+        adapter->Release();

+        adapterIndex++;

+    }

+    assert(adapterFound);

+

+    // Must be done before D3D12 device is created.

+    if(ENABLE_DEBUG_LAYER)

+    {

+        CComPtr<ID3D12Debug> debug;

+        if(SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug))))

+            debug->EnableDebugLayer();

+    }

+

+    // Create the g_Device

+    ID3D12Device* device = nullptr;

+    CHECK_HR( D3D12CreateDevice(

+        adapter,

+        MY_D3D_FEATURE_LEVEL,

+        IID_PPV_ARGS(&device)) );

+    g_Device.Attach(device);

+

+    // Create allocator

+

+    {

+        D3D12MA::ALLOCATOR_DESC desc = {};

+        desc.Flags = D3D12MA::ALLOCATOR_FLAG_NONE;

+        desc.pDevice = device;

+

+        D3D12MA::ALLOCATION_CALLBACKS allocationCallbacks = {};

+        if(ENABLE_CPU_ALLOCATION_CALLBACKS)

+        {

+            allocationCallbacks.pAllocate = &CustomAllocate;

+            allocationCallbacks.pFree = &CustomFree;

+            allocationCallbacks.pUserData = CUSTOM_ALLOCATION_USER_DATA;

+            desc.pAllocationCallbacks = &allocationCallbacks;

+        }

+

+        CHECK_HR( D3D12MA::CreateAllocator(&desc, &g_Allocator) );

+

+        switch(g_Allocator->GetD3D12Options().ResourceHeapTier)

+        {

+        case D3D12_RESOURCE_HEAP_TIER_1:

+            wprintf(L"ResourceHeapTier = D3D12_RESOURCE_HEAP_TIER_1\n");

+            break;

+        case D3D12_RESOURCE_HEAP_TIER_2:

+            wprintf(L"ResourceHeapTier = D3D12_RESOURCE_HEAP_TIER_2\n");

+            break;

+        default:

+            assert(0);

+        }

+    }

+

+    // -- Create the Command Queue -- //

+

+    D3D12_COMMAND_QUEUE_DESC cqDesc = {}; // we will be using all the default values

+

+    ID3D12CommandQueue* commandQueue = nullptr;

+    CHECK_HR( g_Device->CreateCommandQueue(&cqDesc, IID_PPV_ARGS(&commandQueue)) ); // create the command queue

+    g_CommandQueue.Attach(commandQueue);

+

+    // -- Create the Swap Chain (double/tripple buffering) -- //

+

+    DXGI_MODE_DESC backBufferDesc = {}; // this is to describe our display mode

+    backBufferDesc.Width = SIZE_X; // buffer width

+    backBufferDesc.Height = SIZE_Y; // buffer height

+    backBufferDesc.Format = RENDER_TARGET_FORMAT; // format of the buffer (rgba 32 bits, 8 bits for each chanel)

+

+                                                  // describe our multi-sampling. We are not multi-sampling, so we set the count to 1 (we need at least one sample of course)

+    DXGI_SAMPLE_DESC sampleDesc = {};

+    sampleDesc.Count = 1; // multisample count (no multisampling, so we just put 1, since we still need 1 sample)

+

+                          // Describe and create the swap chain.

+    DXGI_SWAP_CHAIN_DESC swapChainDesc = {};

+    swapChainDesc.BufferCount = FRAME_BUFFER_COUNT; // number of buffers we have

+    swapChainDesc.BufferDesc = backBufferDesc; // our back buffer description

+    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // this says the pipeline will render to this swap chain

+    swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; // dxgi will discard the buffer (data) after we call present

+    swapChainDesc.OutputWindow = g_Wnd; // handle to our window

+    swapChainDesc.SampleDesc = sampleDesc; // our multi-sampling description

+    swapChainDesc.Windowed = !FULLSCREEN; // set to true, then if in fullscreen must call SetFullScreenState with true for full screen to get uncapped fps

+

+    IDXGISwapChain* tempSwapChain;

+

+    CHECK_HR( dxgiFactory->CreateSwapChain(

+        g_CommandQueue, // the queue will be flushed once the swap chain is created

+        &swapChainDesc, // give it the swap chain description we created above

+        &tempSwapChain // store the created swap chain in a temp IDXGISwapChain interface

+    ) );

+

+    g_SwapChain.Attach(static_cast<IDXGISwapChain3*>(tempSwapChain));

+

+    g_FrameIndex = g_SwapChain->GetCurrentBackBufferIndex(); 

+

+    // -- Create the Back Buffers (render target views) Descriptor Heap -- //

+

+    // describe an rtv descriptor heap and create

+    D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};

+    rtvHeapDesc.NumDescriptors = FRAME_BUFFER_COUNT; // number of descriptors for this heap.

+    rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; // this heap is a render target view heap

+

+                                                       // This heap will not be directly referenced by the shaders (not shader visible), as this will store the output from the pipeline

+                                                       // otherwise we would set the heap's flag to D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE

+    rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;

+    ID3D12DescriptorHeap* rtvDescriptorHeap = nullptr;

+    CHECK_HR( g_Device->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(&rtvDescriptorHeap)) );

+    g_RtvDescriptorHeap.Attach(rtvDescriptorHeap);

+

+    // get the size of a descriptor in this heap (this is a rtv heap, so only rtv descriptors should be stored in it.

+    // descriptor sizes may vary from g_Device to g_Device, which is why there is no set size and we must ask the 

+    // g_Device to give us the size. we will use this size to increment a descriptor handle offset

+    g_RtvDescriptorSize = g_Device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);

+

+    // get a handle to the first descriptor in the descriptor heap. a handle is basically a pointer,

+    // but we cannot literally use it like a c++ pointer.

+    D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle { g_RtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart() };

+

+    // Create a RTV for each buffer (double buffering is two buffers, tripple buffering is 3).

+    for (int i = 0; i < FRAME_BUFFER_COUNT; i++)

+    {

+        // first we get the n'th buffer in the swap chain and store it in the n'th

+        // position of our ID3D12Resource array

+        ID3D12Resource* res = nullptr;

+        CHECK_HR( g_SwapChain->GetBuffer(i, IID_PPV_ARGS(&res)) );

+        g_RenderTargets[i].Attach(res);

+

+        // the we "create" a render target view which binds the swap chain buffer (ID3D12Resource[n]) to the rtv handle

+        g_Device->CreateRenderTargetView(g_RenderTargets[i], nullptr, rtvHandle);

+

+        // we increment the rtv handle by the rtv descriptor size we got above

+        rtvHandle.ptr += g_RtvDescriptorSize;

+    }

+

+    // -- Create the Command Allocators -- //

+

+    for (int i = 0; i < FRAME_BUFFER_COUNT; i++)

+    {

+        ID3D12CommandAllocator* commandAllocator = nullptr;

+        CHECK_HR( g_Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&commandAllocator)) );

+        g_CommandAllocators[i].Attach(commandAllocator);

+    }

+

+    // create the command list with the first allocator

+    CHECK_HR( g_Device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_CommandAllocators[0], NULL, IID_PPV_ARGS(&g_CommandList)) );

+

+    // command lists are created in the recording state. our main loop will set it up for recording again so close it now

+    g_CommandList->Close();

+

+    // create a depth stencil descriptor heap so we can get a pointer to the depth stencil buffer

+    D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {};

+    dsvHeapDesc.NumDescriptors = 1;

+    dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;

+    dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;

+    CHECK_HR( g_Device->CreateDescriptorHeap(&dsvHeapDesc, IID_PPV_ARGS(&g_DepthStencilDescriptorHeap)) );

+

+    D3D12_CLEAR_VALUE depthOptimizedClearValue = {};

+    depthOptimizedClearValue.Format = DEPTH_STENCIL_FORMAT;

+    depthOptimizedClearValue.DepthStencil.Depth = 1.0f;

+    depthOptimizedClearValue.DepthStencil.Stencil = 0;

+

+    D3D12MA::ALLOCATION_DESC depthStencilAllocDesc = {};

+    depthStencilAllocDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;

+    D3D12_RESOURCE_DESC depthStencilResourceDesc = {};

+    depthStencilResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;

+    depthStencilResourceDesc.Alignment = 0;

+    depthStencilResourceDesc.Width = SIZE_X;

+    depthStencilResourceDesc.Height = SIZE_Y;

+    depthStencilResourceDesc.DepthOrArraySize = 1;

+    depthStencilResourceDesc.MipLevels = 1;

+    depthStencilResourceDesc.Format = DEPTH_STENCIL_FORMAT;

+    depthStencilResourceDesc.SampleDesc.Count = 1;

+    depthStencilResourceDesc.SampleDesc.Quality = 0;

+    depthStencilResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;

+    depthStencilResourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;

+    CHECK_HR( g_Allocator->CreateResource(

+        &depthStencilAllocDesc,

+        &depthStencilResourceDesc,

+        D3D12_RESOURCE_STATE_DEPTH_WRITE,

+        &depthOptimizedClearValue,

+        &g_DepthStencilAllocation,

+        IID_PPV_ARGS(&g_DepthStencilBuffer)

+    ) );

+    CHECK_HR( g_DepthStencilBuffer->SetName(L"Depth/Stencil Resource Heap") );

+

+    D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilDesc = {};

+    depthStencilDesc.Format = DEPTH_STENCIL_FORMAT;

+    depthStencilDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;

+    depthStencilDesc.Flags = D3D12_DSV_FLAG_NONE;

+    g_Device->CreateDepthStencilView(g_DepthStencilBuffer, &depthStencilDesc, g_DepthStencilDescriptorHeap->GetCPUDescriptorHandleForHeapStart());

+

+    // -- Create a Fence & Fence Event -- //

+

+    // create the fences

+    for (int i = 0; i < FRAME_BUFFER_COUNT; i++)

+    {

+        ID3D12Fence* fence = nullptr;

+        CHECK_HR( g_Device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)) );

+        g_Fences[i].Attach(fence);

+        g_FenceValues[i] = 0; // set the initial g_Fences value to 0

+    }

+

+    // create a handle to a g_Fences event

+    g_FenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);

+    assert(g_FenceEvent);

+

+    D3D12_DESCRIPTOR_RANGE cbDescriptorRange;

+    cbDescriptorRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;

+    cbDescriptorRange.NumDescriptors = 1;

+    cbDescriptorRange.BaseShaderRegister = 0;

+    cbDescriptorRange.RegisterSpace = 0;

+    cbDescriptorRange.OffsetInDescriptorsFromTableStart = 0;

+

+    D3D12_DESCRIPTOR_RANGE textureDescRange;

+    textureDescRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;

+    textureDescRange.NumDescriptors = 1;

+    textureDescRange.BaseShaderRegister = 0;

+    textureDescRange.RegisterSpace = 0;

+    textureDescRange.OffsetInDescriptorsFromTableStart = 1;

+

+    D3D12_ROOT_PARAMETER  rootParameters[3];

+

+    rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;

+    rootParameters[0].DescriptorTable = {1, &cbDescriptorRange};

+    rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;

+

+    rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;

+    rootParameters[1].Descriptor = {1, 0};

+    rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;

+

+    rootParameters[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;

+    rootParameters[2].DescriptorTable = {1, &textureDescRange};

+    rootParameters[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;

+

+    // create root signature

+

+    // create a static sampler

+    D3D12_STATIC_SAMPLER_DESC sampler = {};

+    sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;

+    sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER;

+    sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER;

+    sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER;

+    sampler.MipLODBias = 0;

+    sampler.MaxAnisotropy = 0;

+    sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;

+    sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;

+    sampler.MinLOD = 0.0f;

+    sampler.MaxLOD = D3D12_FLOAT32_MAX;

+    sampler.ShaderRegister = 0;

+    sampler.RegisterSpace = 0;

+    sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;

+

+    D3D12_ROOT_SIGNATURE_DESC rootSignatureDesc = {};

+    rootSignatureDesc.NumParameters = _countof(rootParameters);

+    rootSignatureDesc.pParameters = rootParameters;

+    rootSignatureDesc.NumStaticSamplers = 1;

+    rootSignatureDesc.pStaticSamplers = &sampler;

+    rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |

+        D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |

+        D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |

+        D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;

+

+    CComPtr<ID3DBlob> signatureBlob;

+    ID3DBlob* signatureBlobPtr;

+    CHECK_HR( D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signatureBlobPtr, nullptr) );

+    signatureBlob.Attach(signatureBlobPtr);

+

+    ID3D12RootSignature* rootSignature = nullptr;

+    CHECK_HR( device->CreateRootSignature(0, signatureBlob->GetBufferPointer(), signatureBlob->GetBufferSize(), IID_PPV_ARGS(&rootSignature)) );

+    g_RootSignature.Attach(rootSignature);

+

+    for (int i = 0; i < FRAME_BUFFER_COUNT; ++i)

+    {

+        D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};

+        heapDesc.NumDescriptors = 2;

+        heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;

+        heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;

+        CHECK_HR( g_Device->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&g_MainDescriptorHeap[i])) );

+    }

+

+    // # CONSTANT BUFFER

+

+    for (int i = 0; i < FRAME_BUFFER_COUNT; ++i)

+    {

+        D3D12MA::ALLOCATION_DESC constantBufferUploadAllocDesc = {};

+        constantBufferUploadAllocDesc.HeapType = D3D12_HEAP_TYPE_UPLOAD;

+        D3D12_RESOURCE_DESC constantBufferResourceDesc = {};

+        constantBufferResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;

+        constantBufferResourceDesc.Alignment = 0;

+        constantBufferResourceDesc.Width = 1024 * 64;

+        constantBufferResourceDesc.Height = 1;

+        constantBufferResourceDesc.DepthOrArraySize = 1;

+        constantBufferResourceDesc.MipLevels = 1;

+        constantBufferResourceDesc.Format = DXGI_FORMAT_UNKNOWN;

+        constantBufferResourceDesc.SampleDesc.Count = 1;

+        constantBufferResourceDesc.SampleDesc.Quality = 0;

+        constantBufferResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;

+        constantBufferResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

+        CHECK_HR( g_Allocator->CreateResource(

+            &constantBufferUploadAllocDesc,

+            &constantBufferResourceDesc,

+            D3D12_RESOURCE_STATE_GENERIC_READ,

+            nullptr,

+            &g_ConstantBufferUploadAllocation[i],

+            IID_PPV_ARGS(&g_ConstantBufferUploadHeap[i])) );

+        g_ConstantBufferUploadHeap[i]->SetName(L"Constant Buffer Upload Resource Heap");

+

+        D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc = {};

+        cbvDesc.BufferLocation = g_ConstantBufferUploadHeap[i]->GetGPUVirtualAddress();

+        cbvDesc.SizeInBytes = AlignUp<UINT>(sizeof(ConstantBuffer0_PS), 256);

+        g_Device->CreateConstantBufferView(&cbvDesc, g_MainDescriptorHeap[i]->GetCPUDescriptorHandleForHeapStart());

+

+        D3D12_RANGE readRange{0, 0};

+        CHECK_HR( g_ConstantBufferUploadHeap[i]->Map(0, &readRange, &g_ConstantBufferAddress[i]) );

+    }

+

+    // create input layout

+

+    // The input layout is used by the Input Assembler so that it knows

+    // how to read the vertex data bound to it.

+

+    const D3D12_INPUT_ELEMENT_DESC inputLayout[] =

+    {

+        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,    0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },

+        { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,       0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },

+    };

+

+    // create a pipeline state object (PSO)

+

+    // In a real application, you will have many pso's. for each different shader

+    // or different combinations of shaders, different blend states or different rasterizer states,

+    // different topology types (point, line, triangle, patch), or a different number

+    // of render targets you will need a pso

+

+    // VS is the only required shader for a pso. You might be wondering when a case would be where

+    // you only set the VS. It's possible that you have a pso that only outputs data with the stream

+    // output, and not on a render target, which means you would not need anything after the stream

+    // output.

+

+    D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; // a structure to define a pso

+    psoDesc.InputLayout.NumElements = _countof(inputLayout);

+    psoDesc.InputLayout.pInputElementDescs = inputLayout;

+    psoDesc.pRootSignature = g_RootSignature; // the root signature that describes the input data this pso needs

+    psoDesc.VS.BytecodeLength = sizeof(VS::g_main);

+    psoDesc.VS.pShaderBytecode = VS::g_main;

+    psoDesc.PS.BytecodeLength = sizeof(PS::g_main);

+    psoDesc.PS.pShaderBytecode = PS::g_main;

+    psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; // type of topology we are drawing

+    psoDesc.RTVFormats[0] = RENDER_TARGET_FORMAT; // format of the render target

+    psoDesc.DSVFormat = DEPTH_STENCIL_FORMAT;

+    psoDesc.SampleDesc = sampleDesc; // must be the same sample description as the swapchain and depth/stencil buffer

+    psoDesc.SampleMask = 0xffffffff; // sample mask has to do with multi-sampling. 0xffffffff means point sampling is done

+    SetDefaultRasterizerDesc(psoDesc.RasterizerState);

+    SetDefaultBlendDesc(psoDesc.BlendState);

+    psoDesc.NumRenderTargets = 1; // we are only binding one render target

+    SetDefaultDepthStencilDesc(psoDesc.DepthStencilState);

+

+    // create the pso

+    ID3D12PipelineState* pipelineStateObject;

+    CHECK_HR( device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&pipelineStateObject)) );

+    g_PipelineStateObject.Attach(pipelineStateObject);

+

+    // Create vertex buffer

+

+    // a triangle

+    Vertex vList[] = {

+        // front face

+        { -0.5f,  0.5f, -0.5f, 0.f, 0.f },

+        {  0.5f, -0.5f, -0.5f, 1.f, 1.f },

+        { -0.5f, -0.5f, -0.5f, 0.f, 1.f },

+        {  0.5f,  0.5f, -0.5f, 1.f, 0.f },

+

+        // right side face

+        {  0.5f, -0.5f, -0.5f, 0.f, 1.f },

+        {  0.5f,  0.5f,  0.5f, 1.f, 0.f },

+        {  0.5f, -0.5f,  0.5f, 1.f, 1.f },

+        {  0.5f,  0.5f, -0.5f, 0.f, 0.f },

+

+        // left side face

+        { -0.5f,  0.5f,  0.5f, 0.f, 0.f },

+        { -0.5f, -0.5f, -0.5f, 1.f, 1.f },

+        { -0.5f, -0.5f,  0.5f, 0.f, 1.f },

+        { -0.5f,  0.5f, -0.5f, 1.f, 0.f },

+

+        // back face

+        {  0.5f,  0.5f,  0.5f, 0.f, 0.f },

+        { -0.5f, -0.5f,  0.5f, 1.f, 1.f },

+        {  0.5f, -0.5f,  0.5f, 0.f, 1.f },

+        { -0.5f,  0.5f,  0.5f, 1.f, 0.f },

+

+        // top face

+        { -0.5f,  0.5f, -0.5f, 0.f, 0.f },

+        {  0.5f,  0.5f,  0.5f, 1.f, 1.f },

+        {  0.5f,  0.5f, -0.5f, 0.f, 1.f },

+        { -0.5f,  0.5f,  0.5f, 1.f, 0.f },

+

+        // bottom face

+        {  0.5f, -0.5f,  0.5f, 0.f, 0.f },

+        { -0.5f, -0.5f, -0.5f, 1.f, 1.f },

+        {  0.5f, -0.5f, -0.5f, 0.f, 1.f },

+        { -0.5f, -0.5f,  0.5f, 1.f, 0.f },

+    };

+    const uint32_t vBufferSize = sizeof(vList);

+

+    // create default heap

+    // default heap is memory on the GPU. Only the GPU has access to this memory

+    // To get data into this heap, we will have to upload the data using

+    // an upload heap

+    D3D12MA::ALLOCATION_DESC vertexBufferAllocDesc = {};

+    vertexBufferAllocDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;

+    D3D12_RESOURCE_DESC vertexBufferResourceDesc = {};

+    vertexBufferResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;

+    vertexBufferResourceDesc.Alignment = 0;

+    vertexBufferResourceDesc.Width = vBufferSize;

+    vertexBufferResourceDesc.Height = 1;

+    vertexBufferResourceDesc.DepthOrArraySize = 1;

+    vertexBufferResourceDesc.MipLevels = 1;

+    vertexBufferResourceDesc.Format = DXGI_FORMAT_UNKNOWN;

+    vertexBufferResourceDesc.SampleDesc.Count = 1;

+    vertexBufferResourceDesc.SampleDesc.Quality = 0;

+    vertexBufferResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;

+    vertexBufferResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

+    ID3D12Resource* vertexBufferPtr;

+    CHECK_HR( g_Allocator->CreateResource(

+        &vertexBufferAllocDesc,

+        &vertexBufferResourceDesc, // resource description for a buffer

+        D3D12_RESOURCE_STATE_COPY_DEST, // we will start this heap in the copy destination state since we will copy data

+                                        // from the upload heap to this heap

+        nullptr, // optimized clear value must be null for this type of resource. used for render targets and depth/stencil buffers

+        &g_VertexBufferAllocation,

+        IID_PPV_ARGS(&vertexBufferPtr)) );

+    g_VertexBuffer.Attach(vertexBufferPtr);

+

+    // we can give resource heaps a name so when we debug with the graphics debugger we know what resource we are looking at

+    g_VertexBuffer->SetName(L"Vertex Buffer Resource Heap");

+

+    // create upload heap

+    // upload heaps are used to upload data to the GPU. CPU can write to it, GPU can read from it

+    // We will upload the vertex buffer using this heap to the default heap

+    D3D12MA::ALLOCATION_DESC vBufferUploadAllocDesc = {};

+    vBufferUploadAllocDesc.HeapType = D3D12_HEAP_TYPE_UPLOAD;

+    D3D12_RESOURCE_DESC vertexBufferUploadResourceDesc = {};

+    vertexBufferUploadResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;

+    vertexBufferUploadResourceDesc.Alignment = 0;

+    vertexBufferUploadResourceDesc.Width = vBufferSize;

+    vertexBufferUploadResourceDesc.Height = 1;

+    vertexBufferUploadResourceDesc.DepthOrArraySize = 1;

+    vertexBufferUploadResourceDesc.MipLevels = 1;

+    vertexBufferUploadResourceDesc.Format = DXGI_FORMAT_UNKNOWN;

+    vertexBufferUploadResourceDesc.SampleDesc.Count = 1;

+    vertexBufferUploadResourceDesc.SampleDesc.Quality = 0;

+    vertexBufferUploadResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;

+    vertexBufferUploadResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

+    CComPtr<ID3D12Resource> vBufferUploadHeap;

+    D3D12MA::Allocation* vBufferUploadHeapAllocation = nullptr;

+    CHECK_HR( g_Allocator->CreateResource(

+        &vBufferUploadAllocDesc,

+        &vertexBufferUploadResourceDesc, // resource description for a buffer

+        D3D12_RESOURCE_STATE_GENERIC_READ, // GPU will read from this buffer and copy its contents to the default heap

+        nullptr,

+        &vBufferUploadHeapAllocation,

+        IID_PPV_ARGS(&vBufferUploadHeap)) );

+    vBufferUploadHeap->SetName(L"Vertex Buffer Upload Resource Heap");

+

+    // store vertex buffer in upload heap

+    D3D12_SUBRESOURCE_DATA vertexData = {};

+    vertexData.pData = reinterpret_cast<BYTE*>(vList); // pointer to our vertex array

+    vertexData.RowPitch = vBufferSize; // size of all our triangle vertex data

+    vertexData.SlicePitch = vBufferSize; // also the size of our triangle vertex data

+

+    CHECK_HR( g_CommandList->Reset(g_CommandAllocators[g_FrameIndex], NULL) );

+

+    // we are now creating a command with the command list to copy the data from

+    // the upload heap to the default heap

+    UINT64 r = UpdateSubresources(g_CommandList, g_VertexBuffer, vBufferUploadHeap, 0, 0, 1, &vertexData);

+    assert(r);

+

+    // transition the vertex buffer data from copy destination state to vertex buffer state

+    D3D12_RESOURCE_BARRIER vbBarrier = {};

+    vbBarrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;

+    vbBarrier.Transition.pResource = g_VertexBuffer;

+    vbBarrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;

+    vbBarrier.Transition.StateAfter = D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;

+    vbBarrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;

+    g_CommandList->ResourceBarrier(1, &vbBarrier);

+

+    // Create index buffer

+

+    // a quad (2 triangles)

+    uint16_t iList[] = {

+        // ffront face

+        0, 1, 2, // first triangle

+        0, 3, 1, // second triangle

+

+        // left face

+        4, 5, 6, // first triangle

+        4, 7, 5, // second triangle

+

+        // right face

+        8, 9, 10, // first triangle

+        8, 11, 9, // second triangle

+

+        // back face

+        12, 13, 14, // first triangle

+        12, 15, 13, // second triangle

+

+        // top face

+        16, 17, 18, // first triangle

+        16, 19, 17, // second triangle

+

+        // bottom face

+        20, 21, 22, // first triangle

+        20, 23, 21, // second triangle

+    };

+

+    g_CubeIndexCount = (uint32_t)_countof(iList);

+

+    size_t iBufferSize = sizeof(iList);

+

+    // create default heap to hold index buffer

+    D3D12MA::ALLOCATION_DESC indexBufferAllocDesc = {};

+    indexBufferAllocDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;

+    D3D12_RESOURCE_DESC indexBufferResourceDesc = {};

+    indexBufferResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;

+    indexBufferResourceDesc.Alignment = 0;

+    indexBufferResourceDesc.Width = iBufferSize;

+    indexBufferResourceDesc.Height = 1;

+    indexBufferResourceDesc.DepthOrArraySize = 1;

+    indexBufferResourceDesc.MipLevels = 1;

+    indexBufferResourceDesc.Format = DXGI_FORMAT_UNKNOWN;

+    indexBufferResourceDesc.SampleDesc.Count = 1;

+    indexBufferResourceDesc.SampleDesc.Quality = 0;

+    indexBufferResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;

+    indexBufferResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

+    CHECK_HR( g_Allocator->CreateResource(

+        &indexBufferAllocDesc,

+        &indexBufferResourceDesc, // resource description for a buffer

+        D3D12_RESOURCE_STATE_COPY_DEST, // start in the copy destination state

+        nullptr, // optimized clear value must be null for this type of resource

+        &g_IndexBufferAllocation,

+        IID_PPV_ARGS(&g_IndexBuffer)) );

+

+    // we can give resource heaps a name so when we debug with the graphics debugger we know what resource we are looking at

+    g_IndexBuffer->SetName(L"Index Buffer Resource Heap");

+

+    // create upload heap to upload index buffer

+    D3D12MA::ALLOCATION_DESC iBufferUploadAllocDesc = {};

+    iBufferUploadAllocDesc.HeapType = D3D12_HEAP_TYPE_UPLOAD;

+    D3D12_RESOURCE_DESC indexBufferUploadResourceDesc = {};

+    indexBufferUploadResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;

+    indexBufferUploadResourceDesc.Alignment = 0;

+    indexBufferUploadResourceDesc.Width = iBufferSize;

+    indexBufferUploadResourceDesc.Height = 1;

+    indexBufferUploadResourceDesc.DepthOrArraySize = 1;

+    indexBufferUploadResourceDesc.MipLevels = 1;

+    indexBufferUploadResourceDesc.Format = DXGI_FORMAT_UNKNOWN;

+    indexBufferUploadResourceDesc.SampleDesc.Count = 1;

+    indexBufferUploadResourceDesc.SampleDesc.Quality = 0;

+    indexBufferUploadResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;

+    indexBufferUploadResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

+    CComPtr<ID3D12Resource> iBufferUploadHeap;

+    D3D12MA::Allocation* iBufferUploadHeapAllocation = nullptr;

+    CHECK_HR( g_Allocator->CreateResource(

+        &iBufferUploadAllocDesc,

+        &indexBufferUploadResourceDesc, // resource description for a buffer

+        D3D12_RESOURCE_STATE_GENERIC_READ, // GPU will read from this buffer and copy its contents to the default heap

+        nullptr,

+        &iBufferUploadHeapAllocation,

+        IID_PPV_ARGS(&iBufferUploadHeap)) );

+    CHECK_HR( iBufferUploadHeap->SetName(L"Index Buffer Upload Resource Heap") );

+

+    // store vertex buffer in upload heap

+    D3D12_SUBRESOURCE_DATA indexData = {};

+    indexData.pData = iList; // pointer to our index array

+    indexData.RowPitch = iBufferSize; // size of all our index buffer

+    indexData.SlicePitch = iBufferSize; // also the size of our index buffer

+

+                                        // we are now creating a command with the command list to copy the data from

+                                        // the upload heap to the default heap

+    r = UpdateSubresources(g_CommandList, g_IndexBuffer, iBufferUploadHeap, 0, 0, 1, &indexData);

+    assert(r);

+

+    // transition the index buffer data from copy destination state to vertex buffer state

+    D3D12_RESOURCE_BARRIER ibBarrier = {};

+    ibBarrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;

+    ibBarrier.Transition.pResource = g_IndexBuffer;

+    ibBarrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;

+    ibBarrier.Transition.StateAfter = D3D12_RESOURCE_STATE_INDEX_BUFFER;

+    ibBarrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;

+    g_CommandList->ResourceBarrier(1, &ibBarrier);

+

+    // create a vertex buffer view for the triangle. We get the GPU memory address to the vertex pointer using the GetGPUVirtualAddress() method

+    g_VertexBufferView.BufferLocation = g_VertexBuffer->GetGPUVirtualAddress();

+    g_VertexBufferView.StrideInBytes = sizeof(Vertex);

+    g_VertexBufferView.SizeInBytes = vBufferSize;

+

+    // create a index buffer view for the triangle. We get the GPU memory address to the vertex pointer using the GetGPUVirtualAddress() method

+    g_IndexBufferView.BufferLocation = g_IndexBuffer->GetGPUVirtualAddress();

+    g_IndexBufferView.Format = DXGI_FORMAT_R16_UINT;

+    g_IndexBufferView.SizeInBytes = (UINT)iBufferSize;

+

+    D3D12MA::ALLOCATION_DESC cbPerObjectUploadAllocDesc = {};

+    cbPerObjectUploadAllocDesc.HeapType = D3D12_HEAP_TYPE_UPLOAD;

+    D3D12_RESOURCE_DESC cbPerObjectUploadResourceDesc = {};

+    cbPerObjectUploadResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;

+    cbPerObjectUploadResourceDesc.Alignment = 0;

+    cbPerObjectUploadResourceDesc.Width = 1024 * 64;

+    cbPerObjectUploadResourceDesc.Height = 1;

+    cbPerObjectUploadResourceDesc.DepthOrArraySize = 1;

+    cbPerObjectUploadResourceDesc.MipLevels = 1;

+    cbPerObjectUploadResourceDesc.Format = DXGI_FORMAT_UNKNOWN;

+    cbPerObjectUploadResourceDesc.SampleDesc.Count = 1;

+    cbPerObjectUploadResourceDesc.SampleDesc.Quality = 0;

+    cbPerObjectUploadResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;

+    cbPerObjectUploadResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

+    for (size_t i = 0; i < FRAME_BUFFER_COUNT; ++i)

+    {

+        // create resource for cube 1

+        CHECK_HR( g_Allocator->CreateResource(

+            &cbPerObjectUploadAllocDesc,

+            &cbPerObjectUploadResourceDesc, // size of the resource heap. Must be a multiple of 64KB for single-textures and constant buffers

+            D3D12_RESOURCE_STATE_GENERIC_READ, // will be data that is read from so we keep it in the generic read state

+            nullptr, // we do not have use an optimized clear value for constant buffers

+            &g_CbPerObjectUploadHeapAllocations[i],

+            IID_PPV_ARGS(&g_CbPerObjectUploadHeaps[i])) );

+        g_CbPerObjectUploadHeaps[i]->SetName(L"Constant Buffer Upload Resource Heap");

+

+        D3D12_RANGE readRange{0, 0};    // We do not intend to read from this resource on the CPU. (so end is less than or equal to begin)

+                                          // map the resource heap to get a gpu virtual address to the beginning of the heap

+        CHECK_HR( g_CbPerObjectUploadHeaps[i]->Map(0, &readRange, &g_CbPerObjectAddress[i]) );

+    }

+

+    // # TEXTURE

+

+    D3D12_RESOURCE_DESC textureDesc;

+    size_t imageBytesPerRow;

+    size_t imageSize = SIZE_MAX;

+    std::vector<char> imageData;

+    {

+        const UINT sizeX = 256;

+        const UINT sizeY = 256;

+        const DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;

+        const UINT bytesPerPixel = 4;

+

+        imageBytesPerRow = sizeX * bytesPerPixel;

+        imageSize = sizeY * imageBytesPerRow;

+

+        imageData.resize(imageSize);

+        char* rowPtr = (char*)imageData.data();

+        for(UINT y = 0; y < sizeY; ++y)

+        {

+            char* pixelPtr = rowPtr;

+            for(UINT x = 0; x < sizeX; ++x)

+            {

+                *(UINT8*)(pixelPtr    ) = (UINT8)x; // R

+                *(UINT8*)(pixelPtr + 1) = (UINT8)y; // G

+                *(UINT8*)(pixelPtr + 2) = 0x00; // B

+                *(UINT8*)(pixelPtr + 3) = 0xFF; // A

+

+                *(UINT8*)(pixelPtr    ) = x > 128 ? 0xFF : 00;

+                *(UINT8*)(pixelPtr + 1) = y > 128 ? 0xFF : 00;

+                pixelPtr += bytesPerPixel;

+            }

+            rowPtr += imageBytesPerRow;

+        }

+

+        textureDesc = {};

+        textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;

+        textureDesc.Alignment = 0;

+        textureDesc.Width = sizeX;

+        textureDesc.Height = sizeY;

+        textureDesc.DepthOrArraySize = 1;

+        textureDesc.MipLevels = 1;

+        textureDesc.Format = format;

+        textureDesc.SampleDesc.Count = 1;

+        textureDesc.SampleDesc.Quality = 0;

+        textureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;

+        textureDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

+    }

+

+    D3D12MA::ALLOCATION_DESC textureAllocDesc = {};

+    textureAllocDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;

+    CHECK_HR( g_Allocator->CreateResource(

+        &textureAllocDesc,

+        &textureDesc,

+        D3D12_RESOURCE_STATE_COPY_DEST,

+        nullptr, // pOptimizedClearValue

+        &g_TextureAllocation,

+        IID_PPV_ARGS(&g_Texture)) );

+    g_Texture->SetName(L"g_Texture");

+

+    UINT64 textureUploadBufferSize;

+    device->GetCopyableFootprints(

+        &textureDesc,

+        0, // FirstSubresource

+        1, // NumSubresources

+        0, // BaseOffset

+        nullptr, // pLayouts

+        nullptr, // pNumRows

+        nullptr, // pRowSizeInBytes

+        &textureUploadBufferSize); // pTotalBytes

+

+    D3D12MA::ALLOCATION_DESC textureUploadAllocDesc = {};

+    textureUploadAllocDesc.HeapType = D3D12_HEAP_TYPE_UPLOAD;

+    D3D12_RESOURCE_DESC textureUploadResourceDesc = {};

+    textureUploadResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;

+    textureUploadResourceDesc.Alignment = 0;

+    textureUploadResourceDesc.Width = textureUploadBufferSize;

+    textureUploadResourceDesc.Height = 1;

+    textureUploadResourceDesc.DepthOrArraySize = 1;

+    textureUploadResourceDesc.MipLevels = 1;

+    textureUploadResourceDesc.Format = DXGI_FORMAT_UNKNOWN;

+    textureUploadResourceDesc.SampleDesc.Count = 1;

+    textureUploadResourceDesc.SampleDesc.Quality = 0;

+    textureUploadResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;

+    textureUploadResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

+    CComPtr<ID3D12Resource> textureUpload;

+    D3D12MA::Allocation* textureUploadAllocation;

+    CHECK_HR( g_Allocator->CreateResource(

+        &textureUploadAllocDesc,

+        &textureUploadResourceDesc,

+        D3D12_RESOURCE_STATE_GENERIC_READ,

+        nullptr, // pOptimizedClearValue

+        &textureUploadAllocation,

+        IID_PPV_ARGS(&textureUpload)) );

+    textureUpload->SetName(L"textureUpload");

+

+    D3D12_SUBRESOURCE_DATA textureSubresourceData = {};

+    textureSubresourceData.pData = imageData.data();

+    textureSubresourceData.RowPitch = imageBytesPerRow;

+    textureSubresourceData.SlicePitch = imageBytesPerRow * textureDesc.Height;

+

+    UpdateSubresources(g_CommandList, g_Texture, textureUpload, 0, 0, 1, &textureSubresourceData);

+

+    D3D12_RESOURCE_BARRIER textureBarrier = {};

+    textureBarrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;

+    textureBarrier.Transition.pResource = g_Texture;

+    textureBarrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;

+    textureBarrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;

+    textureBarrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;

+    g_CommandList->ResourceBarrier(1, &textureBarrier);

+

+    D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};

+    srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;

+    srvDesc.Format = textureDesc.Format;

+    srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;

+    srvDesc.Texture2D.MipLevels = 1;

+    for (size_t i = 0; i < FRAME_BUFFER_COUNT; ++i)

+    {

+        D3D12_CPU_DESCRIPTOR_HANDLE descHandle = {

+            g_MainDescriptorHeap[i]->GetCPUDescriptorHandleForHeapStart().ptr +

+            g_Device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)};

+        g_Device->CreateShaderResourceView(g_Texture, &srvDesc, descHandle);

+    }

+

+    // # END OF INITIAL COMMAND LIST

+

+    // Now we execute the command list to upload the initial assets (triangle data)

+    g_CommandList->Close();

+    ID3D12CommandList* ppCommandLists[] = { g_CommandList };

+    commandQueue->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists);

+

+    // increment the fence value now, otherwise the buffer might not be uploaded by the time we start drawing

+    WaitGPUIdle(g_FrameIndex);

+

+    textureUploadAllocation->Release();

+    iBufferUploadHeapAllocation->Release();

+    vBufferUploadHeapAllocation->Release();

+}

+

+void Update()

+{

+    {

+        const float f = sin(g_Time * (PI * 2.f)) * 0.5f + 0.5f;

+        ConstantBuffer0_PS cb;

+        cb.Color = vec4(f, f, f, 1.f);

+        memcpy(g_ConstantBufferAddress[g_FrameIndex], &cb, sizeof(cb));

+    }

+

+    {

+        const mat4 projection = mat4::Perspective(

+            45.f * (PI / 180.f), // fovY

+            (float)SIZE_X / (float)SIZE_Y, // aspectRatio

+            0.1f, // zNear

+            1000.0f); // zFar

+        const mat4 view = mat4::LookAt(

+            vec3(0.f, 0.f, 0.f), // at

+            vec3(-.4f, 1.7f, -3.5f), // eye

+            vec3(0.f, 1.f, 0.f)); // up

+        const mat4 viewProjection = view * projection;

+

+        mat4 cube1World = mat4::RotationZ(g_Time);

+

+        ConstantBuffer1_VS cb;

+        mat4 worldViewProjection = cube1World * viewProjection;

+        cb.WorldViewProj = worldViewProjection.Transposed();

+        memcpy(g_CbPerObjectAddress[g_FrameIndex], &cb, sizeof(cb));

+

+        mat4 cube2World = mat4::Scaling(0.5f) *

+            mat4::RotationX(g_Time * 2.0f) *

+            mat4::Translation(vec3(-1.2f, 0.f, 0.f)) *

+            cube1World;

+

+        worldViewProjection = cube2World * viewProjection;

+        cb.WorldViewProj = worldViewProjection.Transposed();

+        memcpy((char*)g_CbPerObjectAddress[g_FrameIndex] + ConstantBufferPerObjectAlignedSize, &cb, sizeof(cb));

+    }

+}

+

+void Render() // execute the command list

+{

+    // # Here was UpdatePipeline function.

+

+    // swap the current rtv buffer index so we draw on the correct buffer

+    g_FrameIndex = g_SwapChain->GetCurrentBackBufferIndex();

+    // We have to wait for the gpu to finish with the command allocator before we reset it

+    WaitForFrame(g_FrameIndex);

+    // increment g_FenceValues for next frame

+    g_FenceValues[g_FrameIndex]++;

+

+    // we can only reset an allocator once the gpu is done with it

+    // resetting an allocator frees the memory that the command list was stored in

+    CHECK_HR( g_CommandAllocators[g_FrameIndex]->Reset() );

+

+    // reset the command list. by resetting the command list we are putting it into

+    // a recording state so we can start recording commands into the command allocator.

+    // the command allocator that we reference here may have multiple command lists

+    // associated with it, but only one can be recording at any time. Make sure

+    // that any other command lists associated to this command allocator are in

+    // the closed state (not recording).

+    // Here you will pass an initial pipeline state object as the second parameter,

+    // but in this tutorial we are only clearing the rtv, and do not actually need

+    // anything but an initial default pipeline, which is what we get by setting

+    // the second parameter to NULL

+    CHECK_HR( g_CommandList->Reset(g_CommandAllocators[g_FrameIndex], NULL) );

+

+    // here we start recording commands into the g_CommandList (which all the commands will be stored in the g_CommandAllocators)

+

+    // transition the "g_FrameIndex" render target from the present state to the render target state so the command list draws to it starting from here

+    D3D12_RESOURCE_BARRIER presentToRenderTargetBarrier = {};

+    presentToRenderTargetBarrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;

+    presentToRenderTargetBarrier.Transition.pResource = g_RenderTargets[g_FrameIndex];

+    presentToRenderTargetBarrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;

+    presentToRenderTargetBarrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;

+    presentToRenderTargetBarrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;

+    g_CommandList->ResourceBarrier(1, &presentToRenderTargetBarrier);

+

+    // here we again get the handle to our current render target view so we can set it as the render target in the output merger stage of the pipeline

+    D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = {

+        g_RtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart().ptr + g_FrameIndex * g_RtvDescriptorSize};

+    D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle =

+        g_DepthStencilDescriptorHeap->GetCPUDescriptorHandleForHeapStart();

+

+    // set the render target for the output merger stage (the output of the pipeline)

+    g_CommandList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle);

+

+    g_CommandList->ClearDepthStencilView(g_DepthStencilDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);

+

+    // Clear the render target by using the ClearRenderTargetView command

+    const float clearColor[] = { 0.0f, 0.2f, 0.4f, 1.0f };

+    g_CommandList->ClearRenderTargetView(rtvHandle, clearColor, 0, nullptr);

+

+    g_CommandList->SetPipelineState(g_PipelineStateObject);

+

+    g_CommandList->SetGraphicsRootSignature(g_RootSignature);

+

+    ID3D12DescriptorHeap* descriptorHeaps[] = { g_MainDescriptorHeap[g_FrameIndex] };

+    g_CommandList->SetDescriptorHeaps(_countof(descriptorHeaps), descriptorHeaps);

+

+    g_CommandList->SetGraphicsRootDescriptorTable(0, g_MainDescriptorHeap[g_FrameIndex]->GetGPUDescriptorHandleForHeapStart());

+    g_CommandList->SetGraphicsRootDescriptorTable(2, g_MainDescriptorHeap[g_FrameIndex]->GetGPUDescriptorHandleForHeapStart());

+

+    D3D12_VIEWPORT viewport{0.f, 0.f, (float)SIZE_X, (float)SIZE_Y, 0.f, 1.f};

+    g_CommandList->RSSetViewports(1, &viewport); // set the viewports

+

+    D3D12_RECT scissorRect{0, 0, SIZE_X, SIZE_Y};

+    g_CommandList->RSSetScissorRects(1, &scissorRect); // set the scissor rects

+

+    g_CommandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // set the primitive topology

+    g_CommandList->IASetVertexBuffers(0, 1, &g_VertexBufferView); // set the vertex buffer (using the vertex buffer view)

+    g_CommandList->IASetIndexBuffer(&g_IndexBufferView);

+

+    g_CommandList->SetGraphicsRootConstantBufferView(1,

+        g_CbPerObjectUploadHeaps[g_FrameIndex]->GetGPUVirtualAddress());

+    g_CommandList->DrawIndexedInstanced(g_CubeIndexCount, 1, 0, 0, 0);

+

+    g_CommandList->SetGraphicsRootConstantBufferView(1,

+        g_CbPerObjectUploadHeaps[g_FrameIndex]->GetGPUVirtualAddress() + ConstantBufferPerObjectAlignedSize);

+    g_CommandList->DrawIndexedInstanced(g_CubeIndexCount, 1, 0, 0, 0);

+

+    // transition the "g_FrameIndex" render target from the render target state to the present state. If the debug layer is enabled, you will receive a

+    // warning if present is called on the render target when it's not in the present state

+    D3D12_RESOURCE_BARRIER renderTargetToPresentBarrier = {};

+    renderTargetToPresentBarrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;

+    renderTargetToPresentBarrier.Transition.pResource = g_RenderTargets[g_FrameIndex];

+    renderTargetToPresentBarrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;

+    renderTargetToPresentBarrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;

+    renderTargetToPresentBarrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;

+    g_CommandList->ResourceBarrier(1, &renderTargetToPresentBarrier);

+

+    CHECK_HR( g_CommandList->Close() );

+

+    // ================

+

+    // create an array of command lists (only one command list here)

+    ID3D12CommandList* ppCommandLists[] = { g_CommandList };

+

+    // execute the array of command lists

+    g_CommandQueue->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists);

+

+    // this command goes in at the end of our command queue. we will know when our command queue 

+    // has finished because the g_Fences value will be set to "g_FenceValues" from the GPU since the command

+    // queue is being executed on the GPU

+    CHECK_HR( g_CommandQueue->Signal(g_Fences[g_FrameIndex], g_FenceValues[g_FrameIndex]) );

+

+    // present the current backbuffer

+    CHECK_HR( g_SwapChain->Present(PRESENT_SYNC_INTERVAL, 0) );

+}

+

+void Cleanup() // release com ojects and clean up memory

+{

+    // wait for the gpu to finish all frames

+    for (size_t i = 0; i < FRAME_BUFFER_COUNT; ++i)

+    {

+        WaitForFrame(i);

+        CHECK_HR( g_CommandQueue->Wait(g_Fences[i], g_FenceValues[i]) );

+    }

+

+    // get swapchain out of full screen before exiting

+    BOOL fs = false;

+    CHECK_HR( g_SwapChain->GetFullscreenState(&fs, NULL) );

+    if (fs)

+        g_SwapChain->SetFullscreenState(false, NULL);

+

+    WaitGPUIdle(0);

+

+    g_Texture.Release();

+    g_TextureAllocation->Release(); g_TextureAllocation = nullptr;

+    g_IndexBuffer.Release();

+    g_IndexBufferAllocation->Release(); g_IndexBufferAllocation = nullptr;

+    g_VertexBuffer.Release();

+    g_VertexBufferAllocation->Release(); g_VertexBufferAllocation = nullptr;

+    g_PipelineStateObject.Release();

+    g_RootSignature.Release();

+

+    CloseHandle(g_FenceEvent);

+    g_CommandList.Release();

+    g_CommandQueue.Release();

+

+    for (size_t i = FRAME_BUFFER_COUNT; i--; )

+    {

+        g_CbPerObjectUploadHeaps[i].Release();

+        g_CbPerObjectUploadHeapAllocations[i]->Release(); g_CbPerObjectUploadHeapAllocations[i] = nullptr;

+        g_MainDescriptorHeap[i].Release();

+        g_ConstantBufferUploadHeap[i].Release();

+        g_ConstantBufferUploadAllocation[i]->Release(); g_ConstantBufferUploadAllocation[i] = nullptr;

+    }

+

+    g_DepthStencilDescriptorHeap.Release();

+    g_DepthStencilBuffer.Release();

+    g_DepthStencilAllocation->Release(); g_DepthStencilAllocation = nullptr;

+    g_RtvDescriptorHeap.Release();

+    for (size_t i = FRAME_BUFFER_COUNT; i--; )

+    {

+        g_RenderTargets[i].Release();

+        g_CommandAllocators[i].Release();

+        g_Fences[i].Release();

+    }

+    

+    g_Allocator->Release(); g_Allocator = nullptr;

+    if(ENABLE_CPU_ALLOCATION_CALLBACKS)

+    {

+        assert(g_CpuAllocationCount.load() == 0);

+    }

+    

+    g_Device.Release();

+    g_SwapChain.Release();

+}

+

+static void ExecuteTests()

+{

+    try

+    {

+        TestContext ctx = {};

+        ctx.device = g_Device;

+        ctx.allocator = g_Allocator;

+        Test(ctx);

+    }

+    catch(const std::exception& ex)

+    {

+        wprintf(L"ERROR: %hs\n", ex.what());

+    }

+}

+

+static void OnKeyDown(WPARAM key)

+{

+    switch (key)

+    {

+    case 'T':

+        ExecuteTests();

+        break;

+

+    case VK_ESCAPE:

+        PostMessage(g_Wnd, WM_CLOSE, 0, 0);

+        break;

+    }

+}

+

+static LRESULT WINAPI WndProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)

+{

+    switch(msg)

+    {

+    case WM_CREATE:

+        g_Wnd = wnd;

+        InitD3D();

+        g_TimeOffset = GetTickCount64();

+        return 0;

+

+    case WM_DESTROY:

+        Cleanup();

+        PostQuitMessage(0);

+        return 0;

+

+    case WM_KEYDOWN:

+        OnKeyDown(wParam);

+        return 0;

+    }

+

+    return DefWindowProc(wnd, msg, wParam, lParam);

+}

+

+ID3D12GraphicsCommandList* BeginCommandList()

+{

+    CHECK_HR( g_CommandList->Reset(g_CommandAllocators[g_FrameIndex], NULL) );

+

+    return g_CommandList;

+}

+

+void EndCommandList(ID3D12GraphicsCommandList* cmdList)

+{

+    cmdList->Close();

+

+    ID3D12CommandList* genericCmdList = cmdList;

+    g_CommandQueue->ExecuteCommandLists(1, &genericCmdList);

+

+    WaitGPUIdle(g_FrameIndex);

+}

+

+int main()

+{

+    g_Instance = (HINSTANCE)GetModuleHandle(NULL);

+

+    CoInitialize(NULL);

+

+    WNDCLASSEX wndClass;

+    ZeroMemory(&wndClass, sizeof(wndClass));

+    wndClass.cbSize = sizeof(wndClass);

+    wndClass.style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS;

+    wndClass.hbrBackground = NULL;

+    wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);

+    wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);

+    wndClass.hInstance = g_Instance;

+    wndClass.lpfnWndProc = &WndProc;

+    wndClass.lpszClassName = CLASS_NAME;

+

+    ATOM classR = RegisterClassEx(&wndClass);

+    assert(classR);

+

+    DWORD style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE;

+    DWORD exStyle = 0;

+

+    RECT rect = { 0, 0, SIZE_X, SIZE_Y };

+    AdjustWindowRectEx(&rect, style, FALSE, exStyle);

+    g_Wnd = CreateWindowEx(

+        exStyle,

+        CLASS_NAME,

+        WINDOW_TITLE,

+        style,

+        CW_USEDEFAULT, CW_USEDEFAULT,

+        rect.right - rect.left, rect.bottom - rect.top,

+        NULL,

+        NULL,

+        g_Instance,

+        0);

+    assert(g_Wnd);

+

+    MSG msg;

+    for (;;)

+    {

+        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))

+        {

+            if (msg.message == WM_QUIT)

+                break;

+            TranslateMessage(&msg);

+            DispatchMessage(&msg);

+        }

+        else

+        {

+            const UINT64 newTimeValue = GetTickCount64() - g_TimeOffset;

+            g_TimeDelta = (float)(newTimeValue - g_TimeValue) * 0.001f;

+            g_TimeValue = newTimeValue;

+            g_Time = (float)newTimeValue * 0.001f;

+

+            Update();

+            Render();

+        }

+    }

+    return (int)msg.wParam;

+} 

diff --git a/src/Doxyfile b/src/Doxyfile
new file mode 100644
index 0000000..0b2b439
--- /dev/null
+++ b/src/Doxyfile
@@ -0,0 +1,2492 @@
+# Doxyfile 1.8.13

+

+# This file describes the settings to be used by the documentation system

+# doxygen (www.doxygen.org) for a project.

+#

+# All text after a double hash (##) is considered a comment and is placed in

+# front of the TAG it is preceding.

+#

+# All text after a single hash (#) is considered a comment and will be ignored.

+# The format is:

+# TAG = value [value, ...]

+# For lists, items can also be appended using:

+# TAG += value [value, ...]

+# Values that contain spaces should be placed between quotes (\" \").

+

+#---------------------------------------------------------------------------

+# Project related configuration options

+#---------------------------------------------------------------------------

+

+# This tag specifies the encoding used for all characters in the config file

+# that follow. The default is UTF-8 which is also the encoding used for all text

+# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv

+# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv

+# for the list of possible encodings.

+# The default value is: UTF-8.

+

+DOXYFILE_ENCODING      = UTF-8

+

+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by

+# double-quotes, unless you are using Doxywizard) that should identify the

+# project for which the documentation is generated. This name is used in the

+# title of most generated pages and in a few other places.

+# The default value is: My Project.

+

+PROJECT_NAME           = "Direct3D 12 Memory Allocator"

+

+# The PROJECT_NUMBER tag can be used to enter a project or revision number. This

+# could be handy for archiving the generated documentation or if some version

+# control system is used.

+

+PROJECT_NUMBER         =

+

+# Using the PROJECT_BRIEF tag one can provide an optional one line description

+# for a project that appears at the top of each page and should give viewer a

+# quick idea about the purpose of the project. Keep the description short.

+

+PROJECT_BRIEF          =

+

+# With the PROJECT_LOGO tag one can specify a logo or an icon that is included

+# in the documentation. The maximum height of the logo should not exceed 55

+# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy

+# the logo to the output directory.

+

+PROJECT_LOGO           =

+

+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path

+# into which the generated documentation will be written. If a relative path is

+# entered, it will be relative to the location where doxygen was started. If

+# left blank the current directory will be used.

+

+OUTPUT_DIRECTORY       = ../docs

+

+# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-

+# directories (in 2 levels) under the output directory of each output format and

+# will distribute the generated files over these directories. Enabling this

+# option can be useful when feeding doxygen a huge amount of source files, where

+# putting all generated files in the same directory would otherwise causes

+# performance problems for the file system.

+# The default value is: NO.

+

+CREATE_SUBDIRS         = NO

+

+# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII

+# characters to appear in the names of generated files. If set to NO, non-ASCII

+# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode

+# U+3044.

+# The default value is: NO.

+

+ALLOW_UNICODE_NAMES    = NO

+

+# The OUTPUT_LANGUAGE tag is used to specify the language in which all

+# documentation generated by doxygen is written. Doxygen will use this

+# information to generate all constant output in the proper language.

+# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,

+# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),

+# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,

+# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),

+# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,

+# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,

+# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,

+# Ukrainian and Vietnamese.

+# The default value is: English.

+

+OUTPUT_LANGUAGE        = English

+

+# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member

+# descriptions after the members that are listed in the file and class

+# documentation (similar to Javadoc). Set to NO to disable this.

+# The default value is: YES.

+

+BRIEF_MEMBER_DESC      = YES

+

+# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief

+# description of a member or function before the detailed description

+#

+# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the

+# brief descriptions will be completely suppressed.

+# The default value is: YES.

+

+REPEAT_BRIEF           = YES

+

+# This tag implements a quasi-intelligent brief description abbreviator that is

+# used to form the text in various listings. Each string in this list, if found

+# as the leading text of the brief description, will be stripped from the text

+# and the result, after processing the whole list, is used as the annotated

+# text. Otherwise, the brief description is used as-is. If left blank, the

+# following values are used ($name is automatically replaced with the name of

+# the entity):The $name class, The $name widget, The $name file, is, provides,

+# specifies, contains, represents, a, an and the.

+

+ABBREVIATE_BRIEF       = "The $name class" \

+                         "The $name widget" \

+                         "The $name file" \

+                         is \

+                         provides \

+                         specifies \

+                         contains \

+                         represents \

+                         a \

+                         an \

+                         the

+

+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then

+# doxygen will generate a detailed section even if there is only a brief

+# description.

+# The default value is: NO.

+

+ALWAYS_DETAILED_SEC    = NO

+

+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all

+# inherited members of a class in the documentation of that class as if those

+# members were ordinary class members. Constructors, destructors and assignment

+# operators of the base classes will not be shown.

+# The default value is: NO.

+

+INLINE_INHERITED_MEMB  = NO

+

+# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path

+# before files name in the file list and in the header files. If set to NO the

+# shortest path that makes the file name unique will be used

+# The default value is: YES.

+

+FULL_PATH_NAMES        = YES

+

+# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.

+# Stripping is only done if one of the specified strings matches the left-hand

+# part of the path. The tag can be used to show relative paths in the file list.

+# If left blank the directory from which doxygen is run is used as the path to

+# strip.

+#

+# Note that you can specify absolute paths here, but also relative paths, which

+# will be relative from the directory where doxygen is started.

+# This tag requires that the tag FULL_PATH_NAMES is set to YES.

+

+STRIP_FROM_PATH        =

+

+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the

+# path mentioned in the documentation of a class, which tells the reader which

+# header file to include in order to use a class. If left blank only the name of

+# the header file containing the class definition is used. Otherwise one should

+# specify the list of include paths that are normally passed to the compiler

+# using the -I flag.

+

+STRIP_FROM_INC_PATH    =

+

+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but

+# less readable) file names. This can be useful is your file systems doesn't

+# support long names like on DOS, Mac, or CD-ROM.

+# The default value is: NO.

+

+SHORT_NAMES            = NO

+

+# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the

+# first line (until the first dot) of a Javadoc-style comment as the brief

+# description. If set to NO, the Javadoc-style will behave just like regular Qt-

+# style comments (thus requiring an explicit @brief command for a brief

+# description.)

+# The default value is: NO.

+

+JAVADOC_AUTOBRIEF      = NO

+

+# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first

+# line (until the first dot) of a Qt-style comment as the brief description. If

+# set to NO, the Qt-style will behave just like regular Qt-style comments (thus

+# requiring an explicit \brief command for a brief description.)

+# The default value is: NO.

+

+QT_AUTOBRIEF           = NO

+

+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a

+# multi-line C++ special comment block (i.e. a block of //! or /// comments) as

+# a brief description. This used to be the default behavior. The new default is

+# to treat a multi-line C++ comment block as a detailed description. Set this

+# tag to YES if you prefer the old behavior instead.

+#

+# Note that setting this tag to YES also means that rational rose comments are

+# not recognized any more.

+# The default value is: NO.

+

+MULTILINE_CPP_IS_BRIEF = NO

+

+# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the

+# documentation from any documented member that it re-implements.

+# The default value is: YES.

+

+INHERIT_DOCS           = YES

+

+# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new

+# page for each member. If set to NO, the documentation of a member will be part

+# of the file/class/namespace that contains it.

+# The default value is: NO.

+

+SEPARATE_MEMBER_PAGES  = NO

+

+# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen

+# uses this value to replace tabs by spaces in code fragments.

+# Minimum value: 1, maximum value: 16, default value: 4.

+

+TAB_SIZE               = 4

+

+# This tag can be used to specify a number of aliases that act as commands in

+# the documentation. An alias has the form:

+# name=value

+# For example adding

+# "sideeffect=@par Side Effects:\n"

+# will allow you to put the command \sideeffect (or @sideeffect) in the

+# documentation, which will result in a user-defined paragraph with heading

+# "Side Effects:". You can put \n's in the value part of an alias to insert

+# newlines.

+

+ALIASES                =

+

+# This tag can be used to specify a number of word-keyword mappings (TCL only).

+# A mapping has the form "name=value". For example adding "class=itcl::class"

+# will allow you to use the command class in the itcl::class meaning.

+

+TCL_SUBST              =

+

+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources

+# only. Doxygen will then generate output that is more tailored for C. For

+# instance, some of the names that are used will be different. The list of all

+# members will be omitted, etc.

+# The default value is: NO.

+

+OPTIMIZE_OUTPUT_FOR_C  = NO

+

+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or

+# Python sources only. Doxygen will then generate output that is more tailored

+# for that language. For instance, namespaces will be presented as packages,

+# qualified scopes will look different, etc.

+# The default value is: NO.

+

+OPTIMIZE_OUTPUT_JAVA   = NO

+

+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran

+# sources. Doxygen will then generate output that is tailored for Fortran.

+# The default value is: NO.

+

+OPTIMIZE_FOR_FORTRAN   = NO

+

+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL

+# sources. Doxygen will then generate output that is tailored for VHDL.

+# The default value is: NO.

+

+OPTIMIZE_OUTPUT_VHDL   = NO

+

+# Doxygen selects the parser to use depending on the extension of the files it

+# parses. With this tag you can assign which parser to use for a given

+# extension. Doxygen has a built-in mapping, but you can override or extend it

+# using this tag. The format is ext=language, where ext is a file extension, and

+# language is one of the parsers supported by doxygen: IDL, Java, Javascript,

+# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran:

+# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran:

+# Fortran. In the later case the parser tries to guess whether the code is fixed

+# or free formatted code, this is the default for Fortran type files), VHDL. For

+# instance to make doxygen treat .inc files as Fortran files (default is PHP),

+# and .f files as C (default is Fortran), use: inc=Fortran f=C.

+#

+# Note: For files without extension you can use no_extension as a placeholder.

+#

+# Note that for custom extensions you also need to set FILE_PATTERNS otherwise

+# the files are not read by doxygen.

+

+EXTENSION_MAPPING      =

+

+# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments

+# according to the Markdown format, which allows for more readable

+# documentation. See http://daringfireball.net/projects/markdown/ for details.

+# The output of markdown processing is further processed by doxygen, so you can

+# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in

+# case of backward compatibilities issues.

+# The default value is: YES.

+

+MARKDOWN_SUPPORT       = YES

+

+# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up

+# to that level are automatically included in the table of contents, even if

+# they do not have an id attribute.

+# Note: This feature currently applies only to Markdown headings.

+# Minimum value: 0, maximum value: 99, default value: 0.

+# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.

+

+TOC_INCLUDE_HEADINGS   = 0

+

+# When enabled doxygen tries to link words that correspond to documented

+# classes, or namespaces to their corresponding documentation. Such a link can

+# be prevented in individual cases by putting a % sign in front of the word or

+# globally by setting AUTOLINK_SUPPORT to NO.

+# The default value is: YES.

+

+AUTOLINK_SUPPORT       = YES

+

+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want

+# to include (a tag file for) the STL sources as input, then you should set this

+# tag to YES in order to let doxygen match functions declarations and

+# definitions whose arguments contain STL classes (e.g. func(std::string);

+# versus func(std::string) {}). This also make the inheritance and collaboration

+# diagrams that involve STL classes more complete and accurate.

+# The default value is: NO.

+

+BUILTIN_STL_SUPPORT    = NO

+

+# If you use Microsoft's C++/CLI language, you should set this option to YES to

+# enable parsing support.

+# The default value is: NO.

+

+CPP_CLI_SUPPORT        = NO

+

+# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:

+# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen

+# will parse them like normal C++ but will assume all classes use public instead

+# of private inheritance when no explicit protection keyword is present.

+# The default value is: NO.

+

+SIP_SUPPORT            = NO

+

+# For Microsoft's IDL there are propget and propput attributes to indicate

+# getter and setter methods for a property. Setting this option to YES will make

+# doxygen to replace the get and set methods by a property in the documentation.

+# This will only work if the methods are indeed getting or setting a simple

+# type. If this is not the case, or you want to show the methods anyway, you

+# should set this option to NO.

+# The default value is: YES.

+

+IDL_PROPERTY_SUPPORT   = YES

+

+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC

+# tag is set to YES then doxygen will reuse the documentation of the first

+# member in the group (if any) for the other members of the group. By default

+# all members of a group must be documented explicitly.

+# The default value is: NO.

+

+DISTRIBUTE_GROUP_DOC   = NO

+

+# If one adds a struct or class to a group and this option is enabled, then also

+# any nested class or struct is added to the same group. By default this option

+# is disabled and one has to add nested compounds explicitly via \ingroup.

+# The default value is: NO.

+

+GROUP_NESTED_COMPOUNDS = NO

+

+# Set the SUBGROUPING tag to YES to allow class member groups of the same type

+# (for instance a group of public functions) to be put as a subgroup of that

+# type (e.g. under the Public Functions section). Set it to NO to prevent

+# subgrouping. Alternatively, this can be done per class using the

+# \nosubgrouping command.

+# The default value is: YES.

+

+SUBGROUPING            = YES

+

+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions

+# are shown inside the group in which they are included (e.g. using \ingroup)

+# instead of on a separate page (for HTML and Man pages) or section (for LaTeX

+# and RTF).

+#

+# Note that this feature does not work in combination with

+# SEPARATE_MEMBER_PAGES.

+# The default value is: NO.

+

+INLINE_GROUPED_CLASSES = NO

+

+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions

+# with only public data fields or simple typedef fields will be shown inline in

+# the documentation of the scope in which they are defined (i.e. file,

+# namespace, or group documentation), provided this scope is documented. If set

+# to NO, structs, classes, and unions are shown on a separate page (for HTML and

+# Man pages) or section (for LaTeX and RTF).

+# The default value is: NO.

+

+INLINE_SIMPLE_STRUCTS  = NO

+

+# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or

+# enum is documented as struct, union, or enum with the name of the typedef. So

+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct

+# with name TypeT. When disabled the typedef will appear as a member of a file,

+# namespace, or class. And the struct will be named TypeS. This can typically be

+# useful for C code in case the coding convention dictates that all compound

+# types are typedef'ed and only the typedef is referenced, never the tag name.

+# The default value is: NO.

+

+TYPEDEF_HIDES_STRUCT   = NO

+

+# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This

+# cache is used to resolve symbols given their name and scope. Since this can be

+# an expensive process and often the same symbol appears multiple times in the

+# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small

+# doxygen will become slower. If the cache is too large, memory is wasted. The

+# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range

+# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536

+# symbols. At the end of a run doxygen will report the cache usage and suggest

+# the optimal cache size from a speed point of view.

+# Minimum value: 0, maximum value: 9, default value: 0.

+

+LOOKUP_CACHE_SIZE      = 0

+

+#---------------------------------------------------------------------------

+# Build related configuration options

+#---------------------------------------------------------------------------

+

+# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in

+# documentation are documented, even if no documentation was available. Private

+# class members and static file members will be hidden unless the

+# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.

+# Note: This will also disable the warnings about undocumented members that are

+# normally produced when WARNINGS is set to YES.

+# The default value is: NO.

+

+EXTRACT_ALL            = YES

+

+# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will

+# be included in the documentation.

+# The default value is: NO.

+

+EXTRACT_PRIVATE        = NO

+

+# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal

+# scope will be included in the documentation.

+# The default value is: NO.

+

+EXTRACT_PACKAGE        = NO

+

+# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be

+# included in the documentation.

+# The default value is: NO.

+

+EXTRACT_STATIC         = NO

+

+# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined

+# locally in source files will be included in the documentation. If set to NO,

+# only classes defined in header files are included. Does not have any effect

+# for Java sources.

+# The default value is: YES.

+

+EXTRACT_LOCAL_CLASSES  = YES

+

+# This flag is only useful for Objective-C code. If set to YES, local methods,

+# which are defined in the implementation section but not in the interface are

+# included in the documentation. If set to NO, only methods in the interface are

+# included.

+# The default value is: NO.

+

+EXTRACT_LOCAL_METHODS  = NO

+

+# If this flag is set to YES, the members of anonymous namespaces will be

+# extracted and appear in the documentation as a namespace called

+# 'anonymous_namespace{file}', where file will be replaced with the base name of

+# the file that contains the anonymous namespace. By default anonymous namespace

+# are hidden.

+# The default value is: NO.

+

+EXTRACT_ANON_NSPACES   = NO

+

+# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all

+# undocumented members inside documented classes or files. If set to NO these

+# members will be included in the various overviews, but no documentation

+# section is generated. This option has no effect if EXTRACT_ALL is enabled.

+# The default value is: NO.

+

+HIDE_UNDOC_MEMBERS     = NO

+

+# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all

+# undocumented classes that are normally visible in the class hierarchy. If set

+# to NO, these classes will be included in the various overviews. This option

+# has no effect if EXTRACT_ALL is enabled.

+# The default value is: NO.

+

+HIDE_UNDOC_CLASSES     = NO

+

+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend

+# (class|struct|union) declarations. If set to NO, these declarations will be

+# included in the documentation.

+# The default value is: NO.

+

+HIDE_FRIEND_COMPOUNDS  = YES

+

+# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any

+# documentation blocks found inside the body of a function. If set to NO, these

+# blocks will be appended to the function's detailed documentation block.

+# The default value is: NO.

+

+HIDE_IN_BODY_DOCS      = NO

+

+# The INTERNAL_DOCS tag determines if documentation that is typed after a

+# \internal command is included. If the tag is set to NO then the documentation

+# will be excluded. Set it to YES to include the internal documentation.

+# The default value is: NO.

+

+INTERNAL_DOCS          = NO

+

+# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file

+# names in lower-case letters. If set to YES, upper-case letters are also

+# allowed. This is useful if you have classes or files whose names only differ

+# in case and if your file system supports case sensitive file names. Windows

+# and Mac users are advised to set this option to NO.

+# The default value is: system dependent.

+

+CASE_SENSE_NAMES       = NO

+

+# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with

+# their full class and namespace scopes in the documentation. If set to YES, the

+# scope will be hidden.

+# The default value is: NO.

+

+HIDE_SCOPE_NAMES       = NO

+

+# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will

+# append additional text to a page's title, such as Class Reference. If set to

+# YES the compound reference will be hidden.

+# The default value is: NO.

+

+HIDE_COMPOUND_REFERENCE= NO

+

+# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of

+# the files that are included by a file in the documentation of that file.

+# The default value is: YES.

+

+SHOW_INCLUDE_FILES     = YES

+

+# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each

+# grouped member an include statement to the documentation, telling the reader

+# which file to include in order to use the member.

+# The default value is: NO.

+

+SHOW_GROUPED_MEMB_INC  = NO

+

+# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include

+# files with double quotes in the documentation rather than with sharp brackets.

+# The default value is: NO.

+

+FORCE_LOCAL_INCLUDES   = NO

+

+# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the

+# documentation for inline members.

+# The default value is: YES.

+

+INLINE_INFO            = YES

+

+# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the

+# (detailed) documentation of file and class members alphabetically by member

+# name. If set to NO, the members will appear in declaration order.

+# The default value is: YES.

+

+SORT_MEMBER_DOCS       = YES

+

+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief

+# descriptions of file, namespace and class members alphabetically by member

+# name. If set to NO, the members will appear in declaration order. Note that

+# this will also influence the order of the classes in the class list.

+# The default value is: NO.

+

+SORT_BRIEF_DOCS        = NO

+

+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the

+# (brief and detailed) documentation of class members so that constructors and

+# destructors are listed first. If set to NO the constructors will appear in the

+# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.

+# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief

+# member documentation.

+# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting

+# detailed member documentation.

+# The default value is: NO.

+

+SORT_MEMBERS_CTORS_1ST = NO

+

+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy

+# of group names into alphabetical order. If set to NO the group names will

+# appear in their defined order.

+# The default value is: NO.

+

+SORT_GROUP_NAMES       = NO

+

+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by

+# fully-qualified names, including namespaces. If set to NO, the class list will

+# be sorted only by class name, not including the namespace part.

+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.

+# Note: This option applies only to the class list, not to the alphabetical

+# list.

+# The default value is: NO.

+

+SORT_BY_SCOPE_NAME     = NO

+

+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper

+# type resolution of all parameters of a function it will reject a match between

+# the prototype and the implementation of a member function even if there is

+# only one candidate or it is obvious which candidate to choose by doing a

+# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still

+# accept a match between prototype and implementation in such cases.

+# The default value is: NO.

+

+STRICT_PROTO_MATCHING  = NO

+

+# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo

+# list. This list is created by putting \todo commands in the documentation.

+# The default value is: YES.

+

+GENERATE_TODOLIST      = YES

+

+# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test

+# list. This list is created by putting \test commands in the documentation.

+# The default value is: YES.

+

+GENERATE_TESTLIST      = YES

+

+# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug

+# list. This list is created by putting \bug commands in the documentation.

+# The default value is: YES.

+

+GENERATE_BUGLIST       = YES

+

+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)

+# the deprecated list. This list is created by putting \deprecated commands in

+# the documentation.

+# The default value is: YES.

+

+GENERATE_DEPRECATEDLIST= YES

+

+# The ENABLED_SECTIONS tag can be used to enable conditional documentation

+# sections, marked by \if <section_label> ... \endif and \cond <section_label>

+# ... \endcond blocks.

+

+ENABLED_SECTIONS       =

+

+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the

+# initial value of a variable or macro / define can have for it to appear in the

+# documentation. If the initializer consists of more lines than specified here

+# it will be hidden. Use a value of 0 to hide initializers completely. The

+# appearance of the value of individual variables and macros / defines can be

+# controlled using \showinitializer or \hideinitializer command in the

+# documentation regardless of this setting.

+# Minimum value: 0, maximum value: 10000, default value: 30.

+

+MAX_INITIALIZER_LINES  = 30

+

+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at

+# the bottom of the documentation of classes and structs. If set to YES, the

+# list will mention the files that were used to generate the documentation.

+# The default value is: YES.

+

+SHOW_USED_FILES        = YES

+

+# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This

+# will remove the Files entry from the Quick Index and from the Folder Tree View

+# (if specified).

+# The default value is: YES.

+

+SHOW_FILES             = YES

+

+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces

+# page. This will remove the Namespaces entry from the Quick Index and from the

+# Folder Tree View (if specified).

+# The default value is: YES.

+

+SHOW_NAMESPACES        = YES

+

+# The FILE_VERSION_FILTER tag can be used to specify a program or script that

+# doxygen should invoke to get the current version for each file (typically from

+# the version control system). Doxygen will invoke the program by executing (via

+# popen()) the command command input-file, where command is the value of the

+# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided

+# by doxygen. Whatever the program writes to standard output is used as the file

+# version. For an example see the documentation.

+

+FILE_VERSION_FILTER    =

+

+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed

+# by doxygen. The layout file controls the global structure of the generated

+# output files in an output format independent way. To create the layout file

+# that represents doxygen's defaults, run doxygen with the -l option. You can

+# optionally specify a file name after the option, if omitted DoxygenLayout.xml

+# will be used as the name of the layout file.

+#

+# Note that if you run doxygen from a directory containing a file called

+# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE

+# tag is left empty.

+

+LAYOUT_FILE            =

+

+# The CITE_BIB_FILES tag can be used to specify one or more bib files containing

+# the reference definitions. This must be a list of .bib files. The .bib

+# extension is automatically appended if omitted. This requires the bibtex tool

+# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.

+# For LaTeX the style of the bibliography can be controlled using

+# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the

+# search path. See also \cite for info how to create references.

+

+CITE_BIB_FILES         =

+

+#---------------------------------------------------------------------------

+# Configuration options related to warning and progress messages

+#---------------------------------------------------------------------------

+

+# The QUIET tag can be used to turn on/off the messages that are generated to

+# standard output by doxygen. If QUIET is set to YES this implies that the

+# messages are off.

+# The default value is: NO.

+

+QUIET                  = NO

+

+# The WARNINGS tag can be used to turn on/off the warning messages that are

+# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES

+# this implies that the warnings are on.

+#

+# Tip: Turn warnings on while writing the documentation.

+# The default value is: YES.

+

+WARNINGS               = YES

+

+# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate

+# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag

+# will automatically be disabled.

+# The default value is: YES.

+

+WARN_IF_UNDOCUMENTED   = YES

+

+# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for

+# potential errors in the documentation, such as not documenting some parameters

+# in a documented function, or documenting parameters that don't exist or using

+# markup commands wrongly.

+# The default value is: YES.

+

+WARN_IF_DOC_ERROR      = YES

+

+# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that

+# are documented, but have no documentation for their parameters or return

+# value. If set to NO, doxygen will only warn about wrong or incomplete

+# parameter documentation, but not about the absence of documentation.

+# The default value is: NO.

+

+WARN_NO_PARAMDOC       = NO

+

+# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when

+# a warning is encountered.

+# The default value is: NO.

+

+WARN_AS_ERROR          = NO

+

+# The WARN_FORMAT tag determines the format of the warning messages that doxygen

+# can produce. The string should contain the $file, $line, and $text tags, which

+# will be replaced by the file and line number from which the warning originated

+# and the warning text. Optionally the format may contain $version, which will

+# be replaced by the version of the file (if it could be obtained via

+# FILE_VERSION_FILTER)

+# The default value is: $file:$line: $text.

+

+WARN_FORMAT            = "$file:$line: $text"

+

+# The WARN_LOGFILE tag can be used to specify a file to which warning and error

+# messages should be written. If left blank the output is written to standard

+# error (stderr).

+

+WARN_LOGFILE           =

+

+#---------------------------------------------------------------------------

+# Configuration options related to the input files

+#---------------------------------------------------------------------------

+

+# The INPUT tag is used to specify the files and/or directories that contain

+# documented source files. You may enter file names like myfile.cpp or

+# directories like /usr/src/myproject. Separate the files or directories with

+# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING

+# Note: If this tag is empty the current directory is searched.

+

+INPUT                  = D3D12MemAlloc.h

+

+# This tag can be used to specify the character encoding of the source files

+# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses

+# libiconv (or the iconv built into libc) for the transcoding. See the libiconv

+# documentation (see: http://www.gnu.org/software/libiconv) for the list of

+# possible encodings.

+# The default value is: UTF-8.

+

+INPUT_ENCODING         = UTF-8

+

+# If the value of the INPUT tag contains directories, you can use the

+# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and

+# *.h) to filter out the source-files in the directories.

+#

+# Note that for custom extensions or not directly supported extensions you also

+# need to set EXTENSION_MAPPING for the extension otherwise the files are not

+# read by doxygen.

+#

+# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,

+# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,

+# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc,

+# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08,

+# *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf and *.qsf.

+

+FILE_PATTERNS          = *.c \

+                         *.cc \

+                         *.cxx \

+                         *.cpp \

+                         *.c++ \

+                         *.java \

+                         *.ii \

+                         *.ixx \

+                         *.ipp \

+                         *.i++ \

+                         *.inl \

+                         *.idl \

+                         *.ddl \

+                         *.odl \

+                         *.h \

+                         *.hh \

+                         *.hxx \

+                         *.hpp \

+                         *.h++ \

+                         *.cs \

+                         *.d \

+                         *.php \

+                         *.php4 \

+                         *.php5 \

+                         *.phtml \

+                         *.inc \

+                         *.m \

+                         *.markdown \

+                         *.md \

+                         *.mm \

+                         *.dox \

+                         *.py \

+                         *.pyw \

+                         *.f90 \

+                         *.f95 \

+                         *.f03 \

+                         *.f08 \

+                         *.f \

+                         *.for \

+                         *.tcl \

+                         *.vhd \

+                         *.vhdl \

+                         *.ucf \

+                         *.qsf

+

+# The RECURSIVE tag can be used to specify whether or not subdirectories should

+# be searched for input files as well.

+# The default value is: NO.

+

+RECURSIVE              = NO

+

+# The EXCLUDE tag can be used to specify files and/or directories that should be

+# excluded from the INPUT source files. This way you can easily exclude a

+# subdirectory from a directory tree whose root is specified with the INPUT tag.

+#

+# Note that relative paths are relative to the directory from which doxygen is

+# run.

+

+EXCLUDE                =

+

+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or

+# directories that are symbolic links (a Unix file system feature) are excluded

+# from the input.

+# The default value is: NO.

+

+EXCLUDE_SYMLINKS       = NO

+

+# If the value of the INPUT tag contains directories, you can use the

+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude

+# certain files from those directories.

+#

+# Note that the wildcards are matched against the file with absolute path, so to

+# exclude all test directories for example use the pattern */test/*

+

+EXCLUDE_PATTERNS       =

+

+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names

+# (namespaces, classes, functions, etc.) that should be excluded from the

+# output. The symbol name can be a fully qualified name, a word, or if the

+# wildcard * is used, a substring. Examples: ANamespace, AClass,

+# AClass::ANamespace, ANamespace::*Test

+#

+# Note that the wildcards are matched against the file with absolute path, so to

+# exclude all test directories use the pattern */test/*

+

+EXCLUDE_SYMBOLS        =

+

+# The EXAMPLE_PATH tag can be used to specify one or more files or directories

+# that contain example code fragments that are included (see the \include

+# command).

+

+EXAMPLE_PATH           =

+

+# If the value of the EXAMPLE_PATH tag contains directories, you can use the

+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and

+# *.h) to filter out the source-files in the directories. If left blank all

+# files are included.

+

+EXAMPLE_PATTERNS       = *

+

+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be

+# searched for input files to be used with the \include or \dontinclude commands

+# irrespective of the value of the RECURSIVE tag.

+# The default value is: NO.

+

+EXAMPLE_RECURSIVE      = NO

+

+# The IMAGE_PATH tag can be used to specify one or more files or directories

+# that contain images that are to be included in the documentation (see the

+# \image command).

+

+IMAGE_PATH             =

+

+# The INPUT_FILTER tag can be used to specify a program that doxygen should

+# invoke to filter for each input file. Doxygen will invoke the filter program

+# by executing (via popen()) the command:

+#

+# <filter> <input-file>

+#

+# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the

+# name of an input file. Doxygen will then use the output that the filter

+# program writes to standard output. If FILTER_PATTERNS is specified, this tag

+# will be ignored.

+#

+# Note that the filter must not add or remove lines; it is applied before the

+# code is scanned, but not when the output code is generated. If lines are added

+# or removed, the anchors will not be placed correctly.

+#

+# Note that for custom extensions or not directly supported extensions you also

+# need to set EXTENSION_MAPPING for the extension otherwise the files are not

+# properly processed by doxygen.

+

+INPUT_FILTER           =

+

+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern

+# basis. Doxygen will compare the file name with each pattern and apply the

+# filter if there is a match. The filters are a list of the form: pattern=filter

+# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how

+# filters are used. If the FILTER_PATTERNS tag is empty or if none of the

+# patterns match the file name, INPUT_FILTER is applied.

+#

+# Note that for custom extensions or not directly supported extensions you also

+# need to set EXTENSION_MAPPING for the extension otherwise the files are not

+# properly processed by doxygen.

+

+FILTER_PATTERNS        =

+

+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using

+# INPUT_FILTER) will also be used to filter the input files that are used for

+# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).

+# The default value is: NO.

+

+FILTER_SOURCE_FILES    = NO

+

+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file

+# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and

+# it is also possible to disable source filtering for a specific pattern using

+# *.ext= (so without naming a filter).

+# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.

+

+FILTER_SOURCE_PATTERNS =

+

+# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that

+# is part of the input, its contents will be placed on the main page

+# (index.html). This can be useful if you have a project on for instance GitHub

+# and want to reuse the introduction page also for the doxygen output.

+

+USE_MDFILE_AS_MAINPAGE =

+

+#---------------------------------------------------------------------------

+# Configuration options related to source browsing

+#---------------------------------------------------------------------------

+

+# If the SOURCE_BROWSER tag is set to YES then a list of source files will be

+# generated. Documented entities will be cross-referenced with these sources.

+#

+# Note: To get rid of all source code in the generated output, make sure that

+# also VERBATIM_HEADERS is set to NO.

+# The default value is: NO.

+

+SOURCE_BROWSER         = NO

+

+# Setting the INLINE_SOURCES tag to YES will include the body of functions,

+# classes and enums directly into the documentation.

+# The default value is: NO.

+

+INLINE_SOURCES         = NO

+

+# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any

+# special comment blocks from generated source code fragments. Normal C, C++ and

+# Fortran comments will always remain visible.

+# The default value is: YES.

+

+STRIP_CODE_COMMENTS    = YES

+

+# If the REFERENCED_BY_RELATION tag is set to YES then for each documented

+# function all documented functions referencing it will be listed.

+# The default value is: NO.

+

+REFERENCED_BY_RELATION = NO

+

+# If the REFERENCES_RELATION tag is set to YES then for each documented function

+# all documented entities called/used by that function will be listed.

+# The default value is: NO.

+

+REFERENCES_RELATION    = NO

+

+# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set

+# to YES then the hyperlinks from functions in REFERENCES_RELATION and

+# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will

+# link to the documentation.

+# The default value is: YES.

+

+REFERENCES_LINK_SOURCE = YES

+

+# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the

+# source code will show a tooltip with additional information such as prototype,

+# brief description and links to the definition and documentation. Since this

+# will make the HTML file larger and loading of large files a bit slower, you

+# can opt to disable this feature.

+# The default value is: YES.

+# This tag requires that the tag SOURCE_BROWSER is set to YES.

+

+SOURCE_TOOLTIPS        = YES

+

+# If the USE_HTAGS tag is set to YES then the references to source code will

+# point to the HTML generated by the htags(1) tool instead of doxygen built-in

+# source browser. The htags tool is part of GNU's global source tagging system

+# (see http://www.gnu.org/software/global/global.html). You will need version

+# 4.8.6 or higher.

+#

+# To use it do the following:

+# - Install the latest version of global

+# - Enable SOURCE_BROWSER and USE_HTAGS in the config file

+# - Make sure the INPUT points to the root of the source tree

+# - Run doxygen as normal

+#

+# Doxygen will invoke htags (and that will in turn invoke gtags), so these

+# tools must be available from the command line (i.e. in the search path).

+#

+# The result: instead of the source browser generated by doxygen, the links to

+# source code will now point to the output of htags.

+# The default value is: NO.

+# This tag requires that the tag SOURCE_BROWSER is set to YES.

+

+USE_HTAGS              = NO

+

+# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a

+# verbatim copy of the header file for each class for which an include is

+# specified. Set to NO to disable this.

+# See also: Section \class.

+# The default value is: YES.

+

+VERBATIM_HEADERS       = YES

+

+# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the

+# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the

+# cost of reduced performance. This can be particularly helpful with template

+# rich C++ code for which doxygen's built-in parser lacks the necessary type

+# information.

+# Note: The availability of this option depends on whether or not doxygen was

+# generated with the -Duse-libclang=ON option for CMake.

+# The default value is: NO.

+

+CLANG_ASSISTED_PARSING = NO

+

+# If clang assisted parsing is enabled you can provide the compiler with command

+# line options that you would normally use when invoking the compiler. Note that

+# the include paths will already be set by doxygen for the files and directories

+# specified with INPUT and INCLUDE_PATH.

+# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.

+

+CLANG_OPTIONS          =

+

+#---------------------------------------------------------------------------

+# Configuration options related to the alphabetical class index

+#---------------------------------------------------------------------------

+

+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all

+# compounds will be generated. Enable this if the project contains a lot of

+# classes, structs, unions or interfaces.

+# The default value is: YES.

+

+ALPHABETICAL_INDEX     = YES

+

+# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in

+# which the alphabetical index list will be split.

+# Minimum value: 1, maximum value: 20, default value: 5.

+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.

+

+COLS_IN_ALPHA_INDEX    = 5

+

+# In case all classes in a project start with a common prefix, all classes will

+# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag

+# can be used to specify a prefix (or a list of prefixes) that should be ignored

+# while generating the index headers.

+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.

+

+IGNORE_PREFIX          =

+

+#---------------------------------------------------------------------------

+# Configuration options related to the HTML output

+#---------------------------------------------------------------------------

+

+# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output

+# The default value is: YES.

+

+GENERATE_HTML          = YES

+

+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a

+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of

+# it.

+# The default directory is: html.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+HTML_OUTPUT            = html

+

+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each

+# generated HTML page (for example: .htm, .php, .asp).

+# The default value is: .html.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+HTML_FILE_EXTENSION    = .html

+

+# The HTML_HEADER tag can be used to specify a user-defined HTML header file for

+# each generated HTML page. If the tag is left blank doxygen will generate a

+# standard header.

+#

+# To get valid HTML the header file that includes any scripts and style sheets

+# that doxygen needs, which is dependent on the configuration options used (e.g.

+# the setting GENERATE_TREEVIEW). It is highly recommended to start with a

+# default header using

+# doxygen -w html new_header.html new_footer.html new_stylesheet.css

+# YourConfigFile

+# and then modify the file new_header.html. See also section "Doxygen usage"

+# for information on how to generate the default header that doxygen normally

+# uses.

+# Note: The header is subject to change so you typically have to regenerate the

+# default header when upgrading to a newer version of doxygen. For a description

+# of the possible markers and block names see the documentation.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+HTML_HEADER            =

+

+# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each

+# generated HTML page. If the tag is left blank doxygen will generate a standard

+# footer. See HTML_HEADER for more information on how to generate a default

+# footer and what special commands can be used inside the footer. See also

+# section "Doxygen usage" for information on how to generate the default footer

+# that doxygen normally uses.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+HTML_FOOTER            =

+

+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style

+# sheet that is used by each HTML page. It can be used to fine-tune the look of

+# the HTML output. If left blank doxygen will generate a default style sheet.

+# See also section "Doxygen usage" for information on how to generate the style

+# sheet that doxygen normally uses.

+# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as

+# it is more robust and this tag (HTML_STYLESHEET) will in the future become

+# obsolete.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+HTML_STYLESHEET        =

+

+# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined

+# cascading style sheets that are included after the standard style sheets

+# created by doxygen. Using this option one can overrule certain style aspects.

+# This is preferred over using HTML_STYLESHEET since it does not replace the

+# standard style sheet and is therefore more robust against future updates.

+# Doxygen will copy the style sheet files to the output directory.

+# Note: The order of the extra style sheet files is of importance (e.g. the last

+# style sheet in the list overrules the setting of the previous ones in the

+# list). For an example see the documentation.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+HTML_EXTRA_STYLESHEET  =

+

+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or

+# other source files which should be copied to the HTML output directory. Note

+# that these files will be copied to the base HTML output directory. Use the

+# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these

+# files. In the HTML_STYLESHEET file, use the file name only. Also note that the

+# files will be copied as-is; there are no commands or markers available.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+HTML_EXTRA_FILES       =

+

+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen

+# will adjust the colors in the style sheet and background images according to

+# this color. Hue is specified as an angle on a colorwheel, see

+# http://en.wikipedia.org/wiki/Hue for more information. For instance the value

+# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300

+# purple, and 360 is red again.

+# Minimum value: 0, maximum value: 359, default value: 220.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+HTML_COLORSTYLE_HUE    = 220

+

+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors

+# in the HTML output. For a value of 0 the output will use grayscales only. A

+# value of 255 will produce the most vivid colors.

+# Minimum value: 0, maximum value: 255, default value: 100.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+HTML_COLORSTYLE_SAT    = 100

+

+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the

+# luminance component of the colors in the HTML output. Values below 100

+# gradually make the output lighter, whereas values above 100 make the output

+# darker. The value divided by 100 is the actual gamma applied, so 80 represents

+# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not

+# change the gamma.

+# Minimum value: 40, maximum value: 240, default value: 80.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+HTML_COLORSTYLE_GAMMA  = 80

+

+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML

+# page will contain the date and time when the page was generated. Setting this

+# to YES can help to show when doxygen was last run and thus if the

+# documentation is up to date.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+HTML_TIMESTAMP         = NO

+

+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML

+# documentation will contain sections that can be hidden and shown after the

+# page has loaded.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+HTML_DYNAMIC_SECTIONS  = NO

+

+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries

+# shown in the various tree structured indices initially; the user can expand

+# and collapse entries dynamically later on. Doxygen will expand the tree to

+# such a level that at most the specified number of entries are visible (unless

+# a fully collapsed tree already exceeds this amount). So setting the number of

+# entries 1 will produce a full collapsed tree by default. 0 is a special value

+# representing an infinite number of entries and will result in a full expanded

+# tree by default.

+# Minimum value: 0, maximum value: 9999, default value: 100.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+HTML_INDEX_NUM_ENTRIES = 100

+

+# If the GENERATE_DOCSET tag is set to YES, additional index files will be

+# generated that can be used as input for Apple's Xcode 3 integrated development

+# environment (see: http://developer.apple.com/tools/xcode/), introduced with

+# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a

+# Makefile in the HTML output directory. Running make will produce the docset in

+# that directory and running make install will install the docset in

+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at

+# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html

+# for more information.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+GENERATE_DOCSET        = NO

+

+# This tag determines the name of the docset feed. A documentation feed provides

+# an umbrella under which multiple documentation sets from a single provider

+# (such as a company or product suite) can be grouped.

+# The default value is: Doxygen generated docs.

+# This tag requires that the tag GENERATE_DOCSET is set to YES.

+

+DOCSET_FEEDNAME        = "Doxygen generated docs"

+

+# This tag specifies a string that should uniquely identify the documentation

+# set bundle. This should be a reverse domain-name style string, e.g.

+# com.mycompany.MyDocSet. Doxygen will append .docset to the name.

+# The default value is: org.doxygen.Project.

+# This tag requires that the tag GENERATE_DOCSET is set to YES.

+

+DOCSET_BUNDLE_ID       = org.doxygen.Project

+

+# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify

+# the documentation publisher. This should be a reverse domain-name style

+# string, e.g. com.mycompany.MyDocSet.documentation.

+# The default value is: org.doxygen.Publisher.

+# This tag requires that the tag GENERATE_DOCSET is set to YES.

+

+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher

+

+# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.

+# The default value is: Publisher.

+# This tag requires that the tag GENERATE_DOCSET is set to YES.

+

+DOCSET_PUBLISHER_NAME  = Publisher

+

+# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three

+# additional HTML index files: index.hhp, index.hhc, and index.hhk. The

+# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop

+# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on

+# Windows.

+#

+# The HTML Help Workshop contains a compiler that can convert all HTML output

+# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML

+# files are now used as the Windows 98 help format, and will replace the old

+# Windows help format (.hlp) on all Windows platforms in the future. Compressed

+# HTML files also contain an index, a table of contents, and you can search for

+# words in the documentation. The HTML workshop also contains a viewer for

+# compressed HTML files.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+GENERATE_HTMLHELP      = NO

+

+# The CHM_FILE tag can be used to specify the file name of the resulting .chm

+# file. You can add a path in front of the file if the result should not be

+# written to the html output directory.

+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.

+

+CHM_FILE               =

+

+# The HHC_LOCATION tag can be used to specify the location (absolute path

+# including file name) of the HTML help compiler (hhc.exe). If non-empty,

+# doxygen will try to run the HTML help compiler on the generated index.hhp.

+# The file has to be specified with full path.

+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.

+

+HHC_LOCATION           =

+

+# The GENERATE_CHI flag controls if a separate .chi index file is generated

+# (YES) or that it should be included in the master .chm file (NO).

+# The default value is: NO.

+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.

+

+GENERATE_CHI           = NO

+

+# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)

+# and project file content.

+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.

+

+CHM_INDEX_ENCODING     =

+

+# The BINARY_TOC flag controls whether a binary table of contents is generated

+# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it

+# enables the Previous and Next buttons.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.

+

+BINARY_TOC             = NO

+

+# The TOC_EXPAND flag can be set to YES to add extra items for group members to

+# the table of contents of the HTML help documentation and to the tree view.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.

+

+TOC_EXPAND             = NO

+

+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and

+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that

+# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help

+# (.qch) of the generated HTML documentation.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+GENERATE_QHP           = NO

+

+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify

+# the file name of the resulting .qch file. The path specified is relative to

+# the HTML output folder.

+# This tag requires that the tag GENERATE_QHP is set to YES.

+

+QCH_FILE               =

+

+# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help

+# Project output. For more information please see Qt Help Project / Namespace

+# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).

+# The default value is: org.doxygen.Project.

+# This tag requires that the tag GENERATE_QHP is set to YES.

+

+QHP_NAMESPACE          = org.doxygen.Project

+

+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt

+# Help Project output. For more information please see Qt Help Project / Virtual

+# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-

+# folders).

+# The default value is: doc.

+# This tag requires that the tag GENERATE_QHP is set to YES.

+

+QHP_VIRTUAL_FOLDER     = doc

+

+# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom

+# filter to add. For more information please see Qt Help Project / Custom

+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-

+# filters).

+# This tag requires that the tag GENERATE_QHP is set to YES.

+

+QHP_CUST_FILTER_NAME   =

+

+# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the

+# custom filter to add. For more information please see Qt Help Project / Custom

+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-

+# filters).

+# This tag requires that the tag GENERATE_QHP is set to YES.

+

+QHP_CUST_FILTER_ATTRS  =

+

+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this

+# project's filter section matches. Qt Help Project / Filter Attributes (see:

+# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).

+# This tag requires that the tag GENERATE_QHP is set to YES.

+

+QHP_SECT_FILTER_ATTRS  =

+

+# The QHG_LOCATION tag can be used to specify the location of Qt's

+# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the

+# generated .qhp file.

+# This tag requires that the tag GENERATE_QHP is set to YES.

+

+QHG_LOCATION           =

+

+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be

+# generated, together with the HTML files, they form an Eclipse help plugin. To

+# install this plugin and make it available under the help contents menu in

+# Eclipse, the contents of the directory containing the HTML and XML files needs

+# to be copied into the plugins directory of eclipse. The name of the directory

+# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.

+# After copying Eclipse needs to be restarted before the help appears.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+GENERATE_ECLIPSEHELP   = NO

+

+# A unique identifier for the Eclipse help plugin. When installing the plugin

+# the directory name containing the HTML and XML files should also have this

+# name. Each documentation set should have its own identifier.

+# The default value is: org.doxygen.Project.

+# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.

+

+ECLIPSE_DOC_ID         = org.doxygen.Project

+

+# If you want full control over the layout of the generated HTML pages it might

+# be necessary to disable the index and replace it with your own. The

+# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top

+# of each HTML page. A value of NO enables the index and the value YES disables

+# it. Since the tabs in the index contain the same information as the navigation

+# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+DISABLE_INDEX          = NO

+

+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index

+# structure should be generated to display hierarchical information. If the tag

+# value is set to YES, a side panel will be generated containing a tree-like

+# index structure (just like the one that is generated for HTML Help). For this

+# to work a browser that supports JavaScript, DHTML, CSS and frames is required

+# (i.e. any modern browser). Windows users are probably better off using the

+# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can

+# further fine-tune the look of the index. As an example, the default style

+# sheet generated by doxygen has an example that shows how to put an image at

+# the root of the tree instead of the PROJECT_NAME. Since the tree basically has

+# the same information as the tab index, you could consider setting

+# DISABLE_INDEX to YES when enabling this option.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+GENERATE_TREEVIEW      = NO

+

+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that

+# doxygen will group on one line in the generated HTML documentation.

+#

+# Note that a value of 0 will completely suppress the enum values from appearing

+# in the overview section.

+# Minimum value: 0, maximum value: 20, default value: 4.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+ENUM_VALUES_PER_LINE   = 4

+

+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used

+# to set the initial width (in pixels) of the frame in which the tree is shown.

+# Minimum value: 0, maximum value: 1500, default value: 250.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+TREEVIEW_WIDTH         = 250

+

+# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to

+# external symbols imported via tag files in a separate window.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+EXT_LINKS_IN_WINDOW    = NO

+

+# Use this tag to change the font size of LaTeX formulas included as images in

+# the HTML documentation. When you change the font size after a successful

+# doxygen run you need to manually remove any form_*.png images from the HTML

+# output directory to force them to be regenerated.

+# Minimum value: 8, maximum value: 50, default value: 10.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+FORMULA_FONTSIZE       = 10

+

+# Use the FORMULA_TRANPARENT tag to determine whether or not the images

+# generated for formulas are transparent PNGs. Transparent PNGs are not

+# supported properly for IE 6.0, but are supported on all modern browsers.

+#

+# Note that when changing this option you need to delete any form_*.png files in

+# the HTML output directory before the changes have effect.

+# The default value is: YES.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+FORMULA_TRANSPARENT    = YES

+

+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see

+# http://www.mathjax.org) which uses client side Javascript for the rendering

+# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX

+# installed or if you want to formulas look prettier in the HTML output. When

+# enabled you may also need to install MathJax separately and configure the path

+# to it using the MATHJAX_RELPATH option.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+USE_MATHJAX            = NO

+

+# When MathJax is enabled you can set the default output format to be used for

+# the MathJax output. See the MathJax site (see:

+# http://docs.mathjax.org/en/latest/output.html) for more details.

+# Possible values are: HTML-CSS (which is slower, but has the best

+# compatibility), NativeMML (i.e. MathML) and SVG.

+# The default value is: HTML-CSS.

+# This tag requires that the tag USE_MATHJAX is set to YES.

+

+MATHJAX_FORMAT         = HTML-CSS

+

+# When MathJax is enabled you need to specify the location relative to the HTML

+# output directory using the MATHJAX_RELPATH option. The destination directory

+# should contain the MathJax.js script. For instance, if the mathjax directory

+# is located at the same level as the HTML output directory, then

+# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax

+# Content Delivery Network so you can quickly see the result without installing

+# MathJax. However, it is strongly recommended to install a local copy of

+# MathJax from http://www.mathjax.org before deployment.

+# The default value is: http://cdn.mathjax.org/mathjax/latest.

+# This tag requires that the tag USE_MATHJAX is set to YES.

+

+MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest

+

+# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax

+# extension names that should be enabled during MathJax rendering. For example

+# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols

+# This tag requires that the tag USE_MATHJAX is set to YES.

+

+MATHJAX_EXTENSIONS     =

+

+# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces

+# of code that will be used on startup of the MathJax code. See the MathJax site

+# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an

+# example see the documentation.

+# This tag requires that the tag USE_MATHJAX is set to YES.

+

+MATHJAX_CODEFILE       =

+

+# When the SEARCHENGINE tag is enabled doxygen will generate a search box for

+# the HTML output. The underlying search engine uses javascript and DHTML and

+# should work on any modern browser. Note that when using HTML help

+# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)

+# there is already a search function so this one should typically be disabled.

+# For large projects the javascript based search engine can be slow, then

+# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to

+# search using the keyboard; to jump to the search box use <access key> + S

+# (what the <access key> is depends on the OS and browser, but it is typically

+# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down

+# key> to jump into the search results window, the results can be navigated

+# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel

+# the search. The filter options can be selected when the cursor is inside the

+# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>

+# to select a filter and <Enter> or <escape> to activate or cancel the filter

+# option.

+# The default value is: YES.

+# This tag requires that the tag GENERATE_HTML is set to YES.

+

+SEARCHENGINE           = YES

+

+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be

+# implemented using a web server instead of a web client using Javascript. There

+# are two flavors of web server based searching depending on the EXTERNAL_SEARCH

+# setting. When disabled, doxygen will generate a PHP script for searching and

+# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing

+# and searching needs to be provided by external tools. See the section

+# "External Indexing and Searching" for details.

+# The default value is: NO.

+# This tag requires that the tag SEARCHENGINE is set to YES.

+

+SERVER_BASED_SEARCH    = NO

+

+# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP

+# script for searching. Instead the search results are written to an XML file

+# which needs to be processed by an external indexer. Doxygen will invoke an

+# external search engine pointed to by the SEARCHENGINE_URL option to obtain the

+# search results.

+#

+# Doxygen ships with an example indexer (doxyindexer) and search engine

+# (doxysearch.cgi) which are based on the open source search engine library

+# Xapian (see: http://xapian.org/).

+#

+# See the section "External Indexing and Searching" for details.

+# The default value is: NO.

+# This tag requires that the tag SEARCHENGINE is set to YES.

+

+EXTERNAL_SEARCH        = NO

+

+# The SEARCHENGINE_URL should point to a search engine hosted by a web server

+# which will return the search results when EXTERNAL_SEARCH is enabled.

+#

+# Doxygen ships with an example indexer (doxyindexer) and search engine

+# (doxysearch.cgi) which are based on the open source search engine library

+# Xapian (see: http://xapian.org/). See the section "External Indexing and

+# Searching" for details.

+# This tag requires that the tag SEARCHENGINE is set to YES.

+

+SEARCHENGINE_URL       =

+

+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed

+# search data is written to a file for indexing by an external tool. With the

+# SEARCHDATA_FILE tag the name of this file can be specified.

+# The default file is: searchdata.xml.

+# This tag requires that the tag SEARCHENGINE is set to YES.

+

+SEARCHDATA_FILE        = searchdata.xml

+

+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the

+# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is

+# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple

+# projects and redirect the results back to the right project.

+# This tag requires that the tag SEARCHENGINE is set to YES.

+

+EXTERNAL_SEARCH_ID     =

+

+# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen

+# projects other than the one defined by this configuration file, but that are

+# all added to the same external search index. Each project needs to have a

+# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of

+# to a relative location where the documentation can be found. The format is:

+# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...

+# This tag requires that the tag SEARCHENGINE is set to YES.

+

+EXTRA_SEARCH_MAPPINGS  =

+

+#---------------------------------------------------------------------------

+# Configuration options related to the LaTeX output

+#---------------------------------------------------------------------------

+

+# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.

+# The default value is: YES.

+

+GENERATE_LATEX         = NO

+

+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a

+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of

+# it.

+# The default directory is: latex.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+LATEX_OUTPUT           = latex

+

+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be

+# invoked.

+#

+# Note that when enabling USE_PDFLATEX this option is only used for generating

+# bitmaps for formulas in the HTML output, but not in the Makefile that is

+# written to the output directory.

+# The default file is: latex.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+LATEX_CMD_NAME         = latex

+

+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate

+# index for LaTeX.

+# The default file is: makeindex.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+MAKEINDEX_CMD_NAME     = makeindex

+

+# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX

+# documents. This may be useful for small projects and may help to save some

+# trees in general.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+COMPACT_LATEX          = NO

+

+# The PAPER_TYPE tag can be used to set the paper type that is used by the

+# printer.

+# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x

+# 14 inches) and executive (7.25 x 10.5 inches).

+# The default value is: a4.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+PAPER_TYPE             = a4

+

+# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names

+# that should be included in the LaTeX output. The package can be specified just

+# by its name or with the correct syntax as to be used with the LaTeX

+# \usepackage command. To get the times font for instance you can specify :

+# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}

+# To use the option intlimits with the amsmath package you can specify:

+# EXTRA_PACKAGES=[intlimits]{amsmath}

+# If left blank no extra packages will be included.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+EXTRA_PACKAGES         =

+

+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the

+# generated LaTeX document. The header should contain everything until the first

+# chapter. If it is left blank doxygen will generate a standard header. See

+# section "Doxygen usage" for information on how to let doxygen write the

+# default header to a separate file.

+#

+# Note: Only use a user-defined header if you know what you are doing! The

+# following commands have a special meaning inside the header: $title,

+# $datetime, $date, $doxygenversion, $projectname, $projectnumber,

+# $projectbrief, $projectlogo. Doxygen will replace $title with the empty

+# string, for the replacement values of the other commands the user is referred

+# to HTML_HEADER.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+LATEX_HEADER           =

+

+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the

+# generated LaTeX document. The footer should contain everything after the last

+# chapter. If it is left blank doxygen will generate a standard footer. See

+# LATEX_HEADER for more information on how to generate a default footer and what

+# special commands can be used inside the footer.

+#

+# Note: Only use a user-defined footer if you know what you are doing!

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+LATEX_FOOTER           =

+

+# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined

+# LaTeX style sheets that are included after the standard style sheets created

+# by doxygen. Using this option one can overrule certain style aspects. Doxygen

+# will copy the style sheet files to the output directory.

+# Note: The order of the extra style sheet files is of importance (e.g. the last

+# style sheet in the list overrules the setting of the previous ones in the

+# list).

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+LATEX_EXTRA_STYLESHEET =

+

+# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or

+# other source files which should be copied to the LATEX_OUTPUT output

+# directory. Note that the files will be copied as-is; there are no commands or

+# markers available.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+LATEX_EXTRA_FILES      =

+

+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is

+# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will

+# contain links (just like the HTML output) instead of page references. This

+# makes the output suitable for online browsing using a PDF viewer.

+# The default value is: YES.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+PDF_HYPERLINKS         = YES

+

+# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate

+# the PDF file directly from the LaTeX files. Set this option to YES, to get a

+# higher quality PDF documentation.

+# The default value is: YES.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+USE_PDFLATEX           = YES

+

+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode

+# command to the generated LaTeX files. This will instruct LaTeX to keep running

+# if errors occur, instead of asking the user for help. This option is also used

+# when generating formulas in HTML.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+LATEX_BATCHMODE        = NO

+

+# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the

+# index chapters (such as File Index, Compound Index, etc.) in the output.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+LATEX_HIDE_INDICES     = NO

+

+# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source

+# code with syntax highlighting in the LaTeX output.

+#

+# Note that which sources are shown also depends on other settings such as

+# SOURCE_BROWSER.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+LATEX_SOURCE_CODE      = NO

+

+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the

+# bibliography, e.g. plainnat, or ieeetr. See

+# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.

+# The default value is: plain.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+LATEX_BIB_STYLE        = plain

+

+# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated

+# page will contain the date and time when the page was generated. Setting this

+# to NO can help when comparing the output of multiple runs.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_LATEX is set to YES.

+

+LATEX_TIMESTAMP        = NO

+

+#---------------------------------------------------------------------------

+# Configuration options related to the RTF output

+#---------------------------------------------------------------------------

+

+# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The

+# RTF output is optimized for Word 97 and may not look too pretty with other RTF

+# readers/editors.

+# The default value is: NO.

+

+GENERATE_RTF           = NO

+

+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a

+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of

+# it.

+# The default directory is: rtf.

+# This tag requires that the tag GENERATE_RTF is set to YES.

+

+RTF_OUTPUT             = rtf

+

+# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF

+# documents. This may be useful for small projects and may help to save some

+# trees in general.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_RTF is set to YES.

+

+COMPACT_RTF            = NO

+

+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will

+# contain hyperlink fields. The RTF file will contain links (just like the HTML

+# output) instead of page references. This makes the output suitable for online

+# browsing using Word or some other Word compatible readers that support those

+# fields.

+#

+# Note: WordPad (write) and others do not support links.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_RTF is set to YES.

+

+RTF_HYPERLINKS         = NO

+

+# Load stylesheet definitions from file. Syntax is similar to doxygen's config

+# file, i.e. a series of assignments. You only have to provide replacements,

+# missing definitions are set to their default value.

+#

+# See also section "Doxygen usage" for information on how to generate the

+# default style sheet that doxygen normally uses.

+# This tag requires that the tag GENERATE_RTF is set to YES.

+

+RTF_STYLESHEET_FILE    =

+

+# Set optional variables used in the generation of an RTF document. Syntax is

+# similar to doxygen's config file. A template extensions file can be generated

+# using doxygen -e rtf extensionFile.

+# This tag requires that the tag GENERATE_RTF is set to YES.

+

+RTF_EXTENSIONS_FILE    =

+

+# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code

+# with syntax highlighting in the RTF output.

+#

+# Note that which sources are shown also depends on other settings such as

+# SOURCE_BROWSER.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_RTF is set to YES.

+

+RTF_SOURCE_CODE        = NO

+

+#---------------------------------------------------------------------------

+# Configuration options related to the man page output

+#---------------------------------------------------------------------------

+

+# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for

+# classes and files.

+# The default value is: NO.

+

+GENERATE_MAN           = NO

+

+# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a

+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of

+# it. A directory man3 will be created inside the directory specified by

+# MAN_OUTPUT.

+# The default directory is: man.

+# This tag requires that the tag GENERATE_MAN is set to YES.

+

+MAN_OUTPUT             = man

+

+# The MAN_EXTENSION tag determines the extension that is added to the generated

+# man pages. In case the manual section does not start with a number, the number

+# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is

+# optional.

+# The default value is: .3.

+# This tag requires that the tag GENERATE_MAN is set to YES.

+

+MAN_EXTENSION          = .3

+

+# The MAN_SUBDIR tag determines the name of the directory created within

+# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by

+# MAN_EXTENSION with the initial . removed.

+# This tag requires that the tag GENERATE_MAN is set to YES.

+

+MAN_SUBDIR             =

+

+# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it

+# will generate one additional man file for each entity documented in the real

+# man page(s). These additional files only source the real man page, but without

+# them the man command would be unable to find the correct page.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_MAN is set to YES.

+

+MAN_LINKS              = NO

+

+#---------------------------------------------------------------------------

+# Configuration options related to the XML output

+#---------------------------------------------------------------------------

+

+# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that

+# captures the structure of the code including all documentation.

+# The default value is: NO.

+

+GENERATE_XML           = NO

+

+# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a

+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of

+# it.

+# The default directory is: xml.

+# This tag requires that the tag GENERATE_XML is set to YES.

+

+XML_OUTPUT             = xml

+

+# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program

+# listings (including syntax highlighting and cross-referencing information) to

+# the XML output. Note that enabling this will significantly increase the size

+# of the XML output.

+# The default value is: YES.

+# This tag requires that the tag GENERATE_XML is set to YES.

+

+XML_PROGRAMLISTING     = YES

+

+#---------------------------------------------------------------------------

+# Configuration options related to the DOCBOOK output

+#---------------------------------------------------------------------------

+

+# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files

+# that can be used to generate PDF.

+# The default value is: NO.

+

+GENERATE_DOCBOOK       = NO

+

+# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.

+# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in

+# front of it.

+# The default directory is: docbook.

+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.

+

+DOCBOOK_OUTPUT         = docbook

+

+# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the

+# program listings (including syntax highlighting and cross-referencing

+# information) to the DOCBOOK output. Note that enabling this will significantly

+# increase the size of the DOCBOOK output.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.

+

+DOCBOOK_PROGRAMLISTING = NO

+

+#---------------------------------------------------------------------------

+# Configuration options for the AutoGen Definitions output

+#---------------------------------------------------------------------------

+

+# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an

+# AutoGen Definitions (see http://autogen.sf.net) file that captures the

+# structure of the code including all documentation. Note that this feature is

+# still experimental and incomplete at the moment.

+# The default value is: NO.

+

+GENERATE_AUTOGEN_DEF   = NO

+

+#---------------------------------------------------------------------------

+# Configuration options related to the Perl module output

+#---------------------------------------------------------------------------

+

+# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module

+# file that captures the structure of the code including all documentation.

+#

+# Note that this feature is still experimental and incomplete at the moment.

+# The default value is: NO.

+

+GENERATE_PERLMOD       = NO

+

+# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary

+# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI

+# output from the Perl module output.

+# The default value is: NO.

+# This tag requires that the tag GENERATE_PERLMOD is set to YES.

+

+PERLMOD_LATEX          = NO

+

+# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely

+# formatted so it can be parsed by a human reader. This is useful if you want to

+# understand what is going on. On the other hand, if this tag is set to NO, the

+# size of the Perl module output will be much smaller and Perl will parse it

+# just the same.

+# The default value is: YES.

+# This tag requires that the tag GENERATE_PERLMOD is set to YES.

+

+PERLMOD_PRETTY         = YES

+

+# The names of the make variables in the generated doxyrules.make file are

+# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful

+# so different doxyrules.make files included by the same Makefile don't

+# overwrite each other's variables.

+# This tag requires that the tag GENERATE_PERLMOD is set to YES.

+

+PERLMOD_MAKEVAR_PREFIX =

+

+#---------------------------------------------------------------------------

+# Configuration options related to the preprocessor

+#---------------------------------------------------------------------------

+

+# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all

+# C-preprocessor directives found in the sources and include files.

+# The default value is: YES.

+

+ENABLE_PREPROCESSING   = YES

+

+# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names

+# in the source code. If set to NO, only conditional compilation will be

+# performed. Macro expansion can be done in a controlled way by setting

+# EXPAND_ONLY_PREDEF to YES.

+# The default value is: NO.

+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

+

+MACRO_EXPANSION        = NO

+

+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then

+# the macro expansion is limited to the macros specified with the PREDEFINED and

+# EXPAND_AS_DEFINED tags.

+# The default value is: NO.

+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

+

+EXPAND_ONLY_PREDEF     = NO

+

+# If the SEARCH_INCLUDES tag is set to YES, the include files in the

+# INCLUDE_PATH will be searched if a #include is found.

+# The default value is: YES.

+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

+

+SEARCH_INCLUDES        = YES

+

+# The INCLUDE_PATH tag can be used to specify one or more directories that

+# contain include files that are not input files but should be processed by the

+# preprocessor.

+# This tag requires that the tag SEARCH_INCLUDES is set to YES.

+

+INCLUDE_PATH           =

+

+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard

+# patterns (like *.h and *.hpp) to filter out the header-files in the

+# directories. If left blank, the patterns specified with FILE_PATTERNS will be

+# used.

+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

+

+INCLUDE_FILE_PATTERNS  =

+

+# The PREDEFINED tag can be used to specify one or more macro names that are

+# defined before the preprocessor is started (similar to the -D option of e.g.

+# gcc). The argument of the tag is a list of macros of the form: name or

+# name=definition (no spaces). If the definition and the "=" are omitted, "=1"

+# is assumed. To prevent a macro definition from being undefined via #undef or

+# recursively expanded use the := operator instead of the = operator.

+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

+

+PREDEFINED             =

+

+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this

+# tag can be used to specify a list of macro names that should be expanded. The

+# macro definition that is found in the sources will be used. Use the PREDEFINED

+# tag if you want to use a different macro definition that overrules the

+# definition found in the source code.

+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

+

+EXPAND_AS_DEFINED      =

+

+# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will

+# remove all references to function-like macros that are alone on a line, have

+# an all uppercase name, and do not end with a semicolon. Such function macros

+# are typically used for boiler-plate code, and will confuse the parser if not

+# removed.

+# The default value is: YES.

+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

+

+SKIP_FUNCTION_MACROS   = YES

+

+#---------------------------------------------------------------------------

+# Configuration options related to external references

+#---------------------------------------------------------------------------

+

+# The TAGFILES tag can be used to specify one or more tag files. For each tag

+# file the location of the external documentation should be added. The format of

+# a tag file without this location is as follows:

+# TAGFILES = file1 file2 ...

+# Adding location for the tag files is done as follows:

+# TAGFILES = file1=loc1 "file2 = loc2" ...

+# where loc1 and loc2 can be relative or absolute paths or URLs. See the

+# section "Linking to external documentation" for more information about the use

+# of tag files.

+# Note: Each tag file must have a unique name (where the name does NOT include

+# the path). If a tag file is not located in the directory in which doxygen is

+# run, you must also specify the path to the tagfile here.

+

+TAGFILES               =

+

+# When a file name is specified after GENERATE_TAGFILE, doxygen will create a

+# tag file that is based on the input files it reads. See section "Linking to

+# external documentation" for more information about the usage of tag files.

+

+GENERATE_TAGFILE       =

+

+# If the ALLEXTERNALS tag is set to YES, all external class will be listed in

+# the class index. If set to NO, only the inherited external classes will be

+# listed.

+# The default value is: NO.

+

+ALLEXTERNALS           = NO

+

+# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed

+# in the modules index. If set to NO, only the current project's groups will be

+# listed.

+# The default value is: YES.

+

+EXTERNAL_GROUPS        = YES

+

+# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in

+# the related pages index. If set to NO, only the current project's pages will

+# be listed.

+# The default value is: YES.

+

+EXTERNAL_PAGES         = YES

+

+# The PERL_PATH should be the absolute path and name of the perl script

+# interpreter (i.e. the result of 'which perl').

+# The default file (with absolute path) is: /usr/bin/perl.

+

+PERL_PATH              = /usr/bin/perl

+

+#---------------------------------------------------------------------------

+# Configuration options related to the dot tool

+#---------------------------------------------------------------------------

+

+# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram

+# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to

+# NO turns the diagrams off. Note that this option also works with HAVE_DOT

+# disabled, but it is recommended to install and use dot, since it yields more

+# powerful graphs.

+# The default value is: YES.

+

+CLASS_DIAGRAMS         = YES

+

+# You can define message sequence charts within doxygen comments using the \msc

+# command. Doxygen will then run the mscgen tool (see:

+# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the

+# documentation. The MSCGEN_PATH tag allows you to specify the directory where

+# the mscgen tool resides. If left empty the tool is assumed to be found in the

+# default search path.

+

+MSCGEN_PATH            =

+

+# You can include diagrams made with dia in doxygen documentation. Doxygen will

+# then run dia to produce the diagram and insert it in the documentation. The

+# DIA_PATH tag allows you to specify the directory where the dia binary resides.

+# If left empty dia is assumed to be found in the default search path.

+

+DIA_PATH               =

+

+# If set to YES the inheritance and collaboration graphs will hide inheritance

+# and usage relations if the target is undocumented or is not a class.

+# The default value is: YES.

+

+HIDE_UNDOC_RELATIONS   = YES

+

+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is

+# available from the path. This tool is part of Graphviz (see:

+# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent

+# Bell Labs. The other options in this section have no effect if this option is

+# set to NO

+# The default value is: NO.

+

+HAVE_DOT               = NO

+

+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed

+# to run in parallel. When set to 0 doxygen will base this on the number of

+# processors available in the system. You can set it explicitly to a value

+# larger than 0 to get control over the balance between CPU load and processing

+# speed.

+# Minimum value: 0, maximum value: 32, default value: 0.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+DOT_NUM_THREADS        = 0

+

+# When you want a differently looking font in the dot files that doxygen

+# generates you can specify the font name using DOT_FONTNAME. You need to make

+# sure dot is able to find the font, which can be done by putting it in a

+# standard location or by setting the DOTFONTPATH environment variable or by

+# setting DOT_FONTPATH to the directory containing the font.

+# The default value is: Helvetica.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+DOT_FONTNAME           = Helvetica

+

+# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of

+# dot graphs.

+# Minimum value: 4, maximum value: 24, default value: 10.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+DOT_FONTSIZE           = 10

+

+# By default doxygen will tell dot to use the default font as specified with

+# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set

+# the path where dot can find it using this tag.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+DOT_FONTPATH           =

+

+# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for

+# each documented class showing the direct and indirect inheritance relations.

+# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.

+# The default value is: YES.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+CLASS_GRAPH            = YES

+

+# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a

+# graph for each documented class showing the direct and indirect implementation

+# dependencies (inheritance, containment, and class references variables) of the

+# class with other documented classes.

+# The default value is: YES.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+COLLABORATION_GRAPH    = YES

+

+# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for

+# groups, showing the direct groups dependencies.

+# The default value is: YES.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+GROUP_GRAPHS           = YES

+

+# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and

+# collaboration diagrams in a style similar to the OMG's Unified Modeling

+# Language.

+# The default value is: NO.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+UML_LOOK               = NO

+

+# If the UML_LOOK tag is enabled, the fields and methods are shown inside the

+# class node. If there are many fields or methods and many nodes the graph may

+# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the

+# number of items for each type to make the size more manageable. Set this to 0

+# for no limit. Note that the threshold may be exceeded by 50% before the limit

+# is enforced. So when you set the threshold to 10, up to 15 fields may appear,

+# but if the number exceeds 15, the total amount of fields shown is limited to

+# 10.

+# Minimum value: 0, maximum value: 100, default value: 10.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+UML_LIMIT_NUM_FIELDS   = 10

+

+# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and

+# collaboration graphs will show the relations between templates and their

+# instances.

+# The default value is: NO.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+TEMPLATE_RELATIONS     = NO

+

+# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to

+# YES then doxygen will generate a graph for each documented file showing the

+# direct and indirect include dependencies of the file with other documented

+# files.

+# The default value is: YES.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+INCLUDE_GRAPH          = YES

+

+# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are

+# set to YES then doxygen will generate a graph for each documented file showing

+# the direct and indirect include dependencies of the file with other documented

+# files.

+# The default value is: YES.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+INCLUDED_BY_GRAPH      = YES

+

+# If the CALL_GRAPH tag is set to YES then doxygen will generate a call

+# dependency graph for every global function or class method.

+#

+# Note that enabling this option will significantly increase the time of a run.

+# So in most cases it will be better to enable call graphs for selected

+# functions only using the \callgraph command. Disabling a call graph can be

+# accomplished by means of the command \hidecallgraph.

+# The default value is: NO.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+CALL_GRAPH             = NO

+

+# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller

+# dependency graph for every global function or class method.

+#

+# Note that enabling this option will significantly increase the time of a run.

+# So in most cases it will be better to enable caller graphs for selected

+# functions only using the \callergraph command. Disabling a caller graph can be

+# accomplished by means of the command \hidecallergraph.

+# The default value is: NO.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+CALLER_GRAPH           = NO

+

+# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical

+# hierarchy of all classes instead of a textual one.

+# The default value is: YES.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+GRAPHICAL_HIERARCHY    = YES

+

+# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the

+# dependencies a directory has on other directories in a graphical way. The

+# dependency relations are determined by the #include relations between the

+# files in the directories.

+# The default value is: YES.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+DIRECTORY_GRAPH        = YES

+

+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images

+# generated by dot. For an explanation of the image formats see the section

+# output formats in the documentation of the dot tool (Graphviz (see:

+# http://www.graphviz.org/)).

+# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order

+# to make the SVG files visible in IE 9+ (other browsers do not have this

+# requirement).

+# Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo,

+# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and

+# png:gdiplus:gdiplus.

+# The default value is: png.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+DOT_IMAGE_FORMAT       = png

+

+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to

+# enable generation of interactive SVG images that allow zooming and panning.

+#

+# Note that this requires a modern browser other than Internet Explorer. Tested

+# and working are Firefox, Chrome, Safari, and Opera.

+# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make

+# the SVG files visible. Older versions of IE do not have SVG support.

+# The default value is: NO.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+INTERACTIVE_SVG        = NO

+

+# The DOT_PATH tag can be used to specify the path where the dot tool can be

+# found. If left blank, it is assumed the dot tool can be found in the path.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+DOT_PATH               =

+

+# The DOTFILE_DIRS tag can be used to specify one or more directories that

+# contain dot files that are included in the documentation (see the \dotfile

+# command).

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+DOTFILE_DIRS           =

+

+# The MSCFILE_DIRS tag can be used to specify one or more directories that

+# contain msc files that are included in the documentation (see the \mscfile

+# command).

+

+MSCFILE_DIRS           =

+

+# The DIAFILE_DIRS tag can be used to specify one or more directories that

+# contain dia files that are included in the documentation (see the \diafile

+# command).

+

+DIAFILE_DIRS           =

+

+# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the

+# path where java can find the plantuml.jar file. If left blank, it is assumed

+# PlantUML is not used or called during a preprocessing step. Doxygen will

+# generate a warning when it encounters a \startuml command in this case and

+# will not generate output for the diagram.

+

+PLANTUML_JAR_PATH      =

+

+# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a

+# configuration file for plantuml.

+

+PLANTUML_CFG_FILE      =

+

+# When using plantuml, the specified paths are searched for files specified by

+# the !include statement in a plantuml block.

+

+PLANTUML_INCLUDE_PATH  =

+

+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes

+# that will be shown in the graph. If the number of nodes in a graph becomes

+# larger than this value, doxygen will truncate the graph, which is visualized

+# by representing a node as a red box. Note that doxygen if the number of direct

+# children of the root node in a graph is already larger than

+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that

+# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.

+# Minimum value: 0, maximum value: 10000, default value: 50.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+DOT_GRAPH_MAX_NODES    = 50

+

+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs

+# generated by dot. A depth value of 3 means that only nodes reachable from the

+# root by following a path via at most 3 edges will be shown. Nodes that lay

+# further from the root node will be omitted. Note that setting this option to 1

+# or 2 may greatly reduce the computation time needed for large code bases. Also

+# note that the size of a graph can be further restricted by

+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.

+# Minimum value: 0, maximum value: 1000, default value: 0.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+MAX_DOT_GRAPH_DEPTH    = 0

+

+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent

+# background. This is disabled by default, because dot on Windows does not seem

+# to support this out of the box.

+#

+# Warning: Depending on the platform used, enabling this option may lead to

+# badly anti-aliased labels on the edges of a graph (i.e. they become hard to

+# read).

+# The default value is: NO.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+DOT_TRANSPARENT        = NO

+

+# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output

+# files in one run (i.e. multiple -o and -T options on the command line). This

+# makes dot run faster, but since only newer versions of dot (>1.8.10) support

+# this, this feature is disabled by default.

+# The default value is: NO.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+DOT_MULTI_TARGETS      = NO

+

+# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page

+# explaining the meaning of the various boxes and arrows in the dot generated

+# graphs.

+# The default value is: YES.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+GENERATE_LEGEND        = YES

+

+# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot

+# files that are used to generate the various graphs.

+# The default value is: YES.

+# This tag requires that the tag HAVE_DOT is set to YES.

+

+DOT_CLEANUP            = YES

diff --git a/src/Shaders/FxBatchCompilerScript.fxbc b/src/Shaders/FxBatchCompilerScript.fxbc
new file mode 100644
index 0000000..d5b475f
--- /dev/null
+++ b/src/Shaders/FxBatchCompilerScript.fxbc
@@ -0,0 +1,19 @@
+// LICENSE

+// =======

+// Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.

+// -------

+// 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.

+

+/T vs_5_0 /E main /O3 /Fh VS_Compiled.h VS.hlsl

+/T ps_5_0 /E main /O3 /Fh PS_Compiled.h PS.hlsl

diff --git a/src/Shaders/PS.hlsl b/src/Shaders/PS.hlsl
new file mode 100644
index 0000000..f84c9d2
--- /dev/null
+++ b/src/Shaders/PS.hlsl
@@ -0,0 +1,40 @@
+//

+// Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.

+//

+// 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.

+//

+

+Texture2D t0 : register(t0);

+SamplerState s0 : register(s0);

+

+struct VS_OUTPUT

+{

+    float4 pos: SV_POSITION;

+    float2 texCoord: TEXCOORD;

+};

+

+cbuffer ConstantBuffer0 : register(b0)

+{

+    float4 color;

+};

+

+float4 main(VS_OUTPUT input) : SV_TARGET

+{

+    return t0.Sample(s0, input.texCoord) * color;

+}

diff --git a/src/Shaders/PS_Compiled.h b/src/Shaders/PS_Compiled.h
new file mode 100644
index 0000000..495c73b
--- /dev/null
+++ b/src/Shaders/PS_Compiled.h
@@ -0,0 +1,203 @@
+#if 0

+//

+// Generated by Microsoft (R) HLSL Shader Compiler 10.0.10011.16384

+//

+//

+// Buffer Definitions: 

+//

+// cbuffer ConstantBuffer0

+// {

+//

+//   float4 color;                      // Offset:    0 Size:    16

+//

+// }

+//

+//

+// Resource Bindings:

+//

+// Name                                 Type  Format         Dim      HLSL Bind  Count

+// ------------------------------ ---------- ------- ----------- -------------- ------

+// s0                                sampler      NA          NA             s0      1 

+// t0                                texture  float4          2d             t0      1 

+// ConstantBuffer0                   cbuffer      NA          NA            cb0      1 

+//

+//

+//

+// Input signature:

+//

+// Name                 Index   Mask Register SysValue  Format   Used

+// -------------------- ----- ------ -------- -------- ------- ------

+// SV_POSITION              0   xyzw        0      POS   float       

+// TEXCOORD                 0   xy          1     NONE   float   xy  

+//

+//

+// Output signature:

+//

+// Name                 Index   Mask Register SysValue  Format   Used

+// -------------------- ----- ------ -------- -------- ------- ------

+// SV_TARGET                0   xyzw        0   TARGET   float   xyzw

+//

+ps_5_0

+dcl_globalFlags refactoringAllowed

+dcl_constantbuffer CB0[1], immediateIndexed

+dcl_sampler s0, mode_default

+dcl_resource_texture2d (float,float,float,float) t0

+dcl_input_ps linear v1.xy

+dcl_output o0.xyzw

+dcl_temps 1

+sample_indexable(texture2d)(float,float,float,float) r0.xyzw, v1.xyxx, t0.xyzw, s0

+mul o0.xyzw, r0.xyzw, cb0[0].xyzw

+ret 

+// Approximately 3 instruction slots used

+#endif

+

+const BYTE g_main[] =

+{

+     68,  88,  66,  67, 120,  29, 

+     48, 248, 140,  25,  86, 194, 

+     52,  40, 230,  77, 247, 113, 

+    213, 244,   1,   0,   0,   0, 

+    112,   3,   0,   0,   5,   0, 

+      0,   0,  52,   0,   0,   0, 

+    152,   1,   0,   0, 240,   1, 

+      0,   0,  36,   2,   0,   0, 

+    212,   2,   0,   0,  82,  68, 

+     69,  70,  92,   1,   0,   0, 

+      1,   0,   0,   0, 180,   0, 

+      0,   0,   3,   0,   0,   0, 

+     60,   0,   0,   0,   0,   5, 

+    255, 255,   0, 129,   0,   0, 

+     40,   1,   0,   0,  82,  68, 

+     49,  49,  60,   0,   0,   0, 

+     24,   0,   0,   0,  32,   0, 

+      0,   0,  40,   0,   0,   0, 

+     36,   0,   0,   0,  12,   0, 

+      0,   0,   0,   0,   0,   0, 

+    156,   0,   0,   0,   3,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      1,   0,   0,   0,   1,   0, 

+      0,   0, 159,   0,   0,   0, 

+      2,   0,   0,   0,   5,   0, 

+      0,   0,   4,   0,   0,   0, 

+    255, 255, 255, 255,   0,   0, 

+      0,   0,   1,   0,   0,   0, 

+     13,   0,   0,   0, 162,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   1,   0, 

+      0,   0,   1,   0,   0,   0, 

+    115,  48,   0, 116,  48,   0, 

+     67, 111, 110, 115, 116,  97, 

+    110, 116,  66, 117, 102, 102, 

+    101, 114,  48,   0, 171, 171, 

+    162,   0,   0,   0,   1,   0, 

+      0,   0, 204,   0,   0,   0, 

+     16,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+    244,   0,   0,   0,   0,   0, 

+      0,   0,  16,   0,   0,   0, 

+      2,   0,   0,   0,   4,   1, 

+      0,   0,   0,   0,   0,   0, 

+    255, 255, 255, 255,   0,   0, 

+      0,   0, 255, 255, 255, 255, 

+      0,   0,   0,   0,  99, 111, 

+    108, 111, 114,   0, 102, 108, 

+    111,  97, 116,  52,   0, 171, 

+    171, 171,   1,   0,   3,   0, 

+      1,   0,   4,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0, 250,   0, 

+      0,   0,  77, 105,  99, 114, 

+    111, 115, 111, 102, 116,  32, 

+     40,  82,  41,  32,  72,  76, 

+     83,  76,  32,  83, 104,  97, 

+    100, 101, 114,  32,  67, 111, 

+    109, 112, 105, 108, 101, 114, 

+     32,  49,  48,  46,  48,  46, 

+     49,  48,  48,  49,  49,  46, 

+     49,  54,  51,  56,  52,   0, 

+     73,  83,  71,  78,  80,   0, 

+      0,   0,   2,   0,   0,   0, 

+      8,   0,   0,   0,  56,   0, 

+      0,   0,   0,   0,   0,   0, 

+      1,   0,   0,   0,   3,   0, 

+      0,   0,   0,   0,   0,   0, 

+     15,   0,   0,   0,  68,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   3,   0, 

+      0,   0,   1,   0,   0,   0, 

+      3,   3,   0,   0,  83,  86, 

+     95,  80,  79,  83,  73,  84, 

+     73,  79,  78,   0,  84,  69, 

+     88,  67,  79,  79,  82,  68, 

+      0, 171, 171, 171,  79,  83, 

+     71,  78,  44,   0,   0,   0, 

+      1,   0,   0,   0,   8,   0, 

+      0,   0,  32,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   3,   0,   0,   0, 

+      0,   0,   0,   0,  15,   0, 

+      0,   0,  83,  86,  95,  84, 

+     65,  82,  71,  69,  84,   0, 

+    171, 171,  83,  72,  69,  88, 

+    168,   0,   0,   0,  80,   0, 

+      0,   0,  42,   0,   0,   0, 

+    106,   8,   0,   1,  89,   0, 

+      0,   4,  70, 142,  32,   0, 

+      0,   0,   0,   0,   1,   0, 

+      0,   0,  90,   0,   0,   3, 

+      0,  96,  16,   0,   0,   0, 

+      0,   0,  88,  24,   0,   4, 

+      0, 112,  16,   0,   0,   0, 

+      0,   0,  85,  85,   0,   0, 

+     98,  16,   0,   3,  50,  16, 

+     16,   0,   1,   0,   0,   0, 

+    101,   0,   0,   3, 242,  32, 

+     16,   0,   0,   0,   0,   0, 

+    104,   0,   0,   2,   1,   0, 

+      0,   0,  69,   0,   0, 139, 

+    194,   0,   0, 128,  67,  85, 

+     21,   0, 242,   0,  16,   0, 

+      0,   0,   0,   0,  70,  16, 

+     16,   0,   1,   0,   0,   0, 

+     70, 126,  16,   0,   0,   0, 

+      0,   0,   0,  96,  16,   0, 

+      0,   0,   0,   0,  56,   0, 

+      0,   8, 242,  32,  16,   0, 

+      0,   0,   0,   0,  70,  14, 

+     16,   0,   0,   0,   0,   0, 

+     70, 142,  32,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+     62,   0,   0,   1,  83,  84, 

+     65,  84, 148,   0,   0,   0, 

+      3,   0,   0,   0,   1,   0, 

+      0,   0,   0,   0,   0,   0, 

+      2,   0,   0,   0,   1,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   1,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   1,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0

+};

diff --git a/src/Shaders/VS.hlsl b/src/Shaders/VS.hlsl
new file mode 100644
index 0000000..89a10b0
--- /dev/null
+++ b/src/Shaders/VS.hlsl
@@ -0,0 +1,46 @@
+//

+// Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.

+//

+// 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.

+//

+

+struct VS_INPUT

+{

+    float3 pos : POSITION;

+    float2 texCoord: TEXCOORD;

+};

+

+struct VS_OUTPUT

+{

+    float4 pos: SV_POSITION;

+    float2 texCoord: TEXCOORD;

+};

+

+cbuffer ConstantBuffer1 : register(b1)

+{

+    float4x4 WorldViewProj;

+};

+

+VS_OUTPUT main(VS_INPUT input)

+{

+    VS_OUTPUT output;

+    output.pos = mul(float4(input.pos, 1.0f), WorldViewProj);

+    output.texCoord = input.texCoord;

+    return output;

+}

diff --git a/src/Shaders/VS_Compiled.h b/src/Shaders/VS_Compiled.h
new file mode 100644
index 0000000..2d30bda
--- /dev/null
+++ b/src/Shaders/VS_Compiled.h
@@ -0,0 +1,220 @@
+#if 0

+//

+// Generated by Microsoft (R) HLSL Shader Compiler 10.0.10011.16384

+//

+//

+// Buffer Definitions: 

+//

+// cbuffer ConstantBuffer1

+// {

+//

+//   float4x4 WorldViewProj;            // Offset:    0 Size:    64

+//

+// }

+//

+//

+// Resource Bindings:

+//

+// Name                                 Type  Format         Dim      HLSL Bind  Count

+// ------------------------------ ---------- ------- ----------- -------------- ------

+// ConstantBuffer1                   cbuffer      NA          NA            cb1      1 

+//

+//

+//

+// Input signature:

+//

+// Name                 Index   Mask Register SysValue  Format   Used

+// -------------------- ----- ------ -------- -------- ------- ------

+// POSITION                 0   xyz         0     NONE   float   xyz 

+// TEXCOORD                 0   xy          1     NONE   float   xy  

+//

+//

+// Output signature:

+//

+// Name                 Index   Mask Register SysValue  Format   Used

+// -------------------- ----- ------ -------- -------- ------- ------

+// SV_POSITION              0   xyzw        0      POS   float   xyzw

+// TEXCOORD                 0   xy          1     NONE   float   xy  

+//

+vs_5_0

+dcl_globalFlags refactoringAllowed

+dcl_constantbuffer CB1[4], immediateIndexed

+dcl_input v0.xyz

+dcl_input v1.xy

+dcl_output_siv o0.xyzw, position

+dcl_output o1.xy

+dcl_temps 1

+mov r0.xyz, v0.xyzx

+mov r0.w, l(1.000000)

+dp4 o0.x, r0.xyzw, cb1[0].xyzw

+dp4 o0.y, r0.xyzw, cb1[1].xyzw

+dp4 o0.z, r0.xyzw, cb1[2].xyzw

+dp4 o0.w, r0.xyzw, cb1[3].xyzw

+mov o1.xy, v1.xyxx

+ret 

+// Approximately 8 instruction slots used

+#endif

+

+const BYTE g_main[] =

+{

+     68,  88,  66,  67, 206,  13, 

+    137, 181, 114, 110, 131,  98, 

+     24, 137, 147, 240, 237, 245, 

+     81, 131,   1,   0,   0,   0, 

+    192,   3,   0,   0,   5,   0, 

+      0,   0,  52,   0,   0,   0, 

+     88,   1,   0,   0, 172,   1, 

+      0,   0,   4,   2,   0,   0, 

+     36,   3,   0,   0,  82,  68, 

+     69,  70,  28,   1,   0,   0, 

+      1,   0,   0,   0, 108,   0, 

+      0,   0,   1,   0,   0,   0, 

+     60,   0,   0,   0,   0,   5, 

+    254, 255,   0, 129,   0,   0, 

+    232,   0,   0,   0,  82,  68, 

+     49,  49,  60,   0,   0,   0, 

+     24,   0,   0,   0,  32,   0, 

+      0,   0,  40,   0,   0,   0, 

+     36,   0,   0,   0,  12,   0, 

+      0,   0,   0,   0,   0,   0, 

+     92,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   1,   0,   0,   0, 

+      1,   0,   0,   0,   1,   0, 

+      0,   0,  67, 111, 110, 115, 

+    116,  97, 110, 116,  66, 117, 

+    102, 102, 101, 114,  49,   0, 

+     92,   0,   0,   0,   1,   0, 

+      0,   0, 132,   0,   0,   0, 

+     64,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+    172,   0,   0,   0,   0,   0, 

+      0,   0,  64,   0,   0,   0, 

+      2,   0,   0,   0, 196,   0, 

+      0,   0,   0,   0,   0,   0, 

+    255, 255, 255, 255,   0,   0, 

+      0,   0, 255, 255, 255, 255, 

+      0,   0,   0,   0,  87, 111, 

+    114, 108, 100,  86, 105, 101, 

+    119,  80, 114, 111, 106,   0, 

+    102, 108, 111,  97, 116,  52, 

+    120,  52,   0, 171,   3,   0, 

+      3,   0,   4,   0,   4,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+    186,   0,   0,   0,  77, 105, 

+     99, 114, 111, 115, 111, 102, 

+    116,  32,  40,  82,  41,  32, 

+     72,  76,  83,  76,  32,  83, 

+    104,  97, 100, 101, 114,  32, 

+     67, 111, 109, 112, 105, 108, 

+    101, 114,  32,  49,  48,  46, 

+     48,  46,  49,  48,  48,  49, 

+     49,  46,  49,  54,  51,  56, 

+     52,   0,  73,  83,  71,  78, 

+     76,   0,   0,   0,   2,   0, 

+      0,   0,   8,   0,   0,   0, 

+     56,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      3,   0,   0,   0,   0,   0, 

+      0,   0,   7,   7,   0,   0, 

+     65,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      3,   0,   0,   0,   1,   0, 

+      0,   0,   3,   3,   0,   0, 

+     80,  79,  83,  73,  84,  73, 

+     79,  78,   0,  84,  69,  88, 

+     67,  79,  79,  82,  68,   0, 

+    171, 171,  79,  83,  71,  78, 

+     80,   0,   0,   0,   2,   0, 

+      0,   0,   8,   0,   0,   0, 

+     56,   0,   0,   0,   0,   0, 

+      0,   0,   1,   0,   0,   0, 

+      3,   0,   0,   0,   0,   0, 

+      0,   0,  15,   0,   0,   0, 

+     68,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      3,   0,   0,   0,   1,   0, 

+      0,   0,   3,  12,   0,   0, 

+     83,  86,  95,  80,  79,  83, 

+     73,  84,  73,  79,  78,   0, 

+     84,  69,  88,  67,  79,  79, 

+     82,  68,   0, 171, 171, 171, 

+     83,  72,  69,  88,  24,   1, 

+      0,   0,  80,   0,   1,   0, 

+     70,   0,   0,   0, 106,   8, 

+      0,   1,  89,   0,   0,   4, 

+     70, 142,  32,   0,   1,   0, 

+      0,   0,   4,   0,   0,   0, 

+     95,   0,   0,   3, 114,  16, 

+     16,   0,   0,   0,   0,   0, 

+     95,   0,   0,   3,  50,  16, 

+     16,   0,   1,   0,   0,   0, 

+    103,   0,   0,   4, 242,  32, 

+     16,   0,   0,   0,   0,   0, 

+      1,   0,   0,   0, 101,   0, 

+      0,   3,  50,  32,  16,   0, 

+      1,   0,   0,   0, 104,   0, 

+      0,   2,   1,   0,   0,   0, 

+     54,   0,   0,   5, 114,   0, 

+     16,   0,   0,   0,   0,   0, 

+     70,  18,  16,   0,   0,   0, 

+      0,   0,  54,   0,   0,   5, 

+    130,   0,  16,   0,   0,   0, 

+      0,   0,   1,  64,   0,   0, 

+      0,   0, 128,  63,  17,   0, 

+      0,   8,  18,  32,  16,   0, 

+      0,   0,   0,   0,  70,  14, 

+     16,   0,   0,   0,   0,   0, 

+     70, 142,  32,   0,   1,   0, 

+      0,   0,   0,   0,   0,   0, 

+     17,   0,   0,   8,  34,  32, 

+     16,   0,   0,   0,   0,   0, 

+     70,  14,  16,   0,   0,   0, 

+      0,   0,  70, 142,  32,   0, 

+      1,   0,   0,   0,   1,   0, 

+      0,   0,  17,   0,   0,   8, 

+     66,  32,  16,   0,   0,   0, 

+      0,   0,  70,  14,  16,   0, 

+      0,   0,   0,   0,  70, 142, 

+     32,   0,   1,   0,   0,   0, 

+      2,   0,   0,   0,  17,   0, 

+      0,   8, 130,  32,  16,   0, 

+      0,   0,   0,   0,  70,  14, 

+     16,   0,   0,   0,   0,   0, 

+     70, 142,  32,   0,   1,   0, 

+      0,   0,   3,   0,   0,   0, 

+     54,   0,   0,   5,  50,  32, 

+     16,   0,   1,   0,   0,   0, 

+     70,  16,  16,   0,   1,   0, 

+      0,   0,  62,   0,   0,   1, 

+     83,  84,  65,  84, 148,   0, 

+      0,   0,   8,   0,   0,   0, 

+      1,   0,   0,   0,   0,   0, 

+      0,   0,   4,   0,   0,   0, 

+      4,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      1,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      3,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0, 

+      0,   0,   0,   0,   0,   0

+};

diff --git a/src/Tests.cpp b/src/Tests.cpp
new file mode 100644
index 0000000..0f22d35
--- /dev/null
+++ b/src/Tests.cpp
@@ -0,0 +1,548 @@
+//

+// Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.

+//

+// 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.

+//

+

+#include "Tests.h"

+#include "Common.h"

+#include <thread>

+

+extern ID3D12GraphicsCommandList* BeginCommandList();

+extern void EndCommandList(ID3D12GraphicsCommandList* cmdList);

+

+struct AllocationDeleter

+{

+    void operator()(D3D12MA::Allocation* obj) const

+    {

+        if(obj)

+        {

+            obj->Release();

+        }

+    }

+};

+

+typedef std::unique_ptr<D3D12MA::Allocation, AllocationDeleter> AllocationUniquePtr;

+

+struct ResourceWithAllocation

+{

+    CComPtr<ID3D12Resource> resource;

+    AllocationUniquePtr allocation;

+    UINT64 size = UINT64_MAX;

+    UINT dataSeed = 0;

+};

+

+static void FillResourceDescForBuffer(D3D12_RESOURCE_DESC& outResourceDesc, UINT64 size)

+{

+    outResourceDesc = {};

+    outResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;

+    outResourceDesc.Alignment = 0;

+    outResourceDesc.Width = size;

+    outResourceDesc.Height = 1;

+    outResourceDesc.DepthOrArraySize = 1;

+    outResourceDesc.MipLevels = 1;

+    outResourceDesc.Format = DXGI_FORMAT_UNKNOWN;

+    outResourceDesc.SampleDesc.Count = 1;

+    outResourceDesc.SampleDesc.Quality = 0;

+    outResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;

+    outResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

+}

+

+static void FillData(void* outPtr, const UINT64 sizeInBytes, UINT seed)

+{

+    UINT* outValues = (UINT*)outPtr;

+    const UINT64 sizeInValues = sizeInBytes / sizeof(UINT);

+    UINT value = seed;

+    for(UINT i = 0; i < sizeInValues; ++i)

+    {

+        outValues[i] = value++;

+    }

+}

+

+static bool ValidateData(const void* ptr, const UINT64 sizeInBytes, UINT seed)

+{

+    const UINT* values = (const UINT*)ptr;

+    const UINT64 sizeInValues = sizeInBytes / sizeof(UINT);

+    UINT value = seed;

+    for(UINT i = 0; i < sizeInValues; ++i)

+    {

+        if(values[i] != value++)

+        {

+            //FAIL("ValidateData failed.");

+            return false;

+        }

+    }

+    return true;

+}

+

+static void TestCommittedResources(const TestContext& ctx)

+{

+    wprintf(L"Test committed resources\n");

+    

+    const UINT count = 4;

+    const UINT64 bufSize = 32ull * 1024;

+    const wchar_t* names[count] = {

+        L"Resource\nFoo\r\nBar",

+        L"Resource \"'&<>?#@!&-=_+[]{};:,./\\",

+        nullptr,

+        L"",

+    };

+

+    ResourceWithAllocation resources[count];

+

+    D3D12MA::ALLOCATION_DESC allocDesc = {};

+    allocDesc.HeapType = D3D12_HEAP_TYPE_UPLOAD;

+    allocDesc.Flags = D3D12MA::ALLOCATION_FLAG_COMMITTED;

+

+    D3D12_RESOURCE_DESC resourceDesc;

+    FillResourceDescForBuffer(resourceDesc, bufSize);

+

+    for(UINT i = 0; i < count; ++i)

+    {

+        D3D12MA::Allocation* alloc = nullptr;

+        CHECK_HR( ctx.allocator->CreateResource(

+            &allocDesc,

+            &resourceDesc,

+            D3D12_RESOURCE_STATE_GENERIC_READ,

+            NULL,

+            &alloc,

+            IID_PPV_ARGS(&resources[i].resource)) );

+        resources[i].allocation.reset(alloc);

+        

+        // Make sure it has implicit heap.

+        CHECK_BOOL( resources[i].allocation->GetHeap() == NULL && resources[i].allocation->GetOffset() == 0 );

+

+        resources[i].allocation->SetName(names[i]);

+    }

+

+    // Check names.

+    for(UINT i = 0; i < count; ++i)

+    {

+        const wchar_t* const allocName = resources[i].allocation->GetName();

+        if(allocName)

+        {

+            CHECK_BOOL( wcscmp(allocName, names[i]) == 0 );

+        }

+        else

+        {

+            CHECK_BOOL(names[i] == NULL);

+        }

+    }

+}

+

+static void TestPlacedResources(const TestContext& ctx)

+{

+    wprintf(L"Test placed resources\n");

+

+    const UINT count = 4;

+    const UINT64 bufSize = 32ull * 1024;

+    ResourceWithAllocation resources[count];

+

+    D3D12MA::ALLOCATION_DESC allocDesc = {};

+    allocDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;

+

+    D3D12_RESOURCE_DESC resourceDesc;

+    FillResourceDescForBuffer(resourceDesc, bufSize);

+

+    D3D12MA::Allocation* alloc = nullptr;

+    for(UINT i = 0; i < count; ++i)

+    {

+        CHECK_HR( ctx.allocator->CreateResource(

+            &allocDesc,

+            &resourceDesc,

+            D3D12_RESOURCE_STATE_GENERIC_READ,

+            NULL,

+            &alloc,

+            IID_PPV_ARGS(&resources[i].resource)) );

+        resources[i].allocation.reset(alloc);

+

+        // Make sure it doesn't have implicit heap.

+        CHECK_BOOL( resources[i].allocation->GetHeap() != NULL );

+    }

+

+    // Make sure at least some of the resources belong to the same heap, but their memory ranges don't overlap.

+    bool sameHeapFound = false;

+    for(size_t i = 0; i < count; ++i)

+    {

+        for(size_t j = i + 1; j < count; ++j)

+        {

+            const ResourceWithAllocation& resI = resources[i];

+            const ResourceWithAllocation& resJ = resources[j];

+            if(resI.allocation->GetHeap() != NULL &&

+                resI.allocation->GetHeap() == resJ.allocation->GetHeap())

+            {

+                sameHeapFound = true;

+                CHECK_BOOL(resI.allocation->GetOffset() + resI.allocation->GetSize() <= resJ.allocation->GetOffset() ||

+                    resJ.allocation->GetOffset() + resJ.allocation->GetSize() <= resI.allocation->GetOffset());

+            }

+        }

+    }

+    CHECK_BOOL(sameHeapFound);

+

+    // Additionally create a texture to see if no error occurs due to bad handling of Resource Tier.

+    resourceDesc = {};

+    resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;

+    resourceDesc.Alignment = 0;

+    resourceDesc.Width = 1024;

+    resourceDesc.Height = 1024;

+    resourceDesc.DepthOrArraySize = 1;

+    resourceDesc.MipLevels = 1;

+    resourceDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

+    resourceDesc.SampleDesc.Count = 1;

+    resourceDesc.SampleDesc.Quality = 0;

+    resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;

+    resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

+    ResourceWithAllocation textureRes;

+    CHECK_HR( ctx.allocator->CreateResource(

+        &allocDesc,

+        &resourceDesc,

+        D3D12_RESOURCE_STATE_COPY_DEST,

+        NULL,

+        &alloc,

+        IID_PPV_ARGS(&textureRes.resource)) );

+    textureRes.allocation.reset(alloc);

+

+    // Additionally create an MSAA render target to see if no error occurs due to bad handling of Resource Tier.

+    resourceDesc = {};

+    resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;

+    resourceDesc.Alignment = 0;

+    resourceDesc.Width = 1920;

+    resourceDesc.Height = 1080;

+    resourceDesc.DepthOrArraySize = 1;

+    resourceDesc.MipLevels = 1;

+    resourceDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

+    resourceDesc.SampleDesc.Count = 2;

+    resourceDesc.SampleDesc.Quality = 0;

+    resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;

+    resourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;

+    ResourceWithAllocation renderTargetRes;

+    CHECK_HR( ctx.allocator->CreateResource(

+        &allocDesc,

+        &resourceDesc,

+        D3D12_RESOURCE_STATE_RENDER_TARGET,

+        NULL,

+        &alloc,

+        IID_PPV_ARGS(&renderTargetRes.resource)) );

+    renderTargetRes.allocation.reset(alloc);

+}

+

+static void TestMapping(const TestContext& ctx)

+{

+    wprintf(L"Test mapping\n");

+

+    const UINT count = 10;

+    const UINT64 bufSize = 32ull * 1024;

+    ResourceWithAllocation resources[count];

+

+    D3D12MA::ALLOCATION_DESC allocDesc = {};

+    allocDesc.HeapType = D3D12_HEAP_TYPE_UPLOAD;

+

+    D3D12_RESOURCE_DESC resourceDesc;

+    FillResourceDescForBuffer(resourceDesc, bufSize);

+

+    for(UINT i = 0; i < count; ++i)

+    {

+        D3D12MA::Allocation* alloc = nullptr;

+        CHECK_HR( ctx.allocator->CreateResource(

+            &allocDesc,

+            &resourceDesc,

+            D3D12_RESOURCE_STATE_GENERIC_READ,

+            NULL,

+            &alloc,

+            IID_PPV_ARGS(&resources[i].resource)) );

+        resources[i].allocation.reset(alloc);

+

+        void* mappedPtr = NULL;

+        CHECK_HR( resources[i].resource->Map(0, NULL, &mappedPtr) );

+

+        FillData(mappedPtr, bufSize, i);

+

+        // Unmap every other buffer. Leave others mapped.

+        if((i % 2) != 0)

+        {

+            resources[i].resource->Unmap(0, NULL);

+        }

+    }

+}

+

+static void TestTransfer(const TestContext& ctx)

+{

+    wprintf(L"Test mapping\n");

+

+    const UINT count = 10;

+    const UINT64 bufSize = 32ull * 1024;

+    

+    ResourceWithAllocation resourcesUpload[count];

+    ResourceWithAllocation resourcesDefault[count];

+    ResourceWithAllocation resourcesReadback[count];

+

+    D3D12MA::ALLOCATION_DESC allocDescUpload = {};

+    allocDescUpload.HeapType = D3D12_HEAP_TYPE_UPLOAD;

+    D3D12MA::ALLOCATION_DESC allocDescDefault = {};

+    allocDescDefault.HeapType = D3D12_HEAP_TYPE_DEFAULT;

+    D3D12MA::ALLOCATION_DESC allocDescReadback = {};

+    allocDescReadback.HeapType = D3D12_HEAP_TYPE_READBACK;

+

+    D3D12_RESOURCE_DESC resourceDesc;

+    FillResourceDescForBuffer(resourceDesc, bufSize);

+

+    // Create 3 sets of resources.

+    for(UINT i = 0; i < count; ++i)

+    {

+        D3D12MA::Allocation* alloc = nullptr;

+        CHECK_HR( ctx.allocator->CreateResource(

+            &allocDescUpload,

+            &resourceDesc,

+            D3D12_RESOURCE_STATE_GENERIC_READ,

+            NULL,

+            &alloc,

+            IID_PPV_ARGS(&resourcesUpload[i].resource)) );

+        resourcesUpload[i].allocation.reset(alloc);

+

+        CHECK_HR( ctx.allocator->CreateResource(

+            &allocDescDefault,

+            &resourceDesc,

+            D3D12_RESOURCE_STATE_COPY_DEST,

+            NULL,

+            &alloc,

+            IID_PPV_ARGS(&resourcesDefault[i].resource)) );

+        resourcesDefault[i].allocation.reset(alloc);

+

+        CHECK_HR( ctx.allocator->CreateResource(

+            &allocDescReadback,

+            &resourceDesc,

+            D3D12_RESOURCE_STATE_COPY_DEST,

+            NULL,

+            &alloc,

+            IID_PPV_ARGS(&resourcesReadback[i].resource)) );

+        resourcesReadback[i].allocation.reset(alloc);

+    }

+

+    // Map and fill data in UPLOAD.

+    for(UINT i = 0; i < count; ++i)

+    {

+        void* mappedPtr = nullptr;

+        CHECK_HR( resourcesUpload[i].resource->Map(0, NULL, &mappedPtr) );

+

+        FillData(mappedPtr, bufSize, i);

+

+        // Unmap every other resource, leave others mapped.

+        if((i % 2) != 0)

+        {

+            resourcesUpload[i].resource->Unmap(0, NULL);

+        }

+    }

+

+    // Transfer from UPLOAD to DEFAULT, from there to READBACK.

+    ID3D12GraphicsCommandList* cmdList = BeginCommandList();

+    for(UINT i = 0; i < count; ++i)

+    {

+        cmdList->CopyBufferRegion(resourcesDefault[i].resource, 0, resourcesUpload[i].resource, 0, bufSize);

+    }

+    D3D12_RESOURCE_BARRIER barriers[count] = {};

+    for(UINT i = 0; i < count; ++i)

+    {

+        barriers[i].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;

+        barriers[i].Transition.pResource = resourcesDefault[i].resource;

+        barriers[i].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;

+        barriers[i].Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;

+        barriers[i].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;

+    }

+    cmdList->ResourceBarrier(count, barriers);

+    for(UINT i = 0; i < count; ++i)

+    {

+        cmdList->CopyBufferRegion(resourcesReadback[i].resource, 0, resourcesDefault[i].resource, 0, bufSize);

+    }

+    EndCommandList(cmdList);

+

+    // Validate READBACK buffers.

+    for(UINT i = count; i--; )

+    {

+        const D3D12_RANGE mapRange = {0, bufSize};

+        void* mappedPtr = nullptr;

+        CHECK_HR( resourcesReadback[i].resource->Map(0, &mapRange, &mappedPtr) );

+

+        CHECK_BOOL( ValidateData(mappedPtr, bufSize, i) );

+

+        // Unmap every 3rd resource, leave others mapped.

+        if((i % 3) != 0)

+        {

+            const D3D12_RANGE writtenRange = {0, 0};

+            resourcesReadback[i].resource->Unmap(0, &writtenRange);

+        }

+    }

+}

+

+static void TestMultithreading(const TestContext& ctx)

+{

+    wprintf(L"Test multithreading\n");

+

+    const UINT threadCount = 32;

+    const UINT bufSizeMin = 1024ull;

+    const UINT bufSizeMax = 1024ull * 1024;

+

+    D3D12MA::ALLOCATION_DESC allocDesc = {};

+    allocDesc.HeapType = D3D12_HEAP_TYPE_UPLOAD;

+

+    // Launch threads.

+    std::thread threads[threadCount];

+    for(UINT threadIndex = 0; threadIndex < threadCount; ++threadIndex)

+    {

+        auto threadFunc = [&, threadIndex]()

+        {

+            RandomNumberGenerator rand(threadIndex);

+

+            std::vector<ResourceWithAllocation> resources;

+            resources.reserve(256);

+

+            // Create starting number of buffers.

+            const UINT bufToCreateCount = 64;

+            for(UINT bufIndex = 0; bufIndex < bufToCreateCount; ++bufIndex)

+            {

+                ResourceWithAllocation res = {};

+                res.dataSeed = (threadIndex << 16) | bufIndex;

+                res.size = AlignUp<UINT>(rand.Generate() % (bufSizeMax - bufSizeMin) + bufSizeMin, 16);

+

+                D3D12_RESOURCE_DESC resourceDesc;

+                FillResourceDescForBuffer(resourceDesc, res.size);

+

+                D3D12MA::Allocation* alloc = nullptr;

+                CHECK_HR( ctx.allocator->CreateResource(

+                    &allocDesc,

+                    &resourceDesc,

+                    D3D12_RESOURCE_STATE_GENERIC_READ,

+                    NULL,

+                    &alloc,

+                    IID_PPV_ARGS(&res.resource)) );

+                res.allocation.reset(alloc);

+                

+                void* mappedPtr = nullptr;

+                CHECK_HR( res.resource->Map(0, NULL, &mappedPtr) );

+

+                FillData(mappedPtr, res.size, res.dataSeed);

+

+                // Unmap some of them, leave others mapped.

+                if(rand.GenerateBool())

+                {

+                    res.resource->Unmap(0, NULL);

+                }

+

+                resources.push_back(std::move(res));

+            }

+            

+            Sleep(20);

+

+            // Make a number of random allocate and free operations.

+            const UINT operationCount = 128;

+            for(UINT operationIndex = 0; operationIndex < operationCount; ++operationIndex)

+            {

+                const bool removePossible = !resources.empty();

+                const bool remove = removePossible && rand.GenerateBool();

+                if(remove)

+                {

+                    const UINT indexToRemove = rand.Generate() % resources.size();

+                    resources.erase(resources.begin() + indexToRemove);

+                }

+                else // Create new buffer.

+                {

+                    ResourceWithAllocation res = {};

+                    res.dataSeed = (threadIndex << 16) | operationIndex;

+                    res.size = AlignUp<UINT>(rand.Generate() % (bufSizeMax - bufSizeMin) + bufSizeMin, 16);

+                    D3D12_RESOURCE_DESC resourceDesc;

+                    FillResourceDescForBuffer(resourceDesc, res.size);

+

+                    D3D12MA::Allocation* alloc = nullptr;

+                    CHECK_HR( ctx.allocator->CreateResource(

+                        &allocDesc,

+                        &resourceDesc,

+                        D3D12_RESOURCE_STATE_GENERIC_READ,

+                        NULL,

+                        &alloc,

+                        IID_PPV_ARGS(&res.resource)) );

+                    res.allocation.reset(alloc);

+

+                    void* mappedPtr = nullptr;

+                    CHECK_HR( res.resource->Map(0, NULL, &mappedPtr) );

+

+                    FillData(mappedPtr, res.size, res.dataSeed);

+

+                    // Unmap some of them, leave others mapped.

+                    if(rand.GenerateBool())

+                    {

+                        res.resource->Unmap(0, NULL);

+                    }

+

+                    resources.push_back(std::move(res));

+                }

+            }

+

+            Sleep(20);

+

+            // Validate data in all remaining buffers while deleting them.

+            for(size_t resIndex = resources.size(); resIndex--; )

+            {

+                void* mappedPtr = nullptr;

+                CHECK_HR( resources[resIndex].resource->Map(0, NULL, &mappedPtr) );

+

+                ValidateData(mappedPtr, resources[resIndex].size, resources[resIndex].dataSeed);

+

+                // Unmap some of them, leave others mapped.

+                if((resIndex % 3) == 1)

+                {

+                    D3D12_RANGE writtenRange = {0, 0};

+                    resources[resIndex].resource->Unmap(0, &writtenRange);

+                } 

+

+                resources.pop_back();

+            }

+        };

+        threads[threadIndex] = std::thread(threadFunc);

+    }

+

+    // Wait for threads to finish.

+    for(UINT threadIndex = threadCount; threadIndex--; )

+    {

+        threads[threadIndex].join();

+    }

+}

+

+static void TestGroupBasics(const TestContext& ctx)

+{

+    TestCommittedResources(ctx);

+    TestPlacedResources(ctx);

+    TestMapping(ctx);

+    TestTransfer(ctx);

+    TestMultithreading(ctx);

+}

+

+void Test(const TestContext& ctx)

+{

+    wprintf(L"TESTS BEGIN\n");

+

+    if(false)

+    {

+        ////////////////////////////////////////////////////////////////////////////////

+        // Temporarily insert custom tests here:

+        return;

+    }

+

+    TestGroupBasics(ctx);

+

+    wprintf(L"TESTS END\n");

+}

diff --git a/src/Tests.h b/src/Tests.h
new file mode 100644
index 0000000..e67c5ee
--- /dev/null
+++ b/src/Tests.h
@@ -0,0 +1,33 @@
+//

+// Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.

+//

+// 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.

+//

+

+#pragma once

+

+#include "D3D12MemAlloc.h"

+

+struct TestContext

+{

+    ID3D12Device* device;

+    D3D12MA::Allocator* allocator;

+};

+

+void Test(const TestContext& ctx);