diff options
| author | Dave Clark <[email protected]> | 2018-02-28 17:22:22 -0500 |
|---|---|---|
| committer | Dave Clark <[email protected]> | 2018-02-28 17:22:22 -0500 |
| commit | 25528fd230f5f4298c35123a833cdb112675808e (patch) | |
| tree | f5aca3f5ee5a7734df41e7b974a04c37ddff528e /samples/DX_APIUsage/Main.cpp | |
| parent | Push GfeSDK #173 (diff) | |
| download | gfesdk-25528fd230f5f4298c35123a833cdb112675808e.tar.xz gfesdk-25528fd230f5f4298c35123a833cdb112675808e.zip | |
Push SDK # 1.1.186
Documentation updates.
Diffstat (limited to 'samples/DX_APIUsage/Main.cpp')
| -rw-r--r-- | samples/DX_APIUsage/Main.cpp | 861 |
1 files changed, 861 insertions, 0 deletions
diff --git a/samples/DX_APIUsage/Main.cpp b/samples/DX_APIUsage/Main.cpp new file mode 100644 index 0000000..eaed21a --- /dev/null +++ b/samples/DX_APIUsage/Main.cpp @@ -0,0 +1,861 @@ +//-------------------------------------------------------------------------------------- +// File: GfeSDKDemo_APIUsage_DX.cpp +// +// This sample shows a simple example of the Microsoft Direct3D's High-Level +// Shader Language (HLSL) using the Effect interface. +// +// Copyright (c) Microsoft Corporation. All rights reserved. +//-------------------------------------------------------------------------------------- +#include "DXUT.h" +#include "DXUTcamera.h" +#include "DXUTgui.h" +#include "DXUTsettingsDlg.h" +#include "SDKmisc.h" +#include "SDKMesh.h" +#include "resource.h" +#include <vector> +#include <future> +#include <fstream> +#include <codecvt> +#include <locale> + +#include <json/json.h> +#include <Shlwapi.h> + +#ifdef GFESDKDEMO_BUILD_C +#include "GfeSDKHighlights.h" +#else +#include "GfeSDKHighlights.hpp" +using namespace GfeSDK; +#endif + +#include <gfesdk/bindings/cpp/highlights/highlights_types_cpp.h> + +void TRACE(const char* format, ...) +{ + char buffer[1000]; + + va_list argptr; + va_start(argptr, format); + vsprintf(buffer, format, argptr); + va_end(argptr); + + OutputDebugStringA(buffer); +} + +enum class AppState +{ + Init, + LoadResources, + Main +}; + +//-------------------------------------------------------------------------------------- +// Global variables +//-------------------------------------------------------------------------------------- +CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs +CModelViewerCamera g_Camera; // A model viewing camera +CDXUTDirectionWidget g_LightControl; +CD3DSettingsDlg g_D3DSettingsDlg; // Device settings dialog +CDXUTDialog g_HUD; // manages the 3D +CDXUTDialog g_SampleUI; // dialog for sample specific controls +D3DXMATRIXA16 g_mCenterMesh; +float g_fLightScale; +int g_nNumActiveLights; +int g_nActiveLight; +bool g_bShowHelp = false; // If true, it renders the UI control text + +// Direct3D9 resources +CDXUTTextHelper* g_pTxtHelper = NULL; + +CDXUTSDKMesh g_Mesh11; + +ID3D11InputLayout* g_pVertexLayout11 = NULL; +ID3D11Buffer* g_pVertexBuffer = NULL; +ID3D11Buffer* g_pIndexBuffer = NULL; +ID3D11VertexShader* g_pVertexShader = NULL; +ID3D11PixelShader* g_pPixelShader = NULL; +ID3D11SamplerState* g_pSamLinear = NULL; + +struct CB_VS_PER_OBJECT +{ + D3DXMATRIX m_WorldViewProj; + D3DXMATRIX m_World; +}; +UINT g_iCBVSPerObjectBind = 0; + +struct CB_PS_PER_OBJECT +{ + D3DXVECTOR4 m_vObjectColor; +}; +UINT g_iCBPSPerObjectBind = 0; + +struct CB_PS_PER_FRAME +{ + D3DXVECTOR4 m_vLightDirAmbient; +}; +UINT g_iCBPSPerFrameBind = 1; + +ID3D11Buffer* g_pcbVSPerObject = NULL; +ID3D11Buffer* g_pcbPSPerObject = NULL; +ID3D11Buffer* g_pcbPSPerFrame = NULL; + +// Highlights +struct HighlightsDataHolder +{ + std::string id; + bool isScreenshot; + int startDelta; + int endDelta; + std::vector<NVGSDK_LocalizedPair> namePairs; + std::map<std::string, std::string> namePairsData; +}; + +struct HighlightsData +{ + std::string gameName; + std::string defaultLocale; + std::vector<HighlightsDataHolder> highlightsData; + std::vector<NVGSDK_Highlight> highlights; +}; + +HighlightsWrapper g_highlights; +NVGSDK_HighlightSignificance g_sigFilter = NVGSDK_HIGHLIGHT_SIGNIFICANCE_NONE; +NVGSDK_HighlightType g_tagFilter = NVGSDK_HIGHLIGHT_TYPE_NONE; +std::wstring_convert<std::codecvt_utf8<wchar_t>> g_converter; +HighlightsData g_highlightsConfig; +char const* GROUP1_ID = "GROUP1"; +char const* GROUP2_ID = "GROUP2"; + +AppState g_state = AppState::Init; + +//-------------------------------------------------------------------------------------- +// Forward declarations +//-------------------------------------------------------------------------------------- +bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); +void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ); +LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, + void* pUserContext ); +void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); +void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ); + +bool CALLBACK IsD3D11DeviceAcceptable(const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, + DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); +HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, + void* pUserContext ); +HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain, + const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); +void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext ); +void CALLBACK OnD3D11DestroyDevice( void* pUserContext ); +void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, + float fElapsedTime, void* pUserContext ); + +void InitApp(); +void RenderText(); +void RenderLoadingText(); + +//-------------------------------------------------------------------------------------- +// Entry point to the program. Initializes everything and goes into a message processing +// loop. Idle time is used to render the scene. +//-------------------------------------------------------------------------------------- +//int main(void) +int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) +{ + // Enable run-time memory check for debug builds. +#if defined(DEBUG) | defined(_DEBUG) + _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); +#endif + + // DXUT will create and use the best device + // that is available on the system depending on which D3D callbacks are set below + + // Set DXUT callbacks + DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); + DXUTSetCallbackMsgProc( MsgProc ); + DXUTSetCallbackKeyboard( OnKeyboard ); + DXUTSetCallbackFrameMove( OnFrameMove ); + + DXUTSetCallbackD3D11DeviceAcceptable( IsD3D11DeviceAcceptable ); + DXUTSetCallbackD3D11DeviceCreated( OnD3D11CreateDevice ); + DXUTSetCallbackD3D11SwapChainResized( OnD3D11ResizedSwapChain ); + DXUTSetCallbackD3D11FrameRender( OnD3D11FrameRender ); + DXUTSetCallbackD3D11SwapChainReleasing( OnD3D11ReleasingSwapChain ); + DXUTSetCallbackD3D11DeviceDestroyed( OnD3D11DestroyDevice ); + + InitApp(); + DXUTInit( true, true, NULL ); // Parse the command line, show msgboxes on error, no extra command line params + DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen + DXUTCreateWindow( L"GfeSDKDemo_DX" ); + DXUTCreateDevice (D3D_FEATURE_LEVEL_9_2, true, 1280, 1024 ); + DXUTMainLoop(); // Enter into the DXUT render loop + + return DXUTGetExitCode(); +} + +void ToggleSignificanceBit(NVGSDK_HighlightSignificance bit) +{ + g_sigFilter = static_cast<NVGSDK_HighlightSignificance>(g_sigFilter ^ bit); +} + +void ToggleTagBit(NVGSDK_HighlightType bit) +{ + g_tagFilter = static_cast<NVGSDK_HighlightType>(g_tagFilter ^ bit); +} + +//-------------------------------------------------------------------------------------- +// Initialize the app +//-------------------------------------------------------------------------------------- +void InitApp() +{ + TRACE("Initialize Application\n"); + + D3DXVECTOR3 vLightDir(-1, 1, -1); + D3DXVec3Normalize(&vLightDir, &vLightDir); + g_LightControl.SetLightDirection(vLightDir); + + // Initialize dialogs + g_D3DSettingsDlg.Init(&g_DialogResourceManager); + g_HUD.Init(&g_DialogResourceManager); + g_SampleUI.Init(&g_DialogResourceManager); + + g_HUD.SetCallback(OnGUIEvent); + + InitHighlightsWrapper(&g_highlights); + + // Find the path to the executable + char path[MAX_PATH]; + GetModuleFileNameA(NULL, path, MAX_PATH); + PathRemoveFileSpecA(path); + std::string pathStr(path); + + Json::Value jsonHighlightsConfig; + { + Json::Reader reader; + std::ifstream inFile(pathStr + "/highlights_config.json"); + if (!inFile.good()) + { + inFile = std::ifstream(pathStr + "/../highlights_config.json"); + if (!inFile.good()) + { + inFile = std::ifstream(pathStr + "/../../highlights_config.json"); + } + } + if (!reader.parse(inFile, jsonHighlightsConfig)) + { + TRACE("FAILED to read json file\n"); + } + } + + // Store the json data in the highlights data structure + g_highlightsConfig.gameName = jsonHighlightsConfig["gameName"].asString(); + g_highlightsConfig.defaultLocale = jsonHighlightsConfig["defaultLocale"].asString(); + g_highlightsConfig.highlightsData.resize(jsonHighlightsConfig["highlights"].size()); + g_highlightsConfig.highlights.resize(jsonHighlightsConfig["highlights"].size()); + + for (int i = 0; i < jsonHighlightsConfig["highlights"].size(); ++i) + { + Json::Value const& def = jsonHighlightsConfig["highlights"][i]; + g_highlightsConfig.highlightsData[i].id = def["id"].asString(); + g_highlightsConfig.highlightsData[i].isScreenshot = !def.isMember("startDelta"); + g_highlightsConfig.highlightsData[i].startDelta = g_highlightsConfig.highlightsData[i].isScreenshot ? 0 : def["startDelta"].asInt(); + g_highlightsConfig.highlightsData[i].endDelta = g_highlightsConfig.highlightsData[i].isScreenshot ? 0 : def["endDelta"].asInt(); + for (auto it = def["name"].begin(); it != def["name"].end(); ++it) + { + g_highlightsConfig.highlightsData[i].namePairsData[it.key().asString()] = it->asString(); + } + for (auto it = g_highlightsConfig.highlightsData[i].namePairsData.begin(); it != g_highlightsConfig.highlightsData[i].namePairsData.end(); ++it) + { + g_highlightsConfig.highlightsData[i].namePairs.push_back({&it->first[0],&it->second[0]}); + } + + g_highlightsConfig.highlights[i].id = g_highlightsConfig.highlightsData[i].id.c_str(); + g_highlightsConfig.highlights[i].userInterest = def["userInterest"].asBool(); + g_highlightsConfig.highlights[i].significance = static_cast<NVGSDK_HighlightSignificance>(def["significance"].asInt()); + g_highlightsConfig.highlights[i].highlightTags = static_cast<NVGSDK_HighlightType>(def["highlightTags"].asInt()); + g_highlightsConfig.highlights[i].nameTable = g_highlightsConfig.highlightsData[i].namePairs.empty() ? nullptr : &g_highlightsConfig.highlightsData[i].namePairs[0]; + g_highlightsConfig.highlights[i].nameTableSize = g_highlightsConfig.highlightsData[i].namePairs.size(); + } + + int iY = 10; + int const PAD = 26; + g_HUD.AddButtonCallback([]() {DXUTToggleFullScreen(); }, L"Toggle full screen", 0, iY, 170, 23); + g_HUD.AddButtonCallback([]() {g_highlights.OnRequestLanguage(); }, L"Get Overlay Language", 0, iY += PAD, 170, 23); + g_HUD.AddButtonCallback([]() {g_highlights.OnRequestUserSettings(); }, L"Get User Settings", 0, iY += PAD, 170, 23); + + iY += 10; + + int iY_groups = iY; + int const GROUP1_X = -250; + int const GROUP2_X = -30; + + g_HUD.AddButtonCallback([]() {g_highlights.OnOpenGroup(GROUP1_ID); }, L"Open Group 1", GROUP1_X, iY += PAD, 200, 23); + for (size_t i = 0; i < g_highlightsConfig.highlightsData.size(); ++i) + { + HighlightsDataHolder const& holder = g_highlightsConfig.highlightsData[i]; + if (!holder.isScreenshot) + { + std::wstring text = std::wstring(L"VIDEO: ") + g_converter.from_bytes(holder.id); + g_HUD.AddButtonCallback([holder]() { g_highlights.OnSaveVideo(holder.id.c_str(), GROUP1_ID, holder.startDelta, holder.endDelta); }, + text.c_str(), GROUP1_X, iY += PAD, 200, 23); + } + else + { + std::wstring text = std::wstring(L"SCREENSHOT: ") + g_converter.from_bytes(holder.id); + g_HUD.AddButtonCallback([holder]() { g_highlights.OnSaveScreenshot(holder.id.c_str(), GROUP1_ID); }, text.c_str(), GROUP1_X, iY += PAD, 200, 23); + } + } + g_HUD.AddButtonCallback([]() {g_highlights.OnOpenSummary(&std::vector<char const*>({ GROUP1_ID })[0], 1, g_sigFilter, g_tagFilter); }, L"Open Group1 Summary", GROUP1_X, iY += PAD, 200, 23); + g_HUD.AddButtonCallback([]() {g_highlights.OnGetNumHighlights(GROUP1_ID , g_sigFilter, g_tagFilter); }, L"GetNumHighlights in Group1", GROUP1_X, iY += PAD, 200, 23); + g_HUD.AddButtonCallback([]() {g_highlights.OnCloseGroup(GROUP1_ID, false); }, L"Close Group 1", GROUP1_X, iY += PAD, 200, 23); + g_HUD.AddButtonCallback([]() {g_highlights.OnCloseGroup(GROUP1_ID, true); }, L"Destroy Group 1", GROUP1_X, iY += PAD, 200, 23); + + iY = iY_groups; + g_HUD.AddButtonCallback([]() {g_highlights.OnOpenGroup(GROUP2_ID); }, L"Open Group 2", GROUP2_X, iY += PAD, 200, 23); + for (size_t i = 0; i < g_highlightsConfig.highlightsData.size(); ++i) + { + HighlightsDataHolder const& holder = g_highlightsConfig.highlightsData[i]; + if (!holder.isScreenshot) + { + std::wstring text = std::wstring(L"VIDEO: ") + g_converter.from_bytes(holder.id); + g_HUD.AddButtonCallback([holder]() { g_highlights.OnSaveVideo(holder.id.c_str(), GROUP2_ID, holder.startDelta, holder.endDelta); }, + text.c_str(), GROUP2_X, iY += PAD, 200, 23); + } + else + { + std::wstring text = std::wstring(L"SCREENSHOT: ") + g_converter.from_bytes(holder.id); + g_HUD.AddButtonCallback([holder]() { g_highlights.OnSaveScreenshot(holder.id.c_str(), GROUP2_ID); }, text.c_str(), GROUP2_X, iY += PAD, 200, 23); + } + } + g_HUD.AddButtonCallback([]() {g_highlights.OnOpenSummary(&std::vector<char const*>({ GROUP2_ID })[0], 1, g_sigFilter, g_tagFilter); }, L"Open Group2 Summary", GROUP2_X, iY += PAD, 200, 23); + g_HUD.AddButtonCallback([]() {g_highlights.OnGetNumHighlights(GROUP2_ID, g_sigFilter, g_tagFilter); }, L"GetNumHighlights in Group2", GROUP2_X, iY += PAD, 200, 23); + g_HUD.AddButtonCallback([]() {g_highlights.OnCloseGroup(GROUP2_ID, false); }, L"Close Group 2", GROUP2_X, iY += PAD, 200, 23); + g_HUD.AddButtonCallback([]() {g_highlights.OnCloseGroup(GROUP2_ID, true); }, L"Destroy Group 2", GROUP2_X, iY += PAD, 200, 23); + + iY += 10; + g_HUD.AddButtonCallback([]() {g_highlights.OnOpenSummary(&std::vector<char const*>({ GROUP1_ID, GROUP2_ID })[0], 2, g_sigFilter, g_tagFilter); }, L"Open GroupSummary 1 + 2", -30, iY += PAD, 200, 23); + + iY += 20; + g_HUD.AddButtonCallback([]() {g_sigFilter = NVGSDK_HIGHLIGHT_SIGNIFICANCE_NONE; }, L"Clear Significance Filter", -30, iY += PAD, 200, 23); + g_HUD.AddButtonCallback(std::bind(ToggleSignificanceBit, NVGSDK_HIGHLIGHT_SIGNIFICANCE_EXTREMELY_BAD), L"Toggle ExtremelyBad", -30, iY += PAD, 200, 23); + g_HUD.AddButtonCallback(std::bind(ToggleSignificanceBit, NVGSDK_HIGHLIGHT_SIGNIFICANCE_VERY_BAD), L"Toggle VeryBad", -30, iY += PAD, 200, 23); + g_HUD.AddButtonCallback(std::bind(ToggleSignificanceBit, NVGSDK_HIGHLIGHT_SIGNIFICANCE_BAD), L"Toggle Bad", -30, iY += PAD, 200, 23); + g_HUD.AddButtonCallback(std::bind(ToggleSignificanceBit, NVGSDK_HIGHLIGHT_SIGNIFICANCE_NEUTRAL), L"Toggle Neutral", -30, iY += PAD, 200, 23); + g_HUD.AddButtonCallback(std::bind(ToggleSignificanceBit, NVGSDK_HIGHLIGHT_SIGNIFICANCE_GOOD), L"Toggle Good", -30, iY += PAD, 200, 23); + g_HUD.AddButtonCallback(std::bind(ToggleSignificanceBit, NVGSDK_HIGHLIGHT_SIGNIFICANCE_VERY_GOOD), L"Toggle VeryGood", -30, iY += PAD, 200, 23); + g_HUD.AddButtonCallback(std::bind(ToggleSignificanceBit, NVGSDK_HIGHLIGHT_SIGNIFICANCE_EXTREMELY_GOOD), L"Toggle ExtremelyGood", -30, iY += PAD, 200, 23); + + iY += 10; + g_HUD.AddButtonCallback([]() {g_tagFilter = NVGSDK_HIGHLIGHT_TYPE_NONE; }, L"Clear Tag Filter", -30, iY += PAD, 200, 23); + g_HUD.AddButtonCallback(std::bind(ToggleTagBit, NVGSDK_HIGHLIGHT_TYPE_MILESTONE), L"Toggle Milestone", -30, iY += PAD, 200, 23); + g_HUD.AddButtonCallback(std::bind(ToggleTagBit, NVGSDK_HIGHLIGHT_TYPE_ACHIEVEMENT), L"Toggle Achievement", -30, iY += PAD, 200, 23); + g_HUD.AddButtonCallback(std::bind(ToggleTagBit, NVGSDK_HIGHLIGHT_TYPE_INCIDENT), L"Toggle Incident", -30, iY += PAD, 200, 23); + g_HUD.AddButtonCallback(std::bind(ToggleTagBit, NVGSDK_HIGHLIGHT_TYPE_STATE_CHANGE), L"Toggle StateChange", -30, iY += PAD, 200, 23); + g_HUD.AddButtonCallback(std::bind(ToggleTagBit, NVGSDK_HIGHLIGHT_TYPE_UNANNOUNCED), L"Toggle Unannounced", -30, iY += PAD, 200, 23); + + g_SampleUI.SetCallback( OnGUIEvent ); iY = 10; +} + + +//-------------------------------------------------------------------------------------- +// Called right before creating a D3D9 or D3D11 device, allowing the app to modify the device settings as needed +//-------------------------------------------------------------------------------------- +bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) +{ + // Uncomment this to get debug information from D3D11 + //pDeviceSettings->d3d11.CreateFlags |= D3D11_CREATE_DEVICE_DEBUG; + + // For the first device created if its a REF device, optionally display a warning dialog box + static bool s_bFirstTime = true; + if( s_bFirstTime ) + { + s_bFirstTime = false; + if( ( DXUT_D3D11_DEVICE == pDeviceSettings->ver && + pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) ) + { + DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver ); + } + } + + return true; +} + + +//-------------------------------------------------------------------------------------- +// Handle updates to the scene. This is called regardless of which D3D API is used +//-------------------------------------------------------------------------------------- +void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) +{ + // Update the camera's position based on user input + g_Camera.FrameMove( fElapsedTime ); + +} + + +//-------------------------------------------------------------------------------------- +// Render the help and statistics text +//-------------------------------------------------------------------------------------- +void RenderText() +{ + UINT nBackBufferHeight = ( DXUTIsAppRenderingWithD3D9() ) ? DXUTGetD3D9BackBufferSurfaceDesc()->Height : + DXUTGetDXGIBackBufferSurfaceDesc()->Height; + + g_pTxtHelper->Begin(); + g_pTxtHelper->SetInsertionPos( 2, 50 ); + g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) ); + g_pTxtHelper->DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) ); + g_pTxtHelper->DrawTextLine( DXUTGetDeviceStats() ); + + // Draw help + if( g_bShowHelp ) + { + g_pTxtHelper->SetInsertionPos( 2, nBackBufferHeight - 20 * 6 ); + g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 0.75f, 0.0f, 1.0f ) ); + g_pTxtHelper->DrawTextLine( L"Controls:" ); + + g_pTxtHelper->SetInsertionPos( 20, nBackBufferHeight - 20 * 5 ); + g_pTxtHelper->DrawTextLine( L"Rotate model: Left mouse button\n" + L"Rotate light: Right mouse button\n" + L"Rotate camera: Middle mouse button\n" + L"Zoom camera: Mouse wheel scroll\n" ); + + g_pTxtHelper->SetInsertionPos( 550, nBackBufferHeight - 20 * 5 ); + g_pTxtHelper->DrawTextLine( L"Hide help: F1\n" + L"Quit: ESC\n" ); + } + else + { + g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) ); + g_pTxtHelper->DrawTextLine( L"Press F1 for help" ); + } + + // Highlights + g_pTxtHelper->SetForegroundColor(D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f)); + g_pTxtHelper->SetInsertionPos(2, 5); + g_pTxtHelper->DrawFormattedTextLine(L"Highlights Permission: %s", g_highlights.GetCurrentPermissionStr()); + g_pTxtHelper->DrawFormattedTextLine(L"Last Overlay Event: %s", g_highlights.GetLastOverlayEvent()); + g_pTxtHelper->DrawFormattedTextLine(L"Last Result: %s", g_highlights.GetLastResult()); + + g_pTxtHelper->SetInsertionPos(500, 5); + g_pTxtHelper->DrawFormattedTextLine(L"Last Query: %s", g_highlights.GetLastQueryResult()); + + g_pTxtHelper->SetInsertionPos(700, 5); + g_pTxtHelper->DrawFormattedTextLine(L"Significance Filter: 0x%08x", g_sigFilter); + g_pTxtHelper->DrawFormattedTextLine(L"Tag Filter: 0x%08x", g_tagFilter); + + g_pTxtHelper->End(); +} + +//-------------------------------------------------------------------------------------- +// Render the loading text +//-------------------------------------------------------------------------------------- +void RenderLoadingText() +{ + UINT nBackBufferHeight = (DXUTIsAppRenderingWithD3D9()) ? DXUTGetD3D9BackBufferSurfaceDesc()->Height : + DXUTGetDXGIBackBufferSurfaceDesc()->Height; + + g_pTxtHelper->Begin(); + + g_pTxtHelper->SetInsertionPos(nBackBufferHeight / 2, 300); + g_pTxtHelper->SetForegroundColor(D3DXCOLOR(1.0f, 1.0f, 0.0f, 1.0f)); + g_pTxtHelper->DrawTextLine(L"LOADING..."); + + g_pTxtHelper->End(); +} + +//-------------------------------------------------------------------------------------- +// Handle messages to the application +//-------------------------------------------------------------------------------------- +LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, + void* pUserContext ) +{ + // Pass messages to dialog resource manager calls so GUI state is updated correctly + *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam ); + if( *pbNoFurtherProcessing ) + return 0; + + // Pass messages to settings dialog if its active + if( g_D3DSettingsDlg.IsActive() ) + { + g_D3DSettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam ); + return 0; + } + + // Give the dialogs a chance to handle the message first + *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam ); + if( *pbNoFurtherProcessing ) + return 0; + *pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam ); + if( *pbNoFurtherProcessing ) + return 0; + + g_LightControl.HandleMessages( hWnd, uMsg, wParam, lParam ); + + // Pass all remaining windows messages to camera so it can respond to user input + g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam ); + + return 0; +} + + +//-------------------------------------------------------------------------------------- +// Handle key presses +//-------------------------------------------------------------------------------------- +void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) +{ + if( bKeyDown ) + { + switch( nChar ) + { + case VK_F1: + g_bShowHelp = !g_bShowHelp; break; + } + } +} + + +//-------------------------------------------------------------------------------------- +// Handles the GUI events +//-------------------------------------------------------------------------------------- +void CALLBACK OnGUIEvent(UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext) +{ + void* pUserData = pControl->GetUserData(); + if (pUserData) + { + std::function<void()>* fn = reinterpret_cast<std::function<void()>*>(pUserData); + (*fn)(); + } +} + + +//-------------------------------------------------------------------------------------- +// Reject any D3D11 devices that aren't acceptable by returning false +//-------------------------------------------------------------------------------------- +bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, + DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) +{ + return true; +} + +//-------------------------------------------------------------------------------------- +// Find and compile the specified shader +//-------------------------------------------------------------------------------------- +HRESULT CompileShaderFromFile( WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut ) +{ + HRESULT hr = S_OK; + + // find the file + WCHAR str[MAX_PATH]; + V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, szFileName ) ); + + DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; +#if defined( DEBUG ) || defined( _DEBUG ) + // Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders. + // Setting this flag improves the shader debugging experience, but still allows + // the shaders to be optimized and to run exactly the way they will run in + // the release configuration of this program. + dwShaderFlags |= D3DCOMPILE_DEBUG; +#endif + + ID3DBlob* pErrorBlob; + hr = D3DX11CompileFromFile( str, NULL, NULL, szEntryPoint, szShaderModel, + dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL ); + if( FAILED(hr) ) + { + if( pErrorBlob != NULL ) + OutputDebugStringA( (char*)pErrorBlob->GetBufferPointer() ); + SAFE_RELEASE( pErrorBlob ); + return hr; + } + SAFE_RELEASE( pErrorBlob ); + + return S_OK; +} + + +//-------------------------------------------------------------------------------------- +// Create any D3D11 resources that aren't dependant on the back buffer +//-------------------------------------------------------------------------------------- +HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, + void* pUserContext ) +{ + HRESULT hr; + + ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext(); + V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) ); + V_RETURN( g_D3DSettingsDlg.OnD3D11CreateDevice( pd3dDevice ) ); + g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 ); + + D3DXVECTOR3 vCenter( 0.25767413f, -28.503521f, 111.00689f ); + FLOAT fObjectRadius = 378.15607f; + + D3DXMatrixTranslation( &g_mCenterMesh, -vCenter.x, -vCenter.y, -vCenter.z ); + D3DXMATRIXA16 m; + D3DXMatrixRotationY( &m, D3DX_PI ); + g_mCenterMesh *= m; + D3DXMatrixRotationX( &m, D3DX_PI / 2.0f ); + g_mCenterMesh *= m; + + // Compile the shaders using the lowest possible profile for broadest feature level support + ID3DBlob* pVertexShaderBuffer = NULL; + V_RETURN( CompileShaderFromFile( L"BasicHLSL11_VS.hlsl", "VSMain", "vs_4_0_level_9_1", &pVertexShaderBuffer ) ); + + ID3DBlob* pPixelShaderBuffer = NULL; + V_RETURN( CompileShaderFromFile( L"BasicHLSL11_PS.hlsl", "PSMain", "ps_4_0_level_9_1", &pPixelShaderBuffer ) ); + + // Create the shaders + V_RETURN( pd3dDevice->CreateVertexShader( pVertexShaderBuffer->GetBufferPointer(), + pVertexShaderBuffer->GetBufferSize(), NULL, &g_pVertexShader ) ); + DXUT_SetDebugName( g_pVertexShader, "VSMain" ); + V_RETURN( pd3dDevice->CreatePixelShader( pPixelShaderBuffer->GetBufferPointer(), + pPixelShaderBuffer->GetBufferSize(), NULL, &g_pPixelShader ) ); + DXUT_SetDebugName( g_pPixelShader, "PSMain" ); + + // Create our vertex input layout + const D3D11_INPUT_ELEMENT_DESC layout[] = + { + { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }, + }; + + V_RETURN( pd3dDevice->CreateInputLayout( layout, ARRAYSIZE( layout ), pVertexShaderBuffer->GetBufferPointer(), + pVertexShaderBuffer->GetBufferSize(), &g_pVertexLayout11 ) ); + DXUT_SetDebugName( g_pVertexLayout11, "Primary" ); + + SAFE_RELEASE( pVertexShaderBuffer ); + SAFE_RELEASE( pPixelShaderBuffer ); + + // Load the mesh + V_RETURN( g_Mesh11.Create( pd3dDevice, L"tiny\\tiny.sdkmesh", true ) ); + + // Create a sampler state + D3D11_SAMPLER_DESC SamDesc; + SamDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; + SamDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; + SamDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; + SamDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; + SamDesc.MipLODBias = 0.0f; + SamDesc.MaxAnisotropy = 1; + SamDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; + SamDesc.BorderColor[0] = SamDesc.BorderColor[1] = SamDesc.BorderColor[2] = SamDesc.BorderColor[3] = 0; + SamDesc.MinLOD = 0; + SamDesc.MaxLOD = D3D11_FLOAT32_MAX; + V_RETURN( pd3dDevice->CreateSamplerState( &SamDesc, &g_pSamLinear ) ); + DXUT_SetDebugName( g_pSamLinear, "Primary" ); + + // Setup constant buffers + D3D11_BUFFER_DESC Desc; + Desc.Usage = D3D11_USAGE_DYNAMIC; + Desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + Desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + Desc.MiscFlags = 0; + + Desc.ByteWidth = sizeof( CB_VS_PER_OBJECT ); + V_RETURN( pd3dDevice->CreateBuffer( &Desc, NULL, &g_pcbVSPerObject ) ); + DXUT_SetDebugName( g_pcbVSPerObject, "CB_VS_PER_OBJECT" ); + + Desc.ByteWidth = sizeof( CB_PS_PER_OBJECT ); + V_RETURN( pd3dDevice->CreateBuffer( &Desc, NULL, &g_pcbPSPerObject ) ); + DXUT_SetDebugName( g_pcbPSPerObject, "CB_PS_PER_OBJECT" ); + + Desc.ByteWidth = sizeof( CB_PS_PER_FRAME ); + V_RETURN( pd3dDevice->CreateBuffer( &Desc, NULL, &g_pcbPSPerFrame ) ); + DXUT_SetDebugName( g_pcbPSPerFrame, "CB_PS_PER_FRAME" ); + + // Setup the camera's view parameters + D3DXVECTOR3 vecEye( 0.0f, 0.0f, -100.0f ); + D3DXVECTOR3 vecAt ( 0.0f, 0.0f, -0.0f ); + g_Camera.SetViewParams( &vecEye, &vecAt ); + g_Camera.SetRadius( fObjectRadius * 3.0f, fObjectRadius * 0.5f, fObjectRadius * 10.0f ); + + return S_OK; +} + + +//-------------------------------------------------------------------------------------- +// Create any D3D11 resources that depend on the back buffer +//-------------------------------------------------------------------------------------- +HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain, + const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) +{ + HRESULT hr; + + V_RETURN( g_DialogResourceManager.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) ); + V_RETURN( g_D3DSettingsDlg.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) ); + + // Setup the camera's projection parameters + float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height; + g_Camera.SetProjParams( D3DX_PI / 4, fAspectRatio, 2.0f, 4000.0f ); + g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height ); + g_Camera.SetButtonMasks( MOUSE_MIDDLE_BUTTON, MOUSE_WHEEL, MOUSE_LEFT_BUTTON ); + + g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 ); + g_HUD.SetSize( 170, 170 ); + g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300 ); + g_SampleUI.SetSize( 170, 300 ); + + return S_OK; +} + + +//-------------------------------------------------------------------------------------- +// Render the scene using the D3D11 device +//-------------------------------------------------------------------------------------- +void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, + float fElapsedTime, void* pUserContext ) +{ + HRESULT hr; + + g_highlights.OnTick(); + + switch (g_state) + { + case AppState::Init: + g_state = AppState::LoadResources; + return; + case AppState::LoadResources: + RenderLoadingText(); + //g_highlights.Init(g_highlightsConfig); + g_highlights.Init(g_highlightsConfig.gameName.c_str(), g_highlightsConfig.defaultLocale.c_str(), &g_highlightsConfig.highlights[0], g_highlightsConfig.highlights.size()); + g_state = AppState::Main; + return; + case AppState::Main: + { + // Clear the render target and depth stencil + float ClearColor[4] = { 0.0f, 0.25f, 0.25f, 0.55f }; + ID3D11RenderTargetView* pRTV = DXUTGetD3D11RenderTargetView(); + pd3dImmediateContext->ClearRenderTargetView(pRTV, ClearColor); + ID3D11DepthStencilView* pDSV = DXUTGetD3D11DepthStencilView(); + pd3dImmediateContext->ClearDepthStencilView(pDSV, D3D11_CLEAR_DEPTH, 1.0, 0); + + D3DXMATRIX mWorldViewProjection; + D3DXVECTOR3 vLightDir; + D3DXMATRIX mWorld; + D3DXMATRIX mView; + D3DXMATRIX mProj; + + // Get the projection & view matrix from the camera class + mProj = *g_Camera.GetProjMatrix(); + mView = *g_Camera.GetViewMatrix(); + + // Get the light direction + vLightDir = g_LightControl.GetLightDirection(); + + // Per frame cb update + D3D11_MAPPED_SUBRESOURCE MappedResource; + V(pd3dImmediateContext->Map(g_pcbPSPerFrame, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource)); + CB_PS_PER_FRAME* pPerFrame = (CB_PS_PER_FRAME*)MappedResource.pData; + float fAmbient = 0.1f; + pPerFrame->m_vLightDirAmbient = D3DXVECTOR4(vLightDir.x, vLightDir.y, vLightDir.z, fAmbient); + pd3dImmediateContext->Unmap(g_pcbPSPerFrame, 0); + + pd3dImmediateContext->PSSetConstantBuffers(g_iCBPSPerFrameBind, 1, &g_pcbPSPerFrame); + + //Get the mesh + //IA setup + pd3dImmediateContext->IASetInputLayout(g_pVertexLayout11); + UINT Strides[1]; + UINT Offsets[1]; + ID3D11Buffer* pVB[1]; + pVB[0] = g_Mesh11.GetVB11(0, 0); + Strides[0] = (UINT)g_Mesh11.GetVertexStride(0, 0); + Offsets[0] = 0; + pd3dImmediateContext->IASetVertexBuffers(0, 1, pVB, Strides, Offsets); + pd3dImmediateContext->IASetIndexBuffer(g_Mesh11.GetIB11(0), g_Mesh11.GetIBFormat11(0), 0); + + // Set the shaders + pd3dImmediateContext->VSSetShader(g_pVertexShader, NULL, 0); + pd3dImmediateContext->PSSetShader(g_pPixelShader, NULL, 0); + + // Set the per object constant data + mWorld = g_mCenterMesh * *g_Camera.GetWorldMatrix(); + mProj = *g_Camera.GetProjMatrix(); + mView = *g_Camera.GetViewMatrix(); + + mWorldViewProjection = mWorld * mView * mProj; + + // VS Per object + V(pd3dImmediateContext->Map(g_pcbVSPerObject, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource)); + CB_VS_PER_OBJECT* pVSPerObject = (CB_VS_PER_OBJECT*)MappedResource.pData; + D3DXMatrixTranspose(&pVSPerObject->m_WorldViewProj, &mWorldViewProjection); + D3DXMatrixTranspose(&pVSPerObject->m_World, &mWorld); + pd3dImmediateContext->Unmap(g_pcbVSPerObject, 0); + + pd3dImmediateContext->VSSetConstantBuffers(g_iCBVSPerObjectBind, 1, &g_pcbVSPerObject); + + // PS Per object + V(pd3dImmediateContext->Map(g_pcbPSPerObject, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource)); + CB_PS_PER_OBJECT* pPSPerObject = (CB_PS_PER_OBJECT*)MappedResource.pData; + pPSPerObject->m_vObjectColor = D3DXVECTOR4(1, 1, 1, 1); + pd3dImmediateContext->Unmap(g_pcbPSPerObject, 0); + + pd3dImmediateContext->PSSetConstantBuffers(g_iCBPSPerObjectBind, 1, &g_pcbPSPerObject); + + //Render + SDKMESH_SUBSET* pSubset = NULL; + D3D11_PRIMITIVE_TOPOLOGY PrimType; + + pd3dImmediateContext->PSSetSamplers(0, 1, &g_pSamLinear); + + for (UINT subset = 0; subset < g_Mesh11.GetNumSubsets(0); ++subset) + { + // Get the subset + pSubset = g_Mesh11.GetSubset(0, subset); + + PrimType = CDXUTSDKMesh::GetPrimitiveType11((SDKMESH_PRIMITIVE_TYPE)pSubset->PrimitiveType); + pd3dImmediateContext->IASetPrimitiveTopology(PrimType); + + // TODO: D3D11 - material loading + ID3D11ShaderResourceView* pDiffuseRV = g_Mesh11.GetMaterial(pSubset->MaterialID)->pDiffuseRV11; + pd3dImmediateContext->PSSetShaderResources(0, 1, &pDiffuseRV); + + pd3dImmediateContext->DrawIndexed((UINT)pSubset->IndexCount, 0, (UINT)pSubset->VertexStart); + } + + DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, L"HUD / Stats"); + g_HUD.OnRender(fElapsedTime); + g_SampleUI.OnRender(fElapsedTime); + RenderText(); + DXUT_EndPerfEvent(); + return; + } + } +} + + +//-------------------------------------------------------------------------------------- +// Release D3D11 resources created in OnD3D11ResizedSwapChain +//-------------------------------------------------------------------------------------- +void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext ) +{ + g_DialogResourceManager.OnD3D11ReleasingSwapChain(); +} + + +//-------------------------------------------------------------------------------------- +// Release D3D11 resources created in OnD3D11CreateDevice +//-------------------------------------------------------------------------------------- +void CALLBACK OnD3D11DestroyDevice( void* pUserContext ) +{ + g_DialogResourceManager.OnD3D11DestroyDevice(); + g_D3DSettingsDlg.OnD3D11DestroyDevice(); + //CDXUTDirectionWidget::StaticOnD3D11DestroyDevice(); + DXUTGetGlobalResourceCache().OnDestroyDevice(); + SAFE_DELETE( g_pTxtHelper ); + + g_Mesh11.Destroy(); + + SAFE_RELEASE( g_pVertexLayout11 ); + SAFE_RELEASE( g_pVertexBuffer ); + SAFE_RELEASE( g_pIndexBuffer ); + SAFE_RELEASE( g_pVertexShader ); + SAFE_RELEASE( g_pPixelShader ); + SAFE_RELEASE( g_pSamLinear ); + + SAFE_RELEASE( g_pcbVSPerObject ); + SAFE_RELEASE( g_pcbPSPerObject ); + SAFE_RELEASE( g_pcbPSPerFrame ); +} + + + |