diff --git a/Kits/ATGTK/CSVReader.h b/Kits/ATGTK/CSVReader.h index 082b92e9..4633c842 100644 --- a/Kits/ATGTK/CSVReader.h +++ b/Kits/ATGTK/CSVReader.h @@ -3,12 +3,15 @@ // // Simple parser for .csv (Comma-Separated Values) files. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- #pragma once +#include +#include +#include #include #include #include diff --git a/Kits/ATGTK/CommandLineHelpers.h b/Kits/ATGTK/CommandLineHelpers.h index ea84e9d3..9feea96b 100644 --- a/Kits/ATGTK/CommandLineHelpers.h +++ b/Kits/ATGTK/CommandLineHelpers.h @@ -6,6 +6,7 @@ //-------------------------------------------------------------------------------------- #pragma once +#include #include namespace ATG @@ -52,7 +53,7 @@ namespace ATG { wprintf(L"Invalid value specified with -%ls (%ls)\n", LookupByValue(option, ::g_Options), name); wprintf(pleaseUseMsg); - PrintTable(_countof(pleaseUseMsg) - 1, table); + PrintTable(std::size(pleaseUseMsg) - 1, table); wprintf(L"\n\n"); return false; } diff --git a/Kits/ATGTK/ControllerFont.h b/Kits/ATGTK/ControllerFont.h index 7787e229..eb2e2811 100644 --- a/Kits/ATGTK/ControllerFont.h +++ b/Kits/ATGTK/ControllerFont.h @@ -3,7 +3,7 @@ // // Class for compositing text with Xbox controller font button sprites // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- diff --git a/Kits/ATGTK/ControllerHelp.cpp b/Kits/ATGTK/ControllerHelp.cpp index 3bcba789..73f199f6 100644 --- a/Kits/ATGTK/ControllerHelp.cpp +++ b/Kits/ATGTK/ControllerHelp.cpp @@ -413,7 +413,8 @@ const ATG::Help::CalloutBox ATG::Help::CalloutBox::s_CalloutTemplates[] = HELP_CALLOUT_COLOR, ANCHOR_DPAD_ALL, nullptr, - CALLOUT_LINE_DPAD_ALL + CALLOUT_LINE_DPAD_ALL, + { 0, 0 } }, // DPAD_DOWN { @@ -427,7 +428,8 @@ const ATG::Help::CalloutBox ATG::Help::CalloutBox::s_CalloutTemplates[] = HELP_CALLOUT_COLOR, ANCHOR_DPAD_ALL, nullptr, - CALLOUT_LINE_DPAD_ALL + CALLOUT_LINE_DPAD_ALL, + { 0, 0 } }, // DPAD_LEFT { @@ -441,7 +443,8 @@ const ATG::Help::CalloutBox ATG::Help::CalloutBox::s_CalloutTemplates[] = HELP_CALLOUT_COLOR, ANCHOR_DPAD_ALL, nullptr, - CALLOUT_LINE_DPAD_ALL + CALLOUT_LINE_DPAD_ALL, + { 0, 0 } }, // DPAD_RIGHT { @@ -455,7 +458,8 @@ const ATG::Help::CalloutBox ATG::Help::CalloutBox::s_CalloutTemplates[] = HELP_CALLOUT_COLOR, ANCHOR_DPAD_ALL, nullptr, - CALLOUT_LINE_DPAD_ALL + CALLOUT_LINE_DPAD_ALL, + { 0, 0 } }, // DPAD_ALL { @@ -763,7 +767,7 @@ void ATG::Help::Render(ID3D12GraphicsCommandList* commandList) { m_descriptorHeap->Heap() }; - commandList->SetDescriptorHeaps(_countof(descriptorHeaps), descriptorHeaps); + commandList->SetDescriptorHeaps(static_cast(std::size(descriptorHeaps)), descriptorHeaps); D3D12_VIEWPORT vp1{ 0.0f, 0.0f, static_cast(m_screenSize.right), static_cast(m_screenSize.bottom), D3D12_MIN_DEPTH, D3D12_MAX_DEPTH }; @@ -859,7 +863,7 @@ void ATG::Help::ReleaseDevice() m_primBatch.reset(); m_lineEffect.reset(); - for (size_t i = 0; i < _countof(m_spriteFonts); ++i) + for (size_t i = 0; i < std::size(m_spriteFonts); ++i) { m_spriteFonts[i].reset(); } diff --git a/Kits/ATGTK/DebugDraw.cpp b/Kits/ATGTK/DebugDraw.cpp index eec76450..d6833e49 100644 --- a/Kits/ATGTK/DebugDraw.cpp +++ b/Kits/ATGTK/DebugDraw.cpp @@ -1,13 +1,15 @@ //-------------------------------------------------------------------------------------- // File: DebugDraw.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- #include "pch.h" #include "DebugDraw.h" +#include + using namespace DirectX; namespace @@ -52,7 +54,7 @@ namespace XMStoreFloat4(&verts[i].color, color); } - batch->DrawIndexed(D3D_PRIMITIVE_TOPOLOGY_LINELIST, s_indices, _countof(s_indices), verts, 8); + batch->DrawIndexed(D3D_PRIMITIVE_TOPOLOGY_LINELIST, s_indices, static_cast(std::size(s_indices)), verts, 8); } } @@ -132,12 +134,12 @@ void XM_CALLCONV DX::Draw(PrimitiveBatch* batch, verts[22].position = corners[7]; verts[23].position = corners[4]; - for (size_t j = 0; j < _countof(verts); ++j) + for (size_t j = 0; j < std::size(verts); ++j) { XMStoreFloat4(&verts[j].color, color); } - batch->Draw(D3D_PRIMITIVE_TOPOLOGY_LINELIST, verts, _countof(verts)); + batch->Draw(D3D_PRIMITIVE_TOPOLOGY_LINELIST, verts, static_cast(std::size(verts))); } void XM_CALLCONV DX::DrawGrid(PrimitiveBatch* batch, diff --git a/Kits/ATGTK/DebugDraw.h b/Kits/ATGTK/DebugDraw.h index 3a6be3fc..2d22a8e6 100644 --- a/Kits/ATGTK/DebugDraw.h +++ b/Kits/ATGTK/DebugDraw.h @@ -3,7 +3,7 @@ // // Helpers for drawing various debug shapes using PrimitiveBatch // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- diff --git a/Kits/ATGTK/FileHelpers.h b/Kits/ATGTK/FileHelpers.h index 2cd22e66..af1153a7 100644 --- a/Kits/ATGTK/FileHelpers.h +++ b/Kits/ATGTK/FileHelpers.h @@ -1,14 +1,15 @@ //-------------------------------------------------------------------------------------- // FileHelpers.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- #pragma once #include -#include -#include + +#include +#include #include @@ -74,4 +75,4 @@ namespace DX Microsoft::WRL::ComPtr& m_handle; }; #endif -} \ No newline at end of file +} diff --git a/Kits/ATGTK/FindMedia.h b/Kits/ATGTK/FindMedia.h index 260fe1c6..89124700 100644 --- a/Kits/ATGTK/FindMedia.h +++ b/Kits/ATGTK/FindMedia.h @@ -4,14 +4,15 @@ // Helper function to find the location of a media file for Windows desktop apps // since they lack appx packaging support. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- #pragma once +#include +#include #include -#include namespace DX @@ -34,6 +35,8 @@ namespace DX static const wchar_t* s_defSearchFolders[] = { L"Assets", + L"Assets\\Fonts", + L"Assets\\Textures", L"Media", L"Media\\Textures", L"Media\\Fonts", @@ -103,4 +106,4 @@ namespace DX throw std::exception("File not found"); } -} \ No newline at end of file +} diff --git a/Kits/ATGTK/FrontPanel/BufferDescriptor.h b/Kits/ATGTK/FrontPanel/BufferDescriptor.h index 2d06381b..d2ce4309 100644 --- a/Kits/ATGTK/FrontPanel/BufferDescriptor.h +++ b/Kits/ATGTK/FrontPanel/BufferDescriptor.h @@ -6,7 +6,8 @@ //-------------------------------------------------------------------------------------- #pragma once -#include +#include +#include namespace ATG diff --git a/Kits/ATGTK/FrontPanel/CPUShapes.h b/Kits/ATGTK/FrontPanel/CPUShapes.h index ba522be5..4c96781f 100644 --- a/Kits/ATGTK/FrontPanel/CPUShapes.h +++ b/Kits/ATGTK/FrontPanel/CPUShapes.h @@ -6,7 +6,7 @@ //-------------------------------------------------------------------------------------- #pragma once -#include +#include namespace ATG diff --git a/Kits/ATGTK/FrontPanel/RasterFont.cpp b/Kits/ATGTK/FrontPanel/RasterFont.cpp index f6911317..d3455479 100644 --- a/Kits/ATGTK/FrontPanel/RasterFont.cpp +++ b/Kits/ATGTK/FrontPanel/RasterFont.cpp @@ -11,10 +11,12 @@ #include "Serialization.h" #include "BufferDescriptor.h" -#include #include -#include +#include #include +#include + +#include using namespace ATG; using namespace DX; diff --git a/Kits/ATGTK/FrontPanel/RasterFont.h b/Kits/ATGTK/FrontPanel/RasterFont.h index 3e635fd0..6dd150c9 100644 --- a/Kits/ATGTK/FrontPanel/RasterFont.h +++ b/Kits/ATGTK/FrontPanel/RasterFont.h @@ -5,8 +5,8 @@ // Copyright (C) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #pragma once + #include -#include #include #include diff --git a/Kits/ATGTK/FullScreenQuad/FullScreenQuad.cpp b/Kits/ATGTK/FullScreenQuad/FullScreenQuad.cpp index 18632bbc..d993780f 100644 --- a/Kits/ATGTK/FullScreenQuad/FullScreenQuad.cpp +++ b/Kits/ATGTK/FullScreenQuad/FullScreenQuad.cpp @@ -3,7 +3,7 @@ // // Class to draw a full-screen quad // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- @@ -61,7 +61,7 @@ void FullScreenQuad::Initialize(_In_ ID3D12Device* d3dDevice) rootParameters[RootParameterIndex::TextureSRV_2].InitAsDescriptorTable(1, &textureSRVs_2, D3D12_SHADER_VISIBILITY_PIXEL); CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc; - rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 1, &sampler, rootSignatureFlags); + rootSignatureDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 1, &sampler, rootSignatureFlags); ComPtr signature; ComPtr error; diff --git a/Kits/ATGTK/FullScreenQuad/FullScreenQuad.h b/Kits/ATGTK/FullScreenQuad/FullScreenQuad.h index 2c9c5e4c..07fc8a39 100644 --- a/Kits/ATGTK/FullScreenQuad/FullScreenQuad.h +++ b/Kits/ATGTK/FullScreenQuad/FullScreenQuad.h @@ -3,7 +3,7 @@ // // Class to draw a full-screen quad // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- @@ -21,8 +21,17 @@ namespace DX { public: void Initialize(_In_ ID3D12Device* d3dDevice); - void Draw(_In_ ID3D12GraphicsCommandList* d3dCommandList, _In_ ID3D12PipelineState* d3dPSO, D3D12_GPU_DESCRIPTOR_HANDLE texture, D3D12_GPU_VIRTUAL_ADDRESS constantBuffer = 0); - void Draw(_In_ ID3D12GraphicsCommandList* d3dCommandList, _In_ ID3D12PipelineState* d3dPSO, D3D12_GPU_DESCRIPTOR_HANDLE texture, D3D12_GPU_DESCRIPTOR_HANDLE texture2, D3D12_GPU_VIRTUAL_ADDRESS constantBuffer = 0); + void Draw( + _In_ ID3D12GraphicsCommandList* d3dCommandList, + _In_ ID3D12PipelineState* d3dPSO, + D3D12_GPU_DESCRIPTOR_HANDLE texture, + D3D12_GPU_VIRTUAL_ADDRESS constantBuffer = 0); + void Draw( + _In_ ID3D12GraphicsCommandList* d3dCommandList, + _In_ ID3D12PipelineState* d3dPSO, + D3D12_GPU_DESCRIPTOR_HANDLE texture, + D3D12_GPU_DESCRIPTOR_HANDLE texture2, + D3D12_GPU_VIRTUAL_ADDRESS constantBuffer = 0); void ReleaseDevice(); diff --git a/Kits/ATGTK/FullScreenQuad/FullScreenQuad.hlsli b/Kits/ATGTK/FullScreenQuad/FullScreenQuad.hlsli index 37f9b67e..5fe761b4 100644 --- a/Kits/ATGTK/FullScreenQuad/FullScreenQuad.hlsli +++ b/Kits/ATGTK/FullScreenQuad/FullScreenQuad.hlsli @@ -3,7 +3,7 @@ // // Common shader code to draw a full-screen quad // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- diff --git a/Kits/ATGTK/FullScreenQuad/FullScreenQuadPS.hlsl b/Kits/ATGTK/FullScreenQuad/FullScreenQuadPS.hlsl index 9d7b8915..26190164 100644 --- a/Kits/ATGTK/FullScreenQuad/FullScreenQuadPS.hlsl +++ b/Kits/ATGTK/FullScreenQuad/FullScreenQuadPS.hlsl @@ -3,7 +3,7 @@ // // A simple pixel shader to render a texture // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- diff --git a/Kits/ATGTK/FullScreenQuad/FullScreenQuadVS.hlsl b/Kits/ATGTK/FullScreenQuad/FullScreenQuadVS.hlsl index 9950a59a..1595f0a8 100644 --- a/Kits/ATGTK/FullScreenQuad/FullScreenQuadVS.hlsl +++ b/Kits/ATGTK/FullScreenQuad/FullScreenQuadVS.hlsl @@ -3,7 +3,7 @@ // // Simple vertex shader to draw a full-screen quad // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- diff --git a/Kits/ATGTK/HDR/HDRCommon.h b/Kits/ATGTK/HDR/HDRCommon.h index 1bc43dca..f662cf71 100644 --- a/Kits/ATGTK/HDR/HDRCommon.h +++ b/Kits/ATGTK/HDR/HDRCommon.h @@ -3,14 +3,13 @@ // // Simple helper functions for HDR // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- #pragma once -#include -#include +#include #include namespace DX @@ -21,14 +20,14 @@ namespace DX // Apply the ST.2084 curve to normalized linear values and outputs normalized non-linear values inline float LinearToST2084(float normalizedLinearValue) { - float ST2084 = pow((0.8359375f + 18.8515625f * pow(abs(normalizedLinearValue), 0.1593017578f)) / (1.0f + 18.6875f * pow(abs(normalizedLinearValue), 0.1593017578f)), 78.84375f); + float ST2084 = powf((0.8359375f + 18.8515625f * powf(abs(normalizedLinearValue), 0.1593017578f)) / (1.0f + 18.6875f * powf(abs(normalizedLinearValue), 0.1593017578f)), 78.84375f); return ST2084; // Don't clamp between [0..1], so we can still perform operations on scene values higher than 10,000 nits } // ST.2084 to linear, resulting in a linear normalized value inline float ST2084ToLinear(float ST2084) { - float normalizedLinear = pow(std::max(pow(abs(ST2084), 1.0f / 78.84375f) - 0.8359375f, 0.0f) / (18.8515625f - 18.6875f * pow(abs(ST2084), 1.0f / 78.84375f)), 1.0f / 0.1593017578f); + float normalizedLinear = powf(std::max(powf(abs(ST2084), 1.0f / 78.84375f) - 0.8359375f, 0.0f) / (18.8515625f - 18.6875f * powf(abs(ST2084), 1.0f / 78.84375f)), 1.0f / 0.1593017578f); return normalizedLinear; } @@ -82,4 +81,4 @@ namespace DX float hdrSceneValue = normalizedLinearValue * c_MaxNitsFor2084 / paperWhiteNits; return hdrSceneValue; } -} \ No newline at end of file +} diff --git a/Kits/ATGTK/HDR/HDRCommon.hlsli b/Kits/ATGTK/HDR/HDRCommon.hlsli index b250ffc5..7ae1b427 100644 --- a/Kits/ATGTK/HDR/HDRCommon.hlsli +++ b/Kits/ATGTK/HDR/HDRCommon.hlsli @@ -3,7 +3,7 @@ // // Shader code helper functions for HDR, such as color rotation, ST.2084, etc. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- diff --git a/Kits/ATGTK/OSHelpers.h b/Kits/ATGTK/OSHelpers.h index f4b67a83..931d0d1e 100644 --- a/Kits/ATGTK/OSHelpers.h +++ b/Kits/ATGTK/OSHelpers.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // OSHelpers.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- #pragma once diff --git a/Kits/ATGTK/OrbitCamera.cpp b/Kits/ATGTK/OrbitCamera.cpp index afc62216..ca29b282 100644 --- a/Kits/ATGTK/OrbitCamera.cpp +++ b/Kits/ATGTK/OrbitCamera.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: OrbitCamera.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- @@ -13,6 +13,8 @@ #include "Mouse.h" #include "SimpleMath.h" +#include + using namespace DirectX; using namespace DX; @@ -716,4 +718,4 @@ XMVECTOR OrbitCamera::GetPosition() const unsigned int OrbitCamera::GetFlags() const { return pImpl->m_flags; -} \ No newline at end of file +} diff --git a/Kits/ATGTK/OrbitCamera.h b/Kits/ATGTK/OrbitCamera.h index aed201fa..c44ea7ab 100644 --- a/Kits/ATGTK/OrbitCamera.h +++ b/Kits/ATGTK/OrbitCamera.h @@ -3,13 +3,14 @@ // // Helper for implementing Model-View camera // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- #pragma once -#include +#include + #include "GamePad.h" @@ -126,4 +127,4 @@ namespace DX std::unique_ptr pImpl; }; -} \ No newline at end of file +} diff --git a/Kits/ATGTK/PBREffect/PBREffect.cpp b/Kits/ATGTK/PBREffect/PBREffect.cpp index f8b1dc93..413eada3 100644 --- a/Kits/ATGTK/PBREffect/PBREffect.cpp +++ b/Kits/ATGTK/PBREffect/PBREffect.cpp @@ -79,7 +79,8 @@ class ATG::PBREffect::Impl : public EffectBase public: Impl(_In_ ID3D12Device* device, int effectFlags, - const EffectPipelineStateDescription& pipelineDescription); + const EffectPipelineStateDescription& pipelineDescription, + bool generateVelocity); void Apply(_In_ ID3D12GraphicsCommandList* commandList); @@ -89,6 +90,9 @@ class ATG::PBREffect::Impl : public EffectBase int flags; + // When PBR moves into DirectXTK, this could become an effect flag. + bool doGenerateVelocity; + enum RootParameterIndex { AlbedoTexture, @@ -140,15 +144,16 @@ const int EffectBase::PixelShaderIndices[] = SharedResourcePool::DeviceResources> EffectBase::deviceResourcesPool; // Constructor. -ATG::PBREffect::Impl::Impl(_In_ ID3D12Device* device, int effectFlags, const EffectPipelineStateDescription& pipelineDescription) +ATG::PBREffect::Impl::Impl(_In_ ID3D12Device* device, int effectFlags, const EffectPipelineStateDescription& pipelineDescription, bool generateVelocity) : EffectBase(device), flags(effectFlags), + doGenerateVelocity(generateVelocity), descriptors{} { - static_assert( _countof(EffectBase::VertexShaderIndices) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch" ); - static_assert( _countof(EffectBase::VertexShaderBytecode) == PBREffectTraits::VertexShaderCount, "array/max mismatch" ); - static_assert( _countof(EffectBase::PixelShaderBytecode) == PBREffectTraits::PixelShaderCount, "array/max mismatch" ); - static_assert( _countof(EffectBase::PixelShaderIndices) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch" ); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == PBREffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == PBREffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch"); // Lighting static const XMVECTORF32 defaultLightDirection = { 0, -1, 0, 0 }; @@ -185,12 +190,12 @@ ATG::PBREffect::Impl::Impl(_In_ ID3D12Device* device, int effectFlags, const Eff CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 1) }; - for (int i = 0; i < _countof(textureSRV); i++) + for (size_t i = 0; i < std::size(textureSRV); i++) { rootParameters[i].InitAsDescriptorTable(1, &textureSRV[i]); } - for (int i = 0; i < _countof(textureSampler); i++) + for (size_t i = 0; i < std::size(textureSampler); i++) { rootParameters[i + SurfaceSampler].InitAsDescriptorTable(1, &textureSampler[i]); } @@ -198,13 +203,13 @@ ATG::PBREffect::Impl::Impl(_In_ ID3D12Device* device, int effectFlags, const Eff rootParameters[ConstantBuffer].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_ALL); CD3DX12_ROOT_SIGNATURE_DESC rsigDesc; - rsigDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 0, nullptr, rootSignatureFlags); mRootSignature = GetRootSignature(0, rsigDesc); // Create pipeline state int sp = GetPipelineStatePermutation((effectFlags & EffectFlags::Texture) != 0, - (effectFlags & EffectFlags::Velocity) != 0); + doGenerateVelocity); int vi = EffectBase::VertexShaderIndices[sp]; int pi = EffectBase::PixelShaderIndices[sp]; @@ -296,8 +301,9 @@ void ATG::PBREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) // Public constructor. ATG::PBREffect::PBREffect(_In_ ID3D12Device* device, int effectFlags, - const EffectPipelineStateDescription& pipelineDescription) - : pImpl(new Impl(device, effectFlags, pipelineDescription)) + const EffectPipelineStateDescription& pipelineDescription, + bool generateVelocity) + : pImpl(new Impl(device, effectFlags, pipelineDescription, generateVelocity)) { } @@ -472,4 +478,4 @@ const D3D12_INPUT_LAYOUT_DESC ATG::VertexPositionNormalTextureTangent::InputLayo { ATG::VertexPositionNormalTextureTangent::InputElements, ATG::VertexPositionNormalTextureTangent::InputElementCount -}; \ No newline at end of file +}; diff --git a/Kits/ATGTK/PBREffect/PBREffect.h b/Kits/ATGTK/PBREffect/PBREffect.h index 105963a9..272f05cd 100644 --- a/Kits/ATGTK/PBREffect/PBREffect.h +++ b/Kits/ATGTK/PBREffect/PBREffect.h @@ -16,7 +16,8 @@ namespace ATG { public: explicit PBREffect(_In_ ID3D12Device* device, int effectFlags, - const DirectX::EffectPipelineStateDescription& pipelineDescription); + const DirectX::EffectPipelineStateDescription& pipelineDescription, + bool generateVelocity = false); PBREffect(PBREffect&& moveFrom); PBREffect& operator= (PBREffect&& moveFrom); diff --git a/Kits/ATGTK/ReadData.h b/Kits/ATGTK/ReadData.h index 4741bcdb..89282f8c 100644 --- a/Kits/ATGTK/ReadData.h +++ b/Kits/ATGTK/ReadData.h @@ -6,15 +6,18 @@ // For Windows desktop apps, it looks for files in the same folder as the running EXE if // it can't find them in the CWD // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- #pragma once +#include #include #include #include +#include +#include #include @@ -29,42 +32,42 @@ namespace DX { wchar_t moduleName[_MAX_PATH]; if (!GetModuleFileNameW(nullptr, moduleName, _MAX_PATH)) - throw std::exception("GetModuleFileName"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "GetModuleFileNameW"); wchar_t drive[_MAX_DRIVE]; wchar_t path[_MAX_PATH]; if (_wsplitpath_s(moduleName, drive, _MAX_DRIVE, path, _MAX_PATH, nullptr, 0, nullptr, 0)) - throw std::exception("_wsplitpath_s"); + throw std::runtime_error("_wsplitpath_s"); wchar_t filename[_MAX_PATH]; if (_wmakepath_s(filename, _MAX_PATH, drive, path, name, nullptr)) - throw std::exception("_wmakepath_s"); + throw std::runtime_error("_wmakepath_s"); inFile.open(filename, std::ios::in | std::ios::binary | std::ios::ate); } #endif if (!inFile) - throw std::exception("ReadData"); + throw std::runtime_error("ReadData"); std::streampos len = inFile.tellg(); if (!inFile) - throw std::exception("ReadData"); + throw std::runtime_error("ReadData"); std::vector blob; blob.resize(size_t(len)); inFile.seekg(0, std::ios::beg); if (!inFile) - throw std::exception("ReadData"); + throw std::runtime_error("ReadData"); inFile.read(reinterpret_cast(blob.data()), len); if (!inFile) - throw std::exception("ReadData"); + throw std::runtime_error("ReadData"); inFile.close(); return blob; } -} \ No newline at end of file +} diff --git a/Kits/ATGTK/RenderTexture.cpp b/Kits/ATGTK/RenderTexture.cpp index 3342fd67..72103296 100644 --- a/Kits/ATGTK/RenderTexture.cpp +++ b/Kits/ATGTK/RenderTexture.cpp @@ -3,7 +3,7 @@ // // Helper for managing offscreen render targets // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- @@ -13,7 +13,7 @@ #include "DirectXHelpers.h" #include -#include +#include #include using namespace DirectX; @@ -52,7 +52,7 @@ void RenderTexture::SetDevice(_In_ ID3D12Device* device, D3D12_CPU_DESCRIPTOR_HA D3D12_FEATURE_DATA_FORMAT_SUPPORT formatSupport = { m_format, D3D12_FORMAT_SUPPORT1_NONE, D3D12_FORMAT_SUPPORT2_NONE }; if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &formatSupport, sizeof(formatSupport)))) { - throw std::exception("CheckFeatureSupport"); + throw std::runtime_error("CheckFeatureSupport"); } UINT required = D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_RENDER_TARGET; @@ -63,13 +63,13 @@ void RenderTexture::SetDevice(_In_ ID3D12Device* device, D3D12_CPU_DESCRIPTOR_HA sprintf_s(buff, "RenderTexture: Device does not support the requested format (%u)!\n", m_format); OutputDebugStringA(buff); #endif - throw std::exception("RenderTexture"); + throw std::runtime_error("RenderTexture"); } } if (!srvDescriptor.ptr || !rtvDescriptor.ptr) { - throw std::exception("Invalid descriptors"); + throw std::runtime_error("Invalid descriptors"); } m_device = device; @@ -170,7 +170,7 @@ void RenderTexture::SetDevice(_In_ ID3D11Device* device) UINT formatSupport = 0; if (FAILED(device->CheckFormatSupport(m_format, &formatSupport))) { - throw std::exception("CheckFormatSupport"); + throw std::runtime_error("CheckFormatSupport"); } UINT32 required = D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_RENDER_TARGET; @@ -181,7 +181,7 @@ void RenderTexture::SetDevice(_In_ ID3D11Device* device) sprintf_s(buff, "RenderTexture: Device does not support the requested format (%u)!\n", m_format); OutputDebugStringA(buff); #endif - throw std::exception("RenderTexture"); + throw std::runtime_error("RenderTexture"); } } diff --git a/Kits/ATGTK/RenderTexture.h b/Kits/ATGTK/RenderTexture.h index f4478fae..9f2626bb 100644 --- a/Kits/ATGTK/RenderTexture.h +++ b/Kits/ATGTK/RenderTexture.h @@ -3,12 +3,14 @@ // // Helper for managing offscreen render targets // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- #pragma once +#include + #include #include diff --git a/Kits/ATGTK/Serialization.h b/Kits/ATGTK/Serialization.h index 714c7de5..65e73054 100644 --- a/Kits/ATGTK/Serialization.h +++ b/Kits/ATGTK/Serialization.h @@ -6,13 +6,15 @@ //-------------------------------------------------------------------------------------- #pragma once -#include -#include - +#include +#include +#include +#include #include #include #include #include +#include #include #define ENABLE_IF_INTEGRAL(_T_) typename std::enable_if::value>::type* = nullptr @@ -1405,7 +1407,7 @@ namespace ATG ctx.Visit(); return srzBffr.GetBytesWritten(); } - + template size_t Serialize(const T &serializeMe, uint8_t *outputBuffer, size_t outputBufferSize) { diff --git a/Kits/ATGTK/Skybox/Skybox.h b/Kits/ATGTK/Skybox/Skybox.h index 819642af..9ebc8bf0 100644 --- a/Kits/ATGTK/Skybox/Skybox.h +++ b/Kits/ATGTK/Skybox/Skybox.h @@ -3,7 +3,7 @@ // // A sky box rendering helper. Takes DDS cubemap as input. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- #pragma once diff --git a/Kits/ATGTK/Skybox/SkyboxEffect.cpp b/Kits/ATGTK/Skybox/SkyboxEffect.cpp index 1b5512e5..dfc662de 100644 --- a/Kits/ATGTK/Skybox/SkyboxEffect.cpp +++ b/Kits/ATGTK/Skybox/SkyboxEffect.cpp @@ -3,7 +3,7 @@ // // A sky box rendering helper. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- @@ -95,10 +95,10 @@ SkyboxEffect::Impl::Impl(_In_ ID3D12Device* device, const EffectPipelineStateDes : EffectBase(device), descriptors{} { - static_assert(_countof(EffectBase::VertexShaderIndices) == SkyboxEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == SkyboxEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == SkyboxEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == SkyboxEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == SkyboxEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == SkyboxEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == SkyboxEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == SkyboxEffectTraits::ShaderPermutationCount, "array/max mismatch"); // Create root signature D3D12_ROOT_SIGNATURE_FLAGS rootSignatureFlags = @@ -116,7 +116,7 @@ SkyboxEffect::Impl::Impl(_In_ ID3D12Device* device, const EffectPipelineStateDes rootParameters[ConstantBuffer].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_ALL); CD3DX12_ROOT_SIGNATURE_DESC rsigDesc; - rsigDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 0, nullptr, rootSignatureFlags); // Create the root signature mRootSignature = GetRootSignature(0, rsigDesc); @@ -213,4 +213,4 @@ void XM_CALLCONV SkyboxEffect::SetMatrices(FXMMATRIX view, CXMMATRIX projection) pImpl->matrices.projection = projection; pImpl->dirtyFlags |= EffectDirtyFlags::WorldViewProj; -} \ No newline at end of file +} diff --git a/Kits/ATGTK/Skybox/SkyboxEffect.h b/Kits/ATGTK/Skybox/SkyboxEffect.h index 9a11c69d..3d573ce8 100644 --- a/Kits/ATGTK/Skybox/SkyboxEffect.h +++ b/Kits/ATGTK/Skybox/SkyboxEffect.h @@ -3,7 +3,7 @@ // // A sky box rendering helper for. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- diff --git a/Kits/ATGTK/Skybox/SkyboxEffect_Common.hlsli b/Kits/ATGTK/Skybox/SkyboxEffect_Common.hlsli index 79547e06..7a6b8584 100644 --- a/Kits/ATGTK/Skybox/SkyboxEffect_Common.hlsli +++ b/Kits/ATGTK/Skybox/SkyboxEffect_Common.hlsli @@ -3,7 +3,7 @@ // // A sky box rendering helper. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- diff --git a/Kits/ATGTK/Skybox/SkyboxEffect_PS.hlsl b/Kits/ATGTK/Skybox/SkyboxEffect_PS.hlsl index ff037c60..7031a1d3 100644 --- a/Kits/ATGTK/Skybox/SkyboxEffect_PS.hlsl +++ b/Kits/ATGTK/Skybox/SkyboxEffect_PS.hlsl @@ -3,7 +3,7 @@ // // A sky box rendering helper. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- diff --git a/Kits/ATGTK/Skybox/SkyboxEffect_VS.hlsl b/Kits/ATGTK/Skybox/SkyboxEffect_VS.hlsl index b7508199..65ac33de 100644 --- a/Kits/ATGTK/Skybox/SkyboxEffect_VS.hlsl +++ b/Kits/ATGTK/Skybox/SkyboxEffect_VS.hlsl @@ -3,7 +3,7 @@ // // A sky box rendering helper. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- diff --git a/Kits/ATGTK/TextConsole.cpp b/Kits/ATGTK/TextConsole.cpp index 6c3ba278..78d25536 100644 --- a/Kits/ATGTK/TextConsole.cpp +++ b/Kits/ATGTK/TextConsole.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: TextConsole.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- @@ -12,7 +12,11 @@ #include "DDSTextureLoader.h" #include "WICTextureLoader.h" -#include +#include +#include +#include +#include +#include using Microsoft::WRL::ComPtr; @@ -518,7 +522,7 @@ void TextConsoleImage::RestoreDevice( auto desc = m_background->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { - throw std::exception("Only supports 2D images"); + throw std::runtime_error("Only supports 2D images"); } D3D12_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; diff --git a/Kits/ATGTK/TextConsole.h b/Kits/ATGTK/TextConsole.h index 46c19a45..c3f6f55b 100644 --- a/Kits/ATGTK/TextConsole.h +++ b/Kits/ATGTK/TextConsole.h @@ -6,7 +6,7 @@ // // Note: This is best used with monospace rather than proportional fonts // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- @@ -19,6 +19,7 @@ #include "SpriteBatch.h" #include "SpriteFont.h" +#include #include #include diff --git a/Kits/ATGTK/ThreadHelpers.h b/Kits/ATGTK/ThreadHelpers.h index 3a304291..317750b4 100644 --- a/Kits/ATGTK/ThreadHelpers.h +++ b/Kits/ATGTK/ThreadHelpers.h @@ -1,15 +1,15 @@ //-------------------------------------------------------------------------------------- // File: ThreadHelpers.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- #pragma once -#include -#include - +#include +#include +#include #include #include #include diff --git a/Kits/ATGTK/ToastManager.h b/Kits/ATGTK/ToastManager.h index f98630a9..b9b040cf 100644 --- a/Kits/ATGTK/ToastManager.h +++ b/Kits/ATGTK/ToastManager.h @@ -3,7 +3,7 @@ // // A helper for showing text messages as toast notifications // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- diff --git a/Kits/ATGTK/WAVFileReader.cpp b/Kits/ATGTK/WAVFileReader.cpp index 5a4cf8d6..41a8cb2c 100644 --- a/Kits/ATGTK/WAVFileReader.cpp +++ b/Kits/ATGTK/WAVFileReader.cpp @@ -3,21 +3,25 @@ // // Functions for loading WAV audio files // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- #include "pch.h" #include "WAVFileReader.h" +#include + #ifdef __clang__ #pragma clang diagnostic ignored "-Wunused-const-variable" #endif #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 )) +#define MAKEFOURCC(ch0, ch1, ch2, ch3) \ + (static_cast(static_cast(ch0)) \ + | (static_cast(static_cast(ch1)) << 8) \ + | (static_cast(static_cast(ch2)) << 16) \ + | (static_cast(static_cast(ch3)) << 24)) #endif /* defined(MAKEFOURCC) */ namespace diff --git a/Kits/ATGTK/WAVFileReader.h b/Kits/ATGTK/WAVFileReader.h index 9f7a0d7c..72cb38d2 100644 --- a/Kits/ATGTK/WAVFileReader.h +++ b/Kits/ATGTK/WAVFileReader.h @@ -3,16 +3,17 @@ // // Functions for loading WAV audio files // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- #pragma once -#include - +#include #include #include + +#include #include #if defined(_XBOX_ONE) && defined(_TITLE) @@ -29,7 +30,7 @@ namespace DX if (wfx->cbSize < (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX))) return 0; - static const GUID s_wfexBase = { 0x00000000, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 }; + static const GUID s_wfexBase = { 0x00000000, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 } }; auto wfex = reinterpret_cast(wfx); diff --git a/Kits/ATGTK/d3dx12.h b/Kits/ATGTK/d3dx12.h index 3bf9ac5b..562fb53a 100644 --- a/Kits/ATGTK/d3dx12.h +++ b/Kits/ATGTK/d3dx12.h @@ -1,11 +1,7 @@ //********************************************************* // -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the MIT License (MIT). -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License (MIT). // //********************************************************* @@ -2415,7 +2411,8 @@ inline HRESULT D3DX12SerializeVersionedRootSignature( { if (desc_1_1.pParameters[n].ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) { - HeapFree(GetProcessHeap(), 0, reinterpret_cast(const_cast(pParameters_1_0[n].DescriptorTable.pDescriptorRanges))); + auto pDescriptorRanges_1_0 = pParameters_1_0[n].DescriptorTable.pDescriptorRanges; + HeapFree(GetProcessHeap(), 0, reinterpret_cast(const_cast(pDescriptorRanges_1_0))); } } HeapFree(GetProcessHeap(), 0, pParameters); diff --git a/Kits/DirectXTK/Audio/AudioEngine.cpp b/Kits/DirectXTK/Audio/AudioEngine.cpp index eb193429..0551cdb9 100644 --- a/Kits/DirectXTK/Audio/AudioEngine.cpp +++ b/Kits/DirectXTK/Audio/AudioEngine.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: AudioEngine.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -32,7 +32,7 @@ namespace mCriticalError.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mCriticalError) { - throw std::exception("CreateEvent"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } } @@ -66,7 +66,7 @@ namespace mBufferEnd.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mBufferEnd) { - throw std::exception("CreateEvent"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } } @@ -248,7 +248,7 @@ namespace } } -static_assert(_countof(gReverbPresets) == Reverb_MAX, "AUDIO_ENGINE_REVERB enum mismatch"); +static_assert(static_cast(std::size(gReverbPresets)) == Reverb_MAX, "AUDIO_ENGINE_REVERB enum mismatch"); //====================================================================================== @@ -674,7 +674,7 @@ bool AudioEngine::Impl::Update() return false; HANDLE events[2] = { mEngineCallback.mCriticalError.get(), mVoiceCallback.mBufferEnd.get() }; - switch (WaitForMultipleObjectsEx(_countof(events), events, FALSE, 0, FALSE)) + switch (WaitForMultipleObjectsEx(static_cast(std::size(events)), events, FALSE, 0, FALSE)) { default: case WAIT_TIMEOUT: @@ -723,7 +723,7 @@ bool AudioEngine::Impl::Update() break; case WAIT_FAILED: - throw std::exception("WaitForMultipleObjects"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForMultipleObjectsEx"); } // @@ -827,12 +827,12 @@ void AudioEngine::Impl::AllocateVoice( IXAudio2SourceVoice** voice) { if (!wfx) - throw std::exception("Wave format is required\n"); + throw std::invalid_argument("Wave format is required\n"); // No need to call IsValid on wfx because CreateSourceVoice will do that if (!voice) - throw std::exception("Voice pointer must be non-null"); + throw std::invalid_argument("Voice pointer must be non-null"); *voice = nullptr; @@ -852,7 +852,7 @@ void AudioEngine::Impl::AllocateVoice( DebugTrace((flags & SoundEffectInstance_NoSetPitch) ? "ERROR: One-shot voices must support pitch-shifting for voice reuse\n" : "ERROR: One-use voices cannot use 3D positional audio\n"); - throw std::exception("Invalid flags for one-shot voice"); + throw std::invalid_argument("Invalid flags for one-shot voice"); } #ifdef VERBOSE_TRACE @@ -947,7 +947,7 @@ void AudioEngine::Impl::AllocateVoice( if (FAILED(hr)) { DebugTrace("ERROR: CreateSourceVoice (reuse) failed with error %08X\n", static_cast(hr)); - throw std::exception("CreateSourceVoice"); + throw std::runtime_error("CreateSourceVoice"); } } @@ -956,7 +956,7 @@ void AudioEngine::Impl::AllocateVoice( if (FAILED(hr)) { DebugTrace("ERROR: SetSourceSampleRate failed with error %08X\n", static_cast(hr)); - throw std::exception("SetSourceSampleRate"); + throw std::runtime_error("SetSourceSampleRate"); } } } @@ -977,7 +977,7 @@ void AudioEngine::Impl::AllocateVoice( { DebugTrace("ERROR: Too many instance voices (%zu >= %zu); see TrimVoicePool\n", mVoiceInstances + 1, maxVoiceInstances); - throw std::exception("Too many instance voices"); + throw std::runtime_error("Too many instance voices"); } UINT32 vflags = (flags & SoundEffectInstance_NoSetPitch) ? XAUDIO2_VOICE_NOPITCH : 0u; @@ -1012,7 +1012,7 @@ void AudioEngine::Impl::AllocateVoice( if (FAILED(hr)) { DebugTrace("ERROR: CreateSourceVoice failed with error %08X\n", static_cast(hr)); - throw std::exception("CreateSourceVoice"); + throw std::runtime_error("CreateSourceVoice"); } else if (!oneshot) { @@ -1131,7 +1131,7 @@ AudioEngine::AudioEngine( if (flags & AudioEngine_ThrowOnNoAudioHW) { DebugTrace("ERROR: AudioEngine found no default audio device\n"); - throw std::exception("AudioEngineNoAudioHW"); + throw std::runtime_error("AudioEngineNoAudioHW"); } else { @@ -1143,7 +1143,7 @@ AudioEngine::AudioEngine( DebugTrace("ERROR: AudioEngine failed (%08X) to initialize using device [%ls]\n", static_cast(hr), (deviceId) ? deviceId : L"default"); - throw std::exception("AudioEngine"); + throw std::runtime_error("AudioEngine"); } } } @@ -1198,7 +1198,7 @@ bool AudioEngine::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceId) if (pImpl->mEngineFlags & AudioEngine_ThrowOnNoAudioHW) { DebugTrace("ERROR: AudioEngine found no default audio device on Reset\n"); - throw std::exception("AudioEngineNoAudioHW"); + throw std::runtime_error("AudioEngineNoAudioHW"); } else { @@ -1210,7 +1210,7 @@ bool AudioEngine::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceId) { DebugTrace("ERROR: AudioEngine failed (%08X) to Reset using device [%ls]\n", static_cast(hr), (deviceId) ? deviceId : L"default"); - throw std::exception("AudioEngine::Reset"); + throw std::runtime_error("AudioEngine::Reset"); } } @@ -1262,7 +1262,7 @@ void AudioEngine::SetMasterVolume(float volume) void AudioEngine::SetReverb(AUDIO_ENGINE_REVERB reverb) { if (reverb >= Reverb_MAX) - throw std::out_of_range("AudioEngine::SetReverb"); + throw std::invalid_argument("reverb parameter is invalid"); if (reverb == Reverb_Off) { @@ -1350,7 +1350,7 @@ bool AudioEngine::IsCriticalError() const noexcept void AudioEngine::SetDefaultSampleRate(int sampleRate) { if ((sampleRate < XAUDIO2_MIN_SAMPLE_RATE) || (sampleRate > XAUDIO2_MAX_SAMPLE_RATE)) - throw std::exception("Default sample rate is out of range"); + throw std::out_of_range("Default sample rate is out of range"); pImpl->defaultRate = sampleRate; } @@ -1552,7 +1552,7 @@ std::vector AudioEngine::GetRendererDetails() while (operation->Status == Windows::Foundation::AsyncStatus::Started) { Sleep(100); } if (operation->Status != Windows::Foundation::AsyncStatus::Completed) { - throw std::exception("FindAllAsync"); + throw std::runtime_error("FindAllAsync"); } DeviceInformationCollection^ devices = operation->GetResults(); @@ -1607,7 +1607,7 @@ std::vector AudioEngine::GetRendererDetails() if (status != ABI::Windows::Foundation::AsyncStatus::Completed) { - throw std::exception("FindAllAsyncDeviceClass"); + throw std::runtime_error("FindAllAsyncDeviceClass"); } ComPtr> devices; diff --git a/Kits/DirectXTK/Audio/DynamicSoundEffectInstance.cpp b/Kits/DirectXTK/Audio/DynamicSoundEffectInstance.cpp index 4dc9ee75..559eecba 100644 --- a/Kits/DirectXTK/Audio/DynamicSoundEffectInstance.cpp +++ b/Kits/DirectXTK/Audio/DynamicSoundEffectInstance.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DynamicSoundEffectInstance.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -35,13 +35,13 @@ class DynamicSoundEffectInstance::Impl : public IVoiceNotify || (sampleRate > XAUDIO2_MAX_SAMPLE_RATE)) { DebugTrace("DynamicSoundEffectInstance sampleRate must be in range %u...%u\n", XAUDIO2_MIN_SAMPLE_RATE, XAUDIO2_MAX_SAMPLE_RATE); - throw std::invalid_argument("DynamicSoundEffectInstance"); + throw std::out_of_range("DynamicSoundEffectInstance"); } if (!channels || (channels > 8)) { DebugTrace("DynamicSoundEffectInstance channels must be in range 1...8\n"); - throw std::invalid_argument("DynamicSoundEffectInstance"); + throw std::out_of_range("DynamicSoundEffectInstance channel count out of range"); } switch (sampleBits) @@ -52,13 +52,13 @@ class DynamicSoundEffectInstance::Impl : public IVoiceNotify default: DebugTrace("DynamicSoundEffectInstance sampleBits must be 8-bit or 16-bit\n"); - throw std::invalid_argument("DynamicSoundEffectInstance"); + throw std::invalid_argument("DynamicSoundEffectInstance supports 8 or 16 bit"); } mBufferEvent.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mBufferEvent) { - throw std::exception("CreateEvent"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } CreateIntegerPCM(&mWaveFormat, sampleRate, channels, sampleBits); @@ -177,7 +177,7 @@ _Use_decl_annotations_ void DynamicSoundEffectInstance::Impl::SubmitBuffer(const uint8_t* pAudioData, uint32_t offset, size_t audioBytes) { if (!pAudioData || !audioBytes) - throw std::exception("Invalid audio data buffer"); + throw std::invalid_argument("Invalid audio data buffer"); if (audioBytes > UINT32_MAX) throw std::out_of_range("SubmitBuffer"); @@ -204,7 +204,7 @@ void DynamicSoundEffectInstance::Impl::SubmitBuffer(const uint8_t* pAudioData, u DebugTrace("\tFormat Tag %u, %u channels, %u-bit, %u Hz, %zu bytes [%u offset)\n", mWaveFormat.wFormatTag, mWaveFormat.nChannels, mWaveFormat.wBitsPerSample, mWaveFormat.nSamplesPerSec, audioBytes, offset); #endif - throw std::exception("SubmitSourceBuffer"); + throw std::runtime_error("SubmitSourceBuffer"); } } @@ -226,7 +226,7 @@ void DynamicSoundEffectInstance::Impl::OnUpdate() break; case WAIT_FAILED: - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); } } @@ -317,7 +317,7 @@ void DynamicSoundEffectInstance::SetPan(float pan) } -void DynamicSoundEffectInstance::Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords) +void DynamicSoundEffectInstance::Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords) { pImpl->mBase.Apply3D(listener, emitter, rhcoords); } @@ -381,6 +381,12 @@ int DynamicSoundEffectInstance::GetPendingBufferCount() const noexcept } +unsigned int DynamicSoundEffectInstance::GetChannelCount() const noexcept +{ + return pImpl->mBase.GetChannelCount(); +} + + const WAVEFORMATEX* DynamicSoundEffectInstance::GetFormat() const noexcept { return pImpl->GetFormat(); diff --git a/Kits/DirectXTK/Audio/SoundCommon.cpp b/Kits/DirectXTK/Audio/SoundCommon.cpp index ef204d59..9f324ba4 100644 --- a/Kits/DirectXTK/Audio/SoundCommon.cpp +++ b/Kits/DirectXTK/Audio/SoundCommon.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SoundCommon.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -505,7 +505,11 @@ uint32_t DirectX::GetDefaultChannelMask(int channels) noexcept _Use_decl_annotations_ -void DirectX::CreateIntegerPCM(WAVEFORMATEX* wfx, int sampleRate, int channels, int sampleBits) noexcept +void DirectX::CreateIntegerPCM( + WAVEFORMATEX* wfx, + int sampleRate, + int channels, + int sampleBits) noexcept { int blockAlign = channels * sampleBits / 8; @@ -522,7 +526,10 @@ void DirectX::CreateIntegerPCM(WAVEFORMATEX* wfx, int sampleRate, int channels, _Use_decl_annotations_ -void DirectX::CreateFloatPCM(WAVEFORMATEX* wfx, int sampleRate, int channels) noexcept +void DirectX::CreateFloatPCM( + WAVEFORMATEX* wfx, + int sampleRate, + int channels) noexcept { int blockAlign = channels * 4; @@ -539,7 +546,12 @@ void DirectX::CreateFloatPCM(WAVEFORMATEX* wfx, int sampleRate, int channels) no _Use_decl_annotations_ -void DirectX::CreateADPCM(WAVEFORMATEX* wfx, size_t wfxSize, int sampleRate, int channels, int samplesPerBlock) noexcept(false) +void DirectX::CreateADPCM( + WAVEFORMATEX* wfx, + size_t wfxSize, + int sampleRate, + int channels, + int samplesPerBlock) noexcept(false) { if (wfxSize < (sizeof(WAVEFORMATEX) + 32 /*MSADPCM_FORMAT_EXTRA_BYTES*/)) { @@ -578,7 +590,13 @@ void DirectX::CreateADPCM(WAVEFORMATEX* wfx, size_t wfxSize, int sampleRate, int #ifdef DIRECTX_ENABLE_XWMA _Use_decl_annotations_ -void DirectX::CreateXWMA(WAVEFORMATEX* wfx, int sampleRate, int channels, int blockAlign, int avgBytes, bool wma3) noexcept +void DirectX::CreateXWMA( + WAVEFORMATEX* wfx, + int sampleRate, + int channels, + int blockAlign, + int avgBytes, + bool wma3) noexcept { wfx->wFormatTag = static_cast((wma3) ? WAVE_FORMAT_WMAUDIO3 : WAVE_FORMAT_WMAUDIO2); wfx->nChannels = static_cast(channels); @@ -595,7 +613,14 @@ void DirectX::CreateXWMA(WAVEFORMATEX* wfx, int sampleRate, int channels, int bl #ifdef DIRECTX_ENABLE_XMA2 _Use_decl_annotations_ -void DirectX::CreateXMA2(WAVEFORMATEX* wfx, size_t wfxSize, int sampleRate, int channels, int bytesPerBlock, int blockCount, int samplesEncoded) noexcept(false) +void DirectX::CreateXMA2( + WAVEFORMATEX* wfx, + size_t wfxSize, + int sampleRate, + int channels, + int bytesPerBlock, + int blockCount, + int samplesEncoded) noexcept(false) { if (wfxSize < sizeof(XMA2WAVEFORMATEX)) { @@ -645,13 +670,13 @@ bool DirectX::ComputePan(float pan, unsigned int channels, float* matrix) noexce if (channels == 1) { // Mono panning - float left = (pan >= 0) ? (1.f - pan) : 1.f; + float left = 1.f - pan; left = std::min(1.f, left); - left = std::max(-1.f, left); + left = std::max(0.f, left); - float right = (pan <= 0) ? (-pan - 1.f) : 1.f; + float right = pan + 1.f; right = std::min(1.f, right); - right = std::max(-1.f, right); + right = std::max(0.f, right); matrix[0] = left; matrix[1] = right; @@ -709,7 +734,7 @@ void SoundEffectInstanceBase::SetPan(float pan) } -void SoundEffectInstanceBase::Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords) +void SoundEffectInstanceBase::Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords) { if (!voice) return; @@ -717,7 +742,7 @@ void SoundEffectInstanceBase::Apply3D(const AudioListener& listener, const Audio if (!(mFlags & SoundEffectInstance_Use3D)) { DebugTrace("ERROR: Apply3D called for an instance created without SoundEffectInstance_Use3D set\n"); - throw std::exception("Apply3D"); + throw std::runtime_error("Apply3D"); } DWORD dwCalcFlags = X3DAUDIO_CALCULATE_MATRIX | X3DAUDIO_CALCULATE_DOPPLER | X3DAUDIO_CALCULATE_LPF_DIRECT; @@ -796,3 +821,73 @@ void SoundEffectInstanceBase::Apply3D(const AudioListener& listener, const Audio } +//====================================================================================== +// AudioEmitter helper +//====================================================================================== + +namespace +{ + // **Note these constants came from xact3d3.h in the legacy DirectX SDK** + // + // Supported speaker positions, represented as azimuth angles. + // + // Here's a picture of the azimuth angles for the 8 cardinal points, + // seen from above. The emitter's base position is at the origin 0. + // + // FRONT + // | 0 <-- azimuth + // | + // 7pi/4 \ | / pi/4 + // \ | / + // LEFT \|/ RIGHT + // 3pi/2-------0-------pi/2 + // /|\ + // / | \ + // 5pi/4 / | \ 3pi/4 + // | + // | pi + // BACK + // + + constexpr float LEFT_AZIMUTH = 3 * X3DAUDIO_PI / 2; + constexpr float RIGHT_AZIMUTH = X3DAUDIO_PI / 2; + constexpr float FRONT_LEFT_AZIMUTH = 7 * X3DAUDIO_PI / 4; + constexpr float FRONT_RIGHT_AZIMUTH = X3DAUDIO_PI / 4; + constexpr float FRONT_CENTER_AZIMUTH = 0.0f; + constexpr float LOW_FREQUENCY_AZIMUTH = X3DAUDIO_2PI; + constexpr float BACK_LEFT_AZIMUTH = 5 * X3DAUDIO_PI / 4; + constexpr float BACK_RIGHT_AZIMUTH = 3 * X3DAUDIO_PI / 4; + constexpr float BACK_CENTER_AZIMUTH = X3DAUDIO_PI; + + constexpr float c_channelAzimuths[9][8] = + { + /* 0 */ { 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }, + /* 1 */ { 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }, + /* 2 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }, + /* 2.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, LOW_FREQUENCY_AZIMUTH, 0.f, 0.f, 0.f, 0.f, 0.f }, + /* 4.0 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, 0.f, 0.f, 0.f, 0.f }, + /* 4.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, LOW_FREQUENCY_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, 0.f, 0.f, 0.f }, + /* 5.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, FRONT_CENTER_AZIMUTH, LOW_FREQUENCY_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, 0.f, 0.f }, + /* 6.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, FRONT_CENTER_AZIMUTH, LOW_FREQUENCY_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, BACK_CENTER_AZIMUTH, 0.f }, + /* 7.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, FRONT_CENTER_AZIMUTH, LOW_FREQUENCY_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, LEFT_AZIMUTH, RIGHT_AZIMUTH } + }; +} + +void AudioEmitter::EnableDefaultMultiChannel(unsigned int channels, float radius) +{ + if (channels > XAUDIO2_MAX_AUDIO_CHANNELS) + throw std::invalid_argument("Invalid channel count"); + + ChannelCount = channels; + ChannelRadius = radius; + pChannelAzimuths = EmitterAzimuths; + + if (channels <= 8) + { + memcpy(EmitterAzimuths, &c_channelAzimuths[channels][0], sizeof(float) * 8); + } + else + { + memset(EmitterAzimuths, 0, sizeof(float) * size_t(channels)); + } +} diff --git a/Kits/DirectXTK/Audio/SoundCommon.h b/Kits/DirectXTK/Audio/SoundCommon.h index a9696b54..e60c5c35 100644 --- a/Kits/DirectXTK/Audio/SoundCommon.h +++ b/Kits/DirectXTK/Audio/SoundCommon.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SoundCommon.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -63,14 +63,19 @@ namespace DirectX // Helpers for creating various wave format structures - void CreateIntegerPCM(_Out_ WAVEFORMATEX* wfx, int sampleRate, int channels, int sampleBits) noexcept; - void CreateFloatPCM(_Out_ WAVEFORMATEX* wfx, int sampleRate, int channels) noexcept; - void CreateADPCM(_Out_writes_bytes_(wfxSize) WAVEFORMATEX* wfx, size_t wfxSize, int sampleRate, int channels, int samplesPerBlock) noexcept(false); + void CreateIntegerPCM(_Out_ WAVEFORMATEX* wfx, + int sampleRate, int channels, int sampleBits) noexcept; + void CreateFloatPCM(_Out_ WAVEFORMATEX* wfx, + int sampleRate, int channels) noexcept; + void CreateADPCM(_Out_writes_bytes_(wfxSize) WAVEFORMATEX* wfx, size_t wfxSize, + int sampleRate, int channels, int samplesPerBlock) noexcept(false); #ifdef DIRECTX_ENABLE_XWMA - void CreateXWMA(_Out_ WAVEFORMATEX* wfx, int sampleRate, int channels, int blockAlign, int avgBytes, bool wma3) noexcept; + void CreateXWMA(_Out_ WAVEFORMATEX* wfx, + int sampleRate, int channels, int blockAlign, int avgBytes, bool wma3) noexcept; #endif #ifdef DIRECTX_ENABLE_XMA2 - void CreateXMA2(_Out_writes_bytes_(wfxSize) WAVEFORMATEX* wfx, size_t wfxSize, int sampleRate, int channels, int bytesPerBlock, int blockCount, int samplesEncoded) noexcept(false); + void CreateXMA2(_Out_writes_bytes_(wfxSize) WAVEFORMATEX* wfx, size_t wfxSize, + int sampleRate, int channels, int bytesPerBlock, int blockCount, int samplesEncoded) noexcept(false); #endif // Helper for computing pan volume matrix @@ -208,7 +213,7 @@ namespace DirectX } } - void Pause() noexcept + void Pause() noexcept { if (voice && state == PLAYING) { @@ -248,7 +253,7 @@ namespace DirectX if ((mFlags & SoundEffectInstance_NoSetPitch) && pitch != 0.f) { DebugTrace("ERROR: Sound effect instance was created with the NoSetPitch flag\n"); - throw std::exception("SetPitch"); + throw std::runtime_error("SetPitch"); } mPitch = pitch; @@ -264,7 +269,7 @@ namespace DirectX void SetPan(float pan); - void Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords); + void Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords); SoundState GetState(bool autostop) noexcept { @@ -294,6 +299,11 @@ namespace DirectX return static_cast(xstate.BuffersQueued); } + unsigned int GetChannelCount() const noexcept + { + return mDSPSettings.SrcChannelCount; + } + void OnCriticalError() noexcept { if (voice) diff --git a/Kits/DirectXTK/Audio/SoundEffect.cpp b/Kits/DirectXTK/Audio/SoundEffect.cpp index 246b087b..378d08bf 100644 --- a/Kits/DirectXTK/Audio/SoundEffect.cpp +++ b/Kits/DirectXTK/Audio/SoundEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SoundEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -15,6 +15,10 @@ #include #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wnonportable-system-include-path" +#endif + #include #include #endif @@ -352,7 +356,7 @@ void SoundEffect::Impl::Play(float volume, float pitch, float pan) DebugTrace("ERROR: SoundEffect failed (%08X) when submitting buffer:\n", static_cast(hr)); DebugTrace("\tFormat Tag %u, %u channels, %u-bit, %u Hz, %u bytes\n", mWaveFormat->wFormatTag, mWaveFormat->nChannels, mWaveFormat->wBitsPerSample, mWaveFormat->nSamplesPerSec, mAudioBytes); - throw std::exception("SubmitSourceBuffer"); + throw std::runtime_error("SubmitSourceBuffer"); } InterlockedIncrement(&mOneShots); @@ -375,7 +379,7 @@ SoundEffect::SoundEffect(AudioEngine* engine, const wchar_t* waveFileName) { DebugTrace("ERROR: SoundEffect failed (%08X) to load from .wav file \"%ls\"\n", static_cast(hr), waveFileName); - throw std::exception("SoundEffect"); + throw std::runtime_error("SoundEffect"); } #ifdef DIRECTX_ENABLE_SEEK_TABLES @@ -391,7 +395,7 @@ SoundEffect::SoundEffect(AudioEngine* engine, const wchar_t* waveFileName) { DebugTrace("ERROR: SoundEffect failed (%08X) to intialize from .wav file \"%ls\"\n", static_cast(hr), waveFileName); - throw std::exception("SoundEffect"); + throw std::runtime_error("SoundEffect"); } } @@ -409,7 +413,7 @@ SoundEffect::SoundEffect(AudioEngine* engine, std::unique_ptr& wavDat if (FAILED(hr)) { DebugTrace("ERROR: SoundEffect failed (%08X) to intialize\n", static_cast(hr)); - throw std::exception("SoundEffect"); + throw std::runtime_error("SoundEffect"); } } @@ -428,7 +432,7 @@ SoundEffect::SoundEffect(AudioEngine* engine, std::unique_ptr& wavDat if (FAILED(hr)) { DebugTrace("ERROR: SoundEffect failed (%08X) to intialize\n", static_cast(hr)); - throw std::exception("SoundEffect"); + throw std::runtime_error("SoundEffect"); } } @@ -444,7 +448,7 @@ SoundEffect::SoundEffect(AudioEngine* engine, std::unique_ptr& wavDat if (FAILED(hr)) { DebugTrace("ERROR: SoundEffect failed (%08X) to intialize\n", static_cast(hr)); - throw std::exception("SoundEffect"); + throw std::runtime_error("SoundEffect"); } } diff --git a/Kits/DirectXTK/Audio/SoundEffectInstance.cpp b/Kits/DirectXTK/Audio/SoundEffectInstance.cpp index 36920f5c..88e6eae0 100644 --- a/Kits/DirectXTK/Audio/SoundEffectInstance.cpp +++ b/Kits/DirectXTK/Audio/SoundEffectInstance.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SoundEffectInstance.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -215,7 +215,7 @@ void SoundEffectInstance::Impl::Play(bool loop) wfx->wFormatTag, wfx->nChannels, wfx->wBitsPerSample, wfx->nSamplesPerSec, length); #endif mBase.Stop(true, mLooped); - throw std::exception("SubmitSourceBuffer"); + throw std::runtime_error("SubmitSourceBuffer"); } } @@ -316,7 +316,7 @@ void SoundEffectInstance::SetPan(float pan) } -void SoundEffectInstance::Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords) +void SoundEffectInstance::Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords) { pImpl->mBase.Apply3D(listener, emitter, rhcoords); } @@ -335,6 +335,12 @@ SoundState SoundEffectInstance::GetState() noexcept } +unsigned int SoundEffectInstance::GetChannelCount() const noexcept +{ + return pImpl->mBase.GetChannelCount(); +} + + IVoiceNotify* SoundEffectInstance::GetVoiceNotify() const noexcept { return pImpl.get(); diff --git a/Kits/DirectXTK/Audio/SoundStreamInstance.cpp b/Kits/DirectXTK/Audio/SoundStreamInstance.cpp index 8d05bcb9..f3d9ab02 100644 --- a/Kits/DirectXTK/Audio/SoundStreamInstance.cpp +++ b/Kits/DirectXTK/Audio/SoundStreamInstance.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SoundStreamInstance.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -15,6 +15,10 @@ #include "SoundCommon.h" #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wnonportable-system-include-path" +#endif + #include #include #endif @@ -140,7 +144,7 @@ class SoundStreamInstance::Impl : public IVoiceNotify mBufferRead.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mBufferEnd || !mBufferRead) { - throw std::exception("CreateEvent"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } ThrowIfFailed(AllocateStreamingBuffers(wfx)); @@ -232,7 +236,7 @@ class SoundStreamInstance::Impl : public IVoiceNotify return; HANDLE events[] = { mBufferRead.get(), mBufferEnd.get() }; - switch (WaitForMultipleObjectsEx(_countof(events), events, FALSE, 0, FALSE)) + switch (WaitForMultipleObjectsEx(static_cast(std::size(events)), events, FALSE, 0, FALSE)) { case WAIT_TIMEOUT: break; @@ -263,7 +267,7 @@ class SoundStreamInstance::Impl : public IVoiceNotify break; case WAIT_FAILED: - throw std::exception("WaitForMultipleObjects"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForMultipleObjectsEx"); } } @@ -819,7 +823,7 @@ void SoundStreamInstance::SetPan(float pan) } -void SoundStreamInstance::Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords) +void SoundStreamInstance::Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords) { pImpl->mBase.Apply3D(listener, emitter, rhcoords); } @@ -843,6 +847,12 @@ SoundState SoundStreamInstance::GetState() noexcept } +unsigned int SoundStreamInstance::GetChannelCount() const noexcept +{ + return pImpl->mBase.GetChannelCount(); +} + + IVoiceNotify* SoundStreamInstance::GetVoiceNotify() const noexcept { return pImpl.get(); diff --git a/Kits/DirectXTK/Audio/WAVFileReader.cpp b/Kits/DirectXTK/Audio/WAVFileReader.cpp index 0c370639..ea517ffd 100644 --- a/Kits/DirectXTK/Audio/WAVFileReader.cpp +++ b/Kits/DirectXTK/Audio/WAVFileReader.cpp @@ -3,7 +3,7 @@ // // Functions for loading WAV audio files // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Audio/WAVFileReader.h b/Kits/DirectXTK/Audio/WAVFileReader.h index 8a6f4dce..c9191799 100644 --- a/Kits/DirectXTK/Audio/WAVFileReader.h +++ b/Kits/DirectXTK/Audio/WAVFileReader.h @@ -3,7 +3,7 @@ // // Functions for loading WAV audio files // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Audio/WaveBank.cpp b/Kits/DirectXTK/Audio/WaveBank.cpp index aa379c4f..6a2a66eb 100644 --- a/Kits/DirectXTK/Audio/WaveBank.cpp +++ b/Kits/DirectXTK/Audio/WaveBank.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: WaveBank.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -162,7 +162,7 @@ void WaveBank::Impl::Play(unsigned int index, float volume, float pitch, float p if (mStreaming) { DebugTrace("ERROR: One-shots can only be created from an in-memory wave bank\n"); - throw std::exception("WaveBank::Play"); + throw std::runtime_error("WaveBank::Play"); } if (index >= mReader.Count()) @@ -249,7 +249,7 @@ void WaveBank::Impl::Play(unsigned int index, float volume, float pitch, float p DebugTrace("ERROR: WaveBank failed (%08X) when submitting buffer:\n", static_cast(hr)); DebugTrace("\tFormat Tag %u, %u channels, %u-bit, %u Hz, %u bytes\n", wfx->wFormatTag, wfx->nChannels, wfx->wBitsPerSample, wfx->nSamplesPerSec, metadata.lengthBytes); - throw std::exception("SubmitSourceBuffer"); + throw std::runtime_error("SubmitSourceBuffer"); } InterlockedIncrement(&mOneShots); @@ -270,7 +270,7 @@ WaveBank::WaveBank(AudioEngine* engine, const wchar_t* wbFileName) { DebugTrace("ERROR: WaveBank failed (%08X) to intialize from .xwb file \"%ls\"\n", static_cast(hr), wbFileName); - throw std::exception("WaveBank"); + throw std::runtime_error("WaveBank"); } DebugTrace("INFO: WaveBank \"%hs\" with %u entries loaded from .xwb file \"%ls\"\n", @@ -346,7 +346,7 @@ std::unique_ptr WaveBank::CreateInstance(unsigned int index if (pImpl->mStreaming) { DebugTrace("ERROR: SoundEffectInstances can only be created from an in-memory wave bank\n"); - throw std::exception("WaveBank::CreateInstance"); + throw std::runtime_error("WaveBank::CreateInstance"); } if (index >= wb.Count()) @@ -389,7 +389,7 @@ std::unique_ptr WaveBank::CreateStreamInstance(unsigned int if (!pImpl->mStreaming) { DebugTrace("ERROR: SoundStreamInstances can only be created from a streaming wave bank\n"); - throw std::exception("WaveBank::CreateStreamInstance"); + throw std::runtime_error("WaveBank::CreateStreamInstance"); } if (index >= wb.Count()) diff --git a/Kits/DirectXTK/Audio/WaveBankReader.cpp b/Kits/DirectXTK/Audio/WaveBankReader.cpp index 21e3fc02..b6467351 100644 --- a/Kits/DirectXTK/Audio/WaveBankReader.cpp +++ b/Kits/DirectXTK/Audio/WaveBankReader.cpp @@ -3,7 +3,7 @@ // // Functions for loading audio data from Wave Banks // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -17,6 +17,10 @@ #include "SoundCommon.h" #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wnonportable-system-include-path" +#endif + #include #include #endif @@ -151,7 +155,7 @@ namespace case TAG_WMA: { - static const uint32_t aWMABlockAlign[] = + static const uint32_t aWMABlockAlign[17] = { 929, 1487, @@ -173,7 +177,7 @@ namespace }; uint32_t dwBlockAlignIndex = wBlockAlign & 0x1F; - if (dwBlockAlignIndex < _countof(aWMABlockAlign)) + if (dwBlockAlignIndex < 17) return aWMABlockAlign[dwBlockAlignIndex]; } break; @@ -201,7 +205,7 @@ namespace case TAG_WMA: { - static const uint32_t aWMAAvgBytesPerSec[] = + static const uint32_t aWMAAvgBytesPerSec[7] = { 12000, 24000, @@ -214,7 +218,7 @@ namespace // bitrate = entry * 8 uint32_t dwBytesPerSecIndex = wBlockAlign >> 5; - if (dwBytesPerSecIndex < _countof(aWMAAvgBytesPerSec)) + if (dwBytesPerSecIndex < 7) return aWMAAvgBytesPerSec[dwBytesPerSecIndex]; } break; diff --git a/Kits/DirectXTK/Audio/WaveBankReader.h b/Kits/DirectXTK/Audio/WaveBankReader.h index d0adedc9..4c52d5eb 100644 --- a/Kits/DirectXTK/Audio/WaveBankReader.h +++ b/Kits/DirectXTK/Audio/WaveBankReader.h @@ -3,7 +3,7 @@ // // Functions for loading audio data from Wave Banks // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Inc/Audio.h b/Kits/DirectXTK/Inc/Audio.h index 875b701c..76e921ed 100644 --- a/Kits/DirectXTK/Inc/Audio.h +++ b/Kits/DirectXTK/Inc/Audio.h @@ -3,7 +3,7 @@ // // DirectXTK for Audio header // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -12,6 +12,13 @@ #pragma once +#include +#include +#include +#include +#include +#include + #include #include #include @@ -41,19 +48,17 @@ #include #ifndef USING_XAUDIO2_REDIST +#if defined(USING_XAUDIO2_8) && defined(NTDDI_WIN10) && !defined(_M_IX86) +// The xaudio2_8.lib in the Windows 10 SDK for x86 is incorrectly annotated as __cdecl instead of __stdcall, so avoid using it in this case. +#pragma comment(lib,"xaudio2_8.lib") +#else #pragma comment(lib,"xaudio2.lib") #endif +#endif #include -#include -#include -#include -#include -#include - - namespace DirectX { class SoundEffectInstance; @@ -594,6 +599,8 @@ namespace DirectX XMStoreFloat3(reinterpret_cast(&Position), newPos); } } + + void __cdecl EnableDefaultMultiChannel(unsigned int channels, float radius = 1.f); }; @@ -618,12 +625,14 @@ namespace DirectX void __cdecl SetPitch(float pitch); void __cdecl SetPan(float pan); - void __cdecl Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords = true); + void __cdecl Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords = true); bool __cdecl IsLooped() const noexcept; SoundState __cdecl GetState() noexcept; + unsigned int __cdecl GetChannelCount() const noexcept; + IVoiceNotify* __cdecl GetVoiceNotify() const noexcept; private: @@ -662,12 +671,14 @@ namespace DirectX void __cdecl SetPitch(float pitch); void __cdecl SetPan(float pan); - void __cdecl Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords = true); + void __cdecl Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords = true); bool __cdecl IsLooped() const noexcept; SoundState __cdecl GetState() noexcept; + unsigned int __cdecl GetChannelCount() const noexcept; + IVoiceNotify* __cdecl GetVoiceNotify() const noexcept; private: @@ -708,7 +719,7 @@ namespace DirectX void __cdecl SetPitch(float pitch); void __cdecl SetPan(float pan); - void __cdecl Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords = true); + void __cdecl Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords = true); void __cdecl SubmitBuffer(_In_reads_bytes_(audioBytes) const uint8_t* pAudioData, size_t audioBytes); void __cdecl SubmitBuffer(_In_reads_bytes_(audioBytes) const uint8_t* pAudioData, uint32_t offset, size_t audioBytes); @@ -728,6 +739,8 @@ namespace DirectX const WAVEFORMATEX* __cdecl GetFormat() const noexcept; + unsigned int __cdecl GetChannelCount() const noexcept; + private: // Private implementation. class Impl; diff --git a/Kits/DirectXTK/Inc/BufferHelpers.h b/Kits/DirectXTK/Inc/BufferHelpers.h index 5e07ae02..4c8aeae6 100644 --- a/Kits/DirectXTK/Inc/BufferHelpers.h +++ b/Kits/DirectXTK/Inc/BufferHelpers.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: BufferHelpers.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -9,6 +9,9 @@ #pragma once +#include +#include + #if defined(_XBOX_ONE) && defined(_TITLE) #include #include "GraphicsMemory.h" @@ -16,8 +19,6 @@ #include #endif -#include - #include diff --git a/Kits/DirectXTK/Inc/CommonStates.h b/Kits/DirectXTK/Inc/CommonStates.h index c1208dd3..f00e6be8 100644 --- a/Kits/DirectXTK/Inc/CommonStates.h +++ b/Kits/DirectXTK/Inc/CommonStates.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: CommonStates.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Inc/DDSTextureLoader.h b/Kits/DirectXTK/Inc/DDSTextureLoader.h index 4d39c22c..0e4a224f 100644 --- a/Kits/DirectXTK/Inc/DDSTextureLoader.h +++ b/Kits/DirectXTK/Inc/DDSTextureLoader.h @@ -7,7 +7,7 @@ // 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. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -22,6 +22,7 @@ #include #endif +#include #include diff --git a/Kits/DirectXTK/Inc/DirectXHelpers.h b/Kits/DirectXTK/Inc/DirectXHelpers.h index 31919488..d486f43d 100644 --- a/Kits/DirectXTK/Inc/DirectXHelpers.h +++ b/Kits/DirectXTK/Inc/DirectXHelpers.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DirectXHelpers.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -25,11 +25,11 @@ #define IID_GRAPHICS_PPV_ARGS(x) IID_PPV_ARGS(x) #endif +#include +#include #include #include -#include - // // The core Direct3D headers provide the following helper C++ classes // CD3D11_RECT diff --git a/Kits/DirectXTK/Inc/Effects.h b/Kits/DirectXTK/Inc/Effects.h index b224a030..94a1dd4d 100644 --- a/Kits/DirectXTK/Inc/Effects.h +++ b/Kits/DirectXTK/Inc/Effects.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Effects.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -15,9 +15,11 @@ #include #endif -#include +#include #include +#include + namespace DirectX { diff --git a/Kits/DirectXTK/Inc/GamePad.h b/Kits/DirectXTK/Inc/GamePad.h index c9e81ad8..c190408e 100644 --- a/Kits/DirectXTK/Inc/GamePad.h +++ b/Kits/DirectXTK/Inc/GamePad.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: GamePad.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -284,7 +284,8 @@ namespace DirectX #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_GAMES) // Underlying device access - void __cdecl GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept; + _Success_(return != false) + bool __cdecl GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept; #endif // Singleton diff --git a/Kits/DirectXTK/Inc/GeometricPrimitive.h b/Kits/DirectXTK/Inc/GeometricPrimitive.h index 55f4f872..dbe60ba0 100644 --- a/Kits/DirectXTK/Inc/GeometricPrimitive.h +++ b/Kits/DirectXTK/Inc/GeometricPrimitive.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: GeometricPrimitive.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -11,11 +11,13 @@ #include "VertexTypes.h" -#include +#include #include #include #include +#include + namespace DirectX { diff --git a/Kits/DirectXTK/Inc/GraphicsMemory.h b/Kits/DirectXTK/Inc/GraphicsMemory.h index d7885c85..5e84efff 100644 --- a/Kits/DirectXTK/Inc/GraphicsMemory.h +++ b/Kits/DirectXTK/Inc/GraphicsMemory.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: GraphicsMemory.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -15,6 +15,7 @@ #include #endif +#include #include diff --git a/Kits/DirectXTK/Inc/Keyboard.h b/Kits/DirectXTK/Inc/Keyboard.h index 044360c9..7ef7e3ef 100644 --- a/Kits/DirectXTK/Inc/Keyboard.h +++ b/Kits/DirectXTK/Inc/Keyboard.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Keyboard.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Inc/Model.h b/Kits/DirectXTK/Inc/Model.h index a2a44e17..62730f6b 100644 --- a/Kits/DirectXTK/Inc/Model.h +++ b/Kits/DirectXTK/Inc/Model.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Model.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -16,9 +16,7 @@ #include #endif -#include -#include - +#include #include #include #include @@ -28,6 +26,9 @@ #include +#include +#include + namespace DirectX { diff --git a/Kits/DirectXTK/Inc/Mouse.h b/Kits/DirectXTK/Inc/Mouse.h index 51aa3603..dff77353 100644 --- a/Kits/DirectXTK/Inc/Mouse.h +++ b/Kits/DirectXTK/Inc/Mouse.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Mouse.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Inc/PostProcess.h b/Kits/DirectXTK/Inc/PostProcess.h index deba9a16..e27a8052 100644 --- a/Kits/DirectXTK/Inc/PostProcess.h +++ b/Kits/DirectXTK/Inc/PostProcess.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: PostProcess.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -15,10 +15,11 @@ #include #endif -#include #include #include +#include + namespace DirectX { diff --git a/Kits/DirectXTK/Inc/PrimitiveBatch.h b/Kits/DirectXTK/Inc/PrimitiveBatch.h index 96931883..9cdec4c8 100644 --- a/Kits/DirectXTK/Inc/PrimitiveBatch.h +++ b/Kits/DirectXTK/Inc/PrimitiveBatch.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: PrimitiveBatch.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -15,7 +15,9 @@ #include #endif +#include #include +#include #include #include diff --git a/Kits/DirectXTK/Inc/ScreenGrab.h b/Kits/DirectXTK/Inc/ScreenGrab.h index 81f78018..a969ad52 100644 --- a/Kits/DirectXTK/Inc/ScreenGrab.h +++ b/Kits/DirectXTK/Inc/ScreenGrab.h @@ -1,4 +1,3 @@ - //-------------------------------------------------------------------------------------- // File: ScreenGrab.h // @@ -9,7 +8,7 @@ // 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. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -24,9 +23,14 @@ #include #endif -#include #include +#ifdef NTDDI_WIN10_FE +#include +#else +#include +#endif + #pragma comment(lib,"uuid.lib") diff --git a/Kits/DirectXTK/Inc/SimpleMath.h b/Kits/DirectXTK/Inc/SimpleMath.h index 70c2eceb..9f4e17f2 100644 --- a/Kits/DirectXTK/Inc/SimpleMath.h +++ b/Kits/DirectXTK/Inc/SimpleMath.h @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------------- // SimpleMath.h -- Simplified C++ Math wrapper for DirectXMath // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -10,15 +10,15 @@ #pragma once -#if !(defined(_XBOX_ONE) && defined(_TITLE)) && !defined(_GAMING_XBOX) +#if (defined(WIN32) || defined(WINAPI_FAMILY)) && !(defined(_XBOX_ONE) && defined(_TITLE)) && !defined(_GAMING_XBOX) #include #endif +#include +#include +#include #include -#include -#include - #include #include #include @@ -403,7 +403,7 @@ namespace DirectX static void Barycentric(const Vector4& v1, const Vector4& v2, const Vector4& v3, float f, float g, Vector4& result) noexcept; static Vector4 Barycentric(const Vector4& v1, const Vector4& v2, const Vector4& v3, float f, float g) noexcept; - + static void CatmullRom(const Vector4& v1, const Vector4& v2, const Vector4& v3, const Vector4& v4, float t, Vector4& result) noexcept; static Vector4 CatmullRom(const Vector4& v1, const Vector4& v2, const Vector4& v3, const Vector4& v4, float t) noexcept; @@ -474,7 +474,7 @@ namespace DirectX r1.x, r1.y, r1.z, r1.w, r2.x, r2.y, r2.z, r2.w, r3.x, r3.y, r3.z, r3.w) {} - Matrix(const XMFLOAT4X4& M) noexcept { memcpy_s(this, sizeof(float) * 16, &M, sizeof(XMFLOAT4X4)); } + Matrix(const XMFLOAT4X4& M) noexcept { memcpy(this, &M, sizeof(XMFLOAT4X4)); } Matrix(const XMFLOAT3X3& M) noexcept; Matrix(const XMFLOAT4X3& M) noexcept; @@ -927,7 +927,9 @@ namespace DirectX void Unproject(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world, Vector3& result) const noexcept; // Static methods +#if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) static RECT __cdecl ComputeDisplayArea(DXGI_SCALING scaling, UINT backBufferWidth, UINT backBufferHeight, int outputWidth, int outputHeight) noexcept; +#endif static RECT __cdecl ComputeTitleSafeArea(UINT backBufferWidth, UINT backBufferHeight) noexcept; }; diff --git a/Kits/DirectXTK/Inc/SimpleMath.inl b/Kits/DirectXTK/Inc/SimpleMath.inl index 576d4258..442c8ffd 100644 --- a/Kits/DirectXTK/Inc/SimpleMath.inl +++ b/Kits/DirectXTK/Inc/SimpleMath.inl @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------------- // SimpleMath.inl -- Simplified C++ Math wrapper for DirectXMath // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Inc/SpriteBatch.h b/Kits/DirectXTK/Inc/SpriteBatch.h index f9bdcbaf..a30b6526 100644 --- a/Kits/DirectXTK/Inc/SpriteBatch.h +++ b/Kits/DirectXTK/Inc/SpriteBatch.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SpriteBatch.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -13,14 +13,16 @@ #include #else #include -#include +#include #endif -#include -#include +#include #include #include +#include +#include + namespace DirectX { @@ -88,7 +90,7 @@ namespace DirectX private: // Private implementation. - class Impl; + struct Impl; std::unique_ptr pImpl; diff --git a/Kits/DirectXTK/Inc/SpriteFont.h b/Kits/DirectXTK/Inc/SpriteFont.h index a48b61e4..98cf1766 100644 --- a/Kits/DirectXTK/Inc/SpriteFont.h +++ b/Kits/DirectXTK/Inc/SpriteFont.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SpriteFont.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -11,6 +11,8 @@ #include "SpriteBatch.h" +#include + namespace DirectX { diff --git a/Kits/DirectXTK/Inc/VertexTypes.h b/Kits/DirectXTK/Inc/VertexTypes.h index ba3e4033..102dde54 100644 --- a/Kits/DirectXTK/Inc/VertexTypes.h +++ b/Kits/DirectXTK/Inc/VertexTypes.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: VertexTypes.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -15,6 +15,8 @@ #include #endif +#include + #include diff --git a/Kits/DirectXTK/Inc/WICTextureLoader.h b/Kits/DirectXTK/Inc/WICTextureLoader.h index 3ba30045..4c187c44 100644 --- a/Kits/DirectXTK/Inc/WICTextureLoader.h +++ b/Kits/DirectXTK/Inc/WICTextureLoader.h @@ -14,7 +14,7 @@ // 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. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -29,6 +29,7 @@ #include #endif +#include #include #pragma comment(lib,"uuid.lib") diff --git a/Kits/DirectXTK/Inc/XboxDDSTextureLoader.h b/Kits/DirectXTK/Inc/XboxDDSTextureLoader.h index a2d1105b..1d8bb2f0 100644 --- a/Kits/DirectXTK/Inc/XboxDDSTextureLoader.h +++ b/Kits/DirectXTK/Inc/XboxDDSTextureLoader.h @@ -8,7 +8,7 @@ // module in the DirectXTex package or as part of the DirectXTK library to load // these files which use standard Direct3D resource creation APIs. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -23,6 +23,7 @@ #include +#include #include #ifndef DDS_ALPHA_MODE_DEFINED @@ -51,7 +52,7 @@ namespace Xbox _Outptr_opt_ ID3D11Resource** texture, _Outptr_opt_ ID3D11ShaderResourceView** textureView, _Outptr_ void** grfxMemory, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, _In_ bool forceSRGB = false) noexcept; HRESULT __cdecl CreateDDSTextureFromFile( _In_ ID3D11DeviceX* d3dDevice, diff --git a/Kits/DirectXTK/README.md b/Kits/DirectXTK/README.md index 2a9b397c..12f1c41c 100644 --- a/Kits/DirectXTK/README.md +++ b/Kits/DirectXTK/README.md @@ -4,13 +4,13 @@ http://go.microsoft.com/fwlink/?LinkId=248929 -Copyright (c) Microsoft Corporation. All rights reserved. +Copyright (c) Microsoft Corporation. -**September 30, 2020** +**June 9, 2021** This package contains the "DirectX Tool Kit", a collection of helper classes for writing Direct3D 11 C++ code for Universal Windows Platform (UWP) apps for Windows 10, Xbox One, and Win32 desktop applications for Windows 7 Service Pack 1 or later. -This code is designed to build with Visual Studio 2017 ([15.9](https://walbourn.github.io/vs-2017-15-9-update/)), Visual Studio 2019, or clang for Windows v9 or later. It is recommended that you make use of the Windows 10 May 2020 Update SDK ([19041](https://walbourn.github.io/windows-10-may-2020-update-sdk/)). +This code is designed to build with Visual Studio 2017 ([15.9](https://walbourn.github.io/vs-2017-15-9-update/)), Visual Studio 2019, or clang for Windows v9 or later. It is recommended that you make use of the Windows 10 May 2020 Update SDK ([19041](https://walbourn.github.io/windows-10-may-2020-update-sdk/)) or later. These components are designed to work without requiring any content from the legacy DirectX SDK. For details, see [Where is the DirectX SDK?](https://aka.ms/dxsdk). @@ -68,8 +68,6 @@ All content and source code for this package are subject to the terms of the [MI For the latest version of DirectXTK, bug reports, etc. please visit the project site on [GitHub](https://github.com/microsoft/DirectXTK). -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. - ## Release Notes * Starting with the June 2020 release, this library makes use of typed enum bitmask flags per the recommendation of the _C++ Standard_ section *17.5.2.1.3 Bitmask types*. This may have *breaking change* impacts to client code: @@ -81,3 +79,15 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope * The UWP projects and the VS 2019 Win10 classic desktop project include configurations for the ARM64 platform. These require VS 2017 (15.9 update) or VS 2019 to build, with the ARM64 toolset installed. * The ``CompileShaders.cmd`` script must have Windows-style (CRLF) line-endings. If it is changed to Linux-style (LF) line-endings, it can fail to build all the required shaders. + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. + +When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +## Trademarks + +This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies. diff --git a/Kits/DirectXTK/Src/AlignedNew.h b/Kits/DirectXTK/Src/AlignedNew.h index 5a0e9c5c..756c5586 100644 --- a/Kits/DirectXTK/Src/AlignedNew.h +++ b/Kits/DirectXTK/Src/AlignedNew.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: AlignedNew.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -10,9 +10,14 @@ #pragma once -#include +#include +#include #include +#ifdef WIN32 +#include +#endif + namespace DirectX { @@ -21,7 +26,7 @@ namespace DirectX // // Example usage: // - // __declspec(align(16)) struct MyAlignedType : public AlignedNew + // XM_ALIGNED_STRUCT(16) MyAlignedType : public AlignedNew template struct AlignedNew @@ -29,12 +34,18 @@ namespace DirectX // Allocate aligned memory. static void* operator new (size_t size) { - const size_t alignment = __alignof(TDerived); + const size_t alignment = alignof(TDerived); static_assert(alignment > 8, "AlignedNew is only useful for types with > 8 byte alignment. Did you forget a __declspec(align) on TDerived?"); + static_assert(((alignment - 1) & alignment) == 0, "AlignedNew only works with power of two alignment"); +#ifdef WIN32 void* ptr = _aligned_malloc(size, alignment); - +#else + // This C++17 Standard Library function is currently NOT + // implemented for the Microsoft Standard C++ Library. + void* ptr = aligned_alloc(alignment, size); +#endif if (!ptr) throw std::bad_alloc(); @@ -45,13 +56,19 @@ namespace DirectX // Free aligned memory. static void operator delete (void* ptr) { +#ifdef WIN32 _aligned_free(ptr); +#else + free(ptr); +#endif } // Array overloads. static void* operator new[](size_t size) { + static_assert((sizeof(TDerived) % alignof(TDerived) == 0), "AlignedNew expects type to be padded to the alignment"); + return operator new(size); } diff --git a/Kits/DirectXTK/Src/AlphaTestEffect.cpp b/Kits/DirectXTK/Src/AlphaTestEffect.cpp index 8e65cddd..0dea2019 100644 --- a/Kits/DirectXTK/Src/AlphaTestEffect.cpp +++ b/Kits/DirectXTK/Src/AlphaTestEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: AlphaTestEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -146,10 +146,10 @@ AlphaTestEffect::Impl::Impl(_In_ ID3D11Device* device) referenceAlpha(0), vertexColorEnabled(false) { - static_assert(_countof(EffectBase::VertexShaderIndices) == AlphaTestEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == AlphaTestEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == AlphaTestEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == AlphaTestEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == AlphaTestEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == AlphaTestEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == AlphaTestEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == AlphaTestEffectTraits::ShaderPermutationCount, "array/max mismatch"); } @@ -259,7 +259,7 @@ void AlphaTestEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) break; default: - throw std::exception("Unknown alpha test function"); + throw std::runtime_error("Unknown alpha test function"); } // x = compareTo, y = threshold, zw = resultSelector. diff --git a/Kits/DirectXTK/Src/BasicEffect.cpp b/Kits/DirectXTK/Src/BasicEffect.cpp index 5108f5b3..d882be1b 100644 --- a/Kits/DirectXTK/Src/BasicEffect.cpp +++ b/Kits/DirectXTK/Src/BasicEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: BasicEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -392,10 +392,10 @@ BasicEffect::Impl::Impl(_In_ ID3D11Device* device) textureEnabled(false), biasedVertexNormals(false) { - static_assert(_countof(EffectBase::VertexShaderIndices) == BasicEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == BasicEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == BasicEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == BasicEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == BasicEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == BasicEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == BasicEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == BasicEffectTraits::ShaderPermutationCount, "array/max mismatch"); lights.InitializeConstants(constants.specularColorAndPower, constants.lightDirection, constants.lightDiffuseColor, constants.lightSpecularColor); } diff --git a/Kits/DirectXTK/Src/BasicPostProcess.cpp b/Kits/DirectXTK/Src/BasicPostProcess.cpp index 4d275197..6f480ab9 100644 --- a/Kits/DirectXTK/Src/BasicPostProcess.cpp +++ b/Kits/DirectXTK/Src/BasicPostProcess.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: BasicPostProcess.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -29,7 +29,7 @@ namespace constexpr int Dirty_Parameters = 0x02; // Constant buffer layout. Must match the shader! - __declspec(align(16)) struct PostProcessConstants + XM_ALIGNED_STRUCT(16) PostProcessConstants { XMVECTOR sampleOffsets[c_MaxSamples]; XMVECTOR sampleWeights[c_MaxSamples]; @@ -92,7 +92,7 @@ namespace { PostProcess_PSBloomBlur, sizeof(PostProcess_PSBloomBlur) }, }; - static_assert(_countof(pixelShaders) == BasicPostProcess::Effect_Max, "array/max mismatch"); + static_assert(static_cast(std::size(pixelShaders)) == BasicPostProcess::Effect_Max, "array/max mismatch"); // Factory for lazily instantiating shaders. class DeviceResources @@ -209,7 +209,7 @@ BasicPostProcess::Impl::Impl(_In_ ID3D11Device* device) { if (device->GetFeatureLevel() < D3D_FEATURE_LEVEL_10_0) { - throw std::exception("BasicPostProcess requires Feature Level 10.0 or later"); + throw std::runtime_error("BasicPostProcess requires Feature Level 10.0 or later"); } SetDebugObjectName(mConstantBuffer.GetBuffer(), "BasicPostProcess"); @@ -318,7 +318,7 @@ void BasicPostProcess::Impl::DownScale2x2() if (!texWidth || !texHeight) { - throw std::exception("Call SetSourceTexture before setting post-process effect"); + throw std::logic_error("Call SetSourceTexture before setting post-process effect"); } float tu = 1.0f / float(texWidth); @@ -345,7 +345,7 @@ void BasicPostProcess::Impl::DownScale4x4() if (!texWidth || !texHeight) { - throw std::exception("Call SetSourceTexture before setting post-process effect"); + throw std::logic_error("Call SetSourceTexture before setting post-process effect"); } float tu = 1.0f / float(texWidth); @@ -373,7 +373,7 @@ void BasicPostProcess::Impl::GaussianBlur5x5(float multiplier) if (!texWidth || !texHeight) { - throw std::exception("Call SetSourceTexture before setting post-process effect"); + throw std::logic_error("Call SetSourceTexture before setting post-process effect"); } float tu = 1.0f / float(texWidth); @@ -429,7 +429,7 @@ void BasicPostProcess::Impl::Bloom(bool horizontal, float size, float brightnes if (!texWidth || !texHeight) { - throw std::exception("Call SetSourceTexture before setting post-process effect"); + throw std::logic_error("Call SetSourceTexture before setting post-process effect"); } float tu = 0.f; @@ -510,7 +510,7 @@ void BasicPostProcess::Process( void BasicPostProcess::SetEffect(Effect fx) { if (fx >= Effect_Max) - throw std::out_of_range("Effect not defined"); + throw std::invalid_argument("Effect not defined"); pImpl->fx = fx; @@ -573,7 +573,7 @@ void BasicPostProcess::SetSourceTexture(_In_opt_ ID3D11ShaderResourceView* value case D3D11_RESOURCE_DIMENSION_BUFFER: case D3D11_RESOURCE_DIMENSION_TEXTURE3D: default: - throw std::exception("Unsupported texture type"); + throw std::invalid_argument("Unsupported texture type"); } } else diff --git a/Kits/DirectXTK/Src/Bezier.h b/Kits/DirectXTK/Src/Bezier.h index 367de975..d1d66ed2 100644 --- a/Kits/DirectXTK/Src/Bezier.h +++ b/Kits/DirectXTK/Src/Bezier.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Bezier.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -51,9 +51,6 @@ namespace Bezier template inline T CubicTangent(T const& p1, T const& p2, T const& p3, T const& p4, float t) noexcept { - using DirectX::operator*; - using DirectX::operator+; - return p1 * (-1 + 2 * t - t * t) + p2 * (1 - 4 * t + 3 * t * t) + p3 * (2 * t - 3 * t * t) + diff --git a/Kits/DirectXTK/Src/BinaryReader.cpp b/Kits/DirectXTK/Src/BinaryReader.cpp index 6c7c5a79..d8947c82 100644 --- a/Kits/DirectXTK/Src/BinaryReader.cpp +++ b/Kits/DirectXTK/Src/BinaryReader.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: BinaryReader.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -27,7 +27,7 @@ BinaryReader::BinaryReader(_In_z_ wchar_t const* fileName) noexcept(false) : { DebugTrace("ERROR: BinaryReader failed (%08X) to load '%ls'\n", static_cast(hr), fileName); - throw std::exception("BinaryReader"); + throw std::runtime_error("BinaryReader"); } mPos = mOwnedData.get(); @@ -44,8 +44,16 @@ BinaryReader::BinaryReader(_In_reads_bytes_(dataSize) uint8_t const* dataBlob, s // Reads from the filesystem into memory. -HRESULT BinaryReader::ReadEntireFile(_In_z_ wchar_t const* fileName, _Inout_ std::unique_ptr& data, _Out_ size_t* dataSize) +HRESULT BinaryReader::ReadEntireFile( + _In_z_ wchar_t const* fileName, + _Inout_ std::unique_ptr& data, + _Out_ size_t* dataSize) { + if (!fileName || !dataSize) + return E_INVALIDARG; + + *dataSize = 0; + // Open the file. #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) ScopedHandle hFile(safe_handle(CreateFile2(fileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr))); diff --git a/Kits/DirectXTK/Src/BinaryReader.h b/Kits/DirectXTK/Src/BinaryReader.h index 97ee5ab2..562b227e 100644 --- a/Kits/DirectXTK/Src/BinaryReader.h +++ b/Kits/DirectXTK/Src/BinaryReader.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: BinaryReader.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -48,7 +48,7 @@ namespace DirectX throw std::overflow_error("ReadArray"); if (newPos > mEnd) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto result = reinterpret_cast(mPos); diff --git a/Kits/DirectXTK/Src/BufferHelpers.cpp b/Kits/DirectXTK/Src/BufferHelpers.cpp index f865bc1a..71251596 100644 --- a/Kits/DirectXTK/Src/BufferHelpers.cpp +++ b/Kits/DirectXTK/Src/BufferHelpers.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: BufferHelpers.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -361,7 +361,7 @@ void Internal::ConstantBufferBase::CreateBuffer( ID3D11Buffer** pBuffer) { if (!pBuffer) - throw std::invalid_argument("ConstantBuffer"); + throw std::invalid_argument("ConstantBuffer needs valid buffer parameter"); *pBuffer = nullptr; diff --git a/Kits/DirectXTK/Src/CommonStates.cpp b/Kits/DirectXTK/Src/CommonStates.cpp index 2a50a31a..8312c627 100644 --- a/Kits/DirectXTK/Src/CommonStates.cpp +++ b/Kits/DirectXTK/Src/CommonStates.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: CommonStates.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/DDSTextureLoader.cpp b/Kits/DirectXTK/Src/DDSTextureLoader.cpp index f4bff58d..94714bd8 100644 --- a/Kits/DirectXTK/Src/DDSTextureLoader.cpp +++ b/Kits/DirectXTK/Src/DDSTextureLoader.cpp @@ -7,7 +7,7 @@ // 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. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTK/Src/DGSLEffect.cpp b/Kits/DirectXTK/Src/DGSLEffect.cpp index 1bb9bce1..0687ef9a 100644 --- a/Kits/DirectXTK/Src/DGSLEffect.cpp +++ b/Kits/DirectXTK/Src/DGSLEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DGSLEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -101,7 +101,7 @@ namespace static_assert((sizeof(MiscConstants) % 16) == 0, "CB size not padded correctly"); static_assert((sizeof(BoneConstants) % 16) == 0, "CB size not padded correctly"); - __declspec(align(16)) struct DGSLEffectConstants + XM_ALIGNED_STRUCT(16) DGSLEffectConstants { MaterialConstants material; LightConstants light; @@ -232,8 +232,8 @@ class DGSLEffect::Impl : public AlignedNew mPixelShader(pixelShader), mDeviceResources(deviceResourcesPool.DemandCreate(device)) { - static_assert(_countof(DGSLEffectTraits::VertexShaderBytecode) == DGSLEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(DGSLEffectTraits::PixelShaderBytecode) == DGSLEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(DGSLEffectTraits::VertexShaderBytecode)) == DGSLEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(DGSLEffectTraits::PixelShaderBytecode)) == DGSLEffectTraits::PixelShaderCount, "array/max mismatch"); XMMATRIX id = XMMatrixIdentity(); world = id; @@ -773,7 +773,7 @@ void XM_CALLCONV DGSLEffect::SetAmbientLightColor(FXMVECTOR value) void DGSLEffect::SetLightEnabled(int whichLight, bool value) { if (whichLight < 0 || whichLight >= MaxDirectionalLights) - throw std::out_of_range("whichLight parameter out of range"); + throw std::invalid_argument("whichLight parameter invalid"); if (pImpl->lightEnabled[whichLight] == value) return; @@ -801,7 +801,7 @@ void DGSLEffect::SetLightEnabled(int whichLight, bool value) void XM_CALLCONV DGSLEffect::SetLightDirection(int whichLight, FXMVECTOR value) { if (whichLight < 0 || whichLight >= MaxDirectionalLights) - throw std::out_of_range("whichLight parameter out of range"); + throw std::invalid_argument("whichLight parameter invalid"); // DGSL effects lights do not negate the direction like BasicEffect pImpl->constants.light.LightDirection[whichLight] = XMVectorNegate(value); @@ -813,7 +813,7 @@ void XM_CALLCONV DGSLEffect::SetLightDirection(int whichLight, FXMVECTOR value) void XM_CALLCONV DGSLEffect::SetLightDiffuseColor(int whichLight, FXMVECTOR value) { if (whichLight < 0 || whichLight >= MaxDirectionalLights) - throw std::out_of_range("whichLight parameter out of range"); + throw std::invalid_argument("whichLight parameter invalid"); pImpl->lightDiffuseColor[whichLight] = value; @@ -829,7 +829,7 @@ void XM_CALLCONV DGSLEffect::SetLightDiffuseColor(int whichLight, FXMVECTOR valu void XM_CALLCONV DGSLEffect::SetLightSpecularColor(int whichLight, FXMVECTOR value) { if (whichLight < 0 || whichLight >= MaxDirectionalLights) - throw std::out_of_range("whichLight parameter out of range"); + throw std::invalid_argument("whichLight parameter invalid"); pImpl->lightSpecularColor[whichLight] = value; @@ -870,7 +870,7 @@ void DGSLEffect::SetTexture(_In_opt_ ID3D11ShaderResourceView* value) void DGSLEffect::SetTexture(int whichTexture, _In_opt_ ID3D11ShaderResourceView* value) { if (whichTexture < 0 || whichTexture >= MaxTextures) - throw std::out_of_range("whichTexture parameter out of range"); + throw std::invalid_argument("whichTexture parameter invalid"); pImpl->textures[whichTexture] = value; } @@ -889,7 +889,7 @@ void DGSLEffect::SetWeightsPerVertex(int value) (value != 2) && (value != 4)) { - throw std::out_of_range("WeightsPerVertex must be 1, 2, or 4"); + throw std::invalid_argument("WeightsPerVertex must be 1, 2, or 4"); } pImpl->weightsPerVertex = value; @@ -899,10 +899,10 @@ void DGSLEffect::SetWeightsPerVertex(int value) void DGSLEffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) { if (!pImpl->weightsPerVertex) - throw std::exception("Skinning not enabled for this effect"); + throw std::runtime_error("Skinning not enabled for this effect"); if (count > MaxBones) - throw std::out_of_range("count parameter out of range"); + throw std::invalid_argument("count parameter exceeds MaxBones"); auto boneConstant = pImpl->constants.bones.Bones; diff --git a/Kits/DirectXTK/Src/DGSLEffectFactory.cpp b/Kits/DirectXTK/Src/DGSLEffectFactory.cpp index 652d6542..845885da 100644 --- a/Kits/DirectXTK/Src/DGSLEffectFactory.cpp +++ b/Kits/DirectXTK/Src/DGSLEffectFactory.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DGSLEffectFactory.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -77,7 +77,7 @@ std::shared_ptr DGSLEffectFactory::Impl::CreateEffect(DGSLEffectFactory { if (info.enableDualTexture) { - throw std::exception("DGSLEffect does not support multiple texcoords"); + throw std::runtime_error("DGSLEffect does not support multiple texcoords"); } if (mSharing && info.name && *info.name) @@ -320,7 +320,7 @@ std::shared_ptr DGSLEffectFactory::Impl::CreateDGSLEffect(DGSLEffectFac effect->SetTextureEnabled(true); } - for (size_t j = 0; j < _countof(info.textures); ++j) + for (size_t j = 0; j < std::size(info.textures); ++j) { if (info.textures[j] && *info.textures[j]) { @@ -355,7 +355,7 @@ _Use_decl_annotations_ void DGSLEffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) { if (!name || !textureView) - throw std::exception("invalid arguments"); + throw std::invalid_argument("name and textureView parameters can't be null"); #if defined(_XBOX_ONE) && defined(_TITLE) UNREFERENCED_PARAMETER(deviceContext); @@ -383,14 +383,15 @@ void DGSLEffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCon if (!GetFileAttributesExW(fullName, GetFileExInfoStandard, &fileAttr)) { DebugTrace("ERROR: DGSLEffectFactory could not find texture file '%ls'\n", name); - throw std::exception("CreateTexture"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "DGSLEffectFactory::CreateTexture"); } } - wchar_t ext[_MAX_EXT]; + wchar_t ext[_MAX_EXT] = {}; _wsplitpath_s(name, nullptr, 0, nullptr, 0, nullptr, 0, ext, _MAX_EXT); + bool isdds = _wcsicmp(ext, L".dds") == 0; - if (_wcsicmp(ext, L".dds") == 0) + if (isdds) { HRESULT hr = CreateDDSTextureFromFileEx( mDevice.Get(), fullName, 0, @@ -400,7 +401,7 @@ void DGSLEffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCon { DebugTrace("ERROR: CreateDDSTextureFromFile failed (%08X) for '%ls'\n", static_cast(hr), fullName); - throw std::exception("CreateDDSTextureFromFile"); + throw std::runtime_error("DGSLEffectFactory::CreateDDSTextureFromFile"); } } #if !defined(_XBOX_ONE) || !defined(_TITLE) @@ -415,7 +416,7 @@ void DGSLEffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCon { DebugTrace("ERROR: CreateWICTextureFromFile failed (%08X) for '%ls'\n", static_cast(hr), fullName); - throw std::exception("CreateWICTextureFromFile"); + throw std::runtime_error("DGSLEffectFactory::CreateWICTextureFromFile"); } } #endif @@ -429,7 +430,7 @@ void DGSLEffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCon { DebugTrace("ERROR: CreateWICTextureFromFile failed (%08X) for '%ls'\n", static_cast(hr), fullName); - throw std::exception("CreateWICTextureFromFile"); + throw std::runtime_error("DGSLEffectFactory::CreateWICTextureFromFile"); } } @@ -447,7 +448,7 @@ _Use_decl_annotations_ void DGSLEffectFactory::Impl::CreatePixelShader(const wchar_t* name, ID3D11PixelShader** pixelShader) { if (!name || !pixelShader) - throw std::exception("invalid arguments"); + throw std::invalid_argument("name and pixelShader parameters can't be null"); auto it = mShaderCache.find(name); @@ -471,7 +472,7 @@ void DGSLEffectFactory::Impl::CreatePixelShader(const wchar_t* name, ID3D11Pixel if (!GetFileAttributesExW(fullName, GetFileExInfoStandard, &fileAttr)) { DebugTrace("ERROR: DGSLEffectFactory could not find shader file '%ls'\n", name); - throw std::exception("CreatePixelShader"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "DGSLEffectFactory::CreatePixelShader"); } } @@ -482,7 +483,7 @@ void DGSLEffectFactory::Impl::CreatePixelShader(const wchar_t* name, ID3D11Pixel { DebugTrace("ERROR: CreatePixelShader failed (%08X) to load shader file '%ls'\n", static_cast(hr), fullName); - throw std::exception("CreatePixelShader"); + throw std::runtime_error("DGSLEffectFactory::CreatePixelShader"); } ThrowIfFailed( diff --git a/Kits/DirectXTK/Src/DebugEffect.cpp b/Kits/DirectXTK/Src/DebugEffect.cpp index 6abad3a9..d0e1c534 100644 --- a/Kits/DirectXTK/Src/DebugEffect.cpp +++ b/Kits/DirectXTK/Src/DebugEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DebugEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -169,13 +169,13 @@ DebugEffect::Impl::Impl(_In_ ID3D11Device* device) { if (device->GetFeatureLevel() < D3D_FEATURE_LEVEL_10_0) { - throw std::exception("DebugEffect requires Feature Level 10.0 or later"); + throw std::runtime_error("DebugEffect requires Feature Level 10.0 or later"); } - static_assert(_countof(EffectBase::VertexShaderIndices) == DebugEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == DebugEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == DebugEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == DebugEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == DebugEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == DebugEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == DebugEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == DebugEffectTraits::ShaderPermutationCount, "array/max mismatch"); static const XMVECTORF32 s_lower = { { { 0.f, 0.f, 0.f, 1.f } } }; diff --git a/Kits/DirectXTK/Src/DemandCreate.h b/Kits/DirectXTK/Src/DemandCreate.h index 9403f5ae..2aba02f7 100644 --- a/Kits/DirectXTK/Src/DemandCreate.h +++ b/Kits/DirectXTK/Src/DemandCreate.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DemandCreate.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -22,14 +22,20 @@ namespace DirectX T* result = comPtr.Get(); // Double-checked lock pattern. +#ifdef _MSC_VER MemoryBarrier(); +#elif defined(__GNUC__) + __sync_synchronize(); +#else +#error Unknown memory barrier syntax +#endif if (!result) { std::lock_guard lock(mutex); result = comPtr.Get(); - + if (!result) { // Create the new object. @@ -37,7 +43,11 @@ namespace DirectX createFunc(&result) ); +#ifdef _MSC_VER MemoryBarrier(); +#elif defined(__GNUC__) + __sync_synchronize(); +#endif comPtr.Attach(result); } diff --git a/Kits/DirectXTK/Src/DirectXHelpers.cpp b/Kits/DirectXTK/Src/DirectXHelpers.cpp index d1d3d0a1..538faf89 100644 --- a/Kits/DirectXTK/Src/DirectXHelpers.cpp +++ b/Kits/DirectXTK/Src/DirectXHelpers.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DirectXHelpers.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/DualPostProcess.cpp b/Kits/DirectXTK/Src/DualPostProcess.cpp index 05c4587b..f582b39c 100644 --- a/Kits/DirectXTK/Src/DualPostProcess.cpp +++ b/Kits/DirectXTK/Src/DualPostProcess.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DualPostProcess.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -29,7 +29,7 @@ namespace constexpr int Dirty_Parameters = 0x02; // Constant buffer layout. Must match the shader! - __declspec(align(16)) struct PostProcessConstants + XM_ALIGNED_STRUCT(16) PostProcessConstants { XMVECTOR sampleOffsets[c_MaxSamples]; XMVECTOR sampleWeights[c_MaxSamples]; @@ -68,7 +68,7 @@ namespace { PostProcess_PSBloomCombine, sizeof(PostProcess_PSBloomCombine) }, }; - static_assert(_countof(pixelShaders) == DualPostProcess::Effect_Max, "array/max mismatch"); + static_assert(static_cast(std::size(pixelShaders)) == DualPostProcess::Effect_Max, "array/max mismatch"); // Factory for lazily instantiating shaders. class DeviceResources @@ -176,7 +176,7 @@ DualPostProcess::Impl::Impl(_In_ ID3D11Device* device) { if (device->GetFeatureLevel() < D3D_FEATURE_LEVEL_10_0) { - throw std::exception("DualPostProcess requires Feature Level 10.0 or later"); + throw std::runtime_error("DualPostProcess requires Feature Level 10.0 or later"); } SetDebugObjectName(mConstantBuffer.GetBuffer(), "DualPostProcess"); @@ -308,7 +308,7 @@ void DualPostProcess::Process( void DualPostProcess::SetEffect(Effect fx) { if (fx >= Effect_Max) - throw std::out_of_range("Effect not defined"); + throw std::invalid_argument("Effect not defined"); pImpl->fx = fx; pImpl->SetDirtyFlag(); diff --git a/Kits/DirectXTK/Src/DualTextureEffect.cpp b/Kits/DirectXTK/Src/DualTextureEffect.cpp index 1b0d9a81..786ff2a8 100644 --- a/Kits/DirectXTK/Src/DualTextureEffect.cpp +++ b/Kits/DirectXTK/Src/DualTextureEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DualTextureEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -128,10 +128,10 @@ DualTextureEffect::Impl::Impl(_In_ ID3D11Device* device) : EffectBase(device), vertexColorEnabled(false) { - static_assert(_countof(EffectBase::VertexShaderIndices) == DualTextureEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == DualTextureEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == DualTextureEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == DualTextureEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == DualTextureEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == DualTextureEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == DualTextureEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == DualTextureEffectTraits::ShaderPermutationCount, "array/max mismatch"); } diff --git a/Kits/DirectXTK/Src/EffectCommon.cpp b/Kits/DirectXTK/Src/EffectCommon.cpp index 6dd2395f..52e76b30 100644 --- a/Kits/DirectXTK/Src/EffectCommon.cpp +++ b/Kits/DirectXTK/Src/EffectCommon.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: EffectCommon.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -340,7 +340,7 @@ void EffectLights::ValidateLightIndex(int whichLight) { if (whichLight < 0 || whichLight >= MaxDirectionalLights) { - throw std::out_of_range("whichLight parameter out of range"); + throw std::invalid_argument("whichLight parameter invalid"); } } diff --git a/Kits/DirectXTK/Src/EffectCommon.h b/Kits/DirectXTK/Src/EffectCommon.h index f8f55722..549e0fac 100644 --- a/Kits/DirectXTK/Src/EffectCommon.h +++ b/Kits/DirectXTK/Src/EffectCommon.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: EffectCommon.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/EffectFactory.cpp b/Kits/DirectXTK/Src/EffectFactory.cpp index a45ef262..6e506ca4 100644 --- a/Kits/DirectXTK/Src/EffectFactory.cpp +++ b/Kits/DirectXTK/Src/EffectFactory.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: EffectFactory.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -357,7 +357,7 @@ _Use_decl_annotations_ void EffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) { if (!name || !textureView) - throw std::exception("invalid arguments"); + throw std::invalid_argument("name and textureView parameters can't be null"); #if defined(_XBOX_ONE) && defined(_TITLE) UNREFERENCED_PARAMETER(deviceContext); @@ -385,14 +385,15 @@ void EffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext if (!GetFileAttributesExW(fullName, GetFileExInfoStandard, &fileAttr)) { DebugTrace("ERROR: EffectFactory could not find texture file '%ls'\n", name); - throw std::exception("CreateTexture"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "EffectFactory::CreateTexture"); } } - wchar_t ext[_MAX_EXT]; + wchar_t ext[_MAX_EXT] = {}; _wsplitpath_s(name, nullptr, 0, nullptr, 0, nullptr, 0, ext, _MAX_EXT); + bool isdds = _wcsicmp(ext, L".dds") == 0; - if (_wcsicmp(ext, L".dds") == 0) + if (isdds) { HRESULT hr = CreateDDSTextureFromFileEx( mDevice.Get(), fullName, 0, @@ -402,7 +403,7 @@ void EffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext { DebugTrace("ERROR: CreateDDSTextureFromFile failed (%08X) for '%ls'\n", static_cast(hr), fullName); - throw std::exception("CreateDDSTextureFromFile"); + throw std::runtime_error("EffectFactory::CreateDDSTextureFromFile"); } } #if !defined(_XBOX_ONE) || !defined(_TITLE) @@ -417,7 +418,7 @@ void EffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext { DebugTrace("ERROR: CreateWICTextureFromFile failed (%08X) for '%ls'\n", static_cast(hr), fullName); - throw std::exception("CreateWICTextureFromFile"); + throw std::runtime_error("EffectFactory::CreateWICTextureFromFile"); } } #endif @@ -431,7 +432,7 @@ void EffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext { DebugTrace("ERROR: CreateWICTextureFromFile failed (%08X) for '%ls'\n", static_cast(hr), fullName); - throw std::exception("CreateWICTextureFromFile"); + throw std::runtime_error("EffectFactory::CreateWICTextureFromFile"); } } diff --git a/Kits/DirectXTK/Src/EnvironmentMapEffect.cpp b/Kits/DirectXTK/Src/EnvironmentMapEffect.cpp index 9ea1c818..31c561fe 100644 --- a/Kits/DirectXTK/Src/EnvironmentMapEffect.cpp +++ b/Kits/DirectXTK/Src/EnvironmentMapEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: EnvironmentMapEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -65,7 +65,6 @@ class EnvironmentMapEffect::Impl : public EffectBase bool specularEnabled; bool biasedVertexNormals; EnvironmentMapEffect::Mapping mapping; - bool shaderModel4; EffectLights lights; @@ -353,10 +352,10 @@ EnvironmentMapEffect::Impl::Impl(_In_ ID3D11Device* device) biasedVertexNormals(false), mapping(Mapping_Cube) { - static_assert(_countof(EffectBase::VertexShaderIndices) == EnvironmentMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == EnvironmentMapEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == EnvironmentMapEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == EnvironmentMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == EnvironmentMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == EnvironmentMapEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == EnvironmentMapEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == EnvironmentMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); constants.environmentMapAmount = 1; constants.fresnelFactor = 1; @@ -572,7 +571,7 @@ void EnvironmentMapEffect::SetLightingEnabled(bool value) { if (!value) { - throw std::exception("EnvironmentMapEffect does not support turning off lighting"); + throw std::invalid_argument("EnvironmentMapEffect does not support turning off lighting"); } } @@ -685,7 +684,7 @@ void EnvironmentMapEffect::SetMode(EnvironmentMapEffect::Mapping mapping) { if (pImpl->GetDeviceFeatureLevel() < D3D_FEATURE_LEVEL_10_0) { - throw std::exception("Dual Parabola requires Feature Level 10.0 or later"); + throw std::runtime_error("Dual Parabola requires Feature Level 10.0 or later"); } } diff --git a/Kits/DirectXTK/Src/GamePad.cpp b/Kits/DirectXTK/Src/GamePad.cpp index dd089dfc..a2b0b383 100644 --- a/Kits/DirectXTK/Src/GamePad.cpp +++ b/Kits/DirectXTK/Src/GamePad.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: GamePad.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -100,7 +100,7 @@ class GamePad::Impl { if (s_gamePad) { - throw std::exception("GamePad is a singleton"); + throw std::logic_error("GamePad is a singleton"); } s_gamePad = this; @@ -129,10 +129,9 @@ class GamePad::Impl { if (mGameInput) { - HRESULT hr = mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX); - if (FAILED(hr)) + if (!mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX)) { - DebugTrace("ERROR: GameInput::UnregisterCallback [gamepad] failed (%08X)", static_cast(hr)); + DebugTrace("ERROR: GameInput::UnregisterCallback [gamepad] failed"); } } @@ -289,10 +288,11 @@ class GamePad::Impl } } - void GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept + _Success_(return != false) + bool GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept { if (!device) - return; + return false; if (player == c_MostRecent) player = mMostRecentGamepad; @@ -306,8 +306,11 @@ class GamePad::Impl { dev->AddRef(); *device = dev; + return true; } } + + return false; } GamePad* mOwner; @@ -416,7 +419,7 @@ class GamePad::Impl if (s_gamePad) { - throw std::exception("GamePad is a singleton"); + throw std::logic_error("GamePad is a singleton"); } s_gamePad = this; @@ -424,7 +427,7 @@ class GamePad::Impl mChanged.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mChanged) { - throw std::exception("CreateEventEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_Gaming_Input_Gamepad).Get(), mStatics.GetAddressOf())); @@ -899,7 +902,7 @@ class GamePad::Impl if (s_gamePad) { - throw std::exception("GamePad is a singleton"); + throw std::logic_error("GamePad is a singleton"); } s_gamePad = this; @@ -907,7 +910,7 @@ class GamePad::Impl mChanged.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mChanged) { - throw std::exception("CreateEventEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_Xbox_Input_Gamepad).Get(), mStatics.GetAddressOf())); @@ -1200,7 +1203,7 @@ class GamePad::Impl { if (empty >= MAX_PLAYER_COUNT) { - throw std::exception("Too many gamepads found"); + throw std::runtime_error("Too many gamepads found"); } mGamePad[empty] = pad; @@ -1254,7 +1257,7 @@ class GamePad::Impl if (s_gamePad) { - throw std::exception("GamePad is a singleton"); + throw std::logic_error("GamePad is a singleton"); } s_gamePad = this; @@ -1648,9 +1651,10 @@ void GamePad::RegisterEvents(HANDLE ctrlChanged) noexcept pImpl->mCtrlChanged = (!ctrlChanged) ? INVALID_HANDLE_VALUE : ctrlChanged; } -void GamePad::GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept +_Success_(return != false) +bool GamePad::GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept { - pImpl->GetDevice(player, device); + return pImpl->GetDevice(player, device); } #elif ((_WIN32_WINNT >= _WIN32_WINNT_WIN10) && !defined(_GAMING_DESKTOP)) || defined(_XBOX_ONE) void GamePad::RegisterEvents(HANDLE ctrlChanged, HANDLE userChanged) noexcept @@ -1664,7 +1668,7 @@ void GamePad::RegisterEvents(HANDLE ctrlChanged, HANDLE userChanged) noexcept GamePad& GamePad::Get() { if (!Impl::s_gamePad || !Impl::s_gamePad->mOwner) - throw std::exception("GamePad is a singleton"); + throw std::logic_error("GamePad singleton not created"); return *Impl::s_gamePad->mOwner; } diff --git a/Kits/DirectXTK/Src/GeometricPrimitive.cpp b/Kits/DirectXTK/Src/GeometricPrimitive.cpp index 692b1895..3d0e6b87 100644 --- a/Kits/DirectXTK/Src/GeometricPrimitive.cpp +++ b/Kits/DirectXTK/Src/GeometricPrimitive.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: GeometricPrimitive.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -148,10 +148,10 @@ _Use_decl_annotations_ void GeometricPrimitive::Impl::Initialize(ID3D11DeviceContext* deviceContext, const VertexCollection& vertices, const IndexCollection& indices) { if (vertices.size() >= USHRT_MAX) - throw std::exception("Too many vertices for 16-bit index buffer"); + throw std::out_of_range("Too many vertices for 16-bit index buffer"); if (indices.size() > UINT32_MAX) - throw std::exception("Too many indices"); + throw std::out_of_range("Too many indices"); mResources = sharedResourcesPool.DemandCreate(deviceContext); @@ -747,20 +747,20 @@ std::unique_ptr GeometricPrimitive::CreateCustom( { // Extra validation if (vertices.empty() || indices.empty()) - throw std::exception("Requires both vertices and indices"); + throw std::invalid_argument("Requires both vertices and indices"); if (indices.size() % 3) - throw std::exception("Expected triangular faces"); + throw std::invalid_argument("Expected triangular faces"); size_t nVerts = vertices.size(); if (nVerts >= USHRT_MAX) - throw std::exception("Too many vertices for 16-bit index buffer"); + throw std::out_of_range("Too many vertices for 16-bit index buffer"); for (auto it = indices.cbegin(); it != indices.cend(); ++it) { if (*it >= nVerts) { - throw std::exception("Index not in vertices list"); + throw std::out_of_range("Index not in vertices list"); } } diff --git a/Kits/DirectXTK/Src/Geometry.cpp b/Kits/DirectXTK/Src/Geometry.cpp index a2c116f9..943727cb 100644 --- a/Kits/DirectXTK/Src/Geometry.cpp +++ b/Kits/DirectXTK/Src/Geometry.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Geometry.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -24,7 +24,7 @@ namespace { // Use >=, not > comparison, because some D3D level 9_x hardware does not support 0xFFFF index values. if (value >= USHRT_MAX) - throw std::exception("Index value out of range: cannot tesselate primitive so finely"); + throw std::out_of_range("Index value out of range: cannot tesselate primitive so finely"); } @@ -150,7 +150,7 @@ void DirectX::ComputeSphere(VertexCollection& vertices, IndexCollection& indices indices.clear(); if (tessellation < 3) - throw std::out_of_range("tesselation parameter out of range"); + throw std::invalid_argument("tesselation parameter must be at least 3"); size_t verticalSegments = tessellation; size_t horizontalSegments = tessellation * 2; @@ -372,7 +372,7 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi vertices.reserve(vertexPositions.size()); for (auto it = vertexPositions.begin(); it != vertexPositions.end(); ++it) { - auto vertexValue = *it; + const auto& vertexValue = *it; auto normal = XMVector3Normalize(XMLoadFloat3(&vertexValue)); auto pos = XMVectorScale(normal, radius); @@ -472,7 +472,7 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi // poles, but reduce stretching. auto fixPole = [&](size_t poleIndex) { - auto poleVertex = vertices[poleIndex]; + const auto& poleVertex = vertices[poleIndex]; bool overwrittenPoleVertex = false; // overwriting the original pole vertex saves us one vertex for (size_t i = 0; i < indices.size(); i += 3) @@ -617,7 +617,7 @@ void DirectX::ComputeCylinder(VertexCollection& vertices, IndexCollection& indic indices.clear(); if (tessellation < 3) - throw std::out_of_range("tesselation parameter out of range"); + throw std::invalid_argument("tesselation parameter must be at least 3"); height /= 2; @@ -666,7 +666,7 @@ void DirectX::ComputeCone(VertexCollection& vertices, IndexCollection& indices, indices.clear(); if (tessellation < 3) - throw std::out_of_range("tesselation parameter out of range"); + throw std::invalid_argument("tesselation parameter must be at least 3"); height /= 2; @@ -720,7 +720,7 @@ void DirectX::ComputeTorus(VertexCollection& vertices, IndexCollection& indices, indices.clear(); if (tessellation < 3) - throw std::out_of_range("tesselation parameter out of range"); + throw std::invalid_argument("tesselation parameter must be at least 3"); size_t stride = tessellation + 1; @@ -799,7 +799,7 @@ void DirectX::ComputeTetrahedron(VertexCollection& vertices, IndexCollection& in 1, 3, 2, }; - for (size_t j = 0; j < _countof(faces); j += 3) + for (size_t j = 0; j < std::size(faces); j += 3) { uint32_t v0 = faces[j]; uint32_t v1 = faces[j + 1]; @@ -865,7 +865,7 @@ void DirectX::ComputeOctahedron(VertexCollection& vertices, IndexCollection& ind 5, 0, 3 }; - for (size_t j = 0; j < _countof(faces); j += 3) + for (size_t j = 0; j < std::size(faces); j += 3) { uint32_t v0 = faces[j]; uint32_t v1 = faces[j + 1]; @@ -979,7 +979,7 @@ void DirectX::ComputeDodecahedron(VertexCollection& vertices, IndexCollection& i }; size_t t = 0; - for (size_t j = 0; j < _countof(faces); j += 5, ++t) + for (size_t j = 0; j < std::size(faces); j += 5, ++t) { uint32_t v0 = faces[j]; uint32_t v1 = faces[j + 1]; @@ -1083,7 +1083,7 @@ void DirectX::ComputeIcosahedron(VertexCollection& vertices, IndexCollection& in 11, 7, 5 }; - for (size_t j = 0; j < _countof(faces); j += 3) + for (size_t j = 0; j < std::size(faces); j += 3) { uint32_t v0 = faces[j]; uint32_t v1 = faces[j + 1]; @@ -1162,7 +1162,7 @@ void DirectX::ComputeTeapot(VertexCollection& vertices, IndexCollection& indices indices.clear(); if (tessellation < 1) - throw std::out_of_range("tesselation parameter out of range"); + throw std::invalid_argument("tesselation parameter must be non-zero"); XMVECTOR scaleVector = XMVectorReplicate(size); @@ -1170,7 +1170,7 @@ void DirectX::ComputeTeapot(VertexCollection& vertices, IndexCollection& indices XMVECTOR scaleNegateZ = XMVectorMultiply(scaleVector, g_XMNegateZ); XMVECTOR scaleNegateXZ = XMVectorMultiply(scaleVector, XMVectorMultiply(g_XMNegateX, g_XMNegateZ)); - for (size_t i = 0; i < _countof(TeapotPatches); i++) + for (size_t i = 0; i < std::size(TeapotPatches); i++) { TeapotPatch const& patch = TeapotPatches[i]; diff --git a/Kits/DirectXTK/Src/Geometry.h b/Kits/DirectXTK/Src/Geometry.h index 73969df7..c5a5475d 100644 --- a/Kits/DirectXTK/Src/Geometry.h +++ b/Kits/DirectXTK/Src/Geometry.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Geometry.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/GraphicsMemory.cpp b/Kits/DirectXTK/Src/GraphicsMemory.cpp index 15a07739..069739f4 100644 --- a/Kits/DirectXTK/Src/GraphicsMemory.cpp +++ b/Kits/DirectXTK/Src/GraphicsMemory.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: GraphicsMemory.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -32,7 +32,7 @@ class GraphicsMemory::Impl { if (s_graphicsMemory) { - throw std::exception("GraphicsMemory is a singleton"); + throw std::logic_error("GraphicsMemory is a singleton"); } s_graphicsMemory = this; @@ -113,7 +113,7 @@ class GraphicsMemory::Impl MEM_LARGE_PAGES | MEM_GRAPHICS | MEM_RESERVE | MEM_COMMIT, PAGE_WRITECOMBINE | PAGE_READWRITE | PAGE_GPU_READONLY); if (!mGrfxMemory) - throw std::bad_alloc(); + throw std::bad_alloc(); } size_t mPageSize; @@ -222,7 +222,7 @@ class GraphicsMemory::Impl { if (s_graphicsMemory) { - throw std::exception("GraphicsMemory is a singleton"); + throw std::logic_error("GraphicsMemory is a singleton"); } s_graphicsMemory = this; @@ -321,7 +321,7 @@ void GraphicsMemory::Commit() GraphicsMemory& GraphicsMemory::Get() { if (!Impl::s_graphicsMemory || !Impl::s_graphicsMemory->mOwner) - throw std::exception("GraphicsMemory singleton not created"); + throw std::logic_error("GraphicsMemory singleton not created"); return *Impl::s_graphicsMemory->mOwner; } diff --git a/Kits/DirectXTK/Src/Keyboard.cpp b/Kits/DirectXTK/Src/Keyboard.cpp index 88439b1b..76d04a1d 100644 --- a/Kits/DirectXTK/Src/Keyboard.cpp +++ b/Kits/DirectXTK/Src/Keyboard.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Keyboard.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -67,7 +67,7 @@ class Keyboard::Impl { if (s_keyboard) { - throw std::exception("Keyboard is a singleton"); + throw std::logic_error("Keyboard is a singleton"); } s_keyboard = this; @@ -96,10 +96,9 @@ class Keyboard::Impl { if (mGameInput) { - HRESULT hr = mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX); - if (FAILED(hr)) + if (!mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX)) { - DebugTrace("ERROR: GameInput::UnregisterCallback [keyboard] failed (%08X)", static_cast(hr)); + DebugTrace("ERROR: GameInput::UnregisterCallback [keyboard] failed"); } } @@ -210,7 +209,7 @@ class Keyboard::Impl { if (s_keyboard) { - throw std::exception("Keyboard is a singleton"); + throw std::logic_error("Keyboard is a singleton"); } s_keyboard = this; @@ -343,7 +342,7 @@ class Keyboard::Impl { if (s_keyboard) { - throw std::exception("Keyboard is a singleton"); + throw std::logic_error("Keyboard is a singleton"); } s_keyboard = this; @@ -604,7 +603,7 @@ bool Keyboard::IsConnected() const Keyboard& Keyboard::Get() { if (!Impl::s_keyboard || !Impl::s_keyboard->mOwner) - throw std::exception("Keyboard is a singleton"); + throw std::logic_error("Keyboard singleton not created"); return *Impl::s_keyboard->mOwner; } diff --git a/Kits/DirectXTK/Src/LoaderHelpers.h b/Kits/DirectXTK/Src/LoaderHelpers.h index d8aac62c..eb71d2ed 100644 --- a/Kits/DirectXTK/Src/LoaderHelpers.h +++ b/Kits/DirectXTK/Src/LoaderHelpers.h @@ -3,7 +3,7 @@ // // Helper functions for texture loaders and screen grabber // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -296,6 +296,8 @@ namespace DirectX return E_POINTER; } + *bitSize = 0; + if (ddsDataSize > UINT32_MAX) { return E_FAIL; @@ -328,7 +330,7 @@ namespace DirectX (MAKEFOURCC('D', 'X', '1', '0') == hdr->ddspf.fourCC)) { // Must be long enough for both headers and magic value - if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_DXT10))) + if (ddsDataSize < (sizeof(uint32_t) + sizeof(DDS_HEADER) + sizeof(DDS_HEADER_DXT10))) { return E_FAIL; } @@ -360,6 +362,8 @@ namespace DirectX return E_POINTER; } + *bitSize = 0; + // open the file #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) ScopedHandle hFile(safe_handle(CreateFile2(fileName, @@ -409,19 +413,21 @@ namespace DirectX } // read the data in - DWORD BytesRead = 0; + DWORD bytesRead = 0; if (!ReadFile(hFile.get(), ddsData.get(), fileInfo.EndOfFile.LowPart, - &BytesRead, + &bytesRead, nullptr )) { + ddsData.reset(); return HRESULT_FROM_WIN32(GetLastError()); } - if (BytesRead < fileInfo.EndOfFile.LowPart) + if (bytesRead < fileInfo.EndOfFile.LowPart) { + ddsData.reset(); return E_FAIL; } @@ -429,6 +435,7 @@ namespace DirectX auto dwMagicNumber = *reinterpret_cast(ddsData.get()); if (dwMagicNumber != DDS_MAGIC) { + ddsData.reset(); return E_FAIL; } @@ -438,6 +445,7 @@ namespace DirectX if (hdr->size != sizeof(DDS_HEADER) || hdr->ddspf.size != sizeof(DDS_PIXELFORMAT)) { + ddsData.reset(); return E_FAIL; } @@ -447,8 +455,9 @@ namespace DirectX (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))) + if (fileInfo.EndOfFile.LowPart < (sizeof(uint32_t) + sizeof(DDS_HEADER) + sizeof(DDS_HEADER_DXT10))) { + ddsData.reset(); return E_FAIL; } @@ -637,97 +646,103 @@ namespace DirectX // 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, 0)) - { - return DXGI_FORMAT_B8G8R8X8_UNORM; - } - - // No DXGI format maps to ISBITMASK(0x000000ff,0x0000ff00,0x00ff0000,0) 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, 0, 0)) - { - return DXGI_FORMAT_R16G16_UNORM; - } - - if (ISBITMASK(0xffffffff, 0, 0, 0)) - { - // 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, 0)) - { - return DXGI_FORMAT_B5G6R5_UNORM; - } - - // No DXGI format maps to ISBITMASK(0x7c00,0x03e0,0x001f,0) aka D3DFMT_X1R5G5B5 - - if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000)) - { - return DXGI_FORMAT_B4G4R4A4_UNORM; - } - - // No DXGI format maps to ISBITMASK(0x0f00,0x00f0,0x000f,0) 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(0xff, 0, 0, 0)) + { + case 32: + if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) { - return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension + return DXGI_FORMAT_R8G8B8A8_UNORM; } - // No DXGI format maps to ISBITMASK(0x0f,0,0,0xf0) aka D3DFMT_A4L4 + if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000)) + { + return DXGI_FORMAT_B8G8R8A8_UNORM; + } + + if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0)) + { + return DXGI_FORMAT_B8G8R8X8_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x000000ff,0x0000ff00,0x00ff0000,0) 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, 0, 0)) + { + return DXGI_FORMAT_R16G16_UNORM; + } + + if (ISBITMASK(0xffffffff, 0, 0, 0)) + { + // 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, 0)) + { + return DXGI_FORMAT_B5G6R5_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x7c00,0x03e0,0x001f,0) aka D3DFMT_X1R5G5B5 + + if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000)) + { + return DXGI_FORMAT_B4G4R4A4_UNORM; + } + // NVTT versions 1.x wrote this as RGB instead of LUMINANCE if (ISBITMASK(0x00ff, 0, 0, 0xff00)) { - return DXGI_FORMAT_R8G8_UNORM; // Some DDS writers assume the bitcount should be 8 instead of 16 + return DXGI_FORMAT_R8G8_UNORM; + } + if (ISBITMASK(0xffff, 0, 0, 0)) + { + return DXGI_FORMAT_R16_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x0f00,0x00f0,0x000f,0) aka D3DFMT_X4R4G4B4 + + // No 3:3:2:8 or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_A8P8, etc. + break; + + case 8: + // NVTT versions 1.x wrote this as RGB instead of LUMINANCE + if (ISBITMASK(0xff, 0, 0, 0)) + { + return DXGI_FORMAT_R8_UNORM; } - } - if (16 == ddpf.RGBBitCount) + // No 3:3:2 or paletted DXGI formats aka D3DFMT_R3G3B2, D3DFMT_P8 + break; + } + } + else if (ddpf.flags & DDS_LUMINANCE) + { + switch (ddpf.RGBBitCount) { + case 16: if (ISBITMASK(0xffff, 0, 0, 0)) { return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension @@ -736,6 +751,21 @@ namespace DirectX { return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension } + break; + + case 8: + if (ISBITMASK(0xff, 0, 0, 0)) + { + return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension + } + + // No DXGI format maps to ISBITMASK(0x0f,0,0,0xf0) aka D3DFMT_A4L4 + + if (ISBITMASK(0x00ff, 0, 0, 0xff00)) + { + return DXGI_FORMAT_R8G8_UNORM; // Some DDS writers assume the bitcount should be 8 instead of 16 + } + break; } } else if (ddpf.flags & DDS_ALPHA) @@ -747,16 +777,9 @@ namespace DirectX } else if (ddpf.flags & DDS_BUMPDUDV) { - if (16 == ddpf.RGBBitCount) - { - if (ISBITMASK(0x00ff, 0xff00, 0, 0)) - { - return DXGI_FORMAT_R8G8_SNORM; // D3DX10/11 writes this out as DX10 extension - } - } - - if (32 == ddpf.RGBBitCount) + switch (ddpf.RGBBitCount) { + case 32: if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) { return DXGI_FORMAT_R8G8B8A8_SNORM; // D3DX10/11 writes this out as DX10 extension @@ -767,6 +790,14 @@ namespace DirectX } // No DXGI format maps to ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000) aka D3DFMT_A2W10V10U10 + break; + + case 16: + if (ISBITMASK(0x00ff, 0xff00, 0, 0)) + { + return DXGI_FORMAT_R8G8_SNORM; // D3DX10/11 writes this out as DX10 extension + } + break; } // No DXGI format maps to DDPF_BUMPLUMINANCE aka D3DFMT_L6V5U5, D3DFMT_X8L8V8U8 diff --git a/Kits/DirectXTK/Src/Model.cpp b/Kits/DirectXTK/Src/Model.cpp index d56d518c..10ad77c4 100644 --- a/Kits/DirectXTK/Src/Model.cpp +++ b/Kits/DirectXTK/Src/Model.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Model.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -16,7 +16,7 @@ using namespace DirectX; -#ifndef _CPPRTTI +#if !defined(_CPPRTTI) && !defined(__GXX_RTTI) #error Model requires RTTI #endif @@ -120,10 +120,10 @@ void ModelMeshPart::CreateInputLayout(ID3D11Device* d3dDevice, IEffect* ieffect, } if (!vbDecl || vbDecl->empty()) - throw std::exception("Model mesh part missing vertex buffer input elements data"); + throw std::runtime_error("Model mesh part missing vertex buffer input elements data"); if (vbDecl->size() > D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) - throw std::exception("Model mesh part input layout size is too large for DirectX 11"); + throw std::runtime_error("Model mesh part input layout size is too large for DirectX 11"); ThrowIfFailed( CreateInputLayoutFromEffect(d3dDevice, ieffect, vbDecl->data(), vbDecl->size(), iinputLayout) @@ -138,10 +138,10 @@ _Use_decl_annotations_ void ModelMeshPart::ModifyEffect(ID3D11Device* d3dDevice, std::shared_ptr& ieffect, bool isalpha) { if (!vbDecl || vbDecl->empty()) - throw std::exception("Model mesh part missing vertex buffer input elements data"); + throw std::runtime_error("Model mesh part missing vertex buffer input elements data"); if (vbDecl->size() > D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) - throw std::exception("Model mesh part input layout size is too large for DirectX 11"); + throw std::runtime_error("Model mesh part input layout size is too large for DirectX 11"); assert(ieffect != nullptr); this->effect = ieffect; diff --git a/Kits/DirectXTK/Src/ModelLoadCMO.cpp b/Kits/DirectXTK/Src/ModelLoadCMO.cpp index 9fed7452..cc58f1c6 100644 --- a/Kits/DirectXTK/Src/ModelLoadCMO.cpp +++ b/Kits/DirectXTK/Src/ModelLoadCMO.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: ModelLoadCMO.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -266,10 +266,10 @@ std::unique_ptr DirectX::Model::CreateFromCMO( ModelLoaderFlags flags) { if (!InitOnceExecuteOnce(&g_InitOnce, InitializeDecl, nullptr, nullptr)) - throw std::exception("One-time initialization failed"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "InitOnceExecuteOnce"); if (!device || !meshData) - throw std::exception("Device and meshData cannot be null"); + throw std::invalid_argument("Device and meshData cannot be null"); auto fxFactoryDGSL = dynamic_cast(&fxFactory); @@ -277,10 +277,10 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto nMesh = reinterpret_cast(meshData); size_t usedSize = sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (!*nMesh) - throw std::exception("No meshes found"); + throw std::runtime_error("No meshes found"); auto model = std::make_unique(); @@ -290,13 +290,13 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto nName = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto meshName = reinterpret_cast(meshData + usedSize); usedSize += sizeof(wchar_t)*(*nName); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto mesh = std::make_shared(); mesh->name.assign(meshName, *nName); @@ -307,7 +307,7 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto nMats = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); std::vector materials; materials.reserve(*nMats); @@ -319,13 +319,13 @@ std::unique_ptr DirectX::Model::CreateFromCMO( nName = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto matName = reinterpret_cast(meshData + usedSize); usedSize += sizeof(wchar_t)*(*nName); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); m.name.assign(matName, *nName); @@ -333,7 +333,7 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto matSetting = reinterpret_cast(meshData + usedSize); usedSize += sizeof(VSD3DStarter::Material); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); m.pMaterial = matSetting; @@ -341,13 +341,13 @@ std::unique_ptr DirectX::Model::CreateFromCMO( nName = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto psName = reinterpret_cast(meshData + usedSize); usedSize += sizeof(wchar_t)*(*nName); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); m.pixelShader.assign(psName, *nName); @@ -356,13 +356,13 @@ std::unique_ptr DirectX::Model::CreateFromCMO( nName = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto txtName = reinterpret_cast(meshData + usedSize); usedSize += sizeof(wchar_t)*(*nName); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); m.texture[t].assign(txtName, *nName); } @@ -385,30 +385,30 @@ std::unique_ptr DirectX::Model::CreateFromCMO( const BYTE* bSkeleton = meshData + usedSize; usedSize += sizeof(BYTE); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); // Submeshes auto nSubmesh = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (!*nSubmesh) - throw std::exception("No submeshes found\n"); + throw std::runtime_error("No submeshes found\n"); auto subMesh = reinterpret_cast(meshData + usedSize); usedSize += sizeof(VSD3DStarter::SubMesh) * (*nSubmesh); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); // Index buffers auto nIBs = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (!*nIBs) - throw std::exception("No index buffers found\n"); + throw std::runtime_error("No index buffers found\n"); struct IBData { @@ -427,20 +427,20 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto nIndexes = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (!*nIndexes) - throw std::exception("Empty index buffer found\n"); + throw std::runtime_error("Empty index buffer found\n"); uint64_t sizeInBytes = uint64_t(*(nIndexes)) * sizeof(USHORT); if (sizeInBytes > UINT32_MAX) - throw std::exception("IB too large"); + throw std::runtime_error("IB too large"); if (!(flags & ModelLoader_AllowLargeModels)) { if (sizeInBytes > (D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("IB too large for DirectX 11"); + throw std::runtime_error("IB too large for DirectX 11"); } auto ibBytes = static_cast(sizeInBytes); @@ -448,7 +448,7 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto indexes = reinterpret_cast(meshData + usedSize); usedSize += ibBytes; if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); IBData ib; ib.nIndices = *nIndexes; @@ -476,10 +476,10 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto nVBs = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (!*nVBs) - throw std::exception("No vertex buffers found\n"); + throw std::runtime_error("No vertex buffers found\n"); struct VBData { @@ -495,17 +495,17 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto nVerts = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (!*nVerts) - throw std::exception("Empty vertex buffer found\n"); + throw std::runtime_error("Empty vertex buffer found\n"); size_t vbBytes = sizeof(VertexPositionNormalTangentColorTexture) * (*(nVerts)); auto verts = reinterpret_cast(meshData + usedSize); usedSize += vbBytes; if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); VBData vb; vb.nVerts = *nVerts; @@ -520,32 +520,32 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto nSkinVBs = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (*nSkinVBs) { if (*nSkinVBs != *nVBs) - throw std::exception("Number of VBs not equal to number of skin VBs"); + throw std::runtime_error("Number of VBs not equal to number of skin VBs"); for (UINT j = 0; j < *nSkinVBs; ++j) { auto nVerts = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (!*nVerts) - throw std::exception("Empty skinning vertex buffer found\n"); + throw std::runtime_error("Empty skinning vertex buffer found\n"); if (vbData[j].nVerts != *nVerts) - throw std::exception("Mismatched number of verts for skin VBs"); + throw std::runtime_error("Mismatched number of verts for skin VBs"); size_t vbBytes = sizeof(VSD3DStarter::SkinningVertex) * (*(nVerts)); auto verts = reinterpret_cast(meshData + usedSize); usedSize += vbBytes; if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); vbData[j].skinPtr = verts; } @@ -555,7 +555,7 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto extents = reinterpret_cast(meshData + usedSize); usedSize += sizeof(VSD3DStarter::MeshExtents); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); mesh->boundingSphere.Center.x = extents->CenterX; mesh->boundingSphere.Center.y = extents->CenterY; @@ -574,10 +574,10 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto nBones = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (!*nBones) - throw std::exception("Animation bone data is missing\n"); + throw std::runtime_error("Animation bone data is missing\n"); for (UINT j = 0; j < *nBones; ++j) { @@ -585,13 +585,13 @@ std::unique_ptr DirectX::Model::CreateFromCMO( nName = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto boneName = reinterpret_cast(meshData + usedSize); usedSize += sizeof(wchar_t)*(*nName); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); // TODO - What to do with bone name? boneName; @@ -600,7 +600,7 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto bones = reinterpret_cast(meshData + usedSize); usedSize += sizeof(VSD3DStarter::Bone); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); // TODO - What to do with bone data? bones; @@ -610,7 +610,7 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto nClips = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); for (UINT j = 0; j < *nClips; ++j) { @@ -618,13 +618,13 @@ std::unique_ptr DirectX::Model::CreateFromCMO( nName = reinterpret_cast(meshData + usedSize); usedSize += sizeof(UINT); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto clipName = reinterpret_cast(meshData + usedSize); usedSize += sizeof(wchar_t)*(*nName); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); // TODO - What to do with clip name? clipName; @@ -632,15 +632,15 @@ std::unique_ptr DirectX::Model::CreateFromCMO( auto clip = reinterpret_cast(meshData + usedSize); usedSize += sizeof(VSD3DStarter::Clip); if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (!clip->keys) - throw std::exception("Keyframes missing in clip"); + throw std::runtime_error("Keyframes missing in clip"); auto keys = reinterpret_cast(meshData + usedSize); usedSize += sizeof(VSD3DStarter::Keyframe) * clip->keys; if (dataSize < usedSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); // TODO - What to do with keys and clip->StartTime, clip->EndTime? keys; @@ -666,12 +666,12 @@ std::unique_ptr DirectX::Model::CreateFromCMO( uint64_t sizeInBytes = uint64_t(stride) * uint64_t(nVerts); if (sizeInBytes > UINT32_MAX) - throw std::exception("VB too large"); + throw std::runtime_error("VB too large"); if (!(flags & ModelLoader_AllowLargeModels)) { if (sizeInBytes > uint64_t(D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("VB too large for DirectX 11"); + throw std::runtime_error("VB too large for DirectX 11"); } size_t bytes = static_cast(sizeInBytes); @@ -737,7 +737,7 @@ std::unique_ptr DirectX::Model::CreateFromCMO( if ((sm.IndexBufferIndex >= *nIBs) || (sm.MaterialIndex >= materials.size())) - throw std::exception("Invalid submesh found\n"); + throw std::out_of_range("Invalid submesh found\n"); XMMATRIX uvTransform = XMLoadFloat4x4(&materials[sm.MaterialIndex].pMaterial->UVTransform); @@ -750,7 +750,7 @@ std::unique_ptr DirectX::Model::CreateFromCMO( size_t v = ib[q]; if (v >= nVerts) - throw std::exception("Invalid index found\n"); + throw std::out_of_range("Invalid index found\n"); auto verts = reinterpret_cast(temp.get() + (v * stride)); if (visited[v] == UINT(-1)) @@ -860,7 +860,7 @@ std::unique_ptr DirectX::Model::CreateFromCMO( if ((sm.IndexBufferIndex >= *nIBs) || (sm.VertexBufferIndex >= *nVBs) || (sm.MaterialIndex >= materials.size())) - throw std::exception("Invalid submesh found\n"); + throw std::out_of_range("Invalid submesh found\n"); auto& mat = materials[sm.MaterialIndex]; @@ -903,7 +903,7 @@ std::unique_ptr DirectX::Model::CreateFromCMO( { DebugTrace("ERROR: CreateFromCMO failed (%08X) loading '%ls'\n", static_cast(hr), szFileName); - throw std::exception("CreateFromCMO"); + throw std::runtime_error("CreateFromCMO"); } auto model = CreateFromCMO(device, data.get(), dataSize, fxFactory, flags); diff --git a/Kits/DirectXTK/Src/ModelLoadSDKMESH.cpp b/Kits/DirectXTK/Src/ModelLoadSDKMESH.cpp index 6df64ce5..18590761 100644 --- a/Kits/DirectXTK/Src/ModelLoadSDKMESH.cpp +++ b/Kits/DirectXTK/Src/ModelLoadSDKMESH.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: ModelLoadSDKMESH.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -56,6 +56,17 @@ namespace } } + template + inline void ASCIIToWChar(wchar_t (&buffer)[sizeOfBuffer], const char *ascii) + { +#ifdef WIN32 + MultiByteToWideChar(CP_UTF8, 0, ascii, -1, buffer, sizeOfBuffer); +#else + mbtowc(nullptr, nullptr, 0); + mbtowc(buffer, ascii, sizeOfBuffer); +#endif + } + void LoadMaterial(const DXUT::SDKMESH_MATERIAL& mh, unsigned int flags, IEffectFactory& fxFactory, @@ -63,16 +74,16 @@ namespace bool srgb) { wchar_t matName[DXUT::MAX_MATERIAL_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.Name, -1, matName, DXUT::MAX_MATERIAL_NAME); + ASCIIToWChar(matName, mh.Name); wchar_t diffuseName[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.DiffuseTexture, -1, diffuseName, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(diffuseName, mh.DiffuseTexture); wchar_t specularName[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.SpecularTexture, -1, specularName, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(specularName, mh.SpecularTexture); wchar_t normalName[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.NormalTexture, -1, normalName, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(normalName, mh.NormalTexture); if (flags & DUAL_TEXTURE && !mh.SpecularTexture[0]) { @@ -143,19 +154,19 @@ namespace MaterialRecordSDKMESH& m) { wchar_t matName[DXUT::MAX_MATERIAL_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.Name, -1, matName, DXUT::MAX_MATERIAL_NAME); + ASCIIToWChar(matName, mh.Name); wchar_t albetoTexture[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.AlbetoTexture, -1, albetoTexture, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(albetoTexture, mh.AlbetoTexture); wchar_t normalName[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.NormalTexture, -1, normalName, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(normalName, mh.NormalTexture); wchar_t rmaName[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.RMATexture, -1, rmaName, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(rmaName, mh.RMATexture); wchar_t emissiveName[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.EmissiveTexture, -1, emissiveName, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(emissiveName, mh.EmissiveTexture); EffectFactory::EffectInfo info; info.name = matName; @@ -352,7 +363,7 @@ namespace } if (!posfound) - throw std::exception("SV_Position is required"); + throw std::runtime_error("SV_Position is required"); if (texcoords == 2) { @@ -377,74 +388,74 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( ModelLoaderFlags flags) { if (!d3dDevice || !meshData) - throw std::exception("Device and meshData cannot be null"); + throw std::invalid_argument("Device and meshData cannot be null"); uint64_t dataSize = idataSize; // File Headers if (dataSize < sizeof(DXUT::SDKMESH_HEADER)) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto header = reinterpret_cast(meshData); size_t headerSize = sizeof(DXUT::SDKMESH_HEADER) + header->NumVertexBuffers * sizeof(DXUT::SDKMESH_VERTEX_BUFFER_HEADER) + header->NumIndexBuffers * sizeof(DXUT::SDKMESH_INDEX_BUFFER_HEADER); if (header->HeaderSize != headerSize) - throw std::exception("Not a valid SDKMESH file"); + throw std::runtime_error("Not a valid SDKMESH file"); if (dataSize < header->HeaderSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (header->Version != DXUT::SDKMESH_FILE_VERSION && header->Version != DXUT::SDKMESH_FILE_VERSION_V2) - throw std::exception("Not a supported SDKMESH version"); + throw std::runtime_error("Not a supported SDKMESH version"); if (header->IsBigEndian) - throw std::exception("Loading BigEndian SDKMESH files not supported"); + throw std::runtime_error("Loading BigEndian SDKMESH files not supported"); if (!header->NumMeshes) - throw std::exception("No meshes found"); + throw std::runtime_error("No meshes found"); if (!header->NumVertexBuffers) - throw std::exception("No vertex buffers found"); + throw std::runtime_error("No vertex buffers found"); if (!header->NumIndexBuffers) - throw std::exception("No index buffers found"); + throw std::runtime_error("No index buffers found"); if (!header->NumTotalSubsets) - throw std::exception("No subsets found"); + throw std::runtime_error("No subsets found"); if (!header->NumMaterials) - throw std::exception("No materials found"); + throw std::runtime_error("No materials found"); // Sub-headers if (dataSize < header->VertexStreamHeadersOffset || (dataSize < (header->VertexStreamHeadersOffset + uint64_t(header->NumVertexBuffers) * sizeof(DXUT::SDKMESH_VERTEX_BUFFER_HEADER)))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto vbArray = reinterpret_cast(meshData + header->VertexStreamHeadersOffset); if (dataSize < header->IndexStreamHeadersOffset || (dataSize < (header->IndexStreamHeadersOffset + uint64_t(header->NumIndexBuffers) * sizeof(DXUT::SDKMESH_INDEX_BUFFER_HEADER)))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto ibArray = reinterpret_cast(meshData + header->IndexStreamHeadersOffset); if (dataSize < header->MeshDataOffset || (dataSize < (header->MeshDataOffset + uint64_t(header->NumMeshes) * sizeof(DXUT::SDKMESH_MESH)))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto meshArray = reinterpret_cast(meshData + header->MeshDataOffset); if (dataSize < header->SubsetDataOffset || (dataSize < (header->SubsetDataOffset + uint64_t(header->NumTotalSubsets) * sizeof(DXUT::SDKMESH_SUBSET)))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto subsetArray = reinterpret_cast(meshData + header->SubsetDataOffset); if (dataSize < header->FrameDataOffset || (dataSize < (header->FrameDataOffset + uint64_t(header->NumFrames) * sizeof(DXUT::SDKMESH_FRAME)))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); // TODO - auto frameArray = reinterpret_cast( meshData + header->FrameDataOffset ); if (dataSize < header->MaterialDataOffset || (dataSize < (header->MaterialDataOffset + uint64_t(header->NumMaterials) * sizeof(DXUT::SDKMESH_MATERIAL)))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); const DXUT::SDKMESH_MATERIAL* materialArray = nullptr; const DXUT::SDKMESH_MATERIAL_V2* materialArray_v2 = nullptr; @@ -461,7 +472,7 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( uint64_t bufferDataOffset = header->HeaderSize + header->NonBufferDataSize; if ((dataSize < bufferDataOffset) || (dataSize < bufferDataOffset + header->BufferDataSize)) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); const uint8_t* bufferData = meshData + bufferDataOffset; // Create vertex buffers @@ -480,17 +491,17 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( auto& vh = vbArray[j]; if (vh.SizeBytes > UINT32_MAX) - throw std::exception("VB too large"); + throw std::runtime_error("VB too large"); if (!(flags & ModelLoader_AllowLargeModels)) { if (vh.SizeBytes > (D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("VB too large for DirectX 11"); + throw std::runtime_error("VB too large for DirectX 11"); } if (dataSize < vh.DataOffset || (dataSize < vh.DataOffset + vh.SizeBytes)) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); vbDecls[j] = std::make_shared>(); unsigned int ilflags = GetInputLayoutDesc(vh.Decl, *vbDecls[j].get()); @@ -542,20 +553,20 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( auto& ih = ibArray[j]; if (ih.SizeBytes > UINT32_MAX) - throw std::exception("IB too large"); + throw std::runtime_error("IB too large"); if (!(flags & ModelLoader_AllowLargeModels)) { if (ih.SizeBytes > (D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("IB too large for DirectX 11"); + throw std::runtime_error("IB too large for DirectX 11"); } if (dataSize < ih.DataOffset || (dataSize < ih.DataOffset + ih.SizeBytes)) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (ih.IndexType != DXUT::IT_16BIT && ih.IndexType != DXUT::IT_32BIT) - throw std::exception("Invalid index buffer type found"); + throw std::runtime_error("Invalid index buffer type found"); auto indices = bufferData + (ih.DataOffset - bufferDataOffset); @@ -588,13 +599,13 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( || !mh.NumVertexBuffers || mh.IndexBuffer >= header->NumIndexBuffers || mh.VertexBuffers[0] >= header->NumVertexBuffers) - throw std::exception("Invalid mesh found"); + throw std::out_of_range("Invalid mesh found"); // mh.NumVertexBuffers is sometimes not what you'd expect, so we skip validating it if (dataSize < mh.SubsetOffset || (dataSize < mh.SubsetOffset + uint64_t(mh.NumSubsets) * sizeof(UINT))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto subsets = reinterpret_cast(meshData + mh.SubsetOffset); @@ -602,14 +613,14 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( { if (dataSize < mh.FrameInfluenceOffset || (dataSize < mh.FrameInfluenceOffset + uint64_t(mh.NumFrameInfluences) * sizeof(UINT))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); // TODO - auto influences = reinterpret_cast( meshData + mh.FrameInfluenceOffset ); } auto mesh = std::make_shared(); wchar_t meshName[DXUT::MAX_MESH_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.Name, -1, meshName, DXUT::MAX_MESH_NAME); + ASCIIToWChar(meshName, mh.Name); mesh->name = meshName; mesh->ccw = (flags & ModelLoader_CounterClockwise) != 0; mesh->pmalpha = (flags & ModelLoader_PremultipledAlpha) != 0; @@ -625,7 +636,7 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( { auto sIndex = subsets[j]; if (sIndex >= header->NumTotalSubsets) - throw std::exception("Invalid mesh found"); + throw std::out_of_range("Invalid mesh found"); auto& subset = subsetArray[sIndex]; @@ -644,14 +655,14 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( case DXUT::PT_QUAD_PATCH_LIST: case DXUT::PT_TRIANGLE_PATCH_LIST: - throw std::exception("Direct3D9 era tessellation not supported"); + throw std::runtime_error("Direct3D9 era tessellation not supported"); default: - throw std::exception("Unknown primitive type"); + throw std::runtime_error("Unknown primitive type"); } if (subset.MaterialID >= header->NumMaterials) - throw std::exception("Invalid mesh found"); + throw std::out_of_range("Invalid mesh found"); auto& mat = materials[subset.MaterialID]; @@ -726,7 +737,7 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( { DebugTrace("ERROR: CreateFromSDKMESH failed (%08X) loading '%ls'\n", static_cast(hr), szFileName); - throw std::exception("CreateFromSDKMESH"); + throw std::runtime_error("CreateFromSDKMESH"); } auto model = CreateFromSDKMESH(device, data.get(), dataSize, fxFactory, flags); diff --git a/Kits/DirectXTK/Src/ModelLoadVBO.cpp b/Kits/DirectXTK/Src/ModelLoadVBO.cpp index bde3f16b..445f6e6b 100644 --- a/Kits/DirectXTK/Src/ModelLoadVBO.cpp +++ b/Kits/DirectXTK/Src/ModelLoadVBO.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: ModelLoadVBO.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -53,51 +53,51 @@ std::unique_ptr DirectX::Model::CreateFromVBO( ModelLoaderFlags flags) { if (!InitOnceExecuteOnce(&g_InitOnce, InitializeDecl, nullptr, nullptr)) - throw std::exception("One-time initialization failed"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "InitOnceExecuteOnce"); if (!device || !meshData) - throw std::exception("Device and meshData cannot be null"); + throw std::invalid_argument("Device and meshData cannot be null"); // File Header if (dataSize < sizeof(VBO::header_t)) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto header = reinterpret_cast(meshData); if (!header->numVertices || !header->numIndices) - throw std::exception("No vertices or indices found"); + throw std::runtime_error("No vertices or indices found"); uint64_t sizeInBytes = uint64_t(header->numVertices) * sizeof(VertexPositionNormalTexture); if (sizeInBytes > UINT32_MAX) - throw std::exception("VB too large"); + throw std::runtime_error("VB too large"); if (!(flags & ModelLoader_AllowLargeModels)) { if (sizeInBytes > uint64_t(D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("VB too large for DirectX 11"); + throw std::runtime_error("VB too large for DirectX 11"); } auto vertSize = static_cast(sizeInBytes); if (dataSize < (vertSize + sizeof(VBO::header_t))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto verts = reinterpret_cast(meshData + sizeof(VBO::header_t)); sizeInBytes = uint64_t(header->numIndices) * sizeof(uint16_t); if (sizeInBytes > UINT32_MAX) - throw std::exception("IB too large"); + throw std::runtime_error("IB too large"); if (!(flags & ModelLoader_AllowLargeModels)) { if (sizeInBytes > uint64_t(D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("IB too large for DirectX 11"); + throw std::runtime_error("IB too large for DirectX 11"); } auto indexSize = static_cast(sizeInBytes); if (dataSize < (sizeof(VBO::header_t) + vertSize + indexSize)) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto indices = reinterpret_cast(meshData + sizeof(VBO::header_t) + vertSize); // Create vertex buffer @@ -191,7 +191,7 @@ std::unique_ptr DirectX::Model::CreateFromVBO( { DebugTrace("ERROR: CreateFromVBO failed (%08X) loading '%ls'\n", static_cast(hr), szFileName); - throw std::exception("CreateFromVBO"); + throw std::runtime_error("CreateFromVBO"); } auto model = CreateFromVBO(device, data.get(), dataSize, ieffect, flags); diff --git a/Kits/DirectXTK/Src/Mouse.cpp b/Kits/DirectXTK/Src/Mouse.cpp index 96f59743..89f712ae 100644 --- a/Kits/DirectXTK/Src/Mouse.cpp +++ b/Kits/DirectXTK/Src/Mouse.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Mouse.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -67,7 +67,7 @@ class Mouse::Impl { if (s_mouse) { - throw std::exception("Mouse is a singleton"); + throw std::logic_error("Mouse is a singleton"); } s_mouse = this; @@ -86,7 +86,7 @@ class Mouse::Impl mScrollWheelValue.reset(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mScrollWheelValue) { - throw std::exception("CreateEventEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } } @@ -102,10 +102,9 @@ class Mouse::Impl { if (mGameInput) { - HRESULT hr = mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX); - if (FAILED(hr)) + if (!mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX)) { - DebugTrace("ERROR: GameInput::UnregisterCallback [mouse] failed (%08X)", static_cast(hr)); + DebugTrace("ERROR: GameInput::UnregisterCallback [mouse] failed"); } } @@ -122,7 +121,7 @@ class Mouse::Impl DWORD result = WaitForSingleObjectEx(mScrollWheelValue.get(), 0, FALSE); if (result == WAIT_FAILED) - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); if (result == WAIT_OBJECT_0) { @@ -206,7 +205,7 @@ class Mouse::Impl CURSORINFO info = { sizeof(CURSORINFO), 0, nullptr, {} }; if (!GetCursorInfo(&info)) { - throw std::exception("GetCursorInfo"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "GetCursorInfo"); } bool isvisible = (info.flags & CURSOR_SHOWING) != 0; @@ -271,7 +270,7 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) DWORD result = WaitForSingleObjectEx(pImpl->mScrollWheelValue.get(), 0, FALSE); if (result == WAIT_FAILED) - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); if (result == WAIT_OBJECT_0) { @@ -446,7 +445,7 @@ class Mouse::Impl { if (s_mouse) { - throw std::exception("Mouse is a singleton"); + throw std::logic_error("Mouse is a singleton"); } s_mouse = this; @@ -460,7 +459,7 @@ class Mouse::Impl || !mAbsoluteMode || !mRelativeMode) { - throw std::exception("CreateEventEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } } @@ -482,7 +481,7 @@ class Mouse::Impl DWORD result = WaitForSingleObjectEx(mScrollWheelValue.get(), 0, FALSE); if (result == WAIT_FAILED) - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); if (result == WAIT_OBJECT_0) { @@ -494,7 +493,7 @@ class Mouse::Impl result = WaitForSingleObjectEx(mRelativeRead.get(), 0, FALSE); if (result == WAIT_FAILED) - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); if (result == WAIT_OBJECT_0) { @@ -529,7 +528,7 @@ class Mouse::Impl tme.dwHoverTime = 1; if (!TrackMouseEvent(&tme)) { - throw std::exception("TrackMouseEvent"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "TrackMouseEvent"); } } @@ -558,7 +557,7 @@ class Mouse::Impl CURSORINFO info = { sizeof(CURSORINFO), 0, nullptr, {} }; if (!GetCursorInfo(&info)) { - throw std::exception("GetCursorInfo"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "GetCursorInfo"); } bool isvisible = (info.flags & CURSOR_SHOWING) != 0; @@ -582,7 +581,7 @@ class Mouse::Impl Rid.hwndTarget = window; if (!RegisterRawInputDevices(&Rid, 1, sizeof(RAWINPUTDEVICE))) { - throw std::exception("RegisterRawInputDevices"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "RegisterRawInputDevices"); } mWindow = window; @@ -658,7 +657,7 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) return; HANDLE events[3] = { pImpl->mScrollWheelValue.get(), pImpl->mAbsoluteMode.get(), pImpl->mRelativeMode.get() }; - switch (WaitForMultipleObjectsEx(_countof(events), events, FALSE, 0, FALSE)) + switch (WaitForMultipleObjectsEx(static_cast(std::size(events)), events, FALSE, 0, FALSE)) { default: case WAIT_TIMEOUT: @@ -706,7 +705,7 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) break; case WAIT_FAILED: - throw std::exception("WaitForMultipleObjectsEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForMultipleObjectsEx"); } switch (message) @@ -744,7 +743,7 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) UINT resultData = GetRawInputData(reinterpret_cast(lParam), RID_INPUT, &raw, &rawSize, sizeof(RAWINPUTHEADER)); if (resultData == UINT(-1)) { - throw std::exception("GetRawInputData"); + throw std::runtime_error("GetRawInputData"); } if (raw.header.dwType == RIM_TYPEMOUSE) @@ -875,7 +874,7 @@ class Mouse::Impl { if (s_mouse) { - throw std::exception("Mouse is a singleton"); + throw std::logic_error("Mouse is a singleton"); } s_mouse = this; @@ -960,7 +959,7 @@ class Mouse::Impl { if (s_mouse) { - throw std::exception("Mouse is a singleton"); + throw std::logic_error("Mouse is a singleton"); } s_mouse = this; @@ -970,7 +969,7 @@ class Mouse::Impl if (!mScrollWheelValue || !mRelativeRead) { - throw std::exception("CreateEventEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } } @@ -987,7 +986,7 @@ class Mouse::Impl DWORD result = WaitForSingleObjectEx(mScrollWheelValue.get(), 0, FALSE); if (result == WAIT_FAILED) - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); if (result == WAIT_OBJECT_0) { @@ -999,7 +998,7 @@ class Mouse::Impl result = WaitForSingleObjectEx(mRelativeRead.get(), 0, FALSE); if (result == WAIT_FAILED) - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); if (result == WAIT_OBJECT_0) { @@ -1463,7 +1462,7 @@ void Mouse::SetVisible(bool visible) Mouse& Mouse::Get() { if (!Impl::s_mouse || !Impl::s_mouse->mOwner) - throw std::exception("Mouse is a singleton"); + throw std::logic_error("Mouse singleton not created"); return *Impl::s_mouse->mOwner; } diff --git a/Kits/DirectXTK/Src/NormalMapEffect.cpp b/Kits/DirectXTK/Src/NormalMapEffect.cpp index 5e124748..b5a59c13 100644 --- a/Kits/DirectXTK/Src/NormalMapEffect.cpp +++ b/Kits/DirectXTK/Src/NormalMapEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: NormalMapEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -181,13 +181,13 @@ NormalMapEffect::Impl::Impl(_In_ ID3D11Device* device) { if (device->GetFeatureLevel() < D3D_FEATURE_LEVEL_10_0) { - throw std::exception("NormalMapEffect requires Feature Level 10.0 or later"); + throw std::runtime_error("NormalMapEffect requires Feature Level 10.0 or later"); } - static_assert(_countof(EffectBase::VertexShaderIndices) == NormalMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == NormalMapEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == NormalMapEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == NormalMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == NormalMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == NormalMapEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == NormalMapEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == NormalMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); lights.InitializeConstants(constants.specularColorAndPower, constants.lightDirection, constants.lightDiffuseColor, constants.lightSpecularColor); } @@ -237,7 +237,7 @@ void NormalMapEffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) // Set the textures ID3D11ShaderResourceView* textures[] = { texture.Get(), specularTexture.Get(), normalTexture.Get()}; - deviceContext->PSSetShaderResources(0, _countof(textures), textures); + deviceContext->PSSetShaderResources(0, static_cast(std::size(textures)), textures); // Set shaders and constant buffers. ApplyShaders(deviceContext, GetCurrentShaderPermutation()); @@ -388,7 +388,7 @@ void NormalMapEffect::SetLightingEnabled(bool value) { if (!value) { - throw std::exception("NormalMapEffect does not support turning off lighting"); + throw std::invalid_argument("NormalMapEffect does not support turning off lighting"); } } diff --git a/Kits/DirectXTK/Src/PBREffect.cpp b/Kits/DirectXTK/Src/PBREffect.cpp index dcb89287..2963b204 100644 --- a/Kits/DirectXTK/Src/PBREffect.cpp +++ b/Kits/DirectXTK/Src/PBREffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: PBREffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -15,23 +15,23 @@ using namespace DirectX; // Constant buffer layout. Must match the shader! struct PBREffectConstants -{ +{ XMVECTOR eyePosition; XMMATRIX world; XMVECTOR worldInverseTranspose[3]; XMMATRIX worldViewProj; XMMATRIX prevWorldViewProj; // for velocity generation - XMVECTOR lightDirection[IEffectLights::MaxDirectionalLights]; + XMVECTOR lightDirection[IEffectLights::MaxDirectionalLights]; XMVECTOR lightDiffuseColor[IEffectLights::MaxDirectionalLights]; - + // PBR Parameters XMVECTOR Albedo; float Metallic; float Roughness; int numRadianceMipLevels; - // Size of render target + // Size of render target float targetWidth; float targetHeight; }; @@ -90,7 +90,7 @@ namespace #include "Shaders/Compiled/XboxOnePBREffect_PSTexturedEmissive.inc" #include "Shaders/Compiled/XboxOnePBREffect_PSTexturedVelocity.inc" #include "Shaders/Compiled/XboxOnePBREffect_PSTexturedEmissiveVelocity.inc" -#else +#else #include "Shaders/Compiled/PBREffect_VSConstant.inc" #include "Shaders/Compiled/PBREffect_VSConstantVelocity.inc" #include "Shaders/Compiled/PBREffect_VSConstantBn.inc" @@ -172,13 +172,13 @@ PBREffect::Impl::Impl(_In_ ID3D11Device* device) { if (device->GetFeatureLevel() < D3D_FEATURE_LEVEL_10_0) { - throw std::exception("PBREffect requires Feature Level 10.0 or later"); + throw std::runtime_error("PBREffect requires Feature Level 10.0 or later"); } - static_assert(_countof(EffectBase::VertexShaderIndices) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == PBREffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == PBREffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == PBREffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == PBREffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch"); // Lighting static const XMVECTORF32 defaultLightDirection = { { { 0, -1, 0, 0 } } }; @@ -235,7 +235,7 @@ void PBREffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) constants.prevWorldViewProj = constants.worldViewProj; // Compute derived parameter values. - matrices.SetConstants(dirtyFlags, constants.worldViewProj); + matrices.SetConstants(dirtyFlags, constants.worldViewProj); // World inverse transpose matrix. if (dirtyFlags & EffectDirtyFlags::WorldInverseTranspose) @@ -270,7 +270,7 @@ void PBREffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) albedoTexture.Get(), normalTexture.Get(), rmaTexture.Get(), emissiveTexture.Get(), radianceTexture.Get(), irradianceTexture.Get() }; - deviceContext->PSSetShaderResources(0, _countof(textures), textures); + deviceContext->PSSetShaderResources(0, static_cast(std::size(textures)), textures); } else { @@ -278,7 +278,7 @@ void PBREffect::Impl::Apply(_In_ ID3D11DeviceContext* deviceContext) nullptr, nullptr, nullptr, nullptr, radianceTexture.Get(), irradianceTexture.Get() }; - deviceContext->PSSetShaderResources(0, _countof(textures), textures); + deviceContext->PSSetShaderResources(0, static_cast(std::size(textures)), textures); } // Set shaders and constant buffers. @@ -366,7 +366,7 @@ void PBREffect::SetLightingEnabled(bool value) { if (!value) { - throw std::exception("PBREffect does not support turning off lighting"); + throw std::invalid_argument("PBREffect does not support turning off lighting"); } } diff --git a/Kits/DirectXTK/Src/PBREffectFactory.cpp b/Kits/DirectXTK/Src/PBREffectFactory.cpp index c2534a58..90e300d2 100644 --- a/Kits/DirectXTK/Src/PBREffectFactory.cpp +++ b/Kits/DirectXTK/Src/PBREffectFactory.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: PBREffectFactory.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -127,7 +127,7 @@ _Use_decl_annotations_ void PBREffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceContext* deviceContext, ID3D11ShaderResourceView** textureView) { if (!name || !textureView) - throw std::exception("invalid arguments"); + throw std::invalid_argument("name and textureView parameters can't be null"); #if defined(_XBOX_ONE) && defined(_TITLE) UNREFERENCED_PARAMETER(deviceContext); @@ -155,14 +155,15 @@ void PBREffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCont if (!GetFileAttributesExW(fullName, GetFileExInfoStandard, &fileAttr)) { DebugTrace("ERROR: PBREffectFactory could not find texture file '%ls'\n", name); - throw std::exception("CreateTexture"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "PBREffectFactory::CreateTexture"); } } - wchar_t ext[_MAX_EXT]; + wchar_t ext[_MAX_EXT] = {}; _wsplitpath_s(name, nullptr, 0, nullptr, 0, nullptr, 0, ext, _MAX_EXT); + bool isdds = _wcsicmp(ext, L".dds") == 0; - if (_wcsicmp(ext, L".dds") == 0) + if (isdds) { HRESULT hr = CreateDDSTextureFromFileEx( mDevice.Get(), fullName, 0, @@ -172,7 +173,7 @@ void PBREffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCont { DebugTrace("ERROR: CreateDDSTextureFromFile failed (%08X) for '%ls'\n", static_cast(hr), fullName); - throw std::exception("CreateDDSTextureFromFile"); + throw std::runtime_error("PBREffectFactory::CreateDDSTextureFromFile"); } } #if !defined(_XBOX_ONE) || !defined(_TITLE) @@ -187,7 +188,7 @@ void PBREffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCont { DebugTrace("ERROR: CreateWICTextureFromFile failed (%08X) for '%ls'\n", static_cast(hr), fullName); - throw std::exception("CreateWICTextureFromFile"); + throw std::runtime_error("PBREffectFactory::CreateWICTextureFromFile"); } } #endif @@ -201,7 +202,7 @@ void PBREffectFactory::Impl::CreateTexture(const wchar_t* name, ID3D11DeviceCont { DebugTrace("ERROR: CreateWICTextureFromFile failed (%08X) for '%ls'\n", static_cast(hr), fullName); - throw std::exception("CreateWICTextureFromFile"); + throw std::runtime_error("PBREffectFactory::CreateWICTextureFromFile"); } } diff --git a/Kits/DirectXTK/Src/PlatformHelpers.h b/Kits/DirectXTK/Src/PlatformHelpers.h index 10832255..401049b0 100644 --- a/Kits/DirectXTK/Src/PlatformHelpers.h +++ b/Kits/DirectXTK/Src/PlatformHelpers.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: PlatformHelpers.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -31,7 +31,7 @@ namespace DirectX public: com_exception(HRESULT hr) noexcept : result(hr) {} - const char* what() const override + const char* what() const noexcept override { static char s_str[64] = {}; sprintf_s(s_str, "Failure with HRESULT of %08X", static_cast(result)); @@ -70,7 +70,6 @@ namespace DirectX #endif } - // Helper smart-pointers #if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) || (defined(_XBOX_ONE) && defined(_TITLE)) || !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) struct virtual_deleter { void operator()(void* p) noexcept { if (p) VirtualFree(p, 0, MEM_RELEASE); } }; diff --git a/Kits/DirectXTK/Src/PrimitiveBatch.cpp b/Kits/DirectXTK/Src/PrimitiveBatch.cpp index c1c23d4a..c1b1ecdc 100644 --- a/Kits/DirectXTK/Src/PrimitiveBatch.cpp +++ b/Kits/DirectXTK/Src/PrimitiveBatch.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: PrimitiveBatch.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -130,20 +130,20 @@ PrimitiveBatchBase::Impl::Impl(_In_ ID3D11DeviceContext* deviceContext, size_t m deviceContext->GetDevice(&device); if (!maxVertices) - throw std::exception("maxVertices must be greater than 0"); + throw std::invalid_argument("maxVertices must be greater than 0"); if (vertexSize > D3D11_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES) - throw std::exception("Vertex size is too large for DirectX 11"); + throw std::invalid_argument("Vertex size is too large for DirectX 11"); uint64_t ibBytes = uint64_t(maxIndices) * sizeof(uint16_t); if (ibBytes > uint64_t(D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u) || ibBytes > UINT32_MAX) - throw std::exception("IB too large for DirectX 11"); + throw std::invalid_argument("IB too large for DirectX 11"); uint64_t vbBytes = uint64_t(maxVertices) * uint64_t(vertexSize); if (vbBytes > uint64_t(D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u) || vbBytes > UINT32_MAX) - throw std::exception("VB too large for DirectX 11"); + throw std::invalid_argument("VB too large for DirectX 11"); #if defined(_XBOX_ONE) && defined(_TITLE) ThrowIfFailed(deviceContext->QueryInterface(IID_GRAPHICS_PPV_ARGS(mDeviceContext.GetAddressOf()))); @@ -180,7 +180,7 @@ PrimitiveBatchBase::Impl::Impl(_In_ ID3D11DeviceContext* deviceContext, size_t m void PrimitiveBatchBase::Impl::Begin() { if (mInBeginEndPair) - throw std::exception("Cannot nest Begin calls"); + throw std::logic_error("Cannot nest Begin calls"); #if defined(_XBOX_ONE) && defined(_TITLE) mDeviceContext->IASetIndexBuffer(nullptr, DXGI_FORMAT_UNKNOWN, 0); @@ -214,7 +214,7 @@ void PrimitiveBatchBase::Impl::Begin() void PrimitiveBatchBase::Impl::End() { if (!mInBeginEndPair) - throw std::exception("Begin must be called before End"); + throw std::logic_error("Begin must be called before End"); FlushBatch(); @@ -266,16 +266,16 @@ _Use_decl_annotations_ void PrimitiveBatchBase::Impl::Draw(D3D11_PRIMITIVE_TOPOLOGY topology, bool isIndexed, uint16_t const* indices, size_t indexCount, size_t vertexCount, void** pMappedVertices) { if (isIndexed && !indices) - throw std::exception("Indices cannot be null"); + throw std::invalid_argument("Indices cannot be null"); if (indexCount >= mMaxIndices) - throw std::exception("Too many indices"); + throw std::out_of_range("Too many indices"); if (vertexCount >= mMaxVertices) - throw std::exception("Too many vertices"); + throw std::out_of_range("Too many vertices"); if (!mInBeginEndPair) - throw std::exception("Begin must be called before Draw"); + throw std::logic_error("Begin must be called before Draw"); // Can we merge this primitive in with an existing batch, or must we flush first? bool wrapIndexBuffer = (mCurrentIndex + indexCount > mMaxIndices); diff --git a/Kits/DirectXTK/Src/SDKMesh.h b/Kits/DirectXTK/Src/SDKMesh.h index 54c11c89..17041022 100644 --- a/Kits/DirectXTK/Src/SDKMesh.h +++ b/Kits/DirectXTK/Src/SDKMesh.h @@ -6,7 +6,7 @@ // // http://go.microsoft.com/fwlink/?LinkId=226208 // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -150,7 +150,7 @@ namespace DXUT enum FRAME_TRANSFORM_TYPE { FTT_RELATIVE = 0, - FTT_ABSOLUTE, //This is not currently used but is here to support absolute transformations in the future + FTT_ABSOLUTE, // This is not currently used but is here to support absolute transformations in the future }; //-------------------------------------------------------------------------------------- @@ -244,7 +244,7 @@ namespace DXUT uint32_t ChildFrame; uint32_t SiblingFrame; DirectX::XMFLOAT4X4 Matrix; - uint32_t AnimationDataIndex; //Used to index which set of keyframes transforms this frame + uint32_t AnimationDataIndex; //Used to index which set of keyframes transforms this frame }; struct SDKMESH_MATERIAL diff --git a/Kits/DirectXTK/Src/ScreenGrab.cpp b/Kits/DirectXTK/Src/ScreenGrab.cpp index 8ab78b30..5b827f6e 100644 --- a/Kits/DirectXTK/Src/ScreenGrab.cpp +++ b/Kits/DirectXTK/Src/ScreenGrab.cpp @@ -8,7 +8,7 @@ // 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. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -186,9 +186,11 @@ HRESULT DirectX::SaveDDSTextureToFile( // Create file #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) - ScopedHandle hFile(safe_handle(CreateFile2(fileName, GENERIC_WRITE | DELETE, 0, CREATE_ALWAYS, nullptr))); + 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))); + ScopedHandle hFile(safe_handle(CreateFileW(fileName, + GENERIC_WRITE | DELETE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr))); #endif if (!hFile) return HRESULT_FROM_WIN32(GetLastError()); @@ -214,30 +216,30 @@ HRESULT DirectX::SaveDDSTextureToFile( 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 + case DXGI_FORMAT_R8G8B8A8_UNORM: memcpy(&header->ddspf, &DDSPF_A8B8G8R8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R16G16_UNORM: memcpy(&header->ddspf, &DDSPF_G16R16, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8_UNORM: memcpy(&header->ddspf, &DDSPF_A8L8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R16_UNORM: memcpy(&header->ddspf, &DDSPF_L16, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8_UNORM: memcpy(&header->ddspf, &DDSPF_L8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_A8_UNORM: memcpy(&header->ddspf, &DDSPF_A8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8_B8G8_UNORM: memcpy(&header->ddspf, &DDSPF_R8G8_B8G8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_G8R8_G8B8_UNORM: memcpy(&header->ddspf, &DDSPF_G8R8_G8B8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC1_UNORM: memcpy(&header->ddspf, &DDSPF_DXT1, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC2_UNORM: memcpy(&header->ddspf, &DDSPF_DXT3, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC3_UNORM: memcpy(&header->ddspf, &DDSPF_DXT5, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC4_UNORM: memcpy(&header->ddspf, &DDSPF_BC4_UNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC4_SNORM: memcpy(&header->ddspf, &DDSPF_BC4_SNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC5_UNORM: memcpy(&header->ddspf, &DDSPF_BC5_UNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC5_SNORM: memcpy(&header->ddspf, &DDSPF_BC5_SNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B5G6R5_UNORM: memcpy(&header->ddspf, &DDSPF_R5G6B5, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B5G5R5A1_UNORM: memcpy(&header->ddspf, &DDSPF_A1R5G5B5, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8_SNORM: memcpy(&header->ddspf, &DDSPF_V8U8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8B8A8_SNORM: memcpy(&header->ddspf, &DDSPF_Q8W8V8U8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R16G16_SNORM: memcpy(&header->ddspf, &DDSPF_V16U16, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B8G8R8A8_UNORM: memcpy(&header->ddspf, &DDSPF_A8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.1 + case DXGI_FORMAT_B8G8R8X8_UNORM: memcpy(&header->ddspf, &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.1 + case DXGI_FORMAT_YUY2: memcpy(&header->ddspf, &DDSPF_YUY2, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.2 + case DXGI_FORMAT_B4G4R4A4_UNORM: memcpy(&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 @@ -257,7 +259,7 @@ HRESULT DirectX::SaveDDSTextureToFile( return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); default: - memcpy_s(&header->ddspf, sizeof(header->ddspf), &DDSPF_DX10, sizeof(DDS_PIXELFORMAT)); + memcpy(&header->ddspf, &DDSPF_DX10, sizeof(DDS_PIXELFORMAT)); headerSize += sizeof(DDS_HEADER_DXT10); extHeader = reinterpret_cast(fileHeader + sizeof(uint32_t) + sizeof(DDS_HEADER)); @@ -308,7 +310,7 @@ HRESULT DirectX::SaveDDSTextureToFile( size_t msize = std::min(rowPitch, mapped.RowPitch); for (size_t h = 0; h < rowCount; ++h) { - memcpy_s(dptr, rowPitch, sptr, msize); + memcpy(dptr, sptr, msize); sptr += mapped.RowPitch; dptr += rowPitch; } diff --git a/Kits/DirectXTK/Src/Shaders/AlphaTestEffect.fx b/Kits/DirectXTK/Src/Shaders/AlphaTestEffect.fx index 4388f5e4..d8ec63c5 100644 --- a/Kits/DirectXTK/Src/Shaders/AlphaTestEffect.fx +++ b/Kits/DirectXTK/Src/Shaders/AlphaTestEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/Shaders/BasicEffect.fx b/Kits/DirectXTK/Src/Shaders/BasicEffect.fx index 1a80f1bb..8ef4c2b1 100644 --- a/Kits/DirectXTK/Src/Shaders/BasicEffect.fx +++ b/Kits/DirectXTK/Src/Shaders/BasicEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/Shaders/Common.fxh b/Kits/DirectXTK/Src/Shaders/Common.fxh index 0e71229a..d997d4ed 100644 --- a/Kits/DirectXTK/Src/Shaders/Common.fxh +++ b/Kits/DirectXTK/Src/Shaders/Common.fxh @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTK/Src/Shaders/CompileShaders.cmd b/Kits/DirectXTK/Src/Shaders/CompileShaders.cmd index c2f4be0c..7c1f6aa4 100644 --- a/Kits/DirectXTK/Src/Shaders/CompileShaders.cmd +++ b/Kits/DirectXTK/Src/Shaders/CompileShaders.cmd @@ -1,5 +1,5 @@ @echo off -rem Copyright (c) Microsoft Corporation. All rights reserved. +rem Copyright (c) Microsoft Corporation. rem Licensed under the MIT License. setlocal diff --git a/Kits/DirectXTK/Src/Shaders/DGSLEffect.fx b/Kits/DirectXTK/Src/Shaders/DGSLEffect.fx index 73c1f249..4a4c4331 100644 --- a/Kits/DirectXTK/Src/Shaders/DGSLEffect.fx +++ b/Kits/DirectXTK/Src/Shaders/DGSLEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // diff --git a/Kits/DirectXTK/Src/Shaders/DGSLLambert.hlsl b/Kits/DirectXTK/Src/Shaders/DGSLLambert.hlsl index 363fed23..69eb11a5 100644 --- a/Kits/DirectXTK/Src/Shaders/DGSLLambert.hlsl +++ b/Kits/DirectXTK/Src/Shaders/DGSLLambert.hlsl @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // diff --git a/Kits/DirectXTK/Src/Shaders/DGSLPhong.hlsl b/Kits/DirectXTK/Src/Shaders/DGSLPhong.hlsl index c0010ea9..44196fdd 100644 --- a/Kits/DirectXTK/Src/Shaders/DGSLPhong.hlsl +++ b/Kits/DirectXTK/Src/Shaders/DGSLPhong.hlsl @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // diff --git a/Kits/DirectXTK/Src/Shaders/DGSLUnlit.hlsl b/Kits/DirectXTK/Src/Shaders/DGSLUnlit.hlsl index eec16649..46c1d808 100644 --- a/Kits/DirectXTK/Src/Shaders/DGSLUnlit.hlsl +++ b/Kits/DirectXTK/Src/Shaders/DGSLUnlit.hlsl @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // diff --git a/Kits/DirectXTK/Src/Shaders/DebugEffect.fx b/Kits/DirectXTK/Src/Shaders/DebugEffect.fx index cfc51916..25c9c8a2 100644 --- a/Kits/DirectXTK/Src/Shaders/DebugEffect.fx +++ b/Kits/DirectXTK/Src/Shaders/DebugEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/Shaders/DualTextureEffect.fx b/Kits/DirectXTK/Src/Shaders/DualTextureEffect.fx index 22a4ca8d..3205a181 100644 --- a/Kits/DirectXTK/Src/Shaders/DualTextureEffect.fx +++ b/Kits/DirectXTK/Src/Shaders/DualTextureEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/Shaders/EnvironmentMapEffect.fx b/Kits/DirectXTK/Src/Shaders/EnvironmentMapEffect.fx index a9e52318..1898114a 100644 --- a/Kits/DirectXTK/Src/Shaders/EnvironmentMapEffect.fx +++ b/Kits/DirectXTK/Src/Shaders/EnvironmentMapEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/Shaders/Lighting.fxh b/Kits/DirectXTK/Src/Shaders/Lighting.fxh index a17187d1..87867354 100644 --- a/Kits/DirectXTK/Src/Shaders/Lighting.fxh +++ b/Kits/DirectXTK/Src/Shaders/Lighting.fxh @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTK/Src/Shaders/NormalMapEffect.fx b/Kits/DirectXTK/Src/Shaders/NormalMapEffect.fx index f7a2d751..aadd0f15 100644 --- a/Kits/DirectXTK/Src/Shaders/NormalMapEffect.fx +++ b/Kits/DirectXTK/Src/Shaders/NormalMapEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/Shaders/PBRCommon.fxh b/Kits/DirectXTK/Src/Shaders/PBRCommon.fxh index d7aad5a0..2481f1b2 100644 --- a/Kits/DirectXTK/Src/Shaders/PBRCommon.fxh +++ b/Kits/DirectXTK/Src/Shaders/PBRCommon.fxh @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTK/Src/Shaders/PBREffect.fx b/Kits/DirectXTK/Src/Shaders/PBREffect.fx index 0f98b3f8..325df4eb 100644 --- a/Kits/DirectXTK/Src/Shaders/PBREffect.fx +++ b/Kits/DirectXTK/Src/Shaders/PBREffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/Shaders/PostProcess.fx b/Kits/DirectXTK/Src/Shaders/PostProcess.fx index ee768249..a2ed9226 100644 --- a/Kits/DirectXTK/Src/Shaders/PostProcess.fx +++ b/Kits/DirectXTK/Src/Shaders/PostProcess.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/Shaders/SkinnedEffect.fx b/Kits/DirectXTK/Src/Shaders/SkinnedEffect.fx index 2b482e10..5a5c18f8 100644 --- a/Kits/DirectXTK/Src/Shaders/SkinnedEffect.fx +++ b/Kits/DirectXTK/Src/Shaders/SkinnedEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/Shaders/SpriteEffect.fx b/Kits/DirectXTK/Src/Shaders/SpriteEffect.fx index f8857714..bd4b9f3e 100644 --- a/Kits/DirectXTK/Src/Shaders/SpriteEffect.fx +++ b/Kits/DirectXTK/Src/Shaders/SpriteEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/Shaders/Structures.fxh b/Kits/DirectXTK/Src/Shaders/Structures.fxh index 34e5e723..6624d17b 100644 --- a/Kits/DirectXTK/Src/Shaders/Structures.fxh +++ b/Kits/DirectXTK/Src/Shaders/Structures.fxh @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTK/Src/Shaders/ToneMap.fx b/Kits/DirectXTK/Src/Shaders/ToneMap.fx index e055250b..f47bd9c5 100644 --- a/Kits/DirectXTK/Src/Shaders/ToneMap.fx +++ b/Kits/DirectXTK/Src/Shaders/ToneMap.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/Shaders/Utilities.fxh b/Kits/DirectXTK/Src/Shaders/Utilities.fxh index 49ea06ce..1c731546 100644 --- a/Kits/DirectXTK/Src/Shaders/Utilities.fxh +++ b/Kits/DirectXTK/Src/Shaders/Utilities.fxh @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTK/Src/SharedResourcePool.h b/Kits/DirectXTK/Src/SharedResourcePool.h index 4848c131..92ec2f13 100644 --- a/Kits/DirectXTK/Src/SharedResourcePool.h +++ b/Kits/DirectXTK/Src/SharedResourcePool.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SharedResourcePool.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/SimpleMath.cpp b/Kits/DirectXTK/Src/SimpleMath.cpp index 76e03cbc..3b3cfb82 100644 --- a/Kits/DirectXTK/Src/SimpleMath.cpp +++ b/Kits/DirectXTK/Src/SimpleMath.cpp @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------------- // SimpleMath.cpp -- Simplified C++ Math wrapper for DirectXMath // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -81,6 +81,7 @@ static_assert(offsetof(DirectX::SimpleMath::Viewport, minDepth) == offsetof(D3D1 static_assert(offsetof(DirectX::SimpleMath::Viewport, maxDepth) == offsetof(D3D12_VIEWPORT, MaxDepth), "Layout mismatch"); #endif +#if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) RECT DirectX::SimpleMath::Viewport::ComputeDisplayArea(DXGI_SCALING scaling, UINT backBufferWidth, UINT backBufferHeight, int outputWidth, int outputHeight) noexcept { RECT rct = {}; @@ -140,6 +141,7 @@ RECT DirectX::SimpleMath::Viewport::ComputeDisplayArea(DXGI_SCALING scaling, UIN return rct; } +#endif RECT DirectX::SimpleMath::Viewport::ComputeTitleSafeArea(UINT backBufferWidth, UINT backBufferHeight) noexcept { diff --git a/Kits/DirectXTK/Src/SkinnedEffect.cpp b/Kits/DirectXTK/Src/SkinnedEffect.cpp index a31818b1..b5e1a65b 100644 --- a/Kits/DirectXTK/Src/SkinnedEffect.cpp +++ b/Kits/DirectXTK/Src/SkinnedEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SkinnedEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -276,10 +276,10 @@ SkinnedEffect::Impl::Impl(_In_ ID3D11Device* device) biasedVertexNormals(false), weightsPerVertex(4) { - static_assert(_countof(EffectBase::VertexShaderIndices) == SkinnedEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == SkinnedEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == SkinnedEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == SkinnedEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == SkinnedEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == SkinnedEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == SkinnedEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == SkinnedEffectTraits::ShaderPermutationCount, "array/max mismatch"); lights.InitializeConstants(constants.specularColorAndPower, constants.lightDirection, constants.lightDiffuseColor, constants.lightSpecularColor); @@ -499,7 +499,7 @@ void SkinnedEffect::SetLightingEnabled(bool value) { if (!value) { - throw std::exception("SkinnedEffect does not support turning off lighting"); + throw std::invalid_argument("SkinnedEffect does not support turning off lighting"); } } @@ -599,7 +599,7 @@ void SkinnedEffect::SetWeightsPerVertex(int value) (value != 2) && (value != 4)) { - throw std::out_of_range("WeightsPerVertex must be 1, 2, or 4"); + throw std::invalid_argument("WeightsPerVertex must be 1, 2, or 4"); } pImpl->weightsPerVertex = value; @@ -609,7 +609,7 @@ void SkinnedEffect::SetWeightsPerVertex(int value) void SkinnedEffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) { if (count > MaxBones) - throw std::out_of_range("count parameter out of range"); + throw std::invalid_argument("count parameter exceeds MaxBones"); auto boneConstant = pImpl->constants.bones; diff --git a/Kits/DirectXTK/Src/SpriteBatch.cpp b/Kits/DirectXTK/Src/SpriteBatch.cpp index 15ab1f26..9ab397d7 100644 --- a/Kits/DirectXTK/Src/SpriteBatch.cpp +++ b/Kits/DirectXTK/Src/SpriteBatch.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SpriteBatch.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -59,7 +59,7 @@ namespace // Internal SpriteBatch implementation class. -__declspec(align(16)) class SpriteBatch::Impl : public AlignedNew +XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew { public: Impl(_In_ ID3D11DeviceContext* deviceContext); @@ -82,7 +82,7 @@ __declspec(align(16)) class SpriteBatch::Impl : public AlignedNew + XM_ALIGNED_STRUCT(16) SpriteInfo : public AlignedNew { XMFLOAT4A source; XMFLOAT4A destination; @@ -393,7 +393,7 @@ void XM_CALLCONV SpriteBatch::Impl::Begin(SpriteSortMode sortMode, FXMMATRIX transformMatrix) { if (mInBeginEndPair) - throw std::exception("Cannot nest Begin calls on a single SpriteBatch"); + throw std::logic_error("Cannot nest Begin calls on a single SpriteBatch"); mSortMode = sortMode; mBlendState = blendState; @@ -407,7 +407,7 @@ void XM_CALLCONV SpriteBatch::Impl::Begin(SpriteSortMode sortMode, { // If we are in immediate mode, set device state ready for drawing. if (mContextResources->inImmediateMode) - throw std::exception("Only one SpriteBatch at a time can use SpriteSortMode_Immediate"); + throw std::logic_error("Only one SpriteBatch at a time can use SpriteSortMode_Immediate"); PrepareForRendering(); @@ -422,7 +422,7 @@ void XM_CALLCONV SpriteBatch::Impl::Begin(SpriteSortMode sortMode, void SpriteBatch::Impl::End() { if (!mInBeginEndPair) - throw std::exception("Begin must be called before End"); + throw std::logic_error("Begin must be called before End"); if (mSortMode == SpriteSortMode_Immediate) { @@ -433,7 +433,7 @@ void SpriteBatch::Impl::End() { // Draw the queued sprites now. if (mContextResources->inImmediateMode) - throw std::exception("Cannot end one SpriteBatch while another is using SpriteSortMode_Immediate"); + throw std::logic_error("Cannot end one SpriteBatch while another is using SpriteSortMode_Immediate"); PrepareForRendering(); FlushBatch(); @@ -457,10 +457,10 @@ void XM_CALLCONV SpriteBatch::Impl::Draw(ID3D11ShaderResourceView* texture, unsigned int flags) { if (!texture) - throw std::exception("Texture cannot be null"); + throw std::invalid_argument("Texture cannot be null"); if (!mInBeginEndPair) - throw std::exception("Begin must be called before Draw"); + throw std::logic_error("Begin must be called before Draw"); // Get a pointer to the output sprite. if (mSpriteQueueCount >= mSpriteQueueArraySize) @@ -934,7 +934,7 @@ XMVECTOR SpriteBatch::Impl::GetTextureSize(_In_ ID3D11ShaderResourceView* textur if (FAILED(resource.As(&texture2D))) { - throw std::exception("SpriteBatch can only draw Texture2D resources"); + throw std::invalid_argument("SpriteBatch can only draw Texture2D resources"); } // Query the texture size. @@ -961,7 +961,7 @@ XMMATRIX SpriteBatch::Impl::GetViewportTransform(_In_ ID3D11DeviceContext* devic deviceContext->RSGetViewports(&viewportCount, &mViewPort); if (viewportCount != 1) - throw std::exception("No viewport is set"); + throw std::runtime_error("No viewport is set"); } // Compute the matrix. diff --git a/Kits/DirectXTK/Src/SpriteFont.cpp b/Kits/DirectXTK/Src/SpriteFont.cpp index 1c9db5eb..354fa61a 100644 --- a/Kits/DirectXTK/Src/SpriteFont.cpp +++ b/Kits/DirectXTK/Src/SpriteFont.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SpriteFont.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -103,7 +103,7 @@ SpriteFont::Impl::Impl( if (reader->Read() != *magic) { DebugTrace("ERROR: SpriteFont provided with an invalid .spritefont file\n"); - throw std::exception("Not a MakeSpriteFont output binary"); + throw std::runtime_error("Not a MakeSpriteFont output binary"); } } @@ -170,7 +170,7 @@ SpriteFont::Impl::Impl( { if (!std::is_sorted(iglyphs, iglyphs + glyphCount)) { - throw std::exception("Glyphs must be in ascending codepoint order"); + throw std::runtime_error("Glyphs must be in ascending codepoint order"); } glyphsIndex.reserve(glyphs.size()); @@ -226,7 +226,7 @@ SpriteFont::Glyph const* SpriteFont::Impl::FindGlyph(wchar_t character) const } DebugTrace("ERROR: SpriteFont encountered a character not in the font (%u, %C), and no default glyph was provided\n", character, character); - throw std::exception("Character not in font"); + throw std::runtime_error("Character not in font"); } @@ -356,7 +356,7 @@ const wchar_t* SpriteFont::Impl::ConvertUTF8(_In_z_ const char *text) noexcept(f if (!result) { DebugTrace("ERROR: MultiByteToWideChar failed with error %u.\n", GetLastError()); - throw std::exception("MultiByteToWideChar"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "MultiByteToWideChar"); } return utfBuffer.get(); diff --git a/Kits/DirectXTK/Src/TeapotData.inc b/Kits/DirectXTK/Src/TeapotData.inc index 39e9a82d..532a6a40 100644 --- a/Kits/DirectXTK/Src/TeapotData.inc +++ b/Kits/DirectXTK/Src/TeapotData.inc @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: TeapotData.inc // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/ToneMapPostProcess.cpp b/Kits/DirectXTK/Src/ToneMapPostProcess.cpp index d5da7233..c911fd2f 100644 --- a/Kits/DirectXTK/Src/ToneMapPostProcess.cpp +++ b/Kits/DirectXTK/Src/ToneMapPostProcess.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: ToneMapPostProcess.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -34,7 +34,7 @@ namespace #endif // Constant buffer layout. Must match the shader! - __declspec(align(16)) struct ToneMapConstants + XM_ALIGNED_STRUCT(16) ToneMapConstants { // linearExposure is .x // paperWhiteNits is .y @@ -111,7 +111,7 @@ namespace #endif }; - static_assert(_countof(pixelShaders) == PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(pixelShaders)) == PixelShaderCount, "array/max mismatch"); const int pixelShaderIndices[] = { @@ -154,7 +154,7 @@ namespace #endif }; - static_assert(_countof(pixelShaderIndices) == ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(pixelShaderIndices)) == ShaderPermutationCount, "array/max mismatch"); // Factory for lazily instantiating shaders. class DeviceResources @@ -263,7 +263,7 @@ ToneMapPostProcess::Impl::Impl(_In_ ID3D11Device* device) { if (device->GetFeatureLevel() < D3D_FEATURE_LEVEL_10_0) { - throw std::exception("ToneMapPostProcess requires Feature Level 10.0 or later"); + throw std::runtime_error("ToneMapPostProcess requires Feature Level 10.0 or later"); } SetDebugObjectName(mConstantBuffer.GetBuffer(), "ToneMapPostProcess"); @@ -391,7 +391,7 @@ void ToneMapPostProcess::Process( void ToneMapPostProcess::SetOperator(Operator op) { if (op >= Operator_Max) - throw std::out_of_range("Tonemap operator not defined"); + throw std::invalid_argument("Tonemap operator not defined"); pImpl->op = op; } @@ -400,7 +400,7 @@ void ToneMapPostProcess::SetOperator(Operator op) void ToneMapPostProcess::SetTransferFunction(TransferFunction func) { if (func >= TransferFunction_Max) - throw std::out_of_range("Electro-optical transfer function not defined"); + throw std::invalid_argument("Electro-optical transfer function not defined"); pImpl->func = func; } diff --git a/Kits/DirectXTK/Src/VertexTypes.cpp b/Kits/DirectXTK/Src/VertexTypes.cpp index f349c94c..a2a8bfc8 100644 --- a/Kits/DirectXTK/Src/VertexTypes.cpp +++ b/Kits/DirectXTK/Src/VertexTypes.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: VertexTypes.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/WICTextureLoader.cpp b/Kits/DirectXTK/Src/WICTextureLoader.cpp index f764fa5d..9ab5d3aa 100644 --- a/Kits/DirectXTK/Src/WICTextureLoader.cpp +++ b/Kits/DirectXTK/Src/WICTextureLoader.cpp @@ -14,7 +14,7 @@ // 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. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -218,7 +218,7 @@ namespace //--------------------------------------------------------------------------------- DXGI_FORMAT _WICToDXGI(const GUID& guid) noexcept { - for (size_t i = 0; i < _countof(g_WICFormats); ++i) + for (size_t i = 0; i < std::size(g_WICFormats); ++i) { if (memcmp(&g_WICFormats[i].wic, &guid, sizeof(GUID)) == 0) return g_WICFormats[i].format; @@ -278,7 +278,7 @@ namespace _In_ unsigned int bindFlags, _In_ unsigned int cpuAccessFlags, _In_ unsigned int miscFlags, - _In_ unsigned int loadFlags, + _In_ WIC_LOADER_FLAGS loadFlags, _Outptr_opt_ ID3D11Resource** texture, _Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept { @@ -383,7 +383,7 @@ namespace } else { - for (size_t i = 0; i < _countof(g_WICConvert); ++i) + for (size_t i = 0; i < std::size(g_WICConvert); ++i) { if (memcmp(&g_WICConvert[i].source, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0) { diff --git a/Kits/DirectXTK/Src/XboxDDSTextureLoader.cpp b/Kits/DirectXTK/Src/XboxDDSTextureLoader.cpp index c84993ec..d3e0052c 100644 --- a/Kits/DirectXTK/Src/XboxDDSTextureLoader.cpp +++ b/Kits/DirectXTK/Src/XboxDDSTextureLoader.cpp @@ -8,7 +8,7 @@ // module in the DirectXTex package or as part of the DirectXTK library to load // these files which use standard Direct3D resource creation APIs. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTK/Src/dds.h b/Kits/DirectXTK/Src/dds.h index 6b02437a..25fe3e53 100644 --- a/Kits/DirectXTK/Src/dds.h +++ b/Kits/DirectXTK/Src/dds.h @@ -1,14 +1,14 @@ //-------------------------------------------------------------------------------------- -// dds.h +// DDS.h // -// This header defines constants and structures that are useful when parsing +// This header defines constants and structures that are useful when parsing // DDS files. DDS files were originally designed to use several structures // and constants that are native to DirectDraw and are defined in ddraw.h, -// such as DDSURFACEDESC2 and DDSCAPS2. This file defines similar -// (compatible) constants and structures so that one can use DDS files +// such as DDSURFACEDESC2 and DDSCAPS2. This file defines similar +// (compatible) constants and structures so that one can use DDS files // without needing to include ddraw.h. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -57,117 +57,134 @@ struct DDS_PIXELFORMAT | (static_cast(static_cast(ch1)) << 8) \ | (static_cast(static_cast(ch2)) << 16) \ | (static_cast(static_cast(ch3)) << 24)) -#endif /* defined(MAKEFOURCC) */ +#endif /* MAKEFOURCC */ -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT1 = +#ifndef DDSGLOBALCONST + #if defined(__GNUC__) && !defined(__MINGW32__) + #define DDSGLOBALCONST extern const __attribute__((weak)) + #else + #define DDSGLOBALCONST extern const __declspec(selectany) + #endif +#endif /* DDSGLOBALCONST */ + +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT1 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','1'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT2 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT2 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','2'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT3 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT3 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','3'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT4 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT4 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','4'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT5 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT5 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','5'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_UNORM = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_BC4_UNORM = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','U'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_SNORM = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_BC4_SNORM = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','S'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_UNORM = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_BC5_UNORM = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','U'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_SNORM = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_BC5_SNORM = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','S'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8_B8G8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_R8G8_B8G8 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('R','G','B','G'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G8R8_G8B8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_G8R8_G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('G','R','G','B'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_YUY2 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_YUY2 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('Y','U','Y','2'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_UYVY = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_UYVY = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('U','Y','V','Y'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8R8G8B8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8R8G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8R8G8B8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_X8R8G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8B8G8R8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8B8G8R8 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8B8G8R8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_X8B8G8R8 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G16R16 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_G16R16 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x0000ffff, 0xffff0000, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R5G6B5 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_R5G6B5 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0xf800, 0x07e0, 0x001f, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A1R5G5B5 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A1R5G5B5 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x7c00, 0x03e0, 0x001f, 0x8000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X1R5G5B5 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_X1R5G5B5 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0x7c00, 0x03e0, 0x001f, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A4R4G4B4 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A4R4G4B4 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x0f00, 0x00f0, 0x000f, 0xf000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X4R4G4B4 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_X4R4G4B4 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0x0f00, 0x00f0, 0x000f, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8B8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_R8G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 24, 0xff0000, 0x00ff00, 0x0000ff, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8R3G3B2 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8R3G3B2 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00e0, 0x001c, 0x0003, 0xff00 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R3G3B2 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_R3G3B2 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 8, 0xe0, 0x1c, 0x03, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A4L4 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A4L4 = { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 8, 0x0f, 0, 0, 0xf0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L8 = - { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 8, 0xff, 0, 0, 0 }; +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_L8 = + { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 8, 0xff, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L16 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_L16 = { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 16, 0xffff, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8L8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8L8 = { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 16, 0x00ff, 0, 0, 0xff00 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8L8_ALT = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8L8_ALT = { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 8, 0x00ff, 0, 0, 0xff00 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_L8_NVTT1 = + { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 8, 0xff, 0, 0, 0 }; + +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_L16_NVTT1 = + { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0xffff, 0, 0, 0 }; + +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8L8_NVTT1 = + { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00ff, 0, 0, 0xff00 }; + +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8 = { sizeof(DDS_PIXELFORMAT), DDS_ALPHA, 0, 8, 0, 0, 0, 0xff }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_V8U8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_V8U8 = { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 16, 0x00ff, 0xff00, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_Q8W8V8U8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_Q8W8V8U8 = { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_V16U16 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_V16U16 = { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x0000ffff, 0xffff0000, 0, 0 }; // D3DFMT_A2R10G10B10/D3DFMT_A2B10G10R10 should be written using DX10 extension to avoid D3DX 10:10:10:2 reversal issue -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A2R10G10B10 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A2R10G10B10 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A2B10G10R10 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A2B10G10R10 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000 }; // We do not support the following legacy Direct3D 9 formats: @@ -176,10 +193,10 @@ extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A2B10G10R10 = // DDSPF_X8L8V8U8 = { sizeof(DDS_PIXELFORMAT), DDS_BUMPLUMINANCE, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0 }; // This indicates the DDS_HEADER_DXT10 extension is present (the format is in dxgiFormat) -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DX10 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DX10 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','1','0'), 0, 0, 0, 0, 0 }; -#define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT +#define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT #define DDS_HEADER_FLAGS_MIPMAP 0x00020000 // DDSD_MIPMAPCOUNT #define DDS_HEADER_FLAGS_VOLUME 0x00800000 // DDSD_DEPTH #define DDS_HEADER_FLAGS_PITCH 0x00000008 // DDSD_PITCH @@ -210,9 +227,9 @@ extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DX10 = // Subset here matches D3D10_RESOURCE_DIMENSION and D3D11_RESOURCE_DIMENSION enum DDS_RESOURCE_DIMENSION : uint32_t { - DDS_DIMENSION_TEXTURE1D = 2, - DDS_DIMENSION_TEXTURE2D = 3, - DDS_DIMENSION_TEXTURE3D = 4, + DDS_DIMENSION_TEXTURE1D = 2, + DDS_DIMENSION_TEXTURE2D = 3, + DDS_DIMENSION_TEXTURE3D = 4, }; // Subset here matches D3D10_RESOURCE_MISC_FLAG and D3D11_RESOURCE_MISC_FLAG diff --git a/Kits/DirectXTK/Src/pch.cpp b/Kits/DirectXTK/Src/pch.cpp index 09b51b53..04dd2c8a 100644 --- a/Kits/DirectXTK/Src/pch.cpp +++ b/Kits/DirectXTK/Src/pch.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: pch.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK/Src/pch.h b/Kits/DirectXTK/Src/pch.h index 74f24c77..fcb379f5 100644 --- a/Kits/DirectXTK/Src/pch.h +++ b/Kits/DirectXTK/Src/pch.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: pch.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -65,6 +65,7 @@ #pragma clang diagnostic ignored "-Wgnu-anonymous-struct" #pragma clang diagnostic ignored "-Wlanguage-extension-token" #pragma clang diagnostic ignored "-Wmissing-variable-declarations" +#pragma clang diagnostic ignored "-Wmicrosoft-include" #pragma clang diagnostic ignored "-Wnested-anon-types" #pragma clang diagnostic ignored "-Wreserved-id-macro" #pragma clang diagnostic ignored "-Wswitch-enum" @@ -94,6 +95,10 @@ #define _WIN32_WINNT_WIN10 0x0A00 #endif +#ifndef WINAPI_FAMILY_GAMES +#define WINAPI_FAMILY_GAMES 6 +#endif + #ifdef _GAMING_XBOX #error This version of DirectX Tool Kit not supported for GDK #elif defined(_XBOX_ONE) && defined(_TITLE) @@ -102,23 +107,24 @@ #include #endif -#define _XM_NO_XMVECTOR_OVERLOADS_ - -#include -#include -#include - #include #include +#include #include #include +#include +#include +#include #include +#include #include #include #include +#include #include #include #include +#include #include #include #include @@ -130,6 +136,16 @@ #include +#define _XM_NO_XMVECTOR_OVERLOADS_ + +#include +#include +#include + +#if (DIRECTX_MATH_VERSION < 315) +#define XM_ALIGNED_STRUCT(x) __declspec(align(x)) struct +#endif + #pragma warning(push) #pragma warning(disable : 4467 5038 5204 5220) #include diff --git a/Kits/DirectXTK/Src/vbo.h b/Kits/DirectXTK/Src/vbo.h index ff999d11..ce600a45 100644 --- a/Kits/DirectXTK/Src/vbo.h +++ b/Kits/DirectXTK/Src/vbo.h @@ -7,7 +7,7 @@ // The meshconvert sample tool for DirectXMesh can produce this file type // http://go.microsoft.com/fwlink/?LinkID=324981 // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK12/Audio/AudioEngine.cpp b/Kits/DirectXTK12/Audio/AudioEngine.cpp index eb193429..0551cdb9 100644 --- a/Kits/DirectXTK12/Audio/AudioEngine.cpp +++ b/Kits/DirectXTK12/Audio/AudioEngine.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: AudioEngine.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -32,7 +32,7 @@ namespace mCriticalError.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mCriticalError) { - throw std::exception("CreateEvent"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } } @@ -66,7 +66,7 @@ namespace mBufferEnd.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mBufferEnd) { - throw std::exception("CreateEvent"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } } @@ -248,7 +248,7 @@ namespace } } -static_assert(_countof(gReverbPresets) == Reverb_MAX, "AUDIO_ENGINE_REVERB enum mismatch"); +static_assert(static_cast(std::size(gReverbPresets)) == Reverb_MAX, "AUDIO_ENGINE_REVERB enum mismatch"); //====================================================================================== @@ -674,7 +674,7 @@ bool AudioEngine::Impl::Update() return false; HANDLE events[2] = { mEngineCallback.mCriticalError.get(), mVoiceCallback.mBufferEnd.get() }; - switch (WaitForMultipleObjectsEx(_countof(events), events, FALSE, 0, FALSE)) + switch (WaitForMultipleObjectsEx(static_cast(std::size(events)), events, FALSE, 0, FALSE)) { default: case WAIT_TIMEOUT: @@ -723,7 +723,7 @@ bool AudioEngine::Impl::Update() break; case WAIT_FAILED: - throw std::exception("WaitForMultipleObjects"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForMultipleObjectsEx"); } // @@ -827,12 +827,12 @@ void AudioEngine::Impl::AllocateVoice( IXAudio2SourceVoice** voice) { if (!wfx) - throw std::exception("Wave format is required\n"); + throw std::invalid_argument("Wave format is required\n"); // No need to call IsValid on wfx because CreateSourceVoice will do that if (!voice) - throw std::exception("Voice pointer must be non-null"); + throw std::invalid_argument("Voice pointer must be non-null"); *voice = nullptr; @@ -852,7 +852,7 @@ void AudioEngine::Impl::AllocateVoice( DebugTrace((flags & SoundEffectInstance_NoSetPitch) ? "ERROR: One-shot voices must support pitch-shifting for voice reuse\n" : "ERROR: One-use voices cannot use 3D positional audio\n"); - throw std::exception("Invalid flags for one-shot voice"); + throw std::invalid_argument("Invalid flags for one-shot voice"); } #ifdef VERBOSE_TRACE @@ -947,7 +947,7 @@ void AudioEngine::Impl::AllocateVoice( if (FAILED(hr)) { DebugTrace("ERROR: CreateSourceVoice (reuse) failed with error %08X\n", static_cast(hr)); - throw std::exception("CreateSourceVoice"); + throw std::runtime_error("CreateSourceVoice"); } } @@ -956,7 +956,7 @@ void AudioEngine::Impl::AllocateVoice( if (FAILED(hr)) { DebugTrace("ERROR: SetSourceSampleRate failed with error %08X\n", static_cast(hr)); - throw std::exception("SetSourceSampleRate"); + throw std::runtime_error("SetSourceSampleRate"); } } } @@ -977,7 +977,7 @@ void AudioEngine::Impl::AllocateVoice( { DebugTrace("ERROR: Too many instance voices (%zu >= %zu); see TrimVoicePool\n", mVoiceInstances + 1, maxVoiceInstances); - throw std::exception("Too many instance voices"); + throw std::runtime_error("Too many instance voices"); } UINT32 vflags = (flags & SoundEffectInstance_NoSetPitch) ? XAUDIO2_VOICE_NOPITCH : 0u; @@ -1012,7 +1012,7 @@ void AudioEngine::Impl::AllocateVoice( if (FAILED(hr)) { DebugTrace("ERROR: CreateSourceVoice failed with error %08X\n", static_cast(hr)); - throw std::exception("CreateSourceVoice"); + throw std::runtime_error("CreateSourceVoice"); } else if (!oneshot) { @@ -1131,7 +1131,7 @@ AudioEngine::AudioEngine( if (flags & AudioEngine_ThrowOnNoAudioHW) { DebugTrace("ERROR: AudioEngine found no default audio device\n"); - throw std::exception("AudioEngineNoAudioHW"); + throw std::runtime_error("AudioEngineNoAudioHW"); } else { @@ -1143,7 +1143,7 @@ AudioEngine::AudioEngine( DebugTrace("ERROR: AudioEngine failed (%08X) to initialize using device [%ls]\n", static_cast(hr), (deviceId) ? deviceId : L"default"); - throw std::exception("AudioEngine"); + throw std::runtime_error("AudioEngine"); } } } @@ -1198,7 +1198,7 @@ bool AudioEngine::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceId) if (pImpl->mEngineFlags & AudioEngine_ThrowOnNoAudioHW) { DebugTrace("ERROR: AudioEngine found no default audio device on Reset\n"); - throw std::exception("AudioEngineNoAudioHW"); + throw std::runtime_error("AudioEngineNoAudioHW"); } else { @@ -1210,7 +1210,7 @@ bool AudioEngine::Reset(const WAVEFORMATEX* wfx, const wchar_t* deviceId) { DebugTrace("ERROR: AudioEngine failed (%08X) to Reset using device [%ls]\n", static_cast(hr), (deviceId) ? deviceId : L"default"); - throw std::exception("AudioEngine::Reset"); + throw std::runtime_error("AudioEngine::Reset"); } } @@ -1262,7 +1262,7 @@ void AudioEngine::SetMasterVolume(float volume) void AudioEngine::SetReverb(AUDIO_ENGINE_REVERB reverb) { if (reverb >= Reverb_MAX) - throw std::out_of_range("AudioEngine::SetReverb"); + throw std::invalid_argument("reverb parameter is invalid"); if (reverb == Reverb_Off) { @@ -1350,7 +1350,7 @@ bool AudioEngine::IsCriticalError() const noexcept void AudioEngine::SetDefaultSampleRate(int sampleRate) { if ((sampleRate < XAUDIO2_MIN_SAMPLE_RATE) || (sampleRate > XAUDIO2_MAX_SAMPLE_RATE)) - throw std::exception("Default sample rate is out of range"); + throw std::out_of_range("Default sample rate is out of range"); pImpl->defaultRate = sampleRate; } @@ -1552,7 +1552,7 @@ std::vector AudioEngine::GetRendererDetails() while (operation->Status == Windows::Foundation::AsyncStatus::Started) { Sleep(100); } if (operation->Status != Windows::Foundation::AsyncStatus::Completed) { - throw std::exception("FindAllAsync"); + throw std::runtime_error("FindAllAsync"); } DeviceInformationCollection^ devices = operation->GetResults(); @@ -1607,7 +1607,7 @@ std::vector AudioEngine::GetRendererDetails() if (status != ABI::Windows::Foundation::AsyncStatus::Completed) { - throw std::exception("FindAllAsyncDeviceClass"); + throw std::runtime_error("FindAllAsyncDeviceClass"); } ComPtr> devices; diff --git a/Kits/DirectXTK12/Audio/DynamicSoundEffectInstance.cpp b/Kits/DirectXTK12/Audio/DynamicSoundEffectInstance.cpp index 4dc9ee75..559eecba 100644 --- a/Kits/DirectXTK12/Audio/DynamicSoundEffectInstance.cpp +++ b/Kits/DirectXTK12/Audio/DynamicSoundEffectInstance.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DynamicSoundEffectInstance.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -35,13 +35,13 @@ class DynamicSoundEffectInstance::Impl : public IVoiceNotify || (sampleRate > XAUDIO2_MAX_SAMPLE_RATE)) { DebugTrace("DynamicSoundEffectInstance sampleRate must be in range %u...%u\n", XAUDIO2_MIN_SAMPLE_RATE, XAUDIO2_MAX_SAMPLE_RATE); - throw std::invalid_argument("DynamicSoundEffectInstance"); + throw std::out_of_range("DynamicSoundEffectInstance"); } if (!channels || (channels > 8)) { DebugTrace("DynamicSoundEffectInstance channels must be in range 1...8\n"); - throw std::invalid_argument("DynamicSoundEffectInstance"); + throw std::out_of_range("DynamicSoundEffectInstance channel count out of range"); } switch (sampleBits) @@ -52,13 +52,13 @@ class DynamicSoundEffectInstance::Impl : public IVoiceNotify default: DebugTrace("DynamicSoundEffectInstance sampleBits must be 8-bit or 16-bit\n"); - throw std::invalid_argument("DynamicSoundEffectInstance"); + throw std::invalid_argument("DynamicSoundEffectInstance supports 8 or 16 bit"); } mBufferEvent.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mBufferEvent) { - throw std::exception("CreateEvent"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } CreateIntegerPCM(&mWaveFormat, sampleRate, channels, sampleBits); @@ -177,7 +177,7 @@ _Use_decl_annotations_ void DynamicSoundEffectInstance::Impl::SubmitBuffer(const uint8_t* pAudioData, uint32_t offset, size_t audioBytes) { if (!pAudioData || !audioBytes) - throw std::exception("Invalid audio data buffer"); + throw std::invalid_argument("Invalid audio data buffer"); if (audioBytes > UINT32_MAX) throw std::out_of_range("SubmitBuffer"); @@ -204,7 +204,7 @@ void DynamicSoundEffectInstance::Impl::SubmitBuffer(const uint8_t* pAudioData, u DebugTrace("\tFormat Tag %u, %u channels, %u-bit, %u Hz, %zu bytes [%u offset)\n", mWaveFormat.wFormatTag, mWaveFormat.nChannels, mWaveFormat.wBitsPerSample, mWaveFormat.nSamplesPerSec, audioBytes, offset); #endif - throw std::exception("SubmitSourceBuffer"); + throw std::runtime_error("SubmitSourceBuffer"); } } @@ -226,7 +226,7 @@ void DynamicSoundEffectInstance::Impl::OnUpdate() break; case WAIT_FAILED: - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); } } @@ -317,7 +317,7 @@ void DynamicSoundEffectInstance::SetPan(float pan) } -void DynamicSoundEffectInstance::Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords) +void DynamicSoundEffectInstance::Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords) { pImpl->mBase.Apply3D(listener, emitter, rhcoords); } @@ -381,6 +381,12 @@ int DynamicSoundEffectInstance::GetPendingBufferCount() const noexcept } +unsigned int DynamicSoundEffectInstance::GetChannelCount() const noexcept +{ + return pImpl->mBase.GetChannelCount(); +} + + const WAVEFORMATEX* DynamicSoundEffectInstance::GetFormat() const noexcept { return pImpl->GetFormat(); diff --git a/Kits/DirectXTK12/Audio/SoundCommon.cpp b/Kits/DirectXTK12/Audio/SoundCommon.cpp index ef204d59..9f324ba4 100644 --- a/Kits/DirectXTK12/Audio/SoundCommon.cpp +++ b/Kits/DirectXTK12/Audio/SoundCommon.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SoundCommon.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -505,7 +505,11 @@ uint32_t DirectX::GetDefaultChannelMask(int channels) noexcept _Use_decl_annotations_ -void DirectX::CreateIntegerPCM(WAVEFORMATEX* wfx, int sampleRate, int channels, int sampleBits) noexcept +void DirectX::CreateIntegerPCM( + WAVEFORMATEX* wfx, + int sampleRate, + int channels, + int sampleBits) noexcept { int blockAlign = channels * sampleBits / 8; @@ -522,7 +526,10 @@ void DirectX::CreateIntegerPCM(WAVEFORMATEX* wfx, int sampleRate, int channels, _Use_decl_annotations_ -void DirectX::CreateFloatPCM(WAVEFORMATEX* wfx, int sampleRate, int channels) noexcept +void DirectX::CreateFloatPCM( + WAVEFORMATEX* wfx, + int sampleRate, + int channels) noexcept { int blockAlign = channels * 4; @@ -539,7 +546,12 @@ void DirectX::CreateFloatPCM(WAVEFORMATEX* wfx, int sampleRate, int channels) no _Use_decl_annotations_ -void DirectX::CreateADPCM(WAVEFORMATEX* wfx, size_t wfxSize, int sampleRate, int channels, int samplesPerBlock) noexcept(false) +void DirectX::CreateADPCM( + WAVEFORMATEX* wfx, + size_t wfxSize, + int sampleRate, + int channels, + int samplesPerBlock) noexcept(false) { if (wfxSize < (sizeof(WAVEFORMATEX) + 32 /*MSADPCM_FORMAT_EXTRA_BYTES*/)) { @@ -578,7 +590,13 @@ void DirectX::CreateADPCM(WAVEFORMATEX* wfx, size_t wfxSize, int sampleRate, int #ifdef DIRECTX_ENABLE_XWMA _Use_decl_annotations_ -void DirectX::CreateXWMA(WAVEFORMATEX* wfx, int sampleRate, int channels, int blockAlign, int avgBytes, bool wma3) noexcept +void DirectX::CreateXWMA( + WAVEFORMATEX* wfx, + int sampleRate, + int channels, + int blockAlign, + int avgBytes, + bool wma3) noexcept { wfx->wFormatTag = static_cast((wma3) ? WAVE_FORMAT_WMAUDIO3 : WAVE_FORMAT_WMAUDIO2); wfx->nChannels = static_cast(channels); @@ -595,7 +613,14 @@ void DirectX::CreateXWMA(WAVEFORMATEX* wfx, int sampleRate, int channels, int bl #ifdef DIRECTX_ENABLE_XMA2 _Use_decl_annotations_ -void DirectX::CreateXMA2(WAVEFORMATEX* wfx, size_t wfxSize, int sampleRate, int channels, int bytesPerBlock, int blockCount, int samplesEncoded) noexcept(false) +void DirectX::CreateXMA2( + WAVEFORMATEX* wfx, + size_t wfxSize, + int sampleRate, + int channels, + int bytesPerBlock, + int blockCount, + int samplesEncoded) noexcept(false) { if (wfxSize < sizeof(XMA2WAVEFORMATEX)) { @@ -645,13 +670,13 @@ bool DirectX::ComputePan(float pan, unsigned int channels, float* matrix) noexce if (channels == 1) { // Mono panning - float left = (pan >= 0) ? (1.f - pan) : 1.f; + float left = 1.f - pan; left = std::min(1.f, left); - left = std::max(-1.f, left); + left = std::max(0.f, left); - float right = (pan <= 0) ? (-pan - 1.f) : 1.f; + float right = pan + 1.f; right = std::min(1.f, right); - right = std::max(-1.f, right); + right = std::max(0.f, right); matrix[0] = left; matrix[1] = right; @@ -709,7 +734,7 @@ void SoundEffectInstanceBase::SetPan(float pan) } -void SoundEffectInstanceBase::Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords) +void SoundEffectInstanceBase::Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords) { if (!voice) return; @@ -717,7 +742,7 @@ void SoundEffectInstanceBase::Apply3D(const AudioListener& listener, const Audio if (!(mFlags & SoundEffectInstance_Use3D)) { DebugTrace("ERROR: Apply3D called for an instance created without SoundEffectInstance_Use3D set\n"); - throw std::exception("Apply3D"); + throw std::runtime_error("Apply3D"); } DWORD dwCalcFlags = X3DAUDIO_CALCULATE_MATRIX | X3DAUDIO_CALCULATE_DOPPLER | X3DAUDIO_CALCULATE_LPF_DIRECT; @@ -796,3 +821,73 @@ void SoundEffectInstanceBase::Apply3D(const AudioListener& listener, const Audio } +//====================================================================================== +// AudioEmitter helper +//====================================================================================== + +namespace +{ + // **Note these constants came from xact3d3.h in the legacy DirectX SDK** + // + // Supported speaker positions, represented as azimuth angles. + // + // Here's a picture of the azimuth angles for the 8 cardinal points, + // seen from above. The emitter's base position is at the origin 0. + // + // FRONT + // | 0 <-- azimuth + // | + // 7pi/4 \ | / pi/4 + // \ | / + // LEFT \|/ RIGHT + // 3pi/2-------0-------pi/2 + // /|\ + // / | \ + // 5pi/4 / | \ 3pi/4 + // | + // | pi + // BACK + // + + constexpr float LEFT_AZIMUTH = 3 * X3DAUDIO_PI / 2; + constexpr float RIGHT_AZIMUTH = X3DAUDIO_PI / 2; + constexpr float FRONT_LEFT_AZIMUTH = 7 * X3DAUDIO_PI / 4; + constexpr float FRONT_RIGHT_AZIMUTH = X3DAUDIO_PI / 4; + constexpr float FRONT_CENTER_AZIMUTH = 0.0f; + constexpr float LOW_FREQUENCY_AZIMUTH = X3DAUDIO_2PI; + constexpr float BACK_LEFT_AZIMUTH = 5 * X3DAUDIO_PI / 4; + constexpr float BACK_RIGHT_AZIMUTH = 3 * X3DAUDIO_PI / 4; + constexpr float BACK_CENTER_AZIMUTH = X3DAUDIO_PI; + + constexpr float c_channelAzimuths[9][8] = + { + /* 0 */ { 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }, + /* 1 */ { 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }, + /* 2 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }, + /* 2.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, LOW_FREQUENCY_AZIMUTH, 0.f, 0.f, 0.f, 0.f, 0.f }, + /* 4.0 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, 0.f, 0.f, 0.f, 0.f }, + /* 4.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, LOW_FREQUENCY_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, 0.f, 0.f, 0.f }, + /* 5.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, FRONT_CENTER_AZIMUTH, LOW_FREQUENCY_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, 0.f, 0.f }, + /* 6.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, FRONT_CENTER_AZIMUTH, LOW_FREQUENCY_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, BACK_CENTER_AZIMUTH, 0.f }, + /* 7.1 */ { FRONT_LEFT_AZIMUTH, FRONT_RIGHT_AZIMUTH, FRONT_CENTER_AZIMUTH, LOW_FREQUENCY_AZIMUTH, BACK_LEFT_AZIMUTH, BACK_RIGHT_AZIMUTH, LEFT_AZIMUTH, RIGHT_AZIMUTH } + }; +} + +void AudioEmitter::EnableDefaultMultiChannel(unsigned int channels, float radius) +{ + if (channels > XAUDIO2_MAX_AUDIO_CHANNELS) + throw std::invalid_argument("Invalid channel count"); + + ChannelCount = channels; + ChannelRadius = radius; + pChannelAzimuths = EmitterAzimuths; + + if (channels <= 8) + { + memcpy(EmitterAzimuths, &c_channelAzimuths[channels][0], sizeof(float) * 8); + } + else + { + memset(EmitterAzimuths, 0, sizeof(float) * size_t(channels)); + } +} diff --git a/Kits/DirectXTK12/Audio/SoundCommon.h b/Kits/DirectXTK12/Audio/SoundCommon.h index a9696b54..e60c5c35 100644 --- a/Kits/DirectXTK12/Audio/SoundCommon.h +++ b/Kits/DirectXTK12/Audio/SoundCommon.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SoundCommon.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -63,14 +63,19 @@ namespace DirectX // Helpers for creating various wave format structures - void CreateIntegerPCM(_Out_ WAVEFORMATEX* wfx, int sampleRate, int channels, int sampleBits) noexcept; - void CreateFloatPCM(_Out_ WAVEFORMATEX* wfx, int sampleRate, int channels) noexcept; - void CreateADPCM(_Out_writes_bytes_(wfxSize) WAVEFORMATEX* wfx, size_t wfxSize, int sampleRate, int channels, int samplesPerBlock) noexcept(false); + void CreateIntegerPCM(_Out_ WAVEFORMATEX* wfx, + int sampleRate, int channels, int sampleBits) noexcept; + void CreateFloatPCM(_Out_ WAVEFORMATEX* wfx, + int sampleRate, int channels) noexcept; + void CreateADPCM(_Out_writes_bytes_(wfxSize) WAVEFORMATEX* wfx, size_t wfxSize, + int sampleRate, int channels, int samplesPerBlock) noexcept(false); #ifdef DIRECTX_ENABLE_XWMA - void CreateXWMA(_Out_ WAVEFORMATEX* wfx, int sampleRate, int channels, int blockAlign, int avgBytes, bool wma3) noexcept; + void CreateXWMA(_Out_ WAVEFORMATEX* wfx, + int sampleRate, int channels, int blockAlign, int avgBytes, bool wma3) noexcept; #endif #ifdef DIRECTX_ENABLE_XMA2 - void CreateXMA2(_Out_writes_bytes_(wfxSize) WAVEFORMATEX* wfx, size_t wfxSize, int sampleRate, int channels, int bytesPerBlock, int blockCount, int samplesEncoded) noexcept(false); + void CreateXMA2(_Out_writes_bytes_(wfxSize) WAVEFORMATEX* wfx, size_t wfxSize, + int sampleRate, int channels, int bytesPerBlock, int blockCount, int samplesEncoded) noexcept(false); #endif // Helper for computing pan volume matrix @@ -208,7 +213,7 @@ namespace DirectX } } - void Pause() noexcept + void Pause() noexcept { if (voice && state == PLAYING) { @@ -248,7 +253,7 @@ namespace DirectX if ((mFlags & SoundEffectInstance_NoSetPitch) && pitch != 0.f) { DebugTrace("ERROR: Sound effect instance was created with the NoSetPitch flag\n"); - throw std::exception("SetPitch"); + throw std::runtime_error("SetPitch"); } mPitch = pitch; @@ -264,7 +269,7 @@ namespace DirectX void SetPan(float pan); - void Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords); + void Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords); SoundState GetState(bool autostop) noexcept { @@ -294,6 +299,11 @@ namespace DirectX return static_cast(xstate.BuffersQueued); } + unsigned int GetChannelCount() const noexcept + { + return mDSPSettings.SrcChannelCount; + } + void OnCriticalError() noexcept { if (voice) diff --git a/Kits/DirectXTK12/Audio/SoundEffect.cpp b/Kits/DirectXTK12/Audio/SoundEffect.cpp index 246b087b..378d08bf 100644 --- a/Kits/DirectXTK12/Audio/SoundEffect.cpp +++ b/Kits/DirectXTK12/Audio/SoundEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SoundEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -15,6 +15,10 @@ #include #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wnonportable-system-include-path" +#endif + #include #include #endif @@ -352,7 +356,7 @@ void SoundEffect::Impl::Play(float volume, float pitch, float pan) DebugTrace("ERROR: SoundEffect failed (%08X) when submitting buffer:\n", static_cast(hr)); DebugTrace("\tFormat Tag %u, %u channels, %u-bit, %u Hz, %u bytes\n", mWaveFormat->wFormatTag, mWaveFormat->nChannels, mWaveFormat->wBitsPerSample, mWaveFormat->nSamplesPerSec, mAudioBytes); - throw std::exception("SubmitSourceBuffer"); + throw std::runtime_error("SubmitSourceBuffer"); } InterlockedIncrement(&mOneShots); @@ -375,7 +379,7 @@ SoundEffect::SoundEffect(AudioEngine* engine, const wchar_t* waveFileName) { DebugTrace("ERROR: SoundEffect failed (%08X) to load from .wav file \"%ls\"\n", static_cast(hr), waveFileName); - throw std::exception("SoundEffect"); + throw std::runtime_error("SoundEffect"); } #ifdef DIRECTX_ENABLE_SEEK_TABLES @@ -391,7 +395,7 @@ SoundEffect::SoundEffect(AudioEngine* engine, const wchar_t* waveFileName) { DebugTrace("ERROR: SoundEffect failed (%08X) to intialize from .wav file \"%ls\"\n", static_cast(hr), waveFileName); - throw std::exception("SoundEffect"); + throw std::runtime_error("SoundEffect"); } } @@ -409,7 +413,7 @@ SoundEffect::SoundEffect(AudioEngine* engine, std::unique_ptr& wavDat if (FAILED(hr)) { DebugTrace("ERROR: SoundEffect failed (%08X) to intialize\n", static_cast(hr)); - throw std::exception("SoundEffect"); + throw std::runtime_error("SoundEffect"); } } @@ -428,7 +432,7 @@ SoundEffect::SoundEffect(AudioEngine* engine, std::unique_ptr& wavDat if (FAILED(hr)) { DebugTrace("ERROR: SoundEffect failed (%08X) to intialize\n", static_cast(hr)); - throw std::exception("SoundEffect"); + throw std::runtime_error("SoundEffect"); } } @@ -444,7 +448,7 @@ SoundEffect::SoundEffect(AudioEngine* engine, std::unique_ptr& wavDat if (FAILED(hr)) { DebugTrace("ERROR: SoundEffect failed (%08X) to intialize\n", static_cast(hr)); - throw std::exception("SoundEffect"); + throw std::runtime_error("SoundEffect"); } } diff --git a/Kits/DirectXTK12/Audio/SoundEffectInstance.cpp b/Kits/DirectXTK12/Audio/SoundEffectInstance.cpp index 36920f5c..88e6eae0 100644 --- a/Kits/DirectXTK12/Audio/SoundEffectInstance.cpp +++ b/Kits/DirectXTK12/Audio/SoundEffectInstance.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SoundEffectInstance.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -215,7 +215,7 @@ void SoundEffectInstance::Impl::Play(bool loop) wfx->wFormatTag, wfx->nChannels, wfx->wBitsPerSample, wfx->nSamplesPerSec, length); #endif mBase.Stop(true, mLooped); - throw std::exception("SubmitSourceBuffer"); + throw std::runtime_error("SubmitSourceBuffer"); } } @@ -316,7 +316,7 @@ void SoundEffectInstance::SetPan(float pan) } -void SoundEffectInstance::Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords) +void SoundEffectInstance::Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords) { pImpl->mBase.Apply3D(listener, emitter, rhcoords); } @@ -335,6 +335,12 @@ SoundState SoundEffectInstance::GetState() noexcept } +unsigned int SoundEffectInstance::GetChannelCount() const noexcept +{ + return pImpl->mBase.GetChannelCount(); +} + + IVoiceNotify* SoundEffectInstance::GetVoiceNotify() const noexcept { return pImpl.get(); diff --git a/Kits/DirectXTK12/Audio/SoundStreamInstance.cpp b/Kits/DirectXTK12/Audio/SoundStreamInstance.cpp index 8d05bcb9..f3d9ab02 100644 --- a/Kits/DirectXTK12/Audio/SoundStreamInstance.cpp +++ b/Kits/DirectXTK12/Audio/SoundStreamInstance.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SoundStreamInstance.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -15,6 +15,10 @@ #include "SoundCommon.h" #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wnonportable-system-include-path" +#endif + #include #include #endif @@ -140,7 +144,7 @@ class SoundStreamInstance::Impl : public IVoiceNotify mBufferRead.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mBufferEnd || !mBufferRead) { - throw std::exception("CreateEvent"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } ThrowIfFailed(AllocateStreamingBuffers(wfx)); @@ -232,7 +236,7 @@ class SoundStreamInstance::Impl : public IVoiceNotify return; HANDLE events[] = { mBufferRead.get(), mBufferEnd.get() }; - switch (WaitForMultipleObjectsEx(_countof(events), events, FALSE, 0, FALSE)) + switch (WaitForMultipleObjectsEx(static_cast(std::size(events)), events, FALSE, 0, FALSE)) { case WAIT_TIMEOUT: break; @@ -263,7 +267,7 @@ class SoundStreamInstance::Impl : public IVoiceNotify break; case WAIT_FAILED: - throw std::exception("WaitForMultipleObjects"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForMultipleObjectsEx"); } } @@ -819,7 +823,7 @@ void SoundStreamInstance::SetPan(float pan) } -void SoundStreamInstance::Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords) +void SoundStreamInstance::Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords) { pImpl->mBase.Apply3D(listener, emitter, rhcoords); } @@ -843,6 +847,12 @@ SoundState SoundStreamInstance::GetState() noexcept } +unsigned int SoundStreamInstance::GetChannelCount() const noexcept +{ + return pImpl->mBase.GetChannelCount(); +} + + IVoiceNotify* SoundStreamInstance::GetVoiceNotify() const noexcept { return pImpl.get(); diff --git a/Kits/DirectXTK12/Audio/WAVFileReader.cpp b/Kits/DirectXTK12/Audio/WAVFileReader.cpp index 0c370639..ea517ffd 100644 --- a/Kits/DirectXTK12/Audio/WAVFileReader.cpp +++ b/Kits/DirectXTK12/Audio/WAVFileReader.cpp @@ -3,7 +3,7 @@ // // Functions for loading WAV audio files // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK12/Audio/WAVFileReader.h b/Kits/DirectXTK12/Audio/WAVFileReader.h index 8a6f4dce..c9191799 100644 --- a/Kits/DirectXTK12/Audio/WAVFileReader.h +++ b/Kits/DirectXTK12/Audio/WAVFileReader.h @@ -3,7 +3,7 @@ // // Functions for loading WAV audio files // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK12/Audio/WaveBank.cpp b/Kits/DirectXTK12/Audio/WaveBank.cpp index aa379c4f..6a2a66eb 100644 --- a/Kits/DirectXTK12/Audio/WaveBank.cpp +++ b/Kits/DirectXTK12/Audio/WaveBank.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: WaveBank.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -162,7 +162,7 @@ void WaveBank::Impl::Play(unsigned int index, float volume, float pitch, float p if (mStreaming) { DebugTrace("ERROR: One-shots can only be created from an in-memory wave bank\n"); - throw std::exception("WaveBank::Play"); + throw std::runtime_error("WaveBank::Play"); } if (index >= mReader.Count()) @@ -249,7 +249,7 @@ void WaveBank::Impl::Play(unsigned int index, float volume, float pitch, float p DebugTrace("ERROR: WaveBank failed (%08X) when submitting buffer:\n", static_cast(hr)); DebugTrace("\tFormat Tag %u, %u channels, %u-bit, %u Hz, %u bytes\n", wfx->wFormatTag, wfx->nChannels, wfx->wBitsPerSample, wfx->nSamplesPerSec, metadata.lengthBytes); - throw std::exception("SubmitSourceBuffer"); + throw std::runtime_error("SubmitSourceBuffer"); } InterlockedIncrement(&mOneShots); @@ -270,7 +270,7 @@ WaveBank::WaveBank(AudioEngine* engine, const wchar_t* wbFileName) { DebugTrace("ERROR: WaveBank failed (%08X) to intialize from .xwb file \"%ls\"\n", static_cast(hr), wbFileName); - throw std::exception("WaveBank"); + throw std::runtime_error("WaveBank"); } DebugTrace("INFO: WaveBank \"%hs\" with %u entries loaded from .xwb file \"%ls\"\n", @@ -346,7 +346,7 @@ std::unique_ptr WaveBank::CreateInstance(unsigned int index if (pImpl->mStreaming) { DebugTrace("ERROR: SoundEffectInstances can only be created from an in-memory wave bank\n"); - throw std::exception("WaveBank::CreateInstance"); + throw std::runtime_error("WaveBank::CreateInstance"); } if (index >= wb.Count()) @@ -389,7 +389,7 @@ std::unique_ptr WaveBank::CreateStreamInstance(unsigned int if (!pImpl->mStreaming) { DebugTrace("ERROR: SoundStreamInstances can only be created from a streaming wave bank\n"); - throw std::exception("WaveBank::CreateStreamInstance"); + throw std::runtime_error("WaveBank::CreateStreamInstance"); } if (index >= wb.Count()) diff --git a/Kits/DirectXTK12/Audio/WaveBankReader.cpp b/Kits/DirectXTK12/Audio/WaveBankReader.cpp index 21e3fc02..b6467351 100644 --- a/Kits/DirectXTK12/Audio/WaveBankReader.cpp +++ b/Kits/DirectXTK12/Audio/WaveBankReader.cpp @@ -3,7 +3,7 @@ // // Functions for loading audio data from Wave Banks // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -17,6 +17,10 @@ #include "SoundCommon.h" #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wnonportable-system-include-path" +#endif + #include #include #endif @@ -151,7 +155,7 @@ namespace case TAG_WMA: { - static const uint32_t aWMABlockAlign[] = + static const uint32_t aWMABlockAlign[17] = { 929, 1487, @@ -173,7 +177,7 @@ namespace }; uint32_t dwBlockAlignIndex = wBlockAlign & 0x1F; - if (dwBlockAlignIndex < _countof(aWMABlockAlign)) + if (dwBlockAlignIndex < 17) return aWMABlockAlign[dwBlockAlignIndex]; } break; @@ -201,7 +205,7 @@ namespace case TAG_WMA: { - static const uint32_t aWMAAvgBytesPerSec[] = + static const uint32_t aWMAAvgBytesPerSec[7] = { 12000, 24000, @@ -214,7 +218,7 @@ namespace // bitrate = entry * 8 uint32_t dwBytesPerSecIndex = wBlockAlign >> 5; - if (dwBytesPerSecIndex < _countof(aWMAAvgBytesPerSec)) + if (dwBytesPerSecIndex < 7) return aWMAAvgBytesPerSec[dwBytesPerSecIndex]; } break; diff --git a/Kits/DirectXTK12/Audio/WaveBankReader.h b/Kits/DirectXTK12/Audio/WaveBankReader.h index d0adedc9..4c52d5eb 100644 --- a/Kits/DirectXTK12/Audio/WaveBankReader.h +++ b/Kits/DirectXTK12/Audio/WaveBankReader.h @@ -3,7 +3,7 @@ // // Functions for loading audio data from Wave Banks // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK12/Inc/Audio.h b/Kits/DirectXTK12/Inc/Audio.h index 875b701c..76e921ed 100644 --- a/Kits/DirectXTK12/Inc/Audio.h +++ b/Kits/DirectXTK12/Inc/Audio.h @@ -3,7 +3,7 @@ // // DirectXTK for Audio header // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -12,6 +12,13 @@ #pragma once +#include +#include +#include +#include +#include +#include + #include #include #include @@ -41,19 +48,17 @@ #include #ifndef USING_XAUDIO2_REDIST +#if defined(USING_XAUDIO2_8) && defined(NTDDI_WIN10) && !defined(_M_IX86) +// The xaudio2_8.lib in the Windows 10 SDK for x86 is incorrectly annotated as __cdecl instead of __stdcall, so avoid using it in this case. +#pragma comment(lib,"xaudio2_8.lib") +#else #pragma comment(lib,"xaudio2.lib") #endif +#endif #include -#include -#include -#include -#include -#include - - namespace DirectX { class SoundEffectInstance; @@ -594,6 +599,8 @@ namespace DirectX XMStoreFloat3(reinterpret_cast(&Position), newPos); } } + + void __cdecl EnableDefaultMultiChannel(unsigned int channels, float radius = 1.f); }; @@ -618,12 +625,14 @@ namespace DirectX void __cdecl SetPitch(float pitch); void __cdecl SetPan(float pan); - void __cdecl Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords = true); + void __cdecl Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords = true); bool __cdecl IsLooped() const noexcept; SoundState __cdecl GetState() noexcept; + unsigned int __cdecl GetChannelCount() const noexcept; + IVoiceNotify* __cdecl GetVoiceNotify() const noexcept; private: @@ -662,12 +671,14 @@ namespace DirectX void __cdecl SetPitch(float pitch); void __cdecl SetPan(float pan); - void __cdecl Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords = true); + void __cdecl Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords = true); bool __cdecl IsLooped() const noexcept; SoundState __cdecl GetState() noexcept; + unsigned int __cdecl GetChannelCount() const noexcept; + IVoiceNotify* __cdecl GetVoiceNotify() const noexcept; private: @@ -708,7 +719,7 @@ namespace DirectX void __cdecl SetPitch(float pitch); void __cdecl SetPan(float pan); - void __cdecl Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords = true); + void __cdecl Apply3D(const X3DAUDIO_LISTENER& listener, const X3DAUDIO_EMITTER& emitter, bool rhcoords = true); void __cdecl SubmitBuffer(_In_reads_bytes_(audioBytes) const uint8_t* pAudioData, size_t audioBytes); void __cdecl SubmitBuffer(_In_reads_bytes_(audioBytes) const uint8_t* pAudioData, uint32_t offset, size_t audioBytes); @@ -728,6 +739,8 @@ namespace DirectX const WAVEFORMATEX* __cdecl GetFormat() const noexcept; + unsigned int __cdecl GetChannelCount() const noexcept; + private: // Private implementation. class Impl; diff --git a/Kits/DirectXTK12/Inc/BufferHelpers.h b/Kits/DirectXTK12/Inc/BufferHelpers.h index dbe81b5a..171ad35f 100644 --- a/Kits/DirectXTK12/Inc/BufferHelpers.h +++ b/Kits/DirectXTK12/Inc/BufferHelpers.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: BufferHelpers.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -17,6 +17,8 @@ #include #endif +#include + namespace DirectX { diff --git a/Kits/DirectXTK12/Inc/CommonStates.h b/Kits/DirectXTK12/Inc/CommonStates.h index 6e4a0642..94ad7b1b 100644 --- a/Kits/DirectXTK12/Inc/CommonStates.h +++ b/Kits/DirectXTK12/Inc/CommonStates.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: CommonStates.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Inc/DDSTextureLoader.h b/Kits/DirectXTK12/Inc/DDSTextureLoader.h index 66a6444b..cb7f96f1 100644 --- a/Kits/DirectXTK12/Inc/DDSTextureLoader.h +++ b/Kits/DirectXTK12/Inc/DDSTextureLoader.h @@ -7,7 +7,7 @@ // 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. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -23,6 +23,7 @@ #include #endif +#include #include #include #include diff --git a/Kits/DirectXTK12/Inc/DescriptorHeap.h b/Kits/DirectXTK12/Inc/DescriptorHeap.h index d35978e1..822606b7 100644 --- a/Kits/DirectXTK12/Inc/DescriptorHeap.h +++ b/Kits/DirectXTK12/Inc/DescriptorHeap.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DescriptorHeap.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -17,11 +17,11 @@ #include #endif +#include +#include #include #include -#include - #include diff --git a/Kits/DirectXTK12/Inc/DirectXHelpers.h b/Kits/DirectXTK12/Inc/DirectXHelpers.h index 4e054106..f1104722 100644 --- a/Kits/DirectXTK12/Inc/DirectXHelpers.h +++ b/Kits/DirectXTK12/Inc/DirectXHelpers.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DirectXHelpers.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -17,16 +17,16 @@ #include #endif -#include - +#include +#include #include #include #include -#include - #include +#include + #ifndef _GAMING_XBOX #pragma comment(lib,"dxguid.lib") #endif @@ -74,7 +74,7 @@ // UpdateSubresources // D3D12IsLayoutOpaque // CommandListCast -// +// namespace DirectX @@ -173,7 +173,7 @@ namespace DirectX if (stateBefore == stateAfter) return; - + D3D12_RESOURCE_BARRIER desc = {}; desc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; desc.Transition.pResource = resource; diff --git a/Kits/DirectXTK12/Inc/EffectPipelineStateDescription.h b/Kits/DirectXTK12/Inc/EffectPipelineStateDescription.h index ed77eae2..0ff92734 100644 --- a/Kits/DirectXTK12/Inc/EffectPipelineStateDescription.h +++ b/Kits/DirectXTK12/Inc/EffectPipelineStateDescription.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: EffectPipelineStateDescription.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -19,6 +19,7 @@ #endif #include +#include #include "RenderTargetState.h" @@ -73,7 +74,7 @@ namespace DirectX psoDesc.IBStripCutValue = stripCutValue; psoDesc.PrimitiveTopologyType = primitiveTopology; psoDesc.NumRenderTargets = renderTargetState.numRenderTargets; - memcpy_s(psoDesc.RTVFormats, sizeof(psoDesc.RTVFormats), renderTargetState.rtvFormats, sizeof(DXGI_FORMAT) * D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT); + memcpy(psoDesc.RTVFormats, renderTargetState.rtvFormats, sizeof(DXGI_FORMAT) * D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT); psoDesc.DSVFormat = renderTargetState.dsvFormat; psoDesc.SampleDesc = renderTargetState.sampleDesc; psoDesc.NodeMask = renderTargetState.nodeMask; diff --git a/Kits/DirectXTK12/Inc/Effects.h b/Kits/DirectXTK12/Inc/Effects.h index 7a5d0c3c..05c7c973 100644 --- a/Kits/DirectXTK12/Inc/Effects.h +++ b/Kits/DirectXTK12/Inc/Effects.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Effects.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -17,10 +17,12 @@ #include #endif -#include +#include #include #include +#include + #include "RenderTargetState.h" #include "EffectPipelineStateDescription.h" @@ -247,7 +249,7 @@ namespace DirectX void XM_CALLCONV SetDiffuseColor(FXMVECTOR value); void __cdecl SetAlpha(float value); void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value); - + // Fog settings. void __cdecl SetFogStart(float value) override; void __cdecl SetFogEnd(float value) override; @@ -293,7 +295,7 @@ namespace DirectX void XM_CALLCONV SetDiffuseColor(FXMVECTOR value); void __cdecl SetAlpha(float value); void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value); - + // Fog settings. void __cdecl SetFogStart(float value) override; void __cdecl SetFogEnd(float value) override; @@ -302,7 +304,7 @@ namespace DirectX // Texture settings. void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); void __cdecl SetTexture2(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); - + private: // Private implementation. class Impl; @@ -346,7 +348,7 @@ namespace DirectX void XM_CALLCONV SetEmissiveColor(FXMVECTOR value); void __cdecl SetAlpha(float value); void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value); - + // Light settings. void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) override; @@ -369,7 +371,7 @@ namespace DirectX void __cdecl SetEnvironmentMapAmount(float value); void XM_CALLCONV SetEnvironmentMapSpecular(FXMVECTOR value); void __cdecl SetFresnelFactor(float value); - + private: // Private implementation. class Impl; @@ -411,7 +413,7 @@ namespace DirectX void __cdecl DisableSpecular(); void __cdecl SetAlpha(float value); void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value); - + // Light settings. void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) override; @@ -429,7 +431,7 @@ namespace DirectX // Texture setting. void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor); - + // Animation settings. void __cdecl SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) override; void __cdecl ResetBoneTransforms() override; @@ -748,10 +750,10 @@ namespace DirectX }; virtual std::shared_ptr __cdecl CreateEffect( - const EffectInfo& info, + const EffectInfo& info, const EffectPipelineStateDescription& opaquePipelineState, const EffectPipelineStateDescription& alphaPipelineState, - const D3D12_INPUT_LAYOUT_DESC& inputLayout, + const D3D12_INPUT_LAYOUT_DESC& inputLayout, int textureDescriptorOffset = 0, int samplerDescriptorOffset = 0) = 0; diff --git a/Kits/DirectXTK12/Inc/GamePad.h b/Kits/DirectXTK12/Inc/GamePad.h index c9e81ad8..c190408e 100644 --- a/Kits/DirectXTK12/Inc/GamePad.h +++ b/Kits/DirectXTK12/Inc/GamePad.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: GamePad.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -284,7 +284,8 @@ namespace DirectX #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_GAMES) // Underlying device access - void __cdecl GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept; + _Success_(return != false) + bool __cdecl GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept; #endif // Singleton diff --git a/Kits/DirectXTK12/Inc/GeometricPrimitive.h b/Kits/DirectXTK12/Inc/GeometricPrimitive.h index 03740f8a..5420b274 100644 --- a/Kits/DirectXTK12/Inc/GeometricPrimitive.h +++ b/Kits/DirectXTK12/Inc/GeometricPrimitive.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: GeometricPrimitive.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -11,6 +11,7 @@ #include "VertexTypes.h" +#include #include #include diff --git a/Kits/DirectXTK12/Inc/GraphicsMemory.h b/Kits/DirectXTK12/Inc/GraphicsMemory.h index 40f8cd9a..6bc968c7 100644 --- a/Kits/DirectXTK12/Inc/GraphicsMemory.h +++ b/Kits/DirectXTK12/Inc/GraphicsMemory.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: GraphicsMemory.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -17,6 +17,8 @@ #include #endif +#include +#include #include @@ -34,7 +36,7 @@ namespace DirectX _In_ LinearAllocatorPage* page, _In_ D3D12_GPU_VIRTUAL_ADDRESS gpuAddress, _In_ ID3D12Resource* resource, - _In_ void* memory, + _In_ void* memory, _In_ size_t offset, _In_ size_t size) noexcept; @@ -51,7 +53,7 @@ namespace DirectX void* Memory() const noexcept { return mMemory; } size_t ResourceOffset() const noexcept { return mBufferOffset; } size_t Size() const noexcept { return mSize; } - + explicit operator bool () const noexcept { return mResource != nullptr; } // Clear the pointer. Using operator -> will produce bad results. @@ -91,7 +93,7 @@ namespace DirectX void* Memory() const noexcept { return mSharedResource->Memory(); } size_t ResourceOffset() const noexcept { return mSharedResource->ResourceOffset(); } size_t Size() const noexcept { return mSharedResource->Size(); } - + explicit operator bool () const noexcept { return mSharedResource != nullptr; } bool operator == (const SharedGraphicsResource& other) const noexcept { return mSharedResource.get() == other.mSharedResource.get(); } @@ -102,7 +104,7 @@ namespace DirectX void __cdecl Reset(GraphicsResource&&); void __cdecl Reset(SharedGraphicsResource&&) noexcept; void __cdecl Reset(const SharedGraphicsResource& resource) noexcept; - + private: std::shared_ptr mSharedResource; }; @@ -151,11 +153,11 @@ namespace DirectX return alloc; } - // Submits all the pending one-shot memory to the GPU. + // Submits all the pending one-shot memory to the GPU. // The memory will be recycled once the GPU is done with it. void __cdecl Commit(_In_ ID3D12CommandQueue* commandQueue); - // This frees up any unused memory. + // This frees up any unused memory. // If you want to make sure all memory is reclaimed, idle the GPU before calling this. // It is not recommended that you call this unless absolutely necessary (e.g. your // memory budget changes at run-time, or perhaps you're changing levels in your game.) @@ -176,4 +178,3 @@ namespace DirectX std::unique_ptr pImpl; }; } - diff --git a/Kits/DirectXTK12/Inc/Keyboard.h b/Kits/DirectXTK12/Inc/Keyboard.h index 044360c9..7ef7e3ef 100644 --- a/Kits/DirectXTK12/Inc/Keyboard.h +++ b/Kits/DirectXTK12/Inc/Keyboard.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Keyboard.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK12/Inc/Model.h b/Kits/DirectXTK12/Inc/Model.h index 26380b15..7985b9ed 100644 --- a/Kits/DirectXTK12/Inc/Model.h +++ b/Kits/DirectXTK12/Inc/Model.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Model.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -18,9 +18,8 @@ #include #endif -#include -#include - +#include +#include #include #include #include @@ -30,10 +29,11 @@ #include #include -#include - #include +#include +#include + #include "GraphicsMemory.h" #include "Effects.h" @@ -106,7 +106,7 @@ namespace DirectX // Draw the mesh with a callback for each mesh part static void __cdecl DrawMeshParts(_In_ ID3D12GraphicsCommandList* commandList, _In_ const ModelMeshPart::Collection& meshParts, DrawCallback callback); - // Draw the mesh with a range of effects that mesh parts will index into. + // Draw the mesh with a range of effects that mesh parts will index into. // Effects can be any IEffect pointer type (including smart pointer). Value or reference types will not compile. // The iterator passed to this method should have random access capabilities for best performance. template @@ -172,7 +172,7 @@ namespace DirectX void __cdecl DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, ModelMeshPart::DrawCallback callback) const; void __cdecl DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, ModelMeshPart::DrawCallback callback) const; - // Draw the mesh with a range of effects that mesh parts will index into. + // Draw the mesh with a range of effects that mesh parts will index into. // TEffectPtr can be any IEffect pointer type (including smart pointer). Value or reference types will not compile. template void DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, TEffectIterator effects) const @@ -208,10 +208,10 @@ namespace DirectX // // NOTE - // + // // The Model::Draw functions use variadic templates and perfect-forwarding in order to support future overloads to the ModelMesh::Draw // family of functions. This means that a new ModelMesh::Draw overload can be added, removed or altered, but the Model::Draw* routines - // will still remain compatible. The correct ModelMesh::Draw overload will be selected by the compiler depending on the arguments you + // will still remain compatible. The correct ModelMesh::Draw overload will be selected by the compiler depending on the arguments you // provide to Model::Draw*. // @@ -301,7 +301,7 @@ namespace DirectX _In_z_ const wchar_t* szFileName, ModelLoaderFlags flags = ModelLoader_Default); - // Utility function for getting a GPU descriptor for a mesh part/material index. If there is no texture the + // Utility function for getting a GPU descriptor for a mesh part/material index. If there is no texture the // descriptor will be zero. D3D12_GPU_DESCRIPTOR_HANDLE __cdecl GetGpuTextureHandleForMaterialIndex(uint32_t materialIndex, _In_ ID3D12DescriptorHeap* heap, _In_ size_t descriptorSize, _In_ size_t descriptorOffset) const { diff --git a/Kits/DirectXTK12/Inc/Mouse.h b/Kits/DirectXTK12/Inc/Mouse.h index 51aa3603..dff77353 100644 --- a/Kits/DirectXTK12/Inc/Mouse.h +++ b/Kits/DirectXTK12/Inc/Mouse.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Mouse.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK12/Inc/PostProcess.h b/Kits/DirectXTK12/Inc/PostProcess.h index 32aff94b..30061b89 100644 --- a/Kits/DirectXTK12/Inc/PostProcess.h +++ b/Kits/DirectXTK12/Inc/PostProcess.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: PostProcess.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -17,9 +17,10 @@ #include #endif -#include #include +#include + #include "RenderTargetState.h" diff --git a/Kits/DirectXTK12/Inc/PrimitiveBatch.h b/Kits/DirectXTK12/Inc/PrimitiveBatch.h index e9b6a173..41f55a5c 100644 --- a/Kits/DirectXTK12/Inc/PrimitiveBatch.h +++ b/Kits/DirectXTK12/Inc/PrimitiveBatch.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: PrimitiveBatch.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -17,7 +17,9 @@ #include #endif +#include #include +#include #include #include diff --git a/Kits/DirectXTK12/Inc/RenderTargetState.h b/Kits/DirectXTK12/Inc/RenderTargetState.h index 7ba7bff6..a1b7b2e3 100644 --- a/Kits/DirectXTK12/Inc/RenderTargetState.h +++ b/Kits/DirectXTK12/Inc/RenderTargetState.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: RenderTargetState.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -15,7 +15,7 @@ #include #else #include -#include +#include #endif #include @@ -58,7 +58,8 @@ namespace DirectX rtvFormats[0] = rtFormat; } - // Convenience constructor converting from DXGI_SWAPCHAIN_DESC + // Convenience constructors converting from DXGI_SWAPCHAIN_DESC +#if defined(__dxgi_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) RenderTargetState( _In_ const DXGI_SWAP_CHAIN_DESC* desc, _In_ DXGI_FORMAT dsFormat) noexcept @@ -72,6 +73,23 @@ namespace DirectX rtvFormats[0] = desc->BufferDesc.Format; sampleDesc = desc->SampleDesc; } +#endif + +#if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) + RenderTargetState( + _In_ const DXGI_SWAP_CHAIN_DESC1* desc, + _In_ DXGI_FORMAT dsFormat) noexcept + : sampleMask(UINT_MAX) + , numRenderTargets(1) + , rtvFormats{} + , dsvFormat(dsFormat) + , sampleDesc{} + , nodeMask(0) + { + rtvFormats[0] = desc->Format; + sampleDesc = desc->SampleDesc; + } +#endif uint32_t sampleMask; uint32_t numRenderTargets; diff --git a/Kits/DirectXTK12/Inc/ResourceUploadBatch.h b/Kits/DirectXTK12/Inc/ResourceUploadBatch.h index aec6f2d5..d9427aa9 100644 --- a/Kits/DirectXTK12/Inc/ResourceUploadBatch.h +++ b/Kits/DirectXTK12/Inc/ResourceUploadBatch.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: ResourceUploadBatch.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Inc/ScreenGrab.h b/Kits/DirectXTK12/Inc/ScreenGrab.h index 6b3a4a3c..b696d215 100644 --- a/Kits/DirectXTK12/Inc/ScreenGrab.h +++ b/Kits/DirectXTK12/Inc/ScreenGrab.h @@ -8,7 +8,7 @@ // 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. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -24,9 +24,14 @@ #include #endif -#include #include +#ifdef NTDDI_WIN10_FE +#include +#else +#include +#endif + #pragma comment(lib,"uuid.lib") diff --git a/Kits/DirectXTK12/Inc/SimpleMath.h b/Kits/DirectXTK12/Inc/SimpleMath.h index 70c2eceb..9f4e17f2 100644 --- a/Kits/DirectXTK12/Inc/SimpleMath.h +++ b/Kits/DirectXTK12/Inc/SimpleMath.h @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------------- // SimpleMath.h -- Simplified C++ Math wrapper for DirectXMath // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -10,15 +10,15 @@ #pragma once -#if !(defined(_XBOX_ONE) && defined(_TITLE)) && !defined(_GAMING_XBOX) +#if (defined(WIN32) || defined(WINAPI_FAMILY)) && !(defined(_XBOX_ONE) && defined(_TITLE)) && !defined(_GAMING_XBOX) #include #endif +#include +#include +#include #include -#include -#include - #include #include #include @@ -403,7 +403,7 @@ namespace DirectX static void Barycentric(const Vector4& v1, const Vector4& v2, const Vector4& v3, float f, float g, Vector4& result) noexcept; static Vector4 Barycentric(const Vector4& v1, const Vector4& v2, const Vector4& v3, float f, float g) noexcept; - + static void CatmullRom(const Vector4& v1, const Vector4& v2, const Vector4& v3, const Vector4& v4, float t, Vector4& result) noexcept; static Vector4 CatmullRom(const Vector4& v1, const Vector4& v2, const Vector4& v3, const Vector4& v4, float t) noexcept; @@ -474,7 +474,7 @@ namespace DirectX r1.x, r1.y, r1.z, r1.w, r2.x, r2.y, r2.z, r2.w, r3.x, r3.y, r3.z, r3.w) {} - Matrix(const XMFLOAT4X4& M) noexcept { memcpy_s(this, sizeof(float) * 16, &M, sizeof(XMFLOAT4X4)); } + Matrix(const XMFLOAT4X4& M) noexcept { memcpy(this, &M, sizeof(XMFLOAT4X4)); } Matrix(const XMFLOAT3X3& M) noexcept; Matrix(const XMFLOAT4X3& M) noexcept; @@ -927,7 +927,9 @@ namespace DirectX void Unproject(const Vector3& p, const Matrix& proj, const Matrix& view, const Matrix& world, Vector3& result) const noexcept; // Static methods +#if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) static RECT __cdecl ComputeDisplayArea(DXGI_SCALING scaling, UINT backBufferWidth, UINT backBufferHeight, int outputWidth, int outputHeight) noexcept; +#endif static RECT __cdecl ComputeTitleSafeArea(UINT backBufferWidth, UINT backBufferHeight) noexcept; }; diff --git a/Kits/DirectXTK12/Inc/SimpleMath.inl b/Kits/DirectXTK12/Inc/SimpleMath.inl index 576d4258..442c8ffd 100644 --- a/Kits/DirectXTK12/Inc/SimpleMath.inl +++ b/Kits/DirectXTK12/Inc/SimpleMath.inl @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------------- // SimpleMath.inl -- Simplified C++ Math wrapper for DirectXMath // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK12/Inc/SpriteBatch.h b/Kits/DirectXTK12/Inc/SpriteBatch.h index 5d40cf8d..2fa3134b 100644 --- a/Kits/DirectXTK12/Inc/SpriteBatch.h +++ b/Kits/DirectXTK12/Inc/SpriteBatch.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SpriteBatch.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -15,14 +15,16 @@ #include #else #include -#include +#include #endif -#include -#include +#include #include #include +#include +#include + #include "RenderTargetState.h" @@ -124,15 +126,17 @@ namespace DirectX void XM_CALLCONV Draw(D3D12_GPU_DESCRIPTOR_HANDLE textureSRV, XMUINT2 const& textureSize, RECT const& destinationRectangle, _In_opt_ RECT const* sourceRectangle, FXMVECTOR color = Colors::White, float rotation = 0, XMFLOAT2 const& origin = Float2Zero, SpriteEffects effects = SpriteEffects_None, float layerDepth = 0); // Rotation mode to be applied to the sprite transformation +#if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) void __cdecl SetRotation(DXGI_MODE_ROTATION mode); DXGI_MODE_ROTATION __cdecl GetRotation() const noexcept; +#endif // Set viewport for sprite transformation void __cdecl SetViewport(const D3D12_VIEWPORT& viewPort); private: // Private implementation. - class Impl; + struct Impl; std::unique_ptr pImpl; diff --git a/Kits/DirectXTK12/Inc/SpriteFont.h b/Kits/DirectXTK12/Inc/SpriteFont.h index 52ca7da1..d2613f21 100644 --- a/Kits/DirectXTK12/Inc/SpriteFont.h +++ b/Kits/DirectXTK12/Inc/SpriteFont.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SpriteFont.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -11,6 +11,8 @@ #include "SpriteBatch.h" +#include + namespace DirectX { diff --git a/Kits/DirectXTK12/Inc/VertexTypes.h b/Kits/DirectXTK12/Inc/VertexTypes.h index fea10335..cadd9df2 100644 --- a/Kits/DirectXTK12/Inc/VertexTypes.h +++ b/Kits/DirectXTK12/Inc/VertexTypes.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: VertexTypes.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Inc/WICTextureLoader.h b/Kits/DirectXTK12/Inc/WICTextureLoader.h index 8e372c37..7e45dc77 100644 --- a/Kits/DirectXTK12/Inc/WICTextureLoader.h +++ b/Kits/DirectXTK12/Inc/WICTextureLoader.h @@ -11,7 +11,7 @@ // 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. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -27,6 +27,7 @@ #include #endif +#include #include #include diff --git a/Kits/DirectXTK12/Inc/XboxDDSTextureLoader.h b/Kits/DirectXTK12/Inc/XboxDDSTextureLoader.h index eb164fe2..44282a52 100644 --- a/Kits/DirectXTK12/Inc/XboxDDSTextureLoader.h +++ b/Kits/DirectXTK12/Inc/XboxDDSTextureLoader.h @@ -8,7 +8,7 @@ // module in the DirectXTex package or as part of the DirectXTK library to load // these files which use standard Direct3D resource creation APIs. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -30,6 +30,7 @@ #pragma comment(lib,"xmem.lib") #endif +#include #include #ifndef DDS_ALPHA_MODE_DEFINED @@ -52,7 +53,7 @@ namespace Xbox using DirectX::DDS_ALPHA_MODE; // - // NOTE: Flush the GPU caches before using textures created + // NOTE: Flush the GPU caches before using textures created // with these functions. // // The simplest means of doing this is: @@ -61,7 +62,7 @@ namespace Xbox // CreateDDSTextureFrom... // CreateDDSTextureFrom... // CreateDDSTextureFrom... - // + // // // Flush the GPU caches // ID3D12CommandList::FlushPipelineX(D3D12XBOX_FLUSH_IDLE, 0, 0); // @@ -79,11 +80,11 @@ namespace Xbox _In_ size_t ddsDataSize, _Outptr_opt_ ID3D12Resource** texture, _Outptr_ void** grfxMemory, - _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, + _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr, _In_ bool forceSRGB = false, _Out_opt_ bool* isCubeMap = nullptr) noexcept; - HRESULT __cdecl CreateDDSTextureFromFile( + HRESULT __cdecl CreateDDSTextureFromFile( _In_ ID3D12Device* d3dDevice, _In_z_ const wchar_t* szFileName, _Outptr_opt_ ID3D12Resource** texture, diff --git a/Kits/DirectXTK12/README.md b/Kits/DirectXTK12/README.md index 6a7a2363..d5d3f4de 100644 --- a/Kits/DirectXTK12/README.md +++ b/Kits/DirectXTK12/README.md @@ -4,13 +4,13 @@ http://go.microsoft.com/fwlink/?LinkID=615561 -Copyright (c) Microsoft Corporation. All rights reserved. +Copyright (c) Microsoft Corporation. -**September 30, 2020** +**June 9, 2021** This package contains the "DirectX Tool Kit", a collection of helper classes for writing Direct3D 12 C++ code for Universal Windows Platform (UWP) apps, Win32 desktop applications for Windows 10, and Xbox. -This code is designed to build with Visual Studio 2017 ([15.9](https://walbourn.github.io/vs-2017-15-9-update/)), Visual Studio 2019, or clang for Windows v9 or later. It is recommended that you make use of the Windows 10 May 2020 Update SDK ([19041](https://walbourn.github.io/windows-10-may-2020-update-sdk/)). +This code is designed to build with Visual Studio 2017 ([15.9](https://walbourn.github.io/vs-2017-15-9-update/)), Visual Studio 2019, or clang for Windows v9 or later. It is recommended that you make use of the Windows 10 May 2020 Update SDK ([19041](https://walbourn.github.io/windows-10-may-2020-update-sdk/)) or later. These components are designed to work without requiring any content from the legacy DirectX SDK. For details, see [Where is the DirectX SDK?](https://aka.ms/dxsdk). @@ -66,8 +66,6 @@ All content and source code for this package are subject to the terms of the [MI For the latest version of DirectXTK12, bug reports, etc. please visit the project site on [GitHub](https://github.com/microsoft/DirectXTK12). -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. - ## Comparisons to DirectX 11 Version * No support for loading ``.CMO`` models or DGSL effect shaders (i.e. *DGSLEffect*) @@ -91,3 +89,15 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope * The UWP projects and the VS 2019 Win10 classic desktop project include configurations for the ARM64 platform. These require VS 2017 (15.9 update) or VS 2019 to build, with the ARM64 toolset installed. * The ``CompileShaders.cmd`` script must have Windows-style (CRLF) line-endings. If it is changed to Linux-style (LF) line-endings, it can fail to build all the required shaders. + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. + +When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +## Trademarks + +This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies. diff --git a/Kits/DirectXTK12/Src/AlignedNew.h b/Kits/DirectXTK12/Src/AlignedNew.h index 5a0e9c5c..756c5586 100644 --- a/Kits/DirectXTK12/Src/AlignedNew.h +++ b/Kits/DirectXTK12/Src/AlignedNew.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: AlignedNew.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -10,9 +10,14 @@ #pragma once -#include +#include +#include #include +#ifdef WIN32 +#include +#endif + namespace DirectX { @@ -21,7 +26,7 @@ namespace DirectX // // Example usage: // - // __declspec(align(16)) struct MyAlignedType : public AlignedNew + // XM_ALIGNED_STRUCT(16) MyAlignedType : public AlignedNew template struct AlignedNew @@ -29,12 +34,18 @@ namespace DirectX // Allocate aligned memory. static void* operator new (size_t size) { - const size_t alignment = __alignof(TDerived); + const size_t alignment = alignof(TDerived); static_assert(alignment > 8, "AlignedNew is only useful for types with > 8 byte alignment. Did you forget a __declspec(align) on TDerived?"); + static_assert(((alignment - 1) & alignment) == 0, "AlignedNew only works with power of two alignment"); +#ifdef WIN32 void* ptr = _aligned_malloc(size, alignment); - +#else + // This C++17 Standard Library function is currently NOT + // implemented for the Microsoft Standard C++ Library. + void* ptr = aligned_alloc(alignment, size); +#endif if (!ptr) throw std::bad_alloc(); @@ -45,13 +56,19 @@ namespace DirectX // Free aligned memory. static void operator delete (void* ptr) { +#ifdef WIN32 _aligned_free(ptr); +#else + free(ptr); +#endif } // Array overloads. static void* operator new[](size_t size) { + static_assert((sizeof(TDerived) % alignof(TDerived) == 0), "AlignedNew expects type to be padded to the alignment"); + return operator new(size); } diff --git a/Kits/DirectXTK12/Src/AlphaTestEffect.cpp b/Kits/DirectXTK12/Src/AlphaTestEffect.cpp index 55eca642..80adb9f6 100644 --- a/Kits/DirectXTK12/Src/AlphaTestEffect.cpp +++ b/Kits/DirectXTK12/Src/AlphaTestEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: AlphaTestEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -181,10 +181,10 @@ AlphaTestEffect::Impl::Impl( texture{}, textureSampler{} { - static_assert(_countof(EffectBase::VertexShaderIndices) == AlphaTestEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == AlphaTestEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == AlphaTestEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == AlphaTestEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == AlphaTestEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == AlphaTestEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == AlphaTestEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == AlphaTestEffectTraits::ShaderPermutationCount, "array/max mismatch"); // Create root signature. { @@ -203,7 +203,7 @@ AlphaTestEffect::Impl::Impl( rootParameters[RootParameterIndex::ConstantBuffer].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_ALL); CD3DX12_ROOT_SIGNATURE_DESC rsigDesc = {}; - rsigDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 0, nullptr, rootSignatureFlags); mRootSignature = GetRootSignature(0, rsigDesc); } @@ -215,12 +215,12 @@ AlphaTestEffect::Impl::Impl( if (effectFlags & EffectFlags::PerPixelLightingBit) { DebugTrace("ERROR: AlphaTestEffect does not implement EffectFlags::PerPixelLighting\n"); - throw std::invalid_argument("AlphaTestEffect"); + throw std::invalid_argument("PerPixelLighting effect flag is invalid"); } else if (effectFlags & EffectFlags::Lighting) { DebugTrace("ERROR: DualTextureEffect does not implement EffectFlags::Lighting\n"); - throw std::invalid_argument("AlphaTestEffect"); + throw std::invalid_argument("Lighting effect flag is invalid"); } // Create pipeline state. @@ -353,7 +353,7 @@ void AlphaTestEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) break; default: - throw std::exception("Unknown alpha test function"); + throw std::runtime_error("Unknown alpha test function"); } // x = compareTo, y = threshold, zw = resultSelector. @@ -370,7 +370,7 @@ void AlphaTestEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) if (!texture.ptr || !textureSampler.ptr) { DebugTrace("ERROR: Missing texture or sampler for AlphaTestEffect (texture %llu, sampler %llu)\n", texture.ptr, textureSampler.ptr); - throw std::exception("AlphaTestEffect"); + throw std::runtime_error("AlphaTestEffect"); } // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. diff --git a/Kits/DirectXTK12/Src/BasicEffect.cpp b/Kits/DirectXTK12/Src/BasicEffect.cpp index 2b4c044f..9b2ce3f4 100644 --- a/Kits/DirectXTK12/Src/BasicEffect.cpp +++ b/Kits/DirectXTK12/Src/BasicEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: BasicEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -418,10 +418,10 @@ BasicEffect::Impl::Impl( texture{}, sampler{} { - static_assert(_countof(EffectBase::VertexShaderIndices) == BasicEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == BasicEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == BasicEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == BasicEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == BasicEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == BasicEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == BasicEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == BasicEffectTraits::ShaderPermutationCount, "array/max mismatch"); lights.InitializeConstants(constants.specularColorAndPower, constants.lightDirection, constants.lightDiffuseColor, constants.lightSpecularColor); @@ -454,7 +454,7 @@ BasicEffect::Impl::Impl( rootParameters[RootParameterIndex::TextureSampler].InitAsDescriptorTable(1, &textureSampler, D3D12_SHADER_VISIBILITY_PIXEL); // use all parameters - rsigDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 0, nullptr, rootSignatureFlags); mRootSignature = GetRootSignature(1, rsigDesc); } @@ -559,7 +559,7 @@ void BasicEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) if (!texture.ptr || !sampler.ptr) { DebugTrace("ERROR: Missing texture or sampler for BasicEffect (texture %llu, sampler %llu)\n", texture.ptr, sampler.ptr); - throw std::exception("BasicEffect"); + throw std::runtime_error("BasicEffect"); } // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. diff --git a/Kits/DirectXTK12/Src/BasicPostProcess.cpp b/Kits/DirectXTK12/Src/BasicPostProcess.cpp index 5c26e7f9..009a3a26 100644 --- a/Kits/DirectXTK12/Src/BasicPostProcess.cpp +++ b/Kits/DirectXTK12/Src/BasicPostProcess.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: BasicPostProcess.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -32,7 +32,7 @@ namespace constexpr int RootSignatureCount = 2; // Constant buffer layout. Must match the shader! - __declspec(align(16)) struct PostProcessConstants + XM_ALIGNED_STRUCT(16) PostProcessConstants { XMVECTOR sampleOffsets[c_MaxSamples]; XMVECTOR sampleWeights[c_MaxSamples]; @@ -121,7 +121,7 @@ namespace { PostProcess_PSBloomBlur, sizeof(PostProcess_PSBloomBlur) }, }; - static_assert(_countof(pixelShaders) == BasicPostProcess::Effect_Max, "array/max mismatch"); + static_assert(static_cast(std::size(pixelShaders)) == BasicPostProcess::Effect_Max, "array/max mismatch"); // Factory for lazily instantiating shared root signatures. class DeviceResources @@ -231,7 +231,7 @@ BasicPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetState& mDeviceResources(deviceResourcesPool.DemandCreate(device)) { if (ifx >= Effect_Max) - throw std::out_of_range("Effect not defined"); + throw std::invalid_argument("Effect not defined"); switch (ifx) { @@ -284,7 +284,7 @@ BasicPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetState& rootParameters[RootParameterIndex::ConstantBuffer].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_PIXEL); // use all parameters - rsigDesc.Init(_countof(rootParameters), rootParameters, 1, &sampler, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 1, &sampler, rootSignatureFlags); mRootSignature = mDeviceResources->GetRootSignature(1, rsigDesc); } @@ -328,7 +328,7 @@ void BasicPostProcess::Impl::Process(_In_ ID3D12GraphicsCommandList* commandList if (!texture.ptr) { DebugTrace("ERROR: Missing texture for BasicPostProcess (texture %llu)\n", texture.ptr); - throw std::exception("BasicPostProcess"); + throw std::runtime_error("BasicPostProcess"); } commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSRV, texture); @@ -391,7 +391,7 @@ void BasicPostProcess::Impl::DownScale2x2() if (!texWidth || !texHeight) { - throw std::exception("Call SetSourceTexture before setting post-process effect"); + throw std::logic_error("Call SetSourceTexture before setting post-process effect"); } float tu = 1.0f / float(texWidth); @@ -418,7 +418,7 @@ void BasicPostProcess::Impl::DownScale4x4() if (!texWidth || !texHeight) { - throw std::exception("Call SetSourceTexture before setting post-process effect"); + throw std::logic_error("Call SetSourceTexture before setting post-process effect"); } float tu = 1.0f / float(texWidth); @@ -446,7 +446,7 @@ void BasicPostProcess::Impl::GaussianBlur5x5(float multiplier) if (!texWidth || !texHeight) { - throw std::exception("Call SetSourceTexture before setting post-process effect"); + throw std::logic_error("Call SetSourceTexture before setting post-process effect"); } float tu = 1.0f / float(texWidth); @@ -502,7 +502,7 @@ void BasicPostProcess::Impl::Bloom(bool horizontal, float size, float brightnes if (!texWidth || !texHeight) { - throw std::exception("Call SetSourceTexture before setting post-process effect"); + throw std::logic_error("Call SetSourceTexture before setting post-process effect"); } float tu = 0.f; diff --git a/Kits/DirectXTK12/Src/Bezier.h b/Kits/DirectXTK12/Src/Bezier.h index 367de975..d1d66ed2 100644 --- a/Kits/DirectXTK12/Src/Bezier.h +++ b/Kits/DirectXTK12/Src/Bezier.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Bezier.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -51,9 +51,6 @@ namespace Bezier template inline T CubicTangent(T const& p1, T const& p2, T const& p3, T const& p4, float t) noexcept { - using DirectX::operator*; - using DirectX::operator+; - return p1 * (-1 + 2 * t - t * t) + p2 * (1 - 4 * t + 3 * t * t) + p3 * (2 * t - 3 * t * t) + diff --git a/Kits/DirectXTK12/Src/BinaryReader.cpp b/Kits/DirectXTK12/Src/BinaryReader.cpp index 6c7c5a79..d8947c82 100644 --- a/Kits/DirectXTK12/Src/BinaryReader.cpp +++ b/Kits/DirectXTK12/Src/BinaryReader.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: BinaryReader.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -27,7 +27,7 @@ BinaryReader::BinaryReader(_In_z_ wchar_t const* fileName) noexcept(false) : { DebugTrace("ERROR: BinaryReader failed (%08X) to load '%ls'\n", static_cast(hr), fileName); - throw std::exception("BinaryReader"); + throw std::runtime_error("BinaryReader"); } mPos = mOwnedData.get(); @@ -44,8 +44,16 @@ BinaryReader::BinaryReader(_In_reads_bytes_(dataSize) uint8_t const* dataBlob, s // Reads from the filesystem into memory. -HRESULT BinaryReader::ReadEntireFile(_In_z_ wchar_t const* fileName, _Inout_ std::unique_ptr& data, _Out_ size_t* dataSize) +HRESULT BinaryReader::ReadEntireFile( + _In_z_ wchar_t const* fileName, + _Inout_ std::unique_ptr& data, + _Out_ size_t* dataSize) { + if (!fileName || !dataSize) + return E_INVALIDARG; + + *dataSize = 0; + // Open the file. #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) ScopedHandle hFile(safe_handle(CreateFile2(fileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr))); diff --git a/Kits/DirectXTK12/Src/BinaryReader.h b/Kits/DirectXTK12/Src/BinaryReader.h index 97ee5ab2..562b227e 100644 --- a/Kits/DirectXTK12/Src/BinaryReader.h +++ b/Kits/DirectXTK12/Src/BinaryReader.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: BinaryReader.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -48,7 +48,7 @@ namespace DirectX throw std::overflow_error("ReadArray"); if (newPos > mEnd) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto result = reinterpret_cast(mPos); diff --git a/Kits/DirectXTK12/Src/BufferHelpers.cpp b/Kits/DirectXTK12/Src/BufferHelpers.cpp index 07adf38f..242e4b1d 100644 --- a/Kits/DirectXTK12/Src/BufferHelpers.cpp +++ b/Kits/DirectXTK12/Src/BufferHelpers.cpp @@ -1,7 +1,7 @@ //------------------------------------- ------------------------------------------------- // File: BufferHelpers.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/CommonStates.cpp b/Kits/DirectXTK12/Src/CommonStates.cpp index eac60825..33b30123 100644 --- a/Kits/DirectXTK12/Src/CommonStates.cpp +++ b/Kits/DirectXTK12/Src/CommonStates.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: CommonStates.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/DDSTextureLoader.cpp b/Kits/DirectXTK12/Src/DDSTextureLoader.cpp index 71f2ef0b..5255660c 100644 --- a/Kits/DirectXTK12/Src/DDSTextureLoader.cpp +++ b/Kits/DirectXTK12/Src/DDSTextureLoader.cpp @@ -7,7 +7,7 @@ // 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. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/DebugEffect.cpp b/Kits/DirectXTK12/Src/DebugEffect.cpp index 5621de15..dce8edf7 100644 --- a/Kits/DirectXTK12/Src/DebugEffect.cpp +++ b/Kits/DirectXTK12/Src/DebugEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DebugEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -194,10 +194,10 @@ DebugEffect::Impl::Impl( DebugEffect::Mode debugMode) : EffectBase(device) { - static_assert(_countof(EffectBase::VertexShaderIndices) == DebugEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == DebugEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == DebugEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == DebugEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == DebugEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == DebugEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == DebugEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == DebugEffectTraits::ShaderPermutationCount, "array/max mismatch"); static const XMVECTORF32 s_lower = { { { 0.f, 0.f, 0.f, 1.f } } }; diff --git a/Kits/DirectXTK12/Src/DemandCreate.h b/Kits/DirectXTK12/Src/DemandCreate.h index 9403f5ae..2aba02f7 100644 --- a/Kits/DirectXTK12/Src/DemandCreate.h +++ b/Kits/DirectXTK12/Src/DemandCreate.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DemandCreate.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -22,14 +22,20 @@ namespace DirectX T* result = comPtr.Get(); // Double-checked lock pattern. +#ifdef _MSC_VER MemoryBarrier(); +#elif defined(__GNUC__) + __sync_synchronize(); +#else +#error Unknown memory barrier syntax +#endif if (!result) { std::lock_guard lock(mutex); result = comPtr.Get(); - + if (!result) { // Create the new object. @@ -37,7 +43,11 @@ namespace DirectX createFunc(&result) ); +#ifdef _MSC_VER MemoryBarrier(); +#elif defined(__GNUC__) + __sync_synchronize(); +#endif comPtr.Attach(result); } diff --git a/Kits/DirectXTK12/Src/DescriptorHeap.cpp b/Kits/DirectXTK12/Src/DescriptorHeap.cpp index fb0c5861..23c3d111 100644 --- a/Kits/DirectXTK12/Src/DescriptorHeap.cpp +++ b/Kits/DirectXTK12/Src/DescriptorHeap.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DescriptorHeap.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -25,10 +25,10 @@ namespace static const DescriptorHeapDesc c_DescriptorHeapDescs[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES] = { - { D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE }, - { D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE }, - { D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE }, - { D3D12_DESCRIPTOR_HEAP_TYPE_DSV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE } + { D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE }, + { D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE }, + { D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE }, + { D3D12_DESCRIPTOR_HEAP_TYPE_DSV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE } }; } @@ -71,7 +71,7 @@ DescriptorHeap::DescriptorHeap( m_increment(0) { if (count > UINT32_MAX) - throw std::exception("Too many descriptors"); + throw std::invalid_argument("Too many descriptors"); D3D12_DESCRIPTOR_HEAP_DESC desc = {}; desc.Flags = flags; @@ -197,7 +197,7 @@ void DescriptorPile::AllocateRange(size_t numDescriptors, _Out_ IndexType& start // make sure we didn't allocate zero if (numDescriptors == 0) { - throw std::out_of_range("Can't allocate zero descriptors"); + throw std::invalid_argument("Can't allocate zero descriptors"); } // get the current top @@ -211,6 +211,6 @@ void DescriptorPile::AllocateRange(size_t numDescriptors, _Out_ IndexType& start if (m_top > Count()) { DebugTrace("DescriptorPile has %zu of %zu descriptors; failed request for %zu more\n", start, Count(), numDescriptors); - throw std::exception("Can't allocate more descriptors"); + throw std::runtime_error("Can't allocate more descriptors"); } } diff --git a/Kits/DirectXTK12/Src/DirectXHelpers.cpp b/Kits/DirectXTK12/Src/DirectXHelpers.cpp index 22ed23fd..6bfe0e53 100644 --- a/Kits/DirectXTK12/Src/DirectXHelpers.cpp +++ b/Kits/DirectXTK12/Src/DirectXHelpers.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DirectXHelpers.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -78,12 +78,12 @@ void DirectX::CreateShaderResourceView( case D3D12_RESOURCE_DIMENSION_BUFFER: DebugTrace("ERROR: CreateShaderResourceView cannot be used with DIMENSION_BUFFER.\n"); - throw std::exception("buffer resources not supported"); + throw std::invalid_argument("buffer resources not supported"); case D3D12_RESOURCE_DIMENSION_UNKNOWN: default: DebugTrace("ERROR: CreateShaderResourceView cannot be used with DIMENSION_UNKNOWN (%d).\n", desc.Dimension); - throw std::exception("unknown resource dimension"); + throw std::invalid_argument("unknown resource dimension"); } device->CreateShaderResourceView(tex, &srvDesc, srvDescriptor); diff --git a/Kits/DirectXTK12/Src/DualPostProcess.cpp b/Kits/DirectXTK12/Src/DualPostProcess.cpp index 477899b8..0bb8f65a 100644 --- a/Kits/DirectXTK12/Src/DualPostProcess.cpp +++ b/Kits/DirectXTK12/Src/DualPostProcess.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DualPostProcess.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -30,7 +30,7 @@ namespace constexpr int Dirty_Parameters = 0x02; // Constant buffer layout. Must match the shader! - __declspec(align(16)) struct PostProcessConstants + XM_ALIGNED_STRUCT(16) PostProcessConstants { XMVECTOR sampleOffsets[c_MaxSamples]; XMVECTOR sampleWeights[c_MaxSamples]; @@ -76,7 +76,7 @@ namespace { PostProcess_PSBloomCombine, sizeof(PostProcess_PSBloomCombine) }, }; - static_assert(_countof(pixelShaders) == DualPostProcess::Effect_Max, "array/max mismatch"); + static_assert(std::size(pixelShaders) == DualPostProcess::Effect_Max, "array/max mismatch"); // Factory for lazily instantiating shared root signatures. class DeviceResources @@ -176,7 +176,7 @@ DualPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetState& mDeviceResources(deviceResourcesPool.DemandCreate(device)) { if (ifx >= Effect_Max) - throw std::out_of_range("Effect not defined"); + throw std::invalid_argument("Effect not defined"); // Create root signature. { @@ -215,7 +215,7 @@ DualPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetState& // Constant buffer rootParameters[RootParameterIndex::ConstantBuffer].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_PIXEL); - rsigDesc.Init(_countof(rootParameters), rootParameters, 1, &sampler, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 1, &sampler, rootSignatureFlags); mRootSignature = mDeviceResources->GetRootSignature(rsigDesc); } @@ -251,7 +251,7 @@ void DualPostProcess::Impl::Process(_In_ ID3D12GraphicsCommandList* commandList) if (!texture.ptr || !texture2.ptr) { DebugTrace("ERROR: Missing texture(s) for DualPostProcess (%llu, %llu)\n", texture.ptr, texture2.ptr); - throw std::exception("DualPostProcess"); + throw std::runtime_error("DualPostProcess"); } commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSRV, texture); commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSRV2, texture2); diff --git a/Kits/DirectXTK12/Src/DualTextureEffect.cpp b/Kits/DirectXTK12/Src/DualTextureEffect.cpp index b59c4ce5..fdfd176c 100644 --- a/Kits/DirectXTK12/Src/DualTextureEffect.cpp +++ b/Kits/DirectXTK12/Src/DualTextureEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: DualTextureEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -163,10 +163,10 @@ DualTextureEffect::Impl::Impl( texture2{}, texture2Sampler{} { - static_assert(_countof(EffectBase::VertexShaderIndices) == DualTextureEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == DualTextureEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == DualTextureEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == DualTextureEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == DualTextureEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == DualTextureEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == DualTextureEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == DualTextureEffectTraits::ShaderPermutationCount, "array/max mismatch"); // Create root signature. { @@ -193,7 +193,7 @@ DualTextureEffect::Impl::Impl( // Create the root signature CD3DX12_ROOT_SIGNATURE_DESC rsigDesc = {}; - rsigDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 0, nullptr, rootSignatureFlags); mRootSignature = GetRootSignature(0, rsigDesc); } @@ -206,12 +206,12 @@ DualTextureEffect::Impl::Impl( if (effectFlags & EffectFlags::PerPixelLightingBit) { DebugTrace("ERROR: DualTextureEffect does not implement EffectFlags::PerPixelLighting\n"); - throw std::invalid_argument("DualTextureEffect"); + throw std::invalid_argument("PerPixelLighting effect flag is invalid"); } else if (effectFlags & EffectFlags::Lighting) { DebugTrace("ERROR: DualTextureEffect does not implement EffectFlags::Lighting\n"); - throw std::invalid_argument("DualTextureEffect"); + throw std::invalid_argument("Lighting effect flag is invalid"); } // Create pipeline state. @@ -277,12 +277,12 @@ void DualTextureEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) if (!texture1.ptr || !texture2.ptr) { DebugTrace("ERROR: Missing texture(s) for DualTextureEffect (texture1 %llu, texture2 %llu)\n", texture1.ptr, texture2.ptr); - throw std::exception("DualTextureEffect"); + throw std::runtime_error("DualTextureEffect"); } if (!texture1Sampler.ptr || !texture2Sampler.ptr) { DebugTrace("ERROR: Missing sampler(s) for DualTextureEffect (samplers1 %llu, samplers2 %llu)\n", texture2Sampler.ptr, texture2Sampler.ptr); - throw std::exception("DualTextureEffect"); + throw std::runtime_error("DualTextureEffect"); } // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. diff --git a/Kits/DirectXTK12/Src/EffectCommon.cpp b/Kits/DirectXTK12/Src/EffectCommon.cpp index 7dc6dae7..7f20d487 100644 --- a/Kits/DirectXTK12/Src/EffectCommon.cpp +++ b/Kits/DirectXTK12/Src/EffectCommon.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: EffectCommon.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -341,7 +341,7 @@ void EffectLights::ValidateLightIndex(int whichLight) { if (whichLight < 0 || whichLight >= MaxDirectionalLights) { - throw std::out_of_range("whichLight parameter out of range"); + throw std::invalid_argument("whichLight parameter invalid"); } } diff --git a/Kits/DirectXTK12/Src/EffectCommon.h b/Kits/DirectXTK12/Src/EffectCommon.h index 4234feba..a7eb6f7c 100644 --- a/Kits/DirectXTK12/Src/EffectCommon.h +++ b/Kits/DirectXTK12/Src/EffectCommon.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: EffectCommon.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/EffectFactory.cpp b/Kits/DirectXTK12/Src/EffectFactory.cpp index 027158e7..b0ed3fd6 100644 --- a/Kits/DirectXTK12/Src/EffectFactory.cpp +++ b/Kits/DirectXTK12/Src/EffectFactory.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: EffectFactory.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -87,27 +87,27 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( { DebugTrace("ERROR: EffectFactory created without texture descriptor heap with texture index set (diffuse %d, specular %d, normal %d, emissive %d)!\n", info.diffuseTextureIndex, info.specularTextureIndex, info.normalTextureIndex, info.emissiveTextureIndex); - throw std::exception("EffectFactory"); + throw std::runtime_error("EffectFactory"); } if (!mSamplerDescriptors && (info.samplerIndex != -1 || info.samplerIndex2 != -1)) { DebugTrace("ERROR: EffectFactory created without sampler descriptor heap with sampler index set (samplerIndex %d, samplerIndex2 %d)!\n", info.samplerIndex, info.samplerIndex2); - throw std::exception("EffectFactory"); + throw std::runtime_error("EffectFactory"); } // If we have descriptors, make sure we have both texture and sampler descriptors if ((mTextureDescriptors == nullptr) != (mSamplerDescriptors == nullptr)) { DebugTrace("ERROR: A texture or sampler descriptor heap was provided, but both are required.\n"); - throw std::exception("EffectFactory"); + throw std::runtime_error("EffectFactory"); } // Validate the we have either both texture and sampler descriptors, or neither if ((info.diffuseTextureIndex == -1) != (info.samplerIndex == -1)) { DebugTrace("ERROR: Material provides either a texture or sampler, but both are required.\n"); - throw std::exception("EffectFactory"); + throw std::runtime_error("EffectFactory"); } int diffuseTextureIndex = (info.diffuseTextureIndex != -1 && mTextureDescriptors != nullptr) ? info.diffuseTextureIndex + textureDescriptorOffset : -1; @@ -240,7 +240,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (samplerIndex2 == -1) { DebugTrace("ERROR: Dual-texture requires a second sampler (emissive %d)\n", emissiveTextureIndex); - throw std::exception("EffectFactory"); + throw std::runtime_error("EffectFactory"); } effect->SetTexture2( @@ -253,7 +253,7 @@ std::shared_ptr EffectFactory::Impl::CreateEffect( if (samplerIndex2 == -1) { DebugTrace("ERROR: Dual-texture requires a second sampler (specular %d)\n", specularTextureIndex); - throw std::exception("EffectFactory"); + throw std::runtime_error("EffectFactory"); } effect->SetTexture2( @@ -468,20 +468,20 @@ EffectFactory::EffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors, _In_ { if (!textureDescriptors) { - throw std::exception("Texture descriptor heap cannot be null if no device is provided. Use the alternative EffectFactory constructor instead."); + throw std::invalid_argument("Texture descriptor heap cannot be null if no device is provided. Use the alternative EffectFactory constructor instead."); } if (!samplerDescriptors) { - throw std::exception("Descriptor heap cannot be null if no device is provided. Use the alternative EffectFactory constructor instead."); + throw std::invalid_argument("Descriptor heap cannot be null if no device is provided. Use the alternative EffectFactory constructor instead."); } if (textureDescriptors->GetDesc().Type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { - throw std::exception("EffectFactory::CreateEffect requires a CBV_SRV_UAV descriptor heap for textureDescriptors."); + throw std::invalid_argument("EffectFactory::CreateEffect requires a CBV_SRV_UAV descriptor heap for textureDescriptors."); } if (samplerDescriptors->GetDesc().Type != D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) { - throw std::exception("EffectFactory::CreateEffect requires a SAMPLER descriptor heap for samplerDescriptors."); + throw std::invalid_argument("EffectFactory::CreateEffect requires a SAMPLER descriptor heap for samplerDescriptors."); } ComPtr device; diff --git a/Kits/DirectXTK12/Src/EffectPipelineStateDescription.cpp b/Kits/DirectXTK12/Src/EffectPipelineStateDescription.cpp index bc219b18..f0e56f98 100644 --- a/Kits/DirectXTK12/Src/EffectPipelineStateDescription.cpp +++ b/Kits/DirectXTK12/Src/EffectPipelineStateDescription.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: EffectPipelineStateDescription.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -103,6 +103,6 @@ void EffectPipelineStateDescription::CreatePipelineState( if (FAILED(hr)) { DebugTrace("ERROR: CreatePipelineState failed to create a PSO. Enable the Direct3D Debug Layer for more information (%08X)\n", static_cast(hr)); - throw std::exception("CreateGraphicsPipelineState"); + throw std::runtime_error("CreateGraphicsPipelineState"); } } diff --git a/Kits/DirectXTK12/Src/EffectTextureFactory.cpp b/Kits/DirectXTK12/Src/EffectTextureFactory.cpp index 3342d5e9..26a95062 100644 --- a/Kits/DirectXTK12/Src/EffectTextureFactory.cpp +++ b/Kits/DirectXTK12/Src/EffectTextureFactory.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: EffectTextureFactory.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -49,8 +49,8 @@ class EffectTextureFactory::Impl , mSharing(true) , mForceSRGB(false) , mAutoGenMips(false) - { - *mPath = 0; + { + *mPath = 0; } Impl( @@ -99,7 +99,7 @@ _Use_decl_annotations_ size_t EffectTextureFactory::Impl::CreateTexture(_In_z_ const wchar_t* name, int descriptorSlot) { if (!name) - throw std::exception("invalid arguments"); + throw std::invalid_argument("name required for CreateTexture"); auto it = mTextureCache.find(name); @@ -123,12 +123,13 @@ size_t EffectTextureFactory::Impl::CreateTexture(_In_z_ const wchar_t* name, int if (!GetFileAttributesExW(fullName, GetFileExInfoStandard, &fileAttr)) { DebugTrace("ERROR: EffectTextureFactory could not find texture file '%ls'\n", name); - throw std::exception("CreateTexture"); + throw std::runtime_error("EffectTextureFactory::CreateTexture"); } } - wchar_t ext[_MAX_EXT]; + wchar_t ext[_MAX_EXT] = {}; _wsplitpath_s(name, nullptr, 0, nullptr, 0, nullptr, 0, ext, _MAX_EXT); + bool isdds = _wcsicmp(ext, L".dds") == 0; DDS_LOADER_FLAGS loadFlags = DDS_LOADER_DEFAULT; if (mForceSRGB) @@ -136,12 +137,7 @@ size_t EffectTextureFactory::Impl::CreateTexture(_In_z_ const wchar_t* name, int if (mAutoGenMips) loadFlags |= DDS_LOADER_MIP_AUTOGEN; - static_assert(static_cast(DDS_LOADER_DEFAULT) == static_cast(WIC_LOADER_DEFAULT), "DDS/WIC Load flags mismatch"); - static_assert(static_cast(DDS_LOADER_FORCE_SRGB) == static_cast(WIC_LOADER_FORCE_SRGB), "DDS/WIC Load flags mismatch"); - static_assert(static_cast(DDS_LOADER_MIP_AUTOGEN) == static_cast(WIC_LOADER_MIP_AUTOGEN), "DDS/WIC Load flags mismatch"); - static_assert(static_cast(DDS_LOADER_MIP_RESERVE) == static_cast(WIC_LOADER_MIP_RESERVE), "DDS/WIC Load flags mismatch"); - - if (_wcsicmp(ext, L".dds") == 0) + if (isdds) { HRESULT hr = CreateDDSTextureFromFileEx( mDevice.Get(), @@ -157,11 +153,16 @@ size_t EffectTextureFactory::Impl::CreateTexture(_In_z_ const wchar_t* name, int { DebugTrace("ERROR: CreateDDSTextureFromFile failed (%08X) for '%ls'\n", static_cast(hr), fullName); - throw std::exception("CreateDDSTextureFromFile"); + throw std::runtime_error("EffectTextureFactory::CreateDDSTextureFromFile"); } } else { + static_assert(static_cast(DDS_LOADER_DEFAULT) == static_cast(WIC_LOADER_DEFAULT), "DDS/WIC Load flags mismatch"); + static_assert(static_cast(DDS_LOADER_FORCE_SRGB) == static_cast(WIC_LOADER_FORCE_SRGB), "DDS/WIC Load flags mismatch"); + static_assert(static_cast(DDS_LOADER_MIP_AUTOGEN) == static_cast(WIC_LOADER_MIP_AUTOGEN), "DDS/WIC Load flags mismatch"); + static_assert(static_cast(DDS_LOADER_MIP_RESERVE) == static_cast(WIC_LOADER_MIP_RESERVE), "DDS/WIC Load flags mismatch"); + textureEntry.mIsCubeMap = false; HRESULT hr = CreateWICTextureFromFileEx( @@ -176,7 +177,7 @@ size_t EffectTextureFactory::Impl::CreateTexture(_In_z_ const wchar_t* name, int { DebugTrace("ERROR: CreateWICTextureFromFile failed (%08X) for '%ls'\n", static_cast(hr), fullName); - throw std::exception("CreateWICTextureFromFile"); + throw std::runtime_error("EffectTextureFactory::CreateWICTextureFromFile"); } } @@ -192,7 +193,7 @@ size_t EffectTextureFactory::Impl::CreateTexture(_In_z_ const wchar_t* name, int assert(textureEntry.mResource != nullptr); - // bind a new descriptor in slot + // bind a new descriptor in slot auto textureDescriptor = mTextureDescriptorHeap.GetCpuHandle(static_cast(descriptorSlot)); DirectX::CreateShaderResourceView(mDevice.Get(), textureEntry.mResource.Get(), textureDescriptor, textureEntry.mIsCubeMap); @@ -317,7 +318,7 @@ _Use_decl_annotations_ void EffectTextureFactory::GetResource(size_t slot, ID3D12Resource** resource, bool* isCubeMap) { if (slot >= pImpl->mResources.size()) - throw std::exception("Accessing resource out of range."); + throw std::invalid_argument("Resource slot is invalid"); const auto& textureEntry = pImpl->mResources[slot]; diff --git a/Kits/DirectXTK12/Src/EnvironmentMapEffect.cpp b/Kits/DirectXTK12/Src/EnvironmentMapEffect.cpp index 7b7a9fca..a1bd9e50 100644 --- a/Kits/DirectXTK12/Src/EnvironmentMapEffect.cpp +++ b/Kits/DirectXTK12/Src/EnvironmentMapEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: EnvironmentMapEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -361,10 +361,10 @@ EnvironmentMapEffect::Impl::Impl( environmentMap{}, environmentMapSampler{} { - static_assert(_countof(EffectBase::VertexShaderIndices) == EnvironmentMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == EnvironmentMapEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == EnvironmentMapEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == EnvironmentMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == EnvironmentMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == EnvironmentMapEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == EnvironmentMapEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == EnvironmentMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); // Create root signature. { @@ -391,7 +391,7 @@ EnvironmentMapEffect::Impl::Impl( // Create the root signature CD3DX12_ROOT_SIGNATURE_DESC rsigDesc = {}; - rsigDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 0, nullptr, rootSignatureFlags); mRootSignature = GetRootSignature(0, rsigDesc); } @@ -403,7 +403,7 @@ EnvironmentMapEffect::Impl::Impl( if (effectFlags & EffectFlags::VertexColor) { DebugTrace("ERROR: EnvironmentMapEffect does not implement EffectFlags::VertexColor\n"); - throw std::invalid_argument("EnvironmentMapEffect"); + throw std::invalid_argument("VertexColor effect flag is invalid"); } constants.environmentMapAmount = 1; @@ -518,12 +518,12 @@ void EnvironmentMapEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandLi if (!texture.ptr || !environmentMap.ptr) { DebugTrace("ERROR: Missing texture(s) for EnvironmentMapEffect (texture %llu, environmentMap %llu)\n", texture.ptr, environmentMap.ptr); - throw std::exception("EnvironmentMapEffect"); + throw std::runtime_error("EnvironmentMapEffect"); } if (!textureSampler.ptr || !environmentMapSampler.ptr) { DebugTrace("ERROR: Missing sampler(s) for EnvironmentMapEffect (sampler %llu, environmentMap %llu)\n", textureSampler.ptr, environmentMapSampler.ptr); - throw std::exception("EnvironmentMapEffect"); + throw std::runtime_error("EnvironmentMapEffect"); } // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. diff --git a/Kits/DirectXTK12/Src/GamePad.cpp b/Kits/DirectXTK12/Src/GamePad.cpp index dd089dfc..a2b0b383 100644 --- a/Kits/DirectXTK12/Src/GamePad.cpp +++ b/Kits/DirectXTK12/Src/GamePad.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: GamePad.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -100,7 +100,7 @@ class GamePad::Impl { if (s_gamePad) { - throw std::exception("GamePad is a singleton"); + throw std::logic_error("GamePad is a singleton"); } s_gamePad = this; @@ -129,10 +129,9 @@ class GamePad::Impl { if (mGameInput) { - HRESULT hr = mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX); - if (FAILED(hr)) + if (!mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX)) { - DebugTrace("ERROR: GameInput::UnregisterCallback [gamepad] failed (%08X)", static_cast(hr)); + DebugTrace("ERROR: GameInput::UnregisterCallback [gamepad] failed"); } } @@ -289,10 +288,11 @@ class GamePad::Impl } } - void GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept + _Success_(return != false) + bool GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept { if (!device) - return; + return false; if (player == c_MostRecent) player = mMostRecentGamepad; @@ -306,8 +306,11 @@ class GamePad::Impl { dev->AddRef(); *device = dev; + return true; } } + + return false; } GamePad* mOwner; @@ -416,7 +419,7 @@ class GamePad::Impl if (s_gamePad) { - throw std::exception("GamePad is a singleton"); + throw std::logic_error("GamePad is a singleton"); } s_gamePad = this; @@ -424,7 +427,7 @@ class GamePad::Impl mChanged.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mChanged) { - throw std::exception("CreateEventEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_Gaming_Input_Gamepad).Get(), mStatics.GetAddressOf())); @@ -899,7 +902,7 @@ class GamePad::Impl if (s_gamePad) { - throw std::exception("GamePad is a singleton"); + throw std::logic_error("GamePad is a singleton"); } s_gamePad = this; @@ -907,7 +910,7 @@ class GamePad::Impl mChanged.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mChanged) { - throw std::exception("CreateEventEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_Xbox_Input_Gamepad).Get(), mStatics.GetAddressOf())); @@ -1200,7 +1203,7 @@ class GamePad::Impl { if (empty >= MAX_PLAYER_COUNT) { - throw std::exception("Too many gamepads found"); + throw std::runtime_error("Too many gamepads found"); } mGamePad[empty] = pad; @@ -1254,7 +1257,7 @@ class GamePad::Impl if (s_gamePad) { - throw std::exception("GamePad is a singleton"); + throw std::logic_error("GamePad is a singleton"); } s_gamePad = this; @@ -1648,9 +1651,10 @@ void GamePad::RegisterEvents(HANDLE ctrlChanged) noexcept pImpl->mCtrlChanged = (!ctrlChanged) ? INVALID_HANDLE_VALUE : ctrlChanged; } -void GamePad::GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept +_Success_(return != false) +bool GamePad::GetDevice(int player, _Outptr_ IGameInputDevice** device) noexcept { - pImpl->GetDevice(player, device); + return pImpl->GetDevice(player, device); } #elif ((_WIN32_WINNT >= _WIN32_WINNT_WIN10) && !defined(_GAMING_DESKTOP)) || defined(_XBOX_ONE) void GamePad::RegisterEvents(HANDLE ctrlChanged, HANDLE userChanged) noexcept @@ -1664,7 +1668,7 @@ void GamePad::RegisterEvents(HANDLE ctrlChanged, HANDLE userChanged) noexcept GamePad& GamePad::Get() { if (!Impl::s_gamePad || !Impl::s_gamePad->mOwner) - throw std::exception("GamePad is a singleton"); + throw std::logic_error("GamePad singleton not created"); return *Impl::s_gamePad->mOwner; } diff --git a/Kits/DirectXTK12/Src/GeometricPrimitive.cpp b/Kits/DirectXTK12/Src/GeometricPrimitive.cpp index 14439718..02de5e12 100644 --- a/Kits/DirectXTK12/Src/GeometricPrimitive.cpp +++ b/Kits/DirectXTK12/Src/GeometricPrimitive.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: GeometricPrimitive.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -59,15 +59,15 @@ void GeometricPrimitive::Impl::Initialize( _In_opt_ ID3D12Device* device) { if (vertices.size() >= USHRT_MAX) - throw std::exception("Too many vertices for 16-bit index buffer"); + throw std::invalid_argument("Too many vertices for 16-bit index buffer"); if (indices.size() > UINT32_MAX) - throw std::exception("Too many indices"); + throw std::invalid_argument("Too many indices"); // Vertex data uint64_t sizeInBytes = uint64_t(vertices.size()) * sizeof(vertices[0]); if (sizeInBytes > uint64_t(D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("VB too large for DirectX 12"); + throw std::invalid_argument("VB too large for DirectX 12"); auto vertSizeBytes = static_cast(sizeInBytes); @@ -79,7 +79,7 @@ void GeometricPrimitive::Impl::Initialize( // Index data sizeInBytes = uint64_t(indices.size()) * sizeof(indices[0]); if (sizeInBytes > uint64_t(D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("IB too large for DirectX 12"); + throw std::invalid_argument("IB too large for DirectX 12"); auto indSizeBytes = static_cast(sizeInBytes); @@ -673,20 +673,20 @@ std::unique_ptr GeometricPrimitive::CreateCustom( { // Extra validation if (vertices.empty() || indices.empty()) - throw std::exception("Requires both vertices and indices"); + throw std::invalid_argument("Requires both vertices and indices"); if (indices.size() % 3) - throw std::exception("Expected triangular faces"); + throw std::invalid_argument("Expected triangular faces"); size_t nVerts = vertices.size(); if (nVerts >= USHRT_MAX) - throw std::exception("Too many vertices for 16-bit index buffer"); + throw std::invalid_argument("Too many vertices for 16-bit index buffer"); for (auto it = indices.cbegin(); it != indices.cend(); ++it) { if (*it >= nVerts) { - throw std::exception("Index not in vertices list"); + throw std::out_of_range("Index not in vertices list"); } } // Create the primitive object. diff --git a/Kits/DirectXTK12/Src/Geometry.cpp b/Kits/DirectXTK12/Src/Geometry.cpp index a2c116f9..943727cb 100644 --- a/Kits/DirectXTK12/Src/Geometry.cpp +++ b/Kits/DirectXTK12/Src/Geometry.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Geometry.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -24,7 +24,7 @@ namespace { // Use >=, not > comparison, because some D3D level 9_x hardware does not support 0xFFFF index values. if (value >= USHRT_MAX) - throw std::exception("Index value out of range: cannot tesselate primitive so finely"); + throw std::out_of_range("Index value out of range: cannot tesselate primitive so finely"); } @@ -150,7 +150,7 @@ void DirectX::ComputeSphere(VertexCollection& vertices, IndexCollection& indices indices.clear(); if (tessellation < 3) - throw std::out_of_range("tesselation parameter out of range"); + throw std::invalid_argument("tesselation parameter must be at least 3"); size_t verticalSegments = tessellation; size_t horizontalSegments = tessellation * 2; @@ -372,7 +372,7 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi vertices.reserve(vertexPositions.size()); for (auto it = vertexPositions.begin(); it != vertexPositions.end(); ++it) { - auto vertexValue = *it; + const auto& vertexValue = *it; auto normal = XMVector3Normalize(XMLoadFloat3(&vertexValue)); auto pos = XMVectorScale(normal, radius); @@ -472,7 +472,7 @@ void DirectX::ComputeGeoSphere(VertexCollection& vertices, IndexCollection& indi // poles, but reduce stretching. auto fixPole = [&](size_t poleIndex) { - auto poleVertex = vertices[poleIndex]; + const auto& poleVertex = vertices[poleIndex]; bool overwrittenPoleVertex = false; // overwriting the original pole vertex saves us one vertex for (size_t i = 0; i < indices.size(); i += 3) @@ -617,7 +617,7 @@ void DirectX::ComputeCylinder(VertexCollection& vertices, IndexCollection& indic indices.clear(); if (tessellation < 3) - throw std::out_of_range("tesselation parameter out of range"); + throw std::invalid_argument("tesselation parameter must be at least 3"); height /= 2; @@ -666,7 +666,7 @@ void DirectX::ComputeCone(VertexCollection& vertices, IndexCollection& indices, indices.clear(); if (tessellation < 3) - throw std::out_of_range("tesselation parameter out of range"); + throw std::invalid_argument("tesselation parameter must be at least 3"); height /= 2; @@ -720,7 +720,7 @@ void DirectX::ComputeTorus(VertexCollection& vertices, IndexCollection& indices, indices.clear(); if (tessellation < 3) - throw std::out_of_range("tesselation parameter out of range"); + throw std::invalid_argument("tesselation parameter must be at least 3"); size_t stride = tessellation + 1; @@ -799,7 +799,7 @@ void DirectX::ComputeTetrahedron(VertexCollection& vertices, IndexCollection& in 1, 3, 2, }; - for (size_t j = 0; j < _countof(faces); j += 3) + for (size_t j = 0; j < std::size(faces); j += 3) { uint32_t v0 = faces[j]; uint32_t v1 = faces[j + 1]; @@ -865,7 +865,7 @@ void DirectX::ComputeOctahedron(VertexCollection& vertices, IndexCollection& ind 5, 0, 3 }; - for (size_t j = 0; j < _countof(faces); j += 3) + for (size_t j = 0; j < std::size(faces); j += 3) { uint32_t v0 = faces[j]; uint32_t v1 = faces[j + 1]; @@ -979,7 +979,7 @@ void DirectX::ComputeDodecahedron(VertexCollection& vertices, IndexCollection& i }; size_t t = 0; - for (size_t j = 0; j < _countof(faces); j += 5, ++t) + for (size_t j = 0; j < std::size(faces); j += 5, ++t) { uint32_t v0 = faces[j]; uint32_t v1 = faces[j + 1]; @@ -1083,7 +1083,7 @@ void DirectX::ComputeIcosahedron(VertexCollection& vertices, IndexCollection& in 11, 7, 5 }; - for (size_t j = 0; j < _countof(faces); j += 3) + for (size_t j = 0; j < std::size(faces); j += 3) { uint32_t v0 = faces[j]; uint32_t v1 = faces[j + 1]; @@ -1162,7 +1162,7 @@ void DirectX::ComputeTeapot(VertexCollection& vertices, IndexCollection& indices indices.clear(); if (tessellation < 1) - throw std::out_of_range("tesselation parameter out of range"); + throw std::invalid_argument("tesselation parameter must be non-zero"); XMVECTOR scaleVector = XMVectorReplicate(size); @@ -1170,7 +1170,7 @@ void DirectX::ComputeTeapot(VertexCollection& vertices, IndexCollection& indices XMVECTOR scaleNegateZ = XMVectorMultiply(scaleVector, g_XMNegateZ); XMVECTOR scaleNegateXZ = XMVectorMultiply(scaleVector, XMVectorMultiply(g_XMNegateX, g_XMNegateZ)); - for (size_t i = 0; i < _countof(TeapotPatches); i++) + for (size_t i = 0; i < std::size(TeapotPatches); i++) { TeapotPatch const& patch = TeapotPatches[i]; diff --git a/Kits/DirectXTK12/Src/Geometry.h b/Kits/DirectXTK12/Src/Geometry.h index 73969df7..c5a5475d 100644 --- a/Kits/DirectXTK12/Src/Geometry.h +++ b/Kits/DirectXTK12/Src/Geometry.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Geometry.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK12/Src/GraphicsMemory.cpp b/Kits/DirectXTK12/Src/GraphicsMemory.cpp index b1fd0787..622a572d 100644 --- a/Kits/DirectXTK12/Src/GraphicsMemory.cpp +++ b/Kits/DirectXTK12/Src/GraphicsMemory.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: GraphicsMemory.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -53,11 +53,26 @@ namespace // 4 - 16k allocator // etc... // Need to convert to an index. - DWORD bitIndex = 0; + +#ifdef _MSC_VER + unsigned long bitIndex = 0; + #ifdef _WIN64 return _BitScanForward64(&bitIndex, allocatorPageSize) ? bitIndex + 1 : 0; #else - return _BitScanForward(&bitIndex, static_cast(allocatorPageSize)) ? bitIndex + 1 : 0; + return _BitScanForward(&bitIndex, static_cast(allocatorPageSize)) ? bitIndex + 1 : 0; +#endif + +#elif defined(__GNUC__) + +#ifdef __LP64__ + return static_cast(__builtin_ffsll(static_cast(allocatorPageSize))); +#else + return static_cast(__builtin_ffs(static_cast(allocatorPageSize))); +#endif + +#else +#error Unknown forward bit-scan syntax #endif } @@ -171,7 +186,7 @@ namespace size_t totalPageCount = 0; size_t committedMemoryUsage = 0; size_t totalMemoryUsage = 0; - + ScopedLock lock(mMutex); for (auto& i : mPools) @@ -218,7 +233,7 @@ class GraphicsMemory::Impl #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) if (s_graphicsMemory) { - throw std::exception("GraphicsMemory is a singleton"); + throw std::logic_error("GraphicsMemory is a singleton"); } s_graphicsMemory = this; @@ -251,7 +266,7 @@ class GraphicsMemory::Impl #if !(defined(_XBOX_ONE) && defined(_TITLE)) && !defined(_GAMING_XBOX) if (s_graphicsMemory.find(device) != s_graphicsMemory.cend()) { - throw std::exception("GraphicsMemory is a per-device singleton"); + throw std::logic_error("GraphicsMemory is a per-device singleton"); } s_graphicsMemory[device] = this; #endif @@ -346,7 +361,7 @@ GraphicsMemory::GraphicsMemory(GraphicsMemory&& moveFrom) noexcept // Move assignment. GraphicsMemory& GraphicsMemory::operator= (GraphicsMemory&& moveFrom) noexcept -{ +{ pImpl = std::move(moveFrom.pImpl); pImpl->mOwner = this; return *this; @@ -393,7 +408,7 @@ void GraphicsMemory::ResetStatistics() GraphicsMemory& GraphicsMemory::Get(_In_opt_ ID3D12Device*) { if (!Impl::s_graphicsMemory || !Impl::s_graphicsMemory->mOwner) - throw std::exception("GraphicsMemory singleton not created"); + throw std::logic_error("GraphicsMemory singleton not created"); return *Impl::s_graphicsMemory->mOwner; } @@ -401,7 +416,7 @@ GraphicsMemory& GraphicsMemory::Get(_In_opt_ ID3D12Device*) GraphicsMemory& GraphicsMemory::Get(_In_opt_ ID3D12Device* device) { if (Impl::s_graphicsMemory.empty()) - throw std::exception("GraphicsMemory singleton not created"); + throw std::logic_error("GraphicsMemory singleton not created"); std::map::const_iterator it; if (!device) @@ -417,7 +432,7 @@ GraphicsMemory& GraphicsMemory::Get(_In_opt_ ID3D12Device* device) } if (it == Impl::s_graphicsMemory.cend() || !it->second->mOwner) - throw std::exception("GraphicsMemory per-device singleton not created"); + throw std::logic_error("GraphicsMemory per-device singleton not created"); return *it->second->mOwner; } @@ -586,4 +601,3 @@ void SharedGraphicsResource::Reset(const SharedGraphicsResource& resource) noexc { mSharedResource = resource.mSharedResource; } - diff --git a/Kits/DirectXTK12/Src/Keyboard.cpp b/Kits/DirectXTK12/Src/Keyboard.cpp index 88439b1b..76d04a1d 100644 --- a/Kits/DirectXTK12/Src/Keyboard.cpp +++ b/Kits/DirectXTK12/Src/Keyboard.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Keyboard.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -67,7 +67,7 @@ class Keyboard::Impl { if (s_keyboard) { - throw std::exception("Keyboard is a singleton"); + throw std::logic_error("Keyboard is a singleton"); } s_keyboard = this; @@ -96,10 +96,9 @@ class Keyboard::Impl { if (mGameInput) { - HRESULT hr = mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX); - if (FAILED(hr)) + if (!mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX)) { - DebugTrace("ERROR: GameInput::UnregisterCallback [keyboard] failed (%08X)", static_cast(hr)); + DebugTrace("ERROR: GameInput::UnregisterCallback [keyboard] failed"); } } @@ -210,7 +209,7 @@ class Keyboard::Impl { if (s_keyboard) { - throw std::exception("Keyboard is a singleton"); + throw std::logic_error("Keyboard is a singleton"); } s_keyboard = this; @@ -343,7 +342,7 @@ class Keyboard::Impl { if (s_keyboard) { - throw std::exception("Keyboard is a singleton"); + throw std::logic_error("Keyboard is a singleton"); } s_keyboard = this; @@ -604,7 +603,7 @@ bool Keyboard::IsConnected() const Keyboard& Keyboard::Get() { if (!Impl::s_keyboard || !Impl::s_keyboard->mOwner) - throw std::exception("Keyboard is a singleton"); + throw std::logic_error("Keyboard singleton not created"); return *Impl::s_keyboard->mOwner; } diff --git a/Kits/DirectXTK12/Src/LinearAllocator.cpp b/Kits/DirectXTK12/Src/LinearAllocator.cpp index dbc8c1a8..c33945f5 100644 --- a/Kits/DirectXTK12/Src/LinearAllocator.cpp +++ b/Kits/DirectXTK12/Src/LinearAllocator.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: LinearAllocator.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -41,7 +41,7 @@ size_t LinearAllocatorPage::Suballocate(_In_ size_t size, _In_ size_t alignment) { // Use of suballocate should be limited to pages with free space, // so really shouldn't happen. - throw std::exception("LinearAllocatorPage::Suballocate"); + throw std::runtime_error("LinearAllocatorPage::Suballocate"); } mOffset = offset + size; return offset; @@ -123,7 +123,7 @@ LinearAllocatorPage* LinearAllocator::FindPageForAlloc(_In_ size_t size, _In_ si if (alignment > m_increment) throw std::out_of_range("Alignment must be less or equal to the allocator's increment"); if (size == 0) - throw std::exception("Cannot honor zero size allocation request."); + throw std::invalid_argument("Cannot honor zero size allocation request."); #endif auto page = GetPageForAlloc(size, alignment); @@ -453,7 +453,7 @@ void LinearAllocator::ValidateList(LinearAllocatorPage* list) { if (page->pPrevPage != lastPage) { - throw std::exception("Broken link to previous"); + throw std::runtime_error("Broken link to previous"); } } } diff --git a/Kits/DirectXTK12/Src/LinearAllocator.h b/Kits/DirectXTK12/Src/LinearAllocator.h index 10b7a5cc..133a1e4c 100644 --- a/Kits/DirectXTK12/Src/LinearAllocator.h +++ b/Kits/DirectXTK12/Src/LinearAllocator.h @@ -34,7 +34,7 @@ // allocator.InsertFences( pContext, 0 ); // Present(...); // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/LoaderHelpers.h b/Kits/DirectXTK12/Src/LoaderHelpers.h index d8aac62c..eb71d2ed 100644 --- a/Kits/DirectXTK12/Src/LoaderHelpers.h +++ b/Kits/DirectXTK12/Src/LoaderHelpers.h @@ -3,7 +3,7 @@ // // Helper functions for texture loaders and screen grabber // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -296,6 +296,8 @@ namespace DirectX return E_POINTER; } + *bitSize = 0; + if (ddsDataSize > UINT32_MAX) { return E_FAIL; @@ -328,7 +330,7 @@ namespace DirectX (MAKEFOURCC('D', 'X', '1', '0') == hdr->ddspf.fourCC)) { // Must be long enough for both headers and magic value - if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_DXT10))) + if (ddsDataSize < (sizeof(uint32_t) + sizeof(DDS_HEADER) + sizeof(DDS_HEADER_DXT10))) { return E_FAIL; } @@ -360,6 +362,8 @@ namespace DirectX return E_POINTER; } + *bitSize = 0; + // open the file #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) ScopedHandle hFile(safe_handle(CreateFile2(fileName, @@ -409,19 +413,21 @@ namespace DirectX } // read the data in - DWORD BytesRead = 0; + DWORD bytesRead = 0; if (!ReadFile(hFile.get(), ddsData.get(), fileInfo.EndOfFile.LowPart, - &BytesRead, + &bytesRead, nullptr )) { + ddsData.reset(); return HRESULT_FROM_WIN32(GetLastError()); } - if (BytesRead < fileInfo.EndOfFile.LowPart) + if (bytesRead < fileInfo.EndOfFile.LowPart) { + ddsData.reset(); return E_FAIL; } @@ -429,6 +435,7 @@ namespace DirectX auto dwMagicNumber = *reinterpret_cast(ddsData.get()); if (dwMagicNumber != DDS_MAGIC) { + ddsData.reset(); return E_FAIL; } @@ -438,6 +445,7 @@ namespace DirectX if (hdr->size != sizeof(DDS_HEADER) || hdr->ddspf.size != sizeof(DDS_PIXELFORMAT)) { + ddsData.reset(); return E_FAIL; } @@ -447,8 +455,9 @@ namespace DirectX (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))) + if (fileInfo.EndOfFile.LowPart < (sizeof(uint32_t) + sizeof(DDS_HEADER) + sizeof(DDS_HEADER_DXT10))) { + ddsData.reset(); return E_FAIL; } @@ -637,97 +646,103 @@ namespace DirectX // 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, 0)) - { - return DXGI_FORMAT_B8G8R8X8_UNORM; - } - - // No DXGI format maps to ISBITMASK(0x000000ff,0x0000ff00,0x00ff0000,0) 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, 0, 0)) - { - return DXGI_FORMAT_R16G16_UNORM; - } - - if (ISBITMASK(0xffffffff, 0, 0, 0)) - { - // 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, 0)) - { - return DXGI_FORMAT_B5G6R5_UNORM; - } - - // No DXGI format maps to ISBITMASK(0x7c00,0x03e0,0x001f,0) aka D3DFMT_X1R5G5B5 - - if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000)) - { - return DXGI_FORMAT_B4G4R4A4_UNORM; - } - - // No DXGI format maps to ISBITMASK(0x0f00,0x00f0,0x000f,0) 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(0xff, 0, 0, 0)) + { + case 32: + if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) { - return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension + return DXGI_FORMAT_R8G8B8A8_UNORM; } - // No DXGI format maps to ISBITMASK(0x0f,0,0,0xf0) aka D3DFMT_A4L4 + if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000)) + { + return DXGI_FORMAT_B8G8R8A8_UNORM; + } + + if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0)) + { + return DXGI_FORMAT_B8G8R8X8_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x000000ff,0x0000ff00,0x00ff0000,0) 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, 0, 0)) + { + return DXGI_FORMAT_R16G16_UNORM; + } + + if (ISBITMASK(0xffffffff, 0, 0, 0)) + { + // 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, 0)) + { + return DXGI_FORMAT_B5G6R5_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x7c00,0x03e0,0x001f,0) aka D3DFMT_X1R5G5B5 + + if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000)) + { + return DXGI_FORMAT_B4G4R4A4_UNORM; + } + // NVTT versions 1.x wrote this as RGB instead of LUMINANCE if (ISBITMASK(0x00ff, 0, 0, 0xff00)) { - return DXGI_FORMAT_R8G8_UNORM; // Some DDS writers assume the bitcount should be 8 instead of 16 + return DXGI_FORMAT_R8G8_UNORM; + } + if (ISBITMASK(0xffff, 0, 0, 0)) + { + return DXGI_FORMAT_R16_UNORM; + } + + // No DXGI format maps to ISBITMASK(0x0f00,0x00f0,0x000f,0) aka D3DFMT_X4R4G4B4 + + // No 3:3:2:8 or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_A8P8, etc. + break; + + case 8: + // NVTT versions 1.x wrote this as RGB instead of LUMINANCE + if (ISBITMASK(0xff, 0, 0, 0)) + { + return DXGI_FORMAT_R8_UNORM; } - } - if (16 == ddpf.RGBBitCount) + // No 3:3:2 or paletted DXGI formats aka D3DFMT_R3G3B2, D3DFMT_P8 + break; + } + } + else if (ddpf.flags & DDS_LUMINANCE) + { + switch (ddpf.RGBBitCount) { + case 16: if (ISBITMASK(0xffff, 0, 0, 0)) { return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension @@ -736,6 +751,21 @@ namespace DirectX { return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension } + break; + + case 8: + if (ISBITMASK(0xff, 0, 0, 0)) + { + return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension + } + + // No DXGI format maps to ISBITMASK(0x0f,0,0,0xf0) aka D3DFMT_A4L4 + + if (ISBITMASK(0x00ff, 0, 0, 0xff00)) + { + return DXGI_FORMAT_R8G8_UNORM; // Some DDS writers assume the bitcount should be 8 instead of 16 + } + break; } } else if (ddpf.flags & DDS_ALPHA) @@ -747,16 +777,9 @@ namespace DirectX } else if (ddpf.flags & DDS_BUMPDUDV) { - if (16 == ddpf.RGBBitCount) - { - if (ISBITMASK(0x00ff, 0xff00, 0, 0)) - { - return DXGI_FORMAT_R8G8_SNORM; // D3DX10/11 writes this out as DX10 extension - } - } - - if (32 == ddpf.RGBBitCount) + switch (ddpf.RGBBitCount) { + case 32: if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) { return DXGI_FORMAT_R8G8B8A8_SNORM; // D3DX10/11 writes this out as DX10 extension @@ -767,6 +790,14 @@ namespace DirectX } // No DXGI format maps to ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000) aka D3DFMT_A2W10V10U10 + break; + + case 16: + if (ISBITMASK(0x00ff, 0xff00, 0, 0)) + { + return DXGI_FORMAT_R8G8_SNORM; // D3DX10/11 writes this out as DX10 extension + } + break; } // No DXGI format maps to DDPF_BUMPLUMINANCE aka D3DFMT_L6V5U5, D3DFMT_X8L8V8U8 diff --git a/Kits/DirectXTK12/Src/Model.cpp b/Kits/DirectXTK12/Src/Model.cpp index 15d5153c..e7ddb7b7 100644 --- a/Kits/DirectXTK12/Src/Model.cpp +++ b/Kits/DirectXTK12/Src/Model.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Model.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -19,7 +19,7 @@ using namespace DirectX; -#ifndef _CPPRTTI +#if !defined(_CPPRTTI) && !defined(__GXX_RTTI) #error Model requires RTTI #endif @@ -55,19 +55,19 @@ void ModelMeshPart::Draw(_In_ ID3D12GraphicsCommandList* commandList) const if (!indexBufferSize || !vertexBufferSize) { DebugTrace("ERROR: Model part missing values for vertex and/or index buffer size (indexBufferSize %u, vertexBufferSize %u)!\n", indexBufferSize, vertexBufferSize); - throw std::exception("ModelMeshPart"); + throw std::runtime_error("ModelMeshPart"); } if (!staticIndexBuffer && !indexBuffer) { DebugTrace("ERROR: Model part missing index buffer!\n"); - throw std::exception("ModelMeshPart"); + throw std::runtime_error("ModelMeshPart"); } if (!staticVertexBuffer && !vertexBuffer) { DebugTrace("ERROR: Model part missing vertex buffer!\n"); - throw std::exception("ModelMeshPart"); + throw std::runtime_error("ModelMeshPart"); } D3D12_VERTEX_BUFFER_VIEW vbv; @@ -94,19 +94,19 @@ void ModelMeshPart::DrawInstanced(_In_ ID3D12GraphicsCommandList* commandList, u if (!indexBufferSize || !vertexBufferSize) { DebugTrace("ERROR: Model part missing values for vertex and/or index buffer size (indexBufferSize %u, vertexBufferSize %u)!\n", indexBufferSize, vertexBufferSize); - throw std::exception("ModelMeshPart"); + throw std::runtime_error("ModelMeshPart"); } if (!staticIndexBuffer && !indexBuffer) { DebugTrace("ERROR: Model part missing index buffer!\n"); - throw std::exception("ModelMeshPart"); + throw std::runtime_error("ModelMeshPart"); } if (!staticVertexBuffer && !vertexBuffer) { DebugTrace("ERROR: Model part missing vertex buffer!\n"); - throw std::exception("ModelMeshPart"); + throw std::runtime_error("ModelMeshPart"); } D3D12_VERTEX_BUFFER_VIEW vbv; @@ -301,7 +301,7 @@ void Model::LoadStaticBuffers( if (!part->vertexBuffer) { DebugTrace("ERROR: Model part missing vertex buffer!\n"); - throw std::exception("ModelMeshPart"); + throw std::runtime_error("ModelMeshPart"); } part->vertexBufferSize = static_cast(part->vertexBuffer.Size()); @@ -357,7 +357,7 @@ void Model::LoadStaticBuffers( if (!part->indexBuffer) { DebugTrace("ERROR: Model part missing index buffer!\n"); - throw std::exception("ModelMeshPart"); + throw std::runtime_error("ModelMeshPart"); } part->indexBufferSize = static_cast(part->indexBuffer.Size()); @@ -421,7 +421,7 @@ std::vector> Model::CreateEffects( if (materials.empty()) { DebugTrace("ERROR: Model has no material information to create effects!\n"); - throw std::exception("CreateEffects"); + throw std::runtime_error("CreateEffects"); } std::vector> effects; @@ -492,10 +492,10 @@ std::shared_ptr Model::CreateEffectForMeshPart( const auto& m = materials[part->materialIndex]; if (!part->vbDecl || part->vbDecl->empty()) - throw std::exception("Model mesh part missing vertex buffer input elements data"); + throw std::runtime_error("Model mesh part missing vertex buffer input elements data"); if (part->vbDecl->size() > D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) - throw std::exception("Model mesh part input layout size is too large for DirectX 12"); + throw std::runtime_error("Model mesh part input layout size is too large for DirectX 12"); D3D12_INPUT_LAYOUT_DESC il = {}; il.NumElements = static_cast(part->vbDecl->size()); @@ -550,8 +550,8 @@ void Model::Transition( { for (auto& pit : mit->opaqueMeshParts) { - assert(count < _countof(barrier)); - _Analysis_assume_(count < _countof(barrier)); + assert(count < std::size(barrier)); + _Analysis_assume_(count < std::size(barrier)); if (stateBeforeIB != stateAfterIB && pit->staticIndexBuffer) { @@ -562,7 +562,7 @@ void Model::Transition( barrier[count].Transition.StateAfter = stateAfterIB; ++count; - if (count >= _countof(barrier)) + if (count >= std::size(barrier)) { commandList->ResourceBarrier(count, barrier); count = 0; @@ -578,7 +578,7 @@ void Model::Transition( barrier[count].Transition.StateAfter = stateAfterVB; ++count; - if (count >= _countof(barrier)) + if (count >= std::size(barrier)) { commandList->ResourceBarrier(count, barrier); count = 0; @@ -588,8 +588,8 @@ void Model::Transition( for (auto& pit : mit->alphaMeshParts) { - assert(count < _countof(barrier)); - _Analysis_assume_(count < _countof(barrier)); + assert(count < std::size(barrier)); + _Analysis_assume_(count < std::size(barrier)); if (stateBeforeIB != stateAfterIB && pit->staticIndexBuffer) { @@ -600,7 +600,7 @@ void Model::Transition( barrier[count].Transition.StateAfter = stateAfterIB; ++count; - if (count >= _countof(barrier)) + if (count >= std::size(barrier)) { commandList->ResourceBarrier(count, barrier); count = 0; @@ -616,7 +616,7 @@ void Model::Transition( barrier[count].Transition.StateAfter = stateAfterVB; ++count; - if (count >= _countof(barrier)) + if (count >= std::size(barrier)) { commandList->ResourceBarrier(count, barrier); count = 0; diff --git a/Kits/DirectXTK12/Src/ModelLoadSDKMESH.cpp b/Kits/DirectXTK12/Src/ModelLoadSDKMESH.cpp index b9078162..7e5f26b2 100644 --- a/Kits/DirectXTK12/Src/ModelLoadSDKMESH.cpp +++ b/Kits/DirectXTK12/Src/ModelLoadSDKMESH.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: ModelLoadSDKMESH.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -71,6 +71,12 @@ namespace } } + template + inline void ASCIIToWChar(wchar_t (&buffer)[sizeOfBuffer], const char *ascii) + { + MultiByteToWideChar(CP_UTF8, 0, ascii, -1, buffer, sizeOfBuffer); + } + void InitMaterial( const DXUT::SDKMESH_MATERIAL& mh, unsigned int flags, @@ -79,16 +85,16 @@ namespace bool srgb) { wchar_t matName[DXUT::MAX_MATERIAL_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.Name, -1, matName, DXUT::MAX_MATERIAL_NAME); + ASCIIToWChar(matName, mh.Name); wchar_t diffuseName[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.DiffuseTexture, -1, diffuseName, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(diffuseName, mh.DiffuseTexture); wchar_t specularName[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.SpecularTexture, -1, specularName, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(specularName, mh.SpecularTexture); wchar_t normalName[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.NormalTexture, -1, normalName, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(normalName, mh.NormalTexture); if ((flags & DUAL_TEXTURE) && !mh.SpecularTexture[0]) { @@ -160,19 +166,19 @@ namespace _Inout_ std::map& textureDictionary) { wchar_t matName[DXUT::MAX_MATERIAL_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.Name, -1, matName, DXUT::MAX_MATERIAL_NAME); + ASCIIToWChar(matName, mh.Name); wchar_t albetoTexture[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.AlbetoTexture, -1, albetoTexture, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(albetoTexture, mh.AlbetoTexture); wchar_t normalName[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.NormalTexture, -1, normalName, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(normalName, mh.NormalTexture); wchar_t rmaName[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.RMATexture, -1, rmaName, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(rmaName, mh.RMATexture); wchar_t emissiveName[DXUT::MAX_TEXTURE_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.EmissiveTexture, -1, emissiveName, DXUT::MAX_TEXTURE_NAME); + ASCIIToWChar(emissiveName, mh.EmissiveTexture); m = {}; m.name = matName; @@ -368,7 +374,7 @@ namespace } if (!posfound) - throw std::exception("SV_Position is required"); + throw std::runtime_error("SV_Position is required"); if (texcoords == 2) { @@ -391,74 +397,74 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( ModelLoaderFlags flags) { if (!meshData) - throw std::exception("meshData cannot be null"); + throw std::invalid_argument("meshData cannot be null"); uint64_t dataSize = idataSize; // File Headers if (dataSize < sizeof(DXUT::SDKMESH_HEADER)) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto header = reinterpret_cast(meshData); size_t headerSize = sizeof(DXUT::SDKMESH_HEADER) + header->NumVertexBuffers * sizeof(DXUT::SDKMESH_VERTEX_BUFFER_HEADER) + header->NumIndexBuffers * sizeof(DXUT::SDKMESH_INDEX_BUFFER_HEADER); if (header->HeaderSize != headerSize) - throw std::exception("Not a valid SDKMESH file"); + throw std::runtime_error("Not a valid SDKMESH file"); if (dataSize < header->HeaderSize) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (header->Version != DXUT::SDKMESH_FILE_VERSION && header->Version != DXUT::SDKMESH_FILE_VERSION_V2) - throw std::exception("Not a supported SDKMESH version"); + throw std::runtime_error("Not a supported SDKMESH version"); if (header->IsBigEndian) - throw std::exception("Loading BigEndian SDKMESH files not supported"); + throw std::runtime_error("Loading BigEndian SDKMESH files not supported"); if (!header->NumMeshes) - throw std::exception("No meshes found"); + throw std::runtime_error("No meshes found"); if (!header->NumVertexBuffers) - throw std::exception("No vertex buffers found"); + throw std::runtime_error("No vertex buffers found"); if (!header->NumIndexBuffers) - throw std::exception("No index buffers found"); + throw std::runtime_error("No index buffers found"); if (!header->NumTotalSubsets) - throw std::exception("No subsets found"); + throw std::runtime_error("No subsets found"); if (!header->NumMaterials) - throw std::exception("No materials found"); + throw std::runtime_error("No materials found"); // Sub-headers if (dataSize < header->VertexStreamHeadersOffset || (dataSize < (header->VertexStreamHeadersOffset + uint64_t(header->NumVertexBuffers) * sizeof(DXUT::SDKMESH_VERTEX_BUFFER_HEADER)))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto vbArray = reinterpret_cast(meshData + header->VertexStreamHeadersOffset); if (dataSize < header->IndexStreamHeadersOffset || (dataSize < (header->IndexStreamHeadersOffset + uint64_t(header->NumIndexBuffers) * sizeof(DXUT::SDKMESH_INDEX_BUFFER_HEADER)))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto ibArray = reinterpret_cast(meshData + header->IndexStreamHeadersOffset); if (dataSize < header->MeshDataOffset || (dataSize < (header->MeshDataOffset + uint64_t(header->NumMeshes) * sizeof(DXUT::SDKMESH_MESH)))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto meshArray = reinterpret_cast(meshData + header->MeshDataOffset); if (dataSize < header->SubsetDataOffset || (dataSize < (header->SubsetDataOffset + uint64_t(header->NumTotalSubsets) * sizeof(DXUT::SDKMESH_SUBSET)))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto subsetArray = reinterpret_cast(meshData + header->SubsetDataOffset); if (dataSize < header->FrameDataOffset || (dataSize < (header->FrameDataOffset + uint64_t(header->NumFrames) * sizeof(DXUT::SDKMESH_FRAME)))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); // TODO - auto frameArray = reinterpret_cast( meshData + header->FrameDataOffset ); if (dataSize < header->MaterialDataOffset || (dataSize < (header->MaterialDataOffset + uint64_t(header->NumMaterials) * sizeof(DXUT::SDKMESH_MATERIAL)))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); const DXUT::SDKMESH_MATERIAL* materialArray = nullptr; const DXUT::SDKMESH_MATERIAL_V2* materialArray_v2 = nullptr; @@ -475,7 +481,7 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( uint64_t bufferDataOffset = header->HeaderSize + header->NonBufferDataSize; if ((dataSize < bufferDataOffset) || (dataSize < bufferDataOffset + header->BufferDataSize)) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); const uint8_t* bufferData = meshData + bufferDataOffset; // Create vertex buffers @@ -491,17 +497,17 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( auto& vh = vbArray[j]; if (vh.SizeBytes > UINT32_MAX) - throw std::exception("VB too large"); + throw std::runtime_error("VB too large"); if (!(flags & ModelLoader_AllowLargeModels)) { if (vh.SizeBytes > (D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("VB too large for DirectX 12"); + throw std::runtime_error("VB too large for DirectX 12"); } if (dataSize < vh.DataOffset || (dataSize < vh.DataOffset + vh.SizeBytes)) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); vbDecls[j] = std::make_shared>(); unsigned int ilflags = GetInputLayoutDesc(vh.Decl, *vbDecls[j].get()); @@ -535,20 +541,20 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( auto& ih = ibArray[j]; if (ih.SizeBytes > UINT32_MAX) - throw std::exception("IB too large"); + throw std::runtime_error("IB too large"); if (!(flags & ModelLoader_AllowLargeModels)) { if (ih.SizeBytes > (D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("IB too large for DirectX 12"); + throw std::runtime_error("IB too large for DirectX 12"); } if (dataSize < ih.DataOffset || (dataSize < ih.DataOffset + ih.SizeBytes)) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); if (ih.IndexType != DXUT::IT_16BIT && ih.IndexType != DXUT::IT_32BIT) - throw std::exception("Invalid index buffer type found"); + throw std::runtime_error("Invalid index buffer type found"); } // Create meshes @@ -570,13 +576,13 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( || !mh.NumVertexBuffers || mh.IndexBuffer >= header->NumIndexBuffers || mh.VertexBuffers[0] >= header->NumVertexBuffers) - throw std::exception("Invalid mesh found"); + throw std::out_of_range("Invalid mesh found"); // mh.NumVertexBuffers is sometimes not what you'd expect, so we skip validating it if (dataSize < mh.SubsetOffset || (dataSize < mh.SubsetOffset + uint64_t(mh.NumSubsets) * sizeof(UINT))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto subsets = reinterpret_cast(meshData + mh.SubsetOffset); @@ -584,14 +590,15 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( { if (dataSize < mh.FrameInfluenceOffset || (dataSize < mh.FrameInfluenceOffset + uint64_t(mh.NumFrameInfluences) * sizeof(UINT))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); // TODO - auto influences = reinterpret_cast( meshData + mh.FrameInfluenceOffset ); } auto mesh = std::make_shared(); wchar_t meshName[DXUT::MAX_MESH_NAME] = {}; - MultiByteToWideChar(CP_UTF8, 0, mh.Name, -1, meshName, DXUT::MAX_MESH_NAME); + ASCIIToWChar(meshName, mh.Name); + mesh->name = meshName; // Extents @@ -604,7 +611,7 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( { auto sIndex = subsets[j]; if (sIndex >= header->NumTotalSubsets) - throw std::exception("Invalid mesh found"); + throw std::out_of_range("Invalid mesh found"); auto& subset = subsetArray[sIndex]; @@ -623,14 +630,14 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( case DXUT::PT_QUAD_PATCH_LIST: case DXUT::PT_TRIANGLE_PATCH_LIST: - throw std::exception("Direct3D9 era tessellation not supported"); + throw std::runtime_error("Direct3D9 era tessellation not supported"); default: - throw std::exception("Unknown primitive type"); + throw std::runtime_error("Unknown primitive type"); } if (subset.MaterialID >= header->NumMaterials) - throw std::exception("Invalid mesh found"); + throw std::out_of_range("Invalid mesh found"); auto& mat = materials[subset.MaterialID]; @@ -718,7 +725,7 @@ std::unique_ptr DirectX::Model::CreateFromSDKMESH( { DebugTrace("ERROR: CreateFromSDKMESH failed (%08X) loading '%ls'\n", static_cast(hr), szFileName); - throw std::exception("CreateFromSDKMESH"); + throw std::runtime_error("CreateFromSDKMESH"); } auto model = CreateFromSDKMESH(device, data.get(), dataSize, flags); diff --git a/Kits/DirectXTK12/Src/ModelLoadVBO.cpp b/Kits/DirectXTK12/Src/ModelLoadVBO.cpp index e7e4c52c..d8385ff6 100644 --- a/Kits/DirectXTK12/Src/ModelLoadVBO.cpp +++ b/Kits/DirectXTK12/Src/ModelLoadVBO.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: ModelLoadVBO.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -53,49 +53,49 @@ std::unique_ptr DirectX::Model::CreateFromVBO( ModelLoaderFlags flags) { if (!InitOnceExecuteOnce(&g_InitOnce, InitializeDecl, nullptr, nullptr)) - throw std::exception("One-time initialization failed"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "InitOnceExecuteOnce"); if (!meshData) - throw std::exception("meshData cannot be null"); + throw std::invalid_argument("meshData cannot be null"); // File Header if (dataSize < sizeof(VBO::header_t)) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto header = reinterpret_cast(meshData); if (!header->numVertices || !header->numIndices) - throw std::exception("No vertices or indices found"); + throw std::runtime_error("No vertices or indices found"); uint64_t sizeInBytes = uint64_t(header->numVertices) * sizeof(VertexPositionNormalTexture); if (sizeInBytes > UINT32_MAX) - throw std::exception("VB too large"); + throw std::runtime_error("VB too large"); if (!(flags & ModelLoader_AllowLargeModels)) { if (sizeInBytes > uint64_t(D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("VB too large for DirectX 12"); + throw std::runtime_error("VB too large for DirectX 12"); } auto vertSize = static_cast(sizeInBytes); if (dataSize < (vertSize + sizeof(VBO::header_t))) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto verts = reinterpret_cast(meshData + sizeof(VBO::header_t)); sizeInBytes = uint64_t(header->numIndices) * sizeof(uint16_t); if (sizeInBytes > UINT32_MAX) - throw std::exception("IB too large"); + throw std::runtime_error("IB too large"); if (!(flags & ModelLoader_AllowLargeModels)) { if (sizeInBytes > uint64_t(D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("IB too large for DirectX 12"); + throw std::runtime_error("IB too large for DirectX 12"); } auto indexSize = static_cast(sizeInBytes); if (dataSize < (sizeof(VBO::header_t) + vertSize + indexSize)) - throw std::exception("End of file"); + throw std::runtime_error("End of file"); auto indices = reinterpret_cast(meshData + sizeof(VBO::header_t) + vertSize); // Create vertex buffer @@ -144,7 +144,7 @@ std::unique_ptr DirectX::Model::CreateFromVBO( { DebugTrace("ERROR: CreateFromVBO failed (%08X) loading '%ls'\n", static_cast(hr), szFileName); - throw std::exception("CreateFromVBO"); + throw std::runtime_error("CreateFromVBO"); } auto model = CreateFromVBO(device, data.get(), dataSize, flags); diff --git a/Kits/DirectXTK12/Src/Mouse.cpp b/Kits/DirectXTK12/Src/Mouse.cpp index 96f59743..89f712ae 100644 --- a/Kits/DirectXTK12/Src/Mouse.cpp +++ b/Kits/DirectXTK12/Src/Mouse.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: Mouse.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -67,7 +67,7 @@ class Mouse::Impl { if (s_mouse) { - throw std::exception("Mouse is a singleton"); + throw std::logic_error("Mouse is a singleton"); } s_mouse = this; @@ -86,7 +86,7 @@ class Mouse::Impl mScrollWheelValue.reset(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_MODIFY_STATE | SYNCHRONIZE)); if (!mScrollWheelValue) { - throw std::exception("CreateEventEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } } @@ -102,10 +102,9 @@ class Mouse::Impl { if (mGameInput) { - HRESULT hr = mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX); - if (FAILED(hr)) + if (!mGameInput->UnregisterCallback(mDeviceToken, UINT64_MAX)) { - DebugTrace("ERROR: GameInput::UnregisterCallback [mouse] failed (%08X)", static_cast(hr)); + DebugTrace("ERROR: GameInput::UnregisterCallback [mouse] failed"); } } @@ -122,7 +121,7 @@ class Mouse::Impl DWORD result = WaitForSingleObjectEx(mScrollWheelValue.get(), 0, FALSE); if (result == WAIT_FAILED) - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); if (result == WAIT_OBJECT_0) { @@ -206,7 +205,7 @@ class Mouse::Impl CURSORINFO info = { sizeof(CURSORINFO), 0, nullptr, {} }; if (!GetCursorInfo(&info)) { - throw std::exception("GetCursorInfo"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "GetCursorInfo"); } bool isvisible = (info.flags & CURSOR_SHOWING) != 0; @@ -271,7 +270,7 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) DWORD result = WaitForSingleObjectEx(pImpl->mScrollWheelValue.get(), 0, FALSE); if (result == WAIT_FAILED) - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); if (result == WAIT_OBJECT_0) { @@ -446,7 +445,7 @@ class Mouse::Impl { if (s_mouse) { - throw std::exception("Mouse is a singleton"); + throw std::logic_error("Mouse is a singleton"); } s_mouse = this; @@ -460,7 +459,7 @@ class Mouse::Impl || !mAbsoluteMode || !mRelativeMode) { - throw std::exception("CreateEventEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } } @@ -482,7 +481,7 @@ class Mouse::Impl DWORD result = WaitForSingleObjectEx(mScrollWheelValue.get(), 0, FALSE); if (result == WAIT_FAILED) - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); if (result == WAIT_OBJECT_0) { @@ -494,7 +493,7 @@ class Mouse::Impl result = WaitForSingleObjectEx(mRelativeRead.get(), 0, FALSE); if (result == WAIT_FAILED) - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); if (result == WAIT_OBJECT_0) { @@ -529,7 +528,7 @@ class Mouse::Impl tme.dwHoverTime = 1; if (!TrackMouseEvent(&tme)) { - throw std::exception("TrackMouseEvent"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "TrackMouseEvent"); } } @@ -558,7 +557,7 @@ class Mouse::Impl CURSORINFO info = { sizeof(CURSORINFO), 0, nullptr, {} }; if (!GetCursorInfo(&info)) { - throw std::exception("GetCursorInfo"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "GetCursorInfo"); } bool isvisible = (info.flags & CURSOR_SHOWING) != 0; @@ -582,7 +581,7 @@ class Mouse::Impl Rid.hwndTarget = window; if (!RegisterRawInputDevices(&Rid, 1, sizeof(RAWINPUTDEVICE))) { - throw std::exception("RegisterRawInputDevices"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "RegisterRawInputDevices"); } mWindow = window; @@ -658,7 +657,7 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) return; HANDLE events[3] = { pImpl->mScrollWheelValue.get(), pImpl->mAbsoluteMode.get(), pImpl->mRelativeMode.get() }; - switch (WaitForMultipleObjectsEx(_countof(events), events, FALSE, 0, FALSE)) + switch (WaitForMultipleObjectsEx(static_cast(std::size(events)), events, FALSE, 0, FALSE)) { default: case WAIT_TIMEOUT: @@ -706,7 +705,7 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) break; case WAIT_FAILED: - throw std::exception("WaitForMultipleObjectsEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForMultipleObjectsEx"); } switch (message) @@ -744,7 +743,7 @@ void Mouse::ProcessMessage(UINT message, WPARAM wParam, LPARAM lParam) UINT resultData = GetRawInputData(reinterpret_cast(lParam), RID_INPUT, &raw, &rawSize, sizeof(RAWINPUTHEADER)); if (resultData == UINT(-1)) { - throw std::exception("GetRawInputData"); + throw std::runtime_error("GetRawInputData"); } if (raw.header.dwType == RIM_TYPEMOUSE) @@ -875,7 +874,7 @@ class Mouse::Impl { if (s_mouse) { - throw std::exception("Mouse is a singleton"); + throw std::logic_error("Mouse is a singleton"); } s_mouse = this; @@ -960,7 +959,7 @@ class Mouse::Impl { if (s_mouse) { - throw std::exception("Mouse is a singleton"); + throw std::logic_error("Mouse is a singleton"); } s_mouse = this; @@ -970,7 +969,7 @@ class Mouse::Impl if (!mScrollWheelValue || !mRelativeRead) { - throw std::exception("CreateEventEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); } } @@ -987,7 +986,7 @@ class Mouse::Impl DWORD result = WaitForSingleObjectEx(mScrollWheelValue.get(), 0, FALSE); if (result == WAIT_FAILED) - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); if (result == WAIT_OBJECT_0) { @@ -999,7 +998,7 @@ class Mouse::Impl result = WaitForSingleObjectEx(mRelativeRead.get(), 0, FALSE); if (result == WAIT_FAILED) - throw std::exception("WaitForSingleObjectEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObjectEx"); if (result == WAIT_OBJECT_0) { @@ -1463,7 +1462,7 @@ void Mouse::SetVisible(bool visible) Mouse& Mouse::Get() { if (!Impl::s_mouse || !Impl::s_mouse->mOwner) - throw std::exception("Mouse is a singleton"); + throw std::logic_error("Mouse singleton not created"); return *Impl::s_mouse->mOwner; } diff --git a/Kits/DirectXTK12/Src/NormalMapEffect.cpp b/Kits/DirectXTK12/Src/NormalMapEffect.cpp index 3f70f918..6d44422c 100644 --- a/Kits/DirectXTK12/Src/NormalMapEffect.cpp +++ b/Kits/DirectXTK12/Src/NormalMapEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: NormalMapEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -241,10 +241,10 @@ NormalMapEffect::Impl::Impl( normal{}, sampler{} { - static_assert(_countof(EffectBase::VertexShaderIndices) == NormalMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == NormalMapEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == NormalMapEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == NormalMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == NormalMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == NormalMapEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == NormalMapEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == NormalMapEffectTraits::ShaderPermutationCount, "array/max mismatch"); lights.InitializeConstants(constants.specularColorAndPower, constants.lightDirection, constants.lightDiffuseColor, constants.lightSpecularColor); @@ -274,13 +274,13 @@ NormalMapEffect::Impl::Impl( CD3DX12_DESCRIPTOR_RANGE textureSRV3(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 2); rootParameters[RootParameterIndex::TextureSpecularSRV].InitAsDescriptorTable(1, &textureSRV3, D3D12_SHADER_VISIBILITY_PIXEL); - rsigDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 0, nullptr, rootSignatureFlags); mRootSignature = GetRootSignature(1, rsigDesc); } else { - rsigDesc.Init(_countof(rootParameters) - 1, rootParameters, 0, nullptr, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters) - 1), rootParameters, 0, nullptr, rootSignatureFlags); mRootSignature = GetRootSignature(0, rsigDesc); } @@ -361,7 +361,7 @@ void NormalMapEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) if (!texture.ptr || !sampler.ptr || !normal.ptr) { DebugTrace("ERROR: Missing texture(s) or sampler for NormalMapEffect (texture %llu, normal %llu, sampler %llu)\n", texture.ptr, normal.ptr, sampler.ptr); - throw std::exception("NormalMapEffect"); + throw std::runtime_error("NormalMapEffect"); } // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. @@ -374,7 +374,7 @@ void NormalMapEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) if (!specular.ptr) { DebugTrace("ERROR: Missing specular texure NormalMapEffect (texture %llu)\n", specular.ptr); - throw std::exception("NormalMapEffect"); + throw std::runtime_error("NormalMapEffect"); } commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSpecularSRV, specular); } diff --git a/Kits/DirectXTK12/Src/PBREffect.cpp b/Kits/DirectXTK12/Src/PBREffect.cpp index 9fe7910e..45bb770a 100644 --- a/Kits/DirectXTK12/Src/PBREffect.cpp +++ b/Kits/DirectXTK12/Src/PBREffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: PBREffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -205,10 +205,10 @@ PBREffect::Impl::Impl(_In_ ID3D12Device* device, descriptors{}, lightColor{} { - static_assert(_countof(EffectBase::VertexShaderIndices) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == PBREffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == PBREffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == PBREffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == PBREffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == PBREffectTraits::ShaderPermutationCount, "array/max mismatch"); // Lighting static const XMVECTORF32 defaultLightDirection = { { { 0, -1, 0, 0 } } }; @@ -230,7 +230,7 @@ PBREffect::Impl::Impl(_In_ ID3D12Device* device, if (effectFlags & (EffectFlags::Emissive | EffectFlags::Velocity)) { DebugTrace("ERROR: PBREffect does not support emissive or velocity without surface textures\n"); - throw std::invalid_argument("PBREffect"); + throw std::invalid_argument("Specified effects flags requires Texture"); } } @@ -263,12 +263,12 @@ PBREffect::Impl::Impl(_In_ ID3D12Device* device, CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 1) }; - for (size_t i = 0; i < _countof(textureSRV); i++) + for (size_t i = 0; i < std::size(textureSRV); i++) { rootParameters[i].InitAsDescriptorTable(1, &textureSRV[i]); } - for (size_t i = 0; i < _countof(textureSampler); i++) + for (size_t i = 0; i < std::size(textureSampler); i++) { rootParameters[i + SurfaceSampler].InitAsDescriptorTable(1, &textureSampler[i]); } @@ -276,7 +276,7 @@ PBREffect::Impl::Impl(_In_ ID3D12Device* device, rootParameters[ConstantBuffer].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_ALL); CD3DX12_ROOT_SIGNATURE_DESC rsigDesc; - rsigDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 0, nullptr, rootSignatureFlags); mRootSignature = GetRootSignature(0, rsigDesc); } @@ -286,12 +286,12 @@ PBREffect::Impl::Impl(_In_ ID3D12Device* device, if (effectFlags & EffectFlags::Fog) { DebugTrace("ERROR: PBEffect does not implement EffectFlags::Fog\n"); - throw std::invalid_argument("PBREffect"); + throw std::invalid_argument("Fog effect flag is invalid"); } else if (effectFlags & EffectFlags::VertexColor) { DebugTrace("ERROR: PBEffect does not implement EffectFlags::VertexColor\n"); - throw std::invalid_argument("PBREffect"); + throw std::invalid_argument("VertexColor effect flag is invalid"); } // Create pipeline state. @@ -392,13 +392,13 @@ void PBREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) if (!descriptors[RadianceTexture].ptr || !descriptors[RadianceSampler].ptr) { DebugTrace("ERROR: Missing radiance texture or sampler for PBREffect (texture %llu, sampler %llu)\n", descriptors[RadianceTexture].ptr, descriptors[RadianceSampler].ptr); - throw std::exception("PBREffect"); + throw std::runtime_error("PBREffect"); } if (!descriptors[IrradianceTexture].ptr) { DebugTrace("ERROR: Missing irradiance texture for PBREffect (texture %llu)\n", descriptors[IrradianceTexture].ptr); - throw std::exception("PBREffect"); + throw std::runtime_error("PBREffect"); } // Set the root parameters @@ -423,19 +423,19 @@ void PBREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) if (!descriptors[AlbedoTexture].ptr || !descriptors[SurfaceSampler].ptr) { DebugTrace("ERROR: Missing albedo texture or sampler for PBREffect (texture %llu, sampler %llu)\n", descriptors[AlbedoTexture].ptr, descriptors[SurfaceSampler].ptr); - throw std::exception("PBREffect"); + throw std::runtime_error("PBREffect"); } if (!descriptors[NormalTexture].ptr) { DebugTrace("ERROR: Missing normal map texture for PBREffect (texture %llu)\n", descriptors[NormalTexture].ptr); - throw std::exception("PBREffect"); + throw std::runtime_error("PBREffect"); } if (!descriptors[RMATexture].ptr) { DebugTrace("ERROR: Missing roughness/metalness texture for PBREffect (texture %llu)\n", descriptors[RMATexture].ptr); - throw std::exception("PBREffect"); + throw std::runtime_error("PBREffect"); } for (unsigned i = 0; i < ConstantBuffer; i++) @@ -452,7 +452,7 @@ void PBREffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) if (!descriptors[EmissiveTexture].ptr) { DebugTrace("ERROR: Missing emissive map texture for PBREffect (texture %llu)\n", descriptors[NormalTexture].ptr); - throw std::exception("PBREffect"); + throw std::runtime_error("PBREffect"); } commandList->SetGraphicsRootDescriptorTable(EmissiveTexture, descriptors[EmissiveTexture]); diff --git a/Kits/DirectXTK12/Src/PBREffectFactory.cpp b/Kits/DirectXTK12/Src/PBREffectFactory.cpp index 253f14bf..0160f41b 100644 --- a/Kits/DirectXTK12/Src/PBREffectFactory.cpp +++ b/Kits/DirectXTK12/Src/PBREffectFactory.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: PBREffectFactory.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -75,12 +75,12 @@ std::shared_ptr PBREffectFactory::Impl::CreateEffect( if (!mTextureDescriptors) { DebugTrace("ERROR: PBREffectFactory created without texture descriptor heap!\n"); - throw std::exception("PBREffectFactory"); + throw std::logic_error("PBREffectFactory"); } if (!mSamplerDescriptors) { DebugTrace("ERROR: PBREffectFactory created without sampler descriptor heap!\n"); - throw std::exception("PBREffectFactory"); + throw std::logic_error("PBREffectFactory"); } int albetoTextureIndex = (info.diffuseTextureIndex != -1) ? info.diffuseTextureIndex + textureDescriptorOffset : -1; @@ -167,20 +167,20 @@ PBREffectFactory::PBREffectFactory(_In_ ID3D12DescriptorHeap* textureDescriptors { if (!textureDescriptors) { - throw std::exception("Texture descriptor heap cannot be null if no device is provided. Use the alternative PBREffectFactory constructor instead."); + throw std::invalid_argument("Texture descriptor heap cannot be null if no device is provided. Use the alternative PBREffectFactory constructor instead."); } if (!samplerDescriptors) { - throw std::exception("Descriptor heap cannot be null if no device is provided. Use the alternative PBREffectFactory constructor instead."); + throw std::invalid_argument("Descriptor heap cannot be null if no device is provided. Use the alternative PBREffectFactory constructor instead."); } if (textureDescriptors->GetDesc().Type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { - throw std::exception("PBREffectFactory::CreateEffect requires a CBV_SRV_UAV descriptor heap for textureDescriptors."); + throw std::invalid_argument("PBREffectFactory::CreateEffect requires a CBV_SRV_UAV descriptor heap for textureDescriptors."); } if (samplerDescriptors->GetDesc().Type != D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) { - throw std::exception("PBREffectFactory::CreateEffect requires a SAMPLER descriptor heap for samplerDescriptors."); + throw std::invalid_argument("PBREffectFactory::CreateEffect requires a SAMPLER descriptor heap for samplerDescriptors."); } ComPtr device; diff --git a/Kits/DirectXTK12/Src/PlatformHelpers.h b/Kits/DirectXTK12/Src/PlatformHelpers.h index 10832255..401049b0 100644 --- a/Kits/DirectXTK12/Src/PlatformHelpers.h +++ b/Kits/DirectXTK12/Src/PlatformHelpers.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: PlatformHelpers.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -31,7 +31,7 @@ namespace DirectX public: com_exception(HRESULT hr) noexcept : result(hr) {} - const char* what() const override + const char* what() const noexcept override { static char s_str[64] = {}; sprintf_s(s_str, "Failure with HRESULT of %08X", static_cast(result)); @@ -70,7 +70,6 @@ namespace DirectX #endif } - // Helper smart-pointers #if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) || (defined(_XBOX_ONE) && defined(_TITLE)) || !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) struct virtual_deleter { void operator()(void* p) noexcept { if (p) VirtualFree(p, 0, MEM_RELEASE); } }; diff --git a/Kits/DirectXTK12/Src/PrimitiveBatch.cpp b/Kits/DirectXTK12/Src/PrimitiveBatch.cpp index 2a12efc6..695ed69b 100644 --- a/Kits/DirectXTK12/Src/PrimitiveBatch.cpp +++ b/Kits/DirectXTK12/Src/PrimitiveBatch.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: PrimitiveBatch.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -74,16 +74,16 @@ PrimitiveBatchBase::Impl::Impl(_In_ ID3D12Device* device, size_t maxIndices, siz mBaseVertex(0) { if (!maxVertices) - throw std::exception("maxVertices must be greater than 0"); + throw std::invalid_argument("maxVertices must be greater than 0"); if (vertexSize > D3D12_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES) - throw std::exception("Vertex size is too large for DirectX 12"); + throw std::invalid_argument("Vertex size is too large for DirectX 12"); if ((uint64_t(maxIndices) * sizeof(uint16_t)) > uint64_t(D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("IB too large for DirectX 12"); + throw std::invalid_argument("IB too large for DirectX 12"); if ((uint64_t(maxVertices) * uint64_t(vertexSize)) > uint64_t(D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024u * 1024u)) - throw std::exception("VB too large for DirectX 12"); + throw std::invalid_argument("VB too large for DirectX 12"); } @@ -92,7 +92,7 @@ PrimitiveBatchBase::Impl::Impl(_In_ ID3D12Device* device, size_t maxIndices, siz void PrimitiveBatchBase::Impl::Begin(_In_ ID3D12GraphicsCommandList* cmdList) { if (mInBeginEndPair) - throw std::exception("Cannot nest Begin calls"); + throw std::logic_error("Cannot nest Begin calls"); mCommandList = cmdList; mInBeginEndPair = true; @@ -103,7 +103,7 @@ void PrimitiveBatchBase::Impl::Begin(_In_ ID3D12GraphicsCommandList* cmdList) void PrimitiveBatchBase::Impl::End() { if (!mInBeginEndPair) - throw std::exception("Begin must be called before End"); + throw std::logic_error("Begin must be called before End"); FlushBatch(); @@ -141,16 +141,16 @@ _Use_decl_annotations_ void PrimitiveBatchBase::Impl::Draw(D3D_PRIMITIVE_TOPOLOGY topology, bool isIndexed, uint16_t const* indices, size_t indexCount, size_t vertexCount, void** pMappedVertices) { if (isIndexed && !indices) - throw std::exception("Indices cannot be null"); + throw std::invalid_argument("Indices cannot be null"); if (indexCount >= mMaxIndices) - throw std::exception("Too many indices"); + throw std::invalid_argument("Too many indices"); if (vertexCount >= mMaxVertices) - throw std::exception("Too many vertices"); + throw std::invalid_argument("Too many vertices"); if (!mInBeginEndPair) - throw std::exception("Begin must be called before Draw"); + throw std::logic_error("Begin must be called before Draw"); assert(pMappedVertices != nullptr); diff --git a/Kits/DirectXTK12/Src/ResourceUploadBatch.cpp b/Kits/DirectXTK12/Src/ResourceUploadBatch.cpp index 4425da5a..1638ed4b 100644 --- a/Kits/DirectXTK12/Src/ResourceUploadBatch.cpp +++ b/Kits/DirectXTK12/Src/ResourceUploadBatch.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: ResourceUploadBatch.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -252,7 +252,7 @@ namespace rootParameters[RootParameterIndex::TargetTexture].InitAsDescriptorTable(1, &targetDescriptorRange); CD3DX12_ROOT_SIGNATURE_DESC rsigDesc; - rsigDesc.Init(_countof(rootParameters), rootParameters, 1, &sampler, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 1, &sampler, rootSignatureFlags); ComPtr rootSignature; ThrowIfFailed(CreateRootSignature(device, &rsigDesc, rootSignature.ReleaseAndGetAddressOf())); @@ -310,7 +310,7 @@ class ResourceUploadBatch::Impl void Begin(D3D12_COMMAND_LIST_TYPE commandType) { if (mInBeginEndBlock) - throw std::exception("Can't Begin: already in a Begin-End block."); + throw std::logic_error("Can't Begin: already in a Begin-End block."); switch (commandType) { @@ -321,7 +321,7 @@ class ResourceUploadBatch::Impl default: DebugTrace("ResourceUploadBatch only supports Direct, Compute, and Copy command queues\n"); - throw std::invalid_argument("ResourceUploadBatch"); + throw std::invalid_argument("commandType parameter is invalid"); } ThrowIfFailed(mDevice->CreateCommandAllocator(commandType, IID_GRAPHICS_PPV_ARGS(mCmdAlloc.ReleaseAndGetAddressOf()))); @@ -345,7 +345,7 @@ class ResourceUploadBatch::Impl uint32_t numSubresources) { if (!mInBeginEndBlock) - throw std::exception("Can't call Upload on a closed ResourceUploadBatch."); + throw std::logic_error("Can't call Upload on a closed ResourceUploadBatch."); UINT64 uploadSize = GetRequiredIntermediateSize( resource, @@ -386,7 +386,7 @@ class ResourceUploadBatch::Impl const SharedGraphicsResource& buffer) { if (!mInBeginEndBlock) - throw std::exception("Can't call Upload on a closed ResourceUploadBatch."); + throw std::logic_error("Can't call Upload on a closed ResourceUploadBatch."); // Submit resource copy to command list mList->CopyBufferRegion(resource, 0, buffer.Resource(), buffer.ResourceOffset(), buffer.Size()); @@ -405,12 +405,12 @@ class ResourceUploadBatch::Impl } if (!mInBeginEndBlock) - throw std::exception("Can't call GenerateMips on a closed ResourceUploadBatch."); + throw std::logic_error("Can't call GenerateMips on a closed ResourceUploadBatch."); if (mCommandType == D3D12_COMMAND_LIST_TYPE_COPY) { DebugTrace("ERROR: GenerateMips cannot operate on a copy queue\n"); - throw std::exception("GenerateMips cannot operate on a copy queue"); + throw std::runtime_error("GenerateMips cannot operate on a copy queue"); } const auto desc = resource->GetDesc(); @@ -422,22 +422,22 @@ class ResourceUploadBatch::Impl } if (desc.MipLevels == 0) { - throw std::exception("GenerateMips: texture has no mips"); + throw std::runtime_error("GenerateMips: texture has no mips"); } if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { - throw std::exception("GenerateMips only supports Texture2D resources"); + throw std::runtime_error("GenerateMips only supports Texture2D resources"); } if (desc.DepthOrArraySize != 1) { - throw std::exception("GenerateMips only supports 2D textures of array size 1"); + throw std::runtime_error("GenerateMips only supports 2D textures of array size 1"); } bool uavCompat = FormatIsUAVCompatible(mDevice.Get(), mTypedUAVLoadAdditionalFormats, desc.Format); if (!uavCompat && !FormatIsSRGB(desc.Format) && !FormatIsBGR(desc.Format)) { - throw std::exception("GenerateMips doesn't support this texture format on this device"); + throw std::runtime_error("GenerateMips doesn't support this texture format on this device"); } // Ensure that we have valid generate mips data @@ -454,14 +454,14 @@ class ResourceUploadBatch::Impl } else if (!mTypedUAVLoadAdditionalFormats) { - throw std::exception("GenerateMips needs TypedUAVLoadAdditionalFormats device support for sRGB/BGR"); + throw std::runtime_error("GenerateMips needs TypedUAVLoadAdditionalFormats device support for sRGB/BGR"); } else if (FormatIsBGR(desc.Format)) { #if !defined(_GAMING_XBOX) && !(defined(_XBOX_ONE) && defined(_TITLE)) if (!mStandardSwizzle64KBSupported) { - throw std::exception("GenerateMips needs StandardSwizzle64KBSupported device support for BGR"); + throw std::runtime_error("GenerateMips needs StandardSwizzle64KBSupported device support for BGR"); } #endif @@ -480,7 +480,7 @@ class ResourceUploadBatch::Impl _In_ D3D12_RESOURCE_STATES stateAfter) { if (!mInBeginEndBlock) - throw std::exception("Can't call Upload on a closed ResourceUploadBatch."); + throw std::logic_error("Can't call Upload on a closed ResourceUploadBatch."); if (mCommandType == D3D12_COMMAND_LIST_TYPE_COPY) { @@ -523,7 +523,7 @@ class ResourceUploadBatch::Impl _In_ ID3D12CommandQueue* commandQueue) { if (!mInBeginEndBlock) - throw std::exception("ResourceUploadBatch already closed."); + throw std::logic_error("ResourceUploadBatch already closed."); ThrowIfFailed(mList->Close()); @@ -538,7 +538,7 @@ class ResourceUploadBatch::Impl HANDLE gpuCompletedEvent = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS); if (!gpuCompletedEvent) - throw std::exception("CreateEventEx"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "CreateEventEx"); ThrowIfFailed(commandQueue->Signal(fence.Get(), 1ULL)); ThrowIfFailed(fence->SetEventOnCompletion(1ULL, gpuCompletedEvent)); @@ -561,11 +561,11 @@ class ResourceUploadBatch::Impl { if (wr == WAIT_FAILED) { - ThrowIfFailed(HRESULT_FROM_WIN32(GetLastError())); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "WaitForSingleObject"); } else { - throw std::exception("WaitForSingleObject"); + throw std::runtime_error("WaitForSingleObject"); } } @@ -994,7 +994,7 @@ class ResourceUploadBatch::Impl std::vector> TrackedObjects; std::vector TrackedMemoryResources; ComPtr CommandList; - ComPtr Fence; + ComPtr Fence; HANDLE GpuCompleteEvent; UploadBatch() noexcept : GpuCompleteEvent(nullptr) {} diff --git a/Kits/DirectXTK12/Src/SDKMesh.h b/Kits/DirectXTK12/Src/SDKMesh.h index 54c11c89..17041022 100644 --- a/Kits/DirectXTK12/Src/SDKMesh.h +++ b/Kits/DirectXTK12/Src/SDKMesh.h @@ -6,7 +6,7 @@ // // http://go.microsoft.com/fwlink/?LinkId=226208 // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -150,7 +150,7 @@ namespace DXUT enum FRAME_TRANSFORM_TYPE { FTT_RELATIVE = 0, - FTT_ABSOLUTE, //This is not currently used but is here to support absolute transformations in the future + FTT_ABSOLUTE, // This is not currently used but is here to support absolute transformations in the future }; //-------------------------------------------------------------------------------------- @@ -244,7 +244,7 @@ namespace DXUT uint32_t ChildFrame; uint32_t SiblingFrame; DirectX::XMFLOAT4X4 Matrix; - uint32_t AnimationDataIndex; //Used to index which set of keyframes transforms this frame + uint32_t AnimationDataIndex; //Used to index which set of keyframes transforms this frame }; struct SDKMESH_MATERIAL diff --git a/Kits/DirectXTK12/Src/ScreenGrab.cpp b/Kits/DirectXTK12/Src/ScreenGrab.cpp index 3037b70f..b9782326 100644 --- a/Kits/DirectXTK12/Src/ScreenGrab.cpp +++ b/Kits/DirectXTK12/Src/ScreenGrab.cpp @@ -8,7 +8,7 @@ // 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. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -67,12 +67,8 @@ namespace return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); D3D12_HEAP_PROPERTIES sourceHeapProperties; - D3D12_HEAP_FLAGS sourceHeapFlags; - HRESULT hr = pSource->GetHeapProperties(&sourceHeapProperties, &sourceHeapFlags); - if (FAILED(hr)) - return hr; - - if (sourceHeapProperties.Type == D3D12_HEAP_TYPE_READBACK) + HRESULT hr = pSource->GetHeapProperties(&sourceHeapProperties, nullptr); + if (SUCCEEDED(hr) && sourceHeapProperties.Type == D3D12_HEAP_TYPE_READBACK) { // Handle case where the source is already a staging texture we can use directly pStaging = pSource; @@ -127,6 +123,7 @@ namespace auto descCopy = desc; descCopy.SampleDesc.Count = 1; descCopy.SampleDesc.Quality = 0; + descCopy.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; ComPtr pTemp; hr = device->CreateCommittedResource( @@ -298,30 +295,30 @@ HRESULT DirectX::SaveDDSTextureToFile( 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; - case DXGI_FORMAT_B8G8R8X8_UNORM: memcpy_s(&header->ddspf, sizeof(header->ddspf), &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_YUY2: memcpy_s(&header->ddspf, sizeof(header->ddspf), &DDSPF_YUY2, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_B4G4R4A4_UNORM: memcpy_s(&header->ddspf, sizeof(header->ddspf), &DDSPF_A4R4G4B4, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8B8A8_UNORM: memcpy(&header->ddspf, &DDSPF_A8B8G8R8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R16G16_UNORM: memcpy(&header->ddspf, &DDSPF_G16R16, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8_UNORM: memcpy(&header->ddspf, &DDSPF_A8L8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R16_UNORM: memcpy(&header->ddspf, &DDSPF_L16, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8_UNORM: memcpy(&header->ddspf, &DDSPF_L8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_A8_UNORM: memcpy(&header->ddspf, &DDSPF_A8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8_B8G8_UNORM: memcpy(&header->ddspf, &DDSPF_R8G8_B8G8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_G8R8_G8B8_UNORM: memcpy(&header->ddspf, &DDSPF_G8R8_G8B8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC1_UNORM: memcpy(&header->ddspf, &DDSPF_DXT1, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC2_UNORM: memcpy(&header->ddspf, &DDSPF_DXT3, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC3_UNORM: memcpy(&header->ddspf, &DDSPF_DXT5, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC4_UNORM: memcpy(&header->ddspf, &DDSPF_BC4_UNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC4_SNORM: memcpy(&header->ddspf, &DDSPF_BC4_SNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC5_UNORM: memcpy(&header->ddspf, &DDSPF_BC5_UNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC5_SNORM: memcpy(&header->ddspf, &DDSPF_BC5_SNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B5G6R5_UNORM: memcpy(&header->ddspf, &DDSPF_R5G6B5, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B5G5R5A1_UNORM: memcpy(&header->ddspf, &DDSPF_A1R5G5B5, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8_SNORM: memcpy(&header->ddspf, &DDSPF_V8U8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8B8A8_SNORM: memcpy(&header->ddspf, &DDSPF_Q8W8V8U8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R16G16_SNORM: memcpy(&header->ddspf, &DDSPF_V16U16, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B8G8R8A8_UNORM: memcpy(&header->ddspf, &DDSPF_A8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B8G8R8X8_UNORM: memcpy(&header->ddspf, &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_YUY2: memcpy(&header->ddspf, &DDSPF_YUY2, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B4G4R4A4_UNORM: memcpy(&header->ddspf, &DDSPF_A4R4G4B4, sizeof(DDS_PIXELFORMAT)); break; // 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 @@ -341,7 +338,7 @@ HRESULT DirectX::SaveDDSTextureToFile( return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); default: - memcpy_s(&header->ddspf, sizeof(header->ddspf), &DDSPF_DX10, sizeof(DDS_PIXELFORMAT)); + memcpy(&header->ddspf, &DDSPF_DX10, sizeof(DDS_PIXELFORMAT)); headerSize += sizeof(DDS_HEADER_DXT10); extHeader = reinterpret_cast(fileHeader + sizeof(uint32_t) + sizeof(DDS_HEADER)); @@ -401,7 +398,7 @@ HRESULT DirectX::SaveDDSTextureToFile( size_t msize = std::min(rowPitch, size_t(dstRowPitch)); for (size_t h = 0; h < rowCount; ++h) { - memcpy_s(dptr, rowPitch, sptr, msize); + memcpy(dptr, sptr, msize); sptr += dstRowPitch; dptr += rowPitch; } diff --git a/Kits/DirectXTK12/Src/Shaders/AlphaTestEffect.fx b/Kits/DirectXTK12/Src/Shaders/AlphaTestEffect.fx index 40a8dcf6..e031173d 100644 --- a/Kits/DirectXTK12/Src/Shaders/AlphaTestEffect.fx +++ b/Kits/DirectXTK12/Src/Shaders/AlphaTestEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/Shaders/BasicEffect.fx b/Kits/DirectXTK12/Src/Shaders/BasicEffect.fx index 7deb85e8..df412896 100644 --- a/Kits/DirectXTK12/Src/Shaders/BasicEffect.fx +++ b/Kits/DirectXTK12/Src/Shaders/BasicEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/Shaders/Common.fxh b/Kits/DirectXTK12/Src/Shaders/Common.fxh index 0e71229a..d997d4ed 100644 --- a/Kits/DirectXTK12/Src/Shaders/Common.fxh +++ b/Kits/DirectXTK12/Src/Shaders/Common.fxh @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTK12/Src/Shaders/CompileShaders.cmd b/Kits/DirectXTK12/Src/Shaders/CompileShaders.cmd index 79a2ab84..ffa32d98 100644 --- a/Kits/DirectXTK12/Src/Shaders/CompileShaders.cmd +++ b/Kits/DirectXTK12/Src/Shaders/CompileShaders.cmd @@ -1,5 +1,5 @@ @echo off -rem Copyright (c) Microsoft Corporation. All rights reserved. +rem Copyright (c) Microsoft Corporation. rem Licensed under the MIT License. setlocal diff --git a/Kits/DirectXTK12/Src/Shaders/DebugEffect.fx b/Kits/DirectXTK12/Src/Shaders/DebugEffect.fx index c9bf9999..b7337d75 100644 --- a/Kits/DirectXTK12/Src/Shaders/DebugEffect.fx +++ b/Kits/DirectXTK12/Src/Shaders/DebugEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK12/Src/Shaders/DualTextureEffect.fx b/Kits/DirectXTK12/Src/Shaders/DualTextureEffect.fx index a760f3b7..bb57959d 100644 --- a/Kits/DirectXTK12/Src/Shaders/DualTextureEffect.fx +++ b/Kits/DirectXTK12/Src/Shaders/DualTextureEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/Shaders/EnvironmentMapEffect.fx b/Kits/DirectXTK12/Src/Shaders/EnvironmentMapEffect.fx index 74941e71..8818bab3 100644 --- a/Kits/DirectXTK12/Src/Shaders/EnvironmentMapEffect.fx +++ b/Kits/DirectXTK12/Src/Shaders/EnvironmentMapEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/Shaders/GenerateMips.hlsl b/Kits/DirectXTK12/Src/Shaders/GenerateMips.hlsl index 1c1af760..a34aae1e 100644 --- a/Kits/DirectXTK12/Src/Shaders/GenerateMips.hlsl +++ b/Kits/DirectXTK12/Src/Shaders/GenerateMips.hlsl @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/Shaders/Lighting.fxh b/Kits/DirectXTK12/Src/Shaders/Lighting.fxh index a17187d1..87867354 100644 --- a/Kits/DirectXTK12/Src/Shaders/Lighting.fxh +++ b/Kits/DirectXTK12/Src/Shaders/Lighting.fxh @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTK12/Src/Shaders/NormalMapEffect.fx b/Kits/DirectXTK12/Src/Shaders/NormalMapEffect.fx index a37e9c33..abbb7da8 100644 --- a/Kits/DirectXTK12/Src/Shaders/NormalMapEffect.fx +++ b/Kits/DirectXTK12/Src/Shaders/NormalMapEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/Shaders/PBRCommon.fxh b/Kits/DirectXTK12/Src/Shaders/PBRCommon.fxh index d7aad5a0..2481f1b2 100644 --- a/Kits/DirectXTK12/Src/Shaders/PBRCommon.fxh +++ b/Kits/DirectXTK12/Src/Shaders/PBRCommon.fxh @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTK12/Src/Shaders/PBREffect.fx b/Kits/DirectXTK12/Src/Shaders/PBREffect.fx index 55e4fa7a..8668f707 100644 --- a/Kits/DirectXTK12/Src/Shaders/PBREffect.fx +++ b/Kits/DirectXTK12/Src/Shaders/PBREffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/Shaders/PostProcess.fx b/Kits/DirectXTK12/Src/Shaders/PostProcess.fx index 235aaf72..ed0eaed2 100644 --- a/Kits/DirectXTK12/Src/Shaders/PostProcess.fx +++ b/Kits/DirectXTK12/Src/Shaders/PostProcess.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/Shaders/RootSig.fxh b/Kits/DirectXTK12/Src/Shaders/RootSig.fxh index 2ddf03ce..af711d81 100644 --- a/Kits/DirectXTK12/Src/Shaders/RootSig.fxh +++ b/Kits/DirectXTK12/Src/Shaders/RootSig.fxh @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/Shaders/SkinnedEffect.fx b/Kits/DirectXTK12/Src/Shaders/SkinnedEffect.fx index 366a123e..92e93a7a 100644 --- a/Kits/DirectXTK12/Src/Shaders/SkinnedEffect.fx +++ b/Kits/DirectXTK12/Src/Shaders/SkinnedEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/Shaders/SpriteEffect.fx b/Kits/DirectXTK12/Src/Shaders/SpriteEffect.fx index 8de0aa8f..80067ba0 100644 --- a/Kits/DirectXTK12/Src/Shaders/SpriteEffect.fx +++ b/Kits/DirectXTK12/Src/Shaders/SpriteEffect.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/Shaders/Structures.fxh b/Kits/DirectXTK12/Src/Shaders/Structures.fxh index 34e5e723..6624d17b 100644 --- a/Kits/DirectXTK12/Src/Shaders/Structures.fxh +++ b/Kits/DirectXTK12/Src/Shaders/Structures.fxh @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTK12/Src/Shaders/ToneMap.fx b/Kits/DirectXTK12/Src/Shaders/ToneMap.fx index 30265035..017e0e9b 100644 --- a/Kits/DirectXTK12/Src/Shaders/ToneMap.fx +++ b/Kits/DirectXTK12/Src/Shaders/ToneMap.fx @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/Shaders/Utilities.fxh b/Kits/DirectXTK12/Src/Shaders/Utilities.fxh index 49ea06ce..1c731546 100644 --- a/Kits/DirectXTK12/Src/Shaders/Utilities.fxh +++ b/Kits/DirectXTK12/Src/Shaders/Utilities.fxh @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTK12/Src/SharedResourcePool.h b/Kits/DirectXTK12/Src/SharedResourcePool.h index 4848c131..92ec2f13 100644 --- a/Kits/DirectXTK12/Src/SharedResourcePool.h +++ b/Kits/DirectXTK12/Src/SharedResourcePool.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SharedResourcePool.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK12/Src/SimpleMath.cpp b/Kits/DirectXTK12/Src/SimpleMath.cpp index 76e03cbc..3b3cfb82 100644 --- a/Kits/DirectXTK12/Src/SimpleMath.cpp +++ b/Kits/DirectXTK12/Src/SimpleMath.cpp @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------------- // SimpleMath.cpp -- Simplified C++ Math wrapper for DirectXMath // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 @@ -81,6 +81,7 @@ static_assert(offsetof(DirectX::SimpleMath::Viewport, minDepth) == offsetof(D3D1 static_assert(offsetof(DirectX::SimpleMath::Viewport, maxDepth) == offsetof(D3D12_VIEWPORT, MaxDepth), "Layout mismatch"); #endif +#if defined(__dxgi1_2_h__) || defined(__d3d11_x_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__) RECT DirectX::SimpleMath::Viewport::ComputeDisplayArea(DXGI_SCALING scaling, UINT backBufferWidth, UINT backBufferHeight, int outputWidth, int outputHeight) noexcept { RECT rct = {}; @@ -140,6 +141,7 @@ RECT DirectX::SimpleMath::Viewport::ComputeDisplayArea(DXGI_SCALING scaling, UIN return rct; } +#endif RECT DirectX::SimpleMath::Viewport::ComputeTitleSafeArea(UINT backBufferWidth, UINT backBufferHeight) noexcept { diff --git a/Kits/DirectXTK12/Src/SkinnedEffect.cpp b/Kits/DirectXTK12/Src/SkinnedEffect.cpp index 2d9e5bac..679395d8 100644 --- a/Kits/DirectXTK12/Src/SkinnedEffect.cpp +++ b/Kits/DirectXTK12/Src/SkinnedEffect.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SkinnedEffect.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -187,10 +187,10 @@ SkinnedEffect::Impl::Impl( texture{}, sampler{} { - static_assert(_countof(EffectBase::VertexShaderIndices) == SkinnedEffectTraits::ShaderPermutationCount, "array/max mismatch"); - static_assert(_countof(EffectBase::VertexShaderBytecode) == SkinnedEffectTraits::VertexShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderBytecode) == SkinnedEffectTraits::PixelShaderCount, "array/max mismatch"); - static_assert(_countof(EffectBase::PixelShaderIndices) == SkinnedEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderIndices)) == SkinnedEffectTraits::ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::VertexShaderBytecode)) == SkinnedEffectTraits::VertexShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderBytecode)) == SkinnedEffectTraits::PixelShaderCount, "array/max mismatch"); + static_assert(static_cast(std::size(EffectBase::PixelShaderIndices)) == SkinnedEffectTraits::ShaderPermutationCount, "array/max mismatch"); lights.InitializeConstants(constants.specularColorAndPower, constants.lightDirection, constants.lightDiffuseColor, constants.lightSpecularColor); @@ -218,7 +218,7 @@ SkinnedEffect::Impl::Impl( rootParameters[RootParameterIndex::ConstantBuffer].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_ALL); CD3DX12_ROOT_SIGNATURE_DESC rsigDesc = {}; - rsigDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 0, nullptr, rootSignatureFlags); mRootSignature = GetRootSignature(0, rsigDesc); } @@ -230,7 +230,7 @@ SkinnedEffect::Impl::Impl( if (effectFlags & EffectFlags::VertexColor) { DebugTrace("ERROR: SkinnedEffect does not implement EffectFlags::VertexColor\n"); - throw std::invalid_argument("SkinnedEffect"); + throw std::invalid_argument("VertexColor effect flag is invalid"); } // Create pipeline state. @@ -301,7 +301,7 @@ void SkinnedEffect::Impl::Apply(_In_ ID3D12GraphicsCommandList* commandList) if (!texture.ptr || !sampler.ptr) { DebugTrace("ERROR: Missing texture or sampler for SkinnedEffect (texture %llu, sampler %llu)\n", texture.ptr, sampler.ptr); - throw std::exception("SkinnedEffect"); + throw std::runtime_error("SkinnedEffect"); } // **NOTE** If D3D asserts or crashes here, you probably need to call commandList->SetDescriptorHeaps() with the required descriptor heaps. @@ -532,7 +532,7 @@ void SkinnedEffect::SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_ void SkinnedEffect::SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) { if (count > MaxBones) - throw std::out_of_range("count parameter out of range"); + throw std::invalid_argument("count parameter exceeds MaxBones"); auto boneConstant = pImpl->constants.bones; diff --git a/Kits/DirectXTK12/Src/SpriteBatch.cpp b/Kits/DirectXTK12/Src/SpriteBatch.cpp index f702fad4..de516770 100644 --- a/Kits/DirectXTK12/Src/SpriteBatch.cpp +++ b/Kits/DirectXTK12/Src/SpriteBatch.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SpriteBatch.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -70,7 +70,7 @@ namespace } // Internal SpriteBatch implementation class. -__declspec(align(16)) class SpriteBatch::Impl : public AlignedNew +XM_ALIGNED_STRUCT(16) SpriteBatch::Impl : public AlignedNew { public: Impl(_In_ ID3D12Device* device, @@ -94,7 +94,7 @@ __declspec(align(16)) class SpriteBatch::Impl : public AlignedNew + XM_ALIGNED_STRUCT(16) SpriteInfo : public AlignedNew { XMFLOAT4A source; XMFLOAT4A destination; @@ -200,7 +200,7 @@ __declspec(align(16)) class SpriteBatch::Impl : public AlignedNew indexBuffer; D3D12_INDEX_BUFFER_VIEW indexBufferView; ComPtr rootSignatureStatic; - ComPtr rootSignatureHeap; + ComPtr rootSignatureHeap; ID3D12Device* mDevice; private: @@ -367,7 +367,7 @@ void SpriteBatch::Impl::DeviceResources::CreateRootSignatures(_In_ ID3D12Device* rootParameters[RootParameterIndex::ConstantBuffer].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_ALL); CD3DX12_ROOT_SIGNATURE_DESC rsigDesc; - rsigDesc.Init(_countof(rootParameters), rootParameters, 1, &sampler, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 1, &sampler, rootSignatureFlags); ThrowIfFailed(::CreateRootSignature(device, &rsigDesc, rootSignatureStatic.ReleaseAndGetAddressOf())); @@ -383,7 +383,7 @@ void SpriteBatch::Impl::DeviceResources::CreateRootSignatures(_In_ ID3D12Device* rootParameters[RootParameterIndex::TextureSampler].InitAsDescriptorTable(1, &textureSampler, D3D12_SHADER_VISIBILITY_PIXEL); CD3DX12_ROOT_SIGNATURE_DESC rsigDesc; - rsigDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 0, nullptr, rootSignatureFlags); ThrowIfFailed(::CreateRootSignature(device, &rsigDesc, rootSignatureHeap.ReleaseAndGetAddressOf())); @@ -445,7 +445,7 @@ SpriteBatch::Impl::Impl(ID3D12Device* device, ResourceUploadBatch& upload, const d3dDesc.DSVFormat = psoDesc.renderTargetState.dsvFormat; d3dDesc.NodeMask = psoDesc.renderTargetState.nodeMask; d3dDesc.NumRenderTargets = psoDesc.renderTargetState.numRenderTargets; - memcpy_s(d3dDesc.RTVFormats, sizeof(d3dDesc.RTVFormats), psoDesc.renderTargetState.rtvFormats, sizeof(DXGI_FORMAT) * D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT); + memcpy(d3dDesc.RTVFormats, psoDesc.renderTargetState.rtvFormats, sizeof(DXGI_FORMAT) * D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT); d3dDesc.SampleDesc = psoDesc.renderTargetState.sampleDesc; d3dDesc.SampleMask = psoDesc.renderTargetState.sampleMask; d3dDesc.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; @@ -502,7 +502,7 @@ void XM_CALLCONV SpriteBatch::Impl::Begin( if (mInBeginEndPair) { DebugTrace("ERROR: Cannot nest Begin calls on a single SpriteBatch\n"); - throw std::exception("SpriteBatch::Begin"); + throw std::logic_error("SpriteBatch::Begin"); } mSortMode = sortMode; @@ -524,7 +524,7 @@ void SpriteBatch::Impl::End() if (!mInBeginEndPair) { DebugTrace("ERROR: Begin must be called before End\n"); - throw std::exception("SpriteBatch::End"); + throw std::logic_error("SpriteBatch::End"); } if (mSortMode != SpriteSortMode_Immediate) @@ -556,11 +556,11 @@ void XM_CALLCONV SpriteBatch::Impl::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, if (!mInBeginEndPair) { DebugTrace("ERROR: Begin must be called before Draw\n"); - throw std::exception("SpriteBatch::Draw"); + throw std::logic_error("SpriteBatch::Draw"); } if (!texture.ptr) - throw std::exception("Invalid texture for Draw"); + throw std::invalid_argument("Invalid texture for Draw"); // Get a pointer to the output sprite. if (mSpriteQueueCount >= mSpriteQueueArraySize) @@ -979,7 +979,7 @@ XMMATRIX SpriteBatch::Impl::GetViewportTransform(_In_ DXGI_MODE_ROTATION rotatio if (!mSetViewport) { DebugTrace("ERROR: SpriteBatch requires viewport information via SetViewport\n"); - throw std::exception("Viewport not set."); + throw std::runtime_error("Viewport not set."); } // Compute the matrix. @@ -1076,12 +1076,12 @@ void XM_CALLCONV SpriteBatch::Begin( FXMMATRIX transformMatrix) { if (!sampler.ptr) - throw std::exception("Invalid heap-based sampler for Begin"); + throw std::invalid_argument("Invalid heap-based sampler for Begin"); if (!pImpl->mSampler.ptr) { DebugTrace("ERROR: sampler version of Begin requires SpriteBatch was created with a heap-based sampler\n"); - throw std::exception("SpriteBatch::Begin"); + throw std::runtime_error("SpriteBatch::Begin"); } pImpl->mSampler = sampler; @@ -1110,7 +1110,7 @@ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, _Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMUINT2 const& textureSize, - XMFLOAT2 const& position, + XMFLOAT2 const& position, RECT const* sourceRectangle, FXMVECTOR color, float rotation, @@ -1128,7 +1128,7 @@ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, _Use_decl_annotations_ -void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, +void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMUINT2 const& textureSize, XMFLOAT2 const& position, RECT const* sourceRectangle, @@ -1158,7 +1158,7 @@ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMUINT2 _Use_decl_annotations_ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMUINT2 const& textureSize, - FXMVECTOR position, + FXMVECTOR position, RECT const* sourceRectangle, FXMVECTOR color, float rotation, @@ -1199,7 +1199,7 @@ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, } -void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, +void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, XMUINT2 const& textureSize, RECT const& destinationRectangle, FXMVECTOR color) @@ -1217,8 +1217,8 @@ void XM_CALLCONV SpriteBatch::Draw(D3D12_GPU_DESCRIPTOR_HANDLE texture, RECT const* sourceRectangle, FXMVECTOR color, float rotation, - XMFLOAT2 const& origin, - SpriteEffects effects, + XMFLOAT2 const& origin, + SpriteEffects effects, float layerDepth) { XMVECTOR destination = LoadRect(&destinationRectangle); // x, y, w, h diff --git a/Kits/DirectXTK12/Src/SpriteFont.cpp b/Kits/DirectXTK12/Src/SpriteFont.cpp index 4783e41e..ae665cff 100644 --- a/Kits/DirectXTK12/Src/SpriteFont.cpp +++ b/Kits/DirectXTK12/Src/SpriteFont.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: SpriteFont.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -117,7 +117,7 @@ SpriteFont::Impl::Impl( if (reader->Read() != *magic) { DebugTrace("ERROR: SpriteFont provided with an invalid .spritefont file\n"); - throw std::exception("Not a MakeSpriteFont output binary"); + throw std::runtime_error("Not a MakeSpriteFont output binary"); } } @@ -196,7 +196,7 @@ SpriteFont::Impl::Impl( { if (!std::is_sorted(iglyphs, iglyphs + glyphCount)) { - throw std::exception("Glyphs must be in ascending codepoint order"); + throw std::runtime_error("Glyphs must be in ascending codepoint order"); } glyphsIndex.reserve(glyphs.size()); @@ -252,7 +252,7 @@ SpriteFont::Glyph const* SpriteFont::Impl::FindGlyph(wchar_t character) const } DebugTrace("ERROR: SpriteFont encountered a character not in the font (%u, %C), and no default glyph was provided\n", character, character); - throw std::exception("Character not in font"); + throw std::runtime_error("Character not in font"); } @@ -392,7 +392,7 @@ const wchar_t* SpriteFont::Impl::ConvertUTF8(_In_z_ const char *text) noexcept(f if (!result) { DebugTrace("ERROR: MultiByteToWideChar failed with error %u.\n", GetLastError()); - throw std::exception("MultiByteToWideChar"); + throw std::system_error(std::error_code(static_cast(GetLastError()), std::system_category()), "MultiByteToWideChar"); } return utfBuffer.get(); diff --git a/Kits/DirectXTK12/Src/TeapotData.inc b/Kits/DirectXTK12/Src/TeapotData.inc index 39e9a82d..532a6a40 100644 --- a/Kits/DirectXTK12/Src/TeapotData.inc +++ b/Kits/DirectXTK12/Src/TeapotData.inc @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: TeapotData.inc // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTK12/Src/ToneMapPostProcess.cpp b/Kits/DirectXTK12/Src/ToneMapPostProcess.cpp index d5277f0a..d501decc 100644 --- a/Kits/DirectXTK12/Src/ToneMapPostProcess.cpp +++ b/Kits/DirectXTK12/Src/ToneMapPostProcess.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: ToneMapPostProcess.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -36,7 +36,7 @@ namespace #endif // Constant buffer layout. Must match the shader! - __declspec(align(16)) struct ToneMapConstants + XM_ALIGNED_STRUCT(16) ToneMapConstants { // linearExposure is .x // paperWhiteNits is .y @@ -146,7 +146,7 @@ namespace #endif }; - static_assert(_countof(pixelShaders) == PixelShaderCount, "array/max mismatch"); + static_assert(std::size(pixelShaders) == PixelShaderCount, "array/max mismatch"); const int pixelShaderIndices[] = { @@ -189,7 +189,7 @@ namespace #endif }; - static_assert(_countof(pixelShaderIndices) == ShaderPermutationCount, "array/max mismatch"); + static_assert(static_cast(std::size(pixelShaderIndices)) == ShaderPermutationCount, "array/max mismatch"); // Factory for lazily instantiating shared root signatures. class DeviceResources @@ -276,10 +276,10 @@ ToneMapPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetStat mDeviceResources(deviceResourcesPool.DemandCreate(device)) { if (op >= Operator_Max) - throw std::out_of_range("Tonemap operator not defined"); + throw std::invalid_argument("Tonemap operator not defined"); if (func > TransferFunction_Max) - throw std::out_of_range("Transfer function not defined"); + throw std::invalid_argument("Transfer function not defined"); // Create root signature. { @@ -317,7 +317,7 @@ ToneMapPostProcess::Impl::Impl(_In_ ID3D12Device* device, const RenderTargetStat // Constant buffer rootParameters[RootParameterIndex::ConstantBuffer].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_PIXEL); - rsigDesc.Init(_countof(rootParameters), rootParameters, 1, &sampler, rootSignatureFlags); + rsigDesc.Init(static_cast(std::size(rootParameters)), rootParameters, 1, &sampler, rootSignatureFlags); mRootSignature = mDeviceResources->GetRootSignature(rsigDesc); } @@ -369,7 +369,7 @@ void ToneMapPostProcess::Impl::Process(_In_ ID3D12GraphicsCommandList* commandLi if (!texture.ptr) { DebugTrace("ERROR: Missing texture for ToneMapPostProcess (texture %llu)\n", texture.ptr); - throw std::exception("ToneMapPostProcess"); + throw std::runtime_error("ToneMapPostProcess"); } commandList->SetGraphicsRootDescriptorTable(RootParameterIndex::TextureSRV, texture); diff --git a/Kits/DirectXTK12/Src/VertexTypes.cpp b/Kits/DirectXTK12/Src/VertexTypes.cpp index dc7ca4be..ba1cf457 100644 --- a/Kits/DirectXTK12/Src/VertexTypes.cpp +++ b/Kits/DirectXTK12/Src/VertexTypes.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: VertexTypes.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/WICTextureLoader.cpp b/Kits/DirectXTK12/Src/WICTextureLoader.cpp index 148a4f33..0ce7dd90 100644 --- a/Kits/DirectXTK12/Src/WICTextureLoader.cpp +++ b/Kits/DirectXTK12/Src/WICTextureLoader.cpp @@ -11,7 +11,7 @@ // 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. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -181,7 +181,7 @@ namespace //--------------------------------------------------------------------------------- DXGI_FORMAT _WICToDXGI(const GUID& guid) noexcept { - for (size_t i = 0; i < _countof(g_WICFormats); ++i) + for (size_t i = 0; i < std::size(g_WICFormats); ++i) { if (memcmp(&g_WICFormats[i].wic, &guid, sizeof(GUID)) == 0) return g_WICFormats[i].format; @@ -286,7 +286,7 @@ namespace DXGI_FORMAT format = _WICToDXGI(pixelFormat); if (format == DXGI_FORMAT_UNKNOWN) { - for (size_t i = 0; i < _countof(g_WICConvert); ++i) + for (size_t i = 0; i < std::size(g_WICConvert); ++i) { if (memcmp(&g_WICConvert[i].source, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0) { @@ -581,7 +581,7 @@ namespace DXGI_FORMAT format = _WICToDXGI(pixelFormat); if (format == DXGI_FORMAT_UNKNOWN) { - for (size_t i = 0; i < _countof(g_WICConvert); ++i) + for (size_t i = 0; i < std::size(g_WICConvert); ++i) { if (memcmp(&g_WICConvert[i].source, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0) { diff --git a/Kits/DirectXTK12/Src/XboxDDSTextureLoader.cpp b/Kits/DirectXTK12/Src/XboxDDSTextureLoader.cpp index ef83446b..ed9d01bc 100644 --- a/Kits/DirectXTK12/Src/XboxDDSTextureLoader.cpp +++ b/Kits/DirectXTK12/Src/XboxDDSTextureLoader.cpp @@ -8,7 +8,7 @@ // module in the DirectXTex package or as part of the DirectXTK library to load // these files which use standard Direct3D resource creation APIs. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/d3dx12.h b/Kits/DirectXTK12/Src/d3dx12.h index 3bf9ac5b..562fb53a 100644 --- a/Kits/DirectXTK12/Src/d3dx12.h +++ b/Kits/DirectXTK12/Src/d3dx12.h @@ -1,11 +1,7 @@ //********************************************************* // -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the MIT License (MIT). -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License (MIT). // //********************************************************* @@ -2415,7 +2411,8 @@ inline HRESULT D3DX12SerializeVersionedRootSignature( { if (desc_1_1.pParameters[n].ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) { - HeapFree(GetProcessHeap(), 0, reinterpret_cast(const_cast(pParameters_1_0[n].DescriptorTable.pDescriptorRanges))); + auto pDescriptorRanges_1_0 = pParameters_1_0[n].DescriptorTable.pDescriptorRanges; + HeapFree(GetProcessHeap(), 0, reinterpret_cast(const_cast(pDescriptorRanges_1_0))); } } HeapFree(GetProcessHeap(), 0, pParameters); diff --git a/Kits/DirectXTK12/Src/dds.h b/Kits/DirectXTK12/Src/dds.h index 6b02437a..25fe3e53 100644 --- a/Kits/DirectXTK12/Src/dds.h +++ b/Kits/DirectXTK12/Src/dds.h @@ -1,14 +1,14 @@ //-------------------------------------------------------------------------------------- -// dds.h +// DDS.h // -// This header defines constants and structures that are useful when parsing +// This header defines constants and structures that are useful when parsing // DDS files. DDS files were originally designed to use several structures // and constants that are native to DirectDraw and are defined in ddraw.h, -// such as DDSURFACEDESC2 and DDSCAPS2. This file defines similar -// (compatible) constants and structures so that one can use DDS files +// such as DDSURFACEDESC2 and DDSCAPS2. This file defines similar +// (compatible) constants and structures so that one can use DDS files // without needing to include ddraw.h. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -57,117 +57,134 @@ struct DDS_PIXELFORMAT | (static_cast(static_cast(ch1)) << 8) \ | (static_cast(static_cast(ch2)) << 16) \ | (static_cast(static_cast(ch3)) << 24)) -#endif /* defined(MAKEFOURCC) */ +#endif /* MAKEFOURCC */ -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT1 = +#ifndef DDSGLOBALCONST + #if defined(__GNUC__) && !defined(__MINGW32__) + #define DDSGLOBALCONST extern const __attribute__((weak)) + #else + #define DDSGLOBALCONST extern const __declspec(selectany) + #endif +#endif /* DDSGLOBALCONST */ + +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT1 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','1'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT2 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT2 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','2'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT3 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT3 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','3'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT4 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT4 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','4'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT5 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT5 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','5'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_UNORM = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_BC4_UNORM = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','U'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_SNORM = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_BC4_SNORM = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','S'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_UNORM = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_BC5_UNORM = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','U'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_SNORM = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_BC5_SNORM = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','S'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8_B8G8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_R8G8_B8G8 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('R','G','B','G'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G8R8_G8B8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_G8R8_G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('G','R','G','B'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_YUY2 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_YUY2 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('Y','U','Y','2'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_UYVY = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_UYVY = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('U','Y','V','Y'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8R8G8B8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8R8G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8R8G8B8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_X8R8G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8B8G8R8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8B8G8R8 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8B8G8R8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_X8B8G8R8 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G16R16 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_G16R16 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x0000ffff, 0xffff0000, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R5G6B5 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_R5G6B5 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0xf800, 0x07e0, 0x001f, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A1R5G5B5 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A1R5G5B5 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x7c00, 0x03e0, 0x001f, 0x8000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X1R5G5B5 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_X1R5G5B5 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0x7c00, 0x03e0, 0x001f, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A4R4G4B4 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A4R4G4B4 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x0f00, 0x00f0, 0x000f, 0xf000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X4R4G4B4 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_X4R4G4B4 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0x0f00, 0x00f0, 0x000f, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8B8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_R8G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 24, 0xff0000, 0x00ff00, 0x0000ff, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8R3G3B2 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8R3G3B2 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00e0, 0x001c, 0x0003, 0xff00 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R3G3B2 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_R3G3B2 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 8, 0xe0, 0x1c, 0x03, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A4L4 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A4L4 = { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 8, 0x0f, 0, 0, 0xf0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L8 = - { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 8, 0xff, 0, 0, 0 }; +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_L8 = + { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 8, 0xff, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L16 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_L16 = { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 16, 0xffff, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8L8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8L8 = { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 16, 0x00ff, 0, 0, 0xff00 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8L8_ALT = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8L8_ALT = { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 8, 0x00ff, 0, 0, 0xff00 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_L8_NVTT1 = + { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 8, 0xff, 0, 0, 0 }; + +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_L16_NVTT1 = + { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0xffff, 0, 0, 0 }; + +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8L8_NVTT1 = + { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00ff, 0, 0, 0xff00 }; + +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8 = { sizeof(DDS_PIXELFORMAT), DDS_ALPHA, 0, 8, 0, 0, 0, 0xff }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_V8U8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_V8U8 = { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 16, 0x00ff, 0xff00, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_Q8W8V8U8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_Q8W8V8U8 = { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_V16U16 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_V16U16 = { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x0000ffff, 0xffff0000, 0, 0 }; // D3DFMT_A2R10G10B10/D3DFMT_A2B10G10R10 should be written using DX10 extension to avoid D3DX 10:10:10:2 reversal issue -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A2R10G10B10 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A2R10G10B10 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A2B10G10R10 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A2B10G10R10 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000 }; // We do not support the following legacy Direct3D 9 formats: @@ -176,10 +193,10 @@ extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A2B10G10R10 = // DDSPF_X8L8V8U8 = { sizeof(DDS_PIXELFORMAT), DDS_BUMPLUMINANCE, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0 }; // This indicates the DDS_HEADER_DXT10 extension is present (the format is in dxgiFormat) -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DX10 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DX10 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','1','0'), 0, 0, 0, 0, 0 }; -#define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT +#define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT #define DDS_HEADER_FLAGS_MIPMAP 0x00020000 // DDSD_MIPMAPCOUNT #define DDS_HEADER_FLAGS_VOLUME 0x00800000 // DDSD_DEPTH #define DDS_HEADER_FLAGS_PITCH 0x00000008 // DDSD_PITCH @@ -210,9 +227,9 @@ extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DX10 = // Subset here matches D3D10_RESOURCE_DIMENSION and D3D11_RESOURCE_DIMENSION enum DDS_RESOURCE_DIMENSION : uint32_t { - DDS_DIMENSION_TEXTURE1D = 2, - DDS_DIMENSION_TEXTURE2D = 3, - DDS_DIMENSION_TEXTURE3D = 4, + DDS_DIMENSION_TEXTURE1D = 2, + DDS_DIMENSION_TEXTURE2D = 3, + DDS_DIMENSION_TEXTURE3D = 4, }; // Subset here matches D3D10_RESOURCE_MISC_FLAG and D3D11_RESOURCE_MISC_FLAG diff --git a/Kits/DirectXTK12/Src/pch.cpp b/Kits/DirectXTK12/Src/pch.cpp index 63d7d1d8..80aab27f 100644 --- a/Kits/DirectXTK12/Src/pch.cpp +++ b/Kits/DirectXTK12/Src/pch.cpp @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: pch.cpp // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 diff --git a/Kits/DirectXTK12/Src/pch.h b/Kits/DirectXTK12/Src/pch.h index 940e8ad3..78b802c8 100644 --- a/Kits/DirectXTK12/Src/pch.h +++ b/Kits/DirectXTK12/Src/pch.h @@ -1,7 +1,7 @@ //-------------------------------------------------------------------------------------- // File: pch.h // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 @@ -125,8 +125,14 @@ #endif #endif -#include +#ifdef USING_DIRECTX_HEADERS +#include +#include +#else #include +#endif + +#include #ifdef __clang__ #pragma clang diagnostic push @@ -135,8 +141,12 @@ #endif #define D3DX12_NO_STATE_OBJECT_HELPERS +#ifdef USING_DIRECTX_HEADERS +#include +#else #include "d3dx12.h" #endif +#endif #ifdef __clang__ #pragma clang diagnostic pop @@ -149,17 +159,15 @@ #pragma warning(pop) #endif -#define _XM_NO_XMVECTOR_OVERLOADS_ - -#include -#include -#include - #include #include #include +#include #include #include +#include +#include +#include #include #include #include @@ -167,9 +175,11 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -186,6 +196,16 @@ #include +#define _XM_NO_XMVECTOR_OVERLOADS_ + +#include +#include +#include + +#if (DIRECTX_MATH_VERSION < 315) +#define XM_ALIGNED_STRUCT(x) __declspec(align(x)) struct +#endif + #pragma warning(push) #pragma warning(disable : 4467 5038 5204 5220) #include diff --git a/Kits/DirectXTK12/Src/vbo.h b/Kits/DirectXTK12/Src/vbo.h index ff999d11..ce600a45 100644 --- a/Kits/DirectXTK12/Src/vbo.h +++ b/Kits/DirectXTK12/Src/vbo.h @@ -7,7 +7,7 @@ // The meshconvert sample tool for DirectXMesh can produce this file type // http://go.microsoft.com/fwlink/?LinkID=324981 // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 diff --git a/Kits/DirectXTex/BC.cpp b/Kits/DirectXTex/BC.cpp index ef4583c0..d4e43beb 100644 --- a/Kits/DirectXTex/BC.cpp +++ b/Kits/DirectXTex/BC.cpp @@ -3,7 +3,7 @@ // // Block-compression (BC) functionality for BC1, BC2, BC3 (orginal DXTn formats) // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTex/BC.h b/Kits/DirectXTex/BC.h index 7fb89696..04e84c5a 100644 --- a/Kits/DirectXTex/BC.h +++ b/Kits/DirectXTex/BC.h @@ -3,7 +3,7 @@ // // Block-compression (BC) functionality // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -11,7 +11,6 @@ #pragma once -#include #include #include diff --git a/Kits/DirectXTex/BC4BC5.cpp b/Kits/DirectXTex/BC4BC5.cpp index c3afdc9e..c5a7a86c 100644 --- a/Kits/DirectXTex/BC4BC5.cpp +++ b/Kits/DirectXTex/BC4BC5.cpp @@ -3,7 +3,7 @@ // // Block-compression (BC) functionality for BC4 and BC5 (DirectX 10 texture compression) // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTex/BC6HBC7.cpp b/Kits/DirectXTex/BC6HBC7.cpp index c26dba16..7d807364 100644 --- a/Kits/DirectXTex/BC6HBC7.cpp +++ b/Kits/DirectXTex/BC6HBC7.cpp @@ -3,7 +3,7 @@ // // Block-compression (BC) functionality for BC6H and BC7 (DirectX 11 texture compression) // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -1660,12 +1660,12 @@ void D3DX_BC6H::Decode(bool bSigned, HDRColorA* pOut) const noexcept if (ms_aModeToInfo[uMode] >= 0) { - assert(static_cast(ms_aModeToInfo[uMode]) < _countof(ms_aInfo)); - _Analysis_assume_(ms_aModeToInfo[uMode] < _countof(ms_aInfo)); + assert(static_cast(ms_aModeToInfo[uMode]) < std::size(ms_aInfo)); + _Analysis_assume_(ms_aModeToInfo[uMode] < std::size(ms_aInfo)); const ModeDescriptor* desc = ms_aDesc[ms_aModeToInfo[uMode]]; - assert(static_cast(ms_aModeToInfo[uMode]) < _countof(ms_aDesc)); - _Analysis_assume_(ms_aModeToInfo[uMode] < _countof(ms_aDesc)); + assert(static_cast(ms_aModeToInfo[uMode]) < std::size(ms_aDesc)); + _Analysis_assume_(ms_aModeToInfo[uMode] < std::size(ms_aDesc)); const ModeInfo& info = ms_aInfo[ms_aModeToInfo[uMode]]; INTEndPntPair aEndPts[BC6H_MAX_REGIONS] = {}; @@ -1811,7 +1811,7 @@ void D3DX_BC6H::Encode(bool bSigned, const HDRColorA* const pIn) noexcept EncodeParams EP(pIn, bSigned); - for (EP.uMode = 0; EP.uMode < ARRAYSIZE(ms_aInfo) && EP.fBestErr > 0; ++EP.uMode) + for (EP.uMode = 0; EP.uMode < std::size(ms_aInfo) && EP.fBestErr > 0; ++EP.uMode) { const uint8_t uShapes = ms_aInfo[EP.uMode].uPartitions ? 32u : 1u; // Number of rough cases to look at. reasonable values of this are 1, uShapes/4, and uShapes diff --git a/Kits/DirectXTex/BCDirectCompute.cpp b/Kits/DirectXTex/BCDirectCompute.cpp index 24937779..bc969655 100644 --- a/Kits/DirectXTex/BCDirectCompute.cpp +++ b/Kits/DirectXTex/BCDirectCompute.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // BCDirectCompute.cpp -// +// // Direct3D 11 Compute Shader BC Compressor // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- @@ -104,7 +104,7 @@ HRESULT GPUCompressBC::Initialize(ID3D11Device* pDevice) if (fl < D3D_FEATURE_LEVEL_10_0) { // DirectCompute not supported on Feature Level 9.x hardware - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } if (fl < D3D_FEATURE_LEVEL_11_0) @@ -119,7 +119,7 @@ HRESULT GPUCompressBC::Initialize(ID3D11Device* pDevice) if (!hwopts.ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x) { - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } } @@ -222,7 +222,7 @@ HRESULT GPUCompressBC::Prepare(size_t width, size_t height, uint32_t flags, DXGI default: m_bcformat = m_srcformat = DXGI_FORMAT_UNKNOWN; - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } m_bcformat = format; @@ -234,7 +234,7 @@ HRESULT GPUCompressBC::Prepare(size_t width, size_t height, uint32_t flags, DXGI // Create structured buffers uint64_t sizeInBytes = uint64_t(num_blocks) * sizeof(BufferBC6HBC7); if (sizeInBytes >= UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; auto bufferSize = static_cast(sizeInBytes); diff --git a/Kits/DirectXTex/BCDirectCompute.h b/Kits/DirectXTex/BCDirectCompute.h index 04d746bd..1013d1ec 100644 --- a/Kits/DirectXTex/BCDirectCompute.h +++ b/Kits/DirectXTex/BCDirectCompute.h @@ -3,7 +3,7 @@ // // Direct3D 11 Compute Shader BC Compressor // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- diff --git a/Kits/DirectXTex/DDS.h b/Kits/DirectXTex/DDS.h index 6b02437a..25fe3e53 100644 --- a/Kits/DirectXTex/DDS.h +++ b/Kits/DirectXTex/DDS.h @@ -1,14 +1,14 @@ //-------------------------------------------------------------------------------------- -// dds.h +// DDS.h // -// This header defines constants and structures that are useful when parsing +// This header defines constants and structures that are useful when parsing // DDS files. DDS files were originally designed to use several structures // and constants that are native to DirectDraw and are defined in ddraw.h, -// such as DDSURFACEDESC2 and DDSCAPS2. This file defines similar -// (compatible) constants and structures so that one can use DDS files +// such as DDSURFACEDESC2 and DDSCAPS2. This file defines similar +// (compatible) constants and structures so that one can use DDS files // without needing to include ddraw.h. // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -57,117 +57,134 @@ struct DDS_PIXELFORMAT | (static_cast(static_cast(ch1)) << 8) \ | (static_cast(static_cast(ch2)) << 16) \ | (static_cast(static_cast(ch3)) << 24)) -#endif /* defined(MAKEFOURCC) */ +#endif /* MAKEFOURCC */ -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT1 = +#ifndef DDSGLOBALCONST + #if defined(__GNUC__) && !defined(__MINGW32__) + #define DDSGLOBALCONST extern const __attribute__((weak)) + #else + #define DDSGLOBALCONST extern const __declspec(selectany) + #endif +#endif /* DDSGLOBALCONST */ + +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT1 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','1'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT2 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT2 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','2'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT3 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT3 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','3'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT4 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT4 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','4'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DXT5 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DXT5 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','T','5'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_UNORM = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_BC4_UNORM = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','U'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC4_SNORM = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_BC4_SNORM = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','4','S'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_UNORM = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_BC5_UNORM = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','U'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_BC5_SNORM = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_BC5_SNORM = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('B','C','5','S'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8_B8G8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_R8G8_B8G8 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('R','G','B','G'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G8R8_G8B8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_G8R8_G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('G','R','G','B'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_YUY2 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_YUY2 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('Y','U','Y','2'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_UYVY = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_UYVY = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('U','Y','V','Y'), 0, 0, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8R8G8B8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8R8G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8R8G8B8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_X8R8G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8B8G8R8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8B8G8R8 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X8B8G8R8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_X8B8G8R8 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_G16R16 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_G16R16 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 32, 0x0000ffff, 0xffff0000, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R5G6B5 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_R5G6B5 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0xf800, 0x07e0, 0x001f, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A1R5G5B5 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A1R5G5B5 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x7c00, 0x03e0, 0x001f, 0x8000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X1R5G5B5 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_X1R5G5B5 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0x7c00, 0x03e0, 0x001f, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A4R4G4B4 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A4R4G4B4 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x0f00, 0x00f0, 0x000f, 0xf000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_X4R4G4B4 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_X4R4G4B4 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0x0f00, 0x00f0, 0x000f, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R8G8B8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_R8G8B8 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 24, 0xff0000, 0x00ff00, 0x0000ff, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8R3G3B2 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8R3G3B2 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00e0, 0x001c, 0x0003, 0xff00 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_R3G3B2 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_R3G3B2 = { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 8, 0xe0, 0x1c, 0x03, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A4L4 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A4L4 = { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 8, 0x0f, 0, 0, 0xf0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L8 = - { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 8, 0xff, 0, 0, 0 }; +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_L8 = + { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 8, 0xff, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_L16 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_L16 = { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCE, 0, 16, 0xffff, 0, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8L8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8L8 = { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 16, 0x00ff, 0, 0, 0xff00 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8L8_ALT = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8L8_ALT = { sizeof(DDS_PIXELFORMAT), DDS_LUMINANCEA, 0, 8, 0x00ff, 0, 0, 0xff00 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_L8_NVTT1 = + { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 8, 0xff, 0, 0, 0 }; + +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_L16_NVTT1 = + { sizeof(DDS_PIXELFORMAT), DDS_RGB, 0, 16, 0xffff, 0, 0, 0 }; + +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8L8_NVTT1 = + { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 16, 0x00ff, 0, 0, 0xff00 }; + +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A8 = { sizeof(DDS_PIXELFORMAT), DDS_ALPHA, 0, 8, 0, 0, 0, 0xff }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_V8U8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_V8U8 = { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 16, 0x00ff, 0xff00, 0, 0 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_Q8W8V8U8 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_Q8W8V8U8 = { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_V16U16 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_V16U16 = { sizeof(DDS_PIXELFORMAT), DDS_BUMPDUDV, 0, 32, 0x0000ffff, 0xffff0000, 0, 0 }; // D3DFMT_A2R10G10B10/D3DFMT_A2B10G10R10 should be written using DX10 extension to avoid D3DX 10:10:10:2 reversal issue -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A2R10G10B10 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A2R10G10B10 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000 }; -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A2B10G10R10 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_A2B10G10R10 = { sizeof(DDS_PIXELFORMAT), DDS_RGBA, 0, 32, 0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000 }; // We do not support the following legacy Direct3D 9 formats: @@ -176,10 +193,10 @@ extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_A2B10G10R10 = // DDSPF_X8L8V8U8 = { sizeof(DDS_PIXELFORMAT), DDS_BUMPLUMINANCE, 0, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0 }; // This indicates the DDS_HEADER_DXT10 extension is present (the format is in dxgiFormat) -extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DX10 = +DDSGLOBALCONST DDS_PIXELFORMAT DDSPF_DX10 = { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('D','X','1','0'), 0, 0, 0, 0, 0 }; -#define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT +#define DDS_HEADER_FLAGS_TEXTURE 0x00001007 // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT #define DDS_HEADER_FLAGS_MIPMAP 0x00020000 // DDSD_MIPMAPCOUNT #define DDS_HEADER_FLAGS_VOLUME 0x00800000 // DDSD_DEPTH #define DDS_HEADER_FLAGS_PITCH 0x00000008 // DDSD_PITCH @@ -210,9 +227,9 @@ extern __declspec(selectany) const DDS_PIXELFORMAT DDSPF_DX10 = // Subset here matches D3D10_RESOURCE_DIMENSION and D3D11_RESOURCE_DIMENSION enum DDS_RESOURCE_DIMENSION : uint32_t { - DDS_DIMENSION_TEXTURE1D = 2, - DDS_DIMENSION_TEXTURE2D = 3, - DDS_DIMENSION_TEXTURE3D = 4, + DDS_DIMENSION_TEXTURE1D = 2, + DDS_DIMENSION_TEXTURE2D = 3, + DDS_DIMENSION_TEXTURE3D = 4, }; // Subset here matches D3D10_RESOURCE_MISC_FLAG and D3D11_RESOURCE_MISC_FLAG diff --git a/Kits/DirectXTex/DirectXTex.h b/Kits/DirectXTex/DirectXTex.h index 03249bd3..cf5233c5 100644 --- a/Kits/DirectXTex/DirectXTex.h +++ b/Kits/DirectXTex/DirectXTex.h @@ -3,7 +3,7 @@ // // DirectX Texture Library // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -11,11 +11,13 @@ #pragma once -#include +#include #include #include +#include #include +#if defined(WIN32) || defined(_WIN32) #if !defined(__d3d11_h__) && !defined(__d3d11_x_h__) && !defined(__d3d12_h__) && !defined(__d3d12_x_h__) && !defined(__XBOX_D3D12_X__) #ifdef _GAMING_XBOX_SCARLETT #include @@ -27,15 +29,25 @@ #include #endif #endif +#else // !WIN32 +#include +#include +#endif #include +#ifdef WIN32 +#ifdef NTDDI_WIN10_FE +#include +#else #include - -#define DIRECTX_TEX_VERSION 191 +#endif struct IWICImagingFactory; struct IWICMetadataQueryReader; +#endif + +#define DIRECTX_TEX_VERSION 193 namespace DirectX @@ -284,6 +296,7 @@ namespace DirectX _In_ TGA_FLAGS flags, _Out_ TexMetadata& metadata) noexcept; +#ifdef WIN32 HRESULT __cdecl GetMetadataFromWICMemory( _In_reads_bytes_(size) const void* pSource, _In_ size_t size, _In_ WIC_FLAGS flags, @@ -295,6 +308,7 @@ namespace DirectX _In_ WIC_FLAGS flags, _Out_ TexMetadata& metadata, _In_opt_ std::function getMQR = nullptr); +#endif // Compatability helpers HRESULT __cdecl GetMetadataFromTGAMemory( @@ -386,7 +400,11 @@ namespace DirectX void *__cdecl GetBufferPointer() const noexcept { return m_buffer; } size_t __cdecl GetBufferSize() const noexcept { return m_size; } + HRESULT __cdecl Resize(size_t size) noexcept; + // Reallocate for a new size + HRESULT __cdecl Trim(size_t size) noexcept; + // Shorten size without reallocation private: void* m_buffer; @@ -449,6 +467,7 @@ namespace DirectX _In_z_ const wchar_t* szFile, _In_opt_ const TexMetadata* metadata = nullptr) noexcept; // WIC operations +#ifdef WIN32 HRESULT __cdecl LoadFromWICMemory( _In_reads_bytes_(size) const void* pSource, _In_ size_t size, _In_ WIC_FLAGS flags, @@ -478,6 +497,7 @@ namespace DirectX _In_ WIC_FLAGS flags, _In_ REFGUID guidContainerFormat, _In_z_ const wchar_t* szFile, _In_opt_ const GUID* targetFormat = nullptr, _In_opt_ std::function setCustomProps = nullptr); +#endif // WIN32 // Compatability helpers HRESULT __cdecl LoadFromTGAMemory( @@ -503,11 +523,13 @@ namespace DirectX TEX_FR_FLIP_VERTICAL = 0x10, }; +#ifdef WIN32 HRESULT __cdecl FlipRotate(_In_ const Image& srcImage, _In_ TEX_FR_FLAGS flags, _Out_ ScratchImage& image) noexcept; HRESULT __cdecl FlipRotate( _In_reads_(nimages) const Image* srcImages, _In_ size_t nimages, _In_ const TexMetadata& metadata, _In_ TEX_FR_FLAGS flags, _Out_ ScratchImage& result) noexcept; // Flip and/or rotate image +#endif enum TEX_FILTER_FLAGS : unsigned long { @@ -787,7 +809,7 @@ namespace DirectX //--------------------------------------------------------------------------------- // WIC utility code - +#ifdef WIN32 enum WICCodecs { WIC_CODEC_BMP = 1, // Windows Bitmap (.bmp) @@ -803,6 +825,7 @@ namespace DirectX IWICImagingFactory* __cdecl GetWICFactory(bool& iswic2) noexcept; void __cdecl SetWICFactory(_In_opt_ IWICImagingFactory* pWIC) noexcept; +#endif //--------------------------------------------------------------------------------- // Direct3D 11 functions diff --git a/Kits/DirectXTex/DirectXTex.inl b/Kits/DirectXTex/DirectXTex.inl index 7ca3f4cb..d458fe4b 100644 --- a/Kits/DirectXTex/DirectXTex.inl +++ b/Kits/DirectXTex/DirectXTex.inl @@ -3,7 +3,7 @@ // // DirectX Texture Library // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 diff --git a/Kits/DirectXTex/DirectXTexCompress.cpp b/Kits/DirectXTex/DirectXTexCompress.cpp index 23aa74e4..c595446c 100644 --- a/Kits/DirectXTex/DirectXTexCompress.cpp +++ b/Kits/DirectXTex/DirectXTexCompress.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexCompress.cpp -// +// // DirectX Texture Library - Texture compression // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -89,7 +89,7 @@ namespace if (sbpp < 8) { // We don't support compressing from monochrome (DXGI_FORMAT_R1_UNORM) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } // Round to bytes @@ -102,9 +102,9 @@ namespace size_t blocksize; TEX_FILTER_FLAGS cflags; if (!DetermineEncoderSettings(result.format, pfEncode, blocksize, cflags)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; - __declspec(align(16)) XMVECTOR temp[16]; + XM_ALIGNED_DATA(16) XMVECTOR temp[16]; const uint8_t *pSrc = image.pixels; const uint8_t *pEnd = image.pixels + image.slicePitch; const size_t rowPitch = image.rowPitch; @@ -218,7 +218,7 @@ namespace if (sbpp < 8) { // We don't support compressing from monochrome (DXGI_FORMAT_R1_UNORM) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } // Round to bytes @@ -231,7 +231,7 @@ namespace size_t blocksize; TEX_FILTER_FLAGS cflags; if (!DetermineEncoderSettings(result.format, pfEncode, blocksize, cflags)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; // Refactored version of loop to support parallel independance const size_t nBlocks = std::max(1, (image.width + 3) / 4) * std::max(1, (image.height + 3) / 4); @@ -263,7 +263,7 @@ namespace assert(bytesLeft > 0); size_t bytesToRead = std::min(rowPitch, size_t(bytesLeft)); - __declspec(align(16)) XMVECTOR temp[16]; + XM_ALIGNED_DATA(16) XMVECTOR temp[16]; if (!_LoadScanline(&temp[0], pw, pSrc, bytesToRead, format)) fail = true; @@ -394,7 +394,7 @@ namespace if (dbpp < 8) { // We don't support decompressing to monochrome (DXGI_FORMAT_R1_UNORM) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } // Round to bytes @@ -438,10 +438,10 @@ namespace case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB: pfDecode = D3DXDecodeBC7; sbpp = 16; break; default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } - __declspec(align(16)) XMVECTOR temp[16]; + XM_ALIGNED_DATA(16) XMVECTOR temp[16]; const uint8_t *pSrc = cImage.pixels; const size_t rowPitch = result.rowPitch; for (size_t h = 0; h < cImage.height; h += 4) @@ -534,7 +534,7 @@ namespace DirectX // Scan blocks for non-opaque alpha static const XMVECTORF32 threshold = { { { 0.99f, 0.99f, 0.99f, 0.99f } } }; - __declspec(align(16)) XMVECTOR temp[16]; + XM_ALIGNED_DATA(16) XMVECTOR temp[16]; const uint8_t *pPixels = cImage.pixels; for (size_t h = 0; h < cImage.height; h += 4) { @@ -603,7 +603,7 @@ HRESULT DirectX::Compress( if (IsTypeless(format) || IsTypeless(srcImage.format) || IsPlanar(srcImage.format) || IsPalettized(srcImage.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; // Create compressed image HRESULT hr = image.Initialize2D(format, srcImage.width, srcImage.height, 1, 1); @@ -655,7 +655,7 @@ HRESULT DirectX::Compress( if (IsTypeless(format) || IsTypeless(metadata.format) || IsPlanar(metadata.format) || IsPalettized(metadata.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; cImages.Release(); @@ -749,7 +749,7 @@ HRESULT DirectX::Decompress( return E_INVALIDARG; if (IsTypeless(format) || IsPlanar(format) || IsPalettized(format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } // Create decompressed image @@ -802,7 +802,7 @@ HRESULT DirectX::Decompress( return E_INVALIDARG; if (IsTypeless(format) || IsPlanar(format) || IsPalettized(format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } images.Release(); diff --git a/Kits/DirectXTex/DirectXTexCompressGPU.cpp b/Kits/DirectXTex/DirectXTexCompressGPU.cpp index 8769f50d..fc366638 100644 --- a/Kits/DirectXTex/DirectXTexCompressGPU.cpp +++ b/Kits/DirectXTex/DirectXTexCompressGPU.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexCompressGPU.cpp -// +// // DirectX Texture Library - DirectCompute-based texture compression // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -59,7 +59,7 @@ namespace return E_POINTER; } - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR) * srcImage.width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(srcImage.width); if (!scanline) { image.Release(); @@ -219,7 +219,7 @@ HRESULT DirectX::Compress( if (IsTypeless(format) || IsTypeless(srcImage.format) || IsPlanar(srcImage.format) || IsPalettized(srcImage.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; // Setup GPU compressor std::unique_ptr gpubc(new (std::nothrow) GPUCompressBC); @@ -272,7 +272,7 @@ HRESULT DirectX::Compress( if (IsTypeless(format) || IsTypeless(metadata.format) || IsPlanar(metadata.format) || IsPalettized(metadata.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; cImages.Release(); @@ -414,7 +414,7 @@ HRESULT DirectX::Compress( break; default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } return S_OK; diff --git a/Kits/DirectXTex/DirectXTexConvert.cpp b/Kits/DirectXTex/DirectXTexConvert.cpp index b42e97bc..2e49bf9a 100644 --- a/Kits/DirectXTex/DirectXTexConvert.cpp +++ b/Kits/DirectXTex/DirectXTexConvert.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexConvert.cpp -// -// DirectX Texture Library - Image pixel format conversion // -// Copyright (c) Microsoft Corporation. All rights reserved. +// DirectX Texture Library - Image pixel format conversion +// +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -435,7 +435,7 @@ void DirectX::_CopyScanline( return; size_t size = std::min(outSize, inSize); - memcpy_s(pDestination, outSize, pSource, size); + memcpy(pDestination, pSource, size); } @@ -605,7 +605,7 @@ void DirectX::_SwizzleScanline( return; size_t size = std::min(outSize, inSize); - memcpy_s(pDestination, outSize, pSource, size); + memcpy(pDestination, pSource, size); } @@ -777,7 +777,7 @@ _Use_decl_annotations_ bool DirectX::_LoadScanline( case DXGI_FORMAT_R32G32B32A32_FLOAT: { size_t msize = (size > (sizeof(XMVECTOR)*count)) ? (sizeof(XMVECTOR)*count) : size; - memcpy_s(dPtr, sizeof(XMVECTOR)*count, pSource, msize); + memcpy(dPtr, pSource, msize); } return true; @@ -1611,15 +1611,23 @@ bool DirectX::_StoreScanline( size_t count, float threshold) noexcept { - assert(pDestination && size > 0); - assert(pSource && count > 0 && ((reinterpret_cast(pSource) & 0xF) == 0)); + assert(pDestination != nullptr); assert(IsValid(format) && !IsTypeless(format) && !IsCompressed(format) && !IsPlanar(format) && !IsPalettized(format)); + if (!size || !count) + return false; + const XMVECTOR* __restrict sPtr = pSource; if (!sPtr) return false; - const XMVECTOR* ePtr = pSource + count; + assert((reinterpret_cast(pSource) & 0xF) == 0); + + const XMVECTOR* ePtr = sPtr + count; + +#ifdef _PREFAST_ + *reinterpret_cast(pDestination) = 0; +#endif switch (static_cast(format)) { @@ -2640,7 +2648,7 @@ HRESULT DirectX::_ConvertToR16G16B16A16(const Image& srcImage, ScratchImage& ima if (FAILED(hr)) return hr; - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR) * srcImage.width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(srcImage.width); if (!scanline) { image.Release(); @@ -2693,7 +2701,7 @@ HRESULT DirectX::_ConvertFromR16G16B16A16(const Image& srcImage, const Image& de if (srcImage.width != destImage.width || srcImage.height != destImage.height) return E_FAIL; - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR) * srcImage.width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(srcImage.width); if (!scanline) return E_OUTOFMEMORY; @@ -2735,9 +2743,10 @@ bool DirectX::_StoreScanlineLinear( TEX_FILTER_FLAGS flags, float threshold) noexcept { - assert(pDestination && size > 0); - assert(pSource && count > 0 && ((reinterpret_cast(pSource) & 0xF) == 0)); - assert(IsValid(format) && !IsTypeless(format) && !IsCompressed(format) && !IsPlanar(format) && !IsPalettized(format)); + if (!pSource || !count) + return false; + + assert((reinterpret_cast(pSource) & 0xF) == 0); switch (format) { @@ -2810,10 +2819,6 @@ bool DirectX::_LoadScanlineLinear( DXGI_FORMAT format, TEX_FILTER_FLAGS flags) noexcept { - assert(pDestination && count > 0 && ((reinterpret_cast(pDestination) & 0xF) == 0)); - assert(pSource && size > 0); - assert(IsValid(format) && !IsTypeless(format, false) && !IsCompressed(format) && !IsPlanar(format) && !IsPalettized(format)); - switch (format) { case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: @@ -2972,10 +2977,9 @@ namespace { XBOX_DXGI_FORMAT_R4G4_UNORM, 4, CONVF_UNORM | CONVF_R | CONVF_G }, }; -#pragma prefast( suppress : 25004, "Signature must match bsearch_s" ); - int __cdecl ConvertCompare(void *context, const void* ptr1, const void *ptr2) noexcept +#pragma prefast( suppress : 25004, "Signature must match bsearch" ); + int __cdecl ConvertCompare(const void* ptr1, const void *ptr2) noexcept { - UNREFERENCED_PARAMETER(context); auto p1 = static_cast(ptr1); auto p2 = static_cast(ptr2); if (p1->format == p2->format) return 0; @@ -2988,9 +2992,9 @@ uint32_t DirectX::_GetConvertFlags(DXGI_FORMAT format) noexcept { #ifdef _DEBUG // Ensure conversion table is in ascending order - assert(_countof(g_ConvertTable) > 0); + assert(std::size(g_ConvertTable) > 0); DXGI_FORMAT lastvalue = g_ConvertTable[0].format; - for (size_t index = 1; index < _countof(g_ConvertTable); ++index) + for (size_t index = 1; index < std::size(g_ConvertTable); ++index) { assert(g_ConvertTable[index].format > lastvalue); lastvalue = g_ConvertTable[index].format; @@ -2998,8 +3002,8 @@ uint32_t DirectX::_GetConvertFlags(DXGI_FORMAT format) noexcept #endif ConvertData key = { format, 0, 0 }; - auto in = reinterpret_cast(bsearch_s(&key, g_ConvertTable, _countof(g_ConvertTable), sizeof(ConvertData), - ConvertCompare, nullptr)); + auto in = reinterpret_cast(bsearch(&key, g_ConvertTable, std::size(g_ConvertTable), sizeof(ConvertData), + ConvertCompare)); return (in) ? in->flags : 0; } @@ -3020,9 +3024,9 @@ void DirectX::_ConvertScanline( #ifdef _DEBUG // Ensure conversion table is in ascending order - assert(_countof(g_ConvertTable) > 0); + assert(std::size(g_ConvertTable) > 0); DXGI_FORMAT lastvalue = g_ConvertTable[0].format; - for (size_t index = 1; index < _countof(g_ConvertTable); ++index) + for (size_t index = 1; index < std::size(g_ConvertTable); ++index) { assert(g_ConvertTable[index].format > lastvalue); lastvalue = g_ConvertTable[index].format; @@ -3032,10 +3036,10 @@ void DirectX::_ConvertScanline( // Determine conversion details about source and dest formats ConvertData key = { inFormat, 0, 0 }; auto in = reinterpret_cast( - bsearch_s(&key, g_ConvertTable, _countof(g_ConvertTable), sizeof(ConvertData), ConvertCompare, nullptr)); + bsearch(&key, g_ConvertTable, std::size(g_ConvertTable), sizeof(ConvertData), ConvertCompare)); key.format = outFormat; auto out = reinterpret_cast( - bsearch_s(&key, g_ConvertTable, _countof(g_ConvertTable), sizeof(ConvertData), ConvertCompare, nullptr)); + bsearch(&key, g_ConvertTable, std::size(g_ConvertTable), sizeof(ConvertData), ConvertCompare)); if (!in || !out) { assert(false); @@ -3910,10 +3914,18 @@ bool DirectX::_StoreScanlineDither( size_t z, XMVECTOR* pDiffusionErrors) noexcept { - assert(pDestination && size > 0); - assert(pSource && count > 0 && ((reinterpret_cast(pSource) & 0xF) == 0)); + assert(pDestination != nullptr); assert(IsValid(format) && !IsTypeless(format) && !IsCompressed(format) && !IsPlanar(format) && !IsPalettized(format)); + if (!size || !count) + return false; + + const XMVECTOR* __restrict sPtr = pSource; + if (!sPtr) + return false; + + assert((reinterpret_cast(pSource) & 0xF) == 0); + XMVECTOR ordered[4]; if (pDiffusionErrors) { @@ -3946,12 +3958,12 @@ bool DirectX::_StoreScanlineDither( ordered[3] = XMVectorSplatW(dither); } - const XMVECTOR* __restrict sPtr = pSource; - if (!sPtr) - return false; - const void* ePtr = static_cast(pDestination) + size; +#ifdef _PREFAST_ + *reinterpret_cast(pDestination) = 0; +#endif + XMVECTOR vError = XMVectorZero(); switch (static_cast(format)) @@ -4373,6 +4385,14 @@ namespace _Out_ WICPixelFormatGUID& pfGUID, _Out_ WICPixelFormatGUID& targetGUID) noexcept { +#ifndef WIN32 + UNREFERENCED_PARAMETER(filter); + UNREFERENCED_PARAMETER(sformat); + UNREFERENCED_PARAMETER(tformat); + UNREFERENCED_PARAMETER(pfGUID); + UNREFERENCED_PARAMETER(targetGUID); + return false; +#else memset(&pfGUID, 0, sizeof(GUID)); memset(&targetGUID, 0, sizeof(GUID)); @@ -4514,6 +4534,7 @@ namespace } return true; +#endif // WIN32 } //------------------------------------------------------------------------------------- @@ -4527,6 +4548,15 @@ namespace _In_ float threshold, _In_ const Image& destImage) { +#ifndef WIN32 + UNREFERENCED_PARAMETER(srcImage); + UNREFERENCED_PARAMETER(pfGUID); + UNREFERENCED_PARAMETER(targetGUID); + UNREFERENCED_PARAMETER(filter); + UNREFERENCED_PARAMETER(threshold); + UNREFERENCED_PARAMETER(destImage); + return E_NOTIMPL; +#else assert(srcImage.width == destImage.width); assert(srcImage.height == destImage.height); @@ -4553,7 +4583,7 @@ namespace if (srcImage.rowPitch > UINT32_MAX || srcImage.slicePitch > UINT32_MAX || destImage.rowPitch > UINT32_MAX || destImage.slicePitch > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; ComPtr source; hr = pWIC->CreateBitmapFromMemory(static_cast(srcImage.width), static_cast(srcImage.height), pfGUID, @@ -4571,9 +4601,9 @@ namespace return hr; return S_OK; +#endif // WIN32 } - //------------------------------------------------------------------------------------- // Convert the source image (not using WIC) //------------------------------------------------------------------------------------- @@ -4597,7 +4627,7 @@ namespace if (filter & TEX_FILTER_DITHER_DIFFUSION) { // Error diffusion dithering (aka Floyd-Steinberg dithering) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*(width * 2 + 2)), 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(width) * 2 + 2); if (!scanline) return E_OUTOFMEMORY; @@ -4620,7 +4650,7 @@ namespace } else { - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(width); if (!scanline) return E_OUTOFMEMORY; @@ -4840,7 +4870,7 @@ HRESULT DirectX::Convert( || IsPlanar(srcImage.format) || IsPlanar(format) || IsPalettized(srcImage.format) || IsPalettized(format) || IsTypeless(srcImage.format) || IsTypeless(format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if ((srcImage.width > UINT32_MAX) || (srcImage.height > UINT32_MAX)) return E_INVALIDARG; @@ -4896,7 +4926,7 @@ HRESULT DirectX::Convert( || IsPlanar(metadata.format) || IsPlanar(format) || IsPalettized(metadata.format) || IsPalettized(format) || IsTypeless(metadata.format) || IsTypeless(format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if ((metadata.width > UINT32_MAX) || (metadata.height > UINT32_MAX)) return E_INVALIDARG; @@ -5049,7 +5079,7 @@ HRESULT DirectX::ConvertToSinglePlane(const Image& srcImage, ScratchImage& image DXGI_FORMAT format = _PlanarToSingle(srcImage.format); if (format == DXGI_FORMAT_UNKNOWN) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if ((srcImage.width > UINT32_MAX) || (srcImage.height > UINT32_MAX)) return E_INVALIDARG; @@ -5092,12 +5122,12 @@ HRESULT DirectX::ConvertToSinglePlane( if (metadata.IsVolumemap()) { // Direct3D does not support any planar formats for Texture3D - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } DXGI_FORMAT format = _PlanarToSingle(metadata.format); if (format == DXGI_FORMAT_UNKNOWN) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if ((metadata.width > UINT32_MAX) || (metadata.height > UINT32_MAX)) return E_INVALIDARG; diff --git a/Kits/DirectXTex/DirectXTexD3D11.cpp b/Kits/DirectXTex/DirectXTexD3D11.cpp index 00c7127d..71be0a3b 100644 --- a/Kits/DirectXTex/DirectXTexD3D11.cpp +++ b/Kits/DirectXTex/DirectXTexD3D11.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexD3D11.cpp -// +// // DirectX Texture Library - Direct3D 11 helpers // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -117,7 +117,7 @@ namespace for (size_t h = 0; h < lines; ++h) { size_t msize = std::min(img->rowPitch, mapped.RowPitch); - memcpy_s(dptr, img->rowPitch, sptr, msize); + memcpy(dptr, sptr, msize); sptr += mapped.RowPitch; dptr += img->rowPitch; } @@ -176,7 +176,7 @@ namespace for (size_t h = 0; h < lines; ++h) { size_t msize = std::min(img->rowPitch, mapped.RowPitch); - memcpy_s(dptr, img->rowPitch, sptr, msize); + memcpy(dptr, sptr, msize); sptr += mapped.RowPitch; dptr += img->rowPitch; } @@ -454,7 +454,7 @@ HRESULT DirectX::CreateTextureEx( if (metadata.arraySize > 1) // Direct3D 11 doesn't support arrays of 3D textures - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; size_t depth = metadata.depth; diff --git a/Kits/DirectXTex/DirectXTexDDS.cpp b/Kits/DirectXTex/DirectXTexDDS.cpp index 9a5d323f..d1e382d1 100644 --- a/Kits/DirectXTex/DirectXTexDDS.cpp +++ b/Kits/DirectXTex/DirectXTexDDS.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexDDS.cpp -// +// // DirectX Texture Library - Microsoft DirectDraw Surface (DDS) file format reader/writer // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -41,9 +41,9 @@ namespace CONV_FLAGS_A8P8 = 0x800, // Has an 8-bit palette with an alpha channel CONV_FLAGS_DX10 = 0x10000, // Has the 'DX10' extension header CONV_FLAGS_PMALPHA = 0x20000, // Contains premultiplied alpha data - CONV_FLAGS_L8 = 0x40000, // Source is a 8 luminance format - CONV_FLAGS_L16 = 0x80000, // Source is a 16 luminance format - CONV_FLAGS_A8L8 = 0x100000, // Source is a 8:8 luminance format + CONV_FLAGS_L8 = 0x40000, // Source is a 8 luminance format + CONV_FLAGS_L16 = 0x80000, // Source is a 16 luminance format + CONV_FLAGS_A8L8 = 0x100000, // Source is a 8:8 luminance format }; struct LegacyDDS @@ -100,11 +100,16 @@ namespace { DXGI_FORMAT_B5G6R5_UNORM, CONV_FLAGS_EXPAND | CONV_FLAGS_332, DDSPF_R3G3B2 }, // D3DFMT_R3G3B2 - { DXGI_FORMAT_R8_UNORM, CONV_FLAGS_NONE, DDSPF_L8 }, // D3DFMT_L8 - { DXGI_FORMAT_R16_UNORM, CONV_FLAGS_NONE, DDSPF_L16 }, // D3DFMT_L16 + { DXGI_FORMAT_R8_UNORM, CONV_FLAGS_NONE, DDSPF_L8 }, // D3DFMT_L8 + { DXGI_FORMAT_R16_UNORM, CONV_FLAGS_NONE, DDSPF_L16 }, // D3DFMT_L16 { DXGI_FORMAT_R8G8_UNORM, CONV_FLAGS_NONE, DDSPF_A8L8 }, // D3DFMT_A8L8 { DXGI_FORMAT_R8G8_UNORM, CONV_FLAGS_NONE, DDSPF_A8L8_ALT }, // D3DFMT_A8L8 (alternative bitcount) + // NVTT v1 wrote these with RGB instead of LUMINANCE + { DXGI_FORMAT_R8_UNORM, CONV_FLAGS_NONE, DDSPF_L8_NVTT1 }, // D3DFMT_L8 + { DXGI_FORMAT_R16_UNORM, CONV_FLAGS_NONE, DDSPF_L16_NVTT1 }, // D3DFMT_L16 + { DXGI_FORMAT_R8G8_UNORM, CONV_FLAGS_NONE, DDSPF_A8L8_NVTT1 }, // D3DFMT_A8L8 + { DXGI_FORMAT_A8_UNORM, CONV_FLAGS_NONE, DDSPF_A8 }, // D3DFMT_A8 { DXGI_FORMAT_R16G16B16A16_UNORM, CONV_FLAGS_NONE, { sizeof(DDS_PIXELFORMAT), DDS_FOURCC, 36, 0, 0, 0, 0, 0 } }, // D3DFMT_A16B16G16R16 @@ -284,7 +289,7 @@ namespace if (size < (sizeof(DDS_HEADER) + sizeof(uint32_t))) { - return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + return HRESULT_E_INVALID_DATA; } // DDS files always start with the same magic number ("DDS ") @@ -323,13 +328,13 @@ namespace metadata.arraySize = d3d10ext->arraySize; if (metadata.arraySize == 0) { - return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + return HRESULT_E_INVALID_DATA; } metadata.format = d3d10ext->dxgiFormat; if (!IsValid(metadata.format) || IsPalettized(metadata.format)) { - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } static_assert(static_cast(TEX_MISC_TEXTURECUBE) == static_cast(DDS_RESOURCE_MISC_TEXTURECUBE), "DDS header mismatch"); @@ -343,7 +348,7 @@ namespace // D3DX writes 1D textures with a fixed Height of 1 if ((pHeader->flags & DDS_HEIGHT) && pHeader->height != 1) { - return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + return HRESULT_E_INVALID_DATA; } metadata.width = pHeader->width; @@ -368,11 +373,11 @@ namespace case DDS_DIMENSION_TEXTURE3D: if (!(pHeader->flags & DDS_HEADER_FLAGS_VOLUME)) { - return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + return HRESULT_E_INVALID_DATA; } if (metadata.arraySize > 1) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; metadata.width = pHeader->width; metadata.height = pHeader->height; @@ -381,7 +386,7 @@ namespace break; default: - return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + return HRESULT_E_INVALID_DATA; } static_assert(static_cast(TEX_MISC2_ALPHA_MODE_MASK) == static_cast(DDS_MISC_FLAGS2_ALPHA_MODE_MASK), "DDS header mismatch"); @@ -411,7 +416,7 @@ namespace { // We require all six faces to be defined if ((pHeader->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; metadata.arraySize = 6; metadata.miscFlags |= TEX_MISC_TEXTURECUBE; @@ -428,7 +433,7 @@ namespace metadata.format = GetDXGIFormat(*pHeader, pHeader->ddspf, flags, convFlags); if (metadata.format == DXGI_FORMAT_UNKNOWN) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; // Special flag for handling LUMINANCE legacy formats if (flags & DDS_FLAGS_EXPAND_LUMINANCE) @@ -504,10 +509,10 @@ namespace case DXGI_FORMAT_B5G6R5_UNORM: case DXGI_FORMAT_B5G5R5A1_UNORM: case DXGI_FORMAT_B4G4R4A4_UNORM: - metadata.format = DXGI_FORMAT_R8G8B8A8_UNORM; - convFlags |= CONV_FLAGS_EXPAND; if (metadata.format == DXGI_FORMAT_B5G6R5_UNORM) convFlags |= CONV_FLAGS_NOALPHA; + metadata.format = DXGI_FORMAT_R8G8B8A8_UNORM; + convFlags |= CONV_FLAGS_EXPAND; break; default: @@ -533,14 +538,14 @@ namespace || metadata.height > 16384u /* D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION */ || metadata.mipLevels > 15u /* D3D12_REQ_MIP_LEVELS */) { - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } // 2048 is the maximum required depth/array size supported by Direct3D if (metadata.arraySize > 2048u /* D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION, D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION */ || metadata.depth > 2048u /* D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION */) { - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } } @@ -564,7 +569,7 @@ HRESULT DirectX::_EncodeDDSHeader( return E_INVALIDARG; if (IsPalettized(metadata.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if (metadata.arraySize > 1) { @@ -572,7 +577,7 @@ HRESULT DirectX::_EncodeDDSHeader( { // Texture1D arrays, Texture2D arrays, and Cubemap arrays must be stored using 'DX10' extended header if (flags & DDS_FLAGS_FORCE_DX9_LEGACY) - return HRESULT_FROM_WIN32(ERROR_CANNOT_MAKE); + return HRESULT_E_CANNOT_MAKE; flags |= DDS_FLAGS_FORCE_DX10_EXT; } @@ -588,28 +593,28 @@ HRESULT DirectX::_EncodeDDSHeader( { switch (metadata.format) { - case DXGI_FORMAT_R8G8B8A8_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_A8B8G8R8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R16G16_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_G16R16, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R8G8_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_A8L8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R16_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_L16, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R8_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_L8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_A8_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_A8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R8G8_B8G8_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_R8G8_B8G8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_G8R8_G8B8_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_G8R8_G8B8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_BC1_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_DXT1, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_BC2_UNORM: memcpy_s(&ddpf, sizeof(ddpf), metadata.IsPMAlpha() ? (&DDSPF_DXT2) : (&DDSPF_DXT3), sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_BC3_UNORM: memcpy_s(&ddpf, sizeof(ddpf), metadata.IsPMAlpha() ? (&DDSPF_DXT4) : (&DDSPF_DXT5), sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_BC4_SNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_BC4_SNORM, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_BC5_SNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_BC5_SNORM, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_B5G6R5_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_R5G6B5, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_B5G5R5A1_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_A1R5G5B5, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R8G8_SNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_V8U8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R8G8B8A8_SNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_Q8W8V8U8, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_R16G16_SNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_V16U16, sizeof(DDS_PIXELFORMAT)); break; - case DXGI_FORMAT_B8G8R8A8_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_A8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.1 - case DXGI_FORMAT_B8G8R8X8_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.1 - case DXGI_FORMAT_B4G4R4A4_UNORM: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_A4R4G4B4, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.2 - case DXGI_FORMAT_YUY2: memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_YUY2, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.2 + case DXGI_FORMAT_R8G8B8A8_UNORM: memcpy(&ddpf, &DDSPF_A8B8G8R8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R16G16_UNORM: memcpy(&ddpf, &DDSPF_G16R16, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8_UNORM: memcpy(&ddpf, &DDSPF_A8L8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R16_UNORM: memcpy(&ddpf, &DDSPF_L16, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8_UNORM: memcpy(&ddpf, &DDSPF_L8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_A8_UNORM: memcpy(&ddpf, &DDSPF_A8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8_B8G8_UNORM: memcpy(&ddpf, &DDSPF_R8G8_B8G8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_G8R8_G8B8_UNORM: memcpy(&ddpf, &DDSPF_G8R8_G8B8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC1_UNORM: memcpy(&ddpf, &DDSPF_DXT1, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC2_UNORM: memcpy(&ddpf, metadata.IsPMAlpha() ? (&DDSPF_DXT2) : (&DDSPF_DXT3), sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC3_UNORM: memcpy(&ddpf, metadata.IsPMAlpha() ? (&DDSPF_DXT4) : (&DDSPF_DXT5), sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC4_SNORM: memcpy(&ddpf, &DDSPF_BC4_SNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_BC5_SNORM: memcpy(&ddpf, &DDSPF_BC5_SNORM, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B5G6R5_UNORM: memcpy(&ddpf, &DDSPF_R5G6B5, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B5G5R5A1_UNORM: memcpy(&ddpf, &DDSPF_A1R5G5B5, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8_SNORM: memcpy(&ddpf, &DDSPF_V8U8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R8G8B8A8_SNORM: memcpy(&ddpf, &DDSPF_Q8W8V8U8, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_R16G16_SNORM: memcpy(&ddpf, &DDSPF_V16U16, sizeof(DDS_PIXELFORMAT)); break; + case DXGI_FORMAT_B8G8R8A8_UNORM: memcpy(&ddpf, &DDSPF_A8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.1 + case DXGI_FORMAT_B8G8R8X8_UNORM: memcpy(&ddpf, &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.1 + case DXGI_FORMAT_B4G4R4A4_UNORM: memcpy(&ddpf, &DDSPF_A4R4G4B4, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.2 + case DXGI_FORMAT_YUY2: memcpy(&ddpf, &DDSPF_YUY2, sizeof(DDS_PIXELFORMAT)); break; // DXGI 1.2 // Legacy D3DX formats using D3DFMT enum value as FourCC case DXGI_FORMAT_R32G32B32A32_FLOAT: @@ -642,40 +647,40 @@ HRESULT DirectX::_EncodeDDSHeader( if (flags & DDS_FLAGS_FORCE_DX9_LEGACY) { // Write using the 'incorrect' mask version to match D3DX bug - memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_A2B10G10R10, sizeof(DDS_PIXELFORMAT)); + memcpy(&ddpf, &DDSPF_A2B10G10R10, sizeof(DDS_PIXELFORMAT)); } break; case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: if (flags & DDS_FLAGS_FORCE_DX9_LEGACY) { - memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_A8B8G8R8, sizeof(DDS_PIXELFORMAT)); + memcpy(&ddpf, &DDSPF_A8B8G8R8, sizeof(DDS_PIXELFORMAT)); } break; case DXGI_FORMAT_BC1_UNORM_SRGB: if (flags & DDS_FLAGS_FORCE_DX9_LEGACY) { - memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_DXT1, sizeof(DDS_PIXELFORMAT)); + memcpy(&ddpf, &DDSPF_DXT1, sizeof(DDS_PIXELFORMAT)); } break; case DXGI_FORMAT_BC2_UNORM_SRGB: if (flags & DDS_FLAGS_FORCE_DX9_LEGACY) { - memcpy_s(&ddpf, sizeof(ddpf), metadata.IsPMAlpha() ? (&DDSPF_DXT2) : (&DDSPF_DXT3), sizeof(DDS_PIXELFORMAT)); + memcpy(&ddpf, metadata.IsPMAlpha() ? (&DDSPF_DXT2) : (&DDSPF_DXT3), sizeof(DDS_PIXELFORMAT)); } break; case DXGI_FORMAT_BC3_UNORM_SRGB: if (flags & DDS_FLAGS_FORCE_DX9_LEGACY) { - memcpy_s(&ddpf, sizeof(ddpf), metadata.IsPMAlpha() ? (&DDSPF_DXT4) : (&DDSPF_DXT5), sizeof(DDS_PIXELFORMAT)); + memcpy(&ddpf, metadata.IsPMAlpha() ? (&DDSPF_DXT4) : (&DDSPF_DXT5), sizeof(DDS_PIXELFORMAT)); } break; case DXGI_FORMAT_BC4_UNORM: - memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_BC4_UNORM, sizeof(DDS_PIXELFORMAT)); + memcpy(&ddpf, &DDSPF_BC4_UNORM, sizeof(DDS_PIXELFORMAT)); if (flags & DDS_FLAGS_FORCE_DX9_LEGACY) { ddpf.fourCC = MAKEFOURCC('A', 'T', 'I', '1'); @@ -683,7 +688,7 @@ HRESULT DirectX::_EncodeDDSHeader( break; case DXGI_FORMAT_BC5_UNORM: - memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_BC5_UNORM, sizeof(DDS_PIXELFORMAT)); + memcpy(&ddpf, &DDSPF_BC5_UNORM, sizeof(DDS_PIXELFORMAT)); if (flags & DDS_FLAGS_FORCE_DX9_LEGACY) { ddpf.fourCC = MAKEFOURCC('A', 'T', 'I', '2'); @@ -693,14 +698,14 @@ HRESULT DirectX::_EncodeDDSHeader( case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: if (flags & DDS_FLAGS_FORCE_DX9_LEGACY) { - memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_A8R8G8B8, sizeof(DDS_PIXELFORMAT)); + memcpy(&ddpf, &DDSPF_A8R8G8B8, sizeof(DDS_PIXELFORMAT)); } break; case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: if (flags & DDS_FLAGS_FORCE_DX9_LEGACY) { - memcpy_s(&ddpf, sizeof(ddpf), &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT)); + memcpy(&ddpf, &DDSPF_X8R8G8B8, sizeof(DDS_PIXELFORMAT)); } break; @@ -714,7 +719,7 @@ HRESULT DirectX::_EncodeDDSHeader( if (ddpf.size == 0) { if (flags & DDS_FLAGS_FORCE_DX9_LEGACY) - return HRESULT_FROM_WIN32(ERROR_CANNOT_MAKE); + return HRESULT_E_CANNOT_MAKE; required += sizeof(DDS_HEADER_DXT10); } @@ -813,7 +818,7 @@ HRESULT DirectX::_EncodeDDSHeader( if (ddpf.size == 0) { - memcpy_s(&header->ddspf, sizeof(header->ddspf), &DDSPF_DX10, sizeof(DDS_PIXELFORMAT)); + memcpy(&header->ddspf, &DDSPF_DX10, sizeof(DDS_PIXELFORMAT)); auto ext = reinterpret_cast(reinterpret_cast(header) + sizeof(DDS_HEADER)); assert(ext); @@ -856,7 +861,7 @@ HRESULT DirectX::_EncodeDDSHeader( } else { - memcpy_s(&header->ddspf, sizeof(header->ddspf), &ddpf, sizeof(ddpf)); + memcpy(&header->ddspf, &ddpf, sizeof(ddpf)); } return S_OK; @@ -1074,7 +1079,7 @@ namespace switch (outFormat) { case DXGI_FORMAT_B4G4R4A4_UNORM: - // D3DFMT_A4L4 -> DXGI_FORMAT_B4G4R4A4_UNORM + // D3DFMT_A4L4 -> DXGI_FORMAT_B4G4R4A4_UNORM if (inSize >= 1 && outSize >= 2) { const uint8_t * __restrict sPtr = static_cast(pSource); @@ -1249,7 +1254,7 @@ namespace size_t pixelSize, nimages; if (!_DetermineImageArray(metadata, cpFlags, nimages, pixelSize)) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; if ((nimages == 0) || (nimages != image.GetImageCount())) { @@ -1258,7 +1263,7 @@ namespace if (pixelSize > size) { - return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); + return HRESULT_E_HANDLE_EOF; } std::unique_ptr timages(new (std::nothrow) Image[nimages]); @@ -1324,14 +1329,14 @@ namespace if (IsCompressed(metadata.format)) { size_t csize = std::min(images[index].slicePitch, timages[index].slicePitch); - memcpy_s(pDest, images[index].slicePitch, pSrc, csize); + memcpy(pDest, pSrc, csize); if (cpFlags & CP_FLAGS_BAD_DXTN_TAILS) { if (images[index].width < 4 || images[index].height < 4) { csize = std::min(images[index].slicePitch, timages[lastgood].slicePitch); - memcpy_s(pDest, images[index].slicePitch, timages[lastgood].pixels, csize); + memcpy(pDest, timages[lastgood].pixels, csize); } else { @@ -1348,7 +1353,7 @@ namespace size_t csize = std::min(dpitch, spitch); for (size_t h = 0; h < count; ++h) { - memcpy_s(pDest, dpitch, pSrc, csize); + memcpy(pDest, pSrc, csize); pSrc += spitch; pDest += dpitch; } @@ -1426,14 +1431,14 @@ namespace if (IsCompressed(metadata.format)) { size_t csize = std::min(images[index].slicePitch, timages[index].slicePitch); - memcpy_s(pDest, images[index].slicePitch, pSrc, csize); + memcpy(pDest, pSrc, csize); if (cpFlags & CP_FLAGS_BAD_DXTN_TAILS) { if (images[index].width < 4 || images[index].height < 4) { csize = std::min(images[index].slicePitch, timages[lastgood + slice].slicePitch); - memcpy_s(pDest, images[index].slicePitch, timages[lastgood + slice].pixels, csize); + memcpy(pDest, timages[lastgood + slice].pixels, csize); } else if (!slice) { @@ -1444,7 +1449,7 @@ namespace else if (IsPlanar(metadata.format)) { // Direct3D does not support any planar formats for Texture3D - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } else { @@ -1509,7 +1514,7 @@ namespace const TexMetadata& metadata = image.GetMetadata(); if (IsPlanar(metadata.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; uint32_t tflags = (convFlags & CONV_FLAGS_NOALPHA) ? TEXP_SCANLINE_SETALPHA : 0u; if (convFlags & CONV_FLAGS_SWIZZLE) @@ -1575,6 +1580,7 @@ HRESULT DirectX::GetMetadataFromDDSFile( if (!szFile) return E_INVALIDARG; +#ifdef WIN32 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr))); #else @@ -1596,11 +1602,31 @@ HRESULT DirectX::GetMetadataFromDDSFile( // File is too big for 32-bit allocation, so reject read (4 GB should be plenty large enough for a valid DDS file) if (fileInfo.EndOfFile.HighPart > 0) { - return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); + return HRESULT_E_FILE_TOO_LARGE; } + size_t len = fileInfo.EndOfFile.LowPart; +#else // !WIN32 + std::ifstream inFile(std::filesystem::path(szFile), std::ios::in | std::ios::binary | std::ios::ate); + if (!inFile) + return E_FAIL; + + std::streampos fileLen = inFile.tellg(); + if (!inFile) + return E_FAIL; + + if (fileLen > UINT32_MAX) + return HRESULT_E_FILE_TOO_LARGE; + + inFile.seekg(0, std::ios::beg); + if (!inFile) + return E_FAIL; + + size_t len = fileLen; +#endif + // Need at least enough data to fill the standard header and magic number to be a valid DDS - if (fileInfo.EndOfFile.LowPart < (sizeof(DDS_HEADER) + sizeof(uint32_t))) + if (len < (sizeof(DDS_HEADER) + sizeof(uint32_t))) { return E_FAIL; } @@ -1609,14 +1635,24 @@ HRESULT DirectX::GetMetadataFromDDSFile( const size_t MAX_HEADER_SIZE = sizeof(uint32_t) + sizeof(DDS_HEADER) + sizeof(DDS_HEADER_DXT10); uint8_t header[MAX_HEADER_SIZE] = {}; +#ifdef WIN32 DWORD bytesRead = 0; if (!ReadFile(hFile.get(), header, MAX_HEADER_SIZE, &bytesRead, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); } + auto headerLen = static_cast(bytesRead); +#else + auto headerLen = std::min(len, MAX_HEADER_SIZE); + + inFile.read(reinterpret_cast(header), headerLen); + if (!inFile) + return E_FAIL; +#endif + uint32_t convFlags = 0; - return DecodeDDSHeader(header, bytesRead, flags, metadata, convFlags); + return DecodeDDSHeader(header, headerLen, flags, metadata, convFlags); } @@ -1708,13 +1744,13 @@ HRESULT DirectX::LoadFromDDSFile( image.Release(); +#ifdef WIN32 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr))); #else ScopedHandle hFile(safe_handle(CreateFileW(szFile, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr))); #endif - if (!hFile) { return HRESULT_FROM_WIN32(GetLastError()); @@ -1729,12 +1765,30 @@ HRESULT DirectX::LoadFromDDSFile( // File is too big for 32-bit allocation, so reject read (4 GB should be plenty large enough for a valid DDS file) if (fileInfo.EndOfFile.HighPart > 0) - { - return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); - } + return HRESULT_E_FILE_TOO_LARGE; + + size_t len = fileInfo.EndOfFile.LowPart; +#else // !WIN32 + std::ifstream inFile(std::filesystem::path(szFile), std::ios::in | std::ios::binary | std::ios::ate); + if (!inFile) + return E_FAIL; + + std::streampos fileLen = inFile.tellg(); + if (!inFile) + return E_FAIL; + + if (fileLen > UINT32_MAX) + return HRESULT_E_FILE_TOO_LARGE; + + inFile.seekg(0, std::ios::beg); + if (!inFile) + return E_FAIL; + + size_t len = fileLen; +#endif // Need at least enough data to fill the standard header and magic number to be a valid DDS - if (fileInfo.EndOfFile.LowPart < (sizeof(DDS_HEADER) + sizeof(uint32_t))) + if (len < (sizeof(DDS_HEADER) + sizeof(uint32_t))) { return E_FAIL; } @@ -1743,28 +1797,44 @@ HRESULT DirectX::LoadFromDDSFile( const size_t MAX_HEADER_SIZE = sizeof(uint32_t) + sizeof(DDS_HEADER) + sizeof(DDS_HEADER_DXT10); uint8_t header[MAX_HEADER_SIZE] = {}; +#ifdef WIN32 DWORD bytesRead = 0; if (!ReadFile(hFile.get(), header, MAX_HEADER_SIZE, &bytesRead, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); } + auto headerLen = static_cast(bytesRead); +#else + auto headerLen = std::min(len, MAX_HEADER_SIZE); + + inFile.read(reinterpret_cast(header), headerLen); + if (!inFile) + return E_FAIL; +#endif + uint32_t convFlags = 0; TexMetadata mdata; - HRESULT hr = DecodeDDSHeader(header, bytesRead, flags, mdata, convFlags); + HRESULT hr = DecodeDDSHeader(header, headerLen, flags, mdata, convFlags); if (FAILED(hr)) return hr; - DWORD offset = MAX_HEADER_SIZE; + size_t offset = MAX_HEADER_SIZE; if (!(convFlags & CONV_FLAGS_DX10)) { +#ifdef WIN32 // Must reset file position since we read more than the standard header above LARGE_INTEGER filePos = { { sizeof(uint32_t) + sizeof(DDS_HEADER), 0 } }; if (!SetFilePointerEx(hFile.get(), filePos, nullptr, FILE_BEGIN)) { return HRESULT_FROM_WIN32(GetLastError()); } +#else + inFile.seekg(sizeof(uint32_t) + sizeof(DDS_HEADER), std::ios::beg); + if (!inFile) + return E_FAIL; +#endif offset = sizeof(uint32_t) + sizeof(DDS_HEADER); } @@ -1778,6 +1848,7 @@ HRESULT DirectX::LoadFromDDSFile( return E_OUTOFMEMORY; } +#ifdef WIN32 if (!ReadFile(hFile.get(), pal8.get(), 256 * sizeof(uint32_t), &bytesRead, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); @@ -1787,11 +1858,16 @@ HRESULT DirectX::LoadFromDDSFile( { return E_FAIL; } +#else + inFile.read(reinterpret_cast(pal8.get()), 256 * sizeof(uint32_t)); + if (!inFile) + return E_FAIL; +#endif offset += (256 * sizeof(uint32_t)); } - DWORD remaining = fileInfo.EndOfFile.LowPart - offset; + size_t remaining = len - offset; if (remaining == 0) return E_FAIL; @@ -1808,7 +1884,8 @@ HRESULT DirectX::LoadFromDDSFile( return E_OUTOFMEMORY; } - if (!ReadFile(hFile.get(), temp.get(), remaining, &bytesRead, nullptr)) +#ifdef WIN32 + if (!ReadFile(hFile.get(), temp.get(), static_cast(remaining), &bytesRead, nullptr)) { image.Release(); return HRESULT_FROM_WIN32(GetLastError()); @@ -1819,6 +1896,14 @@ HRESULT DirectX::LoadFromDDSFile( image.Release(); return E_FAIL; } +#else + inFile.read(reinterpret_cast(temp.get()), remaining); + if (!inFile) + { + image.Release(); + return E_FAIL; + } +#endif CP_FLAGS cflags = CP_FLAGS_NONE; if (flags & DDS_FLAGS_LEGACY_DWORD) @@ -1848,20 +1933,29 @@ HRESULT DirectX::LoadFromDDSFile( if (remaining < image.GetPixelsSize()) { image.Release(); - return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); + return HRESULT_E_HANDLE_EOF; } if (image.GetPixelsSize() > UINT32_MAX) { image.Release(); - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; } +#ifdef WIN32 if (!ReadFile(hFile.get(), image.GetPixels(), static_cast(image.GetPixelsSize()), &bytesRead, nullptr)) { image.Release(); return HRESULT_FROM_WIN32(GetLastError()); } +#else + inFile.read(reinterpret_cast(image.GetPixels()), image.GetPixelsSize()); + if (!inFile) + { + image.Release(); + return E_FAIL; + } +#endif if (convFlags & (CONV_FLAGS_SWIZZLE | CONV_FLAGS_NOALPHA)) { @@ -1974,11 +2068,7 @@ HRESULT DirectX::SaveToDDSMemory( if (fastpath) { size_t pixsize = images[index].slicePitch; - if (memcpy_s(pDestination, remaining, images[index].pixels, pixsize)) - { - blob.Release(); - return E_FAIL; - } + memcpy(pDestination, images[index].pixels, pixsize); pDestination += pixsize; remaining -= pixsize; @@ -2003,11 +2093,7 @@ HRESULT DirectX::SaveToDDSMemory( size_t tremaining = remaining; for (size_t j = 0; j < lines; ++j) { - if (memcpy_s(dPtr, tremaining, sPtr, csize)) - { - blob.Release(); - return E_FAIL; - } + memcpy(dPtr, sPtr, csize); sPtr += rowPitch; dPtr += ddsRowPitch; @@ -2048,11 +2134,7 @@ HRESULT DirectX::SaveToDDSMemory( if (fastpath) { size_t pixsize = images[index].slicePitch; - if (memcpy_s(pDestination, remaining, images[index].pixels, pixsize)) - { - blob.Release(); - return E_FAIL; - } + memcpy(pDestination, images[index].pixels, pixsize); pDestination += pixsize; remaining -= pixsize; @@ -2077,11 +2159,7 @@ HRESULT DirectX::SaveToDDSMemory( size_t tremaining = remaining; for (size_t j = 0; j < lines; ++j) { - if (memcpy_s(dPtr, tremaining, sPtr, csize)) - { - blob.Release(); - return E_FAIL; - } + memcpy(dPtr, sPtr, csize); sPtr += rowPitch; dPtr += ddsRowPitch; @@ -2133,10 +2211,13 @@ HRESULT DirectX::SaveToDDSFile( return hr; // Create file and write header +#ifdef WIN32 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) - ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_WRITE | DELETE, 0, CREATE_ALWAYS, nullptr))); + ScopedHandle hFile(safe_handle(CreateFile2(szFile, + GENERIC_WRITE | DELETE, 0, CREATE_ALWAYS, nullptr))); #else - ScopedHandle hFile(safe_handle(CreateFileW(szFile, GENERIC_WRITE | DELETE, 0, nullptr, CREATE_ALWAYS, 0, nullptr))); + ScopedHandle hFile(safe_handle(CreateFileW(szFile, + GENERIC_WRITE | DELETE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr))); #endif if (!hFile) { @@ -2155,6 +2236,15 @@ HRESULT DirectX::SaveToDDSFile( { return E_FAIL; } +#else // !WIN32 + std::ofstream outFile(std::filesystem::path(szFile), std::ios::out | std::ios::binary | std::ios::trunc); + if (!outFile) + return E_FAIL; + + outFile.write(reinterpret_cast(header), static_cast(required)); + if (!outFile) + return E_FAIL; +#endif // Write images switch (static_cast(metadata.dimension)) @@ -2183,6 +2273,7 @@ HRESULT DirectX::SaveToDDSFile( if ((images[index].slicePitch == ddsSlicePitch) && (ddsSlicePitch <= UINT32_MAX)) { +#ifdef WIN32 if (!WriteFile(hFile.get(), images[index].pixels, static_cast(ddsSlicePitch), &bytesWritten, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); @@ -2192,6 +2283,11 @@ HRESULT DirectX::SaveToDDSFile( { return E_FAIL; } +#else + outFile.write(reinterpret_cast(images[index].pixels), static_cast(ddsSlicePitch)); + if (!outFile) + return E_FAIL; +#endif } else { @@ -2203,13 +2299,14 @@ HRESULT DirectX::SaveToDDSFile( } if (ddsRowPitch > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; const uint8_t * __restrict sPtr = images[index].pixels; size_t lines = ComputeScanlines(metadata.format, images[index].height); for (size_t j = 0; j < lines; ++j) { +#ifdef WIN32 if (!WriteFile(hFile.get(), sPtr, static_cast(ddsRowPitch), &bytesWritten, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); @@ -2219,6 +2316,11 @@ HRESULT DirectX::SaveToDDSFile( { return E_FAIL; } +#else + outFile.write(reinterpret_cast(sPtr), static_cast(ddsRowPitch)); + if (!outFile) + return E_FAIL; +#endif sPtr += rowPitch; } @@ -2256,6 +2358,7 @@ HRESULT DirectX::SaveToDDSFile( if ((images[index].slicePitch == ddsSlicePitch) && (ddsSlicePitch <= UINT32_MAX)) { +#ifdef WIN32 if (!WriteFile(hFile.get(), images[index].pixels, static_cast(ddsSlicePitch), &bytesWritten, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); @@ -2265,6 +2368,11 @@ HRESULT DirectX::SaveToDDSFile( { return E_FAIL; } +#else + outFile.write(reinterpret_cast(images[index].pixels), static_cast(ddsSlicePitch)); + if (!outFile) + return E_FAIL; +#endif } else { @@ -2276,13 +2384,14 @@ HRESULT DirectX::SaveToDDSFile( } if (ddsRowPitch > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; const uint8_t * __restrict sPtr = images[index].pixels; size_t lines = ComputeScanlines(metadata.format, images[index].height); for (size_t j = 0; j < lines; ++j) { +#ifdef WIN32 if (!WriteFile(hFile.get(), sPtr, static_cast(ddsRowPitch), &bytesWritten, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); @@ -2292,7 +2401,11 @@ HRESULT DirectX::SaveToDDSFile( { return E_FAIL; } - +#else + outFile.write(reinterpret_cast(sPtr), static_cast(ddsRowPitch)); + if (!outFile) + return E_FAIL; +#endif sPtr += rowPitch; } } @@ -2308,7 +2421,9 @@ HRESULT DirectX::SaveToDDSFile( return E_FAIL; } +#ifdef WIN32 delonfail.clear(); +#endif return S_OK; } diff --git a/Kits/DirectXTex/DirectXTexFlipRotate.cpp b/Kits/DirectXTex/DirectXTexFlipRotate.cpp index 5f6c789a..70444279 100644 --- a/Kits/DirectXTex/DirectXTexFlipRotate.cpp +++ b/Kits/DirectXTex/DirectXTexFlipRotate.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexFlipRotate.cpp -// +// // DirectX Texture Library - Image flip/rotate operations // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -37,7 +37,7 @@ namespace if (srcImage.rowPitch > UINT32_MAX || srcImage.slicePitch > UINT32_MAX || destImage.rowPitch > UINT32_MAX || destImage.slicePitch > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; ComPtr source; HRESULT hr = pWIC->CreateBitmapFromMemory(static_cast(srcImage.width), static_cast(srcImage.height), pfGUID, @@ -63,7 +63,7 @@ namespace if (memcmp(&pfFR, &pfGUID, sizeof(GUID)) != 0) { // Flip/rotate should return the same format as the source... - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } UINT nwidth, nheight; @@ -199,7 +199,7 @@ HRESULT DirectX::FlipRotate( if (IsCompressed(srcImage.format)) { // We don't support flip/rotate operations on compressed images - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } static_assert(static_cast(TEX_FR_ROTATE0) == static_cast(WICBitmapTransformRotate0), "TEX_FR_ROTATE0 no longer matches WIC"); @@ -292,7 +292,7 @@ HRESULT DirectX::FlipRotate( if (IsCompressed(metadata.format)) { // We don't support flip/rotate operations on compressed images - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } static_assert(static_cast(TEX_FR_ROTATE0) == static_cast(WICBitmapTransformRotate0), "TEX_FR_ROTATE0 no longer matches WIC"); diff --git a/Kits/DirectXTex/DirectXTexHDR.cpp b/Kits/DirectXTex/DirectXTexHDR.cpp index f00d19a4..87218c60 100644 --- a/Kits/DirectXTex/DirectXTexHDR.cpp +++ b/Kits/DirectXTex/DirectXTexHDR.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexHDR.cpp -// +// // DirectX Texture Library - Radiance HDR (RGBE) file format reader/writer // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -17,10 +17,10 @@ // +X width -Y height // -X width +Y height // -X width -Y height -// +Y height +X width -// -Y height +X width -// +Y height -X width -// -Y height -X width +// +Y height +X width +// -Y height +X width +// +Y height -X width +// -Y height -X width // // All HDR files we've encountered are always written as "-Y height +X width", so // we support only that one as that's what other Radiance parsing code does as well. @@ -34,6 +34,13 @@ using namespace DirectX; +#ifndef WIN32 +#include + +#define strncpy_s strncpy +#define sscanf_s sscanf +#endif + namespace { const char g_Signature[] = "#?RADIANCE"; @@ -70,6 +77,19 @@ namespace return 0; } +#ifndef WIN32 + template + inline int sprintf_s(char (&buffer)[sizeOfBuffer], const char* format, ...) + { + // This is adapter code. It is not a full implementation of sprintf_s! + va_list ap; + va_start(ap, format); + int result = vsprintf(buffer, format, ap); + va_end(ap); + return result; + } +#endif + //------------------------------------------------------------------------------------- // Decodes HDR header //------------------------------------------------------------------------------------- @@ -86,10 +106,10 @@ namespace memset(&metadata, 0, sizeof(TexMetadata)); exposure = 1.f; - + if (size < sizeof(g_Signature)) { - return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + return HRESULT_E_INVALID_DATA; } // Verify magic signature @@ -137,7 +157,7 @@ namespace if (memcmp(info, g_sRGBE, encodingLen) != 0 && memcmp(info, g_sXYZE, encodingLen) != 0) { - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } formatFound = true; @@ -217,10 +237,8 @@ namespace if (orientation[0] != '-' && orientation[1] != 'Y') { // We only support the -Y +X orientation (see top of file) - return HRESULT_FROM_WIN32( - static_cast(((orientation[0] == '+' || orientation[0] == '-') && (orientation[1] == 'X' || orientation[1] == 'Y')) - ? ERROR_NOT_SUPPORTED : ERROR_INVALID_DATA) - ); + return (static_cast(((orientation[0] == '+' || orientation[0] == '-') && (orientation[1] == 'X' || orientation[1] == 'Y')))) + ? HRESULT_E_NOT_SUPPORTED : HRESULT_E_INVALID_DATA; } uint32_t height = 0; @@ -240,7 +258,7 @@ namespace else if (*ptr != '+') { // We only support the -Y +X orientation (see top of file) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } ++ptr; @@ -251,7 +269,7 @@ namespace else if (*ptr != 'X') { // We only support the -Y +X orientation (see top of file) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } ++ptr; @@ -266,7 +284,7 @@ namespace if (!width || !height) { - return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + return HRESULT_E_INVALID_DATA; } if (size == 0) @@ -580,6 +598,7 @@ HRESULT DirectX::GetMetadataFromHDRFile(const wchar_t* szFile, TexMetadata& meta if (!szFile) return E_INVALIDARG; +#ifdef WIN32 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr))); #else @@ -601,26 +620,57 @@ HRESULT DirectX::GetMetadataFromHDRFile(const wchar_t* szFile, TexMetadata& meta // File is too big for 32-bit allocation, so reject read (4 GB should be plenty large enough for a valid HDR file) if (fileInfo.EndOfFile.HighPart > 0) { - return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); + return HRESULT_E_FILE_TOO_LARGE; } + size_t len = fileInfo.EndOfFile.LowPart; +#else // !WIN32 + std::ifstream inFile(std::filesystem::path(szFile), std::ios::in | std::ios::binary | std::ios::ate); + if (!inFile) + return E_FAIL; + + std::streampos fileLen = inFile.tellg(); + if (!inFile) + return E_FAIL; + + if (fileLen > UINT32_MAX) + return HRESULT_E_FILE_TOO_LARGE; + + inFile.seekg(0, std::ios::beg); + if (!inFile) + return E_FAIL; + + size_t len = fileLen; +#endif + // Need at least enough data to fill the standard header to be a valid HDR - if (fileInfo.EndOfFile.LowPart < sizeof(g_Signature)) + if (len < sizeof(g_Signature)) { return E_FAIL; } // Read the first part of the file to find the header uint8_t header[8192] = {}; + +#ifdef WIN32 DWORD bytesRead = 0; if (!ReadFile(hFile.get(), header, std::min(sizeof(header), fileInfo.EndOfFile.LowPart), &bytesRead, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); } + auto headerLen = static_cast(bytesRead); +#else + auto headerLen = std::min(sizeof(header), len); + + inFile.read(reinterpret_cast(header), headerLen); + if (!inFile) + return E_FAIL; +#endif + size_t offset; float exposure; - return DecodeHDRHeader(header, bytesRead, metadata, offset, exposure); + return DecodeHDRHeader(header, headerLen, metadata, offset, exposure); } @@ -685,7 +735,7 @@ HRESULT DirectX::LoadFromHDRMemory(const void* pSource, size_t size, TexMetadata pixelLen -= 4; auto scanLine = reinterpret_cast(destPtr); - + if (inColor[0] == 2 && inColor[1] == 2 && inColor[2] < 128) { // Adaptive Run Length Encoding (RLE) @@ -852,6 +902,7 @@ HRESULT DirectX::LoadFromHDRFile(const wchar_t* szFile, TexMetadata* metadata, S image.Release(); +#ifdef WIN32 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr))); #else @@ -873,22 +924,43 @@ HRESULT DirectX::LoadFromHDRFile(const wchar_t* szFile, TexMetadata* metadata, S // File is too big for 32-bit allocation, so reject read (4 GB should be plenty large enough for a valid HDR file) if (fileInfo.EndOfFile.HighPart > 0) { - return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); + return HRESULT_E_FILE_TOO_LARGE; } + size_t len = fileInfo.EndOfFile.LowPart; +#else // !WIN32 + std::ifstream inFile(std::filesystem::path(szFile), std::ios::in | std::ios::binary | std::ios::ate); + if (!inFile) + return E_FAIL; + + std::streampos fileLen = inFile.tellg(); + if (!inFile) + return E_FAIL; + + if (fileLen > UINT32_MAX) + return HRESULT_E_FILE_TOO_LARGE; + + inFile.seekg(0, std::ios::beg); + if (!inFile) + return E_FAIL; + + size_t len = fileLen; +#endif + // Need at least enough data to fill the header to be a valid HDR - if (fileInfo.EndOfFile.LowPart < sizeof(g_Signature)) + if (len < sizeof(g_Signature)) { return E_FAIL; } // Read file - std::unique_ptr temp(new (std::nothrow) uint8_t[fileInfo.EndOfFile.LowPart]); + std::unique_ptr temp(new (std::nothrow) uint8_t[len]); if (!temp) { return E_OUTOFMEMORY; } +#ifdef WIN32 DWORD bytesRead = 0; if (!ReadFile(hFile.get(), temp.get(), fileInfo.EndOfFile.LowPart, &bytesRead, nullptr)) { @@ -899,8 +971,13 @@ HRESULT DirectX::LoadFromHDRFile(const wchar_t* szFile, TexMetadata* metadata, S { return E_FAIL; } +#else + inFile.read(reinterpret_cast(temp.get()), len); + if (!inFile) + return E_FAIL; +#endif - return LoadFromHDRMemory(temp.get(), fileInfo.EndOfFile.LowPart, metadata, image); + return LoadFromHDRMemory(temp.get(), len, metadata, image); } @@ -917,7 +994,7 @@ HRESULT DirectX::SaveToHDRMemory(const Image& image, Blob& blob) noexcept { // Images larger than this can't be RLE encoded. They are technically allowed as // uncompresssed, but we just don't support them. - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } int fpp; @@ -932,7 +1009,7 @@ HRESULT DirectX::SaveToHDRMemory(const Image& image, Blob& blob) noexcept break; default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } blob.Release(); @@ -952,7 +1029,7 @@ HRESULT DirectX::SaveToHDRMemory(const Image& image, Blob& blob) noexcept // Copy header auto dPtr = static_cast(blob.GetBufferPointer()); assert(dPtr != nullptr); - memcpy_s(dPtr, blob.GetBufferSize(), header, headerLen); + memcpy(dPtr, header, headerLen); dPtr += headerLen; #ifdef DISABLE_COMPRESS @@ -1029,7 +1106,7 @@ HRESULT DirectX::SaveToHDRFile(const Image& image, const wchar_t* szFile) noexce { // Images larger than this can't be RLE encoded. They are technically allowed as // uncompresssed, but we just don't support them. - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } int fpp; @@ -1044,14 +1121,17 @@ HRESULT DirectX::SaveToHDRFile(const Image& image, const wchar_t* szFile) noexce break; default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } // Create file and write header +#ifdef WIN32 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) - ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr))); + ScopedHandle hFile(safe_handle(CreateFile2(szFile, + GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr))); #else - ScopedHandle hFile(safe_handle(CreateFileW(szFile, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr))); + ScopedHandle hFile(safe_handle(CreateFileW(szFile, + GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr))); #endif if (!hFile) { @@ -1059,12 +1139,17 @@ HRESULT DirectX::SaveToHDRFile(const Image& image, const wchar_t* szFile) noexce } auto_delete_file delonfail(hFile.get()); +#else // !WIN32 + std::ofstream outFile(std::filesystem::path(szFile), std::ios::out | std::ios::binary | std::ios::trunc); + if (!outFile) + return E_FAIL; +#endif uint64_t pitch = uint64_t(image.width) * 4u; uint64_t slicePitch = uint64_t(image.height) * pitch; if (pitch > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; size_t rowPitch = static_cast(pitch); @@ -1078,6 +1163,7 @@ HRESULT DirectX::SaveToHDRFile(const Image& image, const wchar_t* szFile) noexce return hr; // Write blob +#ifdef WIN32 auto bytesToWrite = static_cast(blob.GetBufferSize()); DWORD bytesWritten; if (!WriteFile(hFile.get(), blob.GetBufferPointer(), bytesToWrite, &bytesWritten, nullptr)) @@ -1089,6 +1175,13 @@ HRESULT DirectX::SaveToHDRFile(const Image& image, const wchar_t* szFile) noexce { return E_FAIL; } +#else + outFile.write(reinterpret_cast(blob.GetBufferPointer()), + static_cast(blob.GetBufferSize())); + + if (!outFile) + return E_FAIL; +#endif } else { @@ -1103,6 +1196,7 @@ HRESULT DirectX::SaveToHDRFile(const Image& image, const wchar_t* szFile) noexce char header[256] = {}; sprintf_s(header, g_Header, image.height, image.width); +#ifdef WIN32 auto headerLen = static_cast(strlen(header)); DWORD bytesWritten; @@ -1113,6 +1207,11 @@ HRESULT DirectX::SaveToHDRFile(const Image& image, const wchar_t* szFile) noexce if (bytesWritten != headerLen) return E_FAIL; +#else + outFile.write(reinterpret_cast(header), static_cast(strlen(header))); + if (!outFile) + return E_FAIL; +#endif #ifdef DISABLE_COMPRESS // Uncompressed write @@ -1122,6 +1221,7 @@ HRESULT DirectX::SaveToHDRFile(const Image& image, const wchar_t* szFile) noexce FloatToRGBE(rgbe, reinterpret_cast(sPtr), image.width, fpp); sPtr += image.rowPitch; + #ifdef WIN32 if (!WriteFile(hFile.get(), rgbe, static_cast(rowPitch), &bytesWritten, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); @@ -1129,6 +1229,12 @@ HRESULT DirectX::SaveToHDRFile(const Image& image, const wchar_t* szFile) noexce if (bytesWritten != rowPitch) return E_FAIL; + #else + outFile.write(reinterpret_cast(rgbe), static_cast(rowPitch)); + if (!outFile) + return E_FAIL; + #endif + } #else auto enc = temp.get() + rowPitch; @@ -1150,8 +1256,9 @@ HRESULT DirectX::SaveToHDRFile(const Image& image, const wchar_t* szFile) noexce if (encSize > 0) { if (encSize > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; +#ifdef WIN32 if (!WriteFile(hFile.get(), enc, static_cast(encSize), &bytesWritten, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); @@ -1159,9 +1266,15 @@ HRESULT DirectX::SaveToHDRFile(const Image& image, const wchar_t* szFile) noexce if (bytesWritten != encSize) return E_FAIL; +#else + outFile.write(reinterpret_cast(enc), static_cast(encSize)); + if (!outFile) + return E_FAIL; +#endif } else { +#ifdef WIN32 if (!WriteFile(hFile.get(), rgbe, static_cast(rowPitch), &bytesWritten, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); @@ -1169,12 +1282,19 @@ HRESULT DirectX::SaveToHDRFile(const Image& image, const wchar_t* szFile) noexce if (bytesWritten != rowPitch) return E_FAIL; +#else + outFile.write(reinterpret_cast(rgbe), static_cast(rowPitch)); + if (!outFile) + return E_FAIL; +#endif } } #endif } +#ifdef WIN32 delonfail.clear(); +#endif return S_OK; } diff --git a/Kits/DirectXTex/DirectXTexImage.cpp b/Kits/DirectXTex/DirectXTexImage.cpp index 2ff93543..6edddaf1 100644 --- a/Kits/DirectXTex/DirectXTexImage.cpp +++ b/Kits/DirectXTex/DirectXTexImage.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexImage.cpp -// +// // DirectX Texture Library - Image container // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -20,6 +20,19 @@ namespace DirectX using namespace DirectX; +#ifndef WIN32 +namespace +{ + inline void * _aligned_malloc(size_t size, size_t alignment) + { + size = (size + alignment - 1) & ~(alignment - 1); + return std::aligned_alloc(alignment, size); + } + + #define _aligned_free free +} +#endif + //------------------------------------------------------------------------------------- // Determines number of image array entries and pixel size //------------------------------------------------------------------------------------- @@ -288,7 +301,7 @@ HRESULT ScratchImage::Initialize(const TexMetadata& mdata, CP_FLAGS flags) noexc return E_INVALIDARG; if (IsPalettized(mdata.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; size_t mipLevels = mdata.mipLevels; @@ -325,7 +338,7 @@ HRESULT ScratchImage::Initialize(const TexMetadata& mdata, CP_FLAGS flags) noexc break; default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } Release(); @@ -342,7 +355,7 @@ HRESULT ScratchImage::Initialize(const TexMetadata& mdata, CP_FLAGS flags) noexc size_t pixelSize, nimages; if (!_DetermineImageArray(m_metadata, flags, nimages, pixelSize)) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; m_image = new (std::nothrow) Image[nimages]; if (!m_image) @@ -390,7 +403,7 @@ HRESULT ScratchImage::Initialize2D(DXGI_FORMAT fmt, size_t width, size_t height, return E_INVALIDARG; if (IsPalettized(fmt)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if (!_CalculateMipLevels(width, height, mipLevels)) return E_INVALIDARG; @@ -409,7 +422,7 @@ HRESULT ScratchImage::Initialize2D(DXGI_FORMAT fmt, size_t width, size_t height, size_t pixelSize, nimages; if (!_DetermineImageArray(m_metadata, flags, nimages, pixelSize)) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; m_image = new (std::nothrow) Image[nimages]; if (!m_image) @@ -441,7 +454,7 @@ HRESULT ScratchImage::Initialize3D(DXGI_FORMAT fmt, size_t width, size_t height, return E_INVALIDARG; if (IsPalettized(fmt)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if (!_CalculateMipLevels3D(width, height, depth, mipLevels)) return E_INVALIDARG; @@ -460,7 +473,7 @@ HRESULT ScratchImage::Initialize3D(DXGI_FORMAT fmt, size_t width, size_t height, size_t pixelSize, nimages; if (!_DetermineImageArray(m_metadata, flags, nimages, pixelSize)) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; m_image = new (std::nothrow) Image[nimages]; if (!m_image) @@ -533,7 +546,7 @@ HRESULT ScratchImage::InitializeFromImage(const Image& srcImage, bool allow1D, C for (size_t y = 0; y < rowCount; ++y) { - memcpy_s(dptr, dpitch, sptr, size); + memcpy(dptr, sptr, size); sptr += spitch; dptr += dpitch; } @@ -592,7 +605,7 @@ HRESULT ScratchImage::InitializeArrayFromImages(const Image* images, size_t nIma for (size_t y = 0; y < rowCount; ++y) { - memcpy_s(dptr, dpitch, sptr, size); + memcpy(dptr, sptr, size); sptr += spitch; dptr += dpitch; } @@ -668,7 +681,7 @@ HRESULT ScratchImage::Initialize3DFromImages(const Image* images, size_t depth, for (size_t y = 0; y < rowCount; ++y) { - memcpy_s(dptr, dpitch, sptr, size); + memcpy(dptr, sptr, size); sptr += spitch; dptr += dpitch; } @@ -786,7 +799,7 @@ bool ScratchImage::IsAlphaAllOpaque() const noexcept } else { - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*m_metadata.width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(m_metadata.width); if (!scanline) return false; diff --git a/Kits/DirectXTex/DirectXTexMipMaps.cpp b/Kits/DirectXTex/DirectXTexMipMaps.cpp index c496ac4c..8623bbcb 100644 --- a/Kits/DirectXTex/DirectXTexMipMaps.cpp +++ b/Kits/DirectXTex/DirectXTexMipMaps.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexMipMaps.cpp -// +// // DirectX Texture Library - Mip-map generation // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -64,7 +64,7 @@ namespace return mipLevels; } - +#ifdef WIN32 HRESULT EnsureWicBitmapPixelFormat( _In_ IWICImagingFactory* pWIC, _In_ IWICBitmap* src, @@ -116,6 +116,7 @@ namespace return hr; } +#endif // WIN32 #if DIRECTX_MATH_VERSION >= 310 @@ -142,7 +143,7 @@ namespace assert(srcImage.width == destImage.width); assert(srcImage.height == destImage.height); - ScopedAlignedArrayXMVECTOR scanline(reinterpret_cast(_aligned_malloc((sizeof(XMVECTOR)*srcImage.width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(srcImage.width); if (!scanline) { return E_OUTOFMEMORY; @@ -214,13 +215,13 @@ namespace { coverage = 0.0f; - ScopedAlignedArrayXMVECTOR row0(reinterpret_cast(_aligned_malloc((sizeof(XMVECTOR)*srcImage.width), 16))); + auto row0 = make_AlignedArrayXMVECTOR(srcImage.width); if (!row0) { return E_OUTOFMEMORY; } - ScopedAlignedArrayXMVECTOR row1(reinterpret_cast(_aligned_malloc((sizeof(XMVECTOR)*srcImage.width), 16))); + auto row1 = make_AlignedArrayXMVECTOR(srcImage.width); if (!row1) { return E_OUTOFMEMORY; @@ -349,9 +350,11 @@ namespace DirectX bool _CalculateMipLevels3D(_In_ size_t width, _In_ size_t height, _In_ size_t depth, _Inout_ size_t& mipLevels) noexcept; // Also used by Compress +#ifdef WIN32 HRESULT _ResizeSeparateColorAndAlpha(_In_ IWICImagingFactory* pWIC, _In_ bool iswic2, _In_ IWICBitmap* original, _In_ size_t newWidth, _In_ size_t newHeight, _In_ TEX_FILTER_FLAGS filter, _Inout_ const Image* img) noexcept; // Also used by Resize +#endif bool _CalculateMipLevels(_In_ size_t width, _In_ size_t height, _Inout_ size_t& mipLevels) noexcept { @@ -391,6 +394,7 @@ namespace DirectX return true; } +#ifdef WIN32 //--- Resizing color and alpha channels separately using WIC --- _Use_decl_annotations_ HRESULT _ResizeSeparateColorAndAlpha( @@ -595,7 +599,7 @@ namespace DirectX if (SUCCEEDED(hr)) { if (img->rowPitch > UINT32_MAX || img->slicePitch > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; ComPtr wicBitmap; hr = EnsureWicBitmapPixelFormat(pWIC, resizedColorWithAlpha.Get(), filter, desiredPixelFormat, wicBitmap.GetAddressOf()); @@ -607,10 +611,12 @@ namespace DirectX return hr; } +#endif // WIN32 } namespace { +#ifdef WIN32 //--- determine when to use WIC vs. non-WIC paths --- bool UseWICFiltering(_In_ DXGI_FORMAT format, _In_ TEX_FILTER_FLAGS filter) noexcept { @@ -705,7 +711,7 @@ namespace size_t height = baseImage.height; if (baseImage.rowPitch > UINT32_MAX || baseImage.slicePitch > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; ComPtr source; HRESULT hr = pWIC->CreateBitmapFromMemory(static_cast(width), static_cast(height), pfGUID, @@ -776,7 +782,7 @@ namespace return hr; if (img->rowPitch > UINT32_MAX || img->slicePitch > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; hr = scaler->Initialize(source.Get(), static_cast(width), static_cast(height), _GetWICInterp(filter)); if (FAILED(hr)) @@ -822,6 +828,7 @@ namespace return S_OK; } +#endif // WIN32 //------------------------------------------------------------------------------------- @@ -873,7 +880,7 @@ namespace for (size_t h = 0; h < mdata.height; ++h) { size_t msize = std::min(dest->rowPitch, rowPitch); - memcpy_s(pDest, dest->rowPitch, pSrc, msize); + memcpy(pDest, pSrc, msize); pSrc += rowPitch; pDest += dest->rowPitch; } @@ -896,7 +903,7 @@ namespace size_t height = mipChain.GetMetadata().height; // Allocate temporary space (2 scanlines) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*width * 2), 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(width) * 2); if (!scanline) return E_OUTOFMEMORY; @@ -983,7 +990,7 @@ namespace return E_FAIL; // Allocate temporary space (3 scanlines) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*width * 3), 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(width) * 3); if (!scanline) return E_OUTOFMEMORY; @@ -1074,7 +1081,7 @@ namespace size_t height = mipChain.GetMetadata().height; // Allocate temporary space (3 scanlines, plus X and Y filters) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*width * 3), 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(width) * 3); if (!scanline) return E_OUTOFMEMORY; @@ -1185,7 +1192,7 @@ namespace size_t height = mipChain.GetMetadata().height; // Allocate temporary space (5 scanlines, plus X and Y filters) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*width * 5), 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(width) * 5); if (!scanline) return E_OUTOFMEMORY; @@ -1373,7 +1380,7 @@ namespace size_t height = mipChain.GetMetadata().height; // Allocate initial temporary space (1 scanline, accumulation rows, plus X and Y filters) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc(sizeof(XMVECTOR) * width, 16))); + auto scanline = make_AlignedArrayXMVECTOR(width); if (!scanline) return E_OUTOFMEMORY; @@ -1462,9 +1469,10 @@ namespace } else { - rowAcc->scanline.reset(static_cast(_aligned_malloc(sizeof(XMVECTOR) * nwidth, 16))); - if (!rowAcc->scanline) + auto nscanline = make_AlignedArrayXMVECTOR(nwidth); + if (!nscanline) return E_OUTOFMEMORY; + rowAcc->scanline.swap(nscanline); } memset(rowAcc->scanline.get(), 0, sizeof(XMVECTOR) * nwidth); @@ -1617,7 +1625,7 @@ namespace for (size_t h = 0; h < height; ++h) { size_t msize = std::min(dest->rowPitch, rowPitch); - memcpy_s(pDest, dest->rowPitch, pSrc, msize); + memcpy(pDest, pSrc, msize); pSrc += rowPitch; pDest += dest->rowPitch; } @@ -1641,7 +1649,7 @@ namespace size_t height = mipChain.GetMetadata().height; // Allocate temporary space (2 scanlines) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*width * 2), 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(width) * 2); if (!scanline) return E_OUTOFMEMORY; @@ -1790,7 +1798,7 @@ namespace return E_FAIL; // Allocate temporary space (5 scanlines) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*width * 5), 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(width) * 5); if (!scanline) return E_OUTOFMEMORY; @@ -1959,7 +1967,7 @@ namespace size_t height = mipChain.GetMetadata().height; // Allocate temporary space (5 scanlines, plus X/Y/Z filters) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*width * 5), 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(width) * 5); if (!scanline) return E_OUTOFMEMORY; @@ -2152,7 +2160,7 @@ namespace size_t height = mipChain.GetMetadata().height; // Allocate temporary space (17 scanlines, plus X/Y/Z filters) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*width * 17), 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(width) * 17); if (!scanline) return E_OUTOFMEMORY; @@ -2533,7 +2541,7 @@ namespace size_t height = mipChain.GetMetadata().height; // Allocate initial temporary space (1 scanline, accumulation rows, plus X/Y/Z filters) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc(sizeof(XMVECTOR) * width, 16))); + auto scanline = make_AlignedArrayXMVECTOR(width); if (!scanline) return E_OUTOFMEMORY; @@ -2616,10 +2624,10 @@ namespace } else { - size_t bytes = sizeof(XMVECTOR) * nwidth * nheight; - sliceAcc->scanline.reset(static_cast(_aligned_malloc(bytes, 16))); - if (!sliceAcc->scanline) + auto nscanline = make_AlignedArrayXMVECTOR(uint64_t(nwidth) * uint64_t(nheight)); + if (!nscanline) return E_OUTOFMEMORY; + sliceAcc->scanline.swap(nscanline); } memset(sliceAcc->scanline.get(), 0, sizeof(XMVECTOR) * nwidth * nheight); @@ -2790,13 +2798,14 @@ HRESULT DirectX::GenerateMipMaps( if (IsCompressed(baseImage.format) || IsTypeless(baseImage.format) || IsPlanar(baseImage.format) || IsPalettized(baseImage.format)) { - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } HRESULT hr = E_UNEXPECTED; static_assert(TEX_FILTER_POINT == 0x100000, "TEX_FILTER_ flag values don't match TEX_FILTER_MODE_MASK"); +#ifdef WIN32 bool usewic = UseWICFiltering(baseImage.format, filter); WICPixelFormatGUID pfGUID = {}; @@ -2810,7 +2819,7 @@ HRESULT DirectX::GenerateMipMaps( if (expandedSize > UINT32_MAX || expandedSize2 > UINT32_MAX) { if (filter & TEX_FILTER_FORCE_WIC) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; usewic = false; } @@ -2871,10 +2880,11 @@ HRESULT DirectX::GenerateMipMaps( } default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } } else +#endif // WIN32 { //--- Use custom filters to generate mipmaps ---------------------------------- TexMetadata mdata = {}; @@ -2953,7 +2963,7 @@ HRESULT DirectX::GenerateMipMaps( return hr; default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } } } @@ -2972,7 +2982,7 @@ HRESULT DirectX::GenerateMipMaps( if (metadata.IsVolumemap() || IsCompressed(metadata.format) || IsTypeless(metadata.format) || IsPlanar(metadata.format) || IsPalettized(metadata.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if (!_CalculateMipLevels(metadata.width, metadata.height, levels)) return E_INVALIDARG; @@ -3010,6 +3020,7 @@ HRESULT DirectX::GenerateMipMaps( static_assert(TEX_FILTER_POINT == 0x100000, "TEX_FILTER_ flag values don't match TEX_FILTER_MODE_MASK"); +#ifdef WIN32 bool usewic = !metadata.IsPMAlpha() && UseWICFiltering(metadata.format, filter); WICPixelFormatGUID pfGUID = {}; @@ -3023,7 +3034,7 @@ HRESULT DirectX::GenerateMipMaps( if (expandedSize > UINT32_MAX || expandedSize2 > UINT32_MAX) { if (filter & TEX_FILTER_FORCE_WIC) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; usewic = false; } @@ -3097,10 +3108,11 @@ HRESULT DirectX::GenerateMipMaps( } default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } } else +#endif // WIN32 { //--- Use custom filters to generate mipmaps ---------------------------------- TexMetadata mdata2 = metadata; @@ -3181,7 +3193,7 @@ HRESULT DirectX::GenerateMipMaps( return hr; default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } } } @@ -3202,7 +3214,7 @@ HRESULT DirectX::GenerateMipMaps3D( return E_INVALIDARG; if (filter & TEX_FILTER_FORCE_WIC) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; DXGI_FORMAT format = baseImages[0].format; size_t width = baseImages[0].width; @@ -3227,7 +3239,7 @@ HRESULT DirectX::GenerateMipMaps3D( } if (IsCompressed(format) || IsTypeless(format) || IsPlanar(format) || IsPalettized(format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; static_assert(TEX_FILTER_POINT == 0x100000, "TEX_FILTER_ flag values don't match TEX_FILTER_MODE_MASK"); @@ -3293,7 +3305,7 @@ HRESULT DirectX::GenerateMipMaps3D( return hr; default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } } @@ -3310,11 +3322,11 @@ HRESULT DirectX::GenerateMipMaps3D( return E_INVALIDARG; if (filter & TEX_FILTER_FORCE_WIC) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if (!metadata.IsVolumemap() || IsCompressed(metadata.format) || IsTypeless(metadata.format) || IsPlanar(metadata.format) || IsPalettized(metadata.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if (!_CalculateMipLevels3D(metadata.width, metadata.height, metadata.depth, levels)) return E_INVALIDARG; @@ -3409,7 +3421,7 @@ HRESULT DirectX::GenerateMipMaps3D( return hr; default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } } @@ -3427,7 +3439,7 @@ HRESULT DirectX::ScaleMipMapsAlphaForCoverage( if (metadata.IsVolumemap() || IsCompressed(metadata.format) || IsTypeless(metadata.format) || IsPlanar(metadata.format) || IsPalettized(metadata.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if (srcImages[0].format != metadata.format || srcImages[0].width != metadata.width || srcImages[0].height != metadata.height) { @@ -3457,7 +3469,7 @@ HRESULT DirectX::ScaleMipMapsAlphaForCoverage( for (size_t h = 0; h < metadata.height; ++h) { size_t msize = std::min(dest->rowPitch, rowPitch); - memcpy_s(pDest, dest->rowPitch, pSrc, msize); + memcpy(pDest, pSrc, msize); pSrc += rowPitch; pDest += dest->rowPitch; } @@ -3481,6 +3493,6 @@ HRESULT DirectX::ScaleMipMapsAlphaForCoverage( if (FAILED(hr)) return hr; } - + return S_OK; } diff --git a/Kits/DirectXTex/DirectXTexMisc.cpp b/Kits/DirectXTex/DirectXTexMisc.cpp index 20056ab4..0d827cd9 100644 --- a/Kits/DirectXTex/DirectXTexMisc.cpp +++ b/Kits/DirectXTex/DirectXTexMisc.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexMisc.cpp -// +// // DirectX Texture Library - Misc image operations // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -13,6 +13,11 @@ using namespace DirectX; +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wignored-attributes" +#endif + namespace { const XMVECTORF32 g_Gamma22 = { { { 2.2f, 2.2f, 2.2f, 1.f } } }; @@ -33,7 +38,7 @@ namespace const size_t width = image1.width; - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*width) * 2, 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(width) * 2); if (!scanline) return E_OUTOFMEMORY; @@ -184,7 +189,7 @@ namespace const size_t width = image.width; - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(width); if (!scanline) return E_OUTOFMEMORY; @@ -222,7 +227,7 @@ namespace const size_t width = srcImage.width; - ScopedAlignedArrayXMVECTOR scanlines(static_cast(_aligned_malloc((sizeof(XMVECTOR)*width*2), 16))); + auto scanlines = make_AlignedArrayXMVECTOR(uint64_t(width) * 2); if (!scanlines) return E_OUTOFMEMORY; @@ -261,7 +266,7 @@ namespace //===================================================================================== // Entry points //===================================================================================== - + //------------------------------------------------------------------------------------- // Copies a rectangle from one image into another //------------------------------------------------------------------------------------- @@ -280,7 +285,7 @@ HRESULT DirectX::CopyRectangle( if (IsCompressed(srcImage.format) || IsCompressed(dstImage.format) || IsPlanar(srcImage.format) || IsPlanar(dstImage.format) || IsPalettized(srcImage.format) || IsPalettized(dstImage.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; // Validate rectangle/offset if (!srcRect.w || !srcRect.h || ((srcRect.x + srcRect.w) > srcImage.width) || ((srcRect.y + srcRect.h) > srcImage.height)) @@ -301,7 +306,7 @@ HRESULT DirectX::CopyRectangle( if (sbpp < 8) { // We don't support monochrome (DXGI_FORMAT_R1_UNORM) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } const uint8_t* pEndSrc = srcImage.pixels + srcImage.rowPitch*srcImage.height; @@ -322,7 +327,7 @@ HRESULT DirectX::CopyRectangle( if (((pSrc + copyW) > pEndSrc) || (pDest > pEndDest)) return E_FAIL; - memcpy_s(pDest, size_t(pEndDest - pDest), pSrc, copyW); + memcpy(pDest, pSrc, copyW); pSrc += srcImage.rowPitch; pDest += dstImage.rowPitch; @@ -339,7 +344,7 @@ HRESULT DirectX::CopyRectangle( if (dbpp < 8) { // We don't support monochrome (DXGI_FORMAT_R1_UNORM) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } // Round to bytes @@ -347,7 +352,7 @@ HRESULT DirectX::CopyRectangle( uint8_t* pDest = dstImage.pixels + (yOffset * dstImage.rowPitch) + (xOffset * dbpp); - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*srcRect.w), 16))); + auto scanline = make_AlignedArrayXMVECTOR(srcRect.w); if (!scanline) return E_OUTOFMEMORY; @@ -374,7 +379,7 @@ HRESULT DirectX::CopyRectangle( return S_OK; } - + //------------------------------------------------------------------------------------- // Computes the Mean-Squared-Error (MSE) between two images //------------------------------------------------------------------------------------- @@ -398,7 +403,7 @@ HRESULT DirectX::ComputeMSE( if (IsPlanar(image1.format) || IsPlanar(image2.format) || IsPalettized(image1.format) || IsPalettized(image2.format) || IsTypeless(image1.format) || IsTypeless(image2.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if (IsCompressed(image1.format)) { @@ -478,7 +483,7 @@ HRESULT DirectX::EvaluateImage( return E_INVALIDARG; if (IsPlanar(image.format) || IsPalettized(image.format) || IsTypeless(image.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if (IsCompressed(image.format)) { @@ -513,7 +518,7 @@ HRESULT DirectX::EvaluateImage( return E_INVALIDARG; if (IsPlanar(metadata.format) || IsPalettized(metadata.format) || IsTypeless(metadata.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if (metadata.width > UINT32_MAX || metadata.height > UINT32_MAX) @@ -607,7 +612,7 @@ HRESULT DirectX::TransformImage( return E_INVALIDARG; if (IsPlanar(image.format) || IsPalettized(image.format) || IsCompressed(image.format) || IsTypeless(image.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; HRESULT hr = result.Initialize2D(image.format, image.width, image.height, 1, 1); if (FAILED(hr)) @@ -626,7 +631,7 @@ HRESULT DirectX::TransformImage( result.Release(); return hr; } - + return S_OK; } @@ -641,7 +646,7 @@ HRESULT DirectX::TransformImage( return E_INVALIDARG; if (IsPlanar(metadata.format) || IsPalettized(metadata.format) || IsCompressed(metadata.format) || IsTypeless(metadata.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if (metadata.width > UINT32_MAX || metadata.height > UINT32_MAX) diff --git a/Kits/DirectXTex/DirectXTexNormalMaps.cpp b/Kits/DirectXTex/DirectXTexNormalMaps.cpp index 763f0cd1..de06f81e 100644 --- a/Kits/DirectXTex/DirectXTexNormalMaps.cpp +++ b/Kits/DirectXTex/DirectXTexNormalMaps.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexNormalMaps.cpp -// +// // DirectX Texture Library - Normal map operations // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -84,7 +84,7 @@ namespace return E_FAIL; if (!(convFlags & (CONVF_UNORM | CONVF_SNORM | CONVF_FLOAT))) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; const size_t width = srcImage.width; const size_t height = srcImage.height; @@ -92,11 +92,11 @@ namespace return E_FAIL; // Allocate temporary space (4 scanlines and 3 evaluated rows) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*width * 4), 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(width) * 4); if (!scanline) return E_OUTOFMEMORY; - ScopedAlignedArrayFloat buffer(static_cast(_aligned_malloc(((sizeof(float) * (width + 2)) * 3), 16))); + auto buffer = make_AlignedArrayFloat((uint64_t(width) + 2) * 3); if (!buffer) return E_OUTOFMEMORY; @@ -124,7 +124,7 @@ namespace if (flags & CNMAP_MIRROR_V) { // Mirror first row - memcpy_s(row0, rowPitch, row1, rowPitch); + memcpy(row0, row1, rowPitch); } else { @@ -248,7 +248,7 @@ namespace //===================================================================================== // Entry points //===================================================================================== - + //------------------------------------------------------------------------------------- // Generates a normal map from a height-map //------------------------------------------------------------------------------------- @@ -282,7 +282,7 @@ HRESULT DirectX::ComputeNormalMap( || IsTypeless(format) || IsTypeless(srcImage.format) || IsPlanar(format) || IsPlanar(srcImage.format) || IsPalettized(format) || IsPalettized(srcImage.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; // Setup target image normalMap.Release(); @@ -325,7 +325,7 @@ HRESULT DirectX::ComputeNormalMap( || IsTypeless(format) || IsTypeless(metadata.format) || IsPlanar(format) || IsPlanar(metadata.format) || IsPalettized(format) || IsPalettized(metadata.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; static_assert(CNMAP_CHANNEL_RED == 0x1, "CNMAP_CHANNEL_ flag values don't match mask"); switch (flags & 0xf) @@ -371,7 +371,7 @@ HRESULT DirectX::ComputeNormalMap( if (IsCompressed(src.format) || IsTypeless(src.format)) { normalMaps.Release(); - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } if (src.width != dest[index].width || src.height != dest[index].height) diff --git a/Kits/DirectXTex/DirectXTexPMAlpha.cpp b/Kits/DirectXTex/DirectXTexPMAlpha.cpp index 5674df0e..e1de5daa 100644 --- a/Kits/DirectXTex/DirectXTexPMAlpha.cpp +++ b/Kits/DirectXTex/DirectXTexPMAlpha.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexPMAlpha.cpp -// +// // DirectX Texture Library - Premultiplied alpha operations // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -31,7 +31,7 @@ namespace assert(srcImage.width == destImage.width); assert(srcImage.height == destImage.height); - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*srcImage.width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(srcImage.width); if (!scanline) return E_OUTOFMEMORY; @@ -74,7 +74,7 @@ namespace static_assert(static_cast(TEX_PMALPHA_SRGB) == static_cast(TEX_FILTER_SRGB), "TEX_PMALHPA_SRGB* should match TEX_FILTER_SRGB*"); flags &= TEX_PMALPHA_SRGB; - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*srcImage.width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(srcImage.width); if (!scanline) return E_OUTOFMEMORY; @@ -116,7 +116,7 @@ namespace assert(srcImage.width == destImage.width); assert(srcImage.height == destImage.height); - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*srcImage.width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(srcImage.width); if (!scanline) return E_OUTOFMEMORY; @@ -162,7 +162,7 @@ namespace static_assert(static_cast(TEX_PMALPHA_SRGB) == static_cast(TEX_FILTER_SRGB), "TEX_PMALPHA_SRGB* should match TEX_FILTER_SRGB*"); flags &= TEX_PMALPHA_SRGB; - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc((sizeof(XMVECTOR)*srcImage.width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(srcImage.width); if (!scanline) return E_OUTOFMEMORY; @@ -223,7 +223,7 @@ HRESULT DirectX::PremultiplyAlpha( || IsPalettized(srcImage.format) || IsTypeless(srcImage.format) || !HasAlpha(srcImage.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if ((srcImage.width > UINT32_MAX) || (srcImage.height > UINT32_MAX)) return E_INVALIDARG; @@ -276,7 +276,7 @@ HRESULT DirectX::PremultiplyAlpha( || IsPalettized(metadata.format) || IsTypeless(metadata.format) || !HasAlpha(metadata.format)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; if ((metadata.width > UINT32_MAX) || (metadata.height > UINT32_MAX)) return E_INVALIDARG; diff --git a/Kits/DirectXTex/DirectXTexResize.cpp b/Kits/DirectXTex/DirectXTexResize.cpp index 5e845e74..b9cd7d30 100644 --- a/Kits/DirectXTex/DirectXTexResize.cpp +++ b/Kits/DirectXTex/DirectXTexResize.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexResize.cpp -// +// // DirectX Texture Library - Image resizing operations // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -16,14 +16,17 @@ using namespace DirectX; using Microsoft::WRL::ComPtr; +#ifdef WIN32 namespace DirectX { extern HRESULT _ResizeSeparateColorAndAlpha(_In_ IWICImagingFactory* pWIC, _In_ bool iswic2, _In_ IWICBitmap* original, _In_ size_t newWidth, _In_ size_t newHeight, _In_ TEX_FILTER_FLAGS filter, _Inout_ const Image* img) noexcept; } +#endif namespace { +#ifdef WIN32 //--- Do image resize using WIC --- HRESULT PerformResizeUsingWIC( const Image& srcImage, @@ -58,7 +61,7 @@ namespace if (srcImage.rowPitch > UINT32_MAX || srcImage.slicePitch > UINT32_MAX || destImage.rowPitch > UINT32_MAX || destImage.slicePitch > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; ComPtr source; hr = pWIC->CreateBitmapFromMemory(static_cast(srcImage.width), static_cast(srcImage.height), pfGUID, @@ -238,7 +241,7 @@ namespace return true; } - +#endif // WIN32 //------------------------------------------------------------------------------------- // Resize custom filters @@ -251,8 +254,7 @@ namespace assert(srcImage.format == destImage.format); // Allocate temporary space (2 scanlines) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc( - (sizeof(XMVECTOR) * (srcImage.width + destImage.width)), 16))); + auto scanline = make_AlignedArrayXMVECTOR(srcImage.width + destImage.width); if (!scanline) return E_OUTOFMEMORY; @@ -312,8 +314,7 @@ namespace return E_FAIL; // Allocate temporary space (3 scanlines) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc( - (sizeof(XMVECTOR) * (srcImage.width * 2 + destImage.width)), 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(srcImage.width) * 2 + destImage.width); if (!scanline) return E_OUTOFMEMORY; @@ -371,8 +372,7 @@ namespace assert(srcImage.format == destImage.format); // Allocate temporary space (3 scanlines, plus X and Y filters) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc( - (sizeof(XMVECTOR) * (srcImage.width * 2 + destImage.width)), 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(srcImage.width) * 2 + destImage.width); if (!scanline) return E_OUTOFMEMORY; @@ -457,8 +457,7 @@ namespace assert(srcImage.format == destImage.format); // Allocate temporary space (5 scanlines, plus X and Y filters) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc( - (sizeof(XMVECTOR) * (srcImage.width * 4 + destImage.width)), 16))); + auto scanline = make_AlignedArrayXMVECTOR(uint64_t(srcImage.width) * 4 + destImage.width); if (!scanline) return E_OUTOFMEMORY; @@ -619,7 +618,7 @@ namespace using namespace TriangleFilter; // Allocate initial temporary space (1 scanline, accumulation rows, plus X and Y filters) - ScopedAlignedArrayXMVECTOR scanline(static_cast(_aligned_malloc(sizeof(XMVECTOR) * srcImage.width, 16))); + auto scanline = make_AlignedArrayXMVECTOR(srcImage.width); if (!scanline) return E_OUTOFMEMORY; @@ -688,9 +687,10 @@ namespace } else { - rowAcc->scanline.reset(static_cast(_aligned_malloc(sizeof(XMVECTOR) * destImage.width, 16))); - if (!rowAcc->scanline) + auto nscanline = make_AlignedArrayXMVECTOR(destImage.width); + if (!nscanline) return E_OUTOFMEMORY; + rowAcc->scanline.swap(nscanline); } memset(rowAcc->scanline.get(), 0, sizeof(XMVECTOR) * destImage.width); @@ -823,7 +823,7 @@ namespace return ResizeTriangleFilter(srcImage, filter, destImage); default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } } } @@ -859,9 +859,10 @@ HRESULT DirectX::Resize( if (IsCompressed(srcImage.format)) { // We don't support resizing compressed images - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } +#ifdef WIN32 bool usewic = UseWICFiltering(srcImage.format, filter); WICPixelFormatGUID pfGUID = {}; @@ -875,11 +876,12 @@ HRESULT DirectX::Resize( if (expandedSize > UINT32_MAX || expandedSize2 > UINT32_MAX) { if (filter & TEX_FILTER_FORCE_WIC) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; usewic = false; } } +#endif // WIN32 HRESULT hr = image.Initialize2D(srcImage.format, width, height, 1, 1); if (FAILED(hr)) @@ -889,6 +891,7 @@ HRESULT DirectX::Resize( if (!rimage) return E_POINTER; +#ifdef WIN32 if (usewic) { if (wicpf) @@ -903,6 +906,7 @@ HRESULT DirectX::Resize( } } else +#endif { // Case 3: not using WIC resizing hr = PerformResizeUsingCustomFilters(srcImage, filter, *rimage); @@ -945,6 +949,7 @@ HRESULT DirectX::Resize( if (FAILED(hr)) return hr; +#ifdef WIN32 bool usewic = !metadata.IsPMAlpha() && UseWICFiltering(metadata.format, filter); WICPixelFormatGUID pfGUID = {}; @@ -958,11 +963,12 @@ HRESULT DirectX::Resize( if (expandedSize > UINT32_MAX || expandedSize2 > UINT32_MAX) { if (filter & TEX_FILTER_FORCE_WIC) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; usewic = false; } } +#endif switch (metadata.dimension) { @@ -999,6 +1005,7 @@ HRESULT DirectX::Resize( return E_FAIL; } +#ifdef WIN32 if (usewic) { if (wicpf) @@ -1013,6 +1020,7 @@ HRESULT DirectX::Resize( } } else +#endif { // Case 3: not using WIC resizing hr = PerformResizeUsingCustomFilters(*srcimg, filter, *destimg); @@ -1058,6 +1066,7 @@ HRESULT DirectX::Resize( return E_FAIL; } +#ifdef WIN32 if (usewic) { if (wicpf) @@ -1072,6 +1081,7 @@ HRESULT DirectX::Resize( } } else +#endif { // Case 3: not using WIC resizing hr = PerformResizeUsingCustomFilters(*srcimg, filter, *destimg); diff --git a/Kits/DirectXTex/DirectXTexTGA.cpp b/Kits/DirectXTex/DirectXTexTGA.cpp index 650b2336..80bb2a70 100644 --- a/Kits/DirectXTex/DirectXTexTGA.cpp +++ b/Kits/DirectXTex/DirectXTexTGA.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexTGA.cpp -// +// // DirectX Texture Library - Targa Truevision (TGA) file format reader/writer // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -148,7 +148,7 @@ namespace if (size < sizeof(TGA_HEADER)) { - return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + return HRESULT_E_INVALID_DATA; } auto pHeader = static_cast(pSource); @@ -156,17 +156,17 @@ namespace if (pHeader->bColorMapType != 0 || pHeader->wColorMapLength != 0) { - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } if (pHeader->bDescriptor & (TGA_FLAGS_INTERLEAVED_2WAY | TGA_FLAGS_INTERLEAVED_4WAY)) { - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } if (!pHeader->wWidth || !pHeader->wHeight) { - return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + return HRESULT_E_INVALID_DATA; } switch (pHeader->bImageType) @@ -214,7 +214,7 @@ namespace break; default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } if (convFlags && (pHeader->bImageType == TGA_BLACK_AND_WHITE_RLE)) @@ -226,10 +226,10 @@ namespace case TGA_NO_IMAGE: case TGA_COLOR_MAPPED: case TGA_COLOR_MAPPED_RLE: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; default: - return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); + return HRESULT_E_INVALID_DATA; } metadata.width = pHeader->wWidth; @@ -1082,7 +1082,7 @@ namespace if ((image.width > UINT16_MAX) || (image.height > UINT16_MAX)) { - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } header.wWidth = static_cast(image.width); @@ -1127,7 +1127,7 @@ namespace break; default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; } return S_OK; @@ -1223,15 +1223,21 @@ namespace time_t now = {}; time(&now); +#ifdef WIN32 tm info; - if (!gmtime_s(&info, &now)) + auto pinfo = &info; + if (!gmtime_s(pinfo, &now)) +#else + const tm* pinfo = gmtime(&now); + if (pinfo) +#endif { - ext->wStampMonth = static_cast(info.tm_mon + 1); - ext->wStampDay = static_cast(info.tm_mday); - ext->wStampYear = static_cast(info.tm_year + 1900); - ext->wStampHour = static_cast(info.tm_hour); - ext->wStampMinute = static_cast(info.tm_min); - ext->wStampSecond = static_cast(info.tm_sec); + ext->wStampMonth = static_cast(pinfo->tm_mon + 1); + ext->wStampDay = static_cast(pinfo->tm_mday); + ext->wStampYear = static_cast(pinfo->tm_year + 1900); + ext->wStampHour = static_cast(pinfo->tm_hour); + ext->wStampMinute = static_cast(pinfo->tm_min); + ext->wStampSecond = static_cast(pinfo->tm_sec); } } } @@ -1336,6 +1342,7 @@ HRESULT DirectX::GetMetadataFromTGAFile(const wchar_t* szFile, TGA_FLAGS flags, if (!szFile) return E_INVALIDARG; +#ifdef WIN32 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr))); #else @@ -1357,25 +1364,56 @@ HRESULT DirectX::GetMetadataFromTGAFile(const wchar_t* szFile, TGA_FLAGS flags, // File is too big for 32-bit allocation, so reject read (4 GB should be plenty large enough for a valid TGA file) if (fileInfo.EndOfFile.HighPart > 0) { - return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); + return HRESULT_E_FILE_TOO_LARGE; } + size_t len = fileInfo.EndOfFile.LowPart; +#else // !WIN32 + std::ifstream inFile(std::filesystem::path(szFile), std::ios::in | std::ios::binary | std::ios::ate); + if (!inFile) + return E_FAIL; + + std::streampos fileLen = inFile.tellg(); + if (!inFile) + return E_FAIL; + + if (fileLen > UINT32_MAX) + return HRESULT_E_FILE_TOO_LARGE; + + inFile.seekg(0, std::ios::beg); + if (!inFile) + return E_FAIL; + + size_t len = fileLen; +#endif + // Need at least enough data to fill the standard header to be a valid TGA - if (fileInfo.EndOfFile.LowPart < (sizeof(TGA_HEADER))) + if (len < (sizeof(TGA_HEADER))) { return E_FAIL; } // Read the standard header (we don't need the file footer to parse the file) uint8_t header[sizeof(TGA_HEADER)] = {}; + +#ifdef WIN32 DWORD bytesRead = 0; if (!ReadFile(hFile.get(), header, sizeof(TGA_HEADER), &bytesRead, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); } + auto headerLen = static_cast(bytesRead); +#else + inFile.read(reinterpret_cast(header), sizeof(TGA_HEADER)); + if (!inFile) + return E_FAIL; + + size_t headerLen = sizeof(TGA_HEADER); +#endif + size_t offset; - HRESULT hr = DecodeTGAHeader(header, bytesRead, flags, metadata, offset, nullptr); + HRESULT hr = DecodeTGAHeader(header, headerLen, flags, metadata, offset, nullptr); if (FAILED(hr)) return hr; @@ -1383,27 +1421,37 @@ HRESULT DirectX::GetMetadataFromTGAFile(const wchar_t* szFile, TGA_FLAGS flags, const TGA_EXTENSION* ext = nullptr; TGA_EXTENSION extData = {}; { - if (SetFilePointer(hFile.get(), -static_cast(sizeof(TGA_FOOTER)), nullptr, FILE_END) == INVALID_SET_FILE_POINTER) - { - return HRESULT_FROM_WIN32(GetLastError()); - } - TGA_FOOTER footer = {}; - if (!ReadFile(hFile.get(), &footer, sizeof(TGA_FOOTER), &bytesRead, nullptr)) + +#ifdef WIN32 + if (SetFilePointer(hFile.get(), -static_cast(sizeof(TGA_FOOTER)), nullptr, FILE_END) != INVALID_SET_FILE_POINTER) { - return HRESULT_FROM_WIN32(GetLastError()); - } + if (!ReadFile(hFile.get(), &footer, sizeof(TGA_FOOTER), &bytesRead, nullptr)) + { + return HRESULT_FROM_WIN32(GetLastError()); + } - if (bytesRead != sizeof(TGA_FOOTER)) + if (bytesRead != sizeof(TGA_FOOTER)) + { + return E_FAIL; + } + } +#else + inFile.seekg(-static_cast(sizeof(TGA_FOOTER)), std::ios::end); + if (inFile) { - return E_FAIL; + inFile.read(reinterpret_cast(&footer), sizeof(TGA_FOOTER)); + if (!inFile) + return E_FAIL; } +#endif if (memcmp(footer.Signature, g_Signature, sizeof(g_Signature)) == 0) { if (footer.dwExtensionOffset != 0 - && ((footer.dwExtensionOffset + sizeof(TGA_EXTENSION)) <= fileInfo.EndOfFile.LowPart)) + && ((footer.dwExtensionOffset + sizeof(TGA_EXTENSION)) <= len)) { +#ifdef WIN32 LARGE_INTEGER filePos = { { static_cast(footer.dwExtensionOffset), 0 } }; if (SetFilePointerEx(hFile.get(), filePos, nullptr, FILE_BEGIN)) { @@ -1414,6 +1462,18 @@ HRESULT DirectX::GetMetadataFromTGAFile(const wchar_t* szFile, TGA_FLAGS flags, metadata.SetAlphaMode(GetAlphaModeFromExtension(ext)); } } +#else // !WIN32 + inFile.seekg(static_cast(footer.dwExtensionOffset), std::ios::beg); + if (inFile) + { + inFile.read(reinterpret_cast(&extData), sizeof(TGA_EXTENSION)); + if (inFile) + { + ext = &extData; + metadata.SetAlphaMode(GetAlphaModeFromExtension(ext)); + } + } +#endif } } } @@ -1531,6 +1591,7 @@ HRESULT DirectX::LoadFromTGAFile( image.Release(); +#ifdef WIN32 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr))); #else @@ -1552,43 +1613,80 @@ HRESULT DirectX::LoadFromTGAFile( // File is too big for 32-bit allocation, so reject read (4 GB should be plenty large enough for a valid TGA file) if (fileInfo.EndOfFile.HighPart > 0) { - return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); + return HRESULT_E_FILE_TOO_LARGE; } + size_t len = fileInfo.EndOfFile.LowPart; +#else // !WIN32 + std::ifstream inFile(std::filesystem::path(szFile), std::ios::in | std::ios::binary | std::ios::ate); + if (!inFile) + return E_FAIL; + + std::streampos fileLen = inFile.tellg(); + if (!inFile) + return E_FAIL; + + if (fileLen > UINT32_MAX) + return HRESULT_E_FILE_TOO_LARGE; + + inFile.seekg(0, std::ios::beg); + if (!inFile) + return E_FAIL; + + size_t len = fileLen; +#endif + // Need at least enough data to fill the header to be a valid TGA - if (fileInfo.EndOfFile.LowPart < sizeof(TGA_HEADER)) + if (len < sizeof(TGA_HEADER)) { return E_FAIL; } // Read the header uint8_t header[sizeof(TGA_HEADER)] = {}; + +#ifdef WIN32 DWORD bytesRead = 0; if (!ReadFile(hFile.get(), header, sizeof(TGA_HEADER), &bytesRead, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); } + auto headerLen = static_cast(bytesRead); +#else + inFile.read(reinterpret_cast(header), sizeof(TGA_HEADER)); + if (!inFile) + return E_FAIL; + + size_t headerLen = sizeof(TGA_HEADER); +#endif + size_t offset; uint32_t convFlags = 0; TexMetadata mdata; - HRESULT hr = DecodeTGAHeader(header, bytesRead, flags, mdata, offset, &convFlags); + HRESULT hr = DecodeTGAHeader(header, headerLen, flags, mdata, offset, &convFlags); if (FAILED(hr)) return hr; // Read the pixels - auto remaining = static_cast(fileInfo.EndOfFile.LowPart - offset); + auto remaining = len - offset; if (remaining == 0) return E_FAIL; if (offset > sizeof(TGA_HEADER)) { +#ifdef WIN32 // Skip past the id string LARGE_INTEGER filePos = { { static_cast(offset), 0 } }; if (!SetFilePointerEx(hFile.get(), filePos, nullptr, FILE_BEGIN)) { return HRESULT_FROM_WIN32(GetLastError()); } +#else + inFile.seekg(offset, std::ios::beg); + if (!inFile) + return E_FAIL; +#endif } hr = image.Initialize2D(mdata.format, mdata.width, mdata.height, 1, 1); @@ -1605,15 +1703,16 @@ HRESULT DirectX::LoadFromTGAFile( if (remaining < image.GetPixelsSize()) { image.Release(); - return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); + return HRESULT_E_HANDLE_EOF; } if (image.GetPixelsSize() > UINT32_MAX) { image.Release(); - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; } +#ifdef WIN32 if (!ReadFile(hFile.get(), image.GetPixels(), static_cast(image.GetPixelsSize()), &bytesRead, nullptr)) { image.Release(); @@ -1625,6 +1724,14 @@ HRESULT DirectX::LoadFromTGAFile( image.Release(); return E_FAIL; } +#else + inFile.read(reinterpret_cast(image.GetPixels()), image.GetPixelsSize()); + if (!inFile) + { + image.Release(); + return E_FAIL; + } +#endif switch (mdata.format) { @@ -1824,7 +1931,8 @@ HRESULT DirectX::LoadFromTGAFile( return E_OUTOFMEMORY; } - if (!ReadFile(hFile.get(), temp.get(), remaining, &bytesRead, nullptr)) +#ifdef WIN32 + if (!ReadFile(hFile.get(), temp.get(), static_cast(remaining), &bytesRead, nullptr)) { image.Release(); return HRESULT_FROM_WIN32(GetLastError()); @@ -1835,6 +1943,14 @@ HRESULT DirectX::LoadFromTGAFile( image.Release(); return E_FAIL; } +#else + inFile.read(reinterpret_cast(temp.get()), remaining); + if (!inFile) + { + image.Release(); + return E_FAIL; + } +#endif if (convFlags & CONV_FLAGS_RLE) { @@ -1859,29 +1975,42 @@ HRESULT DirectX::LoadFromTGAFile( const TGA_EXTENSION* ext = nullptr; TGA_EXTENSION extData = {}; { - if (SetFilePointer(hFile.get(), -static_cast(sizeof(TGA_FOOTER)), nullptr, FILE_END) == INVALID_SET_FILE_POINTER) - { - return HRESULT_FROM_WIN32(GetLastError()); - } - TGA_FOOTER footer = {}; - if (!ReadFile(hFile.get(), &footer, sizeof(TGA_FOOTER), &bytesRead, nullptr)) + +#ifdef WIN32 + if (SetFilePointer(hFile.get(), -static_cast(sizeof(TGA_FOOTER)), nullptr, FILE_END) != INVALID_SET_FILE_POINTER) { - image.Release(); - return HRESULT_FROM_WIN32(GetLastError()); - } + if (!ReadFile(hFile.get(), &footer, sizeof(TGA_FOOTER), &bytesRead, nullptr)) + { + image.Release(); + return HRESULT_FROM_WIN32(GetLastError()); + } - if (bytesRead != sizeof(TGA_FOOTER)) + if (bytesRead != sizeof(TGA_FOOTER)) + { + image.Release(); + return E_FAIL; + } + } +#else // !WIN32 + inFile.seekg(-static_cast(sizeof(TGA_FOOTER)), std::ios::end); + if (inFile) { - image.Release(); - return E_FAIL; + inFile.read(reinterpret_cast(&footer), sizeof(TGA_FOOTER)); + if (!inFile) + { + image.Release(); + return E_FAIL; + } } +#endif if (memcmp(footer.Signature, g_Signature, sizeof(g_Signature)) == 0) { if (footer.dwExtensionOffset != 0 - && ((footer.dwExtensionOffset + sizeof(TGA_EXTENSION)) <= fileInfo.EndOfFile.LowPart)) + && ((footer.dwExtensionOffset + sizeof(TGA_EXTENSION)) <= len)) { +#ifdef WIN32 LARGE_INTEGER filePos = { { static_cast(footer.dwExtensionOffset), 0 } }; if (SetFilePointerEx(hFile.get(), filePos, nullptr, FILE_BEGIN)) { @@ -1891,6 +2020,17 @@ HRESULT DirectX::LoadFromTGAFile( ext = &extData; } } +#else // !WIN32 + inFile.seekg(static_cast(footer.dwExtensionOffset), std::ios::beg); + if (inFile) + { + inFile.read(reinterpret_cast(&extData), sizeof(TGA_EXTENSION)); + if (inFile) + { + ext = &extData; + } + } +#endif } } } @@ -1960,7 +2100,7 @@ HRESULT DirectX::SaveToTGAMemory( assert(destPtr != nullptr); uint8_t* dPtr = destPtr; - memcpy_s(dPtr, blob.GetBufferSize(), &tga_header, sizeof(TGA_HEADER)); + memcpy(dPtr, &tga_header, sizeof(TGA_HEADER)); dPtr += sizeof(TGA_HEADER); const uint8_t* pPixels = image.pixels; @@ -2033,10 +2173,13 @@ HRESULT DirectX::SaveToTGAFile( return hr; // Create file and write header +#ifdef WIN32 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) - ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr))); + ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_WRITE, 0, + CREATE_ALWAYS, nullptr))); #else - ScopedHandle hFile(safe_handle(CreateFileW(szFile, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr))); + ScopedHandle hFile(safe_handle(CreateFileW(szFile, + GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr))); #endif if (!hFile) { @@ -2044,6 +2187,11 @@ HRESULT DirectX::SaveToTGAFile( } auto_delete_file delonfail(hFile.get()); +#else + std::ofstream outFile(std::filesystem::path(szFile), std::ios::out | std::ios::binary | std::ios::trunc); + if (!outFile) + return E_FAIL; +#endif // Determine size for TGA pixel data size_t rowPitch, slicePitch; @@ -2062,6 +2210,7 @@ HRESULT DirectX::SaveToTGAFile( return hr; // Write blob +#ifdef WIN32 const DWORD bytesToWrite = static_cast(blob.GetBufferSize()); DWORD bytesWritten; if (!WriteFile(hFile.get(), blob.GetBufferPointer(), bytesToWrite, &bytesWritten, nullptr)) @@ -2073,6 +2222,13 @@ HRESULT DirectX::SaveToTGAFile( { return E_FAIL; } +#else + outFile.write(reinterpret_cast(blob.GetBufferPointer()), + static_cast(blob.GetBufferSize())); + + if (!outFile) + return E_FAIL; +#endif } else { @@ -2082,6 +2238,7 @@ HRESULT DirectX::SaveToTGAFile( return E_OUTOFMEMORY; // Write header +#ifdef WIN32 DWORD bytesWritten; if (!WriteFile(hFile.get(), &tga_header, sizeof(TGA_HEADER), &bytesWritten, nullptr)) { @@ -2090,9 +2247,14 @@ HRESULT DirectX::SaveToTGAFile( if (bytesWritten != sizeof(TGA_HEADER)) return E_FAIL; +#else + outFile.write(reinterpret_cast(&tga_header), sizeof(TGA_HEADER)); + if (!outFile) + return E_FAIL; +#endif if (rowPitch > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; // Write pixels const uint8_t* pPixels = image.pixels; @@ -2115,6 +2277,7 @@ HRESULT DirectX::SaveToTGAFile( pPixels += image.rowPitch; +#ifdef WIN32 if (!WriteFile(hFile.get(), temp.get(), static_cast(rowPitch), &bytesWritten, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); @@ -2122,6 +2285,11 @@ HRESULT DirectX::SaveToTGAFile( if (bytesWritten != rowPitch) return E_FAIL; +#else + outFile.write(reinterpret_cast(temp.get()), rowPitch); + if (!outFile) + return E_FAIL; +#endif } uint32_t extOffset = 0; @@ -2131,10 +2299,11 @@ HRESULT DirectX::SaveToTGAFile( TGA_EXTENSION ext = {}; SetExtension(&ext, flags, *metadata); +#ifdef WIN32 extOffset = SetFilePointer(hFile.get(), 0, nullptr, FILE_CURRENT); if (extOffset == INVALID_SET_FILE_POINTER) { - return HRESULT_FROM_WIN32(GetLastError()); + return E_FAIL; } if (!WriteFile(hFile.get(), &ext, sizeof(TGA_EXTENSION), &bytesWritten, nullptr)) @@ -2144,6 +2313,15 @@ HRESULT DirectX::SaveToTGAFile( if (bytesWritten != sizeof(TGA_EXTENSION)) return E_FAIL; +#else + extOffset = static_cast(outFile.tellp()); + if (!outFile) + return E_FAIL; + + outFile.write(reinterpret_cast(&ext), sizeof(TGA_EXTENSION)); + if (!outFile) + return E_FAIL; +#endif } // Write TGA 2.0 footer @@ -2151,16 +2329,24 @@ HRESULT DirectX::SaveToTGAFile( footer.dwExtensionOffset = extOffset; memcpy(footer.Signature, g_Signature, sizeof(g_Signature)); - if (!WriteFile(hFile.get(), &footer, sizeof(footer), &bytesWritten, nullptr)) +#ifdef WIN32 + if (!WriteFile(hFile.get(), &footer, sizeof(TGA_FOOTER), &bytesWritten, nullptr)) { return HRESULT_FROM_WIN32(GetLastError()); } if (bytesWritten != sizeof(footer)) return E_FAIL; +#else + outFile.write(reinterpret_cast(&footer), sizeof(TGA_FOOTER)); + if (!outFile) + return E_FAIL; +#endif } +#ifdef WIN32 delonfail.clear(); +#endif return S_OK; } diff --git a/Kits/DirectXTex/DirectXTexUtil.cpp b/Kits/DirectXTex/DirectXTexUtil.cpp index 6f4e5497..68eda92c 100644 --- a/Kits/DirectXTex/DirectXTexUtil.cpp +++ b/Kits/DirectXTex/DirectXTexUtil.cpp @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- // DirectXTexUtil.cpp -// +// // DirectX Texture Library - Utilities // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -32,6 +32,7 @@ using Microsoft::WRL::ComPtr; namespace { +#ifdef WIN32 //------------------------------------------------------------------------------------- // WIC Pixel Format Translation Data //------------------------------------------------------------------------------------- @@ -113,9 +114,20 @@ namespace ifactory)) ? TRUE : FALSE; #endif } + +#else // !WIN32 + inline void * _aligned_malloc(size_t size, size_t alignment) + { + size = (size + alignment - 1) & ~(alignment - 1); + return std::aligned_alloc(alignment, size); + } + + #define _aligned_free free +#endif } +#ifdef WIN32 //===================================================================================== // WIC Utilities //===================================================================================== @@ -123,7 +135,7 @@ namespace _Use_decl_annotations_ DXGI_FORMAT DirectX::_WICToDXGI(const GUID& guid) noexcept { - for (size_t i = 0; i < _countof(g_WICFormats); ++i) + for (size_t i = 0; i < std::size(g_WICFormats); ++i) { if (memcmp(&g_WICFormats[i].wic, &guid, sizeof(GUID)) == 0) return g_WICFormats[i].format; @@ -186,7 +198,7 @@ bool DirectX::_DXGIToWIC(DXGI_FORMAT format, GUID& guid, bool ignoreRGBvsBGR) no #endif default: - for (size_t i = 0; i < _countof(g_WICFormats); ++i) + for (size_t i = 0; i < std::size(g_WICFormats); ++i) { if (g_WICFormats[i].format == format) { @@ -205,7 +217,7 @@ TEX_FILTER_FLAGS DirectX::_CheckWICColorSpace(_In_ const GUID& sourceGUID, _In_ { TEX_FILTER_FLAGS srgb = TEX_FILTER_DEFAULT; - for (size_t i = 0; i < _countof(g_WICFormats); ++i) + for (size_t i = 0; i < std::size(g_WICFormats); ++i) { if (memcmp(&g_WICFormats[i].wic, &sourceGUID, sizeof(GUID)) == 0) { @@ -317,7 +329,7 @@ void DirectX::SetWICFactory(_In_opt_ IWICImagingFactory* pWIC) noexcept if (pWIC) pWIC->Release(); } - +#endif // WIN32 //===================================================================================== @@ -1056,7 +1068,7 @@ HRESULT DirectX::ComputePitch(DXGI_FORMAT fmt, size_t width, size_t height, if (pitch > UINT32_MAX || slice > UINT32_MAX) { rowPitch = slicePitch = 0; - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; } #else static_assert(sizeof(size_t) == 8, "Not a 64-bit platform!"); @@ -1498,3 +1510,25 @@ HRESULT Blob::Trim(size_t size) noexcept return S_OK; } + +HRESULT Blob::Resize(size_t size) noexcept +{ + if (!size) + return E_INVALIDARG; + + if (!m_buffer || !m_size) + return E_UNEXPECTED; + + void *tbuffer = _aligned_malloc(size, 16); + if (!tbuffer) + return E_OUTOFMEMORY; + + memcpy(tbuffer, m_buffer, std::min(m_size, size)); + + Release(); + + m_buffer = tbuffer; + m_size = size; + + return S_OK; +} diff --git a/Kits/DirectXTex/DirectXTexWIC.cpp b/Kits/DirectXTex/DirectXTexWIC.cpp index 57315a41..94f92f34 100644 --- a/Kits/DirectXTex/DirectXTexWIC.cpp +++ b/Kits/DirectXTex/DirectXTexWIC.cpp @@ -3,7 +3,7 @@ // // DirectX Texture Library - WIC-based file reader/writer // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -11,72 +11,14 @@ #include "DirectXTexP.h" -//------------------------------------------------------------------------------------- -// IStream support for WIC Memory routines -//------------------------------------------------------------------------------------- - -#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) && (WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP) - - #include - #pragma comment(lib,"shcore.lib") - -#ifdef __cplusplus_winrt - - static inline HRESULT CreateMemoryStream(_Outptr_ IStream** stream) - { - auto randomAccessStream = ref new ::Windows::Storage::Streams::InMemoryRandomAccessStream(); - return CreateStreamOverRandomAccessStream(randomAccessStream, IID_PPV_ARGS(stream)); - } - -#else - -#pragma warning(push) -#pragma warning(disable : 4619 5038) - #include - #include -#pragma warning(pop) - -#pragma warning(push) -#pragma warning(disable : 4471 5204) - #include -#pragma warning(pop) - - static inline HRESULT CreateMemoryStream(_Outptr_ IStream** stream) - { - Microsoft::WRL::ComPtr abiStream; - HRESULT hr = Windows::Foundation::ActivateInstance( - Microsoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_Storage_Streams_InMemoryRandomAccessStream).Get(), - abiStream.GetAddressOf()); - - if (SUCCEEDED(hr)) - { - hr = CreateStreamOverRandomAccessStream(abiStream.Get(), IID_PPV_ARGS(stream)); - } - return hr; - } - -#endif // __cplusplus_winrt - -#else - - #pragma prefast(suppress:6387 28196, "a simple wrapper around an existing annotated function" ); - static inline HRESULT CreateMemoryStream(_Outptr_ IStream** stream) noexcept - { - return CreateStreamOnHGlobal(nullptr, TRUE, stream); - } - -#endif - using namespace DirectX; using Microsoft::WRL::ComPtr; namespace { - //------------------------------------------------------------------------------------- // WIC Pixel Format nearest conversion table //------------------------------------------------------------------------------------- - struct WICConvert { const GUID& source; @@ -183,7 +125,7 @@ namespace } else { - for (size_t i = 0; i < _countof(g_WICConvert); ++i) + for (size_t i = 0; i < std::size(g_WICConvert); ++i) { if (memcmp(&g_WICConvert[i].source, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0) { @@ -249,6 +191,331 @@ namespace } + //------------------------------------------------------------------------------------- + // IStream over a Blob for WIC in-memory write functions + //------------------------------------------------------------------------------------- + class MemoryStreamOnBlob : public IStream + { + MemoryStreamOnBlob(Blob& blob) noexcept : + mBlob(blob), + m_streamPosition(0), + m_streamEOF(0), + mRefCount(1) + { + assert(mBlob.GetBufferPointer() && mBlob.GetBufferSize() > 0); + } + + public: + virtual ~MemoryStreamOnBlob() = default; + + MemoryStreamOnBlob(MemoryStreamOnBlob&&) = delete; + MemoryStreamOnBlob& operator= (MemoryStreamOnBlob&&) = delete; + + MemoryStreamOnBlob(MemoryStreamOnBlob const&) = delete; + MemoryStreamOnBlob& operator= (MemoryStreamOnBlob const&) = delete; + + // IUnknown + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** ppvObject) override + { + if (iid == __uuidof(IUnknown) + || iid == __uuidof(IStream) + || iid == __uuidof(ISequentialStream)) + { + *ppvObject = static_cast(this); + AddRef(); + return S_OK; + } + else + return E_NOINTERFACE; + } + + ULONG STDMETHODCALLTYPE AddRef() override + { + return InterlockedIncrement(&mRefCount); + } + + ULONG STDMETHODCALLTYPE Release() override + { + ULONG res = InterlockedDecrement(&mRefCount); + if (res == 0) + { + delete this; + } + return res; + } + + // ISequentialStream + HRESULT STDMETHODCALLTYPE Read(void* pv, ULONG cb, ULONG* pcbRead) override + { + size_t maxRead = m_streamEOF - m_streamPosition; + auto ptr = static_cast(mBlob.GetBufferPointer()); + if (cb > maxRead) + { + uint64_t pos = uint64_t(m_streamPosition) + uint64_t(maxRead); + if (pos > UINT32_MAX) + return HRESULT_E_ARITHMETIC_OVERFLOW; + + memcpy(pv, &ptr[m_streamPosition], maxRead); + + m_streamPosition = static_cast(pos); + + if (pcbRead) + { + *pcbRead = static_cast(maxRead); + } + return E_BOUNDS; + } + else + { + uint64_t pos = uint64_t(m_streamPosition) + uint64_t(cb); + if (pos > UINT32_MAX) + return HRESULT_E_ARITHMETIC_OVERFLOW; + + memcpy(pv, &ptr[m_streamPosition], cb); + + m_streamPosition = static_cast(pos); + + if (pcbRead) + { + *pcbRead = cb; + } + return S_OK; + } + } + + HRESULT STDMETHODCALLTYPE Write(void const* pv, ULONG cb, ULONG* pcbWritten) override + { + size_t blobSize = mBlob.GetBufferSize(); + size_t spaceAvailable = blobSize - m_streamPosition; + size_t growAmount = cb; + + if (spaceAvailable > 0) + { + if (spaceAvailable >= growAmount) + { + growAmount = 0; + } + else + { + growAmount -= spaceAvailable; + } + } + + if (growAmount > 0) + { + uint64_t newSize = uint64_t(blobSize); + uint64_t targetSize = uint64_t(blobSize) + growAmount; + HRESULT hr = ComputeGrowSize(newSize, targetSize); + if (FAILED(hr)) + return hr; + + hr = mBlob.Resize(static_cast(newSize)); + if (FAILED(hr)) + return hr; + } + + uint64_t pos = uint64_t(m_streamPosition) + uint64_t(cb); + if (pos > UINT32_MAX) + return HRESULT_E_ARITHMETIC_OVERFLOW; + + auto ptr = static_cast(mBlob.GetBufferPointer()); + memcpy(&ptr[m_streamPosition], pv, cb); + + m_streamPosition = static_cast(pos); + m_streamEOF = std::max(m_streamEOF, m_streamPosition); + + if (pcbWritten) + { + *pcbWritten = cb; + } + return S_OK; + } + + // IStream + HRESULT STDMETHODCALLTYPE SetSize(ULARGE_INTEGER size) override + { + if (size.HighPart > 0) + return E_OUTOFMEMORY; + + size_t blobSize = mBlob.GetBufferSize(); + + if (blobSize >= size.LowPart) + { + auto ptr = static_cast(mBlob.GetBufferPointer()); + if (m_streamEOF < size.LowPart) + { + memset(&ptr[m_streamEOF], 0, size.LowPart - m_streamEOF); + } + + m_streamEOF = static_cast(size.LowPart); + } + else + { + uint64_t newSize = uint64_t(blobSize); + uint64_t targetSize = uint64_t(size.QuadPart); + HRESULT hr = ComputeGrowSize(newSize, targetSize); + if (FAILED(hr)) + return hr; + + hr = mBlob.Resize(static_cast(newSize)); + if (FAILED(hr)) + return hr; + + blobSize = mBlob.GetBufferSize(); + + auto ptr = static_cast(mBlob.GetBufferPointer()); + if (m_streamEOF < size.LowPart) + { + memset(&ptr[m_streamEOF], 0, size.LowPart - m_streamEOF); + } + + m_streamEOF = static_cast(size.LowPart); + } + + if (m_streamPosition > m_streamEOF) + { + m_streamPosition = m_streamEOF; + } + + return S_OK; + } + + HRESULT STDMETHODCALLTYPE CopyTo(IStream*, ULARGE_INTEGER, ULARGE_INTEGER*, ULARGE_INTEGER*) override + { + return E_NOTIMPL; + } + + HRESULT STDMETHODCALLTYPE Commit(DWORD) override + { + return E_NOTIMPL; + } + + HRESULT STDMETHODCALLTYPE Revert(void) override + { + return E_NOTIMPL; + } + + HRESULT STDMETHODCALLTYPE LockRegion(ULARGE_INTEGER, ULARGE_INTEGER, DWORD) override + { + return E_NOTIMPL; + } + + HRESULT STDMETHODCALLTYPE UnlockRegion(ULARGE_INTEGER, ULARGE_INTEGER, DWORD) override + { + return E_NOTIMPL; + } + + HRESULT STDMETHODCALLTYPE Clone(IStream**) override + { + return E_NOTIMPL; + } + + HRESULT STDMETHODCALLTYPE Seek(LARGE_INTEGER liDistanceToMove, DWORD dwOrigin, ULARGE_INTEGER* lpNewFilePointer) override + { + LONGLONG newPosition = 0; + + switch (dwOrigin) + { + case STREAM_SEEK_SET: + newPosition = liDistanceToMove.QuadPart; + break; + + case STREAM_SEEK_CUR: + newPosition = static_cast(m_streamPosition) + liDistanceToMove.QuadPart; + break; + + case STREAM_SEEK_END: + newPosition = static_cast(m_streamEOF) + liDistanceToMove.QuadPart; + break; + + default: + return STG_E_INVALIDFUNCTION; + } + + HRESULT result = S_OK; + + if (newPosition > static_cast(m_streamEOF)) + { + m_streamPosition = m_streamEOF; + result = E_BOUNDS; + } + else if (newPosition < 0) + { + m_streamPosition = 0; + result = E_BOUNDS; + } + else + { + m_streamPosition = static_cast(newPosition); + } + + if (lpNewFilePointer) + { + lpNewFilePointer->QuadPart = static_cast(m_streamPosition); + } + + return result; + } + + HRESULT STDMETHODCALLTYPE Stat(STATSTG* pStatstg, DWORD) override + { + if (!pStatstg) + return E_INVALIDARG; + pStatstg->cbSize.QuadPart = static_cast(m_streamEOF); + return S_OK; + } + + HRESULT Finialize() noexcept + { + if (mRefCount > 1) + return E_FAIL; + + return mBlob.Trim(m_streamEOF); + } + + static HRESULT CreateMemoryStream(_Outptr_ MemoryStreamOnBlob** stream, Blob& blob) noexcept + { + if (!stream) + return E_INVALIDARG; + + *stream = nullptr; + + auto ptr = new (std::nothrow) MemoryStreamOnBlob(blob); + if (!ptr) + return E_OUTOFMEMORY; + + *stream = ptr; + + return S_OK; + } + + private: + Blob& mBlob; + size_t m_streamPosition; + size_t m_streamEOF; + ULONG mRefCount; + + static HRESULT ComputeGrowSize(uint64_t& newSize, uint64_t& targetSize) noexcept + { + // We grow by doubling until we hit 256MB, then we add 16MB at a time. + while (newSize < targetSize) + { + if (newSize < (256 * 1024 * 1024)) + { + newSize <<= 1; + } + else + { + newSize += 16 * 1024 * 1024; + } + if (newSize > UINT32_MAX) + return E_OUTOFMEMORY; + } + + return S_OK; + } + }; + //------------------------------------------------------------------------------------- // Determines metadata for image //------------------------------------------------------------------------------------- @@ -297,7 +564,7 @@ namespace TEX_ALPHA_MODE alphaMode; metadata.format = DetermineFormat(pixelFormat, flags, iswic2, pConvert, &alphaMode); if (metadata.format == DXGI_FORMAT_UNKNOWN) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; metadata.SetAlphaMode(alphaMode); @@ -420,7 +687,7 @@ namespace return E_NOINTERFACE; if (img->rowPitch > UINT32_MAX || img->slicePitch > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; if (memcmp(&convertGUID, &GUID_NULL, sizeof(GUID)) == 0) { @@ -492,7 +759,7 @@ namespace return E_POINTER; if (img->rowPitch > UINT32_MAX || img->slicePitch > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; ComPtr frame; hr = decoder->GetFrame(static_cast(index), frame.GetAddressOf()); @@ -714,7 +981,7 @@ namespace WICPixelFormatGUID pfGuid; if (!_DXGIToWIC(image.format, pfGuid)) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; HRESULT hr = frame->Initialize(props); if (FAILED(hr)) @@ -724,7 +991,7 @@ namespace return E_INVALIDARG; if (image.rowPitch > UINT32_MAX || image.slicePitch > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); + return HRESULT_E_ARITHMETIC_OVERFLOW; hr = frame->SetSize(static_cast(image.width), static_cast(image.height)); if (FAILED(hr)) @@ -902,7 +1169,7 @@ namespace return hr; if (!mframe) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return HRESULT_E_NOT_SUPPORTED; hr = encoder->Initialize(stream, WICBitmapEncoderNoCache); if (FAILED(hr)) @@ -954,7 +1221,7 @@ HRESULT DirectX::GetMetadataFromWICMemory( return E_INVALIDARG; if (size > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); + return HRESULT_E_FILE_TOO_LARGE; bool iswic2 = false; auto pWIC = GetWICFactory(iswic2); @@ -1046,7 +1313,7 @@ HRESULT DirectX::LoadFromWICMemory( return E_INVALIDARG; if (size > UINT32_MAX) - return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); + return HRESULT_E_FILE_TOO_LARGE; bool iswic2 = false; auto pWIC = GetWICFactory(iswic2); @@ -1181,42 +1448,33 @@ HRESULT DirectX::SaveToWICMemory( if (!image.pixels) return E_POINTER; - blob.Release(); - - ComPtr stream; - HRESULT hr = CreateMemoryStream(stream.GetAddressOf()); - if (FAILED(hr)) - return hr; - - hr = EncodeSingleFrame(image, flags, containerFormat, stream.Get(), targetFormat, setCustomProps); - if (FAILED(hr)) - return hr; - - // Copy stream data into blob - STATSTG stat; - hr = stream->Stat(&stat, STATFLAG_NONAME); + HRESULT hr = blob.Initialize(65535u); if (FAILED(hr)) return hr; - if (stat.cbSize.HighPart > 0) - return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); - - hr = blob.Initialize(stat.cbSize.LowPart); + ComPtr stream; + hr = MemoryStreamOnBlob::CreateMemoryStream(&stream, blob); if (FAILED(hr)) + { + blob.Release(); return hr; + } - LARGE_INTEGER li = {}; - hr = stream->Seek(li, STREAM_SEEK_SET, nullptr); + hr = EncodeSingleFrame(image, flags, containerFormat, stream.Get(), targetFormat, setCustomProps); if (FAILED(hr)) + { + blob.Release(); return hr; + } - DWORD bytesRead; - hr = stream->Read(blob.GetBufferPointer(), static_cast(blob.GetBufferSize()), &bytesRead); + hr = stream->Finialize(); if (FAILED(hr)) + { + blob.Release(); return hr; + } - if (bytesRead != blob.GetBufferSize()) - return E_FAIL; + stream.Reset(); return S_OK; } @@ -1234,12 +1492,17 @@ HRESULT DirectX::SaveToWICMemory( if (!images || nimages == 0) return E_INVALIDARG; - blob.Release(); + HRESULT hr = blob.Initialize(65535u); + if (FAILED(hr)) + return hr; - ComPtr stream; - HRESULT hr = CreateMemoryStream(stream.GetAddressOf()); + ComPtr stream; + hr = MemoryStreamOnBlob::CreateMemoryStream(&stream, blob); if (FAILED(hr)) + { + blob.Release(); return hr; + } if (nimages > 1) hr = EncodeMultiframe(images, nimages, flags, containerFormat, stream.Get(), targetFormat, setCustomProps); @@ -1247,33 +1510,19 @@ HRESULT DirectX::SaveToWICMemory( hr = EncodeSingleFrame(images[0], flags, containerFormat, stream.Get(), targetFormat, setCustomProps); if (FAILED(hr)) + { + blob.Release(); return hr; + } - // Copy stream data into blob - STATSTG stat; - hr = stream->Stat(&stat, STATFLAG_NONAME); - if (FAILED(hr)) - return hr; - - if (stat.cbSize.HighPart > 0) - return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); - - hr = blob.Initialize(stat.cbSize.LowPart); - if (FAILED(hr)) - return hr; - - LARGE_INTEGER li = {}; - hr = stream->Seek(li, STREAM_SEEK_SET, nullptr); - if (FAILED(hr)) - return hr; - - DWORD bytesRead; - hr = stream->Read(blob.GetBufferPointer(), static_cast(blob.GetBufferSize()), &bytesRead); + hr = stream->Finialize(); if (FAILED(hr)) + { + blob.Release(); return hr; + } - if (bytesRead != blob.GetBufferSize()) - return E_FAIL; + stream.Reset(); return S_OK; } diff --git a/Kits/DirectXTex/DirectXTexXbox.h b/Kits/DirectXTex/DirectXTexXbox.h index 0debbf6a..cc272a79 100644 --- a/Kits/DirectXTex/DirectXTexXbox.h +++ b/Kits/DirectXTex/DirectXTexXbox.h @@ -3,7 +3,7 @@ // // DirectXTex Auxillary functions for Xbox One texture processing // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- @@ -15,21 +15,35 @@ #include "DirectXTex.h" +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) +#include +#else #include +#endif -#if defined(_XBOX_ONE) && defined(_TITLE) +#ifdef _GAMING_XBOX_SCARLETT +#include +#elif defined(_GAMING_XBOX) +#include +#elif defined(_XBOX_ONE) && defined(_TITLE) #include #else #include #endif -#define DIRECTX_TEX_XBOX_VERSION 102 +#define DIRECTX_TEX_XBOX_VERSION 150 namespace Xbox { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + using XboxTileMode = XG_SWIZZLE_MODE; + const XboxTileMode c_XboxTileModeInvalid = XG_SWIZZLE_MODE_INVALID; + const XboxTileMode c_XboxTileModeLinear = XG_SWIZZLE_MODE_LINEAR; +#else using XboxTileMode = XG_TILE_MODE; constexpr XboxTileMode c_XboxTileModeInvalid = XG_TILE_MODE_INVALID; const XboxTileMode c_XboxTileModeLinear = XG_TILE_MODE_LINEAR; +#endif class XboxImage { @@ -116,9 +130,7 @@ namespace Xbox //--------------------------------------------------------------------------------- // Direct3D 12.X functions -#if defined(_XBOX_ONE) && defined(_TITLE) && (defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__)) - - +#if ((defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX)) && (defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__)) HRESULT CreateTexture( _In_ ID3D12Device* d3dDevice, diff --git a/Kits/DirectXTex/DirectXTexXboxD3D11X.cpp b/Kits/DirectXTex/DirectXTexXboxD3D11X.cpp index fc253c6a..3ed068ac 100644 --- a/Kits/DirectXTex/DirectXTexXboxD3D11X.cpp +++ b/Kits/DirectXTex/DirectXTexXboxD3D11X.cpp @@ -4,14 +4,16 @@ // DirectXTex Auxillary functions for creating resouces from XboxImage containers // via the CreatePlacement APIs // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- #include "DirectXTexP.h" #include "DirectXTexXbox.h" -#if !defined(_XBOX_ONE) || !defined(_TITLE) +#ifdef _GAMING_XBOX +#error This module is not supported for GDK +#elif !defined(_XBOX_ONE) || !defined(_TITLE) #error This module only supports Xbox One exclusive apps #endif @@ -253,4 +255,4 @@ void Xbox::FreeTextureMemory(ID3D11DeviceX* d3dDevice, void* grfxMemory) { XMemFree(grfxMemory, c_XMemAllocAttributes); } -} \ No newline at end of file +} diff --git a/Kits/DirectXTex/DirectXTexXboxD3D12X.cpp b/Kits/DirectXTex/DirectXTexXboxD3D12X.cpp index a09ee73e..50590dfb 100644 --- a/Kits/DirectXTex/DirectXTexXboxD3D12X.cpp +++ b/Kits/DirectXTex/DirectXTexXboxD3D12X.cpp @@ -4,17 +4,21 @@ // DirectXTex Auxillary functions for creating resouces from XboxImage containers // via the CreatePlacedResourceX API // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- #include "DirectXTexP.h" #include "DirectXTexXbox.h" -#if !defined(_XBOX_ONE) || !defined(_TITLE) +#if !(defined(_XBOX_ONE) && defined(_TITLE)) && !defined(_GAMING_XBOX) #error This module only supports Xbox exclusive apps #endif +#ifdef _GAMING_XBOX +#include +#endif + using namespace Xbox; using Microsoft::WRL::ComPtr; @@ -28,7 +32,11 @@ namespace 0, XALLOC_MEMTYPE_GRAPHICS_WRITECOMBINE_GPU_READONLY, XALLOC_PAGESIZE_64KB, - XALLOC_ALIGNMENT_64K); + XALLOC_ALIGNMENT_64K +#ifdef _GAMING_XBOX + , 0 +#endif + ); } //===================================================================================== @@ -106,4 +114,4 @@ void Xbox::FreeTextureMemory(ID3D12Device* d3dDevice, void* grfxMemory) { XMemFree(grfxMemory, c_XMemAllocAttributes); } -} \ No newline at end of file +} diff --git a/Kits/DirectXTex/DirectXTexXboxDDS.cpp b/Kits/DirectXTex/DirectXTexXboxDDS.cpp index 3e2f44c8..8e9c3121 100644 --- a/Kits/DirectXTex/DirectXTexXboxDDS.cpp +++ b/Kits/DirectXTex/DirectXTexXboxDDS.cpp @@ -3,7 +3,7 @@ // // DirectXTex Auxillary functions for saving "XBOX" Xbox One variants of DDS files // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- @@ -11,7 +11,12 @@ #include "DirectXTexXbox.h" #include "DDS.h" + +#if defined(_GAMING_XBOX) || defined(_USE_GXDK) +#include "gxdk.h" +#else #include "xdk.h" +#endif using namespace DirectX; using namespace Xbox; @@ -31,14 +36,16 @@ namespace uint32_t miscFlag; // see DDS_RESOURCE_MISC_FLAG uint32_t arraySize; uint32_t miscFlags2; // see DDS_MISC_FLAGS2 - uint32_t tileMode; // see XG_TILE_MODE + uint32_t tileMode; // see XG_TILE_MODE / XG_SWIZZLE_MODE uint32_t baseAlignment; uint32_t dataSize; - uint32_t xdkVer; // matching _XDK_VER + uint32_t xdkVer; // matching _XDK_VER / _GXDK_VER }; #pragma pack(pop) + static const uint32_t XBOX_TILEMODE_SCARLETT = 0x1000000; + static_assert(sizeof(DDS_HEADER_XBOX) == 36, "DDS XBOX Header size mismatch"); static_assert(sizeof(DDS_HEADER_XBOX) >= sizeof(DDS_HEADER_DXT10), "DDS XBOX Header should be larger than DX10 header"); @@ -109,10 +116,17 @@ namespace auto xboxext = reinterpret_cast( reinterpret_cast(pSource) + sizeof(uint32_t) + sizeof(DDS_HEADER)); +#ifdef _GXDK_VER + if (xboxext->xdkVer < _GXDK_VER) + { + OutputDebugStringA("WARNING: DDS XBOX file may be outdated and need regeneration\n"); + } +#elif defined(_XDK_VER) if (xboxext->xdkVer < _XDK_VER) { OutputDebugStringA("WARNING: DDS XBOX file may be outdated and need regeneration\n"); } +#endif metadata.arraySize = xboxext->arraySize; if (metadata.arraySize == 0) @@ -182,6 +196,18 @@ namespace return HRESULT_FROM_WIN32(ERROR_INVALID_DATA); } +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + else if (!(xboxext->tileMode & XBOX_TILEMODE_SCARLETT)) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } +#else + else if (xboxext->tileMode & XBOX_TILEMODE_SCARLETT) + { + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + } +#endif + static_assert(static_cast(TEX_MISC2_ALPHA_MODE_MASK) == static_cast(DDS_MISC_FLAGS2_ALPHA_MODE_MASK), "DDS header mismatch"); static_assert(static_cast(TEX_ALPHA_MODE_UNKNOWN) == static_cast(DDS_ALPHA_MODE_UNKNOWN), "DDS header mismatch"); @@ -193,7 +219,9 @@ namespace metadata.miscFlags2 = xboxext->miscFlags2; if (tmode) - *tmode = static_cast(xboxext->tileMode); + { + *tmode = static_cast(xboxext->tileMode & ~XBOX_TILEMODE_SCARLETT); + } if (baseAlignment) *baseAlignment = xboxext->baseAlignment; @@ -340,10 +368,19 @@ namespace xboxext->miscFlags2 = metadata.miscFlags2; +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + xboxext->tileMode = static_cast(xbox.GetTileMode()) | XBOX_TILEMODE_SCARLETT; +#else xboxext->tileMode = static_cast(xbox.GetTileMode()); +#endif + xboxext->baseAlignment = xbox.GetAlignment(); xboxext->dataSize = xbox.GetSize(); +#ifdef _GXDK_VER + xboxext->xdkVer = _GXDK_VER; +#elif defined(_XDK_VER) xboxext->xdkVer = _XDK_VER; +#endif return S_OK; } @@ -678,9 +715,11 @@ HRESULT Xbox::SaveToDDSFile(const XboxImage& xbox, const wchar_t* szFile) // Create file and write header #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) - ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr))); + ScopedHandle hFile(safe_handle(CreateFile2(szFile, + GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr))); #else - ScopedHandle hFile(safe_handle(CreateFileW(szFile, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr))); + ScopedHandle hFile(safe_handle(CreateFileW(szFile, + GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr))); #endif if (!hFile) { diff --git a/Kits/DirectXTex/DirectXTexXboxDetile.cpp b/Kits/DirectXTex/DirectXTexXboxDetile.cpp index 90bc1f1f..af113990 100644 --- a/Kits/DirectXTex/DirectXTexXboxDetile.cpp +++ b/Kits/DirectXTex/DirectXTexXboxDetile.cpp @@ -3,7 +3,7 @@ // // DirectXTex Auxillary functions for converting from Xbox One tiled to linear // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- @@ -46,7 +46,12 @@ namespace for (size_t x = 0; x < w; ++x) { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + UINT64 element = (packed) ? (x >> 1) : x; + size_t offset = computer->GetTexelElementOffsetBytes(0, level, element, 0, item, 0, nullptr); +#else size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, 0, item, 0); +#endif if (offset == size_t(-1)) return E_FAIL; @@ -101,7 +106,12 @@ namespace for (size_t x = 0; x < w; ++x) { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + UINT64 element = (packed) ? (x >> 1) : x; + size_t offset = computer->GetTexelElementOffsetBytes(0, level, element, y, item, 0, nullptr); +#else size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, y, item, 0); +#endif if (offset == size_t(-1)) return E_FAIL; @@ -152,7 +162,12 @@ namespace for (size_t x = 0; x < w; ++x) { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + UINT64 element = (packed) ? (x >> 1) : x; + size_t offset = computer->GetTexelElementOffsetBytes(0, level, element, y, z, 0, nullptr); +#else size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, y, z, 0); +#endif if (offset == size_t(-1)) return E_FAIL; @@ -203,6 +218,10 @@ namespace assert(!IsCompressed(format)); bool byelement = IsTypeless(format); +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + if (nimages > 1) + byelement = true; +#endif if (IsPacked(format)) { @@ -233,7 +252,7 @@ namespace UINT32 tiledPixels = mip.PitchPixels * mip.PaddedDepthOrArraySize; - ScopedAlignedArrayXMVECTOR scanline(reinterpret_cast(_aligned_malloc(sizeof(XMVECTOR) * (tiledPixels + result[0]->width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(tiledPixels + result[0]->width); XMVECTOR* target = scanline.get(); XMVECTOR* tiled = target + result[0]->width; @@ -264,7 +283,11 @@ namespace for (size_t x = 0; x < img->width; ++x) { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, 0, item, 0, nullptr); +#else size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, 0, item, 0); +#endif if (offset == size_t(-1)) return E_FAIL; @@ -312,6 +335,10 @@ namespace assert(format == xbox.GetMetadata().format); bool byelement = IsTypeless(format); +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + if (nimages > 1) + byelement = true; +#endif if (IsCompressed(format)) { @@ -366,9 +393,7 @@ namespace const UINT32 tiledPixels = mip.PaddedWidthElements * mip.PaddedHeightElements * mip.PaddedDepthOrArraySize; - ScopedAlignedArrayXMVECTOR scanline( - reinterpret_cast(_aligned_malloc( - sizeof(XMVECTOR) * (tiledPixels + result[0]->width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(tiledPixels + result[0]->width); XMVECTOR* target = scanline.get(); XMVECTOR* tiled = target + result[0]->width; @@ -402,7 +427,11 @@ namespace { for (size_t x = 0; x < img->width; ++x) { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, y, item, 0, nullptr); +#else size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, y, item, 0); +#endif if (offset == size_t(-1)) return E_FAIL; @@ -446,6 +475,9 @@ namespace assert(layout.Planes == 1); bool byelement = IsTypeless(result.format); +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + byelement = true; +#endif if (IsCompressed(result.format)) { @@ -496,9 +528,7 @@ namespace const UINT32 tiledPixels = mip.PaddedWidthElements * mip.PaddedHeightElements * mip.PaddedDepthOrArraySize; assert(tiledPixels >= (result.width * result.height * slices)); - ScopedAlignedArrayXMVECTOR scanline( - reinterpret_cast(_aligned_malloc( - sizeof(XMVECTOR) * (tiledPixels + result.width), 16))); + auto scanline = make_AlignedArrayXMVECTOR(tiledPixels + result.width); XMVECTOR* target = scanline.get(); XMVECTOR* tiled = target + result.width; @@ -546,7 +576,11 @@ namespace { for (size_t x = 0; x < result.width; ++x) { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, y, z, 0, nullptr); +#else size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, y, z, 0); +#endif if (offset == size_t(-1)) return E_FAIL; @@ -624,7 +658,11 @@ HRESULT Xbox::Detile( desc.Usage = XG_USAGE_DEFAULT; desc.BindFlags = XG_BIND_SHADER_RESOURCE; desc.MiscFlags = (metadata.IsCubemap()) ? XG_RESOURCE_MISC_TEXTURECUBE : 0; +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + desc.SwizzleMode = xbox.GetTileMode(); +#else desc.TileMode = xbox.GetTileMode(); +#endif ComPtr computer; HRESULT hr = XGCreateTexture1DComputer(&desc, computer.GetAddressOf()); @@ -699,7 +737,11 @@ HRESULT Xbox::Detile( desc.Usage = XG_USAGE_DEFAULT; desc.BindFlags = XG_BIND_SHADER_RESOURCE; desc.MiscFlags = (metadata.miscFlags & TEX_MISC_TEXTURECUBE) ? XG_RESOURCE_MISC_TEXTURECUBE : 0; +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + desc.SwizzleMode = xbox.GetTileMode(); +#else desc.TileMode = xbox.GetTileMode(); +#endif ComPtr computer; HRESULT hr = XGCreateTexture2DComputer(&desc, computer.GetAddressOf()); @@ -772,7 +814,11 @@ HRESULT Xbox::Detile( desc.Format = static_cast(metadata.format); desc.Usage = XG_USAGE_DEFAULT; desc.BindFlags = XG_BIND_SHADER_RESOURCE; +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + desc.SwizzleMode = xbox.GetTileMode(); +#else desc.TileMode = xbox.GetTileMode(); +#endif ComPtr computer; HRESULT hr = XGCreateTexture3DComputer(&desc, computer.GetAddressOf()); diff --git a/Kits/DirectXTex/DirectXTexXboxImage.cpp b/Kits/DirectXTex/DirectXTexXboxImage.cpp index 019dd3bf..6bfb3728 100644 --- a/Kits/DirectXTex/DirectXTexXboxImage.cpp +++ b/Kits/DirectXTex/DirectXTexXboxImage.cpp @@ -3,7 +3,7 @@ // // DirectXTex Auxillary functions for Xbox One texture blob // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- @@ -177,6 +177,8 @@ HRESULT XboxImage::Initialize(const XG_TEXTURE1D_DESC& desc, const XG_RESOURCE_L if (!memory) return E_OUTOFMEMORY; + memset(memory, 0, layout.SizeBytes); + memset(&metadata, 0, sizeof(metadata)); metadata.width = desc.Width; metadata.height = 1; @@ -189,7 +191,11 @@ HRESULT XboxImage::Initialize(const XG_TEXTURE1D_DESC& desc, const XG_RESOURCE_L dataSize = static_cast(layout.SizeBytes); baseAlignment = static_cast(layout.BaseAlignmentBytes); +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + tilemode = desc.SwizzleMode; +#else tilemode = desc.TileMode; +#endif return S_OK; } @@ -211,6 +217,8 @@ HRESULT XboxImage::Initialize(const XG_TEXTURE2D_DESC& desc, const XG_RESOURCE_L if (!memory) return E_OUTOFMEMORY; + memset(memory, 0, layout.SizeBytes); + memset(&metadata, 0, sizeof(metadata)); metadata.width = desc.Width; metadata.height = desc.Height; @@ -224,7 +232,11 @@ HRESULT XboxImage::Initialize(const XG_TEXTURE2D_DESC& desc, const XG_RESOURCE_L dataSize = static_cast(layout.SizeBytes); baseAlignment = static_cast(layout.BaseAlignmentBytes); +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + tilemode = desc.SwizzleMode; +#else tilemode = desc.TileMode; +#endif return S_OK; } @@ -246,6 +258,8 @@ HRESULT XboxImage::Initialize(const XG_TEXTURE3D_DESC& desc, const XG_RESOURCE_L if (!memory) return E_OUTOFMEMORY; + memset(memory, 0, layout.SizeBytes); + memset(&metadata, 0, sizeof(metadata)); metadata.width = desc.Width; metadata.height = desc.Height; @@ -258,7 +272,11 @@ HRESULT XboxImage::Initialize(const XG_TEXTURE3D_DESC& desc, const XG_RESOURCE_L dataSize = static_cast(layout.SizeBytes); baseAlignment = static_cast(layout.BaseAlignmentBytes); +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + tilemode = desc.SwizzleMode; +#else tilemode = desc.TileMode; +#endif return S_OK; } @@ -276,6 +294,8 @@ HRESULT XboxImage::Initialize(const DirectX::TexMetadata& mdata, XboxTileMode tm if (!memory) return E_OUTOFMEMORY; + memset(memory, 0, size); + metadata = mdata; dataSize = size; diff --git a/Kits/DirectXTex/DirectXTexXboxTile.cpp b/Kits/DirectXTex/DirectXTexXboxTile.cpp index 9b08f4f3..0ea4ee26 100644 --- a/Kits/DirectXTex/DirectXTexXboxTile.cpp +++ b/Kits/DirectXTex/DirectXTexXboxTile.cpp @@ -3,7 +3,7 @@ // // DirectXTex Auxillary functions for converting from linear to Xbox One tiling // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- @@ -49,7 +49,12 @@ namespace for (size_t x = 0; x < w; ++x) { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + UINT64 element = (packed) ? (x >> 1) : x; + size_t offset = computer->GetTexelElementOffsetBytes(0, level, element, 0, item, 0, nullptr); +#else size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, 0, item, 0); +#endif if (offset == size_t(-1)) return E_FAIL; @@ -104,7 +109,12 @@ namespace for (size_t x = 0; x < w; ++x) { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + UINT64 element = (packed) ? (x >> 1) : x; + size_t offset = computer->GetTexelElementOffsetBytes(0, level, element, y, item, 0, nullptr); +#else size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, y, item, 0); +#endif if (offset == size_t(-1)) return E_FAIL; @@ -154,7 +164,12 @@ namespace for (size_t x = 0; x < w; ++x) { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + UINT64 element = (packed) ? (x >> 1) : x; + size_t offset = computer->GetTexelElementOffsetBytes(0, level, element, y, z, 0, nullptr); +#else size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, y, z, 0); +#endif if (offset == size_t(-1)) return E_FAIL; @@ -186,7 +201,11 @@ namespace wchar_t buff[2048] = {}; swprintf_s(buff, L"XG_TEXTURE1D_DESC = { %u, %u, %u, %u, %u, %u, %u, %u, %u, %u }\n", desc.Width, desc.MipLevels, desc.ArraySize, desc.Format, desc.Usage, desc.BindFlags, desc.CPUAccessFlags, desc.MiscFlags, +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + desc.SwizzleMode, +#else desc.TileMode, +#endif desc.Pitch); OutputDebugStringW(buff); } @@ -196,7 +215,11 @@ namespace wchar_t buff[2048] = {}; swprintf_s(buff, L"XG_TEXTURE2D_DESC = { %u, %u, %u, %u, %u, { %u, %u }, %u, %u, %u, %u, %u, %u }\n", desc.Width, desc.Height, desc.MipLevels, desc.ArraySize, desc.Format, desc.SampleDesc.Count, desc.SampleDesc.Quality, desc.Usage, desc.BindFlags, desc.CPUAccessFlags, desc.MiscFlags, +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + desc.SwizzleMode, +#else desc.TileMode, +#endif desc.Pitch); OutputDebugStringW(buff); } @@ -206,7 +229,11 @@ namespace wchar_t buff[2048] = {}; swprintf_s(buff, L"XG_TEXTURE3D_DESC = { %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u }\n", desc.Width, desc.Height, desc.Depth, desc.MipLevels, desc.Format, desc.Usage, desc.BindFlags, desc.CPUAccessFlags, desc.MiscFlags, +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + desc.SwizzleMode, +#else desc.TileMode, +#endif desc.Pitch); OutputDebugStringW(buff); } @@ -239,7 +266,11 @@ namespace swprintf_s(buff, L"\t\tpitch %u pixels (%u bytes)\n", mip.PitchPixels, mip.PitchBytes); OutputDebugStringW(buff); +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + swprintf_s(buff, L"\t\t\t%u samples, %u swizzlemode\n", mip.SampleCount, mip.SwizzleMode); +#else swprintf_s(buff, L"\t\t\t%u samples, %u tilemode\n", mip.SampleCount, mip.TileMode); +#endif OutputDebugStringW(buff); } } @@ -272,6 +303,10 @@ namespace assert(!IsCompressed(format)); bool byelement = IsTypeless(format); +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + if (nimages > 1) + byelement = true; +#endif if (IsPacked(format)) { @@ -302,8 +337,7 @@ namespace UINT32 tiledPixels = mip.PitchPixels * mip.PaddedDepthOrArraySize; - ScopedAlignedArrayXMVECTOR scanline(reinterpret_cast( - _aligned_malloc(sizeof(XMVECTOR) * (images[0]->width + (tiledPixels)), 16))); + auto scanline = make_AlignedArrayXMVECTOR(images[0]->width + tiledPixels); XMVECTOR* row = scanline.get(); XMVECTOR* tiled = row + images[0]->width; @@ -332,7 +366,11 @@ namespace for (size_t x = 0; x < img->width; ++x) { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, 0, item, 0, nullptr); +#else size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, 0, item, 0); +#endif if (offset == size_t(-1)) return E_FAIL; @@ -380,6 +418,10 @@ namespace assert(format == xbox.GetMetadata().format); bool byelement = IsTypeless(format); +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + if (nimages > 1) + byelement = true; +#endif if (IsCompressed(format)) { @@ -434,9 +476,7 @@ namespace const UINT32 tiledPixels = mip.PaddedWidthElements * mip.PaddedHeightElements * mip.PaddedDepthOrArraySize; - ScopedAlignedArrayXMVECTOR scanline( - reinterpret_cast(_aligned_malloc( - sizeof(XMVECTOR) * (images[0]->width + tiledPixels), 16))); + auto scanline = make_AlignedArrayXMVECTOR(images[0]->width + tiledPixels); XMVECTOR* row = scanline.get(); XMVECTOR* tiled = row + images[0]->width; @@ -470,7 +510,11 @@ namespace for (size_t x = 0; x < img->width; ++x) { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, y, item, 0, nullptr); +#else size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, y, item, 0); +#endif if (offset == size_t(-1)) return E_FAIL; @@ -516,6 +560,9 @@ namespace assert(image.format == xbox.GetMetadata().format); bool byelement = IsTypeless(image.format); +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + byelement = true; +#endif if (IsCompressed(image.format)) { @@ -566,9 +613,7 @@ namespace const UINT32 tiledPixels = mip.PaddedWidthElements * mip.PaddedHeightElements * mip.PaddedDepthOrArraySize; assert(tiledPixels >= (image.width * image.height * slices)); - ScopedAlignedArrayXMVECTOR scanline( - reinterpret_cast(_aligned_malloc( - sizeof(XMVECTOR) * (image.width + tiledPixels), 16))); + auto scanline = make_AlignedArrayXMVECTOR(image.width + tiledPixels); XMVECTOR* row = scanline.get(); XMVECTOR* tiled = row + image.width; @@ -594,7 +639,11 @@ namespace for (size_t x = 0; x < image.width; ++x) { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, y, z, 0, nullptr); +#else size_t offset = computer->GetTexelElementOffsetBytes(0, level, x, y, z, 0); +#endif if (offset == size_t(-1)) return E_FAIL; @@ -671,9 +720,15 @@ HRESULT Xbox::Tile( if (mode == c_XboxTileModeInvalid) { // If no specific tile mode is given, assume the optimal default +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + mode = XGComputeOptimalSwizzleMode(XG_RESOURCE_DIMENSION_TEXTURE2D, static_cast(srcImage.format), + static_cast(srcImage.width), static_cast(srcImage.height), + 1, 1, XG_BIND_SHADER_RESOURCE); +#else mode = XGComputeOptimalTileMode(XG_RESOURCE_DIMENSION_TEXTURE2D, static_cast(srcImage.format), static_cast(srcImage.width), static_cast(srcImage.height), 1, 1, XG_BIND_SHADER_RESOURCE); +#endif } XG_TEXTURE2D_DESC desc = {}; @@ -685,7 +740,11 @@ HRESULT Xbox::Tile( desc.SampleDesc.Count = 1; desc.Usage = XG_USAGE_DEFAULT; desc.BindFlags = XG_BIND_SHADER_RESOURCE; +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + desc.SwizzleMode = mode; +#else desc.TileMode = mode; +#endif ComPtr computer; HRESULT hr = XGCreateTexture2DComputer(&desc, computer.GetAddressOf()); @@ -758,11 +817,18 @@ HRESULT Xbox::Tile( if (mode == c_XboxTileModeInvalid) { +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + mode = XGComputeOptimalSwizzleMode(static_cast(metadata.dimension), static_cast(metadata.format), + static_cast(metadata.width), static_cast(metadata.height), + static_cast((metadata.dimension == TEX_DIMENSION_TEXTURE3D) ? metadata.depth : metadata.arraySize), + 1, XG_BIND_SHADER_RESOURCE); +#else // If no specific tile mode is given, assume the optimal default mode = XGComputeOptimalTileMode(static_cast(metadata.dimension), static_cast(metadata.format), static_cast(metadata.width), static_cast(metadata.height), static_cast((metadata.dimension == TEX_DIMENSION_TEXTURE3D) ? metadata.depth : metadata.arraySize), 1, XG_BIND_SHADER_RESOURCE); +#endif } XG_RESOURCE_LAYOUT layout = {}; @@ -779,7 +845,11 @@ HRESULT Xbox::Tile( desc.Usage = XG_USAGE_DEFAULT; desc.BindFlags = XG_BIND_SHADER_RESOURCE; desc.MiscFlags = (metadata.IsCubemap()) ? XG_RESOURCE_MISC_TEXTURECUBE : 0; +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + desc.SwizzleMode = mode; +#else desc.TileMode = mode; +#endif #ifdef VERBOSE DebugPrintDesc(desc); @@ -859,7 +929,11 @@ HRESULT Xbox::Tile( desc.Usage = XG_USAGE_DEFAULT; desc.BindFlags = XG_BIND_SHADER_RESOURCE; desc.MiscFlags = (metadata.miscFlags & TEX_MISC_TEXTURECUBE) ? XG_RESOURCE_MISC_TEXTURECUBE : 0; +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + desc.SwizzleMode = mode; +#else desc.TileMode = mode; +#endif #ifdef VERBOSE DebugPrintDesc(desc); @@ -937,7 +1011,11 @@ HRESULT Xbox::Tile( desc.Format = static_cast(metadata.format); desc.Usage = XG_USAGE_DEFAULT; desc.BindFlags = XG_BIND_SHADER_RESOURCE; +#if defined(_GAMING_XBOX_SCARLETT) || defined(_USE_SCARLETT) + desc.SwizzleMode = mode; +#else desc.TileMode = mode; +#endif #ifdef VERBOSE DebugPrintDesc(desc); diff --git a/Kits/DirectXTex/DirectXTexp.h b/Kits/DirectXTex/DirectXTexp.h index bd3a1936..bb5a223c 100644 --- a/Kits/DirectXTex/DirectXTexp.h +++ b/Kits/DirectXTex/DirectXTexp.h @@ -1,9 +1,9 @@ //------------------------------------------------------------------------------------- -// DirectXTexp.h -// +// DirectXTexP.h +// // DirectX Texture Library - Private header // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -70,6 +70,7 @@ #pragma clang diagnostic ignored "-Wunknown-pragmas" #endif +#if defined(WIN32) || defined(_WIN32) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -85,12 +86,12 @@ #define NOHELP #pragma warning(pop) +#include + #ifndef _WIN32_WINNT_WIN10 #define _WIN32_WINNT_WIN10 0x0A00 #endif -#include - #ifdef _GAMING_XBOX_SCARLETT #include #elif defined(_GAMING_XBOX) @@ -99,34 +100,56 @@ #include #include #elif (_WIN32_WINNT >= _WIN32_WINNT_WIN10) +#ifdef USING_DIRECTX_HEADERS +#include +#include +#else #include +#endif #include #else #include #endif +#else // !WIN32 +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef WIN32 +#include +#include +#include +#endif #define _XM_NO_XMVECTOR_OVERLOADS_ -#include #include -#include -#include -#include +#if (DIRECTX_MATH_VERSION < 315) +#define XM_ALIGNED_DATA(x) __declspec(align(x)) +#endif -#include +#include "DirectXTex.h" -#include -#include -#include +#include +#ifdef WIN32 #include - -#include "DirectXTex.h" - #include - #include +#else +using WICPixelFormatGUID = GUID; +#endif #include "scoped.h" @@ -146,10 +169,34 @@ #define XBOX_DXGI_FORMAT_R4G4_UNORM DXGI_FORMAT(190) +// HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW) +#define HRESULT_E_ARITHMETIC_OVERFLOW static_cast(0x80070216L) + +// HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) +#define HRESULT_E_NOT_SUPPORTED static_cast(0x80070032L) + +// HRESULT_FROM_WIN32(ERROR_HANDLE_EOF) +#define HRESULT_E_HANDLE_EOF static_cast(0x80070026L) + +// HRESULT_FROM_WIN32(ERROR_INVALID_DATA) +#define HRESULT_E_INVALID_DATA static_cast(0x8007000DL) + +// HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE) +#define HRESULT_E_FILE_TOO_LARGE static_cast(0x800700DFL) + +// HRESULT_FROM_WIN32(ERROR_CANNOT_MAKE) +#define HRESULT_E_CANNOT_MAKE static_cast(0x80070052L) + +// HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) +#ifndef E_NOT_SUFFICIENT_BUFFER +#define E_NOT_SUFFICIENT_BUFFER static_cast(0x8007007AL) +#endif + namespace DirectX { //--------------------------------------------------------------------------------- // WIC helper functions +#ifdef WIN32 DXGI_FORMAT __cdecl _WICToDXGI(_In_ const GUID& guid) noexcept; bool __cdecl _DXGIToWIC(_In_ DXGI_FORMAT format, _Out_ GUID& guid, _In_ bool ignoreRGBvsBGR = false) noexcept; @@ -234,7 +281,7 @@ namespace DirectX return WICBitmapInterpolationModeFant; } } - +#endif // WIN32 //--------------------------------------------------------------------------------- // Image helper functions @@ -262,7 +309,7 @@ namespace DirectX CONVF_FLOAT = 0x1, CONVF_UNORM = 0x2, CONVF_UINT = 0x4, - CONVF_SNORM = 0x8, + CONVF_SNORM = 0x8, CONVF_SINT = 0x10, CONVF_DEPTH = 0x20, CONVF_STENCIL = 0x40, @@ -296,7 +343,7 @@ namespace DirectX void* pDestination, _In_ size_t outSize, _In_reads_bytes_(inSize) const void* pSource, _In_ size_t inSize, _In_ DXGI_FORMAT format, _In_ uint32_t tflags) noexcept; - + _Success_(return != false) bool __cdecl _ExpandScanline( _Out_writes_bytes_(outSize) void* pDestination, _In_ size_t outSize, _In_ DXGI_FORMAT outFormat, diff --git a/Kits/DirectXTex/README.md b/Kits/DirectXTex/README.md index 43188b90..c1d1492f 100644 --- a/Kits/DirectXTex/README.md +++ b/Kits/DirectXTex/README.md @@ -1,19 +1,21 @@ ![DirectX Logo](https://github.com/Microsoft/DirectXTex/wiki/X_jpg.jpg) -# DirectXTex texture processing library +# DirectXTex texture processing library (Xbox variant) http://go.microsoft.com/fwlink/?LinkId=248926 -Copyright (c) Microsoft Corporation. All rights reserved. +Copyright (c) Microsoft Corporation. -**September 30, 2020** +**June 9, 2021** This package contains DirectXTex, a shared source library for reading and writing ``.DDS`` files, and performing various texture content processing operations including resizing, format conversion, mip-map generation, block compression for Direct3D runtime texture resources, and height-map to normal-map conversion. This library makes use of the Windows Image Component (WIC) APIs. It also includes ``.TGA`` and ``.HDR`` readers and writers since these image file formats are commonly used for texture content processing pipelines, but are not currently supported by a built-in WIC codec. -This code is designed to build with Visual Studio 2017 ([15.9](https://walbourn.github.io/vs-2017-15-9-update/)), Visual Studio 2019, or clang for Windows v9 or later. It is recommended that you make use of the Windows 10 May 2020 Update SDK ([19041](https://walbourn.github.io/windows-10-may-2020-update-sdk/)). +This code is designed to build with Visual Studio 2017 ([15.9](https://walbourn.github.io/vs-2017-15-9-update/)), Visual Studio 2019, or clang for Windows v9 or later. It is recommended that you make use of the Windows 10 May 2020 Update SDK ([19041](https://walbourn.github.io/windows-10-may-2020-update-sdk/)) or later. These components are designed to work without requiring any content from the legacy DirectX SDK. For details, see [Where is the DirectX SDK?](https://aka.ms/dxsdk). +> This Xbox variant contains DirectXTexXbox modules for tiling/detiling textures offline for use with Xbox One/Xbox One S, Xbox One X, or Xbox Series X|S. Building and running this code requires access to the Xbox One XDK or Microsoft GDK through the ID@Xbox developer program. + ## Directory Layout * ``DirectXTex\`` @@ -67,8 +69,6 @@ All content and source code for this package are subject to the terms of the [MI For the latest version of DirectXTex, bug reports, etc. please visit the project site on [GitHub](https://github.com/microsoft/DirectXTex). -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. - ## Release Notes * Starting with the June 2020 release, this library makes use of typed enum bitmask flags per the recommendation of the _C++ Standard_ section *17.5.2.1.3 Bitmask types*. This is consistent with Direct3D 12's use of the ``DEFINE_ENUM_FLAG_OPERATORS`` macro. This may have *breaking change* impacts to client code: @@ -90,3 +90,15 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope * The UWP projects and the VS 2019 Win10 classic desktop project include configurations for the ARM64 platform. These require VS 2017 (15.9 update) or VS 2019 to build, with the ARM64 toolset installed. * The ``CompileShaders.cmd`` script must have Windows-style (CRLF) line-endings. If it is changed to Linux-style (LF) line-endings, it can fail to build all the required shaders. + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. + +When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +## Trademarks + +This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies. diff --git a/Kits/DirectXTex/Shaders/BC6HEncode.hlsl b/Kits/DirectXTex/Shaders/BC6HEncode.hlsl index cae8f1c8..2fc025a0 100644 --- a/Kits/DirectXTex/Shaders/BC6HEncode.hlsl +++ b/Kits/DirectXTex/Shaders/BC6HEncode.hlsl @@ -3,7 +3,7 @@ // // The Compute Shader for BC6H Encoder // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- diff --git a/Kits/DirectXTex/Shaders/BC7Encode.hlsl b/Kits/DirectXTex/Shaders/BC7Encode.hlsl index 1506ddb2..9552a6f1 100644 --- a/Kits/DirectXTex/Shaders/BC7Encode.hlsl +++ b/Kits/DirectXTex/Shaders/BC7Encode.hlsl @@ -3,7 +3,7 @@ // // The Compute Shader for BC7 Encoder // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- diff --git a/Kits/DirectXTex/Shaders/CompileShaders.cmd b/Kits/DirectXTex/Shaders/CompileShaders.cmd index 48d7c0a2..15a58a3d 100644 --- a/Kits/DirectXTex/Shaders/CompileShaders.cmd +++ b/Kits/DirectXTex/Shaders/CompileShaders.cmd @@ -1,5 +1,5 @@ @echo off -rem Copyright (c) Microsoft Corporation. All rights reserved. +rem Copyright (c) Microsoft Corporation. rem Licensed under the MIT License. setlocal diff --git a/Kits/DirectXTex/filters.h b/Kits/DirectXTex/filters.h index c457c434..2b32039e 100644 --- a/Kits/DirectXTex/filters.h +++ b/Kits/DirectXTex/filters.h @@ -3,7 +3,7 @@ // // Utility header with helpers for implementing image filters // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- diff --git a/Kits/DirectXTex/scoped.h b/Kits/DirectXTex/scoped.h index 9d8832d0..20dd23d6 100644 --- a/Kits/DirectXTex/scoped.h +++ b/Kits/DirectXTex/scoped.h @@ -1,25 +1,76 @@ //------------------------------------------------------------------------------------- // scoped.h -// +// // Utility header with helper classes for exception-safe handling of resources // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------------- #pragma once -#include +#include +#include +#include #include -#include +#ifndef WIN32 +#include + +struct aligned_deleter { void operator()(void* p) noexcept { free(p); } }; + +using ScopedAlignedArrayFloat = std::unique_ptr; + +inline ScopedAlignedArrayFloat make_AlignedArrayFloat(uint64_t count) +{ + uint64_t size = sizeof(float) * count; + size = (size + 15u) & ~0xF; + if (size > static_cast(UINT32_MAX)) + return nullptr; + + auto ptr = aligned_alloc(16, static_cast(size) ); + return ScopedAlignedArrayFloat(static_cast(ptr)); +} + +using ScopedAlignedArrayXMVECTOR = std::unique_ptr; + +inline ScopedAlignedArrayXMVECTOR make_AlignedArrayXMVECTOR(uint64_t count) +{ + uint64_t size = sizeof(DirectX::XMVECTOR) * count; + if (size > static_cast(UINT32_MAX)) + return nullptr; + auto ptr = aligned_alloc(16, static_cast(size)); + return ScopedAlignedArrayXMVECTOR(static_cast(ptr)); +} + +#else // WIN32 //--------------------------------------------------------------------------------- +#include + struct aligned_deleter { void operator()(void* p) noexcept { _aligned_free(p); } }; using ScopedAlignedArrayFloat = std::unique_ptr; +inline ScopedAlignedArrayFloat make_AlignedArrayFloat(uint64_t count) +{ + uint64_t size = sizeof(float) * count; + if (size > static_cast(UINT32_MAX)) + return nullptr; + auto ptr = _aligned_malloc(static_cast(size), 16); + return ScopedAlignedArrayFloat(static_cast(ptr)); +} + using ScopedAlignedArrayXMVECTOR = std::unique_ptr; +inline ScopedAlignedArrayXMVECTOR make_AlignedArrayXMVECTOR(uint64_t count) +{ + uint64_t size = sizeof(DirectX::XMVECTOR) * count; + if (size > static_cast(UINT32_MAX)) + return nullptr; + auto ptr = _aligned_malloc(static_cast(size), 16); + return ScopedAlignedArrayXMVECTOR(static_cast(ptr)); +} + //--------------------------------------------------------------------------------- struct handle_closer { void operator()(HANDLE h) noexcept { assert(h != INVALID_HANDLE_VALUE); if (h) CloseHandle(h); } }; @@ -56,3 +107,5 @@ class auto_delete_file private: HANDLE m_handle; }; + +#endif // WIN32 diff --git a/UWPSamples/System/SystemInfoUWP/SystemInfo.cpp b/UWPSamples/System/SystemInfoUWP/SystemInfo.cpp index 4aa9b80d..6ba87bd7 100644 --- a/UWPSamples/System/SystemInfoUWP/SystemInfo.cpp +++ b/UWPSamples/System/SystemInfoUWP/SystemInfo.cpp @@ -1004,6 +1004,9 @@ void Sample::Render() // Determine highest feature level static const D3D_FEATURE_LEVEL s_featureLevels[] = { +#if defined(NTDDI_WIN10_FE) && (NTDDI_VERSION >= NTDDI_WIN10_FE) + D3D_FEATURE_LEVEL_12_2, +#endif D3D_FEATURE_LEVEL_12_1, D3D_FEATURE_LEVEL_12_0, D3D_FEATURE_LEVEL_11_1, @@ -1027,6 +1030,9 @@ void Sample::Render() case D3D_FEATURE_LEVEL_11_1: featLevel = L"11.1"; break; case D3D_FEATURE_LEVEL_12_0: featLevel = L"12.0"; break; case D3D_FEATURE_LEVEL_12_1: featLevel = L"12.1"; break; +#if defined(NTDDI_WIN10_FE) && (NTDDI_VERSION >= NTDDI_WIN10_FE) + case D3D_FEATURE_LEVEL_12_2: featLevel = L"12.2"; break; +#endif } DrawStringLeft(m_batch.get(), m_smallFont.get(), L"Hardware Feature Level", left, y, m_scale); @@ -1048,7 +1054,9 @@ void Sample::Render() } D3D12_FEATURE_DATA_SHADER_MODEL shaderModel = {}; - #if defined(NTDDI_WIN10_VB) && (NTDDI_VERSION >= NTDDI_WIN10_VB) + #if defined(NTDDI_WIN10_FE) && (NTDDI_VERSION >= NTDDI_WIN10_FE) + shaderModel.HighestShaderModel = D3D_SHADER_MODEL_6_7; + #elif defined(NTDDI_WIN10_VB) && (NTDDI_VERSION >= NTDDI_WIN10_VB) shaderModel.HighestShaderModel = D3D_SHADER_MODEL_6_6; #elif defined(NTDDI_WIN10_19H1) && (NTDDI_VERSION >= NTDDI_WIN10_19H1) shaderModel.HighestShaderModel = D3D_SHADER_MODEL_6_5; @@ -1096,6 +1104,10 @@ void Sample::Render() #if defined(NTDDI_WIN10_VB) && (NTDDI_VERSION >= NTDDI_WIN10_VB) case D3D_SHADER_MODEL_6_6: shaderModelVer = L"6.6"; break; #endif + + #if defined(NTDDI_WIN10_FE) && (NTDDI_VERSION >= NTDDI_WIN10_FE) + case D3D_SHADER_MODEL_6_7: shaderModelVer = L"6.7"; break; + #endif } wchar_t buff[128] = {}; diff --git a/XDKSamples/Tools/xtexconv/DirectXTexEXR.cpp b/XDKSamples/Tools/xtexconv/DirectXTexEXR.cpp index 707b5b65..363f0131 100644 --- a/XDKSamples/Tools/xtexconv/DirectXTexEXR.cpp +++ b/XDKSamples/Tools/xtexconv/DirectXTexEXR.cpp @@ -3,7 +3,7 @@ // // DirectXTex Auxillary functions for using the OpenEXR library // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- @@ -14,26 +14,49 @@ #include -#include +#include #include #include +#include +#include // // Requires the OpenEXR library and ZLIB // +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wswitch-enum" + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec" +#pragma clang diagnostic ignored "-Wfloat-equal" +#pragma clang diagnostic ignored "-Wimplicit-int-conversion" +#pragma clang diagnostic ignored "-Wlanguage-extension-token" +#pragma clang diagnostic ignored "-Wold-style-cast" +#pragma clang diagnostic ignored "-Wreserved-id-macro" +#pragma clang diagnostic ignored "-Wshadow-field-in-constructor" +#pragma clang diagnostic ignored "-Wsign-conversion" +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" +#endif + #pragma warning(push) -#pragma warning(disable : 4244 4996) +#pragma warning(disable : 4244 4996 26439 26495) #include #include #pragma warning(pop) +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + static_assert(sizeof(Imf::Rgba) == 8, "Mismatch size"); using namespace DirectX; using PackedVector::XMHALF4; // Comment out this first anonymous namespace if you add the include of DirectXTexP.h above +#ifdef WIN32 namespace { struct handle_closer { void operator()(HANDLE h) { assert(h != INVALID_HANDLE_VALUE); if (h) CloseHandle(h); } }; @@ -66,7 +89,9 @@ namespace HANDLE m_handle; }; } +#endif +#ifdef WIN32 namespace { class com_exception : public std::exception @@ -74,10 +99,10 @@ namespace public: com_exception(HRESULT hr) : result(hr) {} - const char* what() const override + const char* what() const noexcept override { static char s_str[64] = {}; - sprintf_s(s_str, "Failure with HRESULT of %08X", result); + sprintf_s(s_str, "Failure with HRESULT of %08X", static_cast(result)); return s_str; } @@ -108,8 +133,8 @@ namespace } } - InputStream(const InputStream &) = delete; - InputStream& operator = (const InputStream &) = delete; + InputStream(const InputStream&) = delete; + InputStream& operator = (const InputStream&) = delete; bool read(char c[], int n) override { @@ -137,13 +162,13 @@ namespace { throw com_exception(HRESULT_FROM_WIN32(GetLastError())); } - return result.QuadPart; + return static_cast(result.QuadPart); } void seekg(Imf::Int64 pos) override { LARGE_INTEGER dist; - dist.QuadPart = pos; + dist.QuadPart = static_cast(pos); if (!SetFilePointerEx(m_hFile, dist, nullptr, FILE_BEGIN)) { throw com_exception(HRESULT_FROM_WIN32(GetLastError())); @@ -166,8 +191,8 @@ namespace OutputStream(HANDLE hFile, const char fileName[]) : OStream(fileName), m_hFile(hFile) {} - OutputStream(const OutputStream &) = delete; - OutputStream& operator = (const OutputStream &) = delete; + OutputStream(const OutputStream&) = delete; + OutputStream& operator = (const OutputStream&) = delete; void write(const char c[], int n) override { @@ -186,13 +211,13 @@ namespace { throw com_exception(HRESULT_FROM_WIN32(GetLastError())); } - return result.QuadPart; + return static_cast(result.QuadPart); } void seekp(Imf::Int64 pos) override { LARGE_INTEGER dist; - dist.QuadPart = pos; + dist.QuadPart = static_cast(pos); if (!SetFilePointerEx(m_hFile, dist, nullptr, FILE_BEGIN)) { throw com_exception(HRESULT_FROM_WIN32(GetLastError())); @@ -203,6 +228,7 @@ namespace HANDLE m_hFile; }; } +#endif // WIN32 //===================================================================================== @@ -218,7 +244,8 @@ HRESULT DirectX::GetMetadataFromEXRFile(const wchar_t* szFile, TexMetadata& meta if (!szFile) return E_INVALIDARG; - char fileName[MAX_PATH]; +#ifdef WIN32 + char fileName[MAX_PATH] = {}; const int result = WideCharToMultiByte(CP_UTF8, 0, szFile, -1, fileName, MAX_PATH, nullptr, nullptr); if (result <= 0) { @@ -237,12 +264,20 @@ HRESULT DirectX::GetMetadataFromEXRFile(const wchar_t* szFile, TexMetadata& meta } InputStream stream(hFile.get(), fileName); +#else + std::wstring wFileName(szFile); + std::string fileName(wFileName.cbegin(), wFileName.cend()); +#endif HRESULT hr = S_OK; try { +#ifdef WIN32 Imf::RgbaInputFile file(stream); +#else + Imf::RgbaInputFile file(fileName.c_str()); +#endif const auto dw = file.dataWindow(); @@ -258,6 +293,7 @@ HRESULT DirectX::GetMetadataFromEXRFile(const wchar_t* szFile, TexMetadata& meta metadata.format = DXGI_FORMAT_R16G16B16A16_FLOAT; metadata.dimension = TEX_DIMENSION_TEXTURE2D; } +#ifdef WIN32 catch (const com_exception& exc) { #ifdef _DEBUG @@ -265,7 +301,8 @@ HRESULT DirectX::GetMetadataFromEXRFile(const wchar_t* szFile, TexMetadata& meta #endif hr = exc.hr(); } -#ifdef _DEBUG +#endif +#if defined(WIN32) && defined(_DEBUG) catch (const std::exception& exc) { OutputDebugStringA(exc.what()); @@ -302,7 +339,8 @@ HRESULT DirectX::LoadFromEXRFile(const wchar_t* szFile, TexMetadata* metadata, S memset(metadata, 0, sizeof(TexMetadata)); } - char fileName[MAX_PATH]; +#ifdef WIN32 + char fileName[MAX_PATH] = {}; const int result = WideCharToMultiByte(CP_UTF8, 0, szFile, -1, fileName, MAX_PATH, nullptr, nullptr); if (result <= 0) { @@ -321,12 +359,20 @@ HRESULT DirectX::LoadFromEXRFile(const wchar_t* szFile, TexMetadata* metadata, S } InputStream stream(hFile.get(), fileName); +#else + std::wstring wFileName(szFile); + std::string fileName(wFileName.cbegin(), wFileName.cend()); +#endif HRESULT hr = S_OK; try { +#ifdef WIN32 Imf::RgbaInputFile file(stream); +#else + Imf::RgbaInputFile file(fileName.c_str()); +#endif auto dw = file.dataWindow(); @@ -345,13 +391,15 @@ HRESULT DirectX::LoadFromEXRFile(const wchar_t* szFile, TexMetadata* metadata, S metadata->dimension = TEX_DIMENSION_TEXTURE2D; } - hr = image.Initialize2D(DXGI_FORMAT_R16G16B16A16_FLOAT, width, height, 1, 1); + hr = image.Initialize2D(DXGI_FORMAT_R16G16B16A16_FLOAT, + static_cast(width), static_cast(height), 1u, 1u); if (FAILED(hr)) return hr; - file.setFrameBuffer(reinterpret_cast(image.GetPixels()) - dw.min.x - dw.min.y * width, 1, width); + file.setFrameBuffer(reinterpret_cast(image.GetPixels()) - dw.min.x - dw.min.y * width, 1, static_cast(width)); file.readPixels(dw.min.y, dw.max.y); } +#ifdef WIN32 catch (const com_exception& exc) { #ifdef _DEBUG @@ -359,7 +407,8 @@ HRESULT DirectX::LoadFromEXRFile(const wchar_t* szFile, TexMetadata* metadata, S #endif hr = exc.hr(); } -#ifdef _DEBUG +#endif +#if defined(WIN32) && defined(_DEBUG) catch (const std::exception& exc) { OutputDebugStringA(exc.what()); @@ -398,7 +447,7 @@ HRESULT DirectX::SaveToEXRFile(const Image& image, const wchar_t* szFile) return E_POINTER; if (image.width > INT32_MAX || image.height > INT32_MAX) - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return /* HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) */ static_cast(0x80070032L); switch (image.format) { @@ -412,10 +461,11 @@ HRESULT DirectX::SaveToEXRFile(const Image& image, const wchar_t* szFile) break; default: - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); + return /* HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) */ static_cast(0x80070032L); } - char fileName[MAX_PATH]; +#ifdef WIN32 + char fileName[MAX_PATH] = {}; const int result = WideCharToMultiByte(CP_UTF8, 0, szFile, -1, fileName, MAX_PATH, nullptr, nullptr); if (result <= 0) { @@ -425,7 +475,7 @@ HRESULT DirectX::SaveToEXRFile(const Image& image, const wchar_t* szFile) #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr))); #else - ScopedHandle hFile(safe_handle(CreateFileW(szFile, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr))); + ScopedHandle hFile(safe_handle(CreateFileW(szFile, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr))); #endif if (!hFile) { @@ -435,6 +485,10 @@ HRESULT DirectX::SaveToEXRFile(const Image& image, const wchar_t* szFile) auto_delete_file delonfail(hFile.get()); OutputStream stream(hFile.get(), fileName); +#else + std::wstring wFileName(szFile); + std::string fileName(wFileName.cbegin(), wFileName.cend()); +#endif HRESULT hr = S_OK; @@ -443,7 +497,11 @@ HRESULT DirectX::SaveToEXRFile(const Image& image, const wchar_t* szFile) const int width = static_cast(image.width); const int height = static_cast(image.height); +#ifdef WIN32 Imf::RgbaOutputFile file(stream, Imf::Header(width, height), Imf::WRITE_RGBA); +#else + Imf::RgbaOutputFile file(fileName.c_str(), Imf::Header(width, height), Imf::WRITE_RGBA); +#endif if (image.format == DXGI_FORMAT_R16G16B16A16_FLOAT) { @@ -452,11 +510,18 @@ HRESULT DirectX::SaveToEXRFile(const Image& image, const wchar_t* szFile) } else { - std::unique_ptr temp(new (std::nothrow) XMHALF4[width * height]); + uint64_t bytes = image.width * image.height; + + if (bytes > UINT32_MAX) + { + return /* HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW) */ static_cast(0x80070216L); + } + + std::unique_ptr temp(new (std::nothrow) XMHALF4[static_cast(bytes)]); if (!temp) return E_OUTOFMEMORY; - file.setFrameBuffer(reinterpret_cast(temp.get()), 1, width); + file.setFrameBuffer(reinterpret_cast(temp.get()), 1, image.width); auto sPtr = image.pixels; auto dPtr = temp.get(); @@ -501,6 +566,7 @@ HRESULT DirectX::SaveToEXRFile(const Image& image, const wchar_t* szFile) } } } +#ifdef WIN32 catch (const com_exception& exc) { #ifdef _DEBUG @@ -508,7 +574,8 @@ HRESULT DirectX::SaveToEXRFile(const Image& image, const wchar_t* szFile) #endif hr = exc.hr(); } -#ifdef _DEBUG +#endif +#if defined(WIN32) && defined(_DEBUG) catch (const std::exception& exc) { OutputDebugStringA(exc.what()); @@ -528,7 +595,9 @@ HRESULT DirectX::SaveToEXRFile(const Image& image, const wchar_t* szFile) if (FAILED(hr)) return hr; +#ifdef WIN32 delonfail.clear(); +#endif return S_OK; } diff --git a/XDKSamples/Tools/xtexconv/DirectXTexEXR.h b/XDKSamples/Tools/xtexconv/DirectXTexEXR.h index b64eccc0..39cee9b1 100644 --- a/XDKSamples/Tools/xtexconv/DirectXTexEXR.h +++ b/XDKSamples/Tools/xtexconv/DirectXTexEXR.h @@ -3,7 +3,7 @@ // // DirectXTex Auxillary functions for using the OpenEXR library // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //-------------------------------------------------------------------------------------- diff --git a/XDKSamples/Tools/xtexconv/ExtendedBMP.cpp b/XDKSamples/Tools/xtexconv/ExtendedBMP.cpp index 0b5e7dcf..f9c687b8 100644 --- a/XDKSamples/Tools/xtexconv/ExtendedBMP.cpp +++ b/XDKSamples/Tools/xtexconv/ExtendedBMP.cpp @@ -6,7 +6,7 @@ // // http://www.mwgfx.co.uk/programs/dxtbmp.htm // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -24,8 +24,10 @@ #include +#include #include #include +#include #include "DirectXTex.h" diff --git a/XDKSamples/Tools/xtexconv/PortablePixMap.cpp b/XDKSamples/Tools/xtexconv/PortablePixMap.cpp index 17795194..847523bb 100644 --- a/XDKSamples/Tools/xtexconv/PortablePixMap.cpp +++ b/XDKSamples/Tools/xtexconv/PortablePixMap.cpp @@ -3,7 +3,7 @@ // // Utilities for reading & writing Portable PixMap files (PPM/PFM) // -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248926 @@ -21,8 +21,10 @@ #include +#include #include #include +#include #include "DirectXTex.h" @@ -377,9 +379,11 @@ HRESULT __cdecl SaveToPortablePixMap( } #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) - ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr))); + ScopedHandle hFile(safe_handle(CreateFile2(szFile, + GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr))); #else - ScopedHandle hFile(safe_handle(CreateFileW(szFile, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr))); + ScopedHandle hFile(safe_handle(CreateFileW(szFile, + GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr))); #endif if (!hFile) return HRESULT_FROM_WIN32(GetLastError()); @@ -658,9 +662,11 @@ HRESULT __cdecl SaveToPortablePixMapHDR( tmpImage.Release(); #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) - ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr))); + ScopedHandle hFile(safe_handle(CreateFile2(szFile, + GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr))); #else - ScopedHandle hFile(safe_handle(CreateFileW(szFile, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr))); + ScopedHandle hFile(safe_handle(CreateFileW(szFile, + GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr))); #endif if (!hFile) return HRESULT_FROM_WIN32(GetLastError()); diff --git a/XDKSamples/Tools/xtexconv/texconv.cpp b/XDKSamples/Tools/xtexconv/texconv.cpp index 43b74e09..6433b3f2 100644 --- a/XDKSamples/Tools/xtexconv/texconv.cpp +++ b/XDKSamples/Tools/xtexconv/texconv.cpp @@ -20,13 +20,23 @@ #define NOHELP #pragma warning(pop) -#include -#include -#include - +#include + +#include +#include +#include +#include +#include +#include +#include #include -#include +#include #include +#include +#include +#include +#include +#include #include @@ -60,7 +70,7 @@ using Microsoft::WRL::ComPtr; namespace { - enum OPTIONS + enum OPTIONS : uint64_t { OPT_RECURSIVE = 1, OPT_FILELIST, @@ -118,6 +128,7 @@ namespace OPT_ROTATE_COLOR, OPT_PAPER_WHITE_NITS, OPT_BCNONMULT4FIX, + OPT_SWIZZLE, OPT_USE_XBOX, OPT_XGMODE, OPT_MAX @@ -131,23 +142,26 @@ namespace ROTATE_2020_TO_709, ROTATE_P3_TO_HDR10, ROTATE_P3_TO_2020, + ROTATE_709_TO_DISPLAY_P3, + ROTATE_DISPLAY_P3_TO_709, }; - static_assert(OPT_MAX <= 64, "dwOptions is a DWORD64 bitfield"); + static_assert(OPT_MAX <= 64, "dwOptions is a unsigned int bitfield"); struct SConversion { wchar_t szSrc[MAX_PATH]; - wchar_t szDest[MAX_PATH]; + wchar_t szFolder[MAX_PATH]; }; + template struct SValue { - LPCWSTR pName; - DWORD dwValue; + const wchar_t* name; + T value; }; - const SValue g_pOptions[] = + const SValue g_pOptions[] = { { L"r", OPT_RECURSIVE }, { L"flist", OPT_FILELIST }, @@ -205,6 +219,7 @@ namespace { L"rotatecolor", OPT_ROTATE_COLOR }, { L"nits", OPT_PAPER_WHITE_NITS }, { L"fixbc4x4", OPT_BCNONMULT4FIX }, + { L"swizzle", OPT_SWIZZLE }, { L"xbox", OPT_USE_XBOX }, { L"xgmode", OPT_XGMODE }, { nullptr, 0 } @@ -212,7 +227,7 @@ namespace #define DEFFMT(fmt) { L## #fmt, DXGI_FORMAT_ ## fmt } - const SValue g_pFormats[] = + const SValue g_pFormats[] = { // List does not include _TYPELESS or depth/stencil formats DEFFMT(R32G32B32A32_FLOAT), @@ -305,7 +320,7 @@ namespace { nullptr, DXGI_FORMAT_UNKNOWN } }; - const SValue g_pFormatAliases[] = + const SValue g_pFormatAliases[] = { { L"DXT1", DXGI_FORMAT_BC1_UNORM }, { L"DXT2", DXGI_FORMAT_BC2_UNORM }, @@ -315,6 +330,7 @@ namespace { L"RGBA", DXGI_FORMAT_R8G8B8A8_UNORM }, { L"BGRA", DXGI_FORMAT_B8G8R8A8_UNORM }, + { L"BGR", DXGI_FORMAT_B8G8R8X8_UNORM }, { L"FP16", DXGI_FORMAT_R16G16B16A16_FLOAT }, { L"FP32", DXGI_FORMAT_R32G32B32A32_FLOAT }, @@ -325,7 +341,7 @@ namespace { nullptr, DXGI_FORMAT_UNKNOWN } }; - const SValue g_pReadOnlyFormats[] = + const SValue g_pReadOnlyFormats[] = { DEFFMT(R32G32B32A32_TYPELESS), DEFFMT(R32G32B32_TYPELESS), @@ -379,7 +395,7 @@ namespace { nullptr, DXGI_FORMAT_UNKNOWN } }; - const SValue g_pFilters[] = + const SValue g_pFilters[] = { { L"POINT", TEX_FILTER_POINT }, { L"LINEAR", TEX_FILTER_LINEAR }, @@ -402,7 +418,7 @@ namespace { nullptr, TEX_FILTER_DEFAULT } }; - const SValue g_pRotateColor[] = + const SValue g_pRotateColor[] = { { L"709to2020", ROTATE_709_TO_2020 }, { L"2020to709", ROTATE_2020_TO_709 }, @@ -410,6 +426,8 @@ namespace { L"HDR10to709", ROTATE_HDR10_TO_709 }, { L"P3to2020", ROTATE_P3_TO_2020 }, { L"P3toHDR10", ROTATE_P3_TO_HDR10 }, + { L"709toDisplayP3", ROTATE_709_TO_DISPLAY_P3 }, + { L"DisplayP3to709", ROTATE_DISPLAY_P3_TO_709 }, { nullptr, 0 }, }; @@ -425,7 +443,7 @@ namespace #define CODEC_EXR 0xFFFF0008 #endif - const SValue g_pSaveFileTypes[] = // valid formats to write to + const SValue g_pSaveFileTypes[] = // valid formats to write to { { L"BMP", WIC_CODEC_BMP }, { L"JPG", WIC_CODEC_JPEG }, @@ -447,7 +465,7 @@ namespace { nullptr, CODEC_DDS } }; - const SValue g_pFeatureLevels[] = // valid feature levels for -fl for maximimum size + const SValue g_pFeatureLevels[] = // valid feature levels for -fl for maximimum size { { L"9.1", 2048 }, { L"9.2", 2048 }, @@ -513,12 +531,13 @@ namespace #pragma prefast(disable : 26018, "Only used with static internal arrays") #endif - DWORD LookupByName(const wchar_t *pName, const SValue *pArray) + template + T LookupByName(const wchar_t *pName, const SValue *pArray) { - while (pArray->pName) + while (pArray->name) { - if (!_wcsicmp(pName, pArray->pName)) - return pArray->dwValue; + if (!_wcsicmp(pName, pArray->name)) + return pArray->value; pArray++; } @@ -526,12 +545,13 @@ namespace return 0; } - const wchar_t* LookupByValue(DWORD pValue, const SValue *pArray) + template + const wchar_t* LookupByValue(T value, const SValue *pArray) { - while (pArray->pName) + while (pArray->name) { - if (pValue == pArray->dwValue) - return pArray->pName; + if (value == pArray->value) + return pArray->name; pArray++; } @@ -539,7 +559,7 @@ namespace return L""; } - void SearchForFiles(const wchar_t* path, std::list& files, bool recursive) + void SearchForFiles(const wchar_t* path, std::list& files, bool recursive, const wchar_t* folder) { // Process files WIN32_FIND_DATAW findData = {}; @@ -557,8 +577,12 @@ namespace wchar_t dir[_MAX_DIR] = {}; _wsplitpath_s(path, drive, _MAX_DRIVE, dir, _MAX_DIR, nullptr, 0, nullptr, 0); - SConversion conv; + SConversion conv = {}; _wmakepath_s(conv.szSrc, drive, dir, findData.cFileName, nullptr); + if (folder) + { + wcscpy_s(conv.szFolder, folder); + } files.push_back(conv); } @@ -592,7 +616,9 @@ namespace if (findData.cFileName[0] != L'.') { wchar_t subdir[MAX_PATH] = {}; - + auto subfolder = (folder) + ? (std::wstring(folder) + std::wstring(findData.cFileName) + L"\\") + : (std::wstring(findData.cFileName) + L"\\"); { wchar_t drive[_MAX_DRIVE] = {}; wchar_t dir[_MAX_DIR] = {}; @@ -603,7 +629,7 @@ namespace _wmakepath_s(subdir, drive, dir, fname, ext); } - SearchForFiles(subdir, files, recursive); + SearchForFiles(subdir, files, recursive, subfolder.c_str()); } } @@ -613,22 +639,106 @@ namespace } } + void ProcessFileList(std::wifstream& inFile, std::list& files) + { + std::list flist; + std::set excludes; + wchar_t fname[1024] = {}; + for (;;) + { + inFile >> fname; + if (!inFile) + break; + + if (*fname == L'#') + { + // Comment + } + else if (*fname == L'-') + { + if (flist.empty()) + { + wprintf(L"WARNING: Ignoring the line '%ls' in -flist\n", fname); + } + else + { + if (wcspbrk(fname, L"?*") != nullptr) + { + std::list removeFiles; + SearchForFiles(&fname[1], removeFiles, false, nullptr); + + for (auto it : removeFiles) + { + _wcslwr_s(it.szSrc); + excludes.insert(it.szSrc); + } + } + else + { + std::wstring name = (fname + 1); + std::transform(name.begin(), name.end(), name.begin(), towlower); + excludes.insert(name); + } + } + } + else if (wcspbrk(fname, L"?*") != nullptr) + { + SearchForFiles(fname, flist, false, nullptr); + } + else + { + SConversion conv = {}; + wcscpy_s(conv.szSrc, MAX_PATH, fname); + flist.push_back(conv); + } + + inFile.ignore(1000, '\n'); + } + + inFile.close(); + + if (!excludes.empty()) + { + // Remove any excluded files + for (auto it = flist.begin(); it != flist.end();) + { + std::wstring name = it->szSrc; + std::transform(name.begin(), name.end(), name.begin(), towlower); + auto item = it; + ++it; + if (excludes.find(name) != excludes.end()) + { + flist.erase(item); + } + } + } + + if (flist.empty()) + { + wprintf(L"WARNING: No file names found in -flist\n"); + } + else + { + files.splice(files.end(), flist); + } + } + void PrintFormat(DXGI_FORMAT Format) { - for (const SValue *pFormat = g_pFormats; pFormat->pName; pFormat++) + for (auto pFormat = g_pFormats; pFormat->name; pFormat++) { - if (static_cast(pFormat->dwValue) == Format) + if (static_cast(pFormat->value) == Format) { - wprintf(L"%ls", pFormat->pName); + wprintf(L"%ls", pFormat->name); return; } } - for (const SValue *pFormat = g_pReadOnlyFormats; pFormat->pName; pFormat++) + for (auto pFormat = g_pReadOnlyFormats; pFormat->name; pFormat++) { - if (static_cast(pFormat->dwValue) == Format) + if (static_cast(pFormat->value) == Format) { - wprintf(L"%ls", pFormat->pName); + wprintf(L"%ls", pFormat->name); return; } } @@ -700,11 +810,11 @@ namespace wprintf(L")"); } - void PrintList(size_t cch, const SValue *pValue) + void PrintList(size_t cch, const SValue *pValue) { - while (pValue->pName) + while (pValue->name) { - size_t cchName = wcslen(pValue->pName); + size_t cchName = wcslen(pValue->name); if (cch + cchName + 2 >= 80) { @@ -712,7 +822,7 @@ namespace cch = 6; } - wprintf(L"%ls ", pValue->pName); + wprintf(L"%ls ", pValue->name); cch += cchName + 2; pValue++; } @@ -762,6 +872,8 @@ namespace wprintf(L"Usage: texconv \n\n"); wprintf(L" -r wildcard filename search is recursive\n"); + wprintf(L" -r:flatten flatten the directory structure (default)\n"); + wprintf(L" -r:keep keep the directory structure\n"); wprintf(L" -flist use text file with a list of input files (one per line)\n"); wprintf(L"\n -w width\n"); wprintf(L" -h height\n"); @@ -832,6 +944,7 @@ namespace wprintf(L" -x2bias Enable *2 - 1 conversion cases for unorm/pos-only-float\n"); wprintf(L" -inverty Invert Y (i.e. green) channel values\n"); wprintf(L" -reconstructz Rebuild Z (blue) channel assuming X/Y are normals\n"); + wprintf(L" -swizzle Swizzle image channels using HLSL-style mask\n"); wprintf(L"\n : "); PrintList(13, g_pFormats); @@ -869,6 +982,36 @@ namespace } } + const wchar_t* GetErrorDesc(HRESULT hr) + { + static wchar_t desc[1024] = {}; + + LPWSTR errorText = nullptr; + + DWORD result = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER, + nullptr, static_cast(hr), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast(&errorText), 0, nullptr); + + *desc = 0; + + if (result > 0 && errorText) + { + swprintf_s(desc, L": %ls", errorText); + + size_t len = wcslen(desc); + if (len >= 2) + { + desc[len - 2] = 0; + desc[len - 1] = 0; + } + + if (errorText) + LocalFree(errorText); + } + + return desc; + } + _Success_(return != false) bool CreateDevice(int adapter, _Outptr_ ID3D11Device** pDevice) { @@ -919,7 +1062,7 @@ namespace D3D_FEATURE_LEVEL fl; HRESULT hr = s_DynamicD3D11CreateDevice(pAdapter.Get(), (pAdapter) ? D3D_DRIVER_TYPE_UNKNOWN : D3D_DRIVER_TYPE_HARDWARE, - nullptr, createDeviceFlags, featureLevels, _countof(featureLevels), + nullptr, createDeviceFlags, featureLevels, static_cast(std::size(featureLevels)), D3D11_SDK_VERSION, pDevice, &fl, nullptr); if (SUCCEEDED(hr)) { @@ -1006,30 +1149,87 @@ namespace } } + size_t CountMips(_In_ size_t width, _In_ size_t height) noexcept + { + size_t mipLevels = 1; + + while (height > 1 || width > 1) + { + if (height > 1) + height >>= 1; + + if (width > 1) + width >>= 1; + + ++mipLevels; + } + + return mipLevels; + } + + size_t CountMips3D(_In_ size_t width, _In_ size_t height, _In_ size_t depth) noexcept + { + size_t mipLevels = 1; + + while (height > 1 || width > 1 || depth > 1) + { + if (height > 1) + height >>= 1; + + if (width > 1) + width >>= 1; + + if (depth > 1) + depth >>= 1; + + ++mipLevels; + } + + return mipLevels; + } + const XMVECTORF32 c_MaxNitsFor2084 = { { { 10000.0f, 10000.0f, 10000.0f, 1.f } } }; const XMMATRIX c_from709to2020 = { - XMVECTOR { 0.6274040f, 0.0690970f, 0.0163916f, 0.f }, - XMVECTOR { 0.3292820f, 0.9195400f, 0.0880132f, 0.f }, - XMVECTOR { 0.0433136f, 0.0113612f, 0.8955950f, 0.f }, - XMVECTOR { 0.f, 0.f, 0.f, 1.f } + 0.6274040f, 0.0690970f, 0.0163916f, 0.f, + 0.3292820f, 0.9195400f, 0.0880132f, 0.f, + 0.0433136f, 0.0113612f, 0.8955950f, 0.f, + 0.f, 0.f, 0.f, 1.f }; const XMMATRIX c_from2020to709 = { - XMVECTOR { 1.6604910f, -0.1245505f, -0.0181508f, 0.f }, - XMVECTOR { -0.5876411f, 1.1328999f, -0.1005789f, 0.f }, - XMVECTOR { -0.0728499f, -0.0083494f, 1.1187297f, 0.f }, - XMVECTOR { 0.f, 0.f, 0.f, 1.f } + 1.6604910f, -0.1245505f, -0.0181508f, 0.f, + -0.5876411f, 1.1328999f, -0.1005789f, 0.f, + -0.0728499f, -0.0083494f, 1.1187297f, 0.f, + 0.f, 0.f, 0.f, 1.f }; + // DCI-P3 https://en.wikipedia.org/wiki/DCI-P3 const XMMATRIX c_fromP3to2020 = { - XMVECTOR { 0.753845f, 0.0457456f, -0.00121055f, 0.f }, - XMVECTOR { 0.198593f, 0.941777f, 0.0176041f, 0.f }, - XMVECTOR { 0.047562f, 0.0124772f, 0.983607f, 0.f }, - XMVECTOR { 0.f, 0.f, 0.f, 1.f } + 0.753845f, 0.0457456f, -0.00121055f, 0.f, + 0.198593f, 0.941777f, 0.0176041f, 0.f, + 0.047562f, 0.0124772f, 0.983607f, 0.f, + 0.f, 0.f, 0.f, 1.f + }; + + // Display P3 (P3D65) + const XMMATRIX c_from709toDisplayP3 = + { + 0.822461969f, 0.033194199f, 0.017082631f, 0.f, + 0.1775380f, 0.9668058f, 0.0723974f, 0.f, + 0.0000000f, 0.0000000f, 0.9105199f, 0.f, + 0.f, 0.f, 0.f, 1.f + }; + + const XMMATRIX c_fromDisplayP3to709 = + { + 1.224940176f, -0.042056955f, -0.019637555f, 0.f, + -0.224940176f, 1.042056955f, -0.078636046f, 0.f, + 0.0000000f, 0.0000000f, 1.098273600f, 0.f, + 0.f, 0.f, 0.f, 1.f }; inline float LinearToST2084(float normalizedLinearValue) @@ -1043,6 +1243,99 @@ namespace float normalizedLinear = pow(std::max(pow(abs(ST2084), 1.0f / 78.84375f) - 0.8359375f, 0.0f) / (18.8515625f - 18.6875f * pow(abs(ST2084), 1.0f / 78.84375f)), 1.0f / 0.1593017578f); return normalizedLinear; } + + bool ParseSwizzleMask( + _In_reads_(4) const wchar_t* mask, + _Out_writes_(4) uint32_t* swizzleElements, + _Out_writes_(4) uint32_t* zeroElements, + _Out_writes_(4) uint32_t* oneElements) + { + if (!mask || !swizzleElements || !zeroElements || !oneElements) + return false; + + if (!mask[0]) + return false; + + for (uint32_t j = 0; j < 4; ++j) + { + if (!mask[j]) + break; + + switch (mask[j]) + { + case L'R': + case L'X': + case L'r': + case L'x': + for (uint32_t k = j; k < 4; ++k) + { + swizzleElements[k] = 0; + zeroElements[k] = 0; + oneElements[k] = 0; + } + break; + + case L'G': + case L'Y': + case L'g': + case L'y': + for (uint32_t k = j; k < 4; ++k) + { + swizzleElements[k] = 1; + zeroElements[k] = 0; + oneElements[k] = 0; + } + break; + + case L'B': + case L'Z': + case L'b': + case L'z': + for (uint32_t k = j; k < 4; ++k) + { + swizzleElements[k] = 2; + zeroElements[k] = 0; + oneElements[k] = 0; + } + break; + + case L'A': + case L'W': + case L'a': + case L'w': + for (size_t k = j; k < 4; ++k) + { + swizzleElements[k] = 3; + zeroElements[k] = 0; + oneElements[k] = 0; + } + break; + + case L'0': + for (uint32_t k = j; k < 4; ++k) + { + swizzleElements[k] = k; + zeroElements[k] = 1; + oneElements[k] = 0; + } + break; + + case L'1': + for (uint32_t k = j; k < 4; ++k) + { + swizzleElements[k] = k; + zeroElements[k] = 0; + oneElements[k] = 1; + } + break; + + default: + return false; + } + } + + return true; + } } //-------------------------------------------------------------------------------------- @@ -1064,33 +1357,40 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) TEX_FILTER_FLAGS dwConvert = TEX_FILTER_DEFAULT; TEX_COMPRESS_FLAGS dwCompress = TEX_COMPRESS_DEFAULT; TEX_FILTER_FLAGS dwFilterOpts = TEX_FILTER_DEFAULT; - DWORD FileType = CODEC_DDS; - DWORD maxSize = 16384; + uint32_t FileType = CODEC_DDS; + uint32_t maxSize = 16384; int adapter = -1; float alphaThreshold = TEX_THRESHOLD_DEFAULT; float alphaWeight = 1.f; CNMAP_FLAGS dwNormalMap = CNMAP_DEFAULT; float nmapAmplitude = 1.f; float wicQuality = -1.f; - DWORD colorKey = 0; - DWORD dwRotateColor = 0; + uint32_t colorKey = 0; + uint32_t dwRotateColor = 0; float paperWhiteNits = 200.f; float preserveAlphaCoverageRef = 0.0f; + bool keepRecursiveDirs = false; + uint32_t swizzleElements[4] = { 0, 1, 2, 3 }; + uint32_t zeroElements[4] = {}; + uint32_t oneElements[4] = {}; wchar_t szPrefix[MAX_PATH] = {}; wchar_t szSuffix[MAX_PATH] = {}; wchar_t szOutputDir[MAX_PATH] = {}; + // Set locale for output since GetErrorDesc can get localized strings. + std::locale::global(std::locale("")); + // Initialize COM (needed for WIC) HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); if (FAILED(hr)) { - wprintf(L"Failed to initialize COM (%08X)\n", static_cast(hr)); + wprintf(L"Failed to initialize COM (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } // Process command line - DWORD64 dwOptions = 0; + uint64_t dwOptions = 0; std::list conversion; for (int iArg = 1; iArg < argc; iArg++) @@ -1107,15 +1407,15 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) if (*pValue) *pValue++ = 0; - DWORD dwOption = LookupByName(pArg, g_pOptions); + uint64_t dwOption = LookupByName(pArg, g_pOptions); - if (!dwOption || (dwOptions & (DWORD64(1) << dwOption))) + if (!dwOption || (dwOptions & (uint64_t(1) << dwOption))) { PrintUsage(); return 1; } - dwOptions |= (DWORD64(1) << dwOption); + dwOptions |= (uint64_t(1) << dwOption); // Handle options with additional value parameter switch (dwOption) @@ -1142,7 +1442,9 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) case OPT_ROTATE_COLOR: case OPT_PAPER_WHITE_NITS: case OPT_PRESERVE_ALPHA_COVERAGE: + case OPT_SWIZZLE: case OPT_XGMODE: + // These support either "-arg:value" or "-arg value" if (!*pValue) { if ((iArg + 1 >= argc)) @@ -1270,7 +1572,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) break; case OPT_PREMUL_ALPHA: - if (dwOptions & (DWORD64(1) << OPT_DEMUL_ALPHA)) + if (dwOptions & (uint64_t(1) << OPT_DEMUL_ALPHA)) { wprintf(L"Can't use -pmalpha and -alpha at same time\n\n"); PrintUsage(); @@ -1279,7 +1581,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) break; case OPT_DEMUL_ALPHA: - if (dwOptions & (DWORD64(1) << OPT_PREMUL_ALPHA)) + if (dwOptions & (uint64_t(1) << OPT_PREMUL_ALPHA)) { wprintf(L"Can't use -pmalpha and -alpha at same time\n\n"); PrintUsage(); @@ -1334,7 +1636,6 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) else { wprintf(L"Invalid value specified for -nmap (%ls), missing l, r, g, b, or a\n\n", pValue); - PrintUsage(); return 1; } @@ -1382,7 +1683,6 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) else if (nmapAmplitude < 0.f) { wprintf(L"Normal map amplitude must be positive (%ls)\n\n", pValue); - PrintUsage(); return 1; } break; @@ -1396,7 +1696,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } else if (adapter < 0) { - wprintf(L"Adapter index (%ls)\n\n", pValue); + wprintf(L"Invalid adapter index (%ls)\n\n", pValue); PrintUsage(); return 1; } @@ -1484,7 +1784,6 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) if (!found) { wprintf(L"Invalid value specified for -bc (%ls), missing d, u, q, or x\n\n", pValue); - PrintUsage(); return 1; } } @@ -1503,7 +1802,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) break; case OPT_COLORKEY: - if (swscanf_s(pValue, L"%lx", &colorKey) != 1) + if (swscanf_s(pValue, L"%x", &colorKey) != 1) { printf("Invalid value specified with -c (%ls)\n", pValue); printf("\n"); @@ -1518,7 +1817,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) break; case OPT_USE_DX10: - if (dwOptions & (DWORD64(1) << OPT_USE_DX9)) + if (dwOptions & (uint64_t(1) << OPT_USE_DX9)) { wprintf(L"Can't use -dx9 and -dx10 at same time\n\n"); PrintUsage(); @@ -1527,7 +1826,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) break; case OPT_USE_DX9: - if (dwOptions & (DWORD64(1) << OPT_USE_DX10)) + if (dwOptions & (uint64_t(1) << OPT_USE_DX10)) { wprintf(L"Can't use -dx9 and -dx10 at same time\n\n"); PrintUsage(); @@ -1535,6 +1834,23 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } break; + case OPT_RECURSIVE: + if (*pValue) + { + // This option takes 'flatten' or 'keep' with ':' syntax + if (!_wcsicmp(pValue, L"keep")) + { + keepRecursiveDirs = true; + } + else if (_wcsicmp(pValue, L"flatten") != 0) + { + wprintf(L"For recursive use -r, -r:flatten, or -r:keep\n\n"); + PrintUsage(); + return 1; + } + } + break; + case OPT_FILELIST: { std::wifstream inFile(pValue); @@ -1543,37 +1859,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) wprintf(L"Error opening -flist file %ls\n", pValue); return 1; } - wchar_t fname[1024] = {}; - for (;;) - { - inFile >> fname; - if (!inFile) - break; - - if (*fname == L'#') - { - // Comment - } - else if (*fname == L'-') - { - wprintf(L"Command-line arguments not supported in -flist file\n"); - return 1; - } - else if (wcspbrk(fname, L"?*") != nullptr) - { - wprintf(L"Wildcards not supported in -flist file\n"); - return 1; - } - else - { - SConversion conv; - wcscpy_s(conv.szSrc, MAX_PATH, fname); - conversion.push_back(conv); - } - inFile.ignore(1000, '\n'); - } - inFile.close(); + ProcessFileList(inFile, conversion); } break; @@ -1605,17 +1892,31 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } break; + case OPT_SWIZZLE: + if (!*pValue || wcslen(pValue) > 4) + { + wprintf(L"Invalid value specified with -swizzle (%ls)\n\n", pValue); + PrintUsage(); + return 1; + } + else if (!ParseSwizzleMask(pValue, swizzleElements, zeroElements, oneElements)) + { + wprintf(L"-swizzle requires a 1 to 4 character mask composed of these letters: r, g, b, a, x, y, w, z, 0, 1\n"); + return 1; + } + break; + case OPT_XGMODE: #if _XDK_VER >= 0x3F6803F3 /* XDK Edition 170600 */ { - static const SValue s_pXGModes[] = + static const SValue s_pXGModes[] = { { L"xboxone", XG_HARDWARE_VERSION_XBOX_ONE }, { L"xboxonex", XG_HARDWARE_VERSION_XBOX_ONE_X }, { nullptr, 0 }, }; - DWORD mode = LookupByName(pValue, s_pXGModes); + uint32_t mode = LookupByName(pValue, s_pXGModes); if (!mode) { printf("Invalid value specified with -xgmode (%ls)\n", pValue); @@ -1635,7 +1936,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) else if (wcspbrk(pArg, L"?*") != nullptr) { size_t count = conversion.size(); - SearchForFiles(pArg, conversion, (dwOptions & (DWORD64(1) << OPT_RECURSIVE)) != 0); + SearchForFiles(pArg, conversion, (dwOptions & (uint64_t(1) << OPT_RECURSIVE)) != 0, nullptr); if (conversion.size() <= count) { wprintf(L"No matching files found for %ls\n", pArg); @@ -1644,11 +1945,9 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } else { - SConversion conv; + SConversion conv = {}; wcscpy_s(conv.szSrc, MAX_PATH, pArg); - conv.szDest[0] = 0; - conversion.push_back(conv); } } @@ -1659,18 +1958,13 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) return 0; } - if (~dwOptions & (DWORD64(1) << OPT_NOLOGO)) + if (~dwOptions & (uint64_t(1) << OPT_NOLOGO)) PrintLogo(); // Work out out filename prefix and suffix if (szOutputDir[0] && (L'\\' != szOutputDir[wcslen(szOutputDir) - 1])) wcscat_s(szOutputDir, MAX_PATH, L"\\"); - if (szPrefix[0]) - wcscat_s(szOutputDir, MAX_PATH, szPrefix); - - wcscpy_s(szPrefix, MAX_PATH, szOutputDir); - auto fileTypeName = LookupByValue(FileType, g_pSaveFileTypes); if (fileTypeName) @@ -1688,17 +1982,11 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) mipLevels = 1; } - LARGE_INTEGER qpcFreq; - if (!QueryPerformanceFrequency(&qpcFreq)) - { - qpcFreq.QuadPart = 0; - } + LARGE_INTEGER qpcFreq = {}; + (void)QueryPerformanceFrequency(&qpcFreq); - LARGE_INTEGER qpcStart; - if (!QueryPerformanceCounter(&qpcStart)) - { - qpcStart.QuadPart = 0; - } + LARGE_INTEGER qpcStart = {}; + (void)QueryPerformanceCounter(&qpcStart); // Convert images bool sizewarn = false; @@ -1707,6 +1995,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) bool preserveAlphaCoverage = false; ComPtr pDevice; + int retVal = 0; + for (auto pConv = conversion.begin(); pConv != conversion.end(); ++pConv) { if (pConv != conversion.begin()) @@ -1735,7 +2025,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = Xbox::GetMetadataFromDDSFile(pConv->szSrc, info, isXbox); if (FAILED(hr)) { - wprintf(L" FAILED (%x)\n", static_cast(hr)); + wprintf(L" FAILED (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } @@ -1752,28 +2043,29 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) else { DDS_FLAGS ddsFlags = DDS_FLAGS_ALLOW_LARGE_FILES; - if (dwOptions & (DWORD64(1) << OPT_DDS_DWORD_ALIGN)) + if (dwOptions & (uint64_t(1) << OPT_DDS_DWORD_ALIGN)) ddsFlags |= DDS_FLAGS_LEGACY_DWORD; - if (dwOptions & (DWORD64(1) << OPT_EXPAND_LUMINANCE)) + if (dwOptions & (uint64_t(1) << OPT_EXPAND_LUMINANCE)) ddsFlags |= DDS_FLAGS_EXPAND_LUMINANCE; - if (dwOptions & (DWORD64(1) << OPT_DDS_BAD_DXTN_TAILS)) + if (dwOptions & (uint64_t(1) << OPT_DDS_BAD_DXTN_TAILS)) ddsFlags |= DDS_FLAGS_BAD_DXTN_TAILS; hr = LoadFromDDSFile(pConv->szSrc, ddsFlags, &info, *image); } if (FAILED(hr)) { - wprintf(L" FAILED (%x)\n", static_cast(hr)); + wprintf(L" FAILED (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } if (IsTypeless(info.format)) { - if (dwOptions & (DWORD64(1) << OPT_TYPELESS_UNORM)) + if (dwOptions & (uint64_t(1) << OPT_TYPELESS_UNORM)) { info.format = MakeTypelessUNORM(info.format); } - else if (dwOptions & (DWORD64(1) << OPT_TYPELESS_FLOAT)) + else if (dwOptions & (uint64_t(1) << OPT_TYPELESS_FLOAT)) { info.format = MakeTypelessFLOAT(info.format); } @@ -1781,6 +2073,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) if (IsTypeless(info.format)) { wprintf(L" FAILED due to Typeless format %d\n", info.format); + retVal = 1; continue; } @@ -1792,7 +2085,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = LoadFromBMPEx(pConv->szSrc, WIC_FLAGS_NONE | dwFilter, &info, *image); if (FAILED(hr)) { - wprintf(L" FAILED (%x)\n", static_cast(hr)); + wprintf(L" FAILED (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } } @@ -1801,7 +2095,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = LoadFromTGAFile(pConv->szSrc, TGA_FLAGS_NONE, &info, *image); if (FAILED(hr)) { - wprintf(L" FAILED (%x)\n", static_cast(hr)); + wprintf(L" FAILED (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } } @@ -1810,7 +2105,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = LoadFromHDRFile(pConv->szSrc, &info, *image); if (FAILED(hr)) { - wprintf(L" FAILED (%x)\n", static_cast(hr)); + wprintf(L" FAILED (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } } @@ -1819,7 +2115,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = LoadFromPortablePixMap(pConv->szSrc, &info, *image); if (FAILED(hr)) { - wprintf(L" FAILED (%x)\n", static_cast(hr)); + wprintf(L" FAILED (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } } @@ -1828,7 +2125,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = LoadFromPortablePixMapHDR(pConv->szSrc, &info, *image); if (FAILED(hr)) { - wprintf(L" FAILED (%x)\n", static_cast(hr)); + wprintf(L" FAILED (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } } @@ -1838,7 +2136,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = LoadFromEXRFile(pConv->szSrc, &info, *image); if (FAILED(hr)) { - wprintf(L" FAILED (%x)\n", static_cast(hr)); + wprintf(L" FAILED (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } } @@ -1860,7 +2159,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = LoadFromWICFile(pConv->szSrc, wicFlags, &info, *image); if (FAILED(hr)) { - wprintf(L" FAILED (%x)\n", static_cast(hr)); + wprintf(L" FAILED (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } } @@ -1890,7 +2190,9 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = ConvertToSinglePlane(img, nimg, info, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [converttosingleplane] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [converttosingleplane] (%08X%ls)\n", + static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } @@ -1918,7 +2220,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) // Direct3D can only create BC resources with multiple-of-4 top levels if ((info.width % 4) != 0 || (info.height % 4) != 0) { - if (dwOptions & (DWORD64(1) << OPT_BCNONMULT4FIX)) + if (dwOptions & (uint64_t(1) << OPT_BCNONMULT4FIX)) { std::unique_ptr timage(new (std::nothrow) ScratchImage); if (!timage) @@ -1941,7 +2243,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = timage->Initialize(mdata); if (FAILED(hr)) { - wprintf(L" FAILED [BC non-multiple-of-4 fixup] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [BC non-multiple-of-4 fixup] (%08X%ls)\n", + static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -1991,7 +2294,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = Decompress(img, nimg, info, DXGI_FORMAT_UNKNOWN /* picks good default */, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [decompress] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [decompress] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } @@ -2020,7 +2324,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } // --- Undo Premultiplied Alpha (if requested) --------------------------------- - if ((dwOptions & (DWORD64(1) << OPT_DEMUL_ALPHA)) + if ((dwOptions & (uint64_t(1) << OPT_DEMUL_ALPHA)) && HasAlpha(info.format) && info.format != DXGI_FORMAT_A8_UNORM) { @@ -2048,7 +2352,9 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = PremultiplyAlpha(img, nimg, info, TEX_PMALPHA_REVERSE | dwSRGB, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [demultiply alpha] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [demultiply alpha] (%08X%ls)\n", + static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } @@ -2069,7 +2375,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } // --- Flip/Rotate ------------------------------------------------------------- - if (dwOptions & ((DWORD64(1) << OPT_HFLIP) | (DWORD64(1) << OPT_VFLIP))) + if (dwOptions & ((uint64_t(1) << OPT_HFLIP) | (uint64_t(1) << OPT_VFLIP))) { std::unique_ptr timage(new (std::nothrow) ScratchImage); if (!timage) @@ -2080,10 +2386,10 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) TEX_FR_FLAGS dwFlags = TEX_FR_ROTATE0; - if (dwOptions & (DWORD64(1) << OPT_HFLIP)) + if (dwOptions & (uint64_t(1) << OPT_HFLIP)) dwFlags |= TEX_FR_FLIP_HORIZONTAL; - if (dwOptions & (DWORD64(1) << OPT_VFLIP)) + if (dwOptions & (uint64_t(1) << OPT_VFLIP)) dwFlags |= TEX_FR_FLIP_VERTICAL; assert(dwFlags != 0); @@ -2091,7 +2397,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = FlipRotate(image->GetImages(), image->GetImageCount(), image->GetMetadata(), dwFlags, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [fliprotate] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [fliprotate] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2130,7 +2436,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) sizewarn = true; } - if (dwOptions & (DWORD64(1) << OPT_FIT_POWEROF2)) + if (dwOptions & (uint64_t(1) << OPT_FIT_POWEROF2)) { FitPowerOf2(info.width, info.height, twidth, theight, maxSize); } @@ -2147,7 +2453,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = Resize(image->GetImages(), image->GetImageCount(), image->GetMetadata(), twidth, theight, dwFilter | dwFilterOpts, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [resize] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [resize] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2166,12 +2472,75 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) image.swap(timage); cimage.reset(); + + if (tMips > 0) + { + size_t maxMips = (info.depth > 1) + ? CountMips3D(info.width, info.height, info.depth) + : CountMips(info.width, info.height); + + if (tMips > maxMips) + { + tMips = maxMips; + } + } + } + + // --- Swizzle (if requested) -------------------------------------------------- + if (swizzleElements[0] != 0 || swizzleElements[1] != 1 || swizzleElements[2] != 2 || swizzleElements[3] != 3 + || zeroElements[0] != 0 || zeroElements[1] != 0 || zeroElements[2] != 0 || zeroElements[3] != 0 + || oneElements[0] != 0 || oneElements[1] != 0 || oneElements[2] != 0 || oneElements[3] != 0) + { + std::unique_ptr timage(new (std::nothrow) ScratchImage); + if (!timage) + { + wprintf(L"\nERROR: Memory allocation failed\n"); + return 1; + } + + XMVECTOR zc = XMVectorSelectControl(zeroElements[0], zeroElements[1], zeroElements[2], zeroElements[3]); + XMVECTOR oc = XMVectorSelectControl(oneElements[0], oneElements[1], oneElements[2], oneElements[3]); + + hr = TransformImage(image->GetImages(), image->GetImageCount(), image->GetMetadata(), + [&, zc, oc](XMVECTOR* outPixels, const XMVECTOR* inPixels, size_t w, size_t y) + { + UNREFERENCED_PARAMETER(y); + + for (size_t j = 0; j < w; ++j) + { + XMVECTOR pixel = XMVectorSelect(inPixels[j], g_XMZero, zc); + pixel = XMVectorSelect(pixel, g_XMOne, oc); + outPixels[j] = XMVectorSwizzle(pixel, + swizzleElements[0], swizzleElements[1], swizzleElements[2], swizzleElements[3]); + } + }, *timage); + if (FAILED(hr)) + { + wprintf(L" FAILED [swizzle] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + return 1; + } + +#ifndef NDEBUG + auto& tinfo = timage->GetMetadata(); +#endif + + assert(info.width == tinfo.width); + assert(info.height == tinfo.height); + assert(info.depth == tinfo.depth); + assert(info.arraySize == tinfo.arraySize); + assert(info.mipLevels == tinfo.mipLevels); + assert(info.miscFlags == tinfo.miscFlags); + assert(info.format == tinfo.format); + assert(info.dimension == tinfo.dimension); + + image.swap(timage); + cimage.reset(); } // --- Color rotation (if requested) ------------------------------------------- if (dwRotateColor) { - if (dwRotateColor == ROTATE_HDR10_TO_709) + if (dwRotateColor == ROTATE_HDR10_TO_709 || dwRotateColor == ROTATE_DISPLAY_P3_TO_709) { std::unique_ptr timage(new (std::nothrow) ScratchImage); if (!timage) @@ -2184,7 +2553,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) dwFilter | dwFilterOpts | dwSRGB | dwConvert, alphaThreshold, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [convert] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [convert] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2372,13 +2741,52 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) }, *timage); break; + case ROTATE_709_TO_DISPLAY_P3: + hr = TransformImage(image->GetImages(), image->GetImageCount(), image->GetMetadata(), + [&](XMVECTOR* outPixels, const XMVECTOR* inPixels, size_t w, size_t y) + { + UNREFERENCED_PARAMETER(y); + + for (size_t j = 0; j < w; ++j) + { + XMVECTOR value = inPixels[j]; + + XMVECTOR nvalue = XMVector3Transform(value, c_from709toDisplayP3); + + value = XMVectorSelect(value, nvalue, g_XMSelect1110); + + outPixels[j] = value; + } + }, *timage); + break; + + case ROTATE_DISPLAY_P3_TO_709: + hr = TransformImage(image->GetImages(), image->GetImageCount(), image->GetMetadata(), + [&](XMVECTOR* outPixels, const XMVECTOR* inPixels, size_t w, size_t y) + { + UNREFERENCED_PARAMETER(y); + + for (size_t j = 0; j < w; ++j) + { + XMVECTOR value = inPixels[j]; + + XMVECTOR nvalue = XMVector3Transform(value, c_fromDisplayP3to709); + + value = XMVectorSelect(value, nvalue, g_XMSelect1110); + + outPixels[j] = value; + } + }, *timage); + break; + default: hr = E_NOTIMPL; break; } if (FAILED(hr)) { - wprintf(L" FAILED [rotate color apply] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [rotate color apply] (%08X%ls)\n", + static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2400,7 +2808,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } // --- Tonemap (if requested) -------------------------------------------------- - if (dwOptions & DWORD64(1) << OPT_TONEMAP) + if (dwOptions & uint64_t(1) << OPT_TONEMAP) { std::unique_ptr timage(new (std::nothrow) ScratchImage); if (!timage) @@ -2429,7 +2837,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) }); if (FAILED(hr)) { - wprintf(L" FAILED [tonemap maxlum] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [tonemap maxlum] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2458,7 +2866,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) }, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [tonemap apply] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [tonemap apply] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2480,7 +2888,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } // --- Convert ----------------------------------------------------------------- - if (dwOptions & (DWORD64(1) << OPT_NORMAL_MAP)) + if (dwOptions & (uint64_t(1) << OPT_NORMAL_MAP)) { std::unique_ptr timage(new (std::nothrow) ScratchImage); if (!timage) @@ -2513,7 +2921,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = ComputeNormalMap(image->GetImages(), image->GetImageCount(), image->GetMetadata(), dwNormalMap, nmapAmplitude, nmfmt, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [normalmap] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [normalmap] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2546,7 +2954,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) dwFilter | dwFilterOpts | dwSRGB | dwConvert, alphaThreshold, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [convert] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [convert] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2568,7 +2976,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } // --- ColorKey/ChromaKey ------------------------------------------------------ - if ((dwOptions & (DWORD64(1) << OPT_COLORKEY)) + if ((dwOptions & (uint64_t(1) << OPT_COLORKEY)) && HasAlpha(info.format)) { std::unique_ptr timage(new (std::nothrow) ScratchImage); @@ -2605,7 +3013,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) }, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [colorkey] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [colorkey] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2627,7 +3035,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } // --- Invert Y Channel -------------------------------------------------------- - if (dwOptions & (DWORD64(1) << OPT_INVERT_Y)) + if (dwOptions & (uint64_t(1) << OPT_INVERT_Y)) { std::unique_ptr timage(new (std::nothrow) ScratchImage); if (!timage) @@ -2654,7 +3062,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) }, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [inverty] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [inverty] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2676,7 +3084,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } // --- Reconstruct Z Channel --------------------------------------------------- - if (dwOptions & (DWORD64(1) << OPT_RECONSTRUCT_Z)) + if (dwOptions & (uint64_t(1) << OPT_RECONSTRUCT_Z)) { std::unique_ptr timage(new (std::nothrow) ScratchImage); if (!timage) @@ -2685,6 +3093,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) return 1; } + bool isunorm = (FormatDataType(info.format) == FORMAT_TYPE_UNORM) != 0; + hr = TransformImage(image->GetImages(), image->GetImageCount(), image->GetMetadata(), [&](XMVECTOR* outPixels, const XMVECTOR* inPixels, size_t w, size_t y) { @@ -2696,14 +3106,24 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) { XMVECTOR value = inPixels[j]; - XMVECTOR z = XMVectorSqrt(XMVectorSubtract(g_XMOne, XMVector2Dot(value, value))); + XMVECTOR z; + if (isunorm) + { + XMVECTOR x2 = XMVectorMultiplyAdd(value, g_XMTwo, g_XMNegativeOne); + x2 = XMVectorSqrt(XMVectorSubtract(g_XMOne, XMVector2Dot(x2, x2))); + z = XMVectorMultiplyAdd(x2, g_XMOneHalf, g_XMOneHalf); + } + else + { + z = XMVectorSqrt(XMVectorSubtract(g_XMOne, XMVector2Dot(value, value))); + } outPixels[j] = XMVectorSelect(value, z, s_selectz); } }, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [reconstructz] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [reconstructz] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2763,7 +3183,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = timage->Initialize(mdata); if (FAILED(hr)) { - wprintf(L" FAILED [copy to single level] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [copy to single level] (%08X%ls)\n", + static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2775,7 +3196,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) *timage->GetImage(0, 0, d), TEX_FILTER_DEFAULT, 0, 0); if (FAILED(hr)) { - wprintf(L" FAILED [copy to single level] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [copy to single level] (%08X%ls)\n", + static_cast(hr), GetErrorDesc(hr)); return 1; } } @@ -2788,14 +3210,14 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) *timage->GetImage(0, i, 0), TEX_FILTER_DEFAULT, 0, 0); if (FAILED(hr)) { - wprintf(L" FAILED [copy to single level] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [copy to single level] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } } } image.swap(timage); - info.mipLevels = image->GetMetadata().mipLevels; + info.mipLevels = 1; if (cimage && (tMips == 1)) { @@ -2805,7 +3227,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = timage->Initialize(mdata); if (FAILED(hr)) { - wprintf(L" FAILED [copy compressed to single level] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [copy compressed to single level] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2857,7 +3279,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } if (FAILED(hr)) { - wprintf(L" FAILED [mipmaps] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [mipmaps] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2889,7 +3311,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = timage->Initialize(image->GetMetadata()); if (FAILED(hr)) { - wprintf(L" FAILED [keepcoverage] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [keepcoverage] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } @@ -2902,7 +3324,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = ScaleMipMapsAlphaForCoverage(img, info.mipLevels, info, item, preserveAlphaCoverageRef, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [keepcoverage] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [keepcoverage] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); return 1; } } @@ -2924,7 +3346,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } // --- Premultiplied alpha (if requested) -------------------------------------- - if ((dwOptions & (DWORD64(1) << OPT_PREMUL_ALPHA)) + if ((dwOptions & (uint64_t(1) << OPT_PREMUL_ALPHA)) && HasAlpha(info.format) && info.format != DXGI_FORMAT_A8_UNORM) { @@ -2948,7 +3370,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) hr = PremultiplyAlpha(img, nimg, info, TEX_PMALPHA_DEFAULT | dwSRGB, *timage); if (FAILED(hr)) { - wprintf(L" FAILED [premultiply alpha] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [premultiply alpha] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } @@ -3025,7 +3448,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) { s_tryonce = true; - if (!(dwOptions & (DWORD64(1) << OPT_NOGPU))) + if (!(dwOptions & (uint64_t(1) << OPT_NOGPU))) { if (!CreateDevice(adapter, pDevice.GetAddressOf())) wprintf(L"\nWARNING: DirectCompute is not available, using BC6H / BC7 CPU codec\n"); @@ -3044,7 +3467,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) TEX_COMPRESS_FLAGS cflags = dwCompress; #ifdef _OPENMP - if (!(dwOptions & (DWORD64(1) << OPT_FORCE_SINGLEPROC))) + if (!(dwOptions & (uint64_t(1) << OPT_FORCE_SINGLEPROC))) { cflags |= TEX_COMPRESS_PARALLEL; } @@ -3065,7 +3488,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) } if (FAILED(hr)) { - wprintf(L" FAILED [compress] (%x)\n", static_cast(hr)); + wprintf(L" FAILED [compress] (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } @@ -3100,7 +3524,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) { // Aleady set TEX_ALPHA_MODE_PREMULTIPLIED } - else if (dwOptions & (DWORD64(1) << OPT_SEPALPHA)) + else if (dwOptions & (uint64_t(1) << OPT_SEPALPHA)) { info.SetAlphaMode(TEX_ALPHA_MODE_CUSTOM); } @@ -3120,42 +3544,78 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) assert(img); size_t nimg = image->GetImageCount(); - PrintInfo(info, (FileType == CODEC_DDS) && (dwOptions & (DWORD64(1) << OPT_USE_XBOX))); + PrintInfo(info, (FileType == CODEC_DDS) && (dwOptions & (uint64_t(1) << OPT_USE_XBOX))); wprintf(L"\n"); // Figure out dest filename wchar_t *pchSlash, *pchDot; - wcscpy_s(pConv->szDest, MAX_PATH, szPrefix); + wchar_t szDest[1024] = {}; + wcscpy_s(szDest, szOutputDir); + + if (keepRecursiveDirs && *pConv->szFolder) + { + wcscat_s(szDest, pConv->szFolder); + + wchar_t szPath[MAX_PATH] = {}; + if (!GetFullPathNameW(szDest, MAX_PATH, szPath, nullptr)) + { + wprintf(L" get full path FAILED (%08X%ls)\n", + static_cast(HRESULT_FROM_WIN32(GetLastError())), GetErrorDesc(HRESULT_FROM_WIN32(GetLastError()))); + retVal = 1; + continue; + } + + auto err = static_cast(SHCreateDirectoryExW(nullptr, szPath, nullptr)); + if (err != ERROR_SUCCESS && err != ERROR_ALREADY_EXISTS) + { + wprintf(L" directory creation FAILED (%08X%ls)\n", + static_cast(HRESULT_FROM_WIN32(err)), GetErrorDesc(HRESULT_FROM_WIN32(err))); + retVal = 1; + continue; + } + } + + if (*szPrefix) + wcscat_s(szDest, szPrefix); pchSlash = wcsrchr(pConv->szSrc, L'\\'); if (pchSlash) - wcscat_s(pConv->szDest, MAX_PATH, pchSlash + 1); + wcscat_s(szDest, pchSlash + 1); else - wcscat_s(pConv->szDest, MAX_PATH, pConv->szSrc); + wcscat_s(szDest, pConv->szSrc); - pchSlash = wcsrchr(pConv->szDest, '\\'); - pchDot = wcsrchr(pConv->szDest, '.'); + pchSlash = wcsrchr(szDest, '\\'); + pchDot = wcsrchr(szDest, '.'); if (pchDot > pchSlash) *pchDot = 0; - wcscat_s(pConv->szDest, MAX_PATH, szSuffix); + if (*szSuffix) + wcscat_s(szDest, szSuffix); + + if (dwOptions & (uint64_t(1) << OPT_TOLOWER)) + { + (void)_wcslwr_s(szDest); + } - if (dwOptions & (DWORD64(1) << OPT_TOLOWER)) + if (wcslen(szDest) > _MAX_PATH) { - (void)_wcslwr_s(pConv->szDest); + wprintf(L"\nERROR: Output filename exceeds max-path, skipping!\n"); + retVal = 1; + continue; } // Write texture - wprintf(L"writing %ls", pConv->szDest); + wprintf(L"writing %ls", szDest); fflush(stdout); - if (~dwOptions & (DWORD64(1) << OPT_OVERWRITE)) + if (~dwOptions & (uint64_t(1) << OPT_OVERWRITE)) { - if (GetFileAttributesW(pConv->szDest) != INVALID_FILE_ATTRIBUTES) + if (GetFileAttributesW(szDest) != INVALID_FILE_ATTRIBUTES) { wprintf(L"\nERROR: Output file already exists, use -y to overwrite:\n"); + retVal = 1; continue; } } @@ -3163,62 +3623,62 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) switch (FileType) { case CODEC_DDS: - if (dwOptions & (DWORD64(1) << OPT_USE_XBOX)) + if (dwOptions & (uint64_t(1) << OPT_USE_XBOX)) { Xbox::XboxImage xbox; hr = Xbox::Tile(img, nimg, info, xbox); if (SUCCEEDED(hr)) { - hr = Xbox::SaveToDDSFile(xbox, pConv->szDest); + hr = Xbox::SaveToDDSFile(xbox, szDest); } } else { DDS_FLAGS ddsFlags = DDS_FLAGS_NONE; - if (dwOptions & (DWORD64(1) << OPT_USE_DX10)) + if (dwOptions & (uint64_t(1) << OPT_USE_DX10)) { ddsFlags |= DDS_FLAGS_FORCE_DX10_EXT | DDS_FLAGS_FORCE_DX10_EXT_MISC2; } - else if (dwOptions & (DWORD64(1) << OPT_USE_DX9)) + else if (dwOptions & (uint64_t(1) << OPT_USE_DX9)) { ddsFlags |= DDS_FLAGS_FORCE_DX9_LEGACY; } - hr = SaveToDDSFile(img, nimg, info, ddsFlags, pConv->szDest); + hr = SaveToDDSFile(img, nimg, info, ddsFlags, szDest); } break; case CODEC_TGA: - hr = SaveToTGAFile(img[0], TGA_FLAGS_NONE, pConv->szDest, (dwOptions & (DWORD64(1) << OPT_TGA20)) ? &info : nullptr); + hr = SaveToTGAFile(img[0], TGA_FLAGS_NONE, szDest, (dwOptions & (uint64_t(1) << OPT_TGA20)) ? &info : nullptr); break; case CODEC_HDR: - hr = SaveToHDRFile(img[0], pConv->szDest); + hr = SaveToHDRFile(img[0], szDest); break; case CODEC_PPM: - hr = SaveToPortablePixMap(img[0], pConv->szDest); + hr = SaveToPortablePixMap(img[0], szDest); break; case CODEC_PFM: - hr = SaveToPortablePixMapHDR(img[0], pConv->szDest); + hr = SaveToPortablePixMapHDR(img[0], szDest); break; #ifdef USE_OPENEXR case CODEC_EXR: - hr = SaveToEXRFile(img[0], pConv->szDest); + hr = SaveToEXRFile(img[0], szDest); break; #endif default: { WICCodecs codec = (FileType == CODEC_HDP || FileType == CODEC_JXR) ? WIC_CODEC_WMP : static_cast(FileType); - size_t nimages = (dwOptions & (DWORD64(1) << OPT_WIC_MULTIFRAME)) ? nimg : 1; - hr = SaveToWICFile(img, nimages, WIC_FLAGS_NONE, GetWICCodec(codec), pConv->szDest, nullptr, + size_t nimages = (dwOptions & (uint64_t(1) << OPT_WIC_MULTIFRAME)) ? nimg : 1; + hr = SaveToWICFile(img, nimages, WIC_FLAGS_NONE, GetWICCodec(codec), szDest, nullptr, [&](IPropertyBag2* props) { - bool wicLossless = (dwOptions & (DWORD64(1) << OPT_WIC_LOSSLESS)) != 0; + bool wicLossless = (dwOptions & (uint64_t(1) << OPT_WIC_LOSSLESS)) != 0; switch (FileType) { @@ -3283,7 +3743,8 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) if (FAILED(hr)) { - wprintf(L" FAILED (%x)\n", static_cast(hr)); + wprintf(L" FAILED (%08X%ls)\n", static_cast(hr), GetErrorDesc(hr)); + retVal = 1; continue; } wprintf(L"\n"); @@ -3292,7 +3753,7 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) if (sizewarn) { - wprintf(L"\nWARNING: Target size exceeds maximum size for feature level (%lu)\n", maxSize); + wprintf(L"\nWARNING: Target size exceeds maximum size for feature level (%u)\n", maxSize); } if (nonpow2warn && maxSize <= 4096) @@ -3304,15 +3765,14 @@ int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) if (non4bc) wprintf(L"\nWARNING: Direct3D requires BC image to be multiple of 4 in width & height\n"); - if (dwOptions & (DWORD64(1) << OPT_TIMING)) + if (dwOptions & (uint64_t(1) << OPT_TIMING)) { - LARGE_INTEGER qpcEnd; - if (QueryPerformanceCounter(&qpcEnd)) - { - LONGLONG delta = qpcEnd.QuadPart - qpcStart.QuadPart; - wprintf(L"\n Processing time: %f seconds\n", double(delta) / double(qpcFreq.QuadPart)); - } + LARGE_INTEGER qpcEnd = {}; + (void)QueryPerformanceCounter(&qpcEnd); + + LONGLONG delta = qpcEnd.QuadPart - qpcStart.QuadPart; + wprintf(L"\n Processing time: %f seconds\n", double(delta) / double(qpcFreq.QuadPart)); } - return 0; + return retVal; }