diff options
| author | Vishal More <[email protected]> | 2020-06-11 11:11:17 +0530 |
|---|---|---|
| committer | Vishal More <[email protected]> | 2020-06-11 11:11:17 +0530 |
| commit | bbe353230727568d3c1999af2701d2e150ff232f (patch) | |
| tree | 4b75466fc0f5b8fb70bc020a9da22d2b924d0aab /samples/DX_APIUsage/DXUT/Core | |
| parent | Documentation Update (diff) | |
| download | gfesdk-bbe353230727568d3c1999af2701d2e150ff232f.tar.xz gfesdk-bbe353230727568d3c1999af2701d2e150ff232f.zip | |
Picking up lastest bug fixes & SHA2 signing1.1.232
[SNG-2803] GFE-SDK : SHA-2 sign task
Diffstat (limited to 'samples/DX_APIUsage/DXUT/Core')
| -rw-r--r-- | samples/DX_APIUsage/DXUT/Core/DDSTextureLoader.cpp | 1825 | ||||
| -rw-r--r-- | samples/DX_APIUsage/DXUT/Core/DDSTextureLoader.h | 129 | ||||
| -rw-r--r-- | samples/DX_APIUsage/DXUT/Core/DXUT.cpp | 3892 | ||||
| -rw-r--r-- | samples/DX_APIUsage/DXUT/Core/DXUT.h | 330 | ||||
| -rw-r--r-- | samples/DX_APIUsage/DXUT/Core/DXUTDevice11.cpp | 764 | ||||
| -rw-r--r-- | samples/DX_APIUsage/DXUT/Core/DXUTDevice11.h | 114 | ||||
| -rw-r--r-- | samples/DX_APIUsage/DXUT/Core/DXUTmisc.cpp | 1326 | ||||
| -rw-r--r-- | samples/DX_APIUsage/DXUT/Core/DXUTmisc.h | 460 | ||||
| -rw-r--r-- | samples/DX_APIUsage/DXUT/Core/ScreenGrab.cpp | 1204 | ||||
| -rw-r--r-- | samples/DX_APIUsage/DXUT/Core/ScreenGrab.h | 39 | ||||
| -rw-r--r-- | samples/DX_APIUsage/DXUT/Core/WICTextureLoader.cpp | 932 | ||||
| -rw-r--r-- | samples/DX_APIUsage/DXUT/Core/WICTextureLoader.h | 126 |
12 files changed, 6669 insertions, 4472 deletions
diff --git a/samples/DX_APIUsage/DXUT/Core/DDSTextureLoader.cpp b/samples/DX_APIUsage/DXUT/Core/DDSTextureLoader.cpp new file mode 100644 index 0000000..3d72d9e --- /dev/null +++ b/samples/DX_APIUsage/DXUT/Core/DDSTextureLoader.cpp @@ -0,0 +1,1825 @@ +//-------------------------------------------------------------------------------------- +// File: DDSTextureLoader.cpp +// +// Functions for loading a DDS texture and creating a Direct3D runtime resource for it +// +// Note these functions are useful as a light-weight runtime loader for DDS files. For +// a full-featured DDS file reader, writer, and texture processing pipeline see +// the 'Texconv' sample and the 'DirectXTex' library. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=248926 +// http://go.microsoft.com/fwlink/?LinkId=248929 +//-------------------------------------------------------------------------------------- + +#include "dxut.h" + +#include "DDSTextureLoader.h" + +#include <assert.h> +#include <algorithm> +#include <memory> + +#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) +#pragma comment(lib,"dxguid.lib") +#endif + +using namespace DirectX; + +//-------------------------------------------------------------------------------------- +// Macros +//-------------------------------------------------------------------------------------- +#ifndef MAKEFOURCC + #define MAKEFOURCC(ch0, ch1, ch2, ch3) \ + ((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) | \ + ((uint32_t)(uint8_t)(ch2) << 16) | ((uint32_t)(uint8_t)(ch3) << 24 )) +#endif /* defined(MAKEFOURCC) */ + +//-------------------------------------------------------------------------------------- +// DDS file structure definitions +// +// See DDS.h in the 'Texconv' sample and the 'DirectXTex' library +//-------------------------------------------------------------------------------------- +#pragma pack(push,1) + +const uint32_t DDS_MAGIC = 0x20534444; // "DDS " + +struct DDS_PIXELFORMAT +{ + uint32_t size; + uint32_t flags; + uint32_t fourCC; + uint32_t RGBBitCount; + uint32_t RBitMask; + uint32_t GBitMask; + uint32_t BBitMask; + uint32_t ABitMask; +}; + +#define DDS_FOURCC 0x00000004 // DDPF_FOURCC +#define DDS_RGB 0x00000040 // DDPF_RGB +#define DDS_LUMINANCE 0x00020000 // DDPF_LUMINANCE +#define DDS_ALPHA 0x00000002 // DDPF_ALPHA +#define DDS_BUMPDUDV 0x00080000 // DDPF_BUMPDUDV + +#define DDS_HEADER_FLAGS_VOLUME 0x00800000 // DDSD_DEPTH + +#define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT +#define DDS_WIDTH 0x00000004 // DDSD_WIDTH + +#define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX +#define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX +#define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY +#define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY +#define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ +#define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ + +#define DDS_CUBEMAP_ALLFACES ( DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\ + DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\ + DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ ) + +#define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP + +enum DDS_MISC_FLAGS2 +{ + DDS_MISC_FLAGS2_ALPHA_MODE_MASK = 0x7L, +}; + +struct DDS_HEADER +{ + uint32_t size; + uint32_t flags; + uint32_t height; + uint32_t width; + uint32_t pitchOrLinearSize; + uint32_t depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags + uint32_t mipMapCount; + uint32_t reserved1[11]; + DDS_PIXELFORMAT ddspf; + uint32_t caps; + uint32_t caps2; + uint32_t caps3; + uint32_t caps4; + uint32_t reserved2; +}; + +struct DDS_HEADER_DXT10 +{ + DXGI_FORMAT dxgiFormat; + uint32_t resourceDimension; + uint32_t miscFlag; // see D3D11_RESOURCE_MISC_FLAG + uint32_t arraySize; + uint32_t miscFlags2; +}; + +#pragma pack(pop) + +//-------------------------------------------------------------------------------------- +namespace +{ + struct handle_closer { void operator()(HANDLE h) { if (h) CloseHandle(h); } }; + + typedef public std::unique_ptr<void, handle_closer> ScopedHandle; + + inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? 0 : h; } + + template<UINT TNameLength> + inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_ const char (&name)[TNameLength]) + { + #if defined(_DEBUG) || defined(PROFILE) + resource->SetPrivateData(WKPDID_D3DDebugObjectName, TNameLength - 1, name); + #else + UNREFERENCED_PARAMETER(resource); + UNREFERENCED_PARAMETER(name); + #endif + } + + //-------------------------------------------------------------------------------------- + HRESULT LoadTextureDataFromFile( + _In_z_ const wchar_t* fileName, + std::unique_ptr<uint8_t[]>& ddsData, + const DDS_HEADER** header, + const uint8_t** bitData, + size_t* bitSize) + { + if (!header || !bitData || !bitSize) + { + return E_POINTER; + } + + // open the file +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) + ScopedHandle hFile(safe_handle(CreateFile2(fileName, + GENERIC_READ, + FILE_SHARE_READ, + OPEN_EXISTING, + nullptr))); +#else + ScopedHandle hFile(safe_handle(CreateFileW(fileName, + GENERIC_READ, + FILE_SHARE_READ, + nullptr, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + nullptr))); +#endif + + if (!hFile) + { + return HRESULT_FROM_WIN32(GetLastError()); + } + + // Get the file size + FILE_STANDARD_INFO fileInfo; + if (!GetFileInformationByHandleEx(hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo))) + { + return HRESULT_FROM_WIN32(GetLastError()); + } + + // File is too big for 32-bit allocation, so reject read + if (fileInfo.EndOfFile.HighPart > 0) + { + return E_FAIL; + } + + // Need at least enough data to fill the header and magic number to be a valid DDS + if (fileInfo.EndOfFile.LowPart < (sizeof(DDS_HEADER) + sizeof(uint32_t))) + { + return E_FAIL; + } + + // create enough space for the file data + ddsData.reset(new (std::nothrow) uint8_t[fileInfo.EndOfFile.LowPart]); + if (!ddsData) + { + return E_OUTOFMEMORY; + } + + // read the data in + DWORD BytesRead = 0; + if (!ReadFile(hFile.get(), + ddsData.get(), + fileInfo.EndOfFile.LowPart, + &BytesRead, + nullptr + )) + { + return HRESULT_FROM_WIN32(GetLastError()); + } + + if (BytesRead < fileInfo.EndOfFile.LowPart) + { + return E_FAIL; + } + + // DDS files always start with the same magic number ("DDS ") + uint32_t dwMagicNumber = *reinterpret_cast<const uint32_t*>(ddsData.get()); + if (dwMagicNumber != DDS_MAGIC) + { + return E_FAIL; + } + + auto hdr = reinterpret_cast<const DDS_HEADER*>(ddsData.get() + sizeof(uint32_t)); + + // Verify header to validate DDS file + if (hdr->size != sizeof(DDS_HEADER) || + hdr->ddspf.size != sizeof(DDS_PIXELFORMAT)) + { + return E_FAIL; + } + + // Check for DX10 extension + bool bDXT10Header = false; + if ((hdr->ddspf.flags & DDS_FOURCC) && + (MAKEFOURCC('D', 'X', '1', '0') == hdr->ddspf.fourCC)) + { + // Must be long enough for both headers and magic value + if (fileInfo.EndOfFile.LowPart < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_DXT10))) + { + return E_FAIL; + } + + bDXT10Header = true; + } + + // setup the pointers in the process request + *header = hdr; + ptrdiff_t offset = sizeof(uint32_t) + sizeof(DDS_HEADER) + + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0); + *bitData = ddsData.get() + offset; + *bitSize = fileInfo.EndOfFile.LowPart - offset; + + return S_OK; + } + + + //-------------------------------------------------------------------------------------- + // Return the BPP for a particular format + //-------------------------------------------------------------------------------------- + size_t BitsPerPixel(_In_ DXGI_FORMAT fmt) + { + switch (fmt) + { + case DXGI_FORMAT_R32G32B32A32_TYPELESS: + case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_R32G32B32A32_UINT: + case DXGI_FORMAT_R32G32B32A32_SINT: + return 128; + + case DXGI_FORMAT_R32G32B32_TYPELESS: + case DXGI_FORMAT_R32G32B32_FLOAT: + case DXGI_FORMAT_R32G32B32_UINT: + case DXGI_FORMAT_R32G32B32_SINT: + return 96; + + case DXGI_FORMAT_R16G16B16A16_TYPELESS: + case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16G16B16A16_UINT: + case DXGI_FORMAT_R16G16B16A16_SNORM: + case DXGI_FORMAT_R16G16B16A16_SINT: + case DXGI_FORMAT_R32G32_TYPELESS: + case DXGI_FORMAT_R32G32_FLOAT: + case DXGI_FORMAT_R32G32_UINT: + case DXGI_FORMAT_R32G32_SINT: + case DXGI_FORMAT_R32G8X24_TYPELESS: + case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: + case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: + case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: + case DXGI_FORMAT_Y416: + case DXGI_FORMAT_Y210: + case DXGI_FORMAT_Y216: + return 64; + + case DXGI_FORMAT_R10G10B10A2_TYPELESS: + case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R10G10B10A2_UINT: + case DXGI_FORMAT_R11G11B10_FLOAT: + case DXGI_FORMAT_R8G8B8A8_TYPELESS: + case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: + case DXGI_FORMAT_R8G8B8A8_UINT: + case DXGI_FORMAT_R8G8B8A8_SNORM: + case DXGI_FORMAT_R8G8B8A8_SINT: + case DXGI_FORMAT_R16G16_TYPELESS: + case DXGI_FORMAT_R16G16_FLOAT: + case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_UINT: + case DXGI_FORMAT_R16G16_SNORM: + case DXGI_FORMAT_R16G16_SINT: + case DXGI_FORMAT_R32_TYPELESS: + case DXGI_FORMAT_D32_FLOAT: + case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R32_UINT: + case DXGI_FORMAT_R32_SINT: + case DXGI_FORMAT_R24G8_TYPELESS: + case DXGI_FORMAT_D24_UNORM_S8_UINT: + case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: + case DXGI_FORMAT_X24_TYPELESS_G8_UINT: + case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: + case DXGI_FORMAT_R8G8_B8G8_UNORM: + case DXGI_FORMAT_G8R8_G8B8_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: + case DXGI_FORMAT_B8G8R8A8_TYPELESS: + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: + case DXGI_FORMAT_B8G8R8X8_TYPELESS: + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: + case DXGI_FORMAT_AYUV: + case DXGI_FORMAT_Y410: + case DXGI_FORMAT_YUY2: + return 32; + + case DXGI_FORMAT_P010: + case DXGI_FORMAT_P016: + return 24; + + case DXGI_FORMAT_R8G8_TYPELESS: + case DXGI_FORMAT_R8G8_UNORM: + case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8_SNORM: + case DXGI_FORMAT_R8G8_SINT: + case DXGI_FORMAT_R16_TYPELESS: + case DXGI_FORMAT_R16_FLOAT: + case DXGI_FORMAT_D16_UNORM: + case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16_UINT: + case DXGI_FORMAT_R16_SNORM: + case DXGI_FORMAT_R16_SINT: + case DXGI_FORMAT_B5G6R5_UNORM: + case DXGI_FORMAT_B5G5R5A1_UNORM: + case DXGI_FORMAT_A8P8: + case DXGI_FORMAT_B4G4R4A4_UNORM: + return 16; + + case DXGI_FORMAT_NV12: + case DXGI_FORMAT_420_OPAQUE: + case DXGI_FORMAT_NV11: + return 12; + + case DXGI_FORMAT_R8_TYPELESS: + case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8_SNORM: + case DXGI_FORMAT_R8_SINT: + case DXGI_FORMAT_A8_UNORM: + case DXGI_FORMAT_AI44: + case DXGI_FORMAT_IA44: + case DXGI_FORMAT_P8: + return 8; + + case DXGI_FORMAT_R1_UNORM: + return 1; + + case DXGI_FORMAT_BC1_TYPELESS: + case DXGI_FORMAT_BC1_UNORM: + case DXGI_FORMAT_BC1_UNORM_SRGB: + case DXGI_FORMAT_BC4_TYPELESS: + case DXGI_FORMAT_BC4_UNORM: + case DXGI_FORMAT_BC4_SNORM: + return 4; + + case DXGI_FORMAT_BC2_TYPELESS: + case DXGI_FORMAT_BC2_UNORM: + case DXGI_FORMAT_BC2_UNORM_SRGB: + case DXGI_FORMAT_BC3_TYPELESS: + case DXGI_FORMAT_BC3_UNORM: + case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC5_TYPELESS: + case DXGI_FORMAT_BC5_UNORM: + case DXGI_FORMAT_BC5_SNORM: + case DXGI_FORMAT_BC6H_TYPELESS: + case DXGI_FORMAT_BC6H_UF16: + case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_TYPELESS: + case DXGI_FORMAT_BC7_UNORM: + case DXGI_FORMAT_BC7_UNORM_SRGB: + return 8; + + default: + return 0; + } + } + + + //-------------------------------------------------------------------------------------- + // Get surface information for a particular format + //-------------------------------------------------------------------------------------- + void GetSurfaceInfo( + _In_ size_t width, + _In_ size_t height, + _In_ DXGI_FORMAT fmt, + size_t* outNumBytes, + _Out_opt_ size_t* outRowBytes, + _Out_opt_ size_t* outNumRows) + { + size_t numBytes = 0; + size_t rowBytes = 0; + size_t numRows = 0; + + bool bc = false; + bool packed = false; + bool planar = false; + size_t bpe = 0; + switch (fmt) + { + case DXGI_FORMAT_BC1_TYPELESS: + case DXGI_FORMAT_BC1_UNORM: + case DXGI_FORMAT_BC1_UNORM_SRGB: + case DXGI_FORMAT_BC4_TYPELESS: + case DXGI_FORMAT_BC4_UNORM: + case DXGI_FORMAT_BC4_SNORM: + bc = true; + bpe = 8; + break; + + case DXGI_FORMAT_BC2_TYPELESS: + case DXGI_FORMAT_BC2_UNORM: + case DXGI_FORMAT_BC2_UNORM_SRGB: + case DXGI_FORMAT_BC3_TYPELESS: + case DXGI_FORMAT_BC3_UNORM: + case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC5_TYPELESS: + case DXGI_FORMAT_BC5_UNORM: + case DXGI_FORMAT_BC5_SNORM: + case DXGI_FORMAT_BC6H_TYPELESS: + case DXGI_FORMAT_BC6H_UF16: + case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_TYPELESS: + case DXGI_FORMAT_BC7_UNORM: + case DXGI_FORMAT_BC7_UNORM_SRGB: + bc = true; + bpe = 16; + break; + + case DXGI_FORMAT_R8G8_B8G8_UNORM: + case DXGI_FORMAT_G8R8_G8B8_UNORM: + case DXGI_FORMAT_YUY2: + packed = true; + bpe = 4; + break; + + case DXGI_FORMAT_Y210: + case DXGI_FORMAT_Y216: + packed = true; + bpe = 8; + break; + + case DXGI_FORMAT_NV12: + case DXGI_FORMAT_420_OPAQUE: + planar = true; + bpe = 2; + break; + + case DXGI_FORMAT_P010: + case DXGI_FORMAT_P016: + planar = true; + bpe = 4; + break; + } + + if (bc) + { + size_t numBlocksWide = 0; + if (width > 0) + { + numBlocksWide = std::max<size_t>(1, (width + 3) / 4); + } + size_t numBlocksHigh = 0; + if (height > 0) + { + numBlocksHigh = std::max<size_t>(1, (height + 3) / 4); + } + rowBytes = numBlocksWide * bpe; + numRows = numBlocksHigh; + numBytes = rowBytes * numBlocksHigh; + } + else if (packed) + { + rowBytes = ((width + 1) >> 1) * bpe; + numRows = height; + numBytes = rowBytes * height; + } + else if (fmt == DXGI_FORMAT_NV11) + { + rowBytes = ((width + 3) >> 2) * 4; + numRows = height * 2; // Direct3D makes this simplifying assumption, although it is larger than the 4:1:1 data + numBytes = rowBytes * numRows; + } + else if (planar) + { + rowBytes = ((width + 1) >> 1) * bpe; + numBytes = (rowBytes * height) + ((rowBytes * height + 1) >> 1); + numRows = height + ((height + 1) >> 1); + } + else + { + size_t bpp = BitsPerPixel(fmt); + rowBytes = (width * bpp + 7) / 8; // round up to nearest byte + numRows = height; + numBytes = rowBytes * height; + } + + if (outNumBytes) + { + *outNumBytes = numBytes; + } + if (outRowBytes) + { + *outRowBytes = rowBytes; + } + if (outNumRows) + { + *outNumRows = numRows; + } + } + + + //-------------------------------------------------------------------------------------- + #define ISBITMASK( r,g,b,a ) ( ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a ) + + DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf) + { + if (ddpf.flags & DDS_RGB) + { + // Note that sRGB formats are written using the "DX10" extended header + + switch (ddpf.RGBBitCount) + { + case 32: + if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) + { + return DXGI_FORMAT_R8G8B8A8_UNORM; + } + + if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000)) + { + return DXGI_FORMAT_B8G8R8A8_UNORM; + } + + if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000)) + { + return DXGI_FORMAT_B8G8R8X8_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x000000ff,0x0000ff00,0x00ff0000,0x00000000) aka D3DFMT_X8B8G8R8 + + // Note that many common DDS reader/writers (including D3DX) swap the + // the RED/BLUE masks for 10:10:10:2 formats. We assume + // below that the 'backwards' header mask is being used since it is most + // likely written by D3DX. The more robust solution is to use the 'DX10' + // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly + + // For 'correct' writers, this should be 0x000003ff,0x000ffc00,0x3ff00000 for RGB data + if (ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000)) + { + return DXGI_FORMAT_R10G10B10A2_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x000003ff,0x000ffc00,0x3ff00000,0xc0000000) aka D3DFMT_A2R10G10B10 + + if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000)) + { + return DXGI_FORMAT_R16G16_UNORM; + } + + if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000)) + { + // Only 32-bit color channel format in D3D9 was R32F + return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114 + } + break; + + case 24: + // No 24bpp DXGI formats aka D3DFMT_R8G8B8 + break; + + case 16: + if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000)) + { + return DXGI_FORMAT_B5G5R5A1_UNORM; + } + if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000)) + { + return DXGI_FORMAT_B5G6R5_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x7c00,0x03e0,0x001f,0x0000) aka D3DFMT_X1R5G5B5 + + if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000)) + { + return DXGI_FORMAT_B4G4R4A4_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x0f00,0x00f0,0x000f,0x0000) aka D3DFMT_X4R4G4B4 + + // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc. + break; + } + } + else if (ddpf.flags & DDS_LUMINANCE) + { + if (8 == ddpf.RGBBitCount) + { + if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000)) + { + return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension + } + + // No DXGI format maps to ISBITMASK(0x0f,0x00,0x00,0xf0) aka D3DFMT_A4L4 + + if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00)) + { + return DXGI_FORMAT_R8G8_UNORM; // Some DDS writers assume the bitcount should be 8 instead of 16 + } + } + + if (16 == ddpf.RGBBitCount) + { + if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000)) + { + return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension + } + if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00)) + { + return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension + } + } + } + else if (ddpf.flags & DDS_ALPHA) + { + if (8 == ddpf.RGBBitCount) + { + return DXGI_FORMAT_A8_UNORM; + } + } + else if (ddpf.flags & DDS_BUMPDUDV) + { + if (16 == ddpf.RGBBitCount) + { + if (ISBITMASK(0x00ff, 0xff00, 0x0000, 0x0000)) + { + return DXGI_FORMAT_R8G8_SNORM; // D3DX10/11 writes this out as DX10 extension + } + } + + if (32 == ddpf.RGBBitCount) + { + if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) + { + return DXGI_FORMAT_R8G8B8A8_SNORM; // D3DX10/11 writes this out as DX10 extension + } + if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000)) + { + return DXGI_FORMAT_R16G16_SNORM; // D3DX10/11 writes this out as DX10 extension + } + + // No DXGI format maps to ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000) aka D3DFMT_A2W10V10U10 + } + } + else if (ddpf.flags & DDS_FOURCC) + { + if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC) + { + return DXGI_FORMAT_BC1_UNORM; + } + if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC) + { + return DXGI_FORMAT_BC2_UNORM; + } + if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC) + { + return DXGI_FORMAT_BC3_UNORM; + } + + // While pre-multiplied alpha isn't directly supported by the DXGI formats, + // they are basically the same as these BC formats so they can be mapped + if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC) + { + return DXGI_FORMAT_BC2_UNORM; + } + if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC) + { + return DXGI_FORMAT_BC3_UNORM; + } + + if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC) + { + return DXGI_FORMAT_BC4_UNORM; + } + if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC) + { + return DXGI_FORMAT_BC4_UNORM; + } + if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC) + { + return DXGI_FORMAT_BC4_SNORM; + } + + if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC) + { + return DXGI_FORMAT_BC5_UNORM; + } + if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC) + { + return DXGI_FORMAT_BC5_UNORM; + } + if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC) + { + return DXGI_FORMAT_BC5_SNORM; + } + + // BC6H and BC7 are written using the "DX10" extended header + + if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC) + { + return DXGI_FORMAT_R8G8_B8G8_UNORM; + } + if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC) + { + return DXGI_FORMAT_G8R8_G8B8_UNORM; + } + + if (MAKEFOURCC('Y', 'U', 'Y', '2') == ddpf.fourCC) + { + return DXGI_FORMAT_YUY2; + } + + // Check for D3DFORMAT enums being set here + switch (ddpf.fourCC) + { + case 36: // D3DFMT_A16B16G16R16 + return DXGI_FORMAT_R16G16B16A16_UNORM; + + case 110: // D3DFMT_Q16W16V16U16 + return DXGI_FORMAT_R16G16B16A16_SNORM; + + case 111: // D3DFMT_R16F + return DXGI_FORMAT_R16_FLOAT; + + case 112: // D3DFMT_G16R16F + return DXGI_FORMAT_R16G16_FLOAT; + + case 113: // D3DFMT_A16B16G16R16F + return DXGI_FORMAT_R16G16B16A16_FLOAT; + + case 114: // D3DFMT_R32F + return DXGI_FORMAT_R32_FLOAT; + + case 115: // D3DFMT_G32R32F + return DXGI_FORMAT_R32G32_FLOAT; + + case 116: // D3DFMT_A32B32G32R32F + return DXGI_FORMAT_R32G32B32A32_FLOAT; + } + } + + return DXGI_FORMAT_UNKNOWN; + } + + + //-------------------------------------------------------------------------------------- + DXGI_FORMAT MakeSRGB(_In_ DXGI_FORMAT format) + { + switch (format) + { + case DXGI_FORMAT_R8G8B8A8_UNORM: + return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + + case DXGI_FORMAT_BC1_UNORM: + return DXGI_FORMAT_BC1_UNORM_SRGB; + + case DXGI_FORMAT_BC2_UNORM: + return DXGI_FORMAT_BC2_UNORM_SRGB; + + case DXGI_FORMAT_BC3_UNORM: + return DXGI_FORMAT_BC3_UNORM_SRGB; + + case DXGI_FORMAT_B8G8R8A8_UNORM: + return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; + + case DXGI_FORMAT_B8G8R8X8_UNORM: + return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; + + case DXGI_FORMAT_BC7_UNORM: + return DXGI_FORMAT_BC7_UNORM_SRGB; + + default: + return format; + } + } + + + //-------------------------------------------------------------------------------------- + HRESULT FillInitData( + _In_ size_t width, + _In_ size_t height, + _In_ size_t depth, + _In_ size_t mipCount, + _In_ size_t arraySize, + _In_ DXGI_FORMAT format, + _In_ size_t maxsize, + _In_ size_t bitSize, + _In_reads_bytes_(bitSize) const uint8_t* bitData, + _Out_ size_t& twidth, + _Out_ size_t& theight, + _Out_ size_t& tdepth, + _Out_ size_t& skipMip, + _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData) + { + if (!bitData || !initData) + { + return E_POINTER; + } + + skipMip = 0; + twidth = 0; + theight = 0; + tdepth = 0; + + size_t NumBytes = 0; + size_t RowBytes = 0; + const uint8_t* pSrcBits = bitData; + const uint8_t* pEndBits = bitData + bitSize; + + size_t index = 0; + for (size_t j = 0; j < arraySize; j++) + { + size_t w = width; + size_t h = height; + size_t d = depth; + for (size_t i = 0; i < mipCount; i++) + { + GetSurfaceInfo(w, + h, + format, + &NumBytes, + &RowBytes, + nullptr + ); + + if ((mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize)) + { + if (!twidth) + { + twidth = w; + theight = h; + tdepth = d; + } + + assert(index < mipCount * arraySize); + _Analysis_assume_(index < mipCount * arraySize); + initData[index].pSysMem = (const void*)pSrcBits; + initData[index].SysMemPitch = static_cast<UINT>(RowBytes); + initData[index].SysMemSlicePitch = static_cast<UINT>(NumBytes); + ++index; + } + else if (!j) + { + // Count number of skipped mipmaps (first item only) + ++skipMip; + } + + if (pSrcBits + (NumBytes*d) > pEndBits) + { + return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); + } + + pSrcBits += NumBytes * d; + + w = w >> 1; + h = h >> 1; + d = d >> 1; + if (w == 0) + { + w = 1; + } + if (h == 0) + { + h = 1; + } + if (d == 0) + { + d = 1; + } + } + } + + return (index > 0) ? S_OK : E_FAIL; + } + + + //-------------------------------------------------------------------------------------- + HRESULT CreateD3DResources( + _In_ ID3D11Device* d3dDevice, + _In_ uint32_t resDim, + _In_ size_t width, + _In_ size_t height, + _In_ size_t depth, + _In_ size_t mipCount, + _In_ size_t arraySize, + _In_ DXGI_FORMAT format, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ bool forceSRGB, + _In_ bool isCubeMap, + _In_reads_opt_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) + { + if (!d3dDevice) + return E_POINTER; + + HRESULT hr = E_FAIL; + + if (forceSRGB) + { + format = MakeSRGB(format); + } + + switch (resDim) + { + case D3D11_RESOURCE_DIMENSION_TEXTURE1D: + { + D3D11_TEXTURE1D_DESC desc; + desc.Width = static_cast<UINT>(width); + desc.MipLevels = static_cast<UINT>(mipCount); + desc.ArraySize = static_cast<UINT>(arraySize); + desc.Format = format; + desc.Usage = usage; + desc.BindFlags = bindFlags; + desc.CPUAccessFlags = cpuAccessFlags; + desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE; + + ID3D11Texture1D* tex = nullptr; + hr = d3dDevice->CreateTexture1D(&desc, + initData, + &tex + ); + if (SUCCEEDED(hr) && tex != 0) + { + if (textureView != 0) + { + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; + SRVDesc.Format = format; + + if (arraySize > 1) + { + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY; + SRVDesc.Texture1DArray.MipLevels = (!mipCount) ? -1 : desc.MipLevels; + SRVDesc.Texture1DArray.ArraySize = static_cast<UINT>(arraySize); + } + else + { + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; + SRVDesc.Texture1D.MipLevels = (!mipCount) ? -1 : desc.MipLevels; + } + + hr = d3dDevice->CreateShaderResourceView(tex, + &SRVDesc, + textureView + ); + if (FAILED(hr)) + { + tex->Release(); + return hr; + } + } + + if (texture != 0) + { + *texture = tex; + } + else + { + SetDebugObjectName(tex, "DDSTextureLoader"); + tex->Release(); + } + } + } + break; + + case D3D11_RESOURCE_DIMENSION_TEXTURE2D: + { + D3D11_TEXTURE2D_DESC desc; + desc.Width = static_cast<UINT>(width); + desc.Height = static_cast<UINT>(height); + desc.MipLevels = static_cast<UINT>(mipCount); + desc.ArraySize = static_cast<UINT>(arraySize); + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Usage = usage; + desc.BindFlags = bindFlags; + desc.CPUAccessFlags = cpuAccessFlags; + if (isCubeMap) + { + desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_TEXTURECUBE; + } + else + { + desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE; + } + + ID3D11Texture2D* tex = nullptr; + hr = d3dDevice->CreateTexture2D(&desc, + initData, + &tex + ); + if (SUCCEEDED(hr) && tex != 0) + { + if (textureView != 0) + { + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; + SRVDesc.Format = format; + + if (isCubeMap) + { + if (arraySize > 6) + { + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY; + SRVDesc.TextureCubeArray.MipLevels = (!mipCount) ? -1 : desc.MipLevels; + + // Earlier we set arraySize to (NumCubes * 6) + SRVDesc.TextureCubeArray.NumCubes = static_cast<UINT>(arraySize / 6); + } + else + { + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; + SRVDesc.TextureCube.MipLevels = (!mipCount) ? -1 : desc.MipLevels; + } + } + else if (arraySize > 1) + { + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; + SRVDesc.Texture2DArray.MipLevels = (!mipCount) ? -1 : desc.MipLevels; + SRVDesc.Texture2DArray.ArraySize = static_cast<UINT>(arraySize); + } + else + { + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + SRVDesc.Texture2D.MipLevels = (!mipCount) ? -1 : desc.MipLevels; + } + + hr = d3dDevice->CreateShaderResourceView(tex, + &SRVDesc, + textureView + ); + if (FAILED(hr)) + { + tex->Release(); + return hr; + } + } + + if (texture != 0) + { + *texture = tex; + } + else + { + SetDebugObjectName(tex, "DDSTextureLoader"); + tex->Release(); + } + } + } + break; + + case D3D11_RESOURCE_DIMENSION_TEXTURE3D: + { + D3D11_TEXTURE3D_DESC desc; + desc.Width = static_cast<UINT>(width); + desc.Height = static_cast<UINT>(height); + desc.Depth = static_cast<UINT>(depth); + desc.MipLevels = static_cast<UINT>(mipCount); + desc.Format = format; + desc.Usage = usage; + desc.BindFlags = bindFlags; + desc.CPUAccessFlags = cpuAccessFlags; + desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE; + + ID3D11Texture3D* tex = nullptr; + hr = d3dDevice->CreateTexture3D(&desc, + initData, + &tex + ); + if (SUCCEEDED(hr) && tex != 0) + { + if (textureView != 0) + { + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; + SRVDesc.Format = format; + + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; + SRVDesc.Texture3D.MipLevels = (!mipCount) ? -1 : desc.MipLevels; + + hr = d3dDevice->CreateShaderResourceView(tex, + &SRVDesc, + textureView + ); + if (FAILED(hr)) + { + tex->Release(); + return hr; + } + } + + if (texture != 0) + { + *texture = tex; + } + else + { + SetDebugObjectName(tex, "DDSTextureLoader"); + tex->Release(); + } + } + } + break; + } + + return hr; + } + + + //-------------------------------------------------------------------------------------- + HRESULT CreateTextureFromDDS( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _In_ const DDS_HEADER* header, + _In_reads_bytes_(bitSize) const uint8_t* bitData, + _In_ size_t bitSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ bool forceSRGB, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) + { + HRESULT hr = S_OK; + + UINT width = header->width; + UINT height = header->height; + UINT depth = header->depth; + + uint32_t resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN; + UINT arraySize = 1; + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + bool isCubeMap = false; + + size_t mipCount = header->mipMapCount; + if (0 == mipCount) + { + mipCount = 1; + } + + if ((header->ddspf.flags & DDS_FOURCC) && + (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) + { + auto d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>((const char*)header + sizeof(DDS_HEADER)); + + arraySize = d3d10ext->arraySize; + if (arraySize == 0) + { + return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + } + + switch (d3d10ext->dxgiFormat) + { + case DXGI_FORMAT_AI44: + case DXGI_FORMAT_IA44: + case DXGI_FORMAT_P8: + case DXGI_FORMAT_A8P8: + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + + default: + if (BitsPerPixel(d3d10ext->dxgiFormat) == 0) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + } + + format = d3d10ext->dxgiFormat; + + switch (d3d10ext->resourceDimension) + { + case D3D11_RESOURCE_DIMENSION_TEXTURE1D: + // D3DX writes 1D textures with a fixed Height of 1 + if ((header->flags & DDS_HEIGHT) && height != 1) + { + return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + } + height = depth = 1; + break; + + case D3D11_RESOURCE_DIMENSION_TEXTURE2D: + if (d3d10ext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE) + { + arraySize *= 6; + isCubeMap = true; + } + depth = 1; + break; + + case D3D11_RESOURCE_DIMENSION_TEXTURE3D: + if (!(header->flags & DDS_HEADER_FLAGS_VOLUME)) + { + return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + } + + if (arraySize > 1) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + break; + + default: + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + + resDim = d3d10ext->resourceDimension; + } + else + { + format = GetDXGIFormat(header->ddspf); + + if (format == DXGI_FORMAT_UNKNOWN) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + + if (header->flags & DDS_HEADER_FLAGS_VOLUME) + { + resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D; + } + else + { + if (header->caps2 & DDS_CUBEMAP) + { + // We require all six faces to be defined + if ((header->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + + arraySize = 6; + isCubeMap = true; + } + + depth = 1; + resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D; + + // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture + } + + assert(BitsPerPixel(format) != 0); + } + + // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements) + if (mipCount > D3D11_REQ_MIP_LEVELS) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + + switch (resDim) + { + case D3D11_RESOURCE_DIMENSION_TEXTURE1D: + if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) || + (width > D3D11_REQ_TEXTURE1D_U_DIMENSION)) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + break; + + case D3D11_RESOURCE_DIMENSION_TEXTURE2D: + if (isCubeMap) + { + // This is the right bound because we set arraySize to (NumCubes*6) above + if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || + (width > D3D11_REQ_TEXTURECUBE_DIMENSION) || + (height > D3D11_REQ_TEXTURECUBE_DIMENSION)) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + } + else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) || + (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) || + (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION)) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + break; + + case D3D11_RESOURCE_DIMENSION_TEXTURE3D: + if ((arraySize > 1) || + (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || + (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || + (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + break; + + default: + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + + bool autogen = false; + if (mipCount == 1 && d3dContext != 0 && textureView != 0) // Must have context and shader-view to auto generate mipmaps + { + // See if format is supported for auto-gen mipmaps (varies by feature level) + UINT fmtSupport = 0; + hr = d3dDevice->CheckFormatSupport(format, &fmtSupport); + if (SUCCEEDED(hr) && (fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) + { + // 10level9 feature levels do not support auto-gen mipgen for volume textures + if ((resDim != D3D11_RESOURCE_DIMENSION_TEXTURE3D) + || (d3dDevice->GetFeatureLevel() >= D3D_FEATURE_LEVEL_10_0)) + { + autogen = true; + } + } + } + + if (autogen) + { + // Create texture with auto-generated mipmaps + ID3D11Resource* tex = nullptr; + hr = CreateD3DResources(d3dDevice, resDim, width, height, depth, 0, arraySize, + format, usage, + bindFlags | D3D11_BIND_RENDER_TARGET, + cpuAccessFlags, + miscFlags | D3D11_RESOURCE_MISC_GENERATE_MIPS, forceSRGB, + isCubeMap, nullptr, &tex, textureView); + if (SUCCEEDED(hr)) + { + size_t numBytes = 0; + size_t rowBytes = 0; + GetSurfaceInfo(width, height, format, &numBytes, &rowBytes, nullptr); + + if (numBytes > bitSize) + { + (*textureView)->Release(); + *textureView = nullptr; + tex->Release(); + return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); + } + + D3D11_SHADER_RESOURCE_VIEW_DESC desc; + (*textureView)->GetDesc(&desc); + + UINT mipLevels = 1; + + switch (desc.ViewDimension) + { + case D3D_SRV_DIMENSION_TEXTURE1D: mipLevels = desc.Texture1D.MipLevels; break; + case D3D_SRV_DIMENSION_TEXTURE1DARRAY: mipLevels = desc.Texture1DArray.MipLevels; break; + case D3D_SRV_DIMENSION_TEXTURE2D: mipLevels = desc.Texture2D.MipLevels; break; + case D3D_SRV_DIMENSION_TEXTURE2DARRAY: mipLevels = desc.Texture2DArray.MipLevels; break; + case D3D_SRV_DIMENSION_TEXTURECUBE: mipLevels = desc.TextureCube.MipLevels; break; + case D3D_SRV_DIMENSION_TEXTURECUBEARRAY:mipLevels = desc.TextureCubeArray.MipLevels; break; + case D3D_SRV_DIMENSION_TEXTURE3D: mipLevels = desc.Texture3D.MipLevels; break; + default: + (*textureView)->Release(); + *textureView = nullptr; + tex->Release(); + return E_UNEXPECTED; + } + + if (arraySize > 1) + { + const uint8_t* pSrcBits = bitData; + const uint8_t* pEndBits = bitData + bitSize; + for (UINT item = 0; item < arraySize; ++item) + { + if ((pSrcBits + numBytes) > pEndBits) + { + (*textureView)->Release(); + *textureView = nullptr; + tex->Release(); + return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); + } + + UINT res = D3D11CalcSubresource(0, item, mipLevels); + d3dContext->UpdateSubresource(tex, res, nullptr, pSrcBits, static_cast<UINT>(rowBytes), static_cast<UINT>(numBytes)); + pSrcBits += numBytes; + } + } + else + { + d3dContext->UpdateSubresource(tex, 0, nullptr, bitData, static_cast<UINT>(rowBytes), static_cast<UINT>(numBytes)); + } + + d3dContext->GenerateMips(*textureView); + + if (texture) + { + *texture = tex; + } + else + { + tex->Release(); + } + } + } + else + { + // Create the texture + std::unique_ptr<D3D11_SUBRESOURCE_DATA[]> initData(new (std::nothrow) D3D11_SUBRESOURCE_DATA[mipCount * arraySize]); + if (!initData) + { + return E_OUTOFMEMORY; + } + + size_t skipMip = 0; + size_t twidth = 0; + size_t theight = 0; + size_t tdepth = 0; + hr = FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, + twidth, theight, tdepth, skipMip, initData.get()); + + if (SUCCEEDED(hr)) + { + hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, + format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, + isCubeMap, initData.get(), texture, textureView); + + if (FAILED(hr) && !maxsize && (mipCount > 1)) + { + // Retry with a maxsize determined by feature level + switch (d3dDevice->GetFeatureLevel()) + { + case D3D_FEATURE_LEVEL_9_1: + case D3D_FEATURE_LEVEL_9_2: + if (isCubeMap) + { + maxsize = 512 /*D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION*/; + } + else + { + maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) + ? 256 /*D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ + : 2048 /*D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + } + break; + + case D3D_FEATURE_LEVEL_9_3: + maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) + ? 256 /*D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ + : 4096 /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + break; + + default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1 + maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) + ? 2048 /*D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ + : 8192 /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + break; + } + + hr = FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, + twidth, theight, tdepth, skipMip, initData.get()); + if (SUCCEEDED(hr)) + { + hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, + format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, + isCubeMap, initData.get(), texture, textureView); + } + } + } + } + + return hr; + } + + + //-------------------------------------------------------------------------------------- + DDS_ALPHA_MODE GetAlphaMode(_In_ const DDS_HEADER* header) + { + if (header->ddspf.flags & DDS_FOURCC) + { + if (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC) + { + auto d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>((const char*)header + sizeof(DDS_HEADER)); + auto mode = static_cast<DDS_ALPHA_MODE>(d3d10ext->miscFlags2 & DDS_MISC_FLAGS2_ALPHA_MODE_MASK); + switch (mode) + { + case DDS_ALPHA_MODE_STRAIGHT: + case DDS_ALPHA_MODE_PREMULTIPLIED: + case DDS_ALPHA_MODE_OPAQUE: + case DDS_ALPHA_MODE_CUSTOM: + return mode; + } + } + else if ((MAKEFOURCC('D', 'X', 'T', '2') == header->ddspf.fourCC) + || (MAKEFOURCC('D', 'X', 'T', '4') == header->ddspf.fourCC)) + { + return DDS_ALPHA_MODE_PREMULTIPLIED; + } + } + + return DDS_ALPHA_MODE_UNKNOWN; + } +} // anonymous namespace + +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT DirectX::CreateDDSTextureFromMemory(ID3D11Device* d3dDevice, + const uint8_t* ddsData, + size_t ddsDataSize, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize, + DDS_ALPHA_MODE* alphaMode) +{ + return CreateDDSTextureFromMemoryEx(d3dDevice, nullptr, ddsData, ddsDataSize, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, + texture, textureView, alphaMode); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateDDSTextureFromMemory(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const uint8_t* ddsData, + size_t ddsDataSize, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize, + DDS_ALPHA_MODE* alphaMode) +{ + return CreateDDSTextureFromMemoryEx(d3dDevice, d3dContext, ddsData, ddsDataSize, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, + texture, textureView, alphaMode); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateDDSTextureFromMemoryEx(ID3D11Device* d3dDevice, + const uint8_t* ddsData, + size_t ddsDataSize, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + bool forceSRGB, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + DDS_ALPHA_MODE* alphaMode) +{ + return CreateDDSTextureFromMemoryEx(d3dDevice, nullptr, ddsData, ddsDataSize, maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, + texture, textureView, alphaMode); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateDDSTextureFromMemoryEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const uint8_t* ddsData, + size_t ddsDataSize, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + bool forceSRGB, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + DDS_ALPHA_MODE* alphaMode) +{ + if (texture) + { + *texture = nullptr; + } + if (textureView) + { + *textureView = nullptr; + } + if (alphaMode) + { + *alphaMode = DDS_ALPHA_MODE_UNKNOWN; + } + + if (!d3dDevice || !ddsData || (!texture && !textureView)) + { + return E_INVALIDARG; + } + + // Validate DDS file in memory + if (ddsDataSize < (sizeof(uint32_t) + sizeof(DDS_HEADER))) + { + return E_FAIL; + } + + uint32_t dwMagicNumber = *(const uint32_t*)(ddsData); + if (dwMagicNumber != DDS_MAGIC) + { + return E_FAIL; + } + + auto header = reinterpret_cast<const DDS_HEADER*>(ddsData + sizeof(uint32_t)); + + // Verify header to validate DDS file + if (header->size != sizeof(DDS_HEADER) || + header->ddspf.size != sizeof(DDS_PIXELFORMAT)) + { + return E_FAIL; + } + + // Check for DX10 extension + bool bDXT10Header = false; + if ((header->ddspf.flags & DDS_FOURCC) && + (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) + { + // Must be long enough for both headers and magic value + if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_DXT10))) + { + return E_FAIL; + } + + bDXT10Header = true; + } + + ptrdiff_t offset = sizeof(uint32_t) + + sizeof(DDS_HEADER) + + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0); + + HRESULT hr = CreateTextureFromDDS(d3dDevice, d3dContext, header, + ddsData + offset, ddsDataSize - offset, maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, + texture, textureView); + if (SUCCEEDED(hr)) + { + if (texture != 0 && *texture != 0) + { + SetDebugObjectName(*texture, "DDSTextureLoader"); + } + + if (textureView != 0 && *textureView != 0) + { + SetDebugObjectName(*textureView, "DDSTextureLoader"); + } + + if (alphaMode) + *alphaMode = GetAlphaMode(header); + } + + return hr; +} + +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT DirectX::CreateDDSTextureFromFile(ID3D11Device* d3dDevice, + const wchar_t* fileName, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize, + DDS_ALPHA_MODE* alphaMode) +{ + return CreateDDSTextureFromFileEx(d3dDevice, nullptr, fileName, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, + texture, textureView, alphaMode); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateDDSTextureFromFile(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const wchar_t* fileName, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize, + DDS_ALPHA_MODE* alphaMode) +{ + return CreateDDSTextureFromFileEx(d3dDevice, d3dContext, fileName, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, + texture, textureView, alphaMode); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateDDSTextureFromFileEx(ID3D11Device* d3dDevice, + const wchar_t* fileName, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + bool forceSRGB, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + DDS_ALPHA_MODE* alphaMode) +{ + return CreateDDSTextureFromFileEx(d3dDevice, nullptr, fileName, maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, + texture, textureView, alphaMode); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateDDSTextureFromFileEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const wchar_t* fileName, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + bool forceSRGB, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + DDS_ALPHA_MODE* alphaMode) +{ + if (texture) + { + *texture = nullptr; + } + if (textureView) + { + *textureView = nullptr; + } + if (alphaMode) + { + *alphaMode = DDS_ALPHA_MODE_UNKNOWN; + } + + if (!d3dDevice || !fileName || (!texture && !textureView)) + { + return E_INVALIDARG; + } + + const DDS_HEADER* header = nullptr; + const uint8_t* bitData = nullptr; + size_t bitSize = 0; + + std::unique_ptr<uint8_t[]> ddsData; + HRESULT hr = LoadTextureDataFromFile(fileName, + ddsData, + &header, + &bitData, + &bitSize + ); + if (FAILED(hr)) + { + return hr; + } + + hr = CreateTextureFromDDS(d3dDevice, d3dContext, header, + bitData, bitSize, maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, + texture, textureView); + + if (SUCCEEDED(hr)) + { +#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) + if (texture != 0 || textureView != 0) + { + CHAR strFileA[MAX_PATH]; + int result = WideCharToMultiByte(CP_ACP, + WC_NO_BEST_FIT_CHARS, + fileName, + -1, + strFileA, + MAX_PATH, + nullptr, + FALSE + ); + if (result > 0) + { + const CHAR* pstrName = strrchr(strFileA, '\\'); + if (!pstrName) + { + pstrName = strFileA; + } + else + { + pstrName++; + } + + if (texture != 0 && *texture != 0) + { + (*texture)->SetPrivateData(WKPDID_D3DDebugObjectName, + static_cast<UINT>(strnlen_s(pstrName, MAX_PATH)), + pstrName + ); + } + + if (textureView != 0 && *textureView != 0) + { + (*textureView)->SetPrivateData(WKPDID_D3DDebugObjectName, + static_cast<UINT>(strnlen_s(pstrName, MAX_PATH)), + pstrName + ); + } + } + } +#endif + + if (alphaMode) + *alphaMode = GetAlphaMode(header); + } + + return hr; +} diff --git a/samples/DX_APIUsage/DXUT/Core/DDSTextureLoader.h b/samples/DX_APIUsage/DXUT/Core/DDSTextureLoader.h new file mode 100644 index 0000000..0b5cb19 --- /dev/null +++ b/samples/DX_APIUsage/DXUT/Core/DDSTextureLoader.h @@ -0,0 +1,129 @@ +//-------------------------------------------------------------------------------------- +// File: DDSTextureLoader.h +// +// Functions for loading a DDS texture and creating a Direct3D runtime resource for it +// +// Note these functions are useful as a light-weight runtime loader for DDS files. For +// a full-featured DDS file reader, writer, and texture processing pipeline see +// the 'Texconv' sample and the 'DirectXTex' library. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=248926 +// http://go.microsoft.com/fwlink/?LinkId=248929 +//-------------------------------------------------------------------------------------- + +#pragma once + +#include <d3d11_1.h> +#include <stdint.h> + + +namespace DirectX +{ + enum DDS_ALPHA_MODE + { + DDS_ALPHA_MODE_UNKNOWN = 0, + DDS_ALPHA_MODE_STRAIGHT = 1, + DDS_ALPHA_MODE_PREMULTIPLIED = 2, + DDS_ALPHA_MODE_OPAQUE = 3, + DDS_ALPHA_MODE_CUSTOM = 4, + }; + + // Standard version + HRESULT CreateDDSTextureFromMemory( + _In_ ID3D11Device* d3dDevice, + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + _In_ size_t ddsDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); + + HRESULT CreateDDSTextureFromFile( + _In_ ID3D11Device* d3dDevice, + _In_z_ const wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); + + // Standard version with optional auto-gen mipmap support + HRESULT CreateDDSTextureFromMemory( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + _In_ size_t ddsDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); + + HRESULT CreateDDSTextureFromFile( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _In_z_ const wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); + + // Extended version + HRESULT CreateDDSTextureFromMemoryEx( + _In_ ID3D11Device* d3dDevice, + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + _In_ size_t ddsDataSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ bool forceSRGB, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); + + HRESULT CreateDDSTextureFromFileEx( + _In_ ID3D11Device* d3dDevice, + _In_z_ const wchar_t* szFileName, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ bool forceSRGB, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); + + // Extended version with optional auto-gen mipmap support + HRESULT CreateDDSTextureFromMemoryEx( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, + _In_ size_t ddsDataSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ bool forceSRGB, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); + + HRESULT CreateDDSTextureFromFileEx( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _In_z_ const wchar_t* szFileName, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ bool forceSRGB, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); +}
\ No newline at end of file diff --git a/samples/DX_APIUsage/DXUT/Core/DXUT.cpp b/samples/DX_APIUsage/DXUT/Core/DXUT.cpp index 03ff1e8..3a0e913 100644 --- a/samples/DX_APIUsage/DXUT/Core/DXUT.cpp +++ b/samples/DX_APIUsage/DXUT/Core/DXUT.cpp @@ -2,22 +2,20 @@ // File: DXUT.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" + +#ifndef NDEBUG +#include <dxgidebug.h> +#endif + #define DXUT_MIN_WINDOW_SIZE_X 200 #define DXUT_MIN_WINDOW_SIZE_Y 200 #define DXUT_COUNTER_STAT_LENGTH 2048 -#undef min // use __min instead inside this source file -#undef max // use __max instead inside this source file -#ifndef ARRAYSIZE -extern "C++" // templates cannot be declared to have 'C' linkage -template <typename T, size_t N> -char (*RtlpNumberOf( UNALIGNED T (&)[N] ))[N]; - -#define RTL_NUMBER_OF_V2(A) (sizeof(*RtlpNumberOf(A))) -#define ARRAYSIZE(A) RTL_NUMBER_OF_V2(A) -#endif //-------------------------------------------------------------------------------------- // Thread safety @@ -32,8 +30,10 @@ bool g_bThreadSafe = true; class DXUTLock { public: - inline DXUTLock() { if( g_bThreadSafe ) EnterCriticalSection( &g_cs ); } - inline ~DXUTLock() { if( g_bThreadSafe ) LeaveCriticalSection( &g_cs ); } +#pragma prefast( suppress:26166, "g_bThreadSafe controls behavior" ) + inline _Acquires_lock_(g_cs) DXUTLock() { if( g_bThreadSafe ) EnterCriticalSection( &g_cs ); } +#pragma prefast( suppress:26165, "g_bThreadSafe controls behavior" ) + inline _Releases_lock_(g_cs) ~DXUTLock() { if( g_bThreadSafe ) LeaveCriticalSection( &g_cs ); } }; //-------------------------------------------------------------------------------------- @@ -62,7 +62,6 @@ struct DXUT_TIMER }; - //-------------------------------------------------------------------------------------- // Stores DXUT state and data access is done with thread safety (if g_bThreadSafe==true) //-------------------------------------------------------------------------------------- @@ -71,16 +70,9 @@ class DXUTState protected: struct STATE { - // D3D9 specific - IDirect3D9* m_D3D9; // the main D3D9 object - IDirect3DDevice9* m_D3D9Device; // the D3D9 rendering device DXUTDeviceSettings* m_CurrentDeviceSettings; // current device settings - D3DSURFACE_DESC m_BackBufferSurfaceDesc9; // D3D9 back buffer surface description - D3DCAPS9 m_Caps; // D3D caps for current device - - // D3D11 specific - IDXGIFactory1* m_DXGIFactory; // DXGI Factory object - IDXGIAdapter1* m_DXGIAdapter; // The DXGI adapter object for the D3D11 device + IDXGIFactory1* m_DXGIFactory; // DXGI Factory object + IDXGIAdapter1* m_DXGIAdapter; // The DXGI adapter object for the D3D11 device IDXGIOutput** m_DXGIOutputArray; // The array of output obj for the D3D11 adapter obj UINT m_DXGIOutputArraySize; // Number of elements in m_D3D11OutputArray IDXGISwapChain* m_DXGISwapChain; // the D3D11 swapchain @@ -89,20 +81,41 @@ protected: bool m_DoNotStoreBufferSize; // Do not store the buffer size on WM_SIZE messages // D3D11 specific - bool m_D3D11Available; // if true, then D3D11 is available - ID3D11Device* m_D3D11Device; // the D3D11 rendering device + ID3D11Device* m_D3D11Device; // the D3D11 rendering device ID3D11DeviceContext* m_D3D11DeviceContext; // the D3D11 immediate device context - D3D_FEATURE_LEVEL m_D3D11FeatureLevel; // the D3D11 feature level that this device supports + D3D_FEATURE_LEVEL m_D3D11FeatureLevel; // the D3D11 feature level that this device supports ID3D11Texture2D* m_D3D11DepthStencil; // the D3D11 depth stencil texture (optional) ID3D11DepthStencilView* m_D3D11DepthStencilView; // the D3D11 depth stencil view (optional) ID3D11RenderTargetView* m_D3D11RenderTargetView; // the D3D11 render target view ID3D11RasterizerState* m_D3D11RasterizerState; // the D3D11 Rasterizer state + // D3D11.1 specific + ID3D11Device1* m_D3D11Device1; // the D3D11.1 rendering device + ID3D11DeviceContext1* m_D3D11DeviceContext1; // the D3D11.1 immediate device context + +#ifdef USE_DIRECT3D11_2 + // D3D11.2 specific + ID3D11Device2* m_D3D11Device2; // the D3D11.2 rendering device + ID3D11DeviceContext2* m_D3D11DeviceContext2; // the D3D11.2 immediate device context +#endif + +#ifdef USE_DIRECT3D11_3 + // D3D11.3 specific + ID3D11Device3* m_D3D11Device3; // the D3D11.3 rendering device + ID3D11DeviceContext3* m_D3D11DeviceContext3; // the D3D11.3 immediate device context +#endif + +#ifdef USE_DIRECT3D11_4 + // D3D11.4 specific + ID3D11Device4* m_D3D11Device4; // the D3D11.4 rendering device + ID3D11DeviceContext4* m_D3D11DeviceContext4; // the D3D11.4 immediate device context +#endif + // General HWND m_HWNDFocus; // the main app focus window HWND m_HWNDDeviceFullScreen; // the main app device window in fullscreen mode HWND m_HWNDDeviceWindowed; // the main app device window in windowed mode - HMONITOR m_AdapterMonitor; // the monitor of the adapter + HMONITOR m_AdapterMonitor; // the monitor of the adapter HMENU m_Menu; // handle to menu UINT m_FullScreenBackBufferWidthAtModeChange; // back buffer size of fullscreen mode right before switching to windowed mode. Used to restore to same resolution when toggling back to fullscreen @@ -111,7 +124,7 @@ protected: UINT m_WindowBackBufferHeightAtModeChange; // back buffer size of windowed mode right before switching to fullscreen mode. Used to restore to same resolution when toggling back to windowed mode DWORD m_WindowedStyleAtModeChange; // window style WINDOWPLACEMENT m_WindowedPlacement;// record of windowed HWND position/show state/etc - bool m_TopmostWhileWindowed; // if true, the windowed HWND is topmost + bool m_TopmostWhileWindowed; // if true, the windowed HWND is topmost bool m_Minimized; // if true, the HWND is minimized bool m_Maximized; // if true, the HWND is maximized bool m_MinimizedWhileFullscreen; // if true, the HWND is minimized due to a focus switch away when fullscreen mode @@ -127,18 +140,14 @@ protected: float m_FPS; // frames per second int m_CurrentFrameNumber; // the current frame number HHOOK m_KeyboardHook; // handle to keyboard hook - bool m_AllowShortcutKeysWhenFullscreen; // if true, when fullscreen enable shortcut keys (Windows keys, StickyKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut) - bool m_AllowShortcutKeysWhenWindowed; // if true, when windowed enable shortcut keys (Windows keys, StickyKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut) + bool m_AllowShortcutKeysWhenFullscreen; // if true, when fullscreen enable shortcut keys (Windows keys, StickyKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut) + bool m_AllowShortcutKeysWhenWindowed; // if true, when windowed enable shortcut keys (Windows keys, StickyKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut) bool m_AllowShortcutKeys; // if true, then shortcut keys are currently disabled (Windows key, etc) bool m_CallDefWindowProc; // if true, DXUTStaticWndProc will call DefWindowProc for unhandled messages. Applications rendering to a dialog may need to set this to false. STICKYKEYS m_StartupStickyKeys; // StickyKey settings upon startup so they can be restored later TOGGLEKEYS m_StartupToggleKeys; // ToggleKey settings upon startup so they can be restored later FILTERKEYS m_StartupFilterKeys; // FilterKey settings upon startup so they can be restored later - bool m_AppSupportsD3D9Override; // true if app sets via DXUTSetD3DVersionSupport() - bool m_AppSupportsD3D11Override; // true if app sets via DXUTSetD3DVersionSupport() - bool m_UseD3DVersionOverride; // true if the app ever calls DXUTSetD3DVersionSupport() - bool m_HandleEscape; // if true, then DXUT will handle escape to quit bool m_HandleAltEnter; // if true, then DXUT will handle alt-enter to toggle fullscreen bool m_HandlePause; // if true, then DXUT will handle pause to toggle time pausing @@ -148,18 +157,18 @@ protected: bool m_ShowCursorWhenFullScreen; // if true, then DXUT will show a cursor when full screen bool m_ConstantFrameTime; // if true, then elapsed frame time will always be 0.05f seconds which is good for debugging or automated capture float m_TimePerFrame; // the constant time per frame in seconds, only valid if m_ConstantFrameTime==true - bool m_WireframeMode; // if true, then D3DRS_FILLMODE==D3DFILL_WIREFRAME else D3DRS_FILLMODE==D3DFILL_SOLID + bool m_WireframeMode; // if true, then D3DRS_FILLMODE==D3DFILL_WIREFRAME else D3DRS_FILLMODE==D3DFILL_SOLID bool m_AutoChangeAdapter; // if true, then the adapter will automatically change if the window is different monitor bool m_WindowCreatedWithDefaultPositions; // if true, then CW_USEDEFAULT was used and the window should be moved to the right adapter int m_ExitCode; // the exit code to be returned to the command line bool m_DXUTInited; // if true, then DXUTInit() has succeeded bool m_WindowCreated; // if true, then DXUTCreateWindow() or DXUTSetWindow() has succeeded - bool m_DeviceCreated; // if true, then DXUTCreateDevice() or DXUTSetD3D*Device() has succeeded + bool m_DeviceCreated; // if true, then DXUTCreateDevice() has succeeded bool m_DXUTInitCalled; // if true, then DXUTInit() was called bool m_WindowCreateCalled; // if true, then DXUTCreateWindow() or DXUTSetWindow() was called - bool m_DeviceCreateCalled; // if true, then DXUTCreateDevice() or DXUTSetD3D*Device() was called + bool m_DeviceCreateCalled; // if true, then DXUTCreateDevice() was called bool m_DeviceObjectsCreated; // if true, then DeviceCreated callback has been called (if non-NULL) bool m_DeviceObjectsReset; // if true, then DeviceReset callback has been called (if non-NULL) @@ -175,14 +184,13 @@ protected: bool m_Automation; // if true, automation is enabled bool m_InSizeMove; // if true, app is inside a WM_ENTERSIZEMOVE UINT m_TimerLastID; // last ID of the DXUT timer - bool m_MessageWhenD3D11NotAvailable; - + bool m_MessageWhenD3D11NotAvailable; + D3D_FEATURE_LEVEL m_OverrideForceFeatureLevel; // if != -1, then overrid to use a featurelevel WCHAR m_ScreenShotName[256]; // command line screen shot name bool m_SaveScreenShot; // command line save screen shot bool m_ExitAfterScreenShot; // command line exit after screen shot - - int m_OverrideForceAPI; // if != -1, then override to use this Direct3D API version + int m_OverrideAdapterOrdinal; // if != -1, then override to use this adapter ordinal bool m_OverrideWindowed; // if true, then force to start windowed int m_OverrideOutput; // if != -1, then override to use the particular output on the adapter @@ -193,14 +201,14 @@ protected: int m_OverrideHeight; // if != 0, then override to this height bool m_OverrideForceHAL; // if true, then force to HAL device (failing if one doesn't exist) bool m_OverrideForceREF; // if true, then force to REF device (failing if one doesn't exist) + bool m_OverrideForceWARP; // if true, then force to WARP device (failing if one doesn't exist) bool m_OverrideConstantFrameTime; // if true, then force to constant frame time float m_OverrideConstantTimePerFrame; // the constant time per frame in seconds if m_OverrideConstantFrameTime==true int m_OverrideQuitAfterFrame; // if != 0, then it will force the app to quit after that frame int m_OverrideForceVsync; // if == 0, then it will force the app to use D3DPRESENT_INTERVAL_IMMEDIATE, if == 1 force use of D3DPRESENT_INTERVAL_DEFAULT - bool m_OverrideRelaunchMCE; // if true, then force relaunch of MCE at exit bool m_AppCalledWasKeyPressed; // true if the app ever calls DXUTWasKeyPressed(). Allows for optimzation - bool m_ReleasingSwapChain; // if true, the app is releasing its swapchain - bool m_IsInGammaCorrectMode; // Tell DXUTRes and DXUTMisc that we are in gamma correct mode + bool m_ReleasingSwapChain; // if true, the app is releasing its swapchain + bool m_IsInGammaCorrectMode; // Tell DXUTRes and DXUTMisc that we are in gamma correct mode LPDXUTCALLBACKMODIFYDEVICESETTINGS m_ModifyDeviceSettingsFunc; // modify Direct3D device settings callback LPDXUTCALLBACKDEVICEREMOVED m_DeviceRemovedFunc; // Direct3D device removed callback @@ -208,13 +216,7 @@ protected: LPDXUTCALLBACKKEYBOARD m_KeyboardFunc; // keyboard callback LPDXUTCALLBACKMOUSE m_MouseFunc; // mouse callback LPDXUTCALLBACKMSGPROC m_WindowMsgFunc; // window messages callback - - LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE m_IsD3D9DeviceAcceptableFunc; // D3D9 is device acceptable callback - LPDXUTCALLBACKD3D9DEVICECREATED m_D3D9DeviceCreatedFunc; // D3D9 device created callback - LPDXUTCALLBACKD3D9DEVICERESET m_D3D9DeviceResetFunc; // D3D9 device reset callback - LPDXUTCALLBACKD3D9DEVICELOST m_D3D9DeviceLostFunc; // D3D9 device lost callback - LPDXUTCALLBACKD3D9DEVICEDESTROYED m_D3D9DeviceDestroyedFunc; // D3D9 device destroyed callback - LPDXUTCALLBACKD3D9FRAMERENDER m_D3D9FrameRenderFunc; // D3D9 frame render callback + LPDXUTCALLBACKQUIT m_QuitFunc; // quit callback LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE m_IsD3D11DeviceAcceptableFunc; // D3D11 is device acceptable callback LPDXUTCALLBACKD3D11DEVICECREATED m_D3D11DeviceCreatedFunc; // D3D11 device created callback @@ -223,20 +225,13 @@ protected: LPDXUTCALLBACKD3D11DEVICEDESTROYED m_D3D11DeviceDestroyedFunc; // D3D11 device destroyed callback LPDXUTCALLBACKD3D11FRAMERENDER m_D3D11FrameRenderFunc; // D3D11 frame render callback - void* m_ModifyDeviceSettingsFuncUserContext; // user context for modify Direct3D device settings callback void* m_DeviceRemovedFuncUserContext; // user context for Direct3D device removed callback void* m_FrameMoveFuncUserContext; // user context for frame move callback void* m_KeyboardFuncUserContext; // user context for keyboard callback void* m_MouseFuncUserContext; // user context for mouse callback void* m_WindowMsgFuncUserContext; // user context for window messages callback - - void* m_IsD3D9DeviceAcceptableFuncUserContext; // user context for is D3D9 device acceptable callback - void* m_D3D9DeviceCreatedFuncUserContext; // user context for D3D9 device created callback - void* m_D3D9DeviceResetFuncUserContext; // user context for D3D9 device reset callback - void* m_D3D9DeviceLostFuncUserContext; // user context for D3D9 device lost callback - void* m_D3D9DeviceDestroyedFuncUserContext; // user context for D3D9 device destroyed callback - void* m_D3D9FrameRenderFuncUserContext; // user context for D3D9 frame render callback + void* m_QuitFuncUserContext; // user context for quit callback void* m_IsD3D11DeviceAcceptableFuncUserContext; // user context for is D3D11 device acceptable callback void* m_D3D11DeviceCreatedFuncUserContext; // user context for D3D11 device created callback @@ -249,8 +244,8 @@ protected: bool m_LastKeys[256]; // array of last key state bool m_MouseButtons[5]; // array of mouse states - CGrowableArray<DXUT_TIMER>* m_TimerList; // list of DXUT_TIMER structs - WCHAR m_StaticFrameStats[256]; // static part of frames stats + std::vector<DXUT_TIMER>* m_TimerList; // list of DXUT_TIMER structs + WCHAR m_StaticFrameStats[256]; // static part of frames stats WCHAR m_FPSStats[64]; // fps stats WCHAR m_FrameStats[256]; // frame stats (fps, width, etc) WCHAR m_DeviceStats[256]; // device stats (description, device type, etc) @@ -263,10 +258,10 @@ public: DXUTState() { Create(); } ~DXUTState() { Destroy(); } - void Create() + void Create() { g_bThreadSafe = true; - InitializeCriticalSectionAndSpinCount( &g_cs, 1000 ); + (void)InitializeCriticalSectionAndSpinCount( &g_cs, 1000 ); ZeroMemory( &m_state, sizeof( STATE ) ); m_state.m_OverrideStartX = -1; @@ -275,7 +270,6 @@ public: m_state.m_ScreenShotName[0] = 0; m_state.m_SaveScreenShot = false; m_state.m_ExitAfterScreenShot = false; - m_state.m_OverrideForceAPI = -1; m_state.m_OverrideAdapterOrdinal = -1; m_state.m_OverrideOutput = -1; m_state.m_OverrideForceVsync = -1; @@ -288,7 +282,7 @@ public: m_state.m_HandleAltEnter = true; m_state.m_HandlePause = true; m_state.m_IsInGammaCorrectMode = true; - m_state.m_FPS = 1.0f; + m_state.m_FPS = 1.0f; m_state.m_MessageWhenD3D11NotAvailable = true; } @@ -299,15 +293,9 @@ public: DeleteCriticalSection( &g_cs ); } - // Macros to define access functions for thread safe access into m_state + // Macros to define access functions for thread safe access into m_state GET_SET_ACCESSOR( DXUTDeviceSettings*, CurrentDeviceSettings ); - // D3D9 specific - GET_SET_ACCESSOR( IDirect3D9*, D3D9 ); - GET_SET_ACCESSOR( IDirect3DDevice9*, D3D9Device ); - GETP_SETP_ACCESSOR( D3DSURFACE_DESC, BackBufferSurfaceDesc9 ); - GETP_SETP_ACCESSOR( D3DCAPS9, Caps ); - // D3D11 specific GET_SET_ACCESSOR( IDXGIFactory1*, DXGIFactory ); GET_SET_ACCESSOR( IDXGIAdapter1*, DXGIAdapter ); @@ -318,23 +306,37 @@ public: GET_SET_ACCESSOR( bool, RenderingOccluded ); GET_SET_ACCESSOR( bool, DoNotStoreBufferSize ); - // D3D11 specific - GET_SET_ACCESSOR( bool, D3D11Available ); GET_SET_ACCESSOR( ID3D11Device*, D3D11Device ); GET_SET_ACCESSOR( ID3D11DeviceContext*, D3D11DeviceContext ); GET_SET_ACCESSOR( D3D_FEATURE_LEVEL, D3D11FeatureLevel ); GET_SET_ACCESSOR( ID3D11Texture2D*, D3D11DepthStencil ); - GET_SET_ACCESSOR( ID3D11DepthStencilView*, D3D11DepthStencilView ); + GET_SET_ACCESSOR( ID3D11DepthStencilView*, D3D11DepthStencilView ); GET_SET_ACCESSOR( ID3D11RenderTargetView*, D3D11RenderTargetView ); GET_SET_ACCESSOR( ID3D11RasterizerState*, D3D11RasterizerState ); + GET_SET_ACCESSOR( ID3D11Device1*, D3D11Device1 ); + GET_SET_ACCESSOR( ID3D11DeviceContext1*, D3D11DeviceContext1 ); + +#ifdef USE_DIRECT3D11_2 + GET_SET_ACCESSOR(ID3D11Device2*, D3D11Device2); + GET_SET_ACCESSOR(ID3D11DeviceContext2*, D3D11DeviceContext2); +#endif + +#ifdef USE_DIRECT3D11_3 + GET_SET_ACCESSOR(ID3D11Device3*, D3D11Device3); + GET_SET_ACCESSOR(ID3D11DeviceContext3*, D3D11DeviceContext3); +#endif + +#ifdef USE_DIRECT3D11_4 + GET_SET_ACCESSOR(ID3D11Device4*, D3D11Device4); + GET_SET_ACCESSOR(ID3D11DeviceContext4*, D3D11DeviceContext4); +#endif GET_SET_ACCESSOR( HWND, HWNDFocus ); GET_SET_ACCESSOR( HWND, HWNDDeviceFullScreen ); GET_SET_ACCESSOR( HWND, HWNDDeviceWindowed ); GET_SET_ACCESSOR( HMONITOR, AdapterMonitor ); - GET_SET_ACCESSOR( HMENU, Menu ); - + GET_SET_ACCESSOR( HMENU, Menu ); GET_SET_ACCESSOR( UINT, FullScreenBackBufferWidthAtModeChange ); GET_SET_ACCESSOR( UINT, FullScreenBackBufferHeightAtModeChange ); @@ -346,16 +348,16 @@ public: GET_SET_ACCESSOR( bool, Minimized ); GET_SET_ACCESSOR( bool, Maximized ); GET_SET_ACCESSOR( bool, MinimizedWhileFullscreen ); - GET_SET_ACCESSOR( bool, IgnoreSizeChange ); + GET_SET_ACCESSOR( bool, IgnoreSizeChange ); GET_SET_ACCESSOR( double, Time ); GET_SET_ACCESSOR( double, AbsoluteTime ); GET_SET_ACCESSOR( float, ElapsedTime ); GET_SET_ACCESSOR( HINSTANCE, HInstance ); - GET_SET_ACCESSOR( double, LastStatsUpdateTime ); - GET_SET_ACCESSOR( DWORD, LastStatsUpdateFrames ); - GET_SET_ACCESSOR( float, FPS ); + GET_SET_ACCESSOR( double, LastStatsUpdateTime ); + GET_SET_ACCESSOR( DWORD, LastStatsUpdateFrames ); + GET_SET_ACCESSOR( float, FPS ); GET_SET_ACCESSOR( int, CurrentFrameNumber ); GET_SET_ACCESSOR( HHOOK, KeyboardHook ); GET_SET_ACCESSOR( bool, AllowShortcutKeysWhenFullscreen ); @@ -366,20 +368,16 @@ public: GET_SET_ACCESSOR( TOGGLEKEYS, StartupToggleKeys ); GET_SET_ACCESSOR( FILTERKEYS, StartupFilterKeys ); - GET_SET_ACCESSOR( bool, AppSupportsD3D9Override ); - GET_SET_ACCESSOR( bool, AppSupportsD3D11Override ); - GET_SET_ACCESSOR( bool, UseD3DVersionOverride ); - GET_SET_ACCESSOR( bool, HandleEscape ); GET_SET_ACCESSOR( bool, HandleAltEnter ); GET_SET_ACCESSOR( bool, HandlePause ); GET_SET_ACCESSOR( bool, ShowMsgBoxOnError ); GET_SET_ACCESSOR( bool, NoStats ); - GET_SET_ACCESSOR( bool, ClipCursorWhenFullScreen ); + GET_SET_ACCESSOR( bool, ClipCursorWhenFullScreen ); GET_SET_ACCESSOR( bool, ShowCursorWhenFullScreen ); GET_SET_ACCESSOR( bool, ConstantFrameTime ); GET_SET_ACCESSOR( float, TimePerFrame ); - GET_SET_ACCESSOR( bool, WireframeMode ); + GET_SET_ACCESSOR( bool, WireframeMode ); GET_SET_ACCESSOR( bool, AutoChangeAdapter ); GET_SET_ACCESSOR( bool, WindowCreatedWithDefaultPositions ); GET_SET_ACCESSOR( int, ExitCode ); @@ -412,8 +410,6 @@ public: GET_SET_ACCESSOR( bool, SaveScreenShot ); GET_SET_ACCESSOR( bool, ExitAfterScreenShot ); - - GET_SET_ACCESSOR( int, OverrideForceAPI ); GET_SET_ACCESSOR( int, OverrideAdapterOrdinal ); GET_SET_ACCESSOR( bool, OverrideWindowed ); GET_SET_ACCESSOR( int, OverrideOutput ); @@ -424,27 +420,21 @@ public: GET_SET_ACCESSOR( int, OverrideHeight ); GET_SET_ACCESSOR( bool, OverrideForceHAL ); GET_SET_ACCESSOR( bool, OverrideForceREF ); + GET_SET_ACCESSOR( bool, OverrideForceWARP ); GET_SET_ACCESSOR( bool, OverrideConstantFrameTime ); GET_SET_ACCESSOR( float, OverrideConstantTimePerFrame ); GET_SET_ACCESSOR( int, OverrideQuitAfterFrame ); GET_SET_ACCESSOR( int, OverrideForceVsync ); - GET_SET_ACCESSOR( bool, OverrideRelaunchMCE ); GET_SET_ACCESSOR( bool, ReleasingSwapChain ); GET_SET_ACCESSOR( bool, IsInGammaCorrectMode ); - + GET_SET_ACCESSOR( LPDXUTCALLBACKMODIFYDEVICESETTINGS, ModifyDeviceSettingsFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKDEVICEREMOVED, DeviceRemovedFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKFRAMEMOVE, FrameMoveFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKKEYBOARD, KeyboardFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKMOUSE, MouseFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKMSGPROC, WindowMsgFunc ); - - GET_SET_ACCESSOR( LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE, IsD3D9DeviceAcceptableFunc ); - GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9DEVICECREATED, D3D9DeviceCreatedFunc ); - GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9DEVICERESET, D3D9DeviceResetFunc ); - GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9DEVICELOST, D3D9DeviceLostFunc ); - GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9DEVICEDESTROYED, D3D9DeviceDestroyedFunc ); - GET_SET_ACCESSOR( LPDXUTCALLBACKD3D9FRAMERENDER, D3D9FrameRenderFunc ); + GET_SET_ACCESSOR( LPDXUTCALLBACKQUIT, QuitFunc); GET_SET_ACCESSOR( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE, IsD3D11DeviceAcceptableFunc ); GET_SET_ACCESSOR( LPDXUTCALLBACKD3D11DEVICECREATED, D3D11DeviceCreatedFunc ); @@ -459,13 +449,7 @@ public: GET_SET_ACCESSOR( void*, KeyboardFuncUserContext ); GET_SET_ACCESSOR( void*, MouseFuncUserContext ); GET_SET_ACCESSOR( void*, WindowMsgFuncUserContext ); - - GET_SET_ACCESSOR( void*, IsD3D9DeviceAcceptableFuncUserContext ); - GET_SET_ACCESSOR( void*, D3D9DeviceCreatedFuncUserContext ); - GET_SET_ACCESSOR( void*, D3D9DeviceResetFuncUserContext ); - GET_SET_ACCESSOR( void*, D3D9DeviceLostFuncUserContext ); - GET_SET_ACCESSOR( void*, D3D9DeviceDestroyedFuncUserContext ); - GET_SET_ACCESSOR( void*, D3D9FrameRenderFuncUserContext ); + GET_SET_ACCESSOR( void*, QuitFuncUserContext ); GET_SET_ACCESSOR( void*, IsD3D11DeviceAcceptableFuncUserContext ); GET_SET_ACCESSOR( void*, D3D11DeviceCreatedFuncUserContext ); @@ -474,29 +458,29 @@ public: GET_SET_ACCESSOR( void*, D3D11SwapChainReleasingFuncUserContext ); GET_SET_ACCESSOR( void*, D3D11FrameRenderFuncUserContext ); - GET_SET_ACCESSOR( CGrowableArray<DXUT_TIMER>*, TimerList ); + GET_SET_ACCESSOR( std::vector<DXUT_TIMER>*, TimerList ); GET_ACCESSOR( bool*, Keys ); GET_ACCESSOR( bool*, LastKeys ); GET_ACCESSOR( bool*, MouseButtons ); GET_ACCESSOR( WCHAR*, StaticFrameStats ); GET_ACCESSOR( WCHAR*, FPSStats ); GET_ACCESSOR( WCHAR*, FrameStats ); - GET_ACCESSOR( WCHAR*, DeviceStats ); + GET_ACCESSOR( WCHAR*, DeviceStats ); GET_ACCESSOR( WCHAR*, WindowTitle ); }; //-------------------------------------------------------------------------------------- -// Global state +// Global state //-------------------------------------------------------------------------------------- -DXUTState* g_pDXUTState = NULL; +DXUTState* g_pDXUTState = nullptr; HRESULT WINAPI DXUTCreateState() { - if( g_pDXUTState == NULL ) + if( !g_pDXUTState ) { - g_pDXUTState = new DXUTState; - if( NULL == g_pDXUTState ) + g_pDXUTState = new (std::nothrow) DXUTState; + if( !g_pDXUTState ) return E_OUTOFMEMORY; } return S_OK; @@ -514,13 +498,13 @@ public: ~DXUTMemoryHelper() { DXUTDestroyState(); } }; - DXUTState& GetDXUTState() { // This class will auto create the memory when its first accessed and delete it after the program exits WinMain. - // However the application can also call DXUTCreateState() & DXUTDestroyState() independantly if its wants + // However the application can also call DXUTCreateState() & DXUTDestroyState() independantly if its wants static DXUTMemoryHelper memory; - assert( g_pDXUTState != NULL ); + assert( g_pDXUTState ); + _Analysis_assume_( g_pDXUTState ); return *g_pDXUTState; } @@ -528,117 +512,81 @@ DXUTState& GetDXUTState() //-------------------------------------------------------------------------------------- // Internal functions forward declarations //-------------------------------------------------------------------------------------- -void DXUTParseCommandLine( __inout WCHAR* strCommandLine, - bool bIgnoreFirstCommand = true ); -bool DXUTIsNextArg( __inout WCHAR*& strCmdLine, __in const WCHAR* strArg ); -bool DXUTGetCmdParam( __inout WCHAR*& strCmdLine, __out WCHAR* strFlag ); -void DXUTAllowShortcutKeys( bool bAllowKeys ); +void DXUTParseCommandLine( _In_z_ WCHAR* strCommandLine, + _In_ bool bIgnoreFirstCommand = true ); +bool DXUTIsNextArg( _Inout_ WCHAR*& strCmdLine, _In_ const WCHAR* strArg ); +bool DXUTGetCmdParam( _Inout_ WCHAR*& strCmdLine, _Out_cap_(cchDest) WCHAR* strFlag, _In_ int cchDest ); +void DXUTAllowShortcutKeys( _In_ bool bAllowKeys ); void DXUTUpdateStaticFrameStats(); void DXUTUpdateFrameStats(); -LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); +LRESULT CALLBACK DXUTStaticWndProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); void DXUTHandleTimers(); -void DXUTDisplayErrorMessage( HRESULT hr ); -int DXUTMapButtonToArrayIndex( BYTE vButton ); +void DXUTDisplayErrorMessage( _In_ HRESULT hr ); +int DXUTMapButtonToArrayIndex( _In_ BYTE vButton ); -HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, - IDirect3DDevice9* pd3d9DeviceFromApp, - ID3D11Device* pd3d11DeviceFromApp, - bool bForceRecreate, - bool bClipWindowToSingleAdapter ); +HRESULT DXUTChangeDevice( _In_ DXUTDeviceSettings* pNewDeviceSettings, + _In_ bool bClipWindowToSingleAdapter ); -bool DXUTCanDeviceBeReset( DXUTDeviceSettings* pOldDeviceSettings, - DXUTDeviceSettings* pNewDeviceSettings, - IDirect3DDevice9* pd3d9DeviceFromApp, - ID3D11Device* pd3d11DeviceFromApp ); +bool DXUTCanDeviceBeReset( _In_ DXUTDeviceSettings* pOldDeviceSettings, + _In_ DXUTDeviceSettings* pNewDeviceSettings, + _In_ ID3D11Device* pd3d11DeviceFromApp ); HRESULT DXUTDelayLoadDXGI(); -HRESULT DXUTDelayLoadD3D9(); -HRESULT DXUTSnapDeviceSettingsToEnumDevice( DXUTDeviceSettings* pDeviceSettings, bool forceEnum, D3D_FEATURE_LEVEL forceFL = D3D_FEATURE_LEVEL(0) ); -void DXUTUpdateDeviceSettingsWithOverrides( DXUTDeviceSettings* pDeviceSettings ); +HRESULT DXUTSnapDeviceSettingsToEnumDevice( _In_ DXUTDeviceSettings* pDeviceSettings, _In_ bool forceEnum, _In_ D3D_FEATURE_LEVEL forceFL = D3D_FEATURE_LEVEL(0) ); +void DXUTUpdateDeviceSettingsWithOverrides( _Inout_ DXUTDeviceSettings* pDeviceSettings ); void DXUTCheckForDXGIFullScreenSwitch(); -void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullscreen ); +void DXUTResizeDXGIBuffers( _In_ UINT Width, _In_ UINT Height, _In_ BOOL bFullscreen ); void DXUTCheckForDXGIBufferChange(); void DXUTCheckForWindowSizeChange(); void DXUTCheckForWindowChangingMonitors(); -void DXUTCleanup3DEnvironment( bool bReleaseSettings ); -HMONITOR DXUTGetMonitorFromAdapter( DXUTDeviceSettings* pDeviceSettings ); -HRESULT DXUTGetAdapterOrdinalFromMonitor( HMONITOR hMonitor, UINT* pAdapterOrdinal ); -HRESULT DXUTGetOutputOrdinalFromMonitor( HMONITOR hMonitor, UINT* pOutputOrdinal ); +void DXUTCleanup3DEnvironment( _In_ bool bReleaseSettings ); +HMONITOR DXUTGetMonitorFromAdapter( _In_ DXUTDeviceSettings* pDeviceSettings ); +HRESULT DXUTGetAdapterOrdinalFromMonitor( _In_ HMONITOR hMonitor, _Out_ UINT* pAdapterOrdinal ); +HRESULT DXUTGetOutputOrdinalFromMonitor( _In_ HMONITOR hMonitor, _Out_ UINT* pOutputOrdinal ); HRESULT DXUTHandleDeviceRemoved(); void DXUTUpdateBackBufferDesc(); void DXUTSetupCursor(); -// Direct3D 9 -HRESULT DXUTCreate3DEnvironment9( IDirect3DDevice9* pd3dDeviceFromApp ); -HRESULT DXUTReset3DEnvironment9(); -void DXUTRender3DEnvironment9(); -void DXUTCleanup3DEnvironment9( bool bReleaseSettings = true ); -HRESULT DXUTSetD3D9DeviceCursor( IDirect3DDevice9* pd3dDevice, HCURSOR hCursor, bool bAddWatermark ); -void DXUTUpdateD3D9DeviceStats( D3DDEVTYPE DeviceType, DWORD BehaviorFlags, - D3DADAPTER_IDENTIFIER9* pAdapterIdentifier ); -HRESULT DXUTFindD3D9AdapterFormat( UINT AdapterOrdinal, D3DDEVTYPE DeviceType, D3DFORMAT BackBufferFormat, - BOOL Windowed, D3DFORMAT* pAdapterFormat ); - // Direct3D 11 -HRESULT DXUTCreateD3D11Views( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dDeviceContext, DXUTDeviceSettings* pDeviceSettings ); -HRESULT DXUTCreate3DEnvironment11( ID3D11Device* pd3dDeviceFromApp ); +HRESULT DXUTCreateD3D11Views( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3dDeviceContext, _In_ DXUTDeviceSettings* pDeviceSettings ); +HRESULT DXUTCreate3DEnvironment11(); HRESULT DXUTReset3DEnvironment11(); -void DXUTRender3DEnvironment11(); -void DXUTCleanup3DEnvironment11( bool bReleaseSettings = true ); -void DXUTUpdateD3D11DeviceStats( D3D_DRIVER_TYPE DeviceType, DXGI_ADAPTER_DESC* pAdapterDesc ); +void DXUTUpdateD3D11DeviceStats( _In_ D3D_DRIVER_TYPE DeviceType, _In_ D3D_FEATURE_LEVEL featureLevel, _In_ DXGI_ADAPTER_DESC* pAdapterDesc ); //-------------------------------------------------------------------------------------- -// Internal helper functions +// Internal helper functions //-------------------------------------------------------------------------------------- -bool DXUTIsD3D9( DXUTDeviceSettings* pDeviceSettings ) { return (pDeviceSettings && pDeviceSettings->ver == DXUT_D3D9_DEVICE ); }; -bool DXUTIsCurrentDeviceD3D9() { DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); return DXUTIsD3D9(pDeviceSettings); }; -UINT DXUTGetBackBufferWidthFromDS( DXUTDeviceSettings* pNewDeviceSettings ) -{ - if( DXUTIsD3D9( pNewDeviceSettings ) ) - return pNewDeviceSettings->d3d9.pp.BackBufferWidth; - else - return pNewDeviceSettings->d3d11.sd.BufferDesc.Width; +UINT DXUTGetBackBufferWidthFromDS( _In_ DXUTDeviceSettings* pNewDeviceSettings ) +{ + return pNewDeviceSettings->d3d11.sd.BufferDesc.Width; } -UINT DXUTGetBackBufferHeightFromDS( DXUTDeviceSettings* pNewDeviceSettings ) -{ - if( DXUTIsD3D9(pNewDeviceSettings) ) - return pNewDeviceSettings->d3d9.pp.BackBufferHeight; - else - return pNewDeviceSettings->d3d11.sd.BufferDesc.Height; +UINT DXUTGetBackBufferHeightFromDS( _In_ DXUTDeviceSettings* pNewDeviceSettings ) +{ + return pNewDeviceSettings->d3d11.sd.BufferDesc.Height; } -bool DXUTGetIsWindowedFromDS( DXUTDeviceSettings* pNewDeviceSettings ) -{ - if (!pNewDeviceSettings) - return true; - - if( DXUTIsD3D9(pNewDeviceSettings) ) - return pNewDeviceSettings->d3d9.pp.Windowed ? true : false; - else - return pNewDeviceSettings->d3d11.sd.Windowed ? true : false; +bool DXUTGetIsWindowedFromDS( _In_ DXUTDeviceSettings* pNewDeviceSettings ) +{ + if (!pNewDeviceSettings) + return true; + + return pNewDeviceSettings->d3d11.sd.Windowed ? true : false; } //-------------------------------------------------------------------------------------- // External state access functions //-------------------------------------------------------------------------------------- -BOOL WINAPI DXUTGetMSAASwapChainCreated() { +bool WINAPI DXUTGetMSAASwapChainCreated() +{ DXUTDeviceSettings *psettings = GetDXUTState().GetCurrentDeviceSettings(); - if (psettings->ver == DXUT_D3D11_DEVICE) { - return psettings->d3d11.sd.SampleDesc.Count > 1; - }else if (psettings->ver == DXUT_D3D9_DEVICE) { - return (psettings->d3d9.pp.MultiSampleType >= D3DMULTISAMPLE_2_SAMPLES); - } - else return false; + if ( !psettings ) + return false; + return (psettings->d3d11.sd.SampleDesc.Count > 1); } -IDirect3DDevice9* WINAPI DXUTGetD3D9Device() { return GetDXUTState().GetD3D9Device(); } -const D3DSURFACE_DESC* WINAPI DXUTGetD3D9BackBufferSurfaceDesc() { return GetDXUTState().GetBackBufferSurfaceDesc9(); } -const D3DCAPS9* WINAPI DXUTGetD3D9DeviceCaps() { return GetDXUTState().GetCaps(); } -ID3D11Device* WINAPI DXUTGetD3D11Device() { return GetDXUTState().GetD3D11Device(); } -D3D_FEATURE_LEVEL WINAPI DXUTGetD3D11DeviceFeatureLevel() { return GetDXUTState().GetD3D11FeatureLevel(); } -ID3D11DeviceContext* WINAPI DXUTGetD3D11DeviceContext() { return GetDXUTState().GetD3D11DeviceContext(); } +D3D_FEATURE_LEVEL WINAPI DXUTGetD3D11DeviceFeatureLevel() { return GetDXUTState().GetD3D11FeatureLevel(); } IDXGISwapChain* WINAPI DXUTGetDXGISwapChain() { return GetDXUTState().GetDXGISwapChain(); } ID3D11RenderTargetView* WINAPI DXUTGetD3D11RenderTargetView() { return GetDXUTState().GetD3D11RenderTargetView(); } ID3D11DepthStencilView* WINAPI DXUTGetD3D11DepthStencilView() { return GetDXUTState().GetD3D11DepthStencilView(); } @@ -651,8 +599,8 @@ HWND WINAPI DXUTGetHWNDDeviceWindowed() { return GetDXUTState RECT WINAPI DXUTGetWindowClientRect() { RECT rc; GetClientRect( DXUTGetHWND(), &rc ); return rc; } LONG WINAPI DXUTGetWindowWidth() { RECT rc = DXUTGetWindowClientRect(); return ((LONG)rc.right - rc.left); } LONG WINAPI DXUTGetWindowHeight() { RECT rc = DXUTGetWindowClientRect(); return ((LONG)rc.bottom - rc.top); } -RECT WINAPI DXUTGetWindowClientRectAtModeChange() { RECT rc = { 0, 0, GetDXUTState().GetWindowBackBufferWidthAtModeChange(), GetDXUTState().GetWindowBackBufferHeightAtModeChange() }; return rc; } -RECT WINAPI DXUTGetFullsceenClientRectAtModeChange() { RECT rc = { 0, 0, GetDXUTState().GetFullScreenBackBufferWidthAtModeChange(), GetDXUTState().GetFullScreenBackBufferHeightAtModeChange() }; return rc; } +RECT WINAPI DXUTGetWindowClientRectAtModeChange() { RECT rc = { 0, 0, static_cast<LONG>( GetDXUTState().GetWindowBackBufferWidthAtModeChange() ), static_cast<LONG>( GetDXUTState().GetWindowBackBufferHeightAtModeChange() ) }; return rc; } +RECT WINAPI DXUTGetFullsceenClientRectAtModeChange() { RECT rc = { 0, 0, static_cast<LONG>( GetDXUTState().GetFullScreenBackBufferWidthAtModeChange() ), static_cast<LONG>( GetDXUTState().GetFullScreenBackBufferHeightAtModeChange() ) }; return rc; } double WINAPI DXUTGetTime() { return GetDXUTState().GetTime(); } float WINAPI DXUTGetElapsedTime() { return GetDXUTState().GetElapsedTime(); } float WINAPI DXUTGetFPS() { return GetDXUTState().GetFPS(); } @@ -666,60 +614,65 @@ bool WINAPI DXUTGetShowMsgBoxOnError() { return GetDXUTState bool WINAPI DXUTGetAutomation() { return GetDXUTState().GetAutomation(); } bool WINAPI DXUTIsWindowed() { return DXUTGetIsWindowedFromDS( GetDXUTState().GetCurrentDeviceSettings() ); } bool WINAPI DXUTIsInGammaCorrectMode() { return GetDXUTState().GetIsInGammaCorrectMode(); } -IDirect3D9* WINAPI DXUTGetD3D9Object() { DXUTDelayLoadD3D9(); return GetDXUTState().GetD3D9(); } -IDXGIFactory1* WINAPI DXUTGetDXGIFactory() { DXUTDelayLoadDXGI(); return GetDXUTState().GetDXGIFactory(); } -bool WINAPI DXUTIsD3D11Available() { DXUTDelayLoadDXGI(); return GetDXUTState().GetD3D11Available(); } -bool WINAPI DXUTIsAppRenderingWithD3D9() { return (GetDXUTState().GetD3D9Device() != NULL); } -bool WINAPI DXUTIsAppRenderingWithD3D11() { return (GetDXUTState().GetD3D11Device() != NULL); } +IDXGIFactory1* WINAPI DXUTGetDXGIFactory() { DXUTDelayLoadDXGI(); return GetDXUTState().GetDXGIFactory(); } + +ID3D11Device* WINAPI DXUTGetD3D11Device() { return GetDXUTState().GetD3D11Device(); } +ID3D11DeviceContext* WINAPI DXUTGetD3D11DeviceContext() { return GetDXUTState().GetD3D11DeviceContext(); } +ID3D11Device1* WINAPI DXUTGetD3D11Device1() { return GetDXUTState().GetD3D11Device1(); } +ID3D11DeviceContext1* WINAPI DXUTGetD3D11DeviceContext1() { return GetDXUTState().GetD3D11DeviceContext1(); } + +#ifdef USE_DIRECT3D11_2 +ID3D11Device2* WINAPI DXUTGetD3D11Device2() { return GetDXUTState().GetD3D11Device2(); } +ID3D11DeviceContext2* WINAPI DXUTGetD3D11DeviceContext2() { return GetDXUTState().GetD3D11DeviceContext2(); } +#endif + +#ifdef USE_DIRECT3D11_3 +ID3D11Device3* WINAPI DXUTGetD3D11Device3() { return GetDXUTState().GetD3D11Device3(); } +ID3D11DeviceContext3* WINAPI DXUTGetD3D11DeviceContext3() { return GetDXUTState().GetD3D11DeviceContext3(); } +#endif + +#ifdef USE_DIRECT3D11_4 +ID3D11Device4* WINAPI DXUTGetD3D11Device4() { return GetDXUTState().GetD3D11Device4(); } +ID3D11DeviceContext4* WINAPI DXUTGetD3D11DeviceContext4() { return GetDXUTState().GetD3D11DeviceContext4(); } +#endif //-------------------------------------------------------------------------------------- // External callback setup functions //-------------------------------------------------------------------------------------- // General callbacks -void WINAPI DXUTSetCallbackDeviceChanging( LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallback, void* pUserContext ) { GetDXUTState().SetModifyDeviceSettingsFunc( pCallback ); GetDXUTState().SetModifyDeviceSettingsFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackDeviceRemoved( LPDXUTCALLBACKDEVICEREMOVED pCallback, void* pUserContext ) { GetDXUTState().SetDeviceRemovedFunc( pCallback ); GetDXUTState().SetDeviceRemovedFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackFrameMove( LPDXUTCALLBACKFRAMEMOVE pCallback, void* pUserContext ) { GetDXUTState().SetFrameMoveFunc( pCallback ); GetDXUTState().SetFrameMoveFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackKeyboard( LPDXUTCALLBACKKEYBOARD pCallback, void* pUserContext ) { GetDXUTState().SetKeyboardFunc( pCallback ); GetDXUTState().SetKeyboardFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackMouse( LPDXUTCALLBACKMOUSE pCallback, bool bIncludeMouseMove, void* pUserContext ) { GetDXUTState().SetMouseFunc( pCallback ); GetDXUTState().SetNotifyOnMouseMove( bIncludeMouseMove ); GetDXUTState().SetMouseFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackMsgProc( LPDXUTCALLBACKMSGPROC pCallback, void* pUserContext ) { GetDXUTState().SetWindowMsgFunc( pCallback ); GetDXUTState().SetWindowMsgFuncUserContext( pUserContext ); } - -// Direct3D 9 callbacks -void WINAPI DXUTSetCallbackD3D9DeviceAcceptable( LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE pCallback, void* pUserContext ) { GetDXUTState().SetIsD3D9DeviceAcceptableFunc( pCallback ); GetDXUTState().SetIsD3D9DeviceAcceptableFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D9DeviceCreated( LPDXUTCALLBACKD3D9DEVICECREATED pCallback, void* pUserContext ) { GetDXUTState().SetD3D9DeviceCreatedFunc( pCallback ); GetDXUTState().SetD3D9DeviceCreatedFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D9DeviceReset( LPDXUTCALLBACKD3D9DEVICERESET pCallback, void* pUserContext ) { GetDXUTState().SetD3D9DeviceResetFunc( pCallback ); GetDXUTState().SetD3D9DeviceResetFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D9DeviceLost( LPDXUTCALLBACKD3D9DEVICELOST pCallback, void* pUserContext ) { GetDXUTState().SetD3D9DeviceLostFunc( pCallback ); GetDXUTState().SetD3D9DeviceLostFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D9DeviceDestroyed( LPDXUTCALLBACKD3D9DEVICEDESTROYED pCallback, void* pUserContext ) { GetDXUTState().SetD3D9DeviceDestroyedFunc( pCallback ); GetDXUTState().SetD3D9DeviceDestroyedFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D9FrameRender( LPDXUTCALLBACKD3D9FRAMERENDER pCallback, void* pUserContext ) { GetDXUTState().SetD3D9FrameRenderFunc( pCallback ); GetDXUTState().SetD3D9FrameRenderFuncUserContext( pUserContext ); } -void DXUTGetCallbackD3D9DeviceAcceptable( LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE* ppCallback, void** ppUserContext ) { *ppCallback = GetDXUTState().GetIsD3D9DeviceAcceptableFunc(); *ppUserContext = GetDXUTState().GetIsD3D9DeviceAcceptableFuncUserContext(); } +void WINAPI DXUTSetCallbackDeviceChanging( _In_ LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetModifyDeviceSettingsFunc( pCallback ); GetDXUTState().SetModifyDeviceSettingsFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackDeviceRemoved( _In_ LPDXUTCALLBACKDEVICEREMOVED pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetDeviceRemovedFunc( pCallback ); GetDXUTState().SetDeviceRemovedFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackFrameMove( _In_ LPDXUTCALLBACKFRAMEMOVE pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetFrameMoveFunc( pCallback ); GetDXUTState().SetFrameMoveFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackKeyboard( _In_ LPDXUTCALLBACKKEYBOARD pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetKeyboardFunc( pCallback ); GetDXUTState().SetKeyboardFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackMouse( _In_ LPDXUTCALLBACKMOUSE pCallback, bool bIncludeMouseMove, _In_opt_ void* pUserContext ) { GetDXUTState().SetMouseFunc( pCallback ); GetDXUTState().SetNotifyOnMouseMove( bIncludeMouseMove ); GetDXUTState().SetMouseFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackMsgProc( _In_ LPDXUTCALLBACKMSGPROC pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetWindowMsgFunc( pCallback ); GetDXUTState().SetWindowMsgFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackQuit( _In_ LPDXUTCALLBACKQUIT pCallback, _In_opt_ void* pUserContext) { GetDXUTState().SetQuitFunc( pCallback ); GetDXUTState().SetQuitFuncUserContext( pUserContext ); } // Direct3D 11 callbacks -void WINAPI DXUTSetCallbackD3D11DeviceAcceptable( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE pCallback, void* pUserContext ) { GetDXUTState().SetIsD3D11DeviceAcceptableFunc( pCallback ); GetDXUTState().SetIsD3D11DeviceAcceptableFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D11DeviceCreated( LPDXUTCALLBACKD3D11DEVICECREATED pCallback, void* pUserContext ) { GetDXUTState().SetD3D11DeviceCreatedFunc( pCallback ); GetDXUTState().SetD3D11DeviceCreatedFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D11SwapChainResized( LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallback, void* pUserContext ) { GetDXUTState().SetD3D11SwapChainResizedFunc( pCallback ); GetDXUTState().SetD3D11SwapChainResizedFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D11FrameRender( LPDXUTCALLBACKD3D11FRAMERENDER pCallback, void* pUserContext ) { GetDXUTState().SetD3D11FrameRenderFunc( pCallback ); GetDXUTState().SetD3D11FrameRenderFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D11SwapChainReleasing( LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallback, void* pUserContext ) { GetDXUTState().SetD3D11SwapChainReleasingFunc( pCallback ); GetDXUTState().SetD3D11SwapChainReleasingFuncUserContext( pUserContext ); } -void WINAPI DXUTSetCallbackD3D11DeviceDestroyed( LPDXUTCALLBACKD3D11DEVICEDESTROYED pCallback, void* pUserContext ) { GetDXUTState().SetD3D11DeviceDestroyedFunc( pCallback ); GetDXUTState().SetD3D11DeviceDestroyedFuncUserContext( pUserContext ); } -void DXUTGetCallbackD3D11DeviceAcceptable( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE* ppCallback, void** ppUserContext ) { *ppCallback = GetDXUTState().GetIsD3D11DeviceAcceptableFunc(); *ppUserContext = GetDXUTState().GetIsD3D11DeviceAcceptableFuncUserContext(); } +void WINAPI DXUTSetCallbackD3D11DeviceAcceptable( _In_ LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetIsD3D11DeviceAcceptableFunc( pCallback ); GetDXUTState().SetIsD3D11DeviceAcceptableFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackD3D11DeviceCreated( _In_ LPDXUTCALLBACKD3D11DEVICECREATED pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetD3D11DeviceCreatedFunc( pCallback ); GetDXUTState().SetD3D11DeviceCreatedFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackD3D11SwapChainResized( _In_ LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetD3D11SwapChainResizedFunc( pCallback ); GetDXUTState().SetD3D11SwapChainResizedFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackD3D11FrameRender( _In_ LPDXUTCALLBACKD3D11FRAMERENDER pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetD3D11FrameRenderFunc( pCallback ); GetDXUTState().SetD3D11FrameRenderFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackD3D11SwapChainReleasing( _In_ LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetD3D11SwapChainReleasingFunc( pCallback ); GetDXUTState().SetD3D11SwapChainReleasingFuncUserContext( pUserContext ); } +void WINAPI DXUTSetCallbackD3D11DeviceDestroyed( _In_ LPDXUTCALLBACKD3D11DEVICEDESTROYED pCallback, _In_opt_ void* pUserContext ) { GetDXUTState().SetD3D11DeviceDestroyedFunc( pCallback ); GetDXUTState().SetD3D11DeviceDestroyedFuncUserContext( pUserContext ); } +void DXUTGetCallbackD3D11DeviceAcceptable( _In_ LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE* ppCallback, _Outptr_ void** ppUserContext ) { *ppCallback = GetDXUTState().GetIsD3D11DeviceAcceptableFunc(); *ppUserContext = GetDXUTState().GetIsD3D11DeviceAcceptableFuncUserContext(); } //-------------------------------------------------------------------------------------- // Optionally parses the command line and sets if default hotkeys are handled // // Possible command line parameters are: -// -forcefeaturelevel:fl forces app to use a specified direct3D11 feature level +// -forcefeaturelevel:fl forces app to use a specified direct3D11 feature level // -screenshotexit:filename save a screenshot to the filename.bmp and exit. -// -forceapi:# forces app to use specified Direct3D API version (fails if the application doesn't support this API or if no device is found) // -adapter:# forces app to use this adapter # (fails if the adapter doesn't exist) -// -output:# [D3D11 only] forces app to use a particular output on the adapter (fails if the output doesn't exist) +// -output:# forces app to use a particular output on the adapter (fails if the output doesn't exist) // -windowed forces app to start windowed // -fullscreen forces app to start full screen // -forcehal forces app to use HAL (fails if HAL doesn't exist) // -forceref forces app to use REF (fails if REF doesn't exist) -// -forcepurehwvp [D3D9 only] forces app to use pure HWVP (fails if device doesn't support it) -// -forcehwvp [D3D9 only] forces app to use HWVP (fails if device doesn't support it) -// -forceswvp [D3D9 only] forces app to use SWVP -// -forcevsync:# if # is 0, then vsync is disabled +// -forcewarp forces app to use WARP (fails if WARP doesn't exist) +// -forcevsync:# if # is 0, then vsync is disabled // -width:# forces app to use # for width. for full screen, it will pick the closest possible supported mode // -height:# forces app to use # for height. for full screen, it will pick the closest possible supported mode // -startx:# forces app to use # for the x coord of the window position for windowed mode @@ -728,16 +681,20 @@ void DXUTGetCallbackD3D11DeviceAcceptable( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE // -quitafterframe:x forces app to quit after # frames // -noerrormsgboxes prevents the display of message boxes generated by the framework so the application can be run without user interaction // -nostats prevents the display of the stats -// -relaunchmce re-launches the MCE UI after the app exits -// -automation a hint to other components that automation is active +// -automation a hint to other components that automation is active //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTInit( bool bParseCommandLine, - bool bShowMsgBoxOnError, - __in_opt WCHAR* strExtraCommandLineParams, +_Use_decl_annotations_ +HRESULT WINAPI DXUTInit( bool bParseCommandLine, + bool bShowMsgBoxOnError, + WCHAR* strExtraCommandLineParams, bool bThreadSafeDXUT ) { g_bThreadSafe = bThreadSafeDXUT; + HRESULT hr = CoInitializeEx( nullptr, COINIT_MULTITHREADED ); + if ( FAILED(hr) ) + return hr; + GetDXUTState().SetDXUTInitCalled( true ); // Not always needed, but lets the app create GDI dialogs @@ -745,15 +702,18 @@ HRESULT WINAPI DXUTInit( bool bParseCommandLine, // Save the current sticky/toggle/filter key settings so DXUT can restore them later STICKYKEYS sk = {sizeof(STICKYKEYS), 0}; - SystemParametersInfo(SPI_GETSTICKYKEYS, sizeof(STICKYKEYS), &sk, 0); + if ( !SystemParametersInfo(SPI_GETSTICKYKEYS, sizeof(STICKYKEYS), &sk, 0) ) + memset( &sk, 0, sizeof(sk) ); GetDXUTState().SetStartupStickyKeys( sk ); TOGGLEKEYS tk = {sizeof(TOGGLEKEYS), 0}; - SystemParametersInfo(SPI_GETTOGGLEKEYS, sizeof(TOGGLEKEYS), &tk, 0); + if ( !SystemParametersInfo(SPI_GETTOGGLEKEYS, sizeof(TOGGLEKEYS), &tk, 0) ) + memset( &tk, 0, sizeof(tk) ); GetDXUTState().SetStartupToggleKeys( tk ); FILTERKEYS fk = {sizeof(FILTERKEYS), 0}; - SystemParametersInfo(SPI_GETFILTERKEYS, sizeof(FILTERKEYS), &fk, 0); + if ( !SystemParametersInfo(SPI_GETFILTERKEYS, sizeof(FILTERKEYS), &fk, 0) ) + memset( &fk, 0, sizeof(fk) ); GetDXUTState().SetStartupFilterKeys( fk ); GetDXUTState().SetShowMsgBoxOnError( bShowMsgBoxOnError ); @@ -773,18 +733,19 @@ HRESULT WINAPI DXUTInit( bool bParseCommandLine, //-------------------------------------------------------------------------------------- -// Parses the command line for parameters. See DXUTInit() for list +// Parses the command line for parameters. See DXUTInit() for list //-------------------------------------------------------------------------------------- -void DXUTParseCommandLine(__inout WCHAR* strCommandLine, +_Use_decl_annotations_ +void DXUTParseCommandLine(WCHAR* strCommandLine, bool bIgnoreFirstCommand ) { WCHAR* strCmdLine; WCHAR strFlag[MAX_PATH]; int nNumArgs; - LPWSTR* pstrArgList = CommandLineToArgvW( strCommandLine, &nNumArgs ); - int iArgStart = 0; - if( bIgnoreFirstCommand ) + auto pstrArgList = CommandLineToArgvW( strCommandLine, &nNumArgs ); + int iArgStart = 0; + if( bIgnoreFirstCommand ) iArgStart = 1; for( int iArg = iArgStart; iArg < nNumArgs; iArg++ ) { @@ -797,9 +758,20 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"forcefeaturelevel" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { - if (_wcsnicmp( strFlag, L"D3D_FEATURE_LEVEL_11_0", MAX_PATH) == 0 ) { +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + if (_wcsnicmp(strFlag, L"D3D_FEATURE_LEVEL_12_1", MAX_PATH) == 0) { + GetDXUTState().SetOverrideForceFeatureLevel(D3D_FEATURE_LEVEL_12_1); + } + else if (_wcsnicmp(strFlag, L"D3D_FEATURE_LEVEL_12_0", MAX_PATH) == 0) { + GetDXUTState().SetOverrideForceFeatureLevel(D3D_FEATURE_LEVEL_12_0); + } + else +#endif + if (_wcsnicmp( strFlag, L"D3D_FEATURE_LEVEL_11_1", MAX_PATH) == 0 ) { + GetDXUTState().SetOverrideForceFeatureLevel(D3D_FEATURE_LEVEL_11_1); + }else if (_wcsnicmp( strFlag, L"D3D_FEATURE_LEVEL_11_0", MAX_PATH) == 0 ) { GetDXUTState().SetOverrideForceFeatureLevel(D3D_FEATURE_LEVEL_11_0); }else if (_wcsnicmp( strFlag, L"D3D_FEATURE_LEVEL_10_1", MAX_PATH) == 0 ) { GetDXUTState().SetOverrideForceFeatureLevel(D3D_FEATURE_LEVEL_10_1); @@ -812,25 +784,13 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, }else if (_wcsnicmp( strFlag, L"D3D_FEATURE_LEVEL_9_1", MAX_PATH) == 0 ) { GetDXUTState().SetOverrideForceFeatureLevel(D3D_FEATURE_LEVEL_9_1); } - - - continue; - } - } - - if( DXUTIsNextArg( strCmdLine, L"forceapi" ) ) - { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) - { - int nAPIVersion = _wtoi( strFlag ); - GetDXUTState().SetOverrideForceAPI( nAPIVersion ); continue; } } if( DXUTIsNextArg( strCmdLine, L"adapter" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nAdapter = _wtoi( strFlag ); GetDXUTState().SetOverrideAdapterOrdinal( nAdapter ); @@ -846,7 +806,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"output" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int Output = _wtoi( strFlag ); GetDXUTState().SetOverrideOutput( Output ); @@ -866,11 +826,11 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, continue; } if( DXUTIsNextArg( strCmdLine, L"screenshotexit" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { GetDXUTState().SetExitAfterScreenShot( true ); GetDXUTState().SetSaveScreenShot( true ); - swprintf_s( GetDXUTState().GetScreenShotName(), 256, L"%s.bmp", strFlag ); + swprintf_s( GetDXUTState().GetScreenShotName(), 256, L"%ls.bmp", strFlag ); continue; } } @@ -879,10 +839,15 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, GetDXUTState().SetOverrideForceREF( true ); continue; } + if( DXUTIsNextArg( strCmdLine, L"forcewarp" ) ) + { + GetDXUTState().SetOverrideForceWARP( true ); + continue; + } if( DXUTIsNextArg( strCmdLine, L"forcevsync" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nOn = _wtoi( strFlag ); GetDXUTState().SetOverrideForceVsync( nOn ); @@ -892,7 +857,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"width" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nWidth = _wtoi( strFlag ); GetDXUTState().SetOverrideWidth( nWidth ); @@ -902,7 +867,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"height" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nHeight = _wtoi( strFlag ); GetDXUTState().SetOverrideHeight( nHeight ); @@ -912,7 +877,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"startx" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nX = _wtoi( strFlag ); GetDXUTState().SetOverrideStartX( nX ); @@ -922,7 +887,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"starty" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nY = _wtoi( strFlag ); GetDXUTState().SetOverrideStartY( nY ); @@ -933,8 +898,8 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"constantframetime" ) ) { float fTimePerFrame; - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) - fTimePerFrame = ( float )wcstod( strFlag, NULL ); + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) + fTimePerFrame = ( float )wcstod( strFlag, nullptr ); else fTimePerFrame = 0.0333f; GetDXUTState().SetOverrideConstantFrameTime( true ); @@ -945,7 +910,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, if( DXUTIsNextArg( strCmdLine, L"quitafterframe" ) ) { - if( DXUTGetCmdParam( strCmdLine, strFlag ) ) + if( DXUTGetCmdParam( strCmdLine, strFlag, MAX_PATH ) ) { int nFrame = _wtoi( strFlag ); GetDXUTState().SetOverrideQuitAfterFrame( nFrame ); @@ -965,12 +930,6 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, continue; } - if( DXUTIsNextArg( strCmdLine, L"relaunchmce" ) ) - { - GetDXUTState().SetOverrideRelaunchMCE( true ); - continue; - } - if( DXUTIsNextArg( strCmdLine, L"automation" ) ) { GetDXUTState().SetAutomation( true ); @@ -985,7 +944,7 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, strSpace++; *strSpace = 0; - DXUTOutputDebugString( L"Unrecognized flag: %s", strFlag ); + DXUTOutputDebugString( L"Unrecognized flag: %ls", strFlag ); strCmdLine += wcslen( strFlag ); } @@ -996,10 +955,11 @@ void DXUTParseCommandLine(__inout WCHAR* strCommandLine, //-------------------------------------------------------------------------------------- // Helper function for DXUTParseCommandLine //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ bool DXUTIsNextArg( WCHAR*& strCmdLine, const WCHAR* strArg ) { - int nArgLen = ( int )wcslen( strArg ); - int nCmdLen = ( int )wcslen( strCmdLine ); + size_t nArgLen = wcslen( strArg ); + size_t nCmdLen = wcslen( strCmdLine ); if( nCmdLen >= nArgLen && _wcsnicmp( strCmdLine, strArg, nArgLen ) == 0 && @@ -1014,21 +974,27 @@ bool DXUTIsNextArg( WCHAR*& strCmdLine, const WCHAR* strArg ) //-------------------------------------------------------------------------------------- -// Helper function for DXUTParseCommandLine. Updates strCmdLine and strFlag +// Helper function for DXUTParseCommandLine. Updates strCmdLine and strFlag // Example: if strCmdLine=="-width:1024 -forceref" // then after: strCmdLine==" -forceref" and strFlag=="1024" //-------------------------------------------------------------------------------------- -bool DXUTGetCmdParam( WCHAR*& strCmdLine, WCHAR* strFlag ) +_Use_decl_annotations_ +bool DXUTGetCmdParam( WCHAR*& strCmdLine, WCHAR* strFlag, int cchDest ) { if( *strCmdLine == L':' ) { strCmdLine++; // Skip ':' - // Place NULL terminator in strFlag after current token - wcscpy_s( strFlag, MAX_PATH, strCmdLine ); + // Place nul terminator in strFlag after current token + wcscpy_s( strFlag, cchDest, strCmdLine ); + WCHAR* strSpace = strFlag; - while( *strSpace && ( *strSpace > L' ' ) ) - strSpace++; + int count = 0; + while( *strSpace && ( *strSpace > L' ' ) && (count < cchDest) ) + { + ++strSpace; + ++count; + } *strSpace = 0; // Update strCmdLine @@ -1044,11 +1010,12 @@ bool DXUTGetCmdParam( WCHAR*& strCmdLine, WCHAR* strFlag ) //-------------------------------------------------------------------------------------- -// Creates a window with the specified window title, icon, menu, and +// Creates a window with the specified window title, icon, menu, and // starting position. If DXUTInit() has not already been called, it will -// call it with the default parameters. Instead of calling this, you can -// call DXUTSetWindow() to use an existing window. +// call it with the default parameters. Instead of calling this, you can +// call DXUTSetWindow() to use an existing window. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT WINAPI DXUTCreateWindow( const WCHAR* strWindowTitle, HINSTANCE hInstance, HICON hIcon, HMENU hMenu, int x, int y ) { @@ -1074,15 +1041,15 @@ HRESULT WINAPI DXUTCreateWindow( const WCHAR* strWindowTitle, HINSTANCE hInstanc return hr; } - if( DXUTGetHWNDFocus() == NULL ) + if( !DXUTGetHWNDFocus() ) { - if( hInstance == NULL ) - hInstance = ( HINSTANCE )GetModuleHandle( NULL ); + if( !hInstance ) + hInstance = ( HINSTANCE )GetModuleHandle( nullptr ); GetDXUTState().SetHInstance( hInstance ); WCHAR szExePath[MAX_PATH]; - GetModuleFileName( NULL, szExePath, MAX_PATH ); - if( hIcon == NULL ) // If the icon is NULL, then use the first one found in the exe + GetModuleFileName( nullptr, szExePath, MAX_PATH ); + if( !hIcon ) // If the icon is NULL, then use the first one found in the exe hIcon = ExtractIcon( hInstance, szExePath, 0 ); // Register the windows class @@ -1093,9 +1060,9 @@ HRESULT WINAPI DXUTCreateWindow( const WCHAR* strWindowTitle, HINSTANCE hInstanc wndClass.cbWndExtra = 0; wndClass.hInstance = hInstance; wndClass.hIcon = hIcon; - wndClass.hCursor = LoadCursor( NULL, IDC_ARROW ); + wndClass.hCursor = LoadCursor( nullptr, IDC_ARROW ); wndClass.hbrBackground = ( HBRUSH )GetStockObject( BLACK_BRUSH ); - wndClass.lpszMenuName = NULL; + wndClass.lpszMenuName = nullptr; wndClass.lpszClassName = L"Direct3DWindowClass"; if( !RegisterClass( &wndClass ) ) @@ -1116,8 +1083,8 @@ HRESULT WINAPI DXUTCreateWindow( const WCHAR* strWindowTitle, HINSTANCE hInstanc GetDXUTState().SetWindowCreatedWithDefaultPositions( true ); // Find the window's initial size, but it might be changed later - int nDefaultWidth = 640; - int nDefaultHeight = 480; + int nDefaultWidth = 800; + int nDefaultHeight = 600; if( GetDXUTState().GetOverrideWidth() != 0 ) nDefaultWidth = GetDXUTState().GetOverrideWidth(); if( GetDXUTState().GetOverrideHeight() != 0 ) @@ -1125,7 +1092,7 @@ HRESULT WINAPI DXUTCreateWindow( const WCHAR* strWindowTitle, HINSTANCE hInstanc RECT rc; SetRect( &rc, 0, 0, nDefaultWidth, nDefaultHeight ); - AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, ( hMenu != NULL ) ? true : false ); + AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, ( hMenu ) ? true : false ); WCHAR* strCachedWindowTitle = GetDXUTState().GetWindowTitle(); wcscpy_s( strCachedWindowTitle, 256, strWindowTitle ); @@ -1134,7 +1101,7 @@ HRESULT WINAPI DXUTCreateWindow( const WCHAR* strWindowTitle, HINSTANCE hInstanc HWND hWnd = CreateWindow( L"Direct3DWindowClass", strWindowTitle, WS_OVERLAPPEDWINDOW, x, y, ( rc.right - rc.left ), ( rc.bottom - rc.top ), 0, hMenu, hInstance, 0 ); - if( hWnd == NULL ) + if( !hWnd ) { DWORD dwError = GetLastError(); return DXUT_ERR_MSGBOX( L"CreateWindow", HRESULT_FROM_WIN32(dwError) ); @@ -1151,10 +1118,11 @@ HRESULT WINAPI DXUTCreateWindow( const WCHAR* strWindowTitle, HINSTANCE hInstanc //-------------------------------------------------------------------------------------- -// Sets a previously created window for the framework to use. If DXUTInit() -// has not already been called, it will call it with the default parameters. -// Instead of calling this, you can call DXUTCreateWindow() to create a new window. +// Sets a previously created window for the framework to use. If DXUTInit() +// has not already been called, it will call it with the default parameters. +// Instead of calling this, you can call DXUTCreateWindow() to create a new window. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT WINAPI DXUTSetWindow( HWND hWndFocus, HWND hWndDeviceFullScreen, HWND hWndDeviceWindowed, bool bHandleMessages ) { HRESULT hr; @@ -1165,10 +1133,10 @@ HRESULT WINAPI DXUTSetWindow( HWND hWndFocus, HWND hWndDeviceFullScreen, HWND hW GetDXUTState().SetWindowCreateCalled( true ); - // To avoid confusion, we do not allow any HWND to be NULL here. The + // To avoid confusion, we do not allow any HWND to be nullptr here. The // caller must pass in valid HWND for all three parameters. The same // HWND may be used for more than one parameter. - if( hWndFocus == NULL || hWndDeviceFullScreen == NULL || hWndDeviceWindowed == NULL ) + if( !hWndFocus || !hWndDeviceFullScreen || !hWndDeviceWindowed ) return DXUT_ERR_MSGBOX( L"DXUTSetWindow", E_INVALIDARG ); // If subclassing the window, set the pointer to the local window procedure @@ -1213,11 +1181,12 @@ HRESULT WINAPI DXUTSetWindow( HWND hWndFocus, HWND hWndDeviceFullScreen, HWND hW //-------------------------------------------------------------------------------------- -// Handles window messages +// Handles window messages //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { - + // Consolidate the keyboard messages and pass them to the app's keyboard callback if( uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN || @@ -1289,7 +1258,9 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM xPos, yPos, GetDXUTState().GetMouseFuncUserContext() ); } - // Pass all messages to the app's MsgProc callback, and don't + // TODO - WM_POINTER for touch when on Windows 8.0 + + // Pass all messages to the app's MsgProc callback, and don't // process further messages if the apps says not to. LPDXUTCALLBACKMSGPROC pCallbackMsgProc = GetDXUTState().GetWindowMsgFunc(); if( pCallbackMsgProc ) @@ -1305,7 +1276,6 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM { case WM_PAINT: { - // Handle paint messages when the app is paused if( DXUTIsRenderingPaused() && GetDXUTState().GetDeviceObjectsCreated() && GetDXUTState().GetDeviceObjectsReset() ) @@ -1314,49 +1284,13 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM double fTime = DXUTGetTime(); float fElapsedTime = DXUTGetElapsedTime(); - if( DXUTIsCurrentDeviceD3D9() ) - { - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - if( pd3dDevice ) - { - LPDXUTCALLBACKD3D9FRAMERENDER pCallbackFrameRender = GetDXUTState().GetD3D9FrameRenderFunc(); - if( pCallbackFrameRender != NULL ) - pCallbackFrameRender( pd3dDevice, fTime, fElapsedTime, - GetDXUTState().GetD3D9FrameRenderFuncUserContext() ); - - hr = pd3dDevice->Present( NULL, NULL, NULL, NULL ); - if( D3DERR_DEVICELOST == hr ) - { - GetDXUTState().SetDeviceLost( true ); - } - else if( D3DERR_DRIVERINTERNALERROR == hr ) - { - // When D3DERR_DRIVERINTERNALERROR is returned from Present(), - // the application can do one of the following: - // - // - End, with the pop-up window saying that the application cannot continue - // because of problems in the display adapter and that the user should - // contact the adapter manufacturer. - // - // - Attempt to restart by calling IDirect3DDevice9::Reset, which is essentially the same - // path as recovering from a lost device. If IDirect3DDevice9::Reset fails with - // D3DERR_DRIVERINTERNALERROR, the application should end immediately with the message - // that the user should contact the adapter manufacturer. - // - // The framework attempts the path of resetting the device - // - GetDXUTState().SetDeviceLost( true ); - } - } - } - else { - ID3D11Device* pd3dDevice = DXUTGetD3D11Device(); - ID3D11DeviceContext *pDeferred = DXUTGetD3D11DeviceContext(); + auto pd3dDevice = DXUTGetD3D11Device(); + auto pDeferred = DXUTGetD3D11DeviceContext(); if( pd3dDevice ) { LPDXUTCALLBACKD3D11FRAMERENDER pCallbackFrameRender = GetDXUTState().GetD3D11FrameRenderFunc(); - if( pCallbackFrameRender != NULL && + if( pCallbackFrameRender && !GetDXUTState().GetRenderingOccluded() ) { pCallbackFrameRender( pd3dDevice,pDeferred, fTime, fElapsedTime, @@ -1369,8 +1303,8 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM else dwFlags = GetDXUTState().GetCurrentDeviceSettings()->d3d11.PresentFlags; - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); - hr = pSwapChain->Present( 0, GetDXUTState().GetCurrentDeviceSettings()->d3d11.PresentFlags ); + auto pSwapChain = DXUTGetDXGISwapChain(); + hr = pSwapChain->Present( 0, dwFlags ); if( DXGI_STATUS_OCCLUDED == hr ) { // There is a window covering our entire rendering area. @@ -1393,7 +1327,7 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM } case WM_SIZE: - + if( SIZE_MINIMIZED == wParam ) { DXUTPause( true, true ); // Pause while we're minimized @@ -1408,7 +1342,7 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM if( rcCurrentClient.top == 0 && rcCurrentClient.bottom == 0 ) { // Rapidly clicking the task bar to minimize and restore a window - // can cause a WM_SIZE message with SIZE_RESTORED when + // can cause a WM_SIZE message with SIZE_RESTORED when // the window has actually become minimized due to rapid change // so just ignore this message } @@ -1439,24 +1373,22 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM } else if( GetDXUTState().GetInSizeMove() ) { - // If we're neither maximized nor minimized, the window size - // is changing by the user dragging the window edges. In this - // case, we don't reset the device yet -- we wait until the + // If we're neither maximized nor minimized, the window size + // is changing by the user dragging the window edges. In this + // case, we don't reset the device yet -- we wait until the // user stops dragging, and a WM_EXITSIZEMOVE message comes. } else { - // This WM_SIZE come from resizing the window via an API like SetWindowPos() so + // This WM_SIZE come from resizing the window via an API like SetWindowPos() so // resize and reset the device now. DXUTCheckForWindowSizeChange(); DXUTCheckForWindowChangingMonitors(); } } } - break; - case WM_GETMINMAXINFO: ( ( MINMAXINFO* )lParam )->ptMinTrackSize.x = DXUT_MIN_WINDOW_SIZE_X; ( ( MINMAXINFO* )lParam )->ptMinTrackSize.y = DXUT_MIN_WINDOW_SIZE_Y; @@ -1475,48 +1407,18 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM GetDXUTState().SetInSizeMove( false ); break; - case WM_MOUSEMOVE: - if( DXUTIsActive() && !DXUTIsWindowed() ) - { - if( DXUTIsCurrentDeviceD3D9() ) - { - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - if( pd3dDevice ) - { - POINT ptCursor; - GetCursorPos( &ptCursor ); - pd3dDevice->SetCursorPosition( ptCursor.x, ptCursor.y, 0 ); - } - } - else - { - // For D3D11, no processing is necessary. D3D11 cursor - // is handled in the traditional Windows manner. - } - } - break; - case WM_SETCURSOR: if( DXUTIsActive() && !DXUTIsWindowed() ) { - if( DXUTIsCurrentDeviceD3D9() ) - { - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - if( pd3dDevice && GetDXUTState().GetShowCursorWhenFullScreen() ) - pd3dDevice->ShowCursor( true ); - } - else - { - if( !GetDXUTState().GetShowCursorWhenFullScreen() ) - SetCursor( NULL ); - } + if( !GetDXUTState().GetShowCursorWhenFullScreen() ) + SetCursor( nullptr ); return true; // prevent Windows from setting cursor to window class cursor } break; case WM_ACTIVATEAPP: - if( wParam == TRUE && !DXUTIsActive() ) // Handle only if previously not active + if( wParam == TRUE && !DXUTIsActive() ) // Handle only if previously not active { GetDXUTState().SetActive( true ); @@ -1524,27 +1426,22 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM DXUTEnableXInput( true ); // The GetMinimizedWhileFullscreen() varible is used instead of !DXUTIsWindowed() - // to handle the rare case toggling to windowed mode while the fullscreen application + // to handle the rare case toggling to windowed mode while the fullscreen application // is minimized and thus making the pause count wrong if( GetDXUTState().GetMinimizedWhileFullscreen() ) { - if( DXUTIsD3D9( GetDXUTState().GetCurrentDeviceSettings() ) ) - DXUTPause( false, false ); // Unpause since we're no longer minimized GetDXUTState().SetMinimizedWhileFullscreen( false ); - if( DXUTIsAppRenderingWithD3D11() ) - { - DXUTToggleFullScreen(); - } + DXUTToggleFullScreen(); } - // Upon returning to this app, potentially disable shortcut keys - // (Windows key, accessibility shortcuts) + // Upon returning to this app, potentially disable shortcut keys + // (Windows key, accessibility shortcuts) DXUTAllowShortcutKeys( ( DXUTIsWindowed() ) ? GetDXUTState().GetAllowShortcutKeysWhenWindowed() : GetDXUTState().GetAllowShortcutKeysWhenFullscreen() ); } - else if( wParam == FALSE && DXUTIsActive() ) // Handle only if previously active + else if( wParam == FALSE && DXUTIsActive() ) // Handle only if previously active { GetDXUTState().SetActive( false ); @@ -1553,17 +1450,15 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM if( !DXUTIsWindowed() ) { - // Going from full screen to a minimized state - ClipCursor( NULL ); // don't limit the cursor anymore - if( DXUTIsD3D9( GetDXUTState().GetCurrentDeviceSettings() ) ) - DXUTPause( true, true ); // Pause while we're minimized (take care not to pause twice by handling this message twice) + // Going from full screen to a minimized state + ClipCursor( nullptr ); // don't limit the cursor anymore GetDXUTState().SetMinimizedWhileFullscreen( true ); } // Restore shortcut keys (Windows key, accessibility shortcuts) to original state // - // This is important to call here if the shortcuts are disabled, - // because if this is not done then the Windows key will continue to + // This is important to call here if the shortcuts are disabled, + // because if this is not done then the Windows key will continue to // be disabled while this app is running which is very bad. // If the app crashes, the Windows key will return to normal. DXUTAllowShortcutKeys( true ); @@ -1594,9 +1489,6 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM case WM_POWERBROADCAST: switch( wParam ) { -#ifndef PBT_APMQUERYSUSPEND -#define PBT_APMQUERYSUSPEND 0x0000 -#endif case PBT_APMQUERYSUSPEND: // At this point, the app should save any data for open // network connections, files, etc., and prepare to go into @@ -1604,9 +1496,6 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM // to handle this if desired. return true; -#ifndef PBT_APMRESUMESUSPEND -#define PBT_APMRESUMESUSPEND 0x0007 -#endif case PBT_APMRESUMESUSPEND: // At this point, the app should recover any data, network // connections, files, etc., and resume running from when @@ -1635,31 +1524,6 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM } break; - case WM_SYSKEYDOWN: - { - switch( wParam ) - { - case VK_RETURN: - { - if( GetDXUTState().GetHandleAltEnter() && DXUTIsAppRenderingWithD3D9() ) - { - // Toggle full screen upon alt-enter - DWORD dwMask = ( 1 << 29 ); - if( ( lParam & dwMask ) != 0 ) // Alt is down also - { - // Toggle the full screen/window mode - DXUTPause( true, true ); - DXUTToggleFullScreen(); - DXUTPause( false, false ); - return 0; - } - } - - } - } - break; - } - case WM_KEYDOWN: { switch( wParam ) @@ -1692,25 +1556,30 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM { HMENU hMenu; hMenu = GetMenu( hWnd ); - if( hMenu != NULL ) + if( hMenu ) DestroyMenu( hMenu ); DestroyWindow( hWnd ); - UnregisterClass( L"Direct3DWindowClass", NULL ); - GetDXUTState().SetHWNDFocus( NULL ); - GetDXUTState().SetHWNDDeviceFullScreen( NULL ); - GetDXUTState().SetHWNDDeviceWindowed( NULL ); + UnregisterClass( L"Direct3DWindowClass", nullptr ); + GetDXUTState().SetHWNDFocus( nullptr ); + GetDXUTState().SetHWNDDeviceFullScreen( nullptr ); + GetDXUTState().SetHWNDDeviceWindowed( nullptr ); return 0; } case WM_DESTROY: - PostQuitMessage( 0 ); - break; + { + LPDXUTCALLBACKQUIT pQuitCallback = GetDXUTState().GetQuitFunc(); + if (pQuitCallback) + { + pQuitCallback(GetDXUTState().GetQuitFuncUserContext()); + } + } } // Don't allow the F10 key to act as a shortcut to the menu bar // by not passing these messages to the DefWindowProc only when // there's no menu present - if( !GetDXUTState().GetCallDefWindowProc() || GetDXUTState().GetMenu() == NULL && + if( !GetDXUTState().GetCallDefWindowProc() || !GetDXUTState().GetMenu() && ( uMsg == WM_SYSKEYDOWN || uMsg == WM_SYSKEYUP ) && wParam == VK_F10 ) return 0; else @@ -1719,10 +1588,10 @@ LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM //-------------------------------------------------------------------------------------- -// Handles app's message loop and rendering when idle. If DXUTCreateDevice() or DXUTSetD3D*Device() -// has not already been called, it will call DXUTCreateWindow() with the default parameters. +// Handles app's message loop and rendering when idle. If DXUTCreateDevice() +// has not already been called, it will call DXUTCreateWindow() with the default parameters. //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) +HRESULT WINAPI DXUTMainLoop( _In_opt_ HACCEL hAccel ) { HRESULT hr; @@ -1736,8 +1605,8 @@ HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) GetDXUTState().SetInsideMainloop( true ); - // If DXUTCreateDevice() or DXUTSetD3D*Device() has not already been called, - // then call DXUTCreateDevice() with the default parameters. + // If DXUTCreateDevice() has not already been called, + // then call DXUTCreateDevice() with the default parameters. if( !GetDXUTState().GetDeviceCreated() ) { if( GetDXUTState().GetDeviceCreateCalled() ) @@ -1747,7 +1616,7 @@ HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) return E_FAIL; // DXUTCreateDevice() must first succeed for this function to succeed } - hr = DXUTCreateDevice(D3D_FEATURE_LEVEL_10_0, true, 640, 480); + hr = DXUTCreateDevice(D3D_FEATURE_LEVEL_10_0, true, 800, 600); if( FAILED( hr ) ) { if( ( GetDXUTState().GetExitCode() == 0 ) || ( GetDXUTState().GetExitCode() == 10 ) ) @@ -1760,7 +1629,7 @@ HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) // DXUTInit() must have been called and succeeded for this function to proceed // DXUTCreateWindow() or DXUTSetWindow() must have been called and succeeded for this function to proceed - // DXUTCreateDevice() or DXUTCreateDeviceFromSettings() or DXUTSetD3D*Device() must have been called and succeeded for this function to proceed + // DXUTCreateDevice() or DXUTCreateDeviceFromSettings() must have been called and succeeded for this function to proceed if( !GetDXUTState().GetDXUTInited() || !GetDXUTState().GetWindowCreated() || !GetDXUTState().GetDeviceCreated() ) { if( ( GetDXUTState().GetExitCode() == 0 ) || ( GetDXUTState().GetExitCode() == 10 ) ) @@ -1772,17 +1641,17 @@ HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) bool bGotMsg; MSG msg; msg.message = WM_NULL; - PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE ); + PeekMessage( &msg, nullptr, 0U, 0U, PM_NOREMOVE ); while( WM_QUIT != msg.message ) { - // Use PeekMessage() so we can use idle time to render the scene. - bGotMsg = ( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) != 0 ); + // Use PeekMessage() so we can use idle time to render the scene. + bGotMsg = ( PeekMessage( &msg, nullptr, 0U, 0U, PM_REMOVE ) != 0 ); if( bGotMsg ) { // Translate and dispatch the message - if( hAccel == NULL || hWnd == NULL || + if( !hAccel || !hWnd || 0 == TranslateAccelerator( hWnd, hAccel, &msg ) ) { TranslateMessage( &msg ); @@ -1797,7 +1666,7 @@ HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) } // Cleanup the accelerator table - if( hAccel != NULL ) + if( hAccel ) DestroyAcceleratorTable( hAccel ); GetDXUTState().SetInsideMainloop( false ); @@ -1811,18 +1680,19 @@ HRESULT WINAPI DXUTMainLoop( HACCEL hAccel ) // Direct3D section //====================================================================================== //====================================================================================== -HRESULT WINAPI DXUTCreateDevice(D3D_FEATURE_LEVEL reqFL, bool bWindowed, int nSuggestedWidth, int nSuggestedHeight) { +_Use_decl_annotations_ +HRESULT WINAPI DXUTCreateDevice(D3D_FEATURE_LEVEL reqFL, bool bWindowed, int nSuggestedWidth, int nSuggestedHeight) +{ HRESULT hr = S_OK; - - + // Not allowed to call this from inside the device callbacks if( GetDXUTState().GetInsideDeviceCallback() ) - return DXUT_ERR_MSGBOX( L"DXUTCreateWindow", E_FAIL ); + return DXUT_ERR_MSGBOX( L"DXUTCreateDevice", E_FAIL ); GetDXUTState().SetDeviceCreateCalled( true ); - // If DXUTCreateWindow() or DXUTSetWindow() has not already been called, - // then call DXUTCreateWindow() with the default parameters. + // If DXUTCreateWindow() or DXUTSetWindow() has not already been called, + // then call DXUTCreateWindow() with the default parameters. if( !GetDXUTState().GetWindowCreated() ) { // If DXUTCreateWindow() or DXUTSetWindow() was already called and failed, then fail. @@ -1830,104 +1700,90 @@ HRESULT WINAPI DXUTCreateDevice(D3D_FEATURE_LEVEL reqFL, bool bWindowed, int nS if( GetDXUTState().GetWindowCreateCalled() ) return E_FAIL; - // If DXUTCreateWindow() or DXUTSetWindow() hasn't been called, then + // If DXUTCreateWindow() or DXUTSetWindow() hasn't been called, then // automatically call DXUTCreateWindow() with default params hr = DXUTCreateWindow(); if( FAILED( hr ) ) return hr; } - - DXUTDeviceSettings deviceSettings ; + + DXUTDeviceSettings deviceSettings; DXUTApplyDefaultDeviceSettings(&deviceSettings); deviceSettings.MinimumFeatureLevel = reqFL; deviceSettings.d3d11.sd.BufferDesc.Width = nSuggestedWidth; deviceSettings.d3d11.sd.BufferDesc.Height = nSuggestedHeight; deviceSettings.d3d11.sd.Windowed = bWindowed; - deviceSettings.d3d9.pp.Windowed = bWindowed; - deviceSettings.d3d9.pp.BackBufferWidth= nSuggestedWidth; - deviceSettings.d3d9.pp.BackBufferHeight = nSuggestedHeight; - - bool bAppSupportsD3D9 = DXUTDoesAppSupportD3D9(); - bool bAppSupportsD3D11 = DXUTDoesAppSupportD3D11(); + DXUTUpdateDeviceSettingsWithOverrides(&deviceSettings); - if (bAppSupportsD3D11) { - deviceSettings.ver = DXUT_D3D11_DEVICE; - } - else if (bAppSupportsD3D9) { - deviceSettings.ver = DXUT_D3D9_DEVICE; - } + GetDXUTState().SetWindowBackBufferWidthAtModeChange(deviceSettings.d3d11.sd.BufferDesc.Width); + GetDXUTState().SetWindowBackBufferHeightAtModeChange(deviceSettings.d3d11.sd.BufferDesc.Height); + GetDXUTState().SetFullScreenBackBufferWidthAtModeChange(deviceSettings.d3d11.sd.BufferDesc.Width); + GetDXUTState().SetFullScreenBackBufferHeightAtModeChange(deviceSettings.d3d11.sd.BufferDesc.Height); - DXUTUpdateDeviceSettingsWithOverrides(&deviceSettings); - - // Change to a Direct3D device created from the new device settings. + // Change to a Direct3D device created from the new device settings. // If there is an existing device, then either reset or recreated the scene - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, true ); + hr = DXUTChangeDevice( &deviceSettings, true ); - if ( hr == DXUTERR_NODIRECT3D11 && GetDXUTState().GetMessageWhenD3D11NotAvailable() ) { - + if ( hr == DXUTERR_NODIRECT3D && GetDXUTState().GetMessageWhenD3D11NotAvailable() ) + { OSVERSIONINFOEX osv; memset( &osv, 0, sizeof(osv) ); osv.dwOSVersionInfoSize = sizeof(osv); +#pragma warning( suppress : 4996 28159 ) GetVersionEx( (LPOSVERSIONINFO)&osv ); - if ( ( osv.dwMajorVersion > 6 ) - || ( osv.dwMajorVersion == 6 && osv.dwMinorVersion >= 1 ) + || ( osv.dwMajorVersion == 6 && osv.dwMinorVersion >= 1 ) || ( osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0 && osv.dwBuildNumber > 6002 ) ) { - MessageBox( 0, L"Direct3D 11 components were not found.", L"Error", MB_ICONEXCLAMATION ); // This should not happen, but is here for completeness as the system could be // corrupted or some future OS version could pull D3D11.DLL for some reason } else if ( osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0 && osv.dwBuildNumber == 6002 ) { - MessageBox( 0, L"Direct3D 11 components were not found, but are available for"\ L" this version of Windows.\n"\ L"For details see Microsoft Knowledge Base Article #971644\n"\ L"http://go.microsoft.com/fwlink/?LinkId=160189", L"Error", MB_ICONEXCLAMATION ); - } else if ( osv.dwMajorVersion == 6 && osv.dwMinorVersion == 0 ) { MessageBox( 0, L"Direct3D 11 components were not found. Please install the latest Service Pack.\n"\ L"For details see Microsoft Knowledge Base Article #935791\n"\ L"http://support.microsoft.com/kb/935791/", L"Error", MB_ICONEXCLAMATION ); - } else { MessageBox( 0, L"Direct3D 11 is not supported on this OS.", L"Error", MB_ICONEXCLAMATION ); } - - - } - if( FAILED( hr ) ) return hr; - + return hr; } + //-------------------------------------------------------------------------------------- // Tells the framework to change to a device created from the passed in device settings -// If DXUTCreateWindow() has not already been called, it will call it with the -// default parameters. Instead of calling this, you can call DXUTCreateDevice() -// or DXUTSetD3D*Device() +// If DXUTCreateWindow() has not already been called, it will call it with the +// default parameters. Instead of calling this, you can call DXUTCreateDevice() //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTCreateDeviceFromSettings( DXUTDeviceSettings* pDeviceSettings, bool bPreserveInput, - bool bClipWindowToSingleAdapter ) +_Use_decl_annotations_ +HRESULT WINAPI DXUTCreateDeviceFromSettings( DXUTDeviceSettings* pDeviceSettings, bool bClipWindowToSingleAdapter ) { + if ( !pDeviceSettings ) + return E_INVALIDARG; + HRESULT hr; GetDXUTState().SetDeviceCreateCalled( true ); - // If DXUTCreateWindow() or DXUTSetWindow() has not already been called, - // then call DXUTCreateWindow() with the default parameters. + // If DXUTCreateWindow() or DXUTSetWindow() has not already been called, + // then call DXUTCreateWindow() with the default parameters. if( !GetDXUTState().GetWindowCreated() ) { // If DXUTCreateWindow() or DXUTSetWindow() was already called and failed, then fail. @@ -1935,18 +1791,23 @@ HRESULT WINAPI DXUTCreateDeviceFromSettings( DXUTDeviceSettings* pDeviceSettings if( GetDXUTState().GetWindowCreateCalled() ) return E_FAIL; - // If DXUTCreateWindow() or DXUTSetWindow() hasn't been called, then + // If DXUTCreateWindow() or DXUTSetWindow() hasn't been called, then // automatically call DXUTCreateWindow() with default params hr = DXUTCreateWindow(); if( FAILED( hr ) ) return hr; } - DXUTUpdateDeviceSettingsWithOverrides(pDeviceSettings); - - // Change to a Direct3D device created from the new device settings. + DXUTUpdateDeviceSettingsWithOverrides(pDeviceSettings); + + GetDXUTState().SetWindowBackBufferWidthAtModeChange(pDeviceSettings->d3d11.sd.BufferDesc.Width); + GetDXUTState().SetWindowBackBufferHeightAtModeChange(pDeviceSettings->d3d11.sd.BufferDesc.Height); + GetDXUTState().SetFullScreenBackBufferWidthAtModeChange(pDeviceSettings->d3d11.sd.BufferDesc.Width); + GetDXUTState().SetFullScreenBackBufferHeightAtModeChange(pDeviceSettings->d3d11.sd.BufferDesc.Height); + + // Change to a Direct3D device created from the new device settings. // If there is an existing device, then either reset or recreate the scene - hr = DXUTChangeDevice( pDeviceSettings, NULL, NULL, false, bClipWindowToSingleAdapter ); + hr = DXUTChangeDevice( pDeviceSettings, bClipWindowToSingleAdapter ); if( FAILED( hr ) ) return hr; @@ -1955,51 +1816,38 @@ HRESULT WINAPI DXUTCreateDeviceFromSettings( DXUTDeviceSettings* pDeviceSettings //-------------------------------------------------------------------------------------- -// All device changes are sent to this function. It looks at the current -// device (if any) and the new device and determines the best course of action. It +// All device changes are sent to this function. It looks at the current +// device (if any) and the new device and determines the best course of action. It // also remembers and restores the window state if toggling between windowed and fullscreen // as well as sets the proper window and system state for switching to the new device. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, - IDirect3DDevice9* pd3d9DeviceFromApp, - ID3D11Device* pd3d11DeviceFromApp, - bool bForceRecreate, bool bClipWindowToSingleAdapter ) + bool bClipWindowToSingleAdapter ) { + if ( GetDXUTState().GetReleasingSwapChain() ) + return S_FALSE; + HRESULT hr = S_OK; DXUTDeviceSettings* pOldDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); if( !pNewDeviceSettings ) return S_FALSE; - - - if ( pNewDeviceSettings->ver == DXUT_D3D11_DEVICE ) { - hr = DXUTDelayLoadDXGI(); - } - - - if ( pNewDeviceSettings->ver == DXUT_D3D9_DEVICE || - ( FAILED( hr ) && DXUTDoesAppSupportD3D9() ) ) { - hr = DXUTDelayLoadD3D9(); - pNewDeviceSettings->ver = DXUT_D3D9_DEVICE; - if ( !FAILED( hr ) ) { - pNewDeviceSettings->ver = DXUT_D3D9_DEVICE; - } - } + hr = DXUTDelayLoadDXGI(); if( FAILED( hr ) ) return hr; // Make a copy of the pNewDeviceSettings on the heap - DXUTDeviceSettings* pNewDeviceSettingsOnHeap = new DXUTDeviceSettings; - if( pNewDeviceSettingsOnHeap == NULL ) + DXUTDeviceSettings* pNewDeviceSettingsOnHeap = new (std::nothrow) DXUTDeviceSettings; + if( !pNewDeviceSettingsOnHeap ) return E_OUTOFMEMORY; memcpy( pNewDeviceSettingsOnHeap, pNewDeviceSettings, sizeof( DXUTDeviceSettings ) ); pNewDeviceSettings = pNewDeviceSettingsOnHeap; - GetDXUTState().SetCurrentDeviceSettings(pNewDeviceSettingsOnHeap); - DXUTSnapDeviceSettingsToEnumDevice(pNewDeviceSettingsOnHeap, false); + hr = DXUTSnapDeviceSettingsToEnumDevice(pNewDeviceSettingsOnHeap, false); if( FAILED( hr ) ) // the call will fail if no valid devices were found { @@ -2007,22 +1855,22 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, return DXUT_ERR( L"DXUTFindValidDeviceSettings", hr ); } - // If the ModifyDeviceSettings callback is non-NULL, then call it to let the app + // If the ModifyDeviceSettings callback is non-NULL, then call it to let the app // change the settings or reject the device change by returning false. LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallbackModifyDeviceSettings = GetDXUTState().GetModifyDeviceSettingsFunc(); - if( pCallbackModifyDeviceSettings && pd3d9DeviceFromApp == NULL ) + if( pCallbackModifyDeviceSettings ) { bool bContinue = pCallbackModifyDeviceSettings( pNewDeviceSettings, GetDXUTState().GetModifyDeviceSettingsFuncUserContext() ); if( !bContinue ) { // The app rejected the device change by returning false, so just use the current device if there is one. - if( pOldDeviceSettings == NULL ) + if( !pOldDeviceSettings ) DXUTDisplayErrorMessage( DXUTERR_NOCOMPATIBLEDEVICES ); SAFE_DELETE( pNewDeviceSettings ); return E_ABORT; } - if( GetDXUTState().GetD3D9() == NULL && GetDXUTState().GetDXGIFactory() == NULL ) // if DXUTShutdown() was called in the modify callback, just return + if( !GetDXUTState().GetDXGIFactory() ) // if DXUTShutdown() was called in the modify callback, just return { SAFE_DELETE( pNewDeviceSettings ); return S_FALSE; @@ -2041,13 +1889,6 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, DXUTPause( true, true ); - // When a WM_SIZE message is received, it calls DXUTCheckForWindowSizeChange(). - // A WM_SIZE message might be sent when adjusting the window, so tell - // DXUTCheckForWindowSizeChange() to ignore size changes temporarily - if( DXUTIsCurrentDeviceD3D9() ) - GetDXUTState().SetIgnoreSizeChange( true ); - - // Take note if the backbuffer width & height are 0 now as they will change after pd3dDevice->Reset() bool bKeepCurrentWindowSize = false; if( DXUTGetBackBufferWidthFromDS( pNewDeviceSettings ) == 0 && @@ -2058,125 +1899,30 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, // Before reset ///////////////////////// - // If we are using D3D9, adjust window style when switching from windowed to fullscreen and - // vice versa. Note that this is not necessary in D3D11 because DXGI handles this. If both - // DXUT and DXGI handle this, incorrect behavior would result. - if( DXUTIsCurrentDeviceD3D9() ) + if( DXUTGetIsWindowedFromDS( pNewDeviceSettings ) ) { - if( DXUTGetIsWindowedFromDS( pNewDeviceSettings ) ) + // Going to windowed mode + if( pOldDeviceSettings && !DXUTGetIsWindowedFromDS( pOldDeviceSettings ) ) { - // Going to windowed mode - - if( pOldDeviceSettings && !DXUTGetIsWindowedFromDS( pOldDeviceSettings ) ) - { - // Going from fullscreen -> windowed - GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS( - pOldDeviceSettings ) ); - GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS( - pOldDeviceSettings ) ); - - // Restore windowed mode style - SetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE, GetDXUTState().GetWindowedStyleAtModeChange() ); - } - - // If different device windows are used for windowed mode and fullscreen mode, - // hide the fullscreen window so that it doesn't obscure the screen. - if( DXUTGetHWNDDeviceFullScreen() != DXUTGetHWNDDeviceWindowed() ) - ShowWindow( DXUTGetHWNDDeviceFullScreen(), SW_HIDE ); - - // If using the same window for windowed and fullscreen mode, reattach menu if one exists - if( DXUTGetHWNDDeviceFullScreen() == DXUTGetHWNDDeviceWindowed() ) - { - if( GetDXUTState().GetMenu() != NULL ) - SetMenu( DXUTGetHWNDDeviceWindowed(), GetDXUTState().GetMenu() ); - } - } - else - { - // Going to fullscreen mode - - if( pOldDeviceSettings == NULL || ( pOldDeviceSettings && DXUTGetIsWindowedFromDS( pOldDeviceSettings ) ) ) - { - // Transistioning to full screen mode from a standard window so - // save current window position/size/style now in case the user toggles to windowed mode later - WINDOWPLACEMENT* pwp = GetDXUTState().GetWindowedPlacement(); - ZeroMemory( pwp, sizeof( WINDOWPLACEMENT ) ); - pwp->length = sizeof( WINDOWPLACEMENT ); - GetWindowPlacement( DXUTGetHWNDDeviceWindowed(), pwp ); - bool bIsTopmost = ( ( GetWindowLong( DXUTGetHWNDDeviceWindowed(), - GWL_EXSTYLE ) & WS_EX_TOPMOST ) != 0 ); - GetDXUTState().SetTopmostWhileWindowed( bIsTopmost ); - DWORD dwStyle = GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE ); - dwStyle &= ~WS_MAXIMIZE & ~WS_MINIMIZE; // remove minimize/maximize style - GetDXUTState().SetWindowedStyleAtModeChange( dwStyle ); - if( pOldDeviceSettings ) - { - GetDXUTState().SetWindowBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS( - pOldDeviceSettings ) ); - GetDXUTState().SetWindowBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS( - pOldDeviceSettings ) ); - } - } - - // Hide the window to avoid animation of blank windows - ShowWindow( DXUTGetHWNDDeviceFullScreen(), SW_HIDE ); - - // Set FS window style - SetWindowLong( DXUTGetHWNDDeviceFullScreen(), GWL_STYLE, WS_POPUP | WS_SYSMENU ); - - // If using the same window for windowed and fullscreen mode, save and remove menu - if( DXUTGetHWNDDeviceFullScreen() == DXUTGetHWNDDeviceWindowed() ) - { - HMENU hMenu = GetMenu( DXUTGetHWNDDeviceFullScreen() ); - GetDXUTState().SetMenu( hMenu ); - SetMenu( DXUTGetHWNDDeviceFullScreen(), NULL ); - } - - WINDOWPLACEMENT wpFullscreen; - ZeroMemory( &wpFullscreen, sizeof( WINDOWPLACEMENT ) ); - wpFullscreen.length = sizeof( WINDOWPLACEMENT ); - GetWindowPlacement( DXUTGetHWNDDeviceFullScreen(), &wpFullscreen ); - if( ( wpFullscreen.flags & WPF_RESTORETOMAXIMIZED ) != 0 ) - { - // Restore the window to normal if the window was maximized then minimized. This causes the - // WPF_RESTORETOMAXIMIZED flag to be set which will cause SW_RESTORE to restore the - // window from minimized to maxmized which isn't what we want - wpFullscreen.flags &= ~WPF_RESTORETOMAXIMIZED; - wpFullscreen.showCmd = SW_RESTORE; - SetWindowPlacement( DXUTGetHWNDDeviceFullScreen(), &wpFullscreen ); - } + // Going from fullscreen -> windowed + GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS( + pOldDeviceSettings ) ); + GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS( + pOldDeviceSettings ) ); } } else { - if( DXUTGetIsWindowedFromDS( pNewDeviceSettings ) ) - { - // Going to windowed mode - if( pOldDeviceSettings && !DXUTGetIsWindowedFromDS( pOldDeviceSettings ) ) - { - // Going from fullscreen -> windowed - GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS( - pOldDeviceSettings ) ); - GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS( - pOldDeviceSettings ) ); - //DXGI should handle this, but in the case where switching from d3d9 full screen to windowed d3d11 it does not. - SetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE, GetDXUTState().GetWindowedStyleAtModeChange() ); - - } - } - else + // Going to fullscreen mode + if( !pOldDeviceSettings || ( pOldDeviceSettings && DXUTGetIsWindowedFromDS( pOldDeviceSettings ) ) ) { - // Going to fullscreen mode - if( pOldDeviceSettings == NULL || ( pOldDeviceSettings && DXUTGetIsWindowedFromDS( pOldDeviceSettings ) ) ) + // Transistioning to full screen mode from a standard window so + if( pOldDeviceSettings ) { - // Transistioning to full screen mode from a standard window so - if( pOldDeviceSettings ) - { - GetDXUTState().SetWindowBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS( - pOldDeviceSettings ) ); - GetDXUTState().SetWindowBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS( - pOldDeviceSettings ) ); - } + GetDXUTState().SetWindowBackBufferWidthAtModeChange( DXUTGetBackBufferWidthFromDS( + pOldDeviceSettings ) ); + GetDXUTState().SetWindowBackBufferHeightAtModeChange( DXUTGetBackBufferHeightFromDS( + pOldDeviceSettings ) ); } } } @@ -2185,12 +1931,7 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, DXUTCleanup3DEnvironment( false ); // Create the D3D device and call the app's device callbacks - if( DXUTIsD3D9( pNewDeviceSettings ) ) { - hr = DXUTCreate3DEnvironment9( pd3d9DeviceFromApp ); - } - else { - hr = DXUTCreate3DEnvironment11( pd3d11DeviceFromApp ); - } + hr = DXUTCreate3DEnvironment11(); if( FAILED( hr ) ) { SAFE_DELETE( pOldDeviceSettings ); @@ -2201,7 +1942,7 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, return hr; } - // Enable/disable StickKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut, and Windows key + // Enable/disable StickKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut, and Windows key // to prevent accidental task switching DXUTAllowShortcutKeys( ( DXUTGetIsWindowedFromDS( pNewDeviceSettings ) ) ? GetDXUTState().GetAllowShortcutKeysWhenWindowed() : @@ -2219,10 +1960,10 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, // Going from fullscreen -> windowed // Restore the show state, and positions/size of the window to what it was - // It is important to adjust the window size - // after resetting the device rather than beforehand to ensure + // It is important to adjust the window size + // after resetting the device rather than beforehand to ensure // that the monitor resolution is correct and does not limit the size of the new window. - WINDOWPLACEMENT* pwp = GetDXUTState().GetWindowedPlacement(); + auto pwp = GetDXUTState().GetWindowedPlacement(); SetWindowPlacement( DXUTGetHWNDDeviceWindowed(), pwp ); // Also restore the z-order of window to previous state @@ -2231,9 +1972,9 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSIZE ); } - // Check to see if the window needs to be resized. + // Check to see if the window needs to be resized. // Handle cases where the window is minimized and maxmimized as well. - + bool bNeedToResize = false; if( DXUTGetIsWindowedFromDS( pNewDeviceSettings ) && // only resize if in windowed mode !bKeepCurrentWindowSize ) // only resize if pp.BackbufferWidth/Height were not 0 @@ -2242,8 +1983,8 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, UINT nClientHeight; if( IsIconic( DXUTGetHWNDDeviceWindowed() ) ) { - // Window is currently minimized. To tell if it needs to resize, - // get the client rect of window when its restored the + // Window is currently minimized. To tell if it needs to resize, + // get the client rect of window when its restored the // hard way using GetWindowPlacement() WINDOWPLACEMENT wp; ZeroMemory( &wp, sizeof( WINDOWPLACEMENT ) ); @@ -2253,8 +1994,8 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, if( ( wp.flags & WPF_RESTORETOMAXIMIZED ) != 0 && wp.showCmd == SW_SHOWMINIMIZED ) { // WPF_RESTORETOMAXIMIZED means that when the window is restored it will - // be maximized. So maximize the window temporarily to get the client rect - // when the window is maximized. GetSystemMetrics( SM_CXMAXIMIZED ) will give this + // be maximized. So maximize the window temporarily to get the client rect + // when the window is maximized. GetSystemMetrics( SM_CXMAXIMIZED ) will give this // information if the window is on the primary but this will work on multimon. ShowWindow( DXUTGetHWNDDeviceWindowed(), SW_RESTORE ); RECT rcClient; @@ -2265,10 +2006,10 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, } else { - // Use wp.rcNormalPosition to get the client rect, but wp.rcNormalPosition + // Use wp.rcNormalPosition to get the client rect, but wp.rcNormalPosition // includes the window frame so subtract it - RECT rcFrame = {0}; - AdjustWindowRect( &rcFrame, GetDXUTState().GetWindowedStyleAtModeChange(), GetDXUTState().GetMenu() != NULL ); + RECT rcFrame = {}; + AdjustWindowRect( &rcFrame, GetDXUTState().GetWindowedStyleAtModeChange(), GetDXUTState().GetMenu() != 0 ); LONG nFrameWidth = rcFrame.right - rcFrame.left; LONG nFrameHeight = rcFrame.bottom - rcFrame.top; nClientWidth = ( UINT )( wp.rcNormalPosition.right - wp.rcNormalPosition.left - nFrameWidth ); @@ -2313,8 +2054,8 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, { if( hWindowMonitor == hAdapterMonitor && IsZoomed( DXUTGetHWNDDeviceWindowed() ) ) { - // If the window is maximized and on the same monitor as the adapter, then - // no need to clip to single adapter as the window is already clipped + // If the window is maximized and on the same monitor as the adapter, then + // no need to clip to single adapter as the window is already clipped // even though the rcWindow rect is outside of the miAdapter.rcWork } else @@ -2325,7 +2066,7 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, } } - // Only resize window if needed + // Only resize window if needed if( bNeedToResize ) { @@ -2366,7 +2107,7 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, rcResizedWindow.top = 0; rcResizedWindow.bottom = nClientHeight; AdjustWindowRect( &rcResizedWindow, GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE ), - GetDXUTState().GetMenu() != NULL ); + GetDXUTState().GetMenu() != 0 ); int nWindowWidth = rcResizedWindow.right - rcResizedWindow.left; int nWindowHeight = rcResizedWindow.bottom - rcResizedWindow.top; @@ -2390,8 +2131,8 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, rcResizedWindow.bottom = miAdapter.rcWork.top + nWindowOffsetY + nWindowHeight; } - // Resize the window. It is important to adjust the window size - // after resetting the device rather than beforehand to ensure + // Resize the window. It is important to adjust the window size + // after resetting the device rather than beforehand to ensure // that the monitor resolution is correct and does not limit the size of the new window. SetWindowPos( DXUTGetHWNDDeviceWindowed(), 0, rcResizedWindow.left, rcResizedWindow.top, nWindowWidth, nWindowHeight, SWP_NOZORDER ); @@ -2399,21 +2140,21 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, else { // Make a window rect with a client rect that is the same size as the backbuffer - RECT rcWindow = {0}; + RECT rcWindow = {}; rcWindow.right = (long)( DXUTGetBackBufferWidthFromDS(pNewDeviceSettings) ); rcWindow.bottom = (long)( DXUTGetBackBufferHeightFromDS(pNewDeviceSettings) ); - AdjustWindowRect( &rcWindow, GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE ), GetDXUTState().GetMenu() != NULL ); + AdjustWindowRect( &rcWindow, GetWindowLong( DXUTGetHWNDDeviceWindowed(), GWL_STYLE ), GetDXUTState().GetMenu() != 0 ); - // Resize the window. It is important to adjust the window size - // after resetting the device rather than beforehand to ensure + // Resize the window. It is important to adjust the window size + // after resetting the device rather than beforehand to ensure // that the monitor resolution is correct and does not limit the size of the new window. int cx = ( int )( rcWindow.right - rcWindow.left ); int cy = ( int )( rcWindow.bottom - rcWindow.top ); SetWindowPos( DXUTGetHWNDDeviceWindowed(), 0, 0, 0, cx, cy, SWP_NOZORDER | SWP_NOMOVE ); } - // Its possible that the new window size is not what we asked for. - // No window can be sized larger than the desktop, so see if the Windows OS resized the + // Its possible that the new window size is not what we asked for. + // No window can be sized larger than the desktop, so see if the Windows OS resized the // window to something smaller to fit on the desktop. Also if WM_GETMINMAXINFO // will put a limit on the smallest/largest window size. RECT rcClient; @@ -2423,13 +2164,13 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, if( nClientWidth != DXUTGetBackBufferWidthFromDS( pNewDeviceSettings ) || nClientHeight != DXUTGetBackBufferHeightFromDS( pNewDeviceSettings ) ) { - // If its different, then resize the backbuffer again. This time create a backbuffer that matches the + // If its different, then resize the backbuffer again. This time create a backbuffer that matches the // client rect of the current window w/o resizing the window. - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - if( DXUTIsD3D9( &deviceSettings ) ) deviceSettings.d3d9.pp.BackBufferWidth = 0; else deviceSettings.d3d11.sd.BufferDesc.Width = 0; - if( DXUTIsD3D9( &deviceSettings ) ) deviceSettings.d3d9.pp.BackBufferHeight = 0; else deviceSettings.d3d11.sd.BufferDesc.Height = 0; + auto deviceSettings = DXUTGetDeviceSettings(); + deviceSettings.d3d11.sd.BufferDesc.Width = 0; + deviceSettings.d3d11.sd.BufferDesc.Height = 0; - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, bClipWindowToSingleAdapter ); + hr = DXUTChangeDevice( &deviceSettings, bClipWindowToSingleAdapter ); if( FAILED( hr ) ) { SAFE_DELETE( pOldDeviceSettings ); @@ -2442,8 +2183,8 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, } //if (DXUTGetIsWindowedFromDS( pNewDeviceSettings )) { - // RECT rcFrame = {0}; - // AdjustWindowRect( &rcFrame, GetDXUTState().GetWindowedStyleAtModeChange(), GetDXUTState().GetMenu() != NULL ); + // RECT rcFrame = {}; + // AdjustWindowRect( &rcFrame, GetDXUTState().GetWindowedStyleAtModeChange(), GetDXUTState().GetMenu() ); // } // Make the window visible @@ -2466,920 +2207,96 @@ HRESULT DXUTChangeDevice( DXUTDeviceSettings* pNewDeviceSettings, //-------------------------------------------------------------------------------------- -// Creates a DXGI factory object if one has not already been created +// Creates a DXGI factory object if one has not already been created //-------------------------------------------------------------------------------------- HRESULT DXUTDelayLoadDXGI() { - IDXGIFactory1* pDXGIFactory = GetDXUTState().GetDXGIFactory(); - if( pDXGIFactory == NULL ) + auto pDXGIFactory = GetDXUTState().GetDXGIFactory(); + if( !pDXGIFactory ) { - DXUT_Dynamic_CreateDXGIFactory1( __uuidof( IDXGIFactory1 ), ( LPVOID* )&pDXGIFactory ); - GetDXUTState().SetDXGIFactory( pDXGIFactory ); - if( pDXGIFactory == NULL ) - { - // If still NULL, then DXGI is not availible - GetDXUTState().SetD3D11Available( false ); - return DXUTERR_NODIRECT3D11; - } - - // DXGI 1.1 implies Direct3D 11 - - GetDXUTState().SetD3D11Available( true ); - } - - return S_OK; -} - + HRESULT hr = DXUT_Dynamic_CreateDXGIFactory1( IID_PPV_ARGS(&pDXGIFactory) ); + if ( FAILED(hr) ) + return hr; -//-------------------------------------------------------------------------------------- -// Creates a Direct3D object if one has not already been created -//-------------------------------------------------------------------------------------- -HRESULT DXUTDelayLoadD3D9() -{ - IDirect3D9* pD3D = GetDXUTState().GetD3D9(); - if( pD3D == NULL ) - { - // This may fail if Direct3D 9 isn't installed - // This may also fail if the Direct3D headers are somehow out of sync with the installed Direct3D DLLs - pD3D = DXUT_Dynamic_Direct3DCreate9( D3D_SDK_VERSION ); - if( pD3D == NULL ) + GetDXUTState().SetDXGIFactory( pDXGIFactory ); + if( !pDXGIFactory ) { - // If still NULL, then D3D9 is not availible return DXUTERR_NODIRECT3D; } - GetDXUTState().SetD3D9( pD3D ); + // DXGI 1.1 implies Direct3D 11 } return S_OK; } - //-------------------------------------------------------------------------------------- -// Updates the device settings with default values.. +// Updates the device settings with default values.. //-------------------------------------------------------------------------------------- -void DXUTUpdateDeviceSettingsWithOverrides( DXUTDeviceSettings* pDeviceSettings ) +void DXUTUpdateDeviceSettingsWithOverrides( _Inout_ DXUTDeviceSettings* pDeviceSettings ) { // Override with settings from the command line if( GetDXUTState().GetOverrideWidth() != 0 ) { - pDeviceSettings->d3d9.pp.BackBufferWidth = GetDXUTState().GetOverrideWidth(); pDeviceSettings->d3d11.sd.BufferDesc.Width = GetDXUTState().GetOverrideWidth(); } if( GetDXUTState().GetOverrideHeight() != 0 ) { - pDeviceSettings->d3d9.pp.BackBufferHeight = GetDXUTState().GetOverrideHeight(); pDeviceSettings->d3d11.sd.BufferDesc.Height = GetDXUTState().GetOverrideHeight(); } if( GetDXUTState().GetOverrideAdapterOrdinal() != -1 ) { - pDeviceSettings->d3d9.AdapterOrdinal = GetDXUTState().GetOverrideAdapterOrdinal(); pDeviceSettings->d3d11.AdapterOrdinal = GetDXUTState().GetOverrideAdapterOrdinal(); } if( GetDXUTState().GetOverrideFullScreen() ) { - pDeviceSettings->d3d9.pp.Windowed = FALSE; pDeviceSettings->d3d11.sd.Windowed = FALSE; } - if( GetDXUTState().GetOverrideWindowed() ) { - pDeviceSettings->d3d9.pp.Windowed = TRUE; + if( GetDXUTState().GetOverrideWindowed() ) + { pDeviceSettings->d3d11.sd.Windowed = TRUE; } if( GetDXUTState().GetOverrideForceHAL() ) { - pDeviceSettings->d3d9.DeviceType = D3DDEVTYPE_HAL; pDeviceSettings->d3d11.DriverType = D3D_DRIVER_TYPE_HARDWARE; } if( GetDXUTState().GetOverrideForceREF() ) { - pDeviceSettings->d3d9.DeviceType = D3DDEVTYPE_REF; pDeviceSettings->d3d11.DriverType = D3D_DRIVER_TYPE_REFERENCE; } + if( GetDXUTState().GetOverrideForceWARP() ) + { + pDeviceSettings->d3d11.DriverType = D3D_DRIVER_TYPE_WARP; + pDeviceSettings->d3d11.sd.Windowed = TRUE; + } + if( GetDXUTState().GetOverrideForceVsync() == 0 ) { - pDeviceSettings->d3d9.pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; pDeviceSettings->d3d11.SyncInterval = 0; } else if( GetDXUTState().GetOverrideForceVsync() == 1 ) { - pDeviceSettings->d3d9.pp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT; pDeviceSettings->d3d11.SyncInterval = 1; } - if( GetDXUTState().GetOverrideForceAPI() != -1 ) - { - if( GetDXUTState().GetOverrideForceAPI() == 9 ) - { - pDeviceSettings->ver = DXUT_D3D9_DEVICE; - } - else if( GetDXUTState().GetOverrideForceAPI() == 11 ) - { - pDeviceSettings->ver = DXUT_D3D11_DEVICE; - } - } - - if (GetDXUTState().GetOverrideForceFeatureLevel() != 0) { - pDeviceSettings->d3d11.DeviceFeatureLevel = (D3D_FEATURE_LEVEL)GetDXUTState().GetOverrideForceFeatureLevel(); - } -} - - -//-------------------------------------------------------------------------------------- -// Allows the app to explictly state if it supports D3D9 or D3D11. Typically -// calling this is not needed as DXUT will auto-detect this based on the callbacks set. -//-------------------------------------------------------------------------------------- -void WINAPI DXUTSetD3DVersionSupport( bool bAppCanUseD3D9, bool bAppCanUseD3D11 ) -{ - GetDXUTState().SetUseD3DVersionOverride( true ); - GetDXUTState().SetAppSupportsD3D9Override( bAppCanUseD3D9 ); - GetDXUTState().SetAppSupportsD3D11Override( bAppCanUseD3D11 ); -} - - -//-------------------------------------------------------------------------------------- -// Returns true if app has registered any D3D9 callbacks or -// used the DXUTSetD3DVersionSupport API and passed true for bAppCanUseD3D9 -//-------------------------------------------------------------------------------------- -bool WINAPI DXUTDoesAppSupportD3D9() -{ - if( GetDXUTState().GetUseD3DVersionOverride() ) - return GetDXUTState().GetAppSupportsD3D9Override(); - else - return GetDXUTState().GetIsD3D9DeviceAcceptableFunc() || - GetDXUTState().GetD3D9DeviceCreatedFunc() || - GetDXUTState().GetD3D9DeviceResetFunc() || - GetDXUTState().GetD3D9DeviceLostFunc() || - GetDXUTState().GetD3D9DeviceDestroyedFunc() || - GetDXUTState().GetD3D9FrameRenderFunc(); -} - - -//-------------------------------------------------------------------------------------- -// Returns true if app has registered any D3D11 callbacks or -// used the DXUTSetD3DVersionSupport API and passed true for bAppCanUseD3D11 -//-------------------------------------------------------------------------------------- -bool WINAPI DXUTDoesAppSupportD3D11() -{ - if( GetDXUTState().GetUseD3DVersionOverride() ) - return GetDXUTState().GetAppSupportsD3D11Override(); - else - return GetDXUTState().GetIsD3D11DeviceAcceptableFunc() || - GetDXUTState().GetD3D11DeviceCreatedFunc() || - GetDXUTState().GetD3D11SwapChainResizedFunc() || - GetDXUTState().GetD3D11FrameRenderFunc() || - GetDXUTState().GetD3D11SwapChainReleasingFunc() || - GetDXUTState().GetD3D11DeviceDestroyedFunc(); -} - - -//====================================================================================== -//====================================================================================== -// Direct3D 9 section -//====================================================================================== -//====================================================================================== - - -//-------------------------------------------------------------------------------------- -// Passes a previously created Direct3D9 device for use by the framework. -// If DXUTCreateWindow() has not already been called, it will call it with the -// default parameters. Instead of calling this, you can call DXUTCreateDevice() or -// DXUTCreateDeviceFromSettings() -//-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTSetD3D9Device( IDirect3DDevice9* pd3dDevice ) -{ - HRESULT hr; - - if( pd3dDevice == NULL ) - return DXUT_ERR_MSGBOX( L"DXUTSetD3D9Device", E_INVALIDARG ); - - // Not allowed to call this from inside the device callbacks - if( GetDXUTState().GetInsideDeviceCallback() ) - return DXUT_ERR_MSGBOX( L"DXUTSetD3D9Device", E_FAIL ); - - GetDXUTState().SetDeviceCreateCalled( true ); - - // If DXUTCreateWindow() or DXUTSetWindow() has not already been called, - // then call DXUTCreateWindow() with the default parameters. - if( !GetDXUTState().GetWindowCreated() ) - { - // If DXUTCreateWindow() or DXUTSetWindow() was already called and failed, then fail. - // DXUTCreateWindow() or DXUTSetWindow() must first succeed for this function to succeed - if( GetDXUTState().GetWindowCreateCalled() ) - return E_FAIL; - - // If DXUTCreateWindow() or DXUTSetWindow() hasn't been called, then - // automatically call DXUTCreateWindow() with default params - hr = DXUTCreateWindow(); - if( FAILED( hr ) ) - return hr; - } - - DXUTDeviceSettings DeviceSettings; - ZeroMemory( &DeviceSettings, sizeof( DXUTDeviceSettings ) ); - DeviceSettings.ver = DXUT_D3D9_DEVICE; - - // Get the present params from the swap chain - IDirect3DSurface9* pBackBuffer = NULL; - hr = pd3dDevice->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer ); - if( SUCCEEDED( hr ) ) - { - IDirect3DSwapChain9* pSwapChain = NULL; - hr = pBackBuffer->GetContainer( IID_IDirect3DSwapChain9, ( void** )&pSwapChain ); - if( SUCCEEDED( hr ) ) - { - pSwapChain->GetPresentParameters( &DeviceSettings.d3d9.pp ); - SAFE_RELEASE( pSwapChain ); - } - - SAFE_RELEASE( pBackBuffer ); - } - - D3DDEVICE_CREATION_PARAMETERS d3dCreationParams; - pd3dDevice->GetCreationParameters( &d3dCreationParams ); - - // Fill out the rest of the device settings struct - DeviceSettings.d3d9.AdapterOrdinal = d3dCreationParams.AdapterOrdinal; - DeviceSettings.d3d9.DeviceType = d3dCreationParams.DeviceType; - DXUTFindD3D9AdapterFormat( DeviceSettings.d3d9.AdapterOrdinal, DeviceSettings.d3d9.DeviceType, - DeviceSettings.d3d9.pp.BackBufferFormat, DeviceSettings.d3d9.pp.Windowed, - &DeviceSettings.d3d9.AdapterFormat ); - DeviceSettings.d3d9.BehaviorFlags = d3dCreationParams.BehaviorFlags; - - // Change to the Direct3D device passed in - hr = DXUTChangeDevice( &DeviceSettings, pd3dDevice, NULL, false, false ); - if( FAILED( hr ) ) - return hr; - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -// Creates the 3D environment -//-------------------------------------------------------------------------------------- -HRESULT DXUTCreate3DEnvironment9( IDirect3DDevice9* pd3dDeviceFromApp ) -{ - HRESULT hr = S_OK; - - IDirect3DDevice9* pd3dDevice = NULL; - DXUTDeviceSettings* pNewDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - assert( pNewDeviceSettings != NULL ); - - // Only create a Direct3D device if one hasn't been supplied by the app - if( pd3dDeviceFromApp == NULL ) - { - // Try to create the device with the chosen settings - IDirect3D9* pD3D = DXUTGetD3D9Object(); - assert( pD3D != NULL ); - hr = pD3D->CreateDevice( pNewDeviceSettings->d3d9.AdapterOrdinal, pNewDeviceSettings->d3d9.DeviceType, - DXUTGetHWNDFocus(), pNewDeviceSettings->d3d9.BehaviorFlags, - &pNewDeviceSettings->d3d9.pp, &pd3dDevice ); - if( hr == D3DERR_DEVICELOST ) - { - GetDXUTState().SetDeviceLost( true ); - return S_OK; - } - else if( FAILED( hr ) ) - { - DXUT_ERR( L"CreateDevice", hr ); - return DXUTERR_CREATINGDEVICE; - } - } - else - { - pd3dDeviceFromApp->AddRef(); - pd3dDevice = pd3dDeviceFromApp; - } - - GetDXUTState().SetD3D9Device( pd3dDevice ); - - // If switching to REF, set the exit code to 10. If switching to HAL and exit code was 10, then set it back to 0. - if( pNewDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF && GetDXUTState().GetExitCode() == 0 ) - GetDXUTState().SetExitCode( 10 ); - else if( pNewDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_HAL && GetDXUTState().GetExitCode() == 10 ) - GetDXUTState().SetExitCode( 0 ); - - // Update back buffer desc before calling app's device callbacks - DXUTUpdateBackBufferDesc(); - - // Setup cursor based on current settings (window/fullscreen mode, show cursor state, clip cursor state) - DXUTSetupCursor(); - - // Update GetDXUTState()'s copy of D3D caps - D3DCAPS9* pd3dCaps = GetDXUTState().GetCaps(); - pd3dDevice->GetDeviceCaps( pd3dCaps ); - - // Update the device stats text - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration(); - assert( pd3dEnum != NULL ); - CD3D9EnumAdapterInfo* pAdapterInfo = pd3dEnum->GetAdapterInfo( pNewDeviceSettings->d3d9.AdapterOrdinal ); - DXUTUpdateD3D9DeviceStats( pNewDeviceSettings->d3d9.DeviceType, - pNewDeviceSettings->d3d9.BehaviorFlags, - &pAdapterInfo->AdapterIdentifier ); - - // Call the app's device created callback if non-NULL - const D3DSURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetD3D9BackBufferSurfaceDesc(); - GetDXUTState().SetInsideDeviceCallback( true ); - LPDXUTCALLBACKD3D9DEVICECREATED pCallbackDeviceCreated = GetDXUTState().GetD3D9DeviceCreatedFunc(); - hr = S_OK; - if( pCallbackDeviceCreated != NULL ) - hr = pCallbackDeviceCreated( DXUTGetD3D9Device(), pBackBufferSurfaceDesc, - GetDXUTState().GetD3D9DeviceCreatedFuncUserContext() ); - GetDXUTState().SetInsideDeviceCallback( false ); - if( DXUTGetD3D9Device() == NULL ) // Handle DXUTShutdown from inside callback - return E_FAIL; - if( FAILED( hr ) ) - { - DXUT_ERR( L"DeviceCreated callback", hr ); - return ( hr == DXUTERR_MEDIANOTFOUND ) ? DXUTERR_MEDIANOTFOUND : DXUTERR_CREATINGDEVICEOBJECTS; - } - GetDXUTState().SetDeviceObjectsCreated( true ); - - // Call the app's device reset callback if non-NULL - GetDXUTState().SetInsideDeviceCallback( true ); - LPDXUTCALLBACKD3D9DEVICERESET pCallbackDeviceReset = GetDXUTState().GetD3D9DeviceResetFunc(); - hr = S_OK; - if( pCallbackDeviceReset != NULL ) - hr = pCallbackDeviceReset( DXUTGetD3D9Device(), pBackBufferSurfaceDesc, - GetDXUTState().GetD3D9DeviceResetFuncUserContext() ); - GetDXUTState().SetInsideDeviceCallback( false ); - if( DXUTGetD3D9Device() == NULL ) // Handle DXUTShutdown from inside callback - return E_FAIL; - if( FAILED( hr ) ) - { - DXUT_ERR( L"DeviceReset callback", hr ); - return ( hr == DXUTERR_MEDIANOTFOUND ) ? DXUTERR_MEDIANOTFOUND : DXUTERR_RESETTINGDEVICEOBJECTS; - } - GetDXUTState().SetDeviceObjectsReset( true ); - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -// Resets the 3D environment by: -// - Calls the device lost callback -// - Resets the device -// - Stores the back buffer description -// - Sets up the full screen Direct3D cursor if requested -// - Calls the device reset callback -//-------------------------------------------------------------------------------------- -HRESULT DXUTReset3DEnvironment9() -{ - HRESULT hr; - - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - assert( pd3dDevice != NULL ); - - // Call the app's device lost callback - if( GetDXUTState().GetDeviceObjectsReset() == true ) - { - GetDXUTState().SetInsideDeviceCallback( true ); - LPDXUTCALLBACKD3D9DEVICELOST pCallbackDeviceLost = GetDXUTState().GetD3D9DeviceLostFunc(); - if( pCallbackDeviceLost != NULL ) - pCallbackDeviceLost( GetDXUTState().GetD3D9DeviceLostFuncUserContext() ); - GetDXUTState().SetDeviceObjectsReset( false ); - GetDXUTState().SetInsideDeviceCallback( false ); - } - - // Reset the device - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - hr = pd3dDevice->Reset( &pDeviceSettings->d3d9.pp ); - if( FAILED( hr ) ) - { - if( hr == D3DERR_DEVICELOST ) - return D3DERR_DEVICELOST; // Reset could legitimately fail if the device is lost - else - return DXUT_ERR( L"Reset", DXUTERR_RESETTINGDEVICE ); - } - - // Update back buffer desc before calling app's device callbacks - DXUTUpdateBackBufferDesc(); - - // Setup cursor based on current settings (window/fullscreen mode, show cursor state, clip cursor state) - DXUTSetupCursor(); - - // Call the app's OnDeviceReset callback - GetDXUTState().SetInsideDeviceCallback( true ); - const D3DSURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetD3D9BackBufferSurfaceDesc(); - LPDXUTCALLBACKD3D9DEVICERESET pCallbackDeviceReset = GetDXUTState().GetD3D9DeviceResetFunc(); - hr = S_OK; - if( pCallbackDeviceReset != NULL ) - hr = pCallbackDeviceReset( pd3dDevice, pBackBufferSurfaceDesc, - GetDXUTState().GetD3D9DeviceResetFuncUserContext() ); - GetDXUTState().SetInsideDeviceCallback( false ); - if( FAILED( hr ) ) + if (GetDXUTState().GetOverrideForceFeatureLevel() != 0) { - // If callback failed, cleanup - DXUT_ERR( L"DeviceResetCallback", hr ); - if( hr != DXUTERR_MEDIANOTFOUND ) - hr = DXUTERR_RESETTINGDEVICEOBJECTS; - - GetDXUTState().SetInsideDeviceCallback( true ); - LPDXUTCALLBACKD3D9DEVICELOST pCallbackDeviceLost = GetDXUTState().GetD3D9DeviceLostFunc(); - if( pCallbackDeviceLost != NULL ) - pCallbackDeviceLost( GetDXUTState().GetD3D9DeviceLostFuncUserContext() ); - GetDXUTState().SetInsideDeviceCallback( false ); - return hr; + pDeviceSettings->d3d11.DeviceFeatureLevel = GetDXUTState().GetOverrideForceFeatureLevel(); } - - // Success - GetDXUTState().SetDeviceObjectsReset( true ); - - return S_OK; } //-------------------------------------------------------------------------------------- -// Render the 3D environment by: -// - Checking if the device is lost and trying to reset it if it is -// - Get the elapsed time since the last frame -// - Calling the app's framemove and render callback -// - Calling Present() -//-------------------------------------------------------------------------------------- -void DXUTRender3DEnvironment9() -{ - HRESULT hr; - - if( GetDXUTState().GetDeviceLost() || DXUTIsRenderingPaused() || !DXUTIsActive() ) - { - // Window is minimized or paused so yield CPU time to other processes - Sleep( 50 ); - } - - // If no device created yet because device was lost (ie. another fullscreen exclusive device exists), - // then wait and try to create every so often. - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - if( NULL == pd3dDevice ) - { - if( GetDXUTState().GetDeviceLost() ) - { - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - DXUTChangeDevice( &deviceSettings, NULL, NULL, false, true ); - } - - return; - } - - if( GetDXUTState().GetDeviceLost() && !GetDXUTState().GetRenderingPaused() ) - { - // Test the cooperative level to see if it's okay to render. - if( FAILED( hr = pd3dDevice->TestCooperativeLevel() ) ) - { - if( D3DERR_DEVICELOST == hr ) - { - // The device has been lost but cannot be reset at this time. - // So wait until it can be reset. - return; - } - - // If we are windowed, read the desktop format and - // ensure that the Direct3D device is using the same format - // since the user could have changed the desktop bitdepth - if( DXUTIsWindowed() ) - { - D3DDISPLAYMODE adapterDesktopDisplayMode; - IDirect3D9* pD3D = DXUTGetD3D9Object(); - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - pD3D->GetAdapterDisplayMode( pDeviceSettings->d3d9.AdapterOrdinal, &adapterDesktopDisplayMode ); - if( pDeviceSettings->d3d9.AdapterFormat != adapterDesktopDisplayMode.Format ) - { - - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - deviceSettings.d3d9.AdapterFormat = adapterDesktopDisplayMode.Format; - - hr = DXUTSnapDeviceSettingsToEnumDevice(&deviceSettings, false); - if( FAILED( hr ) ) // the call will fail if no valid devices were found - { - DXUTDisplayErrorMessage( DXUTERR_NOCOMPATIBLEDEVICES ); - DXUTShutdown(); - } - - // Change to a Direct3D device created from the new device settings. - // If there is an existing device, then either reset or recreate the scene - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false ); - if( FAILED( hr ) ) - { - // If this fails, try to go fullscreen and if this fails also shutdown. - if( FAILED( DXUTToggleFullScreen() ) ) - DXUTShutdown(); - } - - return; - } - } - - // Try to reset the device - if( FAILED( hr = DXUTReset3DEnvironment9() ) ) - { - if( D3DERR_DEVICELOST == hr ) - { - // The device was lost again, so continue waiting until it can be reset. - return; - } - else if( DXUTERR_RESETTINGDEVICEOBJECTS == hr || - DXUTERR_MEDIANOTFOUND == hr ) - { - DXUTDisplayErrorMessage( hr ); - DXUTShutdown(); - return; - } - else - { - // Reset failed, but the device wasn't lost so something bad happened, - // so recreate the device to try to recover - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - if( FAILED( DXUTChangeDevice( pDeviceSettings, NULL, NULL, true, false ) ) ) - { - DXUTShutdown(); - return; - } - } - } - } - - GetDXUTState().SetDeviceLost( false ); - } - - // Get the app's time, in seconds. Skip rendering if no time elapsed - double fTime, fAbsTime; float fElapsedTime; - DXUTGetGlobalTimer()->GetTimeValues( &fTime, &fAbsTime, &fElapsedTime ); - - // Store the time for the app - if( GetDXUTState().GetConstantFrameTime() ) - { - fElapsedTime = GetDXUTState().GetTimePerFrame(); - fTime = DXUTGetTime() + fElapsedTime; - } - - GetDXUTState().SetTime( fTime ); - GetDXUTState().SetAbsoluteTime( fAbsTime ); - GetDXUTState().SetElapsedTime( fElapsedTime ); - - // Update the FPS stats - DXUTUpdateFrameStats(); - - DXUTHandleTimers(); - - // Animate the scene by calling the app's frame move callback - LPDXUTCALLBACKFRAMEMOVE pCallbackFrameMove = GetDXUTState().GetFrameMoveFunc(); - if( pCallbackFrameMove != NULL ) - { - pCallbackFrameMove( fTime, fElapsedTime, GetDXUTState().GetFrameMoveFuncUserContext() ); - pd3dDevice = DXUTGetD3D9Device(); - if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback - return; - } - - if( !GetDXUTState().GetRenderingPaused() ) - { - // Render the scene by calling the app's render callback - LPDXUTCALLBACKD3D9FRAMERENDER pCallbackFrameRender = GetDXUTState().GetD3D9FrameRenderFunc(); - if( pCallbackFrameRender != NULL ) - { - pCallbackFrameRender( pd3dDevice, fTime, fElapsedTime, - GetDXUTState().GetD3D9FrameRenderFuncUserContext() ); - pd3dDevice = DXUTGetD3D9Device(); - if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback - return; - } - -#if defined(DEBUG) || defined(_DEBUG) - // The back buffer should always match the client rect - // if the Direct3D backbuffer covers the entire window - RECT rcClient; - GetClientRect( DXUTGetHWND(), &rcClient ); - if( !IsIconic( DXUTGetHWND() ) ) - { - GetClientRect( DXUTGetHWND(), &rcClient ); - assert( DXUTGetD3D9BackBufferSurfaceDesc()->Width == (UINT)rcClient.right ); - assert( DXUTGetD3D9BackBufferSurfaceDesc()->Height == (UINT)rcClient.bottom ); - } -#endif - - // Show the frame on the primary surface. - hr = pd3dDevice->Present( NULL, NULL, NULL, NULL ); - if( FAILED( hr ) ) - { - if( D3DERR_DEVICELOST == hr ) - { - GetDXUTState().SetDeviceLost( true ); - } - else if( D3DERR_DRIVERINTERNALERROR == hr ) - { - // When D3DERR_DRIVERINTERNALERROR is returned from Present(), - // the application can do one of the following: - // - // - End, with the pop-up window saying that the application cannot continue - // because of problems in the display adapter and that the user should - // contact the adapter manufacturer. - // - // - Attempt to restart by calling IDirect3DDevice9::Reset, which is essentially the same - // path as recovering from a lost device. If IDirect3DDevice9::Reset fails with - // D3DERR_DRIVERINTERNALERROR, the application should end immediately with the message - // that the user should contact the adapter manufacturer. - // - // The framework attempts the path of resetting the device - // - GetDXUTState().SetDeviceLost( true ); - } - } - } - - // If the app called DXUTWasKeyPressed() then do the work - // to store the current state of the keys in bLastKeys - if( GetDXUTState().GetAppCalledWasKeyPressed() ) - { - bool* bLastKeys = GetDXUTState().GetLastKeys(); - bool* bKeys = GetDXUTState().GetKeys(); - memcpy( bLastKeys, bKeys, sizeof( bool ) * 256 ); - } - - // Update current frame # - int nFrame = GetDXUTState().GetCurrentFrameNumber(); - nFrame++; - GetDXUTState().SetCurrentFrameNumber( nFrame ); - - // Check to see if the app should shutdown due to cmdline - if( GetDXUTState().GetOverrideQuitAfterFrame() != 0 ) - { - if( nFrame > GetDXUTState().GetOverrideQuitAfterFrame() ) - DXUTShutdown(); - } - - return; -} - - -//-------------------------------------------------------------------------------------- -// Cleans up the 3D environment by: -// - Calls the device lost callback -// - Calls the device destroyed callback -// - Releases the D3D device -//-------------------------------------------------------------------------------------- -void DXUTCleanup3DEnvironment9( bool bReleaseSettings ) -{ - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - if( pd3dDevice != NULL ) - { - GetDXUTState().SetInsideDeviceCallback( true ); - - // Call the app's device lost callback - if( GetDXUTState().GetDeviceObjectsReset() == true ) - { - LPDXUTCALLBACKD3D9DEVICELOST pCallbackDeviceLost = GetDXUTState().GetD3D9DeviceLostFunc(); - if( pCallbackDeviceLost != NULL ) - pCallbackDeviceLost( GetDXUTState().GetD3D9DeviceLostFuncUserContext() ); - GetDXUTState().SetDeviceObjectsReset( false ); - } - - // Call the app's device destroyed callback - if( GetDXUTState().GetDeviceObjectsCreated() == true ) - { - LPDXUTCALLBACKD3D9DEVICEDESTROYED pCallbackDeviceDestroyed = GetDXUTState().GetD3D9DeviceDestroyedFunc(); - if( pCallbackDeviceDestroyed != NULL ) - pCallbackDeviceDestroyed( GetDXUTState().GetD3D9DeviceDestroyedFuncUserContext() ); - GetDXUTState().SetDeviceObjectsCreated( false ); - } - - GetDXUTState().SetInsideDeviceCallback( false ); - - // Release the D3D device and in debug configs, displays a message box if there - // are unrelease objects. - if( pd3dDevice ) - { - UINT references = pd3dDevice->Release(); - if( references > 0 ) - { - DXUTDisplayErrorMessage( DXUTERR_NONZEROREFCOUNT ); - DXUT_ERR( L"DXUTCleanup3DEnvironment", DXUTERR_NONZEROREFCOUNT ); - } - } - GetDXUTState().SetD3D9Device( NULL ); - - if( bReleaseSettings ) - { - DXUTDeviceSettings* pOldDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - SAFE_DELETE(pOldDeviceSettings); - GetDXUTState().SetCurrentDeviceSettings( NULL ); - } - - D3DSURFACE_DESC* pBackBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDesc9(); - ZeroMemory( pBackBufferSurfaceDesc, sizeof( D3DSURFACE_DESC ) ); - - D3DCAPS9* pd3dCaps = GetDXUTState().GetCaps(); - ZeroMemory( pd3dCaps, sizeof( D3DCAPS9 ) ); - - GetDXUTState().SetDeviceCreated( false ); - } -} - - -//-------------------------------------------------------------------------------------- -// Gives the D3D device a cursor with image and hotspot from hCursor. -//-------------------------------------------------------------------------------------- -HRESULT DXUTSetD3D9DeviceCursor( IDirect3DDevice9* pd3dDevice, HCURSOR hCursor, bool bAddWatermark ) -{ - HRESULT hr = E_FAIL; - ICONINFO iconinfo; - bool bBWCursor = false; - LPDIRECT3DSURFACE9 pCursorSurface = NULL; - HDC hdcColor = NULL; - HDC hdcMask = NULL; - HDC hdcScreen = NULL; - BITMAP bm; - DWORD dwWidth = 0; - DWORD dwHeightSrc = 0; - DWORD dwHeightDest = 0; - COLORREF crColor; - COLORREF crMask; - UINT x; - UINT y; - BITMAPINFO bmi; - COLORREF* pcrArrayColor = NULL; - COLORREF* pcrArrayMask = NULL; - DWORD* pBitmap; - HGDIOBJ hgdiobjOld; - - ZeroMemory( &iconinfo, sizeof( iconinfo ) ); - if( !GetIconInfo( hCursor, &iconinfo ) ) - goto End; - - if( 0 == GetObject( ( HGDIOBJ )iconinfo.hbmMask, sizeof( BITMAP ), ( LPVOID )&bm ) ) - goto End; - dwWidth = bm.bmWidth; - dwHeightSrc = bm.bmHeight; - - if( iconinfo.hbmColor == NULL ) - { - bBWCursor = TRUE; - dwHeightDest = dwHeightSrc / 2; - } - else - { - bBWCursor = FALSE; - dwHeightDest = dwHeightSrc; - } - - // Create a surface for the fullscreen cursor - if( FAILED( hr = pd3dDevice->CreateOffscreenPlainSurface( dwWidth, dwHeightDest, - D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &pCursorSurface, - NULL ) ) ) - { - goto End; - } - - pcrArrayMask = new DWORD[dwWidth * dwHeightSrc]; - - ZeroMemory( &bmi, sizeof( bmi ) ); - bmi.bmiHeader.biSize = sizeof( bmi.bmiHeader ); - bmi.bmiHeader.biWidth = dwWidth; - bmi.bmiHeader.biHeight = dwHeightSrc; - bmi.bmiHeader.biPlanes = 1; - bmi.bmiHeader.biBitCount = 32; - bmi.bmiHeader.biCompression = BI_RGB; - - hdcScreen = GetDC( NULL ); - hdcMask = CreateCompatibleDC( hdcScreen ); - if( hdcMask == NULL ) - { - hr = E_FAIL; - goto End; - } - hgdiobjOld = SelectObject( hdcMask, iconinfo.hbmMask ); - GetDIBits( hdcMask, iconinfo.hbmMask, 0, dwHeightSrc, - pcrArrayMask, &bmi, DIB_RGB_COLORS ); - SelectObject( hdcMask, hgdiobjOld ); - - if( !bBWCursor ) - { - pcrArrayColor = new DWORD[dwWidth * dwHeightDest]; - hdcColor = CreateCompatibleDC( hdcScreen ); - if( hdcColor == NULL ) - { - hr = E_FAIL; - goto End; - } - SelectObject( hdcColor, iconinfo.hbmColor ); - GetDIBits( hdcColor, iconinfo.hbmColor, 0, dwHeightDest, - pcrArrayColor, &bmi, DIB_RGB_COLORS ); - } - - // Transfer cursor image into the surface - D3DLOCKED_RECT lr; - pCursorSurface->LockRect( &lr, NULL, 0 ); - pBitmap = ( DWORD* )lr.pBits; - for( y = 0; y < dwHeightDest; y++ ) - { - for( x = 0; x < dwWidth; x++ ) - { - if( bBWCursor ) - { - crColor = pcrArrayMask[dwWidth * ( dwHeightDest - 1 - y ) + x]; - crMask = pcrArrayMask[dwWidth * ( dwHeightSrc - 1 - y ) + x]; - } - else - { - crColor = pcrArrayColor[dwWidth * ( dwHeightDest - 1 - y ) + x]; - crMask = pcrArrayMask[dwWidth * ( dwHeightDest - 1 - y ) + x]; - } - if( crMask == 0 ) - pBitmap[dwWidth * y + x] = 0xff000000 | crColor; - else - pBitmap[dwWidth * y + x] = 0x00000000; - - // It may be helpful to make the D3D cursor look slightly - // different from the Windows cursor so you can distinguish - // between the two when developing/testing code. When - // bAddWatermark is TRUE, the following code adds some - // small grey "D3D" characters to the upper-left corner of - // the D3D cursor image. - if( bAddWatermark && x < 12 && y < 5 ) - { - // 11.. 11.. 11.. .... CCC0 - // 1.1. ..1. 1.1. .... A2A0 - // 1.1. .1.. 1.1. .... A4A0 - // 1.1. ..1. 1.1. .... A2A0 - // 11.. 11.. 11.. .... CCC0 - - const WORD wMask[5] = { 0xccc0, 0xa2a0, 0xa4a0, 0xa2a0, 0xccc0 }; - if( wMask[y] & (1 << (15 - x)) ) - { - pBitmap[dwWidth*y + x] |= 0xff808080; - } - } - } - } - pCursorSurface->UnlockRect(); - - // Set the device cursor - if( FAILED( hr = pd3dDevice->SetCursorProperties( iconinfo.xHotspot, - iconinfo.yHotspot, pCursorSurface ) ) ) - { - goto End; - } - - hr = S_OK; - -End: - if( iconinfo.hbmMask != NULL ) - DeleteObject( iconinfo.hbmMask ); - if( iconinfo.hbmColor != NULL ) - DeleteObject( iconinfo.hbmColor ); - if( hdcScreen != NULL ) - ReleaseDC( NULL, hdcScreen ); - if( hdcColor != NULL ) - DeleteDC( hdcColor ); - if( hdcMask != NULL ) - DeleteDC( hdcMask ); - SAFE_DELETE_ARRAY( pcrArrayColor ); - SAFE_DELETE_ARRAY( pcrArrayMask ); - SAFE_RELEASE( pCursorSurface ); - return hr; -} - - -//-------------------------------------------------------------------------------------- -// Internal helper function to return the adapter format from the first device settings -// combo that matches the passed adapter ordinal, device type, backbuffer format, and windowed. -//-------------------------------------------------------------------------------------- -HRESULT DXUTFindD3D9AdapterFormat( UINT AdapterOrdinal, D3DDEVTYPE DeviceType, D3DFORMAT BackBufferFormat, - BOOL Windowed, D3DFORMAT* pAdapterFormat ) -{ - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration( false ); - assert( pd3dEnum != NULL ); - CD3D9EnumDeviceInfo* pDeviceInfo = pd3dEnum->GetDeviceInfo( AdapterOrdinal, DeviceType ); - if( pDeviceInfo ) - { - for( int iDeviceCombo = 0; iDeviceCombo < pDeviceInfo->deviceSettingsComboList.GetSize(); iDeviceCombo++ ) - { - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = pDeviceInfo->deviceSettingsComboList.GetAt( - iDeviceCombo ); - if( pDeviceSettingsCombo->BackBufferFormat == BackBufferFormat && - pDeviceSettingsCombo->Windowed == Windowed ) - { - // Return the adapter format from the first match - *pAdapterFormat = pDeviceSettingsCombo->AdapterFormat; - return S_OK; - } - } - } - - *pAdapterFormat = BackBufferFormat; - return E_FAIL; -} - -//-------------------------------------------------------------------------------------- // Sets the viewport, render target view, and depth stencil view. //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTSetupD3D11Views( ID3D11DeviceContext* pd3dDeviceContext ) +HRESULT WINAPI DXUTSetupD3D11Views( _In_ ID3D11DeviceContext* pd3dDeviceContext ) { HRESULT hr = S_OK; @@ -3394,8 +2311,8 @@ HRESULT WINAPI DXUTSetupD3D11Views( ID3D11DeviceContext* pd3dDeviceContext ) pd3dDeviceContext->RSSetViewports( 1, &vp ); // Set the render targets - ID3D11RenderTargetView* pRTV = GetDXUTState().GetD3D11RenderTargetView(); - ID3D11DepthStencilView* pDSV = GetDXUTState().GetD3D11DepthStencilView(); + auto pRTV = GetDXUTState().GetD3D11RenderTargetView(); + auto pDSV = GetDXUTState().GetD3D11DepthStencilView(); pd3dDeviceContext->OMSetRenderTargets( 1, &pRTV, pDSV ); return hr; @@ -3405,24 +2322,25 @@ HRESULT WINAPI DXUTSetupD3D11Views( ID3D11DeviceContext* pd3dDeviceContext ) //-------------------------------------------------------------------------------------- // Creates a render target view, and depth stencil texture and view. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT DXUTCreateD3D11Views( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, DXUTDeviceSettings* pDeviceSettings ) { HRESULT hr = S_OK; - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); - ID3D11DepthStencilView* pDSV = NULL; - ID3D11RenderTargetView* pRTV = NULL; + auto pSwapChain = DXUTGetDXGISwapChain(); + ID3D11DepthStencilView* pDSV = nullptr; + ID3D11RenderTargetView* pRTV = nullptr; // Get the back buffer and desc ID3D11Texture2D* pBackBuffer; - hr = pSwapChain->GetBuffer( 0, __uuidof( *pBackBuffer ), ( LPVOID* )&pBackBuffer ); + hr = pSwapChain->GetBuffer( 0, IID_PPV_ARGS(&pBackBuffer) ); if( FAILED( hr ) ) return hr; D3D11_TEXTURE2D_DESC backBufferSurfaceDesc; pBackBuffer->GetDesc( &backBufferSurfaceDesc ); // Create the render target view - hr = pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &pRTV ); + hr = pd3dDevice->CreateRenderTargetView( pBackBuffer, nullptr, &pRTV ); SAFE_RELEASE( pBackBuffer ); if( FAILED( hr ) ) return hr; @@ -3432,7 +2350,7 @@ HRESULT DXUTCreateD3D11Views( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3 if( pDeviceSettings->d3d11.AutoCreateDepthStencil ) { // Create depth stencil texture - ID3D11Texture2D* pDepthStencil = NULL; + ID3D11Texture2D* pDepthStencil = nullptr; D3D11_TEXTURE2D_DESC descDepth; descDepth.Width = backBufferSurfaceDesc.Width; descDepth.Height = backBufferSurfaceDesc.Height; @@ -3445,7 +2363,7 @@ HRESULT DXUTCreateD3D11Views( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3 descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; - hr = pd3dDevice->CreateTexture2D( &descDepth, NULL, &pDepthStencil ); + hr = pd3dDevice->CreateTexture2D( &descDepth, nullptr, &pDepthStencil ); if( FAILED( hr ) ) return hr; DXUT_SetDebugName( pDepthStencil, "DXUT" ); @@ -3478,172 +2396,277 @@ HRESULT DXUTCreateD3D11Views( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3 //-------------------------------------------------------------------------------------- // Creates the 3D environment //-------------------------------------------------------------------------------------- -HRESULT DXUTCreate3DEnvironment11( ID3D11Device* pd3d11DeviceFromApp ) +HRESULT DXUTCreate3DEnvironment11() { HRESULT hr = S_OK; - ID3D11Device* pd3d11Device = NULL; - ID3D11DeviceContext* pd3dImmediateContext = NULL; - D3D_FEATURE_LEVEL FeatureLevel = D3D_FEATURE_LEVEL_11_0; + ID3D11Device* pd3d11Device = nullptr; + ID3D11DeviceContext* pd3dImmediateContext = nullptr; + D3D_FEATURE_LEVEL FeatureLevel = D3D_FEATURE_LEVEL_11_1; - IDXGISwapChain* pSwapChain = NULL; - DXUTDeviceSettings* pNewDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - assert( pNewDeviceSettings != NULL ); - - IDXGIFactory1* pDXGIFactory = DXUTGetDXGIFactory(); - assert( pDXGIFactory != NULL ); + IDXGISwapChain* pSwapChain = nullptr; + auto pNewDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + assert( pNewDeviceSettings ); + _Analysis_assume_( pNewDeviceSettings ); + + auto pDXGIFactory = DXUTGetDXGIFactory(); + assert( pDXGIFactory ); + _Analysis_assume_( pDXGIFactory ); hr = pDXGIFactory->MakeWindowAssociation( DXUTGetHWND(), 0 ); - // Only create a Direct3D device if one hasn't been supplied by the app - if( pd3d11DeviceFromApp == NULL ) + // Try to create the device with the chosen settings + IDXGIAdapter1* pAdapter = nullptr; + + hr = S_OK; + D3D_DRIVER_TYPE ddt = pNewDeviceSettings->d3d11.DriverType; + if( pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_HARDWARE ) { - // Try to create the device with the chosen settings - IDXGIAdapter1* pAdapter = NULL; + hr = pDXGIFactory->EnumAdapters1( pNewDeviceSettings->d3d11.AdapterOrdinal, &pAdapter ); + if ( FAILED( hr) ) + { + return E_FAIL; + } + ddt = D3D_DRIVER_TYPE_UNKNOWN; + } + else if (pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_WARP) + { + ddt = D3D_DRIVER_TYPE_WARP; + pAdapter = nullptr; + } + else if (pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE) + { + ddt = D3D_DRIVER_TYPE_REFERENCE; + pAdapter = nullptr; + } + + if( SUCCEEDED( hr ) ) + { + hr = DXUT_Dynamic_D3D11CreateDevice( pAdapter, + ddt, + ( HMODULE )0, + pNewDeviceSettings->d3d11.CreateFlags, + &pNewDeviceSettings->d3d11.DeviceFeatureLevel, + 1, + D3D11_SDK_VERSION, + &pd3d11Device, + &FeatureLevel, + &pd3dImmediateContext + ); - hr = S_OK; - D3D_DRIVER_TYPE ddt = pNewDeviceSettings->d3d11.DriverType; - if( pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_HARDWARE ) + if ( FAILED( hr ) ) { - hr = pDXGIFactory->EnumAdapters1( pNewDeviceSettings->d3d11.AdapterOrdinal, &pAdapter ); - if ( FAILED( hr) ) + pAdapter = nullptr; + // Remote desktop does not allow you to enumerate the adapter. In this case, we let D3D11 do the enumeration. + if ( ddt == D3D_DRIVER_TYPE_UNKNOWN ) + { + hr = DXUT_Dynamic_D3D11CreateDevice( pAdapter, + D3D_DRIVER_TYPE_HARDWARE, + ( HMODULE )0, + pNewDeviceSettings->d3d11.CreateFlags, + &pNewDeviceSettings->d3d11.DeviceFeatureLevel, + 1, + D3D11_SDK_VERSION, + &pd3d11Device, + &FeatureLevel, + &pd3dImmediateContext + ); + } + if ( FAILED ( hr ) ) { - return E_FAIL; + DXUT_ERR( L"D3D11CreateDevice", hr ); + return DXUTERR_CREATINGDEVICE; } - ddt = D3D_DRIVER_TYPE_UNKNOWN; } - else if (pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_WARP) + } + +#ifndef NDEBUG + if( SUCCEEDED( hr ) ) + { + ID3D11Debug * d3dDebug = nullptr; + if( SUCCEEDED( pd3d11Device->QueryInterface(IID_PPV_ARGS(&d3dDebug) ) ) ) { - ddt = D3D_DRIVER_TYPE_WARP; - pAdapter = NULL; + ID3D11InfoQueue* infoQueue = nullptr; + if( SUCCEEDED( d3dDebug->QueryInterface( IID_PPV_ARGS(&infoQueue) ) ) ) + { + // ignore some "expected" errors + D3D11_MESSAGE_ID denied [] = + { + D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS, + }; + + D3D11_INFO_QUEUE_FILTER filter; + memset( &filter, 0, sizeof(filter) ); + filter.DenyList.NumIDs = _countof(denied); + filter.DenyList.pIDList = denied; + infoQueue->AddStorageFilterEntries( &filter ); + infoQueue->Release(); + } + d3dDebug->Release(); } - else if (pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE) + } +#endif + + if( SUCCEEDED( hr ) ) + { + IDXGIDevice1* pDXGIDev = nullptr; + hr = pd3d11Device->QueryInterface( IID_PPV_ARGS(&pDXGIDev) ); + if( SUCCEEDED( hr ) && pDXGIDev ) { - ddt = D3D_DRIVER_TYPE_REFERENCE; - pAdapter = NULL; + if ( !pAdapter ) + { + IDXGIAdapter *pTempAdapter = nullptr; + V_RETURN( pDXGIDev->GetAdapter( &pTempAdapter ) ); + V_RETURN( pTempAdapter->QueryInterface( IID_PPV_ARGS(&pAdapter) ) ); + V_RETURN( pAdapter->GetParent( IID_PPV_ARGS(&pDXGIFactory) ) ); + SAFE_RELEASE ( pTempAdapter ); + if ( GetDXUTState().GetDXGIFactory() != pDXGIFactory ) + GetDXUTState().GetDXGIFactory()->Release(); + GetDXUTState().SetDXGIFactory( pDXGIFactory ); + } } + SAFE_RELEASE( pDXGIDev ); + GetDXUTState().SetDXGIAdapter( pAdapter ); + } - if( SUCCEEDED( hr ) ) + if( FAILED( hr ) ) + { + DXUT_ERR( L"D3D11CreateDevice", hr ); + return DXUTERR_CREATINGDEVICE; + } + + // set default render state to msaa enabled + D3D11_RASTERIZER_DESC drd = { + D3D11_FILL_SOLID, //D3D11_FILL_MODE FillMode; + D3D11_CULL_BACK,//D3D11_CULL_MODE CullMode; + FALSE, //BOOL FrontCounterClockwise; + 0, //INT DepthBias; + 0.0f,//FLOAT DepthBiasClamp; + 0.0f,//FLOAT SlopeScaledDepthBias; + TRUE,//BOOL DepthClipEnable; + FALSE,//BOOL ScissorEnable; + TRUE,//BOOL MultisampleEnable; + FALSE//BOOL AntialiasedLineEnable; + }; + ID3D11RasterizerState* pRS = nullptr; + hr = pd3d11Device->CreateRasterizerState(&drd, &pRS); + if ( FAILED( hr ) ) + { + DXUT_ERR( L"CreateRasterizerState", hr ); + return DXUTERR_CREATINGDEVICE; + } + DXUT_SetDebugName( pRS, "DXUT Default" ); + GetDXUTState().SetD3D11RasterizerState(pRS); + pd3dImmediateContext->RSSetState(pRS); + + // Enumerate its outputs. + UINT OutputCount, iOutput; + for( OutputCount = 0; ; ++OutputCount ) + { + IDXGIOutput* pOutput; + if( FAILED( pAdapter->EnumOutputs( OutputCount, &pOutput ) ) ) + break; + SAFE_RELEASE( pOutput ); + } + auto ppOutputArray = new (std::nothrow) IDXGIOutput*[OutputCount]; + if( !ppOutputArray ) + return E_OUTOFMEMORY; + for( iOutput = 0; iOutput < OutputCount; ++iOutput ) + pAdapter->EnumOutputs( iOutput, ppOutputArray + iOutput ); + GetDXUTState().SetDXGIOutputArray( ppOutputArray ); + GetDXUTState().SetDXGIOutputArraySize( OutputCount ); + + // Create the swapchain + hr = pDXGIFactory->CreateSwapChain( pd3d11Device, &pNewDeviceSettings->d3d11.sd, &pSwapChain ); + if( FAILED( hr ) ) + { + DXUT_ERR( L"CreateSwapChain", hr ); + return DXUTERR_CREATINGDEVICE; + } + + GetDXUTState().SetD3D11Device( pd3d11Device ); + GetDXUTState().SetD3D11DeviceContext( pd3dImmediateContext ); + GetDXUTState().SetD3D11FeatureLevel( FeatureLevel ); + GetDXUTState().SetDXGISwapChain( pSwapChain ); + + assert( pd3d11Device ); + _Analysis_assume_( pd3d11Device ); + + assert( pd3dImmediateContext ); + _Analysis_assume_( pd3dImmediateContext ); + + // Direct3D 11.1 + { + ID3D11Device1* pd3d11Device1 = nullptr; + hr = pd3d11Device->QueryInterface(IID_PPV_ARGS(&pd3d11Device1)); + if( SUCCEEDED( hr ) && pd3d11Device1 ) { + GetDXUTState().SetD3D11Device1( pd3d11Device1 ); - hr = DXUT_Dynamic_D3D11CreateDevice( pAdapter, - ddt, - ( HMODULE )0, - pNewDeviceSettings->d3d11.CreateFlags, - &pNewDeviceSettings->d3d11.DeviceFeatureLevel, - 1, - D3D11_SDK_VERSION, - &pd3d11Device, - &FeatureLevel, - &pd3dImmediateContext - ); - - if ( FAILED( hr ) ) { - pAdapter = NULL; - // Remote desktop does not allow you to enumerate the adapter. In this case, we let D3D11 do the enumeration. - if ( ddt == D3D_DRIVER_TYPE_UNKNOWN ) { - hr = DXUT_Dynamic_D3D11CreateDevice( pAdapter, - D3D_DRIVER_TYPE_HARDWARE, - ( HMODULE )0, - pNewDeviceSettings->d3d11.CreateFlags, - &pNewDeviceSettings->d3d11.DeviceFeatureLevel, - 1, - D3D11_SDK_VERSION, - &pd3d11Device, - &FeatureLevel, - &pd3dImmediateContext - ); - } - if ( FAILED ( hr ) ) { - DXUT_ERR( L"D3D11CreateDevice", hr ); - return DXUTERR_CREATINGDEVICE; - } + ID3D11DeviceContext1* pd3dImmediateContext1 = nullptr; + hr = pd3dImmediateContext->QueryInterface(IID_PPV_ARGS(&pd3dImmediateContext1)); + if( SUCCEEDED( hr ) && pd3dImmediateContext1 ) + { + GetDXUTState().SetD3D11DeviceContext1( pd3dImmediateContext1 ); } } + } - if( SUCCEEDED( hr ) ) +#ifdef USE_DIRECT3D11_2 + // Direct3D 11.2 + { + ID3D11Device2* pd3d11Device2 = nullptr; + hr = pd3d11Device->QueryInterface(IID_PPV_ARGS(&pd3d11Device2)); + if (SUCCEEDED(hr) && pd3d11Device2) { - IDXGIDevice1* pDXGIDev = NULL; - hr = pd3d11Device->QueryInterface( __uuidof( IDXGIDevice1 ), ( LPVOID* )&pDXGIDev ); - if( SUCCEEDED( hr ) && pDXGIDev ) + GetDXUTState().SetD3D11Device2(pd3d11Device2); + + ID3D11DeviceContext2* pd3dImmediateContext2 = nullptr; + hr = pd3dImmediateContext->QueryInterface(IID_PPV_ARGS(&pd3dImmediateContext2)); + if (SUCCEEDED(hr) && pd3dImmediateContext2) { - if ( pAdapter == NULL ) - { - IDXGIAdapter *pTempAdapter; - pDXGIDev->GetAdapter( &pTempAdapter ); - V_RETURN( pTempAdapter->QueryInterface( __uuidof( IDXGIAdapter1 ), (LPVOID*) &pAdapter ) ); - V_RETURN( pAdapter->GetParent( __uuidof( IDXGIFactory1 ), (LPVOID*) &pDXGIFactory ) ); - SAFE_RELEASE ( pTempAdapter ); - GetDXUTState().SetDXGIFactory( pDXGIFactory ); - } + GetDXUTState().SetD3D11DeviceContext2(pd3dImmediateContext2); } - SAFE_RELEASE( pDXGIDev ); - GetDXUTState().SetDXGIAdapter( pAdapter ); } + } +#endif - if( FAILED( hr ) ) - { - DXUT_ERR( L"D3D11CreateDevice", hr ); - return DXUTERR_CREATINGDEVICE; - } - // set default render state to msaa enabled - D3D11_RASTERIZER_DESC drd = { - D3D11_FILL_SOLID, //D3D11_FILL_MODE FillMode; - D3D11_CULL_BACK,//D3D11_CULL_MODE CullMode; - FALSE, //BOOL FrontCounterClockwise; - 0, //INT DepthBias; - 0.0f,//FLOAT DepthBiasClamp; - 0.0f,//FLOAT SlopeScaledDepthBias; - TRUE,//BOOL DepthClipEnable; - FALSE,//BOOL ScissorEnable; - TRUE,//BOOL MultisampleEnable; - FALSE//BOOL AntialiasedLineEnable; - }; - ID3D11RasterizerState* pRS = NULL; - hr = pd3d11Device->CreateRasterizerState(&drd, &pRS); - if ( FAILED( hr ) ) +#ifdef USE_DIRECT3D11_3 + // Direct3D 11.3 + { + ID3D11Device3* pd3d11Device3 = nullptr; + hr = pd3d11Device->QueryInterface( IID_PPV_ARGS(&pd3d11Device3) ); + if (SUCCEEDED(hr) && pd3d11Device3) { - DXUT_ERR( L"CreateRasterizerState", hr ); - return DXUTERR_CREATINGDEVICE; - } - DXUT_SetDebugName( pRS, "DXUT Default" ); - GetDXUTState().SetD3D11RasterizerState(pRS); - pd3dImmediateContext->RSSetState(pRS); + GetDXUTState().SetD3D11Device3(pd3d11Device3); - // Enumerate its outputs. - UINT OutputCount, iOutput; - for( OutputCount = 0; ; ++OutputCount ) - { - IDXGIOutput* pOutput; - if( FAILED( pAdapter->EnumOutputs( OutputCount, &pOutput ) ) ) - break; - SAFE_RELEASE( pOutput ); + ID3D11DeviceContext3* pd3dImmediateContext3 = nullptr; + hr = pd3dImmediateContext->QueryInterface(IID_PPV_ARGS(&pd3dImmediateContext3)); + if (SUCCEEDED(hr) && pd3dImmediateContext3) + { + GetDXUTState().SetD3D11DeviceContext3(pd3dImmediateContext3); + } } - IDXGIOutput** ppOutputArray = new IDXGIOutput*[OutputCount]; - if( !ppOutputArray ) - return E_OUTOFMEMORY; - for( iOutput = 0; iOutput < OutputCount; ++iOutput ) - pAdapter->EnumOutputs( iOutput, ppOutputArray + iOutput ); - GetDXUTState().SetDXGIOutputArray( ppOutputArray ); - GetDXUTState().SetDXGIOutputArraySize( OutputCount ); + } +#endif - // Create the swapchain - hr = pDXGIFactory->CreateSwapChain( pd3d11Device, &pNewDeviceSettings->d3d11.sd, &pSwapChain ); - if( FAILED( hr ) ) +#ifdef USE_DIRECT3D11_4 + // Direct3D 11.4 + { + ID3D11Device4* pd3d11Device4 = nullptr; + hr = pd3d11Device->QueryInterface(IID_PPV_ARGS(&pd3d11Device4)); + if (SUCCEEDED(hr) && pd3d11Device4) { - DXUT_ERR( L"CreateSwapChain", hr ); - return DXUTERR_CREATINGDEVICE; + GetDXUTState().SetD3D11Device4(pd3d11Device4); + + ID3D11DeviceContext4* pd3dImmediateContext4 = nullptr; + hr = pd3dImmediateContext->QueryInterface(IID_PPV_ARGS(&pd3dImmediateContext4)); + if (SUCCEEDED(hr) && pd3dImmediateContext4) + { + GetDXUTState().SetD3D11DeviceContext4(pd3dImmediateContext4); + } } } - else - { - pd3d11DeviceFromApp->AddRef(); - pd3d11Device = pd3d11DeviceFromApp; - } - - GetDXUTState().SetD3D11Device( pd3d11Device ); - GetDXUTState().SetD3D11DeviceContext( pd3dImmediateContext ); - GetDXUTState().SetD3D11FeatureLevel( FeatureLevel ); - GetDXUTState().SetDXGISwapChain( pSwapChain ); +#endif // If switching to REF, set the exit code to 11. If switching to HAL and exit code was 11, then set it back to 0. if( pNewDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE && GetDXUTState().GetExitCode() == 0 ) @@ -3658,21 +2681,22 @@ HRESULT DXUTCreate3DEnvironment11( ID3D11Device* pd3d11DeviceFromApp ) DXUTSetupCursor(); // Update the device stats text - CD3D11Enumeration* pd3dEnum = DXUTGetD3D11Enumeration(); - assert( pd3dEnum != NULL ); - CD3D11EnumAdapterInfo* pAdapterInfo = pd3dEnum->GetAdapterInfo( pNewDeviceSettings->d3d11.AdapterOrdinal ); - DXUTUpdateD3D11DeviceStats( pNewDeviceSettings->d3d11.DriverType, &pAdapterInfo->AdapterDesc ); + auto pd3dEnum = DXUTGetD3D11Enumeration(); + assert( pd3dEnum ); + _Analysis_assume_( pd3dEnum ); + auto pAdapterInfo = pd3dEnum->GetAdapterInfo( pNewDeviceSettings->d3d11.AdapterOrdinal ); + DXUTUpdateD3D11DeviceStats( pNewDeviceSettings->d3d11.DriverType, pNewDeviceSettings->d3d11.DeviceFeatureLevel, &pAdapterInfo->AdapterDesc ); // Call the app's device created callback if non-NULL - const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetDXGIBackBufferSurfaceDesc(); + auto pBackBufferSurfaceDesc = DXUTGetDXGIBackBufferSurfaceDesc(); GetDXUTState().SetInsideDeviceCallback( true ); - LPDXUTCALLBACKD3D11DEVICECREATED pCallbackDeviceCreated = GetDXUTState().GetD3D11DeviceCreatedFunc(); + auto pCallbackDeviceCreated = GetDXUTState().GetD3D11DeviceCreatedFunc(); hr = S_OK; - if( pCallbackDeviceCreated != NULL ) + if( pCallbackDeviceCreated ) hr = pCallbackDeviceCreated( DXUTGetD3D11Device(), pBackBufferSurfaceDesc, GetDXUTState().GetD3D11DeviceCreatedFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); - if( DXUTGetD3D11Device() == NULL ) // Handle DXUTShutdown from inside callback + if( !DXUTGetD3D11Device() ) // Handle DXUTShutdown from inside callback return E_FAIL; if( FAILED( hr ) ) { @@ -3689,18 +2713,15 @@ HRESULT DXUTCreate3DEnvironment11( ID3D11Device* pd3d11DeviceFromApp ) return DXUTERR_CREATINGDEVICEOBJECTS; } - // Create performance counters - //DXUTCreateD3D11Counters( pd3d11Device ); - // Call the app's swap chain reset callback if non-NULL GetDXUTState().SetInsideDeviceCallback( true ); LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallbackSwapChainResized = GetDXUTState().GetD3D11SwapChainResizedFunc(); hr = S_OK; - if( pCallbackSwapChainResized != NULL ) + if( pCallbackSwapChainResized ) hr = pCallbackSwapChainResized( DXUTGetD3D11Device(), pSwapChain, pBackBufferSurfaceDesc, GetDXUTState().GetD3D11SwapChainResizedFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); - if( DXUTGetD3D11Device() == NULL ) // Handle DXUTShutdown from inside callback + if( !DXUTGetD3D11Device() ) // Handle DXUTShutdown from inside callback return E_FAIL; if( FAILED( hr ) ) { @@ -3715,11 +2736,11 @@ HRESULT DXUTCreate3DEnvironment11( ID3D11Device* pd3d11DeviceFromApp ) //-------------------------------------------------------------------------------------- // Resets the 3D environment by: -// - Calls the device lost callback +// - Calls the device lost callback // - Resets the device // - Stores the back buffer description // - Sets up the full screen Direct3D cursor if requested -// - Calls the device reset callback +// - Calls the device reset callback //-------------------------------------------------------------------------------------- HRESULT DXUTReset3DEnvironment11() { @@ -3729,12 +2750,14 @@ HRESULT DXUTReset3DEnvironment11() DXUTPause( true, true ); bool bDeferredDXGIAction = false; - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); - assert( pSwapChain != NULL ); + auto pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + auto pSwapChain = DXUTGetDXGISwapChain(); + assert( pSwapChain ); + _Analysis_assume_( pSwapChain ); DXGI_SWAP_CHAIN_DESC SCDesc; - pSwapChain->GetDesc( &SCDesc ); + if ( FAILED( pSwapChain->GetDesc(&SCDesc)) ) + memset( &SCDesc, 0, sizeof(SCDesc) ); // Resize backbuffer and target of the swapchain in case they have changed. // For windowed mode, use the client rect as the desired size. Unlike D3D9, @@ -3757,7 +2780,7 @@ HRESULT DXUTReset3DEnvironment11() // Set the fullscreen state if( pDeviceSettings->d3d11.sd.Windowed ) { - V_RETURN( pSwapChain->SetFullscreenState( FALSE, NULL ) ); + V_RETURN( pSwapChain->SetFullscreenState( FALSE, nullptr ) ); bDeferredDXGIAction = true; } else @@ -3766,12 +2789,12 @@ HRESULT DXUTReset3DEnvironment11() // to the desired value. // SetFullscreenState causes a WM_SIZE message to be sent to the window. The WM_SIZE message calls - // DXUTCheckForDXGIBufferChange which normally stores the new height and width in + // DXUTCheckForDXGIBufferChange which normally stores the new height and width in // pDeviceSettings->d3d11.sd.BufferDesc. SetDoNotStoreBufferSize tells DXUTCheckForDXGIBufferChange // not to store the height and width so that we have the correct values when calling ResizeTarget. GetDXUTState().SetDoNotStoreBufferSize( true ); - V_RETURN( pSwapChain->SetFullscreenState( TRUE, NULL ) ); + V_RETURN( pSwapChain->SetFullscreenState( TRUE, nullptr ) ); GetDXUTState().SetDoNotStoreBufferSize( false ); V_RETURN( pSwapChain->ResizeTarget( &pDeviceSettings->d3d11.sd.BufferDesc ) ); @@ -3796,7 +2819,7 @@ HRESULT DXUTReset3DEnvironment11() } // If no deferred DXGI actions are to take place, mark the device as reset. - // If there is a deferred DXGI action, then the device isn't reset until DXGI sends us a + // If there is a deferred DXGI action, then the device isn't reset until DXGI sends us a // window message. Only then can we mark the device as reset. if( !bDeferredDXGIAction ) GetDXUTState().SetDeviceObjectsReset( true ); @@ -3813,20 +2836,20 @@ HRESULT DXUTReset3DEnvironment11() // - Calling the app's framemove and render callback // - Calling Present() //-------------------------------------------------------------------------------------- -void DXUTRender3DEnvironment11() +void WINAPI DXUTRender3DEnvironment() { HRESULT hr; - ID3D11Device* pd3dDevice = DXUTGetD3D11Device(); - if( NULL == pd3dDevice ) + auto pd3dDevice = DXUTGetD3D11Device(); + if( !pd3dDevice ) return; - ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext(); - if( NULL == pd3dImmediateContext ) + auto pd3dImmediateContext = DXUTGetD3D11DeviceContext(); + if( !pd3dImmediateContext ) return; - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); - if( NULL == pSwapChain ) + auto pSwapChain = DXUTGetDXGISwapChain(); + if( !pSwapChain ) return; if( DXUTIsRenderingPaused() || !DXUTIsActive() || GetDXUTState().GetRenderingOccluded() ) @@ -3850,8 +2873,6 @@ void DXUTRender3DEnvironment11() GetDXUTState().SetAbsoluteTime( fAbsTime ); GetDXUTState().SetElapsedTime( fElapsedTime ); - // Start Performance Counters - // Update the FPS stats DXUTUpdateFrameStats(); @@ -3859,11 +2880,11 @@ void DXUTRender3DEnvironment11() // Animate the scene by calling the app's frame move callback LPDXUTCALLBACKFRAMEMOVE pCallbackFrameMove = GetDXUTState().GetFrameMoveFunc(); - if( pCallbackFrameMove != NULL ) + if( pCallbackFrameMove ) { pCallbackFrameMove( fTime, fElapsedTime, GetDXUTState().GetFrameMoveFuncUserContext() ); pd3dDevice = DXUTGetD3D11Device(); - if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback + if( !pd3dDevice ) // Handle DXUTShutdown from inside callback return; } @@ -3871,35 +2892,37 @@ void DXUTRender3DEnvironment11() { // Render the scene by calling the app's render callback LPDXUTCALLBACKD3D11FRAMERENDER pCallbackFrameRender = GetDXUTState().GetD3D11FrameRenderFunc(); - if( pCallbackFrameRender != NULL && !GetDXUTState().GetRenderingOccluded() ) + if( pCallbackFrameRender && !GetDXUTState().GetRenderingOccluded() ) { pCallbackFrameRender( pd3dDevice, pd3dImmediateContext, fTime, fElapsedTime, GetDXUTState().GetD3D11FrameRenderFuncUserContext() ); - + pd3dDevice = DXUTGetD3D11Device(); - if( NULL == pd3dDevice ) // Handle DXUTShutdown from inside callback + if( !pd3dDevice ) // Handle DXUTShutdown from inside callback return; } #if defined(DEBUG) || defined(_DEBUG) - // The back buffer should always match the client rect + // The back buffer should always match the client rect // if the Direct3D backbuffer covers the entire window RECT rcClient; GetClientRect( DXUTGetHWND(), &rcClient ); if( !IsIconic( DXUTGetHWND() ) ) { GetClientRect( DXUTGetHWND(), &rcClient ); - + assert( DXUTGetDXGIBackBufferSurfaceDesc()->Width == (UINT)rcClient.right ); assert( DXUTGetDXGIBackBufferSurfaceDesc()->Height == (UINT)rcClient.bottom ); } #endif } - if ( GetDXUTState().GetSaveScreenShot() ) { - DXUTSnapD3D11Screenshot( GetDXUTState().GetScreenShotName(), D3DX11_IFF_BMP ); + if ( GetDXUTState().GetSaveScreenShot() ) + { + DXUTSnapD3D11Screenshot( GetDXUTState().GetScreenShotName(), false ); } - if ( GetDXUTState().GetExitAfterScreenShot() ) { + if ( GetDXUTState().GetExitAfterScreenShot() ) + { DXUTShutdown(); return; } @@ -3933,10 +2956,10 @@ void DXUTRender3DEnvironment11() } else { - // Reset failed, but the device wasn't lost so something bad happened, + // Reset failed, but the device wasn't lost so something bad happened, // so recreate the device to try to recover - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - if( FAILED( DXUTChangeDevice( pDeviceSettings, NULL, NULL, true, false ) ) ) + auto pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + if( FAILED( DXUTChangeDevice( pDeviceSettings, false ) ) ) { DXUTShutdown(); return; @@ -3948,7 +2971,7 @@ void DXUTRender3DEnvironment11() } else if( DXGI_ERROR_DEVICE_REMOVED == hr ) { - // Use a callback to ask the app if it would like to find a new device. + // Use a callback to ask the app if it would like to find a new device. // If no device removed callback is set, then look for a new device if( FAILED( DXUTHandleDeviceRemoved() ) ) { @@ -3973,10 +2996,6 @@ void DXUTRender3DEnvironment11() nFrame++; GetDXUTState().SetCurrentFrameNumber( nFrame ); - - // Update the D3D11 counter stats - //DXUTUpdateD3D11CounterStats(); - // Check to see if the app should shutdown due to cmdline if( GetDXUTState().GetOverrideQuitAfterFrame() != 0 ) { @@ -3987,113 +3006,51 @@ void DXUTRender3DEnvironment11() return; } -void ClearD3D11DeviceContext( ID3D11DeviceContext* pd3dDeviceContext ) -{ - // Unbind all objects from the immediate context - if (pd3dDeviceContext == NULL) return; - - ID3D11ShaderResourceView* pSRVs[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; - ID3D11RenderTargetView* pRTVs[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; - ID3D11DepthStencilView* pDSV = NULL; - ID3D11Buffer* pBuffers[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; - ID3D11SamplerState* pSamplers[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; - UINT StrideOffset[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; - - // Shaders - pd3dDeviceContext->VSSetShader( NULL, NULL, 0 ); - pd3dDeviceContext->HSSetShader( NULL, NULL, 0 ); - pd3dDeviceContext->DSSetShader( NULL, NULL, 0 ); - pd3dDeviceContext->GSSetShader( NULL, NULL, 0 ); - pd3dDeviceContext->PSSetShader( NULL, NULL, 0 ); - - // IA clear - pd3dDeviceContext->IASetVertexBuffers( 0, 16, pBuffers, StrideOffset, StrideOffset ); - pd3dDeviceContext->IASetIndexBuffer( NULL, DXGI_FORMAT_R16_UINT, 0 ); - pd3dDeviceContext->IASetInputLayout( NULL ); - - // Constant buffers - pd3dDeviceContext->VSSetConstantBuffers( 0, 14, pBuffers ); - pd3dDeviceContext->HSSetConstantBuffers( 0, 14, pBuffers ); - pd3dDeviceContext->DSSetConstantBuffers( 0, 14, pBuffers ); - pd3dDeviceContext->GSSetConstantBuffers( 0, 14, pBuffers ); - pd3dDeviceContext->PSSetConstantBuffers( 0, 14, pBuffers ); - - // Resources - pd3dDeviceContext->VSSetShaderResources( 0, 16, pSRVs ); - pd3dDeviceContext->HSSetShaderResources( 0, 16, pSRVs ); - pd3dDeviceContext->DSSetShaderResources( 0, 16, pSRVs ); - pd3dDeviceContext->GSSetShaderResources( 0, 16, pSRVs ); - pd3dDeviceContext->PSSetShaderResources( 0, 16, pSRVs ); - - // Samplers - pd3dDeviceContext->VSSetSamplers( 0, 16, pSamplers ); - pd3dDeviceContext->HSSetSamplers( 0, 16, pSamplers ); - pd3dDeviceContext->DSSetSamplers( 0, 16, pSamplers ); - pd3dDeviceContext->GSSetSamplers( 0, 16, pSamplers ); - pd3dDeviceContext->PSSetSamplers( 0, 16, pSamplers ); - - // Render targets - pd3dDeviceContext->OMSetRenderTargets( 8, pRTVs, pDSV ); - - // States - FLOAT blendFactor[4] = { 0,0,0,0 }; - pd3dDeviceContext->OMSetBlendState( NULL, blendFactor, 0xFFFFFFFF ); - pd3dDeviceContext->OMSetDepthStencilState( NULL, 0 ); - pd3dDeviceContext->RSSetState( NULL ); -} //-------------------------------------------------------------------------------------- // Cleans up the 3D environment by: -// - Calls the device lost callback -// - Calls the device destroyed callback +// - Calls the device lost callback +// - Calls the device destroyed callback // - Releases the D3D device //-------------------------------------------------------------------------------------- -void DXUTCleanup3DEnvironment11( bool bReleaseSettings ) +void DXUTCleanup3DEnvironment( _In_ bool bReleaseSettings ) { - ID3D11Device* pd3dDevice = DXUTGetD3D11Device(); + auto pd3dDevice = DXUTGetD3D11Device(); - if( pd3dDevice != NULL ) + if( pd3dDevice ) { - if (GetDXUTState().GetD3D11RasterizerState()!= NULL ) + if (GetDXUTState().GetD3D11RasterizerState()) GetDXUTState().GetD3D11RasterizerState()->Release(); - // Call ClearState to avoid tons of messy debug spew telling us that we're deleting bound objects - ID3D11DeviceContext* pImmediateContext = DXUTGetD3D11DeviceContext(); - ClearD3D11DeviceContext( pImmediateContext ); - - // Clear state and flush - pImmediateContext->ClearState(); - pImmediateContext->Flush(); - // Call the app's SwapChain lost callback GetDXUTState().SetInsideDeviceCallback( true ); if( GetDXUTState().GetDeviceObjectsReset() ) { LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallbackSwapChainReleasing = GetDXUTState().GetD3D11SwapChainReleasingFunc(); - if( pCallbackSwapChainReleasing != NULL ) + if( pCallbackSwapChainReleasing ) pCallbackSwapChainReleasing( GetDXUTState().GetD3D11SwapChainReleasingFuncUserContext() ); GetDXUTState().SetDeviceObjectsReset( false ); } - // Release our old depth stencil texture and view - ID3D11Texture2D* pDS = GetDXUTState().GetD3D11DepthStencil(); + // Release our old depth stencil texture and view + auto pDS = GetDXUTState().GetD3D11DepthStencil(); SAFE_RELEASE( pDS ); - GetDXUTState().SetD3D11DepthStencil( NULL ); - ID3D11DepthStencilView* pDSV = GetDXUTState().GetD3D11DepthStencilView(); + GetDXUTState().SetD3D11DepthStencil( nullptr ); + auto pDSV = GetDXUTState().GetD3D11DepthStencilView(); SAFE_RELEASE( pDSV ); - GetDXUTState().SetD3D11DepthStencilView( NULL ); + GetDXUTState().SetD3D11DepthStencilView( nullptr ); // Cleanup the render target view - ID3D11RenderTargetView* pRTV = GetDXUTState().GetD3D11RenderTargetView(); + auto pRTV = GetDXUTState().GetD3D11RenderTargetView(); SAFE_RELEASE( pRTV ); - GetDXUTState().SetD3D11RenderTargetView( NULL ); + GetDXUTState().SetD3D11RenderTargetView( nullptr ); // Call the app's device destroyed callback if( GetDXUTState().GetDeviceObjectsCreated() ) { - LPDXUTCALLBACKD3D11DEVICEDESTROYED pCallbackDeviceDestroyed = GetDXUTState().GetD3D11DeviceDestroyedFunc(); - if( pCallbackDeviceDestroyed != NULL ) + auto pCallbackDeviceDestroyed = GetDXUTState().GetD3D11DeviceDestroyedFunc(); + if( pCallbackDeviceDestroyed ) pCallbackDeviceDestroyed( GetDXUTState().GetD3D11DeviceDestroyedFuncUserContext() ); GetDXUTState().SetDeviceObjectsCreated( false ); } @@ -4102,41 +3059,97 @@ void DXUTCleanup3DEnvironment11( bool bReleaseSettings ) // Release the swap chain GetDXUTState().SetReleasingSwapChain( true ); - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); + auto pSwapChain = DXUTGetDXGISwapChain(); if( pSwapChain ) { pSwapChain->SetFullscreenState( FALSE, 0 ); } SAFE_RELEASE( pSwapChain ); - GetDXUTState().SetDXGISwapChain( NULL ); + GetDXUTState().SetDXGISwapChain( nullptr ); GetDXUTState().SetReleasingSwapChain( false ); // Release the outputs. - IDXGIOutput** ppOutputArray = GetDXUTState().GetDXGIOutputArray(); + auto ppOutputArray = GetDXUTState().GetDXGIOutputArray(); UINT OutputCount = GetDXUTState().GetDXGIOutputArraySize(); for( UINT o = 0; o < OutputCount; ++o ) SAFE_RELEASE( ppOutputArray[o] ); delete[] ppOutputArray; - GetDXUTState().SetDXGIOutputArray( NULL ); + GetDXUTState().SetDXGIOutputArray( nullptr ); GetDXUTState().SetDXGIOutputArraySize( 0 ); // Release the D3D adapter. - IDXGIAdapter* pAdapter = GetDXUTState().GetDXGIAdapter(); + auto pAdapter = GetDXUTState().GetDXGIAdapter(); SAFE_RELEASE( pAdapter ); - GetDXUTState().SetDXGIAdapter( NULL ); + GetDXUTState().SetDXGIAdapter( nullptr ); - // Release the counters - //DXUTDestroyD3D11Counters(); + // Call ClearState to avoid tons of messy debug spew telling us that we're deleting bound objects + auto pImmediateContext = DXUTGetD3D11DeviceContext(); + assert( pImmediateContext ); + pImmediateContext->ClearState(); + pImmediateContext->Flush(); // Release the D3D11 immediate context (if it exists) because it has a extra ref count on it - ID3D11DeviceContext* pd3d11DeviceContext = GetDXUTState().GetD3D11DeviceContext(); - SAFE_RELEASE( pd3d11DeviceContext ); - GetDXUTState().SetD3D11DeviceContext( NULL ); + SAFE_RELEASE( pImmediateContext ); + GetDXUTState().SetD3D11DeviceContext( nullptr ); + + auto pImmediateContext1 = DXUTGetD3D11DeviceContext1(); + SAFE_RELEASE( pImmediateContext1 ); + GetDXUTState().SetD3D11DeviceContext1( nullptr ); + +#ifdef USE_DIRECT3D11_2 + auto pImmediateContext2 = DXUTGetD3D11DeviceContext2(); + SAFE_RELEASE(pImmediateContext2); + GetDXUTState().SetD3D11DeviceContext2(nullptr); +#endif + +#ifdef USE_DIRECT3D11_3 + auto pImmediateContext3 = DXUTGetD3D11DeviceContext3(); + SAFE_RELEASE(pImmediateContext3); + GetDXUTState().SetD3D11DeviceContext3(nullptr); +#endif + +#ifdef USE_DIRECT3D11_4 + auto pImmediateContext4 = DXUTGetD3D11DeviceContext4(); + SAFE_RELEASE(pImmediateContext4); + GetDXUTState().SetD3D11DeviceContext4(nullptr); +#endif - // Release the D3D device and in debug configs, displays a message box if there - // are unrelease objects. - if( pd3dDevice ) + // Report live objects + if ( pd3dDevice ) { +#ifndef NDEBUG + ID3D11Debug * d3dDebug = nullptr; + if( SUCCEEDED( pd3dDevice->QueryInterface( IID_PPV_ARGS(&d3dDebug) ) ) ) + { + d3dDebug->ReportLiveDeviceObjects( D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL ); + d3dDebug->Release(); + } +#endif + + auto pd3dDevice1 = DXUTGetD3D11Device1(); + SAFE_RELEASE( pd3dDevice1 ); + GetDXUTState().SetD3D11Device1(nullptr); + +#ifdef USE_DIRECT3D11_2 + auto pd3dDevice2 = DXUTGetD3D11Device2(); + SAFE_RELEASE(pd3dDevice2); + GetDXUTState().SetD3D11Device2(nullptr); +#endif + +#ifdef USE_DIRECT3D11_3 + auto pd3dDevice3 = DXUTGetD3D11Device3(); + SAFE_RELEASE(pd3dDevice3); + GetDXUTState().SetD3D11Device3(nullptr); +#endif + +#ifdef USE_DIRECT3D11_4 + auto pd3dDevice4 = DXUTGetD3D11Device4(); + SAFE_RELEASE(pd3dDevice4); + GetDXUTState().SetD3D11Device4(nullptr); +#endif + + // Release the D3D device and in debug configs, displays a message box if there + // are unrelease objects. UINT references = pd3dDevice->Release(); if( references > 0 ) { @@ -4144,16 +3157,27 @@ void DXUTCleanup3DEnvironment11( bool bReleaseSettings ) DXUT_ERR( L"DXUTCleanup3DEnvironment", DXUTERR_NONZEROREFCOUNT ); } } - GetDXUTState().SetD3D11Device( NULL ); + GetDXUTState().SetD3D11Device( nullptr ); + +#ifndef NDEBUG + { + IDXGIDebug* dxgiDebug = nullptr; + if ( SUCCEEDED( DXUT_Dynamic_DXGIGetDebugInterface( IID_IDXGIDebug, reinterpret_cast<void**>( &dxgiDebug ) ) ) ) + { + dxgiDebug->ReportLiveObjects( DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_ALL ); + dxgiDebug->Release(); + } + } +#endif if( bReleaseSettings ) { - DXUTDeviceSettings* pOldDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + auto pOldDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); SAFE_DELETE(pOldDeviceSettings); - GetDXUTState().SetCurrentDeviceSettings( NULL ); + GetDXUTState().SetCurrentDeviceSettings( nullptr ); } - DXGI_SURFACE_DESC* pBackBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDescDXGI(); + auto pBackBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDescDXGI(); ZeroMemory( pBackBufferSurfaceDesc, sizeof( DXGI_SURFACE_DESC ) ); GetDXUTState().SetDeviceCreated( false ); @@ -4162,15 +3186,15 @@ void DXUTCleanup3DEnvironment11( bool bReleaseSettings ) //-------------------------------------------------------------------------------------- -// Low level keyboard hook to disable Windows key to prevent accidental task switching. +// Low level keyboard hook to disable Windows key to prevent accidental task switching. //-------------------------------------------------------------------------------------- LRESULT CALLBACK DXUTLowLevelKeyboardProc( int nCode, WPARAM wParam, LPARAM lParam ) { - if( nCode < 0 || nCode != HC_ACTION ) // do not process message + if( nCode < 0 || nCode != HC_ACTION ) // do not process message return CallNextHookEx( GetDXUTState().GetKeyboardHook(), nCode, wParam, lParam ); bool bEatKeystroke = false; - KBDLLHOOKSTRUCT* p = ( KBDLLHOOKSTRUCT* )lParam; + auto p = reinterpret_cast<KBDLLHOOKSTRUCT*>( lParam ); switch( wParam ) { case WM_KEYDOWN: @@ -4189,11 +3213,11 @@ LRESULT CALLBACK DXUTLowLevelKeyboardProc( int nCode, WPARAM wParam, LPARAM lPar } - //-------------------------------------------------------------------------------------- -// Controls how DXUT behaves when fullscreen and windowed mode with regard to -// shortcut keys (Windows keys, StickyKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut) +// Controls how DXUT behaves when fullscreen and windowed mode with regard to +// shortcut keys (Windows keys, StickyKeys shortcut, ToggleKeys shortcut, FilterKeys shortcut) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void WINAPI DXUTSetShortcutKeySettings( bool bAllowWhenFullscreen, bool bAllowWhenWindowed ) { GetDXUTState().SetAllowShortcutKeysWhenWindowed( bAllowWhenWindowed ); @@ -4211,16 +3235,16 @@ void WINAPI DXUTSetShortcutKeySettings( bool bAllowWhenFullscreen, bool bAllowWh //-------------------------------------------------------------------------------------- -// Enables/disables Windows keys, and disables or restores the StickyKeys/ToggleKeys/FilterKeys +// Enables/disables Windows keys, and disables or restores the StickyKeys/ToggleKeys/FilterKeys // shortcut to help prevent accidental task switching //-------------------------------------------------------------------------------------- -void DXUTAllowShortcutKeys( bool bAllowKeys ) +void DXUTAllowShortcutKeys( _In_ bool bAllowKeys ) { GetDXUTState().SetAllowShortcutKeys( bAllowKeys ); if( bAllowKeys ) { - // Restore StickyKeys/etc to original state and enable Windows key + // Restore StickyKeys/etc to original state and enable Windows key STICKYKEYS sk = GetDXUTState().GetStartupStickyKeys(); TOGGLEKEYS tk = GetDXUTState().GetStartupToggleKeys(); FILTERKEYS fk = GetDXUTState().GetStartupFilterKeys(); @@ -4233,27 +3257,21 @@ void DXUTAllowShortcutKeys( bool bAllowKeys ) if( GetDXUTState().GetKeyboardHook() ) { UnhookWindowsHookEx( GetDXUTState().GetKeyboardHook() ); - GetDXUTState().SetKeyboardHook( NULL ); + GetDXUTState().SetKeyboardHook( nullptr ); } } else { // Set low level keyboard hook if haven't already - if( GetDXUTState().GetKeyboardHook() == NULL ) + if( !GetDXUTState().GetKeyboardHook() ) { - // Set the low-level hook procedure. Only works on Windows 2000 and above - OSVERSIONINFO OSVersionInfo; - OSVersionInfo.dwOSVersionInfoSize = sizeof( OSVersionInfo ); - GetVersionEx( &OSVersionInfo ); - if( OSVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT && OSVersionInfo.dwMajorVersion > 4 ) - { - HHOOK hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL, DXUTLowLevelKeyboardProc, - GetModuleHandle( NULL ), 0 ); - GetDXUTState().SetKeyboardHook( hKeyboardHook ); - } + // Set the low-level hook procedure. + HHOOK hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL, DXUTLowLevelKeyboardProc, + GetModuleHandle( nullptr ), 0 ); + GetDXUTState().SetKeyboardHook( hKeyboardHook ); } - // Disable StickyKeys/etc shortcuts but if the accessibility feature is on, + // Disable StickyKeys/etc shortcuts but if the accessibility feature is on, // then leave the settings alone as its probably being usefully used STICKYKEYS skOff = GetDXUTState().GetStartupStickyKeys(); @@ -4292,6 +3310,7 @@ void DXUTAllowShortcutKeys( bool bAllowKeys ) //-------------------------------------------------------------------------------------- // Pauses time or rendering. Keeps a ref count so pausing can be layered //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void WINAPI DXUTPause( bool bPauseTime, bool bPauseRendering ) { int nPauseTimeCount = GetDXUTState().GetPauseTimeCount(); @@ -4327,13 +3346,13 @@ void WINAPI DXUTPause( bool bPauseTime, bool bPauseRendering ) //-------------------------------------------------------------------------------------- // Starts a user defined timer callback //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT WINAPI DXUTSetTimer( LPDXUTCALLBACKTIMER pCallbackTimer, float fTimeoutInSecs, UINT* pnIDEvent, void* pCallbackUserContext ) { - if( pCallbackTimer == NULL ) + if( !pCallbackTimer ) return DXUT_ERR_MSGBOX( L"DXUTSetTimer", E_INVALIDARG ); - HRESULT hr; DXUT_TIMER DXUTTimer; DXUTTimer.pCallbackTimer = pCallbackTimer; DXUTTimer.pCallbackUserContext = pCallbackUserContext; @@ -4343,17 +3362,16 @@ HRESULT WINAPI DXUTSetTimer( LPDXUTCALLBACKTIMER pCallbackTimer, float fTimeoutI DXUTTimer.nID = GetDXUTState().GetTimerLastID() + 1; GetDXUTState().SetTimerLastID( DXUTTimer.nID ); - CGrowableArray <DXUT_TIMER>* pTimerList = GetDXUTState().GetTimerList(); - if( pTimerList == NULL ) + auto pTimerList = GetDXUTState().GetTimerList(); + if( !pTimerList ) { - pTimerList = new CGrowableArray <DXUT_TIMER>; - if( pTimerList == NULL ) + pTimerList = new (std::nothrow) std::vector<DXUT_TIMER>; + if( !pTimerList ) return E_OUTOFMEMORY; GetDXUTState().SetTimerList( pTimerList ); } - if( FAILED( hr = pTimerList->Add( DXUTTimer ) ) ) - return hr; + pTimerList->push_back( DXUTTimer ); if( pnIDEvent ) *pnIDEvent = DXUTTimer.nID; @@ -4365,21 +3383,21 @@ HRESULT WINAPI DXUTSetTimer( LPDXUTCALLBACKTIMER pCallbackTimer, float fTimeoutI //-------------------------------------------------------------------------------------- // Stops a user defined timer callback //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTKillTimer( UINT nIDEvent ) +HRESULT WINAPI DXUTKillTimer( _In_ UINT nIDEvent ) { - CGrowableArray <DXUT_TIMER>* pTimerList = GetDXUTState().GetTimerList(); - if( pTimerList == NULL ) + auto pTimerList = GetDXUTState().GetTimerList(); + if( !pTimerList ) return S_FALSE; bool bFound = false; - for( int i = 0; i < pTimerList->GetSize(); i++ ) + for( auto it = pTimerList->begin(); it != pTimerList->end(); ++it ) { - DXUT_TIMER DXUTTimer = pTimerList->GetAt( i ); + DXUT_TIMER DXUTTimer = *it; if( DXUTTimer.nID == nIDEvent ) { DXUTTimer.bEnabled = false; - pTimerList->SetAt( i, DXUTTimer ); + *it = DXUTTimer; bFound = true; break; } @@ -4399,14 +3417,14 @@ void DXUTHandleTimers() { float fElapsedTime = DXUTGetElapsedTime(); - CGrowableArray <DXUT_TIMER>* pTimerList = GetDXUTState().GetTimerList(); - if( pTimerList == NULL ) + auto pTimerList = GetDXUTState().GetTimerList(); + if( !pTimerList ) return; // Walk through the list of timer callbacks - for( int i = 0; i < pTimerList->GetSize(); i++ ) + for( auto it = pTimerList->begin(); it != pTimerList->end(); ++it ) { - DXUT_TIMER DXUTTimer = pTimerList->GetAt( i ); + DXUT_TIMER DXUTTimer = *it; if( DXUTTimer.bEnabled ) { DXUTTimer.fCountdown -= fElapsedTime; @@ -4416,19 +3434,19 @@ void DXUTHandleTimers() { DXUTTimer.pCallbackTimer( DXUTTimer.nID, DXUTTimer.pCallbackUserContext ); // The callback my have changed the timer. - DXUTTimer = pTimerList->GetAt( i ); + DXUTTimer = *it; DXUTTimer.fCountdown = DXUTTimer.fTimeoutInSecs; } - pTimerList->SetAt( i, DXUTTimer ); + *it = DXUTTimer; } } } //-------------------------------------------------------------------------------------- -// Display an custom error msg box +// Display an custom error msg box //-------------------------------------------------------------------------------------- -void DXUTDisplayErrorMessage( HRESULT hr ) +void DXUTDisplayErrorMessage( _In_ HRESULT hr ) { WCHAR strBuffer[512]; @@ -4439,18 +3457,15 @@ void DXUTDisplayErrorMessage( HRESULT hr ) case DXUTERR_NODIRECT3D: { nExitCode = 2; - if( DXUTDoesAppSupportD3D11() && !DXUTDoesAppSupportD3D9() ) - wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Could not initialize Direct3D 11. " ); - else - wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Could not initialize Direct3D 9. Check that the latest version of DirectX is correctly installed on your system. Also make sure that this program was compiled with header files that match the installed DirectX DLLs." ); + wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Could not initialize Direct3D 11. " ); break; } - case DXUTERR_NOCOMPATIBLEDEVICES: - nExitCode = 3; - if( GetSystemMetrics(0x1000) != 0 ) // SM_REMOTESESSION - wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Direct3D does not work over a remote session." ); + case DXUTERR_NOCOMPATIBLEDEVICES: + nExitCode = 3; + if( GetSystemMetrics(SM_REMOTESESSION) != 0 ) + wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Direct3D does not work over a remote session." ); else - wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Could not find any compatible Direct3D devices." ); + wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Could not find any compatible Direct3D devices." ); break; case DXUTERR_MEDIANOTFOUND: nExitCode = 4; wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Could not find required media." ); break; case DXUTERR_NONZEROREFCOUNT: nExitCode = 5; wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"The Direct3D device has a non-zero reference count, meaning some objects were not released." ); break; @@ -4458,11 +3473,11 @@ void DXUTDisplayErrorMessage( HRESULT hr ) case DXUTERR_RESETTINGDEVICE: nExitCode = 7; wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"Failed resetting the Direct3D device." ); break; case DXUTERR_CREATINGDEVICEOBJECTS: nExitCode = 8; wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"An error occurred in the device create callback function." ); break; case DXUTERR_RESETTINGDEVICEOBJECTS: nExitCode = 9; wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"An error occurred in the device reset callback function." ); break; - // nExitCode 10 means the app exited using a REF device + // nExitCode 10 means the app exited using a REF device case DXUTERR_DEVICEREMOVED: nExitCode = 11; wcscpy_s( strBuffer, ARRAYSIZE(strBuffer), L"The Direct3D device was removed." ); break; default: bFound = false; nExitCode = 1; break; // nExitCode 1 means the API was incorrectly called - } + } GetDXUTState().SetExitCode(nExitCode); @@ -4480,7 +3495,7 @@ void DXUTDisplayErrorMessage( HRESULT hr ) //-------------------------------------------------------------------------------------- // Internal function to map MK_* to an array index //-------------------------------------------------------------------------------------- -int DXUTMapButtonToArrayIndex( BYTE vButton ) +int DXUTMapButtonToArrayIndex( _In_ BYTE vButton ) { switch( vButton ) { @@ -4503,57 +3518,52 @@ int DXUTMapButtonToArrayIndex( BYTE vButton ) } - //-------------------------------------------------------------------------------------- // Toggle between full screen and windowed //-------------------------------------------------------------------------------------- HRESULT WINAPI DXUTToggleFullScreen() { + auto deviceSettings = DXUTGetDeviceSettings(); + if ( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + { + // WARP driver type doesn't support fullscreen + return S_FALSE; + } + + auto orginalDeviceSettings = DXUTGetDeviceSettings(); + + deviceSettings.d3d11.sd.Windowed = !deviceSettings.d3d11.sd.Windowed; + HRESULT hr; - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - DXUTDeviceSettings orginalDeviceSettings = DXUTGetDeviceSettings(); - - if (deviceSettings.ver == DXUT_D3D11_DEVICE) { - deviceSettings.d3d11.sd.Windowed = !deviceSettings.d3d11.sd.Windowed; // datut - if (!deviceSettings.d3d11.sd.Windowed) { - DXGI_MODE_DESC adapterDesktopDisplayMode = + if (!deviceSettings.d3d11.sd.Windowed) + { + DXGI_MODE_DESC adapterDesktopDisplayMode; + hr = DXUTGetD3D11AdapterDisplayMode( deviceSettings.d3d11.AdapterOrdinal, 0, &adapterDesktopDisplayMode ); + if ( FAILED(hr) ) + { + static const DXGI_MODE_DESC s_adapterDesktopDisplayMode = { - 800, 600, { 60, 1 }, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB + 800, 600, { 0, 0 }, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB }; - DXUTGetD3D11AdapterDisplayMode( deviceSettings.d3d11.AdapterOrdinal, 0, &adapterDesktopDisplayMode ); - - - deviceSettings.d3d11.sd.BufferDesc = adapterDesktopDisplayMode; - }else { - RECT r = DXUTGetWindowClientRectAtModeChange(); - deviceSettings.d3d11.sd.BufferDesc.Height = r.bottom; - deviceSettings.d3d11.sd.BufferDesc.Width = r.right; - } - }else if (deviceSettings.ver == DXUT_D3D9_DEVICE){ - deviceSettings.d3d9.pp.Windowed = !deviceSettings.d3d9.pp.Windowed; - if (!deviceSettings.d3d9.pp.Windowed) { - D3DDISPLAYMODE adapterDesktopDisplayMode; - IDirect3D9* pD3D = DXUTGetD3D9Object(); - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - pD3D->GetAdapterDisplayMode( pDeviceSettings->d3d9.AdapterOrdinal, &adapterDesktopDisplayMode ); - deviceSettings.d3d9.pp.BackBufferWidth = adapterDesktopDisplayMode.Width; - deviceSettings.d3d9.pp.BackBufferHeight = adapterDesktopDisplayMode.Height; - deviceSettings.d3d9.pp.BackBufferFormat = adapterDesktopDisplayMode.Format; - } else { - RECT r = DXUTGetWindowClientRectAtModeChange(); - deviceSettings.d3d9.pp.BackBufferHeight= r.bottom; - deviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = 0; - deviceSettings.d3d9.pp.BackBufferWidth = r.right; + memcpy(&adapterDesktopDisplayMode, &s_adapterDesktopDisplayMode, sizeof(DXGI_MODE_DESC)); } + + deviceSettings.d3d11.sd.BufferDesc = adapterDesktopDisplayMode; + } + else + { + RECT r = DXUTGetWindowClientRectAtModeChange(); + deviceSettings.d3d11.sd.BufferDesc.Height = r.bottom; + deviceSettings.d3d11.sd.BufferDesc.Width = r.right; } - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false ); + hr = DXUTChangeDevice( &deviceSettings, false ); // If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback so nothing changed if( FAILED( hr ) && ( hr != E_ABORT ) ) { // Failed creating device, try to switch back. - HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, NULL, NULL, false, false ); + HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, false ); if( FAILED( hr2 ) ) { // If this failed, then shutdown @@ -4566,51 +3576,41 @@ HRESULT WINAPI DXUTToggleFullScreen() //-------------------------------------------------------------------------------------- -// Toggle between HAL and WARP +// Toggle between HAL/REF and WARP //-------------------------------------------------------------------------------------- +HRESULT WINAPI DXUTToggleWARP () +{ + auto deviceSettings = DXUTGetDeviceSettings(); -HRESULT WINAPI DXUTToggleWARP () { - HRESULT hr; - - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - DXUTDeviceSettings orginalDeviceSettings = DXUTGetDeviceSettings(); - - // Toggle between REF & HAL - if( DXUTIsCurrentDeviceD3D9() ) - { - - } - else + if ( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_HARDWARE || deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) { - ID3D11SwitchToRef* pD3D11STR = NULL; - ID3D11Device* pDev = DXUTGetD3D11Device(); - assert( pDev != NULL ); - hr = pDev->QueryInterface( __uuidof( *pD3D11STR ), ( LPVOID* )&pD3D11STR ); - if( SUCCEEDED( hr ) ) + if ( !deviceSettings.d3d11.sd.Windowed ) { - pD3D11STR->SetUseRef( pD3D11STR->GetUseRef() ? FALSE : TRUE ); - SAFE_RELEASE( pD3D11STR ); - return S_OK; + // WARP driver type doesn't support fullscreen + return S_FALSE; } - if( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_HARDWARE || deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) - deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_WARP; - else if( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE || deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) - deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_HARDWARE; + deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_WARP; } - - hr = DXUTSnapDeviceSettingsToEnumDevice(&deviceSettings, false); + else if ( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + { + deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_HARDWARE; + } + + HRESULT hr = DXUTSnapDeviceSettingsToEnumDevice(&deviceSettings, false); if( SUCCEEDED( hr ) ) { - // Create a Direct3D device using the new device settings. + DXUTDeviceSettings orginalDeviceSettings = DXUTGetDeviceSettings(); + + // Create a Direct3D device using the new device settings. // If there is an existing device, then it will either reset or recreate the scene. - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false ); + hr = DXUTChangeDevice( &deviceSettings, false ); // If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback so nothing changed if( FAILED( hr ) && ( hr != E_ABORT ) ) { // Failed creating device, try to switch back. - HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, NULL, NULL, false, false ); + HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, false ); if( FAILED( hr2 ) ) { // If this failed, then shutdown @@ -4621,55 +3621,48 @@ HRESULT WINAPI DXUTToggleWARP () { return hr; } + + //-------------------------------------------------------------------------------------- -// Toggle between HAL and REF +// Toggle between HAL/WARP and REF //-------------------------------------------------------------------------------------- HRESULT WINAPI DXUTToggleREF() { - HRESULT hr; + auto deviceSettings = DXUTGetDeviceSettings(); - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - DXUTDeviceSettings orginalDeviceSettings = DXUTGetDeviceSettings(); - - // Toggle between REF & HAL - if( DXUTIsCurrentDeviceD3D9() ) + if ( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_HARDWARE ) { - if( deviceSettings.d3d9.DeviceType == D3DDEVTYPE_HAL ) - deviceSettings.d3d9.DeviceType = D3DDEVTYPE_REF; - else if( deviceSettings.d3d9.DeviceType == D3DDEVTYPE_REF ) - deviceSettings.d3d9.DeviceType = D3DDEVTYPE_HAL; + deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_REFERENCE; } - else + else if ( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) { - ID3D11SwitchToRef* pD3D11STR = NULL; - ID3D11Device* pDev = DXUTGetD3D11Device(); - assert( pDev != NULL ); - hr = pDev->QueryInterface( __uuidof( *pD3D11STR ), ( LPVOID* )&pD3D11STR ); - if( SUCCEEDED( hr ) ) + deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_HARDWARE; + } + else if ( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + { + if ( !deviceSettings.d3d11.sd.Windowed ) { - pD3D11STR->SetUseRef( pD3D11STR->GetUseRef() ? FALSE : TRUE ); - SAFE_RELEASE( pD3D11STR ); - return S_OK; + // WARP driver type doesn't support fullscreen + return S_FALSE; } - if( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_HARDWARE ) - deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_REFERENCE; - else if( deviceSettings.d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) - deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_HARDWARE; + deviceSettings.d3d11.DriverType = D3D_DRIVER_TYPE_REFERENCE; } - - hr = DXUTSnapDeviceSettingsToEnumDevice(&deviceSettings, false); + + HRESULT hr = DXUTSnapDeviceSettingsToEnumDevice(&deviceSettings, false); if( SUCCEEDED( hr ) ) { - // Create a Direct3D device using the new device settings. + auto orginalDeviceSettings = DXUTGetDeviceSettings(); + + // Create a Direct3D device using the new device settings. // If there is an existing device, then it will either reset or recreate the scene. - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false ); + hr = DXUTChangeDevice( &deviceSettings, false ); // If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback so nothing changed if( FAILED( hr ) && ( hr != E_ABORT ) ) { // Failed creating device, try to switch back. - HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, NULL, NULL, false, false ); + HRESULT hr2 = DXUTChangeDevice( &orginalDeviceSettings, false ); if( FAILED( hr2 ) ) { // If this failed, then shutdown @@ -4686,48 +3679,54 @@ HRESULT WINAPI DXUTToggleREF() //-------------------------------------------------------------------------------------- void DXUTCheckForDXGIFullScreenSwitch() { - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - if( !DXUTIsD3D9( pDeviceSettings ) ) - { - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); - assert( pSwapChain != NULL ); - DXGI_SWAP_CHAIN_DESC SCDesc; - pSwapChain->GetDesc( &SCDesc ); + auto pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + auto pSwapChain = DXUTGetDXGISwapChain(); + assert( pSwapChain ); + _Analysis_assume_( pSwapChain ); + DXGI_SWAP_CHAIN_DESC SCDesc; + if ( FAILED(pSwapChain->GetDesc(&SCDesc)) ) + memset( &SCDesc, 0, sizeof(SCDesc) ); - BOOL bIsWindowed = ( BOOL )DXUTIsWindowed(); - if( bIsWindowed != SCDesc.Windowed ) - { - pDeviceSettings->d3d11.sd.Windowed = SCDesc.Windowed; + BOOL bIsWindowed = ( BOOL )DXUTIsWindowed(); + if( bIsWindowed != SCDesc.Windowed ) + { + pDeviceSettings->d3d11.sd.Windowed = SCDesc.Windowed; - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); + auto deviceSettings = DXUTGetDeviceSettings(); - if( bIsWindowed ) - { - GetDXUTState().SetWindowBackBufferWidthAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Width ); - GetDXUTState().SetWindowBackBufferHeightAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Height ); - } - else - { - GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Width ); - GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Height ); - } + if( bIsWindowed ) + { + GetDXUTState().SetWindowBackBufferWidthAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Width ); + GetDXUTState().SetWindowBackBufferHeightAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Height ); + } + else + { + GetDXUTState().SetFullScreenBackBufferWidthAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Width ); + GetDXUTState().SetFullScreenBackBufferHeightAtModeChange( deviceSettings.d3d11.sd.BufferDesc.Height ); } } } +_Use_decl_annotations_ void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullScreen ) { HRESULT hr = S_OK; RECT rcCurrentClient; GetClientRect( DXUTGetHWND(), &rcCurrentClient ); - DXUTDeviceSettings* pDevSettings = GetDXUTState().GetCurrentDeviceSettings(); - assert( pDevSettings != NULL ); + auto pDevSettings = GetDXUTState().GetCurrentDeviceSettings(); + assert( pDevSettings ); + _Analysis_assume_( pDevSettings ); - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); + auto pSwapChain = DXUTGetDXGISwapChain(); - ID3D11Device* pd3dDevice = DXUTGetD3D11Device(); - ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext(); + auto pd3dDevice = DXUTGetD3D11Device(); + assert( pd3dDevice ); + _Analysis_assume_( pd3dDevice ); + + auto pd3dImmediateContext = DXUTGetD3D11DeviceContext(); + assert( pd3dImmediateContext ); + _Analysis_assume_( pd3dImmediateContext ); // Determine if we're fullscreen pDevSettings->d3d11.sd.Windowed = !bFullScreen; @@ -4736,22 +3735,22 @@ void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullScreen ) GetDXUTState().SetInsideDeviceCallback( true ); LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallbackSwapChainReleasing = GetDXUTState().GetD3D11SwapChainReleasingFunc (); - if( pCallbackSwapChainReleasing != NULL ) + if( pCallbackSwapChainReleasing ) pCallbackSwapChainReleasing( GetDXUTState().GetD3D11SwapChainResizedFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); - // Release our old depth stencil texture and view - ID3D11Texture2D* pDS = GetDXUTState().GetD3D11DepthStencil(); + // Release our old depth stencil texture and view + auto pDS = GetDXUTState().GetD3D11DepthStencil(); SAFE_RELEASE( pDS ); - GetDXUTState().SetD3D11DepthStencil( NULL ); - ID3D11DepthStencilView* pDSV = GetDXUTState().GetD3D11DepthStencilView(); + GetDXUTState().SetD3D11DepthStencil( nullptr ); + auto pDSV = GetDXUTState().GetD3D11DepthStencilView(); SAFE_RELEASE( pDSV ); - GetDXUTState().SetD3D11DepthStencilView( NULL ); + GetDXUTState().SetD3D11DepthStencilView( nullptr ); // Release our old render target view - ID3D11RenderTargetView* pRTV = GetDXUTState().GetD3D11RenderTargetView(); + auto pRTV = GetDXUTState().GetD3D11RenderTargetView(); SAFE_RELEASE( pRTV ); - GetDXUTState().SetD3D11RenderTargetView( NULL ); + GetDXUTState().SetD3D11RenderTargetView( nullptr ); // Alternate between 0 and DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH when resizing buffers. // When in windowed mode, we want 0 since this allows the app to change to the desktop @@ -4794,10 +3793,10 @@ void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullScreen ) // Call the app's SwapChain reset callback GetDXUTState().SetInsideDeviceCallback( true ); - const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc = DXUTGetDXGIBackBufferSurfaceDesc(); + auto pBackBufferSurfaceDesc = DXUTGetDXGIBackBufferSurfaceDesc(); LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallbackSwapChainResized = GetDXUTState().GetD3D11SwapChainResizedFunc(); hr = S_OK; - if( pCallbackSwapChainResized != NULL ) + if( pCallbackSwapChainResized ) hr = pCallbackSwapChainResized( pd3dDevice, pSwapChain, pBackBufferSurfaceDesc, GetDXUTState().GetD3D11SwapChainResizedFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); @@ -4809,13 +3808,18 @@ void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullScreen ) hr = DXUTERR_RESETTINGDEVICEOBJECTS; GetDXUTState().SetInsideDeviceCallback( true ); - LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallbackSwapChainReleasing = + pCallbackSwapChainReleasing = GetDXUTState().GetD3D11SwapChainReleasingFunc(); - if( pCallbackSwapChainReleasing != NULL ) + if( pCallbackSwapChainReleasing ) pCallbackSwapChainReleasing( GetDXUTState().GetD3D11SwapChainResizedFuncUserContext() ); GetDXUTState().SetInsideDeviceCallback( false ); DXUTPause( false, false ); - PostQuitMessage( 0 ); + + LPDXUTCALLBACKQUIT pQuitCallback = GetDXUTState().GetQuitFunc(); + if (pQuitCallback) + { + pQuitCallback(GetDXUTState().GetQuitFuncUserContext()); + } } else { @@ -4829,14 +3833,21 @@ void DXUTResizeDXGIBuffers( UINT Width, UINT Height, BOOL bFullScreen ) //-------------------------------------------------------------------------------------- void DXUTCheckForDXGIBufferChange() { - if(DXUTGetDXGISwapChain() != NULL && !GetDXUTState().GetReleasingSwapChain() ) + if(DXUTGetDXGISwapChain() && !GetDXUTState().GetReleasingSwapChain() ) { //DXUTgetdxgi - IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); + auto pSwapChain = DXUTGetDXGISwapChain(); + assert(pSwapChain); + _Analysis_assume_(pSwapChain); +// workaround for SAL bug in DXGI header +#pragma warning(push) +#pragma warning( disable:4616 6309 6387 ) // Determine if we're fullscreen BOOL bFullScreen; - pSwapChain->GetFullscreenState( &bFullScreen, NULL ); + if ( FAILED(pSwapChain->GetFullscreenState(&bFullScreen, nullptr)) ) + bFullScreen = FALSE; +#pragma warning(pop) DXUTResizeDXGIBuffers( 0, 0, bFullScreen ); @@ -4850,37 +3861,16 @@ void DXUTCheckForDXGIBufferChange() void DXUTCheckForWindowSizeChange() { // Skip the check for various reasons - - if( GetDXUTState().GetIgnoreSizeChange() || !GetDXUTState().GetDeviceCreated() || - ( DXUTIsCurrentDeviceD3D9() && !DXUTIsWindowed() ) ) - return; - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - if( DXUTIsD3D9( &deviceSettings ) ) - { - RECT rcCurrentClient; - GetClientRect( DXUTGetHWND(), &rcCurrentClient ); - - if( ( UINT )rcCurrentClient.right != DXUTGetBackBufferWidthFromDS( &deviceSettings ) || - ( UINT )rcCurrentClient.bottom != DXUTGetBackBufferHeightFromDS( &deviceSettings ) ) - { - // A new window size will require a new backbuffer size size - // Tell DXUTChangeDevice and D3D to size according to the HWND's client rect - if( DXUTIsD3D9( &deviceSettings ) ) deviceSettings.d3d9.pp.BackBufferWidth = 0; else deviceSettings.d3d11.sd.BufferDesc.Width = 0; - if( DXUTIsD3D9( &deviceSettings ) ) deviceSettings.d3d9.pp.BackBufferHeight = 0; else deviceSettings.d3d11.sd.BufferDesc.Height = 0; + if( GetDXUTState().GetIgnoreSizeChange() || !GetDXUTState().GetDeviceCreated() ) + return; - DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false ); - } - } - else - { - DXUTCheckForDXGIBufferChange(); - } + DXUTCheckForDXGIBufferChange(); } //-------------------------------------------------------------------------------------- -// Checks to see if the HWND changed monitors, and if it did it creates a device +// Checks to see if the HWND changed monitors, and if it did it creates a device // from the monitor's adapter and recreates the scene. //-------------------------------------------------------------------------------------- void DXUTCheckForWindowChangingMonitors() @@ -4899,25 +3889,18 @@ void DXUTCheckForWindowChangingMonitors() if( SUCCEEDED( DXUTGetAdapterOrdinalFromMonitor( hWindowMonitor, &newOrdinal ) ) ) { // Find the closest valid device settings with the new ordinal - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); - if( DXUTIsD3D9( &deviceSettings ) ) - { - deviceSettings.d3d9.AdapterOrdinal = newOrdinal; - } - else - { - deviceSettings.d3d11.AdapterOrdinal = newOrdinal; - UINT newOutput; - if( SUCCEEDED( DXUTGetOutputOrdinalFromMonitor( hWindowMonitor, &newOutput ) ) ) - deviceSettings.d3d11.Output = newOutput; - } + auto deviceSettings = DXUTGetDeviceSettings(); + deviceSettings.d3d11.AdapterOrdinal = newOrdinal; + UINT newOutput; + if( SUCCEEDED( DXUTGetOutputOrdinalFromMonitor( hWindowMonitor, &newOutput ) ) ) + deviceSettings.d3d11.Output = newOutput; hr = DXUTSnapDeviceSettingsToEnumDevice( &deviceSettings, false ); if( SUCCEEDED( hr ) ) { - // Create a Direct3D device using the new device settings. + // Create a Direct3D device using the new device settings. // If there is an existing device, then it will either reset or recreate the scene. - hr = DXUTChangeDevice( &deviceSettings, NULL, NULL, false, false ); + hr = DXUTChangeDevice( &deviceSettings, false ); // If hr == E_ABORT, this means the app rejected the device settings in the ModifySettingsCallback if( hr == E_ABORT ) @@ -4938,112 +3921,60 @@ void DXUTCheckForWindowChangingMonitors() //-------------------------------------------------------------------------------------- -// Renders the scene using either D3D9 or D3D11 -//-------------------------------------------------------------------------------------- -void WINAPI DXUTRender3DEnvironment() -{ - if( DXUTIsCurrentDeviceD3D9() ) - DXUTRender3DEnvironment9(); - else - DXUTRender3DEnvironment11(); -} - - -//-------------------------------------------------------------------------------------- -// Cleans up both the D3D9 and D3D11 3D environment (but only one should be active at a time) -//-------------------------------------------------------------------------------------- -void DXUTCleanup3DEnvironment( bool bReleaseSettings ) -{ - if( DXUTGetD3D9Device() ) - DXUTCleanup3DEnvironment9( bReleaseSettings ); - if( DXUTGetD3D11Device() ) - DXUTCleanup3DEnvironment11( bReleaseSettings ); -} - - -//-------------------------------------------------------------------------------------- // Returns the HMONITOR attached to an adapter/output //-------------------------------------------------------------------------------------- -HMONITOR DXUTGetMonitorFromAdapter( DXUTDeviceSettings* pDeviceSettings ) +HMONITOR DXUTGetMonitorFromAdapter( _In_ DXUTDeviceSettings* pDeviceSettings ) { - if( pDeviceSettings->ver == DXUT_D3D9_DEVICE ) - { - IDirect3D9* pD3D = DXUTGetD3D9Object(); - assert( pD3D != NULL ); - return pD3D->GetAdapterMonitor( pDeviceSettings->d3d9.AdapterOrdinal ); - } - else if( pDeviceSettings->ver == DXUT_D3D11_DEVICE ) - { - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); - assert( pD3DEnum != NULL ); - CD3D11EnumOutputInfo* pOutputInfo = pD3DEnum->GetOutputInfo( pDeviceSettings->d3d11.AdapterOrdinal, - pDeviceSettings->d3d11.Output ); - if( !pOutputInfo ) - return 0; - return DXUTMonitorFromRect( &pOutputInfo->Desc.DesktopCoordinates, MONITOR_DEFAULTTONEAREST ); - } - - return 0; + auto pD3DEnum = DXUTGetD3D11Enumeration(); + assert( pD3DEnum ); + _Analysis_assume_( pD3DEnum ); + auto pOutputInfo = pD3DEnum->GetOutputInfo( pDeviceSettings->d3d11.AdapterOrdinal, + pDeviceSettings->d3d11.Output ); + if( !pOutputInfo ) + return 0; + return DXUTMonitorFromRect( &pOutputInfo->Desc.DesktopCoordinates, MONITOR_DEFAULTTONEAREST ); } //-------------------------------------------------------------------------------------- // Look for an adapter ordinal that is tied to a HMONITOR //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT DXUTGetAdapterOrdinalFromMonitor( HMONITOR hMonitor, UINT* pAdapterOrdinal ) { *pAdapterOrdinal = 0; - if( DXUTIsCurrentDeviceD3D9() ) - { - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration(); - IDirect3D9* pD3D = DXUTGetD3D9Object(); + // Get the monitor handle information + MONITORINFOEX mi; + mi.cbSize = sizeof( MONITORINFOEX ); + DXUTGetMonitorInfo( hMonitor, &mi ); - CGrowableArray <CD3D9EnumAdapterInfo*>* pAdapterList = pd3dEnum->GetAdapterInfoList(); - for( int iAdapter = 0; iAdapter < pAdapterList->GetSize(); iAdapter++ ) + // Search for this monitor in our enumeration hierarchy. + auto pd3dEnum = DXUTGetD3D11Enumeration(); + auto pAdapterList = pd3dEnum->GetAdapterInfoList(); + for( auto it = pAdapterList->cbegin(); it != pAdapterList->cend(); ++it ) + { + auto pAdapterInfo = *it; + for( auto jit = pAdapterInfo->outputInfoList.cbegin(); jit != pAdapterInfo->outputInfoList.cend(); ++jit ) { - CD3D9EnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt( iAdapter ); - HMONITOR hAdapterMonitor = pD3D->GetAdapterMonitor( pAdapterInfo->AdapterOrdinal ); - if( hAdapterMonitor == hMonitor ) + auto pOutputInfo = *jit; + // Convert output device name from MBCS to Unicode + if( wcsncmp( pOutputInfo->Desc.DeviceName, mi.szDevice, sizeof( mi.szDevice ) / sizeof + ( mi.szDevice[0] ) ) == 0 ) { *pAdapterOrdinal = pAdapterInfo->AdapterOrdinal; return S_OK; } } } - else - { - // Get the monitor handle information - MONITORINFOEX mi; - mi.cbSize = sizeof( MONITORINFOEX ); - DXUTGetMonitorInfo( hMonitor, &mi ); - - // Search for this monitor in our enumeration hierarchy. - CD3D11Enumeration* pd3dEnum = DXUTGetD3D11Enumeration(); - CGrowableArray <CD3D11EnumAdapterInfo*>* pAdapterList = pd3dEnum->GetAdapterInfoList(); - for( int iAdapter = 0; iAdapter < pAdapterList->GetSize(); ++iAdapter ) - { - CD3D11EnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt( iAdapter ); - for( int o = 0; o < pAdapterInfo->outputInfoList.GetSize(); ++o ) - { - CD3D11EnumOutputInfo* pOutputInfo = pAdapterInfo->outputInfoList.GetAt( o ); - // Convert output device name from MBCS to Unicode - if( wcsncmp( pOutputInfo->Desc.DeviceName, mi.szDevice, sizeof( mi.szDevice ) / sizeof - ( mi.szDevice[0] ) ) == 0 ) - { - *pAdapterOrdinal = pAdapterInfo->AdapterOrdinal; - return S_OK; - } - } - } - } - return E_FAIL; } + //-------------------------------------------------------------------------------------- // Look for a monitor ordinal that is tied to a HMONITOR (D3D11-only) //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT DXUTGetOutputOrdinalFromMonitor( HMONITOR hMonitor, UINT* pOutputOrdinal ) { // Get the monitor handle information @@ -5052,16 +3983,17 @@ HRESULT DXUTGetOutputOrdinalFromMonitor( HMONITOR hMonitor, UINT* pOutputOrdinal DXUTGetMonitorInfo( hMonitor, &mi ); // Search for this monitor in our enumeration hierarchy. - CD3D11Enumeration* pd3dEnum = DXUTGetD3D11Enumeration(); - CGrowableArray <CD3D11EnumAdapterInfo*>* pAdapterList = pd3dEnum->GetAdapterInfoList(); - for( int iAdapter = 0; iAdapter < pAdapterList->GetSize(); ++iAdapter ) + auto pd3dEnum = DXUTGetD3D11Enumeration(); + auto pAdapterList = pd3dEnum->GetAdapterInfoList(); + for( auto it = pAdapterList->cbegin(); it != pAdapterList->cend(); ++it ) { - CD3D11EnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt( iAdapter ); - for( int o = 0; o < pAdapterInfo->outputInfoList.GetSize(); ++o ) + auto pAdapterInfo = *it; + for( auto jit = pAdapterInfo->outputInfoList.cbegin(); jit != pAdapterInfo->outputInfoList.cend(); ++jit ) { - CD3D11EnumOutputInfo* pOutputInfo = pAdapterInfo->outputInfoList.GetAt( o ); + auto pOutputInfo = *jit; DXGI_OUTPUT_DESC Desc; - pOutputInfo->m_pOutput->GetDesc( &Desc ); + if ( FAILED(pOutputInfo->m_pOutput->GetDesc(&Desc)) ) + memset( &Desc, 0, sizeof(Desc) ); if( hMonitor == Desc.Monitor ) { @@ -5074,6 +4006,7 @@ HRESULT DXUTGetOutputOrdinalFromMonitor( HMONITOR hMonitor, UINT* pOutputOrdinal return E_FAIL; } + //-------------------------------------------------------------------------------------- // This method is called when D3DERR_DEVICEREMOVED is returned from an API. DXUT // calls the application's DeviceRemoved callback to inform it of the event. The @@ -5093,7 +4026,7 @@ HRESULT DXUTHandleDeviceRemoved() if( bLookForNewDevice ) { - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + auto pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); hr = DXUTSnapDeviceSettingsToEnumDevice( pDeviceSettings, false); @@ -5101,7 +4034,7 @@ HRESULT DXUTHandleDeviceRemoved() { // Change to a Direct3D device created from the new device settings // that is compatible with the removed device. - hr = DXUTChangeDevice( pDeviceSettings, NULL, NULL, true, false ); + hr = DXUTChangeDevice( pDeviceSettings, false ); if( SUCCEEDED( hr ) ) return S_OK; } @@ -5117,38 +4050,23 @@ HRESULT DXUTHandleDeviceRemoved() //-------------------------------------------------------------------------------------- void DXUTUpdateBackBufferDesc() { - if( DXUTIsCurrentDeviceD3D9() ) - { - HRESULT hr; - IDirect3DSurface9* pBackBuffer; - hr = GetDXUTState().GetD3D9Device()->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer ); - D3DSURFACE_DESC* pBBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDesc9(); - ZeroMemory( pBBufferSurfaceDesc, sizeof( D3DSURFACE_DESC ) ); - if( SUCCEEDED( hr ) ) - { - pBackBuffer->GetDesc( pBBufferSurfaceDesc ); - SAFE_RELEASE( pBackBuffer ); - } - } - else + HRESULT hr; + ID3D11Texture2D* pBackBuffer; + auto pSwapChain = GetDXUTState().GetDXGISwapChain(); + assert( pSwapChain ); + _Analysis_assume_( pSwapChain ); + hr = pSwapChain->GetBuffer( 0, IID_PPV_ARGS(&pBackBuffer) ); + auto pBBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDescDXGI(); + ZeroMemory( pBBufferSurfaceDesc, sizeof( DXGI_SURFACE_DESC ) ); + if( SUCCEEDED( hr ) ) { - HRESULT hr; - ID3D11Texture2D* pBackBuffer; - IDXGISwapChain* pSwapChain = GetDXUTState().GetDXGISwapChain(); - assert( pSwapChain != NULL ); - hr = pSwapChain->GetBuffer( 0, __uuidof( *pBackBuffer ), ( LPVOID* )&pBackBuffer ); - DXGI_SURFACE_DESC* pBBufferSurfaceDesc = GetDXUTState().GetBackBufferSurfaceDescDXGI(); - ZeroMemory( pBBufferSurfaceDesc, sizeof( DXGI_SURFACE_DESC ) ); - if( SUCCEEDED( hr ) ) - { - D3D11_TEXTURE2D_DESC TexDesc; - pBackBuffer->GetDesc( &TexDesc ); - pBBufferSurfaceDesc->Width = ( UINT )TexDesc.Width; - pBBufferSurfaceDesc->Height = ( UINT )TexDesc.Height; - pBBufferSurfaceDesc->Format = TexDesc.Format; - pBBufferSurfaceDesc->SampleDesc = TexDesc.SampleDesc; - SAFE_RELEASE( pBackBuffer ); - } + D3D11_TEXTURE2D_DESC TexDesc; + pBackBuffer->GetDesc( &TexDesc ); + pBBufferSurfaceDesc->Width = ( UINT )TexDesc.Width; + pBBufferSurfaceDesc->Height = ( UINT )TexDesc.Height; + pBBufferSurfaceDesc->Format = TexDesc.Format; + pBBufferSurfaceDesc->SampleDesc = TexDesc.SampleDesc; + SAFE_RELEASE( pBackBuffer ); } } @@ -5158,54 +4076,17 @@ void DXUTUpdateBackBufferDesc() //-------------------------------------------------------------------------------------- void DXUTSetupCursor() { - if( DXUTIsCurrentDeviceD3D9() ) + // Clip cursor if requested + if( !DXUTIsWindowed() && GetDXUTState().GetClipCursorWhenFullScreen() ) { - // Show the cursor again if returning to fullscreen - IDirect3DDevice9* pd3dDevice = DXUTGetD3D9Device(); - if( !DXUTIsWindowed() && pd3dDevice ) - { - if( GetDXUTState().GetShowCursorWhenFullScreen() ) - { - SetCursor( NULL ); // Turn off Windows cursor in full screen mode - HCURSOR hCursor = ( HCURSOR )( ULONG_PTR )GetClassLongPtr( DXUTGetHWNDDeviceFullScreen(), - GCLP_HCURSOR ); - DXUTSetD3D9DeviceCursor( pd3dDevice, hCursor, false ); - DXUTGetD3D9Device()->ShowCursor( true ); - } - else - { - SetCursor( NULL ); // Turn off Windows cursor in full screen mode - DXUTGetD3D9Device()->ShowCursor( false ); - } - } - - // Clip cursor if requested - if( !DXUTIsWindowed() && GetDXUTState().GetClipCursorWhenFullScreen() ) - { - // Confine cursor to full screen window - RECT rcWindow; - GetWindowRect( DXUTGetHWNDDeviceFullScreen(), &rcWindow ); - ClipCursor( &rcWindow ); - } - else - { - ClipCursor( NULL ); - } + // Confine cursor to full screen window + RECT rcWindow; + GetWindowRect( DXUTGetHWNDDeviceFullScreen(), &rcWindow ); + ClipCursor( &rcWindow ); } else { - // Clip cursor if requested - if( !DXUTIsWindowed() && GetDXUTState().GetClipCursorWhenFullScreen() ) - { - // Confine cursor to full screen window - RECT rcWindow; - GetWindowRect( DXUTGetHWNDDeviceFullScreen(), &rcWindow ); - ClipCursor( &rcWindow ); - } - else - { - ClipCursor( NULL ); - } + ClipCursor( nullptr ); } } @@ -5218,92 +4099,32 @@ void DXUTUpdateStaticFrameStats() if( GetDXUTState().GetNoStats() ) return; - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - if( NULL == pDeviceSettings ) + auto pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + if( !pDeviceSettings ) return; - if( DXUTIsD3D9( pDeviceSettings ) ) - { - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration(); - if( NULL == pd3dEnum ) - return; - - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( - pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, - pDeviceSettings->d3d9.AdapterFormat, pDeviceSettings->d3d9.pp.BackBufferFormat, - pDeviceSettings->d3d9.pp.Windowed ); - if( NULL == pDeviceSettingsCombo ) - return; - - WCHAR strFmt[100]; - D3DPRESENT_PARAMETERS* pPP = &pDeviceSettings->d3d9.pp; - - if( pDeviceSettingsCombo->AdapterFormat == pDeviceSettingsCombo->BackBufferFormat ) - { - wcscpy_s( strFmt, 100, DXUTD3DFormatToString( pDeviceSettingsCombo->AdapterFormat, false ) ); - } - else - { - swprintf_s( strFmt, 100, L"backbuf %s, adapter %s", - DXUTD3DFormatToString( pDeviceSettingsCombo->BackBufferFormat, false ), - DXUTD3DFormatToString( pDeviceSettingsCombo->AdapterFormat, false ) ); - } - - WCHAR strDepthFmt[100]; - if( pPP->EnableAutoDepthStencil ) - { - swprintf_s( strDepthFmt, 100, L" (%s)", DXUTD3DFormatToString( pPP->AutoDepthStencilFormat, false ) ); - } - else - { - // No depth buffer - strDepthFmt[0] = 0; - } - - WCHAR strMultiSample[100]; - switch( pPP->MultiSampleType ) - { - case D3DMULTISAMPLE_NONMASKABLE: - wcscpy_s( strMultiSample, 100, L" (Nonmaskable Multisample)" ); break; - case D3DMULTISAMPLE_NONE: - wcscpy_s( strMultiSample, 100, L"" ); break; - default: - swprintf_s( strMultiSample, 100, L" (%dx Multisample)", pPP->MultiSampleType ); break; - } - - WCHAR* pstrStaticFrameStats = GetDXUTState().GetStaticFrameStats(); - swprintf_s( pstrStaticFrameStats, 256, L"D3D9 %%sVsync %s (%dx%d), %s%s%s", - ( pPP->PresentationInterval == D3DPRESENT_INTERVAL_IMMEDIATE ) ? L"off" : L"on", - pPP->BackBufferWidth, pPP->BackBufferHeight, - strFmt, strDepthFmt, strMultiSample ); - } - else - { - // D3D11 - CD3D11Enumeration* pd3dEnum = DXUTGetD3D11Enumeration(); - if( NULL == pd3dEnum ) - return; - - CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( - pDeviceSettings->d3d11.AdapterOrdinal, pDeviceSettings->d3d11.DriverType, pDeviceSettings->d3d11.Output, - pDeviceSettings->d3d11.sd.BufferDesc.Format, pDeviceSettings->d3d11.sd.Windowed ); - if( NULL == pDeviceSettingsCombo ) - return; - - WCHAR strFmt[100]; - - wcscpy_s( strFmt, 100, DXUTDXGIFormatToString( pDeviceSettingsCombo->BackBufferFormat, false ) ); + // D3D11 + auto pd3dEnum = DXUTGetD3D11Enumeration(); + if( !pd3dEnum ) + return; - WCHAR strMultiSample[100]; - swprintf_s( strMultiSample, 100, L" (MS%u, Q%u)", pDeviceSettings->d3d11.sd.SampleDesc.Count, - pDeviceSettings->d3d11.sd.SampleDesc.Quality ); + auto pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( + pDeviceSettings->d3d11.AdapterOrdinal, + pDeviceSettings->d3d11.sd.BufferDesc.Format, pDeviceSettings->d3d11.sd.Windowed ); + if( !pDeviceSettingsCombo ) + return; - WCHAR* pstrStaticFrameStats = GetDXUTState().GetStaticFrameStats(); - swprintf_s( pstrStaticFrameStats, 256, L"D3D11 %%sVsync %s (%dx%d), %s%s", - ( pDeviceSettings->d3d11.SyncInterval == 0 ) ? L"off" : L"on", - pDeviceSettings->d3d11.sd.BufferDesc.Width, pDeviceSettings->d3d11.sd.BufferDesc.Height, - strFmt, strMultiSample ); - } + WCHAR strFmt[100]; + wcscpy_s( strFmt, 100, DXUTDXGIFormatToString( pDeviceSettingsCombo->BackBufferFormat, false ) ); + + WCHAR strMultiSample[100]; + swprintf_s( strMultiSample, 100, L" (MS%u, Q%u)", pDeviceSettings->d3d11.sd.SampleDesc.Count, + pDeviceSettings->d3d11.sd.SampleDesc.Quality ); + auto pstrStaticFrameStats = GetDXUTState().GetStaticFrameStats(); + swprintf_s( pstrStaticFrameStats, 256, L"D3D11 %%ls Vsync %ls (%ux%u), %ls%ls", + ( pDeviceSettings->d3d11.SyncInterval == 0 ) ? L"off" : L"on", + pDeviceSettings->d3d11.sd.BufferDesc.Width, pDeviceSettings->d3d11.sd.BufferDesc.Height, + strFmt, strMultiSample ); } @@ -5330,85 +4151,39 @@ void DXUTUpdateFrameStats() GetDXUTState().SetLastStatsUpdateTime( fAbsTime ); GetDXUTState().SetLastStatsUpdateFrames( 0 ); - WCHAR* pstrFPS = GetDXUTState().GetFPSStats(); + auto pstrFPS = GetDXUTState().GetFPSStats(); swprintf_s( pstrFPS, 64, L"%0.2f fps ", fFPS ); } } + //-------------------------------------------------------------------------------------- // Returns a string describing the current device. If bShowFPS is true, then -// the string contains the frames/sec. If "-nostats" was used in +// the string contains the frames/sec. If "-nostats" was used in // the command line, the string will be blank //-------------------------------------------------------------------------------------- -LPCWSTR WINAPI DXUTGetFrameStats( bool bShowFPS ) +LPCWSTR WINAPI DXUTGetFrameStats( _In_ bool bShowFPS ) { - WCHAR* pstrFrameStats = GetDXUTState().GetFrameStats(); - WCHAR* pstrFPS = ( bShowFPS ) ? GetDXUTState().GetFPSStats() : L""; - swprintf_s( pstrFrameStats, 256, GetDXUTState().GetStaticFrameStats(), pstrFPS ); + auto pstrFrameStats = GetDXUTState().GetFrameStats(); + const WCHAR* pstrFPS = ( bShowFPS ) ? GetDXUTState().GetFPSStats() : L""; + WCHAR* pstrStats = GetDXUTState().GetStaticFrameStats(); + swprintf_s( pstrFrameStats, 256, pstrStats, pstrFPS ); return pstrFrameStats; } //-------------------------------------------------------------------------------------- -// Updates the string which describes the device +// Updates the string which describes the device //-------------------------------------------------------------------------------------- -void DXUTUpdateD3D9DeviceStats( D3DDEVTYPE DeviceType, DWORD BehaviorFlags, - D3DADAPTER_IDENTIFIER9* pAdapterIdentifier ) +#pragma warning( suppress : 6101 ) +_Use_decl_annotations_ +void DXUTUpdateD3D11DeviceStats( D3D_DRIVER_TYPE DeviceType, D3D_FEATURE_LEVEL featureLevel, DXGI_ADAPTER_DESC* pAdapterDesc ) { if( GetDXUTState().GetNoStats() ) return; // Store device description - WCHAR* pstrDeviceStats = GetDXUTState().GetDeviceStats(); - if( DeviceType == D3DDEVTYPE_REF ) - wcscpy_s( pstrDeviceStats, 256, L"REF" ); - else if( DeviceType == D3DDEVTYPE_HAL ) - wcscpy_s( pstrDeviceStats, 256, L"HAL" ); - else if( DeviceType == D3DDEVTYPE_SW ) - wcscpy_s( pstrDeviceStats, 256, L"SW" ); - - if( DeviceType == D3DDEVTYPE_HAL ) - { - // Be sure not to overflow m_strDeviceStats when appending the adapter - // description, since it can be long. - wcscat_s( pstrDeviceStats, 256, L": " ); - - // Try to get a unique description from the CD3D9EnumDeviceSettingsCombo - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); - if( !pDeviceSettings ) - return; - - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration(); - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( - pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, - pDeviceSettings->d3d9.AdapterFormat, pDeviceSettings->d3d9.pp.BackBufferFormat, - pDeviceSettings->d3d9.pp.Windowed ); - if( pDeviceSettingsCombo ) - { - wcscat_s( pstrDeviceStats, 256, pDeviceSettingsCombo->pAdapterInfo->szUniqueDescription ); - } - else - { - const int cchDesc = sizeof( pAdapterIdentifier->Description ); - WCHAR szDescription[cchDesc]; - MultiByteToWideChar( CP_ACP, 0, pAdapterIdentifier->Description, -1, szDescription, cchDesc ); - szDescription[cchDesc - 1] = 0; - wcscat_s( pstrDeviceStats, 256, szDescription ); - } - } -} - - -//-------------------------------------------------------------------------------------- -// Updates the string which describes the device -//-------------------------------------------------------------------------------------- -void DXUTUpdateD3D11DeviceStats( D3D_DRIVER_TYPE DeviceType, DXGI_ADAPTER_DESC* pAdapterDesc ) -{ - if( GetDXUTState().GetNoStats() ) - return; - - // Store device description - WCHAR* pstrDeviceStats = GetDXUTState().GetDeviceStats(); + auto pstrDeviceStats = GetDXUTState().GetDeviceStats(); if( DeviceType == D3D_DRIVER_TYPE_REFERENCE ) wcscpy_s( pstrDeviceStats, 256, L"REFERENCE" ); else if( DeviceType == D3D_DRIVER_TYPE_HARDWARE ) @@ -5420,25 +4195,59 @@ void DXUTUpdateD3D11DeviceStats( D3D_DRIVER_TYPE DeviceType, DXGI_ADAPTER_DESC* if( DeviceType == D3D_DRIVER_TYPE_HARDWARE ) { - // Be sure not to overflow m_strDeviceStats when appending the adapter - // description, since it can be long. + // Be sure not to overflow m_strDeviceStats when appending the adapter + // description, since it can be long. wcscat_s( pstrDeviceStats, 256, L": " ); // Try to get a unique description from the CD3D11EnumDeviceSettingsCombo - DXUTDeviceSettings* pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); + auto pDeviceSettings = GetDXUTState().GetCurrentDeviceSettings(); if( !pDeviceSettings ) return; - CD3D11Enumeration* pd3dEnum = DXUTGetD3D11Enumeration(); - assert( pd3dEnum != NULL ); - CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( - pDeviceSettings->d3d11.AdapterOrdinal, pDeviceSettings->d3d11.DriverType, pDeviceSettings->d3d11.Output, + auto pd3dEnum = DXUTGetD3D11Enumeration(); + assert( pd3dEnum ); + _Analysis_assume_( pd3dEnum ); + auto pDeviceSettingsCombo = pd3dEnum->GetDeviceSettingsCombo( + pDeviceSettings->d3d11.AdapterOrdinal, pDeviceSettings->d3d11.sd.BufferDesc.Format, pDeviceSettings->d3d11.sd.Windowed ); if( pDeviceSettingsCombo ) wcscat_s( pstrDeviceStats, 256, pDeviceSettingsCombo->pAdapterInfo->szUniqueDescription ); else wcscat_s( pstrDeviceStats, 256, pAdapterDesc->Description ); } + + switch( featureLevel ) + { + case D3D_FEATURE_LEVEL_9_1: + wcscat_s( pstrDeviceStats, 256, L" (FL 9.1)" ); + break; + case D3D_FEATURE_LEVEL_9_2: + wcscat_s( pstrDeviceStats, 256, L" (FL 9.2)" ); + break; + case D3D_FEATURE_LEVEL_9_3: + wcscat_s( pstrDeviceStats, 256, L" (FL 9.3)" ); + break; + case D3D_FEATURE_LEVEL_10_0: + wcscat_s( pstrDeviceStats, 256, L" (FL 10.0)" ); + break; + case D3D_FEATURE_LEVEL_10_1: + wcscat_s( pstrDeviceStats, 256, L" (FL 10.1)" ); + break; + case D3D_FEATURE_LEVEL_11_0: + wcscat_s( pstrDeviceStats, 256, L" (FL 11.0)" ); + break; + case D3D_FEATURE_LEVEL_11_1: + wcscat_s( pstrDeviceStats, 256, L" (FL 11.1)" ); + break; +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + case D3D_FEATURE_LEVEL_12_0: + wcscat_s(pstrDeviceStats, 256, L" (FL 12.0)"); + break; + case D3D_FEATURE_LEVEL_12_1: + wcscat_s(pstrDeviceStats, 256, L" (FL 12.1)"); + break; +#endif + } } @@ -5449,7 +4258,7 @@ DXUTDeviceSettings WINAPI DXUTGetDeviceSettings() { // Return a copy of device settings of the current device. If no device exists yet, then // return a blank device settings struct - DXUTDeviceSettings* pDS = GetDXUTState().GetCurrentDeviceSettings(); + auto pDS = GetDXUTState().GetCurrentDeviceSettings(); if( pDS ) { return *pDS; @@ -5462,32 +4271,12 @@ DXUTDeviceSettings WINAPI DXUTGetDeviceSettings() } } -D3DPRESENT_PARAMETERS WINAPI DXUTGetD3D9PresentParameters() -{ - // Return a copy of the present params of the current device. If no device exists yet, then - // return blank present params - DXUTDeviceSettings* pDS = GetDXUTState().GetCurrentDeviceSettings(); - if( pDS ) - { - return pDS->d3d9.pp; - } - else - { - D3DPRESENT_PARAMETERS pp; - ZeroMemory( &pp, sizeof( D3DPRESENT_PARAMETERS ) ); - return pp; - } -} - bool WINAPI DXUTIsVsyncEnabled() { - DXUTDeviceSettings* pDS = GetDXUTState().GetCurrentDeviceSettings(); + auto pDS = GetDXUTState().GetCurrentDeviceSettings(); if( pDS ) { - if( DXUTIsD3D9( pDS ) ) - return ( pDS->d3d9.pp.PresentationInterval == D3DPRESENT_INTERVAL_IMMEDIATE ); - else - return ( pDS->d3d11.SyncInterval == 0 ); + return ( pDS->d3d11.SyncInterval == 0 ); } else { @@ -5495,15 +4284,7 @@ bool WINAPI DXUTIsVsyncEnabled() } }; -HRESULT WINAPI DXUTGetD3D9DeviceCaps( DXUTDeviceSettings* pDeviceSettings, D3DCAPS9* pCaps ) -{ - IDirect3D9* pD3D = DXUTGetD3D9Object(); - assert( pD3D != NULL ); - return pD3D->GetDeviceCaps( pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, pCaps ); -} - - -bool WINAPI DXUTIsKeyDown( BYTE vKey ) +bool WINAPI DXUTIsKeyDown( _In_ BYTE vKey ) { bool* bKeys = GetDXUTState().GetKeys(); if( vKey >= 0xA0 && vKey <= 0xA5 ) // VK_LSHIFT, VK_RSHIFT, VK_LCONTROL, VK_RCONTROL, VK_LMENU, VK_RMENU @@ -5514,7 +4295,7 @@ bool WINAPI DXUTIsKeyDown( BYTE vKey ) return bKeys[vKey]; } -bool WINAPI DXUTWasKeyPressed( BYTE vKey ) +bool WINAPI DXUTWasKeyPressed( _In_ BYTE vKey ) { bool* bLastKeys = GetDXUTState().GetLastKeys(); bool* bKeys = GetDXUTState().GetKeys(); @@ -5522,18 +4303,19 @@ bool WINAPI DXUTWasKeyPressed( BYTE vKey ) return ( !bLastKeys[vKey] && bKeys[vKey] ); } -bool WINAPI DXUTIsMouseButtonDown( BYTE vButton ) +bool WINAPI DXUTIsMouseButtonDown( _In_ BYTE vButton ) { bool* bMouseButtons = GetDXUTState().GetMouseButtons(); int nIndex = DXUTMapButtonToArrayIndex( vButton ); return bMouseButtons[nIndex]; } -void WINAPI DXUTSetMultimonSettings( bool bAutoChangeAdapter ) +void WINAPI DXUTSetMultimonSettings( _In_ bool bAutoChangeAdapter ) { GetDXUTState().SetAutoChangeAdapter( bAutoChangeAdapter ); } +_Use_decl_annotations_ void WINAPI DXUTSetHotkeyHandling( bool bAltEnterToToggleFullscreen, bool bEscapeToQuit, bool bPauseToToggleTimePause ) { GetDXUTState().SetHandleEscape( bEscapeToQuit ); @@ -5541,6 +4323,7 @@ void WINAPI DXUTSetHotkeyHandling( bool bAltEnterToToggleFullscreen, bool bEscap GetDXUTState().SetHandlePause( bPauseToToggleTimePause ); } +_Use_decl_annotations_ void WINAPI DXUTSetCursorSettings( bool bShowCursorWhenFullScreen, bool bClipCursorWhenFullScreen ) { GetDXUTState().SetClipCursorWhenFullScreen( bClipCursorWhenFullScreen ); @@ -5548,11 +4331,12 @@ void WINAPI DXUTSetCursorSettings( bool bShowCursorWhenFullScreen, bool bClipCur DXUTSetupCursor(); } -void WINAPI DXUTSetWindowSettings( bool bCallDefWindowProc ) +void WINAPI DXUTSetWindowSettings( _In_ bool bCallDefWindowProc ) { GetDXUTState().SetCallDefWindowProc( bCallDefWindowProc ); } +_Use_decl_annotations_ void WINAPI DXUTSetConstantFrameTime( bool bEnabled, float fTimePerFrame ) { if( GetDXUTState().GetOverrideConstantFrameTime() ) @@ -5566,7 +4350,7 @@ void WINAPI DXUTSetConstantFrameTime( bool bEnabled, float fTimePerFrame ) //-------------------------------------------------------------------------------------- -// Resets the state associated with DXUT +// Resets the state associated with DXUT //-------------------------------------------------------------------------------------- void WINAPI DXUTResetFrameworkState() { @@ -5578,10 +4362,10 @@ void WINAPI DXUTResetFrameworkState() //-------------------------------------------------------------------------------------- // Closes down the window. When the window closes, it will cleanup everything //-------------------------------------------------------------------------------------- -void WINAPI DXUTShutdown( int nExitCode ) +void WINAPI DXUTShutdown( _In_ int nExitCode ) { HWND hWnd = DXUTGetHWND(); - if( hWnd != NULL ) + if( hWnd ) SendMessage( hWnd, WM_CLOSE, 0, 0 ); GetDXUTState().SetExitCode( nExitCode ); @@ -5589,48 +4373,41 @@ void WINAPI DXUTShutdown( int nExitCode ) DXUTCleanup3DEnvironment( true ); // Restore shortcut keys (Windows key, accessibility shortcuts) to original state - // This is important to call here if the shortcuts are disabled, + // This is important to call here if the shortcuts are disabled, // because accessibility setting changes are permanent. - // This means that if this is not done then the accessibility settings - // might not be the same as when the app was started. + // This means that if this is not done then the accessibility settings + // might not be the same as when the app was started. // If the app crashes without restoring the settings, this is also true so it - // would be wise to backup/restore the settings from a file so they can be + // would be wise to backup/restore the settings from a file so they can be // restored when the crashed app is run again. DXUTAllowShortcutKeys( true ); - // Shutdown D3D9 - IDirect3D9* pD3D = GetDXUTState().GetD3D9(); - SAFE_RELEASE( pD3D ); - GetDXUTState().SetD3D9( NULL ); - // Shutdown D3D11 - IDXGIFactory1* pDXGIFactory = GetDXUTState().GetDXGIFactory(); + auto pDXGIFactory = GetDXUTState().GetDXGIFactory(); SAFE_RELEASE( pDXGIFactory ); - GetDXUTState().SetDXGIFactory( NULL ); - - if( GetDXUTState().GetOverrideRelaunchMCE() ) - DXUTReLaunchMediaCenter(); + GetDXUTState().SetDXGIFactory( nullptr ); } + //-------------------------------------------------------------------------------------- // Tells DXUT whether to operate in gamma correct mode //-------------------------------------------------------------------------------------- -void WINAPI DXUTSetIsInGammaCorrectMode( bool bGammaCorrect ) +void WINAPI DXUTSetIsInGammaCorrectMode( _In_ bool bGammaCorrect ) { GetDXUTState().SetIsInGammaCorrectMode( bGammaCorrect ); } -void DXUTApplyDefaultDeviceSettings(DXUTDeviceSettings *modifySettings) { +//-------------------------------------------------------------------------------------- +void DXUTApplyDefaultDeviceSettings(DXUTDeviceSettings *modifySettings) +{ ZeroMemory( modifySettings, sizeof( DXUTDeviceSettings ) ); - - modifySettings->ver = DXUT_D3D11_DEVICE; modifySettings->d3d11.AdapterOrdinal = 0; modifySettings->d3d11.AutoCreateDepthStencil = true; modifySettings->d3d11.AutoDepthStencilFormat = DXGI_FORMAT_D24_UNORM_S8_UINT; #if defined(DEBUG) || defined(_DEBUG) - modifySettings->d3d11.CreateFlags |= D3D10_CREATE_DEVICE_DEBUG; + modifySettings->d3d11.CreateFlags |= D3D11_CREATE_DEVICE_DEBUG; #else modifySettings->d3d11.CreateFlags = 0; #endif @@ -5639,224 +4416,123 @@ void DXUTApplyDefaultDeviceSettings(DXUTDeviceSettings *modifySettings) { modifySettings->d3d11.PresentFlags = 0; modifySettings->d3d11.sd.BufferCount = 2; modifySettings->d3d11.sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - modifySettings->d3d11.sd.BufferDesc.Height = 480; - modifySettings->d3d11.sd.BufferDesc.RefreshRate.Numerator = 60; - modifySettings->d3d11.sd.BufferDesc.RefreshRate.Denominator = 1; + modifySettings->d3d11.sd.BufferDesc.Height = 600; + modifySettings->d3d11.sd.BufferDesc.RefreshRate.Numerator = 0; + modifySettings->d3d11.sd.BufferDesc.RefreshRate.Denominator = 0; modifySettings->d3d11.sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; modifySettings->d3d11.sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; - modifySettings->d3d11.sd.BufferDesc.Width = 640; + modifySettings->d3d11.sd.BufferDesc.Width = 800; modifySettings->d3d11.sd.BufferUsage = 32; modifySettings->d3d11.sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH ; modifySettings->d3d11.sd.OutputWindow = DXUTGetHWND(); modifySettings->d3d11.sd.SampleDesc.Count = 1; modifySettings->d3d11.sd.SampleDesc.Quality = 0; modifySettings->d3d11.sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; - modifySettings->d3d11.sd.Windowed = 1; + modifySettings->d3d11.sd.Windowed = TRUE; modifySettings->d3d11.SyncInterval = 0; - - modifySettings->d3d9.AdapterFormat = D3DFMT_X8R8G8B8; - modifySettings->d3d9.AdapterOrdinal = 0; - modifySettings->d3d9.BehaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING; - modifySettings->d3d9.DeviceType = D3DDEVTYPE_HAL; - modifySettings->d3d9.pp.AutoDepthStencilFormat = D3DFMT_D24X8; - modifySettings->d3d9.pp.BackBufferCount = 1; - modifySettings->d3d9.pp.BackBufferFormat = D3DFMT_X8R8G8B8; - modifySettings->d3d9.pp.BackBufferHeight = 480; - modifySettings->d3d9.pp.BackBufferWidth = 640; - modifySettings->d3d9.pp.EnableAutoDepthStencil = 1; - modifySettings->d3d9.pp.Flags = 2; - modifySettings->d3d9.pp.FullScreen_RefreshRateInHz = 0; - modifySettings->d3d9.pp.hDeviceWindow = DXUTGetHWND(); - modifySettings->d3d9.pp.MultiSampleQuality = 0; - modifySettings->d3d9.pp.MultiSampleType = D3DMULTISAMPLE_NONE; - modifySettings->d3d9.pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; - modifySettings->d3d9.pp.SwapEffect = D3DSWAPEFFECT_DISCARD; - modifySettings->d3d9.pp.Windowed = 1; } - //-------------------------------------------------------------------------------------- // Update settings based on what is enumeratabled //-------------------------------------------------------------------------------------- -HRESULT DXUTSnapDeviceSettingsToEnumDevice( DXUTDeviceSettings* pDeviceSettings, bool forceEnum, D3D_FEATURE_LEVEL forceFL ) { - bool bAppSupportsD3D9 = DXUTDoesAppSupportD3D9(); - bool bAppSupportsD3D11 = DXUTDoesAppSupportD3D11(); - - if( GetSystemMetrics(0x1000) != 0 ) {// SM_REMOTESESSION - pDeviceSettings->d3d11.sd.Windowed = 1; - pDeviceSettings->d3d9.pp.Windowed = 1; - } +_Use_decl_annotations_ +HRESULT DXUTSnapDeviceSettingsToEnumDevice( DXUTDeviceSettings* pDeviceSettings, bool forceEnum, D3D_FEATURE_LEVEL forceFL ) +{ + if( GetSystemMetrics(SM_REMOTESESSION) != 0 ) + { + pDeviceSettings->d3d11.sd.Windowed = TRUE; + } int bestModeIndex=0; int bestMSAAIndex=0; - //DXUTSetDefaultDeviceSettings - if (bAppSupportsD3D11 && pDeviceSettings->ver == DXUT_D3D11_DEVICE ) { - CD3D11Enumeration *pEnum = NULL; - - - pEnum = DXUTGetD3D11Enumeration( forceEnum, false, forceFL); + CD3D11Enumeration *pEnum = DXUTGetD3D11Enumeration( forceEnum, true, forceFL); - CD3D11EnumAdapterInfo* pAdapterInfo = NULL; - CGrowableArray <CD3D11EnumAdapterInfo*>* pAdapterList = pEnum->GetAdapterInfoList(); - CD3D11EnumAdapterInfo* tempAdapterInfo = pAdapterList->GetAt( 0 ); - for( int iAdapter = 0; iAdapter < pAdapterList->GetSize(); iAdapter++ ) + CD3D11EnumAdapterInfo* pAdapterInfo = nullptr; + auto pAdapterList = pEnum->GetAdapterInfoList(); + for( auto it = pAdapterList->cbegin(); it != pAdapterList->cend(); ++it ) + { + auto tempAdapterInfo = *it; + if (tempAdapterInfo->AdapterOrdinal == pDeviceSettings->d3d11.AdapterOrdinal) pAdapterInfo = tempAdapterInfo; + } + if ( !pAdapterInfo ) + { + if ( pAdapterList->empty() || pDeviceSettings->d3d11.AdapterOrdinal > 0 ) { - tempAdapterInfo = pAdapterList->GetAt( iAdapter ); - if (tempAdapterInfo->AdapterOrdinal == pDeviceSettings->d3d11.AdapterOrdinal) pAdapterInfo = tempAdapterInfo; + return E_FAIL; // no adapters found. } - if (pAdapterInfo == NULL) return E_FAIL; // no adapters found. - CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo = NULL; - float biggestScore = 0; + pAdapterInfo = *pAdapterList->cbegin(); + } + CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo = nullptr; + float biggestScore = 0; - int combo = 0; - for( int iDeviceCombo = 0; iDeviceCombo < pAdapterInfo->deviceSettingsComboList.GetSize(); iDeviceCombo++ ) + for( size_t iDeviceCombo = 0; iDeviceCombo < pAdapterInfo->deviceSettingsComboList.size(); iDeviceCombo++ ) + { + CD3D11EnumDeviceSettingsCombo* tempDeviceSettingsCombo = pAdapterInfo->deviceSettingsComboList[ iDeviceCombo ]; + + int bestMode; + int bestMSAA; + float score = DXUTRankD3D11DeviceCombo(tempDeviceSettingsCombo, &(pDeviceSettings->d3d11), bestMode, bestMSAA ); + if (score > biggestScore) { - CD3D11EnumDeviceSettingsCombo* tempDeviceSettingsCombo = pAdapterInfo->deviceSettingsComboList.GetAt( iDeviceCombo ); - - DXGI_MODE_DESC adapterDisplayMode; - DXUTGetD3D11AdapterDisplayMode( pAdapterInfo->AdapterOrdinal, 0, &adapterDisplayMode ); - - int bestMode; - int bestMSAA; - float score = DXUTRankD3D11DeviceCombo(tempDeviceSettingsCombo, &(pDeviceSettings->d3d11), &adapterDisplayMode, bestMode, bestMSAA ); - if (score > biggestScore) { - combo = iDeviceCombo; - biggestScore = score; - pDeviceSettingsCombo = tempDeviceSettingsCombo; - bestModeIndex = bestMode; - bestMSAAIndex = bestMSAA; - } - - } - if (NULL == pDeviceSettingsCombo ) { - return E_FAIL; // no settigns found. + biggestScore = score; + pDeviceSettingsCombo = tempDeviceSettingsCombo; + bestModeIndex = bestMode; + bestMSAAIndex = bestMSAA; } + } + if (!pDeviceSettingsCombo ) + { + return E_FAIL; // no settings found. + } - pDeviceSettings->d3d11.AdapterOrdinal = pDeviceSettingsCombo->AdapterOrdinal; - pDeviceSettings->d3d11.DriverType = pDeviceSettingsCombo->DeviceType; - pDeviceSettings->d3d11.Output = pDeviceSettingsCombo->Output; - - pDeviceSettings->d3d11.sd.Windowed = pDeviceSettingsCombo->Windowed; - if( GetSystemMetrics(0x1000) != 0 ) {// SM_REMOTESESSION - pDeviceSettings->d3d11.sd.Windowed = 1; - } - if (pDeviceSettingsCombo->pOutputInfo != NULL) { - DXGI_MODE_DESC bestDisplayMode; - bestDisplayMode = pDeviceSettingsCombo->pOutputInfo->displayModeList.GetAt(bestModeIndex); - if (!pDeviceSettingsCombo->Windowed) { - - pDeviceSettings->d3d11.sd.BufferDesc.Height = bestDisplayMode.Height; - pDeviceSettings->d3d11.sd.BufferDesc.Width = bestDisplayMode.Width; - pDeviceSettings->d3d11.sd.BufferDesc.RefreshRate.Numerator = bestDisplayMode.RefreshRate.Numerator; - pDeviceSettings->d3d11.sd.BufferDesc.RefreshRate.Denominator = bestDisplayMode.RefreshRate.Denominator; - pDeviceSettings->d3d11.sd.BufferDesc.Scaling = bestDisplayMode.Scaling; - pDeviceSettings->d3d11.sd.BufferDesc.ScanlineOrdering = bestDisplayMode.ScanlineOrdering; - } - } - if (pDeviceSettings->d3d11.DeviceFeatureLevel == 0) - pDeviceSettings->d3d11.DeviceFeatureLevel = pDeviceSettingsCombo->pDeviceInfo->SelectedLevel; - - - - - pDeviceSettings->d3d11.sd.SampleDesc.Count = pDeviceSettingsCombo->multiSampleCountList.GetAt(bestMSAAIndex); - if (pDeviceSettings->d3d11.sd.SampleDesc.Quality > pDeviceSettingsCombo->multiSampleQualityList.GetAt(bestMSAAIndex) - 1) - pDeviceSettings->d3d11.sd.SampleDesc.Quality = pDeviceSettingsCombo->multiSampleQualityList.GetAt(bestMSAAIndex) - 1; - - pDeviceSettings->d3d11.sd.BufferDesc.Format = pDeviceSettingsCombo->BackBufferFormat; - - return S_OK; - } - // didn't find a D3D11 adapter. - if (bAppSupportsD3D9) { - // Find the best combination of: - // Adapter Ordinal - // Device Type - // Adapter Format - // Back Buffer Format - // Windowed - // given what's available on the system and the match options combined with the device settings input. - // This combination of settings is encapsulated by the CD3D9EnumDeviceSettingsCombo class. - float fBestRanking = -1.0f; - CD3D9EnumDeviceSettingsCombo* pBestDeviceSettingsCombo = NULL; - D3DDISPLAYMODE adapterDesktopDisplayMode; - - IDirect3D9* pD3D = DXUTGetD3D9Object(); - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration( forceEnum ); - CGrowableArray <CD3D9EnumAdapterInfo*>* pAdapterList = pd3dEnum->GetAdapterInfoList(); - for( int iAdapter = 0; iAdapter < pAdapterList->GetSize(); iAdapter++ ) - { - CD3D9EnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt( iAdapter ); + pDeviceSettings->d3d11.AdapterOrdinal = pDeviceSettingsCombo->AdapterOrdinal; + pDeviceSettings->d3d11.DriverType = pDeviceSettingsCombo->DeviceType; + pDeviceSettings->d3d11.Output = pDeviceSettingsCombo->Output; - // Get the desktop display mode of adapter - pD3D->GetAdapterDisplayMode( pAdapterInfo->AdapterOrdinal, &adapterDesktopDisplayMode ); + pDeviceSettings->d3d11.sd.Windowed = pDeviceSettingsCombo->Windowed; + if( GetSystemMetrics(SM_REMOTESESSION) != 0 ) + { + pDeviceSettings->d3d11.sd.Windowed = TRUE; + } + if (pDeviceSettingsCombo->pOutputInfo) + { + auto bestDisplayMode = pDeviceSettingsCombo->pOutputInfo->displayModeList[ bestModeIndex ]; + if (!pDeviceSettingsCombo->Windowed) + { + pDeviceSettings->d3d11.sd.BufferDesc.Height = bestDisplayMode.Height; + pDeviceSettings->d3d11.sd.BufferDesc.Width = bestDisplayMode.Width; + pDeviceSettings->d3d11.sd.BufferDesc.RefreshRate.Numerator = bestDisplayMode.RefreshRate.Numerator; + pDeviceSettings->d3d11.sd.BufferDesc.RefreshRate.Denominator = bestDisplayMode.RefreshRate.Denominator; + pDeviceSettings->d3d11.sd.BufferDesc.Scaling = bestDisplayMode.Scaling; + pDeviceSettings->d3d11.sd.BufferDesc.ScanlineOrdering = bestDisplayMode.ScanlineOrdering; + } + } + if (pDeviceSettings->d3d11.DeviceFeatureLevel == 0) + pDeviceSettings->d3d11.DeviceFeatureLevel = pDeviceSettingsCombo->pDeviceInfo->SelectedLevel; - // Enum all the device types supported by this adapter to find the best device settings - for( int iDeviceInfo = 0; iDeviceInfo < pAdapterInfo->deviceInfoList.GetSize(); iDeviceInfo++ ) - { - CD3D9EnumDeviceInfo* pDeviceInfo = pAdapterInfo->deviceInfoList.GetAt( iDeviceInfo ); + if ( pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_WARP ) + { + D3D_FEATURE_LEVEL maxWarpFL = pEnum->GetWARPFeaturevel(); - // Enum all the device settings combinations. A device settings combination is - // a unique set of an adapter format, back buffer format, and IsWindowed. - for( int iDeviceCombo = 0; iDeviceCombo < pDeviceInfo->deviceSettingsComboList.GetSize(); iDeviceCombo++ ) - { - CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo = pDeviceInfo->deviceSettingsComboList.GetAt( - iDeviceCombo ); + if ( pDeviceSettings->d3d11.DeviceFeatureLevel > maxWarpFL ) + pDeviceSettings->d3d11.DeviceFeatureLevel = maxWarpFL; + } - // If windowed mode the adapter format has to be the same as the desktop - // display mode format so skip any that don't match - if( pDeviceSettingsCombo->Windowed && - ( pDeviceSettingsCombo->AdapterFormat != adapterDesktopDisplayMode.Format ) ) - continue; + if ( pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) + { + D3D_FEATURE_LEVEL maxRefFL = pEnum->GetREFFeaturevel(); - // Skip any combo that doesn't meet the preserve match options - int bestMode; - int bestMSAA; + if ( pDeviceSettings->d3d11.DeviceFeatureLevel > maxRefFL ) + pDeviceSettings->d3d11.DeviceFeatureLevel = maxRefFL; + } - // Get a ranking number that describes how closely this device combo matches the optimal combo - float fCurRanking = DXUTRankD3D9DeviceCombo( pDeviceSettingsCombo, - &(pDeviceSettings->d3d9), &adapterDesktopDisplayMode, bestMode, bestMSAA ); + pDeviceSettings->d3d11.sd.SampleDesc.Count = pDeviceSettingsCombo->multiSampleCountList[ bestMSAAIndex ]; + if (pDeviceSettings->d3d11.sd.SampleDesc.Quality > pDeviceSettingsCombo->multiSampleQualityList[ bestMSAAIndex ] - 1) + pDeviceSettings->d3d11.sd.SampleDesc.Quality = pDeviceSettingsCombo->multiSampleQualityList[ bestMSAAIndex ] - 1; - // If this combo better matches the input device settings then save it - if( fCurRanking > fBestRanking ) - { - pBestDeviceSettingsCombo = pDeviceSettingsCombo; - fBestRanking = fCurRanking; - bestModeIndex = bestMode; - bestMSAAIndex = bestMSAA; - } - } - } - } + pDeviceSettings->d3d11.sd.BufferDesc.Format = pDeviceSettingsCombo->BackBufferFormat; - // If no best device combination was found then fail - if( pBestDeviceSettingsCombo == NULL ) - return DXUTERR_NOCOMPATIBLEDEVICES; - - // Using the best device settings combo found, build valid device settings taking heed of - // the match options and the input device settings - pDeviceSettings->d3d9.AdapterFormat = pBestDeviceSettingsCombo->AdapterFormat;//D3DFMT_X8R8G8B8; - pDeviceSettings->d3d9.AdapterOrdinal = pBestDeviceSettingsCombo->AdapterOrdinal ;//0; - pDeviceSettings->d3d9.DeviceType = pBestDeviceSettingsCombo->DeviceType; - pDeviceSettings->d3d9.pp.BackBufferFormat = pBestDeviceSettingsCombo->BackBufferFormat;//D3DFMT_X8R8G8B8; - if( GetSystemMetrics(0x1000) != 0 ) {// SM_REMOTESESSION - pDeviceSettings->d3d9.pp.Windowed = 1; - } - if (!pBestDeviceSettingsCombo->Windowed) { - D3DDISPLAYMODE displayMode = pBestDeviceSettingsCombo->pAdapterInfo->displayModeList.GetAt( bestModeIndex ); - pDeviceSettings->d3d9.pp.BackBufferHeight = displayMode.Height; - pDeviceSettings->d3d9.pp.BackBufferWidth = displayMode.Width; - pDeviceSettings->d3d9.pp.FullScreen_RefreshRateInHz = displayMode.RefreshRate; - } - pDeviceSettings->d3d9.pp.hDeviceWindow = pBestDeviceSettingsCombo->Windowed ? DXUTGetHWNDDeviceWindowed() : DXUTGetHWNDDeviceFullScreen(); - if (pDeviceSettings->d3d9.pp.MultiSampleQuality > pBestDeviceSettingsCombo->multiSampleQualityList.GetAt(bestMSAAIndex) - 1) - pDeviceSettings->d3d9.pp.MultiSampleQuality = pBestDeviceSettingsCombo->multiSampleQualityList.GetAt( bestMSAAIndex )-1; - - pDeviceSettings->d3d9.pp.MultiSampleType = pBestDeviceSettingsCombo->multiSampleTypeList.GetAt( bestMSAAIndex );; - pDeviceSettings->d3d9.pp.Windowed = pBestDeviceSettingsCombo->Windowed; - return S_OK; - } - return E_FAIL; + return S_OK; } diff --git a/samples/DX_APIUsage/DXUT/Core/DXUT.h b/samples/DX_APIUsage/DXUT/Core/DXUT.h index a436262..37129d1 100644 --- a/samples/DX_APIUsage/DXUT/Core/DXUT.h +++ b/samples/DX_APIUsage/DXUT/Core/DXUT.h @@ -2,10 +2,11 @@ // File: DXUT.h // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef DXUT_H -#define DXUT_H #ifndef UNICODE #error "DXUT requires a Unicode build." @@ -15,55 +16,59 @@ #define STRICT #endif -// If app hasn't choosen, set to work with Windows XP and beyond +// If app hasn't choosen, set to work with Windows Vista and beyond #ifndef WINVER -#define WINVER 0x0501 +#define WINVER 0x0600 #endif #ifndef _WIN32_WINDOWS -#define _WIN32_WINDOWS 0x0501 +#define _WIN32_WINDOWS 0x0600 #endif #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0600 #endif +#if defined(USE_DIRECT3D11_4) && !defined(USE_DIRECT3D11_3) +#define USE_DIRECT3D11_3 +#endif + +#if (_WIN32_WINNT >= 0x0A00) && !defined(USE_DIRECT3D11_3) +#define USE_DIRECT3D11_3 +#endif + +#if (_WIN32_WINNT >= 0x0603) && !defined(USE_DIRECT3D11_2) +#define USE_DIRECT3D11_2 +#endif + +#if defined(USE_DIRECT3D11_3) && !defined(USE_DIRECT3D11_2) +#define USE_DIRECT3D11_2 +#endif + // #define DXUT_AUTOLIB to automatically include the libs needed for DXUT #ifdef DXUT_AUTOLIB -#pragma comment( lib, "dxerr.lib" ) +#pragma comment( lib, "comctl32.lib" ) #pragma comment( lib, "dxguid.lib" ) -#pragma comment( lib, "d3d9.lib" ) -#if defined(DEBUG) || defined(_DEBUG) -#pragma comment( lib, "d3dx9d.lib" ) -#pragma comment( lib, "d3dx11d.lib" ) -#else -#pragma comment( lib, "d3dx9.lib" ) -#pragma comment( lib, "d3dx11.lib" ) -#endif #pragma comment( lib, "d3dcompiler.lib" ) -#pragma comment( lib, "winmm.lib" ) -#pragma comment( lib, "comctl32.lib" ) +#pragma comment( lib, "ole32.lib" ) +#pragma comment( lib, "uuid.lib" ) #endif -#pragma warning( disable : 4100 ) // disable unreference formal parameter warnings for /W4 builds +#pragma warning( disable : 4481 ) -// Enable extra D3D debugging in debug builds if using the debug DirectX runtime. -// This makes D3D objects work well in the debugger watch window, but slows down -// performance slightly. -#if defined(DEBUG) || defined(_DEBUG) -#ifndef D3D_DEBUG_INFO -#define D3D_DEBUG_INFO -#endif +// Standard Windows includes +#if !defined(NOMINMAX) +#define NOMINMAX #endif -// Standard Windows includes #include <windows.h> #include <initguid.h> #include <assert.h> -#include <wchar.h> -#include <mmsystem.h> #include <commctrl.h> // for InitCommonControls() #include <shellapi.h> // for ExtractIcon() #include <new.h> // for placement new +#pragma warning(push, 3) +#pragma warning(disable : 4091) #include <shlobj.h> +#pragma warning(pop) #include <math.h> #include <limits.h> #include <stdio.h> @@ -73,24 +78,54 @@ #include <crtdbg.h> #endif -// Direct3D9 includes -#include <d3d9.h> -#include <d3dx9.h> - // Direct3D11 includes #include <d3dcommon.h> #include <dxgi.h> -#include <d3d11.h> +#include <d3d11_1.h> #include <d3dcompiler.h> -#include <d3dx11.h> + +#ifdef USE_DIRECT3D11_2 +#include <d3d11_2.h> +#endif + +#ifdef USE_DIRECT3D11_3 +#include <d3d11_3.h> +#endif + +#ifdef USE_DIRECT3D11_4 +#include <d3d11_4.h> +#endif + +// DirectXMath includes +#pragma warning(push, 3) +#pragma warning(disable : 4838) +#include <DirectXMath.h> +#include <DirectXColors.h> +#pragma warning(pop) + +// WIC includes +#include <wincodec.h> // XInput includes #include <xinput.h> -// HRESULT translation for Direct3D and other APIs -#include <dxerr.h> +// dxerr.h is deprecated and gone. Replace usage here +#if defined(DEBUG) | defined(_DEBUG) +#define DXTRACE_MSG(str) DXUTTrace( __FILE__, (DWORD)__LINE__, 0, str, FALSE ) +#define DXTRACE_ERR(str,hr) DXUTTrace( __FILE__, (DWORD)__LINE__, hr, str, FALSE ) +#define DXTRACE_ERR_MSGBOX(str,hr) DXUTTrace( __FILE__, (DWORD)__LINE__, hr, str, TRUE ) +#else +#define DXTRACE_MSG(str) (0L) +#define DXTRACE_ERR(str,hr) (hr) +#define DXTRACE_ERR_MSGBOX(str,hr) (hr) +#endif +// STL includes +#include <algorithm> +#include <memory> +#include <vector> + #if defined(DEBUG) || defined(_DEBUG) #ifndef V #define V(x) { hr = (x); if( FAILED(hr) ) { DXUTTrace( __FILE__, (DWORD)__LINE__, hr, L#x, true ); } } @@ -108,29 +143,25 @@ #endif #ifndef SAFE_DELETE -#define SAFE_DELETE(p) { if (p) { delete (p); (p)=NULL; } } +#define SAFE_DELETE(p) { if (p) { delete (p); (p) = nullptr; } } #endif #ifndef SAFE_DELETE_ARRAY -#define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p)=NULL; } } +#define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p) = nullptr; } } #endif #ifndef SAFE_RELEASE -#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p)=NULL; } } +#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = nullptr; } } #endif +#ifndef D3DCOLOR_ARGB +#define D3DCOLOR_ARGB(a,r,g,b) \ + ((DWORD)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff))) +#endif +#define DXUT_VERSION 1118 //-------------------------------------------------------------------------------------- // Structs //-------------------------------------------------------------------------------------- -struct DXUTD3D9DeviceSettings -{ - UINT AdapterOrdinal; - D3DDEVTYPE DeviceType; - D3DFORMAT AdapterFormat; - DWORD BehaviorFlags; - D3DPRESENT_PARAMETERS pp; -}; - struct DXUTD3D11DeviceSettings { UINT AdapterOrdinal; @@ -145,18 +176,10 @@ struct DXUTD3D11DeviceSettings D3D_FEATURE_LEVEL DeviceFeatureLevel; }; -enum DXUTDeviceVersion -{ - DXUT_D3D9_DEVICE, - DXUT_D3D11_DEVICE -}; - struct DXUTDeviceSettings { - DXUTDeviceVersion ver; D3D_FEATURE_LEVEL MinimumFeatureLevel; - DXUTD3D9DeviceSettings d3d9; // only valid if ver == DXUT_D3D9_DEVICE - DXUTD3D11DeviceSettings d3d11; // only valid if ver == DXUT_D3D11_DEVICE + DXUTD3D11DeviceSettings d3d11; }; @@ -172,88 +195,77 @@ struct DXUTDeviceSettings #define DXUTERR_CREATINGDEVICEOBJECTS MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0907) #define DXUTERR_RESETTINGDEVICEOBJECTS MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0908) #define DXUTERR_DEVICEREMOVED MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x090A) -#define DXUTERR_NODIRECT3D11 MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x090) + //-------------------------------------------------------------------------------------- // Callback registration //-------------------------------------------------------------------------------------- // General callbacks -typedef void (CALLBACK *LPDXUTCALLBACKFRAMEMOVE)( double fTime, float fElapsedTime, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKKEYBOARD)( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKMOUSE)( bool bLeftButtonDown, bool bRightButtonDown, bool bMiddleButtonDown, bool bSideButton1Down, bool bSideButton2Down, int nMouseWheelDelta, int xPos, int yPos, void* pUserContext ); -typedef LRESULT (CALLBACK *LPDXUTCALLBACKMSGPROC)( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKTIMER)( UINT idEvent, void* pUserContext ); -typedef bool (CALLBACK *LPDXUTCALLBACKMODIFYDEVICESETTINGS)( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); -typedef bool (CALLBACK *LPDXUTCALLBACKDEVICEREMOVED)( void* pUserContext ); - -// Direct3D 9 callbacks -typedef bool (CALLBACK *LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE)( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); -typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D9DEVICECREATED)( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); -typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D9DEVICERESET)( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKD3D9FRAMERENDER)( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKD3D9DEVICELOST)( void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKD3D9DEVICEDESTROYED)( void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKFRAMEMOVE)( _In_ double fTime, _In_ float fElapsedTime, _In_opt_ void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKKEYBOARD)( _In_ UINT nChar, _In_ bool bKeyDown, _In_ bool bAltDown, _In_opt_ void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKMOUSE)( _In_ bool bLeftButtonDown, _In_ bool bRightButtonDown, _In_ bool bMiddleButtonDown, + _In_ bool bSideButton1Down, _In_ bool bSideButton2Down, _In_ int nMouseWheelDelta, + _In_ int xPos, _In_ int yPos, _In_opt_ void* pUserContext ); +typedef LRESULT (CALLBACK *LPDXUTCALLBACKMSGPROC)( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam, + _Out_ bool* pbNoFurtherProcessing, _In_opt_ void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKTIMER)( _In_ UINT idEvent, _In_opt_ void* pUserContext ); +typedef bool (CALLBACK *LPDXUTCALLBACKMODIFYDEVICESETTINGS)( _In_ DXUTDeviceSettings* pDeviceSettings, _In_opt_ void* pUserContext ); +typedef bool (CALLBACK *LPDXUTCALLBACKDEVICEREMOVED)( _In_opt_ void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKQUIT)( _In_opt_ void* pUserContext ); class CD3D11EnumAdapterInfo; class CD3D11EnumDeviceInfo; + // Direct3D 11 callbacks -typedef bool (CALLBACK *LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE)( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); -typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D11DEVICECREATED)( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); -typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D11SWAPCHAINRESIZED)( ID3D11Device* pd3dDevice, IDXGISwapChain *pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKD3D11FRAMERENDER)( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, float fElapsedTime, void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKD3D11SWAPCHAINRELEASING)( void* pUserContext ); -typedef void (CALLBACK *LPDXUTCALLBACKD3D11DEVICEDESTROYED)( void* pUserContext ); +typedef bool (CALLBACK *LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE)( _In_ const CD3D11EnumAdapterInfo *AdapterInfo, _In_ UINT Output, _In_ const CD3D11EnumDeviceInfo *DeviceInfo, + _In_ DXGI_FORMAT BackBufferFormat, _In_ bool bWindowed, _In_opt_ void* pUserContext ); +typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D11DEVICECREATED)( _In_ ID3D11Device* pd3dDevice, _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, _In_opt_ void* pUserContext ); +typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D11SWAPCHAINRESIZED)( _In_ ID3D11Device* pd3dDevice, _In_ IDXGISwapChain *pSwapChain, _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, _In_opt_ void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKD3D11FRAMERENDER)( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3dImmediateContext, _In_ double fTime, _In_ float fElapsedTime, _In_opt_ void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKD3D11SWAPCHAINRELEASING)( _In_opt_ void* pUserContext ); +typedef void (CALLBACK *LPDXUTCALLBACKD3D11DEVICEDESTROYED)( _In_opt_ void* pUserContext ); // General callbacks -void WINAPI DXUTSetCallbackFrameMove( LPDXUTCALLBACKFRAMEMOVE pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackKeyboard( LPDXUTCALLBACKKEYBOARD pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackMouse( LPDXUTCALLBACKMOUSE pCallback, bool bIncludeMouseMove = false, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackMsgProc( LPDXUTCALLBACKMSGPROC pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackDeviceChanging( LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackDeviceRemoved( LPDXUTCALLBACKDEVICEREMOVED pCallback, void* pUserContext = NULL ); - -// Direct3D 9 callbacks -void WINAPI DXUTSetCallbackD3D9DeviceAcceptable( LPDXUTCALLBACKISD3D9DEVICEACCEPTABLE pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D9DeviceCreated( LPDXUTCALLBACKD3D9DEVICECREATED pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D9DeviceReset( LPDXUTCALLBACKD3D9DEVICERESET pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D9FrameRender( LPDXUTCALLBACKD3D9FRAMERENDER pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D9DeviceLost( LPDXUTCALLBACKD3D9DEVICELOST pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D9DeviceDestroyed( LPDXUTCALLBACKD3D9DEVICEDESTROYED pCallback, void* pUserContext = NULL ); +void WINAPI DXUTSetCallbackFrameMove( _In_ LPDXUTCALLBACKFRAMEMOVE pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackKeyboard( _In_ LPDXUTCALLBACKKEYBOARD pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackMouse( _In_ LPDXUTCALLBACKMOUSE pCallback, bool bIncludeMouseMove = false, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackMsgProc( _In_ LPDXUTCALLBACKMSGPROC pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackDeviceChanging( _In_ LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackDeviceRemoved( _In_ LPDXUTCALLBACKDEVICEREMOVED pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackQuit( _In_ LPDXUTCALLBACKQUIT pCallback, _In_opt_ void* pUserContext = nullptr ); // Direct3D 11 callbacks -void WINAPI DXUTSetCallbackD3D11DeviceAcceptable( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D11DeviceCreated( LPDXUTCALLBACKD3D11DEVICECREATED pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D11SwapChainResized( LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D11FrameRender( LPDXUTCALLBACKD3D11FRAMERENDER pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D11SwapChainReleasing( LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallback, void* pUserContext = NULL ); -void WINAPI DXUTSetCallbackD3D11DeviceDestroyed( LPDXUTCALLBACKD3D11DEVICEDESTROYED pCallback, void* pUserContext = NULL ); +void WINAPI DXUTSetCallbackD3D11DeviceAcceptable( _In_ LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackD3D11DeviceCreated( _In_ LPDXUTCALLBACKD3D11DEVICECREATED pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackD3D11SwapChainResized( _In_ LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackD3D11FrameRender( _In_ LPDXUTCALLBACKD3D11FRAMERENDER pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackD3D11SwapChainReleasing( _In_ LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallback, _In_opt_ void* pUserContext = nullptr ); +void WINAPI DXUTSetCallbackD3D11DeviceDestroyed( _In_ LPDXUTCALLBACKD3D11DEVICEDESTROYED pCallback, _In_opt_ void* pUserContext = nullptr ); //-------------------------------------------------------------------------------------- // Initialization //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTInit( bool bParseCommandLine = true, - bool bShowMsgBoxOnError = true, - __in_opt WCHAR* strExtraCommandLineParams = NULL, - bool bThreadSafeDXUT = false ); +HRESULT WINAPI DXUTInit( _In_ bool bParseCommandLine = true, + _In_ bool bShowMsgBoxOnError = true, + _In_opt_ WCHAR* strExtraCommandLineParams = nullptr, + _In_ bool bThreadSafeDXUT = false ); // Choose either DXUTCreateWindow or DXUTSetWindow. If using DXUTSetWindow, consider using DXUTStaticWndProc -HRESULT WINAPI DXUTCreateWindow( const WCHAR* strWindowTitle = L"Direct3D Window", - HINSTANCE hInstance = NULL, HICON hIcon = NULL, HMENU hMenu = NULL, - int x = CW_USEDEFAULT, int y = CW_USEDEFAULT ); -HRESULT WINAPI DXUTSetWindow( HWND hWndFocus, HWND hWndDeviceFullScreen, HWND hWndDeviceWindowed, bool bHandleMessages = true ); -LRESULT CALLBACK DXUTStaticWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); +HRESULT WINAPI DXUTCreateWindow( _In_z_ const WCHAR* strWindowTitle = L"Direct3D Window", + _In_opt_ HINSTANCE hInstance = nullptr, _In_opt_ HICON hIcon = nullptr, _In_opt_ HMENU hMenu = nullptr, + _In_ int x = CW_USEDEFAULT, _In_ int y = CW_USEDEFAULT ); +HRESULT WINAPI DXUTSetWindow( _In_ HWND hWndFocus, _In_ HWND hWndDeviceFullScreen, _In_ HWND hWndDeviceWindowed, _In_ bool bHandleMessages = true ); +LRESULT CALLBACK DXUTStaticWndProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); -// Choose either DXUTCreateDevice or DXUTSetD3D*Device or DXUTCreateD3DDeviceFromSettings +// Choose either DXUTCreateDevice or DXUTCreateD3DDeviceFromSettings -HRESULT WINAPI DXUTCreateDevice(D3D_FEATURE_LEVEL reqFL, bool bWindowed= true, int nSuggestedWidth =0, int nSuggestedHeight =0 ); -HRESULT WINAPI DXUTCreateDeviceFromSettings( DXUTDeviceSettings* pDeviceSettings, bool bPreserveInput = false, bool bClipWindowToSingleAdapter = true ); -HRESULT WINAPI DXUTSetD3D9Device( IDirect3DDevice9* pd3dDevice ); -HRESULT WINAPI DXUTSetD3D11Device( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain ); +HRESULT WINAPI DXUTCreateDevice(_In_ D3D_FEATURE_LEVEL reqFL, _In_ bool bWindowed= true, _In_ int nSuggestedWidth =0,_In_ int nSuggestedHeight =0 ); +HRESULT WINAPI DXUTCreateDeviceFromSettings( _In_ DXUTDeviceSettings* pDeviceSettings, _In_ bool bClipWindowToSingleAdapter = true ); // Choose either DXUTMainLoop or implement your own main loop -HRESULT WINAPI DXUTMainLoop( HACCEL hAccel = NULL ); +HRESULT WINAPI DXUTMainLoop( _In_opt_ HACCEL hAccel = nullptr ); // If not using DXUTMainLoop consider using DXUTRender3DEnvironment void WINAPI DXUTRender3DEnvironment(); @@ -265,50 +277,54 @@ void WINAPI DXUTRender3DEnvironment(); HRESULT WINAPI DXUTToggleFullScreen(); HRESULT WINAPI DXUTToggleREF(); HRESULT WINAPI DXUTToggleWARP(); -void WINAPI DXUTPause( bool bPauseTime, bool bPauseRendering ); -void WINAPI DXUTSetConstantFrameTime( bool bConstantFrameTime, float fTimePerFrame = 0.0333f ); -void WINAPI DXUTSetCursorSettings( bool bShowCursorWhenFullScreen = false, bool bClipCursorWhenFullScreen = false ); -void WINAPI DXUTSetD3DVersionSupport( bool bAppCanUseD3D9 = true, bool bAppCanUseD3D11 = true ); -void WINAPI DXUTSetHotkeyHandling( bool bAltEnterToToggleFullscreen = true, bool bEscapeToQuit = true, bool bPauseToToggleTimePause = true ); -void WINAPI DXUTSetMultimonSettings( bool bAutoChangeAdapter = true ); -void WINAPI DXUTSetShortcutKeySettings( bool bAllowWhenFullscreen = false, bool bAllowWhenWindowed = true ); // Controls the Windows key, and accessibility shortcut keys -void WINAPI DXUTSetWindowSettings( bool bCallDefWindowProc = true ); -HRESULT WINAPI DXUTSetTimer( LPDXUTCALLBACKTIMER pCallbackTimer, float fTimeoutInSecs = 1.0f, UINT* pnIDEvent = NULL, void* pCallbackUserContext = NULL ); -HRESULT WINAPI DXUTKillTimer( UINT nIDEvent ); +void WINAPI DXUTPause( _In_ bool bPauseTime, _In_ bool bPauseRendering ); +void WINAPI DXUTSetConstantFrameTime( _In_ bool bConstantFrameTime, _In_ float fTimePerFrame = 0.0333f ); +void WINAPI DXUTSetCursorSettings( _In_ bool bShowCursorWhenFullScreen = false, _In_ bool bClipCursorWhenFullScreen = false ); +void WINAPI DXUTSetHotkeyHandling( _In_ bool bAltEnterToToggleFullscreen = true, _In_ bool bEscapeToQuit = true, _In_ bool bPauseToToggleTimePause = true ); +void WINAPI DXUTSetMultimonSettings( _In_ bool bAutoChangeAdapter = true ); +void WINAPI DXUTSetShortcutKeySettings( _In_ bool bAllowWhenFullscreen = false, _In_ bool bAllowWhenWindowed = true ); // Controls the Windows key, and accessibility shortcut keys +void WINAPI DXUTSetWindowSettings( _In_ bool bCallDefWindowProc = true ); +HRESULT WINAPI DXUTSetTimer( _In_ LPDXUTCALLBACKTIMER pCallbackTimer, _In_ float fTimeoutInSecs = 1.0f, _Out_opt_ UINT* pnIDEvent = nullptr, _In_opt_ void* pCallbackUserContext = nullptr ); +HRESULT WINAPI DXUTKillTimer( _In_ UINT nIDEvent ); void WINAPI DXUTResetFrameworkState(); -void WINAPI DXUTShutdown( int nExitCode = 0 ); -void WINAPI DXUTSetIsInGammaCorrectMode( bool bGammaCorrect ); -BOOL WINAPI DXUTGetMSAASwapChainCreated(); +void WINAPI DXUTShutdown( _In_ int nExitCode = 0 ); +void WINAPI DXUTSetIsInGammaCorrectMode( _In_ bool bGammaCorrect ); +bool WINAPI DXUTGetMSAASwapChainCreated(); + //-------------------------------------------------------------------------------------- // State Retrieval //-------------------------------------------------------------------------------------- -// Direct3D 9 -IDirect3D9* WINAPI DXUTGetD3D9Object(); // Does not addref unlike typical Get* APIs -IDirect3DDevice9* WINAPI DXUTGetD3D9Device(); // Does not addref unlike typical Get* APIs -D3DPRESENT_PARAMETERS WINAPI DXUTGetD3D9PresentParameters(); -const D3DSURFACE_DESC* WINAPI DXUTGetD3D9BackBufferSurfaceDesc(); -const D3DCAPS9* WINAPI DXUTGetD3D9DeviceCaps(); -HRESULT WINAPI DXUTGetD3D9DeviceCaps( DXUTDeviceSettings* pDeviceSettings, D3DCAPS9* pCaps ); -bool WINAPI DXUTDoesAppSupportD3D9(); -bool WINAPI DXUTIsAppRenderingWithD3D9(); +// Direct3D 11.x (These do not addref unlike typical Get* APIs) +IDXGIFactory1* WINAPI DXUTGetDXGIFactory(); +IDXGISwapChain* WINAPI DXUTGetDXGISwapChain(); +const DXGI_SURFACE_DESC* WINAPI DXUTGetDXGIBackBufferSurfaceDesc(); +HRESULT WINAPI DXUTSetupD3D11Views( _In_ ID3D11DeviceContext* pd3dDeviceContext ); // Supports immediate or deferred context +D3D_FEATURE_LEVEL WINAPI DXUTGetD3D11DeviceFeatureLevel(); // Returns the D3D11 devices current feature level +ID3D11RenderTargetView* WINAPI DXUTGetD3D11RenderTargetView(); +ID3D11DepthStencilView* WINAPI DXUTGetD3D11DepthStencilView(); +ID3D11Device* WINAPI DXUTGetD3D11Device(); +ID3D11DeviceContext* WINAPI DXUTGetD3D11DeviceContext(); -// Direct3D 11 -IDXGIFactory1* WINAPI DXUTGetDXGIFactory(); // Does not addref unlike typical Get* APIs -IDXGISwapChain* WINAPI DXUTGetDXGISwapChain(); // Does not addref unlike typical Get* APIs -const DXGI_SURFACE_DESC* WINAPI DXUTGetDXGIBackBufferSurfaceDesc(); -bool WINAPI DXUTIsD3D11Available(); // If D3D11 APIs are availible -ID3D11Device* WINAPI DXUTGetD3D11Device(); // Does not addref unlike typical Get* APIs -ID3D11DeviceContext* WINAPI DXUTGetD3D11DeviceContext(); // Does not addref unlike typical Get* APIs -HRESULT WINAPI DXUTSetupD3D11Views( ID3D11DeviceContext* pd3dDeviceContext ); // Supports immediate or deferred context -D3D_FEATURE_LEVEL WINAPI DXUTGetD3D11DeviceFeatureLevel(); // Returns the D3D11 devices current feature level -ID3D11RenderTargetView* WINAPI DXUTGetD3D11RenderTargetView(); // Does not addref unlike typical Get* APIs -ID3D11DepthStencilView* WINAPI DXUTGetD3D11DepthStencilView(); // Does not addref unlike typical Get* APIs -bool WINAPI DXUTDoesAppSupportD3D11(); -bool WINAPI DXUTIsAppRenderingWithD3D11(); +ID3D11Device1* WINAPI DXUTGetD3D11Device1(); +ID3D11DeviceContext1* WINAPI DXUTGetD3D11DeviceContext1(); +#ifdef USE_DIRECT3D11_2 +ID3D11Device2* WINAPI DXUTGetD3D11Device2(); +ID3D11DeviceContext2* WINAPI DXUTGetD3D11DeviceContext2(); +#endif + +#ifdef USE_DIRECT3D11_3 +ID3D11Device3* WINAPI DXUTGetD3D11Device3(); +ID3D11DeviceContext3* WINAPI DXUTGetD3D11DeviceContext3(); +#endif + +#ifdef USE_DIRECT3D11_4 +ID3D11Device4* WINAPI DXUTGetD3D11Device4(); +ID3D11DeviceContext4* WINAPI DXUTGetD3D11DeviceContext4(); +#endif // General DXUTDeviceSettings WINAPI DXUTGetDeviceSettings(); @@ -328,7 +344,7 @@ bool WINAPI DXUTIsWindowed(); bool WINAPI DXUTIsInGammaCorrectMode(); float WINAPI DXUTGetFPS(); LPCWSTR WINAPI DXUTGetWindowTitle(); -LPCWSTR WINAPI DXUTGetFrameStats( bool bIncludeFPS = false ); +LPCWSTR WINAPI DXUTGetFrameStats( _In_ bool bIncludeFPS = false ); LPCWSTR WINAPI DXUTGetDeviceStats(); bool WINAPI DXUTIsVsyncEnabled(); @@ -338,9 +354,9 @@ bool WINAPI DXUTIsActive(); int WINAPI DXUTGetExitCode(); bool WINAPI DXUTGetShowMsgBoxOnError(); bool WINAPI DXUTGetAutomation(); // Returns true if -automation parameter is used to launch the app -bool WINAPI DXUTIsKeyDown( BYTE vKey ); // Pass a virtual-key code, ex. VK_F1, 'A', VK_RETURN, VK_LSHIFT, etc -bool WINAPI DXUTWasKeyPressed( BYTE vKey ); // Like DXUTIsKeyDown() but return true only if the key was just pressed -bool WINAPI DXUTIsMouseButtonDown( BYTE vButton ); // Pass a virtual-key code: VK_LBUTTON, VK_RBUTTON, VK_MBUTTON, VK_XBUTTON1, VK_XBUTTON2 +bool WINAPI DXUTIsKeyDown( _In_ BYTE vKey ); // Pass a virtual-key code, ex. VK_F1, 'A', VK_RETURN, VK_LSHIFT, etc +bool WINAPI DXUTWasKeyPressed( _In_ BYTE vKey ); // Like DXUTIsKeyDown() but return true only if the key was just pressed +bool WINAPI DXUTIsMouseButtonDown( _In_ BYTE vButton ); // Pass a virtual-key code: VK_LBUTTON, VK_RBUTTON, VK_MBUTTON, VK_XBUTTON1, VK_XBUTTON2 HRESULT WINAPI DXUTCreateState(); // Optional method to create DXUT's memory. If its not called by the application it will be automatically called when needed void WINAPI DXUTDestroyState(); // Optional method to destroy DXUT's memory. If its not called by the application it will be automatically called after the application exits WinMain @@ -348,14 +364,4 @@ void WINAPI DXUTDestroyState(); // Optional method to destroy DXUT's memory // DXUT core layer includes //-------------------------------------------------------------------------------------- #include "DXUTmisc.h" -#include "DXUTDevice9.h" #include "DXUTDevice11.h" - - - - -#endif - - - - diff --git a/samples/DX_APIUsage/DXUT/Core/DXUTDevice11.cpp b/samples/DX_APIUsage/DXUT/Core/DXUTDevice11.cpp index 156f48d..eb5f968 100644 --- a/samples/DX_APIUsage/DXUT/Core/DXUTDevice11.cpp +++ b/samples/DX_APIUsage/DXUT/Core/DXUTDevice11.cpp @@ -4,10 +4,11 @@ // Enumerates D3D adapters, devices, modes, etc. // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "DXUT.h" -#undef min // use __min instead -#undef max // use __max instead //-------------------------------------------------------------------------------------- // Forward declarations @@ -16,17 +17,14 @@ extern void DXUTGetCallbackD3D11DeviceAcceptable( LPDXUTCALLBACKISD3D11DEVICEACC static int __cdecl SortModesCallback( const void* arg1, const void* arg2 ); -CD3D11Enumeration* g_pDXUTD3D11Enumeration = NULL; - - - +CD3D11Enumeration* g_pDXUTD3D11Enumeration = nullptr; HRESULT WINAPI DXUTCreateD3D11Enumeration() { - if( g_pDXUTD3D11Enumeration == NULL ) + if( !g_pDXUTD3D11Enumeration ) { - g_pDXUTD3D11Enumeration = new CD3D11Enumeration(); - if( NULL == g_pDXUTD3D11Enumeration ) + g_pDXUTD3D11Enumeration = new (std::nothrow) CD3D11Enumeration(); + if( !g_pDXUTD3D11Enumeration ) return E_OUTOFMEMORY; } return S_OK; @@ -40,18 +38,13 @@ void WINAPI DXUTDestroyD3D11Enumeration() class DXUTMemoryHelperD3D11Enum { public: -DXUTMemoryHelperD3D11Enum() -{ - DXUTCreateD3D11Enumeration(); -} -~DXUTMemoryHelperD3D11Enum() -{ - DXUTDestroyD3D11Enumeration(); -} +DXUTMemoryHelperD3D11Enum() { DXUTCreateD3D11Enumeration(); } +~DXUTMemoryHelperD3D11Enum() { DXUTDestroyD3D11Enumeration(); } }; //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ CD3D11Enumeration* WINAPI DXUTGetD3D11Enumeration( bool bForceEnumerate, bool bEnumerateAllAdapterFormats, D3D_FEATURE_LEVEL forceFL ) { // Using an static class with accessor function to allow control of the construction order @@ -72,21 +65,15 @@ CD3D11Enumeration* WINAPI DXUTGetD3D11Enumeration( bool bForceEnumerate, bool bE //-------------------------------------------------------------------------------------- -CD3D11Enumeration::CD3D11Enumeration() +CD3D11Enumeration::CD3D11Enumeration() : + m_bHasEnumerated(false), + m_IsD3D11DeviceAcceptableFunc(nullptr), + m_pIsD3D11DeviceAcceptableFuncUserContext(nullptr), + m_bEnumerateAllAdapterFormats(false), + m_forceFL(D3D_FEATURE_LEVEL(0)), + m_warpFL(D3D_FEATURE_LEVEL_10_1), + m_refFL(D3D_FEATURE_LEVEL_11_0) { - m_bHasEnumerated = false; - m_IsD3D11DeviceAcceptableFunc = NULL; - m_pIsD3D11DeviceAcceptableFuncUserContext = NULL; - - m_nMinWidth = 640; - m_nMinHeight = 480; - m_nMaxWidth = UINT_MAX; - m_nMaxHeight = UINT_MAX; - m_bEnumerateAllAdapterFormats = false; - - m_nRefreshMin = 0; - m_nRefreshMax = UINT_MAX; - ResetPossibleDepthStencilFormats(); } @@ -110,13 +97,14 @@ CD3D11Enumeration::~CD3D11Enumeration() // if supported otherwise it will default to SWVP, however the app can change this // through the ConfirmDevice callback. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3D11DeviceAcceptableFunc, void* pIsD3D11DeviceAcceptableFuncUserContext ) { CDXUTPerfEventGenerator eventGenerator( DXUT_PERFEVENTCOLOR, L"DXUT D3D11 Enumeration" ); HRESULT hr; - IDXGIFactory1* pFactory = DXUTGetDXGIFactory(); - if( pFactory == NULL ) + auto pFactory = DXUTGetDXGIFactory(); + if( !pFactory ) return E_FAIL; m_bHasEnumerated = true; @@ -127,18 +115,33 @@ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3 for( int index = 0; ; ++index ) { - IDXGIAdapter* pAdapter = NULL; + IDXGIAdapter* pAdapter = nullptr; hr = pFactory->EnumAdapters( index, &pAdapter ); if( FAILED( hr ) ) // DXGIERR_NOT_FOUND is expected when the end of the list is hit break; - CD3D11EnumAdapterInfo* pAdapterInfo = new CD3D11EnumAdapterInfo; + IDXGIAdapter2* pAdapter2 = nullptr; + if ( SUCCEEDED( pAdapter->QueryInterface( __uuidof(IDXGIAdapter2), ( LPVOID* )&pAdapter2 ) ) ) + { + // Succeeds on DirectX 11.1 Runtime systems + DXGI_ADAPTER_DESC2 desc; + hr = pAdapter2->GetDesc2( &desc ); + pAdapter2->Release(); + + if ( SUCCEEDED(hr) && ( desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE ) ) + { + // Skip "always there" Microsoft Basics Display Driver + pAdapter->Release(); + continue; + } + } + + auto pAdapterInfo = new (std::nothrow) CD3D11EnumAdapterInfo; if( !pAdapterInfo ) { SAFE_RELEASE( pAdapter ); return E_OUTOFMEMORY; } - ZeroMemory( pAdapterInfo, sizeof( CD3D11EnumAdapterInfo ) ); pAdapterInfo->AdapterOrdinal = index; pAdapter->GetDesc( &pAdapterInfo->AdapterDesc ); pAdapterInfo->m_pAdapter = pAdapter; @@ -152,38 +155,30 @@ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3 } hr = EnumerateOutputs( pAdapterInfo ); - if( FAILED( hr ) || pAdapterInfo->outputInfoList.GetSize() <= 0 ) + if( FAILED( hr ) || pAdapterInfo->outputInfoList.empty() ) { delete pAdapterInfo; continue; } // Get info for each devicecombo on this device - if( FAILED( hr = EnumerateDeviceCombos( pFactory, pAdapterInfo ) ) ) + if( FAILED( hr = EnumerateDeviceCombos( pAdapterInfo ) ) ) { delete pAdapterInfo; continue; } - hr = m_AdapterInfoList.Add( pAdapterInfo ); - if( FAILED( hr ) ) - { - delete pAdapterInfo; - return hr; - } + m_AdapterInfoList.push_back( pAdapterInfo ); } - // If we did not get an adapter then we should still enumerate WARP and Ref. - if (m_AdapterInfoList.GetSize() == 0) { - - - CD3D11EnumAdapterInfo* pAdapterInfo = new CD3D11EnumAdapterInfo; + if (m_AdapterInfoList.size() == 0) + { + auto pAdapterInfo = new (std::nothrow) CD3D11EnumAdapterInfo; if( !pAdapterInfo ) { return E_OUTOFMEMORY; } - ZeroMemory( pAdapterInfo, sizeof( CD3D11EnumAdapterInfo ) ); pAdapterInfo->bAdapterUnavailable = true; hr = EnumerateDevices( pAdapterInfo ); @@ -194,7 +189,7 @@ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3 delete pAdapterInfo; } - if (!FAILED(hr)) hr = m_AdapterInfoList.Add( pAdapterInfo ); + if (SUCCEEDED(hr)) m_AdapterInfoList.push_back( pAdapterInfo ); } // @@ -203,14 +198,13 @@ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3 // them. // bool bUniqueDesc = true; - CD3D11EnumAdapterInfo* pAdapterInfo; - for( int i = 0; i < m_AdapterInfoList.GetSize(); i++ ) + for( size_t i = 0; i < m_AdapterInfoList.size(); i++ ) { - CD3D11EnumAdapterInfo* pAdapterInfo1 = m_AdapterInfoList.GetAt( i ); + auto pAdapterInfo1 = m_AdapterInfoList[ i ]; - for( int j = i + 1; j < m_AdapterInfoList.GetSize(); j++ ) + for( size_t j = i + 1; j < m_AdapterInfoList.size(); j++ ) { - CD3D11EnumAdapterInfo* pAdapterInfo2 = m_AdapterInfoList.GetAt( j ); + auto pAdapterInfo2 = m_AdapterInfoList[ j ]; if( wcsncmp( pAdapterInfo1->AdapterDesc.Description, pAdapterInfo2->AdapterDesc.Description, DXGI_MAX_DEVICE_IDENTIFIER_STRING ) == 0 ) { @@ -223,17 +217,77 @@ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3 break; } - for( int i = 0; i < m_AdapterInfoList.GetSize(); i++ ) + for( auto it = m_AdapterInfoList.begin(); it != m_AdapterInfoList.end(); ++it ) { - pAdapterInfo = m_AdapterInfoList.GetAt( i ); - - wcscpy_s( pAdapterInfo->szUniqueDescription, 100, pAdapterInfo->AdapterDesc.Description ); + wcscpy_s((*it)->szUniqueDescription, DXGI_MAX_DEVICE_IDENTIFIER_STRING, (*it)->AdapterDesc.Description); if( !bUniqueDesc ) { - WCHAR sz[100]; - swprintf_s( sz, 100, L" (#%d)", pAdapterInfo->AdapterOrdinal ); - wcscat_s( pAdapterInfo->szUniqueDescription, DXGI_MAX_DEVICE_IDENTIFIER_STRING, sz ); + WCHAR sz[32]; + swprintf_s( sz, 32, L" (#%u)", (*it)->AdapterOrdinal ); + wcscat_s( (*it)->szUniqueDescription, DXGI_MAX_DEVICE_IDENTIFIER_STRING, sz ); + } + } + + // Check WARP max feature level + { + static const D3D_FEATURE_LEVEL fLvlWarp[] = + { +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + D3D_FEATURE_LEVEL_12_1, D3D_FEATURE_LEVEL_12_0, +#endif + D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1 + }; + + ID3D11Device* pDevice = nullptr; + hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, fLvlWarp, _countof(fLvlWarp), + D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr ); + if ( hr == E_INVALIDARG ) + { +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + // DirectX 11.1 runtime will not recognize FL 12.x, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, &fLvlWarp[2], _countof(fLvlWarp) - 2, + D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr); + if (hr == E_INVALIDARG) + { + // DirectX 11.0 runtime will not recognize FL 11.1+, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, &fLvlWarp[3], _countof(fLvlWarp) - 3, + D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr); + } +#else + // DirectX 11.0 runtime will not recognize FL 11.1, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, &fLvlWarp[1], _countof(fLvlWarp) - 1, + D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr ); +#endif + } + + if ( SUCCEEDED(hr) ) + { + pDevice->Release(); + } + else + m_warpFL = D3D_FEATURE_LEVEL_10_1; + } + + // Check REF max feature level + { + static const D3D_FEATURE_LEVEL fLvlRef[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1 }; + + ID3D11Device* pDevice = nullptr; + hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_REFERENCE, 0, 0, fLvlRef, _countof(fLvlRef), + D3D11_SDK_VERSION, &pDevice, &m_refFL, nullptr ); + if ( hr == E_INVALIDARG ) + { + // DirectX 11.0 runtime will not recognize FL 11.1, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_REFERENCE, 0, 0, &fLvlRef[1], _countof(fLvlRef) - 1, + D3D11_SDK_VERSION, &pDevice, &m_refFL, nullptr ); } + + if ( SUCCEEDED(hr) ) + { + pDevice->Release(); + } + else + m_refFL = D3D_FEATURE_LEVEL_11_0; } return S_OK; @@ -241,14 +295,14 @@ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3 //-------------------------------------------------------------------------------------- -HRESULT CD3D11Enumeration::EnumerateOutputs( CD3D11EnumAdapterInfo* pAdapterInfo ) +HRESULT CD3D11Enumeration::EnumerateOutputs( _In_ CD3D11EnumAdapterInfo* pAdapterInfo ) { HRESULT hr; IDXGIOutput* pOutput; for( int iOutput = 0; ; ++iOutput ) { - pOutput = NULL; + pOutput = nullptr; hr = pAdapterInfo->m_pAdapter->EnumOutputs( iOutput, &pOutput ); if( DXGI_ERROR_NOT_FOUND == hr ) { @@ -260,38 +314,32 @@ HRESULT CD3D11Enumeration::EnumerateOutputs( CD3D11EnumAdapterInfo* pAdapterInfo } else //Success! { - CD3D11EnumOutputInfo* pOutputInfo = new CD3D11EnumOutputInfo; + auto pOutputInfo = new (std::nothrow) CD3D11EnumOutputInfo; if( !pOutputInfo ) { SAFE_RELEASE( pOutput ); return E_OUTOFMEMORY; } - ZeroMemory( pOutputInfo, sizeof( CD3D11EnumOutputInfo ) ); - pOutput->GetDesc( &pOutputInfo->Desc ); pOutputInfo->Output = iOutput; pOutputInfo->m_pOutput = pOutput; + pOutput->GetDesc( &pOutputInfo->Desc ); EnumerateDisplayModes( pOutputInfo ); - if( pOutputInfo->displayModeList.GetSize() <= 0 ) + if( pOutputInfo->displayModeList.empty() ) { // If this output has no valid display mode, do not save it. delete pOutputInfo; continue; } - hr = pAdapterInfo->outputInfoList.Add( pOutputInfo ); - if( FAILED( hr ) ) - { - delete pOutputInfo; - return hr; - } + pAdapterInfo->outputInfoList.push_back( pOutputInfo ); } } } //-------------------------------------------------------------------------------------- -HRESULT CD3D11Enumeration::EnumerateDisplayModes( CD3D11EnumOutputInfo* pOutputInfo ) +HRESULT CD3D11Enumeration::EnumerateDisplayModes( _In_ CD3D11EnumOutputInfo* pOutputInfo ) { HRESULT hr = S_OK; DXGI_FORMAT allowedAdapterFormatArray[] = @@ -323,7 +371,7 @@ HRESULT CD3D11Enumeration::EnumerateDisplayModes( CD3D11EnumOutputInfo* pOutputI // This is to avoid calling GetDisplayModeList more times than necessary. // GetDisplayModeList is an expensive call. UINT NumModes = 512; - DXGI_MODE_DESC* pDesc = new DXGI_MODE_DESC[ NumModes ]; + auto pDesc = new (std::nothrow) DXGI_MODE_DESC[ NumModes ]; assert( pDesc ); if( !pDesc ) return E_OUTOFMEMORY; @@ -346,14 +394,14 @@ HRESULT CD3D11Enumeration::EnumerateDisplayModes( CD3D11EnumOutputInfo* pOutputI { DEVMODE DevMode; DevMode.dmSize = sizeof( DEVMODE ); - if( EnumDisplaySettings( NULL, ENUM_CURRENT_SETTINGS, &DevMode ) ) + if( EnumDisplaySettings( nullptr, ENUM_CURRENT_SETTINGS, &DevMode ) ) { NumModes = 1; pDesc[0].Width = DevMode.dmPelsWidth; pDesc[0].Height = DevMode.dmPelsHeight; pDesc[0].Format = DXGI_FORMAT_R8G8B8A8_UNORM; - pDesc[0].RefreshRate.Numerator = 60; - pDesc[0].RefreshRate.Denominator = 1; + pDesc[0].RefreshRate.Numerator = 0; + pDesc[0].RefreshRate.Denominator = 0; pDesc[0].ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE; pDesc[0].Scaling = DXGI_MODE_SCALING_CENTERED; hr = S_OK; @@ -367,14 +415,14 @@ HRESULT CD3D11Enumeration::EnumerateDisplayModes( CD3D11EnumOutputInfo* pOutputI hr = pOutputInfo->m_pOutput->GetDisplayModeList( allowedAdapterFormatArray[f], DXGI_ENUM_MODES_SCALING, &NumModes, - NULL ); + nullptr ); if( FAILED( hr ) ) { NumModes = 0; break; } - pDesc = new DXGI_MODE_DESC[ NumModes ]; + pDesc = new (std::nothrow) DXGI_MODE_DESC[ NumModes ]; assert( pDesc ); if( !pDesc ) return E_OUTOFMEMORY; @@ -406,7 +454,8 @@ HRESULT CD3D11Enumeration::EnumerateDisplayModes( CD3D11EnumOutputInfo* pOutputI { for( UINT m = 0; m < NumModes; m++ ) { - pOutputInfo->displayModeList.Add( pDesc[m] ); +#pragma warning ( suppress : 6385 ) + pOutputInfo->displayModeList.push_back( pDesc[m] ); } } @@ -418,10 +467,10 @@ HRESULT CD3D11Enumeration::EnumerateDisplayModes( CD3D11EnumOutputInfo* pOutputI //-------------------------------------------------------------------------------------- -HRESULT CD3D11Enumeration::EnumerateDevices( CD3D11EnumAdapterInfo* pAdapterInfo ) +HRESULT CD3D11Enumeration::EnumerateDevices( _In_ CD3D11EnumAdapterInfo* pAdapterInfo ) { HRESULT hr; - DXUTDeviceSettings deviceSettings = DXUTGetDeviceSettings(); + auto deviceSettings = DXUTGetDeviceSettings(); const D3D_DRIVER_TYPE devTypeArray[] = { D3D_DRIVER_TYPE_HARDWARE, @@ -433,33 +482,35 @@ HRESULT CD3D11Enumeration::EnumerateDevices( CD3D11EnumAdapterInfo* pAdapterInfo // Enumerate each Direct3D device type for( UINT iDeviceType = 0; iDeviceType < devTypeArrayCount; iDeviceType++ ) { - CD3D11EnumDeviceInfo* pDeviceInfo = new CD3D11EnumDeviceInfo; - if( pDeviceInfo == NULL ) + auto pDeviceInfo = new (std::nothrow) CD3D11EnumDeviceInfo; + if( !pDeviceInfo ) return E_OUTOFMEMORY; // Fill struct w/ AdapterOrdinal and D3D_DRIVER_TYPE pDeviceInfo->AdapterOrdinal = pAdapterInfo->AdapterOrdinal; pDeviceInfo->DeviceType = devTypeArray[iDeviceType]; - D3D_FEATURE_LEVEL FeatureLevels[] = + static const D3D_FEATURE_LEVEL FeatureLevels[] = { - D3D_FEATURE_LEVEL_11_0, - D3D_FEATURE_LEVEL_10_1, - D3D_FEATURE_LEVEL_10_0, - D3D_FEATURE_LEVEL_9_3, - D3D_FEATURE_LEVEL_9_2, - D3D_FEATURE_LEVEL_9_1 +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + D3D_FEATURE_LEVEL_12_1, + D3D_FEATURE_LEVEL_12_0, +#endif + D3D_FEATURE_LEVEL_11_1, + D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0, + D3D_FEATURE_LEVEL_9_3, + D3D_FEATURE_LEVEL_9_2, + D3D_FEATURE_LEVEL_9_1 }; UINT NumFeatureLevels = ARRAYSIZE( FeatureLevels ); // Call D3D11CreateDevice to ensure that this is a D3D11 device. - ID3D11Device* pd3dDevice = NULL; - ID3D11DeviceContext* pd3dDeviceContext = NULL; - IDXGIAdapter* pAdapter = NULL; - //if( devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE ) - // pAdapter = pAdapterInfo->m_pAdapter; - hr = DXUT_Dynamic_D3D11CreateDevice( pAdapter, - devTypeArray[iDeviceType], + ID3D11Device* pd3dDevice = nullptr; + ID3D11DeviceContext* pd3dDeviceContext = nullptr; + hr = DXUT_Dynamic_D3D11CreateDevice( (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? pAdapterInfo->m_pAdapter : nullptr, + (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? D3D_DRIVER_TYPE_UNKNOWN : devTypeArray[iDeviceType], ( HMODULE )0, 0, FeatureLevels, @@ -468,163 +519,195 @@ HRESULT CD3D11Enumeration::EnumerateDevices( CD3D11EnumAdapterInfo* pAdapterInfo &pd3dDevice, &pDeviceInfo->MaxLevel, &pd3dDeviceContext ); - if( FAILED( hr ) || pDeviceInfo->MaxLevel < deviceSettings.MinimumFeatureLevel) + + if ( hr == E_INVALIDARG ) + { +#if defined(USE_DIRECT3D11_3) || defined(USE_DIRECT3D11_4) + // DirectX 11.1 runtime will not recognize FL 12.x, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice((devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? pAdapterInfo->m_pAdapter : nullptr, + (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? D3D_DRIVER_TYPE_UNKNOWN : devTypeArray[iDeviceType], + (HMODULE)0, 0, + &FeatureLevels[2], NumFeatureLevels - 2, + D3D11_SDK_VERSION, &pd3dDevice, &pDeviceInfo->MaxLevel, + &pd3dDeviceContext); + + if (hr == E_INVALIDARG) + { + // DirectX 11.0 runtime will not recognize FL 11.1, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice((devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? pAdapterInfo->m_pAdapter : nullptr, + (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? D3D_DRIVER_TYPE_UNKNOWN : devTypeArray[iDeviceType], + (HMODULE)0, 0, + &FeatureLevels[3], NumFeatureLevels - 3, + D3D11_SDK_VERSION, &pd3dDevice, &pDeviceInfo->MaxLevel, + &pd3dDeviceContext); + } +#else + // DirectX 11.0 runtime will not recognize FL 11.1, so try without it + hr = DXUT_Dynamic_D3D11CreateDevice( (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? pAdapterInfo->m_pAdapter : nullptr, + (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? D3D_DRIVER_TYPE_UNKNOWN : devTypeArray[iDeviceType], + ( HMODULE )0, 0, + &FeatureLevels[1], NumFeatureLevels - 1, + D3D11_SDK_VERSION, &pd3dDevice, &pDeviceInfo->MaxLevel, + &pd3dDeviceContext ); +#endif + } + + if ( FAILED(hr) ) { delete pDeviceInfo; continue; } + else if ( pDeviceInfo->MaxLevel < deviceSettings.MinimumFeatureLevel ) + { + delete pDeviceInfo; + SAFE_RELEASE( pd3dDevice ); + SAFE_RELEASE( pd3dDeviceContext ); + continue; + } - if (g_forceFL == 0 || g_forceFL == pDeviceInfo->MaxLevel) { + if (m_forceFL == 0 || m_forceFL == pDeviceInfo->MaxLevel) + { pDeviceInfo->SelectedLevel = pDeviceInfo->MaxLevel; } - else if (g_forceFL > pDeviceInfo->MaxLevel) { + else if (m_forceFL > pDeviceInfo->MaxLevel) + { delete pDeviceInfo; SAFE_RELEASE( pd3dDevice ); SAFE_RELEASE( pd3dDeviceContext ); continue; - } else { + } + else + { // A device was created with a higher feature level that the user-specified feature level. SAFE_RELEASE( pd3dDevice ); SAFE_RELEASE( pd3dDeviceContext ); D3D_FEATURE_LEVEL rtFL; - hr = DXUT_Dynamic_D3D11CreateDevice( pAdapter, - devTypeArray[iDeviceType], - ( HMODULE )0, - 0, - &g_forceFL, - 1, - D3D11_SDK_VERSION, - &pd3dDevice, - &rtFL, - &pd3dDeviceContext ); - - if( !FAILED( hr ) && rtFL == g_forceFL ) { - - pDeviceInfo->SelectedLevel = g_forceFL; - }else { + hr = DXUT_Dynamic_D3D11CreateDevice( (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? pAdapterInfo->m_pAdapter : nullptr, + (devTypeArray[iDeviceType] == D3D_DRIVER_TYPE_HARDWARE) ? D3D_DRIVER_TYPE_UNKNOWN : devTypeArray[iDeviceType], + ( HMODULE )0, + 0, + &m_forceFL, + 1, + D3D11_SDK_VERSION, + &pd3dDevice, + &rtFL, + &pd3dDeviceContext ); + + if( SUCCEEDED( hr ) && rtFL == m_forceFL ) + { + pDeviceInfo->SelectedLevel = m_forceFL; + } + else + { delete pDeviceInfo; - SAFE_RELEASE( pd3dDevice ); - SAFE_RELEASE( pd3dDeviceContext ); + if ( SUCCEEDED(hr) ) + { + SAFE_RELEASE( pd3dDevice ); + SAFE_RELEASE( pd3dDeviceContext ); + } continue; } } - IDXGIDevice1* pDXGIDev = NULL; - hr = pd3dDevice->QueryInterface( __uuidof( IDXGIDevice1 ), ( LPVOID* )&pDXGIDev ); - if( SUCCEEDED( hr ) && pDXGIDev ) - { - SAFE_RELEASE( pAdapterInfo->m_pAdapter ); - pDXGIDev->GetAdapter( &pAdapterInfo->m_pAdapter ); - } - SAFE_RELEASE( pDXGIDev ); - - D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS ho; - pd3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, &ho, sizeof(ho)); + hr = pd3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, &ho, sizeof(ho)); + if ( FAILED(hr) ) + memset( &ho, 0, sizeof(ho) ); + pDeviceInfo->ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x = ho.ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x; SAFE_RELEASE( pd3dDeviceContext ); SAFE_RELEASE( pd3dDevice ); - pAdapterInfo->deviceInfoList.Add( pDeviceInfo ); + pAdapterInfo->deviceInfoList.push_back( pDeviceInfo ); } return S_OK; } -HRESULT CD3D11Enumeration::EnumerateDeviceCombosNoAdapter( CD3D11EnumAdapterInfo* pAdapterInfo ) +HRESULT CD3D11Enumeration::EnumerateDeviceCombosNoAdapter( _In_ CD3D11EnumAdapterInfo* pAdapterInfo ) { // Iterate through each combination of device driver type, output, // adapter format, and backbuffer format to build the adapter's device combo list. // - for( int device = 0; device < pAdapterInfo->deviceInfoList.GetSize(); ++device ) + for( auto dit = pAdapterInfo->deviceInfoList.cbegin(); dit != pAdapterInfo->deviceInfoList.cend(); ++dit ) + { + DXGI_FORMAT BufferFormatArray[] = { - CD3D11EnumDeviceInfo* pDeviceInfo = pAdapterInfo->deviceInfoList.GetAt( device ); + DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, //This is DXUT's preferred mode - DXGI_FORMAT BufferFormatArray[] = - { - DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, //This is DXUT's preferred mode - - DXGI_FORMAT_R8G8B8A8_UNORM, - DXGI_FORMAT_R16G16B16A16_FLOAT, - DXGI_FORMAT_R10G10B10A2_UNORM - }; - const UINT BufferFormatArrayCount = sizeof( BufferFormatArray ) / sizeof - ( BufferFormatArray[0] ); - - // Swap perferred modes for apps running in linear space - if( !DXUTIsInGammaCorrectMode() ) - { - BufferFormatArray[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - BufferFormatArray[1] = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - } + DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_R16G16B16A16_FLOAT, + DXGI_FORMAT_R10G10B10A2_UNORM + }; - for( UINT iBufferFormat = 0; iBufferFormat < BufferFormatArrayCount; iBufferFormat++ ) - { - DXGI_FORMAT BufferFormat = BufferFormatArray[iBufferFormat]; + // Swap perferred modes for apps running in linear space + if( !DXUTIsInGammaCorrectMode() ) + { + BufferFormatArray[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + BufferFormatArray[1] = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + } + for( UINT iBufferFormat = 0; iBufferFormat < _countof( BufferFormatArray ); iBufferFormat++ ) + { + DXGI_FORMAT BufferFormat = BufferFormatArray[iBufferFormat]; + // determine if there are any modes for this particular format - // determine if there are any modes for this particular format + // If an application callback function has been provided, make sure this device + // is acceptable to the app. + if( m_IsD3D11DeviceAcceptableFunc ) + { + if( !m_IsD3D11DeviceAcceptableFunc( pAdapterInfo, + 0, + *dit, + BufferFormat, + TRUE, + m_pIsD3D11DeviceAcceptableFuncUserContext ) ) + continue; + } + // At this point, we have an adapter/device/backbufferformat/iswindowed + // DeviceCombo that is supported by the system. We still + // need to find one or more suitable depth/stencil buffer format, + // multisample type, and present interval. + CD3D11EnumDeviceSettingsCombo* pDeviceCombo = new (std::nothrow) CD3D11EnumDeviceSettingsCombo; + if( !pDeviceCombo ) + return E_OUTOFMEMORY; - // If an application callback function has been provided, make sure this device - // is acceptable to the app. - if( m_IsD3D11DeviceAcceptableFunc != NULL ) - { - if( !m_IsD3D11DeviceAcceptableFunc( pAdapterInfo, - 0, - pDeviceInfo, - BufferFormat, - TRUE, - m_pIsD3D11DeviceAcceptableFuncUserContext ) ) - continue; - } + pDeviceCombo->AdapterOrdinal = (*dit)->AdapterOrdinal; + pDeviceCombo->DeviceType = (*dit)->DeviceType; + pDeviceCombo->BackBufferFormat = BufferFormat; + pDeviceCombo->Windowed = TRUE; + pDeviceCombo->Output = 0; + pDeviceCombo->pAdapterInfo = pAdapterInfo; + pDeviceCombo->pDeviceInfo = (*dit); + pDeviceCombo->pOutputInfo = nullptr; - // At this point, we have an adapter/device/backbufferformat/iswindowed - // DeviceCombo that is supported by the system. We still - // need to find one or more suitable depth/stencil buffer format, - // multisample type, and present interval. - CD3D11EnumDeviceSettingsCombo* pDeviceCombo = new CD3D11EnumDeviceSettingsCombo; - if( pDeviceCombo == NULL ) - return E_OUTOFMEMORY; + BuildMultiSampleQualityList( BufferFormat, pDeviceCombo ); - pDeviceCombo->AdapterOrdinal = pDeviceInfo->AdapterOrdinal; - pDeviceCombo->DeviceType = pDeviceInfo->DeviceType; - pDeviceCombo->BackBufferFormat = BufferFormat; - pDeviceCombo->Windowed = TRUE; - pDeviceCombo->Output = 0; - pDeviceCombo->pAdapterInfo = pAdapterInfo; - pDeviceCombo->pDeviceInfo = pDeviceInfo; - pDeviceCombo->pOutputInfo = NULL; - - BuildMultiSampleQualityList( BufferFormat, pDeviceCombo ); - - if( FAILED( pAdapterInfo->deviceSettingsComboList.Add( pDeviceCombo ) ) ) - delete pDeviceCombo; - } - + pAdapterInfo->deviceSettingsComboList.push_back( pDeviceCombo ); } - + } return S_OK; } //-------------------------------------------------------------------------------------- -HRESULT CD3D11Enumeration::EnumerateDeviceCombos( IDXGIFactory1* pFactory, CD3D11EnumAdapterInfo* pAdapterInfo ) +_Use_decl_annotations_ +HRESULT CD3D11Enumeration::EnumerateDeviceCombos( CD3D11EnumAdapterInfo* pAdapterInfo ) { // Iterate through each combination of device driver type, output, // adapter format, and backbuffer format to build the adapter's device combo list. // - - for( int output = 0; output < pAdapterInfo->outputInfoList.GetSize(); ++output ) + for( size_t output = 0; output < pAdapterInfo->outputInfoList.size(); ++output ) { - CD3D11EnumOutputInfo* pOutputInfo = pAdapterInfo->outputInfoList.GetAt( output ); + auto pOutputInfo = pAdapterInfo->outputInfoList[ output ]; - for( int device = 0; device < pAdapterInfo->deviceInfoList.GetSize(); ++device ) + for( size_t device = 0; device < pAdapterInfo->deviceInfoList.size(); ++device ) { - CD3D11EnumDeviceInfo* pDeviceInfo = pAdapterInfo->deviceInfoList.GetAt( device ); + auto pDeviceInfo = pAdapterInfo->deviceInfoList[ device ]; DXGI_FORMAT backBufferFormatArray[] = { @@ -634,8 +717,6 @@ HRESULT CD3D11Enumeration::EnumerateDeviceCombos( IDXGIFactory1* pFactory, CD3D1 DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R10G10B10A2_UNORM }; - const UINT backBufferFormatArrayCount = sizeof( backBufferFormatArray ) / sizeof - ( backBufferFormatArray[0] ); // Swap perferred modes for apps running in linear space if( !DXUTIsInGammaCorrectMode() ) @@ -644,30 +725,30 @@ HRESULT CD3D11Enumeration::EnumerateDeviceCombos( IDXGIFactory1* pFactory, CD3D1 backBufferFormatArray[1] = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; } - for( UINT iBackBufferFormat = 0; iBackBufferFormat < backBufferFormatArrayCount; iBackBufferFormat++ ) + for( UINT iBackBufferFormat = 0; iBackBufferFormat < _countof( backBufferFormatArray ); iBackBufferFormat++ ) { DXGI_FORMAT backBufferFormat = backBufferFormatArray[iBackBufferFormat]; for( int nWindowed = 0; nWindowed < 2; nWindowed++ ) { - if( !nWindowed && pOutputInfo->displayModeList.GetSize() == 0 ) + if( !nWindowed && pOutputInfo->displayModeList.size() == 0 ) continue; // determine if there are any modes for this particular format - UINT iModes = 0; - for( int i = 0; i < pOutputInfo->displayModeList.GetSize(); i++ ) + size_t iModes = 0; + for( size_t i = 0; i < pOutputInfo->displayModeList.size(); i++ ) { - if( backBufferFormat == pOutputInfo->displayModeList.GetAt( i ).Format ) - iModes ++; + if( backBufferFormat == pOutputInfo->displayModeList[ i ].Format ) + ++iModes; } - if( 0 == iModes ) + if( !iModes ) continue; // If an application callback function has been provided, make sure this device // is acceptable to the app. - if( m_IsD3D11DeviceAcceptableFunc != NULL ) + if( m_IsD3D11DeviceAcceptableFunc ) { - if( !m_IsD3D11DeviceAcceptableFunc( pAdapterInfo, output, + if( !m_IsD3D11DeviceAcceptableFunc( pAdapterInfo, static_cast<UINT>( output ), pDeviceInfo, backBufferFormat, FALSE != nWindowed, m_pIsD3D11DeviceAcceptableFuncUserContext ) ) @@ -678,8 +759,8 @@ HRESULT CD3D11Enumeration::EnumerateDeviceCombos( IDXGIFactory1* pFactory, CD3D1 // DeviceCombo that is supported by the system. We still // need to find one or more suitable depth/stencil buffer format, // multisample type, and present interval. - CD3D11EnumDeviceSettingsCombo* pDeviceCombo = new CD3D11EnumDeviceSettingsCombo; - if( pDeviceCombo == NULL ) + auto pDeviceCombo = new (std::nothrow) CD3D11EnumDeviceSettingsCombo; + if( !pDeviceCombo ) return E_OUTOFMEMORY; pDeviceCombo->AdapterOrdinal = pDeviceInfo->AdapterOrdinal; @@ -693,8 +774,7 @@ HRESULT CD3D11Enumeration::EnumerateDeviceCombos( IDXGIFactory1* pFactory, CD3D1 BuildMultiSampleQualityList( backBufferFormat, pDeviceCombo ); - if( FAILED( pAdapterInfo->deviceSettingsComboList.Add( pDeviceCombo ) ) ) - delete pDeviceCombo; + pAdapterInfo->deviceSettingsComboList.push_back( pDeviceCombo ); } } } @@ -709,47 +789,41 @@ HRESULT CD3D11Enumeration::EnumerateDeviceCombos( IDXGIFactory1* pFactory, CD3D1 //-------------------------------------------------------------------------------------- void CD3D11Enumeration::ClearAdapterInfoList() { - CD3D11EnumAdapterInfo* pAdapterInfo; - for( int i = 0; i < m_AdapterInfoList.GetSize(); i++ ) + for( auto it = m_AdapterInfoList.begin(); it != m_AdapterInfoList.end(); ++it ) { - pAdapterInfo = m_AdapterInfoList.GetAt( i ); + auto pAdapterInfo = *it; delete pAdapterInfo; } - - m_AdapterInfoList.RemoveAll(); + m_AdapterInfoList.clear(); } //-------------------------------------------------------------------------------------- void CD3D11Enumeration::ResetPossibleDepthStencilFormats() { - m_DepthStencilPossibleList.RemoveAll(); - m_DepthStencilPossibleList.Add( DXGI_FORMAT_D32_FLOAT_S8X24_UINT ); - m_DepthStencilPossibleList.Add( DXGI_FORMAT_D32_FLOAT ); - m_DepthStencilPossibleList.Add( DXGI_FORMAT_D24_UNORM_S8_UINT ); - m_DepthStencilPossibleList.Add( DXGI_FORMAT_D16_UNORM ); + m_DepthStencilPossibleList.clear(); + m_DepthStencilPossibleList.push_back( DXGI_FORMAT_D32_FLOAT_S8X24_UINT ); + m_DepthStencilPossibleList.push_back( DXGI_FORMAT_D32_FLOAT ); + m_DepthStencilPossibleList.push_back( DXGI_FORMAT_D24_UNORM_S8_UINT ); + m_DepthStencilPossibleList.push_back( DXGI_FORMAT_D16_UNORM ); } + //-------------------------------------------------------------------------------------- -void CD3D11Enumeration::SetEnumerateAllAdapterFormats( bool bEnumerateAllAdapterFormats ) +void CD3D11Enumeration::SetEnumerateAllAdapterFormats( _In_ bool bEnumerateAllAdapterFormats ) { m_bEnumerateAllAdapterFormats = bEnumerateAllAdapterFormats; } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CD3D11Enumeration::BuildMultiSampleQualityList( DXGI_FORMAT fmt, CD3D11EnumDeviceSettingsCombo* pDeviceCombo ) { - ID3D11Device* pd3dDevice = NULL; - ID3D11DeviceContext* pd3dDeviceContext = NULL; - IDXGIAdapter* pAdapter = NULL; + ID3D11Device* pd3dDevice = nullptr; + ID3D11DeviceContext* pd3dDeviceContext = nullptr; + IDXGIAdapter* pAdapter = nullptr; - //if( pDeviceCombo->DeviceType == D3D_DRIVER_TYPE_HARDWARE ) - // DXUTGetDXGIFactory()->EnumAdapters( pDeviceCombo->pAdapterInfo->AdapterOrdinal, &pAdapter ); - - //DXGI_ADAPTER_DESC dad; - //pAdapter->GetDesc(&dad); - D3D_FEATURE_LEVEL *FeatureLevels = &(pDeviceCombo->pDeviceInfo->SelectedLevel); D3D_FEATURE_LEVEL returnedFeatureLevel; @@ -781,8 +855,8 @@ void CD3D11Enumeration::BuildMultiSampleQualityList( DXGI_FORMAT fmt, CD3D11Enum //the format and sample count combination is not supported for the installed adapter. if (Quality != 0) { - pDeviceCombo->multiSampleCountList.Add( i ); - pDeviceCombo->multiSampleQualityList.Add( Quality ); + pDeviceCombo->multiSampleCountList.push_back( i ); + pDeviceCombo->multiSampleQualityList.push_back( Quality ); } } } @@ -797,84 +871,83 @@ void CD3D11Enumeration::BuildMultiSampleQualityList( DXGI_FORMAT fmt, CD3D11Enum // Call GetAdapterInfoList() after Enumerate() to get a STL vector of // CD3D11EnumAdapterInfo* //-------------------------------------------------------------------------------------- -CGrowableArray <CD3D11EnumAdapterInfo*>* CD3D11Enumeration::GetAdapterInfoList() +std::vector <CD3D11EnumAdapterInfo*>* CD3D11Enumeration::GetAdapterInfoList() { return &m_AdapterInfoList; } //-------------------------------------------------------------------------------------- -CD3D11EnumAdapterInfo* CD3D11Enumeration::GetAdapterInfo( UINT AdapterOrdinal ) +CD3D11EnumAdapterInfo* CD3D11Enumeration::GetAdapterInfo( _In_ UINT AdapterOrdinal ) const { - for( int iAdapter = 0; iAdapter < m_AdapterInfoList.GetSize(); iAdapter++ ) + for( auto it = m_AdapterInfoList.cbegin(); it != m_AdapterInfoList.cend(); ++it ) { - CD3D11EnumAdapterInfo* pAdapterInfo = m_AdapterInfoList.GetAt( iAdapter ); - if( pAdapterInfo->AdapterOrdinal == AdapterOrdinal ) - return pAdapterInfo; + if( (*it)->AdapterOrdinal == AdapterOrdinal ) + return *it; } - return NULL; + return nullptr; } //-------------------------------------------------------------------------------------- -CD3D11EnumDeviceInfo* CD3D11Enumeration::GetDeviceInfo( UINT AdapterOrdinal, D3D_DRIVER_TYPE DeviceType ) +_Use_decl_annotations_ +CD3D11EnumDeviceInfo* CD3D11Enumeration::GetDeviceInfo( UINT AdapterOrdinal, D3D_DRIVER_TYPE DeviceType ) const { - CD3D11EnumAdapterInfo* pAdapterInfo = GetAdapterInfo( AdapterOrdinal ); + auto pAdapterInfo = GetAdapterInfo( AdapterOrdinal ); if( pAdapterInfo ) { - for( int iDeviceInfo = 0; iDeviceInfo < pAdapterInfo->deviceInfoList.GetSize(); iDeviceInfo++ ) + for( auto it = pAdapterInfo->deviceInfoList.cbegin(); it != pAdapterInfo->deviceInfoList.cend(); ++it ) { - CD3D11EnumDeviceInfo* pDeviceInfo = pAdapterInfo->deviceInfoList.GetAt( iDeviceInfo ); - if( pDeviceInfo->DeviceType == DeviceType ) - return pDeviceInfo; + if( (*it)->DeviceType == DeviceType ) + return *it; } } - return NULL; + return nullptr; } //-------------------------------------------------------------------------------------- -CD3D11EnumOutputInfo* CD3D11Enumeration::GetOutputInfo( UINT AdapterOrdinal, UINT Output ) +_Use_decl_annotations_ +CD3D11EnumOutputInfo* CD3D11Enumeration::GetOutputInfo( UINT AdapterOrdinal, UINT Output ) const { - CD3D11EnumAdapterInfo* pAdapterInfo = GetAdapterInfo( AdapterOrdinal ); - if( pAdapterInfo && pAdapterInfo->outputInfoList.GetSize() > int( Output ) ) + auto pAdapterInfo = GetAdapterInfo( AdapterOrdinal ); + if( pAdapterInfo && pAdapterInfo->outputInfoList.size() > size_t( Output ) ) { - return pAdapterInfo->outputInfoList.GetAt( Output ); + return pAdapterInfo->outputInfoList[ Output ]; } - return NULL; + return nullptr; } //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ CD3D11EnumDeviceSettingsCombo* CD3D11Enumeration::GetDeviceSettingsCombo( UINT AdapterOrdinal, - D3D_DRIVER_TYPE DeviceType, UINT Output, - DXGI_FORMAT BackBufferFormat, BOOL Windowed ) + DXGI_FORMAT BackBufferFormat, BOOL Windowed ) const { - CD3D11EnumAdapterInfo* pAdapterInfo = GetAdapterInfo( AdapterOrdinal ); + auto pAdapterInfo = GetAdapterInfo( AdapterOrdinal ); if( pAdapterInfo ) { - for( int iDeviceCombo = 0; iDeviceCombo < pAdapterInfo->deviceSettingsComboList.GetSize(); iDeviceCombo++ ) + for( size_t iDeviceCombo = 0; iDeviceCombo < pAdapterInfo->deviceSettingsComboList.size(); iDeviceCombo++ ) { - CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo = pAdapterInfo->deviceSettingsComboList.GetAt( - iDeviceCombo ); + auto pDeviceSettingsCombo = pAdapterInfo->deviceSettingsComboList[ iDeviceCombo ]; if( pDeviceSettingsCombo->BackBufferFormat == BackBufferFormat && pDeviceSettingsCombo->Windowed == Windowed ) return pDeviceSettingsCombo; } } - return NULL; + return nullptr; } //-------------------------------------------------------------------------------------- -CD3D11EnumOutputInfo::~CD3D11EnumOutputInfo( void ) +CD3D11EnumOutputInfo::~CD3D11EnumOutputInfo() { SAFE_RELEASE( m_pOutput ); - displayModeList.RemoveAll(); + displayModeList.clear(); } @@ -885,28 +958,28 @@ CD3D11EnumDeviceInfo::~CD3D11EnumDeviceInfo() //-------------------------------------------------------------------------------------- -CD3D11EnumAdapterInfo::~CD3D11EnumAdapterInfo( void ) +CD3D11EnumAdapterInfo::~CD3D11EnumAdapterInfo() { - for( int i = 0; i < outputInfoList.GetSize(); i++ ) + for( size_t j = 0; j < outputInfoList.size(); ++j ) { - CD3D11EnumOutputInfo* pOutputInfo = outputInfoList.GetAt( i ); + auto pOutputInfo = outputInfoList[ j ]; delete pOutputInfo; } - outputInfoList.RemoveAll(); + outputInfoList.clear(); - for( int i = 0; i < deviceInfoList.GetSize(); ++i ) + for( size_t j = 0; j < deviceInfoList.size(); ++j ) { - CD3D11EnumDeviceInfo* pDeviceInfo = deviceInfoList.GetAt( i ); + auto pDeviceInfo = deviceInfoList[ j ]; delete pDeviceInfo; } - deviceInfoList.RemoveAll(); + deviceInfoList.clear(); - for( int i = 0; i < deviceSettingsComboList.GetSize(); ++i ) + for( size_t j = 0; j < deviceSettingsComboList.size(); ++j ) { - CD3D11EnumDeviceSettingsCombo* pDeviceCombo = deviceSettingsComboList.GetAt( i ); + auto pDeviceCombo = deviceSettingsComboList[ j ]; delete pDeviceCombo; } - deviceSettingsComboList.RemoveAll(); + deviceSettingsComboList.clear(); SAFE_RELEASE( m_pAdapter ); } @@ -939,6 +1012,7 @@ UINT WINAPI DXUTGetDXGIColorChannelBits( DXGI_FORMAT fmt ) case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R10G10B10A2_UINT: + case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: return 10; case DXGI_FORMAT_R8G8B8A8_TYPELESS: @@ -947,12 +1021,21 @@ UINT WINAPI DXUTGetDXGIColorChannelBits( DXGI_FORMAT fmt ) case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_R8G8B8A8_SINT: + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_B8G8R8A8_TYPELESS: + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: + case DXGI_FORMAT_B8G8R8X8_TYPELESS: + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return 8; case DXGI_FORMAT_B5G6R5_UNORM: case DXGI_FORMAT_B5G5R5A1_UNORM: return 5; + case DXGI_FORMAT_B4G4R4A4_UNORM: + return 4; + default: return 0; } @@ -962,9 +1045,9 @@ UINT WINAPI DXUTGetDXGIColorChannelBits( DXGI_FORMAT fmt ) // Returns a ranking number that describes how closely this device // combo matches the optimal combo based on the match options and the optimal device settings //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo, DXUTD3D11DeviceSettings* pOptimalDeviceSettings, - DXGI_MODE_DESC* pAdapterDisplayMode, int &bestModeIndex, int &bestMSAAIndex ) @@ -981,7 +1064,6 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo const float fResolutionWeight = 1.0f; const float fBackBufferFormatWeight = 1.0f; const float fMultiSampleWeight = 1.0f; - const float fRefreshRateWeight = 1.0f; //--------------------- // Adapter ordinal @@ -1005,7 +1087,7 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo } // Slightly prefer HAL - if( pDeviceSettingsCombo->DeviceType == D3DDEVTYPE_HAL ) + if( pDeviceSettingsCombo->DeviceType == D3D_DRIVER_TYPE_HARDWARE ) fCurRanking += 0.1f; //--------------------- @@ -1015,31 +1097,76 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo fCurRanking += fWindowWeight; //--------------------- - // Resolution + // Resolution/Refresh Rate //--------------------- - bool bResolutionFound = false; - unsigned int best = 0xffffffff; bestModeIndex=0; - for( int idm = 0; pDeviceSettingsCombo->pOutputInfo != NULL && idm < pDeviceSettingsCombo->pOutputInfo->displayModeList.GetSize() && !bResolutionFound; idm++ ) + + if( pDeviceSettingsCombo->pOutputInfo ) { - DXGI_MODE_DESC displayMode = pDeviceSettingsCombo->pOutputInfo->displayModeList.GetAt( idm ); - if( displayMode.Width == pOptimalDeviceSettings->sd.BufferDesc.Width && - displayMode.Height == pOptimalDeviceSettings->sd.BufferDesc.Height ) - bResolutionFound = true; + bool bResolutionFound = false; + float best = FLT_MAX; + + if ( !pDeviceSettingsCombo->Windowed + && !pOptimalDeviceSettings->sd.Windowed + && ( pOptimalDeviceSettings->sd.BufferDesc.RefreshRate.Numerator > 0 || pOptimalDeviceSettings->sd.BufferDesc.RefreshRate.Denominator > 0 ) ) + { + // Match both Resolution & Refresh Rate + for( size_t idm = 0; idm < pDeviceSettingsCombo->pOutputInfo->displayModeList.size() && !bResolutionFound; idm++ ) + { + auto displayMode = pDeviceSettingsCombo->pOutputInfo->displayModeList[ idm ]; + + float refreshDiff = fabs( ( float( displayMode.RefreshRate.Numerator ) / float( displayMode.RefreshRate.Denominator ) ) - + ( float( pOptimalDeviceSettings->sd.BufferDesc.RefreshRate.Numerator ) / float( pOptimalDeviceSettings->sd.BufferDesc.RefreshRate.Denominator ) ) ); + + if( displayMode.Width == pOptimalDeviceSettings->sd.BufferDesc.Width + && displayMode.Height == pOptimalDeviceSettings->sd.BufferDesc.Height + && ( refreshDiff < 0.1f ) ) + { + bResolutionFound = true; + bestModeIndex = static_cast<int>( idm ); + break; + } + + float current = refreshDiff + + fabs( float( displayMode.Width ) - float ( pOptimalDeviceSettings->sd.BufferDesc.Width ) ) + + fabs( float( displayMode.Height ) - float ( pOptimalDeviceSettings->sd.BufferDesc.Height ) ); - unsigned int current = - (UINT) abs ((int)displayMode.Width - (int)pOptimalDeviceSettings->sd.BufferDesc.Width) + - (UINT) abs ((int)displayMode.Height - (int)pOptimalDeviceSettings->sd.BufferDesc.Height ); + if( current < best ) + { + best = current; + bestModeIndex = static_cast<int>( idm ); + } + } + } + else + { + // Match just Resolution + for( size_t idm = 0; idm < pDeviceSettingsCombo->pOutputInfo->displayModeList.size() && !bResolutionFound; idm++ ) + { + auto displayMode = pDeviceSettingsCombo->pOutputInfo->displayModeList[ idm ]; - if (current < best) { - best = current; - bestModeIndex= idm; + if( displayMode.Width == pOptimalDeviceSettings->sd.BufferDesc.Width + && displayMode.Height == pOptimalDeviceSettings->sd.BufferDesc.Height ) + { + bResolutionFound = true; + bestModeIndex = static_cast<int>( idm ); + break; + } + float current = fabs( float( displayMode.Width ) - float ( pOptimalDeviceSettings->sd.BufferDesc.Width ) ) + + fabs( float( displayMode.Height ) - float ( pOptimalDeviceSettings->sd.BufferDesc.Height ) ); + + if( current < best ) + { + best = current; + bestModeIndex = static_cast<int>( idm ); + } + } } + if( bResolutionFound ) + fCurRanking += fResolutionWeight; } - if( bResolutionFound ) - fCurRanking += fResolutionWeight; //--------------------- // Back buffer format @@ -1053,7 +1180,7 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo int nBitDepthDelta = abs( ( long )DXUTGetDXGIColorChannelBits( pDeviceSettingsCombo->BackBufferFormat ) - ( long )DXUTGetDXGIColorChannelBits( pOptimalDeviceSettings->sd.BufferDesc.Format ) ); - float fScale = __max( 0.9f - ( float )nBitDepthDelta * 0.2f, 0.0f ); + float fScale = std::max<float>( 0.9f - ( float )nBitDepthDelta * 0.2f, 0.0f ); fCurRanking += fScale * fBackBufferFormatWeight; } @@ -1067,13 +1194,13 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo //--------------------- bool bMultiSampleFound = false; bestMSAAIndex = 0; - for( int i = 0; i < pDeviceSettingsCombo->multiSampleCountList.GetSize(); i++ ) + for( size_t i = 0; i < pDeviceSettingsCombo->multiSampleCountList.size(); i++ ) { - UINT Count = pDeviceSettingsCombo->multiSampleCountList.GetAt( i ); + UINT Count = pDeviceSettingsCombo->multiSampleCountList[ i ]; if( Count == pOptimalDeviceSettings->sd.SampleDesc.Count ) { - bestMSAAIndex = i; + bestMSAAIndex = static_cast<int>( i ); bMultiSampleFound = true; break; } @@ -1097,21 +1224,6 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo // No caps for the present flags //--------------------- - // Refresh rate - //--------------------- - bool bRefreshFound = false; - for( int idm = 0; pDeviceSettingsCombo->pOutputInfo != NULL && idm < pDeviceSettingsCombo->pOutputInfo->displayModeList.GetSize(); idm++ ) - { - DXGI_MODE_DESC displayMode = pDeviceSettingsCombo->pOutputInfo->displayModeList.GetAt( idm ); - if( fabs( float( displayMode.RefreshRate.Numerator ) / displayMode.RefreshRate.Denominator - - float( pOptimalDeviceSettings->sd.BufferDesc.RefreshRate.Numerator ) / - pOptimalDeviceSettings->sd.BufferDesc.RefreshRate.Denominator ) < 0.1f ) - bRefreshFound = true; - } - if( bRefreshFound ) - fCurRanking += fRefreshRateWeight; - - //--------------------- // Present interval //--------------------- // No caps for the present flags @@ -1123,32 +1235,38 @@ float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCo //-------------------------------------------------------------------------------------- // Returns the DXGI_MODE_DESC struct for a given adapter and output //-------------------------------------------------------------------------------------- +#pragma warning ( suppress : 6101 ) +_Use_decl_annotations_ HRESULT WINAPI DXUTGetD3D11AdapterDisplayMode( UINT AdapterOrdinal, UINT nOutput, DXGI_MODE_DESC* pModeDesc ) { if( !pModeDesc ) return E_INVALIDARG; - CD3D11Enumeration* pD3DEnum = DXUTGetD3D11Enumeration(); - CD3D11EnumOutputInfo* pOutputInfo = pD3DEnum->GetOutputInfo( AdapterOrdinal, nOutput ); + auto pD3DEnum = DXUTGetD3D11Enumeration(); + if ( !pD3DEnum ) + return E_POINTER; + + auto pOutputInfo = pD3DEnum->GetOutputInfo( AdapterOrdinal, nOutput ); if( pOutputInfo ) { - pModeDesc->Width = 640; - pModeDesc->Height = 480; - pModeDesc->RefreshRate.Numerator = 60; - pModeDesc->RefreshRate.Denominator = 1; + pModeDesc->Width = 800; + pModeDesc->Height = 600; + pModeDesc->RefreshRate.Numerator = 0; + pModeDesc->RefreshRate.Denominator = 0; pModeDesc->Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; pModeDesc->Scaling = DXGI_MODE_SCALING_UNSPECIFIED; pModeDesc->ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; DXGI_OUTPUT_DESC Desc; - pOutputInfo->m_pOutput->GetDesc( &Desc ); + if ( FAILED(pOutputInfo->m_pOutput->GetDesc(&Desc))) + memset( &Desc, 0, sizeof(Desc) ); pModeDesc->Width = Desc.DesktopCoordinates.right - Desc.DesktopCoordinates.left; pModeDesc->Height = Desc.DesktopCoordinates.bottom - Desc.DesktopCoordinates.top; - } - // This should not be required with DXGI 1.1 support for BGRA... - if( pModeDesc->Format == DXGI_FORMAT_B8G8R8A8_UNORM ) - pModeDesc->Format = DXGI_FORMAT_R8G8B8A8_UNORM; + // This should not be required with DXGI 1.1 support for BGRA... + if( pModeDesc->Format == DXGI_FORMAT_B8G8R8A8_UNORM ) + pModeDesc->Format = DXGI_FORMAT_R8G8B8A8_UNORM; + } return S_OK; } diff --git a/samples/DX_APIUsage/DXUT/Core/DXUTDevice11.h b/samples/DX_APIUsage/DXUT/Core/DXUTDevice11.h index a76cc69..386b095 100644 --- a/samples/DX_APIUsage/DXUT/Core/DXUTDevice11.h +++ b/samples/DX_APIUsage/DXUT/Core/DXUTDevice11.h @@ -4,17 +4,18 @@ // Enumerates D3D adapters, devices, modes, etc. // // Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef DXUT_DEVICE11_H -#define DXUT_DEVICE11_H void DXUTApplyDefaultDeviceSettings(DXUTDeviceSettings *modifySettings); //-------------------------------------------------------------------------------------- // Functions to get bit depth from formats //-------------------------------------------------------------------------------------- -HRESULT WINAPI DXUTGetD3D11AdapterDisplayMode( UINT AdapterOrdinal, UINT Output, DXGI_MODE_DESC* pModeDesc ); +HRESULT WINAPI DXUTGetD3D11AdapterDisplayMode( _In_ UINT AdapterOrdinal, _In_ UINT Output, _Out_ DXGI_MODE_DESC* pModeDesc ); @@ -39,8 +40,7 @@ struct CD3D11EnumDeviceSettingsCombo; //-------------------------------------------------------------------------------------- -// Enumerates available Direct3D10 adapters, devices, modes, etc. -// Use DXUTGetD3D9Enumeration() to access global instance +// Enumerates available Direct3D11 adapters, devices, modes, etc. //-------------------------------------------------------------------------------------- class CD3D11Enumeration { @@ -49,28 +49,27 @@ public: // // Use these calls and the IsDeviceAcceptable to control the contents of // the enumeration object, which affects the device selection and the device settings dialog. - void SetResolutionMinMax( UINT nMinWidth, UINT nMinHeight, UINT nMaxWidth, UINT nMaxHeight ); - void SetRefreshMinMax( UINT nMin, UINT nMax ); - void SetForceFeatureLevel( D3D_FEATURE_LEVEL forceFL) { - g_forceFL = forceFL; - }; - void SetMultisampleQualityMax( UINT nMax ); - CGrowableArray<D3DFORMAT>* GetPossibleDepthStencilFormatList(); + void SetResolutionMinMax( _In_ UINT nMinWidth, _In_ UINT nMinHeight, _In_ UINT nMaxWidth, _In_ UINT nMaxHeight ); + void SetRefreshMinMax( _In_ UINT nMin, _In_ UINT nMax ); + void SetForceFeatureLevel( _In_ D3D_FEATURE_LEVEL forceFL) { m_forceFL = forceFL; } + void SetMultisampleQualityMax( _In_ UINT nMax ); void ResetPossibleDepthStencilFormats(); - void SetEnumerateAllAdapterFormats( bool bEnumerateAllAdapterFormats ); + void SetEnumerateAllAdapterFormats( _In_ bool bEnumerateAllAdapterFormats ); // Call Enumerate() to enumerate available D3D11 adapters, devices, modes, etc. bool HasEnumerated() { return m_bHasEnumerated; } - HRESULT Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3D11DeviceAcceptableFunc, - void* pIsD3D11DeviceAcceptableFuncUserContext ); + HRESULT Enumerate( _In_ LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3D11DeviceAcceptableFunc, + _In_opt_ void* pIsD3D11DeviceAcceptableFuncUserContext ); // These should be called after Enumerate() is called - CGrowableArray<CD3D11EnumAdapterInfo*>* GetAdapterInfoList(); - CD3D11EnumAdapterInfo* GetAdapterInfo( UINT AdapterOrdinal ); - CD3D11EnumDeviceInfo* GetDeviceInfo( UINT AdapterOrdinal, D3D_DRIVER_TYPE DeviceType ); - CD3D11EnumOutputInfo* GetOutputInfo( UINT AdapterOrdinal, UINT Output ); - CD3D11EnumDeviceSettingsCombo* GetDeviceSettingsCombo( DXUTD3D11DeviceSettings* pDeviceSettings ) { return GetDeviceSettingsCombo( pDeviceSettings->AdapterOrdinal, pDeviceSettings->DriverType, pDeviceSettings->Output, pDeviceSettings->sd.BufferDesc.Format, pDeviceSettings->sd.Windowed ); } - CD3D11EnumDeviceSettingsCombo* GetDeviceSettingsCombo( UINT AdapterOrdinal, D3D_DRIVER_TYPE DeviceType, UINT Output, DXGI_FORMAT BackBufferFormat, BOOL Windowed ); + std::vector<CD3D11EnumAdapterInfo*>* GetAdapterInfoList(); + CD3D11EnumAdapterInfo* GetAdapterInfo( _In_ UINT AdapterOrdinal ) const; + CD3D11EnumDeviceInfo* GetDeviceInfo( _In_ UINT AdapterOrdinal, _In_ D3D_DRIVER_TYPE DeviceType ) const; + CD3D11EnumOutputInfo* GetOutputInfo( _In_ UINT AdapterOrdinal, _In_ UINT Output ) const; + CD3D11EnumDeviceSettingsCombo* GetDeviceSettingsCombo( _In_ DXUTD3D11DeviceSettings* pDeviceSettings ) const { return GetDeviceSettingsCombo( pDeviceSettings->AdapterOrdinal, pDeviceSettings->sd.BufferDesc.Format, pDeviceSettings->sd.Windowed ); } + CD3D11EnumDeviceSettingsCombo* GetDeviceSettingsCombo( _In_ UINT AdapterOrdinal, _In_ DXGI_FORMAT BackBufferFormat, _In_ BOOL Windowed ) const; + D3D_FEATURE_LEVEL GetWARPFeaturevel() const { return m_warpFL; } + D3D_FEATURE_LEVEL GetREFFeaturevel() const { return m_refFL; } ~CD3D11Enumeration(); @@ -84,32 +83,26 @@ private: LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE m_IsD3D11DeviceAcceptableFunc; void* m_pIsD3D11DeviceAcceptableFuncUserContext; - CGrowableArray<DXGI_FORMAT> m_DepthStencilPossibleList; + std::vector<DXGI_FORMAT> m_DepthStencilPossibleList; - UINT m_nMinWidth; - UINT m_nMaxWidth; - UINT m_nMinHeight; - UINT m_nMaxHeight; - UINT m_nRefreshMin; - UINT m_nRefreshMax; - UINT m_nMultisampleQualityMax; bool m_bEnumerateAllAdapterFormats; - D3D_FEATURE_LEVEL g_forceFL; + D3D_FEATURE_LEVEL m_forceFL; + D3D_FEATURE_LEVEL m_warpFL; + D3D_FEATURE_LEVEL m_refFL; - // Array of CD3D9EnumAdapterInfo* with unique AdapterOrdinals - CGrowableArray<CD3D11EnumAdapterInfo*> m_AdapterInfoList; + std::vector<CD3D11EnumAdapterInfo*> m_AdapterInfoList; - HRESULT EnumerateOutputs( CD3D11EnumAdapterInfo *pAdapterInfo ); - HRESULT EnumerateDevices( CD3D11EnumAdapterInfo *pAdapterInfo ); - HRESULT EnumerateDeviceCombos( IDXGIFactory1 *pFactory, CD3D11EnumAdapterInfo* pAdapterInfo ); - HRESULT EnumerateDeviceCombosNoAdapter( CD3D11EnumAdapterInfo* pAdapterInfo ); + HRESULT EnumerateOutputs( _In_ CD3D11EnumAdapterInfo *pAdapterInfo ); + HRESULT EnumerateDevices( _In_ CD3D11EnumAdapterInfo *pAdapterInfo ); + HRESULT EnumerateDeviceCombos( _In_ CD3D11EnumAdapterInfo* pAdapterInfo ); + HRESULT EnumerateDeviceCombosNoAdapter( _In_ CD3D11EnumAdapterInfo* pAdapterInfo ); - HRESULT EnumerateDisplayModes( CD3D11EnumOutputInfo *pOutputInfo ); - void BuildMultiSampleQualityList( DXGI_FORMAT fmt, CD3D11EnumDeviceSettingsCombo* pDeviceCombo ); + HRESULT EnumerateDisplayModes( _In_ CD3D11EnumOutputInfo *pOutputInfo ); + void BuildMultiSampleQualityList( _In_ DXGI_FORMAT fmt, _In_ CD3D11EnumDeviceSettingsCombo* pDeviceCombo ); void ClearAdapterInfoList(); }; -CD3D11Enumeration* WINAPI DXUTGetD3D11Enumeration(bool bForceEnumerate = false, bool EnumerateAllAdapterFormats = false, D3D_FEATURE_LEVEL forceFL = ((D3D_FEATURE_LEVEL )0) ); +CD3D11Enumeration* WINAPI DXUTGetD3D11Enumeration(_In_ bool bForceEnumerate = false, _In_ bool EnumerateAllAdapterFormats = true, _In_ D3D_FEATURE_LEVEL forceFL = ((D3D_FEATURE_LEVEL )0) ); #define DXGI_MAX_DEVICE_IDENTIFIER_STRING 128 @@ -123,6 +116,14 @@ class CD3D11EnumAdapterInfo const CD3D11EnumAdapterInfo &operator = ( const CD3D11EnumAdapterInfo &rhs ); public: + CD3D11EnumAdapterInfo() : + AdapterOrdinal( 0 ), + m_pAdapter( nullptr ), + bAdapterUnavailable(false) + { + *szUniqueDescription = 0; + memset( &AdapterDesc, 0, sizeof(AdapterDesc) ); + } ~CD3D11EnumAdapterInfo(); UINT AdapterOrdinal; @@ -131,11 +132,11 @@ public: IDXGIAdapter *m_pAdapter; bool bAdapterUnavailable; - CGrowableArray<CD3D11EnumOutputInfo*> outputInfoList; // Array of CD3D11EnumOutputInfo* - CGrowableArray<CD3D11EnumDeviceInfo*> deviceInfoList; // Array of CD3D11EnumDeviceInfo* + std::vector<CD3D11EnumOutputInfo*> outputInfoList; // Array of CD3D11EnumOutputInfo* + std::vector<CD3D11EnumDeviceInfo*> deviceInfoList; // Array of CD3D11EnumDeviceInfo* // List of CD3D11EnumDeviceSettingsCombo* with a unique set // of BackBufferFormat, and Windowed - CGrowableArray<CD3D11EnumDeviceSettingsCombo*> deviceSettingsComboList; + std::vector<CD3D11EnumDeviceSettingsCombo*> deviceSettingsComboList; }; @@ -144,6 +145,10 @@ class CD3D11EnumOutputInfo const CD3D11EnumOutputInfo &operator = ( const CD3D11EnumOutputInfo &rhs ); public: + CD3D11EnumOutputInfo() : + AdapterOrdinal( 0 ), + Output( 0 ), + m_pOutput( nullptr ) {} ~CD3D11EnumOutputInfo(); UINT AdapterOrdinal; @@ -151,13 +156,12 @@ public: IDXGIOutput* m_pOutput; DXGI_OUTPUT_DESC Desc; - CGrowableArray <DXGI_MODE_DESC> displayModeList; // Array of supported D3DDISPLAYMODEs + std::vector <DXGI_MODE_DESC> displayModeList; // Array of supported D3DDISPLAYMODEs }; //-------------------------------------------------------------------------------------- -// A class describing a Direct3D10 device that contains a -// unique supported driver type +// A class describing a Direct3D11 device that contains a unique supported driver type //-------------------------------------------------------------------------------------- class CD3D11EnumDeviceInfo { @@ -187,24 +191,16 @@ struct CD3D11EnumDeviceSettingsCombo BOOL Windowed; UINT Output; - CGrowableArray <UINT> multiSampleCountList; // List of valid sampling counts (multisampling) - CGrowableArray <UINT> multiSampleQualityList; // List of number of quality levels for each multisample count + std::vector <UINT> multiSampleCountList; // List of valid sampling counts (multisampling) + std::vector <UINT> multiSampleQualityList; // List of number of quality levels for each multisample count CD3D11EnumAdapterInfo* pAdapterInfo; CD3D11EnumDeviceInfo* pDeviceInfo; CD3D11EnumOutputInfo* pOutputInfo; }; -float DXUTRankD3D11DeviceCombo( CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo, - DXUTD3D11DeviceSettings* pOptimalDeviceSettings, - DXGI_MODE_DESC* pAdapterDisplayMode, - int &bestModeIndex, - int &bestMSAAIndex +float DXUTRankD3D11DeviceCombo( _In_ CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo, + _In_ DXUTD3D11DeviceSettings* pOptimalDeviceSettings, + _Out_ int &bestModeIndex, + _Out_ int &bestMSAAIndex ); - - - - -#endif - - diff --git a/samples/DX_APIUsage/DXUT/Core/DXUTmisc.cpp b/samples/DX_APIUsage/DXUT/Core/DXUTmisc.cpp index bc05d9d..9db95ea 100644 --- a/samples/DX_APIUsage/DXUT/Core/DXUTmisc.cpp +++ b/samples/DX_APIUsage/DXUT/Core/DXUTmisc.cpp @@ -3,13 +3,20 @@ // // Shortcut macros and functions for using DX objects // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #include "dxut.h" #include <xinput.h> + +#include "ScreenGrab.h" + +#include <sstream> + + #define DXUT_GAMEPAD_TRIGGER_THRESHOLD 30 -#undef min // use __min instead -#undef max // use __max instead CDXUTTimer* WINAPI DXUTGetGlobalTimer() { @@ -30,7 +37,7 @@ CDXUTTimer::CDXUTTimer() m_llBaseTime = 0; // Use QueryPerformanceFrequency to get the frequency of the counter - LARGE_INTEGER qwTicksPerSec = { 0 }; + LARGE_INTEGER qwTicksPerSec = {}; QueryPerformanceFrequency( &qwTicksPerSec ); m_llQPFTicksPerSec = qwTicksPerSec.QuadPart; } @@ -52,7 +59,7 @@ void CDXUTTimer::Reset() void CDXUTTimer::Start() { // Get the current time - LARGE_INTEGER qwTime = { 0 }; + LARGE_INTEGER qwTime = {}; QueryPerformanceCounter( &qwTime ); if( m_bTimerStopped ) @@ -68,7 +75,7 @@ void CDXUTTimer::Stop() { if( !m_bTimerStopped ) { - LARGE_INTEGER qwTime = { 0 }; + LARGE_INTEGER qwTime = {}; QueryPerformanceCounter( &qwTime ); m_llStopTime = qwTime.QuadPart; m_llLastElapsedTime = qwTime.QuadPart; @@ -85,9 +92,9 @@ void CDXUTTimer::Advance() //-------------------------------------------------------------------------------------- -double CDXUTTimer::GetAbsoluteTime() +double CDXUTTimer::GetAbsoluteTime() const { - LARGE_INTEGER qwTime = { 0 }; + LARGE_INTEGER qwTime = {}; QueryPerformanceCounter( &qwTime ); double fTime = qwTime.QuadPart / ( double )m_llQPFTicksPerSec; @@ -97,7 +104,7 @@ double CDXUTTimer::GetAbsoluteTime() //-------------------------------------------------------------------------------------- -double CDXUTTimer::GetTime() +double CDXUTTimer::GetTime() const { LARGE_INTEGER qwTime = GetAdjustedCurrentTime(); @@ -108,6 +115,7 @@ double CDXUTTimer::GetTime() //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void CDXUTTimer::GetTimeValues( double* pfTime, double* pfAbsoluteTime, float* pfElapsedTime ) { assert( pfTime && pfAbsoluteTime && pfElapsedTime ); @@ -118,11 +126,11 @@ void CDXUTTimer::GetTimeValues( double* pfTime, double* pfAbsoluteTime, float* p m_llLastElapsedTime = qwTime.QuadPart; // Clamp the timer to non-negative values to ensure the timer is accurate. - // fElapsedTime can be outside this range if processor goes into a - // power save mode or we somehow get shuffled to another processor. - // However, the main thread should call SetThreadAffinityMask to ensure that - // we don't get shuffled to another processor. Other worker threads should NOT call - // SetThreadAffinityMask, but use a shared copy of the timer data gathered from + // fElapsedTime can be outside this range if processor goes into a + // power save mode or we somehow get shuffled to another processor. + // However, the main thread should call SetThreadAffinityMask to ensure that + // we don't get shuffled to another processor. Other worker threads should NOT call + // SetThreadAffinityMask, but use a shared copy of the timer data gathered from // the main thread. if( fElapsedTime < 0.0f ) fElapsedTime = 0.0f; @@ -152,7 +160,7 @@ float CDXUTTimer::GetElapsedTime() //-------------------------------------------------------------------------------------- // If stopped, returns time when stopped otherwise returns current time //-------------------------------------------------------------------------------------- -LARGE_INTEGER CDXUTTimer::GetAdjustedCurrentTime() +LARGE_INTEGER CDXUTTimer::GetAdjustedCurrentTime() const { LARGE_INTEGER qwTime; if( m_llStopTime != 0 ) @@ -163,13 +171,7 @@ LARGE_INTEGER CDXUTTimer::GetAdjustedCurrentTime() } //-------------------------------------------------------------------------------------- -bool CDXUTTimer::IsStopped() -{ - return m_bTimerStopped; -} - -//-------------------------------------------------------------------------------------- -// Limit the current thread to one processor (the current one). This ensures that timing code +// Limit the current thread to one processor (the current one). This ensures that timing code // runs on only one processor, and will not suffer any ill effects from power management. // See "Game Timing and Multicore Processors" for more details //-------------------------------------------------------------------------------------- @@ -202,330 +204,137 @@ void CDXUTTimer::LimitThreadAffinityToCurrentProc() //-------------------------------------------------------------------------------------- -// Returns the string for the given D3DFORMAT. -//-------------------------------------------------------------------------------------- -LPCWSTR WINAPI DXUTD3DFormatToString( D3DFORMAT format, bool bWithPrefix ) -{ - WCHAR* pstr = NULL; - switch( format ) - { - case D3DFMT_UNKNOWN: - pstr = L"D3DFMT_UNKNOWN"; break; - case D3DFMT_R8G8B8: - pstr = L"D3DFMT_R8G8B8"; break; - case D3DFMT_A8R8G8B8: - pstr = L"D3DFMT_A8R8G8B8"; break; - case D3DFMT_X8R8G8B8: - pstr = L"D3DFMT_X8R8G8B8"; break; - case D3DFMT_R5G6B5: - pstr = L"D3DFMT_R5G6B5"; break; - case D3DFMT_X1R5G5B5: - pstr = L"D3DFMT_X1R5G5B5"; break; - case D3DFMT_A1R5G5B5: - pstr = L"D3DFMT_A1R5G5B5"; break; - case D3DFMT_A4R4G4B4: - pstr = L"D3DFMT_A4R4G4B4"; break; - case D3DFMT_R3G3B2: - pstr = L"D3DFMT_R3G3B2"; break; - case D3DFMT_A8: - pstr = L"D3DFMT_A8"; break; - case D3DFMT_A8R3G3B2: - pstr = L"D3DFMT_A8R3G3B2"; break; - case D3DFMT_X4R4G4B4: - pstr = L"D3DFMT_X4R4G4B4"; break; - case D3DFMT_A2B10G10R10: - pstr = L"D3DFMT_A2B10G10R10"; break; - case D3DFMT_A8B8G8R8: - pstr = L"D3DFMT_A8B8G8R8"; break; - case D3DFMT_X8B8G8R8: - pstr = L"D3DFMT_X8B8G8R8"; break; - case D3DFMT_G16R16: - pstr = L"D3DFMT_G16R16"; break; - case D3DFMT_A2R10G10B10: - pstr = L"D3DFMT_A2R10G10B10"; break; - case D3DFMT_A16B16G16R16: - pstr = L"D3DFMT_A16B16G16R16"; break; - case D3DFMT_A8P8: - pstr = L"D3DFMT_A8P8"; break; - case D3DFMT_P8: - pstr = L"D3DFMT_P8"; break; - case D3DFMT_L8: - pstr = L"D3DFMT_L8"; break; - case D3DFMT_A8L8: - pstr = L"D3DFMT_A8L8"; break; - case D3DFMT_A4L4: - pstr = L"D3DFMT_A4L4"; break; - case D3DFMT_V8U8: - pstr = L"D3DFMT_V8U8"; break; - case D3DFMT_L6V5U5: - pstr = L"D3DFMT_L6V5U5"; break; - case D3DFMT_X8L8V8U8: - pstr = L"D3DFMT_X8L8V8U8"; break; - case D3DFMT_Q8W8V8U8: - pstr = L"D3DFMT_Q8W8V8U8"; break; - case D3DFMT_V16U16: - pstr = L"D3DFMT_V16U16"; break; - case D3DFMT_A2W10V10U10: - pstr = L"D3DFMT_A2W10V10U10"; break; - case D3DFMT_UYVY: - pstr = L"D3DFMT_UYVY"; break; - case D3DFMT_YUY2: - pstr = L"D3DFMT_YUY2"; break; - case D3DFMT_DXT1: - pstr = L"D3DFMT_DXT1"; break; - case D3DFMT_DXT2: - pstr = L"D3DFMT_DXT2"; break; - case D3DFMT_DXT3: - pstr = L"D3DFMT_DXT3"; break; - case D3DFMT_DXT4: - pstr = L"D3DFMT_DXT4"; break; - case D3DFMT_DXT5: - pstr = L"D3DFMT_DXT5"; break; - case D3DFMT_D16_LOCKABLE: - pstr = L"D3DFMT_D16_LOCKABLE"; break; - case D3DFMT_D32: - pstr = L"D3DFMT_D32"; break; - case D3DFMT_D15S1: - pstr = L"D3DFMT_D15S1"; break; - case D3DFMT_D24S8: - pstr = L"D3DFMT_D24S8"; break; - case D3DFMT_D24X8: - pstr = L"D3DFMT_D24X8"; break; - case D3DFMT_D24X4S4: - pstr = L"D3DFMT_D24X4S4"; break; - case D3DFMT_D16: - pstr = L"D3DFMT_D16"; break; - case D3DFMT_L16: - pstr = L"D3DFMT_L16"; break; - case D3DFMT_VERTEXDATA: - pstr = L"D3DFMT_VERTEXDATA"; break; - case D3DFMT_INDEX16: - pstr = L"D3DFMT_INDEX16"; break; - case D3DFMT_INDEX32: - pstr = L"D3DFMT_INDEX32"; break; - case D3DFMT_Q16W16V16U16: - pstr = L"D3DFMT_Q16W16V16U16"; break; - case D3DFMT_MULTI2_ARGB8: - pstr = L"D3DFMT_MULTI2_ARGB8"; break; - case D3DFMT_R16F: - pstr = L"D3DFMT_R16F"; break; - case D3DFMT_G16R16F: - pstr = L"D3DFMT_G16R16F"; break; - case D3DFMT_A16B16G16R16F: - pstr = L"D3DFMT_A16B16G16R16F"; break; - case D3DFMT_R32F: - pstr = L"D3DFMT_R32F"; break; - case D3DFMT_G32R32F: - pstr = L"D3DFMT_G32R32F"; break; - case D3DFMT_A32B32G32R32F: - pstr = L"D3DFMT_A32B32G32R32F"; break; - case D3DFMT_CxV8U8: - pstr = L"D3DFMT_CxV8U8"; break; - default: - pstr = L"Unknown format"; break; - } - if( bWithPrefix || wcsstr( pstr, L"D3DFMT_" ) == NULL ) - return pstr; - else - return pstr + lstrlen( L"D3DFMT_" ); -} - - -//-------------------------------------------------------------------------------------- // Returns the string for the given DXGI_FORMAT. //-------------------------------------------------------------------------------------- +#define DXUTDXGIFMTSTR( a ) case a: pstr = L#a; break; + +_Use_decl_annotations_ LPCWSTR WINAPI DXUTDXGIFormatToString( DXGI_FORMAT format, bool bWithPrefix ) { - WCHAR* pstr = NULL; + const WCHAR* pstr = nullptr; switch( format ) { - case DXGI_FORMAT_R32G32B32A32_TYPELESS: - pstr = L"DXGI_FORMAT_R32G32B32A32_TYPELESS"; break; - case DXGI_FORMAT_R32G32B32A32_FLOAT: - pstr = L"DXGI_FORMAT_R32G32B32A32_FLOAT"; break; - case DXGI_FORMAT_R32G32B32A32_UINT: - pstr = L"DXGI_FORMAT_R32G32B32A32_UINT"; break; - case DXGI_FORMAT_R32G32B32A32_SINT: - pstr = L"DXGI_FORMAT_R32G32B32A32_SINT"; break; - case DXGI_FORMAT_R32G32B32_TYPELESS: - pstr = L"DXGI_FORMAT_R32G32B32_TYPELESS"; break; - case DXGI_FORMAT_R32G32B32_FLOAT: - pstr = L"DXGI_FORMAT_R32G32B32_FLOAT"; break; - case DXGI_FORMAT_R32G32B32_UINT: - pstr = L"DXGI_FORMAT_R32G32B32_UINT"; break; - case DXGI_FORMAT_R32G32B32_SINT: - pstr = L"DXGI_FORMAT_R32G32B32_SINT"; break; - case DXGI_FORMAT_R16G16B16A16_TYPELESS: - pstr = L"DXGI_FORMAT_R16G16B16A16_TYPELESS"; break; - case DXGI_FORMAT_R16G16B16A16_FLOAT: - pstr = L"DXGI_FORMAT_R16G16B16A16_FLOAT"; break; - case DXGI_FORMAT_R16G16B16A16_UNORM: - pstr = L"DXGI_FORMAT_R16G16B16A16_UNORM"; break; - case DXGI_FORMAT_R16G16B16A16_UINT: - pstr = L"DXGI_FORMAT_R16G16B16A16_UINT"; break; - case DXGI_FORMAT_R16G16B16A16_SNORM: - pstr = L"DXGI_FORMAT_R16G16B16A16_SNORM"; break; - case DXGI_FORMAT_R16G16B16A16_SINT: - pstr = L"DXGI_FORMAT_R16G16B16A16_SINT"; break; - case DXGI_FORMAT_R32G32_TYPELESS: - pstr = L"DXGI_FORMAT_R32G32_TYPELESS"; break; - case DXGI_FORMAT_R32G32_FLOAT: - pstr = L"DXGI_FORMAT_R32G32_FLOAT"; break; - case DXGI_FORMAT_R32G32_UINT: - pstr = L"DXGI_FORMAT_R32G32_UINT"; break; - case DXGI_FORMAT_R32G32_SINT: - pstr = L"DXGI_FORMAT_R32G32_SINT"; break; - case DXGI_FORMAT_R32G8X24_TYPELESS: - pstr = L"DXGI_FORMAT_R32G8X24_TYPELESS"; break; - case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: - pstr = L"DXGI_FORMAT_D32_FLOAT_S8X24_UINT"; break; - case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: - pstr = L"DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"; break; - case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: - pstr = L"DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"; break; - case DXGI_FORMAT_R10G10B10A2_TYPELESS: - pstr = L"DXGI_FORMAT_R10G10B10A2_TYPELESS"; break; - case DXGI_FORMAT_R10G10B10A2_UNORM: - pstr = L"DXGI_FORMAT_R10G10B10A2_UNORM"; break; - case DXGI_FORMAT_R10G10B10A2_UINT: - pstr = L"DXGI_FORMAT_R10G10B10A2_UINT"; break; - case DXGI_FORMAT_R11G11B10_FLOAT: - pstr = L"DXGI_FORMAT_R11G11B10_FLOAT"; break; - case DXGI_FORMAT_R8G8B8A8_TYPELESS: - pstr = L"DXGI_FORMAT_R8G8B8A8_TYPELESS"; break; - case DXGI_FORMAT_R8G8B8A8_UNORM: - pstr = L"DXGI_FORMAT_R8G8B8A8_UNORM"; break; - case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: - pstr = L"DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"; break; - case DXGI_FORMAT_R8G8B8A8_UINT: - pstr = L"DXGI_FORMAT_R8G8B8A8_UINT"; break; - case DXGI_FORMAT_R8G8B8A8_SNORM: - pstr = L"DXGI_FORMAT_R8G8B8A8_SNORM"; break; - case DXGI_FORMAT_R8G8B8A8_SINT: - pstr = L"DXGI_FORMAT_R8G8B8A8_SINT"; break; - case DXGI_FORMAT_R16G16_TYPELESS: - pstr = L"DXGI_FORMAT_R16G16_TYPELESS"; break; - case DXGI_FORMAT_R16G16_FLOAT: - pstr = L"DXGI_FORMAT_R16G16_FLOAT"; break; - case DXGI_FORMAT_R16G16_UNORM: - pstr = L"DXGI_FORMAT_R16G16_UNORM"; break; - case DXGI_FORMAT_R16G16_UINT: - pstr = L"DXGI_FORMAT_R16G16_UINT"; break; - case DXGI_FORMAT_R16G16_SNORM: - pstr = L"DXGI_FORMAT_R16G16_SNORM"; break; - case DXGI_FORMAT_R16G16_SINT: - pstr = L"DXGI_FORMAT_R16G16_SINT"; break; - case DXGI_FORMAT_R32_TYPELESS: - pstr = L"DXGI_FORMAT_R32_TYPELESS"; break; - case DXGI_FORMAT_D32_FLOAT: - pstr = L"DXGI_FORMAT_D32_FLOAT"; break; - case DXGI_FORMAT_R32_FLOAT: - pstr = L"DXGI_FORMAT_R32_FLOAT"; break; - case DXGI_FORMAT_R32_UINT: - pstr = L"DXGI_FORMAT_R32_UINT"; break; - case DXGI_FORMAT_R32_SINT: - pstr = L"DXGI_FORMAT_R32_SINT"; break; - case DXGI_FORMAT_R24G8_TYPELESS: - pstr = L"DXGI_FORMAT_R24G8_TYPELESS"; break; - case DXGI_FORMAT_D24_UNORM_S8_UINT: - pstr = L"DXGI_FORMAT_D24_UNORM_S8_UINT"; break; - case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: - pstr = L"DXGI_FORMAT_R24_UNORM_X8_TYPELESS"; break; - case DXGI_FORMAT_X24_TYPELESS_G8_UINT: - pstr = L"DXGI_FORMAT_X24_TYPELESS_G8_UINT"; break; - case DXGI_FORMAT_R8G8_TYPELESS: - pstr = L"DXGI_FORMAT_R8G8_TYPELESS"; break; - case DXGI_FORMAT_R8G8_UNORM: - pstr = L"DXGI_FORMAT_R8G8_UNORM"; break; - case DXGI_FORMAT_R8G8_UINT: - pstr = L"DXGI_FORMAT_R8G8_UINT"; break; - case DXGI_FORMAT_R8G8_SNORM: - pstr = L"DXGI_FORMAT_R8G8_SNORM"; break; - case DXGI_FORMAT_R8G8_SINT: - pstr = L"DXGI_FORMAT_R8G8_SINT"; break; - case DXGI_FORMAT_R16_TYPELESS: - pstr = L"DXGI_FORMAT_R16_TYPELESS"; break; - case DXGI_FORMAT_R16_FLOAT: - pstr = L"DXGI_FORMAT_R16_FLOAT"; break; - case DXGI_FORMAT_D16_UNORM: - pstr = L"DXGI_FORMAT_D16_UNORM"; break; - case DXGI_FORMAT_R16_UNORM: - pstr = L"DXGI_FORMAT_R16_UNORM"; break; - case DXGI_FORMAT_R16_UINT: - pstr = L"DXGI_FORMAT_R16_UINT"; break; - case DXGI_FORMAT_R16_SNORM: - pstr = L"DXGI_FORMAT_R16_SNORM"; break; - case DXGI_FORMAT_R16_SINT: - pstr = L"DXGI_FORMAT_R16_SINT"; break; - case DXGI_FORMAT_R8_TYPELESS: - pstr = L"DXGI_FORMAT_R8_TYPELESS"; break; - case DXGI_FORMAT_R8_UNORM: - pstr = L"DXGI_FORMAT_R8_UNORM"; break; - case DXGI_FORMAT_R8_UINT: - pstr = L"DXGI_FORMAT_R8_UINT"; break; - case DXGI_FORMAT_R8_SNORM: - pstr = L"DXGI_FORMAT_R8_SNORM"; break; - case DXGI_FORMAT_R8_SINT: - pstr = L"DXGI_FORMAT_R8_SINT"; break; - case DXGI_FORMAT_A8_UNORM: - pstr = L"DXGI_FORMAT_A8_UNORM"; break; - case DXGI_FORMAT_R1_UNORM: - pstr = L"DXGI_FORMAT_R1_UNORM"; break; - case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: - pstr = L"DXGI_FORMAT_R9G9B9E5_SHAREDEXP"; break; - case DXGI_FORMAT_R8G8_B8G8_UNORM: - pstr = L"DXGI_FORMAT_R8G8_B8G8_UNORM"; break; - case DXGI_FORMAT_G8R8_G8B8_UNORM: - pstr = L"DXGI_FORMAT_G8R8_G8B8_UNORM"; break; - case DXGI_FORMAT_BC1_TYPELESS: - pstr = L"DXGI_FORMAT_BC1_TYPELESS"; break; - case DXGI_FORMAT_BC1_UNORM: - pstr = L"DXGI_FORMAT_BC1_UNORM"; break; - case DXGI_FORMAT_BC1_UNORM_SRGB: - pstr = L"DXGI_FORMAT_BC1_UNORM_SRGB"; break; - case DXGI_FORMAT_BC2_TYPELESS: - pstr = L"DXGI_FORMAT_BC2_TYPELESS"; break; - case DXGI_FORMAT_BC2_UNORM: - pstr = L"DXGI_FORMAT_BC2_UNORM"; break; - case DXGI_FORMAT_BC2_UNORM_SRGB: - pstr = L"DXGI_FORMAT_BC2_UNORM_SRGB"; break; - case DXGI_FORMAT_BC3_TYPELESS: - pstr = L"DXGI_FORMAT_BC3_TYPELESS"; break; - case DXGI_FORMAT_BC3_UNORM: - pstr = L"DXGI_FORMAT_BC3_UNORM"; break; - case DXGI_FORMAT_BC3_UNORM_SRGB: - pstr = L"DXGI_FORMAT_BC3_UNORM_SRGB"; break; - case DXGI_FORMAT_BC4_TYPELESS: - pstr = L"DXGI_FORMAT_BC4_TYPELESS"; break; - case DXGI_FORMAT_BC4_UNORM: - pstr = L"DXGI_FORMAT_BC4_UNORM"; break; - case DXGI_FORMAT_BC4_SNORM: - pstr = L"DXGI_FORMAT_BC4_SNORM"; break; - case DXGI_FORMAT_BC5_TYPELESS: - pstr = L"DXGI_FORMAT_BC5_TYPELESS"; break; - case DXGI_FORMAT_BC5_UNORM: - pstr = L"DXGI_FORMAT_BC5_UNORM"; break; - case DXGI_FORMAT_BC5_SNORM: - pstr = L"DXGI_FORMAT_BC5_SNORM"; break; - case DXGI_FORMAT_B5G6R5_UNORM: - pstr = L"DXGI_FORMAT_B5G6R5_UNORM"; break; - case DXGI_FORMAT_B5G5R5A1_UNORM: - pstr = L"DXGI_FORMAT_B5G5R5A1_UNORM"; break; - case DXGI_FORMAT_B8G8R8A8_UNORM: - pstr = L"DXGI_FORMAT_B8G8R8A8_UNORM"; break; + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32A32_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32A32_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32A32_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32A32_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32B32_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16B16A16_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16B16A16_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16B16A16_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16B16A16_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16B16A16_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16B16A16_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G32_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32G8X24_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_D32_FLOAT_S8X24_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_X32_TYPELESS_G8X24_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R10G10B10A2_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R10G10B10A2_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R10G10B10A2_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R11G11B10_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8B8A8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8B8A8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8B8A8_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8B8A8_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8B8A8_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16G16_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_D32_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R32_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R24G8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_D24_UNORM_S8_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R24_UNORM_X8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_X24_TYPELESS_G8_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16_FLOAT) + DXUTDXGIFMTSTR(DXGI_FORMAT_D16_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R16_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8_UINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8_SINT) + DXUTDXGIFMTSTR(DXGI_FORMAT_A8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R1_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R9G9B9E5_SHAREDEXP) + DXUTDXGIFMTSTR(DXGI_FORMAT_R8G8_B8G8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_G8R8_G8B8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC1_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC1_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC1_UNORM_SRGB) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC2_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC2_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC2_UNORM_SRGB) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC3_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC3_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC3_UNORM_SRGB) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC4_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC4_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC4_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC5_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC5_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC5_SNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_B5G6R5_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_B5G5R5A1_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_B8G8R8A8_UNORM) + + // DXGI 1.1 + DXUTDXGIFMTSTR(DXGI_FORMAT_B8G8R8X8_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_B8G8R8A8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) + DXUTDXGIFMTSTR(DXGI_FORMAT_B8G8R8X8_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC6H_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC6H_UF16) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC6H_SF16) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC7_TYPELESS) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC7_UNORM) + DXUTDXGIFMTSTR(DXGI_FORMAT_BC7_UNORM_SRGB) + + // DXGI 1.2 + DXUTDXGIFMTSTR(DXGI_FORMAT_B4G4R4A4_UNORM) + default: pstr = L"Unknown format"; break; } - if( bWithPrefix || wcsstr( pstr, L"DXGI_FORMAT_" ) == NULL ) + if( bWithPrefix || !wcsstr( pstr, L"DXGI_FORMAT_" ) ) return pstr; else - return pstr + lstrlen( L"DXGI_FORMAT_" ); + return pstr + wcslen( L"DXGI_FORMAT_" ); } +#undef DXUTDXGIFMTSTR + //-------------------------------------------------------------------------------------- // Outputs to the debug stream a formatted Unicode string with a variable-argument list. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ VOID WINAPI DXUTOutputDebugStringW( LPCWSTR strMsg, ... ) { #if defined(DEBUG) || defined(_DEBUG) @@ -547,6 +356,7 @@ VOID WINAPI DXUTOutputDebugStringW( LPCWSTR strMsg, ... ) //-------------------------------------------------------------------------------------- // Outputs to the debug stream a formatted MBCS string with a variable-argument list. //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ VOID WINAPI DXUTOutputDebugStringA( LPCSTR strMsg, ... ) { #if defined(DEBUG) || defined(_DEBUG) @@ -566,203 +376,190 @@ VOID WINAPI DXUTOutputDebugStringA( LPCSTR strMsg, ... ) //-------------------------------------------------------------------------------------- -// Direct3D9 dynamic linking support -- calls top-level D3D9 APIs with graceful +// Direct3D dynamic linking support -- calls top-level D3D APIs with graceful // failure if APIs are not present. //-------------------------------------------------------------------------------------- // Function prototypes -typedef IDirect3D9* (WINAPI * LPDIRECT3DCREATE9) (UINT); -typedef INT (WINAPI * LPD3DPERF_BEGINEVENT)(D3DCOLOR, LPCWSTR); +typedef INT (WINAPI * LPD3DPERF_BEGINEVENT)(DWORD, LPCWSTR); typedef INT (WINAPI * LPD3DPERF_ENDEVENT)(void); -typedef VOID (WINAPI * LPD3DPERF_SETMARKER)(D3DCOLOR, LPCWSTR); -typedef VOID (WINAPI * LPD3DPERF_SETREGION)(D3DCOLOR, LPCWSTR); +typedef VOID (WINAPI * LPD3DPERF_SETMARKER)(DWORD, LPCWSTR); +typedef VOID (WINAPI * LPD3DPERF_SETREGION)(DWORD, LPCWSTR); typedef BOOL (WINAPI * LPD3DPERF_QUERYREPEATFRAME)(void); typedef VOID (WINAPI * LPD3DPERF_SETOPTIONS)( DWORD dwOptions ); -typedef DWORD (WINAPI * LPD3DPERF_GETSTATUS)( void ); +typedef DWORD (WINAPI * LPD3DPERF_GETSTATUS)(); typedef HRESULT (WINAPI * LPCREATEDXGIFACTORY)(REFIID, void ** ); -typedef HRESULT (WINAPI * LPD3D11CREATEDEVICE)( IDXGIAdapter*, D3D_DRIVER_TYPE, HMODULE, UINT32, D3D_FEATURE_LEVEL*, UINT, UINT32, ID3D11Device**, D3D_FEATURE_LEVEL*, ID3D11DeviceContext** ); +typedef HRESULT (WINAPI * LPDXGIGETDEBUGINTERFACE)(REFIID, void ** ); // Module and function pointers -static HMODULE s_hModD3D9 = NULL; -static LPDIRECT3DCREATE9 s_DynamicDirect3DCreate9 = NULL; -static LPD3DPERF_BEGINEVENT s_DynamicD3DPERF_BeginEvent = NULL; -static LPD3DPERF_ENDEVENT s_DynamicD3DPERF_EndEvent = NULL; -static LPD3DPERF_SETMARKER s_DynamicD3DPERF_SetMarker = NULL; -static LPD3DPERF_SETREGION s_DynamicD3DPERF_SetRegion = NULL; -static LPD3DPERF_QUERYREPEATFRAME s_DynamicD3DPERF_QueryRepeatFrame = NULL; -static LPD3DPERF_SETOPTIONS s_DynamicD3DPERF_SetOptions = NULL; -static LPD3DPERF_GETSTATUS s_DynamicD3DPERF_GetStatus = NULL; -static HMODULE s_hModDXGI = NULL; -static LPCREATEDXGIFACTORY s_DynamicCreateDXGIFactory = NULL; -static HMODULE s_hModD3D11 = NULL; -static LPD3D11CREATEDEVICE s_DynamicD3D11CreateDevice = NULL; +static HMODULE s_hModD3D9 = nullptr; +static LPD3DPERF_BEGINEVENT s_DynamicD3DPERF_BeginEvent = nullptr; +static LPD3DPERF_ENDEVENT s_DynamicD3DPERF_EndEvent = nullptr; +static LPD3DPERF_SETMARKER s_DynamicD3DPERF_SetMarker = nullptr; +static LPD3DPERF_SETREGION s_DynamicD3DPERF_SetRegion = nullptr; +static LPD3DPERF_QUERYREPEATFRAME s_DynamicD3DPERF_QueryRepeatFrame = nullptr; +static LPD3DPERF_SETOPTIONS s_DynamicD3DPERF_SetOptions = nullptr; +static LPD3DPERF_GETSTATUS s_DynamicD3DPERF_GetStatus = nullptr; +static HMODULE s_hModDXGI = nullptr; +static HMODULE s_hModDXGIDebug = nullptr; +static LPCREATEDXGIFACTORY s_DynamicCreateDXGIFactory = nullptr; +static LPDXGIGETDEBUGINTERFACE s_DynamicDXGIGetDebugInterface = nullptr; +static HMODULE s_hModD3D11 = nullptr; +static PFN_D3D11_CREATE_DEVICE s_DynamicD3D11CreateDevice = nullptr; // Ensure function pointers are initialized -static bool DXUT_EnsureD3D9APIs( void ) +static bool DXUT_EnsureD3D9APIs() { // If the module is non-NULL, this function has already been called. Note // that this doesn't guarantee that all ProcAddresses were found. - if( s_hModD3D9 != NULL ) + if( s_hModD3D9 ) return true; - // This may fail if Direct3D 9 isn't installed - s_hModD3D9 = LoadLibrary( L"d3d9.dll" ); - if( s_hModD3D9 != NULL ) + // This could fail in theory, but not on any modern version of Windows + s_hModD3D9 = LoadLibraryEx( L"d3d9.dll", nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); + if( s_hModD3D9 ) { - s_DynamicDirect3DCreate9 = (LPDIRECT3DCREATE9)GetProcAddress( s_hModD3D9, "Direct3DCreate9" ); - s_DynamicD3DPERF_BeginEvent = (LPD3DPERF_BEGINEVENT)GetProcAddress( s_hModD3D9, "D3DPERF_BeginEvent" ); - s_DynamicD3DPERF_EndEvent = (LPD3DPERF_ENDEVENT)GetProcAddress( s_hModD3D9, "D3DPERF_EndEvent" ); - s_DynamicD3DPERF_SetMarker = (LPD3DPERF_SETMARKER)GetProcAddress( s_hModD3D9, "D3DPERF_SetMarker" ); - s_DynamicD3DPERF_SetRegion = (LPD3DPERF_SETREGION)GetProcAddress( s_hModD3D9, "D3DPERF_SetRegion" ); - s_DynamicD3DPERF_QueryRepeatFrame = (LPD3DPERF_QUERYREPEATFRAME)GetProcAddress( s_hModD3D9, "D3DPERF_QueryRepeatFrame" ); - s_DynamicD3DPERF_SetOptions = (LPD3DPERF_SETOPTIONS)GetProcAddress( s_hModD3D9, "D3DPERF_SetOptions" ); - s_DynamicD3DPERF_GetStatus = (LPD3DPERF_GETSTATUS)GetProcAddress( s_hModD3D9, "D3DPERF_GetStatus" ); + // TODO - Use 11.1 perf APIs instead? + s_DynamicD3DPERF_BeginEvent = reinterpret_cast<LPD3DPERF_BEGINEVENT>( reinterpret_cast<void*>( GetProcAddress( s_hModD3D9, "D3DPERF_BeginEvent" ) ) ); + s_DynamicD3DPERF_EndEvent = reinterpret_cast<LPD3DPERF_ENDEVENT>( reinterpret_cast<void*>( GetProcAddress( s_hModD3D9, "D3DPERF_EndEvent" ) ) ); + s_DynamicD3DPERF_SetMarker = reinterpret_cast<LPD3DPERF_SETMARKER>( reinterpret_cast<void*>( GetProcAddress( s_hModD3D9, "D3DPERF_SetMarker" ) ) ); + s_DynamicD3DPERF_SetRegion = reinterpret_cast<LPD3DPERF_SETREGION>( reinterpret_cast<void*>( GetProcAddress( s_hModD3D9, "D3DPERF_SetRegion" ) ) ); + s_DynamicD3DPERF_QueryRepeatFrame = reinterpret_cast<LPD3DPERF_QUERYREPEATFRAME>( reinterpret_cast<void*>( GetProcAddress( s_hModD3D9, "D3DPERF_QueryRepeatFrame" ) ) ); + s_DynamicD3DPERF_SetOptions = reinterpret_cast<LPD3DPERF_SETOPTIONS>( reinterpret_cast<void*>( GetProcAddress( s_hModD3D9, "D3DPERF_SetOptions" ) ) ); + s_DynamicD3DPERF_GetStatus = reinterpret_cast<LPD3DPERF_GETSTATUS>( reinterpret_cast<void*>( GetProcAddress( s_hModD3D9, "D3DPERF_GetStatus" ) ) ); } - return s_hModD3D9 != NULL; + return s_hModD3D9 != nullptr; } -bool DXUT_EnsureD3D11APIs( void ) +bool DXUT_EnsureD3D11APIs() { // If both modules are non-NULL, this function has already been called. Note // that this doesn't guarantee that all ProcAddresses were found. - if( s_hModD3D11 != NULL && s_hModDXGI != NULL ) + if( s_hModD3D11 && s_hModDXGI ) return true; // This may fail if Direct3D 11 isn't installed - s_hModD3D11 = LoadLibrary( L"d3d11.dll" ); - if( s_hModD3D11 != NULL ) + s_hModD3D11 = LoadLibraryEx( L"d3d11.dll", nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); + if( s_hModD3D11 ) { - s_DynamicD3D11CreateDevice = ( LPD3D11CREATEDEVICE )GetProcAddress( s_hModD3D11, "D3D11CreateDevice" ); + s_DynamicD3D11CreateDevice = reinterpret_cast<PFN_D3D11_CREATE_DEVICE>( reinterpret_cast<void*>( GetProcAddress( s_hModD3D11, "D3D11CreateDevice" ) ) ); } if( !s_DynamicCreateDXGIFactory ) { - s_hModDXGI = LoadLibrary( L"dxgi.dll" ); + s_hModDXGI = LoadLibraryEx( L"dxgi.dll", nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); if( s_hModDXGI ) { - s_DynamicCreateDXGIFactory = ( LPCREATEDXGIFACTORY )GetProcAddress( s_hModDXGI, "CreateDXGIFactory1" ); + s_DynamicCreateDXGIFactory = reinterpret_cast<LPCREATEDXGIFACTORY>( reinterpret_cast<void*>( GetProcAddress( s_hModDXGI, "CreateDXGIFactory1" ) ) ); } - return ( s_hModDXGI != NULL ) && ( s_hModD3D11 != NULL ); - } + if ( !s_DynamicDXGIGetDebugInterface ) + { + s_hModDXGIDebug = LoadLibraryEx( L"dxgidebug.dll", nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); + if ( s_hModDXGIDebug ) + { + s_DynamicDXGIGetDebugInterface = reinterpret_cast<LPDXGIGETDEBUGINTERFACE>( reinterpret_cast<void*>( GetProcAddress( s_hModDXGIDebug, "DXGIGetDebugInterface" ) ) ); + } + } - return ( s_hModD3D11 != NULL ); -} + return ( s_hModDXGI ) && ( s_hModD3D11 ); + } -IDirect3D9* WINAPI DXUT_Dynamic_Direct3DCreate9( UINT SDKVersion ) -{ - if( DXUT_EnsureD3D9APIs() && s_DynamicDirect3DCreate9 != NULL ) - return s_DynamicDirect3DCreate9( SDKVersion ); - else - return NULL; + return s_hModD3D11 != nullptr; } -int WINAPI DXUT_Dynamic_D3DPERF_BeginEvent( D3DCOLOR col, LPCWSTR wszName ) +int WINAPI DXUT_Dynamic_D3DPERF_BeginEvent( _In_ DWORD col, _In_z_ LPCWSTR wszName ) { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_BeginEvent != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_BeginEvent ) return s_DynamicD3DPERF_BeginEvent( col, wszName ); else return -1; } -int WINAPI DXUT_Dynamic_D3DPERF_EndEvent( void ) +int WINAPI DXUT_Dynamic_D3DPERF_EndEvent() { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_EndEvent != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_EndEvent ) return s_DynamicD3DPERF_EndEvent(); else return -1; } -void WINAPI DXUT_Dynamic_D3DPERF_SetMarker( D3DCOLOR col, LPCWSTR wszName ) +void WINAPI DXUT_Dynamic_D3DPERF_SetMarker( _In_ DWORD col, _In_z_ LPCWSTR wszName ) { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_SetMarker != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_SetMarker ) s_DynamicD3DPERF_SetMarker( col, wszName ); } -void WINAPI DXUT_Dynamic_D3DPERF_SetRegion( D3DCOLOR col, LPCWSTR wszName ) +void WINAPI DXUT_Dynamic_D3DPERF_SetRegion( _In_ DWORD col, _In_z_ LPCWSTR wszName ) { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_SetRegion != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_SetRegion ) s_DynamicD3DPERF_SetRegion( col, wszName ); } -BOOL WINAPI DXUT_Dynamic_D3DPERF_QueryRepeatFrame( void ) +BOOL WINAPI DXUT_Dynamic_D3DPERF_QueryRepeatFrame() { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_QueryRepeatFrame != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_QueryRepeatFrame ) return s_DynamicD3DPERF_QueryRepeatFrame(); else return FALSE; } -void WINAPI DXUT_Dynamic_D3DPERF_SetOptions( DWORD dwOptions ) +void WINAPI DXUT_Dynamic_D3DPERF_SetOptions( _In_ DWORD dwOptions ) { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_SetOptions != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_SetOptions ) s_DynamicD3DPERF_SetOptions( dwOptions ); } -DWORD WINAPI DXUT_Dynamic_D3DPERF_GetStatus( void ) +DWORD WINAPI DXUT_Dynamic_D3DPERF_GetStatus() { - if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_GetStatus != NULL ) + if( DXUT_EnsureD3D9APIs() && s_DynamicD3DPERF_GetStatus ) return s_DynamicD3DPERF_GetStatus(); else return 0; } +_Use_decl_annotations_ HRESULT WINAPI DXUT_Dynamic_CreateDXGIFactory1( REFIID rInterface, void** ppOut ) { - if( DXUT_EnsureD3D11APIs() && s_DynamicCreateDXGIFactory != NULL ) + if( DXUT_EnsureD3D11APIs() && s_DynamicCreateDXGIFactory ) return s_DynamicCreateDXGIFactory( rInterface, ppOut ); else - return DXUTERR_NODIRECT3D11; + return DXUTERR_NODIRECT3D; } +_Use_decl_annotations_ +HRESULT WINAPI DXUT_Dynamic_DXGIGetDebugInterface( REFIID rInterface, void** ppOut ) +{ + if( DXUT_EnsureD3D11APIs() && s_DynamicDXGIGetDebugInterface ) + return s_DynamicDXGIGetDebugInterface( rInterface, ppOut ); + else + return E_NOTIMPL; +} - +_Use_decl_annotations_ HRESULT WINAPI DXUT_Dynamic_D3D11CreateDevice( IDXGIAdapter* pAdapter, D3D_DRIVER_TYPE DriverType, HMODULE Software, UINT32 Flags, - D3D_FEATURE_LEVEL* pFeatureLevels, + const D3D_FEATURE_LEVEL* pFeatureLevels, UINT FeatureLevels, UINT32 SDKVersion, ID3D11Device** ppDevice, D3D_FEATURE_LEVEL* pFeatureLevel, ID3D11DeviceContext** ppImmediateContext ) { - if( DXUT_EnsureD3D11APIs() && s_DynamicD3D11CreateDevice != NULL ) + if( DXUT_EnsureD3D11APIs() && s_DynamicD3D11CreateDevice ) return s_DynamicD3D11CreateDevice( pAdapter, DriverType, Software, Flags, pFeatureLevels, FeatureLevels, SDKVersion, ppDevice, pFeatureLevel, ppImmediateContext ); else - return DXUTERR_NODIRECT3D11; -} - -//-------------------------------------------------------------------------------------- -// Trace a string description of a decl -//-------------------------------------------------------------------------------------- -void WINAPI DXUTTraceDecl( D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE] ) -{ - int iDecl = 0; - for( iDecl = 0; iDecl < MAX_FVF_DECL_SIZE; iDecl++ ) - { - if( decl[iDecl].Stream == 0xFF ) - break; - - DXUTOutputDebugString( L"decl[%d]=Stream:%d, Offset:%d, %s, %s, %s, UsageIndex:%d\n", iDecl, - decl[iDecl].Stream, - decl[iDecl].Offset, - DXUTTraceD3DDECLTYPEtoString( decl[iDecl].Type ), - DXUTTraceD3DDECLMETHODtoString( decl[iDecl].Method ), - DXUTTraceD3DDECLUSAGEtoString( decl[iDecl].Usage ), - decl[iDecl].UsageIndex ); - } - - DXUTOutputDebugString( L"decl[%d]=D3DDECL_END\n", iDecl ); + return DXUTERR_NODIRECT3D; } #define TRACE_ID(iD) case iD: return L#iD; //-------------------------------------------------------------------------------------- -WCHAR* WINAPI DXUTTraceWindowsMessage( UINT uMsg ) +const WCHAR* WINAPI DXUTTraceWindowsMessage( _In_ UINT uMsg ) { switch( uMsg ) { @@ -987,113 +784,6 @@ WCHAR* WINAPI DXUTTraceWindowsMessage( UINT uMsg ) //-------------------------------------------------------------------------------------- -WCHAR* WINAPI DXUTTraceD3DDECLTYPEtoString( BYTE t ) -{ - switch( t ) - { - case D3DDECLTYPE_FLOAT1: - return L"D3DDECLTYPE_FLOAT1"; - case D3DDECLTYPE_FLOAT2: - return L"D3DDECLTYPE_FLOAT2"; - case D3DDECLTYPE_FLOAT3: - return L"D3DDECLTYPE_FLOAT3"; - case D3DDECLTYPE_FLOAT4: - return L"D3DDECLTYPE_FLOAT4"; - case D3DDECLTYPE_D3DCOLOR: - return L"D3DDECLTYPE_D3DCOLOR"; - case D3DDECLTYPE_UBYTE4: - return L"D3DDECLTYPE_UBYTE4"; - case D3DDECLTYPE_SHORT2: - return L"D3DDECLTYPE_SHORT2"; - case D3DDECLTYPE_SHORT4: - return L"D3DDECLTYPE_SHORT4"; - case D3DDECLTYPE_UBYTE4N: - return L"D3DDECLTYPE_UBYTE4N"; - case D3DDECLTYPE_SHORT2N: - return L"D3DDECLTYPE_SHORT2N"; - case D3DDECLTYPE_SHORT4N: - return L"D3DDECLTYPE_SHORT4N"; - case D3DDECLTYPE_USHORT2N: - return L"D3DDECLTYPE_USHORT2N"; - case D3DDECLTYPE_USHORT4N: - return L"D3DDECLTYPE_USHORT4N"; - case D3DDECLTYPE_UDEC3: - return L"D3DDECLTYPE_UDEC3"; - case D3DDECLTYPE_DEC3N: - return L"D3DDECLTYPE_DEC3N"; - case D3DDECLTYPE_FLOAT16_2: - return L"D3DDECLTYPE_FLOAT16_2"; - case D3DDECLTYPE_FLOAT16_4: - return L"D3DDECLTYPE_FLOAT16_4"; - case D3DDECLTYPE_UNUSED: - return L"D3DDECLTYPE_UNUSED"; - default: - return L"D3DDECLTYPE Unknown"; - } -} - -WCHAR* WINAPI DXUTTraceD3DDECLMETHODtoString( BYTE m ) -{ - switch( m ) - { - case D3DDECLMETHOD_DEFAULT: - return L"D3DDECLMETHOD_DEFAULT"; - case D3DDECLMETHOD_PARTIALU: - return L"D3DDECLMETHOD_PARTIALU"; - case D3DDECLMETHOD_PARTIALV: - return L"D3DDECLMETHOD_PARTIALV"; - case D3DDECLMETHOD_CROSSUV: - return L"D3DDECLMETHOD_CROSSUV"; - case D3DDECLMETHOD_UV: - return L"D3DDECLMETHOD_UV"; - case D3DDECLMETHOD_LOOKUP: - return L"D3DDECLMETHOD_LOOKUP"; - case D3DDECLMETHOD_LOOKUPPRESAMPLED: - return L"D3DDECLMETHOD_LOOKUPPRESAMPLED"; - default: - return L"D3DDECLMETHOD Unknown"; - } -} - -WCHAR* WINAPI DXUTTraceD3DDECLUSAGEtoString( BYTE u ) -{ - switch( u ) - { - case D3DDECLUSAGE_POSITION: - return L"D3DDECLUSAGE_POSITION"; - case D3DDECLUSAGE_BLENDWEIGHT: - return L"D3DDECLUSAGE_BLENDWEIGHT"; - case D3DDECLUSAGE_BLENDINDICES: - return L"D3DDECLUSAGE_BLENDINDICES"; - case D3DDECLUSAGE_NORMAL: - return L"D3DDECLUSAGE_NORMAL"; - case D3DDECLUSAGE_PSIZE: - return L"D3DDECLUSAGE_PSIZE"; - case D3DDECLUSAGE_TEXCOORD: - return L"D3DDECLUSAGE_TEXCOORD"; - case D3DDECLUSAGE_TANGENT: - return L"D3DDECLUSAGE_TANGENT"; - case D3DDECLUSAGE_BINORMAL: - return L"D3DDECLUSAGE_BINORMAL"; - case D3DDECLUSAGE_TESSFACTOR: - return L"D3DDECLUSAGE_TESSFACTOR"; - case D3DDECLUSAGE_POSITIONT: - return L"D3DDECLUSAGE_POSITIONT"; - case D3DDECLUSAGE_COLOR: - return L"D3DDECLUSAGE_COLOR"; - case D3DDECLUSAGE_FOG: - return L"D3DDECLUSAGE_FOG"; - case D3DDECLUSAGE_DEPTH: - return L"D3DDECLUSAGE_DEPTH"; - case D3DDECLUSAGE_SAMPLE: - return L"D3DDECLUSAGE_SAMPLE"; - default: - return L"D3DDECLUSAGE Unknown"; - } -} - - -//-------------------------------------------------------------------------------------- // Multimon API handling for OSes with or without multimon API support //-------------------------------------------------------------------------------------- #define DXUT_PRIMARY_MONITOR ((HMONITOR)0x12340042) @@ -1101,24 +791,19 @@ typedef HMONITOR ( WINAPI* LPMONITORFROMWINDOW )( HWND, DWORD ); typedef BOOL ( WINAPI* LPGETMONITORINFO )( HMONITOR, LPMONITORINFO ); typedef HMONITOR ( WINAPI* LPMONITORFROMRECT )( LPCRECT lprcScreenCoords, DWORD dwFlags ); +#pragma warning( suppress : 6101 ) +_Use_decl_annotations_ BOOL WINAPI DXUTGetMonitorInfo( HMONITOR hMonitor, LPMONITORINFO lpMonitorInfo ) { static bool s_bInited = false; - static LPGETMONITORINFO s_pFnGetMonitorInfo = NULL; + static LPGETMONITORINFO s_pFnGetMonitorInfo = nullptr; if( !s_bInited ) { s_bInited = true; HMODULE hUser32 = GetModuleHandle( L"USER32" ); if( hUser32 ) { - OSVERSIONINFOA osvi = - { - 0 - }; osvi.dwOSVersionInfoSize = sizeof( osvi ); GetVersionExA( ( OSVERSIONINFOA* )&osvi ); - bool bNT = ( VER_PLATFORM_WIN32_NT == osvi.dwPlatformId ); - s_pFnGetMonitorInfo = ( LPGETMONITORINFO )( bNT ? GetProcAddress( hUser32, - "GetMonitorInfoW" ) : - GetProcAddress( hUser32, "GetMonitorInfoA" ) ); + s_pFnGetMonitorInfo = reinterpret_cast<LPGETMONITORINFO>( reinterpret_cast<void*>( GetProcAddress( hUser32, "GetMonitorInfoW" ) ) ); } } @@ -1141,16 +826,17 @@ BOOL WINAPI DXUTGetMonitorInfo( HMONITOR hMonitor, LPMONITORINFO lpMonitorInfo ) } +_Use_decl_annotations_ HMONITOR WINAPI DXUTMonitorFromWindow( HWND hWnd, DWORD dwFlags ) { static bool s_bInited = false; - static LPMONITORFROMWINDOW s_pFnGetMonitorFromWindow = NULL; + static LPMONITORFROMWINDOW s_pFnGetMonitorFromWindow = nullptr; if( !s_bInited ) { s_bInited = true; HMODULE hUser32 = GetModuleHandle( L"USER32" ); - if( hUser32 ) s_pFnGetMonitorFromWindow = ( LPMONITORFROMWINDOW )GetProcAddress( hUser32, - "MonitorFromWindow" ); + if( hUser32 ) s_pFnGetMonitorFromWindow = reinterpret_cast<LPMONITORFROMWINDOW>( reinterpret_cast<void*>( GetProcAddress( hUser32, + "MonitorFromWindow" ) ) ); } if( s_pFnGetMonitorFromWindow ) @@ -1160,15 +846,16 @@ HMONITOR WINAPI DXUTMonitorFromWindow( HWND hWnd, DWORD dwFlags ) } +_Use_decl_annotations_ HMONITOR WINAPI DXUTMonitorFromRect( LPCRECT lprcScreenCoords, DWORD dwFlags ) { static bool s_bInited = false; - static LPMONITORFROMRECT s_pFnGetMonitorFromRect = NULL; + static LPMONITORFROMRECT s_pFnGetMonitorFromRect = nullptr; if( !s_bInited ) { s_bInited = true; HMODULE hUser32 = GetModuleHandle( L"USER32" ); - if( hUser32 ) s_pFnGetMonitorFromRect = ( LPMONITORFROMRECT )GetProcAddress( hUser32, "MonitorFromRect" ); + if( hUser32 ) s_pFnGetMonitorFromRect = reinterpret_cast<LPMONITORFROMRECT>( reinterpret_cast<void*>( GetProcAddress( hUser32, "MonitorFromRect" ) ) ); } if( s_pFnGetMonitorFromRect ) @@ -1179,40 +866,30 @@ HMONITOR WINAPI DXUTMonitorFromRect( LPCRECT lprcScreenCoords, DWORD dwFlags ) //-------------------------------------------------------------------------------------- -// Get the desktop resolution of an adapter. This isn't the same as the current resolution -// from GetAdapterDisplayMode since the device might be fullscreen +// Get the desktop resolution of an adapter. This isn't the same as the current resolution +// from GetAdapterDisplayMode since the device might be fullscreen //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ void WINAPI DXUTGetDesktopResolution( UINT AdapterOrdinal, UINT* pWidth, UINT* pHeight ) { - DXUTDeviceSettings DeviceSettings = DXUTGetDeviceSettings(); + auto DeviceSettings = DXUTGetDeviceSettings(); - WCHAR strDeviceName[256] = {0}; + WCHAR strDeviceName[256] = {}; DEVMODE devMode; ZeroMemory( &devMode, sizeof( DEVMODE ) ); devMode.dmSize = sizeof( DEVMODE ); - if( DeviceSettings.ver == DXUT_D3D9_DEVICE ) - { - CD3D9Enumeration* pd3dEnum = DXUTGetD3D9Enumeration(); - assert( pd3dEnum != NULL ); - CD3D9EnumAdapterInfo* pAdapterInfo = pd3dEnum->GetAdapterInfo( AdapterOrdinal ); - if( pAdapterInfo ) - { - MultiByteToWideChar( CP_ACP, 0, pAdapterInfo->AdapterIdentifier.DeviceName, -1, strDeviceName, 256 ); - strDeviceName[255] = 0; - } - } - else + + auto pd3dEnum = DXUTGetD3D11Enumeration(); + assert( pd3dEnum ); + _Analysis_assume_( pd3dEnum ); + auto pOutputInfo = pd3dEnum->GetOutputInfo( AdapterOrdinal, DeviceSettings.d3d11.Output ); + if( pOutputInfo ) { - CD3D11Enumeration* pd3dEnum = DXUTGetD3D11Enumeration(); - assert( pd3dEnum != NULL ); - CD3D11EnumOutputInfo* pOutputInfo = pd3dEnum->GetOutputInfo( AdapterOrdinal, DeviceSettings.d3d11.Output ); - if( pOutputInfo ) - { - wcscpy_s( strDeviceName, 256, pOutputInfo->Desc.DeviceName ); - } + wcscpy_s( strDeviceName, 256, pOutputInfo->Desc.DeviceName ); } EnumDisplaySettings( strDeviceName, ENUM_REGISTRY_SETTINGS, &devMode ); + if( pWidth ) *pWidth = devMode.dmPelsWidth; if( pHeight ) @@ -1221,8 +898,9 @@ void WINAPI DXUTGetDesktopResolution( UINT AdapterOrdinal, UINT* pWidth, UINT* p //-------------------------------------------------------------------------------------- -// Display error msg box to help debug +// Display error msg box to help debug //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT WINAPI DXUTTrace( const CHAR* strFile, DWORD dwLine, HRESULT hr, const WCHAR* strMsg, bool bPopMsgBox ) { @@ -1230,267 +908,17 @@ HRESULT WINAPI DXUTTrace( const CHAR* strFile, DWORD dwLine, HRESULT hr, if( bPopMsgBox && bShowMsgBoxOnError == false ) bPopMsgBox = false; - return DXTrace( strFile, dwLine, hr, strMsg, bPopMsgBox ); -} + std::wstringstream ss; + ss << strFile << L" " << dwLine << L" " << hr << L" " << strMsg; + OutputDebugString(ss.str().c_str()); -//-------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------- -void WINAPI DXUTConvertDeviceSettings11to9( DXUTD3D11DeviceSettings* pIn, DXUTD3D9DeviceSettings* pOut ) -{ - pOut->AdapterOrdinal = pIn->AdapterOrdinal; - - if( pIn->DriverType == D3D_DRIVER_TYPE_HARDWARE ) - pOut->DeviceType = D3DDEVTYPE_HAL; - else if( pIn->DriverType == D3D_DRIVER_TYPE_REFERENCE ) - pOut->DeviceType = D3DDEVTYPE_REF; - else if( pIn->DriverType == D3D_DRIVER_TYPE_NULL ) - pOut->DeviceType = D3DDEVTYPE_NULLREF; - - pOut->AdapterFormat = ConvertFormatDXGIToD3D9( pIn->sd.BufferDesc.Format ); - pOut->BehaviorFlags = D3DCREATE_HARDWARE_VERTEXPROCESSING; - pOut->pp.BackBufferWidth = pIn->sd.BufferDesc.Width; - pOut->pp.BackBufferHeight = pIn->sd.BufferDesc.Height; - pOut->pp.BackBufferFormat = ConvertFormatDXGIToD3D9( pIn->sd.BufferDesc.Format ); - pOut->pp.BackBufferCount = pIn->sd.BufferCount; - pOut->pp.MultiSampleType = ( D3DMULTISAMPLE_TYPE )pIn->sd.SampleDesc.Count; - pOut->pp.MultiSampleQuality = pIn->sd.SampleDesc.Quality; - pOut->pp.SwapEffect = D3DSWAPEFFECT_DISCARD; - pOut->pp.hDeviceWindow = pIn->sd.OutputWindow; - pOut->pp.Windowed = pIn->sd.Windowed; - pOut->pp.EnableAutoDepthStencil = true; - pOut->pp.AutoDepthStencilFormat = D3DFMT_D24FS8; - pOut->pp.Flags = 0; - if( pIn->sd.BufferDesc.RefreshRate.Denominator == 0 ) - pOut->pp.FullScreen_RefreshRateInHz = 60; - else - pOut->pp.FullScreen_RefreshRateInHz = pIn->sd.BufferDesc.RefreshRate.Numerator / - pIn->sd.BufferDesc.RefreshRate.Denominator; - - switch( pIn->SyncInterval ) - { - case 0: - pOut->pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; break; - case 2: - pOut->pp.PresentationInterval = D3DPRESENT_INTERVAL_TWO; break; - case 3: - pOut->pp.PresentationInterval = D3DPRESENT_INTERVAL_THREE; break; - case 4: - pOut->pp.PresentationInterval = D3DPRESENT_INTERVAL_FOUR; break; - - case 1: - default: - pOut->pp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT; - break; - } -} - - -//-------------------------------------------------------------------------------------- -void WINAPI DXUTConvertDeviceSettings9to11( DXUTD3D9DeviceSettings* pIn, DXUTD3D11DeviceSettings* pOut ) -{ - pOut->AdapterOrdinal = pIn->AdapterOrdinal; - - if( pIn->DeviceType == D3DDEVTYPE_HAL ) - pOut->DriverType = D3D_DRIVER_TYPE_HARDWARE; - else if( pIn->DeviceType == D3DDEVTYPE_REF ) - pOut->DriverType = D3D_DRIVER_TYPE_REFERENCE; - else if( pIn->DeviceType == D3DDEVTYPE_NULLREF ) - pOut->DriverType = D3D_DRIVER_TYPE_NULL; - - pOut->Output = 0; - - pOut->sd.BufferDesc.Width = pIn->pp.BackBufferWidth; - pOut->sd.BufferDesc.Height = pIn->pp.BackBufferHeight; - pOut->sd.BufferDesc.RefreshRate.Numerator = pIn->pp.FullScreen_RefreshRateInHz; - pOut->sd.BufferDesc.RefreshRate.Denominator = 1; - pOut->sd.BufferDesc.Format = ConvertFormatD3D9ToDXGI( pIn->pp.BackBufferFormat ); - - if( pIn->pp.MultiSampleType == D3DMULTISAMPLE_NONMASKABLE ) - { - pOut->sd.SampleDesc.Count = pIn->pp.MultiSampleQuality; - pOut->sd.SampleDesc.Quality = 0; - } - else - { - pOut->sd.SampleDesc.Count = pIn->pp.MultiSampleType; - pOut->sd.SampleDesc.Quality = pIn->pp.MultiSampleQuality; - } - - pOut->sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - pOut->sd.BufferCount = pIn->pp.BackBufferCount; - pOut->sd.OutputWindow = pIn->pp.hDeviceWindow; - pOut->sd.Windowed = pIn->pp.Windowed; - -#if defined(DEBUG) || defined(_DEBUG) - pOut->CreateFlags = D3D11_CREATE_DEVICE_DEBUG; -#else - pOut->CreateFlags = 0; -#endif - - switch( pIn->pp.PresentationInterval ) - { - case D3DPRESENT_INTERVAL_IMMEDIATE: - pOut->SyncInterval = 0; break; - case D3DPRESENT_INTERVAL_ONE: - pOut->SyncInterval = 1; break; - case D3DPRESENT_INTERVAL_TWO: - pOut->SyncInterval = 2; break; - case D3DPRESENT_INTERVAL_THREE: - pOut->SyncInterval = 3; break; - case D3DPRESENT_INTERVAL_FOUR: - pOut->SyncInterval = 4; break; - - case D3DPRESENT_INTERVAL_DEFAULT: - default: - pOut->SyncInterval = 1; - break; - } - - pOut->PresentFlags = 0; -} - - - -DXGI_FORMAT WINAPI ConvertFormatD3D9ToDXGI( D3DFORMAT fmt ) -{ - switch( fmt ) + if (bPopMsgBox) { - case D3DFMT_UNKNOWN: - return DXGI_FORMAT_UNKNOWN; - case D3DFMT_R8G8B8: - case D3DFMT_A8R8G8B8: - case D3DFMT_X8R8G8B8: - return DXGI_FORMAT_R8G8B8A8_UNORM; - case D3DFMT_R5G6B5: - return DXGI_FORMAT_B5G6R5_UNORM; - case D3DFMT_X1R5G5B5: - case D3DFMT_A1R5G5B5: - return DXGI_FORMAT_B5G5R5A1_UNORM; - case D3DFMT_A4R4G4B4: - return DXGI_FORMAT_R8G8B8A8_UNORM; - case D3DFMT_R3G3B2: - return DXGI_FORMAT_R8G8B8A8_UNORM; - case D3DFMT_A8: - return DXGI_FORMAT_A8_UNORM; - case D3DFMT_A8R3G3B2: - return DXGI_FORMAT_R8G8B8A8_UNORM; - case D3DFMT_X4R4G4B4: - return DXGI_FORMAT_R8G8B8A8_UNORM; - case D3DFMT_A2B10G10R10: - return DXGI_FORMAT_R10G10B10A2_UNORM; - case D3DFMT_A8B8G8R8: - case D3DFMT_X8B8G8R8: - return DXGI_FORMAT_B8G8R8A8_UNORM; - case D3DFMT_G16R16: - return DXGI_FORMAT_R16G16_UNORM; - case D3DFMT_A2R10G10B10: - return DXGI_FORMAT_R10G10B10A2_UNORM; - case D3DFMT_A16B16G16R16: - return DXGI_FORMAT_R16G16B16A16_UNORM; - case D3DFMT_R16F: - return DXGI_FORMAT_R16_FLOAT; - case D3DFMT_G16R16F: - return DXGI_FORMAT_R16G16_FLOAT; - case D3DFMT_A16B16G16R16F: - return DXGI_FORMAT_R16G16B16A16_FLOAT; - case D3DFMT_R32F: - return DXGI_FORMAT_R32_FLOAT; - case D3DFMT_G32R32F: - return DXGI_FORMAT_R32G32_FLOAT; - case D3DFMT_A32B32G32R32F: - return DXGI_FORMAT_R32G32B32A32_FLOAT; + MessageBox(NULL, ss.str().c_str(), L"Error", MB_OK); } - return DXGI_FORMAT_UNKNOWN; -} - - -D3DFORMAT WINAPI ConvertFormatDXGIToD3D9( DXGI_FORMAT fmt ) -{ - switch( fmt ) - { - case DXGI_FORMAT_UNKNOWN: - return D3DFMT_UNKNOWN; - case DXGI_FORMAT_R8G8B8A8_UNORM: - return D3DFMT_A8R8G8B8; - case DXGI_FORMAT_B5G6R5_UNORM: - return D3DFMT_R5G6B5; - case DXGI_FORMAT_B5G5R5A1_UNORM: - return D3DFMT_A1R5G5B5; - case DXGI_FORMAT_A8_UNORM: - return D3DFMT_A8; - case DXGI_FORMAT_R10G10B10A2_UNORM: - return D3DFMT_A2B10G10R10; - case DXGI_FORMAT_B8G8R8A8_UNORM: - return D3DFMT_A8B8G8R8; - case DXGI_FORMAT_R16G16_UNORM: - return D3DFMT_G16R16; - case DXGI_FORMAT_R16G16B16A16_UNORM: - return D3DFMT_A16B16G16R16; - case DXGI_FORMAT_R16_FLOAT: - return D3DFMT_R16F; - case DXGI_FORMAT_R16G16_FLOAT: - return D3DFMT_G16R16F; - case DXGI_FORMAT_R16G16B16A16_FLOAT: - return D3DFMT_A16B16G16R16F; - case DXGI_FORMAT_R32_FLOAT: - return D3DFMT_R32F; - case DXGI_FORMAT_R32G32_FLOAT: - return D3DFMT_G32R32F; - case DXGI_FORMAT_R32G32B32A32_FLOAT: - return D3DFMT_A32B32G32R32F; - } - return D3DFMT_UNKNOWN; -} - -//-------------------------------------------------------------------------------------- -IDirect3DDevice9* WINAPI DXUTCreateRefDevice9( HWND hWnd, bool bNullRef ) -{ - HRESULT hr; - IDirect3D9* pD3D = DXUT_Dynamic_Direct3DCreate9( D3D_SDK_VERSION ); - if( NULL == pD3D ) - return NULL; - - D3DDISPLAYMODE Mode; - pD3D->GetAdapterDisplayMode( 0, &Mode ); - - D3DPRESENT_PARAMETERS pp; - ZeroMemory( &pp, sizeof( D3DPRESENT_PARAMETERS ) ); - pp.BackBufferWidth = 1; - pp.BackBufferHeight = 1; - pp.BackBufferFormat = Mode.Format; - pp.BackBufferCount = 1; - pp.SwapEffect = D3DSWAPEFFECT_COPY; - pp.Windowed = TRUE; - pp.hDeviceWindow = hWnd; - - IDirect3DDevice9* pd3dDevice = NULL; - hr = pD3D->CreateDevice( D3DADAPTER_DEFAULT, bNullRef ? D3DDEVTYPE_NULLREF : D3DDEVTYPE_REF, - hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &pp, &pd3dDevice ); - - SAFE_RELEASE( pD3D ); - return pd3dDevice; -} - -//-------------------------------------------------------------------------------------- -// Helper function to launch the Media Center UI after the program terminates -//-------------------------------------------------------------------------------------- -bool DXUTReLaunchMediaCenter() -{ - // Get the path to Media Center - WCHAR szExpandedPath[MAX_PATH]; - if( !ExpandEnvironmentStrings( L"%SystemRoot%\\ehome\\ehshell.exe", szExpandedPath, MAX_PATH ) ) - return false; - - // Skip if ehshell.exe doesn't exist - if( GetFileAttributes( szExpandedPath ) == 0xFFFFFFFF ) - return false; - - // Launch ehshell.exe - INT_PTR result = ( INT_PTR )ShellExecute( NULL, TEXT( "open" ), szExpandedPath, NULL, NULL, SW_SHOWNORMAL ); - return ( result > 32 ); + return S_OK; } typedef DWORD ( WINAPI* LPXINPUTGETSTATE )( DWORD dwUserIndex, XINPUT_STATE* pState ); @@ -1502,24 +930,25 @@ typedef void ( WINAPI* LPXINPUTENABLE )( BOOL bEnable ); //-------------------------------------------------------------------------------------- // Does extra processing on XInput data to make it slightly more convenient to use //-------------------------------------------------------------------------------------- +_Use_decl_annotations_ HRESULT DXUTGetGamepadState( DWORD dwPort, DXUT_GAMEPAD* pGamePad, bool bThumbstickDeadZone, bool bSnapThumbstickToCardinals ) { - if( dwPort >= DXUT_MAX_CONTROLLERS || pGamePad == NULL ) + if( dwPort >= DXUT_MAX_CONTROLLERS || !pGamePad ) return E_FAIL; - static LPXINPUTGETSTATE s_pXInputGetState = NULL; - static LPXINPUTGETCAPABILITIES s_pXInputGetCapabilities = NULL; - if( NULL == s_pXInputGetState || NULL == s_pXInputGetCapabilities ) + static LPXINPUTGETSTATE s_pXInputGetState = nullptr; + static LPXINPUTGETCAPABILITIES s_pXInputGetCapabilities = nullptr; + if( !s_pXInputGetState || !s_pXInputGetCapabilities ) { - HINSTANCE hInst = LoadLibrary( XINPUT_DLL ); + HINSTANCE hInst = LoadLibraryEx( XINPUT_DLL, nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); if( hInst ) { - s_pXInputGetState = ( LPXINPUTGETSTATE )GetProcAddress( hInst, "XInputGetState" ); - s_pXInputGetCapabilities = ( LPXINPUTGETCAPABILITIES )GetProcAddress( hInst, "XInputGetCapabilities" ); + s_pXInputGetState = reinterpret_cast<LPXINPUTGETSTATE>( reinterpret_cast<void*>( GetProcAddress( hInst, "XInputGetState" ) ) ); + s_pXInputGetCapabilities = reinterpret_cast<LPXINPUTGETCAPABILITIES>( reinterpret_cast<void*>( GetProcAddress( hInst, "XInputGetCapabilities" ) ) ); } } - if( s_pXInputGetState == NULL ) + if( !s_pXInputGetState ) return E_FAIL; XINPUT_STATE InputState; @@ -1591,7 +1020,7 @@ HRESULT DXUTGetGamepadState( DWORD dwPort, DXUT_GAMEPAD* pGamePad, bool bThumbst pGamePad->fThumbRX = pGamePad->sThumbRX / 32767.0f; pGamePad->fThumbRY = pGamePad->sThumbRY / 32767.0f; - // Get the boolean buttons that have been pressed since the last call. + // Get the boolean buttons that have been pressed since the last call. // Each button is represented by one bit. pGamePad->wPressedButtons = ( pGamePad->wLastButtons ^ pGamePad->wButtons ) & pGamePad->wButtons; pGamePad->wLastButtons = pGamePad->wButtons; @@ -1611,17 +1040,17 @@ HRESULT DXUTGetGamepadState( DWORD dwPort, DXUT_GAMEPAD* pGamePad, bool bThumbst //-------------------------------------------------------------------------------------- -// Don't pause the game or deactive the window without first stopping rumble otherwise +// Don't pause the game or deactive the window without first stopping rumble otherwise // the controller will continue to rumble //-------------------------------------------------------------------------------------- -void DXUTEnableXInput( bool bEnable ) +void DXUTEnableXInput( _In_ bool bEnable ) { - static LPXINPUTENABLE s_pXInputEnable = NULL; - if( NULL == s_pXInputEnable ) + static LPXINPUTENABLE s_pXInputEnable = nullptr; + if( !s_pXInputEnable ) { - HINSTANCE hInst = LoadLibrary( XINPUT_DLL ); + HINSTANCE hInst = LoadLibraryEx( XINPUT_DLL, nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); if( hInst ) - s_pXInputEnable = ( LPXINPUTENABLE )GetProcAddress( hInst, "XInputEnable" ); + s_pXInputEnable = reinterpret_cast<LPXINPUTENABLE>( reinterpret_cast<void*>( GetProcAddress( hInst, "XInputEnable" ) ) ); } if( s_pXInputEnable ) @@ -1630,19 +1059,19 @@ void DXUTEnableXInput( bool bEnable ) //-------------------------------------------------------------------------------------- -// Don't pause the game or deactive the window without first stopping rumble otherwise +// Don't pause the game or deactive the window without first stopping rumble otherwise // the controller will continue to rumble //-------------------------------------------------------------------------------------- HRESULT DXUTStopRumbleOnAllControllers() { - static LPXINPUTSETSTATE s_pXInputSetState = NULL; - if( NULL == s_pXInputSetState ) + static LPXINPUTSETSTATE s_pXInputSetState = nullptr; + if( !s_pXInputSetState ) { - HINSTANCE hInst = LoadLibrary( XINPUT_DLL ); + HINSTANCE hInst = LoadLibraryEx( XINPUT_DLL, nullptr, 0x00000800 /* LOAD_LIBRARY_SEARCH_SYSTEM32 */ ); if( hInst ) - s_pXInputSetState = ( LPXINPUTSETSTATE )GetProcAddress( hInst, "XInputSetState" ); + s_pXInputSetState = reinterpret_cast<LPXINPUTSETSTATE>( reinterpret_cast<void*>( GetProcAddress( hInst, "XInputSetState" ) ) ); } - if( s_pXInputSetState == NULL ) + if( !s_pXInputSetState ) return E_FAIL; XINPUT_VIBRATION vibration; @@ -1657,7 +1086,7 @@ HRESULT DXUTStopRumbleOnAllControllers() //-------------------------------------------------------------------------------------- // Helper functions to create SRGB formats from typeless formats and vice versa //-------------------------------------------------------------------------------------- -DXGI_FORMAT MAKE_SRGB( DXGI_FORMAT format ) +DXGI_FORMAT MAKE_SRGB( _In_ DXGI_FORMAT format ) { if( !DXUTIsInGammaCorrectMode() ) return format; @@ -1674,116 +1103,173 @@ DXGI_FORMAT MAKE_SRGB( DXGI_FORMAT format ) case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: return DXGI_FORMAT_BC1_UNORM_SRGB; + case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: return DXGI_FORMAT_BC2_UNORM_SRGB; + case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: return DXGI_FORMAT_BC3_UNORM_SRGB; + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8A8_TYPELESS: + return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; + + case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_B8G8R8X8_TYPELESS: + return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; + + case DXGI_FORMAT_BC7_TYPELESS: + case DXGI_FORMAT_BC7_UNORM: + return DXGI_FORMAT_BC7_UNORM_SRGB; }; return format; } //-------------------------------------------------------------------------------------- -DXGI_FORMAT MAKE_TYPELESS( DXGI_FORMAT format ) +DXGI_FORMAT MAKE_TYPELESS( _In_ DXGI_FORMAT format ) { - if( !DXUTIsInGammaCorrectMode() ) - return format; - switch( format ) { - case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: - case DXGI_FORMAT_R8G8B8A8_UNORM: - case DXGI_FORMAT_R8G8B8A8_UINT: - case DXGI_FORMAT_R8G8B8A8_SNORM: - case DXGI_FORMAT_R8G8B8A8_SINT: - return DXGI_FORMAT_R8G8B8A8_TYPELESS; - - case DXGI_FORMAT_BC1_UNORM_SRGB: - case DXGI_FORMAT_BC1_UNORM: - return DXGI_FORMAT_BC1_TYPELESS; - case DXGI_FORMAT_BC2_UNORM_SRGB: - case DXGI_FORMAT_BC2_UNORM: - return DXGI_FORMAT_BC2_TYPELESS; - case DXGI_FORMAT_BC3_UNORM_SRGB: - case DXGI_FORMAT_BC3_UNORM: - return DXGI_FORMAT_BC3_TYPELESS; - }; - - return format; + case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_R32G32B32A32_UINT: + case DXGI_FORMAT_R32G32B32A32_SINT: + return DXGI_FORMAT_R32G32B32A32_TYPELESS; + + case DXGI_FORMAT_R32G32B32_FLOAT: + case DXGI_FORMAT_R32G32B32_UINT: + case DXGI_FORMAT_R32G32B32_SINT: + return DXGI_FORMAT_R32G32B32_TYPELESS; + + case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16G16B16A16_UINT: + case DXGI_FORMAT_R16G16B16A16_SNORM: + case DXGI_FORMAT_R16G16B16A16_SINT: + return DXGI_FORMAT_R16G16B16A16_TYPELESS; + + case DXGI_FORMAT_R32G32_FLOAT: + case DXGI_FORMAT_R32G32_UINT: + case DXGI_FORMAT_R32G32_SINT: + return DXGI_FORMAT_R32G32_TYPELESS; + + case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R10G10B10A2_UINT: + return DXGI_FORMAT_R10G10B10A2_TYPELESS; + + case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: + case DXGI_FORMAT_R8G8B8A8_UINT: + case DXGI_FORMAT_R8G8B8A8_SNORM: + case DXGI_FORMAT_R8G8B8A8_SINT: + return DXGI_FORMAT_R8G8B8A8_TYPELESS; + + case DXGI_FORMAT_R16G16_FLOAT: + case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_UINT: + case DXGI_FORMAT_R16G16_SNORM: + case DXGI_FORMAT_R16G16_SINT: + return DXGI_FORMAT_R16G16_TYPELESS; + + case DXGI_FORMAT_D32_FLOAT: + case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R32_UINT: + case DXGI_FORMAT_R32_SINT: + return DXGI_FORMAT_R32_TYPELESS; + + case DXGI_FORMAT_R8G8_UNORM: + case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8_SNORM: + case DXGI_FORMAT_R8G8_SINT: + return DXGI_FORMAT_R8G8_TYPELESS; + + case DXGI_FORMAT_R16_FLOAT: + case DXGI_FORMAT_D16_UNORM: + case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16_UINT: + case DXGI_FORMAT_R16_SNORM: + case DXGI_FORMAT_R16_SINT: + return DXGI_FORMAT_R16_TYPELESS; + + case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8_SNORM: + case DXGI_FORMAT_R8_SINT: + case DXGI_FORMAT_A8_UNORM: + return DXGI_FORMAT_R8_TYPELESS; + + case DXGI_FORMAT_BC1_UNORM: + case DXGI_FORMAT_BC1_UNORM_SRGB: + return DXGI_FORMAT_BC1_TYPELESS; + + case DXGI_FORMAT_BC2_UNORM: + case DXGI_FORMAT_BC2_UNORM_SRGB: + return DXGI_FORMAT_BC2_TYPELESS; + + case DXGI_FORMAT_BC3_UNORM: + case DXGI_FORMAT_BC3_UNORM_SRGB: + return DXGI_FORMAT_BC3_TYPELESS; + + case DXGI_FORMAT_BC4_UNORM: + case DXGI_FORMAT_BC4_SNORM: + return DXGI_FORMAT_BC4_TYPELESS; + + case DXGI_FORMAT_BC5_UNORM: + case DXGI_FORMAT_BC5_SNORM: + return DXGI_FORMAT_BC5_TYPELESS; + + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: + return DXGI_FORMAT_B8G8R8A8_TYPELESS; + + case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: + return DXGI_FORMAT_B8G8R8X8_TYPELESS; + + case DXGI_FORMAT_BC6H_UF16: + case DXGI_FORMAT_BC6H_SF16: + return DXGI_FORMAT_BC6H_TYPELESS; + + case DXGI_FORMAT_BC7_UNORM: + case DXGI_FORMAT_BC7_UNORM_SRGB: + return DXGI_FORMAT_BC7_TYPELESS; + + default: + return format; + } } //-------------------------------------------------------------------------------------- -HRESULT DXUTSnapD3D9Screenshot( LPCTSTR szFileName ) -{ - HRESULT hr = S_OK; - IDirect3DDevice9* pDev = DXUTGetD3D9Device(); - if( !pDev ) - return E_FAIL; - - IDirect3DSurface9* pBackBuffer = NULL; - V_RETURN( pDev->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer ) ); - - return D3DXSaveSurfaceToFile( szFileName, D3DXIFF_BMP, pBackBuffer, NULL, NULL ); -} - - - - -//-------------------------------------------------------------------------------------- -HRESULT DXUTSnapD3D11Screenshot( LPCTSTR szFileName, D3DX11_IMAGE_FILE_FORMAT iff ) +HRESULT DXUTSnapD3D11Screenshot( _In_z_ LPCWSTR szFileName, _In_ bool usedds ) { IDXGISwapChain *pSwap = DXUTGetDXGISwapChain(); if (!pSwap) return E_FAIL; - + ID3D11Texture2D* pBackBuffer; HRESULT hr = pSwap->GetBuffer( 0, __uuidof( *pBackBuffer ), ( LPVOID* )&pBackBuffer ); if (hr != S_OK) return hr; - ID3D11DeviceContext *dc = DXUTGetD3D11DeviceContext(); - if (!dc) { - SAFE_RELEASE(pBackBuffer); - return E_FAIL; - } - ID3D11Device *pDevice = DXUTGetD3D11Device(); + auto dc = DXUTGetD3D11DeviceContext(); if (!dc) { SAFE_RELEASE(pBackBuffer); return E_FAIL; } - D3D11_TEXTURE2D_DESC dsc; - pBackBuffer->GetDesc(&dsc); - D3D11_RESOURCE_DIMENSION dim; - pBackBuffer->GetType(&dim); - // special case msaa textures - ID3D11Texture2D *pCompatableTexture = pBackBuffer; - if ( dsc.SampleDesc.Count > 1) { - D3D11_TEXTURE2D_DESC dsc_new = dsc; - dsc_new.SampleDesc.Count = 1; - dsc_new.SampleDesc.Quality = 0; - dsc_new.Usage = D3D11_USAGE_DEFAULT; - dsc_new.BindFlags = 0; - dsc_new.CPUAccessFlags = 0; - ID3D11Texture2D *resolveTexture; - hr = pDevice->CreateTexture2D(&dsc_new, NULL, &resolveTexture); - if ( SUCCEEDED(hr) ) - { - DXUT_SetDebugName(resolveTexture, "DXUT"); - dc->ResolveSubresource(resolveTexture, 0, pBackBuffer, 0, dsc.Format); - pCompatableTexture = resolveTexture; - } - pCompatableTexture->GetDesc(&dsc); + if ( usedds ) + { + hr = DirectX::SaveDDSTextureToFile( dc, pBackBuffer, szFileName ); + } + else + { + hr = DirectX::SaveWICTextureToFile( dc, pBackBuffer, GUID_ContainerFormatBmp, szFileName ); } - hr = D3DX11SaveTextureToFileW(dc, pCompatableTexture, iff, szFileName); - SAFE_RELEASE(pBackBuffer); - SAFE_RELEASE(pCompatableTexture); return hr; diff --git a/samples/DX_APIUsage/DXUT/Core/DXUTmisc.h b/samples/DX_APIUsage/DXUT/Core/DXUTmisc.h index 6060e5e..a090306 100644 --- a/samples/DX_APIUsage/DXUT/Core/DXUTmisc.h +++ b/samples/DX_APIUsage/DXUT/Core/DXUTmisc.h @@ -3,15 +3,12 @@ // // Helper functions for Direct3D programming. // -// Copyright (c) Microsoft Corporation. All rights reserved +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=320437 //-------------------------------------------------------------------------------------- #pragma once -#ifndef DXUT_MISC_H -#define DXUT_MISC_H - -#ifndef MAX_FVF_DECL_SIZE -#define MAX_FVF_DECL_SIZE MAXD3DDECLLENGTH + 1 // +1 for END -#endif //-------------------------------------------------------------------------------------- // XInput helper state/function @@ -61,68 +58,17 @@ struct DXUT_GAMEPAD bool bLastRightTrigger; }; -HRESULT DXUTGetGamepadState( DWORD dwPort, DXUT_GAMEPAD* pGamePad, bool bThumbstickDeadZone = true, - bool bSnapThumbstickToCardinals = true ); +HRESULT DXUTGetGamepadState( _In_ DWORD dwPort, _In_ DXUT_GAMEPAD* pGamePad, _In_ bool bThumbstickDeadZone = true, + _In_ bool bSnapThumbstickToCardinals = true ); HRESULT DXUTStopRumbleOnAllControllers(); -void DXUTEnableXInput( bool bEnable ); +void DXUTEnableXInput( _In_ bool bEnable ); //-------------------------------------------------------------------------------------- -// Takes a screen shot of a 32bit D3D9 back buffer and saves the images to a BMP file +// Takes a screen shot of a 32bit D3D11 back buffer and saves the images to a BMP or DDS file //-------------------------------------------------------------------------------------- -HRESULT DXUTSnapD3D9Screenshot( LPCTSTR szFileName ); - -//-------------------------------------------------------------------------------------- -// Takes a screen shot of a 32bit D3D11 back buffer and saves the images to a BMP file -//-------------------------------------------------------------------------------------- - -HRESULT DXUTSnapD3D11Screenshot( LPCTSTR szFileName, D3DX11_IMAGE_FILE_FORMAT iff = D3DX11_IFF_DDS ); - - -//-------------------------------------------------------------------------------------- -// A growable array -//-------------------------------------------------------------------------------------- -template<typename TYPE> class CGrowableArray -{ -public: - CGrowableArray() { m_pData = NULL; m_nSize = 0; m_nMaxSize = 0; } - CGrowableArray( const CGrowableArray<TYPE>& a ) { for( int i=0; i < a.m_nSize; i++ ) Add( a.m_pData[i] ); } - ~CGrowableArray() { RemoveAll(); } - - const TYPE& operator[]( int nIndex ) const { return GetAt( nIndex ); } - TYPE& operator[]( int nIndex ) { return GetAt( nIndex ); } - - CGrowableArray& operator=( const CGrowableArray<TYPE>& a ) { if( this == &a ) return *this; RemoveAll(); for( int i=0; i < a.m_nSize; i++ ) Add( a.m_pData[i] ); return *this; } - - HRESULT SetSize( int nNewMaxSize ); - HRESULT Add( const TYPE& value ); - HRESULT Insert( int nIndex, const TYPE& value ); - HRESULT SetAt( int nIndex, const TYPE& value ); - TYPE& GetAt( int nIndex ) const { assert( nIndex >= 0 && nIndex < m_nSize ); return m_pData[nIndex]; } - int GetSize() const { return m_nSize; } - TYPE* GetData() { return m_pData; } - bool Contains( const TYPE& value ){ return ( -1 != IndexOf( value ) ); } - - int IndexOf( const TYPE& value ) { return ( m_nSize > 0 ) ? IndexOf( value, 0, m_nSize ) : -1; } - int IndexOf( const TYPE& value, int iStart ) { return IndexOf( value, iStart, m_nSize - iStart ); } - int IndexOf( const TYPE& value, int nIndex, int nNumElements ); - - int LastIndexOf( const TYPE& value ) { return ( m_nSize > 0 ) ? LastIndexOf( value, m_nSize-1, m_nSize ) : -1; } - int LastIndexOf( const TYPE& value, int nIndex ) { return LastIndexOf( value, nIndex, nIndex+1 ); } - int LastIndexOf( const TYPE& value, int nIndex, int nNumElements ); - - HRESULT Remove( int nIndex ); - void RemoveAll() { SetSize(0); } - void Reset() { m_nSize = 0; } - -protected: - TYPE* m_pData; // the actual array of data - int m_nSize; // # of elements (upperBound - 1) - int m_nMaxSize; // max allocated - - HRESULT SetSizeInternal( int nNewMaxSize ); // This version doesn't call ctor or dtor. -}; +HRESULT DXUTSnapD3D11Screenshot( _In_z_ LPCWSTR szFileName, _In_ bool usedds = true ); //-------------------------------------------------------------------------------------- // Performs timer operations @@ -137,18 +83,18 @@ public: void Start(); // starts the timer void Stop(); // stop (or pause) the timer void Advance(); // advance the timer by 0.1 seconds - double GetAbsoluteTime(); // get the absolute system time - double GetTime(); // get the current time + double GetAbsoluteTime() const; // get the absolute system time + double GetTime() const; // get the current time float GetElapsedTime(); // get the time that elapsed between Get*ElapsedTime() calls - void GetTimeValues( double* pfTime, double* pfAbsoluteTime, float* pfElapsedTime ); // get all time values at once - bool IsStopped(); // returns true if timer stopped + void GetTimeValues( _Out_ double* pfTime, _Out_ double* pfAbsoluteTime, _Out_ float* pfElapsedTime ); // get all time values at once + bool IsStopped() const { return m_bTimerStopped; } // returns true if timer stopped // Limit the current thread to one processor (the current one). This ensures that timing code runs // on only one processor, and will not suffer any ill effects from power management. void LimitThreadAffinityToCurrentProc(); protected: - LARGE_INTEGER GetAdjustedCurrentTime(); + LARGE_INTEGER GetAdjustedCurrentTime() const; bool m_bUsingQPF; bool m_bTimerStopped; @@ -163,41 +109,20 @@ CDXUTTimer* WINAPI DXUTGetGlobalTimer(); //-------------------------------------------------------------------------------------- -// Returns the string for the given D3DFORMAT. -// bWithPrefix determines whether the string should include the "D3DFMT_" -//-------------------------------------------------------------------------------------- -LPCWSTR WINAPI DXUTD3DFormatToString( D3DFORMAT format, bool bWithPrefix ); - - -//-------------------------------------------------------------------------------------- // Returns the string for the given DXGI_FORMAT. // bWithPrefix determines whether the string should include the "DXGI_FORMAT_" //-------------------------------------------------------------------------------------- -LPCWSTR WINAPI DXUTDXGIFormatToString( DXGI_FORMAT format, bool bWithPrefix ); - - -//-------------------------------------------------------------------------------------- -// Device settings conversion -//-------------------------------------------------------------------------------------- -void WINAPI DXUTConvertDeviceSettings11to9( DXUTD3D11DeviceSettings* pIn, DXUTD3D9DeviceSettings* pOut ); -void WINAPI DXUTConvertDeviceSettings9to11( DXUTD3D9DeviceSettings* pIn, DXUTD3D11DeviceSettings* pOut ); - -DXGI_FORMAT WINAPI ConvertFormatD3D9ToDXGI( D3DFORMAT fmt ); -D3DFORMAT WINAPI ConvertFormatDXGIToD3D9( DXGI_FORMAT fmt ); +LPCWSTR WINAPI DXUTDXGIFormatToString( _In_ DXGI_FORMAT format, _In_ bool bWithPrefix ); //-------------------------------------------------------------------------------------- // Debug printing support // See dxerr.h for more debug printing support //-------------------------------------------------------------------------------------- -void WINAPI DXUTOutputDebugStringW( LPCWSTR strMsg, ... ); -void WINAPI DXUTOutputDebugStringA( LPCSTR strMsg, ... ); -HRESULT WINAPI DXUTTrace( const CHAR* strFile, DWORD dwLine, HRESULT hr, const WCHAR* strMsg, bool bPopMsgBox ); -void WINAPI DXUTTraceDecl( D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE] ); -WCHAR* WINAPI DXUTTraceD3DDECLUSAGEtoString( BYTE u ); -WCHAR* WINAPI DXUTTraceD3DDECLMETHODtoString( BYTE m ); -WCHAR* WINAPI DXUTTraceD3DDECLTYPEtoString( BYTE t ); -WCHAR* WINAPI DXUTTraceWindowsMessage( UINT uMsg ); +void WINAPI DXUTOutputDebugStringW( _In_z_ LPCWSTR strMsg, ... ); +void WINAPI DXUTOutputDebugStringA( _In_z_ LPCSTR strMsg, ... ); +HRESULT WINAPI DXUTTrace( _In_z_ const CHAR* strFile, _In_ DWORD dwLine, _In_ HRESULT hr, _In_z_ const WCHAR* strMsg, _In_ bool bPopMsgBox ); +const WCHAR* WINAPI DXUTTraceWindowsMessage( _In_ UINT uMsg ); #ifdef UNICODE #define DXUTOutputDebugString DXUTOutputDebugStringW @@ -219,32 +144,32 @@ WCHAR* WINAPI DXUTTraceWindowsMessage( UINT uMsg ); //-------------------------------------------------------------------------------------- -// Direct3D9 dynamic linking support -- calls top-level D3D9 APIs with graceful +// Direct3D dynamic linking support -- calls top-level D3D APIs with graceful // failure if APIs are not present. //-------------------------------------------------------------------------------------- -IDirect3D9 * WINAPI DXUT_Dynamic_Direct3DCreate9(UINT SDKVersion); -int WINAPI DXUT_Dynamic_D3DPERF_BeginEvent( D3DCOLOR col, LPCWSTR wszName ); +int WINAPI DXUT_Dynamic_D3DPERF_BeginEvent( _In_ DWORD col, _In_z_ LPCWSTR wszName ); int WINAPI DXUT_Dynamic_D3DPERF_EndEvent( void ); -void WINAPI DXUT_Dynamic_D3DPERF_SetMarker( D3DCOLOR col, LPCWSTR wszName ); -void WINAPI DXUT_Dynamic_D3DPERF_SetRegion( D3DCOLOR col, LPCWSTR wszName ); +void WINAPI DXUT_Dynamic_D3DPERF_SetMarker( _In_ DWORD col, _In_z_ LPCWSTR wszName ); +void WINAPI DXUT_Dynamic_D3DPERF_SetRegion( _In_ DWORD col, _In_z_ LPCWSTR wszName ); BOOL WINAPI DXUT_Dynamic_D3DPERF_QueryRepeatFrame( void ); -void WINAPI DXUT_Dynamic_D3DPERF_SetOptions( DWORD dwOptions ); -DWORD WINAPI DXUT_Dynamic_D3DPERF_GetStatus( void ); -HRESULT WINAPI DXUT_Dynamic_CreateDXGIFactory1( REFIID rInterface, void** ppOut ); +void WINAPI DXUT_Dynamic_D3DPERF_SetOptions( _In_ DWORD dwOptions ); +DWORD WINAPI DXUT_Dynamic_D3DPERF_GetStatus(); +HRESULT WINAPI DXUT_Dynamic_CreateDXGIFactory1( _In_ REFIID rInterface, _Out_ void** ppOut ); +HRESULT WINAPI DXUT_Dynamic_DXGIGetDebugInterface( _In_ REFIID rInterface, _Out_ void** ppOut ); -HRESULT WINAPI DXUT_Dynamic_D3D11CreateDevice( IDXGIAdapter* pAdapter, - D3D_DRIVER_TYPE DriverType, - HMODULE Software, - UINT32 Flags, - D3D_FEATURE_LEVEL* pFeatureLevels, - UINT FeatureLevels, - UINT32 SDKVersion, - ID3D11Device** ppDevice, - D3D_FEATURE_LEVEL* pFeatureLevel, - ID3D11DeviceContext** ppImmediateContext ); +HRESULT WINAPI DXUT_Dynamic_D3D11CreateDevice( _In_opt_ IDXGIAdapter* pAdapter, + _In_ D3D_DRIVER_TYPE DriverType, + _In_opt_ HMODULE Software, + _In_ UINT32 Flags, + _In_reads_(FeatureLevels) const D3D_FEATURE_LEVEL* pFeatureLevels, + _In_ UINT FeatureLevels, + _In_ UINT32 SDKVersion, + _Deref_out_ ID3D11Device** ppDevice, + _Out_opt_ D3D_FEATURE_LEVEL* pFeatureLevel, + _Out_opt_ ID3D11DeviceContext** ppImmediateContext ); -bool DXUT_EnsureD3D11APIs( void ); +bool DXUT_EnsureD3D11APIs(); //-------------------------------------------------------------------------------------- @@ -254,35 +179,20 @@ bool DXUT_EnsureD3D11APIs( void ); // Use DXUT_SetDebugName() to attach names to D3D objects for use by // SDKDebugLayer, PIX's object table, etc. #if defined(PROFILE) || defined(DEBUG) -inline void DXUT_SetDebugName( IDirect3DResource9* pObj, const CHAR* pstrName ) +inline void DXUT_SetDebugName( _In_ IDXGIObject* pObj, _In_z_ const CHAR* pstrName ) { if ( pObj ) - pObj->SetPrivateData( WKPDID_D3DDebugObjectName, pstrName, lstrlenA(pstrName), 0 ); + pObj->SetPrivateData( WKPDID_D3DDebugObjectName, (UINT)strlen(pstrName), pstrName ); } -inline void DXUT_SetDebugName( IDXGIObject* pObj, const CHAR* pstrName ) +inline void DXUT_SetDebugName( _In_ ID3D11Device* pObj, _In_z_ const CHAR* pstrName ) { if ( pObj ) - pObj->SetPrivateData( WKPDID_D3DDebugObjectName, lstrlenA(pstrName), pstrName ); + pObj->SetPrivateData( WKPDID_D3DDebugObjectName, (UINT)strlen(pstrName), pstrName ); } -inline void DXUT_SetDebugName( ID3D10Device* pObj, const CHAR* pstrName ) +inline void DXUT_SetDebugName( _In_ ID3D11DeviceChild* pObj, _In_z_ const CHAR* pstrName ) { if ( pObj ) - pObj->SetPrivateData( WKPDID_D3DDebugObjectName, lstrlenA(pstrName), pstrName ); -} -inline void DXUT_SetDebugName( ID3D10DeviceChild* pObj, const CHAR* pstrName ) -{ - if ( pObj ) - pObj->SetPrivateData( WKPDID_D3DDebugObjectName, lstrlenA(pstrName), pstrName ); -} -inline void DXUT_SetDebugName( ID3D11Device* pObj, const CHAR* pstrName ) -{ - if ( pObj ) - pObj->SetPrivateData( WKPDID_D3DDebugObjectName, lstrlenA(pstrName), pstrName ); -} -inline void DXUT_SetDebugName( ID3D11DeviceChild* pObj, const CHAR* pstrName ) -{ - if ( pObj ) - pObj->SetPrivateData( WKPDID_D3DDebugObjectName, lstrlenA(pstrName), pstrName ); + pObj->SetPrivateData( WKPDID_D3DDebugObjectName, (UINT)strlen(pstrName), pstrName ); } #else #define DXUT_SetDebugName( pObj, pstrName ) @@ -294,9 +204,9 @@ inline void DXUT_SetDebugName( ID3D11DeviceChild* pObj, const CHAR* pstrName ) // performance analysis tools. The following constants are provided for your // convenience, but you can use any colors you like. //-------------------------------------------------------------------------------------- -const D3DCOLOR DXUT_PERFEVENTCOLOR = D3DCOLOR_XRGB( 200, 100, 100 ); -const D3DCOLOR DXUT_PERFEVENTCOLOR2 = D3DCOLOR_XRGB( 100, 200, 100 ); -const D3DCOLOR DXUT_PERFEVENTCOLOR3 = D3DCOLOR_XRGB( 100, 100, 200 ); +const DWORD DXUT_PERFEVENTCOLOR = 0xFFC86464; +const DWORD DXUT_PERFEVENTCOLOR2 = 0xFF64C864; +const DWORD DXUT_PERFEVENTCOLOR3 = 0xFF6464C8; //-------------------------------------------------------------------------------------- // The following macros provide a convenient way for your code to call the D3DPERF @@ -330,11 +240,16 @@ const D3DCOLOR DXUT_PERFEVENTCOLOR3 = D3DCOLOR_XRGB( 100, 100, 200 class CDXUTPerfEventGenerator { public: -CDXUTPerfEventGenerator( D3DCOLOR color, LPCWSTR pstrMessage ) +CDXUTPerfEventGenerator( _In_ DWORD color, _In_z_ LPCWSTR pstrMessage ) { +#ifdef PROFILE DXUT_BeginPerfEvent( color, pstrMessage ); +#else + UNREFERENCED_PARAMETER(color); + UNREFERENCED_PARAMETER(pstrMessage); +#endif } -~CDXUTPerfEventGenerator( void ) +~CDXUTPerfEventGenerator() { DXUT_EndPerfEvent(); } @@ -366,269 +281,14 @@ typedef MONITORINFOEXW MONITORINFOEX; typedef LPMONITORINFOEXW LPMONITORINFOEX; #endif -HMONITOR WINAPI DXUTMonitorFromWindow( HWND hWnd, DWORD dwFlags ); -HMONITOR WINAPI DXUTMonitorFromRect( LPCRECT lprcScreenCoords, DWORD dwFlags ); -BOOL WINAPI DXUTGetMonitorInfo( HMONITOR hMonitor, LPMONITORINFO lpMonitorInfo ); -void WINAPI DXUTGetDesktopResolution( UINT AdapterOrdinal, UINT* pWidth, UINT* pHeight ); - - -//-------------------------------------------------------------------------------------- -// Implementation of CGrowableArray -//-------------------------------------------------------------------------------------- - -// This version doesn't call ctor or dtor. -template<typename TYPE> HRESULT CGrowableArray <TYPE>::SetSizeInternal( int nNewMaxSize ) -{ - if( nNewMaxSize < 0 || ( nNewMaxSize > INT_MAX / sizeof( TYPE ) ) ) - { - assert( false ); - return E_INVALIDARG; - } - - if( nNewMaxSize == 0 ) - { - // Shrink to 0 size & cleanup - if( m_pData ) - { - free( m_pData ); - m_pData = NULL; - } - - m_nMaxSize = 0; - m_nSize = 0; - } - else if( m_pData == NULL || nNewMaxSize > m_nMaxSize ) - { - // Grow array - int nGrowBy = ( m_nMaxSize == 0 ) ? 16 : m_nMaxSize; - - // Limit nGrowBy to keep m_nMaxSize less than INT_MAX - if( ( UINT )m_nMaxSize + ( UINT )nGrowBy > ( UINT )INT_MAX ) - nGrowBy = INT_MAX - m_nMaxSize; - - nNewMaxSize = __max( nNewMaxSize, m_nMaxSize + nGrowBy ); - - // Verify that (nNewMaxSize * sizeof(TYPE)) is not greater than UINT_MAX or the realloc will overrun - if( sizeof( TYPE ) > UINT_MAX / ( UINT )nNewMaxSize ) - return E_INVALIDARG; - - TYPE* pDataNew = ( TYPE* )realloc( m_pData, nNewMaxSize * sizeof( TYPE ) ); - if( pDataNew == NULL ) - return E_OUTOFMEMORY; - - m_pData = pDataNew; - m_nMaxSize = nNewMaxSize; - } - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -template<typename TYPE> HRESULT CGrowableArray <TYPE>::SetSize( int nNewMaxSize ) -{ - int nOldSize = m_nSize; - - if( nOldSize > nNewMaxSize ) - { - assert( m_pData ); - if( m_pData ) - { - // Removing elements. Call dtor. - - for( int i = nNewMaxSize; i < nOldSize; ++i ) - m_pData[i].~TYPE(); - } - } - - // Adjust buffer. Note that there's no need to check for error - // since if it happens, nOldSize == nNewMaxSize will be true.) - HRESULT hr = SetSizeInternal( nNewMaxSize ); - - if( nOldSize < nNewMaxSize ) - { - assert( m_pData ); - if( m_pData ) - { - // Adding elements. Call ctor. - - for( int i = nOldSize; i < nNewMaxSize; ++i ) - ::new ( &m_pData[i] ) TYPE; - } - } - - return hr; -} - - -//-------------------------------------------------------------------------------------- -template<typename TYPE> HRESULT CGrowableArray <TYPE>::Add( const TYPE& value ) -{ - HRESULT hr; - if( FAILED( hr = SetSizeInternal( m_nSize + 1 ) ) ) - return hr; - - assert( m_pData != NULL ); - - // Construct the new element - ::new ( &m_pData[m_nSize] ) TYPE; - - // Assign - m_pData[m_nSize] = value; - ++m_nSize; - - return S_OK; -} +HMONITOR WINAPI DXUTMonitorFromWindow( _In_ HWND hWnd, _In_ DWORD dwFlags ); +HMONITOR WINAPI DXUTMonitorFromRect( _In_ LPCRECT lprcScreenCoords, _In_ DWORD dwFlags ); +BOOL WINAPI DXUTGetMonitorInfo( _In_ HMONITOR hMonitor, _Out_ LPMONITORINFO lpMonitorInfo ); +void WINAPI DXUTGetDesktopResolution( _In_ UINT AdapterOrdinal, _Out_ UINT* pWidth, _Out_ UINT* pHeight ); //-------------------------------------------------------------------------------------- -template<typename TYPE> HRESULT CGrowableArray <TYPE>::Insert( int nIndex, const TYPE& value ) -{ - HRESULT hr; - - // Validate index - if( nIndex < 0 || - nIndex > m_nSize ) - { - assert( false ); - return E_INVALIDARG; - } - - // Prepare the buffer - if( FAILED( hr = SetSizeInternal( m_nSize + 1 ) ) ) - return hr; - - // Shift the array - MoveMemory( &m_pData[nIndex + 1], &m_pData[nIndex], sizeof( TYPE ) * ( m_nSize - nIndex ) ); - - // Construct the new element - ::new ( &m_pData[nIndex] ) TYPE; - - // Set the value and increase the size - m_pData[nIndex] = value; - ++m_nSize; - - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -template<typename TYPE> HRESULT CGrowableArray <TYPE>::SetAt( int nIndex, const TYPE& value ) -{ - // Validate arguments - if( nIndex < 0 || - nIndex >= m_nSize ) - { - assert( false ); - return E_INVALIDARG; - } - - m_pData[nIndex] = value; - return S_OK; -} - - -//-------------------------------------------------------------------------------------- -// Searches for the specified value and returns the index of the first occurrence -// within the section of the data array that extends from iStart and contains the -// specified number of elements. Returns -1 if value is not found within the given -// section. -//-------------------------------------------------------------------------------------- -template<typename TYPE> int CGrowableArray <TYPE>::IndexOf( const TYPE& value, int iStart, int nNumElements ) -{ - // Validate arguments - if( iStart < 0 || - iStart >= m_nSize || - nNumElements < 0 || - iStart + nNumElements > m_nSize ) - { - assert( false ); - return -1; - } - - // Search - for( int i = iStart; i < ( iStart + nNumElements ); i++ ) - { - if( value == m_pData[i] ) - return i; - } - - // Not found - return -1; -} - - -//-------------------------------------------------------------------------------------- -// Searches for the specified value and returns the index of the last occurrence -// within the section of the data array that contains the specified number of elements -// and ends at iEnd. Returns -1 if value is not found within the given section. -//-------------------------------------------------------------------------------------- -template<typename TYPE> int CGrowableArray <TYPE>::LastIndexOf( const TYPE& value, int iEnd, int nNumElements ) -{ - // Validate arguments - if( iEnd < 0 || - iEnd >= m_nSize || - nNumElements < 0 || - iEnd - nNumElements < 0 ) - { - assert( false ); - return -1; - } - - // Search - for( int i = iEnd; i > ( iEnd - nNumElements ); i-- ) - { - if( value == m_pData[i] ) - return i; - } - - // Not found - return -1; -} - - - -//-------------------------------------------------------------------------------------- -template<typename TYPE> HRESULT CGrowableArray <TYPE>::Remove( int nIndex ) -{ - if( nIndex < 0 || - nIndex >= m_nSize ) - { - assert( false ); - return E_INVALIDARG; - } - - // Destruct the element to be removed - m_pData[nIndex].~TYPE(); - - // Compact the array and decrease the size - MoveMemory( &m_pData[nIndex], &m_pData[nIndex + 1], sizeof( TYPE ) * ( m_nSize - ( nIndex + 1 ) ) ); - --m_nSize; - - return S_OK; -} - -//-------------------------------------------------------------------------------------- -// Creates a REF or NULLREF D3D9 device and returns that device. The caller should call -// Release() when done with the device. -//-------------------------------------------------------------------------------------- -IDirect3DDevice9* WINAPI DXUTCreateRefDevice9( HWND hWnd, bool bNullRef = true ); - -//-------------------------------------------------------------------------------------- -// Creates a REF or NULLREF D3D10 device and returns the device. The caller should call -// Release() when done with the device. -//-------------------------------------------------------------------------------------- -//test d3d10 version ID3D10Device* WINAPI DXUTCreateRefDevice10( bool bNullRef = true ); - -//-------------------------------------------------------------------------------------- -// Helper function to launch the Media Center UI after the program terminates -//-------------------------------------------------------------------------------------- -bool DXUTReLaunchMediaCenter(); - -//-------------------------------------------------------------------------------------- // Helper functions to create SRGB formats from typeless formats and vice versa //-------------------------------------------------------------------------------------- -DXGI_FORMAT MAKE_SRGB( DXGI_FORMAT format ); -DXGI_FORMAT MAKE_TYPELESS( DXGI_FORMAT format ); - -#endif +DXGI_FORMAT MAKE_SRGB( _In_ DXGI_FORMAT format ); +DXGI_FORMAT MAKE_TYPELESS( _In_ DXGI_FORMAT format ); diff --git a/samples/DX_APIUsage/DXUT/Core/ScreenGrab.cpp b/samples/DX_APIUsage/DXUT/Core/ScreenGrab.cpp new file mode 100644 index 0000000..deb693c --- /dev/null +++ b/samples/DX_APIUsage/DXUT/Core/ScreenGrab.cpp @@ -0,0 +1,1204 @@ +//-------------------------------------------------------------------------------------- +// File: ScreenGrab.cpp +// +// Function for capturing a 2D texture and saving it to a file (aka a 'screenshot' +// when used on a Direct3D 11 Render Target). +// +// Note these functions are useful as a light-weight runtime screen grabber. For +// full-featured texture capture, DDS writer, and texture processing pipeline, +// see the 'Texconv' sample and the 'DirectXTex' library. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=248926 +// http://go.microsoft.com/fwlink/?LinkId=248929 +//-------------------------------------------------------------------------------------- + +#include "dxut.h" + +// Does not capture 1D textures or 3D textures (volume maps) + +// Does not capture mipmap chains, only the top-most texture level is saved + +// For 2D array textures and cubemaps, it captures only the first image in the array + +#include "ScreenGrab.h" + +#include <dxgiformat.h> +#include <assert.h> + +#include <wincodec.h> + +#include <wrl\client.h> + +#include <algorithm> +#include <memory> + +using Microsoft::WRL::ComPtr; + +//-------------------------------------------------------------------------------------- +// Macros +//-------------------------------------------------------------------------------------- +#ifndef MAKEFOURCC + #define MAKEFOURCC(ch0, ch1, ch2, ch3) \ + ((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) | \ + ((uint32_t)(uint8_t)(ch2) << 16) | ((uint32_t)(uint8_t)(ch3) << 24 )) +#endif /* defined(MAKEFOURCC) */ + +//-------------------------------------------------------------------------------------- +// DDS file structure definitions +// +// See DDS.h in the 'Texconv' sample and the 'DirectXTex' library +//-------------------------------------------------------------------------------------- +namespace +{ + #pragma pack(push,1) + + #define DDS_MAGIC 0x20534444 // "DDS " + + struct DDS_PIXELFORMAT + { + uint32_t size; + uint32_t flags; + uint32_t fourCC; + uint32_t RGBBitCount; + uint32_t RBitMask; + uint32_t GBitMask; + uint32_t BBitMask; + uint32_t ABitMask; + }; + + #define DDS_FOURCC 0x00000004 // DDPF_FOURCC + #define DDS_RGB 0x00000040 // DDPF_RGB + #define DDS_RGBA 0x00000041 // DDPF_RGB | DDPF_ALPHAPIXELS + #define DDS_LUMINANCE 0x00020000 // DDPF_LUMINANCE + #define DDS_LUMINANCEA 0x00020001 // DDPF_LUMINANCE | DDPF_ALPHAPIXELS + #define DDS_ALPHA 0x00000002 // DDPF_ALPHA + #define DDS_BUMPDUDV 0x00080000 // DDPF_BUMPDUDV + + #define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT + #define DDS_HEADER_FLAGS_MIPMAP 0x00020000 // DDSD_MIPMAPCOUNT + #define DDS_HEADER_FLAGS_PITCH 0x00000008 // DDSD_PITCH + #define DDS_HEADER_FLAGS_LINEARSIZE 0x00080000 // DDSD_LINEARSIZE + + #define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT + #define DDS_WIDTH 0x00000004 // DDSD_WIDTH + + #define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE + + typedef struct + { + uint32_t size; + uint32_t flags; + uint32_t height; + uint32_t width; + uint32_t pitchOrLinearSize; + uint32_t depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags + uint32_t mipMapCount; + uint32_t reserved1[11]; + DDS_PIXELFORMAT ddspf; + uint32_t caps; + uint32_t caps2; + uint32_t caps3; + uint32_t caps4; + uint32_t reserved2; + } DDS_HEADER; + + typedef struct + { + DXGI_FORMAT dxgiFormat; + uint32_t resourceDimension; + uint32_t miscFlag; // see D3D11_RESOURCE_MISC_FLAG + uint32_t arraySize; + uint32_t reserved; + } DDS_HEADER_DXT10; + + #pragma pack(pop) + + const DDS_PIXELFORMAT DDSPF_DXT1 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','1'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_DXT3 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','3'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_DXT5 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','5'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_BC4_UNORM = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','U'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_BC4_SNORM = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','S'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_BC5_UNORM = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','U'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_BC5_SNORM = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','S'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_R8G8_B8G8 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('R','G','B','G'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_G8R8_G8B8 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('G','R','G','B'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_YUY2 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('Y','U','Y','2'), 0, 0, 0, 0, 0 }; + + const DDS_PIXELFORMAT DDSPF_A8R8G8B8 = + { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 }; + + const DDS_PIXELFORMAT DDSPF_X8R8G8B8 = + { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000 }; + + const DDS_PIXELFORMAT DDSPF_A8B8G8R8 = + { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 }; + + const DDS_PIXELFORMAT DDSPF_G16R16 = + { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x0000ffff, 0xffff0000, 0x00000000, 0x00000000 }; + + const DDS_PIXELFORMAT DDSPF_R5G6B5 = + { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0x0000f800, 0x000007e0, 0x0000001f, 0x00000000 }; + + const DDS_PIXELFORMAT DDSPF_A1R5G5B5 = + { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00007c00, 0x000003e0, 0x0000001f, 0x00008000 }; + + const DDS_PIXELFORMAT DDSPF_A4R4G4B4 = + { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00000f00, 0x000000f0, 0x0000000f, 0x0000f000 }; + + const DDS_PIXELFORMAT DDSPF_L8 = + { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 8, 0xff, 0x00, 0x00, 0x00 }; + + const DDS_PIXELFORMAT DDSPF_L16 = + { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 16, 0xffff, 0x0000, 0x0000, 0x0000 }; + + const DDS_PIXELFORMAT DDSPF_A8L8 = + { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 16, 0x00ff, 0x0000, 0x0000, 0xff00 }; + + const DDS_PIXELFORMAT DDSPF_A8 = + { sizeof(DDS_PIXELFORMAT), DDS_ALPHA, 0, 8, 0x00, 0x00, 0x00, 0xff }; + + const DDS_PIXELFORMAT DDSPF_V8U8 = + { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 16, 0x00ff, 0xff00, 0x0000, 0x0000 }; + + const DDS_PIXELFORMAT DDSPF_Q8W8V8U8 = + { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 }; + + const DDS_PIXELFORMAT DDSPF_V16U16 = + { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x0000ffff, 0xffff0000, 0x00000000, 0x00000000 }; + + // DXGI_FORMAT_R10G10B10A2_UNORM should be written using DX10 extension to avoid D3DX 10:10:10:2 reversal issue + + // This indicates the DDS_HEADER_DXT10 extension is present (the format is in dxgiFormat) + const DDS_PIXELFORMAT DDSPF_DX10 = + { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','1','0'), 0, 0, 0, 0, 0 }; + + //----------------------------------------------------------------------------- + struct handle_closer { void operator()(HANDLE h) { if (h) CloseHandle(h); } }; + + typedef public std::unique_ptr<void, handle_closer> ScopedHandle; + + inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? 0 : h; } + + class auto_delete_file + { + public: + auto_delete_file(HANDLE hFile) : m_handle(hFile) {} + ~auto_delete_file() + { + if (m_handle) + { + FILE_DISPOSITION_INFO info = {}; + info.DeleteFile = TRUE; + (void)SetFileInformationByHandle(m_handle, FileDispositionInfo, &info, sizeof(info)); + } + } + + void clear() { m_handle = 0; } + + private: + HANDLE m_handle; + + auto_delete_file(const auto_delete_file&) = delete; + auto_delete_file& operator=(const auto_delete_file&) = delete; + }; + + class auto_delete_file_wic + { + public: + auto_delete_file_wic(ComPtr<IWICStream>& hFile, const wchar_t* szFile) : m_handle(hFile), m_filename(szFile) {} + ~auto_delete_file_wic() + { + if (m_filename) + { + m_handle.Reset(); + DeleteFileW(m_filename); + } + } + + void clear() { m_filename = 0; } + + private: + const wchar_t* m_filename; + ComPtr<IWICStream>& m_handle; + + auto_delete_file_wic(const auto_delete_file_wic&) = delete; + auto_delete_file_wic& operator=(const auto_delete_file_wic&) = delete; + }; + + //-------------------------------------------------------------------------------------- + // Return the BPP for a particular format + //-------------------------------------------------------------------------------------- + size_t BitsPerPixel( _In_ DXGI_FORMAT fmt ) + { + switch( fmt ) + { + case DXGI_FORMAT_R32G32B32A32_TYPELESS: + case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_R32G32B32A32_UINT: + case DXGI_FORMAT_R32G32B32A32_SINT: + return 128; + + case DXGI_FORMAT_R32G32B32_TYPELESS: + case DXGI_FORMAT_R32G32B32_FLOAT: + case DXGI_FORMAT_R32G32B32_UINT: + case DXGI_FORMAT_R32G32B32_SINT: + return 96; + + case DXGI_FORMAT_R16G16B16A16_TYPELESS: + case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16G16B16A16_UINT: + case DXGI_FORMAT_R16G16B16A16_SNORM: + case DXGI_FORMAT_R16G16B16A16_SINT: + case DXGI_FORMAT_R32G32_TYPELESS: + case DXGI_FORMAT_R32G32_FLOAT: + case DXGI_FORMAT_R32G32_UINT: + case DXGI_FORMAT_R32G32_SINT: + case DXGI_FORMAT_R32G8X24_TYPELESS: + case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: + case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: + case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: + case DXGI_FORMAT_Y416: + case DXGI_FORMAT_Y210: + case DXGI_FORMAT_Y216: + return 64; + + case DXGI_FORMAT_R10G10B10A2_TYPELESS: + case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R10G10B10A2_UINT: + case DXGI_FORMAT_R11G11B10_FLOAT: + case DXGI_FORMAT_R8G8B8A8_TYPELESS: + case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: + case DXGI_FORMAT_R8G8B8A8_UINT: + case DXGI_FORMAT_R8G8B8A8_SNORM: + case DXGI_FORMAT_R8G8B8A8_SINT: + case DXGI_FORMAT_R16G16_TYPELESS: + case DXGI_FORMAT_R16G16_FLOAT: + case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_UINT: + case DXGI_FORMAT_R16G16_SNORM: + case DXGI_FORMAT_R16G16_SINT: + case DXGI_FORMAT_R32_TYPELESS: + case DXGI_FORMAT_D32_FLOAT: + case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R32_UINT: + case DXGI_FORMAT_R32_SINT: + case DXGI_FORMAT_R24G8_TYPELESS: + case DXGI_FORMAT_D24_UNORM_S8_UINT: + case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: + case DXGI_FORMAT_X24_TYPELESS_G8_UINT: + case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: + case DXGI_FORMAT_R8G8_B8G8_UNORM: + case DXGI_FORMAT_G8R8_G8B8_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: + case DXGI_FORMAT_B8G8R8A8_TYPELESS: + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: + case DXGI_FORMAT_B8G8R8X8_TYPELESS: + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: + case DXGI_FORMAT_AYUV: + case DXGI_FORMAT_Y410: + case DXGI_FORMAT_YUY2: + return 32; + + case DXGI_FORMAT_P010: + case DXGI_FORMAT_P016: + return 24; + + case DXGI_FORMAT_R8G8_TYPELESS: + case DXGI_FORMAT_R8G8_UNORM: + case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8_SNORM: + case DXGI_FORMAT_R8G8_SINT: + case DXGI_FORMAT_R16_TYPELESS: + case DXGI_FORMAT_R16_FLOAT: + case DXGI_FORMAT_D16_UNORM: + case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16_UINT: + case DXGI_FORMAT_R16_SNORM: + case DXGI_FORMAT_R16_SINT: + case DXGI_FORMAT_B5G6R5_UNORM: + case DXGI_FORMAT_B5G5R5A1_UNORM: + case DXGI_FORMAT_A8P8: + case DXGI_FORMAT_B4G4R4A4_UNORM: + return 16; + + case DXGI_FORMAT_NV12: + case DXGI_FORMAT_420_OPAQUE: + case DXGI_FORMAT_NV11: + return 12; + + case DXGI_FORMAT_R8_TYPELESS: + case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8_SNORM: + case DXGI_FORMAT_R8_SINT: + case DXGI_FORMAT_A8_UNORM: + case DXGI_FORMAT_AI44: + case DXGI_FORMAT_IA44: + case DXGI_FORMAT_P8: + return 8; + + case DXGI_FORMAT_R1_UNORM: + return 1; + + case DXGI_FORMAT_BC1_TYPELESS: + case DXGI_FORMAT_BC1_UNORM: + case DXGI_FORMAT_BC1_UNORM_SRGB: + case DXGI_FORMAT_BC4_TYPELESS: + case DXGI_FORMAT_BC4_UNORM: + case DXGI_FORMAT_BC4_SNORM: + return 4; + + case DXGI_FORMAT_BC2_TYPELESS: + case DXGI_FORMAT_BC2_UNORM: + case DXGI_FORMAT_BC2_UNORM_SRGB: + case DXGI_FORMAT_BC3_TYPELESS: + case DXGI_FORMAT_BC3_UNORM: + case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC5_TYPELESS: + case DXGI_FORMAT_BC5_UNORM: + case DXGI_FORMAT_BC5_SNORM: + case DXGI_FORMAT_BC6H_TYPELESS: + case DXGI_FORMAT_BC6H_UF16: + case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_TYPELESS: + case DXGI_FORMAT_BC7_UNORM: + case DXGI_FORMAT_BC7_UNORM_SRGB: + return 8; + + default: + return 0; + } + } + + + //-------------------------------------------------------------------------------------- + // Determines if the format is block compressed + //-------------------------------------------------------------------------------------- + bool IsCompressed( _In_ DXGI_FORMAT fmt ) + { + switch ( fmt ) + { + case DXGI_FORMAT_BC1_TYPELESS: + case DXGI_FORMAT_BC1_UNORM: + case DXGI_FORMAT_BC1_UNORM_SRGB: + case DXGI_FORMAT_BC2_TYPELESS: + case DXGI_FORMAT_BC2_UNORM: + case DXGI_FORMAT_BC2_UNORM_SRGB: + case DXGI_FORMAT_BC3_TYPELESS: + case DXGI_FORMAT_BC3_UNORM: + case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC4_TYPELESS: + case DXGI_FORMAT_BC4_UNORM: + case DXGI_FORMAT_BC4_SNORM: + case DXGI_FORMAT_BC5_TYPELESS: + case DXGI_FORMAT_BC5_UNORM: + case DXGI_FORMAT_BC5_SNORM: + case DXGI_FORMAT_BC6H_TYPELESS: + case DXGI_FORMAT_BC6H_UF16: + case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_TYPELESS: + case DXGI_FORMAT_BC7_UNORM: + case DXGI_FORMAT_BC7_UNORM_SRGB: + return true; + + default: + return false; + } + } + + + //-------------------------------------------------------------------------------------- + // Get surface information for a particular format + //-------------------------------------------------------------------------------------- + void GetSurfaceInfo( + _In_ size_t width, + _In_ size_t height, + _In_ DXGI_FORMAT fmt, + _Out_opt_ size_t* outNumBytes, + _Out_opt_ size_t* outRowBytes, + _Out_opt_ size_t* outNumRows ) + { + size_t numBytes = 0; + size_t rowBytes = 0; + size_t numRows = 0; + + bool bc = false; + bool packed = false; + bool planar = false; + size_t bpe = 0; + switch (fmt) + { + case DXGI_FORMAT_BC1_TYPELESS: + case DXGI_FORMAT_BC1_UNORM: + case DXGI_FORMAT_BC1_UNORM_SRGB: + case DXGI_FORMAT_BC4_TYPELESS: + case DXGI_FORMAT_BC4_UNORM: + case DXGI_FORMAT_BC4_SNORM: + bc=true; + bpe = 8; + break; + + case DXGI_FORMAT_BC2_TYPELESS: + case DXGI_FORMAT_BC2_UNORM: + case DXGI_FORMAT_BC2_UNORM_SRGB: + case DXGI_FORMAT_BC3_TYPELESS: + case DXGI_FORMAT_BC3_UNORM: + case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC5_TYPELESS: + case DXGI_FORMAT_BC5_UNORM: + case DXGI_FORMAT_BC5_SNORM: + case DXGI_FORMAT_BC6H_TYPELESS: + case DXGI_FORMAT_BC6H_UF16: + case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_TYPELESS: + case DXGI_FORMAT_BC7_UNORM: + case DXGI_FORMAT_BC7_UNORM_SRGB: + bc = true; + bpe = 16; + break; + + case DXGI_FORMAT_R8G8_B8G8_UNORM: + case DXGI_FORMAT_G8R8_G8B8_UNORM: + case DXGI_FORMAT_YUY2: + packed = true; + bpe = 4; + break; + + case DXGI_FORMAT_Y210: + case DXGI_FORMAT_Y216: + packed = true; + bpe = 8; + break; + + case DXGI_FORMAT_NV12: + case DXGI_FORMAT_420_OPAQUE: + planar = true; + bpe = 2; + break; + + case DXGI_FORMAT_P010: + case DXGI_FORMAT_P016: + planar = true; + bpe = 4; + break; + } + + if (bc) + { + size_t numBlocksWide = 0; + if (width > 0) + { + numBlocksWide = std::max<size_t>( 1, (width + 3) / 4 ); + } + size_t numBlocksHigh = 0; + if (height > 0) + { + numBlocksHigh = std::max<size_t>( 1, (height + 3) / 4 ); + } + rowBytes = numBlocksWide * bpe; + numRows = numBlocksHigh; + numBytes = rowBytes * numBlocksHigh; + } + else if (packed) + { + rowBytes = ( ( width + 1 ) >> 1 ) * bpe; + numRows = height; + numBytes = rowBytes * height; + } + else if ( fmt == DXGI_FORMAT_NV11 ) + { + rowBytes = ( ( width + 3 ) >> 2 ) * 4; + numRows = height * 2; // Direct3D makes this simplifying assumption, although it is larger than the 4:1:1 data + numBytes = rowBytes * numRows; + } + else if (planar) + { + rowBytes = ( ( width + 1 ) >> 1 ) * bpe; + numBytes = ( rowBytes * height ) + ( ( rowBytes * height + 1 ) >> 1 ); + numRows = height + ( ( height + 1 ) >> 1 ); + } + else + { + size_t bpp = BitsPerPixel( fmt ); + rowBytes = ( width * bpp + 7 ) / 8; // round up to nearest byte + numRows = height; + numBytes = rowBytes * height; + } + + if (outNumBytes) + { + *outNumBytes = numBytes; + } + if (outRowBytes) + { + *outRowBytes = rowBytes; + } + if (outNumRows) + { + *outNumRows = numRows; + } + } + + + //-------------------------------------------------------------------------------------- + DXGI_FORMAT EnsureNotTypeless( DXGI_FORMAT fmt ) + { + // Assumes UNORM or FLOAT; doesn't use UINT or SINT + switch( fmt ) + { + case DXGI_FORMAT_R32G32B32A32_TYPELESS: return DXGI_FORMAT_R32G32B32A32_FLOAT; + case DXGI_FORMAT_R32G32B32_TYPELESS: return DXGI_FORMAT_R32G32B32_FLOAT; + case DXGI_FORMAT_R16G16B16A16_TYPELESS: return DXGI_FORMAT_R16G16B16A16_UNORM; + case DXGI_FORMAT_R32G32_TYPELESS: return DXGI_FORMAT_R32G32_FLOAT; + case DXGI_FORMAT_R10G10B10A2_TYPELESS: return DXGI_FORMAT_R10G10B10A2_UNORM; + case DXGI_FORMAT_R8G8B8A8_TYPELESS: return DXGI_FORMAT_R8G8B8A8_UNORM; + case DXGI_FORMAT_R16G16_TYPELESS: return DXGI_FORMAT_R16G16_UNORM; + case DXGI_FORMAT_R32_TYPELESS: return DXGI_FORMAT_R32_FLOAT; + case DXGI_FORMAT_R8G8_TYPELESS: return DXGI_FORMAT_R8G8_UNORM; + case DXGI_FORMAT_R16_TYPELESS: return DXGI_FORMAT_R16_UNORM; + case DXGI_FORMAT_R8_TYPELESS: return DXGI_FORMAT_R8_UNORM; + case DXGI_FORMAT_BC1_TYPELESS: return DXGI_FORMAT_BC1_UNORM; + case DXGI_FORMAT_BC2_TYPELESS: return DXGI_FORMAT_BC2_UNORM; + case DXGI_FORMAT_BC3_TYPELESS: return DXGI_FORMAT_BC3_UNORM; + case DXGI_FORMAT_BC4_TYPELESS: return DXGI_FORMAT_BC4_UNORM; + case DXGI_FORMAT_BC5_TYPELESS: return DXGI_FORMAT_BC5_UNORM; + case DXGI_FORMAT_B8G8R8A8_TYPELESS: return DXGI_FORMAT_B8G8R8A8_UNORM; + case DXGI_FORMAT_B8G8R8X8_TYPELESS: return DXGI_FORMAT_B8G8R8X8_UNORM; + case DXGI_FORMAT_BC7_TYPELESS: return DXGI_FORMAT_BC7_UNORM; + default: return fmt; + } + } + + + //-------------------------------------------------------------------------------------- + HRESULT CaptureTexture( + _In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + D3D11_TEXTURE2D_DESC& desc, + ComPtr<ID3D11Texture2D>& pStaging ) + { + if ( !pContext || !pSource ) + return E_INVALIDARG; + + D3D11_RESOURCE_DIMENSION resType = D3D11_RESOURCE_DIMENSION_UNKNOWN; + pSource->GetType( &resType ); + + if ( resType != D3D11_RESOURCE_DIMENSION_TEXTURE2D ) + return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED ); + + ComPtr<ID3D11Texture2D> pTexture; + HRESULT hr = pSource->QueryInterface(IID_PPV_ARGS(pTexture.GetAddressOf())); + if ( FAILED(hr) ) + return hr; + + assert( pTexture ); + + pTexture->GetDesc( &desc ); + + ComPtr<ID3D11Device> d3dDevice; + pContext->GetDevice( d3dDevice.GetAddressOf() ); + + if ( desc.SampleDesc.Count > 1 ) + { + // MSAA content must be resolved before being copied to a staging texture + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + + ComPtr<ID3D11Texture2D> pTemp; + hr = d3dDevice->CreateTexture2D( &desc, 0, pTemp.GetAddressOf() ); + if ( FAILED(hr) ) + return hr; + + assert( pTemp ); + + DXGI_FORMAT fmt = EnsureNotTypeless( desc.Format ); + + UINT support = 0; + hr = d3dDevice->CheckFormatSupport( fmt, &support ); + if ( FAILED(hr) ) + return hr; + + if ( !(support & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RESOLVE) ) + return E_FAIL; + + for( UINT item = 0; item < desc.ArraySize; ++item ) + { + for( UINT level = 0; level < desc.MipLevels; ++level ) + { + UINT index = D3D11CalcSubresource( level, item, desc.MipLevels ); + pContext->ResolveSubresource( pTemp.Get(), index, pSource, index, fmt ); + } + } + + desc.BindFlags = 0; + desc.MiscFlags &= D3D11_RESOURCE_MISC_TEXTURECUBE; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + desc.Usage = D3D11_USAGE_STAGING; + + hr = d3dDevice->CreateTexture2D(&desc, 0, pStaging.ReleaseAndGetAddressOf()); + if ( FAILED(hr) ) + return hr; + + assert( pStaging ); + + pContext->CopyResource( pStaging.Get(), pTemp.Get() ); + } + else if ( (desc.Usage == D3D11_USAGE_STAGING) && (desc.CPUAccessFlags & D3D11_CPU_ACCESS_READ) ) + { + // Handle case where the source is already a staging texture we can use directly + pStaging = pTexture; + } + else + { + // Otherwise, create a staging texture from the non-MSAA source + desc.BindFlags = 0; + desc.MiscFlags &= D3D11_RESOURCE_MISC_TEXTURECUBE; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + desc.Usage = D3D11_USAGE_STAGING; + + hr = d3dDevice->CreateTexture2D(&desc, 0, pStaging.ReleaseAndGetAddressOf()); + if ( FAILED(hr) ) + return hr; + + assert( pStaging ); + + pContext->CopyResource( pStaging.Get(), pSource ); + } + + return S_OK; + } + + //-------------------------------------------------------------------------------------- + bool g_WIC2 = false; + + IWICImagingFactory* _GetWIC() + { + static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT; + + IWICImagingFactory* factory = nullptr; + InitOnceExecuteOnce(&s_initOnce, + [](PINIT_ONCE, PVOID, LPVOID *factory) -> BOOL + { + #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + HRESULT hr = CoCreateInstance( + CLSID_WICImagingFactory2, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory2), + factory + ); + + if ( SUCCEEDED(hr) ) + { + // WIC2 is available on Windows 10, Windows 8.x, and Windows 7 SP1 with KB 2670838 installed + g_WIC2 = true; + return TRUE; + } + else + { + hr = CoCreateInstance( + CLSID_WICImagingFactory1, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory), + factory + ); + return SUCCEEDED(hr) ? TRUE : FALSE; + } + #else + return SUCCEEDED( CoCreateInstance( + CLSID_WICImagingFactory, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory), + factory) ) ? TRUE : FALSE; + #endif + }, nullptr, reinterpret_cast<LPVOID*>(&factory)); + + return factory; + } +} // anonymous namespace + + +//-------------------------------------------------------------------------------------- +HRESULT DirectX::SaveDDSTextureToFile( _In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + _In_z_ const wchar_t* fileName ) +{ + if ( !fileName ) + return E_INVALIDARG; + + D3D11_TEXTURE2D_DESC desc = {}; + ComPtr<ID3D11Texture2D> pStaging; + HRESULT hr = CaptureTexture( pContext, pSource, desc, pStaging ); + if ( FAILED(hr) ) + return hr; + + // Create file +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) + ScopedHandle hFile( safe_handle( CreateFile2( fileName, GENERIC_WRITE | DELETE, 0, CREATE_ALWAYS, nullptr ) ) ); +#else + ScopedHandle hFile( safe_handle( CreateFileW( fileName, GENERIC_WRITE | DELETE, 0, nullptr, CREATE_ALWAYS, 0, nullptr ) ) ); +#endif + if ( !hFile ) + return HRESULT_FROM_WIN32( GetLastError() ); + + auto_delete_file delonfail(hFile.get()); + + // Setup header + const size_t MAX_HEADER_SIZE = sizeof(uint32_t) + sizeof(DDS_HEADER) + sizeof(DDS_HEADER_DXT10); + uint8_t fileHeader[ MAX_HEADER_SIZE ]; + + *reinterpret_cast<uint32_t*>(&fileHeader[0]) = DDS_MAGIC; + + auto header = reinterpret_cast<DDS_HEADER*>( &fileHeader[0] + sizeof(uint32_t) ); + size_t headerSize = sizeof(uint32_t) + sizeof(DDS_HEADER); + memset( header, 0, sizeof(DDS_HEADER) ); + header->size = sizeof( DDS_HEADER ); + header->flags = DDS_HEADER_FLAGS_TEXTURE | DDS_HEADER_FLAGS_MIPMAP; + header->height = desc.Height; + header->width = desc.Width; + header->mipMapCount = 1; + header->caps = DDS_SURFACE_FLAGS_TEXTURE; + + // Try to use a legacy .DDS pixel format for better tools support, otherwise fallback to 'DX10' header extension + DDS_HEADER_DXT10* extHeader = nullptr; + switch( desc.Format ) + { + case DXGI_FORMAT_R8G8B8A8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_A8B8G8R8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R16G16_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_G16R16, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R8G8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_A8L8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R16_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_L16, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_L8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_A8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_A8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R8G8_B8G8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_R8G8_B8G8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_G8R8_G8B8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_G8R8_G8B8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC1_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_DXT1, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC2_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_DXT3, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC3_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_DXT5, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC4_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_BC4_UNORM, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC4_SNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_BC4_SNORM, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC5_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_BC5_UNORM, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_BC5_SNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_BC5_SNORM, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_B5G6R5_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_R5G6B5, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_B5G5R5A1_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_A1R5G5B5, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R8G8_SNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_V8U8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R8G8B8A8_SNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_Q8W8V8U8, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_R16G16_SNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_V16U16, sizeof(DDS_PIXELFORMAT) ); break; + case DXGI_FORMAT_B8G8R8A8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_A8R8G8B8, sizeof(DDS_PIXELFORMAT) ); break; // DXGI 1.1 + case DXGI_FORMAT_B8G8R8X8_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT) ); break; // DXGI 1.1 + case DXGI_FORMAT_YUY2: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_YUY2, sizeof(DDS_PIXELFORMAT) ); break; // DXGI 1.2 + case DXGI_FORMAT_B4G4R4A4_UNORM: memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_A4R4G4B4, sizeof(DDS_PIXELFORMAT) ); break; // DXGI 1.2 + + // Legacy D3DX formats using D3DFMT enum value as FourCC + case DXGI_FORMAT_R32G32B32A32_FLOAT: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 116; break; // D3DFMT_A32B32G32R32F + case DXGI_FORMAT_R16G16B16A16_FLOAT: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 113; break; // D3DFMT_A16B16G16R16F + case DXGI_FORMAT_R16G16B16A16_UNORM: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 36; break; // D3DFMT_A16B16G16R16 + case DXGI_FORMAT_R16G16B16A16_SNORM: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 110; break; // D3DFMT_Q16W16V16U16 + case DXGI_FORMAT_R32G32_FLOAT: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 115; break; // D3DFMT_G32R32F + case DXGI_FORMAT_R16G16_FLOAT: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 112; break; // D3DFMT_G16R16F + case DXGI_FORMAT_R32_FLOAT: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 114; break; // D3DFMT_R32F + case DXGI_FORMAT_R16_FLOAT: header->ddspf.size = sizeof(DDS_PIXELFORMAT); header->ddspf.flags = DDS_FOURCC; header->ddspf.fourCC = 111; break; // D3DFMT_R16F + + case DXGI_FORMAT_AI44: + case DXGI_FORMAT_IA44: + case DXGI_FORMAT_P8: + case DXGI_FORMAT_A8P8: + return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED ); + + default: + memcpy_s( &header->ddspf, sizeof(header->ddspf), &DDSPF_DX10, sizeof(DDS_PIXELFORMAT) ); + + headerSize += sizeof(DDS_HEADER_DXT10); + extHeader = reinterpret_cast<DDS_HEADER_DXT10*>( reinterpret_cast<uint8_t*>(&fileHeader[0]) + sizeof(uint32_t) + sizeof(DDS_HEADER) ); + memset( extHeader, 0, sizeof(DDS_HEADER_DXT10) ); + extHeader->dxgiFormat = desc.Format; + extHeader->resourceDimension = D3D11_RESOURCE_DIMENSION_TEXTURE2D; + extHeader->arraySize = 1; + break; + } + + size_t rowPitch, slicePitch, rowCount; + GetSurfaceInfo( desc.Width, desc.Height, desc.Format, &slicePitch, &rowPitch, &rowCount ); + + if ( IsCompressed( desc.Format ) ) + { + header->flags |= DDS_HEADER_FLAGS_LINEARSIZE; + header->pitchOrLinearSize = static_cast<uint32_t>( slicePitch ); + } + else + { + header->flags |= DDS_HEADER_FLAGS_PITCH; + header->pitchOrLinearSize = static_cast<uint32_t>( rowPitch ); + } + + // Setup pixels + std::unique_ptr<uint8_t[]> pixels( new (std::nothrow) uint8_t[ slicePitch ] ); + if (!pixels) + return E_OUTOFMEMORY; + + D3D11_MAPPED_SUBRESOURCE mapped; + hr = pContext->Map( pStaging.Get(), 0, D3D11_MAP_READ, 0, &mapped ); + if ( FAILED(hr) ) + return hr; + + auto sptr = reinterpret_cast<const uint8_t*>( mapped.pData ); + if ( !sptr ) + { + pContext->Unmap( pStaging.Get(), 0 ); + return E_POINTER; + } + + uint8_t* dptr = pixels.get(); + + size_t msize = std::min<size_t>( rowPitch, mapped.RowPitch ); + for( size_t h = 0; h < rowCount; ++h ) + { + memcpy_s( dptr, rowPitch, sptr, msize ); + sptr += mapped.RowPitch; + dptr += rowPitch; + } + + pContext->Unmap( pStaging.Get(), 0 ); + + // Write header & pixels + DWORD bytesWritten; + if ( !WriteFile( hFile.get(), fileHeader, static_cast<DWORD>( headerSize ), &bytesWritten, nullptr ) ) + return HRESULT_FROM_WIN32( GetLastError() ); + + if ( bytesWritten != headerSize ) + return E_FAIL; + + if ( !WriteFile( hFile.get(), pixels.get(), static_cast<DWORD>( slicePitch ), &bytesWritten, nullptr ) ) + return HRESULT_FROM_WIN32( GetLastError() ); + + if ( bytesWritten != slicePitch ) + return E_FAIL; + + delonfail.clear(); + + return S_OK; +} + +//-------------------------------------------------------------------------------------- +HRESULT DirectX::SaveWICTextureToFile( _In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + _In_ REFGUID guidContainerFormat, + _In_z_ const wchar_t* fileName, + _In_opt_ const GUID* targetFormat, + _In_opt_ std::function<void(IPropertyBag2*)> setCustomProps ) +{ + if ( !fileName ) + return E_INVALIDARG; + + D3D11_TEXTURE2D_DESC desc = {}; + ComPtr<ID3D11Texture2D> pStaging; + HRESULT hr = CaptureTexture( pContext, pSource, desc, pStaging ); + if ( FAILED(hr) ) + return hr; + + // Determine source format's WIC equivalent + WICPixelFormatGUID pfGuid; + bool sRGB = false; + switch ( desc.Format ) + { + case DXGI_FORMAT_R32G32B32A32_FLOAT: pfGuid = GUID_WICPixelFormat128bppRGBAFloat; break; + case DXGI_FORMAT_R16G16B16A16_FLOAT: pfGuid = GUID_WICPixelFormat64bppRGBAHalf; break; + case DXGI_FORMAT_R16G16B16A16_UNORM: pfGuid = GUID_WICPixelFormat64bppRGBA; break; + case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102XR; break; // DXGI 1.1 + case DXGI_FORMAT_R10G10B10A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102; break; + case DXGI_FORMAT_B5G5R5A1_UNORM: pfGuid = GUID_WICPixelFormat16bppBGRA5551; break; + case DXGI_FORMAT_B5G6R5_UNORM: pfGuid = GUID_WICPixelFormat16bppBGR565; break; + case DXGI_FORMAT_R32_FLOAT: pfGuid = GUID_WICPixelFormat32bppGrayFloat; break; + case DXGI_FORMAT_R16_FLOAT: pfGuid = GUID_WICPixelFormat16bppGrayHalf; break; + case DXGI_FORMAT_R16_UNORM: pfGuid = GUID_WICPixelFormat16bppGray; break; + case DXGI_FORMAT_R8_UNORM: pfGuid = GUID_WICPixelFormat8bppGray; break; + case DXGI_FORMAT_A8_UNORM: pfGuid = GUID_WICPixelFormat8bppAlpha; break; + + case DXGI_FORMAT_R8G8B8A8_UNORM: + pfGuid = GUID_WICPixelFormat32bppRGBA; + break; + + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: + pfGuid = GUID_WICPixelFormat32bppRGBA; + sRGB = true; + break; + + case DXGI_FORMAT_B8G8R8A8_UNORM: // DXGI 1.1 + pfGuid = GUID_WICPixelFormat32bppBGRA; + break; + + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: // DXGI 1.1 + pfGuid = GUID_WICPixelFormat32bppBGRA; + sRGB = true; + break; + + case DXGI_FORMAT_B8G8R8X8_UNORM: // DXGI 1.1 + pfGuid = GUID_WICPixelFormat32bppBGR; + break; + + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: // DXGI 1.1 + pfGuid = GUID_WICPixelFormat32bppBGR; + sRGB = true; + break; + + default: + return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED ); + } + + auto pWIC = _GetWIC(); + if ( !pWIC ) + return E_NOINTERFACE; + + ComPtr<IWICStream> stream; + hr = pWIC->CreateStream( stream.GetAddressOf() ); + if ( FAILED(hr) ) + return hr; + + hr = stream->InitializeFromFilename( fileName, GENERIC_WRITE ); + if ( FAILED(hr) ) + return hr; + + auto_delete_file_wic delonfail(stream, fileName); + + ComPtr<IWICBitmapEncoder> encoder; + hr = pWIC->CreateEncoder( guidContainerFormat, 0, encoder.GetAddressOf() ); + if ( FAILED(hr) ) + return hr; + + hr = encoder->Initialize( stream.Get(), WICBitmapEncoderNoCache ); + if ( FAILED(hr) ) + return hr; + + ComPtr<IWICBitmapFrameEncode> frame; + ComPtr<IPropertyBag2> props; + hr = encoder->CreateNewFrame( frame.GetAddressOf(), props.GetAddressOf() ); + if ( FAILED(hr) ) + return hr; + + if ( targetFormat && memcmp( &guidContainerFormat, &GUID_ContainerFormatBmp, sizeof(WICPixelFormatGUID) ) == 0 && g_WIC2 ) + { + // Opt-in to the WIC2 support for writing 32-bit Windows BMP files with an alpha channel + PROPBAG2 option = {}; + option.pstrName = const_cast<wchar_t*>(L"EnableV5Header32bppBGRA"); + + VARIANT varValue; + varValue.vt = VT_BOOL; + varValue.boolVal = VARIANT_TRUE; + (void)props->Write( 1, &option, &varValue ); + } + + if ( setCustomProps ) + { + setCustomProps( props.Get() ); + } + + hr = frame->Initialize( props.Get() ); + if ( FAILED(hr) ) + return hr; + + hr = frame->SetSize( desc.Width , desc.Height ); + if ( FAILED(hr) ) + return hr; + + hr = frame->SetResolution( 72, 72 ); + if ( FAILED(hr) ) + return hr; + + // Pick a target format + WICPixelFormatGUID targetGuid; + if ( targetFormat ) + { + targetGuid = *targetFormat; + } + else + { + // Screenshots don�t typically include the alpha channel of the render target + switch ( desc.Format ) + { +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_R16G16B16A16_FLOAT: + if ( g_WIC2 ) + { + targetGuid = GUID_WICPixelFormat96bppRGBFloat; + } + else + { + targetGuid = GUID_WICPixelFormat24bppBGR; + } + break; +#endif + + case DXGI_FORMAT_R16G16B16A16_UNORM: targetGuid = GUID_WICPixelFormat48bppBGR; break; + case DXGI_FORMAT_B5G5R5A1_UNORM: targetGuid = GUID_WICPixelFormat16bppBGR555; break; + case DXGI_FORMAT_B5G6R5_UNORM: targetGuid = GUID_WICPixelFormat16bppBGR565; break; + + case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R16_FLOAT: + case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_A8_UNORM: + targetGuid = GUID_WICPixelFormat8bppGray; + break; + + default: + targetGuid = GUID_WICPixelFormat24bppBGR; + break; + } + } + + hr = frame->SetPixelFormat( &targetGuid ); + if ( FAILED(hr) ) + return hr; + + if ( targetFormat && memcmp( targetFormat, &targetGuid, sizeof(WICPixelFormatGUID) ) != 0 ) + { + // Requested output pixel format is not supported by the WIC codec + return E_FAIL; + } + + // Encode WIC metadata + ComPtr<IWICMetadataQueryWriter> metawriter; + if ( SUCCEEDED( frame->GetMetadataQueryWriter( metawriter.GetAddressOf() ) ) ) + { + PROPVARIANT value; + PropVariantInit( &value ); + + value.vt = VT_LPSTR; + value.pszVal = const_cast<char*>("DirectXTK"); + + if ( memcmp( &guidContainerFormat, &GUID_ContainerFormatPng, sizeof(GUID) ) == 0 ) + { + // Set Software name + (void)metawriter->SetMetadataByName( L"/tEXt/{str=Software}", &value ); + + // Set sRGB chunk + if (sRGB) + { + value.vt = VT_UI1; + value.bVal = 0; + (void)metawriter->SetMetadataByName(L"/sRGB/RenderingIntent", &value); + } + else + { + // add gAMA chunk with gamma 1.0 + value.vt = VT_UI4; + value.uintVal = 100000; // gama value * 100,000 -- i.e. gamma 1.0 + (void)metawriter->SetMetadataByName(L"/gAMA/ImageGamma", &value); + + // remove sRGB chunk which is added by default. + (void)metawriter->RemoveMetadataByName(L"/sRGB/RenderingIntent"); + } + } + else + { + // Set Software name + (void)metawriter->SetMetadataByName( L"System.ApplicationName", &value ); + + if ( sRGB ) + { + // Set EXIF Colorspace of sRGB + value.vt = VT_UI2; + value.uiVal = 1; + (void)metawriter->SetMetadataByName( L"System.Image.ColorSpace", &value ); + } + } + } + + D3D11_MAPPED_SUBRESOURCE mapped; + hr = pContext->Map( pStaging.Get(), 0, D3D11_MAP_READ, 0, &mapped ); + if ( FAILED(hr) ) + return hr; + + if ( memcmp( &targetGuid, &pfGuid, sizeof(WICPixelFormatGUID) ) != 0 ) + { + // Conversion required to write + ComPtr<IWICBitmap> source; + hr = pWIC->CreateBitmapFromMemory( desc.Width, desc.Height, pfGuid, + mapped.RowPitch, mapped.RowPitch * desc.Height, + reinterpret_cast<BYTE*>( mapped.pData ), source.GetAddressOf() ); + if ( FAILED(hr) ) + { + pContext->Unmap( pStaging.Get(), 0 ); + return hr; + } + + ComPtr<IWICFormatConverter> FC; + hr = pWIC->CreateFormatConverter( FC.GetAddressOf() ); + if ( FAILED(hr) ) + { + pContext->Unmap( pStaging.Get(), 0 ); + return hr; + } + + BOOL canConvert = FALSE; + hr = FC->CanConvert( pfGuid, targetGuid, &canConvert ); + if ( FAILED(hr) || !canConvert ) + { + return E_UNEXPECTED; + } + + hr = FC->Initialize( source.Get(), targetGuid, WICBitmapDitherTypeNone, nullptr, 0, WICBitmapPaletteTypeMedianCut ); + if ( FAILED(hr) ) + { + pContext->Unmap( pStaging.Get(), 0 ); + return hr; + } + + WICRect rect = { 0, 0, static_cast<INT>( desc.Width ), static_cast<INT>( desc.Height ) }; + hr = frame->WriteSource( FC.Get(), &rect ); + if ( FAILED(hr) ) + { + pContext->Unmap( pStaging.Get(), 0 ); + return hr; + } + } + else + { + // No conversion required + hr = frame->WritePixels( desc.Height, mapped.RowPitch, mapped.RowPitch * desc.Height, reinterpret_cast<BYTE*>( mapped.pData ) ); + if ( FAILED(hr) ) + return hr; + } + + pContext->Unmap( pStaging.Get(), 0 ); + + hr = frame->Commit(); + if ( FAILED(hr) ) + return hr; + + hr = encoder->Commit(); + if ( FAILED(hr) ) + return hr; + + delonfail.clear(); + + return S_OK; +} diff --git a/samples/DX_APIUsage/DXUT/Core/ScreenGrab.h b/samples/DX_APIUsage/DXUT/Core/ScreenGrab.h new file mode 100644 index 0000000..1f18539 --- /dev/null +++ b/samples/DX_APIUsage/DXUT/Core/ScreenGrab.h @@ -0,0 +1,39 @@ +//-------------------------------------------------------------------------------------- +// File: ScreenGrab.h +// +// Function for capturing a 2D texture and saving it to a file (aka a 'screenshot' +// when used on a Direct3D 11 Render Target). +// +// Note these functions are useful as a light-weight runtime screen grabber. For +// full-featured texture capture, DDS writer, and texture processing pipeline, +// see the 'Texconv' sample and the 'DirectXTex' library. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=248926 +// http://go.microsoft.com/fwlink/?LinkId=248929 +//-------------------------------------------------------------------------------------- + +#pragma once + +#include <d3d11_1.h> + +#include <ocidl.h> +#include <stdint.h> +#include <functional> + + +namespace DirectX +{ + HRESULT SaveDDSTextureToFile( _In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + _In_z_ const wchar_t* fileName ); + + HRESULT SaveWICTextureToFile( _In_ ID3D11DeviceContext* pContext, + _In_ ID3D11Resource* pSource, + _In_ REFGUID guidContainerFormat, + _In_z_ const wchar_t* fileName, + _In_opt_ const GUID* targetFormat = nullptr, + _In_opt_ std::function<void(IPropertyBag2*)> setCustomProps = nullptr ); +}
\ No newline at end of file diff --git a/samples/DX_APIUsage/DXUT/Core/WICTextureLoader.cpp b/samples/DX_APIUsage/DXUT/Core/WICTextureLoader.cpp new file mode 100644 index 0000000..a5960f2 --- /dev/null +++ b/samples/DX_APIUsage/DXUT/Core/WICTextureLoader.cpp @@ -0,0 +1,932 @@ +//-------------------------------------------------------------------------------------- +// File: WICTextureLoader.cpp +// +// Function for loading a WIC image and creating a Direct3D runtime texture for it +// (auto-generating mipmaps if possible) +// +// Note: Assumes application has already called CoInitializeEx +// +// Warning: CreateWICTexture* functions are not thread-safe if given a d3dContext instance for +// auto-gen mipmap support. +// +// Note these functions are useful for images created as simple 2D textures. For +// more complex resources, DDSTextureLoader is an excellent light-weight runtime loader. +// For a full-featured DDS file reader, writer, and texture processing pipeline see +// the 'Texconv' sample and the 'DirectXTex' library. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=248926 +// http://go.microsoft.com/fwlink/?LinkId=248929 +//-------------------------------------------------------------------------------------- + +#include "dxut.h" + +// We could load multi-frame images (TIFF/GIF) into a texture array. +// For now, we just load the first frame (note: DirectXTex supports multi-frame images) + +#include "WICTextureLoader.h" + +#include <dxgiformat.h> +#include <assert.h> + +#include <wincodec.h> + +#include <wrl\client.h> + +#include <algorithm> +#include <memory> + +#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) +#pragma comment(lib,"dxguid.lib") +#endif + +using namespace DirectX; +using Microsoft::WRL::ComPtr; + +namespace +{ + //-------------------------------------------------------------------------------------- + template<UINT TNameLength> + inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_ const char(&name)[TNameLength]) + { +#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) + resource->SetPrivateData(WKPDID_D3DDebugObjectName, TNameLength - 1, name); +#else + UNREFERENCED_PARAMETER(resource); + UNREFERENCED_PARAMETER(name); +#endif + } + + //------------------------------------------------------------------------------------- + // WIC Pixel Format Translation Data + //------------------------------------------------------------------------------------- + struct WICTranslate + { + GUID wic; + DXGI_FORMAT format; + }; + + const WICTranslate g_WICFormats[] = + { + { GUID_WICPixelFormat128bppRGBAFloat, DXGI_FORMAT_R32G32B32A32_FLOAT }, + + { GUID_WICPixelFormat64bppRGBAHalf, DXGI_FORMAT_R16G16B16A16_FLOAT }, + { GUID_WICPixelFormat64bppRGBA, DXGI_FORMAT_R16G16B16A16_UNORM }, + + { GUID_WICPixelFormat32bppRGBA, DXGI_FORMAT_R8G8B8A8_UNORM }, + { GUID_WICPixelFormat32bppBGRA, DXGI_FORMAT_B8G8R8A8_UNORM }, // DXGI 1.1 + { GUID_WICPixelFormat32bppBGR, DXGI_FORMAT_B8G8R8X8_UNORM }, // DXGI 1.1 + + { GUID_WICPixelFormat32bppRGBA1010102XR, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM }, // DXGI 1.1 + { GUID_WICPixelFormat32bppRGBA1010102, DXGI_FORMAT_R10G10B10A2_UNORM }, + + { GUID_WICPixelFormat16bppBGRA5551, DXGI_FORMAT_B5G5R5A1_UNORM }, + { GUID_WICPixelFormat16bppBGR565, DXGI_FORMAT_B5G6R5_UNORM }, + + { GUID_WICPixelFormat32bppGrayFloat, DXGI_FORMAT_R32_FLOAT }, + { GUID_WICPixelFormat16bppGrayHalf, DXGI_FORMAT_R16_FLOAT }, + { GUID_WICPixelFormat16bppGray, DXGI_FORMAT_R16_UNORM }, + { GUID_WICPixelFormat8bppGray, DXGI_FORMAT_R8_UNORM }, + + { GUID_WICPixelFormat8bppAlpha, DXGI_FORMAT_A8_UNORM }, + }; + + //------------------------------------------------------------------------------------- + // WIC Pixel Format nearest conversion table + //------------------------------------------------------------------------------------- + + struct WICConvert + { + GUID source; + GUID target; + }; + + const WICConvert g_WICConvert[] = + { + // Note target GUID in this conversion table must be one of those directly supported formats (above). + + { GUID_WICPixelFormatBlackWhite, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM + + { GUID_WICPixelFormat1bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat2bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat4bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat8bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + + { GUID_WICPixelFormat2bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM + { GUID_WICPixelFormat4bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM + + { GUID_WICPixelFormat16bppGrayFixedPoint, GUID_WICPixelFormat16bppGrayHalf }, // DXGI_FORMAT_R16_FLOAT + { GUID_WICPixelFormat32bppGrayFixedPoint, GUID_WICPixelFormat32bppGrayFloat }, // DXGI_FORMAT_R32_FLOAT + + { GUID_WICPixelFormat16bppBGR555, GUID_WICPixelFormat16bppBGRA5551 }, // DXGI_FORMAT_B5G5R5A1_UNORM + + { GUID_WICPixelFormat32bppBGR101010, GUID_WICPixelFormat32bppRGBA1010102 }, // DXGI_FORMAT_R10G10B10A2_UNORM + + { GUID_WICPixelFormat24bppBGR, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat24bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat32bppPBGRA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat32bppPRGBA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + + { GUID_WICPixelFormat48bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat48bppBGR, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppPRGBA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppPBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + + { GUID_WICPixelFormat48bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat48bppBGRFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppRGBAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppBGRAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat48bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + + { GUID_WICPixelFormat128bppPRGBAFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppRGBFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppRGBAFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppRGBFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat32bppRGBE, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + + { GUID_WICPixelFormat32bppCMYK, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat64bppCMYK, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat40bppCMYKAlpha, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat80bppCMYKAlpha, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + + #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + { GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat64bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppPRGBAHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + #endif + + // We don't support n-channel formats + }; + + bool g_WIC2 = false; + + //-------------------------------------------------------------------------------------- + IWICImagingFactory* _GetWIC() + { + static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT; + + IWICImagingFactory* factory = nullptr; + InitOnceExecuteOnce(&s_initOnce, + [](PINIT_ONCE, PVOID, PVOID *factory) -> BOOL + { +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + HRESULT hr = CoCreateInstance( + CLSID_WICImagingFactory2, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory2), + factory + ); + + if (SUCCEEDED(hr)) + { + // WIC2 is available on Windows 10, Windows 8.x, and Windows 7 SP1 with KB 2670838 installed + g_WIC2 = true; + return TRUE; + } + else + { + hr = CoCreateInstance( + CLSID_WICImagingFactory1, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory), + factory + ); + return SUCCEEDED(hr) ? TRUE : FALSE; + } +#else + return SUCCEEDED(CoCreateInstance( + CLSID_WICImagingFactory, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory), + factory)) ? TRUE : FALSE; +#endif + }, nullptr, reinterpret_cast<LPVOID*>(&factory)); + + return factory; + } + + //--------------------------------------------------------------------------------- + DXGI_FORMAT _WICToDXGI(const GUID& guid) + { + for (size_t i = 0; i < _countof(g_WICFormats); ++i) + { + if (memcmp(&g_WICFormats[i].wic, &guid, sizeof(GUID)) == 0) + return g_WICFormats[i].format; + } + +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + if (g_WIC2) + { + if (memcmp(&GUID_WICPixelFormat96bppRGBFloat, &guid, sizeof(GUID)) == 0) + return DXGI_FORMAT_R32G32B32_FLOAT; + } +#endif + + return DXGI_FORMAT_UNKNOWN; + } + + //--------------------------------------------------------------------------------- + size_t _WICBitsPerPixel(REFGUID targetGuid) + { + auto pWIC = _GetWIC(); + if (!pWIC) + return 0; + + ComPtr<IWICComponentInfo> cinfo; + if (FAILED(pWIC->CreateComponentInfo(targetGuid, cinfo.GetAddressOf()))) + return 0; + + WICComponentType type; + if (FAILED(cinfo->GetComponentType(&type))) + return 0; + + if (type != WICPixelFormat) + return 0; + + ComPtr<IWICPixelFormatInfo> pfinfo; + if (FAILED(cinfo.As(&pfinfo))) + return 0; + + UINT bpp; + if (FAILED(pfinfo->GetBitsPerPixel(&bpp))) + return 0; + + return bpp; + } + + + //-------------------------------------------------------------------------------------- + DXGI_FORMAT MakeSRGB(_In_ DXGI_FORMAT format) + { + switch (format) + { + case DXGI_FORMAT_R8G8B8A8_UNORM: + return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + + case DXGI_FORMAT_BC1_UNORM: + return DXGI_FORMAT_BC1_UNORM_SRGB; + + case DXGI_FORMAT_BC2_UNORM: + return DXGI_FORMAT_BC2_UNORM_SRGB; + + case DXGI_FORMAT_BC3_UNORM: + return DXGI_FORMAT_BC3_UNORM_SRGB; + + case DXGI_FORMAT_B8G8R8A8_UNORM: + return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; + + case DXGI_FORMAT_B8G8R8X8_UNORM: + return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; + + case DXGI_FORMAT_BC7_UNORM: + return DXGI_FORMAT_BC7_UNORM_SRGB; + + default: + return format; + } + } + + + //--------------------------------------------------------------------------------- + HRESULT CreateTextureFromWIC(_In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _In_ IWICBitmapFrameDecode *frame, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ unsigned int loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView) + { + UINT width, height; + HRESULT hr = frame->GetSize(&width, &height); + if (FAILED(hr)) + return hr; + + assert(width > 0 && height > 0); + + if (!maxsize) + { + // This is a bit conservative because the hardware could support larger textures than + // the Feature Level defined minimums, but doing it this way is much easier and more + // performant for WIC than the 'fail and retry' model used by DDSTextureLoader + + switch (d3dDevice->GetFeatureLevel()) + { + case D3D_FEATURE_LEVEL_9_1: + case D3D_FEATURE_LEVEL_9_2: + maxsize = 2048 /*D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + break; + + case D3D_FEATURE_LEVEL_9_3: + maxsize = 4096 /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + break; + + case D3D_FEATURE_LEVEL_10_0: + case D3D_FEATURE_LEVEL_10_1: + maxsize = 8192 /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + break; + + default: + maxsize = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; + break; + } + } + + assert(maxsize > 0); + + UINT twidth, theight; + if (width > maxsize || height > maxsize) + { + float ar = static_cast<float>(height) / static_cast<float>(width); + if (width > height) + { + twidth = static_cast<UINT>(maxsize); + theight = std::max<UINT>(1, static_cast<UINT>(static_cast<float>(maxsize) * ar)); + } + else + { + theight = static_cast<UINT>(maxsize); + twidth = std::max<UINT>(1, static_cast<UINT>(static_cast<float>(maxsize) / ar)); + } + assert(twidth <= maxsize && theight <= maxsize); + } + else + { + twidth = width; + theight = height; + } + + // Determine format + WICPixelFormatGUID pixelFormat; + hr = frame->GetPixelFormat(&pixelFormat); + if (FAILED(hr)) + return hr; + + WICPixelFormatGUID convertGUID; + memcpy(&convertGUID, &pixelFormat, sizeof(WICPixelFormatGUID)); + + size_t bpp = 0; + + DXGI_FORMAT format = _WICToDXGI(pixelFormat); + if (format == DXGI_FORMAT_UNKNOWN) + { + if (memcmp(&GUID_WICPixelFormat96bppRGBFixedPoint, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0) + { +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + if (g_WIC2) + { + memcpy(&convertGUID, &GUID_WICPixelFormat96bppRGBFloat, sizeof(WICPixelFormatGUID)); + format = DXGI_FORMAT_R32G32B32_FLOAT; + bpp = 96; + } + else +#endif + { + memcpy(&convertGUID, &GUID_WICPixelFormat128bppRGBAFloat, sizeof(WICPixelFormatGUID)); + format = DXGI_FORMAT_R32G32B32A32_FLOAT; + bpp = 128; + } + } + else + { + for (size_t i = 0; i < _countof(g_WICConvert); ++i) + { + if (memcmp(&g_WICConvert[i].source, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0) + { + memcpy(&convertGUID, &g_WICConvert[i].target, sizeof(WICPixelFormatGUID)); + + format = _WICToDXGI(g_WICConvert[i].target); + assert(format != DXGI_FORMAT_UNKNOWN); + bpp = _WICBitsPerPixel(convertGUID); + break; + } + } + } + + if (format == DXGI_FORMAT_UNKNOWN) + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } + else + { + bpp = _WICBitsPerPixel(pixelFormat); + } + +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + if ((format == DXGI_FORMAT_R32G32B32_FLOAT) && d3dContext != 0 && textureView != 0) + { + // Special case test for optional device support for autogen mipchains for R32G32B32_FLOAT + UINT fmtSupport = 0; + hr = d3dDevice->CheckFormatSupport(DXGI_FORMAT_R32G32B32_FLOAT, &fmtSupport); + if (FAILED(hr) || !(fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) + { + // Use R32G32B32A32_FLOAT instead which is required for Feature Level 10.0 and up + memcpy(&convertGUID, &GUID_WICPixelFormat128bppRGBAFloat, sizeof(WICPixelFormatGUID)); + format = DXGI_FORMAT_R32G32B32A32_FLOAT; + bpp = 128; + } + } +#endif + + if (!bpp) + return E_FAIL; + + // Handle sRGB formats + if (loadFlags & WIC_LOADER_FORCE_SRGB) + { + format = MakeSRGB(format); + } + else if (!(loadFlags & WIC_LOADER_IGNORE_SRGB)) + { + ComPtr<IWICMetadataQueryReader> metareader; + if (SUCCEEDED(frame->GetMetadataQueryReader(metareader.GetAddressOf()))) + { + GUID containerFormat; + if (SUCCEEDED(metareader->GetContainerFormat(&containerFormat))) + { + // Check for sRGB colorspace metadata + bool sRGB = false; + + PROPVARIANT value; + PropVariantInit(&value); + + if (memcmp(&containerFormat, &GUID_ContainerFormatPng, sizeof(GUID)) == 0) + { + // Check for sRGB chunk + if (SUCCEEDED(metareader->GetMetadataByName(L"/sRGB/RenderingIntent", &value)) && value.vt == VT_UI1) + { + sRGB = true; + } + } + else if (SUCCEEDED(metareader->GetMetadataByName(L"System.Image.ColorSpace", &value)) && value.vt == VT_UI2 && value.uiVal == 1) + { + sRGB = true; + } + + (void)PropVariantClear(&value); + + if (sRGB) + format = MakeSRGB(format); + } + } + } + + // Verify our target format is supported by the current device + // (handles WDDM 1.0 or WDDM 1.1 device driver cases as well as DirectX 11.0 Runtime without 16bpp format support) + UINT support = 0; + hr = d3dDevice->CheckFormatSupport(format, &support); + if (FAILED(hr) || !(support & D3D11_FORMAT_SUPPORT_TEXTURE2D)) + { + // Fallback to RGBA 32-bit format which is supported by all devices + memcpy(&convertGUID, &GUID_WICPixelFormat32bppRGBA, sizeof(WICPixelFormatGUID)); + format = DXGI_FORMAT_R8G8B8A8_UNORM; + bpp = 32; + } + + // Allocate temporary memory for image + size_t rowPitch = (twidth * bpp + 7) / 8; + size_t imageSize = rowPitch * theight; + + std::unique_ptr<uint8_t[]> temp(new (std::nothrow) uint8_t[imageSize]); + if (!temp) + return E_OUTOFMEMORY; + + // Load image data + if (memcmp(&convertGUID, &pixelFormat, sizeof(GUID)) == 0 + && twidth == width + && theight == height) + { + // No format conversion or resize needed + hr = frame->CopyPixels(0, static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize), temp.get()); + if (FAILED(hr)) + return hr; + } + else if (twidth != width || theight != height) + { + // Resize + auto pWIC = _GetWIC(); + if (!pWIC) + return E_NOINTERFACE; + + ComPtr<IWICBitmapScaler> scaler; + hr = pWIC->CreateBitmapScaler(scaler.GetAddressOf()); + if (FAILED(hr)) + return hr; + + hr = scaler->Initialize(frame, twidth, theight, WICBitmapInterpolationModeFant); + if (FAILED(hr)) + return hr; + + WICPixelFormatGUID pfScaler; + hr = scaler->GetPixelFormat(&pfScaler); + if (FAILED(hr)) + return hr; + + if (memcmp(&convertGUID, &pfScaler, sizeof(GUID)) == 0) + { + // No format conversion needed + hr = scaler->CopyPixels(0, static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize), temp.get()); + if (FAILED(hr)) + return hr; + } + else + { + ComPtr<IWICFormatConverter> FC; + hr = pWIC->CreateFormatConverter(FC.GetAddressOf()); + if (FAILED(hr)) + return hr; + + BOOL canConvert = FALSE; + hr = FC->CanConvert(pfScaler, convertGUID, &canConvert); + if (FAILED(hr) || !canConvert) + { + return E_UNEXPECTED; + } + + hr = FC->Initialize(scaler.Get(), convertGUID, WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut); + if (FAILED(hr)) + return hr; + + hr = FC->CopyPixels(0, static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize), temp.get()); + if (FAILED(hr)) + return hr; + } + } + else + { + // Format conversion but no resize + auto pWIC = _GetWIC(); + if (!pWIC) + return E_NOINTERFACE; + + ComPtr<IWICFormatConverter> FC; + hr = pWIC->CreateFormatConverter(FC.GetAddressOf()); + if (FAILED(hr)) + return hr; + + BOOL canConvert = FALSE; + hr = FC->CanConvert(pixelFormat, convertGUID, &canConvert); + if (FAILED(hr) || !canConvert) + { + return E_UNEXPECTED; + } + + hr = FC->Initialize(frame, convertGUID, WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut); + if (FAILED(hr)) + return hr; + + hr = FC->CopyPixels(0, static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize), temp.get()); + if (FAILED(hr)) + return hr; + } + + // See if format is supported for auto-gen mipmaps (varies by feature level) + bool autogen = false; + if (d3dContext != 0 && textureView != 0) // Must have context and shader-view to auto generate mipmaps + { + UINT fmtSupport = 0; + hr = d3dDevice->CheckFormatSupport(format, &fmtSupport); + if (SUCCEEDED(hr) && (fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) + { + autogen = true; + } + } + + // Create texture + D3D11_TEXTURE2D_DESC desc; + desc.Width = twidth; + desc.Height = theight; + desc.MipLevels = (autogen) ? 0 : 1; + desc.ArraySize = 1; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Usage = usage; + desc.CPUAccessFlags = cpuAccessFlags; + + if (autogen) + { + desc.BindFlags = bindFlags | D3D11_BIND_RENDER_TARGET; + desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_GENERATE_MIPS; + } + else + { + desc.BindFlags = bindFlags; + desc.MiscFlags = miscFlags; + } + + D3D11_SUBRESOURCE_DATA initData; + initData.pSysMem = temp.get(); + initData.SysMemPitch = static_cast<UINT>(rowPitch); + initData.SysMemSlicePitch = static_cast<UINT>(imageSize); + + ID3D11Texture2D* tex = nullptr; + hr = d3dDevice->CreateTexture2D(&desc, (autogen) ? nullptr : &initData, &tex); + if (SUCCEEDED(hr) && tex != 0) + { + if (textureView != 0) + { + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; + SRVDesc.Format = desc.Format; + + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + SRVDesc.Texture2D.MipLevels = (autogen) ? -1 : 1; + + hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); + if (FAILED(hr)) + { + tex->Release(); + return hr; + } + + if (autogen) + { + assert(d3dContext != 0); + d3dContext->UpdateSubresource(tex, 0, nullptr, temp.get(), static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize)); + d3dContext->GenerateMips(*textureView); + } + } + + if (texture != 0) + { + *texture = tex; + } + else + { + SetDebugObjectName(tex, "WICTextureLoader"); + tex->Release(); + } + } + + return hr; + } +} // anonymous namespace + +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromMemory(ID3D11Device* d3dDevice, + const uint8_t* wicData, + size_t wicDataSize, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize) +{ + return CreateWICTextureFromMemoryEx(d3dDevice, nullptr, wicData, wicDataSize, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, + texture, textureView); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromMemory(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const uint8_t* wicData, + size_t wicDataSize, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize) +{ + return CreateWICTextureFromMemoryEx(d3dDevice, d3dContext, wicData, wicDataSize, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, + texture, textureView); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromMemoryEx(ID3D11Device* d3dDevice, + const uint8_t* wicData, + size_t wicDataSize, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + unsigned int loadFlags, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView) +{ + return CreateWICTextureFromMemoryEx(d3dDevice, nullptr, wicData, wicDataSize, maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, + texture, textureView); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromMemoryEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const uint8_t* wicData, + size_t wicDataSize, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + unsigned int loadFlags, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView) +{ + if (texture) + { + *texture = nullptr; + } + if (textureView) + { + *textureView = nullptr; + } + + if (!d3dDevice || !wicData || (!texture && !textureView)) + return E_INVALIDARG; + + if (!wicDataSize) + return E_FAIL; + + if (wicDataSize > UINT32_MAX) + return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); + + auto pWIC = _GetWIC(); + if (!pWIC) + return E_NOINTERFACE; + + // Create input stream for memory + ComPtr<IWICStream> stream; + HRESULT hr = pWIC->CreateStream(stream.GetAddressOf()); + if (FAILED(hr)) + return hr; + + hr = stream->InitializeFromMemory(const_cast<uint8_t*>(wicData), static_cast<DWORD>(wicDataSize)); + if (FAILED(hr)) + return hr; + + // Initialize WIC + ComPtr<IWICBitmapDecoder> decoder; + hr = pWIC->CreateDecoderFromStream(stream.Get(), 0, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()); + if (FAILED(hr)) + return hr; + + ComPtr<IWICBitmapFrameDecode> frame; + hr = decoder->GetFrame(0, frame.GetAddressOf()); + if (FAILED(hr)) + return hr; + + hr = CreateTextureFromWIC(d3dDevice, d3dContext, frame.Get(), maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, + texture, textureView); + if (FAILED(hr)) + return hr; + + if (texture != 0 && *texture != 0) + { + SetDebugObjectName(*texture, "WICTextureLoader"); + } + + if (textureView != 0 && *textureView != 0) + { + SetDebugObjectName(*textureView, "WICTextureLoader"); + } + + return hr; +} + +//-------------------------------------------------------------------------------------- +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromFile(ID3D11Device* d3dDevice, + const wchar_t* fileName, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize) +{ + return CreateWICTextureFromFileEx(d3dDevice, nullptr, fileName, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, + texture, textureView); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromFile(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const wchar_t* fileName, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView, + size_t maxsize) +{ + return CreateWICTextureFromFileEx(d3dDevice, d3dContext, fileName, maxsize, + D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, + texture, textureView); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromFileEx(ID3D11Device* d3dDevice, + const wchar_t* fileName, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + unsigned int loadFlags, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView) +{ + return CreateWICTextureFromFileEx(d3dDevice, nullptr, fileName, maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, + texture, textureView); +} + +_Use_decl_annotations_ +HRESULT DirectX::CreateWICTextureFromFileEx(ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const wchar_t* fileName, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + unsigned int loadFlags, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView) +{ + if (texture) + { + *texture = nullptr; + } + if (textureView) + { + *textureView = nullptr; + } + + if (!d3dDevice || !fileName || (!texture && !textureView)) + return E_INVALIDARG; + + auto pWIC = _GetWIC(); + if (!pWIC) + return E_NOINTERFACE; + + // Initialize WIC + ComPtr<IWICBitmapDecoder> decoder; + HRESULT hr = pWIC->CreateDecoderFromFilename(fileName, 0, GENERIC_READ, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()); + if (FAILED(hr)) + return hr; + + ComPtr<IWICBitmapFrameDecode> frame; + hr = decoder->GetFrame(0, frame.GetAddressOf()); + if (FAILED(hr)) + return hr; + + hr = CreateTextureFromWIC(d3dDevice, d3dContext, frame.Get(), maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, + texture, textureView); + +#if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) + if (SUCCEEDED(hr)) + { + if (texture != 0 || textureView != 0) + { + char strFileA[MAX_PATH]; + int result = WideCharToMultiByte(CP_ACP, + WC_NO_BEST_FIT_CHARS, + fileName, + -1, + strFileA, + MAX_PATH, + nullptr, + FALSE + ); + if (result > 0) + { + const char* pstrName = strrchr(strFileA, '\\'); + if (!pstrName) + { + pstrName = strFileA; + } + else + { + pstrName++; + } + + if (texture != 0 && *texture != 0) + { + (*texture)->SetPrivateData(WKPDID_D3DDebugObjectName, + static_cast<UINT>(strnlen_s(pstrName, MAX_PATH)), + pstrName + ); + } + + if (textureView != 0 && *textureView != 0) + { + (*textureView)->SetPrivateData(WKPDID_D3DDebugObjectName, + static_cast<UINT>(strnlen_s(pstrName, MAX_PATH)), + pstrName + ); + } + } + } + } +#endif + + return hr; +} diff --git a/samples/DX_APIUsage/DXUT/Core/WICTextureLoader.h b/samples/DX_APIUsage/DXUT/Core/WICTextureLoader.h new file mode 100644 index 0000000..8843c33 --- /dev/null +++ b/samples/DX_APIUsage/DXUT/Core/WICTextureLoader.h @@ -0,0 +1,126 @@ +//-------------------------------------------------------------------------------------- +// File: WICTextureLoader.h +// +// Function for loading a WIC image and creating a Direct3D runtime texture for it +// (auto-generating mipmaps if possible) +// +// Note: Assumes application has already called CoInitializeEx +// +// Warning: CreateWICTexture* functions are not thread-safe if given a d3dContext instance for +// auto-gen mipmap support. +// +// Note these functions are useful for images created as simple 2D textures. For +// more complex resources, DDSTextureLoader is an excellent light-weight runtime loader. +// For a full-featured DDS file reader, writer, and texture processing pipeline see +// the 'Texconv' sample and the 'DirectXTex' library. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// http://go.microsoft.com/fwlink/?LinkId=248926 +// http://go.microsoft.com/fwlink/?LinkId=248929 +//-------------------------------------------------------------------------------------- + +#pragma once + +#include <d3d11_1.h> +#include <stdint.h> + + +namespace DirectX +{ + enum WIC_LOADER_FLAGS + { + WIC_LOADER_DEFAULT = 0, + WIC_LOADER_FORCE_SRGB = 0x1, + WIC_LOADER_IGNORE_SRGB = 0x2, + }; + + // Standard version + HRESULT CreateWICTextureFromMemory( + _In_ ID3D11Device* d3dDevice, + _In_reads_bytes_(wicDataSize) const uint8_t* wicData, + _In_ size_t wicDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0); + + HRESULT CreateWICTextureFromFile( + _In_ ID3D11Device* d3dDevice, + _In_z_ const wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0); + + // Standard version with optional auto-gen mipmap support + HRESULT CreateWICTextureFromMemory( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _In_reads_bytes_(wicDataSize) const uint8_t* wicData, + _In_ size_t wicDataSize, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0); + + HRESULT CreateWICTextureFromFile( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _In_z_ const wchar_t* szFileName, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize = 0); + + // Extended version + HRESULT CreateWICTextureFromMemoryEx( + _In_ ID3D11Device* d3dDevice, + _In_reads_bytes_(wicDataSize) const uint8_t* wicData, + _In_ size_t wicDataSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ unsigned int loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView); + + HRESULT CreateWICTextureFromFileEx( + _In_ ID3D11Device* d3dDevice, + _In_z_ const wchar_t* szFileName, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ unsigned int loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView); + + // Extended version with optional auto-gen mipmap support + HRESULT CreateWICTextureFromMemoryEx( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _In_reads_bytes_(wicDataSize) const uint8_t* wicData, + _In_ size_t wicDataSize, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ unsigned int loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView); + + HRESULT CreateWICTextureFromFileEx( + _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _In_z_ const wchar_t* szFileName, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ unsigned int loadFlags, + _Outptr_opt_ ID3D11Resource** texture, + _Outptr_opt_ ID3D11ShaderResourceView** textureView); +}
\ No newline at end of file |