├── Media ├── UI │ └── Font.dds └── sph_shader.fx ├── DXUT ├── Core │ ├── ScreenGrab.cpp │ ├── CMakeLists.txt │ ├── ScreenGrab.h │ ├── dxerr.h │ ├── WICTextureLoader.h │ ├── DDSTextureLoader.h │ ├── DXUTDevice11.h │ ├── DXUTmisc.h │ ├── DXUT.h │ └── WICTextureLoader.cpp ├── Optional │ ├── directx.ico │ ├── DXUTres.h │ ├── CMakeLists.txt │ ├── ImeUi.h │ ├── SDKmisc.h │ ├── DXUTguiIME.h │ ├── DXUTsettingsdlg.h │ ├── DXUTLockFreePipe.h │ ├── SDKmesh.h │ └── DXUTcamera.h ├── CMakeLists.txt └── ReadMe.txt ├── libsph ├── sph_fluid_system.h ├── sph_point_buffer.h ├── sph_fluid_system.cpp ├── sph_stdafx.cpp ├── sph_stdafx.h ├── sph_interface.h ├── CMakeLists.txt ├── sph_grid_container.h ├── sph_neighbor_table.h ├── sph_point_buffer.cpp ├── sph_math.h ├── sph_neighbor_table.cpp └── sph_grid_container.cpp ├── README.md ├── CMakeLists.txt └── sph ├── CMakeLists.txt └── sph_main.cpp /Media/UI/Font.dds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thejinchao/fluid/HEAD/Media/UI/Font.dds -------------------------------------------------------------------------------- /DXUT/Core/ScreenGrab.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thejinchao/fluid/HEAD/DXUT/Core/ScreenGrab.cpp -------------------------------------------------------------------------------- /DXUT/Optional/directx.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thejinchao/fluid/HEAD/DXUT/Optional/directx.ico -------------------------------------------------------------------------------- /libsph/sph_fluid_system.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thejinchao/fluid/HEAD/libsph/sph_fluid_system.h -------------------------------------------------------------------------------- /libsph/sph_point_buffer.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thejinchao/fluid/HEAD/libsph/sph_point_buffer.h -------------------------------------------------------------------------------- /libsph/sph_fluid_system.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thejinchao/fluid/HEAD/libsph/sph_fluid_system.cpp -------------------------------------------------------------------------------- /DXUT/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | #Copyright(C) thecodeway.com 3 | # 4 | 5 | add_subdirectory(Core) 6 | add_subdirectory(Optional) 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | fluid 2 | ===== 3 | 4 | souce code for the my blog(http://thecodeway.com/blog/?p=204) 5 | 6 | 7 | -------------------------------------------------------------------------------- /libsph/sph_stdafx.cpp: -------------------------------------------------------------------------------- 1 | // stdafx.cpp : source file that includes just the standard includes 2 | // libWorld.pch will be the pre-compiled header 3 | // stdafx.obj will contain the pre-compiled type information 4 | 5 | #include "sph_stdafx.h" 6 | 7 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | #Copyright(C) thecodeway.com 3 | # 4 | 5 | cmake_minimum_required (VERSION 2.8) 6 | project(fluid) 7 | 8 | add_definitions(-DUNICODE -D_UNICODE) 9 | 10 | set_property(GLOBAL PROPERTY USE_FOLDERS ON) 11 | add_subdirectory(libsph) 12 | add_subdirectory(DXUT) 13 | add_subdirectory(sph) 14 | -------------------------------------------------------------------------------- /sph/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | #Copyright(C) thecodeway.com 3 | # 4 | 5 | include_directories( 6 | ../DXUT/Core 7 | ../DXUT/Optional 8 | ../Effects11/inc 9 | ../libsph 10 | ) 11 | 12 | add_definitions(-DUSE_DIRECT3D11_2) 13 | 14 | add_executable(sph WIN32 15 | sph_main.cpp 16 | ) 17 | 18 | target_link_libraries(sph 19 | libsph 20 | DXUT_Core 21 | DXUT_Optional 22 | d3dcompiler.lib 23 | usp10.lib 24 | dxguid.lib 25 | winmm.lib 26 | comctl32.lib 27 | ) 28 | -------------------------------------------------------------------------------- /DXUT/Core/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | #Copyright(C) thecodeway.com 3 | # 4 | 5 | add_library(DXUT_Core 6 | DDSTextureLoader.cpp 7 | DDSTextureLoader.h 8 | dxerr.cpp 9 | dxerr.h 10 | DXUT.cpp 11 | DXUT.h 12 | DXUTDevice11.cpp 13 | DXUTDevice11.h 14 | DXUTmisc.cpp 15 | DXUTmisc.h 16 | ScreenGrab.cpp 17 | ScreenGrab.h 18 | WICTextureLoader.cpp 19 | WICTextureLoader.h 20 | ) 21 | -------------------------------------------------------------------------------- /DXUT/Optional/DXUTres.h: -------------------------------------------------------------------------------- 1 | //---------------------------------------------------------------------------- 2 | // File: dxutres.h 3 | // 4 | // Functions to create DXUT media from arrays in memory 5 | // 6 | // Copyright (c) Microsoft Corporation. All rights reserved. 7 | // Licensed under the MIT License. 8 | // 9 | // http://go.microsoft.com/fwlink/?LinkId=320437 10 | //----------------------------------------------------------------------------- 11 | #pragma once 12 | 13 | HRESULT WINAPI DXUTCreateGUITextureFromInternalArray( _In_ ID3D11Device* pd3dDevice, _Outptr_ ID3D11Texture2D** ppTexture ); 14 | -------------------------------------------------------------------------------- /libsph/sph_stdafx.h: -------------------------------------------------------------------------------- 1 | // stdafx.h : include file for standard system include files, 2 | // or project specific include files that are used frequently, but 3 | // are changed infrequently 4 | // 5 | 6 | #pragma once 7 | 8 | // C Runtime library 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | // CPP Runtime library 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #include "sph_interface.h" 26 | -------------------------------------------------------------------------------- /DXUT/Optional/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | #Copyright(C) thecodeway.com 3 | # 4 | 5 | include_directories( 6 | ../Core 7 | ) 8 | 9 | add_library(DXUT_Optional 10 | DXUTcamera.cpp 11 | DXUTcamera.h 12 | DXUTgui.cpp 13 | DXUTgui.h 14 | DXUTguiIME.cpp 15 | DXUTguiIME.h 16 | DXUTLockFreePipe.h 17 | DXUTres.cpp 18 | DXUTres.h 19 | DXUTsettingsdlg.cpp 20 | DXUTsettingsdlg.h 21 | ImeUi.cpp 22 | ImeUi.h 23 | SDKmesh.cpp 24 | SDKmesh.h 25 | SDKmisc.cpp 26 | SDKmisc.h 27 | ) 28 | -------------------------------------------------------------------------------- /libsph/sph_interface.h: -------------------------------------------------------------------------------- 1 | #ifndef __LIB_SPH_INTERFACE_H__ 2 | #define __LIB_SPH_INTERFACE_H__ 3 | 4 | 5 | namespace SPH 6 | { 7 | 8 | struct float_3 9 | { 10 | float x, y, z; 11 | }; 12 | 13 | class System 14 | { 15 | public: 16 | virtual void init(unsigned short maxPointCounts, 17 | const float_3* wallBox_min, const float_3* wallBox_max, 18 | const float_3* initFluidBox_min, const float_3* initFluidBox_max, 19 | const float_3* gravity) = 0; 20 | 21 | virtual unsigned int getPointStride(void) const = 0; 22 | virtual unsigned int getPointCounts(void) const = 0; 23 | virtual const float_3* getPointBuf(void) const = 0; 24 | virtual void tick(void) = 0; 25 | }; 26 | 27 | } 28 | 29 | extern "C" 30 | { 31 | 32 | /** Get the sigleton SPH System point 33 | */ 34 | SPH::System * getSPHSystem(void); 35 | 36 | }; 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /libsph/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 2 | #Copyright(C) thecodeway.com 3 | # 4 | 5 | set(LIBSPH_SOURCE_CPP 6 | sph_fluid_system.cpp 7 | sph_grid_container.cpp 8 | sph_neighbor_table.cpp 9 | sph_point_buffer.cpp 10 | ) 11 | 12 | set(LIBSPH_SOURCE_H 13 | sph_fluid_system.h 14 | sph_grid_container.h 15 | sph_interface.h 16 | sph_math.h 17 | sph_neighbor_table.h 18 | sph_point_buffer.h 19 | sph_stdafx.h 20 | ) 21 | 22 | set(LIBSPH_SOURCE_CPP_PRECOMPILED 23 | sph_stdafx.cpp 24 | ) 25 | 26 | if(MSVC) 27 | foreach(src_file ${LIBSPH_SOURCE_CPP}) 28 | set_source_files_properties( 29 | ${src_file} 30 | PROPERTIES 31 | COMPILE_FLAGS "/Yusph_stdafx.h" 32 | ) 33 | endforeach() 34 | 35 | set_source_files_properties(${LIBSPH_SOURCE_CPP_PRECOMPILED} 36 | PROPERTIES 37 | COMPILE_FLAGS "/Ycsph_stdafx.h" 38 | ) 39 | endif() 40 | 41 | add_library(libsph 42 | ${LIBSPH_SOURCE_CPP_PRECOMPILED} 43 | ${LIBSPH_SOURCE_CPP} 44 | ${LIBSPH_SOURCE_H} 45 | ) 46 | 47 | -------------------------------------------------------------------------------- /Media/sph_shader.fx: -------------------------------------------------------------------------------- 1 | 2 | cbuffer cbChangesEveryFrame : register( b0 ) 3 | { 4 | matrix WorldViewProj; 5 | }; 6 | 7 | 8 | //-------------------------------------------------------------------------------------- 9 | struct VS_INPUT 10 | { 11 | float4 Pos : POSITION; 12 | float4 Col : COLOR; 13 | }; 14 | 15 | struct PS_INPUT 16 | { 17 | float4 Pos : SV_POSITION; 18 | float4 Col : COLOR; 19 | }; 20 | 21 | 22 | //-------------------------------------------------------------------------------------- 23 | // Vertex Shader 24 | //-------------------------------------------------------------------------------------- 25 | PS_INPUT MainVS( VS_INPUT input ) 26 | { 27 | PS_INPUT output = (PS_INPUT)0; 28 | output.Pos = mul( input.Pos, WorldViewProj ); 29 | output.Col = input.Col; 30 | 31 | return output; 32 | } 33 | 34 | 35 | //-------------------------------------------------------------------------------------- 36 | // Pixel Shader 37 | //-------------------------------------------------------------------------------------- 38 | float4 MainPS( PS_INPUT input) : SV_Target 39 | { 40 | float4 output = input.Col; 41 | return output; 42 | } 43 | -------------------------------------------------------------------------------- /libsph/sph_grid_container.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "sph_math.h" 4 | 5 | namespace SPH 6 | { 7 | 8 | class PointBuffer; 9 | 10 | class GridContainer 11 | { 12 | public: 13 | // Spatial Subdivision 14 | void init(const fBox3& box, float sim_scale, float cell_size, float border); 15 | void insertParticles(PointBuffer* pointBuffer); 16 | void findCells(const fVector3& p, float radius, int* gridCell); 17 | int findCell(const fVector3& p); 18 | int getGridData(int gridIndex); 19 | 20 | const iVector3* getGridRes(void) const { return &m_GridRes; } 21 | const fVector3* getGridMin(void) const { return &m_GridMin; } 22 | const fVector3* getGridMax(void) const { return &m_GridMax; } 23 | const fVector3* getGridSize(void) const { return &m_GridSize; } 24 | 25 | int getGridCellIndex(float px, float py, float pz); 26 | 27 | private: 28 | // Spatial Grid 29 | std::vector< int > m_gridData; 30 | fVector3 m_GridMin; // volume of grid (may not match domain volume exactly) 31 | fVector3 m_GridMax; 32 | iVector3 m_GridRes; // resolution in each axis 33 | fVector3 m_GridSize; // physical size in each axis 34 | fVector3 m_GridDelta; 35 | float m_GridCellsize; 36 | 37 | public: 38 | GridContainer(); 39 | ~GridContainer(); 40 | }; 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /DXUT/Core/ScreenGrab.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: ScreenGrab.h 3 | // 4 | // Function for capturing a 2D texture and saving it to a file (aka a 'screenshot' 5 | // when used on a Direct3D 11 Render Target). 6 | // 7 | // Note these functions are useful as a light-weight runtime screen grabber. For 8 | // full-featured texture capture, DDS writer, and texture processing pipeline, 9 | // see the 'Texconv' sample and the 'DirectXTex' library. 10 | // 11 | // Copyright (c) Microsoft Corporation. All rights reserved. 12 | // Licensed under the MIT License. 13 | // 14 | // http://go.microsoft.com/fwlink/?LinkId=248926 15 | // http://go.microsoft.com/fwlink/?LinkId=248929 16 | //-------------------------------------------------------------------------------------- 17 | 18 | #pragma once 19 | 20 | #include 21 | 22 | #include 23 | #include 24 | #include 25 | 26 | 27 | namespace DirectX 28 | { 29 | HRESULT SaveDDSTextureToFile( _In_ ID3D11DeviceContext* pContext, 30 | _In_ ID3D11Resource* pSource, 31 | _In_z_ const wchar_t* fileName ); 32 | 33 | HRESULT SaveWICTextureToFile( _In_ ID3D11DeviceContext* pContext, 34 | _In_ ID3D11Resource* pSource, 35 | _In_ REFGUID guidContainerFormat, 36 | _In_z_ const wchar_t* fileName, 37 | _In_opt_ const GUID* targetFormat = nullptr, 38 | _In_opt_ std::function setCustomProps = nullptr ); 39 | } -------------------------------------------------------------------------------- /libsph/sph_neighbor_table.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace SPH 4 | { 5 | 6 | class NeighborTable 7 | { 8 | public: 9 | /** reset neighbor table */ 10 | void reset(unsigned short pointCounts); 11 | /** prepare a point neighbor data */ 12 | void point_prepare(unsigned short ptIndex); 13 | /** add neighbor data to current point */ 14 | bool point_add_neighbor(unsigned short ptIndex, float distance); 15 | /** commit point neighbor data to data buf*/ 16 | void point_commit(void); 17 | /** get point neighbor counts */ 18 | int getNeighborCounts(unsigned short ptIndex) { return m_pointExtraData[ptIndex].neighborCounts; } 19 | /** get point neightbor information*/ 20 | void getNeighborInfo(unsigned short ptIndex, int index, unsigned short& neighborIndex, float& neighborDistance); 21 | 22 | private: 23 | enum {MAX_NEIGHTBOR_COUNTS=80,}; 24 | 25 | union PointExtraData 26 | { 27 | struct 28 | { 29 | unsigned neighborDataOffset : 24; 30 | unsigned neighborCounts : 8; 31 | }; 32 | 33 | unsigned int neighborData; 34 | }; 35 | 36 | PointExtraData* m_pointExtraData; 37 | unsigned int m_pointCounts; 38 | unsigned int m_pointCapcity; 39 | 40 | unsigned char* m_neighborDataBuf; //neighbor data buf 41 | unsigned int m_dataBufSize; //in bytes 42 | unsigned int m_dataBufOffset; //current neighbor data buf offset 43 | 44 | ////// temp data for current point 45 | unsigned short m_currPoint; 46 | int m_currNeighborCounts; 47 | unsigned short m_currNeightborIndex[MAX_NEIGHTBOR_COUNTS]; 48 | float m_currNeighborDistance[MAX_NEIGHTBOR_COUNTS]; 49 | 50 | private: 51 | void _growDataBuf(unsigned int need_size); 52 | 53 | public: 54 | NeighborTable(); 55 | ~NeighborTable(); 56 | }; 57 | 58 | } 59 | -------------------------------------------------------------------------------- /libsph/sph_point_buffer.cpp: -------------------------------------------------------------------------------- 1 | #include "sph_stdafx.h" 2 | #include "sph_point_buffer.h" 3 | 4 | namespace SPH 5 | { 6 | //----------------------------------------------------------------------------------------------------------------- 7 | PointBuffer::PointBuffer() 8 | : mFluidBuf(0) 9 | , mFluidCounts(0) 10 | , mBufCapcity(0) 11 | { 12 | } 13 | 14 | //----------------------------------------------------------------------------------------------------------------- 15 | PointBuffer::~PointBuffer() 16 | { 17 | free(mFluidBuf); 18 | mFluidBuf=0; 19 | } 20 | 21 | //----------------------------------------------------------------------------------------------------------------- 22 | void PointBuffer::reset(unsigned int capcity) 23 | { 24 | mBufCapcity = capcity; 25 | if(mFluidBuf != 0) 26 | { 27 | free(mFluidBuf); 28 | mFluidBuf = 0; 29 | } 30 | 31 | if(mBufCapcity>0) 32 | { 33 | mFluidBuf = (Point*)malloc(mBufCapcity* sizeof(Point)); 34 | } 35 | mFluidCounts = 0; 36 | } 37 | 38 | //----------------------------------------------------------------------------------------------------------------- 39 | Point* PointBuffer::AddPointReuse(void) 40 | { 41 | if(mFluidCounts >= mBufCapcity) 42 | { 43 | if(mBufCapcity*2>ELEM_MAX) 44 | { 45 | //get a random point 46 | unsigned int index = rand()%mFluidCounts; 47 | return mFluidBuf+index; 48 | } 49 | 50 | //realloc point buff 51 | mBufCapcity *= 2; 52 | Point* new_data = (Point*)malloc(mBufCapcity* sizeof(Point)); 53 | memcpy(new_data, mFluidBuf, mFluidCounts*sizeof(Point) ); 54 | free(mFluidBuf); 55 | mFluidBuf = new_data; 56 | } 57 | 58 | //a new point 59 | Point* point = mFluidBuf + (mFluidCounts++); 60 | 61 | point->pos.set(0, 0, 0); 62 | point->next = 0; 63 | point->velocity.set(0,0,0); 64 | point->velocity_eval.set(0,0,0); 65 | point->pressure = 0; 66 | point->density = 0; 67 | point->accel.set(0,0,0); 68 | return point; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /DXUT/Core/dxerr.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: DXErr.h 3 | // 4 | // DirectX Error Library 5 | // 6 | // Copyright (c) Microsoft Corporation. All rights reserved. 7 | // Licensed under the MIT License. 8 | //-------------------------------------------------------------------------------------- 9 | 10 | // This version only supports UNICODE. 11 | 12 | #pragma once 13 | 14 | #include 15 | #include 16 | 17 | #ifdef __cplusplus 18 | extern "C" { 19 | #endif 20 | 21 | //-------------------------------------------------------------------------------------- 22 | // DXGetErrorString 23 | //-------------------------------------------------------------------------------------- 24 | const WCHAR* WINAPI DXGetErrorStringW( _In_ HRESULT hr ); 25 | 26 | #define DXGetErrorString DXGetErrorStringW 27 | 28 | //-------------------------------------------------------------------------------------- 29 | // DXGetErrorDescription has to be modified to return a copy in a buffer rather than 30 | // the original static string. 31 | //-------------------------------------------------------------------------------------- 32 | void WINAPI DXGetErrorDescriptionW( _In_ HRESULT hr, _Out_cap_(count) WCHAR* desc, _In_ size_t count ); 33 | 34 | #define DXGetErrorDescription DXGetErrorDescriptionW 35 | 36 | //-------------------------------------------------------------------------------------- 37 | // DXTrace 38 | // 39 | // Desc: Outputs a formatted error message to the debug stream 40 | // 41 | // Args: WCHAR* strFile The current file, typically passed in using the 42 | // __FILEW__ macro. 43 | // DWORD dwLine The current line number, typically passed in using the 44 | // __LINE__ macro. 45 | // HRESULT hr An HRESULT that will be traced to the debug stream. 46 | // CHAR* strMsg A string that will be traced to the debug stream (may be NULL) 47 | // BOOL bPopMsgBox If TRUE, then a message box will popup also containing the passed info. 48 | // 49 | // Return: The hr that was passed in. 50 | //-------------------------------------------------------------------------------------- 51 | HRESULT WINAPI DXTraceW( _In_z_ const WCHAR* strFile, _In_ DWORD dwLine, _In_ HRESULT hr, _In_opt_ const WCHAR* strMsg, _In_ bool bPopMsgBox ); 52 | 53 | #define DXTrace DXTraceW 54 | 55 | //-------------------------------------------------------------------------------------- 56 | // 57 | // Helper macros 58 | // 59 | //-------------------------------------------------------------------------------------- 60 | #if defined(DEBUG) || defined(_DEBUG) 61 | #define DXTRACE_MSG(str) DXTrace( __FILEW__, (DWORD)__LINE__, 0, str, false ) 62 | #define DXTRACE_ERR(str,hr) DXTrace( __FILEW__, (DWORD)__LINE__, hr, str, false ) 63 | #define DXTRACE_ERR_MSGBOX(str,hr) DXTrace( __FILEW__, (DWORD)__LINE__, hr, str, true ) 64 | #else 65 | #define DXTRACE_MSG(str) (0L) 66 | #define DXTRACE_ERR(str,hr) (hr) 67 | #define DXTRACE_ERR_MSGBOX(str,hr) (hr) 68 | #endif 69 | 70 | #ifdef __cplusplus 71 | } 72 | #endif //__cplusplus 73 | -------------------------------------------------------------------------------- /libsph/sph_math.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace SPH 4 | { 5 | 6 | 7 | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 8 | // iVector3 9 | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 10 | class iVector3 11 | { 12 | public: 13 | iVector3() : x(0), y(0), z(0) {} 14 | iVector3(const iVector3& other) : x(other.x), y(other.y), z(other.z) {} 15 | iVector3(int _x, int _y, int _z) : x(_x), y(_y), z(_z) {} 16 | ~iVector3() {} 17 | 18 | public: 19 | int x, y, z; 20 | }; 21 | 22 | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 23 | // fVector3 24 | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 25 | class fVector3 26 | { 27 | public: 28 | fVector3() : x(0), y(0), z(0) {} 29 | fVector3(const fVector3& other) : x(other.x), y(other.y), z(other.z) {} 30 | fVector3(const iVector3& other) : x((float)other.x), y((float)other.y), z((float)other.z) {} 31 | fVector3(const float_3* other) : x(other->x), y(other->y), z(other->z) {} 32 | fVector3(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {} 33 | ~fVector3() {} 34 | 35 | void set(float _x, float _y, float _z) { x=_x; y=_y; z=_z;} 36 | 37 | fVector3& operator= (const fVector3 &op) { x=op.x; y=op.y; z=op.z; return *this; } 38 | 39 | fVector3& operator+= (float op) { x+=op; y+=op; z+=op; return *this; } 40 | fVector3& operator-= (float op) { x-=op; y-=op; z-=op; return *this; } 41 | fVector3& operator*= (float op) { x*=op; y*=op; z*=op; return *this; } 42 | fVector3& operator/= (float op) { x/=op; y/=op; z/=op; return *this; } 43 | 44 | fVector3& operator+= (const fVector3& op) { x+=op.x; y+=op.y; z+=op.z; return *this; } 45 | fVector3& operator-= (const fVector3& op) { x-=op.x; y-=op.y; z-=op.z; return *this; } 46 | fVector3& operator*= (const fVector3& op) { x*=op.x; y*=op.y; z*=op.z; return *this; } 47 | fVector3& operator/= (const fVector3& op) { x/=op.x; y/=op.y; z/=op.z; return *this; } 48 | 49 | float dot(const fVector3& other) 50 | { 51 | return x*other.x + y*other.y + z*other.z; 52 | } 53 | 54 | float len_sq(void) const 55 | { 56 | return x*x + y*y + z*z; 57 | } 58 | 59 | void normalize(void) 60 | { 61 | float len_squar = x*x + y*y + z*z; 62 | if(len_squar!=0.0) 63 | { 64 | float len = sqrt(len_squar); 65 | x /= len; y /= len; z /= len; 66 | } 67 | } 68 | public: 69 | float x, y, z; 70 | }; 71 | 72 | inline fVector3 operator + (const fVector3& a, const fVector3& b) 73 | { 74 | return fVector3(a.x+b.x, a.y+b.y, a.z+b.z); 75 | } 76 | 77 | inline fVector3 operator - (const fVector3& a, const fVector3& b) 78 | { 79 | return fVector3(a.x-b.x, a.y-b.y, a.z-b.z); 80 | } 81 | 82 | inline fVector3 operator * (float s, const fVector3& a) 83 | { 84 | return fVector3(s*a.x, s*a.y, s*a.z); 85 | } 86 | 87 | inline fVector3 operator * (const fVector3& a, float s) 88 | { 89 | return fVector3(s*a.x, s*a.y, s*a.z); 90 | } 91 | 92 | inline fVector3 operator / (const fVector3& a, float s) 93 | { 94 | return fVector3(a.x/s, a.y/s, a.z/s); 95 | } 96 | 97 | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 98 | // fBox3 99 | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 100 | class fBox3 101 | { 102 | public: 103 | fBox3() {} 104 | fBox3(const fBox3& other) : min(other.min), max(other.max) {} 105 | fBox3(const fVector3& _min, const fVector3& _max) : min(_min), max(_max) {} 106 | ~fBox3() {} 107 | 108 | public: 109 | fVector3 min, max; 110 | }; 111 | 112 | } 113 | 114 | 115 | -------------------------------------------------------------------------------- /libsph/sph_neighbor_table.cpp: -------------------------------------------------------------------------------- 1 | #include "sph_stdafx.h" 2 | #include "sph_neighbor_table.h" 3 | 4 | namespace SPH 5 | { 6 | //----------------------------------------------------------------------------------------------------------------- 7 | NeighborTable::NeighborTable() 8 | : m_pointExtraData(0) 9 | , m_pointCounts(0) 10 | , m_pointCapcity(0) 11 | , m_neighborDataBuf(0) 12 | , m_dataBufSize(0) 13 | , m_currNeighborCounts(0) 14 | , m_currPoint(0) 15 | , m_dataBufOffset(0) 16 | { 17 | } 18 | 19 | //----------------------------------------------------------------------------------------------------------------- 20 | NeighborTable::~NeighborTable() 21 | { 22 | if(m_pointExtraData) free(m_pointExtraData); 23 | if(m_neighborDataBuf) free(m_neighborDataBuf); 24 | } 25 | 26 | //----------------------------------------------------------------------------------------------------------------- 27 | void NeighborTable::reset(unsigned short pointCounts) 28 | { 29 | int a = sizeof(PointExtraData); 30 | if(pointCounts>m_pointCapcity) 31 | { 32 | if(m_pointExtraData) 33 | { 34 | free(m_pointExtraData); 35 | } 36 | m_pointExtraData = (PointExtraData*)malloc(sizeof(PointExtraData)*pointCounts); 37 | m_pointCapcity = pointCounts; 38 | } 39 | 40 | m_pointCounts = pointCounts; 41 | memset(m_pointExtraData, 0, sizeof(PointExtraData)*m_pointCapcity); 42 | m_dataBufOffset = 0; 43 | } 44 | 45 | //----------------------------------------------------------------------------------------------------------------- 46 | void NeighborTable::point_prepare(unsigned short ptIndex) 47 | { 48 | m_currPoint = ptIndex; 49 | m_currNeighborCounts = 0; 50 | } 51 | 52 | //----------------------------------------------------------------------------------------------------------------- 53 | bool NeighborTable::point_add_neighbor(unsigned short ptIndex, float distance) 54 | { 55 | if(m_currNeighborCounts>=MAX_NEIGHTBOR_COUNTS) return false; 56 | 57 | m_currNeightborIndex[m_currNeighborCounts]=ptIndex; 58 | m_currNeighborDistance[m_currNeighborCounts]=distance; 59 | 60 | m_currNeighborCounts++; 61 | return true; 62 | } 63 | 64 | //----------------------------------------------------------------------------------------------------------------- 65 | void NeighborTable::point_commit(void) 66 | { 67 | if(m_currNeighborCounts==0) return; 68 | 69 | unsigned int index_size = m_currNeighborCounts*sizeof(unsigned short); 70 | unsigned int distance_size = m_currNeighborCounts*sizeof(float); 71 | 72 | //grow buf 73 | if(m_dataBufOffset+index_size+distance_size>m_dataBufSize) 74 | { 75 | _growDataBuf(m_dataBufOffset+index_size+distance_size); 76 | } 77 | 78 | //set neightbor data 79 | m_pointExtraData[m_currPoint].neighborCounts = m_currNeighborCounts; 80 | m_pointExtraData[m_currPoint].neighborDataOffset = m_dataBufOffset; 81 | 82 | //copy index data 83 | memcpy(m_neighborDataBuf+m_dataBufOffset, m_currNeightborIndex, index_size); 84 | m_dataBufOffset += index_size; 85 | 86 | //copy distance data 87 | memcpy(m_neighborDataBuf+m_dataBufOffset, m_currNeighborDistance, distance_size); 88 | m_dataBufOffset += distance_size; 89 | } 90 | 91 | //----------------------------------------------------------------------------------------------------------------- 92 | void NeighborTable::_growDataBuf(unsigned int need_size) 93 | { 94 | unsigned int newSize = m_dataBufSize>0 ? m_dataBufSize : 1; 95 | while(newSize 12 | 13 | class CImeUiFont_Base 14 | { 15 | public: 16 | virtual void SetHeight( _In_ UINT uHeight ) 17 | { 18 | UNREFERENCED_PARAMETER(uHeight); 19 | }; // for backward compatibility 20 | virtual void SetColor( _In_ DWORD color ) = 0; 21 | virtual void SetPosition( _In_ int x, _In_ int y ) = 0; 22 | virtual void GetTextExtent( _In_z_ LPCTSTR szText, _Out_ DWORD* puWidth, _Out_ DWORD* puHeight ) = 0; 23 | virtual void DrawText( _In_z_ LPCTSTR pszText ) = 0; 24 | }; 25 | 26 | typedef struct 27 | { 28 | // symbol (Henkan-kyu) 29 | DWORD symbolColor; 30 | DWORD symbolColorOff; 31 | DWORD symbolColorText; 32 | BYTE symbolHeight; 33 | BYTE symbolTranslucence; 34 | BYTE symbolPlacement; 35 | CImeUiFont_Base* symbolFont; 36 | 37 | // candidate list 38 | DWORD candColorBase; 39 | DWORD candColorBorder; 40 | DWORD candColorText; 41 | 42 | // composition string 43 | DWORD compColorInput; 44 | DWORD compColorTargetConv; 45 | DWORD compColorConverted; 46 | DWORD compColorTargetNotConv; 47 | DWORD compColorInputErr; 48 | BYTE compTranslucence; 49 | DWORD compColorText; 50 | 51 | // caret 52 | BYTE caretWidth; 53 | BYTE caretYMargin; 54 | } IMEUI_APPEARANCE; 55 | 56 | typedef struct // D3DTLVERTEX compatible 57 | { 58 | float sx; 59 | float sy; 60 | float sz; 61 | float rhw; 62 | DWORD color; 63 | DWORD specular; 64 | float tu; 65 | float tv; 66 | } IMEUI_VERTEX; 67 | 68 | // IME States 69 | #define IMEUI_STATE_OFF 0 70 | #define IMEUI_STATE_ON 1 71 | #define IMEUI_STATE_ENGLISH 2 72 | 73 | // IME const 74 | #define MAX_CANDLIST 10 75 | 76 | // IME Flags 77 | #define IMEUI_FLAG_SUPPORT_CARET 0x00000001 78 | 79 | bool ImeUi_Initialize( _In_ HWND hwnd, _In_ bool bDisable = false ); 80 | void ImeUi_Uninitialize(); 81 | void ImeUi_SetAppearance( _In_opt_ const IMEUI_APPEARANCE* pia ); 82 | void ImeUi_GetAppearance( _Out_opt_ IMEUI_APPEARANCE* pia ); 83 | bool ImeUi_IgnoreHotKey( _In_ const MSG* pmsg ); 84 | LPARAM ImeUi_ProcessMessage( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _Inout_ LPARAM& lParam, _Out_ bool* trapped ); 85 | void ImeUi_SetScreenDimension( _In_ UINT width, _In_ UINT height ); 86 | void ImeUi_RenderUI( _In_ bool bDrawCompAttr = true, _In_ bool bDrawOtherUi = true ); 87 | void ImeUi_SetCaretPosition( _In_ UINT x, _In_ UINT y ); 88 | void ImeUi_SetCompStringAppearance( _In_ CImeUiFont_Base* pFont, _In_ DWORD color, _In_ const RECT* prc ); 89 | bool ImeUi_GetCaretStatus(); 90 | void ImeUi_SetInsertMode( _In_ bool bInsert ); 91 | void ImeUi_SetState( _In_ DWORD dwState ); 92 | DWORD ImeUi_GetState(); 93 | void ImeUi_EnableIme( _In_ bool bEnable ); 94 | bool ImeUi_IsEnabled(); 95 | void ImeUi_FinalizeString( _In_ bool bSend = false ); 96 | void ImeUi_ToggleLanguageBar( _In_ BOOL bRestore ); 97 | bool ImeUi_IsSendingKeyMessage(); 98 | void ImeUi_SetWindow( _In_ HWND hwnd ); 99 | UINT ImeUi_GetInputCodePage(); 100 | DWORD ImeUi_GetFlags(); 101 | void ImeUi_SetFlags( _In_ DWORD dwFlags, _In_ bool bSet ); 102 | 103 | WORD ImeUi_GetPrimaryLanguage(); 104 | DWORD ImeUi_GetImeId( _In_ UINT uIndex ); 105 | WORD ImeUi_GetLanguage(); 106 | LPCTSTR ImeUi_GetIndicatior(); 107 | bool ImeUi_IsShowReadingWindow(); 108 | bool ImeUi_IsShowCandListWindow(); 109 | bool ImeUi_IsVerticalCand(); 110 | bool ImeUi_IsHorizontalReading(); 111 | TCHAR* ImeUi_GetCandidate( _In_ UINT idx ); 112 | TCHAR* ImeUi_GetCompositionString(); 113 | DWORD ImeUi_GetCandidateSelection(); 114 | DWORD ImeUi_GetCandidateCount(); 115 | BYTE* ImeUi_GetCompStringAttr(); 116 | DWORD ImeUi_GetImeCursorChars(); 117 | 118 | extern void ( CALLBACK*ImeUiCallback_DrawRect )( _In_ int x1, _In_ int y1, _In_ int x2, _In_ int y2, _In_ DWORD color ); 119 | extern void* ( __cdecl*ImeUiCallback_Malloc )( _In_ size_t bytes ); 120 | extern void ( __cdecl*ImeUiCallback_Free )( _In_ void* ptr ); 121 | extern void ( CALLBACK*ImeUiCallback_DrawFans )( _In_ const IMEUI_VERTEX* paVertex, _In_ UINT uNum ); 122 | extern void ( CALLBACK*ImeUiCallback_OnChar )( _In_ WCHAR wc ); 123 | -------------------------------------------------------------------------------- /libsph/sph_grid_container.cpp: -------------------------------------------------------------------------------- 1 | #include "sph_stdafx.h" 2 | #include "sph_grid_container.h" 3 | #include "sph_point_buffer.h" 4 | 5 | namespace SPH 6 | { 7 | 8 | //----------------------------------------------------------------------------------------------------------------- 9 | GridContainer::GridContainer() 10 | { 11 | } 12 | 13 | //----------------------------------------------------------------------------------------------------------------- 14 | GridContainer::~GridContainer() 15 | { 16 | } 17 | 18 | //----------------------------------------------------------------------------------------------------------------- 19 | int GridContainer::getGridData(int gridIndex) 20 | { 21 | if(gridIndex<0 || gridIndex>=(int)m_gridData.size()) return -1; 22 | 23 | return m_gridData[gridIndex]; 24 | } 25 | 26 | //----------------------------------------------------------------------------------------------------------------- 27 | int GridContainer::getGridCellIndex(float px, float py, float pz) 28 | { 29 | int gx = (int)((px - m_GridMin.x) * m_GridDelta.x); 30 | int gy = (int)((py - m_GridMin.y) * m_GridDelta.y); 31 | int gz = (int)((pz - m_GridMin.z) * m_GridDelta.z); 32 | return (gz*m_GridRes.y + gy)*m_GridRes.x + gx; 33 | } 34 | 35 | //----------------------------------------------------------------------------------------------------------------- 36 | void GridContainer::init(const fBox3& box, float sim_scale, float cell_size, float border) 37 | { 38 | // Ideal grid cell size (gs) = 2 * smoothing radius = 0.02*2 = 0.04 39 | // Ideal domain size = k*gs/d = k*0.02*2/0.005 = k*8 = {8, 16, 24, 32, 40, 48, ..} 40 | // (k = number of cells, gs = cell size, d = simulation scale) 41 | float world_cellsize = cell_size / sim_scale; 42 | 43 | m_GridMin = box.min; m_GridMin -= border; 44 | m_GridMax = box.max; m_GridMax += border; 45 | m_GridSize = m_GridMax; 46 | m_GridSize -= m_GridMin; 47 | m_GridCellsize = world_cellsize; 48 | // Determine grid resolution 49 | m_GridRes.x = (int)ceil(m_GridSize.x / world_cellsize); 50 | m_GridRes.y = (int)ceil(m_GridSize.y / world_cellsize); 51 | m_GridRes.z = (int)ceil(m_GridSize.z / world_cellsize); 52 | // Adjust grid size to multiple of cell size 53 | m_GridSize.x = m_GridRes.x * cell_size / sim_scale; 54 | m_GridSize.y = m_GridRes.y * cell_size / sim_scale; 55 | m_GridSize.z = m_GridRes.z * cell_size / sim_scale; 56 | // delta = translate from world space to cell # 57 | m_GridDelta = m_GridRes; 58 | m_GridDelta /= m_GridSize; 59 | 60 | int gridTotal = (int)(m_GridRes.x * m_GridRes.y * m_GridRes.z); 61 | m_gridData.resize(gridTotal); 62 | } 63 | 64 | //----------------------------------------------------------------------------------------------------------------- 65 | void GridContainer::insertParticles(PointBuffer* pointBuffer) 66 | { 67 | std::fill(m_gridData.begin(), m_gridData.end(), -1); 68 | 69 | Point* p = pointBuffer->get(0); 70 | for(unsigned int n=0; nsize(); n++, p++) 71 | { 72 | int gs = getGridCellIndex(p->pos.x, p->pos.y, p->pos.z); 73 | if ( gs >= 0 && gs < (int)m_gridData.size() ) 74 | { 75 | p->next = m_gridData[gs]; 76 | m_gridData[gs] =(int) n; 77 | } 78 | else p->next = -1; 79 | } 80 | } 81 | 82 | //----------------------------------------------------------------------------------------------------------------- 83 | int GridContainer::findCell(const fVector3& p) 84 | { 85 | int gc = getGridCellIndex(p.x, p.y, p.z); 86 | 87 | if ( gc < 0 || gc >= (int)m_gridData.size() ) return -1; 88 | return gc; 89 | } 90 | 91 | //----------------------------------------------------------------------------------------------------------------- 92 | void GridContainer::findCells(const fVector3& p, float radius, int* gridCell) 93 | { 94 | for(int i=0; i<8; i++) gridCell[i]=-1; 95 | 96 | // Compute sphere range 97 | int sph_min_x = (int)((-radius + p.x - m_GridMin.x) * m_GridDelta.x); 98 | int sph_min_y = (int)((-radius + p.y - m_GridMin.y) * m_GridDelta.y); 99 | int sph_min_z = (int)((-radius + p.z - m_GridMin.z) * m_GridDelta.z); 100 | if ( sph_min_x < 0 ) sph_min_x = 0; 101 | if ( sph_min_y < 0 ) sph_min_y = 0; 102 | if ( sph_min_z < 0 ) sph_min_z = 0; 103 | 104 | gridCell[0] = (sph_min_z*m_GridRes.y + sph_min_y)*m_GridRes.x + sph_min_x; 105 | gridCell[1] = gridCell[0] + 1; 106 | gridCell[2] = (int)(gridCell[0] + m_GridRes.x); 107 | gridCell[3] = gridCell[2] + 1; 108 | 109 | if ( sph_min_z+1 < m_GridRes.z ) { 110 | gridCell[4] = (int)(gridCell[0] + m_GridRes.y*m_GridRes.x); 111 | gridCell[5] = gridCell[4] + 1; 112 | gridCell[6] = (int)(gridCell[4] + m_GridRes.x); 113 | gridCell[7] = gridCell[6] + 1; 114 | } 115 | if ( sph_min_x+1 >= m_GridRes.x ) { 116 | gridCell[1] = -1; gridCell[3] = -1; 117 | gridCell[5] = -1; gridCell[7] = -1; 118 | } 119 | if ( sph_min_y+1 >= m_GridRes.y ) { 120 | gridCell[2] = -1; gridCell[3] = -1; 121 | gridCell[6] = -1; gridCell[7] = -1; 122 | } 123 | } 124 | 125 | } 126 | -------------------------------------------------------------------------------- /DXUT/Core/WICTextureLoader.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: WICTextureLoader.h 3 | // 4 | // Function for loading a WIC image and creating a Direct3D runtime texture for it 5 | // (auto-generating mipmaps if possible) 6 | // 7 | // Note: Assumes application has already called CoInitializeEx 8 | // 9 | // Warning: CreateWICTexture* functions are not thread-safe if given a d3dContext instance for 10 | // auto-gen mipmap support. 11 | // 12 | // Note these functions are useful for images created as simple 2D textures. For 13 | // more complex resources, DDSTextureLoader is an excellent light-weight runtime loader. 14 | // For a full-featured DDS file reader, writer, and texture processing pipeline see 15 | // the 'Texconv' sample and the 'DirectXTex' library. 16 | // 17 | // Copyright (c) Microsoft Corporation. All rights reserved. 18 | // Licensed under the MIT License. 19 | // 20 | // http://go.microsoft.com/fwlink/?LinkId=248926 21 | // http://go.microsoft.com/fwlink/?LinkId=248929 22 | //-------------------------------------------------------------------------------------- 23 | 24 | #pragma once 25 | 26 | #include 27 | #include 28 | 29 | 30 | namespace DirectX 31 | { 32 | enum WIC_LOADER_FLAGS 33 | { 34 | WIC_LOADER_DEFAULT = 0, 35 | WIC_LOADER_FORCE_SRGB = 0x1, 36 | WIC_LOADER_IGNORE_SRGB = 0x2, 37 | }; 38 | 39 | // Standard version 40 | HRESULT CreateWICTextureFromMemory( 41 | _In_ ID3D11Device* d3dDevice, 42 | _In_reads_bytes_(wicDataSize) const uint8_t* wicData, 43 | _In_ size_t wicDataSize, 44 | _Outptr_opt_ ID3D11Resource** texture, 45 | _Outptr_opt_ ID3D11ShaderResourceView** textureView, 46 | _In_ size_t maxsize = 0); 47 | 48 | HRESULT CreateWICTextureFromFile( 49 | _In_ ID3D11Device* d3dDevice, 50 | _In_z_ const wchar_t* szFileName, 51 | _Outptr_opt_ ID3D11Resource** texture, 52 | _Outptr_opt_ ID3D11ShaderResourceView** textureView, 53 | _In_ size_t maxsize = 0); 54 | 55 | // Standard version with optional auto-gen mipmap support 56 | HRESULT CreateWICTextureFromMemory( 57 | _In_ ID3D11Device* d3dDevice, 58 | _In_opt_ ID3D11DeviceContext* d3dContext, 59 | _In_reads_bytes_(wicDataSize) const uint8_t* wicData, 60 | _In_ size_t wicDataSize, 61 | _Outptr_opt_ ID3D11Resource** texture, 62 | _Outptr_opt_ ID3D11ShaderResourceView** textureView, 63 | _In_ size_t maxsize = 0); 64 | 65 | HRESULT CreateWICTextureFromFile( 66 | _In_ ID3D11Device* d3dDevice, 67 | _In_opt_ ID3D11DeviceContext* d3dContext, 68 | _In_z_ const wchar_t* szFileName, 69 | _Outptr_opt_ ID3D11Resource** texture, 70 | _Outptr_opt_ ID3D11ShaderResourceView** textureView, 71 | _In_ size_t maxsize = 0); 72 | 73 | // Extended version 74 | HRESULT CreateWICTextureFromMemoryEx( 75 | _In_ ID3D11Device* d3dDevice, 76 | _In_reads_bytes_(wicDataSize) const uint8_t* wicData, 77 | _In_ size_t wicDataSize, 78 | _In_ size_t maxsize, 79 | _In_ D3D11_USAGE usage, 80 | _In_ unsigned int bindFlags, 81 | _In_ unsigned int cpuAccessFlags, 82 | _In_ unsigned int miscFlags, 83 | _In_ unsigned int loadFlags, 84 | _Outptr_opt_ ID3D11Resource** texture, 85 | _Outptr_opt_ ID3D11ShaderResourceView** textureView); 86 | 87 | HRESULT CreateWICTextureFromFileEx( 88 | _In_ ID3D11Device* d3dDevice, 89 | _In_z_ const wchar_t* szFileName, 90 | _In_ size_t maxsize, 91 | _In_ D3D11_USAGE usage, 92 | _In_ unsigned int bindFlags, 93 | _In_ unsigned int cpuAccessFlags, 94 | _In_ unsigned int miscFlags, 95 | _In_ unsigned int loadFlags, 96 | _Outptr_opt_ ID3D11Resource** texture, 97 | _Outptr_opt_ ID3D11ShaderResourceView** textureView); 98 | 99 | // Extended version with optional auto-gen mipmap support 100 | HRESULT CreateWICTextureFromMemoryEx( 101 | _In_ ID3D11Device* d3dDevice, 102 | _In_opt_ ID3D11DeviceContext* d3dContext, 103 | _In_reads_bytes_(wicDataSize) const uint8_t* wicData, 104 | _In_ size_t wicDataSize, 105 | _In_ size_t maxsize, 106 | _In_ D3D11_USAGE usage, 107 | _In_ unsigned int bindFlags, 108 | _In_ unsigned int cpuAccessFlags, 109 | _In_ unsigned int miscFlags, 110 | _In_ unsigned int loadFlags, 111 | _Outptr_opt_ ID3D11Resource** texture, 112 | _Outptr_opt_ ID3D11ShaderResourceView** textureView); 113 | 114 | HRESULT CreateWICTextureFromFileEx( 115 | _In_ ID3D11Device* d3dDevice, 116 | _In_opt_ ID3D11DeviceContext* d3dContext, 117 | _In_z_ const wchar_t* szFileName, 118 | _In_ size_t maxsize, 119 | _In_ D3D11_USAGE usage, 120 | _In_ unsigned int bindFlags, 121 | _In_ unsigned int cpuAccessFlags, 122 | _In_ unsigned int miscFlags, 123 | _In_ unsigned int loadFlags, 124 | _Outptr_opt_ ID3D11Resource** texture, 125 | _Outptr_opt_ ID3D11ShaderResourceView** textureView); 126 | } -------------------------------------------------------------------------------- /DXUT/Core/DDSTextureLoader.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: DDSTextureLoader.h 3 | // 4 | // Functions for loading a DDS texture and creating a Direct3D runtime resource for it 5 | // 6 | // Note these functions are useful as a light-weight runtime loader for DDS files. For 7 | // a full-featured DDS file reader, writer, and texture processing pipeline see 8 | // the 'Texconv' sample and the 'DirectXTex' library. 9 | // 10 | // Copyright (c) Microsoft Corporation. All rights reserved. 11 | // Licensed under the MIT License. 12 | // 13 | // http://go.microsoft.com/fwlink/?LinkId=248926 14 | // http://go.microsoft.com/fwlink/?LinkId=248929 15 | //-------------------------------------------------------------------------------------- 16 | 17 | #pragma once 18 | 19 | #include 20 | #include 21 | 22 | 23 | namespace DirectX 24 | { 25 | enum DDS_ALPHA_MODE 26 | { 27 | DDS_ALPHA_MODE_UNKNOWN = 0, 28 | DDS_ALPHA_MODE_STRAIGHT = 1, 29 | DDS_ALPHA_MODE_PREMULTIPLIED = 2, 30 | DDS_ALPHA_MODE_OPAQUE = 3, 31 | DDS_ALPHA_MODE_CUSTOM = 4, 32 | }; 33 | 34 | // Standard version 35 | HRESULT CreateDDSTextureFromMemory( 36 | _In_ ID3D11Device* d3dDevice, 37 | _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, 38 | _In_ size_t ddsDataSize, 39 | _Outptr_opt_ ID3D11Resource** texture, 40 | _Outptr_opt_ ID3D11ShaderResourceView** textureView, 41 | _In_ size_t maxsize = 0, 42 | _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); 43 | 44 | HRESULT CreateDDSTextureFromFile( 45 | _In_ ID3D11Device* d3dDevice, 46 | _In_z_ const wchar_t* szFileName, 47 | _Outptr_opt_ ID3D11Resource** texture, 48 | _Outptr_opt_ ID3D11ShaderResourceView** textureView, 49 | _In_ size_t maxsize = 0, 50 | _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); 51 | 52 | // Standard version with optional auto-gen mipmap support 53 | HRESULT CreateDDSTextureFromMemory( 54 | _In_ ID3D11Device* d3dDevice, 55 | _In_opt_ ID3D11DeviceContext* d3dContext, 56 | _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, 57 | _In_ size_t ddsDataSize, 58 | _Outptr_opt_ ID3D11Resource** texture, 59 | _Outptr_opt_ ID3D11ShaderResourceView** textureView, 60 | _In_ size_t maxsize = 0, 61 | _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); 62 | 63 | HRESULT CreateDDSTextureFromFile( 64 | _In_ ID3D11Device* d3dDevice, 65 | _In_opt_ ID3D11DeviceContext* d3dContext, 66 | _In_z_ const wchar_t* szFileName, 67 | _Outptr_opt_ ID3D11Resource** texture, 68 | _Outptr_opt_ ID3D11ShaderResourceView** textureView, 69 | _In_ size_t maxsize = 0, 70 | _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); 71 | 72 | // Extended version 73 | HRESULT CreateDDSTextureFromMemoryEx( 74 | _In_ ID3D11Device* d3dDevice, 75 | _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, 76 | _In_ size_t ddsDataSize, 77 | _In_ size_t maxsize, 78 | _In_ D3D11_USAGE usage, 79 | _In_ unsigned int bindFlags, 80 | _In_ unsigned int cpuAccessFlags, 81 | _In_ unsigned int miscFlags, 82 | _In_ bool forceSRGB, 83 | _Outptr_opt_ ID3D11Resource** texture, 84 | _Outptr_opt_ ID3D11ShaderResourceView** textureView, 85 | _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); 86 | 87 | HRESULT CreateDDSTextureFromFileEx( 88 | _In_ ID3D11Device* d3dDevice, 89 | _In_z_ const wchar_t* szFileName, 90 | _In_ size_t maxsize, 91 | _In_ D3D11_USAGE usage, 92 | _In_ unsigned int bindFlags, 93 | _In_ unsigned int cpuAccessFlags, 94 | _In_ unsigned int miscFlags, 95 | _In_ bool forceSRGB, 96 | _Outptr_opt_ ID3D11Resource** texture, 97 | _Outptr_opt_ ID3D11ShaderResourceView** textureView, 98 | _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); 99 | 100 | // Extended version with optional auto-gen mipmap support 101 | HRESULT CreateDDSTextureFromMemoryEx( 102 | _In_ ID3D11Device* d3dDevice, 103 | _In_opt_ ID3D11DeviceContext* d3dContext, 104 | _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData, 105 | _In_ size_t ddsDataSize, 106 | _In_ size_t maxsize, 107 | _In_ D3D11_USAGE usage, 108 | _In_ unsigned int bindFlags, 109 | _In_ unsigned int cpuAccessFlags, 110 | _In_ unsigned int miscFlags, 111 | _In_ bool forceSRGB, 112 | _Outptr_opt_ ID3D11Resource** texture, 113 | _Outptr_opt_ ID3D11ShaderResourceView** textureView, 114 | _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); 115 | 116 | HRESULT CreateDDSTextureFromFileEx( 117 | _In_ ID3D11Device* d3dDevice, 118 | _In_opt_ ID3D11DeviceContext* d3dContext, 119 | _In_z_ const wchar_t* szFileName, 120 | _In_ size_t maxsize, 121 | _In_ D3D11_USAGE usage, 122 | _In_ unsigned int bindFlags, 123 | _In_ unsigned int cpuAccessFlags, 124 | _In_ unsigned int miscFlags, 125 | _In_ bool forceSRGB, 126 | _Outptr_opt_ ID3D11Resource** texture, 127 | _Outptr_opt_ ID3D11ShaderResourceView** textureView, 128 | _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr); 129 | } -------------------------------------------------------------------------------- /DXUT/Optional/SDKmisc.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: SDKMisc.h 3 | // 4 | // Various helper functionality that is shared between SDK samples 5 | // 6 | // Copyright (c) Microsoft Corporation. All rights reserved. 7 | // Licensed under the MIT License. 8 | // 9 | // http://go.microsoft.com/fwlink/?LinkId=320437 10 | //-------------------------------------------------------------------------------------- 11 | #pragma once 12 | 13 | //----------------------------------------------------------------------------- 14 | // Resource cache for textures, fonts, meshs, and effects. 15 | // Use DXUTGetGlobalResourceCache() to access the global cache 16 | //----------------------------------------------------------------------------- 17 | 18 | struct DXUTCache_Texture 19 | { 20 | WCHAR wszSource[MAX_PATH]; 21 | bool bSRGB; 22 | ID3D11ShaderResourceView* pSRV11; 23 | 24 | DXUTCache_Texture() : 25 | pSRV11(nullptr) 26 | { 27 | } 28 | }; 29 | 30 | 31 | class CDXUTResourceCache 32 | { 33 | public: 34 | ~CDXUTResourceCache(); 35 | 36 | HRESULT CreateTextureFromFile( _In_ ID3D11Device* pDevice, _In_ ID3D11DeviceContext *pContext, _In_z_ LPCWSTR pSrcFile, 37 | _Outptr_ ID3D11ShaderResourceView** ppOutputRV, _In_ bool bSRGB=false ); 38 | HRESULT CreateTextureFromFile( _In_ ID3D11Device* pDevice, _In_ ID3D11DeviceContext *pContext, _In_z_ LPCSTR pSrcFile, 39 | _Outptr_ ID3D11ShaderResourceView** ppOutputRV, _In_ bool bSRGB=false ); 40 | public: 41 | HRESULT OnDestroyDevice(); 42 | 43 | protected: 44 | friend CDXUTResourceCache& WINAPI DXUTGetGlobalResourceCache(); 45 | friend HRESULT WINAPI DXUTInitialize3DEnvironment(); 46 | friend HRESULT WINAPI DXUTReset3DEnvironment(); 47 | friend void WINAPI DXUTCleanup3DEnvironment( bool bReleaseSettings ); 48 | 49 | CDXUTResourceCache() { } 50 | 51 | std::vector m_TextureCache; 52 | }; 53 | 54 | CDXUTResourceCache& WINAPI DXUTGetGlobalResourceCache(); 55 | 56 | 57 | //-------------------------------------------------------------------------------------- 58 | // Manages the insertion point when drawing text 59 | //-------------------------------------------------------------------------------------- 60 | class CDXUTDialogResourceManager; 61 | class CDXUTTextHelper 62 | { 63 | public: 64 | CDXUTTextHelper( _In_ ID3D11Device* pd3d11Device, _In_ ID3D11DeviceContext* pd3dDeviceContext, _In_ CDXUTDialogResourceManager* pManager, _In_ int nLineHeight ); 65 | ~CDXUTTextHelper(); 66 | 67 | void Init( _In_ int nLineHeight = 15 ); 68 | 69 | void SetInsertionPos( _In_ int x, _In_ int y ) 70 | { 71 | m_pt.x = x; 72 | m_pt.y = y; 73 | } 74 | void SetForegroundColor( _In_ DirectX::XMFLOAT4 clr ) { m_clr = clr; } 75 | void SetForegroundColor( _In_ DirectX::FXMVECTOR clr ) { XMStoreFloat4( &m_clr, clr ); } 76 | 77 | void Begin(); 78 | HRESULT DrawFormattedTextLine( _In_z_ const WCHAR* strMsg, ... ); 79 | HRESULT DrawTextLine( _In_z_ const WCHAR* strMsg ); 80 | HRESULT DrawFormattedTextLine( _In_ const RECT& rc, _In_z_ const WCHAR* strMsg, ... ); 81 | HRESULT DrawTextLine( _In_ const RECT& rc, _In_z_ const WCHAR* strMsg ); 82 | void End(); 83 | 84 | protected: 85 | DirectX::XMFLOAT4 m_clr; 86 | POINT m_pt; 87 | int m_nLineHeight; 88 | 89 | // D3D11 font 90 | ID3D11Device* m_pd3d11Device; 91 | ID3D11DeviceContext* m_pd3d11DeviceContext; 92 | CDXUTDialogResourceManager* m_pManager; 93 | }; 94 | 95 | 96 | //-------------------------------------------------------------------------------------- 97 | // Shared code for samples to ask user if they want to use a REF device or quit 98 | //-------------------------------------------------------------------------------------- 99 | void WINAPI DXUTDisplaySwitchingToREFWarning(); 100 | 101 | //-------------------------------------------------------------------------------------- 102 | // Tries to finds a media file by searching in common locations 103 | //-------------------------------------------------------------------------------------- 104 | HRESULT WINAPI DXUTFindDXSDKMediaFileCch( _Out_writes_(cchDest) WCHAR* strDestPath, 105 | _In_ int cchDest, 106 | _In_z_ LPCWSTR strFilename ); 107 | HRESULT WINAPI DXUTSetMediaSearchPath( _In_z_ LPCWSTR strPath ); 108 | LPCWSTR WINAPI DXUTGetMediaSearchPath(); 109 | 110 | 111 | //-------------------------------------------------------------------------------------- 112 | // Compiles HLSL shaders 113 | //-------------------------------------------------------------------------------------- 114 | HRESULT WINAPI DXUTCompileFromFile( _In_z_ LPCWSTR pFileName, 115 | _In_reads_opt_(_Inexpressible_(pDefines->Name != NULL)) const D3D_SHADER_MACRO* pDefines, 116 | _In_z_ LPCSTR pEntrypoint, _In_z_ LPCSTR pTarget, 117 | _In_ UINT Flags1, _In_ UINT Flags2, 118 | _Outptr_ ID3DBlob** ppCode ); 119 | 120 | //-------------------------------------------------------------------------------------- 121 | // Texture utilities 122 | //-------------------------------------------------------------------------------------- 123 | HRESULT WINAPI DXUTCreateShaderResourceViewFromFile( _In_ ID3D11Device* d3dDevice, _In_z_ const wchar_t* szFileName, _Outptr_ ID3D11ShaderResourceView** textureView ); 124 | HRESULT WINAPI DXUTCreateTextureFromFile( _In_ ID3D11Device* d3dDevice, _In_z_ const wchar_t* szFileName, _Outptr_ ID3D11Resource** texture ); 125 | HRESULT WINAPI DXUTSaveTextureToFile( _In_ ID3D11DeviceContext* pContext, _In_ ID3D11Resource* pSource, _In_ bool usedds, _In_z_ const wchar_t* szFileName ); 126 | 127 | //-------------------------------------------------------------------------------------- 128 | // Returns a view matrix for rendering to a face of a cubemap. 129 | //-------------------------------------------------------------------------------------- 130 | DirectX::XMMATRIX WINAPI DXUTGetCubeMapViewMatrix( _In_ DWORD dwFace ); 131 | -------------------------------------------------------------------------------- /DXUT/Optional/DXUTguiIME.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: DXUTguiIME.h 3 | // 4 | // Copyright (c) Microsoft Corporation. All rights reserved. 5 | // Licensed under the MIT License. 6 | // 7 | // http://go.microsoft.com/fwlink/?LinkId=320437 8 | //-------------------------------------------------------------------------------------- 9 | #pragma once 10 | 11 | #include 12 | #include 13 | #include "ImeUi.h" 14 | 15 | //-------------------------------------------------------------------------------------- 16 | // Forward declarations 17 | //-------------------------------------------------------------------------------------- 18 | class CDXUTIMEEditBox; 19 | 20 | 21 | //----------------------------------------------------------------------------- 22 | // IME-enabled EditBox control 23 | //----------------------------------------------------------------------------- 24 | #define MAX_COMPSTRING_SIZE 256 25 | 26 | 27 | class CDXUTIMEEditBox : public CDXUTEditBox 28 | { 29 | public: 30 | 31 | static HRESULT CreateIMEEditBox( _In_ CDXUTDialog* pDialog, _In_ int ID, _In_z_ LPCWSTR strText, _In_ int x, _In_ int y, _In_ int width, 32 | _In_ int height, _In_ bool bIsDefault=false, _Outptr_opt_ CDXUTIMEEditBox** ppCreated=nullptr ); 33 | 34 | CDXUTIMEEditBox( _In_opt_ CDXUTDialog* pDialog = nullptr ); 35 | virtual ~CDXUTIMEEditBox(); 36 | 37 | static void InitDefaultElements( _In_ CDXUTDialog* pDialog ); 38 | 39 | static void WINAPI Initialize( _In_ HWND hWnd ); 40 | static void WINAPI Uninitialize(); 41 | 42 | static HRESULT WINAPI StaticOnCreateDevice(); 43 | static bool WINAPI StaticMsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); 44 | 45 | static void WINAPI SetImeEnableFlag( _In_ bool bFlag ); 46 | 47 | virtual void Render( _In_ float fElapsedTime ) override; 48 | virtual bool MsgProc( _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; 49 | virtual bool HandleMouse( _In_ UINT uMsg, _In_ const POINT& pt, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; 50 | virtual void UpdateRects() override; 51 | virtual void OnFocusIn() override; 52 | virtual void OnFocusOut() override; 53 | 54 | void PumpMessage(); 55 | 56 | virtual void RenderCandidateReadingWindow( _In_ bool bReading ); 57 | virtual void RenderComposition(); 58 | virtual void RenderIndicator( _In_ float fElapsedTime ); 59 | 60 | protected: 61 | static void WINAPI EnableImeSystem( _In_ bool bEnable ); 62 | 63 | static WORD WINAPI GetLanguage() 64 | { 65 | return ImeUi_GetLanguage(); 66 | } 67 | static WORD WINAPI GetPrimaryLanguage() 68 | { 69 | return ImeUi_GetPrimaryLanguage(); 70 | } 71 | static void WINAPI SendKey( _In_ BYTE nVirtKey ); 72 | static DWORD WINAPI GetImeId( _In_ UINT uIndex = 0 ) 73 | { 74 | return ImeUi_GetImeId( uIndex ); 75 | }; 76 | static void WINAPI CheckInputLocale(); 77 | static void WINAPI CheckToggleState(); 78 | static void WINAPI SetupImeApi(); 79 | static void WINAPI ResetCompositionString(); 80 | 81 | 82 | static void SetupImeUiCallback(); 83 | 84 | protected: 85 | enum 86 | { 87 | INDICATOR_NON_IME, 88 | INDICATOR_CHS, 89 | INDICATOR_CHT, 90 | INDICATOR_KOREAN, 91 | INDICATOR_JAPANESE 92 | }; 93 | 94 | struct CCandList 95 | { 96 | CUniBuffer HoriCand; // Candidate list string (for horizontal candidate window) 97 | int nFirstSelected; // First character position of the selected string in HoriCand 98 | int nHoriSelectedLen; // Length of the selected string in HoriCand 99 | RECT rcCandidate; // Candidate rectangle computed and filled each time before rendered 100 | }; 101 | 102 | static POINT s_ptCompString; // Composition string position. Updated every frame. 103 | static int s_nFirstTargetConv; // Index of the first target converted char in comp string. If none, -1. 104 | static CUniBuffer s_CompString; // Buffer to hold the composition string (we fix its length) 105 | static DWORD s_adwCompStringClause[MAX_COMPSTRING_SIZE]; 106 | static CCandList s_CandList; // Data relevant to the candidate list 107 | static WCHAR s_wszReadingString[32];// Used only with horizontal reading window (why?) 108 | static bool s_bImeFlag; // Is ime enabled 109 | 110 | // Color of various IME elements 111 | DWORD m_ReadingColor; // Reading string color 112 | DWORD m_ReadingWinColor; // Reading window color 113 | DWORD m_ReadingSelColor; // Selected character in reading string 114 | DWORD m_ReadingSelBkColor; // Background color for selected char in reading str 115 | DWORD m_CandidateColor; // Candidate string color 116 | DWORD m_CandidateWinColor; // Candidate window color 117 | DWORD m_CandidateSelColor; // Selected candidate string color 118 | DWORD m_CandidateSelBkColor; // Selected candidate background color 119 | DWORD m_CompColor; // Composition string color 120 | DWORD m_CompWinColor; // Composition string window color 121 | DWORD m_CompCaretColor; // Composition string caret color 122 | DWORD m_CompTargetColor; // Composition string target converted color 123 | DWORD m_CompTargetBkColor; // Composition string target converted background 124 | DWORD m_CompTargetNonColor; // Composition string target non-converted color 125 | DWORD m_CompTargetNonBkColor;// Composition string target non-converted background 126 | DWORD m_IndicatorImeColor; // Indicator text color for IME 127 | DWORD m_IndicatorEngColor; // Indicator text color for English 128 | DWORD m_IndicatorBkColor; // Indicator text background color 129 | 130 | // Edit-control-specific data 131 | int m_nIndicatorWidth; // Width of the indicator symbol 132 | RECT m_rcIndicator; // Rectangle for drawing the indicator button 133 | 134 | #if defined(DEBUG) || defined(_DEBUG) 135 | static bool m_bIMEStaticMsgProcCalled; 136 | #endif 137 | }; 138 | -------------------------------------------------------------------------------- /DXUT/ReadMe.txt: -------------------------------------------------------------------------------- 1 | DXUT FOR DIRECT3D 11 2 | -------------------- 3 | 4 | Copyright (c) Microsoft Corporation. All rights reserved. 5 | 6 | February 27, 2018 7 | 8 | DXUT is a "GLUT"-like framework for Direct3D 11.x Win32 desktop applications; primarily 9 | samples, demos, and prototypes. 10 | 11 | This code is designed to build with Visual Studio 2013 Update 5, Visual Studio 2015 Update 3, 12 | or Visual Studio 2017. It is recommended that you make use of VS 2015 Update 3, Windows Tools 13 | 1.4.1, and the Windows 10 Anniversary Update SDK (14393) or VS 2017 with the Windows 10 14 | Fall Creators Update SDK (16299). 15 | 16 | These components are designed to work without requiring any content from the DirectX SDK. For details, 17 | see "Where is the DirectX SDK?" . 18 | 19 | All content and source code for this package are subject to the terms of the MIT License. 20 | . 21 | 22 | For the latest version of DXUT11, more detailed documentation, etc., please visit the project site. 23 | 24 | http://go.microsoft.com/fwlink/?LinkId=320437 25 | 26 | This project has adopted the Microsoft Open Source Code of Conduct. For more information see the 27 | Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments. 28 | 29 | https://opensource.microsoft.com/codeofconduct/ 30 | 31 | 32 | ------- 33 | SAMPLES 34 | ------- 35 | 36 | Direct3D Tutorial08 - 10 37 | BasicHLSL11, EmptyProject11, SimpleSample11 38 | DXUT+DirectXTK Simple Sample 39 | 40 | These are hosted on GitHub 41 | 42 | 43 | ---------- 44 | DISCLAIMER 45 | ---------- 46 | 47 | DXUT is being provided as a porting aid for older code that makes use of the legacy DirectX SDK, the deprecated D3DX9/D3DX11 48 | library, and the DXUT11 framework. It is a cleaned up version of the original DXUT11 that will build with the Windows 8.1 SDK 49 | and does not make use of any legacy DirectX SDK or DirectSetup deployed components. 50 | 51 | The DXUT framework is for use in Win32 desktop applications. It not usable for Universal Windows Platform apps, Windows Store apps, 52 | Xbox One apps, or Windows phone. 53 | 54 | This version of DXUT only supports Direct3D 11, and therefore is not compatible with Windows XP or early versions of Windows Vista. 55 | 56 | 57 | ------------- 58 | RELEASE NOTES 59 | ------------- 60 | 61 | * The VS 2017 projects make use of /permissive- for improved C++ standard conformance. Use of a Windows 10 SDK prior to 62 | the Fall Creators Update (16299) may result in failures due to problems with the system headers. You can work around 63 | these by deleting /permissive- from the project files which is found in the element. 64 | 65 | 66 | --------------- 67 | RELEASE HISTORY 68 | --------------- 69 | 70 | February 27, 2018 (11.18) 71 | Fixed array length mismatch issue with TOTAL_FEATURE_LEVELS 72 | Fixed optional Direct3D 11.4 support in VS 2013/2015 projects 73 | Minor code cleanup 74 | 75 | November 2, 2017 (11.17) 76 | VS 2017 updated for Windows 10 Fall Creators Update SDK (16299) 77 | Optional support for Direct3D 11.4 (define USE_DIRECT3D11_4 in projects using the 14393 or later Windows 10 SDK) 78 | 79 | October 13, 2017 (11.16) 80 | Updated DDSTextureLoader, WICTextureLoader, and ScreenGrab 81 | Updated for VS 2017 update 15.1 - 15.3 and Windows 10 SDK (15063) 82 | 83 | March 10, 2017 (11.15) 84 | Add VS 2017 projects 85 | Minor code cleanup 86 | 87 | September 15, 2016 (11.14) 88 | Updated WICTextureLoader and ScreenGrab 89 | 90 | August 2, 2016 (11.13) 91 | Updated for VS 2015 Update 3 and Windows 10 SDK (14393) 92 | 93 | April 26, 2016 (11.12) 94 | Updated DDSTextureLoader, WICTextureLoader, and ScreenGrab 95 | Retired VS 2012 projects and obsolete adapter code 96 | Minor code and project file cleanup 97 | 98 | November 30, 2015 (11.11) 99 | Updated DDSTextureLoader, ScreenGrab, DXERR 100 | Updated for VS 2015 Update 1 and Windows 10 SDK (10586) 101 | 102 | July 29, 2015 (11.10) 103 | Updated for VS 2015 and Windows 10 SDK RTM 104 | Retired VS 2010 projects 105 | 106 | June 16, 2015 (11.09) 107 | Optional support for Direct3D 11.3 (define USE_DIRECT3D11_3 in VS 2015 projects) 108 | 109 | April 14, 2015 (11.08) 110 | Fix for auto-gen of volume textures 111 | More updates for VS 2015 112 | 113 | November 24, 2014 (11.07) 114 | Minor fix for Present usage 115 | Minor fix for CBaseCamera::GetInput 116 | Minor fix for WIC usage of IWICFormatConverter 117 | Updates for Visual Studio 2015 Technical Preview 118 | 119 | July 28, 2014 (11.06) 120 | Optional support for Direct3D 11.2 (define USE_DIRECT3D11_2 in VS 2013 projects) 121 | Fixes for various UI and F2 device settings dialog issues 122 | Fixes for device and format enumeration 123 | Changed default resolution to 800x600 124 | Code review fixes 125 | 126 | January 24, 2014 (11.05) 127 | Added use of DXGI debugging when available 128 | Resolved CRT heap leak report 129 | Fixed compile bug in DXUTLockFreePipe 130 | Fixed bug reported in DXUT's sprite implementation 131 | Code cleanup (removed DXGI_1_2_FORMATS control define; ScopedObject typedef removed) 132 | 133 | October 21, 2013 (11.04) 134 | Updated for Visual Studio 2013 and Windows 8.1 SDK RTM 135 | Minor fixes for systems which only have a "Microsoft Basic Renderer" device 136 | 137 | September 2013 (11.03) 138 | Removed dependencies on the D3DX9 and D3DX11 libraries, so DXUT no longer requires the legacy DirectX SDK to build. 139 | It does require the d3dcompiler.h header from the Windows 8.x SDK. 140 | Includes standalone DDSTextureLoader, WICTexureLoader, ScreenGrab, and DxErr modules. 141 | Removed support for Direct3D 9 and Windows XP 142 | Deleted the DXUTDevice9.h/.cpp, SDKSound.h/.cpp, and SDKWaveFile.h/.cpp files 143 | Deleted legacy support for MCE relaunch 144 | General C++ code cleanups (nullptr, auto keyword, C++ style casting, Safer CRT, etc.) which are 145 | compatible with Visual C++ 2010 and 2012 146 | SAL2 annotation and /analyze cleanup 147 | Added DXUTCompileFromFile, DXUTCreateShaderResourceViewFromFile, DXUTCreateTextureFromFile, DXUTSaveTextureToFile helpers 148 | Added '-forcewarp' command-line switch 149 | Added support for DXGI 1.1 and 1.2 formats 150 | Added Direct3D 11.1 Device/Context state 151 | Support Feature Level 11.1 when available 152 | 153 | June 2010 (11.02) 154 | The DirectX SDK (June 2010) included an update to DXUT11. This is the last version to support Visual Studio 2008, 155 | Windows XP, or Direct3D 9. The source code is located in Samples\C++\DXUT11. 156 | 157 | February 2010 (11.01) 158 | An update was shipped with the DirectX SDK (February 2010). This is the last version to support Visual Studio 2005. 159 | The source code is located in Samples\C++\DXUT11. 160 | 161 | August 2009 (11.00) 162 | The initial release of DXUT11 was in DirectX SDK (August 2009). The source code is located in Samples\C++\DXUT11. 163 | This was a port of the original DXUT which supported Direct3D 10 / Direct3D 9 applications on Windows XP and Windows Vista. 164 | -------------------------------------------------------------------------------- /DXUT/Optional/DXUTsettingsdlg.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: DXUTSettingsDlg.h 3 | // 4 | // Copyright (c) Microsoft Corporation. All rights reserved. 5 | // Licensed under the MIT License. 6 | // 7 | // http://go.microsoft.com/fwlink/?LinkId=320437 8 | //-------------------------------------------------------------------------------------- 9 | #pragma once 10 | 11 | //-------------------------------------------------------------------------------------- 12 | // Header Includes 13 | //-------------------------------------------------------------------------------------- 14 | #include "DXUTgui.h" 15 | 16 | //-------------------------------------------------------------------------------------- 17 | // Control IDs 18 | //-------------------------------------------------------------------------------------- 19 | #define DXUTSETTINGSDLG_STATIC -1 20 | #define DXUTSETTINGSDLG_OK 1 21 | #define DXUTSETTINGSDLG_CANCEL 2 22 | #define DXUTSETTINGSDLG_ADAPTER 3 23 | #define DXUTSETTINGSDLG_DEVICE_TYPE 4 24 | #define DXUTSETTINGSDLG_WINDOWED 5 25 | #define DXUTSETTINGSDLG_FULLSCREEN 6 26 | #define DXUTSETTINGSDLG_RESOLUTION_SHOW_ALL 26 27 | #define DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT 28 28 | #define DXUTSETTINGSDLG_D3D11_ADAPTER_OUTPUT_LABEL 29 29 | #define DXUTSETTINGSDLG_D3D11_RESOLUTION 30 30 | #define DXUTSETTINGSDLG_D3D11_RESOLUTION_LABEL 31 31 | #define DXUTSETTINGSDLG_D3D11_REFRESH_RATE 32 32 | #define DXUTSETTINGSDLG_D3D11_REFRESH_RATE_LABEL 33 33 | #define DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT 34 34 | #define DXUTSETTINGSDLG_D3D11_BACK_BUFFER_FORMAT_LABEL 35 35 | #define DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT 36 36 | #define DXUTSETTINGSDLG_D3D11_MULTISAMPLE_COUNT_LABEL 37 37 | #define DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY 38 38 | #define DXUTSETTINGSDLG_D3D11_MULTISAMPLE_QUALITY_LABEL 39 39 | #define DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL 40 40 | #define DXUTSETTINGSDLG_D3D11_PRESENT_INTERVAL_LABEL 41 41 | #define DXUTSETTINGSDLG_D3D11_DEBUG_DEVICE 42 42 | #define DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL 43 43 | #define DXUTSETTINGSDLG_D3D11_FEATURE_LEVEL_LABEL 44 44 | 45 | #define DXUTSETTINGSDLG_MODE_CHANGE_ACCEPT 58 46 | #define DXUTSETTINGSDLG_MODE_CHANGE_REVERT 59 47 | #define DXUTSETTINGSDLG_STATIC_MODE_CHANGE_TIMEOUT 60 48 | #define DXUTSETTINGSDLG_WINDOWED_GROUP 0x0100 49 | 50 | #define TOTAL_FEATURE_LEVELS 9 51 | 52 | //-------------------------------------------------------------------------------------- 53 | // Dialog for selection of device settings 54 | // Use DXUTGetD3DSettingsDialog() to access global instance 55 | // To control the contents of the dialog, use the CD3D11Enumeration class. 56 | //-------------------------------------------------------------------------------------- 57 | class CD3DSettingsDlg 58 | { 59 | public: 60 | CD3DSettingsDlg(); 61 | ~CD3DSettingsDlg(); 62 | 63 | void Init( _In_ CDXUTDialogResourceManager* pManager ); 64 | void Init( _In_ CDXUTDialogResourceManager* pManager, _In_z_ LPCWSTR szControlTextureFileName ); 65 | void Init( _In_ CDXUTDialogResourceManager* pManager, _In_z_ LPCWSTR pszControlTextureResourcename, 66 | _In_ HMODULE hModule ); 67 | 68 | HRESULT Refresh(); 69 | void OnRender( _In_ float fElapsedTime ); 70 | 71 | HRESULT OnD3D11CreateDevice( _In_ ID3D11Device* pd3dDevice ); 72 | HRESULT OnD3D11ResizedSwapChain( _In_ ID3D11Device* pd3dDevice, 73 | _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc ); 74 | void OnD3D11DestroyDevice(); 75 | 76 | CDXUTDialog* GetDialogControl() { return &m_Dialog; } 77 | bool IsActive() const { return m_bActive; } 78 | void SetActive( _In_ bool bActive ) 79 | { 80 | m_bActive = bActive; 81 | if( bActive ) Refresh(); 82 | } 83 | 84 | LRESULT MsgProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); 85 | 86 | protected: 87 | friend CD3DSettingsDlg* WINAPI DXUTGetD3DSettingsDialog(); 88 | 89 | void CreateControls(); 90 | void SetSelectedD3D11RefreshRate( _In_ DXGI_RATIONAL RefreshRate ); 91 | HRESULT UpdateD3D11Resolutions(); 92 | HRESULT UpdateD3D11RefreshRates(); 93 | 94 | void OnEvent( _In_ UINT nEvent, _In_ int nControlID, _In_ CDXUTControl* pControl ); 95 | 96 | static void WINAPI StaticOnEvent( _In_ UINT nEvent, _In_ int nControlID, _In_ CDXUTControl* pControl, _In_opt_ void* pUserData ); 97 | static void WINAPI StaticOnModeChangeTimer( _In_ UINT nIDEvent, _In_opt_ void* pUserContext ); 98 | 99 | CD3D11EnumAdapterInfo* GetCurrentD3D11AdapterInfo() const; 100 | CD3D11EnumDeviceInfo* GetCurrentD3D11DeviceInfo() const; 101 | CD3D11EnumOutputInfo* GetCurrentD3D11OutputInfo() const; 102 | CD3D11EnumDeviceSettingsCombo* GetCurrentD3D11DeviceSettingsCombo() const; 103 | 104 | void AddAdapter( _In_z_ const WCHAR* strDescription, _In_ UINT iAdapter ); 105 | UINT GetSelectedAdapter() const; 106 | 107 | void SetWindowed( _In_ bool bWindowed ); 108 | bool IsWindowed() const; 109 | 110 | // D3D11 111 | void AddD3D11DeviceType( _In_ D3D_DRIVER_TYPE devType ); 112 | D3D_DRIVER_TYPE GetSelectedD3D11DeviceType() const; 113 | 114 | void AddD3D11AdapterOutput( _In_z_ const WCHAR* strName, _In_ UINT nOutput ); 115 | UINT GetSelectedD3D11AdapterOutput() const; 116 | 117 | void AddD3D11Resolution( _In_ DWORD dwWidth, _In_ DWORD dwHeight ); 118 | void GetSelectedD3D11Resolution( _Out_ DWORD* pdwWidth, _Out_ DWORD* pdwHeight ) const; 119 | 120 | void AddD3D11FeatureLevel( _In_ D3D_FEATURE_LEVEL fl ); 121 | D3D_FEATURE_LEVEL GetSelectedFeatureLevel() const; 122 | 123 | void AddD3D11RefreshRate( _In_ DXGI_RATIONAL RefreshRate ); 124 | DXGI_RATIONAL GetSelectedD3D11RefreshRate() const; 125 | 126 | void AddD3D11BackBufferFormat( _In_ DXGI_FORMAT format ); 127 | DXGI_FORMAT GetSelectedD3D11BackBufferFormat() const; 128 | 129 | void AddD3D11MultisampleCount( _In_ UINT count ); 130 | UINT GetSelectedD3D11MultisampleCount() const; 131 | 132 | void AddD3D11MultisampleQuality( _In_ UINT Quality ); 133 | UINT GetSelectedD3D11MultisampleQuality() const; 134 | 135 | DWORD GetSelectedD3D11PresentInterval() const; 136 | bool GetSelectedDebugDeviceValue() const; 137 | 138 | HRESULT OnD3D11ResolutionChanged (); 139 | HRESULT OnFeatureLevelChanged(); 140 | HRESULT OnAdapterChanged(); 141 | HRESULT OnDeviceTypeChanged(); 142 | HRESULT OnWindowedFullScreenChanged(); 143 | HRESULT OnAdapterOutputChanged(); 144 | HRESULT OnRefreshRateChanged(); 145 | HRESULT OnBackBufferFormatChanged(); 146 | HRESULT OnMultisampleTypeChanged(); 147 | HRESULT OnMultisampleQualityChanged(); 148 | HRESULT OnPresentIntervalChanged(); 149 | HRESULT OnDebugDeviceChanged(); 150 | 151 | void UpdateModeChangeTimeoutText( _In_ int nSecRemaining ); 152 | 153 | CDXUTDialog* m_pActiveDialog; 154 | CDXUTDialog m_Dialog; 155 | CDXUTDialog m_RevertModeDialog; 156 | int m_nRevertModeTimeout; 157 | UINT m_nIDEvent; 158 | bool m_bActive; 159 | 160 | D3D_FEATURE_LEVEL m_Levels[TOTAL_FEATURE_LEVELS]; 161 | 162 | }; 163 | 164 | 165 | CD3DSettingsDlg* WINAPI DXUTGetD3DSettingsDialog(); 166 | -------------------------------------------------------------------------------- /DXUT/Core/DXUTDevice11.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: DXUTDevice11.h 3 | // 4 | // Enumerates D3D adapters, devices, modes, etc. 5 | // 6 | // Copyright (c) Microsoft Corporation. All rights reserved. 7 | // Licensed under the MIT License. 8 | // 9 | // http://go.microsoft.com/fwlink/?LinkId=320437 10 | //-------------------------------------------------------------------------------------- 11 | #pragma once 12 | 13 | void DXUTApplyDefaultDeviceSettings(DXUTDeviceSettings *modifySettings); 14 | 15 | //-------------------------------------------------------------------------------------- 16 | // Functions to get bit depth from formats 17 | //-------------------------------------------------------------------------------------- 18 | HRESULT WINAPI DXUTGetD3D11AdapterDisplayMode( _In_ UINT AdapterOrdinal, _In_ UINT Output, _Out_ DXGI_MODE_DESC* pModeDesc ); 19 | 20 | 21 | 22 | 23 | //-------------------------------------------------------------------------------------- 24 | // Optional memory create/destory functions. If not call, these will be called automatically 25 | //-------------------------------------------------------------------------------------- 26 | HRESULT WINAPI DXUTCreateD3D11Enumeration(); 27 | void WINAPI DXUTDestroyD3D11Enumeration(); 28 | 29 | 30 | 31 | 32 | //-------------------------------------------------------------------------------------- 33 | // Forward declarations 34 | //-------------------------------------------------------------------------------------- 35 | class CD3D11EnumAdapterInfo; 36 | class CD3D11EnumDeviceInfo; 37 | class CD3D11EnumOutputInfo; 38 | struct CD3D11EnumDeviceSettingsCombo; 39 | 40 | 41 | 42 | //-------------------------------------------------------------------------------------- 43 | // Enumerates available Direct3D11 adapters, devices, modes, etc. 44 | //-------------------------------------------------------------------------------------- 45 | class CD3D11Enumeration 46 | { 47 | public: 48 | // These should be called before Enumerate(). 49 | // 50 | // Use these calls and the IsDeviceAcceptable to control the contents of 51 | // the enumeration object, which affects the device selection and the device settings dialog. 52 | void SetResolutionMinMax( _In_ UINT nMinWidth, _In_ UINT nMinHeight, _In_ UINT nMaxWidth, _In_ UINT nMaxHeight ); 53 | void SetRefreshMinMax( _In_ UINT nMin, _In_ UINT nMax ); 54 | void SetForceFeatureLevel( _In_ D3D_FEATURE_LEVEL forceFL) { m_forceFL = forceFL; } 55 | void SetMultisampleQualityMax( _In_ UINT nMax ); 56 | void ResetPossibleDepthStencilFormats(); 57 | void SetEnumerateAllAdapterFormats( _In_ bool bEnumerateAllAdapterFormats ); 58 | 59 | // Call Enumerate() to enumerate available D3D11 adapters, devices, modes, etc. 60 | bool HasEnumerated() { return m_bHasEnumerated; } 61 | HRESULT Enumerate( _In_ LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3D11DeviceAcceptableFunc, 62 | _In_opt_ void* pIsD3D11DeviceAcceptableFuncUserContext ); 63 | 64 | // These should be called after Enumerate() is called 65 | std::vector* GetAdapterInfoList(); 66 | CD3D11EnumAdapterInfo* GetAdapterInfo( _In_ UINT AdapterOrdinal ) const; 67 | CD3D11EnumDeviceInfo* GetDeviceInfo( _In_ UINT AdapterOrdinal, _In_ D3D_DRIVER_TYPE DeviceType ) const; 68 | CD3D11EnumOutputInfo* GetOutputInfo( _In_ UINT AdapterOrdinal, _In_ UINT Output ) const; 69 | CD3D11EnumDeviceSettingsCombo* GetDeviceSettingsCombo( _In_ DXUTD3D11DeviceSettings* pDeviceSettings ) const { return GetDeviceSettingsCombo( pDeviceSettings->AdapterOrdinal, pDeviceSettings->sd.BufferDesc.Format, pDeviceSettings->sd.Windowed ); } 70 | CD3D11EnumDeviceSettingsCombo* GetDeviceSettingsCombo( _In_ UINT AdapterOrdinal, _In_ DXGI_FORMAT BackBufferFormat, _In_ BOOL Windowed ) const; 71 | D3D_FEATURE_LEVEL GetWARPFeaturevel() const { return m_warpFL; } 72 | D3D_FEATURE_LEVEL GetREFFeaturevel() const { return m_refFL; } 73 | 74 | ~CD3D11Enumeration(); 75 | 76 | private: 77 | friend HRESULT WINAPI DXUTCreateD3D11Enumeration(); 78 | 79 | // Use DXUTGetD3D11Enumeration() to access global instance 80 | CD3D11Enumeration(); 81 | 82 | bool m_bHasEnumerated; 83 | LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE m_IsD3D11DeviceAcceptableFunc; 84 | void* m_pIsD3D11DeviceAcceptableFuncUserContext; 85 | 86 | std::vector m_DepthStencilPossibleList; 87 | 88 | bool m_bEnumerateAllAdapterFormats; 89 | D3D_FEATURE_LEVEL m_forceFL; 90 | D3D_FEATURE_LEVEL m_warpFL; 91 | D3D_FEATURE_LEVEL m_refFL; 92 | 93 | std::vector m_AdapterInfoList; 94 | 95 | HRESULT EnumerateOutputs( _In_ CD3D11EnumAdapterInfo *pAdapterInfo ); 96 | HRESULT EnumerateDevices( _In_ CD3D11EnumAdapterInfo *pAdapterInfo ); 97 | HRESULT EnumerateDeviceCombos( _In_ CD3D11EnumAdapterInfo* pAdapterInfo ); 98 | HRESULT EnumerateDeviceCombosNoAdapter( _In_ CD3D11EnumAdapterInfo* pAdapterInfo ); 99 | 100 | HRESULT EnumerateDisplayModes( _In_ CD3D11EnumOutputInfo *pOutputInfo ); 101 | void BuildMultiSampleQualityList( _In_ DXGI_FORMAT fmt, _In_ CD3D11EnumDeviceSettingsCombo* pDeviceCombo ); 102 | void ClearAdapterInfoList(); 103 | }; 104 | 105 | CD3D11Enumeration* WINAPI DXUTGetD3D11Enumeration(_In_ bool bForceEnumerate = false, _In_ bool EnumerateAllAdapterFormats = true, _In_ D3D_FEATURE_LEVEL forceFL = ((D3D_FEATURE_LEVEL )0) ); 106 | 107 | 108 | #define DXGI_MAX_DEVICE_IDENTIFIER_STRING 128 109 | 110 | //-------------------------------------------------------------------------------------- 111 | // A class describing an adapter which contains a unique adapter ordinal 112 | // that is installed on the system 113 | //-------------------------------------------------------------------------------------- 114 | class CD3D11EnumAdapterInfo 115 | { 116 | const CD3D11EnumAdapterInfo &operator = ( const CD3D11EnumAdapterInfo &rhs ); 117 | 118 | public: 119 | CD3D11EnumAdapterInfo() : 120 | AdapterOrdinal( 0 ), 121 | m_pAdapter( nullptr ), 122 | bAdapterUnavailable(false) 123 | { 124 | *szUniqueDescription = 0; 125 | memset( &AdapterDesc, 0, sizeof(AdapterDesc) ); 126 | } 127 | ~CD3D11EnumAdapterInfo(); 128 | 129 | UINT AdapterOrdinal; 130 | DXGI_ADAPTER_DESC AdapterDesc; 131 | WCHAR szUniqueDescription[DXGI_MAX_DEVICE_IDENTIFIER_STRING]; 132 | IDXGIAdapter *m_pAdapter; 133 | bool bAdapterUnavailable; 134 | 135 | std::vector outputInfoList; // Array of CD3D11EnumOutputInfo* 136 | std::vector deviceInfoList; // Array of CD3D11EnumDeviceInfo* 137 | // List of CD3D11EnumDeviceSettingsCombo* with a unique set 138 | // of BackBufferFormat, and Windowed 139 | std::vector deviceSettingsComboList; 140 | }; 141 | 142 | 143 | class CD3D11EnumOutputInfo 144 | { 145 | const CD3D11EnumOutputInfo &operator = ( const CD3D11EnumOutputInfo &rhs ); 146 | 147 | public: 148 | CD3D11EnumOutputInfo() : 149 | AdapterOrdinal( 0 ), 150 | Output( 0 ), 151 | m_pOutput( nullptr ) {} 152 | ~CD3D11EnumOutputInfo(); 153 | 154 | UINT AdapterOrdinal; 155 | UINT Output; 156 | IDXGIOutput* m_pOutput; 157 | DXGI_OUTPUT_DESC Desc; 158 | 159 | std::vector displayModeList; // Array of supported D3DDISPLAYMODEs 160 | }; 161 | 162 | 163 | //-------------------------------------------------------------------------------------- 164 | // A class describing a Direct3D11 device that contains a unique supported driver type 165 | //-------------------------------------------------------------------------------------- 166 | class CD3D11EnumDeviceInfo 167 | { 168 | const CD3D11EnumDeviceInfo& operator =( const CD3D11EnumDeviceInfo& rhs ); 169 | 170 | public: 171 | ~CD3D11EnumDeviceInfo(); 172 | 173 | UINT AdapterOrdinal; 174 | D3D_DRIVER_TYPE DeviceType; 175 | D3D_FEATURE_LEVEL SelectedLevel; 176 | D3D_FEATURE_LEVEL MaxLevel; 177 | BOOL ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x; 178 | }; 179 | 180 | 181 | //-------------------------------------------------------------------------------------- 182 | // A struct describing device settings that contains a unique combination of 183 | // adapter format, back buffer format, and windowed that is compatible with a 184 | // particular Direct3D device and the app. 185 | //-------------------------------------------------------------------------------------- 186 | struct CD3D11EnumDeviceSettingsCombo 187 | { 188 | UINT AdapterOrdinal; 189 | D3D_DRIVER_TYPE DeviceType; 190 | DXGI_FORMAT BackBufferFormat; 191 | BOOL Windowed; 192 | UINT Output; 193 | 194 | std::vector multiSampleCountList; // List of valid sampling counts (multisampling) 195 | std::vector multiSampleQualityList; // List of number of quality levels for each multisample count 196 | 197 | CD3D11EnumAdapterInfo* pAdapterInfo; 198 | CD3D11EnumDeviceInfo* pDeviceInfo; 199 | CD3D11EnumOutputInfo* pOutputInfo; 200 | }; 201 | 202 | float DXUTRankD3D11DeviceCombo( _In_ CD3D11EnumDeviceSettingsCombo* pDeviceSettingsCombo, 203 | _In_ DXUTD3D11DeviceSettings* pOptimalDeviceSettings, 204 | _Out_ int &bestModeIndex, 205 | _Out_ int &bestMSAAIndex 206 | ); 207 | -------------------------------------------------------------------------------- /DXUT/Optional/DXUTLockFreePipe.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // DXUTLockFreePipe.h 3 | // 4 | // See the "Lockless Programming Considerations for Xbox 360 and Microsoft Windows" 5 | // article for more details. 6 | // 7 | // http://msdn.microsoft.com/en-us/library/ee418650.aspx 8 | // 9 | // Copyright (c) Microsoft Corporation. All rights reserved. 10 | // Licensed under the MIT License. 11 | // 12 | // http://go.microsoft.com/fwlink/?LinkId=320437 13 | //-------------------------------------------------------------------------------------- 14 | #pragma once 15 | 16 | #include 17 | #include 18 | 19 | #pragma pack(push) 20 | #pragma pack(8) 21 | #include 22 | #pragma pack (pop) 23 | 24 | extern "C" 25 | void _ReadWriteBarrier(); 26 | #pragma intrinsic(_ReadWriteBarrier) 27 | 28 | // Prevent the compiler from rearranging loads 29 | // and stores, sufficiently for read-acquire 30 | // and write-release. This is sufficient on 31 | // x86 and x64. 32 | #define DXUTImportBarrier _ReadWriteBarrier 33 | #define DXUTExportBarrier _ReadWriteBarrier 34 | 35 | // 36 | // Pipe class designed for use by at most two threads: one reader, one writer. 37 | // Access by more than two threads isn't guaranteed to be safe. 38 | // 39 | // In order to provide efficient access the size of the buffer is passed 40 | // as a template parameter and restricted to powers of two less than 31. 41 | // 42 | 43 | template class DXUTLockFreePipe 44 | { 45 | public: 46 | DXUTLockFreePipe() : m_readOffset( 0 ), 47 | m_writeOffset( 0 ) 48 | { 49 | } 50 | 51 | DWORD GetBufferSize() const 52 | { 53 | return c_cbBufferSize; 54 | } 55 | 56 | __forceinline unsigned long BytesAvailable() const 57 | { 58 | return m_writeOffset - m_readOffset; 59 | } 60 | 61 | bool __forceinline Read( _Out_writes_(cbDest) void* pvDest, _In_ unsigned long cbDest ) 62 | { 63 | // Store the read and write offsets into local variables--this is 64 | // essentially a snapshot of their values so that they stay constant 65 | // for the duration of the function (and so we don't end up with cache 66 | // misses due to false sharing). 67 | DWORD readOffset = m_readOffset; 68 | DWORD writeOffset = m_writeOffset; 69 | 70 | // Compare the two offsets to see if we have anything to read. 71 | // Note that we don't do anything to synchronize the offsets here. 72 | // Really there's not much we *can* do unless we're willing to completely 73 | // synchronize access to the entire object. We have to assume that as we 74 | // read, someone else may be writing, and the write offset we have now 75 | // may be out of date by the time we read it. Fortunately that's not a 76 | // very big deal. We might miss reading some data that was just written. 77 | // But the assumption is that we'll be back before long to grab more data 78 | // anyway. 79 | // 80 | // Note that this comparison works because we're careful to constrain 81 | // the total buffer size to be a power of 2, which means it will divide 82 | // evenly into ULONG_MAX+1. That, and the fact that the offsets are 83 | // unsigned, means that the calculation returns correct results even 84 | // when the values wrap around. 85 | DWORD cbAvailable = writeOffset - readOffset; 86 | if( cbDest > cbAvailable ) 87 | { 88 | return false; 89 | } 90 | 91 | // The data has been made available, but we need to make sure 92 | // that our view on the data is up to date -- at least as up to 93 | // date as the control values we just read. We need to prevent 94 | // the compiler or CPU from moving any of the data reads before 95 | // the control value reads. This import barrier serves this 96 | // purpose, on Xbox 360 and on Windows. 97 | 98 | // Reading a control value and then having a barrier is known 99 | // as a "read-acquire." 100 | DXUTImportBarrier(); 101 | 102 | unsigned char* pbDest = ( unsigned char* )pvDest; 103 | 104 | unsigned long actualReadOffset = readOffset & c_sizeMask; 105 | unsigned long bytesLeft = cbDest; 106 | 107 | // 108 | // Copy from the tail, then the head. Note that there's no explicit 109 | // check to see if the write offset comes between the read offset 110 | // and the end of the buffer--that particular condition is implicitly 111 | // checked by the comparison with AvailableToRead(), above. If copying 112 | // cbDest bytes off the tail would cause us to cross the write offset, 113 | // then the previous comparison would have failed since that would imply 114 | // that there were less than cbDest bytes available to read. 115 | // 116 | unsigned long cbTailBytes = std::min( bytesLeft, c_cbBufferSize - actualReadOffset ); 117 | memcpy( pbDest, m_pbBuffer + actualReadOffset, cbTailBytes ); 118 | bytesLeft -= cbTailBytes; 119 | 120 | if( bytesLeft ) 121 | { 122 | memcpy( pbDest + cbTailBytes, m_pbBuffer, bytesLeft ); 123 | } 124 | 125 | // When we update the read offset we are, effectively, 'freeing' buffer 126 | // memory so that the writing thread can use it. We need to make sure that 127 | // we don't free the memory before we have finished reading it. That is, 128 | // we need to make sure that the write to m_readOffset can't get reordered 129 | // above the reads of the buffer data. The only way to guarantee this is to 130 | // have an export barrier to prevent both compiler and CPU rearrangements. 131 | DXUTExportBarrier(); 132 | 133 | // Advance the read offset. From the CPUs point of view this is several 134 | // operations--read, modify, store--and we'd normally want to make sure that 135 | // all of the operations happened atomically. But in the case of a single 136 | // reader, only one thread updates this value and so the only operation that 137 | // must be atomic is the store. That's lucky, because 32-bit aligned stores are 138 | // atomic on all modern processors. 139 | // 140 | readOffset += cbDest; 141 | m_readOffset = readOffset; 142 | 143 | return true; 144 | } 145 | 146 | bool __forceinline Write( _In_reads_(cbSrc) const void* pvSrc, _In_ unsigned long cbSrc ) 147 | { 148 | // Reading the read offset here has the same caveats as reading 149 | // the write offset had in the Read() function above. 150 | DWORD readOffset = m_readOffset; 151 | DWORD writeOffset = m_writeOffset; 152 | 153 | // Compute the available write size. This comparison relies on 154 | // the fact that the buffer size is always a power of 2, and the 155 | // offsets are unsigned integers, so that when the write pointer 156 | // wraps around the subtraction still yields a value (assuming 157 | // we haven't messed up somewhere else) between 0 and c_cbBufferSize - 1. 158 | DWORD cbAvailable = c_cbBufferSize - ( writeOffset - readOffset ); 159 | if( cbSrc > cbAvailable ) 160 | { 161 | return false; 162 | } 163 | 164 | // It is theoretically possible for writes of the data to be reordered 165 | // above the reads to see if the data is available. Improbable perhaps, 166 | // but possible. This barrier guarantees that the reordering will not 167 | // happen. 168 | DXUTImportBarrier(); 169 | 170 | // Write the data 171 | const unsigned char* pbSrc = ( const unsigned char* )pvSrc; 172 | unsigned long actualWriteOffset = writeOffset & c_sizeMask; 173 | unsigned long bytesLeft = cbSrc; 174 | 175 | // See the explanation in the Read() function as to why we don't 176 | // explicitly check against the read offset here. 177 | unsigned long cbTailBytes = std::min( bytesLeft, c_cbBufferSize - actualWriteOffset ); 178 | memcpy( m_pbBuffer + actualWriteOffset, pbSrc, cbTailBytes ); 179 | bytesLeft -= cbTailBytes; 180 | 181 | if( bytesLeft ) 182 | { 183 | memcpy( m_pbBuffer, pbSrc + cbTailBytes, bytesLeft ); 184 | } 185 | 186 | // Now it's time to update the write offset, but since the updated position 187 | // of the write offset will imply that there's data to be read, we need to 188 | // make sure that the data all actually gets written before the update to 189 | // the write offset. The writes could be reordered by the compiler (on any 190 | // platform) or by the CPU (on Xbox 360). We need a barrier which prevents 191 | // the writes from being reordered past each other. 192 | // 193 | // Having a barrier and then writing a control value is called "write-release." 194 | DXUTExportBarrier(); 195 | 196 | // See comments in Read() as to why this operation isn't interlocked. 197 | writeOffset += cbSrc; 198 | m_writeOffset = writeOffset; 199 | 200 | return true; 201 | } 202 | 203 | private: 204 | // Values derived from the buffer size template parameter 205 | // 206 | const static BYTE c_cbBufferSizeLog2 = __min( cbBufferSizeLog2, 31 ); 207 | const static DWORD c_cbBufferSize = ( 1 << c_cbBufferSizeLog2 ); 208 | const static DWORD c_sizeMask = c_cbBufferSize - 1; 209 | 210 | // Leave these private and undefined to prevent their use 211 | DXUTLockFreePipe( const DXUTLockFreePipe& ); 212 | DXUTLockFreePipe& operator =( const DXUTLockFreePipe& ); 213 | 214 | // Member data 215 | // 216 | BYTE m_pbBuffer[c_cbBufferSize]; 217 | // Note that these offsets are not clamped to the buffer size. 218 | // Instead the calculations rely on wrapping at ULONG_MAX+1. 219 | // See the comments in Read() for details. 220 | volatile DWORD __declspec( align( 4 ) ) m_readOffset; 221 | volatile DWORD __declspec( align( 4 ) ) m_writeOffset; 222 | }; -------------------------------------------------------------------------------- /DXUT/Core/DXUTmisc.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: DXUTMisc.h 3 | // 4 | // Helper functions for Direct3D programming. 5 | // 6 | // Copyright (c) Microsoft Corporation. All rights reserved. 7 | // Licensed under the MIT License. 8 | // 9 | // http://go.microsoft.com/fwlink/?LinkId=320437 10 | //-------------------------------------------------------------------------------------- 11 | #pragma once 12 | 13 | //-------------------------------------------------------------------------------------- 14 | // XInput helper state/function 15 | // This performs extra processing on XInput gamepad data to make it slightly more convenient to use 16 | // 17 | // Example usage: 18 | // 19 | // DXUT_GAMEPAD gamepad[4]; 20 | // for( DWORD iPort=0; iPortSetPrivateData( WKPDID_D3DDebugObjectName, (UINT)strlen(pstrName), pstrName ); 186 | } 187 | inline void DXUT_SetDebugName( _In_ ID3D11Device* pObj, _In_z_ const CHAR* pstrName ) 188 | { 189 | if ( pObj ) 190 | pObj->SetPrivateData( WKPDID_D3DDebugObjectName, (UINT)strlen(pstrName), pstrName ); 191 | } 192 | inline void DXUT_SetDebugName( _In_ ID3D11DeviceChild* pObj, _In_z_ const CHAR* pstrName ) 193 | { 194 | if ( pObj ) 195 | pObj->SetPrivateData( WKPDID_D3DDebugObjectName, (UINT)strlen(pstrName), pstrName ); 196 | } 197 | #else 198 | #define DXUT_SetDebugName( pObj, pstrName ) 199 | #endif 200 | 201 | 202 | //-------------------------------------------------------------------------------------- 203 | // Some D3DPERF APIs take a color that can be used when displaying user events in 204 | // performance analysis tools. The following constants are provided for your 205 | // convenience, but you can use any colors you like. 206 | //-------------------------------------------------------------------------------------- 207 | const DWORD DXUT_PERFEVENTCOLOR = 0xFFC86464; 208 | const DWORD DXUT_PERFEVENTCOLOR2 = 0xFF64C864; 209 | const DWORD DXUT_PERFEVENTCOLOR3 = 0xFF6464C8; 210 | 211 | //-------------------------------------------------------------------------------------- 212 | // The following macros provide a convenient way for your code to call the D3DPERF 213 | // functions only when PROFILE is defined. If PROFILE is not defined (as for the final 214 | // release version of a program), these macros evaluate to nothing, so no detailed event 215 | // information is embedded in your shipping program. It is recommended that you create 216 | // and use three build configurations for your projects: 217 | // Debug (nonoptimized code, asserts active, PROFILE defined to assist debugging) 218 | // Profile (optimized code, asserts disabled, PROFILE defined to assist optimization) 219 | // Release (optimized code, asserts disabled, PROFILE not defined) 220 | //-------------------------------------------------------------------------------------- 221 | #ifdef PROFILE 222 | // PROFILE is defined, so these macros call the D3DPERF functions 223 | #define DXUT_BeginPerfEvent( color, pstrMessage ) DXUT_Dynamic_D3DPERF_BeginEvent( color, pstrMessage ) 224 | #define DXUT_EndPerfEvent() DXUT_Dynamic_D3DPERF_EndEvent() 225 | #define DXUT_SetPerfMarker( color, pstrMessage ) DXUT_Dynamic_D3DPERF_SetMarker( color, pstrMessage ) 226 | #else 227 | // PROFILE is not defined, so these macros do nothing 228 | #define DXUT_BeginPerfEvent( color, pstrMessage ) (__noop) 229 | #define DXUT_EndPerfEvent() (__noop) 230 | #define DXUT_SetPerfMarker( color, pstrMessage ) (__noop) 231 | #endif 232 | 233 | //-------------------------------------------------------------------------------------- 234 | // CDXUTPerfEventGenerator is a helper class that makes it easy to attach begin and end 235 | // events to a block of code. Simply define a CDXUTPerfEventGenerator variable anywhere 236 | // in a block of code, and the class's constructor will call DXUT_BeginPerfEvent when 237 | // the block of code begins, and the class's destructor will call DXUT_EndPerfEvent when 238 | // the block ends. 239 | //-------------------------------------------------------------------------------------- 240 | class CDXUTPerfEventGenerator 241 | { 242 | public: 243 | CDXUTPerfEventGenerator( _In_ DWORD color, _In_z_ LPCWSTR pstrMessage ) 244 | { 245 | #ifdef PROFILE 246 | DXUT_BeginPerfEvent( color, pstrMessage ); 247 | #else 248 | UNREFERENCED_PARAMETER(color); 249 | UNREFERENCED_PARAMETER(pstrMessage); 250 | #endif 251 | } 252 | ~CDXUTPerfEventGenerator() 253 | { 254 | DXUT_EndPerfEvent(); 255 | } 256 | }; 257 | 258 | 259 | //-------------------------------------------------------------------------------------- 260 | // Multimon handling to support OSes with or without multimon API support. 261 | // Purposely avoiding the use of multimon.h so DXUT.lib doesn't require 262 | // COMPILE_MULTIMON_STUBS and cause complication with MFC or other users of multimon.h 263 | //-------------------------------------------------------------------------------------- 264 | #ifndef MONITOR_DEFAULTTOPRIMARY 265 | #define MONITORINFOF_PRIMARY 0x00000001 266 | #define MONITOR_DEFAULTTONULL 0x00000000 267 | #define MONITOR_DEFAULTTOPRIMARY 0x00000001 268 | #define MONITOR_DEFAULTTONEAREST 0x00000002 269 | typedef struct tagMONITORINFO 270 | { 271 | DWORD cbSize; 272 | RECT rcMonitor; 273 | RECT rcWork; 274 | DWORD dwFlags; 275 | } MONITORINFO, *LPMONITORINFO; 276 | typedef struct tagMONITORINFOEXW : public tagMONITORINFO 277 | { 278 | WCHAR szDevice[CCHDEVICENAME]; 279 | } MONITORINFOEXW, *LPMONITORINFOEXW; 280 | typedef MONITORINFOEXW MONITORINFOEX; 281 | typedef LPMONITORINFOEXW LPMONITORINFOEX; 282 | #endif 283 | 284 | HMONITOR WINAPI DXUTMonitorFromWindow( _In_ HWND hWnd, _In_ DWORD dwFlags ); 285 | HMONITOR WINAPI DXUTMonitorFromRect( _In_ LPCRECT lprcScreenCoords, _In_ DWORD dwFlags ); 286 | BOOL WINAPI DXUTGetMonitorInfo( _In_ HMONITOR hMonitor, _Out_ LPMONITORINFO lpMonitorInfo ); 287 | void WINAPI DXUTGetDesktopResolution( _In_ UINT AdapterOrdinal, _Out_ UINT* pWidth, _Out_ UINT* pHeight ); 288 | 289 | 290 | //-------------------------------------------------------------------------------------- 291 | // Helper functions to create SRGB formats from typeless formats and vice versa 292 | //-------------------------------------------------------------------------------------- 293 | DXGI_FORMAT MAKE_SRGB( _In_ DXGI_FORMAT format ); 294 | DXGI_FORMAT MAKE_TYPELESS( _In_ DXGI_FORMAT format ); 295 | -------------------------------------------------------------------------------- /DXUT/Core/DXUT.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: DXUT.h 3 | // 4 | // Copyright (c) Microsoft Corporation. All rights reserved. 5 | // Licensed under the MIT License. 6 | // 7 | // http://go.microsoft.com/fwlink/?LinkId=320437 8 | //-------------------------------------------------------------------------------------- 9 | #pragma once 10 | 11 | #ifndef UNICODE 12 | #error "DXUT requires a Unicode build." 13 | #endif 14 | 15 | #ifndef STRICT 16 | #define STRICT 17 | #endif 18 | 19 | // If app hasn't choosen, set to work with Windows Vista and beyond 20 | #ifndef WINVER 21 | #define WINVER 0x0600 22 | #endif 23 | #ifndef _WIN32_WINDOWS 24 | #define _WIN32_WINDOWS 0x0600 25 | #endif 26 | #ifndef _WIN32_WINNT 27 | #define _WIN32_WINNT 0x0600 28 | #endif 29 | 30 | #if defined(USE_DIRECT3D11_4) && !defined(USE_DIRECT3D11_3) 31 | #define USE_DIRECT3D11_3 32 | #endif 33 | 34 | #if (_WIN32_WINNT >= 0x0A00) && !defined(USE_DIRECT3D11_3) 35 | #define USE_DIRECT3D11_3 36 | #endif 37 | 38 | #if (_WIN32_WINNT >= 0x0603) && !defined(USE_DIRECT3D11_2) 39 | #define USE_DIRECT3D11_2 40 | #endif 41 | 42 | #if defined(USE_DIRECT3D11_3) && !defined(USE_DIRECT3D11_2) 43 | #define USE_DIRECT3D11_2 44 | #endif 45 | 46 | // #define DXUT_AUTOLIB to automatically include the libs needed for DXUT 47 | #ifdef DXUT_AUTOLIB 48 | #pragma comment( lib, "comctl32.lib" ) 49 | #pragma comment( lib, "dxguid.lib" ) 50 | #pragma comment( lib, "d3dcompiler.lib" ) 51 | #pragma comment( lib, "ole32.lib" ) 52 | #pragma comment( lib, "uuid.lib" ) 53 | #endif 54 | 55 | #pragma warning( disable : 4481 ) 56 | 57 | // Standard Windows includes 58 | #if !defined(NOMINMAX) 59 | #define NOMINMAX 60 | #endif 61 | 62 | #include 63 | #include 64 | #include 65 | #include // for InitCommonControls() 66 | #include // for ExtractIcon() 67 | #include // for placement new 68 | #include 69 | #include 70 | #include 71 | #include 72 | 73 | // CRT's memory leak detection 74 | #if defined(DEBUG) || defined(_DEBUG) 75 | #include 76 | #endif 77 | 78 | // Direct3D11 includes 79 | #include 80 | #include 81 | #include 82 | #include 83 | 84 | #ifdef USE_DIRECT3D11_2 85 | #include 86 | #endif 87 | 88 | #ifdef USE_DIRECT3D11_3 89 | #include 90 | #endif 91 | 92 | #ifdef USE_DIRECT3D11_4 93 | #include 94 | #endif 95 | 96 | // DirectXMath includes 97 | #include 98 | #include 99 | 100 | // WIC includes 101 | #include 102 | 103 | // XInput includes 104 | #include 105 | 106 | // HRESULT translation for Direct3D and other APIs 107 | #include "dxerr.h" 108 | 109 | // STL includes 110 | #include 111 | #include 112 | #include 113 | 114 | #if defined(DEBUG) || defined(_DEBUG) 115 | #ifndef V 116 | #define V(x) { hr = (x); if( FAILED(hr) ) { DXUTTrace( __FILE__, (DWORD)__LINE__, hr, L#x, true ); } } 117 | #endif 118 | #ifndef V_RETURN 119 | #define V_RETURN(x) { hr = (x); if( FAILED(hr) ) { return DXUTTrace( __FILE__, (DWORD)__LINE__, hr, L#x, true ); } } 120 | #endif 121 | #else 122 | #ifndef V 123 | #define V(x) { hr = (x); } 124 | #endif 125 | #ifndef V_RETURN 126 | #define V_RETURN(x) { hr = (x); if( FAILED(hr) ) { return hr; } } 127 | #endif 128 | #endif 129 | 130 | #ifndef SAFE_DELETE 131 | #define SAFE_DELETE(p) { if (p) { delete (p); (p) = nullptr; } } 132 | #endif 133 | #ifndef SAFE_DELETE_ARRAY 134 | #define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p) = nullptr; } } 135 | #endif 136 | #ifndef SAFE_RELEASE 137 | #define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = nullptr; } } 138 | #endif 139 | 140 | #ifndef D3DCOLOR_ARGB 141 | #define D3DCOLOR_ARGB(a,r,g,b) \ 142 | ((DWORD)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff))) 143 | #endif 144 | 145 | #define DXUT_VERSION 1118 146 | 147 | //-------------------------------------------------------------------------------------- 148 | // Structs 149 | //-------------------------------------------------------------------------------------- 150 | struct DXUTD3D11DeviceSettings 151 | { 152 | UINT AdapterOrdinal; 153 | D3D_DRIVER_TYPE DriverType; 154 | UINT Output; 155 | DXGI_SWAP_CHAIN_DESC sd; 156 | UINT32 CreateFlags; 157 | UINT32 SyncInterval; 158 | DWORD PresentFlags; 159 | bool AutoCreateDepthStencil; // DXUT will create the depth stencil resource and view if true 160 | DXGI_FORMAT AutoDepthStencilFormat; 161 | D3D_FEATURE_LEVEL DeviceFeatureLevel; 162 | }; 163 | 164 | struct DXUTDeviceSettings 165 | { 166 | D3D_FEATURE_LEVEL MinimumFeatureLevel; 167 | DXUTD3D11DeviceSettings d3d11; 168 | }; 169 | 170 | 171 | //-------------------------------------------------------------------------------------- 172 | // Error codes 173 | //-------------------------------------------------------------------------------------- 174 | #define DXUTERR_NODIRECT3D MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0901) 175 | #define DXUTERR_NOCOMPATIBLEDEVICES MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0902) 176 | #define DXUTERR_MEDIANOTFOUND MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0903) 177 | #define DXUTERR_NONZEROREFCOUNT MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0904) 178 | #define DXUTERR_CREATINGDEVICE MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0905) 179 | #define DXUTERR_RESETTINGDEVICE MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0906) 180 | #define DXUTERR_CREATINGDEVICEOBJECTS MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0907) 181 | #define DXUTERR_RESETTINGDEVICEOBJECTS MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0908) 182 | #define DXUTERR_DEVICEREMOVED MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x090A) 183 | 184 | 185 | //-------------------------------------------------------------------------------------- 186 | // Callback registration 187 | //-------------------------------------------------------------------------------------- 188 | 189 | // General callbacks 190 | typedef void (CALLBACK *LPDXUTCALLBACKFRAMEMOVE)( _In_ double fTime, _In_ float fElapsedTime, _In_opt_ void* pUserContext ); 191 | typedef void (CALLBACK *LPDXUTCALLBACKKEYBOARD)( _In_ UINT nChar, _In_ bool bKeyDown, _In_ bool bAltDown, _In_opt_ void* pUserContext ); 192 | typedef void (CALLBACK *LPDXUTCALLBACKMOUSE)( _In_ bool bLeftButtonDown, _In_ bool bRightButtonDown, _In_ bool bMiddleButtonDown, 193 | _In_ bool bSideButton1Down, _In_ bool bSideButton2Down, _In_ int nMouseWheelDelta, 194 | _In_ int xPos, _In_ int yPos, _In_opt_ void* pUserContext ); 195 | typedef LRESULT (CALLBACK *LPDXUTCALLBACKMSGPROC)( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam, 196 | _Out_ bool* pbNoFurtherProcessing, _In_opt_ void* pUserContext ); 197 | typedef void (CALLBACK *LPDXUTCALLBACKTIMER)( _In_ UINT idEvent, _In_opt_ void* pUserContext ); 198 | typedef bool (CALLBACK *LPDXUTCALLBACKMODIFYDEVICESETTINGS)( _In_ DXUTDeviceSettings* pDeviceSettings, _In_opt_ void* pUserContext ); 199 | typedef bool (CALLBACK *LPDXUTCALLBACKDEVICEREMOVED)( _In_opt_ void* pUserContext ); 200 | 201 | class CD3D11EnumAdapterInfo; 202 | class CD3D11EnumDeviceInfo; 203 | 204 | // Direct3D 11 callbacks 205 | typedef bool (CALLBACK *LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE)( _In_ const CD3D11EnumAdapterInfo *AdapterInfo, _In_ UINT Output, _In_ const CD3D11EnumDeviceInfo *DeviceInfo, 206 | _In_ DXGI_FORMAT BackBufferFormat, _In_ bool bWindowed, _In_opt_ void* pUserContext ); 207 | typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D11DEVICECREATED)( _In_ ID3D11Device* pd3dDevice, _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, _In_opt_ void* pUserContext ); 208 | typedef HRESULT (CALLBACK *LPDXUTCALLBACKD3D11SWAPCHAINRESIZED)( _In_ ID3D11Device* pd3dDevice, _In_ IDXGISwapChain *pSwapChain, _In_ const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, _In_opt_ void* pUserContext ); 209 | typedef void (CALLBACK *LPDXUTCALLBACKD3D11FRAMERENDER)( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3dImmediateContext, _In_ double fTime, _In_ float fElapsedTime, _In_opt_ void* pUserContext ); 210 | typedef void (CALLBACK *LPDXUTCALLBACKD3D11SWAPCHAINRELEASING)( _In_opt_ void* pUserContext ); 211 | typedef void (CALLBACK *LPDXUTCALLBACKD3D11DEVICEDESTROYED)( _In_opt_ void* pUserContext ); 212 | 213 | // General callbacks 214 | void WINAPI DXUTSetCallbackFrameMove( _In_ LPDXUTCALLBACKFRAMEMOVE pCallback, _In_opt_ void* pUserContext = nullptr ); 215 | void WINAPI DXUTSetCallbackKeyboard( _In_ LPDXUTCALLBACKKEYBOARD pCallback, _In_opt_ void* pUserContext = nullptr ); 216 | void WINAPI DXUTSetCallbackMouse( _In_ LPDXUTCALLBACKMOUSE pCallback, bool bIncludeMouseMove = false, _In_opt_ void* pUserContext = nullptr ); 217 | void WINAPI DXUTSetCallbackMsgProc( _In_ LPDXUTCALLBACKMSGPROC pCallback, _In_opt_ void* pUserContext = nullptr ); 218 | void WINAPI DXUTSetCallbackDeviceChanging( _In_ LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallback, _In_opt_ void* pUserContext = nullptr ); 219 | void WINAPI DXUTSetCallbackDeviceRemoved( _In_ LPDXUTCALLBACKDEVICEREMOVED pCallback, _In_opt_ void* pUserContext = nullptr ); 220 | 221 | // Direct3D 11 callbacks 222 | void WINAPI DXUTSetCallbackD3D11DeviceAcceptable( _In_ LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE pCallback, _In_opt_ void* pUserContext = nullptr ); 223 | void WINAPI DXUTSetCallbackD3D11DeviceCreated( _In_ LPDXUTCALLBACKD3D11DEVICECREATED pCallback, _In_opt_ void* pUserContext = nullptr ); 224 | void WINAPI DXUTSetCallbackD3D11SwapChainResized( _In_ LPDXUTCALLBACKD3D11SWAPCHAINRESIZED pCallback, _In_opt_ void* pUserContext = nullptr ); 225 | void WINAPI DXUTSetCallbackD3D11FrameRender( _In_ LPDXUTCALLBACKD3D11FRAMERENDER pCallback, _In_opt_ void* pUserContext = nullptr ); 226 | void WINAPI DXUTSetCallbackD3D11SwapChainReleasing( _In_ LPDXUTCALLBACKD3D11SWAPCHAINRELEASING pCallback, _In_opt_ void* pUserContext = nullptr ); 227 | void WINAPI DXUTSetCallbackD3D11DeviceDestroyed( _In_ LPDXUTCALLBACKD3D11DEVICEDESTROYED pCallback, _In_opt_ void* pUserContext = nullptr ); 228 | 229 | 230 | //-------------------------------------------------------------------------------------- 231 | // Initialization 232 | //-------------------------------------------------------------------------------------- 233 | HRESULT WINAPI DXUTInit( _In_ bool bParseCommandLine = true, 234 | _In_ bool bShowMsgBoxOnError = true, 235 | _In_opt_ WCHAR* strExtraCommandLineParams = nullptr, 236 | _In_ bool bThreadSafeDXUT = false ); 237 | 238 | // Choose either DXUTCreateWindow or DXUTSetWindow. If using DXUTSetWindow, consider using DXUTStaticWndProc 239 | HRESULT WINAPI DXUTCreateWindow( _In_z_ const WCHAR* strWindowTitle = L"Direct3D Window", 240 | _In_opt_ HINSTANCE hInstance = nullptr, _In_opt_ HICON hIcon = nullptr, _In_opt_ HMENU hMenu = nullptr, 241 | _In_ int x = CW_USEDEFAULT, _In_ int y = CW_USEDEFAULT ); 242 | HRESULT WINAPI DXUTSetWindow( _In_ HWND hWndFocus, _In_ HWND hWndDeviceFullScreen, _In_ HWND hWndDeviceWindowed, _In_ bool bHandleMessages = true ); 243 | LRESULT CALLBACK DXUTStaticWndProc( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); 244 | 245 | // Choose either DXUTCreateDevice or DXUTCreateD3DDeviceFromSettings 246 | 247 | HRESULT WINAPI DXUTCreateDevice(_In_ D3D_FEATURE_LEVEL reqFL, _In_ bool bWindowed= true, _In_ int nSuggestedWidth =0,_In_ int nSuggestedHeight =0 ); 248 | HRESULT WINAPI DXUTCreateDeviceFromSettings( _In_ DXUTDeviceSettings* pDeviceSettings, _In_ bool bClipWindowToSingleAdapter = true ); 249 | 250 | // Choose either DXUTMainLoop or implement your own main loop 251 | HRESULT WINAPI DXUTMainLoop( _In_opt_ HACCEL hAccel = nullptr ); 252 | 253 | // If not using DXUTMainLoop consider using DXUTRender3DEnvironment 254 | void WINAPI DXUTRender3DEnvironment(); 255 | 256 | 257 | //-------------------------------------------------------------------------------------- 258 | // Common Tasks 259 | //-------------------------------------------------------------------------------------- 260 | HRESULT WINAPI DXUTToggleFullScreen(); 261 | HRESULT WINAPI DXUTToggleREF(); 262 | HRESULT WINAPI DXUTToggleWARP(); 263 | void WINAPI DXUTPause( _In_ bool bPauseTime, _In_ bool bPauseRendering ); 264 | void WINAPI DXUTSetConstantFrameTime( _In_ bool bConstantFrameTime, _In_ float fTimePerFrame = 0.0333f ); 265 | void WINAPI DXUTSetCursorSettings( _In_ bool bShowCursorWhenFullScreen = false, _In_ bool bClipCursorWhenFullScreen = false ); 266 | void WINAPI DXUTSetHotkeyHandling( _In_ bool bAltEnterToToggleFullscreen = true, _In_ bool bEscapeToQuit = true, _In_ bool bPauseToToggleTimePause = true ); 267 | void WINAPI DXUTSetMultimonSettings( _In_ bool bAutoChangeAdapter = true ); 268 | void WINAPI DXUTSetShortcutKeySettings( _In_ bool bAllowWhenFullscreen = false, _In_ bool bAllowWhenWindowed = true ); // Controls the Windows key, and accessibility shortcut keys 269 | void WINAPI DXUTSetWindowSettings( _In_ bool bCallDefWindowProc = true ); 270 | HRESULT WINAPI DXUTSetTimer( _In_ LPDXUTCALLBACKTIMER pCallbackTimer, _In_ float fTimeoutInSecs = 1.0f, _Out_opt_ UINT* pnIDEvent = nullptr, _In_opt_ void* pCallbackUserContext = nullptr ); 271 | HRESULT WINAPI DXUTKillTimer( _In_ UINT nIDEvent ); 272 | void WINAPI DXUTResetFrameworkState(); 273 | void WINAPI DXUTShutdown( _In_ int nExitCode = 0 ); 274 | void WINAPI DXUTSetIsInGammaCorrectMode( _In_ bool bGammaCorrect ); 275 | bool WINAPI DXUTGetMSAASwapChainCreated(); 276 | 277 | 278 | //-------------------------------------------------------------------------------------- 279 | // State Retrieval 280 | //-------------------------------------------------------------------------------------- 281 | 282 | // Direct3D 11.x (These do not addref unlike typical Get* APIs) 283 | IDXGIFactory1* WINAPI DXUTGetDXGIFactory(); 284 | IDXGISwapChain* WINAPI DXUTGetDXGISwapChain(); 285 | const DXGI_SURFACE_DESC* WINAPI DXUTGetDXGIBackBufferSurfaceDesc(); 286 | HRESULT WINAPI DXUTSetupD3D11Views( _In_ ID3D11DeviceContext* pd3dDeviceContext ); // Supports immediate or deferred context 287 | D3D_FEATURE_LEVEL WINAPI DXUTGetD3D11DeviceFeatureLevel(); // Returns the D3D11 devices current feature level 288 | ID3D11RenderTargetView* WINAPI DXUTGetD3D11RenderTargetView(); 289 | ID3D11DepthStencilView* WINAPI DXUTGetD3D11DepthStencilView(); 290 | 291 | ID3D11Device* WINAPI DXUTGetD3D11Device(); 292 | ID3D11DeviceContext* WINAPI DXUTGetD3D11DeviceContext(); 293 | 294 | ID3D11Device1* WINAPI DXUTGetD3D11Device1(); 295 | ID3D11DeviceContext1* WINAPI DXUTGetD3D11DeviceContext1(); 296 | 297 | #ifdef USE_DIRECT3D11_2 298 | ID3D11Device2* WINAPI DXUTGetD3D11Device2(); 299 | ID3D11DeviceContext2* WINAPI DXUTGetD3D11DeviceContext2(); 300 | #endif 301 | 302 | #ifdef USE_DIRECT3D11_3 303 | ID3D11Device3* WINAPI DXUTGetD3D11Device3(); 304 | ID3D11DeviceContext3* WINAPI DXUTGetD3D11DeviceContext3(); 305 | #endif 306 | 307 | #ifdef USE_DIRECT3D11_4 308 | ID3D11Device4* WINAPI DXUTGetD3D11Device4(); 309 | ID3D11DeviceContext4* WINAPI DXUTGetD3D11DeviceContext4(); 310 | #endif 311 | 312 | // General 313 | DXUTDeviceSettings WINAPI DXUTGetDeviceSettings(); 314 | HINSTANCE WINAPI DXUTGetHINSTANCE(); 315 | HWND WINAPI DXUTGetHWND(); 316 | HWND WINAPI DXUTGetHWNDFocus(); 317 | HWND WINAPI DXUTGetHWNDDeviceFullScreen(); 318 | HWND WINAPI DXUTGetHWNDDeviceWindowed(); 319 | RECT WINAPI DXUTGetWindowClientRect(); 320 | LONG WINAPI DXUTGetWindowWidth(); 321 | LONG WINAPI DXUTGetWindowHeight(); 322 | RECT WINAPI DXUTGetWindowClientRectAtModeChange(); // Useful for returning to windowed mode with the same resolution as before toggle to full screen mode 323 | RECT WINAPI DXUTGetFullsceenClientRectAtModeChange(); // Useful for returning to full screen mode with the same resolution as before toggle to windowed mode 324 | double WINAPI DXUTGetTime(); 325 | float WINAPI DXUTGetElapsedTime(); 326 | bool WINAPI DXUTIsWindowed(); 327 | bool WINAPI DXUTIsInGammaCorrectMode(); 328 | float WINAPI DXUTGetFPS(); 329 | LPCWSTR WINAPI DXUTGetWindowTitle(); 330 | LPCWSTR WINAPI DXUTGetFrameStats( _In_ bool bIncludeFPS = false ); 331 | LPCWSTR WINAPI DXUTGetDeviceStats(); 332 | 333 | bool WINAPI DXUTIsVsyncEnabled(); 334 | bool WINAPI DXUTIsRenderingPaused(); 335 | bool WINAPI DXUTIsTimePaused(); 336 | bool WINAPI DXUTIsActive(); 337 | int WINAPI DXUTGetExitCode(); 338 | bool WINAPI DXUTGetShowMsgBoxOnError(); 339 | bool WINAPI DXUTGetAutomation(); // Returns true if -automation parameter is used to launch the app 340 | bool WINAPI DXUTIsKeyDown( _In_ BYTE vKey ); // Pass a virtual-key code, ex. VK_F1, 'A', VK_RETURN, VK_LSHIFT, etc 341 | bool WINAPI DXUTWasKeyPressed( _In_ BYTE vKey ); // Like DXUTIsKeyDown() but return true only if the key was just pressed 342 | bool WINAPI DXUTIsMouseButtonDown( _In_ BYTE vButton ); // Pass a virtual-key code: VK_LBUTTON, VK_RBUTTON, VK_MBUTTON, VK_XBUTTON1, VK_XBUTTON2 343 | HRESULT WINAPI DXUTCreateState(); // Optional method to create DXUT's memory. If its not called by the application it will be automatically called when needed 344 | void WINAPI DXUTDestroyState(); // Optional method to destroy DXUT's memory. If its not called by the application it will be automatically called after the application exits WinMain 345 | 346 | //-------------------------------------------------------------------------------------- 347 | // DXUT core layer includes 348 | //-------------------------------------------------------------------------------------- 349 | #include "DXUTmisc.h" 350 | #include "DXUTDevice11.h" 351 | -------------------------------------------------------------------------------- /DXUT/Optional/SDKmesh.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: SDKMesh.h 3 | // 4 | // Disclaimer: 5 | // The SDK Mesh format (.sdkmesh) is not a recommended file format for shipping titles. 6 | // It was designed to meet the specific needs of the SDK samples. Any real-world 7 | // applications should avoid this file format in favor of a destination format that 8 | // meets the specific needs of the application. 9 | // 10 | // Copyright (c) Microsoft Corporation. All rights reserved. 11 | // Licensed under the MIT License. 12 | // 13 | // http://go.microsoft.com/fwlink/?LinkId=320437 14 | //-------------------------------------------------------------------------------------- 15 | #pragma once 16 | 17 | #undef D3DCOLOR_ARGB 18 | #include 19 | 20 | //-------------------------------------------------------------------------------------- 21 | // Hard Defines for the various structures 22 | //-------------------------------------------------------------------------------------- 23 | #define SDKMESH_FILE_VERSION 101 24 | #define MAX_VERTEX_ELEMENTS 32 25 | #define MAX_VERTEX_STREAMS 16 26 | #define MAX_FRAME_NAME 100 27 | #define MAX_MESH_NAME 100 28 | #define MAX_SUBSET_NAME 100 29 | #define MAX_MATERIAL_NAME 100 30 | #define MAX_TEXTURE_NAME MAX_PATH 31 | #define MAX_MATERIAL_PATH MAX_PATH 32 | #define INVALID_FRAME ((UINT)-1) 33 | #define INVALID_MESH ((UINT)-1) 34 | #define INVALID_MATERIAL ((UINT)-1) 35 | #define INVALID_SUBSET ((UINT)-1) 36 | #define INVALID_ANIMATION_DATA ((UINT)-1) 37 | #define INVALID_SAMPLER_SLOT ((UINT)-1) 38 | #define ERROR_RESOURCE_VALUE 1 39 | 40 | template BOOL IsErrorResource( TYPE data ) 41 | { 42 | if( ( TYPE )ERROR_RESOURCE_VALUE == data ) 43 | return TRUE; 44 | return FALSE; 45 | } 46 | //-------------------------------------------------------------------------------------- 47 | // Enumerated Types. 48 | //-------------------------------------------------------------------------------------- 49 | enum SDKMESH_PRIMITIVE_TYPE 50 | { 51 | PT_TRIANGLE_LIST = 0, 52 | PT_TRIANGLE_STRIP, 53 | PT_LINE_LIST, 54 | PT_LINE_STRIP, 55 | PT_POINT_LIST, 56 | PT_TRIANGLE_LIST_ADJ, 57 | PT_TRIANGLE_STRIP_ADJ, 58 | PT_LINE_LIST_ADJ, 59 | PT_LINE_STRIP_ADJ, 60 | PT_QUAD_PATCH_LIST, 61 | PT_TRIANGLE_PATCH_LIST, 62 | }; 63 | 64 | enum SDKMESH_INDEX_TYPE 65 | { 66 | IT_16BIT = 0, 67 | IT_32BIT, 68 | }; 69 | 70 | enum FRAME_TRANSFORM_TYPE 71 | { 72 | FTT_RELATIVE = 0, 73 | FTT_ABSOLUTE, //This is not currently used but is here to support absolute transformations in the future 74 | }; 75 | 76 | //-------------------------------------------------------------------------------------- 77 | // Structures. Unions with pointers are forced to 64bit. 78 | //-------------------------------------------------------------------------------------- 79 | #pragma pack(push,8) 80 | 81 | struct SDKMESH_HEADER 82 | { 83 | //Basic Info and sizes 84 | UINT Version; 85 | BYTE IsBigEndian; 86 | UINT64 HeaderSize; 87 | UINT64 NonBufferDataSize; 88 | UINT64 BufferDataSize; 89 | 90 | //Stats 91 | UINT NumVertexBuffers; 92 | UINT NumIndexBuffers; 93 | UINT NumMeshes; 94 | UINT NumTotalSubsets; 95 | UINT NumFrames; 96 | UINT NumMaterials; 97 | 98 | //Offsets to Data 99 | UINT64 VertexStreamHeadersOffset; 100 | UINT64 IndexStreamHeadersOffset; 101 | UINT64 MeshDataOffset; 102 | UINT64 SubsetDataOffset; 103 | UINT64 FrameDataOffset; 104 | UINT64 MaterialDataOffset; 105 | }; 106 | 107 | struct SDKMESH_VERTEX_BUFFER_HEADER 108 | { 109 | UINT64 NumVertices; 110 | UINT64 SizeBytes; 111 | UINT64 StrideBytes; 112 | D3DVERTEXELEMENT9 Decl[MAX_VERTEX_ELEMENTS]; 113 | union 114 | { 115 | UINT64 DataOffset; //(This also forces the union to 64bits) 116 | ID3D11Buffer* pVB11; 117 | }; 118 | }; 119 | 120 | struct SDKMESH_INDEX_BUFFER_HEADER 121 | { 122 | UINT64 NumIndices; 123 | UINT64 SizeBytes; 124 | UINT IndexType; 125 | union 126 | { 127 | UINT64 DataOffset; //(This also forces the union to 64bits) 128 | ID3D11Buffer* pIB11; 129 | }; 130 | }; 131 | 132 | struct SDKMESH_MESH 133 | { 134 | char Name[MAX_MESH_NAME]; 135 | BYTE NumVertexBuffers; 136 | UINT VertexBuffers[MAX_VERTEX_STREAMS]; 137 | UINT IndexBuffer; 138 | UINT NumSubsets; 139 | UINT NumFrameInfluences; //aka bones 140 | 141 | DirectX::XMFLOAT3 BoundingBoxCenter; 142 | DirectX::XMFLOAT3 BoundingBoxExtents; 143 | 144 | union 145 | { 146 | UINT64 SubsetOffset; //Offset to list of subsets (This also forces the union to 64bits) 147 | UINT* pSubsets; //Pointer to list of subsets 148 | }; 149 | union 150 | { 151 | UINT64 FrameInfluenceOffset; //Offset to list of frame influences (This also forces the union to 64bits) 152 | UINT* pFrameInfluences; //Pointer to list of frame influences 153 | }; 154 | }; 155 | 156 | struct SDKMESH_SUBSET 157 | { 158 | char Name[MAX_SUBSET_NAME]; 159 | UINT MaterialID; 160 | UINT PrimitiveType; 161 | UINT64 IndexStart; 162 | UINT64 IndexCount; 163 | UINT64 VertexStart; 164 | UINT64 VertexCount; 165 | }; 166 | 167 | struct SDKMESH_FRAME 168 | { 169 | char Name[MAX_FRAME_NAME]; 170 | UINT Mesh; 171 | UINT ParentFrame; 172 | UINT ChildFrame; 173 | UINT SiblingFrame; 174 | DirectX::XMFLOAT4X4 Matrix; 175 | UINT AnimationDataIndex; //Used to index which set of keyframes transforms this frame 176 | }; 177 | 178 | struct SDKMESH_MATERIAL 179 | { 180 | char Name[MAX_MATERIAL_NAME]; 181 | 182 | // Use MaterialInstancePath 183 | char MaterialInstancePath[MAX_MATERIAL_PATH]; 184 | 185 | // Or fall back to d3d8-type materials 186 | char DiffuseTexture[MAX_TEXTURE_NAME]; 187 | char NormalTexture[MAX_TEXTURE_NAME]; 188 | char SpecularTexture[MAX_TEXTURE_NAME]; 189 | 190 | DirectX::XMFLOAT4 Diffuse; 191 | DirectX::XMFLOAT4 Ambient; 192 | DirectX::XMFLOAT4 Specular; 193 | DirectX::XMFLOAT4 Emissive; 194 | float Power; 195 | 196 | union 197 | { 198 | UINT64 Force64_1; //Force the union to 64bits 199 | ID3D11Texture2D* pDiffuseTexture11; 200 | }; 201 | union 202 | { 203 | UINT64 Force64_2; //Force the union to 64bits 204 | ID3D11Texture2D* pNormalTexture11; 205 | }; 206 | union 207 | { 208 | UINT64 Force64_3; //Force the union to 64bits 209 | ID3D11Texture2D* pSpecularTexture11; 210 | }; 211 | 212 | union 213 | { 214 | UINT64 Force64_4; //Force the union to 64bits 215 | ID3D11ShaderResourceView* pDiffuseRV11; 216 | }; 217 | union 218 | { 219 | UINT64 Force64_5; //Force the union to 64bits 220 | ID3D11ShaderResourceView* pNormalRV11; 221 | }; 222 | union 223 | { 224 | UINT64 Force64_6; //Force the union to 64bits 225 | ID3D11ShaderResourceView* pSpecularRV11; 226 | }; 227 | 228 | }; 229 | 230 | struct SDKANIMATION_FILE_HEADER 231 | { 232 | UINT Version; 233 | BYTE IsBigEndian; 234 | UINT FrameTransformType; 235 | UINT NumFrames; 236 | UINT NumAnimationKeys; 237 | UINT AnimationFPS; 238 | UINT64 AnimationDataSize; 239 | UINT64 AnimationDataOffset; 240 | }; 241 | 242 | struct SDKANIMATION_DATA 243 | { 244 | DirectX::XMFLOAT3 Translation; 245 | DirectX::XMFLOAT4 Orientation; 246 | DirectX::XMFLOAT3 Scaling; 247 | }; 248 | 249 | struct SDKANIMATION_FRAME_DATA 250 | { 251 | char FrameName[MAX_FRAME_NAME]; 252 | union 253 | { 254 | UINT64 DataOffset; 255 | SDKANIMATION_DATA* pAnimationData; 256 | }; 257 | }; 258 | 259 | #pragma pack(pop) 260 | 261 | static_assert( sizeof(D3DVERTEXELEMENT9) == 8, "Direct3D9 Decl structure size incorrect" ); 262 | static_assert( sizeof(SDKMESH_HEADER)== 104, "SDK Mesh structure size incorrect" ); 263 | static_assert( sizeof(SDKMESH_VERTEX_BUFFER_HEADER) == 288, "SDK Mesh structure size incorrect" ); 264 | static_assert( sizeof(SDKMESH_INDEX_BUFFER_HEADER) == 32, "SDK Mesh structure size incorrect" ); 265 | static_assert( sizeof(SDKMESH_MESH) == 224, "SDK Mesh structure size incorrect" ); 266 | static_assert( sizeof(SDKMESH_SUBSET) == 144, "SDK Mesh structure size incorrect" ); 267 | static_assert( sizeof(SDKMESH_FRAME) == 184, "SDK Mesh structure size incorrect" ); 268 | static_assert( sizeof(SDKMESH_MATERIAL) == 1256, "SDK Mesh structure size incorrect" ); 269 | static_assert( sizeof(SDKANIMATION_FILE_HEADER) == 40, "SDK Mesh structure size incorrect" ); 270 | static_assert( sizeof(SDKANIMATION_DATA) == 40, "SDK Mesh structure size incorrect" ); 271 | static_assert( sizeof(SDKANIMATION_FRAME_DATA) == 112, "SDK Mesh structure size incorrect" ); 272 | 273 | #ifndef _CONVERTER_APP_ 274 | 275 | //-------------------------------------------------------------------------------------- 276 | // AsyncLoading callbacks 277 | //-------------------------------------------------------------------------------------- 278 | typedef void ( CALLBACK*LPCREATETEXTUREFROMFILE11 )( _In_ ID3D11Device* pDev, _In_z_ char* szFileName, 279 | _Outptr_ ID3D11ShaderResourceView** ppRV, _In_opt_ void* pContext ); 280 | typedef void ( CALLBACK*LPCREATEVERTEXBUFFER11 )( _In_ ID3D11Device* pDev, _Outptr_ ID3D11Buffer** ppBuffer, 281 | _In_ D3D11_BUFFER_DESC BufferDesc, _In_ void* pData, _In_opt_ void* pContext ); 282 | typedef void ( CALLBACK*LPCREATEINDEXBUFFER11 )( _In_ ID3D11Device* pDev, _Outptr_ ID3D11Buffer** ppBuffer, 283 | _In_ D3D11_BUFFER_DESC BufferDesc, _In_ void* pData, _In_opt_ void* pContext ); 284 | struct SDKMESH_CALLBACKS11 285 | { 286 | LPCREATETEXTUREFROMFILE11 pCreateTextureFromFile; 287 | LPCREATEVERTEXBUFFER11 pCreateVertexBuffer; 288 | LPCREATEINDEXBUFFER11 pCreateIndexBuffer; 289 | void* pContext; 290 | }; 291 | 292 | //-------------------------------------------------------------------------------------- 293 | // CDXUTSDKMesh class. This class reads the sdkmesh file format for use by the samples 294 | //-------------------------------------------------------------------------------------- 295 | class CDXUTSDKMesh 296 | { 297 | private: 298 | UINT m_NumOutstandingResources; 299 | bool m_bLoading; 300 | //BYTE* m_pBufferData; 301 | HANDLE m_hFile; 302 | HANDLE m_hFileMappingObject; 303 | std::vector m_MappedPointers; 304 | ID3D11Device* m_pDev11; 305 | ID3D11DeviceContext* m_pDevContext11; 306 | 307 | protected: 308 | //These are the pointers to the two chunks of data loaded in from the mesh file 309 | BYTE* m_pStaticMeshData; 310 | BYTE* m_pHeapData; 311 | BYTE* m_pAnimationData; 312 | BYTE** m_ppVertices; 313 | BYTE** m_ppIndices; 314 | 315 | //Keep track of the path 316 | WCHAR m_strPathW[MAX_PATH]; 317 | char m_strPath[MAX_PATH]; 318 | 319 | //General mesh info 320 | SDKMESH_HEADER* m_pMeshHeader; 321 | SDKMESH_VERTEX_BUFFER_HEADER* m_pVertexBufferArray; 322 | SDKMESH_INDEX_BUFFER_HEADER* m_pIndexBufferArray; 323 | SDKMESH_MESH* m_pMeshArray; 324 | SDKMESH_SUBSET* m_pSubsetArray; 325 | SDKMESH_FRAME* m_pFrameArray; 326 | SDKMESH_MATERIAL* m_pMaterialArray; 327 | 328 | // Adjacency information (not part of the m_pStaticMeshData, so it must be created and destroyed separately ) 329 | SDKMESH_INDEX_BUFFER_HEADER* m_pAdjacencyIndexBufferArray; 330 | 331 | //Animation 332 | SDKANIMATION_FILE_HEADER* m_pAnimationHeader; 333 | SDKANIMATION_FRAME_DATA* m_pAnimationFrameData; 334 | DirectX::XMFLOAT4X4* m_pBindPoseFrameMatrices; 335 | DirectX::XMFLOAT4X4* m_pTransformedFrameMatrices; 336 | DirectX::XMFLOAT4X4* m_pWorldPoseFrameMatrices; 337 | 338 | protected: 339 | void LoadMaterials( _In_ ID3D11Device* pd3dDevice, _In_reads_(NumMaterials) SDKMESH_MATERIAL* pMaterials, 340 | _In_ UINT NumMaterials, _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); 341 | 342 | HRESULT CreateVertexBuffer( _In_ ID3D11Device* pd3dDevice, 343 | _In_ SDKMESH_VERTEX_BUFFER_HEADER* pHeader, _In_reads_(pHeader->SizeBytes) void* pVertices, 344 | _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); 345 | 346 | HRESULT CreateIndexBuffer( _In_ ID3D11Device* pd3dDevice, 347 | _In_ SDKMESH_INDEX_BUFFER_HEADER* pHeader, _In_reads_(pHeader->SizeBytes) void* pIndices, 348 | _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); 349 | 350 | virtual HRESULT CreateFromFile( _In_opt_ ID3D11Device* pDev11, 351 | _In_z_ LPCWSTR szFileName, 352 | _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks11 = nullptr ); 353 | 354 | virtual HRESULT CreateFromMemory( _In_opt_ ID3D11Device* pDev11, 355 | _In_reads_(DataBytes) BYTE* pData, 356 | _In_ size_t DataBytes, 357 | _In_ bool bCopyStatic, 358 | _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks11 = nullptr ); 359 | 360 | //frame manipulation 361 | void TransformBindPoseFrame( _In_ UINT iFrame, _In_ DirectX::CXMMATRIX parentWorld ); 362 | void TransformFrame( _In_ UINT iFrame, _In_ DirectX::CXMMATRIX parentWorld, _In_ double fTime ); 363 | void TransformFrameAbsolute( _In_ UINT iFrame, _In_ double fTime ); 364 | 365 | //Direct3D 11 rendering helpers 366 | void RenderMesh( _In_ UINT iMesh, 367 | _In_ bool bAdjacent, 368 | _In_ ID3D11DeviceContext* pd3dDeviceContext, 369 | _In_ UINT iDiffuseSlot, 370 | _In_ UINT iNormalSlot, 371 | _In_ UINT iSpecularSlot ); 372 | void RenderFrame( _In_ UINT iFrame, 373 | _In_ bool bAdjacent, 374 | _In_ ID3D11DeviceContext* pd3dDeviceContext, 375 | _In_ UINT iDiffuseSlot, 376 | _In_ UINT iNormalSlot, 377 | _In_ UINT iSpecularSlot ); 378 | 379 | public: 380 | CDXUTSDKMesh(); 381 | virtual ~CDXUTSDKMesh(); 382 | 383 | virtual HRESULT Create( _In_ ID3D11Device* pDev11, _In_z_ LPCWSTR szFileName, _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); 384 | virtual HRESULT Create( _In_ ID3D11Device* pDev11, BYTE* pData, size_t DataBytes, _In_ bool bCopyStatic=false, 385 | _In_opt_ SDKMESH_CALLBACKS11* pLoaderCallbacks = nullptr ); 386 | virtual HRESULT LoadAnimation( _In_z_ const WCHAR* szFileName ); 387 | virtual void Destroy(); 388 | 389 | //Frame manipulation 390 | void TransformBindPose( _In_ DirectX::CXMMATRIX world ) { TransformBindPoseFrame( 0, world ); }; 391 | void TransformMesh( _In_ DirectX::CXMMATRIX world, _In_ double fTime ); 392 | 393 | //Direct3D 11 Rendering 394 | virtual void Render( _In_ ID3D11DeviceContext* pd3dDeviceContext, 395 | _In_ UINT iDiffuseSlot = INVALID_SAMPLER_SLOT, 396 | _In_ UINT iNormalSlot = INVALID_SAMPLER_SLOT, 397 | _In_ UINT iSpecularSlot = INVALID_SAMPLER_SLOT ); 398 | virtual void RenderAdjacent( _In_ ID3D11DeviceContext* pd3dDeviceContext, 399 | _In_ UINT iDiffuseSlot = INVALID_SAMPLER_SLOT, 400 | _In_ UINT iNormalSlot = INVALID_SAMPLER_SLOT, 401 | _In_ UINT iSpecularSlot = INVALID_SAMPLER_SLOT ); 402 | 403 | //Helpers (D3D11 specific) 404 | static D3D11_PRIMITIVE_TOPOLOGY GetPrimitiveType11( _In_ SDKMESH_PRIMITIVE_TYPE PrimType ); 405 | DXGI_FORMAT GetIBFormat11( _In_ UINT iMesh ) const; 406 | ID3D11Buffer* GetVB11( _In_ UINT iMesh, _In_ UINT iVB ) const; 407 | ID3D11Buffer* GetIB11( _In_ UINT iMesh ) const; 408 | SDKMESH_INDEX_TYPE GetIndexType( _In_ UINT iMesh ) const; 409 | 410 | ID3D11Buffer* GetAdjIB11( _In_ UINT iMesh ) const; 411 | 412 | //Helpers (general) 413 | const char* GetMeshPathA() const; 414 | const WCHAR* GetMeshPathW() const; 415 | UINT GetNumMeshes() const; 416 | UINT GetNumMaterials() const; 417 | UINT GetNumVBs() const; 418 | UINT GetNumIBs() const; 419 | 420 | ID3D11Buffer* GetVB11At( _In_ UINT iVB ) const; 421 | ID3D11Buffer* GetIB11At( _In_ UINT iIB ) const; 422 | 423 | BYTE* GetRawVerticesAt( _In_ UINT iVB ) const; 424 | BYTE* GetRawIndicesAt( _In_ UINT iIB ) const; 425 | 426 | SDKMESH_MATERIAL* GetMaterial( _In_ UINT iMaterial ) const; 427 | SDKMESH_MESH* GetMesh( _In_ UINT iMesh ) const; 428 | UINT GetNumSubsets( _In_ UINT iMesh ) const; 429 | SDKMESH_SUBSET* GetSubset( _In_ UINT iMesh, _In_ UINT iSubset ) const; 430 | UINT GetVertexStride( _In_ UINT iMesh, _In_ UINT iVB ) const; 431 | UINT GetNumFrames() const; 432 | SDKMESH_FRAME* GetFrame( _In_ UINT iFrame ) const; 433 | SDKMESH_FRAME* FindFrame( _In_z_ const char* pszName ) const; 434 | UINT64 GetNumVertices( _In_ UINT iMesh, _In_ UINT iVB ) const; 435 | UINT64 GetNumIndices( _In_ UINT iMesh ) const; 436 | DirectX::XMVECTOR GetMeshBBoxCenter( _In_ UINT iMesh ) const; 437 | DirectX::XMVECTOR GetMeshBBoxExtents( _In_ UINT iMesh ) const; 438 | UINT GetOutstandingResources() const; 439 | UINT GetOutstandingBufferResources() const; 440 | bool CheckLoadDone(); 441 | bool IsLoaded() const; 442 | bool IsLoading() const; 443 | void SetLoading( _In_ bool bLoading ); 444 | BOOL HadLoadingError() const; 445 | 446 | //Animation 447 | UINT GetNumInfluences( _In_ UINT iMesh ) const; 448 | DirectX::XMMATRIX GetMeshInfluenceMatrix( _In_ UINT iMesh, _In_ UINT iInfluence ) const; 449 | UINT GetAnimationKeyFromTime( _In_ double fTime ) const; 450 | DirectX::XMMATRIX GetWorldMatrix( _In_ UINT iFrameIndex ) const; 451 | DirectX::XMMATRIX GetInfluenceMatrix( _In_ UINT iFrameIndex ) const; 452 | bool GetAnimationProperties( _Out_ UINT* pNumKeys, _Out_ float* pFrameTime ) const; 453 | }; 454 | 455 | #endif 456 | 457 | -------------------------------------------------------------------------------- /DXUT/Optional/DXUTcamera.h: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: Camera.h 3 | // 4 | // Helper functions for Direct3D programming. 5 | // 6 | // Copyright (c) Microsoft Corporation. All rights reserved. 7 | // Licensed under the MIT License. 8 | // 9 | // http://go.microsoft.com/fwlink/?LinkId=320437 10 | //-------------------------------------------------------------------------------------- 11 | #pragma once 12 | 13 | //-------------------------------------------------------------------------------------- 14 | class CD3DArcBall 15 | { 16 | public: 17 | CD3DArcBall(); 18 | 19 | // Functions to change behavior 20 | void Reset(); 21 | void SetTranslationRadius( _In_ float fRadiusTranslation ) 22 | { 23 | m_fRadiusTranslation = fRadiusTranslation; 24 | } 25 | void SetWindow( _In_ INT nWidth, _In_ INT nHeight, _In_ float fRadius = 0.9f ) 26 | { 27 | m_nWidth = nWidth; 28 | m_nHeight = nHeight; 29 | m_fRadius = fRadius; 30 | m_vCenter.x = float(m_nWidth) / 2.0f; 31 | m_vCenter.y = float(m_nHeight) / 2.0f; 32 | } 33 | void SetOffset( _In_ INT nX, _In_ INT nY ) { m_Offset.x = nX; m_Offset.y = nY; } 34 | 35 | // Call these from client and use GetRotationMatrix() to read new rotation matrix 36 | void OnBegin( _In_ int nX, _In_ int nY ); // start the rotation (pass current mouse position) 37 | void OnMove( _In_ int nX, _In_ int nY ); // continue the rotation (pass current mouse position) 38 | void OnEnd(); // end the rotation 39 | 40 | // Or call this to automatically handle left, middle, right buttons 41 | LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); 42 | 43 | // Functions to get/set state 44 | DirectX::XMMATRIX GetRotationMatrix() const 45 | { 46 | using namespace DirectX; 47 | XMVECTOR q = XMLoadFloat4( &m_qNow ); 48 | return DirectX::XMMatrixRotationQuaternion( q ); 49 | } 50 | DirectX::XMMATRIX GetTranslationMatrix() const { return DirectX::XMLoadFloat4x4( &m_mTranslation ); } 51 | DirectX::XMMATRIX GetTranslationDeltaMatrix() const { return DirectX::XMLoadFloat4x4( &m_mTranslationDelta ); } 52 | bool IsBeingDragged() const { return m_bDrag; } 53 | DirectX::XMVECTOR GetQuatNow() const { return DirectX::XMLoadFloat4( &m_qNow ); } 54 | void SetQuatNow( _In_ DirectX::FXMVECTOR& q ) { DirectX::XMStoreFloat4( &m_qNow, q ); } 55 | 56 | static DirectX::XMVECTOR QuatFromBallPoints( _In_ DirectX::FXMVECTOR vFrom, _In_ DirectX::FXMVECTOR vTo ) 57 | { 58 | using namespace DirectX; 59 | 60 | XMVECTOR dot = XMVector3Dot( vFrom, vTo ); 61 | XMVECTOR vPart = XMVector3Cross( vFrom, vTo ); 62 | return XMVectorSelect( dot, vPart, g_XMSelect1110 ); 63 | } 64 | 65 | protected: 66 | DirectX::XMFLOAT4X4 m_mRotation; // Matrix for arc ball's orientation 67 | DirectX::XMFLOAT4X4 m_mTranslation; // Matrix for arc ball's position 68 | DirectX::XMFLOAT4X4 m_mTranslationDelta;// Matrix for arc ball's position 69 | 70 | POINT m_Offset; // window offset, or upper-left corner of window 71 | INT m_nWidth; // arc ball's window width 72 | INT m_nHeight; // arc ball's window height 73 | DirectX::XMFLOAT2 m_vCenter; // center of arc ball 74 | float m_fRadius; // arc ball's radius in screen coords 75 | float m_fRadiusTranslation; // arc ball's radius for translating the target 76 | 77 | DirectX::XMFLOAT4 m_qDown; // Quaternion before button down 78 | DirectX::XMFLOAT4 m_qNow; // Composite quaternion for current drag 79 | bool m_bDrag; // Whether user is dragging arc ball 80 | 81 | POINT m_ptLastMouse; // position of last mouse point 82 | DirectX::XMFLOAT3 m_vDownPt; // starting point of rotation arc 83 | DirectX::XMFLOAT3 m_vCurrentPt; // current point of rotation arc 84 | 85 | DirectX::XMVECTOR ScreenToVector( _In_ float fScreenPtX, _In_ float fScreenPtY ) 86 | { 87 | // Scale to screen 88 | float x = -( fScreenPtX - m_Offset.x - m_nWidth / 2 ) / ( m_fRadius * m_nWidth / 2 ); 89 | float y = ( fScreenPtY - m_Offset.y - m_nHeight / 2 ) / ( m_fRadius * m_nHeight / 2 ); 90 | 91 | float z = 0.0f; 92 | float mag = x * x + y * y; 93 | 94 | if( mag > 1.0f ) 95 | { 96 | float scale = 1.0f / sqrtf( mag ); 97 | x *= scale; 98 | y *= scale; 99 | } 100 | else 101 | z = sqrtf( 1.0f - mag ); 102 | 103 | return DirectX::XMVectorSet( x, y, z, 0 ); 104 | } 105 | }; 106 | 107 | 108 | //-------------------------------------------------------------------------------------- 109 | // used by CCamera to map WM_KEYDOWN keys 110 | //-------------------------------------------------------------------------------------- 111 | enum D3DUtil_CameraKeys 112 | { 113 | CAM_STRAFE_LEFT = 0, 114 | CAM_STRAFE_RIGHT, 115 | CAM_MOVE_FORWARD, 116 | CAM_MOVE_BACKWARD, 117 | CAM_MOVE_UP, 118 | CAM_MOVE_DOWN, 119 | CAM_RESET, 120 | CAM_CONTROLDOWN, 121 | CAM_MAX_KEYS, 122 | CAM_UNKNOWN = 0xFF 123 | }; 124 | 125 | #define KEY_WAS_DOWN_MASK 0x80 126 | #define KEY_IS_DOWN_MASK 0x01 127 | 128 | #define MOUSE_LEFT_BUTTON 0x01 129 | #define MOUSE_MIDDLE_BUTTON 0x02 130 | #define MOUSE_RIGHT_BUTTON 0x04 131 | #define MOUSE_WHEEL 0x08 132 | 133 | 134 | //-------------------------------------------------------------------------------------- 135 | // Simple base camera class that moves and rotates. The base class 136 | // records mouse and keyboard input for use by a derived class, and 137 | // keeps common state. 138 | //-------------------------------------------------------------------------------------- 139 | class CBaseCamera 140 | { 141 | public: 142 | CBaseCamera(); 143 | 144 | // Call these from client and use Get*Matrix() to read new matrices 145 | virtual LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); 146 | virtual void FrameMove( _In_ float fElapsedTime ) = 0; 147 | 148 | // Functions to change camera matrices 149 | virtual void Reset(); 150 | virtual void SetViewParams( _In_ DirectX::FXMVECTOR vEyePt, _In_ DirectX::FXMVECTOR vLookatPt ); 151 | virtual void SetProjParams( _In_ float fFOV, _In_ float fAspect, _In_ float fNearPlane, _In_ float fFarPlane ); 152 | 153 | // Functions to change behavior 154 | virtual void SetDragRect( _In_ const RECT& rc ) { m_rcDrag = rc; } 155 | void SetInvertPitch( _In_ bool bInvertPitch ) { m_bInvertPitch = bInvertPitch; } 156 | void SetDrag( _In_ bool bMovementDrag, _In_ float fTotalDragTimeToZero = 0.25f ) 157 | { 158 | m_bMovementDrag = bMovementDrag; 159 | m_fTotalDragTimeToZero = fTotalDragTimeToZero; 160 | } 161 | void SetEnableYAxisMovement( _In_ bool bEnableYAxisMovement ) { m_bEnableYAxisMovement = bEnableYAxisMovement; } 162 | void SetEnablePositionMovement( _In_ bool bEnablePositionMovement ) { m_bEnablePositionMovement = bEnablePositionMovement; } 163 | void SetClipToBoundary( _In_ bool bClipToBoundary, _In_opt_ DirectX::XMFLOAT3* pvMinBoundary, _In_opt_ DirectX::XMFLOAT3* pvMaxBoundary ) 164 | { 165 | m_bClipToBoundary = bClipToBoundary; 166 | if( pvMinBoundary ) m_vMinBoundary = *pvMinBoundary; 167 | if( pvMaxBoundary ) m_vMaxBoundary = *pvMaxBoundary; 168 | } 169 | void SetScalers( _In_ float fRotationScaler = 0.01f, _In_ float fMoveScaler = 5.0f ) 170 | { 171 | m_fRotationScaler = fRotationScaler; 172 | m_fMoveScaler = fMoveScaler; 173 | } 174 | void SetNumberOfFramesToSmoothMouseData( _In_ int nFrames ) { if( nFrames > 0 ) m_fFramesToSmoothMouseData = ( float )nFrames; } 175 | void SetResetCursorAfterMove( _In_ bool bResetCursorAfterMove ) { m_bResetCursorAfterMove = bResetCursorAfterMove; } 176 | 177 | // Functions to get state 178 | DirectX::XMMATRIX GetViewMatrix() const { return DirectX::XMLoadFloat4x4( &m_mView ); } 179 | DirectX::XMMATRIX GetProjMatrix() const { return DirectX::XMLoadFloat4x4( &m_mProj ); } 180 | DirectX::XMVECTOR GetEyePt() const { return DirectX::XMLoadFloat3( &m_vEye ); } 181 | DirectX::XMVECTOR GetLookAtPt() const { return DirectX::XMLoadFloat3( &m_vLookAt ); } 182 | float GetNearClip() const { return m_fNearPlane; } 183 | float GetFarClip() const { return m_fFarPlane; } 184 | 185 | bool IsBeingDragged() const { return ( m_bMouseLButtonDown || m_bMouseMButtonDown || m_bMouseRButtonDown ); } 186 | bool IsMouseLButtonDown() const { return m_bMouseLButtonDown; } 187 | bool IsMouseMButtonDown() const { return m_bMouseMButtonDown; } 188 | bool sMouseRButtonDown() const { return m_bMouseRButtonDown; } 189 | 190 | protected: 191 | // Functions to map a WM_KEYDOWN key to a D3DUtil_CameraKeys enum 192 | virtual D3DUtil_CameraKeys MapKey( _In_ UINT nKey ); 193 | 194 | bool IsKeyDown( _In_ BYTE key ) const { return( ( key & KEY_IS_DOWN_MASK ) == KEY_IS_DOWN_MASK ); } 195 | bool WasKeyDown( _In_ BYTE key ) const { return( ( key & KEY_WAS_DOWN_MASK ) == KEY_WAS_DOWN_MASK ); } 196 | 197 | DirectX::XMVECTOR ConstrainToBoundary( _In_ DirectX::FXMVECTOR v ) 198 | { 199 | using namespace DirectX; 200 | 201 | XMVECTOR vMin = XMLoadFloat3( &m_vMinBoundary ); 202 | XMVECTOR vMax = XMLoadFloat3( &m_vMaxBoundary ); 203 | 204 | // Constrain vector to a bounding box 205 | return XMVectorClamp( v, vMin, vMax ); 206 | } 207 | 208 | void UpdateMouseDelta(); 209 | void UpdateVelocity( _In_ float fElapsedTime ); 210 | void GetInput( _In_ bool bGetKeyboardInput, _In_ bool bGetMouseInput, _In_ bool bGetGamepadInput ); 211 | 212 | DirectX::XMFLOAT4X4 m_mView; // View matrix 213 | DirectX::XMFLOAT4X4 m_mProj; // Projection matrix 214 | 215 | DXUT_GAMEPAD m_GamePad[DXUT_MAX_CONTROLLERS]; // XInput controller state 216 | DirectX::XMFLOAT3 m_vGamePadLeftThumb; 217 | DirectX::XMFLOAT3 m_vGamePadRightThumb; 218 | double m_GamePadLastActive[DXUT_MAX_CONTROLLERS]; 219 | 220 | int m_cKeysDown; // Number of camera keys that are down. 221 | BYTE m_aKeys[CAM_MAX_KEYS]; // State of input - KEY_WAS_DOWN_MASK|KEY_IS_DOWN_MASK 222 | DirectX::XMFLOAT3 m_vKeyboardDirection; // Direction vector of keyboard input 223 | POINT m_ptLastMousePosition; // Last absolute position of mouse cursor 224 | int m_nCurrentButtonMask; // mask of which buttons are down 225 | int m_nMouseWheelDelta; // Amount of middle wheel scroll (+/-) 226 | DirectX::XMFLOAT2 m_vMouseDelta; // Mouse relative delta smoothed over a few frames 227 | float m_fFramesToSmoothMouseData; // Number of frames to smooth mouse data over 228 | DirectX::XMFLOAT3 m_vDefaultEye; // Default camera eye position 229 | DirectX::XMFLOAT3 m_vDefaultLookAt; // Default LookAt position 230 | DirectX::XMFLOAT3 m_vEye; // Camera eye position 231 | DirectX::XMFLOAT3 m_vLookAt; // LookAt position 232 | float m_fCameraYawAngle; // Yaw angle of camera 233 | float m_fCameraPitchAngle; // Pitch angle of camera 234 | 235 | RECT m_rcDrag; // Rectangle within which a drag can be initiated. 236 | DirectX::XMFLOAT3 m_vVelocity; // Velocity of camera 237 | DirectX::XMFLOAT3 m_vVelocityDrag; // Velocity drag force 238 | float m_fDragTimer; // Countdown timer to apply drag 239 | float m_fTotalDragTimeToZero; // Time it takes for velocity to go from full to 0 240 | DirectX::XMFLOAT2 m_vRotVelocity; // Velocity of camera 241 | 242 | float m_fFOV; // Field of view 243 | float m_fAspect; // Aspect ratio 244 | float m_fNearPlane; // Near plane 245 | float m_fFarPlane; // Far plane 246 | 247 | float m_fRotationScaler; // Scaler for rotation 248 | float m_fMoveScaler; // Scaler for movement 249 | 250 | bool m_bMouseLButtonDown; // True if left button is down 251 | bool m_bMouseMButtonDown; // True if middle button is down 252 | bool m_bMouseRButtonDown; // True if right button is down 253 | bool m_bMovementDrag; // If true, then camera movement will slow to a stop otherwise movement is instant 254 | bool m_bInvertPitch; // Invert the pitch axis 255 | bool m_bEnablePositionMovement; // If true, then the user can translate the camera/model 256 | bool m_bEnableYAxisMovement; // If true, then camera can move in the y-axis 257 | bool m_bClipToBoundary; // If true, then the camera will be clipped to the boundary 258 | bool m_bResetCursorAfterMove; // If true, the class will reset the cursor position so that the cursor always has space to move 259 | 260 | DirectX::XMFLOAT3 m_vMinBoundary; // Min point in clip boundary 261 | DirectX::XMFLOAT3 m_vMaxBoundary; // Max point in clip boundary 262 | }; 263 | 264 | 265 | //-------------------------------------------------------------------------------------- 266 | // Simple first person camera class that moves and rotates. 267 | // It allows yaw and pitch but not roll. It uses WM_KEYDOWN and 268 | // GetCursorPos() to respond to keyboard and mouse input and updates the 269 | // view matrix based on input. 270 | //-------------------------------------------------------------------------------------- 271 | class CFirstPersonCamera : public CBaseCamera 272 | { 273 | public: 274 | CFirstPersonCamera(); 275 | 276 | // Call these from client and use Get*Matrix() to read new matrices 277 | virtual void FrameMove( _In_ float fElapsedTime ) override; 278 | 279 | // Functions to change behavior 280 | void SetRotateButtons( _In_ bool bLeft, _In_ bool bMiddle, _In_ bool bRight, _In_ bool bRotateWithoutButtonDown = false ); 281 | 282 | // Functions to get state 283 | DirectX::XMMATRIX GetWorldMatrix() const { return DirectX::XMLoadFloat4x4( &m_mCameraWorld ); } 284 | 285 | DirectX::XMVECTOR GetWorldRight() const { return DirectX::XMLoadFloat3( reinterpret_cast( &m_mCameraWorld._11 ) ); } 286 | DirectX::XMVECTOR GetWorldUp() const { return DirectX::XMLoadFloat3( reinterpret_cast( &m_mCameraWorld._21 ) ); } 287 | DirectX::XMVECTOR GetWorldAhead() const { return DirectX::XMLoadFloat3( reinterpret_cast( &m_mCameraWorld._31 ) ); } 288 | DirectX::XMVECTOR GetEyePt() const { return DirectX::XMLoadFloat3( reinterpret_cast( &m_mCameraWorld._41 ) ); } 289 | 290 | protected: 291 | DirectX::XMFLOAT4X4 m_mCameraWorld; // World matrix of the camera (inverse of the view matrix) 292 | 293 | int m_nActiveButtonMask; // Mask to determine which button to enable for rotation 294 | bool m_bRotateWithoutButtonDown; 295 | }; 296 | 297 | 298 | //-------------------------------------------------------------------------------------- 299 | // Simple model viewing camera class that rotates around the object. 300 | //-------------------------------------------------------------------------------------- 301 | class CModelViewerCamera : public CBaseCamera 302 | { 303 | public: 304 | CModelViewerCamera(); 305 | 306 | // Call these from client and use Get*Matrix() to read new matrices 307 | virtual LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) override; 308 | virtual void FrameMove( _In_ float fElapsedTime ) override; 309 | 310 | // Functions to change behavior 311 | virtual void SetDragRect( _In_ const RECT& rc ) override; 312 | virtual void Reset() override; 313 | virtual void SetViewParams( _In_ DirectX::FXMVECTOR pvEyePt, _In_ DirectX::FXMVECTOR pvLookatPt ) override; 314 | void SetButtonMasks( _In_ int nRotateModelButtonMask = MOUSE_LEFT_BUTTON, _In_ int nZoomButtonMask = MOUSE_WHEEL, 315 | _In_ int nRotateCameraButtonMask = MOUSE_RIGHT_BUTTON ) 316 | { 317 | m_nRotateModelButtonMask = nRotateModelButtonMask, m_nZoomButtonMask = nZoomButtonMask; 318 | m_nRotateCameraButtonMask = nRotateCameraButtonMask; 319 | } 320 | void SetAttachCameraToModel( _In_ bool bEnable = false ) { m_bAttachCameraToModel = bEnable; } 321 | void SetWindow( _In_ int nWidth, _In_ int nHeight, _In_ float fArcballRadius=0.9f ) 322 | { 323 | m_WorldArcBall.SetWindow( nWidth, nHeight, fArcballRadius ); 324 | m_ViewArcBall.SetWindow( nWidth, nHeight, fArcballRadius ); 325 | } 326 | void SetRadius( _In_ float fDefaultRadius=5.0f, _In_ float fMinRadius=1.0f, _In_ float fMaxRadius=FLT_MAX ) 327 | { 328 | m_fDefaultRadius = m_fRadius = fDefaultRadius; m_fMinRadius = fMinRadius; m_fMaxRadius = fMaxRadius; 329 | m_bDragSinceLastUpdate = true; 330 | } 331 | void SetModelCenter( _In_ const DirectX::XMFLOAT3& vModelCenter ) { m_vModelCenter = vModelCenter; } 332 | void SetLimitPitch( _In_ bool bLimitPitch ) { m_bLimitPitch = bLimitPitch; } 333 | void SetViewQuat( _In_ DirectX::FXMVECTOR q ) 334 | { 335 | m_ViewArcBall.SetQuatNow( q ); 336 | m_bDragSinceLastUpdate = true; 337 | } 338 | void SetWorldQuat( _In_ DirectX::FXMVECTOR q ) 339 | { 340 | m_WorldArcBall.SetQuatNow( q ); 341 | m_bDragSinceLastUpdate = true; 342 | } 343 | 344 | // Functions to get state 345 | DirectX::XMMATRIX GetWorldMatrix() const { return DirectX::XMLoadFloat4x4( &m_mWorld ); } 346 | void SetWorldMatrix( _In_ DirectX::CXMMATRIX mWorld ) 347 | { 348 | XMStoreFloat4x4( &m_mWorld, mWorld ); 349 | m_bDragSinceLastUpdate = true; 350 | } 351 | 352 | protected: 353 | CD3DArcBall m_WorldArcBall; 354 | CD3DArcBall m_ViewArcBall; 355 | DirectX::XMFLOAT3 m_vModelCenter; 356 | DirectX::XMFLOAT4X4 m_mModelLastRot; // Last arcball rotation matrix for model 357 | DirectX::XMFLOAT4X4 m_mModelRot; // Rotation matrix of model 358 | DirectX::XMFLOAT4X4 m_mWorld; // World matrix of model 359 | 360 | int m_nRotateModelButtonMask; 361 | int m_nZoomButtonMask; 362 | int m_nRotateCameraButtonMask; 363 | 364 | bool m_bAttachCameraToModel; 365 | bool m_bLimitPitch; 366 | bool m_bDragSinceLastUpdate; // True if mouse drag has happened since last time FrameMove is called. 367 | float m_fRadius; // Distance from the camera to model 368 | float m_fDefaultRadius; // Distance from the camera to model 369 | float m_fMinRadius; // Min radius 370 | float m_fMaxRadius; // Max radius 371 | 372 | DirectX::XMFLOAT4X4 m_mCameraRotLast; 373 | }; 374 | 375 | 376 | //-------------------------------------------------------------------------------------- 377 | // Manages the mesh, direction, mouse events of a directional arrow that 378 | // rotates around a radius controlled by an arcball 379 | //-------------------------------------------------------------------------------------- 380 | class CDXUTDirectionWidget 381 | { 382 | public: 383 | CDXUTDirectionWidget(); 384 | 385 | LRESULT HandleMessages( _In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); 386 | 387 | HRESULT OnRender( _In_ DirectX::FXMVECTOR color, _In_ DirectX::CXMMATRIX pmView, _In_ DirectX::CXMMATRIX pmProj, _In_ DirectX::FXMVECTOR vEyePt ); 388 | 389 | DirectX::XMVECTOR GetLightDirection() const { return DirectX::XMLoadFloat3( &m_vCurrentDir ); } 390 | void SetLightDirection( _In_ DirectX::FXMVECTOR vDir ) 391 | { 392 | DirectX::XMStoreFloat3( &m_vCurrentDir, vDir ); 393 | m_vDefaultDir = m_vCurrentDir; 394 | } 395 | void SetLightDirection( _In_ DirectX::XMFLOAT3 vDir ) 396 | { 397 | m_vDefaultDir = m_vCurrentDir = vDir; 398 | } 399 | void SetButtonMask( _In_ int nRotate = MOUSE_RIGHT_BUTTON ) { m_nRotateMask = nRotate; } 400 | 401 | float GetRadius() const { return m_fRadius; } 402 | void SetRadius( _In_ float fRadius ) { m_fRadius = fRadius; } 403 | 404 | bool IsBeingDragged() { return m_ArcBall.IsBeingDragged(); } 405 | 406 | static HRESULT WINAPI StaticOnD3D11CreateDevice( _In_ ID3D11Device* pd3dDevice, _In_ ID3D11DeviceContext* pd3dImmediateContext ); 407 | static void WINAPI StaticOnD3D11DestroyDevice(); 408 | 409 | protected: 410 | HRESULT UpdateLightDir(); 411 | 412 | // TODO - need support for Direct3D 11 widget 413 | 414 | DirectX::XMFLOAT4X4 m_mRot; 415 | DirectX::XMFLOAT4X4 m_mRotSnapshot; 416 | float m_fRadius; 417 | int m_nRotateMask; 418 | CD3DArcBall m_ArcBall; 419 | DirectX::XMFLOAT3 m_vDefaultDir; 420 | DirectX::XMFLOAT3 m_vCurrentDir; 421 | DirectX::XMFLOAT4X4 m_mView; 422 | }; 423 | -------------------------------------------------------------------------------- /sph/sph_main.cpp: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: Tutorial08.cpp 3 | // 4 | // Basic introduction to DXUT 5 | // 6 | // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF 7 | // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO 8 | // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A 9 | // PARTICULAR PURPOSE. 10 | // 11 | // Copyright (c) Microsoft Corporation. All rights reserved. 12 | //-------------------------------------------------------------------------------------- 13 | #include "DXUT.h" 14 | #include "DXUTcamera.h" 15 | #include "DXUTgui.h" 16 | #include "DXUTsettingsDlg.h" 17 | #include "SDKmisc.h" 18 | 19 | #include "sph_interface.h" 20 | 21 | #pragma warning( disable : 4100 ) 22 | 23 | using namespace DirectX; 24 | 25 | //-------------------------------------------------------------------------------------- 26 | // Structures 27 | //-------------------------------------------------------------------------------------- 28 | struct PointVertex 29 | { 30 | XMFLOAT3 Pos; 31 | XMFLOAT4 Col; 32 | }; 33 | 34 | struct CBChangesEveryFrame 35 | { 36 | XMFLOAT4X4 mWorldViewProj; 37 | }; 38 | 39 | 40 | //-------------------------------------------------------------------------------------- 41 | // Global Variables 42 | //-------------------------------------------------------------------------------------- 43 | CModelViewerCamera g_Camera; // A model viewing camera 44 | CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs 45 | CD3DSettingsDlg g_SettingsDlg; // Device settings dialog 46 | CDXUTTextHelper* g_pTxtHelper = nullptr; 47 | CDXUTDialog g_HUD; // manages the 3D UI 48 | CDXUTDialog g_SampleUI; // dialog for sample specific controls 49 | 50 | ID3D11VertexShader* g_pVertexShader = nullptr; 51 | ID3D11PixelShader* g_pPixelShader = nullptr; 52 | ID3D11InputLayout* g_pVertexLayout = nullptr; 53 | ID3D11Buffer* g_pParticleVertexBuffer = nullptr; 54 | ID3D11Buffer* g_pBoxVertexBuffer = nullptr; 55 | ID3D11Buffer* g_pBoxIndexBuffer = nullptr; 56 | ID3D11Buffer* g_pCBChangesEveryFrame = nullptr; 57 | ID3D11BlendState* g_pBlendState = nullptr; 58 | XMMATRIX g_World; 59 | SPH::System* g_pSPHSystem = nullptr; 60 | SPH::float_3 g_wallMin = { -25, 00, -25 }; 61 | SPH::float_3 g_wallMax = { 25, 30, 25 }; 62 | 63 | //-------------------------------------------------------------------------------------- 64 | // UI control IDs 65 | //-------------------------------------------------------------------------------------- 66 | #define IDC_TOGGLEFULLSCREEN 1 67 | #define IDC_TOGGLEREF 2 68 | #define IDC_CHANGEDEVICE 3 69 | #define IDC_TOGGLEWARP 4 70 | #define IDC_SPH_RESET 5 71 | 72 | #define MAX_PARTICLE_COUNTS 4096 73 | 74 | //-------------------------------------------------------------------------------------- 75 | void resetSPHSystem(void) 76 | { 77 | SPH::float_3 fluid_min = { -15, 5, -15 }; 78 | SPH::float_3 fluid_max = { 15, 28, 15 }; 79 | SPH::float_3 gravity = { 0.0, -9.8f, 0 }; 80 | g_pSPHSystem->init(MAX_PARTICLE_COUNTS, &g_wallMin, &g_wallMax, &fluid_min, &fluid_max, &gravity); 81 | } 82 | 83 | //-------------------------------------------------------------------------------------- 84 | // Reject any D3D11 devices that aren't acceptable by returning false 85 | //-------------------------------------------------------------------------------------- 86 | bool CALLBACK IsD3D11DeviceAcceptable(const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, 87 | DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext) 88 | { 89 | return true; 90 | } 91 | 92 | 93 | //-------------------------------------------------------------------------------------- 94 | // Called right before creating a D3D device, allowing the app to modify the device settings as needed 95 | //-------------------------------------------------------------------------------------- 96 | bool CALLBACK ModifyDeviceSettings(DXUTDeviceSettings* pDeviceSettings, void* pUserContext) 97 | { 98 | return true; 99 | } 100 | 101 | 102 | //-------------------------------------------------------------------------------------- 103 | // Create any D3D11 resources that aren't dependant on the back buffer 104 | //-------------------------------------------------------------------------------------- 105 | HRESULT CALLBACK OnD3D11CreateDevice(ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, 106 | void* pUserContext) 107 | { 108 | HRESULT hr = S_OK; 109 | 110 | auto pd3dImmediateContext = DXUTGetD3D11DeviceContext(); 111 | 112 | V_RETURN(g_DialogResourceManager.OnD3D11CreateDevice(pd3dDevice, pd3dImmediateContext)); 113 | V_RETURN(g_SettingsDlg.OnD3D11CreateDevice(pd3dDevice)); 114 | g_pTxtHelper = new CDXUTTextHelper(pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15); 115 | 116 | DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; 117 | #ifdef _DEBUG 118 | // Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders. 119 | // Setting this flag improves the shader debugging experience, but still allows 120 | // the shaders to be optimized and to run exactly the way they will run in 121 | // the release configuration of this program. 122 | dwShaderFlags |= D3DCOMPILE_DEBUG; 123 | 124 | // Disable optimizations to further improve shader debugging 125 | dwShaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION; 126 | #endif 127 | 128 | WCHAR strShaderFile[MAX_PATH] = { 0 }; 129 | V_RETURN(DXUTFindDXSDKMediaFileCch(strShaderFile, MAX_PATH, L"sph_shader.fx")); 130 | 131 | // Compile the vertex shader 132 | ID3DBlob* pVSBlob = nullptr; 133 | V_RETURN(DXUTCompileFromFile(strShaderFile, nullptr, "MainVS", "vs_4_0", dwShaderFlags, 0, &pVSBlob)); 134 | 135 | // Create the vertex shader 136 | hr = pd3dDevice->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), nullptr, &g_pVertexShader); 137 | if (FAILED(hr)) 138 | { 139 | SAFE_RELEASE(pVSBlob); 140 | return hr; 141 | } 142 | 143 | // Define the input layout 144 | D3D11_INPUT_ELEMENT_DESC layout[] = 145 | { 146 | { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, 147 | { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, 148 | }; 149 | UINT numElements = ARRAYSIZE(layout); 150 | 151 | // Create the input layout 152 | hr = pd3dDevice->CreateInputLayout(layout, numElements, pVSBlob->GetBufferPointer(), 153 | pVSBlob->GetBufferSize(), &g_pVertexLayout); 154 | SAFE_RELEASE(pVSBlob); 155 | if (FAILED(hr)) 156 | return hr; 157 | 158 | // Set the input layout 159 | pd3dImmediateContext->IASetInputLayout(g_pVertexLayout); 160 | 161 | // Compile the pixel shader 162 | ID3DBlob* pPSBlob = nullptr; 163 | V_RETURN(DXUTCompileFromFile(strShaderFile, nullptr, "MainPS", "ps_4_0", dwShaderFlags, 0, &pPSBlob)); 164 | 165 | // Create the pixel shader 166 | hr = pd3dDevice->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), nullptr, &g_pPixelShader); 167 | SAFE_RELEASE(pPSBlob); 168 | if (FAILED(hr)) 169 | return hr; 170 | 171 | // Create the points vertex buf 172 | D3D11_BUFFER_DESC bd; 173 | ZeroMemory(&bd, sizeof(bd)); 174 | bd.Usage = D3D11_USAGE_DYNAMIC; 175 | bd.ByteWidth = sizeof(PointVertex) * MAX_PARTICLE_COUNTS; 176 | bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; 177 | bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; 178 | V_RETURN(pd3dDevice->CreateBuffer(&bd, nullptr, &g_pParticleVertexBuffer)); 179 | 180 | // Create the box vertex buf 181 | XMFLOAT4 box_color = XMFLOAT4(1.0f, 1.0f, 0.0f, 0.5); 182 | PointVertex boxVertices[] = { 183 | { XMFLOAT3(g_wallMin.x, g_wallMin.y, g_wallMin.z), box_color }, 184 | { XMFLOAT3(g_wallMax.x, g_wallMin.y, g_wallMin.z), box_color }, 185 | { XMFLOAT3(g_wallMax.x, g_wallMin.y, g_wallMax.z), box_color }, 186 | { XMFLOAT3(g_wallMin.x, g_wallMin.y, g_wallMax.z), box_color }, 187 | { XMFLOAT3(g_wallMin.x, g_wallMax.y, g_wallMin.z), box_color }, 188 | { XMFLOAT3(g_wallMax.x, g_wallMax.y, g_wallMin.z), box_color }, 189 | { XMFLOAT3(g_wallMax.x, g_wallMax.y, g_wallMax.z), box_color }, 190 | { XMFLOAT3(g_wallMin.x, g_wallMax.y, g_wallMax.z), box_color }, 191 | }; 192 | bd.Usage = D3D11_USAGE_DEFAULT; 193 | bd.ByteWidth = sizeof(PointVertex) * 8; 194 | bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; 195 | bd.CPUAccessFlags = 0; 196 | 197 | D3D11_SUBRESOURCE_DATA InitData; 198 | ZeroMemory(&InitData, sizeof(InitData)); 199 | InitData.pSysMem = boxVertices; 200 | 201 | V_RETURN(pd3dDevice->CreateBuffer(&bd, &InitData, &g_pBoxVertexBuffer)); 202 | 203 | // Create box index buffer 204 | DWORD indices[] = 205 | { 206 | 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 207 | }; 208 | bd.Usage = D3D11_USAGE_DEFAULT; 209 | bd.ByteWidth = sizeof(DWORD) * 24; 210 | bd.BindFlags = D3D11_BIND_INDEX_BUFFER; 211 | bd.CPUAccessFlags = 0; 212 | bd.MiscFlags = 0; 213 | InitData.pSysMem = indices; 214 | V_RETURN(pd3dDevice->CreateBuffer(&bd, &InitData, &g_pBoxIndexBuffer)); 215 | 216 | // Create the constant buffers 217 | bd.Usage = D3D11_USAGE_DYNAMIC; 218 | bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; 219 | bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; 220 | bd.ByteWidth = sizeof(CBChangesEveryFrame); 221 | V_RETURN(pd3dDevice->CreateBuffer(&bd, nullptr, &g_pCBChangesEveryFrame)); 222 | 223 | // Create blend op 224 | D3D11_BLEND_DESC BSDesc; 225 | ZeroMemory(&BSDesc, sizeof(D3D11_BLEND_DESC)); 226 | BSDesc.RenderTarget[0].BlendEnable = TRUE; 227 | BSDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; 228 | BSDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; 229 | BSDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; 230 | BSDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; 231 | BSDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; 232 | BSDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; 233 | BSDesc.RenderTarget[0].RenderTargetWriteMask = 0x0F; 234 | V_RETURN(pd3dDevice->CreateBlendState(&BSDesc, &g_pBlendState)); 235 | 236 | // Initialize the world matrices 237 | g_World = XMMatrixIdentity(); 238 | 239 | // Initialize the view matrix 240 | static const XMVECTORF32 s_Eye = { 40.0f, 40.0f, 50.0, 0.f }; 241 | static const XMVECTORF32 s_At = { 0.0f, 10.0f, 0.0f, 0.f }; 242 | g_Camera.SetViewParams(s_Eye, s_At); 243 | return S_OK; 244 | } 245 | 246 | 247 | //-------------------------------------------------------------------------------------- 248 | // Create any D3D11 resources that depend on the back buffer 249 | //-------------------------------------------------------------------------------------- 250 | HRESULT CALLBACK OnD3D11ResizedSwapChain(ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain, 251 | const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext) 252 | { 253 | HRESULT hr; 254 | 255 | V_RETURN(g_DialogResourceManager.OnD3D11ResizedSwapChain(pd3dDevice, pBackBufferSurfaceDesc)); 256 | V_RETURN(g_SettingsDlg.OnD3D11ResizedSwapChain(pd3dDevice, pBackBufferSurfaceDesc)); 257 | 258 | // Setup the camera's projection parameters 259 | float fAspectRatio = pBackBufferSurfaceDesc->Width / (FLOAT)pBackBufferSurfaceDesc->Height; 260 | g_Camera.SetProjParams(XM_PI / 4, fAspectRatio, 0.1f, 5000.0f); 261 | g_Camera.SetWindow(pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height); 262 | g_Camera.SetButtonMasks(MOUSE_LEFT_BUTTON, MOUSE_WHEEL, MOUSE_RIGHT_BUTTON); 263 | 264 | g_HUD.SetLocation(pBackBufferSurfaceDesc->Width - 170, 0); 265 | g_HUD.SetSize(170, 170); 266 | g_SampleUI.SetLocation(pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300); 267 | g_SampleUI.SetSize(170, 300); 268 | 269 | return S_OK; 270 | } 271 | 272 | 273 | //-------------------------------------------------------------------------------------- 274 | // Handle updates to the scene. 275 | //-------------------------------------------------------------------------------------- 276 | void CALLBACK OnFrameMove(double fTime, float fElapsedTime, void* pUserContext) 277 | { 278 | // Update the camera's position based on user input 279 | g_Camera.FrameMove(fElapsedTime); 280 | 281 | // Update SPH System to vertex buf 282 | g_pSPHSystem->tick(); 283 | 284 | auto pd3dImmediateContext = DXUTGetD3D11DeviceContext(); 285 | 286 | HRESULT hr; 287 | D3D11_MAPPED_SUBRESOURCE MappedResource; 288 | ZeroMemory(&MappedResource, sizeof(MappedResource)); 289 | 290 | V(pd3dImmediateContext->Map(g_pParticleVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource)); 291 | auto vertices = reinterpret_cast(MappedResource.pData); 292 | 293 | const SPH::float_3* p = g_pSPHSystem->getPointBuf(); 294 | 295 | XMFLOAT4 vertx_color = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0); 296 | 297 | for (unsigned int n = 0; ngetPointCounts(); n++) 298 | { 299 | vertices[n].Pos.x = p->x; 300 | vertices[n].Pos.y = p->y; 301 | vertices[n].Pos.z = p->z; 302 | vertices[n].Col = vertx_color; 303 | 304 | p = (const SPH::float_3*)(((const char*)p) + g_pSPHSystem->getPointStride()); 305 | } 306 | 307 | pd3dImmediateContext->Unmap(g_pParticleVertexBuffer, 0); 308 | } 309 | 310 | //-------------------------------------------------------------------------------------- 311 | // Render the help and statistics text 312 | //-------------------------------------------------------------------------------------- 313 | void RenderText() 314 | { 315 | g_pTxtHelper->Begin(); 316 | g_pTxtHelper->SetInsertionPos(2, 0); 317 | g_pTxtHelper->SetForegroundColor(Colors::Yellow); 318 | g_pTxtHelper->DrawTextLine(DXUTGetFrameStats(DXUTIsVsyncEnabled())); 319 | g_pTxtHelper->DrawTextLine(DXUTGetDeviceStats()); 320 | g_pTxtHelper->DrawTextLine(L"Rotate camera: Right mouse button\n"); 321 | g_pTxtHelper->DrawTextLine(L"Zoom camera: Mouse wheel scroll\n"); 322 | g_pTxtHelper->End(); 323 | } 324 | 325 | //-------------------------------------------------------------------------------------- 326 | // Render the scene using the D3D11 device 327 | //-------------------------------------------------------------------------------------- 328 | void CALLBACK OnD3D11FrameRender(ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, 329 | double fTime, float fElapsedTime, void* pUserContext) 330 | { 331 | // If the settings dialog is being shown, then render it instead of rendering the app's scene 332 | if (g_SettingsDlg.IsActive()) 333 | { 334 | g_SettingsDlg.OnRender(fElapsedTime); 335 | return; 336 | } 337 | // 338 | // Clear the back buffer 339 | // 340 | auto pRTV = DXUTGetD3D11RenderTargetView(); 341 | pd3dImmediateContext->ClearRenderTargetView(pRTV, Colors::MidnightBlue); 342 | 343 | // 344 | // Clear the depth stencil 345 | // 346 | auto pDSV = DXUTGetD3D11DepthStencilView(); 347 | pd3dImmediateContext->ClearDepthStencilView(pDSV, D3D11_CLEAR_DEPTH, 1.0, 0); 348 | 349 | 350 | XMMATRIX mView = g_Camera.GetViewMatrix(); 351 | XMMATRIX mProj = g_Camera.GetProjMatrix(); 352 | XMMATRIX mWorldViewProjection = g_World * mView * mProj; 353 | 354 | // Update constant buffer that changes once per frame 355 | HRESULT hr; 356 | D3D11_MAPPED_SUBRESOURCE MappedResource; 357 | V(pd3dImmediateContext->Map(g_pCBChangesEveryFrame, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource)); 358 | auto pCB = reinterpret_cast(MappedResource.pData); 359 | XMStoreFloat4x4(&pCB->mWorldViewProj, XMMatrixTranspose(mWorldViewProjection)); 360 | pd3dImmediateContext->Unmap(g_pCBChangesEveryFrame, 0); 361 | 362 | float BlendFactor[4] = { 0, 0, 0, 0 }; 363 | pd3dImmediateContext->OMSetBlendState(g_pBlendState, BlendFactor, 0xFFFFFFFF); 364 | 365 | // 366 | // Render the points 367 | // 368 | UINT stride = sizeof(PointVertex); 369 | UINT offset = 0; 370 | pd3dImmediateContext->IASetVertexBuffers(0, 1, &g_pParticleVertexBuffer, &stride, &offset); 371 | pd3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST); 372 | pd3dImmediateContext->VSSetShader(g_pVertexShader, nullptr, 0); 373 | pd3dImmediateContext->VSSetConstantBuffers(0, 1, &g_pCBChangesEveryFrame); 374 | pd3dImmediateContext->PSSetShader(g_pPixelShader, nullptr, 0); 375 | pd3dImmediateContext->PSSetConstantBuffers(0, 1, &g_pCBChangesEveryFrame); 376 | pd3dImmediateContext->Draw(g_pSPHSystem->getPointCounts(), 0); 377 | 378 | // 379 | // Render the cube 380 | // 381 | stride = sizeof(PointVertex); 382 | offset = 0; 383 | pd3dImmediateContext->IASetVertexBuffers(0, 1, &g_pBoxVertexBuffer, &stride, &offset); 384 | pd3dImmediateContext->IASetIndexBuffer(g_pBoxIndexBuffer, DXGI_FORMAT_R32_UINT, 0); 385 | pd3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST); 386 | pd3dImmediateContext->VSSetShader(g_pVertexShader, nullptr, 0); 387 | pd3dImmediateContext->VSSetConstantBuffers(0, 1, &g_pCBChangesEveryFrame); 388 | pd3dImmediateContext->PSSetShader(g_pPixelShader, nullptr, 0); 389 | pd3dImmediateContext->PSSetConstantBuffers(0, 1, &g_pCBChangesEveryFrame); 390 | pd3dImmediateContext->DrawIndexed(24, 0, 0); 391 | 392 | // 393 | // Render the UI 394 | // 395 | g_HUD.OnRender(fElapsedTime); 396 | g_SampleUI.OnRender(fElapsedTime); 397 | RenderText(); 398 | } 399 | 400 | 401 | //-------------------------------------------------------------------------------------- 402 | // Release D3D11 resources created in OnD3D11ResizedSwapChain 403 | //-------------------------------------------------------------------------------------- 404 | void CALLBACK OnD3D11ReleasingSwapChain(void* pUserContext) 405 | { 406 | g_DialogResourceManager.OnD3D11ReleasingSwapChain(); 407 | } 408 | 409 | 410 | //-------------------------------------------------------------------------------------- 411 | // Release D3D11 resources created in OnD3D11CreateDevice 412 | //-------------------------------------------------------------------------------------- 413 | void CALLBACK OnD3D11DestroyDevice(void* pUserContext) 414 | { 415 | g_DialogResourceManager.OnD3D11DestroyDevice(); 416 | g_SettingsDlg.OnD3D11DestroyDevice(); 417 | DXUTGetGlobalResourceCache().OnDestroyDevice(); 418 | SAFE_DELETE(g_pTxtHelper); 419 | 420 | SAFE_RELEASE(g_pParticleVertexBuffer); 421 | SAFE_RELEASE(g_pBoxVertexBuffer); 422 | SAFE_RELEASE(g_pBoxIndexBuffer); 423 | SAFE_RELEASE(g_pVertexLayout); 424 | SAFE_RELEASE(g_pVertexShader); 425 | SAFE_RELEASE(g_pPixelShader); 426 | SAFE_RELEASE(g_pCBChangesEveryFrame); 427 | SAFE_RELEASE(g_pBlendState); 428 | } 429 | 430 | 431 | //-------------------------------------------------------------------------------------- 432 | // Handle messages to the application 433 | //-------------------------------------------------------------------------------------- 434 | LRESULT CALLBACK MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, 435 | bool* pbNoFurtherProcessing, void* pUserContext) 436 | { 437 | // Pass messages to dialog resource manager calls so GUI state is updated correctly 438 | *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam); 439 | if (*pbNoFurtherProcessing) 440 | return 0; 441 | 442 | // Pass messages to settings dialog if its active 443 | if (g_SettingsDlg.IsActive()) 444 | { 445 | g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam); 446 | return 0; 447 | } 448 | 449 | // Give the dialogs a chance to handle the message first 450 | *pbNoFurtherProcessing = g_HUD.MsgProc(hWnd, uMsg, wParam, lParam); 451 | if (*pbNoFurtherProcessing) 452 | return 0; 453 | *pbNoFurtherProcessing = g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam); 454 | if (*pbNoFurtherProcessing) 455 | return 0; 456 | 457 | // Pass all remaining windows messages to camera so it can respond to user input 458 | g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam); 459 | return 0; 460 | } 461 | 462 | //-------------------------------------------------------------------------------------- 463 | // Handles the GUI events 464 | //-------------------------------------------------------------------------------------- 465 | void CALLBACK OnGUIEvent(UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext) 466 | { 467 | switch (nControlID) 468 | { 469 | case IDC_TOGGLEFULLSCREEN: 470 | DXUTToggleFullScreen(); 471 | break; 472 | case IDC_TOGGLEREF: 473 | DXUTToggleREF(); 474 | break; 475 | case IDC_CHANGEDEVICE: 476 | g_SettingsDlg.SetActive(!g_SettingsDlg.IsActive()); 477 | break; 478 | case IDC_TOGGLEWARP: 479 | DXUTToggleWARP(); 480 | break; 481 | case IDC_SPH_RESET: 482 | resetSPHSystem(); 483 | break; 484 | } 485 | } 486 | 487 | //-------------------------------------------------------------------------------------- 488 | // Handle key presses 489 | //-------------------------------------------------------------------------------------- 490 | void CALLBACK OnKeyboard(UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext) 491 | { 492 | if (bKeyDown) 493 | { 494 | switch (nChar) 495 | { 496 | case VK_F1: // Change as needed 497 | break; 498 | } 499 | } 500 | } 501 | 502 | 503 | //-------------------------------------------------------------------------------------- 504 | // Call if device was removed. Return true to find a new device, false to quit 505 | //-------------------------------------------------------------------------------------- 506 | bool CALLBACK OnDeviceRemoved(void* pUserContext) 507 | { 508 | return true; 509 | } 510 | 511 | //-------------------------------------------------------------------------------------- 512 | // Initialize the app 513 | //-------------------------------------------------------------------------------------- 514 | void InitApp() 515 | { 516 | g_SettingsDlg.Init(&g_DialogResourceManager); 517 | g_HUD.Init(&g_DialogResourceManager); 518 | g_SampleUI.Init(&g_DialogResourceManager); 519 | 520 | g_HUD.SetCallback(OnGUIEvent); int iY = 10; 521 | g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 0, iY, 170, 22); 522 | g_HUD.AddButton(IDC_CHANGEDEVICE, L"Change device (F2)", 0, iY += 26, 170, 22, VK_F2); 523 | g_HUD.AddButton(IDC_TOGGLEREF, L"Toggle REF (F3)", 0, iY += 26, 170, 22, VK_F3); 524 | g_HUD.AddButton(IDC_TOGGLEWARP, L"Toggle WARP (F4)", 0, iY += 26, 170, 22, VK_F4); 525 | g_HUD.AddButton(IDC_SPH_RESET, L"Reset", 0, iY += 26, 170, 22, VK_F4); 526 | 527 | g_SampleUI.SetCallback(OnGUIEvent); iY = 10; 528 | 529 | //create sph system 530 | g_pSPHSystem = getSPHSystem(); 531 | resetSPHSystem(); 532 | } 533 | 534 | //-------------------------------------------------------------------------------------- 535 | // Initialize everything and go into a render loop 536 | //-------------------------------------------------------------------------------------- 537 | int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) 538 | { 539 | // Enable run-time memory check for debug builds. 540 | #ifdef _DEBUG 541 | _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); 542 | #endif 543 | 544 | // DXUT will create and use the best device 545 | // that is available on the system depending on which D3D callbacks are set below 546 | 547 | // Set general DXUT callbacks 548 | DXUTSetCallbackFrameMove(OnFrameMove); 549 | DXUTSetCallbackKeyboard(OnKeyboard); 550 | DXUTSetCallbackMsgProc(MsgProc); 551 | DXUTSetCallbackDeviceChanging(ModifyDeviceSettings); 552 | DXUTSetCallbackDeviceRemoved(OnDeviceRemoved); 553 | 554 | // Set the D3D11 DXUT callbacks. Remove these sets if the app doesn't need to support D3D11 555 | DXUTSetCallbackD3D11DeviceAcceptable(IsD3D11DeviceAcceptable); 556 | DXUTSetCallbackD3D11DeviceCreated(OnD3D11CreateDevice); 557 | DXUTSetCallbackD3D11SwapChainResized(OnD3D11ResizedSwapChain); 558 | DXUTSetCallbackD3D11FrameRender(OnD3D11FrameRender); 559 | DXUTSetCallbackD3D11SwapChainReleasing(OnD3D11ReleasingSwapChain); 560 | DXUTSetCallbackD3D11DeviceDestroyed(OnD3D11DestroyDevice); 561 | 562 | // Perform any application-level initialization here 563 | InitApp(); 564 | 565 | DXUTInit(true, true, nullptr); // Parse the command line, show msgboxes on error, no extra command line params 566 | DXUTSetCursorSettings(true, true); // Show the cursor and clip it when in full screen 567 | DXUTCreateWindow(L"SPH - thecodeway.com"); 568 | 569 | // Only require 10-level hardware or later 570 | DXUTCreateDevice(D3D_FEATURE_LEVEL_10_0, true, 800, 600); 571 | DXUTMainLoop(); // Enter into the DXUT render loop 572 | 573 | // Perform any application-level cleanup here 574 | 575 | return DXUTGetExitCode(); 576 | } 577 | -------------------------------------------------------------------------------- /DXUT/Core/WICTextureLoader.cpp: -------------------------------------------------------------------------------- 1 | //-------------------------------------------------------------------------------------- 2 | // File: WICTextureLoader.cpp 3 | // 4 | // Function for loading a WIC image and creating a Direct3D runtime texture for it 5 | // (auto-generating mipmaps if possible) 6 | // 7 | // Note: Assumes application has already called CoInitializeEx 8 | // 9 | // Warning: CreateWICTexture* functions are not thread-safe if given a d3dContext instance for 10 | // auto-gen mipmap support. 11 | // 12 | // Note these functions are useful for images created as simple 2D textures. For 13 | // more complex resources, DDSTextureLoader is an excellent light-weight runtime loader. 14 | // For a full-featured DDS file reader, writer, and texture processing pipeline see 15 | // the 'Texconv' sample and the 'DirectXTex' library. 16 | // 17 | // Copyright (c) Microsoft Corporation. All rights reserved. 18 | // Licensed under the MIT License. 19 | // 20 | // http://go.microsoft.com/fwlink/?LinkId=248926 21 | // http://go.microsoft.com/fwlink/?LinkId=248929 22 | //-------------------------------------------------------------------------------------- 23 | 24 | #include "dxut.h" 25 | 26 | // We could load multi-frame images (TIFF/GIF) into a texture array. 27 | // For now, we just load the first frame (note: DirectXTex supports multi-frame images) 28 | 29 | #include "WICTextureLoader.h" 30 | 31 | #include 32 | #include 33 | 34 | #include 35 | 36 | #include 37 | 38 | #include 39 | #include 40 | 41 | #if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) 42 | #pragma comment(lib,"dxguid.lib") 43 | #endif 44 | 45 | using namespace DirectX; 46 | using Microsoft::WRL::ComPtr; 47 | 48 | namespace 49 | { 50 | //-------------------------------------------------------------------------------------- 51 | template 52 | inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_ const char(&name)[TNameLength]) 53 | { 54 | #if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) 55 | resource->SetPrivateData(WKPDID_D3DDebugObjectName, TNameLength - 1, name); 56 | #else 57 | UNREFERENCED_PARAMETER(resource); 58 | UNREFERENCED_PARAMETER(name); 59 | #endif 60 | } 61 | 62 | //------------------------------------------------------------------------------------- 63 | // WIC Pixel Format Translation Data 64 | //------------------------------------------------------------------------------------- 65 | struct WICTranslate 66 | { 67 | GUID wic; 68 | DXGI_FORMAT format; 69 | }; 70 | 71 | const WICTranslate g_WICFormats[] = 72 | { 73 | { GUID_WICPixelFormat128bppRGBAFloat, DXGI_FORMAT_R32G32B32A32_FLOAT }, 74 | 75 | { GUID_WICPixelFormat64bppRGBAHalf, DXGI_FORMAT_R16G16B16A16_FLOAT }, 76 | { GUID_WICPixelFormat64bppRGBA, DXGI_FORMAT_R16G16B16A16_UNORM }, 77 | 78 | { GUID_WICPixelFormat32bppRGBA, DXGI_FORMAT_R8G8B8A8_UNORM }, 79 | { GUID_WICPixelFormat32bppBGRA, DXGI_FORMAT_B8G8R8A8_UNORM }, // DXGI 1.1 80 | { GUID_WICPixelFormat32bppBGR, DXGI_FORMAT_B8G8R8X8_UNORM }, // DXGI 1.1 81 | 82 | { GUID_WICPixelFormat32bppRGBA1010102XR, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM }, // DXGI 1.1 83 | { GUID_WICPixelFormat32bppRGBA1010102, DXGI_FORMAT_R10G10B10A2_UNORM }, 84 | 85 | { GUID_WICPixelFormat16bppBGRA5551, DXGI_FORMAT_B5G5R5A1_UNORM }, 86 | { GUID_WICPixelFormat16bppBGR565, DXGI_FORMAT_B5G6R5_UNORM }, 87 | 88 | { GUID_WICPixelFormat32bppGrayFloat, DXGI_FORMAT_R32_FLOAT }, 89 | { GUID_WICPixelFormat16bppGrayHalf, DXGI_FORMAT_R16_FLOAT }, 90 | { GUID_WICPixelFormat16bppGray, DXGI_FORMAT_R16_UNORM }, 91 | { GUID_WICPixelFormat8bppGray, DXGI_FORMAT_R8_UNORM }, 92 | 93 | { GUID_WICPixelFormat8bppAlpha, DXGI_FORMAT_A8_UNORM }, 94 | }; 95 | 96 | //------------------------------------------------------------------------------------- 97 | // WIC Pixel Format nearest conversion table 98 | //------------------------------------------------------------------------------------- 99 | 100 | struct WICConvert 101 | { 102 | GUID source; 103 | GUID target; 104 | }; 105 | 106 | const WICConvert g_WICConvert[] = 107 | { 108 | // Note target GUID in this conversion table must be one of those directly supported formats (above). 109 | 110 | { GUID_WICPixelFormatBlackWhite, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM 111 | 112 | { GUID_WICPixelFormat1bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM 113 | { GUID_WICPixelFormat2bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM 114 | { GUID_WICPixelFormat4bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM 115 | { GUID_WICPixelFormat8bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM 116 | 117 | { GUID_WICPixelFormat2bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM 118 | { GUID_WICPixelFormat4bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM 119 | 120 | { GUID_WICPixelFormat16bppGrayFixedPoint, GUID_WICPixelFormat16bppGrayHalf }, // DXGI_FORMAT_R16_FLOAT 121 | { GUID_WICPixelFormat32bppGrayFixedPoint, GUID_WICPixelFormat32bppGrayFloat }, // DXGI_FORMAT_R32_FLOAT 122 | 123 | { GUID_WICPixelFormat16bppBGR555, GUID_WICPixelFormat16bppBGRA5551 }, // DXGI_FORMAT_B5G5R5A1_UNORM 124 | 125 | { GUID_WICPixelFormat32bppBGR101010, GUID_WICPixelFormat32bppRGBA1010102 }, // DXGI_FORMAT_R10G10B10A2_UNORM 126 | 127 | { GUID_WICPixelFormat24bppBGR, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM 128 | { GUID_WICPixelFormat24bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM 129 | { GUID_WICPixelFormat32bppPBGRA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM 130 | { GUID_WICPixelFormat32bppPRGBA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM 131 | 132 | { GUID_WICPixelFormat48bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM 133 | { GUID_WICPixelFormat48bppBGR, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM 134 | { GUID_WICPixelFormat64bppBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM 135 | { GUID_WICPixelFormat64bppPRGBA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM 136 | { GUID_WICPixelFormat64bppPBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM 137 | 138 | { GUID_WICPixelFormat48bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT 139 | { GUID_WICPixelFormat48bppBGRFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT 140 | { GUID_WICPixelFormat64bppRGBAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT 141 | { GUID_WICPixelFormat64bppBGRAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT 142 | { GUID_WICPixelFormat64bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT 143 | { GUID_WICPixelFormat64bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT 144 | { GUID_WICPixelFormat48bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT 145 | 146 | { GUID_WICPixelFormat128bppPRGBAFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT 147 | { GUID_WICPixelFormat128bppRGBFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT 148 | { GUID_WICPixelFormat128bppRGBAFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT 149 | { GUID_WICPixelFormat128bppRGBFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT 150 | { GUID_WICPixelFormat32bppRGBE, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT 151 | 152 | { GUID_WICPixelFormat32bppCMYK, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM 153 | { GUID_WICPixelFormat64bppCMYK, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM 154 | { GUID_WICPixelFormat40bppCMYKAlpha, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM 155 | { GUID_WICPixelFormat80bppCMYKAlpha, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM 156 | 157 | #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) 158 | { GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM 159 | { GUID_WICPixelFormat64bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM 160 | { GUID_WICPixelFormat64bppPRGBAHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT 161 | #endif 162 | 163 | // We don't support n-channel formats 164 | }; 165 | 166 | bool g_WIC2 = false; 167 | 168 | //-------------------------------------------------------------------------------------- 169 | IWICImagingFactory* _GetWIC() 170 | { 171 | static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT; 172 | 173 | IWICImagingFactory* factory = nullptr; 174 | InitOnceExecuteOnce(&s_initOnce, 175 | [](PINIT_ONCE, PVOID, PVOID *factory) -> BOOL 176 | { 177 | #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) 178 | HRESULT hr = CoCreateInstance( 179 | CLSID_WICImagingFactory2, 180 | nullptr, 181 | CLSCTX_INPROC_SERVER, 182 | __uuidof(IWICImagingFactory2), 183 | factory 184 | ); 185 | 186 | if (SUCCEEDED(hr)) 187 | { 188 | // WIC2 is available on Windows 10, Windows 8.x, and Windows 7 SP1 with KB 2670838 installed 189 | g_WIC2 = true; 190 | return TRUE; 191 | } 192 | else 193 | { 194 | hr = CoCreateInstance( 195 | CLSID_WICImagingFactory1, 196 | nullptr, 197 | CLSCTX_INPROC_SERVER, 198 | __uuidof(IWICImagingFactory), 199 | factory 200 | ); 201 | return SUCCEEDED(hr) ? TRUE : FALSE; 202 | } 203 | #else 204 | return SUCCEEDED(CoCreateInstance( 205 | CLSID_WICImagingFactory, 206 | nullptr, 207 | CLSCTX_INPROC_SERVER, 208 | __uuidof(IWICImagingFactory), 209 | factory)) ? TRUE : FALSE; 210 | #endif 211 | }, nullptr, reinterpret_cast(&factory)); 212 | 213 | return factory; 214 | } 215 | 216 | //--------------------------------------------------------------------------------- 217 | DXGI_FORMAT _WICToDXGI(const GUID& guid) 218 | { 219 | for (size_t i = 0; i < _countof(g_WICFormats); ++i) 220 | { 221 | if (memcmp(&g_WICFormats[i].wic, &guid, sizeof(GUID)) == 0) 222 | return g_WICFormats[i].format; 223 | } 224 | 225 | #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) 226 | if (g_WIC2) 227 | { 228 | if (memcmp(&GUID_WICPixelFormat96bppRGBFloat, &guid, sizeof(GUID)) == 0) 229 | return DXGI_FORMAT_R32G32B32_FLOAT; 230 | } 231 | #endif 232 | 233 | return DXGI_FORMAT_UNKNOWN; 234 | } 235 | 236 | //--------------------------------------------------------------------------------- 237 | size_t _WICBitsPerPixel(REFGUID targetGuid) 238 | { 239 | auto pWIC = _GetWIC(); 240 | if (!pWIC) 241 | return 0; 242 | 243 | ComPtr cinfo; 244 | if (FAILED(pWIC->CreateComponentInfo(targetGuid, cinfo.GetAddressOf()))) 245 | return 0; 246 | 247 | WICComponentType type; 248 | if (FAILED(cinfo->GetComponentType(&type))) 249 | return 0; 250 | 251 | if (type != WICPixelFormat) 252 | return 0; 253 | 254 | ComPtr pfinfo; 255 | if (FAILED(cinfo.As(&pfinfo))) 256 | return 0; 257 | 258 | UINT bpp; 259 | if (FAILED(pfinfo->GetBitsPerPixel(&bpp))) 260 | return 0; 261 | 262 | return bpp; 263 | } 264 | 265 | 266 | //-------------------------------------------------------------------------------------- 267 | DXGI_FORMAT MakeSRGB(_In_ DXGI_FORMAT format) 268 | { 269 | switch (format) 270 | { 271 | case DXGI_FORMAT_R8G8B8A8_UNORM: 272 | return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; 273 | 274 | case DXGI_FORMAT_BC1_UNORM: 275 | return DXGI_FORMAT_BC1_UNORM_SRGB; 276 | 277 | case DXGI_FORMAT_BC2_UNORM: 278 | return DXGI_FORMAT_BC2_UNORM_SRGB; 279 | 280 | case DXGI_FORMAT_BC3_UNORM: 281 | return DXGI_FORMAT_BC3_UNORM_SRGB; 282 | 283 | case DXGI_FORMAT_B8G8R8A8_UNORM: 284 | return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; 285 | 286 | case DXGI_FORMAT_B8G8R8X8_UNORM: 287 | return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; 288 | 289 | case DXGI_FORMAT_BC7_UNORM: 290 | return DXGI_FORMAT_BC7_UNORM_SRGB; 291 | 292 | default: 293 | return format; 294 | } 295 | } 296 | 297 | 298 | //--------------------------------------------------------------------------------- 299 | HRESULT CreateTextureFromWIC(_In_ ID3D11Device* d3dDevice, 300 | _In_opt_ ID3D11DeviceContext* d3dContext, 301 | _In_ IWICBitmapFrameDecode *frame, 302 | _In_ size_t maxsize, 303 | _In_ D3D11_USAGE usage, 304 | _In_ unsigned int bindFlags, 305 | _In_ unsigned int cpuAccessFlags, 306 | _In_ unsigned int miscFlags, 307 | _In_ unsigned int loadFlags, 308 | _Outptr_opt_ ID3D11Resource** texture, 309 | _Outptr_opt_ ID3D11ShaderResourceView** textureView) 310 | { 311 | UINT width, height; 312 | HRESULT hr = frame->GetSize(&width, &height); 313 | if (FAILED(hr)) 314 | return hr; 315 | 316 | assert(width > 0 && height > 0); 317 | 318 | if (!maxsize) 319 | { 320 | // This is a bit conservative because the hardware could support larger textures than 321 | // the Feature Level defined minimums, but doing it this way is much easier and more 322 | // performant for WIC than the 'fail and retry' model used by DDSTextureLoader 323 | 324 | switch (d3dDevice->GetFeatureLevel()) 325 | { 326 | case D3D_FEATURE_LEVEL_9_1: 327 | case D3D_FEATURE_LEVEL_9_2: 328 | maxsize = 2048 /*D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; 329 | break; 330 | 331 | case D3D_FEATURE_LEVEL_9_3: 332 | maxsize = 4096 /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; 333 | break; 334 | 335 | case D3D_FEATURE_LEVEL_10_0: 336 | case D3D_FEATURE_LEVEL_10_1: 337 | maxsize = 8192 /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; 338 | break; 339 | 340 | default: 341 | maxsize = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; 342 | break; 343 | } 344 | } 345 | 346 | assert(maxsize > 0); 347 | 348 | UINT twidth, theight; 349 | if (width > maxsize || height > maxsize) 350 | { 351 | float ar = static_cast(height) / static_cast(width); 352 | if (width > height) 353 | { 354 | twidth = static_cast(maxsize); 355 | theight = std::max(1, static_cast(static_cast(maxsize) * ar)); 356 | } 357 | else 358 | { 359 | theight = static_cast(maxsize); 360 | twidth = std::max(1, static_cast(static_cast(maxsize) / ar)); 361 | } 362 | assert(twidth <= maxsize && theight <= maxsize); 363 | } 364 | else 365 | { 366 | twidth = width; 367 | theight = height; 368 | } 369 | 370 | // Determine format 371 | WICPixelFormatGUID pixelFormat; 372 | hr = frame->GetPixelFormat(&pixelFormat); 373 | if (FAILED(hr)) 374 | return hr; 375 | 376 | WICPixelFormatGUID convertGUID; 377 | memcpy(&convertGUID, &pixelFormat, sizeof(WICPixelFormatGUID)); 378 | 379 | size_t bpp = 0; 380 | 381 | DXGI_FORMAT format = _WICToDXGI(pixelFormat); 382 | if (format == DXGI_FORMAT_UNKNOWN) 383 | { 384 | if (memcmp(&GUID_WICPixelFormat96bppRGBFixedPoint, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0) 385 | { 386 | #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) 387 | if (g_WIC2) 388 | { 389 | memcpy(&convertGUID, &GUID_WICPixelFormat96bppRGBFloat, sizeof(WICPixelFormatGUID)); 390 | format = DXGI_FORMAT_R32G32B32_FLOAT; 391 | bpp = 96; 392 | } 393 | else 394 | #endif 395 | { 396 | memcpy(&convertGUID, &GUID_WICPixelFormat128bppRGBAFloat, sizeof(WICPixelFormatGUID)); 397 | format = DXGI_FORMAT_R32G32B32A32_FLOAT; 398 | bpp = 128; 399 | } 400 | } 401 | else 402 | { 403 | for (size_t i = 0; i < _countof(g_WICConvert); ++i) 404 | { 405 | if (memcmp(&g_WICConvert[i].source, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0) 406 | { 407 | memcpy(&convertGUID, &g_WICConvert[i].target, sizeof(WICPixelFormatGUID)); 408 | 409 | format = _WICToDXGI(g_WICConvert[i].target); 410 | assert(format != DXGI_FORMAT_UNKNOWN); 411 | bpp = _WICBitsPerPixel(convertGUID); 412 | break; 413 | } 414 | } 415 | } 416 | 417 | if (format == DXGI_FORMAT_UNKNOWN) 418 | return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); 419 | } 420 | else 421 | { 422 | bpp = _WICBitsPerPixel(pixelFormat); 423 | } 424 | 425 | #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) 426 | if ((format == DXGI_FORMAT_R32G32B32_FLOAT) && d3dContext != 0 && textureView != 0) 427 | { 428 | // Special case test for optional device support for autogen mipchains for R32G32B32_FLOAT 429 | UINT fmtSupport = 0; 430 | hr = d3dDevice->CheckFormatSupport(DXGI_FORMAT_R32G32B32_FLOAT, &fmtSupport); 431 | if (FAILED(hr) || !(fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) 432 | { 433 | // Use R32G32B32A32_FLOAT instead which is required for Feature Level 10.0 and up 434 | memcpy(&convertGUID, &GUID_WICPixelFormat128bppRGBAFloat, sizeof(WICPixelFormatGUID)); 435 | format = DXGI_FORMAT_R32G32B32A32_FLOAT; 436 | bpp = 128; 437 | } 438 | } 439 | #endif 440 | 441 | if (!bpp) 442 | return E_FAIL; 443 | 444 | // Handle sRGB formats 445 | if (loadFlags & WIC_LOADER_FORCE_SRGB) 446 | { 447 | format = MakeSRGB(format); 448 | } 449 | else if (!(loadFlags & WIC_LOADER_IGNORE_SRGB)) 450 | { 451 | ComPtr metareader; 452 | if (SUCCEEDED(frame->GetMetadataQueryReader(metareader.GetAddressOf()))) 453 | { 454 | GUID containerFormat; 455 | if (SUCCEEDED(metareader->GetContainerFormat(&containerFormat))) 456 | { 457 | // Check for sRGB colorspace metadata 458 | bool sRGB = false; 459 | 460 | PROPVARIANT value; 461 | PropVariantInit(&value); 462 | 463 | if (memcmp(&containerFormat, &GUID_ContainerFormatPng, sizeof(GUID)) == 0) 464 | { 465 | // Check for sRGB chunk 466 | if (SUCCEEDED(metareader->GetMetadataByName(L"/sRGB/RenderingIntent", &value)) && value.vt == VT_UI1) 467 | { 468 | sRGB = true; 469 | } 470 | } 471 | else if (SUCCEEDED(metareader->GetMetadataByName(L"System.Image.ColorSpace", &value)) && value.vt == VT_UI2 && value.uiVal == 1) 472 | { 473 | sRGB = true; 474 | } 475 | 476 | (void)PropVariantClear(&value); 477 | 478 | if (sRGB) 479 | format = MakeSRGB(format); 480 | } 481 | } 482 | } 483 | 484 | // Verify our target format is supported by the current device 485 | // (handles WDDM 1.0 or WDDM 1.1 device driver cases as well as DirectX 11.0 Runtime without 16bpp format support) 486 | UINT support = 0; 487 | hr = d3dDevice->CheckFormatSupport(format, &support); 488 | if (FAILED(hr) || !(support & D3D11_FORMAT_SUPPORT_TEXTURE2D)) 489 | { 490 | // Fallback to RGBA 32-bit format which is supported by all devices 491 | memcpy(&convertGUID, &GUID_WICPixelFormat32bppRGBA, sizeof(WICPixelFormatGUID)); 492 | format = DXGI_FORMAT_R8G8B8A8_UNORM; 493 | bpp = 32; 494 | } 495 | 496 | // Allocate temporary memory for image 497 | size_t rowPitch = (twidth * bpp + 7) / 8; 498 | size_t imageSize = rowPitch * theight; 499 | 500 | std::unique_ptr temp(new (std::nothrow) uint8_t[imageSize]); 501 | if (!temp) 502 | return E_OUTOFMEMORY; 503 | 504 | // Load image data 505 | if (memcmp(&convertGUID, &pixelFormat, sizeof(GUID)) == 0 506 | && twidth == width 507 | && theight == height) 508 | { 509 | // No format conversion or resize needed 510 | hr = frame->CopyPixels(0, static_cast(rowPitch), static_cast(imageSize), temp.get()); 511 | if (FAILED(hr)) 512 | return hr; 513 | } 514 | else if (twidth != width || theight != height) 515 | { 516 | // Resize 517 | auto pWIC = _GetWIC(); 518 | if (!pWIC) 519 | return E_NOINTERFACE; 520 | 521 | ComPtr scaler; 522 | hr = pWIC->CreateBitmapScaler(scaler.GetAddressOf()); 523 | if (FAILED(hr)) 524 | return hr; 525 | 526 | hr = scaler->Initialize(frame, twidth, theight, WICBitmapInterpolationModeFant); 527 | if (FAILED(hr)) 528 | return hr; 529 | 530 | WICPixelFormatGUID pfScaler; 531 | hr = scaler->GetPixelFormat(&pfScaler); 532 | if (FAILED(hr)) 533 | return hr; 534 | 535 | if (memcmp(&convertGUID, &pfScaler, sizeof(GUID)) == 0) 536 | { 537 | // No format conversion needed 538 | hr = scaler->CopyPixels(0, static_cast(rowPitch), static_cast(imageSize), temp.get()); 539 | if (FAILED(hr)) 540 | return hr; 541 | } 542 | else 543 | { 544 | ComPtr FC; 545 | hr = pWIC->CreateFormatConverter(FC.GetAddressOf()); 546 | if (FAILED(hr)) 547 | return hr; 548 | 549 | BOOL canConvert = FALSE; 550 | hr = FC->CanConvert(pfScaler, convertGUID, &canConvert); 551 | if (FAILED(hr) || !canConvert) 552 | { 553 | return E_UNEXPECTED; 554 | } 555 | 556 | hr = FC->Initialize(scaler.Get(), convertGUID, WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut); 557 | if (FAILED(hr)) 558 | return hr; 559 | 560 | hr = FC->CopyPixels(0, static_cast(rowPitch), static_cast(imageSize), temp.get()); 561 | if (FAILED(hr)) 562 | return hr; 563 | } 564 | } 565 | else 566 | { 567 | // Format conversion but no resize 568 | auto pWIC = _GetWIC(); 569 | if (!pWIC) 570 | return E_NOINTERFACE; 571 | 572 | ComPtr FC; 573 | hr = pWIC->CreateFormatConverter(FC.GetAddressOf()); 574 | if (FAILED(hr)) 575 | return hr; 576 | 577 | BOOL canConvert = FALSE; 578 | hr = FC->CanConvert(pixelFormat, convertGUID, &canConvert); 579 | if (FAILED(hr) || !canConvert) 580 | { 581 | return E_UNEXPECTED; 582 | } 583 | 584 | hr = FC->Initialize(frame, convertGUID, WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut); 585 | if (FAILED(hr)) 586 | return hr; 587 | 588 | hr = FC->CopyPixels(0, static_cast(rowPitch), static_cast(imageSize), temp.get()); 589 | if (FAILED(hr)) 590 | return hr; 591 | } 592 | 593 | // See if format is supported for auto-gen mipmaps (varies by feature level) 594 | bool autogen = false; 595 | if (d3dContext != 0 && textureView != 0) // Must have context and shader-view to auto generate mipmaps 596 | { 597 | UINT fmtSupport = 0; 598 | hr = d3dDevice->CheckFormatSupport(format, &fmtSupport); 599 | if (SUCCEEDED(hr) && (fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN)) 600 | { 601 | autogen = true; 602 | } 603 | } 604 | 605 | // Create texture 606 | D3D11_TEXTURE2D_DESC desc; 607 | desc.Width = twidth; 608 | desc.Height = theight; 609 | desc.MipLevels = (autogen) ? 0 : 1; 610 | desc.ArraySize = 1; 611 | desc.Format = format; 612 | desc.SampleDesc.Count = 1; 613 | desc.SampleDesc.Quality = 0; 614 | desc.Usage = usage; 615 | desc.CPUAccessFlags = cpuAccessFlags; 616 | 617 | if (autogen) 618 | { 619 | desc.BindFlags = bindFlags | D3D11_BIND_RENDER_TARGET; 620 | desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_GENERATE_MIPS; 621 | } 622 | else 623 | { 624 | desc.BindFlags = bindFlags; 625 | desc.MiscFlags = miscFlags; 626 | } 627 | 628 | D3D11_SUBRESOURCE_DATA initData; 629 | initData.pSysMem = temp.get(); 630 | initData.SysMemPitch = static_cast(rowPitch); 631 | initData.SysMemSlicePitch = static_cast(imageSize); 632 | 633 | ID3D11Texture2D* tex = nullptr; 634 | hr = d3dDevice->CreateTexture2D(&desc, (autogen) ? nullptr : &initData, &tex); 635 | if (SUCCEEDED(hr) && tex != 0) 636 | { 637 | if (textureView != 0) 638 | { 639 | D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; 640 | SRVDesc.Format = desc.Format; 641 | 642 | SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; 643 | SRVDesc.Texture2D.MipLevels = (autogen) ? -1 : 1; 644 | 645 | hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView); 646 | if (FAILED(hr)) 647 | { 648 | tex->Release(); 649 | return hr; 650 | } 651 | 652 | if (autogen) 653 | { 654 | assert(d3dContext != 0); 655 | d3dContext->UpdateSubresource(tex, 0, nullptr, temp.get(), static_cast(rowPitch), static_cast(imageSize)); 656 | d3dContext->GenerateMips(*textureView); 657 | } 658 | } 659 | 660 | if (texture != 0) 661 | { 662 | *texture = tex; 663 | } 664 | else 665 | { 666 | SetDebugObjectName(tex, "WICTextureLoader"); 667 | tex->Release(); 668 | } 669 | } 670 | 671 | return hr; 672 | } 673 | } // anonymous namespace 674 | 675 | //-------------------------------------------------------------------------------------- 676 | _Use_decl_annotations_ 677 | HRESULT DirectX::CreateWICTextureFromMemory(ID3D11Device* d3dDevice, 678 | const uint8_t* wicData, 679 | size_t wicDataSize, 680 | ID3D11Resource** texture, 681 | ID3D11ShaderResourceView** textureView, 682 | size_t maxsize) 683 | { 684 | return CreateWICTextureFromMemoryEx(d3dDevice, nullptr, wicData, wicDataSize, maxsize, 685 | D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, 686 | texture, textureView); 687 | } 688 | 689 | _Use_decl_annotations_ 690 | HRESULT DirectX::CreateWICTextureFromMemory(ID3D11Device* d3dDevice, 691 | ID3D11DeviceContext* d3dContext, 692 | const uint8_t* wicData, 693 | size_t wicDataSize, 694 | ID3D11Resource** texture, 695 | ID3D11ShaderResourceView** textureView, 696 | size_t maxsize) 697 | { 698 | return CreateWICTextureFromMemoryEx(d3dDevice, d3dContext, wicData, wicDataSize, maxsize, 699 | D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, 700 | texture, textureView); 701 | } 702 | 703 | _Use_decl_annotations_ 704 | HRESULT DirectX::CreateWICTextureFromMemoryEx(ID3D11Device* d3dDevice, 705 | const uint8_t* wicData, 706 | size_t wicDataSize, 707 | size_t maxsize, 708 | D3D11_USAGE usage, 709 | unsigned int bindFlags, 710 | unsigned int cpuAccessFlags, 711 | unsigned int miscFlags, 712 | unsigned int loadFlags, 713 | ID3D11Resource** texture, 714 | ID3D11ShaderResourceView** textureView) 715 | { 716 | return CreateWICTextureFromMemoryEx(d3dDevice, nullptr, wicData, wicDataSize, maxsize, 717 | usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, 718 | texture, textureView); 719 | } 720 | 721 | _Use_decl_annotations_ 722 | HRESULT DirectX::CreateWICTextureFromMemoryEx(ID3D11Device* d3dDevice, 723 | ID3D11DeviceContext* d3dContext, 724 | const uint8_t* wicData, 725 | size_t wicDataSize, 726 | size_t maxsize, 727 | D3D11_USAGE usage, 728 | unsigned int bindFlags, 729 | unsigned int cpuAccessFlags, 730 | unsigned int miscFlags, 731 | unsigned int loadFlags, 732 | ID3D11Resource** texture, 733 | ID3D11ShaderResourceView** textureView) 734 | { 735 | if (texture) 736 | { 737 | *texture = nullptr; 738 | } 739 | if (textureView) 740 | { 741 | *textureView = nullptr; 742 | } 743 | 744 | if (!d3dDevice || !wicData || (!texture && !textureView)) 745 | return E_INVALIDARG; 746 | 747 | if (!wicDataSize) 748 | return E_FAIL; 749 | 750 | if (wicDataSize > UINT32_MAX) 751 | return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); 752 | 753 | auto pWIC = _GetWIC(); 754 | if (!pWIC) 755 | return E_NOINTERFACE; 756 | 757 | // Create input stream for memory 758 | ComPtr stream; 759 | HRESULT hr = pWIC->CreateStream(stream.GetAddressOf()); 760 | if (FAILED(hr)) 761 | return hr; 762 | 763 | hr = stream->InitializeFromMemory(const_cast(wicData), static_cast(wicDataSize)); 764 | if (FAILED(hr)) 765 | return hr; 766 | 767 | // Initialize WIC 768 | ComPtr decoder; 769 | hr = pWIC->CreateDecoderFromStream(stream.Get(), 0, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()); 770 | if (FAILED(hr)) 771 | return hr; 772 | 773 | ComPtr frame; 774 | hr = decoder->GetFrame(0, frame.GetAddressOf()); 775 | if (FAILED(hr)) 776 | return hr; 777 | 778 | hr = CreateTextureFromWIC(d3dDevice, d3dContext, frame.Get(), maxsize, 779 | usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, 780 | texture, textureView); 781 | if (FAILED(hr)) 782 | return hr; 783 | 784 | if (texture != 0 && *texture != 0) 785 | { 786 | SetDebugObjectName(*texture, "WICTextureLoader"); 787 | } 788 | 789 | if (textureView != 0 && *textureView != 0) 790 | { 791 | SetDebugObjectName(*textureView, "WICTextureLoader"); 792 | } 793 | 794 | return hr; 795 | } 796 | 797 | //-------------------------------------------------------------------------------------- 798 | _Use_decl_annotations_ 799 | HRESULT DirectX::CreateWICTextureFromFile(ID3D11Device* d3dDevice, 800 | const wchar_t* fileName, 801 | ID3D11Resource** texture, 802 | ID3D11ShaderResourceView** textureView, 803 | size_t maxsize) 804 | { 805 | return CreateWICTextureFromFileEx(d3dDevice, nullptr, fileName, maxsize, 806 | D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, 807 | texture, textureView); 808 | } 809 | 810 | _Use_decl_annotations_ 811 | HRESULT DirectX::CreateWICTextureFromFile(ID3D11Device* d3dDevice, 812 | ID3D11DeviceContext* d3dContext, 813 | const wchar_t* fileName, 814 | ID3D11Resource** texture, 815 | ID3D11ShaderResourceView** textureView, 816 | size_t maxsize) 817 | { 818 | return CreateWICTextureFromFileEx(d3dDevice, d3dContext, fileName, maxsize, 819 | D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, WIC_LOADER_DEFAULT, 820 | texture, textureView); 821 | } 822 | 823 | _Use_decl_annotations_ 824 | HRESULT DirectX::CreateWICTextureFromFileEx(ID3D11Device* d3dDevice, 825 | const wchar_t* fileName, 826 | size_t maxsize, 827 | D3D11_USAGE usage, 828 | unsigned int bindFlags, 829 | unsigned int cpuAccessFlags, 830 | unsigned int miscFlags, 831 | unsigned int loadFlags, 832 | ID3D11Resource** texture, 833 | ID3D11ShaderResourceView** textureView) 834 | { 835 | return CreateWICTextureFromFileEx(d3dDevice, nullptr, fileName, maxsize, 836 | usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, 837 | texture, textureView); 838 | } 839 | 840 | _Use_decl_annotations_ 841 | HRESULT DirectX::CreateWICTextureFromFileEx(ID3D11Device* d3dDevice, 842 | ID3D11DeviceContext* d3dContext, 843 | const wchar_t* fileName, 844 | size_t maxsize, 845 | D3D11_USAGE usage, 846 | unsigned int bindFlags, 847 | unsigned int cpuAccessFlags, 848 | unsigned int miscFlags, 849 | unsigned int loadFlags, 850 | ID3D11Resource** texture, 851 | ID3D11ShaderResourceView** textureView) 852 | { 853 | if (texture) 854 | { 855 | *texture = nullptr; 856 | } 857 | if (textureView) 858 | { 859 | *textureView = nullptr; 860 | } 861 | 862 | if (!d3dDevice || !fileName || (!texture && !textureView)) 863 | return E_INVALIDARG; 864 | 865 | auto pWIC = _GetWIC(); 866 | if (!pWIC) 867 | return E_NOINTERFACE; 868 | 869 | // Initialize WIC 870 | ComPtr decoder; 871 | HRESULT hr = pWIC->CreateDecoderFromFilename(fileName, 0, GENERIC_READ, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf()); 872 | if (FAILED(hr)) 873 | return hr; 874 | 875 | ComPtr frame; 876 | hr = decoder->GetFrame(0, frame.GetAddressOf()); 877 | if (FAILED(hr)) 878 | return hr; 879 | 880 | hr = CreateTextureFromWIC(d3dDevice, d3dContext, frame.Get(), maxsize, 881 | usage, bindFlags, cpuAccessFlags, miscFlags, loadFlags, 882 | texture, textureView); 883 | 884 | #if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) ) 885 | if (SUCCEEDED(hr)) 886 | { 887 | if (texture != 0 || textureView != 0) 888 | { 889 | char strFileA[MAX_PATH]; 890 | int result = WideCharToMultiByte(CP_ACP, 891 | WC_NO_BEST_FIT_CHARS, 892 | fileName, 893 | -1, 894 | strFileA, 895 | MAX_PATH, 896 | nullptr, 897 | FALSE 898 | ); 899 | if (result > 0) 900 | { 901 | const char* pstrName = strrchr(strFileA, '\\'); 902 | if (!pstrName) 903 | { 904 | pstrName = strFileA; 905 | } 906 | else 907 | { 908 | pstrName++; 909 | } 910 | 911 | if (texture != 0 && *texture != 0) 912 | { 913 | (*texture)->SetPrivateData(WKPDID_D3DDebugObjectName, 914 | static_cast(strnlen_s(pstrName, MAX_PATH)), 915 | pstrName 916 | ); 917 | } 918 | 919 | if (textureView != 0 && *textureView != 0) 920 | { 921 | (*textureView)->SetPrivateData(WKPDID_D3DDebugObjectName, 922 | static_cast(strnlen_s(pstrName, MAX_PATH)), 923 | pstrName 924 | ); 925 | } 926 | } 927 | } 928 | } 929 | #endif 930 | 931 | return hr; 932 | } 933 | --------------------------------------------------------------------------------