From 926666a05390dabadf837b4eb536d37da4db16cc Mon Sep 17 00:00:00 2001 From: sfpgmr Date: Sun, 3 Jun 2012 17:54:31 +0900 Subject: [PATCH] =?utf8?q?Release=20Preview=20=E5=AF=BE=E5=BF=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- ShootingGame/App.xaml | 2 +- ShootingGame/App.xaml.cpp | 13 -- ShootingGame/App.xaml.h | 5 - ShootingGame/AutoThrottle.h | 4 +- ShootingGame/BasicLoader.cpp | 203 +++++++++++++----- ShootingGame/BasicLoader.h | 24 +-- ShootingGame/BasicMath.h | 46 +++-- ShootingGame/BasicReaderWriter.cpp | 34 ++- ShootingGame/BasicReaderWriter.h | 18 +- ShootingGame/BasicShapes.h | 2 +- ShootingGame/BasicSprites.h | 4 +- ShootingGame/BasicTimer.h | 4 +- ShootingGame/Common/BindableBase.h | 2 +- ShootingGame/DDSTextureLoader.cpp | 411 +++++++++++++++++++------------------ ShootingGame/DirectXBase.cpp | 60 +++--- ShootingGame/DirectXBase.h | 15 +- ShootingGame/GameMain.cpp | 40 ++-- ShootingGame/GameMain.h | 7 +- ShootingGame/SampleOverlay.h | 2 +- ShootingGame/ShootingGame.vcxproj | 14 -- ShootingGame/SoundDriver.cpp | 398 ++++++++++++++++++++++++----------- ShootingGame/SoundDriver.h | 14 +- ShootingGame/TestSong.cpp | 4 +- ShootingGame/pch.h | 1 + 24 files changed, 780 insertions(+), 547 deletions(-) diff --git a/ShootingGame/App.xaml b/ShootingGame/App.xaml index bdf5cae..f0636ac 100644 --- a/ShootingGame/App.xaml +++ b/ShootingGame/App.xaml @@ -12,7 +12,7 @@ Styles that define common aspects of the platform look and feel Required by Visual Studio project and item templates --> - + diff --git a/ShootingGame/App.xaml.cpp b/ShootingGame/App.xaml.cpp index cf5651d..ff84a4e 100644 --- a/ShootingGame/App.xaml.cpp +++ b/ShootingGame/App.xaml.cpp @@ -69,12 +69,6 @@ void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEvent CompositionTarget::Rendering::add (ref new EventHandler(this, &App::OnRendering)); - ApplicationView::GetForCurrentView()->ViewStateChanged += - ref new TypedEventHandler( - this, - &App::OnViewStateChanged - ); - CoreApplication::Suspending += ref new EventHandler(this, &App::OnSuspending); CoreApplication::Resuming += ref new EventHandler(this, &App::OnResuming); @@ -176,13 +170,6 @@ void App::OnResuming( ) { } -//-------------------------------------------------------------------------------------- -void App::OnViewStateChanged( - _In_ ApplicationView^ view, - _In_ ApplicationViewStateChangedEventArgs^ args - ) -{ -} void App::OnPointerPressed( _In_ Windows::UI::Core::CoreWindow^ sender, diff --git a/ShootingGame/App.xaml.h b/ShootingGame/App.xaml.h index d660673..ffa9216 100644 --- a/ShootingGame/App.xaml.h +++ b/ShootingGame/App.xaml.h @@ -33,11 +33,6 @@ namespace ShootingGame _In_ Platform::Object^ args ); - void OnViewStateChanged( - _In_ Windows::UI::ViewManagement::ApplicationView^ view, - _In_ Windows::UI::ViewManagement::ApplicationViewStateChangedEventArgs^ args - ); - void OnWindowActivationChanged( _In_ Platform::Object^ sender, _In_ Windows::UI::Core::WindowActivatedEventArgs^ args diff --git a/ShootingGame/AutoThrottle.h b/ShootingGame/AutoThrottle.h index ecd498b..a084713 100644 --- a/ShootingGame/AutoThrottle.h +++ b/ShootingGame/AutoThrottle.h @@ -14,9 +14,9 @@ enum class FrameWorkload Maintain }; -ref class AutoThrottle sealed +ref class AutoThrottle { -public: +internal: AutoThrottle(float targetFrameTime); FrameWorkload Update(float frameTime); diff --git a/ShootingGame/BasicLoader.cpp b/ShootingGame/BasicLoader.cpp index 2134d13..af4ff33 100644 --- a/ShootingGame/BasicLoader.cpp +++ b/ShootingGame/BasicLoader.cpp @@ -17,11 +17,13 @@ using namespace Windows::Storage; using namespace Windows::Storage::Streams; using namespace Windows::Foundation; using namespace Windows::ApplicationModel; +using namespace std; +using namespace concurrency; BasicLoader::BasicLoader( _In_ ID3D11Device* d3dDevice, _In_opt_ IWICImagingFactory2* wicFactory - ) : + ) : m_d3dDevice(d3dDevice), m_wicFactory(wicFactory) { @@ -29,7 +31,7 @@ BasicLoader::BasicLoader( m_basicReaderWriter = ref new BasicReaderWriter(); } -template +template inline void BasicLoader::SetDebugName( _In_ DeviceChildType* object, _In_ Platform::String^ name @@ -43,14 +45,14 @@ inline void BasicLoader::SetDebugName( CP_ACP, 0, name->Data(), - -1, + -1, nameString, 1024, nullptr, nullptr ); - if (nameStringLength == 0 ) + if (nameStringLength == 0) { char defaultNameString[] = "BasicLoaderObject"; DX::ThrowIfFailed( @@ -134,7 +136,7 @@ void BasicLoader::CreateTexture( &shaderResourceView ); } - + DX::ThrowIfFailed( resource.As(&texture2D) ); @@ -221,15 +223,17 @@ void BasicLoader::CreateTexture( initialData.SysMemPitch = width * 4; initialData.SysMemSlicePitch = 0; + CD3D11_TEXTURE2D_DESC textureDesc( + DXGI_FORMAT_B8G8R8A8_UNORM, + width, + height, + 1, + 1 + ); + DX::ThrowIfFailed( m_d3dDevice->CreateTexture2D( - &CD3D11_TEXTURE2D_DESC( - DXGI_FORMAT_B8G8R8A8_UNORM, - width, - height, - 1, - 1 - ), + &textureDesc, &initialData, &texture2D ) @@ -237,13 +241,15 @@ void BasicLoader::CreateTexture( if (textureView != nullptr) { + CD3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc( + texture2D.Get(), + D3D11_SRV_DIMENSION_TEXTURE2D + ); + DX::ThrowIfFailed( m_d3dDevice->CreateShaderResourceView( texture2D.Get(), - &CD3D11_SHADER_RESOURCE_VIEW_DESC( - texture2D.Get(), - D3D11_SRV_DIMENSION_TEXTURE2D - ), + &shaderResourceViewDesc, &shaderResourceView ) ); @@ -273,7 +279,7 @@ void BasicLoader::CreateInputLayout( if (layoutDesc == nullptr) { // If no input layout is specified, use the BasicVertex layout. - const D3D11_INPUT_ELEMENT_DESC basicVertexLayoutDesc[] = + const D3D11_INPUT_ELEMENT_DESC basicVertexLayoutDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, @@ -331,9 +337,10 @@ void BasicLoader::CreateMesh( vertexBufferData.pSysMem = vertices; vertexBufferData.SysMemPitch = 0; vertexBufferData.SysMemSlicePitch = 0; + CD3D11_BUFFER_DESC vertexBufferDesc(numVertices * sizeof(BasicVertex), D3D11_BIND_VERTEX_BUFFER); DX::ThrowIfFailed( m_d3dDevice->CreateBuffer( - &CD3D11_BUFFER_DESC(numVertices * sizeof(BasicVertex), D3D11_BIND_VERTEX_BUFFER), + &vertexBufferDesc, &vertexBufferData, vertexBuffer ) @@ -343,9 +350,10 @@ void BasicLoader::CreateMesh( indexBufferData.pSysMem = indices; indexBufferData.SysMemPitch = 0; indexBufferData.SysMemSlicePitch = 0; + CD3D11_BUFFER_DESC indexBufferDesc(numIndices * sizeof(uint16), D3D11_BIND_INDEX_BUFFER); DX::ThrowIfFailed( m_d3dDevice->CreateBuffer( - &CD3D11_BUFFER_DESC(numIndices * sizeof(uint16), D3D11_BIND_INDEX_BUFFER), + &indexBufferDesc, &indexBufferData, indexBuffer ) @@ -382,13 +390,13 @@ void BasicLoader::LoadTexture( ); } -void BasicLoader::LoadTextureAsync( +task BasicLoader::LoadTextureAsync( _In_ Platform::String^ filename, _Out_opt_ ID3D11Texture2D** texture, _Out_opt_ ID3D11ShaderResourceView** textureView ) { - m_basicReaderWriter->ReadDataAsync(filename, ref new ReadDataAsyncCallback([=](Platform::Array^ textureData, AsyncStatus /*status*/) + return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ textureData) { CreateTexture( GetExtension(filename) == "dds", @@ -398,7 +406,7 @@ void BasicLoader::LoadTextureAsync( textureView, filename ); - })); + }); } void BasicLoader::LoadShader( @@ -436,7 +444,7 @@ void BasicLoader::LoadShader( } } -void BasicLoader::LoadShaderAsync( +task BasicLoader::LoadShaderAsync( _In_ Platform::String^ filename, _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[], _In_ uint32 layoutDescNumElements, @@ -444,7 +452,36 @@ void BasicLoader::LoadShaderAsync( _Out_opt_ ID3D11InputLayout** layout ) { - m_basicReaderWriter->ReadDataAsync(filename, ref new ReadDataAsyncCallback([=](Platform::Array^ bytecode, AsyncStatus /*status*/) + // This method assumes that the lifetime of input arguments may be shorter + // than the duration of this task. In order to ensure accurate results, a + // copy of all arguments passed by pointer must be made. The method then + // ensures that the lifetime of the copied data exceeds that of the task. + + // Create copies of the layoutDesc array as well as the SemanticName strings, + // both of which are pointers to data whose lifetimes may be shorter than that + // of this method's task. + shared_ptr> layoutDescCopy; + shared_ptr> layoutDescSemanticNamesCopy; + if (layoutDesc != nullptr) + { + layoutDescCopy.reset( + new vector( + layoutDesc, + layoutDesc + layoutDescNumElements + ) + ); + + layoutDescSemanticNamesCopy.reset( + new vector(layoutDescNumElements) + ); + + for (uint32 i = 0; i < layoutDescNumElements; i++) + { + layoutDescSemanticNamesCopy->at(i).assign(layoutDesc[i].SemanticName); + } + } + + return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) { DX::ThrowIfFailed( m_d3dDevice->CreateVertexShader( @@ -459,17 +496,30 @@ void BasicLoader::LoadShaderAsync( if (layout != nullptr) { + if (layoutDesc != nullptr) + { + // Reassign the SemanticName elements of the layoutDesc array copy to point + // to the corresponding copied strings. Performing the assignment inside the + // lambda body ensures that the lambda will take a reference to the shared_ptr + // that holds the data. This will guarantee that the data is still valid when + // CreateInputLayout is called. + for (uint32 i = 0; i < layoutDescNumElements; i++) + { + layoutDescCopy->at(i).SemanticName = layoutDescSemanticNamesCopy->at(i).c_str(); + } + } + CreateInputLayout( bytecode->Data, bytecode->Length, - layoutDesc, + layoutDesc == nullptr ? nullptr : layoutDescCopy->data(), layoutDescNumElements, layout ); SetDebugName(*layout, filename); } - })); + }); } void BasicLoader::LoadShader( @@ -491,12 +541,12 @@ void BasicLoader::LoadShader( SetDebugName(*shader, filename); } -void BasicLoader::LoadShaderAsync( +task BasicLoader::LoadShaderAsync( _In_ Platform::String^ filename, _Out_ ID3D11PixelShader** shader ) { - m_basicReaderWriter->ReadDataAsync(filename, ref new ReadDataAsyncCallback([=](Platform::Array^ bytecode, AsyncStatus /*status*/) + return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) { DX::ThrowIfFailed( m_d3dDevice->CreatePixelShader( @@ -508,7 +558,7 @@ void BasicLoader::LoadShaderAsync( ); SetDebugName(*shader, filename); - })); + }); } void BasicLoader::LoadShader( @@ -530,12 +580,12 @@ void BasicLoader::LoadShader( SetDebugName(*shader, filename); } -void BasicLoader::LoadShaderAsync( +task BasicLoader::LoadShaderAsync( _In_ Platform::String^ filename, _Out_ ID3D11ComputeShader** shader ) { - m_basicReaderWriter->ReadDataAsync(filename, ref new ReadDataAsyncCallback([=](Platform::Array^ bytecode, AsyncStatus /*status*/) + return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) { DX::ThrowIfFailed( m_d3dDevice->CreateComputeShader( @@ -547,7 +597,7 @@ void BasicLoader::LoadShaderAsync( ); SetDebugName(*shader, filename); - })); + }); } void BasicLoader::LoadShader( @@ -569,12 +619,12 @@ void BasicLoader::LoadShader( SetDebugName(*shader, filename); } -void BasicLoader::LoadShaderAsync( +task BasicLoader::LoadShaderAsync( _In_ Platform::String^ filename, _Out_ ID3D11GeometryShader** shader ) { - m_basicReaderWriter->ReadDataAsync(filename, ref new ReadDataAsyncCallback([=](Platform::Array^ bytecode, AsyncStatus /*status*/) + return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) { DX::ThrowIfFailed( m_d3dDevice->CreateGeometryShader( @@ -586,7 +636,7 @@ void BasicLoader::LoadShaderAsync( ); SetDebugName(*shader, filename); - })); + }); } void BasicLoader::LoadShader( @@ -618,7 +668,7 @@ void BasicLoader::LoadShader( SetDebugName(*shader, filename); } -void BasicLoader::LoadShaderAsync( +task BasicLoader::LoadShaderAsync( _In_ Platform::String^ filename, _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration, _In_ uint32 numEntries, @@ -628,15 +678,70 @@ void BasicLoader::LoadShaderAsync( _Out_ ID3D11GeometryShader** shader ) { - m_basicReaderWriter->ReadDataAsync(filename, ref new ReadDataAsyncCallback([=](Platform::Array^ bytecode, AsyncStatus /*status*/) + // This method assumes that the lifetime of input arguments may be shorter + // than the duration of this task. In order to ensure accurate results, a + // copy of all arguments passed by pointer must be made. The method then + // ensures that the lifetime of the copied data exceeds that of the task. + + // Create copies of the streamOutDeclaration array as well as the SemanticName + // strings, both of which are pointers to data whose lifetimes may be shorter + // than that of this method's task. + shared_ptr> streamOutDeclarationCopy; + shared_ptr> streamOutDeclarationSemanticNamesCopy; + if (streamOutDeclaration != nullptr) { + streamOutDeclarationCopy.reset( + new vector( + streamOutDeclaration, + streamOutDeclaration + numEntries + ) + ); + + streamOutDeclarationSemanticNamesCopy.reset( + new vector(numEntries) + ); + + for (uint32 i = 0; i < numEntries; i++) + { + streamOutDeclarationSemanticNamesCopy->at(i).assign(streamOutDeclaration[i].SemanticName); + } + } + + // Create a copy of the bufferStrides array, which is a pointer to data + // whose lifetime may be shorter than that of this method's task. + shared_ptr> bufferStridesCopy; + if (bufferStrides != nullptr) + { + bufferStridesCopy.reset( + new vector( + bufferStrides, + bufferStrides + numStrides + ) + ); + } + + return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) + { + if (streamOutDeclaration != nullptr) + { + // Reassign the SemanticName elements of the streamOutDeclaration array copy to + // point to the corresponding copied strings. Performing the assignment inside the + // lambda body ensures that the lambda will take a reference to the shared_ptr + // that holds the data. This will guarantee that the data is still valid when + // CreateGeometryShaderWithStreamOutput is called. + for (uint32 i = 0; i < numEntries; i++) + { + streamOutDeclarationCopy->at(i).SemanticName = streamOutDeclarationSemanticNamesCopy->at(i).c_str(); + } + } + DX::ThrowIfFailed( m_d3dDevice->CreateGeometryShaderWithStreamOutput( bytecode->Data, bytecode->Length, - streamOutDeclaration, + streamOutDeclaration == nullptr ? nullptr : streamOutDeclarationCopy->data(), numEntries, - bufferStrides, + bufferStrides == nullptr ? nullptr : bufferStridesCopy->data(), numStrides, rasterizedStream, nullptr, @@ -645,7 +750,7 @@ void BasicLoader::LoadShaderAsync( ); SetDebugName(*shader, filename); - })); + }); } void BasicLoader::LoadShader( @@ -667,12 +772,12 @@ void BasicLoader::LoadShader( SetDebugName(*shader, filename); } -void BasicLoader::LoadShaderAsync( +task BasicLoader::LoadShaderAsync( _In_ Platform::String^ filename, _Out_ ID3D11HullShader** shader ) { - m_basicReaderWriter->ReadDataAsync(filename, ref new ReadDataAsyncCallback([=](Platform::Array^ bytecode, AsyncStatus /*status*/) + return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) { DX::ThrowIfFailed( m_d3dDevice->CreateHullShader( @@ -684,7 +789,7 @@ void BasicLoader::LoadShaderAsync( ); SetDebugName(*shader, filename); - })); + }); } void BasicLoader::LoadShader( @@ -706,12 +811,12 @@ void BasicLoader::LoadShader( SetDebugName(*shader, filename); } -void BasicLoader::LoadShaderAsync( +task BasicLoader::LoadShaderAsync( _In_ Platform::String^ filename, _Out_ ID3D11DomainShader** shader ) { - m_basicReaderWriter->ReadDataAsync(filename, ref new ReadDataAsyncCallback([=](Platform::Array^ bytecode, AsyncStatus /*status*/) + return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ bytecode) { DX::ThrowIfFailed( m_d3dDevice->CreateDomainShader( @@ -723,7 +828,7 @@ void BasicLoader::LoadShaderAsync( ); SetDebugName(*shader, filename); - })); + }); } void BasicLoader::LoadMesh( @@ -746,7 +851,7 @@ void BasicLoader::LoadMesh( ); } -void BasicLoader::LoadMeshAsync( +task BasicLoader::LoadMeshAsync( _In_ Platform::String^ filename, _Out_ ID3D11Buffer** vertexBuffer, _Out_ ID3D11Buffer** indexBuffer, @@ -754,7 +859,7 @@ void BasicLoader::LoadMeshAsync( _Out_opt_ uint32* indexCount ) { - m_basicReaderWriter->ReadDataAsync(filename, ref new ReadDataAsyncCallback([=](Platform::Array^ meshData, AsyncStatus /*status*/) + return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array^ meshData) { CreateMesh( meshData->Data, @@ -764,5 +869,5 @@ void BasicLoader::LoadMeshAsync( indexCount, filename ); - })); + }); } diff --git a/ShootingGame/BasicLoader.h b/ShootingGame/BasicLoader.h index 8465cdd..b23c6e4 100644 --- a/ShootingGame/BasicLoader.h +++ b/ShootingGame/BasicLoader.h @@ -11,7 +11,7 @@ ref class BasicLoader { -public: +internal: BasicLoader( _In_ ID3D11Device* d3dDevice, _In_opt_ IWICImagingFactory2* wicFactory = nullptr @@ -22,8 +22,8 @@ public: _Out_opt_ ID3D11Texture2D** texture, _Out_opt_ ID3D11ShaderResourceView** textureView ); - - void LoadTextureAsync( + + concurrency::task LoadTextureAsync( _In_ Platform::String^ filename, _Out_opt_ ID3D11Texture2D** texture, _Out_opt_ ID3D11ShaderResourceView** textureView @@ -37,7 +37,7 @@ public: _Out_opt_ ID3D11InputLayout** layout ); - void LoadShaderAsync( + concurrency::task LoadShaderAsync( _In_ Platform::String^ filename, _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[], _In_ uint32 layoutDescNumElements, @@ -50,7 +50,7 @@ public: _Out_ ID3D11PixelShader** shader ); - void LoadShaderAsync( + concurrency::task LoadShaderAsync( _In_ Platform::String^ filename, _Out_ ID3D11PixelShader** shader ); @@ -60,7 +60,7 @@ public: _Out_ ID3D11ComputeShader** shader ); - void LoadShaderAsync( + concurrency::task LoadShaderAsync( _In_ Platform::String^ filename, _Out_ ID3D11ComputeShader** shader ); @@ -70,7 +70,7 @@ public: _Out_ ID3D11GeometryShader** shader ); - void LoadShaderAsync( + concurrency::task LoadShaderAsync( _In_ Platform::String^ filename, _Out_ ID3D11GeometryShader** shader ); @@ -85,7 +85,7 @@ public: _Out_ ID3D11GeometryShader** shader ); - void LoadShaderAsync( + concurrency::task LoadShaderAsync( _In_ Platform::String^ filename, _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration, _In_ uint32 numEntries, @@ -100,7 +100,7 @@ public: _Out_ ID3D11HullShader** shader ); - void LoadShaderAsync( + concurrency::task LoadShaderAsync( _In_ Platform::String^ filename, _Out_ ID3D11HullShader** shader ); @@ -110,7 +110,7 @@ public: _Out_ ID3D11DomainShader** shader ); - void LoadShaderAsync( + concurrency::task LoadShaderAsync( _In_ Platform::String^ filename, _Out_ ID3D11DomainShader** shader ); @@ -123,7 +123,7 @@ public: _Out_opt_ uint32* indexCount ); - void LoadMeshAsync( + concurrency::task LoadMeshAsync( _In_ Platform::String^ filename, _Out_ ID3D11Buffer** vertexBuffer, _Out_ ID3D11Buffer** indexBuffer, @@ -136,7 +136,7 @@ private: Microsoft::WRL::ComPtr m_wicFactory; BasicReaderWriter^ m_basicReaderWriter; - template + template inline void SetDebugName( _In_ DeviceChildType* object, _In_ Platform::String^ name diff --git a/ShootingGame/BasicMath.h b/ShootingGame/BasicMath.h index 5c9c4c9..c4f5816 100644 --- a/ShootingGame/BasicMath.h +++ b/ShootingGame/BasicMath.h @@ -10,6 +10,10 @@ #define _USE_MATH_DEFINES #include +// Common Constants + +#define PI_F 3.1415927f + // Template Vector & Matrix Classes template struct Vector2 @@ -103,7 +107,7 @@ template struct Vector4 template struct Matrix4x4 { - union + union { struct { @@ -130,16 +134,16 @@ template struct Matrix4x4 } Matrix4x4( - T i11, T i12, T i13, T i14, + T i11, T i12, T i13, T i14, T i21, T i22, T i23, T i24, T i31, T i32, T i33, T i34, T i41, T i42, T i43, T i44 ) { _11 = i11; _12 = i12; _13 = i13; _14 = i14; - _21 = i21; _22 = i22; _23 = i23; _24 = i24; - _31 = i31; _32 = i32; _33 = i33; _34 = i34; - _41 = i41; _42 = i42; _43 = i43; _44 = i44; + _21 = i21; _22 = i22; _23 = i23; _24 = i24; + _31 = i31; _32 = i32; _33 = i33; _34 = i34; + _41 = i41; _42 = i42; _43 = i43; _44 = i44; } T* operator[](unsigned int index) @@ -180,7 +184,7 @@ T length(Vector3 a) return sqrt(a.x * a.x + a.y * a.y + a.z * a.z); } -template +template T length(Vector4 a) { return sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w); @@ -206,7 +210,7 @@ Vector3 normalize(Vector3 a) return Vector3(a.x / len, a.y / len, a.z / len); } -template +template Vector4 normalize(Vector4 a) { T len = length(a); @@ -234,7 +238,7 @@ Vector3 operator-(Vector3 a, Vector3 b) } template -Vector3 operator-(Vector3 a ) +Vector3 operator-(Vector3 a) { return Vector3( -a.x, -a.y, -a.z); } @@ -246,7 +250,7 @@ Vector4 operator-(Vector4 a, Vector4 b) } template -Vector4 operator-(Vector4 a ) +Vector4 operator-(Vector4 a) { return Vector4( -a.x, -a.y, -a.z, -a.w); } @@ -284,7 +288,7 @@ Vector2 operator*(T s, Vector2 a) template Vector2 operator*(Vector2 a, Vector2 b) { - return Vector2(a.x * b.x, a.y * b.y); + return Vector2(a.x * b.x, a.y * b.y); } template @@ -308,7 +312,7 @@ Vector3 operator*(T s, Vector3 a) template Vector3 operator*(Vector3 a, Vector3 b) { - return Vector3(a.x * b.x, a.y * b.y, a.z * b.z); + return Vector3(a.x * b.x, a.y * b.y, a.z * b.z); } template @@ -332,7 +336,7 @@ Vector4 operator*(T s, Vector4 a) template Vector4 operator*(Vector4 a, Vector4 b) { - return Vector4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); + return Vector4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); } template @@ -349,8 +353,8 @@ template Matrix4x4 transpose(Matrix4x4 m) { return Matrix4x4( - m._11, m._21, m._31, m._41, - m_.12, m._22, m._32, m._42, + m._11, m._21, m._31, m._41, + m_.12, m._22, m._32, m._42, m._13, m._23, m._33, m._43, m._14, m._24, m._34, m._44 ); @@ -361,11 +365,11 @@ Matrix4x4 mul(Matrix4x4 m1, Matrix4x4 m2) { Matrix4x4 mOut; - for(int i=0;i<4;i++) + for (int i = 0; i < 4; i++) { - for(int j=0;j<4;j++) + for (int j = 0; j < 4; j++) { - for(int k=0;k<4;k++) + for (int k = 0; k < 4; k++) { mOut[i][j] += m1[i][k] * m2[k][j]; } @@ -425,7 +429,7 @@ inline float4x4 scale(float x, float y, float z) inline float4x4 rotationX(float degreeX) { - float angleInRadians = degreeX * ((float)M_PI / 180.0f); + float angleInRadians = degreeX * (PI_F / 180.0f); float sinAngle = sinf(angleInRadians); float cosAngle = cosf(angleInRadians); @@ -442,7 +446,7 @@ inline float4x4 rotationX(float degreeX) inline float4x4 rotationY(float degreeY) { - float angleInRadians = degreeY * ((float)M_PI / 180.0f); + float angleInRadians = degreeY * (PI_F / 180.0f); float sinAngle = sinf(angleInRadians); float cosAngle = cosf(angleInRadians); @@ -459,7 +463,7 @@ inline float4x4 rotationY(float degreeY) inline float4x4 rotationZ(float degreeZ) { - float angleInRadians = degreeZ * ((float)M_PI / 180.0f); + float angleInRadians = degreeZ * (PI_F / 180.0f); float sinAngle = sinf(angleInRadians); float cosAngle = cosf(angleInRadians); @@ -479,7 +483,7 @@ inline float4x4 rotationArbitrary(float3 axis, float degree) { axis = normalize(axis); - float angleInRadians = degree * ((float)M_PI / 180.0f); + float angleInRadians = degree * (PI_F / 180.0f); float sinAngle = sinf(angleInRadians); float cosAngle = cosf(angleInRadians); diff --git a/ShootingGame/BasicReaderWriter.cpp b/ShootingGame/BasicReaderWriter.cpp index e545dc0..37e424a 100644 --- a/ShootingGame/BasicReaderWriter.cpp +++ b/ShootingGame/BasicReaderWriter.cpp @@ -7,7 +7,6 @@ #include "pch.h" #include "BasicReaderWriter.h" -#include using namespace Microsoft::WRL; using namespace Windows::Storage; @@ -15,7 +14,7 @@ using namespace Windows::Storage::FileProperties; using namespace Windows::Storage::Streams; using namespace Windows::Foundation; using namespace Windows::ApplicationModel; -using namespace Concurrency; +using namespace concurrency; BasicReaderWriter::BasicReaderWriter() { @@ -61,7 +60,7 @@ Platform::Array^ BasicReaderWriter::ReadData( &extendedParams ) ); - if (file.Get()==INVALID_HANDLE_VALUE) + if (file.Get() == INVALID_HANDLE_VALUE) { throw ref new Platform::FailureException(); } @@ -90,7 +89,7 @@ Platform::Array^ BasicReaderWriter::ReadData( fileData->Length, nullptr, nullptr - ) ) + )) { throw ref new Platform::FailureException(); } @@ -98,25 +97,24 @@ Platform::Array^ BasicReaderWriter::ReadData( return fileData; } -void BasicReaderWriter::ReadDataAsync( - _In_ Platform::String^ filename, - _In_ ReadDataAsyncCallback^ callback +task^> BasicReaderWriter::ReadDataAsync( + _In_ Platform::String^ filename ) { - task(m_location->GetFileAsync(filename)).then([=](StorageFile^ file) + return task(m_location->GetFileAsync(filename)).then([=](StorageFile^ file) { return FileIO::ReadBufferAsync(file); }).then([=](IBuffer^ buffer) { auto fileData = ref new Platform::Array(buffer->Length); DataReader::FromBuffer(buffer)->ReadBytes(fileData); - callback(fileData, AsyncStatus::Completed); + return fileData; }); } uint32 BasicReaderWriter::WriteData( _In_ Platform::String^ filename, - _In_ Platform::Array^ fileData + _In_ const Platform::Array^ fileData ) { CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0}; @@ -136,7 +134,7 @@ uint32 BasicReaderWriter::WriteData( &extendedParams ) ); - if (file.Get()==INVALID_HANDLE_VALUE) + if (file.Get() == INVALID_HANDLE_VALUE) { throw ref new Platform::FailureException(); } @@ -149,7 +147,7 @@ uint32 BasicReaderWriter::WriteData( fileData->Length, &numBytesWritten, nullptr - ) || + ) || numBytesWritten != fileData->Length ) { @@ -159,17 +157,13 @@ uint32 BasicReaderWriter::WriteData( return numBytesWritten; } -void BasicReaderWriter::WriteDataAsync( +task BasicReaderWriter::WriteDataAsync( _In_ Platform::String^ filename, - _In_ Platform::Array^ fileData, - _In_ WriteDataAsyncCallback^ callback + _In_ const Platform::Array^ fileData ) { - task(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file) - { - return FileIO::WriteBytesAsync(file, fileData); - }).then([=]() + return task(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file) { - callback(AsyncStatus::Completed); + FileIO::WriteBytesAsync(file, fileData); }); } diff --git a/ShootingGame/BasicReaderWriter.h b/ShootingGame/BasicReaderWriter.h index 94dbaaa..3b3ee85 100644 --- a/ShootingGame/BasicReaderWriter.h +++ b/ShootingGame/BasicReaderWriter.h @@ -7,9 +7,7 @@ #pragma once -// Define the arguments for the async callbacks. -delegate void ReadDataAsyncCallback(Platform::Array^, Windows::Foundation::AsyncStatus); -delegate void WriteDataAsyncCallback(Windows::Foundation::AsyncStatus); +#include ref class BasicReaderWriter { @@ -17,7 +15,7 @@ private: Windows::Storage::StorageFolder^ m_location; Platform::String^ m_locationPath; -public: +internal: BasicReaderWriter(); BasicReaderWriter( _In_ Windows::Storage::StorageFolder^ folder @@ -27,19 +25,17 @@ public: _In_ Platform::String^ filename ); - void ReadDataAsync( - _In_ Platform::String^ filename, - _In_ ReadDataAsyncCallback^ callback + concurrency::task^> ReadDataAsync( + _In_ Platform::String^ filename ); uint32 WriteData( _In_ Platform::String^ filename, - _In_ Platform::Array^ fileData + _In_ const Platform::Array^ fileData ); - void WriteDataAsync( + concurrency::task WriteDataAsync( _In_ Platform::String^ filename, - _In_ Platform::Array^ fileData, - _In_ WriteDataAsyncCallback^ callback + _In_ const Platform::Array^ fileData ); }; diff --git a/ShootingGame/BasicShapes.h b/ShootingGame/BasicShapes.h index e894616..7197491 100644 --- a/ShootingGame/BasicShapes.h +++ b/ShootingGame/BasicShapes.h @@ -28,7 +28,7 @@ struct TangentVertex ref class BasicShapes { -public: +internal: BasicShapes(ID3D11Device *d3dDevice); void CreateCube( _Out_ ID3D11Buffer **vertexBuffer, diff --git a/ShootingGame/BasicSprites.h b/ShootingGame/BasicSprites.h index 7b05457..291989f 100644 --- a/ShootingGame/BasicSprites.h +++ b/ShootingGame/BasicSprites.h @@ -76,9 +76,9 @@ namespace BasicSprites ) = 0; }; - ref class SpriteBatch sealed + ref class SpriteBatch { - public: + internal: SpriteBatch(); void Initialize( _In_ ID3D11Device1* d3dDevice, diff --git a/ShootingGame/BasicTimer.h b/ShootingGame/BasicTimer.h index dc89390..d7b23d8 100644 --- a/ShootingGame/BasicTimer.h +++ b/ShootingGame/BasicTimer.h @@ -7,7 +7,7 @@ #pragma once -ref class BasicTimer sealed +ref class BasicTimer { private: LARGE_INTEGER m_frequency; @@ -17,7 +17,7 @@ private: float m_total; float m_delta; -public: +internal: BasicTimer(); void Reset(); void Update(); diff --git a/ShootingGame/Common/BindableBase.h b/ShootingGame/Common/BindableBase.h index fbc5755..8be6a59 100644 --- a/ShootingGame/Common/BindableBase.h +++ b/ShootingGame/Common/BindableBase.h @@ -16,7 +16,7 @@ namespace ShootingGame [Windows::Foundation::Metadata::WebHostHidden] public ref class BindableBase : Windows::UI::Xaml::Data::INotifyPropertyChanged { - public: + internal: event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged; protected: diff --git a/ShootingGame/DDSTextureLoader.cpp b/ShootingGame/DDSTextureLoader.cpp index b8ef9d8..9d72772 100644 --- a/ShootingGame/DDSTextureLoader.cpp +++ b/ShootingGame/DDSTextureLoader.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include "DDSTextureLoader.h" #include "DirectXSample.h" @@ -30,7 +31,7 @@ using namespace Microsoft::WRL; #ifndef MAKEFOURCC #define MAKEFOURCC(ch0, ch1, ch2, ch3) \ ((uint32)(byte)(ch0) | ((uint32)(byte)(ch1) << 8) | \ - ((uint32)(byte)(ch2) << 16) | ((uint32)(byte)(ch3) << 24 )) + ((uint32)(byte)(ch2) << 16) | ((uint32)(byte)(ch3) << 24)) #endif /* defined(MAKEFOURCC) */ //-------------------------------------------------------------------------------------- @@ -38,7 +39,7 @@ using namespace Microsoft::WRL; // // See DDS.h in the 'Texconv' sample and the 'DirectXTex' library //-------------------------------------------------------------------------------------- -#pragma pack(push,1) +#pragma pack(push, 1) #define DDS_MAGIC 0x20534444 // "DDS " @@ -62,7 +63,7 @@ struct DDS_PIXELFORMAT #define DDS_ALPHA 0x00000002 // DDPF_ALPHA #define DDS_PAL8 0x00000020 // DDPF_PALETTEINDEXED8 -#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 @@ -82,9 +83,9 @@ struct DDS_PIXELFORMAT #define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ #define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ -#define DDS_CUBEMAP_ALLFACES ( DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\ - DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\ - DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ ) +#define DDS_CUBEMAP_ALLFACES (DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\ + DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\ + DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ) #define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP @@ -122,9 +123,9 @@ typedef struct //-------------------------------------------------------------------------------------- // Return the BPP for a particular format //-------------------------------------------------------------------------------------- -static size_t BitsPerPixel( _In_ DXGI_FORMAT fmt ) +static size_t BitsPerPixel(_In_ DXGI_FORMAT fmt) { - switch( fmt ) + switch (fmt) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: case DXGI_FORMAT_R32G32B32A32_FLOAT: @@ -253,12 +254,14 @@ static size_t BitsPerPixel( _In_ DXGI_FORMAT fmt ) //-------------------------------------------------------------------------------------- // Get surface information for a particular format //-------------------------------------------------------------------------------------- -static void GetSurfaceInfo( _In_ size_t width, - _In_ size_t height, - _In_ DXGI_FORMAT fmt, - _Out_opt_ size_t* outNumBytes, - _Out_opt_ size_t* outRowBytes, - _Out_opt_ size_t* outNumRows ) +static void GetSurfaceInfo( + _In_ size_t width, + _In_ size_t height, + _In_ DXGI_FORMAT fmt, + _Out_opt_ size_t* outNumBytes, + _Out_opt_ size_t* outRowBytes, + _Out_opt_ size_t* outNumRows + ) { size_t numBytes = 0; size_t rowBytes = 0; @@ -275,7 +278,7 @@ static void GetSurfaceInfo( _In_ size_t width, case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM: - bc=true; + bc = true; bcnumBytesPerBlock = 8; break; @@ -309,25 +312,25 @@ static void GetSurfaceInfo( _In_ size_t width, size_t numBlocksWide = 0; if (width > 0) { - numBlocksWide = max( 1, (width + 3) / 4 ); + numBlocksWide = std::max(1, (width + 3) / 4); } size_t numBlocksHigh = 0; if (height > 0) { - numBlocksHigh = max( 1, (height + 3) / 4 ); + numBlocksHigh = std::max(1, (height + 3) / 4); } rowBytes = numBlocksWide * bcnumBytesPerBlock; numRows = numBlocksHigh; } else if (packed) { - rowBytes = ( ( width + 1 ) >> 1 ) * 4; + rowBytes = ((width + 1) >> 1) * 4; numRows = height; } else { - size_t bpp = BitsPerPixel( fmt ); - rowBytes = ( width * bpp + 7 ) / 8; // round up to nearest byte + size_t bpp = BitsPerPixel(fmt); + rowBytes = (width * bpp + 7) / 8; // round up to nearest byte numRows = height; } @@ -348,9 +351,9 @@ static void GetSurfaceInfo( _In_ size_t width, //-------------------------------------------------------------------------------------- -#define ISBITMASK( r,g,b,a ) ( ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a ) +#define ISBITMASK(r, g, b, a) (ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a) -static DXGI_FORMAT GetDXGIFormat( const DDS_PIXELFORMAT& ddpf ) +static DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf) { if (ddpf.flags & DDS_RGB) { @@ -359,22 +362,22 @@ static DXGI_FORMAT GetDXGIFormat( const DDS_PIXELFORMAT& ddpf ) switch (ddpf.RGBBitCount) { case 32: - if (ISBITMASK(0x000000ff,0x0000ff00,0x00ff0000,0xff000000)) + if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000)) { return DXGI_FORMAT_R8G8B8A8_UNORM; } - if (ISBITMASK(0x00ff0000,0x0000ff00,0x000000ff,0xff000000)) + if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000)) { return DXGI_FORMAT_B8G8R8A8_UNORM; } - if (ISBITMASK(0x00ff0000,0x0000ff00,0x000000ff,0x00000000)) + if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000)) { return DXGI_FORMAT_B8G8R8X8_UNORM; } - // No DXGI format maps to ISBITMASK(0x000000ff,0x0000ff00,0x00ff0000,0x00000000) aka D3DFMT_X8B8G8R8 + // No DXGI format maps to ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000) aka D3DFMT_X8B8G8R8 // Note that many common DDS reader/writers (including D3DX) swap the // the RED/BLUE masks for 10:10:10:2 formats. We assumme @@ -382,20 +385,20 @@ static DXGI_FORMAT GetDXGIFormat( const DDS_PIXELFORMAT& ddpf ) // 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)) + // 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 + // No DXGI format maps to ISBITMASK(0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000) aka D3DFMT_A2R10G10B10 - if (ISBITMASK(0x0000ffff,0xffff0000,0x00000000,0x00000000)) + if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000)) { return DXGI_FORMAT_R16G16_UNORM; } - if (ISBITMASK(0xffffffff,0x00000000,0x00000000,0x00000000)) + if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000)) { // Only 32-bit color channel format in D3D9 was R32F return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114 @@ -407,22 +410,22 @@ static DXGI_FORMAT GetDXGIFormat( const DDS_PIXELFORMAT& ddpf ) break; case 16: - if (ISBITMASK(0x7c00,0x03e0,0x001f,0x8000)) + if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000)) { return DXGI_FORMAT_B5G5R5A1_UNORM; } - if (ISBITMASK(0xf800,0x07e0,0x001f,0x0000)) + if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000)) { return DXGI_FORMAT_B5G6R5_UNORM; } - // No DXGI format maps to ISBITMASK(0x7c00,0x03e0,0x001f,0x0000) aka D3DFMT_X1R5G5B5 - if (ISBITMASK(0x0f00,0x00f0,0x000f,0xf000)) + // No DXGI format maps to ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x0000) aka D3DFMT_X1R5G5B5 + if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000)) { return DXGI_FORMAT_B4G4R4A4_UNORM; } - // No DXGI format maps to ISBITMASK(0x0f00,0x00f0,0x000f,0x0000) aka D3DFMT_X4R4G4B4 + // No DXGI format maps to ISBITMASK(0x0f00, 0x00f0, 0x000f, 0x0000) aka D3DFMT_X4R4G4B4 // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc. break; @@ -432,21 +435,21 @@ static DXGI_FORMAT GetDXGIFormat( const DDS_PIXELFORMAT& ddpf ) { if (8 == ddpf.RGBBitCount) { - if (ISBITMASK(0x000000ff,0x00000000,0x00000000,0x00000000)) + if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000)) { return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension } - // No DXGI format maps to ISBITMASK(0x0f,0x00,0x00,0xf0) aka D3DFMT_A4L4 + // No DXGI format maps to ISBITMASK(0x0f, 0x00, 0x00, 0xf0) aka D3DFMT_A4L4 } if (16 == ddpf.RGBBitCount) { - if (ISBITMASK(0x0000ffff,0x00000000,0x00000000,0x00000000)) + if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000)) { return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension } - if (ISBITMASK(0x000000ff,0x00000000,0x00000000,0x0000ff00)) + if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00)) { return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension } @@ -461,69 +464,69 @@ static DXGI_FORMAT GetDXGIFormat( const DDS_PIXELFORMAT& ddpf ) } else if (ddpf.flags & DDS_FOURCC) { - if (MAKEFOURCC( 'D', 'X', 'T', '1' ) == ddpf.fourCC) + if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC) { return DXGI_FORMAT_BC1_UNORM; } - if (MAKEFOURCC( 'D', 'X', 'T', '3' ) == ddpf.fourCC) + if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC) { return DXGI_FORMAT_BC2_UNORM; } - if (MAKEFOURCC( 'D', 'X', 'T', '5' ) == ddpf.fourCC) + if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC) { return DXGI_FORMAT_BC3_UNORM; } // While pre-mulitplied alpha isn't directly supported by the DXGI formats, // they are basically the same as these BC formats so they can be mapped - if (MAKEFOURCC( 'D', 'X', 'T', '2' ) == ddpf.fourCC) + if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC) { return DXGI_FORMAT_BC2_UNORM; } - if (MAKEFOURCC( 'D', 'X', 'T', '4' ) == ddpf.fourCC) + if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC) { return DXGI_FORMAT_BC3_UNORM; } - if (MAKEFOURCC( 'A', 'T', 'I', '1' ) == ddpf.fourCC) + if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC) { return DXGI_FORMAT_BC4_UNORM; } - if (MAKEFOURCC( 'B', 'C', '4', 'U' ) == ddpf.fourCC) + if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC) { return DXGI_FORMAT_BC4_UNORM; } - if (MAKEFOURCC( 'B', 'C', '4', 'S' ) == ddpf.fourCC) + if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC) { return DXGI_FORMAT_BC4_SNORM; } - if (MAKEFOURCC( 'A', 'T', 'I', '2' ) == ddpf.fourCC) + if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC) { return DXGI_FORMAT_BC5_UNORM; } - if (MAKEFOURCC( 'B', 'C', '5', 'U' ) == ddpf.fourCC) + if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC) { return DXGI_FORMAT_BC5_UNORM; } - if (MAKEFOURCC( 'B', 'C', '5', 'S' ) == ddpf.fourCC) + if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC) { return DXGI_FORMAT_BC5_SNORM; } // BC6H and BC7 are written using the "DX10" extended header - if (MAKEFOURCC( 'R', 'G', 'B', 'G' ) == ddpf.fourCC) + if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC) { return DXGI_FORMAT_R8G8_B8G8_UNORM; } - if (MAKEFOURCC( 'G', 'R', 'G', 'B' ) == ddpf.fourCC) + if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC) { return DXGI_FORMAT_G8R8_G8B8_UNORM; } // Check for D3DFORMAT enums being set here - switch( ddpf.fourCC ) + switch (ddpf.fourCC) { case 36: // D3DFMT_A16B16G16R16 return DXGI_FORMAT_R16G16B16A16_UNORM; @@ -556,23 +559,27 @@ static DXGI_FORMAT GetDXGIFormat( const DDS_PIXELFORMAT& ddpf ) //-------------------------------------------------------------------------------------- -static void FillInitData( _In_ size_t width, - _In_ size_t height, - _In_ size_t depth, - _In_ size_t mipCount, - _In_ size_t arraySize, - _In_ DXGI_FORMAT format, - _In_ size_t maxsize, - _In_ size_t bitSize, - _In_reads_bytes_(bitSize) const byte* bitData, - _Out_ size_t& twidth, - _Out_ size_t& theight, - _Out_ size_t& tdepth, - _Out_ size_t& skipMip, - _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData ) +static void FillInitData( + _In_ size_t width, + _In_ size_t height, + _In_ size_t depth, + _In_ size_t mipCount, + _In_ size_t arraySize, + _In_ DXGI_FORMAT format, + _In_ size_t maxsize, + _In_ size_t bitSize, + _In_reads_bytes_(bitSize) const byte* bitData, + _Out_ size_t& twidth, + _Out_ size_t& theight, + _Out_ size_t& tdepth, + _Out_ size_t& skipMip, + _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData + ) { - if ( !bitData || !initData ) + if (!bitData || !initData) + { throw ref new Platform::InvalidArgumentException(); + } skipMip = 0; twidth = 0; @@ -586,43 +593,39 @@ static void FillInitData( _In_ size_t width, const byte* pEndBits = bitData + bitSize; size_t index = 0; - for( size_t j = 0; j < arraySize; j++ ) + for (size_t j = 0; j < arraySize; j++) { size_t w = width; size_t h = height; size_t d = depth; - for( size_t i = 0; i < mipCount; i++ ) + for (size_t i = 0; i < mipCount; i++) { - GetSurfaceInfo( w, - h, - format, - &NumBytes, - &RowBytes, - &NumRows - ); - - if ( (mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize) ) + GetSurfaceInfo(w, h, format, &NumBytes, &RowBytes, &NumRows); + + if ((mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize)) { - if ( !twidth ) + if (!twidth) { twidth = w; theight = h; tdepth = d; } - initData[index].pSysMem = ( const void* )pSrcBits; - initData[index].SysMemPitch = static_cast( RowBytes ); - initData[index].SysMemSlicePitch = static_cast( NumBytes ); + initData[index].pSysMem = (const void*)pSrcBits; + initData[index].SysMemPitch = static_cast(RowBytes); + initData[index].SysMemSlicePitch = static_cast(NumBytes); ++index; } else + { ++skipMip; + } if (pSrcBits + (NumBytes*d) > pEndBits) { throw ref new Platform::OutOfBoundsException(); } - + pSrcBits += NumBytes * d; w = w >> 1; @@ -643,38 +646,44 @@ static void FillInitData( _In_ size_t width, } } - if ( !index ) + if (!index) + { throw ref new Platform::FailureException(); + } } //-------------------------------------------------------------------------------------- -static HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice, - _In_ uint32 resDim, - _In_ size_t width, - _In_ size_t height, - _In_ size_t depth, - _In_ size_t mipCount, - _In_ size_t arraySize, - _In_ DXGI_FORMAT format, - _In_ bool isCubeMap, - _In_reads_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData, - _Out_opt_ ID3D11Resource** texture, - _Out_opt_ ID3D11ShaderResourceView** textureView ) +static HRESULT CreateD3DResources( + _In_ ID3D11Device* d3dDevice, + _In_ uint32 resDim, + _In_ size_t width, + _In_ size_t height, + _In_ size_t depth, + _In_ size_t mipCount, + _In_ size_t arraySize, + _In_ DXGI_FORMAT format, + _In_ bool isCubeMap, + _In_reads_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData, + _Out_opt_ ID3D11Resource** texture, + _Out_opt_ ID3D11ShaderResourceView** textureView + ) { - if ( !d3dDevice || !initData ) + if (!d3dDevice || !initData) + { return E_INVALIDARG; + } HRESULT hr = E_FAIL; - switch ( resDim ) + switch (resDim) { case D3D11_RESOURCE_DIMENSION_TEXTURE1D: { D3D11_TEXTURE1D_DESC desc; - desc.Width = static_cast( width ); - desc.MipLevels = static_cast( mipCount ); - desc.ArraySize = static_cast( arraySize ); + desc.Width = static_cast(width); + desc.MipLevels = static_cast(mipCount); + desc.ArraySize = static_cast(arraySize); desc.Format = format; desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; @@ -682,23 +691,21 @@ static HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice, desc.MiscFlags = 0; ID3D11Texture1D* tex = nullptr; - hr = d3dDevice->CreateTexture1D( &desc, - initData, - &tex - ); - if (SUCCEEDED( hr ) && tex != 0) + hr = d3dDevice->CreateTexture1D(&desc, initData, &tex); + + if (SUCCEEDED(hr) && tex != 0) { if (textureView != 0) { D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; - memset( &SRVDesc, 0, sizeof( SRVDesc ) ); + memset(&SRVDesc, 0, sizeof(SRVDesc)); SRVDesc.Format = format; if (arraySize > 1) { SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1DARRAY; SRVDesc.Texture1DArray.MipLevels = desc.MipLevels; - SRVDesc.Texture1DArray.ArraySize = static_cast( arraySize ); + SRVDesc.Texture1DArray.ArraySize = static_cast(arraySize); } else { @@ -706,10 +713,13 @@ static HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice, SRVDesc.Texture1D.MipLevels = desc.MipLevels; } - hr = d3dDevice->CreateShaderResourceView( tex, - &SRVDesc, - textureView - ); + hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); + + if (FAILED(hr)) + { + tex->Release(); + return hr; + } } if (texture != 0) @@ -722,15 +732,15 @@ static HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice, } } } - break; + break; case D3D11_RESOURCE_DIMENSION_TEXTURE2D: { D3D11_TEXTURE2D_DESC desc; - desc.Width = static_cast( width ); - desc.Height = static_cast( height ); - desc.MipLevels = static_cast( mipCount ); - desc.ArraySize = static_cast( arraySize ); + desc.Width = static_cast(width); + desc.Height = static_cast(height); + desc.MipLevels = static_cast(mipCount); + desc.ArraySize = static_cast(arraySize); desc.Format = format; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; @@ -740,16 +750,14 @@ static HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice, desc.MiscFlags = (isCubeMap) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0; ID3D11Texture2D* tex = nullptr; - hr = d3dDevice->CreateTexture2D( &desc, - initData, - &tex - ); - if (SUCCEEDED( hr ) && tex != 0) + hr = d3dDevice->CreateTexture2D(&desc, initData, &tex); + + if (SUCCEEDED(hr) && tex != 0) { if (textureView != 0) { D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; - memset( &SRVDesc, 0, sizeof( SRVDesc ) ); + memset(&SRVDesc, 0, sizeof(SRVDesc)); SRVDesc.Format = format; if (isCubeMap) @@ -760,7 +768,7 @@ static HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice, SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels; // Earlier we set arraySize to (NumCubes * 6) - SRVDesc.TextureCubeArray.NumCubes = static_cast( arraySize / 6 ); + SRVDesc.TextureCubeArray.NumCubes = static_cast(arraySize / 6); } else { @@ -772,7 +780,7 @@ static HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice, { SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2DARRAY; SRVDesc.Texture2DArray.MipLevels = desc.MipLevels; - SRVDesc.Texture2DArray.ArraySize = static_cast( arraySize ); + SRVDesc.Texture2DArray.ArraySize = static_cast(arraySize); } else { @@ -780,10 +788,13 @@ static HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice, SRVDesc.Texture2D.MipLevels = desc.MipLevels; } - hr = d3dDevice->CreateShaderResourceView( tex, - &SRVDesc, - textureView - ); + hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); + + if (FAILED(hr)) + { + tex->Release(); + return hr; + } } if (texture != 0) @@ -801,10 +812,10 @@ static HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice, case D3D11_RESOURCE_DIMENSION_TEXTURE3D: { D3D11_TEXTURE3D_DESC desc; - desc.Width = static_cast( width ); - desc.Height = static_cast( height ); - desc.Depth = static_cast( depth ); - desc.MipLevels = static_cast( mipCount ); + desc.Width = static_cast(width); + desc.Height = static_cast(height); + desc.Depth = static_cast(depth); + desc.MipLevels = static_cast(mipCount); desc.Format = format; desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; @@ -812,24 +823,25 @@ static HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice, desc.MiscFlags = 0; ID3D11Texture3D* tex = nullptr; - hr = d3dDevice->CreateTexture3D( &desc, - initData, - &tex - ); - if (SUCCEEDED( hr ) && tex != 0) + hr = d3dDevice->CreateTexture3D(&desc, initData, &tex); + + if (SUCCEEDED(hr) && tex != 0) { if (textureView != 0) { D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; - memset( &SRVDesc, 0, sizeof( SRVDesc ) ); + memset(&SRVDesc, 0, sizeof(SRVDesc)); SRVDesc.Format = format; SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE3D; SRVDesc.Texture3D.MipLevels = desc.MipLevels; - hr = d3dDevice->CreateShaderResourceView( tex, - &SRVDesc, - textureView - ); + hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); + + if (FAILED(hr)) + { + tex->Release(); + return hr; + } } if (texture != 0) @@ -842,7 +854,7 @@ static HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice, } } } - break; + break; } return hr; @@ -850,13 +862,15 @@ static HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice, //-------------------------------------------------------------------------------------- -static void CreateTextureFromDDS( _In_ ID3D11Device* d3dDevice, - _In_ const DDS_HEADER* header, - _In_reads_bytes_(bitSize) const byte* bitData, - _In_ size_t bitSize, - _Out_opt_ ID3D11Resource** texture, - _Out_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize ) +static void CreateTextureFromDDS( + _In_ ID3D11Device* d3dDevice, + _In_ const DDS_HEADER* header, + _In_reads_bytes_(bitSize) const byte* bitData, + _In_ size_t bitSize, + _Out_opt_ ID3D11Resource** texture, + _Out_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize + ) { HRESULT hr = S_OK; @@ -876,9 +890,9 @@ static void CreateTextureFromDDS( _In_ ID3D11Device* d3dDevice, } if ((header->ddspf.flags & DDS_FOURCC) && - (MAKEFOURCC( 'D', 'X', '1', '0' ) == header->ddspf.fourCC )) + (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) { - const DDS_HEADER_DXT10* d3d10ext = reinterpret_cast( (const char*)header + sizeof(DDS_HEADER) ); + const DDS_HEADER_DXT10* d3d10ext = reinterpret_cast((const char*)header + sizeof(DDS_HEADER)); arraySize = d3d10ext->arraySize; if (arraySize == 0) @@ -886,14 +900,14 @@ static void CreateTextureFromDDS( _In_ ID3D11Device* d3dDevice, throw ref new Platform::FailureException(); } - if (BitsPerPixel( d3d10ext->dxgiFormat ) == 0) + if (BitsPerPixel(d3d10ext->dxgiFormat) == 0) { throw ref new Platform::FailureException(); } - + format = d3d10ext->dxgiFormat; - switch ( d3d10ext->resourceDimension ) + switch (d3d10ext->resourceDimension) { case D3D11_RESOURCE_DIMENSION_TEXTURE1D: // D3DX writes 1D textures with a fixed Height of 1 @@ -933,7 +947,7 @@ static void CreateTextureFromDDS( _In_ ID3D11Device* d3dDevice, } else { - format = GetDXGIFormat( header->ddspf ); + format = GetDXGIFormat(header->ddspf); if (format == DXGI_FORMAT_UNKNOWN) { @@ -944,12 +958,12 @@ static void CreateTextureFromDDS( _In_ ID3D11Device* d3dDevice, { resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D; } - else + else { if (header->caps2 & DDS_CUBEMAP) { // We require all six faces to be defined - if ((header->caps2 & DDS_CUBEMAP_ALLFACES ) != DDS_CUBEMAP_ALLFACES) + if ((header->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES) { return throw ref new Platform::FailureException(); } @@ -964,7 +978,7 @@ static void CreateTextureFromDDS( _In_ ID3D11Device* d3dDevice, // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture } - assert( BitsPerPixel( format ) != 0 ); + assert(BitsPerPixel(format) != 0); } // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements) @@ -973,11 +987,11 @@ static void CreateTextureFromDDS( _In_ ID3D11Device* d3dDevice, return throw ref new Platform::FailureException(); } - switch ( resDim ) + switch (resDim) { case D3D11_RESOURCE_DIMENSION_TEXTURE1D: if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) || - (width > D3D11_REQ_TEXTURE1D_U_DIMENSION) ) + (width > D3D11_REQ_TEXTURE1D_U_DIMENSION)) { return throw ref new Platform::FailureException(); } @@ -1006,7 +1020,7 @@ static void CreateTextureFromDDS( _In_ ID3D11Device* d3dDevice, if ((arraySize > 1) || (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) || - (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ) + (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION)) { return throw ref new Platform::FailureException(); } @@ -1014,65 +1028,65 @@ static void CreateTextureFromDDS( _In_ ID3D11Device* d3dDevice, } // Create the texture - std::unique_ptr initData( new D3D11_SUBRESOURCE_DATA[ mipCount * arraySize ] ); + std::unique_ptr initData(new D3D11_SUBRESOURCE_DATA[mipCount * arraySize]); size_t skipMip = 0; size_t twidth = 0; size_t theight = 0; size_t tdepth = 0; - FillInitData( width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, - twidth, theight, tdepth, skipMip, initData.get() ); + FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get()); - hr = CreateD3DResources( d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView ); + hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView); - if ( (hr == E_INVALIDARG) && !maxsize && (mipCount > 1) ) + if (FAILED(hr) && !maxsize && (mipCount > 1)) { // Retry with a maxsize determined by feature level - switch( d3dDevice->GetFeatureLevel() ) + switch (d3dDevice->GetFeatureLevel()) { case D3D_FEATURE_LEVEL_9_1: case D3D_FEATURE_LEVEL_9_2: if (isCubeMap) { - maxsize = 512 /*D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION*/; + maxsize = D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION; } else { maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) - ? 256 /*D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ - : 2048 /*D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION + : D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION; } break; case D3D_FEATURE_LEVEL_9_3: maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) - ? 256 /*D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ - : 4096 /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION + : D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION; break; default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1 maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D) - ? 2048 /*D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/ - : 8192 /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + ? D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION + : D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION; break; } - FillInitData( width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, - twidth, theight, tdepth, skipMip, initData.get() ); + FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get()); - hr = CreateD3DResources( d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView ); + hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData.get(), texture, textureView); } DX::ThrowIfFailed(hr); } //-------------------------------------------------------------------------------------- -void CreateDDSTextureFromMemory( _In_ ID3D11Device* d3dDevice, - _In_reads_bytes_(ddsDataSize) const byte* ddsData, - _In_ size_t ddsDataSize, - _Out_opt_ ID3D11Resource** texture, - _Out_opt_ ID3D11ShaderResourceView** textureView, - _In_ size_t maxsize ) +void CreateDDSTextureFromMemory( + _In_ ID3D11Device* d3dDevice, + _In_reads_bytes_(ddsDataSize) const byte* ddsData, + _In_ size_t ddsDataSize, + _Out_opt_ ID3D11Resource** texture, + _Out_opt_ ID3D11ShaderResourceView** textureView, + _In_ size_t maxsize + ) { if (!d3dDevice || !ddsData || (!texture && !textureView)) { @@ -1085,13 +1099,13 @@ void CreateDDSTextureFromMemory( _In_ ID3D11Device* d3dDevice, throw ref new Platform::FailureException(); } - uint32 dwMagicNumber = *( const uint32* )( ddsData ); + uint32 dwMagicNumber = *(const uint32*)(ddsData); if (dwMagicNumber != DDS_MAGIC) { throw ref new Platform::FailureException(); } - const DDS_HEADER* header = reinterpret_cast( ddsData + sizeof( uint32 ) ); + const DDS_HEADER* header = reinterpret_cast(ddsData + sizeof(uint32)); // Verify header to validate DDS file if (header->size != sizeof(DDS_HEADER) || @@ -1103,7 +1117,7 @@ void CreateDDSTextureFromMemory( _In_ ID3D11Device* d3dDevice, // Check for DX10 extension bool bDXT10Header = false; if ((header->ddspf.flags & DDS_FOURCC) && - (MAKEFOURCC( 'D', 'X', '1', '0' ) == header->ddspf.fourCC) ) + (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)) { // Must be long enough for both headers and magic value if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32) + sizeof(DDS_HEADER_DXT10))) @@ -1114,16 +1128,9 @@ void CreateDDSTextureFromMemory( _In_ ID3D11Device* d3dDevice, bDXT10Header = true; } - ptrdiff_t offset = sizeof( uint32 ) - + sizeof( DDS_HEADER ) - + (bDXT10Header ? sizeof( DDS_HEADER_DXT10 ) : 0); - - CreateTextureFromDDS( d3dDevice, - header, - ddsData + offset, - ddsDataSize - offset, - texture, - textureView, - maxsize - ); + ptrdiff_t offset = sizeof(uint32) + + sizeof(DDS_HEADER) + + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0); + + CreateTextureFromDDS(d3dDevice, header, ddsData + offset, ddsDataSize - offset, texture, textureView, maxsize); } diff --git a/ShootingGame/DirectXBase.cpp b/ShootingGame/DirectXBase.cpp index 9ff707a..4225a75 100644 --- a/ShootingGame/DirectXBase.cpp +++ b/ShootingGame/DirectXBase.cpp @@ -6,16 +6,18 @@ //// Copyright (c) Microsoft Corporation. All rights reserved #include "pch.h" -#include "DirectXBase.h" +#include "DirectXBase.h" using namespace Windows::UI::Core; using namespace Windows::Foundation; using namespace Microsoft::WRL; +using namespace Windows::Graphics::Display; using namespace D2D1; // Constructor. DirectXBase::DirectXBase() : - m_dpi(-1.0f) + m_dpi(-1.0f), + m_numBuffers(2) { } @@ -84,7 +86,7 @@ void DirectXBase::CreateDeviceResources() // Note the ordering should be preserved. // Don't forget to declare your application's minimum required feature level in its // description. All applications are assumed to support 9.1 unless otherwise stated. - D3D_FEATURE_LEVEL featureLevels[] = + D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, @@ -154,12 +156,12 @@ void DirectXBase::SetDpi(float dpi) { // Save the DPI of this display in our class. m_dpi = dpi; - + // Update Direct2D's stored DPI. m_d2dContext->SetDpi(m_dpi, m_dpi); - // Often a DPI change implies a window size change. In some cases Windows will issues - // both a size changed event and a DPI changed event. In this case, the resulting bounds + // Often a DPI change implies a window size change. In some cases Windows will issue + // both a size changed event and a DPI changed event. In this case, the resulting bounds // will not change, and the window resize code will only be executed once. UpdateForWindowSizeChange(); } @@ -168,6 +170,12 @@ void DirectXBase::SetDpi(float dpi) // This routine is called in the event handler for the view SizeChanged event. void DirectXBase::UpdateForWindowSizeChange() { + // Only handle window size changed if there is no pending DPI change. + if (m_dpi != DisplayProperties::LogicalDpi) + { + return; + } + if (m_window->Bounds.Width != m_windowBounds.Width || m_window->Bounds.Height != m_windowBounds.Height) { @@ -187,25 +195,24 @@ void DirectXBase::CreateWindowSizeDependentResources() m_windowBounds = m_window->Bounds; // If the swap chain already exists, resize it. - if(m_swapChain != nullptr) + if (m_swapChain != nullptr) { DX::ThrowIfFailed( - m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0) + m_swapChain->ResizeBuffers(m_numBuffers, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0) ); } - // Otherwise, create a new one. - else + else // Otherwise, create a new one. { // Allocate a descriptor. DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0}; swapChainDesc.Width = 0; // use automatic sizing swapChainDesc.Height = 0; swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // this is the most common swapchain format - swapChainDesc.Stereo = false; + swapChainDesc.Stereo = false; swapChainDesc.SampleDesc.Count = 1; // don't use multi-sampling swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - swapChainDesc.BufferCount = 2; // use double buffering to enable flip + swapChainDesc.BufferCount = m_numBuffers; // use multiple buffering to enable flip swapChainDesc.Scaling = DXGI_SCALING_NONE; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // all Metro style apps must use this SwapEffect swapChainDesc.Flags = 0; @@ -213,7 +220,7 @@ void DirectXBase::CreateWindowSizeDependentResources() // Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device // First, retrieve the underlying DXGI Device from the D3D Device. - ComPtr dxgiDevice; + ComPtr dxgiDevice; DX::ThrowIfFailed( m_d3dDevice.As(&dxgiDevice) ); @@ -231,23 +238,23 @@ void DirectXBase::CreateWindowSizeDependentResources() ); // Obtain the final swap chain for this window from the DXGI factory. + CoreWindow^ window = m_window.Get(); DX::ThrowIfFailed( dxgiFactory->CreateSwapChainForCoreWindow( m_d3dDevice.Get(), - reinterpret_cast(m_window), + reinterpret_cast(window), &swapChainDesc, nullptr, // allow on all displays &m_swapChain ) ); - // Ensure that DXGI does not queue more than one frame at a time. This both reduces - // latency and ensures that the application will only render after each VSync, minimizing + // Ensure that DXGI does not queue too many frames. This reduces latency and + // ensures that the application will only render after each VSync, minimizing // power consumption. DX::ThrowIfFailed( - dxgiDevice->SetMaximumFrameLatency(1) + dxgiDevice->SetMaximumFrameLatency(m_numBuffers - 1) ); - } // Obtain the backbuffer for this window which will be the final 3D rendertarget. @@ -273,7 +280,7 @@ void DirectXBase::CreateWindowSizeDependentResources() // Create a descriptor for the depth/stencil buffer. CD3D11_TEXTURE2D_DESC depthStencilDesc( - DXGI_FORMAT_D24_UNORM_S8_UINT, + DXGI_FORMAT_D24_UNORM_S8_UINT, backBufferDesc.Width, backBufferDesc.Height, 1, @@ -292,10 +299,11 @@ void DirectXBase::CreateWindowSizeDependentResources() ); // Create a DepthStencil view on this surface to use on bind. + auto viewDesc = CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D); DX::ThrowIfFailed( m_d3dDevice->CreateDepthStencilView( depthStencil.Get(), - &CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D), + &viewDesc, &m_depthStencilView ) ); @@ -311,10 +319,10 @@ void DirectXBase::CreateWindowSizeDependentResources() // Set the current viewport using the descriptor. m_d3dContext->RSSetViewports(1, &viewport); - // Now we set up the Direct2D render target bitmap linked to the swapchain. - // Whenever we render to this bitmap, it will be directly rendered to the + // Now we set up the Direct2D render target bitmap linked to the swapchain. + // Whenever we render to this bitmap, it will be directly rendered to the // swapchain associated with the window. - D2D1_BITMAP_PROPERTIES1 bitmapProperties = + D2D1_BITMAP_PROPERTIES1 bitmapProperties = BitmapProperties1( D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW, PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED), @@ -354,17 +362,17 @@ void DirectXBase::Present() parameters.pDirtyRects = nullptr; parameters.pScrollRect = nullptr; parameters.pScrollOffset = nullptr; - + // The first argument instructs DXGI to block until VSync, putting the application // to sleep until the next VSync. This ensures we don't waste any cycles rendering // frames that will never be displayed to the screen. HRESULT hr = m_swapChain->Present1(1, 0, ¶meters); - // If the device was removed either by a disconnect or a driver upgrade, we + // If the device was removed either by a disconnect or a driver upgrade, we // must completely reinitialize the renderer. if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) { - Initialize(m_window, m_dpi); + Initialize(m_window.Get(), m_dpi); } else { diff --git a/ShootingGame/DirectXBase.h b/ShootingGame/DirectXBase.h index adfa737..a881f65 100644 --- a/ShootingGame/DirectXBase.h +++ b/ShootingGame/DirectXBase.h @@ -9,12 +9,10 @@ #include "DirectXSample.h" -#pragma warning (disable: 4449) // warns that class is not consumable by JS because it is not sealed - // Helper class that initializes the DirectX APIs in the sample apps. -public ref class DirectXBase abstract +ref class DirectXBase abstract { -public: +internal: DirectXBase(); virtual void Initialize(Windows::UI::Core::CoreWindow^ window, float dpi); @@ -26,9 +24,8 @@ public: virtual void Render() = 0; virtual void Present(); -protected: - - Windows::UI::Core::CoreWindow^ m_window; +protected private: + Platform::Agile m_window; // Declare Direct2D Objects Microsoft::WRL::ComPtr m_d2dFactory; @@ -51,7 +48,5 @@ protected: Windows::Foundation::Size m_renderTargetSize; Windows::Foundation::Rect m_windowBounds; float m_dpi; + unsigned int m_numBuffers; }; - - -#pragma warning (default: 4449) diff --git a/ShootingGame/GameMain.cpp b/ShootingGame/GameMain.cpp index fa83dd7..144e94a 100644 --- a/ShootingGame/GameMain.cpp +++ b/ShootingGame/GameMain.cpp @@ -23,6 +23,7 @@ using namespace Windows::UI::Xaml::Controls; using namespace Windows::Graphics::Display; using namespace DirectX; using namespace D2D1; +using namespace concurrency; using namespace BasicSprites; @@ -33,23 +34,32 @@ const float GameMain::BACKBUFFER_HEIGHT = 240.0f; GameMain::GameMain() : backBufferViewPort_(0.0f,0.0f,BACKBUFFER_WIDTH,BACKBUFFER_HEIGHT) , isDestroy_(false) { - // ƒTƒEƒ“ƒhÄ¶ƒXƒŒƒbƒh‚ÌŠJŽn - soundThread_ = std::thread( - [this]() -> void - { - ExecuteSoundThread(); - } - ); + soundDriver_.reset(new sf::SoundDriver()); + soundManager_.reset(new sf::SoundManager(*soundDriver_.get())); + // ƒTƒEƒ“ƒhÄ¶ƒXƒŒƒbƒh‚ÌŠJŽn + soundTask_ = task(create_async([this]() + { + ExecuteSoundThread(); + }) + ); + //soundThread_ = std::thread( + // [this]() -> void + // { + // ExecuteSoundThread(); + // } + //); } GameMain::~GameMain() { // ƒTƒEƒ“ƒhÄ¶ƒXƒŒƒbƒh‚Ì’âŽ~ isDestroy_ = true; - if(soundThread_.joinable()) - { - soundThread_.join(); - } + soundTask_.wait(); + + //if(soundThread_.joinable()) + //{ + // soundThread_.join(); + //} }; void GameMain::CreateDeviceIndependentResources() @@ -632,9 +642,7 @@ float GameMain::RandFloat(float min, float max) // ƒTƒEƒ“ƒhÄ¶ƒXƒŒƒbƒh void GameMain::ExecuteSoundThread() { - sf::com_init comInit; - soundDriver_.reset(new sf::SoundDriver()); - soundManager_.reset(new sf::SoundManager(*soundDriver_.get())); + //sf::com_init comInit; InitSound(); soundManager_->Sequencer().Play(); while(!isDestroy_) @@ -773,8 +781,8 @@ void GameMain::InitSound() timber.filter.lfo.gain = 1.0f; timber.filter.lfo.waveForm = &(soundManager_->Synthesizer().WaveTables()[3]); timber.filter.lfo.startNoteOn = true; - timber.filter.cutoff = 50.0f; - timber.filter.resonance = 0.7f; + timber.filter.cutoff = 10000.0f; + timber.filter.resonance = 0.0f; timber.filter.envelope.attackTime = 0.01f; timber.filter.envelope.decayTime = 0.03f; timber.filter.envelope.sustainLevel = 0.05f; diff --git a/ShootingGame/GameMain.h b/ShootingGame/GameMain.h index f11e783..928f742 100644 --- a/ShootingGame/GameMain.h +++ b/ShootingGame/GameMain.h @@ -24,7 +24,7 @@ struct CharacterData ref class GameMain : public DirectXBase { -public: +internal: GameMain(); ~GameMain(); virtual void CreateDeviceIndependentResources() override; @@ -36,7 +36,7 @@ public: _In_ Windows::UI::Core::CoreWindow^ window, _In_ Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^ swapChainPanel, _In_ float dpi - ) new; + ) ;//new; void Update(float timeTotal, float timeDelta); @@ -65,5 +65,6 @@ private: Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^ panel_; std::unique_ptr soundManager_; std::unique_ptr soundDriver_; - std::thread soundThread_; + //std::thread soundThread_; + concurrency::task soundTask_; }; diff --git a/ShootingGame/SampleOverlay.h b/ShootingGame/SampleOverlay.h index b71f7e0..770633c 100644 --- a/ShootingGame/SampleOverlay.h +++ b/ShootingGame/SampleOverlay.h @@ -11,7 +11,7 @@ ref class SampleOverlay { -public: +internal: SampleOverlay(); void Initialize( diff --git a/ShootingGame/ShootingGame.vcxproj b/ShootingGame/ShootingGame.vcxproj index dfa5bb1..e4d7ece 100644 --- a/ShootingGame/ShootingGame.vcxproj +++ b/ShootingGame/ShootingGame.vcxproj @@ -78,11 +78,6 @@ - - - - - App.xaml @@ -103,9 +98,6 @@ Designer - - Designer - Designer @@ -114,7 +106,6 @@ Designer - @@ -136,11 +127,6 @@ - - - - - diff --git a/ShootingGame/SoundDriver.cpp b/ShootingGame/SoundDriver.cpp index 1b29526..b4e1421 100644 --- a/ShootingGame/SoundDriver.cpp +++ b/ShootingGame/SoundDriver.cpp @@ -11,6 +11,7 @@ using namespace Platform; #pragma comment(lib, "mmdevapi.lib") using namespace std::placeholders; +using namespace Microsoft::WRL; namespace { void makeWaveFormat(WAVEFORMATEXTENSIBLE& format, @@ -45,117 +46,253 @@ namespace { namespace sf { - - SoundDriver::SoundDriver() : bufferIndex_(0),eventHolder_(nullptr),processBuffer_(std::bind(&SoundDriver::DefaultProcessBuffer,this,_1,_2)),isStart_(false) + struct ActivateAudioInterfaceCompletionHandler + : public RuntimeClass< RuntimeClassFlags< ClassicCom >, FtmBase, IActivateAudioInterfaceCompletionHandler > { - //::AvMMAvSetMmThreadCharacteristics - String^ deviceID = MediaDevice::GetDefaultAudioRenderId(AudioDeviceRole::Default); - ActivateAudioInterface(deviceID->Data(),__uuidof(IAudioClient2),&audioClient_); - if(!audioClient_) + ActivateAudioInterfaceCompletionHandler() : + hr_(S_OK), + ptr_(nullptr), + eventHolder_(::CreateEventEx(NULL, NULL, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)) {}; + + ~ActivateAudioInterfaceCompletionHandler(){}; + + // IActivateAudioInterfaceCompletionHandler + STDMETHOD(ActivateCompleted)( IActivateAudioInterfaceAsyncOperation *operation ) + { + HRESULT hr = S_OK; + HRESULT hrActivateResult = S_OK; + IUnknown *punkAudioInterface = nullptr; + // Check for a successful activation result + hr = operation->GetActivateResult( &hrActivateResult, &punkAudioInterface ); + if(SUCCEEDED(hr)){ + if (SUCCEEDED( hrActivateResult )) + { + hr_ = S_OK; + // Get the pointer for the Audio Client + punkAudioInterface->QueryInterface( IID_PPV_ARGS(&ptr_) ); + if( nullptr == ptr_ ) + { + hr_ = E_FAIL; + ::SetEvent(eventHolder_.get()); + return hr_; + } + ::SetEvent(eventHolder_.get()); + } else { + hr_ = hr = hrActivateResult; + ::SetEvent(eventHolder_.get()); + } + } else { + hr_ = hr; + ::SetEvent(eventHolder_.get()); + } + return hr; + //operation + // concurrency::wait(0); + } + + void wait() { - throw AudioClientNullException(L"Šù’è‚ÌAudioClient‚ðƒAƒNƒeƒBƒx[ƒg‚Å‚«‚Ü‚¹‚ñ‚Å‚µ‚½B"); + ::WaitForSingleObjectEx(eventHolder_.get(),INFINITE,FALSE); } - // ƒI[ƒfƒBƒIƒtƒH[ƒ}ƒbƒg‚̃`ƒFƒbƒN - makeWaveFormat(format_); - //sf::co_task_memory mix_format; - //audioClient_->GetMixFormat(reinterpret_cast(&mix_format)); - // format_ = *mix_format.get(); - - sf::co_task_memory alt_format; - HRESULT hr = audioClient_->IsFormatSupported( - AUDCLNT_SHAREMODE_SHARED, - reinterpret_cast(&format_), - reinterpret_cast(&alt_format)); - int sample_rate_backup = 0; - if(hr == S_FALSE) // FALSE‚ÌŽž‚Í‚¨‚»‚ç‚­ƒTƒ“ƒvƒŠƒ“ƒOƒŒ[ƒg‚ªˆá‚¤ + HRESULT ResultCode() {return hr_;} + IAudioClient2Ptr AudioClient(){return ptr_;} + private: + HRESULT hr_; + sf::handle_holder eventHolder_; + IAudioClient2Ptr ptr_; + }; + + struct SoundDriver::impl + // : public RuntimeClass< RuntimeClassFlags< ClassicCom >, FtmBase, IActivateAudioInterfaceCompletionHandler > + { + + impl() : bufferIndex_(0),eventHolder_(nullptr),processBuffer_(std::bind(&SoundDriver::impl::DefaultProcessBuffer,this,_1,_2)),isStart_(false) { - // ƒTƒ“ƒvƒŠƒ“ƒOƒŒ[ƒg‚Ì‚Ý‚ªˆÙ‚È‚é‚©ƒ`ƒFƒbƒN‚·‚é - if( alt_format->Format.wFormatTag == format_.Format.wFormatTag && - alt_format->Format.nChannels == format_.Format.nChannels && - alt_format->Format.wBitsPerSample == format_.Format.wBitsPerSample && - alt_format->Samples.wValidBitsPerSample == format_.Samples.wValidBitsPerSample && - alt_format->Format.nSamplesPerSec != format_.Format.nSamplesPerSec - ) + //::AvMMAvSetMmThreadCharacteristics + String^ deviceID = MediaDevice::GetDefaultAudioRenderId(AudioDeviceRole::Default); + + { + ComPtr asyncOpPtr; + IActivateAudioInterfaceAsyncOperation* asyncOp; + ComPtr handler(Make()); + HRESULT hr = ActivateAudioInterfaceAsync(deviceID->Data(),__uuidof(IAudioClient2),nullptr,handler.Get(),&asyncOp); + asyncOpPtr.Attach(asyncOp); + if(SUCCEEDED(hr)){ + handler->wait(); + if(handler->ResultCode() == S_OK) + { + audioClient_ = handler->AudioClient(); + } else { + throw AudioClientNullException(L"Šù’è‚ÌAudioClient‚ðƒAƒNƒeƒBƒx[ƒg‚Å‚«‚Ü‚¹‚ñ‚Å‚µ‚½B"); + } + } else { + throw AudioClientNullException(L"Šù’è‚ÌAudioClient‚ðƒAƒNƒeƒBƒx[ƒg‚Å‚«‚Ü‚¹‚ñ‚Å‚µ‚½B"); + } + } + // ƒI[ƒfƒBƒIƒtƒH[ƒ}ƒbƒg‚̃`ƒFƒbƒN + makeWaveFormat(format_); + //sf::co_task_memory mix_format; + //audioClient_->GetMixFormat(reinterpret_cast(&mix_format)); + // format_ = *mix_format.get(); + + sf::co_task_memory alt_format; + HRESULT hr = audioClient_->IsFormatSupported( + AUDCLNT_SHAREMODE_SHARED, + reinterpret_cast(&format_), + reinterpret_cast(&alt_format)); + int sample_rate_backup = 0; + if(hr == S_FALSE) // FALSE‚ÌŽž‚Í‚¨‚»‚ç‚­ƒTƒ“ƒvƒŠƒ“ƒOƒŒ[ƒg‚ªˆá‚¤ + { + // ƒTƒ“ƒvƒŠƒ“ƒOƒŒ[ƒg‚Ì‚Ý‚ªˆÙ‚È‚é‚©ƒ`ƒFƒbƒN‚·‚é + if( alt_format->Format.wFormatTag == format_.Format.wFormatTag && + alt_format->Format.nChannels == format_.Format.nChannels && + alt_format->Format.wBitsPerSample == format_.Format.wBitsPerSample && + alt_format->Samples.wValidBitsPerSample == format_.Samples.wValidBitsPerSample && + alt_format->Format.nSamplesPerSec != format_.Format.nSamplesPerSec + ) + { + sample_rate_backup = format_.Format.nSamplesPerSec; + // ‘ã‘ÖƒtƒH[ƒ}ƒbƒg‚̃Tƒ“ƒvƒ‹ƒŒ[ƒg‚ðƒZƒbƒg‚·‚é + format_.Format.nSamplesPerSec = alt_format->Format.nSamplesPerSec; + // ÄŒvŽZ‚·‚é + format_.Format.nAvgBytesPerSec = alt_format->Format.nSamplesPerSec * format_.Format.nBlockAlign; + // ‚à‚¤ˆê‰ñƒ`ƒFƒbƒN‚·‚éB + // ƒTƒ“ƒvƒ‹ƒŒ[ƒgˆÈŠO‚ŃTƒ|[ƒg‚µ‚Ä‚¢‚È‚¢Ý’肪‚ ‚ê‚ΗáŠO‚ª”­¶‚·‚éB + alt_format.reset(); + ThrowIfErr(audioClient_->IsFormatSupported( + AUDCLNT_SHAREMODE_SHARED, + reinterpret_cast(&format_), + reinterpret_cast(&alt_format))); + } else { + throw AudioFormatNotSupportedException(L"‚±‚̃I[ƒfƒBƒIƒfƒoƒCƒX‚Őݒ肵‚Ä‚¢‚éƒtƒH[ƒ}ƒbƒg‚͑Ήž‚µ‚Ä‚¢‚Ü‚¹‚ñB"); + } + } + + // Audio Client‚̏‰Šú‰» + + REFERENCE_TIME defaultDevicePeriod,minDevicePriod; + audioClient_->GetDevicePeriod(&defaultDevicePeriod,&minDevicePriod); + hr = audioClient_->Initialize( + AUDCLNT_SHAREMODE_SHARED, + AUDCLNT_STREAMFLAGS_NOPERSIST | + AUDCLNT_STREAMFLAGS_EVENTCALLBACK , + minDevicePriod,0, + reinterpret_cast(&format_),NULL); + if(hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) { - sample_rate_backup = format_.Format.nSamplesPerSec; - // ‘ã‘ÖƒtƒH[ƒ}ƒbƒg‚̃Tƒ“ƒvƒ‹ƒŒ[ƒg‚ðƒZƒbƒg‚·‚é - format_.Format.nSamplesPerSec = alt_format->Format.nSamplesPerSec; - // ÄŒvŽZ‚·‚é - format_.Format.nAvgBytesPerSec = alt_format->Format.nSamplesPerSec * format_.Format.nBlockAlign; - // ‚à‚¤ˆê‰ñƒ`ƒFƒbƒN‚·‚éB - // ƒTƒ“ƒvƒ‹ƒŒ[ƒgˆÈŠO‚ŃTƒ|[ƒg‚µ‚Ä‚¢‚È‚¢Ý’肪‚ ‚ê‚ΗáŠO‚ª”­¶‚·‚éB - alt_format.reset(); - ThrowIfErr(audioClient_->IsFormatSupported( + ThrowIfErr(audioClient_->GetBufferSize(&bufferSize_)); + latency_ = (double)10000000 * (bufferSize_) / format_.Format.nSamplesPerSec; + audioClient_.Reset(); + + ComPtr asyncOp; + ActivateAudioInterfaceCompletionHandler handler; + HRESULT hr = ActivateAudioInterfaceAsync(deviceID->Data(),__uuidof(IAudioClient2),nullptr,&handler,&asyncOp); + if(SUCCEEDED(hr)){ + handler.wait(); + if(handler.ResultCode() == S_OK) + { + audioClient_ = handler.AudioClient(); + } else { + throw AudioClientNullException(L"Šù’è‚ÌAudioClient‚ðƒAƒNƒeƒBƒx[ƒg‚Å‚«‚Ü‚¹‚ñ‚Å‚µ‚½B"); + } + } else { + throw AudioClientNullException(L"Šù’è‚ÌAudioClient‚ðƒAƒNƒeƒBƒx[ƒg‚Å‚«‚Ü‚¹‚ñ‚Å‚µ‚½B"); + } + + ThrowIfErr(audioClient_->Initialize( AUDCLNT_SHAREMODE_SHARED, - reinterpret_cast(&format_), - reinterpret_cast(&alt_format))); + AUDCLNT_STREAMFLAGS_NOPERSIST | + AUDCLNT_STREAMFLAGS_EVENTCALLBACK , + latency_,0, + reinterpret_cast(&format_),NULL)); } else { - throw AudioFormatNotSupportedException(L"‚±‚̃I[ƒfƒBƒIƒfƒoƒCƒX‚Őݒ肵‚Ä‚¢‚éƒtƒH[ƒ}ƒbƒg‚͑Ήž‚µ‚Ä‚¢‚Ü‚¹‚ñB"); + ThrowIfErr(hr); } + + ThrowIfErr(audioClient_->GetBufferSize(&bufferSize_)); + + buffer_[0].reset((float*)_aligned_malloc( bufferSize_ * format_.Format.nBlockAlign,16)); + buffer_[1].reset((float*)_aligned_malloc( bufferSize_ * format_.Format.nBlockAlign,16)); + bufferByteCount_ = bufferSize_ * format_.Format.nBlockAlign; + + audioClient_->GetStreamLatency(&latency_); + ThrowIfErr(audioClient_->GetService(__uuidof(IAudioRenderClient),&audioRenderClient_)); + eventHolder_.reset(::CreateEventEx(NULL, NULL, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); + audioClient_->SetEventHandle(eventHolder_.get()); + + processBuffer_(buffer_[bufferIndex_],bufferSize_); + BYTE* rawBuffer; + ThrowIfErr(audioRenderClient_->GetBuffer(bufferSize_,&rawBuffer)); + audioRenderClient_->ReleaseBuffer(bufferSize_,0); + bufferIndex_ = (bufferIndex_ + 1) & 0x1; + processBuffer_(buffer_[bufferIndex_],bufferSize_); + + Start(); + + // ThrowIfErr(ActivateAudioInterfaceAsync(deviceID->Data(),__uuidof(IAudioClient2),nullptr,this,&asyncOp)); + } - // Audio Client‚̏‰Šú‰» - - REFERENCE_TIME defaultDevicePeriod,minDevicePriod; - audioClient_->GetDevicePeriod(&defaultDevicePeriod,&minDevicePriod); - hr = audioClient_->Initialize( - AUDCLNT_SHAREMODE_SHARED, - AUDCLNT_STREAMFLAGS_NOPERSIST | - AUDCLNT_STREAMFLAGS_EVENTCALLBACK , - minDevicePriod,0, - reinterpret_cast(&format_),NULL); - if(hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) + ~impl(){ + audioClient_->Stop(); + audioRenderClient_.Reset(); + audioClient_->Reset(); + }; + void Render() { - ThrowIfErr(audioClient_->GetBufferSize(&bufferSize_)); - latency_ = (double)10000000 * (bufferSize_) / format_.Format.nSamplesPerSec; - audioClient_.Reset(); - ActivateAudioInterface(deviceID->Data(),__uuidof(IAudioClient2),&audioClient_); - if(!audioClient_) + ::WaitForSingleObjectEx(eventHolder_.get(),INFINITE,FALSE); + uint32_t padding; + ThrowIfErr(audioClient_->GetCurrentPadding(&padding)); + if(!padding) { - throw AudioClientNullException(L"Šù’è‚ÌAudioClient‚ðƒAƒNƒeƒBƒx[ƒg‚Å‚«‚Ü‚¹‚ñ‚Å‚µ‚½B"); + BYTE* rawBuffer; + ThrowIfErr(audioRenderClient_->GetBuffer(bufferSize_,&rawBuffer)); + ::memcpy(rawBuffer,buffer_[bufferIndex_].get(),bufferByteCount_); + audioRenderClient_->ReleaseBuffer(bufferSize_,0); + bufferIndex_ = (bufferIndex_ + 1) & 0x1; + processBuffer_(buffer_[bufferIndex_],bufferSize_); } - ThrowIfErr(audioClient_->Initialize( - AUDCLNT_SHAREMODE_SHARED, - AUDCLNT_STREAMFLAGS_NOPERSIST | - AUDCLNT_STREAMFLAGS_EVENTCALLBACK , - latency_,0, - reinterpret_cast(&format_),NULL)); - } else { - ThrowIfErr(hr); } - ThrowIfErr(audioClient_->GetBufferSize(&bufferSize_)); - - buffer_[0].reset((float*)_aligned_malloc( bufferSize_ * format_.Format.nBlockAlign,16)); - buffer_[1].reset((float*)_aligned_malloc( bufferSize_ * format_.Format.nBlockAlign,16)); - bufferByteCount_ = bufferSize_ * format_.Format.nBlockAlign; - - audioClient_->GetStreamLatency(&latency_); - ThrowIfErr(audioClient_->GetService(__uuidof(IAudioRenderClient),&audioRenderClient_)); - eventHolder_.reset(::CreateEventEx(NULL, NULL, 0, EVENT_MODIFY_STATE | SYNCHRONIZE)); - audioClient_->SetEventHandle(eventHolder_.get()); - - processBuffer_(buffer_[bufferIndex_],bufferSize_); - BYTE* rawBuffer; - ThrowIfErr(audioRenderClient_->GetBuffer(bufferSize_,&rawBuffer)); - audioRenderClient_->ReleaseBuffer(bufferSize_,0); - bufferIndex_ = (bufferIndex_ + 1) & 0x1; - processBuffer_(buffer_[bufferIndex_],bufferSize_); - - Start(); - - } + void SetProcessBufferFunc(ProcessBufferType&& v) + { + Stop(); + processBuffer_ = std::move(v); + Start(); + } + void ResetProcessBufferFunc() + { + Stop(); + processBuffer_ = std::move(std::bind(&SoundDriver::impl::DefaultProcessBuffer,this,_1,_2)); + Start(); + } - SoundDriver::~SoundDriver() - { - audioClient_->Stop(); - audioRenderClient_.Reset(); - audioClient_->Reset(); - } + void Start() + { + if(isStart_) return; - void SoundDriver::DefaultProcessBuffer(boost::shared_array arr,int bufferSize) - { + ThrowIfErr(audioClient_->Start()); + + isStart_ = true; + } + + void Stop() + { + if(!isStart_) return; + + ThrowIfErr(audioClient_->Stop()); + + isStart_ = false; + } + + WAVEFORMATEXTENSIBLE& Format() + { + return format_; + } + + void DefaultProcessBuffer(boost::shared_array arr,int bufferSize) + { // ¡‚Ì‚Æ‚±‚ëo—͂̓XƒeƒŒƒI‘O’ñ //for(int j = 0;j < voices_.size();++j) //{ @@ -173,59 +310,76 @@ namespace sf { // synth_->Process(ptr); // ptr += 2; //} + } + + // IActivateAudioInterfaceCompletionHandler + STDMETHOD(ActivateCompleted)( IActivateAudioInterfaceAsyncOperation *operation ) + { + try { + if(!audioClient_) + { + throw AudioClientNullException(L"Šù’è‚ÌAudioClient‚ðƒAƒNƒeƒBƒx[ƒg‚Å‚«‚Ü‚¹‚ñ‚Å‚µ‚½B"); + } + + + } catch (...) + { + return E_FAIL; + } + return S_OK; + } + + private: + ProcessBufferType processBuffer_; + IAudioClient2Ptr audioClient_; + uint32_t bufferSize_; + REFERENCE_TIME latency_; + // IAudioClockAdjustmentPtr audioClockAdjustment_; + IAudioRenderClientPtr audioRenderClient_; + WAVEFORMATEXTENSIBLE format_; + sf::handle_holder eventHolder_; + boost::shared_array buffer_[2]; + int bufferIndex_; + int bufferByteCount_; + bool isStart_; + + }; + + SoundDriver::SoundDriver() : impl_(new impl()) {} + + SoundDriver::~SoundDriver() + { + impl_.reset(); } void SoundDriver::Render() { - ::WaitForSingleObjectEx(eventHolder_.get(),INFINITE,FALSE); - uint32_t padding; - ThrowIfErr(audioClient_->GetCurrentPadding(&padding)); - if(!padding) - { - BYTE* rawBuffer; - ThrowIfErr(audioRenderClient_->GetBuffer(bufferSize_,&rawBuffer)); - ::memcpy(rawBuffer,buffer_[bufferIndex_].get(),bufferByteCount_); - audioRenderClient_->ReleaseBuffer(bufferSize_,0); - bufferIndex_ = (bufferIndex_ + 1) & 0x1; - processBuffer_(buffer_[bufferIndex_],bufferSize_); - } + impl_->Render(); } void SoundDriver::SetProcessBufferFunc(ProcessBufferType&& v) { - Stop(); - processBuffer_ = std::move(v); - Start(); + impl_->SetProcessBufferFunc(std::move(v)); } void SoundDriver::ResetProcessBufferFunc() { - Stop(); - processBuffer_ = std::move(std::bind(&SoundDriver::DefaultProcessBuffer,this,_1,_2)); - Start(); + impl_->ResetProcessBufferFunc(); } void SoundDriver::Start() { - if(isStart_) return; - - ThrowIfErr(audioClient_->Start()); - - isStart_ = true; + impl_->Start(); } void SoundDriver::Stop() { - if(!isStart_) return; - - ThrowIfErr(audioClient_->Stop()); - - isStart_ = false; + impl_->Stop(); } WAVEFORMATEXTENSIBLE& SoundDriver::Format() { - return format_; + return impl_->Format(); } } diff --git a/ShootingGame/SoundDriver.h b/ShootingGame/SoundDriver.h index b071c57..12dc044 100644 --- a/ShootingGame/SoundDriver.h +++ b/ShootingGame/SoundDriver.h @@ -29,18 +29,8 @@ namespace sf { void ResetProcessBufferFunc(); WAVEFORMATEXTENSIBLE& Format(); private: - ProcessBufferType processBuffer_; - IAudioClient2Ptr audioClient_; - uint32_t bufferSize_; - REFERENCE_TIME latency_; - // IAudioClockAdjustmentPtr audioClockAdjustment_; - IAudioRenderClientPtr audioRenderClient_; - WAVEFORMATEXTENSIBLE format_; - sf::handle_holder eventHolder_; - boost::shared_array buffer_[2]; - int bufferIndex_; - int bufferByteCount_; - bool isStart_; + struct impl; + std::unique_ptr impl_; }; } diff --git a/ShootingGame/TestSong.cpp b/ShootingGame/TestSong.cpp index 8110cbf..0560f68 100644 --- a/ShootingGame/TestSong.cpp +++ b/ShootingGame/TestSong.cpp @@ -32,7 +32,9 @@ namespace sf { } //CreateTestTone(); - //CreateMappyData(); + /* for(int i = 0;i < 5;++i){ + CreateMappyData(); + }*/ CreateCosmicSurfin(); diff --git a/ShootingGame/pch.h b/ShootingGame/pch.h index 9f8e61e..5a828be 100644 --- a/ShootingGame/pch.h +++ b/ShootingGame/pch.h @@ -11,6 +11,7 @@ #include #include #include +#include #include #include -- 2.11.0