Prepare initial release

This commit is contained in:
Adam Sawicki 2019-05-20 13:46:23 +02:00
parent e359bafd23
commit eb4b1716aa
23 changed files with 9698 additions and 2 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
build/
docs/html/

3
CHANGELOG.md Normal file
View File

@ -0,0 +1,3 @@
# 1.0.0</b> (2019-07-23)
First published version.

19
LICENSE.txt Normal file
View File

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

82
NOTICES.txt Normal file
View File

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

107
README.md
View File

@ -1,3 +1,106 @@
# Direct3D 12 Memory Allocator
# D3D12 Memory Allocator
Easy to integrate Direct3D 12 memory allocation library
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.

Binary file not shown.

27
premake/LICENSE.txt Normal file
View File

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

BIN
premake/premake5.exe Normal file

Binary file not shown.

50
premake/premake5.lua Normal file
View File

@ -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" }

176
src/Common.cpp Normal file
View File

@ -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);
}

380
src/Common.h Normal file
View File

@ -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, ...);

3122
src/D3D12MemAlloc.cpp Normal file

File diff suppressed because it is too large Load Diff

603
src/D3D12MemAlloc.h Normal file
View File

@ -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

27
src/D3D12MemAlloc.natvis Normal file
View File

@ -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>

1501
src/D3D12Sample.cpp Normal file

File diff suppressed because it is too large Load Diff

2492
src/Doxyfile Normal file

File diff suppressed because it is too large Load Diff

View File

@ -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

40
src/Shaders/PS.hlsl Normal file
View File

@ -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;
}

203
src/Shaders/PS_Compiled.h Normal file
View File

@ -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
};

46
src/Shaders/VS.hlsl Normal file
View File

@ -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;
}

220
src/Shaders/VS_Compiled.h Normal file
View File

@ -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
};

548
src/Tests.cpp Normal file
View File

@ -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");
}

33
src/Tests.h Normal file
View File

@ -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);